返回 CodeWhale
route_receipt.rs
根目录 / crates / engine / src / route_receipt.rs
1 //! Secret-free lifecycle receipts for the exact route a turn was launched on.
2 //!
3 //! A [`TurnRouteReceipt`] is minted from the **installed, preflighted** client —
4 //! the one that was actually constructed to serve the turn — and travels with
5 //! the turn's lifecycle event. Consumers that need to prove "this later request
6 //! goes to the same base route, with the same credential, as the turn it
7 //! descends from" compare receipts instead of re-reading mutable config.
8 //!
9 //! Everything in a receipt is safe to carry through events, state, and `Debug`:
10 //!
11 //! - the provider enum and the non-secret configured route key,
12 //! - the canonical wire model id,
13 //! - a **normalized, redacted** endpoint identity (URL userinfo and sensitive
14 //! query values masked by [`codewhale_sanitize::sanitize::redact_url_for_display`]),
15 //! - a one-way credential *generation* digest that is never rendered.
16 //!
17 //! The credential generation is deliberately taken over the endpoint **and** the
18 //! credential together. Redaction is lossy on purpose — `https://a:b@host/v1`
19 //! and `https://c:d@host/v1` share one endpoint identity — so folding the raw
20 //! endpoint into the digest is what keeps a userinfo swap detectable.
21
22 use std::fmt;
23
24 use codewhale_config::ProviderKind;
25 use codewhale_config::credentials::CredentialGeneration;
26 use codewhale_runtime::config::ProviderIdentity;
27
28 /// Endpoint identity for a string that is not a parseable URL.
29 ///
30 /// Deliberately opaque: an unparseable endpoint could be a filesystem path, and
31 /// absolute paths must never reach an event, log, or `Debug` rendering. Two
32 /// different unparseable endpoints therefore collide here — the credential
33 /// generation digest below is what still tells them apart.
34 const OPAQUE_ENDPOINT: &str = "<opaque-endpoint>";
35
36 #[derive(Debug, Clone, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
37 pub struct ExecRouteBinding {
38 #[serde(default, skip_serializing_if = "Option::is_none")]
39 pub go_dispatch: Option<String>,
40 pub endpoint: Option<String>,
41 pub authority: Option<String>,
42 }
43
44 impl ExecRouteBinding {
45 pub fn endpoint_tag(key: &[u8; 32], base_url: &str) -> String {
46 Self::tag(key, b"endpoint", &[base_url.trim().trim_end_matches('/')])
47 }
48
49 pub(crate) fn tag(key: &[u8; 32], domain: &[u8], values: &[&str]) -> String {
50 use ring::hmac;
51 let key = hmac::Key::new(hmac::HMAC_SHA256, key);
52 let mut digest = hmac::Context::with_key(&key);
53 digest.update(b"codewhale/exec-resume-route/v1\0");
54 digest.update(domain);
55 digest.update(b"\0");
56 for value in values {
57 digest.update(&(value.len() as u64).to_le_bytes());
58 digest.update(value.as_bytes());
59 }
60 digest
61 .sign()
62 .as_ref()
63 .iter()
64 .map(|byte| format!("{byte:02x}"))
65 .collect()
66 }
67
68 pub fn matches(&self, current: &Self) -> bool {
69 self.endpoint.is_some() && self.authority.is_some() && self == current
70 }
71 }
72
73 /// Normalized, redacted, comparable identity for an API endpoint.
74 ///
75 /// Safe to print. Trailing slashes are folded so `…/v1` and `…/v1/` are one
76 /// endpoint; nothing else is folded, so a host, scheme, port, or path change is
77 /// always a different identity.
78 #[must_use]
79 pub fn endpoint_identity(base_url: &str) -> String {
80 let trimmed = base_url.trim();
81 if trimmed.is_empty() {
82 return String::new();
83 }
84 if reqwest::Url::parse(trimmed).is_err() {
85 return OPAQUE_ENDPOINT.to_string();
86 }
87 codewhale_sanitize::sanitize::redact_url_for_display(trimmed)
88 .trim_end_matches('/')
89 .to_string()
90 }
91
92 /// Immutable proof of the exact base route a turn's client was installed on.
93 #[derive(Clone, PartialEq, Eq)]
94 pub struct TurnRouteReceipt {
95 identity: ProviderIdentity,
96 wire_model: String,
97 endpoint_identity: String,
98 credential_generation: CredentialGeneration,
99 openrouter_vendor: Option<String>,
100 }
101
102 impl TurnRouteReceipt {
103 /// Mint a receipt from the values the installed client is bound to.
104 ///
105 /// `base_url` and `credential` are consumed here and never stored: only the
106 /// redacted endpoint identity and the one-way generation digest survive.
107 #[must_use]
108 pub fn from_admitted(
109 identity: &ProviderIdentity,
110 wire_model: &str,
111 base_url: &str,
112 credential: &str,
113 ) -> Self {
114 Self {
115 identity: identity.clone(),
116 wire_model: wire_model.trim().to_string(),
117 endpoint_identity: endpoint_identity(base_url),
118 credential_generation: CredentialGeneration::derive(base_url, credential),
119 openrouter_vendor: None,
120 }
121 }
122
123 /// Test facts do not read a runtime config; production mints from admission.
124 #[cfg(any(test, feature = "test-support"))]
125 pub fn new(
126 provider: ProviderKind,
127 provider_identity: &str,
128 wire_model: &str,
129 base_url: &str,
130 credential: &str,
131 ) -> Self {
132 let identity = ProviderIdentity::test_exact_identity(provider, provider_identity);
133 Self::from_admitted(&identity, wire_model, base_url, credential)
134 }
135
136 /// Non-executing fixture projection for cache scope tests. It uses the
137 /// canonical Config admission and only an already provable read-only
138 /// credential generation. An opaque source gets distinct synthetic facts;
139 /// the production lookup still refuses to reuse that evidence.
140 #[cfg(any(test, feature = "test-support"))]
141 pub fn for_test_fixture(
142 config: &codewhale_runtime::config::Config,
143 kind: ProviderKind,
144 model: &str,
145 ) -> Self {
146 let identity = config.test_identity_for_kind(kind);
147 let base_url = config.base_url_for_route(&identity);
148 let generation = config
149 .readonly_health_credential_generation(&identity)
150 .unwrap_or_else(|| {
151 CredentialGeneration::derive(&base_url, "opaque-test-only-generation")
152 });
153 Self {
154 identity,
155 wire_model: model.to_string(),
156 endpoint_identity: endpoint_identity(&base_url),
157 credential_generation: generation,
158 openrouter_vendor: None,
159 }
160 }
161
162 /// Keep upstream vendor restrictions frozen with the installed route.
163 #[must_use]
164 pub fn with_openrouter_vendor(mut self, vendor: Option<&str>) -> Self {
165 self.openrouter_vendor = vendor.map(str::to_string);
166 self
167 }
168
169 #[must_use]
170 pub fn openrouter_vendor(&self) -> Option<&str> {
171 self.openrouter_vendor.as_deref()
172 }
173
174 #[must_use]
175 pub fn provider(&self) -> ProviderKind {
176 self.identity.provider
177 }
178
179 #[must_use]
180 pub fn provider_identity(&self) -> &str {
181 self.identity.key.as_str()
182 }
183
184 pub fn admitted_identity(&self) -> &ProviderIdentity {
185 &self.identity
186 }
187
188 #[must_use]
189 pub fn wire_model(&self) -> &str {
190 &self.wire_model
191 }
192
193 #[must_use]
194 pub fn endpoint_identity(&self) -> &str {
195 &self.endpoint_identity
196 }
197
198 #[must_use]
199 pub fn credential_generation(&self) -> &CredentialGeneration {
200 &self.credential_generation
201 }
202
203 /// Whether a live re-resolution of this route still lands on the same
204 /// endpoint and the same credential generation.
205 #[must_use]
206 pub fn matches_live_route(&self, base_url: &str, credential: &str) -> bool {
207 endpoint_identity(base_url) == self.endpoint_identity
208 && CredentialGeneration::derive(base_url, credential) == self.credential_generation
209 }
210 }
211
212 /// Redacted by construction: every field here is already non-secret, and the
213 /// generation digest renders as `<redacted>`.
214 impl fmt::Debug for TurnRouteReceipt {
215 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
216 f.debug_struct("TurnRouteReceipt")
217 .field("provider", &self.identity.provider)
218 .field("provider_identity", &self.identity.key)
219 .field("wire_model", &self.wire_model)
220 .field("endpoint_identity", &self.endpoint_identity)
221 .field("credential_generation", &self.credential_generation)
222 .finish()
223 }
224 }
225
226 #[cfg(test)]
227 mod tests {
228 use super::{CredentialGeneration, ProviderKind, TurnRouteReceipt, endpoint_identity};
229
230 const USERINFO_URL: &str = "https://svc-user:hunter2@api.example.com/v1?api_key=sk-live-abc123\
231 &token=tok-secret-xyz&region=us-east";
232
233 #[test]
234 fn endpoint_identity_masks_userinfo_and_sensitive_query_values() {
235 let identity = endpoint_identity(USERINFO_URL);
236
237 for secret in ["svc-user", "hunter2", "sk-live-abc123", "tok-secret-xyz"] {
238 assert!(
239 !identity.contains(secret),
240 "endpoint identity leaked {secret}: {identity}"
241 );
242 }
243 // …and it is still a useful endpoint identity.
244 assert!(identity.contains("api.example.com"), "{identity}");
245 assert!(identity.contains("/v1"), "{identity}");
246 assert!(identity.contains("region=us-east"), "{identity}");
247 }
248
249 #[test]
250 fn endpoint_identity_folds_only_trailing_slashes() {
251 assert_eq!(
252 endpoint_identity("https://api.deepseek.com/v1/"),
253 endpoint_identity(" https://api.deepseek.com/v1 ")
254 );
255 assert_ne!(
256 endpoint_identity("https://api.deepseek.com/v1"),
257 endpoint_identity("https://api.deepseek.com/v2")
258 );
259 assert_ne!(
260 endpoint_identity("https://api.deepseek.com/v1"),
261 endpoint_identity("https://exfil.example.com/v1")
262 );
263 assert_ne!(
264 endpoint_identity("https://api.deepseek.com/v1"),
265 endpoint_identity("https://api.deepseek.com:8443/v1")
266 );
267 }
268
269 #[test]
270 fn unparseable_endpoints_never_render_a_path() {
271 let identity = endpoint_identity("/Users/someone/secret-project/socket");
272 assert!(!identity.contains("someone"), "{identity}");
273 assert!(!identity.contains("secret-project"), "{identity}");
274 assert_eq!(identity, "<opaque-endpoint>");
275 }
276
277 #[test]
278 fn debug_never_renders_credential_material() {
279 let receipt = TurnRouteReceipt::new(
280 ProviderKind::Deepseek,
281 "deepseek",
282 "deepseek-chat",
283 USERINFO_URL,
284 "sk-deepseek-secret",
285 );
286
287 for rendered in [
288 format!("{receipt:?}"),
289 format!("{receipt:#?}"),
290 format!("{:?}", receipt.credential_generation()),
291 ] {
292 for secret in [
293 "sk-deepseek-secret",
294 "hunter2",
295 "sk-live-abc123",
296 "tok-secret-xyz",
297 ] {
298 assert!(
299 !rendered.contains(secret),
300 "Debug leaked {secret}: {rendered}"
301 );
302 }
303 }
304 let rendered = format!("{receipt:?}");
305 assert!(rendered.contains("<redacted>"), "{rendered}");
306 assert!(rendered.contains("api.example.com"), "{rendered}");
307 assert!(rendered.contains("deepseek-chat"), "{rendered}");
308 }
309
310 #[test]
311 fn credential_generation_separates_endpoint_from_credential() {
312 // Length prefixing: no byte can be moved across the field boundary to
313 // forge a matching generation.
314 assert_ne!(
315 CredentialGeneration::derive("https://host/v1a", "bc"),
316 CredentialGeneration::derive("https://host/v1", "abc")
317 );
318 }
319
320 #[test]
321 fn matches_live_route_detects_userinfo_swap_behind_identical_redaction() {
322 let receipt = TurnRouteReceipt::new(
323 ProviderKind::Deepseek,
324 "deepseek",
325 "deepseek-chat",
326 "https://svc:original@api.deepseek.com/v1",
327 "sk-key",
328 );
329 // Same redacted endpoint identity, different real credentials in the
330 // URL. Redaction alone would call this a match; the generation digest
331 // does not.
332 assert_eq!(
333 endpoint_identity("https://svc:rotated@api.deepseek.com/v1"),
334 receipt.endpoint_identity()
335 );
336 assert!(!receipt.matches_live_route("https://svc:rotated@api.deepseek.com/v1", "sk-key"));
337 assert!(receipt.matches_live_route("https://svc:original@api.deepseek.com/v1", "sk-key"));
338 assert!(
339 !receipt.matches_live_route("https://svc:original@api.deepseek.com/v1", "sk-other")
340 );
341 }
342 }
343
343 lines RUST