fix(relay): restrict connector egress to managed endpoints

Co-authored-by: codex <[email protected]>
This commit is contained in:
Julius Marmingeandcodex committed 2026-06-04 14:03:01 -07:00
1 parent 2c34b11bbd
commit ab10db22f8
7 files changed
+274 -17

No files matched your search

+19
View File
@@ -2,7 +2,9 @@ import { describe, expect, it } from "vitest";
import {
managedEndpointDigestInput,
managedEndpointForHostname,
managedEndpointHostname,
isManagedEndpointHostname,
managedEndpointTunnelName,
relayOwnsManagedEndpointZone,
relayPublicDomainForStage,
@@ -71,4 +73,21 @@ describe("managed endpoint names", () => {
expect(hostname.split(".")[0]?.length).toBeLessThanOrEqual(63);
expect(hostname).toMatch(/-a{16}\.example\.com$/);
});
it("accepts allocated hostnames within the relay zone", () => {
expect(
isManagedEndpointHostname("tunnels-dev-julius-abcdef0123456789.example.com", "example.com"),
).toBe(true);
expect(managedEndpointForHostname("tunnels-dev-julius-abcdef0123456789.example.com")).toEqual({
httpBaseUrl: "https://tunnels-dev-julius-abcdef0123456789.example.com/",
wsBaseUrl: "wss://tunnels-dev-julius-abcdef0123456789.example.com/ws",
providerKind: "cloudflare_tunnel",
});
});
it("rejects hostnames outside the relay zone", () => {
expect(isManagedEndpointHostname("internal.example.net", "example.com")).toBe(false);
expect(isManagedEndpointHostname("example.com.attacker.test", "example.com")).toBe(false);
expect(isManagedEndpointHostname("tunnels-dev-julius.example.com.", "example.com")).toBe(false);
});
});
+36
View File
@@ -1,3 +1,5 @@
import type { RelayManagedEndpoint } from "@t3tools/contracts/relay";
const DNS_LABEL_MAX_LENGTH = 63;
const MANAGED_ENDPOINT_HASH_LENGTH = 16;
const MANAGED_ENDPOINT_HOST_PREFIX = "tunnels";
@@ -11,6 +13,21 @@ function normalizeZoneName(zoneName: string): string {
.replace(/^\.+|\.+$/g, "");
}
function isDnsName(name: string): boolean {
return (
name.length > 0 &&
name.length <= 253 &&
name
.split(".")
.every(
(label) =>
label.length > 0 &&
label.length <= DNS_LABEL_MAX_LENGTH &&
/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/u.test(label),
)
);
}
function stableSuffix(hash: string): string {
return hash.toLowerCase().slice(0, MANAGED_ENDPOINT_HASH_LENGTH);
}
@@ -67,6 +84,25 @@ export function managedEndpointHostname(stage: string, baseDomain: string, hash:
return `${label}.${normalizeZoneName(baseDomain)}`;
}
export function isManagedEndpointHostname(hostname: string, baseDomain: string): boolean {
const normalizedHostname = normalizeZoneName(hostname);
const normalizedBaseDomain = normalizeZoneName(baseDomain);
return (
hostname === normalizedHostname &&
isDnsName(normalizedHostname) &&
isDnsName(normalizedBaseDomain) &&
normalizedHostname.endsWith(`.${normalizedBaseDomain}`)
);
}
export function managedEndpointForHostname(hostname: string): RelayManagedEndpoint {
return {
httpBaseUrl: `https://${hostname}/`,
wsBaseUrl: `wss://${hostname}/ws`,
providerKind: "cloudflare_tunnel",
};
}
export function managedEndpointTunnelName(stage: string, hash: string): string {
return `${MANAGED_ENDPOINT_TUNNEL_PREFIX}-${relayStageSlug(stage)}-${stableSuffix(hash)}`;
}
@@ -27,6 +27,7 @@ import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/unstab
import * as EnvironmentLinks from "./EnvironmentLinks.ts";
import * as RelayConfiguration from "../Config.ts";
import * as EnvironmentConnector from "./EnvironmentConnector.ts";
import * as ManagedEndpointAllocations from "./ManagedEndpointAllocations.ts";
const cloudKeyPair = NodeCrypto.generateKeyPairSync("ed25519", {
privateKeyEncoding: { format: "pem", type: "pkcs8" },
@@ -69,7 +70,7 @@ const settings = RelayConfiguration.RelayConfiguration.of({
clerkJwtAudience: "t3-code-relay",
cloudMintPrivateKey: Redacted.make(cloudKeyPair.privateKey),
cloudMintPublicKey: cloudKeyPair.publicKey,
managedEndpointBaseDomain: undefined,
managedEndpointBaseDomain: "example.test",
managedEndpointNamespace: undefined,
});
@@ -155,16 +156,44 @@ function connectorTestLayer(
) => Effect.Effect<HttpClientResponse.HttpClientResponse>,
options?: {
readonly links?: EnvironmentLinks.EnvironmentLinksShape;
readonly allocations?: ManagedEndpointAllocations.ManagedEndpointAllocationsShape;
},
) {
return EnvironmentConnector.layer.pipe(
Layer.provide(NodeCryptoLayer.layer),
Layer.provide(Layer.succeed(EnvironmentLinks.EnvironmentLinks, options?.links ?? makeLinks())),
Layer.provide(
Layer.succeed(
ManagedEndpointAllocations.ManagedEndpointAllocations,
options?.allocations ?? makeAllocations(),
),
),
Layer.provide(Layer.succeed(RelayConfiguration.RelayConfiguration, settings)),
Layer.provide(Layer.succeed(HttpClient.HttpClient, HttpClient.make(execute))),
);
}
function makeAllocations(
allocation: ManagedEndpointAllocations.ManagedEndpointAllocation | null = {
userId: "user_123",
environmentId: "env-connector-test",
hostname: "env.example.test",
tunnelId: "tunnel-id",
tunnelName: "tunnel-name",
dnsRecordId: "dns-record-id",
readyAt: "2026-05-25T00:00:00.000Z",
},
): ManagedEndpointAllocations.ManagedEndpointAllocationsShape {
return {
get: () => Effect.succeed(allocation),
reserve: () => Effect.die("unused"),
recordTunnel: () => Effect.die("unused"),
recordDns: () => Effect.die("unused"),
markReady: () => Effect.die("unused"),
remove: () => Effect.die("unused"),
};
}
function makeLinks(
overrides: Partial<EnvironmentLinks.RelayLinkedEnvironmentRecord> = {},
): EnvironmentLinks.EnvironmentLinksShape {
@@ -180,8 +209,8 @@ function makeLinks(
label: "Connector Test Environment",
endpoint: {
httpBaseUrl: "https://env.example.test/",
wsBaseUrl: "wss://env.example.test/",
providerKind: "manual",
wsBaseUrl: "wss://env.example.test/ws",
providerKind: "cloudflare_tunnel",
},
linkedAt: "2026-05-25T00:00:00.000Z",
environmentPublicKey: environmentKeyPair.publicKey,
@@ -232,6 +261,120 @@ describe("EnvironmentConnector", () => {
}).pipe(Effect.provide(connectorTestLayer(execute)));
});
it.effect("rejects manual endpoints before sending a health request", () => {
let requestCount = 0;
const execute = () =>
Effect.sync(() => {
requestCount += 1;
throw new Error("unexpected request");
});
return Effect.gen(function* () {
const connector = yield* EnvironmentConnector.EnvironmentConnector;
const result = yield* Effect.result(
connector.status({
userId: "user_123",
environmentId: "env-connector-test",
}),
);
expect(Result.isFailure(result)).toBe(true);
if (Result.isFailure(result)) {
expect(result.failure).toBeInstanceOf(EnvironmentConnector.EnvironmentConnectNotAuthorized);
}
expect(requestCount).toBe(0);
}).pipe(
Effect.provide(
connectorTestLayer(execute, {
links: makeLinks({
endpoint: {
httpBaseUrl: "https://127.0.0.1/",
wsBaseUrl: "wss://127.0.0.1/ws",
providerKind: "manual",
},
}),
}),
),
);
});
it.effect("rejects stale managed endpoints before sending a mint request", () => {
let requestCount = 0;
const execute = () =>
Effect.sync(() => {
requestCount += 1;
throw new Error("unexpected request");
});
return Effect.gen(function* () {
const connector = yield* EnvironmentConnector.EnvironmentConnector;
const result = yield* Effect.result(
connector.connect({
userId: "user_123",
environmentId: "env-connector-test",
clientProofKeyThumbprint: "client-proof-key-thumbprint",
}),
);
expect(Result.isFailure(result)).toBe(true);
if (Result.isFailure(result)) {
expect(result.failure).toBeInstanceOf(EnvironmentConnector.EnvironmentConnectNotAuthorized);
}
expect(requestCount).toBe(0);
}).pipe(
Effect.provide(
connectorTestLayer(execute, {
links: makeLinks({
endpoint: {
httpBaseUrl: "https://attacker.example.test/",
wsBaseUrl: "wss://attacker.example.test/ws",
providerKind: "cloudflare_tunnel",
},
}),
}),
),
);
});
it.effect("rejects unready managed endpoint allocations before sending a request", () => {
let requestCount = 0;
const execute = () =>
Effect.sync(() => {
requestCount += 1;
throw new Error("unexpected request");
});
return Effect.gen(function* () {
const connector = yield* EnvironmentConnector.EnvironmentConnector;
const result = yield* Effect.result(
connector.status({
userId: "user_123",
environmentId: "env-connector-test",
}),
);
expect(Result.isFailure(result)).toBe(true);
if (Result.isFailure(result)) {
expect(result.failure).toBeInstanceOf(EnvironmentConnector.EnvironmentConnectNotAuthorized);
}
expect(requestCount).toBe(0);
}).pipe(
Effect.provide(
connectorTestLayer(execute, {
allocations: makeAllocations({
userId: "user_123",
environmentId: "env-connector-test",
hostname: "env.example.test",
tunnelId: "tunnel-id",
tunnelName: "tunnel-name",
dnsRecordId: "dns-record-id",
readyAt: null,
}),
}),
),
);
});
it.effect("rejects signed health responses with stale checkedAt timestamps", () => {
const execute = (request: HttpClientRequest.HttpClientRequest) =>
Effect.sync(() => {
@@ -438,7 +581,7 @@ describe("EnvironmentConnector", () => {
credential: "pairing_credential",
endpoint: {
httpBaseUrl: "https://env.example.test/",
wsBaseUrl: "wss://env.example.test/",
wsBaseUrl: "wss://env.example.test/ws",
},
});
}).pipe(Effect.provide(connectorTestLayer(execute)));
@@ -36,9 +36,10 @@ import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Redacted from "effect/Redacted";
import * as Schema from "effect/Schema";
import { HttpClient } from "effect/unstable/http";
import { FetchHttpClient, HttpClient } from "effect/unstable/http";
import * as EnvironmentLinks from "./EnvironmentLinks.ts";
import * as ManagedEndpointAllocations from "./ManagedEndpointAllocations.ts";
import * as RelayConfiguration from "../Config.ts";
export class EnvironmentConnectNotAuthorized extends Data.TaggedError(
@@ -69,7 +70,8 @@ export type EnvironmentConnectorError =
| EnvironmentMintRequestFailed
| EnvironmentMintRequestTimedOut
| EnvironmentMintResponseInvalid
| EnvironmentLinks.EnvironmentLinkLookupPersistenceError;
| EnvironmentLinks.EnvironmentLinkLookupPersistenceError
| ManagedEndpointAllocations.ManagedEndpointAllocationPersistenceError;
export const ENVIRONMENT_MINT_REQUEST_TIMEOUT_MS = 10_000;
const ENVIRONMENT_HEALTH_CLOCK_SKEW_MILLIS = 60 * 1_000;
@@ -114,6 +116,9 @@ function environmentHealthRequestFailureMessage(cause: unknown): string {
: "Managed endpoint health request failed.";
}
const withoutRedirects = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
effect.pipe(Effect.provideService(FetchHttpClient.RequestInit, { redirect: "manual" }));
const verifyWithEnvironmentKeys = Effect.fnUntraced(function* <A, E>(input: {
readonly token: string;
readonly typ: string;
@@ -216,6 +221,7 @@ function verifyEnvironmentHealthResponse(input: {
const make = Effect.gen(function* () {
const links = yield* EnvironmentLinks.EnvironmentLinks;
const allocations = yield* ManagedEndpointAllocations.ManagedEndpointAllocations;
const settings = yield* RelayConfiguration.RelayConfiguration;
const httpClient = yield* HttpClient.HttpClient;
const crypto = yield* Crypto.Crypto;
@@ -224,6 +230,38 @@ const make = Effect.gen(function* () {
makeEnvironmentHttpApiClient(httpBaseUrl).pipe(
Effect.provideService(HttpClient.HttpClient, httpClient),
);
const resolveManagedEndpoint = Effect.fn("relay.environment_connector.resolve_managed_endpoint")(
function* (input: {
readonly userId: string;
readonly link: EnvironmentLinks.RelayLinkedEnvironmentRecord;
}) {
if (input.link.endpoint.providerKind !== "cloudflare_tunnel") {
return yield* new EnvironmentConnectNotAuthorized({
environmentId: input.link.environmentId,
});
}
const allocation = yield* allocations.get({
userId: input.userId,
environmentId: input.link.environmentId,
});
const endpoint = allocation
? ManagedEndpointAllocations.resolveReadyManagedEndpoint({
allocation,
baseDomain: settings.managedEndpointBaseDomain,
})
: null;
if (
endpoint === null ||
endpoint.httpBaseUrl !== input.link.endpoint.httpBaseUrl ||
endpoint.wsBaseUrl !== input.link.endpoint.wsBaseUrl
) {
return yield* new EnvironmentConnectNotAuthorized({
environmentId: input.link.environmentId,
});
}
return endpoint;
},
);
return EnvironmentConnector.of({
status: Effect.fn("relay.environment_connector.status")(function* (input) {
@@ -235,6 +273,7 @@ const make = Effect.gen(function* () {
if (!link) {
return yield* new EnvironmentConnectNotAuthorized({ environmentId: input.environmentId });
}
const endpoint = yield* resolveManagedEndpoint({ userId: input.userId, link });
const now = yield* DateTime.now;
const expiresAt = DateTime.add(now, { minutes: 2 });
const nonce = yield* crypto.randomUUIDv4.pipe(
@@ -259,8 +298,9 @@ const make = Effect.gen(function* () {
payload,
}).pipe(Effect.mapError((cause) => new EnvironmentMintRequestFailed({ cause })));
const checkedAt = DateTime.formatIso(now);
const environmentClient = yield* makeEnvironmentClient(link.endpoint.httpBaseUrl);
const environmentClient = yield* makeEnvironmentClient(endpoint.httpBaseUrl);
const responseOption = yield* environmentClient.cloud.health({ payload: { proof } }).pipe(
withoutRedirects,
Effect.match({
onFailure: (cause) => ({ _tag: "Failure" as const, cause }),
onSuccess: (response) => ({ _tag: "Success" as const, response }),
@@ -270,7 +310,7 @@ const make = Effect.gen(function* () {
if (Option.isNone(responseOption)) {
return {
environmentId: link.environmentId,
endpoint: link.endpoint,
endpoint,
status: "offline" as const,
checkedAt,
error: "Managed endpoint health request timed out.",
@@ -279,7 +319,7 @@ const make = Effect.gen(function* () {
if (responseOption.value._tag === "Failure") {
return {
environmentId: link.environmentId,
endpoint: link.endpoint,
endpoint,
status: "offline" as const,
checkedAt,
error: environmentHealthRequestFailureMessage(responseOption.value.cause),
@@ -300,7 +340,7 @@ const make = Effect.gen(function* () {
}
return {
environmentId: link.environmentId,
endpoint: link.endpoint,
endpoint,
status: "online" as const,
checkedAt: decoded.checkedAt,
descriptor: decoded.descriptor,
@@ -320,6 +360,7 @@ const make = Effect.gen(function* () {
if (!link) {
return yield* new EnvironmentConnectNotAuthorized({ environmentId: input.environmentId });
}
const endpoint = yield* resolveManagedEndpoint({ userId: input.userId, link });
const now = yield* DateTime.now;
const expiresAt = DateTime.add(now, { minutes: 2 });
const nonce = yield* crypto.randomUUIDv4.pipe(
@@ -346,8 +387,9 @@ const make = Effect.gen(function* () {
typ: RELAY_MINT_REQUEST_TYP,
payload,
}).pipe(Effect.mapError((cause) => new EnvironmentMintRequestFailed({ cause })));
const environmentClient = yield* makeEnvironmentClient(link.endpoint.httpBaseUrl);
const environmentClient = yield* makeEnvironmentClient(endpoint.httpBaseUrl);
const decoded = yield* environmentClient.cloud.t3MintCredential({ payload: { proof } }).pipe(
withoutRedirects,
Effect.mapError((cause) => new EnvironmentMintRequestFailed({ cause })),
Effect.timeoutOption(Duration.millis(ENVIRONMENT_MINT_REQUEST_TIMEOUT_MS)),
Effect.flatMap(
@@ -377,7 +419,7 @@ const make = Effect.gen(function* () {
}
return {
environmentId: link.environmentId,
endpoint: link.endpoint,
endpoint,
credential: decoded.credential,
expiresAt: decoded.expiresAt,
};
@@ -1,3 +1,4 @@
import type { RelayManagedEndpoint } from "@t3tools/contracts/relay";
import { and, eq } from "drizzle-orm";
import * as Context from "effect/Context";
import * as Data from "effect/Data";
@@ -6,6 +7,7 @@ import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import { RelayDb } from "../db.ts";
import { isManagedEndpointHostname, managedEndpointForHostname } from "../deploymentConfig.ts";
import { relayManagedEndpointAllocations } from "../persistence/schema.ts";
export interface ManagedEndpointAllocation {
@@ -18,6 +20,22 @@ export interface ManagedEndpointAllocation {
readonly readyAt: string | null;
}
export function resolveReadyManagedEndpoint(input: {
readonly allocation: ManagedEndpointAllocation;
readonly baseDomain: string | undefined;
}): RelayManagedEndpoint | null {
if (
!input.baseDomain ||
input.allocation.readyAt === null ||
input.allocation.tunnelId === null ||
input.allocation.dnsRecordId === null ||
!isManagedEndpointHostname(input.allocation.hostname, input.baseDomain)
) {
return null;
}
return managedEndpointForHostname(input.allocation.hostname);
}
export class ManagedEndpointAllocationPersistenceError extends Data.TaggedError(
"ManagedEndpointAllocationPersistenceError",
)<{
@@ -19,6 +19,7 @@ import type {
import * as RelayConfiguration from "../Config.ts";
import {
managedEndpointDigestInput,
managedEndpointForHostname,
managedEndpointHostname,
managedEndpointTunnelName,
} from "../deploymentConfig.ts";
@@ -407,11 +408,7 @@ const make = Effect.gen(function* () {
.pipe(Effect.mapError((cause) => new ManagedEndpointProvisioningFailed({ cause })));
return {
endpoint: {
httpBaseUrl: `https://${hostname}/`,
wsBaseUrl: `wss://${hostname}/ws`,
providerKind: "cloudflare_tunnel",
},
endpoint: managedEndpointForHostname(hostname),
runtime: {
providerKind: "cloudflare_tunnel",
connectorToken,
+2
View File
@@ -61,6 +61,7 @@ import * as AgentActivityPublisher from "../agentActivity/AgentActivityPublisher
import * as EnvironmentConnector from "../environments/EnvironmentConnector.ts";
import * as EnvironmentLinker from "../environments/EnvironmentLinker.ts";
import * as ManagedEndpointProvider from "../environments/ManagedEndpointProvider.ts";
import * as ManagedEndpointAllocations from "../environments/ManagedEndpointAllocations.ts";
import * as EnvironmentPublishSignatures from "../environments/EnvironmentPublishSignatures.ts";
import * as MobileRegistrations from "../agentActivity/MobileRegistrations.ts";
import { withSpanAttributes } from "../observability.ts";
@@ -824,6 +825,7 @@ const COMMON_AUTH_INVALID_REASONS = [
EnvironmentLinks.EnvironmentLinkListPersistenceError,
EnvironmentLinks.EnvironmentLinkLookupPersistenceError,
EnvironmentLinks.EnvironmentLinkRevokePersistenceError,
ManagedEndpointAllocations.ManagedEndpointAllocationPersistenceError,
EnvironmentCredentials.EnvironmentCredentialAuthenticatePersistenceError,
EnvironmentCredentials.EnvironmentCredentialRevokePersistenceError,
DpopProofs.DpopProofReplayPersistenceError,