Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

MUL-6341: add fail-open entitlement policy provider (#7148)

Multica Evea35a75ab165a
diff --git a/server/internal/entitlement/README.md b/server/internal/entitlement/README.md
new file mode 100644
index 0000000000..dbb784825c
--- /dev/null
+++ b/server/internal/entitlement/README.md
@@ -0,0 +1,52 @@
+# Entitlement policy consumer
+
+This package is the mechanical Multica-side consumer of the private Cloud
+enforcement-policy endpoint. Commercial inputs stay in Cloud: this package does
+not contain plan names, subscription-state mapping, rollout dates, cohorts,
+exemptions, limit values, or kill-switch policy.
+
+PR-2 intentionally has no production caller. `Config.Enabled` defaults to
+`false`, a disabled client performs no HTTP request, and all gates return `off`.
+Future SaaS wiring must explicitly enable and construct the client; self-hosted
+deployments remain disabled.
+
+## Contract
+
+The client reads:
+
+- `schema_version`: only version 1 is accepted.
+- `policy_revision` and `subscription_version`: independently monotonic. A
+ response that moves either revision backwards cannot replace a cached policy
+ while it is still usable for fresh or stale decisions. After the bounded
+ stale window ends, the cache accepts the current Cloud response so an
+ accidental operator rollback cannot create a permanent retry loop.
+- `valid_for_seconds`: the enforcement TTL, measured from local receipt time
+ with Go's monotonic clock. It is capped at five minutes. This is authoritative
+ for enforcement expiry.
+- `valid_until`: diagnostic Cloud wall-clock time only; it is never used to
+ extend enforcement.
+- `gates`: effective `off`, `observe`, or `enforce` instructions and parameters.
+
+Responses tolerate unknown JSON fields for additive compatibility. Unknown
+schema/action, malformed fields, missing gates, HTTP failures, authentication
+failures, and timeouts fail open.
+
+## Cache and degradation
+
+The cache is workspace-keyed, LRU-bounded, and collapses concurrent refreshes
+for one workspace through `singleflight`. Shared refreshes retain request values
+but are detached from the first caller's cancellation; an independent
+three-second maximum timeout bounds their lifetime. A fresh entry is returned
+without an HTTP call. After its local TTL expires, refresh is attempted. If
+refresh fails during the bounded stale grace,
+cached `enforce` is downgraded to `observe`; after the grace, the result is
+`off`. Stale policy never blocks. A five-second per-workspace retry suppression
+also bounds Cloud request rate when an outage returns errors immediately; cold
+failures are cached only as `off` and never as policy.
+
+`SetEmergencyDisabled(true)` is the local immediate down switch. It only returns
+`off`; it cannot promote a Cloud action. No background goroutine, database
+state, migration, or startup dependency is introduced by this package.
+
+Future consumers should depend on the small `Provider` interface. Tests can use
+`server/internal/entitlement/entitlementtest.Stub` without Cloud.
diff --git a/server/internal/entitlement/cache.go b/server/internal/entitlement/cache.go
new file mode 100644
index 0000000000..3b09b6faf8
--- /dev/null
+++ b/server/internal/entitlement/cache.go
@@ -0,0 +1,123 @@
+package entitlement
+
+import (
+ "container/list"
+ "errors"
+ "sync"
+ "time"
+
+ "github.com/google/uuid"
+)
+
+var errVersionRegression = errors.New("entitlement policy version regression")
+
+type policySnapshot struct {
+ policyRevision int64
+ subscriptionVersion int64
+ cloudValidUntil time.Time
+ gates map[GateName]Gate
+}
+
+type cacheEntry struct {
+ hasPolicy bool
+ policy policySnapshot
+ freshUntil time.Time
+ staleUntil time.Time
+ retryAfter time.Time
+}
+
+type cacheItem struct {
+ workspaceID uuid.UUID
+ entry cacheEntry
+}
+
+// policyCache is a workspace-keyed LRU. The workspace key is never inferred
+// from response data, preventing one tenant's policy from entering another
+// tenant's cache slot.
+type policyCache struct {
+ mu sync.Mutex
+ maxEntries int
+ order *list.List
+ entries map[uuid.UUID]*list.Element
+}
+
+func newPolicyCache(maxEntries int) *policyCache {
+ return &policyCache{
+ maxEntries: maxEntries,
+ order: list.New(),
+ entries: make(map[uuid.UUID]*list.Element, maxEntries),
+ }
+}
+
+func (c *policyCache) get(workspaceID uuid.UUID) (cacheEntry, bool) {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ elem, ok := c.entries[workspaceID]
+ if !ok {
+ return cacheEntry{}, false
+ }
+ c.order.MoveToFront(elem)
+ return elem.Value.(*cacheItem).entry, true
+}
+
+func (c *policyCache) put(workspaceID uuid.UUID, entry cacheEntry, receivedAt time.Time) (cacheEntry, error) {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ if elem, ok := c.entries[workspaceID]; ok {
+ current := elem.Value.(*cacheItem).entry
+ // The version guard prevents an out-of-order response from replacing a
+ // snapshot that is still usable for bounded stale observation. Once that
+ // window ends, accepting the current Cloud response lets an operator
+ // recover from an accidental revision rollback without a retry storm.
+ guardVersions := current.hasPolicy && receivedAt.Before(current.staleUntil)
+ if guardVersions && entry.policy.policyRevision < current.policy.policyRevision {
+ return current, &revisionError{source: "policy"}
+ }
+ if guardVersions && entry.policy.subscriptionVersion < current.policy.subscriptionVersion {
+ return current, &revisionError{source: "subscription"}
+ }
+ elem.Value.(*cacheItem).entry = entry
+ c.order.MoveToFront(elem)
+ return entry, nil
+ }
+
+ c.insert(workspaceID, entry)
+ return entry, nil
+}
+
+func (c *policyCache) markFailure(workspaceID uuid.UUID, retryAfter time.Time) {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ if elem, ok := c.entries[workspaceID]; ok {
+ item := elem.Value.(*cacheItem)
+ item.entry.retryAfter = retryAfter
+ c.order.MoveToFront(elem)
+ return
+ }
+ c.insert(workspaceID, cacheEntry{retryAfter: retryAfter})
+}
+
+// insert requires c.mu to be held.
+func (c *policyCache) insert(workspaceID uuid.UUID, entry cacheEntry) {
+ elem := c.order.PushFront(&cacheItem{workspaceID: workspaceID, entry: entry})
+ c.entries[workspaceID] = elem
+ if c.order.Len() > c.maxEntries {
+ oldest := c.order.Back()
+ item := oldest.Value.(*cacheItem)
+ delete(c.entries, item.workspaceID)
+ c.order.Remove(oldest)
+ }
+}
+
+func (c *policyCache) len() int {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ return len(c.entries)
+}
+
+type revisionError struct {
+ source string
+}
+
+func (e *revisionError) Error() string { return errVersionRegression.Error() }
+func (e *revisionError) Unwrap() error { return errVersionRegression }
diff --git a/server/internal/entitlement/client.go b/server/internal/entitlement/client.go
new file mode 100644
index 0000000000..73a66dd6b7
--- /dev/null
+++ b/server/internal/entitlement/client.go
@@ -0,0 +1,465 @@
+package entitlement
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "log/slog"
+ "net/http"
+ "net/url"
+ "strings"
+ "sync/atomic"
+ "time"
+
+ "github.com/google/uuid"
+ "golang.org/x/sync/singleflight"
+)
+
+const (
+ defaultRequestTimeout = 3 * time.Second
+ maxRequestTimeout = 3 * time.Second
+ defaultMaxEntries = 10_000
+ defaultStaleGrace = 15 * time.Minute
+ defaultFailureRetry = 5 * time.Second
+ maxPolicyTTL = 5 * time.Minute
+ maxResponseBodySize = 64 << 10
+ minServiceTokenBytes = 32
+)
+
+var (
+ ErrInvalidConfig = errors.New("entitlement: invalid configuration")
+ ErrInvalidPolicy = errors.New("entitlement: invalid policy response")
+)
+
+// Config has no environment-loading side effects. A zero Config is disabled,
+// so self-hosted deployments and existing server construction stay unchanged.
+// A future SaaS-only wiring change must explicitly set Enabled and provide the
+// independent service credential issued for the Cloud policy endpoint.
+type Config struct {
+ Enabled bool
+ BaseURL string
+ ServiceToken string
+ Timeout time.Duration
+ MaxEntries int
+ StaleGrace time.Duration
+ HTTPClient *http.Client
+ Observer Observer
+ Logger *slog.Logger
+}
+
+// Client implements Provider with a bounded workspace cache and one in-flight
+// refresh per workspace. It has no goroutines or background lifecycle.
+type Client struct {
+ enabled bool
+ baseURL *url.URL
+ serviceToken string
+ timeout time.Duration
+ staleGrace time.Duration
+ httpClient *http.Client
+ observer Observer
+ logger *slog.Logger
+ now func() time.Time
+ cache *policyCache
+ refreshes singleflight.Group
+ emergencyOff atomic.Bool
+}
+
+var _ Provider = (*Client)(nil)
+
+func New(cfg Config) (*Client, error) {
+ if !cfg.Enabled {
+ return &Client{observer: cfg.Observer, now: time.Now}, nil
+ }
+
+ rawBaseURL := strings.TrimRight(strings.TrimSpace(cfg.BaseURL), "/")
+ baseURL, err := url.Parse(rawBaseURL)
+ if err != nil || (baseURL.Scheme != "http" && baseURL.Scheme != "https") || baseURL.Host == "" ||
+ baseURL.User != nil || baseURL.RawQuery != "" || baseURL.Fragment != "" {
+ return nil, fmt.Errorf("%w: base URL must be an absolute URL without credentials, query, or fragment", ErrInvalidConfig)
+ }
+ if cfg.ServiceToken != strings.TrimSpace(cfg.ServiceToken) || strings.ContainsAny(cfg.ServiceToken, " \t\r\n") || len(cfg.ServiceToken) < minServiceTokenBytes {
+ return nil, fmt.Errorf("%w: service token must contain at least %d non-whitespace bytes", ErrInvalidConfig, minServiceTokenBytes)
+ }
+
+ timeout := cfg.Timeout
+ if timeout == 0 {
+ timeout = defaultRequestTimeout
+ }
+ if timeout < 0 || timeout > maxRequestTimeout {
+ return nil, fmt.Errorf("%w: timeout must be positive and at most %s", ErrInvalidConfig, maxRequestTimeout)
+ }
+ maxEntries := cfg.MaxEntries
+ if maxEntries == 0 {
+ maxEntries = defaultMaxEntries
+ }
+ if maxEntries < 0 {
+ return nil, fmt.Errorf("%w: max entries must be positive", ErrInvalidConfig)
+ }
+ staleGrace := cfg.StaleGrace
+ if staleGrace == 0 {
+ staleGrace = defaultStaleGrace
+ }
+ if staleGrace < 0 {
+ return nil, fmt.Errorf("%w: stale grace must not be negative", ErrInvalidConfig)
+ }
+ httpClient := &http.Client{}
+ if cfg.HTTPClient != nil {
+ clone := *cfg.HTTPClient
+ httpClient = &clone
+ }
+ // Never forward the independent service credential through an HTTP redirect.
+ httpClient.CheckRedirect = func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }
+ logger := cfg.Logger
+ if logger == nil {
+ logger = slog.Default()
+ }
+
+ return &Client{
+ enabled: true,
+ baseURL: baseURL,
+ serviceToken: cfg.ServiceToken,
+ timeout: timeout,
+ staleGrace: staleGrace,
+ httpClient: httpClient,
+ observer: cfg.Observer,
+ logger: logger,
+ now: time.Now,
+ cache: newPolicyCache(maxEntries),
+ }, nil
+}
+
+func (c *Client) Enabled() bool { return c != nil && c.enabled }
+
+// SetEmergencyDisabled is a local, server-only down switch. It can suppress a
+// Cloud action immediately, but can never promote off or observe to enforce.
+func (c *Client) SetEmergencyDisabled(disabled bool) {
+ if c != nil {
+ c.emergencyOff.Store(disabled)
+ }
+}
+
+func (c *Client) Gate(ctx context.Context, workspaceID uuid.UUID, name GateName) Decision {
+ if !c.Enabled() {
+ return c.recordDecision(name, offDecision(ReasonDisabled))
+ }
+ if c.emergencyOff.Load() {
+ return c.recordDecision(name, offDecision(ReasonEmergencyDisabled))
+ }
+ if workspaceID == uuid.Nil {
+ return c.recordDecision(name, offDecision(ReasonInvalidWorkspace))
+ }
+ if !name.valid() {
+ return c.recordDecision(name, offDecision(ReasonUnknownGate))
+ }
+
+ now := c.now()
+ cached, cachedOK := c.cache.get(workspaceID)
+ if cachedOK && cached.hasPolicy && now.Before(cached.freshUntil) {
+ c.recordCache("hit")
+ return c.recordDecision(name, decisionFromEntry(cached, name, ReasonCacheFresh, false))
+ }
+ if cachedOK && now.Before(cached.retryAfter) {
+ c.recordCache("retry_suppressed")
+ if cached.hasPolicy && now.Before(cached.staleUntil) {
+ return c.recordDecision(name, decisionFromEntry(cached, name, ReasonStale, true))
+ }
+ return c.recordDecision(name, offDecision(ReasonUnavailable))
+ }
+ if cachedOK && cached.hasPolicy {
+ c.recordCache("expired")
+ } else {
+ c.recordCache("miss")
+ }
+
+ entry, refreshed, err := c.refresh(ctx, workspaceID)
+ if err == nil {
+ if c.emergencyOff.Load() {
+ return c.recordDecision(name, offDecision(ReasonEmergencyDisabled))
+ }
+ reason := ReasonRefreshed
+ if !refreshed {
+ reason = ReasonCacheFresh
+ }
+ return c.recordDecision(name, decisionFromEntry(entry, name, reason, false))
+ }
+
+ if c.emergencyOff.Load() {
+ return c.recordDecision(name, offDecision(ReasonEmergencyDisabled))
+ }
+ // A stale policy is safe only after enforcement is downgraded to observe.
+ // Re-read the cache because another caller may have refreshed it while this
+ // call was waiting in singleflight.
+ now = c.now()
+ if cached, ok := c.cache.get(workspaceID); ok && cached.hasPolicy && now.Before(cached.staleUntil) {
+ return c.recordDecision(name, decisionFromEntry(cached, name, ReasonStale, true))
+ }
+ reason := ReasonUnavailable
+ if errors.Is(err, ErrInvalidPolicy) {
+ reason = ReasonInvalidPolicy
+ }
+ if errors.Is(err, errVersionRegression) {
+ reason = ReasonVersionRegression
+ }
+ return c.recordDecision(name, offDecision(reason))
+}
+
+type refreshResult struct {
+ entry cacheEntry
+ refreshed bool
+}
+
+func (c *Client) refresh(ctx context.Context, workspaceID uuid.UUID) (cacheEntry, bool, error) {
+ // A refresh is shared by all callers for this workspace, so its lifetime
+ // cannot belong to whichever request happens to enter singleflight first.
+ // Keep request-scoped values, but let the independent fetch timeout bound it.
+ refreshCtx := context.WithoutCancel(ctx)
+ value, err, _ := c.refreshes.Do(workspaceID.String(), func() (any, error) {
+ now := c.now()
+ if cached, ok := c.cache.get(workspaceID); ok {
+ if cached.hasPolicy && now.Before(cached.freshUntil) {
+ return refreshResult{entry: cached}, nil
+ }
+ if now.Before(cached.retryAfter) {
+ return nil, &fetchError{outcome: "retry_suppressed"}
+ }
+ }
+
+ started := time.Now()
+ policy, err := c.fetch(refreshCtx, workspaceID)
+ if err != nil {
+ c.cache.markFailure(workspaceID, c.now().Add(defaultFailureRetry))
+ c.recordRefresh(refreshOutcome(err), time.Since(started))
+ c.logger.DebugContext(refreshCtx, "entitlement policy refresh failed",
+ "workspace_id", workspaceID.String(), "outcome", refreshOutcome(err))
+ return nil, err
+ }
+ receivedAt := c.now()
+ ttl := time.Duration(policy.validForSeconds) * time.Second
+ entry := cacheEntry{
+ hasPolicy: true,
+ policy: policy.snapshot,
+ freshUntil: receivedAt.Add(ttl),
+ staleUntil: receivedAt.Add(ttl).Add(c.staleGrace),
+ }
+ stored, err := c.cache.put(workspaceID, entry, receivedAt)
+ if err != nil {
+ c.cache.markFailure(workspaceID, c.now().Add(defaultFailureRetry))
+ var regression *revisionError
+ source := "unknown"
+ if errors.As(err, &regression) {
+ source = regression.source
+ if c.observer != nil {
+ c.observer.RecordEntitlementVersionRegression(source)
+ }
+ }
+ c.recordRefresh("version_regression", time.Since(started))
+ c.logger.WarnContext(refreshCtx, "entitlement policy revision regressed",
+ "workspace_id", workspaceID.String(), "source", source)
+ return nil, err
+ }
+ c.recordRefresh("ok", time.Since(started))
+ return refreshResult{entry: stored, refreshed: true}, nil
+ })
+ if err != nil {
+ return cacheEntry{}, false, err
+ }
+ result := value.(refreshResult)
+ return result.entry, result.refreshed, nil
+}
+
+type wirePolicy struct {
+ SchemaVersion int `json:"schema_version"`
+ PolicyRevision int64 `json:"policy_revision"`
+ SubscriptionVersion int64 `json:"subscription_version"`
+ ValidUntil time.Time `json:"valid_until"`
+ ValidForSeconds int64 `json:"valid_for_seconds"`
+ Gates map[string]wireGate `json:"gates"`
+}
+
+type wireGate struct {
+ Action string `json:"action"`
+ Limit *int `json:"limit"`
+ PeriodStart *time.Time `json:"period_start"`
+ PeriodEnd *time.Time `json:"period_end"`
+ ResetAt *time.Time `json:"reset_at"`
+}
+
+type fetchedPolicy struct {
+ snapshot policySnapshot
+ validForSeconds int64
+}
+
+func (c *Client) fetch(ctx context.Context, workspaceID uuid.UUID) (fetchedPolicy, error) {
+ u := *c.baseURL
+ u.Path = strings.TrimRight(c.baseURL.Path, "/") + "/api/v1/internal/entitlement-policies/" + workspaceID.String()
+ u.RawQuery = ""
+ u.Fragment = ""
+
+ requestCtx, cancel := context.WithTimeout(ctx, c.timeout)
+ defer cancel()
+ req, err := http.NewRequestWithContext(requestCtx, http.MethodGet, u.String(), nil)
+ if err != nil {
+ return fetchedPolicy{}, &fetchError{outcome: "request"}
+ }
+ req.Header.Set("Accept", "application/json")
+ req.Header.Set("Authorization", "Bearer "+c.serviceToken)
+
+ resp, err := c.httpClient.Do(req)
+ if err != nil {
+ if errors.Is(err, context.DeadlineExceeded) || errors.Is(requestCtx.Err(), context.DeadlineExceeded) {
+ return fetchedPolicy{}, &fetchError{outcome: "timeout"}
+ }
+ return fetchedPolicy{}, &fetchError{outcome: "network"}
+ }
+ defer resp.Body.Close()
+ if resp.StatusCode != http.StatusOK {
+ return fetchedPolicy{}, &fetchError{outcome: statusOutcome(resp.StatusCode)}
+ }
+ body, err := io.ReadAll(io.LimitReader(resp.Body, maxResponseBodySize+1))
+ if err != nil {
+ return fetchedPolicy{}, &fetchError{outcome: "read"}
+ }
+ if len(body) > maxResponseBodySize {
+ return fetchedPolicy{}, fmt.Errorf("%w: response exceeds %d bytes", ErrInvalidPolicy, maxResponseBodySize)
+ }
+ var wire wirePolicy
+ if err := json.Unmarshal(body, &wire); err != nil {
+ return fetchedPolicy{}, fmt.Errorf("%w: malformed JSON", ErrInvalidPolicy)
+ }
+ return normalizePolicy(wire)
+}
+
+func normalizePolicy(wire wirePolicy) (fetchedPolicy, error) {
+ if wire.SchemaVersion != SchemaVersion || wire.PolicyRevision <= 0 || wire.SubscriptionVersion < 0 ||
+ wire.ValidUntil.IsZero() || wire.ValidForSeconds <= 0 || wire.ValidForSeconds > int64(maxPolicyTTL/time.Second) {
+ return fetchedPolicy{}, ErrInvalidPolicy
+ }
+ gates := make(map[GateName]Gate, 2)
+ for _, name := range []GateName{GateIssueWindow, GateAutopilotRuns} {
+ wireGate, ok := wire.Gates[string(name)]
+ if !ok {
+ return fetchedPolicy{}, ErrInvalidPolicy
+ }
+ gate, err := normalizeGate(name, wireGate)
+ if err != nil {
+ return fetchedPolicy{}, err
+ }
+ gates[name] = gate
+ }
+ return fetchedPolicy{
+ snapshot: policySnapshot{
+ policyRevision: wire.PolicyRevision,
+ subscriptionVersion: wire.SubscriptionVersion,
+ cloudValidUntil: wire.ValidUntil,
+ gates: gates,
+ },
+ validForSeconds: wire.ValidForSeconds,
+ }, nil
+}
+
+func normalizeGate(name GateName, wire wireGate) (Gate, error) {
+ action := Action(wire.Action)
+ switch action {
+ case ActionOff:
+ return Gate{Action: ActionOff}, nil
+ case ActionObserve, ActionEnforce:
+ default:
+ return Gate{}, ErrInvalidPolicy
+ }
+ if wire.Limit == nil || *wire.Limit < 0 {
+ return Gate{}, ErrInvalidPolicy
+ }
+ periodFields := 0
+ for _, value := range []*time.Time{wire.PeriodStart, wire.PeriodEnd, wire.ResetAt} {
+ if value != nil {
+ periodFields++
+ }
+ }
+ if periodFields != 0 && periodFields != 3 {
+ return Gate{}, ErrInvalidPolicy
+ }
+ if name == GateAutopilotRuns && periodFields != 3 {
+ return Gate{}, ErrInvalidPolicy
+ }
+ if periodFields == 3 && (!wire.PeriodStart.Before(*wire.PeriodEnd) || !wire.PeriodStart.Before(*wire.ResetAt)) {
+ return Gate{}, ErrInvalidPolicy
+ }
+ limit := *wire.Limit
+ gate := Gate{Action: action, Limit: &limit}
+ if periodFields == 3 {
+ start, end, reset := *wire.PeriodStart, *wire.PeriodEnd, *wire.ResetAt
+ gate.PeriodStart, gate.PeriodEnd, gate.ResetAt = &start, &end, &reset
+ }
+ return gate, nil
+}
+
+func decisionFromEntry(entry cacheEntry, name GateName, reason Reason, stale bool) Decision {
+ gate := cloneGate(entry.policy.gates[name])
+ if stale && gate.Action == ActionEnforce {
+ gate.Action = ActionObserve
+ }
+ return Decision{
+ Gate: gate,
+ Reason: reason,
+ PolicyRevision: entry.policy.policyRevision,
+ SubscriptionVersion: entry.policy.subscriptionVersion,
+ CloudValidUntil: entry.policy.cloudValidUntil,
+ }
+}
+
+type fetchError struct {
+ outcome string
+}
+
+func (e *fetchError) Error() string { return "entitlement policy fetch failed: " + e.outcome }
+
+func statusOutcome(status int) string {
+ switch {
+ case status == http.StatusUnauthorized:
+ return "unauthorized"
+ case status == http.StatusNotFound:
+ return "not_found"
+ case status >= 500 && status < 600:
+ return "5xx"
+ case status >= 400 && status < 500:
+ return "4xx"
+ default:
+ return "status"
+ }
+}
+
+func refreshOutcome(err error) string {
+ var fetchErr *fetchError
+ if errors.As(err, &fetchErr) {
+ return fetchErr.outcome
+ }
+ if errors.Is(err, ErrInvalidPolicy) {
+ return "invalid_policy"
+ }
+ return "error"
+}
+
+func (c *Client) recordCache(outcome string) {
+ if c != nil && c.observer != nil {
+ c.observer.RecordEntitlementCache(outcome)
+ }
+}
+
+func (c *Client) recordRefresh(outcome string, duration time.Duration) {
+ if c != nil && c.observer != nil {
+ c.observer.RecordEntitlementRefresh(outcome, duration.Seconds())
+ }
+}
+
+func (c *Client) recordDecision(name GateName, decision Decision) Decision {
+ if c != nil && c.observer != nil {
+ gate := "unknown"
+ if name.valid() {
+ gate = string(name)
+ }
+ c.observer.RecordEntitlementDecision(gate, string(decision.Gate.Action), string(decision.Reason))
+ }
+ return cloneDecision(decision)
+}
diff --git a/server/internal/entitlement/client_test.go b/server/internal/entitlement/client_test.go
new file mode 100644
index 0000000000..d09e5d6f1e
--- /dev/null
+++ b/server/internal/entitlement/client_test.go
@@ -0,0 +1,744 @@
+package entitlement
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "io"
+ "log/slog"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "sync"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "github.com/google/uuid"
+)
+
+const (
+ testServiceToken = "01234567890123456789012345678901"
+ testIssueLimit = 137
+ testAutopilotLimit = 23
+)
+
+func TestDefaultConfigIsDisabledAndPerformsNoIO(t *testing.T) {
+ var calls atomic.Int64
+ client, err := New(Config{HTTPClient: &http.Client{Transport: roundTripFunc(func(*http.Request) (*http.Response, error) {
+ calls.Add(1)
+ return nil, errors.New("must not be called")
+ })}})
+ if err != nil {
+ t.Fatalf("New: %v", err)
+ }
+ if client.Enabled() {
+ t.Fatal("zero Config must be disabled")
+ }
+ decision := client.Gate(context.Background(), uuid.New(), GateIssueWindow)
+ if decision.Gate.Action != ActionOff || decision.Reason != ReasonDisabled || calls.Load() != 0 {
+ t.Fatalf("decision = %+v, calls = %d", decision, calls.Load())
+ }
+ if _, err := New(Config{
+ Enabled: false, BaseURL: "://invalid", ServiceToken: "weak", Timeout: time.Hour,
+ }); err != nil {
+ t.Fatalf("disabled config must ignore Cloud-only settings: %v", err)
+ }
+}
+
+func TestEnabledConfigValidation(t *testing.T) {
+ valid := Config{
+ Enabled: true,
+ BaseURL: "https://cloud.internal",
+ ServiceToken: testServiceToken,
+ }
+ tests := []struct {
+ name string
+ mutate func(*Config)
+ }{
+ {"missing base URL", func(c *Config) { c.BaseURL = "" }},
+ {"unsupported base URL scheme", func(c *Config) { c.BaseURL = "ftp://cloud.internal" }},
+ {"base URL credentials", func(c *Config) { c.BaseURL = "https://user:[email protected]" }},
+ {"base URL query", func(c *Config) { c.BaseURL = "https://cloud.internal?secret=value" }},
+ {"weak service token", func(c *Config) { c.ServiceToken = "short" }},
+ {"whitespace service token", func(c *Config) { c.ServiceToken = strings.Repeat("x", 32) + "\n" }},
+ {"long timeout", func(c *Config) { c.Timeout = maxRequestTimeout + time.Millisecond }},
+ {"negative max entries", func(c *Config) { c.MaxEntries = -1 }},
+ {"negative stale grace", func(c *Config) { c.StaleGrace = -1 }},
+ }
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ cfg := valid
+ tt.mutate(&cfg)
+ if _, err := New(cfg); !errors.Is(err, ErrInvalidConfig) {
+ t.Fatalf("error = %v, want ErrInvalidConfig", err)
+ }
+ })
+ }
+ if _, err := New(valid); err != nil {
+ t.Fatalf("valid config: %v", err)
+ }
+}
+
+func TestGateFetchesMachinePolicyWithoutHumanIdentity(t *testing.T) {
+ workspaceID := uuid.New()
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.Method != http.MethodGet || r.URL.Path != "/api/v1/internal/entitlement-policies/"+workspaceID.String() {
+ t.Errorf("request = %s %s", r.Method, r.URL.Path)
+ }
+ if got := r.Header.Get("Authorization"); got != "Bearer "+testServiceToken {
+ t.Errorf("Authorization = %q", got)
+ }
+ if got := r.Header.Get("X-User-ID"); got != "" {
+ t.Errorf("X-User-ID must be absent, got %q", got)
+ }
+ writePolicy(t, w, samplePolicy(7, 3, 60, ActionEnforce))
+ }))
+ defer server.Close()
+
+ client := newTestClient(t, server.URL, nil)
+ decision := client.Gate(context.Background(), workspaceID, GateIssueWindow)
+ if decision.Gate.Action != ActionEnforce || decision.Gate.Limit == nil || *decision.Gate.Limit != testIssueLimit ||
+ decision.Reason != ReasonRefreshed || decision.PolicyRevision != 7 || decision.SubscriptionVersion != 3 {
+ t.Fatalf("decision = %+v", decision)
+ }
+}
+
+func TestGateCachesByWorkspaceAndClonesResults(t *testing.T) {
+ var calls atomic.Int64
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+ calls.Add(1)
+ writePolicy(t, w, samplePolicy(1, 0, 60, ActionEnforce))
+ }))
+ defer server.Close()
+ client := newTestClient(t, server.URL, nil)
+ workspaceID := uuid.New()
+
+ first := client.Gate(context.Background(), workspaceID, GateIssueWindow)
+ *first.Gate.Limit = 999
+ second := client.Gate(context.Background(), workspaceID, GateIssueWindow)
+ autopilot := client.Gate(context.Background(), workspaceID, GateAutopilotRuns)
+ if second.Reason != ReasonCacheFresh || second.Gate.Limit == nil || *second.Gate.Limit != testIssueLimit {
+ t.Fatalf("cached decision = %+v", second)
+ }
+ if autopilot.Gate.Action != ActionObserve || calls.Load() != 1 {
+ t.Fatalf("autopilot = %+v, calls = %d", autopilot, calls.Load())
+ }
+}
+
+func TestConcurrentWorkspaceMissesUseSingleflight(t *testing.T) {
+ var calls atomic.Int64
+ requestStarted := make(chan struct{})
+ release := make(chan struct{})
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+ if calls.Add(1) == 1 {
+ close(requestStarted)
+ }
+ <-release
+ writePolicy(t, w, samplePolicy(1, 0, 60, ActionObserve))
+ }))
+ defer server.Close()
+ client := newTestClient(t, server.URL, nil)
+ workspaceID := uuid.New()
+
+ const workers = 32
+ start := make(chan struct{})
+ results := make(chan Decision, workers)
+ var wg sync.WaitGroup
+ for range workers {
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ <-start
+ results <- client.Gate(context.Background(), workspaceID, GateIssueWindow)
+ }()
+ }
+ close(start)
+ <-requestStarted
+ close(release)
+ wg.Wait()
+ close(results)
+ for decision := range results {
+ if decision.Gate.Action != ActionObserve {
+ t.Errorf("decision = %+v", decision)
+ }
+ }
+ if calls.Load() != 1 {
+ t.Fatalf("HTTP calls = %d, want 1", calls.Load())
+ }
+}
+
+func TestCancelledLeaderDoesNotCancelSharedRefresh(t *testing.T) {
+ requestStarted := make(chan struct{})
+ release := make(chan struct{})
+ var calls atomic.Int64
+ policyBody, err := json.Marshal(samplePolicy(1, 0, 60, ActionObserve))
+ if err != nil {
+ t.Fatalf("marshal policy: %v", err)
+ }
+ client := newTestClient(t, "https://cloud.internal", func(cfg *Config) {
+ cfg.HTTPClient = &http.Client{Transport: roundTripFunc(func(req *http.Request) (*http.Response, error) {
+ if calls.Add(1) == 1 {
+ close(requestStarted)
+ }
+ <-release
+ if err := req.Context().Err(); err != nil {
+ return nil, err
+ }
+ return &http.Response{
+ StatusCode: http.StatusOK,
+ Header: make(http.Header),
+ Body: io.NopCloser(strings.NewReader(string(policyBody))),
+ Request: req,
+ }, nil
+ })}
+ })
+ workspaceID := uuid.New()
+ leaderCtx, cancelLeader := context.WithCancel(context.Background())
+ leaderResult := make(chan Decision, 1)
+ go func() {
+ leaderResult <- client.Gate(leaderCtx, workspaceID, GateIssueWindow)
+ }()
+ <-requestStarted
+
+ cancelLeader()
+ followerResult := make(chan Decision, 1)
+ go func() {
+ followerResult <- client.Gate(context.Background(), workspaceID, GateIssueWindow)
+ }()
+ close(release)
+
+ leader, follower := <-leaderResult, <-followerResult
+ if leader.Gate.Action != ActionObserve || follower.Gate.Action != ActionObserve {
+ t.Fatalf("leader = %+v, follower = %+v", leader, follower)
+ }
+ if calls.Load() != 1 {
+ t.Fatalf("HTTP calls = %d, want 1", calls.Load())
+ }
+}
+
+func TestWorkspaceIsolationAndBoundedLRUEviction(t *testing.T) {
+ workspaceA, workspaceB := uuid.New(), uuid.New()
+ limits := map[string]int{workspaceA.String(): 11, workspaceB.String(): 22}
+ var calls atomic.Int64
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ calls.Add(1)
+ workspaceID := strings.TrimPrefix(r.URL.Path, "/api/v1/internal/entitlement-policies/")
+ policy := samplePolicy(1, 0, 60, ActionEnforce)
+ limit := limits[workspaceID]
+ policy.Gates[string(GateIssueWindow)] = wireGate{Action: string(ActionEnforce), Limit: &limit}
+ writePolicy(t, w, policy)
+ }))
+ defer server.Close()
+ client := newTestClient(t, server.URL, func(cfg *Config) { cfg.MaxEntries = 1 })
+ for _, tc := range []struct {
+ workspaceID uuid.UUID
+ wantLimit int
+ }{{workspaceA, 11}, {workspaceB, 22}, {workspaceA, 11}} {
+ decision := client.Gate(context.Background(), tc.workspaceID, GateIssueWindow)
+ if decision.Gate.Limit == nil || *decision.Gate.Limit != tc.wantLimit {
+ t.Fatalf("workspace %s decision = %+v", tc.workspaceID, decision)
+ }
+ }
+ if calls.Load() != 3 || client.cache.len() != 1 {
+ t.Fatalf("calls = %d, cache entries = %d", calls.Load(), client.cache.len())
+ }
+}
+
+func TestColdFailuresFailOpen(t *testing.T) {
+ tests := []struct {
+ name string
+ handler http.HandlerFunc
+ wantReason Reason
+ }{
+ {"unauthorized", statusHandler(http.StatusUnauthorized), ReasonUnavailable},
+ {"not found", statusHandler(http.StatusNotFound), ReasonUnavailable},
+ {"server error", statusHandler(http.StatusServiceUnavailable), ReasonUnavailable},
+ {"malformed JSON", bodyHandler(http.StatusOK, `{`), ReasonInvalidPolicy},
+ {"oversized response", bodyHandler(http.StatusOK, strings.Repeat("x", maxResponseBodySize+1)), ReasonInvalidPolicy},
+ {"unknown schema", policyHandler(func(p *wirePolicy) { p.SchemaVersion = 2 }), ReasonInvalidPolicy},
+ {"unknown action", policyHandler(func(p *wirePolicy) {
+ gate := p.Gates[string(GateIssueWindow)]
+ gate.Action = "future"
+ p.Gates[string(GateIssueWindow)] = gate
+ }), ReasonInvalidPolicy},
+ {"missing gate", policyHandler(func(p *wirePolicy) { delete(p.Gates, string(GateAutopilotRuns)) }), ReasonInvalidPolicy},
+ {"excessive TTL", policyHandler(func(p *wirePolicy) { p.ValidForSeconds = 301 }), ReasonInvalidPolicy},
+ {"missing autopilot period", policyHandler(func(p *wirePolicy) {
+ limit := testAutopilotLimit
+ p.Gates[string(GateAutopilotRuns)] = wireGate{Action: string(ActionEnforce), Limit: &limit}
+ }), ReasonInvalidPolicy},
+ {"autopilot reset is not after period start", policyHandler(func(p *wirePolicy) {
+ gate := p.Gates[string(GateAutopilotRuns)]
+ resetAt := *gate.PeriodStart
+ gate.ResetAt = &resetAt
+ p.Gates[string(GateAutopilotRuns)] = gate
+ }), ReasonInvalidPolicy},
+ }
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ server := httptest.NewServer(tt.handler)
+ defer server.Close()
+ client := newTestClient(t, server.URL, nil)
+ decision := client.Gate(context.Background(), uuid.New(), GateIssueWindow)
+ if decision.Gate.Action != ActionOff || decision.Reason != tt.wantReason {
+ t.Fatalf("decision = %+v", decision)
+ }
+ })
+ }
+}
+
+func TestAutopilotResetMayFollowPeriodEnd(t *testing.T) {
+ policy := samplePolicy(1, 0, 60, ActionObserve)
+ gate := policy.Gates[string(GateAutopilotRuns)]
+ resetAt := gate.PeriodEnd.Add(time.Hour)
+ gate.ResetAt = &resetAt
+ policy.Gates[string(GateAutopilotRuns)] = gate
+
+ if _, err := normalizePolicy(policy); err != nil {
+ t.Fatalf("normalizePolicy: %v", err)
+ }
+}
+
+func TestTimeoutFailsOpenWithinIndependentBound(t *testing.T) {
+ requestCancelled := make(chan struct{})
+ server := httptest.NewServer(http.HandlerFunc(func(_ http.ResponseWriter, r *http.Request) {
+ <-r.Context().Done()
+ close(requestCancelled)
+ }))
+ defer server.Close()
+ client := newTestClient(t, server.URL, func(cfg *Config) { cfg.Timeout = 20 * time.Millisecond })
+
+ started := time.Now()
+ decision := client.Gate(context.Background(), uuid.New(), GateIssueWindow)
+ if decision.Gate.Action != ActionOff || decision.Reason != ReasonUnavailable {
+ t.Fatalf("decision = %+v", decision)
+ }
+ if elapsed := time.Since(started); elapsed > time.Second {
+ t.Fatalf("request took %s", elapsed)
+ }
+ <-requestCancelled
+}
+
+func TestServiceTokenIsNeverForwardedThroughRedirect(t *testing.T) {
+ var redirectedCalls atomic.Int64
+ target := httptest.NewServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {
+ redirectedCalls.Add(1)
+ }))
+ defer target.Close()
+ origin := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ http.Redirect(w, r, target.URL, http.StatusTemporaryRedirect)
+ }))
+ defer origin.Close()
+ client := newTestClient(t, origin.URL, nil)
+
+ decision := client.Gate(context.Background(), uuid.New(), GateIssueWindow)
+ if decision.Gate.Action != ActionOff || decision.Reason != ReasonUnavailable {
+ t.Fatalf("decision = %+v", decision)
+ }
+ if redirectedCalls.Load() != 0 {
+ t.Fatalf("redirect target received %d request(s)", redirectedCalls.Load())
+ }
+}
+
+func TestFastFailuresAreRateLimitedPerWorkspace(t *testing.T) {
+ clock := time.Date(2026, 8, 18, 9, 0, 0, 0, time.UTC)
+ var calls atomic.Int64
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+ calls.Add(1)
+ w.WriteHeader(http.StatusServiceUnavailable)
+ }))
+ defer server.Close()
+ client := newTestClient(t, server.URL, nil)
+ client.now = func() time.Time { return clock }
+ workspaceID := uuid.New()
+
+ for range 2 {
+ decision := client.Gate(context.Background(), workspaceID, GateIssueWindow)
+ if decision.Gate.Action != ActionOff || decision.Reason != ReasonUnavailable {
+ t.Fatalf("decision = %+v", decision)
+ }
+ }
+ if calls.Load() != 1 {
+ t.Fatalf("HTTP calls during retry suppression = %d, want 1", calls.Load())
+ }
+ clock = clock.Add(defaultFailureRetry + time.Millisecond)
+ _ = client.Gate(context.Background(), workspaceID, GateIssueWindow)
+ if calls.Load() != 2 {
+ t.Fatalf("HTTP calls after retry suppression = %d, want 2", calls.Load())
+ }
+}
+
+func TestObserverRecordsCacheRefreshDecisionAndDegradation(t *testing.T) {
+ clock := time.Date(2026, 8, 18, 9, 0, 0, 0, time.UTC)
+ observer := &recordingObserver{}
+ var fail atomic.Bool
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+ if fail.Load() {
+ w.WriteHeader(http.StatusServiceUnavailable)
+ return
+ }
+ writePolicy(t, w, samplePolicy(1, 0, 5, ActionEnforce))
+ }))
+ defer server.Close()
+ client := newTestClient(t, server.URL, func(cfg *Config) { cfg.Observer = observer })
+ client.now = func() time.Time { return clock }
+ workspaceID := uuid.New()
+
+ _ = client.Gate(context.Background(), workspaceID, GateIssueWindow)
+ _ = client.Gate(context.Background(), workspaceID, GateIssueWindow)
+ fail.Store(true)
+ clock = clock.Add(6 * time.Second)
+ _ = client.Gate(context.Background(), workspaceID, GateIssueWindow)
+
+ cache, refresh, decisions, _ := observer.snapshot()
+ if strings.Join(cache, ",") != "miss,hit,expired" {
+ t.Fatalf("cache observations = %v", cache)
+ }
+ if strings.Join(refresh, ",") != "ok,5xx" {
+ t.Fatalf("refresh observations = %v", refresh)
+ }
+ if strings.Join(decisions, ",") != "issue_window/enforce/refreshed,issue_window/enforce/cache_fresh,issue_window/observe/stale" {
+ t.Fatalf("decision observations = %v", decisions)
+ }
+}
+
+func TestExpiredPolicyNeverEnforcesAndIgnoresCloudClock(t *testing.T) {
+ clock := time.Date(2026, 8, 18, 9, 0, 0, 0, time.UTC)
+ var fail atomic.Bool
+ var calls atomic.Int64
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+ calls.Add(1)
+ if fail.Load() {
+ w.WriteHeader(http.StatusServiceUnavailable)
+ return
+ }
+ policy := samplePolicy(1, 0, 5, ActionEnforce)
+ policy.ValidUntil = clock.Add(24 * time.Hour) // diagnostic only; intentionally skewed
+ writePolicy(t, w, policy)
+ }))
+ defer server.Close()
+ client := newTestClient(t, server.URL, func(cfg *Config) { cfg.StaleGrace = 10 * time.Second })
+ client.now = func() time.Time { return clock }
+ workspaceID := uuid.New()
+
+ fresh := client.Gate(context.Background(), workspaceID, GateIssueWindow)
+ if fresh.Gate.Action != ActionEnforce {
+ t.Fatalf("fresh = %+v", fresh)
+ }
+ fail.Store(true)
+ clock = clock.Add(6 * time.Second)
+ stale := client.Gate(context.Background(), workspaceID, GateIssueWindow)
+ if stale.Gate.Action != ActionObserve || stale.Gate.Limit == nil || *stale.Gate.Limit != testIssueLimit || stale.Reason != ReasonStale {
+ t.Fatalf("stale = %+v", stale)
+ }
+ clock = clock.Add(10 * time.Second)
+ expired := client.Gate(context.Background(), workspaceID, GateIssueWindow)
+ if expired.Gate.Action != ActionOff || expired.Reason != ReasonUnavailable {
+ t.Fatalf("expired = %+v", expired)
+ }
+ if calls.Load() != 3 {
+ t.Fatalf("calls = %d, want 3", calls.Load())
+ }
+}
+
+func TestPolicySwitchReplacesExpiredSnapshot(t *testing.T) {
+ clock := time.Date(2026, 8, 18, 9, 0, 0, 0, time.UTC)
+ var policyRevision atomic.Int64
+ policyRevision.Store(1)
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+ action := ActionEnforce
+ if policyRevision.Load() == 2 {
+ action = ActionOff
+ }
+ writePolicy(t, w, samplePolicy(policyRevision.Load(), 0, 5, action))
+ }))
+ defer server.Close()
+ client := newTestClient(t, server.URL, nil)
+ client.now = func() time.Time { return clock }
+ workspaceID := uuid.New()
+
+ if got := client.Gate(context.Background(), workspaceID, GateIssueWindow); got.Gate.Action != ActionEnforce {
+ t.Fatalf("initial = %+v", got)
+ }
+ policyRevision.Store(2)
+ clock = clock.Add(6 * time.Second)
+ got := client.Gate(context.Background(), workspaceID, GateIssueWindow)
+ if got.Gate.Action != ActionOff || got.PolicyRevision != 2 || got.Reason != ReasonRefreshed {
+ t.Fatalf("switched = %+v", got)
+ }
+}
+
+func TestSubscriptionVersionSwitchReplacesExpiredSnapshot(t *testing.T) {
+ clock := time.Date(2026, 8, 18, 9, 0, 0, 0, time.UTC)
+ var subscriptionVersion atomic.Int64
+ subscriptionVersion.Store(1)
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+ action := ActionEnforce
+ if subscriptionVersion.Load() == 2 {
+ action = ActionOff
+ }
+ writePolicy(t, w, samplePolicy(1, subscriptionVersion.Load(), 5, action))
+ }))
+ defer server.Close()
+ client := newTestClient(t, server.URL, nil)
+ client.now = func() time.Time { return clock }
+ workspaceID := uuid.New()
+
+ if got := client.Gate(context.Background(), workspaceID, GateIssueWindow); got.Gate.Action != ActionEnforce {
+ t.Fatalf("initial = %+v", got)
+ }
+ subscriptionVersion.Store(2)
+ clock = clock.Add(6 * time.Second)
+ got := client.Gate(context.Background(), workspaceID, GateIssueWindow)
+ if got.Gate.Action != ActionOff || got.PolicyRevision != 1 || got.SubscriptionVersion != 2 || got.Reason != ReasonRefreshed {
+ t.Fatalf("switched = %+v", got)
+ }
+}
+
+func TestRevisionRegressionCannotOverwriteWorkspaceCache(t *testing.T) {
+ clock := time.Date(2026, 8, 18, 9, 0, 0, 0, time.UTC)
+ observer := &recordingObserver{}
+ var mu sync.Mutex
+ policy := samplePolicy(2, 4, 5, ActionEnforce)
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+ mu.Lock()
+ defer mu.Unlock()
+ writePolicy(t, w, policy)
+ }))
+ defer server.Close()
+ client := newTestClient(t, server.URL, func(cfg *Config) { cfg.Observer = observer })
+ client.now = func() time.Time { return clock }
+ workspaceID := uuid.New()
+
+ initial := client.Gate(context.Background(), workspaceID, GateIssueWindow)
+ if initial.Gate.Action != ActionEnforce {
+ t.Fatalf("initial = %+v", initial)
+ }
+ mu.Lock()
+ policy = samplePolicy(1, 5, 5, ActionOff)
+ mu.Unlock()
+ clock = clock.Add(6 * time.Second)
+ regressed := client.Gate(context.Background(), workspaceID, GateIssueWindow)
+ if regressed.Gate.Action != ActionObserve || regressed.PolicyRevision != 2 || regressed.SubscriptionVersion != 4 {
+ t.Fatalf("regressed = %+v", regressed)
+ }
+ if got := observer.regressions(); len(got) != 1 || got[0] != "policy" {
+ t.Fatalf("regressions = %v", got)
+ }
+
+ mu.Lock()
+ policy = samplePolicy(3, 3, 5, ActionOff)
+ mu.Unlock()
+ clock = clock.Add(defaultFailureRetry + time.Millisecond)
+ regressed = client.Gate(context.Background(), workspaceID, GateIssueWindow)
+ if regressed.PolicyRevision != 2 || regressed.SubscriptionVersion != 4 {
+ t.Fatalf("subscription regression replaced cache: %+v", regressed)
+ }
+ if got := observer.regressions(); len(got) != 2 || got[1] != "subscription" {
+ t.Fatalf("regressions = %v", got)
+ }
+}
+
+func TestRevisionRegressionIsAcceptedAfterStaleGrace(t *testing.T) {
+ clock := time.Date(2026, 8, 18, 9, 0, 0, 0, time.UTC)
+ var calls atomic.Int64
+ var policyRevision atomic.Int64
+ policyRevision.Store(2)
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+ calls.Add(1)
+ writePolicy(t, w, samplePolicy(policyRevision.Load(), 0, 60, ActionOff))
+ }))
+ defer server.Close()
+ client := newTestClient(t, server.URL, func(cfg *Config) { cfg.StaleGrace = 10 * time.Second })
+ client.now = func() time.Time { return clock }
+ workspaceID := uuid.New()
+
+ initial := client.Gate(context.Background(), workspaceID, GateIssueWindow)
+ if initial.PolicyRevision != 2 || initial.Reason != ReasonRefreshed {
+ t.Fatalf("initial = %+v", initial)
+ }
+ policyRevision.Store(1)
+ clock = clock.Add(71 * time.Second)
+ recovered := client.Gate(context.Background(), workspaceID, GateIssueWindow)
+ if recovered.PolicyRevision != 1 || recovered.Reason != ReasonRefreshed {
+ t.Fatalf("recovered = %+v", recovered)
+ }
+
+ clock = clock.Add(defaultFailureRetry + time.Millisecond)
+ cached := client.Gate(context.Background(), workspaceID, GateIssueWindow)
+ if cached.PolicyRevision != 1 || cached.Reason != ReasonCacheFresh || calls.Load() != 2 {
+ t.Fatalf("cached = %+v, HTTP calls = %d", cached, calls.Load())
+ }
+}
+
+func TestEmergencyDisableIsImmediateAndCannotPromote(t *testing.T) {
+ var calls atomic.Int64
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+ calls.Add(1)
+ writePolicy(t, w, samplePolicy(1, 0, 60, ActionEnforce))
+ }))
+ defer server.Close()
+ client := newTestClient(t, server.URL, nil)
+ workspaceID := uuid.New()
+ if got := client.Gate(context.Background(), workspaceID, GateIssueWindow); got.Gate.Action != ActionEnforce {
+ t.Fatalf("initial = %+v", got)
+ }
+ client.SetEmergencyDisabled(true)
+ if got := client.Gate(context.Background(), workspaceID, GateIssueWindow); got.Gate.Action != ActionOff || got.Reason != ReasonEmergencyDisabled {
+ t.Fatalf("emergency = %+v", got)
+ }
+ if calls.Load() != 1 {
+ t.Fatalf("emergency disable made HTTP call; calls = %d", calls.Load())
+ }
+ client.SetEmergencyDisabled(false)
+ if got := client.Gate(context.Background(), workspaceID, GateIssueWindow); got.Gate.Action != ActionEnforce {
+ t.Fatalf("restored = %+v", got)
+ }
+}
+
+func TestInvalidWorkspaceAndUnknownGateDoNotFetch(t *testing.T) {
+ var calls atomic.Int64
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+ calls.Add(1)
+ w.WriteHeader(http.StatusInternalServerError)
+ }))
+ defer server.Close()
+ client := newTestClient(t, server.URL, nil)
+ tests := []struct {
+ workspaceID uuid.UUID
+ gate GateName
+ reason Reason
+ }{{uuid.Nil, GateIssueWindow, ReasonInvalidWorkspace}, {uuid.New(), GateName("future_gate"), ReasonUnknownGate}}
+ for _, tt := range tests {
+ decision := client.Gate(context.Background(), tt.workspaceID, tt.gate)
+ if decision.Gate.Action != ActionOff || decision.Reason != tt.reason {
+ t.Fatalf("decision = %+v", decision)
+ }
+ }
+ if calls.Load() != 0 {
+ t.Fatalf("HTTP calls = %d", calls.Load())
+ }
+}
+
+func newTestClient(t *testing.T, baseURL string, mutate func(*Config)) *Client {
+ t.Helper()
+ cfg := Config{
+ Enabled: true,
+ BaseURL: baseURL,
+ ServiceToken: testServiceToken,
+ Timeout: time.Second,
+ MaxEntries: 8,
+ StaleGrace: time.Minute,
+ Logger: slog.New(slog.NewTextHandler(io.Discard, nil)),
+ }
+ if mutate != nil {
+ mutate(&cfg)
+ }
+ client, err := New(cfg)
+ if err != nil {
+ t.Fatalf("New: %v", err)
+ }
+ return client
+}
+
+func samplePolicy(policyRevision, subscriptionVersion, validForSeconds int64, issueAction Action) wirePolicy {
+ issueLimit := testIssueLimit
+ autopilotLimit := testAutopilotLimit
+ periodStart := time.Date(2026, 8, 1, 0, 0, 0, 0, time.UTC)
+ periodEnd := periodStart.AddDate(0, 1, 0)
+ issueGate := wireGate{Action: string(issueAction)}
+ if issueAction != ActionOff {
+ issueGate.Limit = &issueLimit
+ }
+ return wirePolicy{
+ SchemaVersion: SchemaVersion,
+ PolicyRevision: policyRevision,
+ SubscriptionVersion: subscriptionVersion,
+ ValidUntil: time.Date(2030, 1, 1, 0, 0, 0, 0, time.UTC),
+ ValidForSeconds: validForSeconds,
+ Gates: map[string]wireGate{
+ string(GateIssueWindow): issueGate,
+ string(GateAutopilotRuns): {
+ Action: string(ActionObserve), Limit: &autopilotLimit,
+ PeriodStart: &periodStart, PeriodEnd: &periodEnd, ResetAt: &periodEnd,
+ },
+ },
+ }
+}
+
+func writePolicy(t *testing.T, w http.ResponseWriter, policy wirePolicy) {
+ t.Helper()
+ w.Header().Set("Content-Type", "application/json")
+ if err := json.NewEncoder(w).Encode(policy); err != nil {
+ t.Errorf("encode policy: %v", err)
+ }
+}
+
+func statusHandler(status int) http.HandlerFunc {
+ return func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(status) }
+}
+
+func bodyHandler(status int, body string) http.HandlerFunc {
+ return func(w http.ResponseWriter, _ *http.Request) {
+ w.WriteHeader(status)
+ _, _ = io.WriteString(w, body)
+ }
+}
+
+func policyHandler(mutate func(*wirePolicy)) http.HandlerFunc {
+ return func(w http.ResponseWriter, _ *http.Request) {
+ policy := samplePolicy(1, 0, 60, ActionObserve)
+ mutate(&policy)
+ data, _ := json.Marshal(policy)
+ _, _ = w.Write(data)
+ }
+}
+
+type roundTripFunc func(*http.Request) (*http.Response, error)
+
+func (f roundTripFunc) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) }
+
+type recordingObserver struct {
+ mu sync.Mutex
+ cache []string
+ refresh []string
+ decisions []string
+ versionRegressions []string
+}
+
+func (o *recordingObserver) RecordEntitlementCache(outcome string) {
+ o.mu.Lock()
+ defer o.mu.Unlock()
+ o.cache = append(o.cache, outcome)
+}
+
+func (o *recordingObserver) RecordEntitlementRefresh(outcome string, _ float64) {
+ o.mu.Lock()
+ defer o.mu.Unlock()
+ o.refresh = append(o.refresh, outcome)
+}
+
+func (o *recordingObserver) RecordEntitlementDecision(gate, action, reason string) {
+ o.mu.Lock()
+ defer o.mu.Unlock()
+ o.decisions = append(o.decisions, gate+"/"+action+"/"+reason)
+}
+
+func (o *recordingObserver) RecordEntitlementVersionRegression(source string) {
+ o.mu.Lock()
+ defer o.mu.Unlock()
+ o.versionRegressions = append(o.versionRegressions, source)
+}
+
+func (o *recordingObserver) regressions() []string {
+ _, _, _, regressions := o.snapshot()
+ return regressions
+}
+
+func (o *recordingObserver) snapshot() (cache, refresh, decisions, regressions []string) {
+ o.mu.Lock()
+ defer o.mu.Unlock()
+ return append([]string(nil), o.cache...), append([]string(nil), o.refresh...),
+ append([]string(nil), o.decisions...), append([]string(nil), o.versionRegressions...)
+}
diff --git a/server/internal/entitlement/doc.go b/server/internal/entitlement/doc.go
new file mode 100644
index 0000000000..33a4d1bc07
--- /dev/null
+++ b/server/internal/entitlement/doc.go
@@ -0,0 +1,9 @@
+// Package entitlement fetches and caches workspace-scoped enforcement policy
+// from Multica Cloud. It is intentionally a mechanical policy consumer: plan
+// names, subscription interpretation, rollout cohorts, dates, and commercial
+// limits are resolved by Cloud and never appear here.
+//
+// A zero Config is disabled. Disabled, unavailable, invalid, or expired policy
+// always returns ActionOff, so merely importing or constructing this package
+// cannot change product behavior. No production caller is wired in PR-2.
+package entitlement
diff --git a/server/internal/entitlement/entitlementtest/stub.go b/server/internal/entitlement/entitlementtest/stub.go
new file mode 100644
index 0000000000..ea9021f02a
--- /dev/null
+++ b/server/internal/entitlement/entitlementtest/stub.go
@@ -0,0 +1,78 @@
+// Package entitlementtest provides a deterministic Provider for tests of
+// future entitlement consumers. It never contacts Multica Cloud.
+package entitlementtest
+
+import (
+ "context"
+ "sync"
+
+ "github.com/google/uuid"
+ "github.com/multica-ai/multica/server/internal/entitlement"
+)
+
+type Call struct {
+ WorkspaceID uuid.UUID
+ Gate entitlement.GateName
+}
+
+type Stub struct {
+ mu sync.RWMutex
+ decisions map[uuid.UUID]map[entitlement.GateName]entitlement.Decision
+ calls []Call
+}
+
+var _ entitlement.Provider = (*Stub)(nil)
+
+func New() *Stub {
+ return &Stub{decisions: make(map[uuid.UUID]map[entitlement.GateName]entitlement.Decision)}
+}
+
+func (s *Stub) Set(workspaceID uuid.UUID, name entitlement.GateName, decision entitlement.Decision) {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ if s.decisions[workspaceID] == nil {
+ s.decisions[workspaceID] = make(map[entitlement.GateName]entitlement.Decision)
+ }
+ decision.Reason = entitlement.ReasonStub
+ s.decisions[workspaceID][name] = cloneDecision(decision)
+}
+
+func (s *Stub) Gate(_ context.Context, workspaceID uuid.UUID, name entitlement.GateName) entitlement.Decision {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ s.calls = append(s.calls, Call{WorkspaceID: workspaceID, Gate: name})
+ if decision, ok := s.decisions[workspaceID][name]; ok {
+ return cloneDecision(decision)
+ }
+ return entitlement.Decision{
+ Gate: entitlement.Gate{Action: entitlement.ActionOff},
+ Reason: entitlement.ReasonStub,
+ }
+}
+
+func (s *Stub) Calls() []Call {
+ s.mu.RLock()
+ defer s.mu.RUnlock()
+ return append([]Call(nil), s.calls...)
+}
+
+func cloneDecision(in entitlement.Decision) entitlement.Decision {
+ out := in
+ if in.Gate.Limit != nil {
+ value := *in.Gate.Limit
+ out.Gate.Limit = &value
+ }
+ if in.Gate.PeriodStart != nil {
+ value := *in.Gate.PeriodStart
+ out.Gate.PeriodStart = &value
+ }
+ if in.Gate.PeriodEnd != nil {
+ value := *in.Gate.PeriodEnd
+ out.Gate.PeriodEnd = &value
+ }
+ if in.Gate.ResetAt != nil {
+ value := *in.Gate.ResetAt
+ out.Gate.ResetAt = &value
+ }
+ return out
+}
diff --git a/server/internal/entitlement/entitlementtest/stub_test.go b/server/internal/entitlement/entitlementtest/stub_test.go
new file mode 100644
index 0000000000..3f45daa9e0
--- /dev/null
+++ b/server/internal/entitlement/entitlementtest/stub_test.go
@@ -0,0 +1,35 @@
+package entitlementtest
+
+import (
+ "context"
+ "testing"
+
+ "github.com/google/uuid"
+ "github.com/multica-ai/multica/server/internal/entitlement"
+)
+
+func TestStubIsWorkspaceScopedAndDefaultsOff(t *testing.T) {
+ stub := New()
+ workspaceA, workspaceB := uuid.New(), uuid.New()
+ limit := 7
+ stub.Set(workspaceA, entitlement.GateIssueWindow, entitlement.Decision{
+ Gate: entitlement.Gate{Action: entitlement.ActionEnforce, Limit: &limit},
+ })
+
+ first := stub.Gate(context.Background(), workspaceA, entitlement.GateIssueWindow)
+ if first.Gate.Action != entitlement.ActionEnforce || first.Gate.Limit == nil || *first.Gate.Limit != 7 || first.Reason != entitlement.ReasonStub {
+ t.Fatalf("configured = %+v", first)
+ }
+ *first.Gate.Limit = 99
+ second := stub.Gate(context.Background(), workspaceA, entitlement.GateIssueWindow)
+ if second.Gate.Limit == nil || *second.Gate.Limit != 7 {
+ t.Fatalf("stub leaked mutable decision: %+v", second)
+ }
+ missing := stub.Gate(context.Background(), workspaceB, entitlement.GateIssueWindow)
+ if missing.Gate.Action != entitlement.ActionOff || missing.Reason != entitlement.ReasonStub {
+ t.Fatalf("missing = %+v", missing)
+ }
+ if calls := stub.Calls(); len(calls) != 3 || calls[0].WorkspaceID != workspaceA || calls[2].WorkspaceID != workspaceB {
+ t.Fatalf("calls = %+v", calls)
+ }
+}
diff --git a/server/internal/entitlement/types.go b/server/internal/entitlement/types.go
new file mode 100644
index 0000000000..e7c6070013
--- /dev/null
+++ b/server/internal/entitlement/types.go
@@ -0,0 +1,117 @@
+package entitlement
+
+import (
+ "context"
+ "time"
+
+ "github.com/google/uuid"
+)
+
+const SchemaVersion = 1
+
+type GateName string
+
+const (
+ GateIssueWindow GateName = "issue_window"
+ GateAutopilotRuns GateName = "autopilot_runs"
+)
+
+func (n GateName) valid() bool {
+ switch n {
+ case GateIssueWindow, GateAutopilotRuns:
+ return true
+ default:
+ return false
+ }
+}
+
+type Action string
+
+const (
+ ActionOff Action = "off"
+ ActionObserve Action = "observe"
+ ActionEnforce Action = "enforce"
+)
+
+type Reason string
+
+const (
+ ReasonDisabled Reason = "disabled"
+ ReasonEmergencyDisabled Reason = "emergency_disabled"
+ ReasonInvalidWorkspace Reason = "invalid_workspace"
+ ReasonUnknownGate Reason = "unknown_gate"
+ ReasonCacheFresh Reason = "cache_fresh"
+ ReasonRefreshed Reason = "refreshed"
+ ReasonStale Reason = "stale"
+ ReasonUnavailable Reason = "unavailable"
+ ReasonInvalidPolicy Reason = "invalid_policy"
+ ReasonVersionRegression Reason = "version_regression"
+ ReasonStub Reason = "stub"
+)
+
+// Gate is the effective instruction for one generic enforcement point. Limits
+// and period boundaries come from Cloud; this package does not derive them.
+type Gate struct {
+ Action Action
+ Limit *int
+ PeriodStart *time.Time
+ PeriodEnd *time.Time
+ ResetAt *time.Time
+}
+
+// Decision carries enough source information for consumers to audit why a gate
+// was enforced, observed, or disabled without exposing Cloud's private inputs.
+type Decision struct {
+ Gate Gate
+ Reason Reason
+ PolicyRevision int64
+ SubscriptionVersion int64
+ CloudValidUntil time.Time
+}
+
+// Provider is the only interface future issue-window and autopilot consumers
+// need. It deliberately has no error return: every failure is represented by a
+// fail-open Decision with ActionOff (or ActionObserve for a bounded stale
+// snapshot that can no longer enforce).
+type Provider interface {
+ Gate(ctx context.Context, workspaceID uuid.UUID, name GateName) Decision
+}
+
+// Observer is a low-cardinality instrumentation seam. Implementations must not
+// attach workspace IDs or policy values as metric labels.
+type Observer interface {
+ RecordEntitlementCache(outcome string)
+ RecordEntitlementRefresh(outcome string, durationSeconds float64)
+ RecordEntitlementDecision(gate, action, reason string)
+ RecordEntitlementVersionRegression(source string)
+}
+
+func offDecision(reason Reason) Decision {
+ return Decision{Gate: Gate{Action: ActionOff}, Reason: reason}
+}
+
+func cloneDecision(in Decision) Decision {
+ in.Gate = cloneGate(in.Gate)
+ return in
+}
+
+func cloneGate(in Gate) Gate {
+ out := in
+ if in.Limit != nil {
+ value := *in.Limit
+ out.Limit = &value
+ }
+ if in.PeriodStart != nil {
+ value := *in.PeriodStart
+ out.PeriodStart = &value
+ }
+ if in.PeriodEnd != nil {
+ value := *in.PeriodEnd
+ out.PeriodEnd = &value
+ }
+ if in.ResetAt != nil {
+ value := *in.ResetAt
+ out.ResetAt = &value
+ }
+ return out
+}