Repository navigation
libstore: cache AWS credentials and refresh on S3 token expiry - #15609
Open
lovesegfault wants to merge 2 commits into
Open
lovesegfault wants to merge 2 commits into
lovesegfault wants to merge 2 commits into
Conversation
lovesegfault
force-pushed
the
fix-aws-creds-final-v3-FINAL-final
branch
8 times, most recently
from
March 31, 2026 05:16
64b852d to
0b7b657
Compare
xokdvium
reviewed
Apr 3, 2026
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.
|
Hi, I ran into the same issue here. Any updates? |
This branch has not been deployed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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
ExpiredTokenorTokenRefreshRequirederror 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 inerrorSinkfor<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 athttp-binary-cache-store.cc:173,280,302.Forbidden— S3 never sends 401, and 407 is proxy auth which a credential refresh cannot fix.Cold-start:
setupForS3()triestryGetCredentialsonce synchronously (hot cache is instant). It always setsawsRetryin the provider branch, even if the synchronous fetch failed; in that caseusernameAuthstays empty and the first unauthenticated 403 (AccessDenied) triggers the same async refresh path —s3TokenExpired()returns true on!usernameAuthbefore the body check.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-attemptsis the backstop for a genuinely-hung provider.warnOnceat the terminal!canRetrysite ifusernameAuthis still empty — tells the user "provider" not "permissions". Not in the pre-resolved sandbox path (builtin:fetchurl—awsRetryis never set there).Refresh mechanism:
maybeRetry()spawns a detachedstd::thread+std::promise. Astd::promise-sourced future does not block in its destructor (unlikestd::async, whose future joins the launched thread — [futures.async]/5).tryGetCredentials(noexcept, nowarn()).nix::loggermay 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.FileTransferRequestasAwsRetryInfo {ParsedS3URL, ref<AwsCredentialProvider>}, set bysetupForS3()on the caller thread, then init-captured by value into the detached thread —getAwsCredentialsProvider()'s function-local static is constructed after thefileTransferstatic and destroyed before~curlFileTransfer()joins the worker (LIFO), so neither the worker thread nor the detached thread touch it.init()applies the result viawait_for(0)— non-blocking. The retry loop'scomputeRetryDelayMsbackoff overlaps with the fetch.std::system_error(e.g.EAGAINunderulimit -u);get_future()is assigned after.detach()succeeds so a constructor throw doesn't leave a dangling future.Termination:
awsCredsRefreshedis set ininit()when the future resolves; a consecutive expiry after that falls through (the refresh didn't help — clock skew, server-side revocation).headerCallback— not 1xx (100 Continueon PUT uploads isn't auth confirmation; some S3-compatibles send it before validating the header), not 3xx (a redirect hop viaCURLOPT_FOLLOWLOCATIONdoesn't validate auth either). So a long Range-resumable download spanning multiple token lifetimes can refresh more than once.exc.erroris downgraded — 403→Forbidden(unlistable-bucket mapping), 400→Misc(unambiguous credential failure → surface it). Only whenwrittenToSink == 0: a partial 200 OK proves the file exists, soForbidden→NoSuchBinaryCacheFilewould lie.Range-resume / proxy:
acceptRangesis preserved across 1xx/3xx/4xx/5xx (only 2xx resets, same gate as the loop-guard). An error response doesn't carryAccept-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_HEADERSso a proxy's "200 Connection established" doesn't reachheaderCallbackand clobber the same per-response state.Known limitation:
<Code>gate already bounds this path to cases where the provider's TTL should align with S3's view.