Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

RpcAuthorization.ts

270 lines14.4 KB

1import {
2 CLIENT_GUARDED_RPC_SCOPES,
3 type DeviceListInput,
4 clientRpcRequiredScopes,
5 authScopeRequiredResponse,
6 AssetCreateUrlInput,
7 AuthAccessReadScope,
8 ServerSettingsPatch,
9 ProviderInstanceMutation,
10 requiredScopesForServerSettingsPatch,
11 AuthSettingsWriteScope,
12 AuthProvidersManageScope,
13 AuthEnvironmentMaintainScope,
14 AuthFilesystemReadScope,
15 AuthFilesystemWriteScope,
16 AuthDiagnosticsReadScope,
17 AuthOrchestrationOperateScope,
18 AuthOrchestrationReadScope,
19 AuthPreviewOperateScope,
20 AuthRelayReadScope,
21 AuthRelayWriteScope,
22 AuthTerminalOperateScope,
23 ORCHESTRATION_V2_WS_METHODS,
24 AuthTerminalReadScope,
25 type AuthEnvironmentScope,
26 EnvironmentAuthorizationError,
27 RpcScopeAuthorization,
28 WS_METHODS,
29 WsRpcGroup,
30} from "@t3tools/contracts";
31import * as Effect from "effect/Effect";
32import * as Schema from "effect/Schema";
33import * as Layer from "effect/Layer";
34import type * as RpcGroup from "effect/rpc/RpcGroup";
35​
36type WsRpcMethod = RpcGroup.Rpcs<typeof WsRpcGroup>["_tag"];
37​
38/**
39 * Keep authorization coverage coupled to the RPC group itself. Adding an RPC to
40 * `WsRpcGroup` without choosing a scope is a type error instead of a production
41 * runtime failure.
42 */
43export const RPC_REQUIRED_SCOPES = {
44 ...CLIENT_GUARDED_RPC_SCOPES,
45 [ORCHESTRATION_V2_WS_METHODS.dispatchCommand]: AuthOrchestrationOperateScope,
46 [ORCHESTRATION_V2_WS_METHODS.getWorkflowScript]: AuthOrchestrationReadScope,
47 [ORCHESTRATION_V2_WS_METHODS.getTurnDiff]: AuthOrchestrationReadScope,
48 [ORCHESTRATION_V2_WS_METHODS.getFullThreadDiff]: AuthOrchestrationReadScope,
49 [ORCHESTRATION_V2_WS_METHODS.searchThreads]: AuthOrchestrationReadScope,
50 [ORCHESTRATION_V2_WS_METHODS.getArchivedShellSnapshot]: AuthOrchestrationReadScope,
51 [ORCHESTRATION_V2_WS_METHODS.getThreadProjection]: AuthOrchestrationReadScope,
52 [ORCHESTRATION_V2_WS_METHODS.getTurnItem]: AuthOrchestrationReadScope,
53 [ORCHESTRATION_V2_WS_METHODS.launchThread]: AuthOrchestrationOperateScope,
54 [ORCHESTRATION_V2_WS_METHODS.subscribeArchivedShell]: AuthOrchestrationReadScope,
55 [ORCHESTRATION_V2_WS_METHODS.subscribeShell]: AuthOrchestrationReadScope,
56 [ORCHESTRATION_V2_WS_METHODS.subscribeThread]: AuthOrchestrationReadScope,
57 [WS_METHODS.projectsMutate]: AuthOrchestrationOperateScope,
58 [WS_METHODS.serverProbe]: AuthOrchestrationReadScope,
59 [WS_METHODS.serverGetConfig]: AuthOrchestrationReadScope,
60 [WS_METHODS.serverRefreshProviders]: AuthOrchestrationReadScope,
61 [WS_METHODS.serverUpdateProvider]: AuthProvidersManageScope,
62 [WS_METHODS.providerAuthStart]: AuthProvidersManageScope,
63 [WS_METHODS.providerConsumeResetCredit]: AuthProvidersManageScope,
64 [WS_METHODS.providerAuthComplete]: AuthProvidersManageScope,
65 [WS_METHODS.chatGptReconnectProfile]: AuthProvidersManageScope,
66 [WS_METHODS.chatGptImportProfile]: AuthProvidersManageScope,
67 [WS_METHODS.chatGptHandoffSubscribe]: AuthProvidersManageScope,
68 [WS_METHODS.codexAuthCallbackSubscribe]: AuthProvidersManageScope,
69 [WS_METHODS.providerAuthRespond]: AuthProvidersManageScope,
70 [WS_METHODS.providerAuthCancel]: AuthProvidersManageScope,
71 [WS_METHODS.providerAuthLogout]: AuthProvidersManageScope,
72 [WS_METHODS.providerAuthSubscribe]: AuthProvidersManageScope,
73 [WS_METHODS.providerInstallStart]: AuthProvidersManageScope,
74 [WS_METHODS.providerInstallCancel]: AuthProvidersManageScope,
75 [WS_METHODS.providerInstallSubscribe]: AuthOrchestrationReadScope,
76 [WS_METHODS.providerInstallRemove]: AuthProvidersManageScope,
77 [WS_METHODS.serverUpdateServer]: AuthEnvironmentMaintainScope,
78 [WS_METHODS.serverUpdateServerWithProgress]: AuthEnvironmentMaintainScope,
79 [WS_METHODS.serverCommitDesktopUpdate]: AuthEnvironmentMaintainScope,
80 [WS_METHODS.serverUpsertKeybinding]: AuthSettingsWriteScope,
81 [WS_METHODS.serverRemoveKeybinding]: AuthSettingsWriteScope,
82 [WS_METHODS.serverGetSettings]: AuthOrchestrationReadScope,
83 [WS_METHODS.serverUpdateSettings]: AuthSettingsWriteScope,
84 [WS_METHODS.serverSearchAcpRegistry]: AuthOrchestrationReadScope,
85 [WS_METHODS.serverPrepareAcpRegistryAgent]: AuthProvidersManageScope,
86 [WS_METHODS.serverUninstallAcpRegistryManagedBinary]: AuthProvidersManageScope,
87 [WS_METHODS.serverAcceptAcpRegistryUrlAuth]: AuthProvidersManageScope,
88 [WS_METHODS.serverListAcpRegistrySessions]: AuthOrchestrationReadScope,
89 [WS_METHODS.serverImportAcpRegistrySession]: AuthOrchestrationOperateScope,
90 [WS_METHODS.serverDeleteAcpRegistrySession]: AuthOrchestrationOperateScope,
91 [WS_METHODS.serverListAcpRegistryProviders]: AuthOrchestrationReadScope,
92 [WS_METHODS.serverSetAcpRegistryProvider]: AuthProvidersManageScope,
93 [WS_METHODS.serverDisableAcpRegistryProvider]: AuthProvidersManageScope,
94 [WS_METHODS.serverLogoutAcpRegistry]: AuthProvidersManageScope,
95 [WS_METHODS.serverDiscoverSourceControl]: AuthOrchestrationReadScope,
96 [WS_METHODS.serverGetTraceDiagnostics]: AuthDiagnosticsReadScope,
97 [WS_METHODS.serverGetProcessDiagnostics]: AuthDiagnosticsReadScope,
98 // Load-balancing new threads reads host load; that is part of operating
99 // threads, not of inspecting diagnostics.
100 [WS_METHODS.serverGetHostResources]: AuthOrchestrationReadScope,
101 [WS_METHODS.serverGetProcessResourceHistory]: AuthDiagnosticsReadScope,
102 [WS_METHODS.serverGetResourceTelemetryHistory]: AuthDiagnosticsReadScope,
103 [WS_METHODS.serverRetryResourceTelemetry]: AuthDiagnosticsReadScope,
104 [WS_METHODS.serverGetUsageSummary]: AuthDiagnosticsReadScope,
105 [WS_METHODS.serverRefreshUsageRates]: AuthDiagnosticsReadScope,
106 [WS_METHODS.serverSignalProcess]: AuthEnvironmentMaintainScope,
107 [WS_METHODS.serverReportClientActivity]: AuthOrchestrationReadScope,
108 [WS_METHODS.serverReportHostPowerState]: AuthEnvironmentMaintainScope,
109 [WS_METHODS.serverGetBackgroundPolicy]: AuthOrchestrationReadScope,
110 [WS_METHODS.scheduledTasksList]: AuthOrchestrationReadScope,
111 [WS_METHODS.scheduledTasksSubscribe]: AuthOrchestrationReadScope,
112 [WS_METHODS.secretsAnswerRequest]: AuthOrchestrationOperateScope,
113 // Delivery logs hold request bodies, so they need the same scope as the URL.
114 [WS_METHODS.scheduledTasksListWebhookDeliveries]: AuthOrchestrationOperateScope,
115 [WS_METHODS.scheduledTasksGetWebhookDelivery]: AuthOrchestrationOperateScope,
116 [WS_METHODS.cloudGetRelayClientStatus]: AuthRelayReadScope,
117 [WS_METHODS.cloudInstallRelayClient]: AuthRelayWriteScope,
118 [WS_METHODS.pullRequestsList]: AuthOrchestrationReadScope,
119 [WS_METHODS.pullRequestsListStats]: AuthOrchestrationReadScope,
120 [WS_METHODS.pullRequestsSummary]: AuthOrchestrationReadScope,
121 [WS_METHODS.pullRequestsRouting]: AuthOrchestrationReadScope,
122 [WS_METHODS.pullRequestsRoutingIdentity]: AuthOrchestrationReadScope,
123 [WS_METHODS.pullRequestsStack]: AuthOrchestrationReadScope,
124 [WS_METHODS.pullRequestsLinkedThreads]: AuthOrchestrationReadScope,
125 [WS_METHODS.pullRequestsDetail]: AuthOrchestrationReadScope,
126 [WS_METHODS.pullRequestsPreview]: AuthOrchestrationReadScope,
127 [WS_METHODS.pullRequestsChecks]: AuthOrchestrationReadScope,
128 [WS_METHODS.pullRequestsActivity]: AuthOrchestrationReadScope,
129 [WS_METHODS.pullRequestsThreadComments]: AuthOrchestrationReadScope,
130 [WS_METHODS.pullRequestsDiffFileContents]: AuthOrchestrationReadScope,
131 [WS_METHODS.pullRequestsFilesViewed]: AuthOrchestrationReadScope,
132 // Read scope like the reads it un-caches: refreshing is part of reading, and a read-only
133 // client pressing refresh must not be told it may not look again.
134 [WS_METHODS.pullRequestsInvalidate]: AuthOrchestrationReadScope,
135 [WS_METHODS.pullRequestsSubscribeRefreshes]: AuthOrchestrationReadScope,
136 // The candidate list is a read like the detail beside it; asking somebody for a review is a
137 // write like every other one.
138 [WS_METHODS.pullRequestsReviewerCandidates]: AuthOrchestrationReadScope,
139 [WS_METHODS.pullRequestsLabelCandidates]: AuthOrchestrationReadScope,
140 [WS_METHODS.sourceControlLookupRepository]: AuthOrchestrationReadScope,
141 [WS_METHODS.subscribeProjectClones]: AuthOrchestrationReadScope,
142 [WS_METHODS.projectsListEntries]: AuthFilesystemReadScope,
143 [WS_METHODS.projectsReadFile]: AuthFilesystemReadScope,
144 [WS_METHODS.projectsSearchContents]: AuthFilesystemReadScope,
145 [WS_METHODS.projectsSearchEntries]: AuthFilesystemReadScope,
146 [WS_METHODS.projectsWriteFile]: AuthFilesystemWriteScope,
147 [WS_METHODS.projectsEnsureScratch]: AuthOrchestrationOperateScope,
148 [WS_METHODS.projectsCreateNew]: AuthOrchestrationOperateScope,
149 [WS_METHODS.shellOpenInEditor]: AuthOrchestrationOperateScope,
150 [WS_METHODS.filesystemBrowse]: AuthFilesystemReadScope,
151 [WS_METHODS.agentSessionsScan]: AuthOrchestrationReadScope,
152 [WS_METHODS.agentSessionsImport]: AuthOrchestrationOperateScope,
153 [WS_METHODS.assetsCreateUrl]: AuthOrchestrationReadScope,
154 [WS_METHODS.assetsPersistChatAttachments]: AuthOrchestrationOperateScope,
155 [WS_METHODS.attachmentsCreateUploadUrl]: AuthOrchestrationOperateScope,
156 [WS_METHODS.attachmentsDelete]: AuthOrchestrationOperateScope,
157 [WS_METHODS.providerUploadFeedback]: AuthOrchestrationOperateScope,
158 [WS_METHODS.subscribeVcsStatus]: AuthOrchestrationReadScope,
159 [WS_METHODS.subscribeWorktreeSetup]: AuthOrchestrationReadScope,
160 [WS_METHODS.worktreeSetupCancel]: AuthOrchestrationOperateScope,
161 [WS_METHODS.subscribeResourceTelemetry]: AuthDiagnosticsReadScope,
162 [WS_METHODS.vcsRefreshStatus]: AuthOrchestrationReadScope,
163 [WS_METHODS.gitResolvePullRequest]: AuthOrchestrationReadScope,
164 [WS_METHODS.vcsListRefs]: AuthOrchestrationReadScope,
165 [WS_METHODS.reviewGetDiffPreview]: AuthFilesystemReadScope,
166 [WS_METHODS.reviewGetDiffFileContents]: AuthFilesystemReadScope,
167 [WS_METHODS.terminalOpen]: AuthTerminalOperateScope,
168 [WS_METHODS.terminalAttach]: AuthTerminalOperateScope,
169 [WS_METHODS.terminalObserve]: AuthTerminalReadScope,
170 [WS_METHODS.terminalWrite]: AuthTerminalOperateScope,
171 [WS_METHODS.terminalResize]: AuthTerminalOperateScope,
172 [WS_METHODS.terminalClear]: AuthTerminalOperateScope,
173 [WS_METHODS.terminalRestart]: AuthTerminalOperateScope,
174 [WS_METHODS.terminalClose]: AuthTerminalOperateScope,
175 [WS_METHODS.subscribeTerminalEvents]: AuthTerminalReadScope,
176 [WS_METHODS.subscribeTerminalMetadata]: AuthTerminalReadScope,
177 [WS_METHODS.previewOpen]: AuthPreviewOperateScope,
178 [WS_METHODS.previewNavigate]: AuthPreviewOperateScope,
179 [WS_METHODS.previewResize]: AuthPreviewOperateScope,
180 [WS_METHODS.previewAdjust]: AuthPreviewOperateScope,
181 [WS_METHODS.previewRefresh]: AuthPreviewOperateScope,
182 [WS_METHODS.previewClose]: AuthPreviewOperateScope,
183 [WS_METHODS.previewList]: AuthOrchestrationReadScope,
184 [WS_METHODS.previewClearProfile]: AuthPreviewOperateScope,
185 [WS_METHODS.previewReportStatus]: AuthPreviewOperateScope,
186 [WS_METHODS.subscribePreviewEvents]: AuthOrchestrationReadScope,
187 [WS_METHODS.subscribeDiscoveredLocalServers]: AuthOrchestrationReadScope,
188 [WS_METHODS.deviceConfigure]: AuthSettingsWriteScope,
189 [WS_METHODS.deviceTestHost]: AuthSettingsWriteScope,
190 [WS_METHODS.deviceList]: AuthOrchestrationReadScope,
191 [WS_METHODS.deviceOpen]: AuthOrchestrationOperateScope,
192 [WS_METHODS.deviceClose]: AuthOrchestrationOperateScope,
193 [WS_METHODS.deviceShutdown]: AuthOrchestrationOperateScope,
194 [WS_METHODS.deviceDetail]: AuthOrchestrationReadScope,
195 [WS_METHODS.deviceAction]: AuthOrchestrationOperateScope,
196 [WS_METHODS.subscribeDeviceState]: AuthOrchestrationReadScope,
197 [WS_METHODS.subscribeServerConfig]: AuthOrchestrationReadScope,
198 [WS_METHODS.subscribeServerLifecycle]: AuthOrchestrationReadScope,
199 [WS_METHODS.subscribeAuthAccess]: AuthAccessReadScope,
200 [WS_METHODS.subscribeBackgroundPolicy]: AuthOrchestrationReadScope,
201} as const satisfies Readonly<Record<WsRpcMethod, AuthEnvironmentScope>>;
202​
203export function requiredScopeForRpcMethod(method: string): AuthEnvironmentScope {
204 if (!Object.hasOwn(RPC_REQUIRED_SCOPES, method)) {
205 throw new Error(`RPC method ${method} has no declared authorization scope.`);
206 }
207 const requiredScope = RPC_REQUIRED_SCOPES[method as WsRpcMethod];
208 if (requiredScope === undefined) {
209 throw new Error(`RPC method ${method} has no declared authorization scope.`);
210 }
211 return requiredScope;
213​
214export const rpcAuthorizationError = (requiredScope: AuthEnvironmentScope) =>
215 new EnvironmentAuthorizationError({
216 message: `The authenticated token is missing required scope: ${requiredScope}.`,
217 ...authScopeRequiredResponse(requiredScope),
218 });
219​
220const SettingsUpdate = Schema.Struct({
221 patch: ServerSettingsPatch,
222 providerInstanceMutation: Schema.optionalKey(ProviderInstanceMutation),
223});
224​
225const requiredScopesForSettingsUpdate = (payload: unknown) => {
226 const input = Schema.decodeUnknownSync(SettingsUpdate)(payload);
227 const scopes = requiredScopesForServerSettingsPatch(input.patch);
228 if (input.providerInstanceMutation === undefined) return scopes;
229 // An atomic provider mutation carries an empty patch unless it also changes settings.
230 return Object.values(input.patch).every((value) => value === undefined)
231 ? [AuthProvidersManageScope]
232 : [...new Set([...scopes, AuthProvidersManageScope])];
233};
234​
235const requiredScopesForRpcCall = (
236 method: string,
237 payload: unknown,
238): ReadonlyArray<AuthEnvironmentScope> => {
239 if (method === WS_METHODS.serverRetryResourceTelemetry) {
240 return [AuthEnvironmentMaintainScope, AuthDiagnosticsReadScope];
241 }
242 if (method === WS_METHODS.assetsCreateUrl) {
243 const { resource } = Schema.decodeUnknownSync(AssetCreateUrlInput)(payload);
244 return [
245 resource._tag === "workspace-file" ||
246 resource._tag === "media-file" ||
247 resource._tag === "draft-workspace-file"
248 ? AuthFilesystemReadScope
249 : AuthOrchestrationReadScope,
250 ];
251 }
252 if (method === WS_METHODS.serverUpdateSettings) return requiredScopesForSettingsUpdate(payload);
253 const guarded = clientRpcRequiredScopes(method, payload);
254 if (guarded.length > 0) return guarded;
255 return [requiredScopeForRpcMethod(method)];
256};
257​
258/** Authorizes every RPC on one connection against that connection's session scopes. */
259export const layer = (scopes: ReadonlyArray<AuthEnvironmentScope>) =>
260 Layer.succeed(RpcScopeAuthorization)((effect, { rpc, payload }) => {
261 const requiredScopes = requiredScopesForRpcCall(rpc._tag, payload);
262 const requiredScope = requiredScopes.find((scope) => !scopes.includes(scope));
263 return requiredScope === undefined ? effect : Effect.fail(rpcAuthorizationError(requiredScope));
264 });
265​
266/** Retrying can install or restart tools even though ordinary listing is readable. */
267export const requiredScopeForDeviceList = (input: DeviceListInput): AuthEnvironmentScope =>
268 input.retryHostId || input.updateTool
269 ? AuthOrchestrationOperateScope
270 : AuthOrchestrationReadScope;