audit

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

README

haistack-audit (pkg/audit)

Shared audit event library for HAIStack. Builds on store.AuditStore — it does not replace the persistence contract.

What it does

  • Canonical Event model (actor, tenant, subject, action, outcome, targets)
  • Shared action names for resource, auth, AI, view, sync, export, and blob
  • Logger / StoreAdapter for append and query
  • Emit helpers used by stack packages

Postgres persistence: postgres.TenantDB.AuditStore(). SQLite persistence: sqlite.DB.AuditStore().

Auth may emit decisions through this library; auth does not own audit storage.

Usage

logger := &audit.StoreAdapter{Store: auditStore}

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

_ = audit.LogAIToolCall(ctx, logger, audit.AIToolCallEvent{
    Actor: "agent-1", ToolName: "read_fhir_resource", Outcome: audit.OutcomeSuccess,
})

Action names

Constant Value
ActionResourceRead resource.read
ActionResourceWrite resource.write
ActionExecuteTool execute-tool
ActionExecuteView execute-view
ActionInvokeModel invoke-model
ActionAuthAllow / ActionAuthDeny auth.allow / auth.deny
Sync/conflict sync.* / conflict.*
ActionExport / ActionBlobAccess export / blob.access
ActionTerminologyTranslate terminology.translate

Where it fits

Package Role
store AuditStore persistence contract
audit Canonical events and helpers (this package)
auth Optional emit via AuditingEngine
ai / view Adapters forward package seams into audit
sync Action constants + LogSyncEvent

See doc.go for the full API.

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