Files
tenant-registry/internal/store/store.go
T
sharangandSharang Parnerkar e0ae19f2a7
ci / shared (push) Successful in 11s
ci / test (push) Successful in 22m23s
ci / image (push) Successful in 24s
feat(licences): per-tenant LiteLLM key with a Werkpilot grant (#29)
Demonstration plan, phase D6 (registry side). A prospect trialling Werkpilot had no model access until someone created a LiteLLM key by hand. The registry issues one with the licence, scoped and budgeted per tenant.

**On issue** (`product=werkpilot`): `POST /key/generate` on LiteLLM with `key_alias = werkpilot-<slug>-<licence id>`, `metadata` carrying tenant id/slug/licence/product, the model list and the plan's budget (trial and default, USD per 30 days). LiteLLM's hashed token id goes on the `licences` row (migration `0007`, exposed as `llm_key_id` on `GET /v1/licences`); the `sk-…` secret is returned in that one response as `llm_api_key`, together with `llm_base_url`, and is never stored or returned again.

**On renewal** (licence heartbeat): the existing key moves to the new licence row rather than a second key being generated — the secret cannot be re-read, and the CLI still holds the one it stored.

**On revoke:** the key is deleted; a 404 from LiteLLM is treated as already gone. If the delete fails, the licence is still revoked and the key id stays on the row so it can be retried by hand.

**Failure is never fatal:** with `LITELLM_MASTER_KEY` unset, LiteLLM unreachable or refusing, the licence is issued anyway and the grant carries `warnings: ["llm_key_unavailable"]` with no LLM fields. Also, a key that cannot be persisted is deleted again rather than handed out un-revocable.

Config: `LITELLM_BASE_URL` (default `https://llm.breakpilot.com`), `LITELLM_MASTER_KEY`, `LITELLM_MODELS` (default `Qwen3-Coder-30B-A3B-Instruct,gpt-oss-120b`), `LITELLM_BUDGET_TRIAL` (5), `LITELLM_BUDGET_DEFAULT` (50). Startup logs whether provisioning is on.

Note the migration is numbered `0007`: `0006` is taken by the members PR (#28), which is independent of this one — merge order does not matter.

Verified locally: `go vet ./...`, `gofmt` clean, `go test ./...` green, CI coverage command at **74.4%** (gate 70%). `internal/llmkeys` is tested against an httptest fake; no live LiteLLM call was made.

Pairs with a `bp-licence` bump (the Rust `Grant` gains the optional fields) and with `LITELLM_MASTER_KEY` on `tenant-registry-stage`.

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

https://claude.ai/code/session_01DmXxNULoSNPvjF7buKipsB
Co-authored-by: Sharang Parnerkar <30073382+mighty840@users.noreply.github.com>
Reviewed-on: #29
2026-09-14 08:27:25 +00:00

131 lines
5.0 KiB
Go

// Package store hides the persistence layer behind a Store interface.
// Two implementations: Memory (dev convenience, used when DATABASE_URL is
// empty) and Postgres (production via pgx). Handlers depend on the
// interface — never on a concrete type.
package store
import (
"context"
"errors"
"time"
)
// Sentinel errors.
var (
ErrNotFound = errors.New("not found")
ErrConflict = errors.New("conflict")
ErrInvalidInput = errors.New("invalid input")
)
// TenantCreate is the input shape for Store.CreateTenant.
type TenantCreate struct {
Slug string
Name string
Plan string // optional, defaults to "starter"
Kind string // optional, defaults to "customer"
SalesOwner string // optional
AdminEmail string // optional — the first admin invited at creation
}
// TenantUpdate captures partial mutations. Nil fields are left untouched.
type TenantUpdate struct {
Status *string
Plan *string
ErpCustomerID *string
StripeCustID *string
TrialEndsAt *time.Time
ContractStart *time.Time
ContractEnd *time.Time
SalesOwner *string
AdminEmail *string
}
// APIKeyCreate is the input shape for Store.CreateAPIKey.
type APIKeyCreate struct {
TenantID string
Product string // empty = applies to all products
Name string
Scopes []string
Prefix string
Hash string // argon2id encoded
CreatedBy string
}
// AuditFilter narrows /v1/audit GET results.
type AuditFilter struct {
TenantID string
Product string
ActorID string
Action string
Since *time.Time
Until *time.Time
Limit int
Cursor int64 // id > Cursor (ascending) is the next page anchor
}
// Store is the persistence contract. Implementations:
// - Memory — in-process, used when DATABASE_URL is empty (dev convenience).
// - Postgres — pgxpool-backed, used in stage + prod.
type Store interface {
// Tenants
CreateTenant(ctx context.Context, in TenantCreate) (*Tenant, error)
GetTenant(ctx context.Context, id string) (*Tenant, error)
GetTenantBySlug(ctx context.Context, slug string) (*Tenant, error)
GetTenantByErpCustomerID(ctx context.Context, erpCustomerID string) (*Tenant, error)
UpdateTenant(ctx context.Context, id string, in TenantUpdate) (*Tenant, error)
ListTenants(ctx context.Context, f TenantFilter) ([]Tenant, string, error) // rows + next cursor ("" = none)
// Products (catalog)
ListProducts(ctx context.Context, includeDisabled bool) ([]Product, error)
GetProduct(ctx context.Context, key string) (*Product, error)
// Entitlements
UpsertTenantProduct(ctx context.Context, tp TenantProduct) (*TenantProduct, error)
ListTenantProducts(ctx context.Context, tenantID string) ([]TenantProduct, error)
// API keys
CreateAPIKey(ctx context.Context, in APIKeyCreate) (*APIKey, error)
FindAPIKeyByPrefix(ctx context.Context, prefix string) (*APIKey, string, error) // returns key + hash
TouchAPIKeyUsed(ctx context.Context, id string) error
RevokeAPIKey(ctx context.Context, id string) error
ListAPIKeys(ctx context.Context, tenantID string) ([]APIKey, error)
// Audit
AppendAudit(ctx context.Context, ev AuditEvent) (*AuditEvent, error)
ListAudit(ctx context.Context, f AuditFilter) ([]AuditEvent, int64, error) // returns rows + next cursor (0 = none)
// Subscriptions (M-MIG-7, mirrored from ERPNext Sales Orders)
UpsertSubscription(ctx context.Context, sub Subscription) (*Subscription, error) // key (tenant_id, sku, erp_sales_order)
ListSubscriptions(ctx context.Context, tenantID string) ([]Subscription, error)
// Usage events (§9.2). Inserted reports false when the idempotency key
// was already stored (the existing row is returned).
InsertUsageEvent(ctx context.Context, ev UsageEvent) (*UsageEvent, bool, error)
ListUsageEvents(ctx context.Context, f UsageFilter) ([]UsageEvent, error)
MarkUsageSynced(ctx context.Context, ids []int64, at time.Time) error
// ERP outbox. ClaimOutbox returns due rows (next_attempt_at <= now) and
// pushes their next_attempt_at by lease so a second worker skips them.
EnqueueOutbox(ctx context.Context, item OutboxItem) (*OutboxItem, error)
ClaimOutbox(ctx context.Context, limit int, now time.Time, lease time.Duration) ([]OutboxItem, error)
CompleteOutbox(ctx context.Context, id int64, at time.Time) error
FailOutbox(ctx context.Context, id int64, errMsg string, nextAttempt time.Time) error
PendingOutbox(ctx context.Context) (int, error)
// Webhook idempotency: true when eventID was not seen before.
RecordWebhookReceipt(ctx context.Context, eventID string) (bool, error)
// Licences
CreateLicence(ctx context.Context, l Licence) (*Licence, error)
GetLicence(ctx context.Context, id string) (*Licence, error)
ListLicences(ctx context.Context, tenantID string) ([]Licence, error)
RevokeLicence(ctx context.Context, id string, at time.Time) error
TouchLicence(ctx context.Context, id string, at time.Time) error
// SetLicenceLLMKey records (or clears, with "") the LiteLLM key id.
SetLicenceLLMKey(ctx context.Context, id string, keyID string) error
// Lifecycle
Close()
Ping(ctx context.Context) error
}