aicjwt

package
v0.7.1 Latest Latest
Warning

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

Go to latest
Published: Oct 3, 2026 License: Apache-2.0 Imports: 21 Imported by: 0

Documentation

Overview

Package aicjson is a reference implementation and conformance test target for draft-wei-aic-jwt-00 (AIC-JWT: JSON Web Token Profile for AI Agent Identity Certificates).

Index

Constants

View Source
const (
	MaxConcurrentMin = 1
	MaxConcurrentMax = 1024
)

MaxConcurrentMin/MaxConcurrentMax bound the max-concurrent constraint's "max" parameter (aligned with the X.509 path in pki-types, spec P1-A-29).

View Source
const (
	TypOuter                  = "aic+jwt"
	TypDA                     = "aic+da+jwt"
	TypPA                     = "aic+pa+jwt"
	ModeAuthorized            = "authorized"
	ModeRepresentative        = "representative"
	ConstraintScheme          = "varwof/constraint-v1"
	MaxLifetime               = 86400
	AllowedModeRepresentative = "representative_allowed"
	// MaxTokenSize is the hard upper bound on the serialized token size
	// (draft Section 13.7). Tokens larger than this are rejected before
	// parsing to bound CPU/memory cost.
	MaxTokenSize = 64 * 1024
	// MaxParamsSize is the maximum serialized size of a capability
	// params object (draft Section 13.7).
	MaxParamsSize = 512
)

Variables

View Source
var AllowedAlgs = map[string]bool{
	"ES256": true,
	"ES384": true,
	"ES512": true,
	"RS256": true,
	"RS384": true,
	"RS512": true,
	"PS256": true,
	"PS384": true,
	"PS512": true,
	"EdDSA": true,
}

AllowedAlgs is the full JOSE algorithm allowlist from draft Section 4.5. ES384, ES512, RS384 and RS512 are MAY-level algorithms: a conforming implementation MAY reject them, and this reference implementation does.

View Source
var BuiltinConstraintIDs = map[string]ConstraintEvaluator{
	"allowed-cidr":   evalAllowedCIDR,
	"max-concurrent": evalMaxConcurrent,
	"time-window":    evalTimeWindow,
}

BuiltinConstraintIDs maps the built-in constraint types of draft Section 7 to evaluators.

View Source
var ImplementedAlgs = map[string]bool{
	"ES256": true,
	"RS256": true,
	"PS256": true,
	"PS384": true,
	"PS512": true,
	"EdDSA": true,
}

ImplementedAlgs are the algorithms actually implemented here.

View Source
var SupportedHashAlgs = map[string]int{
	"sha-256": 32,
	"sha-384": 48,
	"sha-512": 64,
	"jkt":     32,
}

SupportedHashAlgs lists the hash_alg values implemented here. sha3-* and sm3 require golang.org/x/crypto and are intentionally not implemented in this stdlib-only reference implementation.

Functions

func AlgForPublicKey added in v0.4.0

func AlgForPublicKey(pub any) (string, error)

AlgForPublicKey derives the JOSE algorithm implied by a public key.

func BuildJWKSJSON added in v0.4.0

func BuildJWKSJSON(certs []*x509.Certificate) ([]byte, error)

BuildJWKSJSON returns the marshaled JWKS for a certificate set.

func CapToPKI

func CapToPKI(c Capability) pki.Capability

CapToPKI converts an AIC-JWT capability to the canonical github.com/varwof/types Capability (ASN.1-oriented encoding).

func CapabilitySubset

func CapabilitySubset(agent Capability, grants []Capability) bool

CapabilitySubset reports whether an agent capability is a capability-level and parameter-level subset of the principal grants (draft Section 8.2).

func CheckHeader

func CheckHeader(h Header, expectedTyp string) error

CheckHeader validates a JOSE header against the expected typ, the algorithm allowlist and the kid requirement (draft Section 11, step 2).

func EvaluateConstraints

func EvaluateConstraints(cs []Capability, ctx RequestContext, strict bool) ([]string, error)

EvaluateConstraints evaluates all constraints with AND semantics (draft Section 7). Unknown constraint types are ignored with an audit note unless strict is true. Constraint scheme values other than varwof/constraint-v1 MUST be rejected.

func JSONRawEqual

func JSONRawEqual(a, b json.RawMessage) (bool, error)

JSONRawEqual compares two raw JSON values semantically (object member order and whitespace are ignored).

func JWKThumbprint

func JWKThumbprint(j JWK) (string, error)

JWKThumbprint implements RFC 7638 for EC, RSA and OKP keys.

func JWKToPublic

func JWKToPublic(j JWK) (crypto.PublicKey, error)

JWKToPublic converts a minimal JWK back to a public key.

func KeyHashOf

func KeyHashOf(pub crypto.PublicKey, hashAlg string) (string, error)

KeyHashOf computes the binding of a public key for the given hash_alg: "jkt" uses the RFC 7638 JWK thumbprint, otherwise the SPKI hash is used.

func MatchCapabilities

func MatchCapabilities(allowed []Capability, req Capability) bool

MatchCapabilities evaluates a request capability against the allowed capabilities using the glob rules and precedence of draft Section 6.2. The highest-precedence matching rule decides; if no rule matches, the request MUST be denied.

func ParamsWithinGrant

func ParamsWithinGrant(grant, agent json.RawMessage) (bool, error)

ParamsWithinGrant reports whether agent params stay within the grant's parameter bounds (draft Section 6.3). Numeric values are bounded by the grant value (agent <= grant); non-numeric values must be equal; arrays must be subsets. Scheme-specific plugins may supply stricter comparators.

func ParseCompact

func ParseCompact(token string) ([]byte, []byte, []byte, error)

ParseCompact splits a JWS compact serialization into header, payload and signature bytes.

func SPKIHash

func SPKIHash(cert *x509.Certificate, hashAlg string) (string, error)

SPKIHash computes hash_alg(SPKI) for an X.509 certificate (draft Section 9.2).

func SPKIHashPub

func SPKIHashPub(pub crypto.PublicKey, hashAlg string) (string, error)

SPKIHashPub computes hash_alg(SPKI) directly from a public key using x509.MarshalPKIXPublicKey.

func SignCompact

func SignCompact(header, payload []byte, alg string, key crypto.Signer) (string, error)

SignCompact creates a JWS compact serialization. header and payload are raw JSON bytes; the protected header MUST contain alg and typ.

func VerifyCompact

func VerifyCompact(token, alg string, pub crypto.PublicKey) error

VerifyCompact verifies the JWS signature for alg over the compact token.

Types

type AICClaims

type AICClaims struct {
	Ver            int                  `json:"ver"`
	Principal      Principal            `json:"principal"`
	DelegationMode string               `json:"delegation_mode"`
	Capabilities   []Capability         `json:"capabilities"`
	Constraints    []Capability         `json:"constraints,omitempty"`
	ChainDepth     int                  `json:"chain_depth,omitempty"`
	MaxDepth       int                  `json:"max_depth,omitempty"`
	Extensions     map[string]Extension `json:"extensions,omitempty"`
}

AICClaims is the "aic" claim (draft Section 5.1.2).

type Actor added in v0.5.0

type Actor struct {
	Sub string `json:"sub"`
}

Actor is the RFC 8693 actor member carried on tokens issued in representative mode: the resource owner is the token subject and the agent is the actor.

type AgentKeyBinding added in v0.7.0

type AgentKeyBinding struct {
	HashAlg string `json:"hash_alg"`
	KeyHash string `json:"key_hash"`
}

AgentKeyBinding is the da.ver=3 binding of the delegation authorization to the Agent's public key (draft Section 5.2): key_hash is the unpadded base64url encoding of hash_alg(SPKI DER).

type Audience

type Audience []string

Audience accepts a JSON string or an array of strings (RFC 9068).

func (Audience) Contains

func (a Audience) Contains(v string) bool

Contains reports whether aud includes v.

func (*Audience) UnmarshalJSON

func (a *Audience) UnmarshalJSON(b []byte) error

type Capability

type Capability struct {
	Scheme string          `json:"scheme"`
	ID     string          `json:"id"`
	Params json.RawMessage `json:"params,omitempty"`
}

Capability is the unified container (draft Section 6.1), reused in aic.capabilities, aic.constraints and PA grants.

func PKIToCap

func PKIToCap(c pki.Capability) Capability

PKIToCap converts the canonical types.Capability to the AIC-JWT JSON capability (draft Section 6.1).

type CapabilityPlugin

type CapabilityPlugin func(req Capability, ctx RequestContext) error

CapabilityPlugin evaluates a request capability for a scheme. The gateway routes evaluation by schemeId (draft Section 6.1); unknown schemes MUST be rejected (fail-closed).

type Cnf

type Cnf struct {
	Jkt string `json:"jkt"`
}

Cnf is the RFC 7800 confirmation claim (jkt form).

type ConstraintEvaluator

type ConstraintEvaluator func(c Capability, ctx RequestContext) error

ConstraintEvaluator evaluates one constraint capability.

type DAClaims

type DAClaims struct {
	Ver               int              `json:"ver"`
	Iss               string           `json:"iss"`           // principal identifier (RFC 7523 issuer)
	Sub               string           `json:"sub"`           // mode-dependent grant subject (RFC 7523)
	Aud               Audience         `json:"aud"`           // intended authorization server (RFC 7523)
	Exp               int64            `json:"exp"`           // ts + requested_lifetime (RFC 7523 expiry)
	Iat               int64            `json:"iat,omitempty"` // equals ts when present
	Jti               string           `json:"jti"`           // equals nonce; replay identifier
	AgentID           string           `json:"agent_id"`
	Principal         Principal        `json:"principal"`
	Reason            Reason           `json:"reason"`
	Capabilities      []Capability     `json:"capabilities"`
	DelegationMode    string           `json:"delegation_mode"`
	Constraints       []Capability     `json:"constraints,omitempty"`
	RequestedLifetime int              `json:"requested_lifetime"`
	TS                int64            `json:"ts"`
	Nonce             string           `json:"nonce"`
	AgentKeyBinding   *AgentKeyBinding `json:"agent_key_binding,omitempty"`
}

DAClaims is the inner DA JWT payload, the JSON equivalent of DelegationAuthTBS (draft Section 5.2). Every member is required except agent_key_binding: it is REQUIRED for ver=3 and MUST be absent for ver=2 (the legacy claim set).

func ValidateDA

func ValidateDA(daToken string, opts VerifyOptions) (*DAClaims, error)

ValidateDA validates a DA JWT in isolation: header checks, required claims, signature, principal binding and nonce. It is used by the validation pipeline and by the authorization server issuance flow.

func (*DAClaims) OAuthSubject added in v0.5.0

func (d *DAClaims) OAuthSubject() string

OAuthSubject resolves the RFC 7523 grant subject for the DA's delegation mode. In representative mode the subject is the resource owner / principal; in authorized mode the agent is the authorized accessor (RFC 7523 Section 3, item 2A).

type Decision

type Decision struct {
	Permit       bool
	Actor        string // audit actor (draft Section 8.1)
	Executor     string // executing agent: outer.act.sub in representative mode, outer sub otherwise
	Principal    string // audit principal identifier
	Capabilities []Capability
	Notes        []string
}

Decision is the outcome of the validation pipeline.

func Validate

func Validate(token string, opts VerifyOptions) (*Decision, error)

Validate executes the 11-step pipeline of draft Section 11.

type DelegationPolicy

type DelegationPolicy struct {
	MaxAgents       int    `json:"max_agents"`
	AllowedMode     string `json:"allowed_mode"`
	MaxSessionHours *int   `json:"max_session_hours,omitempty"`
}

DelegationPolicy is the JSON equivalent of the ASN.1 DelegationPolicy (draft Section 5.3).

type Extension

type Extension struct {
	Critical bool            `json:"critical"`
	Value    json.RawMessage `json:"value"`
}

Extension mirrors the AICExtensions slot.

type Header struct {
	Alg  string   `json:"alg"`
	Typ  string   `json:"typ"`
	Kid  string   `json:"kid"`
	Crit []string `json:"crit,omitempty"`
	JWK  *JWK     `json:"jwk,omitempty"` // used by DPoP proofs (RFC 9449)
}

Header is the JOSE protected header shared by all AIC-JWT token types (draft Sections 4.2-4.4).

type JWK

type JWK struct {
	Kty string   `json:"kty"`
	Crv string   `json:"crv,omitempty"`
	X   string   `json:"x,omitempty"`
	Y   string   `json:"y,omitempty"`
	N   string   `json:"n,omitempty"`
	E   string   `json:"e,omitempty"`
	Kid string   `json:"kid,omitempty"`
	Use string   `json:"use,omitempty"`
	X5c []string `json:"x5c,omitempty"`
	X5t string   `json:"x5t,omitempty"`
}

JWK is an RFC 7517 public JWK supporting EC, RSA and OKP (kty/crv/x/y/n/e), plus the key-set metadata members kid/use/x5c/x5t used to bind a JWK to an X.509 certificate chain (draft Section 5).

func CertToJWK added in v0.4.0

func CertToJWK(cert *x509.Certificate) (JWK, error)

CertToJWK converts an X.509 certificate into a JWK carrying the CF identity binding: kid = SPKI hash, x5c = the certificate, x5t = SHA-256 thumbprint.

func ParseJWK

func ParseJWK(b []byte) (JWK, error)

ParseJWK decodes a JWK JSON object.

func PublicKeyToJWK

func PublicKeyToJWK(pub crypto.PublicKey) (JWK, error)

PublicKeyToJWK converts a public key to a minimal JWK.

type JWKS added in v0.4.0

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

JWKS is a JWK Key Set (RFC 7517 §5).

func BuildJWKS added in v0.4.0

func BuildJWKS(certs []*x509.Certificate) (JWKS, error)

BuildJWKS builds a JWKS from certificates; keys are deduplicated by kid.

type MemNonceStore

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

MemNonceStore is an in-memory NonceStore used for DA nonce / jti replay prevention. Suitable for single-process reference deployments; production deployments MUST use a persistent store.

func NewMemNonceStore

func NewMemNonceStore() *MemNonceStore

NewMemNonceStore creates an empty in-memory nonce store.

func (*MemNonceStore) CheckAndAdd

func (m *MemNonceStore) CheckAndAdd(nonce string) error

CheckAndAdd records the nonce, rejecting duplicates.

type NonceReuseError

type NonceReuseError struct {
	Nonce string
}

NonceReuseError reports a replayed DA nonce.

func (*NonceReuseError) Error

func (e *NonceReuseError) Error() string

type NonceStore

type NonceStore interface {
	CheckAndAdd(nonce string) error
}

NonceStore records used nonces (DA nonce / jti) for replay prevention.

type OuterClaims

type OuterClaims struct {
	Iss          string          `json:"iss"`
	Sub          string          `json:"sub"`
	Aud          Audience        `json:"aud"`
	Iat          int64           `json:"iat"`
	Exp          int64           `json:"exp"`
	Nbf          *int64          `json:"nbf,omitempty"`
	Jti          string          `json:"jti"`
	Cnf          *Cnf            `json:"cnf"`
	Scope        string          `json:"scope,omitempty"`
	ClientID     string          `json:"client_id,omitempty"`
	Status       *StatusRef      `json:"status,omitempty"`
	Aic          *AICClaims      `json:"aic"`
	Da           string          `json:"da,omitempty"`
	AuthzDetails json.RawMessage `json:"authorization_details,omitempty"`
	Act          *Actor          `json:"act,omitempty"`
}

OuterClaims is the outer AIC-JWT payload (draft Section 5.1).

type PAClaims

type PAClaims struct {
	Ver              int                  `json:"ver"`
	Principal        Principal            `json:"principal"`
	Grants           []Capability         `json:"grants"`
	Constraints      []Capability         `json:"constraints,omitempty"`
	DelegationPolicy *DelegationPolicy    `json:"delegation_policy,omitempty"`
	Extensions       map[string]Extension `json:"extensions,omitempty"`
}

PAClaims is the PA JWT payload (draft Section 5.3).

type Principal

type Principal struct {
	Realm   string `json:"realm"`
	ID      string `json:"id"`
	KeyHash string `json:"key_hash"`
	HashAlg string `json:"hash_alg"`
}

Principal is the principalUid equivalent (draft Section 5.1.2).

func (Principal) SubjectID added in v0.5.0

func (p Principal) SubjectID() string

SubjectID returns the canonical realm-qualified principal identifier used as the DA issuer and, in representative mode, as the DA and outer-token subject.

type PrincipalKeyMaterial

type PrincipalKeyMaterial struct {
	X5C []*x509.Certificate
	JWK map[string]JWK
}

PrincipalKeyMaterial is the optional credential bundle (draft Section 9). Either X5C (PKI mode) or JWK (pure-JSON mode) is used.

func (*PrincipalKeyMaterial) LookupByBinding

func (m *PrincipalKeyMaterial) LookupByBinding(p Principal) (crypto.PublicKey, error)

LookupByBinding finds a principal key whose binding matches the principal claim.

type Reason

type Reason struct {
	Code string `json:"code"`
	Desc string `json:"desc"`
}

Reason is the delegation reason (draft Section 5.2).

type RequestContext

type RequestContext struct {
	Now             time.Time
	SourceIP        netip.Addr
	ConcurrentCount int
}

RequestContext carries deployment-side inputs for constraint evaluation and capability plugins.

type StatusChecker

type StatusChecker func(ref StatusRef) error

StatusChecker validates a Token Status List reference (draft-ietf-oauth-status-list).

type StatusRef

type StatusRef struct {
	Idx int    `json:"idx"`
	URI string `json:"uri"`
}

StatusRef references a Token Status List entry (draft-ietf-oauth-status-list).

type VerifyOptions

type VerifyOptions struct {
	Now                  time.Time
	ExpectedIssuer       string
	ExpectedAudience     []string
	IssuerKeys           map[string]crypto.PublicKey // kid -> issuer public key
	PrincipalMaterial    *PrincipalKeyMaterial       // optional credential bundle
	PrincipalJWKS        map[string]crypto.PublicKey // kid -> principal public key (online)
	PresenterKey         crypto.PublicKey            // optional, for cnf proof-of-possession
	RequestCapability    *Capability                 // capability required by the current request
	RequestContext       RequestContext
	ConstraintStrict     bool
	CapabilityPlugins    map[string]CapabilityPlugin
	StatusChecker        StatusChecker
	NonceStore           NonceStore
	RejectDepthGT1       bool
	RequireJtiNonceMatch bool
	PA                   *PAClaims // optional PrincipalAuthorization material
}

VerifyOptions configures the validation pipeline.

Jump to

Keyboard shortcuts

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