aauth

package
v0.6.1 Latest Latest
Warning

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

Go to latest
Published: Jun 27, 2026 License: MIT Imports: 23 Imported by: 0

Documentation

Overview

Package aauth implements the AAuth protocol for agent-to-resource authentication.

EXPERIMENTAL

This package implements a draft specification that is subject to change. The AAuth protocol is defined in draft-hardt-oauth-aauth-protocol.

Protocol Overview

AAuth (Agent Authentication and Authorization) enables AI agents to prove their identity cryptographically without pre-registration. Unlike traditional OAuth 2.0, which requires shared secrets (client_id/client_secret), AAuth uses:

  • Self-published agent identities: aauth:local@domain URIs
  • Cryptographic proof-of-possession: Every token bound via cnf.jwk
  • HTTP request signing: RFC 9421 signatures on all requests
  • Delegation chains: act claim for human-to-agent authorization
  • No pre-registration: Agents prove identity via signatures

Token Types

AAuth defines three token types:

  • aa-agent+jwt: Agent identity token issued by an Agent Provider
  • aa-auth+jwt: Authorization token issued by Person Server or Access Server
  • aa-resource+jwt: Exchange token issued by Resource for PS/AS exchange

Authorization Modes

The protocol supports multiple authorization modes:

  1. Identity-only: Agent identity is sufficient for access
  2. Resource-managed: Resource controls access internally
  3. PS-asserted (3-party): Person Server provides human authorization
  4. Federated (4-party): External Access Server handles authorization

Example Usage

// Create an agent with a key pair
agent, err := aauth.NewAgent(
	&aauth.AAuthID{Local: "calendar-bot", Domain: "example.com"},
	privateKey,
)
if err != nil {
	log.Fatal(err)
}

// Make an authenticated request
client := &http.Client{Transport: agent.Transport()}
resp, err := client.Get("https://api.example.com/calendar")

Token Verification

All verify methods accept a context for proper cancellation and timeout handling:

// Verify tokens on a resource server
rs := aauth.NewResourceServer(...)
agentToken, err := rs.VerifyAgentToken(ctx, tokenString)
authToken, err := rs.VerifyAuthToken(ctx, tokenString)

// Parse tokens for inspection (without verification)
agentToken, err := aauth.ParseAgentToken(tokenString)
authToken, err := aauth.ParseAuthToken(tokenString)
resourceToken, err := aauth.ParseResourceToken(tokenString)

References

Index

Constants

View Source
const (
	ClaimIssuer         = "iss"
	ClaimSubject        = "sub"
	ClaimAudience       = "aud"
	ClaimExpirationTime = "exp"
	ClaimNotBefore      = "nbf"
	ClaimIssuedAt       = "iat"
	ClaimJWTID          = "jti"
)

Standard JWT claim names per RFC 7519.

View Source
const (
	// ClaimCNF is the confirmation claim for proof-of-possession keys (RFC 7800).
	ClaimCNF = "cnf"

	// ClaimActor is the actor claim for delegation chains (RFC 8693).
	ClaimActor = "act"

	// ClaimDWK is the delegate well-known URL for the agent provider.
	ClaimDWK = "dwk"

	// ClaimAgentJKT is the JWK thumbprint of the agent's key.
	ClaimAgentJKT = "agent_jkt"

	// ClaimAgent is the agent identifier in a resource token.
	ClaimAgent = "agent"

	// ClaimScope is the authorized scope.
	ClaimScope = "scope"

	// ClaimMission contains mission-specific claims.
	ClaimMission = "mission"

	// ClaimPS is the person server URL.
	ClaimPS = "ps"

	// ClaimMayAct indicates the entity may act on behalf of another.
	ClaimMayAct = "may_act"
)

AAuth-specific claim names.

View Source
const (
	// CNFClaimJWK contains an embedded JWK public key.
	CNFClaimJWK = "jwk"

	// CNFClaimJKU contains a URL to a JWK Set.
	CNFClaimJKU = "jku"

	// CNFClaimKID contains a key ID for key lookup.
	CNFClaimKID = "kid"
)

CNF sub-claims for key confirmation.

View Source
const (
	// TokenTypeAgentJWT is the type for agent tokens.
	TokenTypeAgentJWT = "aa-agent+jwt"

	// TokenTypeAuthJWT is the type for authorization tokens.
	TokenTypeAuthJWT = "aa-auth+jwt"

	// TokenTypeResourceJWT is the type for resource tokens.
	TokenTypeResourceJWT = "aa-resource+jwt"
)

Token type identifiers as used in the typ header. nolint:gosec // These are token type identifiers, not credentials

View Source
const (
	// TokenTypeURIAgentJWT is the URI for agent token type in token exchange.
	TokenTypeURIAgentJWT = "urn:ietf:params:oauth:token-type:aa-agent+jwt"

	// TokenTypeURIAuthJWT is the URI for auth token type in token exchange.
	TokenTypeURIAuthJWT = "urn:ietf:params:oauth:token-type:aa-auth+jwt"

	// TokenTypeURIResourceJWT is the URI for resource token type in token exchange.
	TokenTypeURIResourceJWT = "urn:ietf:params:oauth:token-type:aa-resource+jwt"
)

Token type URIs for token exchange. nolint:gosec

View Source
const (
	// AlgorithmES256 is ECDSA using P-256 and SHA-256.
	AlgorithmES256 = "ES256"

	// AlgorithmES384 is ECDSA using P-384 and SHA-384.
	AlgorithmES384 = "ES384"

	// AlgorithmES512 is ECDSA using P-521 and SHA-512.
	AlgorithmES512 = "ES512"

	// AlgorithmRS256 is RSASSA-PKCS1-v1_5 using SHA-256.
	AlgorithmRS256 = "RS256"

	// AlgorithmRS384 is RSASSA-PKCS1-v1_5 using SHA-384.
	AlgorithmRS384 = "RS384"

	// AlgorithmRS512 is RSASSA-PKCS1-v1_5 using SHA-512.
	AlgorithmRS512 = "RS512"

	// AlgorithmPS256 is RSASSA-PSS using SHA-256.
	AlgorithmPS256 = "PS256"

	// AlgorithmPS384 is RSASSA-PSS using SHA-384.
	AlgorithmPS384 = "PS384"

	// AlgorithmPS512 is RSASSA-PSS using SHA-512.
	AlgorithmPS512 = "PS512"

	// AlgorithmEdDSA is Edwards-curve Digital Signature Algorithm.
	AlgorithmEdDSA = "EdDSA"
)

Signing algorithms supported by AAuth.

View Source
const (
	// HTTPSigAlgorithmECDSAP256SHA256 is ECDSA using P-256 and SHA-256.
	HTTPSigAlgorithmECDSAP256SHA256 = "ecdsa-p256-sha256"

	// HTTPSigAlgorithmECDSAP384SHA384 is ECDSA using P-384 and SHA-384.
	HTTPSigAlgorithmECDSAP384SHA384 = "ecdsa-p384-sha384"

	// HTTPSigAlgorithmRSAPSSSHA256 is RSASSA-PSS using SHA-256.
	HTTPSigAlgorithmRSAPSSSHA256 = "rsa-pss-sha256"

	// HTTPSigAlgorithmRSAPSSSHA384 is RSASSA-PSS using SHA-384.
	HTTPSigAlgorithmRSAPSSSHA384 = "rsa-pss-sha384"

	// HTTPSigAlgorithmRSAPSSSHA512 is RSASSA-PSS using SHA-512.
	HTTPSigAlgorithmRSAPSSSHA512 = "rsa-pss-sha512"

	// HTTPSigAlgorithmRSAv15SHA256 is RSASSA-PKCS1-v1_5 using SHA-256.
	HTTPSigAlgorithmRSAv15SHA256 = "rsa-v1_5-sha256"

	// HTTPSigAlgorithmEdDSA is Ed25519.
	HTTPSigAlgorithmEdDSA = "ed25519"
)

HTTP signature algorithms per RFC 9421.

View Source
const (
	// WellKnownAgentPath is the path for agent provider metadata.
	WellKnownAgentPath = "/.well-known/aauth-agent.json"

	// WellKnownResourcePath is the path for resource metadata.
	WellKnownResourcePath = "/.well-known/aauth-resource.json"

	// WellKnownPersonPath is the path for person server metadata.
	WellKnownPersonPath = "/.well-known/aauth-person.json"

	// WellKnownAccessPath is the path for access server metadata.
	WellKnownAccessPath = "/.well-known/aauth-access.json"
)

Well-known metadata paths.

View Source
const (
	// HeaderAuthorization is the standard Authorization header.
	HeaderAuthorization = "Authorization"

	// HeaderSignature is the HTTP Message Signatures header (RFC 9421).
	HeaderSignature = "Signature"

	// HeaderSignatureInput is the signature parameters header (RFC 9421).
	HeaderSignatureInput = "Signature-Input"

	// HeaderSignatureKey is the AAuth signature key header.
	HeaderSignatureKey = "Signature-Key"

	// HeaderContentDigest is the content digest header (RFC 9530).
	HeaderContentDigest = "Content-Digest"

	// HeaderWWWAuthenticate is the WWW-Authenticate challenge header.
	HeaderWWWAuthenticate = "WWW-Authenticate"
)

HTTP headers used in AAuth.

View Source
const (
	// ErrorInvalidRequest indicates the request is missing a required parameter
	// or includes an invalid parameter.
	ErrorInvalidRequest = "invalid_request"

	// ErrorInvalidGrant indicates the provided grant is invalid, expired, or revoked.
	ErrorInvalidGrant = "invalid_grant"

	// ErrorInvalidSignature indicates the HTTP signature verification failed.
	ErrorInvalidSignature = "invalid_signature"

	// ErrorInvalidScope indicates the requested scope is invalid or unknown.
	ErrorInvalidScope = "invalid_scope"

	// ErrorUnauthorizedClient indicates the client is not authorized.
	ErrorUnauthorizedClient = "unauthorized_client"

	// ErrorUnsupportedGrantType indicates the grant type is not supported.
	ErrorUnsupportedGrantType = "unsupported_grant_type"

	// ErrorServerError indicates an internal server error.
	ErrorServerError = "server_error"

	// ErrorTemporarilyUnavailable indicates the server is temporarily unavailable.
	ErrorTemporarilyUnavailable = "temporarily_unavailable"
)

OAuth/protocol error codes as defined in the AAuth specification.

View Source
const (
	// WellKnownOAuthPath is the path for OAuth authorization server metadata.
	WellKnownOAuthPath = "/.well-known/oauth-authorization-server"

	// WellKnownJWKSPath is the path for JWKS.
	WellKnownJWKSPath = "/.well-known/jwks.json"
)

Additional well-known paths not defined in claims.go.

View Source
const (
	// AAuthScheme is the URI scheme for AAuth identifiers.
	AAuthScheme = "aauth"
)
View Source
const (
	// GrantTypeRefreshToken is the standard OAuth 2.0 refresh token grant.
	GrantTypeRefreshToken = "refresh_token"
)

Grant types for token refresh.

View Source
const (
	// GrantTypeTokenExchange is the RFC 8693 token exchange grant type.
	GrantTypeTokenExchange = "urn:ietf:params:oauth:grant-type:token-exchange"
)

Grant types for token exchange. nolint:gosec

View Source
const (
	// SignatureKeySchemeJWT indicates the key is provided as a JWT.
	SignatureKeySchemeJWT = "jwt"
)

Signature-Key scheme values.

Variables

View Source
var (
	// ErrAttestationFailed indicates attestation verification failed.
	ErrAttestationFailed = errors.New("attestation verification failed")

	// ErrUnsupportedAttestationType indicates an unsupported attestation type.
	ErrUnsupportedAttestationType = errors.New("unsupported attestation type")

	// ErrAttestationExpired indicates the attestation evidence has expired.
	ErrAttestationExpired = errors.New("attestation evidence expired")

	// ErrInvalidAttestationChain indicates the certificate chain is invalid.
	ErrInvalidAttestationChain = errors.New("invalid attestation certificate chain")

	// ErrPlatformNotSupported indicates the platform doesn't support attestation.
	ErrPlatformNotSupported = errors.New("platform attestation not supported")
)

Attestation errors.

View Source
var (
	// ErrConsentPending indicates consent is still pending approval.
	ErrConsentPending = errors.New("consent pending")

	// ErrConsentDenied indicates consent was denied by the user.
	ErrConsentDenied = errors.New("consent denied")

	// ErrConsentExpired indicates the consent request has expired.
	ErrConsentExpired = errors.New("consent request expired")

	// ErrConsentTimeout indicates polling timed out waiting for consent.
	ErrConsentTimeout = errors.New("consent polling timeout")
)

Deferred consent errors.

View Source
var (
	// ErrDelegationChainTooDeep indicates the delegation chain exceeds the maximum depth.
	ErrDelegationChainTooDeep = errors.New("delegation chain too deep")

	// ErrDelegationChainInvalid indicates the delegation chain is malformed.
	ErrDelegationChainInvalid = errors.New("invalid delegation chain")

	// ErrDelegationNotAuthorized indicates the delegation is not authorized.
	ErrDelegationNotAuthorized = errors.New("delegation not authorized")

	// ErrNoRouteFound indicates no route was found for the delegation request.
	ErrNoRouteFound = errors.New("no route found for delegation")
)

Delegation chain errors.

View Source
var (
	// ErrInvalidAAuthID indicates an invalid AAuth identifier format.
	ErrInvalidAAuthID = errors.New("aauth: invalid aauth identifier")

	// ErrInvalidToken indicates a malformed or invalid token.
	ErrInvalidToken = errors.New("aauth: invalid token")

	// ErrTokenExpired indicates a token has expired.
	ErrTokenExpired = errors.New("aauth: token expired")

	// ErrSignatureInvalid indicates signature verification failed.
	ErrSignatureInvalid = errors.New("aauth: signature verification failed")

	// ErrKeyNotFound indicates the signing key was not found.
	ErrKeyNotFound = errors.New("aauth: signing key not found")

	// ErrMissingCNF indicates a required cnf claim is missing.
	ErrMissingCNF = errors.New("aauth: missing cnf claim")

	// ErrCNFMismatch indicates the cnf claim does not match the request signer.
	ErrCNFMismatch = errors.New("aauth: cnf mismatch with request signer")

	// ErrMissingSignature indicates a required HTTP signature is missing.
	ErrMissingSignature = errors.New("aauth: missing http signature")

	// ErrInvalidChallenge indicates an invalid WWW-Authenticate challenge.
	ErrInvalidChallenge = errors.New("aauth: invalid challenge")

	// ErrUnsupportedAlgorithm indicates an unsupported signing algorithm.
	ErrUnsupportedAlgorithm = errors.New("aauth: unsupported algorithm")

	// ErrInvalidJWK indicates an invalid or malformed JWK.
	ErrInvalidJWK = errors.New("aauth: invalid jwk")

	// ErrInvalidKey indicates an invalid or missing cryptographic key.
	ErrInvalidKey = errors.New("aauth: invalid key")

	// ErrMissingAudience indicates a required audience claim is missing.
	ErrMissingAudience = errors.New("aauth: missing audience")

	// ErrAudienceMismatch indicates the token audience does not match.
	ErrAudienceMismatch = errors.New("aauth: audience mismatch")

	// ErrDiscoveryFailed indicates metadata discovery failed.
	ErrDiscoveryFailed = errors.New("aauth: discovery failed")

	// ErrInvalidRequest indicates a malformed request.
	ErrInvalidRequest = errors.New("aauth: invalid request")

	// ErrInvalidGrant indicates an invalid grant type or token.
	ErrInvalidGrant = errors.New("aauth: invalid grant")
)

Sentinel errors for AAuth protocol operations.

View Source
var (
	// ErrMissionRejected indicates the mission proposal was rejected.
	ErrMissionRejected = errors.New("mission rejected")

	// ErrMissionExpired indicates the mission has expired.
	ErrMissionExpired = errors.New("mission expired")

	// ErrMissionPending indicates the mission is still pending approval.
	ErrMissionPending = errors.New("mission pending approval")

	// ErrPermissionDenied indicates a specific permission was denied.
	ErrPermissionDenied = errors.New("permission denied")
)

Mission governance errors.

View Source
var (
	// ErrRefreshFailed indicates the token refresh failed.
	ErrRefreshFailed = errors.New("token refresh failed")

	// ErrNoRefreshToken indicates no refresh token is available.
	ErrNoRefreshToken = errors.New("no refresh token available")

	// ErrRefreshNotSupported indicates the server doesn't support refresh.
	ErrRefreshNotSupported = errors.New("token refresh not supported")
)

Token refresh errors.

Functions

func BuildWellKnownURL

func BuildWellKnownURL(baseURL, wellKnownPath string) string

BuildWellKnownURL constructs a well-known URL from a base URL and path.

func ContextWithAgentID

func ContextWithAgentID(ctx context.Context, id *AAuthID) context.Context

ContextWithAgentID returns a new context with the agent ID.

func ContextWithAgentToken

func ContextWithAgentToken(ctx context.Context, token *AgentToken) context.Context

ContextWithAgentToken returns a new context with the agent token.

func ContextWithAuthToken

func ContextWithAuthToken(ctx context.Context, token *AuthToken) context.Context

ContextWithAuthToken returns a new context with the auth token.

func ContextWithVerificationResult

func ContextWithVerificationResult(ctx context.Context, result *RequestVerificationResult) context.Context

ContextWithVerificationResult returns a new context with the verification result.

func FlattenChain added in v0.6.0

func FlattenChain(act *Actor) []string

FlattenChain converts a nested actor claim into a flat list of subjects.

func IsDeferredConsent added in v0.6.0

func IsDeferredConsent(resp *http.Response) bool

IsDeferredConsent checks if an HTTP response indicates deferred consent.

func JWKSHandler

func JWKSHandler(jwks *JWKS) http.Handler

JWKSHandler returns an http.Handler that serves the given JWKS.

func JWKToPublicKey

func JWKToPublicKey(jwk *JWK) (crypto.PublicKey, error)

JWKToPublicKey converts a JWK to a crypto.PublicKey.

func MetadataHandler

func MetadataHandler(metadata interface{}) http.Handler

MetadataHandler returns an http.Handler that serves the given metadata as JSON.

func RequireScope

func RequireScope(rs *ResourceServer, requiredScope string) func(http.Handler) http.Handler

RequireScope returns middleware that requires a specific scope.

func ValidateDelegationChain added in v0.6.0

func ValidateDelegationChain(chain *DelegationChain, maxDepth int) error

ValidateDelegationChain validates a delegation chain for integrity.

func VerifyHandler

func VerifyHandler(rs *ResourceServer, handler http.HandlerFunc) http.HandlerFunc

VerifyHandler wraps a handler with AAuth verification. This is a convenience function for simple use cases.

func WithVerification

func WithVerification(rs *ResourceServer, handler VerifiedHandler) http.HandlerFunc

WithVerification wraps a handler to provide the verification result.

Types

type AAuthID

type AAuthID struct {
	// Local is the local part of the identifier (before @).
	// Must contain only lowercase letters, digits, hyphens, underscores,
	// plus signs, and periods. Maximum 255 characters.
	Local string

	// Domain is the domain part of the identifier (after @).
	// Must be a valid domain name.
	Domain string
}

AAuthID represents an AAuth agent identifier. The format is aauth:local@domain, for example aauth:calendar-bot@example.com.

func AgentIDFromContext

func AgentIDFromContext(ctx context.Context) (*AAuthID, bool)

AgentIDFromContext retrieves the agent ID from the context.

func NewAAuthID

func NewAAuthID(local, domain string) (*AAuthID, error)

NewAAuthID creates a new AAuthID from local and domain parts. Returns an error if either part is invalid.

func ParseAAuthID

func ParseAAuthID(uri string) (*AAuthID, error)

ParseAAuthID parses an AAuth identifier string into an AAuthID. The expected format is "aauth:local@domain".

func (*AAuthID) AgentProviderURL

func (id *AAuthID) AgentProviderURL() string

AgentProviderURL returns the presumed agent provider URL for this identity. The URL is https://{domain}/.well-known/aauth-agent.json.

func (*AAuthID) Equals

func (id *AAuthID) Equals(other *AAuthID) bool

Equals returns true if two AAuthIDs are equal.

func (*AAuthID) String

func (id *AAuthID) String() string

String returns the full AAuth URI string (e.g., "aauth:calendar-bot@example.com").

type AccessServerMetadata

type AccessServerMetadata = AuthServerMetadata

AccessServerMetadata represents the .well-known/oauth-authorization-server metadata. This follows the standard OAuth 2.0 Authorization Server Metadata format.

type Actor

type Actor struct {
	// Subject is the subject of the actor.
	Subject string `json:"sub"`

	// Issuer is the issuer of the actor's identity.
	Issuer string `json:"iss,omitempty"`

	// Actor is a nested actor for multi-level delegation.
	Actor *Actor `json:"act,omitempty"`
}

Actor represents an actor in a delegation chain (RFC 8693).

func ExtendChain added in v0.6.0

func ExtendChain(current *Actor, newActorSubject string, newActorIssuer string) *Actor

ExtendChain creates a new actor claim that extends the delegation chain.

type AdaptiveComponentSelector added in v0.6.0

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

AdaptiveComponentSelector selects signature components based on request characteristics.

func NewAdaptiveComponentSelector added in v0.6.0

func NewAdaptiveComponentSelector(config *AdaptiveSignatureConfig) *AdaptiveComponentSelector

NewAdaptiveComponentSelector creates a new adaptive component selector.

func (*AdaptiveComponentSelector) SelectComponents added in v0.6.0

func (s *AdaptiveComponentSelector) SelectComponents(req *http.Request) []string

SelectComponents selects the appropriate signature components for a request.

type AdaptiveSignatureConfig added in v0.6.0

type AdaptiveSignatureConfig struct {
	// BaseComponents are always included in signatures.
	BaseComponents []string

	// ContentComponents are added when the request has a body.
	ContentComponents []string

	// AuthComponents are added when the request has authorization headers.
	AuthComponents []string

	// PathRules map path patterns to additional components.
	PathRules map[string][]string

	// MethodRules map HTTP methods to additional components.
	MethodRules map[string][]string

	// HeaderRules specify headers that should be signed if present.
	HeaderRules []string

	// MinComponents is the minimum number of components required.
	MinComponents int

	// MaxComponents is the maximum number of components to include.
	MaxComponents int
}

AdaptiveSignatureConfig defines rules for adaptive signature component selection. This allows agents to dynamically select which HTTP components to include in signatures based on request characteristics.

func DefaultAdaptiveConfig added in v0.6.0

func DefaultAdaptiveConfig() *AdaptiveSignatureConfig

DefaultAdaptiveConfig returns the default adaptive signature configuration.

func MinimalAdaptiveConfig added in v0.6.0

func MinimalAdaptiveConfig() *AdaptiveSignatureConfig

MinimalAdaptiveConfig returns a minimal configuration for lightweight signatures.

func StrictAdaptiveConfig added in v0.6.0

func StrictAdaptiveConfig() *AdaptiveSignatureConfig

StrictAdaptiveConfig returns a strict configuration that signs more components.

type Agent

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

Agent represents an AAuth agent with identity and signing capability.

func NewAgent

func NewAgent(id *AAuthID, privateKey crypto.PrivateKey, opts ...AgentOption) (*Agent, error)

NewAgent creates a new AAuth agent.

func (*Agent) Client

func (a *Agent) Client() *http.Client

Client returns an http.Client that automatically signs requests.

func (*Agent) CreateAgentToken

func (a *Agent) CreateAgentToken(audience ...string) (*AgentToken, error)

CreateAgentToken creates a new agent token.

func (*Agent) Do

func (a *Agent) Do(req *http.Request) (*http.Response, error)

Do sends a signed HTTP request and returns the response.

func (*Agent) GetOrCreateAgentToken

func (a *Agent) GetOrCreateAgentToken(audience ...string) (string, error)

GetOrCreateAgentToken returns a cached agent token or creates a new one. Tokens are cached until they are within 5 minutes of expiry.

func (*Agent) ID

func (a *Agent) ID() *AAuthID

ID returns the agent's AAuth ID.

func (*Agent) KeyPair

func (a *Agent) KeyPair() *KeyPair

KeyPair returns the agent's key pair.

func (*Agent) SignAgentToken

func (a *Agent) SignAgentToken(audience ...string) (string, error)

SignAgentToken creates and signs an agent token.

func (*Agent) SignRequest

func (a *Agent) SignRequest(req *http.Request) error

SignRequest signs an HTTP request with HTTP Message Signatures. This adds the Signature and Signature-Input headers.

func (*Agent) SignedRequest

func (a *Agent) SignedRequest(ctx context.Context, method, url string, body io.Reader) (*http.Request, error)

SignedRequest creates a new signed HTTP request.

func (*Agent) Transport

func (a *Agent) Transport() http.RoundTripper

Transport returns an http.RoundTripper that automatically signs requests.

type AgentOption

type AgentOption func(*agentOptions)

AgentOption configures an Agent.

func WithAgentProviderURL

func WithAgentProviderURL(url string) AgentOption

WithAgentProviderURL sets the agent provider URL (for DWK claim).

func WithCoveredComponents

func WithCoveredComponents(components []string) AgentOption

WithCoveredComponents sets the HTTP signature covered components.

func WithHTTPClient

func WithHTTPClient(client *http.Client) AgentOption

WithHTTPClient sets a custom HTTP client for the agent.

func WithNonce

func WithNonce(include bool) AgentOption

WithNonce enables or disables nonce in HTTP signatures.

func WithPersonServerURL

func WithPersonServerURL(url string) AgentOption

WithPersonServerURL sets the person server URL.

func WithSignatureLabel

func WithSignatureLabel(label string) AgentOption

WithSignatureLabel sets the HTTP signature label.

func WithSigningMethod

func WithSigningMethod(method jwt.SigningMethod) AgentOption

WithSigningMethod sets the JWT signing method.

func WithTokenTTL

func WithTokenTTL(ttl time.Duration) AgentOption

WithTokenTTL sets the TTL for generated tokens.

type AgentProviderMetadata

type AgentProviderMetadata struct {
	// AgentProvider is the Agent Provider URL.
	AgentProvider string `json:"agent_provider"`

	// JWKSURI is the URL to the Agent Provider's JWKS.
	JWKSURI string `json:"jwks_uri,omitempty"`

	// RegistrationEndpoint is the agent registration endpoint.
	RegistrationEndpoint string `json:"registration_endpoint,omitempty"`

	// DelegationEndpoint is the delegation endpoint for human-to-agent delegation.
	DelegationEndpoint string `json:"delegation_endpoint,omitempty"`

	// SigningAlgorithmsSupported lists supported signing algorithms.
	SigningAlgorithmsSupported []string `json:"signing_algs_supported,omitempty"`

	// AgentIDFormats lists supported agent ID formats.
	AgentIDFormats []string `json:"agent_id_formats_supported,omitempty"`

	// KeyTypesSupported lists supported key types.
	KeyTypesSupported []string `json:"key_types_supported,omitempty"`
}

AgentProviderMetadata represents the .well-known/aauth-agent-provider.json metadata. This metadata is served by Agent Providers to help clients discover agent capabilities.

func ParseAgentProviderMetadata

func ParseAgentProviderMetadata(data []byte) (*AgentProviderMetadata, error)

ParseAgentProviderMetadata parses agent provider metadata from JSON.

type AgentToken

type AgentToken struct {
	// Issuer is the agent provider URL.
	Issuer string `json:"iss"`

	// Subject is the AAuth ID of the agent (e.g., "aauth:calendar-bot@example.com").
	Subject string `json:"sub"`

	// Audience is the intended audience (typically the resource URL).
	Audience []string `json:"aud,omitempty"`

	// IssuedAt is when the token was issued.
	IssuedAt time.Time `json:"iat"`

	// ExpiresAt is when the token expires.
	ExpiresAt time.Time `json:"exp"`

	// JWTID is a unique identifier for the token.
	JWTID string `json:"jti,omitempty"`

	// CNF is the confirmation claim binding the token to a key (required).
	CNF *CNF `json:"cnf"`

	// DWK is the delegate well-known URL for the agent provider.
	DWK string `json:"dwk,omitempty"`

	// PS is the person server URL (optional).
	PS string `json:"ps,omitempty"`

	// Actor represents a delegation chain (optional).
	Actor *Actor `json:"act,omitempty"`

	// Claims contains any additional custom claims.
	Claims map[string]any `json:"-"`
}

AgentToken represents an aa-agent+jwt token. This token proves the identity of an agent and binds it to a cryptographic key.

func AgentTokenFromContext

func AgentTokenFromContext(ctx context.Context) (*AgentToken, bool)

AgentTokenFromContext retrieves the agent token from the context.

func NewAgentToken

func NewAgentToken(issuer, subject string, cnf *CNF, ttl time.Duration) *AgentToken

NewAgentToken creates a new agent token with the required fields.

func ParseAgentToken

func ParseAgentToken(tokenString string) (*AgentToken, error)

ParseAgentToken parses a JWT string into an AgentToken without verification. Use this for inspection only; always verify tokens in production.

func (*AgentToken) IsExpired

func (t *AgentToken) IsExpired() bool

IsExpired returns true if the token has expired.

func (*AgentToken) Sign

func (t *AgentToken) Sign(method jwt.SigningMethod, key crypto.PrivateKey, keyID string) (string, error)

Sign creates a signed JWT string from the token.

func (*AgentToken) TimeToExpiry

func (t *AgentToken) TimeToExpiry() time.Duration

TimeToExpiry returns the time until the token expires.

func (*AgentToken) Validate

func (t *AgentToken) Validate() error

Validate checks that the token has all required fields.

func (*AgentToken) WithActor

func (t *AgentToken) WithActor(actor *Actor) *AgentToken

WithActor sets the actor for delegation.

func (*AgentToken) WithAudience

func (t *AgentToken) WithAudience(audience ...string) *AgentToken

WithAudience sets the audience for the token.

func (*AgentToken) WithClaim

func (t *AgentToken) WithClaim(name string, value any) *AgentToken

WithClaim adds a custom claim to the token.

func (*AgentToken) WithDWK

func (t *AgentToken) WithDWK(dwk string) *AgentToken

WithDWK sets the delegate well-known URL.

func (*AgentToken) WithJWTID

func (t *AgentToken) WithJWTID(jti string) *AgentToken

WithJWTID sets the JWT ID for the token.

func (*AgentToken) WithPS

func (t *AgentToken) WithPS(ps string) *AgentToken

WithPS sets the person server URL.

type AgentTokenRefresher added in v0.6.0

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

AgentTokenRefresher handles agent token refresh using the agent's signing key.

func NewAgentTokenRefresher added in v0.6.0

func NewAgentTokenRefresher(agent *Agent, tokenEndpoint string) *AgentTokenRefresher

NewAgentTokenRefresher creates a token refresher for an agent.

func (*AgentTokenRefresher) ExchangeForAuthToken added in v0.6.0

func (r *AgentTokenRefresher) ExchangeForAuthToken(ctx context.Context, audience []string, scope string) (*TokenExchangeResponse, error)

ExchangeForAuthToken exchanges the agent token for an auth token.

func (*AgentTokenRefresher) RefreshAgentToken added in v0.6.0

func (r *AgentTokenRefresher) RefreshAgentToken(audience ...string) (string, error)

RefreshAgentToken creates a fresh agent token. Unlike OAuth refresh, this creates a new signed agent token.

type AttestationCNF added in v0.6.0

type AttestationCNF struct {
	*CNF

	// Attestation is the platform attestation evidence.
	Attestation *AttestationEvidence `json:"attestation,omitempty"`
}

AttestationCNF extends the CNF claim with attestation evidence.

func NewAttestationCNF added in v0.6.0

func NewAttestationCNF(cnf *CNF, evidence *AttestationEvidence) *AttestationCNF

NewAttestationCNF creates a CNF with attestation evidence.

type AttestationEvidence added in v0.6.0

type AttestationEvidence struct {
	// Type identifies the attestation mechanism.
	Type AttestationType `json:"type"`

	// Timestamp is when the attestation was created.
	Timestamp time.Time `json:"timestamp"`

	// Nonce is a challenge nonce to prevent replay attacks.
	Nonce []byte `json:"nonce,omitempty"`

	// Quote is the signed attestation quote (TPM) or attestation statement.
	Quote []byte `json:"quote,omitempty"`

	// Signature is the signature over the attestation data.
	Signature []byte `json:"signature,omitempty"`

	// PublicKey is the attested public key in DER format.
	PublicKey []byte `json:"public_key,omitempty"`

	// CertificateChain is the certificate chain for verification.
	// The first certificate is the leaf (attestation key), followed by intermediates.
	CertificateChain [][]byte `json:"certificate_chain,omitempty"`

	// PlatformData contains platform-specific attestation data.
	PlatformData map[string]any `json:"platform_data,omitempty"`

	// PCRs are Platform Configuration Register values (TPM-specific).
	PCRs map[int][]byte `json:"pcrs,omitempty"`
}

AttestationEvidence contains proof of platform integrity.

func (*AttestationEvidence) Hash added in v0.6.0

func (e *AttestationEvidence) Hash() ([]byte, error)

Hash returns a SHA-256 hash of the attestation evidence.

func (*AttestationEvidence) IsExpired added in v0.6.0

func (e *AttestationEvidence) IsExpired(maxAge time.Duration) bool

IsExpired checks if the attestation evidence has expired.

func (*AttestationEvidence) Verify added in v0.6.0

func (e *AttestationEvidence) Verify() error

Verify checks the attestation evidence integrity (not trust).

type AttestationType added in v0.6.0

type AttestationType string

AttestationType identifies the type of platform attestation.

const (
	// AttestationTypeTPM is TPM 2.0 attestation.
	AttestationTypeTPM AttestationType = "tpm"

	// AttestationTypeAppleSecureEnclave is Apple Secure Enclave attestation.
	AttestationTypeAppleSecureEnclave AttestationType = "apple-secure-enclave"

	// AttestationTypeAndroidKeystore is Android Keystore attestation.
	AttestationTypeAndroidKeystore AttestationType = "android-keystore"

	// AttestationTypeAzureSGX is Azure SGX enclave attestation.
	AttestationTypeAzureSGX AttestationType = "azure-sgx"

	// AttestationTypeAWSNitro is AWS Nitro Enclave attestation.
	AttestationTypeAWSNitro AttestationType = "aws-nitro"

	// AttestationTypeSoftware is software-based attestation (for testing).
	AttestationTypeSoftware AttestationType = "software"
)

Supported attestation types.

type AttestationVerifier added in v0.6.0

type AttestationVerifier interface {
	// Verify verifies the attestation evidence.
	// It checks the signature, certificate chain, and platform-specific validation.
	Verify(ctx context.Context, evidence *AttestationEvidence, expectedNonce []byte) error

	// SupportedTypes returns the attestation types this verifier supports.
	SupportedTypes() []AttestationType
}

AttestationVerifier verifies attestation evidence.

type AttestedKeyProvider added in v0.6.0

type AttestedKeyProvider struct {
	SignatureKeyProvider
	// contains filtered or unexported fields
}

AttestedKeyProvider wraps a SignatureKeyProvider with attestation.

func NewAttestedKeyProvider added in v0.6.0

func NewAttestedKeyProvider(
	provider SignatureKeyProvider,
	attestor PlatformAttestor,
	opts ...AttestedKeyProviderOption,
) *AttestedKeyProvider

NewAttestedKeyProvider wraps a key provider with platform attestation.

func (*AttestedKeyProvider) Attest added in v0.6.0

func (p *AttestedKeyProvider) Attest(ctx context.Context, nonce []byte) (*AttestationEvidence, error)

Attest generates attestation evidence for this key provider.

func (*AttestedKeyProvider) AttestationType added in v0.6.0

func (p *AttestedKeyProvider) AttestationType() AttestationType

AttestationType returns the type of attestation.

func (*AttestedKeyProvider) CNFWithAttestation added in v0.6.0

func (p *AttestedKeyProvider) CNFWithAttestation(ctx context.Context, nonce []byte) (*AttestationCNF, error)

CNFWithAttestation returns a CNF with attestation evidence.

func (*AttestedKeyProvider) Evidence added in v0.6.0

Evidence returns the current attestation evidence.

type AttestedKeyProviderOption added in v0.6.0

type AttestedKeyProviderOption func(*AttestedKeyProvider)

AttestedKeyProviderOption configures an AttestedKeyProvider.

func WithAttestedEvidence added in v0.6.0

func WithAttestedEvidence(evidence *AttestationEvidence) AttestedKeyProviderOption

WithAttestedEvidence sets pre-computed attestation evidence.

type AuthServer

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

AuthServer handles authorization token issuance for AAuth. It implements the Person Server (PS) or Access Server (AS) role.

func NewAuthServer

func NewAuthServer(issuer string, privateKey crypto.PrivateKey, keyID string, opts ...AuthServerOption) (*AuthServer, error)

NewAuthServer creates a new authorization server.

func (*AuthServer) Handler

func (as *AuthServer) Handler() http.Handler

Handler returns an http.Handler for the token endpoint.

func (*AuthServer) IssueAuthToken

func (as *AuthServer) IssueAuthToken(agentID *AAuthID, agentCNF *CNF, audience []string, scope string) (*AuthToken, error)

IssueAuthToken creates an auth token for an authorized agent.

func (*AuthServer) Issuer

func (as *AuthServer) Issuer() string

Issuer returns the auth server issuer URL.

func (*AuthServer) KeyPair

func (as *AuthServer) KeyPair() *KeyPair

KeyPair returns the auth server's key pair.

func (*AuthServer) Metadata

func (as *AuthServer) Metadata() *AuthServerMetadata

Metadata returns the auth server metadata for discovery.

func (*AuthServer) Options

func (as *AuthServer) Options() *authServerOptions

Options returns the auth server options.

func (*AuthServer) PublicJWKS

func (as *AuthServer) PublicJWKS() (*JWKS, error)

PublicJWKS returns the public keys as a JWKS for discovery.

func (*AuthServer) ServeHTTP

func (as *AuthServer) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP implements http.Handler for the token endpoint.

func (*AuthServer) SignAuthToken

func (as *AuthServer) SignAuthToken(agentID *AAuthID, agentCNF *CNF, audience []string, scope string) (string, error)

SignAuthToken creates and signs an auth token.

func (*AuthServer) TokenEndpoint

func (as *AuthServer) TokenEndpoint() string

TokenEndpoint returns the token endpoint URL.

type AuthServerMetadata

type AuthServerMetadata struct {
	// Issuer is the authorization server's issuer identifier
	Issuer string `json:"issuer"`

	// TokenEndpoint is the URL of the token endpoint
	TokenEndpoint string `json:"token_endpoint"`

	// JWKSURI is the URL of the JSON Web Key Set document
	JWKSURI string `json:"jwks_uri"`

	// GrantTypesSupported lists the supported grant types
	GrantTypesSupported []string `json:"grant_types_supported,omitempty"`

	// TokenEndpointAuthMethodsSupported lists the client auth methods
	TokenEndpointAuthMethodsSupported []string `json:"token_endpoint_auth_methods_supported,omitempty"`

	// ScopesSupported lists the supported scopes
	ScopesSupported []string `json:"scopes_supported,omitempty"`

	// SubjectTokenTypesSupported lists supported subject_token_type values
	SubjectTokenTypesSupported []string `json:"subject_token_types_supported,omitempty"`

	// ActorTokenTypesSupported lists supported actor_token_type values
	ActorTokenTypesSupported []string `json:"actor_token_types_supported,omitempty"`
}

AuthServerMetadata represents the .well-known/oauth-authorization-server metadata.

func ParseAuthServerMetadata

func ParseAuthServerMetadata(data []byte) (*AuthServerMetadata, error)

ParseAuthServerMetadata parses auth server metadata from JSON.

type AuthServerOption

type AuthServerOption func(*authServerOptions)

AuthServerOption configures an AuthServer.

func WithAuthServerAgentJWKSURL

func WithAuthServerAgentJWKSURL(url string) AuthServerOption

WithAuthServerAgentJWKSURL sets the JWKS URL for agent token verification.

func WithAuthServerAgentTokenVerifier

func WithAuthServerAgentTokenVerifier(verifier TokenVerifier) AuthServerOption

WithAuthServerAgentTokenVerifier sets a custom agent token verifier.

func WithAuthServerAllowedAlgorithms

func WithAuthServerAllowedAlgorithms(algorithms []string) AuthServerOption

WithAuthServerAllowedAlgorithms sets the allowed verification algorithms.

func WithAuthServerClockSkew

func WithAuthServerClockSkew(skew time.Duration) AuthServerOption

WithAuthServerClockSkew sets the clock skew tolerance.

func WithAuthServerHTTPClient

func WithAuthServerHTTPClient(client *http.Client) AuthServerOption

WithAuthServerHTTPClient sets a custom HTTP client.

func WithAuthServerResourceJWKSURL

func WithAuthServerResourceJWKSURL(url string) AuthServerOption

WithAuthServerResourceJWKSURL sets the JWKS URL for resource token verification.

func WithAuthServerResourceTokenVerifier

func WithAuthServerResourceTokenVerifier(verifier TokenVerifier) AuthServerOption

WithAuthServerResourceTokenVerifier sets a custom resource token verifier.

func WithAuthServerSigningMethod

func WithAuthServerSigningMethod(method jwt.SigningMethod) AuthServerOption

WithAuthServerSigningMethod sets the signing method for auth tokens.

func WithAuthTokenTTL

func WithAuthTokenTTL(ttl time.Duration) AuthServerOption

WithAuthTokenTTL sets the default TTL for auth tokens.

func WithScopeHandler

func WithScopeHandler(handler ScopeHandler) AuthServerOption

WithScopeHandler sets the scope handler for authorization decisions.

func WithSupportedGrantTypes

func WithSupportedGrantTypes(grantTypes []string) AuthServerOption

WithSupportedGrantTypes sets the supported grant types.

func WithTokenEndpointPath

func WithTokenEndpointPath(path string) AuthServerOption

WithTokenEndpointPath sets the token endpoint path.

type AuthToken

type AuthToken struct {
	// Issuer is the authorization server (Person Server or Access Server) URL.
	Issuer string `json:"iss"`

	// Subject is the AAuth ID of the authorized agent.
	Subject string `json:"sub"`

	// Audience is the resource(s) the token authorizes access to.
	Audience []string `json:"aud"`

	// IssuedAt is when the token was issued.
	IssuedAt time.Time `json:"iat"`

	// ExpiresAt is when the token expires.
	ExpiresAt time.Time `json:"exp"`

	// JWTID is a unique identifier for the token.
	JWTID string `json:"jti,omitempty"`

	// CNF is the confirmation claim binding the token to a key (required).
	CNF *CNF `json:"cnf"`

	// Scope is the authorized scope(s).
	Scope string `json:"scope,omitempty"`

	// Actor represents the delegation chain (optional).
	Actor *Actor `json:"act,omitempty"`

	// MayAct indicates the entity may act on behalf of another.
	MayAct *Actor `json:"may_act,omitempty"`

	// Mission contains mission-related claims.
	Mission *MissionClaims `json:"mission,omitempty"`

	// InteractionType defines how the agent operates.
	InteractionType InteractionType `json:"interaction_type,omitempty"`

	// Claims contains any additional custom claims.
	Claims map[string]any `json:"-"`
}

AuthToken represents an aa-auth+jwt token. This token grants an agent authorization to access a resource.

func AuthTokenFromContext

func AuthTokenFromContext(ctx context.Context) (*AuthToken, bool)

AuthTokenFromContext retrieves the auth token from the context.

func NewAuthToken

func NewAuthToken(issuer, subject string, audience []string, cnf *CNF, ttl time.Duration) *AuthToken

NewAuthToken creates a new auth token with the required fields.

func ParseAuthToken

func ParseAuthToken(tokenString string) (*AuthToken, error)

ParseAuthToken parses a JWT string into an AuthToken without verification. Use this for inspection only; always verify tokens in production.

func (*AuthToken) HasAudience

func (t *AuthToken) HasAudience(audience string) bool

HasAudience checks if the token includes the specified audience.

func (*AuthToken) IsExpired

func (t *AuthToken) IsExpired() bool

IsExpired returns true if the token has expired.

func (*AuthToken) Sign

func (t *AuthToken) Sign(method jwt.SigningMethod, key crypto.PrivateKey, keyID string) (string, error)

Sign creates a signed JWT string from the token.

func (*AuthToken) TimeToExpiry

func (t *AuthToken) TimeToExpiry() time.Duration

TimeToExpiry returns the time until the token expires.

func (*AuthToken) Validate

func (t *AuthToken) Validate() error

Validate checks that the token has all required fields.

func (*AuthToken) WithActor

func (t *AuthToken) WithActor(actor *Actor) *AuthToken

WithActor sets the actor for delegation.

func (*AuthToken) WithClaim

func (t *AuthToken) WithClaim(name string, value any) *AuthToken

WithClaim adds a custom claim to the token.

func (*AuthToken) WithJWTID

func (t *AuthToken) WithJWTID(jti string) *AuthToken

WithJWTID sets the JWT ID for the token.

func (*AuthToken) WithMayAct

func (t *AuthToken) WithMayAct(mayAct *Actor) *AuthToken

WithMayAct sets the may_act claim.

func (*AuthToken) WithScope

func (t *AuthToken) WithScope(scope string) *AuthToken

WithScope sets the scope for the token.

type BasicAttestationVerifier added in v0.6.0

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

BasicAttestationVerifier provides basic attestation verification.

func NewBasicAttestationVerifier added in v0.6.0

func NewBasicAttestationVerifier(opts ...BasicAttestationVerifierOption) *BasicAttestationVerifier

NewBasicAttestationVerifier creates a basic attestation verifier.

func (*BasicAttestationVerifier) SupportedTypes added in v0.6.0

func (v *BasicAttestationVerifier) SupportedTypes() []AttestationType

SupportedTypes returns the supported attestation types.

func (*BasicAttestationVerifier) Verify added in v0.6.0

func (v *BasicAttestationVerifier) Verify(ctx context.Context, evidence *AttestationEvidence, expectedNonce []byte) error

Verify verifies attestation evidence.

type BasicAttestationVerifierOption added in v0.6.0

type BasicAttestationVerifierOption func(*BasicAttestationVerifier)

BasicAttestationVerifierOption configures a BasicAttestationVerifier.

func WithAttestationMaxAge added in v0.6.0

func WithAttestationMaxAge(maxAge time.Duration) BasicAttestationVerifierOption

WithAttestationMaxAge sets the maximum age of attestation evidence.

func WithSupportedAttestationTypes added in v0.6.0

func WithSupportedAttestationTypes(types ...AttestationType) BasicAttestationVerifierOption

WithSupportedAttestationTypes sets the supported attestation types.

func WithTrustedRoots added in v0.6.0

func WithTrustedRoots(roots *x509.CertPool) BasicAttestationVerifierOption

WithTrustedRoots sets the trusted root certificates.

type CNF

type CNF struct {
	// JWK contains the embedded public key (mutually exclusive with JKU/Kid).
	JWK json.RawMessage `json:"jwk,omitempty"`

	// JKU is a URL pointing to a JWK Set containing the key.
	JKU string `json:"jku,omitempty"`

	// Kid is the key ID for key lookup within a JWKS.
	Kid string `json:"kid,omitempty"`
}

CNF represents the confirmation claim for proof-of-possession (RFC 7800). It binds a token to a specific cryptographic key.

func NewCNFWithJKU

func NewCNFWithJKU(jku string, kid string) *CNF

NewCNFWithJKU creates a CNF with a JWK Set URL reference.

func NewCNFWithJWK

func NewCNFWithJWK(pub crypto.PublicKey, keyID string) (*CNF, error)

NewCNFWithJWK creates a CNF with an embedded JWK from a public key.

func (*CNF) GetJWK

func (c *CNF) GetJWK() (*JWK, error)

GetJWK extracts the JWK from the CNF if present.

func (*CNF) GetPublicKey

func (c *CNF) GetPublicKey() (crypto.PublicKey, error)

GetPublicKey extracts the public key from the CNF. This only works for embedded JWKs; JKU references require separate resolution.

func (*CNF) GetThumbprint

func (c *CNF) GetThumbprint() (string, error)

GetThumbprint computes the JWK thumbprint from the CNF.

func (*CNF) IsEmbedded

func (c *CNF) IsEmbedded() bool

IsEmbedded returns true if the CNF contains an embedded JWK.

func (*CNF) IsReference

func (c *CNF) IsReference() bool

IsReference returns true if the CNF references an external key (JKU).

type Challenge

type Challenge struct {
	// Scheme is the authentication scheme (always "AAuth").
	Scheme string

	// Realm is the protection realm.
	Realm string

	// Scope is the required scope (optional).
	Scope string

	// PersonServerURL is the person server URL (optional).
	PersonServerURL string

	// AccessServerURL is the access server URL (optional).
	AccessServerURL string

	// Error is an error code if the challenge is due to an error.
	Error string

	// ErrorDescription is a human-readable error description.
	ErrorDescription string
}

Challenge represents an AAuth WWW-Authenticate challenge.

func InsufficientScopeChallenge

func InsufficientScopeChallenge(realm, requiredScope string) *Challenge

InsufficientScopeChallenge creates a challenge for insufficient scope errors.

func InvalidSignatureChallenge

func InvalidSignatureChallenge(realm string) *Challenge

InvalidSignatureChallenge creates a challenge for invalid signature errors.

func InvalidTokenChallenge

func InvalidTokenChallenge(realm string) *Challenge

InvalidTokenChallenge creates a challenge for invalid token errors.

func NewChallenge

func NewChallenge(realm string) *Challenge

NewChallenge creates a new AAuth challenge.

func ParseChallenge

func ParseChallenge(header string) (*Challenge, error)

ParseChallenge parses a WWW-Authenticate challenge header value.

func (*Challenge) String

func (c *Challenge) String() string

String returns the challenge as a WWW-Authenticate header value.

func (*Challenge) WithAccessServer

func (c *Challenge) WithAccessServer(url string) *Challenge

WithAccessServer sets the access server URL.

func (*Challenge) WithError

func (c *Challenge) WithError(code, description string) *Challenge

WithError sets the error details.

func (*Challenge) WithPersonServer

func (c *Challenge) WithPersonServer(url string) *Challenge

WithPersonServer sets the person server URL.

func (*Challenge) WithScope

func (c *Challenge) WithScope(scope string) *Challenge

WithScope sets the required scope.

type ComponentCondition added in v0.6.0

type ComponentCondition struct {
	// Type is the condition type (method, header, path, content).
	Type string

	// Value is the value to match.
	Value string
}

ComponentCondition defines when a component is required.

type ComponentRequirement added in v0.6.0

type ComponentRequirement struct {
	// Component is the component identifier.
	Component string

	// Required indicates if the component must be present.
	Required bool

	// Conditions are conditions under which the component is required.
	Conditions []ComponentCondition
}

ComponentRequirement defines requirements for a signature component.

type ConsentAwareTransport added in v0.6.0

type ConsentAwareTransport struct {
	// Base transport to use for requests
	Base http.RoundTripper

	// Poller for handling consent polling
	Poller *ConsentPoller

	// ConsentHandler is called when user consent is required.
	// It receives the consent URI and should direct the user to approve.
	// Return nil to continue polling, or an error to abort.
	ConsentHandler func(ctx context.Context, consent *DeferredConsentResponse) error

	// AutoPoll enables automatic polling after deferred consent.
	// If false, returns ErrConsentPending and the caller must handle polling.
	AutoPoll bool
}

ConsentAwareTransport wraps an http.RoundTripper to handle deferred consent.

func (*ConsentAwareTransport) RoundTrip added in v0.6.0

func (t *ConsentAwareTransport) RoundTrip(req *http.Request) (*http.Response, error)

RoundTrip implements http.RoundTripper with deferred consent handling.

type ConsentPoller added in v0.6.0

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

ConsentPoller polls for consent approval with exponential backoff.

func NewConsentPoller added in v0.6.0

func NewConsentPoller(opts ...ConsentPollerOption) *ConsentPoller

NewConsentPoller creates a new consent poller.

func (*ConsentPoller) Poll added in v0.6.0

func (p *ConsentPoller) Poll(ctx context.Context, statusURI string, interval int) (*ConsentStatusResponse, error)

Poll polls the status URI until consent is granted, denied, or times out. Returns the final ConsentStatusResponse or an error.

type ConsentPollerOption added in v0.6.0

type ConsentPollerOption func(*ConsentPoller)

ConsentPollerOption configures a ConsentPoller.

func WithConsentHTTPClient added in v0.6.0

func WithConsentHTTPClient(client *http.Client) ConsentPollerOption

WithConsentHTTPClient sets a custom HTTP client.

func WithInitialBackoff added in v0.6.0

func WithInitialBackoff(d time.Duration) ConsentPollerOption

WithInitialBackoff sets the initial polling backoff duration.

func WithMaxBackoff added in v0.6.0

func WithMaxBackoff(d time.Duration) ConsentPollerOption

WithMaxBackoff sets the maximum polling backoff duration.

func WithMaxWaitTime added in v0.6.0

func WithMaxWaitTime(d time.Duration) ConsentPollerOption

WithMaxWaitTime sets the maximum total wait time for consent.

func WithStatusChangeCallback added in v0.6.0

func WithStatusChangeCallback(fn func(status ConsentStatus)) ConsentPollerOption

WithStatusChangeCallback sets a callback for consent status changes.

type ConsentStatus added in v0.6.0

type ConsentStatus string

ConsentStatus represents the current state of a consent request.

const (
	ConsentStatusPending  ConsentStatus = "pending"
	ConsentStatusApproved ConsentStatus = "approved"
	ConsentStatusDenied   ConsentStatus = "denied"
	ConsentStatusExpired  ConsentStatus = "expired"
)

Consent status values.

type ConsentStatusResponse added in v0.6.0

type ConsentStatusResponse struct {
	// Status is the current consent status.
	Status ConsentStatus `json:"status"`

	// AccessToken is the access token, present when status is "approved".
	AccessToken string `json:"access_token,omitempty"`

	// TokenType is the token type (usually "Bearer").
	TokenType string `json:"token_type,omitempty"`

	// ExpiresIn is the token lifetime in seconds.
	ExpiresIn int `json:"expires_in,omitempty"`

	// Scope is the granted scope.
	Scope string `json:"scope,omitempty"`

	// Error is set when status indicates failure.
	Error string `json:"error,omitempty"`

	// ErrorDescription provides more details about the error.
	ErrorDescription string `json:"error_description,omitempty"`
}

ConsentStatusResponse represents the response from polling the status URI.

type DeferredConsentError added in v0.6.0

type DeferredConsentError struct {
	Consent *DeferredConsentResponse
}

DeferredConsentError wraps a deferred consent response for manual handling.

func (*DeferredConsentError) Error added in v0.6.0

func (e *DeferredConsentError) Error() string

func (*DeferredConsentError) Is added in v0.6.0

func (e *DeferredConsentError) Is(target error) bool

Is implements errors.Is for DeferredConsentError.

type DeferredConsentResponse added in v0.6.0

type DeferredConsentResponse struct {
	// ConsentURI is the URI for the user to provide consent.
	// The agent should direct the user to this URL.
	ConsentURI string `json:"consent_uri,omitempty"`

	// StatusURI is the URI to poll for consent status.
	StatusURI string `json:"status_uri"`

	// Interval is the recommended polling interval in seconds.
	Interval int `json:"interval,omitempty"`

	// ExpiresIn is the number of seconds until the consent request expires.
	ExpiresIn int `json:"expires_in,omitempty"`

	// Message is an optional human-readable message about the consent request.
	Message string `json:"message,omitempty"`

	// Scopes are the requested scopes requiring consent.
	Scopes []string `json:"scopes,omitempty"`
}

DeferredConsentResponse represents a 202 Accepted response indicating that user consent is required before the request can proceed.

func ParseDeferredConsentResponse added in v0.6.0

func ParseDeferredConsentResponse(body []byte) (*DeferredConsentResponse, error)

ParseDeferredConsentResponse parses a 202 Accepted response body.

type DelegationChain added in v0.6.0

type DelegationChain struct {
	// Original is the original actor (usually a human).
	Original *Actor

	// Chain is the sequence of intermediate actors.
	// The first element is the first delegatee, and the last is the current agent.
	Chain []*Actor
}

DelegationChain represents a chain of delegation from the original actor through one or more intermediate agents.

func ParseDelegationChain added in v0.6.0

func ParseDelegationChain(act *Actor) *DelegationChain

ParseDelegationChain extracts the delegation chain from nested act claims.

func (*DelegationChain) AllActors added in v0.6.0

func (d *DelegationChain) AllActors() []*Actor

AllActors returns all actors in the chain, from root to current.

func (*DelegationChain) CurrentActor added in v0.6.0

func (d *DelegationChain) CurrentActor() *Actor

CurrentActor returns the current (innermost) actor.

func (*DelegationChain) Depth added in v0.6.0

func (d *DelegationChain) Depth() int

Depth returns the depth of the delegation chain.

func (*DelegationChain) RootActor added in v0.6.0

func (d *DelegationChain) RootActor() *Actor

RootActor returns the root (original) actor.

type DelegationContext added in v0.6.0

type DelegationContext struct {
	// OriginalRequest is the original HTTP request.
	OriginalRequest *http.Request

	// Chain is the current delegation chain.
	Chain *DelegationChain

	// CurrentToken is the current auth token.
	CurrentToken *AuthToken

	// Route is the matched delegation route.
	Route *DelegationRoute
}

DelegationContext holds context for a delegation operation.

type DelegationRoute added in v0.6.0

type DelegationRoute struct {
	// Pattern is the URL pattern for matching requests.
	Pattern string

	// TargetAgent is the agent to delegate to.
	TargetAgent string

	// TargetURL is the URL of the target agent.
	TargetURL string

	// Scopes are the scopes to request for this delegation.
	Scopes []string

	// MaxDepth overrides the router's default max depth for this route.
	MaxDepth int

	// PreserveChain indicates whether to preserve the existing delegation chain.
	PreserveChain bool
}

DelegationRoute defines how to route a delegation request.

type DelegationRouter added in v0.6.0

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

DelegationRouter routes requests through a delegation chain. It handles multi-agent scenarios where requests pass through multiple agents.

func NewDelegationRouter added in v0.6.0

func NewDelegationRouter(opts ...DelegationRouterOption) *DelegationRouter

NewDelegationRouter creates a new delegation router.

func (*DelegationRouter) AddRoute added in v0.6.0

func (r *DelegationRouter) AddRoute(name string, route *DelegationRoute)

AddRoute adds a delegation route.

func (*DelegationRouter) FindRoute added in v0.6.0

func (r *DelegationRouter) FindRoute(path string) *DelegationRoute

FindRoute finds a matching route for a request path.

func (*DelegationRouter) GetRoute added in v0.6.0

func (r *DelegationRouter) GetRoute(name string) *DelegationRoute

GetRoute retrieves a delegation route by name.

func (*DelegationRouter) RemoveRoute added in v0.6.0

func (r *DelegationRouter) RemoveRoute(name string)

RemoveRoute removes a delegation route.

type DelegationRouterOption added in v0.6.0

type DelegationRouterOption func(*DelegationRouter)

DelegationRouterOption configures a DelegationRouter.

func WithDelegationMaxDepth added in v0.6.0

func WithDelegationMaxDepth(depth int) DelegationRouterOption

WithDelegationMaxDepth sets the maximum delegation depth.

func WithDelegationVerifier added in v0.6.0

func WithDelegationVerifier(v TokenVerifier) DelegationRouterOption

WithDelegationVerifier sets the token verifier for validating tokens.

type DelegationValidator added in v0.6.0

type DelegationValidator struct {
	// MaxDepth is the maximum allowed delegation depth.
	MaxDepth int

	// AllowedDelegates is a map of actors to their allowed delegates.
	// If nil, all delegates are allowed.
	AllowedDelegates map[string][]string

	// RequiredScopes are scopes required for delegation.
	RequiredScopes []string
}

DelegationValidator validates delegation chains and permissions.

func NewDelegationValidator added in v0.6.0

func NewDelegationValidator(maxDepth int) *DelegationValidator

NewDelegationValidator creates a new delegation validator.

func (*DelegationValidator) AllowAllDelegates added in v0.6.0

func (v *DelegationValidator) AllowAllDelegates(delegator string)

AllowAllDelegates allows all delegates for a delegator.

func (*DelegationValidator) AllowDelegate added in v0.6.0

func (v *DelegationValidator) AllowDelegate(delegator, delegate string)

AllowDelegate adds an allowed delegate for a delegator.

func (*DelegationValidator) Validate added in v0.6.0

func (v *DelegationValidator) Validate(ctx context.Context, chain *DelegationChain) error

Validate validates a delegation chain.

type DiscoveryClient

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

DiscoveryClient fetches and caches AAuth metadata from well-known endpoints.

func NewDiscoveryClient

func NewDiscoveryClient(opts ...DiscoveryOption) *DiscoveryClient

NewDiscoveryClient creates a new discovery client.

func (*DiscoveryClient) ClearCache

func (dc *DiscoveryClient) ClearCache()

ClearCache clears the discovery cache.

func (*DiscoveryClient) CreateJWKSVerifier

func (dc *DiscoveryClient) CreateJWKSVerifier(jwksURL string) *JWKSVerifier

CreateJWKSVerifier creates a JWKS verifier for the given URL. The verifier will fetch and cache keys from the JWKS endpoint.

func (*DiscoveryClient) DiscoverAgentProvider

func (dc *DiscoveryClient) DiscoverAgentProvider(ctx context.Context, providerURL string) (*AgentProviderMetadata, error)

DiscoverAgentProvider fetches agent provider metadata.

func (*DiscoveryClient) DiscoverAuthServer

func (dc *DiscoveryClient) DiscoverAuthServer(ctx context.Context, serverURL string) (*AuthServerMetadata, error)

DiscoverAuthServer fetches authorization server metadata (OAuth 2.0 format).

func (*DiscoveryClient) DiscoverPersonServer

func (dc *DiscoveryClient) DiscoverPersonServer(ctx context.Context, serverURL string) (*PersonServerMetadata, error)

DiscoverPersonServer fetches person server metadata.

func (*DiscoveryClient) DiscoverResource

func (dc *DiscoveryClient) DiscoverResource(ctx context.Context, resourceURL string) (*ResourceMetadata, error)

DiscoverResource fetches resource metadata from a resource URL.

func (*DiscoveryClient) DiscoverResourceFlow

func (dc *DiscoveryClient) DiscoverResourceFlow(ctx context.Context, resourceURL string) (tokenEndpoint string, metadata *ResourceMetadata, err error)

DiscoverResourceFlow discovers the token exchange flow for a resource. Returns the person server or access server URL and metadata.

func (*DiscoveryClient) FetchJWKS

func (dc *DiscoveryClient) FetchJWKS(ctx context.Context, jwksURL string) (*JWKS, error)

FetchJWKS fetches a JWKS from a URL.

type DiscoveryOption

type DiscoveryOption func(*DiscoveryClient)

DiscoveryOption configures a DiscoveryClient.

func WithDiscoveryCacheTTL

func WithDiscoveryCacheTTL(ttl time.Duration) DiscoveryOption

WithDiscoveryCacheTTL sets the cache TTL.

func WithDiscoveryHTTPClient

func WithDiscoveryHTTPClient(client *http.Client) DiscoveryOption

WithDiscoveryHTTPClient sets the HTTP client.

type ExchangeClient

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

ExchangeClient performs token exchange requests against an auth server.

func NewExchangeClient

func NewExchangeClient(tokenEndpoint string, httpClient *http.Client) *ExchangeClient

NewExchangeClient creates a new token exchange client.

func (*ExchangeClient) Exchange

Exchange performs a token exchange and returns the response.

func (*ExchangeClient) ExchangeWithAgent

func (c *ExchangeClient) ExchangeWithAgent(agent *Agent, req *TokenExchangeRequest) (*TokenExchangeResponse, error)

ExchangeWithAgent performs a token exchange using an Agent for request signing.

type ExchangeFlowType

type ExchangeFlowType string

ExchangeFlowType identifies the type of token exchange flow.

const (
	// FlowResourceManaged is when the resource provides a resource token
	FlowResourceManaged ExchangeFlowType = "resource_managed"

	// FlowPSAsserted is when only the agent token is provided
	FlowPSAsserted ExchangeFlowType = "ps_asserted"

	// FlowDelegation is when there's an actor token for delegation
	FlowDelegation ExchangeFlowType = "delegation"
)

Supported exchange flow types.

func DetermineFlowType

func DetermineFlowType(req *TokenExchangeRequest) ExchangeFlowType

DetermineFlowType determines the exchange flow type from the request.

type HTTPClient

type HTTPClient interface {
	Do(req *http.Request) (*http.Response, error)
}

HTTPClient is an interface for making HTTP requests.

type HWKKeyProvider added in v0.6.0

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

HWKKeyProvider provides hardware key-backed signatures. This is an interface for TPM, HSM, or secure enclave integration.

func NewHWKKeyProvider added in v0.6.0

func NewHWKKeyProvider(keyID, algorithm string, signer crypto.Signer, opts ...HWKKeyProviderOption) (*HWKKeyProvider, error)

NewHWKKeyProvider creates a hardware key provider. The signer must be backed by secure hardware (TPM, HSM, etc.).

func (*HWKKeyProvider) Algorithm added in v0.6.0

func (p *HWKKeyProvider) Algorithm() string

Algorithm returns the signing algorithm.

func (*HWKKeyProvider) Attestation added in v0.6.0

func (p *HWKKeyProvider) Attestation() []byte

Attestation returns the hardware attestation data, if available.

func (*HWKKeyProvider) CNF added in v0.6.0

func (p *HWKKeyProvider) CNF(ctx context.Context) (*CNF, error)

CNF returns a CNF with the public key JWK.

func (*HWKKeyProvider) KeyID added in v0.6.0

func (p *HWKKeyProvider) KeyID() string

KeyID returns the key identifier.

func (*HWKKeyProvider) Mode added in v0.6.0

func (p *HWKKeyProvider) Mode() SigningMode

Mode returns SigningModeHWK.

func (*HWKKeyProvider) PublicKey added in v0.6.0

func (p *HWKKeyProvider) PublicKey(ctx context.Context) (crypto.PublicKey, error)

PublicKey returns the public key.

func (*HWKKeyProvider) Sign added in v0.6.0

func (p *HWKKeyProvider) Sign(ctx context.Context, data []byte) ([]byte, error)

Sign signs the data using the hardware-backed key.

type HWKKeyProviderOption added in v0.6.0

type HWKKeyProviderOption func(*HWKKeyProvider)

HWKKeyProviderOption configures an HWKKeyProvider.

func WithHWKAttestation added in v0.6.0

func WithHWKAttestation(attestation []byte) HWKKeyProviderOption

WithHWKAttestation sets attestation data for the hardware key.

type InteractionType added in v0.6.0

type InteractionType string

InteractionType defines how an agent interacts with resources.

const (
	// InteractionAutonomous indicates fully autonomous operation.
	InteractionAutonomous InteractionType = "autonomous"

	// InteractionSupervised indicates human supervision is active.
	InteractionSupervised InteractionType = "supervised"

	// InteractionAssisted indicates human-assisted operation.
	InteractionAssisted InteractionType = "assisted"

	// InteractionHumanInLoop indicates human approval for each action.
	InteractionHumanInLoop InteractionType = "human_in_loop"
)

Interaction types per AAuth specification.

type JKTJWTKeyProvider added in v0.6.0

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

JKTJWTKeyProvider uses JWT thumbprint for key confirmation.

func NewJKTJWTKeyProvider added in v0.6.0

func NewJKTJWTKeyProvider(keyPair *KeyPair) (*JKTJWTKeyProvider, error)

NewJKTJWTKeyProvider creates a key provider using JWK thumbprint confirmation.

func (*JKTJWTKeyProvider) Algorithm added in v0.6.0

func (p *JKTJWTKeyProvider) Algorithm() string

Algorithm returns the signing algorithm.

func (*JKTJWTKeyProvider) CNF added in v0.6.0

func (p *JKTJWTKeyProvider) CNF(ctx context.Context) (*CNF, error)

CNF returns a CNF with only the JKT (thumbprint).

func (*JKTJWTKeyProvider) KeyID added in v0.6.0

func (p *JKTJWTKeyProvider) KeyID() string

KeyID returns the key identifier (thumbprint).

func (*JKTJWTKeyProvider) Mode added in v0.6.0

func (p *JKTJWTKeyProvider) Mode() SigningMode

Mode returns SigningModeJKTJWT.

func (*JKTJWTKeyProvider) PublicKey added in v0.6.0

func (p *JKTJWTKeyProvider) PublicKey(ctx context.Context) (crypto.PublicKey, error)

PublicKey returns the public key.

func (*JKTJWTKeyProvider) Sign added in v0.6.0

func (p *JKTJWTKeyProvider) Sign(ctx context.Context, data []byte) ([]byte, error)

Sign signs the data using the private key.

func (*JKTJWTKeyProvider) Thumbprint added in v0.6.0

func (p *JKTJWTKeyProvider) Thumbprint() string

Thumbprint returns the JWK thumbprint.

type JWK

type JWK struct {
	// Key type (e.g., "EC", "RSA", "OKP")
	Kty string `json:"kty"`

	// Key ID
	Kid string `json:"kid,omitempty"`

	// Algorithm
	Alg string `json:"alg,omitempty"`

	// Key use (e.g., "sig", "enc")
	Use string `json:"use,omitempty"`

	// EC and OKP fields
	Crv string `json:"crv,omitempty"` // Curve: P-256, P-384, P-521, Ed25519
	X   string `json:"x,omitempty"`   // X coordinate (base64url)
	Y   string `json:"y,omitempty"`   // Y coordinate (base64url, EC only)

	// RSA fields
	N string `json:"n,omitempty"` // Modulus (base64url)
	E string `json:"e,omitempty"` // Exponent (base64url)
}

JWK represents a JSON Web Key (RFC 7517). This struct supports public keys only; private key fields are not included.

func ParseJWK

func ParseJWK(data []byte) (*JWK, error)

ParseJWK parses a JSON-encoded JWK.

func PublicKeyToJWK

func PublicKeyToJWK(pub crypto.PublicKey, keyID string) (*JWK, error)

PublicKeyToJWK converts a crypto.PublicKey to a JWK.

func (*JWK) Thumbprint

func (j *JWK) Thumbprint() (string, error)

Thumbprint computes the JWK thumbprint per RFC 7638. Uses SHA-256 and returns the base64url-encoded result.

func (*JWK) ToJSON

func (j *JWK) ToJSON() ([]byte, error)

ToJSON returns the JWK as a JSON-encoded byte slice.

type JWKS

type JWKS struct {
	Keys []JWK `json:"keys"`
}

JWKS represents a JSON Web Key Set.

func ParseJWKS

func ParseJWKS(data []byte) (*JWKS, error)

ParseJWKS parses a JSON-encoded JWK Set.

func (*JWKS) FindKey

func (jwks *JWKS) FindKey(kid string) *JWK

FindKey finds a key in the JWKS by key ID.

type JWKSURIKeyProvider added in v0.6.0

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

JWKSURIKeyProvider resolves keys from a remote JWKS endpoint.

func NewJWKSURIKeyProvider added in v0.6.0

func NewJWKSURIKeyProvider(keyPair *KeyPair, jwksURI string, opts ...JWKSURIKeyProviderOption) *JWKSURIKeyProvider

NewJWKSURIKeyProvider creates a key provider that references a remote JWKS.

func (*JWKSURIKeyProvider) Algorithm added in v0.6.0

func (p *JWKSURIKeyProvider) Algorithm() string

Algorithm returns the signing algorithm.

func (*JWKSURIKeyProvider) CNF added in v0.6.0

func (p *JWKSURIKeyProvider) CNF(ctx context.Context) (*CNF, error)

CNF returns a CNF with a JKU reference.

func (*JWKSURIKeyProvider) FetchJWKS added in v0.6.0

func (p *JWKSURIKeyProvider) FetchJWKS(ctx context.Context) (*JWKSet, error)

FetchJWKS fetches the JWKS from the remote URI.

func (*JWKSURIKeyProvider) FindKey added in v0.6.0

func (p *JWKSURIKeyProvider) FindKey(ctx context.Context, kid string) (*JWK, error)

FindKey finds a key by ID in the cached or fetched JWKS.

func (*JWKSURIKeyProvider) JWKSURI added in v0.6.0

func (p *JWKSURIKeyProvider) JWKSURI() string

JWKSURI returns the JWKS URI.

func (*JWKSURIKeyProvider) KeyID added in v0.6.0

func (p *JWKSURIKeyProvider) KeyID() string

KeyID returns the key identifier.

func (*JWKSURIKeyProvider) Mode added in v0.6.0

func (p *JWKSURIKeyProvider) Mode() SigningMode

Mode returns SigningModeJWKSURI.

func (*JWKSURIKeyProvider) PublicKey added in v0.6.0

func (p *JWKSURIKeyProvider) PublicKey(ctx context.Context) (crypto.PublicKey, error)

PublicKey returns the public key (local or fetched from JWKS).

func (*JWKSURIKeyProvider) Sign added in v0.6.0

func (p *JWKSURIKeyProvider) Sign(ctx context.Context, data []byte) ([]byte, error)

Sign signs the data using the private key.

type JWKSURIKeyProviderOption added in v0.6.0

type JWKSURIKeyProviderOption func(*JWKSURIKeyProvider)

JWKSURIKeyProviderOption configures a JWKSURIKeyProvider.

func WithJWKSCacheTTL added in v0.6.0

func WithJWKSCacheTTL(ttl time.Duration) JWKSURIKeyProviderOption

WithJWKSCacheTTL sets the cache TTL for fetched JWKS.

func WithJWKSHTTPClient added in v0.6.0

func WithJWKSHTTPClient(client *http.Client) JWKSURIKeyProviderOption

WithJWKSHTTPClient sets a custom HTTP client for JWKS fetching.

type JWKSVerifier

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

JWKSVerifier verifies tokens using a JWKS endpoint.

func NewJWKSVerifier

func NewJWKSVerifier(jwksURL string, opts ...TokenVerifierOption) *JWKSVerifier

NewJWKSVerifier creates a new verifier that fetches keys from a JWKS endpoint.

func (*JWKSVerifier) VerifyAgentToken

func (v *JWKSVerifier) VerifyAgentToken(ctx context.Context, tokenString string) (*AgentToken, error)

VerifyAgentToken verifies an agent token using JWKS.

func (*JWKSVerifier) VerifyAuthToken

func (v *JWKSVerifier) VerifyAuthToken(ctx context.Context, tokenString string) (*AuthToken, error)

VerifyAuthToken verifies an auth token using JWKS.

func (*JWKSVerifier) VerifyResourceToken

func (v *JWKSVerifier) VerifyResourceToken(ctx context.Context, tokenString string) (*ResourceToken, error)

VerifyResourceToken verifies a resource token using JWKS.

func (*JWKSVerifier) WithCacheTTL

func (v *JWKSVerifier) WithCacheTTL(ttl time.Duration) *JWKSVerifier

WithCacheTTL sets the cache TTL for JWKS keys.

func (*JWKSVerifier) WithHTTPClient

func (v *JWKSVerifier) WithHTTPClient(client HTTPClient) *JWKSVerifier

WithHTTPClient sets a custom HTTP client.

type JWKSet added in v0.6.0

type JWKSet struct {
	Keys []JWK `json:"keys"`
}

JWKSet represents a JSON Web Key Set.

type JWTKeyProvider added in v0.6.0

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

JWTKeyProvider provides keys using embedded JWK in the JWT (default mode).

func NewJWTKeyProvider added in v0.6.0

func NewJWTKeyProvider(keyPair *KeyPair) *JWTKeyProvider

NewJWTKeyProvider creates a key provider with an embedded JWK.

func (*JWTKeyProvider) Algorithm added in v0.6.0

func (p *JWTKeyProvider) Algorithm() string

Algorithm returns the signing algorithm.

func (*JWTKeyProvider) CNF added in v0.6.0

func (p *JWTKeyProvider) CNF(ctx context.Context) (*CNF, error)

CNF returns a CNF with an embedded JWK.

func (*JWTKeyProvider) KeyID added in v0.6.0

func (p *JWTKeyProvider) KeyID() string

KeyID returns the key identifier.

func (*JWTKeyProvider) Mode added in v0.6.0

func (p *JWTKeyProvider) Mode() SigningMode

Mode returns SigningModeJWT.

func (*JWTKeyProvider) PublicKey added in v0.6.0

func (p *JWTKeyProvider) PublicKey(ctx context.Context) (crypto.PublicKey, error)

PublicKey returns the public key.

func (*JWTKeyProvider) Sign added in v0.6.0

func (p *JWTKeyProvider) Sign(ctx context.Context, data []byte) ([]byte, error)

Sign signs the data using the private key.

type KeyPair

type KeyPair struct {
	PrivateKey crypto.PrivateKey
	PublicKey  crypto.PublicKey
	KeyID      string
	Algorithm  string
}

KeyPair holds a private/public key pair for signing.

func GenerateECDSAKeyPair

func GenerateECDSAKeyPair(keyID string, curve elliptic.Curve) (*KeyPair, error)

GenerateECDSAKeyPair generates a new ECDSA key pair. Supported curves: P-256 (default), P-384, P-521.

func GenerateEd25519KeyPair

func GenerateEd25519KeyPair(keyID string) (*KeyPair, error)

GenerateEd25519KeyPair generates a new Ed25519 key pair.

func GenerateRSAKeyPair

func GenerateRSAKeyPair(keyID string, bits int) (*KeyPair, error)

GenerateRSAKeyPair generates a new RSA key pair. Key size should be at least 2048 bits.

func (*KeyPair) HTTPSigAlgorithm

func (kp *KeyPair) HTTPSigAlgorithm() string

HTTPSigAlgorithm returns the HTTP signature algorithm for this key pair.

func (*KeyPair) MatchesCNF

func (kp *KeyPair) MatchesCNF(cnf *CNF) (bool, error)

MatchesCNF checks if this key pair matches the given CNF claim.

func (*KeyPair) Thumbprint

func (kp *KeyPair) Thumbprint() (string, error)

Thumbprint returns the JWK thumbprint of the public key.

func (*KeyPair) ToCNF

func (kp *KeyPair) ToCNF() (*CNF, error)

ToCNF creates a CNF claim from the key pair.

func (*KeyPair) ToJWK

func (kp *KeyPair) ToJWK() (*JWK, error)

ToJWK converts the public key to a JWK.

type MissionApproval added in v0.6.0

type MissionApproval struct {
	// MissionID references the approved mission proposal.
	MissionID string `json:"mission_id"`

	// Status is the approval status.
	Status MissionStatus `json:"status"`

	// ApprovedPermissions are the permissions that were granted.
	// May be a subset of the requested permissions.
	ApprovedPermissions []Permission `json:"approved_permissions,omitempty"`

	// DeniedPermissions are permissions that were explicitly denied.
	DeniedPermissions []Permission `json:"denied_permissions,omitempty"`

	// GrantedScopes are the OAuth scopes that were granted.
	GrantedScopes []string `json:"granted_scopes,omitempty"`

	// ValidUntil is when this approval expires.
	ValidUntil time.Time `json:"valid_until,omitempty"`

	// AccessToken is the token for the approved mission (if issued inline).
	AccessToken string `json:"access_token,omitempty"`

	// RefreshToken for obtaining new access tokens.
	RefreshToken string `json:"refresh_token,omitempty"`

	// Reason provides context for rejection or partial approval.
	Reason string `json:"reason,omitempty"`

	// ApprovedBy identifies who approved the mission.
	ApprovedBy string `json:"approved_by,omitempty"`

	// ApprovedAt is when the mission was approved.
	ApprovedAt time.Time `json:"approved_at,omitempty"`
}

MissionApproval represents the response to a mission proposal.

func (*MissionApproval) HasPermission added in v0.6.0

func (a *MissionApproval) HasPermission(action string, resource string) bool

HasPermission checks if a specific permission was granted.

func (*MissionApproval) IsApproved added in v0.6.0

func (a *MissionApproval) IsApproved() bool

IsApproved returns true if the mission was approved.

func (*MissionApproval) IsExpired added in v0.6.0

func (a *MissionApproval) IsExpired() bool

IsExpired returns true if the approval has expired.

func (*MissionApproval) IsRejected added in v0.6.0

func (a *MissionApproval) IsRejected() bool

IsRejected returns true if the mission was rejected.

func (*MissionApproval) MarshalJSON added in v0.6.0

func (a *MissionApproval) MarshalJSON() ([]byte, error)

MarshalJSON implements custom JSON marshaling for MissionApproval.

func (*MissionApproval) UnmarshalJSON added in v0.6.0

func (a *MissionApproval) UnmarshalJSON(data []byte) error

UnmarshalJSON implements custom JSON unmarshaling for MissionApproval.

type MissionClaims added in v0.6.0

type MissionClaims struct {
	// MissionID is the approved mission identifier.
	MissionID string `json:"mission_id,omitempty"`

	// InteractionType defines how the agent operates.
	InteractionType InteractionType `json:"interaction_type,omitempty"`

	// Permissions are the granted permissions.
	Permissions []Permission `json:"permissions,omitempty"`

	// ValidUntil is when the mission authorization expires.
	ValidUntil int64 `json:"valid_until,omitempty"`
}

MissionClaims represents mission-related claims in an AAuth token.

type MissionGovernor added in v0.6.0

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

MissionGovernor manages mission proposals and approvals.

func NewMissionGovernor added in v0.6.0

func NewMissionGovernor(missionEndpoint string, opts ...MissionGovernorOption) *MissionGovernor

NewMissionGovernor creates a new mission governor.

func (*MissionGovernor) CheckMissionStatus added in v0.6.0

func (g *MissionGovernor) CheckMissionStatus(ctx context.Context, missionID string) (*MissionApproval, error)

CheckMissionStatus checks the current status of a pending mission.

func (*MissionGovernor) CurrentApproval added in v0.6.0

func (g *MissionGovernor) CurrentApproval() *MissionApproval

CurrentApproval returns the current mission approval.

func (*MissionGovernor) HasActiveApproval added in v0.6.0

func (g *MissionGovernor) HasActiveApproval() bool

HasActiveApproval returns true if there's a valid, unexpired approval.

func (*MissionGovernor) ProposeMission added in v0.6.0

func (g *MissionGovernor) ProposeMission(ctx context.Context, proposal *MissionProposal) (*MissionApproval, error)

ProposeMission submits a mission proposal for approval.

func (*MissionGovernor) RequestPerCallPermission added in v0.6.0

func (g *MissionGovernor) RequestPerCallPermission(ctx context.Context, perm *PerCallPermission) (*PerCallApproval, error)

RequestPerCallPermission requests approval for a specific API call.

type MissionGovernorOption added in v0.6.0

type MissionGovernorOption func(*MissionGovernor)

MissionGovernorOption configures a MissionGovernor.

func WithMissionHTTPClient added in v0.6.0

func WithMissionHTTPClient(client *http.Client) MissionGovernorOption

WithMissionHTTPClient sets a custom HTTP client.

type MissionProposal added in v0.6.0

type MissionProposal struct {
	// ID is a unique identifier for this mission proposal.
	ID string `json:"id,omitempty"`

	// AgentID is the identifier of the proposing agent.
	AgentID string `json:"agent_id"`

	// Name is a human-readable name for the mission.
	Name string `json:"name"`

	// Description describes what the agent intends to do.
	Description string `json:"description,omitempty"`

	// InteractionType defines how the agent will operate.
	InteractionType InteractionType `json:"interaction_type"`

	// Permissions are the capabilities the agent is requesting.
	Permissions []Permission `json:"permissions"`

	// Duration is how long the mission should be authorized.
	Duration time.Duration `json:"duration,omitempty"`

	// ExpiresAt is when this proposal expires if not acted upon.
	ExpiresAt time.Time `json:"expires_at,omitempty"`

	// Metadata contains additional mission-specific data.
	Metadata map[string]interface{} `json:"metadata,omitempty"`
}

MissionProposal represents a request for agent authorization.

func (*MissionProposal) MarshalJSON added in v0.6.0

func (p *MissionProposal) MarshalJSON() ([]byte, error)

MarshalJSON implements custom JSON marshaling for MissionProposal.

func (*MissionProposal) UnmarshalJSON added in v0.6.0

func (p *MissionProposal) UnmarshalJSON(data []byte) error

UnmarshalJSON implements custom JSON unmarshaling for MissionProposal.

type MissionStatus added in v0.6.0

type MissionStatus string

MissionStatus represents the current state of a mission.

const (
	MissionStatusProposed MissionStatus = "proposed"
	MissionStatusApproved MissionStatus = "approved"
	MissionStatusRejected MissionStatus = "rejected"
	MissionStatusExpired  MissionStatus = "expired"
	MissionStatusActive   MissionStatus = "active"
	MissionStatusComplete MissionStatus = "complete"
)

Mission status values.

type PerCallApproval added in v0.6.0

type PerCallApproval struct {
	// RequestID correlates with the permission request.
	RequestID string `json:"request_id"`

	// Approved indicates if the call was approved.
	Approved bool `json:"approved"`

	// Reason provides context for the decision.
	Reason string `json:"reason,omitempty"`

	// OneTimeToken is a token valid only for this specific call.
	OneTimeToken string `json:"one_time_token,omitempty"`

	// ValidFor is how long the approval is valid.
	ValidFor time.Duration `json:"valid_for,omitempty"`
}

PerCallApproval represents approval for a specific API call.

type PerCallPermission added in v0.6.0

type PerCallPermission struct {
	// Method is the HTTP method.
	Method string `json:"method"`

	// Path is the request path.
	Path string `json:"path"`

	// Action is the action being performed.
	Action string `json:"action,omitempty"`

	// Justification explains why this permission is needed.
	Justification string `json:"justification,omitempty"`

	// RequestID correlates with the specific request.
	RequestID string `json:"request_id,omitempty"`
}

PerCallPermission represents a permission request for a specific API call.

type Permission added in v0.6.0

type Permission struct {
	// Resource is the resource URI this permission applies to.
	Resource string `json:"resource,omitempty"`

	// Action is the action being permitted (e.g., "read", "write", "execute").
	Action string `json:"action"`

	// Scope is the OAuth scope associated with this permission.
	Scope string `json:"scope,omitempty"`

	// Constraints are additional constraints on the permission.
	Constraints map[string]interface{} `json:"constraints,omitempty"`
}

Permission represents a specific capability or action an agent can perform.

type PersonServerMetadata

type PersonServerMetadata struct {
	// Issuer is the Person Server's issuer identifier.
	Issuer string `json:"issuer"`

	// TokenEndpoint is the URL of the token endpoint.
	TokenEndpoint string `json:"token_endpoint"`

	// JWKSURI is the URL of the JSON Web Key Set document.
	JWKSURI string `json:"jwks_uri"`

	// GrantTypesSupported lists the supported grant types.
	GrantTypesSupported []string `json:"grant_types_supported,omitempty"`

	// TokenEndpointAuthMethodsSupported lists the client auth methods.
	TokenEndpointAuthMethodsSupported []string `json:"token_endpoint_auth_methods_supported,omitempty"`

	// ScopesSupported lists the supported scopes.
	ScopesSupported []string `json:"scopes_supported,omitempty"`

	// SubjectTokenTypesSupported lists supported subject_token_type values.
	SubjectTokenTypesSupported []string `json:"subject_token_types_supported,omitempty"`

	// ActorTokenTypesSupported lists supported actor_token_type values.
	ActorTokenTypesSupported []string `json:"actor_token_types_supported,omitempty"`

	// DelegationSupported indicates if human-to-agent delegation is supported.
	DelegationSupported bool `json:"delegation_supported,omitempty"`

	// SigningAlgorithmsSupported lists supported signing algorithms.
	SigningAlgorithmsSupported []string `json:"signing_algs_supported,omitempty"`
}

PersonServerMetadata represents the .well-known/aauth-person-server.json metadata. This metadata is served by Person Servers (or Access Servers acting as PS).

func ParsePersonServerMetadata

func ParsePersonServerMetadata(data []byte) (*PersonServerMetadata, error)

ParsePersonServerMetadata parses person server metadata from JSON.

type PlatformAttestor added in v0.6.0

type PlatformAttestor interface {
	// Type returns the attestation type.
	Type() AttestationType

	// Attest generates attestation evidence for the given public key.
	// The nonce should be included in the attestation to prevent replay attacks.
	Attest(ctx context.Context, publicKey crypto.PublicKey, nonce []byte) (*AttestationEvidence, error)

	// Available returns true if this attestation mechanism is available on the current platform.
	Available() bool
}

PlatformAttestor generates attestation evidence for a platform.

type RefreshAwareTransport added in v0.6.0

type RefreshAwareTransport struct {
	// Base transport to use for requests
	Base http.RoundTripper

	// RefreshClient handles token refresh
	RefreshClient *TokenRefreshClient

	// AuthorizationHeader is the header to use for the token (default: "Authorization")
	AuthorizationHeader string

	// TokenPrefix is the prefix for the token value (default: "Bearer ")
	TokenPrefix string
}

RefreshAwareTransport wraps an http.RoundTripper to handle automatic token refresh.

func (*RefreshAwareTransport) RoundTrip added in v0.6.0

func (t *RefreshAwareTransport) RoundTrip(req *http.Request) (*http.Response, error)

RoundTrip implements http.RoundTripper with automatic token refresh.

type RefreshableToken added in v0.6.0

type RefreshableToken struct {
	// AccessToken is the current access token.
	AccessToken string

	// RefreshToken is the refresh token for obtaining new access tokens.
	RefreshToken string

	// ExpiresAt is when the access token expires.
	ExpiresAt time.Time

	// Scope is the granted scope.
	Scope string

	// TokenType is the token type (usually "Bearer").
	TokenType string
}

RefreshableToken holds an access token with refresh capability.

func (*RefreshableToken) IsExpired added in v0.6.0

func (t *RefreshableToken) IsExpired(threshold time.Duration) bool

IsExpired returns true if the access token has expired or will expire soon.

type RequestVerificationResult

type RequestVerificationResult struct {
	// AgentToken is the verified agent token.
	AgentToken *AgentToken

	// AuthToken is the verified auth token (if present).
	AuthToken *AuthToken

	// AgentID is the agent's identifier.
	AgentID *AAuthID

	// KeyID is the key ID used for signing.
	KeyID string
}

VerificationResult contains the result of request verification.

func VerificationResultFromContext

func VerificationResultFromContext(ctx context.Context) (*RequestVerificationResult, bool)

VerificationResultFromContext retrieves the verification result from the context.

type ResourceMetadata

type ResourceMetadata struct {
	// Resource is the resource URL.
	Resource string `json:"resource"`

	// JWKSURI is the URL to the resource's JWKS.
	JWKSURI string `json:"jwks_uri,omitempty"`

	// PersonServerURI is the person server URL.
	PersonServerURI string `json:"person_server_uri,omitempty"`

	// AccessServerURI is the access server URL.
	AccessServerURI string `json:"access_server_uri,omitempty"`

	// ScopesSupported lists supported scopes.
	ScopesSupported []string `json:"scopes_supported,omitempty"`

	// SigningAlgorithmsSupported lists supported signing algorithms.
	SigningAlgorithmsSupported []string `json:"signing_algs_supported,omitempty"`
}

ResourceMetadata represents the .well-known/aauth-resource.json metadata.

func ParseResourceMetadata

func ParseResourceMetadata(data []byte) (*ResourceMetadata, error)

ParseResourceMetadata parses resource metadata from JSON.

type ResourceOption

type ResourceOption func(*resourceOptions)

ResourceOption configures a ResourceServer.

func WithAgentJWKSURL

func WithAgentJWKSURL(url string) ResourceOption

WithAgentJWKSURL sets the JWKS URL for agent token verification.

func WithAgentTokenVerifier

func WithAgentTokenVerifier(verifier TokenVerifier) ResourceOption

WithAgentTokenVerifier sets a custom agent token verifier.

func WithAuthJWKSURL

func WithAuthJWKSURL(url string) ResourceOption

WithAuthJWKSURL sets the JWKS URL for auth token verification.

func WithAuthTokenVerifier

func WithAuthTokenVerifier(verifier TokenVerifier) ResourceOption

WithAuthTokenVerifier sets a custom auth token verifier.

func WithIdentityOnlyMode

func WithIdentityOnlyMode(allow bool) ResourceOption

WithIdentityOnlyMode enables identity-only mode.

func WithRequiredScope

func WithRequiredScope(scope string) ResourceOption

WithRequiredScope sets the required scope for access.

func WithResourceAccessServer

func WithResourceAccessServer(url string) ResourceOption

WithResourceAccessServer sets the access server URL.

func WithResourceAllowedAlgorithms

func WithResourceAllowedAlgorithms(algorithms []string) ResourceOption

WithResourceAllowedAlgorithms sets the allowed verification algorithms.

func WithResourceClockSkew

func WithResourceClockSkew(skew time.Duration) ResourceOption

WithResourceClockSkew sets the clock skew tolerance.

func WithResourceHTTPClient

func WithResourceHTTPClient(client *http.Client) ResourceOption

WithResourceHTTPClient sets a custom HTTP client.

func WithResourcePersonServer

func WithResourcePersonServer(url string) ResourceOption

WithResourcePersonServer sets the person server URL.

func WithResourceSigningMethod

func WithResourceSigningMethod(method jwt.SigningMethod) ResourceOption

WithResourceSigningMethod sets the signing method for resource tokens.

func WithResourceTokenTTL

func WithResourceTokenTTL(ttl time.Duration) ResourceOption

WithResourceTokenTTL sets the TTL for resource tokens.

type ResourceServer

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

ResourceServer handles AAuth authentication on the resource side.

func NewResourceServer

func NewResourceServer(url string, privateKey crypto.PrivateKey, keyID string, opts ...ResourceOption) (*ResourceServer, error)

NewResourceServer creates a new resource server.

func (*ResourceServer) Challenge

func (rs *ResourceServer) Challenge() *Challenge

Challenge returns the WWW-Authenticate challenge for this resource.

func (*ResourceServer) ChallengeHeader

func (rs *ResourceServer) ChallengeHeader() string

ChallengeHeader returns the WWW-Authenticate header value.

func (*ResourceServer) CreateTokenExchangeResponse

func (rs *ResourceServer) CreateTokenExchangeResponse(req *ResourceTokenExchangeRequest) (string, error)

CreateTokenExchangeResponse creates a resource token for exchange.

func (*ResourceServer) IssueResourceToken

func (rs *ResourceServer) IssueResourceToken(agentID *AAuthID, agentJKT string, scope string) (*ResourceToken, error)

IssueResourceToken creates a resource token for token exchange.

func (*ResourceServer) KeyPair

func (rs *ResourceServer) KeyPair() *KeyPair

KeyPair returns the resource server's key pair.

func (*ResourceServer) Metadata

func (rs *ResourceServer) Metadata() *ResourceMetadata

Metadata returns the resource metadata for discovery.

func (*ResourceServer) Middleware

func (rs *ResourceServer) Middleware(next http.Handler) http.Handler

Middleware returns HTTP middleware that enforces AAuth authentication.

func (*ResourceServer) MiddlewareFunc

func (rs *ResourceServer) MiddlewareFunc(next http.HandlerFunc) http.HandlerFunc

MiddlewareFunc returns a middleware function for use with various routers.

func (*ResourceServer) Options

func (rs *ResourceServer) Options() *resourceOptions

Options returns the resource server options.

func (*ResourceServer) PublicJWKS

func (rs *ResourceServer) PublicJWKS() (*JWKS, error)

PublicJWKS returns the public keys as a JWKS for discovery.

func (*ResourceServer) SignResourceToken

func (rs *ResourceServer) SignResourceToken(agentID *AAuthID, agentJKT string, scope string) (string, error)

SignResourceToken creates and signs a resource token.

func (*ResourceServer) URL

func (rs *ResourceServer) URL() string

URL returns the resource server URL.

func (*ResourceServer) VerifyAgentToken

func (rs *ResourceServer) VerifyAgentToken(ctx context.Context, tokenString string) (*AgentToken, error)

VerifyAgentToken verifies an agent token.

func (*ResourceServer) VerifyAuthToken

func (rs *ResourceServer) VerifyAuthToken(ctx context.Context, tokenString string) (*AuthToken, error)

VerifyAuthToken verifies an auth token.

type ResourceToken

type ResourceToken struct {
	// Issuer is the resource URL.
	Issuer string `json:"iss"`

	// Subject is the AAuth ID of the agent.
	Subject string `json:"sub"`

	// Audience is the Person Server or Access Server URL.
	Audience []string `json:"aud"`

	// IssuedAt is when the token was issued.
	IssuedAt time.Time `json:"iat"`

	// ExpiresAt is when the token expires (typically short, < 5 minutes).
	ExpiresAt time.Time `json:"exp"`

	// JWTID is a unique identifier for the token.
	JWTID string `json:"jti,omitempty"`

	// AgentJKT is the JWK thumbprint of the agent's key.
	AgentJKT string `json:"agent_jkt"`

	// Agent is the agent identifier (AAuth ID).
	Agent string `json:"agent,omitempty"`

	// Scope is the requested scope.
	Scope string `json:"scope,omitempty"`

	// DWK is the delegate well-known URL.
	DWK string `json:"dwk,omitempty"`

	// Mission contains mission-specific claims (optional).
	Mission map[string]any `json:"mission,omitempty"`

	// Claims contains any additional custom claims.
	Claims map[string]any `json:"-"`
}

ResourceToken represents an aa-resource+jwt token. This token is issued by a resource to be exchanged at an authorization server.

func NewResourceToken

func NewResourceToken(issuer, subject string, audience []string, agentJKT string, ttl time.Duration) *ResourceToken

NewResourceToken creates a new resource token with the required fields. Default TTL is 5 minutes per the AAuth spec recommendation.

func ParseResourceToken

func ParseResourceToken(tokenString string) (*ResourceToken, error)

ParseResourceToken parses a JWT string into a ResourceToken without verification. Use this for inspection only; always verify tokens in production.

func (*ResourceToken) HasAudience

func (t *ResourceToken) HasAudience(aud string) bool

HasAudience checks if the token has a specific audience.

func (*ResourceToken) IsExpired

func (t *ResourceToken) IsExpired() bool

IsExpired returns true if the token has expired.

func (*ResourceToken) Sign

func (t *ResourceToken) Sign(method jwt.SigningMethod, key crypto.PrivateKey, keyID string) (string, error)

Sign creates a signed JWT string from the token.

func (*ResourceToken) TimeToExpiry

func (t *ResourceToken) TimeToExpiry() time.Duration

TimeToExpiry returns the time until the token expires.

func (*ResourceToken) Validate

func (t *ResourceToken) Validate() error

Validate checks that the token has all required fields.

func (*ResourceToken) WithAgent

func (t *ResourceToken) WithAgent(agent string) *ResourceToken

WithAgent sets the agent identifier.

func (*ResourceToken) WithClaim

func (t *ResourceToken) WithClaim(name string, value any) *ResourceToken

WithClaim adds a custom claim to the token.

func (*ResourceToken) WithDWK

func (t *ResourceToken) WithDWK(dwk string) *ResourceToken

WithDWK sets the delegate well-known URL.

func (*ResourceToken) WithJWTID

func (t *ResourceToken) WithJWTID(jti string) *ResourceToken

WithJWTID sets the JWT ID for the token.

func (*ResourceToken) WithMission

func (t *ResourceToken) WithMission(mission map[string]any) *ResourceToken

WithMission sets mission-specific claims.

func (*ResourceToken) WithScope

func (t *ResourceToken) WithScope(scope string) *ResourceToken

WithScope sets the scope for the token.

type ResourceTokenExchangeRequest

type ResourceTokenExchangeRequest struct {
	// AgentToken is the agent's identity token.
	AgentToken *AgentToken

	// AgentJKT is the agent's JWK thumbprint.
	AgentJKT string

	// Scope is the requested scope.
	Scope string
}

ResourceTokenExchangeRequest represents a request to exchange tokens.

type ScopeHandler

type ScopeHandler func(agentID *AAuthID, requestedScope string) (grantedScope string, err error)

ScopeHandler is called to validate and potentially modify requested scopes.

type SelfAPClient added in v0.6.0

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

SelfAPClient enables an agent to act as its own Authorization Provider. This is used when an agent can self-issue tokens without requiring an external authorization server.

func NewSelfAPClient added in v0.6.0

func NewSelfAPClient(agentID *AAuthID, privateKey crypto.PrivateKey, opts ...SelfAPOption) (*SelfAPClient, error)

NewSelfAPClient creates a new self-AP client.

func (*SelfAPClient) IssueAgentToken added in v0.6.0

func (c *SelfAPClient) IssueAgentToken(ctx context.Context, audience ...string) (string, error)

IssueAgentToken creates a self-issued agent token.

func (*SelfAPClient) IssueAuthToken added in v0.6.0

func (c *SelfAPClient) IssueAuthToken(ctx context.Context, scope string, audience ...string) (string, error)

IssueAuthToken creates a self-issued authorization token. This is used when the agent can authorize itself for certain operations.

func (*SelfAPClient) IssueDelegatedToken added in v0.6.0

func (c *SelfAPClient) IssueDelegatedToken(ctx context.Context, delegateTo string, scope string, audience ...string) (string, error)

IssueDelegatedToken creates a token for delegation to another agent.

func (*SelfAPClient) IssueMissionToken added in v0.6.0

func (c *SelfAPClient) IssueMissionToken(ctx context.Context, mission *MissionClaims, audience ...string) (string, error)

IssueMissionToken creates a token with mission claims.

func (*SelfAPClient) JWKS added in v0.6.0

func (c *SelfAPClient) JWKS() (*JWKSet, error)

JWKS returns the JWK Set containing the agent's public key.

func (*SelfAPClient) Metadata added in v0.6.0

func (c *SelfAPClient) Metadata() *SelfAPMetadata

Metadata returns the self-AP metadata for well-known endpoint.

type SelfAPHandler added in v0.6.0

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

SelfAPHandler provides HTTP handlers for self-AP endpoints.

func NewSelfAPHandler added in v0.6.0

func NewSelfAPHandler(client *SelfAPClient) *SelfAPHandler

NewSelfAPHandler creates handlers for self-AP endpoints.

type SelfAPMetadata added in v0.6.0

type SelfAPMetadata struct {
	// Issuer is the issuer identifier (usually the agent's domain).
	Issuer string `json:"issuer"`

	// JWKSURI is the URL for the agent's public keys.
	JWKSURI string `json:"jwks_uri,omitempty"`

	// TokenEndpoint is where token requests should be sent (usually self).
	TokenEndpoint string `json:"token_endpoint,omitempty"`

	// SupportedGrantTypes lists supported grant types.
	SupportedGrantTypes []string `json:"grant_types_supported"`

	// SupportedScopes lists available scopes.
	SupportedScopes []string `json:"scopes_supported,omitempty"`

	// TokenEndpointAuthMethodsSupported lists supported auth methods.
	TokenEndpointAuthMethodsSupported []string `json:"token_endpoint_auth_methods_supported,omitempty"`

	// ResponseTypesSupported lists supported response types.
	ResponseTypesSupported []string `json:"response_types_supported,omitempty"`

	// SelfIssued indicates this is a self-issued AP.
	SelfIssued bool `json:"self_issued"`
}

SelfAPMetadata describes the capabilities of a self-AP.

type SelfAPOption added in v0.6.0

type SelfAPOption func(*SelfAPClient)

SelfAPOption configures a SelfAPClient.

func WithSelfAPIssuer added in v0.6.0

func WithSelfAPIssuer(issuer string) SelfAPOption

WithSelfAPIssuer sets the issuer for self-issued tokens.

func WithSelfAPMetadata added in v0.6.0

func WithSelfAPMetadata(metadata *SelfAPMetadata) SelfAPOption

WithSelfAPMetadata sets the AP metadata.

func WithSelfAPSigningMethod added in v0.6.0

func WithSelfAPSigningMethod(method jwt.SigningMethod) SelfAPOption

WithSelfAPSigningMethod sets the JWT signing method.

func WithSelfAPTokenTTL added in v0.6.0

func WithSelfAPTokenTTL(ttl time.Duration) SelfAPOption

WithSelfAPTokenTTL sets the TTL for self-issued tokens.

type SignatureKeyProvider added in v0.6.0

type SignatureKeyProvider interface {
	// Mode returns the signing mode this provider supports.
	Mode() SigningMode

	// Sign signs the given data using the provider's private key.
	Sign(ctx context.Context, data []byte) ([]byte, error)

	// PublicKey returns the public key for signature verification.
	PublicKey(ctx context.Context) (crypto.PublicKey, error)

	// CNF returns the confirmation claim for this key provider.
	// The format depends on the signing mode (embedded JWK, JKU reference, etc.).
	CNF(ctx context.Context) (*CNF, error)

	// KeyID returns the key identifier.
	KeyID() string

	// Algorithm returns the signing algorithm (e.g., "ES256", "RS256").
	Algorithm() string
}

SignatureKeyProvider resolves signing keys for different signing modes. Implementations handle key storage, retrieval, and cryptographic operations.

func KeyProviderFromKeyPair added in v0.6.0

func KeyProviderFromKeyPair(keyPair *KeyPair, mode SigningMode, opts ...any) (SignatureKeyProvider, error)

KeyProviderFromKeyPair creates the appropriate key provider based on options.

type SignaturePolicy added in v0.6.0

type SignaturePolicy struct {
	// Name is the policy name.
	Name string

	// RequiredComponents are components that must be in all signatures.
	RequiredComponents []string

	// ConditionalComponents have conditional requirements.
	ConditionalComponents []ComponentRequirement

	// MaxAge is the maximum signature age in seconds.
	MaxAge int

	// RequireNonce indicates if nonce is required.
	RequireNonce bool

	// AllowedAlgorithms are the allowed signature algorithms.
	AllowedAlgorithms []string
}

SignaturePolicy defines a policy for signature validation.

func DefaultSignaturePolicy added in v0.6.0

func DefaultSignaturePolicy() *SignaturePolicy

DefaultSignaturePolicy returns the default signature policy.

func (*SignaturePolicy) ValidateSignedComponents added in v0.6.0

func (p *SignaturePolicy) ValidateSignedComponents(components []string, req *http.Request) error

ValidateSignedComponents checks if the signed components meet the policy requirements.

type SignatureValidationError added in v0.6.0

type SignatureValidationError struct {
	Component string
	Message   string
}

SignatureValidationError represents a signature validation error.

func (*SignatureValidationError) Error added in v0.6.0

func (e *SignatureValidationError) Error() string

type SigningMode added in v0.6.0

type SigningMode string

SigningMode identifies the method used to provide and verify signing keys.

const (
	// SigningModeJWT embeds the public key as a JWK in the agent token CNF claim.
	// This is the default mode for agents with self-contained identity.
	SigningModeJWT SigningMode = "jwt"

	// SigningModeJWKSURI references a remote JWKS URL for key resolution.
	// The CNF claim contains jku (URL) and kid (key ID).
	SigningModeJWKSURI SigningMode = "jwks_uri"

	// SigningModeJKTJWT uses a JWT thumbprint for key confirmation.
	// The CNF claim contains only the jkt (JWK thumbprint).
	SigningModeJKTJWT SigningMode = "jkt-jwt"

	// SigningModeHWK indicates hardware key-backed signatures.
	// Used with TPM, HSM, or secure enclave-backed keys.
	SigningModeHWK SigningMode = "hwk"
)

Supported signing modes per AAuth specification.

type SigningTransport

type SigningTransport struct {
	// Base is the underlying transport. If nil, http.DefaultTransport is used.
	Base http.RoundTripper

	// Agent is the agent used for signing.
	Agent *Agent

	// AddAgentToken controls whether to add the agent token.
	// Default is true.
	AddAgentToken bool
}

SigningTransport wraps an existing transport with request signing.

func (*SigningTransport) RoundTrip

func (t *SigningTransport) RoundTrip(req *http.Request) (*http.Response, error)

RoundTrip implements http.RoundTripper.

type SoftwareAttestor added in v0.6.0

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

SoftwareAttestor provides software-based attestation for testing.

func NewSoftwareAttestor added in v0.6.0

func NewSoftwareAttestor(signer crypto.Signer, opts ...SoftwareAttestorOption) *SoftwareAttestor

NewSoftwareAttestor creates a software attestor for testing.

func (*SoftwareAttestor) Attest added in v0.6.0

func (a *SoftwareAttestor) Attest(ctx context.Context, publicKey crypto.PublicKey, nonce []byte) (*AttestationEvidence, error)

Attest generates software attestation evidence.

func (*SoftwareAttestor) Available added in v0.6.0

func (a *SoftwareAttestor) Available() bool

Available always returns true for software attestation.

func (*SoftwareAttestor) Type added in v0.6.0

Type returns AttestationTypeSoftware.

type SoftwareAttestorOption added in v0.6.0

type SoftwareAttestorOption func(*SoftwareAttestor)

SoftwareAttestorOption configures a SoftwareAttestor.

func WithSoftwareAttestorIssuer added in v0.6.0

func WithSoftwareAttestorIssuer(issuer string) SoftwareAttestorOption

WithSoftwareAttestorIssuer sets the issuer for software attestation.

func WithSoftwareAttestorValidity added in v0.6.0

func WithSoftwareAttestorValidity(notBefore, notAfter time.Time) SoftwareAttestorOption

WithSoftwareAttestorValidity sets the validity period.

type StaticKeyVerifier

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

StaticKeyVerifier verifies tokens using a static public key.

func NewStaticKeyVerifier

func NewStaticKeyVerifier(publicKey crypto.PublicKey, opts ...TokenVerifierOption) (*StaticKeyVerifier, error)

NewStaticKeyVerifier creates a new verifier with a static public key.

func (*StaticKeyVerifier) VerifyAgentToken

func (v *StaticKeyVerifier) VerifyAgentToken(ctx context.Context, tokenString string) (*AgentToken, error)

VerifyAgentToken verifies an agent token.

func (*StaticKeyVerifier) VerifyAuthToken

func (v *StaticKeyVerifier) VerifyAuthToken(ctx context.Context, tokenString string) (*AuthToken, error)

VerifyAuthToken verifies an auth token.

func (*StaticKeyVerifier) VerifyResourceToken

func (v *StaticKeyVerifier) VerifyResourceToken(ctx context.Context, tokenString string) (*ResourceToken, error)

VerifyResourceToken verifies a resource token.

type TPMAttestationData added in v0.6.0

type TPMAttestationData struct {
	// TPMVersion is the TPM version (e.g., "2.0").
	TPMVersion string `json:"tpm_version"`

	// Manufacturer is the TPM manufacturer ID.
	Manufacturer string `json:"manufacturer,omitempty"`

	// FirmwareVersion is the TPM firmware version.
	FirmwareVersion string `json:"firmware_version,omitempty"`

	// AttestationKeyHandle is the handle of the attestation key.
	AttestationKeyHandle uint32 `json:"ak_handle,omitempty"`

	// SigningKeyHandle is the handle of the signing key.
	SigningKeyHandle uint32 `json:"sk_handle,omitempty"`

	// PCRSelection specifies which PCRs were included in the quote.
	PCRSelection []int `json:"pcr_selection,omitempty"`

	// ClockInfo contains TPM clock information.
	ClockInfo *TPMClockInfo `json:"clock_info,omitempty"`
}

TPMAttestationData contains TPM-specific attestation information.

type TPMAttestor added in v0.6.0

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

TPMAttestor provides TPM 2.0 attestation.

func NewTPMAttestor added in v0.6.0

func NewTPMAttestor(opts ...TPMAttestorOption) *TPMAttestor

NewTPMAttestor creates a new TPM attestor.

func (*TPMAttestor) Attest added in v0.6.0

func (a *TPMAttestor) Attest(ctx context.Context, publicKey crypto.PublicKey, nonce []byte) (*AttestationEvidence, error)

Attest generates TPM attestation evidence.

func (*TPMAttestor) Available added in v0.6.0

func (a *TPMAttestor) Available() bool

Available checks if TPM is available on this platform.

func (*TPMAttestor) Type added in v0.6.0

func (a *TPMAttestor) Type() AttestationType

Type returns AttestationTypeTPM.

type TPMAttestorOption added in v0.6.0

type TPMAttestorOption func(*TPMAttestor)

TPMAttestorOption configures a TPMAttestor.

func WithTPMAKCert added in v0.6.0

func WithTPMAKCert(cert *x509.Certificate) TPMAttestorOption

WithTPMAKCert sets the attestation key certificate.

func WithTPMAKHandle added in v0.6.0

func WithTPMAKHandle(handle uint32) TPMAttestorOption

WithTPMAKHandle sets the attestation key handle.

func WithTPMDevice added in v0.6.0

func WithTPMDevice(device string) TPMAttestorOption

WithTPMDevice sets the TPM device path.

func WithTPMEKCert added in v0.6.0

func WithTPMEKCert(cert *x509.Certificate) TPMAttestorOption

WithTPMEKCert sets the endorsement key certificate.

func WithTPMSigner added in v0.6.0

func WithTPMSigner(signer crypto.Signer) TPMAttestorOption

WithTPMSigner sets the TPM-backed signer.

type TPMClockInfo added in v0.6.0

type TPMClockInfo struct {
	// Clock is the TPM clock value.
	Clock uint64 `json:"clock"`

	// ResetCount is the number of TPM resets.
	ResetCount uint32 `json:"reset_count"`

	// RestartCount is the number of TPM restarts.
	RestartCount uint32 `json:"restart_count"`

	// Safe indicates if the clock is safe (no power loss).
	Safe bool `json:"safe"`
}

TPMClockInfo contains TPM clock information for freshness verification.

type TokenErrorResponse

type TokenErrorResponse struct {
	Error            string `json:"error"`
	ErrorDescription string `json:"error_description,omitempty"`
	ErrorURI         string `json:"error_uri,omitempty"`
}

TokenErrorResponse represents an OAuth 2.0 error response.

func (*TokenErrorResponse) WriteJSON

func (e *TokenErrorResponse) WriteJSON(w http.ResponseWriter, statusCode int)

WriteJSON writes the error response as JSON.

type TokenExchangeContext

type TokenExchangeContext struct {
	// Request is the original exchange request
	Request *TokenExchangeRequest

	// AgentToken is the verified agent token (if subject is agent token)
	AgentToken *AgentToken

	// ResourceToken is the verified resource token (if present)
	ResourceToken *ResourceToken

	// ActorToken is the verified actor token (if present)
	ActorToken *AgentToken

	// AgentID is the agent's identity
	AgentID *AAuthID

	// AgentCNF is the agent's confirmation claim
	AgentCNF *CNF
}

TokenExchangeContext holds the validated context for a token exchange.

type TokenExchangeRequest

type TokenExchangeRequest struct {
	// GrantType must be "urn:ietf:params:oauth:grant-type:token-exchange"
	GrantType string `json:"grant_type"`

	// SubjectToken is the token being exchanged (agent token or resource token)
	SubjectToken string `json:"subject_token"`

	// SubjectTokenType identifies the type of subject_token
	SubjectTokenType string `json:"subject_token_type"`

	// ActorToken is the token representing the acting party (optional)
	ActorToken string `json:"actor_token,omitempty"`

	// ActorTokenType identifies the type of actor_token
	ActorTokenType string `json:"actor_token_type,omitempty"`

	// RequestedTokenType is the type of token being requested
	RequestedTokenType string `json:"requested_token_type,omitempty"`

	// Audience is the logical name of the target service
	Audience []string `json:"audience,omitempty"`

	// Scope is the desired scope of the requested token
	Scope string `json:"scope,omitempty"`

	// Resource is the URI of the target service or resource
	Resource []string `json:"resource,omitempty"`
}

TokenExchangeRequest represents a token exchange request per RFC 8693.

func NewDelegationExchangeRequest

func NewDelegationExchangeRequest(humanToken, agentToken string, audience []string, scope string) *TokenExchangeRequest

NewDelegationExchangeRequest creates a token exchange request for the delegation flow (human delegating to agent).

func NewPSAssertedExchangeRequest

func NewPSAssertedExchangeRequest(agentToken string, audience []string, scope string) *TokenExchangeRequest

NewPSAssertedExchangeRequest creates a token exchange request for the PS-asserted flow (agent presents only its identity).

func NewResourceManagedExchangeRequest

func NewResourceManagedExchangeRequest(resourceToken string, audience []string, scope string) *TokenExchangeRequest

NewResourceManagedExchangeRequest creates a token exchange request for the resource-managed flow (agent has a resource token).

func ParseTokenExchangeRequest

func ParseTokenExchangeRequest(r *http.Request) (*TokenExchangeRequest, error)

ParseTokenExchangeRequest parses a token exchange request from form values.

func (*TokenExchangeRequest) ToFormValues

func (r *TokenExchangeRequest) ToFormValues() url.Values

ToFormValues converts the request to URL form values.

func (*TokenExchangeRequest) Validate

func (r *TokenExchangeRequest) Validate() error

Validate validates the token exchange request.

type TokenExchangeResponse

type TokenExchangeResponse struct {
	// AccessToken is the issued token
	AccessToken string `json:"access_token"`

	// IssuedTokenType identifies the type of the issued token
	IssuedTokenType string `json:"issued_token_type"`

	// TokenType is the token type (usually "Bearer")
	TokenType string `json:"token_type"`

	// ExpiresIn is the lifetime in seconds
	ExpiresIn int `json:"expires_in,omitempty"`

	// Scope is the granted scope
	Scope string `json:"scope,omitempty"`

	// RefreshToken is an optional refresh token
	RefreshToken string `json:"refresh_token,omitempty"`
}

TokenExchangeResponse represents a successful token exchange response.

type TokenRefreshClient added in v0.6.0

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

TokenRefreshClient handles token refresh requests to an auth server.

func NewTokenRefreshClient added in v0.6.0

func NewTokenRefreshClient(tokenEndpoint string, opts ...TokenRefreshOption) *TokenRefreshClient

NewTokenRefreshClient creates a new token refresh client.

func (*TokenRefreshClient) CurrentToken added in v0.6.0

func (c *TokenRefreshClient) CurrentToken(ctx context.Context) (*RefreshableToken, error)

CurrentToken returns the current token, refreshing if necessary.

func (*TokenRefreshClient) HasRefreshToken added in v0.6.0

func (c *TokenRefreshClient) HasRefreshToken() bool

HasRefreshToken returns true if a refresh token is available.

func (*TokenRefreshClient) Refresh added in v0.6.0

Refresh exchanges the refresh token for new tokens.

func (*TokenRefreshClient) SetRefreshToken added in v0.6.0

func (c *TokenRefreshClient) SetRefreshToken(token string)

SetRefreshToken updates the current refresh token.

func (*TokenRefreshClient) SetToken added in v0.6.0

func (c *TokenRefreshClient) SetToken(token *RefreshableToken)

SetToken sets the current token and refresh token.

type TokenRefreshOption added in v0.6.0

type TokenRefreshOption func(*TokenRefreshClient)

TokenRefreshOption configures a TokenRefreshClient.

func WithAutoRefresh added in v0.6.0

func WithAutoRefresh(enabled bool) TokenRefreshOption

WithAutoRefresh enables automatic token refresh before expiry.

func WithRefreshHTTPClient added in v0.6.0

func WithRefreshHTTPClient(client *http.Client) TokenRefreshOption

WithRefreshHTTPClient sets a custom HTTP client.

func WithRefreshThreshold added in v0.6.0

func WithRefreshThreshold(d time.Duration) TokenRefreshOption

WithRefreshThreshold sets the threshold for proactive refresh. The token will be refreshed when it expires within this duration.

func WithTokenRefreshCallback added in v0.6.0

func WithTokenRefreshCallback(fn func(token *RefreshableToken)) TokenRefreshOption

WithTokenRefreshCallback sets a callback for when tokens are refreshed.

type TokenRefresher added in v0.6.0

type TokenRefresher interface {
	// Refresh exchanges a refresh token for new access and refresh tokens.
	Refresh(ctx context.Context) (*TokenExchangeResponse, error)

	// SetRefreshToken updates the current refresh token.
	SetRefreshToken(token string)

	// HasRefreshToken returns true if a refresh token is available.
	HasRefreshToken() bool
}

TokenRefresher handles automatic token refresh.

type TokenResponse

type TokenResponse struct {
	AccessToken     string `json:"access_token"`
	TokenType       string `json:"token_type"`
	ExpiresIn       int    `json:"expires_in,omitempty"`
	Scope           string `json:"scope,omitempty"`
	IssuedTokenType string `json:"issued_token_type,omitempty"`
}

TokenResponse represents a token exchange response.

func CreateTokenResponse

func CreateTokenResponse(token string, expiresIn time.Duration, scope string) *TokenResponse

CreateTokenResponse creates a token response with the given token.

type TokenVerifier

type TokenVerifier interface {
	// VerifyAgentToken verifies an agent token and returns the parsed token.
	VerifyAgentToken(ctx context.Context, tokenString string) (*AgentToken, error)

	// VerifyAuthToken verifies an auth token and returns the parsed token.
	VerifyAuthToken(ctx context.Context, tokenString string) (*AuthToken, error)

	// VerifyResourceToken verifies a resource token and returns the parsed token.
	VerifyResourceToken(ctx context.Context, tokenString string) (*ResourceToken, error)
}

TokenVerifier verifies AAuth tokens.

type TokenVerifierOption

type TokenVerifierOption func(*TokenVerifierOptions)

TokenVerifierOption configures a TokenVerifier.

func WithVerifierAllowedAlgorithms

func WithVerifierAllowedAlgorithms(algorithms []string) TokenVerifierOption

WithVerifierAllowedAlgorithms sets the allowed algorithms.

func WithVerifierAudience

func WithVerifierAudience(audience string) TokenVerifierOption

WithVerifierAudience sets the expected audience.

func WithVerifierClockSkew

func WithVerifierClockSkew(skew time.Duration) TokenVerifierOption

WithVerifierClockSkew sets the allowed clock skew.

func WithVerifierIssuer

func WithVerifierIssuer(issuer string) TokenVerifierOption

WithVerifierIssuer sets the expected issuer.

func WithVerifierKeyID

func WithVerifierKeyID(keyID string) TokenVerifierOption

WithVerifierKeyID sets the expected key ID.

type TokenVerifierOptions

type TokenVerifierOptions struct {
	// PublicKey is the key used for verification.
	PublicKey crypto.PublicKey

	// KeyID is the expected key ID (optional).
	KeyID string

	// Issuer is the expected issuer (optional).
	Issuer string

	// Audience is the expected audience (optional).
	Audience string

	// AllowedAlgorithms restricts which algorithms are accepted.
	AllowedAlgorithms []string

	// ClockSkew is the allowed clock skew for expiration checking.
	ClockSkew time.Duration
}

TokenVerifierOptions configures a TokenVerifier.

type VerifiedHandler

type VerifiedHandler func(w http.ResponseWriter, r *http.Request, result *RequestVerificationResult)

HandleVerified is a helper that extracts verification context.

Directories

Path Synopsis
examples
delegation command
Package main demonstrates the AAuth delegation flow.
Package main demonstrates the AAuth delegation flow.
resource-managed command
Package main demonstrates the AAuth resource-managed flow.
Package main demonstrates the AAuth resource-managed flow.
simple command
Package main demonstrates the AAuth identity-only flow.
Package main demonstrates the AAuth identity-only flow.
Package httpsig implements HTTP Message Signatures per RFC 9421.
Package httpsig implements HTTP Message Signatures per RFC 9421.
Package personserver implements the AAuth Person Server.
Package personserver implements the AAuth Person Server.

Jump to

Keyboard shortcuts

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