Repository navigation
Expand file tree
/
Copy pathindex.ts
More file actions
4305 lines (4187 loc) · 160 KB
/
Copy pathindex.ts
File metadata and controls
4305 lines (4187 loc) · 160 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 { sandboxPolicyHandlers } from "./http/sandbox-policy.ts";
import swagger from "@fastify/swagger";
import type { TypeBoxTypeProvider } from "@fastify/type-provider-typebox";
import { AuditEventFactory, type AuditSink } from "@openclaw-enterprise/audit";
import {
AgentDeploymentDiagnosticsResponse,
AgentRuntimeCredentialResponse,
AgentRuntimeLogsResponse,
AgentRuntimeResponse,
CredentialSourceResponse,
ErrorDetail as ErrorDetailSchema,
ErrorResponse,
JsonValue,
occApiRoutes,
PluginApproversSchema,
PluginDesiredSelectionSchema,
PluginDesiredStateSchema,
PluginDriverIdentitySchema,
PluginToolDefaultsSchema,
PluginToolPolicySchema,
PRESET_JSON_MAX_BYTES,
SecretResponse,
type AgentRuntimeLogsQuery,
type AuditEvent,
type AuditEventKind,
type AuthorizationEvidence,
type BackendSummary,
type ChannelDriver,
type ComputeDriver,
type ConfigurationDriver,
type IAMDriver,
type Installation,
type OccApiRoute,
type PermissionAction,
type ResourceKind,
type ResourceRef,
type SandboxDriver,
type SecretDriver,
type SecretReference,
type CredentialSourceReference,
type UpdateWorkspaceFileBody,
type WorkspaceFileName,
} from "@openclaw-enterprise/contracts";
import {
AuthAccountRoleInvalidError,
AuthAccountRoleNotFoundError,
NativeIAMDriver,
type AuthPrincipalSeed,
} from "@openclaw-enterprise/iam";
import {
AgentPrincipalAuthorizationError,
AuthorizationDeniedError,
DeletionRetryOwnedError,
BOOTSTRAP_DEFAULT_NAMESPACE_NAME,
ComputeProvisioningRefusedError,
createRuntimeLogCursorCodec,
DependencyUnavailableError,
DeviceAuthorizationStartError,
ResourceConflictError,
RuntimeCredentialsForbiddenByClusterError,
RuntimeLogsError,
UserAlreadyExistsError,
type DeployAgentAuthorization,
type HarnessResolver,
type OpenClawController,
} 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 PreparedAuthAccount,
} from "./auth/index.ts";
import { CONSOLE_CONTENT_SECURITY_POLICY, readConsoleAsset } from "./console-assets.ts";
import type { ConsoleTheme } from "./console-theme.ts";
import {
ControllerWorkspaceFileUnknownOutcomeError,
isAllowedWorkspaceFileName,
type ControllerWorkspaceFileReadResult,
type ControllerWorkspaceFilesAccess,
type ControllerWorkspaceFileWriteResult,
} from "./gateway/contracts.ts";
import type { NativeAdminAccessConfig } from "./gateway/native-admin.ts";
import { createAgentHandlers } from "./http/agents.ts";
import { configurationHandlers } from "./http/configurations.ts";
import { credentialSourceHandlers } from "./http/credential-sources.ts";
import { jsonPointer, type ErrorDetail } 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,
nativeAdminStatusSchema,
nativeAdminReturnOperation,
nativeAdminReturnSchema,
limitNativeAdminReturn,
} from "./http/native-admin.ts";
import { presetHandlers } from "./http/presets.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, ResourceHandlers } from "./http/types.ts";
export { cachedRequestValidators, cachedResponseSerializers } from "./http/route-compilers.ts";
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;
readonly backendSummaries?: readonly BackendSummary[];
readonly observabilityUrl?: string;
readonly development: DevelopmentAdmission;
readonly maxBodyBytes?: number;
readonly auth: ControllerAuth;
readonly workspaceFilesAccess?: ControllerWorkspaceFilesAccess;
readonly workspaceFileRequestTimeoutMs?: number;
readonly nativeAdmin?: NativeAdminAccessConfig;
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?: (
seed: AuthPrincipalSeed,
auditEvent: AuditEvent,
prepared: PreparedAuthAccount,
external?: { readonly providerId: string; readonly subject: string },
) => Promise<void>;
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 RequiredPermission {
readonly action: PermissionAction;
readonly resourceKind: ResourceKind;
readonly scope: "requested" | "installation" | "namespace" | "each_returned" | "request_body";
readonly condition?:
| "associated_service_account"
| "existing_namespace"
| "bound_secret"
| "directory_lookup"
| "selected_secret"
| "iam_binding_target"
| "provisioning_work"
| "missing_runtime_credentials"
| "authenticated_plugin_discovery"
| "read_logs_alternative"
| "bound_credential_source";
}
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);
const WORKSPACE_FILE_CONTENT_LIMIT = 16 * 1024;
// 16 KiB of content may need six bytes per UTF-8 byte in JSON (`\u0001`), plus `{"content":""}`.
const WORKSPACE_FILE_BODY_LIMIT = 6 * WORKSPACE_FILE_CONTENT_LIMIT + 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_",
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>>;
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: OccApiRoute,
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") &&
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 === "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 requiredPermissions(operation: OccApiRoute): readonly RequiredPermission[] {
const permission = {
action: operation.iamAction,
resourceKind: operation.resourceKind,
};
if (
[
"getAgentSandboxPolicy",
"getAgentSandboxRecommendations",
"updateAgentSandboxPolicy",
"applyAgentSandboxPolicy",
].includes(operation.operationId)
) {
return [
{ ...permission, scope: "requested" },
{
action: operation.iamAction === "read" ? "read" : "update",
resourceKind: "sandbox_policy",
scope: "requested",
},
];
}
if (operation.operationId === "TEMPORARY_API_WILL_BREAK_IN_FUTURE_setAgentSandboxPolicyEditing") {
return [
{ ...permission, scope: "requested" },
{ action: "administer", resourceKind: "installation", scope: "installation" },
];
}
if (operation.operationId.endsWith("DeviceAuthorization")) {
const saved = operation.operationId.includes("SavedAgent");
return [
{
action: saved ? "update" : "create",
resourceKind: "agent",
scope: saved ? "requested" : "namespace",
},
...(saved
? [{ action: "read" as const, resourceKind: "agent" as const, scope: "requested" as const }]
: []),
{
action: operation.operationId.startsWith("start") ? "create" : "operate",
resourceKind: "secret",
scope: operation.operationId.startsWith("start") ? "namespace" : "requested",
},
];
}
if (operation.operationId === "createNamespace") {
return [
{ ...permission, scope: "installation" },
{
action: "administer",
resourceKind: "installation",
scope: "requested",
condition: "existing_namespace",
},
];
}
if (
operation.operationId === "createConfiguration" ||
operation.operationId === "updateConfiguration"
) {
return [
{
...permission,
scope: operation.operationId === "createConfiguration" ? "namespace" : "requested",
},
{
action: "operate",
resourceKind: "secret",
scope: operation.operationId === "createConfiguration" ? "request_body" : "requested",
condition: "bound_secret",
},
];
}
if (
operation.operationId === "discoverAgentPlugins" ||
operation.operationId === "discoverAgentPluginDetails"
) {
return [
{ ...permission, scope: "namespace" },
{
action: "operate",
resourceKind: "secret",
scope: "request_body",
condition: "selected_secret",
},
];
}
if (operation.operationId === "createSecret") {
return [{ ...permission, scope: "namespace" }];
}
if (
operation.operationId === "createCredentialSource" ||
operation.operationId === "updateCredentialSource"
) {
// Mirrors OCC readCredentialSourceSecrets: operate on each Secret whose value the
// gateway receives (an update re-sends the current references when it names none).
const create = operation.operationId === "createCredentialSource";
return [
{ ...permission, scope: create ? "namespace" : "requested" },
{
action: "operate",
resourceKind: "secret",
scope: create ? "request_body" : "requested",
condition: "bound_secret",
},
];
}
if (operation.operationId === "lookupChannelDirectory") {
return [
{
action: "operate",
resourceKind: "secret",
scope: "request_body",
condition: "directory_lookup",
},
{
action: "create",
resourceKind: "agent",
scope: "namespace",
condition: "directory_lookup",
},
{
action: "update",
resourceKind: "agent",
scope: "request_body",
condition: "directory_lookup",
},
{
action: "update",
resourceKind: "configuration",
scope: "request_body",
condition: "directory_lookup",
},
];
}
if (operation.operationId === "createIAMAccessBinding") {
return [
{ action: "administer", resourceKind: "installation", scope: "requested" },
{ action: "read", resourceKind: "namespace", scope: "requested" },
{
action: "read",
resourceKind: "agent",
scope: "request_body",
condition: "iam_binding_target",
},
{
action: "read",
resourceKind: "agent_revision",
scope: "request_body",
condition: "iam_binding_target",
},
{
action: "read",
resourceKind: "configuration",
scope: "request_body",
condition: "iam_binding_target",
},
{
action: "read",
resourceKind: "credential_source",
scope: "request_body",
condition: "iam_binding_target",
},
{
action: "read",
resourceKind: "namespace",
scope: "request_body",
condition: "iam_binding_target",
},
{
action: "read",
resourceKind: "preset",
scope: "request_body",
condition: "iam_binding_target",
},
{
action: "read",
resourceKind: "secret",
scope: "request_body",
condition: "iam_binding_target",
},
{
action: "read",
resourceKind: "service_account",
scope: "request_body",
condition: "iam_binding_target",
},
];
}
if (
operation.operationId === "listIAMRoles" ||
operation.operationId === "createIAMRole" ||
operation.operationId === "getIAMRole" ||
operation.operationId === "deleteIAMRole" ||
operation.operationId === "listIAMAccessBindings" ||
operation.operationId === "getIAMAccessBinding" ||
operation.operationId === "deleteIAMAccessBinding" ||
operation.operationId === "listIAMServicePrincipals" ||
operation.operationId === "createIAMServicePrincipal" ||
operation.operationId === "getIAMServicePrincipal"
) {
return [
{ action: "administer", resourceKind: "installation", scope: "requested" },
{ action: "read", resourceKind: "namespace", scope: "requested" },
];
}
if (
operation.operationId === "provisionAgent" ||
operation.operationId === "createAgent" ||
operation.operationId === "updateAgent" ||
operation.operationId === "deployAgent"
) {
return [
{
...permission,
scope:
operation.operationId === "createAgent" || operation.operationId === "provisionAgent"
? "namespace"
: "requested",
},
...(operation.operationId === "provisionAgent"
? [
{
action: "create" as const,
resourceKind: "configuration" as const,
scope: "namespace" as const,
},
{
action: "administer" as const,
resourceKind: "installation" as const,
scope: "requested" as const,
},
]
: [
{
action: "read" as const,
resourceKind: "configuration" as const,
scope: "requested" as const,
},
]),
...(operation.operationId === "deployAgent"
? [
{
action: "read" as const,
resourceKind: "agent" as const,
scope: "requested" as const,
condition: "missing_runtime_credentials" as const,
},
{
action: "operate" as const,
resourceKind: "agent" as const,
scope: "requested" as const,
condition: "missing_runtime_credentials" as const,
},
]
: []),
{
action: "read",
resourceKind: "service_account",
scope: "requested",
condition: "associated_service_account",
},
{
action: "operate",
resourceKind: "secret",
scope: "requested",
condition: "bound_secret",
},
// Mirrors OCC authorizeHarnessAuthSource and authorizeAgentCredentialSources. Agent
// provisioning refuses credential sources, so it needs no such grant.
...(operation.operationId === "provisionAgent"
? []
: [
{
action: "operate" as const,
resourceKind: "credential_source" as const,
scope:
operation.operationId === "createAgent"
? ("request_body" as const)
: ("requested" as const),
condition: "bound_credential_source" as const,
},
]),
];
}
if (
operation.operationId === "getAgentProvisioning" ||
operation.operationId === "retryAgentProvisioning"
) {
// Mirrors OCC authorizeProvisioningRequest, then authorizeProvisioningRecord.
return [
{ action: "create", resourceKind: "agent", scope: "namespace" },
{ action: "create", resourceKind: "configuration", scope: "namespace" },
{ action: "administer", resourceKind: "installation", scope: "requested" },
...(["read", "operate", "deploy"] as const).map((action) => ({
action,
resourceKind: "agent" as const,
scope: "requested" as const,
condition: "provisioning_work" as const,
})),
...(["read", "update"] as const).map((action) => ({
action,
resourceKind: "configuration" as const,
scope: "requested" as const,
condition: "provisioning_work" as const,
})),
{
action: "read",
resourceKind: "service_account",
scope: "requested",
condition: "associated_service_account",
},
{
action: "operate",
resourceKind: "secret",
scope: "requested",
condition: "bound_secret",
},
];
}
if (operation.operationId === "provisionAgentRuntimeCredentials") {
return [
{ ...permission, scope: "requested" },
{ action: "read", resourceKind: "agent", scope: "requested" },
];
}
if (
operation.operationId === "getSavedAgentPluginPolicyCapabilities" ||
operation.operationId === "discoverSavedAgentPlugins" ||
operation.operationId === "discoverSavedAgentPluginDetails"
) {
return [
{ ...permission, scope: "requested" },
{ action: "read", resourceKind: "agent", scope: "requested" },
...(operation.operationId === "getSavedAgentPluginPolicyCapabilities"
? []
: [
{
action: "operate" as const,
resourceKind: "secret" as const,
scope: "requested" as const,
condition: "authenticated_plugin_discovery" as const,
},
]),
];
}
if (operation.operationId === "diagnoseAgentDeployment") {
return [
{ action: "operate", resourceKind: "agent", scope: "requested" },
{ action: "read", resourceKind: "agent", scope: "requested" },
{ action: "read", resourceKind: "agent_revision", scope: "requested" },
];
}
if (operation.operationId === "getAgentDeploymentRuntime") {
return [
{ action: "operate", resourceKind: "agent", scope: "requested" },
{ action: "read", resourceKind: "agent", scope: "requested" },
{ action: "read", resourceKind: "agent_revision", scope: "requested" },
];
}
if (operation.operationId === "getAgentDeploymentRuntimeLogs") {
return [
{ action: "read_logs", resourceKind: "agent", scope: "requested" },
{
action: "administer",
resourceKind: "agent",
scope: "requested",
condition: "read_logs_alternative",
},
{ action: "read", resourceKind: "agent", scope: "requested" },
];
}
switch (operation.authorizationTarget) {
case "namespace_collection":
return [{ ...permission, scope: "namespace" }];
case "namespace_candidates":
return [{ ...permission, scope: "each_returned" }];
case "namespace_and_agent_candidates":
return [
{ action: "read", resourceKind: "namespace", scope: "requested" },
{ ...permission, scope: "each_returned" },
];
case "namespace_and_service_account_candidates":
case "namespace_and_secret_candidates":
case "namespace_and_preset_candidates":
case "namespace_and_credential_source_candidates":
return [
{ action: "read", resourceKind: "namespace", scope: "requested" },
{ ...permission, scope: "each_returned" },
];
case "agent_collection":
return [
{ ...permission, scope: "requested" },
{ action: "read", resourceKind: "agent_revision", scope: "each_returned" },
];
default:
return [{ ...permission, scope: "requested" }];
}
}
function permissionDescription(
permissions: readonly RequiredPermission[],
operation?: OccApiRoute,
): string {
if (
operation?.operationId === "getAgentProvisioning" ||
operation?.operationId === "retryAgentProvisioning"
) {
const verb = operation.operationId === "getAgentProvisioning" ? "read" : "retry";
// The provisioning_work rows are described here, not per row.
return `Requires create permission for Agent and Configuration resources in the requested Namespace and administer permission on the Installation. These are checked from the request path before any lookup, so a caller without them gets 403 whether or not the Namespace or work item exists. Only the principal that started the work can ${verb} it. The caller also needs read, operate and deploy permission on the work's Agent and read and update permission on its Configuration once the work has created them, operate permission on each Secret the work binds or uses for Harness authentication, and read permission on its Harness ServiceAccount when present. OCC re-checks these grants against the initiator while the work runs.`;
}
const names: Record<ResourceKind, string> = {
installation: "Installation",
namespace: "Namespace",
configuration: "Configuration",
preset: "Preset",
service_account: "ServiceAccount",
secret: "Secret",
agent: "Agent",
agent_revision: "Agent revision",
credential_source: "CredentialSource",
sandbox_policy: "SandboxPolicy",
};
const description = permissions
.map(({ action, resourceKind, scope, condition }) => {
const name = names[resourceKind];
if (condition === "associated_service_account") {
return `Requires ${action} permission on each currently associated or newly associated ${name} when present.`;
}
if (condition === "directory_lookup") {
if (resourceKind === "secret") {
return "Requires operate permission on the exact Secret named by secretId.";
}
if (action === "create") {
return "Without an edit target, requires Agent create permission in the Namespace.";
}
return `With ${resourceKind === "agent" ? "agentId" : "configurationId"}, requires update permission on that exact ${name}.`;
}
if (condition === "existing_namespace") {
return `Requires ${action} permission on the ${name} when selecting an existing Kubernetes namespace.`;
}
if (condition === "selected_secret") {
return `Requires ${action} permission on the exact same-Namespace ${name} when a Secret reference is supplied.`;
}
if (condition === "bound_secret") {
if (operation?.operationId === "provisionAgent") {
return `Requires ${action} permission on each existing ${name} reference supplied in provisioning inputs.`;
}
if (operation?.operationId === "createConfiguration") {
return `Requires ${action} permission on each ${name} supplied in request body Secret bindings.`;
}
if (operation?.operationId === "updateConfiguration") {
return `Requires ${action} permission on each ${name} bound by the resulting Configuration.`;
}
if (operation?.operationId === "createCredentialSource") {
return `Requires ${action} permission on each ${name} named in the request body secrets.`;
}
if (operation?.operationId === "updateCredentialSource") {
return `Requires ${action} permission on each ${name} the source references after the update, including its current references when the request omits secrets.`;
}
return `Requires ${action} permission on each bound ${name} when Secret bindings are present or selected.`;
}
if (condition === "bound_credential_source") {
if (operation?.operationId === "createAgent") {
return `Requires ${action} permission on each ${name} listed in credentialSources or named by a credential-source harnessAuth.`;
}
if (operation?.operationId === "updateAgent") {
return `Requires ${action} permission on each ${name} the Agent lists or names in harnessAuth, before and after the update.`;
}
return `Requires ${action} permission on each ${name} the Agent lists or names in harnessAuth.`;
}
if (condition === "missing_runtime_credentials") {
return `Requires ${action} permission on the Agent when the selected Compute Driver must generate missing runtime credentials for its first deployment.`;
}
if (condition === "authenticated_plugin_discovery") {
return `Requires ${action} permission on the Agent's bound ${name} when the selected Plugin Driver requires a discovery credential.`;
}
if (condition === "read_logs_alternative") {
return `Without read_logs, ${action} permission on the requested ${name} also admits the read.`;
}
if (condition === "iam_binding_target") {
return `Requires ${action} permission on the request body ${name} when the AccessBinding targets that resource kind.`;
}