db

package
v1.0.2 Latest Latest
Warning

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

Go to latest
Published: Jul 25, 2026 License: Apache-2.0 Imports: 26 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Index

Constants

View Source
const (
	// DefaultTenantID applies when no tenant is explicitly provided in context.
	DefaultTenantID = "default"
	// DefaultWorkspaceID applies when no workspace is explicitly provided in context.
	DefaultWorkspaceID = "default"
)
View Source
const (
	ScanEventLevelDebug = "debug"
	ScanEventLevelInfo  = "info"
	ScanEventLevelWarn  = "warn"
	ScanEventLevelError = "error"

	RepoScanModeDeep  = "deep"
	RepoScanModeDelta = "delta"
	RepoScanModeQuick = "quick"

	FindingTriageActionAcknowledged = "acknowledged"
	FindingTriageActionSuppressed   = "suppressed"
	FindingTriageActionResolved     = "resolved"
	FindingTriageActionReopened     = "reopened"
	FindingTriageActionAssigned     = "assignee_updated"
	FindingTriageActionSuppression  = "suppression_updated"
	FindingTriageActionCommented    = "commented"

	AuthzEntityKindSubject  = "subject"
	AuthzEntityKindResource = "resource"

	AuthzAttributeEnvProd    = "prod"
	AuthzAttributeEnvStaging = "staging"
	AuthzAttributeEnvDev     = "dev"
	AuthzAttributeEnvTest    = "test"
	AuthzAttributeEnvSandbox = "sandbox"

	AuthzAttributeRiskTierLow      = "low"
	AuthzAttributeRiskTierMedium   = "medium"
	AuthzAttributeRiskTierHigh     = "high"
	AuthzAttributeRiskTierCritical = "critical"

	AuthzAttributeClassificationPublic       = "public"
	AuthzAttributeClassificationInternal     = "internal"
	AuthzAttributeClassificationConfidential = "confidential"
	AuthzAttributeClassificationRestricted   = "restricted"

	AuthzRelationshipOwns           = "owns"
	AuthzRelationshipManages        = "manages"
	AuthzRelationshipDelegatedAdmin = "delegated_admin"
	AuthzRelationshipMemberOf       = "member_of"

	AuthzPolicyRolloutModeDisabled = "disabled"
	AuthzPolicyRolloutModeShadow   = "shadow"
	AuthzPolicyRolloutModeEnforce  = "enforce"
)
View Source
const (
	// UserDataExportDownloadTTL is how long a completed bundle's signed
	// download URL stays valid after the job finishes.
	UserDataExportDownloadTTL = 24 * time.Hour
	// UserDataExportRetention is how long a completed bundle is kept on
	// disk before the GC pass deletes the file and marks the row purged.
	UserDataExportRetention = 7 * 24 * time.Hour
)

Self-serve data-export lifecycle constants (#1421). Held here so the API, worker, and store agree on the same TTLs without drifting if any one of them is changed in isolation.

View Source
const (
	UserDataExportStatusQueued  = "queued"
	UserDataExportStatusRunning = "running"
	UserDataExportStatusReady   = "ready"
	UserDataExportStatusFailed  = "failed"
	UserDataExportStatusExpired = "expired"
)

User-data-export job lifecycle status values.

View Source
const (
	WorkspaceStatusActive    = "active"
	WorkspaceStatusSuspended = "suspended"
	WorkspaceStatusDeleted   = "deleted"
)

Workspace lifecycle statuses persisted on tenancy_workspaces.status.

View Source
const (
	RepoScanSourceHealthComplete          = "complete"
	RepoScanSourceHealthPartial           = "partial"
	RepoScanSourceHealthPermissionLimited = "permission_limited"
	RepoScanSourceHealthRateLimited       = "rate_limited"
	RepoScanSourceHealthUnavailable       = "unavailable"
	RepoScanSourceHealthUnknown           = "unknown"
)
View Source
const (
	AWSAccountRegionCoverageUnknown     = "unknown"
	AWSAccountRegionCoveragePending     = "pending"
	AWSAccountRegionCoverageCovered     = "covered"
	AWSAccountRegionCoverageGap         = "gap"
	AWSAccountRegionCoverageError       = "error"
	AWSAccountRegionCoverageSuspended   = "suspended"
	AWSAccountRegionCoverageDisabled    = "disabled"
	AWSAccountRegionCoverageUnreachable = "unreachable"
)
View Source
const (
	AWSPlatformBaselineStatusNotRun   = "not_run"
	AWSPlatformBaselineStatusReady    = "ready"
	AWSPlatformBaselineStatusDegraded = "degraded"
	AWSPlatformBaselineStatusBlocked  = "blocked"

	AWSPlatformBaselineCheckPassed           = "passed"
	AWSPlatformBaselineCheckFailed           = "failed"
	AWSPlatformBaselineCheckDegraded         = "degraded"
	AWSPlatformBaselineCheckPermissionDenied = "permission_denied"
	AWSPlatformBaselineCheckUnknown          = "unknown"
	AWSPlatformBaselineCheckSkipped          = "skipped"
)
View Source
const DefaultScanMaxRetryCount = 3
View Source
const SessionIdleTimeout = 24 * time.Hour

SessionIdleTimeout is the sliding browser-session renewal window.

View Source
const UserDeletionGracePeriod = 30 * 24 * time.Hour

UserDeletionGracePeriod is the window between the soft-delete request and the hard-delete worker pass during which the user can cancel deletion. It is a const so the API and worker agree on the same number — drifting between them would mean the cancel-deletion endpoint advertises a date the worker does not honor.

View Source
const WebhookEventRetention = 30 * 24 * time.Hour

WebhookEventRetention bounds how long a webhook idempotency row is kept. It must comfortably exceed any provider's retry/replay window (WorkOS retries over days) while keeping the ledger from growing unbounded; rows older than this are opportunistically pruned on the claim path.

View Source
const WebhookProcessingReclaimAfter = 5 * time.Minute

WebhookProcessingReclaimAfter bounds how long a "processing" row may sit before another delivery may reclaim it. It protects against an instance that crashed mid-processing wedging an event forever; it is far longer than the webhook handler's own processing time.

View Source
const WorkspaceDeletionGracePeriod = 30 * 24 * time.Hour

WorkspaceDeletionGracePeriod mirrors UserDeletionGracePeriod for workspace lifecycle. The window between a workspace soft-delete and the worker hard purge. See migration 000036_workspace_lifecycle.

Variables

View Source
var ErrConflict = errors.New("record conflict")

ErrConflict indicates the requested write conflicts with an existing record.

View Source
var ErrNotFound = errors.New("record not found")

ErrNotFound indicates the requested record does not exist.

View Source
var ErrPendingRepoScanExists = errors.New("pending repo scan exists")

ErrPendingRepoScanExists indicates the target repository already has a queued or running scan.

View Source
var ErrPendingScanExists = errors.New("pending scan already exists")

ErrPendingScanExists indicates one queued or running scan already exists for the provider scope.

View Source
var ErrQueueLimitReached = errors.New("queue limit reached")

ErrQueueLimitReached indicates a bounded queue has no remaining capacity.

View Source
var ErrScopeRequired = errors.New("scope is required")

ErrScopeRequired indicates tenant/workspace scope must be provided in context.

Functions

func ApplyDownMigrations

func ApplyDownMigrations(ctx context.Context, db *sql.DB, dir string) error

ApplyDownMigrations applies down migration scripts in rollback order.

func ApplyMigrations

func ApplyMigrations(ctx context.Context, db *sql.DB, dir string) error

ApplyMigrations applies migration scripts from directory against db.

func HardDeletedTombstoneEmail added in v1.0.2

func HardDeletedTombstoneEmail(userID string) string

HardDeletedTombstoneEmail returns the deterministic, PII-free placeholder address assigned to a user row when its account is hard-deleted.

func HardDeletedWorkspaceMarker added in v1.0.2

func HardDeletedWorkspaceMarker(workspaceID string) string

HardDeletedWorkspaceMarker returns the synthetic workspace identifier the workspace hard-delete worker emits on its audit event so downstream consumers can recognize references to purged workspaces without needing a live row to dereference.

func IsHardDeletedTombstoneEmailForUser added in v1.0.2

func IsHardDeletedTombstoneEmailForUser(email string, userID string) bool

IsHardDeletedTombstoneEmailForUser reports whether `email` is exactly the deterministic tombstone for `userID`. Exact per-user matching avoids the false positives a generic prefix+suffix scan would invite — a malicious signup with the right shape could otherwise convince the worker that an active account had already been purged and exclude it from future runs.

func IsHardDeletedWorkspaceMarker added in v1.0.2

func IsHardDeletedWorkspaceMarker(identifier string) bool

IsHardDeletedWorkspaceMarker reports whether the supplied identifier is a hard-delete marker emitted by the workspace purge worker.

func MatchScope

func MatchScope(scope Scope, tenantID string, workspaceID string) bool

MatchScope returns true when record scope matches the active scope.

func NormalizeFindingTriage

func NormalizeFindingTriage(triage domain.FindingTriage, now time.Time) domain.FindingTriage

NormalizeFindingTriage returns a stable, API-shaped finding triage state.

func NormalizeScanEventLevel

func NormalizeScanEventLevel(level string) (string, error)

NormalizeScanEventLevel validates and normalizes event levels.

func QueueTraceContextFromContext

func QueueTraceContextFromContext(ctx context.Context) (string, string)

QueueTraceContextFromContext returns queue trace propagation headers from context.

func ResolveScopedWorkspaceID

func ResolveScopedWorkspaceID(scope Scope, workspaceID string) (string, error)

ResolveScopedWorkspaceID normalizes one workspace identifier and enforces that it remains within the active request scope.

func WithDefaultScope

func WithDefaultScope(ctx context.Context, fallback Scope) context.Context

WithDefaultScope applies fallback scope only when context has no scope.

func WithQueueTraceContext

func WithQueueTraceContext(ctx context.Context, traceParent string, traceState string) context.Context

WithQueueTraceContext stores queue trace propagation headers in context.

func WithScope

func WithScope(ctx context.Context, scope Scope) context.Context

WithScope stores scope in context.

Types

type AWSAccountRegionCoverage added in v1.0.2

type AWSAccountRegionCoverage struct {
	TenantID                 string         `json:"tenant_id"`
	WorkspaceID              string         `json:"workspace_id"`
	ProjectID                string         `json:"project_id"`
	ConnectorID              string         `json:"connector_id"`
	AccountID                string         `json:"account_id"`
	AccountAlias             string         `json:"account_alias,omitempty"`
	OrganizationID           string         `json:"organization_id,omitempty"`
	OUPath                   string         `json:"ou_path,omitempty"`
	Partition                string         `json:"partition"`
	Region                   string         `json:"region"`
	RoleARN                  string         `json:"role_arn,omitempty"`
	CoverageStatus           string         `json:"coverage_status"`
	LastSuccessfulScanAt     *time.Time     `json:"last_successful_scan_at,omitempty"`
	LastObservedErrorCode    string         `json:"last_observed_error_code,omitempty"`
	LastObservedErrorMessage string         `json:"last_observed_error_message,omitempty"`
	ScanCursor               map[string]any `json:"scan_cursor"`
	Suspended                bool           `json:"suspended"`
	Disabled                 bool           `json:"disabled"`
	Unreachable              bool           `json:"unreachable"`
	CreatedAt                time.Time      `json:"created_at"`
	UpdatedAt                time.Time      `json:"updated_at"`
}

AWSAccountRegionCoverage stores account/region inventory and scan readiness for one project-scoped AWS connector. Connector health describes whether Identrail can use the connector role; coverage describes each target account and region reachable through that connector.

func NormalizeAWSAccountRegionCoverageForWrite added in v1.0.2

func NormalizeAWSAccountRegionCoverageForWrite(coverage AWSAccountRegionCoverage) (AWSAccountRegionCoverage, error)

NormalizeAWSAccountRegionCoverageForWrite validates and canonicalizes one AWS account/region coverage record before persistence.

type AWSAccountRegionCoverageFilter added in v1.0.2

type AWSAccountRegionCoverageFilter struct {
	WorkspaceID string
	ProjectID   string
	ConnectorID string
	AccountID   string
	Region      string
	Limit       int
	Offset      int
}

AWSAccountRegionCoverageFilter constrains account/region coverage reads to a scoped project and optionally one connector, account, or region.

type AWSPlatformBaselineCheck added in v1.0.2

type AWSPlatformBaselineCheck struct {
	Name          string         `json:"name"`
	Category      string         `json:"category"`
	Required      bool           `json:"required"`
	Status        string         `json:"status"`
	Message       string         `json:"message"`
	FailureReason string         `json:"failure_reason,omitempty"`
	Remediation   string         `json:"remediation,omitempty"`
	EvidenceURL   string         `json:"evidence_url,omitempty"`
	Confidence    float64        `json:"confidence"`
	Evidence      map[string]any `json:"evidence,omitempty"`
	CheckedAt     time.Time      `json:"checked_at"`
}

AWSPlatformBaselineCheck records one operator-visible readiness check for the AWS baseline gate. Evidence must never contain secret values.

type AWSPlatformBaselineFilter added in v1.0.2

type AWSPlatformBaselineFilter struct {
	WorkspaceID string
	ProjectID   string
	ConnectorID string
}

AWSPlatformBaselineFilter identifies one scoped AWS baseline result. An empty connector id returns the project-level result when no specific connector was requested.

type AWSPlatformBaselineResult added in v1.0.2

type AWSPlatformBaselineResult struct {
	TenantID                string                     `json:"tenant_id"`
	WorkspaceID             string                     `json:"workspace_id"`
	ProjectID               string                     `json:"project_id"`
	ConnectorID             string                     `json:"connector_id,omitempty"`
	GitSHA                  string                     `json:"git_sha"`
	SourceMode              string                     `json:"source_mode"`
	FixtureOnly             bool                       `json:"fixture_only"`
	ConnectorProfileVersion string                     `json:"connector_profile_version"`
	GraphContractVersion    string                     `json:"graph_contract_version"`
	AccountID               string                     `json:"account_id,omitempty"`
	Region                  string                     `json:"region,omitempty"`
	Status                  string                     `json:"status"`
	Confidence              float64                    `json:"confidence"`
	RequiredChecksPassed    bool                       `json:"required_checks_passed"`
	FailureReasons          []string                   `json:"failure_reasons"`
	EvidenceLinks           []string                   `json:"evidence_links"`
	Checks                  []AWSPlatformBaselineCheck `json:"checks"`
	VerifiedAt              time.Time                  `json:"verified_at"`
	CreatedAt               time.Time                  `json:"created_at"`
	UpdatedAt               time.Time                  `json:"updated_at"`
}

AWSPlatformBaselineResult is the persisted project-scoped readiness gate result used before AWS scans or later remediation/governance jobs can start.

func NormalizeAWSPlatformBaselineResultForWrite added in v1.0.2

func NormalizeAWSPlatformBaselineResultForWrite(result AWSPlatformBaselineResult) (AWSPlatformBaselineResult, error)

NormalizeAWSPlatformBaselineResultForWrite validates and canonicalizes one AWS platform baseline gate result before persistence.

type AuthzEntityAttributes

type AuthzEntityAttributes struct {
	TenantID       string    `json:"-"`
	WorkspaceID    string    `json:"-"`
	EntityKind     string    `json:"entity_kind"`
	EntityType     string    `json:"entity_type"`
	EntityID       string    `json:"entity_id"`
	OwnerTeam      string    `json:"owner_team,omitempty"`
	Environment    string    `json:"env,omitempty"`
	RiskTier       string    `json:"risk_tier,omitempty"`
	Classification string    `json:"classification,omitempty"`
	UpdatedAt      time.Time `json:"updated_at"`
}

AuthzEntityAttributes stores trusted policy attributes for one subject or resource.

func NormalizeAuthzEntityAttributesForWrite

func NormalizeAuthzEntityAttributesForWrite(attrs AuthzEntityAttributes) (AuthzEntityAttributes, error)

NormalizeAuthzEntityAttributesForWrite validates and canonicalizes trusted authz attributes.

type AuthzPolicyEvent

type AuthzPolicyEvent struct {
	ID          string         `json:"id"`
	TenantID    string         `json:"-"`
	WorkspaceID string         `json:"-"`
	PolicySetID string         `json:"policy_set_id"`
	EventType   string         `json:"event_type"`
	FromVersion *int           `json:"from_version,omitempty"`
	ToVersion   *int           `json:"to_version,omitempty"`
	Actor       string         `json:"actor,omitempty"`
	Message     string         `json:"message,omitempty"`
	Metadata    map[string]any `json:"metadata,omitempty"`
	CreatedAt   time.Time      `json:"created_at"`
}

AuthzPolicyEvent records one immutable policy lifecycle action.

func NormalizeAuthzPolicyEventForWrite

func NormalizeAuthzPolicyEventForWrite(event AuthzPolicyEvent) (AuthzPolicyEvent, error)

NormalizeAuthzPolicyEventForWrite validates and canonicalizes one immutable policy event.

type AuthzPolicyRollout

type AuthzPolicyRollout struct {
	TenantID           string    `json:"-"`
	WorkspaceID        string    `json:"-"`
	PolicySetID        string    `json:"policy_set_id"`
	ActiveVersion      *int      `json:"active_version,omitempty"`
	CandidateVersion   *int      `json:"candidate_version,omitempty"`
	Mode               string    `json:"mode"`
	TenantAllowlist    []string  `json:"tenant_allowlist,omitempty"`
	WorkspaceAllowlist []string  `json:"workspace_allowlist,omitempty"`
	CanaryPercentage   int       `json:"canary_percentage"`
	ValidatedVersions  []int     `json:"validated_versions,omitempty"`
	UpdatedBy          string    `json:"updated_by,omitempty"`
	UpdatedAt          time.Time `json:"updated_at"`
}

AuthzPolicyRollout stores one scoped rollout pointer for active/candidate versions.

func NormalizeAuthzPolicyRolloutForWrite

func NormalizeAuthzPolicyRolloutForWrite(rollout AuthzPolicyRollout) (AuthzPolicyRollout, error)

NormalizeAuthzPolicyRolloutForWrite validates and canonicalizes one rollout pointer row.

type AuthzPolicySet

type AuthzPolicySet struct {
	TenantID    string    `json:"-"`
	WorkspaceID string    `json:"-"`
	PolicySetID string    `json:"policy_set_id"`
	DisplayName string    `json:"display_name"`
	Description string    `json:"description,omitempty"`
	CreatedBy   string    `json:"created_by,omitempty"`
	CreatedAt   time.Time `json:"created_at"`
	UpdatedAt   time.Time `json:"updated_at"`
}

AuthzPolicySet stores one scoped policy namespace and metadata.

func NormalizeAuthzPolicySetForWrite

func NormalizeAuthzPolicySetForWrite(policySet AuthzPolicySet) (AuthzPolicySet, error)

NormalizeAuthzPolicySetForWrite validates and canonicalizes one policy-set metadata row.

type AuthzPolicyVersion

type AuthzPolicyVersion struct {
	TenantID    string    `json:"-"`
	WorkspaceID string    `json:"-"`
	PolicySetID string    `json:"policy_set_id"`
	Version     int       `json:"version"`
	Bundle      string    `json:"bundle"`
	Checksum    string    `json:"checksum"`
	CreatedBy   string    `json:"created_by,omitempty"`
	CreatedAt   time.Time `json:"created_at"`
}

AuthzPolicyVersion stores one immutable compiled policy bundle.

func NormalizeAuthzPolicyVersionForWrite

func NormalizeAuthzPolicyVersionForWrite(version AuthzPolicyVersion) (AuthzPolicyVersion, error)

NormalizeAuthzPolicyVersionForWrite validates and canonicalizes one immutable policy bundle version.

type AuthzRelationship

type AuthzRelationship struct {
	TenantID    string     `json:"-"`
	WorkspaceID string     `json:"-"`
	SubjectType string     `json:"subject_type"`
	SubjectID   string     `json:"subject_id"`
	Relation    string     `json:"relation"`
	ObjectType  string     `json:"object_type"`
	ObjectID    string     `json:"object_id"`
	Source      string     `json:"source,omitempty"`
	ExpiresAt   *time.Time `json:"expires_at,omitempty"`
	CreatedAt   time.Time  `json:"created_at"`
	UpdatedAt   time.Time  `json:"updated_at"`
}

AuthzRelationship stores one directional relation tuple used by ReBAC checks.

func NormalizeAuthzRelationshipForWrite

func NormalizeAuthzRelationshipForWrite(relationship AuthzRelationship) (AuthzRelationship, error)

NormalizeAuthzRelationshipForWrite validates and canonicalizes relationship tuples.

type AuthzRelationshipFilter

type AuthzRelationshipFilter struct {
	SubjectType    string
	SubjectID      string
	Relation       string
	ObjectType     string
	ObjectID       string
	IncludeExpired bool
}

AuthzRelationshipFilter controls scoped ReBAC tuple listing.

type FindingListFilter

type FindingListFilter struct {
	ScanID          string
	FindingID       string
	Severity        string
	Type            string
	LifecycleStatus string
	Assignee        string
	SortBy          string
	SortDesc        bool
	Limit           int
	Offset          int
	Now             time.Time
}

FindingListFilter controls filtered finding list queries.

func NormalizeFindingListFilter

func NormalizeFindingListFilter(filter FindingListFilter) FindingListFilter

NormalizeFindingListFilter trims inputs and applies stable defaults.

type FindingMeta

type FindingMeta struct {
	ID        string
	ScanID    string
	Severity  string
	Type      string
	CreatedAt time.Time
}

FindingMeta is the lightweight shape used for trend/diff set operations.

type FindingSummaryCounts

type FindingSummaryCounts struct {
	Total      int
	BySeverity map[string]int
	ByType     map[string]int
}

FindingSummaryCounts captures aggregate finding counters for one scoped workspace.

type FindingTrendCount

type FindingTrendCount struct {
	ScanID     string
	StartedAt  time.Time
	Severity   string
	TotalCount int
}

FindingTrendCount aggregates finding totals for one scan and severity bucket.

type FindingTriageEvent

type FindingTriageEvent struct {
	ID                   string                        `json:"id"`
	FindingID            string                        `json:"finding_id"`
	Action               string                        `json:"action"`
	FromStatus           domain.FindingLifecycleStatus `json:"from_status"`
	ToStatus             domain.FindingLifecycleStatus `json:"to_status"`
	Assignee             string                        `json:"assignee,omitempty"`
	SuppressionExpiresAt *time.Time                    `json:"suppression_expires_at,omitempty"`
	Comment              string                        `json:"comment,omitempty"`
	Actor                string                        `json:"actor,omitempty"`
	CreatedAt            time.Time                     `json:"created_at"`
}

FindingTriageEvent records one immutable workflow action.

type FindingTriageState

type FindingTriageState struct {
	FindingID            string                        `json:"finding_id"`
	Status               domain.FindingLifecycleStatus `json:"status"`
	Assignee             string                        `json:"assignee,omitempty"`
	SuppressionExpiresAt *time.Time                    `json:"suppression_expires_at,omitempty"`
	// ResolvedAt is non-nil only while Status is resolved; it captures the
	// resolution time so the executive report can compute accurate MTTR.
	ResolvedAt *time.Time `json:"resolved_at,omitempty"`
	UpdatedAt  time.Time  `json:"updated_at"`
	UpdatedBy  string     `json:"updated_by,omitempty"`
}

FindingTriageState stores mutable workflow metadata for one finding id.

type IdentityConnection

type IdentityConnection struct {
	ID                     string            `json:"id"`
	OrgID                  string            `json:"org_id"`
	Provider               string            `json:"provider"`
	Type                   string            `json:"type"`
	WorkOSConnectionID     string            `json:"workos_connection_id,omitempty"`
	Status                 string            `json:"status"`
	GroupRoleMap           map[string]string `json:"group_role_map"`
	SSORequired            bool              `json:"sso_required"`
	JITProvisioningEnabled bool              `json:"jit_provisioning_enabled"`
	EntityID               string            `json:"entity_id,omitempty"`
	SSOURL                 string            `json:"sso_url,omitempty"`
	CertificatePEM         string            `json:"certificate_pem,omitempty"`
	AttributeMapping       map[string]string `json:"attribute_mapping,omitempty"`
	SCIMBearerTokenHash    string            `json:"scim_bearer_token_hash,omitempty"`
	CreatedAt              time.Time         `json:"created_at"`
	UpdatedAt              time.Time         `json:"updated_at"`
}

IdentityConnection stores one enterprise SSO or directory-sync connection.

A row with Provider == "saml" must be either WorkOS-backed (the legacy path, WorkOSConnectionID populated and native fields zero) or native (EntityID, SSOURL, and CertificatePEM all populated; SSOURL must use https). The two modes are mutually exclusive at write time so callers cannot end up with a half-configured connection.

func NormalizeIdentityConnectionForWrite

func NormalizeIdentityConnectionForWrite(connection IdentityConnection) (IdentityConnection, error)

NormalizeIdentityConnectionForWrite validates and canonicalizes one enterprise identity connection scaffold.

func (IdentityConnection) IsNativeSAML

func (c IdentityConnection) IsNativeSAML() bool

IsNativeSAML reports whether this connection drives native SAML directly (as opposed to delegating to WorkOS). Only meaningful when Provider=="saml".

type IdentityFilter

type IdentityFilter struct {
	ScanID     string
	Provider   string
	Type       string
	NamePrefix string
}

IdentityFilter controls identity list query shape.

type Invitation

type Invitation struct {
	ID              string     `json:"id"`
	OrgID           string     `json:"org_id"`
	Email           string     `json:"email"`
	Role            string     `json:"role"`
	InvitedByUserID string     `json:"invited_by_user_id"`
	TokenHash       []byte     `json:"-"`
	ExpiresAt       time.Time  `json:"expires_at"`
	AcceptedAt      *time.Time `json:"accepted_at,omitempty"`
	RevokedAt       *time.Time `json:"revoked_at,omitempty"`
	CreatedAt       time.Time  `json:"created_at"`
}

Invitation stores one organization invitation scaffold for later invite flows.

func NormalizeInvitationForWrite

func NormalizeInvitationForWrite(invitation Invitation) (Invitation, error)

NormalizeInvitationForWrite validates and canonicalizes one organization invite scaffold.

type MemoryStore

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

MemoryStore is a concurrency-safe in-memory persistence adapter.

func NewMemoryStore

func NewMemoryStore() *MemoryStore

NewMemoryStore initializes an empty in-memory store.

func (*MemoryStore) AppendAuthzPolicyEvent

func (m *MemoryStore) AppendAuthzPolicyEvent(ctx context.Context, event AuthzPolicyEvent) error

AppendAuthzPolicyEvent records one immutable policy lifecycle event.

func (*MemoryStore) AppendFindingTriageEvent

func (m *MemoryStore) AppendFindingTriageEvent(ctx context.Context, event FindingTriageEvent) error

AppendFindingTriageEvent records one immutable triage action.

func (*MemoryStore) AppendScanEvent

func (m *MemoryStore) AppendScanEvent(ctx context.Context, scanID string, level string, message string, metadata map[string]any) error

AppendScanEvent appends one scan event entry.

func (*MemoryStore) ApplyFindingTriageTransition

func (m *MemoryStore) ApplyFindingTriageTransition(ctx context.Context, state FindingTriageState, event FindingTriageEvent) error

ApplyFindingTriageTransition persists state and audit history atomically.

func (*MemoryStore) BeginWebhookEvent

func (m *MemoryStore) BeginWebhookEvent(ctx context.Context, event WebhookEvent, now time.Time) (WebhookEventStatus, string, error)

BeginWebhookEvent atomically claims a webhook event for processing. The mutex makes the read-decide-write sequence atomic, mirroring the Postgres INSERT ... ON CONFLICT path. A claim (insert or stale reclaim) mints a fresh claim token that fences the eventual Complete/Delete.

func (*MemoryStore) CancelRepoScan

func (m *MemoryStore) CancelRepoScan(ctx context.Context, repoScanID string, finishedAt time.Time, errorMessage string) (RepoScanRecord, error)

CancelRepoScan marks a queued or running repository scan as terminal failed.

func (*MemoryStore) CancelUserDeletion added in v1.0.2

func (m *MemoryStore) CancelUserDeletion(ctx context.Context, userID string, now time.Time) (User, error)

CancelUserDeletion reverses a soft delete: it clears deleted_at and returns the account to active.

func (*MemoryStore) CancelWorkspaceDeletion added in v1.0.2

func (m *MemoryStore) CancelWorkspaceDeletion(ctx context.Context, workspaceID string, now time.Time) (TenancyWorkspace, error)

CancelWorkspaceDeletion reverses a soft delete during the grace window: clears deleted_at and returns the workspace to status=active.

func (*MemoryStore) ClaimKubernetesEnrollmentToken

func (m *MemoryStore) ClaimKubernetesEnrollmentToken(ctx context.Context, workspaceID string, projectID string, connectorID string, expectedEnrollmentTokenHash string, updatedMetadata map[string]any, status domain.ConnectorStatus, health string, lastErrorCode string, lastErrorMessage string, observedAt time.Time, updatedAt time.Time) (bool, error)

ClaimKubernetesEnrollmentToken marks a single connector enrollment token as consumed.

func (*MemoryStore) ClaimNextQueuedRepoScan

func (m *MemoryStore) ClaimNextQueuedRepoScan(ctx context.Context) (RepoScanRecord, error)

ClaimNextQueuedRepoScan moves one queued repository scan to running for execution.

func (*MemoryStore) ClaimNextQueuedRepoScanAnyScope

func (m *MemoryStore) ClaimNextQueuedRepoScanAnyScope(_ context.Context) (RepoScanRecord, error)

ClaimNextQueuedRepoScanAnyScope moves one queued repository scan to running across all tenant/workspace scopes.

func (*MemoryStore) ClaimNextQueuedScan

func (m *MemoryStore) ClaimNextQueuedScan(ctx context.Context, provider string) (ScanRecord, error)

ClaimNextQueuedScan moves one queued scan to running for execution.

func (*MemoryStore) ClaimNextQueuedScanAnyScope

func (m *MemoryStore) ClaimNextQueuedScanAnyScope(_ context.Context, provider string) (ScanRecord, error)

ClaimNextQueuedScanAnyScope moves one queued scan to running across all tenant/workspace scopes.

func (*MemoryStore) ClaimNextQueuedUserDataExport added in v1.0.2

func (m *MemoryStore) ClaimNextQueuedUserDataExport(ctx context.Context, now time.Time) (UserDataExport, error)

ClaimNextQueuedUserDataExport pops the oldest queued job and marks it running. Returns ErrNotFound when nothing is queued.

func (*MemoryStore) ClaimQueuedUserDataExport added in v1.0.2

func (m *MemoryStore) ClaimQueuedUserDataExport(ctx context.Context, jobID string, now time.Time) (UserDataExport, error)

ClaimQueuedUserDataExport marks the named queued job running. Returns ErrNotFound when the job is already claimed or terminal.

func (*MemoryStore) ClaimTenancyScanPolicySchedule

func (m *MemoryStore) ClaimTenancyScanPolicySchedule(ctx context.Context, workspaceID string, projectID string, policyID string, scheduledAt time.Time, now time.Time) (bool, error)

ClaimTenancyScanPolicySchedule atomically records the scheduled tick claimed by a worker.

func (*MemoryStore) Close

func (m *MemoryStore) Close() error

Close closes store resources.

func (*MemoryStore) CompleteRepoScan

func (m *MemoryStore) CompleteRepoScan(ctx context.Context, repoScanID string, status string, finishedAt time.Time, commitsScanned int, filesScanned int, findingCount int, truncated bool, scanContext RepoScanContext, errorMessage string) error

CompleteRepoScan finalizes repo scan metadata.

func (*MemoryStore) CompleteScan

func (m *MemoryStore) CompleteScan(ctx context.Context, scanID string, status string, finishedAt time.Time, assetCount int, findingCount int, errorMessage string) error

CompleteScan finalizes persisted scan metadata.

func (*MemoryStore) CompleteUserDataExport added in v1.0.2

func (m *MemoryStore) CompleteUserDataExport(ctx context.Context, jobID string, bundlePath string, sizeBytes int64, sha256Hex string, completedAt time.Time, downloadExpiresAt time.Time, purgeAfter time.Time) (UserDataExport, error)

CompleteUserDataExport marks the job ready and records bundle metadata.

func (*MemoryStore) CompleteWebhookEvent

func (m *MemoryStore) CompleteWebhookEvent(ctx context.Context, provider string, eventID string, claimToken string, now time.Time) error

CompleteWebhookEvent marks a claimed event processed so later duplicates become no-op successes. It is a no-op unless claimToken still matches the active claim, so a superseded stale handler cannot complete the successor's claim.

func (*MemoryStore) ConsumeOAuthTransaction

func (m *MemoryStore) ConsumeOAuthTransaction(ctx context.Context, nonce string, cookieToken string, now time.Time) (OAuthTransaction, error)

ConsumeOAuthTransaction atomically consumes the row matching nonce and cookieToken. Re-consuming, an expired row, a missing row, or a cookie-token mismatch all return ErrNotFound so the OAuth state cannot be replayed.

func (*MemoryStore) ConsumeSAMLRelayState

func (m *MemoryStore) ConsumeSAMLRelayState(ctx context.Context, handle string, now time.Time) (SAMLRelayState, error)

ConsumeSAMLRelayState atomically marks one handle consumed and returns the stored state. Re-consuming the same handle returns ErrNotFound so the RelayState value cannot be replayed.

func (*MemoryStore) CountPendingRepoScansByRepository

func (m *MemoryStore) CountPendingRepoScansByRepository(ctx context.Context, repository string) (int, error)

CountPendingRepoScansByRepository returns queued/running scan count for one repository.

func (*MemoryStore) CountPendingScansWithSource added in v1.0.2

func (m *MemoryStore) CountPendingScansWithSource(ctx context.Context, provider string, source ScanSource) (int, error)

CountPendingScansWithSource returns queued or running scan count for one provider and scan source.

func (*MemoryStore) CountQueuedRepoScans

func (m *MemoryStore) CountQueuedRepoScans(ctx context.Context) (int, error)

CountQueuedRepoScans returns queued repository scan count.

func (*MemoryStore) CountQueuedRepoScansAnyScope

func (m *MemoryStore) CountQueuedRepoScansAnyScope(_ context.Context) (int, error)

CountQueuedRepoScansAnyScope returns queued repository scan count across all scopes.

func (*MemoryStore) CountQueuedScans

func (m *MemoryStore) CountQueuedScans(ctx context.Context, provider string) (int, error)

CountQueuedScans returns the queued scan count for one provider.

func (*MemoryStore) CountQueuedScansAnyScope

func (m *MemoryStore) CountQueuedScansAnyScope(_ context.Context, provider string) (int, error)

CountQueuedScansAnyScope returns queued scan count across all scopes for one provider.

func (*MemoryStore) CountQueuedScansWithSource added in v1.0.2

func (m *MemoryStore) CountQueuedScansWithSource(ctx context.Context, provider string, source ScanSource) (int, error)

CountQueuedScansWithSource returns the queued scan count for one provider and scan source.

func (*MemoryStore) CreateAuthzPolicyVersion

func (m *MemoryStore) CreateAuthzPolicyVersion(ctx context.Context, version AuthzPolicyVersion) (AuthzPolicyVersion, error)

CreateAuthzPolicyVersion persists one immutable policy bundle version.

func (*MemoryStore) CreateIdentityConnection

func (m *MemoryStore) CreateIdentityConnection(ctx context.Context, connection IdentityConnection) (IdentityConnection, error)

CreateIdentityConnection persists one enterprise identity connection scaffold.

func (*MemoryStore) CreateInvitation

func (m *MemoryStore) CreateInvitation(ctx context.Context, invitation Invitation) (Invitation, error)

CreateInvitation persists one invitation scaffold.

func (*MemoryStore) CreateOAuthTransaction

func (m *MemoryStore) CreateOAuthTransaction(ctx context.Context, txn OAuthTransaction) (OAuthTransaction, error)

CreateOAuthTransaction persists one in-flight WorkOS OAuth login keyed by the signed-state nonce. Used by /auth/login and /auth/signup; one-shot consumed by /auth/callback.

func (*MemoryStore) CreateQueuedRepoScan

func (m *MemoryStore) CreateQueuedRepoScan(ctx context.Context, repository string, source RepoScanSource, scanContext RepoScanContext, historyLimit int, maxFindings int, queuedAt time.Time) (RepoScanRecord, error)

CreateQueuedRepoScan persists one queued repository exposure scan request.

func (*MemoryStore) CreateQueuedRepoScanWithinLimit

func (m *MemoryStore) CreateQueuedRepoScanWithinLimit(ctx context.Context, repository string, source RepoScanSource, scanContext RepoScanContext, historyLimit int, maxFindings int, queuedAt time.Time, maxPending int) (RepoScanRecord, error)

CreateQueuedRepoScanWithinLimit persists one queued repository scan only when the target is idle and queue capacity remains.

func (*MemoryStore) CreateQueuedScan

func (m *MemoryStore) CreateQueuedScan(ctx context.Context, provider string, queuedAt time.Time) (ScanRecord, error)

CreateQueuedScan persists one queued scan request.

func (*MemoryStore) CreateQueuedScanIfNoPending

func (m *MemoryStore) CreateQueuedScanIfNoPending(ctx context.Context, provider string, queuedAt time.Time) (ScanRecord, error)

CreateQueuedScanIfNoPending persists one queued scan only when no queued/running scan exists.

func (*MemoryStore) CreateQueuedScanIfNoPendingWithSource added in v1.0.2

func (m *MemoryStore) CreateQueuedScanIfNoPendingWithSource(ctx context.Context, provider string, source ScanSource, queuedAt time.Time) (ScanRecord, error)

CreateQueuedScanIfNoPendingWithSource persists one source-bound queued scan only when no matching queued/running scan exists.

func (*MemoryStore) CreateQueuedScanWithSource added in v1.0.2

func (m *MemoryStore) CreateQueuedScanWithSource(ctx context.Context, provider string, source ScanSource, queuedAt time.Time) (ScanRecord, error)

CreateQueuedScanWithSource persists one queued scan request with project/connector source metadata.

func (*MemoryStore) CreateQueuedScanWithinLimit

func (m *MemoryStore) CreateQueuedScanWithinLimit(ctx context.Context, provider string, queuedAt time.Time, maxPending int) (ScanRecord, error)

CreateQueuedScanWithinLimit persists one queued scan request only when pending capacity remains.

func (*MemoryStore) CreateQueuedScanWithinLimitWithSource added in v1.0.2

func (m *MemoryStore) CreateQueuedScanWithinLimitWithSource(ctx context.Context, provider string, source ScanSource, queuedAt time.Time, maxPending int) (ScanRecord, error)

CreateQueuedScanWithinLimitWithSource persists one queued scan request for a source only when pending capacity remains.

func (*MemoryStore) CreateRepoScan

func (m *MemoryStore) CreateRepoScan(ctx context.Context, repository string, source RepoScanSource, scanContext RepoScanContext, startedAt time.Time) (RepoScanRecord, error)

CreateRepoScan persists one repository exposure scan start event.

func (*MemoryStore) CreateSAMLRelayState

func (m *MemoryStore) CreateSAMLRelayState(ctx context.Context, state SAMLRelayState) (SAMLRelayState, error)

CreateSAMLRelayState persists one SP-initiated SAML AuthnRequest record keyed by the opaque relay handle. Used by /auth/saml/login; consumed (one-shot) by /auth/saml/acs.

func (*MemoryStore) CreateSCIMProvisioningEvent

func (m *MemoryStore) CreateSCIMProvisioningEvent(ctx context.Context, event SCIMProvisioningEventRecord) (SCIMProvisioningEventRecord, error)

CreateSCIMProvisioningEvent appends one SCIM provisioning event to the append-only audit log scoped to the org + connection.

func (*MemoryStore) CreateScan

func (m *MemoryStore) CreateScan(ctx context.Context, provider string, startedAt time.Time) (ScanRecord, error)

CreateScan persists a scan start event.

func (*MemoryStore) CreateSession

func (m *MemoryStore) CreateSession(ctx context.Context, session Session) (Session, error)

CreateSession persists one server-side session.

func (*MemoryStore) CreateTenancyConnectorSecretEnvelopeIfAbsent added in v1.0.2

func (m *MemoryStore) CreateTenancyConnectorSecretEnvelopeIfAbsent(ctx context.Context, envelope TenancyConnectorSecretEnvelope) (TenancyConnectorSecretEnvelope, bool, error)

CreateTenancyConnectorSecretEnvelopeIfAbsent creates a secret envelope or returns the existing envelope unchanged when the scoped secret key exists.

func (*MemoryStore) CreateTenancyConnectorWithSecretEnvelopeIfAbsent added in v1.0.2

func (m *MemoryStore) CreateTenancyConnectorWithSecretEnvelopeIfAbsent(ctx context.Context, connector TenancyConnector, state TenancyConnectorState, envelope TenancyConnectorSecretEnvelope) (TenancyConnectorWithState, bool, error)

CreateTenancyConnectorWithSecretEnvelopeIfAbsent creates a connector, state, and secret envelope atomically, or returns the existing connector unchanged.

func (*MemoryStore) CreateUserDataExport added in v1.0.2

func (m *MemoryStore) CreateUserDataExport(ctx context.Context, export UserDataExport) (UserDataExport, error)

CreateUserDataExport inserts a queued export job for the user.

func (*MemoryStore) CreateVerifiedDomain

func (m *MemoryStore) CreateVerifiedDomain(ctx context.Context, domain VerifiedDomain) (VerifiedDomain, error)

CreateVerifiedDomain persists one domain-verification scaffold.

func (*MemoryStore) DeadLetterScan

func (m *MemoryStore) DeadLetterScan(ctx context.Context, scanID string, finishedAt time.Time, retryCount int, maxRetryCount int, assetCount int, findingCount int, failureCategory string, errorMessage string) error

DeadLetterScan marks a failed queued scan as operator-replayable.

func (*MemoryStore) DeleteAuthzRelationship

func (m *MemoryStore) DeleteAuthzRelationship(ctx context.Context, relationship AuthzRelationship) error

DeleteAuthzRelationship removes one scoped ReBAC tuple.

func (*MemoryStore) DeleteIdentityConnection

func (m *MemoryStore) DeleteIdentityConnection(ctx context.Context, orgID, connectionID string) error

DeleteIdentityConnection removes one persisted identity connection scoped to the (org_id, id) pair, cascading to its SCIM provisioning events. The cascade matches the ON DELETE CASCADE clause on scim_provisioning_events in Postgres so memory mode does not retain orphan audit rows for a connection that no longer exists.

func (*MemoryStore) DeleteOrganization

func (m *MemoryStore) DeleteOrganization(ctx context.Context) error

DeleteOrganization removes the active scoped tenant organization record.

func (*MemoryStore) DeleteProject

func (m *MemoryStore) DeleteProject(ctx context.Context, workspaceID string, projectID string) error

DeleteProject removes one scoped project.

func (*MemoryStore) DeleteRepoFinding added in v1.0.2

func (m *MemoryStore) DeleteRepoFinding(ctx context.Context, repoScanID string, findingID string) error

DeleteRepoFinding removes one persisted repository finding for one scan.

func (*MemoryStore) DeleteRepoFindingTargets added in v1.0.2

func (m *MemoryStore) DeleteRepoFindingTargets(ctx context.Context, targets []RepoFindingDeleteTarget) ([]RepoFindingDeleteTarget, error)

DeleteRepoFindingTargets removes selected persisted repository findings.

func (*MemoryStore) DeleteRepoFindings

func (m *MemoryStore) DeleteRepoFindings(ctx context.Context, repoScanID string) error

DeleteRepoFindings removes all persisted repository findings for one scan.

func (*MemoryStore) DeleteRepoScan added in v1.0.2

func (m *MemoryStore) DeleteRepoScan(ctx context.Context, repoScanID string) error

DeleteRepoScan removes one persisted repository scan and its findings.

func (*MemoryStore) DeleteTenancyConnectorSecretEnvelope

func (m *MemoryStore) DeleteTenancyConnectorSecretEnvelope(ctx context.Context, workspaceID string, projectID string, connectorID string, secretName string) error

DeleteTenancyConnectorSecretEnvelope removes one encrypted connector secret envelope.

func (*MemoryStore) DeleteTenancyScanPolicy

func (m *MemoryStore) DeleteTenancyScanPolicy(ctx context.Context, workspaceID string, projectID string, policyID string) error

DeleteTenancyScanPolicy removes one scoped scan policy.

func (*MemoryStore) DeleteUserIdentity

func (m *MemoryStore) DeleteUserIdentity(ctx context.Context, provider string, subject string) error

DeleteUserIdentity removes one provider identity by provider and subject.

func (*MemoryStore) DeleteWebhookEvent

func (m *MemoryStore) DeleteWebhookEvent(ctx context.Context, provider string, eventID string, claimToken string) error

DeleteWebhookEvent rolls back a claim so a provider retry can reprocess an event whose side effects failed transiently. It is a no-op unless claimToken still matches the active claim, so a superseded stale handler cannot erase the successor's claim.

func (*MemoryStore) DeleteWorkspace

func (m *MemoryStore) DeleteWorkspace(ctx context.Context, workspaceID string) error

DeleteWorkspace removes one scoped workspace and all child records.

func (*MemoryStore) DeleteWorkspaceMember

func (m *MemoryStore) DeleteWorkspaceMember(ctx context.Context, workspaceID string, memberID string) error

DeleteWorkspaceMember removes one scoped workspace member.

func (*MemoryStore) ExpandRepoFindingDeleteTargets added in v1.0.2

func (m *MemoryStore) ExpandRepoFindingDeleteTargets(ctx context.Context, targets []RepoFindingDeleteTarget) ([]RepoFindingDeleteTarget, error)

ExpandRepoFindingDeleteTargets returns every concrete finding row a delete request may remove.

func (*MemoryStore) FailStaleRepoScansAnyScope

func (m *MemoryStore) FailStaleRepoScansAnyScope(_ context.Context, staleBefore time.Time, limit int, errorMessage string) (int, error)

FailStaleRepoScansAnyScope marks stale running repository scans failed across all scopes.

func (*MemoryStore) FailStaleRunningUserDataExports added in v1.0.2

func (m *MemoryStore) FailStaleRunningUserDataExports(ctx context.Context, startedBefore time.Time, failedAt time.Time, limit int, errMsg string) ([]UserDataExport, error)

FailStaleRunningUserDataExports marks old running jobs failed so interrupted workers cannot leave exports stuck running forever.

func (*MemoryStore) FailUserDataExport added in v1.0.2

func (m *MemoryStore) FailUserDataExport(ctx context.Context, jobID string, errMsg string, failedAt time.Time) (UserDataExport, error)

FailUserDataExport marks a job failed.

func (*MemoryStore) FindFirstWorkspaceMemberByUserUUID

func (m *MemoryStore) FindFirstWorkspaceMemberByUserUUID(ctx context.Context, userUUID string) (TenancyWorkspaceMember, error)

FindFirstWorkspaceMemberByUserUUID returns the newest active workspace membership for one auth user.

func (*MemoryStore) FindFirstWorkspaceMemberByUserUUIDAndTenantID

func (m *MemoryStore) FindFirstWorkspaceMemberByUserUUIDAndTenantID(ctx context.Context, userUUID string, tenantID string) (TenancyWorkspaceMember, error)

FindFirstWorkspaceMemberByUserUUIDAndTenantID returns the newest active workspace membership for one auth user in one tenant.

func (*MemoryStore) GetAWSPlatformBaselineResult added in v1.0.2

func (m *MemoryStore) GetAWSPlatformBaselineResult(ctx context.Context, filter AWSPlatformBaselineFilter) (AWSPlatformBaselineResult, error)

GetAWSPlatformBaselineResult returns the latest scoped AWS baseline gate result.

func (*MemoryStore) GetAuthzEntityAttributes

func (m *MemoryStore) GetAuthzEntityAttributes(ctx context.Context, entityKind string, entityType string, entityID string) (AuthzEntityAttributes, error)

GetAuthzEntityAttributes returns trusted authorization attributes for one entity.

func (*MemoryStore) GetAuthzPolicyRollout

func (m *MemoryStore) GetAuthzPolicyRollout(ctx context.Context, policySetID string) (AuthzPolicyRollout, error)

GetAuthzPolicyRollout returns one scoped rollout pointer row.

func (*MemoryStore) GetAuthzPolicySet

func (m *MemoryStore) GetAuthzPolicySet(ctx context.Context, policySetID string) (AuthzPolicySet, error)

GetAuthzPolicySet returns one scoped policy set metadata record.

func (*MemoryStore) GetAuthzPolicyVersion

func (m *MemoryStore) GetAuthzPolicyVersion(ctx context.Context, policySetID string, version int) (AuthzPolicyVersion, error)

GetAuthzPolicyVersion returns one scoped immutable policy bundle version.

func (*MemoryStore) GetFinding

func (m *MemoryStore) GetFinding(ctx context.Context, findingID string, scanID string) (domain.Finding, error)

GetFinding returns one finding by id, optionally scoped to one scan id.

func (*MemoryStore) GetFindingTriageState

func (m *MemoryStore) GetFindingTriageState(ctx context.Context, findingID string) (FindingTriageState, error)

GetFindingTriageState returns triage workflow state for one finding id.

func (*MemoryStore) GetIdentityConnection

func (m *MemoryStore) GetIdentityConnection(ctx context.Context, orgID string, connectionID string) (IdentityConnection, error)

GetIdentityConnection returns one organization identity connection scaffold.

func (*MemoryStore) GetIdentityConnectionByID

func (m *MemoryStore) GetIdentityConnectionByID(ctx context.Context, connectionID string) (IdentityConnection, error)

GetIdentityConnectionByID resolves a connection by its globally unique UUID. Used by entry points that do not know the org id yet (e.g. the SAML SP-initiated login route).

Memory mode does not have the SQL UNIQUE constraint Postgres uses to guarantee global uuid uniqueness, so a buggy seed could insert two rows with the same id. Return ErrConflict in that case rather than picking a non-deterministic match.

func (*MemoryStore) GetIdentityConnectionBySCIMBearerTokenHash

func (m *MemoryStore) GetIdentityConnectionBySCIMBearerTokenHash(ctx context.Context, tokenHash string) (IdentityConnection, error)

GetIdentityConnectionBySCIMBearerTokenHash resolves a connection by its stored SCIM bearer-token hash for unauthenticated SCIM entry points.

func (*MemoryStore) GetInvitation

func (m *MemoryStore) GetInvitation(ctx context.Context, orgID string, invitationID string) (Invitation, error)

GetInvitation returns one organization invitation scaffold.

func (*MemoryStore) GetOnboardingState

func (m *MemoryStore) GetOnboardingState(ctx context.Context, userID string) (OnboardingState, error)

GetOnboardingState returns one user's onboarding progress row.

func (*MemoryStore) GetOrganization

func (m *MemoryStore) GetOrganization(ctx context.Context) (TenancyOrganization, error)

GetOrganization returns the active scoped tenant organization.

func (*MemoryStore) GetProject

func (m *MemoryStore) GetProject(ctx context.Context, workspaceID string, projectID string) (TenancyProject, error)

GetProject returns one scoped project by id.

func (*MemoryStore) GetRepoScan

func (m *MemoryStore) GetRepoScan(ctx context.Context, repoScanID string) (RepoScanRecord, error)

GetRepoScan returns one persisted repo scan by id.

func (*MemoryStore) GetRepoScanCursor

func (m *MemoryStore) GetRepoScanCursor(ctx context.Context, repository string, source RepoScanSource) (RepoScanCursor, error)

GetRepoScanCursor returns the last successful scan cursor for one repository source.

func (*MemoryStore) GetScan

func (m *MemoryStore) GetScan(ctx context.Context, scanID string) (ScanRecord, error)

GetScan returns one persisted scan by id.

func (*MemoryStore) GetTenancyConnector

func (m *MemoryStore) GetTenancyConnector(ctx context.Context, workspaceID string, projectID string, connectorID string) (TenancyConnectorWithState, error)

GetTenancyConnector returns one connector and its latest state.

func (*MemoryStore) GetTenancyConnectorSecretEnvelope

func (m *MemoryStore) GetTenancyConnectorSecretEnvelope(ctx context.Context, workspaceID string, projectID string, connectorID string, secretName string) (TenancyConnectorSecretEnvelope, error)

GetTenancyConnectorSecretEnvelope loads one encrypted connector secret envelope.

func (*MemoryStore) GetTenancyScanPolicy

func (m *MemoryStore) GetTenancyScanPolicy(ctx context.Context, workspaceID string, projectID string, policyID string) (TenancyScanPolicy, error)

GetTenancyScanPolicy returns one scoped scan policy by id.

func (*MemoryStore) GetUser

func (m *MemoryStore) GetUser(ctx context.Context, userID string) (User, error)

GetUser returns one account by UUID.

func (*MemoryStore) GetUserByPrimaryEmail

func (m *MemoryStore) GetUserByPrimaryEmail(ctx context.Context, email string) (User, error)

GetUserByPrimaryEmail returns one account by normalized primary email.

func (*MemoryStore) GetUserDataExport added in v1.0.2

func (m *MemoryStore) GetUserDataExport(ctx context.Context, userID string, jobID string) (UserDataExport, error)

GetUserDataExport returns the export job iff it belongs to the named user.

func (*MemoryStore) GetUserDataExportByID added in v1.0.2

func (m *MemoryStore) GetUserDataExportByID(ctx context.Context, jobID string) (UserDataExport, error)

GetUserDataExportByID returns the export job by id, ignoring caller scoping. The caller is responsible for authorizing the access (the download route proves authorization via HMAC token).

func (*MemoryStore) GetUserIdentity

func (m *MemoryStore) GetUserIdentity(ctx context.Context, provider string, subject string) (UserIdentity, error)

GetUserIdentity returns one provider identity by provider and subject.

func (*MemoryStore) GetUserIdentityByProviderUserID

func (m *MemoryStore) GetUserIdentityByProviderUserID(ctx context.Context, provider string, userID string) (UserIdentity, error)

GetUserIdentityByProviderUserID returns one provider identity for a user.

func (*MemoryStore) GetVerifiedDomain

func (m *MemoryStore) GetVerifiedDomain(ctx context.Context, orgID string, domainID string) (VerifiedDomain, error)

GetVerifiedDomain returns one organization domain-verification scaffold.

func (*MemoryStore) GetWorkspace

func (m *MemoryStore) GetWorkspace(ctx context.Context, workspaceID string) (TenancyWorkspace, error)

GetWorkspace returns one workspace by id in active tenant scope.

func (*MemoryStore) GetWorkspaceMember

func (m *MemoryStore) GetWorkspaceMember(ctx context.Context, workspaceID string, memberID string) (TenancyWorkspaceMember, error)

GetWorkspaceMember returns one scoped workspace member by member id.

func (*MemoryStore) GetWorkspaceMemberByUserUUID

func (m *MemoryStore) GetWorkspaceMemberByUserUUID(ctx context.Context, workspaceID string, userUUID string) (TenancyWorkspaceMember, error)

GetWorkspaceMemberByUserUUID returns one scoped workspace member by auth user UUID.

func (*MemoryStore) HardDeleteUser added in v1.0.2

func (m *MemoryStore) HardDeleteUser(ctx context.Context, userID string, now time.Time) (User, error)

HardDeleteUser purges PII from a soft-deleted account while keeping the row so audit references by UUID remain valid. It deletes provider identities (which carry raw IdP claims) and any session rows, and is safely re-runnable.

func (*MemoryStore) HardDeleteWorkspace added in v1.0.2

func (m *MemoryStore) HardDeleteWorkspace(ctx context.Context, tenantID, workspaceID string, expectedDeletedAt time.Time, now time.Time) (TenancyWorkspace, error)

HardDeleteWorkspace permanently removes a soft-deleted workspace and all of its child rows. Refuses the purge unless the workspace is genuinely past grace (status='deleted', deleted_at matches the value the worker observed when it listed the row) so:

  • workspace_id alone is not globally unique; requiring tenant_id locks the purge to the correct row.
  • a cancel-deletion + re-delete race between the worker's list and its purge call advances deleted_at to a fresh value; matching against the listed deleted_at refuses that case and lets the new 30-day window run.

func (*MemoryStore) ListAWSAccountRegionCoverages added in v1.0.2

func (m *MemoryStore) ListAWSAccountRegionCoverages(ctx context.Context, filter AWSAccountRegionCoverageFilter) ([]AWSAccountRegionCoverage, error)

ListAWSAccountRegionCoverages returns deterministic scoped AWS account/region coverage rows.

func (*MemoryStore) ListAllTenancyConnectorsByType

func (m *MemoryStore) ListAllTenancyConnectorsByType(ctx context.Context, connectorType domain.ConnectorType, limit int) ([]TenancyConnectorWithState, error)

ListAllTenancyConnectorsByType returns connectors across all scopes for internal runtime matching.

func (*MemoryStore) ListAuthzPolicyEvents

func (m *MemoryStore) ListAuthzPolicyEvents(ctx context.Context, policySetID string, limit int) ([]AuthzPolicyEvent, error)

ListAuthzPolicyEvents returns immutable lifecycle events for one policy set (newest first).

func (*MemoryStore) ListAuthzPolicyVersions

func (m *MemoryStore) ListAuthzPolicyVersions(ctx context.Context, policySetID string, limit int) ([]AuthzPolicyVersion, error)

ListAuthzPolicyVersions returns policy bundle versions for one policy set (newest first).

func (*MemoryStore) ListAuthzRelationships

func (m *MemoryStore) ListAuthzRelationships(ctx context.Context, filter AuthzRelationshipFilter, limit int) ([]AuthzRelationship, error)

ListAuthzRelationships returns filtered scoped ReBAC tuples.

func (*MemoryStore) ListFindingMetasByScan

func (m *MemoryStore) ListFindingMetasByScan(ctx context.Context, scanID string) ([]FindingMeta, error)

ListFindingMetasByScan returns lightweight finding metadata for one scan.

func (*MemoryStore) ListFindingTrendCounts

func (m *MemoryStore) ListFindingTrendCounts(ctx context.Context, scanIDs []string, severity string, findingType string) ([]FindingTrendCount, error)

ListFindingTrendCounts aggregates findings by scan and severity.

func (*MemoryStore) ListFindingTriageEvents

func (m *MemoryStore) ListFindingTriageEvents(ctx context.Context, findingID string, limit int) ([]FindingTriageEvent, error)

ListFindingTriageEvents returns triage actions newest-first for one finding id.

func (*MemoryStore) ListFindingTriageStates

func (m *MemoryStore) ListFindingTriageStates(ctx context.Context, findingIDs []string) ([]FindingTriageState, error)

ListFindingTriageStates returns triage states for provided finding ids.

func (*MemoryStore) ListFindings

func (m *MemoryStore) ListFindings(ctx context.Context, limit int) ([]domain.Finding, error)

ListFindings returns latest findings first.

func (*MemoryStore) ListFindingsAll

func (m *MemoryStore) ListFindingsAll(ctx context.Context) ([]domain.Finding, error)

ListFindingsAll returns all findings for current scope ordered by recency.

func (*MemoryStore) ListFindingsByScan

func (m *MemoryStore) ListFindingsByScan(ctx context.Context, scanID string, limit int) ([]domain.Finding, error)

ListFindingsByScan returns latest findings first for one scan.

func (*MemoryStore) ListFindingsByScanAndIDs

func (m *MemoryStore) ListFindingsByScanAndIDs(ctx context.Context, scanID string, findingIDs []string) ([]domain.Finding, error)

ListFindingsByScanAndIDs returns detailed findings for one scan and ID set.

func (*MemoryStore) ListFindingsFiltered

func (m *MemoryStore) ListFindingsFiltered(ctx context.Context, filter FindingListFilter) ([]domain.Finding, error)

ListFindingsFiltered returns findings after applying persistence-level filters and stable ordering.

func (*MemoryStore) ListIdentities

func (m *MemoryStore) ListIdentities(ctx context.Context, filter IdentityFilter, limit int) ([]domain.Identity, error)

ListIdentities returns identities filtered by scan/provider/type/name.

func (*MemoryStore) ListIdentityConnections

func (m *MemoryStore) ListIdentityConnections(ctx context.Context, orgID string, limit int) ([]IdentityConnection, error)

ListIdentityConnections returns organization identity connection scaffolds ordered by newest first.

func (*MemoryStore) ListInvitations

func (m *MemoryStore) ListInvitations(ctx context.Context, orgID string, limit int) ([]Invitation, error)

ListInvitations returns organization invitations ordered by newest first.

func (*MemoryStore) ListProjects

func (m *MemoryStore) ListProjects(ctx context.Context, workspaceID string, includeArchived bool, limit int) ([]TenancyProject, error)

ListProjects returns projects for one scoped workspace.

func (*MemoryStore) ListRelationships

func (m *MemoryStore) ListRelationships(ctx context.Context, filter RelationshipFilter, limit int) ([]domain.Relationship, error)

ListRelationships returns relationships filtered by scan/type/from/to.

func (*MemoryStore) ListRepoFindingClusters

func (m *MemoryStore) ListRepoFindingClusters(ctx context.Context, filter RepoFindingClusterListFilter) ([]domain.RepoFindingCluster, error)

ListRepoFindingClusters returns repository finding clusters using store-backed pagination semantics.

func (*MemoryStore) ListRepoFindingTrendCounts

func (m *MemoryStore) ListRepoFindingTrendCounts(ctx context.Context, repoScanIDs []string, severity string, findingType string, minConfidence float64) ([]FindingTrendCount, error)

ListRepoFindingTrendCounts aggregates repository finding totals by repo scan and severity.

func (*MemoryStore) ListRepoFindings

func (m *MemoryStore) ListRepoFindings(ctx context.Context, filter RepoFindingFilter, limit int) ([]domain.Finding, error)

ListRepoFindings returns repository findings using optional filters.

func (*MemoryStore) ListRepoScans

func (m *MemoryStore) ListRepoScans(ctx context.Context, limit int) ([]RepoScanRecord, error)

ListRepoScans returns latest repo scans first.

func (*MemoryStore) ListSCIMProvisioningEvents

func (m *MemoryStore) ListSCIMProvisioningEvents(ctx context.Context, orgID string, connectionID string, limit int) ([]SCIMProvisioningEventRecord, error)

ListSCIMProvisioningEvents returns events for one connection ordered newest first, capped at limit (default 100).

func (*MemoryStore) ListScanEvents

func (m *MemoryStore) ListScanEvents(ctx context.Context, scanID string, limit int) ([]ScanEvent, error)

ListScanEvents returns most recent scan events first.

func (*MemoryStore) ListScans

func (m *MemoryStore) ListScans(ctx context.Context, limit int) ([]ScanRecord, error)

ListScans returns latest scans first.

func (*MemoryStore) ListScheduledTenancyScanPolicies

func (m *MemoryStore) ListScheduledTenancyScanPolicies(ctx context.Context, limit int, offset int) ([]TenancyScanPolicy, error)

ListScheduledTenancyScanPolicies returns all enabled scheduled policies for worker execution.

func (*MemoryStore) ListSoleOwnerWorkspaces added in v1.0.2

func (m *MemoryStore) ListSoleOwnerWorkspaces(ctx context.Context, userUUID string) ([]TenancyWorkspace, error)

ListSoleOwnerWorkspaces returns every workspace, across all tenants, in which the user is the only active owner.

func (*MemoryStore) ListTenancyConnectors

func (m *MemoryStore) ListTenancyConnectors(ctx context.Context, workspaceID string, projectID string, connectorType domain.ConnectorType, limit int) ([]TenancyConnectorWithState, error)

ListTenancyConnectors returns scoped connectors ordered by most recent update.

func (*MemoryStore) ListTenancyConnectorsUnscoped

func (m *MemoryStore) ListTenancyConnectorsUnscoped(_ context.Context, connectorType domain.ConnectorType, limit int) ([]TenancyConnectorWithState, error)

ListTenancyConnectorsUnscoped returns connectors across all scopes for internal webhook dispatch.

func (*MemoryStore) ListTenancyScanPolicies

func (m *MemoryStore) ListTenancyScanPolicies(ctx context.Context, workspaceID string, projectID string, triggerMode domain.ScanTriggerMode, enabled *bool, sortBy string, sortDesc bool, limit int) ([]TenancyScanPolicy, error)

ListTenancyScanPolicies returns scoped policies ordered before limiting.

func (*MemoryStore) ListUserDataExports added in v1.0.2

func (m *MemoryStore) ListUserDataExports(ctx context.Context, userID string, limit int) ([]UserDataExport, error)

ListUserDataExports returns the user's exports newest-first.

func (*MemoryStore) ListUserDataExportsPendingPurge added in v1.0.2

func (m *MemoryStore) ListUserDataExportsPendingPurge(ctx context.Context, now time.Time, limit int) ([]UserDataExport, error)

ListUserDataExportsPendingPurge returns ready jobs past their retention window whose bundle file has not yet been removed.

func (*MemoryStore) ListUserIdentitiesByProvider

func (m *MemoryStore) ListUserIdentitiesByProvider(ctx context.Context, provider string, limit int) ([]UserIdentity, error)

ListUserIdentitiesByProvider returns provider identities ordered by newest first. A non-positive limit returns all matching identities.

func (*MemoryStore) ListUserSessionHistory added in v1.0.2

func (m *MemoryStore) ListUserSessionHistory(ctx context.Context, userID string, limit int) ([]Session, error)

ListUserSessionHistory returns every session row for one user, including revoked and expired sessions. A non-positive limit means no limit.

func (*MemoryStore) ListUserSessions

func (m *MemoryStore) ListUserSessions(ctx context.Context, userID string, now time.Time, limit int) ([]Session, error)

ListUserSessions returns active sessions for one user.

func (*MemoryStore) ListUsersPendingHardDelete added in v1.0.2

func (m *MemoryStore) ListUsersPendingHardDelete(ctx context.Context, deletedBefore time.Time, limit int) ([]User, error)

ListUsersPendingHardDelete returns soft-deleted accounts whose grace window closed and whose PII has not already been purged.

func (*MemoryStore) ListVerifiedDomains

func (m *MemoryStore) ListVerifiedDomains(ctx context.Context, orgID string, limit int) ([]VerifiedDomain, error)

ListVerifiedDomains returns organization domain-verification scaffolds ordered by newest first.

func (*MemoryStore) ListWorkspaceMembers

func (m *MemoryStore) ListWorkspaceMembers(ctx context.Context, workspaceID string, limit int) ([]TenancyWorkspaceMember, error)

ListWorkspaceMembers returns members for one scoped workspace.

func (*MemoryStore) ListWorkspaceMembershipsByUserUUID added in v1.0.2

func (m *MemoryStore) ListWorkspaceMembershipsByUserUUID(ctx context.Context, userUUID string) ([]TenancyWorkspaceMember, error)

ListWorkspaceMembershipsByUserUUID returns every active workspace membership the user holds across all tenants.

func (*MemoryStore) ListWorkspaceMembershipsByUserUUIDAndTenantID

func (m *MemoryStore) ListWorkspaceMembershipsByUserUUIDAndTenantID(ctx context.Context, userUUID string, tenantID string) ([]TenancyWorkspaceMember, error)

ListWorkspaceMembershipsByUserUUIDAndTenantID returns every active workspace membership the user holds within one tenant. It is the authorization basis for organization-wide reads: a caller may only aggregate data from the workspaces they actually belong to.

func (*MemoryStore) ListWorkspaceStrandedActiveMembers added in v1.0.2

func (m *MemoryStore) ListWorkspaceStrandedActiveMembers(ctx context.Context, workspaceID string, userUUID string) ([]TenancyWorkspaceMember, error)

ListWorkspaceStrandedActiveMembers returns the other active members in the workspace iff the caller is the sole active owner. Empty slice means no stranding would occur — either the caller has co-owners, or there are no other active members to strand.

func (*MemoryStore) ListWorkspaces

func (m *MemoryStore) ListWorkspaces(ctx context.Context, limit int) ([]TenancyWorkspace, error)

ListWorkspaces returns tenant-scoped workspaces ordered by created_at descending.

func (*MemoryStore) ListWorkspacesPendingHardDelete added in v1.0.2

func (m *MemoryStore) ListWorkspacesPendingHardDelete(ctx context.Context, deletedBefore time.Time, limit int) ([]TenancyWorkspace, error)

ListWorkspacesPendingHardDelete returns soft-deleted workspaces whose grace window closed. Bypasses scope so the worker can enumerate across all tenants in a single pass. Results are stable-sorted by deleted_at then workspace_id to make worker progress deterministic.

func (*MemoryStore) MarkUserDataExportPurged added in v1.0.2

func (m *MemoryStore) MarkUserDataExportPurged(ctx context.Context, jobID string, now time.Time) (UserDataExport, error)

MarkUserDataExportPurged transitions a job to expired and stamps purged_at.

func (*MemoryStore) ReactivateWorkspace added in v1.0.2

func (m *MemoryStore) ReactivateWorkspace(ctx context.Context, workspaceID string, now time.Time) (TenancyWorkspace, error)

ReactivateWorkspace flips a suspended workspace back to active and clears suspended_at. Callers that want active-workspace idempotency should check before issuing the store transition.

func (*MemoryStore) RequeueRepoScan

func (m *MemoryStore) RequeueRepoScan(ctx context.Context, repoScanID string) error

RequeueRepoScan moves a running repository scan back to queued state.

func (*MemoryStore) RevokeAllUserSessions

func (m *MemoryStore) RevokeAllUserSessions(ctx context.Context, userID string, revokedAt time.Time) (int, error)

RevokeAllUserSessions revokes every active session for one user.

func (*MemoryStore) RevokeInvitation

func (m *MemoryStore) RevokeInvitation(ctx context.Context, orgID string, invitationID string, revokedAt time.Time) (Invitation, error)

RevokeInvitation marks one pending invitation revoked.

func (*MemoryStore) RevokeOtherUserSessions

func (m *MemoryStore) RevokeOtherUserSessions(ctx context.Context, userID string, currentSessionIDHash []byte, revokedAt time.Time) (int, error)

RevokeOtherUserSessions revokes every active session except the caller's.

func (*MemoryStore) RevokeUserSession

func (m *MemoryStore) RevokeUserSession(ctx context.Context, userID string, sessionIDHash []byte, revokedAt time.Time) (Session, error)

RevokeUserSession revokes one active session if it belongs to the user.

func (*MemoryStore) ScheduleScanRetry

func (m *MemoryStore) ScheduleScanRetry(ctx context.Context, scanID string, queuedAt time.Time, retryCount int, maxRetryCount int, failureCategory string, errorMessage string, nextRetryAt time.Time) error

ScheduleScanRetry moves a failed scan attempt back to queued state with backoff metadata.

func (*MemoryStore) SetUserStatus added in v1.0.2

func (m *MemoryStore) SetUserStatus(ctx context.Context, userID string, status string, now time.Time) (User, error)

SetUserStatus transitions one account between lifecycle states. Calling with the user's current status is a no-op write and still returns the row, so the API layer can treat double-clicks as idempotent successes.

func (*MemoryStore) SoftDeleteUser added in v1.0.2

func (m *MemoryStore) SoftDeleteUser(ctx context.Context, userID string, now time.Time) (User, error)

SoftDeleteUser flips the account to status=deleted and stamps deleted_at to open the reversible grace window. Re-deleting an already-deleted account is a no-op that preserves the original deleted_at so the purge deadline cannot be pushed back by repeat calls.

func (*MemoryStore) SoftDeleteWorkspace added in v1.0.2

func (m *MemoryStore) SoftDeleteWorkspace(ctx context.Context, workspaceID string, now time.Time) (TenancyWorkspace, error)

SoftDeleteWorkspace flips the workspace to status=deleted and stamps deleted_at to open the reversible grace window. Idempotent: an existing deleted_at is preserved so repeat calls cannot extend the grace deadline.

func (*MemoryStore) SummarizeFindings

func (m *MemoryStore) SummarizeFindings(ctx context.Context) (FindingSummaryCounts, error)

SummarizeFindings returns aggregate counters for current scope without materializing router-facing copies.

func (*MemoryStore) SuspendWorkspace added in v1.0.2

func (m *MemoryStore) SuspendWorkspace(ctx context.Context, workspaceID string, now time.Time) (TenancyWorkspace, error)

SuspendWorkspace flips the workspace status to suspended and stamps suspended_at. Idempotent on an already-suspended workspace: the stored suspended_at is preserved.

func (*MemoryStore) TouchSession

func (m *MemoryStore) TouchSession(ctx context.Context, sessionIDHash []byte, now time.Time) (Session, error)

TouchSession renews idle expiry and returns the joined session/user row.

func (*MemoryStore) TouchSessionAllowingPendingDeletion added in v1.0.2

func (m *MemoryStore) TouchSessionAllowingPendingDeletion(ctx context.Context, sessionIDHash []byte, now time.Time) (Session, error)

TouchSessionAllowingPendingDeletion is the lenient variant the cancel-deletion route mounts: it accepts cookies belonging to users whose status is `deleted` and whose grace window has not closed yet, so a freshly-soft-deleted user can still hit `/v1/me/cancel-deletion` while every other route keeps refusing.

func (*MemoryStore) UpdateCurrentUserProfile added in v1.0.2

func (m *MemoryStore) UpdateCurrentUserProfile(ctx context.Context, userID string, displayName *string, avatarURL *string, updatedAt time.Time) (User, error)

UpdateCurrentUserProfile updates only self-service mutable profile fields. It leaves email and lifecycle fields untouched and requires an active row.

func (*MemoryStore) UpdateIdentityConnection

func (m *MemoryStore) UpdateIdentityConnection(ctx context.Context, connection IdentityConnection) (IdentityConnection, error)

UpdateIdentityConnection replaces one persisted identity connection scoped to the (org_id, id) pair. The Postgres path enforces the create-time uniqueness invariants via SQL UNIQUE constraints and preserves the SCIM bearer token hash via COALESCE; this method mirrors both behaviors for memory mode so a parity bug cannot let callers do something through the memory store that Postgres would reject.

func (*MemoryStore) UpdateSessionContext

func (m *MemoryStore) UpdateSessionContext(ctx context.Context, userID string, sessionIDHash []byte, orgID string, workspaceID string, projectID string, now time.Time) (Session, error)

UpdateSessionContext persists the active tenancy context for one browser session.

func (*MemoryStore) UpdateUserProfile added in v1.0.2

func (m *MemoryStore) UpdateUserProfile(ctx context.Context, user User) (User, error)

UpdateUserProfile refreshes user metadata without changing account status.

func (*MemoryStore) UpsertAWSAccountRegionCoverage added in v1.0.2

func (m *MemoryStore) UpsertAWSAccountRegionCoverage(ctx context.Context, coverage AWSAccountRegionCoverage) (AWSAccountRegionCoverage, error)

UpsertAWSAccountRegionCoverage persists one account/region coverage row for a scoped AWS connector.

func (*MemoryStore) UpsertAWSPlatformBaselineResult added in v1.0.2

func (m *MemoryStore) UpsertAWSPlatformBaselineResult(ctx context.Context, result AWSPlatformBaselineResult) (AWSPlatformBaselineResult, error)

UpsertAWSPlatformBaselineResult persists one project-scoped AWS baseline gate result.

func (*MemoryStore) UpsertArtifacts

func (m *MemoryStore) UpsertArtifacts(ctx context.Context, scanID string, artifacts ScanArtifacts) error

UpsertArtifacts persists raw and normalized scan artifacts idempotently.

func (*MemoryStore) UpsertAuthzEntityAttributes

func (m *MemoryStore) UpsertAuthzEntityAttributes(ctx context.Context, attributes AuthzEntityAttributes) error

UpsertAuthzEntityAttributes creates or updates trusted authorization attributes.

func (*MemoryStore) UpsertAuthzPolicyRollout

func (m *MemoryStore) UpsertAuthzPolicyRollout(ctx context.Context, rollout AuthzPolicyRollout) error

UpsertAuthzPolicyRollout creates or updates one scoped rollout pointer row.

func (*MemoryStore) UpsertAuthzPolicySet

func (m *MemoryStore) UpsertAuthzPolicySet(ctx context.Context, policySet AuthzPolicySet) error

UpsertAuthzPolicySet creates or updates one scoped policy set metadata record.

func (*MemoryStore) UpsertAuthzRelationship

func (m *MemoryStore) UpsertAuthzRelationship(ctx context.Context, relationship AuthzRelationship) error

UpsertAuthzRelationship creates or updates one scoped ReBAC tuple.

func (*MemoryStore) UpsertFindingTriageState

func (m *MemoryStore) UpsertFindingTriageState(ctx context.Context, state FindingTriageState) error

UpsertFindingTriageState creates or updates mutable triage metadata.

func (*MemoryStore) UpsertFindings

func (m *MemoryStore) UpsertFindings(ctx context.Context, scanID string, findings []domain.Finding) error

UpsertFindings persists findings idempotently by scan_id + finding_id.

func (*MemoryStore) UpsertOnboardingState

func (m *MemoryStore) UpsertOnboardingState(ctx context.Context, state OnboardingState) (OnboardingState, error)

UpsertOnboardingState persists one user-scoped onboarding progress row.

func (*MemoryStore) UpsertOrganization

func (m *MemoryStore) UpsertOrganization(ctx context.Context, organization TenancyOrganization) error

UpsertOrganization persists or updates one tenant organization record.

func (*MemoryStore) UpsertProject

func (m *MemoryStore) UpsertProject(ctx context.Context, project TenancyProject) error

UpsertProject persists one scoped project record.

func (*MemoryStore) UpsertRepoFindings

func (m *MemoryStore) UpsertRepoFindings(ctx context.Context, repoScanID string, findings []domain.Finding) error

UpsertRepoFindings persists repository findings idempotently by repo_scan_id + finding_id.

func (*MemoryStore) UpsertRepoScanCursor

func (m *MemoryStore) UpsertRepoScanCursor(ctx context.Context, cursor RepoScanCursor) error

UpsertRepoScanCursor stores the latest successful scan cursor for one repository source.

func (*MemoryStore) UpsertTenancyConnector

func (m *MemoryStore) UpsertTenancyConnector(ctx context.Context, connector TenancyConnector, state TenancyConnectorState) error

UpsertTenancyConnector persists one connector and its latest state atomically.

func (*MemoryStore) UpsertTenancyConnectorSecretEnvelope

func (m *MemoryStore) UpsertTenancyConnectorSecretEnvelope(ctx context.Context, envelope TenancyConnectorSecretEnvelope) error

UpsertTenancyConnectorSecretEnvelope persists one encrypted connector secret envelope.

func (*MemoryStore) UpsertTenancyScanPolicy

func (m *MemoryStore) UpsertTenancyScanPolicy(ctx context.Context, policy TenancyScanPolicy) error

UpsertTenancyScanPolicy persists one scan policy for a scoped project.

func (*MemoryStore) UpsertUser

func (m *MemoryStore) UpsertUser(ctx context.Context, user User) (User, error)

UpsertUser persists one account row.

func (*MemoryStore) UpsertUserIdentity

func (m *MemoryStore) UpsertUserIdentity(ctx context.Context, identity UserIdentity) (UserIdentity, error)

UpsertUserIdentity persists one provider identity mapping.

func (*MemoryStore) UpsertWorkspace

func (m *MemoryStore) UpsertWorkspace(ctx context.Context, workspace TenancyWorkspace) error

UpsertWorkspace persists or updates one scoped workspace record.

func (*MemoryStore) UpsertWorkspaceMember

func (m *MemoryStore) UpsertWorkspaceMember(ctx context.Context, member TenancyWorkspaceMember) error

UpsertWorkspaceMember persists one workspace member assignment.

type OAuthTransaction

type OAuthTransaction struct {
	Nonce             string     `json:"nonce"`
	CookieToken       string     `json:"cookie_token"`
	Intent            string     `json:"intent"`
	ReturnTo          string     `json:"return_to,omitempty"`
	ExpectedUserID    string     `json:"expected_user_id,omitempty"`
	ExpectedSessionID string     `json:"expected_session_id,omitempty"`
	ExpiresAt         time.Time  `json:"expires_at"`
	CreatedAt         time.Time  `json:"created_at"`
	ConsumedAt        *time.Time `json:"consumed_at,omitempty"`
}

OAuthTransaction is the persisted server-side record for one in-flight WorkOS OAuth login. The signed `state` token carries Nonce; the matching callback must present both the signed state (Nonce) and the browser-bound CookieToken set when the redirect was issued. The row is one-shot consumed by the callback handler so a captured state cannot be replayed — including against a different API instance that shares this database.

type OnboardingState

type OnboardingState struct {
	UserID                   string     `json:"user_id"`
	CurrentStep              string     `json:"current_step"`
	OrgID                    string     `json:"org_id,omitempty"`
	WorkspaceID              string     `json:"workspace_id,omitempty"`
	ProjectID                string     `json:"project_id,omitempty"`
	ConnectorID              string     `json:"connector_id,omitempty"`
	ConnectorType            string     `json:"connector_type,omitempty"`
	ConnectorSkipped         bool       `json:"connector_skipped"`
	ScanSkipped              bool       `json:"scan_skipped"`
	DashboardTourDismissedAt *time.Time `json:"dashboard_tour_dismissed_at,omitempty"`
	CompletedAt              *time.Time `json:"completed_at,omitempty"`
	StartedAt                time.Time  `json:"started_at"`
	UpdatedAt                time.Time  `json:"updated_at"`
}

OnboardingState stores the server-driven account setup progress for one user.

func NormalizeOnboardingStateForWrite

func NormalizeOnboardingStateForWrite(state OnboardingState) (OnboardingState, error)

NormalizeOnboardingStateForWrite validates and canonicalizes one onboarding state row.

type PostgresStore

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

PostgresStore persists scans/findings in PostgreSQL.

func NewPostgresStore

func NewPostgresStore(databaseURL string) (*PostgresStore, error)

NewPostgresStore opens a PostgreSQL connection and validates connectivity.

func NewPostgresStoreWithDB

func NewPostgresStoreWithDB(db *sql.DB) *PostgresStore

NewPostgresStoreWithDB builds a store around an existing sql.DB (tests).

func (*PostgresStore) AppendAuthzPolicyEvent

func (p *PostgresStore) AppendAuthzPolicyEvent(ctx context.Context, event AuthzPolicyEvent) error

AppendAuthzPolicyEvent records one immutable policy lifecycle event.

func (*PostgresStore) AppendFindingTriageEvent

func (p *PostgresStore) AppendFindingTriageEvent(ctx context.Context, event FindingTriageEvent) error

AppendFindingTriageEvent records one immutable triage action.

func (*PostgresStore) AppendScanEvent

func (p *PostgresStore) AppendScanEvent(ctx context.Context, scanID string, level string, message string, metadata map[string]any) error

AppendScanEvent writes one scan event row.

func (*PostgresStore) ApplyDownMigrations

func (p *PostgresStore) ApplyDownMigrations(ctx context.Context, dir string) error

ApplyDownMigrations runs all *.down.sql files in reverse lexical order.

func (*PostgresStore) ApplyFindingTriageTransition

func (p *PostgresStore) ApplyFindingTriageTransition(ctx context.Context, state FindingTriageState, event FindingTriageEvent) error

ApplyFindingTriageTransition persists state and audit history atomically.

func (*PostgresStore) ApplyMigrations

func (p *PostgresStore) ApplyMigrations(ctx context.Context, dir string) error

ApplyMigrations runs all *.up.sql files in lexical order.

func (*PostgresStore) BeginWebhookEvent

func (p *PostgresStore) BeginWebhookEvent(ctx context.Context, event WebhookEvent, now time.Time) (WebhookEventStatus, string, error)

BeginWebhookEvent atomically claims the (provider, event_id) row. It first tries to win the insert; on conflict it tries to reclaim a stale 'processing' row (claiming instance likely crashed); failing that it reads the current status. Every branch is a single atomic statement, so the claim holds across API restarts and concurrent instances.

func (*PostgresStore) CancelRepoScan

func (p *PostgresStore) CancelRepoScan(ctx context.Context, repoScanID string, finishedAt time.Time, errorMessage string) (RepoScanRecord, error)

CancelRepoScan atomically marks a queued or running repository scan as terminal failed.

func (*PostgresStore) CancelUserDeletion added in v1.0.2

func (p *PostgresStore) CancelUserDeletion(ctx context.Context, userID string, now time.Time) (User, error)

CancelUserDeletion reverses a soft delete: clears deleted_at and returns the account to active.

func (*PostgresStore) CancelWorkspaceDeletion added in v1.0.2

func (p *PostgresStore) CancelWorkspaceDeletion(ctx context.Context, workspaceID string, now time.Time) (TenancyWorkspace, error)

CancelWorkspaceDeletion reverses a soft delete during the grace window: clears deleted_at and returns the workspace to status=active.

func (*PostgresStore) ClaimKubernetesEnrollmentToken

func (p *PostgresStore) ClaimKubernetesEnrollmentToken(ctx context.Context, workspaceID string, projectID string, connectorID string, expectedEnrollmentTokenHash string, updatedMetadata map[string]any, status domain.ConnectorStatus, health string, lastErrorCode string, lastErrorMessage string, observedAt time.Time, updatedAt time.Time) (bool, error)

ClaimKubernetesEnrollmentToken atomically consumes one connector enrollment token if unused.

func (*PostgresStore) ClaimNextQueuedRepoScan

func (p *PostgresStore) ClaimNextQueuedRepoScan(ctx context.Context) (RepoScanRecord, error)

ClaimNextQueuedRepoScan atomically claims one queued repository scan.

func (*PostgresStore) ClaimNextQueuedRepoScanAnyScope

func (p *PostgresStore) ClaimNextQueuedRepoScanAnyScope(ctx context.Context) (RepoScanRecord, error)

ClaimNextQueuedRepoScanAnyScope atomically claims one queued repository scan across all scopes.

func (*PostgresStore) ClaimNextQueuedScan

func (p *PostgresStore) ClaimNextQueuedScan(ctx context.Context, provider string) (ScanRecord, error)

ClaimNextQueuedScan atomically claims one queued scan for execution.

func (*PostgresStore) ClaimNextQueuedScanAnyScope

func (p *PostgresStore) ClaimNextQueuedScanAnyScope(ctx context.Context, provider string) (ScanRecord, error)

ClaimNextQueuedScanAnyScope atomically claims one queued scan across all scopes.

func (*PostgresStore) ClaimNextQueuedUserDataExport added in v1.0.2

func (p *PostgresStore) ClaimNextQueuedUserDataExport(ctx context.Context, now time.Time) (UserDataExport, error)

ClaimNextQueuedUserDataExport atomically transitions one queued job to running and returns it.

func (*PostgresStore) ClaimQueuedUserDataExport added in v1.0.2

func (p *PostgresStore) ClaimQueuedUserDataExport(ctx context.Context, jobID string, now time.Time) (UserDataExport, error)

ClaimQueuedUserDataExport atomically transitions the named queued job to running and returns it.

func (*PostgresStore) ClaimTenancyScanPolicySchedule

func (p *PostgresStore) ClaimTenancyScanPolicySchedule(ctx context.Context, workspaceID string, projectID string, policyID string, scheduledAt time.Time, now time.Time) (bool, error)

ClaimTenancyScanPolicySchedule atomically records that a scheduled tick was claimed.

func (*PostgresStore) Close

func (p *PostgresStore) Close() error

Close closes database resources.

func (*PostgresStore) CompleteRepoScan

func (p *PostgresStore) CompleteRepoScan(ctx context.Context, repoScanID string, status string, finishedAt time.Time, commitsScanned int, filesScanned int, findingCount int, truncated bool, scanContext RepoScanContext, errorMessage string) error

CompleteRepoScan updates repository scan completion metadata.

func (*PostgresStore) CompleteScan

func (p *PostgresStore) CompleteScan(ctx context.Context, scanID string, status string, finishedAt time.Time, assetCount int, findingCount int, errorMessage string) error

CompleteScan updates scan completion metadata.

func (*PostgresStore) CompleteUserDataExport added in v1.0.2

func (p *PostgresStore) CompleteUserDataExport(ctx context.Context, jobID string, bundlePath string, sizeBytes int64, sha256Hex string, completedAt time.Time, downloadExpiresAt time.Time, purgeAfter time.Time) (UserDataExport, error)

CompleteUserDataExport marks the job ready and records bundle metadata.

func (*PostgresStore) CompleteWebhookEvent

func (p *PostgresStore) CompleteWebhookEvent(ctx context.Context, provider string, eventID string, claimToken string, now time.Time) error

CompleteWebhookEvent marks a claimed event processed so later duplicate deliveries become no-op successes. The claim_token predicate makes a superseded stale handler's completion a no-op.

func (*PostgresStore) ConsumeOAuthTransaction

func (p *PostgresStore) ConsumeOAuthTransaction(ctx context.Context, nonce string, cookieToken string, now time.Time) (OAuthTransaction, error)

ConsumeOAuthTransaction atomically consumes the row matching nonce and cookieToken. The UPDATE ... RETURNING with WHERE consumed_at IS NULL AND expires_at > now() guarantees one-shot consumption even under concurrent callbacks hitting different API instances. Any later, expired, missing, or cookie-mismatched call returns ErrNotFound.

func (*PostgresStore) ConsumeSAMLRelayState

func (p *PostgresStore) ConsumeSAMLRelayState(ctx context.Context, handle string, now time.Time) (SAMLRelayState, error)

ConsumeSAMLRelayState atomically marks a relay row consumed and returns the persisted state. The UPDATE ... RETURNING with WHERE consumed_at IS NULL AND expires_at > now() guarantees one-shot consumption even under concurrent ACS POSTs hitting different API instances. A subsequent call with the same handle returns ErrNotFound.

func (*PostgresStore) CountPendingRepoScansByRepository

func (p *PostgresStore) CountPendingRepoScansByRepository(ctx context.Context, repository string) (int, error)

CountPendingRepoScansByRepository returns queued+running scan count for one repository.

func (*PostgresStore) CountPendingScansWithSource added in v1.0.2

func (p *PostgresStore) CountPendingScansWithSource(ctx context.Context, provider string, source ScanSource) (int, error)

CountPendingScansWithSource returns queued or running scan count for one provider and scan source.

func (*PostgresStore) CountQueuedRepoScans

func (p *PostgresStore) CountQueuedRepoScans(ctx context.Context) (int, error)

CountQueuedRepoScans returns queued repository scan requests count.

func (*PostgresStore) CountQueuedRepoScansAnyScope

func (p *PostgresStore) CountQueuedRepoScansAnyScope(ctx context.Context) (int, error)

CountQueuedRepoScansAnyScope returns queued repository scan requests count across all scopes.

func (*PostgresStore) CountQueuedScans

func (p *PostgresStore) CountQueuedScans(ctx context.Context, provider string) (int, error)

CountQueuedScans returns queued scan requests count for one provider.

func (*PostgresStore) CountQueuedScansAnyScope

func (p *PostgresStore) CountQueuedScansAnyScope(ctx context.Context, provider string) (int, error)

CountQueuedScansAnyScope returns queued scan requests count across all scopes for one provider.

func (*PostgresStore) CountQueuedScansWithSource added in v1.0.2

func (p *PostgresStore) CountQueuedScansWithSource(ctx context.Context, provider string, source ScanSource) (int, error)

CountQueuedScansWithSource returns queued scan requests count for one provider and scan source.

func (*PostgresStore) CreateAuthzPolicyVersion

func (p *PostgresStore) CreateAuthzPolicyVersion(ctx context.Context, version AuthzPolicyVersion) (AuthzPolicyVersion, error)

CreateAuthzPolicyVersion persists one immutable policy bundle version.

func (*PostgresStore) CreateIdentityConnection

func (p *PostgresStore) CreateIdentityConnection(ctx context.Context, connection IdentityConnection) (IdentityConnection, error)

CreateIdentityConnection persists one enterprise identity connection scaffold.

func (*PostgresStore) CreateInvitation

func (p *PostgresStore) CreateInvitation(ctx context.Context, invitation Invitation) (Invitation, error)

CreateInvitation persists one invitation scaffold.

func (*PostgresStore) CreateOAuthTransaction

func (p *PostgresStore) CreateOAuthTransaction(ctx context.Context, txn OAuthTransaction) (OAuthTransaction, error)

CreateOAuthTransaction persists one in-flight WorkOS OAuth login keyed by the signed-state nonce.

func (*PostgresStore) CreateQueuedRepoScan

func (p *PostgresStore) CreateQueuedRepoScan(ctx context.Context, repository string, source RepoScanSource, scanContext RepoScanContext, historyLimit int, maxFindings int, queuedAt time.Time) (RepoScanRecord, error)

CreateQueuedRepoScan inserts one queued repository scan request row.

func (*PostgresStore) CreateQueuedRepoScanWithinLimit

func (p *PostgresStore) CreateQueuedRepoScanWithinLimit(ctx context.Context, repository string, source RepoScanSource, scanContext RepoScanContext, historyLimit int, maxFindings int, queuedAt time.Time, maxPending int) (RepoScanRecord, error)

CreateQueuedRepoScanWithinLimit inserts one queued repository scan only when the target is idle and queue capacity remains.

func (*PostgresStore) CreateQueuedScan

func (p *PostgresStore) CreateQueuedScan(ctx context.Context, provider string, queuedAt time.Time) (ScanRecord, error)

CreateQueuedScan inserts a queued scan request row.

func (*PostgresStore) CreateQueuedScanIfNoPending

func (p *PostgresStore) CreateQueuedScanIfNoPending(ctx context.Context, provider string, queuedAt time.Time) (ScanRecord, error)

CreateQueuedScanIfNoPending inserts one queued scan only when no queued/running scan exists.

func (*PostgresStore) CreateQueuedScanIfNoPendingWithSource added in v1.0.2

func (p *PostgresStore) CreateQueuedScanIfNoPendingWithSource(ctx context.Context, provider string, source ScanSource, queuedAt time.Time) (ScanRecord, error)

CreateQueuedScanIfNoPendingWithSource inserts one source-bound queued scan only when no queued/running scan exists.

func (*PostgresStore) CreateQueuedScanWithSource added in v1.0.2

func (p *PostgresStore) CreateQueuedScanWithSource(ctx context.Context, provider string, source ScanSource, queuedAt time.Time) (ScanRecord, error)

CreateQueuedScanWithSource inserts a queued scan request row with project/connector source metadata.

func (*PostgresStore) CreateQueuedScanWithinLimit

func (p *PostgresStore) CreateQueuedScanWithinLimit(ctx context.Context, provider string, queuedAt time.Time, maxPending int) (ScanRecord, error)

CreateQueuedScanWithinLimit inserts one queued scan request only when pending capacity remains.

func (*PostgresStore) CreateQueuedScanWithinLimitWithSource added in v1.0.2

func (p *PostgresStore) CreateQueuedScanWithinLimitWithSource(ctx context.Context, provider string, source ScanSource, queuedAt time.Time, maxPending int) (ScanRecord, error)

CreateQueuedScanWithinLimitWithSource inserts one source-bound queued scan request only when pending capacity remains.

func (*PostgresStore) CreateRepoScan

func (p *PostgresStore) CreateRepoScan(ctx context.Context, repository string, source RepoScanSource, scanContext RepoScanContext, startedAt time.Time) (RepoScanRecord, error)

CreateRepoScan inserts a new repository exposure scan row.

func (*PostgresStore) CreateSAMLRelayState

func (p *PostgresStore) CreateSAMLRelayState(ctx context.Context, state SAMLRelayState) (SAMLRelayState, error)

CreateSAMLRelayState persists one SP-initiated SAML AuthnRequest record.

func (*PostgresStore) CreateSCIMProvisioningEvent

func (p *PostgresStore) CreateSCIMProvisioningEvent(ctx context.Context, event SCIMProvisioningEventRecord) (SCIMProvisioningEventRecord, error)

CreateSCIMProvisioningEvent appends one SCIM provisioning event to the audit log scoped to the org + connection. Append-only by design.

func (*PostgresStore) CreateScan

func (p *PostgresStore) CreateScan(ctx context.Context, provider string, startedAt time.Time) (ScanRecord, error)

CreateScan inserts a new scan row.

func (*PostgresStore) CreateSession

func (p *PostgresStore) CreateSession(ctx context.Context, session Session) (Session, error)

CreateSession persists one server-side session.

func (*PostgresStore) CreateTenancyConnectorSecretEnvelopeIfAbsent added in v1.0.2

func (p *PostgresStore) CreateTenancyConnectorSecretEnvelopeIfAbsent(ctx context.Context, envelope TenancyConnectorSecretEnvelope) (TenancyConnectorSecretEnvelope, bool, error)

CreateTenancyConnectorSecretEnvelopeIfAbsent creates an encrypted connector secret envelope or returns the existing envelope when the scoped secret key already exists.

func (*PostgresStore) CreateTenancyConnectorWithSecretEnvelopeIfAbsent added in v1.0.2

func (p *PostgresStore) CreateTenancyConnectorWithSecretEnvelopeIfAbsent(ctx context.Context, connector TenancyConnector, state TenancyConnectorState, envelope TenancyConnectorSecretEnvelope) (TenancyConnectorWithState, bool, error)

CreateTenancyConnectorWithSecretEnvelopeIfAbsent creates a connector, state, and secret envelope in one transaction, or returns the existing connector unchanged when the scoped connector key already exists.

func (*PostgresStore) CreateUserDataExport added in v1.0.2

func (p *PostgresStore) CreateUserDataExport(ctx context.Context, export UserDataExport) (UserDataExport, error)

CreateUserDataExport inserts a queued export job for the user.

func (*PostgresStore) CreateVerifiedDomain

func (p *PostgresStore) CreateVerifiedDomain(ctx context.Context, domain VerifiedDomain) (VerifiedDomain, error)

CreateVerifiedDomain persists one domain-verification scaffold.

func (*PostgresStore) DB

func (p *PostgresStore) DB() *sql.DB

DB exposes the underlying sql.DB for runtime wiring (locks, health checks).

func (*PostgresStore) DeadLetterScan

func (p *PostgresStore) DeadLetterScan(ctx context.Context, scanID string, finishedAt time.Time, retryCount int, maxRetryCount int, assetCount int, findingCount int, failureCategory string, errorMessage string) error

DeadLetterScan marks a failed queued scan as operator-replayable.

func (*PostgresStore) DeleteAuthzRelationship

func (p *PostgresStore) DeleteAuthzRelationship(ctx context.Context, relationship AuthzRelationship) error

DeleteAuthzRelationship removes one scoped ReBAC tuple.

func (*PostgresStore) DeleteIdentityConnection

func (p *PostgresStore) DeleteIdentityConnection(ctx context.Context, orgID, connectionID string) error

DeleteIdentityConnection removes one identity connection row keyed on (org_id, id). Returns ErrNotFound when no matching row exists.

func (*PostgresStore) DeleteOrganization

func (p *PostgresStore) DeleteOrganization(ctx context.Context) error

DeleteOrganization removes one scoped organization record.

func (*PostgresStore) DeleteProject

func (p *PostgresStore) DeleteProject(ctx context.Context, workspaceID string, projectID string) error

DeleteProject removes one scoped project.

func (*PostgresStore) DeleteRepoFinding added in v1.0.2

func (p *PostgresStore) DeleteRepoFinding(ctx context.Context, repoScanID string, findingID string) error

DeleteRepoFinding removes one repository finding for one scan.

func (*PostgresStore) DeleteRepoFindingTargets added in v1.0.2

func (p *PostgresStore) DeleteRepoFindingTargets(ctx context.Context, targets []RepoFindingDeleteTarget) ([]RepoFindingDeleteTarget, error)

DeleteRepoFindingTargets removes selected repository findings in one scoped operation.

func (*PostgresStore) DeleteRepoFindings

func (p *PostgresStore) DeleteRepoFindings(ctx context.Context, repoScanID string) error

DeleteRepoFindings removes repository findings for one scan.

func (*PostgresStore) DeleteRepoScan added in v1.0.2

func (p *PostgresStore) DeleteRepoScan(ctx context.Context, repoScanID string) error

DeleteRepoScan removes one repository scan and cascades its findings.

func (*PostgresStore) DeleteTenancyConnectorSecretEnvelope

func (p *PostgresStore) DeleteTenancyConnectorSecretEnvelope(ctx context.Context, workspaceID string, projectID string, connectorID string, secretName string) error

DeleteTenancyConnectorSecretEnvelope removes one encrypted connector secret envelope by name.

func (*PostgresStore) DeleteTenancyScanPolicy

func (p *PostgresStore) DeleteTenancyScanPolicy(ctx context.Context, workspaceID string, projectID string, policyID string) error

DeleteTenancyScanPolicy removes one scoped scan policy by id.

func (*PostgresStore) DeleteUserIdentity

func (p *PostgresStore) DeleteUserIdentity(ctx context.Context, provider string, subject string) error

DeleteUserIdentity removes one provider identity by provider and subject.

func (*PostgresStore) DeleteWebhookEvent

func (p *PostgresStore) DeleteWebhookEvent(ctx context.Context, provider string, eventID string, claimToken string) error

DeleteWebhookEvent rolls back a claim so a provider retry can reprocess an event whose side effects failed transiently. The claim_token predicate makes a superseded stale handler's rollback a no-op so it cannot erase the successor's active claim.

func (*PostgresStore) DeleteWorkspace

func (p *PostgresStore) DeleteWorkspace(ctx context.Context, workspaceID string) error

DeleteWorkspace deletes one scoped workspace by id.

func (*PostgresStore) DeleteWorkspaceMember

func (p *PostgresStore) DeleteWorkspaceMember(ctx context.Context, workspaceID string, memberID string) error

DeleteWorkspaceMember removes one scoped member.

func (*PostgresStore) ExpandRepoFindingDeleteTargets added in v1.0.2

func (p *PostgresStore) ExpandRepoFindingDeleteTargets(ctx context.Context, targets []RepoFindingDeleteTarget) ([]RepoFindingDeleteTarget, error)

ExpandRepoFindingDeleteTargets returns every concrete repository finding row a delete request may remove.

func (*PostgresStore) FailStaleRepoScansAnyScope

func (p *PostgresStore) FailStaleRepoScansAnyScope(ctx context.Context, staleBefore time.Time, limit int, errorMessage string) (int, error)

FailStaleRepoScansAnyScope marks stale running repository scans failed across all scopes.

func (*PostgresStore) FailStaleRunningUserDataExports added in v1.0.2

func (p *PostgresStore) FailStaleRunningUserDataExports(ctx context.Context, startedBefore time.Time, failedAt time.Time, limit int, errMsg string) ([]UserDataExport, error)

FailStaleRunningUserDataExports marks interrupted running jobs failed so they can stop polling as running forever after worker restarts.

func (*PostgresStore) FailUserDataExport added in v1.0.2

func (p *PostgresStore) FailUserDataExport(ctx context.Context, jobID string, errMsg string, failedAt time.Time) (UserDataExport, error)

FailUserDataExport marks a job failed.

func (*PostgresStore) FindFirstWorkspaceMemberByUserUUID

func (p *PostgresStore) FindFirstWorkspaceMemberByUserUUID(ctx context.Context, userUUID string) (TenancyWorkspaceMember, error)

FindFirstWorkspaceMemberByUserUUID returns the newest active workspace membership for one auth user.

func (*PostgresStore) FindFirstWorkspaceMemberByUserUUIDAndTenantID

func (p *PostgresStore) FindFirstWorkspaceMemberByUserUUIDAndTenantID(ctx context.Context, userUUID string, tenantID string) (TenancyWorkspaceMember, error)

FindFirstWorkspaceMemberByUserUUIDAndTenantID returns the newest active workspace membership for one auth user in one tenant.

func (*PostgresStore) GetAWSPlatformBaselineResult added in v1.0.2

func (p *PostgresStore) GetAWSPlatformBaselineResult(ctx context.Context, filter AWSPlatformBaselineFilter) (AWSPlatformBaselineResult, error)

GetAWSPlatformBaselineResult returns one persisted project-scoped AWS platform readiness result.

func (*PostgresStore) GetAuthzEntityAttributes

func (p *PostgresStore) GetAuthzEntityAttributes(ctx context.Context, entityKind string, entityType string, entityID string) (AuthzEntityAttributes, error)

GetAuthzEntityAttributes returns trusted authorization attributes for one entity.

func (*PostgresStore) GetAuthzPolicyRollout

func (p *PostgresStore) GetAuthzPolicyRollout(ctx context.Context, policySetID string) (AuthzPolicyRollout, error)

GetAuthzPolicyRollout returns one scoped rollout pointer row.

func (*PostgresStore) GetAuthzPolicySet

func (p *PostgresStore) GetAuthzPolicySet(ctx context.Context, policySetID string) (AuthzPolicySet, error)

GetAuthzPolicySet returns one scoped policy set metadata record.

func (*PostgresStore) GetAuthzPolicyVersion

func (p *PostgresStore) GetAuthzPolicyVersion(ctx context.Context, policySetID string, version int) (AuthzPolicyVersion, error)

GetAuthzPolicyVersion returns one immutable bundle version in scope.

func (*PostgresStore) GetFinding

func (p *PostgresStore) GetFinding(ctx context.Context, findingID string, scanID string) (domain.Finding, error)

GetFinding returns one finding by id, optionally scoped to one scan id.

func (*PostgresStore) GetFindingTriageState

func (p *PostgresStore) GetFindingTriageState(ctx context.Context, findingID string) (FindingTriageState, error)

GetFindingTriageState returns triage workflow state for one finding id.

func (*PostgresStore) GetIdentityConnection

func (p *PostgresStore) GetIdentityConnection(ctx context.Context, orgID string, connectionID string) (IdentityConnection, error)

GetIdentityConnection returns one organization identity connection scaffold.

func (*PostgresStore) GetIdentityConnectionByID

func (p *PostgresStore) GetIdentityConnectionByID(ctx context.Context, connectionID string) (IdentityConnection, error)

GetIdentityConnectionByID resolves a connection by its globally unique UUID, bypassing the org-scope filter applied by GetIdentityConnection. Used by entry points (SAML SP-initiated login) that do not know the org id in advance — the connection itself determines the org scope.

Uses queryRowContextAnyScope so the lookup runs without requiring a db.WithScope context, matching FindFirstWorkspaceMemberByUserUUIDAndTenantID. Under IDENTRAIL_POSTGRES_RLS_ENFORCED=true, the scoped path would short- circuit with ErrScopeRequired before reading any row because /auth/saml routes are unauthenticated entry points.

func (*PostgresStore) GetIdentityConnectionBySCIMBearerTokenHash

func (p *PostgresStore) GetIdentityConnectionBySCIMBearerTokenHash(ctx context.Context, tokenHash string) (IdentityConnection, error)

GetIdentityConnectionBySCIMBearerTokenHash resolves a connection by its stored SCIM bearer-token hash without requiring an org-scoped context.

func (*PostgresStore) GetInvitation

func (p *PostgresStore) GetInvitation(ctx context.Context, orgID string, invitationID string) (Invitation, error)

GetInvitation returns one organization invitation scaffold.

func (*PostgresStore) GetOnboardingState

func (p *PostgresStore) GetOnboardingState(ctx context.Context, userID string) (OnboardingState, error)

GetOnboardingState returns one user's onboarding progress row.

func (*PostgresStore) GetOrganization

func (p *PostgresStore) GetOrganization(ctx context.Context) (TenancyOrganization, error)

GetOrganization returns one scoped organization record.

func (*PostgresStore) GetProject

func (p *PostgresStore) GetProject(ctx context.Context, workspaceID string, projectID string) (TenancyProject, error)

GetProject returns one scoped project.

func (*PostgresStore) GetRepoScan

func (p *PostgresStore) GetRepoScan(ctx context.Context, repoScanID string) (RepoScanRecord, error)

GetRepoScan returns one repository scan by id.

func (*PostgresStore) GetRepoScanCursor

func (p *PostgresStore) GetRepoScanCursor(ctx context.Context, repository string, source RepoScanSource) (RepoScanCursor, error)

GetRepoScanCursor returns the latest successful scan cursor for one repository source.

func (*PostgresStore) GetScan

func (p *PostgresStore) GetScan(ctx context.Context, scanID string) (ScanRecord, error)

GetScan returns one scan by id.

func (*PostgresStore) GetTenancyConnector

func (p *PostgresStore) GetTenancyConnector(ctx context.Context, workspaceID string, projectID string, connectorID string) (TenancyConnectorWithState, error)

GetTenancyConnector returns one connector and its latest state.

func (*PostgresStore) GetTenancyConnectorSecretEnvelope

func (p *PostgresStore) GetTenancyConnectorSecretEnvelope(ctx context.Context, workspaceID string, projectID string, connectorID string, secretName string) (TenancyConnectorSecretEnvelope, error)

GetTenancyConnectorSecretEnvelope loads one encrypted connector secret envelope by name.

func (*PostgresStore) GetTenancyScanPolicy

func (p *PostgresStore) GetTenancyScanPolicy(ctx context.Context, workspaceID string, projectID string, policyID string) (TenancyScanPolicy, error)

GetTenancyScanPolicy returns one scoped scan policy by id.

func (*PostgresStore) GetUser

func (p *PostgresStore) GetUser(ctx context.Context, userID string) (User, error)

GetUser returns one account by UUID.

func (*PostgresStore) GetUserByPrimaryEmail

func (p *PostgresStore) GetUserByPrimaryEmail(ctx context.Context, email string) (User, error)

GetUserByPrimaryEmail returns one account by normalized primary email.

func (*PostgresStore) GetUserDataExport added in v1.0.2

func (p *PostgresStore) GetUserDataExport(ctx context.Context, userID string, jobID string) (UserDataExport, error)

GetUserDataExport returns one export, scoped to its owner.

func (*PostgresStore) GetUserDataExportByID added in v1.0.2

func (p *PostgresStore) GetUserDataExportByID(ctx context.Context, jobID string) (UserDataExport, error)

GetUserDataExportByID looks up a job by id without caller scoping.

func (*PostgresStore) GetUserIdentity

func (p *PostgresStore) GetUserIdentity(ctx context.Context, provider string, subject string) (UserIdentity, error)

GetUserIdentity returns one provider identity by provider and subject.

func (*PostgresStore) GetUserIdentityByProviderUserID

func (p *PostgresStore) GetUserIdentityByProviderUserID(ctx context.Context, provider string, userID string) (UserIdentity, error)

GetUserIdentityByProviderUserID returns one provider identity for a user.

func (*PostgresStore) GetVerifiedDomain

func (p *PostgresStore) GetVerifiedDomain(ctx context.Context, orgID string, domainID string) (VerifiedDomain, error)

GetVerifiedDomain returns one organization domain-verification scaffold.

func (*PostgresStore) GetWorkspace

func (p *PostgresStore) GetWorkspace(ctx context.Context, workspaceID string) (TenancyWorkspace, error)

GetWorkspace returns one scoped workspace by id.

func (*PostgresStore) GetWorkspaceMember

func (p *PostgresStore) GetWorkspaceMember(ctx context.Context, workspaceID string, memberID string) (TenancyWorkspaceMember, error)

GetWorkspaceMember returns one scoped workspace member.

func (*PostgresStore) GetWorkspaceMemberByUserUUID

func (p *PostgresStore) GetWorkspaceMemberByUserUUID(ctx context.Context, workspaceID string, userUUID string) (TenancyWorkspaceMember, error)

GetWorkspaceMemberByUserUUID returns one scoped workspace member by auth user UUID.

func (*PostgresStore) HardDeleteUser added in v1.0.2

func (p *PostgresStore) HardDeleteUser(ctx context.Context, userID string, now time.Time) (User, error)

HardDeleteUser purges PII from a soft-deleted account while keeping the row so audit references by UUID stay valid. Provider identities (raw IdP claims) and session rows are removed first, then the users row is tombstoned, so an interrupted run leaves the account marked pending and gets safely reprocessed.

func (*PostgresStore) HardDeleteWorkspace added in v1.0.2

func (p *PostgresStore) HardDeleteWorkspace(ctx context.Context, tenantID, workspaceID string, expectedDeletedAt time.Time, now time.Time) (TenancyWorkspace, error)

HardDeleteWorkspace purges every row tied to a soft-deleted workspace past its grace window. The destructive predicate lives on the SQL itself — `status='deleted' AND deleted_at = $expected` — so:

  • workspace_id alone is not globally unique (defaults like "default" repeat across tenants); requiring tenant_id locks the purge to the row the worker actually listed.
  • matching against the worker's observed deleted_at refuses any workspace that was cancelled and re-deleted between the worker's list and its purge call, so a fresh-grace re-deletion is not prematurely hard-deleted.

The transaction also explicitly purges every workspace-scoped table that does NOT have an FK back to tenancy_workspaces, so the cascade from the workspace DELETE alone would leave them orphaned: scans, repo_scans, aws_account_region_coverages, the authz suite (entity_attributes, relationships, policy_sets, policy_versions, policy_rollouts, policy_events), and finding-triage state/events. Tables that DO have an FK (members, projects, connectors, secret envelopes, scan policies) are deleted by the cascade from the workspace row itself.

func (*PostgresStore) ListAWSAccountRegionCoverages added in v1.0.2

func (p *PostgresStore) ListAWSAccountRegionCoverages(ctx context.Context, filter AWSAccountRegionCoverageFilter) ([]AWSAccountRegionCoverage, error)

ListAWSAccountRegionCoverages returns deterministic scoped AWS account/region coverage rows.

func (*PostgresStore) ListAllTenancyConnectorsByType

func (p *PostgresStore) ListAllTenancyConnectorsByType(ctx context.Context, connectorType domain.ConnectorType, limit int) ([]TenancyConnectorWithState, error)

ListAllTenancyConnectorsByType returns connectors across all scopes for internal runtime matching.

func (*PostgresStore) ListAuthzPolicyEvents

func (p *PostgresStore) ListAuthzPolicyEvents(ctx context.Context, policySetID string, limit int) ([]AuthzPolicyEvent, error)

ListAuthzPolicyEvents returns lifecycle events for one policy set (newest first).

func (*PostgresStore) ListAuthzPolicyVersions

func (p *PostgresStore) ListAuthzPolicyVersions(ctx context.Context, policySetID string, limit int) ([]AuthzPolicyVersion, error)

ListAuthzPolicyVersions returns policy versions for one policy set ordered by newest first.

func (*PostgresStore) ListAuthzRelationships

func (p *PostgresStore) ListAuthzRelationships(ctx context.Context, filter AuthzRelationshipFilter, limit int) ([]AuthzRelationship, error)

ListAuthzRelationships returns scoped ReBAC tuples using optional filters.

func (*PostgresStore) ListFindingMetasByScan

func (p *PostgresStore) ListFindingMetasByScan(ctx context.Context, scanID string) ([]FindingMeta, error)

ListFindingMetasByScan returns lightweight finding metadata for one scan.

func (*PostgresStore) ListFindingTrendCounts

func (p *PostgresStore) ListFindingTrendCounts(ctx context.Context, scanIDs []string, severity string, findingType string) ([]FindingTrendCount, error)

ListFindingTrendCounts aggregates finding totals per scan and severity.

func (*PostgresStore) ListFindingTriageEvents

func (p *PostgresStore) ListFindingTriageEvents(ctx context.Context, findingID string, limit int) ([]FindingTriageEvent, error)

ListFindingTriageEvents returns triage history newest-first for one finding id.

func (*PostgresStore) ListFindingTriageStates

func (p *PostgresStore) ListFindingTriageStates(ctx context.Context, findingIDs []string) ([]FindingTriageState, error)

ListFindingTriageStates returns triage states for provided finding ids.

func (*PostgresStore) ListFindings

func (p *PostgresStore) ListFindings(ctx context.Context, limit int) ([]domain.Finding, error)

ListFindings returns latest findings first across scans.

func (*PostgresStore) ListFindingsAll

func (p *PostgresStore) ListFindingsAll(ctx context.Context) ([]domain.Finding, error)

ListFindingsAll returns all findings for current scope ordered by recency.

func (*PostgresStore) ListFindingsByScan

func (p *PostgresStore) ListFindingsByScan(ctx context.Context, scanID string, limit int) ([]domain.Finding, error)

ListFindingsByScan returns latest findings first for one scan id.

func (*PostgresStore) ListFindingsByScanAndIDs

func (p *PostgresStore) ListFindingsByScanAndIDs(ctx context.Context, scanID string, findingIDs []string) ([]domain.Finding, error)

ListFindingsByScanAndIDs returns detailed findings for one scan and ID set.

func (*PostgresStore) ListFindingsFiltered

func (p *PostgresStore) ListFindingsFiltered(ctx context.Context, filter FindingListFilter) ([]domain.Finding, error)

ListFindingsFiltered returns one filtered findings page with stable persistence-level ordering.

func (*PostgresStore) ListIdentities

func (p *PostgresStore) ListIdentities(ctx context.Context, filter IdentityFilter, limit int) ([]domain.Identity, error)

ListIdentities returns identities filtered by scan/provider/type/name prefix.

func (*PostgresStore) ListIdentityConnections

func (p *PostgresStore) ListIdentityConnections(ctx context.Context, orgID string, limit int) ([]IdentityConnection, error)

ListIdentityConnections returns organization identity connection scaffolds ordered by newest first.

func (*PostgresStore) ListInvitations

func (p *PostgresStore) ListInvitations(ctx context.Context, orgID string, limit int) ([]Invitation, error)

ListInvitations returns organization invitations ordered by newest first.

func (*PostgresStore) ListProjects

func (p *PostgresStore) ListProjects(ctx context.Context, workspaceID string, includeArchived bool, limit int) ([]TenancyProject, error)

ListProjects returns scoped projects for a workspace.

func (*PostgresStore) ListRelationships

func (p *PostgresStore) ListRelationships(ctx context.Context, filter RelationshipFilter, limit int) ([]domain.Relationship, error)

ListRelationships returns relationships filtered by scan/type/from/to.

func (*PostgresStore) ListRepoFindingClusters

func (p *PostgresStore) ListRepoFindingClusters(ctx context.Context, filter RepoFindingClusterListFilter) ([]domain.RepoFindingCluster, error)

ListRepoFindingClusters returns repository finding clusters with bounded store-side pagination.

func (*PostgresStore) ListRepoFindingTrendCounts

func (p *PostgresStore) ListRepoFindingTrendCounts(ctx context.Context, repoScanIDs []string, severity string, findingType string, minConfidence float64) ([]FindingTrendCount, error)

ListRepoFindingTrendCounts aggregates repository finding totals by repo scan and severity.

func (*PostgresStore) ListRepoFindings

func (p *PostgresStore) ListRepoFindings(ctx context.Context, filter RepoFindingFilter, limit int) ([]domain.Finding, error)

ListRepoFindings returns latest repository findings first with optional filters.

func (*PostgresStore) ListRepoScans

func (p *PostgresStore) ListRepoScans(ctx context.Context, limit int) ([]RepoScanRecord, error)

ListRepoScans returns latest repository scans first.

func (*PostgresStore) ListSCIMProvisioningEvents

func (p *PostgresStore) ListSCIMProvisioningEvents(ctx context.Context, orgID string, connectionID string, limit int) ([]SCIMProvisioningEventRecord, error)

ListSCIMProvisioningEvents returns events for one connection ordered newest first, capped at limit (default 100).

func (*PostgresStore) ListScanEvents

func (p *PostgresStore) ListScanEvents(ctx context.Context, scanID string, limit int) ([]ScanEvent, error)

ListScanEvents returns latest event entries for one scan.

func (*PostgresStore) ListScans

func (p *PostgresStore) ListScans(ctx context.Context, limit int) ([]ScanRecord, error)

ListScans returns latest scans first.

func (*PostgresStore) ListScheduledTenancyScanPolicies

func (p *PostgresStore) ListScheduledTenancyScanPolicies(ctx context.Context, limit int, offset int) ([]TenancyScanPolicy, error)

ListScheduledTenancyScanPolicies returns enabled scheduled policies for worker execution.

func (*PostgresStore) ListSoleOwnerWorkspaces added in v1.0.2

func (p *PostgresStore) ListSoleOwnerWorkspaces(ctx context.Context, userUUID string) ([]TenancyWorkspace, error)

ListSoleOwnerWorkspaces returns every workspace, across all tenants, in which the user is the only active owner. Account deletion uses this to refuse with a structured 409 until ownership is transferred, so a workspace never ends up without a live owner once its current sole owner leaves.

func (*PostgresStore) ListTenancyConnectors

func (p *PostgresStore) ListTenancyConnectors(ctx context.Context, workspaceID string, projectID string, connectorType domain.ConnectorType, limit int) ([]TenancyConnectorWithState, error)

ListTenancyConnectors returns scoped connectors ordered by most recent update.

func (*PostgresStore) ListTenancyConnectorsUnscoped

func (p *PostgresStore) ListTenancyConnectorsUnscoped(ctx context.Context, connectorType domain.ConnectorType, limit int) ([]TenancyConnectorWithState, error)

ListTenancyConnectorsUnscoped returns connectors across all scopes for internal webhook dispatch.

func (*PostgresStore) ListTenancyScanPolicies

func (p *PostgresStore) ListTenancyScanPolicies(ctx context.Context, workspaceID string, projectID string, triggerMode domain.ScanTriggerMode, enabled *bool, sortBy string, sortDesc bool, limit int) ([]TenancyScanPolicy, error)

ListTenancyScanPolicies returns scoped scan policies ordered before limiting.

func (*PostgresStore) ListUserDataExports added in v1.0.2

func (p *PostgresStore) ListUserDataExports(ctx context.Context, userID string, limit int) ([]UserDataExport, error)

ListUserDataExports returns the user's exports newest-first.

func (*PostgresStore) ListUserDataExportsPendingPurge added in v1.0.2

func (p *PostgresStore) ListUserDataExportsPendingPurge(ctx context.Context, now time.Time, limit int) ([]UserDataExport, error)

ListUserDataExportsPendingPurge returns ready jobs past their retention window whose bundle has not yet been purged.

func (*PostgresStore) ListUserIdentitiesByProvider

func (p *PostgresStore) ListUserIdentitiesByProvider(ctx context.Context, provider string, limit int) ([]UserIdentity, error)

ListUserIdentitiesByProvider returns provider identities ordered by newest first. A non-positive limit returns all matching identities.

func (*PostgresStore) ListUserSessionHistory added in v1.0.2

func (p *PostgresStore) ListUserSessionHistory(ctx context.Context, userID string, limit int) ([]Session, error)

ListUserSessionHistory returns every session row for one user, including revoked and expired sessions. A non-positive limit means no limit.

func (*PostgresStore) ListUserSessions

func (p *PostgresStore) ListUserSessions(ctx context.Context, userID string, now time.Time, limit int) ([]Session, error)

ListUserSessions returns active sessions for one user.

func (*PostgresStore) ListUsersPendingHardDelete added in v1.0.2

func (p *PostgresStore) ListUsersPendingHardDelete(ctx context.Context, deletedBefore time.Time, limit int) ([]User, error)

ListUsersPendingHardDelete returns soft-deleted accounts whose grace window closed (deleted_at < deletedBefore) and whose PII has not already been purged.

func (*PostgresStore) ListVerifiedDomains

func (p *PostgresStore) ListVerifiedDomains(ctx context.Context, orgID string, limit int) ([]VerifiedDomain, error)

ListVerifiedDomains returns organization domain-verification scaffolds ordered by newest first.

func (*PostgresStore) ListWorkspaceMembers

func (p *PostgresStore) ListWorkspaceMembers(ctx context.Context, workspaceID string, limit int) ([]TenancyWorkspaceMember, error)

ListWorkspaceMembers lists members for one scoped workspace.

func (*PostgresStore) ListWorkspaceMembershipsByUserUUID added in v1.0.2

func (p *PostgresStore) ListWorkspaceMembershipsByUserUUID(ctx context.Context, userUUID string) ([]TenancyWorkspaceMember, error)

ListWorkspaceMembershipsByUserUUID returns every active workspace membership the user holds across all tenants. AnyScope is used because the export is a global account export rather than a single scoped workspace read.

func (*PostgresStore) ListWorkspaceMembershipsByUserUUIDAndTenantID

func (p *PostgresStore) ListWorkspaceMembershipsByUserUUIDAndTenantID(ctx context.Context, userUUID string, tenantID string) ([]TenancyWorkspaceMember, error)

ListWorkspaceMembershipsByUserUUIDAndTenantID returns every active workspace membership the user holds within one tenant. It is the authorization basis for organization-wide reads: a caller may only aggregate data from the workspaces they actually belong to. AnyScope is used because the lookup spans every workspace in the tenant rather than one scoped workspace.

func (*PostgresStore) ListWorkspaceStrandedActiveMembers added in v1.0.2

func (p *PostgresStore) ListWorkspaceStrandedActiveMembers(ctx context.Context, workspaceID string, userUUID string) ([]TenancyWorkspaceMember, error)

ListWorkspaceStrandedActiveMembers returns the other active members in the workspace iff the caller is the sole active owner. Soft-deleted owners are not counted as live so a caller never strands a workspace by treating a deleted co-owner as a transfer target.

func (*PostgresStore) ListWorkspaces

func (p *PostgresStore) ListWorkspaces(ctx context.Context, limit int) ([]TenancyWorkspace, error)

ListWorkspaces returns all tenant-scoped workspaces ordered by creation time.

func (*PostgresStore) ListWorkspacesPendingHardDelete added in v1.0.2

func (p *PostgresStore) ListWorkspacesPendingHardDelete(ctx context.Context, deletedBefore time.Time, limit int) ([]TenancyWorkspace, error)

ListWorkspacesPendingHardDelete returns soft-deleted workspaces whose grace window closed (deleted_at < deletedBefore). Bypasses scope so the purge worker can enumerate across tenants in a single pass.

func (*PostgresStore) MarkUserDataExportPurged added in v1.0.2

func (p *PostgresStore) MarkUserDataExportPurged(ctx context.Context, jobID string, now time.Time) (UserDataExport, error)

MarkUserDataExportPurged stamps the job as expired and clears the bundle pointer so a later download attempt cannot reach a deleted file.

func (*PostgresStore) ReactivateWorkspace added in v1.0.2

func (p *PostgresStore) ReactivateWorkspace(ctx context.Context, workspaceID string, now time.Time) (TenancyWorkspace, error)

ReactivateWorkspace flips a suspended workspace back to active and clears suspended_at. Callers that want active-workspace idempotency should check before issuing the store transition.

func (*PostgresStore) RequeueRepoScan

func (p *PostgresStore) RequeueRepoScan(ctx context.Context, repoScanID string) error

RequeueRepoScan moves one running repository scan back to queued.

func (*PostgresStore) RevokeAllUserSessions

func (p *PostgresStore) RevokeAllUserSessions(ctx context.Context, userID string, revokedAt time.Time) (int, error)

RevokeAllUserSessions revokes every active session for one user.

func (*PostgresStore) RevokeInvitation

func (p *PostgresStore) RevokeInvitation(ctx context.Context, orgID string, invitationID string, revokedAt time.Time) (Invitation, error)

RevokeInvitation marks one pending invitation revoked.

func (*PostgresStore) RevokeOtherUserSessions

func (p *PostgresStore) RevokeOtherUserSessions(ctx context.Context, userID string, currentSessionIDHash []byte, revokedAt time.Time) (int, error)

RevokeOtherUserSessions revokes every active session except the caller's.

func (*PostgresStore) RevokeUserSession

func (p *PostgresStore) RevokeUserSession(ctx context.Context, userID string, sessionIDHash []byte, revokedAt time.Time) (Session, error)

RevokeUserSession revokes one active session if it belongs to the user.

func (*PostgresStore) ScheduleScanRetry

func (p *PostgresStore) ScheduleScanRetry(ctx context.Context, scanID string, queuedAt time.Time, retryCount int, maxRetryCount int, failureCategory string, errorMessage string, nextRetryAt time.Time) error

ScheduleScanRetry moves a failed scan attempt back into the queue with delay metadata.

func (*PostgresStore) ScopeRLSEnforcementEnabled

func (p *PostgresStore) ScopeRLSEnforcementEnabled() bool

ScopeRLSEnforcementEnabled returns true when scoped RLS enforcement is enabled.

func (*PostgresStore) SetScopeRLSEnforcement

func (p *PostgresStore) SetScopeRLSEnforcement(enabled bool)

SetScopeRLSEnforcement toggles statement-level RLS enforcement with scoped GUCs.

func (*PostgresStore) SetUserStatus added in v1.0.2

func (p *PostgresStore) SetUserStatus(ctx context.Context, userID string, status string, now time.Time) (User, error)

SetUserStatus transitions one account between lifecycle states. Setting the status the row already has is allowed so the API layer can treat repeated requests as idempotent successes.

func (*PostgresStore) SoftDeleteUser added in v1.0.2

func (p *PostgresStore) SoftDeleteUser(ctx context.Context, userID string, now time.Time) (User, error)

SoftDeleteUser flips the account to status=deleted and stamps deleted_at to open the reversible grace window. COALESCE keeps any existing deleted_at so a repeat delete cannot push the purge deadline back.

func (*PostgresStore) SoftDeleteWorkspace added in v1.0.2

func (p *PostgresStore) SoftDeleteWorkspace(ctx context.Context, workspaceID string, now time.Time) (TenancyWorkspace, error)

SoftDeleteWorkspace flips the workspace to status=deleted and stamps deleted_at to open the reversible grace window. COALESCE keeps any existing deleted_at so a repeat delete cannot push the purge deadline back.

func (*PostgresStore) SummarizeFindings

func (p *PostgresStore) SummarizeFindings(ctx context.Context) (FindingSummaryCounts, error)

SummarizeFindings returns aggregate counters for current scope.

func (*PostgresStore) SuspendWorkspace added in v1.0.2

func (p *PostgresStore) SuspendWorkspace(ctx context.Context, workspaceID string, now time.Time) (TenancyWorkspace, error)

SuspendWorkspace flips the workspace to status=suspended and stamps suspended_at. The COALESCE preserves any existing suspended_at so a repeat suspend cannot drift the recorded timestamp under a concurrent caller.

func (*PostgresStore) TouchSession

func (p *PostgresStore) TouchSession(ctx context.Context, sessionIDHash []byte, now time.Time) (Session, error)

TouchSession renews idle expiry and returns the joined session/user row.

func (*PostgresStore) TouchSessionAllowingPendingDeletion added in v1.0.2

func (p *PostgresStore) TouchSessionAllowingPendingDeletion(ctx context.Context, sessionIDHash []byte, now time.Time) (Session, error)

TouchSessionAllowingPendingDeletion is TouchSession with the user-lifecycle gate widened so cookies pointing to a soft-deleted user resolve. The 30-day grace gate is enforced at the handler layer (the cancel-deletion route returns 410 past the window) rather than here, so the past-grace branch remains reachable to produce a well-formed `grace_period_expired` response. Mounted only on `/v1/me/cancel-deletion`; every other route uses TouchSession.

func (*PostgresStore) UpdateCurrentUserProfile added in v1.0.2

func (p *PostgresStore) UpdateCurrentUserProfile(ctx context.Context, userID string, displayName *string, avatarURL *string, updatedAt time.Time) (User, error)

UpdateCurrentUserProfile updates only self-service mutable profile fields. It leaves email and lifecycle fields untouched and requires the account to still be active, so a concurrent account delete cannot lose deleted_at.

func (*PostgresStore) UpdateIdentityConnection

func (p *PostgresStore) UpdateIdentityConnection(ctx context.Context, connection IdentityConnection) (IdentityConnection, error)

UpdateIdentityConnection replaces a persisted identity connection row keyed on (org_id, id). Returns ErrNotFound when no matching row exists.

func (*PostgresStore) UpdateSessionContext

func (p *PostgresStore) UpdateSessionContext(ctx context.Context, userID string, sessionIDHash []byte, orgID string, workspaceID string, projectID string, now time.Time) (Session, error)

UpdateSessionContext persists the active tenancy context for one browser session.

func (*PostgresStore) UpdateUserProfile added in v1.0.2

func (p *PostgresStore) UpdateUserProfile(ctx context.Context, user User) (User, error)

UpdateUserProfile refreshes one account row without changing lifecycle status.

func (*PostgresStore) UpsertAWSAccountRegionCoverage added in v1.0.2

func (p *PostgresStore) UpsertAWSAccountRegionCoverage(ctx context.Context, coverage AWSAccountRegionCoverage) (AWSAccountRegionCoverage, error)

UpsertAWSAccountRegionCoverage persists one account/region coverage row for a scoped AWS connector.

func (*PostgresStore) UpsertAWSPlatformBaselineResult added in v1.0.2

func (p *PostgresStore) UpsertAWSPlatformBaselineResult(ctx context.Context, result AWSPlatformBaselineResult) (AWSPlatformBaselineResult, error)

UpsertAWSPlatformBaselineResult persists one project-scoped AWS platform readiness result.

func (*PostgresStore) UpsertArtifacts

func (p *PostgresStore) UpsertArtifacts(ctx context.Context, scanID string, artifacts ScanArtifacts) error

UpsertArtifacts inserts raw and normalized artifacts idempotently for one scan.

func (*PostgresStore) UpsertAuthzEntityAttributes

func (p *PostgresStore) UpsertAuthzEntityAttributes(ctx context.Context, attributes AuthzEntityAttributes) error

UpsertAuthzEntityAttributes creates or updates trusted authorization attributes.

func (*PostgresStore) UpsertAuthzPolicyRollout

func (p *PostgresStore) UpsertAuthzPolicyRollout(ctx context.Context, rollout AuthzPolicyRollout) error

UpsertAuthzPolicyRollout creates or updates one scoped rollout pointer row.

func (*PostgresStore) UpsertAuthzPolicySet

func (p *PostgresStore) UpsertAuthzPolicySet(ctx context.Context, policySet AuthzPolicySet) error

UpsertAuthzPolicySet creates or updates one scoped policy set metadata record.

func (*PostgresStore) UpsertAuthzRelationship

func (p *PostgresStore) UpsertAuthzRelationship(ctx context.Context, relationship AuthzRelationship) error

UpsertAuthzRelationship creates or updates one scoped ReBAC tuple.

func (*PostgresStore) UpsertFindingTriageState

func (p *PostgresStore) UpsertFindingTriageState(ctx context.Context, state FindingTriageState) error

UpsertFindingTriageState creates or updates mutable triage metadata.

func (*PostgresStore) UpsertFindings

func (p *PostgresStore) UpsertFindings(ctx context.Context, scanID string, findings []domain.Finding) error

UpsertFindings inserts findings idempotently for the scan.

func (*PostgresStore) UpsertOnboardingState

func (p *PostgresStore) UpsertOnboardingState(ctx context.Context, state OnboardingState) (OnboardingState, error)

UpsertOnboardingState persists one user-scoped onboarding progress row.

func (*PostgresStore) UpsertOrganization

func (p *PostgresStore) UpsertOrganization(ctx context.Context, organization TenancyOrganization) error

UpsertOrganization persists one scoped organization metadata row.

func (*PostgresStore) UpsertProject

func (p *PostgresStore) UpsertProject(ctx context.Context, project TenancyProject) error

UpsertProject persists one scoped project record.

func (*PostgresStore) UpsertRepoFindings

func (p *PostgresStore) UpsertRepoFindings(ctx context.Context, repoScanID string, findings []domain.Finding) error

UpsertRepoFindings inserts repository findings idempotently.

func (*PostgresStore) UpsertRepoScanCursor

func (p *PostgresStore) UpsertRepoScanCursor(ctx context.Context, cursor RepoScanCursor) error

UpsertRepoScanCursor stores the latest successful scan cursor for one repository source.

func (*PostgresStore) UpsertTenancyConnector

func (p *PostgresStore) UpsertTenancyConnector(ctx context.Context, connector TenancyConnector, state TenancyConnectorState) error

UpsertTenancyConnector persists one connector and its latest state atomically.

func (*PostgresStore) UpsertTenancyConnectorSecretEnvelope

func (p *PostgresStore) UpsertTenancyConnectorSecretEnvelope(ctx context.Context, envelope TenancyConnectorSecretEnvelope) error

UpsertTenancyConnectorSecretEnvelope persists one encrypted connector secret envelope.

func (*PostgresStore) UpsertTenancyScanPolicy

func (p *PostgresStore) UpsertTenancyScanPolicy(ctx context.Context, policy TenancyScanPolicy) error

UpsertTenancyScanPolicy persists one scan policy for a scoped project.

func (*PostgresStore) UpsertUser

func (p *PostgresStore) UpsertUser(ctx context.Context, user User) (User, error)

UpsertUser persists one account row.

func (*PostgresStore) UpsertUserIdentity

func (p *PostgresStore) UpsertUserIdentity(ctx context.Context, identity UserIdentity) (UserIdentity, error)

UpsertUserIdentity persists one provider identity mapping.

func (*PostgresStore) UpsertWorkspace

func (p *PostgresStore) UpsertWorkspace(ctx context.Context, workspace TenancyWorkspace) error

UpsertWorkspace persists one scoped workspace record.

func (*PostgresStore) UpsertWorkspaceMember

func (p *PostgresStore) UpsertWorkspaceMember(ctx context.Context, member TenancyWorkspaceMember) error

UpsertWorkspaceMember persists one scoped workspace member record.

type RelationshipFilter

type RelationshipFilter struct {
	ScanID     string
	Type       string
	FromNodeID string
	ToNodeID   string
}

RelationshipFilter controls relationship list query shape.

type RepoFindingClusterListFilter

type RepoFindingClusterListFilter struct {
	RepoScanID string
	Severity   string
	Type       string
	SortBy     string
	SortDesc   bool
	Limit      int
	Offset     int
}

RepoFindingClusterListFilter controls repository finding cluster list queries.

func NormalizeRepoFindingClusterListFilter

func NormalizeRepoFindingClusterListFilter(filter RepoFindingClusterListFilter) RepoFindingClusterListFilter

NormalizeRepoFindingClusterListFilter trims inputs and applies stable defaults.

type RepoFindingDeleteTarget added in v1.0.2

type RepoFindingDeleteTarget struct {
	RepoScanID string
	FindingID  string
}

RepoFindingDeleteTarget identifies one persisted repository finding row.

type RepoFindingFilter

type RepoFindingFilter struct {
	RepoScanID        string
	FindingID         string
	Repository        string
	Severity          string
	Type              string
	Status            string
	Detector          string
	Owner             string
	Source            string
	MinConfidence     float64
	MinAgeDays        int
	LifecycleStatus   string
	Assignee          string
	SortBy            string
	SortDesc          bool
	Now               time.Time
	IncludeHistorical bool
}

RepoFindingFilter controls repository finding list queries.

func NormalizeRepoFindingFilter

func NormalizeRepoFindingFilter(filter RepoFindingFilter) RepoFindingFilter

NormalizeRepoFindingFilter trims optional filters for repository findings.

type RepoScanContext

type RepoScanContext struct {
	ScanMode     string
	BaseRevision string
	HeadRevision string
	CursorBefore string
	CursorAfter  string
	ChangedPaths []string
	// InconclusiveLifecycleKeys are lifecycle keys this scan observed but could
	// not conclusively re-evaluate, so completion must not close them. A GitHub
	// posture check that is permission-limited or unavailable still promotes a
	// finding under the same lifecycle key, but at a confidence and severity the
	// reportable filter drops. Without this list the key looks absent from the
	// scan and a real, unverified gap would be marked fixed.
	InconclusiveLifecycleKeys []string
	PartialSourceRun          bool
	SourceHealth              string
	SourceDetails             []RepoScanSourceHealth
}

RepoScanContext captures incremental execution metadata for one scan.

func NormalizeRepoScanContext

func NormalizeRepoScanContext(scanContext RepoScanContext) RepoScanContext

NormalizeRepoScanContext returns stable scan-mode and revision metadata.

type RepoScanCursor

type RepoScanCursor struct {
	TenantID            string         `json:"-"`
	WorkspaceID         string         `json:"-"`
	Repository          string         `json:"repository"`
	Source              RepoScanSource `json:"-"`
	LastScannedRevision string         `json:"last_scanned_revision,omitempty"`
	LastDeepScannedAt   *time.Time     `json:"last_deep_scanned_at,omitempty"`
	LastScanID          string         `json:"last_scan_id,omitempty"`
	LastScanMode        string         `json:"last_scan_mode,omitempty"`
	LastScanCompletedAt time.Time      `json:"last_scan_completed_at"`
	UpdatedAt           time.Time      `json:"updated_at"`
}

RepoScanCursor stores the latest scanned revision for one scoped repository source.

func (RepoScanCursor) Normalize

func (c RepoScanCursor) Normalize() RepoScanCursor

Normalize returns a stable cursor key and payload.

type RepoScanRecord

type RepoScanRecord struct {
	ID                  string                 `json:"id"`
	TenantID            string                 `json:"-"`
	WorkspaceID         string                 `json:"-"`
	Repository          string                 `json:"repository"`
	Status              string                 `json:"status"`
	StartedAt           time.Time              `json:"started_at"`
	FinishedAt          *time.Time             `json:"finished_at,omitempty"`
	CommitsScanned      int                    `json:"commits_scanned"`
	FilesScanned        int                    `json:"files_scanned"`
	FindingCount        int                    `json:"finding_count"`
	Truncated           bool                   `json:"truncated"`
	SourceHealth        string                 `json:"source_health"`
	SourceHealthDetails []RepoScanSourceHealth `json:"source_health_details,omitempty"`
	ScanMode            string                 `json:"scan_mode"`
	BaseRevision        string                 `json:"base_revision,omitempty"`
	HeadRevision        string                 `json:"head_revision,omitempty"`
	CursorBefore        string                 `json:"cursor_before,omitempty"`
	CursorAfter         string                 `json:"cursor_after,omitempty"`
	ChangedPaths        []string               `json:"changed_paths,omitempty"`
	ErrorMessage        string                 `json:"error_message,omitempty"`
	HistoryLimit        int                    `json:"-"`
	MaxFindings         int                    `json:"-"`
	Source              RepoScanSource         `json:"-"`
	TraceParent         string                 `json:"-"`
	TraceState          string                 `json:"-"`
}

RepoScanRecord tracks persisted repository exposure scan metadata.

type RepoScanSource

type RepoScanSource struct {
	Provider       string
	ProjectID      string
	ConnectorID    string
	InstallationID int64
}

RepoScanSource carries non-secret connector context for repository scans. It lets workers resolve short-lived credentials at execution time without persisting raw tokens in the queue.

func (RepoScanSource) Empty

func (s RepoScanSource) Empty() bool

Empty reports whether the scan has no connector-backed source.

func (RepoScanSource) Normalize

func (s RepoScanSource) Normalize() RepoScanSource

Normalize returns a copy with stable whitespace/casing.

type RepoScanSourceHealth added in v1.0.2

type RepoScanSourceHealth struct {
	Source    string `json:"source"`
	Status    string `json:"status"`
	Code      string `json:"code,omitempty"`
	Message   string `json:"message,omitempty"`
	Retryable bool   `json:"retryable,omitempty"`
}

RepoScanSourceHealth captures collection completeness for one repo scan source.

func NormalizeRepoScanSourceHealth added in v1.0.2

func NormalizeRepoScanSourceHealth(status string, details []RepoScanSourceHealth) (string, []RepoScanSourceHealth)

type SAMLRelayState

type SAMLRelayState struct {
	Handle        string     `json:"handle"`
	ConnectionID  string     `json:"connection_id"`
	SAMLRequestID string     `json:"saml_request_id"`
	ReturnTo      string     `json:"return_to,omitempty"`
	Intent        string     `json:"intent"`
	ExpiresAt     time.Time  `json:"expires_at"`
	CreatedAt     time.Time  `json:"created_at"`
	ConsumedAt    *time.Time `json:"consumed_at,omitempty"`
}

SAMLRelayState is the persisted SP-side context for one in-flight SAML SP-initiated AuthnRequest. The handle is the short opaque token that travels through the IdP as RelayState; the row is one-shot consumed by the ACS handler.

type SCIMProvisioningEventRecord

type SCIMProvisioningEventRecord struct {
	ID           string         `json:"id"`
	OrgID        string         `json:"org_id"`
	ConnectionID string         `json:"connection_id"`
	Op           string         `json:"op"`
	ExternalID   string         `json:"external_id,omitempty"`
	UserID       string         `json:"user_id,omitempty"`
	Payload      map[string]any `json:"payload,omitempty"`
	OccurredAt   time.Time      `json:"occurred_at"`
}

SCIMProvisioningEventRecord is the persisted form of one SCIM op recorded for tenant-visible governance audit. Append-only.

func NormalizeSCIMProvisioningEventForWrite

func NormalizeSCIMProvisioningEventForWrite(event SCIMProvisioningEventRecord) (SCIMProvisioningEventRecord, error)

NormalizeSCIMProvisioningEventForWrite validates and canonicalizes one persisted SCIM provisioning event prior to insert.

type ScanArtifacts

type ScanArtifacts struct {
	RawAssets     []providers.RawAsset
	Bundle        providers.NormalizedBundle
	Permissions   []providers.PermissionTuple
	Relationships []domain.Relationship
}

ScanArtifacts contains raw and normalized scan outputs to persist idempotently.

type ScanEvent

type ScanEvent struct {
	ID        string         `json:"id"`
	ScanID    string         `json:"scan_id"`
	Level     string         `json:"level"`
	Message   string         `json:"message"`
	Metadata  map[string]any `json:"metadata,omitempty"`
	CreatedAt time.Time      `json:"created_at"`
}

ScanEvent tracks important state transitions for scan observability.

type ScanRecord

type ScanRecord struct {
	ID              string     `json:"id"`
	TenantID        string     `json:"-"`
	WorkspaceID     string     `json:"-"`
	ProjectID       string     `json:"project_id,omitempty"`
	ConnectorID     string     `json:"connector_id,omitempty"`
	Provider        string     `json:"provider"`
	Status          string     `json:"status"`
	StartedAt       time.Time  `json:"started_at"`
	FinishedAt      *time.Time `json:"finished_at,omitempty"`
	AssetCount      int        `json:"asset_count"`
	FindingCount    int        `json:"finding_count"`
	ErrorMessage    string     `json:"error_message,omitempty"`
	RetryCount      int        `json:"retry_count"`
	MaxRetryCount   int        `json:"max_retry_count"`
	FailureCategory string     `json:"failure_category,omitempty"`
	NextRetryAt     *time.Time `json:"next_retry_at,omitempty"`
	DeadLettered    bool       `json:"dead_lettered"`
	DeadLetteredAt  *time.Time `json:"dead_lettered_at,omitempty"`
	TraceParent     string     `json:"-"`
	TraceState      string     `json:"-"`
}

ScanRecord tracks persisted scan execution metadata.

type ScanSource added in v1.0.2

type ScanSource struct {
	ProjectID   string
	ConnectorID string
}

ScanSource carries non-secret project/connector context for cloud scans.

func (ScanSource) Empty added in v1.0.2

func (s ScanSource) Empty() bool

Empty reports whether a scan has no explicit project/connector binding.

func (ScanSource) Normalize added in v1.0.2

func (s ScanSource) Normalize() ScanSource

Normalize returns a stable source key.

type Scope

type Scope struct {
	TenantID    string
	WorkspaceID string
}

Scope represents the active tenant/workspace boundary for a request.

func LookupScope

func LookupScope(ctx context.Context) (Scope, bool)

LookupScope returns scope from context when present.

func RequireScope

func RequireScope(ctx context.Context) (Scope, error)

RequireScope returns the active scope and fails when context is unscoped.

func ScopeFromContext

func ScopeFromContext(ctx context.Context) Scope

ScopeFromContext always returns a non-empty scope.

func (Scope) Normalize

func (s Scope) Normalize() Scope

Normalize returns a canonical, non-empty scope using secure defaults.

type Session

type Session struct {
	ID                 []byte     `json:"-"`
	UserID             string     `json:"user_id"`
	CurrentOrgID       string     `json:"current_org_id,omitempty"`
	CurrentWorkspaceID string     `json:"current_workspace_id,omitempty"`
	CurrentProjectID   string     `json:"current_project_id,omitempty"`
	AuthMethod         string     `json:"auth_method"`
	IP                 string     `json:"ip,omitempty"`
	UserAgent          string     `json:"user_agent,omitempty"`
	IdleExpiresAt      time.Time  `json:"idle_expires_at"`
	AbsoluteExpiresAt  time.Time  `json:"absolute_expires_at"`
	LastSeenAt         time.Time  `json:"last_seen_at"`
	RevokedAt          *time.Time `json:"revoked_at,omitempty"`
	CreatedAt          time.Time  `json:"created_at"`
	User               *User      `json:"user,omitempty"`
}

Session stores one opaque server-side browser session.

func NormalizeSessionForWrite

func NormalizeSessionForWrite(session Session) (Session, error)

NormalizeSessionForWrite validates and canonicalizes one session row.

type Store

type Store interface {
	CreateScan(ctx context.Context, provider string, startedAt time.Time) (ScanRecord, error)
	CreateQueuedScan(ctx context.Context, provider string, queuedAt time.Time) (ScanRecord, error)
	CreateQueuedScanWithSource(ctx context.Context, provider string, source ScanSource, queuedAt time.Time) (ScanRecord, error)
	CreateQueuedScanWithinLimit(ctx context.Context, provider string, queuedAt time.Time, maxPending int) (ScanRecord, error)
	CreateQueuedScanWithinLimitWithSource(ctx context.Context, provider string, source ScanSource, queuedAt time.Time, maxPending int) (ScanRecord, error)
	CreateQueuedScanIfNoPending(ctx context.Context, provider string, queuedAt time.Time) (ScanRecord, error)
	CreateQueuedScanIfNoPendingWithSource(ctx context.Context, provider string, source ScanSource, queuedAt time.Time) (ScanRecord, error)
	ClaimNextQueuedScan(ctx context.Context, provider string) (ScanRecord, error)
	ClaimNextQueuedScanAnyScope(ctx context.Context, provider string) (ScanRecord, error)
	CountQueuedScans(ctx context.Context, provider string) (int, error)
	CountQueuedScansWithSource(ctx context.Context, provider string, source ScanSource) (int, error)
	CountPendingScansWithSource(ctx context.Context, provider string, source ScanSource) (int, error)
	GetScan(ctx context.Context, scanID string) (ScanRecord, error)
	CompleteScan(ctx context.Context, scanID string, status string, finishedAt time.Time, assetCount int, findingCount int, errorMessage string) error
	ScheduleScanRetry(ctx context.Context, scanID string, queuedAt time.Time, retryCount int, maxRetryCount int, failureCategory string, errorMessage string, nextRetryAt time.Time) error
	DeadLetterScan(ctx context.Context, scanID string, finishedAt time.Time, retryCount int, maxRetryCount int, assetCount int, findingCount int, failureCategory string, errorMessage string) error
	UpsertArtifacts(ctx context.Context, scanID string, artifacts ScanArtifacts) error
	UpsertFindings(ctx context.Context, scanID string, findings []domain.Finding) error
	GetFindingTriageState(ctx context.Context, findingID string) (FindingTriageState, error)
	ListFindingTriageStates(ctx context.Context, findingIDs []string) ([]FindingTriageState, error)
	UpsertFindingTriageState(ctx context.Context, state FindingTriageState) error
	AppendFindingTriageEvent(ctx context.Context, event FindingTriageEvent) error
	ApplyFindingTriageTransition(ctx context.Context, state FindingTriageState, event FindingTriageEvent) error
	ListFindingTriageEvents(ctx context.Context, findingID string, limit int) ([]FindingTriageEvent, error)
	ListScans(ctx context.Context, limit int) ([]ScanRecord, error)
	ListFindings(ctx context.Context, limit int) ([]domain.Finding, error)
	ListFindingsFiltered(ctx context.Context, filter FindingListFilter) ([]domain.Finding, error)
	ListFindingsAll(ctx context.Context) ([]domain.Finding, error)
	ListFindingsByScan(ctx context.Context, scanID string, limit int) ([]domain.Finding, error)
	GetFinding(ctx context.Context, findingID string, scanID string) (domain.Finding, error)
	ListFindingMetasByScan(ctx context.Context, scanID string) ([]FindingMeta, error)
	ListFindingsByScanAndIDs(ctx context.Context, scanID string, findingIDs []string) ([]domain.Finding, error)
	ListFindingTrendCounts(ctx context.Context, scanIDs []string, severity string, findingType string) ([]FindingTrendCount, error)
	ListRepoFindingTrendCounts(ctx context.Context, repoScanIDs []string, severity string, findingType string, minConfidence float64) ([]FindingTrendCount, error)
	UpsertAuthzEntityAttributes(ctx context.Context, attributes AuthzEntityAttributes) error
	GetAuthzEntityAttributes(ctx context.Context, entityKind string, entityType string, entityID string) (AuthzEntityAttributes, error)
	UpsertAuthzRelationship(ctx context.Context, relationship AuthzRelationship) error
	DeleteAuthzRelationship(ctx context.Context, relationship AuthzRelationship) error
	ListAuthzRelationships(ctx context.Context, filter AuthzRelationshipFilter, limit int) ([]AuthzRelationship, error)
	UpsertAuthzPolicySet(ctx context.Context, policySet AuthzPolicySet) error
	GetAuthzPolicySet(ctx context.Context, policySetID string) (AuthzPolicySet, error)
	CreateAuthzPolicyVersion(ctx context.Context, version AuthzPolicyVersion) (AuthzPolicyVersion, error)
	GetAuthzPolicyVersion(ctx context.Context, policySetID string, version int) (AuthzPolicyVersion, error)
	ListAuthzPolicyVersions(ctx context.Context, policySetID string, limit int) ([]AuthzPolicyVersion, error)
	UpsertAuthzPolicyRollout(ctx context.Context, rollout AuthzPolicyRollout) error
	GetAuthzPolicyRollout(ctx context.Context, policySetID string) (AuthzPolicyRollout, error)
	AppendAuthzPolicyEvent(ctx context.Context, event AuthzPolicyEvent) error
	ListAuthzPolicyEvents(ctx context.Context, policySetID string, limit int) ([]AuthzPolicyEvent, error)
	UpsertOrganization(ctx context.Context, organization TenancyOrganization) error
	GetOrganization(ctx context.Context) (TenancyOrganization, error)
	DeleteOrganization(ctx context.Context) error
	UpsertWorkspace(ctx context.Context, workspace TenancyWorkspace) error
	GetWorkspace(ctx context.Context, workspaceID string) (TenancyWorkspace, error)
	ListWorkspaces(ctx context.Context, limit int) ([]TenancyWorkspace, error)
	DeleteWorkspace(ctx context.Context, workspaceID string) error
	// SuspendWorkspace flips the workspace to status=suspended and stamps
	// suspended_at. Idempotent: a repeat call preserves the original
	// suspended_at so an over-eager UI cannot drift the timestamp.
	SuspendWorkspace(ctx context.Context, workspaceID string, now time.Time) (TenancyWorkspace, error)
	// ReactivateWorkspace flips a suspended workspace back to active and
	// clears suspended_at. A no-op on an already-active workspace.
	ReactivateWorkspace(ctx context.Context, workspaceID string, now time.Time) (TenancyWorkspace, error)
	// SoftDeleteWorkspace flips the workspace to status=deleted and stamps
	// deleted_at to start the reversible grace window. Idempotent: a repeat
	// call preserves the original deleted_at so the purge deadline cannot
	// be pushed back.
	SoftDeleteWorkspace(ctx context.Context, workspaceID string, now time.Time) (TenancyWorkspace, error)
	// CancelWorkspaceDeletion reverses a soft delete during the grace
	// window: clears deleted_at and returns the workspace to status=active.
	CancelWorkspaceDeletion(ctx context.Context, workspaceID string, now time.Time) (TenancyWorkspace, error)
	// ListWorkspaceStrandedActiveMembers returns the OTHER active members
	// in the workspace iff the caller is the sole active owner. An empty
	// slice means no stranding would occur — either there are co-owners,
	// or the caller is the only member. Used to gate suspend/delete with
	// the structured `sole_owner_requires_transfer` 409 from #1420.
	ListWorkspaceStrandedActiveMembers(ctx context.Context, workspaceID string, userUUID string) ([]TenancyWorkspaceMember, error)
	// ListWorkspacesPendingHardDelete returns soft-deleted workspaces
	// whose grace window closed (deleted_at < deletedBefore), so the
	// workspace hard-delete worker can purge them. Bypasses scope so
	// the worker enumerates across tenants.
	ListWorkspacesPendingHardDelete(ctx context.Context, deletedBefore time.Time, limit int) ([]TenancyWorkspace, error)
	// HardDeleteWorkspace permanently removes a workspace whose
	// soft-delete grace window has elapsed. The (tenantID, workspaceID)
	// pair is the composite identity — workspace_id alone is not
	// globally unique (defaults like "default" repeat across tenants),
	// so a tenant-less lookup risks destroying a different tenant's
	// data. expectedDeletedAt is the deleted_at the worker observed
	// when it listed this row; the destructive SQL requires the
	// current row's deleted_at to still match, so a cancel-deletion +
	// re-delete race between the worker's list and its purge refreshes
	// the row to a new fresh-grace deleted_at and is correctly refused.
	//
	// Implementations refuse the purge unless the row is genuinely past
	// grace (status='deleted', deleted_at = expectedDeletedAt). Cascades
	// to every child table with an FK on tenancy_workspaces (members,
	// projects, connectors, secret envelopes, scan policies) and
	// explicitly purges every workspace-scoped non-FK table the
	// migrations have introduced (scans, repo_scans, AWS coverage,
	// authz tables, finding triage). Returns the deleted workspace row
	// for audit metadata.
	HardDeleteWorkspace(ctx context.Context, tenantID, workspaceID string, expectedDeletedAt time.Time, now time.Time) (TenancyWorkspace, error)
	UpsertWorkspaceMember(ctx context.Context, member TenancyWorkspaceMember) error
	GetWorkspaceMember(ctx context.Context, workspaceID string, memberID string) (TenancyWorkspaceMember, error)
	GetWorkspaceMemberByUserUUID(ctx context.Context, workspaceID string, userUUID string) (TenancyWorkspaceMember, error)
	ListWorkspaceMembers(ctx context.Context, workspaceID string, limit int) ([]TenancyWorkspaceMember, error)
	DeleteWorkspaceMember(ctx context.Context, workspaceID string, memberID string) error
	UpsertProject(ctx context.Context, project TenancyProject) error
	GetProject(ctx context.Context, workspaceID string, projectID string) (TenancyProject, error)
	ListProjects(ctx context.Context, workspaceID string, includeArchived bool, limit int) ([]TenancyProject, error)
	DeleteProject(ctx context.Context, workspaceID string, projectID string) error
	CreateTenancyConnectorWithSecretEnvelopeIfAbsent(ctx context.Context, connector TenancyConnector, state TenancyConnectorState, envelope TenancyConnectorSecretEnvelope) (TenancyConnectorWithState, bool, error)
	UpsertTenancyConnector(ctx context.Context, connector TenancyConnector, state TenancyConnectorState) error
	GetTenancyConnector(ctx context.Context, workspaceID string, projectID string, connectorID string) (TenancyConnectorWithState, error)
	ListTenancyConnectors(ctx context.Context, workspaceID string, projectID string, connectorType domain.ConnectorType, limit int) ([]TenancyConnectorWithState, error)
	ListTenancyConnectorsUnscoped(ctx context.Context, connectorType domain.ConnectorType, limit int) ([]TenancyConnectorWithState, error)
	UpsertAWSAccountRegionCoverage(ctx context.Context, coverage AWSAccountRegionCoverage) (AWSAccountRegionCoverage, error)
	ListAWSAccountRegionCoverages(ctx context.Context, filter AWSAccountRegionCoverageFilter) ([]AWSAccountRegionCoverage, error)
	UpsertAWSPlatformBaselineResult(ctx context.Context, result AWSPlatformBaselineResult) (AWSPlatformBaselineResult, error)
	GetAWSPlatformBaselineResult(ctx context.Context, filter AWSPlatformBaselineFilter) (AWSPlatformBaselineResult, error)
	ClaimKubernetesEnrollmentToken(ctx context.Context, workspaceID string, projectID string, connectorID string, expectedEnrollmentTokenHash string, updatedMetadata map[string]any, status domain.ConnectorStatus, health string, lastErrorCode string, lastErrorMessage string, observedAt time.Time, updatedAt time.Time) (bool, error)
	UpsertTenancyScanPolicy(ctx context.Context, policy TenancyScanPolicy) error
	GetTenancyScanPolicy(ctx context.Context, workspaceID string, projectID string, policyID string) (TenancyScanPolicy, error)
	ListTenancyScanPolicies(ctx context.Context, workspaceID string, projectID string, triggerMode domain.ScanTriggerMode, enabled *bool, sortBy string, sortDesc bool, limit int) ([]TenancyScanPolicy, error)
	ListScheduledTenancyScanPolicies(ctx context.Context, limit int, offset int) ([]TenancyScanPolicy, error)
	ClaimTenancyScanPolicySchedule(ctx context.Context, workspaceID string, projectID string, policyID string, scheduledAt time.Time, now time.Time) (bool, error)
	DeleteTenancyScanPolicy(ctx context.Context, workspaceID string, projectID string, policyID string) error
	CreateTenancyConnectorSecretEnvelopeIfAbsent(ctx context.Context, envelope TenancyConnectorSecretEnvelope) (TenancyConnectorSecretEnvelope, bool, error)
	UpsertTenancyConnectorSecretEnvelope(ctx context.Context, envelope TenancyConnectorSecretEnvelope) error
	GetTenancyConnectorSecretEnvelope(ctx context.Context, workspaceID string, projectID string, connectorID string, secretName string) (TenancyConnectorSecretEnvelope, error)
	DeleteTenancyConnectorSecretEnvelope(ctx context.Context, workspaceID string, projectID string, connectorID string, secretName string) error
	UpsertUser(ctx context.Context, user User) (User, error)
	UpdateUserProfile(ctx context.Context, user User) (User, error)
	UpdateCurrentUserProfile(ctx context.Context, userID string, displayName *string, avatarURL *string, updatedAt time.Time) (User, error)
	GetUser(ctx context.Context, userID string) (User, error)
	GetUserByPrimaryEmail(ctx context.Context, email string) (User, error)
	SetUserStatus(ctx context.Context, userID string, status string, now time.Time) (User, error)
	// SoftDeleteUser flips the account to status=deleted and stamps deleted_at
	// to start the reversible grace window. Idempotent: an already-deleted row
	// keeps its original deleted_at so repeat calls cannot extend the deadline.
	SoftDeleteUser(ctx context.Context, userID string, now time.Time) (User, error)
	// CancelUserDeletion reverses a soft delete during the grace window: it
	// clears deleted_at and returns the account to status=active.
	CancelUserDeletion(ctx context.Context, userID string, now time.Time) (User, error)
	// ListUsersPendingHardDelete returns soft-deleted accounts whose grace
	// window closed (deleted_at < deletedBefore) and whose PII has not already
	// been purged, so the worker can hard-delete them.
	ListUsersPendingHardDelete(ctx context.Context, deletedBefore time.Time, limit int) ([]User, error)
	// HardDeleteUser purges PII from a soft-deleted account (email tombstoned,
	// display name and avatar cleared) and deletes its provider identities and
	// sessions, while keeping the users row so audit references by UUID stay
	// intact. Idempotent and safely re-runnable.
	HardDeleteUser(ctx context.Context, userID string, now time.Time) (User, error)
	UpsertUserIdentity(ctx context.Context, identity UserIdentity) (UserIdentity, error)
	GetUserIdentity(ctx context.Context, provider string, subject string) (UserIdentity, error)
	GetUserIdentityByProviderUserID(ctx context.Context, provider string, userID string) (UserIdentity, error)
	ListUserIdentitiesByProvider(ctx context.Context, provider string, limit int) ([]UserIdentity, error)
	DeleteUserIdentity(ctx context.Context, provider string, subject string) error
	CreateSession(ctx context.Context, session Session) (Session, error)
	TouchSession(ctx context.Context, sessionIDHash []byte, now time.Time) (Session, error)
	// TouchSessionAllowingPendingDeletion is TouchSession with the lifecycle
	// gate relaxed so cookies pointing to a soft-deleted-within-grace user
	// resolve to their session. It is the single-purpose authentication path
	// for `/v1/me/cancel-deletion` — every other route uses TouchSession and
	// continues to refuse deleted users.
	TouchSessionAllowingPendingDeletion(ctx context.Context, sessionIDHash []byte, now time.Time) (Session, error)
	UpdateSessionContext(ctx context.Context, userID string, sessionIDHash []byte, orgID string, workspaceID string, projectID string, now time.Time) (Session, error)
	ListUserSessions(ctx context.Context, userID string, now time.Time, limit int) ([]Session, error)
	ListUserSessionHistory(ctx context.Context, userID string, limit int) ([]Session, error)
	RevokeUserSession(ctx context.Context, userID string, sessionIDHash []byte, revokedAt time.Time) (Session, error)
	RevokeOtherUserSessions(ctx context.Context, userID string, currentSessionIDHash []byte, revokedAt time.Time) (int, error)
	RevokeAllUserSessions(ctx context.Context, userID string, revokedAt time.Time) (int, error)
	// CreateUserDataExport enqueues a new "Download my data" export job for
	// the caller. The store generates an ID if one is not supplied.
	CreateUserDataExport(ctx context.Context, export UserDataExport) (UserDataExport, error)
	// GetUserDataExport returns one export job, scoped to its owner. Returns
	// ErrNotFound if the row does not exist OR belongs to a different user so
	// scoping cannot be bypassed by guessing job ids.
	GetUserDataExport(ctx context.Context, userID string, jobID string) (UserDataExport, error)
	// GetUserDataExportByID returns one export job by id without scoping to a
	// caller. Used by the signed-download route, which authorizes via the
	// HMAC token rather than a session cookie.
	GetUserDataExportByID(ctx context.Context, jobID string) (UserDataExport, error)
	// ListUserDataExports returns the user's export jobs, newest first.
	ListUserDataExports(ctx context.Context, userID string, limit int) ([]UserDataExport, error)
	// ClaimNextQueuedUserDataExport atomically transitions one queued job to
	// running and returns it. Returns ErrNotFound when nothing is queued.
	ClaimNextQueuedUserDataExport(ctx context.Context, now time.Time) (UserDataExport, error)
	// ClaimQueuedUserDataExport atomically transitions the named queued job to
	// running and returns it. Returns ErrNotFound if the job is already claimed
	// or terminal.
	ClaimQueuedUserDataExport(ctx context.Context, jobID string, now time.Time) (UserDataExport, error)
	// CompleteUserDataExport marks a running job ready and records the
	// finished bundle's metadata and TTLs.
	CompleteUserDataExport(ctx context.Context, jobID string, bundlePath string, sizeBytes int64, sha256Hex string, completedAt time.Time, downloadExpiresAt time.Time, purgeAfter time.Time) (UserDataExport, error)
	// FailUserDataExport marks a job failed and records the error message.
	FailUserDataExport(ctx context.Context, jobID string, errMsg string, failedAt time.Time) (UserDataExport, error)
	// FailStaleRunningUserDataExports marks running jobs as failed when they
	// have been running since before startedBefore and returns the jobs that were
	// transitioned. Workers use this after restarts so interrupted jobs do not
	// remain running forever.
	FailStaleRunningUserDataExports(ctx context.Context, startedBefore time.Time, failedAt time.Time, limit int, errMsg string) ([]UserDataExport, error)
	// ListUserDataExportsPendingPurge returns ready jobs whose retention
	// window has elapsed and whose bundle file has not yet been removed.
	ListUserDataExportsPendingPurge(ctx context.Context, now time.Time, limit int) ([]UserDataExport, error)
	// MarkUserDataExportPurged transitions a job to expired and stamps
	// purged_at after the worker has removed the bundle from storage.
	MarkUserDataExportPurged(ctx context.Context, jobID string, now time.Time) (UserDataExport, error)
	UpsertOnboardingState(ctx context.Context, state OnboardingState) (OnboardingState, error)
	GetOnboardingState(ctx context.Context, userID string) (OnboardingState, error)
	FindFirstWorkspaceMemberByUserUUID(ctx context.Context, userUUID string) (TenancyWorkspaceMember, error)
	FindFirstWorkspaceMemberByUserUUIDAndTenantID(ctx context.Context, userUUID string, tenantID string) (TenancyWorkspaceMember, error)
	ListWorkspaceMembershipsByUserUUID(ctx context.Context, userUUID string) ([]TenancyWorkspaceMember, error)
	ListWorkspaceMembershipsByUserUUIDAndTenantID(ctx context.Context, userUUID string, tenantID string) ([]TenancyWorkspaceMember, error)
	// ListSoleOwnerWorkspaces returns every workspace, across all tenants, in
	// which the user is the only active owner. Account deletion uses this to
	// refuse with a structured 409 until ownership is transferred.
	ListSoleOwnerWorkspaces(ctx context.Context, userUUID string) ([]TenancyWorkspace, error)
	CreateInvitation(ctx context.Context, invitation Invitation) (Invitation, error)
	GetInvitation(ctx context.Context, orgID string, invitationID string) (Invitation, error)
	ListInvitations(ctx context.Context, orgID string, limit int) ([]Invitation, error)
	RevokeInvitation(ctx context.Context, orgID string, invitationID string, revokedAt time.Time) (Invitation, error)
	CreateVerifiedDomain(ctx context.Context, domain VerifiedDomain) (VerifiedDomain, error)
	GetVerifiedDomain(ctx context.Context, orgID string, domainID string) (VerifiedDomain, error)
	ListVerifiedDomains(ctx context.Context, orgID string, limit int) ([]VerifiedDomain, error)
	CreateIdentityConnection(ctx context.Context, connection IdentityConnection) (IdentityConnection, error)
	GetIdentityConnection(ctx context.Context, orgID string, connectionID string) (IdentityConnection, error)
	// GetIdentityConnectionByID looks up a connection by its globally unique
	// UUID without requiring the caller to know the owning org id. Needed
	// for unauthenticated entry points like /auth/saml/login/:connection_id
	// where the org context is determined by the connection itself.
	GetIdentityConnectionByID(ctx context.Context, connectionID string) (IdentityConnection, error)
	GetIdentityConnectionBySCIMBearerTokenHash(ctx context.Context, tokenHash string) (IdentityConnection, error)
	// CreateSAMLRelayState persists one in-flight SAML SP-initiated request
	// so the matching ACS POST (potentially handled by a different API
	// instance) can look the AuthnRequest id, connection scope, and
	// return_to back up by the opaque handle.
	CreateSAMLRelayState(ctx context.Context, state SAMLRelayState) (SAMLRelayState, error)
	// ConsumeSAMLRelayState marks the row consumed and returns the persisted
	// state. A subsequent call with the same handle returns ErrNotFound so
	// the relay value cannot be replayed.
	ConsumeSAMLRelayState(ctx context.Context, handle string, now time.Time) (SAMLRelayState, error)
	// CreateOAuthTransaction persists one in-flight WorkOS OAuth login so the
	// callback (potentially handled by a different API instance) can match
	// the signed state nonce and browser-bound cookie token against a
	// single-use, short-TTL row.
	CreateOAuthTransaction(ctx context.Context, txn OAuthTransaction) (OAuthTransaction, error)
	// ConsumeOAuthTransaction atomically consumes the row matching nonce and
	// cookieToken when it is unexpired and unconsumed, returning the stored
	// transaction. Any later, expired, missing, or cookie-mismatched call
	// returns ErrNotFound so the OAuth state cannot be replayed.
	ConsumeOAuthTransaction(ctx context.Context, nonce string, cookieToken string, now time.Time) (OAuthTransaction, error)
	// BeginWebhookEvent atomically claims a provider webhook event for
	// processing. It returns WebhookEventClaimed when this delivery inserted
	// the row (or reclaimed a stale in-flight row older than
	// WebhookProcessingReclaimAfter) and must apply the side effects;
	// WebhookEventProcessing when another delivery of the same event is
	// still in flight (the caller must return a retryable response, never a
	// success acknowledgement); and WebhookEventProcessed when the event was
	// already fully handled (the caller returns a no-op success). Atomic at
	// the database, so it holds across restarts and concurrent API
	// instances.
	// When the status is WebhookEventClaimed the returned claim token
	// identifies this specific claim; it must be passed back to
	// CompleteWebhookEvent / DeleteWebhookEvent so a handler whose claim was
	// reclaimed (because it ran past WebhookProcessingReclaimAfter and a
	// retry took over) cannot complete or erase the successor's claim. The
	// token is empty for the non-claimed statuses.
	BeginWebhookEvent(ctx context.Context, event WebhookEvent, now time.Time) (WebhookEventStatus, string, error)
	// CompleteWebhookEvent marks a claimed event as fully processed so later
	// duplicate deliveries become no-op successes. Called after side effects
	// are durably applied, or for a deterministic terminal outcome (bad
	// payload, identity conflict) that an identical retry would not resolve.
	// It only acts on the row if claimToken still matches the active claim,
	// so a superseded stale handler cannot mark the successor's in-flight
	// claim processed.
	CompleteWebhookEvent(ctx context.Context, provider string, eventID string, claimToken string, now time.Time) error
	// DeleteWebhookEvent rolls back a claimed webhook row when a transient
	// (server-side) failure prevented the side effects from being applied,
	// so a provider retry can reprocess it. It only deletes the row if
	// claimToken still matches the active claim, so a superseded stale
	// handler cannot erase the successor's claim.
	DeleteWebhookEvent(ctx context.Context, provider string, eventID string, claimToken string) error
	ListIdentityConnections(ctx context.Context, orgID string, limit int) ([]IdentityConnection, error)
	UpdateIdentityConnection(ctx context.Context, connection IdentityConnection) (IdentityConnection, error)
	DeleteIdentityConnection(ctx context.Context, orgID string, connectionID string) error
	CreateSCIMProvisioningEvent(ctx context.Context, event SCIMProvisioningEventRecord) (SCIMProvisioningEventRecord, error)
	ListSCIMProvisioningEvents(ctx context.Context, orgID string, connectionID string, limit int) ([]SCIMProvisioningEventRecord, error)
	ListIdentities(ctx context.Context, filter IdentityFilter, limit int) ([]domain.Identity, error)
	ListRelationships(ctx context.Context, filter RelationshipFilter, limit int) ([]domain.Relationship, error)
	AppendScanEvent(ctx context.Context, scanID string, level string, message string, metadata map[string]any) error
	ListScanEvents(ctx context.Context, scanID string, limit int) ([]ScanEvent, error)
	SummarizeFindings(ctx context.Context) (FindingSummaryCounts, error)
	CreateRepoScan(ctx context.Context, repository string, source RepoScanSource, scanContext RepoScanContext, startedAt time.Time) (RepoScanRecord, error)
	CreateQueuedRepoScan(ctx context.Context, repository string, source RepoScanSource, scanContext RepoScanContext, historyLimit int, maxFindings int, queuedAt time.Time) (RepoScanRecord, error)
	CreateQueuedRepoScanWithinLimit(ctx context.Context, repository string, source RepoScanSource, scanContext RepoScanContext, historyLimit int, maxFindings int, queuedAt time.Time, maxPending int) (RepoScanRecord, error)
	ClaimNextQueuedRepoScan(ctx context.Context) (RepoScanRecord, error)
	ClaimNextQueuedRepoScanAnyScope(ctx context.Context) (RepoScanRecord, error)
	CountQueuedRepoScans(ctx context.Context) (int, error)
	CountPendingRepoScansByRepository(ctx context.Context, repository string) (int, error)
	RequeueRepoScan(ctx context.Context, repoScanID string) error
	FailStaleRepoScansAnyScope(ctx context.Context, staleBefore time.Time, limit int, errorMessage string) (int, error)
	GetRepoScan(ctx context.Context, repoScanID string) (RepoScanRecord, error)
	CancelRepoScan(ctx context.Context, repoScanID string, finishedAt time.Time, errorMessage string) (RepoScanRecord, error)
	DeleteRepoScan(ctx context.Context, repoScanID string) error
	CompleteRepoScan(ctx context.Context, repoScanID string, status string, finishedAt time.Time, commitsScanned int, filesScanned int, findingCount int, truncated bool, scanContext RepoScanContext, errorMessage string) error
	GetRepoScanCursor(ctx context.Context, repository string, source RepoScanSource) (RepoScanCursor, error)
	UpsertRepoScanCursor(ctx context.Context, cursor RepoScanCursor) error
	UpsertRepoFindings(ctx context.Context, repoScanID string, findings []domain.Finding) error
	DeleteRepoFindings(ctx context.Context, repoScanID string) error
	DeleteRepoFinding(ctx context.Context, repoScanID string, findingID string) error
	ExpandRepoFindingDeleteTargets(ctx context.Context, targets []RepoFindingDeleteTarget) ([]RepoFindingDeleteTarget, error)
	DeleteRepoFindingTargets(ctx context.Context, targets []RepoFindingDeleteTarget) ([]RepoFindingDeleteTarget, error)
	ListRepoScans(ctx context.Context, limit int) ([]RepoScanRecord, error)
	ListRepoFindings(ctx context.Context, filter RepoFindingFilter, limit int) ([]domain.Finding, error)
	ListRepoFindingClusters(ctx context.Context, filter RepoFindingClusterListFilter) ([]domain.RepoFindingCluster, error)
	Close() error
}

Store defines persistence operations required by API and scheduler orchestration.

type TenancyConnector

type TenancyConnector struct {
	TenantID            string                 `json:"tenant_id"`
	WorkspaceID         string                 `json:"workspace_id"`
	ProjectID           string                 `json:"project_id"`
	ConnectorID         string                 `json:"connector_id"`
	Type                domain.ConnectorType   `json:"type"`
	DisplayName         string                 `json:"display_name"`
	Status              domain.ConnectorStatus `json:"status"`
	SecretProvider      string                 `json:"secret_provider,omitempty"`
	SecretRefID         string                 `json:"secret_ref_id,omitempty"`
	SecretRefVersion    string                 `json:"secret_ref_version,omitempty"`
	SecretLastRotatedAt *time.Time             `json:"secret_last_rotated_at,omitempty"`
	ConfigChecksum      string                 `json:"config_checksum,omitempty"`
	LastSyncAt          *time.Time             `json:"last_sync_at,omitempty"`
	CreatedAt           time.Time              `json:"created_at"`
	UpdatedAt           time.Time              `json:"updated_at"`
}

TenancyConnector stores one project-scoped source connector record.

func NormalizeTenancyConnectorForWrite

func NormalizeTenancyConnectorForWrite(connector TenancyConnector) (TenancyConnector, error)

NormalizeTenancyConnectorForWrite validates and canonicalizes source connector metadata.

type TenancyConnectorSecretEnvelope

type TenancyConnectorSecretEnvelope struct {
	TenantID        string               `json:"tenant_id"`
	WorkspaceID     string               `json:"workspace_id"`
	ProjectID       string               `json:"project_id"`
	ConnectorID     string               `json:"connector_id"`
	SecretName      string               `json:"secret_name"`
	EnvelopeVersion int                  `json:"envelope_version"`
	Envelope        secretstore.Envelope `json:"envelope"`
	SecretRefID     string               `json:"secret_ref_id,omitempty"`
	RotatedAt       time.Time            `json:"rotated_at"`
	RotationDueAt   *time.Time           `json:"rotation_due_at,omitempty"`
	CreatedAt       time.Time            `json:"created_at"`
	UpdatedAt       time.Time            `json:"updated_at"`
}

TenancyConnectorSecretEnvelope stores one encrypted connector secret envelope.

func NormalizeTenancyConnectorSecretEnvelopeForWrite

func NormalizeTenancyConnectorSecretEnvelopeForWrite(secret TenancyConnectorSecretEnvelope) (TenancyConnectorSecretEnvelope, error)

NormalizeTenancyConnectorSecretEnvelopeForWrite validates one connector secret envelope record.

type TenancyConnectorState

type TenancyConnectorState struct {
	TenantID             string         `json:"tenant_id"`
	WorkspaceID          string         `json:"workspace_id"`
	ProjectID            string         `json:"project_id"`
	ConnectorID          string         `json:"connector_id"`
	HealthStatus         string         `json:"health_status"`
	SyncCursor           string         `json:"sync_cursor,omitempty"`
	LastSuccessfulSyncAt *time.Time     `json:"last_successful_sync_at,omitempty"`
	LastErrorCode        string         `json:"last_error_code,omitempty"`
	LastErrorMessage     string         `json:"last_error_message,omitempty"`
	Metadata             map[string]any `json:"metadata"`
	ObservedAt           time.Time      `json:"observed_at"`
	UpdatedAt            time.Time      `json:"updated_at"`
}

TenancyConnectorState stores observed health and provider metadata for a connector.

func NormalizeTenancyConnectorStateForWrite

func NormalizeTenancyConnectorStateForWrite(state TenancyConnectorState) (TenancyConnectorState, error)

NormalizeTenancyConnectorStateForWrite validates and canonicalizes connector health state.

type TenancyConnectorWithState

type TenancyConnectorWithState struct {
	Connector TenancyConnector      `json:"connector"`
	State     TenancyConnectorState `json:"state"`
}

TenancyConnectorWithState returns a connector with its latest persisted state.

type TenancyOrganization

type TenancyOrganization struct {
	TenantID    string    `json:"tenant_id"`
	DisplayName string    `json:"display_name"`
	Slug        string    `json:"slug"`
	CreatedAt   time.Time `json:"created_at"`
	UpdatedAt   time.Time `json:"updated_at"`
}

TenancyOrganization stores one tenant root metadata record.

func NormalizeTenancyOrganizationForWrite

func NormalizeTenancyOrganizationForWrite(organization TenancyOrganization) (TenancyOrganization, error)

NormalizeTenancyOrganizationForWrite validates and canonicalizes organization metadata.

type TenancyProject

type TenancyProject struct {
	TenantID    string     `json:"tenant_id"`
	WorkspaceID string     `json:"workspace_id"`
	ProjectID   string     `json:"project_id"`
	Name        string     `json:"name"`
	Slug        string     `json:"slug"`
	Description string     `json:"description,omitempty"`
	ArchivedAt  *time.Time `json:"archived_at,omitempty"`
	CreatedAt   time.Time  `json:"created_at"`
	UpdatedAt   time.Time  `json:"updated_at"`
}

TenancyProject stores one project metadata record.

func NormalizeTenancyProjectForWrite

func NormalizeTenancyProjectForWrite(project TenancyProject) (TenancyProject, error)

NormalizeTenancyProjectForWrite validates and canonicalizes project metadata.

type TenancyScanPolicy

type TenancyScanPolicy struct {
	TenantID           string                 `json:"tenant_id"`
	WorkspaceID        string                 `json:"workspace_id"`
	ProjectID          string                 `json:"project_id"`
	PolicyID           string                 `json:"policy_id"`
	Name               string                 `json:"name"`
	Enabled            bool                   `json:"enabled"`
	TriggerMode        domain.ScanTriggerMode `json:"trigger_mode"`
	Cron               string                 `json:"cron,omitempty"`
	MaxConcurrentScans int                    `json:"max_concurrent_scans"`
	HistoryLimit       int                    `json:"history_limit"`
	MaxFindings        int                    `json:"max_findings"`
	LastScheduledAt    *time.Time             `json:"last_scheduled_at,omitempty"`
	CreatedAt          time.Time              `json:"created_at"`
	UpdatedAt          time.Time              `json:"updated_at"`
}

TenancyScanPolicy stores one project-scoped automation policy record.

func NormalizeTenancyScanPolicyForWrite

func NormalizeTenancyScanPolicyForWrite(policy TenancyScanPolicy) (TenancyScanPolicy, error)

NormalizeTenancyScanPolicyForWrite validates and canonicalizes project scan policies.

type TenancyWorkspace

type TenancyWorkspace struct {
	TenantID    string     `json:"tenant_id"`
	WorkspaceID string     `json:"workspace_id"`
	DisplayName string     `json:"display_name"`
	Slug        string     `json:"slug"`
	Status      string     `json:"status,omitempty"`
	SuspendedAt *time.Time `json:"suspended_at,omitempty"`
	DeletedAt   *time.Time `json:"deleted_at,omitempty"`
	CreatedAt   time.Time  `json:"created_at"`
	UpdatedAt   time.Time  `json:"updated_at"`
}

TenancyWorkspace stores one workspace metadata record.

func NormalizeTenancyWorkspaceForWrite

func NormalizeTenancyWorkspaceForWrite(workspace TenancyWorkspace) (TenancyWorkspace, error)

NormalizeTenancyWorkspaceForWrite validates and canonicalizes workspace metadata.

type TenancyWorkspaceMember

type TenancyWorkspaceMember struct {
	TenantID    string    `json:"tenant_id"`
	WorkspaceID string    `json:"workspace_id"`
	MemberID    string    `json:"member_id"`
	UserID      string    `json:"user_id"`
	UserUUID    string    `json:"user_uuid,omitempty"`
	Email       string    `json:"email,omitempty"`
	Role        string    `json:"role"`
	Status      string    `json:"status"`
	JoinedAt    time.Time `json:"joined_at"`
	UpdatedAt   time.Time `json:"updated_at"`
}

TenancyWorkspaceMember stores one workspace member assignment.

func NormalizeTenancyWorkspaceMemberForWrite

func NormalizeTenancyWorkspaceMemberForWrite(member TenancyWorkspaceMember) (TenancyWorkspaceMember, error)

NormalizeTenancyWorkspaceMemberForWrite validates and canonicalizes workspace members.

type User

type User struct {
	ID           string     `json:"id"`
	PrimaryEmail string     `json:"primary_email"`
	DisplayName  string     `json:"display_name,omitempty"`
	AvatarURL    string     `json:"avatar_url,omitempty"`
	Status       string     `json:"status"`
	CreatedAt    time.Time  `json:"created_at"`
	UpdatedAt    time.Time  `json:"updated_at"`
	DeletedAt    *time.Time `json:"deleted_at,omitempty"`
}

User stores one human account independent of provider identities.

func NormalizeUserForWrite

func NormalizeUserForWrite(user User) (User, error)

NormalizeUserForWrite validates and canonicalizes one account row.

type UserDataExport added in v1.0.2

type UserDataExport struct {
	ID                string     `json:"id"`
	UserID            string     `json:"user_id"`
	Status            string     `json:"status"`
	BundlePath        string     `json:"bundle_path,omitempty"`
	BundleSizeBytes   int64      `json:"bundle_size_bytes,omitempty"`
	BundleSHA256      string     `json:"bundle_sha256,omitempty"`
	ErrorMessage      string     `json:"error_message,omitempty"`
	RequestedAt       time.Time  `json:"requested_at"`
	StartedAt         *time.Time `json:"started_at,omitempty"`
	CompletedAt       *time.Time `json:"completed_at,omitempty"`
	DownloadExpiresAt *time.Time `json:"download_expires_at,omitempty"`
	PurgeAfter        *time.Time `json:"purge_after,omitempty"`
	PurgedAt          *time.Time `json:"purged_at,omitempty"`
}

UserDataExport tracks one self-serve "Download my data" job for #1421. Bundles live on disk / object storage at BundlePath; the row holds the metadata and lifecycle timestamps. The signed-download URL the API issues is HMAC-signed by the server's session key, so no token material is persisted on the row.

type UserIdentity

type UserIdentity struct {
	ID                  string          `json:"id"`
	UserID              string          `json:"user_id"`
	Provider            string          `json:"provider"`
	Subject             string          `json:"subject"`
	Email               string          `json:"email,omitempty"`
	EmailVerified       bool            `json:"email_verified"`
	RawClaims           json.RawMessage `json:"raw_claims,omitempty"`
	LastAuthenticatedAt time.Time       `json:"last_authenticated_at"`
	CreatedAt           time.Time       `json:"created_at"`
}

UserIdentity links one external identity provider subject to a user.

func NormalizeUserIdentityForWrite

func NormalizeUserIdentityForWrite(identity UserIdentity) (UserIdentity, error)

NormalizeUserIdentityForWrite validates and canonicalizes one provider identity row.

type VerifiedDomain

type VerifiedDomain struct {
	ID                 string     `json:"id"`
	OrgID              string     `json:"org_id"`
	Domain             string     `json:"domain"`
	VerificationToken  string     `json:"verification_token"`
	VerificationMethod string     `json:"verification_method"`
	VerifiedAt         *time.Time `json:"verified_at,omitempty"`
	CreatedAt          time.Time  `json:"created_at"`
}

VerifiedDomain stores one organization domain-verification scaffold.

func NormalizeVerifiedDomainForWrite

func NormalizeVerifiedDomainForWrite(domain VerifiedDomain) (VerifiedDomain, error)

NormalizeVerifiedDomainForWrite validates and canonicalizes one domain-verification scaffold.

type WebhookEvent

type WebhookEvent struct {
	Provider   string    `json:"provider"`
	EventID    string    `json:"event_id"`
	EventType  string    `json:"event_type,omitempty"`
	ReceivedAt time.Time `json:"received_at"`
}

WebhookEvent is the persisted idempotency record for one provider-issued webhook delivery. (Provider, EventID) is unique. The row carries a status so concurrent deliveries of the same event are handled correctly: the first delivery claims the row ("processing") and applies side effects; only once it finishes ("processed") does a duplicate get a no-op success. A duplicate that arrives while the first is still in flight must be told to retry, never acknowledged — otherwise the provider could stop retrying before the side effects are durably applied. The row is recorded only after signature validation so an attacker cannot poison the table.

type WebhookEventStatus

type WebhookEventStatus string

WebhookEventStatus is the result of BeginWebhookEvent. Claimed/Processing are transient outcomes for the caller; only Processed authorizes a no-op acknowledgement of a duplicate.

const (
	// WebhookEventClaimed means this delivery won the insert (or reclaimed a
	// stale in-flight row) and must apply the side effects, then call
	// CompleteWebhookEvent.
	WebhookEventClaimed WebhookEventStatus = "claimed"
	// WebhookEventProcessing means another delivery of the same event is
	// still in flight. The caller must NOT acknowledge success; it should
	// return a retryable response so the provider redelivers later.
	WebhookEventProcessing WebhookEventStatus = "processing"
	// WebhookEventProcessed means the event was already fully handled. The
	// caller returns a successful no-op without reapplying side effects.
	WebhookEventProcessed WebhookEventStatus = "processed"
)

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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