diff --git a/apps/desktop/src/ipc/DesktopIpcHandlers.ts b/apps/desktop/src/ipc/DesktopIpcHandlers.ts index fe65edd0ee1e..14ebc5cf8e1e 100644 --- a/apps/desktop/src/ipc/DesktopIpcHandlers.ts +++ b/apps/desktop/src/ipc/DesktopIpcHandlers.ts @@ -4,6 +4,7 @@ import * as Effect from "effect/Effect"; import { receiveProviderAuthCallback, cancelProviderAuthCallback } from "./methods/providerAuth.ts"; import * as DesktopIpc from "./DesktopIpc.ts"; import { installNotificationBadge } from "./methods/notificationBadge.ts"; +import { installOidcSessionStore, requestOidcToken } from "./methods/oidcSession.ts"; import { getClientSettings, setClientSettings } from "./methods/clientSettings.ts"; import { getConnectionCatalog, setConnectionCatalog } from "./methods/connectionCatalog.ts"; import { @@ -101,6 +102,8 @@ export const installDesktopIpcHandlers = Effect.fn("desktop.ipc.installHandlers" yield* ipc.handle(completeLegacyLocalStorage); yield* ipc.handleSync(getAppBranding); yield* installRelayTelemetryEnabled(); + yield* installOidcSessionStore(); + yield* ipc.handle(requestOidcToken); yield* ipc.handleSync(getSystemLocale); yield* ipc.handleSync(getPreferredSystemLanguages); yield* ipc.handleSync(getPrimaryPasteEnabled); diff --git a/apps/desktop/src/ipc/channels.ts b/apps/desktop/src/ipc/channels.ts index d8652bd19971..4823a878c5d8 100644 --- a/apps/desktop/src/ipc/channels.ts +++ b/apps/desktop/src/ipc/channels.ts @@ -36,6 +36,9 @@ export const CLI_COMMAND_UNINSTALL_CHANNEL = "desktop:cli-command-uninstall"; export const CLI_COMMAND_ADD_TO_PATH_CHANNEL = "desktop:cli-command-add-to-path"; export const GET_APP_BRANDING_CHANNEL = "desktop:get-app-branding"; export const GET_RELAY_TELEMETRY_ENABLED_CHANNEL = "desktop:get-relay-telemetry-enabled"; +export const GET_OIDC_SESSION_CHANNEL = "desktop:get-oidc-session"; +export const SET_OIDC_SESSION_CHANNEL = "desktop:set-oidc-session"; +export const REQUEST_OIDC_TOKEN_CHANNEL = "desktop:request-oidc-token"; export const GET_SYSTEM_LOCALE_CHANNEL = "desktop:get-system-locale"; export const GET_PREFERRED_SYSTEM_LANGUAGES_CHANNEL = "desktop:get-preferred-system-languages"; export const GET_PRIMARY_PASTE_ENABLED_CHANNEL = "desktop:get-primary-paste-enabled"; diff --git a/apps/desktop/src/ipc/methods/oidcSession.test.ts b/apps/desktop/src/ipc/methods/oidcSession.test.ts new file mode 100644 index 000000000000..12320e8de48a --- /dev/null +++ b/apps/desktop/src/ipc/methods/oidcSession.test.ts @@ -0,0 +1,123 @@ +import { assert, describe, it } from "@effect/vitest"; +import * as NodeServices from "@effect/platform-node/NodeServices"; +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; +import * as Layer from "effect/Layer"; + +import * as DesktopConfig from "../../app/DesktopConfig.ts"; +import * as DesktopEnvironment from "../../app/DesktopEnvironment.ts"; +import * as ElectronSafeStorage from "../../electron/ElectronSafeStorage.ts"; +import * as IpcChannels from "../channels.ts"; +import * as DesktopIpc from "../DesktopIpc.ts"; +import { installOidcSessionStore } from "./oidcSession.ts"; + +const SESSION = '{"refreshToken":"refresh-1"}'; +const reverse = (value: string) => Array.from(value).reverse().join(""); +const sealed = (value: string) => `sealed:${reverse(value)}`; + +const layerSafeStorage = (available: boolean) => + Layer.succeed(ElectronSafeStorage.ElectronSafeStorage, { + isEncryptionAvailable: Effect.succeed(available), + encryptString: (value) => Effect.succeed(new TextEncoder().encode(sealed(value))), + decryptString: (value) => + Effect.sync(() => reverse(new TextDecoder().decode(value).slice("sealed:".length))), + selectedStorageBackend: Effect.succeedNone, + } satisfies ElectronSafeStorage.ElectronSafeStorage["Service"]); + +const layerEnvironment = (baseDir: string) => + DesktopEnvironment.layer({ + dirname: "/repo/apps/desktop/src", + homeDirectory: baseDir, + platform: "darwin", + processArch: "arm64", + appVersion: "1.2.3", + appPath: "/repo", + isPackaged: true, + resourcesPath: "/missing/resources", + runningUnderArm64Translation: false, + }).pipe( + Layer.provide( + Layer.mergeAll(NodeServices.layer, DesktopConfig.layerTest({ T3CODE_HOME: baseDir })), + ), + ); + +/** Installs the store as startup does and answers like the renderer's bridge. */ +const openStore = (baseDir: string, encryptionAvailable: boolean) => + Effect.gen(function* () { + const invoke = new Map(); + const sync = new Map(); + const ipcMain: DesktopIpc.DesktopIpcMain = { + removeHandler: (channel) => void invoke.delete(channel), + handle: (channel, listener) => void invoke.set(channel, listener), + removeAllListeners: (channel) => void sync.delete(channel), + on: (channel, listener) => void sync.set(channel, listener), + }; + yield* installOidcSessionStore().pipe( + Effect.provide( + Layer.mergeAll( + DesktopIpc.layerTest(ipcMain), + layerEnvironment(baseDir), + layerSafeStorage(encryptionAvailable), + NodeServices.layer, + ), + ), + ); + const sender = { sender: { id: 1 } }; + return { + get: () => { + const event = { ...sender, returnValue: undefined as unknown }; + sync.get(IpcChannels.GET_OIDC_SESSION_CHANNEL)?.(event); + return event.returnValue; + }, + set: (session: string | null) => + Effect.promise(async () => + invoke.get(IpcChannels.SET_OIDC_SESSION_CHANNEL)?.(sender, session), + ), + }; + }); + +const sessionFileContents = (baseDir: string) => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const environment = yield* DesktopEnvironment.DesktopEnvironment; + return yield* fileSystem + .readFileString(environment.path.join(environment.stateDir, "oidc-session.bin")) + .pipe(Effect.orElseSucceed(() => null)); + }).pipe(Effect.provide(layerEnvironment(baseDir))); + +describe("installOidcSessionStore", () => { + it.effect("keeps the session encrypted on disk across restarts and deletes it on sign-out", () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const baseDir = yield* fileSystem.makeTempDirectoryScoped(); + + const first = yield* openStore(baseDir, true); + yield* first.set(SESSION); + assert.equal(first.get(), SESSION); + const onDisk = yield* sessionFileContents(baseDir); + assert.isNotNull(onDisk); + assert.notInclude(onDisk ?? "", "refresh-1"); + + const restarted = yield* openStore(baseDir, true); + assert.equal(restarted.get(), SESSION); + + yield* restarted.set(null); + assert.isNull(restarted.get()); + assert.isNull(yield* sessionFileContents(baseDir)); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + ); + + it.effect("keeps the session in memory only when no keychain is available", () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const baseDir = yield* fileSystem.makeTempDirectoryScoped(); + + const store = yield* openStore(baseDir, false); + yield* store.set(SESSION); + + assert.equal(store.get(), SESSION); + assert.isNull(yield* sessionFileContents(baseDir)); + assert.isNull((yield* openStore(baseDir, false)).get()); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + ); +}); diff --git a/apps/desktop/src/ipc/methods/oidcSession.ts b/apps/desktop/src/ipc/methods/oidcSession.ts new file mode 100644 index 000000000000..cd100968545a --- /dev/null +++ b/apps/desktop/src/ipc/methods/oidcSession.ts @@ -0,0 +1,130 @@ +import { writeFileStringAtomically } from "@t3tools/shared/atomicWrite"; +import { oidcDiscoveryUrl, parseOidcMetadata } from "@t3tools/shared/oidc"; +import * as Duration from "effect/Duration"; +import * as Effect from "effect/Effect"; +import * as Base64 from "effect/encoding/Base64"; +import * as FileSystem from "effect/FileSystem"; +import * as Ref from "effect/Ref"; +import * as Schema from "effect/Schema"; +import * as Semaphore from "effect/Semaphore"; +import * as HttpClient from "effect/http/HttpClient"; +import * as HttpClientRequest from "effect/http/HttpClientRequest"; + +import * as DesktopEnvironment from "../../app/DesktopEnvironment.ts"; +import * as ElectronSafeStorage from "../../electron/ElectronSafeStorage.ts"; +import * as IpcChannels from "../channels.ts"; +import * as DesktopIpc from "../DesktopIpc.ts"; + +const OIDC_SESSION_FILE_NAME = "oidc-session.bin"; +const TOKEN_REQUEST_TIMEOUT = Duration.seconds(10); +const TOKEN_GRANT_TYPES = new Set(["authorization_code", "refresh_token"]); + +export class DesktopOidcTokenRequestError extends Schema.TaggedError()( + "DesktopOidcTokenRequestError", + { reason: Schema.String, cause: Schema.optional(Schema.Defect()) }, +) { + override get message(): string { + return `The token request was refused: ${this.reason}.`; + } +} + +/** + * Keeps the renderer's OpenID Connect session encrypted with safeStorage. Read once here because a + * sync IPC handler cannot wait on the filesystem; every write updates this copy first. Without a + * keychain the session stays in memory and ends with the app. + */ +export const installOidcSessionStore = Effect.fn("desktop.ipc.oidcSession.install")(function* () { + const ipc = yield* DesktopIpc.DesktopIpc; + const environment = yield* DesktopEnvironment.DesktopEnvironment; + const fileSystem = yield* FileSystem.FileSystem; + const safeStorage = yield* ElectronSafeStorage.ElectronSafeStorage; + const filePath = environment.path.join(environment.stateDir, OIDC_SESSION_FILE_NAME); + const encryptionAvailable = safeStorage.isEncryptionAvailable.pipe( + Effect.orElseSucceed(() => false), + ); + + const stored = yield* fileSystem.readFileString(filePath).pipe( + Effect.flatMap((encoded) => Effect.fromResult(Base64.decode(encoded.trim()))), + Effect.flatMap(safeStorage.decryptString), + Effect.orElseSucceed(() => null), + ); + const session = yield* Ref.make(stored); + const writes = yield* Semaphore.make(1); + + yield* ipc.handleSync( + DesktopIpc.makeSyncIpcMethod({ + channel: IpcChannels.GET_OIDC_SESSION_CHANNEL, + result: Schema.NullOr(Schema.String), + handler: () => Ref.get(session), + }), + ); + yield* ipc.handle( + DesktopIpc.makeIpcMethod({ + channel: IpcChannels.SET_OIDC_SESSION_CHANNEL, + payload: Schema.NullOr(Schema.String), + result: Schema.Void, + handler: Effect.fn("desktop.ipc.oidcSession.set")(function* (next) { + yield* Ref.set(session, next); + yield* writes.withPermits(1)( + Effect.gen(function* () { + if (next !== null && (yield* encryptionAvailable)) { + const encrypted = yield* safeStorage.encryptString(next); + yield* writeFileStringAtomically({ filePath, contents: Base64.encode(encrypted) }); + return; + } + if (next !== null) { + yield* Effect.logWarning( + "No OS keychain is available, so the sign-in session is kept in memory only.", + ); + } + yield* fileSystem.remove(filePath, { force: true }); + }), + ); + }), + }), + ); +}); + +/** + * Identity providers such as Entra refuse to redeem a code sent from the renderer's custom-scheme + * origin, so token requests run here. Discovery runs here too, so only an issuer's own token + * endpoint can be reached, and only with an authorization code or refresh token grant. + */ +export const requestOidcToken = DesktopIpc.makeIpcMethod({ + channel: IpcChannels.REQUEST_OIDC_TOKEN_CHANNEL, + payload: Schema.Struct({ + issuer: Schema.String, + tokenEndpoint: Schema.String, + body: Schema.String, + }), + result: Schema.Struct({ status: Schema.Number, body: Schema.String }), + handler: Effect.fn("desktop.ipc.oidcSession.requestToken")(function* (input) { + const grantType = new URLSearchParams(input.body).get("grant_type"); + if (grantType === null || !TOKEN_GRANT_TYPES.has(grantType)) { + return yield* new DesktopOidcTokenRequestError({ reason: "unsupported grant type" }); + } + const httpClient = yield* HttpClient.HttpClient; + const metadata = yield* HttpClientRequest.get(oidcDiscoveryUrl(input.issuer)).pipe( + HttpClientRequest.acceptJson, + HttpClient.filterStatusOk(httpClient).execute, + Effect.flatMap((response) => response.json), + Effect.flatMap((body) => + Effect.try({ + try: () => parseOidcMetadata(input.issuer, body), + catch: (cause) => new DesktopOidcTokenRequestError({ reason: "discovery failed", cause }), + }), + ), + Effect.timeout(TOKEN_REQUEST_TIMEOUT), + ); + if (metadata.tokenEndpoint !== input.tokenEndpoint) { + return yield* new DesktopOidcTokenRequestError({ reason: "not the issuer's token endpoint" }); + } + const response = yield* HttpClientRequest.post(metadata.tokenEndpoint).pipe( + HttpClientRequest.bodyText(input.body, "application/x-www-form-urlencoded"), + HttpClientRequest.acceptJson, + httpClient.execute, + Effect.timeout(TOKEN_REQUEST_TIMEOUT), + ); + return { status: response.status, body: yield* response.text }; + }), +}); diff --git a/apps/desktop/src/preload.ts b/apps/desktop/src/preload.ts index b4b15f6a7a4e..1b61e97ddfb4 100644 --- a/apps/desktop/src/preload.ts +++ b/apps/desktop/src/preload.ts @@ -115,6 +115,12 @@ contextBridge.exposeInMainWorld("desktopBridge", { const enabled = ipcRenderer.sendSync(IpcChannels.GET_RELAY_TELEMETRY_ENABLED_CHANNEL); return enabled === null ? null : enabled === true; }, + getOidcSession: () => { + const session: unknown = ipcRenderer.sendSync(IpcChannels.GET_OIDC_SESSION_CHANNEL); + return typeof session === "string" ? session : null; + }, + setOidcSession: (session) => ipcRenderer.invoke(IpcChannels.SET_OIDC_SESSION_CHANNEL, session), + requestOidcToken: (input) => ipcRenderer.invoke(IpcChannels.REQUEST_OIDC_TOKEN_CHANNEL, input), getPathForFile: (file: File) => webUtils.getPathForFile(file), getClientPlatform: () => clientPlatform, restartAudioService: () => ipcRenderer.invoke(IpcChannels.RESTART_AUDIO_SERVICE_CHANNEL), diff --git a/apps/mobile/src/features/cloud/CloudAuthProvider.tsx b/apps/mobile/src/features/cloud/CloudAuthProvider.tsx index c81837474609..020d13344529 100644 --- a/apps/mobile/src/features/cloud/CloudAuthProvider.tsx +++ b/apps/mobile/src/features/cloud/CloudAuthProvider.tsx @@ -7,6 +7,7 @@ import { cloudAccountService, createCloudRelayAccountService, deactivateCloudRelayAccount, + signOutAndUnregisterDevice, } from "./cloudAccountService"; import { CloudAuthContext, type CloudAuth } from "./cloudAuth"; import { getMobileOidcController } from "./oidc/mobileOidc"; @@ -50,7 +51,7 @@ function OidcAuthBridge(props: { userId: snapshot.userId, accountLabel: snapshot.label, getToken: props.controller.getToken, - signOut: props.controller.signOut, + signOut: () => signOutAndUnregisterDevice(props.controller.getToken, props.controller.signOut), }; return {props.children}; } @@ -68,7 +69,11 @@ function ClerkAuthBridge(props: { readonly children: ReactNode }) { userId: userId ?? null, accountLabel: user?.primaryEmailAddress?.emailAddress ?? null, getToken: () => getToken(resolveRelayClerkTokenOptions()), - signOut: () => signOut(), + signOut: () => + signOutAndUnregisterDevice( + () => getToken(resolveRelayClerkTokenOptions()), + () => signOut(), + ), }; return {props.children}; } diff --git a/apps/mobile/src/features/cloud/cloudAccountService.ts b/apps/mobile/src/features/cloud/cloudAccountService.ts index ee2410fb8e36..5ad1302e1fb9 100644 --- a/apps/mobile/src/features/cloud/cloudAccountService.ts +++ b/apps/mobile/src/features/cloud/cloudAccountService.ts @@ -46,6 +46,23 @@ export function activateCloudRelayAccount( }); } +/** + * The relay accepts the device's unregistration only with a valid token, so the device leaves + * before the session does; otherwise the relay keeps pushing to a signed-out phone. + */ +export async function signOutAndUnregisterDevice( + readToken: () => Promise, + signOut: () => Promise, +): Promise { + await runtime.runPromise( + unregisterAgentAwarenessDeviceForCurrentUser(readToken).pipe( + Effect.timeout("5 seconds"), + Effect.ignore, + ), + ); + await signOut(); +} + function clerkTokenReader(clerk: ClerkInstance): () => Promise { return async () => clerk.session ? await clerk.session.getToken(resolveRelayClerkTokenOptions()) : null; diff --git a/apps/mobile/src/features/cloud/oidc/mobileOidc.ts b/apps/mobile/src/features/cloud/oidc/mobileOidc.ts index 1559f942e2a2..c0cf5b4d1aa0 100644 --- a/apps/mobile/src/features/cloud/oidc/mobileOidc.ts +++ b/apps/mobile/src/features/cloud/oidc/mobileOidc.ts @@ -52,11 +52,11 @@ let controller: OidcController | null | undefined; /** The one controller for this app; null when the build has no OpenID Connect provider. */ export function getMobileOidcController(): OidcController | null { if (controller !== undefined) return controller; - const { oidc } = resolveCloudPublicConfig(); + const { oidc, relay } = resolveCloudPublicConfig(); controller = - oidc.issuer && oidc.clientId + oidc.issuer && oidc.clientId && relay.url ? createOidcController({ - config: { issuer: oidc.issuer, clientId: oidc.clientId }, + config: { relayUrl: relay.url, issuer: oidc.issuer, clientId: oidc.clientId }, redirectUri, sessions: secureSessionStore(), pending: memoryStore(), diff --git a/apps/mobile/src/features/cloud/publicConfig.ts b/apps/mobile/src/features/cloud/publicConfig.ts index 0ec8e7e37e08..00dfc2eb5a65 100644 --- a/apps/mobile/src/features/cloud/publicConfig.ts +++ b/apps/mobile/src/features/cloud/publicConfig.ts @@ -1,7 +1,10 @@ import { + canChooseSelfHostedRelay, encodeSelfHostedRelay, + parseRelayPolicy, parseStoredSelfHostedRelay, SELF_HOSTED_RELAY_STORAGE_KEY, + type RelayPolicy, type SelfHostedRelay, } from "@t3tools/client-runtime/relay/self-hosted"; import Constants from "expo-constants"; @@ -69,6 +72,18 @@ function normalizeSecureUrl(value: unknown): string | null { } } +/** Which relays this build lets the user switch to (`T3CODE_RELAY_PINNED`, `T3CODE_RELAY_ALLOWLIST`). */ +export function resolveRelayPolicy( + extra: + | { readonly relay?: { readonly pinned?: unknown; readonly allowlist?: unknown } } + | undefined = Constants.expoConfig?.extra, +): RelayPolicy { + return parseRelayPolicy({ pinned: extra?.relay?.pinned, allowlist: extra?.relay?.allowlist }); +} + +export const selfHostedRelayChoiceAvailable = (): boolean => + canChooseSelfHostedRelay(resolveRelayPolicy()); + let selfHostedRelay: SelfHostedRelay | null | undefined; /** The relay the user chose in settings; it replaces the build's T3 Connect until cleared. */ @@ -77,6 +92,7 @@ export function readSelfHostedRelay(): SelfHostedRelay | null { try { selfHostedRelay = parseStoredSelfHostedRelay( SecureStore.getItem(SELF_HOSTED_RELAY_STORAGE_KEY), + resolveRelayPolicy(), ); } catch { selfHostedRelay = null; diff --git a/apps/mobile/src/features/settings/SettingsConnectServiceRouteScreen.tsx b/apps/mobile/src/features/settings/SettingsConnectServiceRouteScreen.tsx index 109d5ff9fd32..48621665bbb4 100644 --- a/apps/mobile/src/features/settings/SettingsConnectServiceRouteScreen.tsx +++ b/apps/mobile/src/features/settings/SettingsConnectServiceRouteScreen.tsx @@ -11,19 +11,27 @@ import { AppText as Text } from "../../components/ui/AppText"; import { ControlPill } from "../../components/ui/ControlPill"; import { ListChoiceRow } from "../../components/ui/ListChoiceRow"; import * as Dialog from "../../components/ui/Dialog"; -import { readSelfHostedRelay, saveSelfHostedRelay } from "../cloud/publicConfig"; +import { useCloudAuth } from "../cloud/cloudAuth"; +import { + readSelfHostedRelay, + resolveRelayPolicy, + saveSelfHostedRelay, +} from "../cloud/publicConfig"; import { SettingsScreen } from "./components/SettingsScreen"; import { SettingsSection } from "./components/SettingsSection"; -// Sign-in and the relay client are wired once at startup, so a new choice reloads the app. -async function switchTo(relay: SelfHostedRelay | null) { - await saveSelfHostedRelay(relay); - await reloadAppAsync("Switched the T3 Connect service"); -} - /** Chooses between the build's T3 Connect and a relay the user runs themselves. */ export function SettingsConnectServiceRouteScreen() { const gt = useGT(); + const { isSignedIn, signOut } = useCloudAuth(); + // Signing out first lets the current relay drop this phone's push registration while the + // session can still prove who asks. Sign-in and the relay client are wired once at startup, + // so a new choice reloads the app. + const switchTo = async (relay: SelfHostedRelay | null) => { + if (isSignedIn) await signOut(); + await saveSelfHostedRelay(relay); + await reloadAppAsync("Switched the T3 Connect service"); + }; const current = readSelfHostedRelay(); const [selfHosted, setSelfHosted] = useState(current !== null); const [address, setAddress] = useState(current?.relayUrl ?? ""); @@ -97,7 +105,9 @@ export function SettingsConnectServiceRouteScreen() { variant="primary" label={busy ? gt("Checking…") : current ? gt("Update") : gt("Use relay")} disabled={busy || address.trim() === ""} - onPress={() => void run(() => discoverSelfHostedRelay(address))} + onPress={() => + void run(() => discoverSelfHostedRelay(address, { policy: resolveRelayPolicy() })) + } /> diff --git a/apps/mobile/src/features/settings/SettingsRouteScreen.tsx b/apps/mobile/src/features/settings/SettingsRouteScreen.tsx index 44049564b520..ad97f0b92480 100644 --- a/apps/mobile/src/features/settings/SettingsRouteScreen.tsx +++ b/apps/mobile/src/features/settings/SettingsRouteScreen.tsx @@ -22,7 +22,11 @@ import { deriveProjectGroupLabel } from "@t3tools/client-runtime/state/project-g import { useSafeAreaInsets } from "react-native-safe-area-context"; import { useCloudAuth } from "../cloud/cloudAuth"; -import { hasCloudPublicConfig, readSelfHostedRelay } from "../cloud/publicConfig"; +import { + hasCloudPublicConfig, + readSelfHostedRelay, + selfHostedRelayChoiceAvailable, +} from "../cloud/publicConfig"; import { useAdaptiveWorkspaceLayout } from "../layout/adaptive-workspace-context"; import { useSavedRemoteConnections } from "../../state/use-remote-environment-registry"; import { SettingsRow } from "./components/SettingsRow"; @@ -132,7 +136,7 @@ function ConfiguredSettingsRouteScreen() { onPress: () => navigation.navigate("SettingsAuth"), }, environmentsRow(gt("Environments"), Object.keys(savedConnectionsById).length), - connectServiceRow(gt("T3 Connect service")), + ...connectServiceRows(gt("T3 Connect service")), { id: "SettingsNotifications", icon: "bell.badge", @@ -151,22 +155,25 @@ function LocalSettingsRouteScreen() { ); } -function connectServiceRow(label: string): SettingsListRow { +function connectServiceRows(label: string): SettingsListRow[] { + if (!selfHostedRelayChoiceAvailable()) return []; const relay = readSelfHostedRelay(); - return { - id: "SettingsConnectService", - icon: "server.rack", - label, - value: relay ? new URL(relay.relayUrl).host : "T3 Connect", - valuePosition: "trailing", - target: "SettingsConnectService", - }; + return [ + { + id: "SettingsConnectService", + icon: "server.rack", + label, + value: relay ? new URL(relay.relayUrl).host : "T3 Connect", + valuePosition: "trailing", + target: "SettingsConnectService", + }, + ]; } function environmentsRow(label: string, count: number): SettingsListRow { diff --git a/apps/server/src/cli/connect.test.ts b/apps/server/src/cli/connect.test.ts index 4fbec456da09..a75cfe6d26ee 100644 --- a/apps/server/src/cli/connect.test.ts +++ b/apps/server/src/cli/connect.test.ts @@ -18,6 +18,7 @@ import { Command } from "effect/cli"; import { makeCli } from "../binCli.ts"; import { CLOUD_CLI_DESIRED_LINK_SECRET } from "../cloud/CliState.ts"; +import { RELAY_REMOTE_CONTROL_OFF_SECRET } from "../cloud/config.ts"; import { makePersistedServerRuntimeState, persistServerRuntimeState, @@ -104,6 +105,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer, NetService.layer)) readonly portFreed?: boolean; readonly command?: "unlink" | "status"; readonly linkMode?: "managed" | "publish_only"; + readonly activityOnly?: boolean; }, ) => Effect.gen(function* () { @@ -147,6 +149,12 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer, NetService.layer)) `${baseDir}/userdata/secrets/${CLOUD_CLI_DESIRED_LINK_SECRET}.bin`, options.linkMode ?? "managed", ); + if (options.activityOnly) { + yield* fs.writeFileString( + `${baseDir}/userdata/secrets/${RELAY_REMOTE_CONTROL_OFF_SECRET}.bin`, + "true", + ); + } } yield* Command.runWith(makeCli({ cloudEnabled: true }), { version: "0.0.0" })([ @@ -219,16 +227,23 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer, NetService.layer)) }), ); - it.effect("status does not report a publish-only link as exposed", () => - Effect.gen(function* () { - const { printed } = yield* runConnect(process.pid, { - command: "status", - linkMode: "publish_only", - }); + it.effect.each([ + { activityOnly: false, remoteControl: "on" }, + { activityOnly: true, remoteControl: "off" }, + ])( + "status says whether a publish-only link gives the relay remote control ($remoteControl)", + ({ activityOnly, remoteControl }) => + Effect.gen(function* () { + const { printed } = yield* runConnect(process.pid, { + command: "status", + linkMode: "publish_only", + activityOnly, + }); - assert.include(printed, "Exposure: publish-only"); - assert.notInclude(printed, "Other devices can reach this machine"); - }), + assert.include(printed, "Exposure: publish-only"); + assert.include(printed, `Remote control through the relay: ${remoteControl}`); + assert.notInclude(printed, "Other devices can reach this machine"); + }), ); it.effect("asks a running server to stop its tunnel", () => diff --git a/apps/server/src/cli/connect.ts b/apps/server/src/cli/connect.ts index eb651a6d8c94..ee699d58419a 100644 --- a/apps/server/src/cli/connect.ts +++ b/apps/server/src/cli/connect.ts @@ -44,6 +44,8 @@ import { CLOUD_LINKED_USER_ID, isAgentActivityPublishingEnabledValue, PUBLISH_AGENT_ACTIVITY_SECRET, + readRelayRemoteControlAllowed, + RELAY_REMOTE_CONTROL_OFF_SECRET, RELAY_URL_SECRET, } from "../cloud/config.ts"; import { relayUrlConfig } from "../cloud/publicConfig.ts"; @@ -154,6 +156,8 @@ interface CloudCliStatus { readonly cloudUserId: string | null; readonly relayUrl: string | null; readonly publishAgentActivity: boolean; + /** Whether a relay channel may carry remote control of this machine. */ + readonly relayRemoteControl: boolean; readonly relayClient: RelayClient.RelayClientStatus; readonly linkMode: CliState.CliDesiredLinkMode; /** `null` when no server answered the live check, or none ran because no tunnel is wanted. */ @@ -221,13 +225,16 @@ function formatCloudStatus( ` Environment link: ${provisioned}`, ` Relay: ${status.relayUrl ?? "not provisioned"}`, ` Publish agent activity: ${status.publishAgentActivity ? "enabled" : "disabled"}`, + ` Remote control through the relay: ${status.relayRemoteControl ? "on" : "off"}`, ...formatRelayClientStatus(status.relayClient), ...(!status.desired ? [] : publishOnly ? [ "", - "This link publishes agent activity without a managed tunnel. Remote access requires a self-hosted relay channel, a published HTTPS address, or another route such as LAN or Tailscale.", + status.relayRemoteControl + ? "This link has no managed tunnel, but a self-hosted relay with channels enabled can still carry remote control of this machine. Link with --activity-only to publish agent activity alone." + : "This link only publishes agent activity. Remote control has to use another route, such as LAN or Tailscale.", ] : status.reachability === null ? [ @@ -598,10 +605,13 @@ function formatRelayClientReady(version: string): string { const linkEnvironmentForConnect = Effect.fn("cloud.cli.link_environment")(function* (options: { readonly headless: boolean; readonly publishOnly?: boolean; + /** Publish agent activity, and refuse remote control even from a relay channel. */ + readonly activityOnly?: boolean; /** For `t3 up`, where the user already chose T3 Connect: install it quietly, without asking. */ readonly installRelayClient?: boolean; }) { - const publishOnly = options.publishOnly ?? false; + const activityOnly = options.activityOnly ?? false; + const publishOnly = activityOnly || (options.publishOnly ?? false); if (!publishOnly) { const relayClient = yield* RelayClient.RelayClient; const installed = yield* acquireRelayClientForLink( @@ -628,8 +638,11 @@ const linkEnvironmentForConnect = Effect.fn("cloud.cli.link_environment")(functi if (yield* CliState.dropRevokedCloudLink) { yield* Console.log("Replacing the link T3 Connect revoked."); } + const secrets = yield* ServerSecretStore.ServerSecretStore; + yield* activityOnly + ? secrets.set(RELAY_REMOTE_CONTROL_OFF_SECRET, stringToBytes("true")) + : secrets.remove(RELAY_REMOTE_CONTROL_OFF_SECRET); if (publishOnly) { - const secrets = yield* ServerSecretStore.ServerSecretStore; yield* secrets.set(PUBLISH_AGENT_ACTIVITY_SECRET, stringToBytes("true")); } return { identity } as const; @@ -659,7 +672,13 @@ const connectLinkCommand = Command.make("link", { headless: headlessFlag, publishOnly: Flag.Boolean("publish-only").pipe( Flag.withDescription( - "Link without a managed tunnel. A self-hosted relay with channels enabled carries remote access. Otherwise set T3CODE_PUBLIC_URL to publish an HTTPS address, or use another route such as Tailscale.", + "Link without a managed tunnel. Remote control stays on: a self-hosted relay with channels enabled carries it. Otherwise set T3CODE_PUBLIC_URL to publish an HTTPS address, or use another route such as Tailscale.", + ), + Flag.withDefault(false), + ), + activityOnly: Flag.Boolean("activity-only").pipe( + Flag.withDescription( + "Only publish agent activity to your mobile clients. Nothing, not even a relay channel, gets remote control of this machine through T3 Connect.", ), Flag.withDefault(false), ), @@ -675,9 +694,11 @@ const connectLinkCommand = Command.make("link", { if (linked) { const serveCommand = yield* resolveHostCliHint("serve", flags.baseDir); yield* Console.log( - flags.publishOnly - ? `✓ Authorized${connectedAs(linked.identity)}\n\nNext\n Start T3 to publish agent activity (no managed tunnel).` - : `✓ Authorized${connectedAs(linked.identity)}\n\nNext\n Start the server with \`${serveCommand}\` to make this machine reachable.`, + flags.activityOnly + ? `✓ Authorized${connectedAs(linked.identity)}\n\nRemote control through T3 Connect: off. This link only publishes agent activity.\n\nNext\n Start T3 to publish agent activity.` + : flags.publishOnly + ? `✓ Authorized${connectedAs(linked.identity)}\n\nRemote control through T3 Connect: ON. There is no managed tunnel, but a self-hosted relay with channels enabled can control this machine. Use --activity-only to publish agent activity alone.\n\nNext\n Start T3 to publish agent activity.` + : `✓ Authorized${connectedAs(linked.identity)}\n\nRemote control through T3 Connect: ON.\n\nNext\n Start the server with \`${serveCommand}\` to make this machine reachable.`, ); } }), @@ -708,6 +729,7 @@ const connectStatusCommand = Command.make("status", { revoked, executable, linkMode, + relayRemoteControl, ] = yield* Effect.all( [ CliState.readCliDesiredCloudLink, @@ -718,6 +740,7 @@ const connectStatusCommand = Command.make("status", { secrets.get(CLOUD_LINK_REVOKED), relayClient.resolve, CliState.readCliDesiredLinkMode, + readRelayRemoteControlAllowed, ], { concurrency: "unbounded" }, ); @@ -734,6 +757,7 @@ const connectStatusCommand = Command.make("status", { publishAgentActivity: isAgentActivityPublishingEnabledValue( Option.isSome(publishAgentActivity) ? bytesToString(publishAgentActivity.value) : null, ), + relayRemoteControl, relayClient: executable, linkMode, reachability, @@ -806,8 +830,9 @@ const connectPublishCommand = Command.make("publish", { return; } yield* CliState.setCliDesiredCloudLink(true, "publish_only"); + yield* secrets.set(RELAY_REMOTE_CONTROL_OFF_SECRET, stringToBytes("true")); yield* Console.log( - "Restart T3 to finish authorizing this environment to publish (no managed tunnel is created).", + "Restart T3 to finish authorizing this environment to publish. This link only publishes agent activity; it carries no remote control.", ); }), ), diff --git a/apps/server/src/cloud/CliState.ts b/apps/server/src/cloud/CliState.ts index 8c4d9d05c748..a34c98fcf52c 100644 --- a/apps/server/src/cloud/CliState.ts +++ b/apps/server/src/cloud/CliState.ts @@ -12,6 +12,7 @@ import { PUBLISH_AGENT_ACTIVITY_SECRET, RELAY_ENVIRONMENT_CREDENTIAL_SECRET, RELAY_ISSUER_SECRET, + RELAY_REMOTE_CONTROL_OFF_SECRET, RELAY_URL_SECRET, } from "./config.ts"; @@ -88,6 +89,7 @@ export const clearPersistedCloudLink = Effect.gen(function* () { secrets.remove(PUBLISH_AGENT_ACTIVITY_SECRET), secrets.remove(HOLD_WEBHOOKS_WHILE_OFFLINE_SECRET), secrets.remove(CLOUD_LINK_REVOKED), + secrets.remove(RELAY_REMOTE_CONTROL_OFF_SECRET), ], { concurrency: "unbounded" }, ); diff --git a/apps/server/src/cloud/CliTokenManager.test.ts b/apps/server/src/cloud/CliTokenManager.test.ts index 2a4c25c95870..f0e3765990c0 100644 --- a/apps/server/src/cloud/CliTokenManager.test.ts +++ b/apps/server/src/cloud/CliTokenManager.test.ts @@ -22,6 +22,7 @@ const TEST_ENV = { T3CODE_CLERK_PUBLISHABLE_KEY: "pk_test_Y2xlcmsuZXhhbXBsZS50ZXN0JA==", T3CODE_CLERK_CLI_OAUTH_CLIENT_ID: "oauth_client_test", T3CODE_HOSTED_APP_URL: "https://hosted.example.test", + T3CODE_RELAY_URL: "https://relay.example.test", }; interface RecordedTokenRequest { @@ -107,8 +108,14 @@ const layerDeviceFlow = (server: DeviceFlowServer) => const tokenRequests = (requests: ReadonlyArray) => requests.filter((request) => request.url.endsWith("/oauth/token")); +const RELAY_URL = "https://relay.example.test"; const expiredStoredToken = new TextEncoder().encode( - JSON.stringify({ accessToken: "expired", refreshToken: "refresh-token-1", expiresAtEpochMs: 0 }), + JSON.stringify({ + accessToken: "expired", + refreshToken: "refresh-token-1", + expiresAtEpochMs: 0, + provider: `clerk@${RELAY_URL}`, + }), ); const provideRefreshManager = ( @@ -252,14 +259,18 @@ it.effect.each([ ); const OIDC_ISSUER = "https://sso.example.test/realms/t3"; -const OIDC_ENV = { T3CODE_OIDC_ISSUER: OIDC_ISSUER, T3CODE_OIDC_CLIENT_ID: "t3-code" }; -// What an OIDC sign-in stored; `expiredStoredToken` has no provider, so Clerk issued it. +const OIDC_ENV = { + T3CODE_OIDC_ISSUER: OIDC_ISSUER, + T3CODE_OIDC_CLIENT_ID: "t3-code", + T3CODE_RELAY_URL: RELAY_URL, +}; +// What an OIDC sign-in through RELAY_URL stored; `expiredStoredToken` came from Clerk. const oidcStoredToken = new TextEncoder().encode( JSON.stringify({ accessToken: "expired", refreshToken: "refresh-token-1", expiresAtEpochMs: 0, - provider: `oidc:${OIDC_ISSUER}|t3-code`, + provider: `oidc:${OIDC_ISSUER}|t3-code@${RELAY_URL}`, }), ); @@ -363,7 +374,14 @@ it.effect("refuses an OIDC token response that carries no ID token", () => ), ); -it.effect("never refreshes a credential another provider issued", () => { +it.effect.each([ + ["another provider issued", expiredStoredToken, OIDC_ENV], + [ + "obtained through another relay", + oidcStoredToken, + { ...OIDC_ENV, T3CODE_RELAY_URL: "https://relay.attacker.example" }, + ], +] as const)("never presents a credential %s", ([, stored, env]) => { const requests: Array = []; return Effect.gen(function* () { const manager = yield* CliTokenManager.CloudCliTokenManager; @@ -371,7 +389,11 @@ it.effect("never refreshes a credential another provider issued", () => { assert.isFalse(yield* manager.hasCredential); assert.deepEqual(requests, []); }).pipe( - provideRefreshManager(oidcProvider({ requests, tokenResponse: {} }), undefined, OIDC_ENV), + provideRefreshManager( + oidcProvider({ requests, tokenResponse: {} }), + Layer.mock(ServerSecretStore.ServerSecretStore)({ get: () => Effect.succeedSome(stored) }), + env, + ), ); }); diff --git a/apps/server/src/cloud/CliTokenManager.ts b/apps/server/src/cloud/CliTokenManager.ts index 682c85fb5516..b523d441d324 100644 --- a/apps/server/src/cloud/CliTokenManager.ts +++ b/apps/server/src/cloud/CliTokenManager.ts @@ -47,6 +47,7 @@ import { cloudCliOAuthConfig, hostedAppUrlConfig, oidcSettingsConfig, + relayUrlConfig, type CloudCliOAuthConfig, } from "./publicConfig.ts"; import { renderLoopbackAuthorizationCompleteHtml } from "./cliAuthHtml.ts"; @@ -63,6 +64,30 @@ const DEVICE_AUTHORIZATION_SLOW_DOWN_INCREMENT = Duration.seconds(5); const OAUTH_REQUEST_TIMEOUT = Duration.seconds(10); const boldTerminalText = (value: string): string => `\u001b[1m${value}\u001b[22m`; +const hostOf = (url: string): string => { + try { + return new URL(url).host; + } catch { + return url; + } +}; + +/** + * Names the relay and sign-in host before any code or link, so a relay or provider swapped in + * through the environment is visible before the user approves anything. + */ +const describeSignInTarget = Effect.fn("cloud.cli_token.describe_sign_in_target")(function* ( + metadata: Pick, +) { + const relayUrl = yield* Config.option(relayUrlConfig); + return [ + `Signing in to T3 Connect through relay ${Option.getOrElse(relayUrl, () => "(none configured)")}`, + `with the sign-in provider at ${hostOf(metadata.tokenEndpoint)}.`, + "Continue only if you started this sign-in and recognize both addresses.", + "", + ].join("\n"); +}); + function formatLoopbackAuthorizationPrompt(authorizationUrl: string): string { return [ "Open this URL to authorize T3 Connect:", @@ -532,6 +557,7 @@ export const deviceAuthorizationLogin = Effect.fn("cloud.cli_token.device_author authorization.interval === undefined ? DEVICE_AUTHORIZATION_DEFAULT_INTERVAL : Duration.seconds(authorization.interval); + yield* Console.log(yield* describeSignInTarget(metadata)); yield* showPrompt({ verificationUri: authorization.verification_uri, verificationUriComplete: authorization.verification_uri_complete, @@ -560,12 +586,18 @@ export const make = Effect.gen(function* () { const terminal = yield* Terminal.Terminal; const externalLauncher = yield* ExternalLauncher.ExternalLauncher; const semaphore = yield* Semaphore.make(1); - // A credential works only with the provider that issued it; unstamped ones came from Clerk. - const currentProvider = Config.map( - oidcSettingsConfig, - Option.match({ - onNone: () => "clerk", - onSome: ({ issuer, clientId }) => `oidc:${issuer}|${clientId}`, + // A credential works only with the provider that issued it and the relay it was obtained for, + // so a changed T3CODE_RELAY_URL never receives it. Unstamped ones came from Clerk. + const currentProvider = Config.all({ + oidc: oidcSettingsConfig, + relayUrl: Config.option(relayUrlConfig), + }).pipe( + Config.map(({ oidc, relayUrl }) => { + const provider = Option.match(oidc, { + onNone: () => "clerk", + onSome: ({ issuer, clientId }) => `oidc:${issuer}|${clientId}`, + }); + return `${provider}@${Option.getOrElse(relayUrl, () => "")}`; }), ); const persist = Effect.fn("cloud.cli_token.persist")(function* (token: PersistedToken) { @@ -652,6 +684,7 @@ export const make = Effect.gen(function* () { nonce, challenge, }); + yield* Console.log(yield* describeSignInTarget(metadata)); yield* Console.log(formatLoopbackAuthorizationPrompt(authorizationUrl)); const authorization = yield* waitForLoopbackAuthorization({ authorizationUrl, diff --git a/apps/server/src/cloud/CloudLink.lifecycle.test.ts b/apps/server/src/cloud/CloudLink.lifecycle.test.ts index 1bb835193e12..8c98c4e57f00 100644 --- a/apps/server/src/cloud/CloudLink.lifecycle.test.ts +++ b/apps/server/src/cloud/CloudLink.lifecycle.test.ts @@ -53,6 +53,7 @@ import { decodeRuntimeConfig, RELAY_ENVIRONMENT_CREDENTIAL_SECRET, RELAY_ISSUER_SECRET, + RELAY_REMOTE_CONTROL_OFF_SECRET, RELAY_URL_SECRET, } from "./config.ts"; import * as CloudLink from "./CloudLink.ts"; @@ -403,6 +404,48 @@ describe("releaseManagedTunnelOnShutdown", () => { }).pipe(provideReleaseHarness({ store, applyConfigCalls, requests })); }); + const relayChannelConfig = { + providerKind: "t3_relay" as const, + connectorToken: "credential", + channelUrl: "wss://relay.example.test/v1/environments/env_123/channel", + }; + + it.effect("an activity-only link refuses a relay channel the relay hands it", () => { + const { store, values } = makeMemorySecretStore([[RELAY_REMOTE_CONTROL_OFF_SECRET, "true"]]); + const applyConfigCalls: Array = []; + + return Effect.gen(function* () { + const link = yield* CloudLink.CloudLink; + expect( + yield* link.applyRelayConfig({ + relayUrl: "https://relay.example.test", + cloudUserId: "user-123", + environmentCredential: "environment-credential", + cloudMintPublicKey: + "-----BEGIN PUBLIC KEY-----\nMCowBQYDK2VwAyEAqZ2u2LjMoAyG2QTHXmITJ9w6RzZtVUAv394XCcPV0zE=\n-----END PUBLIC KEY-----", + endpointRuntime: relayChannelConfig, + }), + ).toMatchObject({ ok: true, endpointRuntimeStatus: { status: "disabled" } }); + expect(applyConfigCalls.filter((config) => config !== null)).toEqual([]); + expect(values.has(CLOUD_ENDPOINT_RUNTIME_CONFIG)).toBe(false); + expect(values.has(CLOUD_LINKED_USER_ID)).toBe(true); + }).pipe(provideReleaseHarness({ store, applyConfigCalls, requests: [] })); + }); + + it.effect("an activity-only link does not start a relay channel stored before", () => { + const { store } = makeMemorySecretStore([ + [CLOUD_ENDPOINT_RUNTIME_CONFIG, JSON.stringify(relayChannelConfig)], + [RELAY_REMOTE_CONTROL_OFF_SECRET, "true"], + ]); + const applyConfigCalls: Array = []; + + return Effect.gen(function* () { + const link = yield* CloudLink.CloudLink; + expect(yield* link.startManagedTunnelIfOriginConfirmed("http://127.0.0.1:3773")).toBe(false); + expect(applyConfigCalls).toEqual([]); + }).pipe(provideReleaseHarness({ store, applyConfigCalls, requests: [] })); + }); + it.effect("stops the connector, releases the relay tunnel, and drops the dead token", () => { const { store, values } = makeMemorySecretStore(managedLinkSecrets); const applyConfigCalls: Array = []; diff --git a/apps/server/src/cloud/CloudLink.ts b/apps/server/src/cloud/CloudLink.ts index 459a4ac1032a..fad942a073f8 100644 --- a/apps/server/src/cloud/CloudLink.ts +++ b/apps/server/src/cloud/CloudLink.ts @@ -91,8 +91,10 @@ import { HOLD_WEBHOOKS_WHILE_OFFLINE_SECRET, PUBLISH_AGENT_ACTIVITY_SECRET, readRelayConnection, + readRelayRemoteControlAllowed, RELAY_ENVIRONMENT_CREDENTIAL_SECRET, RELAY_ISSUER_SECRET, + RELAY_REMOTE_CONTROL_OFF_SECRET, RELAY_URL_SECRET, } from "./config.ts"; import { EnvironmentSigningKey } from "./environmentKeys.ts"; @@ -738,6 +740,7 @@ const make = Effect.gen(function* () { if (Option.isNone(runtimeBytes)) return false; const config = Option.getOrNull(decodeRuntimeConfig(bytesToString(runtimeBytes.value))); if (config?.providerKind === "t3_relay") { + if (!(yield* readRelayRemoteControlAllowed.pipe(withSecrets))) return false; // The channel dials out and forwards to whatever port this server listens on now. const status = yield* endpointRuntime.applyConfig(config, localOrigin); if (status.status !== "running") { @@ -799,8 +802,17 @@ const make = Effect.gen(function* () { }, }); } - const endpointRuntimeJson = payload.endpointRuntime - ? yield* encodeEndpointRuntimeConfigJson(payload.endpointRuntime) + const remoteControlRefused = + payload.endpointRuntime?.providerKind === "t3_relay" && + !(yield* readRelayRemoteControlAllowed.pipe(withSecrets)); + if (remoteControlRefused) { + yield* Effect.logInfo( + "T3 Connect remote control through the relay is off; this link only publishes activity.", + ); + } + const runtimeConfig = remoteControlRefused ? null : payload.endpointRuntime; + const endpointRuntimeJson = runtimeConfig + ? yield* encodeEndpointRuntimeConfigJson(runtimeConfig) : null; yield* endpointRuntime.applyConfig(null); yield* secrets.remove(CLOUD_ENDPOINT_CONFIRMED_ORIGIN); @@ -823,14 +835,14 @@ const make = Effect.gen(function* () { if (endpointRuntimeJson !== null) { yield* secrets.set(CLOUD_ENDPOINT_RUNTIME_CONFIG, stringToBytes(endpointRuntimeJson)); } - if (payload.endpointRuntime === null || options?.confirmedOrigin === undefined) { + if (runtimeConfig === null || options?.confirmedOrigin === undefined) { return { ok: true, endpointRuntimeStatus: { status: "disabled" }, } satisfies EnvironmentCloudRelayConfigResult; } const endpointRuntimeStatus = yield* endpointRuntime.applyConfig( - payload.endpointRuntime, + runtimeConfig, localOriginUrl(options.confirmedOrigin), ); if (endpointRuntimeStatus.status !== "running") { @@ -840,7 +852,7 @@ const make = Effect.gen(function* () { }); } const marker = yield* encodeConfirmedOriginJson({ - config: payload.endpointRuntime, + config: runtimeConfig, origin: options.confirmedOrigin, }); yield* secrets.set(CLOUD_ENDPOINT_CONFIRMED_ORIGIN, stringToBytes(marker)); @@ -1401,6 +1413,7 @@ const make = Effect.gen(function* () { secrets.remove(PUBLISH_AGENT_ACTIVITY_SECRET), secrets.remove(HOLD_WEBHOOKS_WHILE_OFFLINE_SECRET), secrets.remove(CLOUD_LINK_REVOKED), + secrets.remove(RELAY_REMOTE_CONTROL_OFF_SECRET), ], { concurrency: 10 }, ); diff --git a/apps/server/src/cloud/ConnectReachability.ts b/apps/server/src/cloud/ConnectReachability.ts index e89f5ab3a2cc..86c15f4f8eac 100644 --- a/apps/server/src/cloud/ConnectReachability.ts +++ b/apps/server/src/cloud/ConnectReachability.ts @@ -505,7 +505,7 @@ const make = Effect.gen(function* () { ); } else { yield* Effect.logInfo( - `T3 Connect is reachable from other devices. ${formatConnectReachable(result)}`, + `T3 Connect remote control is on: other devices can reach this machine. ${formatConnectReachable(result)}`, ); } return result; diff --git a/apps/server/src/cloud/config.ts b/apps/server/src/cloud/config.ts index 5dac9e2db905..20156215e987 100644 --- a/apps/server/src/cloud/config.ts +++ b/apps/server/src/cloud/config.ts @@ -2,6 +2,7 @@ import { RelayManagedEndpointOrigin, RelayManagedEndpointRuntimeConfig, } from "@t3tools/contracts/relay"; +import * as Config from "effect/Config"; import * as Effect from "effect/Effect"; import * as Option from "effect/Option"; import * as Schema from "effect/Schema"; @@ -18,6 +19,23 @@ export const RELAY_ENVIRONMENT_CREDENTIAL_SECRET = "cloud-relay-environment-cred export const PUBLISH_AGENT_ACTIVITY_SECRET = "cloud-publish-agent-activity"; export const HOLD_WEBHOOKS_WHILE_OFFLINE_SECRET = "cloud-hold-webhooks-while-offline"; export const CLOUD_LINK_REVOKED = "cloud-link-revoked"; +/** Set by an activity-only link: the relay may receive activity but never carry remote control. */ +export const RELAY_REMOTE_CONTROL_OFF_SECRET = "cloud-relay-remote-control-off"; + +/** + * Whether this host lets a relay channel carry remote control. `T3CODE_RELAY_REMOTE_CONTROL=false` + * turns it off for every link; an activity-only link turns it off for that link. + */ +export const readRelayRemoteControlAllowed = Effect.gen(function* () { + const allowedByEnvironment = yield* Config.Boolean("T3CODE_RELAY_REMOTE_CONTROL").pipe( + Config.withDefault(true), + // A value that does not parse fails closed. + Effect.orElseSucceed(() => false), + ); + if (!allowedByEnvironment) return false; + const secrets = yield* ServerSecretStore.ServerSecretStore; + return Option.isNone(yield* secrets.get(RELAY_REMOTE_CONTROL_OFF_SECRET)); +}); export const encodeEndpointRuntimeConfigJson = Schema.encodeEffect( Schema.fromJsonString(RelayManagedEndpointRuntimeConfig), diff --git a/apps/web/src/cloud/oidc/browserOidc.ts b/apps/web/src/cloud/oidc/browserOidc.ts index 1cab9f0d9a5a..a53c0719379c 100644 --- a/apps/web/src/cloud/oidc/browserOidc.ts +++ b/apps/web/src/cloud/oidc/browserOidc.ts @@ -1,8 +1,12 @@ import { isDesktopOidcCallbackUrl, OIDC_CALLBACK_PATH } from "@t3tools/shared/oidc"; +import type { DesktopBridge } from "@t3tools/contracts"; + import { resolveOidcPublicConfig } from "../publicConfig"; import { + clearStoredOidcSessions, createOidcController, + OIDC_SESSION_STORAGE_KEY, type KeyValueStore, type OidcController, } from "@t3tools/client-runtime/relay"; @@ -22,18 +26,69 @@ const storageOrMemory = (read: () => Storage): KeyValueStore => { } }; +// The main process keeps the session encrypted with the OS keychain; this mirror answers the +// controller's synchronous reads. +function desktopSessionStore(bridge: DesktopBridge): KeyValueStore { + let session = bridge.getOidcSession(); + const write = (value: string | null) => { + session = value; + // Unsaved, the session still lasts until the app quits. + void bridge.setOidcSession(value).catch(() => undefined); + }; + return { + getItem: (key) => (key === OIDC_SESSION_STORAGE_KEY ? session : null), + setItem: (key, value) => { + if (key === OIDC_SESSION_STORAGE_KEY) write(value); + }, + removeItem: (key) => { + if (key === OIDC_SESSION_STORAGE_KEY) write(null); + }, + }; +} + +// Entra and other providers refuse to redeem a code from the renderer's t3code:// origin, so the +// main process, which sends no Origin, makes the token requests. +const desktopTokenFetch = + (bridge: DesktopBridge, issuer: string): typeof fetch => + async (input, init) => { + if (init?.method !== "POST") return fetch(input, init); + const reply = await bridge.requestOidcToken({ + issuer, + tokenEndpoint: String(input), + body: String(init.body), + }); + return new Response(reply.body, { + status: reply.status, + headers: { "content-type": "application/json" }, + }); + }; + let controller: OidcController | null = null; -/** The one controller for this page; null when the build has no OpenID Connect provider. */ +/** + * The one controller for this page; null when the build has no OpenID Connect provider. The web + * keeps the session in this tab's sessionStorage, so it ends with the tab and other tabs sign in + * on their own; the desktop app keeps it encrypted in the main process. + */ export function getBrowserOidcController(): OidcController | null { const config = resolveOidcPublicConfig(); if (config === null) return null; - controller ??= createOidcController({ + if (controller !== null) return controller; + try { + // Drops sessions earlier builds left in long-lived localStorage. + clearStoredOidcSessions(window.localStorage); + } catch {} + const bridge = window.desktopBridge; + controller = createOidcController({ config, redirectUri: `${window.location.origin}${OIDC_CALLBACK_PATH}`, - sessions: storageOrMemory(() => window.localStorage), + sessions: + bridge === undefined + ? storageOrMemory(() => window.sessionStorage) + : desktopSessionStore(bridge), pending: storageOrMemory(() => window.sessionStorage), navigate: (url) => window.location.assign(url), + ...(bridge === undefined ? {} : { fetch: desktopTokenFetch(bridge, config.issuer) }), ...(navigator.locks === undefined ? {} : { withRefreshLock: (run) => navigator.locks.request("t3-oidc-refresh", run) }), diff --git a/apps/web/src/cloud/publicConfig.ts b/apps/web/src/cloud/publicConfig.ts index 7f0b8aa0ddb4..bb1ea1068854 100644 --- a/apps/web/src/cloud/publicConfig.ts +++ b/apps/web/src/cloud/publicConfig.ts @@ -3,9 +3,12 @@ import { relayClerkTokenOptions, } from "@t3tools/shared/relayAuth"; import { + canChooseSelfHostedRelay, encodeSelfHostedRelay, + parseRelayPolicy, parseStoredSelfHostedRelay, SELF_HOSTED_RELAY_STORAGE_KEY, + type RelayPolicy, type SelfHostedRelay, } from "@t3tools/client-runtime/relay/self-hosted"; import { normalizeSecureRelayUrl } from "@t3tools/shared/relayUrl"; @@ -50,6 +53,17 @@ function normalizeSecureUrl(value: string): string | null { } } +/** Which relays this build lets the user switch to (`T3CODE_RELAY_PINNED`, `T3CODE_RELAY_ALLOWLIST`). */ +export function resolveRelayPolicy(): RelayPolicy { + return parseRelayPolicy({ + pinned: import.meta.env.VITE_T3CODE_RELAY_PINNED as string | undefined, + allowlist: import.meta.env.VITE_T3CODE_RELAY_ALLOWLIST as string | undefined, + }); +} + +export const selfHostedRelayChoiceAvailable = (): boolean => + canChooseSelfHostedRelay(resolveRelayPolicy()); + let selfHostedRelay: SelfHostedRelay | null | undefined; /** The relay the user chose in settings; it replaces the build's T3 Connect until cleared. */ @@ -58,6 +72,7 @@ export function readSelfHostedRelay(): SelfHostedRelay | null { try { selfHostedRelay = parseStoredSelfHostedRelay( window.localStorage.getItem(SELF_HOSTED_RELAY_STORAGE_KEY), + resolveRelayPolicy(), ); } catch { selfHostedRelay = null; @@ -139,13 +154,14 @@ export function resolveRelayTracingConfig() { export interface OidcPublicConfig { readonly issuer: string; readonly clientId: string; + readonly relayUrl: string; } /** An OpenID Connect provider takes the place of Clerk when the build configures one. */ export function resolveOidcPublicConfig(): OidcPublicConfig | null { const { oidcIssuer, oidcClientId, relayUrl } = resolveCloudPublicConfig(); return oidcIssuer && oidcClientId && relayUrl - ? { issuer: oidcIssuer, clientId: oidcClientId } + ? { issuer: oidcIssuer, clientId: oidcClientId, relayUrl } : null; } diff --git a/apps/web/src/components/settings/T3ConnectServiceSettings.tsx b/apps/web/src/components/settings/T3ConnectServiceSettings.tsx index c7f17b7aa00b..b7fb777fe669 100644 --- a/apps/web/src/components/settings/T3ConnectServiceSettings.tsx +++ b/apps/web/src/components/settings/T3ConnectServiceSettings.tsx @@ -6,7 +6,12 @@ import { msg, T, useGT, useMessages } from "gt-react"; import { useState } from "react"; import { useCloudAuth } from "~/cloud/cloudAuth"; -import { readSelfHostedRelay, saveSelfHostedRelay } from "~/cloud/publicConfig"; +import { + readSelfHostedRelay, + resolveRelayPolicy, + saveSelfHostedRelay, + selfHostedRelayChoiceAvailable, +} from "~/cloud/publicConfig"; import { Button } from "../ui/button"; import { Input } from "../ui/input"; import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../ui/select"; @@ -36,6 +41,10 @@ const switchTo = (relay: SelfHostedRelay | null) => { /** Chooses between the build's T3 Connect and a relay the user runs themselves. */ export function T3ConnectServiceSettings() { + return selfHostedRelayChoiceAvailable() ? : null; +} + +function ServiceChoice() { const searchableSetting = useSearchableSetting(); const gt = useGT(); const m = useMessages(); @@ -50,7 +59,7 @@ export function T3ConnectServiceSettings() { setError(null); setIsChecking(true); try { - switchTo(await discoverSelfHostedRelay(address)); + switchTo(await discoverSelfHostedRelay(address, { policy: resolveRelayPolicy() })); } catch (cause) { setError(cause instanceof Error ? cause.message : gt("Could not reach the relay.")); setIsChecking(false); diff --git a/apps/web/src/components/settings/settingsSearch.ts b/apps/web/src/components/settings/settingsSearch.ts index af8a94991461..ac26b80fd5d4 100644 --- a/apps/web/src/components/settings/settingsSearch.ts +++ b/apps/web/src/components/settings/settingsSearch.ts @@ -1,4 +1,5 @@ import { HOSTED_APP_CHANNEL } from "~/branding"; +import { selfHostedRelayChoiceAvailable } from "~/cloud/publicConfig"; import { isElectron, isSecretsFeatureEnabled } from "~/env"; import { isMacPlatform, isWindowsPlatform, normalizeSearchText } from "~/lib/utils"; import { STATIC_KEYBINDING_COMMANDS, type KeybindingCommand } from "@t3tools/contracts"; @@ -71,6 +72,8 @@ export interface SettingsSearchItem { readonly wslAvailableOnly?: boolean; readonly managedTunnelOnly?: boolean; readonly peerLinksOnly?: boolean; + /** Hidden in builds pinned to their own relay. */ + readonly selfHostedRelayChoiceOnly?: boolean; readonly fastWorktreeCheckoutOnly?: boolean; readonly textGeneratorsOnly?: boolean; readonly secondary?: boolean; @@ -1417,6 +1420,7 @@ export const SETTINGS_SEARCH_ITEMS = [ }, { id: "t3-connect-service", + selfHostedRelayChoiceOnly: true, title: msg("T3 Connect service"), to: "/settings/connections", searchTerms: [msg("self-hosted relay own server oidc openid sso sign-in provider")], @@ -1639,6 +1643,7 @@ export function settingsForThisPlatform( (isElectron || item.desktopOnly !== true) && (!item.releaseChannelOnly || isElectron || HOSTED_APP_CHANNEL !== null) && (!item.secretsFeatureOnly || isSecretsFeatureEnabled) && + (!item.selfHostedRelayChoiceOnly || selfHostedRelayChoiceAvailable()) && (!item.macOnly || isMacPlatform(platform)) && (!item.windowsOnly || isWindowsPlatform(platform)), ); diff --git a/apps/web/vite.config.ts b/apps/web/vite.config.ts index 43c7579a0d1d..c993541872ae 100644 --- a/apps/web/vite.config.ts +++ b/apps/web/vite.config.ts @@ -37,6 +37,8 @@ const host = explicitHost || "localhost"; const configuredWsUrl = isSingleOriginDev ? undefined : process.env.VITE_WS_URL?.trim(); const configuredHttpUrl = isSingleOriginDev ? undefined : process.env.VITE_HTTP_URL?.trim(); const configuredRelayUrl = repoEnv.VITE_T3CODE_RELAY_URL?.trim() || ""; +const configuredRelayPinned = repoEnv.T3CODE_RELAY_PINNED?.trim() || ""; +const configuredRelayAllowlist = repoEnv.T3CODE_RELAY_ALLOWLIST?.trim() || ""; const configuredClerkPublishableKey = repoEnv.VITE_CLERK_PUBLISHABLE_KEY?.trim() || ""; const configuredClerkJwtTemplate = repoEnv.VITE_CLERK_JWT_TEMPLATE?.trim() || ""; const configuredClerkCliOAuthClientId = repoEnv.VITE_CLERK_CLI_OAUTH_CLIENT_ID?.trim() || ""; @@ -356,6 +358,8 @@ export default defineConfig(({ command }) => { // Override .env URLs with empty values in single-origin dev so clients use window.location.origin. "import.meta.env.VITE_HTTP_URL": JSON.stringify(configuredHttpUrl ?? ""), "import.meta.env.VITE_T3CODE_RELAY_URL": JSON.stringify(configuredRelayUrl), + "import.meta.env.VITE_T3CODE_RELAY_PINNED": JSON.stringify(configuredRelayPinned), + "import.meta.env.VITE_T3CODE_RELAY_ALLOWLIST": JSON.stringify(configuredRelayAllowlist), "import.meta.env.VITE_CLERK_PUBLISHABLE_KEY": JSON.stringify(configuredClerkPublishableKey), "import.meta.env.VITE_CLERK_JWT_TEMPLATE": JSON.stringify(configuredClerkJwtTemplate), "import.meta.env.VITE_CLERK_CLI_OAUTH_CLIENT_ID": JSON.stringify( diff --git a/docs/operations/connect-setup.md b/docs/operations/connect-setup.md index 899d5c4a33a8..382d267c7a45 100644 --- a/docs/operations/connect-setup.md +++ b/docs/operations/connect-setup.md @@ -34,6 +34,18 @@ Copy `infra/relay/.env.example` to `infra/relay/.env` for relay deployment setti Deploy `prod` before personal stages because it owns the retained database that their branches depend on. The stack's `PublishClientConfig` action writes the resulting relay URL back to the root `.env`. +## Restricting relays + +A build lets users switch to any self-hosted relay under **T3 Connect service** unless it sets: + +| Variable | Effect | +| ------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `T3CODE_RELAY_PINNED` | `true`: web, desktop and mobile use only `T3CODE_RELAY_URL`. The service choice is hidden and a relay chosen earlier is ignored. | +| `T3CODE_RELAY_ALLOWLIST` | Comma-separated HTTPS origins the self-hosted choice accepts; any other address is refused before it is contacted. An allowlist with no valid origin hides the choice. | + +Sign-in sessions are bound to the relay they were obtained for, so a switch always signs in again. +The CLI's stored credential is bound to `T3CODE_RELAY_URL` the same way. + ## CLI OAuth application In Clerk's OAuth applications settings: diff --git a/docs/user/remote-access.md b/docs/user/remote-access.md index bd96c6a516a6..5d3d5f5c42ed 100644 --- a/docs/user/remote-access.md +++ b/docs/user/remote-access.md @@ -97,6 +97,10 @@ Connect provider instead of a T3 account. Set up the relay first with On each web, desktop, and mobile app, open **Settings → Connections → T3 Connect service**, choose **Self-hosted relay**, and enter the relay's address. The app reads the sign-in provider from the relay, reloads, and asks you to sign in. +Every switch signs you out, so a relay never receives a sign-in made for another. +An organization's build may hide this choice or accept only its own relays. +In a browser, the sign-in lasts for the tab: a new tab or browser session signs +in again. Choose **T3 Connect** there to switch back. Environments you linked through your relay stay linked to it until you turn T3 Connect off and on again. To remove one from your relay account, choose **Linked environments → Manage** there, or @@ -107,8 +111,15 @@ A self-hosted relay has no managed tunnels. If the relay sets through the relay itself, so there is nothing to expose. Otherwise your other devices reach it only at an HTTPS address you expose yourself, such as a reverse proxy or [Tailscale HTTPS](#tailscale-https): start the host with that address in -`T3CODE_PUBLIC_URL`. Tailscale and LAN addresses also need -`RELAY_MANUAL_ENDPOINTS=private` on the relay. +`T3CODE_PUBLIC_URL`. The relay must allow such addresses with +`RELAY_MANUAL_ENDPOINTS=public`, or `private` for Tailscale and LAN addresses. + +A relay channel gives approved devices remote control of the host, even when it +only listens on localhost. `t3 connect link --publish-only` skips the managed +tunnel but keeps that channel. To only publish agent activity, with no remote +control through T3 Connect, run `t3 connect link --activity-only`, or start the +host with `T3CODE_RELAY_REMOTE_CONTROL=false` to refuse channels for every link. +`t3 connect status` shows which one applies. For a command-line host, set the relay before `t3 connect`: diff --git a/infra/relay/selfhost/.env.example b/infra/relay/selfhost/.env.example index 510884928a30..0e57d77383f8 100644 --- a/infra/relay/selfhost/.env.example +++ b/infra/relay/selfhost/.env.example @@ -1,4 +1,5 @@ -# Copy to .env and fill in. Nothing here is a secret except POSTGRES_PASSWORD. +# Copy to .env and fill in. Nothing here is a secret: keys and database passwords are files +# under secrets/, created by gen-keys.sh. # Public HTTPS origin clients use to reach the relay, served by Caddy. RELAY_PUBLIC_ORIGIN=https://relay.example.com @@ -11,15 +12,15 @@ OIDC_ISSUER=https://sso.example.com/realms/t3 # The OAuth client id of the T3 Code apps. Clients send their ID token, whose `aud` is that id. OIDC_AUDIENCE=t3-code -# Environments you expose yourself (no tunnel): "public" brokers internet-reachable HTTPS -# addresses, "private" also LAN/Tailscale addresses, "off" refuses them. -RELAY_MANUAL_ENDPOINTS=public - # Optional: carry environments with no public address through the relay itself, at # RELAY_PUBLIC_ORIGIN/env//. No DNS or certificate beyond the relay's own. # RELAY_CHANNELS=true -POSTGRES_PASSWORD=change-me +# Optional: environments you expose yourself (no tunnel). "off" (the default) refuses them, +# "public" brokers internet-reachable HTTPS addresses, "private" also LAN/Tailscale addresses. +# The relay connects to whatever address a linking user declares, so leave this off unless +# you need it. +# RELAY_MANUAL_ENDPOINTS=off # Optional: host ports, when 80 and 443 are taken. # HTTP_PORT=80 diff --git a/infra/relay/selfhost/Caddyfile b/infra/relay/selfhost/Caddyfile index f1938b50ebb5..1bb978b7bae3 100644 --- a/infra/relay/selfhost/Caddyfile +++ b/infra/relay/selfhost/Caddyfile @@ -1,5 +1,49 @@ # Caddy terminates TLS and forwards to the relay. The relay trusts its configured # RELAY_PUBLIC_ORIGIN, not forwarded headers, so no proxy header configuration is needed. +{ + servers { + # No body or write timeout: relay channels hold long WebSockets and large uploads. + timeouts { + read_header 10s + idle 5m + } + } +} + {$RELAY_DOMAIN} { - reverse_proxy relay:8080 + # Optional: accept only your own networks. Webhook senders and phones off the VPN need a way + # in too. Certificate renewal over port 80 is not affected. + # @outside not remote_ip 10.0.0.0/8 172.16.0.0/12 192.168.0.0/16 + # respond @outside 403 + + header { + Strict-Transport-Security "max-age=31536000" + -Server + } + + # Environments carried by relay channels. The relay gives their documents a sandbox CSP and + # nosniff, and the apps frame their file previews, so no framing policy here. 64 MiB is the + # relay's own channel request limit. + @carried path /env/* + handle @carried { + request_body { + max_size 64MiB + } + reverse_proxy relay:8080 + } + + # The relay API: JSON, webhooks up to 1 MiB, and the API reference at /docs. + handle { + request_body { + max_size 2MiB + } + header { + X-Content-Type-Options nosniff + X-Frame-Options DENY + Content-Security-Policy "frame-ancestors 'none'" + Referrer-Policy no-referrer + defer + } + reverse_proxy relay:8080 + } } diff --git a/infra/relay/selfhost/Dockerfile b/infra/relay/selfhost/Dockerfile index 1bbd8aa769f8..b892f3337255 100644 --- a/infra/relay/selfhost/Dockerfile +++ b/infra/relay/selfhost/Dockerfile @@ -1,5 +1,6 @@ # Self-hosted T3 relay. Build from the repository root (see README.md in this directory). -FROM node:26-alpine AS build +# Base images are pinned by digest; README.md shows how to refresh them. +FROM node:26-alpine@sha256:6bd9ab43c0ec0190ca7b2d193906cb8b7edf6e7f4afa43ddeccd6452710bffb5 AS build RUN npm install -g pnpm@12.14.0 vite-plus@1.4.0 WORKDIR /repo COPY . . @@ -8,7 +9,9 @@ RUN pnpm install --frozen-lockfile --ignore-scripts --filter "t3code-relay..." # The bundle inlines every dependency, so the runtime image needs no node_modules. RUN vp pack infra/relay/src/node.ts --format esm --platform node --root infra/relay --out-dir /out --no-dts -FROM node:26-alpine +FROM node:26-alpine@sha256:6bd9ab43c0ec0190ca7b2d193906cb8b7edf6e7f4afa43ddeccd6452710bffb5 +# The relay never installs packages at runtime; npm only adds code to patch. +RUN rm -rf /usr/local/lib/node_modules/npm /usr/local/bin/npm /usr/local/bin/npx WORKDIR /app ENV NODE_ENV=production \ PORT=8080 \ diff --git a/infra/relay/selfhost/OPERATING.md b/infra/relay/selfhost/OPERATING.md new file mode 100644 index 000000000000..612ebb79df06 --- /dev/null +++ b/infra/relay/selfhost/OPERATING.md @@ -0,0 +1,82 @@ +# Operating a self-hosted relay + +How to run a self-hosted relay for an organization. Set it up with [README.md](./README.md) first. + +## What you are operating + +The relay is workstation-control infrastructure. It signs the proofs that linked machines accept +before granting access, and with relay channels it carries their traffic. Whoever controls the +relay host, its cloud-mint private key or its HTTPS endpoint can act on every linked machine. +Protect it like a CI runner that holds deploy keys. + +## The relay host + +- Run it on a dedicated host or VM. Limit shell and Docker access to the people who operate it; + Docker access is root on the host. +- Keep the files in `secrets/` in a secret manager. Never put the cloud-mint private key in an + image, a repository or a ticket. +- Allow outbound traffic only to your identity provider's discovery and key endpoints, the relay's + own public address (relay channels check carried environments through it), your certificate + authority for Caddy, and your package mirror. +- Do not capture its traffic or log request bodies, `Authorization` headers or query strings. + Channel traffic includes prompts, code and session tokens. +- Leave `RELAY_MANUAL_ENDPOINTS=off` unless machines must be reached at their own address. Use + relay channels for machines without a public address. +- Optionally restrict who can reach the relay with the `remote_ip` example in `Caddyfile`. +- A restart drops every relay channel until machines reconnect. + +## Identity provider + +Without these, every account the identity provider issues a token to can sign in to the relay and +link machines. The settings below are named for Microsoft Entra ID; other providers have +equivalents. + +- **Assignment required.** In **Enterprise applications**, set **Assignment required?** to **Yes** + and assign the group of T3 Code users. +- **Conditional Access.** Require MFA and a compliant device for the app, and bound sessions with + **Sign-in frequency**. +- **Device code flow.** Only headless CLI sign-in needs it, and it is a common phishing route. + Limit it to a small group, or set **Allow public client flows** to **No** when nobody needs it. +- **No API scope.** Do not add scopes under **Expose an API**. The relay accepts ID tokens whose + audience is the client id and refuses access tokens. +- **Token lifetime.** A stolen ID token works at the relay until it expires, an hour by default. + A shorter ID token lifetime narrows that window. +- **Issuer.** Use the tenant-specific v2.0 issuer, never `/common` or `/organizations`. + +Pin your client builds to this relay with `T3CODE_RELAY_PINNED` or `T3CODE_RELAY_ALLOWLIST` +([connect setup](../../../docs/operations/connect-setup.md#restricting-relays)), so users cannot +be pointed at a look-alike relay. + +## Linked machines + +- Turn on **Require approval for new devices** in **Settings → Sharing & access** on each host. + Without it, anyone who signs in as the user, or who holds the relay's key, can connect a new + device without a prompt. +- Agent activity publishing sends project and thread titles to the relay. Decide whether hosts + should publish it. + +## Offboarding + +Disabling a user in the identity provider stops new sign-ins, but machines they linked and devices +that already connected keep working until revoked. In order: + +1. **Identity provider.** Disable the account or remove it from the app's group, then revoke its + sessions. +2. **Relay.** Run + `docker compose exec relay node src/node.mjs offboard --subject [--issuer ]` + with the user's `sub` claim. In one transaction it revokes their environment links and + credentials and deletes their device and push registrations. Their relay channels close within + seconds. `--issuer` defaults to `OIDC_ISSUER`. +3. **Their machines.** On each machine the user linked, revoke their devices with + `t3 auth connect-device list` and `t3 auth connect-device revoke `, and their sessions + with `t3 auth session list` and `t3 auth session revoke `. +4. **Verify.** Their devices no longer appear in either list, and a sign-in from their account + fails at the identity provider. + +## Known limitations + +- **No end-to-end encryption.** The relay operator can read and change relay channel traffic, and + can mint access to linked machines with the cloud-mint key. +- **Custom-scheme mobile redirects.** Another Android app can register the same scheme and receive + the sign-in redirect. PKCE stops it from redeeming the code alone. +- **Single replica.** Relay channels, queues and rate limits live in one process. diff --git a/infra/relay/selfhost/README.md b/infra/relay/selfhost/README.md index 3637c8f59dce..0923595c9e15 100644 --- a/infra/relay/selfhost/README.md +++ b/infra/relay/selfhost/README.md @@ -6,18 +6,27 @@ account is needed. Every web, desktop, mobile and CLI client signed in to the same account sees the same linked environments, and opens their projects and threads live through them; that is how clients stay -in sync. Thread data stays on each environment, never on the relay. +in sync. Threads are stored on each environment, not on the relay, but the relay stores some +metadata about them, and with relay channels their live traffic passes through it (see +[What the relay stores and sees](#what-the-relay-stores-and-sees)). + +Whoever controls the relay host, its signing key or its HTTPS endpoint can reach every machine +linked to it. Before running it for a team, read [Operating a self-hosted relay](./OPERATING.md). ## Setup Run these from the repository root. -1. Create the cloud-mint signing keys (once): +1. Create the secrets (once): the cloud-mint signing keys and the database passwords. ```sh infra/relay/selfhost/gen-keys.sh ``` + The containers read the secret files as uid 1000 (relay) and uid 70 (Postgres). Run the + `sudo chown` commands the script prints, or run it as root. Keep a copy of the files in your + secret manager. + 2. Configure the stack: ```sh @@ -25,9 +34,7 @@ Run these from the repository root. ``` Set `RELAY_DOMAIN` and `RELAY_PUBLIC_ORIGIN` to the host name that resolves to this server, - `OIDC_ISSUER` to your provider's issuer URL, and `POSTGRES_PASSWORD` to a real password. - It goes into `DATABASE_URL` as is, so use URL-safe characters, for example `openssl rand -hex 32`. - Keep the generated mint keys and the Postgres password in your secret manager. + and `OIDC_ISSUER` to your provider's issuer URL. 3. In your identity provider, create one public OAuth client (authorization code with PKCE, no secret) for the T3 Code apps, and set `OIDC_AUDIENCE` to its client id. The apps send the @@ -41,7 +48,8 @@ Run these from the repository root. | Mobile | `t3code://oidc` (`t3code-dev://oidc`, `t3code-preview://oidc`) | | CLI | `http://127.0.0.1:34338/callback`, or enable the device flow | - Request the `offline_access` scope so sessions refresh without signing in again. + Request the `offline_access` scope so sessions refresh without signing in again. Register + only the clients you use. **Microsoft Entra ID.** Set `OIDC_ISSUER` to the tenant's v2.0 issuer, `https://login.microsoftonline.com//v2.0`. The `/common` and `/organizations` @@ -51,11 +59,14 @@ Run these from the repository root. - Register the web redirect URI under **Single-page application**. A **Web** URI cannot redeem the code from the browser. - Register the desktop, mobile and CLI URIs under **Mobile and desktop applications**. - - Set **Allow public client flows** to **Yes** for the CLI device flow. Without it the token - poll fails with `AADSTS7000218`. + - Set **Allow public client flows** to **Yes** only if you use the CLI device flow. Without + it the device flow's token poll fails with `AADSTS7000218`. - Entra limits refresh tokens issued to a single-page application to 24 hours, so web sessions ask for a new sign-in daily. + Restrict who can sign in before anyone links a machine: see + [identity provider settings](./OPERATING.md#identity-provider). + 4. Start it: ```sh @@ -71,19 +82,72 @@ Run these from the repository root. Requests without a bearer token get `401`. Caddy obtains the certificate automatically when `RELAY_DOMAIN` is a public name that reaches this server on ports 80 and 443. +Only Caddy publishes ports. Postgres sits on a network with no route out, and the relay connects +to it as `relay`, a role that owns the relay database but is not a superuser. Containers run +with no added privileges, a read-only root filesystem, and memory and process limits. Caddy caps +request bodies at 2 MiB for the API and 64 MiB for relay channels, and sends HSTS. + ## Backups and upgrades -The Postgres volume is the source of truth for relay state. Back it up with your normal -Postgres tooling, for example: +The Postgres volume is the source of truth for relay state. Dumps contain who uses the relay, +their machines' names and addresses, and thread and project titles, so encrypt them before they +leave the host. With [age](https://age-encryption.org): ```sh +umask 077 docker compose -f infra/relay/selfhost/docker-compose.yml exec -T postgres \ - pg_dump -U relay relay > relay-$(date +%Y%m%d).sql + pg_dump -U relay -d relay --format=custom \ + | age -r > relay-$(date +%Y%m%d).dump.age ``` -Back up the `infra/relay/selfhost/secrets` directory separately. Restore the database and keys -before starting a new relay image; migrations run automatically and the process refuses to serve -if a migration fails. +Keep the age private key offline, and back up the `infra/relay/selfhost/secrets` directory +separately from the dumps. A short retention, such as 7 daily and 4 weekly dumps, limits how much +history a leaked backup exposes. Rows the relay already deleted live on in older dumps. + +To restore, start Postgres alone on an empty volume, load the dump, then start the rest: + +```sh +docker compose -f infra/relay/selfhost/docker-compose.yml up -d --wait postgres +age -d -i relay-.dump.age \ + | docker compose -f infra/relay/selfhost/docker-compose.yml exec -T postgres \ + pg_restore -U relay -d relay --no-owner --no-privileges --exit-on-error +docker compose -f infra/relay/selfhost/docker-compose.yml --env-file infra/relay/selfhost/.env up -d --build +``` + +Test a restore on a separate host now and then. Migrations run automatically when a new relay +image starts, and the process refuses to serve if a migration fails. + +The base images are pinned by digest. To update them, look up the current digests and replace +the `@sha256:` values in `Dockerfile` and `docker-compose.yml`: + +```sh +docker buildx imagetools inspect node:26-alpine | grep -m1 Digest +docker buildx imagetools inspect postgres:16-alpine | grep -m1 Digest +docker buildx imagetools inspect caddy:2-alpine | grep -m1 Digest +``` + +### Moving an older deployment to the relay role + +Deployments created before the relay had its own database role run it as the Postgres +superuser, with `POSTGRES_PASSWORD` in `.env`. That superuser cannot be demoted, so move the +data into a fresh volume. With this version checked out and the old stack still running: + +```sh +cd infra/relay/selfhost +./gen-keys.sh # keeps the mint keys, adds the database secrets +umask 077 +docker compose exec -T postgres pg_dump -U relay -d relay --no-owner --no-privileges > old.sql +grep -c "dump complete" old.sql # 1: the dump finished +docker compose down +docker volume rm t3-relay_postgres-data +docker compose up -d --wait postgres +docker compose exec -T postgres psql -U relay -d relay -v ON_ERROR_STOP=1 < old.sql +docker compose up -d --build +shred -u old.sql +``` + +Then remove `POSTGRES_PASSWORD` from `.env`. Clients stay linked: the data and mint keys are +unchanged. ## Point the apps at this relay @@ -120,10 +184,10 @@ through the relay host, and channels live in the relay process, so keep a single need a T3 Code version that keeps an environment's path prefix. The relay also checks carried environments through its own public address, so this host must be able to reach `RELAY_PUBLIC_ORIGIN`. -**At an address you expose.** With `RELAY_MANUAL_ENDPOINTS=public` (the default here), an -environment can publish an HTTPS address you already expose (reverse proxy, port forward) and the -relay brokers connections to it like a managed endpoint. Run `t3 connect --publish-only`, then -start the server with `T3CODE_PUBLIC_URL` set to that address: +**At an address you expose.** Manual endpoints are off by default (`RELAY_MANUAL_ENDPOINTS=off`). +With `public`, an environment can publish an HTTPS address you already expose (reverse proxy, +port forward) and the relay brokers connections to it like a managed endpoint. Run +`t3 connect --publish-only`, then start the server with `T3CODE_PUBLIC_URL` set to that address: ```sh t3 connect --publish-only @@ -132,9 +196,10 @@ T3CODE_PUBLIC_URL=https://t3.example.com t3 serve The address must serve the environment's HTTP and WebSocket traffic over HTTPS. The relay refuses loopback, link-local and cloud metadata addresses. `private` also accepts private -network addresses (LAN, Tailscale) for relays only your own network uses; `off` refuses all of -them. Host names are checked as written, not resolved, so only point a relay you trust at names -you control. A published address takes precedence over a relay channel. +network addresses (LAN, Tailscale) for relays only your own network uses. Host names are checked +as written, not resolved, so any user who can sign in can make the relay connect to a name they +choose. Turn manual endpoints on only when every user is trusted, and prefer relay channels. A +published address takes precedence over a relay channel. ## Linking a host from a browser @@ -147,14 +212,30 @@ Caddy is the bundled proxy. To use your own (nginx, Traefik, a cloud load balanc `caddy` service, point your proxy at the relay's port 8080, and keep `RELAY_PUBLIC_ORIGIN` at the public HTTPS address. The relay builds no URLs from request headers, so `X-Forwarded-*` values are ignored. `OIDC_ISSUER` must equal the issuer your provider reports -publicly, including any path prefix your proxy adds. - -## What the relay stores - -While a thread runs, the server publishes its activity so a phone can show it. The relay keeps, -per active thread, the project title, thread title, model name, phase, a short status headline -and detail line, and a deep link (`relay_agent_activity_rows.state_json`). It does not store -message content. +publicly, including any path prefix your proxy adds. Carry over the body limits and headers in +`Caddyfile`, and do not add framing restrictions under `/env/`: the apps frame file previews +from carried environments. + +## What the relay stores and sees + +The relay database holds: + +- **Users:** the identity provider's issuer and `sub` for each user. No names or email addresses. +- **Linked environments:** each environment's id, name (usually the machine name), public key, + HTTP and WebSocket addresses, settings, the linking device's id, and hashed credentials. +- **Agent activity:** while a thread runs on a host with **Publish agent activity** on, its + project title, thread title, model name, phase, a short status headline and detail line, and a + deep link. Rows for finished threads are deleted after about 30 minutes; a thread that never + reports finishing keeps its row. +- **Mobile devices:** device id, platform, OS and app version, label, notification preferences, + and push tokens when push is enabled. +- **Short-lived records:** replay protection for signed requests and a log of push delivery + attempts. + +It does not store messages, prompts, code or files. With `RELAY_CHANNELS=true`, though, every +request to a carried environment, including prompts, code, terminal output and session tokens, +passes through the relay process unencrypted after Caddy ends TLS. Whoever runs the relay host +can read it. ## What this host does not do diff --git a/infra/relay/selfhost/docker-compose.yml b/infra/relay/selfhost/docker-compose.yml index 1c6d3ab6887f..1885fd6fb755 100644 --- a/infra/relay/selfhost/docker-compose.yml +++ b/infra/relay/selfhost/docker-compose.yml @@ -2,16 +2,42 @@ # Usage and configuration: see README.md next to this file. name: t3-relay +x-hardened: &hardened + restart: unless-stopped + read_only: true + cap_drop: [ALL] + security_opt: ["no-new-privileges:true"] + logging: + driver: json-file + options: + max-size: "10m" + max-file: "5" + services: postgres: - image: postgres:16-alpine - restart: unless-stopped + <<: *hardened + image: postgres:16-alpine@sha256:1d5b02d3a9941fbd52437db4107f8c52d6297dac553ca1e5c299ebb3756b4857 + # The image's own postgres user (uid 70), so the container needs no capabilities. + user: postgres environment: - POSTGRES_USER: relay - POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:?set POSTGRES_PASSWORD in .env} + # The bootstrap superuser, for initialization and administration only. The relay connects + # as `relay`, created by initdb/10-relay-role.sh. + POSTGRES_USER: postgres + POSTGRES_PASSWORD_FILE: /run/secrets/postgres_password POSTGRES_DB: relay + secrets: + - postgres_password + - relay_db_password volumes: - postgres-data:/var/lib/postgresql/data + - ./initdb:/docker-entrypoint-initdb.d:ro + tmpfs: + - /var/run/postgresql + - /tmp + networks: + - database + mem_limit: 512m + pids_limit: 200 healthcheck: test: ["CMD-SHELL", "pg_isready -U relay -d relay"] interval: 5s @@ -19,27 +45,37 @@ services: retries: 30 relay: + <<: *hardened build: context: ../../.. dockerfile: infra/relay/selfhost/Dockerfile - restart: unless-stopped depends_on: postgres: condition: service_healthy environment: - DATABASE_URL: postgres://relay:${POSTGRES_PASSWORD}@postgres:5432/relay + DATABASE_URL_FILE: /run/secrets/database_url RELAY_PUBLIC_ORIGIN: ${RELAY_PUBLIC_ORIGIN:?set RELAY_PUBLIC_ORIGIN in .env} OIDC_ISSUER: ${OIDC_ISSUER:?set OIDC_ISSUER in .env} OIDC_AUDIENCE: ${OIDC_AUDIENCE:?set OIDC_AUDIENCE in .env} - RELAY_MANUAL_ENDPOINTS: ${RELAY_MANUAL_ENDPOINTS:-public} + RELAY_MANUAL_ENDPOINTS: ${RELAY_MANUAL_ENDPOINTS:-off} RELAY_CHANNELS: ${RELAY_CHANNELS:-false} CLOUD_MINT_PRIVATE_KEY_FILE: /run/secrets/cloud_mint_private_key CLOUD_MINT_PUBLIC_KEY_FILE: /run/secrets/cloud_mint_public_key # Push notifications need the publisher's APNs and FCM credentials; leave them off here. APNS_ENABLED: "false" secrets: + - database_url - cloud_mint_private_key - cloud_mint_public_key + tmpfs: + - /tmp + # Postgres for state, the edge for Caddy and outbound calls to the identity provider. + networks: + - database + - edge + # Relay channels buffer carried requests of up to 64 MiB in memory. + mem_limit: 1g + pids_limit: 200 healthcheck: test: [ @@ -53,11 +89,13 @@ services: retries: 12 caddy: - image: caddy:2-alpine - restart: unless-stopped + <<: *hardened + image: caddy:2-alpine@sha256:003a97808e781aa9f7e75cc2f43d34d461099031faf5e20faefb9f61126836f0 depends_on: relay: condition: service_healthy + cap_add: + - NET_BIND_SERVICE ports: - "${HTTP_PORT:-80}:80" - "${HTTPS_PORT:-443}:443" @@ -67,12 +105,35 @@ services: - ./Caddyfile:/etc/caddy/Caddyfile:ro - caddy-data:/data - caddy-config:/config + tmpfs: + - /tmp + networks: + - edge + mem_limit: 256m + pids_limit: 100 + healthcheck: + test: ["CMD", "wget", "-q", "-O", "/dev/null", "http://127.0.0.1:2019/config/"] + interval: 30s + timeout: 5s + retries: 3 + +networks: + # No route out: only the relay reaches Postgres, and Postgres reaches nothing. + database: + internal: true + edge: {} secrets: cloud_mint_private_key: file: ./secrets/cloud-mint-private.pem cloud_mint_public_key: file: ./secrets/cloud-mint-public.pem + database_url: + file: ./secrets/database-url + postgres_password: + file: ./secrets/postgres-password + relay_db_password: + file: ./secrets/relay-db-password volumes: postgres-data: diff --git a/infra/relay/selfhost/gen-keys.sh b/infra/relay/selfhost/gen-keys.sh index b5d40f026dc0..78a665ef2d8c 100755 --- a/infra/relay/selfhost/gen-keys.sh +++ b/infra/relay/selfhost/gen-keys.sh @@ -1,8 +1,11 @@ #!/bin/sh -# Creates the relay's cloud-mint signing key pair (Ed25519), keeping a private key that exists. +# Creates the relay's secrets: the cloud-mint signing key pair (Ed25519) and the database +# passwords. Secrets that already exist are kept. set -eu dir="$(dirname "$0")/secrets" -mkdir -p "$dir" +(umask 077 && mkdir -p "$dir") +chmod 700 "$dir" + private="$dir/cloud-mint-private.pem" if [ -f "$private" ]; then echo "Keeping the existing $private." @@ -12,10 +15,32 @@ fi # Derived every run, so a missing or partial public key is repaired. openssl pkey -in "$private" -pubout -out "$dir/cloud-mint-public.pem" chmod 644 "$dir/cloud-mint-public.pem" -# Compose mounts secret files with their host owner, and the relay runs as the image's node user. -if [ "$(id -u)" = 0 ]; then - chown 1000:1000 "$private" -elif [ "$(id -u)" != 1000 ]; then - echo "The relay reads $private as uid 1000. Run: sudo chown 1000 $private" >&2 + +# Hex only: the relay password goes into DATABASE_URL as is. +for name in postgres-password relay-db-password; do + if [ ! -f "$dir/$name" ]; then + (umask 077 && openssl rand -hex 32 >"$dir/$name") + fi +done +if [ ! -f "$dir/database-url" ]; then + (umask 077 && printf 'postgres://relay:%s@postgres:5432/relay\n' \ + "$(cat "$dir/relay-db-password")" >"$dir/database-url") fi -echo "Keys are in $dir" + +# Compose mounts secret files with their host owner and mode. The relay runs as uid 1000 and +# Postgres (alpine image) as uid 70. +need_chown="" +for entry in "1000:$private" "1000:$dir/database-url" "70:$dir/postgres-password" \ + "70:$dir/relay-db-password"; do + uid="${entry%%:*}" + file="${entry#*:}" + if [ "$(id -u)" = 0 ]; then + chown "$uid:$uid" "$file" + elif [ "$(id -u)" != "$uid" ]; then + need_chown="$need_chown\n sudo chown $uid:$uid $file" + fi +done +if [ -n "$need_chown" ]; then + printf "The containers read these files as other users. Run:%b\n" "$need_chown" >&2 +fi +echo "Secrets are in $dir" diff --git a/infra/relay/selfhost/initdb/10-relay-role.sh b/infra/relay/selfhost/initdb/10-relay-role.sh new file mode 100755 index 000000000000..ed3b29b00f41 --- /dev/null +++ b/infra/relay/selfhost/initdb/10-relay-role.sh @@ -0,0 +1,13 @@ +#!/bin/sh +# Runs once, on an empty data volume. The relay's role owns its database, so startup migrations +# work, but is not a superuser. The image may source this file, so it sets no shell options. +relay_password="$(cat /run/secrets/relay_db_password)" +psql -v ON_ERROR_STOP=1 --username "$POSTGRES_USER" --dbname "$POSTGRES_DB" \ + -v relay_password="$relay_password" <<'SQL' +CREATE ROLE relay LOGIN PASSWORD :'relay_password' + NOSUPERUSER NOCREATEDB NOCREATEROLE NOREPLICATION NOBYPASSRLS; +ALTER DATABASE relay OWNER TO relay; +REVOKE ALL ON DATABASE relay FROM PUBLIC; +REVOKE CONNECT ON DATABASE postgres, template1 FROM PUBLIC; +SQL +unset relay_password diff --git a/infra/relay/src/Config.ts b/infra/relay/src/Config.ts index 085472ac1a2c..ac1807916473 100644 --- a/infra/relay/src/Config.ts +++ b/infra/relay/src/Config.ts @@ -42,6 +42,23 @@ export const legacyTunnelGraceMinutesConfig = Config.option( ), ); +const decodePositiveInt = Schema.decodeUnknownEffect( + Schema.NumberFromString.pipe(Schema.check(Schema.isInt(), Schema.isGreaterThan(0))), +); + +/** A positive integer setting; unset or empty (as Compose passes unset variables) means `fallback`. */ +export const positiveIntConfig = (name: string, fallback: number) => + Config.String(name).pipe( + Config.withDefault(""), + Config.mapEffect((value) => + value.trim() === "" + ? Effect.succeed(fallback) + : decodePositiveInt(value.trim()).pipe( + Effect.mapError((error) => new Config.ConfigError(error)), + ), + ), + ); + export interface ApnsCredentials { readonly teamId: string; readonly keyId: string; @@ -89,6 +106,8 @@ export class RelayConfiguration extends Context.Service< readonly managedEndpointBaseDomain: string | undefined; /** Carries publish-only environments over relay channels; self-hosted Node relays only. */ readonly channels?: boolean; + /** Active environment links one account may hold; unset means no cap. */ + readonly maxEnvironmentsPerUser?: number; readonly managedEndpointNamespace: string | undefined; readonly managedEndpointCleanupMode?: ManagedEndpointCleanupMode; readonly legacyManagedEndpointCleanupMode?: ManagedEndpointCleanupMode; diff --git a/infra/relay/src/agentActivity/AgentActivityRows.ts b/infra/relay/src/agentActivity/AgentActivityRows.ts index 0faf5b9da358..d58ca7270705 100644 --- a/infra/relay/src/agentActivity/AgentActivityRows.ts +++ b/infra/relay/src/agentActivity/AgentActivityRows.ts @@ -7,7 +7,7 @@ import * as Function 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, lt, sql } from "drizzle-orm"; +import { and, desc, eq, isNull, lt, or, sql } from "drizzle-orm"; import * as RelayDb from "../db.ts"; import { relayAgentActivityRows, relayEnvironmentLinks } from "../persistence/schema.ts"; @@ -69,8 +69,13 @@ export class AgentActivityRows extends Context.Service< readonly environmentPublicKey: string; readonly state: RelayAgentActivityState; }) => Effect.Effect; + /** + * Drops finished rows untouched since `updatedBefore`, and rows in any phase untouched since + * `abandonedBefore`, whose environment stopped reporting before they finished. + */ readonly pruneTerminal: (input: { readonly updatedBefore: string; + readonly abandonedBefore?: string; }) => Effect.Effect; readonly remove: (input: { readonly environmentId: string; @@ -187,9 +192,14 @@ const make = Effect.gen(function* () { yield* db .delete(relayAgentActivityRows) .where( - and( - sql`${relayAgentActivityRows.stateJson} ->> 'phase' IN ('completed', 'failed')`, - lt(relayAgentActivityRows.updatedAt, input.updatedBefore), + or( + and( + sql`${relayAgentActivityRows.stateJson} ->> 'phase' IN ('completed', 'failed')`, + lt(relayAgentActivityRows.updatedAt, input.updatedBefore), + ), + input.abandonedBefore === undefined + ? undefined + : lt(relayAgentActivityRows.updatedAt, input.abandonedBefore), ), ) .pipe( diff --git a/infra/relay/src/auth/SubjectTokens.test.ts b/infra/relay/src/auth/SubjectTokens.test.ts index d18d4abe75e8..e576337058ef 100644 --- a/infra/relay/src/auth/SubjectTokens.test.ts +++ b/infra/relay/src/auth/SubjectTokens.test.ts @@ -35,6 +35,11 @@ const Claims = Schema.Struct({ sub: Schema.String, iat: Schema.Number, exp: Schema.Number, + azp: Schema.optionalKey(Schema.String), + scp: Schema.optionalKey(Schema.String), + tid: Schema.optionalKey(Schema.String), + oid: Schema.optionalKey(Schema.String), + ver: Schema.optionalKey(Schema.String), }); const signToken = Effect.fn("test.signToken")(function* (options: { @@ -42,6 +47,8 @@ const signToken = Effect.fn("test.signToken")(function* (options: { readonly audience?: string; readonly subject?: string; readonly expiresInSeconds?: number; + readonly typ?: string; + readonly claims?: Partial; readonly privateKey: Jwk.PrivateKey; }) { const now = Math.floor((yield* Clock.currentTimeMillis) / 1000); @@ -53,9 +60,10 @@ const signToken = Effect.fn("test.signToken")(function* (options: { sub: options.subject ?? "user-1", iat: now, exp: now + (options.expiresInSeconds ?? 300), + ...options.claims, }, options.privateKey, - { kid: "k1" }, + { kid: "k1", ...(options.typ === undefined ? {} : { typ: options.typ }) }, ); return Redacted.value(token); }); @@ -129,6 +137,43 @@ it.layer(crypto)("SubjectTokens", (it) => { }), ); + it.effect("accepts Entra-shaped ID tokens and an azp naming the relay's client", () => + Effect.gen(function* () { + const f = yield* fixture; + const entraIdToken = yield* f.sign({ + typ: "JWT", + claims: { tid: "tenant", oid: "object", ver: "2.0" }, + }); + const withAzp = yield* f.sign({ claims: { azp: AUDIENCE } }); + + for (const token of [entraIdToken, withAzp]) { + expect(yield* verifySubjectToken(f.settings, token, { acceptClerkOAuth: false })).toEqual({ + sub: oidcAccountId(ISSUER, "user-1"), + mode: "oidc_bearer", + }); + } + }), + ); + + it.effect("rejects access tokens and tokens issued to another client", () => + Effect.gen(function* () { + const f = yield* fixture; + const cases = [ + [{ typ: "at+jwt" }, "access_token_type"], + [{ typ: "application/at+jwt" }, "access_token_type"], + [{ claims: { scp: "relay.access" } }, "access_token_scope"], + [{ claims: { azp: "another-client" } }, "authorized_party_mismatch"], + ] as const; + + for (const [options, cause] of cases) { + const error = yield* Effect.flip( + verifySubjectToken(f.settings, yield* f.sign(options), { acceptClerkOAuth: false }), + ); + expect(error.cause).toBe(cause); + } + }), + ); + it.effect("rejects expired configured-issuer tokens", () => Effect.gen(function* () { const f = yield* fixture; @@ -226,4 +271,44 @@ it.layer(crypto)("SubjectTokens", (it) => { expect(error.cause).toBe("oidc_issuer_mismatch"); }).pipe(Effect.scoped), ); + + it.effect("does not follow a redirected discovery request", () => + Effect.gen(function* () { + const inits: Array = []; + const fetches = vi.fn(async (_input: RequestInfo | URL, init?: RequestInit) => { + inits.push(init); + return new Response(null, { status: 302, headers: { location: "https://evil.test/" } }); + }); + const [keySet] = yield* discoverWith(fetches as never); + + const error = yield* Effect.flip(keySet); + expect(error.cause).toBe("oidc_discovery_status_302"); + expect(inits.map((init) => init?.redirect)).toEqual(["manual"]); + }).pipe(Effect.scoped), + ); + + it.effect("refuses an oversized discovery document", () => + Effect.gen(function* () { + const [keySet] = yield* discoverWith( + fakeFetch({ issuer: ISSUER, jwks_uri: `${ISSUER}/certs`, padding: "x".repeat(300_000) }), + ); + + const error = yield* Effect.flip(keySet); + expect(error.cause).toBe("oidc_discovery_too_large"); + }).pipe(Effect.scoped), + ); + + it.effect("refuses a plain-http issuer unless it is on this machine", () => + Effect.gen(function* () { + const discover = (issuer: string) => + makeOidcKeySet(issuer).pipe( + Effect.provide(FetchHttpClient.layer), + Effect.provideService(FetchHttpClient.Fetch, fakeFetch({}) as unknown as typeof fetch), + Effect.exit, + ); + + expect(Exit.hasDies(yield* discover("http://sso.example.com/realms/t3"))).toBe(true); + expect(Exit.isSuccess(yield* discover("http://127.0.0.1:8180/realms/t3"))).toBe(true); + }).pipe(Effect.scoped), + ); }); diff --git a/infra/relay/src/auth/SubjectTokens.ts b/infra/relay/src/auth/SubjectTokens.ts index 8420ff60a0e3..c52949f9e4df 100644 --- a/infra/relay/src/auth/SubjectTokens.ts +++ b/infra/relay/src/auth/SubjectTokens.ts @@ -1,6 +1,9 @@ import { createClerkClient, verifyToken } from "@clerk/backend"; +import { isLocalLoopbackHost } from "@t3tools/shared/hostClassification"; import { decodeIdTokenClaims, oidcAccountId, oidcDiscoveryUrl } from "@t3tools/shared/oidc"; import * as Effect from "effect/Effect"; +import * as Stream from "effect/Stream"; +import * as FetchHttpClient from "effect/http/FetchHttpClient"; import * as Duration from "effect/Duration"; import * as Exit from "effect/Exit"; import * as Redacted from "effect/Redacted"; @@ -34,12 +37,24 @@ export interface VerifiedSubject { const OIDC_ALGORITHMS = ["RS256", "ES256", "EdDSA"] as const; const OIDC_DISCOVERY_TIMEOUT = "10 seconds"; +// Real discovery documents are a few KiB. +const OIDC_DISCOVERY_MAX_BYTES = 256 * 1024; + +/** HTTPS, or plain HTTP to this machine for local identity providers and tests. */ +function isSecureOidcUrl(value: string): boolean { + const url = URL.parse(value); + if (url === null || url.username !== "" || url.password !== "") return false; + if (url.protocol === "https:") return true; + return url.protocol === "http:" && isLocalLoopbackHost(url.hostname); +} const OidcDiscoveryDocument = Schema.Struct({ issuer: Schema.String, jwks_uri: Schema.String, }); -const decodeOidcDiscoveryDocument = Schema.decodeUnknownEffect(OidcDiscoveryDocument); +const decodeOidcDiscoveryDocument = Schema.decodeUnknownEffect( + Schema.fromJsonString(OidcDiscoveryDocument), +); const isSubjectTokenVerificationFailed = Schema.is(SubjectTokenVerificationFailed); /** @@ -48,16 +63,38 @@ const isSubjectTokenVerificationFailed = Schema.is(SubjectTokenVerificationFaile * a reverse proxy that rewrites the public origin should be reflected in the configured issuer. */ export const makeOidcKeySet = Effect.fn("relay.auth.make_oidc_key_set")(function* (issuer: string) { - const httpClient = yield* HttpClient.HttpClient; + const discoveryUrl = oidcDiscoveryUrl(issuer); + if (!isSecureOidcUrl(discoveryUrl)) { + return yield* Effect.die( + `OIDC_ISSUER must be an https URL (plain http is accepted for loopback only): ${issuer}`, + ); + } + // Whoever answers discovery picks the keys every token is checked against, so a redirect, which + // fetch would otherwise follow, must not move that choice to another origin. + const httpClient = HttpClient.transform(yield* HttpClient.HttpClient, (effect) => + Effect.provideService(effect, FetchHttpClient.RequestInit, { redirect: "manual" }), + ); const scope = yield* Effect.scope; const discover = Effect.gen(function* () { - const response = yield* httpClient.execute(HttpClientRequest.get(oidcDiscoveryUrl(issuer))); + const response = yield* httpClient.execute(HttpClientRequest.get(discoveryUrl)); if (response.status !== 200) { return yield* new SubjectTokenVerificationFailed({ cause: `oidc_discovery_status_${response.status}`, }); } - const document = yield* response.json.pipe(Effect.flatMap(decodeOidcDiscoveryDocument)); + const decoder = new TextDecoder(); + const body = yield* Stream.runFoldEffect( + response.stream, + () => ({ size: 0, text: "" }), + (read, chunk) => + read.size + chunk.byteLength > OIDC_DISCOVERY_MAX_BYTES + ? Effect.fail(new SubjectTokenVerificationFailed({ cause: "oidc_discovery_too_large" })) + : Effect.succeed({ + size: read.size + chunk.byteLength, + text: read.text + decoder.decode(chunk, { stream: true }), + }), + ); + const document = yield* decodeOidcDiscoveryDocument(body.text + decoder.decode()); if (document.issuer !== issuer) { return yield* new SubjectTokenVerificationFailed({ cause: "oidc_issuer_mismatch" }); } @@ -87,7 +124,28 @@ const readUnverifiedIssuer = (token: string): string | undefined => { } }; -const OidcClaims = Schema.Struct({ sub: Schema.NonEmptyString }); +const OidcClaims = Schema.Struct({ + sub: Schema.NonEmptyString, + azp: Schema.optionalKey(Schema.String), + scp: Schema.optionalKey(Schema.Unknown), +}); + +/** + * The relay accepts ID tokens only. An access token for an API on the same app registration can + * carry the same issuer and audience; access tokens carry `scp` (Entra) or the `at+jwt` type + * (RFC 9068). `azp`, when present, names the client the token was issued to. + */ +export function oidcIdTokenRejection( + header: { readonly typ?: string | undefined }, + claims: typeof OidcClaims.Type, + audience: string, +): string | null { + const typ = header.typ?.toLowerCase(); + if (typ === "at+jwt" || typ === "application/at+jwt") return "access_token_type"; + if (claims.scp !== undefined) return "access_token_scope"; + if (claims.azp !== undefined && claims.azp !== audience) return "authorized_party_mismatch"; + return null; +} /** Binds the crypto service at startup, since the auth middleware cannot require services. */ export const makeOidcVerifier = Effect.fn("relay.auth.make_oidc_verifier")(function* (options: { @@ -112,10 +170,15 @@ export const makeOidcVerifier = Effect.fn("relay.auth.make_oidc_verifier")(funct Effect.mapError((cause) => new SubjectTokenVerificationFailed({ cause })), ), ), - Effect.map(({ claims }): VerifiedSubject => ({ - sub: oidcAccountId(options.issuer, claims.sub), - mode: "oidc_bearer", - })), + Effect.flatMap(({ claims, protectedHeader }) => { + const rejection = oidcIdTokenRejection(protectedHeader, claims, options.audience); + return rejection === null + ? Effect.succeed({ + sub: oidcAccountId(options.issuer, claims.sub), + mode: "oidc_bearer", + }) + : Effect.fail(new SubjectTokenVerificationFailed({ cause: rejection })); + }), Effect.withSpan("relay.auth.verify_oidc_token"), ); }); diff --git a/infra/relay/src/composition.ts b/infra/relay/src/composition.ts index b3023b84d70f..69a2f53abf83 100644 --- a/infra/relay/src/composition.ts +++ b/infra/relay/src/composition.ts @@ -184,6 +184,9 @@ export const composeRelay = Effect.fn("relay.composition.compose")(function* cloudMintPublicKey: yield* cloudMintPublicKey, managedEndpointBaseDomain: host.managedEndpointBaseDomain, ...(host.channels ? { channels: true } : {}), + ...(host.maxEnvironmentsPerUser === undefined + ? {} + : { maxEnvironmentsPerUser: host.maxEnvironmentsPerUser }), managedEndpointNamespace: stage, managedEndpointCleanupMode, legacyManagedEndpointCleanupMode, @@ -195,12 +198,19 @@ export const composeRelay = Effect.fn("relay.composition.compose")(function* }); const layerHookInbox = host.hookInbox; + const layerManualEndpointHttpClient = + manualEndpoints === "off" || host.manualEndpointHttpClient === undefined + ? Layer.empty + : Layer.succeed( + EnvironmentConnector.ManualEndpointHttpClient, + yield* host.manualEndpointHttpClient(manualEndpoints), + ); const layerRuntime = Layer.empty.pipe( Layer.provideMerge(MobileRegistrations.layer), Layer.provideMerge(AgentActivityPublisher.layer), Layer.provideMerge(EnvironmentConnector.layer), - Layer.provideMerge(EnvironmentLinker.layer), + Layer.provideMerge(Layer.merge(EnvironmentLinker.layer, layerManualEndpointHttpClient)), Layer.provideMerge( Layer.mergeAll( EnvironmentPublishSignatures.layer, @@ -351,6 +361,16 @@ export const composeRelay = Effect.fn("relay.composition.compose")(function* Effect.flatMap(([activityRows, now]) => activityRows.pruneTerminal({ updatedBefore: DateTime.formatIso(DateTime.subtract(now, { minutes: 30 })), + abandonedBefore: DateTime.formatIso(DateTime.subtract(now, { days: 7 })), + }), + ), + ), + ), + Effect.andThen( + Effect.all([EnvironmentCredentials.EnvironmentCredentials, DateTime.now]).pipe( + Effect.flatMap(([credentials, now]) => + credentials.pruneRevoked({ + revokedBefore: DateTime.formatIso(DateTime.subtract(now, { days: 30 })), }), ), ), diff --git a/infra/relay/src/environments/EnvironmentConnector.test.ts b/infra/relay/src/environments/EnvironmentConnector.test.ts index 6f492f98cacb..31057ecb18e4 100644 --- a/infra/relay/src/environments/EnvironmentConnector.test.ts +++ b/infra/relay/src/environments/EnvironmentConnector.test.ts @@ -21,7 +21,7 @@ import * as Redacted from "effect/Redacted"; import * as Result from "effect/Result"; import * as Schema from "effect/Schema"; import * as Tracer from "effect/Tracer"; -import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/http"; +import { HttpClient, HttpClientError, HttpClientRequest, HttpClientResponse } from "effect/http"; import * as CloudMintSigner from "../auth/CloudMintSigner.ts"; import * as EnvironmentLinks from "./EnvironmentLinks.ts"; @@ -161,9 +161,20 @@ function layerConnectorTest( readonly links?: EnvironmentLinks.EnvironmentLinks["Service"]; readonly allocations?: ManagedEndpointAllocations.ManagedEndpointAllocations["Service"]; readonly manualEndpoints?: RelayConfiguration.ManualEndpointsMode; + readonly manualExecute?: ( + request: HttpClientRequest.HttpClientRequest, + ) => Effect.Effect; }, ) { return EnvironmentConnector.layer.pipe( + Layer.provide( + options?.manualExecute === undefined + ? Layer.empty + : Layer.succeed( + EnvironmentConnector.ManualEndpointHttpClient, + HttpClient.make(options.manualExecute), + ), + ), Layer.provide(CloudMintSigner.layer), Layer.provide(NodeCryptoLayer.layer), Layer.provide(Layer.succeed(EnvironmentLinks.EnvironmentLinks, options?.links ?? makeLinks())), @@ -365,6 +376,63 @@ describe("EnvironmentConnector", () => { ); }); + it.effect( + "sends self-declared endpoints through the host's guard and hides why they failed", + () => { + const manualEndpoint = { + httpBaseUrl: "https://10-0-0-5.example.dev/", + wsBaseUrl: "wss://10-0-0-5.example.dev/ws", + providerKind: "manual" as const, + }; + const execute = () => Effect.die("manual endpoints must not use the relay's own client"); + const refused = (request: HttpClientRequest.HttpClientRequest) => + Effect.fail( + new HttpClientError.HttpClientError({ + reason: new HttpClientError.TransportError({ + request, + cause: Object.assign(new Error("connect ECONNREFUSED 10.0.0.5:443"), { + code: "ECONNREFUSED", + }), + }), + }), + ); + + return Effect.gen(function* () { + const connector = yield* EnvironmentConnector.EnvironmentConnector; + const status = yield* connector.status({ + userId: "user_123", + environmentId: "env-connector-test", + }); + expect(status).toMatchObject({ + status: "offline", + error: "Endpoint health request failed.", + endpointFailure: "unknown", + }); + const connect = yield* Effect.flip( + connector.connect({ + userId: "user_123", + environmentId: "env-connector-test", + clientProofKeyThumbprint: "thumbprint", + }), + ); + expect(connect).toMatchObject({ + _tag: "EnvironmentMintRequestFailed", + endpointFailure: "unknown", + }); + expect(connect).not.toHaveProperty("endpointStatus"); + }).pipe( + Effect.provide( + layerConnectorTest(execute, { + manualEndpoints: "public", + manualExecute: refused, + allocations: makeAllocations(null), + links: makeLinks({ endpoint: manualEndpoint }), + }), + ), + ); + }, + ); + it.effect("rejects stale managed endpoints before sending a mint request", () => { let requestCount = 0; const spans: Array = []; diff --git a/infra/relay/src/environments/EnvironmentConnector.ts b/infra/relay/src/environments/EnvironmentConnector.ts index f3e411f7a0cb..7ebae65e71fa 100644 --- a/infra/relay/src/environments/EnvironmentConnector.ts +++ b/infra/relay/src/environments/EnvironmentConnector.ts @@ -195,6 +195,34 @@ const currentTraceId = Effect.currentSpan.pipe( Effect.orElseSucceed(() => "unavailable"), ); +/** + * Sends requests to endpoints environments declare themselves. A host that can check where a + * connection really goes (see `host/manualEndpointClient.ts`) provides one; otherwise the relay's + * own client is used. + */ +export class ManualEndpointHttpClient extends Context.Service< + ManualEndpointHttpClient, + HttpClient.HttpClient +>()("t3code-relay/environments/EnvironmentConnector/ManualEndpointHttpClient") {} + +// An environment picks its own address, so how a request to it failed would map the relay's +// network for it. Callers get this instead; the reason stays in the relay's logs. +const MANUAL_ENDPOINT_FAILURE = { endpointFailure: "unknown" } as const; +const MANUAL_ENDPOINT_HEALTH_FAILURE = "Endpoint health request failed."; + +/** The messages along a failure's cause chain, for the relay's own logs. */ +function transportFailureDetail(cause: unknown): string { + const parts: Array = []; + for (let current = cause, depth = 0; depth < 4 && current instanceof Error; depth++) { + parts.push(current.message); + current = current.cause; + } + if (HttpClientError.isHttpClientError(cause) && cause.reason._tag === "TransportError") { + parts.push(transportFailureDetail(cause.reason.cause)); + } + return parts.filter((part) => part.length > 0).join(": "); +} + export const withoutRedirects = (effect: Effect.Effect) => effect.pipe(Effect.provideService(FetchHttpClient.RequestInit, { redirect: "manual" })); @@ -383,8 +411,8 @@ const parseEndpointUrl = (value: string): URL | null => { /** * An environment that declares its own address has no allocation to check it against, and the * relay will send requests to it. Require a secure address that is not an internal one, so a - * linked environment cannot point the relay at its own network. - * DNS names that resolve to private addresses are not detected here. + * linked environment cannot point the relay at its own network. Names are checked again where + * they resolve, by the host's `ManualEndpointHttpClient`. */ export function validateManualEndpoint(input: { readonly endpoint: RelayManagedEndpoint; @@ -443,13 +471,19 @@ const make = Effect.gen(function* () { const allocations = yield* ManagedEndpointAllocations.ManagedEndpointAllocations; const settings = yield* RelayConfiguration.RelayConfiguration; const httpClient = yield* HttpClient.HttpClient; + const manualHttpClient = yield* Effect.serviceOption(ManualEndpointHttpClient); const random = yield* SecureRandom.SecureRandom; const signature = yield* Signature.Signature; const mint = yield* CloudMintSigner.CloudMintSigner; const relayIssuer = normalizeRelayIssuer(settings.relayIssuer); - const makeEnvironmentClient = (httpBaseUrl: string) => - makeEnvironmentHttpApiClient(httpBaseUrl).pipe( - Effect.provideService(HttpClient.HttpClient, httpClient), + const makeEnvironmentClient = (endpoint: RelayManagedEndpoint) => + makeEnvironmentHttpApiClient(endpoint.httpBaseUrl).pipe( + Effect.provideService( + HttpClient.HttpClient, + endpoint.providerKind === "manual" + ? Option.getOrElse(manualHttpClient, () => httpClient) + : httpClient, + ), ); const resolveManagedEndpoint = Effect.fn("relay.environment_connector.resolve_managed_endpoint")( function* (input: { @@ -558,7 +592,8 @@ const make = Effect.gen(function* () { ); const checkedAt = DateTime.formatIso(now); const traceId = yield* currentTraceId; - const environmentClient = yield* makeEnvironmentClient(endpoint.httpBaseUrl); + const manual = endpoint.providerKind === "manual"; + const environmentClient = yield* makeEnvironmentClient(endpoint); const responseOption = yield* environmentClient.connect.health({ payload: { proof } }).pipe( withoutRedirects, Effect.match({ @@ -582,8 +617,12 @@ const make = Effect.gen(function* () { endpoint, status: "offline" as const, checkedAt, - error: "Managed endpoint health request timed out.", - endpointFailure: "timeout" as const, + ...(manual + ? { error: MANUAL_ENDPOINT_HEALTH_FAILURE, ...MANUAL_ENDPOINT_FAILURE } + : { + error: "Managed endpoint health request timed out.", + endpointFailure: "timeout" as const, + }), ...offlineReasonFor(allocation), traceId, }; @@ -602,6 +641,7 @@ const make = Effect.gen(function* () { endpoint: endpoint.httpBaseUrl, failureReason, endpointFailure: diagnosis.endpointFailure, + ...(manual ? { cause: transportFailureDetail(responseOption.value.cause) } : {}), traceId, }); return { @@ -609,8 +649,12 @@ const make = Effect.gen(function* () { endpoint, status: "offline" as const, checkedAt, - error: environmentHealthRequestFailureMessage(responseOption.value.cause), - ...diagnosis, + ...(manual + ? { error: MANUAL_ENDPOINT_HEALTH_FAILURE, ...MANUAL_ENDPOINT_FAILURE } + : { + error: environmentHealthRequestFailureMessage(responseOption.value.cause), + ...diagnosis, + }), ...offlineReasonFor(allocation), traceId, }; @@ -722,34 +766,59 @@ const make = Effect.gen(function* () { }), ), ); - const environmentClient = yield* makeEnvironmentClient(endpoint.httpBaseUrl); + const manual = endpoint.providerKind === "manual"; + const environmentClient = yield* makeEnvironmentClient(endpoint); const decoded = yield* environmentClient.connect .t3MintCredential({ payload: { proof } }) .pipe( withoutRedirects, Effect.catch((cause) => - diagnoseEndpointFailure(cause).pipe( - Effect.flatMap((diagnosis) => - Effect.fail( - new EnvironmentMintRequestFailed({ - environmentId: input.environmentId, - operation: "connect", - cause, - ...diagnosis, - }), + manual + ? Effect.logWarning("Manual endpoint mint request failed", { + environmentId: link.environmentId, + endpoint: endpoint.httpBaseUrl, + cause: transportFailureDetail(cause), + }).pipe( + Effect.andThen( + Effect.fail( + new EnvironmentMintRequestFailed({ + environmentId: input.environmentId, + operation: "connect", + cause, + ...MANUAL_ENDPOINT_FAILURE, + }), + ), + ), + ) + : diagnoseEndpointFailure(cause).pipe( + Effect.flatMap((diagnosis) => + Effect.fail( + new EnvironmentMintRequestFailed({ + environmentId: input.environmentId, + operation: "connect", + cause, + ...diagnosis, + }), + ), + ), ), - ), - ), ), Effect.timeoutOption(Duration.millis(ENVIRONMENT_MINT_REQUEST_TIMEOUT_MS)), Effect.flatMap( Option.match({ onNone: () => Effect.fail( - new EnvironmentMintRequestTimedOut({ - environmentId: input.environmentId, - timeoutMs: ENVIRONMENT_MINT_REQUEST_TIMEOUT_MS, - }), + manual + ? new EnvironmentMintRequestFailed({ + environmentId: input.environmentId, + operation: "connect", + cause: "timeout", + ...MANUAL_ENDPOINT_FAILURE, + }) + : new EnvironmentMintRequestTimedOut({ + environmentId: input.environmentId, + timeoutMs: ENVIRONMENT_MINT_REQUEST_TIMEOUT_MS, + }), ), onSome: Effect.succeed, }), diff --git a/infra/relay/src/environments/EnvironmentCredentials.test.ts b/infra/relay/src/environments/EnvironmentCredentials.test.ts index b116fb7c5852..b51c543dc150 100644 --- a/infra/relay/src/environments/EnvironmentCredentials.test.ts +++ b/infra/relay/src/environments/EnvironmentCredentials.test.ts @@ -144,7 +144,22 @@ describe("EnvironmentCredentials", () => { it.effect("revokes active credentials for an environment public key", () => { const updateValues: Array> = []; const whereConditions: Array = []; + const executed: Array = []; + const pruned: Array = []; const fakeDb = { + execute: (query: unknown) => { + executed.push(query); + return Effect.succeed([]); + }, + delete: (table: unknown) => { + expect(table).toBe(relayEnvironmentCredentials); + return { + where: (condition: unknown) => { + pruned.push(condition); + return Effect.void; + }, + }; + }, update: (table: unknown) => { expect(table).toBe(relayEnvironmentCredentials); return { @@ -173,6 +188,10 @@ describe("EnvironmentCredentials", () => { }); expect(revoked).toBe(true); + expect(executed).toHaveLength(1); + const notify = new PgDialect().sqlToQuery(executed[0] as never); + expect(notify.sql).toContain("pg_notify"); + expect(notify.params).toEqual([EnvironmentCredentials.CREDENTIALS_REVOKED_CHANNEL]); expect(updateValues).toHaveLength(1); expect(updateValues[0]?.revokedAt).toEqual(updateValues[0]?.updatedAt); expect(whereConditions).toHaveLength(1); @@ -191,6 +210,12 @@ describe("EnvironmentCredentials", () => { "env_test", "environment-public-key", ]); + + // Revoked rows are kept a while, then forgotten; active ones (revoked_at null) never match. + yield* credentials.pruneRevoked({ revokedBefore: "2026-10-01T00:00:00.000Z" }); + const prune = new PgDialect().sqlToQuery(pruned[0] as never); + expect(prune.sql).toBe('"relay_environment_credentials"."revoked_at" < $1'); + expect(prune.params).toEqual(["2026-10-01T00:00:00.000Z"]); }).pipe( Effect.provide( EnvironmentCredentials.layer.pipe( diff --git a/infra/relay/src/environments/EnvironmentCredentials.ts b/infra/relay/src/environments/EnvironmentCredentials.ts index de346caf6484..58bccc5f2696 100644 --- a/infra/relay/src/environments/EnvironmentCredentials.ts +++ b/infra/relay/src/environments/EnvironmentCredentials.ts @@ -7,7 +7,7 @@ import * as Base64Url from "effect/encoding/Base64Url"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; import * as Schema from "effect/Schema"; -import { and, eq, exists, isNull, ne, notExists } from "drizzle-orm"; +import { and, eq, exists, isNull, lt, ne, notExists, sql } from "drizzle-orm"; import { QueryBuilder } from "drizzle-orm/pg-core"; import * as RelayDb from "../db.ts"; @@ -47,12 +47,15 @@ export class EnvironmentCredentialAuthenticatePersistenceError extends Schema.Ta export class EnvironmentCredentialRevokePersistenceError extends Schema.TaggedError()( "EnvironmentCredentialRevokePersistenceError", { - environmentId: Schema.String, + /** Absent when pruning revoked credentials of every environment. */ + environmentId: Schema.optionalKey(Schema.String), cause: Schema.Defect(), }, ) { override get message(): string { - return `Failed to revoke credentials for environment '${this.environmentId}'`; + return this.environmentId === undefined + ? "Failed to prune revoked environment credentials" + : `Failed to revoke credentials for environment '${this.environmentId}'`; } } @@ -79,6 +82,10 @@ export class EnvironmentCredentials extends Context.Service< readonly environmentId: string; readonly environmentPublicKey: string; }) => Effect.Effect; + /** Forgets credentials revoked before `revokedBefore`; they can never authenticate again. */ + readonly pruneRevoked: (input: { + readonly revokedBefore: string; + }) => Effect.Effect; } >()("t3code-relay/environments/EnvironmentCredentials") {} @@ -284,9 +291,33 @@ const make = Effect.gen(function* () { }), ), ); + if (rows.length > 0) { + // Delivered on commit; relays carrying channels recheck them now instead of on their timer. + yield* db.execute(sql`SELECT pg_notify(${CREDENTIALS_REVOKED_CHANNEL}, '')`).pipe( + Effect.mapError( + (cause) => + new EnvironmentCredentialRevokePersistenceError({ + environmentId: input.environmentId, + cause, + }), + ), + ); + } return rows.length > 0; }), + + pruneRevoked: Effect.fn("relay.environment_credentials.prune_revoked")(function* (input) { + yield* db + .delete(relayEnvironmentCredentials) + .where(lt(relayEnvironmentCredentials.revokedAt, input.revokedBefore)) + .pipe( + Effect.mapError((cause) => new EnvironmentCredentialRevokePersistenceError({ cause })), + ); + }), }); }); +/** The Postgres notification channel announcing revoked environment credentials. */ +export const CREDENTIALS_REVOKED_CHANNEL = "t3_relay_credentials_revoked"; + export const layer = Layer.effect(EnvironmentCredentials, make); diff --git a/infra/relay/src/environments/EnvironmentLinker.test.ts b/infra/relay/src/environments/EnvironmentLinker.test.ts index fe15ef03dd6a..8a6dfd155793 100644 --- a/infra/relay/src/environments/EnvironmentLinker.test.ts +++ b/infra/relay/src/environments/EnvironmentLinker.test.ts @@ -20,6 +20,7 @@ import * as RelayTokens from "../auth/RelayTokens.ts"; import * as EnvironmentCredentials from "./EnvironmentCredentials.ts"; import * as EnvironmentLinks from "./EnvironmentLinks.ts"; import * as RelayConfiguration from "../Config.ts"; +import * as RelayDb from "../db.ts"; import * as EnvironmentLinker from "./EnvironmentLinker.ts"; import * as ManagedEndpointProvider from "./ManagedEndpointProvider.ts"; @@ -161,15 +162,40 @@ const makePublishOnlyRequest = (httpBaseUrl = "http://127.0.0.1:3773/") => function layerTest(input?: { readonly channels?: boolean; + readonly maxEnvironmentsPerUser?: number; + readonly activeLinks?: number; readonly upsert?: EnvironmentLinks.EnvironmentLinks["Service"]["upsert"]; + readonly create?: EnvironmentCredentials.EnvironmentCredentials["Service"]["create"]; + readonly transaction?: { open: boolean; outcome?: "committed" | "rolled-back" }; readonly consume?: DpopProofs.DpopProofReplay["Service"]["consume"]; readonly deprovision?: ManagedEndpointProvider.ManagedEndpointProvider["Service"]["deprovision"]; }) { + const transaction = input?.transaction ?? { open: false }; return EnvironmentLinker.layer.pipe( Layer.provideMerge(RelayTokens.layer.pipe(Layer.provide(CloudMintSigner.layer))), Layer.provide( Layer.mergeAll( - RelayConfiguration.layer(input?.channels ? { ...config, channels: true } : config), + RelayConfiguration.layer({ + ...config, + ...(input?.channels ? { channels: true } : {}), + ...(input?.maxEnvironmentsPerUser === undefined + ? {} + : { maxEnvironmentsPerUser: input.maxEnvironmentsPerUser }), + }), + Layer.succeed(RelayDb.RelayTransactions, { + withTransaction: (effect) => + Effect.sync(() => { + transaction.open = true; + }).pipe( + Effect.andThen(effect), + Effect.onExit((exit) => + Effect.sync(() => { + transaction.open = false; + transaction.outcome = exit._tag === "Success" ? "committed" : "rolled-back"; + }), + ), + ), + }), Layer.succeed(DpopProofs.DpopProofReplay, { verifyAndConsume: () => Effect.die("unexpected DPoP proof verification"), consume: input?.consume ?? (() => Effect.succeed(true)), @@ -178,16 +204,18 @@ function layerTest(input?: { Layer.succeed(EnvironmentLinks.EnvironmentLinks, { upsert: input?.upsert ?? (() => Effect.void), listDeliveryUsersForEnvironment: () => Effect.succeed([]), - listForUser: () => Effect.succeed([]), + listForUser: () => + Effect.succeed(Array.from({ length: input?.activeLinks ?? 0 }, () => ({}) as never)), getForUser: () => Effect.succeed(null), findActiveManagedForEnvironment: () => Effect.succeed([]), setHoldWebhooksWhileOffline: () => Effect.void, revokeForUser: () => Effect.succeed(false), }), Layer.succeed(EnvironmentCredentials.EnvironmentCredentials, { - create: () => Effect.succeed("t3env_credential_secret"), + create: input?.create ?? (() => Effect.succeed("t3env_credential_secret")), authenticate: () => Effect.succeedNone, revokeForEnvironmentPublicKey: () => Effect.succeed(false), + pruneRevoked: () => Effect.die("unused"), }), Layer.succeed(ManagedEndpointProvider.ManagedEndpointProvider, { reconcileOrigin: () => Effect.succeed("ready"), @@ -213,6 +241,8 @@ function layerTest(input?: { describe("EnvironmentLinker", () => { it.effect("uses verified JWT claims when linking an environment", () => { let persistedEnvironmentId: string | null = null; + const transaction: { open: boolean; outcome?: "committed" | "rolled-back" } = { open: false }; + const writesInTransaction: Array = []; return Effect.gen(function* () { const { request, payload } = yield* makeRequest; const linker = yield* EnvironmentLinker.EnvironmentLinker; @@ -220,13 +250,55 @@ describe("EnvironmentLinker", () => { expect(result.environmentId).toBe(payload.environmentId); expect(result.environmentCredential).toBe("t3env_credential_secret"); expect(persistedEnvironmentId).toBe(payload.environmentId); + // The link and its credential commit together or not at all. + expect(writesInTransaction).toEqual([true, true]); + expect(transaction.outcome).toBe("committed"); }).pipe( Effect.provide( layerTest({ + transaction, + maxEnvironmentsPerUser: 2, + activeLinks: 2, upsert: (input) => Effect.sync(() => { + writesInTransaction.push(transaction.open); persistedEnvironmentId = input.proof.environmentId; }), + create: () => + Effect.sync(() => { + writesInTransaction.push(transaction.open); + return "t3env_credential_secret"; + }), + }), + ), + ); + }); + + it.effect("refuses a link past the account's cap and rolls the link back", () => { + const transaction: { open: boolean; outcome?: "committed" | "rolled-back" } = { open: false }; + let credentialCreated = false; + return Effect.gen(function* () { + const { request } = yield* makeRequest; + const linker = yield* EnvironmentLinker.EnvironmentLinker; + const error = yield* Effect.flip(linker.link({ userId: "user_123", request })); + expect(error).toMatchObject({ + _tag: "ManagedTunnelLimitExceeded", + maxTunnels: 2, + activeTunnels: 2, + }); + expect(transaction.outcome).toBe("rolled-back"); + expect(credentialCreated).toBe(false); + }).pipe( + Effect.provide( + layerTest({ + transaction, + maxEnvironmentsPerUser: 2, + activeLinks: 3, + create: () => + Effect.sync(() => { + credentialCreated = true; + return "t3env_credential_secret"; + }), }), ), ); diff --git a/infra/relay/src/environments/EnvironmentLinker.ts b/infra/relay/src/environments/EnvironmentLinker.ts index 0c9bb0c9845c..b7636aff7e34 100644 --- a/infra/relay/src/environments/EnvironmentLinker.ts +++ b/infra/relay/src/environments/EnvironmentLinker.ts @@ -25,6 +25,8 @@ import * as EnvironmentLinks from "./EnvironmentLinks.ts"; import * as ManagedEndpointProvider from "./ManagedEndpointProvider.ts"; import { channelEndpoint, channelKey } from "./RelayChannelEndpoint.ts"; import * as RelayConfiguration from "../Config.ts"; +import * as RelayDb from "../db.ts"; +import * as ManagedTunnelLimits from "./ManagedTunnelLimits.ts"; export class EnvironmentLinkProofExpired extends Schema.TaggedError()( "EnvironmentLinkProofExpired", @@ -72,6 +74,7 @@ export type EnvironmentLinkError = | DpopProofs.DpopProofReplayPersistenceError | EnvironmentLinks.EnvironmentLinkUpsertPersistenceError | EnvironmentCredentials.EnvironmentCredentialCreatePersistenceError + | ManagedTunnelLimits.ManagedTunnelLimitExceeded | ManagedEndpointProvider.ManagedEndpointProviderError; export class EnvironmentLinker extends Context.Service< @@ -147,6 +150,7 @@ const make = Effect.gen(function* () { const relayTokens = yield* RelayTokens.RelayTokens; const config = yield* RelayConfiguration.RelayConfiguration; const signature = yield* Signature.Signature; + const transactions = yield* RelayDb.RelayTransactions; return EnvironmentLinker.of({ link: Effect.fn("relay.environment_linker.link")(function* (input) { @@ -339,11 +343,38 @@ const make = Effect.gen(function* () { stage: "validate_endpoint", }); } - yield* links.upsert({ ...input, proof: verified, endpoint }); - const environmentCredential = yield* credentials.create({ - environmentId: verified.environmentId, - environmentPublicKey: verified.environmentPublicKey, - }); + const persistenceFailed = (cause: unknown) => + new EnvironmentLinks.EnvironmentLinkUpsertPersistenceError({ + userId: input.userId, + environmentId: verified.environmentId, + cause, + }); + // One transaction, so a failed or refused link never leaves a link without a credential. + const environmentCredential = yield* transactions + .withTransaction( + Effect.gen(function* () { + yield* links.upsert({ ...input, proof: verified, endpoint }); + const maxLinks = config.maxEnvironmentsPerUser; + if (maxLinks !== undefined) { + const active = yield* links + .listForUser({ userId: input.userId }) + .pipe(Effect.mapError(persistenceFailed)); + if (active.length > maxLinks) { + return yield* new ManagedTunnelLimits.ManagedTunnelLimitExceeded({ + userId: input.userId, + environmentId: verified.environmentId, + maxTunnels: maxLinks, + activeTunnels: active.length - 1, + }); + } + } + return yield* credentials.create({ + environmentId: verified.environmentId, + environmentPublicKey: verified.environmentPublicKey, + }); + }), + ) + .pipe(Effect.catchTags({ SqlError: (error) => Effect.fail(persistenceFailed(error)) })); return { environmentId: verified.environmentId, endpoint, diff --git a/infra/relay/src/host/RelayChannels.test.ts b/infra/relay/src/host/RelayChannels.test.ts index 0a46d857538f..4e5b656e2cdf 100644 --- a/infra/relay/src/host/RelayChannels.test.ts +++ b/infra/relay/src/host/RelayChannels.test.ts @@ -12,7 +12,7 @@ import * as TestClock from "effect/testing/TestClock"; import * as EnvironmentCredentials from "../environments/EnvironmentCredentials.ts"; import { channelKey } from "../environments/RelayChannelEndpoint.ts"; -import { makeRelayChannels } from "./RelayChannels.ts"; +import { makeRelayChannels, type RelayChannelLimits } from "./RelayChannels.ts"; const makeLayer = (credentialValid: () => boolean = () => true) => Layer.mergeAll( @@ -26,16 +26,19 @@ const makeLayer = (credentialValid: () => boolean = () => true) => : Option.none(), ), revokeForEnvironmentPublicKey: () => Effect.die("unused"), + pruneRevoked: () => Effect.die("unused"), }), ); -const serveRelay = Effect.gen(function* () { - yield* HttpServer.serveEffect( - makeRelayChannels()(Effect.succeed(HttpServerResponse.text("relay api"))), - ); - const { address } = yield* HttpServer.HttpServer; - return "port" in address ? address.port : 0; -}); +const serveRelayWith = (limits: Partial = {}) => + Effect.gen(function* () { + const channels = makeRelayChannels(limits); + yield* HttpServer.serveEffect(channels(Effect.succeed(HttpServerResponse.text("relay api")))); + const { address } = yield* HttpServer.HttpServer; + return { port: "port" in address ? address.port : 0, recheckAll: channels.recheckAll }; + }); + +const serveRelay = Effect.map(serveRelayWith(), ({ port }) => port); const channelPrefix = Effect.map(channelKey("env-1", "k"), (key) => `/env/${key}`); @@ -51,7 +54,15 @@ const connectEnvironment = (port: number, token: string) => // The relay pings once the channel is registered. if (frame.type === "ping") resume(Effect.succeed(socket)); if (frame.type === "http-request") { - const echo = `${frame.method} ${frame.path} ${frame.headers["x-forwarded-prefix"]}`; + const echo = [ + frame.method, + frame.path, + frame.headers["x-forwarded-prefix"], + frame.headers["x-forwarded-for"], + frame.headers["x-forwarded-host"] ?? "-", + frame.headers.forwarded ?? "-", + frame.headers["x-real-ip"] ?? "-", + ].join(" "); socket.send( JSON.stringify({ type: "http-response", @@ -59,7 +70,7 @@ const connectEnvironment = (port: number, token: string) => status: 302, headers: { "content-type": frame.path.endsWith(".pdf") ? "application/pdf" : "text/plain", - location: "/next", + location: frame.headers["x-test-location"] ?? "/next", "Set-Cookie": "s=1", "Content-Security-Policy": "default-src *", "Clear-Site-Data": '"*"', @@ -74,9 +85,12 @@ const connectEnvironment = (port: number, token: string) => (socket) => Effect.sync(() => socket.close()), ); -const get = (port: number, path: string) => +const get = (port: number, path: string, init: RequestInit = {}) => Effect.promise(async () => { - const response = await fetch(`http://127.0.0.1:${port}${path}`, { redirect: "manual" }); + const response = await fetch(`http://127.0.0.1:${port}${path}`, { + redirect: "manual", + ...init, + }); return { status: response.status, body: await response.text(), @@ -96,7 +110,7 @@ describe("makeRelayChannels", () => { expect(yield* get(port, `${prefix}/api/state?x=1`)).toEqual({ status: 302, - body: `GET /api/state?x=1 ${prefix}`, + body: `GET /api/state?x=1 ${prefix} 127.0.0.1 - - -`, location: `${prefix}/next`, cookie: null, csp: "sandbox allow-scripts allow-forms allow-popups allow-downloads", @@ -117,6 +131,62 @@ describe("makeRelayChannels", () => { }).pipe(Effect.scoped, Effect.provide(makeLayer())), ); + it.live("states the client address itself and keeps redirects on the environment's path", () => + Effect.gen(function* () { + const port = yield* serveRelay; + const prefix = yield* channelPrefix; + yield* connectEnvironment(port, "good"); + // The loopback peer stands in for the front proxy, whose own entry comes last. + const spoofed = yield* get(port, `${prefix}/api/state`, { + headers: { + "x-forwarded-for": "198.51.100.1, 203.0.113.9", + "x-forwarded-host": "elsewhere.example", + forwarded: "for=198.51.100.1", + "x-real-ip": "198.51.100.1", + }, + }); + expect(spoofed.body).toBe(`GET /api/state ${prefix} 203.0.113.9 - - -`); + + const redirects = [ + ["next", `${prefix}/api/next`], + ["/next?a=1", `${prefix}/next?a=1`], + ["https://elsewhere.example/login", null], + ["//elsewhere.example/login", null], + ["/\\elsewhere.example/login", null], + ["../../../login", null], + ] as const; + for (const [location, expected] of redirects) { + const response = yield* get(port, `${prefix}/api/state`, { + headers: { "x-test-location": location }, + }); + expect([location, response.location]).toEqual([location, expected]); + } + }).pipe(Effect.scoped, Effect.provide(makeLayer())), + ); + + it.live("refuses bodies past the limit and requests past the memory budget", () => + Effect.gen(function* () { + const { port } = yield* serveRelayWith({ maxBodyBytes: 64, maxBufferedBytes: 1024 }); + const prefix = yield* channelPrefix; + yield* connectEnvironment(port, "good"); + const post = (bytes: number) => + get(port, `${prefix}/upload`, { method: "POST", body: "x".repeat(bytes) }); + expect((yield* post(64)).status).toBe(302); + expect((yield* post(65)).status).toBe(413); + }).pipe(Effect.scoped, Effect.provide(makeLayer())), + ); + + it.live("answers 503 once carried bodies would pass the relay's memory budget", () => + Effect.gen(function* () { + // A body is held twice while forwarded: as read, and base64-encoded in its frame. + const { port } = yield* serveRelayWith({ maxBufferedBytes: 200 }); + yield* connectEnvironment(port, "good"); + const path = `${yield* channelPrefix}/upload`; + expect((yield* get(port, path, { method: "POST", body: "x".repeat(50) })).status).toBe(302); + expect((yield* get(port, path, { method: "POST", body: "x".repeat(101) })).status).toBe(503); + }).pipe(Effect.scoped, Effect.provide(makeLayer())), + ); + it.live("answers the environment's keepalive pings", () => Effect.gen(function* () { const socket = yield* connectEnvironment(yield* serveRelay, "good"); @@ -177,6 +247,21 @@ describe("makeRelayChannels", () => { }, ); + it.effect("closes a revoked channel as soon as a revocation is announced", () => { + let valid = true; + return Effect.gen(function* () { + const { port, recheckAll } = yield* serveRelayWith(); + const socket = yield* connectEnvironment(port, "good"); + const closed = Effect.callback((resume) => + socket.addEventListener("close", () => resume(Effect.void)), + ); + valid = false; + // The test clock never moves, so only the announcement can end the channel. + yield* recheckAll; + yield* closed; + }).pipe(Effect.scoped, Effect.provide(makeLayer(() => valid))); + }); + it.live("refuses a channel opened with another credential", () => Effect.gen(function* () { const port = yield* serveRelay; diff --git a/infra/relay/src/host/RelayChannels.ts b/infra/relay/src/host/RelayChannels.ts index cd95614494ae..42210b2851a9 100644 --- a/infra/relay/src/host/RelayChannels.ts +++ b/infra/relay/src/host/RelayChannels.ts @@ -1,8 +1,5 @@ -import { - RELAY_CHANNEL_MAX_BODY_BYTES, - RELAY_CHANNEL_RESPONSE_TIMEOUT_MS, - RelayChannelFrame, -} from "@t3tools/contracts/relay"; +import { PROVIDER_SEND_TURN_MAX_FILE_BYTES } from "@t3tools/contracts"; +import { RELAY_CHANNEL_RESPONSE_TIMEOUT_MS, RelayChannelFrame } from "@t3tools/contracts/relay"; import * as ByteSize from "effect/ByteSize"; import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; @@ -17,6 +14,7 @@ import * as Socket from "effect/socket/Socket"; import * as EnvironmentCredentials from "../environments/EnvironmentCredentials.ts"; import { channelKey, channelPathTarget } from "../environments/RelayChannelEndpoint.ts"; +import { endpointAddressRejection, isIpAddress } from "./manualEndpointClient.ts"; type HttpResponseFrame = Extract; type SocketFrame = Extract< @@ -24,33 +22,135 @@ type SocketFrame = Extract< { readonly type: "ws-opened" | "ws-message" | "ws-close" } >; +interface CarriedSocket { + readonly inbox: Queue.Queue; + /** Bytes of `ws-message` data waiting in `inbox` for a slow client. */ + queuedBytes: number; + /** Completed when the client falls too far behind; its socket is then closed. */ + readonly overflowed: Deferred.Deferred; +} + interface Channel { readonly send: (frame: RelayChannelFrame) => Effect.Effect; readonly responses: Map>; - readonly sockets: Map>; + readonly sockets: Map; /** Completed when a reconnect takes this channel's place. */ readonly replaced: Deferred.Deferred; /** Completed once the channel's socket is gone. */ readonly ended: Deferred.Deferred; /** Rechecks since the environment last sent a frame. */ quietChecks: number; + /** Credential lookups failed in a row. */ + failedLookups: number; + /** Asks for a credential check now rather than at the next interval. */ + readonly wakeups: Queue.Queue; +} + +/** + * Memory bounds for carried traffic. Bodies and frames cross the channel whole, so these cap what + * one environment, or anyone who knows its `/env//` path, can make the relay hold. + */ +export interface RelayChannelLimits { + /** Largest request body forwarded to an environment. */ + readonly maxBodyBytes: number; + /** Bodies and socket frames held across all channels at once; past it, new ones are refused. */ + readonly maxBufferedBytes: number; + /** Requests waiting on one environment's answers. */ + readonly maxPendingRequests: number; + /** WebSockets carried to one environment. */ + readonly maxSockets: number; + /** Frames from the environment a slow client may leave unread before its socket is closed. */ + readonly maxSocketQueueBytes: number; +} + +// The largest legitimate upload is a file attachment; RPC frames with images are smaller. +export const DEFAULT_RELAY_CHANNEL_LIMITS: RelayChannelLimits = { + maxBodyBytes: PROVIDER_SEND_TURN_MAX_FILE_BYTES, + maxBufferedBytes: 256 * 1024 * 1024, + maxPendingRequests: 64, + maxSockets: 64, + maxSocketQueueBytes: 16 * 1024 * 1024, +}; + +/** A frame carrying a body this large, base64-encoded, plus room for the frame around it. */ +export const channelFrameBytesFor = (bodyBytes: number) => + Math.ceil(bodyBytes / 3) * 4 + 1024 * 1024; + +/** Shares one memory allowance between every carried request and socket. */ +const makeByteBudget = (limit: number) => { + let used = 0; + return { + acquire: (bytes: number) => { + if (used + bytes > limit) return false; + used += bytes; + return true; + }, + release: (bytes: number) => { + used = Math.max(0, used - bytes); + }, + }; +}; + +// Socket writes do not wait for the peer; past this many unsent bytes the writer waits for drain. +const WRITE_HIGH_WATER_BYTES = 1024 * 1024; + +interface WritableSocket { + readonly writableLength: number; + once(event: "drain" | "close", listener: () => void): unknown; + off(event: "drain" | "close", listener: () => void): unknown; +} + +/** The TCP socket under a Node request, which a WebSocket upgrade keeps using. */ +function writableSocketOf(request: HttpServerRequest.HttpServerRequest): WritableSocket | null { + const source: unknown = request.source; + const socket: unknown = + typeof source === "object" && source !== null ? Reflect.get(source, "socket") : null; + return typeof socket === "object" && socket !== null && "writableLength" in socket + ? (socket as WritableSocket) + : null; } +/** Waits until the peer has read enough of what was sent, so a slow reader slows the writer. */ +const whenDrained = (socket: WritableSocket | null) => + socket === null || socket.writableLength <= WRITE_HIGH_WATER_BYTES + ? Effect.void + : Effect.callback((resume) => { + const done = () => resume(Effect.void); + socket.once("drain", done); + socket.once("close", done); + return Effect.sync(() => { + socket.off("drain", done); + socket.off("close", done); + }); + }); + const CREDENTIAL_RECHECK_INTERVAL = "25 seconds"; // Environments ping as often as the relay rechecks, so this much silence is a dead connection. const MAX_QUIET_CHECKS = 2; +// A database hiccup should not drop every environment, but an outage must not keep revoked ones. +const MAX_FAILED_LOOKUPS = 4; // The environment's own document sandbox: scripts run, but in an opaque origin, never the relay's. const CARRIED_CONTENT_SECURITY_POLICY = "sandbox allow-scripts allow-forms allow-popups allow-downloads"; const CHANNEL_SOCKET_PATH = /^\/v1\/environments\/([^/?]+)\/channel(?:\?.*)?$/u; -// Per-connection headers stay on their own side of the relay. +// Per-connection headers stay on their own side of the relay, and so do claims about the client's +// address, which the relay states itself. const HOP_BY_HOP_HEADERS = new Set([ "connection", "keep-alive", "upgrade", "transfer-encoding", "content-length", + "te", + "trailer", + "proxy-connection", + "proxy-authorization", + "proxy-authenticate", + "forwarded", + "x-real-ip", ]); +const isClientAddressClaim = (name: string) => + HOP_BY_HOP_HEADERS.has(name) || name.startsWith("x-forwarded-"); const decodeFrame = Schema.decodeUnknownOption(RelayChannelFrame); @@ -93,10 +193,40 @@ const ALLOWED_RESPONSE_HEADERS = new Set([ function withoutHopByHop(headers: Readonly>): Record { return Object.fromEntries( - Object.entries(headers).filter(([name]) => !HOP_BY_HOP_HEADERS.has(name.toLowerCase())), + Object.entries(headers).filter(([name]) => !isClientAddressClaim(name.toLowerCase())), ); } +/** + * The client as this relay sees it. A peer on a private or loopback address is the front proxy, + * whose own entry is the last one; any other peer is the client itself. + */ +function clientAddress(request: HttpServerRequest.HttpServerRequest): string | undefined { + const peer = Option.getOrUndefined(request.peerAddress); + if (peer === undefined || endpointAddressRejection(peer, "public") === null) return peer; + const forwarded = request.headers["x-forwarded-for"]?.split(",").at(-1)?.trim(); + return forwarded !== undefined && isIpAddress(forwarded) ? forwarded : peer; +} + +/** + * Keeps a redirect on the environment's own path: root-relative targets gain its prefix, and + * anything a browser would resolve elsewhere, including `//host` and `/\host`, is dropped. + */ +function carriedLocation(location: string, target: ChannelTarget): string | undefined { + const base = new URL(`${target.prefix}${target.path}`, "https://relay.invalid"); + const rooted = /^\/(?![/\\])/u.test(location) ? `${target.prefix}${location}` : location; + try { + const resolved = new URL(rooted, base); + const path = `${resolved.pathname}${resolved.search}${resolved.hash}`; + return resolved.origin === base.origin && + (resolved.pathname === target.prefix || resolved.pathname.startsWith(`${target.prefix}/`)) + ? path + : undefined; + } catch { + return undefined; + } +} + /** Lowercases names, which frames from an environment need not do, and keeps the allowlist. */ function allowedResponseHeaders(headers: Readonly>): Record { return Object.fromEntries( @@ -121,9 +251,20 @@ type ChannelTarget = NonNullable>; /** The client's headers, telling the environment which prefix the relay stripped. */ function forwardedHeaders(request: HttpServerRequest.HttpServerRequest, target: ChannelTarget) { - return { ...withoutHopByHop(request.headers), "x-forwarded-prefix": target.prefix }; + const client = clientAddress(request); + return { + ...withoutHopByHop(request.headers), + "x-forwarded-prefix": target.prefix, + ...(client === undefined ? {} : { "x-forwarded-for": client }), + }; } +const busy = () => + HttpServerResponse.text("The relay is carrying too much for this environment right now.", { + status: 503, + headers: { "retry-after": "5" }, + }); + const isWebSocketUpgrade = (request: HttpServerRequest.HttpServerRequest) => request.headers.upgrade?.toLowerCase() === "websocket"; @@ -132,7 +273,9 @@ const isWebSocketUpgrade = (request: HttpServerRequest.HttpServerRequest) => * and requests under its `/env//` path are forwarded over that socket, prefix stripped. * Channels live in this process, so a relay serving them must run as a single replica. */ -export const makeRelayChannels = () => { +export const makeRelayChannels = (options: Partial = {}) => { + const limits = { ...DEFAULT_RELAY_CHANNEL_LIMITS, ...options }; + const budget = makeByteBudget(limits.maxBufferedBytes); const channels = new Map(); let nextId = 0; @@ -144,8 +287,21 @@ export const makeRelayChannels = () => { return response ? Deferred.succeed(response, frame).pipe(Effect.asVoid) : Effect.void; } if (frame?.type === "ws-opened" || frame?.type === "ws-message" || frame?.type === "ws-close") { - const inbox = channel.sockets.get(frame.id); - return inbox ? Queue.offer(inbox, frame).pipe(Effect.asVoid) : Effect.void; + const carried = channel.sockets.get(frame.id); + if (carried === undefined) return Effect.void; + if (frame.type === "ws-message") { + const size = frame.data.length; + // A queue that is not empty belongs to a client that stopped reading; past the cap it is + // closed rather than buffered, and one huge frame alone still gets through. + if ( + (carried.queuedBytes > 0 && carried.queuedBytes + size > limits.maxSocketQueueBytes) || + !budget.acquire(size) + ) { + return Deferred.succeed(carried.overflowed, undefined).pipe(Effect.asVoid); + } + carried.queuedBytes += size; + } + return Queue.offer(carried.inbox, frame).pipe(Effect.asVoid); } return Effect.void; }; @@ -162,17 +318,22 @@ export const makeRelayChannels = () => { const writer = yield* socket.writer; const reader = yield* socket.reader; const socketEnded = yield* Deferred.make(); + const environmentSocket = writableSocketOf(request); const channel: Channel = { // Once the socket closes, a write waits for it to reopen, which never happens. send: (frame) => - writer - .write(JSON.stringify(frame)) - .pipe(Effect.raceFirst(Deferred.await(socketEnded)), Effect.ignore), + whenDrained(environmentSocket).pipe( + Effect.andThen(writer.write(JSON.stringify(frame))), + Effect.raceFirst(Deferred.await(socketEnded)), + Effect.ignore, + ), responses: new Map(), sockets: new Map(), replaced: yield* Deferred.make(), ended: socketEnded, quietChecks: 0, + failedLookups: 0, + wakeups: yield* Queue.sliding(1), }; const previous = channels.get(key); channels.set(key, channel); @@ -184,8 +345,8 @@ export const makeRelayChannels = () => { if (channels.get(key) === channel) channels.delete(key); // Pending requests answer 502, and sends stop waiting on the closed socket. yield* Deferred.succeed(socketEnded, undefined); - for (const [id, inbox] of channel.sockets) { - yield* Queue.offer(inbox, { type: "ws-close", id, code: 1012 }); + for (const [id, carried] of channel.sockets) { + yield* Queue.offer(carried.inbox, { type: "ws-close", id, code: 1012 }); } yield* Effect.logInfo("Relay channel disconnected", { environmentId }); }), @@ -202,19 +363,34 @@ export const makeRelayChannels = () => { Effect.forever, ); // Revocation and silence end the channel on the relay's own clock, whatever the environment - // sends. A failed lookup keeps the channel: a database hiccup should not drop every environment. - const recheck = Effect.suspend(() => { - channel.quietChecks += 1; - if (channel.quietChecks > MAX_QUIET_CHECKS) return Effect.succeed(false); - return credentials.authenticate(token).pipe( - Effect.map((current) => - Option.exists(current, (now) => now.credentialId === principal.credentialId), - ), - Effect.orElseSucceed(() => true), - ); - }); - const ended = yield* Effect.sleep(CREDENTIAL_RECHECK_INTERVAL).pipe( - Effect.andThen(recheck), + // sends; a revocation elsewhere wakes the check early. + const recheck = (timed: boolean) => + Effect.suspend(() => { + if (timed) channel.quietChecks += 1; + if (channel.quietChecks > MAX_QUIET_CHECKS) return Effect.succeed(false); + return credentials.authenticate(token).pipe( + Effect.match({ + onFailure: () => { + channel.failedLookups += 1; + return channel.failedLookups <= MAX_FAILED_LOOKUPS; + }, + onSuccess: (current) => { + channel.failedLookups = 0; + return Option.exists(current, (now) => now.credentialId === principal.credentialId); + }, + }), + ); + }); + // True when the interval elapsed, false when woken early. + const nextCheck = Queue.take(channel.wakeups).pipe( + Effect.as(false), + Effect.timeoutOrElse({ + duration: CREDENTIAL_RECHECK_INTERVAL, + orElse: () => Effect.succeed(true), + }), + ); + const ended = yield* nextCheck.pipe( + Effect.flatMap(recheck), Effect.repeat({ while: (stillValid) => stillValid }), Effect.forkScoped({ startImmediately: true }), ); @@ -232,11 +408,18 @@ export const makeRelayChannels = () => { request: HttpServerRequest.HttpServerRequest, target: ChannelTarget, ) { + if (channel.responses.size >= limits.maxPendingRequests) return busy(); + // Held twice while forwarded: the body itself and its base64 copy in the frame. + const declared = Number(request.headers["content-length"] ?? 0); + const reserved = + 2 * + (request.headers["transfer-encoding"] !== undefined || !Number.isFinite(declared) + ? limits.maxBodyBytes + : Math.min(declared, limits.maxBodyBytes)); + if (!budget.acquire(reserved)) return busy(); + yield* Effect.addFinalizer(() => Effect.sync(() => budget.release(reserved))); const body = yield* request.arrayBuffer.pipe( - Effect.provideService( - HttpIncomingMessage.MaxBodySize, - ByteSize.bytes(RELAY_CHANNEL_MAX_BODY_BYTES), - ), + Effect.provideService(HttpIncomingMessage.MaxBodySize, ByteSize.bytes(limits.maxBodyBytes)), Effect.map((buffer) => new Uint8Array(buffer)), Effect.option, ); @@ -268,6 +451,10 @@ export const makeRelayChannels = () => { if (Option.isNone(result)) { return HttpServerResponse.text("The environment did not answer in time.", { status: 504 }); } + // The answer is already in memory; refusing it keeps it from also being decoded and sent. + const answerBytes = result.value.body?.length ?? 0; + if (!budget.acquire(answerBytes)) return busy(); + yield* Effect.addFinalizer(() => Effect.sync(() => budget.release(answerBytes))); const { "content-type": contentType, ...forwarded } = allowedResponseHeaders( result.value.headers, ); @@ -279,30 +466,39 @@ export const makeRelayChannels = () => { "content-security-policy": CARRIED_CONTENT_SECURITY_POLICY, "x-content-type-options": "nosniff", }; - // A root-relative redirect from the environment stays under its prefix. - if (headers.location?.startsWith("/") && !headers.location.startsWith("//")) { - headers.location = `${target.prefix}${headers.location}`; + if (headers.location !== undefined) { + const location = carriedLocation(headers.location, target); + if (location === undefined) delete headers.location; + else headers.location = location; } return HttpServerResponse.uint8Array( result.value.body ? Buffer.from(result.value.body, "base64") : new Uint8Array(), { status: result.value.status, headers, ...(contentType ? { contentType } : {}) }, ); - }); + }, Effect.scoped); const forwardWebSocket = Effect.fn("RelayChannels.forwardWebSocket")(function* ( channel: Channel, request: HttpServerRequest.HttpServerRequest, target: ChannelTarget, ) { + if (channel.sockets.size >= limits.maxSockets) return busy(); const id = ++nextId; - const inbox = yield* Queue.unbounded(); - channel.sockets.set(id, inbox); + const carried: CarriedSocket = { + inbox: yield* Queue.unbounded(), + queuedBytes: 0, + overflowed: yield* Deferred.make(), + }; + const { inbox } = carried; + channel.sockets.set(id, carried); // However this ends, even when the client vanishes mid-handshake, the environment closes its // side: its local socket would otherwise stay open, sending into an inbox nobody reads. yield* Effect.addFinalizer(() => - Effect.sync(() => channel.sockets.delete(id)).pipe( - Effect.andThen(channel.send({ type: "ws-close", id })), - ), + Effect.sync(() => { + channel.sockets.delete(id); + budget.release(carried.queuedBytes); + carried.queuedBytes = 0; + }).pipe(Effect.andThen(channel.send({ type: "ws-close", id }))), ); yield* channel.send({ type: "ws-open", @@ -317,10 +513,22 @@ export const makeRelayChannels = () => { const socket = yield* request.upgrade; const writer = yield* socket.writer; const reader = yield* socket.reader; + const clientSocket = writableSocketOf(request); const toClient = Queue.take(inbox).pipe( + Effect.tap((frame) => + Effect.sync(() => { + if (frame.type !== "ws-message") return; + carried.queuedBytes -= frame.data.length; + budget.release(frame.data.length); + }), + ), Effect.flatMap((frame) => frame.type === "ws-message" - ? writer.write(frame.binary ? Buffer.from(frame.data, "base64") : frame.data) + ? whenDrained(clientSocket).pipe( + Effect.andThen( + writer.write(frame.binary ? Buffer.from(frame.data, "base64") : frame.data), + ), + ) : frame.type === "ws-close" ? writer .write(new Socket.CloseEvent(sendableCloseCode(frame.code), frame.reason)) @@ -349,7 +557,13 @@ export const makeRelayChannels = () => { ), Effect.forever, ); - yield* Effect.raceFirst(toClient, toEnvironment).pipe(Effect.ignore); + // 1013 (try again later): the client fell too far behind what its environment sent. + const overflowed = Deferred.await(carried.overflowed).pipe( + Effect.andThen(writer.write(new Socket.CloseEvent(1013, "client too slow"))), + ); + yield* Effect.raceFirst(toClient, Effect.raceFirst(toEnvironment, overflowed)).pipe( + Effect.ignore, + ); return HttpServerResponse.empty(); }, Effect.scoped); @@ -368,29 +582,39 @@ export const makeRelayChannels = () => { : null; }); - return (handler: Effect.Effect) => - Effect.gen(function* () { - const request = yield* HttpServerRequest.HttpServerRequest; - const channelPath = CHANNEL_SOCKET_PATH.exec(request.url); - if (channelPath?.[1] !== undefined && isWebSocketUpgrade(request)) { - const authorized = yield* authenticateChannel(request, channelPath[1]); - if (authorized === null) return HttpServerResponse.empty({ status: 401 }); - return yield* serveChannel(authorized.principal, authorized.token, request).pipe( - Effect.orElseSucceed(() => HttpServerResponse.empty({ status: 400 })), - ); - } - const target = channelPathTarget(request.url); - if (target === null) return yield* handler; - const channel = channels.get(target.key); - if (channel === undefined) { - return HttpServerResponse.text("This environment is not connected to the relay.", { - status: 502, - }); - } - return yield* ( - isWebSocketUpgrade(request) - ? forwardWebSocket(channel, request, target) - : forwardHttp(channel, request, target) - ).pipe(Effect.orElseSucceed(() => HttpServerResponse.empty({ status: 400 }))); - }); + /** Rechecks every channel's credential now, as after a revocation. */ + const recheckAll = Effect.suspend(() => + Effect.forEach(channels.values(), (channel) => Queue.offer(channel.wakeups, undefined), { + discard: true, + }), + ); + + // Untraced: it wraps every relay request, and the relay API traces its own. + const middleware = Effect.fnUntraced(function* ( + handler: Effect.Effect, + ) { + const request = yield* HttpServerRequest.HttpServerRequest; + const channelPath = CHANNEL_SOCKET_PATH.exec(request.url); + if (channelPath?.[1] !== undefined && isWebSocketUpgrade(request)) { + const authorized = yield* authenticateChannel(request, channelPath[1]); + if (authorized === null) return HttpServerResponse.empty({ status: 401 }); + return yield* serveChannel(authorized.principal, authorized.token, request).pipe( + Effect.orElseSucceed(() => HttpServerResponse.empty({ status: 400 })), + ); + } + const target = channelPathTarget(request.url); + if (target === null) return yield* handler; + const channel = channels.get(target.key); + if (channel === undefined) { + return HttpServerResponse.text("This environment is not connected to the relay.", { + status: 502, + }); + } + return yield* ( + isWebSocketUpgrade(request) + ? forwardWebSocket(channel, request, target) + : forwardHttp(channel, request, target) + ).pipe(Effect.orElseSucceed(() => HttpServerResponse.empty({ status: 400 }))); + }); + return Object.assign(middleware, { recheckAll }); }; diff --git a/infra/relay/src/host/RelayHost.ts b/infra/relay/src/host/RelayHost.ts index 2f4689c0a91b..a79c27a18fdf 100644 --- a/infra/relay/src/host/RelayHost.ts +++ b/infra/relay/src/host/RelayHost.ts @@ -33,6 +33,8 @@ export interface RelayHost { readonly managedEndpointBaseDomain: string | undefined; /** Whether environments with no public address are carried over relay channels at `/env//`. */ readonly channels?: boolean; + /** Active environment links one account may hold; unset means no cap. */ + readonly maxEnvironmentsPerUser?: number; readonly database: RelayDb.RelayDb["Service"]; /** Tunnel and DNS clients behind managed endpoints; inert on hosts without managed tunnels. */ readonly managedEndpointClients: Layer.Layer< @@ -42,6 +44,13 @@ export interface RelayHost { CloudflareApiPause.CloudflareApiPause | HttpClient.HttpClient >; readonly hookInbox: Layer.Layer; + /** + * Reaches endpoints environments declare themselves only at addresses the policy allows, + * checked where the name resolves. Hosts without one use their default client. + */ + readonly manualEndpointHttpClient?: ( + policy: "public" | "private", + ) => Effect.Effect; /** Each limiter may fail; the composition decides to fail open. */ readonly rateLimits: { readonly hook: (key: string) => Effect.Effect; diff --git a/infra/relay/src/host/manualEndpointClient.test.ts b/infra/relay/src/host/manualEndpointClient.test.ts new file mode 100644 index 000000000000..6da59ca86a4d --- /dev/null +++ b/infra/relay/src/host/manualEndpointClient.test.ts @@ -0,0 +1,104 @@ +import type * as NodeDns from "node:dns"; + +import { describe, expect, it } from "@effect/vitest"; +import * as Effect from "effect/Effect"; + +import { + EndpointAddressBlocked, + endpointAddressRejection, + makeGuardedLookup, + makeManualEndpointHttpClient, +} from "./manualEndpointClient.ts"; + +const lookupWith = + (addresses: ReadonlyArray, policy: "public" | "private" = "public") => + (all: boolean) => + new Promise<{ error: Error | null; result: unknown }>((resolve) => + makeGuardedLookup(policy, (_hostname, _options, callback) => callback(null, [...addresses]))( + "t3.example.dev", + { all }, + (error, address, family) => resolve({ error, result: all ? address : [address, family] }), + ), + ); + +describe("endpointAddressRejection", () => { + it.each([ + ["127.0.0.1", "internal_address"], + ["0.0.0.0", "internal_address"], + ["169.254.169.254", "internal_address"], + ["224.0.0.1", "internal_address"], + ["255.255.255.255", "internal_address"], + ["::", "internal_address"], + ["::1", "internal_address"], + ["fe80::1", "internal_address"], + ["ff02::1", "internal_address"], + ["::ffff:127.0.0.1", "internal_address"], + ["::ffff:a9fe:a9fe", "internal_address"], + ["64:ff9b::a9fe:a9fe", "internal_address"], + ["2002:a9fe:a9fe::1", "internal_address"], + ["10.0.0.5", "private_network"], + ["172.16.4.1", "private_network"], + ["192.168.1.1", "private_network"], + ["100.64.0.1", "private_network"], + ["fd00::1", "private_network"], + ["::ffff:10.0.0.5", "private_network"], + ["8.8.8.8", null], + ["2606:4700::1111", null], + ["::ffff:8.8.8.8", null], + ] as const)("classifies %s", (address, rejection) => { + expect(endpointAddressRejection(address, "public")).toBe(rejection); + }); + + it("allows private networks, but never internal addresses, when the relay opts in", () => { + expect(endpointAddressRejection("10.0.0.5", "private")).toBeNull(); + expect(endpointAddressRejection("fd00::1", "private")).toBeNull(); + expect(endpointAddressRejection("169.254.169.254", "private")).toBe("internal_address"); + expect(endpointAddressRejection("127.0.0.1", "private")).toBe("internal_address"); + }); +}); + +describe("makeGuardedLookup", () => { + it("hands the socket the addresses it checked", async () => { + const lookup = lookupWith([{ address: "8.8.8.8", family: 4 }]); + expect(await lookup(true)).toEqual({ + error: null, + result: [{ address: "8.8.8.8", family: 4 }], + }); + expect(await lookup(false)).toEqual({ error: null, result: ["8.8.8.8", 4] }); + }); + + it("refuses the whole answer when any address is internal", async () => { + const { error } = await lookupWith([ + { address: "8.8.8.8", family: 4 }, + { address: "127.0.0.1", family: 4 }, + ])(true); + expect(error).toBeInstanceOf(EndpointAddressBlocked); + expect(error).toMatchObject({ address: "127.0.0.1", rejection: "internal_address" }); + }); + + it("refuses names that resolve to a private network unless the relay allows them", async () => { + const answer = [{ address: "10.1.2.3", family: 4 }] as const; + expect((await lookupWith(answer)(false)).error).toMatchObject({ + rejection: "private_network", + }); + expect((await lookupWith(answer, "private")(false)).error).toBeNull(); + }); +}); + +describe("makeManualEndpointHttpClient", () => { + it.effect("refuses literal internal addresses and plain HTTP before connecting", () => + Effect.gen(function* () { + const client = yield* makeManualEndpointHttpClient("public"); + for (const url of [ + "https://169.254.169.254/latest", + "https://[::1]/", + "http://t3.example/", + ]) { + const error = yield* Effect.flip(client.get(url)); + expect(error.reason._tag === "TransportError" && error.reason.cause).toBeInstanceOf( + EndpointAddressBlocked, + ); + } + }).pipe(Effect.scoped), + ); +}); diff --git a/infra/relay/src/host/manualEndpointClient.ts b/infra/relay/src/host/manualEndpointClient.ts new file mode 100644 index 000000000000..610e0a12020a --- /dev/null +++ b/infra/relay/src/host/manualEndpointClient.ts @@ -0,0 +1,148 @@ +// @effect-diagnostics nodeBuiltinImport:off - the guard must see the addresses Node's own sockets dial. +import * as NodeDns from "node:dns"; +import * as NodeNet from "node:net"; + +import * as NodeHttpClient from "@effect/platform-node/NodeHttpClient"; +import * as Effect from "effect/Effect"; +import * as HttpClient from "effect/http/HttpClient"; +import * as HttpClientError from "effect/http/HttpClientError"; +import * as Schema from "effect/Schema"; + +/** "public" refuses private networks too; "private" refuses only addresses that never name another machine. */ +export type EndpointAddressPolicy = "public" | "private"; +export type EndpointAddressRejection = "internal_address" | "private_network"; + +const blockList = (ranges: ReadonlyArray) => { + const list = new NodeNet.BlockList(); + for (const [network, prefix, family] of ranges) list.addSubnet(network, prefix, family); + return list; +}; + +// Loopback, link-local (cloud metadata), unspecified, multicast and reserved space, plus the IPv6 +// forms that embed an IPv4 address (compatible, NAT64, 6to4), which could carry any of these. +// BlockList also matches IPv4-mapped IPv6 (::ffff:a.b.c.d) against the IPv4 rules. +const INTERNAL = blockList([ + ["0.0.0.0", 8, "ipv4"], + ["127.0.0.0", 8, "ipv4"], + ["169.254.0.0", 16, "ipv4"], + ["224.0.0.0", 4, "ipv4"], + ["240.0.0.0", 4, "ipv4"], + ["::", 96, "ipv6"], + ["64:ff9b::", 96, "ipv6"], + ["64:ff9b:1::", 48, "ipv6"], + ["100::", 64, "ipv6"], + ["2001::", 23, "ipv6"], + ["2002::", 16, "ipv6"], + ["fe80::", 10, "ipv6"], + ["fec0::", 10, "ipv6"], + ["ff00::", 8, "ipv6"], +]); + +// Private, shared (CGNAT), documentation and benchmarking networks, and IPv6 unique-local. +const PRIVATE = blockList([ + ["10.0.0.0", 8, "ipv4"], + ["100.64.0.0", 10, "ipv4"], + ["172.16.0.0", 12, "ipv4"], + ["192.0.0.0", 24, "ipv4"], + ["192.0.2.0", 24, "ipv4"], + ["192.88.99.0", 24, "ipv4"], + ["192.168.0.0", 16, "ipv4"], + ["198.18.0.0", 15, "ipv4"], + ["198.51.100.0", 24, "ipv4"], + ["203.0.113.0", 24, "ipv4"], + ["2001:db8::", 32, "ipv6"], + ["fc00::", 7, "ipv6"], +]); + +export function endpointAddressRejection( + address: string, + policy: EndpointAddressPolicy, +): EndpointAddressRejection | null { + const family = NodeNet.isIP(address); + if (family === 0) return "internal_address"; + const type = family === 4 ? "ipv4" : "ipv6"; + if (INTERNAL.check(address, type)) return "internal_address"; + return policy === "public" && PRIVATE.check(address, type) ? "private_network" : null; +} + +export const isIpAddress = (value: string) => NodeNet.isIP(value) !== 0; + +export class EndpointAddressBlocked extends Schema.TaggedError()( + "EndpointAddressBlocked", + { + hostname: Schema.String, + address: Schema.String, + rejection: Schema.Literals(["internal_address", "private_network"]), + }, +) { + override get message(): string { + return `Endpoint ${this.hostname} resolves to '${this.address}', an address of kind ${this.rejection}`; + } +} + +const blocked = (hostname: string, address: string, rejection: EndpointAddressRejection) => + new EndpointAddressBlocked({ hostname, address, rejection }); + +type Resolve = ( + hostname: string, + options: NodeDns.LookupAllOptions, + callback: (error: NodeJS.ErrnoException | null, addresses: Array) => void, +) => void; + +/** + * A `lookup` for Node sockets that refuses the whole answer when any address is not allowed. The + * socket then dials the address checked here, so a second DNS answer cannot swap it. + */ +export const makeGuardedLookup = + (policy: EndpointAddressPolicy, resolve: Resolve = NodeDns.lookup): NodeNet.LookupFunction => + (hostname, options, callback) => { + resolve(hostname, { ...options, all: true }, (error, addresses) => { + if (error) return callback(error, "", 0); + const first = addresses[0]; + if (first === undefined) { + return callback(blocked(hostname, "", "internal_address"), "", 0); + } + for (const { address } of addresses) { + const rejection = endpointAddressRejection(address, policy); + if (rejection !== null) { + return callback(blocked(hostname, address, rejection), "", 0); + } + } + return options.all ? callback(null, addresses) : callback(null, first.address, first.family); + }); + }; + +/** + * The client the relay uses for endpoints environments declare themselves. Sockets skip `lookup` + * for IP literals, so those are checked here before any connection. + */ +export const makeManualEndpointHttpClient = Effect.fn("relay.node.manual_endpoint_client")( + function* (policy: EndpointAddressPolicy) { + const client = yield* NodeHttpClient.makeNodeHttp.pipe( + Effect.provideServiceEffect( + NodeHttpClient.HttpAgent, + NodeHttpClient.makeAgent({ lookup: makeGuardedLookup(policy), keepAlive: false }), + ), + ); + return HttpClient.mapRequestEffect(client, (request) => { + const url = URL.parse(request.url); + const hostname = url?.hostname.replace(/^\[|\]$/gu, "") ?? ""; + const rejection = + url?.protocol !== "https:" + ? "internal_address" + : NodeNet.isIP(hostname) === 0 + ? null + : endpointAddressRejection(hostname, policy); + return rejection === null + ? Effect.succeed(request) + : Effect.fail( + new HttpClientError.HttpClientError({ + reason: new HttpClientError.TransportError({ + request, + cause: blocked(hostname, hostname, rejection), + }), + }), + ); + }); + }, +); diff --git a/infra/relay/src/host/node.test.ts b/infra/relay/src/host/node.test.ts index 69ef63194e86..0e7e76bb262d 100644 --- a/infra/relay/src/host/node.test.ts +++ b/infra/relay/src/host/node.test.ts @@ -2,6 +2,7 @@ import { describe, expect, it } from "@effect/vitest"; import * as Effect from "effect/Effect"; import * as Exit from "effect/Exit"; import * as FetchHttpClient from "effect/http/FetchHttpClient"; +import * as FileSystem from "effect/FileSystem"; import * as HttpServerRequest from "effect/http/HttpServerRequest"; import * as Layer from "effect/Layer"; import * as Queue from "effect/Queue"; @@ -10,7 +11,7 @@ import * as SecureRandom from "effect/crypto/SecureRandom"; import * as TestClock from "effect/testing/TestClock"; import type * as RelayDb from "../db.ts"; -import { fixedWindowLimit, makeNodeHost, withPublicOrigin } from "./node.ts"; +import { fixedWindowLimit, makeNodeHost, withFileSecrets, withPublicOrigin } from "./node.ts"; import * as Ports from "./ports.ts"; const layer = Layer.mergeAll(SecureRandom.layerWebCrypto, FetchHttpClient.layer); @@ -45,6 +46,41 @@ describe("withPublicOrigin", () => { ); }); +describe("withFileSecrets", () => { + const files = FileSystem.layerNoop({ + readFileString: (path) => + path === "/run/secrets/database-url" + ? Effect.succeed("postgres://relay:secret@db:5432/relay\n") + : Effect.die(`unexpected read of ${path}`), + }); + + it.effect("reads `_FILE` secrets in as ``, with empty meaning unset", () => + Effect.gen(function* () { + const env = yield* withFileSecrets({ + DATABASE_URL: "", + DATABASE_URL_FILE: "/run/secrets/database-url", + MOBILE_TELEMETRY_TOKEN_FILE: "", + LOG_FILE: "/var/log/relay.log", + }); + expect(env.DATABASE_URL).toBe("postgres://relay:secret@db:5432/relay"); + expect(env.MOBILE_TELEMETRY_TOKEN).toBeUndefined(); + expect(env.LOG).toBeUndefined(); + }).pipe(Effect.provide(files)), + ); + + it.effect("refuses a secret set both directly and from a file", () => + Effect.gen(function* () { + const exit = yield* Effect.exit( + withFileSecrets({ + DATABASE_URL: "postgres://elsewhere", + DATABASE_URL_FILE: "/run/secrets/database-url", + }), + ); + expect(Exit.hasDies(exit)).toBe(true); + }).pipe(Effect.provide(files)), + ); +}); + describe("fixedWindowLimit", () => { it.effect("allows the limit per key within a window and resets after it", () => Effect.gen(function* () { diff --git a/infra/relay/src/host/node.ts b/infra/relay/src/host/node.ts index 57b95ab144ef..5df5ebe89e7a 100644 --- a/infra/relay/src/host/node.ts +++ b/infra/relay/src/host/node.ts @@ -2,12 +2,13 @@ import * as Cause from "effect/Cause"; import * as Clock from "effect/Clock"; import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; import * as Headers from "effect/http/Headers"; import * as HttpServerRequest from "effect/http/HttpServerRequest"; import * as Layer from "effect/Layer"; import * as Queue from "effect/Queue"; import * as Redacted from "effect/Redacted"; -import type * as Scope from "effect/Scope"; +import * as Scope from "effect/Scope"; import * as SecureRandom from "effect/crypto/SecureRandom"; import type * as RelayDb from "../db.ts"; @@ -15,9 +16,41 @@ import * as HookForwarder from "../hooks/HookForwarder.ts"; import * as HookInbox from "../hooks/HookInbox.ts"; import * as ManagedEndpointProvider from "../environments/ManagedEndpointProvider.ts"; import * as MobileTelemetry from "../mobileTelemetry/MobileTelemetry.ts"; +import { makeManualEndpointHttpClient } from "./manualEndpointClient.ts"; import * as Ports from "./ports.ts"; import type { RelayHost } from "./RelayHost.ts"; +/** Secrets that may come from a file named by `_FILE`, as Docker and Compose secrets do. */ +export const FILE_SECRETS = [ + "DATABASE_URL", + "APNS_PRIVATE_KEY", + "APNS_DELIVERY_JOB_SIGNING_SECRET", + "FCM_SERVICE_ACCOUNT", + "CLERK_SECRET_KEY", + "T3CHAT_LINK_SECRET", + "MOBILE_TELEMETRY_TOKEN", +] as const; + +/** + * The environment with each `_FILE` secret read in as ``. Compose passes unset + * variables as empty strings, so empty counts as unset; setting both is refused as ambiguous. + */ +export const withFileSecrets = Effect.fn("relay.node.file_secrets")(function* ( + env: Readonly>, +) { + const fs = yield* FileSystem.FileSystem; + const resolved: Record = { ...env }; + for (const name of FILE_SECRETS) { + const path = env[`${name}_FILE`]?.trim(); + if (!path) continue; + if (env[name]?.trim()) { + return yield* Effect.die(`Set ${name} or ${name}_FILE, not both.`); + } + resolved[name] = (yield* fs.readFileString(path).pipe(Effect.orDie)).trim(); + } + return resolved; +}); + /** * TLS ends at the proxy, so the Node request is plain HTTP. DPoP proofs sign the public URL, * so every request is rewritten to the configured origin instead of trusting forwarded headers. @@ -35,6 +68,7 @@ export interface NodeHostOptions { readonly relayPublicOrigin: string; readonly stage: string; readonly channels?: boolean; + readonly maxEnvironmentsPerUser?: number; readonly mintKeyPair: { readonly privateKey: Redacted.Redacted; readonly publicKey: string; @@ -59,6 +93,7 @@ interface QueuedJob { // Self-hosted relay: queues and rate limits live in this process, so pending pushes do not // survive a restart. Cron supports only `*/N * * * *`, the one schedule the relay uses. const MINUTE_STEP_CRON = /^\*\/(\d+) \* \* \* \*$/; +const MAX_QUEUED_DELIVERY_JOBS = 10_000; export const fixedWindowLimit = (limit: number, periodSeconds: number) => { const windows = new Map(); @@ -163,12 +198,19 @@ const inertHookInbox = Layer.succeed(HookInbox.HookInbox, { */ export const makeNodeHost = Effect.fn("relay.node.host")(function* (options: NodeHostOptions) { const random = yield* SecureRandom.SecureRandom; - const apnsQueue = yield* Queue.unbounded(); - const fcmQueue = yield* Queue.unbounded(); + const scope = yield* Effect.scope; + // Pushes are best effort: past this backlog a new one is dropped rather than held in memory. + const apnsQueue = yield* Queue.dropping(MAX_QUEUED_DELIVERY_JOBS); + const fcmQueue = yield* Queue.dropping(MAX_QUEUED_DELIVERY_JOBS); const queueFor = (name: "apns" | "fcm") => (name === "apns" ? apnsQueue : fcmQueue); const senderFor = (queue: Queue.Queue): Ports.DeliveryQueueSender => ({ - send: (body) => Queue.offer(queue, { body, attempts: 0 }).pipe(Effect.asVoid), + send: (body) => + Queue.offer(queue, { body, attempts: 0 }).pipe( + Effect.flatMap((accepted) => + accepted ? Effect.void : Effect.logWarning("Dropping relay delivery job: queue is full"), + ), + ), }); const hookLimit = fixedWindowLimit( @@ -199,12 +241,17 @@ export const makeNodeHost = Effect.fn("relay.node.host")(function* (options: Nod apnsJobSigningSecret: Effect.succeed(apnsJobSigningSecret), managedEndpointBaseDomain: undefined, channels: options.channels ?? false, + ...(options.maxEnvironmentsPerUser === undefined + ? {} + : { maxEnvironmentsPerUser: options.maxEnvironmentsPerUser }), database: options.database, managedEndpointClients: Layer.mergeAll( Layer.succeed(ManagedEndpointProvider.ManagedEndpointTunnelClient, inertTunnelClient), Layer.succeed(ManagedEndpointProvider.ManagedEndpointDnsClient, inertDnsClient), ), hookInbox: inertHookInbox, + manualEndpointHttpClient: (policy) => + makeManualEndpointHttpClient(policy).pipe(Effect.provideService(Scope.Scope, scope)), rateLimits: { hook: hookLimit, hookEndpoint: hookEndpointLimit, diff --git a/infra/relay/src/http/Api.test.ts b/infra/relay/src/http/Api.test.ts index fa4203ff7955..8016f151e1e8 100644 --- a/infra/relay/src/http/Api.test.ts +++ b/infra/relay/src/http/Api.test.ts @@ -476,6 +476,7 @@ describe("relay environment authentication", () => { create: () => Effect.die("unused create"), authenticate: () => Effect.fail(failure), revokeForEnvironmentPublicKey: () => Effect.die("unused revoke"), + pruneRevoked: () => Effect.die("unused prune"), }; return Effect.gen(function* () { @@ -552,6 +553,7 @@ function layerRelayUnlinkTest(input?: { create: () => Effect.die("unused create"), authenticate: () => Effect.die("unused authenticate"), revokeForEnvironmentPublicKey: input?.revokeCredential ?? (() => Effect.succeed(false)), + pruneRevoked: () => Effect.die("unused prune"), }), ), Layer.succeed( diff --git a/infra/relay/src/node.ts b/infra/relay/src/node.ts index de46a4e4d418..44d0b6336826 100644 --- a/infra/relay/src/node.ts +++ b/infra/relay/src/node.ts @@ -1,5 +1,6 @@ // Self-hosted relay entrypoint. The same composition as the Cloudflare Worker (`composition.ts`), // served from Node with Postgres. See `host/node.ts` for what differs and why. +// `node node.mjs offboard --subject [--issuer ]` instead cuts one account off and exits. // @effect-diagnostics nodeBuiltinImport:off - the Node HTTP server is the platform entry point. import * as NodeHttp from "node:http"; @@ -9,27 +10,68 @@ import * as NodeServices from "@effect/platform-node/NodeServices"; import * as PgClient from "@effect/sql-pg/PgClient"; import { makeWithDefaults } from "drizzle-orm/effect-postgres"; import { migrate } from "drizzle-orm/effect-postgres/migrator"; +import * as ByteSize from "effect/ByteSize"; import * as Config from "effect/Config"; +import * as ConfigProvider from "effect/ConfigProvider"; +import * as Console from "effect/Console"; +import * as Digest from "effect/crypto/Digest"; import * as Effect from "effect/Effect"; import * as FetchHttpClient from "effect/http/FetchHttpClient"; +import * as HttpIncomingMessage from "effect/http/HttpIncomingMessage"; import * as HttpServer from "effect/http/HttpServer"; import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; +import * as Queue from "effect/Queue"; import * as Redacted from "effect/Redacted"; +import * as Schedule from "effect/Schedule"; import * as SecureRandom from "effect/crypto/SecureRandom"; import { composeRelay } from "./composition.ts"; -import { makeNodeHost, withPublicOrigin } from "./host/node.ts"; -import { makeRelayChannels } from "./host/RelayChannels.ts"; +import { positiveIntConfig } from "./Config.ts"; +import * as RelayDb from "./db.ts"; +import * as EnvironmentCredentials from "./environments/EnvironmentCredentials.ts"; +import { makeNodeHost, withFileSecrets, withPublicOrigin } from "./host/node.ts"; +import { + channelFrameBytesFor, + DEFAULT_RELAY_CHANNEL_LIMITS, + makeRelayChannels, +} from "./host/RelayChannels.ts"; +import { offboardOidcSubject, parseOffboardArgs } from "./offboard.ts"; -const program = Effect.gen(function* () { +const channelLimitsConfig = Config.all({ + maxBodyBytes: positiveIntConfig( + "RELAY_CHANNEL_MAX_BODY_BYTES", + DEFAULT_RELAY_CHANNEL_LIMITS.maxBodyBytes, + ), + maxBufferedBytes: positiveIntConfig( + "RELAY_CHANNEL_MAX_BUFFERED_BYTES", + DEFAULT_RELAY_CHANNEL_LIMITS.maxBufferedBytes, + ), + maxPendingRequests: positiveIntConfig( + "RELAY_CHANNEL_MAX_PENDING_REQUESTS", + DEFAULT_RELAY_CHANNEL_LIMITS.maxPendingRequests, + ), + maxSockets: positiveIntConfig( + "RELAY_CHANNEL_MAX_SOCKETS", + DEFAULT_RELAY_CHANNEL_LIMITS.maxSockets, + ), + maxSocketQueueBytes: positiveIntConfig( + "RELAY_CHANNEL_SOCKET_QUEUE_BYTES", + DEFAULT_RELAY_CHANNEL_LIMITS.maxSocketQueueBytes, + ), +}); + +const serve = Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; const readSecret = (path: string) => fs.readFileString(path).pipe(Effect.map((text) => text.trim())); const relayPublicOrigin = yield* Config.String("RELAY_PUBLIC_ORIGIN"); const channels = yield* Config.Boolean("RELAY_CHANNELS").pipe(Config.withDefault(false)); + const channelLimits = yield* channelLimitsConfig; + const apiMaxBodyBytes = yield* positiveIntConfig("RELAY_API_MAX_BODY_BYTES", 1024 * 1024); + const maxEnvironmentsPerUser = yield* positiveIntConfig("RELAY_MAX_ENVIRONMENTS_PER_USER", 25); const migrationsFolder = yield* Config.String("RELAY_MIGRATIONS_FOLDER").pipe( Config.withDefault("migrations/postgres"), ); @@ -56,6 +98,7 @@ const program = Effect.gen(function* () { relayPublicOrigin, stage: "selfhost", channels, + maxEnvironmentsPerUser, mintKeyPair: { privateKey: Redacted.make(mintPrivateKey), publicKey: mintPublicKey, @@ -76,10 +119,33 @@ const program = Effect.gen(function* () { // Built once: every request reuses the same services, as the Worker's per-isolate layers do. const context = yield* Layer.build(relay.runtime); const handler = yield* relay.fetch.pipe(Effect.provideContext(context)); + const relayChannels = channels ? makeRelayChannels(channelLimits) : undefined; + if (relayChannels !== undefined) { + // A revocation on any replica or from `offboard` closes the channels it covers right away. + const pg = yield* PgClient.PgClient; + yield* Effect.scoped( + Effect.gen(function* () { + const revocations = yield* pg.listen(EnvironmentCredentials.CREDENTIALS_REVOKED_CHANNEL); + yield* relayChannels.recheckAll; + return yield* Queue.take(revocations).pipe( + Effect.andThen(relayChannels.recheckAll), + Effect.forever, + ); + }), + ).pipe( + Effect.tapCause((cause) => + Effect.logWarning("Listening for credential revocations failed; retrying", { cause }), + ), + Effect.retry(Schedule.spaced("5 seconds")), + Effect.forkScoped, + ); + } yield* HttpServer.serveEffect( handler.pipe( + // The relay API takes small JSON bodies; carried environments get their own limit below. + Effect.provideService(HttpIncomingMessage.MaxBodySize, ByteSize.bytes(apiMaxBodyBytes)), // Around the relay API, so channel traffic skips its middleware and tracing. - channels ? makeRelayChannels() : (effect) => effect, + (effect) => (relayChannels === undefined ? effect : relayChannels(effect)), // Outermost: carried environments rebuild the URLs clients sign from this host, whatever // Host the reverse proxy in front of the relay sends. withPublicOrigin(relayPublicOrigin), @@ -91,23 +157,71 @@ const program = Effect.gen(function* () { return yield* Effect.never; }); +const offboard = Effect.fn("relay.node.offboard")(function* (args: { + readonly issuer: string | undefined; + readonly subject: string; +}) { + const issuer = args.issuer ?? (yield* Config.String("OIDC_ISSUER")).trim(); + const database = yield* makeWithDefaults(); + const result = yield* offboardOidcSubject({ issuer, subject: args.subject }).pipe( + Effect.provide( + Layer.mergeAll(EnvironmentCredentials.layer, RelayDb.RelayTransactions.layer).pipe( + Layer.provideMerge(Layer.succeed(RelayDb.RelayDb, database)), + Layer.provide(Digest.layerWebCrypto), + Layer.provide(SecureRandom.layerWebCrypto), + ), + ), + ); + yield* Console.log( + `Offboarded ${result.userId}: ${result.linksRevoked} links and ` + + `${result.credentialsRevoked} credentials revoked, ${result.devicesRemoved} devices and ` + + `${result.liveActivitiesRemoved} live activities removed.`, + ); +}); + +const args = process.argv.slice(2); +const offboardArgs = parseOffboardArgs(args); +const program = Effect.gen(function* () { + if (offboardArgs !== null) return yield* offboard(offboardArgs); + if (args.length > 0) { + return yield* Effect.die("Usage: node node.mjs [offboard --subject [--issuer ]]"); + } + return yield* serve; +}); + const serverLayer = Layer.unwrap( - Effect.map(Config.Int("PORT").pipe(Config.withDefault(8080)), (port) => - NodeHttpServer.layer(NodeHttp.createServer, { port, host: "0.0.0.0" }), - ), + Effect.gen(function* () { + const port = yield* Config.Int("PORT").pipe(Config.withDefault(8080)); + const { maxBodyBytes } = yield* channelLimitsConfig; + // Any single frame must fit a forwarded body, so the default follows the channel body limit. + const maxPayload = yield* positiveIntConfig( + "RELAY_WS_MAX_FRAME_BYTES", + channelFrameBytesFor(maxBodyBytes), + ); + return NodeHttpServer.layer(NodeHttp.createServer, { + port, + host: "0.0.0.0", + websocket: { maxPayload }, + }); + }), ); +// `_FILE` secrets become `` for every config read, the database URL included. +const configLayer = ConfigProvider.layer( + withFileSecrets(process.env).pipe(Effect.map((env) => ConfigProvider.fromEnvRecord(env))), +).pipe(Layer.provide(NodeServices.layer)); + NodeRuntime.runMain( program.pipe( Effect.scoped, Effect.provide( Layer.mergeAll( - serverLayer, + args.length === 0 ? serverLayer : Layer.empty, NodeServices.layer, FetchHttpClient.layer, SecureRandom.layerWebCrypto, PgClient.layerConfig({ url: Config.Redacted("DATABASE_URL") }), - ), + ).pipe(Layer.provideMerge(configLayer)), ), ), ); diff --git a/infra/relay/src/offboard.test.ts b/infra/relay/src/offboard.test.ts new file mode 100644 index 000000000000..7443efd993f1 --- /dev/null +++ b/infra/relay/src/offboard.test.ts @@ -0,0 +1,131 @@ +import { describe, expect, it } from "@effect/vitest"; +import { PgDialect } from "drizzle-orm/pg-core"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; + +import * as RelayDb from "./db.ts"; +import * as EnvironmentCredentials from "./environments/EnvironmentCredentials.ts"; +import { offboardOidcSubject, parseOffboardArgs } from "./offboard.ts"; +import { + relayEnvironmentLinks, + relayLiveActivities, + relayMobileDevices, +} from "./persistence/schema.ts"; + +const USER_ID = "oidc:https://login.example.test/v2.0|subject-1"; + +describe("offboardOidcSubject", () => { + it.effect("revokes the account's links and credentials and forgets its devices", () => { + const dialect = new PgDialect(); + const writes: Array<{ table: unknown; sql: string; params: unknown; inTransaction: boolean }> = + []; + const revokedKeys: Array = []; + let inTransaction = false; + const record = (table: unknown, condition: unknown) => { + const query = dialect.sqlToQuery(condition as never); + writes.push({ table, sql: query.sql, params: query.params, inTransaction }); + }; + const fakeDb = { + update: (table: unknown) => ({ + set: () => ({ + where: (condition: unknown) => ({ + returning: () => + Effect.sync(() => { + record(table, condition); + return [ + { environmentId: "env-1", environmentPublicKey: "key-1" }, + { environmentId: "env-2", environmentPublicKey: "key-2" }, + ]; + }), + }), + }), + }), + delete: (table: unknown) => ({ + where: (condition: unknown) => ({ + returning: () => + Effect.sync(() => { + record(table, condition); + return table === relayMobileDevices ? [{ deviceId: "d1" }] : []; + }), + }), + }), + } as unknown as RelayDb.RelayDb["Service"]; + + return Effect.gen(function* () { + const result = yield* offboardOidcSubject({ + issuer: "https://login.example.test/v2.0", + subject: "subject-1", + }); + expect(result).toEqual({ + userId: USER_ID, + linksRevoked: 2, + credentialsRevoked: 1, + devicesRemoved: 1, + liveActivitiesRemoved: 0, + }); + expect(revokedKeys).toEqual([ + { environmentId: "env-1", environmentPublicKey: "key-1", inTransaction: true }, + { environmentId: "env-2", environmentPublicKey: "key-2", inTransaction: true }, + ]); + expect(writes.map((write) => write.table)).toEqual([ + relayEnvironmentLinks, + relayMobileDevices, + relayLiveActivities, + ]); + for (const write of writes) { + expect(write.inTransaction).toBe(true); + expect(write.params).toEqual([USER_ID]); + } + expect(writes[0]?.sql).toContain('"relay_environment_links"."revoked_at" is null'); + }).pipe( + Effect.provide( + Layer.mergeAll( + Layer.succeed(RelayDb.RelayDb, fakeDb), + Layer.succeed(RelayDb.RelayTransactions, { + withTransaction: (effect) => + Effect.sync(() => { + inTransaction = true; + }).pipe( + Effect.andThen(effect), + Effect.ensuring( + Effect.sync(() => { + inTransaction = false; + }), + ), + ), + }), + Layer.succeed(EnvironmentCredentials.EnvironmentCredentials, { + create: () => Effect.die("unused"), + authenticate: () => Effect.die("unused"), + pruneRevoked: () => Effect.die("unused"), + // Another account still links env-2, so its credentials stay. + revokeForEnvironmentPublicKey: (input) => + Effect.sync(() => { + revokedKeys.push({ ...input, inTransaction }); + return input.environmentId === "env-1"; + }), + }), + ), + ), + ); + }); +}); + +describe("parseOffboardArgs", () => { + it.each([ + [["offboard", "--subject", "s"], { issuer: undefined, subject: "s" }], + [ + ["offboard", "--issuer", "https://i.example/", "--subject", "s"], + { issuer: "https://i.example/", subject: "s" }, + ], + [["offboard"], null], + [["offboard", "--issuer", "https://i.example/"], null], + [["offboard", "--subject"], null], + [["offboard", "--subject", "s", "--subject", "t"], null], + [["offboard", "--user", "s"], null], + [["serve"], null], + [[], null], + ] as const)("%j", (args, expected) => { + expect(parseOffboardArgs(args)).toEqual(expected); + }); +}); diff --git a/infra/relay/src/offboard.ts b/infra/relay/src/offboard.ts new file mode 100644 index 000000000000..445f2e96e477 --- /dev/null +++ b/infra/relay/src/offboard.ts @@ -0,0 +1,114 @@ +import { oidcAccountId } from "@t3tools/shared/oidc"; +import { and, eq, isNull } from "drizzle-orm"; +import * as DateTime from "effect/DateTime"; +import * as Effect from "effect/Effect"; +import * as Schema from "effect/Schema"; + +import * as RelayDb from "./db.ts"; +import * as EnvironmentCredentials from "./environments/EnvironmentCredentials.ts"; +import { + relayEnvironmentLinks, + relayLiveActivities, + relayMobileDevices, +} from "./persistence/schema.ts"; + +export class OffboardPersistenceError extends Schema.TaggedError()( + "OffboardPersistenceError", + { + stage: Schema.Literals([ + "transaction", + "revoke-links", + "delete-devices", + "delete-live-activities", + ]), + cause: Schema.Defect(), + }, +) { + override get message(): string { + return `Offboarding failed during '${this.stage}'`; + } +} + +export interface OffboardResult { + readonly userId: string; + readonly linksRevoked: number; + readonly credentialsRevoked: number; + readonly devicesRemoved: number; + readonly liveActivitiesRemoved: number; +} + +/** + * Cuts one OIDC account off the relay: revokes its environment links and the credentials behind + * them, which closes their channels, and forgets its devices and push tokens. Signing in again + * still works unless the identity provider stops issuing that account tokens. + */ +export const offboardOidcSubject = Effect.fn("relay.offboard_oidc_subject")(function* (input: { + readonly issuer: string; + readonly subject: string; +}) { + const db = yield* RelayDb.RelayDb; + const transactions = yield* RelayDb.RelayTransactions; + const credentials = yield* EnvironmentCredentials.EnvironmentCredentials; + const userId = oidcAccountId(input.issuer, input.subject); + const failed = (stage: OffboardPersistenceError["stage"]) => (cause: unknown) => + new OffboardPersistenceError({ stage, cause }); + + return yield* transactions + .withTransaction( + Effect.gen(function* () { + const now = DateTime.formatIso(yield* DateTime.now); + const links = yield* db + .update(relayEnvironmentLinks) + .set({ revokedAt: now, updatedAt: now }) + .where( + and(eq(relayEnvironmentLinks.userId, userId), isNull(relayEnvironmentLinks.revokedAt)), + ) + .returning({ + environmentId: relayEnvironmentLinks.environmentId, + environmentPublicKey: relayEnvironmentLinks.environmentPublicKey, + }) + .pipe(Effect.mapError(failed("revoke-links"))); + // Another account may still link the same environment key; its credentials then stay. + const revoked = yield* Effect.forEach(links, (link) => + credentials.revokeForEnvironmentPublicKey(link), + ); + const devices = yield* db + .delete(relayMobileDevices) + .where(eq(relayMobileDevices.userId, userId)) + .returning({ deviceId: relayMobileDevices.deviceId }) + .pipe(Effect.mapError(failed("delete-devices"))); + const liveActivities = yield* db + .delete(relayLiveActivities) + .where(eq(relayLiveActivities.userId, userId)) + .returning({ deviceId: relayLiveActivities.deviceId }) + .pipe(Effect.mapError(failed("delete-live-activities"))); + return { + userId, + linksRevoked: links.length, + credentialsRevoked: revoked.filter(Boolean).length, + devicesRemoved: devices.length, + liveActivitiesRemoved: liveActivities.length, + } satisfies OffboardResult; + }), + ) + .pipe(Effect.catchTags({ SqlError: (cause) => Effect.fail(failed("transaction")(cause)) })); +}); + +/** + * Reads `offboard --subject [--issuer ]`; null when the arguments are anything else. + * The issuer defaults to the relay's own, since account ids embed it exactly. + */ +export function parseOffboardArgs( + args: ReadonlyArray, +): { readonly issuer: string | undefined; readonly subject: string } | null { + if (args[0] !== "offboard") return null; + const values = new Map(); + for (let index = 1; index < args.length; index += 2) { + const name = args[index]; + const value = args[index + 1]?.trim(); + if ((name !== "--issuer" && name !== "--subject") || !value || values.has(name)) return null; + values.set(name, value); + } + const subject = values.get("--subject"); + return subject === undefined ? null : { issuer: values.get("--issuer"), subject }; +} diff --git a/packages/client-runtime/src/relay/oidcController.test.ts b/packages/client-runtime/src/relay/oidcController.test.ts index 79ab1be4e572..8f68128ee2ec 100644 --- a/packages/client-runtime/src/relay/oidcController.test.ts +++ b/packages/client-runtime/src/relay/oidcController.test.ts @@ -1,11 +1,16 @@ import { base64UrlEncode, type OidcCrypto } from "@t3tools/shared/oidc"; import { afterEach, describe, expect, it, vi } from "vite-plus/test"; -import { createOidcController, type KeyValueStore } from "./oidcController.ts"; +import { + clearStoredOidcSessions, + createOidcController, + type KeyValueStore, +} from "./oidcController.ts"; const ISSUER = "https://sso.example.com/realms/t3"; const REDIRECT_URI = "https://app.example.com/oidc/callback"; const ALICE = `oidc:${ISSUER}|alice`; +const RELAY_URL = "https://relay.example.com"; const memoryStore = (): KeyValueStore & { readonly entries: Map } => { const entries = new Map(); @@ -37,8 +42,14 @@ interface Harness { tokenReply: () => Response | Promise; } -function makeHarness(options: { readonly crypto?: OidcCrypto } = {}): Harness { - const sessions = memoryStore(); +function makeHarness( + options: { + readonly crypto?: OidcCrypto; + readonly relayUrl?: string; + readonly sessions?: ReturnType; + } = {}, +): Harness { + const { relayUrl = RELAY_URL, sessions = memoryStore(), ...overrides } = options; const pending = memoryStore(); const harness: Harness = { sessions, @@ -63,14 +74,14 @@ function makeHarness(options: { readonly crypto?: OidcCrypto } = {}): Harness { }; return Object.assign(harness, { controller: createOidcController({ - config: { issuer: ISSUER, clientId: "t3-code" }, + config: { relayUrl, issuer: ISSUER, clientId: "t3-code" }, redirectUri: REDIRECT_URI, sessions, pending, navigate: (url) => harness.navigations.push(url), now: () => harness.clock, fetch: fetchImpl as typeof fetch, - ...options, + ...overrides, }), }); } @@ -244,6 +255,9 @@ describe("tokens", () => { // What another tab's sign-in leaves in the storage the tabs share. const BOB_SESSION = { + relayUrl: RELAY_URL, + issuer: ISSUER, + clientId: "t3-code", idToken: "bob-id-token", refreshToken: "refresh-bob", expiresAtEpochMs: Number.MAX_SAFE_INTEGER, @@ -337,3 +351,50 @@ describe("tokens", () => { expect(harness.controller.getSnapshot().userId).toBeNull(); }); }); + +describe("session binding", () => { + it.each([ + ["a different relay", { relayUrl: "https://relay.attacker.example" }], + ["the same relay", {}], + ])("starts %s signed in only if the session was obtained there", async (name, options) => { + const first = makeHarness(); + await signInWith(first); + + const next = makeHarness({ ...options, sessions: first.sessions }); + + const keeps = name === "the same relay"; + expect(next.controller.getSnapshot().userId).toBe(keeps ? ALICE : null); + expect(await next.controller.getToken()).toEqual(keeps ? expect.any(String) : null); + // The other relay's refresh token must not wait in storage for a switch back. + expect(next.sessions.entries.size).toBe(keeps ? 1 : 0); + }); + + it("drops a session stored before sessions named their relay", () => { + const sessions = memoryStore(); + const legacyKey = `t3-oidc-session:${ISSUER}:t3-code`; + sessions.setItem(legacyKey, JSON.stringify({ idToken: "old", refreshToken: "old" })); + + const harness = makeHarness({ sessions }); + + expect(harness.controller.getSnapshot().userId).toBeNull(); + expect(sessions.entries.has(legacyKey)).toBe(false); + }); + + it("clears every stored session from storage the app no longer keeps them in", () => { + const entries = new Map([ + ["t3-oidc-session", "{}"], + [`t3-oidc-session:${ISSUER}:t3-code`, "{}"], + ["t3-oidc-session:https://other.example.com:web", "{}"], + ["t3-connect-self-hosted-relay", "{}"], + ]); + clearStoredOidcSessions({ + get length() { + return entries.size; + }, + key: (index) => [...entries.keys()][index] ?? null, + removeItem: (key) => void entries.delete(key), + }); + + expect([...entries.keys()]).toEqual(["t3-connect-self-hosted-relay"]); + }); +}); diff --git a/packages/client-runtime/src/relay/oidcController.ts b/packages/client-runtime/src/relay/oidcController.ts index 9800d5f8b4b3..778445b28bfb 100644 --- a/packages/client-runtime/src/relay/oidcController.ts +++ b/packages/client-runtime/src/relay/oidcController.ts @@ -23,7 +23,14 @@ export interface KeyValueStore { readonly removeItem: (key: string) => void; } -interface StoredSession { +/** A session is only valid for the relay, provider and client it was obtained for. */ +interface SessionBinding { + readonly relayUrl: string; + readonly issuer: string; + readonly clientId: string; +} + +interface StoredSession extends SessionBinding { readonly idToken: string; readonly refreshToken: string | null; readonly expiresAtEpochMs: number; @@ -44,7 +51,7 @@ export interface OidcSnapshot { } export interface OidcControllerDeps { - readonly config: { readonly issuer: string; readonly clientId: string }; + readonly config: SessionBinding; readonly redirectUri: string; /** Survives reloads and is shared between tabs. */ readonly sessions: KeyValueStore; @@ -60,6 +67,24 @@ export interface OidcControllerDeps { const SIGNED_OUT: OidcSnapshot = { userId: null, label: null }; const PENDING_KEY = "t3-oidc-pending"; +/** One key per app, so a session obtained through another relay is always found and dropped. */ +export const OIDC_SESSION_STORAGE_KEY = "t3-oidc-session"; + +/** Removes every stored session, including ones older builds keyed by provider only. */ +export function clearStoredOidcSessions(storage: { + readonly length: number; + readonly key: (index: number) => string | null; + readonly removeItem: (key: string) => void; +}): void { + const keys: Array = []; + for (let index = 0; index < storage.length; index += 1) { + const key = storage.key(index); + if (key === OIDC_SESSION_STORAGE_KEY || key?.startsWith(`${OIDC_SESSION_STORAGE_KEY}:`)) { + keys.push(key); + } + } + for (const key of keys) storage.removeItem(key); +} const parseJson = (value: string | null): A | null => { if (value === null) return null; @@ -79,10 +104,21 @@ export function createOidcController(deps: OidcControllerDeps) { const now = deps.now ?? Date.now; const fetchImpl = deps.fetch ?? fetch; const withRefreshLock = deps.withRefreshLock ?? ((run: () => Promise) => run()); - const storageKey = `t3-oidc-session:${deps.config.issuer}:${deps.config.clientId}`; + const storageKey = OIDC_SESSION_STORAGE_KEY; + const { relayUrl, issuer, clientId } = deps.config; + // Older builds keyed sessions by provider only, so nothing says which relay they were for. + deps.sessions.removeItem(`${storageKey}:${issuer}:${clientId}`); - const readSession = (): StoredSession | null => - parseJson(deps.sessions.getItem(storageKey)); + const readSession = (): StoredSession | null => { + const stored = parseJson(deps.sessions.getItem(storageKey)); + if (stored === null) return null; + if (stored.relayUrl === relayUrl && stored.issuer === issuer && stored.clientId === clientId) { + return stored; + } + // A relay switch must not hand the account's tokens to the new relay. + deps.sessions.removeItem(storageKey); + return null; + }; let session = readSession(); let signOuts = 0; const toSnapshot = (value: StoredSession | null): OidcSnapshot => @@ -105,6 +141,9 @@ export function createOidcController(deps: OidcControllerDeps) { }; const toStored = (tokens: OidcTokens): StoredSession => ({ + relayUrl, + issuer, + clientId, idToken: tokens.idToken, refreshToken: tokens.refreshToken, expiresAtEpochMs: tokens.expiresAtEpochMs, diff --git a/packages/client-runtime/src/relay/selfHostedRelay.test.ts b/packages/client-runtime/src/relay/selfHostedRelay.test.ts index 0146e42c91db..b996cb60cc21 100644 --- a/packages/client-runtime/src/relay/selfHostedRelay.test.ts +++ b/packages/client-runtime/src/relay/selfHostedRelay.test.ts @@ -1,8 +1,10 @@ import { describe, expect, it } from "vite-plus/test"; import { + canChooseSelfHostedRelay, discoverSelfHostedRelay, encodeSelfHostedRelay, + parseRelayPolicy, parseStoredSelfHostedRelay, } from "./selfHostedRelay.ts"; @@ -22,7 +24,9 @@ describe("discoverSelfHostedRelay", () => { const { requests, fetchImpl } = replying(() => Response.json({ oidc: OIDC, managedTunnels: false }), ); - await expect(discoverSelfHostedRelay(" relay.example.com/ ", fetchImpl)).resolves.toEqual({ + await expect( + discoverSelfHostedRelay(" relay.example.com/ ", { fetch: fetchImpl }), + ).resolves.toEqual({ relayUrl: "https://relay.example.com", oidcIssuer: OIDC.issuer, oidcClientId: OIDC.clientId, @@ -38,7 +42,7 @@ describe("discoverSelfHostedRelay", () => { ["relay.example.com", () => Response.json({ oidc: null, managedTunnels: true })], ])("rejects %s when the relay cannot be used", async (address, reply) => { const { fetchImpl } = replying(reply); - await expect(discoverSelfHostedRelay(address, fetchImpl)).rejects.toThrow(); + await expect(discoverSelfHostedRelay(address, { fetch: fetchImpl })).rejects.toThrow(); }); }); @@ -60,3 +64,44 @@ describe("parseStoredSelfHostedRelay", () => { ).toBeNull(); }); }); + +describe("relay policy", () => { + const relay = { + relayUrl: "https://relay.example.com", + oidcIssuer: OIDC.issuer, + oidcClientId: OIDC.clientId, + managedTunnels: false, + }; + + it.each([ + [{}, true, true], + [{ pinned: "true" }, false, false], + [{ pinned: "1", allowlist: "https://relay.example.com" }, false, false], + [{ allowlist: "https://other.example.com, https://relay.example.com/" }, true, true], + [{ allowlist: "https://other.example.com" }, true, false], + // A list with nothing usable in it fails closed instead of allowing every relay. + [{ allowlist: "http://relay.example.com" }, false, false], + ])("%j offers the choice: %s, keeps the stored relay: %s", (input, offered, kept) => { + const policy = parseRelayPolicy(input); + expect(canChooseSelfHostedRelay(policy)).toBe(offered); + expect(parseStoredSelfHostedRelay(encodeSelfHostedRelay(relay), policy)).toEqual( + kept ? relay : null, + ); + }); + + it.each([{ pinned: "true" }, { allowlist: "https://other.example.com" }])( + "refuses a relay %j does not allow before contacting it", + async (input) => { + const { requests, fetchImpl } = replying(() => + Response.json({ oidc: OIDC, managedTunnels: false }), + ); + await expect( + discoverSelfHostedRelay("relay.example.com", { + fetch: fetchImpl, + policy: parseRelayPolicy(input), + }), + ).rejects.toThrow(/only connects/u); + expect(requests).toEqual([]); + }, + ); +}); diff --git a/packages/client-runtime/src/relay/selfHostedRelay.ts b/packages/client-runtime/src/relay/selfHostedRelay.ts index cd6193fb79a9..2cffe3d4a2b4 100644 --- a/packages/client-runtime/src/relay/selfHostedRelay.ts +++ b/packages/client-runtime/src/relay/selfHostedRelay.ts @@ -14,14 +14,61 @@ export const SelfHostedRelay = Schema.Struct({ }); export type SelfHostedRelay = typeof SelfHostedRelay.Type; +/** Which relays a build lets the user choose instead of its own. */ +export interface RelayPolicy { + /** Only the build's relay; the self-hosted choice is hidden and any stored one ignored. */ + readonly pinned: boolean; + /** HTTPS origins the self-hosted choice accepts; null accepts any. */ + readonly allowedOrigins: ReadonlyArray | null; +} + +const UNRESTRICTED_RELAY_POLICY: RelayPolicy = { pinned: false, allowedOrigins: null }; + +/** + * Reads the build's `T3CODE_RELAY_PINNED` (`true`/`1`) and `T3CODE_RELAY_ALLOWLIST` (origins + * separated by commas or spaces). An allowlist with no valid origin allows none. + */ +export function parseRelayPolicy(input: { + readonly pinned?: unknown; + readonly allowlist?: unknown; +}): RelayPolicy { + const pinned = + input.pinned === true || + (typeof input.pinned === "string" && /^(?:1|true|yes)$/iu.test(input.pinned.trim())); + const entries = + typeof input.allowlist === "string" ? input.allowlist.split(/[\s,]+/u).filter(Boolean) : []; + return { + pinned, + allowedOrigins: + entries.length === 0 + ? null + : entries.flatMap((entry) => normalizeSecureRelayUrl(entry) ?? []), + }; +} + +export const canChooseSelfHostedRelay = (policy: RelayPolicy): boolean => + !policy.pinned && (policy.allowedOrigins === null || policy.allowedOrigins.length > 0); + +const isSelfHostedRelayAllowed = (policy: RelayPolicy, relayUrl: string): boolean => + canChooseSelfHostedRelay(policy) && + (policy.allowedOrigins === null || policy.allowedOrigins.includes(relayUrl)); + const decodeStoredRelay = Schema.decodeUnknownOption(Schema.fromJsonString(SelfHostedRelay)); const decodeServiceMetadata = Schema.decodeUnknownOption(RelayServiceMetadata); -/** Null for anything but a relay this module stored, so a corrupt entry falls back to the default. */ -export function parseStoredSelfHostedRelay(value: string | null): SelfHostedRelay | null { +/** + * Null for anything but a relay this module stored that the build still allows, so a corrupt or + * no longer allowed entry falls back to the build's relay. + */ +export function parseStoredSelfHostedRelay( + value: string | null, + policy: RelayPolicy = UNRESTRICTED_RELAY_POLICY, +): SelfHostedRelay | null { if (value === null) return null; const relay = Option.getOrNull(decodeStoredRelay(value)); - return relay !== null && normalizeSecureRelayUrl(relay.relayUrl) === relay.relayUrl + return relay !== null && + normalizeSecureRelayUrl(relay.relayUrl) === relay.relayUrl && + isSelfHostedRelayAllowed(policy, relay.relayUrl) ? relay : null; } @@ -31,8 +78,10 @@ export const encodeSelfHostedRelay = (relay: SelfHostedRelay): string => JSON.st /** Asks the relay at a user-entered address how to sign in, so the user only types the address. */ export async function discoverSelfHostedRelay( address: string, - fetchImpl: typeof fetch = fetch, + options: { readonly fetch?: typeof fetch; readonly policy?: RelayPolicy } = {}, ): Promise { + const fetchImpl = options.fetch ?? fetch; + const policy = options.policy ?? UNRESTRICTED_RELAY_POLICY; const trimmed = address.trim(); const relayUrl = normalizeSecureRelayUrl( /^[a-z][a-z0-9+.-]*:\/\//iu.test(trimmed) ? trimmed : `https://${trimmed}`, @@ -40,6 +89,14 @@ export async function discoverSelfHostedRelay( if (relayUrl === null) { throw new Error("Enter the relay's HTTPS address, for example https://relay.example.com."); } + // Checked before any request, so a relay outside the list never learns this app asked. + if (!isSelfHostedRelayAllowed(policy, relayUrl)) { + throw new Error( + policy.allowedOrigins === null || policy.pinned + ? "This build only connects to its own relay." + : `This build only connects to these relays: ${policy.allowedOrigins.join(", ")}.`, + ); + } const response = await fetchImpl(`${relayUrl}/.well-known/t3-relay`, { headers: { accept: "application/json" }, }).catch(() => null); diff --git a/packages/contracts/src/environmentHttp.ts b/packages/contracts/src/environmentHttp.ts index d23ec12e754a..1fe8cd943d4a 100644 --- a/packages/contracts/src/environmentHttp.ts +++ b/packages/contracts/src/environmentHttp.ts @@ -492,12 +492,12 @@ export const EnvironmentConnectReachability = Schema.Union([ ]); export type EnvironmentConnectReachability = typeof EnvironmentConnectReachability.Type; -/** "Tunnel connected · 4 connections · QUIC" for a healthy check; "Connected" for a relay channel. */ +/** "Tunnel connected · 4 connections · QUIC" for a healthy tunnel; "Relay channel connected" for a channel. */ export function formatConnectReachable( result: Extract, ): string { const count = result.readyConnections; - if (count === null && result.protocol === null) return "Connected"; + if (count === null && result.protocol === null) return "Relay channel connected"; return [ "Tunnel connected", ...(count === null ? [] : [`${count} connection${count === 1 ? "" : "s"}`]), diff --git a/packages/contracts/src/ipc.ts b/packages/contracts/src/ipc.ts index b44f8e77f239..e521e8b09a11 100644 --- a/packages/contracts/src/ipc.ts +++ b/packages/contracts/src/ipc.ts @@ -1060,6 +1060,16 @@ export interface DesktopBridge { getAppBranding: () => DesktopAppBranding | null; /** `null` until the desktop host has read the login shell's environment; ask again later. */ getRelayTelemetryEnabled: () => boolean | null; + /** The OpenID Connect session the main process keeps encrypted with the OS keychain. */ + getOidcSession: () => string | null; + /** Null deletes it. Without a keychain the session is kept in memory only. */ + setOidcSession: (session: string | null) => Promise; + /** POSTs a token request to the issuer's discovered token endpoint from the main process. */ + requestOidcToken: (input: { + readonly issuer: string; + readonly tokenEndpoint: string; + readonly body: string; + }) => Promise<{ readonly status: number; readonly body: string }>; getPathForFile: (file: File) => string; getClientPlatform: () => string; restartAudioService?: () => Promise;