# Security invariants

> The security rules the library holds, each one with the tests that hold it.

From `docs/ARCHITECTURE.md` in tensile-tools/tensile-auth at commit `e66760d` (v0.4.1-7-ge66760d). The HTML page is https://auth.tensile.tools/docs/reference/invariants.

| # | Invariant | Test |
|---|---|---|
| 1 | Raw tokens never reach the store, logs or events | `TestRawTokensNeverLeaveTheService`, `TestSignupSecretsNeverReachTheStore` |
| 2 | Tokens redact under every fmt verb, slog, JSON, and text | `TestTokenRedactsItself` |
| 3 | Every principal names the responsible human, at any depth, except an unclaimed agent's, which has no human and reports `Unclaimed` | `TestDelegationChainKeepsResponsibleHuman`, `FuzzSessionOps`, `TestUnclaimedAgentCantEscapeTheSandbox` |
| 4 | Delegation only narrows: scopes, expiry and depth | `TestDelegationOnlyNarrows`, `TestDelegationDepthIsCapped`, `FuzzSessionOps` |
| 5 | Revocation cascades and is immediate | `TestRevokeCascadesImmediately`, `FuzzSessionOps` |
| 6 | Delegate racing revoke never leaves a live child | `storetest: DelegateRacingRevokeLeavesNoLiveChild` |
| 7 | Revoking a user or agent kills all their sessions and everything delegated from them; a revoked agent gets no new ones | `TestRevokeUserAndAgent`, `storetest: RevokeUserAndAgent`, `storetest: RevokeAgentCascades` |
| 17 | An agent can only delegate to sub-sessions of itself, never to a different agent | `TestAgentCanOnlyDelegateToItself` |
| 18 | Every change records its audit event in the same transaction; a failed operation records nothing | `storetest: EventsAreRecorded`, `storetest: FailedOperationsRecordNoEvent`, `TestAuditTrailIsComplete` |
| 19 | A process killed in the middle of a rotation leaves it undone: the old token stays current, the new one is unknown, and no event is recorded | `storetest.CrashDuringRotation`, run by `sqlitestore` and `pgstore` |
| 20 | Caching never changes what a store means, and changes made through the cache are visible at once | `cachestore: TestConformance` and `cachestore: TestOptionalConformance` (the full suites through the cache), `FuzzSessionOps` through the cache |
| 21 | A revocation on one server reaches every server's cache, and a server that can't hear about changes doesn't serve cached lookups | `pgstore: TestWatchMakesRemoteRevocationVisible` |
| 36 | Step-up rotates the token and elevates only the new one; proofs must match the user and be at most 5 minutes old | `TestStepUpRotatesAndElevatesOnlyTheNewToken`, `TestProofMustMatchUserAndBeFresh`, `storetest: SwapCarriesStepUp` |
| 37 | Agents are never fresh, and step-up rejects agent sessions | `TestAgentsAreNeverFresh` |
| 22 | A ceremony can be finished at most once, and not after it expires | `storetest: CeremonyIsConsumedOnce`, `storetest: ConcurrentCeremonyConsume` |
| 29 | A first passkey can be registered only while the user has none, even under concurrency | `storetest: FirstCredentialIsFirst`, `storetest: ConcurrentFirstCredential` |
| 25 | A credential's sign count changes only by compare-and-set | `storetest: CredentialUseIsCompareAndSet` |
| 39 | Factor changes are audited in the same transaction; failed ones record nothing | `storetest: FactorEventsAreRecorded` |
| 23 | Ceremonies from the wrong origin, relying party, or browser binding are rejected | `passkey: TestRejectsWrongOriginRPAndBinding` |
| 24 | Passkey registration and sign-in require user verification | `passkey: TestUserVerificationIsRequired` |
| 25 | A device-bound passkey whose sign count goes backwards is rejected and flagged; a synced one is flagged | `passkey: TestSignCountRegressionPolicy` |
| 27 | PRF outputs never reach the server | `passkey: TestPRFOutputsNeverReachTheServer` |
| 28 | Passkey user handles are random and never the user ID | `passkey: TestUserHandleIsRandomAndNotTheUserID` |
| 29 | Adding or removing a passkey needs a fresh human session; a first passkey only while there is none | `passkey: TestFactorChangesNeedAFreshHumanSession`, `passkey: TestFirstRegistrationOnlyOnce` |
| 35 | Sign-in options before identification don't depend on whether accounts exist | `passkey: TestBeginLoginDoesNotDependOnAccount`, `passkey: TestUnknownPasskeysLookLikeAnyOtherFailure` |
| 30 | A TOTP code works once, even under concurrency | `totp: TestTOTPCodeWorksOnce`, `storetest: TOTPStepOnlyAdvances`, `storetest: ConcurrentTOTPStep` |
| 31 | TOTP secrets are sealed and bound to their user; rotation reseals | `totp: TestTOTPSecretIsSealedAndBoundToItsRow`, `totp: TestKeyRotationReseals`, `seal: TestSealedDataIsBoundToItsRow` |
| 32 | TOTP locks after 100 consecutive failures, and can't be used without a first factor | `totp: TestTOTPLocksAfter100Failures`, `totp: TestTOTPNeedsAFirstFactor`, `storetest: TOTPLocksAtTheLimit` |
| 33 | A recovery code works once; a new set replaces the old; codes are stored only as hashes | `storetest: RecoveryCodeIsConsumedOnce`, `storetest: ConcurrentRecoveryRedeem`, `recovery: TestNewRecoverySetReplacesOld`, `recovery: TestRecoveryCodesAreStoredHashed` |
| 34 | Every factor failure returns the same error; only logs see the reason | `TestFactorErrorsAreIndistinguishable` |
| 38 | A throttled attempt returns ErrThrottled with a wait; a limiter outage is a server error, not a rejection | `TestLimiterThrottlesAndSeesTheClient`, `TestLimiterOutageIsNotRejection` |
| 40 | A passkey step-up finishes only for the session that began it, and sign-in and step-up ceremonies can't finish each other | `passkey: TestStepUpIsBoundToItsSession` |
| 41 | Every failed attempt is recorded in the audit log, with the client: rejected factors, throttled attempts, rejected tokens, and denied requests | `TestFailedAttemptsAreAudited`, `authhttp: TestRejectedRequestsAreAudited`, `TestEveryEventRecordsTheClient` |
| 42 | Failure rows are bounded per key and in total, attacker-chosen fields can't get around the bound, and every attempt beyond it is counted in a summary that keeps its user | `TestFailureEventsAreBoundedPerClient`, `TestFailureEventsAreBoundedInTotal`, `TestFailureKeysAreBounded`, `TestVaryingTheActionDoesntBypassTheCap`, `TestAttributedSummariesKeepTheUser` |
| 43 | The observer sees every attempt; failed writes are retried; a client that hangs up, a store outage, or a shutdown can't drop a count | `TestObserverSeesEveryAttempt`, `TestAnonymousFloodsDontHideAttributedFailures`, `TestSummariesSurviveCancellationOutagesAndShutdown`, `TestLongOutagesKeepCountsAndSayTheyMerged`, `TestRunWritesSummariesWithoutAnotherFailure` |
| 44 | Every rate-limit backend behaves the same: a burst, then throttling with a retry time; independent keys; and no more than the burst under concurrency | `limittest.Run` on memory, Valkey, and PostgreSQL |
| 45 | Limits before sign-in key on the client only; per-user limits apply only to identified attempts; a backend outage fails closed | `ratelimit: TestUserLimitsApplyAcrossClients`, `ratelimit: TestBackendOutagesFailClosed` |
| 46 | The memory backend stays bounded without letting one client throttle others, reset a counter, or evict a per-user counter | `ratelimit: TestMemoryCountersAreBounded`, `ratelimit: TestMemoryEvictsTheLeastRecentlyUsed`, `ratelimit: TestMemoryLimitsDontShareCounters`, `ratelimit: TestClientChurnCantEvictUserCounters` |
| 47 | Every sealed audit event is hash-chained over all its fields; any edit, deletion, reordering, or truncation fails verification, and a signed checkpoint catches a rebuilt chain | `TestAuditChainDetectsTampering`, `TestCheckpointsCatchARebuiltChain`, `TestChainHashCoversEveryField` |
| 48 | Sealing is serialized across servers and never slows audited writes; concurrent sealers build one chain | `storetest: ConcurrentSealersShareOneChain`, `storetest: SealEventsBuildsTheChain`, `storetest: FailedSealStoresNothing` |
| 49 | Agent signup is off unless the application turns it on, and with it off an unclaimed agent's tokens are rejected | `TestSignupIsOffByDefault` |
| 50 | An unclaimed agent can't escape its sandbox: its sessions hold only the current sandbox's scopes, it delegates only to itself within them, and it can't create agents, step up, claim, or list sessions | `TestUnclaimedAgentCantEscapeTheSandbox` |
| 51 | A claim code works once, even under concurrency, and never after the claim deadline or for a disabled agent | `TestClaimCodeWorksOnce`, `storetest: ClaimCodeWorksOnce`, `storetest: ConcurrentClaimHasOneWinner`, `storetest: ClaimNeedsALiveUnexpiredAgent` |
| 52 | Only a fresh, multi-factor human can claim, never with more scopes than they hold; claiming revokes every sandbox session, and the agent collects its new token once, a second pickup revoking it | `TestClaimNeedsAFreshMultiFactorHuman`, `TestClaimRotatesTheAgentsToken`, `TestClaimedSessionFollowsItsClaimer`, `storetest: ClaimRevokesTheSandbox`, `storetest: ClaimChecksTheParent` |
| 53 | Expiry deletes an unclaimed agent and every session it holds in one transaction, never touches a claimed agent, and runs from `Service.Run`; signup tokens stop at the deadline before the sweep | `TestExpiryRevokesEverything`, `TestRunExpiresUnclaimedAgents`, `storetest: ExpiryDeletesEverything`, `storetest: ClaimRacingExpiryIsConsistent` |
| 54 | Signups are throttled per client before any policy hook runs, and the unclaimed-agent quota holds under concurrency | `TestSignupIsThrottledFirst`, `TestSignupQuotaIsEnforced`, `storetest: SignupQuotaHolds`, `storetest: ConcurrentSignupQuotaHolds` |
| 55 | A self-reported agent type is verified only by the verifier, and type rules compare lowercased types | `TestTypeIsUnverifiedWithoutAVerifier`, `TestSignupPolicyHooksRunInOrder` |
| 56 | Only a request signed by a current provider key, unchanged and not seen within the replay window, can revoke a leaked token; every rejected request is audited | `leakscan: TestBadSignaturesAreRejected`, `leakscan: TestReplaysAreRejected`, `leakscan: TestUnknownKeyIDsRefetchAtMostOncePerInterval` |
| 57 | A leaked token revokes its session and every session delegated from it, in any state, records where it was found, and changes nothing for tokens the service didn't issue | `TestLeakedTokensRevokeTheirTree`, `TestLeakedTokensAreRevokedInAnyState`, `TestLeakFalsePositivesChangeNothing`, `TestLeaksMustMatchTheSessionsHashAndKind`, `storetest: LeakRevocationKeepsItsSource` |
| 58 | Leak alerts are bounded in body size and tokens, pass the limiter first, fetch keys only from the fixed provider URL, and answer with only hashes, types, and labels | `leakscan: TestOversizedRequestsAreRejected`, `leakscan: TestTheLimiterRunsBeforeAnyWork`, `leakscan: TestGitHubKeysReadsOnlyTheKeysURL`, `leakscan: TestResponsesRevealOnlyHashesAndLabels` |
| 59 | Every admin request needs a principal that the application's `Authorizer` accepts, and every refusal is audited | `authadmin: TestNonAdminsAreForbidden`, `authadmin: TestAnonymousRequestsAreUnauthenticated` |
| 60 | Admin changes need a fresh human session: stale sessions and agents can read but not change | `authadmin: TestChangesNeedAFreshHumanSession`, `authadmin: TestAgentsFollowTheSameRules` |
| 61 | Every admin change records the acting admin in the change's own event, written in the same transaction | `authadmin: TestChangesRecordTheActor`, `storetest: EventsRecordTheActor` |
| 62 | Admin changes are rate-limited per admin through the service's limiter | `authadmin: TestChangesAreRateLimited` |
| 63 | Admin responses never contain tokens or token hashes | `authadmin: TestResponsesContainNoSecrets` |
| 64 | PATs, OAuth access tokens, and refresh tokens are never fresh and can't step up; only a human session that authenticated within 10 minutes creates a PAT or approves an OAuth request, and within 30 minutes for `Grant` | `TestAppTokensAreNeverFresh`, `TestCreatePATNeedsAFreshHumanSession`, `TestGrantNeedsAFreshHumanSession`, `oauth: TestDeviceFlowDeniedAndExpired` |
| 65 | A refresh token never authenticates a request; it rotates on use with one winner, and reuse after the grace window revokes the grant and every access token under it | `TestRefreshTokensDontAuthenticate`, `TestRefreshRotatesAndReuseRevokesTheGrant`, `TestConcurrentRefreshHasOneWinner`, `oauth: TestRefreshOverHTTP` |
| 66 | A PAT, OAuth grant, or exchanged token holds only scopes that both the approving principal and the client hold, and lives no longer than its policy allows | `TestGrantsOnlyNarrow`, `TestPATLifetimes`, `TestGrantLifetimes`, `TestTokenExchangeFromAppTokensOnlyNarrows`, `oauth: TestTokenExchange` |
| 67 | An authorization code works once, only for its client, redirect URI, and PKCE verifier, and within 60 seconds; public clients must use PKCE | `oauth: TestCodeIsSingleUseAndBound`, `oauth: TestPromptAndMaxAge` |
| 68 | A device code yields at most one token, only after a human approves it, before it expires, and while the approving session is live | `storetest: DeviceCodeYieldsOnce`, `storetest: ConcurrentDevicePollYieldsOnce`, `storetest: DeviceDecisionIsCompareAndSet`, `oauth: TestDeviceFlow`, `TestGrantNeedsALiveApprover` |
| 69 | Only human session tokens are accepted from cookies | `authhttp: TestOnlyHumanTokensFromCookies` |
| 70 | Revoking a user ends their PATs and OAuth grants; revoking a refresh token ends its access tokens | `storetest: RevokeUserEndsAppTokens`, `storetest: AppTokenKindsRoundTrip` |
| 71 | OAuth failures return one error per kind, are reported to the limiter, and are audited with the reason; a confidential client's secret can't be guessed without the limiter | `oauth: TestOAuthFailuresLookTheSameAndAreAudited` |
| 72 | An audit event without fields added after the chain's first version hashes exactly as it did in that version, so chains sealed then keep verifying | `TestChainHashOfEventsWithoutNewerFields`, `TestChainHashCoversEveryField` |
| 73 | A client that hangs up during a leak alert can't stop the provider's keys from being fetched, so genuine alerts keep being handled | `leakscan: TestAClientThatHangsUpCantBlockKeyFetches` |
| 74 | Signup spikes, a full signup quota, and unclaimed agents close to their deadline raise admin alerts; claimed agents never count as close to expiry | `authadmin: TestSignupSpikeAndQuotaAlerts`, `authadmin: TestUnclaimedNearExpiryAlert` |
| 75 | A signup override can only narrow the code policy; changing it needs a fresh multi-factor human and the current version, and is audited | `TestOverridesCanOnlyNarrow`, `TestChangingOverridesNeedsAFreshMultiFactorHumanAndTheVersion`, `authadmin: TestSignupOverrideThroughTheAPI` |
| 76 | Every server applies an override within 5 seconds, and a server that never loaded it refuses signups and empties the sandbox | `TestOtherServersSeeAChangeWithinSeconds`, `TestAServerThatNeverLoadedTheOverrideFailsClosed`, `storetest: ConcurrentOverrideWritesHaveOneWinner` |
| 77 | A leaked claim code deletes its unclaimed agent with every session of it; a used code, or one no agent holds, changes nothing | `TestLeakedClaimCodesDeleteTheUnclaimedAgent`, `storetest: DeleteSignupDeletesEverything` |
| 78 | The admin API's chain status reports a tampered chain on the first check after the interval, and only the first request waits for a check | `authadmin: TestAuditChainStatus` |
| 79 | A session cookie that fails authentication is cleared and the request passes anonymously; a header credential that fails gets a 401 | `authhttp: TestStaleCookiesAreClearedAndPassAnonymously`, `authhttp: TestEveryFailureLooksTheSame` |
| 80 | Agent creation, signup, claims, delegation (with token exchange), and PAT creation pass every quota first; a refusal or a quota error refuses the action, creates nothing, and records an `access_denied` event with the reason | `TestEveryQuotaCallSiteRefusesOverQuota`, `TestQuotaErrorsFailClosed`, `oauth: TestTokenExchangeHonorsTheQuota` |
| 81 | `Caps` counts a human's enabled agents and an agent's live sessions, and quotas run only after the permission checks pass | `TestCapsCountAgentsAndSessions`, `TestCapsCountTheSessionsOfAnUnclaimedAgent`, `TestQuotaRunsAfterPermissionChecks` |
| 82 | A human's agent cap holds under concurrency, across creates and claims; an agent's session cap is exceeded by at most the number of concurrent delegations to it, minus one | `TestCapsAgentLimitHoldsUnderConcurrency`, `storetest: ConcurrentAgentCapHolds`, `storetest: ConcurrentClaimsAndCreatesHoldTheCap`, `storetest: AgentCapHolds`, `storetest: ClaimHonorsTheAgentCap`, `TestCapsSessionLimitIsSoftByTheConcurrentDelegations` |
| 83 | A token bound to a key works only with a valid proof of possession from that key that covers the token; sent as a Bearer token, or with another key's proof, it fails like any other token, and the service records a distinct reason | `TestBoundTokensNeedAProofFromTheirKey`, `authhttp: TestStolenBoundTokensAreRejected`, `authhttp: TestDPoPNeedsAVerifier`, `TestCollectingABoundSignupNeedsItsKey` |
| 84 | A session delegated from a bound session is always bound, to the parent's key or to its own, and every store keeps the binding | `TestChildInheritsTheKeyBinding`, `storetest: KeyBindingRoundTrips`, `storetest: SignupKeyBindingRoundTrips` |
| 85 | With `RequireAgentKeys`, delegation, signup, claiming, and token exchange never create an unbound agent session | `TestRequireAgentKeysRefusesUnboundSessions`, `oauth: TestTokenExchangeNeedsAKeyWhenRequired` |
| 86 | A DPoP proof is accepted only as a compact JWS with typ `dpop+jwt`, alg ES256 or EdDSA, a public jwk of that algorithm, a valid signature, the request's method and normalized URL, an iat within the skew, and the presented token's ath | `dpop: TestEveryClaimMismatchIsRejected`, `dpop: TestMalformedProofsAreRejected`, `dpop: TestURLsCompareAfterNormalization`, `dpop: FuzzVerify` |
| 87 | A proof works once within its window, its ID is recorded only after its token authenticates, and a replay-cache outage is a server error, not a rejection | `TestBoundTokensNeedAProofFromTheirKey`, `TestReplayCheckOutageIsNotRejection`, `replaytest.Run` on memory, PostgreSQL, and Valkey |
| 88 | The in-memory replay cache stays bounded in size and drops expired IDs | `dpop: TestMemoryReplaysAreBounded` |
| 89 | A bound token exchanges only with a proof from its own key that covers it, and the issued token stays bound; a proof with an unbound token is rejected, except to bind a token being issued | `oauth: TestTokenExchangeBindsToTheDPoPKey`, `TestProofsWithUnboundTokensAreRejected`, `authhttp: TestHandlersDontSeeTheProof` |
| 90 | External identities are keyed by issuer and subject, never by email address: an identity that no account holds never attaches to an existing account, and an email collision fails like any other sign-in failure | `federation: TestEmailCollisionNeverLinks`, `storetest: IdentityRoundTrip` |
| 91 | A sign-in callback works once, only in the browser that began it, before it expires, and only with that ceremony's PKCE verifier and nonce; ID tokens with the wrong audience, issuer, expiry, or key, and callbacks from another issuer, are rejected | `federation: TestStateIsSingleUseAndBound`, `federation: TestNonceAndPKCEAreEnforced`, `federation: TestIDTokenValidation`, `federation: TestIssuerMixUpIsRejected`, `federation: TestGitHubSignIn` |
| 92 | A federated sign-in is single-factor and never fresh: it can't step a session up, extend another factor's freshness, create a PAT, or claim an agent | `TestFederatedSessionsAreNeverFresh`, `TestClaimNeedsAFreshMultiFactorHuman` |
| 93 | Linking an identity needs a fresh human session, finishes only in the session that began it, and is audited in the same transaction | `federation: TestLinkNeedsAFreshHumanSession`, `federation: TestLinkIsBoundToItsSession`, `federation: TestLinkIsAudited`, `storetest: IdentityEventsAreRecorded` |
| 94 | An identity belongs to at most one account, even under concurrency | `federation: TestIdentityCantLinkToTwoAccounts`, `storetest: IdentityIsUnique`, `storetest: ConcurrentLinkHasOneWinner` |
| 95 | The library never creates accounts: an unknown identity signs up only through the application's hook, and only onto an account without an identity, a passkey, recovery codes, or a TOTP factor, checked atomically | `federation: TestSignUpNeedsTheHook`, `federation: TestSignUpHookCantAttachToAnExistingAccount`, `storetest: FirstIdentityIsFirst`, `storetest: ConcurrentFirstIdentity` |
| 96 | Unlinking needs a fresh human session, is audited, and refuses to remove the last sign-in method unless the application reports another | `federation: TestUnlinkRules`, `storetest: DeleteIdentity` |
| 97 | The admin API shows the application's profiles only from its directory, and a directory outage leaves profiles out instead of failing the request | `authadmin: TestDirectoryAddsProfiles` |
| 98 | A first passkey registers only for an account with no passkey, recovery codes, or TOTP factor, checked at begin and again atomically at finish | `passkey: TestFirstRegistrationNeedsNoOtherFactor`, `storetest: FirstCredentialIsFirst` |
| 99 | Unlinking an identity ends the user's other sessions that signed in through an external identity, and keeps the session that unlinked | `federation: TestUnlinkEndsFederatedSessions` |
| 100 | A session whose only factor is a recovery code, alone or with a federated sign-in, can add a passkey and make new recovery codes, but can't create a PAT, approve an OAuth grant or device, link or unlink an identity, change TOTP, remove a passkey, or make admin changes | `TestRecoveryCodeAloneCantMintCredentials`, `TestRecoveryOnlyCoversRecoveryWithFederation`, `totp: TestRecoveryCodeAloneCantChangeTOTP`, `passkey: TestRecoveryCodeCanAddButNotRemoveAPasskey`, `federation: TestLinkNeedsAFreshHumanSession`, `authadmin: TestRecoveryCodeAloneCantMakeChanges` |
| 101 | `Service.Require` checks human, then scopes, then assurance, then recency, records every refusal as `access_denied`, and `WithNeeds` can only tighten a need | `TestRequireChecksInOrder`, `TestWithNeedsOnlyTightens` |
| 102 | A challenge lists only factors the account has that would meet the need, and names adding a passkey when there are none | `TestChallengeListsOnlyFactorsTheAccountHas` |
| 103 | Every library error describes as a specific problem; unknown errors become a 500 that hides their message; problems before identification are identical for every cause | `TestDescribeCoversEveryError`, `TestProblemsBeforeIdentificationAreGeneric`, `authhttp: TestErrorWritesEveryLibraryError` |
| 104 | `authhttp` writes every refusal as `application/problem+json` that is never cached, with an RFC 9470 challenge for a step-up | `authhttp: TestRefusalsAreProblemsWithChallenges` |
| 105 | A recovery code that `recovery.Codes.Check` reserved is spent only when a session starts or steps up with it; an incomplete or expired pending sign-in keeps it, and two sign-ins holding it can't both finish | `TestRecoveryCodeIsSpentOnlyWhenSignInCompletes`, `TestReservedCodeWorksOnce`, `TestExpiredPendingSignInReleasesTheCode`, `storetest: RecoveryCodeIsConsumedOnce` |
| 106 | A sign-in that starts with anything but a passkey needs TOTP when the account has it, even while it is locked; a pending token works once, never authenticates a request, and expires after 5 minutes | `TestRecoveryCodeIsSpentOnlyWhenSignInCompletes`, `TestPasskeySignInNeedsNothingMore`, `TestExpiredPendingSignInReleasesTheCode` |
| 107 | For the recovery hold after a recovery code is used, every session of the account is refused personal access tokens, OAuth grants and approvals, and agent claims; undoing that recovery lifts its hold, never another's | `TestRecoveryHoldsCredentialMinting`, `TestRecoveryHoldCanBeTurnedOff`, `TestUndoRecoveryReversesEverything`, `TestUndoingOneRecoveryKeepsTheHoldOfAnother` |
| 108 | Only a session from before a recovery that never used a recovery code, meeting `NeedUndoRecovery`, can undo it, and every recovery in the window is found however many events follow it; the undo revokes the recovered session and everything created since, disables new agents, removes new factors, and deletes the remaining recovery codes | `TestUndoRecoveryReversesEverything`, `TestUndoingOneRecoveryKeepsTheHoldOfAnother`, `TestRecoverySignInsSeeEveryEventInTheWindow` |
| 109 | `RevokeOwn` and `RevokeOwnAgent` never revoke another account's session or agent, and answer `ErrNotFound` for one; `RevokeOthers` keeps the caller's session and what is delegated from it, and refuses recovery mode | `TestRevokeOwnNeverTouchesAnotherAccount`, `TestRevokeOthersKeepsTheCallerAndRefusesRecovery` |
| 110 | Every request under the admin prefix needs a multi-factor human whichever route serves it; `Mux.Check` refuses a route without a rule, an admin route below a multi-factor human, a missing client key or limiter, and an http origin other than localhost | `authhttp: TestMuxCheckNamesEveryMisconfiguration`, `authhttp: TestAdminPrefixHoldsWhicheverRouteMatches` |
| 111 | No route of a `Mux` serves a principal its need excludes: anonymous, recovery mode, a stale session, or an agent without scopes | `authhttp: TestAuthtestCallsEveryRouteAsExcludedPrincipals` (`authtest.Routes`) |
| 112 | The client key comes from `X-Forwarded-For` only through trusted proxies, read from the right; IPv6 keys are /64 prefixes | `authhttp: TestClientIPTrustsOnlyListedProxies` |
| 113 | Every store keeps a session's device, user agent, and token issue time, and a token swap updates the issue time | `storetest: DeviceAndRotationRoundTrip`, `TestPrincipalsCarryWhenTheirTokenWasIssued` |
| 114 | `WithRotation` rotates only human sessions from the cookie, and only once their token is older than the interval | `authhttp: TestRotationReplacesOldBrowserTokens` |
| 115 | Hints appear only after identification: a reused TOTP code says how long to wait and never counts toward the lockout; a locked factor names itself, and a step-up with another account's passkey is logged but not shown; failures before sign-in stay identical | `totp: TestReusedCodeHintsAndDoesntCountTowardLockout`, `totp: TestTOTPLocksAfter100Failures`, `passkey: TestStepUpWithAnotherAccountsPasskeyIsLoggedNotShown`, `TestFactorErrorsAreIndistinguishable` |
| 116 | `PeekClaim` shows an unclaimed agent without spending its code, only to a human, rate-limited, and answers `ErrClaimInvalid` for every bad code; pairing words are stable per code | `TestPeekClaimShowsTheAgentWithoutSpendingTheCode`, `storetest: ClaimCodeWorksOnce` |
| 117 | `CollectClaimWait` returns as soon as the agent is claimed, waits at most 60 seconds, and stops when its context ends | `TestCollectClaimWaitReturnsOnceClaimed` |
| 118 | An approval redeems at most once, only by the agent that asked, only for an action with the same digest under a need with the same action, and only before it expires; a wrong redeem never spends it; only the approving human's own sessions can view or decide it; the agent must meet the need's scopes and the recovery hold itself, and the approver must meet the whole need | `passkey: TestApprovalBindsOneTapToOneAction`, `passkey: TestDeniedApprovalTellsTheAgent`, `authhttp: TestApprovableTurnsARefusalIntoAnApproval`, `TestApprovalCantStandInForScopesOrTheHold`, `TestOthersCantBurnAnApproval`, `TestRedeemNeedsTheSameNeedAndTheAgentsPart` |
| 119 | An approval needs a passkey assertion over the approval's challenge, and its receipt verifies against the credential's stored key, needs the user-present and user-verified flags, and fails for any other action | `passkey: TestApprovalBindsOneTapToOneAction`, `passkey: TestReceiptNeedsUserPresence` |
| 120 | Every store can read a ceremony without consuming it, and never returns an expired one | `storetest: CeremonyIsConsumedOnce` |
| 121 | A need with a purpose passes only through an elevation for the same purpose and resource, within its window; an elevation never makes the session fresh for anything else, and only a live human session of its own user, with real, non-federated proofs, can elevate | `TestElevationCountsOnlyForItsPurpose`, `TestOnlyHumansWithRealProofsElevate` |
| 122 | Consuming a ceremony matches its kind atomically, so a lookup in one flow never deletes another flow's ceremony | `storetest: CeremonyIsConsumedOnce` |
| 123 | The browser client never holds a token, maps every WebAuthn failure to an outcome a person can act on, steps up only for a challenge a passkey can meet and retries once, and derives only non-extractable PRF keys | `client: test/client.test.ts` (`just client`) |
| 124 | Dev tools answer 404 unless the service has `WithDevTools`, and `Mux.Check` refuses them unless every origin is localhost | `authhttp: TestDevToolsAgeAndRecoverOnlyWhenOn`, `authhttp: TestDevToolsRefuseToStartOutsideLocalhost` |
| 125 | A passkey can be renamed only by its own user, in the same transaction as its audit event | `storetest: RenameCredentialIsOwnedAndAudited`, `passkey: TestRenameAndRegistrationState` |
| 126 | Every route `authroutes.Mount` adds declares its rule and holds it, and a sign-up's finish works only in the browser that began it | `authroutes: TestEveryMountedRouteHoldsItsRule`, `authroutes: TestSignUpFinishNeedsItsOwnBrowser`, `authroutes: TestPasskeysTOTPAndRecoveryThroughTheRoutes` |
| 127 | A device-bound session renews only with a valid proof from its own key over a fresh, single-use refresh challenge, issued only for its current binding; a session gets one registration challenge and is bound once; its token is refused once past its short lifetime however it is sent; a refresh after the session ended tells the browser to drop the binding; DBSC is off unless turned on, and turning it off signs no one out: in retired mode a bound browser gets a plain cookie only after a valid proof, and a copy of its short-lived cookie still expires | `authhttp: TestDeviceBoundSessionsRenewOnlyWithTheKey`, `authhttp: TestDeviceBoundIsOffWithoutTheOption`, `authhttp: TestRetiringDeviceBoundSignsNoOneOut`, `authroutes: TestDeviceBoundIsOptIn` |
| 128 | A password is stored only as an Argon2id PHC string with a 16-byte random salt and parameters at or above the OWASP minimum; a sign-in with other stored parameters rehashes; a stored hash that doesn't parse or exceeds the limits is a server error and is never computed; at most `MaxHashes` computations run at once | `password: TestHashIsArgon2idPHC`, `password: TestWeakParamsAreRefused`, `password: TestSignInRehashesOldParams`, `password: TestBadStoredHashesAreServerErrors`, `password: TestBadStoredHashesDontParse`, `password: TestHashingIsBounded`, `password: FuzzParsePHC`, `storetest: RehashIsCompareAndSet` |
| 129 | Password length counts code points after NFC; the minimum can't be set below 8 or the maximum below 64; a password that is too long is refused, never cut; no rule limits which characters a password holds; a password is checked as received, without trimming or case mapping, and never expires | `password: TestLengthCountsCodePointsAfterNFC`, `password: TestLengthBoundsCantBeWeakened`, `password: TestLongPasswordsAreRefusedNotCut`, `password: TestAnyCompositionIsAccepted`, `password: TestPasswordIsCheckedAsReceived`, `password: TestPasswordIsNormalizedOnlyByNFC`, `password: TestPasswordsNeverExpire`, `password: FuzzPolicy` |
| 130 | A password in the embedded list of at least 3,000 common passwords of 8 or more characters is refused; context words don't count toward the minimum length; a breached password is refused when the check is on, and only 5 characters of its SHA-1 leave the process | `password: TestCommonPasswordsAreRefused`, `password: TestEmbeddedListMeetsThePolicy`, `password: TestContextWordsDontCount`, `password: TestBreachedPasswordsAreRefused`, `password: TestBreachOutageFollowsTheSetting`, `pwned: TestOnlyTheHashPrefixLeaves`, `pwned: TestPaddingAndBoundsAreHandled` |
| 131 | Every failed password sign-in returns the same error and does the same work: one read and one Argon2 verification, for a known address, an unknown one, an address without a password, and a malformed input. One deviation: a sign-in against an imported bcrypt hash that isn't upgraded yet (invariant 177) does up to 2 bcrypt computations instead, so its timing can show that the address has such a hash; the limiter bounds the probing, and the signal ends at that person's first correct sign-in | `password: TestSignInFailuresLookTheSame`, `password: TestSignInDoesTheSameWorkForEveryAddress`, `password: TestFactorErrorsAreIndistinguishableForPasswords`, `TestFactorErrorsAreIndistinguishable` |
| 132 | Sign-up, forgot-password, adding an address, and changing an address return the same answer for every address, with one read, one ceremony write, and one message on every path; a mailer error never changes the answer; with `VerifyFirst`, no account exists before its address is confirmed | `password: TestSignUpAnswersTheSameForEveryAddress`, `password: TestForgotAnswersTheSameForEveryAddress`, `password: TestAddressChangesAnswerTheSame`, `password: TestEveryPathSendsOneMessage`, `password: TestMailerOutageDoesntChangeTheAnswer`, `password: TestVerifyFirstCreatesNothingBeforeConfirmation` |
| 133 | An email code works once, even under concurrency, until it expires (invariant 150), only for its purpose, its user, and its address, and is stored only as a hash; a reset code dies with any password change | `emailcode: TestCodesWorkOnce`, `emailcode: TestCodesLiveWithinTheirCeiling`, `emailcode: TestCodesAreBoundToTheirKind`, `emailcode: TestCodesAreStoredHashed`, `emailcode: FuzzRedeem`, `password: TestCodesAreBoundToUserAndAddress`, `password: TestAPasswordChangeVoidsResetCodes`, `storetest: CeremonyIsConsumedOnce`, `storetest: ConcurrentCeremonyConsume` |
| 134 | A code alone never confirms an address or creates an account: confirming needs the account's session or password, or the browser that signed up; a wrong password spends the code; no code returns a proof or starts a session | `password: TestACodeAloneConfirmsNothing`, `password: TestSignUpConfirmNeedsItsBrowserOrItsPassword`, `password: TestAWrongPasswordSpendsTheCode`, `password: TestCodesNeverSignIn` |
| 135 | An address belongs to at most one user and a user has at most one address, even under concurrency; an unverified address never evicts, and is evicted only by a verified claim; a verified address is never evicted or unverified | `password: TestAnUnverifiedAddressReservesNothing`, `storetest: EmailIsUnique`, `storetest: ConcurrentClaimHasOneWinner`, `storetest: UnverifiedClaimNeverEvicts`, `storetest: VerifiedClaimEvictsUnverified`, `storetest: VerifyEmailIsMonotonic` |
| 136 | The library never creates accounts: a sign-up reaches only the application's hook, and only onto an account without an address, a password, an identity, a passkey, recovery codes, or a TOTP factor, checked atomically; a federated sign-up can't attach to an account with an address | `password: TestSignUpNeedsTheHook`, `password: TestSignUpHookCantAttachToAnExistingAccount`, `storetest: FirstEmailIsFirst`, `storetest: ConcurrentFirstEmail`, `storetest: FirstIdentityIsFirst` |
| 137 | A password alone is single-factor; on an account with a passkey or confirmed TOTP, even a locked one, a session whose strongest method is a password is never fresh, and a password proof can't step up or elevate; a store error in that check refuses; a password sign-in needs TOTP when the account has it | `TestPasswordAloneIsSingleFactor`, `TestPasswordNeverStandsInForAStrongerFactor`, `TestPasswordCantStepUpAStrongAccount`, `TestPasswordStepsUpAnAccountThatIsntStrong`, `TestPasswordCapFailsClosed`, `TestPasswordWithTOTPIsMultiFactor`, `TestChallengeListsOnlyFactorsTheAccountHas`, `TestPasswordSignInNeedsTOTP` |
| 138 | A password session can't claim an agent, change signup overrides, or reach an admin route, and a password can't approve an agent's action | `TestPasswordCantClaimOrApprove`, `passkey: TestApprovalBindsOneTapToOneAction`, `authhttp: TestAdminPrefixHoldsWhicheverRouteMatches` |
| 139 | An account whose address is unverified can't create an agent, claim one, or delegate from a human session, and each refusal is recorded; an account without an address is unaffected; token exchange holds the same rule | `TestUnverifiedAddressCantUseAgents`, `TestAccountsWithoutAnAddressAreUnaffected`, `oauth: TestTokenExchangeHonorsTheAddressGate` |
| 140 | A reset code goes only to a verified address of an account with a password; a reset sets the password by compare-and-set, ends every session, starts none, and changes no other factor, so sign-in still needs the second factor | `password: TestResetNeedsAVerifiedAddress`, `password: TestResetEndsEverySession`, `password: TestResetNeverBypassesSecondFactors`, `password: TestResetHonorsARemovedPassword`, `storetest: SetPasswordIsCompareAndSet`, `storetest: ConcurrentSetPasswordHasOneWinner` |
| 141 | Changing a password needs a fresh human session and the current password, and can end every other session; adding or removing a password and changing the address need a fresh human session; removing refuses the last sign-in method; an address changes only when the new one is confirmed, and the old one is told; the recovery hold covers these changes, and undoing a recovery deletes a password or address set since | `password: TestChangeNeedsAFreshSessionAndTheCurrentPassword`, `password: TestChangeCanEndOtherSessions`, `password: TestFactorChangesNeedAFreshHumanSession`, `password: TestRemoveKeepsTheLastSignInMethod`, `password: TestAddressChangeConfirmsTheNewAndTellsTheOld`, `password: TestRecoveryHoldCoversPasswordChanges`, `TestUndoRecoveryRemovesPasswordAndAddressSetSince`, `federation: TestUnlinkRules` |
| 142 | An administrator can start a reset and invalidate a password, but never sees a code or sets a password; the request records the administrator | `password: TestAdminResetNeverRevealsOrSetsAPassword` |
| 143 | Every password entry point passes the limiter before any other work, and the package refuses to start without one; limits on a target don't depend on whether it has an account; a known device keeps its own budget; no number of failures disables a password or an account | `password: TestLimiterRunsBeforeAnyWork`, `password: TestNewNeedsALimiter`, `password: TestTargetLimitsDontRevealAccounts`, `password: TestKnownDevicesKeepTheirOwnBudget`, `password: TestFailuresNeverLockAnAccount`, `password: TestDefaultRulesNameEveryAction`, `ratelimit: TestTargetLimitsApplyAcrossClients`, `ratelimit: TestDefaultRulesCoverPasswordActions`, `limittest.Run` |
| 144 | No password, hash, code, or address reaches an event, a log line, or an error; a code redacts itself under every fmt verb, `slog`, JSON, and text | `password: TestSecretsNeverReachEventsLogsOrErrors`, `password: TestSecretRedactsItself`, `TestRawTokensNeverLeaveTheService` |
| 145 | Every address and password change records its event in the same transaction and sends its notice; every failed and throttled attempt is recorded with its action and client, and its user when known | `password: TestEveryChangeIsAuditedAndNotified`, `password: TestFailedPasswordAttemptsAreAudited`, `storetest: EmailEventsAreRecorded`, `storetest: FailedEmailOperationsRecordNoEvent` |
| 146 | Erasing a user's factors deletes the address and the password and keeps the events | `storetest: DeleteUserFactorsDeletesEmails` |
| 147 | `authroutes.Mount` serves the password routes unless the application sets `PasskeyOnly`, and each declares its rule and holds it; an address can't carry a control character or a separator | `authroutes: TestPasswordsAreOnUnlessPasskeyOnly`, `authroutes: TestEveryMountedRouteHoldsItsRule`, `authroutes: TestPasswordsThroughTheRoutes`, `password: TestAddressesCantInjectHeaders`, `password: FuzzNormalizeEmail` |
| 148 | A typed email code has 40 bits from `crypto/rand`, is stored only as an Argon2id hash with a 16-byte random salt, works once and spends its link, works only on the device that started the flow, and dies after 5 wrong guesses even under concurrency; a code lives at most 72 hours, and at most 10 minutes when it proves possession | `emailcode: TestTypedCodesWorkOnce`, `emailcode: TestTypedCodesDieAfterFiveWrongTries`, `emailcode: TestTypedCodesAreBoundToTheirDevice`, `emailcode: TestTypedCodesAreStoredWithASaltedHash`, `emailcode: TestTypedCodesParseLeniently`, `emailcode: TestCodesLiveWithinTheirCeiling`, `emailcode: FuzzParseTyped` |
| 149 | A typed code works only on the device that started its flow: the browser binding of a sign-up or a reset, or the session that asked; never with a password instead, and never in another session or browser; every guess passes the limiter for the client and for the device; a link opened on another device still confirms only with the account's session or password, or the sign-up's browser | `password: TestTypedCodesFinishOnTheStartingDevice`, `password: TestTypedCodesDieAfterFiveWrongGuesses`, `password: TestALinkOnAnotherDeviceStillNeedsTheDesignsRule`, `password: TestACodeAloneConfirmsNothing`, `ratelimit: TestDefaultRulesCoverPasswordActions` |
| 150 | A code that confirms an address lives `ConfirmTTL`, 24 hours by default and at most 72; a reset code lives `ResetTTL`, at most 10 minutes; confirming an address never starts a session or returns a proof; every message with a code carries the link code, the typed code when a device started the flow, and how long they work, and a reset an administrator started carries no typed code | `password: TestCodeLifetimesFollowTheirKind`, `password: TestConfirmingNeverStartsASession`, `password: TestCodesNeverSignIn`, `password: TestMessagesCarryTheLinkAndTheCode`, `password: TestLengthBoundsCantBeWeakened` |
| 151 | Opening a link from an email changes nothing: `authroutes` serves each link as a page that posts the code only when the person presses its button, never holds the code in its HTML, can't be framed, and isn't cached; no `GET` route changes state; the typed code works through the routes only in the browser that started | `authroutes: TestEmailLinksChangeNothingOnGet`, `authroutes: TestTypedCodesThroughTheRoutes`, `authroutes: TestEveryMountedRouteHoldsItsRule` |
| 152 | A reset email carries a typed code only when the browser that asked holds a known-device token for the account and its current password version; a code relayed to any other browser redeems nothing; the reset link works on any device but only by a post from its page; an address-change code confirms only in the session that asked; every email with a typed code says what it does and never to share it | `password: TestResetCodesAreTypedOnlyForTrustedDevices`, `password: TestAddressChangeNeedsItsSessionAndTheCode`, `password: TestMessagesCarryTheLinkAndTheCode`, `password: TestResetNeverBypassesSecondFactors`, `password: TestForgotAnswersTheSameForEveryAddress`, `authroutes: TestTypedCodesThroughTheRoutes`, `authroutes: TestEmailLinksChangeNothingOnGet` |
| 153 | A released preset's expansion never changes: every `@1` preset matches its golden file, field by field, and `Get` returns a copy | `preset: TestReleasedPresetsNeverChange`, `preset: TestGetReturnsACopy` |
| 154 | Each preset states its ASVS level, the Level 2 requirements it misses, and its deviations as data, each deviation recorded in `docs/security/asvs-5.0.md`; a single-factor full session always lists 6.3.3, a breached-password check that isn't required always lists 6.2.12, and a preset that claims Level 2 has the recovery gate, multi-factor full sessions, and 15 characters; `strict@1` refuses a configuration without the breached-password check; every expansion is accepted by `auth.New` and `password.New` | `preset: TestPresetsStateTheirLevelHonestly`, `preset: TestStrictNeedsTheBreachCheck` |
| 155 | Under a recovery gate, no need at `AssuranceMulti` passes until the account has a second factor and a confirmed recovery path; generating new codes voids the confirmation; a store error refuses; each refusal is recorded | `TestRecoveryGateHoldsFullSessions`, `TestNewRecoveryCodesNeedConfirming`, `TestRecoveryGateFailsClosed`, `recovery: TestConfirmChecksWithoutSpending`, `preset: TestStrictHoldsFullSessionsUntilRecovery` |
| 156 | A nudge is required while the recovery gate is unmet, and otherwise offered at most once per the preset's interval; no offer has a permanent opt-out | `preset: TestNudgesFollowThePreset` |
| 157 | An authorization request names at most one resource (RFC 8707), and only a registered one; every token of the grant carries it; a code redeems only for its own resource; a refresh copies it from the grant and refuses another; introspection reports it as `aud`; the device flow takes none | `oauth: TestResourceIsBoundToTheGrant`, `oauth: TestUnknownResourceIsInvalidTarget`, `oauth: TestCodeRedeemsOnlyForItsResource`, `oauth: TestIntrospectionReportsTheAudience`, `TestRefreshKeepsTheResource`, `storetest: ResourceRoundTrips` |
| 158 | A token bound to a resource authenticates only at that resource: `authhttp` refuses it unless configured for it with `WithResource`, with a 401 whose detail says the token is for a different resource without naming it, and a log warning that names it, and userinfo and token exchange refuse it; `mcpauth` accepts only an OAuth access token whose audience is its own resource, so a PAT, a `gh` token, an agent token, a refresh token, a human session, and a token for another resource get 401; the raw token never reaches the MCP handler | `authhttp: TestResourceTokensStayAtTheirResource`, `authhttp: TestResourceRefusalExplainsItself`, `oauth: TestResourceTokensCantReachUserinfoOrExchange`, `mcpauth: TestWrongAudienceIsRejected`, `mcpauth: TestOtherTokenKindsAreRejected`, `mcpauth: TestTheRawTokenStaysInTheMiddleware` |
| 159 | Every redirect from the authorization endpoint that carries a code or an error carries `iss` (RFC 9207), in the query or the fragment, whether the provider or zitadel/oidc raised the error; the metadata, served at both the OpenID Connect and the RFC 8414 URIs, sets `authorization_response_iss_parameter_supported` and offers only `S256` | `oauth: TestEveryAuthorizationResponseCarriesIss`, `oauth: TestMetadataForMCP` |
| 160 | A client ID metadata document is fetched only from a valid `https` client ID URL on port 443, never from an address outside the allowlist of public IPv4 and IPv6 ranges, checked after DNS resolution at dial time, without a proxy or redirects, within 5 KiB and 5 seconds, and only after the limiter allows it; errors and invalid documents are never cached; the cache holds at most 1,000 documents and follows the cache headers within 1 minute and 24 hours; only a transient failure serves the last valid document, for at most 24 hours | `oauth: TestCIMDFetchRefusesPrivateAddresses`, `oauth: TestCIMDFetchFollowsNoRedirects`, `oauth: TestCIMDFetchIsBounded`, `oauth: TestCIMDCacheFollowsHeaders`, `oauth: TestCIMDFetchRefusesBadURLs`, `oauth: TestCacheLifetime`, `safefetch: TestIsPublic`, `safefetch: TestFetchRefusesLoopbackWithoutTheTestOption`, `safefetch: TestFetchBounds` |
| 161 | A document client is accepted only when its `client_id` equals the URL, it has a clean name of at most 100 bytes and 1 to 10 redirect URIs that are `https` or loopback `http`, it carries no secret, and it can authenticate with `none`; its redirect must match exactly, a loopback entry on any port of the same host; it gets only the code and refresh grants; CIMD is off, allowlisted, or open, and allowlisted to `DefaultCIMDHosts` by default | `oauth: TestCIMDDocumentRules`, `oauth: FuzzParseClientMetadata`, `oauth: TestCIMDRedirectsMatchExactly`, `oauth: TestCIMDModes`, `oauth: TestCIMDClientSignsIn` |
| 162 | A dynamic client (from a metadata document or registration) never skips consent, needs a registered resource, and gets only its scopes; a loopback redirect never skips consent for any client, first-party included; the consent request names the client ID, its verified host, its claimed name, where it came from, the redirect host, the resource, and the scopes, and carries `WarningLoopback` for a loopback redirect; every approval on the consent page is recorded as `oauth_consented` before its code exists, and a store error fails the approval | `oauth: TestDynamicClientsAlwaysSeeConsent`, `oauth: TestDynamicClientsNeedAResource`, `oauth: TestLoopbackNeverSkipsConsent`, `oauth: TestConsentRequestNamesEverything`, `oauth: TestApprovalsAreRecorded` |
| 163 | Dynamic client registration (RFC 7591) is off unless `Config.Registration` is set; it passes the limiter before any other work, admits only public clients that state an `application_type` whose redirect URIs fit it (loopback `http` for `native`, `https` on other hosts for `web`), records each registration, and a registered client expires after its TTL | `oauth: TestRegistrationIsOffByDefault`, `oauth: TestRegistrationRules`, `oauth: TestRegistrationIsRateLimited`, `oauth: TestRegisteredClientsExpire`, `ratelimit: TestDefaultRulesCoverPasswordActions` |
| 164 | `mcpauth` reads a token only from one `Authorization: Bearer` header, never a cookie or the query; its challenges carry `resource_metadata` and the base scopes, with `invalid_token` for a bad token and no error code without one; a refused scope gets one 403 `insufficient_scope` naming every scope the request needs, batches included, broader scopes satisfying narrower ones; an unlisted tool is refused; a verifier failure, including any introspection answer it can't trust, is a 503 without a challenge, and the introspection cache lasts at most 5 seconds | `mcpauth: TestOnlyBearerHeaders`, `mcpauth: TestChallengesFollowTheSpec`, `mcpauth: TestInsufficientScopeNamesEveryScope`, `mcpauth: TestScopeHierarchy`, `mcpauth: TestUnlistedToolsAreRefused`, `mcpauth: TestVerifierFailureIsUnavailable`, `mcpauth: TestIntrospectionFailsClosed`, `mcpauth: TestNewRefusesBadOptions` |
| 165 | Each OAuth grant for a resource is a connection listed on its own; revoking one ends it and every token under it at once and leaves the user's other grants, from the same client included; only a human session of its own user revokes it through `RevokeConnection`; every tool call is recorded as `tool_called` with its grant, tool, decision, and argument hash, never the arguments | `TestConnectionsAreGrantsRevokedOneByOne`, `TestOnlyTheOwnerRevokesAConnection`, `TestToolCallsAreRecorded`, `mcpauth: TestToolCallsAreAudited`, `mcpauth: TestAuditToRecordsToolCalls`, `authadmin: TestConnectionsRoute` |
| 166 | The tool a request runs is the tool its scopes were checked for: the authoritative check runs in SDK middleware that `mcpauth.Protector.Handler` always installs, on the request the SDK parsed and will run; the HTTP pre-check refuses with 400 any body with a duplicate key at any depth, a key that differs from `jsonrpc`, `id`, `method`, `params`, or `name` only in case, nesting deeper than 64 levels (walked without recursion), a parse failure, a `tools/call` without a string `params.name`, or a batch of the wrong shape; a batch with any forbidden tool runs none | `mcpauth: TestAmbiguousBodiesAreRefused`, `mcpauth: TestBatchMixingToolsIsRefused`, `mcpauth: TestTheSDKRunsOnlyTheAuthorizedTool`, `mcpauth: TestToolScopesAreEnforcedTwice`, `mcpauth: TestDepthIsBounded`, `mcpauth: FuzzParseCalls`, `mcpauth: FuzzNoDuplicateKeys` |
| 167 | `authhttp.Bridge` keeps one bridged session per sign-in to the application, in `__Host-bridge` (`HttpOnly`, `Secure`, `SameSite=Lax`, host-only), and reuses it; a new sign-in to the application, even by the same person, starts a new session and revokes the old one; the session keeps the application's sign-in time to the second and lives at most `MaxAge`, 1 hour by default | `authhttp: TestBridgeReusesOneSession`, `TestBridgedSessionsKeepTheAppsTime` |
| 168 | On every request, the bridge compares its session with the application's current user, sign-in time, and scopes, compared as sets; when the user signs out, another user signs in, the scopes narrow or widen, or the cookie arrives without the matching application session, it revokes the session before anything else and never uses it; it never uses a session it didn't start; it refuses unsafe cross-origin requests; `authhttp.Middleware` refuses a bridged session from a cookie or a header, recorded with reason `bridged` | `authhttp: TestBridgeFollowsTheAppUser`, `authhttp: TestBridgeFollowsTheAppScopes`, `authhttp: TestBridgeRefusesCrossOriginPosts`, `authhttp: TestMiddlewareRefusesBridgedSessions` |
| 169 | A bridged session is no stronger than the application says: its methods hold `bridged`, shown on `session_started`; it needs the application's `AuthenticatedAt` and is never fresher; it meets only needs that set `Need.Bridged` (approving an OAuth grant and redeeming its code, under the normal freshness rules), so a PAT, claiming or creating an agent, delegating or exchanging a token, admin changes, and factor changes refuse it with `stronger_factor_required` and reason `bridged`; `WithNeeds` can't add `Bridged`; no proof carries the bridged method; a real factor's step-up lifts the restriction; tokens it approves carry its methods and can't be delegated | `TestBridgedSessionsMeetOnlyBridgedNeeds`, `TestBridgedSessionsKeepTheAppsTime`, `oauth: TestBridgedSessionApproves` |
| 170 | Consent is never skipped because of the bridge: with a bridged session, a dynamic client and a loopback redirect still see the consent page, `prompt=none` answers `consent_required`, and every approval is recorded before its code exists | `oauth: TestBridgeNeverSkipsConsent`, `examples/mcpserver: TestOwnLoginBridgesTheConsent` |
| 171 | `mcpauth.JWT` allows only asymmetric algorithms (RS, PS, ES, and EdDSA), at configuration and at parse time, so `none` and HMAC never reach a key; a key is used only when it fits the token's `alg` and its own declared `alg` and `use`, RSA keys need 2,048 bits, and private and symmetric keys are ignored; `kid` is at most 256 bytes and only a lookup key; `crit`, JWE, and JSON serialization are refused; an unknown `kid` refetches the keys at most once per `MinRefetch`, 1 minute by default and at least 10 seconds | `mcpauth: TestJWTRejections`, `mcpauth: TestJWTRefetchIsBounded`, `mcpauth: TestJWTRefusesBadConfig` |
| 172 | A JWT is accepted only with `iss` equal to the issuer byte for byte, `sub`, `exp` not past and `nbf` and `iat` not in the future beyond the skew (30 seconds by default, at most 5 minutes), an `aud` that includes the MCP resource in canonical form, and a `typ` that is absent, `JWT`, or `at+jwt` (only `at+jwt` with `RequireTyp`), and without the ID token claims `nonce`, `at_hash`, and `c_hash`; with `MaxAge`, `iat` is required and caps `ExpiresAt`; the Protector checks the audience again | `mcpauth: TestJWTRejections`, `mcpauth: TestJWTFromAThirdPartyServer` |
| 173 | The JWT verifier fetches keys and metadata only through `safefetch`: https on port 443 to a public address, or a loopback URL for a loopback issuer, without a proxy or redirects, within 64 KiB and 5 seconds; discovered metadata must name the configured issuer and a `jwks_uri` that follows the same rules; keys are cached for their `max-age` between 5 minutes and 24 hours; a fetch failure, or keys that expired during an outage, is `ErrUnavailable`, a 503, and retries wait `MinRefetch` | `mcpauth: TestJWTKeysAreFetchedSafely`, `mcpauth: TestJWTOutageIsUnavailable`, `safefetch: TestFetchAllowsHTTPOnlyToLoopback` |
| 174 | A JWT access token from an authorization server that isn't this library, zitadel/oidc's `op` provider, calls a tool on an `mcpauth`-protected server, and a token from it for another audience gets 401 | `mcpauth: TestJWTFromAThirdPartyServer` |
| 175 | An approval works under `WithNeeds`: the agent that asks or redeems meets only the agent part (scopes and the recovery hold) of the need after `WithNeeds` tightened it, so a floor that marks the action `Human` doesn't refuse the agent, but a floor's scopes and hold still apply to it, and the approver meets the whole tightened need | `TestApprovalsWorkWithNeeds`, `authhttp: TestApprovableWorksWithNeeds` |
| 176 | `VerifyAudit` never seals, so it never vouches for an event that may have changed before sealing; `UnsealedAudit` counts every committed event that isn't sealed, with the oldest one's time, and the admin API's chain status reports both | `TestUnsealedAuditReportsTheTail`, `storetest: SealEventsBuildsTheChain`, `authadmin: TestAuditChainStatus` |
| 177 | The server refuses to start, naming the setting and the fix and never echoing a secret, for every case its design lists: a missing or unreachable database, a schema newer than the binary in any `migrate` mode, pending migrations under `migrate=check`, bad origins or `rp_id`, a missing or malformed master key, passwords without a mailer, an unknown key or `TENSILE_AUTH_` variable, a value that doesn't parse, `dev` outside localhost, and running as root | `server: TestStartupRefusals`, `server: TestUnknownKeysAndVariablesStopTheServer`, `server: TestANewerSchemaStopsTheServerInEveryMode`, `server: TestMigrateModes`, `server: TestAPostgresThatDoesntAnswerIsRefused` |
| 178 | The server shuts down in order: readiness fails first, in-flight requests finish within `shutdown_timeout`, and only then does `svc.Run` stop, so no event an in-flight request records is left unsealed or unwritten | `server: TestShutdownSealsInFlightEvents` |
| 179 | The server is ready only while the database answers, both schemas match the binary, the rate-limit backend answers, `svc.Run` runs, and, with the cache on, the watcher listens; each failed check is named | `server: TestReadinessNamesEachFailedCheck`, `server: TestServeMigratesAndIsReady` |
| 180 | The server keeps every key it stores sealed under the master key, which is never stored; a master key that doesn't open the key-check value stops `serve`, `check`, and `keys` before any key is generated or changed, and `keys rewrap` changes nothing unless every key opens under the current master key | `server: TestAWrongMasterKeyStopsTheServerAndGeneratesNoKeys`, `server: TestKeysStatusRotateAndRewrap` |
| 181 | Key rotation never strands a secret or a signature: a rotated TOTP key keeps opening the secrets it sealed while the server reseals them under the new key with compare-and-set; the OpenID key set publishes the next key 24 hours before it signs and keeps the old one 24 hours after; webhooks sign with both secrets for 24 hours; and old checkpoint public keys stay | `server: TestTOTPRotationReseals`, `server: TestOpenIDKeySetCarriesBothKeysDuringRotation`, `server: TestWebhookAndCheckpointRotation` |
| 182 | Behind an app's proxy that changes `Host`, the server's browser routes keep the library's protections: `__Host-` cookies on the app's origin, the configured origins trusted for cross-origin protection and a cross-site request with the cookie refused, and every route meeting its rule | `server: TestBrowserFlowsThroughAProxyThatChangesHost`, `server: TestEveryServerRouteMeetsItsRule` |
| 183 | The server's mail leaves only over TLS outside loopback (SMTP with STARTTLS or `smtps://`, or an `https://` webhook), and every webhook carries a Standard Webhooks signature made with each live webhook secret | `server: TestSMTPWithoutSTARTTLSIsRefusedOutsideLoopback`, `server: TestPasswordMailGoesToTheSignedWebhook`, `server: TestWebhookMailerFailsOnARefusal` |
| 184 | An app key alone checks nothing: every `/v1` call but the document needs a live `tsx_` key, which is stored only as a hash and stops at once when revoked; a missing, malformed, revoked, or unknown key answers 401 `app_key_invalid` | `server: TestAppKeysLookLikeTokensAndOnlyLiveOnesWork` |
| 185 | `/v1/check` applies `authhttp.Middleware`'s rules by serving the end user's rebuilt request through it: only human session tokens as `cookie`, cross-origin protection on cookie requests from `request.origin` and `request.sec_fetch_site`, a `request.url` outside `origins` refused, and the need applied by `RequireNeed` or `Approvable` | `server: TestCheckAppliesTheMiddlewaresRules`, `server: TestCheckRefusesAgentTokensAsCookies` |
| 186 | The `/v1` and browser OpenAPI documents and the handlers can't drift: every route is documented and every documented path is a route, each `/v1` request and response type's fields match its schema, each browser route's documented security and `x-tensile-action` match its rule, and the merged document equals a fresh merge, which refuses a path in two documents or a shared component defined two ways | `server: TestV1DocumentMatchesTheRoutes`, `server: TestMergedDocumentIsCurrent`, `server: TestMergeRefusesConflicts`, `authroutes: TestOpenAPIMatchesTheRoutes` |
| 187 | `PendingApprovals` lists only the viewer's own approvals that are still pending and unexpired, and only for a human session; another person and an agent get none; every approval event names its approval in `Factor` | `TestPendingApprovalsListsOnlyYourOwnWaitingRequests` |
| 188 | The account routes that `authroutes.Mount` serves for the elements (approvals, sessions, activity, and undoing a recovery) refuse agents, and read or change only the signed-in person's own approvals, sessions, agents, and events: another person's approval or session is not found; the activity route leaves out client keys and approval receipts, and verifies the whole chain at most once a minute, one check at a time, in the background under a context no request can cancel; tampering (`ErrAuditTampered`) is kept at once until a later verification; a verification counts for 3 intervals; a cancellation, timeout, or store error is shown as a failed check and never extends a verification, so the state turns `unavailable` | `authroutes: TestApprovalRoutesArePeopleOnlyAndScoped`, `authroutes: TestSessionRoutesAreScopedToThePerson`, `authroutes: TestActivityShowsOnlyYourEventsAndTheChain`, `authroutes: TestUndoRecoveryRefusesSessionsThatArentYours`, `authroutes: TestACanceledRequestDoesntChangeTheChainState`, `authroutes: TestAStoreErrorDoesntKeepVerifiedPastItsAge`, `authroutes: TestTamperingWinsOverAnOlderVerification`, `authroutes: TestOneChainCheckRunsAtATime` |
| 189 | A session in recovery mode can revoke with `RevokeOwn` only itself and what is delegated from it; any other session of the account needs `NeedRevokeOthers`, which recovery mode fails with `stronger_factor_required`, so a stolen recovery code can't sign the owner out of the devices that could undo the recovery | `TestRecoveryModeCantRevokeTheOwnersOtherSessions`, `authroutes: TestARecoveryCodeCantSignTheOwnerOut` |
| 190 | A bcrypt hash verifies only when `Config.AcceptBcrypt` is on, and is otherwise a server error that is never computed; a cost below 10 or above 14 is never computed; bcrypt runs under the `MaxHashes` gate, tries at most 2 forms (NFC, then the bytes as typed), and keeps the 72-byte truncation; the first correct password replaces it with Argon2id by compare-and-set at the same version; no code path creates a bcrypt hash | `password: TestBcryptIsOffByDefault`, `password: TestBcryptCostIsBounded`, `password: TestBcryptRunsUnderTheHashGate`, `password: TestBcryptTriesAtMostTwoForms`, `password: TestBcryptKeepsThe72ByteTruncation`, `password: TestBcryptSignsInAndRehashes`, `password: TestBcryptIsNeverCreated`, `password: FuzzParseStored` |
| 191 | An export is always age-encrypted, to a recipient or a generated 128-bit passphrase, and refuses without one; its file is created with mode 0600 and never overwrites one; it records `export_started` before the first byte, stopping when it can't, and `users_exported` after the last, with the recipients' fingerprints; a TOTP key ring that is missing or doesn't open a secret stops it, saying how many, unless TOTP is skipped; it holds no session, token, audit event, unconfirmed TOTP factor, or unclaimed agent | `authexport: TestExportRefusesWithoutARecipient`, `authexport: TestExportIsAlwaysEncrypted`, `authexport: TestExportNeverOverwritesAFile`, `authexport: TestExportIsAudited`, `authexport: TestExportRefusesTOTPSecretsThatDontOpen`, `authexport: TestExportLeavesOutSessionsAndTokens` |
| 192 | An import stores the whole file or nothing, and refuses a target with sign-in records unless it merges; a file for another relying party ID unless it drops passkeys; an unknown major version or line type; a missing header or end line, counts that differ, or a line over 1 MiB; a password hash that the password package doesn't verify, or bcrypt with it off; two users with one normalized address, even when it merges; a credential whose data doesn't match its ID and public key; and a file that doesn't decrypt with its identity. A dry run runs every check and stores nothing. Every person signs in on the target as the same user, and what failed before still fails | `authexport: TestImportRefusesATargetThatIsntEmpty`, `authexport: TestImportRefusesAnotherRelyingParty`, `authexport: TestImportRefusesAnUnknownVersion`, `authexport: TestImportRefusesAnUnknownLineType`, `authexport: TestImportRefusesAnIncompleteFile`, `authexport: TestImportRefusesCountsThatDiffer`, `authexport: TestImportRefusesLongLines`, `authexport: TestImportRefusesBadPasswordHashes`, `authexport: TestImportRefusesSharedAddresses`, `authexport: TestImportRefusesTamperedCredentials`, `authexport: TestImportNeedsTheRightIdentity`, `authexport: TestImportDryRunStoresNothing`, `authexport: TestRoundTripSignsEveryoneIn`, `authexport: TestGoldenExport`, `authexport: FuzzParse` |
| 193 | An export reads every sign-in record in one read-only snapshot, in byte order of the user ID, and leaves out unclaimed agents; an import stores all its rows and its event in one transaction or nothing, refuses a store with any sign-in record unless it merges, and a merge skips a user whose ID, address, user handle, credential, recovery code, or identity exists, never overwriting a record or attaching one to another user | `storetest: ExportCoversEveryRecord`, `storetest: ExportOrdersByteWise`, `storetest: ExportIsASnapshot`, `storetest: ExportReadsPastOneBatch`, `storetest: ExportLeavesOutUnclaimedAgents`, `storetest: ImportRoundTrips`, `storetest: ImportedRecordsWork`, `storetest: ImportRefusesAStoreThatIsntEmpty`, `storetest: ImportIsAllOrNothing`, `storetest: MergeSkipsConflictsWhole`, `storetest: MergeNeverOverwrites` |
| 194 | An import never attaches an agent to a user who existed before it: a file whose agent names an owner that isn't a user in the file is refused, and a store stores an agent only for an owner that the same import stored, so a merge skips and reports an agent whose owner existed or was skipped; an imported agent's name and scopes follow the rules of `CreateAgent`. Scopes aren't capped by the owner's, because the library stores no scopes for a user, and `Delegate` grants a session only scopes that both the owner's session and the agent hold | `authexport: TestImportRefusesAnAgentWithAnUnknownOwner`, `authexport: TestMergeSkipsAgentsOfExistingUsers`, `authexport: TestImportRefusesInvalidAgents`, `storetest: ImportedAgentsNeedAnImportedOwner` |
| 195 | An agent's wait for an approval (`Prefer: wait`, `RedeemApprovalWait`) lasts at most 60 seconds, ends when the person approves or denies, when the approval expires, or when the client disconnects, and leaves an undecided approval untouched; one agent holds at most 4 waits and a service at most 1,024, and a wait over either limit answers `approval_pending` at once; concurrent waits on one approval run the route at most once | `TestApprovalWaitEndsAtTheDecision`, `TestApprovalWaitRunsOnceForConcurrentWaiters`, `TestApprovalWaitEndsWithTheClient`, `TestApprovalWaitEndsAtExpiry`, `TestApprovalWaitsAreBounded`, `authhttp: TestApprovableHoldsTheRetryUntilTheDecision`, `authhttp: TestApprovableWaitEndsWhenTheClientDisconnects` |
| 196 | A wait for an approval never runs the route with a stale credential: before every redeem, the first and each after a wake-up, the agent's token is authenticated again through the store, so a token, agent, or session tree revoked or expired during the wait gets 401 and leaves the approval unspent; the redeem still needs that agent's own approval for the same digest; and `Approvable` runs the route as the principal from that last check | `TestApprovalWaitChecksTheTokenAgain`, `authhttp: TestApprovableRefusesATokenRevokedDuringTheWait`, `authhttp: TestApprovableHoldsTheRetryUntilTheDecision` |
| 197 | While an agent has a pending, unexpired approval for an action with the same digest under a need with the same action, asking again returns that approval and records nothing, concurrent requests included; another action, need, or agent, and a decided or expired approval, get a new one. The approval link comes only from configuration (`auth.WithApprovalURL`, an absolute https or loopback URL, or `authhttp.WithApprovalURL` joined to `WithOrigins`), never from the request's `Host` or forwarded headers | `TestAnAgentThatAsksAgainGetsTheSameApproval`, `TestApprovalURLComesOnlyFromConfiguration`, `authhttp: TestApprovableAsksOnceAndLinksToTheConfiguredOrigin` |
| 198 | An approval lives for its need's `ApprovalTTL`, 5 minutes by default, both while it waits for the person and after the grant while it waits for the agent; a TTL outside 1 minute to 24 hours is refused by `RequestApproval` and `New`, and makes `Approvable` panic; a `WithNeeds` floor keeps the shorter TTL | `TestApprovalTTLIsConfigurableWithinLimits`, `authhttp: TestApprovableTakesTheNeedsApprovalTTL` |
| 199 | `WithApprovalNotifier` runs once for each new approval, after it is stored and recorded, and never for a refused request or one answered with an approval that was already pending; it runs in its own goroutine, at most 32 at a time, under a context the request's end doesn't cancel and that ends after 30 seconds, so it never delays or fails the request; a busy notifier, an error, and a panic are logged | `TestApprovalNotifierRunsOncePerNewApproval`, `TestApprovalNotifierNeverBlocksOrFailsTheRequest`, `TestApprovalNotificationsAreBounded` |
| 200 | In `examples/agents`, an agent's own token reaches `/mcp` only for its household, and `task_mark_paid` pays only after its person's approval, once, through the same need and digest as the API route; the payment's action carries the amount, currency, payee, and task, so a changed task needs a new approval; and a task turns paid only from done, so two payments can't both win | `examples/agents: TestTour`, `examples/agents/cmd/errands: TestPayAsksShowsTheLinkAndWaits` |
| 201 | `/v1/check` gives app requests the rest of `authhttp.Middleware`'s rules: a token bound to a key works only as `DPoP` with a proof for exactly `request.method` and `request.url` on a configured origin, once, with the replay cache shared by every replica on Postgres; a session cookie older than 15 minutes comes back rotated in `set_cookies` with the library's attributes; and an agent that misses a human-only need gets an approval for exactly `approval.action`, which redeems once and only for that action after its human approves | `server: TestCheckNeedsAProofForDPoPBoundTokens`, `server: TestCheckRotatesOldSessionCookies`, `server: TestCheckApprovalRoundTrip` |
| 202 | A leaked app key stops working when a signed secret-scanning alert reports it: `leakscan` asks each `WithRevoker` hook after `RevokeLeaked`, labels a token `true_positive` when one knows it, and answers 503 so the provider retries when one can't tell; the server revokes only the reported key and records `server.app_key_leaked` with where it was found, and counts a key as handled only when it revoked it or found it revoked already, so a failed revocation answers 503 and the provider's retry revokes it; an unsigned alert changes nothing; every route the server serves is in its published document | `leakscan: TestRevokersRevokeTheApplicationsOwnKeys`, `server: TestALeakedAppKeyIsRevoked`, `server: TestALeakedAppKeyIsRetriedWhenTheRevocationFails`, `server: TestEveryServedRouteIsDocumented` |
| 203 | `tensile-auth-server export` refuses without a recipient when standard input isn't a terminal, to write to a terminal, to overwrite a file, with a wrong master key, with a TOTP secret that doesn't open, and with a schema that isn't the binary's, and leaves no file behind when it fails; it writes a mode 0600 file, records `export_started` and `users_exported` with `Source` `cli`, and prints a generated passphrase once; `import` refuses bcrypt unless `passwords.accept_bcrypt` is on, another relying party ID, a target that isn't empty, a missing or wrong identity, an unsupported source, and a wrong master key, storing nothing; a dry run stores nothing; after a round trip the person signs in with the same password, which is upgraded to Argon2id, and the TOTP secret opens under the target's keys; `check` reports the bcrypt hashes that remain | `server: TestExportAndImportRoundTrip`, `server: TestExportRefusals`, `server: TestExportPrintsAPassphraseOnATerminal`, `server: TestImportRefusals`, `server: TestCheckReportsBcryptHashes` |
| 204 | An export or a finished export raises a high-severity admin alert, `export_started` or `users_exported`, so an administrator sees every credential dump | `authadmin: TestExportsRaiseAlerts` |
| 205 | An app key alone acts for nobody: `POST /v1/agents`, `POST /v1/agents/{id}/delegate`, `POST /v1/approvals`, and `GET /v1/sessions/tree` act only as the person whose own credential is the subject, authenticated with `authhttp.Middleware`'s rules, and a missing or invalid subject, an agent token as a cookie, a key-bound token, or a subject with two credentials answers 401 `unauthenticated` and changes nothing; a missing app key answers 401 `app_key_invalid` | `server: TestAnAppKeyAloneActsForNobody`, `server: TestPersonRoutesActAsTheSubject` |
| 206 | Approvals through `/v1` follow the library's deduplication and TTL: asking again for the same pending action returns the same approval, `approval_ttl_seconds` sets its lifetime, a TTL outside 60 to 86,400 seconds is a 400 and never reaches `Approvable`, and `/v1/check` without a `Prefer` header answers a pending approval at once and offers no wait | `server: TestPersonRoutesActAsTheSubject`, `server: TestCheckHoldsARequestOnlyWithPrefer` |
| 207 | `GET /v1/users/{id}` answers the address or `null`, and 404 `not_found` for a user with no session, agent, or address; the server's browser routes for a person refuse agents, act only on the signed-in person's own agents, and are documented with their action | `server: TestUsersRouteAnswersAddressOrNull`, `server: TestBrowserPersonRoutesArePeopleOnlyAndScoped`, `server: TestServerBrowserRoutesMatchTheirDocument` |
| 208 | The server's OAuth consent and device routes refuse signed-out callers and agents, leave the request undecided when they refuse, approve only for a human who signed in within `oauth.ApproveFreshFor`, decide each request once, and are documented with their action | `server: TestConsentAndDeviceRoutesArePeopleOnly`, `server: TestDeviceApprovalThroughTheServer`, `server: TestConsentThroughTheServer`, `server: TestConsentRoutesMatchTheirDocument` |
| 209 | `GET /v1/events/stream` needs a live app key, sends `ready` once subscribed and `invalidate` within 100 milliseconds of a revocation, and serves nothing while the server can't hear every change: when the Postgres watcher loses its connection, every stream ends and a new one answers 503 until it listens again; shutdown ends every stream | `server: TestARevocationReachesTheStreamWithin100ms`, `server: TestTheStreamEndsWhileChangesCantBeHeard` |
| 210 | The sign-up hook fails closed: a timeout of 2 seconds, a non-200 answer, an answer without a Standard Webhooks signature for the request's own `webhook-id` with a live secret and a timestamp within 5 minutes, an answer without `allow`, or a `user_id` that is malformed or names a user the server knows refuses the sign-up with 503; `allow: false` refuses it with 403 `signup_rejected`; a failed session scopes hook gives the session no scopes, never the defaults | `server: TestTheSignUpHookFailsClosed`, `server: TestTheScopesHookFailsClosed` |
| 211 | Webhooks are read from the sealed audit chain in position order, so each is sent only after its change committed; they are signed with every live webhook secret, keep one `webhook-id` across retries, move the cursor only after a 2xx answer, retry with backoff from 1 second to 1 hour, skip an event after 72 hours of failures, and never send events from before webhooks were turned on | `server: TestWebhooksAreSignedRetriedAndSentAfterCommit`, `server: TestAWebhookIsSkippedAfter72Hours` |
| 212 | The admin API under `/admin/` answers only administrators in `auth_server_admins` who meet `AssuranceMulti`, whichever admin path they call; revoking the grant takes effect on the next request; and outside `admin.allowed_networks` every admin path answers 404 | `server: TestTheAdminAPIIsForAdministratorsOnly`, `server: TestEveryServerRouteMeetsItsRule` |
| 213 | An admin invitation from `admin invite` is a 256-bit code stored only as its SHA-256, works once, only within 15 minutes, and only for a human who proved a second factor in the last 15 minutes; a refused, second, expired, or guessed use grants nothing | `server: TestAnAdminInviteWorksOnceWithin15Minutes`, `server: TestAdminCommands` |
| 214 | The OAuth provider mounts only with `oauth.enabled`, signs with the server's sealed OpenID Connect key, and publishes only public keys; the server refuses an `http://` issuer outside localhost, a resource that isn't an absolute `https` URI, an unknown grant, a client secret given as anything but a SHA-256, an unknown key in a client table, and clients or resources while the provider is off | `server: TestTheOAuthProviderMountsFromTheConfiguration`, `server: TestOAuthConfigurationRefusals` |
| 215 | Every document the server merges describes problems as `authhttp` writes them: `Problem`, `Challenge`, `ChallengeApproval`, and `Purpose` have exactly the library's fields, with each field that is always sent required; every response that answers a `Problem` declares `application/problem+json`; and no two operations in the merged document share an `operationId` | `server: TestProblemSchemasMatchTheLibrary`, `server: TestMergedOperationIDsAreUnique`, `sdk: test/contract.ts` |
| 216 | An import from Auth0, Clerk, or Supabase reads only the files the operator names and never connects to the product; a column or field that the reader doesn't know stops it with `ErrUnknownField`, storing nothing; a user ID that appears twice, a row that doesn't parse, and a bcrypt hash while `AcceptBcrypt` is off or with a cost outside 10 to 14 refuse the whole file | `authexport: TestSourcesStopAtUnknownFields`, `authexport: TestSourcesRefuseMalformedFiles`, `authexport: TestSourcesRefuseBcryptWhenItIsOff` |
| 217 | An import from another product never matches by address: two source users with one normalized address, or one Google or GitHub identity, are both skipped and reported; a blocked, banned, or deleted user is skipped and reported; without `Merge` a target with sign-in records is refused, and with it a user whose address exists is skipped, so the address keeps signing in to the user who held it | `authexport: TestAuth0FixtureUsersSignIn`, `authexport: TestSupabaseFixtureUsersSignIn`, `authexport: TestSourcesNeverMatchByAddress` |
| 218 | Each source's fixture users sign in with their passwords through `password.SignIn` as the source's user ID, or as a minted `usr_` ID with 192 random bits whose mapping is written first, to a new mode 0600 file that is never overwritten; the bcrypt hash is then replaced with Argon2id; a dry run stores nothing, records nothing, and writes no mapping | `authexport: TestClerkFixtureUsersSignIn`, `authexport: TestSourceMintIDsWritesTheMapping`, `authexport: TestSourceDryRunStoresNothing`, `server: TestImportFromOtherProducts`, `server: TestImportFromAuth0DryRunAndMintIDs`, `server: TestSourceImportRefusals` |
| 219 | The SDK cache serves nothing until `/v1/events/stream` sends `ready` and nothing while the stream is down, failing, or silent for 45 seconds; it clears everything on each `invalidate` and on reconnect, drops an answer fetched across an invalidation, holds only allowed answers that set no cookie, for at most 30 seconds and never past the session's expiry, keyed by the SHA-256 of the credential, and never holds a DPoP request, an approval, or a need with freshness or assurance; a revocation reaches a connected SDK within 100 milliseconds; it is off by default | `sdk: cache.test.ts "a dropped stream turns the cache off until the next ready"`, `sdk: cache.test.ts "DPoP requests, approvals, and freshness or assurance needs skip the cache"`, `sdk: cache.test.ts "the cache holds an answer at most 30 seconds, and never past the session"`, `sdk: cache.test.ts "a stream that stays silent counts as dropped"`, `sdk: e2e/contract.test.ts "the cache serves allowed answers while the event stream is up, and a revocation reaches it within 100 ms"` |
| 220 | In Next.js, a request the SDK rebuilds from headers in a Server Component or Server Action is checked as a `POST` unless `gate` attested its method with the process's random token, which `gate` overwrites on every request; a request with `next-action` is always a `POST`; the rebuilt request keeps `Origin` and `Sec-Fetch-Site`, so a cross-site Server Action with a valid session cookie is refused | `sdk: rebuild.test.ts "a forged attestation is ignored"`, `sdk: rebuild.test.ts "a cross-site Server Action with a valid session cookie is refused"`, `sdk: examples/next "a Server Action works same-site and is refused cross-site, even with a valid cookie"` |
| 221 | The SDK adapters read a client address from a forwarded header only when `trustProxy` names that header, and, where the socket address is known, only when it is in `trustedProxies`; they never fall back from one header to the other, stop the `X-Forwarded-For` walk at an entry that isn't an address or a proxy outside `trustedProxies`, and `requestInfo` never reads forwarded headers | `sdk: clientip.test.ts "the header named is the only one read"`, `sdk: clientip.test.ts "forwarded headers are read only when the socket address is in trustedProxies"`, `sdk: clientip.test.ts "requestInfo never reads forwarded headers"` |
| 222 | A refusal from `/v1/check` is data, never an exception; an outage, a timeout, a bad or throttled app key, or an answer over 1 MiB throws a `TensileError`, which every adapter answers with 503, never 401; `check` never retries, and a route the server doesn't serve is `no_v1`, not a refusal of the person | `sdk: core.test.ts "a refusal is data, never an exception"`, `sdk: core.test.ts "check never retries"`, `sdk: adapters.ts "<adapter>: an outage is a 503, never a 401"`, `sdk: body.test.ts "check treats an answer over the limit as an outage and cancels it"`, `sdk: core.test.ts "a call for a person on a server without the route is no_v1, not a refusal"` |
| 223 | The SDK proxy forwards only `/auth/` and the route groups the app turns on, only the library's cookies in either direction and an allowlist of headers; it sets `Tensile-App-Key` and `Tensile-Client-IP` itself, so a client can't, never returns the app key, returns redirects instead of following them, never forwards `/v1/`, and caps request bodies at 1 MiB | `sdk: proxy.test.ts "the proxy forwards only allowlisted paths"`, `sdk: proxy.test.ts "the proxy adds the app key and client address, and a client cannot set them"`, `sdk: proxy.test.ts "the app key never appears in a response"`, `sdk: proxy.test.ts "the proxy caps request bodies at 1 MiB"`, `sdk: e2e/contract.test.ts "the proxy forwards the browser routes and nothing else"` |
| 224 | `answerHook` signs a hook's answer for that hook's own `webhook-id` with every live secret, so the server reads it, and the server fails closed on an unsigned answer or one signed for another `webhook-id` | `sdk: core.test.ts "answerHook signs the answer for the hook's own webhook-id, with every secret"`, `sdk: e2e/contract.test.ts "hooks: the server reads answers signed for their webhook-id, and refuses others"` |
| 225 | The SDK refuses an `http://` server URL unless the host is loopback, a private address, or a single-label name, and an agent's approval through the SDK redeems once and only for the action it was asked for, against the real server | `sdk: core.test.ts "http:// is refused for public hosts"`, `sdk: e2e/contract.test.ts "an agent asks for an approval, the person approves it with a passkey, and the agent redeems it once"` |
| 226 | A webhook whose event has failed for 15 minutes or more raises a `high` `webhook_late` alert in the admin API, read from the cursor's state, until a delivery succeeds; an event skipped after 72 hours is recorded as `server.webhook_skipped` and raises `webhook_skipped`; an alert source that fails, or returns an alert without a valid kind, severity, message, and start, fails the alerts request with 503 instead of hiding the alert | `server: TestALateWebhookRaisesAnAdminAlert`, `server: TestAWebhookIsSkippedAfter72Hours`, `authadmin: TestAlertSourceAddsAlerts` |
| 227 | The server keys per-client rate limits and the audit log by `Tensile-Client-IP` only on a request that also carries a live app key, checked before the header is trusted, and only when the request holds one such header whose value is a single IP address with no zone; otherwise it ignores the header and uses `X-Forwarded-For` through `trusted_proxies` or the peer. `/v1/check` keys by `request.client_ip` under the same parsing and falls back to the app's own address. IPv6 keys are /64 prefixes | `server: TestTrustedClientIPKeysTheRateLimits`, `server: TestClientIPWithoutALiveAppKeyIsIgnored`, `server: TestClientIPInTheAuditLog`, `server: TestCheckKeysTheClientByRequestClientIP`, `authhttp: TestClientKeyAndClientIPMatchWithClientIP` |
| 228 | With several replicas on one Postgres, each webhook event is delivered once in normal operation, by one replica at a time; a replica that stops mid-delivery leaves the event to another, which delivers it, at least once; and a replica whose cursor connection drops mid-batch sends nothing more of that batch | `server: TestReplicasDeliverEachWebhookOnce`, `server: TestAWebhookSurvivesAReplicaStoppingMidDelivery`, `server: TestAReplicaThatLosesTheCursorStopsDelivering` |
| 229 | A revocation on one replica reaches `/v1/events/stream` subscribers on every other replica within 100 ms, through `pgstore.Watch`; a replica whose watcher can't listen ends its streams and answers new ones with 503 `unavailable` until the watcher listens again | `server: TestARevocationOnOneReplicaReachesStreamsOnAnother` |
| 230 | A session cached on one replica is refused within 100 ms after another replica revokes it, and a replica's cache stays bypassed, and the replica not ready, until its watcher first listens | `server: TestARevocationOnOneReplicaReachesAnotherReplicasCache`, `server: TestACacheIsBypassedUntilItsWatcherListens` |
| 231 | `authhttp.WithApprovalWait` caps both how long `Approvable` holds a retry and the wait the refusal offers, so the offer is one the application keeps: `wait_hint` and the fix offer the smallest of the cap, 60 seconds, and the seconds until the approval expires; with a cap of 0 the refusal has no `wait_hint` and tells the agent to retry after `Retry-After`, a retry that asks to wait answers `approval_pending` at once, and the pending fix offers no wait; without the option the cap is 60 seconds | `authhttp: TestApprovalWaitCapsTheWaitAndTheHint`, `authhttp: TestApprovableAsksOnceAndLinksToTheConfiguredOrigin` |
| 232 | `/v1/check` holds a retry only for an authenticated agent that meets the agent part of the need and redeems its own pending approval, and only when the call sends `Prefer: wait=N`; it waits at most N and 60 seconds, ends at the decision, at expiry, when the app disconnects (releasing the slot and writing nothing), and when shutdown starts (answering `approval_pending` with `Retry-After` before `shutdown_timeout`); it authenticates the token again before it spends the approval, so a token revoked during the wait gets `unauthenticated` and the approval stays unspent; one app key holds at most 256 waits on a replica, besides the library's 4 per agent and 1,024 per replica, and a wait over any limit answers `approval_pending` at once, never 429; the call's `Prefer` caps the wait the refusal offers, and without it the refusal offers none; a decision on another replica wakes the wait within 2 seconds | `server: TestCheckWaitsForTheDecision`, `server: TestCheckWaitEndsAtExpiry`, `server: TestCheckWaitRunsOutAsPending`, `server: TestCheckWaitRefusesARevokedToken`, `server: TestCheckWaitsAreBounded`, `server: TestCheckWaitEndsWhenTheAppDisconnects`, `server: TestCheckOffersOnlyTheAppsWait`, `server: TestShutdownEndsCheckWaits`, `server: TestADecisionOnOneReplicaWakesAWaitOnAnother` |
| 233 | Through the SDK, an approvable route waits for the person only as long as the app keeps a request: `approvalWait` defaults to 50 seconds on a long-running server and to 0 on a detected serverless platform, takes 0 to 60, and a route's `wait` replaces it; the creating check sends `Prefer: wait=<cap>` and a retry the smaller of the cap and the agent's own `Prefer`, or none when the agent sent none, never a `wait` in the body; a waiting check's timeout is its wait plus `timeoutMs`, so a wait that runs out is `approval_pending`, never an outage; the check ends when the agent disconnects in Express, Hono, and Next.js, and an aborted check rejects with the signal's reason instead of reporting an outage; against the real server, a tap during the wait runs the route once as the agent, a revocation during the wait gets 401 and leaves the approval unspent, a denial ends the wait within 2 seconds, and a check without `Prefer` gets an immediate answer and no wait hint | `sdk: core.test.ts "approvalWait defaults to 50 on a long-running server and 0 on serverless, and takes 0 to 60 seconds"`, `sdk: core.test.ts "a waiting redeem sends Prefer and gets its wait on top of timeoutMs; the body never carries wait"`, `sdk: core.test.ts "an aborted check rejects with the signal's reason, never an outage"`, `sdk: adapters.ts "an approvable route offers approvalWait, and waits for the smaller of it and the agent's Prefer"`, `sdk: express.test.ts and hono.test.ts "an agent that disconnects aborts the waiting check"`, `sdk: e2e/contract.test.ts "wait: …"` (7 tests) |
| 234 | A cache implements each optional store interface (`FactorStore`, `DeviceStore`, `TransferStore`, `EmailStore`, `IdentityStore`, `SignupStore`, and `SignupSettingsStore`) exactly when the store it wraps does, so a service behind the cache keeps approvals, step-up, pending sign-ins, device binding, the password cap, and pruning, and never sees an interface the wrapped store lacks; methods that revoke or delete sessions through those interfaces clear the cache | `storetest: RunWrapper` over memstore (`cachestore: TestOptionalInterfacesMatchTheWrappedStore`), SQLite, and Postgres (`TestCacheKeepsOptionalInterfaces`), `cachestore: TestEveryCombinationHasExactlyItsInterfaces`, `cachestore: TestOptionalConformance`, `server: TestCheckRedeemsAnApprovalThroughTheCache`, `server: TestADecisionOnOneReplicaWakesAWaitOnAnother`, `passkey: TestStepUpThroughTheCache` |
| 235 | A signed-out request for the approval page, or a page listed in `authhttp.WithSignInPage`, is redirected to sign-in only when it is a GET or HEAD whose `Accept` ranks `text/html` above JSON; a fetch, an API client, a POST, an unlisted page, and an app without the option get the 401 problem; a signed-in person sees the page | `authhttp: TestABrowserOpeningTheApprovalPageSignedOutGoesToSignIn`, `authhttp: TestTheServiceApprovalURLMarksTheApprovalPage`, `authhttp: TestOnlyBrowserNavigationsToPagesGoToSignIn`, `authhttp: TestWithoutASignInPageTheApprovalPageAnswers401`, `authhttp: TestASignedInPersonSeesTheApprovalPage`, `examples/agents: TestASignedOutApprovalLinkGoesToSignInAndBack` |
| 236 | A return-to path is never an open redirect: `authhttp.SafeReturnTo` and the elements' `safeReturnTo` accept only a relative path on the same origin, with one leading `/` not followed by `/` or `\`, no scheme, host, or fragment, no backslash, space, or control character, no decoded path that starts with `//`, no `.` or `..` segment, plain or percent-encoded (`%2e` or `%2E`), so that resolving the path can't leave one that starts with `//`, and at most 2,048 bytes; the sign-in redirect carries only the request's own path, and `Mux.Check` refuses a sign-in page off the origin | `authhttp: TestSafeReturnToAcceptsOnlyRelativePaths`, `authhttp: TestTheSignInRedirectNeverPointsOffTheOrigin`, `authhttp: TestMuxCheckRefusesAnOffOriginSignInPage`, `client: elements.test.ts "return_to accepts only a relative path on this origin"`, `client: elements.test.ts "return_to comes from the query, and links carry it on"`, `examples/agents: TestTheSignInPageIgnoresAReturnToOffTheOrigin` |
| 237 | The Errands device page's GET changes nothing and, signed out, asks the person to sign in first with a link that returns to it; submitting a code needs a signed-in person | `examples/agents: TestTheDevicePageAsksASignedOutPersonToSignInFirst`, `examples/agents: TestPublicRoutes` |
| 238 | When the session ends, by sign-out, expiry, or a revocation in any tab, every element that shows the person's data removes it from its shadow DOM at once and shows the signed-out state; it sends no request while signed out, so a 401 never loops, and loads exactly once after the next sign-in | `client: session.test.ts "<tensile-sessions>: a lost session clears the person's data at once, without a request loop"` (and for `<tensile-activity>`, `<tensile-approvals>`, and `<tensile-approval>`), `client: session.test.ts "<tensile-approval> opened signed out asks once, then shows the request after sign-in"` |
| 239 | Every session change, whether a lost session, a sign-out, or a sign-in, bumps the element's load generation, and a load that started at an earlier generation, or finishes while signed out, drops its result; a sign-in drops the earlier data and renders the loading state before it loads, so no frame after a sign-in shows another person's data | `client: session.test.ts "a slow load that resolves after the session is lost doesn't render"`, `client: session.test.ts "signing in as a different person never shows the previous person's data"`, `client: session.test.ts "signing in straight from one person to another, with no sign-out, drops the first person's data"` |
| 240 | `GET /auth/totp/status` and `POST /auth/totp/remove` are for a human session only and act on the session's own user, whatever the request names: an agent is refused, another person reads or removes only their own app, and a remove needs a sign-in from the last 10 minutes (`totp.NeedRemove`) | `authroutes: TestTOTPStatusIsThePersonsOwnAndPeopleOnly`, `authroutes: TestOpenAPIMatchesTheRoutes` |
| 241 | The Errands activity feed names the agent, never its person, for work an agent did, over the API and over MCP, and records the person who approved an agent's payment; the agent's name is stored with the entry, so it reads the same after the agent is revoked | `examples/agents: TestTour`, `examples/agents: TestPagesShowMoneyAndActivityAsPeopleReadThem` |
| 242 | An address or an external identity's subject never appears in the audit log or a rate-limit key, and its label can't be linked to it without the audit key: address labels, federated identity labels, and per-address limiter keys are HMAC-SHA256 pseudonyms under `auth.WithAuditKey`, at least 32 bytes that don't all have the same value, with the purpose and every part length-prefixed; `password.New` refuses a service without the key, and a service without one labels every address `email` and every identity `federated:<provider>`; identities are looked up by issuer and subject, never by label | `auth: TestEmailLabelIsKeyed`, `auth: TestEmailLabelWithoutAKeyNamesNoAddress`, `auth: TestPseudonymSeparatesPurposesAndParts`, `auth: TestAuditKeyMustBeLongEnough`, `auth: TestAuditKeyMustNotBeConstant`, `password: TestNewNeedsAnAuditKey`, `federation: TestFederatedLabelIsKeyed`, `federation: TestFederatedLabelIsTheSameInEveryEvent`, `federation: TestFederatedLabelWithoutAKeyNamesNoIdentity` |
| 8 | Idle and absolute expiry hold at the boundary; use never extends the maximum | `TestExpiryBoundaries` |
| 9 | Rotated-out tokens work only in the grace window; reuse revokes the tree | `TestRotateGraceAndReuseDetection` |
| 10 | Every failure looks identical to clients, in Go and over HTTP | `TestFailuresAreIndistinguishable`, `authhttp: TestEveryFailureLooksTheSame` |
| 11 | Token kind must match the session; agent tokens never from cookies | `TestTokenKindMustMatchSession`, `authhttp: TestAgentTokensAreNeverAcceptedFromCookies` |
| 12 | Cross-origin cookie requests are rejected; bearer requests are not | `authhttp: TestCrossOriginCookieRequestsAreRejected` |
| 13 | Cookies are `__Host-`, Secure, HttpOnly, SameSite=Lax | `authhttp: TestCookieAttributes` |
| 14 | Concurrent rotation has exactly one winner | `TestConcurrentRotateHasOneWinner`, `storetest: ConcurrentSwapHasOneWinner` |
| 15 | Generated tokens are unique, valid and match the scanner pattern | `token: TestGeneratedTokensMatchScannerPatternAndAreUnique` |
| 16 | A store outage is a server error, not a logout | `TestStoreFailureIsNotUnauthenticated`, `authhttp: TestStoreOutageIs503Not401` |

Fuzz targets. On a pull request, CI runs for 30 seconds each the targets that the change can affect (`just fuzz-changed`); every target runs for 2 minutes each week and for 5 minutes on every version tag (`.github/workflows/fuzz.yml`): `FuzzSessionOps` (a model-based fuzzer that checks every token against a reference model after each random operation), `FuzzAuthenticate`, and `FuzzNormalizeScopes` in the root package; `token: FuzzParse`; `seal: FuzzOpen`; `authhttp: FuzzExtract`; `passkey: FuzzFinishLogin` and `passkey: FuzzFinishRegistration`; `recovery: FuzzRedeem`; `totp: FuzzVerify`; `leakscan: FuzzParseAlerts`; `authadmin: FuzzCursor`; `dpop: FuzzVerify` (DPoP proof parsing); `oauth: FuzzParseClientMetadata` (client ID metadata documents); `mcpauth: FuzzParseCalls` and `mcpauth: FuzzNoDuplicateKeys` (JSON-RPC bodies); `password: FuzzParsePHC`, `password: FuzzParseStored`, `password: FuzzPolicy`, and `password: FuzzNormalizeEmail`; `authexport: FuzzParse` (decrypted export files); and `emailcode: FuzzRedeem` and `emailcode: FuzzParseTyped` (email-code parsing).

Invariant numbers follow the order in which invariants were added, not the table order; 25 and 29 each name two rows.
