oauth

package
v0.2.0 Latest Latest
Warning

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

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

README

pkg/oauth

Production-capable OAuth2/OIDC authorization server for SMART on FHIR.

Endpoints

Path Description
/.well-known/openid-configuration OIDC discovery
/.well-known/smart-configuration SMART metadata
/oauth/authorize Authorization code + PKCE
/oauth/token Token exchange (auth code, client credentials, refresh)
/oauth/revoke Revoke refresh tokens and JWT access tokens (by jti)
/oauth/introspect RFC 7662 token introspection (confidential clients only)
/oauth/jwks Signing key set
/oauth/login Session login for production consent (when UserAuthenticator is configured)
/t/{tenantId}/oauth/* Tenant-scoped OAuth routes (via MultiTenantServer)
/oauth/register Dynamic client registration (opt-in)
/oauth/consent Built-in HTML consent form
/oauth/launch EHR launch context (JSON)
/oauth/launch/ui EHR launch orchestration page

Use oauthstore.NewPostgresServer (or ApplyPostgresStores + oauth.NewServer) for multi-instance clusters. Postgres provides transactional DELETE … RETURNING consume semantics and row-level locking — no shared filesystem required.

import (
    "github.com/degoke/haistack/pkg/oauth"
    oauthstore "github.com/degoke/haistack/pkg/oauth/store"
    "github.com/degoke/haistack/pkg/postgres"
)

db, _ := postgres.Open(ctx, dsn)
_ = db.Migrate(ctx)

server, err := oauthstore.NewPostgresServer(oauth.Config{
    Issuer:             "https://auth.example",
    FHIRAudience:       "https://fhir.example",
    RequireConsentForm: true,
    LaunchResolver:     myLaunchResolver,
    UserAuthenticator:  myUserAuthenticator,
}, db.Pool())

oauthstore.PostgresStores wires:

  • AuthorizationStore — auth codes, refresh tokens, consent sessions
  • ClientRegistry — clients with bcrypt-hashed secrets
  • ReplayStore — backend/client-assertion jti replay protection
  • RevocationStore — revoked access-token jti denylist
  • TokenRateLimiter / RegisterRateLimiter — DB-backed endpoint rate limits
  • DB signing keys via ApplyPostgresSigningKey / ApplySQLiteSigningKey when OAUTH_SIGNING_KEY_ENCRYPTION_SECRET is set

Schema: migrations 0017_oauth.sql + 0018_oauth_rate_limit.sql + 0019_oauth_signing_key.sql + 0020_oauth_issuer_binding.sql + 0021_oauth_issuer_pk.sql + 0022_oauth_client_issuer.sql (Postgres), or 0014_oauth.sql + 0015_oauth_rate_limit.sql + 0016_oauth_signing_key.sql + 0017_oauth_issuer_binding.sql + 0018_oauth_issuer_pk.sql + 0019_oauth_client_issuer.sql (SQLite).

Auth codes, refresh tokens, and pending consent rows store an issuer column (and JSON issuer field) so a shared SQL store can enforce that tokens minted under /t/{tenantId}/ are only consumed by the matching tenant issuer.

Redis (ephemeral token state)

Use oauthredis.NewServer for TTL-backed auth codes, refresh tokens, replay JTIs, and revocation denylist. Client registration stays on Postgres or SQLite — pass a durable cfg.Clients registry; Redis does not store clients.

import (
    "github.com/degoke/haistack/pkg/oauth"
    oauthstore "github.com/degoke/haistack/pkg/oauth/store"
    oauthredis "github.com/degoke/haistack/pkg/oauth/redis"
    goredis "github.com/redis/go-redis/v9"
)

db, _ := postgres.Open(ctx, dsn)
_, clientStore, _, _ := oauthstore.PostgresStores(db.Pool())
rdb := goredis.NewClient(&goredis.Options{Addr: "localhost:6379"})
server, err := oauthredis.NewServer(oauth.Config{
    Issuer:  "https://auth.example",
    Clients: clientStore,
}, rdb, "hai:oauth:")

oauthredis.EphemeralStores wires the three ephemeral interfaces with TTL-based keys.

Client authentication at the token endpoint

Method Grants Server Client SDK
client_secret_post auth code, refresh, revoke Supported ClientAuthSecretPost (default)
client_secret_basic auth code, refresh, revoke Supported ClientAuthSecretBasic
private_key_jwt auth code, refresh, revoke, client credentials Supported ClientAuthPrivateKeyJWT + ClientJWT

Set TokenEndpointAuthMethod on each registered Client.

private_key_jwt example (auth code exchange)
form.Set("grant_type", "authorization_code")
form.Set("code", code)
form.Set("redirect_uri", redirectURI)
form.Set("client_assertion_type", "urn:ietf:params:oauth:client-assertion-type:jwt-bearer")
form.Set("client_assertion", signedJWT)
form.Set("code_verifier", pkceVerifier)

Access-token revocation

POST /oauth/revoke accepts:

  • refresh_token — deletes the refresh token when it belongs to the authenticated client
  • access_token (or token_type_hint=access_token) — adds the JWT jti to the revocation denylist when the token's client_id claim matches the authenticated client (required)

Revoked access tokens are rejected by server.BearerAuthConfig() via TokenValidateOptions.IsJWTRevoked. All access tokens include a client_id claim; revoke rejects tokens without it.

Production environment variables

Variable Purpose
OAUTH_REGISTRATION_TOKEN Bearer token for POST /oauth/register
OAUTH_SIGNING_KEY_ENCRYPTION_SECRET AES key for DB-stored signing keys (required for haistack serve production)
OAUTH_SESSION_SECRET HMAC secret for /oauth/login session cookies (required for production consent)
OAUTH_LOGIN_USERS Production login directory: username:password or username:$2a$... (newline or ; separated)

When OAUTH_SIGNING_KEY_ENCRYPTION_SECRET is unset, signing keys fall back to PEM at {state-dir}/oauth-signing.pem (oauth.DefaultSigningKeyPaths). Set OAUTH_SIGNING_KEY_ROTATE=1 before restart to rotate the active DB key.

Embedders that previously used oauth.NewProductionServer should call oauthstore.NewSQLiteServer or oauthstore.NewPostgresServer instead. Those APIs persist clients, authorization codes, refresh tokens, replay JTIs, and revocation across process restarts. oauth.NewServer without a store is in-memory only.

pkg/smart still has FileBackendClientStore / FileReplayStore for SMART backend-service assertion clients and jti replay — they are not the OAuth authorization-server stores.

Multi-instance checklist

  1. Use oauthstore.NewPostgresServer (recommended) or oauthstore.NewSQLiteServer for single-node.
  2. Persist signing keys in DB (OAUTH_SIGNING_KEY_ENCRYPTION_SECRET) or oauth-signing.pem across restarts.
  3. Set UserAuthenticator with a real user directory (or haistack serve production session login via OAUTH_LOGIN_USERS) for end-user consent binding.
  4. Keep AutoApprove: false in production.
  5. Enable AllowDynamicRegistration only when required.
  6. Mount tenant routes at /t/{tenantId}/ when using MultiTenantServer.

See examples/smart-oauth for a runnable demo, or haistack serve for built-in OAuth with SQLite/Postgres stores (runtime.WithBuiltinOAuth). Operations guidance: OPERATIONS.md.

Documentation

Overview

Package oauth provides a built-in OAuth2/OIDC authorization server for SMART on FHIR.

Hosts can mount oauth.Server alongside pkg/http FHIR handlers to issue and validate access tokens without an external authorization server. The server exposes:

  • /.well-known/openid-configuration
  • /.well-known/smart-configuration
  • /oauth/authorize
  • /oauth/token
  • /oauth/jwks
  • /oauth/register

Durable state is provided by pkg/oauth/store (Postgres or SQLite). haistack serve wires builtin OAuth via runtime.WithBuiltinOAuth when oauth.enabled is true.

Index

Constants

View Source
const (
	AuthMethodClientSecretPost  = "client_secret_post"
	AuthMethodClientSecretBasic = "client_secret_basic"
	AuthMethodPrivateKeyJWT     = "private_key_jwt"
	AuthMethodNone              = "none"
)
View Source
const DefaultPendingAuthorizationCleanupInterval = 5 * time.Minute

DefaultPendingAuthorizationCleanupInterval is the recommended background purge interval for SQL-backed consent sessions in production-like hosts.

View Source
const LoginUsersEnv = "OAUTH_LOGIN_USERS"

LoginUsersEnv is the production username/password directory. Entries are `username:password` or `username:$2a$...` separated by newlines or `;`.

Variables

View Source
var ErrInvalidConfig = errors.New("oauth: invalid config")

ErrInvalidConfig indicates invalid OAuth server configuration.

View Source
var ErrInvalidScope = errors.New("oauth: invalid scope")

ErrInvalidScope indicates a requested OAuth scope is not allowed.

Functions

func ApplyProductionDefaults

func ApplyProductionDefaults(cfg *Config) error

ApplyProductionDefaults applies safer OAuth defaults for production-like hosts. Call after store wiring and before NewServer.

func CombineHandlers

func CombineHandlers(primary http.Handler, extras ...http.Handler) http.Handler

CombineHandlers mounts multiple OAuth handlers on one mux by path prefix.

func DecryptSigningKeyPEM

func DecryptSigningKeyPEM(ciphertext, nonce, secret string) ([]byte, error)

DecryptSigningKeyPEM decrypts a PEM-encoded private key encrypted with EncryptSigningKeyPEM.

func DefaultRegisteredClientScopes

func DefaultRegisteredClientScopes() []string

DefaultRegisteredClientScopes is the SMART scope allow-list applied to dynamically registered clients that omit scope, and the maximum scopes DCR may request.

func EncryptSigningKeyPEM

func EncryptSigningKeyPEM(pem []byte, secret string) (ciphertext string, nonce string, err error)

EncryptSigningKeyPEM encrypts a PEM-encoded private key with AES-GCM.

func EntryIssuerMatches

func EntryIssuerMatches(entryIssuer, serverIssuer string) bool

EntryIssuerMatches reports whether a stored row belongs to serverIssuer. Both issuers must be non-empty and equal after normalization.

func HashLoginPassword

func HashLoginPassword(password string) (string, error)

HashLoginPassword returns a bcrypt hash of password.

func IssuerScopedKey

func IssuerScopedKey(issuer, id string) (string, error)

IssuerScopedKey returns a map key unique to one issuer and token/code/session id.

func NormalizeIssuerURL

func NormalizeIssuerURL(issuer string) string

NormalizeIssuerURL trims and removes a trailing slash from an issuer URL.

func PrepareClientSecret

func PrepareClientSecret(client *Client) error

PrepareClientSecret hashes plaintext client secrets before persistence.

func RequireBoundIssuer

func RequireBoundIssuer(issuer string) (string, error)

RequireBoundIssuer returns a normalized issuer or an error when missing.

func RequireSigningKeyEncryptionSecret

func RequireSigningKeyEncryptionSecret() error

RequireSigningKeyEncryptionSecret returns an error when secret is empty.

func RunPendingAuthorizationCleanup

func RunPendingAuthorizationCleanup(ctx context.Context, store AuthorizationStore, interval time.Duration)

RunPendingAuthorizationCleanup periodically purges expired consent sessions until ctx is cancelled.

func SaveKeySetToPEM

func SaveKeySetToPEM(path string, key *KeySet) error

SaveKeySetToPEM writes an RSA private key to path, creating parent directories as needed.

func ServeConsentPage

func ServeConsentPage(w http.ResponseWriter, req AuthorizationRequest, csrfToken string)

ServeConsentPage writes a minimal HTML consent form for pending authorization requests.

func SigningKeyEncryptionSecret

func SigningKeyEncryptionSecret() string

SigningKeyEncryptionSecret returns the configured signing-key encryption secret.

func SigningKeyRotateOnStartup

func SigningKeyRotateOnStartup() bool

SigningKeyRotateOnStartup reports whether signing keys should rotate on process start.

func StartPendingAuthorizationCleanup

func StartPendingAuthorizationCleanup(ctx context.Context, store AuthorizationStore, interval time.Duration)

StartPendingAuthorizationCleanup runs RunPendingAuthorizationCleanup in a background goroutine.

func ValidateProductionIssuer

func ValidateProductionIssuer(issuer string) error

ValidateProductionIssuer requires a non-empty https issuer URL.

func ValidateRedirectURI

func ValidateRedirectURI(raw string) error

ValidateRedirectURI checks redirect URIs allowed for dynamic client registration.

Types

type AuthorizationCode

type AuthorizationCode struct {
	Issuer      string    `json:"issuer,omitempty"`
	ClientID    string    `json:"clientId"`
	RedirectURI string    `json:"redirectUri"`
	Scope       string    `json:"scope"`
	Patient     string    `json:"patient,omitempty"`
	Encounter   string    `json:"encounter,omitempty"`
	Subject     string    `json:"subject,omitempty"`
	FHIRUser    string    `json:"fhirUser,omitempty"`
	Challenge   string    `json:"challenge,omitempty"`
	Method      string    `json:"method,omitempty"`
	ExpiresAt   time.Time `json:"expiresAt"`
}

AuthorizationCode is a short-lived authorization code entry.

type AuthorizationRequest

type AuthorizationRequest struct {
	ClientID            string
	RedirectURI         string
	Scope               string
	State               string
	Patient             string
	Encounter           string
	Subject             string
	FHIRUser            string
	Launch              string
	CodeChallenge       string
	CodeChallengeMethod string
}

AuthorizationRequest captures parameters from the authorize endpoint.

type AuthorizationStore

type AuthorizationStore interface {
	SaveAuthorizationCode(code string, entry AuthorizationCode) error
	ConsumeAuthorizationCode(issuer, code string) (AuthorizationCode, bool)
	SaveRefreshToken(token string, entry RefreshTokenEntry) error
	ConsumeRefreshToken(issuer, token string) (RefreshTokenEntry, bool)
	LookupRefreshToken(issuer, token string) (RefreshTokenEntry, bool)
	SavePendingAuthorization(id string, entry PendingAuthorization) error
	GetPendingAuthorization(issuer, id string) (PendingAuthorization, bool)
	ConsumePendingAuthorization(issuer, id string) (PendingAuthorization, bool)
	DeleteRefreshTokenForClient(issuer, token, clientID string) bool
	// PurgeExpiredPendingAuthorizations removes expired consent sessions.
	PurgeExpiredPendingAuthorizations() int
}

AuthorizationStore persists authorization codes, refresh tokens, and pending authorization sessions. Production deployments use pkg/oauth/store (SQLite or Postgres).

type BcryptLoginUsers

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

BcryptLoginUsers is a static username → bcrypt-hash directory.

func ParsePasswordUsers

func ParsePasswordUsers(raw string) (*BcryptLoginUsers, error)

ParsePasswordUsers parses OAUTH_LOGIN_USERS contents.

func PasswordUsersFromEnv

func PasswordUsersFromEnv() (*BcryptLoginUsers, error)

PasswordUsersFromEnv loads OAUTH_LOGIN_USERS.

func RequirePasswordUsersFromEnv

func RequirePasswordUsersFromEnv() (*BcryptLoginUsers, error)

RequirePasswordUsersFromEnv requires a non-empty production login directory.

func (*BcryptLoginUsers) Verify

func (u *BcryptLoginUsers) Verify(username, password string) (UserIdentity, bool)

Verify implements LoginUserStore.

type Client

type Client struct {
	ClientID                string
	ClientSecret            string
	ClientSecretHash        string
	ClientName              string
	RedirectURIs            []string
	GrantTypes              []string
	ResponseTypes           []string
	Scopes                  []string
	TokenEndpointAuthMethod string
	PublicKeyPEM            string
	KeyID                   string
	Algorithm               string
}

Client describes a registered OAuth client.

func (Client) ToBackendClient

func (c Client) ToBackendClient() smart.BackendClient

ToBackendClient converts client key metadata for backend assertion validation.

type ClientRegistry

type ClientRegistry interface {
	Get(clientID string) (Client, bool)
	Register(client Client) error
}

ClientRegistry stores registered OAuth clients.

type ClientStore

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

ClientStore stores registered OAuth clients in memory.

func NewClientStore

func NewClientStore() *ClientStore

NewClientStore constructs an empty client store.

func (*ClientStore) ForIssuer

func (s *ClientStore) ForIssuer(string) ClientRegistry

ForIssuer returns an empty in-memory registry so tenants do not share clients.

func (*ClientStore) Get

func (s *ClientStore) Get(clientID string) (Client, bool)

Get returns a registered client.

func (*ClientStore) Register

func (s *ClientStore) Register(client Client) error

Register adds or replaces a client.

type Config

type Config struct {
	Issuer             string
	FHIRAudience       string
	SigningKey         *KeySet
	Clients            ClientRegistry
	AuthorizationStore AuthorizationStore
	ReplayStore        smart.ReplayStore
	RevocationStore    TokenRevocationStore
	AccessTokenTTL     time.Duration
	RefreshTokenTTL    time.Duration
	AuthCodeTTL        time.Duration
	Now                func() time.Time
	// ConsentHandler approves authorization requests. When nil and AutoApprove is false,
	// the authorize endpoint rejects requests.
	ConsentHandler ConsentHandler
	// AutoApprove issues authorization codes without consent review. Use only in tests.
	AutoApprove bool
	// RequireConsentForm redirects to a built-in HTML consent page before issuing codes.
	RequireConsentForm bool
	// AllowDynamicRegistration enables POST /oauth/register. Disabled by default.
	AllowDynamicRegistration bool
	// RegistrationAccessToken protects POST /oauth/register when set.
	RegistrationAccessToken string
	// LaunchResolver resolves EHR launch tokens for /oauth/launch and authorize.
	LaunchResolver LaunchResolver
	// UserAuthenticator identifies the end user approving access in production flows.
	UserAuthenticator UserAuthenticator
	// LoginPath redirects unauthenticated authorize requests when UserAuthenticator is set.
	LoginPath string
	// RateLimit configures token and registration endpoint rate limits.
	RateLimit RateLimitConfig
	// TokenRateLimiter overrides the default in-memory token endpoint limiter.
	TokenRateLimiter RateLimitStore
	// RegisterRateLimiter overrides the default in-memory registration limiter.
	RegisterRateLimiter RateLimitStore
	// VerificationKeys are additional public keys exposed via JWKS (for rotation).
	VerificationKeys []*KeySet
	// RequirePKCEForAllClients requires code_challenge for every client at authorize.
	RequirePKCEForAllClients bool
	// RegisteredClientScopes limits scopes for dynamic client registration.
	RegisteredClientScopes []string
}

Config configures a built-in OAuth2/OIDC authorization server.

type ConsentHandler

type ConsentHandler interface {
	Approve(ctx context.Context, req AuthorizationRequest) (bool, error)
}

ConsentHandler approves or denies authorization requests before codes are issued. When nil, the server auto-approves (development mode only).

func AutoApproveConsentHandler

func AutoApproveConsentHandler() ConsentHandler

AutoApproveConsentHandler always approves authorization requests.

type ConsentHandlerFunc

type ConsentHandlerFunc func(ctx context.Context, req AuthorizationRequest) (bool, error)

ConsentHandlerFunc adapts a function to ConsentHandler.

func (ConsentHandlerFunc) Approve

Approve implements ConsentHandler.

type IntrospectionResponse

type IntrospectionResponse struct {
	Active    bool   `json:"active"`
	Scope     string `json:"scope,omitempty"`
	ClientID  string `json:"client_id,omitempty"`
	Username  string `json:"username,omitempty"`
	TokenType string `json:"token_type,omitempty"`
	Exp       int64  `json:"exp,omitempty"`
	Iat       int64  `json:"iat,omitempty"`
	Sub       string `json:"sub,omitempty"`
	Aud       string `json:"aud,omitempty"`
	Iss       string `json:"iss,omitempty"`
	JTI       string `json:"jti,omitempty"`
	Patient   string `json:"patient,omitempty"`
	FHIRUser  string `json:"fhirUser,omitempty"`
	Tenant    string `json:"tenant,omitempty"`
}

IntrospectionResponse is the RFC 7662 token introspection payload.

type IssuerScopedClientRegistry

type IssuerScopedClientRegistry interface {
	ForIssuer(issuer string) ClientRegistry
}

IssuerScopedClientRegistry can return an issuer-isolated client registry view.

type KeySet

type KeySet struct {
	PrivateKey *rsa.PrivateKey
	KeyID      string
	Algorithm  string
	// RetireAt is when a rotated key leaves JWKS and verification. Zero means active.
	RetireAt time.Time
}

KeySet holds signing keys exposed through JWKS.

func LoadKeySetFromPEM

func LoadKeySetFromPEM(path string, keyID string) (*KeySet, error)

LoadKeySetFromPEM loads an RSA signing key from a PKCS#8 or PKCS#1 PEM file.

func LoadOrCreateSigningKey

func LoadOrCreateSigningKey(path string, keyID string) (*KeySet, error)

LoadOrCreateSigningKey loads a PEM signing key from path or generates and persists one.

func LoadSigningKey

func LoadSigningKey(paths SigningKeyPaths) (*KeySet, error)

LoadSigningKey loads a persistent signing key when the PEM file exists.

func NewKeySet

func NewKeySet(bits int) (*KeySet, error)

NewKeySet generates an RSA signing key set.

func (*KeySet) JWKS

func (k *KeySet) JWKS() map[string]any

JWKS returns a JWKS document for the public key.

func (*KeySet) PublicKeyPEM

func (k *KeySet) PublicKeyPEM() (string, error)

PublicKeyPEM returns PKIX PEM for the public key.

func (*KeySet) Published

func (k *KeySet) Published(now time.Time) bool

Published reports whether the key should still appear in JWKS and verify tokens.

type LaunchContext

type LaunchContext struct {
	PatientID string
	Encounter string
	Intent    string
	NeedPI    bool
}

LaunchContext is the SMART EHR launch context returned from /oauth/launch.

type LaunchResolver

type LaunchResolver interface {
	ResolveLaunch(ctx context.Context, launch string, iss string) (LaunchContext, error)
}

LaunchResolver resolves a launch token into SMART launch context.

func StaticLaunchResolver

func StaticLaunchResolver(ctx LaunchContext) LaunchResolver

StaticLaunchResolver returns fixed launch context for demos and tests.

type LaunchResolverFunc

type LaunchResolverFunc func(ctx context.Context, launch string, iss string) (LaunchContext, error)

LaunchResolverFunc adapts a function to LaunchResolver.

func (LaunchResolverFunc) ResolveLaunch

func (f LaunchResolverFunc) ResolveLaunch(ctx context.Context, launch string, iss string) (LaunchContext, error)

type LoginUserStore

type LoginUserStore interface {
	Verify(username, password string) (UserIdentity, bool)
}

LoginUserStore verifies end-user passwords for session login.

type MemoryAuthorizationStore

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

MemoryAuthorizationStore is a process-local AuthorizationStore.

func NewMemoryAuthorizationStore

func NewMemoryAuthorizationStore() *MemoryAuthorizationStore

NewMemoryAuthorizationStore constructs an in-memory authorization store.

func NewTokenStore

func NewTokenStore() *MemoryAuthorizationStore

NewTokenStore constructs an in-memory authorization store.

func (*MemoryAuthorizationStore) ConsumeAuthorizationCode

func (s *MemoryAuthorizationStore) ConsumeAuthorizationCode(issuer, code string) (AuthorizationCode, bool)

func (*MemoryAuthorizationStore) ConsumePendingAuthorization

func (s *MemoryAuthorizationStore) ConsumePendingAuthorization(issuer, id string) (PendingAuthorization, bool)

func (*MemoryAuthorizationStore) ConsumeRefreshToken

func (s *MemoryAuthorizationStore) ConsumeRefreshToken(issuer, token string) (RefreshTokenEntry, bool)

func (*MemoryAuthorizationStore) DeleteRefreshTokenForClient

func (s *MemoryAuthorizationStore) DeleteRefreshTokenForClient(issuer, token, clientID string) bool

func (*MemoryAuthorizationStore) GetPendingAuthorization

func (s *MemoryAuthorizationStore) GetPendingAuthorization(issuer, id string) (PendingAuthorization, bool)

func (*MemoryAuthorizationStore) LookupRefreshToken

func (s *MemoryAuthorizationStore) LookupRefreshToken(issuer, token string) (RefreshTokenEntry, bool)

func (*MemoryAuthorizationStore) PurgeExpiredPendingAuthorizations

func (s *MemoryAuthorizationStore) PurgeExpiredPendingAuthorizations() int

func (*MemoryAuthorizationStore) SaveAuthorizationCode

func (s *MemoryAuthorizationStore) SaveAuthorizationCode(code string, entry AuthorizationCode) error

func (*MemoryAuthorizationStore) SavePendingAuthorization

func (s *MemoryAuthorizationStore) SavePendingAuthorization(id string, entry PendingAuthorization) error

func (*MemoryAuthorizationStore) SaveRefreshToken

func (s *MemoryAuthorizationStore) SaveRefreshToken(token string, entry RefreshTokenEntry) error

type MemoryTokenRevocationStore

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

MemoryTokenRevocationStore is a process-local revocation denylist.

func NewMemoryTokenRevocationStore

func NewMemoryTokenRevocationStore() *MemoryTokenRevocationStore

NewMemoryTokenRevocationStore constructs an in-memory revocation store.

func (*MemoryTokenRevocationStore) IsRevoked

func (s *MemoryTokenRevocationStore) IsRevoked(jti string) bool

func (*MemoryTokenRevocationStore) Revoke

func (s *MemoryTokenRevocationStore) Revoke(jti string, expiresAt time.Time) error

type MultiTenantBearerAuth

type MultiTenantBearerAuth struct {
	Base    *Server
	Tenants *MultiTenantServer
	Adapter *smart.AuthAdapter
}

MultiTenantBearerAuth validates Bearer tokens issued by the base OAuth server or any registered tenant issuer.

func (MultiTenantBearerAuth) BearerConfigForRequest

func (m MultiTenantBearerAuth) BearerConfigForRequest(r *http.Request) (smart.BearerAuthConfig, error)

BearerConfigForRequest selects the bearer validation config for the request token issuer.

func (MultiTenantBearerAuth) BundleResolver

func (m MultiTenantBearerAuth) BundleResolver() hahttp.AuthBundleResolver

BundleResolver returns an HTTP auth bundle resolver for multi-tenant OAuth tokens.

func (MultiTenantBearerAuth) PrincipalResolver

func (m MultiTenantBearerAuth) PrincipalResolver() hahttp.PrincipalResolver

PrincipalResolver returns an HTTP principal resolver for multi-tenant OAuth tokens.

func (MultiTenantBearerAuth) ResolveBearerTokenCached

func (m MultiTenantBearerAuth) ResolveBearerTokenCached(ctx context.Context, r *http.Request) (smart.BearerAuthResult, error)

ResolveBearerTokenCached validates the Bearer token against the matching issuer.

type MultiTenantConfig

type MultiTenantConfig struct {
	Base    Config
	Tenants *TenantRegistry
}

MultiTenantConfig configures a shared OAuth backend with per-tenant issuers.

type MultiTenantServer

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

MultiTenantServer hosts OAuth endpoints for multiple tenant issuers.

func NewMultiTenantServer

func NewMultiTenantServer(cfg MultiTenantConfig) (*MultiTenantServer, error)

NewMultiTenantServer validates config and returns a multi-tenant OAuth server.

func (*MultiTenantServer) Handler

func (m *MultiTenantServer) Handler() http.Handler

Handler mounts tenant-scoped routes under /t/{tenantID}/.

func (*MultiTenantServer) LookupByIssuer

func (m *MultiTenantServer) LookupByIssuer(issuer string) (TenantIssuerConfig, error)

LookupByIssuer returns tenant configuration for a token issuer URL.

func (*MultiTenantServer) ServerForTenant

func (m *MultiTenantServer) ServerForTenant(tenantID string) (*Server, error)

ServerForTenant returns a tenant-scoped authorization server view.

type PendingAuthorization

type PendingAuthorization struct {
	Issuer    string               `json:"issuer,omitempty"`
	Request   AuthorizationRequest `json:"request"`
	Subject   string               `json:"subject,omitempty"`
	FHIRUser  string               `json:"fhirUser,omitempty"`
	CSRFToken string               `json:"csrfToken,omitempty"`
	ExpiresAt time.Time            `json:"expiresAt"`
}

PendingAuthorization stores an in-progress authorize/consent/launch session.

type RateLimitConfig

type RateLimitConfig struct {
	TokenRequests    int
	RegisterRequests int
	LoginRequests    int
	LoginIPRequests  int
	Window           time.Duration
}

RateLimitConfig configures OAuth endpoint rate limits.

type RateLimitStore

type RateLimitStore interface {
	Allow(ctx context.Context, endpoint, bucketKey string, limit int, window time.Duration, now time.Time) (bool, error)
}

RateLimitStore persists or tracks OAuth endpoint request counters.

type RefreshTokenEntry

type RefreshTokenEntry struct {
	Issuer    string    `json:"issuer,omitempty"`
	ClientID  string    `json:"clientId"`
	Scope     string    `json:"scope"`
	Patient   string    `json:"patient,omitempty"`
	Encounter string    `json:"encounter,omitempty"`
	Subject   string    `json:"subject"`
	FHIRUser  string    `json:"fhirUser,omitempty"`
	ExpiresAt time.Time `json:"expiresAt"`
}

RefreshTokenEntry stores refresh-token metadata.

type Server

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

Server is a SMART-compatible OAuth2/OIDC authorization server.

func NewServer

func NewServer(cfg Config) (*Server, error)

NewServer constructs an authorization server.

func (*Server) BackendAssertionAuthConfig

func (s *Server) BackendAssertionAuthConfig(adapter *smart.AuthAdapter) smart.BackendAssertionAuthConfig

BackendAssertionAuthConfig validates backend client assertions for registered clients.

func (*Server) BearerAuthConfig

func (s *Server) BearerAuthConfig(adapter *smart.AuthAdapter) smart.BearerAuthConfig

BearerAuthConfig returns SMART bearer validation wired to this server's signing and verification keys.

func (*Server) Handler

func (s *Server) Handler() http.Handler

Handler mounts OAuth/OIDC discovery and protocol endpoints on the issuer prefix.

func (*Server) IntrospectToken

func (s *Server) IntrospectToken(token, tokenTypeHint string) IntrospectionResponse

IntrospectToken validates a token and returns RFC 7662 metadata.

func (*Server) Issuer

func (s *Server) Issuer() string

Issuer returns the configured issuer URL.

func (*Server) RegisterClient

func (s *Server) RegisterClient(client Client) error

RegisterClient registers an OAuth client.

func (*Server) SigningPrivateKey

func (s *Server) SigningPrivateKey() *rsa.PrivateKey

SigningPrivateKey returns the RSA private key used to sign access tokens.

type SessionAuthConfig

type SessionAuthConfig struct {
	Secret     string
	TTL        time.Duration
	Now        func() time.Time
	Issuer     string
	CookiePath string
	Users      LoginUserStore
}

SessionAuthConfig configures signed cookie sessions for production consent login.

type SessionUserAuthenticator

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

SessionUserAuthenticator authenticates users from signed session cookies.

func NewSessionUserAuthenticator

func NewSessionUserAuthenticator(cfg SessionAuthConfig) (*SessionUserAuthenticator, error)

NewSessionUserAuthenticator constructs a cookie session authenticator.

func (*SessionUserAuthenticator) AuthenticateUser

func (a *SessionUserAuthenticator) AuthenticateUser(r *http.Request) (UserIdentity, bool)

func (*SessionUserAuthenticator) ForIssuer

func (a *SessionUserAuthenticator) ForIssuer(issuer, cookiePath string) *SessionUserAuthenticator

ForIssuer returns a copy bound to issuer and cookie path (tenant isolation).

func (*SessionUserAuthenticator) SetSession

func (a *SessionUserAuthenticator) SetSession(w http.ResponseWriter, subject string) error

type SigningKeyPaths

type SigningKeyPaths struct {
	SigningKey string
	SigningKID string
}

SigningKeyPaths names the PEM signing-key fallback on disk. Token, client, replay, and revocation state use pkg/oauth/store (SQLite or Postgres).

func DefaultSigningKeyPaths

func DefaultSigningKeyPaths(stateDir string) SigningKeyPaths

DefaultSigningKeyPaths returns the conventional PEM path and key id under stateDir.

type TenantIssuerConfig

type TenantIssuerConfig struct {
	TenantID          string
	Issuer            string
	FHIRAudience      string
	SigningKey        *KeySet
	Clients           ClientRegistry
	AutoApprove       *bool
	ConsentHandler    ConsentHandler
	UserAuthenticator UserAuthenticator
	LoginPath         string
}

TenantIssuerConfig describes OAuth issuer settings for one tenant namespace.

type TenantRegistry

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

TenantRegistry stores per-tenant issuer configuration.

func NewTenantRegistry

func NewTenantRegistry() *TenantRegistry

NewTenantRegistry returns an empty tenant registry.

func (*TenantRegistry) IDs

func (r *TenantRegistry) IDs() []string

IDs returns registered tenant ids.

func (*TenantRegistry) Lookup

func (r *TenantRegistry) Lookup(tenantID string) (TenantIssuerConfig, error)

Lookup returns configuration for a tenant id.

func (*TenantRegistry) LookupByIssuer

func (r *TenantRegistry) LookupByIssuer(issuer string) (TenantIssuerConfig, error)

LookupByIssuer returns tenant configuration matching an OAuth issuer URL.

func (*TenantRegistry) Register

func (r *TenantRegistry) Register(cfg TenantIssuerConfig) error

Register upserts a tenant issuer configuration.

type TokenRevocationStore

type TokenRevocationStore interface {
	Revoke(jti string, expiresAt time.Time) error
	IsRevoked(jti string) bool
}

TokenRevocationStore records revoked access-token JTIs until natural expiry.

type TokenStore deprecated

type TokenStore = MemoryAuthorizationStore

Deprecated: use AuthorizationStore via Config.AuthorizationStore. TokenStore remains as a thin alias for tests migrating to AuthorizationStore.

type UserAuthenticator

type UserAuthenticator interface {
	AuthenticateUser(r *http.Request) (UserIdentity, bool)
}

UserAuthenticator identifies the human user approving SMART authorization.

func StaticUserAuthenticator

func StaticUserAuthenticator(user UserIdentity) UserAuthenticator

StaticUserAuthenticator returns a fixed user for demos and tests.

type UserAuthenticatorFunc

type UserAuthenticatorFunc func(r *http.Request) (UserIdentity, bool)

UserAuthenticatorFunc adapts a function to UserAuthenticator.

func (UserAuthenticatorFunc) AuthenticateUser

func (f UserAuthenticatorFunc) AuthenticateUser(r *http.Request) (UserIdentity, bool)

type UserIdentity

type UserIdentity struct {
	Subject  string
	FHIRUser string
}

UserIdentity is an authenticated end-user at the authorization server.

Directories

Path Synopsis
Package store provides durable OAuth authorization state backed by Postgres or SQLite.
Package store provides durable OAuth authorization state backed by Postgres or SQLite.

Jump to

Keyboard shortcuts

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