authtest

package
v0.5.0 Latest Latest
Warning

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

Go to latest
Published: Oct 31, 2026 License: Apache-2.0 Imports: 23 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

Overview

Package authtest provides the test harness every purser authenticator is held to: an in-memory certificate authority and a conformance suite.

It exists because the properties that matter in authentication code are negative ones. A test that only asserts the happy path passes just as well against a check that never runs, so the interesting cases are the untrusted issuer, the expired certificate, the malformed token, the peer the authorizer should have rejected. Writing those once, here, is the reason purser is a shared module rather than four copies of the same package.

Certificates are minted in-process. Nothing touches disk, no fixture keys live in the repository, and no test rots when a checked-in certificate expires.

This package imports testing and is meant for use from tests.

Index

Constants

View Source
const DefaultAudience = "purser.authtest/audience"

DefaultAudience is the audience Issuer.Mint puts on a token when TokenOptions.Audience is empty. Configure the authenticator under test with it, or set an audience explicitly on both sides.

View Source
const DefaultSubject = "purser.authtest/subject"

DefaultSubject is the "sub" claim Mint uses when the caller supplies none. Every token needs one — a token without "sub" is rejected — and most tests do not care what it is. Exported so a test asserting on the resolved identity does not have to repeat the literal.

Variables

This section is empty.

Functions

func RunAuthenticatorSuite

func RunAuthenticatorSuite(t *testing.T, s Subject)

RunAuthenticatorSuite runs the conformance suite against s. Every authn.Authenticator, in this module and in consuming repositories, is expected to pass it:

func TestMyAuth(t *testing.T) {
    authtest.RunAuthenticatorSuite(t, authtest.Subject{
        Authenticator: myAuth,
        WantSource:    purser.AuthSourceBearer,
        Valid:         func() (*http.Request, purser.Caller) { ... },
        Malformed:     []authtest.MalformedCase{ ... },
    })
}

Passing the suite is a floor, not a substitute for tests of what the authenticator specifically does. The suite knows nothing about issuers, claims, or trust domains.

Types

type CA

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

CA is an in-memory certificate authority. Use it to mint client and server certificates for handshake tests, and to build the trust pool a verifier is configured with.

A test that needs an untrusted-issuer negative creates a second CA and offers its leaf to a verifier configured with the first CA's pool.

Every method reports failure through testing.TB, because a CA that cannot mint is a broken test rather than a case under test. The error-returning form lives in the module's internal/ca package, for the examples, which mint credentials outside a test.

func NewCA

func NewCA(tb testing.TB, name string) *CA

NewCA returns a fresh self-signed authority named name. The name appears in the issuer DN, so give the trusted and untrusted authorities in a test distinguishable names: it is the difference between a legible failure and "x509: certificate signed by unknown authority".

func (*CA) Cert

func (c *CA) Cert() *x509.Certificate

Cert returns the authority's own certificate.

func (*CA) Issue

func (c *CA) Issue(tb testing.TB, opts LeafOptions) tls.Certificate

Issue mints and signs a leaf certificate. The returned tls.Certificate carries the leaf's parsed form in its Leaf field and the issuing CA in its chain, so it can be presented directly by either side of a handshake.

func (*CA) IssueClient

func (c *CA) IssueClient(tb testing.TB, cn string) tls.Certificate

IssueClient mints a client certificate whose subject CN is cn. A shorthand for the common case; reach for Issue when the test cares about SANs or validity.

func (*CA) IssueServer

func (c *CA) IssueServer(tb testing.TB, host string) tls.Certificate

IssueServer mints a server certificate valid for host, which may be a DNS name or an IP literal.

func (*CA) Pool

func (c *CA) Pool() *x509.CertPool

Pool returns a certificate pool trusting only this authority. Each call returns a fresh pool, so a test may add to one without affecting another.

type Issuer

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

Issuer is an OpenID Connect provider backed by an httptest server. It serves a discovery document and a JWK Set, and mints tokens signed by the keys it publishes.

It runs over TLS, because purser's OIDC authenticator refuses a plaintext issuer: the transport is what authenticates the published keys. Pass Client to the authenticator's Options.HTTPClient so it trusts the server's ephemeral certificate.

Every method reports failure through testing.TB. A provider that cannot mint is a broken test, not a case under test. The server is closed by a t.Cleanup registered in NewIssuer.

func NewIssuer

func NewIssuer(tb testing.TB) *Issuer

NewIssuer starts a provider with a single RS256 key.

RS256 rather than something quicker to generate because it is what OpenID Connect requires every provider to support and what the real ones use; a test suite that only ever sees elliptic keys would not notice an authenticator that mishandles the common case. Use AddKey for the others.

func (*Issuer) AddKey

func (i *Issuer) AddKey(tb testing.TB, alg string) string

AddKey generates a key for alg, publishes it, and makes it the one Mint signs with. It returns the new key's ID.

The keys already published stay published, which is what a real rotation looks like: the new key appears in the JWK Set before anything is signed with it, and the old one stays until the tokens it signed have expired. Use Rotate for the abrupt version.

func (*Issuer) Certificate

func (i *Issuer) Certificate() *x509.Certificate

Certificate is the server's ephemeral TLS certificate, for a test that has to build a client trusting this issuer alongside something else.

func (*Issuer) Claims

func (i *Issuer) Claims(tb testing.TB, opts TokenOptions) []byte

Claims returns the JSON payload Mint would sign for opts, for a test that wants those claims under a header it builds itself. See RawToken.

func (*Issuer) Client

func (i *Issuer) Client() *http.Client

Client returns an http.Client that trusts this server's certificate.

func (*Issuer) Close

func (i *Issuer) Close()

Close stops the server, for a test that needs the provider to become unreachable: a key cache that must serve what it already has, or a cold cache that must report the outage. Idempotent, and harmless alongside the cleanup NewIssuer registers.

Mint keeps working afterwards. The keys are held in this process, so a closed issuer still mints the token whose verification is the thing under test.

func (*Issuer) DiscoveryRequests

func (i *Issuer) DiscoveryRequests() int

DiscoveryRequests reports how many times the discovery document has been fetched.

func (*Issuer) JWKS

func (i *Issuer) JWKS(tb testing.TB) []byte

JWKS returns the key set exactly as the endpoint serves it, for a test that needs to serve a doctored version of it from somewhere else. It does not count as a fetch.

func (*Issuer) JWKSRequests

func (i *Issuer) JWKSRequests() int

JWKSRequests reports how many times the key endpoint has been fetched. It is what a test asserts against to pin a key cache: that a hundred verifications cost one fetch, and that a flood of unknown-key tokens does not cost a hundred.

func (*Issuer) JWKSURL

func (i *Issuer) JWKSURL() string

JWKSURL is the key endpoint, for a test that configures it directly rather than letting the authenticator discover it.

func (*Issuer) KeyID

func (i *Issuer) KeyID(tb testing.TB) string

KeyID is the ID of the key Mint signs with by default: the most recently added one. A test that wants to name that key in a header it builds by hand needs it, and parsing the JWK Set back to find it is no way to spend a test.

func (*Issuer) Mint

func (i *Issuer) Mint(tb testing.TB, opts TokenOptions) string

Mint returns a signed, compact-serialized token.

func (*Issuer) PublicKey

func (i *Issuer) PublicKey(tb testing.TB, keyID string) []byte

PublicKey returns the PKIX DER encoding of a published key's public half. Pass "" for the current key.

This is the material an algorithm-confusion attack signs with: the whole shape of that attack is an HMAC whose secret is the verification key the issuer published, so a test that fakes it with a random secret is not testing the attack. See RawTokenOptions.HMACKey.

func (*Issuer) RawToken

func (i *Issuer) RawToken(tb testing.TB, opts RawTokenOptions) string

RawToken assembles a compact JWS from the header and payload a test chooses.

func (*Issuer) Rotate

func (i *Issuer) Rotate(tb testing.TB) string

Rotate replaces the published key set with a single new key of the same algorithm as the current one, and returns its ID.

This is the abrupt rotation: tokens signed by the old key stop verifying as soon as anything refetches the set. It is how a test pins that a key withdrawn by the issuer eventually stops being accepted here, which is a property no gradual rotation can demonstrate.

Read, generate and install happen under one lock, so two concurrent rotations cannot lose one another's key.

func (*Issuer) URL

func (i *Issuer) URL() string

URL is the issuer URL: what goes in the authenticator's Options.Issuer, and what appears in the "iss" claim of minted tokens.

type LeafOptions

type LeafOptions = ca.LeafOptions

LeafOptions describes a certificate to mint. The zero value yields a client certificate valid from an hour ago until an hour from now, with no subject and no SANs — useful in itself, as the certificate that carries none of the fields an authenticator might read.

type MalformedCase

type MalformedCase struct {
	// Name identifies the case in test output.
	Name string
	// Request returns the request carrying the bad credential.
	Request func() *http.Request
}

MalformedCase is one credential that must be rejected.

type RawTokenOptions

type RawTokenOptions struct {
	// Payload is the JWS payload, verbatim. Issuer.Claims produces the
	// usual one; a test can pass anything, including bytes that are not
	// a JSON object.
	Payload []byte

	// SignWith names the published key whose private half signs.
	// Defaults to the current key.
	SignWith string

	// UnpublishedKey signs with a fresh key of the signing key's
	// algorithm that is not in the JWK Set.
	UnpublishedKey bool

	// Algorithm signs with this algorithm using the chosen key's
	// material, rather than with the algorithm that key is published
	// under. Defaults to the key's own.
	//
	// This is how a token gets a genuine RS256 signature from a key the
	// JWK Set publishes as PS256 — the same key material, the padding
	// the issuer did not sanction.
	Algorithm string

	// HMACKey signs symmetrically over these bytes instead of with a
	// published key, for the algorithm-confusion attack. Pass
	// Issuer.PublicKey: the attack's whole shape is an HMAC keyed by
	// material the issuer publishes. Header must name the "kid", since
	// there is no published key to take one from.
	HMACKey []byte

	// OmitKeyID leaves "kid" out of the header, which is legal and what
	// a single-key provider often emits.
	OmitKeyID bool

	// Header is merged over the protected header last, so it overrides
	// "alg", "kid" and "typ". This is where a header is made to
	// disagree with the signature beneath it:
	//
	//	Header: map[string]any{"kid": other}  // names a key that did not sign
	//	Header: map[string]any{"alg": "RS256"} // over a PS256 signature
	//
	// Values are set, never removed; use OmitKeyID for the one field
	// worth omitting.
	Header map[string]any

	// Unsigned emits "alg": "none" and an empty signature segment. No
	// key is used.
	Unsigned bool
}

RawTokenOptions describes a token assembled header-first.

Mint covers a token that should be accepted, and one malformed in its claims. This covers the ones malformed in the *header* — the shapes a real provider never emits, which are exactly the ones a verifier has to refuse. Without it those tokens have to be built by splicing base64 segments by hand, and a test that does that tends to end up asserting something other than what it names.

type Subject

type Subject struct {
	// Authenticator under test. Required.
	Authenticator authn.Authenticator

	// WantSource is the credential class Authenticator must report.
	// Required: an authenticator whose Source is not pinned by a test
	// can start mis-reporting how requests were authenticated without
	// anything failing.
	WantSource purser.AuthSource

	// Valid returns a request carrying a credential Authenticator must
	// accept, and the Caller it must resolve to. Called repeatedly, so
	// it must return an equivalent fresh request each time.
	//
	// Only Identity and Admin are compared, plus Labels when the
	// returned Caller carries any — a subject that does not care about
	// Labels returns none.
	//
	// Required unless AcceptsUncredentialed.
	Valid func() (*http.Request, purser.Caller)

	// Malformed returns requests whose credentials must be rejected:
	// the wrong token, a truncated header, a certificate lacking the
	// configured subject field. Required unless AcceptsUncredentialed.
	Malformed []MalformedCase

	// AcceptsUncredentialed marks an authenticator that resolves every
	// request by design, such as authn.Anonymous. It inverts the
	// no-credential check and waives the requirement for failing
	// cases. Set it only for an authenticator that verifies nothing;
	// setting it to quiet the suite disables the checks that matter.
	AcceptsUncredentialed bool

	// ProxyDenied returns a request whose credential is valid but not
	// permitted to assert other identities. Optional; only meaningful
	// for an authenticator implementing authn.AuthenticatorWithProxy.
	ProxyDenied func() *http.Request

	// UnprovisionedIdentity is an identity the authenticator's table
	// does not contain. Optional; only meaningful for an
	// authenticator implementing authn.IdentityLookup.
	UnprovisionedIdentity string

	// ProvisionedIdentity is an identity the authenticator's table does
	// contain. Optional; only meaningful for an authenticator
	// implementing authn.IdentityLookup, where it lets the suite check
	// that a looked-up Caller aliases no table state — the same hazard
	// as on the Authenticate path, reached instead through the proxy
	// path that materializes an asserted Caller.
	ProvisionedIdentity string
}

Subject describes an Authenticator under test, plus the minimum a caller must supply for the suite to exercise it: one request that must succeed, and at least one that must fail.

The failing cases are not optional politeness. An authenticator that is only ever shown a good credential passes identically to one whose verification is commented out.

type TokenOptions

type TokenOptions struct {
	// Subject is the "sub" claim. Defaults to a fixed placeholder.
	Subject string

	// Email is the "email" claim, omitted when empty. Setting it also
	// sets "email_verified" to true, unless EmailUnverified says
	// otherwise.
	Email string

	// EmailUnverified mints "email_verified": false. Only meaningful
	// alongside Email.
	EmailUnverified bool

	// Audience is the "aud" claim. Defaults to DefaultAudience.
	Audience []string

	// Issuer overrides the "iss" claim, for the token that was minted
	// by somebody else and offered here.
	Issuer string

	// IssuedAt, NotBefore and Expiry are the validity window. IssuedAt
	// defaults to now and Expiry to an hour from now; NotBefore is
	// omitted when zero.
	IssuedAt  time.Time
	NotBefore time.Time
	Expiry    time.Time

	// Claims are merged into the payload last, so they override
	// anything above. A nil value removes the claim:
	//
	//	Claims: map[string]any{"exp": nil}          // no expiry at all
	//	Claims: map[string]any{"exp": "next week"}  // wrong type
	//	Claims: map[string]any{"hd": "example.com"} // an extra claim
	//
	// which is how a test reaches the malformed shapes that a
	// well-behaved provider never emits and an attacker will.
	//
	// A claim set to JSON null — a different thing from a missing one,
	// and worth its own test — is spelled with a json.RawMessage, which
	// is copied into the payload verbatim:
	//
	//	Claims: map[string]any{"email_verified": json.RawMessage("null")}
	Claims map[string]any

	// KeyID names the published key to sign with. Defaults to the
	// current one — the most recently added.
	KeyID string

	// UnpublishedKey signs with a freshly generated key that is not in
	// the JWK Set: a well-formed token from the wrong signer.
	UnpublishedKey bool
}

TokenOptions describes a token to mint. The zero value yields a token that a correctly configured authenticator accepts: the issuer's own URL, DefaultAudience, a subject, and an hour of validity.

Jump to

Keyboard shortcuts

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