nomoss 0.0.3 → 0.0.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (150) hide show
  1. package/CHANGELOG.md +27 -0
  2. package/README.md +5 -15
  3. package/ROADMAP.md +2 -0
  4. package/docs/README.md +1 -1
  5. package/docs/application/aws-resource-coverage.md +26 -0
  6. package/docs/application/aws-resource-lifecycle-management.md +13 -23
  7. package/docs/application/cli-workflow.md +1 -1
  8. package/docs/application/engine-design.md +2 -2
  9. package/docs/application/generation-architecture.md +10 -45
  10. package/docs/application/resource-command-policy-stage.md +2 -2
  11. package/docs/application/resource-graph.md +1 -1
  12. package/docs/application/resource-lifecycle-tracker.md +1 -9
  13. package/docs/application/resource-mapping.md +4 -9
  14. package/docs/application/resource-operations.md +4 -2
  15. package/docs/application/tracing.md +2 -6
  16. package/docs/development/code-documentation.md +2 -0
  17. package/docs/development/effect-native-development.md +44 -0
  18. package/docs/development/linting.md +1 -1
  19. package/docs/development/review-code.md +22 -6
  20. package/docs/development/review-remediation-spec.md +28 -37
  21. package/docs/development/spec-writing.md +1 -1
  22. package/docs/development/testing.md +23 -9
  23. package/docs/operations/observability-sop.md +11 -17
  24. package/docs/operations/releasing.md +3 -1
  25. package/examples/README.md +3 -26
  26. package/examples/commands.ts +2 -36
  27. package/examples/queue/application.ts +8 -2
  28. package/examples/state-machine/application.ts +3 -1
  29. package/package.json +40 -46
  30. package/providers/aws/README.md +21 -0
  31. package/providers/aws/awsEnvironment.ts +114 -0
  32. package/providers/aws/generated/managementRegistry.ts +136 -0
  33. package/{src/providers/aws/resources/generated/native/apigatewayv2/api/index.ts → providers/aws/generated/resources/apigatewayv2/api.ts} +13 -50
  34. package/{src/providers/aws/resources/generated/native/apigatewayv2/integration/index.ts → providers/aws/generated/resources/apigatewayv2/integration.ts} +13 -37
  35. package/{src/providers/aws/resources/generated/native/apigatewayv2/route/index.ts → providers/aws/generated/resources/apigatewayv2/route.ts} +23 -40
  36. package/{src/providers/aws/resources/generated/native/apigatewayv2/stage/index.ts → providers/aws/generated/resources/apigatewayv2/stage.ts} +13 -38
  37. package/providers/aws/generated/resources/iam/accesskey.ts +184 -0
  38. package/{src/providers/aws/resources/generated/native/iam/group/index.ts → providers/aws/generated/resources/iam/group.ts} +13 -38
  39. package/{src/providers/aws/resources/generated/native/iam/grouppolicy/index.ts → providers/aws/generated/resources/iam/grouppolicy.ts} +29 -59
  40. package/{src/providers/aws/resources/generated/native/iam/instanceprofile/index.ts → providers/aws/generated/resources/iam/instanceprofile.ts} +13 -41
  41. package/{src/providers/aws/resources/generated/native/iam/managedpolicy/index.ts → providers/aws/generated/resources/iam/managedpolicy.ts} +13 -95
  42. package/providers/aws/generated/resources/iam/oidcprovider.ts +314 -0
  43. package/{src/providers/aws/resources/generated/native/iam/policy/index.ts → providers/aws/generated/resources/iam/policy.ts} +13 -28
  44. package/{src/providers/aws/resources/generated/native/iam/role/index.ts → providers/aws/generated/resources/iam/role.ts} +13 -47
  45. package/{src/providers/aws/resources/generated/native/iam/rolepolicy/index.ts → providers/aws/generated/resources/iam/rolepolicy.ts} +29 -59
  46. package/providers/aws/generated/resources/iam/samlprovider.ts +463 -0
  47. package/providers/aws/generated/resources/iam/servercertificate.ts +465 -0
  48. package/providers/aws/generated/resources/iam/servicelinkedrole.ts +187 -0
  49. package/{src/providers/aws/resources/generated/native/iam/user/index.ts → providers/aws/generated/resources/iam/user.ts} +13 -38
  50. package/{src/providers/aws/resources/generated/native/iam/userpolicy/index.ts → providers/aws/generated/resources/iam/userpolicy.ts} +29 -59
  51. package/{src/providers/aws/resources/generated/native/iam/usertogroupaddition/index.ts → providers/aws/generated/resources/iam/usertogroupaddition.ts} +13 -27
  52. package/providers/aws/generated/resources/iam/virtualmfadevice.ts +298 -0
  53. package/{src/providers/aws/resources/generated/native/kms/key/index.ts → providers/aws/generated/resources/kms/key.ts} +13 -41
  54. package/{src/providers/aws/resources/generated/native/lambda/function/index.ts → providers/aws/generated/resources/lambda/function.ts} +13 -63
  55. package/{src/providers/aws/resources/generated/native/lambda/permission/index.ts → providers/aws/generated/resources/lambda/permission.ts} +13 -55
  56. package/{src/providers/aws/resources/generated/native/s3/bucket/index.ts → providers/aws/generated/resources/s3/bucket.ts} +14 -104
  57. package/{src/providers/aws/resources/generated/native/sns/topic/index.ts → providers/aws/generated/resources/sns/topic.ts} +14 -29
  58. package/{src/providers/aws/resources/generated/native/sqs/queue/index.ts → providers/aws/generated/resources/sqs/queue.ts} +14 -38
  59. package/{src/providers/aws/resources/generated/native/stepfunctions/statemachine/index.ts → providers/aws/generated/resources/stepfunctions/statemachine.ts} +15 -58
  60. package/providers/aws/management/mappings/iam/group.ts +63 -0
  61. package/providers/aws/management/mappings/iam/iamIdentity.ts +41 -0
  62. package/providers/aws/management/mappings/iam/iamLifecycleSettings.ts +8 -0
  63. package/providers/aws/management/mappings/iam/inlinePolicies.ts +159 -0
  64. package/providers/aws/management/mappings/iam/instanceProfile.ts +77 -0
  65. package/providers/aws/management/mappings/iam/oidcProvider.ts +94 -0
  66. package/providers/aws/management/mappings/iam/role.ts +74 -0
  67. package/providers/aws/management/mappings/iam/samlProvider.ts +98 -0
  68. package/providers/aws/management/mappings/iam/serverCertificate.ts +72 -0
  69. package/providers/aws/management/mappings/iam/user.ts +61 -0
  70. package/providers/aws/management/mappings/iam/userToGroupAddition.ts +75 -0
  71. package/providers/aws/management/operations/iam/accessKey.ts +206 -0
  72. package/providers/aws/management/operations/iam/managedPolicy.ts +491 -0
  73. package/providers/aws/management/operations/iam/policy.ts +476 -0
  74. package/providers/aws/management/operations/iam/serviceLinkedRole.ts +172 -0
  75. package/providers/aws/management/operations/iam/virtualMfaDevice.ts +253 -0
  76. package/providers/aws/management/resourceAssociationConfiguration.ts +112 -0
  77. package/providers/aws/management/resourceAssociationRegistration.ts +349 -0
  78. package/providers/aws/management/resourceAssociations.ts +168 -0
  79. package/{src/providers → providers}/aws/management/resourceConfiguration.ts +24 -26
  80. package/providers/aws/management/resourceLifecycleRegistration.ts +540 -0
  81. package/providers/aws/management/resourceManagementModule.ts +31 -0
  82. package/providers/aws/management/resourceManagementRegistry.ts +62 -0
  83. package/providers/aws/management/resourceMapping.ts +84 -0
  84. package/providers/aws/management/resourceOperation.ts +134 -0
  85. package/providers/aws/management/resourceTagOperations.ts +108 -0
  86. package/providers/aws/management/resourceTiming.ts +4 -0
  87. package/providers/aws/runtime.ts +52 -0
  88. package/src/core/resource/resourceCommandPolicy.ts +20 -0
  89. package/src/core/resource/resourceLifecycle.ts +644 -0
  90. package/src/core/resource/resourceStabilization.ts +120 -0
  91. package/src/core/resource/resourceVersions.ts +102 -0
  92. package/src/core/stack/planner.ts +9 -0
  93. package/src/core/stack/resourceStackLifecycle.ts +36 -3
  94. package/src/core/state/resourceState.ts +6 -4
  95. package/src/core/state/stateStore.ts +57 -10
  96. package/src/providers/file/resourcePolicy.ts +13 -12
  97. package/src/providers/providerRuntimeLayer.ts +5 -2
  98. package/src/providers/resourceCommandPolicyLayer.ts +117 -37
  99. package/src/providers/stripe/management/resourcePolicy.ts +22 -11
  100. package/examples/http-echo/application.ts +0 -87
  101. package/src/providers/aws/client/awsClient.ts +0 -418
  102. package/src/providers/aws/client/awsClientConfig.ts +0 -133
  103. package/src/providers/aws/client/awsClientModel.ts +0 -119
  104. package/src/providers/aws/client/awsHttpOperation.ts +0 -153
  105. package/src/providers/aws/client/awsQueryOperation.ts +0 -149
  106. package/src/providers/aws/client/awsRequestSigner.ts +0 -115
  107. package/src/providers/aws/client/awsResponseDecoder.ts +0 -135
  108. package/src/providers/aws/client/awsRetryPolicy.ts +0 -62
  109. package/src/providers/aws/client/generated/apiGatewayV2.ts +0 -3025
  110. package/src/providers/aws/client/generated/cloudControl.ts +0 -5746
  111. package/src/providers/aws/client/generated/iam.ts +0 -10892
  112. package/src/providers/aws/client/generated/lambda.ts +0 -5403
  113. package/src/providers/aws/client/generated/sqs.ts +0 -3769
  114. package/src/providers/aws/client/generated/stepFunctions.ts +0 -1726
  115. package/src/providers/aws/client/openapi/cloudControl/CancelResourceRequest.json +0 -579
  116. package/src/providers/aws/client/openapi/cloudControl/CreateResource.json +0 -1019
  117. package/src/providers/aws/client/openapi/cloudControl/DeleteResource.json +0 -1018
  118. package/src/providers/aws/client/openapi/cloudControl/GetResource.json +0 -883
  119. package/src/providers/aws/client/openapi/cloudControl/GetResourceRequestStatus.json +0 -655
  120. package/src/providers/aws/client/openapi/cloudControl/ListResourceRequests.json +0 -566
  121. package/src/providers/aws/client/openapi/cloudControl/ListResources.json +0 -913
  122. package/src/providers/aws/client/openapi/cloudControl/UpdateResource.json +0 -1027
  123. package/src/providers/aws/cloudControl/client.ts +0 -69
  124. package/src/providers/aws/cloudControl/requestTracker.ts +0 -138
  125. package/src/providers/aws/cloudControl/resourceCommandPolicyLayer.ts +0 -63
  126. package/src/providers/aws/cloudControl/resourceLifecycle.ts +0 -479
  127. package/src/providers/aws/cloudControl/resources/generated/certificatemanager/certificate/index.ts +0 -179
  128. package/src/providers/aws/cloudControl/resources/generated/kms/key/index.ts +0 -362
  129. package/src/providers/aws/cloudControl/resources/generated/s3/bucket/index.ts +0 -2364
  130. package/src/providers/aws/cloudControl/resources/generated/sns/topic/index.ts +0 -326
  131. package/src/providers/aws/cloudControl/resources/generated/sqs/queue/index.ts +0 -307
  132. package/src/providers/aws/cloudControl/resources/generated/sqs/queueinlinepolicy/index.ts +0 -108
  133. package/src/providers/aws/cloudControl/runtime.ts +0 -127
  134. package/src/providers/aws/management/resourceMapping.ts +0 -343
  135. package/src/providers/aws/management/resourceOperation.ts +0 -57
  136. package/src/providers/aws/management/resourcePolicy.ts +0 -549
  137. package/src/providers/aws/management/resourceRegistration.ts +0 -294
  138. package/src/providers/aws/resources/apiGatewayV2/httpApi.ts +0 -327
  139. package/src/providers/aws/resources/generated/native/resourceCommands.ts +0 -152
  140. package/src/providers/aws/resources/iam/grant.ts +0 -150
  141. package/src/providers/aws/resources/iam/grantCommands.ts +0 -283
  142. package/src/providers/aws/resources/iam/policyDocument.ts +0 -30
  143. package/src/providers/aws/resources/iam/policyStatement.ts +0 -59
  144. package/src/providers/aws/resources/iam/role.ts +0 -426
  145. package/src/providers/aws/resources/iam/roleDeclaration.ts +0 -105
  146. package/src/providers/aws/resources/lambda/function.ts +0 -403
  147. package/src/providers/aws/resources/lambda/functionDeclaration.ts +0 -234
  148. package/src/providers/aws/resources/lambda/permission.ts +0 -363
  149. package/src/providers/aws/resources/stepFunctions/stateMachine.ts +0 -95
  150. package/src/providers/aws/runtime.ts +0 -70
@@ -0,0 +1,491 @@
1
+ import { AwsArn, AwsServiceError } from "@tradedal/aws-client-core/model";
2
+ import {
3
+ AttachGroupPolicyRequest,
4
+ AttachRolePolicyRequest,
5
+ AttachUserPolicyRequest,
6
+ iamOperations,
7
+ makeIAMClient,
8
+ Policy,
9
+ PolicyGroup,
10
+ PolicyRole,
11
+ PolicyUser,
12
+ PolicyVersion,
13
+ } from "@tradedal/aws-client-iam";
14
+ import {
15
+ Array as Arr,
16
+ Context,
17
+ Effect,
18
+ Option,
19
+ Order,
20
+ Schema,
21
+ Stream,
22
+ Struct,
23
+ } from "effect";
24
+ import {
25
+ AWSManagedPolicyOutputsSchema,
26
+ AWSManagedPolicyRequestSchema,
27
+ AWSManagedPolicyResourceSchema,
28
+ } from "nomoss/providers/aws/iam/managedpolicy";
29
+ import {
30
+ ResourceIdentityMismatch,
31
+ ResourceModel,
32
+ type ResourceNode,
33
+ } from "../../../../../src/core/resource/model.js";
34
+ import { ResourceLifecycle } from "../../../../../src/core/resource/resourceLifecycle.js";
35
+ import { IamPolicyId } from "../../mappings/iam/iamIdentity.js";
36
+ import { iamLifecycleSettings } from "../../mappings/iam/iamLifecycleSettings.js";
37
+ import {
38
+ AssociationNames,
39
+ AwsResourceAssociationOperations,
40
+ } from "../../resourceAssociations.js";
41
+ import { AwsResourceMapping } from "../../resourceMapping.js";
42
+ import {
43
+ awsJsonDocument,
44
+ awsJsonDocumentValue,
45
+ resourceRequest,
46
+ } from "../../resourceOperation.js";
47
+
48
+ const identity = Schema.Struct({
49
+ PolicyArn: AwsArn,
50
+ PolicyId: IamPolicyId,
51
+ });
52
+
53
+ const metadata = Schema.Struct({
54
+ ...AWSManagedPolicyOutputsSchema.fields,
55
+ ...identity.fields,
56
+ ManagedPolicyName: Schema.requiredKey(Policy.schema.fields.PolicyName),
57
+ Description: Policy.schema.fields.Description,
58
+ Path: Policy.schema.fields.Path,
59
+ DefaultVersionId: Schema.requiredKey(Policy.schema.fields.DefaultVersionId),
60
+ });
61
+
62
+ const nativeMetadata = metadata.pipe(
63
+ Schema.encodeKeys({ PolicyArn: "Arn", ManagedPolicyName: "PolicyName" }),
64
+ );
65
+
66
+ const observation = Schema.Struct({
67
+ ...metadata.fields,
68
+ PolicyDocument: Schema.JsonObject,
69
+ Groups: AssociationNames,
70
+ Roles: AssociationNames,
71
+ Users: AssociationNames,
72
+ });
73
+
74
+ type ManagedPolicyObservation = typeof observation.Type;
75
+ type ManagedPolicyRequest = typeof AWSManagedPolicyRequestSchema.Type;
76
+
77
+ const version = Schema.Struct({
78
+ Document: Schema.requiredKey(PolicyVersion.schema.fields.Document),
79
+ });
80
+
81
+ const versionSummary = Schema.Struct({
82
+ VersionId: Schema.requiredKey(PolicyVersion.schema.fields.VersionId),
83
+ IsDefaultVersion: Schema.requiredKey(
84
+ PolicyVersion.schema.fields.IsDefaultVersion,
85
+ ),
86
+ CreateDate: Schema.requiredKey(PolicyVersion.schema.fields.CreateDate),
87
+ });
88
+
89
+ const group = Schema.Struct({
90
+ Parent: AttachGroupPolicyRequest.schema.fields.PolicyArn,
91
+ Member: AttachGroupPolicyRequest.schema.fields.GroupName,
92
+ }).pipe(Schema.encodeKeys({ Parent: "PolicyArn", Member: "GroupName" }));
93
+
94
+ const role = Schema.Struct({
95
+ Parent: AttachRolePolicyRequest.schema.fields.PolicyArn,
96
+ Member: AttachRolePolicyRequest.schema.fields.RoleName,
97
+ }).pipe(Schema.encodeKeys({ Parent: "PolicyArn", Member: "RoleName" }));
98
+
99
+ const user = Schema.Struct({
100
+ Parent: AttachUserPolicyRequest.schema.fields.PolicyArn,
101
+ Member: AttachUserPolicyRequest.schema.fields.UserName,
102
+ }).pipe(Schema.encodeKeys({ Parent: "PolicyArn", Member: "UserName" }));
103
+
104
+ const missing = AwsServiceError.hasCode("NoSuchEntity");
105
+ const sameDocument = Schema.toEquivalence(Schema.JsonObject);
106
+
107
+ const encodeDocument = Schema.encodeEffect(
108
+ Schema.fromJsonString(Schema.JsonObject),
109
+ );
110
+
111
+ const memberNames = (names: ReadonlyArray<string> | undefined) =>
112
+ Option.fromUndefinedOr(names).pipe(Option.toArray, Arr.flatten);
113
+
114
+ type Attachments = Pick<ManagedPolicyRequest, "Groups" | "Roles" | "Users">;
115
+
116
+ const emptyAttachments: Required<Attachments> = {
117
+ Groups: [],
118
+ Roles: [],
119
+ Users: [],
120
+ };
121
+
122
+ /**
123
+ * The ManagedPolicyManagement service confirms the document IAM uses for
124
+ * authorization. IAM stores updates as new versions. A version has no effect
125
+ * on attached principals until IAM makes it the default.
126
+ *
127
+ * @see ../../../../../refs/aws-api-models/models/iam/service/2010-05-08/iam-2010-05-08.json (GetPolicyVersion and CreatePolicyVersion)
128
+ */
129
+ export class ManagedPolicyManagement extends Context.Service<ManagedPolicyManagement>()(
130
+ "nomoss/providers/aws/management/operations/iam/managedPolicy/ManagedPolicyManagement",
131
+ {
132
+ make: Effect.gen(function* () {
133
+ const iam = yield* makeIAMClient;
134
+ const model = yield* ResourceModel;
135
+ const names = yield* AwsResourceMapping;
136
+
137
+ const groups = yield* AwsResourceAssociationOperations.make(
138
+ iamLifecycleSettings,
139
+ {
140
+ add: resourceRequest(iamOperations.AttachGroupPolicy, group),
141
+ remove: resourceRequest(iamOperations.DetachGroupPolicy, group),
142
+ },
143
+ );
144
+
145
+ const roles = yield* AwsResourceAssociationOperations.make(
146
+ iamLifecycleSettings,
147
+ {
148
+ add: resourceRequest(iamOperations.AttachRolePolicy, role),
149
+ remove: resourceRequest(iamOperations.DetachRolePolicy, role),
150
+ },
151
+ );
152
+
153
+ const users = yield* AwsResourceAssociationOperations.make(
154
+ iamLifecycleSettings,
155
+ {
156
+ add: resourceRequest(iamOperations.AttachUserPolicy, user),
157
+ remove: resourceRequest(iamOperations.DetachUserPolicy, user),
158
+ },
159
+ );
160
+
161
+ yield* model.registerOutputsSchema(
162
+ AWSManagedPolicyResourceSchema,
163
+ AWSManagedPolicyOutputsSchema,
164
+ );
165
+
166
+ const propsFor = (node: ResourceNode) =>
167
+ model.decodeProps(node, AWSManagedPolicyRequestSchema);
168
+
169
+ /**
170
+ * The readAttachments operation reads every page before an update may
171
+ * detach anyone. The IAM request selects attached permission policies.
172
+ * An entity that uses the policy as a permissions limit does not count
173
+ * as an attachment that the stack can detach.
174
+ *
175
+ * @see ../../../../../refs/effect/packages/effect/src/Stream.ts (runCollect)
176
+ */
177
+ const readAttachments = Effect.fn("ManagedPolicy.readAttachments")(
178
+ function* (PolicyArn: string) {
179
+ const pages = yield* iam
180
+ .listEntitiesForPolicyPages({
181
+ PolicyArn,
182
+ PolicyUsageFilter: "PermissionsPolicy",
183
+ })
184
+ .pipe(Stream.runCollect);
185
+
186
+ const lists = yield* Effect.forEach(pages, (page) =>
187
+ Schema.decodeUnknownEffect(
188
+ Schema.Struct({
189
+ PolicyGroups: Schema.Array(
190
+ Schema.Struct({
191
+ GroupName: Schema.requiredKey(
192
+ PolicyGroup.schema.fields.GroupName,
193
+ ),
194
+ }),
195
+ ).pipe(Schema.withDecodingDefaultKey(Effect.succeed([]))),
196
+ PolicyRoles: Schema.Array(
197
+ Schema.Struct({
198
+ RoleName: Schema.requiredKey(
199
+ PolicyRole.schema.fields.RoleName,
200
+ ),
201
+ }),
202
+ ).pipe(Schema.withDecodingDefaultKey(Effect.succeed([]))),
203
+ PolicyUsers: Schema.Array(
204
+ Schema.Struct({
205
+ UserName: Schema.requiredKey(
206
+ PolicyUser.schema.fields.UserName,
207
+ ),
208
+ }),
209
+ ).pipe(Schema.withDecodingDefaultKey(Effect.succeed([]))),
210
+ }),
211
+ )(page),
212
+ );
213
+
214
+ return {
215
+ Groups: Arr.flatMap(lists, ({ PolicyGroups }) =>
216
+ Arr.map(PolicyGroups, ({ GroupName }) => GroupName),
217
+ ),
218
+ Roles: Arr.flatMap(lists, ({ PolicyRoles }) =>
219
+ Arr.map(PolicyRoles, ({ RoleName }) => RoleName),
220
+ ),
221
+ Users: Arr.flatMap(lists, ({ PolicyUsers }) =>
222
+ Arr.map(PolicyUsers, ({ UserName }) => UserName),
223
+ ),
224
+ };
225
+ },
226
+ );
227
+
228
+ /**
229
+ * The lookup operation reads the document for the exact version IAM
230
+ * reports as current. If that version disappears during a concurrent
231
+ * change, the next confirmation can read the new default.
232
+ */
233
+ const lookup = Effect.fn("ManagedPolicy.lookup")(
234
+ function* ({ PolicyArn }: typeof identity.Type) {
235
+ const response = yield* iam.getPolicy({ PolicyArn });
236
+
237
+ const policy = yield* Schema.decodeUnknownEffect(nativeMetadata)(
238
+ response.Policy,
239
+ );
240
+
241
+ const reply = yield* iam.getPolicyVersion({
242
+ PolicyArn,
243
+ VersionId: policy.DefaultVersionId,
244
+ });
245
+
246
+ const current = yield* Schema.decodeUnknownEffect(version)(
247
+ reply.PolicyVersion,
248
+ );
249
+ const PolicyDocument = yield* Schema.decodeEffect(awsJsonDocument)(
250
+ current.Document,
251
+ );
252
+
253
+ const attachments = yield* readAttachments(PolicyArn);
254
+
255
+ const observed: ManagedPolicyObservation = {
256
+ ...policy,
257
+ ...attachments,
258
+ PolicyDocument,
259
+ };
260
+
261
+ return Option.some(observed);
262
+ },
263
+ Effect.catchIf(missing, () => Effect.succeedNone),
264
+ );
265
+
266
+ const lifecycle = yield* ResourceLifecycle.make(
267
+ {
268
+ identity,
269
+ lookup,
270
+ ownership: {
271
+ matches: (saved, observed) => saved.PolicyId === observed.PolicyId,
272
+ onMismatch: (saved) =>
273
+ new ResourceIdentityMismatch({
274
+ property: "PolicyId",
275
+ expected: saved.PolicyId,
276
+ actual: null,
277
+ }),
278
+ },
279
+ },
280
+ iamLifecycleSettings.timeout,
281
+ );
282
+
283
+ /**
284
+ * The create operation returns the policy ARN and ID before the stack
285
+ * makes any attachments. An interrupted apply can find that policy
286
+ * again from its checkpoint.
287
+ */
288
+ const create = Effect.fn("ManagedPolicy.create")(function* (
289
+ node: ResourceNode,
290
+ ) {
291
+ const props = yield* propsFor(node);
292
+
293
+ const PolicyName = yield* names.resolveName(
294
+ node,
295
+ props.ManagedPolicyName,
296
+ 128,
297
+ );
298
+
299
+ const desired = yield* Schema.decodeEffect(awsJsonDocumentValue)(
300
+ props.PolicyDocument,
301
+ );
302
+ const PolicyDocument = yield* encodeDocument(desired);
303
+
304
+ const request = Struct.assign(
305
+ Struct.pick(props, ["Description", "Path"]),
306
+ {
307
+ PolicyName,
308
+ PolicyDocument,
309
+ },
310
+ );
311
+
312
+ const reply = yield* iam.createPolicy(request);
313
+
314
+ const saved = yield* Schema.decodeUnknownEffect(nativeMetadata)(
315
+ reply.Policy,
316
+ );
317
+
318
+ return {
319
+ ...emptyAttachments,
320
+ ...saved,
321
+ PolicyDocument: desired,
322
+ };
323
+ });
324
+
325
+ /**
326
+ * The reconcileAttachments operation keeps group, role, and user names
327
+ * separate. IAM permits the same name in all three namespaces. The
328
+ * returned check accepts a fresh read only after each set agrees.
329
+ */
330
+ const reconcileAttachments = Effect.fn(
331
+ "ManagedPolicy.reconcileAttachments",
332
+ )(function* (
333
+ observed: ManagedPolicyObservation,
334
+ previous: Attachments,
335
+ desired: Attachments,
336
+ ) {
337
+ const { PolicyArn } = observed;
338
+
339
+ const acceptsGroup = yield* groups.reconcile(
340
+ PolicyArn,
341
+ observed.Groups,
342
+ memberNames(previous.Groups),
343
+ memberNames(desired.Groups),
344
+ );
345
+
346
+ const acceptsRole = yield* roles.reconcile(
347
+ PolicyArn,
348
+ observed.Roles,
349
+ memberNames(previous.Roles),
350
+ memberNames(desired.Roles),
351
+ );
352
+
353
+ const acceptsUser = yield* users.reconcile(
354
+ PolicyArn,
355
+ observed.Users,
356
+ memberNames(previous.Users),
357
+ memberNames(desired.Users),
358
+ );
359
+
360
+ return (confirmed: typeof observed) =>
361
+ acceptsGroup(confirmed.Groups) &&
362
+ acceptsRole(confirmed.Roles) &&
363
+ acceptsUser(confirmed.Users);
364
+ });
365
+
366
+ /**
367
+ * The readVersions operation requires each IAM version to identify
368
+ * itself and say whether it is the default. Only nondefault versions
369
+ * are eligible for deletion.
370
+ */
371
+ const readVersions = Effect.fn("ManagedPolicy.readVersions")(
372
+ (PolicyArn: string) =>
373
+ iam.listPolicyVersionsPages({ PolicyArn }).pipe(
374
+ Stream.mapEffect(({ Versions }) =>
375
+ Schema.decodeUnknownEffect(Schema.Array(versionSummary))(
376
+ Versions,
377
+ ),
378
+ ),
379
+ Stream.runCollect,
380
+ Effect.map(Arr.flatten),
381
+ ),
382
+ );
383
+
384
+ /**
385
+ * The publishDocument operation frees one slot only when the policy
386
+ * reaches IAM's five-version limit. It keeps the default active until
387
+ * IAM accepts the new version as its replacement.
388
+ */
389
+ const publishDocument = Effect.fn("ManagedPolicy.publishDocument")(
390
+ function* (PolicyArn: string, desired: Schema.JsonObject) {
391
+ const PolicyDocument = yield* encodeDocument(desired);
392
+
393
+ const versions = yield* readVersions(PolicyArn);
394
+ const inactive = Arr.filter(
395
+ versions,
396
+ (value) => !value.IsDefaultVersion,
397
+ );
398
+
399
+ yield* Arr.head(
400
+ Arr.sortWith(inactive, (value) => value.CreateDate, Order.String),
401
+ ).pipe(
402
+ Effect.fromOption,
403
+ Effect.flatMap(({ VersionId }) =>
404
+ iam.deletePolicyVersion({ PolicyArn, VersionId }),
405
+ ),
406
+ Effect.when(Effect.succeed(versions.length >= 5)),
407
+ );
408
+
409
+ yield* iam.createPolicyVersion({
410
+ PolicyArn,
411
+ PolicyDocument,
412
+ SetAsDefault: true,
413
+ });
414
+ },
415
+ );
416
+
417
+ const update = lifecycle.observedUpdate(
418
+ (node, current) =>
419
+ Effect.all({ desired: propsFor(node), previous: propsFor(current) }),
420
+ Effect.fnUntraced(function* (observed, { previous, desired }) {
421
+ const expected = yield* Schema.decodeEffect(awsJsonDocumentValue)(
422
+ desired.PolicyDocument,
423
+ );
424
+
425
+ yield* publishDocument(observed.PolicyArn, expected).pipe(
426
+ Effect.when(
427
+ Effect.succeed(!sameDocument(observed.PolicyDocument, expected)),
428
+ ),
429
+ );
430
+
431
+ const accepts = yield* reconcileAttachments(
432
+ observed,
433
+ previous,
434
+ desired,
435
+ );
436
+
437
+ return (confirmed: typeof observed) =>
438
+ sameDocument(confirmed.PolicyDocument, expected) &&
439
+ accepts(confirmed);
440
+ }),
441
+ );
442
+
443
+ /**
444
+ * The remove operation clears the nondefault versions before it asks
445
+ * IAM to delete the policy. If an external attachment remains, IAM can
446
+ * reject the delete and the stack retains the policy record.
447
+ */
448
+ const remove = Effect.fn("ManagedPolicy.remove")(
449
+ function* ({ PolicyArn }: typeof identity.Type) {
450
+ const versions = yield* readVersions(PolicyArn);
451
+
452
+ yield* Effect.forEach(
453
+ Arr.filter(versions, (value) => !value.IsDefaultVersion),
454
+ ({ VersionId }) =>
455
+ iam
456
+ .deletePolicyVersion({ PolicyArn, VersionId })
457
+ .pipe(Effect.catchIf(missing, () => Effect.void)),
458
+ { discard: true },
459
+ );
460
+
461
+ yield* iam.deletePolicy({ PolicyArn });
462
+ },
463
+ Effect.catchIf(missing, () => Effect.void),
464
+ );
465
+
466
+ return ResourceLifecycle.execute(
467
+ ResourceLifecycle.commands({
468
+ Read: (command) => lifecycle.observe(command),
469
+ Create: lifecycle.create(create, {
470
+ checkpoint: observation,
471
+ configure: (node, observed) =>
472
+ propsFor(node).pipe(
473
+ Effect.flatMap((desired) =>
474
+ reconcileAttachments(observed, emptyAttachments, desired),
475
+ ),
476
+ ),
477
+ }),
478
+ Update: lifecycle.update(update),
479
+ Destroy: lifecycle.remove(remove, {
480
+ cleanup: (observed, node) =>
481
+ propsFor(node).pipe(
482
+ Effect.flatMap((previous) =>
483
+ reconcileAttachments(observed, previous, emptyAttachments),
484
+ ),
485
+ ),
486
+ }),
487
+ }),
488
+ );
489
+ }),
490
+ },
491
+ ) {}