Files
tenant-registry/internal/server/update_policy.go
Sharang ParnerkarandClaude Opus 5.5 361e748f06
ci / shared (pull_request) Successful in 11s
ci / test (pull_request) Successful in 6m39s
ci / image (pull_request) Skipped
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" | "<semver>"}: 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 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Q9inRayW7ztyk1uAtwMJPR
2026-11-23 16:38:36 +01:00

193 lines
6.9 KiB
Go

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" | "<semver>"}. 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" | "<semver release version, e.g. 0.3.1>"}`)
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))
}