diff --git a/Dockerfile b/Dockerfile index f678abf..4faac04 100644 --- a/Dockerfile +++ b/Dockerfile @@ -2,6 +2,7 @@ # Produces two binaries: # /tenant-registry — long-running API server # /migrate — one-shot schema migrator (Orca init container in prod) +# /erpmock — ERPNext stand-in for staging (decision 18; cmd/erpmock) FROM golang:1.25-alpine AS build WORKDIR /src @@ -9,12 +10,14 @@ COPY go.mod go.sum ./ RUN go mod download COPY . . RUN CGO_ENABLED=0 GOOS=linux go build -ldflags="-s -w" -o /out/tenant-registry ./cmd/server && \ - CGO_ENABLED=0 GOOS=linux go build -ldflags="-s -w" -o /out/migrate ./cmd/migrate + CGO_ENABLED=0 GOOS=linux go build -ldflags="-s -w" -o /out/migrate ./cmd/migrate && \ + CGO_ENABLED=0 GOOS=linux go build -ldflags="-s -w" -o /out/erpmock ./cmd/erpmock FROM gcr.io/distroless/static-debian12:nonroot WORKDIR / COPY --from=build /out/tenant-registry /tenant-registry COPY --from=build /out/migrate /migrate +COPY --from=build /out/erpmock /erpmock USER nonroot:nonroot EXPOSE 8090 ENTRYPOINT ["/tenant-registry"] diff --git a/README.md b/README.md index 0b49c41..3033692 100644 --- a/README.md +++ b/README.md @@ -47,6 +47,12 @@ Env vars (override at the shell): | `AUTH_ENABLED` / `AUTH_EXPECTED_AUDIENCE` | `false` / `tenant-registry` | Bearer-token gate on every non-health route | | `AUTHZ_RULES` | empty (allow all — dev only) | Per-client route groups, e.g. `portal-svc-stage:tenants,catalog,api-keys,audit,users;pruefwerk-svc-stage:entitlements,tenants.read,api-keys.verify,audit.write` | | `INVITE_CLIENT_ID` / `INVITE_REDIRECT_URI` | `dev-portal` / `https://breakpilot.com/onboard` | Keycloak invite mail client + landing URL (stage: `portal-stage`, `https://app-stage.breakpilot.com/start?invited=1`) | +| `ERP_BASE_URL` / `ERP_API_KEY` / `ERP_API_SECRET` | empty (outbox idle) | ERPNext / erpmock base URL + `token key:secret` credentials | +| `ERP_LEAD_DOCTYPE` | `Lead` | `CRM Lead` when the Frappe CRM app is used | +| `ERP_WEBHOOK_SECRET` | empty (receiver disabled) | HMAC secret for `POST /v1/internal/erp/webhook` | +| `ERP_OUTBOX_INTERVAL` / `ERP_RECONCILE_INTERVAL` | `15s` / `15m` | Worker cadence | +| `ERP_RESTRICT_AFTER_DAYS` / `ERP_HALT_AFTER_DAYS` / `ERP_EXPORT_WINDOW_DAYS` | `14` / `30` / `30` | Ladder timing | +| `LICENCE_SIGNING_KEY` / `LICENCE_ISSUER` / `LICENCE_TTL_DAYS` | empty (ephemeral) / `tenant-registry` / `30` | CLI licence signer (base64 Ed25519 seed) | ## Endpoints @@ -74,9 +80,61 @@ Authoritative spec: [`openapi.yaml`](./openapi.yaml). Summary: | POST | `/v1/internal/api-keys/verify` | Used by headless products to validate inbound keys | | POST | `/v1/audit` | Append an audit event | | GET | `/v1/audit` | Query (cursor-paginated) | +| POST | `/v1/usage/events` | Products push usage facts (idempotent; forwarded to ERPNext via the outbox) | +| GET | `/v1/usage/events?tenant_id={id}` | Query usage | +| GET | `/v1/subscriptions?tenant_id={id}` | Subscriptions mirrored from ERPNext | +| POST | `/v1/internal/erp/webhook` | ERPNext webhook receiver (HMAC, no bearer) → ladder | +| GET | `/v1/internal/erp/status` | Outbox backlog + ERP/licence configuration | +| POST | `/v1/internal/erp/reconcile` | Run the reconcile pass now | +| POST | `/v1/licences` | Issue a CLI licence JWT (Werkpilot, Firmwerk) | +| GET | `/v1/licences?tenant_id={id}` | List licences | +| POST | `/v1/licences/{id}/revoke` | Revoke | +| POST | `/v1/licences/heartbeat` | CLI phone-home (licence JWT is the credential; renews past half-life) | +| GET | `/.well-known/licence-keys.json` | JWKS (Ed25519) for offline licence verification | State-changing endpoints emit audit events automatically. The OpenAPI contract test (`openapi_test.go`) asserts every listed path resolves against the committed spec. +## ERP link (M-MIG-7) + +ERPNext is the commercial authority; the registry mirrors it and moves tenants +on the ladder (`ERP/02 Billing and Entitlements`): + +- **Outbox** (`erp_outbox`): tenant create → `customer.upsert` (writes + `erp_customer_id`), usage event → `usage.record`, catalog request → + `lead.create`. The worker runs every `ERP_OUTBOX_INTERVAL` (15 s) with + backoff 1 m / 5 m / 15 m / 1 h. With `ERP_BASE_URL` unset it idles and the + rows accumulate. +- **Webhooks** (`POST /v1/internal/erp/webhook`, HMAC `ERP_WEBHOOK_SECRET`): + `sales_order.submit` → subscriptions + `tenant_products` (SKU → product, + `-STD/-BUS/-ENT` → plan, add-on SKUs → limit, e.g. `runners`) + `active`; + `sales_invoice.overdue` → `warning`, `restricted` from + `ERP_RESTRICT_AFTER_DAYS` (14), `halted` from `ERP_HALT_AFTER_DAYS` (30); + `payment_entry.submit` → `active`; `subscription.cancel` → `halted`. +- **Reconcile** every `ERP_RECONCILE_INTERVAL` (15 min): re-reads ERP + Subscriptions per customer (safety net for lost webhooks) and applies the + time-based steps — trial expiry → `restricted`, `warning` → `restricted` + after 14 d, `restricted` → `halted` after 30 d total, `halted` → + `archived` after `ERP_EXPORT_WINDOW_DAYS` (30). +- Every status change syncs the coarse `tenant_status` claim to Keycloak. + +**Staging uses the mock** (`cmd/erpmock`, decision 18): the Frappe REST +surface (`/api/resource/{Customer,Subscription,Usage Record,Lead,…}` with +`Authorization: token key:secret`), `GET /_mock/requests` for assertions and +`POST /_mock/fire/{sales-order-submit|invoice-overdue|payment-entry|subscription-cancel}` +which mutate the mock's docs and deliver the signed webhook to +`ERP_WEBHOOK_URL`. The live-ERP configuration (custom field `tenant_id`, API +user, Frappe Webhooks) is documented in `ERP/03` for the prod phase. + +## CLI licences (decision 13) + +`werkpilot login` / `firmwerk login` run the device flow on the realm and call +`POST /v1/licences` with the user token; the registry checks the entitlement, +records the licence and signs an EdDSA JWT (`LICENCE_SIGNING_KEY` = base64 +32-byte Ed25519 seed; unset ⇒ ephemeral dev key). CLIs verify offline against +`/.well-known/licence-keys.json`, phone home hourly via `/v1/licences/heartbeat` +(ok → warning → degraded → hard_stop on the token's own clock after expiry, +plus the tenant ladder; renewal past half-life) and honour `revoked`. + ## Storage The service picks its store based on `DATABASE_URL`: diff --git a/cmd/erpmock/main.go b/cmd/erpmock/main.go new file mode 100644 index 0000000..30d5a78 --- /dev/null +++ b/cmd/erpmock/main.go @@ -0,0 +1,58 @@ +// erpmock — the staging stand-in for ERPNext (decision 18). See +// internal/erpmock. Configuration: +// +// ERPMOCK_ADDR listen address (default :8000) +// ERP_API_KEY expected `token key:secret` (default mock / mock) +// ERP_API_SECRET +// ERP_WEBHOOK_URL registry receiver, e.g. http://tenant-registry:8090/v1/internal/erp/webhook +// ERP_WEBHOOK_SECRET HMAC secret shared with the registry (ERP_WEBHOOK_SECRET there too) +package main + +import ( + "context" + "errors" + "log/slog" + "net/http" + "os" + "os/signal" + "syscall" + "time" + + "git.breakpilot.com/platform/tenant-registry/internal/erpmock" +) + +func main() { + logger := slog.New(slog.NewJSONHandler(os.Stdout, nil)) + slog.SetDefault(logger) + cfg := erpmock.Config{ + APIKey: env("ERP_API_KEY", "mock"), + APISecret: env("ERP_API_SECRET", "mock"), + WebhookURL: os.Getenv("ERP_WEBHOOK_URL"), + WebhookSecret: os.Getenv("ERP_WEBHOOK_SECRET"), + } + addr := env("ERPMOCK_ADDR", ":8000") + if cfg.WebhookURL == "" { + slog.Warn("ERP_WEBHOOK_URL not set — /_mock/fire/* simulates events without delivering webhooks") + } + srv := &http.Server{Addr: addr, Handler: erpmock.New(cfg), ReadTimeout: 10 * time.Second, WriteTimeout: 30 * time.Second} + ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) + defer stop() + go func() { + slog.Info("erpmock listening", "addr", addr, "webhook_url", cfg.WebhookURL) + if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) { + slog.Error("server crashed", "err", err) + os.Exit(1) + } + }() + <-ctx.Done() + shutdownCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + _ = srv.Shutdown(shutdownCtx) +} + +func env(k, def string) string { + if v := os.Getenv(k); v != "" { + return v + } + return def +} diff --git a/cmd/server/main.go b/cmd/server/main.go index bf86cbf..0f92b0b 100644 --- a/cmd/server/main.go +++ b/cmd/server/main.go @@ -12,7 +12,9 @@ import ( "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/product" "git.breakpilot.com/platform/tenant-registry/internal/server" "git.breakpilot.com/platform/tenant-registry/internal/store" @@ -93,7 +95,29 @@ func main() { authz := server.ParseAuthzRules(cfg.AuthzRules) server.LogAuthz(logger, authz) - handler := server.NewRouter(&server.Server{Cfg: cfg, Log: logger, Store: s, Keycloak: kc, Auth: av, Authz: authz, Product: pv}) + // 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()) + } + + app := &server.Server{Cfg: cfg, Log: logger, Store: s, Keycloak: kc, Auth: av, Authz: authz, Product: pv, ERP: erpClient, Licences: signer} + handler := server.NewRouter(app) srv := &http.Server{ Addr: cfg.Addr, Handler: handler, @@ -105,6 +129,9 @@ func main() { 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) { diff --git a/internal/authn/authn.go b/internal/authn/authn.go index f6a7c1e..124a7f5 100644 --- a/internal/authn/authn.go +++ b/internal/authn/authn.go @@ -28,8 +28,18 @@ type Principal struct { Subject string // JWT sub — the Keycloak user or service-account id ClientID string // JWT azp — which OAuth client obtained the token Issuer string + // tenant-context scope claims (present on user tokens; empty on + // client_credentials service tokens). + TenantID string + TenantSlug string + TenantStatus string + Email string } +// IsUser reports whether the token carries a tenant context (a person +// logged in through the portal / a CLI device flow) rather than a service. +func (p *Principal) IsUser() bool { return p != nil && p.TenantID != "" } + type ctxKey struct{} // WithPrincipal returns ctx carrying p. @@ -81,8 +91,13 @@ func (v *Verifier) Verify(ctx context.Context, authorization string) (*Principal return nil, err } var claims struct { - Azp string `json:"azp"` + Azp string `json:"azp"` + TenantID string `json:"tenant_id"` + TenantSlug string `json:"tenant_slug"` + TenantStatus string `json:"tenant_status"` + Email string `json:"email"` } _ = tok.Claims(&claims) // azp is informational; absence is not an error - return &Principal{Subject: tok.Subject, ClientID: claims.Azp, Issuer: tok.Issuer}, nil + return &Principal{Subject: tok.Subject, ClientID: claims.Azp, Issuer: tok.Issuer, + TenantID: claims.TenantID, TenantSlug: claims.TenantSlug, TenantStatus: claims.TenantStatus, Email: claims.Email}, nil } diff --git a/internal/config/config.go b/internal/config/config.go index 6f4087e..2b99483 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -3,6 +3,7 @@ package config import ( "fmt" "os" + "strconv" "time" ) @@ -42,6 +43,26 @@ type Config struct { // Per-client authorization rules (see server.ParseAuthzRules). Empty ⇒ // every authenticated client may call every route (dev only). AuthzRules string + + // ERP link (M-MIG-7). ErpBaseURL empty ⇒ outbox accumulates, reconcile + // idle (dev). Staging points at erpnext-mock-stage. + ErpBaseURL string + ErpAPIKey string + ErpAPISecret string + ErpLeadDoctype string + ErpWebhookSecret string // HMAC for POST /v1/internal/erp/webhook; empty ⇒ receiver disabled + ErpOutboxInterval time.Duration + ErpReconcileEvery time.Duration + // Ladder timing (days): warning → restricted, restricted → halted, + // halted → archived (export window). + RestrictAfterDays int + HaltAfterDays int + ExportWindowDays int + + // CLI licences (decision 13). Empty key ⇒ ephemeral (dev only, logged). + LicenceSigningKey string + LicenceIssuer string + LicenceTTLDays int } func Load() (*Config, error) { @@ -72,9 +93,42 @@ func Load() (*Config, error) { InviteClientID: getenv("INVITE_CLIENT_ID", "dev-portal"), InviteRedirectURI: getenv("INVITE_REDIRECT_URI", "https://breakpilot.com/onboard"), AuthzRules: os.Getenv("AUTHZ_RULES"), + + ErpBaseURL: os.Getenv("ERP_BASE_URL"), + ErpAPIKey: os.Getenv("ERP_API_KEY"), + ErpAPISecret: os.Getenv("ERP_API_SECRET"), + ErpLeadDoctype: getenv("ERP_LEAD_DOCTYPE", "Lead"), + ErpWebhookSecret: os.Getenv("ERP_WEBHOOK_SECRET"), + ErpOutboxInterval: getduration("ERP_OUTBOX_INTERVAL", 15*time.Second), + ErpReconcileEvery: getduration("ERP_RECONCILE_INTERVAL", 15*time.Minute), + RestrictAfterDays: getint("ERP_RESTRICT_AFTER_DAYS", 14), + HaltAfterDays: getint("ERP_HALT_AFTER_DAYS", 30), + ExportWindowDays: getint("ERP_EXPORT_WINDOW_DAYS", 30), + + LicenceSigningKey: os.Getenv("LICENCE_SIGNING_KEY"), + LicenceIssuer: getenv("LICENCE_ISSUER", "tenant-registry"), + LicenceTTLDays: getint("LICENCE_TTL_DAYS", 30), }, nil } +func getint(key string, fallback int) int { + if v := os.Getenv(key); v != "" { + if n, err := strconv.Atoi(v); err == nil { + return n + } + } + return fallback +} + +func getduration(key string, fallback time.Duration) time.Duration { + if v := os.Getenv(key); v != "" { + if d, err := time.ParseDuration(v); err == nil { + return d + } + } + return fallback +} + func getenv(key, fallback string) string { if v := os.Getenv(key); v != "" { return v diff --git a/internal/erp/erp.go b/internal/erp/erp.go new file mode 100644 index 0000000..944bcd7 --- /dev/null +++ b/internal/erp/erp.go @@ -0,0 +1,266 @@ +// Package erp is the ERPNext (Frappe REST) client the registry uses for the +// always-on customer ⇄ ERP link (ERP/02, decision 3 + 12): Customer upsert on +// tenant creation, Subscription reads for the reconcile job, Usage Record +// pushes from the outbox and CRM leads from catalog requests. On staging the +// endpoint is cmd/erpmock (decision 18); prod talks to erp.breakpilot.com. +// +// Authentication is Frappe's `Authorization: token :`. +package erp + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "net/url" + "strings" + "time" +) + +// Doctypes. LeadDoctype is ERPNext v15's "Lead"; the Frappe CRM app names it +// "CRM Lead" — configurable via Config.LeadDoctype. +const ( + CustomerDoctype = "Customer" + SubscriptionDoctype = "Subscription" + UsageRecordDoctype = "Usage Record" + SalesInvoiceDoctype = "Sales Invoice" + DefaultLeadDoctype = "Lead" +) + +// ErrUnavailable wraps transport / 5xx failures so the outbox retries them. +var ErrUnavailable = errors.New("erp: unavailable") + +// ErrNotFound — a GET by name returned 404. +var ErrNotFound = errors.New("erp: not found") + +type Config struct { + BaseURL string + APIKey string + APISecret string + LeadDoctype string + Timeout time.Duration +} + +type Client struct { + cfg Config + http *http.Client +} + +// New returns a client; Enabled() is false when BaseURL is empty. +func New(cfg Config) *Client { + if cfg.Timeout <= 0 { + cfg.Timeout = 10 * time.Second + } + if cfg.LeadDoctype == "" { + cfg.LeadDoctype = DefaultLeadDoctype + } + cfg.BaseURL = strings.TrimRight(cfg.BaseURL, "/") + return &Client{cfg: cfg, http: &http.Client{Timeout: cfg.Timeout}} +} + +func (c *Client) Enabled() bool { return c != nil && c.cfg.BaseURL != "" } + +// Customer — the ERPNext Customer doc subset we read/write. TenantID is the +// custom field `tenant_id` (ERP/03 live configuration). +type Customer struct { + Name string `json:"name,omitempty"` + CustomerName string `json:"customer_name"` + CustomerType string `json:"customer_type,omitempty"` + CustomerGroup string `json:"customer_group,omitempty"` + Territory string `json:"territory,omitempty"` + TenantID string `json:"tenant_id"` + TenantSlug string `json:"tenant_slug,omitempty"` +} + +// Subscription — Subscription doc subset. Plans carry the SKU (Subscription +// Plan name == Item code == platform SKU) and the quantity (seats/runners). +type Subscription struct { + Name string `json:"name"` + Party string `json:"party"` + Status string `json:"status"` // Trialling | Active | Past Due Date | Unpaid | Cancelled | Completed + SalesOrder string `json:"sales_order,omitempty"` + StartDate string `json:"start_date,omitempty"` + EndDate string `json:"end_date,omitempty"` + Plans []SubscriptionPlan `json:"plans"` +} + +type SubscriptionPlan struct { + Plan string `json:"plan"` + Qty float64 `json:"qty"` +} + +// UsageRecord — one metered fact (custom doctype, ERP/02 §usage). +type UsageRecord struct { + Customer string `json:"customer"` + TenantID string `json:"tenant_id"` + Product string `json:"product"` + Metric string `json:"metric"` + Qty float64 `json:"qty"` + OccurredAt string `json:"occurred_at"` + IdempotencyKey string `json:"idempotency_key"` +} + +// Lead — a CRM lead from a catalog request. +type Lead struct { + LeadName string `json:"lead_name"` + CompanyName string `json:"company_name,omitempty"` + EmailID string `json:"email_id,omitempty"` + Source string `json:"source,omitempty"` + Notes string `json:"notes,omitempty"` + TenantID string `json:"tenant_id,omitempty"` + Product string `json:"requested_product,omitempty"` +} + +// FindCustomerByTenant returns the Customer whose tenant_id equals tenantID +// ("" when none). +func (c *Client) FindCustomerByTenant(ctx context.Context, tenantID string) (*Customer, error) { + filters := fmt.Sprintf(`[["tenant_id","=",%q]]`, tenantID) + var out struct { + Data []Customer `json:"data"` + } + q := url.Values{"filters": {filters}, "fields": {`["name","customer_name","tenant_id","tenant_slug"]`}, "limit_page_length": {"1"}} + if err := c.do(ctx, http.MethodGet, "/api/resource/"+url.PathEscape(CustomerDoctype)+"?"+q.Encode(), nil, &out); err != nil { + return nil, err + } + if len(out.Data) == 0 { + return nil, nil + } + return &out.Data[0], nil +} + +// UpsertCustomer creates the Customer for a tenant unless one already carries +// its tenant_id. Returns the ERP customer name (the id the registry stores). +func (c *Client) UpsertCustomer(ctx context.Context, in Customer) (string, error) { + if in.TenantID == "" { + return "", errors.New("erp: tenant_id required") + } + if existing, err := c.FindCustomerByTenant(ctx, in.TenantID); err != nil { + return "", err + } else if existing != nil { + return existing.Name, nil + } + if in.CustomerType == "" { + in.CustomerType = "Company" + } + if in.CustomerGroup == "" { + in.CustomerGroup = "Commercial" + } + if in.Territory == "" { + in.Territory = "All Territories" + } + var out struct { + Data Customer `json:"data"` + } + if err := c.do(ctx, http.MethodPost, "/api/resource/"+url.PathEscape(CustomerDoctype), in, &out); err != nil { + return "", err + } + return out.Data.Name, nil +} + +// ListSubscriptions returns every Subscription of the customer (any status). +func (c *Client) ListSubscriptions(ctx context.Context, customer string) ([]Subscription, error) { + filters := fmt.Sprintf(`[["party","=",%q]]`, customer) + var names struct { + Data []struct { + Name string `json:"name"` + } `json:"data"` + } + q := url.Values{"filters": {filters}, "fields": {`["name"]`}, "limit_page_length": {"200"}} + if err := c.do(ctx, http.MethodGet, "/api/resource/"+url.PathEscape(SubscriptionDoctype)+"?"+q.Encode(), nil, &names); err != nil { + return nil, err + } + out := make([]Subscription, 0, len(names.Data)) + for _, n := range names.Data { + var doc struct { + Data Subscription `json:"data"` + } + if err := c.do(ctx, http.MethodGet, "/api/resource/"+url.PathEscape(SubscriptionDoctype)+"/"+url.PathEscape(n.Name), nil, &doc); err != nil { + return nil, err + } + out = append(out, doc.Data) + } + return out, nil +} + +// CreateUsageRecord pushes one usage record (idempotency is the registry's +// job: it only sends each event once, via the outbox). +func (c *Client) CreateUsageRecord(ctx context.Context, rec UsageRecord) (string, error) { + var out struct { + Data struct { + Name string `json:"name"` + } `json:"data"` + } + if err := c.do(ctx, http.MethodPost, "/api/resource/"+url.PathEscape(UsageRecordDoctype), rec, &out); err != nil { + return "", err + } + return out.Data.Name, nil +} + +// CreateLead files a CRM lead. +func (c *Client) CreateLead(ctx context.Context, lead Lead) (string, error) { + var out struct { + Data struct { + Name string `json:"name"` + } `json:"data"` + } + if err := c.do(ctx, http.MethodPost, "/api/resource/"+url.PathEscape(c.cfg.LeadDoctype), lead, &out); err != nil { + return "", err + } + return out.Data.Name, nil +} + +func (c *Client) do(ctx context.Context, method, path string, body any, into any) error { + if !c.Enabled() { + return fmt.Errorf("%w: ERP_BASE_URL not configured", ErrUnavailable) + } + var reader io.Reader + if body != nil { + buf, err := json.Marshal(body) + if err != nil { + return err + } + reader = bytes.NewReader(buf) + } + req, err := http.NewRequestWithContext(ctx, method, c.cfg.BaseURL+path, reader) + if err != nil { + return err + } + req.Header.Set("Accept", "application/json") + if body != nil { + req.Header.Set("Content-Type", "application/json") + } + if c.cfg.APIKey != "" { + req.Header.Set("Authorization", "token "+c.cfg.APIKey+":"+c.cfg.APISecret) + } + resp, err := c.http.Do(req) + if err != nil { + return fmt.Errorf("%w: %v", ErrUnavailable, err) + } + defer func() { _ = resp.Body.Close() }() + raw, _ := io.ReadAll(io.LimitReader(resp.Body, 1<<20)) + switch { + case resp.StatusCode == http.StatusNotFound: + return ErrNotFound + case resp.StatusCode >= 500 || resp.StatusCode == http.StatusTooManyRequests: + return fmt.Errorf("%w: %s %s → %d %s", ErrUnavailable, method, path, resp.StatusCode, truncate(raw)) + case resp.StatusCode/100 != 2: + return fmt.Errorf("erp: %s %s → %d %s", method, path, resp.StatusCode, truncate(raw)) + } + if into != nil && len(raw) > 0 { + if err := json.Unmarshal(raw, into); err != nil { + return fmt.Errorf("erp: decode %s %s: %w", method, path, err) + } + } + return nil +} + +func truncate(b []byte) string { + s := strings.TrimSpace(string(b)) + if len(s) > 200 { + return s[:200] + "…" + } + return s +} diff --git a/internal/erp/erp_test.go b/internal/erp/erp_test.go new file mode 100644 index 0000000..c3a0a8f --- /dev/null +++ b/internal/erp/erp_test.go @@ -0,0 +1,69 @@ +package erp_test + +import ( + "context" + "errors" + "net/http" + "net/http/httptest" + "testing" + + . "git.breakpilot.com/platform/tenant-registry/internal/erp" + "git.breakpilot.com/platform/tenant-registry/internal/erpmock" +) + +func TestClient_againstMock(t *testing.T) { + ms := httptest.NewServer(erpmock.New(erpmock.Config{APIKey: "k", APISecret: "s"})) + defer ms.Close() + c := New(Config{BaseURL: ms.URL + "/", APIKey: "k", APISecret: "s"}) + ctx := context.Background() + + if cust, err := c.FindCustomerByTenant(ctx, "t-1"); err != nil || cust != nil { + t.Fatalf("find before: %v %v", cust, err) + } + name, err := c.UpsertCustomer(ctx, Customer{CustomerName: "Acme", TenantID: "t-1"}) + if err != nil || name == "" { + t.Fatalf("upsert: %q %v", name, err) + } + if again, err := c.UpsertCustomer(ctx, Customer{CustomerName: "Acme", TenantID: "t-1"}); err != nil || again != name { + t.Fatalf("upsert idempotent: %q %v", again, err) + } + if _, err := c.UpsertCustomer(ctx, Customer{CustomerName: "x"}); err == nil { + t.Fatal("tenant_id required") + } + if subs, err := c.ListSubscriptions(ctx, name); err != nil || len(subs) != 0 { + t.Fatalf("subs: %v %v", subs, err) + } + if _, err := c.CreateUsageRecord(ctx, UsageRecord{Customer: name, Metric: "m", Qty: 1}); err != nil { + t.Fatal(err) + } + if _, err := c.CreateLead(ctx, Lead{LeadName: "Acme"}); err != nil { + t.Fatal(err) + } + bad := New(Config{BaseURL: ms.URL, APIKey: "wrong", APISecret: "s"}) + if _, err := bad.FindCustomerByTenant(ctx, "t-1"); err == nil || errors.Is(err, ErrUnavailable) { + t.Fatalf("401 must be a permanent error: %v", err) + } + off := New(Config{}) + if off.Enabled() { + t.Fatal("empty base url must be disabled") + } + if _, err := off.CreateLead(ctx, Lead{}); !errors.Is(err, ErrUnavailable) { + t.Fatalf("disabled: %v", err) + } + down := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(503) })) + defer down.Close() + if _, err := New(Config{BaseURL: down.URL}).CreateLead(ctx, Lead{}); !errors.Is(err, ErrUnavailable) { + t.Fatalf("503: %v", err) + } +} + +func TestSignature(t *testing.T) { + body := []byte(`{"a":1}`) + sig := Sign("sec", body) + if !VerifySignature("sec", body, sig) || VerifySignature("other", body, sig) || VerifySignature("sec", body, "") || VerifySignature("", body, sig) { + t.Fatal("base64 verify") + } + if VerifySignature("sec", body, "sha256=00") { + t.Fatal("bad hex must fail") + } +} diff --git a/internal/erp/webhook.go b/internal/erp/webhook.go new file mode 100644 index 0000000..6e8df63 --- /dev/null +++ b/internal/erp/webhook.go @@ -0,0 +1,72 @@ +package erp + +import ( + "crypto/hmac" + "crypto/sha256" + "encoding/base64" + "encoding/hex" + "strings" +) + +// Webhook headers. Frappe's Webhook doctype signs the JSON body with +// HMAC-SHA256 and sends it base64-encoded in X-Frappe-Webhook-Signature; +// the mock adds X-Frappe-Event-Id so receipts are idempotent by id. +const ( + HeaderSignature = "X-Frappe-Webhook-Signature" + HeaderEventID = "X-Frappe-Event-Id" + HeaderEvent = "X-Frappe-Event" +) + +// Webhook events the registry maps onto the tenant ladder (ERP/02). +const ( + EventSalesOrderSubmit = "sales_order.submit" + EventInvoiceOverdue = "sales_invoice.overdue" + EventPaymentEntrySubmit = "payment_entry.submit" + EventSubscriptionCancel = "subscription.cancel" +) + +// WebhookEvent is the payload shape both the mock and the live Frappe +// Webhook configuration (ERP/03) deliver. +type WebhookEvent struct { + Event string `json:"event"` + Doctype string `json:"doctype"` + Name string `json:"name"` + Modified string `json:"modified,omitempty"` + Customer string `json:"customer,omitempty"` + TenantID string `json:"tenant_id,omitempty"` + Items []WebhookItem `json:"items,omitempty"` + DaysOverdue int `json:"days_overdue,omitempty"` + Subscription string `json:"subscription,omitempty"` + Invoice string `json:"invoice,omitempty"` + Amount float64 `json:"amount,omitempty"` +} + +type WebhookItem struct { + ItemCode string `json:"item_code"` + Qty float64 `json:"qty"` +} + +// Sign returns the base64 HMAC-SHA256 of body. +func Sign(secret string, body []byte) string { + mac := hmac.New(sha256.New, []byte(secret)) + mac.Write(body) + return base64.StdEncoding.EncodeToString(mac.Sum(nil)) +} + +// VerifySignature accepts the Frappe base64 form and the GitHub-style +// "sha256=" form. +func VerifySignature(secret string, body []byte, header string) bool { + header = strings.TrimSpace(header) + if secret == "" || header == "" { + return false + } + mac := hmac.New(sha256.New, []byte(secret)) + mac.Write(body) + sum := mac.Sum(nil) + if hexSig, ok := strings.CutPrefix(header, "sha256="); ok { + want, err := hex.DecodeString(hexSig) + return err == nil && hmac.Equal(want, sum) + } + want, err := base64.StdEncoding.DecodeString(header) + return err == nil && hmac.Equal(want, sum) +} diff --git a/internal/erpmock/fire.go b/internal/erpmock/fire.go new file mode 100644 index 0000000..d1b0f86 --- /dev/null +++ b/internal/erpmock/fire.go @@ -0,0 +1,197 @@ +package erpmock + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "io" + "net/http" + "strings" + "time" + + "github.com/google/uuid" + + "git.breakpilot.com/platform/tenant-registry/internal/erp" +) + +// fireReq is the body of POST /_mock/fire/{trigger}. Either customer (ERP +// name) or tenant_id (looked up on the Customer docs) identifies the tenant. +type fireReq struct { + Customer string `json:"customer"` + TenantID string `json:"tenant_id"` + Items []erp.WebhookItem `json:"items"` + DaysOverdue int `json:"days_overdue"` + Subscription string `json:"subscription"` + Invoice string `json:"invoice"` + Amount float64 `json:"amount"` +} + +// fire simulates the ERPNext business event AND delivers the webhook the +// live Frappe Webhook configuration (ERP/03) would send. +func (s *Server) fire(w http.ResponseWriter, r *http.Request) { + var in fireReq + body, _ := io.ReadAll(io.LimitReader(r.Body, 1<<20)) + if len(body) > 0 { + if err := json.Unmarshal(body, &in); err != nil { + writeJSON(w, 400, map[string]any{"message": "invalid JSON"}) + return + } + } + cust, tenantID := s.resolveCustomer(in.Customer, in.TenantID) + if cust == "" { + writeJSON(w, 404, map[string]any{"message": "customer not found (create it via POST /api/resource/Customer or pass tenant_id of an existing one)"}) + return + } + ev := erp.WebhookEvent{Customer: cust, TenantID: tenantID} + s.mu.Lock() + switch r.PathValue("trigger") { + case "sales-order-submit": + if len(in.Items) == 0 { + s.mu.Unlock() + writeJSON(w, 400, map[string]any{"message": "items required"}) + return + } + items := make([]any, 0, len(in.Items)) + plans := make([]any, 0, len(in.Items)) + for _, it := range in.Items { + q := it.Qty + if q <= 0 { + q = 1 + } + items = append(items, map[string]any{"item_code": it.ItemCode, "qty": q}) + plans = append(plans, map[string]any{"plan": it.ItemCode, "qty": q}) + } + so := s.put("Sales Order", Doc{"customer": cust, "tenant_id": tenantID, "docstatus": 1, "status": "To Deliver and Bill", + "transaction_date": today(0), "delivery_date": today(0), "items": items}) + sub := s.put("Subscription", Doc{"party_type": "Customer", "party": cust, "status": "Active", "sales_order": so["name"], + "start_date": today(0), "current_invoice_start": today(0), "current_invoice_end": today(30), "plans": plans}) + ev.Event, ev.Doctype, ev.Name = erp.EventSalesOrderSubmit, "Sales Order", fmt.Sprint(so["name"]) + ev.Modified = fmt.Sprint(so["modified"]) + ev.Items = in.Items + ev.Subscription = fmt.Sprint(sub["name"]) + case "invoice-overdue": + days := in.DaysOverdue + if days <= 0 { + days = 1 + } + inv := s.put("Sales Invoice", Doc{"customer": cust, "tenant_id": tenantID, "docstatus": 1, "status": "Overdue", + "posting_date": today(-days - 14), "due_date": today(-days), "grand_total": in.Amount, "outstanding_amount": in.Amount}) + ev.Event, ev.Doctype, ev.Name = erp.EventInvoiceOverdue, "Sales Invoice", fmt.Sprint(inv["name"]) + ev.Modified = fmt.Sprint(inv["modified"]) + ev.DaysOverdue = days + ev.Invoice = fmt.Sprint(inv["name"]) + ev.Amount = in.Amount + case "payment-entry": + if in.Invoice != "" { + if inv, ok := s.docs["Sales Invoice"][in.Invoice]; ok { + inv["status"] = "Paid" + inv["outstanding_amount"] = 0 + s.put("Sales Invoice", inv) + } + } else { + for _, inv := range s.docs["Sales Invoice"] { + if inv["customer"] == cust && inv["status"] == "Overdue" { + inv["status"] = "Paid" + inv["outstanding_amount"] = 0 + s.put("Sales Invoice", inv) + } + } + } + pe := s.put("Payment Entry", Doc{"party_type": "Customer", "party": cust, "tenant_id": tenantID, "docstatus": 1, + "payment_type": "Receive", "paid_amount": in.Amount, "reference_no": in.Invoice}) + ev.Event, ev.Doctype, ev.Name = erp.EventPaymentEntrySubmit, "Payment Entry", fmt.Sprint(pe["name"]) + ev.Modified = fmt.Sprint(pe["modified"]) + ev.Invoice = in.Invoice + ev.Amount = in.Amount + case "subscription-cancel": + var target Doc + if in.Subscription != "" { + target = s.docs["Subscription"][in.Subscription] + } else { + for _, sub := range s.docs["Subscription"] { + if sub["party"] == cust && sub["status"] != "Cancelled" { + target = sub + break + } + } + } + if target == nil { + s.mu.Unlock() + writeJSON(w, 404, map[string]any{"message": "no active subscription for customer"}) + return + } + target["status"] = "Cancelled" + target["cancelation_date"] = today(0) + s.put("Subscription", target) + ev.Event, ev.Doctype, ev.Name = erp.EventSubscriptionCancel, "Subscription", fmt.Sprint(target["name"]) + ev.Modified = fmt.Sprint(target["modified"]) + ev.Subscription = fmt.Sprint(target["name"]) + default: + s.mu.Unlock() + writeJSON(w, 404, map[string]any{"message": "unknown trigger; use sales-order-submit | invoice-overdue | payment-entry | subscription-cancel"}) + return + } + s.mu.Unlock() + + d := s.deliver(r.Context(), ev) + code := 200 + if d.Status == 0 || d.Status >= 400 { + code = 502 + } + writeJSON(w, code, map[string]any{"event": ev, "delivery": d}) +} + +// resolveCustomer maps (customer | tenant_id) → (customer name, tenant_id). +func (s *Server) resolveCustomer(customer, tenantID string) (string, string) { + s.mu.Lock() + defer s.mu.Unlock() + if customer != "" { + if d, ok := s.docs["Customer"][customer]; ok { + return customer, fmt.Sprint(d["tenant_id"]) + } + return "", "" + } + for name, d := range s.docs["Customer"] { + if fmt.Sprint(d["tenant_id"]) == tenantID && tenantID != "" { + return name, tenantID + } + } + return "", "" +} + +// deliver POSTs the signed webhook to the registry and records the attempt. +func (s *Server) deliver(ctx context.Context, ev erp.WebhookEvent) Delivery { + payload, _ := json.Marshal(ev) + d := Delivery{At: time.Now().UTC(), Event: ev.Event, EventID: uuid.NewString(), Payload: payload} + if s.cfg.WebhookURL == "" { + d.Error = "ERP_WEBHOOK_URL not configured — event simulated, nothing delivered" + } else { + req, err := http.NewRequestWithContext(ctx, http.MethodPost, s.cfg.WebhookURL, bytes.NewReader(payload)) + if err == nil { + req.Header.Set("Content-Type", "application/json") + req.Header.Set(erp.HeaderSignature, erp.Sign(s.cfg.WebhookSecret, payload)) + req.Header.Set(erp.HeaderEventID, d.EventID) + req.Header.Set(erp.HeaderEvent, ev.Event) + resp, rerr := s.http.Do(req) + if rerr != nil { + d.Error = rerr.Error() + } else { + b, _ := io.ReadAll(io.LimitReader(resp.Body, 4096)) + _ = resp.Body.Close() + d.Status = resp.StatusCode + d.Response = strings.TrimSpace(string(b)) + } + } else { + d.Error = err.Error() + } + } + s.mu.Lock() + s.deliveries = append(s.deliveries, d) + s.mu.Unlock() + return d +} + +func today(offsetDays int) string { + return time.Now().UTC().AddDate(0, 0, offsetDays).Format("2006-01-02") +} diff --git a/internal/erpmock/server.go b/internal/erpmock/server.go new file mode 100644 index 0000000..3e29edd --- /dev/null +++ b/internal/erpmock/server.go @@ -0,0 +1,402 @@ +// Package erpmock is the staging stand-in for ERPNext (decision 18): the +// Frappe REST surface the registry uses (/api/resource/{doctype}), a request +// log for test assertions and /_mock/fire/* triggers that send HMAC-signed +// webhooks in the shape the registry's receiver expects. State is in memory. +package erpmock + +import ( + "encoding/json" + "fmt" + "io" + "net/http" + "sort" + "strings" + "sync" + "time" +) + +// Doc is a Frappe document: a JSON object with at least "name". +type Doc map[string]any + +// Request is one logged inbound API call. +type Request struct { + At time.Time `json:"at"` + Method string `json:"method"` + Path string `json:"path"` + Doctype string `json:"doctype,omitempty"` + Body json.RawMessage `json:"body,omitempty"` + Status int `json:"status"` +} + +// Delivery is one outbound webhook attempt. +type Delivery struct { + At time.Time `json:"at"` + Event string `json:"event"` + EventID string `json:"event_id"` + Payload json.RawMessage `json:"payload"` + Status int `json:"status"` + Error string `json:"error,omitempty"` + Response string `json:"response,omitempty"` +} + +type Config struct { + APIKey string + APISecret string + WebhookURL string + WebhookSecret string + // SKUs seeded as Item + Subscription Plan docs. + SKUs []string +} + +type Server struct { + cfg Config + mux *http.ServeMux + http *http.Client + + mu sync.Mutex + docs map[string]map[string]Doc // doctype → name → doc + seq map[string]int + requests []Request + deliveries []Delivery +} + +// DefaultSKUs mirrors the Phase-1 SKU sheet (ERP/02). +var DefaultSKUs = []string{ + "PLT-CORE-CLD-STD", "PLT-CORE-CLD-BUS", "PLT-CORE-CLD-ENT", + "CRA-CSA-CLD-STD", "CRA-CSA-CLD-BUS", "CRA-CSA-CLD-ENT", "CRA-CSA-CLD-SCAN", + "CRA-WBK-CLD-STD", "CRA-WBK-CLD-BUS", "CRA-WBK-CLD-ENT", + "DEV-WP-CLD-STD", "DEV-WP-CLD-BUS", "DEV-WP-CLD-ENT", "DEV-WP-OPR-STD", "DEV-WP-OPR-BUS", "DEV-WP-OPR-ENT", + "DEV-FWK-CLD-STD", "DEV-FWK-CLD-BUS", "DEV-FWK-CLD-ENT", "DEV-FWK-OPR-STD", "DEV-FWK-OPR-BUS", "DEV-FWK-OPR-ENT", +} + +func New(cfg Config) *Server { + if len(cfg.SKUs) == 0 { + cfg.SKUs = DefaultSKUs + } + s := &Server{cfg: cfg, mux: http.NewServeMux(), http: &http.Client{Timeout: 10 * time.Second}} + s.reset() + s.mux.HandleFunc("GET /api/method/ping", func(w http.ResponseWriter, _ *http.Request) { writeJSON(w, 200, map[string]any{"message": "pong"}) }) + s.mux.HandleFunc("GET /api/resource/{doctype}", s.withAuth(s.list)) + s.mux.HandleFunc("POST /api/resource/{doctype}", s.withAuth(s.create)) + s.mux.HandleFunc("GET /api/resource/{doctype}/{name}", s.withAuth(s.get)) + s.mux.HandleFunc("PUT /api/resource/{doctype}/{name}", s.withAuth(s.update)) + s.mux.HandleFunc("DELETE /api/resource/{doctype}/{name}", s.withAuth(s.del)) + s.mux.HandleFunc("GET /_mock/requests", s.listRequests) + s.mux.HandleFunc("DELETE /_mock/requests", s.clearRequests) + s.mux.HandleFunc("GET /_mock/deliveries", s.listDeliveries) + s.mux.HandleFunc("GET /_mock/docs/{doctype}", s.dumpDocs) + s.mux.HandleFunc("POST /_mock/reset", s.resetHandler) + s.mux.HandleFunc("POST /_mock/fire/{trigger}", s.fire) + s.mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, _ *http.Request) { writeJSON(w, 200, map[string]string{"status": "ok"}) }) + return s +} + +func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { s.mux.ServeHTTP(w, r) } + +func (s *Server) reset() { + s.mu.Lock() + defer s.mu.Unlock() + s.docs = map[string]map[string]Doc{} + s.seq = map[string]int{} + s.requests = nil + s.deliveries = nil + for _, sku := range s.cfg.SKUs { + s.put("Item", Doc{"name": sku, "item_code": sku, "item_name": sku, "item_group": "Services", "is_stock_item": 0}) + s.put("Subscription Plan", Doc{"name": sku, "plan_name": sku, "item": sku, "billing_interval": "Month"}) + } +} + +// put stores a doc under doctype (assigning a name when absent). Caller holds mu. +func (s *Server) put(doctype string, d Doc) Doc { + if s.docs[doctype] == nil { + s.docs[doctype] = map[string]Doc{} + } + name, _ := d["name"].(string) + if name == "" { + s.seq[doctype]++ + name = fmt.Sprintf("%s-%05d", prefix(doctype), s.seq[doctype]) + d["name"] = name + } + now := time.Now().UTC().Format("2006-01-02 15:04:05.000000") + if _, ok := d["creation"]; !ok { + d["creation"] = now + } + d["modified"] = now + d["doctype"] = doctype + s.docs[doctype][name] = d + return d +} + +func prefix(doctype string) string { + switch doctype { + case "Customer": + return "CUST" + case "Subscription": + return "SUB" + case "Sales Order": + return "SAL-ORD" + case "Sales Invoice": + return "ACC-SINV" + case "Payment Entry": + return "ACC-PAY" + case "Usage Record": + return "USG" + case "Lead", "CRM Lead": + return "CRM-LEAD" + } + return strings.ToUpper(strings.ReplaceAll(doctype, " ", "-")) +} + +func (s *Server) withAuth(next http.HandlerFunc) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + want := "token " + s.cfg.APIKey + ":" + s.cfg.APISecret + if s.cfg.APIKey != "" && r.Header.Get("Authorization") != want { + s.log(r, nil, http.StatusUnauthorized) + writeJSON(w, http.StatusUnauthorized, map[string]any{"exc_type": "AuthenticationError", "message": "Invalid API key"}) + return + } + next(w, r) + } +} + +func (s *Server) log(r *http.Request, body []byte, status int) { + s.mu.Lock() + defer s.mu.Unlock() + req := Request{At: time.Now().UTC(), Method: r.Method, Path: r.URL.RequestURI(), Doctype: r.PathValue("doctype"), Status: status} + if len(body) > 0 && json.Valid(body) { + req.Body = json.RawMessage(body) + } + s.requests = append(s.requests, req) +} + +// ─── /api/resource ──────────────────────────────────────────────────────── + +type filter struct { + Field, Op string + Value any +} + +func parseFilters(raw string) ([]filter, error) { + if strings.TrimSpace(raw) == "" { + return nil, nil + } + var arr [][]any + if err := json.Unmarshal([]byte(raw), &arr); err != nil { + return nil, err + } + out := make([]filter, 0, len(arr)) + for _, f := range arr { + if len(f) == 3 { + out = append(out, filter{Field: fmt.Sprint(f[0]), Op: fmt.Sprint(f[1]), Value: f[2]}) + } else if len(f) == 4 { // [doctype, field, op, value] + out = append(out, filter{Field: fmt.Sprint(f[1]), Op: fmt.Sprint(f[2]), Value: f[3]}) + } + } + return out, nil +} + +func matches(d Doc, fs []filter) bool { + for _, f := range fs { + got := fmt.Sprint(d[f.Field]) + want := fmt.Sprint(f.Value) + switch f.Op { + case "=", "==": + if got != want { + return false + } + case "!=": + if got == want { + return false + } + case "like": + if !strings.Contains(strings.ToLower(got), strings.ToLower(strings.Trim(want, "%"))) { + return false + } + case "in": + ok := false + if arr, isArr := f.Value.([]any); isArr { + for _, v := range arr { + if fmt.Sprint(v) == got { + ok = true + } + } + } + if !ok { + return false + } + } + } + return true +} + +func (s *Server) list(w http.ResponseWriter, r *http.Request) { + doctype := r.PathValue("doctype") + fs, err := parseFilters(r.URL.Query().Get("filters")) + if err != nil { + s.log(r, nil, 400) + writeJSON(w, 400, map[string]any{"message": "invalid filters"}) + return + } + var fields []string + _ = json.Unmarshal([]byte(r.URL.Query().Get("fields")), &fields) + s.mu.Lock() + out := []Doc{} + names := make([]string, 0, len(s.docs[doctype])) + for n := range s.docs[doctype] { + names = append(names, n) + } + sort.Strings(names) + for _, n := range names { + d := s.docs[doctype][n] + if matches(d, fs) { + out = append(out, project(d, fields)) + } + } + s.mu.Unlock() + s.log(r, nil, 200) + writeJSON(w, 200, map[string]any{"data": out}) +} + +func project(d Doc, fields []string) Doc { + if len(fields) == 0 { + return Doc{"name": d["name"]} + } + for _, f := range fields { + if f == "*" { + return d + } + } + out := Doc{} + for _, f := range fields { + if v, ok := d[f]; ok { + out[f] = v + } + } + return out +} + +func (s *Server) create(w http.ResponseWriter, r *http.Request) { + doctype := r.PathValue("doctype") + body, _ := io.ReadAll(io.LimitReader(r.Body, 1<<20)) + var d Doc + if err := json.Unmarshal(body, &d); err != nil || d == nil { + s.log(r, body, 400) + writeJSON(w, 400, map[string]any{"message": "invalid JSON"}) + return + } + delete(d, "name") // ERP assigns names + s.mu.Lock() + d = s.put(doctype, d) + s.mu.Unlock() + s.log(r, body, 200) + writeJSON(w, 200, map[string]any{"data": d}) +} + +func (s *Server) get(w http.ResponseWriter, r *http.Request) { + s.mu.Lock() + d, ok := s.docs[r.PathValue("doctype")][r.PathValue("name")] + s.mu.Unlock() + if !ok { + s.log(r, nil, 404) + writeJSON(w, 404, map[string]any{"exc_type": "DoesNotExistError"}) + return + } + s.log(r, nil, 200) + writeJSON(w, 200, map[string]any{"data": d}) +} + +func (s *Server) update(w http.ResponseWriter, r *http.Request) { + body, _ := io.ReadAll(io.LimitReader(r.Body, 1<<20)) + var patch Doc + if err := json.Unmarshal(body, &patch); err != nil { + s.log(r, body, 400) + writeJSON(w, 400, map[string]any{"message": "invalid JSON"}) + return + } + s.mu.Lock() + d, ok := s.docs[r.PathValue("doctype")][r.PathValue("name")] + if ok { + for k, v := range patch { + if k != "name" && k != "doctype" && k != "creation" { + d[k] = v + } + } + d = s.put(r.PathValue("doctype"), d) + } + s.mu.Unlock() + if !ok { + s.log(r, body, 404) + writeJSON(w, 404, map[string]any{"exc_type": "DoesNotExistError"}) + return + } + s.log(r, body, 200) + writeJSON(w, 200, map[string]any{"data": d}) +} + +func (s *Server) del(w http.ResponseWriter, r *http.Request) { + s.mu.Lock() + _, ok := s.docs[r.PathValue("doctype")][r.PathValue("name")] + delete(s.docs[r.PathValue("doctype")], r.PathValue("name")) + s.mu.Unlock() + if !ok { + s.log(r, nil, 404) + writeJSON(w, 404, map[string]any{"exc_type": "DoesNotExistError"}) + return + } + s.log(r, nil, 202) + writeJSON(w, 202, map[string]any{"message": "ok"}) +} + +// ─── /_mock ─────────────────────────────────────────────────────────────── + +func (s *Server) listRequests(w http.ResponseWriter, r *http.Request) { + s.mu.Lock() + out := make([]Request, 0, len(s.requests)) + for _, q := range s.requests { + if dt := r.URL.Query().Get("doctype"); dt != "" && q.Doctype != dt { + continue + } + if m := r.URL.Query().Get("method"); m != "" && q.Method != m { + continue + } + out = append(out, q) + } + s.mu.Unlock() + writeJSON(w, 200, map[string]any{"requests": out}) +} + +func (s *Server) clearRequests(w http.ResponseWriter, _ *http.Request) { + s.mu.Lock() + s.requests = nil + s.mu.Unlock() + writeJSON(w, 200, map[string]string{"status": "cleared"}) +} + +func (s *Server) listDeliveries(w http.ResponseWriter, _ *http.Request) { + s.mu.Lock() + out := append([]Delivery(nil), s.deliveries...) + s.mu.Unlock() + writeJSON(w, 200, map[string]any{"deliveries": out}) +} + +func (s *Server) dumpDocs(w http.ResponseWriter, r *http.Request) { + s.mu.Lock() + out := []Doc{} + for _, d := range s.docs[r.PathValue("doctype")] { + out = append(out, d) + } + s.mu.Unlock() + sort.Slice(out, func(i, j int) bool { return fmt.Sprint(out[i]["name"]) < fmt.Sprint(out[j]["name"]) }) + writeJSON(w, 200, map[string]any{"data": out}) +} + +func (s *Server) resetHandler(w http.ResponseWriter, _ *http.Request) { + s.reset() + writeJSON(w, 200, map[string]string{"status": "reset"}) +} + +func writeJSON(w http.ResponseWriter, code int, body any) { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(code) + _ = json.NewEncoder(w).Encode(body) +} diff --git a/internal/erpmock/server_test.go b/internal/erpmock/server_test.go new file mode 100644 index 0000000..66102e3 --- /dev/null +++ b/internal/erpmock/server_test.go @@ -0,0 +1,157 @@ +package erpmock + +import ( + "bytes" + "encoding/json" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "git.breakpilot.com/platform/tenant-registry/internal/erp" +) + +func call(t *testing.T, base, method, path string, body any, auth bool) (int, []byte) { + t.Helper() + var reader io.Reader + if body != nil { + buf, _ := json.Marshal(body) + reader = bytes.NewReader(buf) + } + req, _ := http.NewRequest(method, base+path, reader) + if auth { + req.Header.Set("Authorization", "token k:s") + } + resp, err := http.DefaultClient.Do(req) + if err != nil { + t.Fatal(err) + } + defer func() { _ = resp.Body.Close() }() + raw, _ := io.ReadAll(resp.Body) + return resp.StatusCode, raw +} + +func TestMock_resourceAPI(t *testing.T) { + // receiver that records the webhook + var got erp.WebhookEvent + var sig, eventID string + recv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + body, _ := io.ReadAll(r.Body) + sig = r.Header.Get(erp.HeaderSignature) + eventID = r.Header.Get(erp.HeaderEventID) + if !erp.VerifySignature("sec", body, sig) { + w.WriteHeader(401) + return + } + _ = json.Unmarshal(body, &got) + w.WriteHeader(200) + })) + defer recv.Close() + srv := httptest.NewServer(New(Config{APIKey: "k", APISecret: "s", WebhookURL: recv.URL, WebhookSecret: "sec"})) + defer srv.Close() + + if code, _ := call(t, srv.URL, "GET", "/api/resource/Item", nil, false); code != 401 { + t.Fatalf("no auth: %d", code) + } + code, raw := call(t, srv.URL, "GET", `/api/resource/Item?fields=["name"]`, nil, true) + if code != 200 || !bytes.Contains(raw, []byte("CRA-CSA-CLD-STD")) { + t.Fatalf("items: %d %s", code, raw) + } + code, raw = call(t, srv.URL, "POST", "/api/resource/Customer", map[string]any{"customer_name": "Acme", "tenant_id": "t-1"}, true) + if code != 200 || !bytes.Contains(raw, []byte(`"name":"CUST-00001"`)) { + t.Fatalf("create: %d %s", code, raw) + } + code, raw = call(t, srv.URL, "GET", `/api/resource/Customer?filters=[["tenant_id","=","t-1"]]&fields=["name","tenant_id"]`, nil, true) + if code != 200 || !bytes.Contains(raw, []byte(`CUST-00001`)) { + t.Fatalf("filter: %d %s", code, raw) + } + if _, raw = call(t, srv.URL, "GET", `/api/resource/Customer?filters=[["tenant_id","=","t-2"]]`, nil, true); !bytes.Contains(raw, []byte(`"data":[]`)) { + t.Fatalf("filter miss: %s", raw) + } + if code, _ = call(t, srv.URL, "GET", `/api/resource/Customer?filters=nope`, nil, true); code != 400 { + t.Fatalf("bad filter: %d", code) + } + if code, raw = call(t, srv.URL, "PUT", "/api/resource/Customer/CUST-00001", map[string]any{"territory": "Germany"}, true); code != 200 || !bytes.Contains(raw, []byte("Germany")) { + t.Fatalf("update: %d %s", code, raw) + } + if code, _ = call(t, srv.URL, "GET", "/api/resource/Customer/CUST-00009", nil, true); code != 404 { + t.Fatalf("get missing: %d", code) + } + if code, _ = call(t, srv.URL, "PUT", "/api/resource/Customer/CUST-00009", map[string]any{}, true); code != 404 { + t.Fatalf("update missing: %d", code) + } + + // fire: unknown customer, missing items, then a real order + if code, _ = call(t, srv.URL, "POST", "/_mock/fire/sales-order-submit", map[string]any{"tenant_id": "nope"}, false); code != 404 { + t.Fatalf("fire unknown: %d", code) + } + if code, _ = call(t, srv.URL, "POST", "/_mock/fire/sales-order-submit", map[string]any{"tenant_id": "t-1"}, false); code != 400 { + t.Fatalf("fire no items: %d", code) + } + if code, _ = call(t, srv.URL, "POST", "/_mock/fire/bogus", map[string]any{"tenant_id": "t-1"}, false); code != 404 { + t.Fatalf("fire bogus: %d", code) + } + code, raw = call(t, srv.URL, "POST", "/_mock/fire/sales-order-submit", map[string]any{"customer": "CUST-00001", "items": []map[string]any{{"item_code": "CRA-CSA-CLD-STD", "qty": 2}}}, false) + if code != 200 { + t.Fatalf("fire: %d %s", code, raw) + } + if got.Event != erp.EventSalesOrderSubmit || got.Customer != "CUST-00001" || got.TenantID != "t-1" || len(got.Items) != 1 || got.Subscription == "" || sig == "" || eventID == "" { + t.Fatalf("delivered event: %+v sig=%q id=%q", got, sig, eventID) + } + // the Subscription doc exists and lists the plan + _, raw = call(t, srv.URL, "GET", `/api/resource/Subscription?filters=[["party","=","CUST-00001"]]&fields=["*"]`, nil, true) + if !bytes.Contains(raw, []byte(`"plan":"CRA-CSA-CLD-STD"`)) || !bytes.Contains(raw, []byte(`"status":"Active"`)) { + t.Fatalf("subscription doc: %s", raw) + } + call(t, srv.URL, "POST", "/_mock/fire/invoice-overdue", map[string]any{"customer": "CUST-00001", "days_overdue": 5, "amount": 10}, false) + if got.Event != erp.EventInvoiceOverdue || got.DaysOverdue != 5 { + t.Fatalf("overdue: %+v", got) + } + call(t, srv.URL, "POST", "/_mock/fire/payment-entry", map[string]any{"customer": "CUST-00001", "amount": 10}, false) + if got.Event != erp.EventPaymentEntrySubmit { + t.Fatalf("payment: %+v", got) + } + _, raw = call(t, srv.URL, "GET", "/_mock/docs/Sales Invoice", nil, false) + if !bytes.Contains(raw, []byte(`"status":"Paid"`)) { + t.Fatalf("invoice not paid: %s", raw) + } + call(t, srv.URL, "POST", "/_mock/fire/subscription-cancel", map[string]any{"customer": "CUST-00001"}, false) + if got.Event != erp.EventSubscriptionCancel || got.Subscription == "" { + t.Fatalf("cancel: %+v", got) + } + if code, _ = call(t, srv.URL, "POST", "/_mock/fire/subscription-cancel", map[string]any{"customer": "CUST-00001"}, false); code != 404 { + t.Fatalf("second cancel: %d", code) + } + // logs + _, raw = call(t, srv.URL, "GET", "/_mock/requests?doctype=Customer&method=POST", nil, false) + if strings.Count(string(raw), `"method":"POST"`) != 1 { + t.Fatalf("request log: %s", raw) + } + _, raw = call(t, srv.URL, "GET", "/_mock/deliveries", nil, false) + if strings.Count(string(raw), `"status":200`) != 4 { + t.Fatalf("deliveries: %s", raw) + } + if code, _ = call(t, srv.URL, "DELETE", "/_mock/requests", nil, false); code != 200 { + t.Fatalf("clear: %d", code) + } + if code, _ = call(t, srv.URL, "DELETE", "/api/resource/Customer/CUST-00001", nil, true); code != 202 { + t.Fatalf("delete: %d", code) + } + if code, _ = call(t, srv.URL, "POST", "/_mock/reset", nil, false); code != 200 { + t.Fatalf("reset: %d", code) + } + if _, raw = call(t, srv.URL, "GET", `/api/resource/Customer?fields=["*"]`, nil, true); !bytes.Contains(raw, []byte(`"data":[]`)) { + t.Fatalf("after reset: %s", raw) + } +} + +func TestMock_noWebhookURL(t *testing.T) { + srv := httptest.NewServer(New(Config{APIKey: "k", APISecret: "s"})) + defer srv.Close() + call(t, srv.URL, "POST", "/api/resource/Customer", map[string]any{"customer_name": "A", "tenant_id": "t"}, true) + code, raw := call(t, srv.URL, "POST", "/_mock/fire/invoice-overdue", map[string]any{"tenant_id": "t"}, false) + if code != 502 || !bytes.Contains(raw, []byte("not configured")) { + t.Fatalf("got %d %s", code, raw) + } +} diff --git a/internal/licence/licence.go b/internal/licence/licence.go new file mode 100644 index 0000000..c8d2afd --- /dev/null +++ b/internal/licence/licence.go @@ -0,0 +1,161 @@ +// Package licence issues and verifies the CLI licence JWTs the registry +// hands to Werkpilot and Firmwerk (decision 13): Ed25519-signed, verified +// offline by the CLI against /.well-known/licence-keys.json, refreshed by +// the heartbeat endpoint. The grace ladder (ERP/02 SKU sheet) rides inside +// the token so an offline CLI degrades on its own clock. +package licence + +import ( + "crypto/ed25519" + "crypto/rand" + "crypto/sha256" + "encoding/base64" + "encoding/hex" + "errors" + "fmt" + "strings" + "time" + + "github.com/go-jose/go-jose/v4" + "github.com/go-jose/go-jose/v4/jwt" +) + +// GracePolicy — days after expiry: warning (still full), degraded (read-only +// / reduced), hard stop. Healthy 0-7 / Warning 7-14 / Degraded 14-30 / Hard-stop. +type GracePolicy struct { + WarningDays int `json:"warning_days"` + DegradedDays int `json:"degraded_days"` + HardStopDays int `json:"hard_stop_days"` +} + +var DefaultGrace = GracePolicy{WarningDays: 7, DegradedDays: 14, HardStopDays: 30} + +// Claims is the licence token body. +type Claims struct { + jwt.Claims + TenantID string `json:"tenant_id"` + TenantSlug string `json:"tenant_slug,omitempty"` + Product string `json:"product"` + Plan string `json:"plan,omitempty"` + Seats int `json:"seats,omitempty"` + Device string `json:"device,omitempty"` + Grace GracePolicy `json:"grace"` + Heartbeat string `json:"heartbeat_url,omitempty"` +} + +// Signer holds the Ed25519 key. Ephemeral is true when no key was +// configured (dev): tokens then die with the process. +type Signer struct { + priv ed25519.PrivateKey + kid string + issuer string + Ephemeral bool +} + +// NewSigner parses a base64 (std or url, padded or not) 32-byte seed or a +// 64-byte private key. Empty seed → ephemeral key. +func NewSigner(seedB64, issuer string) (*Signer, error) { + if issuer == "" { + issuer = "tenant-registry" + } + var priv ed25519.PrivateKey + ephemeral := false + if strings.TrimSpace(seedB64) == "" { + _, k, err := ed25519.GenerateKey(rand.Reader) + if err != nil { + return nil, err + } + priv, ephemeral = k, true + } else { + raw, err := decodeB64(seedB64) + if err != nil { + return nil, fmt.Errorf("LICENCE_SIGNING_KEY: %w", err) + } + switch len(raw) { + case ed25519.SeedSize: + priv = ed25519.NewKeyFromSeed(raw) + case ed25519.PrivateKeySize: + priv = ed25519.PrivateKey(raw) + default: + return nil, fmt.Errorf("LICENCE_SIGNING_KEY: want 32-byte seed, got %d bytes", len(raw)) + } + } + pub := priv.Public().(ed25519.PublicKey) + sum := sha256.Sum256(pub) + return &Signer{priv: priv, kid: hex.EncodeToString(sum[:4]), issuer: issuer, Ephemeral: ephemeral}, nil +} + +func decodeB64(s string) ([]byte, error) { + s = strings.TrimSpace(s) + for _, enc := range []*base64.Encoding{base64.RawURLEncoding, base64.RawStdEncoding, base64.URLEncoding, base64.StdEncoding} { + if b, err := enc.DecodeString(strings.TrimRight(s, "=")); err == nil { + return b, nil + } + if b, err := enc.DecodeString(s); err == nil { + return b, nil + } + } + return nil, errors.New("not base64") +} + +func (s *Signer) KID() string { return s.kid } +func (s *Signer) Issuer() string { return s.issuer } + +// PublicJWK is the verification key entry for /.well-known/licence-keys.json. +func (s *Signer) PublicJWK() jose.JSONWebKey { + return jose.JSONWebKey{Key: s.priv.Public(), KeyID: s.kid, Algorithm: string(jose.EdDSA), Use: "sig"} +} + +// Issue signs c (iss/iat/jti filled in when empty). +func (s *Signer) Issue(c Claims) (string, error) { + signer, err := jose.NewSigner(jose.SigningKey{Algorithm: jose.EdDSA, Key: s.priv}, + (&jose.SignerOptions{}).WithType("JWT").WithHeader("kid", s.kid)) + if err != nil { + return "", err + } + if c.Issuer == "" { + c.Issuer = s.issuer + } + if c.IssuedAt == nil { + c.IssuedAt = jwt.NewNumericDate(time.Now().UTC()) + } + if c.Grace == (GracePolicy{}) { + c.Grace = DefaultGrace + } + return jwt.Signed(signer).Claims(c).Serialize() +} + +// Verify checks the signature and issuer but NOT expiry — the caller decides +// what an expired licence means (grace ladder). +func (s *Signer) Verify(raw string) (*Claims, error) { + tok, err := jwt.ParseSigned(raw, []jose.SignatureAlgorithm{jose.EdDSA}) + if err != nil { + return nil, err + } + var c Claims + if err := tok.Claims(s.priv.Public(), &c); err != nil { + return nil, err + } + if c.Issuer != s.issuer { + return nil, fmt.Errorf("issuer %q is not %q", c.Issuer, s.issuer) + } + return &c, nil +} + +// State classifies a licence at `now` against the grace policy. +func (p GracePolicy) State(expiry, now time.Time) string { + if !now.After(expiry) { + return "ok" + } + over := now.Sub(expiry) + day := 24 * time.Hour + switch { + case over >= time.Duration(p.HardStopDays)*day: + return "hard_stop" + case over >= time.Duration(p.DegradedDays)*day: + return "degraded" + case over >= time.Duration(p.WarningDays)*day: + return "warning" + } + return "warning" +} diff --git a/internal/licence/licence_test.go b/internal/licence/licence_test.go new file mode 100644 index 0000000..b2803d0 --- /dev/null +++ b/internal/licence/licence_test.go @@ -0,0 +1,65 @@ +package licence + +import ( + "encoding/base64" + "testing" + "time" + + "github.com/go-jose/go-jose/v4/jwt" +) + +func TestSigner_roundTrip(t *testing.T) { + seed := make([]byte, 32) + for i := range seed { + seed[i] = byte(i) + } + s, err := NewSigner(base64.RawURLEncoding.EncodeToString(seed), "reg") + if err != nil || s.Ephemeral { + t.Fatalf("signer: %v %v", err, s) + } + s2, _ := NewSigner(base64.StdEncoding.EncodeToString(seed), "reg") + if s.KID() != s2.KID() { + t.Fatalf("kid must be stable across encodings: %s %s", s.KID(), s2.KID()) + } + tok, err := s.Issue(Claims{Claims: jwt.Claims{Subject: "u1", ID: "lic-1", Expiry: jwt.NewNumericDate(time.Now().Add(time.Hour))}, TenantID: "t1", Product: "werkpilot"}) + if err != nil { + t.Fatal(err) + } + c, err := s2.Verify(tok) + if err != nil || c.TenantID != "t1" || c.ID != "lic-1" || c.Grace != DefaultGrace || c.Issuer != "reg" { + t.Fatalf("verify: %v %+v", err, c) + } + other, _ := NewSigner("", "reg") + if _, err := other.Verify(tok); err == nil { + t.Fatal("foreign key must not verify") + } + wrongIss, _ := NewSigner(base64.RawURLEncoding.EncodeToString(seed), "someone-else") + if _, err := wrongIss.Verify(tok); err == nil { + t.Fatal("issuer mismatch must fail") + } + if _, err := NewSigner("nope!", "x"); err == nil { + t.Fatal("bad base64 must fail") + } + if _, err := NewSigner(base64.StdEncoding.EncodeToString([]byte("short")), "x"); err == nil { + t.Fatal("wrong length must fail") + } + if jwk := s.PublicJWK(); jwk.KeyID != s.KID() || jwk.Algorithm != "EdDSA" { + t.Fatalf("jwk: %+v", jwk) + } +} + +func TestGracePolicy_State(t *testing.T) { + exp := time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC) + day := 24 * time.Hour + for _, c := range []struct { + at time.Time + want string + }{ + {exp.Add(-time.Hour), "ok"}, {exp.Add(time.Hour), "warning"}, {exp.Add(8 * day), "warning"}, + {exp.Add(14 * day), "degraded"}, {exp.Add(29 * day), "degraded"}, {exp.Add(30 * day), "hard_stop"}, + } { + if got := DefaultGrace.State(exp, c.at); got != c.want { + t.Errorf("%v: got %s want %s", c.at, got, c.want) + } + } +} diff --git a/internal/server/authz.go b/internal/server/authz.go index ce7eada..b62e849 100644 --- a/internal/server/authz.go +++ b/internal/server/authz.go @@ -89,7 +89,12 @@ func routeGroup(method, path string) string { case strings.HasPrefix(path, "/v1/users/"): return "users" case strings.HasPrefix(path, "/v1/usage"): + if method == http.MethodGet { + return "usage.read" + } return "usage" + case strings.HasPrefix(path, "/v1/subscriptions"): + return "tenants.read" case strings.HasPrefix(path, "/v1/licences"): return "licences" case strings.HasPrefix(path, "/v1/tenants"): diff --git a/internal/server/catalog.go b/internal/server/catalog.go index 79c0b33..f915974 100644 --- a/internal/server/catalog.go +++ b/internal/server/catalog.go @@ -3,6 +3,7 @@ package server import ( "context" "errors" + "git.breakpilot.com/platform/tenant-registry/internal/authn" "net/http" "time" @@ -76,7 +77,8 @@ func (s *Server) catalogRequest(w http.ResponseWriter, r *http.Request) { writeError(w, http.StatusBadRequest, "unknown_product", "product is not in the catalog") return } - if _, err := s.Store.GetTenant(ctx, in.TenantID); err != nil { + t, err := s.Store.GetTenant(ctx, in.TenantID) + if err != nil { if mapStoreError(w, err) { return } @@ -88,6 +90,16 @@ func (s *Server) catalogRequest(w http.ResponseWriter, r *http.Request) { TargetID: in.Product, TargetType: "product", Metadata: map[string]interface{}{"product": in.Product}, }) + // CRM lead through the ERP outbox (M-MIG-7). + email := "" + if p, _ := authn.PrincipalFrom(r.Context()); p != nil { + email = p.Email + } + if _, err := s.Store.EnqueueOutbox(ctx, store.OutboxItem{Kind: store.OutboxLeadCreate, TenantID: in.TenantID, + Payload: map[string]interface{}{"lead_name": t.Name, "company_name": t.Name, "email": email, "product": in.Product, + "notes": "Requested " + in.Product + " from the platform catalog"}}); err != nil { + s.Log.Error("enqueue lead failed", "tenant_id", in.TenantID, "err", err) + } writeJSON(w, http.StatusAccepted, map[string]string{ "status": "accepted", "message": "request recorded; sales will be in touch", diff --git a/internal/server/erp.go b/internal/server/erp.go new file mode 100644 index 0000000..2c0003d --- /dev/null +++ b/internal/server/erp.go @@ -0,0 +1,612 @@ +package server + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "errors" + "io" + "net/http" + "sort" + "strings" + "time" + + "git.breakpilot.com/platform/tenant-registry/internal/erp" + "git.breakpilot.com/platform/tenant-registry/internal/store" +) + +// ─── ERP link (M-MIG-7): webhook receiver, subscription → entitlement +// mapping, ladder transitions, reconcile ────────────────────────────────── +// +// ERPNext is the commercial authority (Sales Orders / Subscriptions / +// Invoices / Payments); the registry mirrors what it hears into +// subscriptions + tenant_products and moves the tenant on the ladder +// (ERP/02): active → warning (invoice overdue) → restricted (grace over, +// read-only) → halted (cancelled / hard stop) → archived (export window over). + +// erpWebhook is POST /v1/internal/erp/webhook (PUBLIC_EXPLICIT, HMAC). +func (s *Server) erpWebhook(w http.ResponseWriter, r *http.Request) { + secret := s.cfg().ErpWebhookSecret + if secret == "" { + writeError(w, http.StatusServiceUnavailable, "webhook_disabled", "ERP_WEBHOOK_SECRET is not configured") + return + } + body, err := io.ReadAll(io.LimitReader(r.Body, 1<<20)) + if err != nil { + writeError(w, http.StatusBadRequest, "invalid_body", err.Error()) + return + } + sig := r.Header.Get(erp.HeaderSignature) + if sig == "" { + sig = r.Header.Get("X-Hub-Signature-256") + } + if !erp.VerifySignature(secret, body, sig) { + s.Log.Warn("erp webhook signature rejected", "ip", clientIP(r)) + writeError(w, http.StatusUnauthorized, "bad_signature", "webhook signature invalid") + return + } + var ev erp.WebhookEvent + if err := json.Unmarshal(body, &ev); err != nil { + writeError(w, http.StatusBadRequest, "invalid_json", err.Error()) + return + } + if ev.Event == "" { + ev.Event = r.Header.Get(erp.HeaderEvent) + } + eventID := r.Header.Get(erp.HeaderEventID) + if eventID == "" { + sum := sha256.Sum256(body) + eventID = ev.Event + ":" + ev.Name + ":" + ev.Modified + ":" + hex.EncodeToString(sum[:8]) + } + ctx, cancel := context.WithTimeout(r.Context(), 10*time.Second) + defer cancel() + fresh, err := s.Store.RecordWebhookReceipt(ctx, eventID) + if err != nil { + writeError(w, http.StatusInternalServerError, "internal", err.Error()) + return + } + if !fresh { + writeJSON(w, http.StatusOK, map[string]any{"status": "duplicate", "event_id": eventID}) + return + } + t, err := s.resolveWebhookTenant(ctx, ev) + if err != nil { + if errors.Is(err, store.ErrNotFound) { + // Not ours (e.g. a customer without tenant_id). Acknowledge so + // ERPNext does not retry forever; the receipt keeps it idempotent. + s.Log.Warn("erp webhook for unknown tenant", "event", ev.Event, "customer", ev.Customer, "tenant_id", ev.TenantID) + writeJSON(w, http.StatusAccepted, map[string]any{"status": "ignored", "reason": "tenant_not_found", "event_id": eventID}) + return + } + writeError(w, http.StatusInternalServerError, "internal", err.Error()) + return + } + res, err := s.applyErpEvent(ctx, r, t, ev) + if err != nil { + writeError(w, http.StatusInternalServerError, "internal", err.Error()) + return + } + res["event_id"] = eventID + writeJSON(w, http.StatusOK, res) +} + +func (s *Server) resolveWebhookTenant(ctx context.Context, ev erp.WebhookEvent) (*store.Tenant, error) { + if ev.TenantID != "" { + if t, err := s.Store.GetTenant(ctx, ev.TenantID); err == nil { + return t, nil + } else if !errors.Is(err, store.ErrNotFound) { + return nil, err + } + } + return s.Store.GetTenantByErpCustomerID(ctx, ev.Customer) +} + +// applyErpEvent maps one webhook onto the ladder. Returns a small result map. +func (s *Server) applyErpEvent(ctx context.Context, r *http.Request, t *store.Tenant, ev erp.WebhookEvent) (map[string]any, error) { + s.emitAudit(ctx, r, store.AuditEvent{ + TenantID: t.ID, Action: "erp.webhook", TargetID: ev.Name, TargetType: ev.Doctype, ActorType: "service", + Metadata: map[string]interface{}{"event": ev.Event, "customer": ev.Customer}, + }) + switch ev.Event { + case erp.EventSalesOrderSubmit: + for _, it := range ev.Items { + prod := s.productForSKU(ctx, it.ItemCode) + if prod == nil { + s.Log.Warn("sales order item without catalog product", "sku", it.ItemCode, "tenant_id", t.ID) + continue + } + qty := it.Qty + if qty <= 0 { + qty = 1 + } + if _, err := s.Store.UpsertSubscription(ctx, store.Subscription{ + TenantID: t.ID, Product: prod.Key, SKU: it.ItemCode, Plan: planForSKU(it.ItemCode), Seats: int(qty), + Status: store.SubscriptionActive, ErpSalesOrder: ev.Name, ErpSubscription: ev.Subscription, + }); err != nil { + return nil, err + } + } + t2, err := s.recomputeEntitlements(ctx, r, t, "erp:"+ev.Name) + if err != nil { + return nil, err + } + return map[string]any{"status": "applied", "tenant_status": t2.Status}, nil + + case erp.EventInvoiceOverdue: + if t.Status == store.StatusDemo || t.Status == store.StatusArchived || t.Status == store.StatusHalted { + return map[string]any{"status": "ignored", "tenant_status": t.Status}, nil + } + next := store.StatusWarning + if ev.DaysOverdue >= s.restrictAfterDays() { + next = store.StatusRestricted + } + if ev.DaysOverdue >= s.haltAfterDays() { + next = store.StatusHalted + } + if rank(next) <= rank(t.Status) && t.Status != store.StatusTrial && t.Status != store.StatusActive { + return map[string]any{"status": "unchanged", "tenant_status": t.Status}, nil + } + t2, err := s.transition(ctx, r, t, next, "erp:invoice_overdue:"+ev.Name) + if err != nil { + return nil, err + } + return map[string]any{"status": "applied", "tenant_status": t2.Status}, nil + + case erp.EventPaymentEntrySubmit: + if t.Status != store.StatusWarning && t.Status != store.StatusRestricted && t.Status != store.StatusFrozen && t.Status != store.StatusHalted { + return map[string]any{"status": "unchanged", "tenant_status": t.Status}, nil + } + subs, err := s.Store.ListSubscriptions(ctx, t.ID) + if err != nil { + return nil, err + } + if !hasActive(subs) { + return map[string]any{"status": "unchanged", "tenant_status": t.Status, "reason": "no_active_subscription"}, nil + } + t2, err := s.transition(ctx, r, t, store.StatusActive, "erp:payment:"+ev.Name) + if err != nil { + return nil, err + } + return map[string]any{"status": "applied", "tenant_status": t2.Status}, nil + + case erp.EventSubscriptionCancel: + subs, err := s.Store.ListSubscriptions(ctx, t.ID) + if err != nil { + return nil, err + } + for _, sub := range subs { + if sub.Status != store.SubscriptionActive { + continue + } + if ev.Subscription != "" && sub.ErpSubscription != ev.Subscription && sub.ErpSalesOrder != ev.Name { + continue + } + sub.Status = store.SubscriptionCancelled + if _, err := s.Store.UpsertSubscription(ctx, sub); err != nil { + return nil, err + } + } + t2, err := s.recomputeEntitlements(ctx, r, t, "erp:cancel:"+ev.Name) + if err != nil { + return nil, err + } + return map[string]any{"status": "applied", "tenant_status": t2.Status}, nil + } + return map[string]any{"status": "ignored", "reason": "unknown_event"}, nil +} + +// applySubscriptions mirrors the ERP Subscription list (reconcile path). +func (s *Server) applySubscriptions(ctx context.Context, t *store.Tenant, subs []erp.Subscription) (*store.Tenant, bool, error) { + changed := false + local, err := s.Store.ListSubscriptions(ctx, t.ID) + if err != nil { + return nil, false, err + } + seen := map[string]bool{} + for _, es := range subs { + status := store.SubscriptionActive + switch strings.ToLower(es.Status) { + case "cancelled", "canceled", "completed": + status = store.SubscriptionCancelled + } + for _, pl := range es.Plans { + prod := s.productForSKU(ctx, pl.Plan) + if prod == nil { + continue + } + key := pl.Plan + "|" + es.SalesOrder + seen[key] = true + qty := int(pl.Qty) + if qty <= 0 { + qty = 1 + } + cur := findSub(local, pl.Plan, es.SalesOrder) + if cur != nil && cur.Status == status && cur.Seats == qty && cur.ErpSubscription == es.Name { + continue + } + if _, err := s.Store.UpsertSubscription(ctx, store.Subscription{ + TenantID: t.ID, Product: prod.Key, SKU: pl.Plan, Plan: planForSKU(pl.Plan), Seats: qty, Status: status, + ErpSalesOrder: es.SalesOrder, ErpSubscription: es.Name, + }); err != nil { + return nil, false, err + } + changed = true + } + } + // Local active rows the ERP no longer lists → cancelled. + for _, l := range local { + if l.Status == store.SubscriptionActive && l.ErpSubscription != "" && !seen[l.SKU+"|"+l.ErpSalesOrder] { + l.Status = store.SubscriptionCancelled + if _, err := s.Store.UpsertSubscription(ctx, l); err != nil { + return nil, false, err + } + changed = true + } + } + if !changed { + return t, false, nil + } + t2, err := s.recomputeEntitlements(ctx, nil, t, "erp:reconcile") + return t2, true, err +} + +func findSub(list []store.Subscription, sku, so string) *store.Subscription { + for i := range list { + if list[i].SKU == sku && list[i].ErpSalesOrder == so { + return &list[i] + } + } + return nil +} + +func hasActive(subs []store.Subscription) bool { + for _, sub := range subs { + if sub.Status == store.SubscriptionActive { + return true + } + } + return false +} + +// recomputeEntitlements derives tenant_products from active subscriptions +// and moves the tenant to active (has subscriptions) or halted (none). +func (s *Server) recomputeEntitlements(ctx context.Context, r *http.Request, t *store.Tenant, source string) (*store.Tenant, error) { + subs, err := s.Store.ListSubscriptions(ctx, t.ID) + if err != nil { + return nil, err + } + products, err := s.Store.ListProducts(ctx, true) + if err != nil { + return nil, err + } + existing, err := s.Store.ListTenantProducts(ctx, t.ID) + if err != nil { + return nil, err + } + best := "" + for _, p := range products { + cfg := map[string]interface{}{"source": "erp"} + seats := 0 + skus := []string{} + active := false + addons := map[string]int{} + for _, sub := range subs { + if sub.Status != store.SubscriptionActive || sub.Product != p.Key { + continue + } + active = true + skus = append(skus, sub.SKU) + if addon := addonForSKU(&p, sub.SKU); addon != nil { + addons[addon.LimitKey] += sub.Seats + } else { + seats += sub.Seats + } + if rankPlan(sub.Plan) > rankPlan(best) { + best = sub.Plan + } + } + if active { + sort.Strings(skus) + cfg["skus"] = skus + if seats > 0 { + cfg["seats"] = seats + } + for k, v := range addons { + cfg[k] = v + } + tp, err := s.Store.UpsertTenantProduct(ctx, store.TenantProduct{TenantID: t.ID, Product: p.Key, Enabled: true, Config: cfg}) + if err != nil { + return nil, err + } + s.emitAudit(ctx, r, store.AuditEvent{TenantID: t.ID, Action: "entitlement.granted", TargetID: p.Key, TargetType: "product", + ActorType: "service", Metadata: map[string]interface{}{"config": cfg, "source": source}}) + s.provisionProduct(ctx, r, t, &p, tp) + continue + } + // no active subscription: disable only ERP-sourced grants (trials stay) + for _, e := range existing { + if e.Product == p.Key && e.Enabled && e.Config["source"] == "erp" { + e.Enabled = false + if _, err := s.Store.UpsertTenantProduct(ctx, e); err != nil { + return nil, err + } + s.emitAudit(ctx, r, store.AuditEvent{TenantID: t.ID, Action: "entitlement.revoked", TargetID: p.Key, TargetType: "product", + ActorType: "service", Metadata: map[string]interface{}{"source": source}}) + } + } + } + upd := store.TenantUpdate{} + next := t.Status + if hasActive(subs) { + if best != "" && best != t.Plan { + upd.Plan = &best + } + if t.Status != store.StatusActive && t.Status != store.StatusDemo { + next = store.StatusActive + } + } else if t.Status == store.StatusActive || t.Status == store.StatusWarning || t.Status == store.StatusRestricted || t.Status == store.StatusFrozen { + next = store.StatusHalted + } + if next != t.Status { + upd.Status = &next + } + if upd.Status == nil && upd.Plan == nil { + return t, nil + } + t2, err := s.Store.UpdateTenant(ctx, t.ID, upd) + if err != nil { + return nil, err + } + if upd.Status != nil { + s.emitAudit(ctx, r, store.AuditEvent{TenantID: t.ID, Action: "tenant.status_changed", TargetID: t.ID, TargetType: "tenant", + ActorType: "service", Metadata: map[string]interface{}{"from": t.Status, "to": t2.Status, "source": source}}) + s.syncTenantStatus(ctx, r, t2) + } + return t2, nil +} + +// transition moves a tenant to `next` with audit + Keycloak sync. +func (s *Server) transition(ctx context.Context, r *http.Request, t *store.Tenant, next, source string) (*store.Tenant, error) { + if t.Status == next { + return t, nil + } + t2, err := s.Store.UpdateTenant(ctx, t.ID, store.TenantUpdate{Status: ptrStr(next)}) + if err != nil { + return nil, err + } + s.emitAudit(ctx, r, store.AuditEvent{TenantID: t.ID, Action: "tenant.status_changed", TargetID: t.ID, TargetType: "tenant", + ActorType: "service", Metadata: map[string]interface{}{"from": t.Status, "to": next, "source": source}}) + s.syncTenantStatus(ctx, r, t2) + return t2, nil +} + +// productForSKU finds the product selling sku (as base SKU or add-on SKU). +func (s *Server) productForSKU(ctx context.Context, sku string) *store.Product { + products, err := s.Store.ListProducts(ctx, true) + if err != nil { + return nil + } + for i := range products { + p := products[i] + for _, x := range p.SKUs { + if x == sku { + return &p + } + } + if addonForSKU(&p, sku) != nil { + return &p + } + } + return nil +} + +func addonForSKU(p *store.Product, sku string) *store.ProductAddon { + for i := range p.Addons { + for _, x := range p.Addons[i].SKUs { + if x == sku { + a := p.Addons[i] + if a.LimitKey == "" { + a.LimitKey = a.ID + } + return &a + } + } + } + return nil +} + +// planForSKU maps the SKU tier suffix onto the plan names of the catalog. +func planForSKU(sku string) string { + switch { + case strings.HasSuffix(sku, "-ENT"): + return "enterprise" + case strings.HasSuffix(sku, "-BUS"): + return "business" + case strings.HasSuffix(sku, "-STD"): + return "standard" + } + return "" +} + +func rankPlan(p string) int { + switch p { + case "enterprise": + return 3 + case "business": + return 2 + case "standard": + return 1 + } + return 0 +} + +// rank orders the ladder for "never move backwards on overdue" checks. +func rank(status string) int { + switch status { + case store.StatusActive, store.StatusTrial, store.StatusDemo: + return 0 + case store.StatusWarning: + return 1 + case store.StatusRestricted, store.StatusFrozen: + return 2 + case store.StatusHalted: + return 3 + case store.StatusArchived: + return 4 + } + return 0 +} + +func (s *Server) restrictAfterDays() int { + if d := s.cfg().RestrictAfterDays; d > 0 { + return d + } + return 14 +} + +func (s *Server) haltAfterDays() int { + if d := s.cfg().HaltAfterDays; d > 0 { + return d + } + return 30 +} + +func (s *Server) exportWindowDays() int { + if d := s.cfg().ExportWindowDays; d > 0 { + return d + } + return 30 +} + +// ─── reconcile ──────────────────────────────────────────────────────────── + +// ReconcileReport summarises one reconcile pass. +type ReconcileReport struct { + Tenants int `json:"tenants"` + ErpChecked int `json:"erp_checked"` + Changed []string `json:"changed"` + Escalated []string `json:"escalated"` + Errors []string `json:"errors,omitempty"` + ErpAvailable bool `json:"erp_available"` +} + +// Reconcile walks every tenant: mirrors ERP subscriptions (when the ERP +// client is configured) and applies time-based ladder steps — trial expiry, +// warning → restricted, restricted → halted, halted → archived. +func (s *Server) Reconcile(ctx context.Context) ReconcileReport { + rep := ReconcileReport{Changed: []string{}, Escalated: []string{}, ErpAvailable: s.ERP.Enabled()} + now := s.now() + cursor := "" + for { + page, next, err := s.Store.ListTenants(ctx, store.TenantFilter{Limit: 200, Cursor: cursor}) + if err != nil { + rep.Errors = append(rep.Errors, "list tenants: "+err.Error()) + return rep + } + for i := range page { + t := &page[i] + rep.Tenants++ + if s.ERP.Enabled() && t.ErpCustomerID != "" { + subs, err := s.ERP.ListSubscriptions(ctx, t.ErpCustomerID) + if err != nil { + rep.Errors = append(rep.Errors, t.Slug+": erp: "+err.Error()) + } else { + rep.ErpChecked++ + t2, changed, err := s.applySubscriptions(ctx, t, subs) + if err != nil { + rep.Errors = append(rep.Errors, t.Slug+": apply: "+err.Error()) + } else { + if changed { + rep.Changed = append(rep.Changed, t.Slug) + } + t = t2 + } + } + } + if next, why := s.escalation(t, now); next != "" { + if _, err := s.transition(ctx, nil, t, next, "reconcile:"+why); err != nil { + rep.Errors = append(rep.Errors, t.Slug+": escalate: "+err.Error()) + } else { + rep.Escalated = append(rep.Escalated, t.Slug+"→"+next) + } + } + } + if next == "" { + break + } + cursor = next + } + return rep +} + +// escalation returns the time-based next rung for t at `now` ("" = none). +func (s *Server) escalation(t *store.Tenant, now time.Time) (string, string) { + day := 24 * time.Hour + age := now.Sub(t.StatusChangedAt) + switch t.Status { + case store.StatusTrial: + if t.TrialEndsAt != nil && now.After(*t.TrialEndsAt) { + return store.StatusRestricted, "trial_expired" + } + case store.StatusWarning: + if age >= time.Duration(s.restrictAfterDays())*day { + return store.StatusRestricted, "grace_over" + } + case store.StatusRestricted, store.StatusFrozen: + // non-payment and expired trials alike: read-only for the rest of the + // grace window, then halted (no access), then the export window. + if age >= time.Duration(s.haltAfterDays()-s.restrictAfterDays())*day { + return store.StatusHalted, "hard_stop" + } + case store.StatusHalted: + if age >= time.Duration(s.exportWindowDays())*day { + return store.StatusArchived, "export_window_over" + } + } + return "", "" +} + +// erpReconcileNow — POST /v1/internal/erp/reconcile (ops / tests). +func (s *Server) erpReconcileNow(w http.ResponseWriter, r *http.Request) { + ctx, cancel := context.WithTimeout(r.Context(), 60*time.Second) + defer cancel() + writeJSON(w, http.StatusOK, s.Reconcile(ctx)) +} + +// erpStatus — GET /v1/internal/erp/status. +func (s *Server) erpStatus(w http.ResponseWriter, r *http.Request) { + ctx, cancel := context.WithTimeout(r.Context(), 5*time.Second) + defer cancel() + pending, err := s.Store.PendingOutbox(ctx) + if err != nil { + writeError(w, http.StatusInternalServerError, "internal", err.Error()) + return + } + writeJSON(w, http.StatusOK, map[string]any{ + "erp_configured": s.ERP.Enabled(), + "webhook_enabled": s.cfg().ErpWebhookSecret != "", + "outbox_pending": pending, + "licences_enabled": s.Licences != nil, + }) +} + +// listSubscriptions — GET /v1/subscriptions?tenant_id= +func (s *Server) listSubscriptions(w http.ResponseWriter, r *http.Request) { + tenantID := r.URL.Query().Get("tenant_id") + if tenantID == "" { + writeError(w, http.StatusBadRequest, "invalid_input", "tenant_id query param is required") + return + } + ctx, cancel := context.WithTimeout(r.Context(), 2*time.Second) + defer cancel() + list, err := s.Store.ListSubscriptions(ctx, tenantID) + if err != nil { + if mapStoreError(w, err) { + return + } + writeError(w, http.StatusInternalServerError, "internal", err.Error()) + return + } + writeJSON(w, http.StatusOK, map[string]any{"items": list}) +} diff --git a/internal/server/erp_test.go b/internal/server/erp_test.go new file mode 100644 index 0000000..650b24f --- /dev/null +++ b/internal/server/erp_test.go @@ -0,0 +1,372 @@ +package server_test + +import ( + "bytes" + "encoding/json" + "net/http" + "net/http/httptest" + "testing" + "time" + + "git.breakpilot.com/platform/tenant-registry/internal/erp" + "git.breakpilot.com/platform/tenant-registry/internal/erpmock" + "git.breakpilot.com/platform/tenant-registry/internal/store" +) + +// webhook posts a signed ERP event to the registry. +func (h *testHarness) webhook(t *testing.T, ev erp.WebhookEvent, eventID string) (*http.Response, []byte) { + t.Helper() + body, _ := json.Marshal(ev) + req, _ := http.NewRequest("POST", h.srv.URL+"/v1/internal/erp/webhook", bytes.NewReader(body)) + req.Header.Set("Content-Type", "application/json") + req.Header.Set(erp.HeaderSignature, erp.Sign(testWebhookSecret, body)) + if eventID != "" { + req.Header.Set(erp.HeaderEventID, eventID) + } + resp, err := http.DefaultClient.Do(req) + if err != nil { + t.Fatal(err) + } + defer func() { _ = resp.Body.Close() }() + var buf bytes.Buffer + _, _ = buf.ReadFrom(resp.Body) + return resp, buf.Bytes() +} + +func newTenant(t *testing.T, h *testHarness, slug string) *store.Tenant { + t.Helper() + resp, raw := h.do("POST", "/v1/tenants", map[string]any{"slug": slug, "name": slug + " GmbH"}) + if resp.StatusCode != 201 { + t.Fatalf("create %s: %d %s", slug, resp.StatusCode, raw) + } + return decode[struct { + Tenant *store.Tenant `json:"tenant"` + }](t, raw).Tenant +} + +func getTenant(t *testing.T, h *testHarness, id string) store.Tenant { + t.Helper() + _, raw := h.do("GET", "/v1/tenants/"+id, nil) + return decode[store.Tenant](t, raw) +} + +func TestErpWebhook_ladder(t *testing.T) { + eachStore(t, func(t *testing.T, h *testHarness) { + tn := newTenant(t, h, "erp-co") + // link the ERP customer as the outbox worker would + if _, err := h.store.UpdateTenant(t.Context(), tn.ID, store.TenantUpdate{ErpCustomerID: ptr("CUST-00001")}); err != nil { + t.Fatal(err) + } + + // unsigned → 401 + body, _ := json.Marshal(erp.WebhookEvent{Event: erp.EventSalesOrderSubmit}) + req, _ := http.NewRequest("POST", h.srv.URL+"/v1/internal/erp/webhook", bytes.NewReader(body)) + if resp, _ := http.DefaultClient.Do(req); resp.StatusCode != http.StatusUnauthorized { + t.Fatalf("unsigned: %d", resp.StatusCode) + } + + // sales order: Prüfwerk business + 2 Werkbank runners + Firmwerk std → active, entitlements from ERP + so := erp.WebhookEvent{Event: erp.EventSalesOrderSubmit, Doctype: "Sales Order", Name: "SAL-ORD-00001", Customer: "CUST-00001", + Subscription: "SUB-00001", + Items: []erp.WebhookItem{{ItemCode: "CRA-CSA-CLD-BUS", Qty: 5}, {ItemCode: "CRA-WBK-CLD-BUS", Qty: 2}, {ItemCode: "DEV-FWK-CLD-STD", Qty: 3}, {ItemCode: "PLT-CORE-CLD-BUS", Qty: 1}}} + resp, raw := h.webhook(t, so, "evt-1") + if resp.StatusCode != 200 { + t.Fatalf("sales order: %d %s", resp.StatusCode, raw) + } + got := getTenant(t, h, tn.ID) + if got.Status != "active" || got.Plan != "business" { + t.Fatalf("after SO: status=%s plan=%s", got.Status, got.Plan) + } + if h.kcMock.Status["erp-co"] != "active" { + t.Fatalf("keycloak not synced: %q", h.kcMock.Status["erp-co"]) + } + chk := check(t, h, map[string]any{"tenant_id": tn.ID, "product": "pruefwerk", "addon": "werkbank"}) + if !chk.Allowed || toF(chk.Limits["runners"]) != 2 || toF(chk.Limits["seats"]) != 5 { + t.Fatalf("pruefwerk entitlement: %+v", chk) + } + if chk := check(t, h, map[string]any{"tenant_id": tn.ID, "product": "firmwerk"}); !chk.Allowed || toF(chk.Limits["seats"]) != 3 { + t.Fatalf("firmwerk entitlement: %+v", chk) + } + if chk := check(t, h, map[string]any{"tenant_id": tn.ID, "product": "werkpilot"}); chk.Allowed { + t.Fatalf("werkpilot must not be entitled: %+v", chk) + } + _, raw = h.do("GET", "/v1/subscriptions?tenant_id="+tn.ID, nil) + subs := decode[struct { + Items []store.Subscription `json:"items"` + }](t, raw).Items + if len(subs) != 3 { // PLT-CORE has no product → not mirrored + t.Fatalf("subscriptions = %d: %+v", len(subs), subs) + } + + // duplicate delivery is a no-op + if resp, raw := h.webhook(t, so, "evt-1"); resp.StatusCode != 200 || !bytes.Contains(raw, []byte(`"duplicate"`)) { + t.Fatalf("duplicate: %d %s", resp.StatusCode, raw) + } + + // overdue 3 days → warning; 20 days → restricted (read-only) + if resp, raw := h.webhook(t, erp.WebhookEvent{Event: erp.EventInvoiceOverdue, Doctype: "Sales Invoice", Name: "INV-1", Customer: "CUST-00001", DaysOverdue: 3}, "evt-2"); resp.StatusCode != 200 { + t.Fatalf("overdue: %d %s", resp.StatusCode, raw) + } + if got = getTenant(t, h, tn.ID); got.Status != "warning" { + t.Fatalf("after overdue 3d: %s", got.Status) + } + h.webhook(t, erp.WebhookEvent{Event: erp.EventInvoiceOverdue, Doctype: "Sales Invoice", Name: "INV-1", Customer: "CUST-00001", DaysOverdue: 20}, "evt-3") + if got = getTenant(t, h, tn.ID); got.Status != "restricted" { + t.Fatalf("after overdue 20d: %s", got.Status) + } + if chk := check(t, h, map[string]any{"tenant_id": tn.ID, "product": "pruefwerk"}); !chk.Allowed || !chk.ReadOnly { + t.Fatalf("restricted must be read-only: %+v", chk) + } + // a later, shorter overdue never moves the tenant back up + h.webhook(t, erp.WebhookEvent{Event: erp.EventInvoiceOverdue, Doctype: "Sales Invoice", Name: "INV-2", Customer: "CUST-00001", DaysOverdue: 1}, "evt-4") + if got = getTenant(t, h, tn.ID); got.Status != "restricted" { + t.Fatalf("overdue must not lift restriction: %s", got.Status) + } + + // payment → active again + h.webhook(t, erp.WebhookEvent{Event: erp.EventPaymentEntrySubmit, Doctype: "Payment Entry", Name: "PAY-1", Customer: "CUST-00001", Invoice: "INV-1"}, "evt-5") + if got = getTenant(t, h, tn.ID); got.Status != "active" { + t.Fatalf("after payment: %s", got.Status) + } + + // cancel the subscription → halted, ERP-sourced entitlements disabled + h.webhook(t, erp.WebhookEvent{Event: erp.EventSubscriptionCancel, Doctype: "Subscription", Name: "SUB-00001", Customer: "CUST-00001", Subscription: "SUB-00001"}, "evt-6") + if got = getTenant(t, h, tn.ID); got.Status != "halted" { + t.Fatalf("after cancel: %s", got.Status) + } + if chk := check(t, h, map[string]any{"tenant_id": tn.ID, "product": "pruefwerk"}); chk.Allowed || chk.Reason != "tenant_halted" { + t.Fatalf("halted: %+v", chk) + } + // payment after cancel does not reactivate (no active subscription) + h.webhook(t, erp.WebhookEvent{Event: erp.EventPaymentEntrySubmit, Doctype: "Payment Entry", Name: "PAY-2", Customer: "CUST-00001"}, "evt-7") + if got = getTenant(t, h, tn.ID); got.Status != "halted" { + t.Fatalf("payment without subscription: %s", got.Status) + } + + // unknown customer → 202 ignored; unknown event → ignored + if resp, raw := h.webhook(t, erp.WebhookEvent{Event: erp.EventPaymentEntrySubmit, Name: "PAY-9", Customer: "CUST-NOPE"}, "evt-8"); resp.StatusCode != 202 { + t.Fatalf("unknown customer: %d %s", resp.StatusCode, raw) + } + if _, raw := h.webhook(t, erp.WebhookEvent{Event: "bogus", Name: "X", TenantID: tn.ID}, "evt-9"); !bytes.Contains(raw, []byte("unknown_event")) { + t.Fatalf("unknown event: %s", raw) + } + _, raw = h.do("GET", "/v1/audit?tenant_id="+tn.ID+"&limit=100", nil) + for _, a := range []string{"erp.webhook", "entitlement.granted", "entitlement.revoked", "tenant.status_changed"} { + if !containsAction(raw, a) { + t.Fatalf("audit missing %s", a) + } + } + }) +} + +func TestErpWebhook_disabledWithoutSecret(t *testing.T) { + h := newMemoryHarness(t) + defer h.Close() + h.app.Cfg.ErpWebhookSecret = "" + if resp, _ := h.webhook(t, erp.WebhookEvent{Event: "x"}, ""); resp.StatusCode != http.StatusServiceUnavailable { + t.Fatalf("got %d", resp.StatusCode) + } +} + +func TestUsageEvents_idempotentAndQueued(t *testing.T) { + eachStore(t, func(t *testing.T, h *testHarness) { + tn := newTenant(t, h, "usage-co") + ev := map[string]any{"idempotency_key": "scan-1", "tenant_id": tn.ID, "product": "pruefwerk", "metric": "scan.completed", "quantity": 1, + "occurred_at": time.Now().UTC().Format(time.RFC3339), "properties": map[string]any{"scan_type": "sbom"}} + resp, raw := h.do("POST", "/v1/usage/events", ev) + if resp.StatusCode != 202 || !bytes.Contains(raw, []byte(`"accepted":1`)) { + t.Fatalf("first: %d %s", resp.StatusCode, raw) + } + // batch with the duplicate + a new one + a rejected one + resp, raw = h.do("POST", "/v1/usage/events", map[string]any{"events": []map[string]any{ + ev, + {"idempotency_key": "scan-2", "tenant_id": tn.ID, "product": "pruefwerk", "metric": "scan.completed"}, + {"idempotency_key": "bad", "tenant_id": tn.ID, "product": "nope", "metric": "x"}, + }}) + if resp.StatusCode != 202 || !bytes.Contains(raw, []byte(`"accepted":1`)) || !bytes.Contains(raw, []byte(`"duplicates":1`)) || !bytes.Contains(raw, []byte(`unknown_product`)) { + t.Fatalf("batch: %d %s", resp.StatusCode, raw) + } + // array form + bad timestamp + resp, raw = h.do("POST", "/v1/usage/events", []map[string]any{{"idempotency_key": "scan-3", "tenant_id": tn.ID, "product": "pruefwerk", "metric": "target.added", "occurred_at": "yesterday"}}) + if resp.StatusCode != 400 || !bytes.Contains(raw, []byte("RFC3339")) { + t.Fatalf("bad ts: %d %s", resp.StatusCode, raw) + } + resp, raw = h.do("GET", "/v1/usage/events?tenant_id="+tn.ID+"&product=pruefwerk&limit=10", nil) + items := decode[struct { + Items []store.UsageEvent `json:"items"` + }](t, raw).Items + if resp.StatusCode != 200 || len(items) != 2 { + t.Fatalf("list: %d %d", resp.StatusCode, len(items)) + } + if _, raw := h.do("GET", "/v1/usage/events?tenant_id="+tn.ID+"&metric=scan.completed&since="+time.Now().Add(-time.Hour).UTC().Format(time.RFC3339), nil); !bytes.Contains(raw, []byte("scan-1")) { + t.Fatalf("filtered list: %s", raw) + } + for _, q := range []string{"", "?tenant_id=" + tn.ID + "&limit=0", "?tenant_id=" + tn.ID + "&since=bad"} { + if resp, _ := h.do("GET", "/v1/usage/events"+q, nil); resp.StatusCode != 400 { + t.Fatalf("list %q: %d", q, resp.StatusCode) + } + } + // outbox: customer upsert (from create) + 2 usage records pending + _, raw = h.do("GET", "/v1/internal/erp/status", nil) + if !bytes.Contains(raw, []byte(`"outbox_pending":3`)) { + t.Fatalf("status: %s", raw) + } + }) +} + +// TestOutbox_drainsIntoErpMock runs the worker against the ERP mock: customer +// upsert links erp_customer_id, usage records + leads land in the mock, the +// reconcile path mirrors mock subscriptions, and fired webhooks come back. +func TestOutbox_drainsIntoErpMock(t *testing.T) { + eachStore(t, func(t *testing.T, h *testHarness) { + mock := erpmock.New(erpmock.Config{APIKey: "k", APISecret: "s", WebhookURL: h.srv.URL + "/v1/internal/erp/webhook", WebhookSecret: testWebhookSecret}) + ms := httptest.NewServer(mock) + defer ms.Close() + h.app.ERP = erp.New(erp.Config{BaseURL: ms.URL, APIKey: "k", APISecret: "s"}) + + tn := newTenant(t, h, "mock-co") + h.do("POST", "/v1/usage/events", map[string]any{"idempotency_key": "u-1", "tenant_id": tn.ID, "product": "pruefwerk", "metric": "scan.completed"}) + h.do("POST", "/v1/catalog/request", map[string]any{"tenant_id": tn.ID, "product": "werkpilot"}) + + // first drain: customer upsert succeeds, usage fails (no customer yet at claim time) → retried + if _, err := h.app.DrainOutbox(t.Context()); err != nil { + t.Fatal(err) + } + got := getTenant(t, h, tn.ID) + if got.ErpCustomerID == "" { + t.Fatalf("erp_customer_id not linked: %+v", got) + } + // force the retry due now and drain again + h.app.Now = func() time.Time { return time.Now().Add(3 * time.Hour) } + if _, err := h.app.DrainOutbox(t.Context()); err != nil { + t.Fatal(err) + } + h.app.Now = nil + _, raw := h.do("GET", "/v1/internal/erp/status", nil) + if !bytes.Contains(raw, []byte(`"outbox_pending":0`)) { + t.Fatalf("outbox not drained: %s", raw) + } + _, raw = h.do("GET", "/v1/usage/events?tenant_id="+tn.ID, nil) + if !bytes.Contains(raw, []byte("erp_synced_at")) { + t.Fatalf("usage not marked synced: %s", raw) + } + reqs := mockRequests(t, ms.URL) + if reqs["POST Usage Record"] != 1 || reqs["POST Lead"] != 1 || reqs["POST Customer"] != 1 { + t.Fatalf("mock requests: %v", reqs) + } + + // fire a sales order from the mock → webhook → tenant active + fire := func(trigger string, body map[string]any) []byte { + buf, _ := json.Marshal(body) + resp, err := http.Post(ms.URL+"/_mock/fire/"+trigger, "application/json", bytes.NewReader(buf)) + if err != nil { + t.Fatal(err) + } + defer func() { _ = resp.Body.Close() }() + var out bytes.Buffer + _, _ = out.ReadFrom(resp.Body) + if resp.StatusCode != 200 { + t.Fatalf("fire %s: %d %s", trigger, resp.StatusCode, out.String()) + } + return out.Bytes() + } + fire("sales-order-submit", map[string]any{"tenant_id": tn.ID, "items": []map[string]any{{"item_code": "DEV-WP-CLD-STD", "qty": 4}}}) + if got = getTenant(t, h, tn.ID); got.Status != "active" || got.Plan != "standard" { + t.Fatalf("after fired SO: %+v", got) + } + fire("invoice-overdue", map[string]any{"tenant_id": tn.ID, "days_overdue": 2, "amount": 99}) + if got = getTenant(t, h, tn.ID); got.Status != "warning" { + t.Fatalf("after fired overdue: %s", got.Status) + } + fire("payment-entry", map[string]any{"tenant_id": tn.ID, "amount": 99}) + if got = getTenant(t, h, tn.ID); got.Status != "active" { + t.Fatalf("after fired payment: %s", got.Status) + } + + // reconcile against the mock: cancel the subscription in ERP only, then reconcile → halted + fire("subscription-cancel", map[string]any{"tenant_id": tn.ID}) + if got = getTenant(t, h, tn.ID); got.Status != "halted" { + t.Fatalf("after fired cancel: %s", got.Status) + } + // new order directly in the mock (no webhook) → reconcile picks it up + mock2 := erp.New(erp.Config{BaseURL: ms.URL, APIKey: "k", APISecret: "s"}) + _ = mock2 + buf, _ := json.Marshal(map[string]any{"party": got.ErpCustomerID, "status": "Active", "sales_order": "SAL-ORD-MANUAL", "plans": []map[string]any{{"plan": "DEV-FWK-CLD-ENT", "qty": 2}}}) + req, _ := http.NewRequest("POST", ms.URL+"/api/resource/Subscription", bytes.NewReader(buf)) + req.Header.Set("Authorization", "token k:s") + if resp, err := http.DefaultClient.Do(req); err != nil || resp.StatusCode != 200 { + t.Fatalf("mock subscription: %v %v", err, resp) + } + _, raw = h.do("POST", "/v1/internal/erp/reconcile", nil) + if !bytes.Contains(raw, []byte(`"changed":["mock-co"]`)) { + t.Fatalf("reconcile: %s", raw) + } + if got = getTenant(t, h, tn.ID); got.Status != "active" || got.Plan != "enterprise" { + t.Fatalf("after reconcile: %+v", got) + } + if chk := check(t, h, map[string]any{"tenant_id": tn.ID, "product": "firmwerk"}); !chk.Allowed || toF(chk.Limits["seats"]) != 2 { + t.Fatalf("firmwerk after reconcile: %+v", chk) + } + // second reconcile: nothing changes + if _, raw = h.do("POST", "/v1/internal/erp/reconcile", nil); !bytes.Contains(raw, []byte(`"changed":[]`)) { + t.Fatalf("idempotent reconcile: %s", raw) + } + }) +} + +func mockRequests(t *testing.T, base string) map[string]int { + t.Helper() + resp, err := http.Get(base + "/_mock/requests") + if err != nil { + t.Fatal(err) + } + defer func() { _ = resp.Body.Close() }() + var out struct { + Requests []erpmock.Request `json:"requests"` + } + _ = json.NewDecoder(resp.Body).Decode(&out) + counts := map[string]int{} + for _, r := range out.Requests { + counts[r.Method+" "+r.Doctype]++ + } + return counts +} + +func TestReconcile_ladderEscalation(t *testing.T) { + eachStore(t, func(t *testing.T, h *testHarness) { + warn := newTenant(t, h, "esc-warning") + h.do("POST", "/v1/tenants/"+warn.ID+"/status", map[string]any{"status": "warning"}) + halted := newTenant(t, h, "esc-halted") + h.do("POST", "/v1/tenants/"+halted.ID+"/status", map[string]any{"status": "halted"}) + trial := newTenant(t, h, "esc-trial") // trial_ends_at = +14d + + // +1 day: nothing + h.app.Now = func() time.Time { return time.Now().Add(24 * time.Hour) } + _, raw := h.do("POST", "/v1/internal/erp/reconcile", nil) + if !bytes.Contains(raw, []byte(`"escalated":[]`)) { + t.Fatalf("day 1: %s", raw) + } + // +15 days: warning → restricted, trial expired → restricted + h.app.Now = func() time.Time { return time.Now().Add(15 * 24 * time.Hour) } + _, raw = h.do("POST", "/v1/internal/erp/reconcile", nil) + if getTenant(t, h, warn.ID).Status != "restricted" || getTenant(t, h, trial.ID).Status != "restricted" { + t.Fatalf("day 15: %s", raw) + } + // +31 days: halted → archived (export window); restricted (ex-warning) → halted + h.app.Now = func() time.Time { return time.Now().Add(31 * 24 * time.Hour) } + _, raw = h.do("POST", "/v1/internal/erp/reconcile", nil) + if getTenant(t, h, halted.ID).Status != "archived" { + t.Fatalf("day 31 halted: %s", raw) + } + if getTenant(t, h, warn.ID).Status != "halted" { + t.Fatalf("day 31 restricted: %s", raw) + } + // expired trial walks the same ladder: restricted → halted + if getTenant(t, h, trial.ID).Status != "halted" { + t.Fatalf("expired trial: %s", getTenant(t, h, trial.ID).Status) + } + h.app.Now = nil + }) +} + +func ptr(s string) *string { return &s } diff --git a/internal/server/licences.go b/internal/server/licences.go new file mode 100644 index 0000000..00506d6 --- /dev/null +++ b/internal/server/licences.go @@ -0,0 +1,277 @@ +package server + +import ( + "context" + "errors" + "net/http" + "time" + + "github.com/go-jose/go-jose/v4" + "github.com/go-jose/go-jose/v4/jwt" + + "git.breakpilot.com/platform/tenant-registry/internal/authn" + "git.breakpilot.com/platform/tenant-registry/internal/licence" + "git.breakpilot.com/platform/tenant-registry/internal/store" +) + +// ─── CLI licences (decision 13) ─────────────────────────────────────────── +// +// `werkpilot login` / `firmwerk login` do the device flow on the realm +// (clients werkpilot-cli / firmwerk-cli, audience tenant-registry) and call +// POST /v1/licences with the user token; the tenant comes from the token's +// tenant-context claims. The CLI stores the JWT, verifies it offline against +// /.well-known/licence-keys.json and phones home hourly via the heartbeat. + +type issueLicenceReq struct { + TenantID string `json:"tenant_id,omitempty"` // service callers only; users get their own tenant + Product string `json:"product"` + Device string `json:"device,omitempty"` + TTLDays int `json:"ttl_days,omitempty"` +} + +type licenceResp struct { + ID string `json:"id"` + Licence string `json:"licence"` + Kid string `json:"kid"` + ExpiresAt time.Time `json:"expires_at"` + Grace licence.GracePolicy `json:"grace"` + Status string `json:"status"` +} + +func (s *Server) licenceKeys(w http.ResponseWriter, _ *http.Request) { + if s.Licences == nil { + writeError(w, http.StatusServiceUnavailable, "licences_disabled", "licence signer not configured") + return + } + w.Header().Set("Cache-Control", "public, max-age=3600") + writeJSON(w, http.StatusOK, jose.JSONWebKeySet{Keys: []jose.JSONWebKey{s.Licences.PublicJWK()}}) +} + +func (s *Server) issueLicence(w http.ResponseWriter, r *http.Request) { + if s.Licences == nil { + writeError(w, http.StatusServiceUnavailable, "licences_disabled", "licence signer not configured") + return + } + var in issueLicenceReq + if !decodeJSON(w, r, &in) { + return + } + p, _ := authn.PrincipalFrom(r.Context()) + subject := "service:" + in.TenantID + if p != nil { + subject = p.Subject + if p.IsUser() { + in.TenantID = p.TenantID + } + } + if in.TenantID == "" || in.Product == "" { + writeError(w, http.StatusBadRequest, "invalid_input", "product is required (tenant_id for service callers)") + return + } + ctx, cancel := context.WithTimeout(r.Context(), 5*time.Second) + defer cancel() + resp, code, kind, msg := s.issue(ctx, r, in, subject) + if code != http.StatusCreated { + writeError(w, code, kind, msg) + return + } + writeJSON(w, http.StatusCreated, resp) +} + +// issue evaluates the entitlement, records the licence row and signs the JWT. +func (s *Server) issue(ctx context.Context, r *http.Request, in issueLicenceReq, subject string) (*licenceResp, int, string, string) { + check, err := s.evaluateEntitlement(ctx, entitlementCheckReq{TenantID: in.TenantID, Product: in.Product}) + if err != nil { + return nil, http.StatusInternalServerError, "internal", err.Error() + } + if !check.Allowed { + return nil, http.StatusForbidden, "not_entitled", "tenant is not entitled to " + in.Product + " (" + check.Reason + ")" + } + t, err := s.Store.GetTenant(ctx, in.TenantID) + if err != nil { + return nil, http.StatusNotFound, "not_found", "tenant not found" + } + ttl := in.TTLDays + if ttl <= 0 { + ttl = s.cfg().LicenceTTLDays + } + if ttl <= 0 { + ttl = 30 + } + now := s.now() + exp := now.Add(time.Duration(ttl) * 24 * time.Hour) + if check.ExpiresAt != nil && check.ExpiresAt.Before(exp) { + exp = check.ExpiresAt.UTC() + } + seats := 0 + if v, ok := check.Limits["seats"]; ok { + seats = int(toFloat(v)) + } + row, err := s.Store.CreateLicence(ctx, store.Licence{ + Kid: s.Licences.KID(), TenantID: t.ID, Product: in.Product, Subject: subject, Device: in.Device, ExpiresAt: exp, + }) + if err != nil { + return nil, http.StatusInternalServerError, "internal", err.Error() + } + heartbeat := "" + if r != nil { + scheme := "https" + if r.TLS == nil && (r.Host == "" || isLoopback(r.Host)) { + scheme = "http" + } + heartbeat = scheme + "://" + r.Host + "/v1/licences/heartbeat" + } + token, err := s.Licences.Issue(licence.Claims{ + Claims: jwt.Claims{Subject: subject, ID: row.ID, Audience: jwt.Audience{in.Product}, + IssuedAt: jwt.NewNumericDate(now), Expiry: jwt.NewNumericDate(exp)}, + TenantID: t.ID, TenantSlug: t.Slug, Product: in.Product, Plan: t.Plan, Seats: seats, Device: in.Device, + Grace: licence.DefaultGrace, Heartbeat: heartbeat, + }) + if err != nil { + return nil, http.StatusInternalServerError, "internal", err.Error() + } + s.emitAudit(ctx, r, store.AuditEvent{TenantID: t.ID, Action: "licence.issued", TargetID: row.ID, TargetType: "licence", + ActorID: subject, Product: in.Product, Metadata: map[string]interface{}{"device": in.Device, "expires_at": exp.Format(time.RFC3339)}}) + return &licenceResp{ID: row.ID, Licence: token, Kid: s.Licences.KID(), ExpiresAt: exp, Grace: licence.DefaultGrace, Status: "ok"}, http.StatusCreated, "", "" +} + +type heartbeatReq struct { + Licence string `json:"licence"` +} + +type heartbeatResp struct { + Status string `json:"status"` // ok | warning | degraded | hard_stop | revoked + TenantStatus string `json:"tenant_status,omitempty"` + ExpiresAt time.Time `json:"expires_at"` + Reason string `json:"reason,omitempty"` + Renewed *licenceResp `json:"renewed,omitempty"` +} + +// licenceHeartbeat — POST /v1/licences/heartbeat (PUBLIC_EXPLICIT; the JWT +// is the credential). Reports the grace state, records last_seen and hands +// out a fresh token when the current one is past half-life and the tenant +// is still entitled. +func (s *Server) licenceHeartbeat(w http.ResponseWriter, r *http.Request) { + if s.Licences == nil { + writeError(w, http.StatusServiceUnavailable, "licences_disabled", "licence signer not configured") + return + } + var in heartbeatReq + if !decodeJSON(w, r, &in) { + return + } + claims, err := s.Licences.Verify(in.Licence) + if err != nil { + writeError(w, http.StatusUnauthorized, "invalid_licence", "licence signature or issuer invalid") + return + } + ctx, cancel := context.WithTimeout(r.Context(), 5*time.Second) + defer cancel() + row, err := s.Store.GetLicence(ctx, claims.ID) + if err != nil { + writeError(w, http.StatusUnauthorized, "unknown_licence", "licence is not on record") + return + } + now := s.now() + _ = s.Store.TouchLicence(ctx, row.ID, now) + out := heartbeatResp{ExpiresAt: row.ExpiresAt} + if row.RevokedAt != nil { + out.Status, out.Reason = "revoked", "licence_revoked" + writeJSON(w, http.StatusOK, out) + return + } + t, err := s.Store.GetTenant(ctx, row.TenantID) + if err != nil { + out.Status, out.Reason = "hard_stop", "tenant_not_found" + writeJSON(w, http.StatusOK, out) + return + } + out.TenantStatus = t.Status + check, err := s.evaluateEntitlement(ctx, entitlementCheckReq{TenantID: t.ID, Product: row.Product}) + if err != nil { + writeError(w, http.StatusInternalServerError, "internal", err.Error()) + return + } + grace := claims.Grace + if grace == (licence.GracePolicy{}) { + grace = licence.DefaultGrace + } + switch { + case !check.Allowed: + // Not entitled any more (halted / archived / cancelled): the token + // keeps working through its own grace ladder, no renewal. + out.Status, out.Reason = grace.State(row.ExpiresAt, now), check.Reason + if out.Status == "ok" { + out.Status = "warning" + } + case check.ReadOnly: + out.Status, out.Reason = "degraded", "tenant_"+t.Status + case t.Status == store.StatusWarning: + out.Status, out.Reason = "warning", "tenant_warning" + default: + out.Status = grace.State(row.ExpiresAt, now) + } + // Renewal: entitled, not read-only, past half-life (or expired). + if check.Allowed && !check.ReadOnly { + half := row.CreatedAt.Add(row.ExpiresAt.Sub(row.CreatedAt) / 2) + if now.After(half) { + renewed, code, _, _ := s.issue(ctx, r, issueLicenceReq{TenantID: t.ID, Product: row.Product, Device: row.Device}, row.Subject) + if code == http.StatusCreated { + out.Renewed = renewed + out.Status = "ok" + out.Reason = "renewed" + } + } + } + writeJSON(w, http.StatusOK, out) +} + +func (s *Server) listLicences(w http.ResponseWriter, r *http.Request) { + tenantID := r.URL.Query().Get("tenant_id") + if p, _ := authn.PrincipalFrom(r.Context()); p.IsUser() { + tenantID = p.TenantID + } + if tenantID == "" { + writeError(w, http.StatusBadRequest, "invalid_input", "tenant_id query param is required") + return + } + ctx, cancel := context.WithTimeout(r.Context(), 2*time.Second) + defer cancel() + list, err := s.Store.ListLicences(ctx, tenantID) + if err != nil { + if mapStoreError(w, err) { + return + } + writeError(w, http.StatusInternalServerError, "internal", err.Error()) + return + } + writeJSON(w, http.StatusOK, map[string]any{"items": list}) +} + +func (s *Server) revokeLicence(w http.ResponseWriter, r *http.Request) { + ctx, cancel := context.WithTimeout(r.Context(), 2*time.Second) + defer cancel() + row, err := s.Store.GetLicence(ctx, r.PathValue("id")) + if err != nil { + if mapStoreError(w, err) { + return + } + writeError(w, http.StatusInternalServerError, "internal", err.Error()) + return + } + if p, _ := authn.PrincipalFrom(r.Context()); p.IsUser() && p.TenantID != row.TenantID { + writeError(w, http.StatusNotFound, "not_found", "licence not found") + return + } + if err := s.Store.RevokeLicence(ctx, row.ID, s.now()); err != nil && !errors.Is(err, store.ErrNotFound) { + writeError(w, http.StatusInternalServerError, "internal", err.Error()) + return + } + s.emitAudit(ctx, r, store.AuditEvent{TenantID: row.TenantID, Action: "licence.revoked", TargetID: row.ID, TargetType: "licence", Product: row.Product}) + row, _ = s.Store.GetLicence(ctx, row.ID) + writeJSON(w, http.StatusOK, row) +} + +func isLoopback(host string) bool { + return len(host) >= 9 && (host[:9] == "127.0.0.1" || host[:9] == "localhost") +} diff --git a/internal/server/licences_test.go b/internal/server/licences_test.go new file mode 100644 index 0000000..cd387df --- /dev/null +++ b/internal/server/licences_test.go @@ -0,0 +1,125 @@ +package server_test + +import ( + "bytes" + "net/http" + "testing" + "time" + + "git.breakpilot.com/platform/tenant-registry/internal/store" +) + +type licenceOut struct { + ID string `json:"id"` + Licence string `json:"licence"` + Kid string `json:"kid"` + ExpiresAt time.Time `json:"expires_at"` + Status string `json:"status"` +} + +type heartbeatOut struct { + Status string `json:"status"` + TenantStatus string `json:"tenant_status"` + Reason string `json:"reason"` + Renewed *licenceOut `json:"renewed"` +} + +func TestLicences_issueHeartbeatRevoke(t *testing.T) { + eachStore(t, func(t *testing.T, h *testHarness) { + tn := newTenant(t, h, "lic-co") + // not entitled yet + if resp, raw := h.do("POST", "/v1/licences", map[string]any{"tenant_id": tn.ID, "product": "werkpilot", "device": "laptop-1"}); resp.StatusCode != http.StatusForbidden { + t.Fatalf("not entitled: %d %s", resp.StatusCode, raw) + } + h.do("POST", "/v1/catalog/trial-request", map[string]any{"tenant_id": tn.ID, "product": "werkpilot"}) + resp, raw := h.do("POST", "/v1/licences", map[string]any{"tenant_id": tn.ID, "product": "werkpilot", "device": "laptop-1"}) + if resp.StatusCode != http.StatusCreated { + t.Fatalf("issue: %d %s", resp.StatusCode, raw) + } + lic := decode[licenceOut](t, raw) + if lic.Licence == "" || lic.Kid == "" || lic.Status != "ok" { + t.Fatalf("licence: %+v", lic) + } + // trial caps expiry at trial end (14 d < 30 d default) + if lic.ExpiresAt.After(time.Now().Add(15 * 24 * time.Hour)) { + t.Fatalf("expiry not capped by trial: %v", lic.ExpiresAt) + } + // jwks published + if resp, raw := h.do("GET", "/.well-known/licence-keys.json", nil); resp.StatusCode != 200 || !bytes.Contains(raw, []byte(`"OKP"`)) || !bytes.Contains(raw, []byte(lic.Kid)) { + t.Fatalf("jwks: %d %s", resp.StatusCode, raw) + } + // heartbeat ok + resp, raw = h.do("POST", "/v1/licences/heartbeat", map[string]any{"licence": lic.Licence}) + hb := decode[heartbeatOut](t, raw) + if resp.StatusCode != 200 || hb.Status != "ok" || hb.TenantStatus != "trial" { + t.Fatalf("heartbeat: %d %+v", resp.StatusCode, hb) + } + // past half-life → renewed + h.app.Now = func() time.Time { return time.Now().Add(10 * 24 * time.Hour) } + _, raw = h.do("POST", "/v1/licences/heartbeat", map[string]any{"licence": lic.Licence}) + hb = decode[heartbeatOut](t, raw) + if hb.Status != "ok" || hb.Renewed == nil || hb.Renewed.Licence == lic.Licence { + t.Fatalf("renewal: %+v", hb) + } + h.app.Now = nil + // restricted tenant → degraded + h.do("POST", "/v1/tenants/"+tn.ID+"/status", map[string]any{"status": "restricted"}) + _, raw = h.do("POST", "/v1/licences/heartbeat", map[string]any{"licence": lic.Licence}) + if hb = decode[heartbeatOut](t, raw); hb.Status != "degraded" { + t.Fatalf("restricted: %+v", hb) + } + h.do("POST", "/v1/tenants/"+tn.ID+"/status", map[string]any{"status": "warning"}) + _, raw = h.do("POST", "/v1/licences/heartbeat", map[string]any{"licence": lic.Licence}) + if hb = decode[heartbeatOut](t, raw); hb.Status != "warning" { + t.Fatalf("warning: %+v", hb) + } + // halted → not entitled: grace ladder on the token's own expiry + h.do("POST", "/v1/tenants/"+tn.ID+"/status", map[string]any{"status": "halted"}) + _, raw = h.do("POST", "/v1/licences/heartbeat", map[string]any{"licence": lic.Licence}) + if hb = decode[heartbeatOut](t, raw); hb.Status != "warning" || hb.Reason != "tenant_halted" { + t.Fatalf("halted: %+v", hb) + } + h.app.Now = func() time.Time { return time.Now().Add(60 * 24 * time.Hour) } + _, raw = h.do("POST", "/v1/licences/heartbeat", map[string]any{"licence": lic.Licence}) + if hb = decode[heartbeatOut](t, raw); hb.Status != "hard_stop" { + t.Fatalf("hard stop: %+v", hb) + } + h.app.Now = nil + // list + revoke + _, raw = h.do("GET", "/v1/licences?tenant_id="+tn.ID, nil) + list := decode[struct { + Items []store.Licence `json:"items"` + }](t, raw).Items + if len(list) != 2 { + t.Fatalf("licences = %d", len(list)) + } + if resp, raw := h.do("POST", "/v1/licences/"+lic.ID+"/revoke", nil); resp.StatusCode != 200 || !bytes.Contains(raw, []byte("revoked_at")) { + t.Fatalf("revoke: %d %s", resp.StatusCode, raw) + } + _, raw = h.do("POST", "/v1/licences/heartbeat", map[string]any{"licence": lic.Licence}) + if hb = decode[heartbeatOut](t, raw); hb.Status != "revoked" { + t.Fatalf("after revoke: %+v", hb) + } + // garbage + unknown + if resp, _ := h.do("POST", "/v1/licences/heartbeat", map[string]any{"licence": "not.a.jwt"}); resp.StatusCode != 401 { + t.Fatalf("garbage: %d", resp.StatusCode) + } + if resp, _ := h.do("POST", "/v1/licences/00000000-0000-0000-0000-000000000000/revoke", nil); resp.StatusCode != 404 { + t.Fatalf("revoke unknown: %d", resp.StatusCode) + } + if resp, _ := h.do("POST", "/v1/licences", map[string]any{"product": "werkpilot"}); resp.StatusCode != 400 { + t.Fatalf("missing tenant: %d", resp.StatusCode) + } + }) +} + +func TestLicences_disabled(t *testing.T) { + h := newMemoryHarness(t) + defer h.Close() + h.app.Licences = nil + for _, c := range []struct{ m, p string }{{"GET", "/.well-known/licence-keys.json"}, {"POST", "/v1/licences"}, {"POST", "/v1/licences/heartbeat"}} { + if resp, _ := h.do(c.m, c.p, map[string]any{}); resp.StatusCode != http.StatusServiceUnavailable { + t.Fatalf("%s %s: %d", c.m, c.p, resp.StatusCode) + } + } +} diff --git a/internal/server/openapi_test.go b/internal/server/openapi_test.go index 8650579..8bcfca2 100644 --- a/internal/server/openapi_test.go +++ b/internal/server/openapi_test.go @@ -48,6 +48,16 @@ func TestOpenAPISpec_loadsAndIsConsistent(t *testing.T) { {"GET", "/v1/tenants?limit=10"}, {"POST", "/v1/tenants/00000000-0000-0000-0000-000000000001/status"}, {"POST", "/v1/internal/entitlements/check"}, + {"POST", "/v1/internal/erp/webhook"}, + {"POST", "/v1/internal/erp/reconcile"}, + {"GET", "/v1/internal/erp/status"}, + {"GET", "/v1/subscriptions?tenant_id=00000000-0000-0000-0000-000000000001"}, + {"POST", "/v1/usage/events"}, + {"GET", "/v1/usage/events?tenant_id=00000000-0000-0000-0000-000000000001"}, + {"POST", "/v1/licences"}, + {"POST", "/v1/licences/heartbeat"}, + {"POST", "/v1/licences/00000000-0000-0000-0000-000000000001/revoke"}, + {"GET", "/.well-known/licence-keys.json"}, } for _, c := range cases { req := newRequest(t, c.method, c.path) diff --git a/internal/server/outbox.go b/internal/server/outbox.go new file mode 100644 index 0000000..3b76d79 --- /dev/null +++ b/internal/server/outbox.go @@ -0,0 +1,152 @@ +package server + +import ( + "context" + "errors" + "fmt" + "time" + + "git.breakpilot.com/platform/tenant-registry/internal/erp" + "git.breakpilot.com/platform/tenant-registry/internal/store" +) + +// ─── ERP outbox worker (M-MIG-7) ─────────────────────────────────────────── +// +// Every ERP write is a row in erp_outbox; the worker drains due rows, calls +// ERPNext and marks them done or schedules a retry with backoff +// (1m, 5m, 15m, 1h, 1h…). Nothing is lost when ERP is down; the reconcile +// job is the safety net for the other direction. + +var outboxBackoff = []time.Duration{time.Minute, 5 * time.Minute, 15 * time.Minute, time.Hour} + +// EnqueueCustomerUpsert is called on tenant creation. +func (s *Server) EnqueueCustomerUpsert(ctx context.Context, t *store.Tenant) { + if _, err := s.Store.EnqueueOutbox(ctx, store.OutboxItem{Kind: store.OutboxCustomerUpsert, TenantID: t.ID, + Payload: map[string]interface{}{"name": t.Name, "slug": t.Slug}}); err != nil { + s.Log.Error("enqueue customer upsert failed", "tenant_id", t.ID, "err", err) + } +} + +// RunOutbox drains the outbox until ctx is done. No-op when ERP is not +// configured (items accumulate and are drained once it is). +func (s *Server) RunOutbox(ctx context.Context, every time.Duration) { + if !s.ERP.Enabled() { + s.Log.Warn("ERP_BASE_URL not set — outbox worker idle (ERP writes accumulate)") + return + } + if every <= 0 { + every = 15 * time.Second + } + t := time.NewTicker(every) + defer t.Stop() + for { + if n, err := s.DrainOutbox(ctx); err != nil { + s.Log.Error("outbox drain failed", "err", err) + } else if n > 0 { + s.Log.Info("outbox drained", "processed", n) + } + select { + case <-ctx.Done(): + return + case <-t.C: + } + } +} + +// DrainOutbox processes one batch; returns the number of items attempted. +func (s *Server) DrainOutbox(ctx context.Context) (int, error) { + now := s.now() + items, err := s.Store.ClaimOutbox(ctx, 50, now, 2*time.Minute) + if err != nil { + return 0, err + } + for _, it := range items { + if err := s.processOutbox(ctx, it); err != nil { + delay := outboxBackoff[min(it.Attempts, len(outboxBackoff)-1)] + s.Log.Warn("outbox item failed", "id", it.ID, "kind", it.Kind, "attempt", it.Attempts+1, "retry_in", delay, "err", err) + if ferr := s.Store.FailOutbox(ctx, it.ID, err.Error(), s.now().Add(delay)); ferr != nil { + return len(items), ferr + } + continue + } + if cerr := s.Store.CompleteOutbox(ctx, it.ID, s.now()); cerr != nil { + return len(items), cerr + } + } + return len(items), nil +} + +func (s *Server) processOutbox(ctx context.Context, it store.OutboxItem) error { + switch it.Kind { + case store.OutboxCustomerUpsert: + t, err := s.Store.GetTenant(ctx, it.TenantID) + if err != nil { + return err + } + if t.ErpCustomerID != "" { + return nil + } + name, err := s.ERP.UpsertCustomer(ctx, erp.Customer{CustomerName: t.Name, TenantID: t.ID, TenantSlug: t.Slug}) + if err != nil { + return err + } + if _, err := s.Store.UpdateTenant(ctx, t.ID, store.TenantUpdate{ErpCustomerID: &name}); err != nil { + return err + } + s.emitAudit(ctx, nil, store.AuditEvent{TenantID: t.ID, Action: "erp.customer_linked", TargetID: name, TargetType: "customer", ActorType: "service"}) + return nil + + case store.OutboxUsageRecord: + t, err := s.Store.GetTenant(ctx, it.TenantID) + if err != nil { + return err + } + if t.ErpCustomerID == "" { + // customer.upsert is still pending — retry later + return errors.New("tenant has no ERP customer yet") + } + id := toFloat(it.Payload["usage_event_id"]) + if _, err := s.ERP.CreateUsageRecord(ctx, erp.UsageRecord{ + Customer: t.ErpCustomerID, TenantID: t.ID, + Product: str(it.Payload["product"]), Metric: str(it.Payload["metric"]), Qty: toFloat(it.Payload["quantity"]), + OccurredAt: str(it.Payload["occurred_at"]), IdempotencyKey: str(it.Payload["idempotency_key"]), + }); err != nil { + return err + } + if id > 0 { + return s.Store.MarkUsageSynced(ctx, []int64{int64(id)}, s.now()) + } + return nil + + case store.OutboxLeadCreate: + _, err := s.ERP.CreateLead(ctx, erp.Lead{ + LeadName: str(it.Payload["lead_name"]), CompanyName: str(it.Payload["company_name"]), EmailID: str(it.Payload["email"]), + Source: "Platform catalog", Notes: str(it.Payload["notes"]), TenantID: it.TenantID, Product: str(it.Payload["product"]), + }) + return err + } + return fmt.Errorf("unknown outbox kind %q", it.Kind) +} + +func str(v interface{}) string { + s, _ := v.(string) + return s +} + +// RunReconcile runs Reconcile every `every` until ctx is done. +func (s *Server) RunReconcile(ctx context.Context, every time.Duration) { + if every <= 0 { + every = 15 * time.Minute + } + t := time.NewTicker(every) + defer t.Stop() + for { + select { + case <-ctx.Done(): + return + case <-t.C: + } + rep := s.Reconcile(ctx) + s.Log.Info("reconcile", "tenants", rep.Tenants, "erp_checked", rep.ErpChecked, "changed", rep.Changed, "escalated", rep.Escalated, "errors", rep.Errors) + } +} diff --git a/internal/server/server.go b/internal/server/server.go index 070b157..096385e 100644 --- a/internal/server/server.go +++ b/internal/server/server.go @@ -8,10 +8,13 @@ import ( "errors" "log/slog" "net/http" + "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/product" "git.breakpilot.com/platform/tenant-registry/internal/store" ) @@ -25,6 +28,25 @@ type Server struct { Auth *authn.Verifier // nil ⇒ AUTH_ENABLED=false, API is open (dev only) Authz *Authz // nil ⇒ AUTHZ_RULES unset, every client may call every route Product product.Provisioner // never nil — main wires Noop when PRODUCT_API_URL is unset + + // M-MIG-7 + ERP *erp.Client // nil / disabled ⇒ outbox accumulates, reconcile idle + Licences *licence.Signer // nil ⇒ licence endpoints return 503 + Now func() time.Time // injectable clock (tests); nil ⇒ time.Now +} + +func (s *Server) now() time.Time { + if s.Now != nil { + return s.Now().UTC() + } + return time.Now().UTC() +} + +func (s *Server) cfg() *config.Config { + if s.Cfg == nil { + return &config.Config{} + } + return s.Cfg } // productProvisioner guarantees the "never nil" invariant the struct documents. @@ -50,6 +72,14 @@ func NewRouter(s *Server) http.Handler { // PUBLIC_EXPLICIT: health + status probes. root.HandleFunc("GET /healthz", s.healthz) root.HandleFunc("GET /readyz", s.readyz) + // PUBLIC_EXPLICIT: ERPNext webhooks carry no Keycloak token — the body + // is HMAC-signed with ERP_WEBHOOK_SECRET (receiver refuses without it). + root.HandleFunc("POST /v1/internal/erp/webhook", s.erpWebhook) + // PUBLIC_EXPLICIT: licence verification keys + heartbeat. The heartbeat + // is authenticated by the licence JWT it carries (offline CLIs hold no + // Keycloak session). + root.HandleFunc("GET /.well-known/licence-keys.json", s.licenceKeys) + root.HandleFunc("POST /v1/licences/heartbeat", s.licenceHeartbeat) mux := http.NewServeMux() @@ -81,6 +111,16 @@ func NewRouter(s *Server) http.Handler { mux.HandleFunc("POST /v1/audit", s.appendAudit) mux.HandleFunc("GET /v1/audit", s.listAudit) + // usage (§9.2) + subscriptions + ERP ops + licences (M-MIG-7) + mux.HandleFunc("POST /v1/usage/events", s.postUsageEvents) + mux.HandleFunc("GET /v1/usage/events", s.listUsageEvents) + mux.HandleFunc("GET /v1/subscriptions", s.listSubscriptions) + mux.HandleFunc("GET /v1/internal/erp/status", s.erpStatus) + mux.HandleFunc("POST /v1/internal/erp/reconcile", s.erpReconcileNow) + mux.HandleFunc("POST /v1/licences", s.issueLicence) + mux.HandleFunc("GET /v1/licences", s.listLicences) + mux.HandleFunc("POST /v1/licences/{id}/revoke", s.revokeLicence) + // keycloak claims refresh — the URL the protocol mapper would call at // token issuance to grab the up-to-date entitlement bundle. Today the // dev realm projects user attributes (set by SyncClaims) — this is diff --git a/internal/server/server_test.go b/internal/server/server_test.go index 5f86a52..adea46c 100644 --- a/internal/server/server_test.go +++ b/internal/server/server_test.go @@ -22,16 +22,20 @@ import ( "git.breakpilot.com/platform/tenant-registry/internal/config" "git.breakpilot.com/platform/tenant-registry/internal/keycloak" + "git.breakpilot.com/platform/tenant-registry/internal/licence" "git.breakpilot.com/platform/tenant-registry/internal/server" "git.breakpilot.com/platform/tenant-registry/internal/store" "git.breakpilot.com/platform/tenant-registry/migrations" ) +const testWebhookSecret = "test-webhook-secret" + // ─── harness ────────────────────────────────────────────────────────────── type testHarness struct { t *testing.T srv *httptest.Server + app *server.Server // the wired server (tests set app.Now / app.ERP / app.Cfg fields) store store.Store tenant *store.Tenant // pre-created acme tenant kcMock *keycloak.Mock @@ -134,14 +138,21 @@ func wireHarness(t *testing.T, s store.Store, seed *store.Tenant) *testHarness { t.Helper() logger := slog.New(slog.NewTextHandler(io.Discard, nil)) mock := keycloak.NewMock() - handler := server.NewRouter(&server.Server{ - Cfg: &config.Config{Env: "dev"}, + signer, err := licence.NewSigner("", "tenant-registry-test") + if err != nil { + t.Fatalf("licence signer: %v", err) + } + app := &server.Server{ + Cfg: &config.Config{Env: "dev", ErpWebhookSecret: testWebhookSecret, LicenceTTLDays: 30}, Log: logger, Store: s, Keycloak: mock, - }) + Licences: signer, + } + handler := server.NewRouter(app) return &testHarness{ t: t, + app: app, srv: httptest.NewServer(handler), store: s, tenant: seed, diff --git a/internal/server/tenants.go b/internal/server/tenants.go index a4172ae..400b830 100644 --- a/internal/server/tenants.go +++ b/internal/server/tenants.go @@ -117,6 +117,12 @@ func (s *Server) createTenant(w http.ResponseWriter, r *http.Request) { }) } + // ERP link: create the Customer through the outbox (retried until ERP + // answers); erp_customer_id is written back by the worker. + if in.Kind != "demo" { + s.EnqueueCustomerUpsert(ctx, t) + } + writeJSON(w, http.StatusCreated, createTenantResp{Tenant: t, InviteURL: inviteURL}) } @@ -447,8 +453,12 @@ func parseDate(p *string) (*time.Time, error) { // emitAudit is a fire-and-forget audit emit. Failures are logged but not // returned to the caller — the actual user-facing operation already succeeded. func (s *Server) emitAudit(ctx context.Context, r *http.Request, ev store.AuditEvent) { - ev.SourceIP = clientIP(r) - ev.UserAgent = r.UserAgent() + if r != nil { + ev.SourceIP = clientIP(r) + ev.UserAgent = r.UserAgent() + } else if ev.ActorType == "" { + ev.ActorType = "system" + } if _, err := s.Store.AppendAudit(ctx, ev); err != nil { s.Log.Warn("audit emit failed", "err", err, "action", ev.Action) } diff --git a/internal/server/usage.go b/internal/server/usage.go new file mode 100644 index 0000000..87197f0 --- /dev/null +++ b/internal/server/usage.go @@ -0,0 +1,174 @@ +package server + +import ( + "context" + "encoding/json" + "errors" + "net/http" + "strconv" + "time" + + "git.breakpilot.com/platform/tenant-registry/internal/authn" + "git.breakpilot.com/platform/tenant-registry/internal/store" +) + +// ─── usage events (PRODUCT_INTEGRATION_SPEC 2.0 §9.2) ──────────────────── +// +// Products push facts continuously; the registry stores them once +// (idempotency_key) and forwards each new one to ERPNext through the outbox +// as a Usage Record. Billing reads ERP; the portal reads the registry. + +type usageEventIn struct { + IdempotencyKey string `json:"idempotency_key"` + TenantID string `json:"tenant_id"` + Product string `json:"product"` + Metric string `json:"metric"` + Quantity *float64 `json:"quantity"` + OccurredAt string `json:"occurred_at"` + Properties map[string]interface{} `json:"properties"` +} + +type usageBatch struct { + Events []usageEventIn `json:"events"` +} + +// postUsageEvents accepts one event, an array, or {"events": [...]}. +func (s *Server) postUsageEvents(w http.ResponseWriter, r *http.Request) { + dec := json.NewDecoder(http.MaxBytesReader(w, r.Body, 1<<20)) + var raw json.RawMessage + if err := dec.Decode(&raw); err != nil { + writeError(w, http.StatusBadRequest, "invalid_json", err.Error()) + return + } + var events []usageEventIn + switch { + case len(raw) > 0 && raw[0] == '[': + if err := json.Unmarshal(raw, &events); err != nil { + writeError(w, http.StatusBadRequest, "invalid_json", err.Error()) + return + } + default: + var b usageBatch + if err := json.Unmarshal(raw, &b); err != nil { + writeError(w, http.StatusBadRequest, "invalid_json", err.Error()) + return + } + if b.Events == nil { + var one usageEventIn + if err := json.Unmarshal(raw, &one); err != nil { + writeError(w, http.StatusBadRequest, "invalid_json", err.Error()) + return + } + events = []usageEventIn{one} + } else { + events = b.Events + } + } + if len(events) == 0 || len(events) > 500 { + writeError(w, http.StatusBadRequest, "invalid_input", "1..500 events per request") + return + } + p, _ := authn.PrincipalFrom(r.Context()) + ctx, cancel := context.WithTimeout(r.Context(), 10*time.Second) + defer cancel() + accepted, duplicates := 0, 0 + rejected := []map[string]any{} + for i, in := range events { + if p.IsUser() { + in.TenantID = p.TenantID // users may only report for their own tenant + } + if in.IdempotencyKey == "" || in.TenantID == "" || in.Product == "" || in.Metric == "" { + rejected = append(rejected, map[string]any{"index": i, "reason": "idempotency_key, tenant_id, product and metric are required"}) + continue + } + if !s.knownProduct(ctx, in.Product) { + rejected = append(rejected, map[string]any{"index": i, "reason": "unknown_product"}) + continue + } + qty := 1.0 + if in.Quantity != nil { + qty = *in.Quantity + } + occurred := s.now() + if in.OccurredAt != "" { + ts, err := time.Parse(time.RFC3339, in.OccurredAt) + if err != nil { + rejected = append(rejected, map[string]any{"index": i, "reason": "occurred_at must be RFC3339"}) + continue + } + occurred = ts.UTC() + } + ev, inserted, err := s.Store.InsertUsageEvent(ctx, store.UsageEvent{ + IdempotencyKey: in.IdempotencyKey, TenantID: in.TenantID, Product: in.Product, Metric: in.Metric, + Quantity: qty, OccurredAt: occurred, Properties: in.Properties, + }) + if err != nil { + if errors.Is(err, store.ErrNotFound) { + rejected = append(rejected, map[string]any{"index": i, "reason": "tenant_not_found"}) + continue + } + if errors.Is(err, store.ErrInvalidInput) { + rejected = append(rejected, map[string]any{"index": i, "reason": "invalid_input"}) + continue + } + writeError(w, http.StatusInternalServerError, "internal", err.Error()) + return + } + if !inserted { + duplicates++ + continue + } + accepted++ + if _, err := s.Store.EnqueueOutbox(ctx, store.OutboxItem{ + Kind: store.OutboxUsageRecord, TenantID: ev.TenantID, + Payload: map[string]interface{}{"usage_event_id": ev.ID, "idempotency_key": ev.IdempotencyKey, "product": ev.Product, + "metric": ev.Metric, "quantity": ev.Quantity, "occurred_at": ev.OccurredAt.Format(time.RFC3339)}, + }); err != nil { + s.Log.Error("enqueue usage outbox failed", "err", err, "usage_event_id", ev.ID) + } + } + code := http.StatusAccepted + if accepted == 0 && duplicates == 0 { + code = http.StatusBadRequest + } + writeJSON(w, code, map[string]any{"accepted": accepted, "duplicates": duplicates, "rejected": rejected}) +} + +// listUsageEvents — GET /v1/usage/events?tenant_id=&product=&metric=&since=&until=&limit= +func (s *Server) listUsageEvents(w http.ResponseWriter, r *http.Request) { + q := r.URL.Query() + f := store.UsageFilter{TenantID: q.Get("tenant_id"), Product: q.Get("product"), Metric: q.Get("metric")} + if p, _ := authn.PrincipalFrom(r.Context()); p.IsUser() { + f.TenantID = p.TenantID + } + if f.TenantID == "" { + writeError(w, http.StatusBadRequest, "invalid_input", "tenant_id query param is required") + return + } + for name, dst := range map[string]**time.Time{"since": &f.Since, "until": &f.Until} { + if v := q.Get(name); v != "" { + ts, err := time.Parse(time.RFC3339, v) + if err != nil { + writeError(w, http.StatusBadRequest, "invalid_"+name, "must be RFC3339") + return + } + *dst = &ts + } + } + if v := q.Get("limit"); v != "" { + n, err := strconv.Atoi(v) + if err != nil || n <= 0 || n > 1000 { + writeError(w, http.StatusBadRequest, "invalid_limit", "limit must be 1..1000") + return + } + f.Limit = n + } + ctx, cancel := context.WithTimeout(r.Context(), 5*time.Second) + defer cancel() + items, err := s.Store.ListUsageEvents(ctx, f) + if err != nil { + writeError(w, http.StatusInternalServerError, "internal", err.Error()) + return + } + writeJSON(w, http.StatusOK, map[string]any{"items": items}) +} diff --git a/internal/store/memory.go b/internal/store/memory.go index c0bcdb7..7611779 100644 --- a/internal/store/memory.go +++ b/internal/store/memory.go @@ -22,6 +22,16 @@ type Memory struct { 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 } type apiKeyWithHash struct { @@ -38,17 +48,22 @@ func NewMemory() *Memory { apiKeys: make(map[string]*apiKeyWithHash), byPrefix: make(map[string]string), catalog: DefaultProducts(), + subs: make(map[string]*Subscription), + usageKey: make(map[string]int64), + receipts: make(map[string]time.Time), + licences: make(map[string]*Licence), } now := time.Now().UTC() seed := &Tenant{ - ID: "00000000-0000-0000-0000-000000000001", - Slug: "acme", - Name: "Acme Inc.", - Status: "active", - Kind: "customer", - Plan: "professional", - CreatedAt: now, - UpdatedAt: now, + 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 @@ -81,16 +96,17 @@ func (m *Memory) CreateTenant(_ context.Context, in TenantCreate) (*Tenant, erro 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, - TrialEndsAt: trialEnds, - CreatedAt: now, - UpdatedAt: now, + ID: uuid.NewString(), + Slug: in.Slug, + Name: in.Name, + Status: status, + Kind: kind, + Plan: firstNonEmpty(in.Plan, "starter"), + SalesOwner: in.SalesOwner, + TrialEndsAt: trialEnds, + StatusChangedAt: now, + CreatedAt: now, + UpdatedAt: now, } m.tenants[t.ID] = t m.bySlug[t.Slug] = t.ID @@ -121,6 +137,21 @@ func (m *Memory) GetTenantBySlug(_ context.Context, slug string) (*Tenant, error 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() @@ -129,6 +160,9 @@ func (m *Memory) UpdateTenant(_ context.Context, id string, in TenantUpdate) (*T 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 { diff --git a/internal/store/memory_erp.go b/internal/store/memory_erp.go new file mode 100644 index 0000000..04f072c --- /dev/null +++ b/internal/store/memory_erp.go @@ -0,0 +1,320 @@ +package store + +import ( + "context" + "sort" + "time" + + "github.com/google/uuid" +) + +// ─── M-MIG-7: subscriptions / usage / outbox / receipts / licences (Memory) ── + +func (m *Memory) UpsertSubscription(_ context.Context, sub Subscription) (*Subscription, error) { + m.mu.Lock() + defer m.mu.Unlock() + if _, ok := m.tenants[sub.TenantID]; !ok { + return nil, ErrNotFound + } + if sub.SKU == "" || sub.Product == "" { + return nil, ErrInvalidInput + } + now := time.Now().UTC() + var row *Subscription + for _, s := range m.subs { + if s.TenantID == sub.TenantID && s.SKU == sub.SKU && s.ErpSalesOrder == sub.ErpSalesOrder { + row = s + break + } + } + if row == nil { + row = &Subscription{ID: uuid.NewString(), TenantID: sub.TenantID, SKU: sub.SKU, ErpSalesOrder: sub.ErpSalesOrder, CreatedAt: now} + m.subs[row.ID] = row + } + row.Product = sub.Product + row.Plan = sub.Plan + row.Seats = sub.Seats + row.Status = firstNonEmpty(sub.Status, SubscriptionActive) + row.ErpSubscription = sub.ErpSubscription + row.PeriodStart = sub.PeriodStart + row.PeriodEnd = sub.PeriodEnd + row.UpdatedAt = now + cp := *row + return &cp, nil +} + +func (m *Memory) ListSubscriptions(_ context.Context, tenantID string) ([]Subscription, error) { + m.mu.RLock() + defer m.mu.RUnlock() + if _, ok := m.tenants[tenantID]; !ok { + return nil, ErrNotFound + } + out := []Subscription{} + for _, s := range m.subs { + if s.TenantID == tenantID { + out = append(out, *s) + } + } + sort.Slice(out, func(i, j int) bool { + if out[i].CreatedAt.Equal(out[j].CreatedAt) { + return out[i].ID < out[j].ID + } + return out[i].CreatedAt.Before(out[j].CreatedAt) + }) + return out, nil +} + +func (m *Memory) InsertUsageEvent(_ context.Context, ev UsageEvent) (*UsageEvent, bool, error) { + m.mu.Lock() + defer m.mu.Unlock() + if _, ok := m.tenants[ev.TenantID]; !ok { + return nil, false, ErrNotFound + } + if ev.IdempotencyKey == "" || ev.Metric == "" || ev.Product == "" { + return nil, false, ErrInvalidInput + } + if id, dup := m.usageKey[ev.IdempotencyKey]; dup { + for _, u := range m.usage { + if u.ID == id { + cp := *u + return &cp, false, nil + } + } + } + m.usageID++ + row := ev + row.ID = m.usageID + row.ReceivedAt = time.Now().UTC() + if row.OccurredAt.IsZero() { + row.OccurredAt = row.ReceivedAt + } + if row.Properties == nil { + row.Properties = map[string]interface{}{} + } + m.usage = append(m.usage, &row) + m.usageKey[ev.IdempotencyKey] = row.ID + cp := row + return &cp, true, nil +} + +func (m *Memory) ListUsageEvents(_ context.Context, f UsageFilter) ([]UsageEvent, error) { + m.mu.RLock() + defer m.mu.RUnlock() + limit := f.Limit + if limit <= 0 || limit > 1000 { + limit = 200 + } + out := []UsageEvent{} + for i := len(m.usage) - 1; i >= 0 && len(out) < limit; i-- { + u := m.usage[i] + if f.TenantID != "" && u.TenantID != f.TenantID { + continue + } + if f.Product != "" && u.Product != f.Product { + continue + } + if f.Metric != "" && u.Metric != f.Metric { + continue + } + if f.Since != nil && u.OccurredAt.Before(*f.Since) { + continue + } + if f.Until != nil && u.OccurredAt.After(*f.Until) { + continue + } + out = append(out, *u) + } + return out, nil +} + +func (m *Memory) MarkUsageSynced(_ context.Context, ids []int64, at time.Time) error { + m.mu.Lock() + defer m.mu.Unlock() + set := map[int64]bool{} + for _, id := range ids { + set[id] = true + } + for _, u := range m.usage { + if set[u.ID] { + t := at + u.ErpSyncedAt = &t + } + } + return nil +} + +func (m *Memory) EnqueueOutbox(_ context.Context, item OutboxItem) (*OutboxItem, error) { + m.mu.Lock() + defer m.mu.Unlock() + if item.Kind == "" { + return nil, ErrInvalidInput + } + m.outboxID++ + row := item + row.ID = m.outboxID + row.Attempts = 0 + row.DoneAt = nil + row.CreatedAt = time.Now().UTC() + if row.NextAttemptAt.IsZero() { + row.NextAttemptAt = row.CreatedAt + } + if row.Payload == nil { + row.Payload = map[string]interface{}{} + } + m.outbox = append(m.outbox, &row) + cp := row + return &cp, nil +} + +func (m *Memory) ClaimOutbox(_ context.Context, limit int, now time.Time, lease time.Duration) ([]OutboxItem, error) { + m.mu.Lock() + defer m.mu.Unlock() + if limit <= 0 { + limit = 50 + } + out := []OutboxItem{} + for _, o := range m.outbox { + if o.DoneAt != nil || o.NextAttemptAt.After(now) { + continue + } + o.NextAttemptAt = now.Add(lease) + out = append(out, *o) + if len(out) >= limit { + break + } + } + return out, nil +} + +func (m *Memory) CompleteOutbox(_ context.Context, id int64, at time.Time) error { + m.mu.Lock() + defer m.mu.Unlock() + for _, o := range m.outbox { + if o.ID == id { + t := at + o.DoneAt = &t + o.Attempts++ + o.LastError = "" + return nil + } + } + return ErrNotFound +} + +func (m *Memory) FailOutbox(_ context.Context, id int64, errMsg string, nextAttempt time.Time) error { + m.mu.Lock() + defer m.mu.Unlock() + for _, o := range m.outbox { + if o.ID == id { + o.Attempts++ + o.LastError = errMsg + o.NextAttemptAt = nextAttempt + return nil + } + } + return ErrNotFound +} + +func (m *Memory) PendingOutbox(_ context.Context) (int, error) { + m.mu.RLock() + defer m.mu.RUnlock() + n := 0 + for _, o := range m.outbox { + if o.DoneAt == nil { + n++ + } + } + return n, nil +} + +func (m *Memory) RecordWebhookReceipt(_ context.Context, eventID string) (bool, error) { + m.mu.Lock() + defer m.mu.Unlock() + if eventID == "" { + return false, ErrInvalidInput + } + if _, seen := m.receipts[eventID]; seen { + return false, nil + } + m.receipts[eventID] = time.Now().UTC() + return true, nil +} + +func (m *Memory) CreateLicence(_ context.Context, l Licence) (*Licence, error) { + m.mu.Lock() + defer m.mu.Unlock() + if _, ok := m.tenants[l.TenantID]; !ok { + return nil, ErrNotFound + } + if l.Product == "" || l.Subject == "" || l.Kid == "" || l.ExpiresAt.IsZero() { + return nil, ErrInvalidInput + } + row := l + if row.ID == "" { + row.ID = uuid.NewString() + } + row.CreatedAt = time.Now().UTC() + row.RevokedAt = nil + row.LastSeenAt = nil + m.licences[row.ID] = &row + cp := row + return &cp, nil +} + +func (m *Memory) GetLicence(_ context.Context, id string) (*Licence, error) { + m.mu.RLock() + defer m.mu.RUnlock() + l, ok := m.licences[id] + if !ok { + return nil, ErrNotFound + } + cp := *l + return &cp, nil +} + +func (m *Memory) ListLicences(_ context.Context, tenantID string) ([]Licence, error) { + m.mu.RLock() + defer m.mu.RUnlock() + if _, ok := m.tenants[tenantID]; !ok { + return nil, ErrNotFound + } + out := []Licence{} + for _, l := range m.licences { + if l.TenantID == tenantID { + out = append(out, *l) + } + } + sort.Slice(out, func(i, j int) bool { + if out[i].CreatedAt.Equal(out[j].CreatedAt) { + return out[i].ID < out[j].ID + } + return out[i].CreatedAt.Before(out[j].CreatedAt) + }) + return out, nil +} + +func (m *Memory) RevokeLicence(_ context.Context, id string, at time.Time) error { + m.mu.Lock() + defer m.mu.Unlock() + l, ok := m.licences[id] + if !ok { + return ErrNotFound + } + if l.RevokedAt == nil { + t := at + l.RevokedAt = &t + } + return nil +} + +func (m *Memory) TouchLicence(_ context.Context, id string, at time.Time) error { + m.mu.Lock() + defer m.mu.Unlock() + l, ok := m.licences[id] + if !ok { + return ErrNotFound + } + t := at + l.LastSeenAt = &t + return nil +} diff --git a/internal/store/postgres.go b/internal/store/postgres.go index 7cd1289..d242b1c 100644 --- a/internal/store/postgres.go +++ b/internal/store/postgres.go @@ -63,7 +63,7 @@ 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,''), - created_at, updated_at + status_changed_at, created_at, updated_at FROM tenants ` func scanTenant(row pgx.Row) (*Tenant, error) { @@ -73,7 +73,7 @@ func scanTenant(row pgx.Row) (*Tenant, error) { &t.ID, &t.Slug, &t.Name, &t.Status, &t.Kind, &t.Plan, &t.ErpCustomerID, &t.StripeCustID, &trialEnds, &cStart, &cEnd, &t.SalesOwner, - &t.CreatedAt, &t.UpdatedAt, + &t.StatusChangedAt, &t.CreatedAt, &t.UpdatedAt, ) if errors.Is(err, pgx.ErrNoRows) { return nil, ErrNotFound @@ -107,7 +107,7 @@ func (p *Postgres) CreateTenant(ctx context.Context, in TenantCreate) (*Tenant, 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,''), - created_at, updated_at`, + status_changed_at, created_at, updated_at`, in.Slug, in.Name, kind, plan, in.SalesOwner, ) t, err := scanTenant(row) @@ -131,6 +131,13 @@ func (p *Postgres) GetTenantBySlug(ctx context.Context, slug string) (*Tenant, e 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. @@ -148,7 +155,7 @@ func (p *Postgres) UpdateTenant(ctx context.Context, id string, in TenantUpdate) 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,''), - created_at, updated_at`, + status_changed_at, created_at, updated_at`, id, nullableStr(in.Status), nullableStr(in.Plan), nullableStr(in.ErpCustomerID), nullableStr(in.StripeCustID), diff --git a/internal/store/postgres_erp.go b/internal/store/postgres_erp.go new file mode 100644 index 0000000..12d1fa7 --- /dev/null +++ b/internal/store/postgres_erp.go @@ -0,0 +1,426 @@ +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" +) + +// ─── M-MIG-7: subscriptions / usage / outbox / receipts / licences (Postgres) ─ + +func isFKViolation(err error) bool { + var pgErr *pgconn.PgError + return errors.As(err, &pgErr) && pgErr.Code == pgerrcode.ForeignKeyViolation +} + +func isInvalidUUID(err error) bool { + var pgErr *pgconn.PgError + return errors.As(err, &pgErr) && pgErr.Code == pgerrcode.InvalidTextRepresentation +} + +const subscriptionSelect = ` +SELECT id::text, tenant_id::text, product, sku, plan, seats, status, + erp_sales_order, erp_subscription, period_start, period_end, created_at, updated_at +FROM subscriptions ` + +func scanSubscription(row pgx.Row) (*Subscription, error) { + var s Subscription + var ps, pe *time.Time + err := row.Scan(&s.ID, &s.TenantID, &s.Product, &s.SKU, &s.Plan, &s.Seats, &s.Status, + &s.ErpSalesOrder, &s.ErpSubscription, &ps, &pe, &s.CreatedAt, &s.UpdatedAt) + if errors.Is(err, pgx.ErrNoRows) { + return nil, ErrNotFound + } + if err != nil { + return nil, err + } + s.PeriodStart, s.PeriodEnd = ps, pe + return &s, nil +} + +func (p *Postgres) UpsertSubscription(ctx context.Context, sub Subscription) (*Subscription, error) { + if sub.SKU == "" || sub.Product == "" { + return nil, ErrInvalidInput + } + row := p.pool.QueryRow(ctx, ` + INSERT INTO subscriptions (tenant_id, product, sku, plan, seats, status, erp_sales_order, erp_subscription, period_start, period_end) + VALUES ($1::uuid, $2, $3, $4, $5, $6, $7, $8, $9, $10) + ON CONFLICT (tenant_id, sku, erp_sales_order) DO UPDATE SET + product = EXCLUDED.product, plan = EXCLUDED.plan, seats = EXCLUDED.seats, status = EXCLUDED.status, + erp_subscription = EXCLUDED.erp_subscription, period_start = EXCLUDED.period_start, period_end = EXCLUDED.period_end + RETURNING id::text, tenant_id::text, product, sku, plan, seats, status, + erp_sales_order, erp_subscription, period_start, period_end, created_at, updated_at`, + sub.TenantID, sub.Product, sub.SKU, sub.Plan, sub.Seats, firstNonEmpty(sub.Status, SubscriptionActive), + sub.ErpSalesOrder, sub.ErpSubscription, nullableTime(sub.PeriodStart), nullableTime(sub.PeriodEnd)) + out, err := scanSubscription(row) + if err != nil { + if isFKViolation(err) || isInvalidUUID(err) { + return nil, ErrNotFound + } + if isCheckViolation(err) { + return nil, ErrInvalidInput + } + return nil, err + } + return out, nil +} + +func (p *Postgres) ListSubscriptions(ctx context.Context, tenantID string) ([]Subscription, error) { + if _, err := p.GetTenant(ctx, tenantID); err != nil { + return nil, err + } + rows, err := p.pool.Query(ctx, subscriptionSelect+`WHERE tenant_id = $1::uuid ORDER BY created_at, id`, tenantID) + if err != nil { + return nil, err + } + defer rows.Close() + out := []Subscription{} + for rows.Next() { + s, err := scanSubscription(rows) + if err != nil { + return nil, err + } + out = append(out, *s) + } + return out, rows.Err() +} + +const usageSelect = ` +SELECT id, idempotency_key, tenant_id::text, product, metric, quantity, occurred_at, properties, received_at, erp_synced_at +FROM usage_events ` + +func scanUsage(row pgx.Row) (*UsageEvent, error) { + var u UsageEvent + var props []byte + var synced *time.Time + err := row.Scan(&u.ID, &u.IdempotencyKey, &u.TenantID, &u.Product, &u.Metric, &u.Quantity, &u.OccurredAt, &props, &u.ReceivedAt, &synced) + if errors.Is(err, pgx.ErrNoRows) { + return nil, ErrNotFound + } + if err != nil { + return nil, err + } + u.ErpSyncedAt = synced + if err := json.Unmarshal(props, &u.Properties); err != nil || u.Properties == nil { + u.Properties = map[string]interface{}{} + } + return &u, nil +} + +func (p *Postgres) InsertUsageEvent(ctx context.Context, ev UsageEvent) (*UsageEvent, bool, error) { + if ev.IdempotencyKey == "" || ev.Metric == "" || ev.Product == "" { + return nil, false, ErrInvalidInput + } + props, err := json.Marshal(ev.Properties) + if err != nil || string(props) == "null" { + props = []byte("{}") + } + occurred := ev.OccurredAt + if occurred.IsZero() { + occurred = time.Now().UTC() + } + row := p.pool.QueryRow(ctx, ` + INSERT INTO usage_events (idempotency_key, tenant_id, product, metric, quantity, occurred_at, properties) + VALUES ($1, $2::uuid, $3, $4, $5, $6, $7::jsonb) + ON CONFLICT (idempotency_key) DO NOTHING + RETURNING id, idempotency_key, tenant_id::text, product, metric, quantity, occurred_at, properties, received_at, erp_synced_at`, + ev.IdempotencyKey, ev.TenantID, ev.Product, ev.Metric, ev.Quantity, occurred, props) + u, err := scanUsage(row) + if err == nil { + return u, true, nil + } + if errors.Is(err, ErrNotFound) { + // duplicate key → return the stored row + u, err = scanUsage(p.pool.QueryRow(ctx, usageSelect+`WHERE idempotency_key = $1`, ev.IdempotencyKey)) + if err != nil { + return nil, false, err + } + return u, false, nil + } + if isFKViolation(err) || isInvalidUUID(err) { + return nil, false, ErrNotFound + } + return nil, false, err +} + +func (p *Postgres) ListUsageEvents(ctx context.Context, f UsageFilter) ([]UsageEvent, error) { + limit := f.Limit + if limit <= 0 || limit > 1000 { + limit = 200 + } + 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.TenantID != "" { + add("tenant_id = $%d::uuid", f.TenantID) + } + if f.Product != "" { + add("product = $%d", f.Product) + } + if f.Metric != "" { + add("metric = $%d", f.Metric) + } + if f.Since != nil { + add("occurred_at >= $%d", *f.Since) + } + if f.Until != nil { + add("occurred_at <= $%d", *f.Until) + } + args = append(args, limit) + rows, err := p.pool.Query(ctx, usageSelect+`WHERE `+strings.Join(where, " AND ")+ + fmt.Sprintf(` ORDER BY occurred_at DESC, id DESC LIMIT $%d`, len(args)), args...) + if err != nil { + if isInvalidUUID(err) { + return []UsageEvent{}, nil + } + return nil, err + } + defer rows.Close() + out := []UsageEvent{} + for rows.Next() { + u, err := scanUsage(rows) + if err != nil { + return nil, err + } + out = append(out, *u) + } + return out, rows.Err() +} + +func (p *Postgres) MarkUsageSynced(ctx context.Context, ids []int64, at time.Time) error { + if len(ids) == 0 { + return nil + } + _, err := p.pool.Exec(ctx, `UPDATE usage_events SET erp_synced_at = $2 WHERE id = ANY($1)`, ids, at) + return err +} + +const outboxSelect = ` +SELECT id, kind, COALESCE(tenant_id::text, ''), payload, attempts, next_attempt_at, last_error, done_at, created_at +FROM erp_outbox ` + +func scanOutbox(row pgx.Row) (*OutboxItem, error) { + var o OutboxItem + var payload []byte + var done *time.Time + err := row.Scan(&o.ID, &o.Kind, &o.TenantID, &payload, &o.Attempts, &o.NextAttemptAt, &o.LastError, &done, &o.CreatedAt) + if errors.Is(err, pgx.ErrNoRows) { + return nil, ErrNotFound + } + if err != nil { + return nil, err + } + o.DoneAt = done + if err := json.Unmarshal(payload, &o.Payload); err != nil || o.Payload == nil { + o.Payload = map[string]interface{}{} + } + return &o, nil +} + +func (p *Postgres) EnqueueOutbox(ctx context.Context, item OutboxItem) (*OutboxItem, error) { + if item.Kind == "" { + return nil, ErrInvalidInput + } + payload, err := json.Marshal(item.Payload) + if err != nil || string(payload) == "null" { + payload = []byte("{}") + } + next := item.NextAttemptAt + if next.IsZero() { + next = time.Now().UTC() + } + var tenant any + if item.TenantID != "" { + tenant = item.TenantID + } + o, err := scanOutbox(p.pool.QueryRow(ctx, ` + INSERT INTO erp_outbox (kind, tenant_id, payload, next_attempt_at) + VALUES ($1, $2::uuid, $3::jsonb, $4) + RETURNING id, kind, COALESCE(tenant_id::text, ''), payload, attempts, next_attempt_at, last_error, done_at, created_at`, + item.Kind, tenant, payload, next)) + if err != nil { + if isFKViolation(err) || isInvalidUUID(err) { + return nil, ErrNotFound + } + return nil, err + } + return o, nil +} + +func (p *Postgres) ClaimOutbox(ctx context.Context, limit int, now time.Time, lease time.Duration) ([]OutboxItem, error) { + if limit <= 0 { + limit = 50 + } + rows, err := p.pool.Query(ctx, ` + UPDATE erp_outbox SET next_attempt_at = $1::timestamptz + $2::interval + WHERE id IN ( + SELECT id FROM erp_outbox + WHERE done_at IS NULL AND next_attempt_at <= $1 + ORDER BY next_attempt_at, id + LIMIT $3 + FOR UPDATE SKIP LOCKED + ) + RETURNING id, kind, COALESCE(tenant_id::text, ''), payload, attempts, next_attempt_at, last_error, done_at, created_at`, + now, lease, limit) + if err != nil { + return nil, err + } + defer rows.Close() + out := []OutboxItem{} + for rows.Next() { + o, err := scanOutbox(rows) + if err != nil { + return nil, err + } + out = append(out, *o) + } + return out, rows.Err() +} + +func (p *Postgres) CompleteOutbox(ctx context.Context, id int64, at time.Time) error { + tag, err := p.pool.Exec(ctx, `UPDATE erp_outbox SET done_at = $2, attempts = attempts + 1, last_error = '' WHERE id = $1`, id, at) + if err != nil { + return err + } + if tag.RowsAffected() == 0 { + return ErrNotFound + } + return nil +} + +func (p *Postgres) FailOutbox(ctx context.Context, id int64, errMsg string, nextAttempt time.Time) error { + tag, err := p.pool.Exec(ctx, `UPDATE erp_outbox SET attempts = attempts + 1, last_error = $2, next_attempt_at = $3 WHERE id = $1`, id, errMsg, nextAttempt) + if err != nil { + return err + } + if tag.RowsAffected() == 0 { + return ErrNotFound + } + return nil +} + +func (p *Postgres) PendingOutbox(ctx context.Context) (int, error) { + var n int + err := p.pool.QueryRow(ctx, `SELECT COUNT(*) FROM erp_outbox WHERE done_at IS NULL`).Scan(&n) + return n, err +} + +func (p *Postgres) RecordWebhookReceipt(ctx context.Context, eventID string) (bool, error) { + if eventID == "" { + return false, ErrInvalidInput + } + tag, err := p.pool.Exec(ctx, `INSERT INTO erp_webhook_receipts (event_id) VALUES ($1) ON CONFLICT DO NOTHING`, eventID) + if err != nil { + return false, err + } + return tag.RowsAffected() == 1, nil +} + +const licenceSelect = ` +SELECT id::text, kid, tenant_id::text, product, subject, device, expires_at, revoked_at, last_seen_at, created_at +FROM licences ` + +func scanLicence(row pgx.Row) (*Licence, error) { + var l Licence + var revoked, seen *time.Time + err := row.Scan(&l.ID, &l.Kid, &l.TenantID, &l.Product, &l.Subject, &l.Device, &l.ExpiresAt, &revoked, &seen, &l.CreatedAt) + if errors.Is(err, pgx.ErrNoRows) { + return nil, ErrNotFound + } + if err != nil { + return nil, err + } + l.RevokedAt, l.LastSeenAt = revoked, seen + return &l, nil +} + +func (p *Postgres) CreateLicence(ctx context.Context, l Licence) (*Licence, error) { + if l.Product == "" || l.Subject == "" || l.Kid == "" || l.ExpiresAt.IsZero() { + return nil, ErrInvalidInput + } + var id any + if l.ID != "" { + id = l.ID + } + out, err := scanLicence(p.pool.QueryRow(ctx, ` + INSERT INTO licences (id, kid, tenant_id, product, subject, device, expires_at) + VALUES (COALESCE($1::uuid, gen_random_uuid()), $2, $3::uuid, $4, $5, $6, $7) + RETURNING id::text, kid, tenant_id::text, product, subject, device, expires_at, revoked_at, last_seen_at, created_at`, + id, l.Kid, l.TenantID, l.Product, l.Subject, l.Device, l.ExpiresAt)) + if err != nil { + if isFKViolation(err) || isInvalidUUID(err) { + return nil, ErrNotFound + } + if isUniqueViolation(err) { + return nil, ErrConflict + } + return nil, err + } + return out, nil +} + +func (p *Postgres) GetLicence(ctx context.Context, id string) (*Licence, error) { + l, err := scanLicence(p.pool.QueryRow(ctx, licenceSelect+`WHERE id = $1::uuid`, id)) + if err != nil && isInvalidUUID(err) { + return nil, ErrNotFound + } + return l, err +} + +func (p *Postgres) ListLicences(ctx context.Context, tenantID string) ([]Licence, error) { + if _, err := p.GetTenant(ctx, tenantID); err != nil { + return nil, err + } + rows, err := p.pool.Query(ctx, licenceSelect+`WHERE tenant_id = $1::uuid ORDER BY created_at, id`, tenantID) + if err != nil { + return nil, err + } + defer rows.Close() + out := []Licence{} + for rows.Next() { + l, err := scanLicence(rows) + if err != nil { + return nil, err + } + out = append(out, *l) + } + return out, rows.Err() +} + +func (p *Postgres) RevokeLicence(ctx context.Context, id string, at time.Time) error { + tag, err := p.pool.Exec(ctx, `UPDATE licences SET revoked_at = COALESCE(revoked_at, $2) WHERE id = $1::uuid`, id, at) + if err != nil { + if isInvalidUUID(err) { + return ErrNotFound + } + return err + } + if tag.RowsAffected() == 0 { + return ErrNotFound + } + return nil +} + +func (p *Postgres) TouchLicence(ctx context.Context, id string, at time.Time) error { + tag, err := p.pool.Exec(ctx, `UPDATE licences SET last_seen_at = $2 WHERE id = $1::uuid`, id, at) + if err != nil { + if isInvalidUUID(err) { + return ErrNotFound + } + return err + } + if tag.RowsAffected() == 0 { + return ErrNotFound + } + return nil +} diff --git a/internal/store/store.go b/internal/store/store.go index f0c234d..8f6ae4b 100644 --- a/internal/store/store.go +++ b/internal/store/store.go @@ -69,6 +69,7 @@ type Store interface { 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) @@ -91,6 +92,34 @@ type Store interface { 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 + // Lifecycle Close() Ping(ctx context.Context) error diff --git a/internal/store/types.go b/internal/store/types.go index 7b81e3d..c7244ea 100644 --- a/internal/store/types.go +++ b/internal/store/types.go @@ -22,8 +22,10 @@ type Tenant struct { ContractStart *time.Time `json:"contract_start,omitempty"` ContractEnd *time.Time `json:"contract_end,omitempty"` SalesOwner string `json:"sales_owner,omitempty"` - CreatedAt time.Time `json:"created_at"` - UpdatedAt time.Time `json:"updated_at"` + // StatusChangedAt — when the current ladder status was entered (M-MIG-7). + StatusChangedAt time.Time `json:"status_changed_at"` + CreatedAt time.Time `json:"created_at"` + UpdatedAt time.Time `json:"updated_at"` } // TenantProduct — entitlement matrix row. @@ -145,3 +147,84 @@ func ValidStatus(s string) bool { } return false } + +// ─── M-MIG-7: ERP link ──────────────────────────────────────────────────── + +// Subscription mirrors one ERPNext Sales Order line (tenant × SKU). +type Subscription struct { + ID string `json:"id"` + TenantID string `json:"tenant_id"` + Product string `json:"product"` + SKU string `json:"sku"` + Plan string `json:"plan,omitempty"` + Seats int `json:"seats"` + Status string `json:"status"` // active | cancelled + ErpSalesOrder string `json:"erp_sales_order,omitempty"` + ErpSubscription string `json:"erp_subscription,omitempty"` + PeriodStart *time.Time `json:"period_start,omitempty"` + PeriodEnd *time.Time `json:"period_end,omitempty"` + CreatedAt time.Time `json:"created_at"` + UpdatedAt time.Time `json:"updated_at"` +} + +const ( + SubscriptionActive = "active" + SubscriptionCancelled = "cancelled" +) + +// UsageEvent — one metered fact pushed by a product (§9.2). +type UsageEvent struct { + ID int64 `json:"id"` + IdempotencyKey string `json:"idempotency_key"` + TenantID string `json:"tenant_id"` + Product string `json:"product"` + Metric string `json:"metric"` + Quantity float64 `json:"quantity"` + OccurredAt time.Time `json:"occurred_at"` + Properties map[string]interface{} `json:"properties,omitempty"` + ReceivedAt time.Time `json:"received_at"` + ErpSyncedAt *time.Time `json:"erp_synced_at,omitempty"` +} + +// UsageFilter narrows Store.ListUsageEvents. +type UsageFilter struct { + TenantID string + Product string + Metric string + Since *time.Time + Until *time.Time + Limit int +} + +// OutboxItem — a pending ERP write. +type OutboxItem struct { + ID int64 `json:"id"` + Kind string `json:"kind"` // customer.upsert | usage.record | lead.create + TenantID string `json:"tenant_id,omitempty"` + Payload map[string]interface{} `json:"payload"` + Attempts int `json:"attempts"` + NextAttemptAt time.Time `json:"next_attempt_at"` + LastError string `json:"last_error,omitempty"` + DoneAt *time.Time `json:"done_at,omitempty"` + CreatedAt time.Time `json:"created_at"` +} + +const ( + OutboxCustomerUpsert = "customer.upsert" + OutboxUsageRecord = "usage.record" + OutboxLeadCreate = "lead.create" +) + +// Licence — revocation + heartbeat record of an issued CLI licence JWT. +type Licence struct { + ID string `json:"id"` + Kid string `json:"kid"` + TenantID string `json:"tenant_id"` + Product string `json:"product"` + Subject string `json:"subject"` + Device string `json:"device,omitempty"` + ExpiresAt time.Time `json:"expires_at"` + RevokedAt *time.Time `json:"revoked_at,omitempty"` + LastSeenAt *time.Time `json:"last_seen_at,omitempty"` + CreatedAt time.Time `json:"created_at"` +} diff --git a/migrations/0004_erp_link.down.sql b/migrations/0004_erp_link.down.sql new file mode 100644 index 0000000..caf2154 --- /dev/null +++ b/migrations/0004_erp_link.down.sql @@ -0,0 +1,8 @@ +DROP TABLE IF EXISTS licences; +DROP TABLE IF EXISTS erp_webhook_receipts; +DROP TABLE IF EXISTS erp_outbox; +DROP TABLE IF EXISTS usage_events; +DROP TABLE IF EXISTS subscriptions; +DROP TRIGGER IF EXISTS tenants_touch_status_changed_at ON tenants; +DROP FUNCTION IF EXISTS touch_status_changed_at(); +ALTER TABLE tenants DROP COLUMN IF EXISTS status_changed_at; diff --git a/migrations/0004_erp_link.up.sql b/migrations/0004_erp_link.up.sql new file mode 100644 index 0000000..99322e8 --- /dev/null +++ b/migrations/0004_erp_link.up.sql @@ -0,0 +1,103 @@ +-- M-MIG-7 — the always-on customer ⇄ CRM ⇄ ERP link (ERP/02, decision 3): +-- subscriptions mirrored from ERPNext Sales Orders, continuous usage events, +-- an outbox for ERP writes with retry, webhook idempotency, and CLI licences +-- issued by the registry (decision 13). + +-- Ladder timing: when the current status was entered (grace escalation and +-- the halted → archived export window key off this). +ALTER TABLE tenants ADD COLUMN status_changed_at TIMESTAMPTZ NOT NULL DEFAULT NOW(); + +CREATE OR REPLACE FUNCTION touch_status_changed_at() RETURNS trigger AS $$ +BEGIN + IF NEW.status IS DISTINCT FROM OLD.status THEN + NEW.status_changed_at = NOW(); + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER tenants_touch_status_changed_at + BEFORE UPDATE ON tenants + FOR EACH ROW EXECUTE FUNCTION touch_status_changed_at(); + +-- subscriptions — one row per (tenant, SKU, ERP Sales Order). The registry +-- derives entitlements (tenant_products) from active rows. +CREATE TABLE subscriptions ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + tenant_id UUID NOT NULL REFERENCES tenants(id) ON DELETE CASCADE, + product TEXT NOT NULL, + sku TEXT NOT NULL, + plan TEXT NOT NULL DEFAULT '', + seats INT NOT NULL DEFAULT 1 CHECK (seats >= 0), + status TEXT NOT NULL DEFAULT 'active' CHECK (status IN ('active', 'cancelled')), + erp_sales_order TEXT NOT NULL DEFAULT '', + erp_subscription TEXT NOT NULL DEFAULT '', + period_start DATE, + period_end DATE, + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + UNIQUE (tenant_id, sku, erp_sales_order) +); + +CREATE INDEX subscriptions_tenant_idx ON subscriptions (tenant_id) WHERE status = 'active'; + +CREATE TRIGGER subscriptions_touch_updated_at + BEFORE UPDATE ON subscriptions + FOR EACH ROW EXECUTE FUNCTION touch_updated_at(); + +-- usage_events — pushed by products (PRODUCT_INTEGRATION_SPEC 2.0 §9.2). +-- idempotency_key makes retries safe; erp_synced_at is set by the outbox. +CREATE TABLE usage_events ( + id BIGSERIAL PRIMARY KEY, + idempotency_key TEXT NOT NULL UNIQUE, + tenant_id UUID NOT NULL REFERENCES tenants(id) ON DELETE CASCADE, + product TEXT NOT NULL, + metric TEXT NOT NULL, + quantity DOUBLE PRECISION NOT NULL DEFAULT 1, + occurred_at TIMESTAMPTZ NOT NULL, + properties JSONB NOT NULL DEFAULT '{}'::jsonb, + received_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + erp_synced_at TIMESTAMPTZ +); + +CREATE INDEX usage_events_tenant_idx ON usage_events (tenant_id, occurred_at DESC); + +-- erp_outbox — every ERP write goes through here (customer upsert, usage +-- record, CRM lead). The worker claims due rows, retries with backoff and +-- marks them done; nothing is lost when ERPNext is unreachable. +CREATE TABLE erp_outbox ( + id BIGSERIAL PRIMARY KEY, + kind TEXT NOT NULL, + tenant_id UUID REFERENCES tenants(id) ON DELETE CASCADE, + payload JSONB NOT NULL DEFAULT '{}'::jsonb, + attempts INT NOT NULL DEFAULT 0, + next_attempt_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + last_error TEXT NOT NULL DEFAULT '', + done_at TIMESTAMPTZ, + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW() +); + +CREATE INDEX erp_outbox_pending_idx ON erp_outbox (next_attempt_at) WHERE done_at IS NULL; + +-- erp_webhook_receipts — inbound ERPNext webhooks are idempotent by event id. +CREATE TABLE erp_webhook_receipts ( + event_id TEXT PRIMARY KEY, + received_at TIMESTAMPTZ NOT NULL DEFAULT NOW() +); + +-- licences — CLI licences (Werkpilot, Firmwerk) issued as Ed25519 JWTs; the +-- row is the revocation + heartbeat record, the JWT itself is not stored. +CREATE TABLE licences ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + kid TEXT NOT NULL, + tenant_id UUID NOT NULL REFERENCES tenants(id) ON DELETE CASCADE, + product TEXT NOT NULL, + subject TEXT NOT NULL, + device TEXT NOT NULL DEFAULT '', + expires_at TIMESTAMPTZ NOT NULL, + revoked_at TIMESTAMPTZ, + last_seen_at TIMESTAMPTZ, + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW() +); + +CREATE INDEX licences_tenant_idx ON licences (tenant_id, product) WHERE revoked_at IS NULL; diff --git a/openapi.yaml b/openapi.yaml index 5e39309..d1c2e25 100644 --- a/openapi.yaml +++ b/openapi.yaml @@ -494,6 +494,234 @@ paths: format: int64 "400": { $ref: "#/components/responses/BadRequest" } + /v1/internal/erp/webhook: + post: + summary: ERPNext webhook receiver (HMAC-signed, no bearer token). + description: | + PUBLIC_EXPLICIT. Body is signed with ERP_WEBHOOK_SECRET + (X-Frappe-Webhook-Signature = base64 HMAC-SHA256, or + X-Hub-Signature-256 = sha256=hex). Idempotent by X-Frappe-Event-Id + (fallback: hash of event+name+modified+body). Events: + sales_order.submit → subscriptions + entitlements + active; + sales_invoice.overdue → warning / restricted (days_overdue ≥ + ERP_RESTRICT_AFTER_DAYS) / halted; payment_entry.submit → active; + subscription.cancel → halted. Unknown customers are acknowledged (202). + requestBody: + required: true + content: + application/json: { schema: { $ref: "#/components/schemas/ErpWebhookEvent" } } + responses: + "200": { description: "Applied, unchanged or duplicate." } + "202": { description: "Ignored (tenant not found)." } + "401": { description: Bad signature. } + "503": { description: ERP_WEBHOOK_SECRET not configured. } + + /v1/internal/erp/status: + get: + summary: ERP link status (outbox backlog, webhook/licence configuration). + responses: + "200": + description: Status. + content: + application/json: + schema: + type: object + properties: + erp_configured: { type: boolean } + webhook_enabled: { type: boolean } + outbox_pending: { type: integer } + licences_enabled: { type: boolean } + + /v1/internal/erp/reconcile: + post: + summary: Run one reconcile pass now (ops / tests). + description: | + Mirrors ERP subscriptions for every tenant with an ERP customer and + applies the time-based ladder steps (trial expiry, warning → + restricted, restricted → halted, halted → archived). Runs every + ERP_RECONCILE_INTERVAL in the background as well. + responses: + "200": + description: Report. + content: + application/json: { schema: { $ref: "#/components/schemas/ReconcileReport" } } + + /v1/subscriptions: + get: + summary: Subscriptions mirrored from ERPNext for one tenant. + parameters: + - in: query + name: tenant_id + required: true + schema: { type: string, format: uuid } + responses: + "200": + description: List. + content: + application/json: + schema: + type: object + properties: + items: + type: array + items: { $ref: "#/components/schemas/Subscription" } + "404": { $ref: "#/components/responses/NotFound" } + + /v1/usage/events: + post: + summary: Push usage events (PRODUCT_INTEGRATION_SPEC 2.0 §9.2). + description: | + One event, an array, or {"events": [...]} (≤ 500). Idempotent by + idempotency_key; each new event is forwarded to ERPNext as a Usage + Record through the outbox. User tokens may only report for their + own tenant. + requestBody: + required: true + content: + application/json: + schema: + oneOf: + - $ref: "#/components/schemas/UsageEventIn" + - type: array + items: { $ref: "#/components/schemas/UsageEventIn" } + - type: object + properties: + events: + type: array + items: { $ref: "#/components/schemas/UsageEventIn" } + responses: + "202": + description: "Accepted (partial rejections listed)." + content: + application/json: + schema: + type: object + properties: + accepted: { type: integer } + duplicates: { type: integer } + rejected: { type: array, items: { type: object } } + "400": { $ref: "#/components/responses/BadRequest" } + get: + summary: Query usage events. + parameters: + - { in: query, name: tenant_id, required: true, schema: { type: string, format: uuid } } + - { in: query, name: product, schema: { type: string } } + - { in: query, name: metric, schema: { type: string } } + - { in: query, name: since, schema: { type: string, format: date-time } } + - { in: query, name: until, schema: { type: string, format: date-time } } + - { in: query, name: limit, schema: { type: integer, minimum: 1, maximum: 1000 } } + responses: + "200": + description: Newest first. + content: + application/json: + schema: + type: object + properties: + items: + type: array + items: { $ref: "#/components/schemas/UsageEvent" } + "400": { $ref: "#/components/responses/BadRequest" } + + /v1/licences: + post: + summary: Issue a CLI licence JWT (Werkpilot, Firmwerk). + description: | + Requires an active entitlement for the product. User tokens (device + flow, tenant-context claims) get a licence for their own tenant; + service tokens pass tenant_id. Ed25519-signed (EdDSA), verifiable + offline against /.well-known/licence-keys.json; expiry = min(ttl, + entitlement expiry). Grace ladder inside the token. + requestBody: + required: true + content: + application/json: + schema: + type: object + required: [product] + properties: + tenant_id: { type: string, format: uuid } + product: { type: string } + device: { type: string } + ttl_days: { type: integer } + responses: + "201": + description: Issued. + content: + application/json: { schema: { $ref: "#/components/schemas/LicenceIssued" } } + "400": { $ref: "#/components/responses/BadRequest" } + "403": { description: Not entitled. } + "503": { description: Licence signer not configured. } + get: + summary: List licences of a tenant. + parameters: + - { in: query, name: tenant_id, required: true, schema: { type: string, format: uuid } } + responses: + "200": + description: List. + content: + application/json: + schema: + type: object + properties: + items: + type: array + items: { $ref: "#/components/schemas/Licence" } + "404": { $ref: "#/components/responses/NotFound" } + + /v1/licences/{id}/revoke: + post: + summary: Revoke a licence (next heartbeat reports `revoked`). + parameters: + - in: path + name: id + required: true + schema: { type: string, format: uuid } + responses: + "200": + description: Revoked. + content: + application/json: { schema: { $ref: "#/components/schemas/Licence" } } + "404": { $ref: "#/components/responses/NotFound" } + + /v1/licences/heartbeat: + post: + summary: CLI phone-home (PUBLIC_EXPLICIT — the licence JWT is the credential). + description: | + Reports ok | warning | degraded | hard_stop | revoked from the tenant + ladder and the token's grace policy, records last_seen, and returns a + renewed licence once the current one is past half-life while the + tenant is still entitled. + requestBody: + required: true + content: + application/json: + schema: + type: object + required: [licence] + properties: + licence: { type: string } + responses: + "200": + description: State. + content: + application/json: { schema: { $ref: "#/components/schemas/LicenceHeartbeat" } } + "401": { description: "Signature invalid or licence unknown." } + "503": { description: Licence signer not configured. } + + /.well-known/licence-keys.json: + get: + summary: Licence verification keys (JWKS, OKP/Ed25519). PUBLIC_EXPLICIT. + responses: + "200": + description: JWKS. + content: + application/json: + schema: + type: object + properties: + keys: { type: array, items: { type: object } } + components: securitySchemes: bearerAuth: @@ -519,6 +747,106 @@ components: application/json: { schema: { $ref: "#/components/schemas/Error" } } schemas: + ErpWebhookEvent: + type: object + required: [event, name] + properties: + event: { type: string, enum: [sales_order.submit, sales_invoice.overdue, payment_entry.submit, subscription.cancel] } + doctype: { type: string } + name: { type: string } + modified: { type: string } + customer: { type: string, description: "ERP customer name (tenants.erp_customer_id)" } + tenant_id: { type: string, format: uuid, description: "Custom field on the Customer; preferred over customer" } + items: + type: array + items: + type: object + properties: + item_code: { type: string, description: "Platform SKU" } + qty: { type: number } + days_overdue: { type: integer } + subscription: { type: string } + invoice: { type: string } + amount: { type: number } + ReconcileReport: + type: object + properties: + tenants: { type: integer } + erp_checked: { type: integer } + changed: { type: array, items: { type: string } } + escalated: { type: array, items: { type: string } } + errors: { type: array, items: { type: string } } + erp_available: { type: boolean } + Subscription: + type: object + properties: + id: { type: string, format: uuid } + tenant_id: { type: string, format: uuid } + product: { type: string } + sku: { type: string } + plan: { type: string } + seats: { type: integer } + status: { type: string, enum: [active, cancelled] } + erp_sales_order: { type: string } + erp_subscription: { type: string } + period_start: { type: string, format: date-time } + period_end: { type: string, format: date-time } + created_at: { type: string, format: date-time } + updated_at: { type: string, format: date-time } + UsageEventIn: + type: object + required: [idempotency_key, tenant_id, product, metric] + properties: + idempotency_key: { type: string } + tenant_id: { type: string, format: uuid } + product: { type: string } + metric: { type: string, description: "e.g. scan.completed, target.added, seat.login" } + quantity: { type: number, default: 1 } + occurred_at: { type: string, format: date-time } + properties: { type: object, additionalProperties: true } + UsageEvent: + allOf: + - $ref: "#/components/schemas/UsageEventIn" + - type: object + properties: + id: { type: integer } + received_at: { type: string, format: date-time } + erp_synced_at: { type: string, format: date-time } + Licence: + type: object + properties: + id: { type: string, format: uuid } + kid: { type: string } + tenant_id: { type: string, format: uuid } + product: { type: string } + subject: { type: string } + device: { type: string } + expires_at: { type: string, format: date-time } + revoked_at: { type: string, format: date-time } + last_seen_at: { type: string, format: date-time } + created_at: { type: string, format: date-time } + LicenceIssued: + type: object + properties: + id: { type: string, format: uuid } + licence: { type: string, description: "EdDSA JWT" } + kid: { type: string } + expires_at: { type: string, format: date-time } + grace: + type: object + properties: + warning_days: { type: integer } + degraded_days: { type: integer } + hard_stop_days: { type: integer } + status: { type: string } + LicenceHeartbeat: + type: object + properties: + status: { type: string, enum: [ok, warning, degraded, hard_stop, revoked] } + tenant_status: { $ref: "#/components/schemas/TenantStatus" } + expires_at: { type: string, format: date-time } + reason: { type: string } + renewed: { $ref: "#/components/schemas/LicenceIssued" } TenantStatus: type: string enum: [demo, trial, active, warning, restricted, frozen, halted, archived]