feat(relay): enforce resource limits

Co-authored-by: codex <[email protected]>
This commit is contained in:
Julius Marmingeandcodex committed 2026-06-03 23:56:39 -07:00
1 parent 974463ee9d
commit d3d38272d7
30 files changed
+3252 -166

No files matched your search

@@ -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}).`;
}
+4
View File
@@ -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}).`;
}
@@ -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");
File diff suppressed because it is too large. Load diff
@@ -17,6 +17,7 @@ import * as ApnsDeliveries from "./ApnsDeliveries.ts";
export type AgentActivityPublishError =
| AgentActivityRows.AgentActivityRowUpsertPersistenceError
| AgentActivityRows.AgentActivityRowQuotaExceeded
| AgentActivityRows.AgentActivityRowDeletePersistenceError
| AgentActivityRows.AgentActivityRowListPersistenceError
| EnvironmentLinks.EnvironmentLinkUserListPersistenceError
@@ -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: <A, E, R>(effect: Effect.Effect<A, E, R>) => 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)))),
);
});
});
@@ -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<void, AgentActivityRowUpsertPersistenceError>;
}) => Effect.Effect<void, AgentActivityRowUpsertPersistenceError | AgentActivityRowQuotaExceeded>;
readonly remove: (input: {
readonly environmentId: string;
readonly environmentPublicKey: string;
@@ -76,29 +85,59 @@ const make = Effect.gen(function* () {
Effect.flatMap(decodeJsonString),
Effect.map(cast<unknown, RelayAgentActivityState>),
);
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) {
+64 -3
View File
@@ -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<string> = [];
const updateSets: Array<Record<string, unknown>> = [];
@@ -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)));
});
});
+90 -53
View File
@@ -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<void, DeviceRegistrationPersistenceError>;
}) => 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<Devices, DevicesShape>()(
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) {
@@ -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 {
+4
View File
@@ -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)),
);
+5
View File
@@ -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<typeof RelayDpopAccessTokenClaims.Type, "scope"> & {
readonly scope: ReadonlyArray<RelayDpopAccessTokenScope>;
@@ -104,6 +107,7 @@ export interface RelayTokensShape {
readonly expiresAtEpochSeconds: number;
readonly clientId: RelayPublicClientId;
readonly scopes: ReadonlyArray<RelayDpopAccessTokenScope>;
readonly rateLimitTier: RelayRateLimitTier;
}) => Effect.Effect<string, RelayJwtError>;
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,
},
});
});
@@ -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<Record<string, unknown>>) {
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",
},
]),
),
),
);
});
@@ -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<EffectiveUserEntitlements, UserEntitlementPersistenceError>;
readonly withUserLock: <A, E, R>(
userId: string,
effect: Effect.Effect<A, E, R>,
) => Effect.Effect<A, E | UserEntitlementPersistenceError, R>;
}
export class Entitlements extends Context.Service<Entitlements, EntitlementsShape>()(
"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);
@@ -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,
}),
}),
),
@@ -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* () {
@@ -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,
@@ -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,
@@ -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)));
});
});
@@ -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<ManagedEndpointAllocation | null, ManagedEndpointAllocationPersistenceError>;
readonly reserve: (
input: ReserveManagedEndpointAllocationInput,
) => Effect.Effect<ManagedEndpointAllocation, ManagedEndpointAllocationPersistenceError>;
) => Effect.Effect<
ManagedEndpointAllocation,
ManagedEndpointAllocationPersistenceError | Entitlements.UserResourceQuotaExceeded
>;
readonly recordTunnel: (
input: RecordManagedEndpointTunnelInput,
) => Effect.Effect<void, ManagedEndpointAllocationPersistenceError>;
@@ -76,6 +88,21 @@ export interface ManagedEndpointAllocationsShape {
readonly markReady: (
input: ManagedEndpointAllocationKey,
) => Effect.Effect<void, ManagedEndpointAllocationPersistenceError>;
readonly requestDeprovision: (
input: ManagedEndpointAllocationKey,
) => Effect.Effect<void, ManagedEndpointAllocationPersistenceError>;
readonly markDeprovisionAttempt: (
input: ManagedEndpointAllocationKey,
) => Effect.Effect<void, ManagedEndpointAllocationPersistenceError>;
readonly recordDeprovisionFailure: (
input: RecordManagedEndpointDeprovisionFailureInput,
) => Effect.Effect<void, ManagedEndpointAllocationPersistenceError>;
readonly listCleanupCandidates: (input: {
readonly orphanedBefore: string;
}) => Effect.Effect<
ReadonlyArray<ManagedEndpointAllocationKey>,
ManagedEndpointAllocationPersistenceError
>;
readonly remove: (
input: ManagedEndpointAllocationKey,
) => Effect.Effect<void, ManagedEndpointAllocationPersistenceError>;
@@ -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,
) {
@@ -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[] = [];
@@ -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<void, ManagedEndpointDeprovisioningFailed>;
readonly reconcileDeprovisioning: Effect.Effect<void, ManagedEndpointDeprovisioningFailed>;
}
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(
+131 -8
View File
@@ -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<string>):
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<E> =
| Exclude<E, HttpApiError.Unauthorized | RelayCommonPersistenceError>
| Exclude<
E,
| HttpApiError.Unauthorized
| RelayCommonPersistenceError
| Entitlements.UserResourceQuotaExceeded
| AgentActivityRows.AgentActivityRowQuotaExceeded
| RateLimits.RelayRateLimitExceeded
>
| (Extract<E, HttpApiError.Unauthorized> extends never ? never : RelayAuthInvalidError)
| (Extract<E, RelayCommonPersistenceError> extends never ? never : RelayInternalError);
| (Extract<E, RelayCommonPersistenceError> extends never ? never : RelayInternalError)
| (Extract<E, Entitlements.UserResourceQuotaExceeded> extends never
? never
: RelayQuotaExceededError)
| (Extract<E, AgentActivityRows.AgentActivityRowQuotaExceeded> extends never
? never
: RelayQuotaExceededError)
| (Extract<E, RateLimits.RelayRateLimitExceeded> 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<E>,
);
}
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<E>,
);
}
if (error instanceof RateLimits.RelayRateLimitExceeded) {
return yield* Effect.fail(
new RelayRateLimitedError({
code: "rate_limited",
operation: error.operation,
retryAfterSeconds: error.retryAfterSeconds,
traceId,
}) as MapRelayCommonApiError<E>,
);
}
return yield* Effect.fail(error as MapRelayCommonApiError<E>);
});
@@ -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<unknown> = [];
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)))));
});
});
@@ -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<void, RelayMaintenancePersistenceError>;
}
export class Maintenance extends Context.Service<Maintenance, MaintenanceShape>()(
"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);
+39
View File
@@ -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')`,
),
],
);
@@ -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> = {},
): 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())),
),
);
});
+88
View File
@@ -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<RelayRateLimitTier, "blocked">;
export class RelayRateLimitExceeded extends Data.TaggedError("RelayRateLimitExceeded")<{
readonly operation: RelayRateLimitOperation;
readonly retryAfterSeconds: number;
}> {}
export type RelayRateLimitClients = Readonly<
Record<
RelayRateLimitOperation,
Readonly<Record<ActiveRelayRateLimitTier, Cloudflare.RateLimitClient>>
>
>;
export interface RateLimitsShape {
readonly check: (input: {
readonly operation: RelayRateLimitOperation;
readonly key: string;
readonly tier?: RelayRateLimitTier;
}) => Effect.Effect<void, RelayRateLimitExceeded, Cloudflare.WorkerEnvironment>;
}
export class RateLimits extends Context.Service<RateLimits, RateLimitsShape>()(
"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,
}),
);
+65 -3
View File
@@ -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>()(
"Api",
RelayDeploymentConfig.pipe(
@@ -143,6 +162,36 @@ export default class Api extends Cloudflare.Worker<Api>()(
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<Api>()(
}).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<Api>()(
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<Api>()(
);
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<Api>()(
Layer.provideMerge(Cloudflare.QueueEventSourceLive),
Layer.provideMerge(Cloudflare.TunnelReadWriteLive),
Layer.provideMerge(Cloudflare.DnsReadWriteLive),
Layer.provideMerge(Cloudflare.RateLimitBindingLive),
),
),
),
+63 -5
View File
@@ -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>()(
"RelayAuthInvalidError",
{
@@ -427,6 +448,28 @@ export class RelayInternalError extends Schema.TaggedErrorClass<RelayInternalErr
{ httpApiStatus: 500 },
) {}
export class RelayQuotaExceededError extends Schema.TaggedErrorClass<RelayQuotaExceededError>()(
"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>()(
"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<RelayDpopAccessTokenScope>;
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")