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

main
ts 227 lines 8.13 KB
Raw
1 import * as iam from "@distilled.cloud/aws/iam";
2 import { isResolved } from "alchemy/Diff";
3 import * as Provider from "alchemy/Provider";
4 import { Resource } from "alchemy/Resource";
5 import * as Data from "effect/Data";
6 import * as Effect from "effect/Effect";
7 import * as Redacted from "effect/Redacted";
8 import * as Stream from "effect/Stream";
9 import type { Providers } from "../Providers.ts";
10 import { toRedactedString } from "./common.ts";
11
12 export class AccessKeyUnexpectedResponse extends Data.TaggedError("AccessKeyUnexpectedResponse")<{
13 readonly message: string;
14 readonly cause?: unknown;
15 }> {}
16
17 export interface AccessKeyProps {
18 /**
19 * User that owns the access key.
20 */
21 userName: string;
22 /**
23 * Desired access key status.
24 * @default "Active"
25 */
26 status?: iam.StatusType;
27 }
28
29 export interface AccessKey extends Resource<
30 "AWS.IAM.AccessKey",
31 AccessKeyProps,
32 {
33 /** The IAM user the access key belongs to. */
34 userName: string;
35 /** The access key ID. */
36 accessKeyId: string;
37 /** Whether the key is `Active` or `Inactive`. */
38 status: iam.StatusType;
39 /** When the access key was created. */
40 createDate: Date | undefined;
41 /** The secret access key. AWS only returns it at creation; later reads preserve the originally stored redacted value. */
42 secretAccessKey: Redacted.Redacted<string> | undefined;
43 /** When the access key was last used, if ever. */
44 lastUsedDate: Date | undefined;
45 /** The AWS service the key last authenticated to. */
46 lastUsedServiceName: string | undefined;
47 /** The region of the key's last use. */
48 lastUsedRegion: string | undefined;
49 },
50 never,
51 Providers
52 > {}
53
54 /**
55 * An IAM access key for a user.
56 *
57 * `AccessKey` manages long-lived programmatic credentials for an IAM user. The
58 * secret access key is only returned during creation, so later reads preserve
59 * the originally stored redacted value instead of pretending AWS can return it again.
60 * ### Managing Programmatic Credentials
61 * **Example:** Create an Access Key
62 * ```typescript
63 * const user = yield* User("DeployUser", {
64 * userName: "deploy-user",
65 * });
66 *
67 * const key = yield* AccessKey("DeployUserKey", {
68 * userName: user.userName,
69 * status: "Active",
70 * });
71 * ```
72 *
73 * @resource
74 */
75 export const AccessKey = Resource<AccessKey>("AWS.IAM.AccessKey");
76
77 export const AccessKeyProvider = () =>
78 Provider.succeed(AccessKey, {
79 stables: ["accessKeyId"],
80 diff: Effect.fn(function* ({ olds, news }) {
81 if (!isResolved(news)) return;
82 if (olds.userName !== news.userName) {
83 return { action: "replace" } as const;
84 }
85 }),
86 read: Effect.fn(function* ({ output }) {
87 if (!output) {
88 return undefined;
89 }
90 const listed = yield* iam.listAccessKeys({
91 UserName: output.userName,
92 });
93 const metadata = listed.AccessKeyMetadata.find(
94 (entry) => entry.AccessKeyId === output.accessKeyId,
95 );
96 if (!metadata?.AccessKeyId) {
97 return undefined;
98 }
99 const lastUsed = yield* iam.getAccessKeyLastUsed({
100 AccessKeyId: output.accessKeyId,
101 });
102 return {
103 userName: metadata.UserName ?? output.userName,
104 accessKeyId: metadata.AccessKeyId,
105 status: metadata.Status ?? output.status,
106 createDate: metadata.CreateDate,
107 secretAccessKey: output.secretAccessKey,
108 lastUsedDate: lastUsed?.AccessKeyLastUsed?.LastUsedDate,
109 lastUsedServiceName: lastUsed?.AccessKeyLastUsed?.ServiceName,
110 lastUsedRegion: lastUsed?.AccessKeyLastUsed?.Region,
111 };
112 }),
113 reconcile: Effect.fn(function* ({ news, output, session }) {
114 // Observe — `accessKeyId` is generated by AWS, so we can only locate
115 // an existing key when we already have its id from a prior output.
116 // Without it (first reconciliation), we go straight to create.
117 const existing = output
118 ? yield* iam.listAccessKeys({ UserName: output.userName }).pipe(
119 Effect.map((listed) =>
120 listed.AccessKeyMetadata.find((entry) => entry.AccessKeyId === output.accessKeyId),
121 ),
122 Effect.catchTag("NoSuchEntityException", () => Effect.undefined),
123 )
124 : undefined;
125
126 // Ensure — create the access key if it does not exist on the cloud.
127 // The secret is only returned at creation time, so on adoption the
128 // best we can do is preserve any redacted value already stored.
129 let accessKeyId = existing?.AccessKeyId ?? output?.accessKeyId;
130 let secretAccessKey = output?.secretAccessKey;
131 let createDate: Date | undefined = existing?.CreateDate ?? output?.createDate;
132
133 if (!existing) {
134 const created = yield* iam.createAccessKey({
135 UserName: news.userName,
136 });
137 accessKeyId = created.AccessKey.AccessKeyId;
138 secretAccessKey = toRedactedString(created.AccessKey.SecretAccessKey);
139 createDate = created.AccessKey.CreateDate;
140 }
141
142 if (!accessKeyId) {
143 return yield* new AccessKeyUnexpectedResponse({
144 message: `AccessKey for user '${news.userName}' has no id`,
145 });
146 }
147
148 // Sync — apply the desired status when it differs from the observed
149 // value. Default of `Active` matches AWS's behaviour.
150 const observedStatus = existing?.Status ?? output?.status ?? "Active";
151 const desiredStatus = news.status ?? observedStatus;
152 if (desiredStatus !== observedStatus) {
153 yield* iam.updateAccessKey({
154 UserName: news.userName,
155 AccessKeyId: accessKeyId,
156 Status: desiredStatus,
157 });
158 }
159
160 const lastUsed = yield* iam.getAccessKeyLastUsed({
161 AccessKeyId: accessKeyId,
162 });
163
164 yield* session.note(accessKeyId);
165 return {
166 userName: existing?.UserName ?? news.userName,
167 accessKeyId,
168 status: desiredStatus,
169 createDate,
170 secretAccessKey,
171 lastUsedDate: lastUsed?.AccessKeyLastUsed?.LastUsedDate,
172 lastUsedServiceName: lastUsed?.AccessKeyLastUsed?.ServiceName,
173 lastUsedRegion: lastUsed?.AccessKeyLastUsed?.Region,
174 };
175 }),
176 delete: Effect.fn(function* ({ output }) {
177 yield* iam
178 .deleteAccessKey({
179 UserName: output.userName,
180 AccessKeyId: output.accessKeyId,
181 })
182 .pipe(Effect.catchTag("NoSuchEntityException", () => Effect.void));
183 }),
184 // IAM is a global service. `listAccessKeys` requires a `UserName`, so we
185 // enumerate every IAM user first (paginated) and then list the keys for
186 // each user (also paginated) with bounded concurrency. The secret access
187 // key and last-used details are not part of the list metadata — the secret
188 // is only returned at creation and cannot be re-read — so those fields are
189 // left undefined here.
190 list: Effect.fn(function* () {
191 const users = yield* iam.listUsers.pages({}).pipe(
192 Stream.runCollect,
193 Effect.map((chunk) => Array.from(chunk).flatMap((page) => page.Users)),
194 );
195 const perUser = yield* Effect.forEach(
196 users,
197 (user) =>
198 iam.listAccessKeys.pages({ UserName: user.UserName }).pipe(
199 Stream.runCollect,
200 Effect.map((chunk) =>
201 Array.from(chunk).flatMap((page) =>
202 page.AccessKeyMetadata.filter(
203 (
204 entry,
205 ): entry is iam.AccessKeyMetadata & {
206 AccessKeyId: string;
207 } => entry.AccessKeyId != null,
208 ).map((entry) => ({
209 userName: entry.UserName ?? user.UserName,
210 accessKeyId: entry.AccessKeyId,
211 status: entry.Status ?? "Active",
212 createDate: entry.CreateDate,
213 secretAccessKey: undefined,
214 lastUsedDate: undefined,
215 lastUsedServiceName: undefined,
216 lastUsedRegion: undefined,
217 })),
218 ),
219 ),
220 // The user may be deleted between enumeration and per-user list.
221 Effect.catchTag("NoSuchEntityException", () => Effect.succeed([])),
222 ),
223 { concurrency: 10 },
224 );
225 return perUser.flat();
226 }),
227 });