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
| 1 | import * as auditmanager from "@distilled.cloud/aws/auditmanager"; |
| 2 | import { Unowned } from "alchemy/AdoptPolicy"; |
| 3 | import { isResolved } from "alchemy/Diff"; |
| 4 | import { createPhysicalName } from "alchemy/PhysicalName"; |
| 5 | import * as Provider from "alchemy/Provider"; |
| 6 | import { Resource } from "alchemy/Resource"; |
| 7 | import { createInternalTags, diffTags, hasAlchemyTags, type Tags } from "alchemy/Tags"; |
| 8 | import * as Data from "effect/Data"; |
| 9 | import * as Effect from "effect/Effect"; |
| 10 | import * as Schedule from "effect/Schedule"; |
| 11 | import * as EffectStream from "effect/Stream"; |
| 12 | import { AWSEnvironment } from "../Environment.ts"; |
| 13 | import type { Providers } from "../Providers.ts"; |
| 14 | import { toTagRecord, unredact } from "./internal.ts"; |
| 15 | |
| 16 | export class AssessmentUnexpectedResponse extends Data.TaggedError("AssessmentUnexpectedResponse")<{ |
| 17 | readonly message: string; |
| 18 | readonly cause?: unknown; |
| 19 | }> {} |
| 20 | |
| 21 | /** |
| 22 | * Where Audit Manager stores generated assessment reports. |
| 23 | */ |
| 24 | export interface AssessmentReportsDestinationProps { |
| 25 | /** |
| 26 | * The destination type. Only `S3` is supported. |
| 27 | * @default "S3" |
| 28 | */ |
| 29 | destinationType?: auditmanager.AssessmentReportDestinationType; |
| 30 | /** |
| 31 | * The destination bucket, as an S3 URL (e.g. `s3://my-bucket`). |
| 32 | */ |
| 33 | destination: string; |
| 34 | } |
| 35 | |
| 36 | /** |
| 37 | * An AWS account included in the scope of an assessment. |
| 38 | */ |
| 39 | export interface AssessmentScopeAccount { |
| 40 | /** |
| 41 | * The account id. |
| 42 | */ |
| 43 | id: string; |
| 44 | } |
| 45 | |
| 46 | /** |
| 47 | * An AWS service included in the scope of an assessment. |
| 48 | */ |
| 49 | export interface AssessmentScopeService { |
| 50 | /** |
| 51 | * The service name (e.g. `s3`, `iam`). |
| 52 | */ |
| 53 | serviceName: string; |
| 54 | } |
| 55 | |
| 56 | /** |
| 57 | * The accounts and services an assessment collects evidence for. |
| 58 | */ |
| 59 | export interface AssessmentScope { |
| 60 | /** |
| 61 | * The accounts in scope. |
| 62 | */ |
| 63 | awsAccounts?: AssessmentScopeAccount[]; |
| 64 | /** |
| 65 | * The services in scope. Omit to let Audit Manager infer services from |
| 66 | * the in-scope accounts. |
| 67 | */ |
| 68 | awsServices?: AssessmentScopeService[]; |
| 69 | } |
| 70 | |
| 71 | /** |
| 72 | * A user or role responsible for an assessment. |
| 73 | */ |
| 74 | export interface AssessmentRole { |
| 75 | /** |
| 76 | * The role type — `PROCESS_OWNER` or `RESOURCE_OWNER`. |
| 77 | */ |
| 78 | roleType: auditmanager.RoleType; |
| 79 | /** |
| 80 | * ARN of the IAM user or role. |
| 81 | */ |
| 82 | roleArn: string; |
| 83 | } |
| 84 | |
| 85 | export interface AssessmentProps { |
| 86 | /** |
| 87 | * Name of the assessment. |
| 88 | * @default ${app}-${stage}-${id} |
| 89 | */ |
| 90 | name?: string; |
| 91 | /** |
| 92 | * A description of the assessment. |
| 93 | */ |
| 94 | description?: string; |
| 95 | /** |
| 96 | * The unique identifier of the framework the assessment is created from. |
| 97 | * Changing it replaces the assessment. |
| 98 | */ |
| 99 | frameworkId: string; |
| 100 | /** |
| 101 | * Where generated assessment reports are stored. |
| 102 | */ |
| 103 | assessmentReportsDestination: AssessmentReportsDestinationProps; |
| 104 | /** |
| 105 | * The accounts and services in scope. |
| 106 | * @default the current account |
| 107 | */ |
| 108 | scope?: AssessmentScope; |
| 109 | /** |
| 110 | * The users and roles responsible for the assessment. |
| 111 | */ |
| 112 | roles: AssessmentRole[]; |
| 113 | /** |
| 114 | * Tags to associate with the assessment. |
| 115 | */ |
| 116 | tags?: Record<string, string>; |
| 117 | } |
| 118 | |
| 119 | export interface Assessment extends Resource< |
| 120 | "AWS.AuditManager.Assessment", |
| 121 | AssessmentProps, |
| 122 | { |
| 123 | /** |
| 124 | * Service-assigned unique identifier of the assessment. |
| 125 | */ |
| 126 | assessmentId: string; |
| 127 | /** |
| 128 | * ARN of the assessment. |
| 129 | */ |
| 130 | arn: string; |
| 131 | /** |
| 132 | * The assessment's name. |
| 133 | */ |
| 134 | name: string; |
| 135 | /** |
| 136 | * Current status of the assessment (`ACTIVE` or `INACTIVE`). |
| 137 | */ |
| 138 | status: auditmanager.AssessmentStatus | undefined; |
| 139 | /** |
| 140 | * The id of the framework the assessment was created from. |
| 141 | */ |
| 142 | frameworkId: string; |
| 143 | /** |
| 144 | * Current tags reported for the assessment. |
| 145 | */ |
| 146 | tags: Record<string, string>; |
| 147 | }, |
| 148 | never, |
| 149 | Providers |
| 150 | > {} |
| 151 | |
| 152 | /** |
| 153 | * An AWS Audit Manager assessment — an active evidence-collection engagement |
| 154 | * created from a framework, continuously gathering evidence for the controls |
| 155 | * in scope. |
| 156 | * |
| 157 | * :::note |
| 158 | * Audit Manager must be registered in the account (`RegisterAccount`) |
| 159 | * before assessments can be created. |
| 160 | * ::: |
| 161 | * ### Creating Assessments |
| 162 | * **Example:** Assessment from a Custom Framework |
| 163 | * ```typescript |
| 164 | * import * as AWS from "@alchemy.run/aws"; |
| 165 | * |
| 166 | * const reports = yield* AWS.S3.Bucket("AuditReports", {}); |
| 167 | * |
| 168 | * const owner = yield* AWS.IAM.Role("AuditOwner", { |
| 169 | * assumeRolePolicyDocument: { |
| 170 | * Version: "2012-10-17", |
| 171 | * Statement: [{ |
| 172 | * Effect: "Allow", |
| 173 | * Principal: { Service: "auditmanager.amazonaws.com" }, |
| 174 | * Action: ["sts:AssumeRole"], |
| 175 | * }], |
| 176 | * }, |
| 177 | * }); |
| 178 | * |
| 179 | * const assessment = yield* AWS.AuditManager.Assessment("Quarterly", { |
| 180 | * frameworkId: framework.frameworkId, |
| 181 | * assessmentReportsDestination: { |
| 182 | * destination: reports.bucketName.apply((name) => `s3://${name}`), |
| 183 | * }, |
| 184 | * roles: [{ roleType: "PROCESS_OWNER", roleArn: owner.roleArn }], |
| 185 | * }); |
| 186 | * ``` |
| 187 | * |
| 188 | * @resource |
| 189 | */ |
| 190 | export const Assessment = Resource<Assessment>("AWS.AuditManager.Assessment"); |
| 191 | |
| 192 | const createAssessmentName = (id: string, props: { name?: string | undefined }) => |
| 193 | props.name ? Effect.succeed(props.name) : createPhysicalName({ id, maxLength: 100 }); |
| 194 | |
| 195 | const toAttributes = (assessment: auditmanager.Assessment): Assessment["Attributes"] => ({ |
| 196 | assessmentId: assessment.metadata?.id ?? "", |
| 197 | arn: assessment.arn ?? "", |
| 198 | name: unredact(assessment.metadata?.name) ?? "", |
| 199 | status: assessment.metadata?.status, |
| 200 | frameworkId: assessment.framework?.id ?? "", |
| 201 | tags: toTagRecord(assessment.tags), |
| 202 | }); |
| 203 | |
| 204 | const readAssessmentById = Effect.fn(function* (assessmentId: string) { |
| 205 | const response = yield* auditmanager |
| 206 | .getAssessment({ assessmentId }) |
| 207 | .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined)); |
| 208 | return response?.assessment; |
| 209 | }); |
| 210 | |
| 211 | const findAssessmentByName = Effect.fn(function* (name: string) { |
| 212 | const pages = yield* auditmanager.listAssessments.pages({}).pipe(EffectStream.runCollect); |
| 213 | const match = Array.from(pages) |
| 214 | .flatMap((page) => page.assessmentMetadata ?? []) |
| 215 | .find((assessment) => unredact(assessment.name) === name && assessment.status !== "INACTIVE"); |
| 216 | if (!match?.id) return undefined; |
| 217 | return yield* readAssessmentById(match.id); |
| 218 | }); |
| 219 | |
| 220 | /** |
| 221 | * Projection of the mutable assessment surface used for drift detection. |
| 222 | */ |
| 223 | const projectAssessment = (input: { |
| 224 | name: string; |
| 225 | description: string; |
| 226 | destinationType: string; |
| 227 | destination: string; |
| 228 | accountIds: string[]; |
| 229 | serviceNames: string[]; |
| 230 | roles: { roleType: string; roleArn: string }[]; |
| 231 | }) => ({ |
| 232 | ...input, |
| 233 | accountIds: [...input.accountIds].sort(), |
| 234 | serviceNames: [...input.serviceNames].sort(), |
| 235 | roles: [...input.roles].sort((l, r) => |
| 236 | `${l.roleArn}:${l.roleType}`.localeCompare(`${r.roleArn}:${r.roleType}`), |
| 237 | ), |
| 238 | }); |
| 239 | |
| 240 | // CreateAssessment validates the process-owner IAM roles up front; a |
| 241 | // freshly-created role may not have propagated yet and surfaces as |
| 242 | // ValidationException. Bounded retry through the propagation window (~60s). |
| 243 | // Explicitly typed — an inline `Effect.retry` in provider lifecycle code |
| 244 | // leaks `Retry.Return`'s conditional type into declaration emit and widens |
| 245 | // the provider layer to `unknown` for every consumer of `AWS.providers()`. |
| 246 | const retryThroughIamPropagation = <A, E extends { readonly _tag: string }, R>( |
| 247 | self: Effect.Effect<A, E, R>, |
| 248 | ): Effect.Effect<A, E, R> => |
| 249 | Effect.retry(self, { |
| 250 | while: (e) => e._tag === "ValidationException", |
| 251 | schedule: Schedule.max([Schedule.spaced("5 seconds"), Schedule.recurs(12)]), |
| 252 | }); |
| 253 | |
| 254 | export const AssessmentProvider = () => |
| 255 | Provider.effect( |
| 256 | Assessment, |
| 257 | Effect.gen(function* () { |
| 258 | return { |
| 259 | stables: ["assessmentId", "arn"], |
| 260 | list: () => |
| 261 | Effect.gen(function* () { |
| 262 | const pages = yield* auditmanager.listAssessments |
| 263 | .pages({}) |
| 264 | .pipe(EffectStream.runCollect); |
| 265 | const ids = Array.from(pages) |
| 266 | .flatMap((page) => page.assessmentMetadata ?? []) |
| 267 | .flatMap((assessment) => (assessment.id ? [assessment.id] : [])); |
| 268 | const hydrated = yield* Effect.forEach( |
| 269 | ids, |
| 270 | (assessmentId) => readAssessmentById(assessmentId), |
| 271 | { concurrency: 5 }, |
| 272 | ); |
| 273 | return hydrated.flatMap((assessment) => |
| 274 | assessment === undefined ? [] : [toAttributes(assessment)], |
| 275 | ); |
| 276 | }), |
| 277 | read: Effect.fn(function* ({ id, olds, output }) { |
| 278 | const assessment = output?.assessmentId |
| 279 | ? yield* readAssessmentById(output.assessmentId) |
| 280 | : yield* findAssessmentByName(yield* createAssessmentName(id, olds ?? {})); |
| 281 | if (!assessment) return undefined; |
| 282 | const attrs = toAttributes(assessment); |
| 283 | return (yield* hasAlchemyTags(id, attrs.tags as Tags)) ? attrs : Unowned(attrs); |
| 284 | }), |
| 285 | diff: Effect.fn(function* ({ news, olds }) { |
| 286 | if (!isResolved(news)) return; |
| 287 | if (olds === undefined) return; |
| 288 | // The source framework is fixed at creation. |
| 289 | if (olds.frameworkId !== news.frameworkId) { |
| 290 | return { action: "replace" } as const; |
| 291 | } |
| 292 | }), |
| 293 | reconcile: Effect.fn(function* ({ id, news, output, session }) { |
| 294 | const { accountId } = yield* AWSEnvironment.current; |
| 295 | const name = yield* createAssessmentName(id, news); |
| 296 | const internalTags = yield* createInternalTags(id); |
| 297 | const desiredTags = { ...internalTags, ...news.tags }; |
| 298 | const desiredScope: AssessmentScope = news.scope ?? { |
| 299 | awsAccounts: [{ id: accountId }], |
| 300 | }; |
| 301 | const desiredDestination = { |
| 302 | destinationType: news.assessmentReportsDestination.destinationType ?? "S3", |
| 303 | destination: news.assessmentReportsDestination.destination, |
| 304 | }; |
| 305 | |
| 306 | // Observe — prefer the cached id; fall back to a name lookup so a |
| 307 | // create whose state failed to persist is adopted, not duplicated. |
| 308 | let assessment = output?.assessmentId |
| 309 | ? yield* readAssessmentById(output.assessmentId) |
| 310 | : yield* findAssessmentByName(name); |
| 311 | |
| 312 | // Ensure — create if missing. |
| 313 | if (assessment === undefined) { |
| 314 | const created = yield* retryThroughIamPropagation( |
| 315 | auditmanager.createAssessment({ |
| 316 | name, |
| 317 | description: news.description, |
| 318 | frameworkId: news.frameworkId, |
| 319 | assessmentReportsDestination: desiredDestination, |
| 320 | scope: desiredScope, |
| 321 | roles: news.roles, |
| 322 | tags: desiredTags, |
| 323 | }), |
| 324 | ); |
| 325 | assessment = created.assessment; |
| 326 | if (!assessment?.metadata?.id) { |
| 327 | return yield* new AssessmentUnexpectedResponse({ |
| 328 | message: `CreateAssessment for '${name}' returned no assessment`, |
| 329 | }); |
| 330 | } |
| 331 | yield* session.note(`Created assessment ${name} (${assessment.metadata.id})`); |
| 332 | } |
| 333 | |
| 334 | // Sync — diff observed against desired; update on drift. |
| 335 | const metadata = assessment.metadata; |
| 336 | const observed = projectAssessment({ |
| 337 | name: unredact(metadata?.name) ?? "", |
| 338 | description: unredact(metadata?.description) ?? "", |
| 339 | destinationType: metadata?.assessmentReportsDestination?.destinationType ?? "S3", |
| 340 | destination: metadata?.assessmentReportsDestination?.destination ?? "", |
| 341 | accountIds: (metadata?.scope?.awsAccounts ?? []).flatMap((account) => |
| 342 | account.id ? [account.id] : [], |
| 343 | ), |
| 344 | serviceNames: (metadata?.scope?.awsServices ?? []).flatMap((service) => |
| 345 | service.serviceName ? [service.serviceName] : [], |
| 346 | ), |
| 347 | roles: (metadata?.roles ?? []).map((role) => ({ |
| 348 | roleType: role.roleType, |
| 349 | roleArn: role.roleArn, |
| 350 | })), |
| 351 | }); |
| 352 | const desired = projectAssessment({ |
| 353 | name, |
| 354 | description: news.description ?? "", |
| 355 | destinationType: desiredDestination.destinationType, |
| 356 | destination: desiredDestination.destination, |
| 357 | accountIds: (desiredScope.awsAccounts ?? []).map((account) => account.id), |
| 358 | serviceNames: (desiredScope.awsServices ?? []).map((service) => service.serviceName), |
| 359 | roles: news.roles.map((role) => ({ |
| 360 | roleType: role.roleType, |
| 361 | roleArn: role.roleArn, |
| 362 | })), |
| 363 | }); |
| 364 | // Audit Manager expands an accounts-only scope with the services it |
| 365 | // detects, so only compare services the user explicitly pinned. |
| 366 | const serviceDrifted = |
| 367 | news.scope?.awsServices !== undefined && |
| 368 | JSON.stringify(observed.serviceNames) !== JSON.stringify(desired.serviceNames); |
| 369 | const drifted = |
| 370 | observed.name !== desired.name || |
| 371 | observed.description !== desired.description || |
| 372 | observed.destinationType !== desired.destinationType || |
| 373 | observed.destination !== desired.destination || |
| 374 | JSON.stringify(observed.accountIds) !== JSON.stringify(desired.accountIds) || |
| 375 | JSON.stringify(observed.roles) !== JSON.stringify(desired.roles) || |
| 376 | serviceDrifted; |
| 377 | const assessmentId = metadata?.id ?? output?.assessmentId ?? ""; |
| 378 | if (drifted) { |
| 379 | const updated = yield* retryThroughIamPropagation( |
| 380 | auditmanager.updateAssessment({ |
| 381 | assessmentId, |
| 382 | assessmentName: name, |
| 383 | assessmentDescription: news.description, |
| 384 | scope: desiredScope, |
| 385 | assessmentReportsDestination: desiredDestination, |
| 386 | roles: news.roles, |
| 387 | }), |
| 388 | ); |
| 389 | assessment = updated.assessment ?? assessment; |
| 390 | yield* session.note(`Updated assessment ${name}`); |
| 391 | } |
| 392 | |
| 393 | // Sync tags — diff against observed cloud tags. |
| 394 | const attrs = toAttributes(assessment); |
| 395 | const { removed, upsert } = diffTags(attrs.tags, desiredTags); |
| 396 | if (removed.length > 0) { |
| 397 | yield* auditmanager.untagResource({ |
| 398 | resourceArn: attrs.arn, |
| 399 | tagKeys: removed, |
| 400 | }); |
| 401 | } |
| 402 | if (upsert.length > 0) { |
| 403 | yield* auditmanager.tagResource({ |
| 404 | resourceArn: attrs.arn, |
| 405 | tags: Object.fromEntries(upsert.map(({ Key, Value }) => [Key, Value])), |
| 406 | }); |
| 407 | } |
| 408 | |
| 409 | yield* session.note(attrs.arn); |
| 410 | return { ...attrs, tags: desiredTags }; |
| 411 | }), |
| 412 | delete: Effect.fn(function* ({ output }) { |
| 413 | yield* auditmanager |
| 414 | .deleteAssessment({ assessmentId: output.assessmentId }) |
| 415 | .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.void)); |
| 416 | }), |
| 417 | }; |
| 418 | }), |
| 419 | ); |