@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 285 lines 11.1 KB
Raw
1 import * as ec2 from "@distilled.cloud/aws/ec2";
2 import { isResolved } from "alchemy/Diff";
3 import * as Provider from "alchemy/Provider";
4 import { Resource } from "alchemy/Resource";
5 import { canonicalCidr } from "alchemy/Util/ip-address";
6 import * as Data from "effect/Data";
7 import * as Effect from "effect/Effect";
8 import * as Stream from "effect/Stream";
9 import type { Providers } from "../Providers.ts";
10 import type { ClientVpnEndpointId } from "./ClientVpnEndpoint.ts";
11 import { retryClientVpn } from "./ClientVpnWait.ts";
12
13 /** Immutable settings for a Client VPN ingress authorization rule. */
14 export interface ClientVpnAuthorizationRuleProps {
15 /** The Client VPN endpoint. Changing this replaces the rule. */
16 clientVpnEndpointId: ClientVpnEndpointId;
17 /** The destination IPv4 CIDR to authorize. Changing this replaces the rule. */
18 targetNetworkCidr: string;
19 /**
20 * The directory or federated identity group allowed to access the network.
21 * Required unless authorizeAllGroups is true. Changing this replaces the rule.
22 */
23 accessGroupId?: string;
24 /**
25 * Authorize every authenticated client instead of one access group.
26 * Cannot be combined with accessGroupId. Changing this replaces the rule.
27 * @default false
28 */
29 authorizeAllGroups?: boolean;
30 /** A description of the rule. Changing this replaces the rule. */
31 description?: string;
32 }
33
34 /** An ingress authorization rule owned by a Client VPN endpoint. */
35 export interface ClientVpnAuthorizationRule extends Resource<
36 "AWS.EC2.ClientVpnAuthorizationRule",
37 ClientVpnAuthorizationRuleProps,
38 {
39 /** The Client VPN endpoint containing the rule. */
40 clientVpnEndpointId: ClientVpnEndpointId;
41 /** The canonical destination network CIDR. */
42 targetNetworkCidr: string;
43 /** The authorized group, absent for an all-groups rule. */
44 accessGroupId: string | undefined;
45 /** Whether all authenticated clients are authorized. */
46 authorizeAllGroups: boolean;
47 /** The observed description. */
48 description: string | undefined;
49 /** The current authorization state. */
50 status: ec2.ClientVpnAuthorizationRuleStatusCode;
51 /** Additional information about the authorization state. */
52 statusMessage: string | undefined;
53 },
54 never,
55 Providers
56 > {}
57
58 /**
59 * Authorizes Client VPN clients to access a destination network. Authorization
60 * does not create a route: configure a target association and any required routes
61 * separately. Specify either accessGroupId or authorizeAllGroups: true.
62 *
63 * Every property is immutable, including description. Description-only changes
64 * revoke the old rule before creating its replacement. This resource manages the
65 * declared endpoint/CIDR/group identity, including an existing rule discovered
66 * without cached state. Rules have no independent ownership markers. Revoking an
67 * all-groups rule leaves group-specific rules untouched.
68 *
69 * Readiness waits default to 30 minutes. Set `AWS_CLIENT_VPN_TIMEOUT` to a
70 * positive finite duration, such as `45 minutes`, to override this deadline.
71 *
72 * ### Authorizing All Clients
73 * **Example:** Permit authenticated clients to reach the VPC
74 * ```typescript
75 * const rule = yield* AWS.EC2.ClientVpnAuthorizationRule("VpnVpcAccess", {
76 * clientVpnEndpointId: endpoint.clientVpnEndpointId,
77 * targetNetworkCidr: "10.0.0.0/16",
78 * authorizeAllGroups: true,
79 * description: "Access to the VPC",
80 * });
81 * ```
82 *
83 * ### Authorizing One Group
84 * **Example:** Restrict a destination to a directory group
85 * ```typescript
86 * const rule = yield* AWS.EC2.ClientVpnAuthorizationRule("VpnAdminAccess", {
87 * clientVpnEndpointId: endpoint.clientVpnEndpointId,
88 * targetNetworkCidr: "10.0.1.0/24",
89 * accessGroupId: "S-1-5-21-123456789-123456789-123456789-1234",
90 * });
91 * ```
92 *
93 * @resource
94 */
95 export const ClientVpnAuthorizationRule = Resource<ClientVpnAuthorizationRule>(
96 "AWS.EC2.ClientVpnAuthorizationRule",
97 );
98
99 class ClientVpnAuthorizationPending extends Data.TaggedError("ClientVpnAuthorizationPending")<{
100 message: string;
101 }> {}
102
103 class ClientVpnAuthorizationFailed extends Data.TaggedError("ClientVpnAuthorizationFailed")<{
104 message: string;
105 }> {}
106
107 const rules = (clientVpnEndpointId: ClientVpnEndpointId) =>
108 ec2.describeClientVpnAuthorizationRules.items({ ClientVpnEndpointId: clientVpnEndpointId }).pipe(
109 Stream.runCollect,
110 Effect.map((items) => items.filter((rule) => rule.Status?.Code !== "revoked")),
111 Effect.catchTag("InvalidClientVpnEndpointId.NotFound", () =>
112 Effect.succeed([] as ec2.AuthorizationRule[]),
113 ),
114 );
115
116 const findRule = (props: ClientVpnAuthorizationRuleProps) =>
117 rules(props.clientVpnEndpointId).pipe(
118 Effect.map((items) =>
119 items.find(
120 (rule) =>
121 canonicalCidr(rule.DestinationCidr) === canonicalCidr(props.targetNetworkCidr) &&
122 (rule.AccessAll ?? false) === (props.authorizeAllGroups ?? false) &&
123 (props.authorizeAllGroups === true || rule.GroupId === props.accessGroupId),
124 ),
125 ),
126 );
127
128 const toAttributes = (
129 clientVpnEndpointId: ClientVpnEndpointId,
130 rule: ec2.AuthorizationRule,
131 ): ClientVpnAuthorizationRule["Attributes"] => ({
132 clientVpnEndpointId,
133 targetNetworkCidr: rule.DestinationCidr!,
134 accessGroupId: rule.AccessAll ? undefined : rule.GroupId,
135 authorizeAllGroups: rule.AccessAll ?? false,
136 description: rule.Description,
137 status: rule.Status?.Code ?? "authorizing",
138 statusMessage: rule.Status?.Message,
139 });
140
141 const waitForRule = (props: ClientVpnAuthorizationRuleProps, deleted: boolean) =>
142 Effect.gen(function* () {
143 const rule = yield* findRule(props);
144 if (deleted && !rule) return undefined;
145 if (!deleted && rule?.Status?.Code === "active") return rule;
146 if (!deleted && rule?.Status?.Code === "failed") {
147 return yield* new ClientVpnAuthorizationFailed({
148 message: rule.Status.Message ?? "Client VPN authorization failed",
149 });
150 }
151 return yield* new ClientVpnAuthorizationPending({
152 message: `Client VPN authorization for ${props.targetNetworkCidr} is ${rule?.Status?.Code ?? "not visible"}; waiting for ${deleted ? "revocation" : "active"}`,
153 });
154 }).pipe((effect) =>
155 retryClientVpn(effect, (error) => error._tag === "ClientVpnAuthorizationPending"),
156 );
157
158 const removeRule = Effect.fn(function* (props: ClientVpnAuthorizationRuleProps) {
159 const rule = yield* findRule(props);
160 if (!rule) return;
161 if (rule.Status?.Code !== "revoking") {
162 yield* ec2
163 .revokeClientVpnIngress({
164 ClientVpnEndpointId: props.clientVpnEndpointId,
165 TargetNetworkCidr: canonicalCidr(props.targetNetworkCidr),
166 AccessGroupId: props.authorizeAllGroups ? undefined : props.accessGroupId,
167 RevokeAllGroups: props.authorizeAllGroups ?? false,
168 })
169 .pipe(
170 Effect.catchTag(
171 [
172 "InvalidClientVpnEndpointId.NotFound",
173 "InvalidClientVpnEndpointAuthorizationRuleNotFound",
174 ],
175 () => Effect.void,
176 ),
177 (effect) => retryClientVpn(effect, (error) => error._tag === "IncorrectState"),
178 );
179 }
180 yield* waitForRule(props, true);
181 });
182
183 /** Live AWS provider for ClientVpnAuthorizationRule. */
184 export const ClientVpnAuthorizationRuleProvider = () =>
185 Provider.effect(
186 ClientVpnAuthorizationRule,
187 Effect.gen(function* () {
188 return {
189 stables: [
190 "clientVpnEndpointId",
191 "targetNetworkCidr",
192 "accessGroupId",
193 "authorizeAllGroups",
194 ],
195 nuke: { dependsOn: ["AWS.EC2.ClientVpnEndpoint"] },
196 list: Effect.fn(function* () {
197 const endpoints = yield* ec2.describeClientVpnEndpoints.items({}).pipe(Stream.runCollect);
198 const items = yield* Effect.forEach(endpoints, (endpoint) =>
199 rules(endpoint.ClientVpnEndpointId as ClientVpnEndpointId).pipe(
200 Effect.map((items) =>
201 items.map((rule) =>
202 toAttributes(endpoint.ClientVpnEndpointId as ClientVpnEndpointId, rule),
203 ),
204 ),
205 ),
206 );
207 return items.flat();
208 }),
209 read: Effect.fn(function* ({ olds, output }) {
210 const props = output ?? olds;
211 const rule = yield* findRule(props);
212 if (!rule) return undefined;
213 return toAttributes(props.clientVpnEndpointId, rule);
214 }),
215 diff: Effect.fn(function* ({ olds, news }) {
216 if (!isResolved(news)) {
217 return { action: "replace", deleteFirst: true };
218 }
219 const sameKey =
220 news.clientVpnEndpointId === olds.clientVpnEndpointId &&
221 canonicalCidr(news.targetNetworkCidr) === canonicalCidr(olds.targetNetworkCidr) &&
222 news.accessGroupId === olds.accessGroupId &&
223 (news.authorizeAllGroups ?? false) === (olds.authorizeAllGroups ?? false);
224 if (
225 !sameKey ||
226 news.targetNetworkCidr !== olds.targetNetworkCidr ||
227 news.authorizeAllGroups !== olds.authorizeAllGroups ||
228 news.description !== olds.description
229 ) {
230 return { action: "replace", deleteFirst: sameKey };
231 }
232 const rule = yield* findRule(news);
233 if (!rule) return { action: "update" };
234 if (
235 (rule.Description ?? "") !== (news.description ?? "") ||
236 rule.Status?.Code === "failed"
237 ) {
238 return { action: "replace", deleteFirst: true };
239 }
240 if (rule.Status?.Code !== "active") return { action: "update" };
241 }),
242 reconcile: Effect.fn(function* ({ news }) {
243 if (
244 (news.authorizeAllGroups === true) === (news.accessGroupId !== undefined) ||
245 news.accessGroupId === ""
246 ) {
247 return yield* new ClientVpnAuthorizationFailed({
248 message: "Specify exactly one of accessGroupId or authorizeAllGroups: true.",
249 });
250 }
251 let rule = yield* findRule(news);
252 if (
253 rule &&
254 (rule.Status?.Code === "revoking" ||
255 (rule.Description ?? "") !== (news.description ?? ""))
256 ) {
257 yield* removeRule(news);
258 rule = undefined;
259 }
260 if (!rule) {
261 // Do not replay a completed create token after out-of-band deletion.
262 const clientToken = yield* Effect.sync(() => crypto.randomUUID());
263 yield* ec2
264 .authorizeClientVpnIngress({
265 ClientVpnEndpointId: news.clientVpnEndpointId,
266 TargetNetworkCidr: canonicalCidr(news.targetNetworkCidr),
267 AccessGroupId: news.accessGroupId,
268 AuthorizeAllGroups: news.authorizeAllGroups ?? false,
269 Description: news.description,
270 ClientToken: clientToken,
271 })
272 .pipe(
273 Effect.catchTag("InvalidClientVpnDuplicateAuthorizationRule", () => Effect.void),
274 (effect) => retryClientVpn(effect, (error) => error._tag === "IncorrectState"),
275 );
276 }
277 const active = yield* waitForRule(news, false);
278 return toAttributes(news.clientVpnEndpointId, active!);
279 }),
280 delete: Effect.fn(function* ({ output }) {
281 yield* removeRule(output);
282 }),
283 };
284 }),
285 );