## 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
695 lines
18 KiB
Go
695 lines
18 KiB
Go
package store
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"slices"
|
|
"sort"
|
|
"strings"
|
|
"sync"
|
|
"time"
|
|
|
|
"github.com/google/uuid"
|
|
)
|
|
|
|
// Memory — in-process Store used when DATABASE_URL is empty. Convenient for
|
|
// local dev when you don't want to bring up Postgres + run migrations.
|
|
// Pre-seeded with the acme tenant.
|
|
type Memory struct {
|
|
mu sync.RWMutex
|
|
tenants map[string]*Tenant // id → tenant
|
|
bySlug map[string]string // slug → id
|
|
products map[string]map[string]*TenantProduct // tenant_id → product → row
|
|
apiKeys map[string]*apiKeyWithHash // id → key
|
|
audit []*AuditEvent
|
|
auditID int64
|
|
catalog []Product
|
|
|
|
// M-MIG-7
|
|
subs map[string]*Subscription // id → row
|
|
usage []*UsageEvent
|
|
usageKey map[string]int64 // idempotency key → id
|
|
usageID int64
|
|
outbox []*OutboxItem
|
|
outboxID int64
|
|
receipts map[string]time.Time
|
|
licences map[string]*Licence
|
|
|
|
documents map[string]*Document
|
|
projects map[string]*Project
|
|
offers map[string]*TrialOffer
|
|
services map[string]*ManagedService
|
|
preparations map[string]*Preparation // document id → delivered prepared version (0022)
|
|
assets map[string]*StoreAsset // tenant_id + "/" + sha256 (0022)
|
|
profiles map[string]*CompanyProfile // tenant_id → current
|
|
profRevs map[string][]CompanyProfile // tenant_id → every revision
|
|
roleSets map[string][]RoleDataset // tenant_id → every revision, oldest first (0024)
|
|
mail []*MailItem
|
|
mailID int64
|
|
|
|
prodSets map[string]*TenantProductSettings // tenant_id + "/" + product (0025)
|
|
|
|
contractDocs []ContractDocument // every row, oldest first (0027)
|
|
|
|
intakeReports []IntakeReport // every report, oldest first (0028)
|
|
intakeEntries []IntakeEntry // every entry with its receipts, oldest first
|
|
intakeCounters map[string]int // tenant_id → last seq
|
|
intakeEntryID int64
|
|
contractDocID int64
|
|
|
|
capRequests []CapabilityRequest // pending four-eyes grants, oldest first (0029)
|
|
|
|
connInvites []ConnectionInvite // connection codes, oldest first (0032)
|
|
connections []Connection // stored sides, snapshot names and end; oldest first (0032)
|
|
|
|
moduleDays map[moduleDayKey]int // Managed Git daily counts (0031)
|
|
moduleSeen map[moduleSeenKey]time.Time // licence users per month (0031) → first seen
|
|
}
|
|
|
|
type apiKeyWithHash struct {
|
|
APIKey
|
|
Hash string
|
|
HashSHA256 []byte
|
|
}
|
|
|
|
// NewMemory returns a fresh in-memory store with the seed acme tenant.
|
|
func NewMemory() *Memory {
|
|
m := &Memory{
|
|
tenants: make(map[string]*Tenant),
|
|
bySlug: make(map[string]string),
|
|
products: make(map[string]map[string]*TenantProduct),
|
|
apiKeys: make(map[string]*apiKeyWithHash),
|
|
catalog: DefaultProducts(),
|
|
subs: make(map[string]*Subscription),
|
|
usageKey: make(map[string]int64),
|
|
receipts: make(map[string]time.Time),
|
|
licences: make(map[string]*Licence),
|
|
projects: make(map[string]*Project),
|
|
offers: make(map[string]*TrialOffer),
|
|
services: make(map[string]*ManagedService),
|
|
profiles: make(map[string]*CompanyProfile),
|
|
preparations: make(map[string]*Preparation),
|
|
assets: make(map[string]*StoreAsset),
|
|
profRevs: make(map[string][]CompanyProfile),
|
|
roleSets: make(map[string][]RoleDataset),
|
|
intakeCounters: make(map[string]int),
|
|
|
|
documents: make(map[string]*Document),
|
|
prodSets: make(map[string]*TenantProductSettings),
|
|
|
|
moduleDays: make(map[moduleDayKey]int),
|
|
moduleSeen: make(map[moduleSeenKey]time.Time),
|
|
}
|
|
now := time.Now().UTC()
|
|
seed := &Tenant{
|
|
ID: "00000000-0000-0000-0000-000000000001",
|
|
Slug: "acme",
|
|
Name: "Acme Inc.",
|
|
Status: "active",
|
|
Kind: "customer",
|
|
Plan: "professional",
|
|
StatusChangedAt: now,
|
|
CreatedAt: now,
|
|
UpdatedAt: now,
|
|
}
|
|
m.tenants[seed.ID] = seed
|
|
m.bySlug[seed.Slug] = seed.ID
|
|
m.products[seed.ID] = map[string]*TenantProduct{
|
|
"pruefwerk": {TenantID: seed.ID, Product: "pruefwerk", Enabled: true, Config: map[string]interface{}{"runners": float64(1)}, CreatedAt: now, UpdatedAt: now},
|
|
"firmwerk": {TenantID: seed.ID, Product: "firmwerk", Enabled: true, Config: map[string]interface{}{}, CreatedAt: now, UpdatedAt: now},
|
|
}
|
|
return m
|
|
}
|
|
|
|
func (m *Memory) Close() {}
|
|
func (m *Memory) Ping(_ context.Context) error { return nil }
|
|
|
|
// ─── tenants ──────────────────────────────────────────────────────────────
|
|
|
|
func (m *Memory) CreateTenant(_ context.Context, in TenantCreate) (*Tenant, error) {
|
|
m.mu.Lock()
|
|
defer m.mu.Unlock()
|
|
if _, taken := m.bySlug[in.Slug]; taken {
|
|
return nil, ErrConflict
|
|
}
|
|
now := time.Now().UTC()
|
|
kind := firstNonEmpty(in.Kind, "customer")
|
|
status := "trial"
|
|
var trialEnds *time.Time
|
|
if kind == "demo" {
|
|
status = "demo"
|
|
} else {
|
|
end := now.Add(14 * 24 * time.Hour)
|
|
trialEnds = &end
|
|
}
|
|
t := &Tenant{
|
|
ID: uuid.NewString(),
|
|
Slug: in.Slug,
|
|
Name: in.Name,
|
|
Status: status,
|
|
Kind: kind,
|
|
Plan: firstNonEmpty(in.Plan, "starter"),
|
|
SalesOwner: in.SalesOwner,
|
|
AdminEmail: in.AdminEmail,
|
|
TrialEndsAt: trialEnds,
|
|
StatusChangedAt: now,
|
|
CreatedAt: now,
|
|
UpdatedAt: now,
|
|
}
|
|
m.tenants[t.ID] = t
|
|
m.bySlug[t.Slug] = t.ID
|
|
cp := *t
|
|
return &cp, nil
|
|
}
|
|
|
|
func (m *Memory) GetTenant(_ context.Context, id string) (*Tenant, error) {
|
|
m.mu.RLock()
|
|
defer m.mu.RUnlock()
|
|
t, ok := m.tenants[id]
|
|
if !ok {
|
|
return nil, ErrNotFound
|
|
}
|
|
cp := *t
|
|
return &cp, nil
|
|
}
|
|
|
|
func (m *Memory) GetTenantBySlug(_ context.Context, slug string) (*Tenant, error) {
|
|
m.mu.RLock()
|
|
defer m.mu.RUnlock()
|
|
id, ok := m.bySlug[slug]
|
|
if !ok {
|
|
return nil, ErrNotFound
|
|
}
|
|
t := m.tenants[id]
|
|
cp := *t
|
|
return &cp, nil
|
|
}
|
|
|
|
func (m *Memory) GetTenantByErpCustomerID(_ context.Context, erpCustomerID string) (*Tenant, error) {
|
|
m.mu.RLock()
|
|
defer m.mu.RUnlock()
|
|
if erpCustomerID == "" {
|
|
return nil, ErrNotFound
|
|
}
|
|
for _, t := range m.tenants {
|
|
if t.ErpCustomerID == erpCustomerID {
|
|
cp := *t
|
|
return &cp, nil
|
|
}
|
|
}
|
|
return nil, ErrNotFound
|
|
}
|
|
|
|
func (m *Memory) UpdateTenant(_ context.Context, id string, in TenantUpdate) (*Tenant, error) {
|
|
m.mu.Lock()
|
|
defer m.mu.Unlock()
|
|
t, ok := m.tenants[id]
|
|
if !ok {
|
|
return nil, ErrNotFound
|
|
}
|
|
if in.Status != nil {
|
|
if *in.Status != t.Status {
|
|
t.StatusChangedAt = time.Now().UTC()
|
|
}
|
|
t.Status = *in.Status
|
|
}
|
|
if in.Plan != nil {
|
|
t.Plan = *in.Plan
|
|
}
|
|
if in.ErpCustomerID != nil {
|
|
t.ErpCustomerID = *in.ErpCustomerID
|
|
}
|
|
if in.StripeCustID != nil {
|
|
t.StripeCustID = *in.StripeCustID
|
|
}
|
|
if in.TrialEndsAt != nil {
|
|
t.TrialEndsAt = in.TrialEndsAt
|
|
}
|
|
if in.ContractStart != nil {
|
|
t.ContractStart = in.ContractStart
|
|
}
|
|
if in.ContractEnd != nil {
|
|
t.ContractEnd = in.ContractEnd
|
|
}
|
|
if in.SalesOwner != nil {
|
|
t.SalesOwner = *in.SalesOwner
|
|
}
|
|
if in.AdminEmail != nil {
|
|
t.AdminEmail = *in.AdminEmail
|
|
}
|
|
t.UpdatedAt = time.Now().UTC()
|
|
cp := *t
|
|
return &cp, nil
|
|
}
|
|
|
|
func (m *Memory) ListTenants(_ context.Context, f TenantFilter) ([]Tenant, string, error) {
|
|
m.mu.RLock()
|
|
defer m.mu.RUnlock()
|
|
limit := f.Limit
|
|
if limit <= 0 || limit > 500 {
|
|
limit = 100
|
|
}
|
|
cAt, cID, ok := decodeTenantCursor(f.Cursor)
|
|
if !ok {
|
|
return nil, "", ErrInvalidInput
|
|
}
|
|
all := make([]Tenant, 0, len(m.tenants))
|
|
for _, t := range m.tenants {
|
|
if f.Status != "" && t.Status != f.Status {
|
|
continue
|
|
}
|
|
if f.Kind != "" && t.Kind != f.Kind {
|
|
continue
|
|
}
|
|
if q := strings.ToLower(strings.TrimSpace(f.Query)); q != "" &&
|
|
!strings.Contains(strings.ToLower(t.Slug), q) &&
|
|
!strings.Contains(strings.ToLower(t.Name), q) &&
|
|
!strings.Contains(strings.ToLower(t.AdminEmail), q) {
|
|
continue
|
|
}
|
|
// keyset: only rows strictly after (cAt, cID)
|
|
if f.Cursor != "" && t.CreatedAt.Before(cAt) || (f.Cursor != "" && t.CreatedAt.Equal(cAt) && t.ID <= cID) {
|
|
continue
|
|
}
|
|
all = append(all, *t)
|
|
}
|
|
sort.Slice(all, func(i, j int) bool {
|
|
if all[i].CreatedAt.Equal(all[j].CreatedAt) {
|
|
return all[i].ID < all[j].ID
|
|
}
|
|
return all[i].CreatedAt.Before(all[j].CreatedAt)
|
|
})
|
|
next := ""
|
|
if len(all) > limit {
|
|
all = all[:limit]
|
|
next = encodeTenantCursor(all[len(all)-1])
|
|
}
|
|
return all, next, nil
|
|
}
|
|
|
|
func (m *Memory) TenantActivity(_ context.Context, tenantIDs []string, since time.Time) (map[string]TenantActivity, error) {
|
|
m.mu.RLock()
|
|
defer m.mu.RUnlock()
|
|
want := map[string]bool{}
|
|
for _, id := range tenantIDs {
|
|
want[id] = true
|
|
}
|
|
out := map[string]TenantActivity{}
|
|
get := func(id string) TenantActivity {
|
|
a, ok := out[id]
|
|
if !ok {
|
|
a = TenantActivity{Usage: map[string]float64{}}
|
|
}
|
|
return a
|
|
}
|
|
for _, u := range m.usage {
|
|
if !want[u.TenantID] || u.OccurredAt.Before(since) {
|
|
continue
|
|
}
|
|
a := get(u.TenantID)
|
|
a.Usage[u.Metric] += u.Quantity
|
|
out[u.TenantID] = a
|
|
}
|
|
for _, ev := range m.audit {
|
|
if !want[ev.TenantID] {
|
|
continue
|
|
}
|
|
a := get(ev.TenantID)
|
|
if a.LastActivityAt == nil || ev.CreatedAt.After(*a.LastActivityAt) {
|
|
at := ev.CreatedAt
|
|
a.LastActivityAt = &at
|
|
}
|
|
out[ev.TenantID] = a
|
|
}
|
|
return out, nil
|
|
}
|
|
|
|
// ─── products ─────────────────────────────────────────────────────────────
|
|
|
|
func (m *Memory) ListProducts(_ context.Context, includeDisabled bool) ([]Product, error) {
|
|
m.mu.RLock()
|
|
defer m.mu.RUnlock()
|
|
out := make([]Product, 0, len(m.catalog))
|
|
for _, p := range m.catalog {
|
|
if p.Enabled || includeDisabled {
|
|
out = append(out, p)
|
|
}
|
|
}
|
|
sort.SliceStable(out, func(i, j int) bool { return out[i].SortOrder < out[j].SortOrder })
|
|
return out, nil
|
|
}
|
|
|
|
func (m *Memory) GetProduct(_ context.Context, key string) (*Product, error) {
|
|
m.mu.RLock()
|
|
defer m.mu.RUnlock()
|
|
for _, p := range m.catalog {
|
|
if p.Key == key {
|
|
cp := p
|
|
return &cp, nil
|
|
}
|
|
}
|
|
return nil, ErrNotFound
|
|
}
|
|
|
|
// ─── entitlements ─────────────────────────────────────────────────────────
|
|
|
|
func (m *Memory) UpsertTenantProduct(_ context.Context, tp TenantProduct) (*TenantProduct, error) {
|
|
m.mu.Lock()
|
|
defer m.mu.Unlock()
|
|
if _, ok := m.tenants[tp.TenantID]; !ok {
|
|
return nil, ErrNotFound
|
|
}
|
|
if _, ok := m.products[tp.TenantID]; !ok {
|
|
m.products[tp.TenantID] = map[string]*TenantProduct{}
|
|
}
|
|
now := time.Now().UTC()
|
|
stored, exists := m.products[tp.TenantID][tp.Product]
|
|
if !exists {
|
|
stored = &TenantProduct{
|
|
TenantID: tp.TenantID,
|
|
Product: tp.Product,
|
|
CreatedAt: now,
|
|
}
|
|
m.products[tp.TenantID][tp.Product] = stored
|
|
}
|
|
stored.Enabled = tp.Enabled
|
|
stored.Config = tp.Config
|
|
stored.ExpiresAt = tp.ExpiresAt
|
|
stored.Preview, stored.PreviewExpiresAt = false, nil // a real booking ends a preview
|
|
stored.UpdatedAt = now
|
|
cp := *stored
|
|
return &cp, nil
|
|
}
|
|
|
|
func (m *Memory) SetPreviewGrant(_ context.Context, tenantID, product string, expiresAt time.Time) (*TenantProduct, error) {
|
|
m.mu.Lock()
|
|
defer m.mu.Unlock()
|
|
if _, ok := m.tenants[tenantID]; !ok {
|
|
return nil, ErrNotFound
|
|
}
|
|
if _, ok := m.products[tenantID]; !ok {
|
|
m.products[tenantID] = map[string]*TenantProduct{}
|
|
}
|
|
now := time.Now().UTC()
|
|
stored, exists := m.products[tenantID][product]
|
|
if exists && stored.Enabled && !stored.Preview {
|
|
return nil, ErrConflict
|
|
}
|
|
if !exists {
|
|
stored = &TenantProduct{TenantID: tenantID, Product: product, Config: map[string]interface{}{}, CreatedAt: now}
|
|
m.products[tenantID][product] = stored
|
|
}
|
|
exp := expiresAt
|
|
stored.Enabled, stored.Preview, stored.PreviewExpiresAt, stored.UpdatedAt = true, true, &exp, now
|
|
cp := *stored
|
|
return &cp, nil
|
|
}
|
|
|
|
func (m *Memory) RevokePreviewGrant(_ context.Context, tenantID, product string) error {
|
|
m.mu.Lock()
|
|
defer m.mu.Unlock()
|
|
stored, ok := m.products[tenantID][product]
|
|
if !ok || !stored.Preview {
|
|
return ErrNotFound
|
|
}
|
|
delete(m.products[tenantID], product)
|
|
return nil
|
|
}
|
|
|
|
func (m *Memory) ListTenantProducts(_ context.Context, tenantID string) ([]TenantProduct, error) {
|
|
m.mu.RLock()
|
|
defer m.mu.RUnlock()
|
|
if _, ok := m.tenants[tenantID]; !ok {
|
|
return nil, ErrNotFound
|
|
}
|
|
out := make([]TenantProduct, 0, len(m.products[tenantID]))
|
|
for _, p := range m.products[tenantID] {
|
|
out = append(out, *p)
|
|
}
|
|
sort.Slice(out, func(i, j int) bool { return out[i].Product < out[j].Product })
|
|
return out, nil
|
|
}
|
|
|
|
// ─── api keys ─────────────────────────────────────────────────────────────
|
|
|
|
func (m *Memory) CreateAPIKey(_ context.Context, in APIKeyCreate) (*APIKey, error) {
|
|
m.mu.Lock()
|
|
defer m.mu.Unlock()
|
|
if _, ok := m.tenants[in.TenantID]; !ok {
|
|
return nil, ErrNotFound
|
|
}
|
|
for _, k := range m.apiKeys {
|
|
if k.TenantID == in.TenantID && k.Name == in.Name && k.RevokedAt == nil {
|
|
return nil, ErrConflict
|
|
}
|
|
if len(in.HashSHA256) > 0 && bytes.Equal(k.HashSHA256, in.HashSHA256) {
|
|
return nil, ErrConflict
|
|
}
|
|
}
|
|
kind := in.Kind
|
|
if kind == "" {
|
|
kind = APIKeyKindUser
|
|
}
|
|
now := time.Now().UTC()
|
|
k := &apiKeyWithHash{
|
|
APIKey: APIKey{
|
|
ID: uuid.NewString(),
|
|
TenantID: in.TenantID,
|
|
Product: in.Product,
|
|
Name: in.Name,
|
|
Scopes: append([]string{}, in.Scopes...),
|
|
Prefix: in.Prefix,
|
|
Kind: kind,
|
|
Holder: in.Holder,
|
|
ExpiresAt: in.ExpiresAt,
|
|
CreatedBy: in.CreatedBy,
|
|
CreatedAt: now,
|
|
},
|
|
Hash: in.Hash,
|
|
HashSHA256: append([]byte(nil), in.HashSHA256...),
|
|
}
|
|
m.apiKeys[k.ID] = k
|
|
cp := k.APIKey
|
|
return &cp, nil
|
|
}
|
|
|
|
func (m *Memory) FindAPIKeyBySHA256(_ context.Context, sum []byte) (*APIKey, error) {
|
|
m.mu.RLock()
|
|
defer m.mu.RUnlock()
|
|
for _, k := range m.apiKeys {
|
|
if k.RevokedAt == nil && len(k.HashSHA256) > 0 && bytes.Equal(k.HashSHA256, sum) {
|
|
cp := k.APIKey
|
|
return &cp, nil
|
|
}
|
|
}
|
|
return nil, ErrNotFound
|
|
}
|
|
|
|
func (m *Memory) FindAPIKeysByPrefix(_ context.Context, prefix string) ([]APIKeyCandidate, error) {
|
|
m.mu.RLock()
|
|
defer m.mu.RUnlock()
|
|
var out []APIKeyCandidate
|
|
for _, k := range m.apiKeys {
|
|
if k.Prefix == prefix && k.RevokedAt == nil && k.Hash != "" {
|
|
out = append(out, APIKeyCandidate{APIKey: k.APIKey, Hash: k.Hash})
|
|
}
|
|
}
|
|
return out, nil
|
|
}
|
|
|
|
func (m *Memory) TouchAPIKeyUsed(_ context.Context, id string) error {
|
|
m.mu.Lock()
|
|
defer m.mu.Unlock()
|
|
k, ok := m.apiKeys[id]
|
|
if !ok {
|
|
return ErrNotFound
|
|
}
|
|
now := time.Now().UTC()
|
|
k.LastUsedAt = &now
|
|
return nil
|
|
}
|
|
|
|
func (m *Memory) RevokeAPIKey(_ context.Context, id, tenantID string) error {
|
|
m.mu.Lock()
|
|
defer m.mu.Unlock()
|
|
k, ok := m.apiKeys[id]
|
|
if !ok || k.RevokedAt != nil || (tenantID != "" && k.TenantID != tenantID) {
|
|
return ErrNotFound
|
|
}
|
|
now := time.Now().UTC()
|
|
k.RevokedAt = &now
|
|
return nil
|
|
}
|
|
|
|
func (m *Memory) ListAPIKeys(_ context.Context, tenantID string) ([]APIKey, error) {
|
|
m.mu.RLock()
|
|
defer m.mu.RUnlock()
|
|
if _, ok := m.tenants[tenantID]; !ok {
|
|
return nil, ErrNotFound
|
|
}
|
|
out := []APIKey{}
|
|
for _, k := range m.apiKeys {
|
|
if k.TenantID == tenantID {
|
|
out = append(out, k.APIKey)
|
|
}
|
|
}
|
|
sort.Slice(out, func(i, j int) bool { return out[i].CreatedAt.After(out[j].CreatedAt) })
|
|
return out, nil
|
|
}
|
|
|
|
// ─── audit ────────────────────────────────────────────────────────────────
|
|
|
|
func (m *Memory) AppendAudit(_ context.Context, ev AuditEvent) (*AuditEvent, error) {
|
|
m.mu.Lock()
|
|
defer m.mu.Unlock()
|
|
m.auditID++
|
|
ev.ID = m.auditID
|
|
ev.CreatedAt = time.Now().UTC()
|
|
cp := ev
|
|
m.audit = append(m.audit, &cp)
|
|
out := ev
|
|
return &out, nil
|
|
}
|
|
|
|
func (m *Memory) ListAudit(_ context.Context, f AuditFilter) ([]AuditEvent, int64, error) {
|
|
m.mu.RLock()
|
|
defer m.mu.RUnlock()
|
|
limit := f.Limit
|
|
if limit <= 0 || limit > 500 {
|
|
limit = 100
|
|
}
|
|
matches := []AuditEvent{}
|
|
for _, ev := range m.audit {
|
|
if ev.ID <= f.Cursor {
|
|
continue
|
|
}
|
|
if f.TenantID != "" && ev.TenantID != f.TenantID {
|
|
continue
|
|
}
|
|
if f.Product != "" && ev.Product != f.Product {
|
|
continue
|
|
}
|
|
if f.ActorID != "" && ev.ActorID != f.ActorID {
|
|
continue
|
|
}
|
|
if f.Action != "" && ev.Action != f.Action {
|
|
continue
|
|
}
|
|
if f.Since != nil && ev.CreatedAt.Before(*f.Since) {
|
|
continue
|
|
}
|
|
if f.Until != nil && ev.CreatedAt.After(*f.Until) {
|
|
continue
|
|
}
|
|
matches = append(matches, *ev)
|
|
if len(matches) >= limit {
|
|
break
|
|
}
|
|
}
|
|
var nextCursor int64
|
|
if len(matches) == limit && len(matches) > 0 {
|
|
nextCursor = matches[len(matches)-1].ID
|
|
}
|
|
return matches, nextCursor, nil
|
|
}
|
|
|
|
func firstNonEmpty(values ...string) string {
|
|
for _, v := range values {
|
|
if v != "" {
|
|
return v
|
|
}
|
|
}
|
|
return ""
|
|
}
|
|
|
|
// DeleteTenant implements Store.
|
|
func (m *Memory) DeleteTenant(_ context.Context, id string) error {
|
|
m.mu.Lock()
|
|
defer m.mu.Unlock()
|
|
t, ok := m.tenants[id]
|
|
if !ok {
|
|
return ErrNotFound
|
|
}
|
|
if slices.ContainsFunc(m.intakeReports, func(r IntakeReport) bool { return r.TenantID == id }) {
|
|
return ErrConflict // security reports outlive the tenant (0030)
|
|
}
|
|
delete(m.tenants, id)
|
|
delete(m.bySlug, t.Slug)
|
|
delete(m.products, id)
|
|
for k, ps := range m.prodSets {
|
|
if ps.TenantID == id {
|
|
delete(m.prodSets, k)
|
|
}
|
|
}
|
|
kept := m.contractDocs[:0]
|
|
for _, d := range m.contractDocs {
|
|
if d.TenantID != id {
|
|
kept = append(kept, d)
|
|
}
|
|
}
|
|
m.contractDocs = kept
|
|
m.deleteIntake(id)
|
|
m.capRequests = slices.DeleteFunc(m.capRequests, func(r CapabilityRequest) bool { return r.TenantID == id })
|
|
m.deleteConnections(id)
|
|
m.deleteModuleUsers(id)
|
|
for kid, k := range m.apiKeys {
|
|
if k.TenantID == id {
|
|
delete(m.apiKeys, kid)
|
|
}
|
|
}
|
|
for sid, sub := range m.subs {
|
|
if sub.TenantID == id {
|
|
delete(m.subs, sid)
|
|
}
|
|
}
|
|
for lid, l := range m.licences {
|
|
if l.TenantID == id {
|
|
delete(m.licences, lid)
|
|
}
|
|
}
|
|
for did, d := range m.documents {
|
|
if d.TenantID == id {
|
|
delete(m.documents, did)
|
|
}
|
|
}
|
|
for pid, pr := range m.projects {
|
|
if pr.TenantID == id {
|
|
delete(m.projects, pid)
|
|
}
|
|
}
|
|
for sid, ms := range m.services {
|
|
if ms.TenantID == id {
|
|
delete(m.services, sid)
|
|
}
|
|
}
|
|
usage := m.usage[:0]
|
|
for _, u := range m.usage {
|
|
if u.TenantID != id {
|
|
usage = append(usage, u)
|
|
} else {
|
|
delete(m.usageKey, u.IdempotencyKey)
|
|
}
|
|
}
|
|
m.usage = usage
|
|
outbox := m.outbox[:0]
|
|
for _, o := range m.outbox {
|
|
if o.TenantID != id {
|
|
outbox = append(outbox, o)
|
|
}
|
|
}
|
|
m.outbox = outbox
|
|
mail := m.mail[:0]
|
|
for _, mi := range m.mail {
|
|
if mi.TenantID != id {
|
|
mail = append(mail, mi)
|
|
}
|
|
}
|
|
m.mail = mail
|
|
for _, a := range m.audit {
|
|
if a.TenantID == id {
|
|
a.TenantID = ""
|
|
}
|
|
}
|
|
return nil
|
|
}
|