diff --git a/infra/relay/src/deploymentConfig.test.ts b/infra/relay/src/deploymentConfig.test.ts index c7dc7b3506..1b69d55058 100644 --- a/infra/relay/src/deploymentConfig.test.ts +++ b/infra/relay/src/deploymentConfig.test.ts @@ -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); + }); }); diff --git a/infra/relay/src/deploymentConfig.ts b/infra/relay/src/deploymentConfig.ts index 413201f277..253fcaf345 100644 --- a/infra/relay/src/deploymentConfig.ts +++ b/infra/relay/src/deploymentConfig.ts @@ -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)}`; } diff --git a/infra/relay/src/environments/EnvironmentConnector.test.ts b/infra/relay/src/environments/EnvironmentConnector.test.ts index 553491d881..505d1f31d0 100644 --- a/infra/relay/src/environments/EnvironmentConnector.test.ts +++ b/infra/relay/src/environments/EnvironmentConnector.test.ts @@ -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, 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.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))); diff --git a/infra/relay/src/environments/EnvironmentConnector.ts b/infra/relay/src/environments/EnvironmentConnector.ts index a7d1652c07..d31cf499e4 100644 --- a/infra/relay/src/environments/EnvironmentConnector.ts +++ b/infra/relay/src/environments/EnvironmentConnector.ts @@ -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 = (effect: Effect.Effect) => + effect.pipe(Effect.provideService(FetchHttpClient.RequestInit, { redirect: "manual" })); + const verifyWithEnvironmentKeys = Effect.fnUntraced(function* (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, }; diff --git a/infra/relay/src/environments/ManagedEndpointAllocations.ts b/infra/relay/src/environments/ManagedEndpointAllocations.ts index c813b7c987..236414e955 100644 --- a/infra/relay/src/environments/ManagedEndpointAllocations.ts +++ b/infra/relay/src/environments/ManagedEndpointAllocations.ts @@ -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", )<{ diff --git a/infra/relay/src/environments/ManagedEndpointProvider.ts b/infra/relay/src/environments/ManagedEndpointProvider.ts index 9804ba0a1e..068beccff0 100644 --- a/infra/relay/src/environments/ManagedEndpointProvider.ts +++ b/infra/relay/src/environments/ManagedEndpointProvider.ts @@ -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, diff --git a/infra/relay/src/http/Api.ts b/infra/relay/src/http/Api.ts index cbb9f4e92e..3691088662 100644 --- a/infra/relay/src/http/Api.ts +++ b/infra/relay/src/http/Api.ts @@ -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,