Skip to content

Commit 490a968

Browse files
committed
fix(gateway): honor pairing exemptions on reconnect
1 parent 0c54697 commit 490a968

9 files changed

Lines changed: 224 additions & 77 deletions

‎src/cli/devices-cli.runtime.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -368,7 +368,9 @@ function redactLocalPairedDevice(device: InfraPairedDevice): PairedDevice {
368368

369369
async function listPairingWithFallback(opts: DevicesRpcOpts): Promise<DevicePairingList> {
370370
try {
371-
return parseDevicePairingList(await callGatewayCli("device.pair.list", opts, {}));
371+
return parseDevicePairingList(
372+
await callGatewayCli("device.pair.list", opts, {}, { scopes: [PAIRING_SCOPE] }),
373+
);
372374
} catch (error) {
373375
const fallback = resolveLocalPairingFallback(opts, error);
374376
if (!fallback) {

‎src/cli/devices-cli.test.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -208,7 +208,7 @@ describe("devices cli approve", () => {
208208
await runDevicesApprove(["req-123"]);
209209

210210
expect(callGateway).toHaveBeenCalledTimes(2);
211-
expectGatewayCall(0, { method: "device.pair.list" });
211+
expectGatewayCall(0, { method: "device.pair.list", scopes: ["operator.pairing"] });
212212
expectGatewayCall(1, {
213213
method: "device.pair.approve",
214214
params: { requestId: "req-123" },

‎src/gateway/server.silent-scope-upgrade-reconnect.poc.test.ts‎

Lines changed: 0 additions & 46 deletions
Original file line numberDiff line numberDiff line change
@@ -202,52 +202,6 @@ describe("gateway silent scope-upgrade reconnect", () => {
202202
}
203203
});
204204

205-
test("does not let backend reconnect bypass the paired scope baseline", async () => {
206-
const started = await startServerWithClient("secret");
207-
const paired = await issueReadScopedOperatorToken({
208-
name: "backend-scope-upgrade-reconnect-poc",
209-
clientId: GATEWAY_CLIENT_NAMES.GATEWAY_CLIENT,
210-
clientMode: GATEWAY_CLIENT_MODES.BACKEND,
211-
});
212-
213-
let watcherWs: WebSocket | undefined;
214-
let backendReconnectWs: WebSocket | undefined;
215-
let requestedEvent: Promise<unknown>;
216-
217-
try {
218-
({ ws: watcherWs, requestedEvent } = await watchScopeUpgradeRequests(started.port));
219-
220-
backendReconnectWs = await openTrackedWs(started.port);
221-
const reconnectAttempt = await connectReq(backendReconnectWs, {
222-
token: "secret",
223-
deviceIdentityPath: paired.identityPath,
224-
client: {
225-
id: GATEWAY_CLIENT_NAMES.GATEWAY_CLIENT,
226-
version: "1.0.0",
227-
platform: "node",
228-
mode: GATEWAY_CLIENT_MODES.BACKEND,
229-
},
230-
role: "operator",
231-
scopes: ["operator.admin"],
232-
});
233-
expect(reconnectAttempt.ok).toBe(false);
234-
expect(reconnectAttempt.error?.message).toBe(
235-
"pairing required: device is asking for more scopes than currently approved",
236-
);
237-
238-
await expectRejectedScopeUpgradeAttempt({
239-
attempt: reconnectAttempt,
240-
requestedEvent,
241-
deviceId: paired.deviceId,
242-
token: paired.token,
243-
});
244-
} finally {
245-
watcherWs?.close();
246-
backendReconnectWs?.close();
247-
await closeStartedGateway(started);
248-
}
249-
});
250-
251205
test("keeps direct-local backend callGateway scoped calls off stale paired CLI baseline", async () => {
252206
const started = await startServerWithClient("secret");
253207
const identity = await approveReadScopedDevice({

‎src/gateway/server/ws-connection/connect-auth.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -464,7 +464,7 @@ export async function authenticateGatewayConnect(
464464
scopes = applyConnectionScopeCap({ scopes, upgradeReq });
465465
connectParams.scopes = scopes;
466466
}
467-
const skipControlUiPairingForDevice = shouldSkipControlUiPairing(
467+
const controlUiPairingKind = shouldSkipControlUiPairing(
468468
controlUiAuthPolicy,
469469
role,
470470
trustedProxyAuthOk,
@@ -510,7 +510,7 @@ export async function authenticateGatewayConnect(
510510
handoffBootstrapProfile,
511511
trustedProxyAuthOk,
512512
allowControlUiDeviceAuthMigration,
513-
skipControlUiPairingForDevice,
513+
controlUiPairingKind,
514514
skipLocalBackendSelfPairing,
515515
rejectUnauthorized,
516516
};
Lines changed: 174 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,174 @@
1+
// Gateway connect pairing tests protect session exemptions and durable device grant bounds.
2+
import { describe, expect, test } from "vitest";
3+
import {
4+
GATEWAY_CLIENT_MODES,
5+
GATEWAY_CLIENT_NAMES,
6+
} from "../../../../packages/gateway-protocol/src/client-info.js";
7+
import { replaceConfigFile } from "../../../config/config.js";
8+
import type { GatewayAuthConfig } from "../../../config/types.gateway.js";
9+
import { ensureDeviceToken, getPairedDevice } from "../../../infra/device-pairing.js";
10+
import {
11+
loadDeviceIdentity,
12+
openTrackedWs,
13+
pairDeviceIdentity,
14+
} from "../../device-authz.test-helpers.js";
15+
import { CONTROL_UI_CLIENT, openTailscaleWs } from "../../server.auth.test-helpers.js";
16+
import {
17+
connectReq,
18+
installGatewayTestHooks,
19+
startServer,
20+
startServerWithClient,
21+
testState,
22+
testTailscaleWhois,
23+
} from "../../test-helpers.js";
24+
25+
installGatewayTestHooks({ scope: "suite" });
26+
27+
await import("../../server.js");
28+
29+
const BACKEND_CLIENT = {
30+
id: GATEWAY_CLIENT_NAMES.GATEWAY_CLIENT,
31+
version: "1.0.0",
32+
platform: "node",
33+
mode: GATEWAY_CLIENT_MODES.BACKEND,
34+
} as const;
35+
36+
const TUI_CLIENT = {
37+
id: GATEWAY_CLIENT_NAMES.TUI,
38+
version: "1.0.0",
39+
platform: "test",
40+
mode: GATEWAY_CLIENT_MODES.CLI,
41+
} as const;
42+
43+
describe("gateway connect pairing exemptions", () => {
44+
test.each([
45+
{
46+
name: "local backend self-call",
47+
client: BACKEND_CLIENT,
48+
approvedScopes: ["operator.pairing"],
49+
pairingClientId: GATEWAY_CLIENT_NAMES.CLI,
50+
pairingClientMode: GATEWAY_CLIENT_MODES.CLI,
51+
},
52+
{
53+
name: "TUI operator client",
54+
client: TUI_CLIENT,
55+
approvedScopes: ["operator.read"],
56+
pairingClientId: GATEWAY_CLIENT_NAMES.TUI,
57+
pairingClientMode: GATEWAY_CLIENT_MODES.CLI,
58+
},
59+
])(
60+
"admits an auth-none $name before and after a narrower pairing row exists",
61+
async ({ name, client, approvedScopes, pairingClientId, pairingClientMode }) => {
62+
const started = await startServerWithClient(undefined, { auth: { mode: "none" } });
63+
const identityName = `auth-none-${name.replaceAll(" ", "-")}`;
64+
const loaded = loadDeviceIdentity(identityName);
65+
let pairedWs: Awaited<ReturnType<typeof openTrackedWs>> | undefined;
66+
67+
try {
68+
const unpaired = await connectReq(started.ws, {
69+
client,
70+
role: "operator",
71+
scopes: ["operator.write"],
72+
deviceIdentityPath: loaded.identityPath,
73+
skipDefaultAuth: true,
74+
prePairDevice: false,
75+
});
76+
expect(unpaired.ok, JSON.stringify(unpaired)).toBe(true);
77+
started.ws.close();
78+
79+
await pairDeviceIdentity({
80+
name: identityName,
81+
role: "operator",
82+
scopes: approvedScopes,
83+
clientId: pairingClientId,
84+
clientMode: pairingClientMode,
85+
});
86+
const tokenBefore = await ensureDeviceToken({
87+
deviceId: loaded.identity.deviceId,
88+
role: "operator",
89+
scopes: approvedScopes,
90+
});
91+
expect(tokenBefore?.scopes).toEqual(approvedScopes);
92+
93+
pairedWs = await openTrackedWs(started.port);
94+
const pairedConnect = await connectReq(pairedWs, {
95+
client,
96+
role: "operator",
97+
scopes: ["operator.write"],
98+
deviceIdentityPath: loaded.identityPath,
99+
skipDefaultAuth: true,
100+
prePairDevice: false,
101+
});
102+
expect(pairedConnect.ok, JSON.stringify(pairedConnect)).toBe(true);
103+
104+
const paired = await getPairedDevice(loaded.identity.deviceId);
105+
expect(paired?.approvedScopes).toEqual(approvedScopes);
106+
expect(paired?.tokens?.operator).toMatchObject({
107+
token: tokenBefore?.token,
108+
scopes: approvedScopes,
109+
});
110+
expect(paired?.lastSeenReason).toBe("connect");
111+
} finally {
112+
pairedWs?.close();
113+
started.ws.close();
114+
await started.server.close();
115+
started.envSnapshot.restore();
116+
}
117+
},
118+
);
119+
120+
test("keeps a narrow pairing row as the Tailscale Control UI scope cap", async () => {
121+
const tailscaleOrigin = "https://gateway.tailnet.ts.net";
122+
const auth = {
123+
mode: "token",
124+
token: "secret",
125+
allowTailscale: true,
126+
} satisfies GatewayAuthConfig;
127+
testState.gatewayAuth = auth;
128+
testState.gatewayControlUi = { allowedOrigins: [tailscaleOrigin] };
129+
testTailscaleWhois.value = { login: "peter", name: "Peter" };
130+
await replaceConfigFile({
131+
nextConfig: {
132+
gateway: {
133+
auth,
134+
controlUi: { allowedOrigins: [tailscaleOrigin] },
135+
},
136+
},
137+
afterWrite: { mode: "auto" },
138+
});
139+
const started = await startServer(undefined, { auth, controlUiEnabled: true });
140+
const identityName = "tailscale-control-ui-scope-cap";
141+
const paired = await pairDeviceIdentity({
142+
name: identityName,
143+
role: "operator",
144+
scopes: ["operator.read"],
145+
clientId: CONTROL_UI_CLIENT.id,
146+
clientMode: CONTROL_UI_CLIENT.mode,
147+
});
148+
let ws: Awaited<ReturnType<typeof openTailscaleWs>> | undefined;
149+
150+
try {
151+
ws = await openTailscaleWs(started.port, { origin: tailscaleOrigin });
152+
const response = await connectReq(ws, {
153+
skipDefaultAuth: true,
154+
prePairDevice: false,
155+
scopes: ["operator.write"],
156+
client: CONTROL_UI_CLIENT,
157+
deviceIdentityPath: paired.identityPath,
158+
});
159+
expect(response.ok).toBe(false);
160+
expect(response.error?.details).toMatchObject({
161+
reason: "scope-upgrade",
162+
approvedScopes: ["operator.read"],
163+
});
164+
expect((await getPairedDevice(paired.identity.deviceId))?.approvedScopes).toEqual([
165+
"operator.read",
166+
]);
167+
} finally {
168+
ws?.close();
169+
await started.server.close();
170+
started.envSnapshot.restore();
171+
testTailscaleWhois.value = null;
172+
}
173+
});
174+
});

‎src/gateway/server/ws-connection/connect-device-pairing.ts‎

Lines changed: 22 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ import {
2121
listDevicePairing,
2222
requestDevicePairing,
2323
resolveEffectiveOperatorDeviceIdentity,
24+
updatePairedDeviceMetadata,
2425
} from "../../../infra/device-pairing.js";
2526
import {
2627
resolveBootstrapProfileScopesForRole,
@@ -121,7 +122,7 @@ export async function authorizeGatewayConnectDevice(
121122
bootstrapTokenCandidate,
122123
pairingLocality,
123124
skipLocalBackendSelfPairing,
124-
skipControlUiPairingForDevice,
125+
controlUiPairingKind,
125126
allowControlUiDeviceAuthMigration,
126127
} = state;
127128
let hasServerApprovedDeviceTokenBaseline = false;
@@ -631,8 +632,25 @@ export async function authorizeGatewayConnectDevice(
631632

632633
const paired = await getPairedDevice(device.id);
633634
const isPaired = paired?.publicKey === devicePublicKey;
634-
if (!isPaired) {
635-
if (!(skipLocalBackendSelfPairing || skipControlUiPairingForDevice)) {
635+
const pairingRecordDoesNotAuthorizeSession =
636+
skipLocalBackendSelfPairing || controlUiPairingKind === "auth-none";
637+
if (pairingRecordDoesNotAuthorizeSession) {
638+
if (isPaired) {
639+
// Locality plus auth mode authorizes this session; the pairing row only
640+
// bounds durable grants and owns last-seen diagnostics. Reapplying its
641+
// scope cap here would make an unrelated narrow row deny local access.
642+
pairedClientId = paired.clientId;
643+
pairedBrowserOrigin = paired.browserOrigin;
644+
hasServerApprovedDeviceTokenBaseline = true;
645+
await updatePairedDeviceMetadata(device.id, clientAccessMetadata);
646+
} else if (
647+
controlUiPairingKind === "auth-none" ||
648+
(skipLocalBackendSelfPairing && authMethod !== "device-token")
649+
) {
650+
hasServerApprovedDeviceTokenBaseline = true;
651+
}
652+
} else if (!isPaired) {
653+
if (controlUiPairingKind === null) {
636654
const ok = await requirePairing("not-paired", paired);
637655
if (!ok) {
638656
return undefined;
@@ -647,10 +665,7 @@ export async function authorizeGatewayConnectDevice(
647665
: undefined;
648666
hasServerApprovedDeviceTokenBaseline = true;
649667
}
650-
} else if (
651-
skipControlUiPairingForDevice ||
652-
(skipLocalBackendSelfPairing && authMethod !== "device-token")
653-
) {
668+
} else {
654669
hasServerApprovedDeviceTokenBaseline = true;
655670
}
656671
} else {

‎src/gateway/server/ws-connection/connect-policy.test.ts‎

Lines changed: 14 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -61,7 +61,7 @@ function expectMissingDeviceDecision(
6161
function expectSkipPairing(
6262
policy: Parameters<typeof shouldSkipControlUiPairing>[0],
6363
role: PairingRole,
64-
expected: boolean,
64+
expected: ReturnType<typeof shouldSkipControlUiPairing>,
6565
params: {
6666
pairingComplete?: boolean;
6767
authMode?: PairingAuthMode;
@@ -272,26 +272,26 @@ describe("ws connect policy", () => {
272272
test("strict control-ui policy does not skip pairing", () => {
273273
const strict = authPolicy({ isControlUi: true });
274274

275-
expectSkipPairing(strict, "node", false);
276-
expectSkipPairing(strict, "operator", false);
277-
expectSkipPairing(strict, "operator", false, { pairingComplete: true });
275+
expectSkipPairing(strict, "node", null);
276+
expectSkipPairing(strict, "operator", null);
277+
expectSkipPairing(strict, "operator", null, { pairingComplete: true });
278278
});
279279

280280
test("auth.mode=none skips pairing for operator control-ui only", () => {
281281
const controlUi = authPolicy({ isControlUi: true });
282282
const nonControlUi = authPolicy();
283283

284284
// Control UI + operator + auth.mode=none: skip pairing (the fix for #42931)
285-
expectSkipPairing(controlUi, "operator", true, { authMode: "none" });
285+
expectSkipPairing(controlUi, "operator", "auth-none", { authMode: "none" });
286286
// Control UI + node role + auth.mode=none: still require pairing
287-
expectSkipPairing(controlUi, "node", false, { authMode: "none" });
287+
expectSkipPairing(controlUi, "node", null, { authMode: "none" });
288288
// Non-Control-UI + operator + auth.mode=none: still require pairing
289289
// (prevents #43478 regression where ALL clients bypassed pairing)
290-
expectSkipPairing(nonControlUi, "operator", false, { authMode: "none" });
290+
expectSkipPairing(nonControlUi, "operator", null, { authMode: "none" });
291291
// Control UI + operator + auth.mode=shared-key: no change
292-
expectSkipPairing(controlUi, "operator", false, { authMode: "shared-key" });
292+
expectSkipPairing(controlUi, "operator", null, { authMode: "shared-key" });
293293
// Control UI + operator + no authMode: no change
294-
expectSkipPairing(controlUi, "operator", false);
294+
expectSkipPairing(controlUi, "operator", null);
295295
});
296296

297297
test("tailscale auth skips pairing only for operator control-ui with device identity", () => {
@@ -305,23 +305,23 @@ describe("ws connect policy", () => {
305305
deviceRaw: device,
306306
});
307307

308-
expectSkipPairing(controlUiWithDevice, "operator", true, {
308+
expectSkipPairing(controlUiWithDevice, "operator", "tailscale-device", {
309309
authMode: "token",
310310
authMethod: "tailscale",
311311
});
312-
expectSkipPairing(controlUiWithoutDevice, "operator", false, {
312+
expectSkipPairing(controlUiWithoutDevice, "operator", null, {
313313
authMode: "token",
314314
authMethod: "tailscale",
315315
});
316-
expectSkipPairing(controlUiWithDevice, "node", false, {
316+
expectSkipPairing(controlUiWithDevice, "node", null, {
317317
authMode: "token",
318318
authMethod: "tailscale",
319319
});
320-
expectSkipPairing(nonControlUiWithDevice, "operator", false, {
320+
expectSkipPairing(nonControlUiWithDevice, "operator", null, {
321321
authMode: "token",
322322
authMethod: "tailscale",
323323
});
324-
expectSkipPairing(controlUiWithDevice, "operator", false, {
324+
expectSkipPairing(controlUiWithDevice, "operator", null, {
325325
authMode: "token",
326326
authMethod: "token",
327327
});

0 commit comments

Comments
 (0)