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

main
ts 231 lines 7.86 KB
Raw
1 import * as aoss from "@distilled.cloud/aws/opensearchserverless";
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 Stream from "effect/Stream";
8 import type { Providers } from "../Providers.ts";
9 import { canonicalizePolicy, retryWhileConflict, stringifyPolicy } from "./internal.ts";
10 import type { SecurityPolicyDocument } from "./SecurityPolicy.ts";
11
12 export interface AccessPolicyProps {
13 /**
14 * Name of the data access policy (3-32 characters, lowercase). Changing the
15 * name replaces the policy.
16 * @default a generated physical name
17 */
18 policyName?: string;
19 /**
20 * The data access policy document — a JSON array of rules granting principals
21 * (IAM roles/users) collection- and index-level permissions such as
22 * `aoss:CreateIndex`, `aoss:ReadDocument`, `aoss:WriteDocument`. Supply an
23 * array/object or a pre-serialized string.
24 */
25 policy: SecurityPolicyDocument;
26 /**
27 * A human-readable description of the policy.
28 */
29 description?: string;
30 }
31
32 export interface AccessPolicy extends Resource<
33 "AWS.OpenSearchServerless.AccessPolicy",
34 AccessPolicyProps,
35 {
36 /**
37 * Name of the access policy.
38 */
39 policyName: string;
40 /**
41 * Policy type (`data`).
42 */
43 type: string;
44 /**
45 * Version of the policy, used for optimistic-concurrency updates.
46 */
47 policyVersion: string;
48 /**
49 * Description of the access policy.
50 */
51 description?: string;
52 },
53 {},
54 Providers
55 > {}
56
57 /**
58 * An Amazon OpenSearch Serverless data access policy. Data access policies
59 * grant IAM principals fine-grained permissions on collections and their
60 * indexes (create/read/write/delete documents, create indexes, etc.) — they
61 * are the data-plane authorization layer that complements the network and
62 * encryption {@link SecurityPolicy | security policies}.
63 *
64 * A Bedrock Knowledge Base backed by an OpenSearch Serverless collection
65 * requires a data access policy granting the Knowledge Base's service role
66 * `aoss:APIAccessAll` on the collection and its indexes.
67 *
68 * ### Creating Access Policies
69 * **Example:** Grant a Role Full Data Access
70 * ```typescript
71 * import * as AWS from "@alchemy.run/aws";
72 *
73 * const access = yield* AWS.OpenSearchServerless.AccessPolicy("Access", {
74 * policyName: "my-collection-access",
75 * policy: [
76 * {
77 * Rules: [
78 * {
79 * ResourceType: "collection",
80 * Resource: ["collection/my-collection"],
81 * Permission: ["aoss:*"],
82 * },
83 * {
84 * ResourceType: "index",
85 * Resource: ["index/my-collection/*"],
86 * Permission: ["aoss:*"],
87 * },
88 * ],
89 * Principal: ["arn:aws:iam::123456789012:role/my-role"],
90 * },
91 * ],
92 * });
93 * ```
94 *
95 * @resource
96 */
97 export const AccessPolicy = Resource<AccessPolicy>("AWS.OpenSearchServerless.AccessPolicy");
98
99 // OpenSearch Serverless only defines the "data" access-policy type.
100 const ACCESS_POLICY_TYPE = "data";
101
102 export const AccessPolicyProvider = () =>
103 Provider.effect(
104 AccessPolicy,
105 Effect.gen(function* () {
106 const createName = Effect.fn(function* (
107 id: string,
108 props: { policyName?: string | undefined },
109 ) {
110 return (
111 props.policyName ?? (yield* createPhysicalName({ id, maxLength: 32, lowercase: true }))
112 );
113 });
114
115 const toAttributes = (detail: aoss.AccessPolicyDetail) => ({
116 policyName: detail.name!,
117 type: detail.type!,
118 policyVersion: detail.policyVersion!,
119 description: detail.description,
120 });
121
122 return AccessPolicy.Provider.of({
123 stables: ["policyName", "type"],
124
125 list: () =>
126 Effect.gen(function* () {
127 const pages = yield* aoss.listAccessPolicies
128 .pages({ type: ACCESS_POLICY_TYPE })
129 .pipe(Stream.runCollect);
130 return Array.from(pages)
131 .flatMap((page) => page.accessPolicySummaries ?? [])
132 .filter(
133 (s) =>
134 s.name !== undefined && s.type !== undefined && s.policyVersion !== undefined,
135 )
136 .map((s) => ({
137 policyName: s.name!,
138 type: s.type!,
139 policyVersion: s.policyVersion!,
140 description: s.description,
141 }));
142 }),
143
144 read: Effect.fn(function* ({ id, olds, output }) {
145 const name = output?.policyName ?? (yield* createName(id, olds ?? {}));
146 const found = yield* aoss
147 .getAccessPolicy({ type: ACCESS_POLICY_TYPE, name })
148 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined));
149 if (found?.accessPolicyDetail === undefined) {
150 return undefined;
151 }
152 // Access policies carry no tags, so an existing same-name policy is
153 // adopted.
154 return toAttributes(found.accessPolicyDetail);
155 }),
156
157 diff: Effect.fn(function* ({ id, news, olds }) {
158 if (!isResolved(news)) return undefined;
159 const oldName = yield* createName(id, olds);
160 const newName = yield* createName(id, news);
161 if (oldName !== newName) {
162 return { action: "replace" } as const;
163 }
164 // description/policy fall through to the default update path
165 }),
166
167 reconcile: Effect.fn(function* ({ id, news, output, session }) {
168 const name = output?.policyName ?? (yield* createName(id, news));
169 const policy = stringifyPolicy(news.policy);
170
171 // 1. OBSERVE
172 let detail = yield* aoss.getAccessPolicy({ type: ACCESS_POLICY_TYPE, name }).pipe(
173 Effect.map((r) => r.accessPolicyDetail),
174 Effect.catchTag("ResourceNotFoundException", () => Effect.undefined),
175 );
176
177 // 2. ENSURE
178 if (detail === undefined) {
179 detail = yield* aoss
180 .createAccessPolicy({
181 type: ACCESS_POLICY_TYPE,
182 name,
183 policy,
184 description: news.description,
185 })
186 .pipe(
187 Effect.map((r) => r.accessPolicyDetail),
188 Effect.catchTag("ConflictException", () =>
189 aoss
190 .getAccessPolicy({ type: ACCESS_POLICY_TYPE, name })
191 .pipe(Effect.map((r) => r.accessPolicyDetail)),
192 ),
193 );
194 } else {
195 // 3. SYNC
196 const policyDrift = canonicalizePolicy(detail.policy) !== canonicalizePolicy(policy);
197 const descriptionDrift =
198 news.description !== undefined && news.description !== detail.description;
199 if (policyDrift || descriptionDrift) {
200 detail = yield* aoss
201 .updateAccessPolicy({
202 type: ACCESS_POLICY_TYPE,
203 name,
204 policyVersion: detail.policyVersion!,
205 policy: policyDrift ? policy : undefined,
206 description: descriptionDrift ? news.description : undefined,
207 })
208 .pipe(Effect.map((r) => r.accessPolicyDetail));
209 }
210 }
211
212 if (detail?.name === undefined) {
213 return yield* aoss.ResourceNotFoundException.make({
214 message: `access policy ${name} not visible after reconcile`,
215 });
216 }
217 yield* session.note(name);
218 return toAttributes(detail);
219 }),
220
221 delete: Effect.fn(function* ({ output }) {
222 yield* retryWhileConflict(
223 aoss.deleteAccessPolicy({
224 type: ACCESS_POLICY_TYPE,
225 name: output.policyName,
226 }),
227 ).pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.void));
228 }),
229 });
230 }),
231 );