@devries-cameron20 / t3code Mirror · read-only
Fork 0

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, 04:45 UTC

main
ts 201 lines 7.28 KB
Raw
1 import * as xray from "@distilled.cloud/aws/xray";
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 Option from "effect/Option";
8 import * as Stream from "effect/Stream";
9 import type { Providers } from "../Providers.ts";
10
11 export interface ResourcePolicyProps {
12 /**
13 * Name of the resource policy. Must be unique within the account (each
14 * account holds at most 5 X-Ray resource policies).
15 *
16 * Changing the name replaces the policy.
17 * @default ${app}-${stage}-${id}
18 */
19 policyName?: string;
20 /**
21 * The IAM resource-based policy document (JSON, maximum 5 KB) granting
22 * one or more Amazon Web Services services and accounts permission to
23 * access X-Ray — e.g. allowing SNS active tracing to call
24 * `xray:PutTraceSegments`. Updated in place.
25 */
26 policyDocument: string;
27 /**
28 * Skip the check that prevents locking yourself out of the ability to
29 * change the policy in the future.
30 * @default false
31 */
32 bypassPolicyLockoutCheck?: boolean;
33 }
34
35 export interface ResourcePolicy extends Resource<
36 "AWS.XRay.ResourcePolicy",
37 ResourcePolicyProps,
38 {
39 /**
40 * Name of the resource policy.
41 */
42 policyName: string;
43 /**
44 * Revision id of the policy document, changed on every update.
45 */
46 policyRevisionId: string | undefined;
47 },
48 never,
49 Providers
50 > {}
51
52 /**
53 * An X-Ray resource policy — an account-level, resource-based IAM policy
54 * that grants other Amazon Web Services services and accounts access to
55 * X-Ray, e.g. allowing SNS active tracing to send trace segments.
56 *
57 * Resource policies are not taggable; ownership is keyed by the
58 * deterministic policy name.
59 * ### Creating Resource Policies
60 * **Example:** Allow SNS active tracing to send trace data
61 * ```typescript
62 * import * as XRay from "@alchemy.run/aws/XRay";
63 *
64 * const policy = yield* XRay.ResourcePolicy("SnsActiveTracing", {
65 * policyDocument: JSON.stringify({
66 * Version: "2012-10-17",
67 * Statement: [
68 * {
69 * Effect: "Allow",
70 * Principal: { Service: "sns.amazonaws.com" },
71 * Action: ["xray:PutTraceSegments", "xray:GetSamplingRules"],
72 * Resource: "*",
73 * },
74 * ],
75 * }),
76 * });
77 * ```
78 *
79 * @resource
80 */
81 export const ResourcePolicy = Resource<ResourcePolicy>("AWS.XRay.ResourcePolicy");
82
83 /** Order-insensitive canonical form of a JSON policy document. */
84 const canonicalJson = (document: string): string => {
85 const sort = (value: unknown): unknown =>
86 Array.isArray(value)
87 ? value.map(sort)
88 : value !== null && typeof value === "object"
89 ? Object.fromEntries(
90 Object.entries(value as Record<string, unknown>)
91 .sort(([a], [b]) => a.localeCompare(b))
92 .map(([k, v]) => [k, sort(v)]),
93 )
94 : value;
95 try {
96 return JSON.stringify(sort(JSON.parse(document)));
97 } catch {
98 return document;
99 }
100 };
101
102 export const ResourcePolicyProvider = () =>
103 Provider.effect(
104 ResourcePolicy,
105 Effect.gen(function* () {
106 const createPolicyName = Effect.fn(function* (
107 id: string,
108 props: Pick<ResourcePolicyProps, "policyName">,
109 ) {
110 // X-Ray policy names are limited to 128 characters.
111 return props.policyName ?? (yield* createPhysicalName({ id, maxLength: 128 }));
112 });
113
114 // X-Ray has no GetResourcePolicy — observe by enumerating the (at
115 // most 5) policies in the account and matching on the policy name.
116 const observePolicy = (policyName: string) =>
117 xray.listResourcePolicies.items({}).pipe(
118 Stream.filter((policy) => policy.PolicyName === policyName),
119 Stream.runHead,
120 Effect.map(Option.getOrUndefined),
121 );
122
123 return ResourcePolicy.Provider.of({
124 stables: ["policyName"],
125 list: () =>
126 Effect.gen(function* () {
127 const policies = yield* xray.listResourcePolicies.items({}).pipe(Stream.runCollect);
128 return Array.from(policies).flatMap((policy) =>
129 policy.PolicyName
130 ? [
131 {
132 policyName: policy.PolicyName,
133 policyRevisionId: policy.PolicyRevisionId,
134 },
135 ]
136 : [],
137 );
138 }),
139 read: Effect.fn(function* ({ id, olds, output }) {
140 const policyName = output?.policyName ?? (yield* createPolicyName(id, olds ?? {}));
141 const found = yield* observePolicy(policyName);
142 if (found === undefined) return undefined;
143 // Resource policies are not taggable — ownership is keyed by the
144 // deterministic policy name.
145 return { policyName, policyRevisionId: found.PolicyRevisionId };
146 }),
147 diff: Effect.fn(function* ({ id, news, olds }) {
148 if (!isResolved(news)) return undefined;
149 const oldName = yield* createPolicyName(id, olds ?? {});
150 const newName = yield* createPolicyName(id, news ?? {});
151 if (oldName !== newName) {
152 return { action: "replace" } as const;
153 }
154 // fall through: engine default update logic for the document
155 }),
156 reconcile: Effect.fn(function* ({ id, news, output, session }) {
157 const policyName = output?.policyName ?? (yield* createPolicyName(id, news));
158
159 // 1. OBSERVE — the live policy list is authoritative.
160 const existing = yield* observePolicy(policyName);
161
162 // 2/3. ENSURE + SYNC — `putResourcePolicy` is a true upsert; call
163 // it only when the canonical document drifts. The observed
164 // revision id guards against concurrent writers; a revision race
165 // surfaces as the typed InvalidPolicyRevisionIdException, which we
166 // resolve by re-observing and applying once more.
167 const putPolicy = (revisionId: string | undefined) =>
168 xray
169 .putResourcePolicy({
170 PolicyName: policyName,
171 PolicyDocument: news.policyDocument,
172 PolicyRevisionId: revisionId,
173 BypassPolicyLockoutCheck: news.bypassPolicyLockoutCheck,
174 })
175 .pipe(Effect.map((r) => r.ResourcePolicy));
176
177 const policy =
178 existing?.PolicyDocument !== undefined &&
179 canonicalJson(existing.PolicyDocument) === canonicalJson(news.policyDocument)
180 ? existing
181 : yield* putPolicy(existing?.PolicyRevisionId).pipe(
182 Effect.catchTag("InvalidPolicyRevisionIdException", () =>
183 observePolicy(policyName).pipe(
184 Effect.flatMap((observed) => putPolicy(observed?.PolicyRevisionId)),
185 ),
186 ),
187 );
188
189 yield* session.note(policyName);
190 return { policyName, policyRevisionId: policy?.PolicyRevisionId };
191 }),
192 delete: Effect.fn(function* ({ output }) {
193 // DeleteResourcePolicy without a revision id skips the revision
194 // check and is idempotent — deleting a missing policy succeeds.
195 yield* xray.deleteResourcePolicy({
196 PolicyName: output.policyName,
197 });
198 }),
199 });
200 }),
201 );