Repository navigation
Expand file tree
/
Copy pathindex.ts
More file actions
3933 lines (3828 loc) · 148 KB
/
Copy pathindex.ts
File metadata and controls
3933 lines (3828 loc) · 148 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { AGENT_CHAT_BODY_LIMIT, relayAgentChat } from "./http/agent-chat.ts";
import { sandboxPolicyHandlers } from "./http/sandbox-policy.ts";
import { createAgentAuditReader } from "./http/agent-audit.ts";
import { isAgentAutomationOperation, relayAgentAutomation } from "./http/agent-automations.ts";
import swagger from "@fastify/swagger";
import type { TypeBoxTypeProvider } from "@fastify/type-provider-typebox";
import { AuditEventFactory, type AuditSink } from "@openclaw-enterprise/audit";
import {
API_REQUEST_AUDIT_ACTIONS,
AgentDeploymentDiagnosticsResponse,
AgentRuntimeCredentialResponse,
AgentRuntimeLogsResponse,
AgentRuntimeResponse,
ConnectionTemplateSchema,
OAuthConnectionTemplateVersionSchema,
StaticKeyConnectionTemplateVersionSchema,
ModelProviderSchema,
ModelProviderModelSchema,
CredentialSourceResponse,
RegisterTokenServiceSourceBody,
RegisterGitHubAppTokenServiceSourceBody,
UpdateTokenServiceSourceBody,
PushAgentCredentialsBody,
PushAgentCredentialsResponse,
ErrorResponse,
JsonValue,
occApiRoutes,
PluginApproversSchema,
PluginDesiredSelectionSchema,
PluginDesiredStateSchema,
PluginDriverIdentitySchema,
PluginToolDefaultsSchema,
PluginToolPolicySchema,
PRESET_JSON_MAX_BYTES,
SecretResponse,
type AgentRuntimeLogsQuery,
type ApiRequestAuditObservation,
type AuditEvent,
type AuditEventKind,
type AuthorizationEvidence,
type BackendSummary,
type ChannelDriver,
type ComputeDriver,
type ConfigurationDriver,
type IAMDriver,
type Installation,
type OccApiRoute,
type DiscoverSavedAgentPluginDetailsBody,
type PermissionAction,
type ResourceRef,
type SandboxDriver,
type SecretDriver,
type CredentialSourceReference,
} from "@openclaw-enterprise/contracts";
import {
AuthAccountRoleInvalidError,
AuthAccountRoleNotFoundError,
NativeIAMDriver,
} from "@openclaw-enterprise/iam";
import {
AgentPrincipalAuthorizationError,
AuditAppendUnavailableError,
AuthorizationDeniedError,
DeletionRetryOwnedError,
ComputeProvisioningRefusedError,
createRuntimeLogCursorCodec,
DependencyUnavailableError,
CredentialDeliveryFailedError,
DeviceAuthorizationScopeMismatchError,
DeviceAuthorizationStartError,
PostgresCommitOutcomeUnknownError,
ResourceStateConflictError,
RuntimeCredentialsForbiddenByClusterError,
RuntimeLogsError,
UserAlreadyExistsError,
type DeployAgentAuthorization,
type HarnessResolver,
type OpenClawController,
type PlatformUnitOfWork,
} from "@openclaw-enterprise/occ";
import { isNonEmptyString } from "@openclaw-enterprise/utils";
import Fastify, {
LogController,
type FastifyBaseLogger,
type FastifyInstance,
type FastifyReply,
type FastifyRequest,
type FastifySchema,
type HTTPMethods,
type InjectOptions,
type RouteGenericInterface,
} from "fastify";
import { randomUUID } from "node:crypto";
import type { IncomingMessage, ServerResponse } from "node:http";
import type { AdmittedCaller } from "./admission/admission-verifier.ts";
import {
DEVELOPMENT_BROWSER_ORIGIN_RULE,
isDevelopmentBrowserOrigin,
} from "./auth/configuration.ts";
import {
OCC_SERVICE_KEY_HEADER,
SERVICE_KEY_NAME_MAX_LENGTH,
ServiceKeyNameRefused,
type ClientAddressConfiguration,
type ControllerAuth,
type ProvisionAuthAccount,
} from "./auth/index.ts";
import { CONSOLE_CONTENT_SECURITY_POLICY, readConsoleAsset } from "./console-assets.ts";
import { createBootstrapResources } from "./composition/installation-bootstrap.ts";
import { discoverMcpAuthorization } from "./connections/mcp-discovery.ts";
import { listManagedMcpToolNames } from "./connections/mcp-tool-discovery.ts";
import type { ConsoleTheme } from "./console-theme.ts";
import type { ControllerWorkspaceFilesAccess } from "./gateway/contracts.ts";
import { normalizeNativeAdminDomain } from "./gateway/native-admin.ts";
import type { NativeAdminAccessConfig } from "./gateway/native-admin.ts";
import { createAgentHandlers } from "./http/agents.ts";
import { createDeviceAuthorizationHandlers } from "./http/device-authorization.ts";
import { callerDenialMessage, GENERIC_DENIAL, requestedValues } from "./http/caller-denial.ts";
import { configurationHandlers } from "./http/configurations.ts";
import { credentialSourceHandlers } from "./http/credential-sources.ts";
import { jsonPointer } from "./http/error-details.ts";
import {
canonicalFailure,
cappedPath,
dependencyUnavailable,
dependencyUnavailableLogFields,
failure,
isAuthorizationDenied,
isDependencyUnavailable,
RequestFailure,
requestFailure,
responseHeaders,
unstorableTextFailure,
} from "./http/errors.ts";
import { iamHandlers } from "./http/iam.ts";
import { MAX_JSON_BODY_DEPTH, tooDeepFailure, tooDeepJsonPath } from "./http/json-depth.ts";
import {
createNativeAdminAccess,
nativeAdminStatusOperation,
nativeAdminLaunchOperation,
nativeAdminConfirmOperation,
nativeAdminLaunchSchema,
nativeAdminStatusSchema,
nativeAdminReturnOperation,
nativeAdminReturnSchema,
limitNativeAdminReturn,
} from "./http/native-admin.ts";
import { permissionAdvice } from "./http/permission-advice.ts";
import { createAuthRouteSchemas, installationAuthOperation } from "./http/auth-schemas.ts";
import { routePermissionMetadata, type RequiredPermission } from "./http/permission-metadata.ts";
import { presetHandlers } from "./http/presets.ts";
import { connectionTemplateHandlers } from "./http/connection-templates.ts";
import {
CONNECTION_CALLBACK_PATH,
connectionCallbackOperation,
connectionCallbackSchema,
createConnectionCallback,
namespaceConnectionHandlers,
} from "./http/connections.ts";
import {
isRuntimeLogDownload,
RUNTIME_LOG_DOWNLOAD_ACTION,
runtimeLogDownloadBody,
runtimeLogDownloadFileName,
RuntimeLogLimiter,
runtimeLogPageBody,
runtimeLogQuery,
type AgentRuntimeLogsConfig,
} from "./http/runtime-logs.ts";
import { RequestRateLimiter } from "./http/request-rate-limiter.ts";
import {
cachedRequestValidators,
cachedResponseSerializers,
defaultPrecompiledRouteCompilers,
formatsPlugin,
} from "./http/route-compilers.ts";
import { secretHandlers } from "./http/secrets.ts";
import { serviceAccountHandlers } from "./http/service-accounts.ts";
import type { RequestContext, RequestOperation, ResourceHandlers } from "./http/types.ts";
import { createWorkspaceFileHandlers, WORKSPACE_FILE_BODY_LIMIT } from "./http/workspace-files.ts";
export { cachedRequestValidators, cachedResponseSerializers } from "./http/route-compilers.ts";
class AccountPrincipalAccessDeniedError extends AuthorizationDeniedError {
readonly userId: string;
readonly principalId: string;
constructor(userId: string, principalId: string, evidence: AuthorizationEvidence) {
super("The caller does not hold every grant of the target account's Principal.", evidence);
this.userId = userId;
this.principalId = principalId;
}
}
export interface DevelopmentAdmission {
readonly enabled: boolean;
readonly installationId?: string;
/** Exact browser origin for a loopback-owned development endpoint. */
readonly browserOrigin?: string;
readonly trustedCidrs?: readonly string[];
}
export interface ControllerAppOptions {
readonly consoleTheme?: ConsoleTheme;
readonly metrics?: import("./metrics/index.ts").OccMetrics;
readonly controller?: OpenClawController;
readonly createController?: (installation: Installation) => OpenClawController;
readonly iamDriver: IAMDriver;
readonly computeDriver?: ComputeDriver;
readonly configurationDriver?: ConfigurationDriver;
readonly channelDriver?: ChannelDriver;
readonly secretDriver?: SecretDriver;
readonly sandboxDriver?: SandboxDriver;
readonly resolveHarness: HarnessResolver;
readonly auditSink: AuditSink;
/** Durable sink for required HTTP admission and result records. */
readonly durableRequestAuditSink?: AuditSink;
readonly agentAuditCursorSecret?: string;
readonly backendSummaries?: readonly BackendSummary[];
readonly observabilityUrl?: string;
readonly development: DevelopmentAdmission;
readonly maxBodyBytes?: number;
readonly auth: ControllerAuth;
readonly workspaceFilesAccess?: ControllerWorkspaceFilesAccess;
readonly workspaceFileRequestTimeoutMs?: number;
readonly discoverMcpAuthorization?: typeof discoverMcpAuthorization;
readonly readManagedMcpToolNames?: typeof listManagedMcpToolNames;
readonly nativeAdmin?: NativeAdminAccessConfig;
/** Private Agent gateway transport credential, shared by native browser and HTTP chat relays. */
readonly nativeAdminGatewayApiKey?: () => Promise<string>;
/**
* How often a native admin WebSocket rechecks its admission (default 25 s). The server
* leaves it unset; tests shorten it so revocation closes do not wait the full interval.
*/
readonly nativeAdminWebSocketLeaseIntervalMs?: number;
/** Absent or disabled: both runtime routes answer 501. */
readonly agentRuntimeLogs?: AgentRuntimeLogsConfig;
readonly publicOrigin?: string;
/** Writes the prepared account with its Principal, bindings and enrolment atomically. */
readonly provisionAuthAccount?: ProvisionAuthAccount;
readonly auditEventFactory?: AuditEventFactory;
readonly logger?: FastifyBaseLogger;
/** Production proxies allowed to send forwarded headers; admission ignores those headers. */
readonly trustedProxies?: Pick<ClientAddressConfiguration, "trusts">;
}
export interface ControllerApp {
fetch(request: Request): Promise<Response>;
}
interface DocumentedFastifySchema extends FastifySchema {
readonly "x-openclaw-permissions": readonly RequiredPermission[];
}
const resourceHandlers: ResourceHandlers = {
...configurationHandlers,
...presetHandlers,
...secretHandlers,
...credentialSourceHandlers,
...iamHandlers,
...serviceAccountHandlers,
};
const DEFAULT_BODY_LIMIT = 64 * 1024;
// Four 16 KiB documents can expand sixfold in JSON, plus the ordinary create fields.
const AGENT_CREATE_BODY_LIMIT = 448 * 1024;
// A bounded template may use six-byte JSON escapes; reserve space for its name and envelope.
const PRESET_BODY_LIMIT = 6 * PRESET_JSON_MAX_BYTES + 8 * 1024;
// The bundled Kubernetes Configuration Driver stores values up to 1 MiB of JSON (its ConfigMap
// cap). A Configuration write must admit that plus the envelope (`kind` and up to 64 Secret
// bindings, each a 253-character name and a reference: under 32 KiB), all written with
// six-byte JSON escapes. Like Preset writes, these routes check the grant before the body.
const CONFIGURATION_BODY_LIMIT = 6 * (1024 * 1024 + 32 * 1024);
// Path parameters such as IAM Role and AccessBinding IDs hold up to 200 characters (code
// points). The router compares a parameter's decoded UTF-16 length, so 200 characters need
// at most 400 units; its default of 100 refused contract-valid IDs before any handler ran.
const MAX_PATH_PARAMETER_LENGTH = 400;
const LOOPBACK_ADDRESSES = new Set(["127.0.0.1", "::1", "::ffff:127.0.0.1"]);
const LOOPBACK_HOSTNAMES = new Set(["127.0.0.1", "localhost", "[::1]", "::1"]);
const RESOURCE_ID_PREFIX = {
namespaceId: "ns_",
presetId: "pre_",
configurationId: "cfg_",
serviceAccountId: "sa_",
secretId: "sec_",
sessionId: "sec_",
credentialSourceId: "cs_",
agentId: "agt_",
revisionId: "rev_",
deploymentId: "rev_",
} as const;
const RESOURCE_ID = Object.fromEntries(
Object.entries(RESOURCE_ID_PREFIX).map(([parameter, prefix]) => [
parameter,
new RegExp(`^${prefix}[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$`),
]),
) as Readonly<Record<keyof typeof RESOURCE_ID_PREFIX, RegExp>>;
// Runs only after the JSON parser refused a body, to tell text that is not JSON from JSON its
// poisoning guard refused.
function isJson(text: string): boolean {
try {
JSON.parse(text);
return true;
} catch {
return false;
}
}
function ipv4(value: string): number | undefined {
const parts = value.split(".");
if (parts.length !== 4) {
return undefined;
}
let result = 0;
for (const part of parts) {
// Same no-leading-zero rule as production trusted proxies and Compute: "010" is not 10.
if (!/^(?:0|[1-9][0-9]{0,2})$/.test(part)) {
return undefined;
}
const octet = Number(part);
if (octet > 255) {
return undefined;
}
result = (result << 8) | octet;
}
return result >>> 0;
}
function cidrContains(cidr: string, address: string): boolean {
const [network, prefixText] = cidr.split("/");
if (network === undefined || prefixText === undefined || cidr.split("/").length !== 2) {
throw new Error("Development trusted CIDRs must use IPv4 CIDR notation.");
}
const prefix = Number(prefixText);
// "08" is not prefix 8. Production parseCidr refuses that spelling, and so does Compute.
if (
!/^(?:0|[1-9][0-9]{0,2})$/.test(prefixText) ||
!Number.isInteger(prefix) ||
prefix < 0 ||
prefix > 32
) {
throw new Error("Development trusted CIDRs must use IPv4 CIDR notation.");
}
const networkValue = ipv4(network);
const addressValue = ipv4(address);
if (networkValue === undefined) {
throw new Error("Development trusted CIDRs must use IPv4 CIDR notation.");
}
if (addressValue === undefined) {
return false;
}
const mask = prefix === 0 ? 0 : (0xffffffff << (32 - prefix)) >>> 0;
return (networkValue & mask) === (addressValue & mask);
}
function trustedDevelopmentAddress(
development: DevelopmentAdmission,
remoteAddress: string,
): boolean {
if (LOOPBACK_ADDRESSES.has(remoteAddress)) {
return true;
}
const cidrs = development.trustedCidrs ?? [];
if (cidrs.length === 0) {
return false;
}
const normalized = remoteAddress.startsWith("::ffff:")
? remoteAddress.slice("::ffff:".length)
: remoteAddress;
return cidrs.some((cidr) => cidrContains(cidr, normalized));
}
function validateTrustedDevelopmentCidrs(development: DevelopmentAdmission): void {
for (const cidr of development.trustedCidrs ?? []) {
cidrContains(cidr, "127.0.0.1");
}
}
function developmentBrowserOrigin(development: DevelopmentAdmission): URL | undefined {
if (development.browserOrigin === undefined) {
return undefined;
}
if (!development.enabled || !isDevelopmentBrowserOrigin(development.browserOrigin)) {
throw new Error(`The development browser origin must be ${DEVELOPMENT_BROWSER_ORIGIN_RULE}.`);
}
return new URL(development.browserOrigin);
}
function validAuthorizationEvidence(value: unknown): value is AuthorizationEvidence {
if (typeof value !== "object" || value === null) {
return false;
}
const candidate = value as Partial<AuthorizationEvidence>;
if (candidate.identityId !== undefined && !isNonEmptyString(candidate.identityId)) {
return false;
}
return [
candidate.groupIds,
candidate.bindingIds,
candidate.roleIds,
candidate.restrictionIds,
].every((entries) => Array.isArray(entries) && entries.every(isNonEmptyString));
}
function validateConfiguration(value: unknown, depth = 0, path = ""): void {
// The JSON body parser already refuses deeper bodies; this keeps the rule for any other input.
if (depth > MAX_JSON_BODY_DEPTH) {
throw tooDeepFailure(path);
}
if (value === null || typeof value !== "object") {
return;
}
if (Array.isArray(value)) {
for (const [index, entry] of value.entries()) {
validateConfiguration(entry, depth + 1, `${path}/${index}`);
}
return;
}
for (const [key, entry] of Object.entries(value)) {
if (key === "__proto__" || key === "constructor" || key === "prototype") {
throw failure(400, "INVALID_REQUEST", "The supplied configuration is invalid.", [
{ path: cappedPath(`${path}/${jsonPointer(key)}`), code: "INVALID_VALUE" },
]);
}
validateConfiguration(entry, depth + 1, `${path}/${jsonPointer(key)}`);
}
}
/** Operations whose grant check runs before their body is read (see authorizeBeforeBody). */
function authorizesBeforeBody(operation: OccApiRoute): boolean {
return (
operation.operationId === "createPreset" ||
operation.operationId === "updatePreset" ||
operation.operationId === "createConfiguration" ||
operation.operationId === "updateConfiguration"
);
}
function operationTarget(
operation: RequestOperation,
installationId: string,
params: Readonly<Record<string, unknown>>,
): ResourceRef {
const namespaceId = typeof params.namespaceId === "string" ? params.namespaceId : undefined;
const configurationId =
typeof params.configurationId === "string" ? params.configurationId : undefined;
const serviceAccountId =
typeof params.serviceAccountId === "string" ? params.serviceAccountId : undefined;
const presetId = typeof params.presetId === "string" ? params.presetId : undefined;
const secretId = typeof params.secretId === "string" ? params.secretId : undefined;
const credentialSourceId =
typeof params.credentialSourceId === "string" ? params.credentialSourceId : undefined;
const agentId = typeof params.agentId === "string" ? params.agentId : undefined;
const revisionId = typeof params.revisionId === "string" ? params.revisionId : undefined;
if (operation.operationId === "createNamespace") {
return { kind: "namespace", id: installationId };
}
if (operation.resourceKind === "preset" && namespaceId) {
return { kind: "preset", id: presetId ?? namespaceId, namespaceId };
}
if (operation.operationId === "createConfiguration" && namespaceId) {
return { kind: "configuration", id: namespaceId, namespaceId };
}
if (configurationId && namespaceId) {
return { kind: "configuration", id: configurationId, namespaceId };
}
if (operation.operationId === "createServiceAccount" && namespaceId) {
return { kind: "service_account", id: namespaceId, namespaceId };
}
if (serviceAccountId && namespaceId) {
return { kind: "service_account", id: serviceAccountId, namespaceId };
}
if (
(operation.operationId === "createSecret" || operation.operationId === "listSecrets") &&
namespaceId
) {
return { kind: "secret", id: namespaceId, namespaceId };
}
if (operation.operationId.endsWith("DeviceAuthorization") && namespaceId) {
return { kind: "agent", id: agentId ?? namespaceId, namespaceId };
}
if (secretId && namespaceId) {
return { kind: "secret", id: secretId, namespaceId };
}
if (
(operation.operationId === "createCredentialSource" ||
operation.operationId === "listCredentialSources" ||
operation.operationId === "listUsableConnectionTemplates" ||
operation.operationId === "listEligibleOAuthClients" ||
operation.operationId === "startNamespaceConnection") &&
namespaceId
) {
return { kind: "credential_source", id: namespaceId, namespaceId };
}
// A route naming a credential source authorizes the resource kind it declares: withdrawal
// routes declare the Agent.
if (credentialSourceId && namespaceId) {
return operation.resourceKind === "agent" && agentId
? { kind: "agent", id: agentId, namespaceId }
: { kind: "credential_source", id: credentialSourceId, namespaceId };
}
if (
(operation.operationId === "createAgent" ||
operation.operationId === "validateAgentCreate" ||
operation.operationId === "getNamespaceAgentCapabilities" ||
operation.operationId === "provisionAgent" ||
operation.operationId === "listRepositoryOptions") &&
namespaceId
) {
return { kind: "agent", id: namespaceId, namespaceId };
}
if (
(operation.operationId === "getAgentProvisioning" ||
operation.operationId === "retryAgentProvisioning") &&
namespaceId &&
typeof params.workId === "string"
) {
return { kind: "agent", id: params.workId, namespaceId };
}
if (operation.operationId === "getAgentRevision" && namespaceId && revisionId) {
return { kind: "agent_revision", id: revisionId, namespaceId };
}
if (agentId && namespaceId) {
return { kind: "agent", id: agentId, namespaceId };
}
if (namespaceId) {
return { kind: "namespace", id: namespaceId, namespaceId };
}
return { kind: "installation", id: installationId };
}
function clientInstallation(
installation: Readonly<Installation>,
computeDriver: Readonly<ComputeDriver> | undefined,
nativeAdminEnabled: boolean,
): Record<string, unknown> {
const agentProvisioning = computeDriver?.agentProvisioning;
const capabilities = {
...installation.capabilities,
...(nativeAdminEnabled ? { nativeAdmin: true } : {}),
...(agentProvisioning === undefined
? {}
: {
agentProvisioning: { executionModes: [...agentProvisioning.executionModes] },
}),
};
return {
id: installation.id,
name: installation.name,
createdAt: installation.createdAt,
...(Object.keys(capabilities).length === 0 ? {} : { capabilities }),
};
}
export function createFastifyApp(options: ControllerAppOptions): FastifyInstance {
const development = Object.freeze({ ...options.development });
const browserOrigin = developmentBrowserOrigin(development);
if (
options.controller &&
development.installationId !== undefined &&
development.installationId !== options.controller.installation.id
) {
throw new Error(
"The configured Installation does not match the controller-owned Installation.",
);
}
const bodyLimit = options.maxBodyBytes ?? DEFAULT_BODY_LIMIT;
const precompiledRouteCompilers = defaultPrecompiledRouteCompilers();
if (!Number.isSafeInteger(bodyLimit) || bodyLimit < 1) {
throw new Error("The controller request-body limit must be a positive integer.");
}
const workspaceFileRequestTimeoutMs = options.workspaceFileRequestTimeoutMs ?? 30_000;
if (!Number.isSafeInteger(workspaceFileRequestTimeoutMs) || workspaceFileRequestTimeoutMs < 1) {
throw new Error("The workspace file request timeout must be a positive integer.");
}
const nativeAdminWebSocketLeaseIntervalMs = options.nativeAdminWebSocketLeaseIntervalMs;
if (
nativeAdminWebSocketLeaseIntervalMs !== undefined &&
(!Number.isSafeInteger(nativeAdminWebSocketLeaseIntervalMs) ||
nativeAdminWebSocketLeaseIntervalMs < 1)
) {
throw new Error("The native admin WebSocket lease interval must be a positive integer.");
}
let publicOrigin: string | undefined;
let publicOriginHost: string | undefined;
if (options.publicOrigin !== undefined) {
try {
const parsed = new URL(options.publicOrigin);
publicOrigin = parsed.origin;
publicOriginHost = parsed.host;
if (
parsed.username ||
parsed.password ||
parsed.pathname !== "/" ||
parsed.search ||
parsed.hash
) {
throw new Error("Invalid public origin.");
}
} catch {
throw new Error("The controller public origin must be an absolute origin URL.");
}
}
validateTrustedDevelopmentCidrs(development);
if (development.enabled && options.trustedProxies !== undefined) {
throw new Error("Trusted proxies are a production setting.");
}
const app = Fastify({
bodyLimit,
...(options.logger === undefined
? {}
: {
loggerInstance: options.logger,
logController: new LogController({ disableRequestLogging: true }),
}),
trustProxy: false,
requestIdHeader: false,
genReqId: () => `req_${randomUUID()}`,
routerOptions: { maxParamLength: MAX_PATH_PARAMETER_LENGTH },
// Router failures happen before routing, so no hook or error handler runs; without this
// Fastify answers its own body (echoing the path) with no request ID or security headers.
frameworkErrors: (error, request, reply) => {
const mapped =
error.code === "FST_ERR_BAD_URL"
? failure(400, "INVALID_REQUEST", "The request path has a malformed percent-encoding.")
: error.code === "FST_ERR_MAX_PARAM_LENGTH"
? failure(
400,
"INVALID_REQUEST",
"The request does not match the operation contract: a path parameter is too long.",
)
: // FST_ERR_ASYNC_CONSTRAINT; this app registers no async route constraints.
failure(500, "INTERNAL_ERROR", "The platform request could not be completed.");
// No hook runs for these, so record them as the onResponse hook records other requests,
// with no measured duration.
options.metrics?.observeHttp("unmatched", request.method, mapped.status, 0);
options.logger?.info({
event: "http.completed",
requestId: request.id,
method: request.method,
route: "unmatched",
status: mapped.status,
});
canonicalFailure(reply, mapped);
},
ajv: {
// `verbose` attaches each failure's schema and value, so contract errors can tell which
// shape of a discriminated union a request chose (http/error-details.ts). Neither is logged or
// returned: problems name only paths and the schema's accepted values, and http/errors.ts
// drops both from the error once its problems are built. An onError hook runs before
// that, so none may log `error.validation`.
customOptions: {
removeAdditional: false,
coerceTypes: false,
useDefaults: false,
verbose: true,
},
plugins: [formatsPlugin],
},
schemaController: {
compilersFactory: {
buildValidator: cachedRequestValidators(precompiledRouteCompilers),
buildSerializer: cachedResponseSerializers(precompiledRouteCompilers),
},
},
}).withTypeProvider<TypeBoxTypeProvider>();
// Shutdown (app.close) drains admitted requests, but Node and Fastify close only the
// keep-alive sockets that are idle when it starts. A socket whose response finishes during
// the drain would stay open until the server's 72 s keep-alive timeout, past the API Pod's
// 30 s termination grace. Mark those responses `Connection: close`, or close the socket
// after a response whose headers were already sent, as Node does for `Connection: close`.
const openResponses = new Set<ServerResponse>();
app.server.on("request", (_request: IncomingMessage, response: ServerResponse) => {
openResponses.add(response);
response.once("close", () => openResponses.delete(response));
});
app.addHook("preClose", async () => {
for (const response of openResponses) {
if (!response.headersSent) {
response.setHeader("connection", "close");
} else if (!response.writableFinished) {
const { socket } = response;
response.once("finish", () => socket?.destroySoon());
}
}
});
app.removeContentTypeParser("text/plain");
// Refuse a body nested deeper than any document the API stores before it is parsed: parsing
// allocates every level, and schema validation recurses through them (a 6 MB body of nested
// arrays cost about 300 MB of heap, then overflowed the stack into a 500).
const parseJson = app.getDefaultJsonParser(
app.initialConfig.onProtoPoisoning ?? "error",
app.initialConfig.onConstructorPoisoning ?? "error",
);
app.addContentTypeParser("application/json", { parseAs: "string" }, (request, body, done) => {
const tooDeep = tooDeepJsonPath(body as string);
if (tooDeep !== undefined) {
done(tooDeepFailure(tooDeep), undefined);
return;
}
parseJson(request, body as string, (error, parsed) => {
// Text that is not JSON at all gets its own message (finding D762). Valid JSON the
// poisoning guard refused, such as a __proto__ key, keeps the generic contract message.
if (
(error as { code?: unknown } | null)?.code === "FST_ERR_CTP_INVALID_JSON_BODY" &&
!isJson(body as string)
) {
done(failure(400, "INVALID_REQUEST", "The request body is not valid JSON."), undefined);
return;
}
done(error, parsed);
});
});
app.addSchema(JsonValue);
app.addSchema(PluginDriverIdentitySchema);
app.addSchema(PluginApproversSchema);
app.addSchema(PluginToolPolicySchema);
app.addSchema(PluginToolDefaultsSchema);
app.addSchema(PluginDesiredSelectionSchema);
app.addSchema(PluginDesiredStateSchema);
app.addSchema(ErrorResponse);
app.addSchema(AgentDeploymentDiagnosticsResponse);
app.addSchema(AgentRuntimeResponse);
app.addSchema(AgentRuntimeLogsResponse);
app.addSchema(AgentRuntimeCredentialResponse);
app.addSchema(SecretResponse);
app.addSchema(CredentialSourceResponse);
app.addSchema(OAuthConnectionTemplateVersionSchema);
app.addSchema(ConnectionTemplateSchema);
app.addSchema(StaticKeyConnectionTemplateVersionSchema);
app.addSchema(ModelProviderModelSchema);
app.addSchema(ModelProviderSchema);
app.addSchema(RegisterTokenServiceSourceBody);
app.addSchema(RegisterGitHubAppTokenServiceSourceBody);
app.addSchema(UpdateTokenServiceSourceBody);
app.addSchema(PushAgentCredentialsBody);
app.addSchema(PushAgentCredentialsResponse);
void app.register(swagger, {
convertConstToEnum: false,
refResolver: {
buildLocalReference(schema, _baseUri, _fragment, index) {
// Standalone contracts have public names. Keep Swagger's names and titles for route schemas.
if (typeof schema.$id === "string") {
schema.title ??= schema.$id;
switch (schema.$id) {
case "RegisterTokenServiceSourceBody":
case "RegisterGitHubAppTokenServiceSourceBody":
case "UpdateTokenServiceSourceBody":
case "PushAgentCredentialsBody":
case "PushAgentCredentialsResponse":
return schema.$id;
}
}
return `def-${index}`;
},
},
openapi: {
openapi: "3.1.0",
info: {
title: development.enabled ? "Development OCC API" : "Internal OCC API",
version: "0.1.0",
},
components: {
securitySchemes: {
sessionCookie: {
type: "apiKey",
in: "cookie",
name: options.auth?.sessionCookieName ?? "openclaw_occ.session_token",
},
serviceApiKey: { type: "apiKey", in: "header", name: OCC_SERVICE_KEY_HEADER },
},
},
security: [{ sessionCookie: [] }, { serviceApiKey: [] }],
},
});
let controller = options.controller;
let bootstrapping = false;
const installationId =
development.installationId ?? controller?.installation.id ?? `ins_${randomUUID()}`;
const admissions = new WeakMap<FastifyRequest, AdmittedCaller>();
const contexts = new WeakMap<FastifyRequest, RequestContext>();
const requestStartedAt = new WeakMap<FastifyRequest, bigint>();
const requestAuditState = new WeakMap<
FastifyRequest,
{
denialObserved: boolean;
resultSelected: boolean;
readTarget?: ResourceRef;
commitOutcomeUnknown?: true;
}
>();
const requestAuditSink = options.durableRequestAuditSink;
const factory = options.auditEventFactory ?? new AuditEventFactory();
const readAgentAudit =
options.agentAuditCursorSecret === undefined
? undefined
: createAgentAuditReader(options.agentAuditCursorSecret);
const createAuthAccountOperation = installationAuthOperation({
operationId: "createAuthAccount",
method: "POST",
path: "/api/auth/accounts",
action: "openclaw.auth.accounts.create",
summary: "Create a local auth account as an Installation administrator",
});
const serviceKeyOperations = (
[
{
operationId: "createServiceKey",
method: "POST",
path: "/api/auth/service-keys",
action: "openclaw.auth.service-keys.create",
summary: "Issue a service API key",
},
{
operationId: "revokeServiceKey",
method: "DELETE",
path: "/api/auth/service-keys/:keyId",
action: "openclaw.auth.service-keys.revoke",
summary: "Revoke a service API key",
},
] as const
).map(installationAuthOperation);
const runtimeLogLimiter = new RuntimeLogLimiter();
const runtimeLogCursor =
options.agentRuntimeLogs?.enabled === true
? createRuntimeLogCursorCodec(options.agentRuntimeLogs.cursorSecret)
: undefined;
function event(
operation: RequestOperation,
request: FastifyRequest,
resource: ResourceRef,
kind: AuditEventKind,
context?: RequestContext,
evidence?: AuthorizationEvidence,
result?: {
readonly outcome: "success" | "denied" | "failure";
readonly reasonCode?: string;
// A route's own denial explanation. It passes through the factory with the rest of the
// event, so its reason is redacted and capped and its details are redacted.
readonly decisionReason?: string;
readonly details?: Readonly<Record<string, unknown>>;
},
authorization?: NonNullable<AuthorizationDeniedError["authorization"]>,
validatedAuthorization?: Readonly<DeployAgentAuthorization>,
): AuditEvent {
const authorizationEvidence = validatedAuthorization?.decision.evidence ?? evidence;
const outcome = result?.outcome ?? (kind === "authorization_denial" ? "denied" : "success");
const evidenceDetails =
context === undefined || authorizationEvidence === undefined
? undefined
: {
iamEvidence: {
...(authorizationEvidence.identityId === undefined
? {}
: { identityId: authorizationEvidence.identityId }),
groupIds: authorizationEvidence.groupIds,
bindingIds: authorizationEvidence.bindingIds,
roleIds: authorizationEvidence.roleIds,
restrictionIds: authorizationEvidence.restrictionIds,
},
};
// A request admitted by a service key names that key (its non-secret ID), so an
// administrator can tell which of a ServicePrincipal's keys acted. `serviceKeyId` stays
// the key a key-management event acts on.
const admitted = admissions.get(request);
const actorKeyDetails =
admitted?.method === "api_key" && admitted.serviceKeyId !== undefined
? { actorServiceKeyId: admitted.serviceKeyId }
: undefined;
const details =
result?.details === undefined && actorKeyDetails === undefined
? evidenceDetails
: { ...evidenceDetails, ...result?.details, ...actorKeyDetails };
return factory.create({
installationId,
...(resource.namespaceId === undefined ? {} : { namespaceId: resource.namespaceId }),
kind,
source: "occ",
requestId: request.id,
...(context === undefined
? { actor: { unresolved: true } }
: {
actor: {
principalId: context.actorId,
issuer: context.issuer,
subject: context.subject,
},
admissionDecisionId: context.admissionDecisionId,
iamDriverId: validatedAuthorization?.decision.driverId ?? selectedIAMDriver().id,
authorization: validatedAuthorization?.request ?? {
principalId: context.actorId,
action: authorization?.action ?? operation.iamAction,
// Namespace IAM policy routes are admitted by administer on the
// Installation (plus reads), never by a Namespace administer check.
resource:
authorization?.resource ??
(operation.authorizationTarget === "namespace_iam"
? { kind: "installation", id: installationId }
: operationTarget(
operation,
installationId,
request.params as Record<string, unknown>,
)),
},
...(authorizationEvidence === undefined
? {}
: {
...(outcome === "denied" && authorizationEvidence.restrictionIds.length > 0
? { decisionReason: "A matching Restriction denied the operation." }
: {}),
}),
}),
...(result?.decisionReason === undefined ? {} : { decisionReason: result.decisionReason }),
...(details === undefined ? {} : { details }),
action: auditAction(operation, request),
resource,
outcome,
...(result?.reasonCode === undefined
? kind === "authorization_denial"
? { reasonCode: "AUTHORIZATION_DENIED" }
: {}
: { reasonCode: result.reasonCode }),
});
}
/** Log views and downloads share a route and permissions but not an audit action. */
function auditAction(operation: RequestOperation, request: FastifyRequest): string {
return operation.operationId === "getAgentDeploymentRuntimeLogs" &&
isRuntimeLogDownload(request.query as AgentRuntimeLogsQuery)
? RUNTIME_LOG_DOWNLOAD_ACTION
: operation.action;
}
function selectedIAMDriver(): IAMDriver {
try {
const selected =
controller === undefined ? options.iamDriver : controller.selectedDriver("iam");
if (selected.capability !== "iam") {
throw new Error("Invalid authorization authority.");
}
return selected;
} catch {
throw dependencyUnavailable();
}
}
function requireWorkspaceFileCsrf(request: FastifyRequest, requireOrigin: boolean): void {
const admitted = admissions.get(request);
if (admitted?.method === "api_key") {
return;
}
const fetchSite = request.headers["sec-fetch-site"];
const fetchSites =
fetchSite === undefined ? [] : Array.isArray(fetchSite) ? fetchSite : [fetchSite];
if (fetchSites.some((site) => site.toLowerCase() === "cross-site")) {
throw failure(403, "FORBIDDEN", "The request did not satisfy the configured CSRF boundary.");
}
if (!requireOrigin) {
return;
}
if (publicOrigin === undefined) {
throw dependencyUnavailable();
}
const origin = request.headers.origin;
if (typeof origin !== "string" || origin !== publicOrigin) {
throw failure(403, "FORBIDDEN", "The request did not satisfy the configured CSRF boundary.");
}
}
function pluginDiscoveryRequestSignal(reply: FastifyReply): AbortSignal {
// The POST can finish parsing and its client disconnect while IAM resolves the caller.
if (reply.raw.destroyed) {
return AbortSignal.abort();
}
const disconnected = new AbortController();
reply.raw.once("close", () => {
if (!reply.raw.writableEnded) {
disconnected.abort();
}
});
return disconnected.signal;
}
async function requireInstallationAdmin(
request: FastifyRequest,
operation: RequestOperation,
context: RequestContext,
) {
const target: ResourceRef = { kind: "installation", id: installationId };
const selected = selectedIAMDriver();
const decision = await installationAdminDecision(selected, context.actorId, target);
if (!decision.allowed) {
await denial(operation, request, "authorization_denial", context, decision.evidence);
throw failure(
403,