Skip to main content

alien_client_core/
interceptor.rs

1//! Interceptors: an extension's code that changes a cloud call after Alien builds it and before
2//! Alien signs it, and changes the response before Alien reads it.
3//!
4//! A deployment's chain travels on the clients built for it, never on a client config or in a
5//! global, so two deployments in one process never see each other's interceptors. An
6//! interceptor never sees the credentials Alien signs with. It may change what a call says about
7//! the deployment's own resources, and Alien refuses any change to where a call goes, to its
8//! method and path, to which identity it names, to an image in a cloud registry, or to a header
9//! that carries or protects a credential; on Kubernetes it may change only an object's labels. A
10//! call that changes who has access, acts as another identity or carries a Kubernetes credential
11//! is never offered, and no call may become one.
12
13use crate::error::{ErrorData, Result};
14use crate::identity::{decoded, is_identity_call};
15use alien_error::{AlienError, Context, IntoAlienError};
16use base64::Engine;
17use reqwest::header::{HeaderMap, HeaderValue, CONTENT_LENGTH};
18use reqwest::{Method, Url};
19#[cfg(not(target_arch = "wasm32"))]
20use reqwest::{ResponseBuilderExt, StatusCode};
21use sha2::{Digest, Sha256};
22use std::collections::BTreeSet;
23use std::sync::Arc;
24
25/// The API a call goes to.
26#[derive(Debug, Clone, Copy, PartialEq, Eq)]
27pub enum Cloud {
28    Aws,
29    Gcp,
30    Azure,
31    Kubernetes,
32}
33
34impl std::fmt::Display for Cloud {
35    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
36        f.write_str(match self {
37            Cloud::Aws => "aws",
38            Cloud::Gcp => "gcp",
39            Cloud::Azure => "azure",
40            Cloud::Kubernetes => "kubernetes",
41        })
42    }
43}
44
45/// A call as an interceptor sees it: the request Alien built, without credentials.
46#[derive(Debug, Clone)]
47pub struct HookRequest {
48    pub cloud: Cloud,
49    /// The service the call is signed for: the SigV4 signing name on AWS (`rds`), Alien's
50    /// endpoint key on Google Cloud (`cloudsql`), `management` for Azure Resource Manager, and
51    /// `kubernetes` for the API server.
52    pub service: String,
53    pub method: Method,
54    pub url: Url,
55    /// The request's headers, without `authorization`, `proxy-authorization` and
56    /// `x-amz-security-token`.
57    pub headers: HeaderMap,
58    /// The body as text, or `None` when the request has no body. A binary body is never
59    /// offered, so `matches` sees `None` for it as well, and a call it matches fails.
60    pub body: Option<String>,
61}
62
63/// A response as an interceptor sees it, before Alien reads it.
64#[derive(Debug, Clone)]
65pub struct HookResponse {
66    pub status: u16,
67    pub headers: HeaderMap,
68    pub body: String,
69}
70
71/// One extension's interceptor.
72pub trait CallInterceptor: Send + Sync {
73    /// The extension's name, which every error this interceptor causes carries.
74    fn extension(&self) -> &str;
75
76    /// Whether this interceptor sees `request`, the call as the interceptors before it left it.
77    /// Only the interceptors that match a call see its request and its response. An error fails
78    /// the call, as a failing `modify_request` does.
79    fn matches(&self, request: &HookRequest) -> Result<bool>;
80
81    fn modify_request(&self, request: &mut HookRequest) -> Result<()>;
82
83    /// Changes `response`, error responses included. `request` is the request as sent. An error
84    /// fails the call for good, even one the interceptor marked retryable.
85    fn modify_response(&self, request: &HookRequest, response: &mut HookResponse) -> Result<()>;
86}
87
88/// A deployment's interceptors, in the order its stack lists extensions. Each one gets the
89/// request as the previous one left it.
90#[derive(Clone, Default)]
91pub struct InterceptorChain {
92    interceptors: Vec<Arc<dyn CallInterceptor>>,
93    /// Set for a call whose body, sent or received, is an object's bytes.
94    object_payload: bool,
95}
96
97impl std::fmt::Debug for InterceptorChain {
98    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
99        f.debug_list()
100            .entries(
101                self.interceptors
102                    .iter()
103                    .map(|interceptor| interceptor.extension()),
104            )
105            .finish()
106    }
107}
108
109/// Headers an interceptor may not set, change or remove: they pick the destination, the method
110/// the server runs, the project billed or the object an S3 copy reads, carry a credential, are
111/// signed with one, or say how the body is read.
112const PROTECTED_HEADERS: [&str; 12] = [
113    "host",
114    "content-type",
115    "x-http-method-override",
116    "x-http-method",
117    "authorization",
118    "x-amz-date",
119    "x-amz-security-token",
120    "proxy-authorization",
121    "x-goog-user-project",
122    "x-goog-api-key",
123    "x-ms-authorization-auxiliary",
124    "x-amz-copy-source",
125];
126
127/// Query parameters Google Cloud reads the project billed, the caller's credential or the
128/// format of the body and response from, in any case, so an interceptor may not set, change or
129/// remove them on a Google Cloud call. Every system parameter written with a leading `$` (such
130/// as `$ct`, which sets the body's content type) is protected the same way.
131const PROTECTED_GCP_QUERY: [&str; 6] = [
132    "userproject",
133    "key",
134    "access_token",
135    "oauth_token",
136    "bearer_token",
137    "alt",
138];
139
140/// Kubernetes' impersonation headers (`impersonate-user`, `impersonate-group`,
141/// `impersonate-extra-*`, ...) set who the call acts as, so an interceptor may not set, change or
142/// remove any of them.
143const PROTECTED_HEADER_PREFIX: &str = "impersonate-";
144
145/// AWS operations that read or change a resource's policy, its grants or who may call it,
146/// through the resource's own service: SNS and SQS permissions, KMS key policies and grants,
147/// ECR repository policies, and Secrets Manager and CloudWatch Logs resource policies.
148const AWS_POLICY_OPERATIONS: [&str; 13] = [
149    "AddPermission",
150    "RemovePermission",
151    "PutKeyPolicy",
152    "GetKeyPolicy",
153    "CreateGrant",
154    "RetireGrant",
155    "RevokeGrant",
156    "SetRepositoryPolicy",
157    "GetRepositoryPolicy",
158    "DeleteRepositoryPolicy",
159    "PutResourcePolicy",
160    "GetResourcePolicy",
161    "DeleteResourcePolicy",
162];
163
164/// The WebAssembly reqwest cannot rebuild a response, and no WebAssembly build of Alien gives
165/// its clients interceptors, so a call one matches fails before it is sent.
166const WASM_UNSUPPORTED: &str = "interceptors do not run in WebAssembly builds of Alien";
167
168/// Headers that carry a credential. The interceptor's view leaves them out, and the request
169/// keeps them as they were.
170const CREDENTIAL_HEADERS: [&str; 3] = [
171    "authorization",
172    "proxy-authorization",
173    "x-amz-security-token",
174];
175
176/// Where a signed request carries a credential: these headers, and on Google Cloud these query
177/// parameters. A response can quote them, as AWS quotes the signed headers, session token
178/// included, when a signature does not match.
179const CREDENTIAL_CARRIERS: [&str; 5] = [
180    "authorization",
181    "proxy-authorization",
182    "x-amz-security-token",
183    "x-goog-api-key",
184    "x-ms-authorization-auxiliary",
185];
186const CREDENTIAL_QUERY: [&str; 3] = ["access_token", "key", "oauth_token"];
187
188impl InterceptorChain {
189    pub fn new(interceptors: Vec<Arc<dyn CallInterceptor>>) -> Self {
190        Self {
191            interceptors,
192            object_payload: false,
193        }
194    }
195
196    pub fn is_empty(&self) -> bool {
197        self.interceptors.is_empty()
198    }
199
200    /// The same interceptors, for a call that sends or returns an object's bytes (an S3 or Cloud
201    /// Storage object, a Lambda payload). Those bytes are never offered, whatever their content
202    /// type, so the call fails before it is sent when an interceptor matches it.
203    pub fn for_object_payload(&self) -> Self {
204        Self {
205            interceptors: self.interceptors.clone(),
206            object_payload: true,
207        }
208    }
209
210    /// Runs the interceptors that match `request`, which Alien built and has not sent, on it.
211    /// Returns the hook its response must pass through, or `None` when no interceptor matched
212    /// and the request is left as it was.
213    pub fn intercept(
214        &self,
215        cloud: Cloud,
216        service: &str,
217        request: &mut reqwest::Request,
218    ) -> Result<Option<ResponseHook>> {
219        if self.is_empty() {
220            return Ok(None);
221        }
222        let body = match request.body() {
223            _ if self.object_payload => Err(()),
224            None => Ok(None),
225            Some(body) => match body.as_bytes() {
226                None => Err(()),
227                Some([]) => Ok(None),
228                Some(bytes) => String::from_utf8(bytes.to_vec()).map(Some).map_err(|_| ()),
229            },
230        };
231        let mut headers = request.headers().clone();
232        for name in CREDENTIAL_HEADERS {
233            headers.remove(name);
234        }
235        let original = HookRequest {
236            cloud,
237            service: service.to_string(),
238            method: request.method().clone(),
239            url: request.url().clone(),
240            headers,
241            body: body.clone().unwrap_or_default(),
242        };
243        // Not even `matches` sees it, so an interceptor that matches every call never fails it.
244        if changes_access(&original) {
245            return Ok(None);
246        }
247
248        if body.is_err() || cfg!(target_arch = "wasm32") {
249            let mut first_match = None;
250            for interceptor in &self.interceptors {
251                if matches(interceptor.as_ref(), &original)? {
252                    first_match = Some(interceptor);
253                    break;
254                }
255            }
256            let Some(interceptor) = first_match else {
257                return Ok(None);
258            };
259            let reason = if body.is_err() {
260                format!(
261                    "the {cloud} {service} call {} {} carries a binary body, which interceptors are not offered",
262                    original.method,
263                    original.url.path()
264                )
265            } else {
266                WASM_UNSUPPORTED.to_string()
267            };
268            return Err(failed(interceptor.extension(), reason));
269        }
270
271        let mut view = original.clone();
272        let mut matched = Vec::new();
273        for interceptor in &self.interceptors {
274            if !matches(interceptor.as_ref(), &view)? {
275                continue;
276            }
277            interceptor
278                .modify_request(&mut view)
279                .context_keeping_retry(ErrorData::InterceptorFailed {
280                    extension: interceptor.extension().to_string(),
281                    message: format!("modify_request failed on the {cloud} {service} call"),
282                })?;
283            // A JSON body is sent as it was parsed, and checked in that form, so a key written
284            // twice or an escape a cloud would decode can't carry a change the checks never saw.
285            if view.body != original.body {
286                if let Some(Ok(parsed)) = view
287                    .body
288                    .as_deref()
289                    .map(serde_json::from_str::<serde_json::Value>)
290                {
291                    view.body = Some(parsed.to_string());
292                }
293            }
294            if let Some(reason) = refused_change(&original, &view) {
295                return Err(failed(interceptor.extension(), reason));
296            }
297            matched.push(interceptor.clone());
298        }
299        if matched.is_empty() {
300            return Ok(None);
301        }
302
303        let mut headers = view.headers.clone();
304        for name in CREDENTIAL_HEADERS {
305            for value in request.headers().get_all(name) {
306                headers.append(name, value.clone());
307            }
308        }
309        *request.method_mut() = view.method.clone();
310        *request.url_mut() = view.url.clone();
311        *request.headers_mut() = headers;
312        if view.body != original.body {
313            let body = view.body.clone().unwrap_or_default();
314            rewrite_body_digests(request.headers_mut(), body.as_bytes())?;
315            *request.body_mut() = view.body.clone().map(reqwest::Body::from);
316        }
317
318        let mut hook = ResponseHook {
319            matched: matched.into(),
320            request: Arc::new(view),
321            secrets: Vec::new(),
322        };
323        // A client that signs before its interceptors run has its credential on the request
324        // already; one that signs after adds it with `remember_credentials`.
325        hook.remember_credentials(request);
326        Ok(Some(hook))
327    }
328
329    /// Refuses `url` unless it is on `endpoint`, the endpoint this client was configured with.
330    /// A response names URLs Alien then sends its credential to (an operation to poll, a next
331    /// page), and an interceptor can rewrite a response, so a client with interceptors signs only
332    /// for its own endpoint.
333    pub fn check_destination(&self, url: &Url, endpoint: &str) -> Result<()> {
334        if self.is_empty() {
335            return Ok(());
336        }
337        let endpoint =
338            Url::parse(endpoint)
339                .into_alien_error()
340                .context(ErrorData::InvalidClientConfig {
341                    message: format!("The client's endpoint '{endpoint}' is not a URL"),
342                    errors: None,
343                })?;
344        if url.origin() == endpoint.origin() {
345            return Ok(());
346        }
347        Err(AlienError::new(ErrorData::DestinationRefused {
348            url: url.origin().ascii_serialization(),
349            endpoint: endpoint.origin().ascii_serialization(),
350        }))
351    }
352}
353
354/// The interceptors that matched one call, to run on its response.
355#[derive(Clone)]
356pub struct ResponseHook {
357    matched: Arc<[Arc<dyn CallInterceptor>]>,
358    request: Arc<HookRequest>,
359    /// The credentials the call was sent with, cleared from its response before any interceptor
360    /// reads it.
361    secrets: Vec<String>,
362}
363
364impl std::fmt::Debug for ResponseHook {
365    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
366        f.debug_list()
367            .entries(
368                self.matched
369                    .iter()
370                    .map(|interceptor| interceptor.extension()),
371            )
372            .finish()
373    }
374}
375
376impl ResponseHook {
377    /// Records the credentials `request` carries, so they are cleared from the response before
378    /// an interceptor reads it. A client that signs after the interceptors ran calls this with
379    /// the signed request.
380    pub fn remember_credentials(&mut self, request: &reqwest::Request) {
381        for name in CREDENTIAL_CARRIERS {
382            for value in request.headers().get_all(name) {
383                let Ok(value) = value.to_str() else {
384                    continue;
385                };
386                self.remember(value);
387                // `Bearer <token>`, alone or listed, as Azure's auxiliary header lists them.
388                for part in value.split(',') {
389                    if let Some((_, credential)) = part.trim().split_once(' ') {
390                        self.remember(credential);
391                    }
392                }
393            }
394        }
395        for (name, value) in request.url().query_pairs() {
396            if CREDENTIAL_QUERY
397                .iter()
398                .any(|carrier| name.eq_ignore_ascii_case(carrier))
399            {
400                self.remember(&value);
401            }
402        }
403    }
404
405    fn remember(&mut self, secret: &str) {
406        let secret = secret.trim();
407        // Short of any real credential, and short enough to match ordinary text.
408        if secret.len() >= 8 && !self.secrets.iter().any(|known| known == secret) {
409            self.secrets.push(secret.to_string());
410        }
411    }
412
413    /// `bytes` with each recorded credential replaced by `[redacted]`, longest first, so one
414    /// that contains another is cleared whole.
415    fn cleared(&self, bytes: &[u8]) -> Vec<u8> {
416        let mut secrets: Vec<&String> = self.secrets.iter().collect();
417        secrets.sort_by_key(|secret| std::cmp::Reverse(secret.len()));
418        secrets.into_iter().fold(bytes.to_vec(), |bytes, secret| {
419            blank(bytes, secret.as_bytes())
420        })
421    }
422
423    /// Reads the whole response, lets each interceptor that matched the call change it, and
424    /// returns a response Alien reads as if the cloud had sent it.
425    #[cfg(not(target_arch = "wasm32"))]
426    pub async fn apply(&self, response: reqwest::Response) -> Result<reqwest::Response> {
427        let status = response.status();
428        let url = response.url().clone();
429        let headers = response.headers().clone();
430        let read = response.bytes().await.into_alien_error();
431        // This runs inside the retry loop, and after a 2xx the cloud already acted on the call.
432        let bytes = if status.is_success() {
433            read.context(ErrorData::HttpResponseBodyReadFailed {
434                http_status: status.as_u16(),
435            })?
436        } else {
437            read.context(ErrorData::HttpRequestFailed {
438                message: "Failed to read response body".to_string(),
439            })?
440        };
441        let Ok(body) = String::from_utf8(bytes.to_vec()) else {
442            return Err(failed(
443                self.matched[0].extension(),
444                format!(
445                    "the response to the {} {} call {} {} has a binary body, which interceptors are not offered",
446                    self.request.cloud,
447                    self.request.service,
448                    self.request.method,
449                    self.request.url.path()
450                ),
451            ));
452        };
453
454        // Cleared before any interceptor runs: one could encode an echoed credential into what
455        // it leaves, where clearing it later would no longer find it.
456        let mut cleared_headers = HeaderMap::with_capacity(headers.len());
457        for (name, value) in &headers {
458            // `[redacted]` in place of the credential keeps the value a valid header.
459            if let Ok(value) = HeaderValue::from_bytes(&self.cleared(value.as_bytes())) {
460                cleared_headers.append(name.clone(), value);
461            }
462        }
463        let body = String::from_utf8(self.cleared(body.as_bytes())).unwrap_or(body);
464        let mut view = HookResponse {
465            status: status.as_u16(),
466            headers: cleared_headers,
467            body,
468        };
469        let received = (view.status, view.headers.clone(), view.body.clone());
470        for interceptor in self.matched.iter() {
471            // Final whatever the hook said: the cloud already acted on the call, and a retry
472            // would send it again.
473            interceptor
474                .modify_response(&self.request, &mut view)
475                .context(ErrorData::InterceptorFailed {
476                    extension: interceptor.extension().to_string(),
477                    message: format!(
478                        "modify_response failed on the {} {} call",
479                        self.request.cloud, self.request.service
480                    ),
481                })?;
482            let Ok(left) = StatusCode::from_u16(view.status) else {
483                return Err(failed(
484                    interceptor.extension(),
485                    format!("{} is not an HTTP status", view.status),
486                ));
487            };
488            // The cloud already acted on a call it answered with success, so a failure a hook
489            // makes of it fails the call for good: a client would retry a status such as 429,
490            // and send a create again.
491            if status.is_success() && !left.is_success() {
492                return Err(failed(
493                    interceptor.extension(),
494                    format!(
495                        "it turned the {} {} call's success ({}) into {left}, after the cloud had acted on it",
496                        self.request.cloud,
497                        self.request.service,
498                        status.as_u16()
499                    ),
500                ));
501            }
502            if self.request.cloud == Cloud::Kubernetes
503                && (view.status, &view.headers, &view.body)
504                    != (received.0, &received.1, &received.2)
505            {
506                return Err(failed(
507                    interceptor.extension(),
508                    "on Kubernetes an interceptor may not change a response".to_string(),
509                ));
510            }
511        }
512
513        let mut headers = view.headers;
514        // The body's own length decides it; a stale one would cut or stall the read.
515        headers.remove(CONTENT_LENGTH);
516        let last = &self.matched[self.matched.len() - 1];
517        let mut rebuilt = http::Response::builder()
518            .status(view.status)
519            .url(url)
520            .body(view.body)
521            .into_alien_error()
522            .context(ErrorData::InterceptorFailed {
523                extension: last.extension().to_string(),
524                message: "the response it left could not be rebuilt".to_string(),
525            })?;
526        *rebuilt.headers_mut() = headers;
527        Ok(reqwest::Response::from(rebuilt))
528    }
529
530    #[cfg(target_arch = "wasm32")]
531    pub async fn apply(&self, _response: reqwest::Response) -> Result<reqwest::Response> {
532        Err(failed(
533            self.matched[0].extension(),
534            format!(
535                "{WASM_UNSUPPORTED}: the {} {} call",
536                self.request.cloud, self.request.service
537            ),
538        ))
539    }
540}
541
542/// Keeps an interceptor's failure final under a wrapper that marks the error retryable: the same
543/// request fails the same way again. A failure before the call was sent that the interceptor
544/// itself marked retryable, as a hook stopped at its deadline is, stays retryable.
545pub fn keep_interceptor_failure_final<T>(result: Result<T>) -> Result<T> {
546    result.map_err(|mut error| {
547        let final_failure =
548            |code: &str, retryable: bool| is_interceptor_failure(code) && !retryable;
549        let mut caused_by_interceptor = final_failure(&error.code, error.retryable);
550        let mut layer = error.source.as_deref();
551        while let Some(source) = layer {
552            caused_by_interceptor |= final_failure(&source.code, source.retryable);
553            layer = source.source.as_deref();
554        }
555        if caused_by_interceptor {
556            error.retryable = false;
557        }
558        error
559    })
560}
561
562/// `bytes` with each occurrence of `secret` replaced by `[redacted]`.
563fn blank(bytes: Vec<u8>, secret: &[u8]) -> Vec<u8> {
564    const BLANK: &[u8] = b"[redacted]";
565    let mut cleared = Vec::new();
566    let mut rest = bytes.as_slice();
567    while let Some(at) = rest
568        .windows(secret.len())
569        .position(|window| window == secret)
570    {
571        cleared.extend_from_slice(&rest[..at]);
572        cleared.extend_from_slice(BLANK);
573        rest = &rest[at + secret.len()..];
574    }
575    if cleared.is_empty() {
576        return bytes;
577    }
578    cleared.extend_from_slice(rest);
579    cleared
580}
581
582fn is_interceptor_failure(code: &str) -> bool {
583    matches!(code, "INTERCEPTOR_FAILED" | "DESTINATION_REFUSED")
584}
585
586/// Passes `response` through `hook`, when the call had one.
587pub async fn apply_response_hook(
588    hook: Option<&ResponseHook>,
589    response: reqwest::Response,
590) -> Result<reqwest::Response> {
591    match hook {
592        Some(hook) => hook.apply(response).await,
593        None => Ok(response),
594    }
595}
596
597/// Asks `interceptor` whether it sees `request`, naming it in the error when it can't answer.
598fn matches(interceptor: &dyn CallInterceptor, request: &HookRequest) -> Result<bool> {
599    interceptor
600        .matches(request)
601        .context_keeping_retry(ErrorData::InterceptorFailed {
602            extension: interceptor.extension().to_string(),
603            message: format!(
604                "matches failed on the {} {} call",
605                request.cloud, request.service
606            ),
607        })
608}
609
610/// `.context` for an interceptor's error from `matches` or `modify_request`, before the call is
611/// sent. The failure is final unless the interceptor itself said it may pass, as a hook stopped
612/// at its deadline may.
613trait KeepingRetry<T> {
614    fn context_keeping_retry(self, context: ErrorData) -> Result<T>;
615}
616
617impl<T> KeepingRetry<T> for Result<T> {
618    fn context_keeping_retry(self, context: ErrorData) -> Result<T> {
619        self.map_err(|error| {
620            let retryable = error.retryable && error.code == "INTERCEPTOR_FAILED";
621            let mut wrapped = Err::<(), _>(error).context(context).unwrap_err();
622            wrapped.retryable = retryable;
623            wrapped
624        })
625    }
626}
627
628fn failed(extension: &str, message: String) -> AlienError<ErrorData> {
629    AlienError::new(ErrorData::InterceptorFailed {
630        extension: extension.to_string(),
631        message,
632    })
633}
634
635/// Why the change from `original` to `changed` is refused, if it is.
636fn refused_change(original: &HookRequest, changed: &HookRequest) -> Option<String> {
637    if original.cloud == Cloud::Kubernetes && !only_labels_changed(original, changed) {
638        return Some(
639            "on Kubernetes an interceptor may change only the object's metadata.labels".to_string(),
640        );
641    }
642    if changed.url.origin() != original.url.origin() {
643        return Some(format!(
644            "it moved the call from {} to {}; it may change the query, not the scheme, host or port",
645            original.url.origin().ascii_serialization(),
646            changed.url.origin().ascii_serialization()
647        ));
648    }
649    if changed.cloud != original.cloud || changed.service != original.service {
650        return Some(format!(
651            "it changed the call's cloud or service from {} {} to {} {}",
652            original.cloud, original.service, changed.cloud, changed.service
653        ));
654    }
655    if changes_access(changed) {
656        return Some(
657            "it turned the call into one that changes who has access or acts as another identity"
658                .to_string(),
659        );
660    }
661    let (before, after) = (exposure_settings(original), exposure_settings(changed));
662    if let Some((place, _)) = before.symmetric_difference(&after).next() {
663        return Some(format!(
664            "it added, removed or changed a setting that decides who can reach a resource ({place}); an interceptor may not touch network, firewall, access or public-exposure settings"
665        ));
666    }
667    if let Some(exposure) = public_exposures(changed)
668        .difference(&public_exposures(original))
669        .next()
670    {
671        return Some(format!(
672            "it made the call open a resource to the internet ({exposure}); an interceptor may not make storage or a network public"
673        ));
674    }
675    if is_json(original) && !is_json(changed) {
676        return Some("it changed a JSON body into one that is not JSON".to_string());
677    }
678    // The checks read a body by its format, and the cloud by the call's content type, which a
679    // call Alien sends without a body may not match.
680    if original.body.is_none() && changed.body.is_some() {
681        return Some("it added a body to a call Alien sends without one".to_string());
682    }
683    // A JSON body is sent as it was parsed, so a body read as something else may not become one.
684    if !is_json(original) && is_json(changed) {
685        return Some("it changed a body that is not JSON into JSON".to_string());
686    }
687    if named_identities(changed) != named_identities(original) {
688        return Some(
689            "it changed which identity the call names; a call acts only as the identities Alien gives it"
690                .to_string(),
691        );
692    }
693    if let Some(image) = registry_images(changed)
694        .difference(&registry_images(original))
695        .next()
696    {
697        return Some(format!(
698            "it named {image}, a reference to a cloud registry the call didn't name; only an image from a public registry may be added"
699        ));
700    }
701    if changed.method != original.method || changed.url.path() != original.url.path() {
702        return Some(format!(
703            "it changed {} {} to {} {}; the method and path say which resource the call acts on and how",
704            original.method,
705            original.url.path(),
706            changed.method,
707            changed.url.path()
708        ));
709    }
710    if original.cloud == Cloud::Aws && aws_operations(original) != aws_operations(changed) {
711        return Some(
712            "it changed the AWS operation, in the Action parameter or the X-Amz-Target header"
713                .to_string(),
714        );
715    }
716    // A query parameter can be the operation, such as S3's `?logging` or API Gateway's
717    // `?mode=import`, so on AWS a parameter's value may change, its name not.
718    if original.cloud == Cloud::Aws && query_names(original) != query_names(changed) {
719        return Some(
720            "it added or removed a query parameter; on AWS the parameters a call has are part of its operation"
721                .to_string(),
722        );
723    }
724    if original.cloud == Cloud::Gcp {
725        let values = |request: &HookRequest, name: &str| -> Vec<String> {
726            request
727                .url
728                .query_pairs()
729                .filter(|(key, _)| key.eq_ignore_ascii_case(name))
730                .map(|(_, value)| value.into_owned())
731                .collect()
732        };
733        let system: BTreeSet<String> = [original, changed]
734            .into_iter()
735            .flat_map(|request| {
736                request
737                    .url
738                    .query_pairs()
739                    .map(|(key, _)| key.to_ascii_lowercase())
740            })
741            .filter(|key| key.starts_with('$'))
742            .collect();
743        if let Some(name) = PROTECTED_GCP_QUERY
744            .into_iter()
745            .map(str::to_string)
746            .chain(
747                PROTECTED_GCP_QUERY
748                    .into_iter()
749                    .map(|name| format!("${name}")),
750            )
751            .chain(system)
752            .find(|name| values(original, name) != values(changed, name))
753        {
754            return Some(format!(
755                "it set, changed or removed the '{name}' query parameter"
756            ));
757        }
758    }
759    // Header names are stored lowercase, so the prefix matches whatever case was sent.
760    let impersonation = original
761        .headers
762        .keys()
763        .chain(changed.headers.keys())
764        .map(|name| name.as_str())
765        .filter(|name| name.starts_with(PROTECTED_HEADER_PREFIX));
766    PROTECTED_HEADERS
767        .into_iter()
768        .chain(impersonation)
769        .find(|name| {
770            !original
771                .headers
772                .get_all(*name)
773                .iter()
774                .eq(changed.headers.get_all(*name).iter())
775        })
776        .map(|name| format!("it set, changed or removed the '{name}' header"))
777}
778
779/// Whether `request` changes who has access, acts as another identity, reads a policy Alien then
780/// writes back, or carries a Kubernetes Secret or service account token. The path is read
781/// as the cloud reads it: percent-decoded and in any case.
782fn changes_access(request: &HookRequest) -> bool {
783    let path = decoded(request.url.path());
784    // A cloud may fold a character that is not ASCII into one that is, and reach a name the
785    // checks look for.
786    if !path.is_ascii() {
787        return true;
788    }
789    let path = path.to_ascii_lowercase();
790    let segments: Vec<&str> = path.split('/').filter(|s| !s.is_empty()).collect();
791    let query: Vec<(String, String)> = request.url.query_pairs().into_owned().collect();
792    if is_identity_call(
793        request.cloud,
794        &[request.service.as_str()],
795        request.method.as_str(),
796        &segments,
797        &query,
798    ) {
799        return true;
800    }
801    match request.cloud {
802        // Alien reads a policy, adds its binding and writes the policy back, so a read's
803        // response decides the write.
804        Cloud::Gcp => {
805            segments.iter().any(|s| s.contains("iampolicy"))
806                || (request.service == "storage"
807                    && (segments.last() == Some(&"iam")
808                        || segments
809                            .iter()
810                            .any(|s| matches!(*s, "acl" | "defaultobjectacl"))))
811        }
812        Cloud::Aws => {
813            aws_operations(request).iter().any(|operation| {
814                // A target is `<service>.<operation>`.
815                let name = operation.rsplit('.').next().unwrap_or(operation);
816                AWS_POLICY_OPERATIONS.contains(&name)
817            }) || request.body.as_deref().is_some_and(sets_a_policy)
818                // The query protocol reads parameters from the URL as well as the form body.
819                || form_sets_a_policy(request.url.query().unwrap_or_default())
820                || (request.service == "s3"
821                    && (query
822                        .iter()
823                        .any(|(name, _)| {
824                            matches!(
825                                name.to_ascii_lowercase().as_str(),
826                                "policy" | "acl" | "publicaccessblock"
827                            )
828                        })
829                        || request.headers.keys().any(|name| {
830                            name == "x-amz-acl" || name.as_str().starts_with("x-amz-grant-")
831                        })))
832                || (request.service == "lambda" && segments.contains(&"policy"))
833                || (request.service == "apigateway"
834                    && request.body.as_deref().is_some_and(sets_an_api_policy))
835        }
836        // A Secret holds the deployment's registry credential, a token request mints a service
837        // account's token, and a token review carries one.
838        Cloud::Kubernetes => {
839            segments.contains(&"tokenreviews")
840                || segments
841                    .windows(3)
842                    .any(|w| w[0] == "namespaces" && w[2] == "secrets")
843                || segments.windows(2).any(|w| w == ["v1", "secrets"])
844                || segments
845                    .windows(3)
846                    .any(|w| w[0] == "serviceaccounts" && w[2] == "token")
847        }
848        Cloud::Azure => false,
849    }
850}
851
852/// Network ranges that mean the whole internet, in any cloud.
853const OPEN_RANGES: [&str; 5] = ["0.0.0.0/0", "::/0", "internet", "any", "*"];
854
855/// Fields that hold a source range or address prefix on Azure, which may name the internet as a
856/// tag (`Internet`, `Any`, `*`) and not only as a CIDR.
857const AZURE_SOURCE_FIELDS: [&str; 4] = [
858    "sourceaddressprefix",
859    "sourceaddressprefixes",
860    "sourceaddresses",
861    "ipaddressorrange",
862];
863
864/// A field name without case, `_` and `-`, so `invoker_iam_disabled`, `invokerIamDisabled` and
865/// `Invoker-Iam-Disabled` are one name.
866fn field_key(name: &str) -> String {
867    name.chars()
868        .filter(|c| !matches!(c, '_' | '-'))
869        .map(|c| c.to_ascii_lowercase())
870        .collect()
871}
872
873/// Whether a field by this name sets who can reach a resource: a public-access, network, firewall,
874/// source-range, ingress, ACL or access-policy setting, on any cloud.
875fn exposure_field(name: &str) -> bool {
876    let name = field_key(name);
877    name.starts_with("publicaccess")
878        || name.starts_with("sourceaddressprefix")
879        || name.contains("ingress")
880        || matches!(
881            name.as_str(),
882            "allowblobpublicaccess"
883                | "allowpublicaccess"
884                | "publicnetworkaccess"
885                | "networkacls"
886                | "defaultaction"
887                | "iprules"
888                | "ipranges"
889                | "ipaddressorrange"
890                | "sourceaddresses"
891                | "sourceranges"
892                | "invokeriamdisabled"
893                | "publiclyaccessible"
894                | "ipconfiguration"
895                | "ipv4enabled"
896                | "authorizednetworks"
897                | "cidrip"
898                | "cidripv6"
899                | "acl"
900                | "defaultobjectacl"
901                | "iamconfiguration"
902                | "accesspolicies"
903                | "enablerbacauthorization"
904        )
905}
906
907/// Every exposure or access setting a call carries, with where it sits and its whole value
908/// (every leaf of a nested setting). The set must be equal before and after an interceptor: a
909/// setting added, removed or changed in any way counts, so a range split in two, a firewall
910/// field flipped, or a protection element dropped is caught without judging its value.
911fn exposure_settings(request: &HookRequest) -> BTreeSet<(String, String)> {
912    let body = request.body.as_deref().unwrap_or_default();
913    let mut found = BTreeSet::new();
914    let json = serde_json::from_str::<serde_json::Value>(body).ok();
915    let mut pairs = |location: &str, text: &str| {
916        for (key, value) in form_urlencoded::parse(text.as_bytes()) {
917            if key.rsplit('.').next().is_some_and(exposure_field) {
918                found.insert((format!("{location}{key}"), value.into_owned()));
919            }
920        }
921    };
922    pairs("?", request.url.query().unwrap_or_default());
923    if json.is_none() {
924        pairs("&", body);
925    }
926    if let Some(value) = &json {
927        json_settings(value, "", &mut found);
928    }
929    // The S3 public access block is XML: each element is a setting, counted by position.
930    let lower = body.to_ascii_lowercase();
931    for tag in [
932        "blockpublicacls",
933        "ignorepublicacls",
934        "blockpublicpolicy",
935        "restrictpublicbuckets",
936    ] {
937        let open = format!("<{tag}>");
938        for (n, (at, _)) in lower.match_indices(&open).enumerate() {
939            let rest = &lower[at + open.len()..];
940            let value = rest.split('<').next().unwrap_or_default().trim();
941            found.insert((format!("S3 {tag} #{n}"), value.to_string()));
942        }
943    }
944    found
945}
946
947fn json_settings(value: &serde_json::Value, pointer: &str, found: &mut BTreeSet<(String, String)>) {
948    match value {
949        serde_json::Value::Object(fields) => {
950            for (key, field) in fields {
951                let at = pointer_to(pointer, key);
952                if exposure_field(key) {
953                    every_leaf(field, &at, found);
954                }
955                json_settings(field, &at, found);
956            }
957        }
958        serde_json::Value::Array(items) => {
959            for (index, item) in items.iter().enumerate() {
960                json_settings(item, &format!("{pointer}/{index}"), found);
961            }
962        }
963        _ => {}
964    }
965}
966
967/// What in `request` opens a resource to the internet, each as a short description. A call that
968/// Alien builds with one of them (a bucket made public on purpose) keeps it; the check refuses an
969/// exposure the original call did not have. It covers a storage account or container that allows
970/// public access, a storage firewall, network security group or firewall rule whose source is the
971/// internet, a security group open to `0.0.0.0/0` or `::/0`, `allUsers` and
972/// `allAuthenticatedUsers` in a Cloud Storage body, and an S3 public access block turned off.
973fn public_exposures(request: &HookRequest) -> BTreeSet<String> {
974    let body = request.body.as_deref().unwrap_or_default();
975    let query = request.url.query().unwrap_or_default();
976    let json = serde_json::from_str::<serde_json::Value>(body).ok();
977    let mut texts = vec![body.to_string(), decoded(body), decoded(query)];
978    if let Some(value) = &json {
979        json_strings(value, &mut texts);
980    }
981    let mut found = BTreeSet::new();
982    // A needle counts once per place it appears, so a second one is a new exposure.
983    for needle in ["0.0.0.0/0", "::/0", "allusers", "allauthenticatedusers"] {
984        let count = texts
985            .iter()
986            .map(|text| text.to_ascii_lowercase().matches(needle).count())
987            .max()
988            .unwrap_or(0);
989        for n in 0..count {
990            found.insert(format!("{needle} #{n}"));
991        }
992    }
993    // An S3 public access block with a protection turned off.
994    let lower = body.to_ascii_lowercase();
995    for tag in [
996        "blockpublicacls",
997        "ignorepublicacls",
998        "blockpublicpolicy",
999        "restrictpublicbuckets",
1000    ] {
1001        if lower.contains(&format!("<{tag}>false")) {
1002            found.insert(format!("S3 {tag} turned off"));
1003        }
1004    }
1005    if let Some(value) = &json {
1006        json_exposures(value, "", &mut found);
1007    }
1008    found
1009}
1010
1011fn json_exposures(value: &serde_json::Value, pointer: &str, found: &mut BTreeSet<String>) {
1012    match value {
1013        serde_json::Value::Object(fields) => {
1014            for (key, field) in fields {
1015                let name = field_key(key);
1016                let at = pointer_to(pointer, key);
1017                let text = field.as_str().map(|text| text.trim().to_ascii_lowercase());
1018                let public = match name.as_str() {
1019                    "allowblobpublicaccess" | "allowpublicaccess" => {
1020                        field.as_bool() == Some(true) || text.as_deref() == Some("true")
1021                    }
1022                    // A container's access level: anything but none or off.
1023                    "publicaccess" => text
1024                        .as_deref()
1025                        .is_some_and(|t| !matches!(t, "none" | "off" | "")),
1026                    "publicnetworkaccess" => text.as_deref() == Some("enabled"),
1027                    "defaultaction" => text.as_deref() == Some("allow"),
1028                    // Cloud Storage: public access prevention turned off.
1029                    "publicaccessprevention" => text.as_deref().is_some_and(|t| t != "enforced"),
1030                    _ => false,
1031                };
1032                if public {
1033                    found.insert(at.clone());
1034                }
1035                if AZURE_SOURCE_FIELDS.contains(&name.as_str())
1036                    || name == "ipranges"
1037                    || name == "sourceranges"
1038                {
1039                    let mut leaves = Vec::new();
1040                    json_strings(field, &mut leaves);
1041                    if leaves.iter().any(|leaf| {
1042                        let leaf = leaf.trim().to_ascii_lowercase();
1043                        OPEN_RANGES.contains(&leaf.as_str()) || leaf.ends_with("/0")
1044                    }) {
1045                        found.insert(format!("{at}: an open source range"));
1046                    }
1047                }
1048                json_exposures(field, &at, found);
1049            }
1050        }
1051        serde_json::Value::Array(items) => {
1052            for (index, item) in items.iter().enumerate() {
1053                json_exposures(item, &format!("{pointer}/{index}"), found);
1054            }
1055        }
1056        _ => {}
1057    }
1058}
1059
1060/// The identities a call's body or query names, each with where it names it: a Google service
1061/// account's email, an AWS IAM role or instance profile ARN, an Azure managed identity's
1062/// resource ID, and a field that names an identity by its name. A call that drops one may act as
1063/// a default identity instead, and a name kept in another field no longer picks the identity, so
1064/// a change of any kind counts.
1065fn named_identities(request: &HookRequest) -> BTreeSet<(String, String)> {
1066    let body = request.body.as_deref().unwrap_or_default();
1067    let query = request.url.query().unwrap_or_default();
1068    let json = serde_json::from_str::<serde_json::Value>(body).ok();
1069    // Every identity the text names, wherever it sits, so a duplicate JSON key or a body that is
1070    // neither JSON nor a form still counts. A JSON escape hides a name from the raw text, so the
1071    // decoded strings are read too.
1072    let mut texts = vec![body.to_string(), decoded(body), decoded(query)];
1073    if let Some(value) = &json {
1074        json_strings(value, &mut texts);
1075    }
1076    let mut named = BTreeSet::new();
1077    for text in texts {
1078        let tokens = text.split(|c: char| !(c.is_ascii_alphanumeric() || "@._:/+=,-".contains(c)));
1079        for token in tokens {
1080            if names_an_identity(token) {
1081                named.insert(("*".to_string(), token.to_ascii_lowercase()));
1082            }
1083        }
1084    }
1085    let pairs = |location: &str, text: &str, named: &mut BTreeSet<(String, String)>| {
1086        for (key, value) in form_urlencoded::parse(text.as_bytes()) {
1087            if key.split('.').any(identity_field)
1088                || names_an_identity(&key)
1089                || names_an_identity(&value)
1090            {
1091                named.insert((format!("{location}{key}"), value.into_owned()));
1092            }
1093        }
1094    };
1095    pairs("?", query, &mut named);
1096    match &json {
1097        Some(value) => identity_fields(value, "", false, &mut named),
1098        None => pairs("&", body, &mut named),
1099    }
1100    named
1101}
1102
1103/// Whether `text` contains a Google service account's email, an AWS IAM ARN or an Azure managed
1104/// identity's resource ID.
1105fn names_an_identity(text: &str) -> bool {
1106    let text = text.to_ascii_lowercase();
1107    text.contains(".gserviceaccount.com")
1108        || (text.contains("arn:aws") && text.contains(":iam::"))
1109        || text.contains("/providers/microsoft.managedidentity/")
1110}
1111
1112/// Whether a field by this name names the identity a resource acts as, whatever its value.
1113fn identity_field(name: &str) -> bool {
1114    let name = field_key(name);
1115    matches!(
1116        name.as_str(),
1117        "role" | "identity" | "serviceaccount" | "serviceaccountname" | "serviceaccountemail"
1118    ) || name.ends_with("rolearn")
1119        || name.starts_with("iaminstanceprofile")
1120}
1121
1122/// Each identity in `value` with its JSON pointer: a key or string that names one, and the whole
1123/// value of a field named for one. `in_service_accounts` is set under a `serviceAccounts` field,
1124/// whose `email` names the account.
1125fn identity_fields(
1126    value: &serde_json::Value,
1127    pointer: &str,
1128    in_service_accounts: bool,
1129    named: &mut BTreeSet<(String, String)>,
1130) {
1131    match value {
1132        serde_json::Value::String(text) if names_an_identity(text) => {
1133            named.insert((pointer.to_string(), text.clone()));
1134        }
1135        serde_json::Value::Array(items) => {
1136            for (index, item) in items.iter().enumerate() {
1137                let at = format!("{pointer}/{index}");
1138                identity_fields(item, &at, in_service_accounts, named);
1139            }
1140        }
1141        serde_json::Value::Object(fields) => {
1142            // A label or tag may be named `role`, and no cloud reads an identity from a key in a
1143            // labels, tags or annotations map; only a value shaped like an identity counts there.
1144            let free_form = pointer
1145                .rsplit('/')
1146                .next()
1147                .is_some_and(|parent| matches!(parent, "labels" | "tags" | "Tags" | "annotations"));
1148            for (key, field) in fields {
1149                let at = pointer_to(pointer, key);
1150                if names_an_identity(key) {
1151                    named.insert((at.clone(), key.clone()));
1152                }
1153                if !free_form && (identity_field(key) || (in_service_accounts && key == "email")) {
1154                    every_leaf(field, &at, named);
1155                }
1156                let under = key.eq_ignore_ascii_case("serviceaccounts");
1157                identity_fields(field, &at, under, named);
1158            }
1159        }
1160        _ => {}
1161    }
1162}
1163
1164/// Every value in `value` with its JSON pointer, objects and arrays as `{}` and `[]`, so a field
1165/// counts whatever order its keys are written in.
1166fn every_leaf(value: &serde_json::Value, pointer: &str, named: &mut BTreeSet<(String, String)>) {
1167    match value {
1168        serde_json::Value::Object(fields) => {
1169            named.insert((pointer.to_string(), "{}".to_string()));
1170            for (key, field) in fields {
1171                every_leaf(field, &pointer_to(pointer, key), named);
1172            }
1173        }
1174        serde_json::Value::Array(items) => {
1175            named.insert((pointer.to_string(), "[]".to_string()));
1176            for (index, item) in items.iter().enumerate() {
1177                every_leaf(item, &format!("{pointer}/{index}"), named);
1178            }
1179        }
1180        scalar => {
1181            named.insert((pointer.to_string(), scalar.to_string()));
1182        }
1183    }
1184}
1185
1186/// The JSON pointer to `key` in the object at `pointer`.
1187fn pointer_to(pointer: &str, key: &str) -> String {
1188    format!("{pointer}/{}", key.replace('~', "~0").replace('/', "~1"))
1189}
1190
1191/// Whether `changed` differs from `original` in at most labels added to the object's top-level
1192/// `metadata.labels`. A Kubernetes call is signed by an identity that reaches what every
1193/// deployment on the cluster shares, so nothing else of it may change.
1194fn only_labels_changed(original: &HookRequest, changed: &HookRequest) -> bool {
1195    if original.method == changed.method
1196        && original.url == changed.url
1197        && original.headers == changed.headers
1198        && original.body == changed.body
1199    {
1200        return true;
1201    }
1202    type Labels = serde_json::Map<String, serde_json::Value>;
1203    let split = |request: &HookRequest| -> Option<(serde_json::Value, Labels)> {
1204        let mut object = match request.body.as_deref() {
1205            None => return Some((serde_json::Value::Null, Labels::new())),
1206            Some(body) => serde_json::from_str::<serde_json::Value>(body).ok()?,
1207        };
1208        let labels = match object
1209            .get_mut("metadata")
1210            .and_then(|m| m.as_object_mut())
1211            .and_then(|metadata| metadata.remove("labels"))
1212        {
1213            None | Some(serde_json::Value::Null) => Labels::new(),
1214            Some(serde_json::Value::Object(labels))
1215                if labels.values().all(serde_json::Value::is_string) =>
1216            {
1217                labels
1218            }
1219            Some(_) => return None,
1220        };
1221        Some((object, labels))
1222    };
1223    let (Some((before, kept)), Some((after, labels))) = (split(original), split(changed)) else {
1224        return false;
1225    };
1226    // Alien and the cluster select and clean up objects by these labels (`alien.dev/deployment`,
1227    // `kubernetes.io/...`, `managed-by`), so an interceptor adds only other labels and leaves every
1228    // label Alien set as it was.
1229    let reserved = |key: &str| key.contains('/') || key == "managed-by";
1230    original.method == changed.method
1231        && original.url == changed.url
1232        && original.headers == changed.headers
1233        && original.body.is_some() == changed.body.is_some()
1234        && before == after
1235        && kept
1236            .iter()
1237            .all(|(key, value)| labels.get(key) == Some(value))
1238        && labels
1239            .keys()
1240            .all(|key| kept.contains_key(key) || !reserved(key))
1241}
1242
1243/// Whether the request's body, when it has one, is JSON.
1244fn is_json(request: &HookRequest) -> bool {
1245    request
1246        .body
1247        .as_deref()
1248        .is_some_and(|body| serde_json::from_str::<serde_json::Value>(body).is_ok())
1249}
1250
1251/// Every key and string value in `value`.
1252fn json_strings(value: &serde_json::Value, texts: &mut Vec<String>) {
1253    match value {
1254        serde_json::Value::String(text) => texts.push(text.clone()),
1255        serde_json::Value::Array(items) => items.iter().for_each(|item| json_strings(item, texts)),
1256        serde_json::Value::Object(fields) => {
1257            for (key, field) in fields {
1258                texts.push(key.clone());
1259                json_strings(field, texts);
1260            }
1261        }
1262        _ => {}
1263    }
1264}
1265
1266/// The operations an AWS call names: its `Action` parameters, in the query and in a form body in
1267/// any case, and its `X-Amz-Target` headers.
1268fn aws_operations(request: &HookRequest) -> Vec<String> {
1269    let body = request.body.as_deref().unwrap_or_default();
1270    let targets = request
1271        .headers
1272        .get_all("x-amz-target")
1273        .iter()
1274        .map(|value| String::from_utf8_lossy(value.as_bytes()).into_owned());
1275    request
1276        .url
1277        .query_pairs()
1278        .chain(form_urlencoded::parse(body.as_bytes()))
1279        .filter(|(name, _)| name.eq_ignore_ascii_case("action"))
1280        .map(|(_, value)| value.into_owned())
1281        .chain(targets)
1282        .collect()
1283}
1284
1285/// The names of a URL's query parameters, each as often as it appears.
1286fn query_names(request: &HookRequest) -> Vec<String> {
1287    let mut names: Vec<String> = request
1288        .url
1289        .query_pairs()
1290        .map(|(name, _)| name.into_owned())
1291        .collect();
1292    names.sort();
1293    names
1294}
1295
1296/// Hosts of the cloud registries a deployment's images can be pulled from with Alien's grants:
1297/// Amazon ECR in every endpoint form (IPv4, dual-stack, FIPS), Artifact Registry and its `gcr.io`
1298/// hosts, and Azure Container Registry.
1299const CLOUD_REGISTRIES: [&str; 5] = [".dkr.ecr", ".dkr-ecr", "pkg.dev", "gcr.io", ".azurecr."];
1300
1301/// Every reference to an image in a cloud registry that `request` names, lowercase, wherever it
1302/// sits: in the query or the body, in any field, raw and percent-decoded. Alien sets up the
1303/// grants a deployment pulls those images with, so an interceptor may not add or change one.
1304fn registry_images(request: &HookRequest) -> BTreeSet<String> {
1305    let body = request.body.as_deref().unwrap_or_default();
1306    // A changed JSON body is checked as it is sent, written out again, so a host written with a
1307    // `\u` escape is read as the cloud reads it.
1308    let texts = [
1309        body.to_string(),
1310        decoded(body),
1311        decoded(request.url.query().unwrap_or_default()),
1312    ];
1313    texts
1314        .iter()
1315        .flat_map(|text| {
1316            text.split(|c: char| !(c.is_alphanumeric() || "@._:/+-~%".contains(c)))
1317                .map(|token| token.to_lowercase())
1318                .collect::<Vec<_>>()
1319        })
1320        // A reference spelled with a character outside ASCII counts too, whatever it may fold to.
1321        .filter(|token| {
1322            CLOUD_REGISTRIES.iter().any(|host| token.contains(host))
1323                || (!token.is_ascii() && token.contains('.') && token.contains('/'))
1324        })
1325        .collect()
1326}
1327
1328/// Whether an AWS body sets a resource policy: a `Policy` field (KMS, EventBridge), a
1329/// `ResourcePolicy` field (DynamoDB), a `Policy` attribute (SQS, SNS) in JSON, or one named in a
1330/// form.
1331fn sets_a_policy(body: &str) -> bool {
1332    if let Ok(serde_json::Value::Object(fields)) = serde_json::from_str(body) {
1333        return fields.iter().any(|(key, field)| {
1334            key.eq_ignore_ascii_case("Policy")
1335                || key.eq_ignore_ascii_case("ResourcePolicy")
1336                || (key.eq_ignore_ascii_case("Attributes")
1337                    && field.as_object().is_some_and(|attributes| {
1338                        attributes
1339                            .keys()
1340                            .any(|name| name.eq_ignore_ascii_case("Policy"))
1341                    }))
1342        });
1343    }
1344    form_sets_a_policy(body)
1345}
1346
1347/// Whether an API Gateway body writes the API's resource policy: a `policy` field, an OpenAPI
1348/// document's `x-amazon-apigateway-policy`, or a patch to `/policy`, at any depth and in any
1349/// case.
1350fn sets_an_api_policy(body: &str) -> bool {
1351    fn writes(value: &serde_json::Value) -> bool {
1352        match value {
1353            serde_json::Value::Object(fields) => fields.iter().any(|(key, field)| {
1354                matches!(
1355                    key.to_ascii_lowercase().as_str(),
1356                    "policy" | "x-amazon-apigateway-policy"
1357                ) || ((key.eq_ignore_ascii_case("path") || key.eq_ignore_ascii_case("from"))
1358                    && field
1359                        .as_str()
1360                        .is_some_and(|path| path.to_ascii_lowercase().starts_with("/policy")))
1361                    || writes(field)
1362            }),
1363            serde_json::Value::Array(items) => items.iter().any(writes),
1364            _ => false,
1365        }
1366    }
1367    match serde_json::from_str::<serde_json::Value>(body) {
1368        Ok(value) => writes(&value),
1369        // An OpenAPI document may be YAML.
1370        Err(_) => body.to_ascii_lowercase().contains("policy"),
1371    }
1372}
1373
1374/// Whether a form, in a body or a URL's query, names a `Policy` field or attribute.
1375fn form_sets_a_policy(form: &str) -> bool {
1376    form_urlencoded::parse(form.as_bytes()).any(|(name, value)| {
1377        let name = name.to_ascii_lowercase();
1378        name == "policy"
1379            || (value.eq_ignore_ascii_case("Policy")
1380                && (name.ends_with("name") || name.ends_with(".key")))
1381    })
1382}
1383
1384/// Rewrites the headers that describe the body, when the request carries them, so a signature
1385/// never covers a digest of a body that is no longer sent.
1386fn rewrite_body_digests(headers: &mut HeaderMap, body: &[u8]) -> Result<()> {
1387    if headers.contains_key(CONTENT_LENGTH) {
1388        headers.insert(CONTENT_LENGTH, HeaderValue::from(body.len()));
1389    }
1390    let sha256 = format!("{:x}", Sha256::digest(body));
1391    let md5 = base64::engine::general_purpose::STANDARD.encode(md5::compute(body).0);
1392    for (name, digest) in [("x-amz-content-sha256", sha256), ("content-md5", md5)] {
1393        if headers.contains_key(name) {
1394            let value = HeaderValue::try_from(digest).into_alien_error().context(
1395                ErrorData::GenericError {
1396                    message: format!("Failed to write the '{name}' header"),
1397                },
1398            )?;
1399            headers.insert(name, value);
1400        }
1401    }
1402    Ok(())
1403}
1404
1405#[cfg(test)]
1406mod tests {
1407    use super::*;
1408    use crate::testing::TestInterceptor;
1409    use std::sync::Mutex;
1410
1411    fn chain(interceptors: Vec<TestInterceptor>) -> InterceptorChain {
1412        InterceptorChain::new(
1413            interceptors
1414                .into_iter()
1415                .map(|interceptor| Arc::new(interceptor) as Arc<dyn CallInterceptor>)
1416                .collect(),
1417        )
1418    }
1419
1420    fn rds_request(body: &str) -> reqwest::Request {
1421        reqwest::Client::new()
1422            .post("https://rds.us-east-1.amazonaws.com/")
1423            .header("content-type", "application/x-www-form-urlencoded")
1424            .header("content-length", body.len())
1425            .header(
1426                "x-amz-content-sha256",
1427                format!("{:x}", Sha256::digest(body)),
1428            )
1429            .header("content-md5", "stale")
1430            .body(body.to_string())
1431            .build()
1432            .unwrap()
1433    }
1434
1435    fn body_text(request: &reqwest::Request) -> String {
1436        String::from_utf8(request.body().unwrap().as_bytes().unwrap().to_vec()).unwrap()
1437    }
1438
1439    fn assert_fails_naming(error: AlienError<ErrorData>, extension: &str) {
1440        assert_eq!(error.code, "INTERCEPTOR_FAILED", "{error}");
1441        assert!(
1442            !error.retryable,
1443            "an interceptor failure is not retried unless the interceptor says it may pass"
1444        );
1445        assert!(
1446            matches!(&error.error, Some(ErrorData::InterceptorFailed { extension: name, .. }) if name == extension),
1447            "{error}"
1448        );
1449    }
1450
1451    #[test]
1452    fn a_call_no_interceptor_matches_is_left_as_it_was() {
1453        let interceptors = chain(vec![TestInterceptor::new("acme", Cloud::Aws, "s3")
1454            .on_request(|_| panic!("an S3 interceptor never sees an RDS call"))]);
1455        let mut request = reqwest::Client::new()
1456            .put("https://bucket.s3.amazonaws.com/object")
1457            .body(vec![0xff, 0xfe, 0x00])
1458            .build()
1459            .unwrap();
1460        let before = format!("{request:?}");
1461        assert!(interceptors
1462            .intercept(Cloud::Aws, "rds", &mut request)
1463            .unwrap()
1464            .is_none());
1465        assert_eq!(format!("{request:?}"), before);
1466        assert_eq!(
1467            request.body().unwrap().as_bytes(),
1468            Some(&[0xff, 0xfe, 0x00][..])
1469        );
1470    }
1471
1472    /// An interceptor that can't say whether it sees a call, as a hook that traps or runs out of
1473    /// time can't.
1474    struct CannotMatch;
1475
1476    impl CallInterceptor for CannotMatch {
1477        fn extension(&self) -> &str {
1478            "acme"
1479        }
1480
1481        fn matches(&self, _request: &HookRequest) -> Result<bool> {
1482            Err(AlienError::new(ErrorData::GenericError {
1483                message: "the hook ran out of time".to_string(),
1484            }))
1485        }
1486
1487        fn modify_request(&self, _request: &mut HookRequest) -> Result<()> {
1488            panic!("a call the interceptor did not match is never offered to it")
1489        }
1490
1491        fn modify_response(&self, _: &HookRequest, _: &mut HookResponse) -> Result<()> {
1492            panic!("a call the interceptor did not match is never offered to it")
1493        }
1494    }
1495
1496    #[test]
1497    fn an_interceptor_that_cannot_answer_matches_fails_the_call() {
1498        let interceptors = InterceptorChain::new(vec![Arc::new(CannotMatch)]);
1499        let mut text = rds_request("Action=CreateDBCluster");
1500        let error = interceptors
1501            .intercept(Cloud::Aws, "rds", &mut text)
1502            .unwrap_err();
1503        assert_fails_naming(error, "acme");
1504        assert_eq!(body_text(&text), "Action=CreateDBCluster");
1505
1506        let mut binary = reqwest::Client::new()
1507            .put("https://bucket.s3.amazonaws.com/object")
1508            .body(vec![0xff, 0xfe, 0x00])
1509            .build()
1510            .unwrap();
1511        let error = interceptors
1512            .intercept(Cloud::Aws, "s3", &mut binary)
1513            .unwrap_err();
1514        assert_fails_naming(error, "acme");
1515    }
1516
1517    #[test]
1518    fn a_change_of_destination_or_credentials_is_refused() {
1519        let cases: Vec<(&str, fn(&mut HookRequest))> = vec![
1520            ("another host", |r| {
1521                r.url.set_host(Some("evil.example.com")).unwrap()
1522            }),
1523            ("another port", |r| r.url.set_port(Some(8443)).unwrap()),
1524            ("another scheme", |r| r.url.set_scheme("http").unwrap()),
1525            ("a Host header", |r| {
1526                r.headers
1527                    .insert("host", HeaderValue::from_static("evil.example.com"));
1528            }),
1529            ("an Authorization header", |r| {
1530                r.headers
1531                    .insert("authorization", HeaderValue::from_static("Bearer forged"));
1532            }),
1533            ("a session token", |r| {
1534                r.headers
1535                    .insert("x-amz-security-token", HeaderValue::from_static("stolen"));
1536            }),
1537            ("a signing date", |r| {
1538                r.headers
1539                    .insert("x-amz-date", HeaderValue::from_static("20000101T000000Z"));
1540            }),
1541            ("the signing service", |r| r.service = "ec2".to_string()),
1542            ("the cloud", |r| r.cloud = Cloud::Gcp),
1543        ];
1544        for (what, change) in cases {
1545            let interceptors = chain(vec![TestInterceptor::new("acme", Cloud::Aws, "rds")
1546                .on_request(move |r| {
1547                    change(r);
1548                    Ok(())
1549                })]);
1550            let mut request = rds_request("Action=CreateDBCluster");
1551            let error = interceptors
1552                .intercept(Cloud::Aws, "rds", &mut request)
1553                .expect_err(what);
1554            assert_fails_naming(error, "acme");
1555            assert_eq!(
1556                request.url().host_str(),
1557                Some("rds.us-east-1.amazonaws.com")
1558            );
1559        }
1560    }
1561
1562    /// Headers that pick the project billed, the method the server runs or the object an S3 copy
1563    /// reads, add a credential, or set who the call acts as.
1564    #[test]
1565    fn a_header_that_picks_the_project_or_identity_is_refused() {
1566        use reqwest::header::HeaderName;
1567
1568        let cases = [
1569            (
1570                Cloud::Gcp,
1571                "cloudsql",
1572                "https://sqladmin.googleapis.com/v1/projects/p/instances",
1573                "x-goog-user-project",
1574            ),
1575            (
1576                Cloud::Gcp,
1577                "cloudsql",
1578                "https://sqladmin.googleapis.com/v1/projects/p/instances",
1579                "x-goog-api-key",
1580            ),
1581            (
1582                Cloud::Azure,
1583                "management",
1584                "https://management.azure.com/subscriptions/sub",
1585                "x-ms-authorization-auxiliary",
1586            ),
1587            (
1588                Cloud::Gcp,
1589                "cloudsql",
1590                "https://sqladmin.googleapis.com/v1/projects/p/instances",
1591                "X-HTTP-Method-Override",
1592            ),
1593            (
1594                Cloud::Azure,
1595                "management",
1596                "https://management.azure.com/subscriptions/sub",
1597                "X-HTTP-Method",
1598            ),
1599            (
1600                Cloud::Kubernetes,
1601                "kubernetes",
1602                "https://cluster.local/api/v1/namespaces/ns/pods",
1603                "Impersonate-User",
1604            ),
1605            (
1606                Cloud::Kubernetes,
1607                "kubernetes",
1608                "https://cluster.local/api/v1/namespaces/ns/pods",
1609                "Impersonate-Extra-Scopes",
1610            ),
1611            (
1612                Cloud::Aws,
1613                "s3",
1614                "https://bucket.s3.amazonaws.com/copy",
1615                "x-amz-copy-source",
1616            ),
1617        ];
1618        for (cloud, service, url, name) in cases {
1619            let header = HeaderName::from_bytes(name.as_bytes()).unwrap();
1620            for already_sent in [false, true] {
1621                let set = header.clone();
1622                let interceptors = chain(vec![TestInterceptor::new("acme", cloud, service)
1623                    .on_request(move |r| {
1624                        r.headers
1625                            .insert(set.clone(), HeaderValue::from_static("other"));
1626                        Ok(())
1627                    })]);
1628                let mut request = reqwest::Client::new().get(url);
1629                if already_sent {
1630                    request = request.header(header.clone(), "original");
1631                }
1632                let mut request = request.build().unwrap();
1633                let error = interceptors
1634                    .intercept(cloud, service, &mut request)
1635                    .expect_err(name);
1636                assert_fails_naming(error, "acme");
1637                assert_eq!(
1638                    request.headers().get(&header).is_some(),
1639                    already_sent,
1640                    "{name}"
1641                );
1642            }
1643        }
1644    }
1645
1646    /// Google Cloud reads the project billed, an API key, a credential and the body's or
1647    /// response's format from these parameters, in any case.
1648    #[test]
1649    fn a_query_parameter_that_picks_the_project_billed_or_an_api_key_is_refused() {
1650        let url = "https://storage.googleapis.com/storage/v1/b/bucket/o?userProject=the-project";
1651        for (what, change) in [
1652            ("added", "userProject=the-project&userProject=other"),
1653            ("changed", "userProject=other"),
1654            ("removed", "prefix=a"),
1655            (
1656                "added in another case",
1657                "userProject=the-project&USERPROJECT=other",
1658            ),
1659            (
1660                "added with a $",
1661                "userProject=the-project&%24userProject=other",
1662            ),
1663            ("an API key", "userProject=the-project&key=other"),
1664            ("an API key with a $", "userProject=the-project&$Key=other"),
1665            (
1666                "an access token",
1667                "userProject=the-project&access_token=other",
1668            ),
1669            (
1670                "an OAuth token",
1671                "userProject=the-project&oauth_token=other",
1672            ),
1673            (
1674                "a bearer token",
1675                "userProject=the-project&bearer_token=other",
1676            ),
1677            ("a response format", "userProject=the-project&alt=media"),
1678            (
1679                "a content type for the body",
1680                "userProject=the-project&%24ct=application%2Fjson%2Bprotobuf",
1681            ),
1682            (
1683                "another system parameter",
1684                "userProject=the-project&$Fields=name",
1685            ),
1686        ] {
1687            let interceptors = chain(vec![TestInterceptor::new("acme", Cloud::Gcp, "storage")
1688                .on_request(move |r| {
1689                    r.url.set_query(Some(change));
1690                    Ok(())
1691                })]);
1692            let mut request = reqwest::Client::new().get(url).build().unwrap();
1693            let error = interceptors
1694                .intercept(Cloud::Gcp, "storage", &mut request)
1695                .expect_err(what);
1696            assert_fails_naming(error, "acme");
1697            assert_eq!(request.url().as_str(), url, "{what}");
1698        }
1699
1700        // Every other parameter can change, as can these on another cloud's call.
1701        for (cloud, service, url, query) in [
1702            (
1703                Cloud::Gcp,
1704                "storage",
1705                url,
1706                "prefix=a&userProject=the-project",
1707            ),
1708            (
1709                Cloud::Aws,
1710                "rds",
1711                "https://rds.us-east-1.amazonaws.com/?key=x&userProject=y",
1712                "key=a&userProject=b",
1713            ),
1714        ] {
1715            let interceptors = chain(vec![TestInterceptor::new("acme", cloud, service)
1716                .on_request(move |r| {
1717                    r.url.set_query(Some(query));
1718                    Ok(())
1719                })]);
1720            let mut request = reqwest::Client::new().get(url).build().unwrap();
1721            interceptors
1722                .intercept(cloud, service, &mut request)
1723                .unwrap()
1724                .expect("the interceptor matched");
1725            assert_eq!(request.url().query(), Some(query));
1726        }
1727    }
1728
1729    #[test]
1730    fn a_query_value_and_other_headers_can_change() {
1731        let interceptors = chain(vec![TestInterceptor::new("acme", Cloud::Aws, "rds")
1732            .on_request(|r| {
1733                r.url.set_query(Some("extension=1"));
1734                r.headers
1735                    .insert("x-extension", HeaderValue::from_static("acme"));
1736                Ok(())
1737            })]);
1738        let mut request = rds_request("Action=CreateDBCluster");
1739        request.url_mut().set_query(Some("extension=0"));
1740        interceptors
1741            .intercept(Cloud::Aws, "rds", &mut request)
1742            .unwrap()
1743            .expect("the interceptor matched");
1744        assert_eq!(
1745            request.url().as_str(),
1746            "https://rds.us-east-1.amazonaws.com/?extension=1"
1747        );
1748        assert_eq!(request.method(), Method::POST);
1749        assert_eq!(request.headers()["x-extension"], "acme");
1750        assert_eq!(body_text(&request), "Action=CreateDBCluster");
1751    }
1752
1753    /// A request `(cloud, service, method, url, headers, body)` as Alien builds it.
1754    type Built = (
1755        Cloud,
1756        &'static str,
1757        Method,
1758        &'static str,
1759        &'static [(&'static str, &'static str)],
1760        Option<&'static str>,
1761    );
1762
1763    fn build((_, _, method, url, headers, body): &Built) -> reqwest::Request {
1764        let mut builder = reqwest::Client::new().request(method.clone(), *url);
1765        for (name, value) in *headers {
1766            builder = builder.header(*name, *value);
1767        }
1768        if let Some(body) = body {
1769            builder = builder.body(*body);
1770        }
1771        builder.build().unwrap()
1772    }
1773
1774    /// Runs `change` on `built` and expects the chain to refuse it before anything is sent.
1775    fn assert_change_refused(what: &str, built: Built, change: fn(&mut HookRequest)) {
1776        assert_change_refused_because(what, built, "", change)
1777    }
1778
1779    /// Like `assert_change_refused`, and the refusal's reason must contain `reason`.
1780    fn assert_change_refused_because(
1781        what: &str,
1782        built: Built,
1783        reason: &str,
1784        change: fn(&mut HookRequest),
1785    ) {
1786        let (cloud, service) = (built.0, built.1);
1787        let interceptors = chain(vec![TestInterceptor::new("acme", cloud, service)
1788            .on_request(move |r| {
1789                change(r);
1790                Ok(())
1791            })]);
1792        let mut request = build(&built);
1793        let before = format!("{request:?}");
1794        let error = interceptors
1795            .intercept(cloud, service, &mut request)
1796            .expect_err(what);
1797        assert_fails_naming(error.clone(), "acme");
1798        assert!(
1799            matches!(&error.error, Some(ErrorData::InterceptorFailed { message, .. }) if message.contains(reason)),
1800            "{what}: the reason should contain {reason:?}: {error}"
1801        );
1802        assert_eq!(format!("{request:?}"), before, "{what}");
1803    }
1804
1805    const CLOUD_RUN_SERVICE: Built = (
1806        Cloud::Gcp,
1807        "cloudrun",
1808        Method::PATCH,
1809        "https://run.googleapis.com/v2/projects/p/locations/l/services/web",
1810        &[("content-type", "application/json")],
1811        Some(r#"{"labels":{"team":"a"}}"#),
1812    );
1813
1814    /// An image in a cloud registry stays as Alien named it, however the change names one; an
1815    /// image from a public registry may be added.
1816    #[test]
1817    fn an_image_in_a_cloud_registry_is_never_added_or_changed() {
1818        const FUNCTION: Built = (
1819            Cloud::Aws,
1820            "lambda",
1821            Method::POST,
1822            "https://lambda.us-east-1.amazonaws.com/2015-03-31/functions",
1823            &[("content-type", "application/json")],
1824            Some(
1825                r#"{"FunctionName":"f","Code":{"ImageUri":"1.dkr.ecr.us-east-1.amazonaws.com/artifacts-a@sha256:00"}}"#,
1826            ),
1827        );
1828        const SERVICE: Built = (
1829            Cloud::Gcp,
1830            "run",
1831            Method::POST,
1832            "https://run.googleapis.com/v2/projects/p/locations/l/services",
1833            &[("content-type", "application/json")],
1834            Some(
1835                r#"{"template":{"containers":[{"image":"us-docker.pkg.dev/m/artifacts-a/web:1"}]}}"#,
1836            ),
1837        );
1838        const TEMPLATE: Built = (
1839            Cloud::Gcp,
1840            "aiplatform",
1841            Method::POST,
1842            "https://us-central1-aiplatform.googleapis.com/v1beta1/projects/p/locations/l/templates",
1843            &[("content-type", "application/json")],
1844            Some(r#"{"spec":{"imageUri":"docker.io/library/python:3.12"}}"#),
1845        );
1846        const SETTINGS: Built = (
1847            Cloud::Aws,
1848            "ssm",
1849            Method::POST,
1850            "https://ssm.us-east-1.amazonaws.com/",
1851            &[
1852                ("content-type", "application/x-amz-json-1.1"),
1853                ("x-amz-target", "AmazonSSM.PutParameter"),
1854            ],
1855            Some(r#"{"value":"REGISTRY=1.dkr.ecr.us-east-1.amazonaws.com/r:1,TAG=1"}"#),
1856        );
1857        let refused: [(&str, Built, fn(&mut HookRequest)); 11] = [
1858            (
1859                "a registry host with a character outside ASCII",
1860                FUNCTION,
1861                |r| {
1862                    r.body = Some(
1863                    "{\"FunctionName\":\"f\",\"Code\":{\"ImageUri\":\"1.d\u{212a}r.ecr.us-east-1.amazonaws.com/artifacts-b:1\"}}"
1864                        .into(),
1865                )
1866                },
1867            ),
1868            ("a FIPS registry host", FUNCTION, |r| {
1869                r.body = Some(
1870                    r#"{"FunctionName":"f","Code":{"ImageUri":"1.dkr.ecr-fips.us-east-1.amazonaws.com/artifacts-b:1"}}"#
1871                        .into(),
1872                )
1873            }),
1874            ("a dual-stack FIPS registry host", FUNCTION, |r| {
1875                r.body = Some(
1876                    r#"{"FunctionName":"f","Code":{"ImageUri":"1.dkr-ecr-fips.us-east-1.on.aws/artifacts-b:1"}}"#
1877                        .into(),
1878                )
1879            }),
1880            ("a gcr.io host", SERVICE, |r| {
1881                r.body = Some(
1882                    r#"{"template":{"containers":[{"image":"us-docker.pkg.dev/m/artifacts-a/web:1"},{"image":"us.gcr.io/m/artifacts-b:1"}]}}"#
1883                        .into(),
1884                )
1885            }),
1886            ("a regional Artifact Registry host", SERVICE, |r| {
1887                r.body = Some(
1888                    r#"{"template":{"containers":[{"image":"docker.us-east1.rep.pkg.dev/m/artifacts-b/web:1"}]}}"#
1889                        .into(),
1890                )
1891            }),
1892            ("another repository", FUNCTION, |r| {
1893                r.body = Some(
1894                    r#"{"FunctionName":"f","Code":{"ImageUri":"1.dkr.ecr.us-east-1.amazonaws.com/artifacts-b:latest"}}"#
1895                        .into(),
1896                )
1897            }),
1898            ("another tag of the same repository", FUNCTION, |r| {
1899                r.body = Some(
1900                    r#"{"FunctionName":"f","Code":{"ImageUri":"1.dkr.ecr.us-east-1.amazonaws.com/artifacts-a:v2"}}"#
1901                        .into(),
1902                )
1903            }),
1904            (
1905                "the registry host in another case and with a port",
1906                FUNCTION,
1907                |r| {
1908                    r.body = Some(
1909                    r#"{"FunctionName":"f","Code":{"ImageUri":"1.DKR.ECR.us-east-1.amazonaws.com:443/artifacts-b:1"}}"#
1910                        .into(),
1911                )
1912                },
1913            ),
1914            ("a second container from the same registry", SERVICE, |r| {
1915                r.body = Some(
1916                    r#"{"template":{"containers":[{"image":"us-docker.pkg.dev/m/artifacts-a/web:1"},{"image":"us-docker.pkg.dev/m/artifacts-b/web:1"}]}}"#
1917                        .into(),
1918                )
1919            }),
1920            (
1921                "a cloud registry's image in a field of another name",
1922                TEMPLATE,
1923                |r| {
1924                    r.body = Some(
1925                    r#"{"spec":{"image_uri":"us-central1-docker.pkg.dev/m/artifacts-b/sandbox:1"}}"#
1926                        .into(),
1927                )
1928                },
1929            ),
1930            (
1931                "a cloud registry's image where the call named a public one",
1932                TEMPLATE,
1933                |r| {
1934                    r.body = Some(
1935                    r#"{"spec":{"imageUri":"us-central1-docker.pkg.dev/m/artifacts-b/sandbox:1"}}"#
1936                        .into(),
1937                )
1938                },
1939            ),
1940        ];
1941        for (what, built, change) in refused {
1942            assert_change_refused(what, built, change);
1943        }
1944        let sent: [(&str, Built, fn(&mut HookRequest)); 3] = [
1945            ("a setting beside an image in one string", SETTINGS, |r| {
1946                r.body = Some(
1947                    r#"{"value":"REGISTRY=1.dkr.ecr.us-east-1.amazonaws.com/r:1,TAG=2"}"#.into(),
1948                )
1949            }),
1950            ("another field beside the image", FUNCTION, |r| {
1951                r.body = Some(
1952                    r#"{"FunctionName":"f","Code":{"ImageUri":"1.dkr.ecr.us-east-1.amazonaws.com/artifacts-a@sha256:00"},"Description":"d"}"#
1953                        .into(),
1954                )
1955            }),
1956            ("a sidecar from a public registry", SERVICE, |r| {
1957                r.body = Some(
1958                    r#"{"template":{"containers":[{"image":"us-docker.pkg.dev/m/artifacts-a/web:1"},{"image":"ghcr.io/vendor/agent:1"}]}}"#
1959                        .into(),
1960                )
1961            }),
1962        ];
1963        for (what, built, change) in sent {
1964            assert_change_sent(what, built, change);
1965        }
1966    }
1967
1968    /// The method and the path say which resource a call acts on and what it does to it.
1969    #[test]
1970    fn a_change_of_method_or_path_is_refused() {
1971        let cases: [(&str, fn(&mut HookRequest)); 4] = [
1972            ("another method", |r| r.method = Method::DELETE),
1973            ("a sibling service", |r| {
1974                r.url
1975                    .set_path("/v2/projects/p/locations/l/services/billing")
1976            }),
1977            ("a trailing slash", |r| {
1978                r.url.set_path("/v2/projects/p/locations/l/services/web/")
1979            }),
1980            ("another project", |r| {
1981                r.url.set_path("/v2/projects/q/locations/l/services/web")
1982            }),
1983        ];
1984        for (what, change) in cases {
1985            assert_change_refused(what, CLOUD_RUN_SERVICE, change);
1986        }
1987    }
1988
1989    /// Which identity a call names decides who the resource acts as, wherever the name sits.
1990    #[test]
1991    fn a_change_to_the_identity_a_call_names_is_refused() {
1992        const LAMBDA: Built = (
1993            Cloud::Aws,
1994            "lambda",
1995            Method::PUT,
1996            "https://lambda.us-east-1.amazonaws.com/2015-03-31/functions/fn/configuration",
1997            &[("content-type", "application/json")],
1998            Some(r#"{"Role":"arn:aws:iam::111111111111:role/app-fn","Timeout":30}"#),
1999        );
2000        const APP: Built = (
2001            Cloud::Azure,
2002            "management",
2003            Method::PUT,
2004            "https://management.azure.com/subscriptions/s/resourceGroups/rg/providers/Microsoft.App/containerApps/web",
2005            &[("content-type", "application/json")],
2006            Some(r#"{"location":"eastus"}"#),
2007        );
2008        let cases: [(&str, Built, fn(&mut HookRequest)); 8] = [
2009            ("a body that is no longer JSON", LAMBDA, |r| {
2010                r.body = Some("Role: arn:aws:iam::111111111111:role/admin\n".into())
2011            }),
2012            ("a body no JSON parser reads alike", LAMBDA, |r| {
2013                r.body = Some(
2014                    r#"{"Description":"\ud800","Role":"arn:aws:iam::111111111111:role/admin","Timeout":30}"#
2015                        .into(),
2016                )
2017            }),
2018            ("another content type", LAMBDA, |r| {
2019                r.headers
2020                    .insert("content-type", HeaderValue::from_static("application/yaml"));
2021            }),
2022            ("an escaped role", LAMBDA, |r| {
2023                r.body = Some(
2024                    r#"{"Role":"\u0061rn:aws:iam::111111111111:role/admin","Description":"arn:aws:iam::111111111111:role/app-fn","Timeout":30}"#
2025                        .into(),
2026                )
2027            }),
2028            ("another service account", CLOUD_RUN_SERVICE, |r| {
2029                r.body = Some(
2030                    r#"{"labels":{"team":"a"},"template":{"serviceAccount":"other@p.iam.gserviceaccount.com"}}"#
2031                        .into(),
2032                )
2033            }),
2034            ("another role", LAMBDA, |r| {
2035                r.body =
2036                    Some(r#"{"Role":"arn:aws:iam::111111111111:role/admin","Timeout":30}"#.into())
2037            }),
2038            ("no role", LAMBDA, |r| {
2039                r.body = Some(r#"{"Timeout":30}"#.into())
2040            }),
2041            ("a managed identity added", APP, |r| {
2042                r.body = Some(
2043                    r#"{"location":"eastus","identity":{"type":"UserAssigned","userAssignedIdentities":{"/subscriptions/s/resourceGroups/other/providers/Microsoft.ManagedIdentity/userAssignedIdentities/admin":{}}}}"#
2044                        .into(),
2045                )
2046            }),
2047        ];
2048        for (what, built, change) in cases {
2049            assert_change_refused(what, built, change);
2050        }
2051    }
2052
2053    const LAUNCH_TEMPLATE: Built = (
2054        Cloud::Aws,
2055        "ec2",
2056        Method::POST,
2057        "https://ec2.us-east-1.amazonaws.com/",
2058        &[("content-type", "application/x-www-form-urlencoded")],
2059        Some("Action=CreateLaunchTemplate&LaunchTemplateName=web&LaunchTemplateData.IamInstanceProfile.Arn=arn%3Aaws%3Aiam%3A%3A111111111111%3Ainstance-profile%2Fweb&LaunchTemplateData.IamInstanceProfile.Name=web"),
2060    );
2061
2062    const CLOUD_RUN_AS_APP: Built = (
2063        Cloud::Gcp,
2064        "cloudrun",
2065        Method::PATCH,
2066        "https://run.googleapis.com/v2/projects/p/locations/l/services/web",
2067        &[("content-type", "application/json")],
2068        Some(
2069            r#"{"labels":{"team":"a"},"template":{"serviceAccount":"app@p.iam.gserviceaccount.com"}}"#,
2070        ),
2071    );
2072
2073    const INSTANCE_AS_APP: Built = (
2074        Cloud::Gcp,
2075        "compute",
2076        Method::POST,
2077        "https://compute.googleapis.com/compute/v1/projects/p/zones/z/instances",
2078        &[("content-type", "application/json")],
2079        Some(
2080            r#"{"name":"web","description":"","serviceAccounts":[{"email":"app@p.iam.gserviceaccount.com","scopes":[]}]}"#,
2081        ),
2082    );
2083
2084    /// An identity is compared where it sits: a form value is read by its key, and a name moved
2085    /// to another field no longer names the identity the call acts as.
2086    #[test]
2087    fn an_identity_is_compared_where_the_call_names_it() {
2088        let cases: [(&str, Built, fn(&mut HookRequest)); 5] = [
2089            (
2090                "another instance profile ARN in a form",
2091                LAUNCH_TEMPLATE,
2092                |r| {
2093                    r.body = Some(
2094                        LAUNCH_TEMPLATE
2095                            .5
2096                            .unwrap()
2097                            .replace("profile%2Fweb", "profile%2Fadmin"),
2098                    )
2099                },
2100            ),
2101            (
2102                "another instance profile name in a form",
2103                LAUNCH_TEMPLATE,
2104                |r| {
2105                    r.body = Some(
2106                        LAUNCH_TEMPLATE
2107                            .5
2108                            .unwrap()
2109                            .replace("Profile.Name=web", "Profile.Name=admin"),
2110                    )
2111                },
2112            ),
2113            (
2114                "an instance profile ARN in the query",
2115                LAUNCH_TEMPLATE,
2116                |r| {
2117                    r.url
2118                        .set_query(Some("RoleArn=arn:aws:iam::111111111111:role/admin"))
2119                },
2120            ),
2121            (
2122                "a service account dropped and kept in a label",
2123                CLOUD_RUN_AS_APP,
2124                |r| {
2125                    r.body = Some(
2126                    r#"{"labels":{"team":"a","sa":"app@p.iam.gserviceaccount.com"},"template":{}}"#
2127                        .into(),
2128                )
2129                },
2130            ),
2131            (
2132                "a service account replaced and kept in the description",
2133                INSTANCE_AS_APP,
2134                |r| {
2135                    r.body = Some(
2136                    r#"{"name":"web","description":"app@p.iam.gserviceaccount.com","serviceAccounts":[{"email":"default","scopes":[]}]}"#
2137                        .into(),
2138                )
2139                },
2140            ),
2141        ];
2142        for (what, built, change) in cases {
2143            assert_change_refused(what, built, change);
2144        }
2145    }
2146
2147    /// Runs `change` on `built` and expects the chain to send the changed call.
2148    fn assert_change_sent(what: &str, built: Built, change: fn(&mut HookRequest)) {
2149        let (cloud, service) = (built.0, built.1);
2150        let interceptors = chain(vec![TestInterceptor::new("acme", cloud, service)
2151            .on_request(move |r| {
2152                change(r);
2153                Ok(())
2154            })]);
2155        let mut request = build(&built);
2156        interceptors
2157            .intercept(cloud, service, &mut request)
2158            .unwrap_or_else(|error| panic!("{what}: {error}"))
2159            .expect("the interceptor matched");
2160        assert_ne!(Some(body_text(&request).as_str()), built.5, "{what}");
2161    }
2162
2163    #[test]
2164    fn a_change_that_keeps_every_identity_where_it_was_is_sent() {
2165        const APP_AS_APP: Built = (
2166            Cloud::Azure,
2167            "management",
2168            Method::PUT,
2169            "https://management.azure.com/subscriptions/s/resourceGroups/rg/providers/Microsoft.App/containerApps/web",
2170            &[("content-type", "application/json")],
2171            Some(r#"{"location":"eastus","identity":{"type":"UserAssigned","userAssignedIdentities":{"/subscriptions/s/resourceGroups/rg/providers/Microsoft.ManagedIdentity/userAssignedIdentities/app":{}}}}"#),
2172        );
2173        let cases: [(&str, Built, fn(&mut HookRequest)); 4] = [
2174            (
2175                "a tag on a container app, its identity's keys written in another order",
2176                APP_AS_APP,
2177                |r| {
2178                    r.body = Some(
2179                    r#"{"tags":{"team":"a"},"identity":{"userAssignedIdentities":{"/subscriptions/s/resourceGroups/rg/providers/Microsoft.ManagedIdentity/userAssignedIdentities/app":{}},"type":"UserAssigned"},"location":"eastus"}"#
2180                        .into(),
2181                )
2182                },
2183            ),
2184            ("a tag on a launch template", LAUNCH_TEMPLATE, |r| {
2185                r.body.as_mut().unwrap().push_str(
2186                    "&TagSpecification.1.ResourceType=launch-template&TagSpecification.1.Tag.1.Key=team&TagSpecification.1.Tag.1.Value=a",
2187                )
2188            }),
2189            ("a label on a Cloud Run service", CLOUD_RUN_AS_APP, |r| {
2190                r.body = Some(
2191                    r#"{"labels":{"team":"b"},"template":{"serviceAccount":"app@p.iam.gserviceaccount.com"}}"#
2192                        .into(),
2193                )
2194            }),
2195            ("a description on an instance", INSTANCE_AS_APP, |r| {
2196                r.body = Some(
2197                    r#"{"name":"web","description":"web tier","serviceAccounts":[{"email":"app@p.iam.gserviceaccount.com","scopes":[]}]}"#
2198                        .into(),
2199                )
2200            }),
2201        ];
2202        for (what, built, change) in cases {
2203            assert_change_sent(what, built, change);
2204        }
2205    }
2206
2207    const DEPLOYMENT: Built = (
2208        Cloud::Kubernetes,
2209        "kubernetes",
2210        Method::POST,
2211        "https://cluster.example.com/apis/apps/v1/namespaces/app/deployments",
2212        &[("content-type", "application/json")],
2213        Some(
2214            r#"{"metadata":{"name":"web","labels":{"alien.dev/deployment":"d1"}},"spec":{"template":{"spec":{"containers":[{"name":"main","image":"web","securityContext":{"runAsNonRoot":true}}],"volumes":[{"name":"data","emptyDir":{}}]}}}}"#,
2215        ),
2216    );
2217
2218    /// On Kubernetes an interceptor adds or changes the object's labels, and nothing else: the
2219    /// cluster's shared parts (ingress hosts, runtime classes, nodes) read the rest.
2220    #[test]
2221    fn a_kubernetes_interceptor_changes_only_the_object_s_labels() {
2222        assert_change_sent("a label", DEPLOYMENT, |r| {
2223            let mut value: serde_json::Value =
2224                serde_json::from_str(r.body.as_deref().unwrap()).unwrap();
2225            value["metadata"]["labels"]["team"] = "a".into();
2226            value["metadata"]["labels"]["role"] = "frontend".into();
2227            r.body = Some(value.to_string());
2228        });
2229        fn edit(r: &mut HookRequest, change: fn(&mut serde_json::Value)) {
2230            let mut value: serde_json::Value =
2231                serde_json::from_str(r.body.as_deref().unwrap()).unwrap();
2232            change(&mut value);
2233            r.body = Some(value.to_string());
2234        }
2235        let cases: [(&str, fn(&mut HookRequest)); 12] = [
2236            ("a sidecar", |r| {
2237                edit(r, |object| {
2238                    object["spec"]["template"]["spec"]["containers"]
2239                        .as_array_mut()
2240                        .unwrap()
2241                        .insert(0, serde_json::json!({"name":"agent","image":"agent"}))
2242                })
2243            }),
2244            ("an annotation", |r| {
2245                edit(
2246                    r,
2247                    |object| {
2248                        object["metadata"]["annotations"] =
2249                            serde_json::json!({"nginx.ingress.kubernetes.io/server-snippet": "x"})
2250                    },
2251                )
2252            }),
2253            ("a runtime class", |r| {
2254                edit(r, |object| {
2255                    object["spec"]["template"]["spec"]["runtimeClassName"] = "runc".into()
2256                })
2257            }),
2258            ("a label with a prefix", |r| {
2259                edit(r, |object| {
2260                    object["metadata"]["labels"]["alien.dev/resource"] = "other".into()
2261                })
2262            }),
2263            ("a label Alien set, changed", |r| {
2264                edit(r, |object| {
2265                    object["metadata"]["labels"]["alien.dev/deployment"] = "d2".into()
2266                })
2267            }),
2268            ("a label Alien set, removed", |r| {
2269                edit(r, |object| {
2270                    object["metadata"]["labels"] = serde_json::json!({})
2271                })
2272            }),
2273            ("a managed-by label", |r| {
2274                edit(r, |object| {
2275                    object["metadata"]["labels"]["managed-by"] = "acme".into()
2276                })
2277            }),
2278            ("a header", |r| {
2279                r.headers
2280                    .insert("x-extension", HeaderValue::from_static("acme"));
2281            }),
2282            ("another method", |r| r.method = Method::PUT),
2283            ("a label that is not text", |r| {
2284                edit(r, |object| {
2285                    object["metadata"]["labels"] = serde_json::json!({"a": 1})
2286                })
2287            }),
2288            ("a label on the pod template", |r| {
2289                edit(r, |object| {
2290                    object["spec"]["template"]["metadata"] =
2291                        serde_json::json!({"labels": {"a": "b"}})
2292                })
2293            }),
2294            ("a query parameter", |r| r.url.set_query(Some("dryRun=All"))),
2295        ];
2296        for (what, change) in cases {
2297            assert_change_refused(what, DEPLOYMENT, change);
2298        }
2299    }
2300
2301    /// Each check reads the body as its protocol reads it, so a body may not change format: a
2302    /// form body turned into a JSON string would be checked as a form and sent decoded.
2303    #[test]
2304    fn a_body_that_changes_format_is_refused_saying_so() {
2305        const SQS: Built = (
2306            Cloud::Aws,
2307            "sqs",
2308            Method::POST,
2309            "https://sqs.us-east-1.amazonaws.com/",
2310            &[("content-type", "application/x-www-form-urlencoded")],
2311            Some("Action=CreateQueue&Version=2012-11-05&QueueName=q"),
2312        );
2313        const APP: Built = (
2314            Cloud::Azure,
2315            "management",
2316            Method::PUT,
2317            "https://management.azure.com/subscriptions/s/resourceGroups/rg/providers/Microsoft.App/containerApps/web",
2318            &[("content-type", "application/json")],
2319            Some(r#"{"location":"eastus"}"#),
2320        );
2321        const BODYLESS_SQS: Built = (
2322            Cloud::Aws,
2323            "sqs",
2324            Method::POST,
2325            "https://sqs.us-east-1.amazonaws.com/",
2326            &[("content-type", "application/x-www-form-urlencoded")],
2327            None,
2328        );
2329        let cases: [(&str, Built, fn(&mut HookRequest), &str); 5] = [
2330            (
2331                "an escaped form added to a call with no body",
2332                BODYLESS_SQS,
2333                |r| r.body = Some(r#""x\u0026Action\u003dAddPermission\u0026Label\u003dl""#.into()),
2334                "changes who has access",
2335            ),
2336            (
2337                "a policy as a form inside a JSON object added to a call with no body",
2338                BODYLESS_SQS,
2339                |r| {
2340                    r.body = Some(
2341                        r#"{"a":"x&Attribute.1.Name=Policy&Attribute.1.Value=%7B%7D&y="}"#.into(),
2342                    )
2343                },
2344                "added a body",
2345            ),
2346            (
2347                "an identity as a form inside a JSON string added to a call with no body",
2348                BODYLESS_SQS,
2349                |r| r.body = Some(r#""x&IamInstanceProfile.Name=admin&y=""#.into()),
2350                "added a body",
2351            ),
2352            (
2353                "a form body turned into a JSON string",
2354                SQS,
2355                |r| {
2356                    r.body = Some(
2357                        r#""Action=CreateQueue&Version=2012-11-05&QueueName=q&Attribute.1.Name\u003dPolicy""#
2358                            .into(),
2359                    )
2360                },
2361                "not JSON into JSON",
2362            ),
2363            (
2364                "a JSON body turned into text",
2365                APP,
2366                |r| r.body = Some("location: eastus\n".into()),
2367                "into one that is not JSON",
2368            ),
2369        ];
2370        for (what, built, change, reason) in cases {
2371            let (cloud, service) = (built.0, built.1);
2372            let interceptors = chain(vec![TestInterceptor::new("acme", cloud, service)
2373                .on_request(move |r| {
2374                    change(r);
2375                    Ok(())
2376                })]);
2377            let mut request = build(&built);
2378            let error = interceptors
2379                .intercept(cloud, service, &mut request)
2380                .expect_err(what);
2381            assert!(!error.retryable, "{what}");
2382            assert!(format!("{error:?}").contains(reason), "{what}: {error:?}");
2383        }
2384    }
2385
2386    /// The body sent is the one the checks read, so a key written twice can't carry a change
2387    /// a cloud's parser would merge in.
2388    #[test]
2389    fn a_json_body_is_sent_as_it_was_checked() {
2390        let interceptors = chain(vec![TestInterceptor::new("acme", Cloud::Gcp, "cloudrun")
2391            .on_request(|r| {
2392                r.body = Some(r#"{"labels":{"team":"a"},"labels":{"team":"b"}}"#.to_string());
2393                Ok(())
2394            })]);
2395        let mut request = build(&CLOUD_RUN_SERVICE);
2396        interceptors
2397            .intercept(Cloud::Gcp, "cloudrun", &mut request)
2398            .unwrap()
2399            .expect("the interceptor matched");
2400        assert_eq!(body_text(&request), r#"{"labels":{"team":"b"}}"#);
2401    }
2402
2403    /// On AWS's query and JSON protocols the operation is a body or query parameter, or a
2404    /// header, not the path.
2405    #[test]
2406    fn a_change_of_the_aws_operation_is_refused() {
2407        const RDS: Built = (
2408            Cloud::Aws,
2409            "rds",
2410            Method::POST,
2411            "https://rds.us-east-1.amazonaws.com/",
2412            &[("content-type", "application/x-www-form-urlencoded")],
2413            Some("Action=ModifyDBCluster&Version=2014-10-31&DBClusterIdentifier=db"),
2414        );
2415        const KMS: Built = (
2416            Cloud::Aws,
2417            "kms",
2418            Method::POST,
2419            "https://kms.us-east-1.amazonaws.com/",
2420            &[
2421                ("content-type", "application/x-amz-json-1.1"),
2422                ("x-amz-target", "TrentService.DescribeKey"),
2423            ],
2424            Some(r#"{"KeyId":"k"}"#),
2425        );
2426        const TAGGING: Built = (
2427            Cloud::Aws,
2428            "s3",
2429            Method::PUT,
2430            "https://bucket.s3.amazonaws.com/?tagging",
2431            &[("content-type", "application/xml")],
2432            Some("<Tagging><TagSet/></Tagging>"),
2433        );
2434        const CREATE_API: Built = (
2435            Cloud::Aws,
2436            "apigateway",
2437            Method::POST,
2438            "https://apigateway.us-east-1.amazonaws.com/restapis",
2439            &[("content-type", "application/json")],
2440            Some(r#"{"name":"api"}"#),
2441        );
2442        let cases: [(&str, Built, fn(&mut HookRequest)); 10] = [
2443            ("a query parameter added to a query API's call", RDS, |r| {
2444                r.url.set_query(Some("Tags.Tag.1.Key=a"))
2445            }),
2446            ("an API created by importing a document", CREATE_API, |r| {
2447                r.url.set_query(Some("mode=import"))
2448            }),
2449            ("another Action in the body", RDS, |r| {
2450                r.body = Some("Action=DeleteDBCluster&Version=2014-10-31".into())
2451            }),
2452            ("a second Action in the body", RDS, |r| {
2453                r.body.as_mut().unwrap().push_str("&Action=DeleteDBCluster")
2454            }),
2455            ("an Action in the query", RDS, |r| {
2456                r.url.set_query(Some("Action=DeleteDBCluster"))
2457            }),
2458            (
2459                "an S3 subresource that sends the bucket's logs elsewhere",
2460                TAGGING,
2461                |r| r.url.set_query(Some("logging")),
2462            ),
2463            (
2464                "an S3 subresource added beside the call's own",
2465                TAGGING,
2466                |r| r.url.set_query(Some("tagging&replication")),
2467            ),
2468            ("an S3 subresource removed", TAGGING, |r| {
2469                r.url.set_query(None)
2470            }),
2471            ("another target", KMS, |r| {
2472                r.headers.insert(
2473                    "x-amz-target",
2474                    HeaderValue::from_static("TrentService.ScheduleKeyDeletion"),
2475                );
2476            }),
2477            ("a form body on a JSON service", KMS, |r| {
2478                r.headers.remove("x-amz-target");
2479                r.body = Some("Action=ScheduleKeyDeletion&KeyId=k".into());
2480            }),
2481        ];
2482        for (what, built, change) in cases {
2483            assert_change_refused(what, built, change);
2484        }
2485    }
2486
2487    /// A query parameter, a header or a body field can turn a call on the deployment's own
2488    /// resource into one that changes who has access to it.
2489    #[test]
2490    fn a_call_turned_into_one_that_changes_access_is_refused() {
2491        const CREATE_BUCKET: Built = (
2492            Cloud::Aws,
2493            "s3",
2494            Method::PUT,
2495            "https://bucket.s3.amazonaws.com/",
2496            &[],
2497            None,
2498        );
2499        const SQS_JSON: Built = (
2500            Cloud::Aws,
2501            "sqs",
2502            Method::POST,
2503            "https://sqs.us-east-1.amazonaws.com/",
2504            &[
2505                ("content-type", "application/x-amz-json-1.0"),
2506                ("x-amz-target", "AmazonSQS.SetQueueAttributes"),
2507            ],
2508            Some(r#"{"QueueUrl":"q","Attributes":{"VisibilityTimeout":"30"}}"#),
2509        );
2510        const SQS_QUERY: Built = (
2511            Cloud::Aws,
2512            "sqs",
2513            Method::POST,
2514            "https://sqs.us-east-1.amazonaws.com/",
2515            &[("content-type", "application/x-www-form-urlencoded")],
2516            Some(
2517                "Action=SetQueueAttributes&Attribute.1.Name=VisibilityTimeout&Attribute.1.Value=30",
2518            ),
2519        );
2520        const CREATE_KEY: Built = (
2521            Cloud::Aws,
2522            "kms",
2523            Method::POST,
2524            "https://kms.us-east-1.amazonaws.com/",
2525            &[
2526                ("content-type", "application/x-amz-json-1.1"),
2527                ("x-amz-target", "TrentService.CreateKey"),
2528            ],
2529            Some(r#"{"Description":"k"}"#),
2530        );
2531        const BUCKET_PATCH: Built = (
2532            Cloud::Gcp,
2533            "storage",
2534            Method::PATCH,
2535            "https://storage.googleapis.com/storage/v1/b/bucket",
2536            &[("content-type", "application/json")],
2537            Some(r#"{"labels":{"team":"a"}}"#),
2538        );
2539        const RESOURCE_GROUP: Built = (
2540            Cloud::Azure,
2541            "management",
2542            Method::PUT,
2543            "https://management.azure.com/subscriptions/s/resourcegroups/g",
2544            &[("content-type", "application/json")],
2545            Some(r#"{"location":"eastus"}"#),
2546        );
2547        const REST_API: Built = (
2548            Cloud::Aws,
2549            "apigateway",
2550            Method::POST,
2551            "https://apigateway.us-east-1.amazonaws.com/restapis",
2552            &[("content-type", "application/json")],
2553            Some(r#"{"name":"api","endpointConfiguration":{"types":["REGIONAL"]}}"#),
2554        );
2555        const REST_API_PATCH: Built = (
2556            Cloud::Aws,
2557            "apigateway",
2558            Method::PATCH,
2559            "https://apigateway.us-east-1.amazonaws.com/restapis/a1",
2560            &[("content-type", "application/json")],
2561            Some(r#"{"patchOperations":[{"op":"replace","path":"/description","value":"d"}]}"#),
2562        );
2563        const CREATE_TABLE: Built = (
2564            Cloud::Aws,
2565            "dynamodb",
2566            Method::POST,
2567            "https://dynamodb.us-east-1.amazonaws.com/",
2568            &[
2569                ("content-type", "application/x-amz-json-1.0"),
2570                ("x-amz-target", "DynamoDB_20120810.CreateTable"),
2571            ],
2572            Some(r#"{"TableName":"t"}"#),
2573        );
2574        let cases: [(&str, Built, fn(&mut HookRequest)); 20] = [
2575            (
2576                "a DynamoDB resource policy in another case",
2577                CREATE_TABLE,
2578                |r| r.body = Some(r#"{"TableName":"t","resourcePolicy":"{}"}"#.into()),
2579            ),
2580            (
2581                "an API Gateway policy moved away in a patch",
2582                REST_API_PATCH,
2583                |r| {
2584                    r.body = Some(
2585                    r#"{"patchOperations":[{"op":"move","from":"/policy","path":"/description"}]}"#
2586                        .into(),
2587                )
2588                },
2589            ),
2590            ("a DynamoDB resource policy", CREATE_TABLE, |r| {
2591                r.body = Some(r#"{"TableName":"t","ResourcePolicy":"{}"}"#.into())
2592            }),
2593            ("an API Gateway resource policy", REST_API, |r| {
2594                r.body = Some(r#"{"name":"api","policy":"{}"}"#.into())
2595            }),
2596            ("an API Gateway policy in a patch", REST_API_PATCH, |r| {
2597                r.body = Some(
2598                    r#"{"patchOperations":[{"op":"replace","path":"/policy","value":"{}"}]}"#
2599                        .into(),
2600                )
2601            }),
2602            (
2603                "an API Gateway policy in an OpenAPI document",
2604                REST_API,
2605                |r| {
2606                    r.body = Some(
2607                        r#"{"name":"api","body":{"x-amazon-apigateway-policy":{"Statement":[]}}}"#
2608                            .into(),
2609                    )
2610                },
2611            ),
2612            ("an S3 bucket policy", CREATE_BUCKET, |r| {
2613                r.url.set_query(Some("policy"));
2614                r.body = Some(r#"{"Statement":[]}"#.into());
2615            }),
2616            ("an S3 ACL", CREATE_BUCKET, |r| r.url.set_query(Some("acl"))),
2617            ("an S3 canned ACL header", CREATE_BUCKET, |r| {
2618                r.headers
2619                    .insert("x-amz-acl", HeaderValue::from_static("public-read"));
2620            }),
2621            ("an SQS queue policy in JSON", SQS_JSON, |r| {
2622                r.body = Some(
2623                    r#"{"QueueUrl":"q","Attributes":{"VisibilityTimeout":"30","Policy":"{}"}}"#
2624                        .into(),
2625                )
2626            }),
2627            (
2628                "an SQS queue policy in JSON, in another case",
2629                SQS_JSON,
2630                |r| r.body = Some(r#"{"QueueUrl":"q","attributes":{"policy":"{}"}}"#.into()),
2631            ),
2632            (
2633                "an SQS queue policy in a form, in another case",
2634                SQS_QUERY,
2635                |r| {
2636                    r.body
2637                        .as_mut()
2638                        .unwrap()
2639                        .push_str("&Attribute.2.name=policy&Attribute.2.Value=%7B%7D")
2640                },
2641            ),
2642            (
2643                "a policy field in a form, in another case",
2644                SQS_QUERY,
2645                |r| r.body.as_mut().unwrap().push_str("&policy=%7B%7D"),
2646            ),
2647            ("an SQS queue policy in a form", SQS_QUERY, |r| {
2648                r.body
2649                    .as_mut()
2650                    .unwrap()
2651                    .push_str("&Attribute.2.Name=Policy&Attribute.2.Value=%7B%7D")
2652            }),
2653            ("an SQS queue policy in the query", SQS_QUERY, |r| {
2654                r.url
2655                    .set_query(Some("Attribute.2.Name=Policy&Attribute.2.Value=%7B%7D"))
2656            }),
2657            ("an SQS form moved into the query", SQS_QUERY, |r| {
2658                let form = r.body.take().unwrap();
2659                r.url.set_query(Some(&format!(
2660                    "{form}&Attribute.2.Name=Policy&Attribute.2.Value=%7B%7D"
2661                )))
2662            }),
2663            ("a KMS key policy", CREATE_KEY, |r| {
2664                r.body = Some(r#"{"Description":"k","Policy":"{}"}"#.into())
2665            }),
2666            ("a Cloud Storage predefined ACL", BUCKET_PATCH, |r| {
2667                r.url.set_query(Some("predefinedAcl=publicRead"))
2668            }),
2669            ("a Cloud Run IAM policy", CLOUD_RUN_SERVICE, |r| {
2670                r.url
2671                    .set_path("/v2/projects/p/locations/l/services/web:setIamPolicy");
2672                r.method = Method::POST;
2673            }),
2674            ("an Azure role assignment", RESOURCE_GROUP, |r| {
2675                r.url.set_path(
2676                    "/subscriptions/s/resourcegroups/g/providers/Microsoft.Authorization/roleAssignments/a",
2677                )
2678            }),
2679        ];
2680        for (what, built, change) in cases {
2681            assert_change_refused(what, built, change);
2682        }
2683    }
2684
2685    const AZURE_JSON: [(&str, &str, &str); 4] = [
2686        (
2687            "storage account",
2688            "https://management.azure.com/subscriptions/s/resourceGroups/g/providers/Microsoft.Storage/storageAccounts/acct?api-version=2023-01-01",
2689            r#"{"location":"eastus","properties":{"allowBlobPublicAccess":false,"networkAcls":{"defaultAction":"Deny","ipRules":[{"value":"10.0.0.0/8"}]}}}"#,
2690        ),
2691        (
2692            "container",
2693            "https://management.azure.com/subscriptions/s/resourceGroups/g/providers/Microsoft.Storage/storageAccounts/acct/blobServices/default/containers/c?api-version=2023-01-01",
2694            r#"{"properties":{"publicAccess":"None"}}"#,
2695        ),
2696        (
2697            "network security group",
2698            "https://management.azure.com/subscriptions/s/resourceGroups/g/providers/Microsoft.Network/networkSecurityGroups/nsg?api-version=2023-01-01",
2699            r#"{"location":"eastus","properties":{"securityRules":[{"name":"r","properties":{"access":"Allow","direction":"Inbound","sourceAddressPrefix":"10.0.0.0/16","sourceAddressPrefixes":[]}}]}}"#,
2700        ),
2701        (
2702            "storage account with a public default",
2703            "https://management.azure.com/subscriptions/s/resourceGroups/g/providers/Microsoft.Storage/storageAccounts/acct?api-version=2023-01-01",
2704            r#"{"properties":{"publicNetworkAccess":"Disabled"}}"#,
2705        ),
2706    ];
2707
2708    fn azure_call(what: &str) -> Built {
2709        let (_, url, body) = AZURE_JSON.iter().find(|(name, ..)| *name == what).unwrap();
2710        (
2711            Cloud::Azure,
2712            "management",
2713            Method::PUT,
2714            url,
2715            &[("content-type", "application/json")],
2716            Some(body),
2717        )
2718    }
2719
2720    /// An interceptor never makes storage or a network public, on any cloud.
2721    #[test]
2722    fn a_change_that_opens_storage_or_a_network_to_the_internet_is_refused() {
2723        const SECURITY_GROUP: Built = (
2724            Cloud::Aws,
2725            "ec2",
2726            Method::POST,
2727            "https://ec2.us-east-1.amazonaws.com/",
2728            &[("content-type", "application/x-www-form-urlencoded")],
2729            Some("Action=AuthorizeSecurityGroupIngress&GroupId=sg-1&IpPermissions.1.IpProtocol=-1&IpPermissions.1.IpRanges.1.CidrIp=10.0.0.0%2F16"),
2730        );
2731        const GCS_BUCKET: Built = (
2732            Cloud::Gcp,
2733            "storage",
2734            Method::PATCH,
2735            "https://storage.googleapis.com/storage/v1/b/bucket",
2736            &[("content-type", "application/json")],
2737            Some(r#"{"iamConfiguration":{"publicAccessPrevention":"enforced"}}"#),
2738        );
2739        const FIREWALL: Built = (
2740            Cloud::Gcp,
2741            "compute",
2742            Method::POST,
2743            "https://compute.googleapis.com/compute/v1/projects/p/global/firewalls",
2744            &[("content-type", "application/json")],
2745            Some(r#"{"name":"f","sourceRanges":["10.0.0.0/16"]}"#),
2746        );
2747        let cases: [(&str, Built, fn(&mut HookRequest)); 15] = [
2748            (
2749                "an Azure storage account allowing public blobs",
2750                azure_call("storage account"),
2751                |r| {
2752                    r.body = Some(r.body.as_ref().unwrap().replace(
2753                        r#""allowBlobPublicAccess":false"#,
2754                        r#""allowBlobPublicAccess":true"#,
2755                    ))
2756                },
2757            ),
2758            (
2759                "an Azure container with blob access",
2760                azure_call("container"),
2761                |r| r.body = Some(r#"{"properties":{"publicAccess":"Blob"}}"#.into()),
2762            ),
2763            (
2764                "an Azure container with container access",
2765                azure_call("container"),
2766                |r| r.body = Some(r#"{"properties":{"publicAccess":"Container"}}"#.into()),
2767            ),
2768            (
2769                "an Azure storage firewall that allows by default",
2770                azure_call("storage account"),
2771                |r| r.body = Some(r.body.as_ref().unwrap().replace(r#""Deny""#, r#""Allow""#)),
2772            ),
2773            (
2774                "an Azure storage firewall rule for the whole internet",
2775                azure_call("storage account"),
2776                |r| r.body = Some(r.body.as_ref().unwrap().replace("10.0.0.0/8", "0.0.0.0/0")),
2777            ),
2778            (
2779                "an Azure storage account with public network access",
2780                azure_call("storage account with a public default"),
2781                |r| r.body = Some(r#"{"properties":{"publicNetworkAccess":"Enabled"}}"#.into()),
2782            ),
2783            (
2784                "an Azure NSG rule from *",
2785                azure_call("network security group"),
2786                |r| r.body = Some(r.body.as_ref().unwrap().replace("10.0.0.0/16", "*")),
2787            ),
2788            (
2789                "an Azure NSG rule from Internet",
2790                azure_call("network security group"),
2791                |r| r.body = Some(r.body.as_ref().unwrap().replace("10.0.0.0/16", "Internet")),
2792            ),
2793            (
2794                "an Azure NSG rule from Any",
2795                azure_call("network security group"),
2796                |r| r.body = Some(r.body.as_ref().unwrap().replace("10.0.0.0/16", "any")),
2797            ),
2798            (
2799                "an Azure NSG rule from ::/0 in a prefix list",
2800                azure_call("network security group"),
2801                |r| {
2802                    r.body = Some(r.body.as_ref().unwrap().replace(
2803                        r#""sourceAddressPrefixes":[]"#,
2804                        r#""sourceAddressPrefixes":["::/0"]"#,
2805                    ))
2806                },
2807            ),
2808            ("an AWS security group open to IPv4", SECURITY_GROUP, |r| {
2809                r.body = Some(
2810                    r.body
2811                        .as_ref()
2812                        .unwrap()
2813                        .replace("10.0.0.0%2F16", "0.0.0.0%2F0"),
2814                )
2815            }),
2816            ("an AWS security group open to IPv6", SECURITY_GROUP, |r| {
2817                r.body
2818                    .as_mut()
2819                    .unwrap()
2820                    .push_str("&IpPermissions.1.Ipv6Ranges.1.CidrIpv6=%3A%3A%2F0")
2821            }),
2822            (
2823                "a Cloud Storage public access prevention turned off",
2824                GCS_BUCKET,
2825                |r| {
2826                    r.body = Some(
2827                        r#"{"iamConfiguration":{"publicAccessPrevention":"inherited"}}"#.into(),
2828                    )
2829                },
2830            ),
2831            ("a Cloud Storage ACL entry for allUsers", GCS_BUCKET, |r| {
2832                r.body = Some(r#"{"acl":[{"entity":"allUsers","role":"READER"}]}"#.into())
2833            }),
2834            ("a Google firewall open to the internet", FIREWALL, |r| {
2835                r.body = Some(r#"{"name":"f","sourceRanges":["10.0.0.0/16","0.0.0.0/0"]}"#.into())
2836            }),
2837        ];
2838        for (what, built, change) in cases {
2839            assert_change_refused(what, built, change);
2840        }
2841    }
2842
2843    /// Any change to an exposure or access setting is refused, whatever its value: the check
2844    /// does not judge a value, so a split range or a flipped flag cannot slip past it.
2845    #[test]
2846    fn any_change_to_an_exposure_or_access_setting_is_refused_with_its_reason() {
2847        const REASON: &str = "a setting that decides who can reach a resource";
2848        const SECURITY_GROUP: Built = (
2849            Cloud::Aws,
2850            "ec2",
2851            Method::POST,
2852            "https://ec2.us-east-1.amazonaws.com/",
2853            &[("content-type", "application/x-www-form-urlencoded")],
2854            Some("Action=AuthorizeSecurityGroupIngress&GroupId=sg-1&IpPermissions.1.IpRanges.1.CidrIp=10.0.0.0%2F16"),
2855        );
2856        const RDS: Built = (
2857            Cloud::Aws,
2858            "rds",
2859            Method::POST,
2860            "https://rds.us-east-1.amazonaws.com/?Action=ModifyDBInstance&DBInstanceIdentifier=db&PubliclyAccessible=false",
2861            &[],
2862            None,
2863        );
2864        const SQL: Built = (
2865            Cloud::Gcp,
2866            "sqladmin",
2867            Method::PATCH,
2868            "https://sqladmin.googleapis.com/v1/projects/p/instances/i",
2869            &[("content-type", "application/json")],
2870            Some(
2871                r#"{"settings":{"ipConfiguration":{"ipv4Enabled":false,"authorizedNetworks":[]}}}"#,
2872            ),
2873        );
2874        const RUN: Built = (
2875            Cloud::Gcp,
2876            "run",
2877            Method::PATCH,
2878            "https://run.googleapis.com/v2/projects/p/locations/l/services/web",
2879            &[("content-type", "application/json")],
2880            Some(r#"{"ingress":"INGRESS_TRAFFIC_INTERNAL_ONLY","invokerIamDisabled":false}"#),
2881        );
2882        const APP: Built = (
2883            Cloud::Azure,
2884            "management",
2885            Method::PUT,
2886            "https://management.azure.com/subscriptions/s/resourceGroups/g/providers/Microsoft.App/containerApps/web?api-version=2024-03-01",
2887            &[("content-type", "application/json")],
2888            Some(r#"{"properties":{"configuration":{"ingress":{"external":false,"targetPort":80}}}}"#),
2889        );
2890        const VAULT: Built = (
2891            Cloud::Azure,
2892            "management",
2893            Method::PUT,
2894            "https://management.azure.com/subscriptions/s/resourceGroups/g/providers/Microsoft.KeyVault/vaults/v?api-version=2023-07-01",
2895            &[("content-type", "application/json")],
2896            Some(r#"{"properties":{"enableRbacAuthorization":true,"accessPolicies":[]}}"#),
2897        );
2898        const GCS: Built = (
2899            Cloud::Gcp,
2900            "storage",
2901            Method::PATCH,
2902            "https://storage.googleapis.com/storage/v1/b/bucket",
2903            &[("content-type", "application/json")],
2904            Some(r#"{"iamConfiguration":{"uniformBucketLevelAccess":{"enabled":true}},"acl":[]}"#),
2905        );
2906        const FIREWALL: Built = (
2907            Cloud::Gcp,
2908            "compute",
2909            Method::POST,
2910            "https://compute.googleapis.com/compute/v1/projects/p/global/firewalls",
2911            &[("content-type", "application/json")],
2912            Some(r#"{"name":"f","sourceRanges":["10.0.0.0/16"]}"#),
2913        );
2914        let cases: [(&str, Built, fn(&mut HookRequest)); 11] = [
2915            (
2916                "a range split in two halves of the internet",
2917                FIREWALL,
2918                |r| {
2919                    r.body =
2920                        Some(r#"{"name":"f","sourceRanges":["0.0.0.0/1","128.0.0.0/1"]}"#.into())
2921                },
2922            ),
2923            ("an RDS instance made publicly accessible", RDS, |r| {
2924                r.url = "https://rds.us-east-1.amazonaws.com/?Action=ModifyDBInstance&DBInstanceIdentifier=db&PubliclyAccessible=true"
2925                    .parse()
2926                    .unwrap()
2927            }),
2928            ("a Cloud SQL authorized network added", SQL, |r| {
2929                r.body = Some(
2930                    r#"{"settings":{"ipConfiguration":{"ipv4Enabled":false,"authorizedNetworks":[{"value":"203.0.113.0/24"}]}}}"#.into(),
2931                )
2932            }),
2933            (
2934                "a Cloud Run ingress opened and IAM invoker check off",
2935                RUN,
2936                |r| {
2937                    r.body = Some(
2938                        r#"{"ingress":"INGRESS_TRAFFIC_ALL","invokerIamDisabled":true}"#.into(),
2939                    )
2940                },
2941            ),
2942            ("a snake_case Cloud Run invoker_iam_disabled", RUN, |r| {
2943                r.body = Some(
2944                    r#"{"ingress":"INGRESS_TRAFFIC_INTERNAL_ONLY","invoker_iam_disabled":true}"#
2945                        .into(),
2946                )
2947            }),
2948            ("a snake_case publicly_accessible", SQL, |r| {
2949                r.body = Some(r#"{"settings":{"publicly_accessible":true}}"#.into())
2950            }),
2951            ("a Container App with external ingress", APP, |r| {
2952                r.body = Some(
2953                    r.body
2954                        .as_ref()
2955                        .unwrap()
2956                        .replace(r#""external":false"#, r#""external":true"#),
2957                )
2958            }),
2959            ("a Key Vault moved to access policies", VAULT, |r| {
2960                r.body = Some(
2961                    r#"{"properties":{"enableRbacAuthorization":false,"accessPolicies":[{"objectId":"o"}]}}"#.into(),
2962                )
2963            }),
2964            ("a bucket with uniform access off and an ACL", GCS, |r| {
2965                r.body = Some(
2966                    r#"{"iamConfiguration":{"uniformBucketLevelAccess":{"enabled":false}},"acl":[{"entity":"project-owners-1","role":"OWNER"}]}"#.into(),
2967                )
2968            }),
2969            (
2970                "a security group range added next to the original",
2971                SECURITY_GROUP,
2972                |r| {
2973                    r.body
2974                        .as_mut()
2975                        .unwrap()
2976                        .push_str("&IpPermissions.1.IpRanges.2.CidrIp=203.0.113.0%2F24")
2977                },
2978            ),
2979            ("a setting removed", FIREWALL, |r| {
2980                r.body = Some(r#"{"name":"f"}"#.into())
2981            }),
2982        ];
2983        for (what, built, change) in cases {
2984            assert_change_refused_because(what, built, REASON, change);
2985        }
2986    }
2987
2988    /// Ordinary changes still go through, and a call Alien itself builds public stays so.
2989    #[test]
2990    fn a_change_that_does_not_open_anything_to_the_internet_is_sent() {
2991        const PUBLIC_CONTAINER: Built = (
2992            Cloud::Azure,
2993            "management",
2994            Method::PUT,
2995            "https://management.azure.com/subscriptions/s/resourceGroups/g/providers/Microsoft.Storage/storageAccounts/acct/blobServices/default/containers/c?api-version=2023-01-01",
2996            &[("content-type", "application/json")],
2997            Some(r#"{"properties":{"publicAccess":"Blob"}}"#),
2998        );
2999        const EGRESS: Built = (
3000            Cloud::Aws,
3001            "ec2",
3002            Method::POST,
3003            "https://ec2.us-east-1.amazonaws.com/",
3004            &[("content-type", "application/x-www-form-urlencoded")],
3005            Some("Action=AuthorizeSecurityGroupEgress&GroupId=sg-1&IpPermissions.1.IpRanges.1.CidrIp=0.0.0.0%2F0"),
3006        );
3007        const CONTAINER_APP: Built = (
3008            Cloud::Azure,
3009            "management",
3010            Method::PUT,
3011            "https://management.azure.com/subscriptions/s/resourceGroups/g/providers/Microsoft.App/containerApps/web?api-version=2024-03-01",
3012            &[("content-type", "application/json")],
3013            Some(r#"{"properties":{"template":{"containers":[{"name":"web","env":[{"name":"MODE","value":"a"}]}]}}}"#),
3014        );
3015        let cases: [(&str, Built, fn(&mut HookRequest)); 4] = [
3016            (
3017                "an environment variable that ends in /0 (a Redis URL)",
3018                CONTAINER_APP,
3019                |r| {
3020                    r.body = Some(r.body.as_ref().unwrap().replace(
3021                        r#"{"name":"MODE","value":"a"}"#,
3022                        r#"{"name":"MODE","value":"a"},{"name":"REDIS_URL","value":"redis://cache:6379/0"}"#,
3023                    ))
3024                },
3025            ),
3026            (
3027                "a tag on an Azure storage account",
3028                azure_call("storage account"),
3029                |r| {
3030                    r.body = Some(r.body.as_ref().unwrap().replace(
3031                        r#""location":"eastus""#,
3032                        r#""location":"eastus","tags":{"team":"a"}"#,
3033                    ))
3034                },
3035            ),
3036            (
3037                "an Azure container Alien made public on purpose",
3038                PUBLIC_CONTAINER,
3039                |r| {
3040                    r.body = Some(
3041                        r#"{"properties":{"publicAccess":"Blob"},"metadata":{"a":"b"}}"#.into(),
3042                    )
3043                },
3044            ),
3045            (
3046                "an AWS rule Alien already opened to the internet",
3047                EGRESS,
3048                |r| {
3049                    r.body
3050                        .as_mut()
3051                        .unwrap()
3052                        .push_str("&IpPermissions.1.IpRanges.1.Description=x")
3053                },
3054            ),
3055        ];
3056        for (what, built, change) in cases {
3057            assert_change_sent(what, built, change);
3058        }
3059    }
3060
3061    /// A call Alien makes to change who has access, to act as another identity, or to read a
3062    /// policy it then writes back is sent as Alien built it: no interceptor is asked whether it
3063    /// matches it, so one that matches everything never fails it.
3064    #[test]
3065    fn a_call_that_changes_access_or_identity_is_never_offered() {
3066        let cases: [Built; 20] = [
3067            (
3068                Cloud::Aws,
3069                "iam",
3070                Method::POST,
3071                "https://iam.amazonaws.com/",
3072                &[("content-type", "application/x-www-form-urlencoded")],
3073                Some("Action=PutRolePolicy&RoleName=r&PolicyName=p&PolicyDocument=%7B%7D"),
3074            ),
3075            (
3076                Cloud::Aws,
3077                "cloudcontrolapi",
3078                Method::POST,
3079                "https://cloudcontrolapi.us-east-1.amazonaws.com/",
3080                &[(
3081                    "x-amz-target",
3082                    "CloudApiService.CreateResource",
3083                )],
3084                Some(r#"{"TypeName":"AWS::EC2::VPC"}"#),
3085            ),
3086            (
3087                Cloud::Aws,
3088                "s3",
3089                Method::PUT,
3090                "https://bucket.s3.amazonaws.com/?policy",
3091                &[],
3092                Some(r#"{"Statement":[]}"#),
3093            ),
3094            (
3095                Cloud::Aws,
3096                "s3",
3097                Method::PUT,
3098                "https://bucket.s3.amazonaws.com/?publicAccessBlock",
3099                &[],
3100                Some("<PublicAccessBlockConfiguration><BlockPublicAcls>false</BlockPublicAcls></PublicAccessBlockConfiguration>"),
3101            ),
3102            (
3103                Cloud::Aws,
3104                "s3",
3105                Method::GET,
3106                "https://bucket.s3.amazonaws.com/?policy",
3107                &[],
3108                None,
3109            ),
3110            (
3111                Cloud::Aws,
3112                "kms",
3113                Method::POST,
3114                "https://kms.us-east-1.amazonaws.com/",
3115                &[("x-amz-target", "TrentService.PutKeyPolicy")],
3116                Some(r#"{"KeyId":"k","Policy":"{}"}"#),
3117            ),
3118            (
3119                Cloud::Aws,
3120                "ecr",
3121                Method::POST,
3122                "https://api.ecr.us-east-1.amazonaws.com/",
3123                &[(
3124                    "x-amz-target",
3125                    "AmazonEC2ContainerRegistry_V20150921.GetRepositoryPolicy",
3126                )],
3127                Some(r#"{"repositoryName":"r"}"#),
3128            ),
3129            (
3130                Cloud::Aws,
3131                "lambda",
3132                Method::POST,
3133                "https://lambda.us-east-1.amazonaws.com/2015-03-31/functions/f/policy",
3134                &[],
3135                Some(r#"{"StatementId":"s","Action":"lambda:InvokeFunction"}"#),
3136            ),
3137            (
3138                Cloud::Aws,
3139                "sqs",
3140                Method::POST,
3141                "https://sqs.us-east-1.amazonaws.com/",
3142                &[],
3143                Some("Action=SetQueueAttributes&Attribute.1.Name=Policy&Attribute.1.Value=%7B%7D"),
3144            ),
3145            (
3146                Cloud::Aws,
3147                "logs",
3148                Method::POST,
3149                "https://logs.us-east-1.amazonaws.com/",
3150                &[("x-amz-target", "Logs_20140328.PutResourcePolicy")],
3151                Some(r#"{"policyName":"p","policyDocument":"{}"}"#),
3152            ),
3153            (
3154                Cloud::Gcp,
3155                "cloudrun",
3156                Method::POST,
3157                "https://run.googleapis.com/v2/projects/p/locations/l/services/web:setIamPolicy",
3158                &[],
3159                Some(r#"{"policy":{}}"#),
3160            ),
3161            (
3162                Cloud::Gcp,
3163                "cloudrun",
3164                Method::GET,
3165                "https://run.googleapis.com/v2/projects/p/locations/l/services/web:getIamPolicy",
3166                &[],
3167                None,
3168            ),
3169            (
3170                Cloud::Gcp,
3171                "storage",
3172                Method::GET,
3173                "https://storage.googleapis.com/storage/v1/b/bucket/iam",
3174                &[],
3175                None,
3176            ),
3177            (
3178                Cloud::Azure,
3179                "management",
3180                Method::PUT,
3181                "https://management.azure.com/subscriptions/s/providers/Microsoft.Authorization/roleAssignments/a",
3182                &[],
3183                Some(r#"{"properties":{}}"#),
3184            ),
3185            (
3186                Cloud::Azure,
3187                "management",
3188                Method::PUT,
3189                "https://management.azure.com/subscriptions/s/resourceGroups/g/providers/Microsoft.ManagedIdentity/userAssignedIdentities/u/federatedIdentityCredentials/c",
3190                &[],
3191                Some(r#"{"properties":{}}"#),
3192            ),
3193            (
3194                Cloud::Kubernetes,
3195                "kubernetes",
3196                Method::POST,
3197                "https://cluster.example.com/api/v1/namespaces/app/secrets",
3198                &[("content-type", "application/json")],
3199                Some(r#"{"metadata":{"name":"registry"},"type":"kubernetes.io/dockerconfigjson"}"#),
3200            ),
3201            (
3202                Cloud::Kubernetes,
3203                "kubernetes",
3204                Method::GET,
3205                "https://cluster.example.com/api/v1/namespaces/app/secrets/registry",
3206                &[],
3207                None,
3208            ),
3209            (
3210                Cloud::Kubernetes,
3211                "kubernetes",
3212                Method::GET,
3213                "https://cluster.example.com/api/v1/secrets?labelSelector=app",
3214                &[],
3215                None,
3216            ),
3217            (
3218                Cloud::Kubernetes,
3219                "kubernetes",
3220                Method::POST,
3221                "https://cluster.example.com/api/v1/namespaces/app/serviceaccounts/app/token",
3222                &[("content-type", "application/json")],
3223                Some(r#"{"spec":{"audiences":["api"]}}"#),
3224            ),
3225            (
3226                Cloud::Kubernetes,
3227                "kubernetes",
3228                Method::POST,
3229                "https://cluster.example.com/apis/authentication.k8s.io/v1/tokenreviews",
3230                &[("content-type", "application/json")],
3231                Some(r#"{"spec":{"token":"t"}}"#),
3232            ),
3233        ];
3234        for built in cases {
3235            let (cloud, service) = (built.0, built.1);
3236            let interceptors = chain(vec![TestInterceptor::new("acme", cloud, service)
3237                .when(|request| panic!("{} {} was offered", request.method, request.url))]);
3238            let mut request = build(&built);
3239            let before = format!("{request:?}");
3240            assert!(interceptors
3241                .intercept(cloud, service, &mut request)
3242                .unwrap()
3243                .is_none());
3244            assert_eq!(format!("{request:?}"), before);
3245        }
3246    }
3247
3248    #[test]
3249    fn an_interceptor_never_sees_credentials_and_the_request_keeps_them() {
3250        let seen = Arc::new(Mutex::new(None));
3251        let spy = seen.clone();
3252        let interceptors = chain(vec![TestInterceptor::new(
3253            "acme",
3254            Cloud::Azure,
3255            "management",
3256        )
3257        .on_request(move |r| {
3258            *spy.lock().unwrap() = Some(r.headers.clone());
3259            Ok(())
3260        })]);
3261        let mut request = reqwest::Client::new()
3262            .get("https://management.azure.com/subscriptions/sub")
3263            .header("authorization", "Bearer azure-token")
3264            .header("proxy-authorization", "Basic proxy")
3265            .header("x-ms-version", "2023-11-03")
3266            .build()
3267            .unwrap();
3268        interceptors
3269            .intercept(Cloud::Azure, "management", &mut request)
3270            .unwrap();
3271        let seen = seen.lock().unwrap().clone().unwrap();
3272        assert!(seen.get("authorization").is_none());
3273        assert!(seen.get("proxy-authorization").is_none());
3274        assert_eq!(seen["x-ms-version"], "2023-11-03");
3275        assert_eq!(request.headers()["authorization"], "Bearer azure-token");
3276        assert_eq!(request.headers()["proxy-authorization"], "Basic proxy");
3277    }
3278
3279    #[test]
3280    fn a_changed_body_gets_new_digest_headers() {
3281        let interceptors = chain(vec![TestInterceptor::new("acme", Cloud::Aws, "rds")
3282            .on_request(|r| {
3283                r.body
3284                    .as_mut()
3285                    .unwrap()
3286                    .push_str("&EnableIAMDatabaseAuthentication=true");
3287                Ok(())
3288            })]);
3289        let mut request = rds_request("Action=CreateDBCluster");
3290        interceptors
3291            .intercept(Cloud::Aws, "rds", &mut request)
3292            .unwrap();
3293        let body = "Action=CreateDBCluster&EnableIAMDatabaseAuthentication=true";
3294        assert_eq!(body_text(&request), body);
3295        assert_eq!(
3296            request.headers()["content-length"],
3297            body.len().to_string().as_str()
3298        );
3299        assert_eq!(
3300            request.headers()["x-amz-content-sha256"],
3301            format!("{:x}", Sha256::digest(body)).as_str()
3302        );
3303        assert_eq!(
3304            request.headers()["content-md5"],
3305            base64::engine::general_purpose::STANDARD
3306                .encode(md5::compute(body).0)
3307                .as_str()
3308        );
3309    }
3310
3311    #[test]
3312    fn interceptors_run_in_order_on_the_request_the_previous_one_left() {
3313        let interceptors = chain(vec![
3314            TestInterceptor::new("first", Cloud::Gcp, "cloudsql").on_request(|r| {
3315                r.body = Some(r#"{"tier":"small"}"#.to_string());
3316                Ok(())
3317            }),
3318            TestInterceptor::new("second", Cloud::Gcp, "cloudsql").on_request(|r| {
3319                assert_eq!(r.body.as_deref(), Some(r#"{"tier":"small"}"#));
3320                r.body = Some(r#"{"tier":"large"}"#.to_string());
3321                Ok(())
3322            }),
3323        ]);
3324        let mut request = reqwest::Client::new()
3325            .post("https://sqladmin.googleapis.com/v1/projects/p/instances")
3326            .json(&serde_json::json!({"tier": "tiny"}))
3327            .build()
3328            .unwrap();
3329        interceptors
3330            .intercept(Cloud::Gcp, "cloudsql", &mut request)
3331            .unwrap();
3332        assert_eq!(body_text(&request), r#"{"tier":"large"}"#);
3333    }
3334
3335    #[test]
3336    fn an_interceptor_error_fails_the_call_naming_its_extension() {
3337        let interceptors = chain(vec![TestInterceptor::new(
3338            "acme",
3339            Cloud::Kubernetes,
3340            "kubernetes",
3341        )
3342        .on_request(|_| {
3343            Err(AlienError::new(ErrorData::GenericError {
3344                message: "label value missing".to_string(),
3345            }))
3346        })]);
3347        let mut request = reqwest::Client::new()
3348            .post("https://cluster.local/api/v1/namespaces/ns/pods")
3349            .json(&serde_json::json!({"kind": "Pod"}))
3350            .build()
3351            .unwrap();
3352        let error = interceptors
3353            .intercept(Cloud::Kubernetes, "kubernetes", &mut request)
3354            .unwrap_err();
3355        assert!(error
3356            .source
3357            .as_ref()
3358            .unwrap()
3359            .message
3360            .contains("label value missing"));
3361        assert_fails_naming(error, "acme");
3362    }
3363
3364    #[test]
3365    fn a_binary_request_body_fails_a_call_an_interceptor_matches() {
3366        let interceptors = chain(vec![TestInterceptor::new("acme", Cloud::Aws, "s3")
3367            .on_request(|_| panic!("a binary body is never offered"))]);
3368        let mut request = reqwest::Client::new()
3369            .put("https://bucket.s3.amazonaws.com/key")
3370            .header("content-type", "application/json")
3371            .body(vec![0xff, 0xfe])
3372            .build()
3373            .unwrap();
3374        let error = interceptors
3375            .intercept(Cloud::Aws, "s3", &mut request)
3376            .unwrap_err();
3377        assert_fails_naming(error, "acme");
3378    }
3379
3380    #[test]
3381    fn an_object_payload_is_binary_whatever_its_content_type() {
3382        let interceptors = chain(vec![TestInterceptor::new("acme", Cloud::Aws, "s3")
3383            .on_request(|_| panic!("an object's bytes are never offered"))]);
3384        for builder in [
3385            reqwest::Client::new()
3386                .put("https://bucket.s3.amazonaws.com/config.json")
3387                .header("content-type", "application/json")
3388                .body(r#"{"looks":"like json"}"#),
3389            reqwest::Client::new().get("https://bucket.s3.amazonaws.com/config.json"),
3390        ] {
3391            let mut request = builder.build().unwrap();
3392            let error = interceptors
3393                .for_object_payload()
3394                .intercept(Cloud::Aws, "s3", &mut request)
3395                .unwrap_err();
3396            assert_fails_naming(error, "acme");
3397        }
3398    }
3399
3400    #[test]
3401    fn a_binary_call_no_interceptor_matches_is_sent_as_it_was() {
3402        let seen = Arc::new(Mutex::new(Vec::new()));
3403        let spy = seen.clone();
3404        let tagging = TestInterceptor::new("acme", Cloud::Aws, "s3").when(move |request| {
3405            spy.lock()
3406                .unwrap()
3407                .push((request.method.clone(), request.body.clone()));
3408            request.url.query() == Some("tagging")
3409        });
3410        let interceptors = chain(vec![tagging]);
3411        let mut request = reqwest::Client::new()
3412            .put("https://bucket.s3.amazonaws.com/image.png")
3413            .body(vec![0x89, b'P', b'N', b'G'])
3414            .build()
3415            .unwrap();
3416        assert!(interceptors
3417            .for_object_payload()
3418            .intercept(Cloud::Aws, "s3", &mut request)
3419            .unwrap()
3420            .is_none());
3421        assert_eq!(
3422            request.body().unwrap().as_bytes(),
3423            Some(&[0x89, b'P', b'N', b'G'][..])
3424        );
3425        assert_eq!(*seen.lock().unwrap(), vec![(Method::PUT, None)]);
3426    }
3427
3428    #[test]
3429    fn a_text_body_is_offered_whatever_its_content_type() {
3430        let interceptors = chain(vec![TestInterceptor::new(
3431            "acme",
3432            Cloud::Kubernetes,
3433            "kubernetes",
3434        )
3435        .on_request(|request| {
3436            assert_eq!(request.body.as_deref(), Some("plain words"));
3437            Ok(())
3438        })]);
3439        let mut request = reqwest::Client::new()
3440            .post("https://cluster.local/api/v1/namespaces/ns/configmaps")
3441            .header("content-type", "text/plain")
3442            .body("plain words")
3443            .build()
3444            .unwrap();
3445        assert!(interceptors
3446            .intercept(Cloud::Kubernetes, "kubernetes", &mut request)
3447            .unwrap()
3448            .is_some());
3449    }
3450
3451    #[tokio::test]
3452    async fn modify_response_sees_and_can_change_an_error_response() {
3453        let interceptors = chain(vec![TestInterceptor::new(
3454            "acme",
3455            Cloud::Azure,
3456            "management",
3457        )
3458        .on_response(|request, response| {
3459            assert_eq!(request.method, Method::PUT);
3460            assert_eq!(response.status, 409);
3461            response.status = 200;
3462            response.body = r#"{"name":"recovered"}"#.to_string();
3463            Ok(())
3464        })]);
3465        let mut request = reqwest::Client::new()
3466            .put("https://management.azure.com/subscriptions/sub/thing")
3467            .json(&serde_json::json!({}))
3468            .build()
3469            .unwrap();
3470        let hook = interceptors
3471            .intercept(Cloud::Azure, "management", &mut request)
3472            .unwrap()
3473            .unwrap();
3474        let response = reqwest::Response::from(
3475            http::Response::builder()
3476                .status(409)
3477                .header("content-type", "application/json")
3478                .url(Url::parse("https://management.azure.com/subscriptions/sub/thing").unwrap())
3479                .body(r#"{"error":{"code":"Conflict"}}"#)
3480                .unwrap(),
3481        );
3482        let response = hook.apply(response).await.unwrap();
3483        assert_eq!(response.status(), 200);
3484        assert_eq!(
3485            response.url().as_str(),
3486            "https://management.azure.com/subscriptions/sub/thing"
3487        );
3488        assert_eq!(response.text().await.unwrap(), r#"{"name":"recovered"}"#);
3489    }
3490
3491    async fn hooked_get(interceptor: TestInterceptor) -> ResponseHook {
3492        let mut request = reqwest::Client::new()
3493            .get("https://cluster.local/api/v1/namespaces/ns/pods/web")
3494            .build()
3495            .unwrap();
3496        chain(vec![interceptor])
3497            .intercept(Cloud::Kubernetes, "kubernetes", &mut request)
3498            .unwrap()
3499            .unwrap()
3500    }
3501
3502    #[tokio::test]
3503    async fn a_binary_response_fails_a_call_an_interceptor_matches() {
3504        let hook = hooked_get(
3505            TestInterceptor::new("acme", Cloud::Kubernetes, "kubernetes")
3506                .on_response(|_, _| panic!("a binary body is never offered")),
3507        )
3508        .await;
3509        let response = reqwest::Response::from(
3510            http::Response::builder()
3511                .status(200)
3512                .header("content-type", "application/json")
3513                .body(vec![0x89, b'P', b'N', b'G', 0xff])
3514                .unwrap(),
3515        );
3516        assert_fails_naming(hook.apply(response).await.unwrap_err(), "acme");
3517    }
3518
3519    /// A plain-text error page from an API server or a proxy is text: it reaches the client's own
3520    /// status handling and retries instead of failing the call.
3521    #[tokio::test]
3522    async fn a_plain_text_error_response_is_offered() {
3523        let hook = hooked_get(
3524            TestInterceptor::new("acme", Cloud::Kubernetes, "kubernetes").on_response(
3525                |_, response| {
3526                    assert_eq!(response.body, "upstream connect error");
3527                    Ok(())
3528                },
3529            ),
3530        )
3531        .await;
3532        let response = reqwest::Response::from(
3533            http::Response::builder()
3534                .status(503)
3535                .header("content-type", "text/plain")
3536                .body("upstream connect error")
3537                .unwrap(),
3538        );
3539        let response = hook.apply(response).await.unwrap();
3540        assert_eq!(response.status(), 503);
3541        assert_eq!(response.text().await.unwrap(), "upstream connect error");
3542    }
3543
3544    /// A cloud's error can quote the request it refused, as AWS quotes the signed headers when a
3545    /// signature does not match. The credential the call was signed with is cleared before an
3546    /// interceptor reads the response, whether the client signed before the interceptors ran or
3547    /// after.
3548    #[tokio::test]
3549    async fn an_echoed_credential_is_cleared_before_an_interceptor_reads_the_response() {
3550        let token = "IQoJb3JpZ2luX2VjEXAMPLESESSIONTOKEN";
3551        let quoting = |request: &mut reqwest::Request| {
3552            chain(vec![TestInterceptor::new("acme", Cloud::Aws, "s3")
3553                .on_response(move |_, response| {
3554                    assert!(!response.body.contains(token), "{}", response.body);
3555                    assert!(response.body.contains("[redacted]"), "{}", response.body);
3556                    let echoed = response.headers["x-amz-echo"].to_str().unwrap();
3557                    assert!(!echoed.contains(token), "{echoed}");
3558                    Ok(())
3559                })])
3560            .intercept(Cloud::Aws, "s3", request)
3561            .unwrap()
3562            .unwrap()
3563        };
3564        let response = || {
3565            reqwest::Response::from(
3566                http::Response::builder()
3567                    .status(403)
3568                    .header("content-type", "application/xml")
3569                    .header("x-amz-echo", format!("token={token}"))
3570                    .body(format!(
3571                        "<Error><Code>SignatureDoesNotMatch</Code><CanonicalRequest>x-amz-security-token:{token}</CanonicalRequest></Error>"
3572                    ))
3573                    .unwrap(),
3574            )
3575        };
3576        let unsigned = || {
3577            reqwest::Client::new()
3578                .get("https://bucket.s3.us-east-1.amazonaws.com/key")
3579                .build()
3580                .unwrap()
3581        };
3582
3583        // Signed after the interceptors ran: the signer hands the hook the signed request.
3584        let mut request = unsigned();
3585        let mut hook = quoting(&mut request);
3586        request.headers_mut().insert(
3587            "x-amz-security-token",
3588            HeaderValue::from_str(token).unwrap(),
3589        );
3590        hook.remember_credentials(&request);
3591        let read = hook.apply(response()).await.unwrap().text().await.unwrap();
3592        assert!(!read.contains(token), "{read}");
3593
3594        // Signed before: the hook reads the credential off the request it intercepts.
3595        let mut request = unsigned();
3596        request.headers_mut().insert(
3597            "x-amz-security-token",
3598            HeaderValue::from_str(token).unwrap(),
3599        );
3600        let hook = quoting(&mut request);
3601        hook.apply(response()).await.unwrap();
3602    }
3603
3604    /// A bearer token is cleared on its own as well as with its scheme, and a short value that
3605    /// could be ordinary text is left alone.
3606    #[test]
3607    fn a_bearer_token_is_cleared_on_its_own() {
3608        let mut request = reqwest::Client::new()
3609            .get("https://management.azure.com/subscriptions/sub?api-version=1")
3610            .header("authorization", "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOi")
3611            .header("proxy-authorization", "Basic abc")
3612            .build()
3613            .unwrap();
3614        let hook = chain(vec![TestInterceptor::new(
3615            "acme",
3616            Cloud::Azure,
3617            "management",
3618        )])
3619        .intercept(Cloud::Azure, "management", &mut request)
3620        .unwrap()
3621        .unwrap();
3622        assert_eq!(
3623            hook.cleared(br#"{"token":"eyJ0eXAiOiJKV1QiLCJhbGciOi","word":"abc"}"#),
3624            br#"{"token":"[redacted]","word":"abc"}"#.to_vec()
3625        );
3626    }
3627
3628    /// A create the cloud answered with success already made the resource, so a hook that turns
3629    /// the answer into a throttle fails the call for good instead of having it sent again.
3630    #[tokio::test]
3631    async fn a_hook_that_fails_a_successful_call_fails_it_for_good() {
3632        let mut request = reqwest::Client::new()
3633            .post("https://ec2.us-east-1.amazonaws.com/")
3634            .header("content-type", "application/x-www-form-urlencoded")
3635            .body("Action=CreateVpc&CidrBlock=10.0.0.0%2F16")
3636            .build()
3637            .unwrap();
3638        let hook = chain(vec![TestInterceptor::new("acme", Cloud::Aws, "ec2")
3639            .on_response(|_, response| {
3640                response.status = 429;
3641                Ok(())
3642            })])
3643        .intercept(Cloud::Aws, "ec2", &mut request)
3644        .unwrap()
3645        .unwrap();
3646        let response = reqwest::Response::from(
3647            http::Response::builder()
3648                .status(200)
3649                .header("content-type", "text/xml")
3650                .body("<CreateVpcResponse><vpc><vpcId>vpc-1</vpcId></vpc></CreateVpcResponse>")
3651                .unwrap(),
3652        );
3653        let error = hook.apply(response).await.unwrap_err();
3654        assert!(!error.retryable);
3655        assert_fails_naming(error, "acme");
3656    }
3657
3658    /// Alien reads a Kubernetes response to decide its next calls on the cluster, so an
3659    /// interceptor may not change one.
3660    #[tokio::test]
3661    async fn a_kubernetes_response_is_not_changed() {
3662        let hook = hooked_get(
3663            TestInterceptor::new("acme", Cloud::Kubernetes, "kubernetes").on_response(
3664                |_, response| {
3665                    response.body = r#"{"metadata":{"name":"other"}}"#.to_string();
3666                    Ok(())
3667                },
3668            ),
3669        )
3670        .await;
3671        let response = reqwest::Response::from(
3672            http::Response::builder()
3673                .status(200)
3674                .header("content-type", "application/json")
3675                .body(r#"{"metadata":{"name":"web"}}"#)
3676                .unwrap(),
3677        );
3678        let error = hook.apply(response).await.unwrap_err();
3679        assert!(!error.retryable);
3680        assert_fails_naming(error, "acme");
3681    }
3682
3683    /// The cloud already acted on the call when `modify_response` runs, so a failure there is
3684    /// final even when the hook marked it retryable: a retry would create the resource twice.
3685    #[tokio::test]
3686    async fn a_failed_modify_response_is_never_sent_again() {
3687        use crate::request_utils::InterceptedRequestBuilder;
3688        use crate::testing::capture;
3689
3690        let server = capture::start(|_| capture::Reply::new(200, "application/json", "{}")).await;
3691        let client = reqwest::Client::new();
3692        let mut request = client
3693            .post(format!("{}/servers", server.base_url))
3694            .body("{}")
3695            .build()
3696            .unwrap();
3697        let hook = chain(vec![TestInterceptor::new(
3698            "acme",
3699            Cloud::Azure,
3700            "management",
3701        )
3702        .on_response(|_, _| {
3703            let mut deadline = failed(
3704                "acme",
3705                "its hook 'h' failed (HOOK_DEADLINE_EXCEEDED)".into(),
3706            );
3707            deadline.retryable = true;
3708            Err(deadline)
3709        })])
3710        .intercept(Cloud::Azure, "management", &mut request)
3711        .unwrap();
3712
3713        let error = InterceptedRequestBuilder::new(
3714            reqwest::RequestBuilder::from_parts(client, request),
3715            hook,
3716        )
3717        .with_retry()
3718        .send_json::<serde_json::Value>()
3719        .await
3720        .unwrap_err();
3721        assert_eq!(error.code, "INTERCEPTOR_FAILED");
3722        assert!(!error.retryable);
3723        assert_eq!(server.requests().len(), 1);
3724    }
3725
3726    /// A 2xx means the cloud acted on the call, so a body that breaks off after it is not
3727    /// retried through the interceptors either.
3728    #[tokio::test]
3729    async fn success_body_read_failure_does_not_replay_an_intercepted_mutation() {
3730        use crate::request_utils::InterceptedRequestBuilder;
3731        use backon::ExponentialBuilder;
3732        use std::sync::atomic::{AtomicUsize, Ordering};
3733        use std::time::Duration;
3734        use tokio::io::{AsyncBufReadExt, AsyncWriteExt};
3735
3736        let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
3737            .await
3738            .expect("listen");
3739        let address = listener.local_addr().expect("address");
3740        let requests = Arc::new(AtomicUsize::new(0));
3741        let seen = requests.clone();
3742        let server = tokio::spawn(async move {
3743            loop {
3744                let (mut stream, _) = listener.accept().await.expect("accept");
3745                {
3746                    let mut reader = tokio::io::BufReader::new(&mut stream);
3747                    loop {
3748                        let mut line = String::new();
3749                        assert!(reader.read_line(&mut line).await.expect("request header") > 0);
3750                        if line == "\r\n" {
3751                            break;
3752                        }
3753                    }
3754                }
3755                seen.fetch_add(1, Ordering::SeqCst);
3756                stream
3757                    .write_all(
3758                        b"HTTP/1.1 200 OK\r\nContent-Length: 10\r\nConnection: close\r\n\r\nshort",
3759                    )
3760                    .await
3761                    .expect("response");
3762                stream.shutdown().await.expect("close response");
3763            }
3764        });
3765
3766        let client = reqwest::Client::builder()
3767            .no_proxy()
3768            .timeout(Duration::from_secs(5))
3769            .build()
3770            .expect("client");
3771        let mut request = client
3772            .post(format!("http://{address}/servers"))
3773            .build()
3774            .unwrap();
3775        let hook = chain(vec![TestInterceptor::new(
3776            "acme",
3777            Cloud::Azure,
3778            "management",
3779        )])
3780        .intercept(Cloud::Azure, "management", &mut request)
3781        .unwrap();
3782        assert!(hook.is_some(), "the interceptor matched");
3783
3784        let error = InterceptedRequestBuilder::new(
3785            reqwest::RequestBuilder::from_parts(client, request),
3786            hook,
3787        )
3788        .with_retry()
3789        .backoff(
3790            ExponentialBuilder::default()
3791                .with_min_delay(Duration::from_millis(1))
3792                .with_max_delay(Duration::from_millis(1))
3793                .with_max_times(2),
3794        )
3795        .send_no_response()
3796        .await
3797        .expect_err("a truncated body fails the call");
3798        assert_eq!(
3799            requests.load(Ordering::SeqCst),
3800            1,
3801            "the mutation was sent again"
3802        );
3803        assert_eq!(error.code, "HTTP_RESPONSE_BODY_READ_FAILED", "{error}");
3804        assert!(!error.retryable);
3805        assert!(matches!(
3806            error.error,
3807            Some(ErrorData::HttpResponseBodyReadFailed { http_status: 200 })
3808        ));
3809        server.abort();
3810    }
3811
3812    #[test]
3813    fn a_wrapper_keeps_an_interceptor_failure_final() {
3814        let wrapped: Result<()> =
3815            Err(failed("acme", "refused".to_string())).context(ErrorData::HttpRequestFailed {
3816                message: "GetObject request failed".to_string(),
3817            });
3818        assert!(wrapped.as_ref().unwrap_err().retryable);
3819        assert!(
3820            !keep_interceptor_failure_final(wrapped)
3821                .unwrap_err()
3822                .retryable
3823        );
3824
3825        let mut deadline = failed(
3826            "acme",
3827            "its hook 'h' failed (HOOK_DEADLINE_EXCEEDED)".into(),
3828        );
3829        deadline.retryable = true;
3830        let wrapped: Result<()> = Err(deadline).context(ErrorData::HttpRequestFailed {
3831            message: "GetObject request failed".to_string(),
3832        });
3833        assert!(
3834            keep_interceptor_failure_final(wrapped)
3835                .unwrap_err()
3836                .retryable,
3837            "an interceptor's own retryable failure stays retryable"
3838        );
3839
3840        let network: Result<()> = Err(AlienError::new(ErrorData::HttpRequestFailed {
3841            message: "connection reset".to_string(),
3842        }));
3843        assert!(
3844            keep_interceptor_failure_final(network)
3845                .unwrap_err()
3846                .retryable
3847        );
3848    }
3849
3850    #[test]
3851    fn a_client_with_interceptors_signs_only_for_its_endpoint() {
3852        let endpoint = "https://management.azure.com";
3853        let elsewhere = Url::parse("https://evil.example.com/operations/1").unwrap();
3854        assert!(InterceptorChain::default()
3855            .check_destination(&elsewhere, endpoint)
3856            .is_ok());
3857
3858        let interceptors = chain(vec![TestInterceptor::new(
3859            "acme",
3860            Cloud::Azure,
3861            "management",
3862        )]);
3863        let error = interceptors
3864            .check_destination(&elsewhere, endpoint)
3865            .unwrap_err();
3866        assert_eq!(error.code, "DESTINATION_REFUSED");
3867        assert!(!error.retryable);
3868        interceptors
3869            .check_destination(
3870                &Url::parse("https://management.azure.com/subscriptions/s/operations/1").unwrap(),
3871                endpoint,
3872            )
3873            .unwrap();
3874    }
3875}