Skip to content

Commit 3caf21b

Browse files
authored
refactor(gateway): consolidate pairing approval ownership (#129744)
The approval plan now owns the whole trusted-proxy auto-approval decision — eligibility and the capped grant — returning trustedProxyAutoApproveScopes/trustedProxyUser instead of a bare flag that requirePairing re-derived from config. One failPairingHandshake helper replaces three hand-rolled failure blocks, and the bootstrap retry block in connect-existing-device flattens its guard pyramid and computes scopes only where used. Behavior-neutral; net -20 production LOC.
1 parent a9303f2 commit 3caf21b

3 files changed

Lines changed: 100 additions & 120 deletions

File tree

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

Lines changed: 58 additions & 84 deletions
Original file line numberDiff line numberDiff line change
@@ -42,10 +42,7 @@ import {
4242
import { issueGatewayConnectDeviceTokens } from "./connect-device-tokens.js";
4343
import { authorizeExistingGatewayDevice } from "./connect-existing-device.js";
4444
import { startGatewayNodePairingSshApproval } from "./connect-node-pairing-ssh.js";
45-
import {
46-
resolvePairingApprovalPlan,
47-
resolveTrustedProxyDeviceAutoApproveScopes,
48-
} from "./connect-pairing-approval-plan.js";
45+
import { resolvePairingApprovalPlan } from "./connect-pairing-approval-plan.js";
4946
import type {
5047
AuthenticatedGatewayConnect,
5148
DeviceAuthorizedGatewayConnect,
@@ -86,18 +83,29 @@ export async function authorizeGatewayConnectDevice(
8683
skipLocalBackendSelfPairing,
8784
controlUiPairingKind,
8885
} = state;
89-
const roleConfiguredHumanOperator = role === "operator" && Boolean(configSnapshot.gateway?.roles);
90-
const sharedSecretOwner = authMethod === "token" || authMethod === "password";
91-
if (roleConfiguredHumanOperator && !sharedSecretOwner && !authResult.user?.trim()) {
92-
const message = "operator role policies require a verified user identity";
86+
const failPairingHandshake = (params: {
87+
message: string;
88+
details?: ReturnType<typeof buildPairingConnectErrorDetails>;
89+
closeCause?: { cause: string; meta: Record<string, unknown> };
90+
closeReason?: string;
91+
}) => {
92+
const { message, details, closeCause, closeReason } = params;
9393
setHandshakeState("failed");
94+
if (closeCause) {
95+
setCloseCause(closeCause.cause, closeCause.meta);
96+
}
9497
send({
9598
type: "res",
9699
id: frame.id,
97100
ok: false,
98-
error: errorShape(ErrorCodes.NOT_PAIRED, message),
101+
error: errorShape(ErrorCodes.NOT_PAIRED, message, details ? { details } : undefined),
99102
});
100-
close(1008, truncateCloseReason(message));
103+
close(1008, truncateCloseReason(closeReason ?? message));
104+
};
105+
const roleConfiguredHumanOperator = role === "operator" && Boolean(configSnapshot.gateway?.roles);
106+
const sharedSecretOwner = authMethod === "token" || authMethod === "password";
107+
if (roleConfiguredHumanOperator && !sharedSecretOwner && !authResult.user?.trim()) {
108+
failPairingHandshake({ message: "operator role policies require a verified user identity" });
101109
return undefined;
102110
}
103111
let hasServerApprovedDeviceTokenBaseline = false;
@@ -143,19 +151,14 @@ export async function authorizeGatewayConnectDevice(
143151
const pairingStateAllowsRequestedAccess = (
144152
pairedCandidate: Awaited<ReturnType<typeof getPairedDevice>>,
145153
requestedScopes = scopes,
146-
): boolean => {
147-
if (!pairedCandidate || pairedCandidate.publicKey !== devicePublicKey) {
148-
return false;
149-
}
150-
if (!hasEffectivePairedDeviceRole(pairedCandidate, role)) {
151-
return false;
152-
}
153-
return roleScopesAllow({
154+
): boolean =>
155+
pairedCandidate?.publicKey === devicePublicKey &&
156+
hasEffectivePairedDeviceRole(pairedCandidate, role) &&
157+
roleScopesAllow({
154158
role,
155159
requestedScopes,
156160
allowedScopes: resolvePairedAccessScopes(pairedCandidate),
157161
});
158-
};
159162
const plan = await resolvePairingApprovalPlan({
160163
reason,
161164
existingPairedDevice,
@@ -168,25 +171,15 @@ export async function authorizeGatewayConnectDevice(
168171
deviceId: device.id,
169172
devicePublicKey,
170173
scopes,
174+
hasRequestedScopes,
175+
connectionScopeCap: (capped) =>
176+
applyConnectionScopeCap({ scopes: capped, upgradeReq: context.handler.upgradeReq }),
171177
});
172-
const trustedProxyAutoApproveConfig =
173-
configSnapshot.gateway?.auth?.trustedProxy?.deviceAutoApprove;
174-
const trustedProxyUser = authResult.user?.trim();
175-
const trustedProxyAutoApproveScopes = plan.allowTrustedProxyDeviceAutoApproval
176-
? applyConnectionScopeCap({
177-
scopes: resolveTrustedProxyDeviceAutoApproveScopes({
178-
requestedScopes: scopes,
179-
hasRequestedScopes,
180-
configuredScopes: trustedProxyAutoApproveConfig?.scopes,
181-
}),
182-
upgradeReq: context.handler.upgradeReq,
183-
})
184-
: null;
185178
// Same-key reconnects reuse paired grants without pairing or false upgrade audits.
186179
if (
187180
reason === "scope-upgrade" &&
188181
plan.isTrustedProxySameKeyUpgrade &&
189-
trustedProxyAutoApproveScopes !== null
182+
plan.trustedProxyAutoApproveScopes !== null
190183
) {
191184
// Authority is the live row, not the pre-plan snapshot: a revoke, key
192185
// replacement, or grant reduction landing during the plan await must
@@ -195,11 +188,11 @@ export async function authorizeGatewayConnectDevice(
195188
const livePaired = await getPairedDevice(device.id);
196189
if (
197190
livePaired &&
198-
pairingStateAllowsRequestedAccess(livePaired, trustedProxyAutoApproveScopes)
191+
pairingStateAllowsRequestedAccess(livePaired, plan.trustedProxyAutoApproveScopes)
199192
) {
200193
const livePairedScopes = resolvePairedAccessScopes(livePaired);
201194
scopes = normalizeSortedUniqueTrimmedStringList(
202-
[...scopes, ...trustedProxyAutoApproveScopes].filter((scope) =>
195+
[...scopes, ...plan.trustedProxyAutoApproveScopes].filter((scope) =>
203196
roleScopesAllow({ role, requestedScopes: [scope], allowedScopes: livePairedScopes }),
204197
),
205198
);
@@ -229,7 +222,7 @@ export async function authorizeGatewayConnectDevice(
229222
});
230223
const trustedProxyApprovalScopes =
231224
pairing.request.isRepair !== true || plan.isTrustedProxySameKeyUpgrade
232-
? trustedProxyAutoApproveScopes
225+
? plan.trustedProxyAutoApproveScopes
233226
: null;
234227
const requestContext = buildRequestContext();
235228
// A replacement request obsoletes older pending requestIds; tell approval
@@ -305,9 +298,9 @@ export async function authorizeGatewayConnectDevice(
305298
if (plan.bootstrapApprovalProfile) {
306299
handoffBootstrapProfile = plan.bootstrapApprovalProfile;
307300
}
308-
if (trustedProxyApprovalScopes !== null && trustedProxyUser) {
301+
if (trustedProxyApprovalScopes !== null && plan.trustedProxyUser) {
309302
logGateway.warn(
310-
`security audit: trusted-proxy browser device auto-approved user=${formatForLog(trustedProxyUser)} device=${formatForLog(approved.device.deviceId.slice(0, 12))} scopes=${formatAuditList(scopes)}`,
303+
`security audit: trusted-proxy browser device auto-approved user=${formatForLog(plan.trustedProxyUser)} device=${formatForLog(approved.device.deviceId.slice(0, 12))} scopes=${formatAuditList(scopes)}`,
311304
);
312305
} else {
313306
logGateway.info(
@@ -401,46 +394,34 @@ export async function authorizeGatewayConnectDevice(
401394
// pairing-required behavior pauses the client reconnect loop.
402395
const retryWhileDetachedApprovalPending =
403396
retryAfterBootstrapPairingApproval || sshVerifyStarted;
404-
const pairingErrorDetails = buildPairingConnectErrorDetails({
405-
reason,
406-
requestId: recoveryRequestId,
407-
...(retryWhileDetachedApprovalPending
408-
? {
409-
recommendedNextStep: "wait_then_retry",
410-
retryable: true,
411-
pauseReconnect: false,
412-
}
413-
: {}),
414-
deviceId: device.id,
415-
requestedRole: role,
416-
requestedScopes: scopes,
417-
...(approvedRoles.length > 0 ? { approvedRoles } : {}),
418-
...(approvedScopes.length > 0 ? { approvedScopes } : {}),
419-
});
420-
const pairingErrorMessage = buildPairingConnectErrorMessage(reason);
421-
setHandshakeState("failed");
422-
setCloseCause("pairing-required", {
423-
deviceId: device.id,
424-
...(recoveryRequestId ? { requestId: recoveryRequestId } : {}),
425-
reason,
426-
});
427-
send({
428-
type: "res",
429-
id: frame.id,
430-
ok: false,
431-
error: errorShape(ErrorCodes.NOT_PAIRED, pairingErrorMessage, {
432-
details: pairingErrorDetails,
397+
failPairingHandshake({
398+
message: buildPairingConnectErrorMessage(reason),
399+
details: buildPairingConnectErrorDetails({
400+
reason,
401+
requestId: recoveryRequestId,
402+
...(retryWhileDetachedApprovalPending
403+
? {
404+
recommendedNextStep: "wait_then_retry",
405+
retryable: true,
406+
pauseReconnect: false,
407+
}
408+
: {}),
409+
deviceId: device.id,
410+
requestedRole: role,
411+
requestedScopes: scopes,
412+
...(approvedRoles.length > 0 ? { approvedRoles } : {}),
413+
...(approvedScopes.length > 0 ? { approvedScopes } : {}),
433414
}),
434-
});
435-
close(
436-
1008,
437-
truncateCloseReason(
438-
buildPairingConnectCloseReason({
415+
closeCause: {
416+
cause: "pairing-required",
417+
meta: {
418+
deviceId: device.id,
419+
...(recoveryRequestId ? { requestId: recoveryRequestId } : {}),
439420
reason,
440-
requestId: recoveryRequestId,
441-
}),
442-
),
443-
);
421+
},
422+
},
423+
closeReason: buildPairingConnectCloseReason({ reason, requestId: recoveryRequestId }),
424+
});
444425
return false;
445426
}
446427
return true;
@@ -517,14 +498,7 @@ export async function authorizeGatewayConnectDevice(
517498
(!pairedBrowserOrigin || !browserCopilotOrigin || pairedBrowserOrigin !== browserCopilotOrigin);
518499
if (browserCopilotIdentityMismatch || browserCopilotOriginMismatch) {
519500
const message = "browser copilot requires a dedicated paired device identity";
520-
setHandshakeState("failed");
521-
send({
522-
type: "res",
523-
id: frame.id,
524-
ok: false,
525-
error: errorShape(ErrorCodes.NOT_PAIRED, message),
526-
});
527-
close(1008, truncateCloseReason(message));
501+
failPairingHandshake({ message });
528502
return undefined;
529503
}
530504

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

Lines changed: 23 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -131,42 +131,38 @@ export async function authorizeExistingGatewayDevice(params: {
131131
publicKey: devicePublicKey,
132132
})
133133
: null;
134-
if (retryBootstrapHandoffProfile) {
134+
if (
135+
retryBootstrapHandoffProfile &&
136+
isSetupCodeHandoffBootstrapClient({
137+
profile: retryBootstrapHandoffProfile,
138+
client: connectParams.client,
139+
})
140+
) {
135141
const retryBootstrapOperatorScopes = resolveBootstrapProfileScopesForRole(
136142
"operator",
137143
retryBootstrapHandoffProfile.scopes,
138144
retryBootstrapHandoffProfile.purpose,
139145
);
146+
const pairedAllowsHandoff =
147+
pairedRoles.includes("operator") &&
148+
roleScopesAllow({
149+
role: "operator",
150+
requestedScopes: retryBootstrapOperatorScopes,
151+
allowedScopes: pairedScopes,
152+
});
153+
if (!pairedAllowsHandoff && !(await requirePairing("scope-upgrade", paired))) {
154+
return { ok: false, handoffBootstrapProfile };
155+
}
140156
if (
141-
isSetupCodeHandoffBootstrapClient({
157+
pairedDeviceAllowsBootstrapOperator({
158+
device: device ? await getPairedDevice(device.id) : null,
159+
devicePublicKey,
142160
profile: retryBootstrapHandoffProfile,
143-
client: connectParams.client,
144161
})
145162
) {
146-
const pairedAllowsHandoff =
147-
pairedRoles.includes("operator") &&
148-
roleScopesAllow({
149-
role: "operator",
150-
requestedScopes: retryBootstrapOperatorScopes,
151-
allowedScopes: pairedScopes,
152-
});
153-
if (!pairedAllowsHandoff) {
154-
if (!(await requirePairing("scope-upgrade", paired))) {
155-
return { ok: false, handoffBootstrapProfile };
156-
}
157-
}
158-
const pairedAfterBootstrapUpgrade = device ? await getPairedDevice(device.id) : null;
159-
if (
160-
pairedDeviceAllowsBootstrapOperator({
161-
device: pairedAfterBootstrapUpgrade,
162-
devicePublicKey,
163-
profile: retryBootstrapHandoffProfile,
164-
})
165-
) {
166-
// The setup code is the owner-approved upgrade artifact. Reuse the
167-
// same handoff after retrying or promoting an existing mobile pairing.
168-
handoffBootstrapProfile = retryBootstrapHandoffProfile;
169-
}
163+
// The setup code is the owner-approved upgrade artifact. Reuse the
164+
// same handoff after retrying or promoting an existing mobile pairing.
165+
handoffBootstrapProfile = retryBootstrapHandoffProfile;
170166
}
171167
}
172168

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

Lines changed: 19 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@ const DEFAULT_TRUSTED_PROXY_DEVICE_AUTO_APPROVE_SCOPES = [
3232
"operator.questions",
3333
] as const;
3434

35-
export function resolveTrustedProxyDeviceAutoApproveScopes(params: {
35+
function resolveTrustedProxyDeviceAutoApproveScopes(params: {
3636
requestedScopes: string[];
3737
hasRequestedScopes: boolean;
3838
configuredScopes?: string[];
@@ -60,7 +60,8 @@ export type PairingApprovalPlan = {
6060
/** Request is created silent and immediately self-approved by its lane. */
6161
silent: boolean;
6262
allowSilentLocalPairing: boolean;
63-
allowTrustedProxyDeviceAutoApproval: boolean;
63+
trustedProxyAutoApproveScopes: string[] | null;
64+
trustedProxyUser: string | undefined;
6465
isTrustedProxySameKeyUpgrade: boolean;
6566
allowSetupCodeHandoffBootstrapPairing: boolean;
6667
allowControlUiOwnerBootstrapPairing: boolean;
@@ -87,9 +88,10 @@ export async function resolvePairingApprovalPlan(params: {
8788
deviceId: string;
8889
devicePublicKey: string;
8990
scopes: string[];
91+
hasRequestedScopes: boolean;
92+
connectionScopeCap: (scopes: string[]) => string[];
9093
}): Promise<PairingApprovalPlan> {
91-
const { reason, existingPairedDevice, state, configSnapshot, scopes } = params;
92-
const { connectParams } = params;
94+
const { reason, existingPairedDevice, state, connectParams, configSnapshot, scopes } = params;
9395
const {
9496
role,
9597
isControlUi,
@@ -101,9 +103,8 @@ export async function resolvePairingApprovalPlan(params: {
101103
bootstrapTokenCandidate,
102104
pairingLocality,
103105
} = state;
104-
const allowSilentExistingNonOperatorPairing = !(existingPairedDevice && role !== "operator");
105106
const allowSilentLocalPairing =
106-
allowSilentExistingNonOperatorPairing &&
107+
!(existingPairedDevice && role !== "operator") &&
107108
shouldAllowSilentLocalPairing({
108109
autoApproveLocal: configSnapshot.gateway?.nodes?.pairing?.autoApproveLocal,
109110
locality: pairingLocality,
@@ -135,13 +136,21 @@ export async function resolvePairingApprovalPlan(params: {
135136
// mismatch stays a manual owner decision (possible deviceId squat).
136137
const isTrustedProxySameKeyUpgrade =
137138
reason === "scope-upgrade" && existingPairedDevice?.publicKey === params.devicePublicKey;
138-
const allowTrustedProxyDeviceAutoApproval =
139+
const trustedProxyAutoApproveScopes =
139140
((reason === "not-paired" && !existingPairedDevice) || isTrustedProxySameKeyUpgrade) &&
140141
role === "operator" &&
141142
(isBrowserOperatorUi || isWebchat) &&
142143
authMethod === "trusted-proxy" &&
143144
Boolean(trustedProxyUser) &&
144-
trustedProxyAutoApproveConfig?.enabled === true;
145+
trustedProxyAutoApproveConfig?.enabled === true
146+
? params.connectionScopeCap(
147+
resolveTrustedProxyDeviceAutoApproveScopes({
148+
requestedScopes: scopes,
149+
hasRequestedScopes: params.hasRequestedScopes,
150+
configuredScopes: trustedProxyAutoApproveConfig?.scopes,
151+
}),
152+
)
153+
: null;
145154
const isSetupCodeMobileNodeConnect = isMobileNodeBootstrapConnect({
146155
role,
147156
scopes,
@@ -226,7 +235,8 @@ export async function resolvePairingApprovalPlan(params: {
226235
allowSetupCodeHandoffBootstrapPairing ||
227236
allowControlUiOperatorBootstrapPairing,
228237
allowSilentLocalPairing,
229-
allowTrustedProxyDeviceAutoApproval,
238+
trustedProxyAutoApproveScopes,
239+
trustedProxyUser,
230240
isTrustedProxySameKeyUpgrade,
231241
allowSetupCodeHandoffBootstrapPairing,
232242
allowControlUiOwnerBootstrapPairing,

0 commit comments

Comments
 (0)