@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, 06:00 UTC

main
ts 251 lines 8.54 KB
Raw
1 import * as GCP from "@alchemy.run/gcp";
2 import { describe, expect } from "@alchemy.run/test";
3 import * as Test from "@alchemy.run/test/Alchemy";
4 import * as Core from "@alchemy.run/test/Core";
5 import * as resourcemanager from "@distilled.cloud/gcp/cloudresourcemanager_v3";
6 import * as secretmanager from "@distilled.cloud/gcp/secretmanager_v1";
7 import * as sqladmin from "@distilled.cloud/gcp/sqladmin_v1";
8 import * as Effect from "effect/Effect";
9 import { expectProbe } from "../bindingHost.ts";
10 import SqlBindingsHost, { Db, USER_PASSWORD } from "./fixtures/bindings-host.ts";
11
12 const testOptions = { providers: GCP.providers() };
13 const { test, beforeAll, afterAll } = Test.make(testOptions);
14 const sharedStack = Core.scratchStack(testOptions, "SqlBindings");
15
16 // Cloud SQL instances take well over 5 minutes to provision.
17 const runLifecycle = !!process.env.GCP_TEST_SLOW && !process.env.FAST;
18
19 let baseUrl: string;
20 let hostAccount: string;
21 let project: string;
22 let region: string;
23 let instanceName: string;
24 let databaseName: string;
25 let userName: string;
26 let secretName: string;
27
28 /** IAM Condition the bindings scope their project grants with. */
29 const instanceCondition = () => {
30 const name = `projects/${project}/instances/${instanceName}`;
31 return `resource.name == "${name}" || resource.name.startsWith("${name}/")`;
32 };
33
34 /**
35 * Project-level roles held by the host's service account, with their IAM
36 * Condition. Cloud SQL has no instance-level IAM policy.
37 */
38 const projectRoles = () =>
39 resourcemanager
40 .getIamPolicyProjects({
41 resource: `projects/${project}`,
42 body: { options: { requestedPolicyVersion: 3 } },
43 })
44 .pipe(
45 Effect.map((policy) =>
46 (policy.bindings ?? [])
47 .filter((binding) => (binding.members ?? []).includes(`serviceAccount:${hostAccount}`))
48 .map((binding) => ({
49 role: binding.role,
50 condition: binding.condition?.expression,
51 }))
52 .sort((a, b) => (a.role ?? "").localeCompare(b.role ?? "")),
53 ),
54 );
55
56 const expectRole = (role: string) =>
57 Effect.gen(function* () {
58 expect(yield* projectRoles()).toContainEqual({
59 role,
60 condition: instanceCondition(),
61 });
62 });
63
64 describe.skipIf(!runLifecycle)(
65 "SQL Bindings",
66 {
67 tags: ["provider:gcp", "provider:gcp:sql", "provider:gcp:run", "live"],
68 },
69 () => {
70 beforeAll(
71 Effect.gen(function* () {
72 yield* sharedStack.destroy();
73 const out = yield* sharedStack.deploy(
74 Effect.gen(function* () {
75 const host = yield* SqlBindingsHost;
76 const { instance, database, user, password } = yield* Db;
77 return {
78 uri: host.uri,
79 serviceAccount: host.serviceAccount,
80 project: host.project,
81 region: instance.region,
82 instance: instance.instanceName,
83 database: database.databaseName,
84 user: user.userName,
85 secret: password.name,
86 };
87 }),
88 );
89 baseUrl = out.uri!;
90 hostAccount = out.serviceAccount!;
91 project = out.project;
92 region = out.region;
93 instanceName = out.instance;
94 databaseName = out.database;
95 userName = out.user;
96 secretName = out.secret;
97
98 // The user's password, where Connect and the Data API read it.
99 const payload = yield* Effect.sync(() =>
100 Buffer.from(USER_PASSWORD, "utf8").toString("base64"),
101 );
102 yield* Core.withProviders(
103 secretmanager.addVersionProjectsLocationsSecrets({
104 parent: secretName,
105 body: { payload: { data: payload } },
106 }),
107 testOptions,
108 "SqlBindings",
109 );
110 }),
111 { timeout: 1_800_000 },
112 );
113
114 afterAll(sharedStack.destroy(), { timeout: 1_200_000 });
115
116 describe("Connect", () => {
117 test.provider(
118 "queries the database over the Cloud SQL socket as the host",
119 (_stack) =>
120 Effect.gen(function* () {
121 const out = yield* expectProbe<{
122 connectionName: string;
123 socketPath: string;
124 username: string;
125 database: string;
126 passwordMatches: boolean;
127 rows: { user: string; database: string }[];
128 }>(baseUrl, "connect");
129 expect(out.connectionName).toEqual(`${project}:${region}:${instanceName}`);
130 expect(out.socketPath).toEqual(`/cloudsql/${project}:${region}:${instanceName}`);
131 expect(out.username).toEqual(userName);
132 expect(out.database).toEqual(databaseName);
133 expect(out.passwordMatches).toEqual(true);
134 expect(out.rows).toEqual([{ user: userName, database: databaseName }]);
135
136 yield* expectRole("roles/cloudsql.client");
137 const secretPolicy = yield* secretmanager.getIamPolicyProjectsLocationsSecrets({
138 resource: secretName,
139 });
140 expect(
141 (secretPolicy.bindings ?? [])
142 .filter((binding) =>
143 (binding.members ?? []).includes(`serviceAccount:${hostAccount}`),
144 )
145 .map((binding) => binding.role),
146 ).toEqual(["roles/secretmanager.secretAccessor"]);
147 }),
148 {
149 tags: ["provider:gcp", "provider:gcp:sql", "live"],
150 timeout: 900_000,
151 },
152 );
153 });
154
155 describe("ExecuteSql", () => {
156 test.provider(
157 "runs a statement through the Data API as the host",
158 (_stack) =>
159 Effect.gen(function* () {
160 const out = yield* expectProbe<{
161 status: { code?: number } | undefined;
162 columns: string[];
163 values: string[];
164 }>(baseUrl, "executeSql");
165 expect(out.status?.code ?? 0).toEqual(0);
166 expect(out.columns).toEqual(["who", "answer"]);
167 expect(out.values).toEqual([userName, "42"]);
168 yield* expectRole("roles/cloudsql.instanceUser");
169 }),
170 {
171 tags: ["provider:gcp", "provider:gcp:sql", "live"],
172 timeout: 900_000,
173 },
174 );
175 });
176
177 describe("GetInstance", () => {
178 test.provider(
179 "reads the bound instance as the host",
180 (_stack) =>
181 Effect.gen(function* () {
182 const out = yield* expectProbe<{
183 name: string;
184 state: string;
185 connectionName: string;
186 }>(baseUrl, "getInstance");
187 const live = yield* sqladmin.getInstances({
188 project,
189 instance: instanceName,
190 });
191 expect(out.name).toEqual(instanceName);
192 expect(out.state).toEqual("RUNNABLE");
193 expect(out.connectionName).toEqual(live.connectionName);
194 yield* expectRole("roles/cloudsql.viewer");
195 }),
196 {
197 tags: ["provider:gcp", "provider:gcp:sql", "live"],
198 timeout: 900_000,
199 },
200 );
201 });
202
203 describe("GetUser", () => {
204 test.provider(
205 "reads the bound user as the host",
206 (_stack) =>
207 Effect.gen(function* () {
208 const out = yield* expectProbe<{ name: string; instance: string }>(baseUrl, "getUser");
209 expect(out.name).toEqual(userName);
210 expect(out.instance).toEqual(instanceName);
211 // users.get does not match an instance-scoped IAM Condition.
212 expect(yield* projectRoles()).toContainEqual({
213 role: "roles/cloudsql.viewer",
214 condition: undefined,
215 });
216 }),
217 {
218 tags: ["provider:gcp", "provider:gcp:sql", "live"],
219 timeout: 900_000,
220 },
221 );
222 });
223
224 describe("grants", () => {
225 test.provider(
226 "the host holds only the bindings' roles, instance-scoped except GetUser's",
227 (_stack) =>
228 Effect.gen(function* () {
229 // Wait for the probes above so every grant is in place.
230 yield* expectProbe(baseUrl, "getInstance");
231 const roles = yield* projectRoles();
232 expect(roles).toHaveLength(4);
233 expect(roles).toEqual(
234 expect.arrayContaining([
235 ...[
236 "roles/cloudsql.client",
237 "roles/cloudsql.instanceUser",
238 "roles/cloudsql.viewer",
239 ].map((role) => ({ role, condition: instanceCondition() })),
240 { role: "roles/cloudsql.viewer", condition: undefined },
241 ]),
242 );
243 }),
244 {
245 tags: ["provider:gcp", "provider:gcp:sql", "live"],
246 timeout: 900_000,
247 },
248 );
249 });
250 },
251 );