audit

package
v0.1.4 Latest Latest
Warning

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

Go to latest
Published: Apr 7, 2026 License: GPL-3.0 Imports: 5 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AuditLogNotFoundError

func AuditLogNotFoundError(id shared.ID) error

AuditLogNotFoundError returns a not found error for an audit log.

func InvalidFilterError

func InvalidFilterError(reason string) error

InvalidFilterError returns a validation error for invalid filter.

Types

type Action

type Action string

Action represents the type of action performed.

const (
	// User actions
	ActionUserCreated     Action = "user.created"
	ActionUserUpdated     Action = "user.updated"
	ActionUserDeleted     Action = "user.deleted"
	ActionUserSuspended   Action = "user.suspended"
	ActionUserActivated   Action = "user.activated"
	ActionUserDeactivated Action = "user.deactivated"
	ActionUserLogin       Action = "user.login"
	ActionUserLogout      Action = "user.logout"

	// Tenant actions
	ActionTenantCreated                Action = "tenant.created"
	ActionTenantUpdated                Action = "tenant.updated"
	ActionTenantDeleted                Action = "tenant.deleted"
	ActionTenantSettingsUpdated        Action = "tenant.settings_updated"
	ActionTenantModulesUpdated         Action = "tenant.modules_updated"
	ActionTenantRiskScoringUpdated     Action = "tenant.risk_scoring_updated"
	ActionTenantRiskScoresRecalculated Action = "tenant.risk_scores_recalculated"

	// Membership actions
	ActionMemberAdded       Action = "member.added"
	ActionMemberRemoved     Action = "member.removed"
	ActionMemberRoleChanged Action = "member.role_changed"

	// Invitation actions
	ActionInvitationCreated  Action = "invitation.created"
	ActionInvitationAccepted Action = "invitation.accepted"
	ActionInvitationDeleted  Action = "invitation.deleted"
	ActionInvitationExpired  Action = "invitation.expired"

	// Repository actions
	ActionRepositoryCreated  Action = "repository.created"
	ActionRepositoryUpdated  Action = "repository.updated"
	ActionRepositoryDeleted  Action = "repository.deleted"
	ActionRepositoryArchived Action = "repository.archived"

	// Component actions
	ActionComponentCreated Action = "component.created"
	ActionComponentUpdated Action = "component.updated"
	ActionComponentDeleted Action = "component.deleted"

	// Vulnerability actions
	ActionVulnerabilityCreated Action = "vulnerability.created"
	ActionVulnerabilityUpdated Action = "vulnerability.updated"
	ActionVulnerabilityDeleted Action = "vulnerability.deleted"

	// Finding actions
	ActionFindingCreated       Action = "finding.created"
	ActionFindingUpdated       Action = "finding.updated"
	ActionFindingDeleted       Action = "finding.deleted"
	ActionFindingStatusChanged Action = "finding.status_changed"
	ActionFindingTriaged       Action = "finding.triaged"
	ActionFindingAssigned      Action = "finding.assigned"
	ActionFindingUnassigned    Action = "finding.unassigned"
	ActionFindingCommented     Action = "finding.commented"
	ActionFindingBulkUpdated   Action = "finding.bulk_updated"

	// Branch actions
	ActionBranchCreated    Action = "branch.created"
	ActionBranchUpdated    Action = "branch.updated"
	ActionBranchDeleted    Action = "branch.deleted"
	ActionBranchScanned    Action = "branch.scanned"
	ActionBranchSetDefault Action = "branch.set_default"

	// SLA Policy actions
	ActionSLAPolicyCreated Action = "sla_policy.created"
	ActionSLAPolicyUpdated Action = "sla_policy.updated"
	ActionSLAPolicyDeleted Action = "sla_policy.deleted"

	// Scan actions
	ActionScanStarted   Action = "scan.started"
	ActionScanCompleted Action = "scan.completed"
	ActionScanFailed    Action = "scan.failed"

	// Security actions
	ActionAuthLogin        Action = "auth.login"
	ActionAuthLogout       Action = "auth.logout"
	ActionAuthRegister     Action = "auth.register"
	ActionAuthFailed       Action = "auth.failed"
	ActionPermissionDenied Action = "permission.denied"
	ActionTokenRevoked     Action = "token.revoked"

	// Settings actions
	ActionSettingsUpdated Action = "settings.updated"

	// Data actions
	ActionDataExported Action = "data.exported"
	ActionDataImported Action = "data.imported"

	// Agent actions
	ActionAgentCreated        Action = "agent.created"
	ActionAgentUpdated        Action = "agent.updated"
	ActionAgentDeleted        Action = "agent.deleted"
	ActionAgentActivated      Action = "agent.activated"
	ActionAgentDeactivated    Action = "agent.deactivated"
	ActionAgentRevoked        Action = "agent.revoked"
	ActionAgentKeyRegenerated Action = "agent.key_regenerated"
	ActionAgentConnected      Action = "agent.connected"
	ActionAgentDisconnected   Action = "agent.disconnected"

	// Credential (Secret Store) actions
	ActionCredentialCreated  Action = "credential.created"
	ActionCredentialUpdated  Action = "credential.updated"
	ActionCredentialDeleted  Action = "credential.deleted"
	ActionCredentialAccessed Action = "credential.accessed"

	// Group actions
	ActionGroupCreated Action = "group.created"
	ActionGroupUpdated Action = "group.updated"
	ActionGroupDeleted Action = "group.deleted"

	// Capability actions
	ActionCapabilityCreated Action = "capability.created"
	ActionCapabilityUpdated Action = "capability.updated"
	ActionCapabilityDeleted Action = "capability.deleted"

	// Tool actions
	ActionToolCreated         Action = "tool.created"
	ActionToolUpdated         Action = "tool.updated"
	ActionToolDeleted         Action = "tool.deleted"
	ActionToolCapabilitiesSet Action = "tool.capabilities_set"

	// Asset Ownership actions
	ActionAssetAssigned         Action = "asset.assigned"
	ActionAssetUnassigned       Action = "asset.unassigned"
	ActionAssetOwnershipUpdated Action = "asset.ownership_updated"

	// Permission Set actions
	ActionPermissionSetCreated    Action = "permission_set.created"
	ActionPermissionSetUpdated    Action = "permission_set.updated"
	ActionPermissionSetDeleted    Action = "permission_set.deleted"
	ActionPermissionSetAssigned   Action = "permission_set.assigned"
	ActionPermissionSetUnassigned Action = "permission_set.unassigned"

	// Permission actions
	ActionPermissionGranted Action = "permission.granted"
	ActionPermissionRevoked Action = "permission.revoked"

	// Role actions
	ActionRoleCreated      Action = "role.created"
	ActionRoleUpdated      Action = "role.updated"
	ActionRoleDeleted      Action = "role.deleted"
	ActionRoleAssigned     Action = "role.assigned"
	ActionRoleUnassigned   Action = "role.unassigned"
	ActionUserRolesUpdated Action = "user.roles_updated"

	// Pipeline actions
	ActionPipelineTemplateCreated     Action = "pipeline_template.created"
	ActionPipelineTemplateUpdated     Action = "pipeline_template.updated"
	ActionPipelineTemplateDeleted     Action = "pipeline_template.deleted"
	ActionPipelineTemplateActivated   Action = "pipeline_template.activated"
	ActionPipelineTemplateDeactivated Action = "pipeline_template.deactivated"
	ActionPipelineStepCreated         Action = "pipeline_step.created"
	ActionPipelineStepUpdated         Action = "pipeline_step.updated"
	ActionPipelineStepDeleted         Action = "pipeline_step.deleted"
	ActionPipelineRunTriggered        Action = "pipeline_run.triggered"
	ActionPipelineRunCompleted        Action = "pipeline_run.completed"
	ActionPipelineRunFailed           Action = "pipeline_run.failed"
	ActionPipelineRunCanceled         Action = "pipeline_run.canceled"

	// Scan config actions
	ActionScanConfigCreated   Action = "scan_config.created"
	ActionScanConfigUpdated   Action = "scan_config.updated"
	ActionScanConfigDeleted   Action = "scan_config.deleted"
	ActionScanConfigTriggered Action = "scan_config.triggered"
	ActionScanConfigPaused    Action = "scan_config.paused"
	ActionScanConfigActivated Action = "scan_config.activated"
	ActionScanConfigDisabled  Action = "scan_config.disabled"
	ActionScanConfigExported  Action = "scan_config.exported"
	ActionScanConfigImported  Action = "scan_config.imported"

	// Security events
	ActionSecurityValidationFailed  Action = "security.validation_failed"
	ActionSecurityCrossTenantAccess Action = "security.cross_tenant_access"

	// Workflow actions
	ActionWorkflowCreated      Action = "workflow.created"
	ActionWorkflowUpdated      Action = "workflow.updated"
	ActionWorkflowDeleted      Action = "workflow.deleted"
	ActionWorkflowActivated    Action = "workflow.activated"
	ActionWorkflowDeactivated  Action = "workflow.deactivated"
	ActionWorkflowRunTriggered Action = "workflow_run.triggered"
	ActionWorkflowRunCompleted Action = "workflow_run.completed"
	ActionWorkflowRunFailed    Action = "workflow_run.failed"
	ActionWorkflowRunCanceled  Action = "workflow_run.canceled"

	// Rule actions
	ActionRuleSourceCreated   Action = "rule_source.created"
	ActionRuleSourceUpdated   Action = "rule_source.updated"
	ActionRuleSourceDeleted   Action = "rule_source.deleted"
	ActionRuleOverrideCreated Action = "rule_override.created"
	ActionRuleOverrideUpdated Action = "rule_override.updated"
	ActionRuleOverrideDeleted Action = "rule_override.deleted"

	// Ingest actions (agent upload)
	ActionIngestStarted        Action = "ingest.started"
	ActionIngestCompleted      Action = "ingest.completed"
	ActionIngestFailed         Action = "ingest.failed"
	ActionIngestPartialSuccess Action = "ingest.partial_success"

	// AI Triage actions
	ActionAITriageRequested  Action = "ai_triage.requested"
	ActionAITriageStarted    Action = "ai_triage.started"
	ActionAITriageCompleted  Action = "ai_triage.completed"
	ActionAITriageFailed     Action = "ai_triage.failed"
	ActionAITriageBulk       Action = "ai_triage.bulk_requested"
	ActionAITriageRateLimit  Action = "ai_triage.rate_limited"
	ActionAITriageTokenLimit Action = "ai_triage.token_limit_exceeded"
)

func (Action) Category

func (a Action) Category() string

Category returns the category of the action (e.g., "user", "tenant").

func (Action) IsValid

func (a Action) IsValid() bool

IsValid checks if the action is a known action type.

func (Action) String

func (a Action) String() string

String returns the string representation of the action.

type AuditLog

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

AuditLog represents an audit log entry.

func NewAuditLog

func NewAuditLog(
	action Action,
	resourceType ResourceType,
	resourceID string,
	result Result,
) (*AuditLog, error)

NewAuditLog creates a new audit log entry.

func Reconstitute

func Reconstitute(
	id shared.ID,
	tenantID *shared.ID,
	actorID *shared.ID,
	actorEmail string,
	actorIP string,
	actorAgent string,
	action Action,
	resourceType ResourceType,
	resourceID string,
	resourceName string,
	changes *Changes,
	result Result,
	severity Severity,
	message string,
	metadata map[string]any,
	requestID string,
	sessionID string,
	timestamp time.Time,
) *AuditLog

Reconstitute recreates an AuditLog from persistence.

func (*AuditLog) Action

func (a *AuditLog) Action() Action

Action returns the action.

func (*AuditLog) ActorAgent

func (a *AuditLog) ActorAgent() string

ActorAgent returns the actor user agent.

func (*AuditLog) ActorEmail

func (a *AuditLog) ActorEmail() string

ActorEmail returns the actor email.

func (*AuditLog) ActorID

func (a *AuditLog) ActorID() *shared.ID

ActorID returns the actor ID.

func (*AuditLog) ActorIP

func (a *AuditLog) ActorIP() string

ActorIP returns the actor IP address.

func (*AuditLog) Category

func (a *AuditLog) Category() string

Category returns the action category.

func (*AuditLog) Changes

func (a *AuditLog) Changes() *Changes

Changes returns the changes.

func (*AuditLog) GenerateMessage

func (a *AuditLog) GenerateMessage() string

GenerateMessage generates a default message if none is set.

func (*AuditLog) HasChanges

func (a *AuditLog) HasChanges() bool

HasChanges checks if there are recorded changes.

func (*AuditLog) ID

func (a *AuditLog) ID() shared.ID

ID returns the audit log ID.

func (*AuditLog) IsCritical

func (a *AuditLog) IsCritical() bool

IsCritical checks if the severity is critical.

func (*AuditLog) IsDenied

func (a *AuditLog) IsDenied() bool

IsDenied checks if the action was denied.

func (*AuditLog) IsFailure

func (a *AuditLog) IsFailure() bool

IsFailure checks if the action failed.

func (*AuditLog) IsHighOrCritical

func (a *AuditLog) IsHighOrCritical() bool

IsHighOrCritical checks if the severity is high or critical.

func (*AuditLog) IsSuccess

func (a *AuditLog) IsSuccess() bool

IsSuccess checks if the action was successful.

func (*AuditLog) Message

func (a *AuditLog) Message() string

Message returns the message.

func (*AuditLog) Metadata

func (a *AuditLog) Metadata() map[string]any

Metadata returns a copy of the metadata.

func (*AuditLog) RequestID

func (a *AuditLog) RequestID() string

RequestID returns the request ID.

func (*AuditLog) ResourceID

func (a *AuditLog) ResourceID() string

ResourceID returns the resource ID.

func (*AuditLog) ResourceName

func (a *AuditLog) ResourceName() string

ResourceName returns the resource name.

func (*AuditLog) ResourceType

func (a *AuditLog) ResourceType() ResourceType

ResourceType returns the resource type.

func (*AuditLog) Result

func (a *AuditLog) Result() Result

Result returns the result.

func (*AuditLog) SessionID

func (a *AuditLog) SessionID() string

SessionID returns the session ID.

func (*AuditLog) Severity

func (a *AuditLog) Severity() Severity

Severity returns the severity.

func (*AuditLog) TenantID

func (a *AuditLog) TenantID() *shared.ID

TenantID returns the tenant ID.

func (*AuditLog) Timestamp

func (a *AuditLog) Timestamp() time.Time

Timestamp returns the timestamp.

func (*AuditLog) WithActor

func (a *AuditLog) WithActor(actorID shared.ID, email string) *AuditLog

WithActor sets the actor information.

func (*AuditLog) WithActorAgent

func (a *AuditLog) WithActorAgent(agent string) *AuditLog

WithActorAgent sets the actor user agent.

func (*AuditLog) WithActorIP

func (a *AuditLog) WithActorIP(ip string) *AuditLog

WithActorIP sets the actor IP address.

func (*AuditLog) WithChanges

func (a *AuditLog) WithChanges(changes *Changes) *AuditLog

WithChanges sets the changes.

func (*AuditLog) WithMessage

func (a *AuditLog) WithMessage(message string) *AuditLog

WithMessage sets the message.

func (*AuditLog) WithMetadata

func (a *AuditLog) WithMetadata(key string, value any) *AuditLog

WithMetadata sets a metadata key-value pair.

func (*AuditLog) WithRequestID

func (a *AuditLog) WithRequestID(requestID string) *AuditLog

WithRequestID sets the request ID.

func (*AuditLog) WithResourceName

func (a *AuditLog) WithResourceName(name string) *AuditLog

WithResourceName sets the resource name.

func (*AuditLog) WithSessionID

func (a *AuditLog) WithSessionID(sessionID string) *AuditLog

WithSessionID sets the session ID.

func (*AuditLog) WithSeverity

func (a *AuditLog) WithSeverity(severity Severity) *AuditLog

WithSeverity sets the severity (overrides default).

func (*AuditLog) WithTenantID

func (a *AuditLog) WithTenantID(tenantID shared.ID) *AuditLog

WithTenantID sets the tenant ID.

type Changes

type Changes struct {
	Before map[string]any `json:"before,omitempty"`
	After  map[string]any `json:"after,omitempty"`
}

Changes represents before/after values for an update operation.

func NewChanges

func NewChanges() *Changes

NewChanges creates a new Changes instance.

func (*Changes) IsEmpty

func (c *Changes) IsEmpty() bool

IsEmpty checks if changes are empty.

func (*Changes) Set

func (c *Changes) Set(key string, before, after any) *Changes

Set sets both before and after values.

func (*Changes) SetAfter

func (c *Changes) SetAfter(key string, value any) *Changes

SetAfter sets an after value.

func (*Changes) SetBefore

func (c *Changes) SetBefore(key string, value any) *Changes

SetBefore sets a before value.

func (*Changes) String

func (c *Changes) String() string

String returns a string representation of changes.

type Filter

type Filter struct {
	TenantID      *shared.ID
	ActorID       *shared.ID
	Actions       []Action
	ResourceTypes []ResourceType
	ResourceID    *string
	Results       []Result
	Severities    []Severity
	Categories    []string
	RequestID     *string
	SessionID     *string
	Since         *time.Time
	Until         *time.Time
	SearchTerm    *string // Search in message, resource name, actor email
	SortBy        string
	SortOrder     string // "asc" or "desc"
	ExcludeSystem bool   // Exclude system events
}

Filter defines criteria for filtering audit logs.

func NewFilter

func NewFilter() Filter

NewFilter creates a new empty filter.

func (Filter) IsEmpty

func (f Filter) IsEmpty() bool

IsEmpty checks if no filters are applied.

func (Filter) WithActions

func (f Filter) WithActions(actions ...Action) Filter

WithActions sets the actions filter.

func (Filter) WithActorID

func (f Filter) WithActorID(actorID shared.ID) Filter

WithActorID sets the actor ID filter.

func (Filter) WithCategories

func (f Filter) WithCategories(categories ...string) Filter

WithCategories sets the categories filter.

func (Filter) WithExcludeSystem

func (f Filter) WithExcludeSystem(exclude bool) Filter

WithExcludeSystem sets the exclude system filter.

func (Filter) WithRequestID

func (f Filter) WithRequestID(requestID string) Filter

WithRequestID sets the request ID filter.

func (Filter) WithResourceID

func (f Filter) WithResourceID(resourceID string) Filter

WithResourceID sets the resource ID filter.

func (Filter) WithResourceTypes

func (f Filter) WithResourceTypes(types ...ResourceType) Filter

WithResourceTypes sets the resource types filter.

func (Filter) WithResults

func (f Filter) WithResults(results ...Result) Filter

WithResults sets the results filter.

func (Filter) WithSearchTerm

func (f Filter) WithSearchTerm(term string) Filter

WithSearchTerm sets the search term filter.

func (Filter) WithSessionID

func (f Filter) WithSessionID(sessionID string) Filter

WithSessionID sets the session ID filter.

func (Filter) WithSeverities

func (f Filter) WithSeverities(severities ...Severity) Filter

WithSeverities sets the severities filter.

func (Filter) WithSince

func (f Filter) WithSince(since time.Time) Filter

WithSince sets the since time filter.

func (Filter) WithSort

func (f Filter) WithSort(sortBy, sortOrder string) Filter

WithSort sets the sort order.

func (Filter) WithTenantID

func (f Filter) WithTenantID(tenantID shared.ID) Filter

WithTenantID sets the tenant ID filter.

func (Filter) WithTimeRange

func (f Filter) WithTimeRange(since, until time.Time) Filter

WithTimeRange sets both since and until time filters.

func (Filter) WithUntil

func (f Filter) WithUntil(until time.Time) Filter

WithUntil sets the until time filter.

type Repository

type Repository interface {
	// Create persists a new audit log entry.
	Create(ctx context.Context, log *AuditLog) error

	// CreateBatch persists multiple audit log entries.
	CreateBatch(ctx context.Context, logs []*AuditLog) error

	// GetByID retrieves an audit log by ID.
	GetByID(ctx context.Context, id shared.ID) (*AuditLog, error)

	// GetByTenantAndID retrieves an audit log by tenant and ID.
	GetByTenantAndID(ctx context.Context, tenantID, id shared.ID) (*AuditLog, error)

	// List retrieves audit logs matching the filter with pagination.
	List(ctx context.Context, filter Filter, page pagination.Pagination) (pagination.Result[*AuditLog], error)

	// Count returns the count of audit logs matching the filter.
	Count(ctx context.Context, filter Filter) (int64, error)

	// DeleteOlderThan deletes audit logs older than the specified time.
	// Used for retention policy enforcement.
	DeleteOlderThan(ctx context.Context, before time.Time) (int64, error)

	// GetLatestByResource retrieves the latest audit log for a resource.
	GetLatestByResource(ctx context.Context, resourceType ResourceType, resourceID string) (*AuditLog, error)

	// ListByActor retrieves audit logs for a specific actor.
	ListByActor(ctx context.Context, actorID shared.ID, page pagination.Pagination) (pagination.Result[*AuditLog], error)

	// ListByResource retrieves audit logs for a specific resource.
	ListByResource(ctx context.Context, resourceType ResourceType, resourceID string, page pagination.Pagination) (pagination.Result[*AuditLog], error)

	// CountByAction counts occurrences of an action within a time range.
	CountByAction(ctx context.Context, tenantID *shared.ID, action Action, since time.Time) (int64, error)
}

Repository defines the interface for audit log persistence.

type ResourceType

type ResourceType string

ResourceType represents the type of resource being acted upon.

const (
	ResourceTypeUser             ResourceType = "user"
	ResourceTypeTenant           ResourceType = "tenant"
	ResourceTypeMembership       ResourceType = "membership"
	ResourceTypeInvitation       ResourceType = "invitation"
	ResourceTypeRepository       ResourceType = "repository"
	ResourceTypeBranch           ResourceType = "branch"
	ResourceTypeComponent        ResourceType = "component"
	ResourceTypeVulnerability    ResourceType = "vulnerability"
	ResourceTypeFinding          ResourceType = "finding"
	ResourceTypeFindingComment   ResourceType = "finding_comment"
	ResourceTypeSLAPolicy        ResourceType = "sla_policy"
	ResourceTypeScan             ResourceType = "scan"
	ResourceTypeAsset            ResourceType = "asset"
	ResourceTypeSettings         ResourceType = "settings"
	ResourceTypeToken            ResourceType = "token"
	ResourceTypeAgent            ResourceType = "agent"
	ResourceTypeGroup            ResourceType = "group"
	ResourceTypePermissionSet    ResourceType = "permission_set"
	ResourceTypeRole             ResourceType = "role"
	ResourceTypePipelineTemplate ResourceType = "pipeline_template"
	ResourceTypePipelineStep     ResourceType = "pipeline_step"
	ResourceTypePipelineRun      ResourceType = "pipeline_run"
	ResourceTypeScanConfig       ResourceType = "scan_config"
	ResourceTypeWorkflow         ResourceType = "workflow"
	ResourceTypeWorkflowRun      ResourceType = "workflow_run"
	ResourceTypeCapability       ResourceType = "capability"
	ResourceTypeTool             ResourceType = "tool"
	ResourceTypeRuleSource       ResourceType = "rule_source"
	ResourceTypeRuleOverride     ResourceType = "rule_override"
	ResourceTypeIngest           ResourceType = "ingest"
	ResourceTypeAITriage         ResourceType = "ai_triage"
)

func (ResourceType) IsValid

func (r ResourceType) IsValid() bool

IsValid checks if the resource type is valid.

func (ResourceType) String

func (r ResourceType) String() string

String returns the string representation of the resource type.

type Result

type Result string

Result represents the outcome of an action.

const (
	ResultSuccess Result = "success"
	ResultFailure Result = "failure"
	ResultDenied  Result = "denied"
)

func (Result) IsValid

func (r Result) IsValid() bool

IsValid checks if the result is valid.

func (Result) String

func (r Result) String() string

String returns the string representation of the result.

type Severity

type Severity string

Severity represents the severity level of an audit event.

const (
	SeverityLow      Severity = "low"
	SeverityMedium   Severity = "medium"
	SeverityHigh     Severity = "high"
	SeverityCritical Severity = "critical"
)

func SeverityForAction

func SeverityForAction(a Action) Severity

SeverityForAction returns the default severity for an action.

func (Severity) IsValid

func (s Severity) IsValid() bool

IsValid checks if the severity is valid.

func (Severity) String

func (s Severity) String() string

String returns the string representation of the severity.

Jump to

Keyboard shortcuts

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