redisstore

package
v0.77.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 5, 2026 License: Apache-2.0 Imports: 26 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type MigrationResult

type MigrationResult struct {
	TokensMigrated     int
	TokensSkipped      int
	TokensFailed       int
	IdentitiesMigrated int
	IdentitiesSkipped  int
	IdentitiesFailed   int
}

MigrationResult holds counts of items migrated during bulk migration.

type RedisStorage

type RedisStorage struct {
	// contains filtered or unexported fields
}

RedisStorage implements the Storage interface backed by Redis. Supports standalone mode (single endpoint), Sentinel failover mode, and Cluster mode. It provides distributed storage for OAuth2 tokens, authorization codes, user data, and pending authorizations, enabling horizontal scaling.

func NewRedisStorage

func NewRedisStorage(
	ctx context.Context, cfg redisconn.Config, keyPrefix string, opts ...RedisStorageOption,
) (*RedisStorage, error)

NewRedisStorage creates Redis-backed storage. Connection-mode topology, timeouts, TLS, and credentials are configured through cfg; keyPrefix is the per-tenant key prefix (a single Redis Cluster hash tag combining namespace and name — see DeriveKeyPrefix, e.g. "thv:auth:{ns:name}:") and must be non-empty.

Connection-mode validation, timeout defaults, client construction (standalone, cluster, or sentinel), TLS plumbing, and connectivity verification are delegated to the shared toolhive-core redisconn package. cfg.Password may be empty when the Redis server does not require authentication (the auth server does not mandate ACL auth); the keyPrefix is storage-specific and required.

func NewRedisStorageWithClient

func NewRedisStorageWithClient(
	client redis.UniversalClient, keyPrefix string, opts ...RedisStorageOption,
) *RedisStorage

NewRedisStorageWithClient creates a RedisStorage with a pre-configured client. This is useful for testing with miniredis.

func (*RedisStorage) BackfillDCRClientIndex

func (s *RedisStorage) BackfillDCRClientIndex(ctx context.Context) error

BackfillDCRClientIndex adds every live client row counted against the DCR cap to the KeyTypeDCRClientIdx sorted set, scored by the row's current expiry. Rows written before the index existed have no entry, so without this a deployment already holding more than the cap would keep admitting registrations past it.

It is idempotent and runs on every startup, in the style of MigrateLegacyUpstreamData: ZADD NX never moves an existing entry, so a row indexed by RegisterClient or RenewClientTTL keeps its exact score. Running it again also picks up rows an older replica wrote during a rolling upgrade. A row without a TTL is not DCR-issued and is skipped.

Reads are batched per SCAN page. A row that cannot be parsed is skipped and counted in one WARN line rather than failing startup: it would equally fail GetClient, and one bad row must not keep every replica down. Only Redis errors (SCAN, reads, writes) are returned.

On success it logs one INFO line with the rows scanned, the entries added and the duration, and one WARN line when the live count is already at or above the cap, so an operator sees why /oauth/register answers 503 from the first request.

TODO(migration): Remove once all deployments have upgraded past this version.

func (*RedisStorage) ClientAssertionJWTValid

func (s *RedisStorage) ClientAssertionJWTValid(ctx context.Context, jti string) error

ClientAssertionJWTValid atomically reserves jti for a short window via Redis SET NX, returning fosite.ErrJTIKnown if it is already reserved or was previously consumed and not yet expired. This is the only atomic checkpoint in fosite's two-call client-assertion replay protocol (Valid, then SetClientAssertionJWT with the real expiry once the rest of the assertion has been validated) — an Exists-then-Set pair (the prior implementation) lets two concurrent requests presenting the same assertion both observe jti as unused before either records it. jti length is bounded here too, before it's ever sent to Redis, since fosite hands it to us before parsing exp.

func (*RedisStorage) Close

func (s *RedisStorage) Close() error

Close closes the Redis client connection.

func (*RedisStorage) CompareAndSwapProviderIdentity

func (s *RedisStorage) CompareAndSwapProviderIdentity(
	ctx context.Context, expected, replacement *storage.ProviderIdentity,
) error

CompareAndSwapProviderIdentity atomically updates a provider identity row iff its stored (UserID, Issuer, SubjectClaim) matches expected.

func (*RedisStorage) CompareAndSwapUpstreamTokens

func (s *RedisStorage) CompareAndSwapUpstreamTokens(
	ctx context.Context, sessionID, providerName, expectedRefreshToken string, tokens *storage.UpstreamTokens,
) error

CompareAndSwapUpstreamTokens stores tokens for (sessionID, providerName) only if the refresh token currently stored there equals expectedRefreshToken; see the interface doc (UpstreamTokenStorage.CompareAndSwapUpstreamTokens) for the coordination contract. Uses casUpstreamTokensScript so the comparison and the write (and its index maintenance) happen as one atomic Redis operation.

func (*RedisStorage) ConsumeAssertionJWT

func (s *RedisStorage) ConsumeAssertionJWT(ctx context.Context, purpose, issuer, jti string, exp time.Time) error

ConsumeAssertionJWT atomically records an assertion JWT as consumed until its expiry. Reusing an unexpired (purpose, issuer, jti) tuple returns fosite.ErrJTIKnown. Redis errors are returned so callers fail closed rather than accepting an assertion whose replay status is unknown.

func (*RedisStorage) CountDCRClients

func (s *RedisStorage) CountDCRClients(ctx context.Context) (int64, error)

CountDCRClients implements DCRClientCounter: the number of index entries whose expiry has not passed. It only reads, so a metric collection never writes.

func (*RedisStorage) CreateAccessTokenSession

func (s *RedisStorage) CreateAccessTokenSession(ctx context.Context, signature string, request fosite.Requester) error

CreateAccessTokenSession stores the access token session.

func (*RedisStorage) CreateAuthorizeCodeSession

func (s *RedisStorage) CreateAuthorizeCodeSession(ctx context.Context, code string, request fosite.Requester) error

CreateAuthorizeCodeSession stores the authorization request for a given authorization code.

func (*RedisStorage) CreateExchangeGrant

func (s *RedisStorage) CreateExchangeGrant(ctx context.Context, g *storage.ExchangeGrant) error

CreateExchangeGrant stores g and, for a top-level grant, its replay marker in one script. See ExchangeGrantStorage for the contract. TTLs and the marker liveness cutoff come from the store clock, never the wall clock. A grant whose ExpiresAt is already past by the store clock is refused before the script runs.

The marker window follows Redis's own TTL: the script checks EXISTS, and Go only skips the marker once its window has already passed. The margin absorbs clock skew and the time between s.now() and script execution, which can only lengthen the window (the safe direction).

Redis treats any existing record hash as a duplicate signature, whereas the memory backend ignores a record past its ExpiresAt. The difference is only reachable within about 1 ms plus network latency of expiry, or under clock skew, and either outcome is safe. A hash with no data field is ErrAlreadyExists here but ErrNotFound on Get.

An error return does not prove nothing was written. The script is atomic on the server, but if the connection fails after Redis ran it, the caller sees an error while the record and its marker exist. The marker makes a second create for the same jti fail, so a retry is safe but will not succeed.

The marker is only as durable as the Redis deployment. Redis replicates asynchronously, so a failover to a replica that had not yet received the write loses the marker, and the same subject token could be exchanged again until SourceExpiresAt + ExchangeGrantMarkerMargin. WAIT and AOF narrow this window but do not close it. Operators who need to bound it set min-replicas-to-write and min-replicas-max-lag, or use a store that acknowledges writes only once they are durable.

func (*RedisStorage) CreatePKCERequestSession

func (s *RedisStorage) CreatePKCERequestSession(ctx context.Context, signature string, request fosite.Requester) error

CreatePKCERequestSession stores the PKCE request session.

func (*RedisStorage) CreateProviderIdentity

func (s *RedisStorage) CreateProviderIdentity(ctx context.Context, identity *storage.ProviderIdentity) error

CreateProviderIdentity links a provider identity to a user.

func (*RedisStorage) CreateRefreshTokenSession

func (s *RedisStorage) CreateRefreshTokenSession(
	ctx context.Context, signature string, _ string, request fosite.Requester,
) error

CreateRefreshTokenSession stores the refresh token session.

func (*RedisStorage) CreateUser

func (s *RedisStorage) CreateUser(ctx context.Context, user *storage.User) error

CreateUser creates a new user account.

func (*RedisStorage) DeleteAccessTokenSession

func (s *RedisStorage) DeleteAccessTokenSession(ctx context.Context, signature string) error

DeleteAccessTokenSession removes the access token session.

func (*RedisStorage) DeleteConsentSession

func (s *RedisStorage) DeleteConsentSession(ctx context.Context, digest string) error

DeleteConsentSession revokes the originating browser session.

func (*RedisStorage) DeleteDeviceRequest

func (s *RedisStorage) DeleteDeviceRequest(ctx context.Context, deviceCode string) error

DeleteDeviceRequest removes a device request, e.g. once its token has been issued so the device_code cannot be redeemed twice. Both the canonical record and the user_code secondary index are deleted in one pipeline.

The get-then-delete sequence runs inside a Redis WATCH/MULTI transaction, mirroring UpsertDCRIssuedClient: if another caller deletes (or otherwise modifies) the key between our GET and EXEC, EXEC aborts with redis.TxFailedErr. Retrying then re-runs the GET, which now observes redis.Nil and reports ErrNotFound to the loser -- so a second concurrent or replayed DeleteDeviceRequest for the same device_code can never also observe success, which is what made this method single-use. See maxConfiguredClientReconcileRetries for why the retry count is bounded.

func (*RedisStorage) DeletePKCERequestSession

func (s *RedisStorage) DeletePKCERequestSession(ctx context.Context, signature string) error

DeletePKCERequestSession removes the PKCE request session.

func (*RedisStorage) DeletePendingAuthorization

func (s *RedisStorage) DeletePendingAuthorization(ctx context.Context, state string) error

DeletePendingAuthorization removes a pending authorization.

func (*RedisStorage) DeletePendingDeviceConfirmation

func (s *RedisStorage) DeletePendingDeviceConfirmation(ctx context.Context, token string) error

DeletePendingDeviceConfirmation removes a pending device confirmation.

func (*RedisStorage) DeletePendingDeviceLogin

func (s *RedisStorage) DeletePendingDeviceLogin(ctx context.Context, state string) error

DeletePendingDeviceLogin removes a pending device login.

func (*RedisStorage) DeleteRefreshTokenSession

func (s *RedisStorage) DeleteRefreshTokenSession(ctx context.Context, signature string) error

DeleteRefreshTokenSession removes the refresh token session. Deleting the signature of a rotated token is how fosite revokes the grant after reuse: it returns nil and keeps the tombstone, so every later replay revokes again.

func (*RedisStorage) DeleteUpstreamTokens

func (s *RedisStorage) DeleteUpstreamTokens(ctx context.Context, sessionID string) error

DeleteUpstreamTokens removes all upstream IDP tokens for a session (all providers). Uses the session index set to find all provider keys and deletes them atomically.

func (*RedisStorage) DeleteUpstreamTokensForProvider

func (s *RedisStorage) DeleteUpstreamTokensForProvider(ctx context.Context, sessionID, providerName string) error

DeleteUpstreamTokensForProvider removes tokens for a single (sessionID, providerName), leaving sibling providers' rows intact. Absent row returns nil.

The row and its index members are removed by one Lua script, and any Redis error is returned. A session index key or user set holding a non-set value fails the call with WRONGTYPE before anything is changed: the row, the session index and the user set are all left untouched. The session index key itself is not deleted; Redis drops a set when its last member is removed.

func (*RedisStorage) DeleteUser

func (s *RedisStorage) DeleteUser(ctx context.Context, id string) error

DeleteUser removes a user account and all associated data.

func (*RedisStorage) GetAccessTokenSession

func (s *RedisStorage) GetAccessTokenSession(ctx context.Context, signature string, _ fosite.Session) (fosite.Requester, error)

GetAccessTokenSession retrieves the access token session by its signature.

func (*RedisStorage) GetAllUpstreamTokens

func (s *RedisStorage) GetAllUpstreamTokens(ctx context.Context, sessionID string) (map[string]*storage.UpstreamTokens, error)

GetAllUpstreamTokens retrieves all upstream IDP tokens for a session across all providers. Uses SMEMBERS on the session index set to find all provider keys, then MGET to fetch them. Returns a map of providerName -> tokens. Returns an empty map for unknown sessions.

func (*RedisStorage) GetAuthorizeCodeSession

func (s *RedisStorage) GetAuthorizeCodeSession(ctx context.Context, code string, _ fosite.Session) (fosite.Requester, error)

GetAuthorizeCodeSession retrieves the authorization request for a given code. Matches memory.go's pattern: get the auth code data first, then check if invalidated. InvalidateAuthorizeCodeSession extends the auth code TTL to match the invalidation marker, so the data is always available when the marker exists.

func (*RedisStorage) GetClient

func (s *RedisStorage) GetClient(ctx context.Context, id string) (fosite.Client, error)

GetClient loads the client by its ID.

The value and the key's TTL are fetched together in one pipelined round trip: clientFromStored needs the TTL to disambiguate the legacy public client shape (see DCRIssued and clientFromStored for why), and issuing GET then TTL as two separate round trips would leave a window where a concurrent RenewClientTTL or expiry changes the answer between them.

func (*RedisStorage) GetClientApproval

func (s *RedisStorage) GetClientApproval(ctx context.Context, userID, clientID string) (*storage.ClientApproval, error)

GetClientApproval returns a copy only until its stored absolute expiry.

func (*RedisStorage) GetConsentSession

func (s *RedisStorage) GetConsentSession(ctx context.Context, digest string) (*storage.ConsentSession, error)

GetConsentSession returns a session only until its stored absolute expiry.

func (*RedisStorage) GetDCRCredentials

func (s *RedisStorage) GetDCRCredentials(ctx context.Context, key dcrkey.Key) (*storage.DCRCredentials, error)

GetDCRCredentials retrieves the credentials previously persisted under key. Returns ErrNotFound (wrapped) when no entry exists. The returned value is a fresh struct decoded from JSON, which acts as a defensive copy.

An unpopulated key (empty Issuer, UpstreamID, RedirectURI, or ScopesHash) cannot match any stored row because StoreDCRCredentialsIfAbsent rejects such keys, so a Get against one is a normal miss — ErrNotFound — matching MemoryStorage.GetDCRCredentials and the DCRCredentialStore interface contract.

func (*RedisStorage) GetExchangeGrant

func (s *RedisStorage) GetExchangeGrant(ctx context.Context, signature string) (*storage.ExchangeGrant, error)

GetExchangeGrant returns the grant, including revoked grants. A record past ExpiresAt is not found even if Redis has not evicted it, so the store clock decides, not the key TTL.

func (*RedisStorage) GetLatestUpstreamTokensForUser

func (s *RedisStorage) GetLatestUpstreamTokensForUser(
	ctx context.Context,
	userID string,
	providerID string,
) (*storage.UpstreamTokens, error)

GetLatestUpstreamTokensForUser returns the upstream token row for (userID, providerID) with the highest ExpiresAt across all sessions.

Expired tokens (past ExpiresAt) are returned so callers can use the refresh token; filtering by access-token expiry is the caller's responsibility. See the interface declaration in types.go for the full contract.

func (*RedisStorage) GetPKCERequestSession

func (s *RedisStorage) GetPKCERequestSession(ctx context.Context, signature string, _ fosite.Session) (fosite.Requester, error)

GetPKCERequestSession retrieves the PKCE request session by its signature.

func (*RedisStorage) GetProviderIdentity

func (s *RedisStorage) GetProviderIdentity(
	ctx context.Context,
	providerID string,
	providerSubject string,
) (*storage.ProviderIdentity, error)

GetProviderIdentity retrieves a provider identity by provider ID and subject.

func (*RedisStorage) GetRefreshTokenSession

func (s *RedisStorage) GetRefreshTokenSession(ctx context.Context, signature string, _ fosite.Session) (fosite.Requester, error)

GetRefreshTokenSession retrieves the refresh token session by its signature.

A live token whose grant is marked revoked is reported as inactive. A rotated token is answered in one of two ways. Less than RecentRotationWindow after the rotation time stored in its tombstone it is reported as not found, which includes a rotation time ahead of this replica's clock. After that it is reported as reuse: a requester carrying only the request ID is returned together with fosite.ErrInactiveToken, so fosite revokes the grant. Both keys are read in one MGET so a concurrent rotation cannot make the token look absent.

func (*RedisStorage) GetUpstreamTokens

func (s *RedisStorage) GetUpstreamTokens(ctx context.Context, sessionID, providerName string) (*storage.UpstreamTokens, error)

GetUpstreamTokens retrieves the upstream IDP tokens for a session and provider. Returns a new UpstreamTokens struct deserialized from Redis, which acts as a defensive copy - callers cannot modify the stored data by mutating the return value.

func (*RedisStorage) GetUser

func (s *RedisStorage) GetUser(ctx context.Context, id string) (*storage.User, error)

GetUser retrieves a user by their internal ID.

func (*RedisStorage) GetUserProviderIdentities

func (s *RedisStorage) GetUserProviderIdentities(ctx context.Context, userID string) ([]*storage.ProviderIdentity, error)

GetUserProviderIdentities returns all provider identities linked to a user.

func (*RedisStorage) Health

func (s *RedisStorage) Health(ctx context.Context) error

Health checks Redis connectivity.

func (*RedisStorage) InvalidateAuthorizeCodeSession

func (s *RedisStorage) InvalidateAuthorizeCodeSession(ctx context.Context, code string) error

InvalidateAuthorizeCodeSession marks an authorization code as used/invalid. It extends the auth code key's TTL to match the invalidation marker, ensuring GetAuthorizeCodeSession can always return the Requester alongside ErrInvalidatedAuthorizeCode as required by fosite for token revocation.

func (*RedisStorage) LoadDeviceRequestByDeviceCode

func (s *RedisStorage) LoadDeviceRequestByDeviceCode(ctx context.Context, deviceCode string) (*storage.DeviceRequest, error)

LoadDeviceRequestByDeviceCode retrieves a device request by its device_code.

func (*RedisStorage) LoadDeviceRequestByUserCode

func (s *RedisStorage) LoadDeviceRequestByUserCode(ctx context.Context, userCode string) (*storage.DeviceRequest, error)

LoadDeviceRequestByUserCode retrieves a device request by its user_code, for the verification page.

func (*RedisStorage) LoadPendingAuthorization

func (s *RedisStorage) LoadPendingAuthorization(ctx context.Context, state string) (*storage.PendingAuthorization, error)

LoadPendingAuthorization retrieves a pending authorization by internal state.

func (*RedisStorage) LoadPendingDeviceConfirmation

func (s *RedisStorage) LoadPendingDeviceConfirmation(
	ctx context.Context, token string,
) (*storage.PendingDeviceConfirmation, error)

LoadPendingDeviceConfirmation retrieves a pending device confirmation by token.

func (*RedisStorage) LoadPendingDeviceLogin

func (s *RedisStorage) LoadPendingDeviceLogin(ctx context.Context, state string) (*storage.PendingDeviceLogin, error)

LoadPendingDeviceLogin retrieves a pending device login by state.

func (*RedisStorage) MarkDeviceRequestAuthorized

func (s *RedisStorage) MarkDeviceRequestAuthorized(
	ctx context.Context, deviceCode string, auth storage.DeviceAuthorization,
) error

MarkDeviceRequestAuthorized transitions a pending device request to authorized, attaching the resolved identity.

func (*RedisStorage) MarkDeviceRequestDenied

func (s *RedisStorage) MarkDeviceRequestDenied(ctx context.Context, deviceCode string) error

MarkDeviceRequestDenied transitions a pending device request to denied.

func (*RedisStorage) MigrateLegacyUpstreamData

func (s *RedisStorage) MigrateLegacyUpstreamData(ctx context.Context, providerName, legacyProviderID string) error

MigrateLegacyUpstreamData performs a one-shot bulk migration of legacy upstream token keys and provider identity keys to the new multi-upstream format.

Token key migration: renames "upstream:{sessionID}" keys (legacy, no provider suffix) to "upstream:{sessionID}:{providerName}" and patches ProviderID.

Provider identity migration: duplicates identities stored under legacy protocol-type IDs (e.g. "oidc", "oauth2") to the new logical provider name. Legacy identity keys are NOT deleted to allow safe rollback.

The migration is idempotent and crash-safe: each key is migrated independently, and existing new-format keys are never overwritten.

Returns an error if any keys fail to migrate, since the request path no longer has inline fallbacks for legacy data.

TODO(migration): Remove once all deployments have upgraded past this version.

func (*RedisStorage) ReconcileConfiguredClient

func (s *RedisStorage) ReconcileConfiguredClient(ctx context.Context, client fosite.Client) error

ReconcileConfiguredClient applies an operator-declared client: creates it if absent, otherwise replaces the existing record unless ConfiguredClientConflict refuses (or the record is DCR-issued), in which case it returns ErrAlreadyExists. See the ClientRegistry interface doc for the full contract.

The read-check-write sequence for an existing key runs inside a Redis WATCH/MULTI transaction so a concurrent writer (e.g. a DCR registration on another replica racing this reconciliation) cannot interleave between the conflict check and the write. Redis aborts the transaction if the watched key changed concurrently, and go-redis surfaces that as redis.TxFailedErr rather than retrying it — see maxConfiguredClientReconcileRetries for why this method retries that error itself, up to a bounded count. A configured client is stored with ttl=0 (operator-declared clients never expire), clearing any TTL the row might have inherited.

func (*RedisStorage) RegisterClient

func (s *RedisStorage) RegisterClient(ctx context.Context, client fosite.Client) error

RegisterClient creates a client in storage. Always create-only via SetNX: it atomically returns ErrAlreadyExists when a client with the same ID is already registered, regardless of the new client's origin. /oauth/register is unauthenticated, so this must never clobber an existing client; operator-declared clients reconcile through ReconcileConfiguredClient instead.

func (*RedisStorage) RenewClientTTL

func (s *RedisStorage) RenewClientTTL(ctx context.Context, client fosite.Client) error

RenewClientTTL extends a DCR-issued client's registration TTL to DefaultDCRClientTTL. This also raises a newly registered client off DefaultUnusedDCRClientTTL on its first token exchange, and moves its DCR cap index score to match.

Call this on a proven-use signal — a successful token exchange/refresh — not on a client read. GetClient is reached from the unauthenticated front-channel /oauth/authorize handler before any authentication, and DCR-issued public clients have no secret, so renewing there would let any caller who knows a public client_id keep its row alive indefinitely and defeat the anti-bloat TTL. Renewing on token issuance ties registration survival to actual use.

Only DCR-issued clients carry a TTL; pre-provisioned clients are stored without one and are left untouched. The gate is the registration.DCRIssued marker, not IsPublic: EXPIRE on a key with no TTL creates one, so keying on IsPublic would hand an existing permanent confidential client an expiry on its first token request after upgrade. PEXPIRE on a missing key is a no-op, so a client whose row has already expired (or a non-persisted CIMD client) is safely ignored.

func (*RedisStorage) ResolveUpstreamTokenRowID

func (s *RedisStorage) ResolveUpstreamTokenRowID(
	_ context.Context,
	sessionID string,
	providerName string,
) (storage.UpstreamTokenRowID, error)

ResolveUpstreamTokenRowID returns an opaque ID for process-local refresh coordination of a logical upstream-token row.

func (*RedisStorage) RevokeAccessToken

func (s *RedisStorage) RevokeAccessToken(ctx context.Context, requestID string) error

RevokeAccessToken marks an access token as revoked by request ID.

func (*RedisStorage) RevokeExchangeGrant

func (s *RedisStorage) RevokeExchangeGrant(ctx context.Context, signature string, now time.Time) error

RevokeExchangeGrant records now as the revocation time unless the grant is already revoked. It is one HSETNX-style write that leaves the key TTLs alone. Revocation is stored at millisecond precision. A missing or expired record returns ErrNotFound.

func (*RedisStorage) RevokeRefreshToken

func (s *RedisStorage) RevokeRefreshToken(ctx context.Context, requestID string) error

RevokeRefreshToken marks a refresh token as revoked by request ID.

func (*RedisStorage) RevokeRefreshTokenMaybeGracePeriod

func (s *RedisStorage) RevokeRefreshTokenMaybeGracePeriod(ctx context.Context, requestID string, _ string) error

RevokeRefreshTokenMaybeGracePeriod marks a refresh token as revoked, optionally allowing a grace period. For this implementation, we revoke immediately.

func (*RedisStorage) RotateRefreshToken

func (s *RedisStorage) RotateRefreshToken(ctx context.Context, requestID string, refreshTokenSignature string) error

RotateRefreshToken moves a refresh token to a tombstone and deletes the access tokens issued under the same request ID. Only the first rotation of a token wins: when the token's row is already gone, it returns fosite.ErrSerializationFailure and changes nothing, because the access tokens of that request ID may belong to the winner. A failure of the atomic move is returned, so no token pair is issued. The access token cleanup that follows is best-effort (see warnOnCleanupErr).

func (*RedisStorage) SetClientAssertionJWT

func (s *RedisStorage) SetClientAssertionJWT(ctx context.Context, jti string, deadline time.Time) error

SetClientAssertionJWT extends jti's replay marker to deadline, which becomes the key's TTL as given. The authorization server hands it the marker deadline (server.ClientAssertionRetainUntil of the assertion's exp), so the marker outlives the clock skew in which the assertion is still accepted. A deadline that server.ValidateClientAssertionMarkerDeadline refuses, because it is not in the future or too far ahead, is rejected with invalid_client and the key is left as ClientAssertionJWTValid reserved it. The ahead bound keeps a registered caller from setting a deadline decades out and giving Redis a key with a correspondingly enormous TTL. Unconditional overwrite, not a fresh atomic check: only the caller that already won ClientAssertionJWTValid's reservation reaches this call. The check must precede Set: go-redis sends no expiry for a non-positive duration other than -1ns, which it sends as KEEPTTL.

func (*RedisStorage) StoreClientApproval

func (s *RedisStorage) StoreClientApproval(ctx context.Context, userID, clientID string, approval *storage.ClientApproval) error

StoreClientApproval overwrites one user's approval for one client.

func (*RedisStorage) StoreConsentSession

func (s *RedisStorage) StoreConsentSession(ctx context.Context, digest string, session *storage.ConsentSession) error

StoreConsentSession stores a digest with its remaining fixed lifetime.

func (*RedisStorage) StoreDCRCredentialsIfAbsent

func (s *RedisStorage) StoreDCRCredentialsIfAbsent(
	ctx context.Context,
	creds *storage.DCRCredentials,
) (*storage.DCRCredentials, error)

StoreDCRCredentialsIfAbsent claims creds.Key for creds via a Redis WATCH/MULTI compare-and-set (the same pattern ReconcileConfiguredClient uses above), returning the authoritative durable value: creds itself on a successful claim, or the existing winner's credentials when the key already holds a live (non-expired) entry. Callers MUST use the returned value — RFC 7591 dynamic registration mints a unique client_id/client_secret on every call, so two replicas racing a cache miss for the same Key register genuinely different OAuth clients with the upstream, and only the value the durable store agrees to is a credential either replica actually holds. Defensive copy is provided implicitly by JSON serialisation — caller mutations after the call cannot reach the persisted bytes.

Expired existing rows are claimable

An existing row whose ClientSecretExpiresAt is non-zero and already in the past is treated as absent, mirroring MemoryStorage.StoreDCRCredentialsIfAbsent: it is overwritten with creds rather than handed back as if it were still the authoritative winner — but only when creds itself is fresher (creds' own ClientSecretExpiresAt is zero or still in the future). When both the existing row and the incoming creds are already expired — the startup case where many replicas independently re-resolve a dead upstream registration and each mints equally-stale credentials — the existing row is returned as-is instead. Overwriting would gain nothing there, and without this guard every concurrent claimant would keep re-observing an expired row and re-entering the write path, risking exhausting maxDCRClaimRetries under contention instead of converging the way the genuinely-absent case does. WATCH still guards the overwrite path: if another replica claims or refreshes the same key between our GET and our SET, EXEC aborts with redis.TxFailedErr and the loop below retries, so this does not reopen the double-registration race the NX-based predecessor of this method was built to close — it only changes what happens when the existing row is provably expired.

This means a caller CAN receive an already-expired credential back from this call — deliberately, per the above, rather than as an oversight. The only thing that later re-checks an expiry against ResolveCredentials' cache is lookupCachedResolution, which only runs on a *subsequent* ResolveCredentials call for the same key; nothing currently re-resolves after the one-time boot-time call in embeddedauthserver.go. So a replica that receives an expired credential here keeps it for the rest of its process lifetime, failing cleanly with an upstream invalid_client/ invalid_grant on every use until restart. Closing that gap needs revisiting credentials after boot, not another guard in this function — tracked in #6496.

TTL

When creds.ClientSecretExpiresAt is non-zero (the upstream advertised an RFC 7591 §3.2.1 client_secret_expires_at), the entry is stored with a Redis TTL derived from time.Until(ClientSecretExpiresAt) so the row evicts before the upstream rejects the secret at the token endpoint. When zero (RFC 7591 "never"), TTL=0 is used and the entry is long-lived.

If ClientSecretExpiresAt is already in the past at call time, the entry is written with the bounded TTL pastExpiryDCRTTL (1 second) rather than rejected or stored long-lived. This keeps the store's "already-expired secret" window narrow even if the resolver never re-reads the row, and matches the fail-loud-but-tolerant posture: the caller's expiry timestamp round-trips so a downstream reader can still observe it and trigger re-registration.

Validation is delegated to ValidateDCRCredentialsForStore so the rejection set stays in sync with MemoryStorage and any future backend.

func (*RedisStorage) StoreDeviceRequest

func (s *RedisStorage) StoreDeviceRequest(ctx context.Context, device *storage.DeviceRequest) error

StoreDeviceRequest stores a new pending device request, indexed by both DeviceCode and UserCode.

Both keys are created with SETNX inside a single Redis transaction, so a concurrent double-store cannot silently overwrite either index. Because MULTI/EXEC applies each queued command unconditionally (there is no short-circuit between them), the two SETNX calls can succeed and fail independently; when exactly one did, the successful key is deleted so no half-written pair is ever left behind.

func (*RedisStorage) StorePendingAuthorization

func (s *RedisStorage) StorePendingAuthorization(ctx context.Context, state string, pending *storage.PendingAuthorization) error

StorePendingAuthorization stores a pending authorization request.

func (*RedisStorage) StorePendingDeviceConfirmation

func (s *RedisStorage) StorePendingDeviceConfirmation(
	ctx context.Context, token string, pending *storage.PendingDeviceConfirmation,
) error

StorePendingDeviceConfirmation stores a pending device-flow confirmation, keyed by an opaque token. See PendingDeviceConfirmation's doc comment for why the resolved identity is addressed by token rather than round-tripped through the browser.

func (*RedisStorage) StorePendingDeviceLogin

func (s *RedisStorage) StorePendingDeviceLogin(ctx context.Context, state string, pending *storage.PendingDeviceLogin) error

StorePendingDeviceLogin stores a pending device-flow verification-page login.

func (*RedisStorage) StoreUpstreamTokens

func (s *RedisStorage) StoreUpstreamTokens(
	ctx context.Context,
	sessionID string,
	providerName string,
	tokens *storage.UpstreamTokens,
) error

StoreUpstreamTokens stores the upstream IDP tokens for a session and provider. Uses a Lua script to atomically write token data, update the session index set, and update user reverse-index sets, preventing race conditions on concurrent writes.

func (*RedisStorage) UpdateDCRCredentialsIfPresent

func (s *RedisStorage) UpdateDCRCredentialsIfPresent(
	ctx context.Context,
	creds *storage.DCRCredentials,
) (*storage.DCRCredentials, error)

UpdateDCRCredentialsIfPresent replaces the row at creds.Key with creds using a single Redis SET with the XX flag, returning ErrNotFound (wrapped) when no row physically exists at the key. It never creates: XX makes Redis itself refuse the write when the key is absent, so an update racing a concurrent delete or TTL eviction fails with ErrNotFound rather than silently re-creating the row.

The write needs no WATCH/MULTI (unlike StoreDCRCredentialsIfAbsent, which must read the existing row to decide whether it may claim the slot). Nothing here depends on the old value: only the key's bare existence gates the write, and SET XX evaluates that existence and performs the write in one atomic server-side step. There is therefore no read-check-write window to guard, no lost-update race, and no possibility of redis.TxFailedErr.

Presence is physical, not liveness

Unlike StoreDCRCredentialsIfAbsent, this does not treat an expired existing row as absent — any row whose key still exists is updatable, including one whose ClientSecretExpiresAt has passed but whose Redis key has not yet self-evicted. See the DCRCredentialStore interface docs for why Update gates on physical presence: it exists so a decorator can rewrite a row it just read via GetDCRCredentials, which itself does not filter on expiry.

TTL

The rewritten row's TTL is derived from the incoming creds by marshalDCRCredentialsForStore, identically to StoreDCRCredentialsIfAbsent: a future ClientSecretExpiresAt sets that TTL, a zero value clears it (the row becomes long-lived, since a SET without KEEPTTL discards any existing TTL), and a past value uses the bounded pastExpiryDCRTTL. An update can therefore extend, shorten, or clear the row's TTL exactly as an initial store would.

Validation is delegated to ValidateDCRCredentialsForStore so the rejection set stays in sync with MemoryStorage and any future backend.

func (*RedisStorage) UpdateDCRCredentialsIfUnchanged

func (s *RedisStorage) UpdateDCRCredentialsIfUnchanged(
	ctx context.Context, creds, expected *storage.DCRCredentials,
) (*storage.DCRCredentials, error)

UpdateDCRCredentialsIfUnchanged replaces the row at creds.Key with creds only when the stored row still equals expected, returning ErrNotFound (wrapped) when no row exists and ErrDCRCredentialsChanged when it differs.

The compare and the write run in a WATCH/MULTI transaction on the single row key — the same pattern StoreDCRCredentialsIfAbsent uses — so the operation is atomic against concurrent writers and valid in standalone, Sentinel and Cluster modes alike (one key means one hash slot). If another writer touches the key between the GET and EXEC, EXEC aborts with redis.TxFailedErr and the read-compare-write is retried, up to maxDCRClaimRetries; the retry re-reads the row and so normally resolves to ErrDCRCredentialsChanged. If every attempt aborts, a generic error is returned and nothing was written by this call.

The comparison is between decoded stored forms (expected is normalised via newStoredDCRCredentials, and storedDCRCredentials holds only strings and int64s, so == compares every field by value), not raw JSON bytes, so it is unaffected by field ordering or by a row written by an older encoder, and a value obtained from GetDCRCredentials always matches the row it was read from despite the one-second time precision of the stored form.

Presence and TTL handling are identical to UpdateDCRCredentialsIfPresent: an expired-but-present row is updatable, and the rewritten row's TTL is derived from creds by marshalDCRCredentialsForStore. The write uses SET XX for parity with that method, although WATCH already guarantees the key still exists at EXEC.

func (*RedisStorage) UpdateDeviceRequestLastPolledAt

func (s *RedisStorage) UpdateDeviceRequestLastPolledAt(ctx context.Context, deviceCode string, polledAt time.Time) error

UpdateDeviceRequestLastPolledAt records the time of the most recent poll.

func (*RedisStorage) UpdateProviderIdentityLastUsed

func (s *RedisStorage) UpdateProviderIdentityLastUsed(
	ctx context.Context, providerID, providerSubject string, lastUsedAt time.Time,
) error

UpdateProviderIdentityLastUsed updates the LastUsedAt timestamp for a provider identity. Uses a Lua script to ensure atomicity and prevent race conditions.

func (*RedisStorage) UpsertDCRIssuedClient

func (s *RedisStorage) UpsertDCRIssuedClient(ctx context.Context, client fosite.Client) error

UpsertDCRIssuedClient creates or replaces a DCR-issued client at client.GetID(). Unlike RegisterClient (create-only via SetNX), an existing row is replaced -- and its TTL refreshed to DefaultDCRClientTTL -- when the existing row is itself DCR-issued; it refuses with ErrAlreadyExists when the existing row is NOT DCR-issued, protecting a configured/SPIFFE-reconciled client from being clobbered. See the ClientRegistry interface doc for the full contract.

The read-check-write sequence for an existing key runs inside a Redis WATCH/MULTI transaction, mirroring ReconcileConfiguredClient, so a concurrent writer cannot interleave between the DCR-issued check and the write; see maxConfiguredClientReconcileRetries for why this method retries redis.TxFailedErr itself, up to the same bounded count. Unlike ReconcileConfiguredClient (ttl=0, permanent), the write here always uses DefaultDCRClientTTL: this row is TTL-bounded like any other DCR-issued client. A client counted against the DCR cap is refused, so this path can neither bypass the cap nor leave the index out of step.

type RedisStorageOption

type RedisStorageOption func(*RedisStorage)

RedisStorageOption configures a RedisStorage.

func WithRedisMaxDCRClients

func WithRedisMaxDCRClients(n int) RedisStorageOption

WithRedisMaxDCRClients sets the cap on live clients counted by CountsTowardDCRCap; zero means unlimited. At the cap RegisterClient returns a *ClientCapacityError and writes nothing. It panics on a negative n, which RunConfig.ResolvedMaxDCRClients already rejects.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL