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

main
ts 278 lines 9.06 KB
Raw
1 import * as binaryauthorization from "@distilled.cloud/gcp/binaryauthorization_v1";
2 import { unownedUnlessPrevious } from "alchemy/AdoptPolicy";
3 import { isResolved } from "alchemy/Diff";
4 import * as Provider from "alchemy/Provider";
5 import { Resource } from "alchemy/Resource";
6 import * as Data from "effect/Data";
7 import * as Effect from "effect/Effect";
8 import { GcpEnvironment } from "../Environment.ts";
9 import type { Providers } from "../Providers.ts";
10 import {
11 attestorName,
12 createOwnership,
13 encodeDescription,
14 expandNoteReference,
15 hasOwnershipMarker,
16 ignoreGone,
17 lastSegment,
18 listAttestors,
19 missingGet,
20 ownedBy,
21 parseAttestorName,
22 parseDescription,
23 publicKeysOf,
24 replaceOnIdentity,
25 ResourceNotResolved,
26 retryTransient,
27 samePublicKeys,
28 sameText,
29 toPhysicalId,
30 } from "./internal.ts";
31
32 export type AttestorPublicKey = binaryauthorization.AttestorPublicKey;
33
34 export type AttestorProps = {
35 /**
36 * Attestor id (the `{attestor}` segment of
37 * `projects/{project}/attestors/{attestor}`). If omitted, a unique RFC1035
38 * id is generated. Immutable — changing it replaces the attestor.
39 */
40 attestorId?: string;
41 /**
42 * Grafeas Attestation Authority note this attestor reads, as
43 * `projects/{project}/notes/{note}` or a note id in the same project.
44 * Immutable — changing it replaces the attestor.
45 */
46 noteReference: string;
47 /**
48 * Human-readable comment. Binary Authorization attestors have no labels
49 * field, so Alchemy stamps ownership into this field for `list` / nuke
50 * and strips the marker from attributes.
51 */
52 description?: string;
53 /**
54 * Public keys that verify attestations signed by this attestor. Empty
55 * means the attestor never reports a valid attestation.
56 */
57 publicKeys?: AttestorPublicKey[];
58 };
59
60 export type Attestor = Resource<
61 "GCP.BinaryAuthorization.Attestor",
62 AttestorProps,
63 {
64 /** Full resource name `projects/{project}/attestors/{attestor}`. */
65 name: string;
66 /** Attestor id (last path segment). */
67 attestorId: string;
68 /** Project id. */
69 project: string;
70 /** User description with the Alchemy ownership prefix stripped. */
71 description: string | undefined;
72 /** Grafeas note this attestor reads. */
73 noteReference: string;
74 /** Public keys that verify attestations. */
75 publicKeys: AttestorPublicKey[];
76 /**
77 * Service account Binary Authorization uses when querying Container
78 * Analysis for this attestor.
79 */
80 delegationServiceAccountEmail: string | undefined;
81 /** Server-assigned checksum for optimistic concurrency. */
82 etag: string | undefined;
83 /** RFC3339 last-update timestamp. */
84 updateTime: string | undefined;
85 },
86 never,
87 Providers
88 >;
89
90 /**
91 * A Binary Authorization attestor that verifies container-image
92 * attestations against a Grafeas Attestation Authority note.
93 *
94 * Attestors have no labels field, so Alchemy stamps ownership into
95 * `description` for `list` / nuke. `attestorId` and `noteReference` are
96 * identity — changing either replaces the attestor. Description and
97 * public keys update in place.
98 *
99 * ### Creating an Attestor
100 * **Example:** Generated name
101 * ```typescript
102 * const note = yield* GCP.ContainerAnalysis.Note("Authority", {
103 * attestation: { hint: { humanReadableName: "QA" } },
104 * });
105 * const attestor = yield* GCP.BinaryAuthorization.Attestor("Qa", {
106 * noteReference: note.name,
107 * });
108 * ```
109 *
110 * **Example:** Explicit id, description, and PKIX key
111 * ```typescript
112 * const attestor = yield* GCP.BinaryAuthorization.Attestor("Qa", {
113 * attestorId: "qa-attestor",
114 * noteReference: note.name,
115 * description: "signs production images",
116 * publicKeys: [
117 * {
118 * comment: "ci",
119 * pkixPublicKey: {
120 * publicKeyPem: pem,
121 * signatureAlgorithm: "EC_SIGN_P256_SHA256",
122 * },
123 * },
124 * ],
125 * });
126 * ```
127 *
128 * ### Updating an Attestor
129 * **Example:** Change the description
130 * ```typescript
131 * const attestor = yield* GCP.BinaryAuthorization.Attestor("Qa", {
132 * description: "signs staging and production images",
133 * });
134 * ```
135 *
136 * @resource
137 * @category BinaryAuthorization
138 */
139 export const Attestor = Resource<Attestor>("GCP.BinaryAuthorization.Attestor");
140
141 export class NoteReferenceRequired extends Data.TaggedError(
142 "GCP.BinaryAuthorization.NoteReferenceRequired",
143 )<{
144 attestorId: string;
145 }> {}
146
147 const getByName = missingGet(binaryauthorization.getProjectsAttestors);
148
149 const toAttrs = (
150 attestor: binaryauthorization.Attestor,
151 project: string,
152 ): Attestor["Attributes"] => {
153 const name = attestor.name ?? "";
154 const parsed = parseAttestorName(name);
155 const { description } = parseDescription(attestor.description);
156 const note = attestor.userOwnedGrafeasNote;
157 return {
158 name,
159 attestorId: parsed.attestorId,
160 project: parsed.project || project,
161 description,
162 noteReference: note?.noteReference ?? "",
163 publicKeys: publicKeysOf(note?.publicKeys),
164 delegationServiceAccountEmail: note?.delegationServiceAccountEmail,
165 etag: attestor.etag,
166 updateTime: attestor.updateTime,
167 };
168 };
169
170 const toBody = (
171 news: AttestorProps,
172 description: string,
173 noteReference: string,
174 ): binaryauthorization.Attestor => ({
175 description,
176 userOwnedGrafeasNote: {
177 noteReference,
178 publicKeys: news.publicKeys,
179 },
180 });
181
182 export const AttestorProvider = () =>
183 Provider.succeed(Attestor, {
184 stables: ["name", "attestorId", "project", "noteReference"],
185
186 diff: Effect.fn(function* ({ news, olds, output }) {
187 if (!isResolved(news)) return undefined;
188 const previousNote = lastSegment(olds?.noteReference ?? output?.noteReference ?? "");
189 const nextNote = lastSegment(news.noteReference);
190 return replaceOnIdentity({
191 previousId: olds?.attestorId ?? output?.attestorId,
192 nextId: news.attestorId,
193 extra: previousNote.length > 0 && nextNote.length > 0 && previousNote !== nextNote,
194 deleteFirst: true,
195 });
196 }),
197
198 read: Effect.fn(function* ({ id, olds, output, previous }) {
199 const env = yield* GcpEnvironment.current;
200 const attestorId = yield* toPhysicalId(id, olds?.attestorId, output?.attestorId, "attestor");
201 const name = output?.name ?? attestorName(env.project, attestorId);
202 const existing = yield* getByName(name);
203 if (existing === undefined) return undefined;
204 const attrs = toAttrs(existing, env.project);
205 const { labels } = parseDescription(existing.description);
206 return (yield* ownedBy(id, labels)) ? attrs : unownedUnlessPrevious(attrs, previous, "name");
207 }),
208
209 list: () =>
210 Effect.gen(function* () {
211 const env = yield* GcpEnvironment.current;
212 const items = yield* listAttestors(env.project);
213 return items
214 .filter((item) => hasOwnershipMarker(item.description))
215 .map((item) => toAttrs(item, env.project));
216 }),
217
218 reconcile: Effect.fn(function* ({ id, news, output }) {
219 const env = yield* GcpEnvironment.current;
220 const attestorId = yield* toPhysicalId(id, news.attestorId, output?.attestorId, "attestor");
221 const name = attestorName(env.project, attestorId);
222 if (news.noteReference.trim().length === 0) {
223 return yield* new NoteReferenceRequired({ attestorId });
224 }
225 const desiredNote = expandNoteReference(news.noteReference, env.project);
226 const ownership = yield* createOwnership(id);
227 const desiredDescription = encodeDescription(ownership, news.description);
228
229 let current = yield* getByName(output?.name ?? name);
230
231 if (current === undefined) {
232 const created = yield* retryTransient(
233 binaryauthorization.createProjectsAttestors({
234 parent: `projects/${env.project}`,
235 attestorId,
236 body: toBody(news, desiredDescription, desiredNote),
237 }),
238 ).pipe(Effect.catchTag("Conflict", () => getByName(name)));
239 current = created ?? undefined;
240 }
241
242 if (current === undefined) {
243 return yield* new ResourceNotResolved({ resourceName: name });
244 }
245
246 const observedNote = current.userOwnedGrafeasNote?.noteReference ?? "";
247 const descriptionChanged = !sameText(current.description, desiredDescription);
248 const keysChanged = !samePublicKeys(
249 current.userOwnedGrafeasNote?.publicKeys,
250 news.publicKeys,
251 );
252
253 if (descriptionChanged || keysChanged) {
254 current = yield* retryTransient(
255 binaryauthorization.updateProjectsAttestors({
256 name: current.name ?? name,
257 body: {
258 name: current.name ?? name,
259 description: desiredDescription,
260 etag: current.etag,
261 userOwnedGrafeasNote: {
262 noteReference: observedNote || desiredNote,
263 publicKeys: news.publicKeys,
264 delegationServiceAccountEmail:
265 current.userOwnedGrafeasNote?.delegationServiceAccountEmail,
266 },
267 },
268 }),
269 );
270 }
271
272 return toAttrs(current, env.project);
273 }),
274
275 delete: Effect.fn(function* ({ output }) {
276 yield* ignoreGone(binaryauthorization.deleteProjectsAttestors({ name: output.name }));
277 }),
278 });