accesstest

package
v1.0.0-dev.9 Latest Latest
Warning

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

Go to latest
Published: Nov 11, 2026 License: Apache-2.0 Imports: 37 Imported by: 0

Documentation

Overview

Package accesstest supports tests of access and its stores: MemStore is an in-memory account.Store for consumer tests, not for production, and StoreContract runs account's store contract against any store.

Index

Constants

View Source
const (
	AlgRS256 = "RS256"
	AlgES256 = "ES256"
	AlgNone  = "none"
	AlgHS256 = "HS256"
)

The ID-token signing algorithms IdPOptions.Algorithm accepts. The IdP advertises only the two it signs with keys from its JWKS; AlgNone and AlgHS256 produce tokens a correct relying party refuses.

View Source
const (
	DefaultIdPClientID     = "authtest-client"
	DefaultIdPClientSecret = "authtest-secret"
	DefaultIdPSubject      = "authtest-subject"
	DefaultIdPEmail        = "authtest@example.com"
	DefaultIdPUsername     = "authtest"
)

The defaults NewIdP fills for an empty field of IdPOptions, and the user claims every ID token carries.

Variables

This section is empty.

Functions

func StoreContract

func StoreContract(t *testing.T, newStore func(t *testing.T) account.Store, cfg ContractConfig)

StoreContract runs every contract rule of account's package doc against stores made by newStore; each call must return an empty, independent store.

Types

type ContractConfig

type ContractConfig struct {
	// NewFaulty makes stores whose medium the returned DurabilityFaults can
	// fail and count; rule 10's cases, rule 5's grouped-commit case, rule
	// 14's re-run case and rule 16's direct-write case run on them. Nil
	// skips those subtests.
	NewFaulty func(t *testing.T) (account.Store, DurabilityFaults)
	// Reopen closes old, a store newStore made and the suite wrote to, and
	// returns a store over the same medium; rule 20's fidelity case, rule
	// 14's deleted-set case and rule 17's never-reused cases for users and
	// keys run across it. Nil skips those subtests.
	Reopen func(t *testing.T, old account.Store) account.Store
}

ContractConfig configures StoreContract. Every zero value is the default: the zero ContractConfig runs every case a store with no medium hooks can run and skips the rest, each skip naming its rule.

type DurabilityFaults

type DurabilityFaults struct {
	// BeforePublish makes the next write fail before its new state is
	// published. Required.
	BeforePublish func()
	// AfterPublish makes the next write publish its new state and then fail
	// to confirm durability. Nil for a medium that reports durability with
	// its commit (bbolt).
	AfterPublish func()
	// Publishes reports how many durable publishes the medium has made.
	// Required.
	Publishes func() int
	// HoldPublish blocks the medium's next publish until release, and
	// pending reports the writes, Updates and single-call writes alike,
	// waiting for a publish. Nil for a store that groups by delay (bbolt's
	// db.Batch), which skips rule 16's direct-write case.
	HoldPublish func() (pending func() int, release func())
}

DurabilityFaults arms one medium fault for the store's next write.

type IdP

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

IdP is an OpenID Connect provider on an httptest server for one client and one user, signed in at NewIdP. /authorize approves each valid request at once, honours prompt and max_age (OpenID Connect Core 1.0 section 3.1.2.1), takes PKCE as S256 only (RFC 7636), and answers a bad client_id or redirect_uri with 400, not a redirect. Every IdP of a test binary signs with the same keys, so a token one issues verifies against another's JWKS.

func NewIdP

func NewIdP(t testing.TB, opts IdPOptions) *IdP

NewIdP starts an IdP for the test and closes it at the test's cleanup. It fails the test on an unknown IdPOptions.Algorithm, a URL outside its rule, or an EmailVerified or Groups value that does not encode as JSON.

func (*IdP) Addr

func (p *IdP) Addr() netip.AddrPort

Addr returns the address the IdP listens on.

func (*IdP) Authorizations

func (p *IdP) Authorizations() []url.Values

Authorizations returns a copy of the query of every /authorize request received so far, refused ones included, in arrival order.

func (*IdP) Client

func (p *IdP) Client() *http.Client

Client returns an HTTP client for the IdP, built from Addr and RootCAs alone: it trusts RootCAs and, under IdPOptions.URL, dials Addr for URL's host and port. A test whose own outbound client must reach the IdP builds it from the same two values.

func (*IdP) ClientID

func (p *IdP) ClientID() string

ClientID returns the one client ID the IdP accepts.

func (*IdP) ClientSecret

func (p *IdP) ClientSecret() string

ClientSecret returns ClientID's secret.

func (*IdP) Issuer

func (p *IdP) Issuer() string

Issuer returns the IdP's issuer, IdPOptions.URL when set and its listener's URL otherwise; it is the base of every default endpoint.

func (*IdP) RootCAs

func (p *IdP) RootCAs() *x509.CertPool

RootCAs returns a new pool holding only the IdP's certificate on each call, so a write to it reaches neither the IdP nor Client; it is nil when the IdP serves plain HTTP.

type IdPEndpoint

type IdPEndpoint struct {
	// Delay is waited, in wall time whatever IdPOptions.Now says, before the
	// response is written. The wait ends early when the request's context
	// ends or the IdP closes, so a hung endpoint never blocks the test's
	// cleanup.
	Delay time.Duration
	// BodyBytes, when larger than the response's JSON, pads the JSON with
	// trailing spaces to exactly this many bytes, so the body stays valid
	// JSON and only a size cap refuses it.
	BodyBytes int
	// Streamed sends the response with no Content-Length, so a client
	// learns the body's length only by reading it (chunked transfer coding,
	// RFC 9112 section 7.1).
	Streamed bool
}

IdPEndpoint shapes the responses of one IdP endpoint, for tests of a relying party's outbound-HTTP bounds.

type IdPOptions

type IdPOptions struct {
	// Now is the IdP's clock for iat, exp, auth_time and max_age; nil is
	// time.Now.
	Now func() time.Time
	// Nonce, when non-nil, is the nonce claim, an empty string included;
	// nil echoes the authorize request's nonce, and omits the claim when the
	// request carried none.
	Nonce *string
	// Subject, when non-nil, is the sub claim, an empty string included; nil
	// is DefaultIdPSubject.
	Subject *string
	// EmailVerified, when non-nil, is written as the email_verified claim
	// as given, so a string "true" tests a relying party's tolerance; nil
	// is the boolean true. NewIdP fails the test when it does not encode as
	// JSON.
	EmailVerified any
	// Groups, when non-nil, is written as the groups claim as given, a
	// string or a []string; nil omits the claim. NewIdP fails the test when
	// it does not encode as JSON.
	Groups any
	// URL, when non-empty, is the issuer in place of the listener's URL:
	// discovery's issuer, the iss claim and the authorization response's
	// iss, and, less any final "/", the base of every endpoint (OpenID
	// Connect Discovery 1.0 section 4.1). It is https with a DNS host
	// httptest's certificate covers (example.com or one label below it), an
	// optional port and path, and no query, fragment or userinfo; NewIdP
	// fails the test on any other. The IdP then serves HTTPS, reached only by
	// a client that dials IdP.Addr for URL's host and port, as IdP.Client does.
	URL string
	// AuthorizedParty, when non-empty, is the azp claim; empty omits it.
	AuthorizedParty string
	// Algorithm is the ID token's alg header, one of the Alg constants;
	// empty is AlgRS256. AlgHS256 signs with ClientSecret, AlgNone writes
	// an empty signature.
	Algorithm string
	// ClientID is the one client /authorize and /token accept, and the
	// default aud; empty is DefaultIdPClientID.
	ClientID string
	// ClientSecret authenticates ClientID at /token; empty is
	// DefaultIdPClientSecret.
	ClientSecret string
	// AuthorizationEndpoint, TokenEndpoint and JWKSURI, when non-empty, are
	// advertised by discovery as given instead of the IdP's own endpoints.
	AuthorizationEndpoint string
	TokenEndpoint         string
	JWKSURI               string
	// Audience, when non-nil, is the aud claim: one entry is written as a
	// string, any other count as an array. Nil is ClientID as a string.
	Audience []string
	// Discovery, JWKS and Token shape those endpoints' responses.
	Discovery IdPEndpoint
	JWKS      IdPEndpoint
	Token     IdPEndpoint
	// Lifetime is exp minus iat; zero is five minutes, and a negative value
	// issues a token that expired before it was issued.
	Lifetime time.Duration
	// AuthTimeOffset is added to the auth_time the IdP would write, so a
	// negative value backdates the sign-in.
	AuthTimeOffset time.Duration
	// OmitAuthTime leaves auth_time out of the ID token, even after a
	// max_age request, whose token OpenID Connect Core 1.0 section 2
	// requires it in.
	OmitAuthTime bool
	// TLS serves the IdP over HTTPS with httptest's certificate, which only
	// a client trusting IdP.RootCAs, such as IdP.Client, trusts; false
	// serves plain HTTP on loopback unless URL is set.
	TLS bool
}

IdPOptions configures NewIdP. Every zero value is the default, and each other field changes one thing about what the IdP serves. NewIdP copies every value, so a later write to the options, or to a slice or string they point at, never reaches the running IdP.

type MemStore

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

MemStore is an in-memory account.Store. Every read returns a deep copy and every write stores one. Writers serialise on a mutex and publish a copied state through an atomic pointer, so a read takes no lock and never waits on a write. Construct it with NewMemStore.

func NewMemStore

func NewMemStore() *MemStore

NewMemStore returns a new empty MemStore.

func (*MemStore) APIKeyByHash

func (m *MemStore) APIKeyByHash(ctx context.Context, hash access.Hash) (*access.Key, bool, error)

APIKeyByHash implements account.KeyStore.

func (*MemStore) AuthFailure

func (m *MemStore) AuthFailure(ctx context.Context, ref account.FailureRef) (account.FailureCount, bool, error)

AuthFailure implements account.FailureStore.

func (*MemStore) CleanupExpiredOneTimeTokens

func (m *MemStore) CleanupExpiredOneTimeTokens(_ context.Context, now time.Time) (int64, error)

CleanupExpiredOneTimeTokens deletes every token whose ExpiresAt is not after now.

func (*MemStore) CleanupExpiredSessions

func (m *MemStore) CleanupExpiredSessions(_ context.Context, now time.Time, timeouts access.SessionTimeouts, limit int) ([]access.SessionRef, error)

CleanupExpiredSessions deletes at most limit of the sessions access.ValidateSession refuses, in one snapshot swap, and returns their refs. It refuses a limit below 1 and a non-positive timeout.

func (*MemStore) ConsumeOneTimeToken

func (m *MemStore) ConsumeOneTimeToken(_ context.Context, hash access.Hash, now time.Time) (access.OneTimeToken, bool, error)

ConsumeOneTimeToken implements account.TokenStore.

func (*MemStore) CreateAPIKey

func (m *MemStore) CreateAPIKey(ctx context.Context, key *access.Key) error

CreateAPIKey implements account.KeyStore.

func (*MemStore) CreateInitialUser

func (m *MemStore) CreateInitialUser(ctx context.Context, user *access.User) error

CreateInitialUser implements account.UserStore.

func (*MemStore) CreateKeyAttribution

func (m *MemStore) CreateKeyAttribution(ctx context.Context, a *access.KeyAttribution) error

CreateKeyAttribution implements account.AttributionStore.

func (*MemStore) CreateOneTimeToken

func (m *MemStore) CreateOneTimeToken(ctx context.Context, tok access.OneTimeToken) error

CreateOneTimeToken implements account.TokenStore.

func (*MemStore) CreatePasskey

func (m *MemStore) CreatePasskey(ctx context.Context, cred *access.PasskeyCredential) error

CreatePasskey implements account.PasskeyStore.

func (*MemStore) CreateSession

func (m *MemStore) CreateSession(ctx context.Context, sess *access.Session) error

CreateSession implements account.SessionStore.

func (*MemStore) CreateUser

func (m *MemStore) CreateUser(ctx context.Context, user *access.User) error

CreateUser implements account.UserStore.

func (*MemStore) DeleteAPIKey

func (m *MemStore) DeleteAPIKey(ctx context.Context, ref access.KeyRef) error

DeleteAPIKey implements account.KeyStore.

func (*MemStore) DeleteAuthFailures

func (m *MemStore) DeleteAuthFailures(ctx context.Context, name string, methods []access.Method) error

DeleteAuthFailures implements account.FailureStore.

func (*MemStore) DeleteOneTimeTokens

func (m *MemStore) DeleteOneTimeTokens(_ context.Context, purpose access.TokenPurpose, subject int64) (int, error)

DeleteOneTimeTokens implements account.TokenStore.

func (*MemStore) DeleteOneTimeTokensIssuedBy

func (m *MemStore) DeleteOneTimeTokensIssuedBy(_ context.Context, keyIDs []int64) (int, error)

DeleteOneTimeTokensIssuedBy implements account.TokenStore.

func (*MemStore) DeletePasskey

func (m *MemStore) DeletePasskey(ctx context.Context, ref access.PasskeyRef) error

DeletePasskey implements account.PasskeyStore.

func (*MemStore) DeleteSession

func (m *MemStore) DeleteSession(ctx context.Context, ref access.SessionRef) error

DeleteSession implements account.SessionStore.

func (*MemStore) DeleteSessionByHash

func (m *MemStore) DeleteSessionByHash(ctx context.Context, tokenHash access.Hash) error

DeleteSessionByHash implements account.SessionStore.

func (*MemStore) DeleteUser

func (m *MemStore) DeleteUser(ctx context.Context, id int64) error

DeleteUser implements account.UserStore.

func (*MemStore) DeleteUserAPIKeys

func (m *MemStore) DeleteUserAPIKeys(_ context.Context, userID int64) ([]int64, error)

DeleteUserAPIKeys implements account.KeyStore.

func (*MemStore) DeleteUserPasskeys

func (m *MemStore) DeleteUserPasskeys(_ context.Context, userID int64) ([]int64, error)

DeleteUserPasskeys implements account.PasskeyStore.

func (*MemStore) DeleteUserSessions

func (m *MemStore) DeleteUserSessions(_ context.Context, userID int64, exceptID string) ([]string, error)

DeleteUserSessions implements account.SessionStore.

func (*MemStore) ListAPIKeys

func (m *MemStore) ListAPIKeys(ctx context.Context) ([]access.Key, error)

ListAPIKeys implements account.KeyStore.

func (*MemStore) ListAPIKeysByUserID

func (m *MemStore) ListAPIKeysByUserID(ctx context.Context, userID int64) ([]access.Key, error)

ListAPIKeysByUserID implements account.KeyStore.

func (*MemStore) ListKeyAttributions

func (m *MemStore) ListKeyAttributions(ctx context.Context) ([]access.KeyAttribution, error)

ListKeyAttributions implements account.AttributionStore.

func (*MemStore) ListUsers

func (m *MemStore) ListUsers(ctx context.Context) ([]access.User, error)

ListUsers implements account.UserStore.

func (*MemStore) LiveOneTimeTokens

func (m *MemStore) LiveOneTimeTokens(ctx context.Context, purposes []access.TokenPurpose, now time.Time) ([]access.OneTimeToken, error)

LiveOneTimeTokens implements account.TokenStore.

func (*MemStore) OneTimeTokenByHash

func (m *MemStore) OneTimeTokenByHash(ctx context.Context, hash access.Hash) (access.OneTimeToken, bool, error)

OneTimeTokenByHash implements account.TokenStore.

func (*MemStore) PasskeysByUserID

func (m *MemStore) PasskeysByUserID(ctx context.Context, userID int64) ([]access.PasskeyCredential, error)

PasskeysByUserID implements account.PasskeyStore.

func (*MemStore) PruneAuthFailures

func (m *MemStore) PruneAuthFailures(_ context.Context, keep []string) (int64, error)

PruneAuthFailures implements account.FailureStore.

func (*MemStore) PutAuthFailure

func (m *MemStore) PutAuthFailure(ctx context.Context, f account.FailureCount) error

PutAuthFailure implements account.FailureStore.

func (*MemStore) RenamePasskey

func (m *MemStore) RenamePasskey(ctx context.Context, ref access.PasskeyRef, name string) error

RenamePasskey implements account.PasskeyStore.

func (*MemStore) RotateSession

func (m *MemStore) RotateSession(ctx context.Context, rot account.Rotation) error

RotateSession implements account.SessionStore.

func (*MemStore) SessionByHash

func (m *MemStore) SessionByHash(ctx context.Context, tokenHash access.Hash) (*access.Session, bool, error)

SessionByHash implements account.SessionStore.

func (*MemStore) SessionsByUserID

func (m *MemStore) SessionsByUserID(ctx context.Context, userID int64) ([]access.Session, error)

SessionsByUserID implements account.SessionStore.

func (*MemStore) TouchAPIKey

func (m *MemStore) TouchAPIKey(_ context.Context, keyID int64, at time.Time) error

TouchAPIKey keeps rule 21: an at not after the stored LastUsedAt, or an unknown key, publishes nothing.

func (*MemStore) UnreportedLocks

func (m *MemStore) UnreportedLocks(ctx context.Context) ([]account.FailureCount, error)

UnreportedLocks implements account.FailureStore.

func (*MemStore) Update

func (m *MemStore) Update(_ context.Context, fn func(tx account.Tx) error) error

Update runs fn on a private copy of the store and publishes it when fn returns nil; an error or a panic publishes nothing.

func (*MemStore) UpdatePasskeyAfterLogin

func (m *MemStore) UpdatePasskeyAfterLogin(ctx context.Context, userID int64, credID []byte, upd access.PasskeyLoginUpdate) error

UpdatePasskeyAfterLogin implements account.PasskeyStore.

func (*MemStore) UpdateSessionActivity

func (m *MemStore) UpdateSessionActivity(_ context.Context, tokenHash access.Hash, act access.SessionActivity) error

UpdateSessionActivity keeps rule 21: an At not after the stored LastActivity, or a hash no session has, publishes nothing.

func (*MemStore) UpdateSessionLabel

func (m *MemStore) UpdateSessionLabel(ctx context.Context, ref access.SessionRef, label string) error

UpdateSessionLabel implements account.SessionStore.

func (*MemStore) UpdateUser

func (m *MemStore) UpdateUser(ctx context.Context, user *access.User) error

UpdateUser implements account.UserStore.

func (*MemStore) UserByID

func (m *MemStore) UserByID(ctx context.Context, id int64) (*access.User, bool, error)

UserByID implements account.UserStore.

func (*MemStore) UserByOIDC

func (m *MemStore) UserByOIDC(ctx context.Context, id access.OIDCIdentity) (*access.User, bool, error)

UserByOIDC implements account.UserStore.

func (*MemStore) UserByUsername

func (m *MemStore) UserByUsername(ctx context.Context, canonical string) (*access.User, bool, error)

UserByUsername implements account.UserStore.

func (*MemStore) UserByWebAuthnHandle

func (m *MemStore) UserByWebAuthnHandle(ctx context.Context, handle []byte) (*access.User, bool, error)

UserByWebAuthnHandle implements account.UserStore.

func (*MemStore) UserCount

func (m *MemStore) UserCount(ctx context.Context) (int, error)

UserCount implements account.UserStore.

type PasskeyDevice

type PasskeyDevice struct {

	// CredentialID is the credential's raw ID; NewPasskeyDevice draws 32
	// random bytes.
	CredentialID []byte
	// Origin is the origin clientDataJSON names; empty is "https://" plus the
	// RP ID.
	Origin string
	// UserHandle is the userHandle an assertion carries. Nil is the user ID of
	// the last registration (none before one); a non-nil empty slice sends no
	// userHandle.
	UserHandle []byte
	// SignCount is the signature counter of the last ceremony. A registration
	// reports it unchanged and an assertion increments it before signing, so
	// setting it below a value already sent makes the next assertion a
	// regression.
	SignCount uint32
	// Flags, when non-zero, is the authenticator-data flags octet of every
	// ceremony, written as given: a registration still appends the attested
	// credential data whatever the AT bit says. Zero is UP, UV, BE and BS
	// (0x1D), plus AT (0x40) on a registration.
	Flags byte
	// contains filtered or unexported fields
}

PasskeyDevice is a software WebAuthn authenticator holding one discoverable ES256 credential with "none" attestation. Register and Assert read the options JSON a relying party sends the browser (a {"publicKey": …} object) and return the PublicKeyCredential.toJSON() body the browser sends back. The device answers every options it can parse: it ignores allowCredentials and excludeCredentials, so a test can present a credential a real authenticator would withhold. The exported fields are knobs a test may set between ceremonies; a PasskeyDevice is not safe for concurrent use.

func NewPasskeyDevice

func NewPasskeyDevice(t testing.TB) *PasskeyDevice

NewPasskeyDevice returns a device with a fresh P-256 key and a random credential ID. Register and Assert fail through the t given to NewPasskeyDevice on options they cannot answer, so call them on that test's goroutine; a subtest makes its own device.

func (*PasskeyDevice) Assert

func (d *PasskeyDevice) Assert(options []byte) []byte

Assert answers credential request options with an assertion body signed by the device's key, after incrementing SignCount. The RP ID is the options' rpId, else the last registration's, else Origin's host; the test fails when none is known or the options do not parse or lack a challenge.

func (*PasskeyDevice) Register

func (d *PasskeyDevice) Register(options []byte) []byte

Register answers credential creation options with a registration body and records the RP ID and user ID for later assertions. It fails the test when the options do not parse, lack a challenge or user ID, offer no ES256 parameter, leave the RP ID unknown, or CredentialID is over 65535 bytes.

Jump to

Keyboard shortcuts

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