Skip to main content

rustango_cms/
cache_cloudfront.rs

1//! AWS CloudFront invalidator for [`crate::cache_invalidate::PageCacheInvalidator`].
2//!
3//! Wires the per-page cache-invalidation hook to CloudFront's
4//! [CreateInvalidation] API. After a CMS save, the public path is
5//! dropped from every edge POP in the distribution so the next
6//! request regenerates against the freshly-saved markup instead
7//! of the cached version.
8//!
9//! ## Usage
10//!
11//! Behind the `cache_cloudfront` feature. The minimum config is
12//! the distribution id; credentials come from the standard AWS
13//! config chain (env vars, shared credentials file, IRSA / IMDS
14//! when running on EKS/EC2, etc.):
15//!
16//! ```ignore
17//! use rustango_cms::cache_cloudfront::CloudFrontInvalidator;
18//!
19//! // `from_env_distribution` resolves AWS credentials from the
20//! // standard provider chain and builds the client. async because
21//! // the SDK's config loader does an `imds` lookup on EC2/EKS.
22//! let inv = CloudFrontInvalidator::from_env_distribution(
23//!     std::env::var("CLOUDFRONT_DISTRIBUTION_ID").unwrap(),
24//! ).await;
25//!
26//! let router = rustango_cms::admin::router_with_invalidator(
27//!     tera.clone(),
28//!     std::sync::Arc::new(inv),
29//! );
30//! ```
31//!
32//! ## Permissions
33//!
34//! The IAM principal (user / role) the SDK resolves to must carry:
35//!
36//! ```text
37//! cloudfront:CreateInvalidation
38//! ```
39//!
40//! scoped to the target distribution. The role-based assumption
41//! flow (the `role_arn` field) is satisfied by setting
42//! `AWS_ROLE_ARN` + `AWS_WEB_IDENTITY_TOKEN_FILE` in the
43//! environment — the SDK picks them up automatically. Hand-rolled
44//! AssumeRole is a follow-up; the env-driven flow covers EKS IRSA
45//! + most CI runners.
46//!
47//! ## Failure mode
48//!
49//! Logged through `tracing` at WARN; the calling admin handler
50//! doesn't propagate the error (cache invalidation is best-effort
51//! by trait contract — a stale render is worse than a failed save).
52//!
53//! [CreateInvalidation]: https://docs.aws.amazon.com/AmazonCloudFront/latest/APIReference/API_CreateInvalidation.html
54
55use std::sync::Arc;
56
57use async_trait::async_trait;
58
59use crate::cache_invalidate::PageCacheInvalidator;
60
61/// CloudFront-backed page-cache invalidator. Holds the resolved
62/// SDK client + the target distribution id. Built via
63/// [`Self::from_env_distribution`] (recommended) or
64/// [`Self::with_client`] for tests / hand-rolled config.
65pub struct CloudFrontInvalidator {
66    distribution_id: String,
67    client: Arc<aws_sdk_cloudfront::Client>,
68}
69
70impl CloudFrontInvalidator {
71    /// Resolve AWS credentials from the standard provider chain
72    /// (env vars → shared credentials file → IMDS / IRSA) and
73    /// build a CloudFront client targeting `distribution_id`.
74    ///
75    /// async because the credential chain does network I/O on
76    /// EC2 / EKS to fetch instance / pod credentials. Call once
77    /// at boot, share the resulting `Arc<CloudFrontInvalidator>`
78    /// across the admin router.
79    pub async fn from_env_distribution(distribution_id: impl Into<String>) -> Self {
80        // `load_defaults(BehaviorVersion::latest())` replaces the
81        // pre-1.0 `load_from_env`; same provider chain, just
82        // pinned to a stable behaviour version so future SDK
83        // upgrades don't silently flip default knobs.
84        let cfg = aws_config::load_defaults(aws_config::BehaviorVersion::latest()).await;
85        let client = aws_sdk_cloudfront::Client::new(&cfg);
86        Self {
87            distribution_id: distribution_id.into(),
88            client: Arc::new(client),
89        }
90    }
91
92    /// Build an invalidator from a pre-configured SDK client. Use
93    /// when the host already loaded an `aws_config::SdkConfig` for
94    /// other AWS calls and wants to reuse it. Tests use this with
95    /// a mock client.
96    #[must_use]
97    pub fn with_client(
98        distribution_id: impl Into<String>,
99        client: aws_sdk_cloudfront::Client,
100    ) -> Self {
101        Self {
102            distribution_id: distribution_id.into(),
103            client: Arc::new(client),
104        }
105    }
106
107    /// Submit a `CreateInvalidation` for the provided path. The
108    /// `CallerReference` is timestamp-based so retried submissions
109    /// from a flaky network don't collapse into one CloudFront
110    /// request (CF dedups identical references for 8 hours).
111    async fn invalidate(&self, path: &str) {
112        // CloudFront paths must start with `/`. The trait contract
113        // already has callers pass url_paths with a leading slash,
114        // but normalise defensively so a missing one doesn't get a
115        // 400 from the SDK.
116        let normalised = if path.starts_with('/') {
117            path.to_owned()
118        } else {
119            format!("/{path}")
120        };
121        // Reference must be unique per invalidation; use a coarse
122        // timestamp + the path so retries with the same path-and-
123        // second collapse (acceptable — same purge) but distinct
124        // paths or times don't.
125        let caller_ref = format!(
126            "rcms-{}-{}",
127            std::time::SystemTime::now()
128                .duration_since(std::time::UNIX_EPOCH)
129                .map(|d| d.as_secs())
130                .unwrap_or(0),
131            normalised.replace(['/', '?', '&'], "_"),
132        );
133        let batch = aws_sdk_cloudfront::types::InvalidationBatch::builder()
134            .caller_reference(caller_ref)
135            .paths(
136                aws_sdk_cloudfront::types::Paths::builder()
137                    .quantity(1)
138                    .items(normalised.clone())
139                    .build()
140                    .expect("paths build never fails — quantity matches items"),
141            )
142            .build();
143        let batch = match batch {
144            Ok(b) => b,
145            Err(e) => {
146                tracing::warn!(
147                    target: "rustango_cms::cache_invalidate",
148                    error = %e,
149                    path = %normalised,
150                    "cloudfront: invalidation batch build failed"
151                );
152                return;
153            }
154        };
155        let req = self
156            .client
157            .create_invalidation()
158            .distribution_id(&self.distribution_id)
159            .invalidation_batch(batch);
160        match req.send().await {
161            Ok(out) => {
162                tracing::debug!(
163                    target: "rustango_cms::cache_invalidate",
164                    invalidation_id = ?out.invalidation().map(|i| i.id()),
165                    path = %normalised,
166                    "cloudfront invalidation submitted"
167                );
168            }
169            Err(e) => {
170                tracing::warn!(
171                    target: "rustango_cms::cache_invalidate",
172                    error = %e,
173                    path = %normalised,
174                    distribution = %self.distribution_id,
175                    "cloudfront: CreateInvalidation failed"
176                );
177            }
178        }
179    }
180}
181
182#[async_trait]
183impl PageCacheInvalidator for CloudFrontInvalidator {
184    async fn invalidate_url(&self, _tenant: &rustango::tenancy::TenantSlug, url_path: &str) {
185        // Distribution targeting is per-process; the tenant slug
186        // doesn't gate which distribution receives the purge. Hosts
187        // that need per-tenant distributions can build one
188        // CloudFrontInvalidator per tenant + dispatch in their own
189        // PageCacheInvalidator wrapper.
190        self.invalidate(url_path).await;
191    }
192
193    async fn invalidate_subtree(&self, _tenant: &rustango::tenancy::TenantSlug, url_path: &str) {
194        // CloudFront accepts wildcards in invalidation paths — a
195        // `/blog/*` invalidation drops every cached entry under
196        // `/blog/`. That's the right shape for slug-rename / move
197        // cascades, which is the dominant subtree-purge case in
198        // the CMS.
199        let trimmed = url_path.trim_end_matches('/');
200        let wildcard = format!("{trimmed}/*");
201        // Also include the parent path so the moved-page's own
202        // cached entry purges alongside its descendants.
203        self.invalidate(url_path).await;
204        self.invalidate(&wildcard).await;
205    }
206}
207
208#[cfg(test)]
209mod tests {
210    use super::*;
211
212    /// CloudFront's SDK doesn't ship a built-in mock client — unlike
213    /// the HTTP-based backends where httpmock makes the test trivial,
214    /// we'd need `aws-smithy-mocks` (separate crate, heavier) to
215    /// exercise the real request shape. For now the helper-level
216    /// behaviours (path normalisation, subtree wildcard shape) cover
217    /// what's most likely to regress.
218    ///
219    /// Live exercising of the SDK call path is something hosts can
220    /// run against a real distribution with cargo run-mode; the
221    /// failure mode (4xx / 5xx → tracing::warn) is symmetric with
222    /// the existing Cloudflare backend that DOES have httpmock
223    /// coverage, so the contract is consistent.
224
225    /// The leading-slash normalisation is a sync substring operation
226    /// — extract just enough of the invalidate() body to test
227    /// without juggling a fake SDK client.
228    fn normalise_path(path: &str) -> String {
229        if path.starts_with('/') {
230            path.to_owned()
231        } else {
232            format!("/{path}")
233        }
234    }
235
236    #[test]
237    fn normalise_adds_leading_slash() {
238        assert_eq!(normalise_path("blog/post"), "/blog/post");
239    }
240
241    #[test]
242    fn normalise_keeps_existing_slash() {
243        assert_eq!(normalise_path("/about"), "/about");
244    }
245
246    #[test]
247    fn subtree_wildcard_shape() {
248        // Mirrors the inline construction in `invalidate_subtree`.
249        let url_path = "/blog/";
250        let trimmed = url_path.trim_end_matches('/');
251        let wildcard = format!("{trimmed}/*");
252        assert_eq!(wildcard, "/blog/*");
253    }
254
255    #[test]
256    fn subtree_wildcard_no_trailing_slash() {
257        // Slug-rename cascades pass `/blog` (no trailing slash);
258        // the wildcard should still come out as `/blog/*`.
259        let url_path = "/blog";
260        let trimmed = url_path.trim_end_matches('/');
261        let wildcard = format!("{trimmed}/*");
262        assert_eq!(wildcard, "/blog/*");
263    }
264
265    #[test]
266    fn caller_reference_contains_path() {
267        // CloudFront dedups identical caller_references for 8 hours,
268        // so the reference must include the path. The body-call
269        // form uses `path.replace(['/', '?', '&'], '_')`.
270        let path = "/blog/post?draft=1&v=2";
271        let safe = path.replace(['/', '?', '&'], "_");
272        assert_eq!(safe, "_blog_post_draft=1_v=2");
273        // The full reference shape is `rcms-{secs}-{safe}` — the
274        // secs is non-deterministic in a unit test, just confirm
275        // the safe-path component renders without collision.
276        assert!(safe.contains("blog_post"));
277        assert!(!safe.contains('?'));
278        assert!(!safe.contains('&'));
279    }
280}