Skip to content

feat(cache): add S3-compatible origin backend (#437) - #471

Merged
thiras merged 4 commits into
mainfrom
feat/origin-s3
May 8, 2026
Merged

thiras merged 4 commits into
mainfrom
feat/origin-s3

Conversation

@thiras

@thiras thiras commented May 7, 2026 •

Copy link
Copy Markdown
Contributor

Depends on #463 — merge after that lands. #463 is PR1 of the same #437 series (the breaking [cache.origin] schema change). This branch carries an equivalent commit (54779b9) as its base; once #463 is merged to main, that commit will drop cleanly on rebase and only the PR2 / PR3 / test-backfill commits will remain.

Closes #437.

Adds a first-class S3 origin backend (AWS S3 / Cloudflare R2 / Backblaze B2 / MinIO) alongside the existing http and fs backends. Selection is via the tagged [cache.origin] kind = "http"|"fs"|"s3" table this PR also introduces.

Summary

  • PR1 — feat(config)! (54779b9): replace flat cache.origin_url / cache.origin_path / cache.decompress with tagged [cache.origin]. Adds deny_unknown_fields everywhere so legacy configs and typos (decompres = "auto") fail at load with a clear error instead of silently becoming "no origin configured." Adds SecretString newtype for credentials (Debug → "***", Serialize → deterministic non-cryptographic hash for SIGHUP-time diff detection without cleartext exposure), per-rule AWS bucket-name validation, full resolve_s3_origin (region/endpoint/prefix shape, control-char rejection, path_style: Option<bool> collapse). The S3 variant is recognised by the schema but rejected at startup by build_cache with an operator-greppable placeholder. This is a breaking config change — flat fields are gone.
  • PR2 — feat(cache) (49ce2c0): wires the S3 arm to a real backend via aws-sdk-s3 (pinned at =1.129.0; 1.130 bumps to sha2 ^0.11 which conflicts with iroh-base 0.98's exact pin). Hyper-1 + rustls 0.23 + aws-lc-rs explicitly — single TLS stack across the workspace, no rustls-0.21+ring parallel. Errors land in the existing OriginPullError taxonomy (NoSuchKey/404 → NotFound, 5xx/408/429 → Transient, others → Permanent). Same {prefix?}{hex[..2]}/{hex} sharded layout as FilesystemOrigin so blobs aws s3 sync 1:1 between the two.
  • PR3 — fix(cache) (62ed1ea): multi-agent review fixes. Critical: bare-404 no longer silently masks NoSuchBucket/AccessDenied; S3Credentials Debug no longer leaks cleartext (manual impl mirroring SecretString); SDK internal retry disabled so cache.origin_retry is the single retry budget (was producing up to 12 dispatches per logical fetch). Plus error-source-chain preservation, catch-all SdkError warn-logging, empty-static-credential rejection, and a stack of doc precision fixes.
  • Test backfill (8790424, 8071066, 23bd93f): closes coverage gaps from PR1/PR2 review (env-var substitution on every S3 field including the no-cleartext-on-error invariant, serde-tagged-enum rejection shapes, S3 credential round-trip, tilde expansion, doc-only corrections to DefaultHasher / SecretString / ResolvedS3Config invariants).

Final state: 577 tests pass; cargo build/clippy/fmt/nextest/deny/doc all clean.

Breaking change

Flat cache.origin_url, cache.origin_path, and cache.decompress fields, plus the --origin-url / --origin-path flags and their env vars, are removed. Operators must migrate to:

[cache.origin]
kind = "http"           # or "fs" or "s3"
url = "https://..."     # http only
# path = "/srv/blobs"   # fs
# bucket/region/...     # s3

Origin selection is now config-only — S3 has too many fields to fit cleanly on a CLI, and keeping all three backends file-only avoids CLI-vs-TOML mismatch silently picking the wrong backend.

Follow-ups (not in this PR)

  • Per-backend metrics labels (backend = "http" | "fs" | "s3").
  • Content-Encoding decompression reuse from HttpOrigin::decompress_body (today, non-identity encoding from S3 is rejected as Permanent with an operator-actionable message).
  • Real-S3 integration test gated on DECDN_S3_TEST_ENDPOINT.

Test plan

  • cargo build --workspace clean
  • cargo clippy --workspace --all-targets -- -D warnings clean
  • cargo fmt -- --check clean
  • cargo nextest run --workspace — 577 tests pass
  • cargo deny check clean
  • cargo doc --workspace --no-deps clean
  • Manual: decdn config validate against an S3 TOML fixture (regression-locked by a test)
  • Manual: smoke against MinIO (endpoint_url + path_style = true) — covered by construction tests but worth a live run before merge

🤖 Generated with Claude Code

Copilot AI review requested due to automatic review settings May 7, 2026 22:40

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request introduces an S3-compatible origin backend for the cache service, enabling blob retrieval from S3, R2, B2, and MinIO. It refactors the cache configuration to use a tagged [cache.origin] table, replacing the previous flat fields, and adds robust validation and secret redaction for S3 credentials. My review highlights a potential OOM vulnerability due to non-streaming body collection and suggests renaming a misleading hash prefix in the secret serialization logic to improve accuracy and clarity.

Comment thread crates/cache/src/origin/s3.rs Resolved
Comment thread crates/common/src/config/secret.rs Resolved

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Adds an S3-compatible cache origin backend and migrates cache-origin configuration from legacy flat fields to a tagged [cache.origin] enum, with stronger config validation/redaction and new test coverage.

Changes:

  • Introduces kind = "http" | "fs" | "s3" under [cache.origin] (removing cache.origin_url, cache.origin_path, and cache.decompress plus their CLI flags).
  • Implements decdn_cache::S3Origin (AWS SDK) with error classification into existing OriginPullError taxonomy and retry-budget alignment.
  • Adds SecretString for config-borne secrets (redacted Debug, hashed Serialize) and expands tests/docs/changelog for the new schema/backend.

Reviewed changes

Copilot reviewed 18 out of 19 changed files in this pull request and generated 6 comments.

Show a summary per file
File Description
crates/node/tests/sighup_signal.rs Updates resolved-config test fixture for new cache.origin shape.
crates/node/src/runtime/reload.rs Updates reload fixtures/tests to use cache.origin: Option<...>.
crates/node/src/runtime/mod.rs Wires runtime cache construction to new origin enum and adds S3 construction tests/log labels.
crates/common/src/config/types.rs Defines new tagged [cache.origin] schema including S3 and credential types; adds deny_unknown_fields.
crates/common/src/config/secret.rs Adds SecretString newtype for redacted debug + hashed serialization.
crates/common/src/config/resolved.rs Replaces flat resolved origin fields with ResolvedOrigin + resolved S3 types.
crates/common/src/config/mod.rs Resolves/validates tagged origin variants, adds env-var expansion for all origin fields, and S3 validators.
crates/common/src/cli/run.rs Removes --origin-url/--origin-path CLI flags and documents config-only origin selection.
crates/common/Cargo.toml Adds serde_json dev-dep for SecretString serialization tests.
crates/cli/tests/config_validate.rs Updates CLI-side resolved-config fixture for new origin field.
crates/cache/tests/s3_origin.rs Adds integration tests for S3Origin using aws-smithy-mocks.
crates/cache/src/origin/s3.rs Implements the S3 origin backend and its error classification logic.
crates/cache/src/origin/mod.rs Exposes the new S3 origin module and updates origin module docs.
crates/cache/src/origin/fs.rs Updates error messages to match new config key names (cache.origin.path).
crates/cache/src/lib.rs Re-exports S3 origin types from the cache crate.
crates/cache/Cargo.toml Adds AWS SDK dependencies and S3 mocks for tests.
CHANGELOG.md Documents breaking config/CLI changes and the new S3 origin backend.
Cargo.toml Adds/pins AWS SDK workspace dependencies and documents TLS stack rationale.
Cargo.lock Locks new AWS SDK dependency graph and related transitive changes.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread crates/cache/src/origin/s3.rs Resolved
Comment thread crates/cache/src/origin/s3.rs Resolved
Comment thread crates/cache/src/origin/s3.rs Resolved
Comment thread crates/node/src/runtime/mod.rs Resolved
Comment thread crates/node/src/runtime/mod.rs Resolved
Comment thread crates/common/src/config/mod.rs Resolved
@github-actions

github-actions Bot commented May 7, 2026 •

Copy link
Copy Markdown

Coverage report

Total: 86.89% (was 86.54%, ▲ +0.35%) — 10408/11978 lines

File Coverage Lines Δ
crates/cache/src/origin/s3.rs 90.91% 340/374 new
crates/common/src/config/mod.rs 96.18% 2975/3093 ▼ 0.06%
crates/common/src/config/secret.rs 95.59% 65/68 ● 0.00%
crates/node/src/runtime/mod.rs 51.33% 329/641 ▲ +10.37%
History
Commit Total Δ vs base
700595f (HEAD) 86.89% ▲ +0.35%

@thiras thiras changed the title feat(cache): S3-compatible origin backend (#437) feat(cache): add S3-compatible origin backend (#437) May 7, 2026
thiras added a commit that referenced this pull request May 7, 2026
…437)

Two of the actionable items from the multi-agent PR #471 review:

1. **Rename `SecretString::Serialize` prefix `sha:` → `hash:`.**
   The hashed-redaction emitted by `SecretString` uses `DefaultHasher`
   (SipHash-1-3 in current std), not any SHA family — calling it
   `sha:` was a misleading shorthand. Renamed to the algorithm-neutral
   `hash:` and pinned the rationale in a comment on the format string
   so a future contributor doesn't re-introduce a SHA reference. The
   format is intra-process only (compared structurally in
   `runtime::reload::FileSectionSnapshot`, never persisted), so no
   cross-version compatibility concern.

   Updates: module doc, the `Serialize` impl, and the
   `serialize_redacts_secret_value` test assertion.

2. **`runtime::tests::cfg_with_origin` now uses `tempfile::tempdir()`
   per test instead of a pid-keyed shared directory.** Under
   `cargo nextest` (the project's stated test runner) the prior
   `format!("decdn-build-cache-test-{pid}")` was unique-per-test, but
   `cargo test` (used by some local devs) shares the process across
   tests in a binary and would race two parallel callers on the same
   `cache_dir` inside `CacheEngine::open_full`. The helper now returns
   `(TempDir, ResolvedConfig)` so each caller binds the temp directory
   to a `_tmp` local that lives until end-of-test.

Verification: cargo build / clippy / fmt / nextest (400 tests in the
affected crates pass, including the two `build_cache_constructs_s3_*`
tests that exercised `cfg_with_origin`) all clean.

Not-fixed items from the review (replies on the PR thread explain):
- 4× Copilot use-after-move / temp-across-await claims on `s3.rs`
  match arms and `runtime::mod.rs:572` are false positives — the `_`
  patterns don't move out of `err`, and Rust's temporary-lifetime
  rules keep the `S3OriginConfig` alive across the `.await`.
  `cargo check --workspace --all-targets` is clean.
- Gemini's OOM-on-`collect()` concern is real but already mitigated
  via the SDK-side `Content-Length` pre-check and the post-collect
  cap (max_blob_size_mb, default 1 GB). Streaming with a running
  cap is a follow-up matching `HttpOrigin`'s same design — pinned
  in the PR description's follow-ups list.
- Copilot's `expand_origin` doc claim is correct as written:
  `expand_value` performs both `\${VAR}` and leading-`~` expansion
  (see `expand_tilde_prefix` at `mod.rs:1149`), so the doc isn't
  misleading.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
thiras added a commit that referenced this pull request May 7, 2026
Three small wins surfaced by the comprehensive review pass on PR #471
(comment-analyzer, type-design-analyzer, pr-test-analyzer). All
changes are low-risk: stale comments, one resolver normalization, and
expanded coverage on the resolver-to-runtime conversion seam.

1. **`DefaultChain { profile = "" }` → `None` at the resolver.** A
   `${PROFILE}` env-var that resolved to empty (or a literal empty
   TOML value) would land at the SDK as `loader.profile_name("")`,
   surfacing as a confusing "profile '' not found" only at first
   credential need. The resolver now collapses empty to `None` so the
   runtime's `loader.profile_name(...)` arm fires only for a real
   name. New test:
   `resolve_cache_origin_s3_default_chain_empty_profile_collapses_to_none`.

2. **Pin `region` and `endpoint_url` field-equivalence on the
   `s3_origin_config_from_resolved` seam, and add a sibling test
   for the `DefaultChain` arm.** The conversion uses field access
   rather than destructuring, so a new field added to one side and
   forgotten on the other isn't a compile error. The existing
   `*_preserves_static_credentials` test only locked `bucket` /
   `path_style` / `prefix` / `Static` credentials; this commit
   adds:
   - `region` + `endpoint_url` assertions in the Static test;
   - new `s3_origin_config_from_resolved_preserves_default_chain`
     covering the `DefaultChain { profile }` arm + `endpoint_url:
     None` + `path_style: false` (the AWS / R2 default).

3. **Comment rot: stale "PR1 / PR2 lands later" + `BehaviorVersion`
   panic-vs-error wording.** PR2 has shipped (this PR is the
   merge target). Updated:
   - `crates/cache/tests/s3_origin.rs:531-534` — "SDK still has its
     own internal retries" claim was the opposite of reality
     (`mock_s3_client` calls `RetryConfig::disabled()`); rewritten
     to match.
   - `crates/cache/src/origin/s3.rs:660-663` — "panic from the SDK
     config builder" softened to "Err … failing this test's
     `.expect`", matching the post-correction wording on
     `S3Origin::new`.
   - `crates/node/src/runtime/mod.rs:989-997` — `BehaviorVersion`
     "panic" → "missing runtime error" for the same reason.
   - `crates/common/src/config/mod.rs` — six sites referring to
     "PR1 / PR2" or "PR2 onward" rewritten to present tense; the
     S3 test-section header reframed to drop the future-tense
     framing of the runtime backend (which now ships in this PR).
   - `crates/common/src/config/types.rs` — `region` and
     `DefaultChain.profile` doc comments dropped the "wired in
     the follow-up PR" / "Once the S3 backend is wired (PR2)"
     parentheticals.
   - `Cargo.toml` — `sha2` pin rationale clarified. The lockfile
     already carries 0.10.9 alongside `=0.11.0-rc.5`; the pin
     prevents adding a *third* (stable 0.11.x), not "two majors
     would otherwise live in the tree".

Verification: cargo build / clippy / fmt / nextest (402 tests in
the affected crates pass, including the three new ones) all clean.

Items reviewed and intentionally NOT changed (with rationale):
- `S3Origin::from_parts` is `pub + #[doc(hidden)]` for cross-crate
  integration test access — standard idiom, documented inline.
  Code-reviewer agreed; silent-failure-hunter's "footgun" framing
  doesn't account for the doc-hidden semver convention.
- 4× Copilot use-after-move + temp-across-await claims on the
  prior commit are false positives; `cargo check --all-targets`
  is clean.
- `#[non_exhaustive]` on the new types would force `decdn-node`
  to add wildcard arms when matching `ResolvedOrigin`, which is
  a regression — the current "compile-error on new variant"
  property is a feature for a workspace-internal sum type.
- STS `ExpiredToken` 403 classification: Permanent is defensible
  for `Static { session_token }` (retry can't help) and largely
  unreached for `DefaultChain` (the SDK's credentials cache
  proactively refreshes on TTL). Filed as a follow-up rather
  than a blocking change.
- Test coverage gaps on `SdkError` variant arms (TimeoutError,
  DispatchFailure, ConstructionFailure, ResponseError, _ catch-
  all, body-collect mid-stream): real but mechanical to add via
  `aws-smithy-mocks`. Tracked for a follow-up; the arms are
  short and well-typed so regression risk in this PR is low.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
thiras and others added 4 commits May 8, 2026 14:48
Wires the S3 arm of `[cache.origin]` to a real backend over the official
`aws-sdk-s3`. Keys follow the same `{prefix?}{hex[..2]}/{hex}` sharded
layout as `FilesystemOrigin` so blobs `aws s3 sync` 1:1 between the two
origins. Supports plain AWS S3, Cloudflare R2, Backblaze B2, MinIO, and
any other S3-compatible service via the existing `endpoint_url` /
`path_style` knobs from PR1.

The SDK is wired with `default-features = false` and an explicit
`aws-smithy-http-client` (hyper-1 + rustls 0.23 + aws-lc-rs) so the
workspace stays on a single TLS implementation — no rustls 0.21 + ring
parallel stack. `BehaviorVersion::latest()` is set explicitly at the
call site even though `aws-config`'s `behavior-version-latest` feature
implies it, as belt-and-braces against the SDK's only construction-path
panic.

Errors land in the existing `OriginPullError` taxonomy:
* `NoSuchKey` (and bare HTTP 404) → `OriginFetch::NotFound`
* 5xx / 408 / 429 → `Transient` (after the SDK's own retry budget)
* Other 4xx, `ConstructionFailure`, `ResponseError` → `Permanent`
* `TimeoutError` / `DispatchFailure` → `Transient`
* `Content-Encoding` other than identity → `Permanent` with an
  operator-actionable message (decompression reuse from `HttpOrigin`
  is a follow-up).

Test coverage:
* 5 unit tests (`origin/s3.rs`): key-layout invariants, status
  classification, both credential variants construct without I/O.
* 11 integration tests (`tests/s3_origin.rs`): operation-level mocks
  via `aws-smithy-mocks` cover happy path, `NoSuchKey` + bare 404,
  5xx-then-success driving SDK retry, 4xx fail-fast (with
  `num_calls() == 1` pinning the no-retry contract),
  Content-Encoding gzip rejection with the operator-friendly
  message, identity passthrough, oversize-body cap, prefix +
  sharded-key layout, end-to-end `CacheEngine` miss-then-cache,
  and end-to-end `NotFound` propagation.
* 3 node-runtime tests: `build_cache` constructs the S3 backend
  for both credential variants, plus a direct unit test on the
  `ResolvedS3Config -> S3OriginConfig` conversion that pins
  `SecretString::expose` survival of static credentials through
  the seam.

aws-sdk-s3 pinned at =1.129.0 (last release on sha2 ^0.10): 1.130
bumped to sha2 ^0.11 stable, which conflicts with iroh-base 0.98's
`=0.11.0-rc.5` exact pin. Re-evaluate when iroh moves off the rc.

Cargo lock churn is sizeable (~50 new transitive crates). The TLS
layer stays on one implementation; a small hyper-0.14 transitive
subtree (`hyper`, `h2`, `http`, `http-body`, `socket2`) does land
because `aws-smithy-runtime` enables `connector-hyper-0-14-x` on
its dep — that's not an active code path at runtime but cargo
unifies features across the graph and we can't disable a flag set
by a transitive crate. Documented inline in the workspace
Cargo.toml.

Follow-ups (not in this PR):
* Per-backend metrics labels (`backend = "http" | "fs" | "s3"`).
* Content-Encoding decompression reuse from `HttpOrigin::decompress_body`.
* Real-S3 integration test gated on `DECDN_S3_TEST_ENDPOINT`.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…ebug leak (#437)

CRITICAL fixes from the multi-agent PR review:

1. **Bare HTTP 404 no longer silently masks IAM/bucket misconfigurations.**
   `classify_get_object_error` now inspects the AWS error code via
   `ProvideErrorMetadata::code()` before falling back to NotFound:
   only empty / `NoSuchKey` / synthetic `NotFound` map to
   `OriginFetch::NotFound`. A 404 with `NoSuchBucket` (typo'd config)
   or `AccessDenied` (missing `s3:ListBucket` IAM grant — AWS returns
   404 instead of 403 to avoid leaking object existence) now surfaces
   as `Permanent` with the AWS error code visible in the chain. New
   integration tests cover both NoSuchBucket and AccessDenied 404
   cases.

2. **`S3Credentials` Debug now redacts cleartext credentials.** The
   derived `Debug` would have leaked access-key / secret-key /
   session-token bytes through any incidental `tracing::debug!(?cfg)`
   or panic backtrace — `s3_origin_config_from_resolved` strips the
   `SecretString` wrapper at the crate boundary and the cache crate
   can't depend on it (would be circular). Added manual `Debug` impls
   on both `S3Credentials::Static` and `S3OriginConfig` mirroring the
   `SecretString::Debug` pattern (`"***"` placeholders, variant tag
   preserved). Three new unit tests pin the redaction contract:
   direct, when nested in `S3OriginConfig`, and that `DefaultChain`'s
   profile name (operator-set, non-secret) still appears.

3. **SDK internal retry disabled — `cache.origin_retry` is the single
   retry budget.** Without this, transient failures got retried twice:
   once by the SDK (default 3 attempts) and again by the cache
   engine's outer `retry_fetch` (default 4 attempts), producing up
   to 12 dispatches per logical fetch on sustained 5xx — not what an
   operator reading `cache.origin_retry.max_retries = 3` expects.
   `S3Origin::new` now sets `RetryConfig::disabled()` on the
   `aws_config::ConfigLoader`. The integration test helpers
   (`mock_s3_client` / `mock_s3_client_match_any`) re-apply the same
   config since they bypass `S3Origin::new` via the `from_parts` test
   seam. Replaces the prior 5xx test that depended on SDK-level retry
   with two cleaner tests: classifier-only single-dispatch transient
   classification, plus an end-to-end engine retry via
   `cache.origin_retry`.

IMPORTANT fixes:

4. **Source chain preserved through error classification.** Replaced
   `anyhow::anyhow!("…{err}")` with `anyhow::Error::from(err).context(…)`
   in `classify_get_object_error` and the body-collect path so the
   underlying `GetObjectError` / `SdkError` / smithy-types body error
   stays in `anyhow::Error::chain()` for tracing exporters and
   future structured downcasts.

5. **Catch-all `SdkError` arm now logs `tracing::warn!`.** Future SDK
   variants we don't yet classify get surfaced as Permanent (safe
   default) but no longer silently — operators see a warn line with
   the variant text so an SDK upgrade introducing a transient-shaped
   variant we should be retrying becomes ticket-actionable.

6. **Empty static credentials rejected at construction.** A hand-built
   `S3OriginConfig` (or a future config-resolver gap) with empty
   `access_key_id` or `secret_access_key` now bails at startup with a
   pointer at `[cache.origin.credentials]` instead of the SDK silently
   accepting them and producing a confusing 403 at first fetch.

Doc / comment fixes:

7. `S3Origin::new` doc no longer claims "performs no network I/O" as an
   absolute — softened to acknowledge the AWS SSO credential provider
   may fire HTTP at first credential need (not at construction). Plus
   softened the `BehaviorVersion` panic claim to acknowledge current
   SDK versions surface a runtime error rather than panic.

8. `from_parts` doc clarifies that `#[doc(hidden)]` only excludes from
   rustdoc — the function is technically callable by downstream crates
   and is part of the semver surface by convention.

9. Body-collect comment expanded to explain why all collect failures
   are conservatively classified as Transient.

10. Wrong `max_blob_size_mb` default ("128 MB") corrected to the actual
    `DEFAULT_MAX_BLOB_SIZE_MB = 1024` (1 GB).

11. Workspace `Cargo.toml` AWS-dep block:
    - Hyper-0.14 transitive subtree attribution corrected: it lands via
      `aws-sdk-s3/test-util` (dev-dep on `decdn-cache`) and
      `aws-smithy-mocks` enabling `aws-smithy-runtime/legacy-test-util`,
      not via `aws-smithy-runtime`'s production defaults. Production
      binary `decdn-node` ships hyper-1 only.
    - SSO credential provider's HTTP-at-first-fetch behavior now
      explicitly noted.

12. Bucket/key log-target rationale tightened — the property is "no
    secrets in the log target" (S3 paths don't carry credentials
    inline), not "operator-chosen" which read as if the key wasn't
    request-derived.

13. Bare-404 test docstring updated to reflect the gating change and
    cross-reference the NoSuchBucket / AccessDenied tests.

New construction tests in `s3.rs`:

- `new_with_endpoint_url_construction_is_pure` — pins the entire
  R2/B2/MinIO path (the PR's headline use case had zero construction
  evidence before).
- `new_with_path_style_true_construction_is_pure` — pins MinIO
  addressing.
- `new_with_named_profile_construction_is_pure` — pins
  `DefaultChain { profile: Some(...) }`.
- `new_rejects_empty_static_credentials` — pins the new defense.

Verification gates: cargo build/clippy/fmt/nextest/deny/doc all clean
across the workspace (577 tests pass, including the 14 new ones).

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…437)

Two of the actionable items from the multi-agent PR #471 review:

1. **Rename `SecretString::Serialize` prefix `sha:` → `hash:`.**
   The hashed-redaction emitted by `SecretString` uses `DefaultHasher`
   (SipHash-1-3 in current std), not any SHA family — calling it
   `sha:` was a misleading shorthand. Renamed to the algorithm-neutral
   `hash:` and pinned the rationale in a comment on the format string
   so a future contributor doesn't re-introduce a SHA reference. The
   format is intra-process only (compared structurally in
   `runtime::reload::FileSectionSnapshot`, never persisted), so no
   cross-version compatibility concern.

   Updates: module doc, the `Serialize` impl, and the
   `serialize_redacts_secret_value` test assertion.

2. **`runtime::tests::cfg_with_origin` now uses `tempfile::tempdir()`
   per test instead of a pid-keyed shared directory.** Under
   `cargo nextest` (the project's stated test runner) the prior
   `format!("decdn-build-cache-test-{pid}")` was unique-per-test, but
   `cargo test` (used by some local devs) shares the process across
   tests in a binary and would race two parallel callers on the same
   `cache_dir` inside `CacheEngine::open_full`. The helper now returns
   `(TempDir, ResolvedConfig)` so each caller binds the temp directory
   to a `_tmp` local that lives until end-of-test.

Verification: cargo build / clippy / fmt / nextest (400 tests in the
affected crates pass, including the two `build_cache_constructs_s3_*`
tests that exercised `cfg_with_origin`) all clean.

Not-fixed items from the review (replies on the PR thread explain):
- 4× Copilot use-after-move / temp-across-await claims on `s3.rs`
  match arms and `runtime::mod.rs:572` are false positives — the `_`
  patterns don't move out of `err`, and Rust's temporary-lifetime
  rules keep the `S3OriginConfig` alive across the `.await`.
  `cargo check --workspace --all-targets` is clean.
- Gemini's OOM-on-`collect()` concern is real but already mitigated
  via the SDK-side `Content-Length` pre-check and the post-collect
  cap (max_blob_size_mb, default 1 GB). Streaming with a running
  cap is a follow-up matching `HttpOrigin`'s same design — pinned
  in the PR description's follow-ups list.
- Copilot's `expand_origin` doc claim is correct as written:
  `expand_value` performs both `\${VAR}` and leading-`~` expansion
  (see `expand_tilde_prefix` at `mod.rs:1149`), so the doc isn't
  misleading.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Three small wins surfaced by the comprehensive review pass on PR #471
(comment-analyzer, type-design-analyzer, pr-test-analyzer). All
changes are low-risk: stale comments, one resolver normalization, and
expanded coverage on the resolver-to-runtime conversion seam.

1. **`DefaultChain { profile = "" }` → `None` at the resolver.** A
   `${PROFILE}` env-var that resolved to empty (or a literal empty
   TOML value) would land at the SDK as `loader.profile_name("")`,
   surfacing as a confusing "profile '' not found" only at first
   credential need. The resolver now collapses empty to `None` so the
   runtime's `loader.profile_name(...)` arm fires only for a real
   name. New test:
   `resolve_cache_origin_s3_default_chain_empty_profile_collapses_to_none`.

2. **Pin `region` and `endpoint_url` field-equivalence on the
   `s3_origin_config_from_resolved` seam, and add a sibling test
   for the `DefaultChain` arm.** The conversion uses field access
   rather than destructuring, so a new field added to one side and
   forgotten on the other isn't a compile error. The existing
   `*_preserves_static_credentials` test only locked `bucket` /
   `path_style` / `prefix` / `Static` credentials; this commit
   adds:
   - `region` + `endpoint_url` assertions in the Static test;
   - new `s3_origin_config_from_resolved_preserves_default_chain`
     covering the `DefaultChain { profile }` arm + `endpoint_url:
     None` + `path_style: false` (the AWS / R2 default).

3. **Comment rot: stale "PR1 / PR2 lands later" + `BehaviorVersion`
   panic-vs-error wording.** PR2 has shipped (this PR is the
   merge target). Updated:
   - `crates/cache/tests/s3_origin.rs:531-534` — "SDK still has its
     own internal retries" claim was the opposite of reality
     (`mock_s3_client` calls `RetryConfig::disabled()`); rewritten
     to match.
   - `crates/cache/src/origin/s3.rs:660-663` — "panic from the SDK
     config builder" softened to "Err … failing this test's
     `.expect`", matching the post-correction wording on
     `S3Origin::new`.
   - `crates/node/src/runtime/mod.rs:989-997` — `BehaviorVersion`
     "panic" → "missing runtime error" for the same reason.
   - `crates/common/src/config/mod.rs` — six sites referring to
     "PR1 / PR2" or "PR2 onward" rewritten to present tense; the
     S3 test-section header reframed to drop the future-tense
     framing of the runtime backend (which now ships in this PR).
   - `crates/common/src/config/types.rs` — `region` and
     `DefaultChain.profile` doc comments dropped the "wired in
     the follow-up PR" / "Once the S3 backend is wired (PR2)"
     parentheticals.
   - `Cargo.toml` — `sha2` pin rationale clarified. The lockfile
     already carries 0.10.9 alongside `=0.11.0-rc.5`; the pin
     prevents adding a *third* (stable 0.11.x), not "two majors
     would otherwise live in the tree".

Verification: cargo build / clippy / fmt / nextest (402 tests in
the affected crates pass, including the three new ones) all clean.

Items reviewed and intentionally NOT changed (with rationale):
- `S3Origin::from_parts` is `pub + #[doc(hidden)]` for cross-crate
  integration test access — standard idiom, documented inline.
  Code-reviewer agreed; silent-failure-hunter's "footgun" framing
  doesn't account for the doc-hidden semver convention.
- 4× Copilot use-after-move + temp-across-await claims on the
  prior commit are false positives; `cargo check --all-targets`
  is clean.
- `#[non_exhaustive]` on the new types would force `decdn-node`
  to add wildcard arms when matching `ResolvedOrigin`, which is
  a regression — the current "compile-error on new variant"
  property is a feature for a workspace-internal sum type.
- STS `ExpiredToken` 403 classification: Permanent is defensible
  for `Static { session_token }` (retry can't help) and largely
  unreached for `DefaultChain` (the SDK's credentials cache
  proactively refreshes on TTL). Filed as a follow-up rather
  than a blocking change.
- Test coverage gaps on `SdkError` variant arms (TimeoutError,
  DispatchFailure, ConstructionFailure, ResponseError, _ catch-
  all, body-collect mid-stream): real but mechanical to add via
  `aws-smithy-mocks`. Tracked for a follow-up; the arms are
  short and well-typed so regression risk in this PR is low.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@thiras
thiras force-pushed the feat/origin-s3 branch from 6522f1a to 700595f Compare May 8, 2026 11:53
@alpergundogdu

Copy link
Copy Markdown
Contributor

Code review

No issues found. Checked for bugs and CLAUDE.md compliance.

🤖 Generated with Claude Code

- If this code review was useful, please react with 👍. Otherwise, react with 👎.

@thiras
thiras merged commit 9f4c898 into main May 8, 2026
12 checks passed
@thiras
thiras deleted the feat/origin-s3 branch May 8, 2026 13:09
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Implement an S3-compatible origin backend (S3/R2/B2/MinIO) as a first-class Origin impl

3 participants