egauthtest

package
v0.18.0 Latest Latest
Warning

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

Go to latest
Published: Nov 14, 2026 License: MIT Imports: 27 Imported by: 1 module, 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 egauthtest holds the test-only helpers of egauth: the development configuration, the principal builder, the manual clock, a capturing mailbox and a fake OIDC provider. It is the only sanctioned home of Insecure opt-outs and of the root test hooks, and the G15 guard fails any import of it from a non-test file, so a helper copied into a main package fails CI.

Stability

Stability class: experimental. No SemVer guarantee: the API may change or be removed in any release. See docs/adr/0001-v1-scope-and-stability-classes.md.

Index

Constants

View Source
const TestOptOutReason = "egauthtest development configuration; never use in production"

TestOptOutReason is the reason every opt-out of Config acknowledges; Posture reports it.

Variables

This section is empty.

Functions

func Config

func Config[C any]() egauth.Config[C]

Config returns a loopback development configuration: stateful sessions, the password module with a Mailbox as Email, and the opt-outs a fast test needs (no rate limit). Storage is left empty because this package cannot import the stores; assign it before New:

cfg := egauthtest.Config[struct{}]()
cfg.Storage = memstore.New(cfg.KEK)

Read captured mail back with cfg.Email.(*egauthtest.Mailbox). Every call draws a fresh KEK from crypto/rand, so data sealed under one Config is unreadable under another: keep cfg.KEK to reopen a store. Every opt-out carries TestOptOutReason and is accepted by New only while every origin and audience is loopback; a public deployment must acknowledge it with its own reason.

func New

func New[C any](cfg egauth.Config[C], clk *Clock, idp *IdP) (*egauth.Auth[C], error)

New is egauth.New for a journey: every component of the Auth reads clk instead of the wall clock, which must be the clock the storage was built with (memstore.NewWithClock), and its outbound client trusts the certificate of idp. Either may be nil to keep the wall clock or the system roots. The SSRF dial guard stays in force, so a loopback provider still needs Insecure.OutboundPrivateNetwork in cfg.

func NewPrincipal

func NewPrincipal[C any](spec PrincipalSpec) (egauth.Principal[C], error)

NewPrincipal builds the Principal described by spec without running any route gate: an API-key Principal when spec.Machine is set, a session Principal otherwise. Use egauth.Principal's zero value for Anonymous. It fails when Custom is not a C or the spec cannot form a caller.

func NewResourceServer

func NewResourceServer[C any](cfg egauth.ResourceConfig, clk *Clock, roots *x509.CertPool) (*egauth.ResourceServer[C], error)

NewResourceServer is egauth.NewResourceServer for a journey: the server reads clk, trusts the certificates in roots, and may reach an Auth on loopback, as an httptest Auth is. Either may be nil to keep the wall clock or the system roots.

func ReferenceTime

func ReferenceTime() time.Time

ReferenceTime is the instant NewClock(time.Time{}) starts at and the default instant of every time in a PrincipalSpec.

Types

type Clock

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

Clock is a manually driven clock: it never advances on its own and is safe for concurrent use.

func NewClock

func NewClock(start time.Time) *Clock

NewClock returns a clock stopped at start, or at ReferenceTime when start is zero.

func (*Clock) Advance

func (c *Clock) Advance(d time.Duration)

Advance moves the clock forward by d; a negative d moves it back.

func (*Clock) Library

func (c *Clock) Library() egauth.TestClock

Library returns the library clock that reads c, observing every Set and Advance. Pass it to memstore.NewWithClock so that store-side expiry follows c.

func (*Clock) Now

func (c *Clock) Now() time.Time

Now returns the instant the clock is stopped at.

func (*Clock) Set

func (c *Clock) Set(now time.Time)

Set moves the clock to now, backwards or forwards.

type IDToken

type IDToken struct {
	User     IdPUser
	Audience string
	Nonce    string
}

IDToken is what SignIDToken signs; an empty Nonce is omitted.

type IdP

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

IdP is a fake OpenID Connect provider on a loopback TLS server: discovery, authorization, token, userinfo and JWKS endpoints, ID tokens signed with a throwaway ES256 key. It is as strict as a conforming provider so that a client regression fails: authorization requires state, nonce and an S256 PKCE challenge; the token endpoint requires the authorization_code grant, the verifier and client authentication (client_secret_post or client_secret_basic) by the client the code was issued to. The browser sign-in is simulated: Authorize immediately redirects back as the current user.

func NewIdP

func NewIdP(t testing.TB, clk *Clock) *IdP

NewIdP starts the fake provider and stops it when t ends. Times in ID tokens come from clk, or from the wall clock when clk is nil, which is what an Auth without a test clock checks them against. The initial user is subject "idp-user-1" with a verified email.

func (*IdP) ClientID

func (p *IdP) ClientID() string

ClientID returns the client id Provider registers.

func (*IdP) ClientSecret

func (p *IdP) ClientSecret() string

ClientSecret returns the client secret the token endpoint requires with ClientID, by client_secret_post or client_secret_basic. It is public and protects nothing.

func (*IdP) HTTPClient

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

HTTPClient returns a client that trusts the provider's certificate, follows no redirect and gives up after 60 seconds.

func (*IdP) Issuer

func (p *IdP) Issuer() string

Issuer returns the issuer URL, which is also the origin of every endpoint.

func (*IdP) Provider

func (p *IdP) Provider(name string) federation.Provider

Provider returns the egauth federation spec of the fake provider under name, trusting its verified emails. It carries Issuer and JWKSURL, so it needs no discovery.

func (*IdP) SetUser

func (p *IdP) SetUser(u IdPUser)

SetUser replaces the identity asserted by the next sign-ins.

func (*IdP) SignIDToken

func (p *IdP) SignIDToken(t IDToken) (string, error)

SignIDToken returns t signed by the provider, valid for ten minutes from the provider clock. It fails only when the system random source does.

type IdPUser

type IdPUser struct {
	Subject       string
	Email         string
	EmailVerified bool
	Name          string
}

IdPUser is the identity the fake provider asserts after a sign-in.

type Mail

type Mail struct {
	Kind       string
	To         string
	Link       string
	Code       string
	RevertLink string
	DeliveryID string
}

Mail is one message a Mailbox captured. Link, Code and RevertLink are the working secrets, so never log a Mail.

func (Mail) GoString

func (m Mail) GoString() string

GoString renders m for %#v with its secrets redacted.

func (Mail) LogValue

func (m Mail) LogValue() slog.Value

LogValue renders m for slog with its secrets redacted.

func (Mail) MarshalJSON

func (m Mail) MarshalJSON() ([]byte, error)

MarshalJSON renders m with its secrets redacted.

func (Mail) String

func (m Mail) String() string

String renders m with its secrets redacted.

type Mailbox

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

Mailbox is an egauth.EmailDeliverer that records every message instead of sending it. It is safe for concurrent use.

func (*Mailbox) AccountExistsNotice

func (m *Mailbox) AccountExistsNotice(_ context.Context, n egauth.NoticeMessage) error
func (m *Mailbox) EmailChangeLink(_ context.Context, l egauth.LinkMessage) error
func (m *Mailbox) EmailVerificationLink(_ context.Context, l egauth.LinkMessage) error

func (*Mailbox) GoString

func (m *Mailbox) GoString() string

GoString renders like String.

func (*Mailbox) Last

func (m *Mailbox) Last(kind string) (Mail, bool)

Last returns the most recent message of kind, and false when there is none. Kind is the method name of egauth.EmailDeliverer, for example "PasswordResetLink".

func (*Mailbox) LogValue

func (m *Mailbox) LogValue() slog.Value

LogValue renders like String.

func (*Mailbox) LoginCode

func (m *Mailbox) LoginCode(_ context.Context, c egauth.CodeMessage) error
func (m *Mailbox) MagicLink(_ context.Context, l egauth.LinkMessage) error

func (*Mailbox) Messages

func (m *Mailbox) Messages() []Mail

Messages returns a copy of the captured messages in delivery order.

func (m *Mailbox) PasswordResetLink(_ context.Context, l egauth.LinkMessage) error
func (m *Mailbox) RecoveryEmailLink(_ context.Context, l egauth.LinkMessage) error
func (m *Mailbox) RegistrationLink(_ context.Context, l egauth.LinkMessage) error

func (*Mailbox) SecurityNotice

func (m *Mailbox) SecurityNotice(_ context.Context, n egauth.SecurityNoticeMessage) error

func (*Mailbox) String

func (m *Mailbox) String() string

String renders the mailbox without its messages, which carry secrets.

type PrincipalSpec

type PrincipalSpec struct {
	Subject         principal.Subject
	Lineage         uuid.UUID
	UsedFactors     []principal.Factor
	PasskeyID       []byte
	SecurityEpoch   uint64
	MustChange      bool
	Remembered      bool
	ReturnPath      string
	Transport       principal.Transport
	Provider        string
	PrimaryAt       time.Time
	SecondAt        time.Time
	CreatedAt       time.Time
	ClaimsFetchedAt time.Time
	Roles           []string
	Groups          []string
	Scopes          []string
	Custom          any
	Machine         *egauth.APIKeyInfo
}

PrincipalSpec describes the Principal NewPrincipal builds. Every zero field takes a default: the single tenant and a fixed user, the password factor, cookie transport, and ReferenceTime for PrimaryAt, CreatedAt and ClaimsFetchedAt.

type Resolution

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

Resolution is the read-only view of a configuration after the defaults registry was applied.

func Resolved

func Resolved[C any](cfg egauth.Config[C]) Resolution

Resolved applies the library defaults to a copy of cfg without building an Auth, so a test can read back that a default took effect. Paths are dotted field names with [i] for elements, for example "Policy.IdleTimeout" or "Modules.APIKeys.Kinds[0]".

func (Resolution) Applied

func (r Resolution) Applied() []string

Applied returns the sorted paths filled from the defaults registry.

func (Resolution) Defaulted

func (r Resolution) Defaulted(path string) bool

Defaulted reports whether the field at path was filled from the defaults registry.

func (Resolution) Get

func (r Resolution) Get(path string) (any, bool)

Get returns the value at path after defaults, and false for an unknown path.

func (Resolution) Problems

func (r Resolution) Problems() []string

Problems returns every validation failure as "<field>: <problem>".

Jump to

Keyboard shortcuts

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