aauth

package
v0.4.0 Latest Latest
Warning

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

Go to latest
Published: May 24, 2026 License: MIT Imports: 22 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 (
	// 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 (
	// 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")

	// 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.

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 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 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).

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 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"`

	// 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 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 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 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 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 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 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 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 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 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 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 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.

Jump to

Keyboard shortcuts

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