audit

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

README

haistack-audit (pkg/audit)

Shared audit event library for HAIStack.

What it does

haistack-audit defines the canonical audit event model and emit helpers used across auth, FHIR reads/writes, sync, AI tooling, views, exports, blob access, and terminology translation. It builds on store.AuditStore — the persistence contract — without owning storage itself.

Producers call typed helpers such as LogResourceRead, LogAuthDecision, or LogSyncEvent with small event structs; helpers normalize default outcomes, merge detail maps, and map to the shared Event shape. Append goes through the Logger interface, most often StoreAdapter wrapping store.AuditStore.

Querying uses Query (package-level filters) converted to store.AuditQuery in StoreAdapter.ListEvents, with FromStoreRecord / ToStoreRecord bridging legacy detail keys and first-class columns.

An optional MemoryStore implements store.AuditStore for tests. NopLogger discards events when auditing is disabled.

What it does not do

  • Choose authorization policy — pkg/auth decides allow/deny; audit records the decision
  • Open databases or define schemas — use pkg/sqlite or pkg/postgres for AuditStore
  • Replace package-specific seams — ai.AuditLogger and view.AuditLogger adapt into these helpers rather than duplicating event shapes
  • Guarantee tamper-evident or WORM storage — append semantics depend on the backend implementation
  • Correlate logs across services — events are row-oriented; distributed tracing is out of scope

Audit owns consistent event vocabulary and append/query adapters, not policy or storage engines.

How it fits in the ecosystem

  pkg/auth / pkg/core / pkg/sync / pkg/ai / pkg/view / pkg/export
                              |
                    Log* helpers (emit.go)
                              |
                              v
                         audit.Logger
                              |
                    StoreAdapter.Log -> Event
                              |
                              v
                      store.AuditStore
                              |
                    sqlite.DB / postgres.TenantDB
Direction Package Relationship
Upstream store AuditStore, AuditRecord, AuditQuery
Upstream sqlite / postgres Durable audit persistence
Peer auth Emits LogAuthDecision; does not own storage
Peer sync Uses LogSyncEvent and sync/conflict action constants
Peer ai Tool/model invoke events via adapters
Peer view LogViewAccess for execute-view auditing
Peer export LogExport for export operations
Downstream operators / compliance Query via ListEvents or store APIs

Typical wiring in a server: construct auditStore := tenantDB.AuditStore(), wrap with &audit.StoreAdapter{Store: auditStore}, pass the adapter (as audit.Logger) into HTTP middleware and domain services.

When to use it

  • Recording FHIR resource reads and writes with actor, tenant, and outcome
  • Auditing authorization allow/deny decisions with reasons and scoped targets
  • Logging sync acceptance, rejection, conflicts, and device push/pull
  • Logging AI tool execution and model invocation with conversation metadata
  • Logging view execution, CSV/bulk export, and binary/blob access
  • Logging ConceptMap translation for terminology provenance research
  • Unit tests that assert action names and fields without a database (NewMemoryStore)

Usage modes

Production append via StoreAdapter

Bridge domain code to durable storage:

import (
    "context"

    "github.com/degoke/haistack/pkg/audit"
)

auditStore := tenantDB.AuditStore()
logger := &audit.StoreAdapter{Store: auditStore}

err := audit.LogAuthDecision(ctx, logger, audit.AuthDecisionEvent{
    Actor:      "user-1",
    Tenant:     "tenant-a",
    Subject:    "patient/pat-1",
    AuthAction: "read",
    Allowed:    true,
    Reason:     "rule matched",
})
In-memory tests without SQLite

Use MemoryStore plus StoreAdapter for round-trip assertions:

mem := audit.NewMemoryStore()
logger := &audit.StoreAdapter{
    Store: mem,
    Now:   func() time.Time { return fixedTime },
    NewID: func() string { return "fixed-id" },
}
Disabled auditing in hot paths

Inject audit.NopLogger{} or a no-op LoggerFunc when configuration turns auditing off; emit helpers return ErrNilLogger only when the logger is nil.

Query and investigation

List canonical events with package-level filters:

events, err := logger.ListEvents(ctx, audit.Query{
    Actor:  "user-1",
    Action: audit.ActionResourceRead,
    Limit:  100,
})

Lower-level store access remains available via StoreAdapter.List with store.AuditQuery.

Examples

FHIR read/write and sync (from audit_test patterns):

_ = audit.LogResourceRead(ctx, logger, audit.ResourceReadEvent{
    Actor: "practitioner-1", Tenant: "tenant-a", ResourceType: "Patient", ResourceID: "pat-1",
})
_ = audit.LogResourceWrite(ctx, logger, audit.ResourceWriteEvent{
    Actor: "practitioner-1", ResourceType: "Observation", ResourceID: "obs-1", Operation: "create",
})
_ = audit.LogSyncEvent(ctx, logger, audit.SyncEvent{
    Actor: "device-9", Action: audit.ActionSyncAccepted, Outcome: audit.OutcomeSuccess,
})

AI, auth, view, export, blob, terminology:

_ = audit.LogAIToolCall(ctx, logger, audit.AIToolCallEvent{
    Actor: "agent-1", ToolName: "read_fhir_resource", Outcome: audit.OutcomeSuccess,
    ConversationID: "conv-1",
})
_ = audit.LogAIModelInvoke(ctx, logger, audit.AIToolCallEvent{
    Actor: "agent-1", ToolName: "stub-v1", Outcome: audit.OutcomeSuccess,
})
_ = audit.LogAuthDecision(ctx, logger, audit.AuthDecisionEvent{
    Actor: "user-2", Allowed: false, Reason: "insufficient scope",
})
_ = audit.LogViewAccess(ctx, logger, audit.ViewAccessEvent{
    Actor: "analyst-1", ViewName: "patient-summary", Version: "2",
})
_ = audit.LogExport(ctx, logger, audit.ExportEvent{Actor: "analyst-1", ViewName: "cohort-export"})
_ = audit.LogBlobAccess(ctx, logger, audit.BlobAccessEvent{Actor: "service-1", BlobKey: "binary/doc-1"})
_ = audit.LogTerminologyTranslate(ctx, logger, audit.TerminologyTranslateEvent{
    MapURL: "http://example.org/ConceptMap/example", SourceCode: "123", TargetCode: "456",
})

Round-trip and custom logger:

events, err := logger.ListEvents(ctx, audit.Query{Actor: "agent-1", Action: audit.ActionExecuteTool})
rec := audit.ToStoreRecord(audit.Event{Actor: "system", Action: audit.ActionExport})
ev := audit.FromStoreRecord(rec)
_ = events
_ = err
_ = ev

Configuration / key types

Event: ID, Timestamp, Actor, Tenant, Subject, Action, Outcome, resource/view/tool fields, BlobKey, Details. Helpers set subsets; StoreAdapter fills zero Timestamp/ID.

Query: filters for ListEvents (resource, actor, action, outcome, tenant, view, tool, conversation, time range, limit).

StoreAdapter: Store (required), optional Now / NewID for tests.

Actions / outcomes: defined in types.go — prefer ActionResourceRead, ActionAuthAllow/ActionAuthDeny, ActionSync*, ActionConflict*, ActionExecuteTool, ActionExecuteView, ActionInvokeModel, ActionExport, ActionBlobAccess, ActionTerminologyTranslate; outcomes include OutcomeSuccess, OutcomeError, OutcomeAllow/OutcomeDeny, etc.

Errors: ErrNilStore, ErrNilLogger.

Where it fits

Package Role
store AuditStore persistence contract
audit Canonical events and helpers (this package)
sqlite / postgres Durable audit backends
auth Policy decisions; optional emit via auditing engine
sync Device and conflict auditing
ai Tool/model invoke adapters
view View execution auditing
export Export operation auditing
terminology Translation audit for research/provenance

Limits

  • v1 focuses on append and list — retention, encryption, and streaming export are backend/ops concerns.
  • Legacy detail keys — FromStoreRecord lifts tenant, subject, viewName, etc. from Details when first-class columns are empty.
  • Helper defaults — empty outcomes on read/write/export/blob default to OutcomeSuccess; auth uses allow/deny actions and outcomes explicitly.
  • LogSyncEvent does not validate Action — callers must pass one of the documented sync/conflict/device constants.
  • MemoryStore.List applies simple in-memory filtering; it is not a production backend.
  • Nil logger is an error — use NopLogger instead of nil when auditing is disabled.
  • Query support varies by backend — prefer fields mirrored in store.AuditQuery; unsupported filters may be no-ops on thin adapters.

Documentation

Overview

Package audit implements haistack-audit, the shared audit event library for HAIStack.

Scope

v1 builds on store.AuditStore as the persistence contract. This package owns the canonical audit event model, action names, append/query helpers, and adapters used by auth, AI, view, sync, exports, and future packages.

It does not replace store.AuditStore. Postgres persistence remains in pkg/postgres (TenantDB.AuditStore). SQLite persistence is in pkg/sqlite (DB.AuditStore). Auth may emit decisions through this package but must not own audit storage.

Public API

  • Event / Query — canonical event and filter shapes
  • Logger / LoggerFunc — append seam
  • StoreAdapter — bridges Event to store.AuditStore
  • Emit helpers: LogResourceRead, LogResourceWrite, LogSyncEvent, LogAIToolCall, LogAIModelInvoke, LogAuthDecision, LogExport, LogBlobAccess, LogViewAccess
  • Action and Outcome constants for consistent naming

Typical usage

logger := &audit.StoreAdapter{Store: auditStore}
_ = audit.LogAuthDecision(ctx, logger, audit.AuthDecisionEvent{
    Actor: "user-1", Tenant: "tenant-a", Allowed: true, Reason: "rule X",
})

Package-specific seams (ai.AuditLogger, view.AuditLogger) adapt into these helpers so callers query one consistent shape regardless of producer.

Index

Constants

View Source
const (
	OutcomeSuccess          = "success"
	OutcomeDenied           = "denied"
	OutcomeError            = "error"
	OutcomeValidationFailed = "validation-failed"
	OutcomeApprovalRequired = "approval-required"
	OutcomeAllow            = "allow"
	OutcomeDeny             = "deny"
)

Outcome values used across package emit helpers.

View Source
const (
	ActionResourceRead  = "resource.read"
	ActionResourceWrite = "resource.write"

	ActionExecuteTool = "execute-tool"
	ActionExecuteView = "execute-view"
	ActionInvokeModel = "invoke-model"

	ActionAuthAllow = "auth.allow"
	ActionAuthDeny  = "auth.deny"

	ActionSyncAccepted        = "sync.accepted"
	ActionSyncRejected        = "sync.rejected"
	ActionSyncConflicted      = "sync.conflicted"
	ActionDevicePushed        = "sync.device_pushed"
	ActionDevicePulled        = "sync.device_pulled"
	ActionConflictAutoMerged  = "conflict.auto_merged"
	ActionConflictNeedsReview = "conflict.needs_review"

	ActionExport     = "export"
	ActionBlobAccess = "blob.access"

	ActionTerminologyTranslate = "terminology.translate"
)

Canonical action names. Producers should prefer these over free-form strings.

Variables

View Source
var (
	// ErrNilStore is returned when StoreAdapter has no backing AuditStore.
	ErrNilStore = errors.New("audit: audit store is required")
	// ErrNilLogger is returned when an emit helper is called with a nil Logger.
	ErrNilLogger = errors.New("audit: logger is required")
)

Functions

func LogAIModelInvoke

func LogAIModelInvoke(ctx context.Context, logger Logger, ev AIToolCallEvent) error

LogAIModelInvoke emits an invoke-model event.

func LogAIToolCall

func LogAIToolCall(ctx context.Context, logger Logger, ev AIToolCallEvent) error

LogAIToolCall emits an execute-tool event.

func LogAuthDecision

func LogAuthDecision(ctx context.Context, logger Logger, ev AuthDecisionEvent) error

LogAuthDecision emits auth.allow or auth.deny.

func LogBlobAccess

func LogBlobAccess(ctx context.Context, logger Logger, ev BlobAccessEvent) error

LogBlobAccess emits a blob.access event.

func LogExport

func LogExport(ctx context.Context, logger Logger, ev ExportEvent) error

LogExport emits an export event.

func LogResourceRead

func LogResourceRead(ctx context.Context, logger Logger, ev ResourceReadEvent) error

LogResourceRead emits a resource.read event.

func LogResourceWrite

func LogResourceWrite(ctx context.Context, logger Logger, ev ResourceWriteEvent) error

LogResourceWrite emits a resource.write event.

func LogSyncEvent

func LogSyncEvent(ctx context.Context, logger Logger, ev SyncEvent) error

LogSyncEvent emits a sync-related event. Action should be one of the ActionSync* / ActionConflict* / ActionDevice* constants.

func LogTerminologyTranslate

func LogTerminologyTranslate(ctx context.Context, logger Logger, ev TerminologyTranslateEvent) error

LogTerminologyTranslate emits a terminology.translate event.

func LogViewAccess

func LogViewAccess(ctx context.Context, logger Logger, ev ViewAccessEvent) error

LogViewAccess emits an execute-view event.

func ToStoreRecord

func ToStoreRecord(event Event) store.AuditRecord

ToStoreRecord converts an Event into store.AuditRecord using first-class fields. Legacy detail keys are still lifted on read via FromStoreRecord when columns are empty.

Types

type AIToolCallEvent

type AIToolCallEvent struct {
	Actor          string
	Tenant         string
	Subject        string
	ToolName       string
	Outcome        string
	ConversationID string
	Details        map[string]string
	Timestamp      time.Time
	ID             string
}

AIToolCallEvent describes an AI tool invocation audit entry.

type AuthDecisionEvent

type AuthDecisionEvent struct {
	Actor        string
	Tenant       string
	Subject      string
	AuthAction   string // the authorization action checked (read, write, …)
	ResourceType string
	ResourceID   string
	ViewName     string
	ToolName     string
	ModuleName   string
	Allowed      bool
	Reason       string
	Details      map[string]string
	Timestamp    time.Time
	ID           string
}

AuthDecisionEvent describes an authorization allow/deny for audit.

type BlobAccessEvent

type BlobAccessEvent struct {
	Actor     string
	Tenant    string
	Subject   string
	BlobKey   string
	Outcome   string
	Details   map[string]string
	Timestamp time.Time
	ID        string
}

BlobAccessEvent describes blob/binary access for audit.

type Event

type Event struct {
	ID             string            `json:"id"`
	Timestamp      time.Time         `json:"timestamp"`
	Actor          string            `json:"actor"`
	Tenant         string            `json:"tenant,omitempty"`
	Subject        string            `json:"subject,omitempty"`
	Action         string            `json:"action"`
	Outcome        string            `json:"outcome,omitempty"`
	ResourceType   string            `json:"resourceType,omitempty"`
	ResourceID     string            `json:"resourceId,omitempty"`
	ViewName       string            `json:"viewName,omitempty"`
	ToolName       string            `json:"toolName,omitempty"`
	ConversationID string            `json:"conversationId,omitempty"`
	ModuleName     string            `json:"moduleName,omitempty"`
	BlobKey        string            `json:"blobKey,omitempty"`
	Details        map[string]string `json:"details,omitempty"`
}

Event is the canonical audit event model used across the stack.

func FromStoreRecord

func FromStoreRecord(rec store.AuditRecord) Event

FromStoreRecord converts a store.AuditRecord into Event, lifting legacy detail keys when first-class columns are empty.

type ExportEvent

type ExportEvent struct {
	Actor     string
	Tenant    string
	Subject   string
	Outcome   string
	ViewName  string
	Details   map[string]string
	Timestamp time.Time
	ID        string
}

ExportEvent describes an export operation for audit.

type Logger

type Logger interface {
	Log(ctx context.Context, event Event) error
}

Logger is the shared append seam for canonical audit events.

type LoggerFunc

type LoggerFunc func(ctx context.Context, event Event) error

LoggerFunc adapts a function to Logger.

func (LoggerFunc) Log

func (f LoggerFunc) Log(ctx context.Context, event Event) error

Log implements Logger.

type MemoryStore

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

MemoryStore is an optional in-memory store.AuditStore for tests.

func NewMemoryStore

func NewMemoryStore() *MemoryStore

NewMemoryStore constructs an empty in-memory audit store.

func (*MemoryStore) Append

func (s *MemoryStore) Append(_ context.Context, record store.AuditRecord) error

Append implements store.AuditStore.

func (*MemoryStore) List

List implements store.AuditStore.

func (*MemoryStore) Records

func (s *MemoryStore) Records() []store.AuditRecord

Records returns a copy of all stored records.

type NopLogger

type NopLogger struct{}

NopLogger discards all events.

func (NopLogger) Log

Log implements Logger.

type Query

type Query struct {
	ResourceType   string    `json:"resourceType,omitempty"`
	ResourceID     string    `json:"resourceId,omitempty"`
	Actor          string    `json:"actor,omitempty"`
	Action         string    `json:"action,omitempty"`
	Outcome        string    `json:"outcome,omitempty"`
	Tenant         string    `json:"tenant,omitempty"`
	ViewName       string    `json:"viewName,omitempty"`
	ToolName       string    `json:"toolName,omitempty"`
	ConversationID string    `json:"conversationId,omitempty"`
	After          time.Time `json:"after,omitempty"`
	Before         time.Time `json:"before,omitempty"`
	Limit          int       `json:"limit,omitempty"`
}

Query selects audit events using store-backed filters where available.

type ResourceReadEvent

type ResourceReadEvent struct {
	Actor        string
	Tenant       string
	Subject      string
	ResourceType string
	ResourceID   string
	Outcome      string
	Details      map[string]string
	Timestamp    time.Time
	ID           string
}

ResourceReadEvent describes a FHIR resource read for audit.

type ResourceWriteEvent

type ResourceWriteEvent struct {
	Actor        string
	Tenant       string
	Subject      string
	ResourceType string
	ResourceID   string
	Operation    string
	Outcome      string
	Details      map[string]string
	Timestamp    time.Time
	ID           string
}

ResourceWriteEvent describes a FHIR resource write for audit.

type StoreAdapter

type StoreAdapter struct {
	Store store.AuditStore
	Now   func() time.Time
	NewID func() string
}

StoreAdapter writes Event values to a store.AuditStore and can list them back as Event values.

func (*StoreAdapter) List

List returns store records matching store.AuditQuery filters.

func (*StoreAdapter) ListEvents

func (a *StoreAdapter) ListEvents(ctx context.Context, query Query) ([]Event, error)

ListEvents lists and converts records using store-level filters where supported.

func (*StoreAdapter) Log

func (a *StoreAdapter) Log(ctx context.Context, event Event) error

Log implements Logger.

type SyncEvent

type SyncEvent struct {
	Actor        string
	Tenant       string
	Subject      string
	Action       string
	Outcome      string
	ResourceType string
	ResourceID   string
	Details      map[string]string
	Timestamp    time.Time
	ID           string
}

SyncEvent describes a sync push/pull/conflict audit entry.

type TerminologyTranslateEvent

type TerminologyTranslateEvent struct {
	Actor        string
	Tenant       string
	Subject      string
	Outcome      string
	Details      map[string]string
	Timestamp    time.Time
	ID           string
	MapURL       string
	MapVersion   string
	SourceSystem string
	SourceCode   string
	TargetCode   string
}

TerminologyTranslateEvent describes a ConceptMap translation for audit and provenance research. Details should include map version, source CodeSystem version, and equivalence class when known.

type ViewAccessEvent

type ViewAccessEvent struct {
	Actor     string
	Tenant    string
	Subject   string
	ViewName  string
	Version   string
	Outcome   string
	Details   map[string]string
	Timestamp time.Time
	ID        string
}

ViewAccessEvent describes a view execution for audit.

Jump to

Keyboard shortcuts

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