From 46afa39c29113783ed5c0c48a1ed35ace41b91c2 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Wed, 3 Jun 2026 20:08:25 -0700 Subject: [PATCH] refactor(relay): clean up resource limit enforcement Co-authored-by: codex --- .../agentActivity/AgentActivityPublisher.ts | 3 +- .../agentActivity/AgentActivityRows.test.ts | 3 +- .../src/agentActivity/AgentActivityRows.ts | 25 ++--- infra/relay/src/agentActivity/Devices.test.ts | 3 +- infra/relay/src/agentActivity/Devices.ts | 7 +- .../src/agentActivity/MobileRegistrations.ts | 7 +- infra/relay/src/entitlements/Entitlements.ts | 16 +-- .../src/environments/EnvironmentLinks.ts | 13 ++- .../ManagedEndpointAllocations.test.ts | 59 +++++++++- .../ManagedEndpointAllocations.ts | 33 +++++- .../environments/ManagedEndpointProvider.ts | 6 +- infra/relay/src/http/Api.ts | 102 +++++++++++------- infra/relay/src/rateLimits/RateLimits.test.ts | 12 +++ infra/relay/src/rateLimits/RateLimits.ts | 23 +++- infra/relay/src/resourceLimits.ts | 12 +++ infra/relay/src/worker.ts | 40 ++----- packages/contracts/src/relay.ts | 8 +- 17 files changed, 246 insertions(+), 126 deletions(-) create mode 100644 infra/relay/src/resourceLimits.ts diff --git a/infra/relay/src/agentActivity/AgentActivityPublisher.ts b/infra/relay/src/agentActivity/AgentActivityPublisher.ts index 97369dcdfc..8defc1ed32 100644 --- a/infra/relay/src/agentActivity/AgentActivityPublisher.ts +++ b/infra/relay/src/agentActivity/AgentActivityPublisher.ts @@ -14,10 +14,11 @@ import * as AgentActivityRows from "./AgentActivityRows.ts"; import * as EnvironmentLinks from "../environments/EnvironmentLinks.ts"; import * as LiveActivities from "./LiveActivities.ts"; import * as ApnsDeliveries from "./ApnsDeliveries.ts"; +import * as ResourceLimits from "../resourceLimits.ts"; export type AgentActivityPublishError = | AgentActivityRows.AgentActivityRowUpsertPersistenceError - | AgentActivityRows.AgentActivityRowQuotaExceeded + | ResourceLimits.ResourceQuotaExceeded | AgentActivityRows.AgentActivityRowDeletePersistenceError | AgentActivityRows.AgentActivityRowListPersistenceError | EnvironmentLinks.EnvironmentLinkUserListPersistenceError diff --git a/infra/relay/src/agentActivity/AgentActivityRows.test.ts b/infra/relay/src/agentActivity/AgentActivityRows.test.ts index eb519756c7..e9cf81d6ad 100644 --- a/infra/relay/src/agentActivity/AgentActivityRows.test.ts +++ b/infra/relay/src/agentActivity/AgentActivityRows.test.ts @@ -4,6 +4,7 @@ import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; import { RelayDb, type RelayDatabase } from "../db.ts"; +import * as ResourceLimits from "../resourceLimits.ts"; import * as AgentActivityRows from "./AgentActivityRows.ts"; const state: RelayAgentActivityState = { @@ -52,7 +53,7 @@ describe("AgentActivityRows", () => { ); expect(error).toEqual( - new AgentActivityRows.AgentActivityRowQuotaExceeded({ + new ResourceLimits.ResourceQuotaExceeded({ resource: "active_agent_threads", limit: 50, }), diff --git a/infra/relay/src/agentActivity/AgentActivityRows.ts b/infra/relay/src/agentActivity/AgentActivityRows.ts index 9562810b66..93e870e492 100644 --- a/infra/relay/src/agentActivity/AgentActivityRows.ts +++ b/infra/relay/src/agentActivity/AgentActivityRows.ts @@ -12,6 +12,7 @@ import { and, count, desc, eq, isNull } from "drizzle-orm"; import { RelayDb } from "../db.ts"; import { relayAgentActivityRows, relayEnvironmentLinks } from "../persistence/schema.ts"; +import * as ResourceLimits from "../resourceLimits.ts"; export class AgentActivityRowUpsertPersistenceError extends Data.TaggedError( "AgentActivityRowUpsertPersistenceError", @@ -31,20 +32,14 @@ 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< + void, + AgentActivityRowUpsertPersistenceError | ResourceLimits.ResourceQuotaExceeded + >; readonly remove: (input: { readonly environmentId: string; readonly environmentPublicKey: string; @@ -102,10 +97,12 @@ const make = Effect.gen(function* () { .select({ value: count() }) .from(relayAgentActivityRows) .where(keyCondition); - if ((rows[0]?.value ?? 0) >= MAX_ACTIVE_AGENT_THREADS_PER_ENVIRONMENT) { - return yield* new AgentActivityRowQuotaExceeded({ + if ( + (rows[0]?.value ?? 0) >= ResourceLimits.MAX_ACTIVE_AGENT_THREADS_PER_ENVIRONMENT + ) { + return yield* new ResourceLimits.ResourceQuotaExceeded({ resource: "active_agent_threads", - limit: MAX_ACTIVE_AGENT_THREADS_PER_ENVIRONMENT, + limit: ResourceLimits.MAX_ACTIVE_AGENT_THREADS_PER_ENVIRONMENT, }); } } @@ -134,7 +131,7 @@ const make = Effect.gen(function* () { ); }, Effect.mapError((cause) => - cause instanceof AgentActivityRowQuotaExceeded + cause instanceof ResourceLimits.ResourceQuotaExceeded ? cause : new AgentActivityRowUpsertPersistenceError({ cause }), ), diff --git a/infra/relay/src/agentActivity/Devices.test.ts b/infra/relay/src/agentActivity/Devices.test.ts index fd38bd957e..dc4aa27bcd 100644 --- a/infra/relay/src/agentActivity/Devices.test.ts +++ b/infra/relay/src/agentActivity/Devices.test.ts @@ -9,6 +9,7 @@ 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"; +import * as ResourceLimits from "../resourceLimits.ts"; const registration: RelayDeviceRegistrationRequest = { deviceId: "device-1" as RelayDeviceRegistrationRequest["deviceId"], @@ -74,7 +75,7 @@ describe("Devices", () => { const error = yield* Effect.flip(devices.register({ userId: "user-2", registration })); expect(error).toEqual( - new Entitlements.UserResourceQuotaExceeded({ + new ResourceLimits.ResourceQuotaExceeded({ resource: "mobile_devices", limit: 5, }), diff --git a/infra/relay/src/agentActivity/Devices.ts b/infra/relay/src/agentActivity/Devices.ts index ea11a4037d..ced4580e40 100644 --- a/infra/relay/src/agentActivity/Devices.ts +++ b/infra/relay/src/agentActivity/Devices.ts @@ -13,6 +13,7 @@ import { sql } from "drizzle-orm"; import { RelayDb } from "../db.ts"; import * as Entitlements from "../entitlements/Entitlements.ts"; import { relayLiveActivities, relayMobileDevices } from "../persistence/schema.ts"; +import * as ResourceLimits from "../resourceLimits.ts"; export class DeviceRegistrationPersistenceError extends Data.TaggedError( "DeviceRegistrationPersistenceError", @@ -36,7 +37,7 @@ export interface DevicesShape { readonly registration: RelayDeviceRegistrationRequest; }) => Effect.Effect< void, - DeviceRegistrationPersistenceError | Entitlements.UserResourceQuotaExceeded + DeviceRegistrationPersistenceError | ResourceLimits.ResourceQuotaExceeded >; readonly unregister: (input: { readonly userId: string; @@ -83,7 +84,7 @@ const make = Effect.gen(function* () { .from(relayMobileDevices) .where(eq(relayMobileDevices.userId, input.userId)); if ((deviceCounts[0]?.value ?? 0) >= effective.mobileDeviceLimit) { - return yield* new Entitlements.UserResourceQuotaExceeded({ + return yield* new ResourceLimits.ResourceQuotaExceeded({ resource: "mobile_devices", limit: effective.mobileDeviceLimit, }); @@ -143,7 +144,7 @@ const make = Effect.gen(function* () { ); }, Effect.mapError((cause) => - cause instanceof Entitlements.UserResourceQuotaExceeded + cause instanceof ResourceLimits.ResourceQuotaExceeded ? cause : new DeviceRegistrationPersistenceError({ cause }), ), diff --git a/infra/relay/src/agentActivity/MobileRegistrations.ts b/infra/relay/src/agentActivity/MobileRegistrations.ts index a2fb185570..7539abb035 100644 --- a/infra/relay/src/agentActivity/MobileRegistrations.ts +++ b/infra/relay/src/agentActivity/MobileRegistrations.ts @@ -9,12 +9,11 @@ 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"; +import * as ResourceLimits from "../resourceLimits.ts"; export type MobileRegistrationError = | Devices.DeviceRegistrationPersistenceError - | Devices.DeviceUnregistrationPersistenceError - | Entitlements.UserResourceQuotaExceeded + | ResourceLimits.ResourceQuotaExceeded | LiveActivities.LiveActivityRegistrationPersistenceError; export interface MobileRegistrationsShape { @@ -29,7 +28,7 @@ export interface MobileRegistrationsShape { readonly unregisterDevice: (input: { readonly userId: string; readonly deviceId: string; - }) => Effect.Effect<{ readonly ok: true }, MobileRegistrationError>; + }) => Effect.Effect<{ readonly ok: true }, Devices.DeviceUnregistrationPersistenceError>; } export class MobileRegistrations extends Context.Service< diff --git a/infra/relay/src/entitlements/Entitlements.ts b/infra/relay/src/entitlements/Entitlements.ts index 2d06401e90..d1bcf4ceb4 100644 --- a/infra/relay/src/entitlements/Entitlements.ts +++ b/infra/relay/src/entitlements/Entitlements.ts @@ -9,11 +9,7 @@ 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"; +import * as ResourceLimits from "../resourceLimits.ts"; export interface EffectiveUserEntitlements { readonly managedEndpointLimit: number; @@ -27,11 +23,6 @@ export class UserEntitlementPersistenceError extends Data.TaggedError( readonly cause: unknown; }> {} -export class UserResourceQuotaExceeded extends Data.TaggedError("UserResourceQuotaExceeded")<{ - readonly resource: RelayQuotaResource; - readonly limit: number; -}> {} - export interface EntitlementsShape { readonly getEffectiveForUser: ( userId: string, @@ -70,8 +61,9 @@ const make = Effect.gen(function* () { .limit(1); const row = rows[0]; return { - managedEndpointLimit: row?.managedEndpointLimit ?? DEFAULT_MANAGED_ENDPOINT_LIMIT, - mobileDeviceLimit: row?.mobileDeviceLimit ?? DEFAULT_MOBILE_DEVICE_LIMIT, + managedEndpointLimit: + row?.managedEndpointLimit ?? ResourceLimits.DEFAULT_MANAGED_ENDPOINT_LIMIT, + mobileDeviceLimit: row?.mobileDeviceLimit ?? ResourceLimits.DEFAULT_MOBILE_DEVICE_LIMIT, rateLimitTier: row?.rateLimitTier ?? "standard", }; }, diff --git a/infra/relay/src/environments/EnvironmentLinks.ts b/infra/relay/src/environments/EnvironmentLinks.ts index c540099534..1cb8651c19 100644 --- a/infra/relay/src/environments/EnvironmentLinks.ts +++ b/infra/relay/src/environments/EnvironmentLinks.ts @@ -13,6 +13,7 @@ import { and, eq, isNull, or } from "drizzle-orm"; import { RelayDb } from "../db.ts"; import { relayEnvironmentLinks } from "../persistence/schema.ts"; +import * as ResourceLimits from "../resourceLimits.ts"; export interface RelayLinkedEnvironmentRecord extends RelayClientEnvironmentRecord { readonly environmentPublicKey: string; @@ -60,8 +61,6 @@ 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; @@ -200,10 +199,10 @@ const make = Effect.gen(function* () { }) .from(relayEnvironmentLinks) .where(agentAwarenessDeliveryUserKeyCondition(input)) - .limit(MAX_AGENT_AWARENESS_DELIVERY_USERS + 1) + .limit(ResourceLimits.MAX_AGENT_AWARENESS_DELIVERY_USERS + 1) .pipe( Effect.flatMap((rows) => - rows.length > MAX_AGENT_AWARENESS_DELIVERY_USERS + rows.length > ResourceLimits.MAX_AGENT_AWARENESS_DELIVERY_USERS ? Effect.fail( new EnvironmentLinkUserListPersistenceError({ cause: new Error("Agent-awareness delivery fanout limit exceeded."), @@ -218,7 +217,11 @@ const make = Effect.gen(function* () { liveActivitiesEnabled: row.liveActivitiesEnabled, })), ), - Effect.mapError((cause) => new EnvironmentLinkUserListPersistenceError({ cause })), + Effect.mapError((cause) => + cause instanceof EnvironmentLinkUserListPersistenceError + ? cause + : new EnvironmentLinkUserListPersistenceError({ cause }), + ), ); }), diff --git a/infra/relay/src/environments/ManagedEndpointAllocations.test.ts b/infra/relay/src/environments/ManagedEndpointAllocations.test.ts index ea38244d1d..b4b009938d 100644 --- a/infra/relay/src/environments/ManagedEndpointAllocations.test.ts +++ b/infra/relay/src/environments/ManagedEndpointAllocations.test.ts @@ -4,6 +4,7 @@ import * as Layer from "effect/Layer"; import { RelayDb, type RelayDatabase } from "../db.ts"; import * as Entitlements from "../entitlements/Entitlements.ts"; +import * as ResourceLimits from "../resourceLimits.ts"; import * as ManagedEndpointAllocations from "./ManagedEndpointAllocations.ts"; function testLayer(fakeDb: RelayDatabase, managedEndpointLimit = 3) { @@ -60,7 +61,7 @@ describe("ManagedEndpointAllocations", () => { ); expect(error).toEqual( - new Entitlements.UserResourceQuotaExceeded({ + new ResourceLimits.ResourceQuotaExceeded({ resource: "managed_endpoints", limit: 3, }), @@ -106,4 +107,60 @@ describe("ManagedEndpointAllocations", () => { ).toEqual(existing); }).pipe(Effect.provide(testLayer(fakeDb, 0))); }); + + it.effect("reactivates an existing reservation before provisioning retries", () => { + const existing: ManagedEndpointAllocations.ManagedEndpointAllocation = { + userId: "user-1", + environmentId: "env-1", + hostname: "env-1.example.test", + tunnelName: "tunnel-env-1", + tunnelId: "tunnel-1", + dnsRecordId: "dns-1", + readyAt: "2026-06-01T00:00:00.000Z", + deprovisionRequestedAt: "2026-06-02T00:00:00.000Z", + lastDeprovisionAttemptAt: "2026-06-02T00:01:00.000Z", + lastDeprovisionError: "upstream unavailable", + }; + const reactivated = { + ...existing, + readyAt: null, + deprovisionRequestedAt: null, + lastDeprovisionAttemptAt: null, + lastDeprovisionError: null, + }; + let updated = false; + const fakeDb = { + select: () => ({ + from: () => ({ + where: () => ({ + limit: () => Effect.succeed([existing]), + }), + }), + }), + update: () => ({ + set: () => ({ + where: () => ({ + returning: () => + Effect.sync(() => { + updated = true; + return [reactivated]; + }), + }), + }), + }), + } 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(reactivated); + expect(updated).toBe(true); + }).pipe(Effect.provide(testLayer(fakeDb, 0))); + }); }); diff --git a/infra/relay/src/environments/ManagedEndpointAllocations.ts b/infra/relay/src/environments/ManagedEndpointAllocations.ts index be5d670a17..e5b693e817 100644 --- a/infra/relay/src/environments/ManagedEndpointAllocations.ts +++ b/infra/relay/src/environments/ManagedEndpointAllocations.ts @@ -10,6 +10,7 @@ import { RelayDb } from "../db.ts"; import { isManagedEndpointHostname, managedEndpointForHostname } from "../deploymentConfig.ts"; import * as Entitlements from "../entitlements/Entitlements.ts"; import { relayEnvironmentLinks, relayManagedEndpointAllocations } from "../persistence/schema.ts"; +import * as ResourceLimits from "../resourceLimits.ts"; export interface ManagedEndpointAllocation { readonly userId: string; @@ -77,7 +78,7 @@ export interface ManagedEndpointAllocationsShape { input: ReserveManagedEndpointAllocationInput, ) => Effect.Effect< ManagedEndpointAllocation, - ManagedEndpointAllocationPersistenceError | Entitlements.UserResourceQuotaExceeded + ManagedEndpointAllocationPersistenceError | ResourceLimits.ResourceQuotaExceeded >; readonly recordTunnel: ( input: RecordManagedEndpointTunnelInput, @@ -133,7 +134,7 @@ const persistenceError = (cause: unknown) => : new ManagedEndpointAllocationPersistenceError({ cause }); const reservationError = (cause: unknown) => - cause instanceof Entitlements.UserResourceQuotaExceeded ? cause : persistenceError(cause); + cause instanceof ResourceLimits.ResourceQuotaExceeded ? cause : persistenceError(cause); const make = Effect.gen(function* () { const db = yield* RelayDb; @@ -153,6 +154,30 @@ const make = Effect.gen(function* () { ); }); + const reactivate = Effect.fn("relay.managed_endpoint_allocations.reactivate")(function* ( + input: ManagedEndpointAllocationKey, + ) { + const reactivated = yield* db + .update(relayManagedEndpointAllocations) + .set({ + readyAt: null, + deprovisionRequestedAt: null, + lastDeprovisionAttemptAt: null, + lastDeprovisionError: null, + updatedAt: DateTime.formatIso(yield* DateTime.now), + }) + .where(whereAllocation(input)) + .returning(allocationSelection) + .pipe(Effect.mapError(persistenceError)); + const allocation = reactivated[0]; + if (allocation === undefined) { + return yield* new ManagedEndpointAllocationPersistenceError({ + cause: new Error("Managed endpoint allocation was not reactivated."), + }); + } + return allocation; + }); + return ManagedEndpointAllocations.of({ get, reserve: Effect.fn("relay.managed_endpoint_allocations.reserve")(function* ( @@ -163,7 +188,7 @@ const make = Effect.gen(function* () { Effect.gen(function* () { const existing = yield* get(input); if (existing !== null) { - return existing; + return existing.deprovisionRequestedAt === null ? existing : yield* reactivate(input); } const effective = yield* entitlements.getEffectiveForUser(input.userId); const allocationCounts = yield* db @@ -172,7 +197,7 @@ const make = Effect.gen(function* () { .where(eq(relayManagedEndpointAllocations.userId, input.userId)) .pipe(Effect.mapError(persistenceError)); if ((allocationCounts[0]?.value ?? 0) >= effective.managedEndpointLimit) { - return yield* new Entitlements.UserResourceQuotaExceeded({ + return yield* new ResourceLimits.ResourceQuotaExceeded({ resource: "managed_endpoints", limit: effective.managedEndpointLimit, }); diff --git a/infra/relay/src/environments/ManagedEndpointProvider.ts b/infra/relay/src/environments/ManagedEndpointProvider.ts index 7bb7277c45..6504daa397 100644 --- a/infra/relay/src/environments/ManagedEndpointProvider.ts +++ b/infra/relay/src/environments/ManagedEndpointProvider.ts @@ -18,7 +18,7 @@ import type { } from "@t3tools/contracts/relay"; import * as RelayConfiguration from "../Config.ts"; -import * as Entitlements from "../entitlements/Entitlements.ts"; +import * as ResourceLimits from "../resourceLimits.ts"; import { managedEndpointDigestInput, managedEndpointForHostname, @@ -54,7 +54,7 @@ export type ManagedEndpointProviderError = | ManagedEndpointProvisioningNotConfigured | ManagedEndpointProvisioningFailed | ManagedEndpointOriginNotAllowed - | Entitlements.UserResourceQuotaExceeded; + | ResourceLimits.ResourceQuotaExceeded; export interface ManagedEndpointProvisioningResult { readonly endpoint: RelayManagedEndpoint; @@ -381,7 +381,7 @@ const make = Effect.gen(function* () { }) .pipe( Effect.mapError((cause) => - cause instanceof Entitlements.UserResourceQuotaExceeded + cause instanceof ResourceLimits.ResourceQuotaExceeded ? cause : new ManagedEndpointProvisioningFailed({ cause }), ), diff --git a/infra/relay/src/http/Api.ts b/infra/relay/src/http/Api.ts index c32c2197e1..f49d047546 100644 --- a/infra/relay/src/http/Api.ts +++ b/infra/relay/src/http/Api.ts @@ -42,6 +42,7 @@ import { RelayEnvironmentLinkProofInvalidError, RelayEnvironmentLinkUnavailableError, RelayEnvironmentPrincipal, + type RelayClientPrincipalShape, type RelayEnvironmentConnectRequest, type RelayDpopAccessTokenScope, RelayInternalError, @@ -70,6 +71,7 @@ import { withSpanAttributes } from "../observability.ts"; import { RelayDb } from "../db.ts"; import * as Entitlements from "../entitlements/Entitlements.ts"; import * as RateLimits from "../rateLimits/RateLimits.ts"; +import * as ResourceLimits from "../resourceLimits.ts"; const relayCorsAllowedMethods = ["GET", "POST", "DELETE", "OPTIONS"] as const; const relayCorsAllowedHeaders = [ @@ -332,8 +334,8 @@ const checkDpopUserRateLimit = Effect.fnUntraced(function* ( rateLimits: RateLimits.RateLimitsShape, operation: RateLimits.RelayRateLimitOperation, key: string, + principal: RelayClientPrincipalShape, ) { - const principal = yield* RelayClientPrincipal; yield* rateLimits.check({ operation, key, @@ -341,6 +343,37 @@ const checkDpopUserRateLimit = Effect.fnUntraced(function* ( }); }); +const authorizeDpopPrincipal = Effect.fnUntraced(function* ( + dpopProofs: DpopProofs.DpopProofReplayShape, + scope: RelayDpopAccessTokenScope, + principal: RelayClientPrincipalShape, +) { + const proofKeyThumbprint = yield* requireDpopPrincipalScope(scope); + yield* requireDpopThumbprint(proofKeyThumbprint, { + expectedAccessToken: principal.token, + }).pipe(Effect.provideService(DpopProofs.DpopProofReplay, dpopProofs)); + return { ...principal, proofKeyThumbprint }; +}); + +const authorizeDpopRequest = Effect.fnUntraced(function* ( + dpopProofs: DpopProofs.DpopProofReplayShape, + scope: RelayDpopAccessTokenScope, +) { + return yield* authorizeDpopPrincipal(dpopProofs, scope, yield* RelayClientPrincipal); +}); + +const authorizeRateLimitedDpopRequest = Effect.fnUntraced(function* ( + dpopProofs: DpopProofs.DpopProofReplayShape, + rateLimits: RateLimits.RateLimitsShape, + operation: RateLimits.RelayRateLimitOperation, + keyForPrincipal: (principal: RelayClientPrincipalShape) => string, + scope: RelayDpopAccessTokenScope, +) { + const principal = yield* RelayClientPrincipal; + yield* checkDpopUserRateLimit(rateLimits, operation, keyForPrincipal(principal), principal); + return yield* authorizeDpopPrincipal(dpopProofs, scope, principal); +}); + export const metadataApi = HttpApiBuilder.group( RelayApi, "metadata", @@ -410,12 +443,13 @@ export const mobileApi = HttpApiBuilder.group( "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, - }).pipe(Effect.provideService(DpopProofs.DpopProofReplay, dpopProofs)); + const { userId } = yield* authorizeRateLimitedDpopRequest( + dpopProofs, + rateLimits, + "mobile_registration", + (principal) => principal.userId, + "mobile:registration", + ); return yield* registrations.registerDevice({ userId, payload }); }, mapRelayCommonApiErrors("invalid_dpop")), ) @@ -423,12 +457,13 @@ export const mobileApi = HttpApiBuilder.group( "registerLiveActivity", 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, - }).pipe(Effect.provideService(DpopProofs.DpopProofReplay, dpopProofs)); + const { userId } = yield* authorizeRateLimitedDpopRequest( + dpopProofs, + rateLimits, + "mobile_registration", + (principal) => principal.userId, + "mobile:registration", + ); return yield* registrations.registerLiveActivity({ userId, payload }); }, mapRelayCommonApiErrors("invalid_dpop")), ) @@ -436,12 +471,7 @@ export const mobileApi = HttpApiBuilder.group( "unregisterDevice", 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, - }).pipe(Effect.provideService(DpopProofs.DpopProofReplay, dpopProofs)); + const { userId } = yield* authorizeDpopRequest(dpopProofs, "mobile:registration"); return yield* registrations.unregisterDevice({ userId, deviceId: params.deviceId }); }, mapRelayCommonApiErrors("invalid_dpop")), ); @@ -712,11 +742,13 @@ export const dpopClientApi = HttpApiBuilder.group( function* (args) { const { params, payload } = args; yield* appendRelayCredentialResponseHeaders; - const { userId, token } = yield* RelayClientPrincipal; + const principal = yield* RelayClientPrincipal; + const { userId, token } = principal; yield* checkDpopUserRateLimit( rateLimits, "environment_connect", `${userId}:${params.environmentId}`, + principal, ); const proofKeyThumbprint = yield* requireDpopPrincipalScope("environment:connect"); const requestedThumbprint = resolveConnectClientKeyThumbprint(payload); @@ -765,16 +797,13 @@ export const dpopClientApi = HttpApiBuilder.group( Effect.fn("relay.api.dpopClient.getEnvironmentStatus")( function* (args) { const { params } = args; - const { userId, token } = yield* RelayClientPrincipal; - yield* checkDpopUserRateLimit( + const { userId } = yield* authorizeRateLimitedDpopRequest( + dpopProofs, rateLimits, "environment_status", - `${userId}:${params.environmentId}`, + (principal) => `${principal.userId}:${params.environmentId}`, + "environment:status", ); - const proofKeyThumbprint = yield* requireDpopPrincipalScope("environment:status"); - yield* requireDpopThumbprint(proofKeyThumbprint, { - expectedAccessToken: token, - }).pipe(Effect.provideService(DpopProofs.DpopProofReplay, dpopProofs)); return yield* connector.status({ userId, environmentId: params.environmentId, @@ -909,7 +938,7 @@ const currentTraceId = Effect.currentParentSpan.pipe( Effect.orElseSucceed(() => "unavailable"), ); -const COMMON_AUTH_INVALID_REASONS = [ +const RELAY_COMMON_PERSISTENCE_ERRORS = [ Devices.DeviceRegistrationPersistenceError, Devices.DeviceUnregistrationPersistenceError, Devices.DeviceListPersistenceError, @@ -931,29 +960,25 @@ const COMMON_AUTH_INVALID_REASONS = [ LiveActivities.LiveActivityDeliveryMarkPersistenceError, DeliveryAttempts.DeliveryAttemptRecordPersistenceError, ] as const; -type RelayCommonPersistenceError = InstanceType<(typeof COMMON_AUTH_INVALID_REASONS)[number]>; +type RelayCommonPersistenceError = InstanceType<(typeof RELAY_COMMON_PERSISTENCE_ERRORS)[number]>; type MapRelayCommonApiError = | Exclude< E, | HttpApiError.Unauthorized | RelayCommonPersistenceError - | Entitlements.UserResourceQuotaExceeded - | AgentActivityRows.AgentActivityRowQuotaExceeded + | ResourceLimits.ResourceQuotaExceeded | RateLimits.RelayRateLimitExceeded > | (Extract extends never ? never : RelayAuthInvalidError) | (Extract extends never ? never : RelayInternalError) - | (Extract extends never - ? never - : RelayQuotaExceededError) - | (Extract extends never + | (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); + return RELAY_COMMON_PERSISTENCE_ERRORS.some((ErrorType) => error instanceof ErrorType); } function relayInternalErrorResponse(reason: RelayInternalError["reason"]) { @@ -985,10 +1010,7 @@ function mapRelayCommonApiErrors(authReason: RelayAuthInvalidReason) { }) as MapRelayCommonApiError, ); } - if ( - error instanceof Entitlements.UserResourceQuotaExceeded || - error instanceof AgentActivityRows.AgentActivityRowQuotaExceeded - ) { + if (error instanceof ResourceLimits.ResourceQuotaExceeded) { return yield* Effect.fail( new RelayQuotaExceededError({ code: "quota_exceeded", diff --git a/infra/relay/src/rateLimits/RateLimits.test.ts b/infra/relay/src/rateLimits/RateLimits.test.ts index b5688c4876..9964cc2f43 100644 --- a/infra/relay/src/rateLimits/RateLimits.test.ts +++ b/infra/relay/src/rateLimits/RateLimits.test.ts @@ -30,6 +30,18 @@ function clients( } describe("RateLimits", () => { + it("maps every configured operation", () => { + expect(RateLimits.mapRelayRateLimitOperations((operation) => operation)).toEqual({ + token_exchange: "token_exchange", + link_challenge: "link_challenge", + managed_endpoint_provision: "managed_endpoint_provision", + environment_connect: "environment_connect", + environment_status: "environment_status", + mobile_registration: "mobile_registration", + agent_activity_publish: "agent_activity_publish", + }); + }); + it.effect("returns a typed denial when Cloudflare rejects the key", () => Effect.gen(function* () { const rateLimits = yield* RateLimits.RateLimits; diff --git a/infra/relay/src/rateLimits/RateLimits.ts b/infra/relay/src/rateLimits/RateLimits.ts index 2a730e2639..abe9027d05 100644 --- a/infra/relay/src/rateLimits/RateLimits.ts +++ b/infra/relay/src/rateLimits/RateLimits.ts @@ -6,6 +6,18 @@ import * as Layer from "effect/Layer"; import type { RelayRateLimitTier } from "@t3tools/contracts/relay"; +export const RELAY_RATE_LIMIT_OPERATIONS = [ + "token_exchange", + "link_challenge", + "managed_endpoint_provision", + "environment_connect", + "environment_status", + "mobile_registration", + "agent_activity_publish", +] as const; + +export type RelayRateLimitOperation = (typeof RELAY_RATE_LIMIT_OPERATIONS)[number]; + export const RELAY_RATE_LIMITS = { token_exchange: { limit: 20, period: 60 }, link_challenge: { limit: 10, period: 60 }, @@ -14,11 +26,18 @@ export const RELAY_RATE_LIMITS = { environment_status: { limit: 30, period: 60 }, mobile_registration: { limit: 10, period: 60 }, agent_activity_publish: { limit: 60, period: 10 }, -} as const; +} as const satisfies Readonly>; -export type RelayRateLimitOperation = keyof typeof RELAY_RATE_LIMITS; type ActiveRelayRateLimitTier = Exclude; +export function mapRelayRateLimitOperations( + map: (operation: RelayRateLimitOperation) => A, +): Readonly> { + return Object.fromEntries( + RELAY_RATE_LIMIT_OPERATIONS.map((operation) => [operation, map(operation)]), + ) as Record; +} + export class RelayRateLimitExceeded extends Data.TaggedError("RelayRateLimitExceeded")<{ readonly operation: RelayRateLimitOperation; readonly retryAfterSeconds: number; diff --git a/infra/relay/src/resourceLimits.ts b/infra/relay/src/resourceLimits.ts new file mode 100644 index 0000000000..d804d1faf3 --- /dev/null +++ b/infra/relay/src/resourceLimits.ts @@ -0,0 +1,12 @@ +import type { RelayQuotaResource } from "@t3tools/contracts/relay"; +import * as Data from "effect/Data"; + +export const DEFAULT_MANAGED_ENDPOINT_LIMIT = 3; +export const DEFAULT_MOBILE_DEVICE_LIMIT = 5; +export const MAX_ACTIVE_AGENT_THREADS_PER_ENVIRONMENT = 50; +export const MAX_AGENT_AWARENESS_DELIVERY_USERS = 10; + +export class ResourceQuotaExceeded extends Data.TaggedError("ResourceQuotaExceeded")<{ + readonly resource: RelayQuotaResource; + readonly limit: number; +}> {} diff --git a/infra/relay/src/worker.ts b/infra/relay/src/worker.ts index faa678c3ea..f7ca03a713 100644 --- a/infra/relay/src/worker.ts +++ b/infra/relay/src/worker.ts @@ -162,36 +162,14 @@ 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"), - }), - }); + const rateLimitClients = yield* Effect.all( + RateLimits.mapRelayRateLimitOperations((operation) => + Effect.all({ + standard: bindRelayRateLimit(stage, operation, "standard"), + trusted: bindRelayRateLimit(stage, operation, "trusted"), + }), + ), + ); // // 3. Runtime layers and app construction @@ -305,7 +283,7 @@ export default class Api extends Cloudflare.Worker()( Maintenance.Maintenance.pipe(Effect.flatMap((maintenance) => maintenance.pruneExpired)), ]).pipe( Effect.asVoid, - Effect.withSpan("relay.cron.prune_expired_dpop_proofs"), + Effect.withSpan("relay.cron.maintenance"), Effect.provide(runtimeLayer), ), ); diff --git a/packages/contracts/src/relay.ts b/packages/contracts/src/relay.ts index 13578621f7..e36d88e3e0 100644 --- a/packages/contracts/src/relay.ts +++ b/packages/contracts/src/relay.ts @@ -489,7 +489,7 @@ export type RelayProtectedError = typeof RelayProtectedError.Type; const RelayAuthAndInternalErrors = [RelayAuthInvalidError, RelayInternalError] as const; -const RelayMobileErrors = [ +const RelayMobileRegistrationErrors = [ RelayAuthInvalidError, RelayQuotaExceededError, RelayRateLimitedError, @@ -866,7 +866,7 @@ export const RelayRegisterDeviceEndpoint = HttpApiEndpoint.post( headers: RelayDpopRequestHeaders, payload: RelayDeviceRegistrationRequest, success: RelayOkResponse, - error: RelayMobileErrors, + error: RelayMobileRegistrationErrors, }, ).annotate(OpenApi.Summary, "Register or update a mobile device"); @@ -877,7 +877,7 @@ export const RelayRegisterLiveActivityEndpoint = HttpApiEndpoint.post( headers: RelayDpopRequestHeaders, payload: RelayLiveActivityRegistrationRequest, success: RelayOkResponse, - error: RelayMobileErrors, + error: RelayMobileRegistrationErrors, }, ).annotate(OpenApi.Summary, "Register a Live Activity push token"); @@ -888,7 +888,7 @@ export const RelayUnregisterDeviceEndpoint = HttpApiEndpoint.delete( headers: RelayDpopRequestHeaders, params: RelayDeviceUnregistrationParams, success: RelayOkResponse, - error: RelayMobileErrors, + error: RelayAuthAndInternalErrors, }, ).annotate(OpenApi.Summary, "Unregister a mobile device");