The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import * as guardduty from "@distilled.cloud/aws/guardduty"; |
| 2 | import { Unowned } from "alchemy/AdoptPolicy"; |
| 3 | import { isResolved } from "alchemy/Diff"; |
| 4 | import { createPhysicalName } from "alchemy/PhysicalName"; |
| 5 | import * as Provider from "alchemy/Provider"; |
| 6 | import { Resource } from "alchemy/Resource"; |
| 7 | import { createInternalTags, diffTags, hasAlchemyTags, tagRecord } from "alchemy/Tags"; |
| 8 | import * as Effect from "effect/Effect"; |
| 9 | import * as Stream from "effect/Stream"; |
| 10 | import { AWSEnvironment } from "../Environment.ts"; |
| 11 | import type { Providers } from "../Providers.ts"; |
| 12 | |
| 13 | /** File format of the hosted IP list. */ |
| 14 | export type IpSetFormat = "TXT" | "STIX" | "OTX_CSV" | "ALIEN_VAULT" | "PROOF_POINT" | "FIRE_EYE"; |
| 15 | |
| 16 | export interface IPSetProps { |
| 17 | /** |
| 18 | * ID of the detector the trusted IP set belongs to. Changing this replaces |
| 19 | * the IP set. |
| 20 | */ |
| 21 | detectorId: string; |
| 22 | |
| 23 | /** |
| 24 | * Display name of the IP set. If omitted, a unique name is generated. |
| 25 | * Updatable in place. |
| 26 | */ |
| 27 | name?: string; |
| 28 | |
| 29 | /** |
| 30 | * Format of the file hosting the IP list. Changing this replaces the IP |
| 31 | * set. |
| 32 | */ |
| 33 | format: IpSetFormat; |
| 34 | |
| 35 | /** |
| 36 | * S3 URI of the file containing the trusted IP list, e.g. |
| 37 | * `https://s3.amazonaws.com/my-bucket/trusted.txt`. Updatable in place. |
| 38 | */ |
| 39 | location: string; |
| 40 | |
| 41 | /** |
| 42 | * Whether GuardDuty actively uses the IP set. Traffic from trusted IPs |
| 43 | * does not generate findings while active. Updatable in place. |
| 44 | * @default true |
| 45 | */ |
| 46 | activate?: boolean; |
| 47 | |
| 48 | /** |
| 49 | * Account ID of the bucket owner hosting the list (guards against bucket |
| 50 | * squatting). |
| 51 | */ |
| 52 | expectedBucketOwner?: string; |
| 53 | |
| 54 | /** |
| 55 | * Tags applied to the IP set. Alchemy ownership tags are merged in |
| 56 | * automatically. |
| 57 | */ |
| 58 | tags?: Record<string, string>; |
| 59 | } |
| 60 | |
| 61 | /** @resource */ |
| 62 | export interface IPSet extends Resource< |
| 63 | "AWS.GuardDuty.IPSet", |
| 64 | IPSetProps, |
| 65 | { |
| 66 | /** ID of the detector the IP set belongs to. */ |
| 67 | detectorId: string; |
| 68 | /** The auto-generated IP set ID. */ |
| 69 | ipSetId: string; |
| 70 | /** ARN of the IP set. */ |
| 71 | ipSetArn: string; |
| 72 | /** Display name of the IP set. */ |
| 73 | name: string; |
| 74 | /** File format of the hosted list. */ |
| 75 | format: string; |
| 76 | /** S3 URI of the hosted list. */ |
| 77 | location: string; |
| 78 | /** Current status (`ACTIVE`, `INACTIVE`, `ACTIVATING`, `ERROR`, …). */ |
| 79 | status: string; |
| 80 | }, |
| 81 | never, |
| 82 | Providers |
| 83 | > {} |
| 84 | |
| 85 | /** |
| 86 | * A GuardDuty trusted IP set — an S3-hosted list of IP addresses GuardDuty |
| 87 | * treats as trusted, suppressing findings for traffic from them. The list |
| 88 | * file must exist in S3 before activation; name, location, and activation |
| 89 | * are updatable in place, while format changes replace the set. |
| 90 | * |
| 91 | * ### Trusting Known IPs |
| 92 | * **Example:** Trust the office IP range |
| 93 | * ```typescript |
| 94 | * const detector = yield* AWS.GuardDuty.Detector("Detector", {}); |
| 95 | * const ipSet = yield* AWS.GuardDuty.IPSet("OfficeIPs", { |
| 96 | * detectorId: detector.detectorId, |
| 97 | * format: "TXT", |
| 98 | * location: "https://s3.amazonaws.com/my-security-bucket/office-ips.txt", |
| 99 | * }); |
| 100 | * ``` |
| 101 | * |
| 102 | * **Example:** Stage a list without activating it |
| 103 | * ```typescript |
| 104 | * const ipSet = yield* AWS.GuardDuty.IPSet("StagedIPs", { |
| 105 | * detectorId: detector.detectorId, |
| 106 | * format: "TXT", |
| 107 | * location: "https://s3.amazonaws.com/my-security-bucket/staged.txt", |
| 108 | * activate: false, |
| 109 | * }); |
| 110 | * ``` |
| 111 | */ |
| 112 | const IPSetResource = Resource<IPSet>("AWS.GuardDuty.IPSet"); |
| 113 | |
| 114 | export { IPSetResource as IPSet }; |
| 115 | |
| 116 | const ipSetArn = (region: string, accountId: string, detectorId: string, ipSetId: string) => |
| 117 | `arn:aws:guardduty:${region}:${accountId}:detector/${detectorId}/ipset/${ipSetId}`; |
| 118 | |
| 119 | /** Statuses that count as "the set is (becoming) active". */ |
| 120 | const ACTIVE_STATUSES = ["ACTIVE", "ACTIVATING"]; |
| 121 | |
| 122 | export const IPSetProvider = () => |
| 123 | Provider.effect( |
| 124 | IPSetResource, |
| 125 | Effect.gen(function* () { |
| 126 | const toName = (id: string, props: { name?: string }) => |
| 127 | props.name ? Effect.succeed(props.name) : createPhysicalName({ id, maxLength: 64 }); |
| 128 | |
| 129 | const getIPSet = (detectorId: string, ipSetId: string) => |
| 130 | guardduty |
| 131 | .getIPSet({ DetectorId: detectorId, IpSetId: ipSetId }) |
| 132 | .pipe(Effect.catchTag("BadRequestException", () => Effect.undefined)); |
| 133 | |
| 134 | // Recover the set id after state loss by matching the deterministic |
| 135 | // name across the detector's IP sets. |
| 136 | const findByName = Effect.fn(function* (detectorId: string, name: string) { |
| 137 | const pages = yield* guardduty.listIPSets |
| 138 | .pages({ DetectorId: detectorId }) |
| 139 | .pipe(Stream.runCollect); |
| 140 | for (const ipSetId of Array.from(pages).flatMap((page) => page.IpSetIds ?? [])) { |
| 141 | const s = yield* getIPSet(detectorId, ipSetId); |
| 142 | if (s?.Name === name && s.Status !== "DELETE_PENDING") { |
| 143 | return { ipSetId, set: s }; |
| 144 | } |
| 145 | } |
| 146 | return undefined; |
| 147 | }); |
| 148 | |
| 149 | const buildAttrs = Effect.fn(function* ( |
| 150 | detectorId: string, |
| 151 | ipSetId: string, |
| 152 | s: guardduty.GetIPSetResponse, |
| 153 | ) { |
| 154 | const { accountId, region } = yield* AWSEnvironment.current; |
| 155 | return { |
| 156 | detectorId, |
| 157 | ipSetId, |
| 158 | ipSetArn: ipSetArn(region, accountId, detectorId, ipSetId), |
| 159 | name: s.Name, |
| 160 | format: s.Format, |
| 161 | location: s.Location, |
| 162 | status: s.Status, |
| 163 | }; |
| 164 | }); |
| 165 | |
| 166 | return { |
| 167 | stables: ["detectorId", "ipSetId", "ipSetArn"], |
| 168 | diff: Effect.fn(function* ({ olds, news }) { |
| 169 | if (!isResolved(news)) return; |
| 170 | if (olds === undefined) return; |
| 171 | if (olds.detectorId !== news.detectorId || olds.format !== news.format) { |
| 172 | return { action: "replace" } as const; |
| 173 | } |
| 174 | }), |
| 175 | read: Effect.fn(function* ({ id, olds, output }) { |
| 176 | const detectorId = output?.detectorId ?? olds?.detectorId; |
| 177 | if (!detectorId) return undefined; |
| 178 | let ipSetId = output?.ipSetId; |
| 179 | let set = ipSetId ? yield* getIPSet(detectorId, ipSetId) : undefined; |
| 180 | if (!set) { |
| 181 | const found = yield* findByName(detectorId, yield* toName(id, olds ?? {})); |
| 182 | if (!found) return undefined; |
| 183 | ({ ipSetId, set } = found); |
| 184 | } |
| 185 | const attrs = yield* buildAttrs(detectorId, ipSetId!, set); |
| 186 | return (yield* hasAlchemyTags(id, set.Tags)) ? attrs : Unowned(attrs); |
| 187 | }), |
| 188 | list: () => |
| 189 | Effect.gen(function* () { |
| 190 | const { DetectorIds } = yield* guardduty.listDetectors({}); |
| 191 | const out: IPSet["Attributes"][] = []; |
| 192 | for (const detectorId of DetectorIds ?? []) { |
| 193 | const pages = yield* guardduty.listIPSets |
| 194 | .pages({ DetectorId: detectorId }) |
| 195 | .pipe(Stream.runCollect); |
| 196 | for (const ipSetId of Array.from(pages).flatMap((page) => page.IpSetIds ?? [])) { |
| 197 | const s = yield* getIPSet(detectorId, ipSetId); |
| 198 | if (s) out.push(yield* buildAttrs(detectorId, ipSetId, s)); |
| 199 | } |
| 200 | } |
| 201 | return out; |
| 202 | }), |
| 203 | reconcile: Effect.fn(function* ({ id, news, output, session }) { |
| 204 | const detectorId = news.detectorId; |
| 205 | const name = yield* toName(id, news); |
| 206 | const desiredActivate = news.activate ?? true; |
| 207 | const internalTags = yield* createInternalTags(id); |
| 208 | const desiredTags = { ...news.tags, ...internalTags }; |
| 209 | |
| 210 | // 1. OBSERVE — output.ipSetId is only a cache; fall back to a |
| 211 | // name search so a crash-and-retry converges. |
| 212 | let ipSetId = output?.ipSetId; |
| 213 | let live = ipSetId ? yield* getIPSet(detectorId, ipSetId) : undefined; |
| 214 | if (!live) { |
| 215 | const found = yield* findByName(detectorId, name); |
| 216 | if (found) ({ ipSetId, set: live } = found); |
| 217 | } |
| 218 | |
| 219 | if (!live || !ipSetId) { |
| 220 | // 2. ENSURE — create with tags applied inline. |
| 221 | const created = yield* guardduty.createIPSet({ |
| 222 | DetectorId: detectorId, |
| 223 | Name: name, |
| 224 | Format: news.format, |
| 225 | Location: news.location, |
| 226 | Activate: desiredActivate, |
| 227 | ExpectedBucketOwner: news.expectedBucketOwner, |
| 228 | Tags: desiredTags, |
| 229 | }); |
| 230 | ipSetId = created.IpSetId; |
| 231 | } else { |
| 232 | // 3. SYNC settings — observed ↔ desired. |
| 233 | const observedActive = ACTIVE_STATUSES.includes(live.Status); |
| 234 | const drift = |
| 235 | live.Name !== name || |
| 236 | live.Location !== news.location || |
| 237 | observedActive !== desiredActivate; |
| 238 | if (drift) { |
| 239 | yield* guardduty.updateIPSet({ |
| 240 | DetectorId: detectorId, |
| 241 | IpSetId: ipSetId, |
| 242 | Name: name, |
| 243 | Location: news.location, |
| 244 | Activate: desiredActivate, |
| 245 | ExpectedBucketOwner: news.expectedBucketOwner, |
| 246 | }); |
| 247 | } |
| 248 | |
| 249 | // 3b. SYNC tags — diff against OBSERVED cloud tags. |
| 250 | const { accountId, region } = yield* AWSEnvironment.current; |
| 251 | const arn = ipSetArn(region, accountId, detectorId, ipSetId); |
| 252 | const { upsert, removed } = diffTags(tagRecord(live.Tags), desiredTags); |
| 253 | if (upsert.length > 0) { |
| 254 | yield* guardduty.tagResource({ |
| 255 | ResourceArn: arn, |
| 256 | Tags: Object.fromEntries(upsert.map((t) => [t.Key, t.Value])), |
| 257 | }); |
| 258 | } |
| 259 | if (removed.length > 0) { |
| 260 | yield* guardduty.untagResource({ |
| 261 | ResourceArn: arn, |
| 262 | TagKeys: removed, |
| 263 | }); |
| 264 | } |
| 265 | } |
| 266 | |
| 267 | // 4. RETURN fresh attributes. |
| 268 | const final = yield* guardduty.getIPSet({ |
| 269 | DetectorId: detectorId, |
| 270 | IpSetId: ipSetId, |
| 271 | }); |
| 272 | yield* session.note(`${detectorId}/${ipSetId}`); |
| 273 | return yield* buildAttrs(detectorId, ipSetId, final); |
| 274 | }), |
| 275 | delete: Effect.fn(function* ({ output }) { |
| 276 | // Idempotent — the set (or its whole detector) may already be |
| 277 | // gone; both surface as BadRequestException. |
| 278 | yield* guardduty |
| 279 | .deleteIPSet({ |
| 280 | DetectorId: output.detectorId, |
| 281 | IpSetId: output.ipSetId, |
| 282 | }) |
| 283 | .pipe(Effect.catchTag("BadRequestException", () => Effect.void)); |
| 284 | }), |
| 285 | }; |
| 286 | }), |
| 287 | ); |