@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 203 lines 7.89 KB
Raw
1 import * as Grafana from "@alchemy.run/aws/Grafana";
2 import * as Lambda from "@alchemy.run/aws/Lambda";
3 import * as Duration from "effect/Duration";
4 import * as Effect from "effect/Effect";
5 import { HttpServerRequest } from "effect/http/HttpServerRequest";
6 import * as HttpServerResponse from "effect/http/HttpServerResponse";
7 import * as Layer from "effect/Layer";
8 import * as Redacted from "effect/Redacted";
9 import path from "pathe";
10
11 const main = path.resolve(import.meta.dirname, "workspace-handler.ts");
12
13 export class GrafanaWorkspaceTestFunction extends Lambda.Function<Lambda.Function>()(
14 "GrafanaWorkspaceTestFunction",
15 ) {}
16
17 /** Unwrap a possibly-redacted secret returned by the distilled client. */
18 const unwrap = (value: string | Redacted.Redacted<string>): string =>
19 typeof value === "string" ? value : Redacted.value(value);
20
21 const errorTagged = <A, E extends { _tag: string }, R>(
22 effect: Effect.Effect<A, E, R>,
23 ): Effect.Effect<A | { errorTag: string }, never, R> =>
24 effect.pipe(
25 Effect.map((a): A | { errorTag: string } => a),
26 Effect.catch((e) => Effect.succeed({ errorTag: e._tag })),
27 );
28
29 /**
30 * GATED fixture (AWS_TEST_GRAFANA=1): creates a SAML-authenticated Grafana
31 * workspace (no IAM Identity Center requirement) and binds every
32 * workspace-scoped capability. License and mutation-heavy capabilities
33 * (AssociateLicense enables billed Enterprise; UpdateWorkspaceAuthentication
34 * and UpdateWorkspaceConfiguration mutate long-lived workspace state;
35 * UpdatePermissions requires SSO users) are bound — proving init + IAM
36 * deploy — but not exercised against live state.
37 */
38 export default GrafanaWorkspaceTestFunction.make(
39 {
40 main,
41 functionUrl: true,
42 timeout: Duration.seconds(60),
43 },
44 Effect.gen(function* () {
45 const workspace = yield* Grafana.Workspace("BindingsWorkspace", {
46 description: "grafana bindings fixture",
47 accountAccessType: "CURRENT_ACCOUNT",
48 authenticationProviders: ["SAML"],
49 permissionType: "SERVICE_MANAGED",
50 dataSources: ["CLOUDWATCH"],
51 tags: { fixture: "grafana-bindings" },
52 });
53
54 const describeAuth = yield* Grafana.DescribeWorkspaceAuthentication(workspace);
55 const updateAuth = yield* Grafana.UpdateWorkspaceAuthentication(workspace);
56 const describeConfig = yield* Grafana.DescribeWorkspaceConfiguration(workspace);
57 const updateConfig = yield* Grafana.UpdateWorkspaceConfiguration(workspace);
58 const associateLicense = yield* Grafana.AssociateLicense(workspace);
59 const disassociateLicense = yield* Grafana.DisassociateLicense(workspace);
60 const listPermissions = yield* Grafana.ListPermissions(workspace);
61 const updatePermissions = yield* Grafana.UpdatePermissions(workspace);
62 const createServiceAccount = yield* Grafana.CreateWorkspaceServiceAccount(workspace);
63 const deleteServiceAccount = yield* Grafana.DeleteWorkspaceServiceAccount(workspace);
64 const listServiceAccounts = yield* Grafana.ListWorkspaceServiceAccounts(workspace);
65 const createToken = yield* Grafana.CreateWorkspaceServiceAccountToken(workspace);
66 const deleteToken = yield* Grafana.DeleteWorkspaceServiceAccountToken(workspace);
67 const listTokens = yield* Grafana.ListWorkspaceServiceAccountTokens(workspace);
68 const listVersions = yield* Grafana.ListVersions();
69
70 const bound = {
71 describeAuth,
72 updateAuth,
73 describeConfig,
74 updateConfig,
75 associateLicense,
76 disassociateLicense,
77 listPermissions,
78 updatePermissions,
79 createServiceAccount,
80 deleteServiceAccount,
81 listServiceAccounts,
82 createToken,
83 deleteToken,
84 listTokens,
85 listVersions,
86 };
87
88 return {
89 fetch: Effect.gen(function* () {
90 const request = yield* HttpServerRequest;
91 const url = new URL(request.originalUrl);
92 const pathname = url.pathname;
93
94 if (request.method === "GET" && pathname === "/bindings") {
95 return yield* HttpServerResponse.json({
96 bound: Object.keys(bound),
97 });
98 }
99
100 // Injected workspace id: the auth description round-trips.
101 if (request.method === "GET" && pathname === "/auth") {
102 const { authentication } = yield* describeAuth();
103 return yield* HttpServerResponse.json({
104 providers: authentication.providers,
105 samlStatus: authentication.saml?.status,
106 });
107 }
108
109 if (request.method === "GET" && pathname === "/config") {
110 const { configuration, grafanaVersion } = yield* describeConfig();
111 return yield* HttpServerResponse.json({
112 hasConfiguration: configuration.length > 0,
113 grafanaVersion,
114 });
115 }
116
117 // A SAML-only workspace may reject SSO-permission listing with a
118 // typed error — either outcome proves the binding + IAM wiring.
119 if (request.method === "GET" && pathname === "/permissions") {
120 const result = yield* errorTagged(
121 listPermissions().pipe(Effect.map((r) => ({ count: r.permissions.length }))),
122 );
123 return yield* HttpServerResponse.json(result);
124 }
125
126 if (request.method === "GET" && pathname === "/service-accounts") {
127 const { serviceAccounts } = yield* listServiceAccounts();
128 return yield* HttpServerResponse.json({
129 count: serviceAccounts.length,
130 });
131 }
132
133 // Upgradable versions for the bound workspace (account-level cap).
134 if (request.method === "GET" && pathname === "/versions") {
135 const { grafanaVersions } = yield* listVersions();
136 return yield* HttpServerResponse.json({
137 count: (grafanaVersions ?? []).length,
138 });
139 }
140
141 // Full service-account + token lifecycle: create → mint (Duration
142 // timeToLive → wire secondsToLive; Redacted key) → list → revoke →
143 // delete. Exercises five bindings in one deterministic round-trip.
144 if (request.method === "POST" && pathname === "/service-account-roundtrip") {
145 const account = yield* createServiceAccount({
146 name: "bindings-roundtrip",
147 grafanaRole: "EDITOR",
148 });
149
150 const minted = yield* createToken({
151 name: "bindings-roundtrip-token",
152 serviceAccountId: account.id,
153 timeToLive: "5 minutes",
154 });
155 const key = unwrap(minted.serviceAccountToken.key);
156
157 const { serviceAccountTokens } = yield* listTokens({
158 serviceAccountId: account.id,
159 });
160
161 yield* deleteToken({
162 serviceAccountId: account.id,
163 tokenId: minted.serviceAccountToken.id,
164 });
165 yield* deleteServiceAccount({ serviceAccountId: account.id });
166
167 return yield* HttpServerResponse.json({
168 serviceAccountId: account.id,
169 grafanaRole: account.grafanaRole,
170 keyPrefix: key.slice(0, 5),
171 keyLength: key.length,
172 tokenCount: serviceAccountTokens.length,
173 });
174 }
175
176 return yield* HttpServerResponse.json(
177 { error: "Not found", method: request.method, pathname },
178 { status: 404 },
179 );
180 }).pipe(Effect.orDie),
181 };
182 }).pipe(
183 Effect.provide(
184 Layer.mergeAll(
185 Grafana.AssociateLicenseHttp,
186 Grafana.CreateWorkspaceServiceAccountHttp,
187 Grafana.CreateWorkspaceServiceAccountTokenHttp,
188 Grafana.DeleteWorkspaceServiceAccountHttp,
189 Grafana.DeleteWorkspaceServiceAccountTokenHttp,
190 Grafana.DescribeWorkspaceAuthenticationHttp,
191 Grafana.DescribeWorkspaceConfigurationHttp,
192 Grafana.DisassociateLicenseHttp,
193 Grafana.ListPermissionsHttp,
194 Grafana.ListVersionsHttp,
195 Grafana.ListWorkspaceServiceAccountsHttp,
196 Grafana.ListWorkspaceServiceAccountTokensHttp,
197 Grafana.UpdatePermissionsHttp,
198 Grafana.UpdateWorkspaceAuthenticationHttp,
199 Grafana.UpdateWorkspaceConfigurationHttp,
200 ),
201 ),
202 ),
203 );