Skip to content

Commit 5fe8d6a

Browse files
authored
fix(gateway): clients can identify authorization failures (#110925)
* fix(gateway): structure authorization errors * test(gateway): align authorization contracts * fix(gateway): regenerate protocol bindings * fix(gateway): preserve optional scope errors * fix(gateway): report complete pairing scopes * style(gateway): format protocol exports
1 parent bde17f9 commit 5fe8d6a

18 files changed

Lines changed: 262 additions & 26 deletions

‎apps/shared/OpenClawKit/Sources/OpenClawProtocol/GatewayModels.swift‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@ public enum ErrorCode: String, Codable, Sendable {
2626
case notPaired = "NOT_PAIRED"
2727
case agentTimeout = "AGENT_TIMEOUT"
2828
case invalidRequest = "INVALID_REQUEST"
29+
case forbidden = "FORBIDDEN"
2930
case approvalNotFound = "APPROVAL_NOT_FOUND"
3031
case unavailable = "UNAVAILABLE"
3132
}
@@ -573,6 +574,28 @@ public struct ErrorShape: Codable, Sendable {
573574
}
574575
}
575576

577+
public struct GatewayErrorDetails: Codable, Sendable {
578+
public let code: String
579+
public let missingscope: String
580+
public let requiredscopes: [String]
581+
582+
public init(
583+
code: String,
584+
missingscope: String,
585+
requiredscopes: [String])
586+
{
587+
self.code = code
588+
self.missingscope = missingscope
589+
self.requiredscopes = requiredscopes
590+
}
591+
592+
private enum CodingKeys: String, CodingKey {
593+
case code
594+
case missingscope = "missingScope"
595+
case requiredscopes = "requiredScopes"
596+
}
597+
}
598+
576599
public struct GatewaySuspendTaskBlocker: Codable, Sendable {
577600
public let taskid: String
578601
public let status: String

‎docs/.generated/plugin-sdk-api-baseline.sha256‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -122,7 +122,7 @@ b013053a61e7d9be3d0c683c02baf57fa7e4393ec54e0df6a46ab0f2fe2348fd module/extensi
122122
e2d4a336857b4bdc98137162d16a683d8aa39b46028b74deb731b9f939efc62b module/file-access-runtime
123123
d13708bc224297df10a7f91e244f87e822fef9d71e2ca799442a49e42b6868c5 module/file-lock
124124
ceacad83db01c66e7be6aa21a291597020f13f737b697690eae7d47098e6499a module/gateway-method-runtime
125-
50c1d8bd7662eede9f74791f7f09cdeeb5337258229d12307c96efd3c6dcc59a module/gateway-runtime
125+
ce90af5578795d6e1cd2e9e3db5018071e57e0b21d67dfe8b8e847c0dfec5bcc module/gateway-runtime
126126
4611de9835515711d641f0f3e48d3c4e528afc343d5e5934fe3ed62072955511 module/global-singleton
127127
6062869202e3d7fdaa1f6801d6c1df7bf7406b8118cc4c7167ed409f5257b05c module/group-access
128128
5e672df8c679d90e2e61b30d08cc9de8f1a1cac439e7020869b088ee9ab4e5ce module/group-activation

‎docs/gateway/protocol.md‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,21 @@ Frame shapes:
3030
- Response: `{type:"res", id, ok, payload|error}`
3131
- Event: `{type:"event", event, payload, seq?, stateVersion?}`
3232

33+
Response errors use `{ code, message, details?, retryable?, retryAfterMs? }`.
34+
Clients should branch on `code` and `details.code`; `message` remains human-readable
35+
and can change except where a compatibility note says otherwise. Method-level
36+
authorization failures use top-level `code: "FORBIDDEN"` with structured
37+
missing-scope details:
38+
39+
- Missing scope: `{ code: "MISSING_SCOPE", missingScope, requiredScopes }`.
40+
`requiredScopes` is the complete known scope set for the requested operation.
41+
The legacy `missing scope: <scope>` message is retained for older clients.
42+
43+
The schemas are exported as `GatewayErrorDetailsSchema`,
44+
`MissingScopeErrorDetailsSchema` from `@openclaw/gateway-protocol/schema`.
45+
HTTP scope failures mirror the `MISSING_SCOPE` object under `error.details` and
46+
use HTTP status `403`.
47+
3348
Side-effecting methods require idempotency keys (see schema).
3449

3550
## Handshake

‎packages/gateway-protocol/src/index.ts‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ export type { ProtocolValidator } from "./protocol-validator.js";
1313
export * from "./schema/worker-inference.js";
1414
export * from "./schema/skill-history.js";
1515
export * from "./schema/ui-command.js";
16+
export type { GatewayErrorDetails, MissingScopeErrorDetails } from "./schema/error-codes.js";
1617
export * from "./migration-api.js";
1718
export type * from "./public-session-catalog.js";
1819
import {
@@ -229,6 +230,10 @@ import {
229230
PluginsUninstallParamsSchema,
230231
PluginsUninstallResultSchema,
231232
ErrorCodes,
233+
buildMissingScopeErrorDetails,
234+
GatewayErrorDetailCodes,
235+
GatewayErrorDetailsSchema,
236+
MissingScopeErrorDetailsSchema,
232237
EnvironmentSummarySchema,
233238
EnvironmentsCreateParamsSchema,
234239
EnvironmentsCreateResultSchema,
@@ -284,6 +289,7 @@ import {
284289
ErrorShapeSchema,
285290
EventFrameSchema,
286291
errorShape,
292+
missingScopeErrorShape,
287293
GatewayFrameSchema,
288294
GATEWAY_SERVER_CAPS,
289295
HelloOkSchema,
@@ -942,6 +948,8 @@ export {
942948
PresenceEntrySchema,
943949
SnapshotSchema,
944950
ErrorShapeSchema,
951+
GatewayErrorDetailsSchema,
952+
MissingScopeErrorDetailsSchema,
945953
WorkerAdmissionFailureReasonSchema,
946954
WorkerAdmissionHandshakeSchema,
947955
WorkerAdmissionResponseFrameSchema,
@@ -1402,7 +1410,10 @@ export {
14021410
MIN_PROBE_PROTOCOL_VERSION,
14031411
PROTOCOL_VERSION,
14041412
ErrorCodes,
1413+
buildMissingScopeErrorDetails,
1414+
GatewayErrorDetailCodes,
14051415
errorShape,
1416+
missingScopeErrorShape,
14061417
};
14071418

14081419
// Type exports mirror the schema exports for downstream TypeScript consumers.
Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
import { Value } from "typebox/value";
2+
import { describe, expect, it } from "vitest";
3+
import {
4+
ErrorCodes,
5+
GatewayErrorDetailCodes,
6+
GatewayErrorDetailsSchema,
7+
MissingScopeErrorDetailsSchema,
8+
missingScopeErrorShape,
9+
} from "./error-codes.js";
10+
11+
describe("gateway error details", () => {
12+
it("validates missing-scope details", () => {
13+
const details = {
14+
code: GatewayErrorDetailCodes.MISSING_SCOPE,
15+
missingScope: "operator.write",
16+
requiredScopes: ["operator.write"],
17+
};
18+
19+
expect(Value.Check(MissingScopeErrorDetailsSchema, details)).toBe(true);
20+
expect(Value.Check(GatewayErrorDetailsSchema, details)).toBe(true);
21+
expect(Value.Check(MissingScopeErrorDetailsSchema, { ...details, requiredScopes: [] })).toBe(
22+
false,
23+
);
24+
});
25+
26+
it("builds a distinct forbidden missing-scope response", () => {
27+
expect(
28+
missingScopeErrorShape({
29+
missingScope: "operator.approvals",
30+
requiredScopes: ["operator.read", "operator.approvals"],
31+
}),
32+
).toEqual({
33+
code: ErrorCodes.FORBIDDEN,
34+
message: "missing scope: operator.approvals",
35+
details: {
36+
code: GatewayErrorDetailCodes.MISSING_SCOPE,
37+
missingScope: "operator.approvals",
38+
requiredScopes: ["operator.read", "operator.approvals"],
39+
},
40+
});
41+
});
42+
43+
it("keeps requiredScopes non-empty when a caller has no method metadata", () => {
44+
expect(
45+
missingScopeErrorShape({ missingScope: "operator.admin", requiredScopes: [] }).details,
46+
).toEqual({
47+
code: GatewayErrorDetailCodes.MISSING_SCOPE,
48+
missingScope: "operator.admin",
49+
requiredScopes: ["operator.admin"],
50+
});
51+
});
52+
});

‎packages/gateway-protocol/src/schema/error-codes.ts‎

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,9 @@
11
// Gateway Protocol schema module defines protocol validation shapes.
2+
import type { Static } from "typebox";
3+
import { Type } from "typebox";
4+
import { closedObject } from "./closed-object.js";
25
import type { ErrorShape } from "./frames.js";
6+
import { NonEmptyString } from "./primitives.js";
37

48
/** Gateway JSON-RPC style error codes shared by clients and server handlers. */
59
export const ErrorCodes = {
@@ -11,6 +15,8 @@ export const ErrorCodes = {
1115
AGENT_TIMEOUT: "AGENT_TIMEOUT",
1216
/** Request payload failed protocol validation or method preconditions. */
1317
INVALID_REQUEST: "INVALID_REQUEST",
18+
/** Authenticated caller lacks permission for the requested operation. */
19+
FORBIDDEN: "FORBIDDEN",
1420
/** Approval resolution referenced a missing or expired approval request. */
1521
APPROVAL_NOT_FOUND: "APPROVAL_NOT_FOUND",
1622
/** Gateway service or required backend is temporarily unavailable. */
@@ -20,6 +26,24 @@ export const ErrorCodes = {
2026
/** Closed set of canonical gateway error code strings. */
2127
export type ErrorCode = (typeof ErrorCodes)[keyof typeof ErrorCodes];
2228

29+
/** Stable discriminants for structured method-level authorization failures. */
30+
export const GatewayErrorDetailCodes = {
31+
MISSING_SCOPE: "MISSING_SCOPE",
32+
} as const;
33+
34+
/** Missing operator-scope details shared by WebSocket and HTTP responses. */
35+
export const MissingScopeErrorDetailsSchema = closedObject({
36+
code: Type.Literal(GatewayErrorDetailCodes.MISSING_SCOPE),
37+
missingScope: NonEmptyString,
38+
requiredScopes: Type.Array(NonEmptyString, { minItems: 1 }),
39+
});
40+
41+
/** Structured details emitted by method-level authorization failures. */
42+
export const GatewayErrorDetailsSchema = MissingScopeErrorDetailsSchema;
43+
44+
export type MissingScopeErrorDetails = Static<typeof MissingScopeErrorDetailsSchema>;
45+
export type GatewayErrorDetails = Static<typeof GatewayErrorDetailsSchema>;
46+
2347
/** Builds the canonical gateway error payload while preserving optional retry metadata. */
2448
export function errorShape(
2549
code: ErrorCode,
@@ -32,3 +56,26 @@ export function errorShape(
3256
...opts,
3357
};
3458
}
59+
60+
/** Builds structured details for a missing operator scope. */
61+
export function buildMissingScopeErrorDetails(params: {
62+
missingScope: string;
63+
requiredScopes: readonly string[];
64+
}): MissingScopeErrorDetails {
65+
const requiredScopes =
66+
params.requiredScopes.length > 0 ? [...params.requiredScopes] : [params.missingScope];
67+
return {
68+
code: GatewayErrorDetailCodes.MISSING_SCOPE,
69+
missingScope: params.missingScope,
70+
requiredScopes,
71+
};
72+
}
73+
74+
/** Builds a forbidden error for a missing operator scope without message parsing. */
75+
export function missingScopeErrorShape(params: {
76+
missingScope: string;
77+
requiredScopes: readonly string[];
78+
}): ErrorShape {
79+
const details = buildMissingScopeErrorDetails(params);
80+
return errorShape(ErrorCodes.FORBIDDEN, `missing scope: ${params.missingScope}`, { details });
81+
}

‎packages/gateway-protocol/src/schema/protocol-schemas.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -248,6 +248,7 @@ import {
248248
WorkerEnvironmentStateSchema,
249249
WorkerTunnelStatusSchema,
250250
} from "./environments.js";
251+
import { GatewayErrorDetailsSchema } from "./error-codes.js";
251252
import {
252253
ExecApprovalsGetParamsSchema,
253254
ExecApprovalsNodeGetParamsSchema,
@@ -548,6 +549,7 @@ export const ProtocolSchemas = {
548549
StateVersion: StateVersionSchema,
549550
Snapshot: SnapshotSchema,
550551
ErrorShape: ErrorShapeSchema,
552+
GatewayErrorDetails: GatewayErrorDetailsSchema,
551553
GatewaySuspendTaskBlocker: GatewaySuspendTaskBlockerSchema,
552554
GatewaySuspendBlocker: GatewaySuspendBlockerSchema,
553555
GatewaySuspendPrepareParams: GatewaySuspendPrepareParamsSchema,

‎src/gateway/control-ui.http.test.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -299,6 +299,11 @@ describe("handleControlUiHttpRequest", () => {
299299
error: {
300300
type: "forbidden",
301301
message: "missing scope: operator.read",
302+
details: {
303+
code: "MISSING_SCOPE",
304+
missingScope: "operator.read",
305+
requiredScopes: ["operator.read"],
306+
},
302307
},
303308
});
304309
}

‎src/gateway/http-common.test.ts‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ import {
1010
} from "../infra/diagnostic-events.js";
1111
import type { GatewayAuthResult } from "./auth.js";
1212
import {
13+
buildMissingScopeForbiddenBody,
1314
readJsonBodyOrError,
1415
sendGatewayAuthFailure,
1516
sendInvalidRequest,
@@ -122,6 +123,18 @@ describe("sendJson", () => {
122123
});
123124
});
124125

126+
describe("buildMissingScopeForbiddenBody", () => {
127+
it("preserves the legacy response when no concrete scope is available", () => {
128+
expect(buildMissingScopeForbiddenBody(undefined)).toEqual({
129+
ok: false,
130+
error: {
131+
type: "forbidden",
132+
message: "missing scope: undefined",
133+
},
134+
});
135+
});
136+
});
137+
125138
describe("sendMethodNotAllowed", () => {
126139
it("defaults the Allow header to POST and responds 405", () => {
127140
const { res, setHeader, end } = makeMockHttpResponse();

‎src/gateway/http-common.ts‎

Lines changed: 19 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
// Shared Gateway HTTP helpers handle small JSON/text responses, SSE headers,
22
// body-size errors, and client disconnect aborts.
33
import type { IncomingMessage, ServerResponse } from "node:http";
4+
import { buildMissingScopeErrorDetails } from "../../packages/gateway-protocol/src/index.js";
45
import {
56
logRejectedLargePayload,
67
parseContentLengthHeader,
@@ -76,18 +77,33 @@ export function sendInvalidRequest(res: ServerResponse, message: string) {
7677
});
7778
}
7879

79-
export function buildMissingScopeForbiddenBody(missingScope: string | undefined) {
80+
export function buildMissingScopeForbiddenBody(
81+
missingScope: string | undefined,
82+
requiredScopes?: readonly string[],
83+
) {
84+
const details =
85+
typeof missingScope === "string" && missingScope.length > 0
86+
? buildMissingScopeErrorDetails({
87+
missingScope,
88+
requiredScopes: requiredScopes ?? [missingScope],
89+
})
90+
: undefined;
8091
return {
8192
ok: false,
8293
error: {
8394
type: "forbidden",
8495
message: `missing scope: ${missingScope}`,
96+
...(details ? { details } : {}),
8597
},
8698
};
8799
}
88100

89-
export function sendMissingScopeForbidden(res: ServerResponse, missingScope: string | undefined) {
90-
sendJson(res, 403, buildMissingScopeForbiddenBody(missingScope));
101+
export function sendMissingScopeForbidden(
102+
res: ServerResponse,
103+
missingScope: string | undefined,
104+
requiredScopes?: readonly string[],
105+
) {
106+
sendJson(res, 403, buildMissingScopeForbiddenBody(missingScope, requiredScopes));
91107
}
92108

93109
export async function readJsonBodyOrError(

0 commit comments

Comments
 (0)