smart

package
v0.2.1 Latest Latest
Warning

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

Go to latest
Published: Sep 26, 2026 License: Apache-2.0 Imports: 26 Imported by: 0

README

haistack-smart (pkg/smart)

Optional SMART on FHIR library for HAIStack: scope parsing, token and backend-assertion validation, launch context, and adaptation into pkg/auth. It does not replace an OAuth authorization server or EHR launch UI.

What it does

pkg/smart (haistack-smart) interprets SMART scopes and JWT claims and produces auth-ready inputs—principals, tenant context, permissions, and request builders. Authorization decisions stay in pkg/auth; this package normalizes SMART semantics only.

v1 capabilities:

  • Scopes — ParseScopes, ScopeSet matching (Allows, AllowsRead, AllowsWrite) for SMART 1.x .read/.write patterns and SMART 2.2 CRUDS granular scopes with optional search-parameter filters (patient/Observation.rs?category=laboratory).
  • Launch context — BuildLaunchContext, ExtractLaunchContext, LaunchContextInput for patient, encounter, user, tenant hints (no full EHR/standalone launch orchestration).
  • Tokens — TokenValidator, ValidateToken, ValidateClaims for JWT structure, iss/aud/exp/nbf, scope extraction; optional PEMVerifier / custom signature verification.
  • Backend services — BackendServiceAuth, ValidateBackendAssertion for signed client assertions, allow-listed clients, mandatory jti replay protection, strict assertion time checks.
  • Auth bridge — AuthAdapter, ToAuthRequests, FromBackendService, ToPatientScopeRequest map SMART into auth.Principal, auth.TenantContext, and permission lists.
  • Metadata — Configuration, DefaultConfiguration(issuer) for SMART App Launch discovery document fields (hosts serve via pkg/oauth or custom HTTP).
  • Scope filters — RegistryScopeFilterMatcherChain, InstallRegistryScopeFilterMatcher integrate SearchParameter-aware filter matching with FHIRPath and search registry normalization.
  • Persistence helpers — NewFileBackendClientStore, NewFileReplayStore for single-instance backend-service deployments (not multi-instance production defaults).

Explicitly out of v1: EHR/standalone launch product flows, refresh-token lifecycle, SMART session UI, dynamic client registration product surface, and HTTP middleware as the architectural center of the package.

How it fits in the ecosystem

Layer Package Role
OAuth AS / token endpoint oauth (optional) Codes, refresh tokens, client store in SQLite/Postgres
SMART interpretation smart Scopes, launch, JWT/assertion validation, auth adapter
Authorization auth Engine checks patient scope, read/write, tenant policy
FHIR API core, http Resource handlers; optional ScopeFilterMatcher wiring
Offline/local MVP core, sync, view, ai Do not require SMART

Hosts own transport to token endpoints and AS configuration. SMART plugs in where you validate access tokens or backend assertions before calling auth.Engine.

Multi-instance SMART hosts should inject transactional BackendClientStore and ReplayStore implementations instead of JSON file stores.

When to use it

Import pkg/smart when you:

  • Accept SMART scopes on user or patient tokens and need deterministic matching before auth checks.
  • Run backend services with JWT client assertions and need assertion validation + service principal mapping.
  • Advertise SMART configuration (permission-v2, permission-v2.2, launch capabilities) consistently with what this library parses.
  • Enforce granular scope filters on search/read using registered SearchParameters.

Skip this package for purely local/offline deployments with no OAuth, or when you implement SMART entirely in another language and only pass pre-mapped roles into auth.

Usage modes

1. Parse and match scopes
scopes, err := smart.ParseScopes("patient/*.read launch/patient openid")
ok := scopes.AllowsRead(smart.ActorPatient, "Observation")
denied := scopes.AllowsWrite(smart.ActorPatient, "Observation") // patient write not in v1 patterns
2. User/patient token → auth bundle
launch := smart.BuildLaunchContext(smart.LaunchContextInput{
    PatientID:  "pat-1",
    UserID:     "Practitioner/pract-1",
    TenantHint: "tenant-a",
    Scopes:     scopes,
})
adapter := smart.NewAuthAdapter(smart.AuthAdapterConfig{
    DefaultTenantID:  "tenant-a",
    DefaultUserRoles: []string{"smart-user"},
})
bundle, err := adapter.ToAuthRequests(claims, launch)
req := adapter.ToPatientScopeRequest(bundle, "")
// eng.CheckPatientScope(ctx, req)
3. Backend service assertion → service principal
bsa, err := smart.NewBackendServiceAuth("https://auth.example/token", smart.BackendClient{
    ClientID:       "backend-app",
    AllowedScopes:  []string{"system/*.read", "system/*.write"},
    Key: smart.ClientKeyMetadata{Algorithm: "RS256", PublicKeyPEM: pubPEM},
    TenantHint:     "tenant-svc",
})
claims, client, err := bsa.ValidateBackendAssertion(assertionJWT, smart.TokenValidateOptions{})
bundle, err := adapter.FromBackendService(claims, client, smart.LaunchContext{})
// bundle.Principal.Kind == auth.KindService
4. Token validation with optional PEM verifier
tv := smart.NewTokenValidator(smart.TokenValidatorConfig{
    Issuer:   "https://auth.example",
    Audience: "https://fhir.example",
    Verifier: smart.NewPEMVerifier(pubPEM),
})
claims, err := tv.ValidateToken(rawJWT, smart.TokenValidateOptions{})
5. SMART discovery metadata
doc := smart.DefaultConfiguration("https://auth.example")
// Override AuthorizationEndpoint, TokenEndpoint, ScopesSupported for your deployment

Capabilities include permission-v2, permission-v2.2, launch modes, and PKCE S256.

6. HTTP scope filter matcher (search/read enforcement)

Prefer per-handler wiring in hahttp.Config:

ScopeFilterMatcher: smart.RegistryScopeFilterMatcherChain(searchRegistry, fhirpathEngine),

Process-wide default: smart.InstallRegistryScopeFilterMatcher(...). Unregistered SearchParameters fall back to the MVP matcher.

7. File-backed backend client + replay store (single node)
clientStore, err := smart.NewFileBackendClientStore("/etc/haistack/backend-clients.json")
replayStore, err := smart.NewFileReplayStore("/var/lib/haistack/jti-replay.json")
bsa, err := smart.NewBackendServiceAuth(tokenURL, client, smart.WithReplayStore(replayStore))

Examples (from tests and public API)

SMART 1.x patterns (TestParseScopes_ValidPatterns):

smart.ParseScopes("patient/*.read")
smart.ParseScopes("patient/Observation.read")
smart.ParseScopes("user/*.write")
smart.ParseScopes("system/*.read")

Launch and specialty tokens (TestParseScopes_LaunchAndSpecialty):

set, _ := smart.ParseScopes("launch launch/patient openid fhirUser patient/*.read")
set.HasLaunch() // true

Malformed scopes (TestParseScopes_Malformed):

_, err := smart.ParseScopes("patient/")
errors.Is(err, smart.ErrInvalidScope) // true for patient/, patient.read, patient/*.write, etc.

Duplicate collapse (TestParseScopes_NormalizeDuplicatesAndOverlaps):

set, _ := smart.ParseScopes("patient/*.read patient/*.read patient/Observation.read")
// Len() == 1, raw scope patient/*.read

ScopeSet matching (TestScopeSet_Matching):

set, _ := smart.ParseScopes("user/Patient.read user/*.write system/*.read")
set.AllowsRead(smart.ActorUser, "Patient")        // true
set.AllowsWrite(smart.ActorUser, "Patient")       // true via user/*.write
set.AllowsRead(smart.ActorSystem, "Observation")  // true
set.AllowsWrite(smart.ActorSystem, "Observation") // false

BuildLaunchContext merges claims and input (TestBuildLaunchContext in smart_test.go).

SMARTVersion constant — documents implemented scope patterns:

const smart.SMARTVersion = "2.2 granular scopes (CRUDS + search-parameter filters); v1 read/write patterns supported"

Configuration / key types

Type Purpose
ScopeSet, Scope, ActorClass, AccessVerb Parsed scope model
ParseScopes, ScopeParser Entry parsing
LaunchContext, LaunchContextInput, BuildLaunchContext Launch hints
TokenClaims, TokenValidator, TokenValidateOptions JWT validation
BackendServiceAuth, BackendClient, ClientKeyMetadata Backend assertions
BackendClientStore, ReplayStore Client allow-list and jti replay
AuthAdapter, AuthAdapterConfig, AuthBundle SMART → auth translation
Configuration, DefaultConfiguration SMART metadata document
ClientRegistration Minimal static client metadata
ErrInvalidScope, ErrClientNotAllowed, … Error taxonomy

Backend assertion scopes must be a subset of the client's AllowedScopes. Unknown client IDs fail closed.

Where it fits

Client app / backend job
        │
        ▼
   OAuth AS (host: pkg/oauth or external)
        │
        ▼
   Access token or client assertion JWT
        │
        ▼
   pkg/smart  (parse scopes, validate token/assertion, build LaunchContext)
        │
        ▼
   AuthAdapter → AuthBundle
        │
        ▼
   pkg/auth.Engine  (CheckPatientScope, read/write decisions)
        │
        ▼
   pkg/core / handlers (optional ScopeFilterMatcher on search)

Limits

  • Deny by absence — Scopes must explicitly allow resource and verb; broad hospital policy may further narrow access in auth.
  • Patient scopes — Only r and s CRUDS letters; .write on patient compartment is rejected at parse time in v1 tests.
  • Launch flows — No built-in EHR iframe launch, standalone redirect choreography, or refresh rotation.
  • Signature verification — Optional; hosts must configure verifiers for production token trust.
  • File stores — Convenient for dev/single node; race and durability limits for clustered deployments.
  • Filter matching — Requires SearchParameter registration for full FHIRPath filter semantics; otherwise MVP fallback applies.
  • OAuth persistence — Authorization codes and refresh tokens live in pkg/oauth/store, not in pkg/smart.
  • doc.go — API inventory and non-goals
  • pkg/auth/README.md
  • pkg/oauth — authorization server persistence and endpoints
  • Root README SMART / security sections where present

Documentation

Overview

Package smart implements haistack-smart, an optional SMART on FHIR library for HAIStack.

Scope

v1 establishes SMART as a separate interpreter that plugs into haistack-auth through adapters. It does not move SMART concepts into pkg/auth, and it is not required by offline/local runtimes (core, sync, view, ai, auth).

Contained in v1:

  • SMART scope parsing and normalized ScopeSet matching
  • LaunchContext types and builders (no EHR/standalone launch runtime)
  • Token / JWT claim validation helpers
  • Backend-service assertion validation and client registry
  • AuthAdapter translating scopes + launch context into pkg/auth inputs
  • Minimal ClientRegistration types for future expansion

Explicitly out of v1: full SMART App Launch product flow, EHR launch orchestration, standalone launch orchestration, dynamic client registration, refresh-token lifecycle, SMART UI/session management, and HTTP middleware as the center of the package.

Public API

  • ParseScopes / ScopeParser: normalize patient|user|system resource scopes and launch/specialty tokens
  • ScopeSet.Allows / AllowsRead / AllowsWrite: resource/action matching
  • BuildLaunchContext / ExtractLaunchContext: patient/encounter/user context
  • TokenValidator / ValidateToken / ValidateClaims: JWT structure, iss/aud/exp/nbf, scope extraction (optional SignatureVerifier / PEMVerifier)
  • BackendServiceAuth / ValidateBackendAssertion: signed client assertions, allow-listed scopes, service-client registry
  • AuthAdapter / ToAuthRequests / FromBackendService: derive auth.Principal, TenantContext (including PatientScope), and request builders for pkg/auth
  • ClientRegistration: minimal static client metadata

Typical usage

scopes, err := smart.ParseScopes("patient/*.read launch/patient")
ok := scopes.AllowsRead(smart.ActorPatient, "Observation")

launch := smart.BuildLaunchContext(smart.LaunchContextInput{
    PatientID:  "pat-1",
    UserID:     "Practitioner/pract-1",
    TenantHint: "tenant-a",
    Scopes:     scopes,
})

adapter := smart.NewAuthAdapter(smart.AuthAdapterConfig{
    DefaultTenantID:  "tenant-a",
    DefaultUserRoles: []string{"smart-user"},
})
bundle, err := adapter.ToAuthRequests(claims, launch)
_ = eng.CheckPatientScope(ctx, adapter.ToPatientScopeRequest(bundle, ""))

bsa, _ := smart.NewBackendServiceAuth("https://auth.example/token", client)
claims, client, err := bsa.ValidateBackendAssertion(assertionJWT, smart.TokenValidateOptions{})
bundle, err = adapter.FromBackendService(claims, client, smart.LaunchContext{})

Integration

  • haistack-auth: AuthAdapter produces Principal, TenantContext, permissions, ReadRequest/WriteRequest/PatientScopeRequest; Engine remains the decision authority
  • Hosts own OAuth/token-endpoint transport; this package validates and adapts

Index

Constants

View Source
const SMARTVersion = "2.2 granular scopes (CRUDS + search-parameter filters); v1 read/write patterns supported"

SMARTVersion documents the SMART scope patterns implemented by pkg/smart.

Variables

View Source
var (
	// ErrInvalidScope is returned when a scope string cannot be parsed.
	ErrInvalidScope = errors.New("smart: invalid scope")

	// ErrInvalidToken is returned when a token or assertion is malformed.
	ErrInvalidToken = errors.New("smart: invalid token")

	// ErrTokenExpired is returned when exp is in the past.
	ErrTokenExpired = errors.New("smart: token expired")

	// ErrTokenNotYetValid is returned when nbf is in the future.
	ErrTokenNotYetValid = errors.New("smart: token not yet valid")

	// ErrIssuerMismatch is returned when iss does not match the expected issuer.
	ErrIssuerMismatch = errors.New("smart: issuer mismatch")

	// ErrAudienceMismatch is returned when aud does not include the expected audience.
	ErrAudienceMismatch = errors.New("smart: audience mismatch")

	// ErrMissingScopes is returned when required scopes are absent.
	ErrMissingScopes = errors.New("smart: missing scopes")

	// ErrClientNotAllowed is returned when a backend client is unknown or denied.
	ErrClientNotAllowed = errors.New("smart: client not allowed")

	// ErrScopeNotAllowed is returned when requested scopes exceed a client's allow-list.
	ErrScopeNotAllowed = errors.New("smart: scope not allowed")

	// ErrSignatureInvalid is returned when JWT signature verification fails.
	ErrSignatureInvalid = errors.New("smart: signature invalid")

	// ErrInvalidConfig is returned when adapter or validator config is incomplete.
	ErrInvalidConfig = errors.New("smart: invalid config")

	// ErrMissingKey is returned when signature verification requires a key that is absent.
	ErrMissingKey = errors.New("smart: missing key")

	// ErrReplay is returned when a JWT assertion identifier has already been used.
	ErrReplay = errors.New("smart: replayed assertion")

	// ErrUnauthorized is returned when a request lacks valid SMART credentials.
	ErrUnauthorized = errors.New("smart: unauthorized")
)
View Source
var ErrScopeFilterDenied = fmt.Errorf("%w: resource outside granted scope filters", auth.ErrDenied)

ErrScopeFilterDenied is returned when a resource or search request falls outside SMART 2.2 scope filters.

Functions

func AllowsResourceWithFiltersReadOrSearch

func AllowsResourceWithFiltersReadOrSearch(ctx context.Context, scopes ScopeSet, actor ActorClass, resourceType string, resource *types.ResourceEnvelope) bool

AllowsResourceWithFiltersReadOrSearch reports whether read or search scope authorizes a bundle entry.

func ApplyScopeFiltersToParams

func ApplyScopeFiltersToParams(scopes ScopeSet, actor ActorClass, resourceType string, params url.Values) (url.Values, error)

ApplyScopeFiltersToParams intersects SMART 2.2 scope filters with FHIR search params.

func CheckEnvelopeScopeFilters

func CheckEnvelopeScopeFilters(ctx context.Context, scopes ScopeSet, actor ActorClass, resourceType string, op AccessOp, resource *types.ResourceEnvelope) error

CheckEnvelopeScopeFilters enforces SMART 2.2 scope filters for a loaded resource.

func ContextWithAuthBundle

func ContextWithAuthBundle(ctx context.Context, bundle AuthBundle) context.Context

ContextWithAuthBundle stores a validated SMART AuthBundle on the context.

func ContextWithBearerAuthCache

func ContextWithBearerAuthCache(ctx context.Context) context.Context

ContextWithBearerAuthCache attaches a per-request bearer auth cache to ctx.

func ContextWithScopeFilterMatcher

func ContextWithScopeFilterMatcher(ctx context.Context, matcher ScopeFilterMatcher) context.Context

ContextWithScopeFilterMatcher attaches a per-request scope filter matcher. Handlers should prefer this over the package-global matcher from SetScopeFilterMatcher.

func CurveByteLen

func CurveByteLen(key *ecdsa.PublicKey) int

CurveByteLen returns the ECDSA signature coordinate length for a public key.

func DefaultPermissionsFromScopes

func DefaultPermissionsFromScopes(scopes ScopeSet) []auth.Permission

DefaultPermissionsFromScopes maps resource scopes to auth permissions.

func FilterBundleEnvelopeScopeFilters

func FilterBundleEnvelopeScopeFilters(ctx context.Context, scopes ScopeSet, actor ActorClass, defaultResourceType string, envelope *types.ResourceEnvelope, codec types.ResourceCodec) (*types.ResourceEnvelope, error)

FilterBundleEnvelopeScopeFilters removes bundle entries outside granted scope filters.

func FilterSearchBundleScopeFilters

func FilterSearchBundleScopeFilters(ctx context.Context, scopes ScopeSet, actor ActorClass, resourceType string, bundle *search.SearchBundle) error

FilterSearchBundleScopeFilters keeps results produced by a rewritten query and still drops match, include, revinclude, and empty-mode ($everything) entries that fall outside granted scope filters. This post-filter is a safety net if a backend ignores rewrite. Total is left as the query-time count; Count follows remaining match rows.

func InstallRegistryScopeFilterMatcher

func InstallRegistryScopeFilterMatcher(registry search.Registry, engine fhirpath.Engine)

InstallRegistryScopeFilterMatcher registers a registry-backed matcher ahead of the MVP matcher.

func SetScopeFilterMatcher

func SetScopeFilterMatcher(matcher ScopeFilterMatcher)

SetScopeFilterMatcher replaces the global scope filter matcher used by enforcement helpers. Hosts typically chain a registry-backed matcher ahead of the built-in MVP matcher.

func StableAuthDiagnostics

func StableAuthDiagnostics(err error) string

StableAuthDiagnostics returns catalog-stable diagnostics for SMART authentication errors. Dynamic suffixes such as exp/nbf timestamps are stripped so HTTP responses and golden tests can compare against AuthOutcomeCatalog entries.

func ValidateBackendAssertion

func ValidateBackendAssertion(b *BackendServiceAuth, assertion string, opts TokenValidateOptions) (TokenClaims, BackendClient, error)

ValidateBackendAssertion validates a SMART backend-service client assertion against the given BackendServiceAuth registry.

func ValidateClaims

func ValidateClaims(claims TokenClaims, opts TokenValidateOptions) error

ValidateClaims checks issuer, audience, time, and scope requirements.

func WellKnownHandler

func WellKnownHandler(cfg Configuration) http.Handler

WellKnownHandler serves /.well-known/smart-configuration for reference hosts.

Types

type AccessOp

type AccessOp rune

AccessOp is one SMART 2.x CRUDS operation letter.

const (
	OpRead   AccessOp = 'r'
	OpSearch AccessOp = 's'
	OpCreate AccessOp = 'c'
	OpUpdate AccessOp = 'u'
	OpDelete AccessOp = 'd'
)

type AccessVerb

type AccessVerb string

AccessVerb is the access capability granted by a resource scope.

const (
	VerbRead  AccessVerb = "read"
	VerbWrite AccessVerb = "write"
	VerbAll   AccessVerb = "*"
)

type ActorClass

type ActorClass string

ActorClass is the SMART scope actor prefix (patient, user, or system).

const (
	ActorPatient ActorClass = "patient"
	ActorUser    ActorClass = "user"
	ActorSystem  ActorClass = "system"
)

func ActorForPrincipal

func ActorForPrincipal(kind auth.PrincipalKind, scopes ScopeSet) ActorClass

ActorForPrincipal returns the SMART actor class for a principal and scope set.

type AuthAdapter

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

AuthAdapter translates SMART scopes, launch context, and token claims into pkg/auth principals, tenant context, permissions, and request builders. Authorization decisions remain in pkg/auth; this adapter only interprets SMART.

func NewAuthAdapter

func NewAuthAdapter(cfg AuthAdapterConfig) *AuthAdapter

NewAuthAdapter returns an AuthAdapter.

func (*AuthAdapter) FromBackendService

func (a *AuthAdapter) FromBackendService(claims TokenClaims, client BackendClient, launch LaunchContext) (AuthBundle, error)

FromBackendService maps a validated backend assertion to an AuthBundle with a service principal.

func (*AuthAdapter) PermissionsFromScopes

func (a *AuthAdapter) PermissionsFromScopes(scopes ScopeSet) []auth.Permission

PermissionsFromScopes derives auth.Permission values from SMART resource scopes. Default form is "{ResourceType}.{verb}" or "*.{verb}" for wildcards.

func (*AuthAdapter) ScopeImplies

func (a *AuthAdapter) ScopeImplies(bundle AuthBundle, resourceType string, verb AccessVerb) bool

ScopeImplies reports whether the bundle's scopes authorize a resource action for the principal's SMART actor class.

func (*AuthAdapter) ScopeImpliesOp

func (a *AuthAdapter) ScopeImpliesOp(bundle AuthBundle, resourceType string, op AccessOp) bool

ScopeImpliesOp reports whether the bundle's scopes authorize a CRUDS operation.

func (*AuthAdapter) ToAIToolRequest

func (a *AuthAdapter) ToAIToolRequest(bundle AuthBundle, toolName, resourceType, viewName string) auth.AIToolRequest

ToAIToolRequest builds an auth.AIToolRequest with SMART-derived RequiredPermissions for a read of resourceType.

func (*AuthAdapter) ToAuthRequests

func (a *AuthAdapter) ToAuthRequests(claims TokenClaims, launch LaunchContext) (AuthBundle, error)

ToAuthRequests builds an AuthBundle from token claims and launch context.

func (*AuthAdapter) ToPatientScopeRequest

func (a *AuthAdapter) ToPatientScopeRequest(bundle AuthBundle, patientID string) auth.PatientScopeRequest

ToPatientScopeRequest builds an auth.PatientScopeRequest using launch patient id when patientID is empty.

func (*AuthAdapter) ToReadRequest

func (a *AuthAdapter) ToReadRequest(bundle AuthBundle, resourceType, id string) auth.ReadRequest

ToReadRequest builds an auth.ReadRequest using SMART-derived identity and permissions derived from scopes for the resource type.

func (*AuthAdapter) ToViewRequest

func (a *AuthAdapter) ToViewRequest(bundle AuthBundle, viewName, resourceType string) auth.ViewRequest

ToViewRequest builds an auth.ViewRequest with SMART-derived RequiredPermissions for a read of resourceType (same scope→permission mapping as ToReadRequest).

func (*AuthAdapter) ToWriteRequest

func (a *AuthAdapter) ToWriteRequest(bundle AuthBundle, operation, resourceType, id string) auth.WriteRequest

ToWriteRequest builds an auth.WriteRequest.

type AuthAdapterConfig

type AuthAdapterConfig struct {
	// DefaultTenantID is used when launch/claims do not supply a tenant hint.
	DefaultTenantID string
	// DefaultUserRoles are applied to user principals when RoleBindings are empty.
	DefaultUserRoles []string
	// DefaultServiceRoles are applied to service principals when RoleBindings are empty.
	DefaultServiceRoles []string
	// PermissionMapper overrides default scope→permission derivation.
	PermissionMapper func(ScopeSet) []auth.Permission
}

AuthAdapterConfig configures SMART → auth translation.

type AuthBundle

type AuthBundle struct {
	Principal   auth.Principal
	Tenant      auth.TenantContext
	Permissions []auth.Permission
	Scopes      ScopeSet
	Launch      LaunchContext
	Claims      TokenClaims
	Client      *BackendClient
}

AuthBundle is the SMART-derived input ready for haistack-auth decision APIs.

func AuthBundleFromContext

func AuthBundleFromContext(ctx context.Context) (AuthBundle, bool)

AuthBundleFromContext retrieves a SMART AuthBundle previously stored on ctx.

type BackendAssertionAuthConfig

type BackendAssertionAuthConfig struct {
	Backend *BackendServiceAuth
	Adapter *AuthAdapter
	Options TokenValidateOptions
}

BackendAssertionAuthConfig validates backend-service client assertions for HTTP hosts.

func (BackendAssertionAuthConfig) ResolveBackendAssertionCached

func (c BackendAssertionAuthConfig) ResolveBackendAssertionCached(ctx context.Context, r *http.Request) (BearerAuthResult, error)

ResolveBackendAssertionCached validates a backend assertion at most once per request context.

type BackendClient

type BackendClient struct {
	ClientID      string   `json:"clientId"`
	AllowedScopes []string `json:"allowedScopes,omitempty"`
	// AllowAnyScope permits assertions with any scope when AllowedScopes is empty.
	// By default clients must declare an explicit allow-list.
	AllowAnyScope bool              `json:"allowAnyScope,omitempty"`
	Key           ClientKeyMetadata `json:"key"`
	// Issuer defaults to ClientID when empty (common for client assertions).
	Issuer string `json:"issuer,omitempty"`
	// TenantHint optionally seeds auth tenant context for this client.
	TenantHint string `json:"tenantHint,omitempty"`
	// DisplayName is optional metadata for the derived service principal.
	DisplayName string `json:"displayName,omitempty"`
}

BackendClient describes a registered SMART backend-service client.

func (BackendClient) EffectiveIssuer

func (c BackendClient) EffectiveIssuer() string

EffectiveIssuer returns Issuer or ClientID.

type BackendClientStore

type BackendClientStore interface {
	LookupBackendClient(clientID string) (BackendClient, error)
	RegisterBackendClient(client BackendClient) error
}

BackendClientStore is an optional persistent/dynamic registry boundary for backend clients. Implementations can load credentials and allow-list changes without rebuilding the process.

type BackendServiceAuth

type BackendServiceAuth struct {
	Clients     map[string]BackendClient
	ClientStore BackendClientStore
	// Audience is the expected assertion audience (typically the token endpoint URL).
	Audience string
	Now      func() time.Time
	// ClockSkew allowed for exp/nbf.
	ClockSkew time.Duration
	// RequireScopeClaim requires a non-empty scope claim on the assertion.
	RequireScopeClaim bool
	// VerifierForClient may resolve a rotating/JWKS-backed verifier. When nil,
	// inline client PEM metadata is used.
	VerifierForClient func(BackendClient) SignatureVerifier
	// Replay records assertion jti values. Nil lazily gets a process-local store.
	Replay ReplayStore
	// contains filtered or unexported fields
}

BackendServiceAuth validates backend-service client assertions and maps them toward service principals. It does not implement an OAuth authorization server or token endpoint; hosts provide transport and token exchange.

func NewBackendServiceAuth

func NewBackendServiceAuth(audience string, clients ...BackendClient) (*BackendServiceAuth, error)

NewBackendServiceAuth returns a BackendServiceAuth indexed by client id.

func NewBackendServiceAuthWithStores

func NewBackendServiceAuthWithStores(audience string, clientStore BackendClientStore, replay ReplayStore, clients ...BackendClient) (*BackendServiceAuth, error)

NewBackendServiceAuthWithStores constructs backend auth with explicit client-registry and replay persistence. Nil stores use process-local memory.

func (*BackendServiceAuth) AuthorizeBackendScopes

func (b *BackendServiceAuth) AuthorizeBackendScopes(clientID string, requested ScopeSet) error

AuthorizeBackendScopes checks whether requested scopes are permitted for the client without validating a token (useful before token exchange).

func (*BackendServiceAuth) LookupClient

func (b *BackendServiceAuth) LookupClient(clientID string) (BackendClient, error)

LookupClient returns a registered client.

func (*BackendServiceAuth) RegisterClient

func (b *BackendServiceAuth) RegisterClient(c BackendClient) error

RegisterClient upserts a backend client.

func (*BackendServiceAuth) ValidateBackendAssertion

func (b *BackendServiceAuth) ValidateBackendAssertion(assertion string, opts TokenValidateOptions) (TokenClaims, BackendClient, error)

ValidateBackendAssertion parses and validates a signed client assertion JWT for a known backend client. Scopes on the assertion must be a subset of the client's AllowedScopes when that allow-list is non-empty.

type BearerAuthConfig

type BearerAuthConfig struct {
	Validator *TokenValidator
	Adapter   *AuthAdapter
	Options   TokenValidateOptions
}

BearerAuthConfig validates Bearer JWT access tokens and builds AuthBundles for HTTP hosts.

func (BearerAuthConfig) ResolveBearerToken

func (c BearerAuthConfig) ResolveBearerToken(r *http.Request) (BearerAuthResult, error)

ResolveBearerToken extracts and validates a Bearer token from the Authorization header.

func (BearerAuthConfig) ResolveBearerTokenCached

func (c BearerAuthConfig) ResolveBearerTokenCached(ctx context.Context, r *http.Request) (BearerAuthResult, error)

ResolveBearerTokenCached validates the Bearer token at most once per request context.

type BearerAuthResult

type BearerAuthResult struct {
	Bundle AuthBundle
}

BearerAuthResult is the authenticated SMART identity for one HTTP request.

type ChainedScopeFilterMatcher

type ChainedScopeFilterMatcher []ScopeFilterMatcher

ChainedScopeFilterMatcher tries matchers in order and uses the first known result.

func (ChainedScopeFilterMatcher) Match

func (c ChainedScopeFilterMatcher) Match(ctx context.Context, resourceType string, resource *types.ResourceEnvelope, param string, want []string) (matched bool, known bool)

Match implements ScopeFilterMatcher.

type ClientKeyMetadata

type ClientKeyMetadata struct {
	// Algorithm is the expected JWS alg (RS256, RS384, ES256, ES384).
	Algorithm string `json:"algorithm,omitempty"`
	// PublicKeyPEM is a PEM-encoded PKIX public key or certificate.
	PublicKeyPEM string `json:"publicKeyPem,omitempty"`
	// JWKSURI is an optional discovery hint for host-provided key resolution.
	JWKSURI string `json:"jwksUri,omitempty"`
	// KeyID is an optional kid matching the assertion header.
	KeyID string `json:"keyId,omitempty"`
}

ClientKeyMetadata describes key material used to validate backend-service client assertions. JWKS URI is recorded for host resolvers; v1 verifies from inline PEM when present.

type ClientRegistration

type ClientRegistration struct {
	ClientID                string   `json:"clientId"`
	ClientName              string   `json:"clientName,omitempty"`
	RedirectURIs            []string `json:"redirectUris,omitempty"`
	GrantTypes              []string `json:"grantTypes,omitempty"`
	ResponseTypes           []string `json:"responseTypes,omitempty"`
	Scopes                  []string `json:"scopes,omitempty"`
	TokenEndpointAuthMethod string   `json:"tokenEndpointAuthMethod,omitempty"`
	JWKSURI                 string   `json:"jwksUri,omitempty"`
	Contacts                []string `json:"contacts,omitempty"`
}

ClientRegistration is a minimal static description of a SMART client for future expansion. v1 does not implement dynamic client registration or launch/session runtime; hosts may store these fields alongside BackendClient.

type Configuration

type Configuration struct {
	Issuer                        string   `json:"issuer"`
	JWKSURI                       string   `json:"jwks_uri,omitempty"`
	AuthorizationEndpoint         string   `json:"authorization_endpoint,omitempty"`
	TokenEndpoint                 string   `json:"token_endpoint,omitempty"`
	RegistrationEndpoint          string   `json:"registration_endpoint,omitempty"`
	ScopesSupported               []string `json:"scopes_supported,omitempty"`
	ResponseTypesSupported        []string `json:"response_types_supported,omitempty"`
	GrantTypesSupported           []string `json:"grant_types_supported,omitempty"`
	Capabilities                  []string `json:"capabilities,omitempty"`
	CodeChallengeMethodsSupported []string `json:"code_challenge_methods_supported,omitempty"`
}

Configuration is the SMART App Launch metadata shape served at /.well-known/smart-configuration by pkg/oauth or host integrations.

func DefaultConfiguration

func DefaultConfiguration(issuer string) Configuration

DefaultConfiguration returns a baseline SMART 1.x/2.x compatible configuration document. Hosts should override endpoints and supported scopes for their deployment.

type FileBackendClientStore

type FileBackendClientStore struct {
	Path string
	// contains filtered or unexported fields
}

FileBackendClientStore persists backend client registrations as a JSON map and reloads the file on every lookup, allowing configuration changes to be picked up without restarting the process. Protect the file with deployment filesystem permissions; production multi-instance deployments should use a shared transactional store implementing BackendClientStore.

func NewFileBackendClientStore

func NewFileBackendClientStore(path string) (*FileBackendClientStore, error)

func (*FileBackendClientStore) LookupBackendClient

func (s *FileBackendClientStore) LookupBackendClient(clientID string) (BackendClient, error)

func (*FileBackendClientStore) RegisterBackendClient

func (s *FileBackendClientStore) RegisterBackendClient(client BackendClient) error

type FileReplayStore

type FileReplayStore struct {
	Path string
	Now  func() time.Time
	// contains filtered or unexported fields
}

FileReplayStore persists used assertion IDs across process restarts. It is safe for concurrent use within one process. Use a shared ReplayStore with transactional/distributed locking when multiple instances share a path.

func NewFileReplayStore

func NewFileReplayStore(path string) (*FileReplayStore, error)

func (*FileReplayStore) CheckAndStore

func (s *FileReplayStore) CheckAndStore(jti string, expiresAt time.Time) error

type LaunchContext

type LaunchContext struct {
	PatientID   string            `json:"patientId,omitempty"`
	EncounterID string            `json:"encounterId,omitempty"`
	UserID      string            `json:"userId,omitempty"`
	TenantHint  string            `json:"tenantHint,omitempty"`
	Metadata    map[string]string `json:"metadata,omitempty"`
}

LaunchContext holds SMART launch patient/user/encounter context used to feed haistack-auth patient-scope and principal decisions. It does not orchestrate EHR or standalone launch flows.

func BuildLaunchContext

func BuildLaunchContext(in LaunchContextInput) LaunchContext

BuildLaunchContext constructs a LaunchContext from structured fields, token claims, and scope markers. Empty inputs yield an empty context (not an error).

func ExtractLaunchContext

func ExtractLaunchContext(claims TokenClaims, overlay LaunchContextInput) LaunchContext

ExtractLaunchContext builds LaunchContext from token claims and optional overlays.

type LaunchContextInput

type LaunchContextInput struct {
	PatientID   string
	EncounterID string
	UserID      string
	TenantHint  string
	// Scopes optionally contribute launch markers into Metadata.
	Scopes ScopeSet
	// Metadata is copied into the result; known keys are not overwritten by
	// structured fields unless empty.
	Metadata map[string]string
	// Claims optionally supply patient/encounter/fhirUser when structured
	// fields are empty.
	Claims *TokenClaims
}

LaunchContextInput is the application-supplied input for BuildLaunchContext.

type MemoryReplayStore

type MemoryReplayStore struct {

	// Now is injectable for deterministic tests and hosts with a shared clock.
	// A nil function uses time.Now.
	Now func() time.Time
	// contains filtered or unexported fields
}

MemoryReplayStore is a process-local replay store suitable for development and single-instance deployments.

func NewMemoryReplayStore

func NewMemoryReplayStore() *MemoryReplayStore

func (*MemoryReplayStore) CheckAndStore

func (s *MemoryReplayStore) CheckAndStore(jti string, expiresAt time.Time) error

type PEMVerifier

type PEMVerifier struct {
	PublicKeyPEM string
	// Algorithm, when set, must match the token header alg.
	Algorithm string
}

PEMVerifier verifies JWT signatures with a PEM-encoded RSA or ECDSA public key.

func (PEMVerifier) Verify

func (v PEMVerifier) Verify(headerSegment, payloadSegment string, signature []byte, alg string) error

Verify implements SignatureVerifier.

type RegistryScopeFilterMatcher

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

RegistryScopeFilterMatcher evaluates SMART scope filters using registry SearchParameters.

func NewRegistryScopeFilterMatcher

func NewRegistryScopeFilterMatcher(registry search.Registry, engine fhirpath.Engine) *RegistryScopeFilterMatcher

NewRegistryScopeFilterMatcher constructs a matcher backed by compiled search metadata.

func (*RegistryScopeFilterMatcher) Match

func (m *RegistryScopeFilterMatcher) Match(ctx context.Context, resourceType string, resource *types.ResourceEnvelope, param string, want []string) (matched bool, known bool)

Match implements ScopeFilterMatcher.

type ReplayStore

type ReplayStore interface {
	CheckAndStore(jti string, expiresAt time.Time) error
}

ReplayStore atomically records a JWT ID until its expiry and rejects IDs already recorded. Hosts may provide a distributed implementation for multi-instance deployments.

type Scope

type Scope struct {
	// Raw is the original scope string after whitespace trim.
	Raw string `json:"raw"`
	// Kind classifies the scope.
	Kind ScopeKind `json:"kind"`
	// Actor is patient, user, or system for resource scopes; empty otherwise.
	Actor ActorClass `json:"actor,omitempty"`
	// Resource is "*" or a FHIR resource type for resource scopes.
	Resource string `json:"resource,omitempty"`
	// Verb is read, write, or * for resource scopes (v1 compatibility).
	Verb AccessVerb `json:"verb,omitempty"`
	// Letters is the normalized CRUDS suffix (for example "rs", "cud", "cruds").
	Letters string `json:"letters,omitempty"`
	// Filters holds optional SMART 2.2 search-parameter filters from the scope suffix.
	Filters url.Values `json:"filters,omitempty"`
	// LaunchType is set for launch scopes ("" for bare "launch", "patient" for
	// "launch/patient", "encounter" for "launch/encounter").
	LaunchType string `json:"launchType,omitempty"`
	// Specialty is the specialty token name (openid, fhirUser, ...).
	Specialty string `json:"specialty,omitempty"`
}

Scope is one normalized SMART scope token.

func (Scope) AllowsOp

func (s Scope) AllowsOp(op AccessOp) bool

AllowsOp reports whether the scope grants the requested CRUDS operation.

func (Scope) Matches

func (s Scope) Matches(resourceType string, verb AccessVerb) bool

Matches reports whether this resource scope authorizes the given resource type and verb. Non-resource scopes never match.

func (Scope) MatchesActor

func (s Scope) MatchesActor(actor ActorClass, resourceType string, verb AccessVerb) bool

MatchesActor reports whether this resource scope matches actor, resource, and verb.

func (Scope) MatchesOp

func (s Scope) MatchesOp(actor ActorClass, resourceType string, op AccessOp) bool

MatchesOp reports whether this resource scope authorizes actor, resource type, and op.

type ScopeFilterMatcher

type ScopeFilterMatcher interface {
	Match(ctx context.Context, resourceType string, resource *types.ResourceEnvelope, param string, want []string) (matched bool, known bool)
}

ScopeFilterMatcher evaluates whether a resource satisfies one SMART scope filter parameter. Implementations return known=false when the parameter is outside their domain so callers can fall back to the built-in MVP matcher.

func DefaultScopeFilterMatcher

func DefaultScopeFilterMatcher() ScopeFilterMatcher

DefaultScopeFilterMatcher returns the currently configured matcher.

func MVPScopeFilterMatcher

func MVPScopeFilterMatcher() ScopeFilterMatcher

MVPScopeFilterMatcher returns the built-in fallback matcher.

func RegistryScopeFilterMatcherChain

func RegistryScopeFilterMatcherChain(registry search.Registry, engine fhirpath.Engine) ScopeFilterMatcher

RegistryScopeFilterMatcherChain returns a registry-backed matcher ahead of the MVP matcher.

func ScopeFilterMatcherFromContext

func ScopeFilterMatcherFromContext(ctx context.Context) ScopeFilterMatcher

ScopeFilterMatcherFromContext returns the request matcher when present, otherwise the configured default matcher.

type ScopeFilterMatcherFunc

type ScopeFilterMatcherFunc func(ctx context.Context, resourceType string, resource *types.ResourceEnvelope, param string, want []string) (matched bool, known bool)

ScopeFilterMatcherFunc adapts a function to ScopeFilterMatcher.

func (ScopeFilterMatcherFunc) Match

func (f ScopeFilterMatcherFunc) Match(ctx context.Context, resourceType string, resource *types.ResourceEnvelope, param string, want []string) (matched bool, known bool)

Match implements ScopeFilterMatcher.

type ScopeKind

type ScopeKind string

ScopeKind classifies a parsed scope token.

const (
	// ScopeKindResource is a resource permission scope (patient|user|system).
	ScopeKindResource ScopeKind = "resource"
	// ScopeKindLaunch is a launch or launch/* context marker.
	ScopeKindLaunch ScopeKind = "launch"
	// ScopeKindSpecialty covers openid, fhirUser, offline_access, and similar.
	ScopeKindSpecialty ScopeKind = "specialty"
)

type ScopeParser

type ScopeParser struct{}

ScopeParser parses and normalizes SMART scope strings.

func NewScopeParser

func NewScopeParser() *ScopeParser

NewScopeParser returns a ScopeParser.

func (*ScopeParser) Parse

func (p *ScopeParser) Parse(raw string) (ScopeSet, error)

Parse parses a space-delimited SMART scope string into a normalized ScopeSet.

type ScopePolicyAuthChecker

type ScopePolicyAuthChecker struct {
	Engine  auth.PolicyEngine
	Adapter *AuthAdapter
	// BundleFor returns the SMART auth bundle for the authenticated principal.
	// When it returns false, requests are evaluated without scope-derived permissions.
	BundleFor func(principal auth.Principal, tenant auth.TenantContext) (AuthBundle, bool)
}

ScopePolicyAuthChecker adapts auth.PolicyEngine to pkg/http.AuthChecker while passing SMART scope-derived RequiredPermissions into read/write/search decisions. Pair with BundleFor to supply the validated SMART AuthBundle per request.

func (ScopePolicyAuthChecker) AuthorizeExport

func (c ScopePolicyAuthChecker) AuthorizeExport(ctx context.Context, principal auth.Principal, tenant auth.TenantContext, groupID string) (auth.Decision, error)

AuthorizeExport implements http.AuthChecker.

func (ScopePolicyAuthChecker) AuthorizeRead

func (c ScopePolicyAuthChecker) AuthorizeRead(ctx context.Context, principal auth.Principal, tenant auth.TenantContext, resourceType, id string) (auth.Decision, error)

AuthorizeRead implements http.AuthChecker.

func (ScopePolicyAuthChecker) AuthorizeSearch

func (c ScopePolicyAuthChecker) AuthorizeSearch(ctx context.Context, principal auth.Principal, tenant auth.TenantContext, resourceType string) (auth.Decision, error)

AuthorizeSearch implements http.AuthChecker.

func (ScopePolicyAuthChecker) AuthorizeWrite

func (c ScopePolicyAuthChecker) AuthorizeWrite(ctx context.Context, principal auth.Principal, tenant auth.TenantContext, operation, resourceType, id string) (auth.Decision, error)

AuthorizeWrite implements http.AuthChecker.

type ScopeSet

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

ScopeSet is a normalized, deduplicated collection of SMART scopes.

func ParseScopes

func ParseScopes(raw string) (ScopeSet, error)

ParseScopes parses a space-delimited SMART scope string into a normalized ScopeSet.

func (ScopeSet) Allows

func (s ScopeSet) Allows(actor ActorClass, resourceType string, verb AccessVerb) bool

Allows reports whether any resource scope authorizes actor/resource/verb.

func (ScopeSet) AllowsOp

func (s ScopeSet) AllowsOp(actor ActorClass, resourceType string, op AccessOp) bool

AllowsOp reports whether any scope authorizes actor/resource/op.

func (ScopeSet) AllowsRead

func (s ScopeSet) AllowsRead(actor ActorClass, resourceType string) bool

AllowsRead is Allows(..., VerbRead).

func (ScopeSet) AllowsResourceWithFilters

func (s ScopeSet) AllowsResourceWithFilters(ctx context.Context, actor ActorClass, resourceType string, op AccessOp, resource *types.ResourceEnvelope) bool

AllowsResourceWithFilters reports whether any granted scope authorizes the resource and, when present, scope filters match the resource payload.

func (ScopeSet) AllowsSearch

func (s ScopeSet) AllowsSearch(actor ActorClass, resourceType string) bool

AllowsSearch reports whether any scope authorizes search for actor/resource.

func (ScopeSet) AllowsWrite

func (s ScopeSet) AllowsWrite(actor ActorClass, resourceType string) bool

AllowsWrite is Allows(..., VerbWrite).

func (ScopeSet) ContainsAll

func (s ScopeSet) ContainsAll(required []string) bool

ContainsAll reports whether every required raw scope string is present.

func (ScopeSet) Empty

func (s ScopeSet) Empty() bool

Empty reports whether the set has no scopes.

func (ScopeSet) Has

func (s ScopeSet) Has(raw string) bool

Has reports whether an identical raw scope is present.

func (ScopeSet) HasLaunch

func (s ScopeSet) HasLaunch() bool

HasLaunch reports whether any launch context marker is present.

func (ScopeSet) LaunchScopes

func (s ScopeSet) LaunchScopes() []Scope

LaunchScopes returns launch-kind scopes.

func (ScopeSet) Len

func (s ScopeSet) Len() int

Len returns the number of scopes.

func (ScopeSet) ResourceScopes

func (s ScopeSet) ResourceScopes(actors ...ActorClass) []Scope

ResourceScopes returns resource permission scopes, optionally filtered by actor.

func (ScopeSet) Scopes

func (s ScopeSet) Scopes() []Scope

Scopes returns a copy of the normalized scopes in stable order.

func (ScopeSet) ScopesAllowingOp

func (s ScopeSet) ScopesAllowingOp(actor ActorClass, resourceType string, op AccessOp) []Scope

ScopesAllowingOp returns resource scopes that authorize the operation.

func (ScopeSet) SpaceSeparated

func (s ScopeSet) SpaceSeparated() string

SpaceSeparated returns scopes joined by a single space (OAuth scope form).

func (ScopeSet) Strings

func (s ScopeSet) Strings() []string

Strings returns the raw scope strings in stable order.

func (ScopeSet) SubsetOf

func (s ScopeSet) SubsetOf(allowed ScopeSet) bool

SubsetOf reports whether every scope in s is allowed by allowed (exact raw match or covered by a broader resource scope in allowed).

type SignatureVerifier

type SignatureVerifier interface {
	Verify(headerSegment, payloadSegment string, signature []byte, alg string) error
}

SignatureVerifier verifies a compact JWT signature over header.payload.

type SignatureVerifierFunc

type SignatureVerifierFunc func(headerSegment, payloadSegment string, signature []byte, alg string) error

SignatureVerifierFunc adapts a function to SignatureVerifier.

func (SignatureVerifierFunc) Verify

func (f SignatureVerifierFunc) Verify(headerSegment, payloadSegment string, signature []byte, alg string) error

Verify implements SignatureVerifier.

type TokenClaims

type TokenClaims struct {
	Issuer    string    `json:"iss,omitempty"`
	Subject   string    `json:"sub,omitempty"`
	Audience  []string  `json:"aud,omitempty"`
	ExpiresAt time.Time `json:"exp,omitempty"`
	NotBefore time.Time `json:"nbf,omitempty"`
	IssuedAt  time.Time `json:"iat,omitempty"`
	JWTID     string    `json:"jti,omitempty"`
	ClientID  string    `json:"client_id,omitempty"`

	// Scope is the raw space-delimited scope claim.
	Scope  string   `json:"scope,omitempty"`
	Scopes ScopeSet `json:"-"`

	// Launch / FHIR context claims commonly present on SMART access tokens.
	Patient   string `json:"patient,omitempty"`
	Encounter string `json:"encounter,omitempty"`
	FHIRUser  string `json:"fhirUser,omitempty"`

	// TenantHint is an optional application-specific tenant claim.
	TenantHint string `json:"tenant,omitempty"`

	// LaunchExtensions holds additional string launch metadata from the token.
	LaunchExtensions map[string]string `json:"-"`

	// Extra retains unrecognized claims for host adapters.
	Extra map[string]any `json:"-"`
}

TokenClaims holds normalized JWT/assertion claims relevant to SMART decisions.

func ParseTokenUnverified

func ParseTokenUnverified(token string) (TokenClaims, error)

ParseTokenUnverified parses a compact JWT into TokenClaims without signature or time validation. Hosts that already trust the token may use this then call ValidateClaims.

func ValidateToken

func ValidateToken(token string, verifier SignatureVerifier, opts TokenValidateOptions) (TokenClaims, error)

ValidateToken parses and validates a compact JWT using an optional verifier. When verifier is nil, only structural claim validation runs.

type TokenValidateOptions

type TokenValidateOptions struct {
	// ExpectedIssuer, when non-empty, must equal claims.Issuer.
	ExpectedIssuer string
	// ExpectedAudience, when non-empty, must appear in claims.Audience.
	ExpectedAudience string
	// ExpectedAudiences, when non-empty, requires at least one match.
	ExpectedAudiences []string
	// RequiredScopes, when non-empty, must all be present (exact raw match).
	RequiredScopes []string
	// RequireScopesClaim fails when the scope claim is empty.
	RequireScopesClaim bool
	// RequireIssuer, RequireAudience, RequireExpiry, RequireSubject, and
	// RequireJWTID make the corresponding claims mandatory for assertion
	// validation. They are opt-in because gateway-validated access tokens may
	// intentionally omit some claims from a local trust boundary.
	RequireIssuer   bool
	RequireAudience bool
	RequireExpiry   bool
	RequireSubject  bool
	RequireJWTID    bool
	// Clock skew allowed for exp/nbf checks.
	ClockSkew time.Duration
	// Now overrides time.Now for tests.
	Now func() time.Time
	// SkipTimeChecks disables exp/nbf validation.
	SkipTimeChecks bool
	// IsJWTRevoked rejects tokens whose jti is revoked (for example via /oauth/revoke).
	IsJWTRevoked func(jti string) bool
}

TokenValidateOptions configures TokenValidator checks.

type TokenValidator

type TokenValidator struct {
	Verifier SignatureVerifier
	Now      func() time.Time
}

TokenValidator parses JWT structure and validates SMART-relevant claims. Signature verification is optional via SignatureVerifier so hosts can plug in crypto without making HTTP or browser runtimes a package dependency.

func NewTokenValidator

func NewTokenValidator(verifier SignatureVerifier) *TokenValidator

NewTokenValidator returns a TokenValidator. verifier may be nil when only claim-shape validation is required (e.g. after an upstream gateway verified the signature).

func (*TokenValidator) ValidateToken

func (v *TokenValidator) ValidateToken(token string, opts TokenValidateOptions) (TokenClaims, error)

ValidateToken parses a compact JWT, optionally verifies the signature, and validates iss/aud/exp/nbf/scope per opts.

Jump to

Keyboard shortcuts

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