Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions apps/desktop/src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,7 @@ const layerDesktopSshEnvironment = Layer.unwrap(
const environment = yield* DesktopEnvironment.DesktopEnvironment;
return DesktopSshEnvironment.layer({
resolveCliRunner: Effect.succeed(resolveDesktopSshCliRunner(environment)),
controlSocketDirectory: environment.path.join(environment.stateDir, "ssh-control"),
});
}),
);
Expand Down
12 changes: 2 additions & 10 deletions apps/desktop/src/ssh/DesktopSshEnvironment.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,9 +67,7 @@ export class DesktopSshEnvironment extends Context.Service<
}
>()("@t3tools/desktop/ssh/DesktopSshEnvironment") {}

export interface DesktopSshEnvironmentLayerOptions {
readonly resolveCliRunner?: Effect.Effect<SshTunnel.RemoteT3RunnerOptions>;
}
export type DesktopSshEnvironmentLayerOptions = SshTunnel.SshEnvironmentManagerOptions;

function discoverDesktopSshHostsEffect(input?: { readonly homeDir?: string }) {
return discoverSshHosts(input ?? {});
Expand Down Expand Up @@ -161,11 +159,5 @@ export const make = Effect.gen(function* () {

export const layer = (options: DesktopSshEnvironmentLayerOptions = {}) =>
Layer.effect(DesktopSshEnvironment, make).pipe(
Layer.provide(
SshTunnel.SshEnvironmentManager.layer(
options.resolveCliRunner === undefined
? {}
: { resolveCliRunner: options.resolveCliRunner },
),
),
Layer.provide(SshTunnel.SshEnvironmentManager.layer(options)),
);
9 changes: 7 additions & 2 deletions apps/web/src/connection/platform.ts
Original file line number Diff line number Diff line change
Expand Up @@ -262,6 +262,7 @@ export const provisionDesktopSshEnvironment = Effect.fn(
label: descriptor.label,
bootstrap,
bearerToken: access.access_token,
descriptor,
};
});

Expand Down Expand Up @@ -302,15 +303,19 @@ export const prepareDesktopSshEnvironment = Effect.fn("web.connectionPlatform.ss
session.authenticated &&
AuthStandardClientScopes.every((scope) => granted.includes(scope))
) {
return { bootstrap, bearerToken };
return { bootstrap, bearerToken, descriptor };
}
}
const provisioned = yield* provisionDesktopSshEnvironment(
bridge,
input.target,
input.expectedEnvironmentId,
);
return { bootstrap: provisioned.bootstrap, bearerToken: provisioned.bearerToken };
return {
bootstrap: provisioned.bootstrap,
bearerToken: provisioned.bearerToken,
descriptor: provisioned.descriptor,
};
},
);

Expand Down
16 changes: 16 additions & 0 deletions docs/internals/remote.md
Original file line number Diff line number Diff line change
Expand Up @@ -176,6 +176,22 @@ runner never stops a server, since agent turns may be running there; an update
stops it and the next connect starts the client's version. Reconnection restores
the forward before opening the application transport.

Each new SSH connection costs several round trips, which is seconds on a slow
link, so each tunnel is one supervised control master (`ssh -M -N`), and its
launch, port forward (`-O forward`), pairing, and disconnect run over it. Explicit
options override the user's `ControlMaster` and `ControlPersist`, which otherwise
hand the forward to another master and exit (upstream #3533), and the commands
over it set `ProxyCommand=false`, so a dead master fails them instead of letting
them connect on their own. The master's socket gets a fresh name per tunnel, so a
replacement for a slow tunnel never joins the master it may be replacing, and
sockets a crashed app left behind get `-O exit` before the first new one. ssh
binds the socket at its path plus 17 characters, inside macOS's 104-byte limit,
so a path that cannot fit, Windows (whose OpenSSH has no multiplexing), and a
master that cannot create its socket all fall back to one connection per command.
The supervisor's 15-second setup budget stops while an SSH route is being
prepared: desktop main bounds every SSH step and request in it, and a launch over
a slow link or a first install takes far longer than 15 seconds.

Remote servers can outlive several client releases. Clients must use advertised
capabilities and handle their absence, rather than assume their own version
describes the server. Process replacement belongs to the launcher's
Expand Down
5 changes: 5 additions & 0 deletions docs/user/remote-access.md
Original file line number Diff line number Diff line change
Expand Up @@ -237,6 +237,11 @@ neither answers, it keeps the first connection and tries again. When the old
connection has clearly closed, for example after your computer sleeps, it is
replaced right away.

T3 Code sets up the host and its port forward over a single SSH connection, so
a slow link pays for the SSH handshake once. It keeps its own shared connection
and does not use `ControlMaster` settings from your SSH config. On Windows each
step opens its own connection.

Each desktop app keeps one session on the host for its SSH connection and reuses
it when it reconnects. Revoke sessions you no longer use in **Settings →
Sharing & access** on the host, or on a headless host with `t3 auth session list` and
Expand Down
37 changes: 37 additions & 0 deletions packages/client-runtime/src/authorization/layer.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -378,6 +378,43 @@ describe("RemoteEnvironmentAuthorization", () => {
}),
);

it.effect("authorizes over SSH without reading the descriptor the desktop just read", () =>
Effect.gen(function* () {
const descriptor = {
...DESCRIPTOR,
orchestrationProtocolVersion: ORCHESTRATION_PROTOCOL_VERSION,
} as ExecutionEnvironmentDescriptor;
const harness = yield* makeHarness({
responses: [
websocketTicket("forwarded"),
Response.json(descriptor),
websocketTicket("checked"),
],
});
yield* Effect.gen(function* () {
const remote = yield* RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization;
const authorize = (verifiedDescriptor: ExecutionEnvironmentDescriptor) =>
remote.authorizeBearer({
expectedEnvironmentId: ENVIRONMENT_ID,
httpBaseUrl: "http://127.0.0.1:41773",
wsBaseUrl: "ws://127.0.0.1:41773",
bearerToken: "bearer-token",
connectionMethod: "ssh",
verifiedDescriptor,
});
yield* authorize(descriptor);
// One for another environment proves nothing, so it reads again.
yield* authorize({ ...descriptor, environmentId: "other" as never });
}).pipe(Effect.provide(harness.layer));

expect(harness.fetch.calls.map(([url]) => new URL(String(url)).pathname)).toEqual([
"/api/auth/websocket-ticket/rpc",
"/.well-known/t3/environment",
"/api/auth/websocket-ticket/rpc",
]);
}),
);

it.effect("blocks a warm direct bearer prepare when the environment changes identity", () =>
Effect.gen(function* () {
const harness = yield* makeHarness({
Expand Down
11 changes: 10 additions & 1 deletion packages/client-runtime/src/authorization/service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,11 @@ export class RemoteEnvironmentAuthorization extends Context.Service<
readonly wsBaseUrl: string;
readonly bearerToken: string;
readonly connectionMethod: ClientConnectionMethod;
/**
* A descriptor this client read from the same endpoint moment ago over a route it
* controls, such as its own SSH forward, which saves reading it again.
*/
readonly verifiedDescriptor?: ExecutionEnvironmentDescriptor;
}) => Effect.Effect<AuthorizedRemoteEnvironment, ConnectionAttemptError>;
readonly authorizeDpop: (input: {
readonly expectedEnvironmentId: EnvironmentId;
Expand Down Expand Up @@ -189,8 +194,12 @@ export const make = Effect.gen(function* () {
readonly wsBaseUrl: string;
readonly bearerToken: string;
readonly connectionMethod: ClientConnectionMethod;
readonly verifiedDescriptor?: ExecutionEnvironmentDescriptor;
}) {
const descriptor = yield* verifyDirectEndpoint(input);
const descriptor =
input.verifiedDescriptor?.environmentId === input.expectedEnvironmentId
? input.verifiedDescriptor
: yield* verifyDirectEndpoint(input);
const socketUrl = yield* resolveRemoteWebSocketConnectionUrl({
wsBaseUrl: input.wsBaseUrl,
httpBaseUrl: input.httpBaseUrl,
Expand Down
3 changes: 3 additions & 0 deletions packages/client-runtime/src/connection/driver.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,8 @@ import { fetchRemoteEnvironmentDescriptor } from "../environment/descriptor.ts";
export type ConnectionDriverProgress =
| {
readonly stage: "preparing";
/** The route about to be prepared; absent before any route is chosen. */
readonly route?: ConnectionRoute;
}
| {
readonly stage: Exclude<ConnectionAttemptStage, "preparing">;
Expand Down Expand Up @@ -199,6 +201,7 @@ export const make = Effect.gen(function* () {
entry,
(route) => checkRoute(entry, route),
Effect.fnUntraced(function* (route) {
yield* reportProgress({ stage: "preparing", route });
const prepared = yield* resolver.prepare(routeEntry(entry, route));
yield* reportProgress({ stage: "opening", prepared });
const session = yield* sessions.connect(prepared);
Expand Down
1 change: 1 addition & 0 deletions packages/client-runtime/src/connection/resolver.ts
Original file line number Diff line number Diff line change
Expand Up @@ -258,6 +258,7 @@ const makeSshBroker = Effect.fn("clientRuntime.connection.broker.makeSsh")(funct
wsBaseUrl: prepared.bootstrap.wsBaseUrl,
bearerToken: prepared.bearerToken,
connectionMethod: "ssh",
...(prepared.descriptor === undefined ? {} : { verifiedDescriptor: prepared.descriptor }),
});
return {
...authorized,
Expand Down
52 changes: 49 additions & 3 deletions packages/client-runtime/src/connection/supervisor.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ import {
ConnectionTransientError,
PrimaryConnectionTarget,
RelayConnectionTarget,
SshConnectionTarget,
type ConnectionAttemptError,
type ConnectionTarget,
type NetworkStatus,
Expand Down Expand Up @@ -68,6 +69,16 @@ const RELAY_ENTRY: ConnectionCatalogEntry = {
enabled: true,
};

const SSH_ENTRY: ConnectionCatalogEntry = {
target: new SshConnectionTarget({
environmentId: TARGET.environmentId,
label: TARGET.label,
connectionId: "ssh:devbox",
}),
profile: Option.none(),
enabled: true,
};

const PREPARED_CONNECTION: PreparedConnection = {
environmentId: TARGET.environmentId,
label: TARGET.label,
Expand Down Expand Up @@ -191,10 +202,11 @@ const makeHarness = Effect.fn("TestConnectionHarness.make")(function* (options?:
options?.checkRoute?.(route) ?? Effect.succeed<ConnectionDriver.RouteCheck>("unchecked");

const connectRoute = Effect.fn("TestConnectionDriver.connectRoute")(function* (
target: ConnectionTarget,
route: ConnectionRoute,
reportProgress: (progress: ConnectionDriver.ConnectionDriverProgress) => Effect.Effect<void>,
) {
const prepared = yield* prepare(target);
yield* reportProgress({ stage: "preparing", route });
const prepared = yield* prepare(route.target);
yield* reportProgress({ stage: "opening", prepared });

const attempt = yield* Ref.updateAndGet(sessionCount, (count) => count + 1);
Expand Down Expand Up @@ -233,7 +245,7 @@ const makeHarness = Effect.fn("TestConnectionHarness.make")(function* (options?:
) {
yield* reportProgress({ stage: "preparing" });
return yield* ConnectionDriver.connectOverRoutes(entry, checkRoute, (route) =>
connectRoute(route.target, reportProgress),
connectRoute(route, reportProgress),
);
});

Expand Down Expand Up @@ -556,6 +568,40 @@ describe("EnvironmentSupervisor", () => {
}).pipe(Effect.provide(TestClock.layer())),
);

it.effect("does not count preparing an SSH route against the setup timeout", () =>
Effect.gen(function* () {
const prepareStarted = yield* Deferred.make<void>();
const tunnelReady = yield* Deferred.make<void>();
const harness = yield* makeHarness({
prepare: (_attempt, target) =>
Deferred.succeed(prepareStarted, undefined).pipe(
Effect.andThen(Deferred.await(tunnelReady)),
Effect.as(preparedFor(target)),
),
ready: () => Effect.never,
});
const supervisor = yield* EnvironmentSupervisor.make(SSH_ENTRY, {
initiallyDesired: true,
}).pipe(Effect.provide(harness.dependencies));

// A cold launch over a slow link outlasts the 15-second setup budget.
yield* Deferred.await(prepareStarted);
yield* TestClock.adjust("60 seconds");
yield* Deferred.succeed(tunnelReady, undefined);
const settled = yield* awaitState(
supervisor.state,
(state) => state.phase === "backoff" || state.stage === "synchronizing",
);
expect(settled).toMatchObject({ phase: "connecting", stage: "synchronizing", attempt: 1 });

// Once prepared, the session still has only its usual budget.
yield* TestClock.adjust("90 seconds");
const timedOut = yield* awaitState(supervisor.state, (state) => state.phase === "backoff");
expect(timedOut).toMatchObject({ attempt: 1, lastFailure: { reason: "timeout" } });
expect(yield* Ref.get(harness.prepareCount)).toBe(1);
}).pipe(Effect.provide(TestClock.layer())),
);

it.effect("treats an involuntary session close as transient and reconnects", () =>
Effect.gen(function* () {
const harness = yield* makeHarness();
Expand Down
Loading
Loading