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") }