auth

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: 15 Imported by: 0

README

haistack-auth (pkg/auth)

Shared identity and policy library for HAIStack. It answers authorization questions for the rest of the stack — not HTTP auth flows, database user tables, or SMART launch logic.

What it does

v1 centers on principals, roles, permissions, tenant context, device trust, and a deny-by-default policy DSL:

  • CanReadResource / CanWriteResource — FHIR resource access
  • CanExecuteView — view execution with declared permissions
  • CanExecuteAITool — AI tool execution
  • CanPushDeviceEvent — sync device trust for a tenant
  • CanInstallModule — module install authorization
  • CanBulkExport — bulk export authorization (when wired)
  • CheckPatientScope — patient-level compartment enforcement

Adapters wire into existing seams:

  • ViewAuthorizer → view.Authorizer
  • AIPolicyAdapter → ai.PolicyEngine
  • AuditingEngine → optional emit of allow/deny through pkg/audit (auth does not own audit storage)

What it does not do

  • Issue or validate OAuth2/OIDC tokens (see pkg/oauth, pkg/smart)
  • Store users in SQL — supply Catalog data from the host application
  • Enforce consent, break-glass, or security labels
  • Replace SMART scope parsing — intersect scopes in middleware, then call the engine

How it fits in the ecosystem

  HTTP / SMART middleware          pkg/view / pkg/ai / pkg/modules / pkg/sync
              |                              |
              v                              v
        resolve Principal + TenantContext
              |
              v
         auth.Engine (policy DSL + Catalog)
              |
              +---- ViewAuthorizer ----> view.Executor
              +---- AIPolicyAdapter ---> ai.Executor
              +---- direct APIs ------> CanInstallModule, CanPushDeviceEvent, ...
              |
              v (optional)
         AuditingEngine ----> pkg/audit.LogAuthDecision
Direction Package Relationship
Peer smart Scopes/tokens parsed upstream; engine evaluates tenant policy
Peer view ViewAuthorizer implements view.Authorizer
Peer ai AIPolicyAdapter implements ai.PolicyEngine + optional AIConstraints
Peer audit Decision emit only; no storage ownership
Peer modules CanInstallModule before install/upgrade
Peer sync CanPushDeviceEvent for trusted device checks
Peer export CanBulkExport when bulk jobs require explicit allow rules
Downstream testkit/authztest Scenario catalog for CI matrices (not production import)

When to use it

  • Centralizing allow/deny for FHIR reads/writes beyond coarse SMART scopes
  • Wiring view execution permissions to roles and named views
  • Gating AI tools with the same principals used for human users
  • Validating sync device identity before accepting push batches
  • Authorizing module installs per tenant and module name
  • Enforcing patient compartment rules for portal or scoped agents

Usage modes

1. Standalone engine (in-memory catalog)

Load roles, principals, devices, and policy bytes at process startup — typical for edge nodes and tests:

eng, err := auth.NewEngine(auth.Config{
    Roles:       []auth.Role{/* ... */},
    Principals:  []auth.Principal{/* ... */},
    Devices:     []auth.DeviceIdentity{/* ... */},
    PolicyBytes: policyJSON,
})
2. View layer adapter

Map HTTP/session actors to principals once, then reuse ViewAuthorizer on every Execute:

authorizer := &auth.ViewAuthorizer{
    Engine:   eng,
    TenantID: "tenant-a",
    Resolve: func(ctx context.Context, actor, subject string) (auth.Principal, auth.TenantContext, error) {
        p, err := eng.Catalog().GetPrincipal(actor)
        return p, auth.TenantContext{TenantID: "tenant-a"}, err
    },
}
3. AI policy adapter (engine + field constraints)

Use AIPolicyAdapter when auth rules should drive tool allow-lists; narrow read/search/write/view shapes with AIConstraints:

policy := &auth.AIPolicyAdapter{
    Engine:      eng,
    TenantID:    "tenant-a",
    Resolve:     resolveActor,
    Constraints: &auth.AIConstraints{ /* Search/Write maps */ },
}
exec, err := ai.NewExecutor(ai.Config{Policy: policy, /* ... */ })
4. Audited decisions

Wrap the engine to append audit rows without changing call sites:

audited := &auth.AuditingEngine{
    Engine: eng,
    Log:    auditLogger, // audit.Logger
}
d, err := audited.CanReadResource(ctx, req)
5. Device and sync authorization

Register devices in Catalog and match policy rules on push-device-event:

d, err := eng.CanPushDeviceEvent(ctx, auth.DevicePushRequest{
    Principal: devicePrincipal,
    Tenant:    auth.TenantContext{TenantID: "tenant-a"},
    DeviceID:  "device-1",
})
6. YAML/JSON policy reload (application-owned)

Parse and compile policy separately when the host app hot-reloads rules:

compiled, err := auth.ParseAndCompilePolicy(policyBytes, auth.PolicyFormatJSON)
eng, err := auth.NewEngine(auth.Config{Compiled: compiled, /* catalog */ })

Examples

Build an engine:

eng, err := auth.NewEngine(auth.Config{
    Roles: []auth.Role{{
        Name: "clinician",
        Permissions: []auth.Permission{
            "appointment.read",
            "read-patient-summary",
            "module.install",
        },
    }},
    Principals: []auth.Principal{{
        ID:   "user-1",
        Kind: auth.KindUser,
        TenantBindings: []auth.TenantBinding{{
            TenantID: "tenant-a",
            Roles:    []string{"clinician"},
        }},
    }},
    Devices: []auth.DeviceIdentity{{
        DeviceID: "device-1",
        TenantID: "tenant-a",
        Status:   auth.DeviceStatusActive,
        Trusted:  true,
    }},
    PolicyBytes: []byte(`{
      "version": "1",
      "rules": [
        {
          "name": "appointment-rw",
          "effect": "allow",
          "match": {
            "actions": ["read", "write"],
            "resourceTypes": ["Appointment"],
            "anyPermissions": ["appointment.read"]
          },
          "reason": "clinicians may access appointments"
        },
        {
          "name": "device-push",
          "effect": "allow",
          "match": {
            "actions": ["push-device-event"],
            "deviceTrusted": true,
            "deviceStatuses": ["active"]
          }
        },
        {
          "name": "install-scheduling",
          "effect": "allow",
          "match": {
            "actions": ["install-module"],
            "moduleNames": ["scheduling"],
            "roles": ["clinician"]
          }
        }
      ]
    }`),
})

Authorize a read:

d, err := eng.CanReadResource(ctx, auth.ReadRequest{
    Principal:    principal,
    Tenant:       auth.TenantContext{TenantID: "tenant-a"},
    ResourceType: "Appointment",
    ID:           "appt-1",
})
// d.Allowed, d.Reason

Execute view and AI tool checks:

viewDecision, err := eng.CanExecuteView(ctx, auth.ViewRequest{
    Principal: principal,
    Tenant:    auth.TenantContext{TenantID: "tenant-a"},
    ViewName:  "patient_summary_view",
})
toolDecision, err := eng.CanExecuteAITool(ctx, auth.AIToolRequest{
    Principal: principal,
    Tenant:    auth.TenantContext{TenantID: "tenant-a"},
    ToolName:  "read_fhir_resource",
})

Patient compartment:

scoped := auth.TenantContext{
    TenantID:     "tenant-a",
    PatientScope: "pat-1",
}
d, err := eng.CheckPatientScope(ctx, auth.PatientScopeRequest{
    Principal: portalUser,
    Tenant:    scoped,
    PatientID: "pat-1",
})
// Reads outside the compartment are denied via CanReadResource + scoped TenantContext

Module install:

d, err := eng.CanInstallModule(ctx, auth.ModuleInstallRequest{
    Principal:  installer,
    Tenant:     auth.TenantContext{TenantID: "tenant-a"},
    ModuleName: "scheduling",
})

Policy DSL

Rules are loaded from JSON or YAML, compiled in memory, and evaluated in order. The first matching rule wins. When no rule matches, access is denied.

Match fields (empty = any):

Field Meaning
principalKinds user, device, service, ai-agent
tenants tenant ids (* wildcard)
roles any overlapping role
anyPermissions / allPermissions permission checks
resourceTypes FHIR resource type
actions read, write, execute-view, …
viewNames / toolNames / moduleNames named targets
purposeOfUse simple attribute match
deviceTrusted / deviceStatuses device trust
patientScoped whether tenant patient scope is set

Permissions treat appointment.read and read-appointment as equivalent.

Safety model

  • Deny by default
  • Explicit allow rules
  • Tenant binding required for user principals
  • Device push requires registered, trusted, active device for the target tenant
  • Patient compartment: scoped principals may only access their patient id and linked resources
  • Persistence is application-owned; Catalog is in-memory by default

Where it fits

Layer Role
auth Identity and policy decisions (this package)
audit Shared audit event library; auth may emit via AuditingEngine
view Consumes ViewAuthorizer
ai Consumes AIPolicyAdapter
modules Asks CanInstallModule before install
sync Asks CanPushDeviceEvent for device trust
smart Optional SMART scopes/tokens/launch via pkg/smart adapters (out of scope here)

Testing

go test ./pkg/auth/... -count=1

For cross-package authorization matrices, use pkg/testkit/authztest (RunAll, YAML catalogues) — production code must not import testkit.

Limits

  • No OAuth2/OIDC or SMART scopes (see pkg/smart)
  • No consent engine or security labels
  • No break-glass workflow
  • No full ABAC attribute language
  • No DB user tables — supply principals/roles/devices from the host app

Documentation

Overview

Package auth implements haistack-auth, the shared identity and policy library for HAIStack.

Scope

v1 answers authorization questions for the rest of the stack. It does not own HTTP auth flows, database user tables, OAuth2/OIDC, or SMART launch logic.

Contained in v1:

  • Principal, Role, Permission
  • TenantContext
  • DeviceIdentity and trust state
  • PolicyEngine / Engine decision APIs
  • Patient-level compartment enforcement (CheckPatientScope)
  • Module install checks
  • Core policy DSL (JSON/YAML)
  • Adapters for view.Authorizer and ai.PolicyEngine
  • Optional AuditingEngine wrapper that emits decisions via pkg/audit

Out of v1: OAuth2/OIDC, SMART scopes, consent enforcement, security labels, break-glass workflows, full ABAC, and DB-specific user schemas. Auth does not own audit storage; use pkg/audit (and AuditingEngine) to emit.

Public API

  • Engine / NewEngine: compiles policy, holds an in-memory Catalog, and answers CanReadResource, CanWriteResource, CanExecuteView, CanExecuteAITool, CanPushDeviceEvent, CanInstallModule, and CheckPatientScope.
  • Catalog: application-supplied principals, roles, and devices.
  • PolicyDocument / ParsePolicy / CompilePolicy: deny-by-default DSL with ordered allow/deny rules.
  • ViewAuthorizer: adapts Engine to view.Authorizer.
  • AIPolicyAdapter: adapts Engine to ai.PolicyEngine; optional AIConstraints keep field/param/de-identify/approval narrowing in the AI layer.
  • AuditingEngine: wraps PolicyEngine and emits allow/deny via pkg/audit.

Typical usage

eng, err := auth.NewEngine(auth.Config{
    Roles: []auth.Role{{
        Name: "clinician",
        Permissions: []auth.Permission{"appointment.read", "read-patient-summary"},
    }},
    Principals: []auth.Principal{{
        ID:   "user-1",
        Kind: auth.KindUser,
        TenantBindings: []auth.TenantBinding{{
            TenantID: "tenant-a",
            Roles:    []string{"clinician"},
        }},
    }},
    Devices: []auth.DeviceIdentity{{
        DeviceID: "device-1",
        TenantID: "tenant-a",
        Status:   auth.DeviceStatusActive,
        Trusted:  true,
    }},
    PolicyBytes: policyJSON,
})

d, err := eng.CanReadResource(ctx, auth.ReadRequest{
    Principal:    principal,
    Tenant:       auth.TenantContext{TenantID: "tenant-a"},
    ResourceType: "Appointment",
    ID:           "appt-1",
})

Execution model

Decision methods resolve role permissions from Catalog, apply tenant binding checks, then evaluate CompiledPolicy rules in order. The first matching rule wins. When no rule matches, access is denied.

Integration points

  • haistack-view: ViewAuthorizer implements view.Authorizer.
  • haistack-ai: AIPolicyAdapter implements ai.PolicyEngine.
  • haistack-modules: CanInstallModule checks installer permissions and module policy before install (execution stays in pkg/modules).
  • haistack-sync: CanPushDeviceEvent evaluates device trust for a tenant (transport stays in pkg/sync).
  • haistack-audit: AuditingEngine emits decision events; storage stays in store.AuditStore adapters (postgres/sqlite).
  • haistack-smart: optional SMART scopes/tokens/launch adapt into auth via smart.AuthAdapter; SMART logic stays in pkg/smart.
  • haistack-postgres: tenant scoping stays in adapters; auth only decides whether a principal may act in a tenant.

Index

Constants

View Source
const (
	DeviceStatusActive  = "active"
	DeviceStatusPending = "pending"
	DeviceStatusRevoked = "revoked"
)

DeviceStatus values for DeviceIdentity.Status.

View Source
const (
	ActionRead          = "read"
	ActionWrite         = "write"
	ActionSearch        = "search"
	ActionExecuteView   = "execute-view"
	ActionExecuteAITool = "execute-ai-tool"
	ActionPushDevice    = "push-device-event"
	ActionInstallModule = "install-module"
	ActionPatientAccess = "patient-access"
	ActionBulkExport    = "bulk-export"
)

Action names used by decision APIs and the policy DSL.

Variables

View Source
var (
	// ErrDenied is returned when a policy decision is deny (or adapters need an error).
	ErrDenied = errors.New("auth: denied")

	// ErrInvalidPolicy is returned when a policy document fails validation or parsing.
	ErrInvalidPolicy = errors.New("auth: invalid policy")

	// ErrInvalidConfig is returned when Engine configuration is incomplete or invalid.
	ErrInvalidConfig = errors.New("auth: invalid config")

	// ErrPrincipalNotFound is returned when a principal id cannot be resolved.
	ErrPrincipalNotFound = errors.New("auth: principal not found")

	// ErrDeviceNotFound is returned when a device identity cannot be resolved.
	ErrDeviceNotFound = errors.New("auth: device not found")

	// ErrRoleNotFound is returned when a role name cannot be resolved.
	ErrRoleNotFound = errors.New("auth: role not found")

	// ErrMissingResolver is returned when an adapter needs an actor resolver but none is set.
	ErrMissingResolver = errors.New("auth: missing actor resolver")
)
View Source
var ErrNoPatientSearchScope = fmt.Errorf("%w: no patient search scope configured", ErrDenied)

ErrNoPatientSearchScope is returned when a patient-scoped principal searches a resource type that has no configured patient relationship search parameter.

Functions

func ApplyPatientSearchScopeToParams

func ApplyPatientSearchScopeToParams(params url.Values, resourceType, patientID string, resolver PatientSearchParamResolver) (url.Values, error)

ApplyPatientSearchScopeToParams injects query-time patient filters into FHIR search parameters so the store never returns out-of-compartment primary matches. Patient searches are narrowed to _id. Other resource types use the resolved relationship parameter (for example subject=Patient/{id}).

func CheckEnvelopePatientScope

func CheckEnvelopePatientScope(ctx context.Context, tenant TenantContext, resolver ResourcePatientResolver, resource *types.ResourceEnvelope) error

CheckEnvelopePatientScope enforces patient scope for one loaded resource envelope.

func CheckResourcePatientScope

func CheckResourcePatientScope(tenant TenantContext, resourceType, resourceID, patientID string, hasPatient bool) error

CheckResourcePatientScope enforces TenantContext.PatientScope against a loaded resource. Non-patient resources without a resolvable patient link are allowed.

func CloneURLValues

func CloneURLValues(v url.Values) url.Values

CloneURLValues returns a shallow copy of url.Values.

func CompartmentPatientFromJSON

func CompartmentPatientFromJSON(resourceType string, raw []byte) string

CompartmentPatientFromJSON reads the Patient.id linked on a FHIR resource body. Observation uses subject.reference; Appointment uses participant.actor.reference. Other types use subject.reference when present.

func OverlayPatientID

func OverlayPatientID(resourceType, resourceID, compartmentPatient string) string

OverlayPatientID is the patient-compartment overlay target: Patient.id, else the compartment patient resolved from the resource (Observation.subject, Appointment.participant.actor, …). Empty compartment patient is unrestricted for non-Patient types.

Types

type AIConstraints

type AIConstraints struct {
	Read   map[string]ai.ReadTypePolicy
	Search map[string]ai.SearchTypePolicy
	Views  map[string]ai.ViewTypePolicy
	Write  map[string]ai.WriteTypePolicy
}

AIConstraints holds optional AI-specific narrowing that stays in the AI layer (field/param allow-lists, de-identify, approval). Auth decides access; these constraints shape the ToolResult when access is allowed.

type AIPolicyAdapter

type AIPolicyAdapter struct {
	Engine      *Engine
	Resolve     ActorResolver
	TenantID    string
	Constraints *AIConstraints
	// PatientSearchParams resolves the FHIR search parameter that scopes a resource
	// type to one patient. Registry snapshots implement this from installed
	// SearchParameters; maps can be used for tests and overrides.
	PatientSearchParams PatientSearchParamResolver
	// PatientViewScope must inject/validate a patient scope parameter for views.
	// Scoped view calls are denied when it is nil because ViewDefinitions are
	// otherwise free to scan unrelated patients.
	PatientViewScope func(ctx context.Context, req ai.ViewPolicyRequest, patientID string) (map[string]any, error)
}

AIPolicyAdapter adapts Engine to ai.PolicyEngine. Access is decided by auth; optional AIConstraints supply field/param narrowing and de-identify/approval flags.

func (*AIPolicyAdapter) ApplyViewScope

func (a *AIPolicyAdapter) ApplyViewScope(ctx context.Context, req ai.ViewPolicyRequest) (*ai.ViewPolicyRequest, error)

ApplyViewScope enforces a fail-closed rule for patient-scoped principals.

func (*AIPolicyAdapter) CheckRead

CheckRead implements ai.PolicyEngine.

func (*AIPolicyAdapter) CheckSearch

CheckSearch implements ai.PolicyEngine.

func (*AIPolicyAdapter) CheckView

func (a *AIPolicyAdapter) CheckView(ctx context.Context, req ai.ViewPolicyRequest) error

CheckView implements ai.PolicyEngine.

func (*AIPolicyAdapter) CheckViewDecision

func (a *AIPolicyAdapter) CheckViewDecision(req ai.ViewPolicyRequest) (*ai.ViewPolicyDecision, error)

CheckViewDecision returns the AI-layer view decision, combining auth access with optional AI-only de-identification hints.

func (*AIPolicyAdapter) CheckViewDecisionContext

func (a *AIPolicyAdapter) CheckViewDecisionContext(ctx context.Context, req ai.ViewPolicyRequest) (*ai.ViewPolicyDecision, error)

CheckViewDecisionContext is the context-aware view decision entrypoint used by ai.Executor so actor/subject resolution is preserved for de-identification.

func (*AIPolicyAdapter) CheckWrite

CheckWrite implements ai.PolicyEngine.

func (*AIPolicyAdapter) MaxSearchCount

func (a *AIPolicyAdapter) MaxSearchCount(resourceType string) (int, bool)

MaxSearchCount implements ai.SearchCountPolicy.

type AIToolRequest

type AIToolRequest struct {
	Principal           Principal
	Tenant              TenantContext
	ToolName            string
	ResourceType        string
	ViewName            string
	RequiredPermissions []string
}

AIToolRequest asks whether a principal may execute an AI tool.

type ActorResolver

type ActorResolver func(ctx context.Context, actor, subject string) (Principal, TenantContext, error)

ActorResolver maps a free-form actor string (as used by view/ai) to a Principal and TenantContext for authorization decisions.

type AuditingEngine

type AuditingEngine struct {
	Inner PolicyEngine
	Audit audit.Logger
}

AuditingEngine wraps a PolicyEngine and optionally emits allow/deny events through pkg/audit. Auth does not own audit storage; supply an audit.Logger (typically audit.StoreAdapter) from the host application.

func (*AuditingEngine) CanBulkExport

func (a *AuditingEngine) CanBulkExport(ctx context.Context, req BulkExportRequest) (Decision, error)

CanBulkExport implements PolicyEngine and emits an auth decision event.

func (*AuditingEngine) CanExecuteAITool

func (a *AuditingEngine) CanExecuteAITool(ctx context.Context, req AIToolRequest) (Decision, error)

CanExecuteAITool implements PolicyEngine and emits an auth decision event.

func (*AuditingEngine) CanExecuteView

func (a *AuditingEngine) CanExecuteView(ctx context.Context, req ViewRequest) (Decision, error)

CanExecuteView implements PolicyEngine and emits an auth decision event.

func (*AuditingEngine) CanInstallModule

func (a *AuditingEngine) CanInstallModule(ctx context.Context, req ModuleInstallRequest) (Decision, error)

CanInstallModule implements PolicyEngine and emits an auth decision event.

func (*AuditingEngine) CanPushDeviceEvent

func (a *AuditingEngine) CanPushDeviceEvent(ctx context.Context, req DevicePushRequest) (Decision, error)

CanPushDeviceEvent implements PolicyEngine and emits an auth decision event.

func (*AuditingEngine) CanReadResource

func (a *AuditingEngine) CanReadResource(ctx context.Context, req ReadRequest) (Decision, error)

CanReadResource implements PolicyEngine and emits an auth decision event.

func (*AuditingEngine) CanWriteResource

func (a *AuditingEngine) CanWriteResource(ctx context.Context, req WriteRequest) (Decision, error)

CanWriteResource implements PolicyEngine and emits an auth decision event.

func (*AuditingEngine) CheckPatientScope

func (a *AuditingEngine) CheckPatientScope(ctx context.Context, req PatientScopeRequest) (Decision, error)

CheckPatientScope implements PolicyEngine and emits an auth decision event.

type BulkExportRequest

type BulkExportRequest struct {
	Principal           Principal
	Tenant              TenantContext
	GroupID             string
	RequiredPermissions []string
}

BulkExportRequest asks whether a principal may start or poll a bulk export.

type Catalog

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

Catalog is an in-memory store for principals, roles, and devices. Applications own persistence; Catalog is the v1 domain-first default.

func NewCatalog

func NewCatalog() *Catalog

NewCatalog returns an empty catalog.

func (*Catalog) GetDevice

func (c *Catalog) GetDevice(id string) (DeviceIdentity, error)

GetDevice returns a device by id.

func (*Catalog) GetPrincipal

func (c *Catalog) GetPrincipal(id string) (Principal, error)

GetPrincipal returns a principal by id.

func (*Catalog) GetRole

func (c *Catalog) GetRole(name string) (Role, error)

GetRole returns a role by name.

func (*Catalog) PermissionsFor

func (c *Catalog) PermissionsFor(p Principal, tenant TenantContext) ([]Permission, []string, error)

PermissionsFor returns the union of permissions for a principal in a tenant. RoleBindings on the tenant context take precedence when non-empty; otherwise roles are taken from the principal's TenantBindings for that tenant.

func (*Catalog) PutDevice

func (c *Catalog) PutDevice(d DeviceIdentity) error

PutDevice upserts a device identity.

func (*Catalog) PutPrincipal

func (c *Catalog) PutPrincipal(p Principal) error

PutPrincipal upserts a principal.

func (*Catalog) PutRole

func (c *Catalog) PutRole(r Role) error

PutRole upserts a role.

type CompiledPolicy

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

CompiledPolicy is an immutable evaluator compiled from a PolicyDocument.

func CompilePolicy

func CompilePolicy(doc PolicyDocument) (*CompiledPolicy, error)

CompilePolicy validates and compiles a policy document.

func ParseAndCompilePolicy

func ParseAndCompilePolicy(data []byte, format PolicyFormat) (*CompiledPolicy, error)

ParseAndCompilePolicy parses and compiles a policy document in one step.

func (*CompiledPolicy) Evaluate

func (p *CompiledPolicy) Evaluate(in evalInput) Decision

Evaluate applies rules in order. The first matching rule wins. If none match, DefaultEffect applies (deny by default).

type Config

type Config struct {
	// Catalog supplies principals, roles, and devices. When nil, a new empty
	// catalog is created. Seed Principals/Roles/Devices are loaded into it.
	Catalog *Catalog

	Principals []Principal
	Roles      []Role
	Devices    []DeviceIdentity

	// Policy is a pre-parsed policy document. Ignored when Compiled is set.
	Policy *PolicyDocument

	// PolicyBytes are parsed according to PolicyFormat when Policy and Compiled
	// are both nil.
	PolicyBytes  []byte
	PolicyFormat PolicyFormat

	// Compiled is a pre-compiled policy evaluator.
	Compiled *CompiledPolicy
}

Config configures an Engine.

func ConfigFromSnapshot

func ConfigFromSnapshot(snapshot store.AuthSnapshot) (Config, error)

ConfigFromSnapshot converts a persisted auth snapshot into an Engine Config.

type Decision

type Decision struct {
	Allowed             bool              `json:"allowed"`
	Reason              string            `json:"reason,omitempty"`
	RequiredPermissions []string          `json:"requiredPermissions,omitempty"`
	Filters             map[string]string `json:"filters,omitempty"`
	Constraints         map[string]string `json:"constraints,omitempty"`
	RequiresApproval    bool              `json:"requiresApproval,omitempty"`
}

Decision is the outcome of an authorization check.

func Allow

func Allow(reason string) Decision

Allow returns an allow Decision with the given reason.

func Deny

func Deny(reason string) Decision

Deny returns a deny Decision with the given reason.

type DeviceIdentity

type DeviceIdentity struct {
	DeviceID          string            `json:"deviceId"`
	TenantID          string            `json:"tenantId"`
	Status            string            `json:"status"`
	Trusted           bool              `json:"trusted"`
	Metadata          map[string]string `json:"metadata,omitempty"`
	LinkedPrincipalID string            `json:"linkedPrincipalId,omitempty"`
}

DeviceIdentity is a first-class device record used for sync trust checks.

type DevicePushRequest

type DevicePushRequest struct {
	DeviceID string
	TenantID string
}

DevicePushRequest asks whether a device may push sync events for a tenant.

type Effect

type Effect string

Effect is the effect of a policy rule.

const (
	EffectAllow Effect = "allow"
	EffectDeny  Effect = "deny"
)

type Engine

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

Engine evaluates authorization decisions against an in-memory catalog and compiled policy. It does not own persistence or HTTP auth flows.

func NewEngine

func NewEngine(cfg Config) (*Engine, error)

NewEngine constructs an Engine from Config.

func NewEngineFromStore

func NewEngineFromStore(ctx context.Context, authStore store.AuthStore) (*Engine, error)

NewEngineFromStore loads a tenant auth snapshot from persistent storage and builds an Engine from it.

func (*Engine) CanBulkExport

func (e *Engine) CanBulkExport(ctx context.Context, req BulkExportRequest) (Decision, error)

CanBulkExport implements PolicyEngine.

func (*Engine) CanExecuteAITool

func (e *Engine) CanExecuteAITool(ctx context.Context, req AIToolRequest) (Decision, error)

CanExecuteAITool implements PolicyEngine.

func (*Engine) CanExecuteView

func (e *Engine) CanExecuteView(ctx context.Context, req ViewRequest) (Decision, error)

CanExecuteView implements PolicyEngine.

func (*Engine) CanInstallModule

func (e *Engine) CanInstallModule(ctx context.Context, req ModuleInstallRequest) (Decision, error)

CanInstallModule implements PolicyEngine.

func (*Engine) CanPushDeviceEvent

func (e *Engine) CanPushDeviceEvent(ctx context.Context, req DevicePushRequest) (Decision, error)

CanPushDeviceEvent implements PolicyEngine.

func (*Engine) CanReadResource

func (e *Engine) CanReadResource(ctx context.Context, req ReadRequest) (Decision, error)

CanReadResource implements PolicyEngine.

func (*Engine) CanWriteResource

func (e *Engine) CanWriteResource(ctx context.Context, req WriteRequest) (Decision, error)

CanWriteResource implements PolicyEngine.

func (*Engine) Catalog

func (e *Engine) Catalog() *Catalog

Catalog returns the engine's identity catalog.

func (*Engine) CheckPatientOverlay

func (e *Engine) CheckPatientOverlay(tenant TenantContext, patientID string) Decision

CheckPatientOverlay is patient-compartment overlay (SEMANTICS gate 2). patientID is Patient.id or the compartment patient of the resource. Empty PatientScope or empty patientID is unrestricted.

func (*Engine) CheckPatientScope

func (e *Engine) CheckPatientScope(ctx context.Context, req PatientScopeRequest) (Decision, error)

CheckPatientScope enforces patient-level access for SMART launch and patient-scoped principals. An empty TenantContext.PatientScope is unrestricted. A scoped principal may only access the listed patient id and resources in that compartment (enforced on Patient reads/writes and on ReadRequest/WriteRequest PatientID for Observation.subject / Appointment.participant.actor; loaded envelopes also use CheckEnvelopePatientScope in HTTP/search paths).

func (*Engine) CheckTenantBinding

func (e *Engine) CheckTenantBinding(p Principal, tenant TenantContext) Decision

CheckTenantBinding is identity: the principal must exist and be bound to the request tenant (SEMANTICS gate 1).

type MapPatientSearchParamResolver

type MapPatientSearchParamResolver map[string]string

MapPatientSearchParamResolver adapts a static map for tests and host overrides.

func (MapPatientSearchParamResolver) PatientSearchParameterCode

func (m MapPatientSearchParamResolver) PatientSearchParameterCode(resourceType string) (string, bool)

type ModuleInstallRequest

type ModuleInstallRequest struct {
	Principal           Principal
	Tenant              TenantContext
	ModuleName          string
	ModuleVersion       string
	RequiredPermissions []string
}

ModuleInstallRequest asks whether a principal may install a module.

type ModuleInstallerAuthorizer

type ModuleInstallerAuthorizer struct {
	Engine  *Engine
	Resolve PrincipalResolver
}

ModuleInstallerAuthorizer adapts Engine to modules.InstallAuthorizer.

func (*ModuleInstallerAuthorizer) AuthorizeModuleInstall

func (a *ModuleInstallerAuthorizer) AuthorizeModuleInstall(ctx context.Context, req modules.InstallAuthRequest) error

AuthorizeModuleInstall implements modules.InstallAuthorizer.

type OverridePatientSearchParamResolver

type OverridePatientSearchParamResolver struct {
	Base      PatientSearchParamResolver
	Overrides MapPatientSearchParamResolver
}

OverridePatientSearchParamResolver applies map overrides before delegating to base.

func (OverridePatientSearchParamResolver) PatientSearchParameterCode

func (r OverridePatientSearchParamResolver) PatientSearchParameterCode(resourceType string) (string, bool)

type PatientScopeRequest

type PatientScopeRequest struct {
	Principal Principal
	Tenant    TenantContext
	PatientID string
}

PatientScopeRequest asks whether a principal may access a patient within their tenant patient compartment.

type PatientSearchParamResolver

type PatientSearchParamResolver interface {
	PatientSearchParameterCode(resourceType string) (code string, ok bool)
}

PatientSearchParamResolver resolves the FHIR search parameter code that scopes one resource type to a single Patient reference. Registry snapshots implement this from installed SearchParameters; maps can be used for tests and overrides.

type Permission

type Permission string

Permission is a string-based capability declaration (e.g. "read-appointment", "appointment.read"). v1 keeps permissions as free-form strings consistent with module and view permission declarations.

type PolicyDocument

type PolicyDocument struct {
	Version       string       `json:"version" yaml:"version"`
	DefaultEffect Effect       `json:"defaultEffect,omitempty" yaml:"defaultEffect,omitempty"`
	Rules         []PolicyRule `json:"rules" yaml:"rules"`
}

PolicyDocument is a code-loaded policy document (JSON or YAML).

func ParsePolicy

func ParsePolicy(data []byte, format PolicyFormat) (PolicyDocument, error)

ParsePolicy parses a policy document from JSON or YAML bytes.

type PolicyEngine

type PolicyEngine interface {
	CanReadResource(ctx context.Context, req ReadRequest) (Decision, error)
	CanWriteResource(ctx context.Context, req WriteRequest) (Decision, error)
	CanExecuteView(ctx context.Context, req ViewRequest) (Decision, error)
	CanExecuteAITool(ctx context.Context, req AIToolRequest) (Decision, error)
	CanPushDeviceEvent(ctx context.Context, req DevicePushRequest) (Decision, error)
	CanInstallModule(ctx context.Context, req ModuleInstallRequest) (Decision, error)
	CheckPatientScope(ctx context.Context, req PatientScopeRequest) (Decision, error)
	CanBulkExport(ctx context.Context, req BulkExportRequest) (Decision, error)
}

PolicyEngine is the auth decision surface used by the rest of the stack.

type PolicyFormat

type PolicyFormat string

PolicyFormat identifies a policy document encoding.

const (
	PolicyFormatJSON PolicyFormat = "json"
	PolicyFormatYAML PolicyFormat = "yaml"
	PolicyFormatAuto PolicyFormat = "auto"
)

type PolicyRule

type PolicyRule struct {
	Name   string    `json:"name" yaml:"name"`
	Effect Effect    `json:"effect" yaml:"effect"`
	Match  RuleMatch `json:"match" yaml:"match"`
	Reason string    `json:"reason,omitempty" yaml:"reason,omitempty"`
}

PolicyRule is one ordered allow/deny rule.

type Principal

type Principal struct {
	ID             string            `json:"id"`
	Kind           PrincipalKind     `json:"kind"`
	DisplayName    string            `json:"displayName,omitempty"`
	TenantBindings []TenantBinding   `json:"tenantBindings,omitempty"`
	Attributes     map[string]string `json:"attributes,omitempty"`
}

Principal is the generic identity model for authorization decisions.

type PrincipalKind

type PrincipalKind string

PrincipalKind classifies a principal identity.

const (
	// KindUser is a human operator or clinician.
	KindUser PrincipalKind = "user"
	// KindDevice is an edge or sync device.
	KindDevice PrincipalKind = "device"
	// KindService is a backend service account.
	KindService PrincipalKind = "service"
	// KindAIAgent is an AI agent or tool-calling identity.
	KindAIAgent PrincipalKind = "ai-agent"
)

type PrincipalResolver

type PrincipalResolver func(ctx context.Context) (Principal, TenantContext, error)

PrincipalResolver maps ambient request context to a principal and tenant for non-view, non-AI package integrations such as module installation.

type ReadRequest

type ReadRequest struct {
	Principal    Principal
	Tenant       TenantContext
	ResourceType string
	ID           string
	// PatientID is the compartment patient of a non-Patient resource
	// (Observation.subject, Appointment.participant.actor, …). Empty skips
	// overlay for non-Patient types. Patient resources use ID.
	PatientID           string
	RequiredPermissions []string
}

ReadRequest asks whether a principal may read a FHIR resource.

type ResourcePatientResolver

type ResourcePatientResolver interface {
	PatientIDForResource(ctx context.Context, resourceType string, resource *types.ResourceEnvelope) (patientID string, ok bool, err error)
}

ResourcePatientResolver extracts the patient id linked to one FHIR resource.

type Role

type Role struct {
	Name        string       `json:"name" yaml:"name"`
	Permissions []Permission `json:"permissions,omitempty" yaml:"permissions,omitempty"`
}

Role groups permissions under a named role.

type RuleMatch

type RuleMatch struct {
	PrincipalKinds []string `json:"principalKinds,omitempty" yaml:"principalKinds,omitempty"`
	Tenants        []string `json:"tenants,omitempty" yaml:"tenants,omitempty"`
	Roles          []string `json:"roles,omitempty" yaml:"roles,omitempty"`
	AnyPermissions []string `json:"anyPermissions,omitempty" yaml:"anyPermissions,omitempty"`
	AllPermissions []string `json:"allPermissions,omitempty" yaml:"allPermissions,omitempty"`
	ResourceTypes  []string `json:"resourceTypes,omitempty" yaml:"resourceTypes,omitempty"`
	Actions        []string `json:"actions,omitempty" yaml:"actions,omitempty"`
	ViewNames      []string `json:"viewNames,omitempty" yaml:"viewNames,omitempty"`
	ToolNames      []string `json:"toolNames,omitempty" yaml:"toolNames,omitempty"`
	ModuleNames    []string `json:"moduleNames,omitempty" yaml:"moduleNames,omitempty"`
	PurposeOfUse   []string `json:"purposeOfUse,omitempty" yaml:"purposeOfUse,omitempty"`
	DeviceTrusted  *bool    `json:"deviceTrusted,omitempty" yaml:"deviceTrusted,omitempty"`
	DeviceStatuses []string `json:"deviceStatuses,omitempty" yaml:"deviceStatuses,omitempty"`
	PatientScoped  *bool    `json:"patientScoped,omitempty" yaml:"patientScoped,omitempty"`
}

RuleMatch describes the conditions a rule must satisfy. Empty slices and nil pointers mean "any" (do not constrain). Wildcard "*" in a string list matches any value for that field.

type TenantBinding

type TenantBinding struct {
	TenantID string   `json:"tenantId"`
	Roles    []string `json:"roles,omitempty"`
}

TenantBinding links a principal to roles within one tenant.

type TenantContext

type TenantContext struct {
	TenantID     string   `json:"tenantId"`
	RoleBindings []string `json:"roleBindings,omitempty"`
	PurposeOfUse string   `json:"purposeOfUse,omitempty"`
	PatientScope string   `json:"patientScope,omitempty"`
}

TenantContext carries the active tenant, role bindings, purpose-of-use, and optional patient scope for one authorization decision.

type ViewAuthorizer

type ViewAuthorizer struct {
	Engine   *Engine
	Resolve  ActorResolver
	TenantID string // fallback tenant when Resolve does not set one
}

ViewAuthorizer adapts Engine to view.Authorizer.

func (*ViewAuthorizer) AuthorizeView

func (a *ViewAuthorizer) AuthorizeView(ctx context.Context, req view.AuthRequest) error

AuthorizeView implements view.Authorizer. When the view declares permissions, the principal must hold at least one of them and pass policy for execute-view.

type ViewRequest

type ViewRequest struct {
	Principal           Principal
	Tenant              TenantContext
	ViewName            string
	Version             string
	ResourceType        string
	RequiredPermissions []string
	Parameters          map[string]any
}

ViewRequest asks whether a principal may execute a view.

type WriteRequest

type WriteRequest struct {
	Principal    Principal
	Tenant       TenantContext
	Operation    string // create | update | patch
	ResourceType string
	ID           string
	// PatientID is the compartment patient of a non-Patient resource.
	PatientID           string
	RequiredPermissions []string
}

WriteRequest asks whether a principal may write a FHIR resource.

Jump to

Keyboard shortcuts

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