From d3d38272d7898009bf64960bd37ca893092d542d Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Wed, 3 Jun 2026 00:24:12 -0700 Subject: [PATCH] feat(relay): enforce resource limits Co-authored-by: codex --- .../src/features/cloud/linkEnvironment.ts | 4 + apps/web/src/cloud/linkEnvironment.ts | 4 + .../migration.sql | 22 + .../snapshot.json | 1659 +++++++++++++++++ .../agentActivity/AgentActivityPublisher.ts | 1 + .../agentActivity/AgentActivityRows.test.ts | 64 + .../src/agentActivity/AgentActivityRows.ts | 87 +- infra/relay/src/agentActivity/Devices.test.ts | 67 +- infra/relay/src/agentActivity/Devices.ts | 143 +- .../src/agentActivity/MobileRegistrations.ts | 2 + infra/relay/src/auth/RelayTokens.test.ts | 4 + infra/relay/src/auth/RelayTokens.ts | 5 + .../src/entitlements/Entitlements.test.ts | 53 + infra/relay/src/entitlements/Entitlements.ts | 101 + .../environments/EnvironmentConnector.test.ts | 10 + .../environments/EnvironmentLinker.test.ts | 26 +- .../src/environments/EnvironmentLinker.ts | 17 + .../src/environments/EnvironmentLinks.ts | 12 + .../ManagedEndpointAllocations.test.ts | 109 ++ .../ManagedEndpointAllocations.ts | 216 ++- .../ManagedEndpointProvider.test.ts | 81 +- .../environments/ManagedEndpointProvider.ts | 92 +- infra/relay/src/http/Api.ts | 139 +- .../relay/src/maintenance/Maintenance.test.ts | 36 + infra/relay/src/maintenance/Maintenance.ts | 63 + infra/relay/src/persistence/schema.ts | 39 + infra/relay/src/rateLimits/RateLimits.test.ts | 138 ++ infra/relay/src/rateLimits/RateLimits.ts | 88 + infra/relay/src/worker.ts | 68 +- packages/contracts/src/relay.ts | 68 +- 30 files changed, 3252 insertions(+), 166 deletions(-) create mode 100644 infra/relay/migrations/postgres/20260603072155_relay_resource_limits/migration.sql create mode 100644 infra/relay/migrations/postgres/20260603072155_relay_resource_limits/snapshot.json create mode 100644 infra/relay/src/agentActivity/AgentActivityRows.test.ts create mode 100644 infra/relay/src/entitlements/Entitlements.test.ts create mode 100644 infra/relay/src/entitlements/Entitlements.ts create mode 100644 infra/relay/src/environments/ManagedEndpointAllocations.test.ts create mode 100644 infra/relay/src/maintenance/Maintenance.test.ts create mode 100644 infra/relay/src/maintenance/Maintenance.ts create mode 100644 infra/relay/src/rateLimits/RateLimits.test.ts create mode 100644 infra/relay/src/rateLimits/RateLimits.ts diff --git a/apps/mobile/src/features/cloud/linkEnvironment.ts b/apps/mobile/src/features/cloud/linkEnvironment.ts index 61ebad2623..d4fea895cf 100644 --- a/apps/mobile/src/features/cloud/linkEnvironment.ts +++ b/apps/mobile/src/features/cloud/linkEnvironment.ts @@ -147,6 +147,10 @@ function relayProtectedErrorMessage(error: RelayProtectedErrorType): string { return "Relay rejected an expired agent activity publish proof."; case "RelayAgentActivityPublishProofInvalidError": return `Relay rejected the agent activity publish proof (${error.reason}).`; + case "RelayQuotaExceededError": + return `Relay quota exceeded for ${error.resource} (limit ${error.limit}).`; + case "RelayRateLimitedError": + return `Relay rate limit exceeded for ${error.operation}; retry in ${error.retryAfterSeconds} seconds.`; case "RelayInternalError": return `Relay encountered an internal error (${error.reason}, trace ${error.traceId}).`; } diff --git a/apps/web/src/cloud/linkEnvironment.ts b/apps/web/src/cloud/linkEnvironment.ts index f68849e276..134bf54971 100644 --- a/apps/web/src/cloud/linkEnvironment.ts +++ b/apps/web/src/cloud/linkEnvironment.ts @@ -154,6 +154,10 @@ function relayProtectedErrorMessage(error: RelayProtectedErrorType): string { return "Relay rejected an expired agent activity publish proof."; case "RelayAgentActivityPublishProofInvalidError": return `Relay rejected the agent activity publish proof (${error.reason}).`; + case "RelayQuotaExceededError": + return `Relay quota exceeded for ${error.resource} (limit ${error.limit}).`; + case "RelayRateLimitedError": + return `Relay rate limit exceeded for ${error.operation}; retry in ${error.retryAfterSeconds} seconds.`; case "RelayInternalError": return `Relay encountered an internal error (${error.reason}, trace ${error.traceId}).`; } diff --git a/infra/relay/migrations/postgres/20260603072155_relay_resource_limits/migration.sql b/infra/relay/migrations/postgres/20260603072155_relay_resource_limits/migration.sql new file mode 100644 index 0000000000..1941b228e6 --- /dev/null +++ b/infra/relay/migrations/postgres/20260603072155_relay_resource_limits/migration.sql @@ -0,0 +1,22 @@ +CREATE TABLE "relay_user_entitlements" ( + "user_id" varchar(255) PRIMARY KEY, + "managed_endpoint_limit" integer, + "mobile_device_limit" integer, + "rate_limit_tier" varchar(32), + "expires_at" varchar(64), + "reason" text, + "created_at" varchar(64) NOT NULL, + "updated_at" varchar(64) NOT NULL, + CONSTRAINT "chk_relay_user_entitlements_managed_endpoint_limit" CHECK ("managed_endpoint_limit" IS NULL OR "managed_endpoint_limit" >= 0), + CONSTRAINT "chk_relay_user_entitlements_mobile_device_limit" CHECK ("mobile_device_limit" IS NULL OR "mobile_device_limit" >= 0), + CONSTRAINT "chk_relay_user_entitlements_rate_limit_tier" CHECK ("rate_limit_tier" IS NULL OR "rate_limit_tier" IN ('standard', 'trusted', 'blocked')) +); + +--> statement-breakpoint +ALTER TABLE "relay_managed_endpoint_allocations" ADD COLUMN "deprovision_requested_at" varchar(64); +--> statement-breakpoint +ALTER TABLE "relay_managed_endpoint_allocations" ADD COLUMN "last_deprovision_attempt_at" varchar(64); +--> statement-breakpoint +ALTER TABLE "relay_managed_endpoint_allocations" ADD COLUMN "last_deprovision_error" text; +--> statement-breakpoint +CREATE INDEX "idx_relay_managed_endpoint_allocations_cleanup" ON "relay_managed_endpoint_allocations" ("deprovision_requested_at","updated_at"); diff --git a/infra/relay/migrations/postgres/20260603072155_relay_resource_limits/snapshot.json b/infra/relay/migrations/postgres/20260603072155_relay_resource_limits/snapshot.json new file mode 100644 index 0000000000..b9030f54c7 --- /dev/null +++ b/infra/relay/migrations/postgres/20260603072155_relay_resource_limits/snapshot.json @@ -0,0 +1,1659 @@ +{ + "dialect": "postgres", + "id": "c093e404-e665-4e09-b191-dfe7ff5851b6", + "prevIds": ["00000000-0000-0000-0000-000000000000"], + "version": "8", + "ddl": [ + { + "isRlsEnabled": false, + "name": "relay_agent_activity_rows", + "entityType": "tables", + "schema": "public" + }, + { + "isRlsEnabled": false, + "name": "relay_delivery_attempts", + "entityType": "tables", + "schema": "public" + }, + { + "isRlsEnabled": false, + "name": "relay_dpop_proofs", + "entityType": "tables", + "schema": "public" + }, + { + "isRlsEnabled": false, + "name": "relay_environment_credentials", + "entityType": "tables", + "schema": "public" + }, + { + "isRlsEnabled": false, + "name": "relay_environment_links", + "entityType": "tables", + "schema": "public" + }, + { + "isRlsEnabled": false, + "name": "relay_live_activities", + "entityType": "tables", + "schema": "public" + }, + { + "isRlsEnabled": false, + "name": "relay_managed_endpoint_allocations", + "entityType": "tables", + "schema": "public" + }, + { + "isRlsEnabled": false, + "name": "relay_mobile_devices", + "entityType": "tables", + "schema": "public" + }, + { + "isRlsEnabled": false, + "name": "relay_user_entitlements", + "entityType": "tables", + "schema": "public" + }, + { + "type": "varchar(191)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "environment_id", + "entityType": "columns", + "schema": "public", + "table": "relay_agent_activity_rows" + }, + { + "type": "text", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "environment_public_key", + "entityType": "columns", + "schema": "public", + "table": "relay_agent_activity_rows" + }, + { + "type": "varchar(191)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "thread_id", + "entityType": "columns", + "schema": "public", + "table": "relay_agent_activity_rows" + }, + { + "type": "jsonb", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "state_json", + "entityType": "columns", + "schema": "public", + "table": "relay_agent_activity_rows" + }, + { + "type": "varchar(64)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "updated_at", + "entityType": "columns", + "schema": "public", + "table": "relay_agent_activity_rows" + }, + { + "type": "varchar(64)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "created_at", + "entityType": "columns", + "schema": "public", + "table": "relay_agent_activity_rows" + }, + { + "type": "varchar(36)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "id", + "entityType": "columns", + "schema": "public", + "table": "relay_delivery_attempts" + }, + { + "type": "varchar(64)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "created_at", + "entityType": "columns", + "schema": "public", + "table": "relay_delivery_attempts" + }, + { + "type": "varchar(255)", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "user_id", + "entityType": "columns", + "schema": "public", + "table": "relay_delivery_attempts" + }, + { + "type": "varchar(191)", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "environment_id", + "entityType": "columns", + "schema": "public", + "table": "relay_delivery_attempts" + }, + { + "type": "varchar(191)", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "thread_id", + "entityType": "columns", + "schema": "public", + "table": "relay_delivery_attempts" + }, + { + "type": "varchar(255)", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "device_id", + "entityType": "columns", + "schema": "public", + "table": "relay_delivery_attempts" + }, + { + "type": "varchar(64)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "kind", + "entityType": "columns", + "schema": "public", + "table": "relay_delivery_attempts" + }, + { + "type": "varchar(64)", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "source_job_id", + "entityType": "columns", + "schema": "public", + "table": "relay_delivery_attempts" + }, + { + "type": "varchar(16)", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "token_suffix", + "entityType": "columns", + "schema": "public", + "table": "relay_delivery_attempts" + }, + { + "type": "integer", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "apns_status", + "entityType": "columns", + "schema": "public", + "table": "relay_delivery_attempts" + }, + { + "type": "text", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "apns_reason", + "entityType": "columns", + "schema": "public", + "table": "relay_delivery_attempts" + }, + { + "type": "varchar(128)", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "apns_id", + "entityType": "columns", + "schema": "public", + "table": "relay_delivery_attempts" + }, + { + "type": "text", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "transport_error", + "entityType": "columns", + "schema": "public", + "table": "relay_delivery_attempts" + }, + { + "type": "varchar(128)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "thumbprint", + "entityType": "columns", + "schema": "public", + "table": "relay_dpop_proofs" + }, + { + "type": "varchar(255)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "jti", + "entityType": "columns", + "schema": "public", + "table": "relay_dpop_proofs" + }, + { + "type": "integer", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "iat", + "entityType": "columns", + "schema": "public", + "table": "relay_dpop_proofs" + }, + { + "type": "varchar(64)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "expires_at", + "entityType": "columns", + "schema": "public", + "table": "relay_dpop_proofs" + }, + { + "type": "varchar(64)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "created_at", + "entityType": "columns", + "schema": "public", + "table": "relay_dpop_proofs" + }, + { + "type": "varchar(64)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "credential_id", + "entityType": "columns", + "schema": "public", + "table": "relay_environment_credentials" + }, + { + "type": "varchar(191)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "environment_id", + "entityType": "columns", + "schema": "public", + "table": "relay_environment_credentials" + }, + { + "type": "text", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "environment_public_key", + "entityType": "columns", + "schema": "public", + "table": "relay_environment_credentials" + }, + { + "type": "varchar(191)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "credential_hash", + "entityType": "columns", + "schema": "public", + "table": "relay_environment_credentials" + }, + { + "type": "varchar(64)", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "revoked_at", + "entityType": "columns", + "schema": "public", + "table": "relay_environment_credentials" + }, + { + "type": "varchar(64)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "created_at", + "entityType": "columns", + "schema": "public", + "table": "relay_environment_credentials" + }, + { + "type": "varchar(64)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "updated_at", + "entityType": "columns", + "schema": "public", + "table": "relay_environment_credentials" + }, + { + "type": "varchar(191)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "user_id", + "entityType": "columns", + "schema": "public", + "table": "relay_environment_links" + }, + { + "type": "varchar(191)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "environment_id", + "entityType": "columns", + "schema": "public", + "table": "relay_environment_links" + }, + { + "type": "text", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": "'T3 Environment'", + "generated": null, + "identity": null, + "name": "environment_label", + "entityType": "columns", + "schema": "public", + "table": "relay_environment_links" + }, + { + "type": "text", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "environment_public_key", + "entityType": "columns", + "schema": "public", + "table": "relay_environment_links" + }, + { + "type": "text", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "endpoint_http_base_url", + "entityType": "columns", + "schema": "public", + "table": "relay_environment_links" + }, + { + "type": "text", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "endpoint_ws_base_url", + "entityType": "columns", + "schema": "public", + "table": "relay_environment_links" + }, + { + "type": "varchar(32)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "endpoint_provider_kind", + "entityType": "columns", + "schema": "public", + "table": "relay_environment_links" + }, + { + "type": "boolean", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": "true", + "generated": null, + "identity": null, + "name": "notifications_enabled", + "entityType": "columns", + "schema": "public", + "table": "relay_environment_links" + }, + { + "type": "boolean", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": "true", + "generated": null, + "identity": null, + "name": "live_activities_enabled", + "entityType": "columns", + "schema": "public", + "table": "relay_environment_links" + }, + { + "type": "boolean", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": "false", + "generated": null, + "identity": null, + "name": "managed_tunnels_enabled", + "entityType": "columns", + "schema": "public", + "table": "relay_environment_links" + }, + { + "type": "varchar(191)", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "created_by_device_id", + "entityType": "columns", + "schema": "public", + "table": "relay_environment_links" + }, + { + "type": "varchar(64)", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "revoked_at", + "entityType": "columns", + "schema": "public", + "table": "relay_environment_links" + }, + { + "type": "varchar(64)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "created_at", + "entityType": "columns", + "schema": "public", + "table": "relay_environment_links" + }, + { + "type": "varchar(64)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "updated_at", + "entityType": "columns", + "schema": "public", + "table": "relay_environment_links" + }, + { + "type": "varchar(255)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "user_id", + "entityType": "columns", + "schema": "public", + "table": "relay_live_activities" + }, + { + "type": "varchar(255)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "device_id", + "entityType": "columns", + "schema": "public", + "table": "relay_live_activities" + }, + { + "type": "text", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "activity_push_token", + "entityType": "columns", + "schema": "public", + "table": "relay_live_activities" + }, + { + "type": "varchar(64)", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "remote_start_queued_at", + "entityType": "columns", + "schema": "public", + "table": "relay_live_activities" + }, + { + "type": "varchar(64)", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "remote_started_at", + "entityType": "columns", + "schema": "public", + "table": "relay_live_activities" + }, + { + "type": "varchar(64)", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "ended_at", + "entityType": "columns", + "schema": "public", + "table": "relay_live_activities" + }, + { + "type": "jsonb", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "last_aggregate_json", + "entityType": "columns", + "schema": "public", + "table": "relay_live_activities" + }, + { + "type": "varchar(64)", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "last_live_activity_delivery_at", + "entityType": "columns", + "schema": "public", + "table": "relay_live_activities" + }, + { + "type": "varchar(64)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "created_at", + "entityType": "columns", + "schema": "public", + "table": "relay_live_activities" + }, + { + "type": "varchar(64)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "updated_at", + "entityType": "columns", + "schema": "public", + "table": "relay_live_activities" + }, + { + "type": "varchar(191)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "user_id", + "entityType": "columns", + "schema": "public", + "table": "relay_managed_endpoint_allocations" + }, + { + "type": "varchar(191)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "environment_id", + "entityType": "columns", + "schema": "public", + "table": "relay_managed_endpoint_allocations" + }, + { + "type": "text", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "hostname", + "entityType": "columns", + "schema": "public", + "table": "relay_managed_endpoint_allocations" + }, + { + "type": "varchar(191)", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "tunnel_id", + "entityType": "columns", + "schema": "public", + "table": "relay_managed_endpoint_allocations" + }, + { + "type": "text", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "tunnel_name", + "entityType": "columns", + "schema": "public", + "table": "relay_managed_endpoint_allocations" + }, + { + "type": "varchar(191)", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "dns_record_id", + "entityType": "columns", + "schema": "public", + "table": "relay_managed_endpoint_allocations" + }, + { + "type": "varchar(64)", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "ready_at", + "entityType": "columns", + "schema": "public", + "table": "relay_managed_endpoint_allocations" + }, + { + "type": "varchar(64)", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "deprovision_requested_at", + "entityType": "columns", + "schema": "public", + "table": "relay_managed_endpoint_allocations" + }, + { + "type": "varchar(64)", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "last_deprovision_attempt_at", + "entityType": "columns", + "schema": "public", + "table": "relay_managed_endpoint_allocations" + }, + { + "type": "text", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "last_deprovision_error", + "entityType": "columns", + "schema": "public", + "table": "relay_managed_endpoint_allocations" + }, + { + "type": "varchar(64)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "created_at", + "entityType": "columns", + "schema": "public", + "table": "relay_managed_endpoint_allocations" + }, + { + "type": "varchar(64)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "updated_at", + "entityType": "columns", + "schema": "public", + "table": "relay_managed_endpoint_allocations" + }, + { + "type": "varchar(255)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "user_id", + "entityType": "columns", + "schema": "public", + "table": "relay_mobile_devices" + }, + { + "type": "varchar(255)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "device_id", + "entityType": "columns", + "schema": "public", + "table": "relay_mobile_devices" + }, + { + "type": "text", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": "'iOS device'", + "generated": null, + "identity": null, + "name": "label", + "entityType": "columns", + "schema": "public", + "table": "relay_mobile_devices" + }, + { + "type": "varchar(16)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "platform", + "entityType": "columns", + "schema": "public", + "table": "relay_mobile_devices" + }, + { + "type": "integer", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "ios_major_version", + "entityType": "columns", + "schema": "public", + "table": "relay_mobile_devices" + }, + { + "type": "varchar(64)", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "app_version", + "entityType": "columns", + "schema": "public", + "table": "relay_mobile_devices" + }, + { + "type": "text", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "push_token", + "entityType": "columns", + "schema": "public", + "table": "relay_mobile_devices" + }, + { + "type": "text", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "push_to_start_token", + "entityType": "columns", + "schema": "public", + "table": "relay_mobile_devices" + }, + { + "type": "jsonb", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "preferences_json", + "entityType": "columns", + "schema": "public", + "table": "relay_mobile_devices" + }, + { + "type": "varchar(64)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "created_at", + "entityType": "columns", + "schema": "public", + "table": "relay_mobile_devices" + }, + { + "type": "varchar(64)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "updated_at", + "entityType": "columns", + "schema": "public", + "table": "relay_mobile_devices" + }, + { + "type": "varchar(255)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "user_id", + "entityType": "columns", + "schema": "public", + "table": "relay_user_entitlements" + }, + { + "type": "integer", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "managed_endpoint_limit", + "entityType": "columns", + "schema": "public", + "table": "relay_user_entitlements" + }, + { + "type": "integer", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "mobile_device_limit", + "entityType": "columns", + "schema": "public", + "table": "relay_user_entitlements" + }, + { + "type": "varchar(32)", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "rate_limit_tier", + "entityType": "columns", + "schema": "public", + "table": "relay_user_entitlements" + }, + { + "type": "varchar(64)", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "expires_at", + "entityType": "columns", + "schema": "public", + "table": "relay_user_entitlements" + }, + { + "type": "text", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "reason", + "entityType": "columns", + "schema": "public", + "table": "relay_user_entitlements" + }, + { + "type": "varchar(64)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "created_at", + "entityType": "columns", + "schema": "public", + "table": "relay_user_entitlements" + }, + { + "type": "varchar(64)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "updated_at", + "entityType": "columns", + "schema": "public", + "table": "relay_user_entitlements" + }, + { + "nameExplicit": true, + "columns": [ + { + "value": "updated_at", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + } + ], + "isUnique": false, + "where": null, + "with": "", + "method": "btree", + "concurrently": false, + "name": "idx_relay_agent_activity_rows_updated", + "entityType": "indexes", + "schema": "public", + "table": "relay_agent_activity_rows" + }, + { + "nameExplicit": true, + "columns": [ + { + "value": "environment_id", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + }, + { + "value": "thread_id", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + }, + { + "value": "created_at", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + } + ], + "isUnique": false, + "where": null, + "with": "", + "method": "btree", + "concurrently": false, + "name": "idx_relay_delivery_attempts_environment", + "entityType": "indexes", + "schema": "public", + "table": "relay_delivery_attempts" + }, + { + "nameExplicit": true, + "columns": [ + { + "value": "source_job_id", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + } + ], + "isUnique": true, + "where": null, + "with": "", + "method": "btree", + "concurrently": false, + "name": "idx_relay_delivery_attempts_source_job", + "entityType": "indexes", + "schema": "public", + "table": "relay_delivery_attempts" + }, + { + "nameExplicit": true, + "columns": [ + { + "value": "expires_at", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + } + ], + "isUnique": false, + "where": null, + "with": "", + "method": "btree", + "concurrently": false, + "name": "idx_relay_dpop_proofs_expires_at", + "entityType": "indexes", + "schema": "public", + "table": "relay_dpop_proofs" + }, + { + "nameExplicit": true, + "columns": [ + { + "value": "credential_hash", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + } + ], + "isUnique": true, + "where": null, + "with": "", + "method": "btree", + "concurrently": false, + "name": "idx_relay_environment_credentials_hash", + "entityType": "indexes", + "schema": "public", + "table": "relay_environment_credentials" + }, + { + "nameExplicit": true, + "columns": [ + { + "value": "environment_id", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + }, + { + "value": "revoked_at", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + } + ], + "isUnique": false, + "where": null, + "with": "", + "method": "btree", + "concurrently": false, + "name": "idx_relay_environment_credentials_environment", + "entityType": "indexes", + "schema": "public", + "table": "relay_environment_credentials" + }, + { + "nameExplicit": true, + "columns": [ + { + "value": "environment_id", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + }, + { + "value": "environment_public_key", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + }, + { + "value": "revoked_at", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + } + ], + "isUnique": false, + "where": null, + "with": "", + "method": "btree", + "concurrently": false, + "name": "idx_relay_environment_credentials_environment_key", + "entityType": "indexes", + "schema": "public", + "table": "relay_environment_credentials" + }, + { + "nameExplicit": true, + "columns": [ + { + "value": "environment_id", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + }, + { + "value": "revoked_at", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + } + ], + "isUnique": false, + "where": null, + "with": "", + "method": "btree", + "concurrently": false, + "name": "idx_relay_environment_links_environment", + "entityType": "indexes", + "schema": "public", + "table": "relay_environment_links" + }, + { + "nameExplicit": true, + "columns": [ + { + "value": "user_id", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + } + ], + "isUnique": false, + "where": null, + "with": "", + "method": "btree", + "concurrently": false, + "name": "idx_relay_live_activities_user", + "entityType": "indexes", + "schema": "public", + "table": "relay_live_activities" + }, + { + "nameExplicit": true, + "columns": [ + { + "value": "activity_push_token", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + } + ], + "isUnique": true, + "where": null, + "with": "", + "method": "btree", + "concurrently": false, + "name": "idx_relay_live_activities_activity_push_token", + "entityType": "indexes", + "schema": "public", + "table": "relay_live_activities" + }, + { + "nameExplicit": true, + "columns": [ + { + "value": "hostname", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + } + ], + "isUnique": true, + "where": null, + "with": "", + "method": "btree", + "concurrently": false, + "name": "idx_relay_managed_endpoint_allocations_hostname", + "entityType": "indexes", + "schema": "public", + "table": "relay_managed_endpoint_allocations" + }, + { + "nameExplicit": true, + "columns": [ + { + "value": "tunnel_name", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + } + ], + "isUnique": true, + "where": null, + "with": "", + "method": "btree", + "concurrently": false, + "name": "idx_relay_managed_endpoint_allocations_tunnel_name", + "entityType": "indexes", + "schema": "public", + "table": "relay_managed_endpoint_allocations" + }, + { + "nameExplicit": true, + "columns": [ + { + "value": "deprovision_requested_at", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + }, + { + "value": "updated_at", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + } + ], + "isUnique": false, + "where": null, + "with": "", + "method": "btree", + "concurrently": false, + "name": "idx_relay_managed_endpoint_allocations_cleanup", + "entityType": "indexes", + "schema": "public", + "table": "relay_managed_endpoint_allocations" + }, + { + "nameExplicit": true, + "columns": [ + { + "value": "user_id", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + } + ], + "isUnique": false, + "where": null, + "with": "", + "method": "btree", + "concurrently": false, + "name": "idx_relay_mobile_devices_user", + "entityType": "indexes", + "schema": "public", + "table": "relay_mobile_devices" + }, + { + "nameExplicit": true, + "columns": [ + { + "value": "push_token", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + } + ], + "isUnique": true, + "where": null, + "with": "", + "method": "btree", + "concurrently": false, + "name": "idx_relay_mobile_devices_push_token", + "entityType": "indexes", + "schema": "public", + "table": "relay_mobile_devices" + }, + { + "nameExplicit": true, + "columns": [ + { + "value": "push_to_start_token", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + } + ], + "isUnique": true, + "where": null, + "with": "", + "method": "btree", + "concurrently": false, + "name": "idx_relay_mobile_devices_push_to_start_token", + "entityType": "indexes", + "schema": "public", + "table": "relay_mobile_devices" + }, + { + "columns": ["environment_id", "environment_public_key", "thread_id"], + "nameExplicit": false, + "name": "relay_agent_activity_rows_pkey", + "entityType": "pks", + "schema": "public", + "table": "relay_agent_activity_rows" + }, + { + "columns": ["thumbprint", "jti"], + "nameExplicit": false, + "name": "relay_dpop_proofs_pkey", + "entityType": "pks", + "schema": "public", + "table": "relay_dpop_proofs" + }, + { + "columns": ["user_id", "environment_id"], + "nameExplicit": false, + "name": "relay_environment_links_pkey", + "entityType": "pks", + "schema": "public", + "table": "relay_environment_links" + }, + { + "columns": ["user_id", "device_id"], + "nameExplicit": false, + "name": "relay_live_activities_pkey", + "entityType": "pks", + "schema": "public", + "table": "relay_live_activities" + }, + { + "columns": ["user_id", "environment_id"], + "nameExplicit": false, + "name": "relay_managed_endpoint_allocations_pkey", + "entityType": "pks", + "schema": "public", + "table": "relay_managed_endpoint_allocations" + }, + { + "columns": ["user_id", "device_id"], + "nameExplicit": false, + "name": "relay_mobile_devices_pkey", + "entityType": "pks", + "schema": "public", + "table": "relay_mobile_devices" + }, + { + "columns": ["id"], + "nameExplicit": false, + "name": "relay_delivery_attempts_pkey", + "schema": "public", + "table": "relay_delivery_attempts", + "entityType": "pks" + }, + { + "columns": ["credential_id"], + "nameExplicit": false, + "name": "relay_environment_credentials_pkey", + "schema": "public", + "table": "relay_environment_credentials", + "entityType": "pks" + }, + { + "columns": ["user_id"], + "nameExplicit": false, + "name": "relay_user_entitlements_pkey", + "schema": "public", + "table": "relay_user_entitlements", + "entityType": "pks" + }, + { + "value": "\"managed_endpoint_limit\" IS NULL OR \"managed_endpoint_limit\" >= 0", + "name": "chk_relay_user_entitlements_managed_endpoint_limit", + "entityType": "checks", + "schema": "public", + "table": "relay_user_entitlements" + }, + { + "value": "\"mobile_device_limit\" IS NULL OR \"mobile_device_limit\" >= 0", + "name": "chk_relay_user_entitlements_mobile_device_limit", + "entityType": "checks", + "schema": "public", + "table": "relay_user_entitlements" + }, + { + "value": "\"rate_limit_tier\" IS NULL OR \"rate_limit_tier\" IN ('standard', 'trusted', 'blocked')", + "name": "chk_relay_user_entitlements_rate_limit_tier", + "entityType": "checks", + "schema": "public", + "table": "relay_user_entitlements" + } + ], + "renames": [] +} diff --git a/infra/relay/src/agentActivity/AgentActivityPublisher.ts b/infra/relay/src/agentActivity/AgentActivityPublisher.ts index 3881bc6c1a..97369dcdfc 100644 --- a/infra/relay/src/agentActivity/AgentActivityPublisher.ts +++ b/infra/relay/src/agentActivity/AgentActivityPublisher.ts @@ -17,6 +17,7 @@ import * as ApnsDeliveries from "./ApnsDeliveries.ts"; export type AgentActivityPublishError = | AgentActivityRows.AgentActivityRowUpsertPersistenceError + | AgentActivityRows.AgentActivityRowQuotaExceeded | AgentActivityRows.AgentActivityRowDeletePersistenceError | AgentActivityRows.AgentActivityRowListPersistenceError | EnvironmentLinks.EnvironmentLinkUserListPersistenceError diff --git a/infra/relay/src/agentActivity/AgentActivityRows.test.ts b/infra/relay/src/agentActivity/AgentActivityRows.test.ts new file mode 100644 index 0000000000..eb519756c7 --- /dev/null +++ b/infra/relay/src/agentActivity/AgentActivityRows.test.ts @@ -0,0 +1,64 @@ +import type { RelayAgentActivityState } from "@t3tools/contracts/relay"; +import { describe, expect, it } from "@effect/vitest"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; + +import { RelayDb, type RelayDatabase } from "../db.ts"; +import * as AgentActivityRows from "./AgentActivityRows.ts"; + +const state: RelayAgentActivityState = { + environmentId: "env-1" as RelayAgentActivityState["environmentId"], + threadId: "thread-51" as RelayAgentActivityState["threadId"], + projectTitle: "Project", + threadTitle: "Thread", + phase: "running", + headline: "Running", + modelTitle: "gpt-5", + updatedAt: "2026-06-03T00:00:00.000Z", + deepLink: "/threads/env-1/thread-51", +}; + +describe("AgentActivityRows", () => { + it.effect("rejects a new active thread after the per-environment cap", () => { + let selectCount = 0; + const sqlClient = Object.assign(() => Effect.void, { + withTransaction: (effect: Effect.Effect) => effect, + }); + const fakeDb = { + $client: sqlClient, + select: () => { + selectCount++; + return { + from: () => ({ + where: () => + selectCount === 1 + ? { limit: () => Effect.succeed([]) } + : Effect.succeed([{ value: 50 }]), + }), + }; + }, + insert: () => { + throw new Error("activity insert should not run"); + }, + } as unknown as RelayDatabase; + + return Effect.gen(function* () { + const rows = yield* AgentActivityRows.AgentActivityRows; + const error = yield* Effect.flip( + rows.upsert({ + environmentPublicKey: "environment-public-key", + state, + }), + ); + + expect(error).toEqual( + new AgentActivityRows.AgentActivityRowQuotaExceeded({ + resource: "active_agent_threads", + limit: 50, + }), + ); + }).pipe( + Effect.provide(AgentActivityRows.layer.pipe(Layer.provide(Layer.succeed(RelayDb, fakeDb)))), + ); + }); +}); diff --git a/infra/relay/src/agentActivity/AgentActivityRows.ts b/infra/relay/src/agentActivity/AgentActivityRows.ts index 00d3f5f780..9562810b66 100644 --- a/infra/relay/src/agentActivity/AgentActivityRows.ts +++ b/infra/relay/src/agentActivity/AgentActivityRows.ts @@ -8,7 +8,7 @@ import { cast } from "effect/Function"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; import * as Schema from "effect/Schema"; -import { and, desc, eq, isNull } from "drizzle-orm"; +import { and, count, desc, eq, isNull } from "drizzle-orm"; import { RelayDb } from "../db.ts"; import { relayAgentActivityRows, relayEnvironmentLinks } from "../persistence/schema.ts"; @@ -31,11 +31,20 @@ export class AgentActivityRowListPersistenceError extends Data.TaggedError( readonly cause: unknown; }> {} +export class AgentActivityRowQuotaExceeded extends Data.TaggedError( + "AgentActivityRowQuotaExceeded", +)<{ + readonly resource: "active_agent_threads"; + readonly limit: number; +}> {} + +const MAX_ACTIVE_AGENT_THREADS_PER_ENVIRONMENT = 50; + export interface AgentActivityRowsShape { readonly upsert: (input: { readonly environmentPublicKey: string; readonly state: RelayAgentActivityState; - }) => Effect.Effect; + }) => Effect.Effect; readonly remove: (input: { readonly environmentId: string; readonly environmentPublicKey: string; @@ -76,29 +85,59 @@ const make = Effect.gen(function* () { Effect.flatMap(decodeJsonString), Effect.map(cast), ); - yield* db - .insert(relayAgentActivityRows) - .values({ - environmentId: input.state.environmentId, - environmentPublicKey: input.environmentPublicKey, - threadId: input.state.threadId, - stateJson, - updatedAt: input.state.updatedAt, - createdAt: DateTime.formatIso(now), - }) - .onConflictDoUpdate({ - target: [ - relayAgentActivityRows.environmentId, - relayAgentActivityRows.environmentPublicKey, - relayAgentActivityRows.threadId, - ], - set: { - stateJson, - updatedAt: input.state.updatedAt, - }, - }); + yield* db.$client.withTransaction( + Effect.gen(function* () { + yield* db.$client`SELECT pg_advisory_xact_lock(hashtextextended(${`${input.state.environmentId}:${input.environmentPublicKey}`}, 1))`; + const keyCondition = and( + eq(relayAgentActivityRows.environmentId, input.state.environmentId), + eq(relayAgentActivityRows.environmentPublicKey, input.environmentPublicKey), + ); + const existing = yield* db + .select({ threadId: relayAgentActivityRows.threadId }) + .from(relayAgentActivityRows) + .where(and(keyCondition, eq(relayAgentActivityRows.threadId, input.state.threadId))) + .limit(1); + if (existing.length === 0) { + const rows = yield* db + .select({ value: count() }) + .from(relayAgentActivityRows) + .where(keyCondition); + if ((rows[0]?.value ?? 0) >= MAX_ACTIVE_AGENT_THREADS_PER_ENVIRONMENT) { + return yield* new AgentActivityRowQuotaExceeded({ + resource: "active_agent_threads", + limit: MAX_ACTIVE_AGENT_THREADS_PER_ENVIRONMENT, + }); + } + } + yield* db + .insert(relayAgentActivityRows) + .values({ + environmentId: input.state.environmentId, + environmentPublicKey: input.environmentPublicKey, + threadId: input.state.threadId, + stateJson, + updatedAt: input.state.updatedAt, + createdAt: DateTime.formatIso(now), + }) + .onConflictDoUpdate({ + target: [ + relayAgentActivityRows.environmentId, + relayAgentActivityRows.environmentPublicKey, + relayAgentActivityRows.threadId, + ], + set: { + stateJson, + updatedAt: input.state.updatedAt, + }, + }); + }), + ); }, - Effect.mapError((cause) => new AgentActivityRowUpsertPersistenceError({ cause })), + Effect.mapError((cause) => + cause instanceof AgentActivityRowQuotaExceeded + ? cause + : new AgentActivityRowUpsertPersistenceError({ cause }), + ), ), remove: Effect.fn("relay.agent_activity_rows.remove")(function* (input) { diff --git a/infra/relay/src/agentActivity/Devices.test.ts b/infra/relay/src/agentActivity/Devices.test.ts index 7a3b227703..fd38bd957e 100644 --- a/infra/relay/src/agentActivity/Devices.test.ts +++ b/infra/relay/src/agentActivity/Devices.test.ts @@ -8,6 +8,7 @@ import * as Layer from "effect/Layer"; import { RelayDb, type RelayDatabase } from "../db.ts"; import { relayLiveActivities, relayMobileDevices } from "../persistence/schema.ts"; import * as Devices from "./Devices.ts"; +import * as Entitlements from "../entitlements/Entitlements.ts"; const registration: RelayDeviceRegistrationRequest = { deviceId: "device-1" as RelayDeviceRegistrationRequest["deviceId"], @@ -27,7 +28,60 @@ const registration: RelayDeviceRegistrationRequest = { }, }; +const entitlements = Entitlements.Entitlements.of({ + getEffectiveForUser: () => + Effect.succeed({ + managedEndpointLimit: 3, + mobileDeviceLimit: 5, + rateLimitTier: "standard", + }), + withUserLock: (_userId, effect) => effect, +}); + +function devicesLayer(fakeDb: RelayDatabase) { + return Devices.layer.pipe( + Layer.provide( + Layer.mergeAll( + Layer.succeed(RelayDb, fakeDb), + Layer.succeed(Entitlements.Entitlements, entitlements), + ), + ), + ); +} + describe("Devices", () => { + it.effect("rejects a new device when the user is at the configured cap", () => { + let selectCount = 0; + const fakeDb = { + select: () => { + selectCount++; + return { + from: () => ({ + where: () => + selectCount === 1 + ? { limit: () => Effect.succeed([]) } + : Effect.succeed([{ value: 5 }]), + }), + }; + }, + insert: () => { + throw new Error("device insert should not run"); + }, + } as unknown as RelayDatabase; + + return Effect.gen(function* () { + const devices = yield* Devices.Devices; + const error = yield* Effect.flip(devices.register({ userId: "user-2", registration })); + + expect(error).toEqual( + new Entitlements.UserResourceQuotaExceeded({ + resource: "mobile_devices", + limit: 5, + }), + ); + }).pipe(Effect.provide(devicesLayer(fakeDb))); + }); + it.effect("claims APNs tokens globally before upserting the current user device", () => { const calls: Array = []; const updateSets: Array> = []; @@ -36,6 +90,13 @@ describe("Devices", () => { const dialect = new PgDialect(); const fakeDb = { + select: () => ({ + from: () => ({ + where: () => ({ + limit: () => Effect.succeed([{ deviceId: "device-1" }]), + }), + }), + }), update: (table: unknown) => { expect(table).toBe(relayMobileDevices); calls.push("update"); @@ -110,7 +171,7 @@ describe("Devices", () => { pushToStartToken: "push-to-start-token", }), ]); - }).pipe(Effect.provide(Devices.layer.pipe(Layer.provide(Layer.succeed(RelayDb, fakeDb))))); + }).pipe(Effect.provide(devicesLayer(fakeDb))); }); it.effect("unregisters APNs state only for the current user device", () => { @@ -156,7 +217,7 @@ describe("Devices", () => { params: ["user-2", "device-1"], }, ]); - }).pipe(Effect.provide(Devices.layer.pipe(Layer.provide(Layer.succeed(RelayDb, fakeDb))))); + }).pipe(Effect.provide(devicesLayer(fakeDb))); }); it.effect("lists safe notification state without exposing APNs tokens", () => { @@ -215,6 +276,6 @@ describe("Devices", () => { updatedAt: "2026-06-01T00:00:00.000Z", }, ]); - }).pipe(Effect.provide(Devices.layer.pipe(Layer.provide(Layer.succeed(RelayDb, fakeDb))))); + }).pipe(Effect.provide(devicesLayer(fakeDb))); }); }); diff --git a/infra/relay/src/agentActivity/Devices.ts b/infra/relay/src/agentActivity/Devices.ts index 417dba80dd..ea11a4037d 100644 --- a/infra/relay/src/agentActivity/Devices.ts +++ b/infra/relay/src/agentActivity/Devices.ts @@ -7,10 +7,11 @@ import * as Data from "effect/Data"; import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; -import { and, eq } from "drizzle-orm"; +import { and, count, eq } from "drizzle-orm"; import { sql } from "drizzle-orm"; import { RelayDb } from "../db.ts"; +import * as Entitlements from "../entitlements/Entitlements.ts"; import { relayLiveActivities, relayMobileDevices } from "../persistence/schema.ts"; export class DeviceRegistrationPersistenceError extends Data.TaggedError( @@ -33,7 +34,10 @@ export interface DevicesShape { readonly register: (input: { readonly userId: string; readonly registration: RelayDeviceRegistrationRequest; - }) => Effect.Effect; + }) => Effect.Effect< + void, + DeviceRegistrationPersistenceError | Entitlements.UserResourceQuotaExceeded + >; readonly unregister: (input: { readonly userId: string; readonly deviceId: string; @@ -49,6 +53,7 @@ export class Devices extends Context.Service()( const make = Effect.gen(function* () { const db = yield* RelayDb; + const entitlements = yield* Entitlements.Entitlements; return Devices.of({ register: Effect.fn("relay.devices.register")( @@ -56,60 +61,92 @@ const make = Effect.gen(function* () { yield* Effect.annotateCurrentSpan({ "relay.mobile.device_id": input.registration.deviceId, }); - const updatedAt = DateTime.formatIso(yield* DateTime.now); - const registration = input.registration; + yield* entitlements.withUserLock( + input.userId, + Effect.gen(function* () { + const updatedAt = DateTime.formatIso(yield* DateTime.now); + const registration = input.registration; + const existing = yield* db + .select({ deviceId: relayMobileDevices.deviceId }) + .from(relayMobileDevices) + .where( + and( + eq(relayMobileDevices.userId, input.userId), + eq(relayMobileDevices.deviceId, registration.deviceId), + ), + ) + .limit(1); + if (existing.length === 0) { + const effective = yield* entitlements.getEffectiveForUser(input.userId); + const deviceCounts = yield* db + .select({ value: count() }) + .from(relayMobileDevices) + .where(eq(relayMobileDevices.userId, input.userId)); + if ((deviceCounts[0]?.value ?? 0) >= effective.mobileDeviceLimit) { + return yield* new Entitlements.UserResourceQuotaExceeded({ + resource: "mobile_devices", + limit: effective.mobileDeviceLimit, + }); + } + } - yield* Effect.all( - [ - registration.pushToken - ? db - .update(relayMobileDevices) - .set({ pushToken: null, updatedAt }) - .where(eq(relayMobileDevices.pushToken, registration.pushToken)) - : Effect.void, - registration.pushToStartToken - ? db - .update(relayMobileDevices) - .set({ pushToStartToken: null, updatedAt }) - .where(eq(relayMobileDevices.pushToStartToken, registration.pushToStartToken)) - : Effect.void, - ], - { concurrency: 2, discard: true }, + yield* Effect.all( + [ + registration.pushToken + ? db + .update(relayMobileDevices) + .set({ pushToken: null, updatedAt }) + .where(eq(relayMobileDevices.pushToken, registration.pushToken)) + : Effect.void, + registration.pushToStartToken + ? db + .update(relayMobileDevices) + .set({ pushToStartToken: null, updatedAt }) + .where(eq(relayMobileDevices.pushToStartToken, registration.pushToStartToken)) + : Effect.void, + ], + { concurrency: 2, discard: true }, + ); + + yield* db + .insert(relayMobileDevices) + .values({ + userId: input.userId, + deviceId: registration.deviceId, + label: registration.label, + platform: registration.platform, + iosMajorVersion: registration.iosMajorVersion, + appVersion: registration.appVersion ?? null, + pushToken: registration.pushToken ?? null, + pushToStartToken: registration.pushToStartToken ?? null, + preferencesJson: registration.preferences, + createdAt: updatedAt, + updatedAt, + }) + .onConflictDoUpdate({ + target: [relayMobileDevices.userId, relayMobileDevices.deviceId], + set: { + platform: registration.platform, + label: registration.label, + iosMajorVersion: registration.iosMajorVersion, + appVersion: registration.appVersion ?? null, + pushToken: sql`coalesce(excluded.push_token, ${relayMobileDevices.pushToken})`, + pushToStartToken: sql`coalesce( + excluded.push_to_start_token, + ${relayMobileDevices.pushToStartToken} + )`, + preferencesJson: registration.preferences, + updatedAt, + }, + }); + }), ); - - yield* db - .insert(relayMobileDevices) - .values({ - userId: input.userId, - deviceId: registration.deviceId, - label: registration.label, - platform: registration.platform, - iosMajorVersion: registration.iosMajorVersion, - appVersion: registration.appVersion ?? null, - pushToken: registration.pushToken ?? null, - pushToStartToken: registration.pushToStartToken ?? null, - preferencesJson: registration.preferences, - createdAt: updatedAt, - updatedAt, - }) - .onConflictDoUpdate({ - target: [relayMobileDevices.userId, relayMobileDevices.deviceId], - set: { - platform: registration.platform, - label: registration.label, - iosMajorVersion: registration.iosMajorVersion, - appVersion: registration.appVersion ?? null, - pushToken: sql`coalesce(excluded.push_token, ${relayMobileDevices.pushToken})`, - pushToStartToken: sql`coalesce( - excluded.push_to_start_token, - ${relayMobileDevices.pushToStartToken} - )`, - preferencesJson: registration.preferences, - updatedAt, - }, - }); }, - Effect.mapError((cause) => new DeviceRegistrationPersistenceError({ cause })), + Effect.mapError((cause) => + cause instanceof Entitlements.UserResourceQuotaExceeded + ? cause + : new DeviceRegistrationPersistenceError({ cause }), + ), ), unregister: Effect.fn("relay.devices.unregister")( function* (input) { diff --git a/infra/relay/src/agentActivity/MobileRegistrations.ts b/infra/relay/src/agentActivity/MobileRegistrations.ts index d9c013232a..a2fb185570 100644 --- a/infra/relay/src/agentActivity/MobileRegistrations.ts +++ b/infra/relay/src/agentActivity/MobileRegistrations.ts @@ -9,10 +9,12 @@ import * as Layer from "effect/Layer"; import * as Devices from "./Devices.ts"; import * as LiveActivities from "./LiveActivities.ts"; import * as AgentActivityPublisher from "./AgentActivityPublisher.ts"; +import * as Entitlements from "../entitlements/Entitlements.ts"; export type MobileRegistrationError = | Devices.DeviceRegistrationPersistenceError | Devices.DeviceUnregistrationPersistenceError + | Entitlements.UserResourceQuotaExceeded | LiveActivities.LiveActivityRegistrationPersistenceError; export interface MobileRegistrationsShape { diff --git a/infra/relay/src/auth/RelayTokens.test.ts b/infra/relay/src/auth/RelayTokens.test.ts index 171981834c..db289577c9 100644 --- a/infra/relay/src/auth/RelayTokens.test.ts +++ b/infra/relay/src/auth/RelayTokens.test.ts @@ -91,6 +91,7 @@ describe("RelayTokens", () => { expiresAtEpochSeconds: 200, clientId: "t3-mobile", scopes: ["environment:connect", "environment:status", "mobile:registration"], + rateLimitTier: "standard", }); expect( @@ -100,6 +101,7 @@ describe("RelayTokens", () => { cnf: { jkt: "proof-key-thumbprint" }, client_id: "t3-mobile", scope: ["environment:connect", "environment:status", "mobile:registration"], + rate_limit_tier: "standard", }); expect(yield* relayTokens.verifyDpopAccessToken({ token, nowEpochSeconds: 261 })).toBeNull(); }).pipe(Effect.provide(layer)), @@ -116,6 +118,7 @@ describe("RelayTokens", () => { expiresAtEpochSeconds: 200, clientId: "t3-web", scopes: ["environment:connect", "environment:status"], + rateLimitTier: "trusted", }); expect( @@ -124,6 +127,7 @@ describe("RelayTokens", () => { client_id: "t3-web", scope: ["environment:connect", "environment:status"], cnf: { jkt: "web-proof-key-thumbprint" }, + rate_limit_tier: "trusted", }); }).pipe(Effect.provide(layer)), ); diff --git a/infra/relay/src/auth/RelayTokens.ts b/infra/relay/src/auth/RelayTokens.ts index b9c50bd2e8..81f794ff0e 100644 --- a/infra/relay/src/auth/RelayTokens.ts +++ b/infra/relay/src/auth/RelayTokens.ts @@ -4,9 +4,11 @@ import { RelayEnvironmentStatusScope, RelayMobileClientId, RelayMobileRegistrationScope, + RelayRateLimitTier as RelayRateLimitTierSchema, RelayWebClientId, type RelayPublicClientId, type RelayEnvironmentLinkChallengeRequest, + type RelayRateLimitTier, } from "@t3tools/contracts/relay"; import { encodeOAuthScope, parseAllowedOAuthScope } from "@t3tools/shared/oauthScope"; import { @@ -51,6 +53,7 @@ const RelayDpopAccessTokenClaims = Schema.Struct({ client_id: Schema.Literals([RelayMobileClientId, RelayWebClientId]), scope: Schema.String, cnf: Schema.Struct({ jkt: Schema.String }), + rate_limit_tier: RelayRateLimitTierSchema, }); export type RelayDpopAccessTokenClaims = Omit & { readonly scope: ReadonlyArray; @@ -104,6 +107,7 @@ export interface RelayTokensShape { readonly expiresAtEpochSeconds: number; readonly clientId: RelayPublicClientId; readonly scopes: ReadonlyArray; + readonly rateLimitTier: RelayRateLimitTier; }) => Effect.Effect; readonly verifyDpopAccessToken: (input: { readonly token: string; @@ -181,6 +185,7 @@ const make = Effect.gen(function* () { client_id: input.clientId, scope: encodeOAuthScope(input.scopes), cnf: { jkt: input.proofKeyThumbprint }, + rate_limit_tier: input.rateLimitTier, }, }); }); diff --git a/infra/relay/src/entitlements/Entitlements.test.ts b/infra/relay/src/entitlements/Entitlements.test.ts new file mode 100644 index 0000000000..13b160feeb --- /dev/null +++ b/infra/relay/src/entitlements/Entitlements.test.ts @@ -0,0 +1,53 @@ +import { describe, expect, it } from "@effect/vitest"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; + +import { RelayDb, type RelayDatabase } from "../db.ts"; +import * as Entitlements from "./Entitlements.ts"; + +function testLayer(rows: ReadonlyArray>) { + const fakeDb = { + select: () => ({ + from: () => ({ + where: () => ({ + limit: () => Effect.succeed(rows), + }), + }), + }), + } as unknown as RelayDatabase; + return Entitlements.layer.pipe(Layer.provide(Layer.succeed(RelayDb, fakeDb))); +} + +describe("Entitlements", () => { + it.effect("uses the platform defaults when a user has no override", () => + Effect.gen(function* () { + const entitlements = yield* Entitlements.Entitlements; + expect(yield* entitlements.getEffectiveForUser("user-1")).toEqual({ + managedEndpointLimit: 3, + mobileDeviceLimit: 5, + rateLimitTier: "standard", + }); + }).pipe(Effect.provide(testLayer([]))), + ); + + it.effect("applies sparse per-user overrides", () => + Effect.gen(function* () { + const entitlements = yield* Entitlements.Entitlements; + expect(yield* entitlements.getEffectiveForUser("user-1")).toEqual({ + managedEndpointLimit: 12, + mobileDeviceLimit: 5, + rateLimitTier: "trusted", + }); + }).pipe( + Effect.provide( + testLayer([ + { + managedEndpointLimit: 12, + mobileDeviceLimit: null, + rateLimitTier: "trusted", + }, + ]), + ), + ), + ); +}); diff --git a/infra/relay/src/entitlements/Entitlements.ts b/infra/relay/src/entitlements/Entitlements.ts new file mode 100644 index 0000000000..2d06401e90 --- /dev/null +++ b/infra/relay/src/entitlements/Entitlements.ts @@ -0,0 +1,101 @@ +import * as Context from "effect/Context"; +import * as Data from "effect/Data"; +import * as DateTime from "effect/DateTime"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import { isSqlError } from "effect/unstable/sql/SqlError"; +import { and, eq, gt, isNull, or } from "drizzle-orm"; +import type { RelayRateLimitTier } from "@t3tools/contracts/relay"; + +import { RelayDb } from "../db.ts"; +import { relayUserEntitlements } from "../persistence/schema.ts"; + +export const DEFAULT_MANAGED_ENDPOINT_LIMIT = 3; +export const DEFAULT_MOBILE_DEVICE_LIMIT = 5; + +export type RelayQuotaResource = "managed_endpoints" | "mobile_devices"; + +export interface EffectiveUserEntitlements { + readonly managedEndpointLimit: number; + readonly mobileDeviceLimit: number; + readonly rateLimitTier: RelayRateLimitTier; +} + +export class UserEntitlementPersistenceError extends Data.TaggedError( + "UserEntitlementPersistenceError", +)<{ + readonly cause: unknown; +}> {} + +export class UserResourceQuotaExceeded extends Data.TaggedError("UserResourceQuotaExceeded")<{ + readonly resource: RelayQuotaResource; + readonly limit: number; +}> {} + +export interface EntitlementsShape { + readonly getEffectiveForUser: ( + userId: string, + ) => Effect.Effect; + readonly withUserLock: ( + userId: string, + effect: Effect.Effect, + ) => Effect.Effect; +} + +export class Entitlements extends Context.Service()( + "t3code-relay/entitlements/Entitlements", +) {} + +const make = Effect.gen(function* () { + const db = yield* RelayDb; + + const getEffectiveForUser: EntitlementsShape["getEffectiveForUser"] = Effect.fn( + "relay.entitlements.get_effective_for_user", + )( + function* (userId) { + const now = DateTime.formatIso(yield* DateTime.now); + const rows = yield* db + .select({ + managedEndpointLimit: relayUserEntitlements.managedEndpointLimit, + mobileDeviceLimit: relayUserEntitlements.mobileDeviceLimit, + rateLimitTier: relayUserEntitlements.rateLimitTier, + }) + .from(relayUserEntitlements) + .where( + and( + eq(relayUserEntitlements.userId, userId), + or(isNull(relayUserEntitlements.expiresAt), gt(relayUserEntitlements.expiresAt, now)), + ), + ) + .limit(1); + const row = rows[0]; + return { + managedEndpointLimit: row?.managedEndpointLimit ?? DEFAULT_MANAGED_ENDPOINT_LIMIT, + mobileDeviceLimit: row?.mobileDeviceLimit ?? DEFAULT_MOBILE_DEVICE_LIMIT, + rateLimitTier: row?.rateLimitTier ?? "standard", + }; + }, + Effect.mapError((cause) => new UserEntitlementPersistenceError({ cause })), + ); + + const withUserLock: EntitlementsShape["withUserLock"] = (userId, effect) => + db.$client + .withTransaction( + Effect.gen(function* () { + yield* db.$client`SELECT pg_advisory_xact_lock(hashtextextended(${userId}, 0))`; + return yield* effect; + }), + ) + .pipe( + Effect.catchIf(isSqlError, (cause) => + Effect.fail(new UserEntitlementPersistenceError({ cause })), + ), + ); + + return Entitlements.of({ + getEffectiveForUser, + withUserLock, + }); +}); + +export const layer = Layer.effect(Entitlements, make); diff --git a/infra/relay/src/environments/EnvironmentConnector.test.ts b/infra/relay/src/environments/EnvironmentConnector.test.ts index 505d1f31d0..4bdb29b703 100644 --- a/infra/relay/src/environments/EnvironmentConnector.test.ts +++ b/infra/relay/src/environments/EnvironmentConnector.test.ts @@ -182,6 +182,9 @@ function makeAllocations( tunnelName: "tunnel-name", dnsRecordId: "dns-record-id", readyAt: "2026-05-25T00:00:00.000Z", + deprovisionRequestedAt: null, + lastDeprovisionAttemptAt: null, + lastDeprovisionError: null, }, ): ManagedEndpointAllocations.ManagedEndpointAllocationsShape { return { @@ -190,6 +193,10 @@ function makeAllocations( recordTunnel: () => Effect.die("unused"), recordDns: () => Effect.die("unused"), markReady: () => Effect.die("unused"), + requestDeprovision: () => Effect.die("unused"), + markDeprovisionAttempt: () => Effect.die("unused"), + recordDeprovisionFailure: () => Effect.die("unused"), + listCleanupCandidates: () => Effect.die("unused"), remove: () => Effect.die("unused"), }; } @@ -369,6 +376,9 @@ describe("EnvironmentConnector", () => { tunnelName: "tunnel-name", dnsRecordId: "dns-record-id", readyAt: null, + deprovisionRequestedAt: null, + lastDeprovisionAttemptAt: null, + lastDeprovisionError: null, }), }), ), diff --git a/infra/relay/src/environments/EnvironmentLinker.test.ts b/infra/relay/src/environments/EnvironmentLinker.test.ts index dce364bffa..79710f5b67 100644 --- a/infra/relay/src/environments/EnvironmentLinker.test.ts +++ b/infra/relay/src/environments/EnvironmentLinker.test.ts @@ -107,6 +107,7 @@ const makeRequest = Effect.gen(function* () { function testLayer(input?: { readonly upsert?: EnvironmentLinks.EnvironmentLinksShape["upsert"]; readonly consume?: DpopProofs.DpopProofReplayShape["consume"]; + readonly deprovision?: ManagedEndpointProvider.ManagedEndpointProviderShape["deprovision"]; }) { return EnvironmentLinker.layer.pipe( Layer.provideMerge(RelayTokens.layer), @@ -133,7 +134,8 @@ function testLayer(input?: { revokeForEnvironmentPublicKey: () => Effect.succeed(false), }), Layer.succeed(ManagedEndpointProvider.ManagedEndpointProvider, { - deprovision: () => Effect.void, + deprovision: input?.deprovision ?? (() => Effect.void), + reconcileDeprovisioning: Effect.void, provision: () => Effect.succeed({ endpoint: { @@ -150,6 +152,28 @@ function testLayer(input?: { } describe("EnvironmentLinker", () => { + it.effect("cleans up an existing managed allocation after a manual relink", () => { + let deprovisioned: { readonly userId: string; readonly environmentId: string } | null = null; + return Effect.gen(function* () { + const { request } = yield* makeRequest; + const linker = yield* EnvironmentLinker.EnvironmentLinker; + yield* linker.link({ userId: "user_123", request }); + expect(deprovisioned).toEqual({ + userId: "user_123", + environmentId: "env-link-test", + }); + }).pipe( + Effect.provide( + testLayer({ + deprovision: (input) => + Effect.sync(() => { + deprovisioned = input; + }), + }), + ), + ); + }); + it.effect("uses verified JWT claims when linking an environment", () => { let persistedEnvironmentId: string | null = null; return Effect.gen(function* () { diff --git a/infra/relay/src/environments/EnvironmentLinker.ts b/infra/relay/src/environments/EnvironmentLinker.ts index 853ea41cbd..bc84d47c2a 100644 --- a/infra/relay/src/environments/EnvironmentLinker.ts +++ b/infra/relay/src/environments/EnvironmentLinker.ts @@ -247,6 +247,23 @@ const make = Effect.gen(function* () { }); } yield* links.upsert({ ...input, proof: verified, endpoint }); + if (!input.request.managedTunnelsEnabled) { + yield* managedEndpointProvider + .deprovision({ + userId: input.userId, + environmentId: verified.environmentId, + }) + .pipe( + Effect.tapError((cause) => + Effect.logWarning("managed endpoint cleanup after manual relink failed", { + cause, + userId: input.userId, + environmentId: verified.environmentId, + }), + ), + Effect.ignore, + ); + } const environmentCredential = yield* credentials.create({ environmentId: verified.environmentId, environmentPublicKey: verified.environmentPublicKey, diff --git a/infra/relay/src/environments/EnvironmentLinks.ts b/infra/relay/src/environments/EnvironmentLinks.ts index b1e28d0da0..c540099534 100644 --- a/infra/relay/src/environments/EnvironmentLinks.ts +++ b/infra/relay/src/environments/EnvironmentLinks.ts @@ -60,6 +60,8 @@ export class EnvironmentLinkRevokePersistenceError extends Data.TaggedError( readonly cause: unknown; }> {} +const MAX_AGENT_AWARENESS_DELIVERY_USERS = 10; + export interface EnvironmentLinksShape { readonly upsert: (input: { readonly userId: string; @@ -198,7 +200,17 @@ const make = Effect.gen(function* () { }) .from(relayEnvironmentLinks) .where(agentAwarenessDeliveryUserKeyCondition(input)) + .limit(MAX_AGENT_AWARENESS_DELIVERY_USERS + 1) .pipe( + Effect.flatMap((rows) => + rows.length > MAX_AGENT_AWARENESS_DELIVERY_USERS + ? Effect.fail( + new EnvironmentLinkUserListPersistenceError({ + cause: new Error("Agent-awareness delivery fanout limit exceeded."), + }), + ) + : Effect.succeed(rows), + ), Effect.map((rows) => rows.map((row) => ({ userId: row.userId, diff --git a/infra/relay/src/environments/ManagedEndpointAllocations.test.ts b/infra/relay/src/environments/ManagedEndpointAllocations.test.ts new file mode 100644 index 0000000000..ea38244d1d --- /dev/null +++ b/infra/relay/src/environments/ManagedEndpointAllocations.test.ts @@ -0,0 +1,109 @@ +import { describe, expect, it } from "@effect/vitest"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; + +import { RelayDb, type RelayDatabase } from "../db.ts"; +import * as Entitlements from "../entitlements/Entitlements.ts"; +import * as ManagedEndpointAllocations from "./ManagedEndpointAllocations.ts"; + +function testLayer(fakeDb: RelayDatabase, managedEndpointLimit = 3) { + return ManagedEndpointAllocations.ManagedEndpointAllocations.layer.pipe( + Layer.provide( + Layer.mergeAll( + Layer.succeed(RelayDb, fakeDb), + Layer.succeed( + Entitlements.Entitlements, + Entitlements.Entitlements.of({ + getEffectiveForUser: () => + Effect.succeed({ + managedEndpointLimit, + mobileDeviceLimit: 5, + rateLimitTier: "standard", + }), + withUserLock: (_userId, effect) => effect, + }), + ), + ), + ), + ); +} + +describe("ManagedEndpointAllocations", () => { + it.effect("rejects a new managed endpoint when every slot is reserved", () => { + let selectCount = 0; + const fakeDb = { + select: () => { + selectCount++; + return { + from: () => ({ + where: () => + selectCount === 1 + ? { limit: () => Effect.succeed([]) } + : Effect.succeed([{ value: 3 }]), + }), + }; + }, + insert: () => { + throw new Error("allocation insert should not run"); + }, + } as unknown as RelayDatabase; + + return Effect.gen(function* () { + const allocations = yield* ManagedEndpointAllocations.ManagedEndpointAllocations; + const error = yield* Effect.flip( + allocations.reserve({ + userId: "user-1", + environmentId: "env-4", + hostname: "env-4.example.test", + tunnelName: "tunnel-env-4", + }), + ); + + expect(error).toEqual( + new Entitlements.UserResourceQuotaExceeded({ + resource: "managed_endpoints", + limit: 3, + }), + ); + }).pipe(Effect.provide(testLayer(fakeDb))); + }); + + it.effect("returns an existing reservation even when the user is at the cap", () => { + const existing: ManagedEndpointAllocations.ManagedEndpointAllocation = { + userId: "user-1", + environmentId: "env-1", + hostname: "env-1.example.test", + tunnelName: "tunnel-env-1", + tunnelId: null, + dnsRecordId: null, + readyAt: null, + deprovisionRequestedAt: null, + lastDeprovisionAttemptAt: null, + lastDeprovisionError: null, + }; + const fakeDb = { + select: () => ({ + from: () => ({ + where: () => ({ + limit: () => Effect.succeed([existing]), + }), + }), + }), + insert: () => { + throw new Error("allocation insert should not run"); + }, + } as unknown as RelayDatabase; + + return Effect.gen(function* () { + const allocations = yield* ManagedEndpointAllocations.ManagedEndpointAllocations; + expect( + yield* allocations.reserve({ + userId: "user-1", + environmentId: "env-1", + hostname: "env-1.example.test", + tunnelName: "tunnel-env-1", + }), + ).toEqual(existing); + }).pipe(Effect.provide(testLayer(fakeDb, 0))); + }); +}); diff --git a/infra/relay/src/environments/ManagedEndpointAllocations.ts b/infra/relay/src/environments/ManagedEndpointAllocations.ts index 236414e955..be5d670a17 100644 --- a/infra/relay/src/environments/ManagedEndpointAllocations.ts +++ b/infra/relay/src/environments/ManagedEndpointAllocations.ts @@ -1,5 +1,5 @@ import type { RelayManagedEndpoint } from "@t3tools/contracts/relay"; -import { and, eq } from "drizzle-orm"; +import { and, count, eq, isNotNull, isNull, lt, or } from "drizzle-orm"; import * as Context from "effect/Context"; import * as Data from "effect/Data"; import * as DateTime from "effect/DateTime"; @@ -8,7 +8,8 @@ import * as Layer from "effect/Layer"; import { RelayDb } from "../db.ts"; import { isManagedEndpointHostname, managedEndpointForHostname } from "../deploymentConfig.ts"; -import { relayManagedEndpointAllocations } from "../persistence/schema.ts"; +import * as Entitlements from "../entitlements/Entitlements.ts"; +import { relayEnvironmentLinks, relayManagedEndpointAllocations } from "../persistence/schema.ts"; export interface ManagedEndpointAllocation { readonly userId: string; @@ -18,6 +19,9 @@ export interface ManagedEndpointAllocation { readonly tunnelName: string; readonly dnsRecordId: string | null; readonly readyAt: string | null; + readonly deprovisionRequestedAt: string | null; + readonly lastDeprovisionAttemptAt: string | null; + readonly lastDeprovisionError: string | null; } export function resolveReadyManagedEndpoint(input: { @@ -27,6 +31,7 @@ export function resolveReadyManagedEndpoint(input: { if ( !input.baseDomain || input.allocation.readyAt === null || + input.allocation.deprovisionRequestedAt !== null || input.allocation.tunnelId === null || input.allocation.dnsRecordId === null || !isManagedEndpointHostname(input.allocation.hostname, input.baseDomain) @@ -60,13 +65,20 @@ interface RecordManagedEndpointDnsInput extends ManagedEndpointAllocationKey { readonly dnsRecordId: string; } +interface RecordManagedEndpointDeprovisionFailureInput extends ManagedEndpointAllocationKey { + readonly cause: unknown; +} + export interface ManagedEndpointAllocationsShape { readonly get: ( input: ManagedEndpointAllocationKey, ) => Effect.Effect; readonly reserve: ( input: ReserveManagedEndpointAllocationInput, - ) => Effect.Effect; + ) => Effect.Effect< + ManagedEndpointAllocation, + ManagedEndpointAllocationPersistenceError | Entitlements.UserResourceQuotaExceeded + >; readonly recordTunnel: ( input: RecordManagedEndpointTunnelInput, ) => Effect.Effect; @@ -76,6 +88,21 @@ export interface ManagedEndpointAllocationsShape { readonly markReady: ( input: ManagedEndpointAllocationKey, ) => Effect.Effect; + readonly requestDeprovision: ( + input: ManagedEndpointAllocationKey, + ) => Effect.Effect; + readonly markDeprovisionAttempt: ( + input: ManagedEndpointAllocationKey, + ) => Effect.Effect; + readonly recordDeprovisionFailure: ( + input: RecordManagedEndpointDeprovisionFailureInput, + ) => Effect.Effect; + readonly listCleanupCandidates: (input: { + readonly orphanedBefore: string; + }) => Effect.Effect< + ReadonlyArray, + ManagedEndpointAllocationPersistenceError + >; readonly remove: ( input: ManagedEndpointAllocationKey, ) => Effect.Effect; @@ -89,6 +116,9 @@ const allocationSelection = { tunnelName: relayManagedEndpointAllocations.tunnelName, dnsRecordId: relayManagedEndpointAllocations.dnsRecordId, readyAt: relayManagedEndpointAllocations.readyAt, + deprovisionRequestedAt: relayManagedEndpointAllocations.deprovisionRequestedAt, + lastDeprovisionAttemptAt: relayManagedEndpointAllocations.lastDeprovisionAttemptAt, + lastDeprovisionError: relayManagedEndpointAllocations.lastDeprovisionError, }; const whereAllocation = (input: ManagedEndpointAllocationKey) => @@ -102,54 +132,82 @@ const persistenceError = (cause: unknown) => ? cause : new ManagedEndpointAllocationPersistenceError({ cause }); +const reservationError = (cause: unknown) => + cause instanceof Entitlements.UserResourceQuotaExceeded ? cause : persistenceError(cause); + const make = Effect.gen(function* () { const db = yield* RelayDb; + const entitlements = yield* Entitlements.Entitlements; + + const get = Effect.fn("relay.managed_endpoint_allocations.get")(function* ( + input: ManagedEndpointAllocationKey, + ) { + return yield* db + .select(allocationSelection) + .from(relayManagedEndpointAllocations) + .where(whereAllocation(input)) + .limit(1) + .pipe( + Effect.map((rows) => rows[0] ?? null), + Effect.mapError(persistenceError), + ); + }); return ManagedEndpointAllocations.of({ - get: Effect.fn("relay.managed_endpoint_allocations.get")(function* ( - input: ManagedEndpointAllocationKey, - ) { - return yield* db - .select(allocationSelection) - .from(relayManagedEndpointAllocations) - .where(whereAllocation(input)) - .limit(1) - .pipe( - Effect.map((rows) => rows[0] ?? null), - Effect.mapError(persistenceError), - ); - }), + get, reserve: Effect.fn("relay.managed_endpoint_allocations.reserve")(function* ( input: ReserveManagedEndpointAllocationInput, ) { - const now = DateTime.formatIso(yield* DateTime.now); - const inserted = yield* db - .insert(relayManagedEndpointAllocations) - .values({ - ...input, - createdAt: now, - updatedAt: now, - }) - .onConflictDoNothing() - .returning(allocationSelection); - - const allocation = - inserted[0] ?? - (yield* db - .select(allocationSelection) - .from(relayManagedEndpointAllocations) - .where(whereAllocation(input)) - .limit(1) - .pipe(Effect.map((rows) => rows[0]))); - - if (allocation === undefined) { - return yield* new ManagedEndpointAllocationPersistenceError({ - cause: new Error("Managed endpoint allocation was not persisted."), - }); - } - - return allocation; - }, Effect.mapError(persistenceError)), + return yield* entitlements.withUserLock( + input.userId, + Effect.gen(function* () { + const existing = yield* get(input); + if (existing !== null) { + return existing; + } + const effective = yield* entitlements.getEffectiveForUser(input.userId); + const allocationCounts = yield* db + .select({ value: count() }) + .from(relayManagedEndpointAllocations) + .where(eq(relayManagedEndpointAllocations.userId, input.userId)) + .pipe(Effect.mapError(persistenceError)); + if ((allocationCounts[0]?.value ?? 0) >= effective.managedEndpointLimit) { + return yield* new Entitlements.UserResourceQuotaExceeded({ + resource: "managed_endpoints", + limit: effective.managedEndpointLimit, + }); + } + const now = DateTime.formatIso(yield* DateTime.now); + const inserted = yield* db + .insert(relayManagedEndpointAllocations) + .values({ + ...input, + createdAt: now, + updatedAt: now, + }) + .onConflictDoNothing() + .returning(allocationSelection) + .pipe(Effect.mapError(persistenceError)); + const allocation = + inserted[0] ?? + (yield* db + .select(allocationSelection) + .from(relayManagedEndpointAllocations) + .where(whereAllocation(input)) + .limit(1) + .pipe( + Effect.map((rows) => rows[0]), + Effect.mapError(persistenceError), + )); + if (allocation === undefined) { + return yield* new ManagedEndpointAllocationPersistenceError({ + cause: new Error("Managed endpoint allocation was not persisted."), + }); + } + return allocation; + }), + ); + }, Effect.mapError(reservationError)), recordTunnel: Effect.fn("relay.managed_endpoint_allocations.record_tunnel")(function* ( input: RecordManagedEndpointTunnelInput, ) { @@ -184,6 +242,76 @@ const make = Effect.gen(function* () { }) .where(whereAllocation(input)); }, Effect.mapError(persistenceError)), + requestDeprovision: Effect.fn("relay.managed_endpoint_allocations.request_deprovision")( + function* (input: ManagedEndpointAllocationKey) { + const now = DateTime.formatIso(yield* DateTime.now); + yield* db + .update(relayManagedEndpointAllocations) + .set({ + deprovisionRequestedAt: now, + updatedAt: now, + }) + .where(whereAllocation(input)); + }, + Effect.mapError(persistenceError), + ), + markDeprovisionAttempt: Effect.fn( + "relay.managed_endpoint_allocations.mark_deprovision_attempt", + )(function* (input: ManagedEndpointAllocationKey) { + const now = DateTime.formatIso(yield* DateTime.now); + yield* db + .update(relayManagedEndpointAllocations) + .set({ + lastDeprovisionAttemptAt: now, + lastDeprovisionError: null, + updatedAt: now, + }) + .where(whereAllocation(input)); + }, Effect.mapError(persistenceError)), + recordDeprovisionFailure: Effect.fn( + "relay.managed_endpoint_allocations.record_deprovision_failure", + )(function* (input: RecordManagedEndpointDeprovisionFailureInput) { + yield* db + .update(relayManagedEndpointAllocations) + .set({ + lastDeprovisionError: + input.cause instanceof Error ? input.cause.message : String(input.cause), + updatedAt: DateTime.formatIso(yield* DateTime.now), + }) + .where(whereAllocation(input)); + }, Effect.mapError(persistenceError)), + listCleanupCandidates: Effect.fn("relay.managed_endpoint_allocations.list_cleanup_candidates")( + function* (input) { + return yield* db + .select({ + userId: relayManagedEndpointAllocations.userId, + environmentId: relayManagedEndpointAllocations.environmentId, + }) + .from(relayManagedEndpointAllocations) + .leftJoin( + relayEnvironmentLinks, + and( + eq(relayEnvironmentLinks.userId, relayManagedEndpointAllocations.userId), + eq( + relayEnvironmentLinks.environmentId, + relayManagedEndpointAllocations.environmentId, + ), + isNull(relayEnvironmentLinks.revokedAt), + eq(relayEnvironmentLinks.managedTunnelsEnabled, true), + ), + ) + .where( + or( + isNotNull(relayManagedEndpointAllocations.deprovisionRequestedAt), + and( + isNull(relayEnvironmentLinks.userId), + lt(relayManagedEndpointAllocations.updatedAt, input.orphanedBefore), + ), + ), + ); + }, + Effect.mapError(persistenceError), + ), remove: Effect.fn("relay.managed_endpoint_allocations.remove")(function* ( input: ManagedEndpointAllocationKey, ) { diff --git a/infra/relay/src/environments/ManagedEndpointProvider.test.ts b/infra/relay/src/environments/ManagedEndpointProvider.test.ts index 5d82711745..912f2c2b4e 100644 --- a/infra/relay/src/environments/ManagedEndpointProvider.test.ts +++ b/infra/relay/src/environments/ManagedEndpointProvider.test.ts @@ -40,7 +40,17 @@ interface DnsCall { } interface AllocationCall { - readonly operation: "get" | "reserve" | "recordTunnel" | "recordDns" | "markReady" | "remove"; + readonly operation: + | "get" + | "reserve" + | "recordTunnel" + | "recordDns" + | "markReady" + | "requestDeprovision" + | "markDeprovisionAttempt" + | "recordDeprovisionFailure" + | "listCleanupCandidates" + | "remove"; readonly input: unknown; } @@ -158,6 +168,9 @@ function makeAllocations(calls: AllocationCall[] = []) { tunnelId: null, dnsRecordId: null, readyAt: null, + deprovisionRequestedAt: null, + lastDeprovisionAttemptAt: null, + lastDeprovisionError: null, }; allocations.set(allocationKey(input), allocation); return allocation; @@ -189,6 +202,23 @@ function makeAllocations(calls: AllocationCall[] = []) { }); } }), + requestDeprovision: (input) => + Effect.sync(() => { + calls.push({ operation: "requestDeprovision", input }); + }), + markDeprovisionAttempt: (input) => + Effect.sync(() => { + calls.push({ operation: "markDeprovisionAttempt", input }); + }), + recordDeprovisionFailure: (input) => + Effect.sync(() => { + calls.push({ operation: "recordDeprovisionFailure", input }); + }), + listCleanupCandidates: (input) => + Effect.sync(() => { + calls.push({ operation: "listCleanupCandidates", input }); + return []; + }), remove: (input) => Effect.sync(() => { calls.push({ operation: "remove", input }); @@ -560,7 +590,9 @@ describe("ManagedEndpointProvider", () => { "recordTunnel", "recordDns", "markReady", + "requestDeprovision", "get", + "markDeprovisionAttempt", "remove", ]); }).pipe(Effect.provide(layer)); @@ -584,7 +616,10 @@ describe("ManagedEndpointProvider", () => { expect(tunnelCalls).toEqual([]); expect(dnsCalls).toEqual([]); - expect(allocationCalls).toEqual([{ operation: "get", input: key }]); + expect(allocationCalls).toEqual([ + { operation: "requestDeprovision", input: key }, + { operation: "get", input: key }, + ]); }).pipe(Effect.provide(layer)); }); @@ -625,8 +660,13 @@ describe("ManagedEndpointProvider", () => { "recordTunnel", "recordDns", "markReady", + "requestDeprovision", "get", + "markDeprovisionAttempt", + "recordDeprovisionFailure", + "requestDeprovision", "get", + "markDeprovisionAttempt", "remove", ]); }).pipe(Effect.provide(layer)); @@ -662,6 +702,43 @@ describe("ManagedEndpointProvider", () => { }).pipe(Effect.provide(layer)); }); + it.effect("reconciles endpoint allocations selected for cleanup", () => { + const allocationCalls: AllocationCall[] = []; + const key = { userId: "user_ABC", environmentId: "env_ABC" } as const; + const baseAllocations = makeAllocations(allocationCalls); + const allocations = ManagedEndpointAllocations.ManagedEndpointAllocations.of({ + ...baseAllocations, + listCleanupCandidates: (input) => + Effect.sync(() => { + allocationCalls.push({ operation: "listCleanupCandidates", input }); + return [key]; + }), + }); + + return Effect.gen(function* () { + const provider = yield* ManagedEndpointProvider.ManagedEndpointProvider; + yield* provider.provision({ + ...key, + origin: { localHttpHost: "127.0.0.1", localHttpPort: 3773 }, + }); + yield* provider.reconcileDeprovisioning; + + expect(allocationCalls.map((call) => call.operation)).toEqual([ + "reserve", + "recordTunnel", + "recordDns", + "markReady", + "listCleanupCandidates", + "requestDeprovision", + "get", + "markDeprovisionAttempt", + "remove", + ]); + }).pipe( + Effect.provide(providerLayer(makePersistentTunnelClient(), makeDnsClient(), allocations)), + ); + }); + it.effect("scopes managed endpoint resources by user", () => { const tunnelCalls: TunnelCall[] = []; diff --git a/infra/relay/src/environments/ManagedEndpointProvider.ts b/infra/relay/src/environments/ManagedEndpointProvider.ts index 068beccff0..7bb7277c45 100644 --- a/infra/relay/src/environments/ManagedEndpointProvider.ts +++ b/infra/relay/src/environments/ManagedEndpointProvider.ts @@ -4,6 +4,7 @@ import * as Arr from "effect/Array"; import * as Context from "effect/Context"; import * as Crypto from "effect/Crypto"; import * as Data from "effect/Data"; +import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; import * as Encoding from "effect/Encoding"; import * as Layer from "effect/Layer"; @@ -17,6 +18,7 @@ import type { } from "@t3tools/contracts/relay"; import * as RelayConfiguration from "../Config.ts"; +import * as Entitlements from "../entitlements/Entitlements.ts"; import { managedEndpointDigestInput, managedEndpointForHostname, @@ -51,7 +53,8 @@ export class ManagedEndpointOriginNotAllowed extends Data.TaggedError( export type ManagedEndpointProviderError = | ManagedEndpointProvisioningNotConfigured | ManagedEndpointProvisioningFailed - | ManagedEndpointOriginNotAllowed; + | ManagedEndpointOriginNotAllowed + | Entitlements.UserResourceQuotaExceeded; export interface ManagedEndpointProvisioningResult { readonly endpoint: RelayManagedEndpoint; @@ -68,6 +71,7 @@ export interface ManagedEndpointProviderShape { readonly userId: string; readonly environmentId: string; }) => Effect.Effect; + readonly reconcileDeprovisioning: Effect.Effect; } export class ManagedEndpointProvider extends Context.Service< @@ -281,32 +285,68 @@ const make = Effect.gen(function* () { ); }); - return ManagedEndpointProvider.of({ - deprovision: Effect.fn("relay.managed_endpoint_provider.deprovision")(function* (input) { - yield* Effect.annotateCurrentSpan({ - "relay.user_id": input.userId, - "relay.environment_id": input.environmentId, - }); - const allocation = yield* allocations - .get(input) - .pipe(Effect.mapError((cause) => new ManagedEndpointDeprovisioningFailed({ cause }))); - if (allocation === null) { - return; - } + const deprovision: ManagedEndpointProviderShape["deprovision"] = Effect.fn( + "relay.managed_endpoint_provider.deprovision", + )(function* (input) { + yield* Effect.annotateCurrentSpan({ + "relay.user_id": input.userId, + "relay.environment_id": input.environmentId, + }); + yield* allocations + .requestDeprovision(input) + .pipe(Effect.mapError((cause) => new ManagedEndpointDeprovisioningFailed({ cause }))); + const allocation = yield* allocations + .get(input) + .pipe(Effect.mapError((cause) => new ManagedEndpointDeprovisioningFailed({ cause }))); + if (allocation === null) { + return; + } + yield* allocations + .markDeprovisionAttempt(input) + .pipe(Effect.mapError((cause) => new ManagedEndpointDeprovisioningFailed({ cause }))); + yield* Effect.gen(function* () { if (allocation.dnsRecordId !== null) { - yield* ignoreNotFound(dns.deleteRecord(allocation.dnsRecordId)).pipe( - Effect.mapError((cause) => new ManagedEndpointDeprovisioningFailed({ cause })), - ); + yield* ignoreNotFound(dns.deleteRecord(allocation.dnsRecordId)); } if (allocation.tunnelId !== null) { - yield* ignoreNotFound(tunnels.delete(allocation.tunnelId)).pipe( - Effect.mapError((cause) => new ManagedEndpointDeprovisioningFailed({ cause })), - ); + yield* ignoreNotFound(tunnels.delete(allocation.tunnelId)); } - yield* allocations - .remove(input) + yield* allocations.remove(input); + }).pipe( + Effect.mapError((cause) => new ManagedEndpointDeprovisioningFailed({ cause })), + Effect.tapError((error) => + allocations.recordDeprovisionFailure({ ...input, cause: error.cause }).pipe(Effect.ignore), + ), + ); + }); + + return ManagedEndpointProvider.of({ + deprovision, + reconcileDeprovisioning: Effect.gen(function* () { + const orphanedBefore = DateTime.formatIso( + DateTime.subtract(yield* DateTime.now, { + minutes: 15, + }), + ); + const candidates = yield* allocations + .listCleanupCandidates({ orphanedBefore }) .pipe(Effect.mapError((cause) => new ManagedEndpointDeprovisioningFailed({ cause }))); - }), + yield* Effect.forEach( + candidates, + (input) => + deprovision(input).pipe( + Effect.tapError((cause) => + Effect.logWarning("managed endpoint deprovision reconciliation failed", { + cause, + userId: input.userId, + environmentId: input.environmentId, + }), + ), + Effect.ignore, + ), + { concurrency: 5, discard: true }, + ); + }).pipe(Effect.withSpan("relay.managed_endpoint_provider.reconcile_deprovisioning")), provision: Effect.fn("relay.managed_endpoint_provider.provision")(function* (input) { yield* Effect.annotateCurrentSpan({ "relay.user_id": input.userId, @@ -339,7 +379,13 @@ const make = Effect.gen(function* () { hostname: managedEndpointHostname(cf.namespace, cf.baseDomain, environmentHash), tunnelName: managedEndpointTunnelName(cf.namespace, environmentHash), }) - .pipe(Effect.mapError((cause) => new ManagedEndpointProvisioningFailed({ cause }))); + .pipe( + Effect.mapError((cause) => + cause instanceof Entitlements.UserResourceQuotaExceeded + ? cause + : new ManagedEndpointProvisioningFailed({ cause }), + ), + ); const { hostname, tunnelName } = allocation; const tunnel = yield* tunnels.list({ name: tunnelName, isDeleted: false }).pipe( diff --git a/infra/relay/src/http/Api.ts b/infra/relay/src/http/Api.ts index 3a9e59a671..c32c2197e1 100644 --- a/infra/relay/src/http/Api.ts +++ b/infra/relay/src/http/Api.ts @@ -45,6 +45,8 @@ import { type RelayEnvironmentConnectRequest, type RelayDpopAccessTokenScope, RelayInternalError, + RelayQuotaExceededError, + RelayRateLimitedError, } from "@t3tools/contracts/relay"; import { normalizeRelayIssuer } from "@t3tools/shared/relayJwt"; @@ -66,6 +68,8 @@ import * as EnvironmentPublishSignatures from "../environments/EnvironmentPublis import * as MobileRegistrations from "../agentActivity/MobileRegistrations.ts"; import { withSpanAttributes } from "../observability.ts"; import { RelayDb } from "../db.ts"; +import * as Entitlements from "../entitlements/Entitlements.ts"; +import * as RateLimits from "../rateLimits/RateLimits.ts"; const relayCorsAllowedMethods = ["GET", "POST", "DELETE", "OPTIONS"] as const; const relayCorsAllowedHeaders = [ @@ -293,6 +297,7 @@ export const relayDpopClientAuthLayer = Layer.effect( token, proofKeyThumbprint: verified.cnf.jkt, dpopScopes: verified.scope, + rateLimitTier: verified.rate_limit_tier, }), ); }), @@ -309,6 +314,33 @@ function readHttpAuthorizationCredential(credential: Redacted.Redacted): return Redacted.value(credential).trimStart(); } +const relayClientIpAddress = HttpServerRequest.HttpServerRequest.pipe( + Effect.map((request) => request.headers["cf-connecting-ip"] ?? "unknown"), +); + +const checkUserRateLimit = Effect.fnUntraced(function* ( + entitlements: Entitlements.EntitlementsShape, + rateLimits: RateLimits.RateLimitsShape, + operation: RateLimits.RelayRateLimitOperation, + userId: string, +) { + const effective = yield* entitlements.getEffectiveForUser(userId); + yield* rateLimits.check({ operation, key: userId, tier: effective.rateLimitTier }); +}); + +const checkDpopUserRateLimit = Effect.fnUntraced(function* ( + rateLimits: RateLimits.RateLimitsShape, + operation: RateLimits.RelayRateLimitOperation, + key: string, +) { + const principal = yield* RelayClientPrincipal; + yield* rateLimits.check({ + operation, + key, + ...(principal.rateLimitTier ? { tier: principal.rateLimitTier } : {}), + }); +}); + export const metadataApi = HttpApiBuilder.group( RelayApi, "metadata", @@ -372,12 +404,14 @@ export const mobileApi = HttpApiBuilder.group( Effect.fnUntraced(function* (handlers) { const registrations = yield* MobileRegistrations.MobileRegistrations; const dpopProofs = yield* DpopProofs.DpopProofReplay; + const rateLimits = yield* RateLimits.RateLimits; return handlers .handle( "registerDevice", Effect.fn("relay.api.mobile.registerDevice")(function* (args) { const { payload } = args; const { userId, token } = yield* RelayClientPrincipal; + yield* checkDpopUserRateLimit(rateLimits, "mobile_registration", userId); const proofKeyThumbprint = yield* requireDpopPrincipalScope("mobile:registration"); yield* requireDpopThumbprint(proofKeyThumbprint, { expectedAccessToken: token, @@ -390,6 +424,7 @@ export const mobileApi = HttpApiBuilder.group( Effect.fn("relay.api.mobile.registerLiveActivity")(function* (args) { const { payload } = args; const { userId, token } = yield* RelayClientPrincipal; + yield* checkDpopUserRateLimit(rateLimits, "mobile_registration", userId); const proofKeyThumbprint = yield* requireDpopPrincipalScope("mobile:registration"); yield* requireDpopThumbprint(proofKeyThumbprint, { expectedAccessToken: token, @@ -402,6 +437,7 @@ export const mobileApi = HttpApiBuilder.group( Effect.fn("relay.api.mobile.unregisterDevice")(function* (args) { const { params } = args; const { userId, token } = yield* RelayClientPrincipal; + yield* checkDpopUserRateLimit(rateLimits, "mobile_registration", userId); const proofKeyThumbprint = yield* requireDpopPrincipalScope("mobile:registration"); yield* requireDpopThumbprint(proofKeyThumbprint, { expectedAccessToken: token, @@ -424,6 +460,8 @@ export const clientApi = HttpApiBuilder.group( const managedEndpointProvider = yield* ManagedEndpointProvider.ManagedEndpointProvider; const credentials = yield* EnvironmentCredentials.EnvironmentCredentials; const devices = yield* Devices.Devices; + const entitlements = yield* Entitlements.Entitlements; + const rateLimits = yield* RateLimits.RateLimits; return handlers .handle( "listEnvironments", @@ -447,6 +485,14 @@ export const clientApi = HttpApiBuilder.group( const { payload } = args; yield* appendRelayCredentialResponseHeaders; const { userId } = yield* RelayClientPrincipal; + if (payload.managedTunnelsEnabled) { + yield* checkUserRateLimit( + entitlements, + rateLimits, + "managed_endpoint_provision", + userId, + ); + } const result = yield* linker.link({ userId, request: payload }); return { ok: true, @@ -516,6 +562,7 @@ export const clientApi = HttpApiBuilder.group( Effect.fn("relay.api.client.createEnvironmentLinkChallenge")(function* (args) { yield* appendRelayCredentialResponseHeaders; const { userId } = yield* RelayClientPrincipal; + yield* checkUserRateLimit(entitlements, rateLimits, "link_challenge", userId); const now = yield* DateTime.now; const expiresAt = DateTime.add(now, { minutes: 5 }); const jti = yield* crypto.randomUUIDv4.pipe( @@ -538,12 +585,6 @@ export const clientApi = HttpApiBuilder.group( Effect.fn("relay.api.client.unlinkEnvironment")(function* (args) { const { params } = args; const { userId } = yield* RelayClientPrincipal; - yield* managedEndpointProvider - .deprovision({ - userId, - environmentId: params.environmentId, - }) - .pipe(Effect.catch(() => relayInternalErrorResponse("upstream_unavailable"))); const link = yield* links.getForUser({ userId, environmentId: params.environmentId, @@ -560,6 +601,21 @@ export const clientApi = HttpApiBuilder.group( environmentId: link.environmentId, environmentPublicKey: link.environmentPublicKey, }); + yield* managedEndpointProvider + .deprovision({ + userId, + environmentId: params.environmentId, + }) + .pipe( + Effect.tapError((cause) => + Effect.logWarning("managed endpoint cleanup after unlink failed", { + cause, + userId, + environmentId: params.environmentId, + }), + ), + Effect.ignore, + ); } return { ok: unlinked }; }, mapRelayCommonApiErrors("not_authorized")), @@ -575,10 +631,16 @@ export const tokenApi = HttpApiBuilder.group( const crypto = yield* Crypto.Crypto; const dpopProofs = yield* DpopProofs.DpopProofReplay; const relayTokens = yield* RelayTokens.RelayTokens; + const entitlements = yield* Entitlements.Entitlements; + const rateLimits = yield* RateLimits.RateLimits; return handlers.handle( "exchangeDpopAccessToken", Effect.fn("relay.api.token.exchangeDpopAccessToken")(function* (args) { yield* appendRelayCredentialResponseHeaders; + yield* rateLimits.check({ + operation: "token_exchange", + key: `ip:${yield* relayClientIpAddress}`, + }); const issuer = normalizeRelayIssuer(config.relayIssuer); const requestedScopes = relayTokens.resolveDpopAccessTokenScopes({ clientId: args.payload.client_id, @@ -599,6 +661,12 @@ export const tokenApi = HttpApiBuilder.group( if (!verified.sub || !hasExpectedClerkAudience(verified.aud, config.clerkJwtAudience)) { return yield* relayAuthInvalidError("invalid_bearer"); } + const effective = yield* entitlements.getEffectiveForUser(verified.sub); + yield* rateLimits.check({ + operation: "token_exchange", + key: `user:${verified.sub}`, + tier: effective.rateLimitTier, + }); const proofKeyThumbprint = yield* requireDpopProof().pipe( Effect.provideService(DpopProofs.DpopProofReplay, dpopProofs), ); @@ -617,6 +685,7 @@ export const tokenApi = HttpApiBuilder.group( expiresAtEpochSeconds: Math.floor(expiresAt.epochMilliseconds / 1_000), clientId: args.payload.client_id, scopes: requestedScopes, + rateLimitTier: effective.rateLimitTier, }) .pipe(Effect.catch(() => relayInternalErrorResponse("internal_error"))), issued_token_type: RelayAccessTokenType, @@ -635,6 +704,7 @@ export const dpopClientApi = HttpApiBuilder.group( Effect.fnUntraced(function* (handlers) { const connector = yield* EnvironmentConnector.EnvironmentConnector; const dpopProofs = yield* DpopProofs.DpopProofReplay; + const rateLimits = yield* RateLimits.RateLimits; return handlers .handle( "connectEnvironment", @@ -643,6 +713,11 @@ export const dpopClientApi = HttpApiBuilder.group( const { params, payload } = args; yield* appendRelayCredentialResponseHeaders; const { userId, token } = yield* RelayClientPrincipal; + yield* checkDpopUserRateLimit( + rateLimits, + "environment_connect", + `${userId}:${params.environmentId}`, + ); const proofKeyThumbprint = yield* requireDpopPrincipalScope("environment:connect"); const requestedThumbprint = resolveConnectClientKeyThumbprint(payload); if (!requestedThumbprint || requestedThumbprint !== proofKeyThumbprint) { @@ -691,6 +766,11 @@ export const dpopClientApi = HttpApiBuilder.group( function* (args) { const { params } = args; const { userId, token } = yield* RelayClientPrincipal; + yield* checkDpopUserRateLimit( + rateLimits, + "environment_status", + `${userId}:${params.environmentId}`, + ); const proofKeyThumbprint = yield* requireDpopPrincipalScope("environment:status"); yield* requireDpopThumbprint(proofKeyThumbprint, { expectedAccessToken: token, @@ -736,6 +816,7 @@ export const serverApi = HttpApiBuilder.group( Effect.fnUntraced(function* (handlers) { const publisher = yield* AgentActivityPublisher.AgentActivityPublisher; const publishSignatures = yield* EnvironmentPublishSignatures.EnvironmentPublishSignatures; + const rateLimits = yield* RateLimits.RateLimits; return handlers.handle( "publishAgentActivity", Effect.fn("relay.api.server.publishAgentActivity")( @@ -745,6 +826,10 @@ export const serverApi = HttpApiBuilder.group( if (principal.environmentId !== params.environmentId) { return yield* new HttpApiError.Unauthorized({}); } + yield* rateLimits.check({ + operation: "agent_activity_publish", + key: `${params.environmentId}:${principal.environmentPublicKey}`, + }); yield* publishSignatures.verify({ environmentId: params.environmentId, environmentPublicKey: principal.environmentPublicKey, @@ -835,6 +920,7 @@ const COMMON_AUTH_INVALID_REASONS = [ EnvironmentLinks.EnvironmentLinkLookupPersistenceError, EnvironmentLinks.EnvironmentLinkRevokePersistenceError, ManagedEndpointAllocations.ManagedEndpointAllocationPersistenceError, + Entitlements.UserEntitlementPersistenceError, EnvironmentCredentials.EnvironmentCredentialAuthenticatePersistenceError, EnvironmentCredentials.EnvironmentCredentialRevokePersistenceError, DpopProofs.DpopProofReplayPersistenceError, @@ -848,9 +934,23 @@ const COMMON_AUTH_INVALID_REASONS = [ type RelayCommonPersistenceError = InstanceType<(typeof COMMON_AUTH_INVALID_REASONS)[number]>; type MapRelayCommonApiError = - | Exclude + | Exclude< + E, + | HttpApiError.Unauthorized + | RelayCommonPersistenceError + | Entitlements.UserResourceQuotaExceeded + | AgentActivityRows.AgentActivityRowQuotaExceeded + | RateLimits.RelayRateLimitExceeded + > | (Extract extends never ? never : RelayAuthInvalidError) - | (Extract extends never ? never : RelayInternalError); + | (Extract extends never ? never : RelayInternalError) + | (Extract extends never + ? never + : RelayQuotaExceededError) + | (Extract extends never + ? never + : RelayQuotaExceededError) + | (Extract extends never ? never : RelayRateLimitedError); function isRelayCommonPersistenceError(error: unknown): error is RelayCommonPersistenceError { return COMMON_AUTH_INVALID_REASONS.some((ErrorType) => error instanceof ErrorType); @@ -885,6 +985,29 @@ function mapRelayCommonApiErrors(authReason: RelayAuthInvalidReason) { }) as MapRelayCommonApiError, ); } + if ( + error instanceof Entitlements.UserResourceQuotaExceeded || + error instanceof AgentActivityRows.AgentActivityRowQuotaExceeded + ) { + return yield* Effect.fail( + new RelayQuotaExceededError({ + code: "quota_exceeded", + resource: error.resource, + limit: error.limit, + traceId, + }) as MapRelayCommonApiError, + ); + } + if (error instanceof RateLimits.RelayRateLimitExceeded) { + return yield* Effect.fail( + new RelayRateLimitedError({ + code: "rate_limited", + operation: error.operation, + retryAfterSeconds: error.retryAfterSeconds, + traceId, + }) as MapRelayCommonApiError, + ); + } return yield* Effect.fail(error as MapRelayCommonApiError); }); diff --git a/infra/relay/src/maintenance/Maintenance.test.ts b/infra/relay/src/maintenance/Maintenance.test.ts new file mode 100644 index 0000000000..df7acd3698 --- /dev/null +++ b/infra/relay/src/maintenance/Maintenance.test.ts @@ -0,0 +1,36 @@ +import { describe, expect, it } from "@effect/vitest"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; + +import { RelayDb, type RelayDatabase } from "../db.ts"; +import { + relayAgentActivityRows, + relayDeliveryAttempts, + relayLiveActivities, +} from "../persistence/schema.ts"; +import * as Maintenance from "./Maintenance.ts"; + +describe("Maintenance", () => { + it.effect("prunes bounded-retention relay state", () => { + const deletedTables: Array = []; + const fakeDb = { + delete: (table: unknown) => { + deletedTables.push(table); + return { + where: () => Effect.void, + }; + }, + } as unknown as RelayDatabase; + + return Effect.gen(function* () { + const maintenance = yield* Maintenance.Maintenance; + yield* maintenance.pruneExpired; + + expect(deletedTables).toEqual([ + relayAgentActivityRows, + relayDeliveryAttempts, + relayLiveActivities, + ]); + }).pipe(Effect.provide(Maintenance.layer.pipe(Layer.provide(Layer.succeed(RelayDb, fakeDb))))); + }); +}); diff --git a/infra/relay/src/maintenance/Maintenance.ts b/infra/relay/src/maintenance/Maintenance.ts new file mode 100644 index 0000000000..6625966df3 --- /dev/null +++ b/infra/relay/src/maintenance/Maintenance.ts @@ -0,0 +1,63 @@ +import * as Context from "effect/Context"; +import * as Data from "effect/Data"; +import * as DateTime from "effect/DateTime"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import { and, isNotNull, lt } from "drizzle-orm"; + +import { RelayDb } from "../db.ts"; +import { + relayAgentActivityRows, + relayDeliveryAttempts, + relayLiveActivities, +} from "../persistence/schema.ts"; + +export class RelayMaintenancePersistenceError extends Data.TaggedError( + "RelayMaintenancePersistenceError", +)<{ + readonly cause: unknown; +}> {} + +export interface MaintenanceShape { + readonly pruneExpired: Effect.Effect; +} + +export class Maintenance extends Context.Service()( + "t3code-relay/maintenance/Maintenance", +) {} + +const make = Effect.gen(function* () { + const db = yield* RelayDb; + + const pruneExpired: MaintenanceShape["pruneExpired"] = Effect.gen(function* () { + const now = yield* DateTime.now; + const activityCutoff = DateTime.formatIso(DateTime.subtract(now, { hours: 24 })); + const historicalCutoff = DateTime.formatIso(DateTime.subtract(now, { days: 30 })); + yield* Effect.all( + [ + db + .delete(relayAgentActivityRows) + .where(lt(relayAgentActivityRows.updatedAt, activityCutoff)), + db + .delete(relayDeliveryAttempts) + .where(lt(relayDeliveryAttempts.createdAt, historicalCutoff)), + db + .delete(relayLiveActivities) + .where( + and( + isNotNull(relayLiveActivities.endedAt), + lt(relayLiveActivities.endedAt, historicalCutoff), + ), + ), + ], + { concurrency: 3, discard: true }, + ); + }).pipe( + Effect.withSpan("relay.maintenance.prune_expired"), + Effect.mapError((cause) => new RelayMaintenancePersistenceError({ cause })), + ); + + return Maintenance.of({ pruneExpired }); +}); + +export const layer = Layer.effect(Maintenance, make); diff --git a/infra/relay/src/persistence/schema.ts b/infra/relay/src/persistence/schema.ts index ab3d2dfd97..2b82947e41 100644 --- a/infra/relay/src/persistence/schema.ts +++ b/infra/relay/src/persistence/schema.ts @@ -3,8 +3,10 @@ import type { RelayAgentActivityState, RelayAgentAwarenessPreferences, } from "@t3tools/contracts/relay"; +import { sql } from "drizzle-orm"; import { boolean, + check, index, integer, jsonb, @@ -93,6 +95,9 @@ export const relayManagedEndpointAllocations = pgTable( tunnelName: text("tunnel_name").notNull(), dnsRecordId: varchar("dns_record_id", { length: 191 }), readyAt: varchar("ready_at", { length: 64 }), + deprovisionRequestedAt: varchar("deprovision_requested_at", { length: 64 }), + lastDeprovisionAttemptAt: varchar("last_deprovision_attempt_at", { length: 64 }), + lastDeprovisionError: text("last_deprovision_error"), createdAt: varchar("created_at", { length: 64 }).notNull(), updatedAt: varchar("updated_at", { length: 64 }).notNull(), }, @@ -100,6 +105,40 @@ export const relayManagedEndpointAllocations = pgTable( primaryKey({ columns: [table.userId, table.environmentId] }), uniqueIndex("idx_relay_managed_endpoint_allocations_hostname").on(table.hostname), uniqueIndex("idx_relay_managed_endpoint_allocations_tunnel_name").on(table.tunnelName), + index("idx_relay_managed_endpoint_allocations_cleanup").on( + table.deprovisionRequestedAt, + table.updatedAt, + ), + ], +); + +export const relayUserEntitlements = pgTable( + "relay_user_entitlements", + { + userId: varchar("user_id", { length: 255 }).primaryKey(), + managedEndpointLimit: integer("managed_endpoint_limit"), + mobileDeviceLimit: integer("mobile_device_limit"), + rateLimitTier: varchar("rate_limit_tier", { length: 32 }).$type< + "standard" | "trusted" | "blocked" + >(), + expiresAt: varchar("expires_at", { length: 64 }), + reason: text("reason"), + createdAt: varchar("created_at", { length: 64 }).notNull(), + updatedAt: varchar("updated_at", { length: 64 }).notNull(), + }, + (table) => [ + check( + "chk_relay_user_entitlements_managed_endpoint_limit", + sql`${table.managedEndpointLimit} IS NULL OR ${table.managedEndpointLimit} >= 0`, + ), + check( + "chk_relay_user_entitlements_mobile_device_limit", + sql`${table.mobileDeviceLimit} IS NULL OR ${table.mobileDeviceLimit} >= 0`, + ), + check( + "chk_relay_user_entitlements_rate_limit_tier", + sql`${table.rateLimitTier} IS NULL OR ${table.rateLimitTier} IN ('standard', 'trusted', 'blocked')`, + ), ], ); diff --git a/infra/relay/src/rateLimits/RateLimits.test.ts b/infra/relay/src/rateLimits/RateLimits.test.ts new file mode 100644 index 0000000000..b5688c4876 --- /dev/null +++ b/infra/relay/src/rateLimits/RateLimits.test.ts @@ -0,0 +1,138 @@ +import { describe, expect, it } from "@effect/vitest"; +import * as Cloudflare from "alchemy/Cloudflare"; +import * as Effect from "effect/Effect"; + +import * as RateLimits from "./RateLimits.ts"; + +const provideWorkerEnvironment = Effect.provideService(Cloudflare.WorkerEnvironment, {}); + +function client(limit: Cloudflare.RateLimitClient["limit"]): Cloudflare.RateLimitClient { + return { + raw: Effect.die("unused raw rate limit binding"), + limit, + }; +} + +function clients( + overrides: Partial = {}, +): RateLimits.RelayRateLimitClients { + const allow = client(() => Effect.succeed({ success: true })); + return { + token_exchange: { standard: allow, trusted: allow }, + link_challenge: { standard: allow, trusted: allow }, + managed_endpoint_provision: { standard: allow, trusted: allow }, + environment_connect: { standard: allow, trusted: allow }, + environment_status: { standard: allow, trusted: allow }, + mobile_registration: { standard: allow, trusted: allow }, + agent_activity_publish: { standard: allow, trusted: allow }, + ...overrides, + }; +} + +describe("RateLimits", () => { + it.effect("returns a typed denial when Cloudflare rejects the key", () => + Effect.gen(function* () { + const rateLimits = yield* RateLimits.RateLimits; + const error = yield* Effect.flip( + rateLimits.check({ + operation: "environment_connect", + key: "user-1:env-1", + }), + ); + + expect(error).toEqual( + new RateLimits.RelayRateLimitExceeded({ + operation: "environment_connect", + retryAfterSeconds: 60, + }), + ); + }).pipe( + provideWorkerEnvironment, + Effect.provide( + RateLimits.layerCloudflareBindings( + clients({ + environment_connect: { + standard: client(() => Effect.succeed({ success: false })), + trusted: client(() => Effect.succeed({ success: true })), + }, + }), + ), + ), + ), + ); + + it.effect("uses the trusted binding for trusted users", () => { + let checked = false; + return Effect.gen(function* () { + const rateLimits = yield* RateLimits.RateLimits; + yield* rateLimits.check({ + operation: "link_challenge", + key: "user-1", + tier: "trusted", + }); + expect(checked).toBe(true); + }).pipe( + provideWorkerEnvironment, + Effect.provide( + RateLimits.layerCloudflareBindings( + clients({ + link_challenge: { + standard: client(() => Effect.die("standard binding should not run")), + trusted: client(() => + Effect.sync(() => { + checked = true; + return { success: true }; + }), + ), + }, + }), + ), + ), + ); + }); + + it.effect("fails open when the Cloudflare binding is unavailable", () => + Effect.gen(function* () { + const rateLimits = yield* RateLimits.RateLimits; + yield* rateLimits.check({ + operation: "agent_activity_publish", + key: "env-1:key-1", + }); + }).pipe( + provideWorkerEnvironment, + Effect.provide( + RateLimits.layerCloudflareBindings( + clients({ + agent_activity_publish: { + standard: client(() => + Effect.fail({ + _tag: "RateLimitError", + message: "binding unavailable", + cause: "binding unavailable", + } as never), + ), + trusted: client(() => Effect.succeed({ success: true })), + }, + }), + ), + ), + ), + ); + + it.effect("always denies blocked users without calling Cloudflare", () => + Effect.gen(function* () { + const rateLimits = yield* RateLimits.RateLimits; + const error = yield* Effect.flip( + rateLimits.check({ + operation: "mobile_registration", + key: "user-1", + tier: "blocked", + }), + ); + expect(error.operation).toBe("mobile_registration"); + }).pipe( + provideWorkerEnvironment, + Effect.provide(RateLimits.layerCloudflareBindings(clients())), + ), + ); +}); diff --git a/infra/relay/src/rateLimits/RateLimits.ts b/infra/relay/src/rateLimits/RateLimits.ts new file mode 100644 index 0000000000..2a730e2639 --- /dev/null +++ b/infra/relay/src/rateLimits/RateLimits.ts @@ -0,0 +1,88 @@ +import type * as Cloudflare from "alchemy/Cloudflare"; +import * as Context from "effect/Context"; +import * as Data from "effect/Data"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; + +import type { RelayRateLimitTier } from "@t3tools/contracts/relay"; + +export const RELAY_RATE_LIMITS = { + token_exchange: { limit: 20, period: 60 }, + link_challenge: { limit: 10, period: 60 }, + managed_endpoint_provision: { limit: 5, period: 60 }, + environment_connect: { limit: 20, period: 60 }, + environment_status: { limit: 30, period: 60 }, + mobile_registration: { limit: 10, period: 60 }, + agent_activity_publish: { limit: 60, period: 10 }, +} as const; + +export type RelayRateLimitOperation = keyof typeof RELAY_RATE_LIMITS; +type ActiveRelayRateLimitTier = Exclude; + +export class RelayRateLimitExceeded extends Data.TaggedError("RelayRateLimitExceeded")<{ + readonly operation: RelayRateLimitOperation; + readonly retryAfterSeconds: number; +}> {} + +export type RelayRateLimitClients = Readonly< + Record< + RelayRateLimitOperation, + Readonly> + > +>; + +export interface RateLimitsShape { + readonly check: (input: { + readonly operation: RelayRateLimitOperation; + readonly key: string; + readonly tier?: RelayRateLimitTier; + }) => Effect.Effect; +} + +export class RateLimits extends Context.Service()( + "t3code-relay/rateLimits/RateLimits", +) {} + +export const layerCloudflareBindings = (clients: RelayRateLimitClients) => + Layer.succeed( + RateLimits, + RateLimits.of({ + check: Effect.fn("relay.rate_limits.check")(function* (input) { + const tier = input.tier ?? "standard"; + const config = RELAY_RATE_LIMITS[input.operation]; + yield* Effect.annotateCurrentSpan({ + "relay.rate_limit.operation": input.operation, + "relay.rate_limit.tier": tier, + }); + if (tier === "blocked") { + return yield* new RelayRateLimitExceeded({ + operation: input.operation, + retryAfterSeconds: config.period, + }); + } + const result = yield* clients[input.operation][tier].limit({ key: input.key }).pipe( + Effect.tapError((cause) => + Effect.logWarning("relay rate limit binding failed open", { + cause, + operation: input.operation, + tier, + }), + ), + Effect.orElseSucceed(() => ({ success: true })), + ); + if (!result.success) { + return yield* new RelayRateLimitExceeded({ + operation: input.operation, + retryAfterSeconds: config.period, + }); + } + }), + }), + ); + +export const layerAllowAll = Layer.succeed( + RateLimits, + RateLimits.of({ + check: () => Effect.void, + }), +); diff --git a/infra/relay/src/worker.ts b/infra/relay/src/worker.ts index 8f00cc452f..faa678c3ea 100644 --- a/infra/relay/src/worker.ts +++ b/infra/relay/src/worker.ts @@ -54,6 +54,9 @@ import * as EnvironmentLinker from "./environments/EnvironmentLinker.ts"; import * as EnvironmentPublishSignatures from "./environments/EnvironmentPublishSignatures.ts"; import * as ManagedEndpointProvider from "./environments/ManagedEndpointProvider.ts"; import * as MobileRegistrations from "./agentActivity/MobileRegistrations.ts"; +import * as Entitlements from "./entitlements/Entitlements.ts"; +import * as RateLimits from "./rateLimits/RateLimits.ts"; +import * as Maintenance from "./maintenance/Maintenance.ts"; const webcryptoLayer = Layer.succeed( Crypto.Crypto, @@ -88,6 +91,22 @@ const ApnsDeliveryJobSigningSecret = Alchemy.makeRandom("ApnsDeliveryJobSigningS bytes: 32, }); +function bindRelayRateLimit( + stage: string, + operation: RateLimits.RelayRateLimitOperation, + tier: "standard" | "trusted", +) { + const config = RateLimits.RELAY_RATE_LIMITS[operation]; + return Cloudflare.RateLimit({ + name: `RATE_LIMIT_${operation.toUpperCase()}_${tier.toUpperCase()}`, + namespaceId: `${stage}:relay:${operation}:${tier}`, + simple: { + limit: tier === "trusted" ? config.limit * 4 : config.limit, + period: config.period, + }, + }).asEffect(); +} + export default class Api extends Cloudflare.Worker()( "Api", RelayDeploymentConfig.pipe( @@ -143,6 +162,36 @@ export default class Api extends Cloudflare.Worker()( const managedEndpointTunnelBinding = yield* Cloudflare.TunnelReadWrite.bind(); const managedEndpointDnsBinding = yield* Cloudflare.DnsReadWrite.bind(managedEndpointZone); const managedEndpointZoneName = yield* managedEndpointZone.name; + const rateLimitClients = yield* Effect.all({ + token_exchange: Effect.all({ + standard: bindRelayRateLimit(stage, "token_exchange", "standard"), + trusted: bindRelayRateLimit(stage, "token_exchange", "trusted"), + }), + link_challenge: Effect.all({ + standard: bindRelayRateLimit(stage, "link_challenge", "standard"), + trusted: bindRelayRateLimit(stage, "link_challenge", "trusted"), + }), + managed_endpoint_provision: Effect.all({ + standard: bindRelayRateLimit(stage, "managed_endpoint_provision", "standard"), + trusted: bindRelayRateLimit(stage, "managed_endpoint_provision", "trusted"), + }), + environment_connect: Effect.all({ + standard: bindRelayRateLimit(stage, "environment_connect", "standard"), + trusted: bindRelayRateLimit(stage, "environment_connect", "trusted"), + }), + environment_status: Effect.all({ + standard: bindRelayRateLimit(stage, "environment_status", "standard"), + trusted: bindRelayRateLimit(stage, "environment_status", "trusted"), + }), + mobile_registration: Effect.all({ + standard: bindRelayRateLimit(stage, "mobile_registration", "standard"), + trusted: bindRelayRateLimit(stage, "mobile_registration", "trusted"), + }), + agent_activity_publish: Effect.all({ + standard: bindRelayRateLimit(stage, "agent_activity_publish", "standard"), + trusted: bindRelayRateLimit(stage, "agent_activity_publish", "trusted"), + }), + }); // // 3. Runtime layers and app construction @@ -178,8 +227,10 @@ export default class Api extends Cloudflare.Worker()( }).pipe(Effect.map(makeRelayTraceLayer)), ); - const runtimeLayer = Layer.empty.pipe( + const relayServiceLayer = Layer.empty.pipe( Layer.provideMerge(MobileRegistrations.layer), + Layer.provideMerge(Maintenance.layer), + Layer.provideMerge(RateLimits.layerCloudflareBindings(rateLimitClients)), Layer.provideMerge(AgentActivityPublisher.layer), Layer.provideMerge(EnvironmentConnector.layer), Layer.provideMerge(EnvironmentLinker.layer), @@ -206,8 +257,12 @@ export default class Api extends Cloudflare.Worker()( ManagedEndpointAllocations.ManagedEndpointAllocations.layer, ), ), + Layer.provideMerge(Entitlements.layer), Layer.provideMerge(LiveActivities.layer), Layer.provideMerge(DeliveryAttempts.layer), + ); + + const runtimeLayer = relayServiceLayer.pipe( Layer.provideMerge(RelayTokens.layer), Layer.provideMerge(Layer.succeed(RelayDb, db)), Layer.provideMerge(Layer.effect(RelayConfiguration.RelayConfiguration, loadSettings)), @@ -242,8 +297,14 @@ export default class Api extends Cloudflare.Worker()( ); yield* Cloudflare.cron("*/5 * * * *").subscribe(() => - DpopProofs.DpopProofReplay.pipe( - Effect.flatMap((dpopProofs) => dpopProofs.pruneExpired), + Effect.all([ + DpopProofs.DpopProofReplay.pipe(Effect.flatMap((dpopProofs) => dpopProofs.pruneExpired)), + ManagedEndpointProvider.ManagedEndpointProvider.pipe( + Effect.flatMap((provider) => provider.reconcileDeprovisioning), + ), + Maintenance.Maintenance.pipe(Effect.flatMap((maintenance) => maintenance.pruneExpired)), + ]).pipe( + Effect.asVoid, Effect.withSpan("relay.cron.prune_expired_dpop_proofs"), Effect.provide(runtimeLayer), ), @@ -274,6 +335,7 @@ export default class Api extends Cloudflare.Worker()( Layer.provideMerge(Cloudflare.QueueEventSourceLive), Layer.provideMerge(Cloudflare.TunnelReadWriteLive), Layer.provideMerge(Cloudflare.DnsReadWriteLive), + Layer.provideMerge(Cloudflare.RateLimitBindingLive), ), ), ), diff --git a/packages/contracts/src/relay.ts b/packages/contracts/src/relay.ts index 11b30ac3ee..13578621f7 100644 --- a/packages/contracts/src/relay.ts +++ b/packages/contracts/src/relay.ts @@ -321,6 +321,27 @@ export const RelayInternalErrorReason = Schema.Literals([ ]); export type RelayInternalErrorReason = typeof RelayInternalErrorReason.Type; +export const RelayQuotaResource = Schema.Literals([ + "managed_endpoints", + "mobile_devices", + "active_agent_threads", +]); +export type RelayQuotaResource = typeof RelayQuotaResource.Type; + +export const RelayRateLimitOperation = Schema.Literals([ + "token_exchange", + "link_challenge", + "managed_endpoint_provision", + "environment_connect", + "environment_status", + "mobile_registration", + "agent_activity_publish", +]); +export type RelayRateLimitOperation = typeof RelayRateLimitOperation.Type; + +export const RelayRateLimitTier = Schema.Literals(["standard", "trusted", "blocked"]); +export type RelayRateLimitTier = typeof RelayRateLimitTier.Type; + export class RelayAuthInvalidError extends Schema.TaggedErrorClass()( "RelayAuthInvalidError", { @@ -427,6 +448,28 @@ export class RelayInternalError extends Schema.TaggedErrorClass()( + "RelayQuotaExceededError", + { + code: Schema.Literal("quota_exceeded"), + resource: RelayQuotaResource, + limit: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)), + traceId: TrimmedNonEmptyString, + }, + { httpApiStatus: 409 }, +) {} + +export class RelayRateLimitedError extends Schema.TaggedErrorClass()( + "RelayRateLimitedError", + { + code: Schema.Literal("rate_limited"), + operation: RelayRateLimitOperation, + retryAfterSeconds: Schema.Int.check(Schema.isGreaterThan(0)), + traceId: TrimmedNonEmptyString, + }, + { httpApiStatus: 429 }, +) {} + export const RelayProtectedError = Schema.Union([ RelayAuthInvalidError, RelayEnvironmentLinkProofExpiredError, @@ -439,17 +482,28 @@ export const RelayProtectedError = Schema.Union([ RelayAgentActivityPublishProofExpiredError, RelayAgentActivityPublishProofInvalidError, RelayInternalError, + RelayQuotaExceededError, + RelayRateLimitedError, ]); export type RelayProtectedError = typeof RelayProtectedError.Type; const RelayAuthAndInternalErrors = [RelayAuthInvalidError, RelayInternalError] as const; +const RelayMobileErrors = [ + RelayAuthInvalidError, + RelayQuotaExceededError, + RelayRateLimitedError, + RelayInternalError, +] as const; + const RelayEnvironmentLinkErrors = [ RelayAuthInvalidError, RelayEnvironmentLinkProofExpiredError, RelayEnvironmentLinkProofInvalidError, RelayEnvironmentLinkUnavailableError, RelayEnvironmentLinkFailedError, + RelayQuotaExceededError, + RelayRateLimitedError, RelayInternalError, ] as const; @@ -458,6 +512,7 @@ const RelayEnvironmentConnectErrors = [ RelayEnvironmentConnectNotAuthorizedError, RelayEnvironmentEndpointUnavailableError, RelayEnvironmentEndpointTimedOutError, + RelayRateLimitedError, RelayInternalError, ] as const; @@ -465,6 +520,8 @@ const RelayAgentActivityPublishErrors = [ RelayAuthInvalidError, RelayAgentActivityPublishProofExpiredError, RelayAgentActivityPublishProofInvalidError, + RelayQuotaExceededError, + RelayRateLimitedError, RelayInternalError, ] as const; @@ -473,6 +530,7 @@ export interface RelayClientPrincipalShape { readonly token: string; readonly proofKeyThumbprint?: string; readonly dpopScopes?: ReadonlyArray; + readonly rateLimitTier?: RelayRateLimitTier; } export class RelayClientPrincipal extends Context.Service< @@ -808,7 +866,7 @@ export const RelayRegisterDeviceEndpoint = HttpApiEndpoint.post( headers: RelayDpopRequestHeaders, payload: RelayDeviceRegistrationRequest, success: RelayOkResponse, - error: RelayAuthAndInternalErrors, + error: RelayMobileErrors, }, ).annotate(OpenApi.Summary, "Register or update a mobile device"); @@ -819,7 +877,7 @@ export const RelayRegisterLiveActivityEndpoint = HttpApiEndpoint.post( headers: RelayDpopRequestHeaders, payload: RelayLiveActivityRegistrationRequest, success: RelayOkResponse, - error: RelayAuthAndInternalErrors, + error: RelayMobileErrors, }, ).annotate(OpenApi.Summary, "Register a Live Activity push token"); @@ -830,7 +888,7 @@ export const RelayUnregisterDeviceEndpoint = HttpApiEndpoint.delete( headers: RelayDpopRequestHeaders, params: RelayDeviceUnregistrationParams, success: RelayOkResponse, - error: RelayAuthAndInternalErrors, + error: RelayMobileErrors, }, ).annotate(OpenApi.Summary, "Unregister a mobile device"); @@ -868,7 +926,7 @@ export const RelayClientGroup = HttpApiGroup.make("client") headers: RelayBearerRequestHeaders, payload: RelayEnvironmentLinkChallengeRequest, success: RelayEnvironmentLinkChallengeResponse, - error: RelayAuthAndInternalErrors, + error: [RelayAuthInvalidError, RelayRateLimitedError, RelayInternalError], }, ).annotate(OpenApi.Summary, "Create an environment-link challenge"), HttpApiEndpoint.delete("unlinkEnvironment", "/v1/client/environment-links/:environmentId", { @@ -888,7 +946,7 @@ export const RelayExchangeDpopAccessTokenEndpoint = HttpApiEndpoint.post( headers: RelayDpopProofRequestHeaders, payload: RelayDpopAccessTokenRequest, success: RelayDpopAccessTokenResponse, - error: RelayAuthAndInternalErrors, + error: [RelayAuthInvalidError, RelayRateLimitedError, RelayInternalError], }, ) .annotate(OpenApi.Summary, "Exchange a Clerk token for a DPoP access token")