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
- Variables
- func AllowsResourceWithFiltersReadOrSearch(ctx context.Context, scopes ScopeSet, actor ActorClass, resourceType string, ...) bool
- func ApplyScopeFiltersToParams(scopes ScopeSet, actor ActorClass, resourceType string, params url.Values) (url.Values, error)
- func CheckEnvelopeScopeFilters(ctx context.Context, scopes ScopeSet, actor ActorClass, resourceType string, ...) error
- func ContextWithAuthBundle(ctx context.Context, bundle AuthBundle) context.Context
- func ContextWithBearerAuthCache(ctx context.Context) context.Context
- func ContextWithScopeFilterMatcher(ctx context.Context, matcher ScopeFilterMatcher) context.Context
- func CurveByteLen(key *ecdsa.PublicKey) int
- func DefaultPermissionsFromScopes(scopes ScopeSet) []auth.Permission
- func FilterBundleEnvelopeScopeFilters(ctx context.Context, scopes ScopeSet, actor ActorClass, ...) (*types.ResourceEnvelope, error)
- func FilterSearchBundleScopeFilters(ctx context.Context, scopes ScopeSet, actor ActorClass, resourceType string, ...) error
- func InstallRegistryScopeFilterMatcher(registry search.Registry, engine fhirpath.Engine)
- func SetScopeFilterMatcher(matcher ScopeFilterMatcher)
- func StableAuthDiagnostics(err error) string
- func ValidateBackendAssertion(b *BackendServiceAuth, assertion string, opts TokenValidateOptions) (TokenClaims, BackendClient, error)
- func ValidateClaims(claims TokenClaims, opts TokenValidateOptions) error
- func WellKnownHandler(cfg Configuration) http.Handler
- type AccessOp
- type AccessVerb
- type ActorClass
- type AuthAdapter
- func (a *AuthAdapter) FromBackendService(claims TokenClaims, client BackendClient, launch LaunchContext) (AuthBundle, error)
- func (a *AuthAdapter) PermissionsFromScopes(scopes ScopeSet) []auth.Permission
- func (a *AuthAdapter) ScopeImplies(bundle AuthBundle, resourceType string, verb AccessVerb) bool
- func (a *AuthAdapter) ScopeImpliesOp(bundle AuthBundle, resourceType string, op AccessOp) bool
- func (a *AuthAdapter) ToAIToolRequest(bundle AuthBundle, toolName, resourceType, viewName string) auth.AIToolRequest
- func (a *AuthAdapter) ToAuthRequests(claims TokenClaims, launch LaunchContext) (AuthBundle, error)
- func (a *AuthAdapter) ToPatientScopeRequest(bundle AuthBundle, patientID string) auth.PatientScopeRequest
- func (a *AuthAdapter) ToReadRequest(bundle AuthBundle, resourceType, id string) auth.ReadRequest
- func (a *AuthAdapter) ToViewRequest(bundle AuthBundle, viewName, resourceType string) auth.ViewRequest
- func (a *AuthAdapter) ToWriteRequest(bundle AuthBundle, operation, resourceType, id string) auth.WriteRequest
- type AuthAdapterConfig
- type AuthBundle
- type BackendAssertionAuthConfig
- type BackendClient
- type BackendClientStore
- type BackendServiceAuth
- func (b *BackendServiceAuth) AuthorizeBackendScopes(clientID string, requested ScopeSet) error
- func (b *BackendServiceAuth) LookupClient(clientID string) (BackendClient, error)
- func (b *BackendServiceAuth) RegisterClient(c BackendClient) error
- func (b *BackendServiceAuth) ValidateBackendAssertion(assertion string, opts TokenValidateOptions) (TokenClaims, BackendClient, error)
- type BearerAuthConfig
- type BearerAuthResult
- type ChainedScopeFilterMatcher
- type ClientKeyMetadata
- type ClientRegistration
- type Configuration
- type FileBackendClientStore
- type FileReplayStore
- type LaunchContext
- type LaunchContextInput
- type MemoryReplayStore
- type PEMVerifier
- type RegistryScopeFilterMatcher
- type ReplayStore
- type Scope
- type ScopeFilterMatcher
- type ScopeFilterMatcherFunc
- type ScopeKind
- type ScopeParser
- type ScopePolicyAuthChecker
- func (c ScopePolicyAuthChecker) AuthorizeExport(ctx context.Context, principal auth.Principal, tenant auth.TenantContext, ...) (auth.Decision, error)
- func (c ScopePolicyAuthChecker) AuthorizeRead(ctx context.Context, principal auth.Principal, tenant auth.TenantContext, ...) (auth.Decision, error)
- func (c ScopePolicyAuthChecker) AuthorizeSearch(ctx context.Context, principal auth.Principal, tenant auth.TenantContext, ...) (auth.Decision, error)
- func (c ScopePolicyAuthChecker) AuthorizeWrite(ctx context.Context, principal auth.Principal, tenant auth.TenantContext, ...) (auth.Decision, error)
- type ScopeSet
- func (s ScopeSet) Allows(actor ActorClass, resourceType string, verb AccessVerb) bool
- func (s ScopeSet) AllowsOp(actor ActorClass, resourceType string, op AccessOp) bool
- func (s ScopeSet) AllowsRead(actor ActorClass, resourceType string) bool
- func (s ScopeSet) AllowsResourceWithFilters(ctx context.Context, actor ActorClass, resourceType string, op AccessOp, ...) bool
- func (s ScopeSet) AllowsSearch(actor ActorClass, resourceType string) bool
- func (s ScopeSet) AllowsWrite(actor ActorClass, resourceType string) bool
- func (s ScopeSet) ContainsAll(required []string) bool
- func (s ScopeSet) Empty() bool
- func (s ScopeSet) Has(raw string) bool
- func (s ScopeSet) HasLaunch() bool
- func (s ScopeSet) LaunchScopes() []Scope
- func (s ScopeSet) Len() int
- func (s ScopeSet) ResourceScopes(actors ...ActorClass) []Scope
- func (s ScopeSet) Scopes() []Scope
- func (s ScopeSet) ScopesAllowingOp(actor ActorClass, resourceType string, op AccessOp) []Scope
- func (s ScopeSet) SpaceSeparated() string
- func (s ScopeSet) Strings() []string
- func (s ScopeSet) SubsetOf(allowed ScopeSet) bool
- type SignatureVerifier
- type SignatureVerifierFunc
- type TokenClaims
- type TokenValidateOptions
- type TokenValidator
Constants ¶
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 ¶
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 = errors.New("smart: unauthorized") )
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 ¶
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 ¶
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 ¶
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 ¶
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 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.
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.
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.
type ReplayStore ¶
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) 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.
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.
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 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 ¶
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 ¶
ContainsAll reports whether every required raw scope string is present.
func (ScopeSet) LaunchScopes ¶
LaunchScopes returns launch-kind scopes.
func (ScopeSet) ResourceScopes ¶
func (s ScopeSet) ResourceScopes(actors ...ActorClass) []Scope
ResourceScopes returns resource permission scopes, optionally filtered by actor.
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 ¶
SpaceSeparated returns scopes joined by a single space (OAuth scope form).
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.
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.