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
| 1 | /** |
| 2 | * Internal kubeconfig resolution for the built-in cluster adapters: parse a |
| 3 | * kubeconfig file, resolve a context to (cluster, user), and turn its auth |
| 4 | * stanza — static token, client certificate, or `exec` credential plugin — |
| 5 | * into a {@link ClusterTransport}. This is the "anything kubectl can reach" |
| 6 | * path: AKS/GKE/EKS CLI-managed contexts work through their exec plugins |
| 7 | * (`kubelogin`, `gke-gcloud-auth-plugin`, `aws eks get-token`). |
| 8 | */ |
| 9 | import * as Config from "effect/Config"; |
| 10 | import * as Data from "effect/Data"; |
| 11 | import * as Effect from "effect/Effect"; |
| 12 | import * as FileSystem from "effect/FileSystem"; |
| 13 | import * as Path from "effect/Path"; |
| 14 | import * as ChildProcess from "effect/process/ChildProcess"; |
| 15 | import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner"; |
| 16 | import * as Stream from "effect/Stream"; |
| 17 | import * as YAML from "yaml"; |
| 18 | |
| 19 | /** A kubeconfig file could not be read, parsed, or resolved. */ |
| 20 | export class KubeConfigError extends Data.TaggedError("Kubernetes.KubeConfigError")<{ |
| 21 | readonly message: string; |
| 22 | readonly cause?: unknown; |
| 23 | }> {} |
| 24 | |
| 25 | /** An exec credential plugin invocation failed or answered malformed. */ |
| 26 | export class ExecCredentialError extends Data.TaggedError("Kubernetes.ExecCredentialError")<{ |
| 27 | readonly message: string; |
| 28 | readonly cause?: unknown; |
| 29 | }> {} |
| 30 | |
| 31 | interface KubeConfigFile { |
| 32 | "current-context"?: string; |
| 33 | clusters?: { |
| 34 | name?: string; |
| 35 | cluster?: { |
| 36 | server?: string; |
| 37 | "certificate-authority"?: string; |
| 38 | "certificate-authority-data"?: string; |
| 39 | "insecure-skip-tls-verify"?: boolean; |
| 40 | }; |
| 41 | }[]; |
| 42 | users?: { |
| 43 | name?: string; |
| 44 | user?: KubeConfigUser; |
| 45 | }[]; |
| 46 | contexts?: { |
| 47 | name?: string; |
| 48 | context?: { cluster?: string; user?: string }; |
| 49 | }[]; |
| 50 | } |
| 51 | |
| 52 | interface KubeConfigUser { |
| 53 | token?: string; |
| 54 | tokenFile?: string; |
| 55 | "client-certificate"?: string; |
| 56 | "client-certificate-data"?: string; |
| 57 | "client-key"?: string; |
| 58 | "client-key-data"?: string; |
| 59 | exec?: { |
| 60 | command?: string; |
| 61 | args?: string[]; |
| 62 | env?: { name?: string; value?: string }[]; |
| 63 | apiVersion?: string; |
| 64 | }; |
| 65 | } |
| 66 | |
| 67 | /** The resolved connection material for one kubeconfig context. */ |
| 68 | export interface ResolvedKubeContext { |
| 69 | endpoint: string; |
| 70 | certificateAuthorityData?: string; |
| 71 | insecureSkipTlsVerify?: boolean; |
| 72 | user: KubeConfigUser; |
| 73 | } |
| 74 | |
| 75 | const decodeBase64 = (value: string) => Buffer.from(value, "base64").toString("utf8"); |
| 76 | |
| 77 | const expandHome = Effect.fn(function* (input: string) { |
| 78 | if (!input.startsWith("~")) return input; |
| 79 | const home = yield* Effect.sync(() => process.env.HOME ?? process.env.USERPROFILE); |
| 80 | if (!home) { |
| 81 | return yield* new KubeConfigError({ |
| 82 | message: `Cannot expand '${input}': no HOME environment variable`, |
| 83 | }); |
| 84 | } |
| 85 | const path = yield* Path.Path; |
| 86 | return path.join(home, input.slice(1)); |
| 87 | }); |
| 88 | |
| 89 | /** Resolve the kubeconfig file path: explicit → `$KUBECONFIG` → default. */ |
| 90 | export const resolveKubeConfigPath = Effect.fn(function* (explicit: string | undefined) { |
| 91 | if (explicit) return yield* expandHome(explicit); |
| 92 | const fromEnv = yield* Config.String("KUBECONFIG").pipe(Effect.orElseSucceed(() => undefined)); |
| 93 | // $KUBECONFIG may be a path list; use the first entry like kubectl's |
| 94 | // effective-config merge order. |
| 95 | const candidate = fromEnv?.split(":")[0]; |
| 96 | if (candidate) return yield* expandHome(candidate); |
| 97 | return yield* expandHome("~/.kube/config"); |
| 98 | }); |
| 99 | |
| 100 | /** Load a kubeconfig file and resolve one context to its cluster + user. */ |
| 101 | export const resolveKubeContext = Effect.fn(function* (options: { |
| 102 | path?: string; |
| 103 | context?: string; |
| 104 | }) { |
| 105 | const fs = yield* FileSystem.FileSystem; |
| 106 | const configPath = yield* resolveKubeConfigPath(options.path); |
| 107 | |
| 108 | const raw = yield* fs.readFileString(configPath).pipe( |
| 109 | Effect.mapError( |
| 110 | (cause) => |
| 111 | new KubeConfigError({ |
| 112 | message: `Failed to read kubeconfig at '${configPath}'`, |
| 113 | cause, |
| 114 | }), |
| 115 | ), |
| 116 | ); |
| 117 | |
| 118 | const parsed = yield* Effect.try({ |
| 119 | try: () => YAML.parse(raw) as KubeConfigFile, |
| 120 | catch: (cause) => |
| 121 | new KubeConfigError({ |
| 122 | message: `Failed to parse kubeconfig at '${configPath}'`, |
| 123 | cause, |
| 124 | }), |
| 125 | }); |
| 126 | |
| 127 | const contextName = options.context ?? parsed["current-context"]; |
| 128 | if (!contextName) { |
| 129 | return yield* new KubeConfigError({ |
| 130 | message: `Kubeconfig '${configPath}' has no current-context — pass an explicit context`, |
| 131 | }); |
| 132 | } |
| 133 | |
| 134 | const context = parsed.contexts?.find((entry) => entry.name === contextName)?.context; |
| 135 | if (!context?.cluster) { |
| 136 | return yield* new KubeConfigError({ |
| 137 | message: `Context '${contextName}' not found in kubeconfig '${configPath}'`, |
| 138 | }); |
| 139 | } |
| 140 | |
| 141 | const cluster = parsed.clusters?.find((entry) => entry.name === context.cluster)?.cluster; |
| 142 | if (!cluster?.server) { |
| 143 | return yield* new KubeConfigError({ |
| 144 | message: `Cluster '${context.cluster}' (context '${contextName}') has no server in kubeconfig '${configPath}'`, |
| 145 | }); |
| 146 | } |
| 147 | |
| 148 | const user = parsed.users?.find((entry) => entry.name === context.user)?.user ?? {}; |
| 149 | |
| 150 | let certificateAuthorityData = cluster["certificate-authority-data"]; |
| 151 | if (!certificateAuthorityData && cluster["certificate-authority"]) { |
| 152 | const caPath = yield* expandHome(cluster["certificate-authority"]); |
| 153 | const pem = yield* fs.readFileString(caPath).pipe( |
| 154 | Effect.mapError( |
| 155 | (cause) => |
| 156 | new KubeConfigError({ |
| 157 | message: `Failed to read certificate authority file '${caPath}'`, |
| 158 | cause, |
| 159 | }), |
| 160 | ), |
| 161 | ); |
| 162 | certificateAuthorityData = Buffer.from(pem, "utf8").toString("base64"); |
| 163 | } |
| 164 | |
| 165 | return { |
| 166 | endpoint: cluster.server, |
| 167 | certificateAuthorityData, |
| 168 | insecureSkipTlsVerify: cluster["insecure-skip-tls-verify"], |
| 169 | user, |
| 170 | } satisfies ResolvedKubeContext; |
| 171 | }); |
| 172 | |
| 173 | interface ExecCredentialStatus { |
| 174 | token?: string; |
| 175 | clientCertificateData?: string; |
| 176 | clientKeyData?: string; |
| 177 | expirationTimestamp?: string; |
| 178 | } |
| 179 | |
| 180 | /** Credentials minted by a user's auth stanza for one request. */ |
| 181 | export interface MintedCredentials { |
| 182 | token?: string; |
| 183 | clientCert?: { certificate: string; key: string }; |
| 184 | } |
| 185 | |
| 186 | // Exec plugin invocations are cached per (command, args) until their |
| 187 | // expirationTimestamp (or briefly, when the plugin doesn't declare one). |
| 188 | // Plain cached values, no finalizers — module scope is safe. |
| 189 | const execCache = new Map<string, { credentials: MintedCredentials; expiresAt: number }>(); |
| 190 | |
| 191 | /** |
| 192 | * Run a kubeconfig-style exec credential plugin and parse its |
| 193 | * ExecCredential response. |
| 194 | */ |
| 195 | export const runExecCredential = Effect.fn(function* (options: { |
| 196 | command: string; |
| 197 | args?: string[] | undefined; |
| 198 | env?: Record<string, string> | undefined; |
| 199 | }) { |
| 200 | const cacheKey = JSON.stringify([options.command, options.args ?? [], options.env ?? {}]); |
| 201 | const cached = execCache.get(cacheKey); |
| 202 | const now = yield* Effect.sync(() => Date.now()); |
| 203 | if (cached && cached.expiresAt > now) { |
| 204 | return cached.credentials; |
| 205 | } |
| 206 | |
| 207 | const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; |
| 208 | // The child process is scoped to this invocation: spawn, drain stdio, |
| 209 | // and close the scope when the plugin exits. |
| 210 | const result = yield* ChildProcess.make(options.command, options.args ?? [], { |
| 211 | stdin: "ignore", |
| 212 | stdout: "pipe", |
| 213 | stderr: "pipe", |
| 214 | detached: false, |
| 215 | extendEnv: true, |
| 216 | env: options.env, |
| 217 | }).pipe( |
| 218 | (command) => spawner.spawn(command), |
| 219 | Effect.flatMap((child) => |
| 220 | Effect.all( |
| 221 | { |
| 222 | exitCode: child.exitCode, |
| 223 | stdout: child.stdout.pipe(Stream.decodeText, Stream.mkString), |
| 224 | stderr: child.stderr.pipe(Stream.decodeText, Stream.mkString), |
| 225 | }, |
| 226 | { concurrency: "unbounded" }, |
| 227 | ), |
| 228 | ), |
| 229 | Effect.scoped, |
| 230 | Effect.catchCause((cause) => |
| 231 | Effect.fail( |
| 232 | new ExecCredentialError({ |
| 233 | message: `Failed to run exec credential plugin '${options.command}': ${String(cause)}`, |
| 234 | }), |
| 235 | ), |
| 236 | ), |
| 237 | ); |
| 238 | |
| 239 | if (result.exitCode !== 0) { |
| 240 | return yield* new ExecCredentialError({ |
| 241 | message: |
| 242 | `Exec credential plugin '${options.command} ${(options.args ?? []).join(" ")}' ` + |
| 243 | `exited with code ${String(result.exitCode)}: ${result.stderr.trim()}`, |
| 244 | }); |
| 245 | } |
| 246 | |
| 247 | const status = yield* Effect.try({ |
| 248 | try: () => (JSON.parse(result.stdout) as { status?: ExecCredentialStatus }).status, |
| 249 | catch: (cause) => |
| 250 | new ExecCredentialError({ |
| 251 | message: `Exec credential plugin '${options.command}' answered malformed JSON`, |
| 252 | cause, |
| 253 | }), |
| 254 | }); |
| 255 | |
| 256 | if (!status || (!status.token && !(status.clientCertificateData && status.clientKeyData))) { |
| 257 | return yield* new ExecCredentialError({ |
| 258 | message: `Exec credential plugin '${options.command}' returned no token or client certificate`, |
| 259 | }); |
| 260 | } |
| 261 | |
| 262 | const credentials: MintedCredentials = { |
| 263 | token: status.token, |
| 264 | clientCert: |
| 265 | status.clientCertificateData && status.clientKeyData |
| 266 | ? { |
| 267 | certificate: status.clientCertificateData, |
| 268 | key: status.clientKeyData, |
| 269 | } |
| 270 | : undefined, |
| 271 | }; |
| 272 | |
| 273 | const expiresAt = status.expirationTimestamp |
| 274 | ? // Re-mint 30s before the declared expiry. |
| 275 | new Date(status.expirationTimestamp).getTime() - 30_000 |
| 276 | : // No declared expiry: cache briefly so bursts of requests share one |
| 277 | // plugin invocation without holding a stale credential for long. |
| 278 | now + 60_000; |
| 279 | execCache.set(cacheKey, { credentials, expiresAt }); |
| 280 | |
| 281 | return credentials; |
| 282 | }); |
| 283 | |
| 284 | /** Mint request credentials from a kubeconfig user's auth stanza. */ |
| 285 | export const mintUserCredentials = Effect.fn(function* (user: KubeConfigUser) { |
| 286 | if (user.exec?.command) { |
| 287 | return yield* runExecCredential({ |
| 288 | command: user.exec.command, |
| 289 | args: user.exec.args, |
| 290 | env: user.exec.env |
| 291 | ? Object.fromEntries( |
| 292 | user.exec.env |
| 293 | .filter( |
| 294 | (entry): entry is { name: string; value: string } => |
| 295 | typeof entry.name === "string" && typeof entry.value === "string", |
| 296 | ) |
| 297 | .map((entry) => [entry.name, entry.value]), |
| 298 | ) |
| 299 | : undefined, |
| 300 | }); |
| 301 | } |
| 302 | |
| 303 | if (user.token) { |
| 304 | return { token: user.token } satisfies MintedCredentials; |
| 305 | } |
| 306 | |
| 307 | if (user.tokenFile) { |
| 308 | const fs = yield* FileSystem.FileSystem; |
| 309 | const tokenPath = yield* expandHome(user.tokenFile); |
| 310 | const token = yield* fs.readFileString(tokenPath).pipe( |
| 311 | Effect.mapError( |
| 312 | (cause) => |
| 313 | new KubeConfigError({ |
| 314 | message: `Failed to read token file '${tokenPath}'`, |
| 315 | cause, |
| 316 | }), |
| 317 | ), |
| 318 | ); |
| 319 | return { token: token.trim() } satisfies MintedCredentials; |
| 320 | } |
| 321 | |
| 322 | const certData = user["client-certificate-data"]; |
| 323 | const keyData = user["client-key-data"]; |
| 324 | if (certData && keyData) { |
| 325 | return { |
| 326 | clientCert: { |
| 327 | certificate: decodeBase64(certData), |
| 328 | key: decodeBase64(keyData), |
| 329 | }, |
| 330 | } satisfies MintedCredentials; |
| 331 | } |
| 332 | |
| 333 | const certPath = user["client-certificate"]; |
| 334 | const keyPath = user["client-key"]; |
| 335 | if (certPath && keyPath) { |
| 336 | const fs = yield* FileSystem.FileSystem; |
| 337 | const readPem = (file: string) => |
| 338 | expandHome(file).pipe( |
| 339 | Effect.flatMap((resolved) => |
| 340 | fs.readFileString(resolved).pipe( |
| 341 | Effect.mapError( |
| 342 | (cause) => |
| 343 | new KubeConfigError({ |
| 344 | message: `Failed to read credential file '${resolved}'`, |
| 345 | cause, |
| 346 | }), |
| 347 | ), |
| 348 | ), |
| 349 | ), |
| 350 | ); |
| 351 | return { |
| 352 | clientCert: { |
| 353 | certificate: yield* readPem(certPath), |
| 354 | key: yield* readPem(keyPath), |
| 355 | }, |
| 356 | } satisfies MintedCredentials; |
| 357 | } |
| 358 | |
| 359 | return yield* new KubeConfigError({ |
| 360 | message: |
| 361 | "Kubeconfig user has no supported auth stanza (token, tokenFile, " + |
| 362 | "client certificate, or exec credential plugin)", |
| 363 | }); |
| 364 | }); |