Skip to content

libstore: cache AWS credentials and refresh on S3 token expiry - #15609

Open
lovesegfault wants to merge 2 commits into
masterfrom
fix-aws-creds-final-v3-FINAL-final
Open

lovesegfault wants to merge 2 commits into
masterfrom
fix-aws-creds-final-v3-FINAL-final

Conversation

@lovesegfault

@lovesegfault lovesegfault commented Mar 31, 2026 •

Copy link
Copy Markdown
Member

Follow-up to #15594. Wraps the credential provider chain in CredentialsProviderCached (15-minute TTL, honors embedded expiration if shorter). Previously every S3 request triggered a fresh STS / SSO / IMDS round-trip — for a build pulling hundreds of narinfos that was hundreds of STS calls. aws-c-auth's default chain does this internally; our custom chain bypassed it.

When an S3 request fails with an ExpiredToken or TokenRefreshRequired error code, credentials are refreshed asynchronously and the request retried. Previously a session token expiring mid-build was a hard failure.

Trigger:

  • finish() inspects the S3 error body captured in errorSink for <Code>ExpiredToken</Code> or <Code>TokenRefreshRequired</Code>. AWS S3 documents these as HTTP 400, so the check admits both 400 and 403 — AWS SDKs check the body <Code> status-agnostic for this reason. AccessDenied (403, missing key in an unlistable bucket) does not match — those probes stay at one S3 request, preserving the existing 403→404 mapping at http-binary-cache-store.cc:173,280,302.
  • HEAD requests have no body to inspect and fall through — not a regression, HEAD never retried before either.
  • 401 and 407 are always Forbidden — S3 never sends 401, and 407 is proxy auth which a credential refresh cannot fix.

Cold-start:

  • setupForS3() tries tryGetCredentials once synchronously (hot cache is instant). It always sets awsRetry in the provider branch, even if the synchronous fetch failed; in that case usernameAuth stays empty and the first unauthenticated 403 (AccessDenied) triggers the same async refresh path — s3TokenExpired() returns true on !usernameAuth before the body check.
  • Bounded by awsCredsRefreshed: init() sets it unconditionally when the future resolves (even nullopt), and even a blackholed-IMDS chain resolves within ~1s — well inside the retry window. download-attempts is the backstop for a genuinely-hung provider.
  • One warnOnce at the terminal !canRetry site if usernameAuth is still empty — tells the user "provider" not "permissions". Not in the pre-resolved sandbox path (builtin:fetchurl — awsRetry is never set there).

Refresh mechanism:

  • maybeRetry() spawns a detached std::thread + std::promise. A std::promise-sourced future does not block in its destructor (unlike std::async, whose future joins the launched thread — [futures.async]/5).
  • The detached thread calls tryGetCredentials (noexcept, no warn()). nix::logger may be destroyed before this thread completes since it isn't joined by any destructor — the AWS CRT's process-global log hook is a residual risk at -vvvvv, but default verbosity is gated.
  • The provider is stashed on FileTransferRequest as AwsRetryInfo {ParsedS3URL, ref<AwsCredentialProvider>}, set by setupForS3() on the caller thread, then init-captured by value into the detached thread — getAwsCredentialsProvider()'s function-local static is constructed after the fileTransfer static and destroyed before ~curlFileTransfer() joins the worker (LIFO), so neither the worker thread nor the detached thread touch it.
  • init() applies the result via wait_for(0) — non-blocking. The retry loop's computeRetryDelayMs backoff overlaps with the fetch.
  • The spawn is guarded against std::system_error (e.g. EAGAIN under ulimit -u); get_future() is assigned after .detach() succeeds so a constructor throw doesn't leave a dangling future.

Termination:

  • awsCredsRefreshed is set in init() when the future resolves; a consecutive expiry after that falls through (the refresh didn't help — clock skew, server-side revocation).
  • The flag is cleared only on 2xx in headerCallback — not 1xx (100 Continue on PUT uploads isn't auth confirmation; some S3-compatibles send it before validating the header), not 3xx (a redirect hop via CURLOPT_FOLLOWLOCATION doesn't validate auth either). So a long Range-resumable download spanning multiple token lifetimes can refresh more than once.
  • If retries exhaust before the refresh completes, exc.error is downgraded — 403→Forbidden (unlistable-bucket mapping), 400→Misc (unambiguous credential failure → surface it). Only when writtenToSink == 0: a partial 200 OK proves the file exists, so Forbidden→NoSuchBinaryCacheFile would lie.

Range-resume / proxy:

  • acceptRanges is preserved across 1xx/3xx/4xx/5xx (only 2xx resets, same gate as the loop-guard). An error response doesn't carry Accept-Ranges, but it also doesn't revoke the server's range support established by a prior 200; nor does a redirect hop or a Continue.
  • CURLOPT_SUPPRESS_CONNECT_HEADERS so a proxy's "200 Connection established" doesn't reach headerCallback and clobber the same per-response state.

Known limitation:

  • The cached provider honors embedded credential expiration, so natural expiry works. Under clock skew or server-side token revocation, the refresh may return the same cached credential — we don't force-invalidate since the <Code> gate already bounds this path to cases where the provider's TTL should align with S3's view.

@lovesegfault
lovesegfault force-pushed the fix-aws-creds-final-v3-FINAL-final branch 8 times, most recently from 64b852d to 0b7b657 Compare March 31, 2026 05:16
Comment thread src/libstore/filetransfer.cc Resolved
Comment thread src/libstore/filetransfer.cc Resolved
Comment thread src/libstore/filetransfer.cc Resolved
Wraps the credential provider chain in CredentialsProviderCached
(15-minute TTL, honors embedded expiration if shorter). Previously every
S3 request triggered a fresh STS / SSO / IMDS round-trip — for a build
pulling hundreds of narinfos that was hundreds of STS calls. aws-c-auth's
default chain does this internally; our custom chain bypassed it.

When an S3 request fails with an ExpiredToken or TokenRefreshRequired
error code (S3 documents these as HTTP 400; AWS SDKs check the body
<Code> status-agnostic), credentials are refreshed asynchronously and
the request retried. Previously a session token expiring mid-build was
a hard failure.

Refresh mechanism:
- maybeRetry() spawns a detached std::thread + std::promise (a future
  from std::promise does not block in its destructor, unlike std::async).
  The thread holds the provider via its own refcount and uses
  tryGetCredentials (noexcept, no warn() — nix::logger may be destroyed
  before this thread completes, since it isn't joined by any destructor).
- init() applies the result via wait_for(0) — non-blocking. The retry
  loop's computeRetryDelayMs backoff overlaps with the fetch.
- awsCredsRefreshed loop-guard cleared only on 2xx (not 1xx Continue,
  not 3xx redirect hops via CURLOPT_FOLLOWLOCATION) so a long Range-
  resumable download spanning multiple token lifetimes can refresh
  more than once.

Cold-start: setupForS3() tries tryGetCredentials once synchronously
(hot cache is instant). On failure, awsRetry is still set; the first
unauthenticated 403 triggers the same async refresh path. Bounded by
awsCredsRefreshed — init() sets it unconditionally when the future
resolves (even nullopt), and even a blackholed-IMDS chain resolves
within ~1s, well inside the retry window. download-attempts is the
backstop for a genuinely-hung provider.

Downgrade: when retries exhaust, Transient → Forbidden (403) or Misc
(400), but only when writtenToSink == 0 — a partial 200 OK proves the
file exists, so Forbidden→NoSuchBinaryCacheFile would lie.

Provider stashed on FileTransferRequest as AwsRetryInfo {ParsedS3URL,
ref<AwsCredentialProvider>} — read on the worker thread instead of
calling getAwsCredentialsProvider() there (that function-local static
is destroyed before ~curlFileTransfer joins the worker; LIFO).

Also: CURLOPT_SUPPRESS_CONNECT_HEADERS so proxy CONNECT 200 doesn't
clobber per-response state; acceptRanges preserved across 3xx/4xx/5xx
(only 2xx resets, same as the loop-guard).
Replaces the per-item polling refresh with a credential broker: items
park (removed from the worker's queue) instead of firing doomed
retries, one detached fetch thread per (profile, region) key, and
wakeupMulti() releases all waiters at once when the fetch lands.

The retry decision is now a generic FileTransferRequest::CredentialHook
{key, shouldRefresh, fetchAndApply}. setupForS3() populates it with
the S3-specific <Code>ExpiredToken</Code> regex and tryGetCredentials
closure; finish() consults it without #if NIX_WITH_AWS_AUTH.

Removed: pendingAwsCredRefresh future + init() wait_for(0) polling,
maybeRetry() spawn block, the Transient→Forbidden downgrade (no
retries while pending → nothing to downgrade), AwsRetryInfo (folded
into the hook closure).

State::credentialBroker is map<key, {waiters, inFlight}>. Late
arrivals during the slow first fetch see inFlight=true, join waiters;
the broker thread loops to drain (subsequent iterations hit the
now-warm provider cache). inFlight cleared atomically with the empty
check.

credsRefreshedSinceLast2xx (was awsCredsRefreshed) is set by
parkOnCredentials() on the parking thread — never the broker thread —
and is a plain bool (not :1) so it doesn't share a byte with the
worker's post-finish() bitfield writes. Cleared on 2xx as before.

Cold-start: enqueueFileTransfer parks immediately if credentialHook
is set but usernameAuth isn't — no doomed first 403.

Spawn-failure (EAGAIN under ulimit -u): re-enqueue waiters with
doFetch=false instead of running fetchAndApply inline on the worker.
@cep21

cep21 commented Apr 28, 2026

Copy link
Copy Markdown

Hi,

I ran into the same issue here. Any updates?

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants