Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 2 additions & 3 deletions .github/workflows/tests.yml
Original file line number Diff line number Diff line change
@@ -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 }}
Expand Down
1 change: 0 additions & 1 deletion apps/docs/compose.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,5 @@ services:
dockerfile: apps/docs/Dockerfile
context: ../..
image: pkg.bar/clowder-docs
pull_policy: always
x-ports:
- clowder.run:80/https
Original file line number Diff line number Diff line change
Expand Up @@ -52,23 +52,48 @@
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,
]),
),
Comment thread
greptile-apps[bot] marked this conversation as resolved.
Resolved
);
} catch {
return null;
}
});

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<IngressEntry | null>(null);

let ingressError = $state("");
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -281,7 +296,7 @@
· {entry.service}
{/if}
{/snippet}
{#if ingressEditor?.entry === entry}
{#if ingressEditor && isEditing(entry)}
{@render editor(ingressEditor)}
{:else}
{@render networkRow(
Expand Down
20 changes: 15 additions & 5 deletions packages/workflows/src/ingress.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, string> = {},
): IngressSnapshot {
const resolved = new Map<string, string>();
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. */
Expand Down
70 changes: 67 additions & 3 deletions packages/workflows/src/references.ts
Original file line number Diff line number Diff line change
@@ -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,
Expand All @@ -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<ReferenceTarget["bucket"]>) {
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<string, string>;
}

/**
* 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.
Expand Down Expand Up @@ -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;
}

Expand Down Expand Up @@ -134,14 +194,18 @@ 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 };
}

/** 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<string, ReferenceSource>();

Expand Down
5 changes: 1 addition & 4 deletions tests/api/template-create.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
Expand Down
30 changes: 30 additions & 0 deletions tests/workflows/ingress.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
69 changes: 68 additions & 1 deletion tests/workflows/references.test.ts
Original file line number Diff line number Diff line change
@@ -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,
Expand Down Expand Up @@ -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.');
});
});