diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 8cae75d..b955b26 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -1,12 +1,11 @@ name: Tests on: - push: - branches: - - master + workflow_dispatch: pull_request: branches: - master + types: [opened, reopened, ready_for_review] concurrency: group: tests-${{ github.ref }} diff --git a/apps/docs/compose.yaml b/apps/docs/compose.yaml index d2bbc9e..c6fc1b8 100644 --- a/apps/docs/compose.yaml +++ b/apps/docs/compose.yaml @@ -4,6 +4,5 @@ services: dockerfile: apps/docs/Dockerfile context: ../.. image: pkg.bar/clowder-docs - pull_policy: always x-ports: - clowder.run:80/https diff --git a/apps/web/src/lib/components/canvas/panel/settings/settings-networking.svelte b/apps/web/src/lib/components/canvas/panel/settings/settings-networking.svelte index 69b7dae..44752e1 100644 --- a/apps/web/src/lib/components/canvas/panel/settings/settings-networking.svelte +++ b/apps/web/src/lib/components/canvas/panel/settings/settings-networking.svelte @@ -52,10 +52,30 @@ shows: (...words: string[]) => boolean; } = $props(); + // CLOWDER_DOMAIN and CLOWDER_PREFIX, to name the hostname Uncloud gives a hostless entry. + const systemQuery = createQuery(() => + orpc.resources.listSystemVariables.queryOptions({ + input: { + projectId: resource.projectId, + resourceId: resource.id, + }, + }), + ); + // Ingress is edited in the draft, like the Ingress page; the next deploy publishes it. + // Built-ins resolve hostnames like `${SILO_SERVICE_NAME}.${CLOWDER_DOMAIN}`. const ingress = $derived.by(() => { try { - return parseIngressCompose(draftCompose, env); + return parseIngressCompose( + draftCompose, + env, + Object.fromEntries( + (systemQuery.data ?? []).map(({ key, value }) => [ + key, + value, + ]), + ), + ); } catch { return null; } @@ -63,12 +83,17 @@ const ingressEntries = $derived(ingress?.entries ?? []); - // Raw, so the entry being edited keeps its identity and its row can be swapped for the editor. let ingressEditor = $state.raw<{ mode: IngressMode; entry: HttpIngress | HostIngress | null; } | null>(null); + // Entries are rebuilt whenever the built-ins load, so the edited row is matched by its spec. + const isEditing = (entry: IngressEntry) => + entry.kind !== "caddy" && + ingressEditor?.entry?.service === entry.service && + ingressEditor.entry.raw === entry.raw; + let ingressRemoval = $state(null); let ingressError = $state(""); @@ -102,16 +127,6 @@ } } - // CLOWDER_DOMAIN and CLOWDER_PREFIX, to name the hostname Uncloud gives a hostless entry. - const systemQuery = createQuery(() => - orpc.resources.listSystemVariables.queryOptions({ - input: { - projectId: resource.projectId, - resourceId: resource.id, - }, - }), - ); - const systemValue = (key: string) => systemQuery.data?.find((variable) => variable.key === key) ?.value; @@ -281,7 +296,7 @@ ยท {entry.service} {/if} {/snippet} - {#if ingressEditor?.entry === entry} + {#if ingressEditor && isEditing(entry)} {@render editor(ingressEditor)} {:else} {@render networkRow( diff --git a/packages/workflows/src/ingress.ts b/packages/workflows/src/ingress.ts index 59e13c8..61215e4 100644 --- a/packages/workflows/src/ingress.ts +++ b/packages/workflows/src/ingress.ts @@ -792,12 +792,22 @@ function readServices(composeText: string): ComposeRecord { /** * Parse every service's `x-ports` / `x-caddy` into ingress entries plus issues. * Display values (hostnames, ports, routes) are resolved through the - * resource's Variables (`envText`); entries keep the raw spec for edits. + * resource's Variables (`envText`) over Clowder's `builtIns`; entries keep the raw spec for edits. */ -export function parseIngressCompose(composeText: string, envText = ""): IngressSnapshot { - const vars = parseEnvText(envText); - - return parseIngressComposeWith(composeText, (name) => vars.get(name)); +export function parseIngressCompose( + composeText: string, + envText = "", + builtIns: Record = {}, +): IngressSnapshot { + const resolved = new Map(); + const lookup = (name: string): string | undefined => resolved.get(name) ?? builtIns[name]; + + // Like a deploy, in file order: a Variable sees the built-ins and the Variables above it, + // e.g. `${SILO_SERVICE_NAME}.${CLOWDER_DOMAIN}`. + for (const [name, value] of parseEnvText(envText)) + resolved.set(name, interpolateComposeVariables(value, lookup)); + + return parseIngressComposeWith(composeText, lookup); } /** `parseIngressCompose` with variables from `lookup`, e.g. an already resolved environment. */ diff --git a/packages/workflows/src/references.ts b/packages/workflows/src/references.ts index 572a9e3..75fe111 100644 --- a/packages/workflows/src/references.ts +++ b/packages/workflows/src/references.ts @@ -1,4 +1,7 @@ import type { Database } from "@clowder/db"; +import { s3Buckets, s3Connections, type S3BucketStatus } from "@clowder/db/schema/index"; +import { s3BucketTarget, type S3ConnectionRecord } from "@clowder/s3"; +import { eq, inArray } from "drizzle-orm"; import { parseEnv } from "node:util"; import { ComposeVariableError, @@ -23,10 +26,43 @@ export type ReferenceTarget = { spec: string; // Saved draft, for keys the deployed spec doesn't have yet, like a service moved in. draftSpec?: string; + // Set on bucket resources, which expose their S3 settings instead of Compose variables. + bucket?: { + name: string; + status: S3BucketStatus; + encryptedCredentials: string | null; + connection: S3ConnectionRecord; + }; }; +// Named like the bucket's Variables tab. +const BUCKET_KEYS = [ + "S3_ACCESS_KEY_ID", + "S3_BUCKET", + "S3_ENDPOINT", + "S3_FORCE_PATH_STYLE", + "S3_REGION", + "S3_SECRET_ACCESS_KEY", +]; + +function bucketVariables(target: ReferenceTarget, bucket: NonNullable) { + if (bucket.status !== "ready") + throw new ComposeVariableError(`Bucket "${target.name}" is not ready yet.`); + + const s3 = s3BucketTarget(bucket.connection, target.id, bucket.encryptedCredentials); + + return { + S3_ACCESS_KEY_ID: s3.credentials.accessKey, + S3_BUCKET: bucket.name, + S3_ENDPOINT: s3.endpoint, + S3_FORCE_PATH_STYLE: String(s3.forcePathStyle), + S3_REGION: s3.region, + S3_SECRET_ACCESS_KEY: s3.credentials.secretKey, + } satisfies Record; +} + /** - * Compose resources a reference may point at: same cluster, never internal projects. + * Compose, database and bucket resources a reference may point at: same cluster, never internal projects. * The cluster scope is the tenancy boundary, since env text can hold any UUID. * With `ids`, also every resource those reference in turn, since a chained reference * resolves through each of them. @@ -68,12 +104,36 @@ async function queryTargets(db: Database, clusterId: string, ids?: string[]) { JOIN projects p ON p.id = r.project_id WHERE p.cluster_id = $1 AND p.is_internal IS NOT TRUE - AND r.type IN ('compose', 'database') + AND r.type IN ('compose', 'database', 'bucket') AND ($2::uuid[] IS NULL OR r.id = ANY($2::uuid[])) ORDER BY p.name, r.created_at`, [clusterId, ids ?? null], ); + // Resources without a bucket row match nothing here. + const buckets = await db + .select({ bucket: s3Buckets, connection: s3Connections }) + .from(s3Buckets) + .innerJoin(s3Connections, eq(s3Buckets.connectionId, s3Connections.id)) + .where( + inArray( + s3Buckets.resourceId, + rows.map((row) => row.id), + ), + ); + + for (const { bucket, connection } of buckets) { + const row = rows.find((candidate) => candidate.id === bucket.resourceId); + + if (row) + row.bucket = { + name: bucket.name, + status: bucket.status, + encryptedCredentials: bucket.encryptedCredentials, + connection, + }; + } + return rows; } @@ -134,7 +194,9 @@ export function referenceVariables( target: ReferenceTarget, domain?: string, references?: VariableReferences, -) { +): VariableReferences { + if (target.bucket) return bucketVariables(target, target.bucket); + const { variables, compose } = readVariables(target, domain, references); return { ...compose, ...variables }; @@ -142,6 +204,8 @@ export function referenceVariables( /** Keys a picker offers, by source. Draft keys count too, since references fall back to the draft. */ export function referenceKeys(target: ReferenceTarget) { + if (target.bucket) return BUCKET_KEYS.map((key) => ({ key, source: "clowder" as const })); + const own = parseEnv(resourceEnv(target)); const keys = new Map(); diff --git a/tests/api/template-create.test.ts b/tests/api/template-create.test.ts index 60883ee..aa7c82c 100644 --- a/tests/api/template-create.test.ts +++ b/tests/api/template-create.test.ts @@ -99,10 +99,7 @@ describe("creating every template (PostgreSQL)", () => { expect(group).toMatchObject({ projectId, name: `${appId} ${version}` }); - created = await db - .select() - .from(resources) - .where(eq(resources.groupId, app!.groupId!)); + created = await db.select().from(resources).where(eq(resources.groupId, app!.groupId!)); expect(created).toHaveLength(1 + companionCount); } diff --git a/tests/workflows/ingress.test.ts b/tests/workflows/ingress.test.ts index d91c794..5bc0e6c 100644 --- a/tests/workflows/ingress.test.ts +++ b/tests/workflows/ingress.test.ts @@ -481,6 +481,36 @@ describe("environment variables", () => { expect(snapshot.issues).toEqual([]); }); + it("resolves Variables built from built-ins and other Variables", () => { + const snapshot = parseIngressCompose( + "services:\n silo:\n image: x\n x-ports:\n - ${SILO_HOST}:8080/https\n", + "SILO_HOST=${SILO_SERVICE_NAME}.${CLOWDER_DOMAIN}\nLOOP=${LOOP}\n", + { SILO_SERVICE_NAME: "media-silo", CLOWDER_DOMAIN: "example.uncld.dev" }, + ); + + expect(snapshot.entries.map((entry) => entry.kind === "http" && entry.hostname)).toEqual([ + "media-silo.example.uncld.dev", + ]); + expect(snapshot.issues).toEqual([]); + expect( + parseIngressCompose( + "services:\n a:\n x-ports:\n - ${LOOP}:80/https\n", + "LOOP=${LOOP}\n", + ).issues, + ).toHaveLength(1); + }); + + it("resolves Variables in file order, like a deploy", () => { + const snapshot = parseIngressCompose( + "services:\n web:\n x-ports:\n - ${HOST}:80/https\n", + "HOST=${BASE:-old.example.com}\nBASE=new.example.com\n", + ); + + expect(snapshot.entries.map((entry) => entry.kind === "http" && entry.hostname)).toEqual([ + "old.example.com", + ]); + }); + it("resolves x-caddy site addresses from variables", () => { const snapshot = parseIngressCompose( "services:\n web:\n image: x\n x-caddy: |\n ${SEAFILE_HOST} {\n reverse_proxy {{upstreams ${PORT}}}\n }\n", diff --git a/tests/workflows/references.test.ts b/tests/workflows/references.test.ts index a143fdb..e9fc8b3 100644 --- a/tests/workflows/references.test.ts +++ b/tests/workflows/references.test.ts @@ -1,5 +1,7 @@ +import { encryptS3BucketCredentials } from "@clowder/s3"; +import { encryptS3Secret } from "@clowder/s3/secrets"; import { globSync, readFileSync } from "node:fs"; -import { describe, expect, it } from "vite-plus/test"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test"; import { assertNoComposeReference, ComposeVariableError, @@ -591,3 +593,68 @@ describe("Compose environment references", () => { ); }); }); + +describe("bucket references", () => { + beforeEach(() => vi.stubEnv("APP_SECRET", "references-test-secret-at-least-32-bytes")); + afterEach(() => vi.unstubAllEnvs()); + + const BUCKET_ID = "bbbbbbbb-2222-4333-8444-555555555555"; + + const CONNECTION_ID = "cccccccc-2222-4333-8444-555555555555"; + + const bucket = (status: "ready" | "provisioning"): ReferenceTarget => ({ + ...target(BUCKET_ID, "files", "", ""), + bucket: { + name: "opencloud", + status, + encryptedCredentials: encryptS3BucketCredentials( + { accessKey: "AK", secretKey: "SK" }, + BUCKET_ID, + ), + connection: { + id: CONNECTION_ID, + organizationId: "org", + provider: "generic", + endpoint: "https://s3.example.com", + region: "us-east-1", + forcePathStyle: true, + encryptedCredentials: encryptS3Secret( + JSON.stringify({ accessKey: "shared", secretKey: "shared" }), + { + kind: "connection-credentials", + organizationId: "org", + connectionId: CONNECTION_ID, + }, + ), + providerAccountId: null, + encryptedApiToken: null, + }, + }, + }); + + it("offers the keys the bucket's Variables tab shows", () => { + expect(referenceKeys(bucket("ready")).map(({ key }) => key)).toEqual([ + "S3_ACCESS_KEY_ID", + "S3_BUCKET", + "S3_ENDPOINT", + "S3_FORCE_PATH_STYLE", + "S3_REGION", + "S3_SECRET_ACCESS_KEY", + ]); + }); + + it("resolves the bucket's settings and its own key pair", () => { + const env = `A=${ref(BUCKET_ID, "S3_BUCKET")}\nB=${ref(BUCKET_ID, "S3_SECRET_ACCESS_KEY")}`; + + expect(resolveReferences(env, [bucket("ready")])).toEqual({ + [`${BUCKET_ID}.S3_BUCKET`]: "opencloud", + [`${BUCKET_ID}.S3_SECRET_ACCESS_KEY`]: "SK", + }); + }); + + it("refuses a bucket that is not ready", () => { + expect(() => + resolveReferences(`A=${ref(BUCKET_ID, "S3_BUCKET")}`, [bucket("provisioning")]), + ).toThrow('Bucket "files" is not ready yet.'); + }); +});