From 13231aa0342fbb78833367fa8a6dd71f632c7f4b Mon Sep 17 00:00:00 2001 From: Abhyudaya Baiju Tharakan Date: Fri, 9 Oct 2026 10:11:16 +0530 Subject: [PATCH] feat(enterprise): add optional enterprise integration contracts Defines frozen identity, tenancy, quota and credit authority contracts with explicit adapters and deny-by-default missing authority, plus an administrator-only dry-run preview at /admin/enterprise/preview. ENTERPRISE_PREVIEW_ENABLED defaults to off, and registering the contracts activates nothing. --- app.py | 2 + docs/enterprise-contracts.md | 445 +++++++++++++++++++ package.json | 2 +- routes/enterprise_preview.py | 31 ++ services/enterprise_contract.py | 256 +++++++++++ tests/fixtures/secret_firewall_coverage.json | 4 + tests/test_enterprise_contracts.py | 237 ++++++++++ tests/test_enterprise_contracts_worker.mjs | 124 ++++++ worker/container-env.mjs | 1 + worker/enterprise-contract.mjs | 185 ++++++++ 10 files changed, 1286 insertions(+), 1 deletion(-) create mode 100644 docs/enterprise-contracts.md create mode 100644 routes/enterprise_preview.py create mode 100644 services/enterprise_contract.py create mode 100644 tests/test_enterprise_contracts.py create mode 100644 tests/test_enterprise_contracts_worker.mjs create mode 100644 worker/enterprise-contract.mjs diff --git a/app.py b/app.py index 143ccdeb..cbe4c0d9 100644 --- a/app.py +++ b/app.py @@ -19,6 +19,7 @@ login_required, ) from routes.config_snapshots import register_config_snapshot_routes +from routes.enterprise_preview import register_enterprise_preview_routes from routes.core import register_core_routes from routes.dashboard_security import register_dashboard_security_routes from routes.intelligence_media import register_intelligence_media_routes @@ -144,6 +145,7 @@ def create_app() -> Flask: register_dashboard_security_routes(app) register_workbench_routes(app) register_config_snapshot_routes(app) + register_enterprise_preview_routes(app) register_shadow_eval_routes(app, csrf, AuthService, MetricsService, ProxyService) register_knowledge_routes(app, csrf) register_gateway_mcp_routes(app, csrf) diff --git a/docs/enterprise-contracts.md b/docs/enterprise-contracts.md new file mode 100644 index 00000000..c3c786db --- /dev/null +++ b/docs/enterprise-contracts.md @@ -0,0 +1,445 @@ +# Enterprise integration contracts + +`ENTERPRISE_PREVIEW_ENABLED` defaults to off. Empty, `false`, `0`, `no` and `off` disable the preview. `true`, `1`, `yes` and `on` enable it, ignoring case and surrounding whitespace. Malformed settings disable it and log one warning per process without the supplied value. + +With the default settings, `GET /admin/enterprise/preview` returns HTTP 404, including for unauthenticated requests. To enable it, set `ENTERPRISE_PREVIEW_ENABLED=true` and use an existing administrator dashboard session: + +```sh +curl --cookie session-cookie.txt https://gateway.example/admin/enterprise/preview +``` + +The enabled route returns a JSON descriptor with `version: 1`, `dry_run: true`, `activation: false`, contract names, registered-authority availability and the supported operations. It does not call an authority or mutate grants, quotas or balances. An unauthenticated JSON request returns 401; an authenticated non-administrator returns 403. It sends `Cache-Control: no-store`. There is no Worker-native public preview route; the Flask preview is served through the existing Container transport. + +## Authority boundary + +Python exports frozen dataclasses and typed protocols from `services/enterprise_contract.py`. Worker exports frozen classes and matching JSDoc interfaces from `worker/enterprise-contract.mjs`. Construct `AuthorityOperation(context, scoped_id, revision, operation_id, amount)` in Python, or pass those named fields to the Worker constructor. A context carries `principal_id`, optional `org_id`/`team_id`, and `grants_revision`; a team requires an organisation. + +Identifiers are opaque, case-sensitive ASCII strings of 1–128 letters, digits, underscores, colons, dots or hyphens. They are never parsed as hierarchy, paths or credentials. Revisions and amounts are nonnegative integers below 9007199254740991 so both runtimes agree exactly. Amounts use the registered authority's documented integer units; these contracts introduce no pricing or currency conversion. An authority's successful result must retain the exact context, scoped ID and operation ID, and return the atomic successor revision. Only result revisions may equal 9007199254740991. Stale, foreign, untyped or denied results raise `AuthorityDenied`. + +Register explicit functions with `register_enterprise_adapters` / `registerEnterpriseAdapters`. Tenant and identity callbacks return a matching immutable context. Quota and credit adapters expose all three methods: `reserve`, `commit`, `reconcile`. Payment callbacks accept only immutable verified `PaymentEvent` instances and return a bound `AuthorityResult`. Registration performs no calls. There is no plugin discovery, runtime module loading or routing language. The initial tenant callback preserves the existing single principal and grants revision, denies organisation/team scope, and provides no identity, quota, credit or payment authority. Passing a missing callback denies access. Registration and the preview flag never activate enterprise enforcement on existing requests; authentication, key controls and budgets remain authoritative. + +Concrete authorities must atomically compare the revision, validate the current grants revision and scoped ownership, and persist the operation ID with the state change. Repeated IDs return the original bound result without a second mutation. A later lifecycle step uses a new operation ID and the prior successor revision. Conflicts deny; transport errors propagate and do not permit automatic replay. These modules validate input and result bindings but contain no storage, CAS implementation or deduplication ledger. + +IdentityAssertion records pinned issuer, subject, audience, request, nonce and expiry. Its trusted producer must verify signature, issuer/audience, recipient, clock expiry and single use before construction. PaymentEvent records processor/event IDs, context, scoped ID, expected revision, idempotency ID, kind (`credit`, `refund`, `dispute`), uppercase three-letter currency and integer amount. Its trusted producer must verify the processor signature and merchant/currency/event binding before construction. `verified: true` is a typed attestation from that trusted producer, not signature verification and never a field accepted directly from public JSON. The identity authority must bind the assertion subject to the requested principal and scope. No webhook, SAML verifier, organisational data, ledger, migration or payment processing is supplied here. + +## Cost, errors and retention + +The descriptor makes no provider, database, billing or processor calls and incurs no generation cost. It includes no identity, credential, prompt, response or payment details and creates no stored data. Contract calls have no retry policy; callers must handle denial and uncertainty without fabricating success. Concrete integrations own storage retention and audit policies. These contracts do not certify provider metering, merchant processing or deployed enterprise capabilities. + +## Shared contract vectors + +Both test suites read the following synthetic vectors directly. All IDs and values are fixtures. + +```json +[ + { + "name": "legacy context", + "type": "TenantContext", + "data": { + "principal_id": "principal:one", + "grants_revision": 4 + }, + "valid": true + }, + { + "name": "org team context", + "type": "TenantContext", + "data": { + "principal_id": "principal:one", + "grants_revision": 4, + "org_id": "org:one", + "team_id": "team:one" + }, + "valid": true + }, + { + "name": "team without org", + "type": "TenantContext", + "data": { + "principal_id": "principal:one", + "grants_revision": 4, + "team_id": "team:one" + }, + "valid": false + }, + { + "name": "empty principal", + "type": "TenantContext", + "data": { + "principal_id": "", + "grants_revision": 4 + }, + "valid": false + }, + { + "name": "boolean revision", + "type": "TenantContext", + "data": { + "principal_id": "principal:one", + "grants_revision": true + }, + "valid": false + }, + { + "name": "negative revision", + "type": "TenantContext", + "data": { + "principal_id": "principal:one", + "grants_revision": -1 + }, + "valid": false + }, + { + "name": "operation", + "type": "AuthorityOperation", + "data": { + "context": { + "principal_id": "principal:one", + "grants_revision": 4 + }, + "scoped_id": "resource:one", + "revision": 7, + "operation_id": "operation:one", + "amount": 12 + }, + "valid": true + }, + { + "name": "empty operation id", + "type": "AuthorityOperation", + "data": { + "context": { + "principal_id": "principal:one", + "grants_revision": 4 + }, + "scoped_id": "resource:one", + "revision": 7, + "operation_id": "", + "amount": 12 + }, + "valid": false + }, + { + "name": "fractional revision", + "type": "AuthorityOperation", + "data": { + "context": { + "principal_id": "principal:one", + "grants_revision": 4 + }, + "scoped_id": "resource:one", + "revision": 1.5, + "operation_id": "operation:one", + "amount": 12 + }, + "valid": false + }, + { + "name": "unsafe revision", + "type": "AuthorityOperation", + "data": { + "context": { + "principal_id": "principal:one", + "grants_revision": 4 + }, + "scoped_id": "resource:one", + "revision": 9007199254740991, + "operation_id": "operation:one", + "amount": 12 + }, + "valid": false + }, + { + "name": "negative units", + "type": "AuthorityOperation", + "data": { + "context": { + "principal_id": "principal:one", + "grants_revision": 4 + }, + "scoped_id": "resource:one", + "revision": 7, + "operation_id": "operation:one", + "amount": -1 + }, + "valid": false + }, + { + "name": "verified assertion", + "type": "IdentityAssertion", + "data": { + "issuer_id": "issuer:one", + "subject_id": "subject:one", + "audience_id": "audience:one", + "request_id": "request:one", + "nonce_id": "nonce:one", + "expires_at": 1000, + "verified": true + }, + "valid": true + }, + { + "name": "unverified assertion", + "type": "IdentityAssertion", + "data": { + "issuer_id": "issuer:one", + "subject_id": "subject:one", + "audience_id": "audience:one", + "request_id": "request:one", + "nonce_id": "nonce:one", + "expires_at": 1000, + "verified": false + }, + "valid": false + }, + { + "name": "missing nonce", + "type": "IdentityAssertion", + "data": { + "issuer_id": "issuer:one", + "subject_id": "subject:one", + "audience_id": "audience:one", + "request_id": "request:one", + "expires_at": 1000, + "verified": true + }, + "valid": false + }, + { + "name": "verified payment", + "type": "PaymentEvent", + "data": { + "context": { + "principal_id": "principal:one", + "grants_revision": 4 + }, + "scoped_id": "resource:one", + "revision": 7, + "idempotency_id": "operation:one", + "processor_id": "processor:one", + "event_id": "event:one", + "kind": "credit", + "currency": "USD", + "amount": 12, + "verified": true + }, + "valid": true + }, + { + "name": "unverified payment", + "type": "PaymentEvent", + "data": { + "context": { + "principal_id": "principal:one", + "grants_revision": 4 + }, + "scoped_id": "resource:one", + "revision": 7, + "idempotency_id": "operation:one", + "processor_id": "processor:one", + "event_id": "event:one", + "kind": "credit", + "currency": "USD", + "amount": 12, + "verified": false + }, + "valid": false + }, + { + "name": "payment idempotency", + "type": "PaymentEvent", + "data": { + "context": { + "principal_id": "principal:one", + "grants_revision": 4 + }, + "scoped_id": "resource:one", + "revision": 7, + "idempotency_id": "", + "processor_id": "processor:one", + "event_id": "event:one", + "kind": "credit", + "currency": "USD", + "amount": 12, + "verified": true + }, + "valid": false + }, + { + "name": "payment currency", + "type": "PaymentEvent", + "data": { + "context": { + "principal_id": "principal:one", + "grants_revision": 4 + }, + "scoped_id": "resource:one", + "revision": 7, + "idempotency_id": "operation:one", + "processor_id": "processor:one", + "event_id": "event:one", + "kind": "credit", + "currency": "usd", + "amount": 12, + "verified": true + }, + "valid": false + }, + { + "name": "bound decision", + "type": "AuthorityResult", + "data": { + "context": { + "principal_id": "principal:one", + "grants_revision": 4 + }, + "scoped_id": "resource:one", + "revision": 8, + "operation_id": "operation:one", + "allowed": true + }, + "valid": true + }, + { + "name": "unknown context field", + "type": "TenantContext", + "data": { + "principal_id": "principal:one", + "grants_revision": 4, + "extra": "value" + }, + "valid": false + }, + { + "name": "identifier newline", + "type": "TenantContext", + "data": { + "principal_id": "principal:one\n", + "grants_revision": 4 + }, + "valid": false + }, + { + "name": "long identifier", + "type": "TenantContext", + "data": { + "principal_id": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "grants_revision": 4 + }, + "valid": false + }, + { + "name": "identifier upper bound", + "type": "TenantContext", + "data": { + "principal_id": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "grants_revision": 4 + }, + "valid": true + }, + { + "name": "string revision", + "type": "AuthorityOperation", + "data": { + "context": { + "principal_id": "principal:one", + "grants_revision": 4 + }, + "scoped_id": "resource:one", + "revision": "7", + "operation_id": "operation:one", + "amount": 12 + }, + "valid": false + }, + { + "name": "null amount", + "type": "AuthorityOperation", + "data": { + "context": { + "principal_id": "principal:one", + "grants_revision": 4 + }, + "scoped_id": "resource:one", + "revision": 7, + "operation_id": "operation:one", + "amount": null + }, + "valid": false + }, + { + "name": "operation upper bound", + "type": "AuthorityOperation", + "data": { + "context": { + "principal_id": "principal:one", + "grants_revision": 4 + }, + "scoped_id": "resource:one", + "revision": 9007199254740990, + "operation_id": "operation:one", + "amount": 12 + }, + "valid": true + }, + { + "name": "currency newline", + "type": "PaymentEvent", + "data": { + "context": { + "principal_id": "principal:one", + "grants_revision": 4 + }, + "scoped_id": "resource:one", + "revision": 7, + "idempotency_id": "operation:one", + "processor_id": "processor:one", + "event_id": "event:one", + "kind": "credit", + "currency": "USD\n", + "amount": 12, + "verified": true + }, + "valid": false + }, + { + "name": "nonboolean attestation", + "type": "PaymentEvent", + "data": { + "context": { + "principal_id": "principal:one", + "grants_revision": 4 + }, + "scoped_id": "resource:one", + "revision": 7, + "idempotency_id": "operation:one", + "processor_id": "processor:one", + "event_id": "event:one", + "kind": "credit", + "currency": "USD", + "amount": 12, + "verified": 1 + }, + "valid": false + }, + { + "name": "unknown payment kind", + "type": "PaymentEvent", + "data": { + "context": { + "principal_id": "principal:one", + "grants_revision": 4 + }, + "scoped_id": "resource:one", + "revision": 7, + "idempotency_id": "operation:one", + "processor_id": "processor:one", + "event_id": "event:one", + "kind": "transfer", + "currency": "USD", + "amount": 12, + "verified": true + }, + "valid": false + } +]``` diff --git a/package.json b/package.json index a006629c..b54f995a 100644 --- a/package.json +++ b/package.json @@ -9,7 +9,7 @@ "lint": "ruff check . --select E9,F63,F7,F82", "typecheck": "mypy --ignore-missing-imports --follow-imports=skip --disable-error-code import-untyped --disable-error-code var-annotated --disable-error-code arg-type --disable-error-code assignment --disable-error-code operator app.py routes services providers streaming", "test": "python -m pytest -q", - "test:worker": "node --test tests/test_cloudflare_worker.mjs tests/test_cascades_worker.mjs tests/test_cascades_dashboard.mjs tests/test_image_quality_worker.mjs tests/test_secret_scan_worker.mjs tests/test_secret_firewall_worker.mjs tests/test_secret_firewall_coverage_worker.mjs tests/test_roleplay_compaction_budget_worker.mjs tests/test_roleplay_compaction_model_worker.mjs tests/test_roleplay_stream_validation_worker.mjs tests/test_aihubmix_worker.mjs tests/test_gpt_image_moderation_worker.mjs tests/test_dashboard_scripts.mjs tests/test_operations_dashboard.mjs tests/test_opencode_reasoning_worker.mjs tests/test_opencode_thinking_worker.mjs tests/test_nanogpt_reasoning_worker.mjs tests/test_nanogpt_speed_routing_worker.mjs tests/test_sse_heartbeat_worker.mjs tests/test_roleplay_worker.mjs tests/test_roleplay_config_worker.mjs tests/test_roleplay_glm_failover_worker.mjs tests/test_roleplay_intelligence_worker.mjs tests/test_roleplay_memory_worker.mjs tests/test_roleplay_compatibility_worker.mjs tests/test_roleplay_history_reconciliation_worker.mjs tests/test_roleplay_output_contract_analysis.mjs tests/test_roleplay_output_contract_cleanup_worker.mjs tests/test_roleplay_output_contract_nonstream_worker.mjs tests/test_roleplay_output_contract_worker.mjs tests/test_roleplay_performance_worker.mjs tests/test_roleplay_quality_routing_worker.mjs tests/test_roleplay_reasoning_worker.mjs tests/test_roleplay_session_storage_worker.mjs tests/test_roleplay_transport_failure_worker.mjs tests/test_roleplay_unlimited_worker.mjs tests/test_roleplay_workbench_worker.mjs tests/test_roleplay_candidate_context_worker.mjs tests/test_roleplay_operator_worker.mjs tests/test_workbench_stream.mjs tests/test_intelligence_worker.mjs tests/test_intelligence_d1_worker.mjs tests/test_intelligence_auth_worker.mjs tests/test_intelligence_outbound_worker.mjs tests/test_intelligence_operator.mjs tests/test_control_users_worker.mjs tests/test_control_audit_worker.mjs tests/test_access_sso_worker.mjs tests/test_d1_schema_worker.mjs tests/test_shadow_eval_worker.mjs tests/test_auto_routes_worker.mjs tests/test_ai_outbound_worker.mjs tests/test_knowledge_*.mjs tests/test_control_state_worker.mjs tests/test_route_health_worker.mjs tests/test_gateway_mcp_worker.mjs tests/test_usage_ledger_worker.mjs tests/test_media_outbound_worker.mjs tests/test_media_files_worker.mjs tests/test_media_jobs_worker.mjs tests/test_tool_repair_worker.mjs tests/test_prometheus_worker.mjs tests/test_evaluation_noise_floor_worker.mjs tests/test_prompt_templates_worker.mjs tests/test_config_snapshots_worker.mjs tests/test_managed_idempotency_worker.mjs tests/test_wave3_hub_worker.mjs tests/test_wave3_transport_worker.mjs tests/test_admission_leases_worker.mjs tests/test_edge_request_metrics_worker.mjs tests/test_request_cancellation_worker.mjs tests/test_mcp_contract_drift_worker.mjs tests/test_zero_content_retention_worker.mjs tests/test_prompt_cache_cost_worker.mjs tests/test_config_revision_sync_worker.mjs tests/test_gateway_alerts_worker.mjs tests/test_session_tiers_worker.mjs tests/test_usage_reservations_worker.mjs tests/test_shared_generation_cache_worker.mjs tests/test_deferred_tools_worker.mjs tests/test_generation_deadline_worker.mjs tests/test_wave4_worker.mjs tests/test_responses_state_worker.mjs tests/test_gateway_batches_worker.mjs tests/test_semantic_generation_cache_worker.mjs tests/test_canary_traffic_worker.mjs tests/test_context_pages_worker.mjs tests/test_observability_exports_worker.mjs tests/test_prompt_injection_worker.mjs tests/test_pii_rehydration_worker.mjs tests/test_wave5_worker.mjs", + "test:worker": "node --test tests/test_cloudflare_worker.mjs tests/test_cascades_worker.mjs tests/test_cascades_dashboard.mjs tests/test_image_quality_worker.mjs tests/test_secret_scan_worker.mjs tests/test_secret_firewall_worker.mjs tests/test_secret_firewall_coverage_worker.mjs tests/test_roleplay_compaction_budget_worker.mjs tests/test_roleplay_compaction_model_worker.mjs tests/test_roleplay_stream_validation_worker.mjs tests/test_aihubmix_worker.mjs tests/test_gpt_image_moderation_worker.mjs tests/test_dashboard_scripts.mjs tests/test_operations_dashboard.mjs tests/test_opencode_reasoning_worker.mjs tests/test_opencode_thinking_worker.mjs tests/test_nanogpt_reasoning_worker.mjs tests/test_nanogpt_speed_routing_worker.mjs tests/test_sse_heartbeat_worker.mjs tests/test_roleplay_worker.mjs tests/test_roleplay_config_worker.mjs tests/test_roleplay_glm_failover_worker.mjs tests/test_roleplay_intelligence_worker.mjs tests/test_roleplay_memory_worker.mjs tests/test_roleplay_compatibility_worker.mjs tests/test_roleplay_history_reconciliation_worker.mjs tests/test_roleplay_output_contract_analysis.mjs tests/test_roleplay_output_contract_cleanup_worker.mjs tests/test_roleplay_output_contract_nonstream_worker.mjs tests/test_roleplay_output_contract_worker.mjs tests/test_roleplay_performance_worker.mjs tests/test_roleplay_quality_routing_worker.mjs tests/test_roleplay_reasoning_worker.mjs tests/test_roleplay_session_storage_worker.mjs tests/test_roleplay_transport_failure_worker.mjs tests/test_roleplay_unlimited_worker.mjs tests/test_roleplay_workbench_worker.mjs tests/test_roleplay_candidate_context_worker.mjs tests/test_roleplay_operator_worker.mjs tests/test_workbench_stream.mjs tests/test_intelligence_worker.mjs tests/test_intelligence_d1_worker.mjs tests/test_intelligence_auth_worker.mjs tests/test_intelligence_outbound_worker.mjs tests/test_intelligence_operator.mjs tests/test_control_users_worker.mjs tests/test_control_audit_worker.mjs tests/test_access_sso_worker.mjs tests/test_d1_schema_worker.mjs tests/test_shadow_eval_worker.mjs tests/test_auto_routes_worker.mjs tests/test_ai_outbound_worker.mjs tests/test_knowledge_*.mjs tests/test_control_state_worker.mjs tests/test_route_health_worker.mjs tests/test_gateway_mcp_worker.mjs tests/test_usage_ledger_worker.mjs tests/test_media_outbound_worker.mjs tests/test_media_files_worker.mjs tests/test_media_jobs_worker.mjs tests/test_tool_repair_worker.mjs tests/test_prometheus_worker.mjs tests/test_evaluation_noise_floor_worker.mjs tests/test_prompt_templates_worker.mjs tests/test_config_snapshots_worker.mjs tests/test_managed_idempotency_worker.mjs tests/test_wave3_hub_worker.mjs tests/test_wave3_transport_worker.mjs tests/test_admission_leases_worker.mjs tests/test_edge_request_metrics_worker.mjs tests/test_request_cancellation_worker.mjs tests/test_mcp_contract_drift_worker.mjs tests/test_zero_content_retention_worker.mjs tests/test_prompt_cache_cost_worker.mjs tests/test_config_revision_sync_worker.mjs tests/test_gateway_alerts_worker.mjs tests/test_session_tiers_worker.mjs tests/test_usage_reservations_worker.mjs tests/test_shared_generation_cache_worker.mjs tests/test_deferred_tools_worker.mjs tests/test_generation_deadline_worker.mjs tests/test_wave4_worker.mjs tests/test_responses_state_worker.mjs tests/test_gateway_batches_worker.mjs tests/test_semantic_generation_cache_worker.mjs tests/test_canary_traffic_worker.mjs tests/test_context_pages_worker.mjs tests/test_observability_exports_worker.mjs tests/test_prompt_injection_worker.mjs tests/test_pii_rehydration_worker.mjs tests/test_wave5_worker.mjs tests/test_enterprise_contracts_worker.mjs", "db:migrate": "python scripts/validate_sqlite_schema.py --apply", "db:validate": "python scripts/validate_sqlite_schema.py", "security:secrets": "python scripts/check_static_secrets.py", diff --git a/routes/enterprise_preview.py b/routes/enterprise_preview.py new file mode 100644 index 00000000..b2f9a6f8 --- /dev/null +++ b/routes/enterprise_preview.py @@ -0,0 +1,31 @@ +"""Administrator-only read-only descriptor for explicit enterprise contracts.""" +from flask import jsonify, request + +from route_helpers import login_required +from routes.config_snapshots import json_errors +from routes.core import require_admin_dashboard_user +from services import enterprise_contract as contracts + + +def register_enterprise_preview_routes(app): + app.extensions["enterprise_adapters"] = contracts.register_enterprise_adapters() + + def disabled_enterprise_preview(): + if request.path != "/admin/enterprise/preview": + return None + if not contracts.preview_enabled(): + return jsonify({"error": "not_found"}), 404 + if request.method not in {"GET", "HEAD", "OPTIONS"}: + return jsonify({"error": "method_not_allowed"}), 405, {"Allow": "GET, HEAD, OPTIONS"} + return None + + app.before_request_funcs.setdefault(None, []).insert(0, disabled_enterprise_preview) + + @app.get("/admin/enterprise/preview") + @json_errors + @login_required + def admin_enterprise_preview(): + require_admin_dashboard_user() + response = jsonify(contracts.preview_descriptor(app.extensions["enterprise_adapters"])) + response.headers["Cache-Control"] = "no-store" + return response diff --git a/services/enterprise_contract.py b/services/enterprise_contract.py new file mode 100644 index 00000000..21de8fa7 --- /dev/null +++ b/services/enterprise_contract.py @@ -0,0 +1,256 @@ +"""Explicit immutable authority boundaries; registration grants no permissions.""" +from __future__ import annotations + +import logging +import os +import re +from dataclasses import dataclass +from functools import lru_cache +from typing import Literal, Mapping, Protocol + +logger = logging.getLogger(__name__) +MAX_INTEGER = 9007199254740991 + + +def _opaque(value: object) -> None: + if not isinstance(value, str) or not re.fullmatch(r"[A-Za-z0-9_:.\-]{1,128}", value): + raise ValueError("Invalid opaque identifier") + + +def _integer(value: object) -> None: + if type(value) is not int or not 0 <= value < MAX_INTEGER: + raise ValueError("Invalid bounded integer") + + +@dataclass(frozen=True) +class TenantContext: + principal_id: str + org_id: str | None = None + team_id: str | None = None + grants_revision: int = 0 + + def __post_init__(self) -> None: + _opaque(self.principal_id) + _integer(self.grants_revision) + for value in (self.org_id, self.team_id): + if value is not None: + _opaque(value) + if self.team_id is not None and self.org_id is None: + raise ValueError("Team requires organisation scope") + + +@dataclass(frozen=True) +class IdentityAssertion: + issuer_id: str + subject_id: str + audience_id: str + request_id: str + nonce_id: str + expires_at: int + verified: bool + + def __post_init__(self) -> None: + for value in (self.issuer_id, self.subject_id, self.audience_id, self.request_id, self.nonce_id): + _opaque(value) + _integer(self.expires_at) + if self.verified is not True or self.expires_at == 0: + raise ValueError("Verified identity assertion required") + + +@dataclass(frozen=True) +class AuthorityOperation: + context: TenantContext + scoped_id: str + revision: int + operation_id: str + amount: int = 0 + + def __post_init__(self) -> None: + if type(self.context) is not TenantContext: + raise TypeError("TenantContext required") + _opaque(self.scoped_id) + _opaque(self.operation_id) + _integer(self.revision) + _integer(self.amount) + + +@dataclass(frozen=True) +class AuthorityResult: + context: TenantContext + scoped_id: str + revision: int + operation_id: str + allowed: bool + + def __post_init__(self) -> None: + if type(self.context) is not TenantContext: + raise TypeError("TenantContext required") + _opaque(self.scoped_id) + _opaque(self.operation_id) + # Results may include the successor of the largest accepted input revision. + if type(self.revision) is not int or not 0 <= self.revision <= MAX_INTEGER: + raise ValueError("Invalid revision") + if type(self.allowed) is not bool: + raise TypeError("Boolean decision required") + + +@dataclass(frozen=True) +class PaymentEvent: + context: TenantContext + scoped_id: str + revision: int + idempotency_id: str + processor_id: str + event_id: str + kind: Literal["credit", "refund", "dispute"] + currency: str + amount: int + verified: bool + + def __post_init__(self) -> None: + AuthorityOperation(self.context, self.scoped_id, self.revision, self.idempotency_id, self.amount) + _opaque(self.processor_id) + _opaque(self.event_id) + if (self.verified is not True or self.kind not in {"credit", "refund", "dispute"} + or not isinstance(self.currency, str) or not re.fullmatch(r"[A-Z]{3}", self.currency)): + raise ValueError("Verified payment event required") + + +class TenantAuthority(Protocol): + def __call__(self, operation: AuthorityOperation) -> TenantContext: ... + + +class IdentityAuthority(Protocol): + def __call__(self, assertion: IdentityAssertion, operation: AuthorityOperation) -> TenantContext: ... + + +class QuotaAuthority(Protocol): + def reserve(self, operation: AuthorityOperation) -> AuthorityResult: ... + def commit(self, operation: AuthorityOperation) -> AuthorityResult: ... + def reconcile(self, operation: AuthorityOperation) -> AuthorityResult: ... + + +class CreditAuthority(QuotaAuthority, Protocol): + """Integer units and atomic revision semantics are defined by the registered ledger.""" + + +class PaymentCallback(Protocol): + def __call__(self, event: PaymentEvent) -> AuthorityResult: ... + + +class AuthorityDenied(Exception): + """A missing authority or unbound decision cannot grant access.""" + + +def legacy_tenant(operation: AuthorityOperation) -> TenantContext: + _operation(operation) + if operation.context.org_id is not None or operation.context.team_id is not None: + raise AuthorityDenied("tenant_scope_denied") + return operation.context + + +@dataclass(frozen=True) +class EnterpriseAdapters: + tenant: TenantAuthority | None = legacy_tenant + identity: IdentityAuthority | None = None + quota: QuotaAuthority | None = None + credit: CreditAuthority | None = None + payment: PaymentCallback | None = None + + +def register_enterprise_adapters(*, tenant: TenantAuthority | None = legacy_tenant, + identity: IdentityAuthority | None = None, + quota: QuotaAuthority | None = None, + credit: CreditAuthority | None = None, + payment: PaymentCallback | None = None) -> EnterpriseAdapters: + """Return fixed collaborators without importing plugins or calling authorities.""" + for callback in (tenant, identity, payment): + if callback is not None and not callable(callback): + raise TypeError("Explicit authority function required") + for authority in (quota, credit): + if authority is not None and not all(callable(getattr(authority, name, None)) + for name in ("reserve", "commit", "reconcile")): + raise TypeError("Complete reserve/commit/reconcile authority required") + return EnterpriseAdapters(tenant, identity, quota, credit, payment) + + +def _operation(operation: AuthorityOperation) -> None: + if type(operation) is not AuthorityOperation: + raise TypeError("AuthorityOperation required") + + +def _context(result: object, operation: AuthorityOperation) -> TenantContext: + if type(result) is not TenantContext or result != operation.context: + raise AuthorityDenied("authority_scope_mismatch") + return result + + +def resolve_tenant(adapters: EnterpriseAdapters, operation: AuthorityOperation) -> TenantContext: + _operation(operation) + if adapters.tenant is None: + raise AuthorityDenied("authority_unavailable") + return _context(adapters.tenant(operation), operation) + + +def resolve_identity(adapters: EnterpriseAdapters, assertion: IdentityAssertion, + operation: AuthorityOperation) -> TenantContext: + _operation(operation) + if type(assertion) is not IdentityAssertion or assertion.verified is not True: + raise TypeError("Verified IdentityAssertion required") + if adapters.identity is None: + raise AuthorityDenied("authority_unavailable") + return _context(adapters.identity(assertion, operation), operation) + + +def _result(result: object, operation: AuthorityOperation) -> AuthorityResult: + if (type(result) is not AuthorityResult or not result.allowed + or result.context != operation.context or result.scoped_id != operation.scoped_id + or result.operation_id != operation.operation_id or result.revision != operation.revision + 1): + raise AuthorityDenied("authority_decision_denied") + return result + + +def call_authority(adapters: EnterpriseAdapters, authority: Literal["quota", "credit"], + action: Literal["reserve", "commit", "reconcile"], + operation: AuthorityOperation) -> AuthorityResult: + _operation(operation) + if authority not in {"quota", "credit"} or action not in {"reserve", "commit", "reconcile"}: + raise ValueError("Unknown authority operation") + target = adapters.quota if authority == "quota" else adapters.credit + if target is None: + raise AuthorityDenied("authority_unavailable") + callback = target.reserve if action == "reserve" else target.commit if action == "commit" else target.reconcile + return _result(callback(operation), operation) + + +def deliver_payment(adapters: EnterpriseAdapters, event: PaymentEvent) -> AuthorityResult: + if type(event) is not PaymentEvent or event.verified is not True: + raise TypeError("Verified PaymentEvent required") + if adapters.payment is None: + raise AuthorityDenied("authority_unavailable") + operation = AuthorityOperation(event.context, event.scoped_id, event.revision, event.idempotency_id, event.amount) + return _result(adapters.payment(event), operation) + + +@lru_cache(maxsize=1) +def _warn_once() -> None: + logger.warning("Invalid ENTERPRISE_PREVIEW_ENABLED; enterprise preview disabled") + + +def preview_enabled(env: Mapping[str, str] | None = None) -> bool: + raw = (os.environ if env is None else env).get("ENTERPRISE_PREVIEW_ENABLED", "") + flag = raw.strip().lower() if isinstance(raw, str) else "invalid" + if flag in {"", "0", "false", "no", "off"}: + return False + if flag in {"1", "true", "yes", "on"}: + return True + _warn_once() + return False + + +def preview_descriptor(adapters: EnterpriseAdapters) -> dict: + return {"version": 1, "dry_run": True, "activation": False, + "contracts": ["TenantContext", "IdentityAssertion", "QuotaAuthority", "CreditAuthority", "PaymentEvent"], + "authorities": {name: getattr(adapters, name) is not None + for name in ("tenant", "identity", "quota", "credit", "payment")}, + "operations": ["reserve", "commit", "reconcile"], "missing_authority": "denied"} diff --git a/tests/fixtures/secret_firewall_coverage.json b/tests/fixtures/secret_firewall_coverage.json index 37f37f77..374f2a17 100644 --- a/tests/fixtures/secret_firewall_coverage.json +++ b/tests/fixtures/secret_firewall_coverage.json @@ -49,6 +49,9 @@ "app.route('/docs.json')", "app.route('/openapi.json', methods=['GET'])" ], + "routes/enterprise_preview.py": [ + "app.get('/admin/enterprise/preview')" + ], "routes/free_routes.py": [ "app.route('/v1/free//chat/completions', methods=['POST', 'OPTIONS'])", "app.route('/v1/free//models', methods=['GET', 'OPTIONS'])", @@ -255,6 +258,7 @@ "worker/control-users-d1.mjs", "worker/cors-policy.mjs", "worker/d1-schema.mjs", + "worker/enterprise-contract.mjs", "worker/exact-generation-cache.mjs", "worker/fallback-page.mjs", "worker/gateway-extensions.mjs", diff --git a/tests/test_enterprise_contracts.py b/tests/test_enterprise_contracts.py new file mode 100644 index 00000000..a189979d --- /dev/null +++ b/tests/test_enterprise_contracts.py @@ -0,0 +1,237 @@ +"""Immutable enterprise boundaries with synthetic authorities and no live calls.""" +import importlib +import json +import sys +from dataclasses import FrozenInstanceError, replace +from pathlib import Path +from unittest.mock import Mock, patch + +import pytest + +from services import enterprise_contract as ec + + +def vectors(): + text = (Path(__file__).resolve().parents[1] / "docs/enterprise-contracts.md").read_text() + return json.loads(text.split("```json\n", 1)[1].split("```", 1)[0]) + + +@pytest.mark.parametrize("index", range(len(vectors()))) +def test_shared_contract_vectors(index): + vector = vectors()[index] + constructor = getattr(ec, vector["type"]) + data = dict(vector["data"]) + if "context" in data: + data["context"] = ec.TenantContext(**data["context"]) + if vector["valid"]: + value = constructor(**data) + assert value is not None + with pytest.raises(FrozenInstanceError): + value.principal_id = "changed" + else: + with pytest.raises((TypeError, ValueError)): + constructor(**data) + + +def operation(**changes): + data = dict(next(vector["data"] for vector in vectors() if vector["name"] == "operation")) + data["context"] = ec.TenantContext(**data["context"]) + return ec.AuthorityOperation(**{**data, **changes}) + + +def test_legacy_adapter_keeps_single_principal_and_rejects_tenants(): + op = operation() + adapters = ec.register_enterprise_adapters() + assert ec.resolve_tenant(adapters, op) == op.context + with pytest.raises(ec.AuthorityDenied, match="tenant_scope_denied"): + ec.resolve_tenant(adapters, replace(op, context=replace(op.context, org_id="org:one"))) + + +@pytest.mark.parametrize("authority", ["quota", "credit"]) +@pytest.mark.parametrize("action", ["reserve", "commit", "reconcile"]) +def test_missing_authorities_deny(authority, action): + with pytest.raises(ec.AuthorityDenied, match="authority_unavailable"): + ec.call_authority(ec.register_enterprise_adapters(), authority, action, operation()) + + +def test_fake_authority_preserves_scope_revision_and_operation_ids(): + op = operation() + calls = [] + + class Fake: + def reserve(self, value): + calls.append(value) + return ec.AuthorityResult(value.context, value.scoped_id, value.revision + 1, + value.operation_id, True) + commit = reserve + reconcile = reserve + + adapters = ec.register_enterprise_adapters(quota=Fake(), credit=Fake(), tenant=lambda value: value.context) + for authority in ("quota", "credit"): + for action in ("reserve", "commit", "reconcile"): + assert ec.call_authority(adapters, authority, action, op).revision == 8 + assert calls == [op] * 6 + assert ec.resolve_tenant(adapters, op) == op.context + + +@pytest.mark.parametrize("change", [{"revision": 7}, {"operation_id": "other"}, + {"scoped_id": "other"}, {"context": ec.TenantContext("foreign")}, + {"allowed": False}]) +def test_authority_cannot_return_stale_foreign_or_denied_result(change): + op = operation() + result = ec.AuthorityResult(op.context, op.scoped_id, 8, op.operation_id, True) + fake = Mock() + fake.reserve.return_value = replace(result, **change) + with pytest.raises(ec.AuthorityDenied): + ec.call_authority(ec.register_enterprise_adapters(credit=fake), "credit", "reserve", op) + fake.reserve.assert_called_once_with(op) + + +def test_identity_and_payment_require_explicit_verified_boundaries(): + op = operation() + assertion = ec.IdentityAssertion("issuer:one", "subject:one", "audience:one", + "request:one", "nonce:one", 1000, True) + event = ec.PaymentEvent(op.context, op.scoped_id, op.revision, op.operation_id, + "processor:one", "event:one", "credit", "USD", 12, True) + adapters = ec.register_enterprise_adapters() + with pytest.raises(ec.AuthorityDenied): + ec.resolve_identity(adapters, assertion, op) + with pytest.raises(ec.AuthorityDenied): + ec.deliver_payment(adapters, event) + identity = Mock(return_value=op.context) + callback = Mock(return_value=ec.AuthorityResult(op.context, op.scoped_id, 8, op.operation_id, True)) + adapters = ec.register_enterprise_adapters(identity=identity, payment=callback) + assert ec.resolve_identity(adapters, assertion, op) == op.context + assert ec.deliver_payment(adapters, event).revision == 8 + callback.assert_called_once_with(event) + with pytest.raises((TypeError, ValueError)): + ec.deliver_payment(adapters, {"verified": True}) + with pytest.raises(ec.AuthorityDenied): + ec.resolve_identity(ec.register_enterprise_adapters(identity=lambda *_: ec.TenantContext("foreign")), assertion, op) + + +def test_fake_credit_atomic_revision_and_idempotency(): + from concurrent.futures import ThreadPoolExecutor + from threading import Lock + op = operation() + revision, writes, records = op.revision, [], {} + lock = Lock() + + def apply(value): + nonlocal revision + with lock: + if value.operation_id in records: + if records[value.operation_id][0] != value: + raise ec.AuthorityDenied("operation_conflict") + return records[value.operation_id][1] + if value.revision != revision: + raise ec.AuthorityDenied("revision_conflict") + revision += 1 + result = ec.AuthorityResult(value.context, value.scoped_id, revision, value.operation_id, True) + records[value.operation_id] = (value, result) + writes.append(value) + return result + + class Fake: + reserve = staticmethod(apply) + commit = staticmethod(apply) + reconcile = staticmethod(apply) + + adapters = ec.register_enterprise_adapters(credit=Fake(), tenant=None) + with pytest.raises(ec.AuthorityDenied): + ec.resolve_tenant(adapters, op) + with ThreadPoolExecutor(max_workers=2) as pool: + results = list(pool.map(lambda _: ec.call_authority(adapters, "credit", "reserve", op), range(2))) + assert results[0] == results[1] and writes == [op] + with pytest.raises(ec.AuthorityDenied, match="operation_conflict"): + ec.call_authority(adapters, "credit", "reserve", replace(op, amount=13)) + with pytest.raises(ec.AuthorityDenied, match="revision_conflict"): + ec.call_authority(adapters, "credit", "commit", replace(op, operation_id="operation:two")) + next_op = replace(op, revision=8, operation_id="operation:two") + assert ec.call_authority(adapters, "credit", "commit", next_op).revision == 9 + assert writes == [op, next_op] + + +def test_adapter_failure_is_not_retried_or_converted_to_success(): + fake = Mock() + fake.reserve.side_effect = RuntimeError("authority unavailable") + with pytest.raises(RuntimeError, match="authority unavailable"): + ec.call_authority(ec.register_enterprise_adapters(credit=fake), "credit", "reserve", operation()) + fake.reserve.assert_called_once() + with pytest.raises(TypeError): + ec.register_enterprise_adapters(tenant="plugin.module") + + +def test_preview_flag_defaults_and_warns_once_without_value(caplog): + ec._warn_once.cache_clear() + for flag in (None, "", "false", "0", "off", "no"): + assert not ec.preview_enabled({} if flag is None else {"ENTERPRISE_PREVIEW_ENABLED": flag}) + for flag in ("true", "1", "YES", " on "): + assert ec.preview_enabled({"ENTERPRISE_PREVIEW_ENABLED": flag}) + for _ in range(2): + assert not ec.preview_enabled({"ENTERPRISE_PREVIEW_ENABLED": "private-invalid"}) + assert caplog.text.count("Invalid ENTERPRISE_PREVIEW_ENABLED") == 1 + assert "private-invalid" not in caplog.text + + +@pytest.fixture +def registered(monkeypatch, tmp_path): + for key, value in {"FLASK_SECRET_KEY": "synthetic-enterprise-session", "JWT_SECRET": "synthetic-enterprise-jwt", + "ADMIN_API_KEY": "synthetic-enterprise-admin", "ENTERPRISE_PREVIEW_ENABLED": "", + "AUTH_DB_PATH": str(tmp_path / "auth.sqlite3"), "MODEL_REGISTRY_DB_PATH": str(tmp_path / "models.sqlite3"), + "RATE_LIMIT_DB_PATH": str(tmp_path / "limits.sqlite3")}.items(): + monkeypatch.setenv(key, value) + with patch("config.load_runtime_env"), patch("env_loader.load_runtime_env"), \ + patch("services.usage_ledger.start"), patch("requests.Session.send", side_effect=AssertionError("No network")): + module = importlib.import_module("app") + with patch.object(module, "load_runtime_env"): + app = module.create_app() + app.config.update(TESTING=True, WTF_CSRF_ENABLED=False) + auth = module.AuthService + # Other suites re-import the auth and route modules; patch the guards this route calls. + preview = sys.modules[module.register_enterprise_preview_routes.__module__] + for guard in (preview.login_required, preview.require_admin_dashboard_user): + monkeypatch.setitem(guard.__globals__, "AuthService", auth) + with patch.object(auth, "is_authenticated", return_value=True), \ + patch.object(auth, "get_current_user", return_value={"username": "operator", "is_admin": True}): + yield app, app.test_client(), auth + + +def test_registered_preview_disabled_before_auth(registered): + _, client, auth = registered + with patch.object(auth, "is_authenticated", return_value=False), \ + patch.object(auth, "get_current_user", side_effect=AssertionError("Disabled route checked grants")): + assert client.get("/admin/enterprise/preview").status_code == 404 + + +def test_registered_preview_auth_and_zero_mutation(registered, monkeypatch): + app, client, auth = registered + monkeypatch.setenv("ENTERPRISE_PREVIEW_ENABLED", "true") + with patch.object(auth, "is_authenticated", return_value=False): + assert client.get("/admin/enterprise/preview", headers={"Accept": "application/json"}).status_code == 401 + with patch.object(auth, "get_current_user", return_value={"is_admin": False}): + assert client.get("/admin/enterprise/preview").status_code == 403 + authority = Mock(side_effect=AssertionError("Preview called authority")) + app.extensions["enterprise_adapters"] = ec.register_enterprise_adapters(tenant=authority, payment=authority) + response = client.get("/admin/enterprise/preview", headers={"X-Org-ID": "spoofed"}) + assert response.status_code == 200 + assert response.json == ec.preview_descriptor(app.extensions["enterprise_adapters"]) + assert response.json["dry_run"] is True + assert response.headers["Cache-Control"] == "no-store" + authority.assert_not_called() + assert client.post("/admin/enterprise/preview", json={}).status_code == 405 + + +def test_registration_leaves_existing_response_bytes_and_headers_unchanged(monkeypatch): + from flask import Flask, Response + from routes.enterprise_preview import register_enterprise_preview_routes + monkeypatch.setenv("ENTERPRISE_PREVIEW_ENABLED", "") + def baseline(): + app = Flask(__name__) + app.add_url_rule("/existing", view_func=lambda: Response(b"raw bytes", headers={"X-Existing": "same"})) + return app + before = baseline().test_client().get("/existing") + app = baseline() + register_enterprise_preview_routes(app) + after = app.test_client().get("/existing") + assert (after.status_code, after.data, list(after.headers)) == (before.status_code, before.data, list(before.headers)) diff --git a/tests/test_enterprise_contracts_worker.mjs b/tests/test_enterprise_contracts_worker.mjs new file mode 100644 index 00000000..f0696c76 --- /dev/null +++ b/tests/test_enterprise_contracts_worker.mjs @@ -0,0 +1,124 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { readFileSync } from "node:fs"; +import * as ec from "../worker/enterprise-contract.mjs"; + +const vectors = JSON.parse(readFileSync(new URL("../docs/enterprise-contracts.md", import.meta.url), "utf8") + .split("```json\n")[1].split("```")[0]); +for (const vector of vectors) { + test(`shared contract vector: ${vector.name}`, () => { + const data = { ...vector.data }; + if (data.context) data.context = new ec.TenantContext(data.context); + if (!vector.valid) return assert.throws(() => new ec[vector.type](data)); + const value = new ec[vector.type](data); + assert.ok(Object.isFrozen(value)); + assert.throws(() => { value.principal_id = "changed"; }, TypeError); + }); +} + +function operation(changes = {}) { + const data = vectors.find(vector => vector.name === "operation").data; + return new ec.AuthorityOperation({ ...data, context: new ec.TenantContext(data.context), ...changes }); +} +function result(op, changes = {}) { + return new ec.AuthorityResult({ context: op.context, scoped_id: op.scoped_id, revision: 8, + operation_id: op.operation_id, allowed: true, ...changes }); +} + +test("legacy single principal and missing authorities deny tenant and money grants", async () => { + const op = operation(); + const adapters = ec.registerEnterpriseAdapters(); + assert.deepEqual(await ec.resolveTenant(adapters, op), op.context); + await assert.rejects(ec.resolveTenant(adapters, operation({ context: new ec.TenantContext({ principal_id: "principal:one", org_id: "org:one" }) })), /tenant_scope_denied/); + for (const authority of ["quota", "credit"]) for (const action of ["reserve", "commit", "reconcile"]) { + await assert.rejects(ec.callAuthority(adapters, authority, action, op), /authority_unavailable/); + } +}); + +test("fake quota and credit enforce operation and atomic revision boundaries", async () => { + const op = operation(); + const calls = []; + const call = async value => { calls.push(value); return result(value); }; + const fake = Object.freeze({ reserve: call, commit: call, reconcile: call }); + const adapters = ec.registerEnterpriseAdapters({ quota: fake, credit: fake, tenant: value => value.context }); + for (const authority of ["quota", "credit"]) for (const action of ["reserve", "commit", "reconcile"]) { + assert.equal((await ec.callAuthority(adapters, authority, action, op)).revision, 8); + } + assert.deepEqual(calls, Array(6).fill(op)); + for (const change of [{ revision: 7 }, { operation_id: "other" }, { scoped_id: "other" }, + { context: new ec.TenantContext({ principal_id: "foreign" }) }, { allowed: false }]) { + const denied = () => result(op, change); + await assert.rejects(ec.callAuthority(ec.registerEnterpriseAdapters({ credit: { reserve: denied, commit: denied, reconcile: denied } }), "credit", "reserve", op), ec.AuthorityDenied); + } +}); + +test("identity and payment accept only verified immutable scoped inputs", async () => { + const op = operation(); + const assertion = new ec.IdentityAssertion({ issuer_id: "issuer:one", subject_id: "subject:one", audience_id: "audience:one", + request_id: "request:one", nonce_id: "nonce:one", expires_at: 1000, verified: true }); + const event = new ec.PaymentEvent({ context: op.context, scoped_id: op.scoped_id, revision: 7, + idempotency_id: op.operation_id, processor_id: "processor:one", event_id: "event:one", kind: "credit", + currency: "USD", amount: 12, verified: true }); + const empty = ec.registerEnterpriseAdapters(); + await assert.rejects(ec.resolveIdentity(empty, assertion, op), ec.AuthorityDenied); + await assert.rejects(ec.deliverPayment(empty, event), ec.AuthorityDenied); + const calls = []; + const adapters = ec.registerEnterpriseAdapters({ identity: (value, request) => { assert.equal(value, assertion); return request.context; }, + payment: value => { calls.push(value); return result(op); } }); + assert.deepEqual(await ec.resolveIdentity(adapters, assertion, op), op.context); + assert.equal((await ec.deliverPayment(adapters, event)).revision, 8); + assert.deepEqual(calls, [event]); + await assert.rejects(ec.deliverPayment(adapters, { verified: true }), TypeError); + await assert.rejects(ec.resolveIdentity(ec.registerEnterpriseAdapters({ identity: () => new ec.TenantContext({ principal_id: "foreign" }) }), assertion, op), ec.AuthorityDenied); +}); + +test("preview settings and descriptor have no authority side effects", () => { + for (const value of [undefined, "", "false", "0", "off", "no"]) { + assert.equal(ec.previewEnabled({ ENTERPRISE_PREVIEW_ENABLED: value }), false); + } + for (const value of ["true", "1", "YES", " on "]) assert.equal(ec.previewEnabled({ ENTERPRISE_PREVIEW_ENABLED: value }), true); + const warnings = []; + for (let i = 0; i < 2; i++) assert.equal(ec.previewEnabled({ ENTERPRISE_PREVIEW_ENABLED: "private-invalid" }, message => warnings.push(message)), false); + assert.equal(warnings.length, 1); + assert.doesNotMatch(warnings[0], /private-invalid/); + const fail = () => { throw new Error("Descriptor called authority"); }; + const adapters = ec.registerEnterpriseAdapters({ tenant: fail, payment: fail }); + assert.equal(ec.previewDescriptor(adapters).dry_run, true); + assert.ok(Object.isFrozen(adapters)); +}); + +test("fake credit atomic revision and idempotency", async () => { + const op = operation(); + let revision = op.revision; + const records = new Map(), writes = []; + const apply = value => { + if (records.has(value.operation_id)) { + const record = records.get(value.operation_id); + if (JSON.stringify(record.operation) !== JSON.stringify(value)) throw new ec.AuthorityDenied("operation_conflict"); + return record.result; + } + if (value.revision !== revision) throw new ec.AuthorityDenied("revision_conflict"); + const decision = result(value, { revision: ++revision }); + records.set(value.operation_id, { operation: value, result: decision }); + writes.push(value); + return decision; + }; + const adapters = ec.registerEnterpriseAdapters({ tenant: null, credit: { reserve: apply, commit: apply, reconcile: apply } }); + await assert.rejects(ec.resolveTenant(adapters, op), ec.AuthorityDenied); + const results = await Promise.all([ec.callAuthority(adapters, "credit", "reserve", op), ec.callAuthority(adapters, "credit", "reserve", op)]); + assert.deepEqual(results[0], results[1]); + assert.deepEqual(writes, [op]); + await assert.rejects(ec.callAuthority(adapters, "credit", "reserve", operation({ amount: 13 })), /operation_conflict/); + await assert.rejects(ec.callAuthority(adapters, "credit", "commit", operation({ operation_id: "operation:two" })), /revision_conflict/); + const next = operation({ revision: 8, operation_id: "operation:two" }); + assert.equal((await ec.callAuthority(adapters, "credit", "commit", next)).revision, 9); + assert.deepEqual(writes, [op, next]); +}); + +test("adapter failure is not retried or converted to success", async () => { + let calls = 0; + const fail = () => { calls++; throw new Error("authority unavailable"); }; + await assert.rejects(ec.callAuthority(ec.registerEnterpriseAdapters({ credit: { reserve: fail, commit: fail, reconcile: fail } }), "credit", "reserve", operation()), /authority unavailable/); + assert.equal(calls, 1); + assert.throws(() => ec.registerEnterpriseAdapters({ tenant: "plugin.module" }), TypeError); +}); diff --git a/worker/container-env.mjs b/worker/container-env.mjs index a27d53fb..02d0022f 100644 --- a/worker/container-env.mjs +++ b/worker/container-env.mjs @@ -40,6 +40,7 @@ const DIRECT_ENV_KEYS = [ "CONNECTION_PROFILES_DB_PATH", "CONFIG_REVISION_SYNC_ENABLED", "CONFIG_SYNC_TTL_SECONDS", + "ENTERPRISE_PREVIEW_ENABLED", "BANDIT_MODE", "BATCH_SPILLOVER_ENABLED", "CANARY_TRAFFIC_ENABLED", diff --git a/worker/enterprise-contract.mjs b/worker/enterprise-contract.mjs new file mode 100644 index 00000000..8d0a74c5 --- /dev/null +++ b/worker/enterprise-contract.mjs @@ -0,0 +1,185 @@ +/** Explicit immutable authority boundaries; registration grants no permissions. */ +export const MAX_INTEGER = Number.MAX_SAFE_INTEGER; + +function opaque(value) { + if (typeof value !== "string" || value.length < 1 || value.length > 128 || /[^A-Za-z0-9_:.\-]/.test(value)) { + throw new TypeError("Invalid opaque identifier"); + } +} +function integer(value, maximum = MAX_INTEGER - 1) { + if (!Number.isSafeInteger(value) || value < 0 || value > maximum) throw new TypeError("Invalid bounded integer"); +} +function fields(data, required, optional = []) { + if (!data || typeof data !== "object" || Array.isArray(data) || + required.some(name => !(name in data)) || + Object.keys(data).some(name => !required.includes(name) && !optional.includes(name))) { + throw new TypeError("Invalid contract fields"); + } +} +function context(value) { + if (!(value instanceof TenantContext) || !Object.isFrozen(value)) throw new TypeError("TenantContext required"); +} + +export class TenantContext { + constructor(data) { + fields(data, ["principal_id"], ["org_id", "team_id", "grants_revision"]); + const { principal_id, org_id = null, team_id = null, grants_revision = 0 } = data; + opaque(principal_id); + integer(grants_revision); + for (const value of [org_id, team_id]) if (value !== null) opaque(value); + if (team_id !== null && org_id === null) throw new TypeError("Team requires organisation scope"); + Object.assign(this, { principal_id, org_id, team_id, grants_revision }); + Object.freeze(this); + } +} + +export class IdentityAssertion { + constructor(data) { + fields(data, ["issuer_id", "subject_id", "audience_id", "request_id", "nonce_id", "expires_at", "verified"]); + for (const name of ["issuer_id", "subject_id", "audience_id", "request_id", "nonce_id"]) opaque(data[name]); + integer(data.expires_at); + if (data.verified !== true || data.expires_at === 0) throw new TypeError("Verified identity assertion required"); + Object.assign(this, data); + Object.freeze(this); + } +} + +export class AuthorityOperation { + constructor(data) { + fields(data, ["context", "scoped_id", "revision", "operation_id"], ["amount"]); + context(data.context); + opaque(data.scoped_id); + opaque(data.operation_id); + integer(data.revision); + integer(data.amount === undefined ? 0 : data.amount); + Object.assign(this, { ...data, amount: data.amount === undefined ? 0 : data.amount }); + Object.freeze(this); + } +} + +export class AuthorityResult { + constructor(data) { + fields(data, ["context", "scoped_id", "revision", "operation_id", "allowed"]); + context(data.context); + opaque(data.scoped_id); + opaque(data.operation_id); + integer(data.revision, MAX_INTEGER); + if (typeof data.allowed !== "boolean") throw new TypeError("Boolean decision required"); + Object.assign(this, data); + Object.freeze(this); + } +} + +export class PaymentEvent { + constructor(data) { + fields(data, ["context", "scoped_id", "revision", "idempotency_id", "processor_id", "event_id", "kind", "currency", "amount", "verified"]); + new AuthorityOperation({ context: data.context, scoped_id: data.scoped_id, revision: data.revision, + operation_id: data.idempotency_id, amount: data.amount }); + opaque(data.processor_id); + opaque(data.event_id); + if (data.verified !== true || !["credit", "refund", "dispute"].includes(data.kind) || + typeof data.currency !== "string" || data.currency.length !== 3 || /[^A-Z]/.test(data.currency)) { + throw new TypeError("Verified payment event required"); + } + Object.assign(this, data); + Object.freeze(this); + } +} + +/** @typedef {{reserve: function(AuthorityOperation): (AuthorityResult|Promise), + * commit: function(AuthorityOperation): (AuthorityResult|Promise), + * reconcile: function(AuthorityOperation): (AuthorityResult|Promise)}} QuotaAuthority */ +/** @typedef {QuotaAuthority} CreditAuthority */ +/** @typedef {function(AuthorityOperation): (TenantContext|Promise)} TenantAuthority */ +/** @typedef {function(IdentityAssertion, AuthorityOperation): (TenantContext|Promise)} IdentityAuthority */ +/** @typedef {function(PaymentEvent): (AuthorityResult|Promise)} PaymentCallback */ + +export class AuthorityDenied extends Error {} + +export function legacyTenant(operation) { + requireOperation(operation); + if (operation.context.org_id !== null || operation.context.team_id !== null) throw new AuthorityDenied("tenant_scope_denied"); + return operation.context; +} + +/** @param {{tenant?: TenantAuthority|null, identity?: IdentityAuthority|null, + * quota?: QuotaAuthority|null, credit?: CreditAuthority|null, payment?: PaymentCallback|null}} [options] */ +export function registerEnterpriseAdapters(options = {}) { + fields(options, [], ["tenant", "identity", "quota", "credit", "payment"]); + const { tenant = legacyTenant, identity = null, quota = null, credit = null, payment = null } = options; + for (const callback of [tenant, identity, payment]) { + if (callback !== null && typeof callback !== "function") throw new TypeError("Explicit authority function required"); + } + for (const authority of [quota, credit]) { + if (authority !== null && ["reserve", "commit", "reconcile"].some(name => typeof authority[name] !== "function")) { + throw new TypeError("Complete reserve/commit/reconcile authority required"); + } + } + return Object.freeze({ tenant, identity, quota, credit, payment }); +} + +function requireOperation(value) { + if (!(value instanceof AuthorityOperation) || !Object.isFrozen(value)) throw new TypeError("AuthorityOperation required"); +} +function sameContext(left, right) { + return left instanceof TenantContext && Object.isFrozen(left) && + ["principal_id", "org_id", "team_id", "grants_revision"].every(name => left[name] === right[name]); +} +function boundContext(value, operation) { + if (!sameContext(value, operation.context)) throw new AuthorityDenied("authority_scope_mismatch"); + return value; +} +function boundResult(value, operation) { + if (!(value instanceof AuthorityResult) || !Object.isFrozen(value) || !value.allowed || + !sameContext(value.context, operation.context) || value.scoped_id !== operation.scoped_id || + value.operation_id !== operation.operation_id || value.revision !== operation.revision + 1) { + throw new AuthorityDenied("authority_decision_denied"); + } + return value; +} + +export async function resolveTenant(adapters, operation) { + requireOperation(operation); + if (!adapters.tenant) throw new AuthorityDenied("authority_unavailable"); + return boundContext(await adapters.tenant(operation), operation); +} +export async function resolveIdentity(adapters, assertion, operation) { + requireOperation(operation); + if (!(assertion instanceof IdentityAssertion) || !Object.isFrozen(assertion) || assertion.verified !== true) { + throw new TypeError("Verified IdentityAssertion required"); + } + if (!adapters.identity) throw new AuthorityDenied("authority_unavailable"); + return boundContext(await adapters.identity(assertion, operation), operation); +} +export async function callAuthority(adapters, authority, action, operation) { + requireOperation(operation); + if (!["quota", "credit"].includes(authority) || !["reserve", "commit", "reconcile"].includes(action)) { + throw new TypeError("Unknown authority operation"); + } + const target = authority === "quota" ? adapters.quota : adapters.credit; + if (!target) throw new AuthorityDenied("authority_unavailable"); + return boundResult(await target[action](operation), operation); +} +export async function deliverPayment(adapters, event) { + if (!(event instanceof PaymentEvent) || !Object.isFrozen(event) || event.verified !== true) throw new TypeError("Verified PaymentEvent required"); + if (!adapters.payment) throw new AuthorityDenied("authority_unavailable"); + const operation = new AuthorityOperation({ context: event.context, scoped_id: event.scoped_id, + revision: event.revision, operation_id: event.idempotency_id, amount: event.amount }); + return boundResult(await adapters.payment(event), operation); +} + +let warned = false; +export function previewEnabled(env = {}, warn = message => console.warn(message)) { + const raw = env.ENTERPRISE_PREVIEW_ENABLED; + const flag = raw === undefined ? "" : typeof raw === "string" ? raw.trim().toLowerCase() : "invalid"; + if (["", "0", "false", "no", "off"].includes(flag)) return false; + if (["1", "true", "yes", "on"].includes(flag)) return true; + if (!warned) { warned = true; warn("Invalid ENTERPRISE_PREVIEW_ENABLED; enterprise preview disabled"); } + return false; +} +export function previewDescriptor(adapters) { + return { version: 1, dry_run: true, activation: false, + contracts: ["TenantContext", "IdentityAssertion", "QuotaAuthority", "CreditAuthority", "PaymentEvent"], + authorities: Object.fromEntries(["tenant", "identity", "quota", "credit", "payment"].map(name => [name, adapters[name] !== null])), + operations: ["reserve", "commit", "reconcile"], missing_authority: "denied" }; +}