The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import * as iam from "@distilled.cloud/cloudflare/iam"; |
| 2 | import { createPhysicalName } from "alchemy/PhysicalName"; |
| 3 | import * as Provider from "alchemy/Provider"; |
| 4 | import { Resource } from "alchemy/Resource"; |
| 5 | import * as Effect from "effect/Effect"; |
| 6 | import * as Predicate from "effect/Predicate"; |
| 7 | import * as Stream from "effect/Stream"; |
| 8 | import { CloudflareEnvironment } from "../CloudflareEnvironment.ts"; |
| 9 | import type { Providers } from "../Providers.ts"; |
| 10 | |
| 11 | const TypeId = "Cloudflare.Iam.UserGroup" as const; |
| 12 | type TypeId = typeof TypeId; |
| 13 | |
| 14 | /** |
| 15 | * A fine-grained policy attached to a user group: an allow/deny decision |
| 16 | * over a set of permission groups (what actions) and resource groups |
| 17 | * (which resources). |
| 18 | */ |
| 19 | export interface UserGroupPolicyInput { |
| 20 | /** |
| 21 | * Whether the policy allows or denies the combined permission/resource |
| 22 | * groups. Note: Cloudflare currently rejects `deny` user-group policies |
| 23 | * with "Policy validation failed" — only `allow` is accepted in |
| 24 | * practice. |
| 25 | */ |
| 26 | access: "allow" | "deny"; |
| 27 | /** |
| 28 | * IDs of the permission groups (what actions are permitted). Look these |
| 29 | * up via the account's `/iam/permission_groups` catalog. |
| 30 | */ |
| 31 | permissionGroups: string[]; |
| 32 | /** |
| 33 | * IDs of the resource groups (which resources the permissions apply |
| 34 | * to) — e.g. from {@link ResourceGroup}. |
| 35 | */ |
| 36 | resourceGroups: string[]; |
| 37 | } |
| 38 | |
| 39 | /** |
| 40 | * A fully-resolved user group policy as observed on Cloudflare, including |
| 41 | * the server-assigned policy id. |
| 42 | */ |
| 43 | export interface UserGroupPolicy { |
| 44 | /** |
| 45 | * Server-assigned identifier of the policy. Not stable — Cloudflare |
| 46 | * assigns fresh policy ids on every policy update. |
| 47 | */ |
| 48 | id: string | undefined; |
| 49 | /** Whether the policy allows or denies. */ |
| 50 | access: "allow" | "deny"; |
| 51 | /** IDs of the permission groups in the policy. */ |
| 52 | permissionGroups: string[]; |
| 53 | /** IDs of the resource groups in the policy. */ |
| 54 | resourceGroups: string[]; |
| 55 | } |
| 56 | |
| 57 | export interface UserGroupProps { |
| 58 | /** |
| 59 | * Name of the user group. If omitted, a unique name is generated from |
| 60 | * the app, stage, and logical ID. |
| 61 | * @default ${app}-${stage}-${id} |
| 62 | */ |
| 63 | name?: string; |
| 64 | /** |
| 65 | * Fine-grained policies attached to the user group. Mutable in place — |
| 66 | * the full set is replaced on update. |
| 67 | */ |
| 68 | policies?: UserGroupPolicyInput[]; |
| 69 | } |
| 70 | |
| 71 | export interface UserGroupAttributes { |
| 72 | /** Cloudflare-assigned identifier of the user group. */ |
| 73 | userGroupId: string; |
| 74 | /** The Cloudflare account the user group belongs to. */ |
| 75 | accountId: string; |
| 76 | /** Name of the user group. */ |
| 77 | name: string; |
| 78 | /** Policies attached to the user group (with server-assigned ids). */ |
| 79 | policies: UserGroupPolicy[]; |
| 80 | /** ISO8601 creation timestamp. */ |
| 81 | createdOn: string; |
| 82 | /** ISO8601 last-modified timestamp. */ |
| 83 | modifiedOn: string; |
| 84 | } |
| 85 | |
| 86 | export type UserGroup = Resource<TypeId, UserGroupProps, UserGroupAttributes, never, Providers>; |
| 87 | |
| 88 | /** |
| 89 | * A Cloudflare IAM user group — a named set of account members that share |
| 90 | * fine-grained policies (permission groups scoped to resource groups). |
| 91 | * |
| 92 | * Both `name` and `policies` are mutable in place; updating policies |
| 93 | * replaces the full set. Add members with |
| 94 | * {@link UserGroupMembership}. |
| 95 | * |
| 96 | * Account-scoped IAM (resource groups, user groups) is an Enterprise |
| 97 | * feature. |
| 98 | * ### Creating a User Group |
| 99 | * **Example:** Empty group |
| 100 | * ```typescript |
| 101 | * const group = yield* Cloudflare.Iam.UserGroup("Operators", {}); |
| 102 | * ``` |
| 103 | * |
| 104 | * **Example:** Group with a policy |
| 105 | * ```typescript |
| 106 | * const readers = yield* Cloudflare.Iam.UserGroup("Readers", { |
| 107 | * name: "zone-readers", |
| 108 | * policies: [ |
| 109 | * { |
| 110 | * access: "allow", |
| 111 | * permissionGroups: [readOnlyPermissionGroupId], |
| 112 | * resourceGroups: [resourceGroup.resourceGroupId], |
| 113 | * }, |
| 114 | * ], |
| 115 | * }); |
| 116 | * ``` |
| 117 | * |
| 118 | * ### Managing Members |
| 119 | * **Example:** Add an account member to the group |
| 120 | * ```typescript |
| 121 | * yield* Cloudflare.Iam.UserGroupMembership("SamInReaders", { |
| 122 | * userGroup: readers.userGroupId, |
| 123 | * memberId: accountMember.memberId, |
| 124 | * }); |
| 125 | * ``` |
| 126 | * |
| 127 | * @see https://developers.cloudflare.com/fundamentals/manage-members/user-groups/ |
| 128 | * |
| 129 | * @resource |
| 130 | * @product IAM |
| 131 | * @category Account & Identity |
| 132 | */ |
| 133 | export const UserGroup = Resource<UserGroup>(TypeId); |
| 134 | |
| 135 | /** |
| 136 | * Returns true if the given value is an UserGroup resource. |
| 137 | */ |
| 138 | export const isUserGroup = (value: unknown): value is UserGroup => |
| 139 | Predicate.hasProperty(value, "Type") && value.Type === TypeId; |
| 140 | |
| 141 | export const UserGroupProvider = () => |
| 142 | Provider.succeed(UserGroup, { |
| 143 | stables: ["userGroupId", "accountId", "createdOn"], |
| 144 | |
| 145 | // Account-scoped collection: exhaustively paginate the account's |
| 146 | // user-groups list. Each page item already carries the full shape |
| 147 | // (`id`/`name`/`policies`/`createdOn`/`modifiedOn`) identical to the |
| 148 | // single-get response, so it hydrates directly into `read`'s |
| 149 | // Attributes via `toAttributes` — no per-item re-fetch needed. |
| 150 | list: Effect.fn(function* () { |
| 151 | const { accountId } = yield* yield* CloudflareEnvironment; |
| 152 | return yield* iam.listUserGroups.pages({ accountId }).pipe( |
| 153 | Stream.runCollect, |
| 154 | Effect.map((chunk) => |
| 155 | Array.from(chunk).flatMap((page) => |
| 156 | (page.result ?? []).map((group) => toAttributes(group, accountId)), |
| 157 | ), |
| 158 | ), |
| 159 | ); |
| 160 | }), |
| 161 | |
| 162 | read: Effect.fn(function* ({ id, output, olds }) { |
| 163 | const { accountId } = yield* yield* CloudflareEnvironment; |
| 164 | const acct = output?.accountId ?? accountId; |
| 165 | |
| 166 | if (output?.userGroupId) { |
| 167 | const observed = yield* getUserGroup(acct, output.userGroupId); |
| 168 | return observed ? toAttributes(observed, acct) : undefined; |
| 169 | } |
| 170 | |
| 171 | // Cold read — recover from lost state by matching the deterministic |
| 172 | // physical name (exact match, re-checked client-side). |
| 173 | const name = yield* createGroupName(id, olds?.name); |
| 174 | const match = yield* findByName(acct, name); |
| 175 | if (match) { |
| 176 | const observed = yield* getUserGroup(acct, match.id); |
| 177 | return observed ? toAttributes(observed, acct) : undefined; |
| 178 | } |
| 179 | return undefined; |
| 180 | }), |
| 181 | |
| 182 | reconcile: Effect.fn(function* ({ id, news, output }) { |
| 183 | const { accountId } = yield* yield* CloudflareEnvironment; |
| 184 | const name = yield* createGroupName(id, news.name); |
| 185 | const desired = resolvePolicies(news.policies ?? []); |
| 186 | |
| 187 | // 1. Observe — the id cached on `output` is a hint, not a |
| 188 | // guarantee: a missing group falls through to the name scan and |
| 189 | // then to create. |
| 190 | let observed = output?.userGroupId |
| 191 | ? yield* getUserGroup(accountId, output.userGroupId) |
| 192 | : undefined; |
| 193 | if (!observed) { |
| 194 | const match = yield* findByName(accountId, name); |
| 195 | observed = match ? yield* getUserGroup(accountId, match.id) : undefined; |
| 196 | } |
| 197 | |
| 198 | // 2. Ensure — create when missing. User group names ARE unique on |
| 199 | // Cloudflare's side; losing a create race surfaces as the typed |
| 200 | // `UserGroupNameInUse`, in which case we observe the winner and |
| 201 | // fall through to sync. |
| 202 | if (!observed) { |
| 203 | const created = yield* iam |
| 204 | .createUserGroup({ |
| 205 | accountId, |
| 206 | name, |
| 207 | policies: desired.length > 0 ? desired : undefined, |
| 208 | }) |
| 209 | .pipe(Effect.catchTag("UserGroupNameInUse", () => Effect.undefined)); |
| 210 | if (created) { |
| 211 | return toAttributes(created, accountId); |
| 212 | } |
| 213 | const match = yield* findByName(accountId, name); |
| 214 | observed = match ? yield* getUserGroup(accountId, match.id) : undefined; |
| 215 | if (!observed) { |
| 216 | // The name is claimed but invisible to our listing — re-attempt |
| 217 | // the create so the typed conflict surfaces rather than looping. |
| 218 | const retried = yield* iam.createUserGroup({ |
| 219 | accountId, |
| 220 | name, |
| 221 | policies: desired.length > 0 ? desired : undefined, |
| 222 | }); |
| 223 | return toAttributes(retried, accountId); |
| 224 | } |
| 225 | } |
| 226 | |
| 227 | // 3. Sync — diff observed name/policies against desired. The PUT |
| 228 | // replaces the full policy set and entries MUST be sent without |
| 229 | // ids (Cloudflare rejects re-used policy ids with "Cannot re-use |
| 230 | // policy IDs"); the server assigns fresh ids on every update. |
| 231 | // Skip the call entirely on a no-op. |
| 232 | const observedPolicies = parsePolicies(observed.policies); |
| 233 | const dirty = observed.name !== name || !samePolicies(observedPolicies, desired); |
| 234 | if (!dirty) { |
| 235 | return toAttributes(observed, accountId); |
| 236 | } |
| 237 | |
| 238 | const updated = yield* iam.updateUserGroup({ |
| 239 | accountId, |
| 240 | userGroupId: observed.id, |
| 241 | name, |
| 242 | policies: desired, |
| 243 | }); |
| 244 | return toAttributes(updated, accountId); |
| 245 | }), |
| 246 | |
| 247 | delete: Effect.fn(function* ({ output }) { |
| 248 | yield* iam |
| 249 | .deleteUserGroup({ |
| 250 | accountId: output.accountId, |
| 251 | userGroupId: output.userGroupId, |
| 252 | }) |
| 253 | .pipe(Effect.catchTag("UserGroupNotFound", () => Effect.void)); |
| 254 | }), |
| 255 | }); |
| 256 | |
| 257 | type ObservedUserGroup = iam.GetUserGroupResponse; |
| 258 | |
| 259 | /** |
| 260 | * Read a user group by id, mapping "gone" (`UserGroupNotFound`, |
| 261 | * HTTP 404) to `undefined`. |
| 262 | */ |
| 263 | const getUserGroup = (accountId: string, userGroupId: string) => |
| 264 | iam.getUserGroup({ accountId, userGroupId }).pipe( |
| 265 | Effect.map((g): ObservedUserGroup | undefined => g), |
| 266 | Effect.catchTag("UserGroupNotFound", () => Effect.undefined), |
| 267 | ); |
| 268 | |
| 269 | /** |
| 270 | * Find a user group by exact name (re-checked client-side). User group |
| 271 | * names are unique on Cloudflare's side; the sort is belt-and-braces |
| 272 | * determinism. |
| 273 | */ |
| 274 | const findByName = (accountId: string, name: string) => |
| 275 | iam.listUserGroups.items({ accountId, name }).pipe( |
| 276 | Stream.runCollect, |
| 277 | Effect.map((chunk) => |
| 278 | Array.from(chunk) |
| 279 | .filter((g) => g.name === name) |
| 280 | .sort((a, b) => a.createdOn.localeCompare(b.createdOn)) |
| 281 | .at(0), |
| 282 | ), |
| 283 | ); |
| 284 | |
| 285 | const createGroupName = (id: string, name: string | undefined) => |
| 286 | Effect.gen(function* () { |
| 287 | return name ?? (yield* createPhysicalName({ id, lowercase: true })); |
| 288 | }); |
| 289 | |
| 290 | /** Resolve `Input<string>` policy ids to concrete strings (post-Plan). */ |
| 291 | const resolvePolicies = (policies: UserGroupPolicyInput[]) => |
| 292 | policies.map((p) => ({ |
| 293 | access: p.access, |
| 294 | permissionGroups: p.permissionGroups.map((id) => ({ id: id as string })), |
| 295 | resourceGroups: p.resourceGroups.map((id) => ({ id: id as string })), |
| 296 | })); |
| 297 | |
| 298 | const parsePolicies = (policies: ObservedUserGroup["policies"]): UserGroupPolicy[] => |
| 299 | (policies ?? []).map((p) => ({ |
| 300 | id: p.id ?? undefined, |
| 301 | access: p.access === "deny" ? "deny" : "allow", |
| 302 | permissionGroups: (p.permissionGroups ?? []).map((g) => g.id), |
| 303 | resourceGroups: (p.resourceGroups ?? []).map((g) => g.id), |
| 304 | })); |
| 305 | |
| 306 | /** Canonical string form of a policy set for order-insensitive diffing. */ |
| 307 | const policyKey = (p: { |
| 308 | access: string; |
| 309 | permissionGroups: { id: string }[] | string[]; |
| 310 | resourceGroups: { id: string }[] | string[]; |
| 311 | }) => { |
| 312 | const ids = (xs: { id: string }[] | string[]) => |
| 313 | xs |
| 314 | .map((x) => (typeof x === "string" ? x : x.id)) |
| 315 | .sort() |
| 316 | .join(","); |
| 317 | return `${p.access}|${ids(p.permissionGroups)}|${ids(p.resourceGroups)}`; |
| 318 | }; |
| 319 | |
| 320 | const samePolicies = (observed: UserGroupPolicy[], desired: ReturnType<typeof resolvePolicies>) => |
| 321 | observed.length === desired.length && |
| 322 | observed.map(policyKey).sort().join(";") === desired.map(policyKey).sort().join(";"); |
| 323 | |
| 324 | const toAttributes = ( |
| 325 | group: iam.GetUserGroupResponse | iam.CreateUserGroupResponse | iam.UpdateUserGroupResponse, |
| 326 | accountId: string, |
| 327 | ): UserGroupAttributes => ({ |
| 328 | userGroupId: group.id, |
| 329 | accountId, |
| 330 | name: group.name, |
| 331 | policies: parsePolicies(group.policies), |
| 332 | createdOn: group.createdOn, |
| 333 | modifiedOn: group.modifiedOn, |
| 334 | }); |