From 361e748f0669df4fbc6a268b962ade88e2efb803 Mon Sep 17 00:00:00 2001 From: Sharang Parnerkar <30073382+mighty840@users.noreply.github.com> Date: Mon, 23 Nov 2026 16:38:36 +0100 Subject: [PATCH] feat(updates): per-tenant self-update policy for Werkpilot A workspace can leave Werkpilot's self-update on ("auto", the default), turn it off, or pin a release version. - GET/PUT /v1/tenants/{id}/products/{product}/updates with {"policy": "auto" | "off" | ""}: the "updates" key of the product's settings document (0025, no migration); IT_ADMIN/OWNER or services; audited as product_settings.changed; werkpilot only - "updates" in licence grants (POST /v1/licences, /v1/licences/ci, heartbeat renewals) and at the top of the heartbeat answer, read fresh each time, "auto" when unset Refs platform/werkpilot#89 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Q9inRayW7ztyk1uAtwMJPR --- internal/server/authz_test.go | 4 + internal/server/licences.go | 12 +- internal/server/licences_ci.go | 3 +- internal/server/openapi_test.go | 3 + internal/server/server.go | 5 + internal/server/update_policy.go | 192 ++++++++++++++++++++ internal/server/update_policy_scope_test.go | 60 ++++++ internal/server/update_policy_test.go | 180 ++++++++++++++++++ openapi.yaml | 72 ++++++++ 9 files changed, 527 insertions(+), 4 deletions(-) create mode 100644 internal/server/update_policy.go create mode 100644 internal/server/update_policy_scope_test.go create mode 100644 internal/server/update_policy_test.go diff --git a/internal/server/authz_test.go b/internal/server/authz_test.go index 4bc9099..c57ef72 100644 --- a/internal/server/authz_test.go +++ b/internal/server/authz_test.go @@ -30,6 +30,10 @@ func TestAuthzRules(t *testing.T) { {"portal-svc", "GET", "/v1/internal/connections/c1", false}, {"portal-svc", "POST", "/v1/tenants/t1/connections", true}, {"pruefwerk-svc", "POST", "/v1/tenants/t1/connection-invites", false}, + // Update policy (werkpilot#89): the tenants groups. + {"portal-svc", "PUT", "/v1/tenants/t1/products/werkpilot/updates", true}, + {"pruefwerk-svc", "GET", "/v1/tenants/t1/products/werkpilot/updates", true}, + {"pruefwerk-svc", "PUT", "/v1/tenants/t1/products/werkpilot/updates", false}, } for _, c := range cases { if got := a.Allowed(c.azp, routeGroup(c.method, c.path)); got != c.want { diff --git a/internal/server/licences.go b/internal/server/licences.go index 171f3bb..a941146 100644 --- a/internal/server/licences.go +++ b/internal/server/licences.go @@ -41,7 +41,10 @@ type licenceResp struct { // D6: Werkpilot grants carry a per-tenant LiteLLM virtual key. The // secret is returned in this response only — never persisted, never // returned again. Absent (with a warning) when LiteLLM is off/down. - LLMAPIKey string `json:"llm_api_key,omitempty"` + LLMAPIKey string `json:"llm_api_key,omitempty"` + // Updates is the workspace's update policy for the product + // (werkpilot#89): "auto", "off" or a pinned version. Applied by the CLI. + Updates string `json:"updates"` LLMBaseURL string `json:"llm_base_url,omitempty"` Warnings []string `json:"warnings,omitempty"` } @@ -150,7 +153,8 @@ func (s *Server) issue(ctx context.Context, r *http.Request, in issueLicenceReq, if err != nil { return nil, http.StatusInternalServerError, "internal", err.Error() } - out := &licenceResp{ID: row.ID, Licence: token, Kid: s.Licences.KID(), ExpiresAt: exp, Grace: licence.DefaultGrace, Status: "ok"} + out := &licenceResp{ID: row.ID, Licence: token, Kid: s.Licences.KID(), ExpiresAt: exp, Grace: licence.DefaultGrace, Status: "ok", + Updates: s.updatePolicy(ctx, t.ID, in.Product)} llmKey := s.provisionLLMKey(ctx, t, row, renewOf, out, "") 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), "llm_key": llmKey}}) @@ -240,6 +244,7 @@ type heartbeatResp struct { ExpiresAt time.Time `json:"expires_at"` Reason string `json:"reason,omitempty"` Renewed *licenceResp `json:"renewed,omitempty"` + Updates string `json:"updates"` } // licenceHeartbeat — POST /v1/licences/heartbeat (PUBLIC_EXPLICIT; the JWT @@ -269,7 +274,7 @@ func (s *Server) licenceHeartbeat(w http.ResponseWriter, r *http.Request) { } now := s.now() _ = s.Store.TouchLicence(ctx, row.ID, now) - out := heartbeatResp{ExpiresAt: row.ExpiresAt} + out := heartbeatResp{ExpiresAt: row.ExpiresAt, Updates: updatesAuto} if row.RevokedAt != nil { out.Status, out.Reason = "revoked", "licence_revoked" writeJSON(w, http.StatusOK, out) @@ -282,6 +287,7 @@ func (s *Server) licenceHeartbeat(w http.ResponseWriter, r *http.Request) { return } out.TenantStatus = t.Status + out.Updates = s.updatePolicy(ctx, t.ID, row.Product) check, err := s.evaluateEntitlement(ctx, entitlementCheckReq{TenantID: t.ID, Product: row.Product}) if err != nil { writeError(w, http.StatusInternalServerError, "internal", err.Error()) diff --git a/internal/server/licences_ci.go b/internal/server/licences_ci.go index e3d0a42..75d4f68 100644 --- a/internal/server/licences_ci.go +++ b/internal/server/licences_ci.go @@ -152,7 +152,8 @@ func (s *Server) issueCILicence(w http.ResponseWriter, r *http.Request) { writeError(w, http.StatusInternalServerError, "internal", err.Error()) return } - out := &licenceResp{ID: row.ID, Licence: token, Kid: s.Licences.KID(), ExpiresAt: row.ExpiresAt, Grace: licence.DefaultGrace, Status: "ok"} + out := &licenceResp{ID: row.ID, Licence: token, Kid: s.Licences.KID(), ExpiresAt: row.ExpiresAt, Grace: licence.DefaultGrace, Status: "ok", + Updates: s.updatePolicy(ctx, t.ID, in.Product)} if in.Product == llmKeyProduct { if err := s.ciLLMKey(ctx, t, row, subject, day, out); err != nil { writeError(w, http.StatusInternalServerError, "internal", err.Error()) diff --git a/internal/server/openapi_test.go b/internal/server/openapi_test.go index 3b05e94..474b97e 100644 --- a/internal/server/openapi_test.go +++ b/internal/server/openapi_test.go @@ -108,6 +108,9 @@ func TestOpenAPISpec_loadsAndIsConsistent(t *testing.T) { {"POST", "/v1/licences/heartbeat"}, {"POST", "/v1/licences/ci"}, {"POST", "/v1/licences/00000000-0000-0000-0000-000000000001/revoke"}, + {"GET", "/v1/tenants/00000000-0000-0000-0000-000000000001/products/werkpilot/updates"}, + {"PUT", "/v1/tenants/00000000-0000-0000-0000-000000000001/products/werkpilot/updates"}, + {"GET", "/v1/tenants/00000000-0000-0000-0000-000000000001/products/pruefwerk/settings"}, {"GET", "/.well-known/licence-keys.json"}, {"GET", "/v1/tenants/00000000-0000-0000-0000-000000000001/managed-services"}, {"GET", "/v1/tenants/00000000-0000-0000-0000-000000000001/contracts"}, diff --git a/internal/server/server.go b/internal/server/server.go index 1bff94b..77c5506 100644 --- a/internal/server/server.go +++ b/internal/server/server.go @@ -237,6 +237,11 @@ func NewRouter(s *Server) http.Handler { mux.HandleFunc("GET /v1/licences", s.listLicences) mux.HandleFunc("POST /v1/licences/{id}/revoke", s.revokeLicence) + // Update policy per product (werkpilot#89): tenants.read / + // tenants.write, admins for user tokens; grants and heartbeats carry it. + mux.HandleFunc("GET /v1/tenants/{id}/products/{product}/updates", s.getUpdatePolicy) + mux.HandleFunc("PUT /v1/tenants/{id}/products/{product}/updates", s.putUpdatePolicy) + // 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/update_policy.go b/internal/server/update_policy.go new file mode 100644 index 0000000..59d6791 --- /dev/null +++ b/internal/server/update_policy.go @@ -0,0 +1,192 @@ +package server + +import ( + "context" + "encoding/json" + "errors" + "net/http" + "regexp" + "time" + + "git.breakpilot.com/platform/tenant-registry/internal/authn" + "git.breakpilot.com/platform/tenant-registry/internal/store" +) + +// ─── product update policy (werkpilot#89) ───────────────────────────────── +// +// A workspace decides how its CLIs update themselves: "auto" (the default, +// also when nothing is saved), "off", or a pinned release version. The +// choice is the "updates" key of the product's settings document (0025); +// licence grants and heartbeats hand it to the CLI, which applies it. Only +// products that update themselves take it: the Prüfwerk settings PUT +// replaces its whole document, so the key must never land there. + +const ( + updatesSettingKey = "updates" + updatesAuto = "auto" + updatesOff = "off" +) + +// updatePolicyProducts update themselves and so take the setting. +var updatePolicyProducts = map[string]bool{"werkpilot": true} + +// semverPin is a release version per semver.org 2.0.0 (the spec's own +// regex): no "v" prefix, no ranges, no wildcards. +var semverPin = regexp.MustCompile(`^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)` + + `(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?` + + `(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$`) + +const maxPinLength = 64 + +func validUpdatePolicy(v string) bool { + return v == updatesAuto || v == updatesOff || (len(v) <= maxPinLength && semverPin.MatchString(v)) +} + +type updatePolicyResp struct { + TenantID string `json:"tenant_id"` + Product string `json:"product"` + Policy string `json:"policy"` + UpdatedBy string `json:"updated_by,omitempty"` + UpdatedAt *time.Time `json:"updated_at,omitempty"` +} + +// updatePolicy is the workspace's current policy for product: "auto" for +// products without the setting, when none was saved, or when it cannot be +// read. +func (s *Server) updatePolicy(ctx context.Context, tenantID, product string) string { + policy, _, err := s.loadUpdatePolicy(ctx, tenantID, product) + if err != nil { + s.Log.Warn("update policy unreadable; treated as auto", "tenant_id", tenantID, "product", product, "err", err) + return updatesAuto + } + return policy +} + +// loadUpdatePolicy returns the policy and the settings row (nil when none +// was saved). +func (s *Server) loadUpdatePolicy(ctx context.Context, tenantID, product string) (string, *store.TenantProductSettings, error) { + if !updatePolicyProducts[product] { + return updatesAuto, nil, nil + } + row, err := s.Store.GetTenantProductSettings(ctx, tenantID, product) + if errors.Is(err, store.ErrNotFound) { + return updatesAuto, nil, nil + } + if err != nil { + return updatesAuto, nil, err + } + var doc map[string]json.RawMessage + if err := json.Unmarshal(row.Settings, &doc); err != nil { + return updatesAuto, nil, err + } + raw, ok := doc[updatesSettingKey] + if !ok { + return updatesAuto, row, nil + } + var policy string + if err := json.Unmarshal(raw, &policy); err != nil || !validUpdatePolicy(policy) { + return updatesAuto, nil, errors.New("stored update policy is not valid") + } + return policy, row, nil +} + +// updatePolicyScope resolves the tenant and product of a policy route. +// User tokens need IT_ADMIN or OWNER in their own workspace; services pass +// with tenants.read / tenants.write. On false the response is written. +func (s *Server) updatePolicyScope(ctx context.Context, w http.ResponseWriter, r *http.Request) (*store.Tenant, string, bool) { + if p, _ := authn.PrincipalFrom(r.Context()); p.IsUser() && !p.IsTenantAdmin() { + writeError(w, http.StatusForbidden, "FORBIDDEN_ROLE", "the update policy requires the IT_ADMIN or OWNER org role") + return nil, "", false + } + product := r.PathValue("product") + if !updatePolicyProducts[product] { + writeError(w, http.StatusNotFound, "not_found", "this product has no update policy") + return nil, "", false + } + t, ok := s.tenantInScope(ctx, w, r) + return t, product, ok +} + +func updatePolicyAnswer(tenantID, product, policy string, row *store.TenantProductSettings) updatePolicyResp { + out := updatePolicyResp{TenantID: tenantID, Product: product, Policy: policy} + if row != nil { + at := row.UpdatedAt + out.UpdatedBy, out.UpdatedAt = row.UpdatedBy, &at + } + return out +} + +// getUpdatePolicy is GET /v1/tenants/{id}/products/{product}/updates. +func (s *Server) getUpdatePolicy(w http.ResponseWriter, r *http.Request) { + ctx, cancel := context.WithTimeout(r.Context(), 10*time.Second) + defer cancel() + t, product, ok := s.updatePolicyScope(ctx, w, r) + if !ok { + return + } + policy, row, err := s.loadUpdatePolicy(ctx, t.ID, product) + if err != nil { + writeError(w, http.StatusInternalServerError, "internal", err.Error()) + return + } + writeJSON(w, http.StatusOK, updatePolicyAnswer(t.ID, product, policy, row)) +} + +// putUpdatePolicy is PUT /v1/tenants/{id}/products/{product}/updates with +// {"policy": "auto" | "off" | ""}. A save that changes nothing +// writes nothing. +func (s *Server) putUpdatePolicy(w http.ResponseWriter, r *http.Request) { + ctx, cancel := context.WithTimeout(r.Context(), 10*time.Second) + defer cancel() + t, product, ok := s.updatePolicyScope(ctx, w, r) + if !ok { + return + } + r.Body = http.MaxBytesReader(w, r.Body, 4096) + var in map[string]json.RawMessage + if !decodeJSON(w, r, &in) { + return + } + var next string + raw, has := in["policy"] + if len(in) != 1 || !has || json.Unmarshal(raw, &next) != nil || !validUpdatePolicy(next) { + writeError(w, http.StatusBadRequest, "invalid_input", `the body is {"policy": "auto" | "off" | ""}`) + return + } + cur, row, err := s.loadUpdatePolicy(ctx, t.ID, product) + if err != nil { + writeError(w, http.StatusInternalServerError, "internal", err.Error()) + return + } + if cur == next { + writeJSON(w, http.StatusOK, updatePolicyAnswer(t.ID, product, cur, row)) + return + } + doc := map[string]json.RawMessage{} + if row != nil { + if err := json.Unmarshal(row.Settings, &doc); err != nil { + writeError(w, http.StatusInternalServerError, "internal", err.Error()) + return + } + } + doc[updatesSettingKey], _ = json.Marshal(next) + settings, _ := json.Marshal(doc) + actor := s.teamActor(r) + saved, err := s.Store.PutTenantProductSettings(ctx, store.TenantProductSettings{ + TenantID: t.ID, Product: product, Settings: settings, + UpdatedBy: firstNonEmpty(actor.Email, actor.ID), UpdatedAt: s.now(), + }) + if err != nil { + if mapStoreError(w, err) { + return + } + writeError(w, http.StatusInternalServerError, "internal", err.Error()) + return + } + s.emitAudit(ctx, r, store.AuditEvent{ + TenantID: t.ID, Action: "product_settings.changed", TargetID: product, TargetType: "product_settings", + TargetName: product, ActorID: actor.ID, ActorName: actor.Email, ActorType: actor.Type, Product: product, + Metadata: map[string]interface{}{"setting": updatesSettingKey, "old": cur, "new": next}, + }) + writeJSON(w, http.StatusOK, updatePolicyAnswer(t.ID, product, next, saved)) +} diff --git a/internal/server/update_policy_scope_test.go b/internal/server/update_policy_scope_test.go new file mode 100644 index 0000000..1419550 --- /dev/null +++ b/internal/server/update_policy_scope_test.go @@ -0,0 +1,60 @@ +package server + +import ( + "context" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "git.breakpilot.com/platform/tenant-registry/internal/authn" + "git.breakpilot.com/platform/tenant-registry/internal/store" +) + +// Only a workspace administrator reads or sets the update policy, and only +// in its own workspace; another workspace's administrator gets a 404. +func TestUpdatePolicy_adminsOnly(t *testing.T) { + acme := "00000000-0000-0000-0000-000000000001" + for _, c := range []struct { + name string + tenant string + roles []string + want int + }{ + {"plain user", acme, []string{"USER"}, http.StatusForbidden}, + {"cxo", acme, []string{"CXO"}, http.StatusForbidden}, + {"finance", acme, []string{"FINANCE"}, http.StatusForbidden}, + {"another workspace's admin", "11111111-1111-1111-1111-111111111111", []string{"IT_ADMIN"}, http.StatusNotFound}, + {"it admin", acme, []string{"IT_ADMIN"}, http.StatusOK}, + {"owner", acme, []string{"OWNER"}, http.StatusOK}, + } { + for _, rt := range []struct{ method, body string }{{http.MethodGet, ""}, {http.MethodPut, `{"policy":"off"}`}} { + p := &authn.Principal{Subject: "u-1", ClientID: "portal", TenantID: c.tenant, Email: "ada@acme.test", OrgRoles: c.roles} + s, h, tenant := scopedServer(t, p) + rr := httptest.NewRecorder() + h.ServeHTTP(rr, httptest.NewRequest(rt.method, "/v1/tenants/"+tenant.ID+"/products/werkpilot/updates", strings.NewReader(rt.body))) + if rr.Code != c.want { + t.Errorf("%s %s: %d %s", c.name, rt.method, rr.Code, rr.Body.String()) + } + want := "auto" + if rt.method == http.MethodPut && c.want == http.StatusOK { + want = "off" + } + if got := s.updatePolicy(context.Background(), tenant.ID, "werkpilot"); got != want { + t.Errorf("%s %s: policy now %q", c.name, rt.method, got) + } + } + } + // The change is attributed to the administrator who made it. + p := &authn.Principal{Subject: "u-1", ClientID: "portal", TenantID: acme, Email: "ada@acme.test", OrgRoles: []string{"IT_ADMIN"}} + s, h, tenant := scopedServer(t, p) + rr := httptest.NewRecorder() + h.ServeHTTP(rr, httptest.NewRequest(http.MethodPut, "/v1/tenants/"+tenant.ID+"/products/werkpilot/updates", strings.NewReader(`{"policy":"0.3.1"}`))) + if rr.Code != http.StatusOK || !strings.Contains(rr.Body.String(), `"updated_by":"ada@acme.test"`) { + t.Fatalf("put: %d %s", rr.Code, rr.Body.String()) + } + events, _, _ := s.Store.ListAudit(context.Background(), store.AuditFilter{TenantID: tenant.ID, Action: "product_settings.changed"}) + if len(events) != 1 || events[0].ActorID != "u-1" || events[0].ActorType != "user" || events[0].Metadata["new"] != "0.3.1" { + t.Fatalf("audit: %+v", events) + } +} diff --git a/internal/server/update_policy_test.go b/internal/server/update_policy_test.go new file mode 100644 index 0000000..22b3171 --- /dev/null +++ b/internal/server/update_policy_test.go @@ -0,0 +1,180 @@ +package server_test + +import ( + "bytes" + "context" + "encoding/json" + "net/http" + "testing" + "time" + + "git.breakpilot.com/platform/tenant-registry/internal/store" +) + +type grantUpdates struct { + Licence string `json:"licence"` + Updates *string `json:"updates"` +} + +type heartbeatUpdates struct { + Status string `json:"status"` + Updates *string `json:"updates"` + Renewed *grantUpdates `json:"renewed"` +} + +func updatesPath(h *testHarness, product string) string { + return "/v1/tenants/" + h.tenant.ID + "/products/" + product + "/updates" +} + +func putPolicy(t *testing.T, h *testHarness, policy string) { + t.Helper() + resp, raw := h.do("PUT", updatesPath(h, "werkpilot"), map[string]any{"policy": policy}) + if resp.StatusCode != http.StatusOK || !bytes.Contains(raw, []byte(`"policy":"`+policy+`"`)) { + t.Fatalf("put %s: %d %s", policy, resp.StatusCode, raw) + } +} + +// Grants and heartbeats carry the workspace's current update policy for the +// licence's product: "auto" until an administrator changes it. +func TestLicences_updatePolicyFollowsTheSetting(t *testing.T) { + eachStore(t, func(t *testing.T, h *testHarness) { + fake := newFakeLiteLLM(t) + h.app.LLMKeys = fake.client() + entitle(t, h, "werkpilot", true) + entitle(t, h, "firmwerk", true) + issue := func() string { + t.Helper() + resp, raw := h.do("POST", "/v1/licences", map[string]any{"tenant_id": h.tenant.ID, "product": "werkpilot", "device": "laptop"}) + g := decode[grantUpdates](t, raw) + if resp.StatusCode != http.StatusCreated || g.Updates == nil { + t.Fatalf("issue: %d %s", resp.StatusCode, raw) + } + return *g.Updates + } + resp, raw := h.do("POST", "/v1/licences", map[string]any{"tenant_id": h.tenant.ID, "product": "werkpilot", "device": "laptop"}) + first := decode[grantUpdates](t, raw) + if resp.StatusCode != http.StatusCreated || first.Updates == nil || *first.Updates != "auto" { + t.Fatalf("default grant: %d %s", resp.StatusCode, raw) + } + beat := func() heartbeatUpdates { + t.Helper() + _, raw := h.do("POST", "/v1/licences/heartbeat", map[string]any{"licence": first.Licence}) + hb := decode[heartbeatUpdates](t, raw) + if hb.Updates == nil { + t.Fatalf("heartbeat without updates: %s", raw) + } + return hb + } + key := ciKey(t, h, "ci", "werkpilot:licence", "firmwerk:licence") + ci := func(product, device string) string { + t.Helper() + code, _, body := postCI(t, h, key, product, device) + g := decode[grantUpdates](t, []byte(body)) + if code != http.StatusCreated && code != http.StatusOK || g.Updates == nil { + t.Fatalf("ci %s: %d %s", product, code, body) + } + return *g.Updates + } + if hb := beat(); *hb.Updates != "auto" { + t.Fatalf("default heartbeat: %+v", hb) + } + if got := ci("werkpilot", "r-1"); got != "auto" { + t.Fatalf("default CI grant: %q", got) + } + resp, raw = h.do("GET", updatesPath(h, "werkpilot"), nil) + if resp.StatusCode != http.StatusOK || !bytes.Contains(raw, []byte(`"policy":"auto"`)) { + t.Fatalf("default setting: %d %s", resp.StatusCode, raw) + } + + putPolicy(t, h, "0.4.0-rc2") + putPolicy(t, h, "0.4.0-rc2") // unchanged: no write, no audit + if hb := beat(); *hb.Updates != "0.4.0-rc2" { + t.Fatalf("heartbeat after pinning: %+v", hb) + } + if got := issue(); got != "0.4.0-rc2" { + t.Fatalf("grant after pinning: %q", got) + } + if got, other := ci("werkpilot", "r-2"), ci("firmwerk", "r-1"); got != "0.4.0-rc2" || other != "auto" { + t.Fatalf("CI grants: werkpilot %q, firmwerk (no setting) %q", got, other) + } + + putPolicy(t, h, "off") + // Past half-life of the 30-day licence: renewed, with the policy. + h.app.Now = func() time.Time { return time.Now().Add(20 * 24 * time.Hour) } + hb := beat() + h.app.Now = nil + if hb.Renewed == nil || hb.Renewed.Updates == nil || *hb.Renewed.Updates != "off" || *hb.Updates != "off" { + t.Fatalf("renewal: %+v", hb) + } + + putPolicy(t, h, "auto") + if got := issue(); got != "auto" { + t.Fatalf("grant after auto: %q", got) + } + events, _, err := h.store.ListAudit(context.Background(), store.AuditFilter{TenantID: h.tenant.ID, Action: "product_settings.changed"}) + if err != nil || len(events) != 3 { + t.Fatalf("audit: %v %+v", err, events) + } + want := [][2]string{{"auto", "0.4.0-rc2"}, {"0.4.0-rc2", "off"}, {"off", "auto"}} + for _, ev := range events { + found := false + for _, w := range want { + if ev.Metadata["old"] == w[0] && ev.Metadata["new"] == w[1] { + found = true + } + } + if !found || ev.TargetID != "werkpilot" || ev.TargetType != "product_settings" || ev.Product != "werkpilot" || ev.Metadata["setting"] != "updates" { + t.Errorf("audit event: %+v", ev) + } + } + }) +} + +func TestUpdatePolicy_isChecked(t *testing.T) { + eachStore(t, func(t *testing.T, h *testHarness) { + for _, body := range []string{ + `{}`, `{"policy":""}`, `{"policy":null}`, `{"policy":1}`, `{"policy":true}`, `{"policy":"auto","other":1}`, `[]`, `nope`, + `{"policy":"on"}`, `{"policy":"Auto"}`, `{"policy":"latest"}`, `{"policy":"stable"}`, + `{"policy":"v0.3.1"}`, `{"policy":"0.3"}`, `{"policy":"0.3.1.2"}`, `{"policy":"01.3.1"}`, `{"policy":"0.3.01"}`, + `{"policy":"0.3.1-"}`, `{"policy":"0.3.1-01"}`, `{"policy":"0.3.1+"}`, `{"policy":" 0.3.1"}`, `{"policy":"0.3.1\n"}`, + `{"policy":"^0.3.1"}`, `{"policy":"~0.3"}`, `{"policy":">=0.3.1"}`, `{"policy":"0.3.x"}`, `{"policy":"0.3.*"}`, + `{"policy":"0.3.1 - 0.4.0"}`, `{"policy":"0.3.1 || 0.4.0"}`, + `{"policy":"0.3.1-` + string(bytes.Repeat([]byte("a"), 60)) + `"}`, + } { + if resp, raw := h.doRaw("PUT", updatesPath(h, "werkpilot"), body); resp.StatusCode != http.StatusBadRequest { + t.Errorf("%s: %d %s", body, resp.StatusCode, raw) + } + } + for _, policy := range []string{"0.3.1", "0.4.0-rc2", "1.0.0-alpha.1", "1.0.0+build.5", "1.0.0-rc.1+g1a2b3c", "10.20.30"} { + putPolicy(t, h, policy) + } + // Only products that update themselves take the policy. + for _, product := range []string{"pruefwerk", "firmwerk", "nope"} { + if resp, _ := h.do("PUT", updatesPath(h, product), map[string]any{"policy": "off"}); resp.StatusCode != http.StatusNotFound { + t.Errorf("put %s: %d", product, resp.StatusCode) + } + if resp, _ := h.do("GET", updatesPath(h, product), nil); resp.StatusCode != http.StatusNotFound { + t.Errorf("get %s: %d", product, resp.StatusCode) + } + } + if resp, _ := h.do("GET", "/v1/tenants/00000000-0000-0000-0000-00000000dead/products/werkpilot/updates", nil); resp.StatusCode != http.StatusNotFound { + t.Errorf("unknown tenant: %d", resp.StatusCode) + } + // Other keys of the product's settings document survive. + if _, err := h.store.PutTenantProductSettings(context.Background(), store.TenantProductSettings{ + TenantID: h.tenant.ID, Product: "werkpilot", Settings: json.RawMessage(`{"keep":42,"telemetry":true}`), UpdatedAt: time.Now(), + }); err != nil { + t.Fatal(err) + } + resp, raw := h.do("GET", updatesPath(h, "werkpilot"), nil) + if resp.StatusCode != http.StatusOK || !bytes.Contains(raw, []byte(`"policy":"auto"`)) { + t.Fatalf("document without the key: %d %s", resp.StatusCode, raw) + } + putPolicy(t, h, "off") + row, err := h.store.GetTenantProductSettings(context.Background(), h.tenant.ID, "werkpilot") + var doc map[string]any + if err != nil || json.Unmarshal(row.Settings, &doc) != nil || doc["keep"] != float64(42) || doc["telemetry"] != true || doc["updates"] != "off" { + t.Fatalf("settings document: %v %s", err, row.Settings) + } + }) +} diff --git a/openapi.yaml b/openapi.yaml index e92db7b..0da9ae4 100644 --- a/openapi.yaml +++ b/openapi.yaml @@ -793,6 +793,56 @@ paths: "403": { $ref: "#/components/responses/Forbidden" } "404": { $ref: "#/components/responses/NotFound" } + /v1/tenants/{id}/products/{product}/updates: + get: + summary: The workspace's self-update policy for a product (werkpilot#89). + description: | + `auto` until changed. Only products that update themselves take it + (today `werkpilot`; others 404). User tokens reach their own tenant + only and need IT_ADMIN or OWNER (else 403 FORBIDDEN_ROLE); service + clients read with tenants.read. + parameters: + - { in: path, name: id, required: true, schema: { type: string, format: uuid } } + - { in: path, name: product, required: true, schema: { type: string, example: werkpilot } } + responses: + "200": + description: The policy. + content: + application/json: { schema: { $ref: "#/components/schemas/UpdatePolicy" } } + "403": { $ref: "#/components/responses/Forbidden" } + "404": { $ref: "#/components/responses/NotFound" } + put: + summary: Set the self-update policy (auto, off, or a pinned version). + description: | + Same roles as the GET; service clients write with tenants.write. + `policy` is `auto`, `off`, or a release version matching the + semver 2.0.0 grammar (at most 64 characters; no `v` prefix, ranges + or wildcards). A change is audited as `product_settings.changed` + (setting `updates`, old and new value); a save that changes nothing + writes nothing. Licence grants and heartbeats report it as + `updates`. + parameters: + - { in: path, name: id, required: true, schema: { type: string, format: uuid } } + - { in: path, name: product, required: true, schema: { type: string, example: werkpilot } } + requestBody: + required: true + content: + application/json: + schema: + type: object + required: [policy] + additionalProperties: false + properties: + policy: { $ref: "#/components/schemas/UpdatePolicyValue" } + responses: + "200": + description: Saved (or unchanged). + content: + application/json: { schema: { $ref: "#/components/schemas/UpdatePolicy" } } + "400": { $ref: "#/components/responses/BadRequest" } + "403": { $ref: "#/components/responses/Forbidden" } + "404": { $ref: "#/components/responses/NotFound" } + /v1/tenants/{id}/contracts: get: summary: The tenant's Vertragsunterlagen (trial, AVV, TOM, SaaS, contract documents). @@ -2829,6 +2879,7 @@ components: type: array items: { type: string, enum: [llm_key_unavailable] } description: Non-fatal issue notes; the licence itself is valid. + updates: { $ref: "#/components/schemas/UpdatePolicyValue" } LicenceHeartbeat: type: object properties: @@ -2837,6 +2888,27 @@ components: expires_at: { type: string, format: date-time } reason: { type: string } renewed: { $ref: "#/components/schemas/LicenceIssued" } + updates: { $ref: "#/components/schemas/UpdatePolicyValue" } + UpdatePolicyValue: + type: string + example: auto + description: | + The workspace's update policy for the licence's product + (werkpilot#89), always present: `auto` (default, also when nothing + is saved and for products without the setting), `off`, or a pinned + release version (semver 2.0.0, e.g. `0.3.1`, `0.4.0-rc2`). Read + fresh on every grant and heartbeat (`auto` on revoked or + unknown-tenant heartbeats). Informational, not a JWT claim; the + CLI applies it. + UpdatePolicy: + type: object + required: [tenant_id, product, policy] + properties: + tenant_id: { type: string, format: uuid } + product: { type: string, example: werkpilot } + policy: { $ref: "#/components/schemas/UpdatePolicyValue" } + updated_by: { type: string } + updated_at: { type: string, format: date-time } TenantStatus: type: string enum: [demo, trial, active, warning, restricted, frozen, halted, archived] -- 2.54.1