Skip to content

Commit 72fc073

Browse files
juliusmarmingeshivamhwpclaude
committed
fix(server): T3 Connect links even when the host clock is off
Link proofs were dated with the host clock, so a host running ahead issued a proof from the relay's future and one running behind issued an expired proof. The proof now takes its `iat` from the relay challenge and expires 300 seconds later, falling back to host time when the challenge timestamp is unusable. The relay still verifies and consumes the challenge. Rebased onto main as one commit; the regression tests now provide the authenticated principal that linkProof requires since #19271. Co-authored-by: shivamhwp <[email protected]> Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent 05b697f commit 72fc073

2 files changed

Lines changed: 124 additions & 6 deletions

File tree

‎apps/server/src/cloud/CloudLink.lifecycle.test.ts‎

Lines changed: 114 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,10 +8,24 @@ import * as Path from "effect/Path";
88
import * as PlatformError from "effect/PlatformError";
99
import * as Schema from "effect/Schema";
1010
import * as Stream from "effect/Stream";
11-
import { HttpClient, HttpClientResponse, HttpServer, type HttpClientRequest } from "effect/http";
11+
import * as TestClock from "effect/testing/TestClock";
12+
import {
13+
HttpClient,
14+
HttpClientResponse,
15+
HttpServer,
16+
HttpServerRequest,
17+
type HttpClientRequest,
18+
} from "effect/http";
19+
import { exportPKCS8, exportSPKI, generateKeyPair } from "jose";
20+
import { RELAY_LINK_PROOF_TYP, signRelayJwt, verifyRelayJwt } from "@t3tools/shared/relayJwt";
1221
import * as NetAddress from "effect/net/NetAddress";
1322

14-
import { EnvironmentId } from "@t3tools/contracts";
23+
import {
24+
AuthSessionId,
25+
type AuthEnvironmentScope,
26+
EnvironmentAuthenticatedPrincipal,
27+
EnvironmentId,
28+
} from "@t3tools/contracts";
1529
import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts";
1630
import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
1731
import * as ServerConfigModule from "../config.ts";
@@ -41,6 +55,7 @@ import * as CloudLink from "./CloudLink.ts";
4155
import * as ConnectReachability from "./ConnectReachability.ts";
4256
import { consumeCloudReplayGuards } from "./CloudLink.ts";
4357
import { pendingServiceUpdateExists } from "./updateHandoff.ts";
58+
import { getOrCreateEnvironmentKeyPairFromSecretStore } from "./environmentKeys.ts";
4459
import { managedTunnelStartupAction } from "./managedTunnelStartup.ts";
4560
import * as ManagedEndpointRuntime from "./ManagedEndpointRuntime.ts";
4661

@@ -176,7 +191,13 @@ describe("releaseManagedTunnelOnShutdown", () => {
176191
ServerEnvironment.ServerEnvironment,
177192
ServerEnvironment.ServerEnvironment.of({
178193
getEnvironmentId: Effect.succeed(EnvironmentId.make("env_123")),
179-
getDescriptor: Effect.die("unused"),
194+
getDescriptor: Effect.succeed({
195+
environmentId: EnvironmentId.make("env_123"),
196+
label: "Test environment",
197+
platform: { os: "linux", arch: "x64" },
198+
serverVersion: "0.0.0-test",
199+
capabilities: { repositoryIdentity: true },
200+
}),
180201
}),
181202
),
182203
Effect.provideService(
@@ -241,6 +262,96 @@ describe("releaseManagedTunnelOnShutdown", () => {
241262
Effect.scoped,
242263
);
243264

265+
it.effect.each([
266+
{ direction: "ahead", skewSeconds: 600 },
267+
{ direction: "behind", skewSeconds: -600 },
268+
])(
269+
"signs a link proof accepted at relay time when the host clock is $direction",
270+
({ skewSeconds }) => {
271+
const { store } = makeMemorySecretStore();
272+
273+
return Effect.gen(function* () {
274+
const relayNow = 1_800_000_000;
275+
const relayIssuer = "https://relay.example.test";
276+
const relayKeys = yield* Effect.promise(async () => {
277+
const { privateKey, publicKey } = await generateKeyPair("EdDSA", { extractable: true });
278+
return {
279+
privateKey: await exportPKCS8(privateKey),
280+
publicKey: await exportSPKI(publicKey),
281+
};
282+
});
283+
const challenge = yield* signRelayJwt({
284+
privateKey: relayKeys.privateKey,
285+
typ: "t3-link-challenge+jwt",
286+
payload: {
287+
kind: "environment_link_challenge",
288+
iss: relayIssuer,
289+
aud: relayIssuer,
290+
sub: "user-123",
291+
jti: "challenge-jti",
292+
iat: relayNow,
293+
exp: relayNow + 300,
294+
notificationsEnabled: true,
295+
liveActivitiesEnabled: false,
296+
managedTunnelsEnabled: false,
297+
},
298+
});
299+
yield* verifyRelayJwt({
300+
publicKey: relayKeys.publicKey,
301+
token: challenge,
302+
typ: "t3-link-challenge+jwt",
303+
issuer: relayIssuer,
304+
audience: relayIssuer,
305+
nowEpochSeconds: relayNow,
306+
});
307+
308+
yield* TestClock.setTime((relayNow + skewSeconds) * 1_000);
309+
const link = yield* CloudLink.CloudLink;
310+
const proof = yield* link
311+
.linkProof(
312+
{
313+
challenge,
314+
relayIssuer,
315+
endpoint: {
316+
httpBaseUrl: "http://127.0.0.1:3773",
317+
wsBaseUrl: "ws://127.0.0.1:3773",
318+
providerKind: "manual",
319+
},
320+
origin: { localHttpHost: "127.0.0.1", localHttpPort: 3773 },
321+
},
322+
HttpServerRequest.fromWeb(
323+
new Request("http://127.0.0.1:3773/api/t3-connect/link-proof"),
324+
),
325+
)
326+
.pipe(
327+
Effect.provideService(EnvironmentAuthenticatedPrincipal, {
328+
sessionId: AuthSessionId.make("test-session"),
329+
subject: "test",
330+
method: "bearer-access-token",
331+
scopes: new Set<AuthEnvironmentScope>(),
332+
}),
333+
);
334+
const environmentKeys = yield* getOrCreateEnvironmentKeyPairFromSecretStore(store);
335+
const verified = yield* verifyRelayJwt({
336+
publicKey: environmentKeys.publicKey,
337+
token: proof,
338+
typ: RELAY_LINK_PROOF_TYP,
339+
issuer: "t3-env:env_123",
340+
audience: relayIssuer,
341+
nowEpochSeconds: relayNow,
342+
});
343+
344+
expect(verified).toMatchObject({
345+
iat: relayNow,
346+
exp: relayNow + 300,
347+
challenge,
348+
environmentId: "env_123",
349+
scopes: ["agent_activity_notifications"],
350+
});
351+
}).pipe(provideReleaseHarness({ store, applyConfigCalls: [], requests: [] }));
352+
},
353+
);
354+
244355
const managedLinkSecrets = [
245356
[CLOUD_ENDPOINT_RUNTIME_CONFIG, "runtime-config"],
246357
[CLOUD_ENDPOINT_CONFIRMED_ORIGIN, "confirmed-origin"],

‎apps/server/src/cloud/CloudLink.ts‎

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@ import {
3131
} from "@t3tools/contracts/relay";
3232
import { withRelayClientTracing } from "@t3tools/shared/relayTracing";
3333
import {
34+
decodeRelayJwt,
3435
normalizeRelayIssuer,
3536
RELAY_HEALTH_REQUEST_TYP,
3637
RELAY_HEALTH_RESPONSE_TYP,
@@ -604,16 +605,22 @@ const make = Effect.gen(function* () {
604605
return yield* new CloudLinkOriginInvalidError({ origin: "endpoint" });
605606
}
606607
const now = yield* DateTime.now;
607-
const expiresAt = DateTime.add(now, { minutes: 5 });
608608
const nowSeconds = Math.floor(now.epochMilliseconds / 1_000);
609+
// Borrow only the relay clock; the relay still verifies and consumes the challenge.
610+
const issuedAt = yield* Effect.try(() => decodeRelayJwt(request.challenge)).pipe(
611+
Effect.map(({ iat }) =>
612+
typeof iat === "number" && Number.isSafeInteger(iat) && iat > 0 ? iat : nowSeconds,
613+
),
614+
Effect.orElseSucceed(() => nowSeconds),
615+
);
609616
const descriptor = yield* environment.getDescriptor;
610617
const payload = {
611618
iss: `t3-env:${descriptor.environmentId}`,
612619
aud: normalizeRelayIssuer(request.relayIssuer),
613620
sub: descriptor.environmentId,
614621
jti: yield* crypto.randomUUIDv4(),
615-
iat: nowSeconds,
616-
exp: Math.floor(expiresAt.epochMilliseconds / 1_000),
622+
iat: issuedAt,
623+
exp: issuedAt + 5 * 60,
617624
challenge: request.challenge,
618625
descriptor,
619626
environmentId: descriptor.environmentId,

0 commit comments

Comments
 (0)