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,476 @@
1
+ import { AwsServiceError } from "@tradedal/aws-client-core/model";
2
+ import { makeIAMClient } from "@tradedal/aws-client-iam";
3
+ import {
4
+ Array as Arr,
5
+ Context,
6
+ Data,
7
+ Effect,
8
+ Exit,
9
+ Match,
10
+ Option,
11
+ Schema,
12
+ } from "effect";
13
+ import {
14
+ AWSPolicyOutputsSchema,
15
+ AWSPolicyRequestSchema,
16
+ AWSPolicyResourceSchema,
17
+ } from "nomoss/providers/aws/iam/policy";
18
+ import {
19
+ ResourceModel,
20
+ type ResourceNode,
21
+ } from "../../../../../src/core/resource/model.js";
22
+ import { ResourceLifecycle } from "../../../../../src/core/resource/resourceLifecycle.js";
23
+ import { iamLifecycleSettings } from "../../mappings/iam/iamLifecycleSettings.js";
24
+ import { AwsResourceMapping } from "../../resourceMapping.js";
25
+ import {
26
+ awsJsonDocument,
27
+ awsJsonDocumentValue,
28
+ } from "../../resourceOperation.js";
29
+
30
+ const identity = Schema.Struct({
31
+ Id: Schema.requiredKey(AWSPolicyOutputsSchema.fields.Id),
32
+ });
33
+
34
+ const principal = Schema.Struct({
35
+ kind: Schema.Literals(["Groups", "Roles", "Users"]),
36
+ name: Schema.String,
37
+ });
38
+ type Principal = typeof principal.Type;
39
+
40
+ const inlinePolicy = Schema.Struct({
41
+ principal,
42
+ document: Schema.JsonObject,
43
+ });
44
+
45
+ const observation = Schema.Struct({
46
+ ...identity.fields,
47
+ PolicyName: AWSPolicyRequestSchema.fields.PolicyName,
48
+ copies: Schema.Array(inlinePolicy),
49
+ });
50
+ type InlinePolicyObservation = typeof observation.Type;
51
+
52
+ class InlinePolicyConflict extends Data.TaggedError("InlinePolicyConflict")<{
53
+ readonly policyName: string;
54
+ readonly principal: Principal;
55
+ }> {
56
+ override get message() {
57
+ return `Inline policy "${this.policyName}" already exists on ${this.principal.kind} "${this.principal.name}".`;
58
+ }
59
+ }
60
+
61
+ class InlinePolicyPrincipalRequired extends Data.TaggedError(
62
+ "InlinePolicyPrincipalRequired",
63
+ )<{
64
+ readonly policyName: string;
65
+ }> {
66
+ override get message() {
67
+ return `Inline policy "${this.policyName}" requires a group, role, or user.`;
68
+ }
69
+ }
70
+
71
+ const missing = AwsServiceError.hasCode("NoSuchEntity");
72
+ const samePrincipal = Schema.toEquivalence(principal);
73
+
74
+ const sameDocument = Schema.toEquivalence(Schema.JsonObject);
75
+ const encodeDocument = Schema.encodeEffect(
76
+ Schema.fromJsonString(Schema.JsonObject),
77
+ );
78
+
79
+ const principalNames = (names: ReadonlyArray<string> | undefined) =>
80
+ Option.fromUndefinedOr(names).pipe(Option.toArray, Arr.flatten, Arr.dedupe);
81
+
82
+ /**
83
+ * The PolicyManagement service manages copies of one inline document on
84
+ * IAM groups, roles, and users. IAM gives each copy the name of the policy
85
+ * and its principal. The stack has one stable ID for the entire declaration.
86
+ *
87
+ * @see ../../../../../refs/aws-api-models/models/iam/service/2010-05-08/iam-2010-05-08.json (GetGroupPolicy, GetRolePolicy, and GetUserPolicy)
88
+ */
89
+ export class PolicyManagement extends Context.Service<PolicyManagement>()(
90
+ "nomoss/providers/aws/management/operations/iam/policy/PolicyManagement",
91
+ {
92
+ make: Effect.gen(function* () {
93
+ const model = yield* ResourceModel;
94
+ const names = yield* AwsResourceMapping;
95
+
96
+ const iam = yield* makeIAMClient;
97
+
98
+ yield* model.registerOutputsSchema(
99
+ AWSPolicyResourceSchema,
100
+ AWSPolicyOutputsSchema,
101
+ );
102
+
103
+ /**
104
+ * The prepare operation requires at least one principal. IAM has no
105
+ * inline policy to read or delete until the declaration names a group,
106
+ * role, or user.
107
+ */
108
+ const prepare = Effect.fn("Policy.prepare")(function* (
109
+ node: ResourceNode,
110
+ ) {
111
+ const props = yield* model.decodeProps(node, AWSPolicyRequestSchema);
112
+
113
+ const principals: ReadonlyArray<Principal> = [
114
+ ...Arr.map(
115
+ principalNames(props.Groups),
116
+ (name): Principal => ({ kind: "Groups", name }),
117
+ ),
118
+ ...Arr.map(
119
+ principalNames(props.Roles),
120
+ (name): Principal => ({ kind: "Roles", name }),
121
+ ),
122
+ ...Arr.map(
123
+ principalNames(props.Users),
124
+ (name): Principal => ({ kind: "Users", name }),
125
+ ),
126
+ ];
127
+
128
+ yield* new InlinePolicyPrincipalRequired({
129
+ policyName: props.PolicyName,
130
+ }).pipe(
131
+ Effect.when(Effect.succeed(Arr.isReadonlyArrayEmpty(principals))),
132
+ );
133
+
134
+ const document = yield* Schema.decodeEffect(awsJsonDocumentValue)(
135
+ props.PolicyDocument,
136
+ );
137
+
138
+ return { PolicyName: props.PolicyName, principals, document };
139
+ });
140
+
141
+ /**
142
+ * The readCopy operation checks one principal and policy name. IAM's
143
+ * absence error can mean either the policy or the principal is gone.
144
+ * An authorization error leaves the copy's presence unknown.
145
+ */
146
+ const readCopy = Effect.fn("Policy.readCopy")(
147
+ (PolicyName: string, target: Principal) =>
148
+ Match.value(target.kind).pipe(
149
+ Match.when("Groups", () =>
150
+ iam.getGroupPolicy({ GroupName: target.name, PolicyName }),
151
+ ),
152
+ Match.when("Roles", () =>
153
+ iam.getRolePolicy({ RoleName: target.name, PolicyName }),
154
+ ),
155
+ Match.when("Users", () =>
156
+ iam.getUserPolicy({ UserName: target.name, PolicyName }),
157
+ ),
158
+ Match.exhaustive,
159
+ Effect.flatMap((reply) =>
160
+ Schema.decodeEffect(awsJsonDocument)(reply.PolicyDocument),
161
+ ),
162
+ Effect.map((document) =>
163
+ Option.some({ principal: target, document }),
164
+ ),
165
+ Effect.catchIf(missing, () => Effect.succeedNone),
166
+ ),
167
+ );
168
+
169
+ const putCopy = (
170
+ PolicyName: string,
171
+ PolicyDocument: string,
172
+ target: Principal,
173
+ ) =>
174
+ Match.value(target.kind).pipe(
175
+ Match.when("Groups", () =>
176
+ iam.putGroupPolicy({
177
+ GroupName: target.name,
178
+ PolicyName,
179
+ PolicyDocument,
180
+ }),
181
+ ),
182
+ Match.when("Roles", () =>
183
+ iam.putRolePolicy({
184
+ RoleName: target.name,
185
+ PolicyName,
186
+ PolicyDocument,
187
+ }),
188
+ ),
189
+ Match.when("Users", () =>
190
+ iam.putUserPolicy({
191
+ UserName: target.name,
192
+ PolicyName,
193
+ PolicyDocument,
194
+ }),
195
+ ),
196
+ Match.exhaustive,
197
+ );
198
+
199
+ const removeCopy = (PolicyName: string, target: Principal) =>
200
+ Match.value(target.kind).pipe(
201
+ Match.when("Groups", () =>
202
+ iam.deleteGroupPolicy({ GroupName: target.name, PolicyName }),
203
+ ),
204
+ Match.when("Roles", () =>
205
+ iam.deleteRolePolicy({ RoleName: target.name, PolicyName }),
206
+ ),
207
+ Match.when("Users", () =>
208
+ iam.deleteUserPolicy({ UserName: target.name, PolicyName }),
209
+ ),
210
+ Match.exhaustive,
211
+ Effect.catchIf(missing, () => Effect.void),
212
+ );
213
+
214
+ /**
215
+ * The readCopies operation reports the documents on the selected
216
+ * principals. A successful read on one principal says nothing about
217
+ * the others, even when they use the same policy name.
218
+ */
219
+ const readCopies = Effect.fn("Policy.readCopies")(
220
+ (PolicyName: string, principals: ReadonlyArray<Principal>) =>
221
+ Effect.forEach(principals, (target) =>
222
+ readCopy(PolicyName, target),
223
+ ).pipe(Effect.map(Arr.getSomes)),
224
+ );
225
+
226
+ /**
227
+ * The lookup operation checks the principals from the declaration
228
+ * for the current command. After an update, that declaration can
229
+ * name a different set of principals under the same saved stack ID.
230
+ */
231
+ const lookup = Effect.fn("Policy.lookup")(function* (
232
+ { Id }: typeof identity.Type,
233
+ node: ResourceNode,
234
+ ) {
235
+ const { PolicyName, principals } = yield* prepare(node);
236
+
237
+ const copies = yield* readCopies(PolicyName, principals);
238
+
239
+ return Option.liftPredicate(Arr.isReadonlyArrayNonEmpty)(copies).pipe(
240
+ Option.map(
241
+ (): InlinePolicyObservation => ({ Id, PolicyName, copies }),
242
+ ),
243
+ );
244
+ });
245
+
246
+ const lifecycle = yield* ResourceLifecycle.make(
247
+ { identity, lookup },
248
+ iamLifecycleSettings.timeout,
249
+ );
250
+
251
+ const confirms = (
252
+ observed: InlinePolicyObservation,
253
+ desired: Effect.Success<ReturnType<typeof prepare>>,
254
+ ) =>
255
+ Arr.every(desired.principals, (target) =>
256
+ Arr.some(
257
+ observed.copies,
258
+ (copy) =>
259
+ samePrincipal(target, copy.principal) &&
260
+ sameDocument(copy.document, desired.document),
261
+ ),
262
+ );
263
+
264
+ /**
265
+ * The requireAbsent operation checks every new address before the
266
+ * stack writes any copy. IAM's Put operations would otherwise replace
267
+ * a document already present at that principal and policy name.
268
+ */
269
+ const requireAbsent = Effect.fn("Policy.requireAbsent")(function* (
270
+ PolicyName: string,
271
+ targets: ReadonlyArray<Principal>,
272
+ ) {
273
+ const existing = yield* readCopies(PolicyName, targets);
274
+
275
+ yield* Arr.head(existing).pipe(
276
+ Option.map(({ principal }) =>
277
+ Effect.fail(
278
+ new InlinePolicyConflict({ policyName: PolicyName, principal }),
279
+ ),
280
+ ),
281
+ Effect.transposeOption,
282
+ );
283
+ });
284
+
285
+ /**
286
+ * The addCopies operation registers cleanup for each new copy. Call it
287
+ * after the target addresses pass the conflict check. During an update,
288
+ * keep the scope open until the stack confirms the new configuration.
289
+ * If confirmation fails, the saved declaration still describes the
290
+ * old addresses and cannot locate the new copies for cleanup.
291
+ *
292
+ * @see ../../../../../refs/effect/packages/effect/src/Effect.ts (acquireRelease and scoped)
293
+ */
294
+ const addCopies = Effect.fn("Policy.addCopies")(function* (
295
+ PolicyName: string,
296
+ PolicyDocument: string,
297
+ added: ReadonlyArray<Principal>,
298
+ ) {
299
+ yield* Effect.forEach(
300
+ added,
301
+ (target) =>
302
+ Effect.acquireRelease(
303
+ putCopy(PolicyName, PolicyDocument, target),
304
+ (_, exit) =>
305
+ removeCopy(PolicyName, target).pipe(
306
+ Effect.when(Effect.succeed(Exit.isFailure(exit))),
307
+ Effect.orDie,
308
+ ),
309
+ ),
310
+ { discard: true },
311
+ );
312
+ });
313
+
314
+ /**
315
+ * The create operation rejects a collision on any selected principal
316
+ * before it writes the first copy. Its checkpoint lets an apply resume
317
+ * confirmation of the copies it already submitted.
318
+ */
319
+ const create = Effect.fn("Policy.create")(function* (node: ResourceNode) {
320
+ const desired = yield* prepare(node);
321
+
322
+ const Id = yield* names.resolveName(node, undefined, 128);
323
+
324
+ const encoded = yield* encodeDocument(desired.document);
325
+
326
+ yield* requireAbsent(desired.PolicyName, desired.principals);
327
+
328
+ yield* addCopies(desired.PolicyName, encoded, desired.principals).pipe(
329
+ Effect.scoped,
330
+ );
331
+
332
+ return {
333
+ Id,
334
+ PolicyName: desired.PolicyName,
335
+ copies: Arr.map(desired.principals, (principal) => ({
336
+ principal,
337
+ document: desired.document,
338
+ })),
339
+ };
340
+ });
341
+
342
+ /**
343
+ * The update operation writes the requested document to the selected
344
+ * principals and verifies that retired copies are gone. A policy rename
345
+ * uses new addresses, so it checks every destination for a collision.
346
+ */
347
+ const update = Effect.fn("Policy.update")(function* (
348
+ node: ResourceNode,
349
+ current: ResourceNode,
350
+ ) {
351
+ const desired = yield* prepare(node);
352
+ const previous = yield* prepare(current);
353
+
354
+ const sameName = previous.PolicyName === desired.PolicyName;
355
+ const retained = Arr.filter(
356
+ desired.principals,
357
+ (target) =>
358
+ sameName &&
359
+ Arr.some(previous.principals, (prior) =>
360
+ samePrincipal(prior, target),
361
+ ),
362
+ );
363
+
364
+ const added = Arr.filter(
365
+ desired.principals,
366
+ (target) =>
367
+ !Arr.some(retained, (prior) => samePrincipal(prior, target)),
368
+ );
369
+
370
+ const retired = Arr.filter(
371
+ previous.principals,
372
+ (target) =>
373
+ !Arr.some(retained, (next) => samePrincipal(target, next)),
374
+ );
375
+
376
+ const encoded = yield* encodeDocument(desired.document);
377
+
378
+ yield* requireAbsent(desired.PolicyName, added);
379
+
380
+ yield* Effect.forEach(
381
+ retained,
382
+ (target) => putCopy(desired.PolicyName, encoded, target),
383
+ { discard: true },
384
+ );
385
+ yield* addCopies(desired.PolicyName, encoded, added);
386
+
387
+ yield* Effect.forEach(
388
+ retired,
389
+ (target) => removeCopy(previous.PolicyName, target),
390
+ { discard: true },
391
+ );
392
+
393
+ return (observed: InlinePolicyObservation) =>
394
+ readCopies(previous.PolicyName, retired).pipe(
395
+ Effect.map(
396
+ (copies) =>
397
+ Arr.isReadonlyArrayEmpty(copies) && confirms(observed, desired),
398
+ ),
399
+ );
400
+ });
401
+
402
+ /**
403
+ * The remove operation deletes copies from the saved declaration only.
404
+ * An inline policy with the same name on another principal remains in IAM.
405
+ */
406
+ const remove = Effect.fn("Policy.remove")(function* (
407
+ _saved: typeof identity.Type,
408
+ node: ResourceNode,
409
+ ) {
410
+ const { PolicyName, principals } = yield* prepare(node);
411
+
412
+ yield* Effect.forEach(
413
+ principals,
414
+ (target) => removeCopy(PolicyName, target),
415
+ { discard: true },
416
+ );
417
+ });
418
+
419
+ /**
420
+ * The project function reports the principals IAM still returns. It
421
+ * exposes one common PolicyDocument only if every observed copy agrees.
422
+ * The copies also expose a difference that affects only one principal.
423
+ */
424
+ const project = (observed: InlinePolicyObservation) => {
425
+ const first = Arr.head(observed.copies);
426
+ const common = Option.filter(first, ({ document }) =>
427
+ Arr.every(observed.copies, (copy) =>
428
+ sameDocument(copy.document, document),
429
+ ),
430
+ );
431
+
432
+ const namesFor = (kind: Principal["kind"]) =>
433
+ Arr.map(
434
+ Arr.filter(observed.copies, (copy) => copy.principal.kind === kind),
435
+ (copy) => copy.principal.name,
436
+ );
437
+
438
+ return {
439
+ ...observed,
440
+ ...Option.match(common, {
441
+ onNone: () => ({}),
442
+ onSome: ({ document }) => ({ PolicyDocument: document }),
443
+ }),
444
+ Groups: namesFor("Groups"),
445
+ Roles: namesFor("Roles"),
446
+ Users: namesFor("Users"),
447
+ };
448
+ };
449
+
450
+ const confirmUpdate = lifecycle.update(update);
451
+
452
+ return ResourceLifecycle.execute(
453
+ ResourceLifecycle.commands({
454
+ Read: (command) =>
455
+ lifecycle.observe(command, (outputs) =>
456
+ Effect.succeed(project(outputs)),
457
+ ),
458
+ Create: lifecycle.create(create, {
459
+ checkpoint: observation,
460
+ matches: (created, observed) =>
461
+ Arr.every(created.copies, (desired) =>
462
+ Arr.some(
463
+ observed.copies,
464
+ (copy) =>
465
+ samePrincipal(copy.principal, desired.principal) &&
466
+ sameDocument(copy.document, desired.document),
467
+ ),
468
+ ),
469
+ }),
470
+ Update: (command) => confirmUpdate(command).pipe(Effect.scoped),
471
+ Destroy: lifecycle.remove(remove),
472
+ }),
473
+ );
474
+ }),
475
+ },
476
+ ) {}
@@ -0,0 +1,172 @@
1
+ import { AwsClient } from "@tradedal/aws-client-core";
2
+ import { AwsServiceError } from "@tradedal/aws-client-core/model";
3
+ import {
4
+ CreateServiceLinkedRoleRequest,
5
+ iamOperations,
6
+ iamService,
7
+ Role,
8
+ } from "@tradedal/aws-client-iam";
9
+ import { Context, Data, Effect, Option, Schema } from "effect";
10
+ import {
11
+ AWSServiceLinkedRoleOutputsSchema,
12
+ AWSServiceLinkedRoleRequestSchema,
13
+ AWSServiceLinkedRoleResourceSchema,
14
+ } from "nomoss/providers/aws/iam/servicelinkedrole";
15
+ import {
16
+ ResourceIdentityMismatch,
17
+ ResourceModel,
18
+ type ResourceNode,
19
+ } from "../../../../../src/core/resource/model.js";
20
+ import { ResourceLifecycle } from "../../../../../src/core/resource/resourceLifecycle.js";
21
+ import { ResourceStabilization } from "../../../../../src/core/resource/resourceStabilization.js";
22
+ import { resourceTiming } from "../../resourceTiming.js";
23
+
24
+ /**
25
+ * The identity schema requires the original RoleId because IAM addresses
26
+ * a role by name. A later command can tell the saved role from a different
27
+ * role that has the same name.
28
+ */
29
+ const identity = Schema.Struct({
30
+ RoleName: Role.schema.fields.RoleName,
31
+ RoleId: IamRoleId,
32
+ });
33
+
34
+ const missing = AwsServiceError.hasCode("NoSuchEntity");
35
+
36
+ class ServiceLinkedRoleDeletionFailed extends Data.TaggedError(
37
+ "ServiceLinkedRoleDeletionFailed",
38
+ )<{
39
+ readonly roleName: string;
40
+ readonly task: string;
41
+ readonly reason: string | undefined;
42
+ }> {}
43
+
44
+ /**
45
+ * The ServiceLinkedRoleManagement service leaves a role in stack state
46
+ * if the linked AWS service refuses to release it. Resources that still
47
+ * use the role can block deletion even after IAM accepts the request.
48
+ *
49
+ * @see ../../../../../refs/aws-api-models/models/iam/service/2010-05-08/iam-2010-05-08.json (DeleteServiceLinkedRole and GetServiceLinkedRoleDeletionStatus)
50
+ */
51
+ export class ServiceLinkedRoleManagement extends Context.Service<ServiceLinkedRoleManagement>()(
52
+ "nomoss/providers/aws/management/operations/iam/serviceLinkedRole/ServiceLinkedRoleManagement",
53
+ {
54
+ make: Effect.gen(function* () {
55
+ const model = yield* ResourceModel;
56
+ const stabilization = yield* ResourceStabilization;
57
+ const client = yield* AwsClient;
58
+
59
+ const bind = client.bindOperation(iamService);
60
+
61
+ const getRole = bind(iamOperations.GetRole);
62
+ const createRole = bind(iamOperations.CreateServiceLinkedRole);
63
+ const updateRole = bind(iamOperations.UpdateRole);
64
+ const deleteRole = bind(iamOperations.DeleteServiceLinkedRole);
65
+
66
+ const status = bind(iamOperations.GetServiceLinkedRoleDeletionStatus);
67
+
68
+ yield* model.registerOutputsSchema(
69
+ AWSServiceLinkedRoleResourceSchema,
70
+ AWSServiceLinkedRoleOutputsSchema,
71
+ );
72
+
73
+ const lifecycle = yield* ResourceLifecycle.make(
74
+ {
75
+ identity,
76
+ lookup: ({ RoleName }) =>
77
+ getRole({ RoleName }).pipe(
78
+ Effect.map(({ Role }) => Option.some(Role)),
79
+ Effect.catchIf(missing, () => Effect.succeedNone),
80
+ ),
81
+ ownership: {
82
+ matches: (saved, observed) => saved.RoleId === observed.RoleId,
83
+ onMismatch: (saved) =>
84
+ new ResourceIdentityMismatch({
85
+ property: "RoleId",
86
+ expected: saved.RoleId,
87
+ actual: null,
88
+ }),
89
+ },
90
+ },
91
+ resourceTiming.iam,
92
+ );
93
+
94
+ /**
95
+ * The create operation requires a valid Role in the IAM reply. The stack
96
+ * needs its RoleId to identify the same role on later reads and mutations.
97
+ */
98
+ const create = Effect.fn("ServiceLinkedRole.create")(function* (
99
+ node: ResourceNode,
100
+ ) {
101
+ const properties = yield* model.decodeProps(
102
+ node,
103
+ CreateServiceLinkedRoleRequest.schema,
104
+ );
105
+
106
+ const response = yield* createRole(properties);
107
+
108
+ return yield* Schema.decodeUnknownEffect(Role)(response.Role);
109
+ });
110
+
111
+ /**
112
+ * The update operation clears the role description if the declaration
113
+ * omits it. A read with either an empty string or no description confirms
114
+ * that IAM cleared the value.
115
+ */
116
+ const update = lifecycle.observedUpdate(
117
+ (node) => model.decodeProps(node, AWSServiceLinkedRoleRequestSchema),
118
+ Effect.fnUntraced(function* ({ RoleName }, { Description }) {
119
+ const description = Description ?? "";
120
+
121
+ yield* updateRole({ RoleName, Description: description });
122
+
123
+ return (observed: typeof Role.Type) =>
124
+ (observed.Description ?? "") === description;
125
+ }),
126
+ );
127
+
128
+ /**
129
+ * The remove operation waits for IAM to report that the deletion task
130
+ * succeeded or failed. If the task fails, the error includes its ID and
131
+ * any reason IAM returned, so the caller can find out why the role remains.
132
+ */
133
+ const remove = Effect.fn("ServiceLinkedRole.remove")(function* ({
134
+ RoleName,
135
+ }: typeof identity.Type) {
136
+ const { DeletionTaskId } = yield* deleteRole({ RoleName });
137
+
138
+ const result = yield* status({ DeletionTaskId }).pipe(
139
+ Effect.map(
140
+ Option.liftPredicate(
141
+ ({ Status }) => Status === "SUCCEEDED" || Status === "FAILED",
142
+ ),
143
+ ),
144
+ stabilization.waitForPresence("90 seconds"),
145
+ );
146
+
147
+ yield* Effect.fail(
148
+ new ServiceLinkedRoleDeletionFailed({
149
+ roleName: RoleName,
150
+ task: DeletionTaskId,
151
+ reason: result.Reason?.Reason,
152
+ }),
153
+ ).pipe(Effect.when(Effect.succeed(result.Status === "FAILED")));
154
+ });
155
+
156
+ return ResourceLifecycle.execute(
157
+ ResourceLifecycle.commands({
158
+ Read: (command) => lifecycle.observe(command),
159
+ Create: lifecycle.create(create, { checkpoint: Role }),
160
+ Update: lifecycle.update(update),
161
+ Destroy: lifecycle.remove(
162
+ (saved) =>
163
+ remove(saved).pipe(Effect.catchIf(missing, () => Effect.void)),
164
+ {},
165
+ ),
166
+ }),
167
+ );
168
+ }),
169
+ },
170
+ ) {}
171
+
172
+ import { IamRoleId } from "../../mappings/iam/iamIdentity.js";