## What - **Codes:** two workspaces connect by code. One administrator creates a code; another workspace's administrator enters it, and the two are connected at once. Each side sees only the other's display name. - **Ending:** either side can end a connection. Archiving a workspace ends all of its connections. When a workspace is purged, the other side keeps the ended connection under the name it knew. - **Product routes:** products (Prüfwerk's supplier SBOM releases first) list a tenant's active connections and check one before each delivery, under a new route group `connections.read`. ## Why Closes #138. This is phase 4 of platform/pruefwerk#1028. Prüfwerk's agent is on stage and already calls the two internal routes; without them the release screen warns that connections can't be read (see the comment on #138). Linked milestone: **n/a** (Prüfwerk #1028, phase 4) ## How **Routes:** | Call | Group | Answer | |---|---|---| | `POST /v1/tenants/{id}/connection-invites` | tenants.write | `201 {id, code, created_at, expires_at}`; the code is in this answer only | | `GET /v1/tenants/{id}/connection-invites` | tenants.read | open codes, without the codes | | `DELETE /v1/tenants/{id}/connection-invites/{invite}` | tenants.write | `204`, withdraws an unused code | | `POST /v1/tenants/{id}/connections` `{code}` | tenants.write | `201 {id, peer_name, state, created_at, ended_by_us}` | | `GET /v1/tenants/{id}/connections` | tenants.read | `{items: [...]}`, newest first | | `POST /v1/tenants/{id}/connections/{connection}/end` | tenants.write | `200`; ending one that has ended answers it unchanged | | `GET /v1/internal/tenants/{id}/connections?state=active` | **connections.read** | `{items: [{id, peer_tenant_id, peer_name}]}`; 404 for an unknown tenant | | `GET /v1/internal/connections/{connection}` | **connections.read** | `{active, tenant_ids}`; 404 for an unknown id | The two internal answers match what `compliance-agent/src/registry.rs` reads. A test pins the `items` key, because the agent defaults a missing key to "no connections". **Codes:** - 160 random bits (`crypto/rand`), shown as eight groups of four base32 letters. - Stored as SHA-256 only, looked up by hash; case, spaces and dashes don't matter. - Valid for 14 days, single use, at most 20 open per workspace. - Every code that doesn't work gets the same 404 `invalid_code`: unknown, used, expired, withdrawn, the workspace's own, or either workspace archived. - 409 `already_connected` when the two are connected already; the code then stays open. - Entering codes is limited to 20 per hour per workspace, and per person when the call names one (`keyRateLimiter` now takes its limit as an argument; CI licences keep theirs). A call from the portal's own client that names nobody has only the workspace limit. Otherwise every workspace would share one limit through that client. **portal#201 must send `X-Portal-User-Subject`.** **Redeeming** is one transaction. `SELECT … FOR UPDATE` on the code, insert the connection, then mark the code used. A partial unique index allows at most one connection per pair of workspaces that hasn't ended. A race test has two workspaces enter one code at the same time: exactly one connects. **Active** is derived on every read: not ended, both workspaces exist, and neither is archived. So no delivery can go to an archived workspace, even if writing the end failed. **Ending on archive:** every status change passes through `syncTenantStatus`, which now ends an archived workspace's connections. The admin purge calls the same step again before `DeleteTenant`, as a safety net. The foreign keys are `ON DELETE SET NULL`, with name snapshots, so the other side keeps its history. **Audit:** `connection.invite_created`, `connection.invite_withdrawn`, `connection.created` and `connection.ended` go into both workspaces' logs. - The acting side's entry names the actor. - The other side's entry is a system entry with `by: peer`: no person, IP or user agent, only the connection id and the acting side's display name. - Ends caused by archiving carry `reason: tenant_archived`. **Product routes refuse user tokens** (403 `FORBIDDEN_CLIENT`), whatever groups the token's client holds, because they carry the peer's tenant id. **Who may:** user tokens need IT_ADMIN or OWNER in their own workspace (the existing team gate, `IsTenantAdmin`). Another workspace's administrator gets a 404. The portal calls as its service client, naming the person in `X-Portal-User-*`. **Side fix:** the Postgres `GetTenant` now answers a non-UUID id as not found (404), as the memory store does. It was a 500, which the new internal route hit. ## Test plan - [x] Unit tests: route groups in `authz_test`, roles and cross-tenant scoping in `connections_scope_test`, and the OpenAPI contract cases. - [x] Integration tests on memory **and Postgres (testcontainers)** in `connections_test.go`, run locally: - connect, list, product view, check, and the re-connect after end; - every invalid code gives the same answer, including expiry with an injected clock; - archive, then purge; - unknown ids; - the rate limit; - the redeem race. - [x] The whole `internal/server` suite runs against Postgres locally (`go test -count=1 ./internal/server/`, 236 s, green). `-race` is green on the connection tests. `go vet` and `golangci-lint` v2.12.2: 0 issues. - [ ] Playwright e2e: n/a, there's no UI here (portal#201). - [ ] Manual smoke on stage after deploy, once `AUTHZ_RULES` carries the grant below. Prüfwerk's release screen should then show no warning. ## Risk **Blast radius:** new tables and routes only. Existing routes change in two small ways: the `GetTenant` 500→404 for non-UUID ids, and the archive path now also ends connections. **What could break:** - **Migration number:** `0032` is also used by the open onprem PRs (#142/#143, `0032_werkpilot_description`). Whichever merges second must renumber. A duplicate version fails the migrations test loudly. I didn't pick 0033, because golang-migrate would silently skip a 0032 that merges after it. - **Deployment grant:** the new group needs a grant in stage and prod `AUTHZ_RULES`. That config isn't in this repo: `pruefwerk-svc-stage:…,connections.read`, and the same for prod. Until it's added, Prüfwerk keeps getting 403. **Rollback plan:** revert the PR and redeploy. The down migration drops both tables. ## Decided (2026-11-20, by the product owner) - **Archived only** ends connections. A `halted` workspace keeps them, so a returning customer finds them again. Active stays false while a side is archived. - **IT_ADMIN or OWNER** may create, enter and end, using the existing team gate rather than a new catalogue right. ## Open points for review 1. **Retention:** a purged workspace's display name stays visible to its former peers through the name snapshot, with no time limit. Should it be dropped after a while? 2. **Additions to the sketch:** the create answer now carries the invite `id`, which the withdraw route needs, and there's a list of open codes, without the codes. ## Checklist - [x] Docs updated: the OpenAPI spec and the package doc in `connections.go` (no separate docs page for registry routes) - [x] Audit events emitted for state changes - [x] Secrets via Infisical, never in repo (none involved) - [x] Migration is forward-only (new tables; down drops them) - [x] Tenant scoping enforced on every DB query - [x] OpenAPI spec updated - [ ] `featureFlags.evaluate()`: n/a (nothing toggleable) - [ ] CHANGELOG entry: n/a (generated by git-cliff on release) 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01Q9inRcu428A2iNjDHPEAT9 Co-authored-by: Sharang Parnerkar <30073382+mighty840@users.noreply.github.com> Reviewed-on: #145
356 lines
18 KiB
Go
356 lines
18 KiB
Go
// Package server wires the HTTP surface for tenant-registry.
|
|
//
|
|
// All routes are registered in NewRouter; per-concern handlers live in
|
|
// peer files (tenants.go, catalog.go, apikeys.go, audit.go, keycloak.go).
|
|
package server
|
|
|
|
import (
|
|
"errors"
|
|
"git.breakpilot.com/platform/tenant-registry/internal/mail"
|
|
"git.breakpilot.com/platform/tenant-registry/internal/storage"
|
|
"git.breakpilot.com/platform/tenant-registry/internal/telemetry"
|
|
"log/slog"
|
|
"net/http"
|
|
"slices"
|
|
"strings"
|
|
"time"
|
|
|
|
"git.breakpilot.com/platform/tenant-registry/internal/authn"
|
|
"git.breakpilot.com/platform/tenant-registry/internal/buildinfo"
|
|
"git.breakpilot.com/platform/tenant-registry/internal/config"
|
|
"git.breakpilot.com/platform/tenant-registry/internal/erp"
|
|
"git.breakpilot.com/platform/tenant-registry/internal/gitea"
|
|
"git.breakpilot.com/platform/tenant-registry/internal/keycloak"
|
|
"git.breakpilot.com/platform/tenant-registry/internal/legal/contractdocs"
|
|
"git.breakpilot.com/platform/tenant-registry/internal/licence"
|
|
"git.breakpilot.com/platform/tenant-registry/internal/llmkeys"
|
|
"git.breakpilot.com/platform/tenant-registry/internal/product"
|
|
"git.breakpilot.com/platform/tenant-registry/internal/secretbox"
|
|
"git.breakpilot.com/platform/tenant-registry/internal/store"
|
|
)
|
|
|
|
// Server bundles the dependencies every handler needs.
|
|
type Server struct {
|
|
Cfg *config.Config
|
|
Log *slog.Logger
|
|
Store store.Store
|
|
Keycloak keycloak.Adapter // never nil — main wires Mock when KC env is unset
|
|
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
|
|
LLMKeys *llmkeys.Client // nil / disabled ⇒ Werkpilot grants carry no LiteLLM key (D6)
|
|
// Secrets seals CI licences' LiteLLM keys for reuse; nil ⇒ not stored.
|
|
Secrets *secretbox.Box
|
|
Objects storage.Objects // nil ⇒ document routes answer 503 (F2)
|
|
Mail mail.Sender // nil ⇒ notifications queue up unsent (F3)
|
|
Gitea *gitea.Client // Managed Git user lists (t81); nil ⇒ http.DefaultClient
|
|
Now func() time.Time // injectable clock (tests); nil ⇒ time.Now
|
|
// Contracts are the released contract documents; nil ⇒ the committed
|
|
// ones (contractdocs.Default). Tests pass their own.
|
|
Contracts *contractdocs.Catalogue
|
|
|
|
blocks blockCache // MemberBlocked answers for user tokens (team.go)
|
|
ciLimiter keyRateLimiter // CI licence issues per API key (licences_ci.go)
|
|
connLimiter keyRateLimiter // codes entered per tenant and person (connections.go)
|
|
}
|
|
|
|
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.
|
|
// Tests construct Server directly and would otherwise panic; an unset provisioner
|
|
// simply means no downstream provisioning, never a crash mid-tenant-creation.
|
|
func (s *Server) productProvisioner() product.Provisioner {
|
|
if s.Product == nil {
|
|
return product.NoopProvisioner{}
|
|
}
|
|
return s.Product
|
|
}
|
|
|
|
// NewRouter builds the http.Handler with logging middleware applied.
|
|
//
|
|
// Route auth classes (ratified auth design): /healthz and /readyz are
|
|
// PUBLIC_EXPLICIT (orca probes, no auth by design); every other route is
|
|
// INTERNAL_SERVICE_ONLY and sits behind requireAuth. New routes land in
|
|
// the protected mux by construction — registering one on the root mux is
|
|
// the exception and needs a PUBLIC_EXPLICIT justification comment.
|
|
func NewRouter(s *Server) http.Handler {
|
|
root := http.NewServeMux()
|
|
|
|
// PUBLIC_EXPLICIT: health + status probes.
|
|
root.HandleFunc("GET /healthz", s.healthz)
|
|
root.HandleFunc("GET /readyz", s.readyz)
|
|
// PUBLIC_EXPLICIT: build version and commit (portal#64), no tenant data;
|
|
// the staff dashboard and feedback reports show which build runs.
|
|
root.HandleFunc("GET /version", s.version)
|
|
// 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)
|
|
// Trial terms (portal#64): public, the same bytes before and after the offer.
|
|
root.HandleFunc("GET /v1/legal/trial-terms", s.legalTrialTerms)
|
|
root.HandleFunc("GET /v1/legal/trial-terms/{file}", s.legalTrialTermsFile)
|
|
root.HandleFunc("POST /v1/licences/heartbeat", s.licenceHeartbeat)
|
|
// PUBLIC_EXPLICIT: CI licences are authenticated by the tenant API key in
|
|
// the Authorization header (scope <product>:licence), checked in the handler.
|
|
root.HandleFunc("POST /v1/licences/ci", s.issueCILicence)
|
|
|
|
mux := http.NewServeMux()
|
|
|
|
// tenants
|
|
mux.HandleFunc("POST /v1/tenants", s.createTenant)
|
|
mux.HandleFunc("GET /v1/tenants", s.listTenants)
|
|
mux.HandleFunc("GET /v1/tenants/{id}", s.getTenant)
|
|
mux.HandleFunc("GET /v1/tenants/by-slug/{slug}", s.getTenantBySlug)
|
|
mux.HandleFunc("POST /v1/tenants/{id}/activate", s.activateTenant)
|
|
mux.HandleFunc("POST /v1/tenants/{id}/cancel", s.cancelTenant)
|
|
mux.HandleFunc("POST /v1/tenants/{id}/status", s.setTenantStatus)
|
|
// tenant members (D1) — portal Settings/Users. Route groups:
|
|
// GET members = tenants.read, POST invites = tenants.write.
|
|
//
|
|
// The GET is registered as a wildcard sub-resource, not as
|
|
// "GET /v1/tenants/{id}/members": ServeMux rejects that one as conflicting
|
|
// with "GET /v1/tenants/by-slug/{slug}", because both match
|
|
// "/v1/tenants/by-slug/members" and neither is the more specific pattern.
|
|
// "/v1/tenants/{id}/{sub}" *is* less specific than the by-slug lookup, so
|
|
// the two coexist and the lookup keeps winning for its own prefix.
|
|
mux.HandleFunc(tenantSubPattern, s.tenantSubresource)
|
|
mux.HandleFunc("POST /v1/tenants/{id}/invites", s.inviteTenantMember)
|
|
// Team management (portal#74): role, block, remove/revoke, resend.
|
|
mux.HandleFunc("PATCH /v1/tenants/{id}/members/{uid}", s.patchTenantMember)
|
|
mux.HandleFunc("DELETE /v1/tenants/{id}/members/{uid}", s.deleteTenantMember)
|
|
mux.HandleFunc("POST /v1/tenants/{id}/members/{uid}/resend", s.resendTenantMember)
|
|
// Individual capabilities (RBAC step 3, capabilities.go); the list of
|
|
// open requests is a {sub} of tenantSubresource.
|
|
mux.HandleFunc("POST /v1/tenants/{id}/members/{uid}/capabilities", s.grantCapability)
|
|
mux.HandleFunc("DELETE /v1/tenants/{id}/members/{uid}/capabilities/{cap}", s.revokeCapability)
|
|
mux.HandleFunc("POST /v1/tenants/{id}/capability-requests/{rid}/approve", s.approveCapabilityRequest)
|
|
mux.HandleFunc("DELETE /v1/tenants/{id}/capability-requests/{rid}", s.deleteCapabilityRequest)
|
|
// Trial signup (portal#64): offer, confirmation/activation, new link; the
|
|
// contract documents of a tenant.
|
|
mux.HandleFunc("POST /v1/trial-offers", s.createTrialOffer)
|
|
mux.HandleFunc("POST /v1/trial-offers/verify", s.verifyTrialOffer)
|
|
mux.HandleFunc("POST /v1/trial-offers/{id}/resend", s.resendTrialOffer)
|
|
mux.HandleFunc("GET /v1/trial-offers/{id}", s.trialOfferStatus)
|
|
mux.HandleFunc("GET /v1/tenants/{id}/contracts/trial/terms.pdf", s.tenantTrialTermsPDF)
|
|
// Contract documents (AGB, AVV, TOM, Leistungsbeschreibungen): "<doc>.pdf".
|
|
mux.HandleFunc("GET /v1/tenants/{id}/contracts/documents/{file}", s.tenantContractDocumentPDF)
|
|
// Projekte (0010): the list is a {sub} of tenantSubresource.
|
|
mux.HandleFunc("POST /v1/tenants/{id}/projects", s.createTenantProject)
|
|
mux.HandleFunc("PATCH /v1/tenants/{id}/projects/{pid}", s.updateTenantProject)
|
|
mux.HandleFunc("DELETE /v1/tenants/{id}/projects/{pid}", s.deleteTenantProject)
|
|
mux.HandleFunc("GET /v1/tenants/{id}/projects/{pid}/targets", s.listProjectTargets)
|
|
// Dokumentenablage (0022): the list is a {sub} of tenantSubresource.
|
|
mux.HandleFunc("POST /v1/tenants/{id}/store/documents", s.uploadStoreDocument)
|
|
mux.HandleFunc("GET /v1/tenants/{id}/store/documents/{doc}/original", s.storeOriginal)
|
|
mux.HandleFunc("GET /v1/tenants/{id}/store/documents/{doc}/prepared", s.storePrepared)
|
|
mux.HandleFunc("GET /v1/tenants/{id}/store/documents/{doc}/consent-banner", s.storeConsentBanner)
|
|
mux.HandleFunc("GET /v1/tenants/{id}/store/assets/{sha}", s.storeAsset)
|
|
// Unternehmensprofil (0021): the GET is a {sub} of tenantSubresource.
|
|
mux.HandleFunc("PUT /v1/tenants/{id}/company-profile", s.saveCompanyProfile)
|
|
mux.HandleFunc("POST /v1/tenants/{id}/company-profile/submit", s.submitCompanyProfile)
|
|
// Rollen- und Befugnisdatensatz (0024): the GET is a {sub} of tenantSubresource.
|
|
mux.HandleFunc("PUT /v1/tenants/{id}/role-dataset", s.saveRoleDataset)
|
|
mux.HandleFunc("GET /v1/tenants/{id}/role-dataset/revisions/{rev}", s.getRoleDatasetRevision)
|
|
mux.HandleFunc("GET /v1/tenants/{id}/role-dataset/resolve", s.resolveRoleDataset)
|
|
mux.HandleFunc("GET /v1/tenants/{id}/role-dataset/holders", s.roleDatasetHolders)
|
|
mux.HandleFunc("GET /v1/tenants/{id}/role-dataset/rules", s.roleDatasetRules)
|
|
// Prüfwerk settings (0025, t72): the workspace's Prüftag cap.
|
|
// R1 intake (0028, docgen#6 F01): intake.go.
|
|
mux.HandleFunc("POST /v1/tenants/{id}/intake/reports", s.createIntakeReport)
|
|
mux.HandleFunc("GET /v1/tenants/{id}/intake/reports", s.listIntakeReports)
|
|
mux.HandleFunc("GET /v1/tenants/{id}/intake/reports/{ref}", s.getIntakeReport)
|
|
mux.HandleFunc("POST /v1/tenants/{id}/intake/reports/{ref}/supplements", s.addIntakeSupplement)
|
|
mux.HandleFunc("GET /v1/internal/intake/pending", s.pendingIntake)
|
|
mux.HandleFunc("POST /v1/internal/intake/entries/{entry}/receipts", s.addIntakeReceipt)
|
|
mux.HandleFunc("GET /v1/tenants/{id}/products/pruefwerk/settings", s.getPruefwerkSettings)
|
|
mux.HandleFunc("PUT /v1/tenants/{id}/products/pruefwerk/settings", s.putPruefwerkSettings)
|
|
|
|
// Connections between tenants (0032, #138): the two lists are {sub}s of
|
|
// tenantSubresource; products read the internal pair (connections.read).
|
|
mux.HandleFunc("POST /v1/tenants/{id}/connection-invites", s.createConnectionInvite)
|
|
mux.HandleFunc("DELETE /v1/tenants/{id}/connection-invites/{invite}", s.deleteConnectionInvite)
|
|
mux.HandleFunc("POST /v1/tenants/{id}/connections", s.redeemConnectionInvite)
|
|
mux.HandleFunc("POST /v1/tenants/{id}/connections/{connection}/end", s.endConnection)
|
|
mux.HandleFunc("GET /v1/internal/tenants/{id}/connections", s.internalTenantConnections)
|
|
mux.HandleFunc("GET /v1/internal/connections/{connection}", s.checkConnection)
|
|
|
|
// entitlements
|
|
mux.HandleFunc("GET /v1/entitlements", s.listTenantProducts)
|
|
mux.HandleFunc("POST /v1/internal/entitlements/check", s.checkEntitlement)
|
|
|
|
// catalog
|
|
mux.HandleFunc("GET /v1/catalog", s.getCatalog)
|
|
// The catalogue of rights (RBAC step 1): read-only, group "authz".
|
|
mux.HandleFunc("GET /v1/authz/catalogue", s.getAuthzCatalogue)
|
|
mux.HandleFunc("POST /v1/catalog/request", s.catalogRequest)
|
|
mux.HandleFunc("POST /v1/catalog/trial-request", s.catalogTrialRequest)
|
|
|
|
// api keys
|
|
mux.HandleFunc("POST /v1/api-keys", s.createAPIKey)
|
|
mux.HandleFunc("GET /v1/api-keys", s.listAPIKeys)
|
|
mux.HandleFunc("GET /v1/api-keys/scopes", s.listAPIKeyScopes)
|
|
mux.HandleFunc("DELETE /v1/api-keys/{id}", s.revokeAPIKey)
|
|
mux.HandleFunc("POST /v1/internal/api-keys/verify", s.verifyAPIKey)
|
|
|
|
// audit
|
|
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/usage/summary", s.summarizeUsage)
|
|
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
|
|
// the "pull" complement for when the realm is reconfigured to fetch.
|
|
mux.HandleFunc("POST /v1/internal/keycloak/claims", s.kcClaims)
|
|
|
|
// memberships — the B2 membership authority: which tenants does a
|
|
// JWT subject belong to, with which org_roles and entitlements.
|
|
mux.HandleFunc("GET /v1/users/{id}/memberships", s.getUserMemberships)
|
|
|
|
// Staff administration (portal /admin; group "admin").
|
|
mux.HandleFunc("GET /v1/admin/tenants", s.adminListTenants)
|
|
mux.HandleFunc("GET /v1/admin/tenants/{id}", s.adminGetTenant)
|
|
mux.HandleFunc("POST /v1/admin/tenants/{id}/trial", s.adminExtendTrial)
|
|
mux.HandleFunc("POST /v1/admin/tenants/{id}/invites/resend", s.adminResendInvite)
|
|
mux.HandleFunc("PATCH /v1/admin/tenants/{id}/members/{uid}", s.adminPatchMember)
|
|
mux.HandleFunc("DELETE /v1/admin/tenants/{id}/members/{uid}", s.adminDeleteMember)
|
|
mux.HandleFunc("POST /v1/admin/tenants/{id}/members/{uid}/resend", s.adminResendMember)
|
|
mux.HandleFunc("POST /v1/admin/tenants/{id}/reprovision", s.adminReprovision)
|
|
mux.HandleFunc("DELETE /v1/admin/tenants/{id}", s.adminPurgeTenant)
|
|
// Preview grants of products not for sale yet (staff only, audited).
|
|
mux.HandleFunc("POST /v1/admin/tenants/{id}/preview-grants", s.adminGrantPreview)
|
|
mux.HandleFunc("DELETE /v1/admin/tenants/{id}/preview-grants/{product}", s.adminRevokePreview)
|
|
mux.HandleFunc("GET /v1/admin/audit", s.listAudit)
|
|
mux.HandleFunc("POST /v1/admin/tenants/{id}/store/import", s.importStore)
|
|
mux.HandleFunc("GET /v1/admin/tenants/{id}/company-profile", s.getCompanyProfile)
|
|
mux.HandleFunc("PUT /v1/admin/tenants/{id}/company-profile", s.importCompanyProfile)
|
|
// The tenant's own filled AVV (0027): its details, then the PDF.
|
|
mux.HandleFunc("GET /v1/admin/tenants/{id}/avv-values", s.adminAVVValues)
|
|
mux.HandleFunc("PUT /v1/admin/tenants/{id}/contract-documents/avv", s.adminPutAVV)
|
|
mux.HandleFunc("GET /v1/admin/tenants/{id}/documents", s.adminListDocuments)
|
|
mux.HandleFunc("POST /v1/admin/tenants/{id}/documents", s.adminUploadDocument)
|
|
mux.HandleFunc("POST /v1/admin/documents/{doc}/publish", s.adminPublishDocument)
|
|
mux.HandleFunc("DELETE /v1/admin/documents/{doc}", s.adminDeleteDocument)
|
|
mux.HandleFunc("PATCH /v1/admin/documents/{doc}", s.adminUpdateDocument)
|
|
// Managed services (0012, portal#77); the tenant's list is a {sub} of
|
|
// tenantSubresource.
|
|
mux.HandleFunc("GET /v1/admin/tenants/{id}/managed-services", s.adminListManagedServices)
|
|
mux.HandleFunc("POST /v1/admin/tenants/{id}/managed-services", s.adminCreateManagedService)
|
|
mux.HandleFunc("PATCH /v1/admin/tenants/{id}/managed-services/{sid}", s.adminUpdateManagedService)
|
|
mux.HandleFunc("DELETE /v1/admin/tenants/{id}/managed-services/{sid}", s.adminDeleteManagedService)
|
|
// Module users (0031, t81): the Git instance's read:admin token (sealed,
|
|
// write-only), the month's counts, and the count pass on demand; the
|
|
// tenant's counts are a {sub} of tenantSubresource.
|
|
mux.HandleFunc("PUT /v1/admin/tenants/{id}/managed-services/{sid}/admin-token", s.adminSetServiceToken)
|
|
mux.HandleFunc("GET /v1/admin/tenants/{id}/module-users", s.adminModuleUsers)
|
|
mux.HandleFunc("POST /v1/internal/module-users/count", s.moduleUsersCountNow)
|
|
|
|
// Notifications from products (F3; group "notify").
|
|
mux.HandleFunc("POST /v1/notifications", s.postNotification)
|
|
|
|
// Tenant documents (F2): the list is a {sub} of tenantSubresource.
|
|
mux.HandleFunc("GET /v1/tenants/{id}/documents/{doc}/download", s.downloadTenantDocument)
|
|
|
|
root.Handle("/", s.requireAuth(s.requireMember(s.requireAuthz(mux))))
|
|
// The matched pattern names the span and the access-log line; the raw path
|
|
// carries slugs and stays out of both.
|
|
route := func(r *http.Request) string {
|
|
if _, p := root.Handler(r); p != "/" {
|
|
return p
|
|
}
|
|
_, p := mux.Handler(r)
|
|
if p == tenantSubPattern {
|
|
return subRoute(r.URL.Path)
|
|
}
|
|
return p
|
|
}
|
|
return telemetry.Middleware(route, logRequest(s.Log, route)(root))
|
|
}
|
|
|
|
// requireAuth gates the INTERNAL_SERVICE_ONLY routes. With Auth nil
|
|
// (AUTH_ENABLED=false) it passes through — the startup log carries the
|
|
// warning, and the Auth-5 activation flips the env, not the code.
|
|
func (s *Server) requireAuth(next http.Handler) http.Handler {
|
|
if s.Auth == nil {
|
|
return next
|
|
}
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
p, err := s.Auth.Verify(r.Context(), r.Header.Get("Authorization"))
|
|
if err != nil {
|
|
if errors.Is(err, authn.ErrNoToken) {
|
|
writeError(w, http.StatusUnauthorized, "TOKEN_MISSING", "bearer token required")
|
|
return
|
|
}
|
|
// Signature, issuer, expiry, and audience failures all land
|
|
// here; the message says which without echoing the token.
|
|
writeError(w, http.StatusUnauthorized, "TOKEN_INVALID", err.Error())
|
|
return
|
|
}
|
|
next.ServeHTTP(w, r.WithContext(authn.WithPrincipal(r.Context(), p)))
|
|
})
|
|
}
|
|
|
|
func (s *Server) healthz(w http.ResponseWriter, _ *http.Request) {
|
|
writeJSON(w, http.StatusOK, map[string]string{"status": "ok"})
|
|
}
|
|
|
|
// version reports the build (internal/buildinfo, set at image build time).
|
|
func (s *Server) version(w http.ResponseWriter, _ *http.Request) {
|
|
writeJSON(w, http.StatusOK, map[string]string{"version": buildinfo.Version, "commit": buildinfo.Commit})
|
|
}
|
|
|
|
func (s *Server) readyz(w http.ResponseWriter, r *http.Request) {
|
|
if err := s.Store.Ping(r.Context()); err != nil {
|
|
writeError(w, http.StatusServiceUnavailable, "store_unavailable", err.Error())
|
|
return
|
|
}
|
|
if err := s.Keycloak.Health(r.Context()); err != nil {
|
|
writeError(w, http.StatusServiceUnavailable, "keycloak_unavailable", err.Error())
|
|
return
|
|
}
|
|
writeJSON(w, http.StatusOK, map[string]string{"status": "ready"})
|
|
}
|
|
|
|
// tenantSubPattern is the wildcard route of tenantSubresource.
|
|
const tenantSubPattern = "GET /v1/tenants/{id}/{sub}"
|
|
|
|
// subRoute names a tenantSubresource request after the collection it asks for
|
|
// ("GET /v1/tenants/{id}/store"), so SigNoz can tell them apart. Only known
|
|
// collection names make it in; any other segment keeps the wildcard pattern.
|
|
func subRoute(path string) string {
|
|
parts := strings.Split(strings.TrimPrefix(path, "/"), "/")
|
|
if len(parts) == 4 && slices.Contains(tenantSubresources, parts[3]) {
|
|
return "GET /v1/tenants/{id}/" + parts[3]
|
|
}
|
|
return tenantSubPattern
|
|
}
|