Files

369 lines
14 KiB
Go

package store
import (
"context"
"errors"
"fmt"
"strings"
"time"
"github.com/jackc/pgx/v5/pgconn"
"github.com/jmoiron/sqlx"
)
var (
// ErrNotFound means the requested row does not exist.
ErrNotFound = errors.New("not found")
// ErrAlreadyExists means a unique constraint rejected the insert.
ErrAlreadyExists = errors.New("already exists")
// ErrLastOwner means a membership or lifecycle change would leave an org without an active owner.
ErrLastOwner = errors.New("last active owner")
// ErrVersionConflict means the row changed after the caller read it.
ErrVersionConflict = errors.New("version conflict")
// ErrSetupComplete means the instance already has a registered owner account.
ErrSetupComplete = errors.New("setup complete")
// ErrCredentialRejected means presented credentials were invalid, locked, or inactive.
ErrCredentialRejected = errors.New("credential rejected")
// ErrIdentityInactive means the identity's lifecycle is not active.
ErrIdentityInactive = errors.New("identity inactive")
)
func isUniqueViolation(err error) bool {
pgerr, ok := errors.AsType[*pgconn.PgError](err)
return ok && pgerr.Code == "23505"
}
func isForeignKeyViolation(err error) bool {
pgerr, ok := errors.AsType[*pgconn.PgError](err)
return ok && pgerr.Code == "23503"
}
func (s *Store) withTx(ctx context.Context, fn func(*sqlx.Tx) error) error {
tx, err := s.db.BeginTxx(ctx, nil)
if err != nil {
return err
}
defer func() { _ = tx.Rollback() }()
if err := fn(tx); err != nil {
return err
}
return tx.Commit()
}
// PolicyRow is a stored Cedar policy in governance.access_policies.
type PolicyRow struct {
Level string `db:"level"`
OrgID string `db:"org_id"`
WorkspaceID string `db:"workspace_id"`
ObjectKind string `db:"object_kind"`
ObjectID string `db:"object_id"`
PolicyID string `db:"policy_id"`
Text string `db:"text"`
UpdatedAt time.Time `db:"updated_at"`
}
// DecisionRow is a coalesced authorisation decision in governance.access_decisions.
type DecisionRow struct {
ID int64 `db:"id"`
OrgID string `db:"org_id"`
Principal string `db:"principal"`
Action string `db:"action"`
ResourceKind string `db:"resource_kind"`
ResourceID string `db:"resource_id"`
Outcome string `db:"outcome"`
Level string `db:"level"`
Policies []string `db:"policies"`
MinuteAt time.Time `db:"minute_at"`
Count int64 `db:"count"`
CreatedAt time.Time `db:"created_at"`
UpdatedAt time.Time `db:"updated_at"`
}
func policyLockKey(p PolicyRow) string {
joined := strings.Join([]string{p.Level, p.OrgID, p.WorkspaceID, p.ObjectKind, p.ObjectID, p.PolicyID}, "/")
return strings.Trim(joined, "/")
}
func bumpPolicyRevision(ctx context.Context, tx *sqlx.Tx) error {
if _, err := tx.ExecContext(ctx, `
INSERT INTO governance.access_policy_revision (only_row, version) VALUES (true, 1)
ON CONFLICT (only_row)
DO UPDATE SET version = governance.access_policy_revision.version + 1, updated_at = now()`); err != nil {
return fmt.Errorf("bump access policy revision: %w", err)
}
return nil
}
func cleanEmptyPolicyVersion(ctx context.Context, tx *sqlx.Tx, level, orgID, wsID string) error {
_, err := tx.ExecContext(ctx, `
DELETE FROM governance.access_policy_versions v
WHERE v.level = $1 AND v.org_id = $2 AND v.workspace_id = $3
AND NOT EXISTS (
SELECT 1 FROM governance.access_policies p
WHERE p.level = v.level AND p.org_id = v.org_id AND p.workspace_id = v.workspace_id
)`, level, orgID, wsID)
return err
}
// ListAccessPolicies returns stored policies visible to scopeOrg (or all when nil).
func (s *Store) ListAccessPolicies(ctx context.Context, scopeOrg *string, instanceScope bool) ([]PolicyRow, error) {
var out []PolicyRow
if err := s.db.SelectContext(ctx, &out, `
SELECT level, org_id, workspace_id, object_kind, object_id, policy_id, text, updated_at
FROM governance.access_policies
WHERE $1::text IS NULL
OR (level = 'instance' AND $2::bool)
OR (level <> 'instance' AND org_id = $1::text)
ORDER BY level, org_id, workspace_id, object_kind, object_id, policy_id`, scopeOrg, instanceScope); err != nil {
return nil, fmt.Errorf("list access policies: %w", err)
}
return out, nil
}
// AccessPolicyRevision returns the instance-wide monotonic policy revision.
func (s *Store) AccessPolicyRevision(ctx context.Context) (int64, error) {
var version int64
if err := s.db.GetContext(ctx, &version, `SELECT version FROM governance.access_policy_revision`); err != nil {
return 0, fmt.Errorf("read access policy revision: %w", err)
}
return version, nil
}
// PutAccessPolicy upserts p, bumps its scope version and the instance revision in one transaction.
func (s *Store) PutAccessPolicy(ctx context.Context, p PolicyRow) (int64, error) {
var version int64
err := s.withTx(ctx, func(tx *sqlx.Tx) error {
if _, err := tx.ExecContext(ctx, `SELECT pg_advisory_xact_lock(hashtextextended($1, 0))`, policyLockKey(p)); err != nil {
return err
}
if _, err := tx.ExecContext(ctx, `
INSERT INTO governance.access_policies (level, org_id, workspace_id, object_kind, object_id, policy_id, text)
VALUES ($1, $2, $3, $4, $5, $6, $7)
ON CONFLICT (level, org_id, workspace_id, object_kind, object_id, policy_id)
DO UPDATE SET text = EXCLUDED.text, updated_at = now()`,
p.Level, p.OrgID, p.WorkspaceID, p.ObjectKind, p.ObjectID, p.PolicyID, p.Text); err != nil {
return err
}
if err := tx.GetContext(ctx, &version, `
INSERT INTO governance.access_policy_versions (level, org_id, workspace_id, version)
VALUES ($1, $2, $3, 2)
ON CONFLICT (level, org_id, workspace_id)
DO UPDATE SET version = governance.access_policy_versions.version + 1, updated_at = now()
RETURNING version`, p.Level, p.OrgID, p.WorkspaceID); err != nil {
return err
}
return bumpPolicyRevision(ctx, tx)
})
if err != nil {
return 0, fmt.Errorf("put access policy: %w", err)
}
return version, nil
}
// DeleteAccessPolicy removes one policy; found is false when absent.
func (s *Store) DeleteAccessPolicy(ctx context.Context, p PolicyRow) (found bool, err error) {
err = s.withTx(ctx, func(tx *sqlx.Tx) error {
if _, err := tx.ExecContext(ctx, `SELECT pg_advisory_xact_lock(hashtextextended($1, 0))`, policyLockKey(p)); err != nil {
return err
}
res, err := tx.ExecContext(ctx, `
DELETE FROM governance.access_policies
WHERE level = $1 AND org_id = $2 AND workspace_id = $3
AND object_kind = $4 AND object_id = $5 AND policy_id = $6`,
p.Level, p.OrgID, p.WorkspaceID, p.ObjectKind, p.ObjectID, p.PolicyID)
if err != nil {
return err
}
n, err := res.RowsAffected()
if err != nil || n == 0 {
return err
}
found = true
if _, err := tx.ExecContext(ctx, `
INSERT INTO governance.access_policy_versions (level, org_id, workspace_id, version)
VALUES ($1, $2, $3, 2)
ON CONFLICT (level, org_id, workspace_id)
DO UPDATE SET version = governance.access_policy_versions.version + 1, updated_at = now()`,
p.Level, p.OrgID, p.WorkspaceID); err != nil {
return err
}
if err := cleanEmptyPolicyVersion(ctx, tx, p.Level, p.OrgID, p.WorkspaceID); err != nil {
return err
}
return bumpPolicyRevision(ctx, tx)
})
if err != nil {
return false, fmt.Errorf("delete access policy: %w", err)
}
return found, nil
}
// SeedOrgPolicies stores an org's initial policies, unless the org already has
// any of them.
//
// The check and the writes share one transaction, and the lock is taken before
// the check, so a second seed waits for the first to commit and then finds its
// rows: it writes nothing, and an edit or a deletion made in between stands.
func (s *Store) SeedOrgPolicies(ctx context.Context, orgID string, shippedIDs []string, rows []PolicyRow) error {
if len(rows) == 0 {
return nil
}
err := s.withTx(ctx, func(tx *sqlx.Tx) error {
if _, err := tx.ExecContext(ctx, `SELECT pg_advisory_xact_lock(hashtextextended($1, 0))`, seedLockKey(orgID)); err != nil {
return err
}
var present int64
if err := tx.GetContext(ctx, &present, `
SELECT count(*) FROM governance.access_policies
WHERE level = 'org' AND org_id = $1 AND policy_id = ANY($2::text[])`,
orgID, shippedIDs); err != nil {
return err
}
if present > 0 {
return nil
}
for _, p := range rows {
if _, err := tx.ExecContext(ctx, `
INSERT INTO governance.access_policies (level, org_id, workspace_id, object_kind, object_id, policy_id, text)
VALUES ($1, $2, $3, $4, $5, $6, $7)
ON CONFLICT (level, org_id, workspace_id, object_kind, object_id, policy_id)
DO UPDATE SET text = EXCLUDED.text, updated_at = now()`,
p.Level, p.OrgID, p.WorkspaceID, p.ObjectKind, p.ObjectID, p.PolicyID, p.Text); err != nil {
return err
}
}
// One version for the whole seed: a reader sees none of the policies or
// all of them.
first := rows[0]
if _, err := tx.ExecContext(ctx, `
INSERT INTO governance.access_policy_versions (level, org_id, workspace_id, version)
VALUES ($1, $2, $3, 2)
ON CONFLICT (level, org_id, workspace_id)
DO UPDATE SET version = governance.access_policy_versions.version + 1, updated_at = now()`,
first.Level, first.OrgID, first.WorkspaceID); err != nil {
return err
}
return bumpPolicyRevision(ctx, tx)
})
if err != nil {
return fmt.Errorf("seed org policies: %w", err)
}
return nil
}
// seedLockKey is the advisory lock key a seed takes before it reads whether the
// org has policies, distinct from the per-policy keys.
func seedLockKey(orgID string) string { return "seed/" + orgID }
// DeleteOrgPoliciesNotShipped removes non-shipped org policies and bumps revision.
func (s *Store) DeleteOrgPoliciesNotShipped(ctx context.Context, orgID string, shippedIDs []string) error {
return s.withTx(ctx, func(tx *sqlx.Tx) error {
if _, err := tx.ExecContext(ctx, `
DELETE FROM governance.access_policies
WHERE level = 'org' AND org_id = $1 AND NOT (policy_id = ANY($2::text[]))`,
orgID, shippedIDs); err != nil {
return err
}
if err := cleanEmptyPolicyVersion(ctx, tx, "org", orgID, ""); err != nil {
return err
}
return bumpPolicyRevision(ctx, tx)
})
}
// ResetInstancePolicies deletes every stored instance-level policy and bumps revision.
func (s *Store) ResetInstancePolicies(ctx context.Context) error {
return s.withTx(ctx, func(tx *sqlx.Tx) error {
if _, err := tx.ExecContext(ctx, `DELETE FROM governance.access_policies WHERE level = 'instance'`); err != nil {
return err
}
if err := cleanEmptyPolicyVersion(ctx, tx, "instance", "", ""); err != nil {
return err
}
return bumpPolicyRevision(ctx, tx)
})
}
// RecordDecision stores or increments a per-minute coalesced access decision.
func (s *Store) RecordDecision(ctx context.Context, d DecisionRow) error {
policies := d.Policies
if policies == nil {
policies = []string{}
}
if _, err := s.db.ExecContext(ctx, `
INSERT INTO governance.access_decisions (org_id, principal, action, resource_kind, resource_id, outcome, level, policies)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8)
ON CONFLICT (org_id, principal, action, resource_kind, resource_id, outcome, level, policies, minute_at)
DO UPDATE SET count = governance.access_decisions.count + 1, updated_at = now()`,
d.OrgID, d.Principal, d.Action, d.ResourceKind, d.ResourceID, d.Outcome, d.Level, policies); err != nil {
return fmt.Errorf("record decision: %w", err)
}
return nil
}
// ListDecisions returns an org's most recent decisions, newest first.
func (s *Store) ListDecisions(ctx context.Context, orgID string, limit int) ([]DecisionRow, error) {
var out []DecisionRow
if err := s.db.SelectContext(ctx, &out, `
SELECT id, org_id, principal, action, resource_kind, resource_id, outcome, level, policies, minute_at, count, created_at, updated_at
FROM governance.access_decisions WHERE org_id = $1 ORDER BY id DESC LIMIT $2`, orgID, limit); err != nil {
return nil, fmt.Errorf("list decisions: %w", err)
}
return out, nil
}
// DecisionFilter narrows SearchDecisions. A zero field matches everything.
type DecisionFilter struct {
OrgID string
Principal string
Action string
ResourceKind string
Outcome string
Since, Until time.Time
Limit int
Offset int
}
// SearchDecisions returns an org's decisions matching f, newest first.
func (s *Store) SearchDecisions(ctx context.Context, f DecisionFilter) ([]DecisionRow, error) {
var out []DecisionRow
if err := s.db.SelectContext(ctx, &out, `
SELECT id, org_id, principal, action, resource_kind, resource_id, outcome, level, policies, minute_at, count, created_at, updated_at
FROM governance.access_decisions
WHERE org_id = $1
AND ($2 = '' OR principal = $2)
AND ($3 = '' OR action = $3)
AND ($4 = '' OR resource_kind = $4)
AND ($5 = '' OR outcome = $5)
AND ($6::timestamptz IS NULL OR created_at >= $6)
AND ($7::timestamptz IS NULL OR created_at < $7)
ORDER BY id DESC LIMIT $8 OFFSET $9`,
f.OrgID, f.Principal, f.Action, f.ResourceKind, f.Outcome, nullTime(f.Since), nullTime(f.Until), f.Limit, f.Offset); err != nil {
return nil, fmt.Errorf("search decisions: %w", err)
}
return out, nil
}
func nullTime(t time.Time) *time.Time {
if t.IsZero() {
return nil
}
return &t
}
// PruneDecisions deletes up to batch decision rows created before cutoff.
func (s *Store) PruneDecisions(ctx context.Context, cutoff time.Time, batch int) (int64, error) {
res, err := s.db.ExecContext(ctx, `
DELETE FROM governance.access_decisions
WHERE id IN (
SELECT id FROM governance.access_decisions
WHERE created_at < $1
ORDER BY created_at
LIMIT $2
)`, cutoff.UTC(), batch)
if err != nil {
return 0, fmt.Errorf("prune decisions: %w", err)
}
return res.RowsAffected()
}