Files
tenant-registry/internal/store/memory.go
T
Sharang ParnerkarandClaude Opus 5.5 7b9ae37be7 feat(store): module user counts and sealed git admin token (0031)
Migration 0031 adds managed_services.admin_token_enc (sealed, write-only),
module_user_days (Managed Git daily counts, month = peak day) and
module_users_seen (Werkpilot/Firmwerk people per month). Postgres and
Memory stores implement both.

Refs: t81

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 09:28:20 +01:00

691 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)
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.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
}