Files
tenant-registry/internal/store/postgres.go
T
sharangandSharang Parnerkar c6de35858e
ci / shared (push) Successful in 12s
ci / test (push) Successful in 6m30s
ci / image (push) Successful in 38s
feat(connections): connect two workspaces by code (#138) (#145)
## What

- **Codes:** two workspaces connect by code. One administrator creates a code; another workspace's administrator enters it, and the two are connected at once. Each side sees only the other's display name.
- **Ending:** either side can end a connection. Archiving a workspace ends all of its connections. When a workspace is purged, the other side keeps the ended connection under the name it knew.
- **Product routes:** products (Prüfwerk's supplier SBOM releases first) list a tenant's active connections and check one before each delivery, under a new route group `connections.read`.

## Why

Closes #138. This is phase 4 of platform/pruefwerk#1028. Prüfwerk's agent is on stage and already calls the two internal routes; without them the release screen warns that connections can't be read (see the comment on #138).

Linked milestone: **n/a** (Prüfwerk #1028, phase 4)

## How

**Routes:**

| Call | Group | Answer |
|---|---|---|
| `POST /v1/tenants/{id}/connection-invites` | tenants.write | `201 {id, code, created_at, expires_at}`; the code is in this answer only |
| `GET /v1/tenants/{id}/connection-invites` | tenants.read | open codes, without the codes |
| `DELETE /v1/tenants/{id}/connection-invites/{invite}` | tenants.write | `204`, withdraws an unused code |
| `POST /v1/tenants/{id}/connections` `{code}` | tenants.write | `201 {id, peer_name, state, created_at, ended_by_us}` |
| `GET /v1/tenants/{id}/connections` | tenants.read | `{items: [...]}`, newest first |
| `POST /v1/tenants/{id}/connections/{connection}/end` | tenants.write | `200`; ending one that has ended answers it unchanged |
| `GET /v1/internal/tenants/{id}/connections?state=active` | **connections.read** | `{items: [{id, peer_tenant_id, peer_name}]}`; 404 for an unknown tenant |
| `GET /v1/internal/connections/{connection}` | **connections.read** | `{active, tenant_ids}`; 404 for an unknown id |

The two internal answers match what `compliance-agent/src/registry.rs` reads. A test pins the `items` key, because the agent defaults a missing key to "no connections".

**Codes:**
- 160 random bits (`crypto/rand`), shown as eight groups of four base32 letters.
- Stored as SHA-256 only, looked up by hash; case, spaces and dashes don't matter.
- Valid for 14 days, single use, at most 20 open per workspace.
- Every code that doesn't work gets the same 404 `invalid_code`: unknown, used, expired, withdrawn, the workspace's own, or either workspace archived.
- 409 `already_connected` when the two are connected already; the code then stays open.
- Entering codes is limited to 20 per hour per workspace, and per person when the call names one (`keyRateLimiter` now takes its limit as an argument; CI licences keep theirs). A call from the portal's own client that names nobody has only the workspace limit. Otherwise every workspace would share one limit through that client. **portal#201 must send `X-Portal-User-Subject`.**

**Redeeming** is one transaction. `SELECT … FOR UPDATE` on the code, insert the connection, then mark the code used. A partial unique index allows at most one connection per pair of workspaces that hasn't ended. A race test has two workspaces enter one code at the same time: exactly one connects.

**Active** is derived on every read: not ended, both workspaces exist, and neither is archived. So no delivery can go to an archived workspace, even if writing the end failed.

**Ending on archive:** every status change passes through `syncTenantStatus`, which now ends an archived workspace's connections. The admin purge calls the same step again before `DeleteTenant`, as a safety net. The foreign keys are `ON DELETE SET NULL`, with name snapshots, so the other side keeps its history.

**Audit:** `connection.invite_created`, `connection.invite_withdrawn`, `connection.created` and `connection.ended` go into both workspaces' logs.
- The acting side's entry names the actor.
- The other side's entry is a system entry with `by: peer`: no person, IP or user agent, only the connection id and the acting side's display name.
- Ends caused by archiving carry `reason: tenant_archived`.

**Product routes refuse user tokens** (403 `FORBIDDEN_CLIENT`), whatever groups the token's client holds, because they carry the peer's tenant id.

**Who may:** user tokens need IT_ADMIN or OWNER in their own workspace (the existing team gate, `IsTenantAdmin`). Another workspace's administrator gets a 404. The portal calls as its service client, naming the person in `X-Portal-User-*`.

**Side fix:** the Postgres `GetTenant` now answers a non-UUID id as not found (404), as the memory store does. It was a 500, which the new internal route hit.

## Test plan

- [x] Unit tests: route groups in `authz_test`, roles and cross-tenant scoping in `connections_scope_test`, and the OpenAPI contract cases.
- [x] Integration tests on memory **and Postgres (testcontainers)** in `connections_test.go`, run locally:
  - connect, list, product view, check, and the re-connect after end;
  - every invalid code gives the same answer, including expiry with an injected clock;
  - archive, then purge;
  - unknown ids;
  - the rate limit;
  - the redeem race.
- [x] The whole `internal/server` suite runs against Postgres locally (`go test -count=1 ./internal/server/`, 236 s, green). `-race` is green on the connection tests. `go vet` and `golangci-lint` v2.12.2: 0 issues.
- [ ] Playwright e2e: n/a, there's no UI here (portal#201).
- [ ] Manual smoke on stage after deploy, once `AUTHZ_RULES` carries the grant below. Prüfwerk's release screen should then show no warning.

## Risk

**Blast radius:** new tables and routes only. Existing routes change in two small ways: the `GetTenant` 500→404 for non-UUID ids, and the archive path now also ends connections.

**What could break:**
- **Migration number:** `0032` is also used by the open onprem PRs (#142/#143, `0032_werkpilot_description`). Whichever merges second must renumber. A duplicate version fails the migrations test loudly. I didn't pick 0033, because golang-migrate would silently skip a 0032 that merges after it.
- **Deployment grant:** the new group needs a grant in stage and prod `AUTHZ_RULES`. That config isn't in this repo: `pruefwerk-svc-stage:…,connections.read`, and the same for prod. Until it's added, Prüfwerk keeps getting 403.

**Rollback plan:** revert the PR and redeploy. The down migration drops both tables.

## Decided (2026-11-20, by the product owner)

- **Archived only** ends connections. A `halted` workspace keeps them, so a returning customer finds them again. Active stays false while a side is archived.
- **IT_ADMIN or OWNER** may create, enter and end, using the existing team gate rather than a new catalogue right.

## Open points for review

1. **Retention:** a purged workspace's display name stays visible to its former peers through the name snapshot, with no time limit. Should it be dropped after a while?
2. **Additions to the sketch:** the create answer now carries the invite `id`, which the withdraw route needs, and there's a list of open codes, without the codes.

## Checklist

- [x] Docs updated: the OpenAPI spec and the package doc in `connections.go` (no separate docs page for registry routes)
- [x] Audit events emitted for state changes
- [x] Secrets via Infisical, never in repo (none involved)
- [x] Migration is forward-only (new tables; down drops them)
- [x] Tenant scoping enforced on every DB query
- [x] OpenAPI spec updated
- [ ] `featureFlags.evaluate()`: n/a (nothing toggleable)
- [ ] CHANGELOG entry: n/a (generated by git-cliff on release)

🤖 Generated with [Claude Code](https://claude.com/claude-code)

https://claude.ai/code/session_01Q9inRcu428A2iNjDHPEAT9
Co-authored-by: Sharang Parnerkar <30073382+mighty840@users.noreply.github.com>
Reviewed-on: #145
2026-11-20 08:54:44 +00:00

758 lines
24 KiB
Go

package store
import (
"context"
"encoding/json"
"errors"
"fmt"
"strings"
"time"
"github.com/jackc/pgerrcode"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
"github.com/jackc/pgx/v5/pgxpool"
"git.breakpilot.com/platform/tenant-registry/internal/telemetry"
)
// Postgres — pgxpool-backed Store. The schema this expects is produced by
// the migrations/ package (M4.1 forward).
type Postgres struct {
pool *pgxpool.Pool
}
// NewPostgres opens a pool and pings. Caller must Close().
func NewPostgres(ctx context.Context, dsn string) (*Postgres, error) {
cfg, err := pgxpool.ParseConfig(dsn)
if err != nil {
return nil, fmt.Errorf("parse dsn: %w", err)
}
cfg.MaxConns = 20
cfg.MinConns = 2
cfg.MaxConnLifetime = time.Hour
cfg.ConnConfig.Tracer = telemetry.QueryTracer{} // spans only inside a traced request
pool, err := pgxpool.NewWithConfig(ctx, cfg)
if err != nil {
return nil, fmt.Errorf("create pool: %w", err)
}
if err := pool.Ping(ctx); err != nil {
pool.Close()
return nil, fmt.Errorf("ping: %w", err)
}
return &Postgres{pool: pool}, nil
}
func (p *Postgres) Close() { p.pool.Close() }
func (p *Postgres) Ping(ctx context.Context) error { return p.pool.Ping(ctx) }
// isUniqueViolation detects Postgres unique_violation (23505) so callers
// can return ErrConflict cleanly.
func isUniqueViolation(err error) bool {
var pgErr *pgconn.PgError
return errors.As(err, &pgErr) && pgErr.Code == pgerrcode.UniqueViolation
}
// isCheckViolation detects check_constraint_violation (23514) — used by the
// slug regex check + plan/status enum guards.
func isCheckViolation(err error) bool {
var pgErr *pgconn.PgError
return errors.As(err, &pgErr) && pgErr.Code == pgerrcode.CheckViolation
}
// ─── tenants ──────────────────────────────────────────────────────────────
const tenantSelect = `
SELECT id::text, slug, name, status::text, kind::text, plan,
COALESCE(erp_customer_id,''), COALESCE(stripe_cust_id,''),
trial_ends_at, contract_start, contract_end, COALESCE(sales_owner,''),
COALESCE(admin_email,''), status_changed_at, created_at, updated_at
FROM tenants `
func scanTenant(row pgx.Row) (*Tenant, error) {
var t Tenant
var trialEnds, cStart, cEnd *time.Time
err := row.Scan(
&t.ID, &t.Slug, &t.Name, &t.Status, &t.Kind, &t.Plan,
&t.ErpCustomerID, &t.StripeCustID,
&trialEnds, &cStart, &cEnd, &t.SalesOwner,
&t.AdminEmail, &t.StatusChangedAt, &t.CreatedAt, &t.UpdatedAt,
)
if errors.Is(err, pgx.ErrNoRows) {
return nil, ErrNotFound
}
if err != nil {
return nil, err
}
t.TrialEndsAt = trialEnds
t.ContractStart = cStart
t.ContractEnd = cEnd
return &t, nil
}
func (p *Postgres) CreateTenant(ctx context.Context, in TenantCreate) (*Tenant, error) {
kind := firstNonEmpty(in.Kind, "customer")
plan := firstNonEmpty(in.Plan, "starter")
// Default status = 'trial'; set trial_ends_at = NOW() + 14 days so the
// portal's trial banner has a real countdown to render. Demo tenants
// (kind=demo) get status='demo' and no trial_ends_at — that's set by
// the M13.2 demo provisioning path.
row := p.pool.QueryRow(ctx,
`INSERT INTO tenants (slug, name, kind, plan, status, sales_owner, trial_ends_at, admin_email)
VALUES (
$1, $2, $3::tenant_kind, $4,
CASE WHEN $3::tenant_kind = 'demo' THEN 'demo'::tenant_status
ELSE 'trial'::tenant_status END,
NULLIF($5, ''),
CASE WHEN $3::tenant_kind = 'demo' THEN NULL
ELSE NOW() + INTERVAL '14 days' END,
NULLIF($6, '')
)
RETURNING id::text, slug, name, status::text, kind::text, plan,
COALESCE(erp_customer_id,''), COALESCE(stripe_cust_id,''),
trial_ends_at, contract_start, contract_end, COALESCE(sales_owner,''),
COALESCE(admin_email,''), status_changed_at, created_at, updated_at`,
in.Slug, in.Name, kind, plan, in.SalesOwner, in.AdminEmail,
)
t, err := scanTenant(row)
if err != nil {
if isUniqueViolation(err) {
return nil, ErrConflict
}
if isCheckViolation(err) {
return nil, ErrInvalidInput
}
return nil, fmt.Errorf("create tenant: %w", err)
}
return t, nil
}
func (p *Postgres) GetTenant(ctx context.Context, id string) (*Tenant, error) {
t, err := scanTenant(p.pool.QueryRow(ctx, tenantSelect+`WHERE id = $1::uuid`, id))
if isInvalidUUID(err) {
// Not a tenant id at all: unknown, as in the memory store.
return nil, ErrNotFound
}
return t, err
}
func (p *Postgres) GetTenantBySlug(ctx context.Context, slug string) (*Tenant, error) {
return scanTenant(p.pool.QueryRow(ctx, tenantSelect+`WHERE slug = $1`, slug))
}
func (p *Postgres) GetTenantByErpCustomerID(ctx context.Context, erpCustomerID string) (*Tenant, error) {
if erpCustomerID == "" {
return nil, ErrNotFound
}
return scanTenant(p.pool.QueryRow(ctx, tenantSelect+`WHERE erp_customer_id = $1`, erpCustomerID))
}
func (p *Postgres) UpdateTenant(ctx context.Context, id string, in TenantUpdate) (*Tenant, error) {
// Build a partial UPDATE via COALESCE on each nullable input. Reads each
// field once; trivially type-safe.
row := p.pool.QueryRow(ctx, `
UPDATE tenants SET
status = COALESCE($2::tenant_status, status),
plan = COALESCE($3, plan),
erp_customer_id = COALESCE($4, erp_customer_id),
stripe_cust_id = COALESCE($5, stripe_cust_id),
trial_ends_at = COALESCE($6, trial_ends_at),
contract_start = COALESCE($7, contract_start),
contract_end = COALESCE($8, contract_end),
sales_owner = COALESCE($9, sales_owner),
admin_email = COALESCE($10, admin_email)
WHERE id = $1::uuid
RETURNING id::text, slug, name, status::text, kind::text, plan,
COALESCE(erp_customer_id,''), COALESCE(stripe_cust_id,''),
trial_ends_at, contract_start, contract_end, COALESCE(sales_owner,''),
COALESCE(admin_email,''), status_changed_at, created_at, updated_at`,
id,
nullableStr(in.Status), nullableStr(in.Plan),
nullableStr(in.ErpCustomerID), nullableStr(in.StripeCustID),
nullableTime(in.TrialEndsAt), nullableTime(in.ContractStart), nullableTime(in.ContractEnd),
nullableStr(in.SalesOwner), nullableStr(in.AdminEmail),
)
t, err := scanTenant(row)
if err != nil {
if isCheckViolation(err) {
return nil, ErrInvalidInput
}
return nil, err
}
return t, nil
}
// ─── entitlements ─────────────────────────────────────────────────────────
func (p *Postgres) UpsertTenantProduct(ctx context.Context, tp TenantProduct) (*TenantProduct, error) {
cfg, err := json.Marshal(tp.Config)
if err != nil {
return nil, fmt.Errorf("marshal config: %w", err)
}
if cfg == nil || string(cfg) == "null" {
cfg = []byte("{}")
}
row := p.pool.QueryRow(ctx, `
INSERT INTO tenant_products (tenant_id, product, enabled, config, expires_at)
VALUES ($1::uuid, $2, $3, $4::jsonb, $5)
ON CONFLICT (tenant_id, product) DO UPDATE SET
enabled = EXCLUDED.enabled,
config = EXCLUDED.config,
expires_at = EXCLUDED.expires_at,
-- a real booking ends a preview grant (its expiry must never cut
-- off a paid entitlement)
preview = FALSE,
preview_expires_at = NULL
RETURNING `+tenantProductCols,
tp.TenantID, tp.Product, tp.Enabled, cfg, tp.ExpiresAt,
)
out, err := scanTenantProduct(row)
if err != nil {
// FK violation on tenant_id → not found
var pgErr *pgconn.PgError
if errors.As(err, &pgErr) && pgErr.Code == pgerrcode.ForeignKeyViolation {
return nil, ErrNotFound
}
return nil, err
}
return out, nil
}
const tenantProductCols = `tenant_id::text, product, enabled, config, expires_at, preview, preview_expires_at, created_at, updated_at`
func scanTenantProduct(row pgx.Row) (*TenantProduct, error) {
var tp TenantProduct
var rawCfg []byte
if err := row.Scan(&tp.TenantID, &tp.Product, &tp.Enabled, &rawCfg, &tp.ExpiresAt, &tp.Preview, &tp.PreviewExpiresAt, &tp.CreatedAt, &tp.UpdatedAt); err != nil {
return nil, err
}
if err := json.Unmarshal(rawCfg, &tp.Config); err != nil || tp.Config == nil {
tp.Config = map[string]interface{}{}
}
return &tp, nil
}
func (p *Postgres) SetPreviewGrant(ctx context.Context, tenantID, product string, expiresAt time.Time) (*TenantProduct, error) {
tp, err := scanTenantProduct(p.pool.QueryRow(ctx, `
INSERT INTO tenant_products (tenant_id, product, enabled, config, preview, preview_expires_at)
VALUES ($1::uuid, $2, TRUE, '{}'::jsonb, TRUE, $3)
ON CONFLICT (tenant_id, product) DO UPDATE SET
enabled = TRUE, preview = TRUE, preview_expires_at = EXCLUDED.preview_expires_at
WHERE tenant_products.preview OR NOT tenant_products.enabled
RETURNING `+tenantProductCols, tenantID, product, expiresAt))
if errors.Is(err, pgx.ErrNoRows) {
return nil, ErrConflict // really booked: the WHERE refused the update
}
var pgErr *pgconn.PgError
if errors.As(err, &pgErr) && (pgErr.Code == pgerrcode.ForeignKeyViolation || pgErr.Code == pgerrcode.InvalidTextRepresentation) {
return nil, ErrNotFound
}
return tp, err
}
func (p *Postgres) RevokePreviewGrant(ctx context.Context, tenantID, product string) error {
tag, err := p.pool.Exec(ctx, `DELETE FROM tenant_products WHERE tenant_id = $1::uuid AND product = $2 AND preview`, tenantID, product)
if err != nil {
var pgErr *pgconn.PgError
if errors.As(err, &pgErr) && pgErr.Code == pgerrcode.InvalidTextRepresentation {
return ErrNotFound
}
return err
}
if tag.RowsAffected() == 0 {
return ErrNotFound
}
return nil
}
func (p *Postgres) ListTenantProducts(ctx context.Context, tenantID string) ([]TenantProduct, error) {
// First confirm tenant exists so we can return ErrNotFound consistent with Memory.
if _, err := p.GetTenant(ctx, tenantID); err != nil {
return nil, err
}
rows, err := p.pool.Query(ctx, `
SELECT `+tenantProductCols+`
FROM tenant_products WHERE tenant_id = $1::uuid ORDER BY product`, tenantID)
if err != nil {
return nil, err
}
defer rows.Close()
out := []TenantProduct{}
for rows.Next() {
tp, err := scanTenantProduct(rows)
if err != nil {
return nil, err
}
out = append(out, *tp)
}
return out, rows.Err()
}
// ─── api keys ─────────────────────────────────────────────────────────────
func (p *Postgres) CreateAPIKey(ctx context.Context, in APIKeyCreate) (*APIKey, error) {
var product, createdBy, hash, holder any
if in.Product != "" {
product = in.Product
}
if in.CreatedBy != "" {
createdBy = in.CreatedBy
}
if in.Hash != "" {
hash = in.Hash
}
if in.Holder != "" {
holder = in.Holder
}
kind := in.Kind
if kind == "" {
kind = APIKeyKindUser
}
// Coerce nil to an empty slice — the schema's NOT NULL DEFAULT only
// fires when the column is omitted, not when an explicit NULL is sent.
scopes := in.Scopes
if scopes == nil {
scopes = []string{}
}
row := p.pool.QueryRow(ctx, `
INSERT INTO api_keys (tenant_id, product, name, scopes, hash, hash_sha256, prefix, kind, holder, expires_at, created_by)
VALUES ($1::uuid, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11)
RETURNING `+apiKeyCols,
in.TenantID, product, in.Name, scopes, hash, in.HashSHA256, in.Prefix, kind, holder, in.ExpiresAt, createdBy,
)
k, err := scanAPIKey(row)
if err != nil {
if isUniqueViolation(err) {
return nil, ErrConflict
}
var pgErr *pgconn.PgError
if errors.As(err, &pgErr) && pgErr.Code == pgerrcode.ForeignKeyViolation {
return nil, ErrNotFound
}
return nil, err
}
return k, nil
}
// apiKeyCols is the column list scanAPIKey reads, in order.
const apiKeyCols = `id::text, tenant_id::text, COALESCE(product,''), name, scopes, prefix,
kind, COALESCE(holder,''), expires_at, COALESCE(created_by,''), last_used_at, revoked_at, created_at`
func scanAPIKey(row pgx.Row, extra ...any) (*APIKey, error) {
var k APIKey
dest := append([]any{&k.ID, &k.TenantID, &k.Product, &k.Name, &k.Scopes, &k.Prefix,
&k.Kind, &k.Holder, &k.ExpiresAt, &k.CreatedBy, &k.LastUsedAt, &k.RevokedAt, &k.CreatedAt}, extra...)
err := row.Scan(dest...)
if errors.Is(err, pgx.ErrNoRows) {
return nil, ErrNotFound
}
if err != nil {
return nil, err
}
return &k, nil
}
func (p *Postgres) FindAPIKeyBySHA256(ctx context.Context, sum []byte) (*APIKey, error) {
return scanAPIKey(p.pool.QueryRow(ctx, `
SELECT `+apiKeyCols+` FROM api_keys WHERE hash_sha256 = $1 AND revoked_at IS NULL`, sum))
}
func (p *Postgres) FindAPIKeysByPrefix(ctx context.Context, prefix string) ([]APIKeyCandidate, error) {
rows, err := p.pool.Query(ctx, `
SELECT `+apiKeyCols+`, hash FROM api_keys
WHERE prefix = $1 AND revoked_at IS NULL AND hash IS NOT NULL`, prefix)
if err != nil {
return nil, err
}
defer rows.Close()
var out []APIKeyCandidate
for rows.Next() {
var hash string
k, err := scanAPIKey(rows, &hash)
if err != nil {
return nil, err
}
out = append(out, APIKeyCandidate{APIKey: *k, Hash: hash})
}
return out, rows.Err()
}
func (p *Postgres) TouchAPIKeyUsed(ctx context.Context, id string) error {
tag, err := p.pool.Exec(ctx, `UPDATE api_keys SET last_used_at = NOW() WHERE id = $1::uuid`, id)
if err != nil {
return err
}
if tag.RowsAffected() == 0 {
return ErrNotFound
}
return nil
}
func (p *Postgres) RevokeAPIKey(ctx context.Context, id, tenantID string) error {
tag, err := p.pool.Exec(ctx, `
UPDATE api_keys SET revoked_at = NOW()
WHERE id = $1::uuid AND revoked_at IS NULL AND ($2 = '' OR tenant_id::text = $2)`, id, tenantID)
if err != nil {
return err
}
if tag.RowsAffected() == 0 {
return ErrNotFound
}
return nil
}
func (p *Postgres) ListAPIKeys(ctx context.Context, tenantID string) ([]APIKey, error) {
if _, err := p.GetTenant(ctx, tenantID); err != nil {
return nil, err
}
rows, err := p.pool.Query(ctx, `
SELECT `+apiKeyCols+` FROM api_keys WHERE tenant_id = $1::uuid ORDER BY created_at DESC`, tenantID)
if err != nil {
return nil, err
}
defer rows.Close()
out := []APIKey{}
for rows.Next() {
k, err := scanAPIKey(rows)
if err != nil {
return nil, err
}
out = append(out, *k)
}
return out, rows.Err()
}
// ─── audit ────────────────────────────────────────────────────────────────
func (p *Postgres) AppendAudit(ctx context.Context, ev AuditEvent) (*AuditEvent, error) {
meta, _ := json.Marshal(ev.Metadata)
if meta == nil || string(meta) == "null" {
meta = []byte("{}")
}
row := p.pool.QueryRow(ctx, `
INSERT INTO audit_log
(tenant_id, project_id, actor_id, actor_name, actor_type, action,
target_id, target_type, target_name, product, metadata, source_ip, user_agent)
VALUES
(NULLIF($1,'')::uuid, NULLIF($2,'')::uuid, NULLIF($3,''), NULLIF($4,''), NULLIF($5,''), $6,
NULLIF($7,''), NULLIF($8,''), NULLIF($9,''), NULLIF($10,''), $11::jsonb,
NULLIF($12,'')::inet, NULLIF($13,''))
RETURNING id, COALESCE(tenant_id::text,''), COALESCE(project_id::text,''),
COALESCE(actor_id,''), COALESCE(actor_name,''), COALESCE(actor_type,''),
action, COALESCE(target_id,''), COALESCE(target_type,''), COALESCE(target_name,''),
COALESCE(product,''), metadata, COALESCE(host(source_ip),''), COALESCE(user_agent,''),
created_at`,
ev.TenantID, ev.ProjectID, ev.ActorID, ev.ActorName, ev.ActorType, ev.Action,
ev.TargetID, ev.TargetType, ev.TargetName, ev.Product, meta, ev.SourceIP, ev.UserAgent,
)
out, err := scanAudit(row)
if err != nil {
return nil, err
}
return out, nil
}
func scanAudit(row pgx.Row) (*AuditEvent, error) {
var ev AuditEvent
var rawMeta []byte
err := row.Scan(
&ev.ID, &ev.TenantID, &ev.ProjectID,
&ev.ActorID, &ev.ActorName, &ev.ActorType,
&ev.Action, &ev.TargetID, &ev.TargetType, &ev.TargetName,
&ev.Product, &rawMeta, &ev.SourceIP, &ev.UserAgent,
&ev.CreatedAt,
)
if errors.Is(err, pgx.ErrNoRows) {
return nil, ErrNotFound
}
if err != nil {
return nil, err
}
if len(rawMeta) > 0 {
if err := json.Unmarshal(rawMeta, &ev.Metadata); err != nil {
ev.Metadata = map[string]interface{}{}
}
}
return &ev, nil
}
func (p *Postgres) ListAudit(ctx context.Context, f AuditFilter) ([]AuditEvent, int64, error) {
limit := f.Limit
if limit <= 0 || limit > 500 {
limit = 100
}
// Build WHERE clauses dynamically — keep param indices stable.
where := []string{"id > $1"}
args := []any{f.Cursor}
add := func(clause string, v any) {
args = append(args, v)
where = append(where, fmt.Sprintf(clause, len(args)))
}
if f.TenantID != "" {
add("tenant_id = $%d::uuid", f.TenantID)
}
if f.Product != "" {
add("product = $%d", f.Product)
}
if f.ActorID != "" {
add("actor_id = $%d", f.ActorID)
}
if f.Action != "" {
add("action = $%d", f.Action)
}
if f.Since != nil {
add("created_at >= $%d", *f.Since)
}
if f.Until != nil {
add("created_at <= $%d", *f.Until)
}
args = append(args, limit)
sql := `
SELECT id, COALESCE(tenant_id::text,''), COALESCE(project_id::text,''),
COALESCE(actor_id,''), COALESCE(actor_name,''), COALESCE(actor_type,''),
action, COALESCE(target_id,''), COALESCE(target_type,''), COALESCE(target_name,''),
COALESCE(product,''), metadata, COALESCE(host(source_ip),''), COALESCE(user_agent,''),
created_at
FROM audit_log
WHERE ` + strings.Join(where, " AND ") + `
ORDER BY id ASC
LIMIT $` + fmt.Sprintf("%d", len(args))
rows, err := p.pool.Query(ctx, sql, args...)
if err != nil {
return nil, 0, err
}
defer rows.Close()
out := []AuditEvent{}
for rows.Next() {
ev, err := scanAudit(rows)
if err != nil {
return nil, 0, err
}
out = append(out, *ev)
}
if err := rows.Err(); err != nil {
return nil, 0, err
}
var nextCursor int64
if len(out) == limit && len(out) > 0 {
nextCursor = out[len(out)-1].ID
}
return out, nextCursor, nil
}
func nullableStr(p *string) any {
if p == nil {
return nil
}
return *p
}
func nullableTime(p *time.Time) any {
if p == nil {
return nil
}
return *p
}
// ─── tenant listing ───────────────────────────────────────────────────────
func (p *Postgres) ListTenants(ctx context.Context, f TenantFilter) ([]Tenant, string, error) {
limit := f.Limit
if limit <= 0 || limit > 500 {
limit = 100
}
cAt, cID, ok := decodeTenantCursor(f.Cursor)
if !ok {
return nil, "", ErrInvalidInput
}
where := []string{"TRUE"}
args := []any{}
add := func(clause string, v any) {
args = append(args, v)
where = append(where, fmt.Sprintf(clause, len(args)))
}
if f.Status != "" {
add("status = $%d::tenant_status", f.Status)
}
if f.Kind != "" {
add("kind = $%d::tenant_kind", f.Kind)
}
if q := strings.TrimSpace(f.Query); q != "" {
args = append(args, "%"+likeEscape(q)+"%")
n := len(args)
where = append(where, fmt.Sprintf("(slug ILIKE $%d OR name ILIKE $%d OR COALESCE(admin_email, '') ILIKE $%d)", n, n, n))
}
if f.Cursor != "" {
args = append(args, cAt, cID)
where = append(where, fmt.Sprintf("(created_at, id::text) > ($%d, $%d)", len(args)-1, len(args)))
}
args = append(args, limit+1)
rows, err := p.pool.Query(ctx, tenantSelect+`WHERE `+strings.Join(where, " AND ")+
` ORDER BY created_at, id LIMIT $`+fmt.Sprintf("%d", len(args)), args...)
if err != nil {
return nil, "", err
}
defer rows.Close()
out := []Tenant{}
for rows.Next() {
t, err := scanTenant(rows)
if err != nil {
return nil, "", err
}
out = append(out, *t)
}
if err := rows.Err(); err != nil {
return nil, "", err
}
next := ""
if len(out) > limit {
out = out[:limit]
next = encodeTenantCursor(out[len(out)-1])
}
return out, next, nil
}
// ─── products ─────────────────────────────────────────────────────────────
const productSelect = `
SELECT key, name, description, type, launch_urls, provision_urls, skus, addons,
plans_required, supports_trial, trial_days, enabled, sort_order, created_at, updated_at
FROM products `
func scanProduct(row pgx.Row) (*Product, error) {
var pr Product
var launch, prov, skus, addons []byte
err := row.Scan(&pr.Key, &pr.Name, &pr.Description, &pr.Type, &launch, &prov, &skus, &addons,
&pr.PlansRequired, &pr.SupportsTrial, &pr.TrialDays, &pr.Enabled, &pr.SortOrder, &pr.CreatedAt, &pr.UpdatedAt)
if errors.Is(err, pgx.ErrNoRows) {
return nil, ErrNotFound
}
if err != nil {
return nil, err
}
_ = json.Unmarshal(launch, &pr.LaunchURLs)
_ = json.Unmarshal(prov, &pr.ProvisionURLs)
_ = json.Unmarshal(skus, &pr.SKUs)
_ = json.Unmarshal(addons, &pr.Addons)
if pr.LaunchURLs == nil {
pr.LaunchURLs = map[string]string{}
}
if pr.ProvisionURLs == nil {
pr.ProvisionURLs = map[string]string{}
}
if pr.SKUs == nil {
pr.SKUs = []string{}
}
if pr.Addons == nil {
pr.Addons = []ProductAddon{}
}
if pr.PlansRequired == nil {
pr.PlansRequired = []string{}
}
return &pr, nil
}
func (p *Postgres) ListProducts(ctx context.Context, includeDisabled bool) ([]Product, error) {
q := productSelect
if !includeDisabled {
q += `WHERE enabled `
}
rows, err := p.pool.Query(ctx, q+`ORDER BY sort_order, key`)
if err != nil {
return nil, err
}
defer rows.Close()
out := []Product{}
for rows.Next() {
pr, err := scanProduct(rows)
if err != nil {
return nil, err
}
out = append(out, *pr)
}
return out, rows.Err()
}
func (p *Postgres) GetProduct(ctx context.Context, key string) (*Product, error) {
return scanProduct(p.pool.QueryRow(ctx, productSelect+`WHERE key = $1`, key))
}
// likeEscape escapes the LIKE wildcards in user input (the default escape is \).
func likeEscape(s string) string {
return strings.NewReplacer(`\`, `\\`, `%`, `\%`, `_`, `\_`).Replace(s)
}
func (p *Postgres) TenantActivity(ctx context.Context, tenantIDs []string, since time.Time) (map[string]TenantActivity, error) {
out := map[string]TenantActivity{}
if len(tenantIDs) == 0 {
return out, nil
}
get := func(id string) TenantActivity {
a, ok := out[id]
if !ok {
a = TenantActivity{Usage: map[string]float64{}}
}
return a
}
rows, err := p.pool.Query(ctx, `
SELECT tenant_id::text, metric, SUM(quantity)
FROM usage_events
WHERE tenant_id::text = ANY($1) AND occurred_at >= $2
GROUP BY tenant_id, metric`, tenantIDs, since)
if err != nil {
return nil, err
}
for rows.Next() {
var id, metric string
var total float64
if err := rows.Scan(&id, &metric, &total); err != nil {
rows.Close()
return nil, err
}
a := get(id)
a.Usage[metric] = total
out[id] = a
}
rows.Close()
if err := rows.Err(); err != nil {
return nil, err
}
rows, err = p.pool.Query(ctx, `
SELECT tenant_id::text, MAX(created_at)
FROM audit_log
WHERE tenant_id::text = ANY($1)
GROUP BY tenant_id`, tenantIDs)
if err != nil {
return nil, err
}
defer rows.Close()
for rows.Next() {
var id string
var at time.Time
if err := rows.Scan(&id, &at); err != nil {
return nil, err
}
a := get(id)
a.LastActivityAt = &at
out[id] = a
}
return out, rows.Err()
}
// DeleteTenant implements Store. The foreign keys do the rest: every table
// that belongs to a tenant cascades, audit_log keeps its rows (SET NULL);
// intake_reports refuses (RESTRICT, 0030): security reports outlive it.
func (p *Postgres) DeleteTenant(ctx context.Context, id string) error {
tag, err := p.pool.Exec(ctx, `DELETE FROM tenants WHERE id = $1`, id)
var pgErr *pgconn.PgError
if errors.As(err, &pgErr) && pgErr.Code == pgerrcode.ForeignKeyViolation {
return ErrConflict
}
if err != nil {
return err
}
if tag.RowsAffected() == 0 {
return ErrNotFound
}
return nil
}