Remember the token endpoint's refusal of an agent's secret

Merged
JE
2mo ago
+1260-36

What happened in production

An agent's secret was rotated on the server. After that, a process on the owner's machine kept sending grant_type=client_credentials with the old secret to POST /oauth/tokens, about six times a minute for more than twelve hours: roughly 350 requests an hour, all using a secret that could never work again. bc3 answered 401 invalid_client. That tripped its abuse tracker, which blocks the address for five minutes, so most of those requests got 429 with Retry-After. That works out to about 340 × 429 and 12 × 401 an hour.

Root cause

An agent credential renews by minting a new token with its client secret, and each process mints on its own. mintAgentCredential intentionally forgot every failed mint and left the stored credential "exactly as it was, so the next command tries again". agentMintRefusal already sorted refusals correctly, but nothing saved the result. So every CLI invocation minted again, and so did every poll of a connector that shells out to basecamp or runs basecamp connect. A 429's Retry-After was lost the same way.

The fix

The token endpoint's verdict is now saved on the stored credential as Credentials.MintHold (see internal/auth/agent_hold.go). The next mint checks it in resolveAgentMint and fails locally without making a request.

ResponseHeldWhy
invalid_clientUntil a login stores a different secret (never re-checked)bc3's Oauth::AgentClients.rotate! replaces the secret digest, disconnect! clears it, and quarantine (Oauth::Client::Disabling) can't be undone. No later server state makes that secret valid again, and each retry counts against the abuse tracker.
invalid_grant, or a 401/403 with no error code1 hour, then one retryIn handle_client_credentials_grant, bc3's invalid_grant means "Agent is no longer active", which reactivating the account undoes. bc3 always names its refusals, so an unnamed 401/403 came from something else (a proxy or WAF) and doesn't prove the secret is dead.
429Until Retry-After (60s if absent, at most 30m since retryAfter caps what it parses)Treated as a retryable rate_limit that says when the hold ends.
5xx, network errors, anything elseNot heldRetried by the next command, as before.
  • The error the caller gets is the same one the refusal produced, with the same --with-client-credentials remedy. It adds that the refusal is remembered, and when it will be retried if it will be.
  • Scoped to the secret. Each hold stores a fingerprint of the client id and secret it applies to (a labelled, truncated SHA-256, never the secret itself). A credential holding a different secret ignores the hold. Logging in again with a new secret writes a fresh credential with no hold. A successful mint clears the hold.
  • Concurrency. The hold is written while holding m.mu and the credential key's cross-process lock, which logins also take. It is written against a fresh read, and only if that read still has the refused secret. On a host that can't take the lock (lock.go runs it unsynchronized, with a warning), the fresh read narrows the race with a concurrent login from the whole token round trip to one local load and save. It doesn't close it: that host has no lock or compare-and-swap to build on. A successful mint there already has a wider window with the same outcome, and skipping the hold would bring the retry storm back on exactly those hosts.
  • Fails open. A stored hold is only believed when it's well formed (MintHold.holds): it names these client credentials, its kind is known, and if it expires, it expires in the future and within an hour. Only an invalid_client refusal is held with no expiry; a rate limit or any other refusal without one is treated as damaged. Anything else is ignored and the mint goes out, which is the old behavior. Every hold's deadline is stored rounded up to the next whole second, and every wait reported for a hold (the first 429's error, a held one, a held refusal's hint) is the time left to that deadline, rounded up.
  • Login isn't held. LoginClientCredentials and the connect handover don't record holds: nothing is stored yet, and a login is a single attempt, not a loop.
  • auth status. It reports what a renewal sent now would meet. Only a permanent invalid_client hold makes the credential refreshable: false, shown as "expired, and the renewal would be refused: …" with the agent-login hint. A time-limited hold (a 429, or an invalid_grant or bare 401/403 refusal) leaves it refreshable, and the hint is to wait until the deadline. The JSON has a new renewal_refused object (kind, detail, until, message, hint) taken from the stored hold only: it's absent for a local setup error such as a missing secret, and present whether or not an access token is stored.
  • Disconnect detection (#806). A remembered refusal carries the same ErrAgentCredentialRefused cause as the first one, so the connector and guided setup still report the agent as disconnected once the refusal is stored. A held rate limit doesn't carry it.

basecamp connect (in-process)

I checked this but didn't change anything. The connector gets every token through managerTokens → Manager.AccessToken. The intake feed treats a failed token (the mint's ErrAuth) as unrecoverable, and runPart then cancels the whole run. So the connector already stops on its first refused mint. Before this change, each restart (systemd Restart=always, RestartSec=5, within its start limit) sent the dead secret again. Now a restart fails locally without a request.

Admission, outbox and membership only log token failures and back off; they now get a cheap local failure too. One gap remains: a feed sitting idle on its websocket may not notice for a while. Canceling the run from a wrapper around managerTokens would close that gap, but it isn't needed to stop the retry storm, so it's left out.

A related problem I found but didn't fix: the feed also treats a 429 or 5xx from the token endpoint as unrecoverable, so one throttled mint ends the connector run. The hold keeps the restart loop cheap, but the right fix belongs in the feed's error classification, in a separate change.

Tests

internal/auth/agent_hold_test.go, run against a local token endpoint that counts requests, with the Manager's clock as a test seam:

  • A 401 invalid_client means the next mints make zero requests: in the same process, 30 days later, and from a new Manager. The remembered error carries the agent remedy and never the secret.
  • A different secret mints normally, and the success clears the hold.
  • A 429 with Retry-After: 300 means no request at +299s and one at +300s. The success clears the hold. Also tested: no Retry-After, a very large value, the HTTP-date form, and 0.
  • 5xx responses and a proxy's bare 400 hold nothing and are retried.
  • invalid_grant and bare 401/403 get one retry per hour, a second refusal holds again, and a later success clears the hold.
  • A stale refusal is never written over a new secret.
  • A hold too far in the future, of an unknown kind, or with no deadline when it isn't an invalid_client refusal, is ignored.
  • A remembered refusal is errors.Is(ErrAgentCredentialRefused); a held rate limit is not.
  • auth status reports the remembered refusal and its remedy without calling the token endpoint; a rate limit, invalid_grant or bare 401 hold is refreshable with a wait hint; a hold is reported with no access token; a missing secret reports no hold.
  • Every hold deadline is rounded up, a full-hour hold set mid-second is still believed, and the wait each error names is read from the deadline.

I checked that the tests catch the bug they target: with the hold check disabled, the refusal, rate-limit and recheck tests fail, and with the fingerprint check removed, the stale-write test fails. make lint is clean and go test ./... passes on Linux.


Summary by cubic

Stops agent credentials from repeatedly presenting a secret the token endpoint has refused. Previously a rotated secret was sent again on every poll, tripping the abuse tracker; now the refusal is stored with the credential and answered locally.

Remembered refusals

  • invalid_client is held until a login stores a different secret.
  • invalid_grant and bare 401/403 are held an hour, then tried once.
  • 429 is held until Retry-After (60s default, capped at 30 minutes), from status and header alone even when the body cannot be read; a 429 reports only its status, never an OAuth code its body carries.
  • A refusal naming an OAuth code this version does not know is not held and is asked again.
  • 5xx and network errors are not held and are retried as before.

Implementation notes

  • The hold is scoped to a fingerprint of client id and secret, so a new secret ignores the old hold.
  • A successful mint clears the hold; login is never held.
  • A stored hold is believed only when well formed: only an invalid_client refusal is held with no deadline, and any other deadline-less hold, one more than an hour out, or an unknown kind is ignored.
  • Deadlines are stored rounded up to the whole second, and every wait reported is read from the stored deadline.
  • A remembered refusal carries the same ErrAgentCredentialRefused cause, so connectors and guided setup still treat the agent as disconnected; a held rate limit does not.
  • auth status reports the refusal, its deadline, and a hint to wait; only a permanent refusal makes a credential unrefreshable — rate-limited and hourly-refused agents stay refreshable — and a permanent one is named on the token line while the token is still live, not only once it expires.
  • A hold reports itself only when it is the answer a renewal would meet, so a report can't disagree with the next mint and a local failure like a missing token endpoint isn't masked; a refusal that can't be remembered because the credential can't be read or written is warned about.