domain

package
v0.29.0 Latest Latest
Warning

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

Go to latest
Published: Oct 28, 2026 License: MIT Imports: 8 Imported by: 0

Documentation

Overview

Package domain holds the access contracts: credentials, ports and use-case interfaces.

Index

Constants

View Source
const (
	TokenPrefix         = "nct_"
	InvitePrefix        = "nci_"
	AdminKeyPrefix      = "nca_"
	CredentialSeparator = "_"

	IDBytes             = 16
	SecretBytes         = 32
	EncodedIDLength     = 2 * IDBytes
	EncodedSecretLength = 43

	InviteTTL          = time.Hour
	LastUsedResolution = time.Minute

	UserLabelPattern = "^[a-z0-9][a-z0-9._-]{0,63}$"

	AuthorizationHeader = "Authorization"
	AuthenticateHeader  = "WWW-Authenticate"

	BearerScheme = "Bearer"
	InviteScheme = "Invite"

	RedeemPath          = "/api/v1/invites/redeem"
	RedeemPattern       = "POST " + RedeemPath
	CreateInvitePattern = "POST /admin/v1/invites"
	ListTokensPattern   = "GET /admin/v1/tokens"         //nolint:gosec // route pattern, not a credential
	DeleteTokenPattern  = "DELETE /admin/v1/tokens/{id}" //nolint:gosec // route pattern, not a credential
	TokenIDPathValue    = "id"

	RedactedSecret = "[REDACTED]"

	MaxRequestBodyBytes = 16 << 10

	PublicURLVariable = "$NOTIFYCAT_URL"
)

Credential wire format, sizes and lifetimes.

Variables

View Source
var (
	ErrUnauthorized        = errors.New("access: unauthorized")
	ErrMalformedCredential = errors.New("access: malformed credential")
	ErrInvalidUser         = errors.New("access: invalid user")
	ErrInviteNotFound      = errors.New("access: invite not found")
	ErrInviteUsed          = errors.New("access: invite already used")
	ErrTokenNotFound       = errors.New("access: token not found")
)

Access sentinel errors.

Functions

func RedeemCommand

func RedeemCommand(publicDomain, invite string) string

RedeemCommand returns the curl command that redeems the invite.

func ValidUser

func ValidUser(user string) bool

ValidUser reports whether user matches UserLabelPattern.

func WithPrincipal

func WithPrincipal(ctx context.Context, principal Principal) context.Context

WithPrincipal stores the principal in the context.

Types

type AdminAuthenticator

type AdminAuthenticator interface {
	Authenticate(ctx context.Context, rawKey string) error
}

AdminAuthenticator verifies a raw admin key.

type AdminHandlerParams

type AdminHandlerParams struct {
	Authenticator AdminAuthenticator
	Invites       InviteIssuer
	Tokens        TokenAdmin
	Logger        *slog.Logger
}

AdminHandlerParams are the dependencies of the admin HTTP handler.

type AuthError

type AuthError struct {
	Reason AuthFailureReason
}

AuthError is an authentication failure carrying the reason for logs; it unwraps to ErrUnauthorized.

func (*AuthError) Error

func (authError *AuthError) Error() string

func (*AuthError) Unwrap

func (authError *AuthError) Unwrap() error

type AuthFailureReason

type AuthFailureReason string

AuthFailureReason names why authentication failed, for logs only.

const (
	AuthFailureMalformed AuthFailureReason = "malformed"
	AuthFailureUnknown   AuthFailureReason = "unknown"
	AuthFailureMismatch  AuthFailureReason = "mismatch"
	AuthFailureExpired   AuthFailureReason = "expired"
	AuthFailureUsed      AuthFailureReason = "used"
)

Authentication failure reasons.

type Clock

type Clock interface {
	Now() time.Time
}

Clock provides the current time.

type Credential

type Credential struct {
	Prefix string
	ID     string
	Secret string
}

Credential is a parsed prefix + id + secret; fmt and slog render it redacted, and only Encode returns the wire form.

func ParseCredential

func ParseCredential(raw, prefix string) (Credential, error)

ParseCredential parses raw as prefix + hex id + "_" + base64url secret. It never splits on "_" because the secret may contain it.

func (Credential) Encode

func (credential Credential) Encode() string

Encode returns the wire form of the credential.

func (Credential) Format

func (credential Credential) Format(state fmt.State, _ rune)

Format writes the redacted form for every fmt verb.

func (Credential) LogValue

func (credential Credential) LogValue() slog.Value

LogValue renders the redacted form in slog output.

func (Credential) String

func (credential Credential) String() string

String renders the credential with the secret redacted.

type ErrorCode

type ErrorCode string

ErrorCode is the machine-readable code in an HTTP error body.

const (
	ErrorCodeUnauthorized ErrorCode = "unauthorized"
	ErrorCodeInvalidBody  ErrorCode = "invalid_body"
	ErrorCodeInvalidUser  ErrorCode = "invalid_user"
	ErrorCodeNotFound     ErrorCode = "not_found"
	ErrorCodeInternal     ErrorCode = "internal_error"
)

HTTP error codes.

type Hasher

type Hasher interface {
	Hash(secret string) (string, error)
	Matches(hash, secret string) bool
}

Hasher hashes and verifies credential secrets.

type Invite

type Invite struct {
	ID        string
	User      string
	ExpiresAt time.Time
	UsedAt    *time.Time
	CreatedAt time.Time
}

Invite is a single-use, expiring offer to create a token.

type InviteIssuer

type InviteIssuer interface {
	Issue(ctx context.Context, user string) (IssuedInvite, error)
}

InviteIssuer creates an invite for a user.

type InviteIssuerParams

type InviteIssuerParams struct {
	Invites  InviteStore
	Secrets  SecretSource
	Hasher   Hasher
	Clock    Clock
	Settings Settings
	Logger   *slog.Logger
}

InviteIssuerParams are the dependencies of the invite issuer.

type InviteRedeemer

type InviteRedeemer interface {
	Redeem(ctx context.Context, rawInvite string) (IssuedToken, error)
}

InviteRedeemer exchanges a raw invite credential for a token.

type InviteRedeemerParams

type InviteRedeemerParams struct {
	Invites InviteStore
	Secrets SecretSource
	Hasher  Hasher
	Clock   Clock
	Logger  *slog.Logger
}

InviteRedeemerParams are the dependencies of the invite redeemer.

type InviteStore

type InviteStore interface {
	Create(ctx context.Context, invite StoredInvite) error
	// Find returns ErrInviteNotFound when no invite has the id.
	Find(ctx context.Context, id string) (StoredInvite, error)
	// Redeem marks the invite used and inserts the token in one transaction; it returns ErrInviteUsed when the invite was already used.
	Redeem(ctx context.Context, inviteID string, token StoredToken) error
}

InviteStore persists single-use invites.

type IssuedInvite

type IssuedInvite struct {
	Invite        Invite
	Secret        string
	RedeemCommand string
}

IssuedInvite carries the full encoded invite credential in Secret, shown once.

func (IssuedInvite) Format

func (issued IssuedInvite) Format(state fmt.State, _ rune)

Format writes the redacted form for every fmt verb.

func (IssuedInvite) LogValue

func (issued IssuedInvite) LogValue() slog.Value

LogValue renders the redacted form in slog output.

func (IssuedInvite) String

func (issued IssuedInvite) String() string

String renders the invite with the secret redacted.

type IssuedToken

type IssuedToken struct {
	Token  Token
	Secret string
}

IssuedToken carries the full encoded token credential in Secret, shown once.

func (IssuedToken) Format

func (issued IssuedToken) Format(state fmt.State, _ rune)

Format writes the redacted form for every fmt verb.

func (IssuedToken) LogValue

func (issued IssuedToken) LogValue() slog.Value

LogValue renders the redacted form in slog output.

func (IssuedToken) String

func (issued IssuedToken) String() string

String renders the token with the secret redacted.

type Principal

type Principal struct {
	TokenID string
	User    string
}

Principal is the authenticated agent behind a request.

func PrincipalFrom

func PrincipalFrom(ctx context.Context) (Principal, bool)

PrincipalFrom reads the principal stored by WithPrincipal.

type SecretSource

type SecretSource interface {
	// NewID returns IDBytes random bytes, hex encoded.
	NewID() (string, error)
	// NewSecret returns SecretBytes random bytes, base64url encoded without padding.
	NewSecret() (string, error)
}

SecretSource generates random credential parts.

type Settings

type Settings struct {
	AdminKeyHash string
	PublicDomain string
}

Settings is the access configuration.

type StoredInvite

type StoredInvite struct {
	Invite
	SecretHash string
}

StoredInvite is an Invite with its secret hash.

type StoredToken

type StoredToken struct {
	Token
	SecretHash string
}

StoredToken is a Token with its secret hash.

type Token

type Token struct {
	ID         string
	User       string
	CreatedAt  time.Time
	LastUsedAt *time.Time
}

Token is an agent token without its secret.

type TokenAdmin

type TokenAdmin interface {
	List(ctx context.Context) ([]Token, error)
	Delete(ctx context.Context, id string) error
}

TokenAdmin lists and revokes tokens.

type TokenAuthenticator

type TokenAuthenticator interface {
	Authenticate(ctx context.Context, rawToken string) (Principal, error)
}

TokenAuthenticator resolves a raw token credential to a Principal.

type TokenAuthenticatorParams

type TokenAuthenticatorParams struct {
	Tokens TokenStore
	Hasher Hasher
	Clock  Clock
	Logger *slog.Logger
}

TokenAuthenticatorParams are the dependencies of the token authenticator.

type TokenStore

type TokenStore interface {
	// Find returns ErrTokenNotFound when no token has the id.
	Find(ctx context.Context, id string) (StoredToken, error)
	List(ctx context.Context) ([]Token, error)
	// Delete returns ErrTokenNotFound when no token has the id.
	Delete(ctx context.Context, id string) error
	TouchLastUsed(ctx context.Context, id string, usedAt time.Time) error
}

TokenStore persists agent tokens.

Jump to

Keyboard shortcuts

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