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
182 lines
6.4 KiB
Go
182 lines
6.4 KiB
Go
package main
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"log/slog"
|
|
"net/http"
|
|
"os"
|
|
"os/signal"
|
|
"syscall"
|
|
"time"
|
|
|
|
"git.breakpilot.com/platform/tenant-registry/internal/authn"
|
|
"git.breakpilot.com/platform/tenant-registry/internal/config"
|
|
"git.breakpilot.com/platform/tenant-registry/internal/erp"
|
|
"git.breakpilot.com/platform/tenant-registry/internal/keycloak"
|
|
"git.breakpilot.com/platform/tenant-registry/internal/licence"
|
|
"git.breakpilot.com/platform/tenant-registry/internal/llmkeys"
|
|
"git.breakpilot.com/platform/tenant-registry/internal/product"
|
|
"git.breakpilot.com/platform/tenant-registry/internal/server"
|
|
"git.breakpilot.com/platform/tenant-registry/internal/store"
|
|
"git.breakpilot.com/platform/tenant-registry/migrations"
|
|
)
|
|
|
|
func main() {
|
|
logger := slog.New(slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{Level: slog.LevelInfo}))
|
|
slog.SetDefault(logger)
|
|
|
|
cfg, err := config.Load()
|
|
if err != nil {
|
|
slog.Error("config load failed", "err", err)
|
|
os.Exit(1)
|
|
}
|
|
|
|
bootCtx, cancelBoot := context.WithTimeout(context.Background(), 15*time.Second)
|
|
defer cancelBoot()
|
|
|
|
var s store.Store
|
|
if cfg.DatabaseURL == "" {
|
|
slog.Warn("DATABASE_URL not set — running with in-memory store (dev only)")
|
|
s = store.NewMemory()
|
|
} else {
|
|
if os.Getenv("MIGRATE_ON_START") == "true" {
|
|
if err := migrations.Up(bootCtx, cfg.DatabaseURL); err != nil {
|
|
slog.Error("MIGRATE_ON_START failed", "err", err)
|
|
os.Exit(1)
|
|
}
|
|
}
|
|
pg, err := store.NewPostgres(bootCtx, cfg.DatabaseURL)
|
|
if err != nil {
|
|
slog.Error("postgres connect failed", "err", err)
|
|
os.Exit(1)
|
|
}
|
|
s = pg
|
|
}
|
|
defer s.Close()
|
|
|
|
var kc keycloak.Adapter
|
|
if cfg.KeycloakAdminURL != "" && cfg.KeycloakClientID != "" {
|
|
kc = keycloak.NewHTTPAdapter(keycloak.HTTPConfig{
|
|
BaseURL: cfg.KeycloakAdminURL,
|
|
Realm: cfg.KeycloakRealm,
|
|
ClientID: cfg.KeycloakClientID,
|
|
ClientSecret: cfg.KeycloakClientSecret,
|
|
Timeout: cfg.KeycloakTimeout,
|
|
|
|
InviteClientID: cfg.InviteClientID,
|
|
InviteRedirectURI: cfg.InviteRedirectURI,
|
|
})
|
|
slog.Info("keycloak adapter configured",
|
|
"url", cfg.KeycloakAdminURL, "realm", cfg.KeycloakRealm, "client_id", cfg.KeycloakClientID)
|
|
} else {
|
|
slog.Warn("KEYCLOAK_ADMIN_URL not set — using mock adapter (dev only; no real KC writes)")
|
|
kc = keycloak.NewMock()
|
|
}
|
|
|
|
var av *authn.Verifier
|
|
if cfg.AuthEnabled {
|
|
av, err = authn.New(bootCtx, cfg.KeycloakIssuer, cfg.AuthAudience)
|
|
if err != nil {
|
|
// Fail closed: never start an "authenticated" server that
|
|
// cannot actually verify tokens.
|
|
slog.Error("AUTH_CONFIG_INCOMPLETE — AUTH_ENABLED=true but verifier init failed", "err", err)
|
|
os.Exit(1)
|
|
}
|
|
slog.Info("api auth enabled", "issuer", cfg.KeycloakIssuer, "audience", cfg.AuthAudience)
|
|
} else {
|
|
slog.Warn("AUTH_ENABLED=false — API is unauthenticated (dev only)")
|
|
}
|
|
|
|
// Downstream product provisioning. Wired only when PRODUCT_API_URL is set;
|
|
// otherwise a no-op so an unconfigured deployment still creates tenants.
|
|
// The product's gate is not yet enforcing, so no token is attached today —
|
|
// AuthHeaderFunc is the seam for when it is.
|
|
var pv product.Provisioner = product.NoopProvisioner{}
|
|
if cfg.ProductAPIURL != "" {
|
|
pv = product.NewHTTPProvisioner(cfg.ProductAPIURL, cfg.ProductAPIPath, nil, cfg.ProductTimeout)
|
|
slog.Info("product provisioner configured", "url", cfg.ProductAPIURL, "path", cfg.ProductAPIPath)
|
|
} else {
|
|
slog.Warn("PRODUCT_API_URL not set — product tenant provisioning disabled (anchors may diverge)")
|
|
}
|
|
|
|
authz := server.ParseAuthzRules(cfg.AuthzRules)
|
|
server.LogAuthz(logger, authz)
|
|
|
|
// ERP link (M-MIG-7). Staging: erpnext-mock-stage; prod: erp.breakpilot.com.
|
|
erpClient := erp.New(erp.Config{BaseURL: cfg.ErpBaseURL, APIKey: cfg.ErpAPIKey, APISecret: cfg.ErpAPISecret, LeadDoctype: cfg.ErpLeadDoctype})
|
|
if erpClient.Enabled() {
|
|
slog.Info("erp client configured", "url", cfg.ErpBaseURL, "lead_doctype", cfg.ErpLeadDoctype)
|
|
} else {
|
|
slog.Warn("ERP_BASE_URL not set — ERP outbox idle, reconcile runs ladder steps only")
|
|
}
|
|
if cfg.ErpWebhookSecret == "" {
|
|
slog.Warn("ERP_WEBHOOK_SECRET not set — POST /v1/internal/erp/webhook is disabled")
|
|
}
|
|
signer, err := licence.NewSigner(cfg.LicenceSigningKey, cfg.LicenceIssuer)
|
|
if err != nil {
|
|
slog.Error("licence signer init failed", "err", err)
|
|
os.Exit(1)
|
|
}
|
|
if signer.Ephemeral {
|
|
slog.Warn("LICENCE_SIGNING_KEY not set — ephemeral licence key (dev only; licences die with the process)", "kid", signer.KID())
|
|
} else {
|
|
slog.Info("licence signer configured", "kid", signer.KID(), "issuer", signer.Issuer())
|
|
}
|
|
|
|
// LiteLLM virtual keys for Werkpilot licences (D6).
|
|
llmKeys := llmkeys.New(llmkeys.Config{BaseURL: cfg.LiteLLMBaseURL, MasterKey: cfg.LiteLLMMasterKey, Models: cfg.LiteLLMModels,
|
|
BudgetTrial: cfg.LiteLLMBudgetTrial, BudgetDefault: cfg.LiteLLMBudgetDefault})
|
|
if llmKeys.Enabled() {
|
|
slog.Info("litellm key provisioning configured", "url", llmKeys.BaseURL(), "models", llmKeys.Models(),
|
|
"budget_trial_usd", llmKeys.Budget(true), "budget_default_usd", llmKeys.Budget(false), "budget_duration", llmKeys.BudgetDuration())
|
|
} else {
|
|
slog.Warn("LITELLM_MASTER_KEY not set — Werkpilot licences are issued without a LiteLLM key")
|
|
}
|
|
|
|
app := &server.Server{Cfg: cfg, Log: logger, Store: s, Keycloak: kc, Auth: av, Authz: authz, Product: pv, ERP: erpClient, Licences: signer, LLMKeys: llmKeys}
|
|
handler := server.NewRouter(app)
|
|
srv := &http.Server{
|
|
Addr: cfg.Addr,
|
|
Handler: handler,
|
|
ReadTimeout: 10 * time.Second,
|
|
WriteTimeout: 30 * time.Second,
|
|
IdleTimeout: 60 * time.Second,
|
|
}
|
|
|
|
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
|
|
defer stop()
|
|
|
|
go app.RunOutbox(ctx, cfg.ErpOutboxInterval)
|
|
go app.RunReconcile(ctx, cfg.ErpReconcileEvery)
|
|
|
|
go func() {
|
|
slog.Info("tenant-registry listening", "addr", cfg.Addr, "env", cfg.Env, "store", storeKind(s))
|
|
if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
|
|
slog.Error("server crashed", "err", err)
|
|
os.Exit(1)
|
|
}
|
|
}()
|
|
|
|
<-ctx.Done()
|
|
slog.Info("shutdown requested")
|
|
shutdownCtx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
|
|
defer cancel()
|
|
if err := srv.Shutdown(shutdownCtx); err != nil {
|
|
slog.Error("shutdown failed", "err", err)
|
|
os.Exit(1)
|
|
}
|
|
slog.Info("bye")
|
|
}
|
|
|
|
func storeKind(s store.Store) string {
|
|
switch s.(type) {
|
|
case *store.Memory:
|
|
return "memory"
|
|
case *store.Postgres:
|
|
return "postgres"
|
|
default:
|
|
return "unknown"
|
|
}
|
|
}
|