Skip to content

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

Go

refactor(cloud): use URL-only internal connection (#7566)

LinYushen55fe79248345
diff --git a/.env.example b/.env.example
index 4aa003a3ca..29325afb62 100644
--- a/.env.example
+++ b/.env.example
@@ -205,38 +205,11 @@ MULTICA_FEATURE_FLAGS_FILE=
# Configuring a workspace-specific URL instead would strand every other
# workspace on someone else's page.
-# Managed entitlement-policy consumer. Keep disabled for local development and
-# self-hosting: when false, the backend does not call Cloud or access quota
-# accounting tables. Managed deployments enable it only after multica-cloud's
-# private entitlement endpoint and service token are configured. The token must
-# be an independent random value of at least 32 bytes and match Cloud's
-# billing.subscriptions.policy.service_token_env secret.
-MULTICA_ENTITLEMENT_POLICY_ENABLED=false
-MULTICA_ENTITLEMENT_POLICY_URL=
-MULTICA_ENTITLEMENT_SERVICE_TOKEN=
-MULTICA_ENTITLEMENT_POLICY_TIMEOUT=3s
-MULTICA_ENTITLEMENT_STALE_GRACE=15m
-# Local down switch applied on the next service rollout/restart. true forces
-# all gates off without contacting Cloud; it cannot enable a policy.
-MULTICA_ENTITLEMENT_EMERGENCY_DISABLED=false
-
# Managed multica-cloud connection. Leave the URL empty for self-hosting. When
-# connected, Fleet, Billing, and strict pre-purchased seat capacity use this
-# same service; capacity cannot be disabled independently. Entitlement policy
-# keeps its dedicated configuration above.
+# connected, Fleet, Billing, entitlement policy, and strict pre-purchased seat
+# capacity all use this service. Authentication and network isolation for these
+# internal routes are owned by the deployment platform.
MULTICA_CLOUD_URL=
-MULTICA_CLOUD_TIMEOUT=35s
-# The machine token must match Cloud's
-# billing.subscriptions.service_token_env secret.
-MULTICA_SUBSCRIPTION_CAPACITY_SERVICE_TOKEN=
-MULTICA_SUBSCRIPTION_CAPACITY_TIMEOUT=3s
-# Retired Cloud/Fleet/capacity variables are intentionally unsupported. The
-# server refuses to start when any retired variable has a non-empty value so a
-# rollout cannot silently lose PAT/runtime connectivity or seat enforcement.
-# Replace MULTICA_FLEET_URL / MULTICA_CLOUD_FLEET_URL and the retired capacity
-# URL/switch variables with the settings above before deploying this version.
-# Delete/unset the old switches completely: a literal value such as
-# MULTICA_SUBSCRIPTION_CAPACITY_ENABLED=false is still non-empty and blocks boot.
# Self-host image channel
# Default stable release channel. Pin to an exact release like v0.2.4 if you
diff --git a/deploy/helm/multica/templates/configmap.yaml b/deploy/helm/multica/templates/configmap.yaml
index a01d512e52..31d3c226c5 100644
--- a/deploy/helm/multica/templates/configmap.yaml
+++ b/deploy/helm/multica/templates/configmap.yaml
@@ -21,14 +21,7 @@ data:
ALLOWED_EMAIL_DOMAINS: {{ .Values.backend.config.allowedEmailDomains | quote }}
DISABLE_WORKSPACE_CREATION: {{ .Values.backend.config.disableWorkspaceCreation | quote }}
MULTICA_VCS_INTEGRATION_ENABLED: {{ .Values.backend.config.vcsIntegrationEnabled | quote }}
- MULTICA_ENTITLEMENT_POLICY_ENABLED: {{ .Values.backend.config.entitlementPolicy.enabled | quote }}
- MULTICA_ENTITLEMENT_POLICY_URL: {{ .Values.backend.config.entitlementPolicy.url | quote }}
- MULTICA_ENTITLEMENT_POLICY_TIMEOUT: {{ .Values.backend.config.entitlementPolicy.timeout | quote }}
- MULTICA_ENTITLEMENT_STALE_GRACE: {{ .Values.backend.config.entitlementPolicy.staleGrace | quote }}
- MULTICA_ENTITLEMENT_EMERGENCY_DISABLED: {{ .Values.backend.config.entitlementPolicy.emergencyDisabled | quote }}
MULTICA_CLOUD_URL: {{ .Values.backend.config.cloud.url | quote }}
- MULTICA_CLOUD_TIMEOUT: {{ .Values.backend.config.cloud.timeout | quote }}
- MULTICA_SUBSCRIPTION_CAPACITY_TIMEOUT: {{ .Values.backend.config.cloud.capacityTimeout | quote }}
GOOGLE_CLIENT_ID: {{ .Values.backend.config.googleClientId | quote }}
GOOGLE_REDIRECT_URI: {{ .Values.backend.config.googleRedirectUri | quote }}
S3_BUCKET: {{ .Values.backend.config.s3Bucket | quote }}
diff --git a/deploy/helm/multica/values.yaml b/deploy/helm/multica/values.yaml
index 15cede9e23..abf1c0eaa3 100644
--- a/deploy/helm/multica/values.yaml
+++ b/deploy/helm/multica/values.yaml
@@ -28,8 +28,6 @@ images:
# --from-literal=RESEND_API_KEY="" \
# --from-literal=GOOGLE_CLIENT_SECRET="" \
# --from-literal=CLOUDFRONT_PRIVATE_KEY="" \
-# --from-literal=MULTICA_ENTITLEMENT_SERVICE_TOKEN="" \
-# --from-literal=MULTICA_SUBSCRIPTION_CAPACITY_SERVICE_TOKEN="" \
# --from-literal=MULTICA_DEV_VERIFICATION_CODE=""
#
# External postgres (postgres.external.enabled=true):
@@ -40,8 +38,6 @@ images:
# --from-literal=RESEND_API_KEY="" \
# --from-literal=GOOGLE_CLIENT_SECRET="" \
# --from-literal=CLOUDFRONT_PRIVATE_KEY="" \
-# --from-literal=MULTICA_ENTITLEMENT_SERVICE_TOKEN="" \
-# --from-literal=MULTICA_SUBSCRIPTION_CAPACITY_SERVICE_TOKEN="" \
# --from-literal=MULTICA_DEV_VERIFICATION_CODE=""
#
# The chart references this Secret by name; it does not template it, so real
@@ -140,24 +136,10 @@ backend:
# MULTICA_VCS_SECRET_KEY through existingSecret before connections work.
# Set false to hide and reject the integration for this deployment.
vcsIntegrationEnabled: true
- # Managed Cloud policy consumer. The public/self-host chart keeps this off
- # by default, which also guarantees no quota-table access. To enable it,
- # set enabled=true and url to multica-cloud's HTTPS internal base URL, then
- # put a matching 32+ byte MULTICA_ENTITLEMENT_SERVICE_TOKEN in existingSecret.
- entitlementPolicy:
- enabled: false
- url: ""
- timeout: 3s
- staleGrace: 15m
- # Local down switch applied by the next chart rollout; it only forces off.
- emergencyDisabled: false
# Managed multica-cloud connection. Empty keeps self-hosting independent.
- # When set, Fleet, Billing and strict seat capacity share this URL; put the
- # matching seat-capacity service token in existingSecret.
+ # Fleet, Billing, entitlement policy and strict seat capacity share it.
cloud:
url: ""
- timeout: 35s
- capacityTimeout: 3s
googleClientId: ""
googleRedirectUri: http://multica.dev.lan/auth/callback
s3Bucket: ""
diff --git a/docker-compose.selfhost.yml b/docker-compose.selfhost.yml
index 367566cb70..06dea83950 100644
--- a/docker-compose.selfhost.yml
+++ b/docker-compose.selfhost.yml
@@ -106,20 +106,9 @@ services:
ALLOWED_EMAILS: ${ALLOWED_EMAILS:-}
ALLOWED_EMAIL_DOMAINS: ${ALLOWED_EMAIL_DOMAINS:-}
DISABLE_WORKSPACE_CREATION: ${DISABLE_WORKSPACE_CREATION:-}
- # Managed entitlement policy is explicitly opt-in. The false/empty
- # defaults keep self-hosted installs on the legacy path with no Cloud
- # request and no quota-table access.
- MULTICA_ENTITLEMENT_POLICY_ENABLED: ${MULTICA_ENTITLEMENT_POLICY_ENABLED:-false}
- MULTICA_ENTITLEMENT_POLICY_URL: ${MULTICA_ENTITLEMENT_POLICY_URL:-}
- MULTICA_ENTITLEMENT_SERVICE_TOKEN: ${MULTICA_ENTITLEMENT_SERVICE_TOKEN:-}
- MULTICA_ENTITLEMENT_POLICY_TIMEOUT: ${MULTICA_ENTITLEMENT_POLICY_TIMEOUT:-3s}
- MULTICA_ENTITLEMENT_STALE_GRACE: ${MULTICA_ENTITLEMENT_STALE_GRACE:-15m}
- MULTICA_ENTITLEMENT_EMERGENCY_DISABLED: ${MULTICA_ENTITLEMENT_EMERGENCY_DISABLED:-false}
- # Managed Cloud stays off for self-hosting; seat capacity follows this URL.
+ # Managed Cloud stays off for self-hosting. All managed Cloud clients use
+ # this single URL when it is configured.
MULTICA_CLOUD_URL: ${MULTICA_CLOUD_URL:-}
- MULTICA_CLOUD_TIMEOUT: ${MULTICA_CLOUD_TIMEOUT:-35s}
- MULTICA_SUBSCRIPTION_CAPACITY_SERVICE_TOKEN: ${MULTICA_SUBSCRIPTION_CAPACITY_SERVICE_TOKEN:-}
- MULTICA_SUBSCRIPTION_CAPACITY_TIMEOUT: ${MULTICA_SUBSCRIPTION_CAPACITY_TIMEOUT:-3s}
GITHUB_APP_SLUG: ${GITHUB_APP_SLUG:-}
GITHUB_WEBHOOK_SECRET: ${GITHUB_WEBHOOK_SECRET:-}
# App API credentials. The pull_request webhook is what mirrors a PR
diff --git a/scripts/helm-config.test.sh b/scripts/helm-config.test.sh
index d48c314030..4df9c96640 100644
--- a/scripts/helm-config.test.sh
+++ b/scripts/helm-config.test.sh
@@ -33,16 +33,10 @@ default_config="$(
--show-only templates/configmap.yaml
)"
require_rendered_value "$default_config" 'MULTICA_VCS_INTEGRATION_ENABLED: "true"'
-require_rendered_value "$default_config" 'MULTICA_ENTITLEMENT_POLICY_ENABLED: "false"'
-require_rendered_value "$default_config" 'MULTICA_ENTITLEMENT_POLICY_URL: ""'
-reject_rendered_value "$default_config" 'MULTICA_SUBSCRIPTION_CAPACITY_ENABLED'
-reject_rendered_value "$default_config" 'MULTICA_SUBSCRIPTION_CAPACITY_URL'
require_rendered_value "$default_config" 'MULTICA_CLOUD_URL: ""'
require_rendered_value "$default_config" 'MULTICA_TASK_QUEUED_TTL: "2h"'
require_rendered_value "$default_config" 'MULTICA_DATABASE_STARTUP_TIMEOUT: "3m"'
require_rendered_value "$default_config" 'MULTICA_DATABASE_CONNECT_TIMEOUT: "5s"'
-reject_rendered_value "$default_config" 'MULTICA_ENTITLEMENT_SERVICE_TOKEN'
-reject_rendered_value "$default_config" 'MULTICA_SUBSCRIPTION_CAPACITY_SERVICE_TOKEN'
queued_ttl_config="$(
helm template multica "$CHART_DIR" \
@@ -67,33 +61,12 @@ disabled_config="$(
)"
require_rendered_value "$disabled_config" 'MULTICA_VCS_INTEGRATION_ENABLED: "false"'
-entitlement_config="$(
- helm template multica "$CHART_DIR" \
- --show-only templates/configmap.yaml \
- --set backend.config.entitlementPolicy.enabled=true \
- --set-string backend.config.entitlementPolicy.url=https://multica-cloud.internal \
- --set-string backend.config.entitlementPolicy.timeout=2s \
- --set-string backend.config.entitlementPolicy.staleGrace=10m \
- --set backend.config.entitlementPolicy.emergencyDisabled=false
-)"
-require_rendered_value "$entitlement_config" 'MULTICA_ENTITLEMENT_POLICY_ENABLED: "true"'
-require_rendered_value "$entitlement_config" 'MULTICA_ENTITLEMENT_POLICY_URL: "https://multica-cloud.internal"'
-require_rendered_value "$entitlement_config" 'MULTICA_ENTITLEMENT_POLICY_TIMEOUT: "2s"'
-require_rendered_value "$entitlement_config" 'MULTICA_ENTITLEMENT_STALE_GRACE: "10m"'
-require_rendered_value "$entitlement_config" 'MULTICA_ENTITLEMENT_EMERGENCY_DISABLED: "false"'
-reject_rendered_value "$entitlement_config" 'MULTICA_ENTITLEMENT_SERVICE_TOKEN'
-
capacity_config="$(
helm template multica "$CHART_DIR" \
--show-only templates/configmap.yaml \
- --set-string backend.config.cloud.url=https://multica-cloud.internal \
- --set-string backend.config.cloud.capacityTimeout=2s
+ --set-string backend.config.cloud.url=https://multica-cloud.internal
)"
require_rendered_value "$capacity_config" 'MULTICA_CLOUD_URL: "https://multica-cloud.internal"'
-require_rendered_value "$capacity_config" 'MULTICA_SUBSCRIPTION_CAPACITY_TIMEOUT: "2s"'
-reject_rendered_value "$capacity_config" 'MULTICA_SUBSCRIPTION_CAPACITY_ENABLED'
-reject_rendered_value "$capacity_config" 'MULTICA_SUBSCRIPTION_CAPACITY_URL'
-reject_rendered_value "$capacity_config" 'MULTICA_SUBSCRIPTION_CAPACITY_SERVICE_TOKEN'
capacity_alerts="$(
helm template multica "$CHART_DIR" \
diff --git a/server/cmd/server/main.go b/server/cmd/server/main.go
index e74c6d5e58..f3a6603dc0 100644
--- a/server/cmd/server/main.go
+++ b/server/cmd/server/main.go
@@ -269,38 +269,8 @@ func jwtSecretBootError(jwtSecret, appEnv string) error {
return auth.ValidateJWTSecret(jwtSecret)
}
-var retiredCloudEnvironmentVariables = []string{
- "MULTICA_FLEET_URL",
- "MULTICA_CLOUD_FLEET_URL",
- "MULTICA_CLOUD_FLEET_TIMEOUT",
- "MULTICA_SUBSCRIPTION_CAPACITY_ENABLED",
- "MULTICA_SUBSCRIPTION_CAPACITY_URL",
- "MULTICA_SUBSCRIPTION_CAPACITY_WORKER_ENABLED",
-}
-
-func retiredCloudEnvironmentError(lookupEnv func(string) (string, bool)) error {
- var configured []string
- for _, name := range retiredCloudEnvironmentVariables {
- if value, exists := lookupEnv(name); exists && strings.TrimSpace(value) != "" {
- configured = append(configured, name)
- }
- }
- if len(configured) == 0 {
- return nil
- }
- return fmt.Errorf(
- "retired Cloud environment variables are still configured: %s; use MULTICA_CLOUD_URL and the current capacity token/timeout settings",
- strings.Join(configured, ", "),
- )
-}
-
func main() {
logger.Init()
- if err := retiredCloudEnvironmentError(os.LookupEnv); err != nil {
- slog.Error("refusing to start with retired Cloud configuration", "error", err)
- os.Exit(1)
- }
-
// Warn about missing configuration
if err := jwtSecretBootError(os.Getenv("JWT_SECRET"), os.Getenv("APP_ENV")); err != nil {
slog.Error(
diff --git a/server/cmd/server/main_test.go b/server/cmd/server/main_test.go
index 8a8f8c13e1..a4fe4b5747 100644
--- a/server/cmd/server/main_test.go
+++ b/server/cmd/server/main_test.go
@@ -513,27 +513,3 @@ func TestJWTSecretBootError(t *testing.T) {
})
}
}
-
-func TestRetiredCloudEnvironmentError(t *testing.T) {
- tests := []struct {
- name string
- env map[string]string
- want bool
- }{
- {name: "current configuration", env: map[string]string{"MULTICA_CLOUD_URL": "https://cloud.internal"}},
- {name: "empty retired variable", env: map[string]string{"MULTICA_FLEET_URL": ""}},
- {name: "retired fleet URL", env: map[string]string{"MULTICA_FLEET_URL": "https://fleet.internal"}, want: true},
- {name: "retired capacity switch", env: map[string]string{"MULTICA_SUBSCRIPTION_CAPACITY_ENABLED": "false"}, want: true},
- }
- for _, tt := range tests {
- t.Run(tt.name, func(t *testing.T) {
- err := retiredCloudEnvironmentError(func(name string) (string, bool) {
- value, ok := tt.env[name]
- return value, ok
- })
- if (err != nil) != tt.want {
- t.Fatalf("retiredCloudEnvironmentError() = %v, want error %v", err, tt.want)
- }
- })
- }
-}
diff --git a/server/cmd/server/router.go b/server/cmd/server/router.go
index a7f7bc8ac0..a6bd362ecb 100644
--- a/server/cmd/server/router.go
+++ b/server/cmd/server/router.go
@@ -393,18 +393,16 @@ func strictPositiveDurationEnv(name string, fallback time.Duration) (time.Durati
return value, nil
}
-func seatCapacityExecutorFromEnv(cloudURL string) seatcapacity.Executor {
+func seatCapacityExecutor(cloudURL string) seatcapacity.Executor {
executor, err := seatcapacity.New(seatcapacity.Config{
- BaseURL: cloudURL,
- ServiceToken: os.Getenv("MULTICA_SUBSCRIPTION_CAPACITY_SERVICE_TOKEN"),
- Timeout: envDuration("MULTICA_SUBSCRIPTION_CAPACITY_TIMEOUT", 3*time.Second),
+ BaseURL: cloudURL,
})
if err == nil {
return executor
}
- // A Cloud-connected deployment with malformed credentials must not
+ // A Cloud-connected deployment with malformed connection settings must not
// silently restore unlimited membership. The fail-closed executor returns
- // 503 until the operator repairs the machine credential; it is deliberately
+ // 503 until the operator repairs the Cloud URL; it is deliberately
// ineligible for recovery-worker startup so queued intents keep their retry
// budget while configuration is broken.
slog.Error("subscription seat capacity executor unavailable", "error", err)
@@ -451,7 +449,7 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus
AppURL: appURLFromEnv(),
TrustedProxies: parseTrustedProxies(os.Getenv("MULTICA_TRUSTED_PROXIES")),
CloudURL: strings.TrimSpace(os.Getenv("MULTICA_CLOUD_URL")),
- CloudTimeout: envDuration("MULTICA_CLOUD_TIMEOUT", 35*time.Second),
+ CloudTimeout: 35 * time.Second,
AttachmentDownloadMode: os.Getenv("ATTACHMENT_DOWNLOAD_MODE"),
AttachmentDownloadURLTTL: envDuration("ATTACHMENT_DOWNLOAD_URL_TTL", 30*time.Minute),
AttachmentFrameAncestors: origins,
@@ -475,18 +473,13 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus
h.TaskService.Metrics = opts.BusinessMetrics
h.IssueService.Metrics = opts.BusinessMetrics
entitlementClient, entitlementErr := entitlement.New(entitlement.Config{
- Enabled: envBool("MULTICA_ENTITLEMENT_POLICY_ENABLED", false),
- BaseURL: strings.TrimSpace(os.Getenv("MULTICA_ENTITLEMENT_POLICY_URL")),
- ServiceToken: os.Getenv("MULTICA_ENTITLEMENT_SERVICE_TOKEN"),
- Timeout: envDuration("MULTICA_ENTITLEMENT_POLICY_TIMEOUT", 3*time.Second),
- StaleGrace: envNonNegativeDuration("MULTICA_ENTITLEMENT_STALE_GRACE", 15*time.Minute),
- Observer: opts.BusinessMetrics,
+ BaseURL: signupConfig.CloudURL,
+ Observer: opts.BusinessMetrics,
})
if entitlementErr != nil {
- slog.Error("entitlement policy client disabled by invalid configuration", "error", entitlementErr)
+ slog.Error("entitlement policy client disabled by malformed Multica Cloud URL", "error", entitlementErr)
opts.BusinessMetrics.RecordEntitlementConfigError()
} else if entitlementClient.Enabled() {
- entitlementClient.SetEmergencyDisabled(envBool("MULTICA_ENTITLEMENT_EMERGENCY_DISABLED", false))
h.Entitlements = entitlementClient
h.AutopilotService.Entitlements = entitlementClient
h.AutopilotService.QuotaMetrics = opts.BusinessMetrics
@@ -494,7 +487,7 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus
// Cloud Runtime and strict seat capacity are one managed deployment. Reuse
// the same base URL so Billing cannot be readable while invitation writes
// silently skip Cloud's authoritative seat policy.
- h.SeatCapacity = seatCapacityExecutorFromEnv(signupConfig.CloudURL)
+ h.SeatCapacity = seatCapacityExecutor(signupConfig.CloudURL)
capacityLocker := seatcapacity.NewWorkspaceLocker(pool)
h.SeatCapacityLocker = capacityLocker
if seatcapacity.CanRunWorker(h.SeatCapacity) {
diff --git a/server/cmd/server/router_seat_capacity_test.go b/server/cmd/server/router_seat_capacity_test.go
index 693eb98bf9..d06be7047d 100644
--- a/server/cmd/server/router_seat_capacity_test.go
+++ b/server/cmd/server/router_seat_capacity_test.go
@@ -1,28 +1,17 @@
package main
import (
- "context"
"testing"
- "time"
- "github.com/google/uuid"
"github.com/multica-ai/multica/server/internal/seatcapacity"
)
-func TestSeatCapacityAssemblyFailsClosedWithoutServiceToken(t *testing.T) {
- t.Setenv("MULTICA_SUBSCRIPTION_CAPACITY_SERVICE_TOKEN", "")
- t.Setenv("MULTICA_SUBSCRIPTION_CAPACITY_TIMEOUT", "3s")
-
- executor := seatCapacityExecutorFromEnv("https://cloud.internal")
+func TestSeatCapacityAssemblyUsesCloudURLAlone(t *testing.T) {
+ executor := seatCapacityExecutor("https://cloud.internal")
if executor == nil {
t.Fatal("Cloud-connected router assembled a nil capacity executor")
}
- if seatcapacity.CanRunWorker(executor) {
- t.Fatal("unavailable capacity executor was eligible for worker startup")
- }
- if _, err := executor.ReserveInvitation(
- context.Background(), uuid.New(), uuid.New(), time.Now().Add(time.Hour),
- ); err == nil {
- t.Fatal("Cloud-connected admission succeeded without a capacity service token")
+ if !seatcapacity.CanRunWorker(executor) {
+ t.Fatal("Cloud URL did not assemble a recovery-capable capacity executor")
}
}
diff --git a/server/internal/entitlement/README.md b/server/internal/entitlement/README.md
index ebd9e7966e..0e49cb89c1 100644
--- a/server/internal/entitlement/README.md
+++ b/server/internal/entitlement/README.md
@@ -2,40 +2,41 @@
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.
+not contain plan names, subscription-state mapping, limit values, or policy
+switches.
-Production wiring remains explicit and off by default. Set
-`MULTICA_ENTITLEMENT_POLICY_ENABLED=true`,
-`MULTICA_ENTITLEMENT_POLICY_URL`, and the independent
-`MULTICA_ENTITLEMENT_SERVICE_TOKEN` to enable the client. A disabled client
-performs no HTTP request, and the autopilot consumer does not access its quota
-tables; the issue-window consumer likewise keeps its legacy SQL and performs no
-window read. Self-hosted deployments therefore retain the legacy paths.
-Timeout, stale grace, and the emergency down switch are controlled by
-`MULTICA_ENTITLEMENT_POLICY_TIMEOUT`, `MULTICA_ENTITLEMENT_STALE_GRACE`, and
-`MULTICA_ENTITLEMENT_EMERGENCY_DISABLED`.
+Production wiring has one boundary: setting `MULTICA_CLOUD_URL` connects this
+consumer as well as the other managed Cloud clients. An empty URL performs no
+HTTP request, and the autopilot consumer does not access its quota tables; the
+issue-window consumer likewise keeps its legacy SQL and performs no window
+read. Self-hosted deployments therefore retain the legacy paths. Request
+timeout and stale grace use bounded code defaults instead of deployment
+configuration.
## 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
+- `policy_revision`: the policy protocol generation, currently fixed at `1` by
+ Cloud and not deployment configuration.
+- `subscription_version`: the workspace's monotonic subscription revision. A
+ response that moves this 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.
+ stale window ends, the cache accepts the current Cloud response so a 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.
+- `gates`: effective `off` or `enforce` instructions and parameters. Cloud does
+ not expose an `observe` rollout mode; `observe` exists only as Multica's local
+ downgrade of an expired cached `enforce` instruction.
Responses tolerate unknown JSON fields for additive compatibility. Unknown
-schema/action, malformed fields, missing gates, HTTP failures, authentication
-failures, and timeouts fail open.
+schema/action, malformed fields, missing gates, HTTP failures, and timeouts fail
+open.
## Cache and degradation
@@ -50,10 +51,10 @@ cached `enforce` is downgraded to `observe`; after the grace, the result is
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. The client itself has no background
-goroutine and introduces no startup dependency; the autopilot consumer owns its
-policy-neutral accounting and recovery lifecycle separately.
+The client itself has no background goroutine and introduces no startup
+dependency; the autopilot consumer owns its policy-neutral accounting and
+recovery lifecycle separately. Cloud remains the only place that determines
+the effective policy from subscription facts and authoritative limits.
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
index 3b09b6faf8..f7ed8fc6ab 100644
--- a/server/internal/entitlement/cache.go
+++ b/server/internal/entitlement/cache.go
@@ -9,7 +9,7 @@ import (
"github.com/google/uuid"
)
-var errVersionRegression = errors.New("entitlement policy version regression")
+var errVersionRegression = errors.New("entitlement subscription version regression")
type policySnapshot struct {
policyRevision int64
@@ -65,16 +65,13 @@ func (c *policyCache) put(workspaceID uuid.UUID, entry cacheEntry, receivedAt ti
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.
+ // The version guard prevents an out-of-order subscription response from
+ // replacing a snapshot that is still usable for bounded stale observation.
+ // Once that window ends, accepting the current Cloud response lets the
+ // service recover from a 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"}
+ return current, errVersionRegression
}
elem.Value.(*cacheItem).entry = entry
c.order.MoveToFront(elem)
@@ -114,10 +111,3 @@ func (c *policyCache) len() int {
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
index 73a66dd6b7..904e60e59a 100644
--- a/server/internal/entitlement/client.go
+++ b/server/internal/entitlement/client.go
@@ -10,7 +10,6 @@ import (
"net/http"
"net/url"
"strings"
- "sync/atomic"
"time"
"github.com/google/uuid"
@@ -19,13 +18,11 @@ import (
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 (
@@ -33,43 +30,34 @@ var (
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.
+// Config has no environment-loading side effects. A zero Config is disabled;
+// setting BaseURL connects the client to the internal 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
+ BaseURL string
+ 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
+ enabled bool
+ baseURL *url.URL
+ timeout time.Duration
+ staleGrace time.Duration
+ httpClient *http.Client
+ observer Observer
+ logger *slog.Logger
+ now func() time.Time
+ cache *policyCache
+ refreshes singleflight.Group
}
var _ Provider = (*Client)(nil)
func New(cfg Config) (*Client, error) {
- if !cfg.Enabled {
+ if strings.TrimSpace(cfg.BaseURL) == "" {
return &Client{observer: cfg.Observer, now: time.Now}, nil
}
@@ -79,37 +67,12 @@ func New(cfg Config) (*Client, error) {
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.
+ // Internal Cloud calls must not follow a redirect to another origin.
httpClient.CheckRedirect = func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }
logger := cfg.Logger
if logger == nil {
@@ -117,36 +80,24 @@ func New(cfg Config) (*Client, error) {
}
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),
+ enabled: true,
+ baseURL: baseURL,
+ timeout: defaultRequestTimeout,
+ staleGrace: defaultStaleGrace,
+ httpClient: httpClient,
+ observer: cfg.Observer,
+ logger: logger,
+ now: time.Now,
+ cache: newPolicyCache(defaultMaxEntries),
}, 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))
}
@@ -175,9 +126,6 @@ func (c *Client) Gate(ctx context.Context, workspaceID uuid.UUID, name GateName)
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
@@ -185,9 +133,6 @@ func (c *Client) Gate(ctx context.Context, workspaceID uuid.UUID, name GateName)
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.
@@ -246,17 +191,12 @@ func (c *Client) refresh(ctx context.Context, workspaceID uuid.UUID) (cacheEntry
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)
- }
+ if c.observer != nil {
+ c.observer.RecordEntitlementVersionRegression()
}
c.recordRefresh("version_regression", time.Since(started))
- c.logger.WarnContext(refreshCtx, "entitlement policy revision regressed",
- "workspace_id", workspaceID.String(), "source", source)
+ c.logger.WarnContext(refreshCtx, "entitlement subscription version regressed",
+ "workspace_id", workspaceID.String())
return nil, err
}
c.recordRefresh("ok", time.Since(started))
@@ -304,7 +244,6 @@ func (c *Client) fetch(ctx context.Context, workspaceID uuid.UUID) (fetchedPolic
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 {
@@ -364,7 +303,7 @@ func normalizeGate(name GateName, wire wireGate) (Gate, error) {
switch action {
case ActionOff:
return Gate{Action: ActionOff}, nil
- case ActionObserve, ActionEnforce:
+ case ActionEnforce:
default:
return Gate{}, ErrInvalidPolicy
}
diff --git a/server/internal/entitlement/client_test.go b/server/internal/entitlement/client_test.go
index d09e5d6f1e..85eda6fe6b 100644
--- a/server/internal/entitlement/client_test.go
+++ b/server/internal/entitlement/client_test.go
@@ -18,7 +18,6 @@ import (
)
const (
- testServiceToken = "01234567890123456789012345678901"
testIssueLimit = 137
testAutopilotLimit = 23
)
@@ -39,32 +38,17 @@ func TestDefaultConfigIsDisabledAndPerformsNoIO(t *testing.T) {
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,
- }
+func TestConnectedConfigValidation(t *testing.T) {
+ valid := Config{BaseURL: "https://cloud.internal"}
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) {
@@ -86,8 +70,8 @@ func TestGateFetchesMachinePolicyWithoutHumanIdentity(t *testing.T) {
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("Authorization"); got != "" {
+ t.Errorf("Authorization must be absent, got %q", got)
}
if got := r.Header.Get("X-User-ID"); got != "" {
t.Errorf("X-User-ID must be absent, got %q", got)
@@ -121,7 +105,7 @@ func TestGateCachesByWorkspaceAndClonesResults(t *testing.T) {
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 {
+ if autopilot.Gate.Action != ActionEnforce || calls.Load() != 1 {
t.Fatalf("autopilot = %+v, calls = %d", autopilot, calls.Load())
}
}
@@ -135,7 +119,7 @@ func TestConcurrentWorkspaceMissesUseSingleflight(t *testing.T) {
close(requestStarted)
}
<-release
- writePolicy(t, w, samplePolicy(1, 0, 60, ActionObserve))
+ writePolicy(t, w, samplePolicy(1, 0, 60, ActionEnforce))
}))
defer server.Close()
client := newTestClient(t, server.URL, nil)
@@ -159,7 +143,7 @@ func TestConcurrentWorkspaceMissesUseSingleflight(t *testing.T) {
wg.Wait()
close(results)
for decision := range results {
- if decision.Gate.Action != ActionObserve {
+ if decision.Gate.Action != ActionEnforce {
t.Errorf("decision = %+v", decision)
}
}
@@ -172,7 +156,7 @@ 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))
+ policyBody, err := json.Marshal(samplePolicy(1, 0, 60, ActionEnforce))
if err != nil {
t.Fatalf("marshal policy: %v", err)
}
@@ -209,7 +193,7 @@ func TestCancelledLeaderDoesNotCancelSharedRefresh(t *testing.T) {
close(release)
leader, follower := <-leaderResult, <-followerResult
- if leader.Gate.Action != ActionObserve || follower.Gate.Action != ActionObserve {
+ if leader.Gate.Action != ActionEnforce || follower.Gate.Action != ActionEnforce {
t.Fatalf("leader = %+v, follower = %+v", leader, follower)
}
if calls.Load() != 1 {
@@ -230,7 +214,8 @@ func TestWorkspaceIsolationAndBoundedLRUEviction(t *testing.T) {
writePolicy(t, w, policy)
}))
defer server.Close()
- client := newTestClient(t, server.URL, func(cfg *Config) { cfg.MaxEntries = 1 })
+ client := newTestClient(t, server.URL, nil)
+ client.cache = newPolicyCache(1)
for _, tc := range []struct {
workspaceID uuid.UUID
wantLimit int
@@ -262,6 +247,11 @@ func TestColdFailuresFailOpen(t *testing.T) {
gate.Action = "future"
p.Gates[string(GateIssueWindow)] = gate
}), ReasonInvalidPolicy},
+ {"cloud observe action", policyHandler(func(p *wirePolicy) {
+ gate := p.Gates[string(GateIssueWindow)]
+ gate.Action = string(ActionObserve)
+ 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) {
@@ -289,7 +279,7 @@ func TestColdFailuresFailOpen(t *testing.T) {
}
func TestAutopilotResetMayFollowPeriodEnd(t *testing.T) {
- policy := samplePolicy(1, 0, 60, ActionObserve)
+ policy := samplePolicy(1, 0, 60, ActionEnforce)
gate := policy.Gates[string(GateAutopilotRuns)]
resetAt := gate.PeriodEnd.Add(time.Hour)
gate.ResetAt = &resetAt
@@ -307,7 +297,8 @@ func TestTimeoutFailsOpenWithinIndependentBound(t *testing.T) {
close(requestCancelled)
}))
defer server.Close()
- client := newTestClient(t, server.URL, func(cfg *Config) { cfg.Timeout = 20 * time.Millisecond })
+ client := newTestClient(t, server.URL, nil)
+ client.timeout = 20 * time.Millisecond
started := time.Now()
decision := client.Gate(context.Background(), uuid.New(), GateIssueWindow)
@@ -320,7 +311,7 @@ func TestTimeoutFailsOpenWithinIndependentBound(t *testing.T) {
<-requestCancelled
}
-func TestServiceTokenIsNeverForwardedThroughRedirect(t *testing.T) {
+func TestInternalPolicyClientDoesNotFollowRedirect(t *testing.T) {
var redirectedCalls atomic.Int64
target := httptest.NewServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {
redirectedCalls.Add(1)
@@ -418,7 +409,8 @@ func TestExpiredPolicyNeverEnforcesAndIgnoresCloudClock(t *testing.T) {
writePolicy(t, w, policy)
}))
defer server.Close()
- client := newTestClient(t, server.URL, func(cfg *Config) { cfg.StaleGrace = 10 * time.Second })
+ client := newTestClient(t, server.URL, nil)
+ client.staleGrace = 10 * time.Second
client.now = func() time.Time { return clock }
workspaceID := uuid.New()
@@ -442,33 +434,6 @@ func TestExpiredPolicyNeverEnforcesAndIgnoresCloudClock(t *testing.T) {
}
}
-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
@@ -496,11 +461,11 @@ func TestSubscriptionVersionSwitchReplacesExpiredSnapshot(t *testing.T) {
}
}
-func TestRevisionRegressionCannotOverwriteWorkspaceCache(t *testing.T) {
+func TestSubscriptionVersionRegressionCannotOverwriteWorkspaceCache(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)
+ policy := samplePolicy(1, 4, 5, ActionEnforce)
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
mu.Lock()
defer mu.Unlock()
@@ -516,87 +481,51 @@ func TestRevisionRegressionCannotOverwriteWorkspaceCache(t *testing.T) {
t.Fatalf("initial = %+v", initial)
}
mu.Lock()
- policy = samplePolicy(1, 5, 5, ActionOff)
+ policy = samplePolicy(1, 3, 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 {
+ if regressed.Gate.Action != ActionObserve || regressed.PolicyRevision != 1 || 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)
+ if got := observer.regressions(); got != 1 {
+ t.Fatalf("regressions = %d", got)
}
}
-func TestRevisionRegressionIsAcceptedAfterStaleGrace(t *testing.T) {
+func TestSubscriptionVersionRegressionIsAcceptedAfterStaleGrace(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)
+ var subscriptionVersion atomic.Int64
+ subscriptionVersion.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))
+ writePolicy(t, w, samplePolicy(1, subscriptionVersion.Load(), 60, ActionOff))
}))
defer server.Close()
- client := newTestClient(t, server.URL, func(cfg *Config) { cfg.StaleGrace = 10 * time.Second })
+ client := newTestClient(t, server.URL, nil)
+ client.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 {
+ if initial.SubscriptionVersion != 2 || initial.Reason != ReasonRefreshed {
t.Fatalf("initial = %+v", initial)
}
- policyRevision.Store(1)
+ subscriptionVersion.Store(1)
clock = clock.Add(71 * time.Second)
recovered := client.Gate(context.Background(), workspaceID, GateIssueWindow)
- if recovered.PolicyRevision != 1 || recovered.Reason != ReasonRefreshed {
+ if recovered.SubscriptionVersion != 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 {
+ if cached.SubscriptionVersion != 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) {
@@ -624,13 +553,8 @@ func TestInvalidWorkspaceAndUnknownGateDoNotFetch(t *testing.T) {
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)),
+ BaseURL: baseURL,
+ Logger: slog.New(slog.NewTextHandler(io.Discard, nil)),
}
if mutate != nil {
mutate(&cfg)
@@ -660,7 +584,7 @@ func samplePolicy(policyRevision, subscriptionVersion, validForSeconds int64, is
Gates: map[string]wireGate{
string(GateIssueWindow): issueGate,
string(GateAutopilotRuns): {
- Action: string(ActionObserve), Limit: &autopilotLimit,
+ Action: string(ActionEnforce), Limit: &autopilotLimit,
PeriodStart: &periodStart, PeriodEnd: &periodEnd, ResetAt: &periodEnd,
},
},
@@ -688,7 +612,7 @@ func bodyHandler(status int, body string) http.HandlerFunc {
func policyHandler(mutate func(*wirePolicy)) http.HandlerFunc {
return func(w http.ResponseWriter, _ *http.Request) {
- policy := samplePolicy(1, 0, 60, ActionObserve)
+ policy := samplePolicy(1, 0, 60, ActionEnforce)
mutate(&policy)
data, _ := json.Marshal(policy)
_, _ = w.Write(data)
@@ -704,7 +628,7 @@ type recordingObserver struct {
cache []string
refresh []string
decisions []string
- versionRegressions []string
+ versionRegressions int
}
func (o *recordingObserver) RecordEntitlementCache(outcome string) {
@@ -725,20 +649,20 @@ func (o *recordingObserver) RecordEntitlementDecision(gate, action, reason strin
o.decisions = append(o.decisions, gate+"/"+action+"/"+reason)
}
-func (o *recordingObserver) RecordEntitlementVersionRegression(source string) {
+func (o *recordingObserver) RecordEntitlementVersionRegression() {
o.mu.Lock()
defer o.mu.Unlock()
- o.versionRegressions = append(o.versionRegressions, source)
+ o.versionRegressions++
}
-func (o *recordingObserver) regressions() []string {
+func (o *recordingObserver) regressions() int {
_, _, _, regressions := o.snapshot()
return regressions
}
-func (o *recordingObserver) snapshot() (cache, refresh, decisions, regressions []string) {
+func (o *recordingObserver) snapshot() (cache, refresh, decisions []string, regressions int) {
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...)
+ append([]string(nil), o.decisions...), o.versionRegressions
}
diff --git a/server/internal/entitlement/doc.go b/server/internal/entitlement/doc.go
index 33a4d1bc07..9a65304773 100644
--- a/server/internal/entitlement/doc.go
+++ b/server/internal/entitlement/doc.go
@@ -1,9 +1,10 @@
// 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.
+// names, subscription interpretation, 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.
+// cannot change product behavior. A configured MULTICA_CLOUD_URL connects the
+// production consumer.
package entitlement
diff --git a/server/internal/entitlement/types.go b/server/internal/entitlement/types.go
index e7c6070013..73ff6655ba 100644
--- a/server/internal/entitlement/types.go
+++ b/server/internal/entitlement/types.go
@@ -37,7 +37,6 @@ type Reason string
const (
ReasonDisabled Reason = "disabled"
- ReasonEmergencyDisabled Reason = "emergency_disabled"
ReasonInvalidWorkspace Reason = "invalid_workspace"
ReasonUnknownGate Reason = "unknown_gate"
ReasonCacheFresh Reason = "cache_fresh"
@@ -83,7 +82,7 @@ type Observer interface {
RecordEntitlementCache(outcome string)
RecordEntitlementRefresh(outcome string, durationSeconds float64)
RecordEntitlementDecision(gate, action, reason string)
- RecordEntitlementVersionRegression(source string)
+ RecordEntitlementVersionRegression()
}
func offDecision(reason Reason) Decision {
diff --git a/server/internal/metrics/business.go b/server/internal/metrics/business.go
index f1bd129058..a3e67dc721 100644
--- a/server/internal/metrics/business.go
+++ b/server/internal/metrics/business.go
@@ -47,7 +47,7 @@ type BusinessMetrics struct {
entitlementRefresh *prometheus.CounterVec
entitlementRefreshDuration *prometheus.HistogramVec
entitlementDecision *prometheus.CounterVec
- entitlementVersionRegression *prometheus.CounterVec
+ entitlementVersionRegression prometheus.Counter
autopilotQuotaDecision *prometheus.CounterVec
issueWindowDecision *prometheus.CounterVec
@@ -207,7 +207,7 @@ func NewBusinessMetrics() *BusinessMetrics {
}),
entitlementConfigError: prometheus.NewCounter(prometheus.CounterOpts{
Namespace: "multica", Subsystem: "entitlement", Name: "config_error_total",
- Help: "Total startup failures caused by explicitly enabled but invalid entitlement policy configuration.",
+ Help: "Total startup failures caused by a malformed Multica Cloud URL for entitlement policy.",
}),
entitlementCache: prometheus.NewCounterVec(prometheus.CounterOpts{
Namespace: "multica", Subsystem: "entitlement", Name: "cache_total",
@@ -225,10 +225,10 @@ func NewBusinessMetrics() *BusinessMetrics {
Namespace: "multica", Subsystem: "entitlement", Name: "decision_total",
Help: "Total entitlement decisions by bounded gate, action, and reason.",
}, metricLabels("multica_entitlement_decision_total")),
- entitlementVersionRegression: prometheus.NewCounterVec(prometheus.CounterOpts{
+ entitlementVersionRegression: prometheus.NewCounter(prometheus.CounterOpts{
Namespace: "multica", Subsystem: "entitlement", Name: "version_regression_total",
- Help: "Total rejected entitlement version regressions.",
- }, metricLabels("multica_entitlement_version_regression_total")),
+ Help: "Total rejected entitlement subscription-version regressions.",
+ }),
autopilotQuotaDecision: prometheus.NewCounterVec(prometheus.CounterOpts{
Namespace: "multica", Subsystem: "autopilot_quota", Name: "decision_total",
Help: "Total autopilot quota admission outcomes.",
@@ -306,9 +306,9 @@ func (m *BusinessMetrics) RecordEntitlementDecision(gate, action, reason string)
}
}
-func (m *BusinessMetrics) RecordEntitlementVersionRegression(source string) {
+func (m *BusinessMetrics) RecordEntitlementVersionRegression() {
if m != nil {
- m.entitlementVersionRegression.WithLabelValues(source).Inc()
+ m.entitlementVersionRegression.Inc()
}
}
diff --git a/server/internal/metrics/business_test.go b/server/internal/metrics/business_test.go
index fbee51e48e..2444144cc7 100644
--- a/server/internal/metrics/business_test.go
+++ b/server/internal/metrics/business_test.go
@@ -180,7 +180,7 @@ func TestBusinessMetricsRegistryExposesAllFamilies(t *testing.T) {
m.RecordEntitlementCache("hit")
m.RecordEntitlementRefresh("success", 0.01)
m.RecordEntitlementDecision("autopilot_runs", "observe", "cache_fresh")
- m.RecordEntitlementVersionRegression("refresh")
+ m.RecordEntitlementVersionRegression()
m.RecordAutopilotQuotaDecision("observe", "manual", "admitted")
m.RecordIssueWindowDecision("observe", "list", "would_block")
diff --git a/server/internal/metrics/labels.go b/server/internal/metrics/labels.go
index 8043ee6286..18bce2d528 100644
--- a/server/internal/metrics/labels.go
+++ b/server/internal/metrics/labels.go
@@ -97,7 +97,7 @@ var businessMetricLabels = map[string][]string{
"multica_entitlement_refresh_total": {labelOutcome},
"multica_entitlement_refresh_duration_seconds": {labelOutcome},
"multica_entitlement_decision_total": {labelGate, labelAction, labelReason},
- "multica_entitlement_version_regression_total": {labelSource},
+ "multica_entitlement_version_regression_total": {},
"multica_autopilot_quota_decision_total": {labelAction, labelSource, labelResult},
"multica_issue_window_decision_total": {labelAction, labelSurface, labelResult},
}
diff --git a/server/internal/seatcapacity/client.go b/server/internal/seatcapacity/client.go
index a980010a13..ac52f28c39 100644
--- a/server/internal/seatcapacity/client.go
+++ b/server/internal/seatcapacity/client.go
@@ -20,9 +20,7 @@ import (
const (
defaultTimeout = 3 * time.Second
- maxTimeout = 5 * time.Second
maxResponseBodySize = 64 << 10
- minServiceTokenSize = 32
rateLimitScopeHeader = "X-Multica-RateLimit-Scope"
RateLimitScopeGlobal = "global"
@@ -32,10 +30,8 @@ const (
var ErrInvalidConfig = errors.New("seat capacity: invalid configuration")
type Config struct {
- BaseURL string
- ServiceToken string
- Timeout time.Duration
- HTTPClient *http.Client
+ BaseURL string
+ HTTPClient *http.Client
}
type Capacity struct {
@@ -80,7 +76,7 @@ type Executor interface {
type unavailableExecutor struct{ err error }
// NewUnavailable preserves fail-closed behavior when a Cloud-connected
-// deployment has invalid capacity credentials.
+// deployment has invalid connection configuration.
func NewUnavailable(err error) Executor { return &unavailableExecutor{err: err} }
// CanRunWorker reports whether executor can safely settle durable intents.
@@ -116,10 +112,8 @@ func (u *unavailableExecutor) GetOperation(context.Context, uuid.UUID, uuid.UUID
}
type Client struct {
- baseURL *url.URL
- serviceToken string
- timeout time.Duration
- httpClient *http.Client
+ baseURL *url.URL
+ httpClient *http.Client
}
var _ Executor = (*Client)(nil)
@@ -128,39 +122,24 @@ func (*Client) RecoveryAvailable() bool { return true }
func New(cfg Config) (Executor, error) {
rawURL := strings.TrimRight(strings.TrimSpace(cfg.BaseURL), "/")
- if rawURL == "" && cfg.ServiceToken == "" {
- return nil, nil
- }
if rawURL == "" {
- return nil, fmt.Errorf("%w: base URL is required when a service token is configured", ErrInvalidConfig)
+ return nil, nil
}
baseURL, err := url.Parse(rawURL)
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 absolute and contain no credentials, query, or fragment", ErrInvalidConfig)
}
- if cfg.ServiceToken != strings.TrimSpace(cfg.ServiceToken) || strings.ContainsAny(cfg.ServiceToken, " \t\r\n") || len(cfg.ServiceToken) < minServiceTokenSize {
- return nil, fmt.Errorf("%w: service token must contain at least %d non-whitespace bytes", ErrInvalidConfig, minServiceTokenSize)
- }
- timeout := cfg.Timeout
- if timeout == 0 {
- timeout = defaultTimeout
- }
- if timeout < 0 || timeout > maxTimeout {
- return nil, fmt.Errorf("%w: timeout must be positive and at most %s", ErrInvalidConfig, maxTimeout)
- }
httpClient := &http.Client{}
if cfg.HTTPClient != nil {
clone := *cfg.HTTPClient
httpClient = &clone
}
- // The machine credential must never cross an HTTP redirect boundary.
+ // Internal Cloud calls must not follow a redirect to another origin.
httpClient.CheckRedirect = func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }
return &Client{
- baseURL: baseURL,
- serviceToken: cfg.ServiceToken,
- timeout: timeout,
- httpClient: httpClient,
+ baseURL: baseURL,
+ httpClient: httpClient,
}, nil
}
@@ -211,7 +190,7 @@ func (c *Client) do(ctx context.Context, method string, workspaceID uuid.UUID, s
u := *c.baseURL
u.Path = strings.TrimRight(c.baseURL.Path, "/") + "/api/v1/internal/subscriptions/" + workspaceID.String() + "/capacity/" + suffix
- requestCtx, cancel := context.WithTimeout(ctx, c.timeout)
+ requestCtx, cancel := context.WithTimeout(ctx, defaultTimeout)
defer cancel()
var reader io.Reader
if len(body) > 0 {
@@ -222,7 +201,6 @@ func (c *Client) do(ctx context.Context, method string, workspaceID uuid.UUID, s
return Decision{}, err
}
req.Header.Set("Accept", "application/json")
- req.Header.Set("Authorization", "Bearer "+c.serviceToken)
if len(body) > 0 {
req.Header.Set("Content-Type", "application/json")
}
diff --git a/server/internal/seatcapacity/client_test.go b/server/internal/seatcapacity/client_test.go
index bb146f554d..f2a5816479 100644
--- a/server/internal/seatcapacity/client_test.go
+++ b/server/internal/seatcapacity/client_test.go
@@ -5,7 +5,6 @@ import (
"errors"
"net/http"
"net/http/httptest"
- "strings"
"testing"
"time"
@@ -18,15 +17,15 @@ func TestClientReserveInvitation(t *testing.T) {
if r.Method != http.MethodPost || r.URL.Path != "/base/api/v1/internal/subscriptions/"+workspaceID.String()+"/capacity/reserve" {
t.Fatalf("unexpected request %s %s", r.Method, r.URL.Path)
}
- if got := r.Header.Get("Authorization"); got != "Bearer "+strings.Repeat("s", 32) {
- t.Fatalf("Authorization = %q", got)
+ if got := r.Header.Get("Authorization"); got != "" {
+ t.Fatalf("Authorization must be absent, got %q", got)
}
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"managed":true,"allowed":false,"reason":"capacity_full"}`))
}))
defer server.Close()
- client, err := New(Config{BaseURL: server.URL + "/base", ServiceToken: strings.Repeat("s", 32)})
+ client, err := New(Config{BaseURL: server.URL + "/base"})
if err != nil {
t.Fatal(err)
}
@@ -39,10 +38,10 @@ func TestClientReserveInvitation(t *testing.T) {
}
}
-func TestClientRejectsRedirectAndDoesNotForwardCredential(t *testing.T) {
- var redirectedAuth string
- target := httptest.NewServer(http.HandlerFunc(func(_ http.ResponseWriter, r *http.Request) {
- redirectedAuth = r.Header.Get("Authorization")
+func TestClientRejectsRedirect(t *testing.T) {
+ var redirected bool
+ target := httptest.NewServer(http.HandlerFunc(func(_ http.ResponseWriter, _ *http.Request) {
+ redirected = true
}))
defer target.Close()
source := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
@@ -50,7 +49,7 @@ func TestClientRejectsRedirectAndDoesNotForwardCredential(t *testing.T) {
}))
defer source.Close()
- client, err := New(Config{BaseURL: source.URL, ServiceToken: strings.Repeat("s", 32)})
+ client, err := New(Config{BaseURL: source.URL})
if err != nil {
t.Fatal(err)
}
@@ -59,8 +58,8 @@ func TestClientRejectsRedirectAndDoesNotForwardCredential(t *testing.T) {
if !errors.As(err, &remote) || remote.StatusCode != http.StatusTemporaryRedirect {
t.Fatalf("error = %v", err)
}
- if redirectedAuth != "" {
- t.Fatalf("credential reached redirect target: %q", redirectedAuth)
+ if redirected {
+ t.Fatal("redirect target received an internal Cloud request")
}
}
@@ -83,7 +82,7 @@ func TestClientPreservesCapacityRateLimit(t *testing.T) {
}))
defer server.Close()
- client, err := New(Config{BaseURL: server.URL, ServiceToken: strings.Repeat("s", 32)})
+ client, err := New(Config{BaseURL: server.URL})
if err != nil {
t.Fatal(err)
}
@@ -107,7 +106,7 @@ func TestClientPreservesCloudWorkspaceRateLimitScope(t *testing.T) {
}))
defer server.Close()
- client, err := New(Config{BaseURL: server.URL, ServiceToken: strings.Repeat("s", 32)})
+ client, err := New(Config{BaseURL: server.URL})
if err != nil {
t.Fatal(err)
}
@@ -125,7 +124,7 @@ func TestRetryAfterDurationAcceptsHTTPDate(t *testing.T) {
}
}
-func TestClientIsDisabledOnlyWhenCloudURLAndTokenAreAbsent(t *testing.T) {
+func TestClientIsDisabledWhenCloudURLIsAbsent(t *testing.T) {
client, err := New(Config{})
if err != nil {
t.Fatal(err)
@@ -135,23 +134,8 @@ func TestClientIsDisabledOnlyWhenCloudURLAndTokenAreAbsent(t *testing.T) {
}
}
-func TestCloudConnectedClientRejectsUnsafeConfiguration(t *testing.T) {
- tests := []struct {
- name string
- cfg Config
- }{
- {name: "missing URL", cfg: Config{ServiceToken: strings.Repeat("s", 32)}},
- {name: "missing token", cfg: Config{BaseURL: "https://example.com"}},
- {name: "URL credentials", cfg: Config{BaseURL: "https://user:[email protected]", ServiceToken: strings.Repeat("s", 32)}},
- {name: "short token", cfg: Config{BaseURL: "https://example.com", ServiceToken: "short"}},
- {name: "token whitespace", cfg: Config{BaseURL: "https://example.com", ServiceToken: strings.Repeat("s", 31) + "\n"}},
- {name: "excessive timeout", cfg: Config{BaseURL: "https://example.com", ServiceToken: strings.Repeat("s", 32), Timeout: 6 * time.Second}},
- }
- for _, tt := range tests {
- t.Run(tt.name, func(t *testing.T) {
- if _, err := New(tt.cfg); !errors.Is(err, ErrInvalidConfig) {
- t.Fatalf("New() error = %v, want ErrInvalidConfig", err)
- }
- })
+func TestCloudConnectedClientRejectsUnsafeURL(t *testing.T) {
+ if _, err := New(Config{BaseURL: "https://user:[email protected]"}); !errors.Is(err, ErrInvalidConfig) {
+ t.Fatalf("New() error = %v, want ErrInvalidConfig", err)
}
}