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
25 changes: 9 additions & 16 deletions apps/cli/src/command-internal/stack-config.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,12 @@
import { getDefaultCliConfig, type CliConfig } from "@supabase/config";
import { resolveCliConfigSubtree } from "@supabase/config/internal";
import { validateCliConfig } from "@supabase/config/effect";
import {
DEFAULT_LOCAL_JWT_SECRET,
DEFAULT_POSTGRES_ROOT_KEY,
type ServiceCreation as ServiceCreationType,
} from "@supabase/stack/effect";
import { Crypto, Effect, Data, FileSystem, Path, Redacted, SchemaIssue } from "effect";
import type { ServiceCreation as ServiceCreationType } from "@supabase/stack/effect";

import { loadLocalProjectContext, type LocalProjectContext } from "./local-project-context.ts";
import { RuntimeInfo } from "../shared/runtime/runtime-info.service.ts";
Expand Down Expand Up @@ -905,7 +909,6 @@ export const loadStackConfig = Effect.fn("StackConfig.load")(
),
catch: (cause) => new StackConfigError({ message: String(cause) }),
});
const crypto = yield* Crypto.Crypto;
const storageFileSizeLimit = yield* Effect.try({
try: () => String(parseFileSizeLimit(validatedConfig.storage.file_size_limit)),
catch: (cause) =>
Expand All @@ -918,22 +921,12 @@ export const loadStackConfig = Effect.fn("StackConfig.load")(
});
const configuredJwtSecret = yield* Effect.try({
try: () =>
validatedConfig.auth.jwt_secret === undefined
validatedConfig.auth.jwt_secret === undefined || validatedConfig.auth.jwt_secret === ""
? undefined
: resolveJwtSecret(validatedConfig.auth.jwt_secret),
catch: (cause) => new StackConfigError({ message: String(cause) }),
});
const jwtSecret =
configuredJwtSecret === undefined
? Redacted.make(
yield* crypto.randomUUIDv4.pipe(
Effect.mapError(
(cause) =>
new StackConfigError({ message: `Unable to generate JWT secret: ${cause}` }),
),
),
)
: Redacted.make(configuredJwtSecret);
const jwtSecret = Redacted.make(configuredJwtSecret ?? DEFAULT_LOCAL_JWT_SECRET);
const document = context.loaded?.document;
const rootKey = yield* Effect.try({
try: () => {
Expand All @@ -944,7 +937,7 @@ export const loadStackConfig = Effect.fn("StackConfig.load")(
envOverride("SUPABASE_DB_ROOT_KEY", raw, context.projectEnvValues),
context.projectEnvValues,
);
return value === "" ? undefined : value;
return value === undefined || value === "" ? DEFAULT_POSTGRES_ROOT_KEY : value;
},
catch: (cause) => new StackConfigError({ message: String(cause) }),
});
Expand Down Expand Up @@ -1059,7 +1052,7 @@ export const loadStackConfig = Effect.fn("StackConfig.load")(
jwtExpiry: validatedConfig.auth.jwt_expiry,
settings: validatedConfig.db.settings,
healthTimeoutMs,
...(rootKey === undefined ? {} : { rootKey: Redacted.make(rootKey) }),
rootKey: Redacted.make(rootKey),
},
endpoints: { sql: endpoint(dbPort) },
},
Expand Down
3 changes: 2 additions & 1 deletion apps/cli/src/commands/db/start/start.integration.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ import {
StackError,
type DatabaseInstance,
type ServiceCreation,
type ServiceCreationInput,
type Stack,
} from "@supabase/stack/effect";

Expand Down Expand Up @@ -1647,7 +1648,7 @@ describe("db start stack backend", () => {
members: members.map(({ id }) => ({ id, activation: "eager" as const })),
dependencies: [],
})),
supabase: (creations: ReadonlyArray<ServiceCreation>) =>
supabase: (creations: ReadonlyArray<ServiceCreationInput>) =>
Effect.sync(() => {
members = creations.map(() => database);
registered = [database];
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { Effect, FileSystem, Layer, Option, Path, Redacted, Stream } from "effec
import {
StackError,
type Stack,
type ServiceCreation,
type ServiceCreationInput,
type ServiceInstances,
} from "@supabase/stack/effect";
import { runtimeInfoLayer } from "../../../../shared/runtime/runtime-info.layer.ts";
Expand Down Expand Up @@ -92,11 +92,11 @@ const makeFixture = (root: string, failPreparation = false) => {
restoreSnapshot: () => Effect.die("unused"),
resetData: Effect.die("unused"),
};
function create<Input extends ServiceCreation>(
function create<Input extends ServiceCreationInput>(
creation: Input,
): Effect.Effect<ServiceInstances[Input["service"]]>;
function create(
creation: ServiceCreation,
creation: ServiceCreationInput,
): Effect.Effect<ServiceInstances[keyof ServiceInstances]> {
switch (creation.service) {
case "database":
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { BunServices } from "@effect/platform-bun";
import { describe, expect, it } from "@effect/vitest";
import { Effect, Exit, Layer, Schema } from "effect";
import { DEFAULT_LOCAL_JWT_SECRET, DEFAULT_POSTGRES_ROOT_KEY } from "@supabase/stack";
import { Effect, Exit, Layer, Redacted, Schema } from "effect";
import { ServiceCreation } from "../../../../../../packages/stack/src/services/Catalog.ts";
import { runtimeInfoLayer } from "../../../shared/runtime/runtime-info.layer.ts";
import { renderCliConfigTemplate } from "../../../shared/init/project-init.templates.ts";
Expand Down Expand Up @@ -30,9 +31,15 @@ enabled = true
`);
const config = yield* load(root);
const services = yield* config.creations("stack-defaults");
expect(Redacted.value(config.jwtSecret)).toBe(DEFAULT_LOCAL_JWT_SECRET);
for (const service of services) yield* Schema.decodeEffect(ServiceCreation)(service);

const recipes = byService(services);
const database = recipes.get("database");
const rootKey = database?.service === "database" ? database.config.rootKey : undefined;
expect(rootKey === undefined ? undefined : Redacted.value(rootKey)).toBe(
DEFAULT_POSTGRES_ROOT_KEY,
);
expect(recipes.get("database")?.endpoints).toEqual({ sql: { port: "auto" } });
expect(recipes.get("rest")?.endpoints).toEqual({ http: { port: "auto" } });
expect(recipes.get("analytics")?.endpoints).toEqual({ http: { port: "auto" } });
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { BunServices } from "@effect/platform-bun";
import { describe, expect, it } from "@effect/vitest";
import { DEFAULT_LOCAL_JWT_SECRET, DEFAULT_POSTGRES_ROOT_KEY } from "@supabase/stack";
import { Effect, FileSystem, Layer, Redacted, Schema } from "effect";
import { ServiceCreation } from "../../../../../../packages/stack/src/services/Catalog.ts";
import { makeSpec as authSpec } from "../../../../../../packages/stack/src/services/Auth.ts";
Expand Down Expand Up @@ -166,7 +167,7 @@ jwt_secret = "encrypted:BOsrXIZY2BNTW43BeRhMbfvlOIUjwI7GCyFHxJD/Ik+UQ4mqkgVl2+61
}).pipe(Effect.provide(layer)),
);

it.live("reopens with an empty configured JWT secret and omits an empty database root key", () =>
it.live("reopens with empty configured secrets using package defaults", () =>
Effect.gen(function* () {
const root = yield* createStackConfigProject(`project_id = "empty-secrets"
[auth]
Expand All @@ -176,9 +177,12 @@ root_key = ""
`);
const config = yield* loadStackConfig(root);
const creations = yield* config.creations("empty-secrets", { jwtSecret: config.jwtSecret });
expect(Redacted.value(config.jwtSecret)).toBe(DEFAULT_LOCAL_JWT_SECRET);
const database = creations.find((creation) => creation.service === "database");
expect(database).toBeDefined();
expect(database?.config.rootKey).toBeUndefined();
expect(database?.config.rootKey && Redacted.value(database.config.rootKey)).toBe(
DEFAULT_POSTGRES_ROOT_KEY,
);
}).pipe(Effect.provide(layer)),
);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,8 @@ Auth policies, OAuth providers, hooks, MFA, SMTP, email subjects and notificatio
forwarded to Auth. REST search paths, pooler limits, Realtime settings, Studio settings, Storage
S3 protocol/vector controls, and configured Vector ports are forwarded to their services.
Encrypted JWT secrets are decrypted before shared credentials are derived. `db.health_timeout`
controls database readiness; an explicit `db.root_key` is supplied through a stack-owned key file.
controls database readiness; package JWT and PostgreSQL root-key defaults apply when omitted, and
the effective root key is supplied through a stack-owned key file.
Studio receives the Functions management directory/URL and Analytics credentials when present.
Email template `content_path` values and third-party identity providers remain unsupported: they
require template serving and shared external JWKS verification respectively.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { describe, expect, it } from "@effect/vitest";
import { Effect, FileSystem, Layer, Option, Stream } from "effect";
import type {
ServiceCreation,
ServiceCreationInput,
ServiceInstance,
ServiceInstances,
Stack,
Expand Down Expand Up @@ -128,14 +129,30 @@ const instance = (
}
};

const requireConcreteCreation = (creation: ServiceCreationInput): ServiceCreation => {
if (creation.service !== "database") return creation;
if (creation.config.jwtSecret === undefined)
throw new Error("Database creation is missing jwtSecret");
if (creation.config.rootKey === undefined)
throw new Error("Database creation is missing rootKey");
return {
...creation,
config: {
...creation.config,
jwtSecret: creation.config.jwtSecret,
rootKey: creation.config.rootKey,
},
};
};

const fakeStack = () => {
let members: Array<ServiceInstances[keyof ServiceInstances]> = [];
let stopped = 0;
let composed = 0;
const stack: Stack = {
id: "a".repeat(64),
services: {
create: <Input extends ServiceCreation>(_creation: Input) => Effect.die("unused"),
create: <Input extends ServiceCreationInput>(_creation: Input) => Effect.die("unused"),
get: (id: string) => {
const found = members.find((entry) => entry.id === id);
return found === undefined ? Effect.die(`missing instance ${id}`) : Effect.succeed(found);
Expand All @@ -149,10 +166,12 @@ const fakeStack = () => {
members: members.map(({ id }) => ({ id, activation: "eager" as const })),
dependencies: [],
})),
supabase: (creations: ReadonlyArray<ServiceCreation>) =>
supabase: (creations: ReadonlyArray<ServiceCreationInput>) =>
Effect.sync(() => {
composed += 1;
members = creations.map((creation) => instance(creation, `${creation.service}-member`));
members = creations.map((creation) =>
instance(requireConcreteCreation(creation), `${creation.service}-member`),
);
return members;
}),
configure: () => Effect.void,
Expand Down
4 changes: 3 additions & 1 deletion packages/stack/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,9 @@ On Linux, native Functions project files must be outside `/tmp`: Edge Runtime us

The stack owns database, Functions bootstrap, and tool-job directories below its data directory. Storage uploads remain at the caller-supplied Storage `filePath` and are preserved when the stack is destroyed; the caller owns that directory.

Without an explicit database root key, PostgreSQL generates one in its data directory. The key survives stop/reopen and is removed with the database data on reset or destroy.
Omitted database `jwtSecret` and `rootKey` inputs use the shared local-development values exported
as `DEFAULT_LOCAL_JWT_SECRET` and `DEFAULT_POSTGRES_ROOT_KEY`. Explicit values override these defaults.
The effective root key is supplied through a stack-owned file for both native and container runtimes.

## Composition and operation scope

Expand Down
6 changes: 6 additions & 0 deletions packages/stack/src/Defaults.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
/** JWT secret used by local development services when no secret is configured. */
export const DEFAULT_LOCAL_JWT_SECRET = "super-secret-jwt-token-with-at-least-32-characters-long";

/** Root key used by local development PostgreSQL instances when none is configured. */
export const DEFAULT_POSTGRES_ROOT_KEY =
"d4dc5b6d4a1d6a10b2c1e76112c994d65db7cec380572cc1839624d4be3fa275";
Comment thread
jgoux marked this conversation as resolved.
Loading
Loading