@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, 06:00 UTC

main
ts 275 lines 10.6 KB
Raw
1 import * as signer from "@distilled.cloud/aws/signer";
2 import { isResolved } from "alchemy/Diff";
3 import { createPhysicalName } from "alchemy/PhysicalName";
4 import * as Provider from "alchemy/Provider";
5 import { Resource } from "alchemy/Resource";
6 import * as Effect from "effect/Effect";
7 import * as Schedule from "effect/Schedule";
8 import * as Stream from "effect/Stream";
9 import type { Providers } from "../Providers.ts";
10
11 export interface ProfilePermissionProps {
12 /**
13 * The name of the signing profile the permission is attached to.
14 * Changing it replaces the permission.
15 */
16 profileName: string;
17
18 /**
19 * The Signer action the principal is allowed to perform on the profile:
20 * `signer:StartSigningJob`, `signer:SignPayload`,
21 * `signer:GetSigningProfile`, or `signer:RevokeSignature`.
22 */
23 action: string;
24
25 /**
26 * The AWS principal (account id, or IAM user/role ARN) receiving
27 * cross-account permission to use the profile.
28 */
29 principal: string;
30
31 /**
32 * A unique statement id identifying this permission inside the profile's
33 * resource policy. If omitted, a deterministic id is generated from the
34 * logical id. Changing it replaces the permission.
35 */
36 statementId?: string;
37
38 /**
39 * The signing profile version the permission applies to. Omit to attach
40 * the permission to the profile as a whole.
41 */
42 profileVersion?: string;
43 }
44
45 export interface ProfilePermission extends Resource<
46 "AWS.Signer.ProfilePermission",
47 ProfilePermissionProps,
48 {
49 /** The name of the signing profile the permission is attached to. */
50 profileName: string;
51 /** The statement id of the permission inside the profile's policy. */
52 statementId: string;
53 },
54 never,
55 Providers
56 > {}
57
58 /**
59 * A cross-account permission on an AWS Signer signing profile — one statement
60 * in the profile's resource policy granting another AWS account (or IAM
61 * identity) a Signer action such as `signer:StartSigningJob`. The Signer
62 * counterpart of CloudFormation's `AWS::Signer::ProfilePermission`.
63 *
64 * Permissions have no update API: changing the `action`, `principal`, or
65 * `profileVersion` converges by removing and re-adding the statement under
66 * the same statement id (revision-checked, so concurrent policy edits are
67 * retried); changing `profileName` or `statementId` replaces the permission.
68 *
69 * ### Sharing a Signing Profile
70 * **Example:** Allow Another Account to Sign
71 * ```typescript
72 * const profile = yield* Signer.SigningProfile("ReleaseProfile", {
73 * platformId: "AWSLambda-SHA384-ECDSA",
74 * });
75 *
76 * const permission = yield* Signer.ProfilePermission("CiAccountCanSign", {
77 * profileName: profile.profileName,
78 * action: "signer:StartSigningJob",
79 * principal: "123456789012",
80 * });
81 * ```
82 *
83 * **Example:** Pin the Permission to a Profile Version
84 * ```typescript
85 * const permission = yield* Signer.ProfilePermission("CiAccountCanSign", {
86 * profileName: profile.profileName,
87 * action: "signer:StartSigningJob",
88 * principal: "123456789012",
89 * profileVersion: profile.profileVersion,
90 * });
91 * ```
92 *
93 * @resource
94 */
95 export const ProfilePermission = Resource<ProfilePermission>("AWS.Signer.ProfilePermission");
96
97 /**
98 * The profile policy is capped at 20 statements, but the list API still
99 * pages — walk it fully so revision ids and statement lookups are accurate.
100 * A profile that has never had a permission answers with a typed
101 * `ResourceNotFoundException` ("No policies associated with profile …") —
102 * observed as an empty policy. A genuinely missing profile surfaces on the
103 * subsequent `addProfilePermission` instead.
104 */
105 const listAllPermissions = Effect.fn(function* (profileName: string) {
106 const permissions: signer.Permission[] = [];
107 let revisionId: string | undefined;
108 let nextToken: string | undefined;
109 do {
110 const page = yield* signer.listProfilePermissions({ profileName, nextToken }).pipe(
111 Effect.catchTag("ResourceNotFoundException", () =>
112 Effect.succeed({
113 permissions: [] as signer.Permission[],
114 revisionId: undefined,
115 nextToken: undefined,
116 } as signer.ListProfilePermissionsResponse),
117 ),
118 );
119 permissions.push(...(page.permissions ?? []));
120 revisionId = page.revisionId ?? revisionId;
121 nextToken = page.nextToken;
122 } while (nextToken !== undefined);
123 return { permissions, revisionId };
124 });
125
126 /** Concurrent policy edits bump the revision id — re-observe and retry. */
127 const conflictRetry = {
128 while: (e: { _tag: string }): boolean => e._tag === "ConflictException",
129 schedule: Schedule.exponential("500 millis"),
130 times: 5,
131 } as const;
132
133 export const ProfilePermissionProvider = () =>
134 Provider.effect(
135 ProfilePermission,
136 Effect.gen(function* () {
137 const createStatementId = Effect.fn(function* (
138 id: string,
139 props: Pick<ProfilePermissionProps, "statementId">,
140 ) {
141 return (
142 props.statementId ??
143 // Signer rejects statement ids of 64+ characters.
144 (yield* createPhysicalName({ id, delimiter: "-", maxLength: 63 }))
145 );
146 });
147
148 return ProfilePermission.Provider.of({
149 stables: ["profileName", "statementId"],
150
151 list: () =>
152 Effect.gen(function* () {
153 // A ProfilePermission is one statement inside a profile's
154 // resource policy — fan out: enumerate active profiles, list
155 // each policy, emit one Attributes per statement id.
156 const profileNames = yield* signer.listSigningProfiles
157 .pages({ includeCanceled: false })
158 .pipe(
159 Stream.runCollect,
160 Effect.map((chunk) =>
161 Array.from(chunk).flatMap((page) =>
162 (page.profiles ?? [])
163 .map((p) => p.profileName)
164 .filter((name): name is string => name != null),
165 ),
166 ),
167 );
168 const perProfile = yield* Effect.forEach(
169 profileNames,
170 (profileName) =>
171 listAllPermissions(profileName).pipe(
172 Effect.map(({ permissions }) =>
173 permissions
174 .filter(
175 (p): p is signer.Permission & { statementId: string } =>
176 typeof p.statementId === "string",
177 )
178 .map((p) => ({
179 profileName,
180 statementId: p.statementId,
181 })),
182 ),
183 ),
184 { concurrency: 5 },
185 );
186 return perProfile.flat();
187 }),
188
189 read: Effect.fn(function* ({ id, olds, output }) {
190 const profileName = output?.profileName ?? olds?.profileName;
191 if (profileName === undefined) return undefined;
192 const statementId = output?.statementId ?? (yield* createStatementId(id, olds ?? {}));
193 const { permissions } = yield* listAllPermissions(profileName);
194 const statement = permissions.find((p) => p.statementId === statementId);
195 if (statement === undefined) return undefined;
196 return { profileName, statementId };
197 }),
198
199 diff: Effect.fn(function* ({ id, news, olds }) {
200 if (!isResolved(news)) return undefined;
201 const oldStatementId = yield* createStatementId(id, olds);
202 const newStatementId = yield* createStatementId(id, news);
203 // The statement id is the permission's identity within the policy
204 // and the profile is the policy's host — either change replaces.
205 // action/principal/profileVersion converge in reconcile via
206 // remove + re-add under the same statement id.
207 if (news.profileName !== olds.profileName || oldStatementId !== newStatementId) {
208 return { action: "replace" } as const;
209 }
210 return undefined;
211 }),
212
213 reconcile: Effect.fn(function* ({ id, news, output, session }) {
214 const statementId = output?.statementId ?? (yield* createStatementId(id, news));
215
216 yield* Effect.gen(function* () {
217 // OBSERVE — the profile's policy is authoritative.
218 const { permissions, revisionId } = yield* listAllPermissions(news.profileName);
219 const existing = permissions.find((p) => p.statementId === statementId);
220
221 // SYNC — statements have no update API. If the existing statement
222 // differs from the desired one, remove it (revision-checked) and
223 // fall through to re-add.
224 if (existing !== undefined) {
225 const matches =
226 existing.action === news.action &&
227 existing.principal === news.principal &&
228 (existing.profileVersion ?? undefined) === (news.profileVersion ?? undefined);
229 if (matches) return;
230 yield* signer
231 .removeProfilePermission({
232 profileName: news.profileName,
233 statementId,
234 revisionId: revisionId!,
235 })
236 .pipe(
237 // Already removed by a concurrent writer — proceed to add.
238 Effect.catchTag("ResourceNotFoundException", () => Effect.void),
239 );
240 }
241
242 // ENSURE — add the desired statement. A ConflictException here is
243 // a revision race (or the remove above still propagating); the
244 // outer retry re-observes and converges.
245 yield* signer.addProfilePermission({
246 profileName: news.profileName,
247 action: news.action,
248 principal: news.principal,
249 statementId,
250 profileVersion: news.profileVersion,
251 revisionId: existing !== undefined ? undefined : revisionId,
252 });
253 }).pipe(Effect.retry(conflictRetry));
254
255 yield* session.note(`${statementId} on ${news.profileName}`);
256 return { profileName: news.profileName, statementId };
257 }),
258
259 delete: Effect.fn(function* ({ output }) {
260 yield* Effect.gen(function* () {
261 const { permissions, revisionId } = yield* listAllPermissions(output.profileName);
262 const existing = permissions.find((p) => p.statementId === output.statementId);
263 if (existing === undefined || revisionId === undefined) return;
264 yield* signer
265 .removeProfilePermission({
266 profileName: output.profileName,
267 statementId: output.statementId,
268 revisionId,
269 })
270 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.void));
271 }).pipe(Effect.retry(conflictRetry));
272 }),
273 });
274 }),
275 );