@devries-cameron20 / t3code Mirror · read-only
Fork 0

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

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
ts 407 lines 14.5 KB
Raw
1 import * as avp from "@distilled.cloud/aws/verifiedpermissions";
2 import { isResolved } from "alchemy/Diff";
3 import * as Provider from "alchemy/Provider";
4 import { Resource } from "alchemy/Resource";
5 import * as Effect from "effect/Effect";
6 import * as Redacted from "effect/Redacted";
7 import * as Schedule from "effect/Schedule";
8 import type { Providers } from "../Providers.ts";
9
10 const unwrap = (v: string | Redacted.Redacted<string> | undefined) =>
11 v === undefined ? undefined : Redacted.isRedacted(v) ? Redacted.value(v) : v;
12
13 const unwrapAll = (vs: readonly (string | Redacted.Redacted<string>)[] | undefined) =>
14 vs === undefined ? undefined : vs.map((v) => unwrap(v)!);
15
16 /** Sorted copy, with empty/absent arrays collapsing to `undefined`. */
17 const sortedOrUndefined = (vs: readonly string[] | undefined) =>
18 vs === undefined || vs.length === 0 ? undefined : [...vs].sort();
19
20 /**
21 * Identity-source configuration backed by an Amazon Cognito user pool.
22 */
23 export interface CognitoUserPoolConfiguration {
24 /**
25 * ARN of the Cognito user pool whose identities should be usable as
26 * principals in authorization requests.
27 */
28 userPoolArn: string;
29 /**
30 * The user pool app client IDs to accept tokens from. When omitted, tokens
31 * from any of the pool's app clients are accepted.
32 */
33 clientIds?: string[];
34 /**
35 * The Cedar entity type to map Cognito groups to (e.g.
36 * `PhotoApp::UserGroup`). Enables group claims in policies.
37 */
38 groupEntityType?: string;
39 }
40
41 /**
42 * Identity-source configuration backed by a generic OpenID Connect (OIDC)
43 * identity provider.
44 */
45 export interface OpenIdConnectConfiguration {
46 /**
47 * The issuer URL of the OIDC provider, e.g. `https://accounts.google.com`.
48 * Verified Permissions fetches `/.well-known/openid-configuration` from
49 * this URL at creation time.
50 */
51 issuer: string;
52 /**
53 * A prefix prepended to the user ID taken from the token, producing entity
54 * IDs like `MyOIDCProvider|user-id`.
55 */
56 entityIdPrefix?: string;
57 /**
58 * Map a token group claim onto a Cedar entity type so policies can match
59 * on group membership.
60 */
61 groupConfiguration?: {
62 /** The token claim that lists the user's groups, e.g. `groups`. */
63 groupClaim: string;
64 /** The Cedar entity type groups map to, e.g. `PhotoApp::UserGroup`. */
65 groupEntityType: string;
66 };
67 /**
68 * Which token type the identity source consumes — exactly one of
69 * `accessTokenOnly` or `identityTokenOnly`.
70 */
71 tokenSelection:
72 | {
73 /** Consume OIDC access tokens. */
74 accessTokenOnly: {
75 /** The claim to derive the principal entity ID from. @default "sub" */
76 principalIdClaim?: string;
77 /** The `aud` values to accept tokens for. */
78 audiences?: string[];
79 };
80 identityTokenOnly?: never;
81 }
82 | {
83 accessTokenOnly?: never;
84 /** Consume OIDC identity (ID) tokens. */
85 identityTokenOnly: {
86 /** The claim to derive the principal entity ID from. @default "sub" */
87 principalIdClaim?: string;
88 /** The client IDs (`aud`) to accept tokens for. */
89 clientIds?: string[];
90 };
91 };
92 }
93
94 /**
95 * Exactly one of a Cognito user pool or an OIDC provider configuration.
96 */
97 export type IdentitySourceConfiguration =
98 | {
99 /** Use an Amazon Cognito user pool as the identity provider. */
100 cognito: CognitoUserPoolConfiguration;
101 openIdConnect?: never;
102 }
103 | {
104 cognito?: never;
105 /** Use a generic OpenID Connect provider as the identity provider. */
106 openIdConnect: OpenIdConnectConfiguration;
107 };
108
109 export type IdentitySourceProps = IdentitySourceConfiguration & {
110 /**
111 * The ID of the policy store the identity source belongs to. Changing the
112 * store replaces the identity source.
113 */
114 policyStoreId: string;
115 /**
116 * The Cedar entity type that tokens from this identity source map to, e.g.
117 * `PhotoApp::User`. Mutable via `UpdateIdentitySource`.
118 */
119 principalEntityType?: string;
120 };
121
122 export interface IdentitySource extends Resource<
123 "AWS.VerifiedPermissions.IdentitySource",
124 IdentitySourceProps,
125 {
126 /**
127 * ID of the policy store the identity source belongs to.
128 */
129 policyStoreId: string;
130 /**
131 * Service-assigned unique ID of the identity source within the store.
132 */
133 identitySourceId: string;
134 },
135 {},
136 Providers
137 > {}
138
139 /**
140 * An identity source connects a Verified Permissions policy store to an
141 * identity provider — an Amazon Cognito user pool or any OpenID Connect
142 * (OIDC) IdP — so that `IsAuthorizedWithToken` and
143 * `BatchIsAuthorizedWithToken` can derive the principal directly from a JWT.
144 * ### Connecting an Identity Provider
145 * **Example:** Cognito User Pool
146 * ```typescript
147 * import * as AWS from "@alchemy.run/aws";
148 *
149 * const store = yield* AWS.VerifiedPermissions.PolicyStore("Store", {});
150 *
151 * yield* AWS.VerifiedPermissions.IdentitySource("Users", {
152 * policyStoreId: store.policyStoreId,
153 * principalEntityType: "PhotoApp::User",
154 * cognito: {
155 * userPoolArn: userPool.userPoolArn,
156 * },
157 * });
158 * ```
159 *
160 * **Example:** OpenID Connect Provider
161 * ```typescript
162 * yield* AWS.VerifiedPermissions.IdentitySource("Oidc", {
163 * policyStoreId: store.policyStoreId,
164 * principalEntityType: "PhotoApp::User",
165 * openIdConnect: {
166 * issuer: "https://accounts.google.com",
167 * tokenSelection: {
168 * identityTokenOnly: { clientIds: ["my-oauth-client-id"] },
169 * },
170 * },
171 * });
172 * ```
173 *
174 * @resource
175 */
176 export const IdentitySource = Resource<IdentitySource>("AWS.VerifiedPermissions.IdentitySource");
177
178 /** Desired props → the wire `Configuration` union. */
179 const toConfiguration = (news: IdentitySourceProps): avp.Configuration =>
180 news.cognito !== undefined
181 ? {
182 cognitoUserPoolConfiguration: {
183 userPoolArn: news.cognito.userPoolArn,
184 clientIds: news.cognito.clientIds,
185 groupConfiguration:
186 news.cognito.groupEntityType === undefined
187 ? undefined
188 : { groupEntityType: news.cognito.groupEntityType },
189 },
190 }
191 : {
192 openIdConnectConfiguration: {
193 issuer: news.openIdConnect.issuer,
194 entityIdPrefix: news.openIdConnect.entityIdPrefix,
195 groupConfiguration: news.openIdConnect.groupConfiguration,
196 tokenSelection: news.openIdConnect.tokenSelection,
197 },
198 };
199
200 /**
201 * Observed `ConfigurationDetail` → the plain props shape, for diffing the
202 * desired configuration against what is actually deployed.
203 */
204 const toObservedConfiguration = (
205 detail: avp.ConfigurationDetail | undefined,
206 ): IdentitySourceConfiguration | undefined => {
207 if (detail === undefined) return undefined;
208 if (detail.cognitoUserPoolConfiguration !== undefined) {
209 const cognito = detail.cognitoUserPoolConfiguration;
210 return {
211 cognito: {
212 userPoolArn: cognito.userPoolArn,
213 clientIds: unwrapAll(cognito.clientIds),
214 groupEntityType: unwrap(cognito.groupConfiguration?.groupEntityType),
215 },
216 };
217 }
218 const oidc = detail.openIdConnectConfiguration;
219 return {
220 openIdConnect: {
221 issuer: oidc.issuer,
222 entityIdPrefix: unwrap(oidc.entityIdPrefix),
223 groupConfiguration:
224 oidc.groupConfiguration === undefined
225 ? undefined
226 : {
227 groupClaim: unwrap(oidc.groupConfiguration.groupClaim)!,
228 groupEntityType: unwrap(oidc.groupConfiguration.groupEntityType)!,
229 },
230 tokenSelection:
231 oidc.tokenSelection.accessTokenOnly !== undefined
232 ? {
233 accessTokenOnly: {
234 principalIdClaim: unwrap(oidc.tokenSelection.accessTokenOnly.principalIdClaim),
235 audiences: oidc.tokenSelection.accessTokenOnly.audiences
236 ? [...oidc.tokenSelection.accessTokenOnly.audiences]
237 : undefined,
238 },
239 }
240 : {
241 identityTokenOnly: {
242 principalIdClaim: unwrap(oidc.tokenSelection.identityTokenOnly.principalIdClaim),
243 clientIds: unwrapAll(oidc.tokenSelection.identityTokenOnly.clientIds),
244 },
245 },
246 },
247 };
248 };
249
250 /**
251 * Canonicalize + serialize a configuration for drift comparison: arrays are
252 * sorted (empty ≡ absent) and AWS-filled defaults (`principalIdClaim: "sub"`)
253 * are applied so an untouched deploy is a no-op.
254 */
255 const normalize = (config: IdentitySourceConfiguration): string => {
256 const canonical =
257 config.cognito !== undefined
258 ? {
259 cognito: {
260 userPoolArn: config.cognito.userPoolArn,
261 clientIds: sortedOrUndefined(config.cognito.clientIds),
262 groupEntityType: config.cognito.groupEntityType,
263 },
264 }
265 : {
266 openIdConnect: {
267 issuer: config.openIdConnect.issuer,
268 entityIdPrefix: config.openIdConnect.entityIdPrefix,
269 groupConfiguration: config.openIdConnect.groupConfiguration,
270 tokenSelection:
271 config.openIdConnect.tokenSelection.accessTokenOnly !== undefined
272 ? {
273 accessTokenOnly: {
274 principalIdClaim:
275 config.openIdConnect.tokenSelection.accessTokenOnly.principalIdClaim ??
276 "sub",
277 audiences: sortedOrUndefined(
278 config.openIdConnect.tokenSelection.accessTokenOnly.audiences,
279 ),
280 },
281 }
282 : {
283 identityTokenOnly: {
284 principalIdClaim:
285 config.openIdConnect.tokenSelection.identityTokenOnly.principalIdClaim ??
286 "sub",
287 clientIds: sortedOrUndefined(
288 config.openIdConnect.tokenSelection.identityTokenOnly.clientIds,
289 ),
290 },
291 },
292 },
293 };
294 return JSON.stringify(canonical);
295 };
296
297 /** Desired props → the wire `UpdateConfiguration` union (same field shapes). */
298 const toUpdateConfiguration = (news: IdentitySourceProps): avp.UpdateConfiguration =>
299 toConfiguration(news) as avp.UpdateConfiguration;
300
301 export const IdentitySourceProvider = () =>
302 Provider.effect(
303 IdentitySource,
304 Effect.gen(function* () {
305 const observe = Effect.fn(function* (policyStoreId: string, identitySourceId: string) {
306 return yield* avp
307 .getIdentitySource({ policyStoreId, identitySourceId })
308 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined));
309 });
310
311 return IdentitySource.Provider.of({
312 stables: ["policyStoreId", "identitySourceId"],
313
314 // child of a policy store — not enumerable account-wide
315 list: () => Effect.succeed([]),
316
317 read: Effect.fn(function* ({ olds, output }) {
318 const policyStoreId = output?.policyStoreId ?? olds?.policyStoreId;
319 const identitySourceId = output?.identitySourceId;
320 if (policyStoreId === undefined || identitySourceId === undefined) {
321 return undefined;
322 }
323 const source = yield* observe(policyStoreId, identitySourceId);
324 if (source === undefined) return undefined;
325 return { policyStoreId, identitySourceId: source.identitySourceId };
326 }),
327
328 diff: Effect.fn(function* ({ news, olds }) {
329 if (!isResolved(news)) return undefined;
330 if (olds.policyStoreId !== news.policyStoreId) {
331 return { action: "replace" } as const;
332 }
333 // configuration + principalEntityType are mutable via
334 // updateIdentitySource → default update path
335 }),
336
337 reconcile: Effect.fn(function* ({ news, output, session }) {
338 // 1. OBSERVE — cloud state is authoritative
339 const existing =
340 output?.identitySourceId !== undefined
341 ? yield* observe(news.policyStoreId, output.identitySourceId)
342 : undefined;
343
344 // 2. ENSURE — a freshly created policy store is eventually
345 // consistent; createIdentitySource can briefly 404 on it
346 if (existing === undefined) {
347 const created = yield* avp
348 .createIdentitySource({
349 policyStoreId: news.policyStoreId,
350 configuration: toConfiguration(news),
351 principalEntityType: news.principalEntityType,
352 })
353 .pipe(
354 Effect.retry({
355 while: (e): boolean => e._tag === "ResourceNotFoundException",
356 schedule: Schedule.max([Schedule.exponential("1 second"), Schedule.recurs(5)]),
357 }),
358 );
359 yield* session.note(created.identitySourceId);
360 return {
361 policyStoreId: news.policyStoreId,
362 identitySourceId: created.identitySourceId,
363 };
364 }
365
366 // 3. SYNC — diff observed configuration/principal type vs desired
367 const desired = normalize(
368 news.cognito !== undefined
369 ? { cognito: news.cognito }
370 : { openIdConnect: news.openIdConnect },
371 );
372 // If the response carries no configuration detail, we can't prove
373 // convergence — treat it as drift and (re)apply the desired config.
374 const observedConfiguration = toObservedConfiguration(existing.configuration);
375 const observed =
376 observedConfiguration === undefined ? undefined : normalize(observedConfiguration);
377 const observedPrincipalType = unwrap(existing.principalEntityType);
378 const principalDrift =
379 news.principalEntityType !== undefined &&
380 observedPrincipalType !== news.principalEntityType;
381 if (desired !== observed || principalDrift) {
382 yield* avp.updateIdentitySource({
383 policyStoreId: news.policyStoreId,
384 identitySourceId: existing.identitySourceId,
385 updateConfiguration: toUpdateConfiguration(news),
386 principalEntityType: news.principalEntityType,
387 });
388 }
389
390 yield* session.note(existing.identitySourceId);
391 return {
392 policyStoreId: news.policyStoreId,
393 identitySourceId: existing.identitySourceId,
394 };
395 }),
396
397 delete: Effect.fn(function* ({ output }) {
398 yield* avp
399 .deleteIdentitySource({
400 policyStoreId: output.policyStoreId,
401 identitySourceId: output.identitySourceId,
402 })
403 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.void));
404 }),
405 });
406 }),
407 );