The best way to control Claude Code, Codex and more from any computer or phone

main
ts 385 lines 13.3 KB
Raw
1 import * as agentidentity from "@distilled.cloud/gcp/agentidentity_v1";
2 import { Unowned } from "alchemy/AdoptPolicy";
3 import { isResolved } from "alchemy/Diff";
4 import * as Provider from "alchemy/Provider";
5 import { Resource } from "alchemy/Resource";
6 import { tagRecord } from "alchemy/Tags";
7 import * as Effect from "effect/Effect";
8 import { GcpEnvironment } from "../Environment.ts";
9 import { createInternalLabels, diffLabels, hasAlchemyLabels, toLabels } from "../Labels.ts";
10 import type { Providers } from "../Providers.ts";
11 import {
12 AuthProviderNotResolved,
13 clipDescription,
14 fieldMask,
15 fingerprint,
16 getByName,
17 hasSecretUpdate,
18 listOwned,
19 normalizeLocation,
20 parseName,
21 publicTypeParams,
22 resourceName,
23 sameStringList,
24 sameText,
25 toPhysicalId,
26 toTypeParams,
27 typeParamsBody,
28 userLabels,
29 type ApiKeyParams,
30 type AuthProviderTypeParams,
31 type ThreeLeggedOAuthParams,
32 type TwoLeggedOAuthParams,
33 } from "./internal.ts";
34
35 export type { ApiKeyParams, AuthProviderTypeParams, ThreeLeggedOAuthParams, TwoLeggedOAuthParams };
36
37 export type AuthProviderProps = {
38 /**
39 * Auth provider id (the `{auth_provider}` segment of
40 * `projects/{project}/locations/{location}/authProviders/{auth_provider}`).
41 * If omitted, a unique RFC1035 name is generated. Must be 1-63
42 * characters, start with a lowercase letter, and use only `a-z` and
43 * `-`. Immutable — changing it replaces the auth provider.
44 */
45 authProviderId?: string;
46 /**
47 * Location of the auth provider. Immutable — changing it replaces the
48 * auth provider.
49 * @default the stack's GCP region (`GCP.Region`, profile region, `us-central1`)
50 */
51 location?: string;
52 /**
53 * Human-readable description (max 256 characters).
54 */
55 description?: string;
56 /**
57 * Scopes that may be requested. Empty or omitted allows every scope
58 * except those in `blockedScopes`. At most 200 entries.
59 */
60 allowedScopes?: string[];
61 /**
62 * Scopes that must not be requested. Takes precedence over
63 * `allowedScopes`. At most 200 entries.
64 */
65 blockedScopes?: string[];
66 /**
67 * Workload identities (`principal://…`) of the agents that use this
68 * auth provider. Input-only — omitted from attributes.
69 */
70 workloadIds?: string[];
71 /**
72 * When true, the auth provider is disabled via `:disable`. Defaults to
73 * enabled.
74 * @default false
75 */
76 disabled?: boolean;
77 /**
78 * Auth method parameters. Required on create. Exactly one of
79 * `threeLeggedOauth`, `twoLeggedOauth`, `apiKey`, or `geAuthProvider`
80 * should be set. Client secrets and API keys are input-only.
81 */
82 authProviderTypeParams: AuthProviderTypeParams;
83 /**
84 * User labels. Alchemy ownership labels are merged in automatically.
85 */
86 labels?: Record<string, string>;
87 };
88
89 export type AuthProvider = Resource<
90 "GCP.AgentIdentity.AuthProvider",
91 AuthProviderProps,
92 {
93 /** Full resource name `projects/{project}/locations/{location}/authProviders/{auth_provider}`. */
94 name: string;
95 /** Auth provider id (last path segment). */
96 authProviderId: string;
97 /** Project id. */
98 project: string;
99 /** Location id (`us-central1`, …). */
100 location: string;
101 /** Human-readable description. */
102 description: string | undefined;
103 /** Allowed OAuth scopes. */
104 allowedScopes: string[];
105 /** Blocked OAuth scopes. */
106 blockedScopes: string[];
107 /** User labels (Alchemy ownership labels stripped). */
108 labels: Record<string, string>;
109 /** Public auth method parameters (secrets stripped). */
110 authProviderTypeParams: AuthProviderTypeParams | undefined;
111 /** Server-reported state (`ENABLED`, `DISABLED`, …). */
112 state: string | undefined;
113 /** Whether the auth provider is disabled. */
114 disabled: boolean;
115 /** RFC3339 time the auth provider expires, if any. */
116 expireTime: string | undefined;
117 /** RFC3339 creation timestamp. */
118 createTime: string | undefined;
119 /** RFC3339 last-update timestamp. */
120 updateTime: string | undefined;
121 },
122 never,
123 Providers
124 >;
125
126 /**
127 * An Agent Identity auth provider — the credential configuration agents
128 * use to call third-party APIs (API keys, 2LO, or 3LO OAuth).
129 *
130 * `authProviderId` and `location` replace the resource. Description,
131 * labels, scopes, type parameters, and enabled/disabled update in place.
132 *
133 * ### Creating an Auth Provider
134 * **Example:** API key
135 * ```typescript
136 * const auth = yield* GCP.AgentIdentity.AuthProvider("Maps", {
137 * authProviderTypeParams: {
138 * apiKey: { apiKey: "maps-api-key" },
139 * },
140 * labels: { env: "prod" },
141 * });
142 * ```
143 *
144 * **Example:** Three-legged OAuth
145 * ```typescript
146 * const auth = yield* GCP.AgentIdentity.AuthProvider("Atlassian", {
147 * authProviderTypeParams: {
148 * threeLeggedOauth: {
149 * clientId: "jira-client",
150 * clientSecret: "jira-secret",
151 * authorizationUrl: "https://auth.atlassian.com/authorize",
152 * tokenUrl: "https://auth.atlassian.com/oauth/token",
153 * enablePkce: true,
154 * },
155 * },
156 * allowedScopes: ["read:jira-work"],
157 * labels: { env: "prod" },
158 * });
159 * ```
160 *
161 * ### Updating an Auth Provider
162 * **Example:** Description and labels
163 * ```typescript
164 * const auth = yield* GCP.AgentIdentity.AuthProvider("Maps", {
165 * authProviderId: "maps",
166 * authProviderTypeParams: {
167 * apiKey: { apiKey: "maps-api-key" },
168 * },
169 * description: "Maps API key for agents",
170 * labels: { env: "prod", role: "maps" },
171 * });
172 * ```
173 *
174 * @resource
175 * @category AgentIdentity
176 */
177 export const AuthProvider = Resource<AuthProvider>("GCP.AgentIdentity.AuthProvider");
178
179 export { AuthProviderNotResolved };
180
181 const toAttrs = (item: agentidentity.AuthProvider, project: string, region: string) => {
182 const name = item.name ?? "";
183 const parsed = parseName(name, region);
184 const state = item.state;
185 return {
186 name,
187 authProviderId: parsed.authProviderId,
188 project: parsed.project || project,
189 location: parsed.location,
190 description: item.description,
191 allowedScopes: item.allowedScopes ?? [],
192 blockedScopes: item.blockedScopes ?? [],
193 labels: userLabels(item.labels),
194 authProviderTypeParams: toTypeParams(item.authProviderTypeParams),
195 state,
196 disabled: state === "DISABLED",
197 expireTime: item.expireTime,
198 createTime: item.createTime,
199 updateTime: item.updateTime,
200 };
201 };
202
203 const replaceOnIdentity = (input: {
204 previousId: string | undefined;
205 nextId: string | undefined;
206 previousLocation: string;
207 nextLocation: string;
208 }) => {
209 const idChanged =
210 input.previousId !== undefined &&
211 input.nextId !== undefined &&
212 input.nextId !== input.previousId;
213 const locationChanged = input.previousLocation !== input.nextLocation;
214 if (!idChanged && !locationChanged) return undefined;
215 return {
216 action: "replace" as const,
217 deleteFirst:
218 locationChanged &&
219 !idChanged &&
220 input.previousId !== undefined &&
221 input.nextId === input.previousId,
222 };
223 };
224
225 export const AuthProviderProvider = () =>
226 Provider.succeed(AuthProvider, {
227 stables: ["name", "authProviderId", "project", "location", "createTime"],
228
229 diff: Effect.fn(function* ({ news, olds, output }) {
230 if (!isResolved(news)) return undefined;
231 const env = yield* GcpEnvironment.current;
232 return replaceOnIdentity({
233 previousId: olds?.authProviderId ?? output?.authProviderId,
234 nextId: news.authProviderId ?? olds?.authProviderId ?? output?.authProviderId,
235 previousLocation: normalizeLocation(olds?.location ?? output?.location, env.region),
236 nextLocation: normalizeLocation(
237 news.location ?? olds?.location ?? output?.location,
238 env.region,
239 ),
240 });
241 }),
242
243 read: Effect.fn(function* ({ id, olds, output }) {
244 const env = yield* GcpEnvironment.current;
245 const authProviderId = yield* toPhysicalId(id, olds?.authProviderId, output?.authProviderId);
246 const location = normalizeLocation(olds?.location ?? output?.location, env.region);
247 const name = output?.name ?? resourceName(env.project, location, authProviderId);
248 const existing = yield* getByName(name);
249 if (existing === undefined || existing.deleted === true) {
250 return undefined;
251 }
252 const attrs = toAttrs(existing, env.project, env.region);
253 return (yield* hasAlchemyLabels(id, tagRecord(existing.labels))) ? attrs : Unowned(attrs);
254 }),
255
256 list: () =>
257 Effect.gen(function* () {
258 const env = yield* GcpEnvironment.current;
259 const items = yield* listOwned(env.project, env.region);
260 return items.map((item) => toAttrs(item, env.project, env.region));
261 }),
262
263 reconcile: Effect.fn(function* ({ id, news, olds, output }) {
264 const env = yield* GcpEnvironment.current;
265 const authProviderId = yield* toPhysicalId(id, news.authProviderId, output?.authProviderId);
266 const location = normalizeLocation(news.location ?? output?.location, env.region);
267 const name = resourceName(env.project, location, authProviderId);
268 const desiredLabels = {
269 ...toLabels(news.labels),
270 ...(yield* createInternalLabels(id)),
271 };
272 const description = clipDescription(news.description);
273 const allowedScopes = news.allowedScopes ?? [];
274 const blockedScopes = news.blockedScopes ?? [];
275 const workloadIds = news.workloadIds;
276 const typeParams = typeParamsBody(news.authProviderTypeParams);
277
278 let current = yield* getByName(output?.name ?? name);
279
280 if (current !== undefined && current.deleted === true) {
281 current = yield* agentidentity
282 .undeleteProjectsLocationsAuthProviders({
283 name: current.name ?? name,
284 body: {},
285 })
286 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
287 }
288
289 if (current === undefined) {
290 const created = yield* agentidentity
291 .createProjectsLocationsAuthProviders({
292 parent: `projects/${env.project}/locations/${location}`,
293 authProviderId,
294 body: {
295 labels: desiredLabels,
296 description,
297 allowedScopes: allowedScopes.length > 0 ? allowedScopes : undefined,
298 blockedScopes: blockedScopes.length > 0 ? blockedScopes : undefined,
299 workloadIds:
300 workloadIds !== undefined && workloadIds.length > 0 ? workloadIds : undefined,
301 authProviderTypeParams: typeParams,
302 },
303 })
304 .pipe(Effect.catchTag("Conflict", () => getByName(output?.name ?? name)));
305 current = created ?? undefined;
306 }
307
308 if (current === undefined) {
309 return yield* new AuthProviderNotResolved({ resourceName: name });
310 }
311
312 const resource = current.name ?? name;
313 if (current.deleted === true) {
314 current = yield* agentidentity.undeleteProjectsLocationsAuthProviders({
315 name: resource,
316 body: {},
317 });
318 }
319
320 const observedLabels = tagRecord(current.labels);
321 const { upsert, removed } = diffLabels(observedLabels, desiredLabels);
322 const labelsChanged = upsert.length > 0 || removed.length > 0;
323 const descriptionChanged = !sameText(current.description, description);
324 const allowedChanged = !sameStringList(current.allowedScopes, allowedScopes);
325 const blockedChanged = !sameStringList(current.blockedScopes, blockedScopes);
326 const observedTypeParams = publicTypeParams(toTypeParams(current.authProviderTypeParams));
327 const desiredTypeParams = publicTypeParams(news.authProviderTypeParams);
328 const typeParamsChanged =
329 (observedTypeParams !== undefined &&
330 fingerprint(observedTypeParams) !== fingerprint(desiredTypeParams)) ||
331 hasSecretUpdate(news.authProviderTypeParams, olds?.authProviderTypeParams);
332 const workloadChanged =
333 workloadIds !== undefined &&
334 olds !== undefined &&
335 !sameStringList(olds.workloadIds, workloadIds);
336
337 const mask = fieldMask([
338 labelsChanged && "labels",
339 descriptionChanged && "description",
340 allowedChanged && "allowedScopes",
341 blockedChanged && "blockedScopes",
342 typeParamsChanged && "authProviderTypeParams",
343 workloadChanged && "workloadIds",
344 ]);
345
346 if (mask.length > 0) {
347 current = yield* agentidentity.patchProjectsLocationsAuthProviders({
348 name: resource,
349 updateMask: mask,
350 body: {
351 name: resource,
352 labels: desiredLabels,
353 description,
354 allowedScopes,
355 blockedScopes,
356 workloadIds,
357 authProviderTypeParams: typeParams,
358 },
359 });
360 }
361
362 const desiredDisabled = news.disabled === true;
363 const observedDisabled = current.state === "DISABLED";
364 if (desiredDisabled && !observedDisabled) {
365 current = yield* agentidentity.disableProjectsLocationsAuthProviders({
366 name: current.name ?? resource,
367 body: {},
368 });
369 } else if (!desiredDisabled && observedDisabled) {
370 current = yield* agentidentity.enableProjectsLocationsAuthProviders({
371 name: current.name ?? resource,
372 body: {},
373 });
374 }
375
376 return toAttrs(current, env.project, env.region);
377 }),
378
379 delete: Effect.fn(function* ({ output }) {
380 if (output.name.length === 0) return;
381 yield* agentidentity
382 .deleteProjectsLocationsAuthProviders({ name: output.name })
383 .pipe(Effect.catchTag("NotFound", () => Effect.void));
384 }),
385 });