Skip to content

PostgreSQL backup tool with Point-In-Time-Recovery and restore verification

FIX (docker): Restore console command access to the metadata database

Rostislav Dugind4e229f26f2b
diff --git a/.github/workflows/ci-release.yml b/.github/workflows/ci-release.yml
index e34e3335..a02f079c 100644
--- a/.github/workflows/ci-release.yml
+++ b/.github/workflows/ci-release.yml
@@ -460,6 +460,21 @@ jobs:
rm -f "$out"
done
+ # A console command is the only user of the credential start.sh publishes for
+ # processes that miss PID 1's environment, so nothing else here notices when
+ # publishing breaks.
+ echo "Checking that a console command reaches the metadata database..."
+ console_output=$(mktemp)
+ if ! docker exec databasus-dev-smoke ./main --list-admins >"$console_output" 2>&1; then
+ echo "console command could not reach the metadata database"
+ cat "$console_output"
+ docker logs databasus-dev-smoke
+ rm -f "$console_output"
+ exit 1
+ fi
+ rm -f "$console_output"
+ echo "console command OK"
+
- name: Install Trivy
run: |
sudo apt-get update
@@ -662,6 +677,21 @@ jobs:
rm -f "$out"
done
+ # A console command is the only user of the credential start.sh publishes for
+ # processes that miss PID 1's environment, so nothing else here notices when
+ # publishing breaks.
+ echo "Checking that a console command reaches the metadata database..."
+ console_output=$(mktemp)
+ if ! docker exec databasus-smoke ./main --list-admins >"$console_output" 2>&1; then
+ echo "console command could not reach the metadata database"
+ cat "$console_output"
+ docker logs databasus-smoke
+ rm -f "$console_output"
+ exit 1
+ fi
+ rm -f "$console_output"
+ echo "console command OK"
+
- name: Install Trivy
run: |
sudo apt-get update
diff --git a/Dockerfile b/Dockerfile
index 61e4b7b3..8573b729 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -188,9 +188,14 @@ COPY --from=verification-agent-build /verification-agent-binaries/* ./agent-bina
# Bake .env.example as /.env so the binary has defaults when no env file is
# mounted. The backend looks for .env at the parent of cwd (= /app), i.e. /.
-# Real env vars (-e, compose, k8s) take precedence — godotenv.Load does not
-# overwrite already-set variables.
+# Real env vars (-e, compose, k8s) win, then the connection string start.sh
+# publishes for the embedded database, then these defaults. godotenv.Load does
+# not overwrite already-set variables, which is what puts these defaults last.
+# DATABASE_DSN is stripped because its development password cannot authenticate
+# against the embedded database, whose password is generated at every start.
+# Keeping it would turn a missing configuration into an authentication failure.
COPY .env.example /.env
+RUN sed -i '/^DATABASE_DSN=/d' /.env
COPY --chmod=0755 docker/start.sh /app/start.sh
diff --git a/backend/cmd/main.go b/backend/cmd/main.go
index 5371b35b..34ba2ddc 100644
--- a/backend/cmd/main.go
+++ b/backend/cmd/main.go
@@ -149,7 +149,11 @@ type commandLineOptions struct {
}
func parseCommandLineOptions() commandLineOptions {
- shouldTestStorage := flag.Bool("test-storage", false, "Save and delete a local storage probe")
+ shouldTestStorage := flag.Bool(
+ config.StorageProbeFlagName,
+ false,
+ "Save and delete a local storage probe",
+ )
shouldListAdmins := flag.Bool("list-admins", false, "Print every administrator account of this instance")
newPassword := flag.String("new-password", "", "Set a new password for the user")
passwordResetEmail := flag.String("email", "", "Email of the user to reset password")
diff --git a/backend/internal/config/config.go b/backend/internal/config/config.go
index e6c5e57e..be735be1 100644
--- a/backend/internal/config/config.go
+++ b/backend/internal/config/config.go
@@ -3,6 +3,7 @@ package config
import (
"context"
"database/sql"
+ "errors"
"fmt"
"os"
"path/filepath"
@@ -26,6 +27,16 @@ const (
AppModeBackground = "background"
)
+const databaseDsnEnvVariable = "DATABASE_DSN"
+
+const StorageProbeFlagName = "test-storage"
+
+// A process started with `docker exec` does not inherit PID 1's environment, so this file
+// is the only way it learns the internal password, which is rotated on every container
+// start. The location is memory-backed, so the value dies with the container instead of
+// going stale against the next rotation.
+const publishedDatabaseDsnPath = "/dev/shm/databasus-database-dsn"
+
const (
// defaultTestParallelWorkers must equal the `go test -p` value so every running package can
// claim an isolated metadata database.
@@ -125,6 +136,8 @@ func loadEnvVariables() {
envPath := filepath.Join(filepath.Dir(backendRoot), ".env")
+ adoptPublishedDatabaseDsnIfUnset(publishedDatabaseDsnPath)
+
log.Info("trying to load .env", "path", envPath)
if err := godotenv.Load(envPath); err != nil {
log.Error("error loading .env file from repo root", "path", envPath, "error", err)
@@ -174,7 +187,7 @@ func loadEnvVariables() {
}
}
- if env.DatabaseDsn == "" {
+ if !isStorageProbeProcess(os.Args) && env.DatabaseDsn == "" {
log.Error("DATABASE_DSN is empty")
logger.ExitAfterFlush(1)
}
@@ -222,6 +235,39 @@ func loadEnvVariables() {
log.Info("environment variables loaded successfully")
}
+// An operator-supplied connection string wins, then the one startup published, then
+// whatever the baked defaults still carry.
+func adoptPublishedDatabaseDsnIfUnset(publishedDsnPath string) {
+ if _, isSet := os.LookupEnv(databaseDsnEnvVariable); isSet {
+ return
+ }
+
+ publishedDsn, err := os.ReadFile(publishedDsnPath)
+ if err != nil {
+ if !errors.Is(err, os.ErrNotExist) {
+ log.Warn(
+ "could not read the published database connection string",
+ "path", publishedDsnPath,
+ "error", err,
+ )
+ }
+
+ return
+ }
+
+ dsn := strings.TrimSpace(string(publishedDsn))
+ if dsn == "" {
+ return
+ }
+
+ if err := os.Setenv(databaseDsnEnvVariable, dsn); err != nil {
+ log.Error("could not apply the published database connection string", "error", err)
+ logger.ExitAfterFlush(1)
+ }
+
+ log.Info("using the database connection string published by container startup")
+}
+
func unsetEmptyEnvVars() {
for _, kv := range os.Environ() {
key, value, ok := strings.Cut(kv, "=")
@@ -235,6 +281,29 @@ func unsetEmptyEnvVars() {
}
}
+// The storage probe never opens the metadata database, and container startup runs it
+// before the embedded database exists, so demanding a connection string there would
+// refuse a healthy container. The flag is read here rather than passed in because
+// package-level dependency wiring loads the configuration before main runs.
+func isStorageProbeProcess(arguments []string) bool {
+ if len(arguments) == 0 {
+ return false
+ }
+
+ for _, argument := range arguments[1:] {
+ if !strings.HasPrefix(argument, "-") {
+ continue
+ }
+
+ flagName, _, _ := strings.Cut(strings.TrimLeft(argument, "-"), "=")
+ if flagName == StorageProbeFlagName {
+ return true
+ }
+ }
+
+ return false
+}
+
func isTestProcess(arguments []string) bool {
if len(arguments) == 0 {
return false
diff --git a/backend/internal/config/config_test.go b/backend/internal/config/config_test.go
index 8ac24349..2e42b33e 100644
--- a/backend/internal/config/config_test.go
+++ b/backend/internal/config/config_test.go
@@ -1,9 +1,13 @@
package config
import (
+ "os"
+ "path/filepath"
"testing"
+ "github.com/ilyakaznacheev/cleanenv"
"github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
)
func Test_IsTestProcess_UsesExecutableNameOnly(t *testing.T) {
@@ -51,3 +55,108 @@ func Test_IsTestProcess_UsesExecutableNameOnly(t *testing.T) {
})
}
}
+
+const publishedTestDsn = "host=localhost user=postgres password=published dbname=databasus port=5437 sslmode=disable"
+
+func Test_AdoptPublishedDatabaseDsnIfUnset_WhenEnvironmentHasNoDsn_UsesThePublishedOne(t *testing.T) {
+ clearDatabaseDsnEnvVariable(t)
+ publishedDsnPath := writePublishedDsn(t, publishedTestDsn+"\n")
+
+ adoptPublishedDatabaseDsnIfUnset(publishedDsnPath)
+
+ assert.Equal(t, publishedTestDsn, os.Getenv(databaseDsnEnvVariable))
+}
+
+func Test_AdoptPublishedDatabaseDsnIfUnset_WhenEnvironmentHasADsn_KeepsIt(t *testing.T) {
+ const suppliedDsn = "host=external user=postgres password=supplied dbname=databasus port=5432 sslmode=require"
+
+ t.Setenv(databaseDsnEnvVariable, suppliedDsn)
+ publishedDsnPath := writePublishedDsn(t, publishedTestDsn)
+
+ adoptPublishedDatabaseDsnIfUnset(publishedDsnPath)
+
+ assert.Equal(t, suppliedDsn, os.Getenv(databaseDsnEnvVariable))
+}
+
+func Test_AdoptPublishedDatabaseDsnIfUnset_WhenNothingIsPublishedOrSupplied_LeavesTheDsnEmpty(
+ t *testing.T,
+) {
+ clearDatabaseDsnEnvVariable(t)
+ missingDsnPath := filepath.Join(t.TempDir(), "never-published")
+
+ adoptPublishedDatabaseDsnIfUnset(missingDsnPath)
+
+ assert.Empty(t, os.Getenv(databaseDsnEnvVariable))
+
+ var environmentVariables EnvVariables
+ require.NoError(t, cleanenv.ReadEnv(&environmentVariables))
+
+ assert.Empty(t, environmentVariables.DatabaseDsn)
+}
+
+func clearDatabaseDsnEnvVariable(t *testing.T) {
+ t.Helper()
+
+ t.Setenv(databaseDsnEnvVariable, "")
+ require.NoError(t, os.Unsetenv(databaseDsnEnvVariable))
+}
+
+func writePublishedDsn(t *testing.T, contents string) string {
+ t.Helper()
+
+ publishedDsnPath := filepath.Join(t.TempDir(), "databasus-database-dsn")
+ require.NoError(t, os.WriteFile(publishedDsnPath, []byte(contents), 0o600))
+
+ return publishedDsnPath
+}
+
+func Test_IsStorageProbeProcess_RecognisesOnlyTheStorageProbeFlag(t *testing.T) {
+ testCases := []struct {
+ name string
+ arguments []string
+ isStorageProbe bool
+ }{
+ {
+ name: "double dash flag",
+ arguments: []string{"/app/main", "--test-storage"},
+ isStorageProbe: true,
+ },
+ {
+ name: "single dash flag",
+ arguments: []string{"/app/main", "-test-storage"},
+ isStorageProbe: true,
+ },
+ {
+ name: "flag with explicit value",
+ arguments: []string{"/app/main", "--test-storage=true"},
+ isStorageProbe: true,
+ },
+ {
+ name: "another command",
+ arguments: []string{"/app/main", "--list-admins"},
+ isStorageProbe: false,
+ },
+ {
+ name: "flag name inside an attached value",
+ arguments: []string{"/app/main", "--email=test-storage"},
+ isStorageProbe: false,
+ },
+ {
+ name: "flag name as a separate value",
+ arguments: []string{"/app/main", "--email", "test-storage"},
+ isStorageProbe: false,
+ },
+ {
+ name: "no arguments",
+ arguments: nil,
+ isStorageProbe: false,
+ },
+ }
+
+ for _, testCase := range testCases {
+ t.Run(testCase.name, func(t *testing.T) {
+ isStorageProbe := isStorageProbeProcess(testCase.arguments)
+ assert.Equal(t, testCase.isStorageProbe, isStorageProbe)
+ })
+ }
+}
diff --git a/docker/start.sh b/docker/start.sh
index 4014144f..f8cd9468 100755
--- a/docker/start.sh
+++ b/docker/start.sh
@@ -6,6 +6,12 @@ export TMPDIR=/tmp
readonly permissions_documentation_url="https://databasus.com/advanced-config/#docker-storage-permissions"
readonly postgres_binary_directory="/usr/lib/postgresql/17/bin"
+# A process started with `docker exec` inherits the container's configured environment, not
+# PID 1's, so the generated credential reaches it through this file instead. The location is
+# memory-backed, so the value dies with the container rather than outliving the password
+# rotation of the next start. backend/internal/config/config.go reads the same path.
+readonly published_database_dsn_path="/dev/shm/databasus-database-dsn"
+
runtime_uid=""
runtime_gid=""
postgres_pid=""
@@ -531,6 +537,10 @@ configure_application_database_dsn() {
fi
export DATABASE_DSN="host=localhost user=postgres password=${internal_postgres_password} dbname=databasus port=5437 sslmode=disable"
+
+ install -m 0600 -o databasus -g databasus /dev/null "${published_database_dsn_path}"
+ printf '%s\n' "${DATABASE_DSN}" \
+ | gosu databasus tee "${published_database_dsn_path}" >/dev/null
}
bootstrap_postgresql() {
diff --git a/openspec/changes/restore-console-command-database-access/.openspec.yaml b/openspec/changes/archive/2026-09-20-restore-console-command-database-access/.openspec.yaml
similarity index 100%
rename from openspec/changes/restore-console-command-database-access/.openspec.yaml
rename to openspec/changes/archive/2026-09-20-restore-console-command-database-access/.openspec.yaml
diff --git a/openspec/changes/restore-console-command-database-access/design.md b/openspec/changes/archive/2026-09-20-restore-console-command-database-access/design.md
similarity index 79%
rename from openspec/changes/restore-console-command-database-access/design.md
rename to openspec/changes/archive/2026-09-20-restore-console-command-database-access/design.md
index 586481cb..b9f23579 100644
--- a/openspec/changes/restore-console-command-database-access/design.md
+++ b/openspec/changes/archive/2026-09-20-restore-console-command-database-access/design.md
@@ -104,6 +104,31 @@ embedded credential override an operator's deliberate choice of an external
metadata database, inverting the precedence the current startup already
guarantees.
+### Exempt the storage probe from the metadata-database requirement
+
+`prepare_and_verify_storage` (`docker/start.sh:343-352`) ends with
+`gosu databasus /app/main --test-storage`, and it runs before
+`bootstrap_postgresql`, so the generated password does not exist yet. Once the
+baked default is gone, that probe is refused for a connection string that
+cannot be available at that point, and the container never starts. The probe
+itself only needs `TempFolder` and `DataFolder`, both derived from paths.
+
+Configuration loading therefore recognises the `--test-storage` process from
+`os.Args` and skips the missing-connection-string exit for it, the way it
+already recognises a test binary. The flag is read inside
+`backend/internal/config` rather than passed in from `main`, because
+package-level dependency wiring such as `backend/internal/features/email/di.go:9`
+calls `GetEnv` during program initialisation, before `main` runs.
+
+Alternatives rejected:
+
+- **Running the probe after `bootstrap_postgresql`.** The permission checks
+ around it exist to fail early with the documentation URL; an operator with a
+ broken `/databasus-data` would instead first see `initdb` fail.
+- **Handing the probe a placeholder connection string from `start.sh`.**
+ Reinstates the fake credential this change deletes, and it is the value the
+ probe would connect with if it ever grew a database dependency.
+
### Delete `DATABASE_DSN` from the baked `/.env`, keep it in `.env.example`
`.env.example` stays as it is, because the repository's Docker Compose stack
@@ -141,6 +166,16 @@ Alternatives rejected:
(`docker/start.sh:121-136`) has applied `PUID`/`PGID`, so publishing must stay
ordered after it. `bootstrap_postgresql` already runs later in `main()`
(`docker/start.sh:586-595`), so the required order is the existing one.
+- **Who writes and who reads the published file** → The application reads it as
+ the runtime account (`docker/start.sh:605` ends with
+ `exec gosu databasus ./main`), so that account must own it. Startup runs as
+ root, and writing into a `0600` file owned by another account was refused on
+ the host this was verified on, so startup creates the file with `install` and
+ fills it through `gosu databasus tee`, the idiom the script already uses for
+ `pg_hba.conf`. The image declares no `USER`, so the documented
+ `docker exec <container> ./main ...` runs as root; root reading that file
+ worked on the same host, and a deployment that drops `CAP_DAC_OVERRIDE` would
+ lose the documented recovery command.
- **Silent regression** → The failure is invisible to normal startup: PID 1
keeps working even when publishing is broken. An automated check that runs a
console command against a started container is the only thing that catches
diff --git a/openspec/changes/restore-console-command-database-access/proposal.md b/openspec/changes/archive/2026-09-20-restore-console-command-database-access/proposal.md
similarity index 100%
rename from openspec/changes/restore-console-command-database-access/proposal.md
rename to openspec/changes/archive/2026-09-20-restore-console-command-database-access/proposal.md
diff --git a/openspec/changes/restore-console-command-database-access/specs/internal-postgresql-protection/spec.md b/openspec/changes/archive/2026-09-20-restore-console-command-database-access/specs/internal-postgresql-protection/spec.md
similarity index 93%
rename from openspec/changes/restore-console-command-database-access/specs/internal-postgresql-protection/spec.md
rename to openspec/changes/archive/2026-09-20-restore-console-command-database-access/specs/internal-postgresql-protection/spec.md
index d0cca8c2..6c4175a7 100644
--- a/openspec/changes/restore-console-command-database-access/specs/internal-postgresql-protection/spec.md
+++ b/openspec/changes/archive/2026-09-20-restore-console-command-database-access/specs/internal-postgresql-protection/spec.md
@@ -68,12 +68,19 @@ An operator-supplied connection string SHALL take precedence over the one startu
When no metadata-database connection string is available from any source, a starting process SHALL report that the configuration is missing and SHALL NOT attempt a connection with a default credential. A rejected credential and an absent configuration SHALL produce distinguishable messages.
+A process that never opens the metadata database SHALL be exempt from this requirement, because container startup runs the storage probe before the embedded database exists.
+
#### Scenario: No connection string anywhere
- **WHEN** a process starts in a container where startup published no connection string and the operator supplied none
- **THEN** it reports the metadata-database configuration as missing
- **AND** the message does not describe an authentication failure
+#### Scenario: Storage probe before the database exists
+
+- **WHEN** container startup runs the storage probe, before any metadata-database credential exists
+- **THEN** the probe completes on its own merits rather than being refused for a missing connection string
+
#### Scenario: Wrong credential supplied
- **WHEN** a process starts with a connection string whose password the database rejects
diff --git a/openspec/changes/restore-console-command-database-access/tasks.md b/openspec/changes/archive/2026-09-20-restore-console-command-database-access/tasks.md
similarity index 69%
rename from openspec/changes/restore-console-command-database-access/tasks.md
rename to openspec/changes/archive/2026-09-20-restore-console-command-database-access/tasks.md
index 836cb6e2..6e8701c4 100644
--- a/openspec/changes/restore-console-command-database-access/tasks.md
+++ b/openspec/changes/archive/2026-09-20-restore-console-command-database-access/tasks.md
@@ -1,32 +1,33 @@
## 1. Resolve the credential inside the backend
-- [ ] 1.1 Add a resolution step in `backend/internal/config` that reads the published connection string when `DATABASE_DSN` is absent from the process environment, ordered before the `/.env` load at `backend/internal/config/config.go:126-133`; verify with a new test in `backend/internal/config/config_test.go` that the published value is used when the environment is empty
-- [ ] 1.2 Cover the precedence rule with a test asserting that a `DATABASE_DSN` already set in the environment wins over a published file holding a different value; verify with `cd backend && make test` for that package
-- [ ] 1.3 Cover the absent case with a test asserting that no published file and no environment value leaves `DatabaseDsn` empty, so the existing required-field diagnostic at `backend/internal/config/config.go:178` is what the operator sees; verify with `cd backend && make test` for that package
-- [ ] 1.4 Run `cd backend && make lint` and fix every finding in the touched files
+- [x] 1.1 Add a resolution step in `backend/internal/config` that reads the published connection string when `DATABASE_DSN` is absent from the process environment, ordered before the `/.env` load at `backend/internal/config/config.go:126-133`; verify with a new test in `backend/internal/config/config_test.go` that the published value is used when the environment is empty
+- [x] 1.2 Cover the precedence rule with a test asserting that a `DATABASE_DSN` already set in the environment wins over a published file holding a different value; verify with `cd backend && make test` for that package
+- [x] 1.3 Cover the absent case with a test asserting that no published file and no environment value leaves `DatabaseDsn` empty, so the existing required-field diagnostic at `backend/internal/config/config.go:178` is what the operator sees; verify with `cd backend && make test` for that package
+- [x] 1.4 Run `cd backend && make lint` and fix every finding in the touched files
+- [x] 1.5 Exempt the `--test-storage` process from the missing-connection-string exit in `backend/internal/config`, because container startup runs it before the embedded database exists; verify with a test covering the flag forms and by starting a built container
## 2. Publish the credential at startup
-- [ ] 2.1 Extend `configure_application_database_dsn` (`docker/start.sh:528-534`) to write the generated connection string to the memory-backed location with mode `0600` owned by the runtime account, keeping the existing early return that preserves an operator-supplied value; verify by starting a built container and confirming the file exists with the expected owner and mode
-- [ ] 2.2 Confirm the ordering constraint holds by starting a container with `PUID` and `PGID` set to unused non-default ids and checking that the published file is owned by the renumbered account
+- [x] 2.1 Extend `configure_application_database_dsn` (`docker/start.sh:528-534`) to write the generated connection string to the memory-backed location with mode `0600` owned by the runtime account, keeping the existing early return that preserves an operator-supplied value; verify by starting a built container and confirming the file exists with the expected owner and mode
+- [x] 2.2 Confirm the ordering constraint holds by starting a container with `PUID` and `PGID` set to unused non-default ids and checking that the published file is owned by the renumbered account
## 3. Remove the stale default from the image
-- [ ] 3.1 Drop `DATABASE_DSN` from the copy of `.env.example` that lands at `/.env` during the build (`Dockerfile:189-193`), leaving `.env.example` itself untouched, and correct the comment above that copy (`Dockerfile:189-192`), which currently explains the baked defaults and the precedence rule without the new source; verify with `docker run --rm --entrypoint sh <image> -c 'grep -c DATABASE_DSN /.env'` returning no match
-- [ ] 3.2 Confirm local development still works after the change by running the backend against the repository Docker Compose stack
+- [x] 3.1 Drop `DATABASE_DSN` from the copy of `.env.example` that lands at `/.env` during the build (`Dockerfile:189-193`), leaving `.env.example` itself untouched, and correct the comment above that copy (`Dockerfile:189-192`), which currently explains the baked defaults and the precedence rule without the new source; verify with `docker run --rm --entrypoint sh <image> -c 'grep -c DATABASE_DSN /.env'` returning no match
+- [x] 3.2 Confirm local development still works after the change by running the backend against the repository Docker Compose stack
## 4. Verify the reported scenario end to end
-- [ ] 4.1 Build the image, start a fresh container with no `DATABASE_DSN` supplied, and run `docker exec <container> ./main --new-password="..." --email="..."`; verify the command completes without an authentication error and the new password signs in
-- [ ] 4.2 Restart that container and run the same command again; verify it succeeds with the rotated password rather than the one from the previous run
-- [ ] 4.3 Start a container with an explicit `DATABASE_DSN` pointing at an external metadata database, then run a console command; verify it connects to that external database and that no credential file was published
-- [ ] 4.4 Start a container whose startup published nothing and whose environment carries no connection string, then run a console command; verify the failure names the missing configuration instead of reporting an authentication failure
+- [x] 4.1 Build the image, start a fresh container with no `DATABASE_DSN` supplied, and run `docker exec <container> ./main --new-password="..." --email="..."`; verify the command completes without an authentication error and the new password signs in
+- [x] 4.2 Restart that container and run the same command again; verify it succeeds with the rotated password rather than the one from the previous run
+- [x] 4.3 Start a container with an explicit `DATABASE_DSN` pointing at an external metadata database, then run a console command; verify it connects to that external database and that no credential file was published
+- [x] 4.4 Start a container whose startup published nothing and whose environment carries no connection string, then run a console command; verify the failure names the missing configuration instead of reporting an authentication failure
## 5. Guard against silent regression
-- [ ] 5.1 Add an automated check that runs a console command against a started container, so a future change that breaks publishing fails a check rather than only breaking `docker exec`; verify the check fails when the publishing step is removed and passes when it is restored
+- [x] 5.1 Add an automated check that runs a console command against a started container, so a future change that breaks publishing fails a check rather than only breaking `docker exec`; verify the check fails when the publishing step is removed and passes when it is restored
## 6. Review
-- [ ] 6.1 Complete the mandatory compliance review for the finished diff and resolve every CHANGES REQUIRED finding.
-- [ ] 6.2 Mark the completed tasks in this file so the status update is part of the same commit as the implementation
+- [x] 6.1 Complete the mandatory compliance review for the finished diff and resolve every CHANGES REQUIRED finding.
+- [x] 6.2 Mark the completed tasks in this file so the status update is part of the same commit as the implementation
diff --git a/openspec/specs/internal-postgresql-protection/spec.md b/openspec/specs/internal-postgresql-protection/spec.md
index 69e815e2..4dbe7bef 100644
--- a/openspec/specs/internal-postgresql-protection/spec.md
+++ b/openspec/specs/internal-postgresql-protection/spec.md
@@ -199,6 +199,10 @@ The embedded PostgreSQL port SHALL remain unpublished by the image.
When Databasus uses its embedded metadata database, the container SHALL generate a cryptographically random PostgreSQL password at startup, set it on the internal role, and supply it to the application without logging it. A container restart SHALL replace the previous password. An explicitly supplied external metadata-database connection string SHALL remain unchanged.
+The generated connection string SHALL also be readable by processes that start later in the same container, so that a command run against a running instance authenticates with the same credential as the application. That value SHALL exist only for the lifetime of the running container: it SHALL NOT be written to storage that survives a container stop, and it SHALL NOT be part of the distributed image.
+
+When the operator supplies a metadata-database connection string, startup SHALL neither generate nor publish one, and every process in the container SHALL use the supplied value. When the operator supplies none, every process SHALL use the generated one. No process SHALL fall back to a connection string shipped as a default inside the image.
+
An operator-supplied connection string that points back to the embedded database with the previously published fixed password is incompatible with rotation and SHALL NOT be treated as a supported embedded-database configuration.
#### Scenario: Fresh container startup
@@ -212,6 +216,7 @@ An operator-supplied connection string that points back to the embedded database
- **WHEN** the same container restarts
- **THEN** the embedded role receives a different generated password
- **AND** the application reconnects with the new password
+- **AND** a command started after the restart authenticates with the new password rather than the previous one
#### Scenario: Previously published fixed password
@@ -222,9 +227,73 @@ An operator-supplied connection string that points back to the embedded database
- **WHEN** the operator explicitly supplies a connection string for an external metadata database
- **THEN** startup preserves that value rather than replacing it with the embedded database connection
+- **AND** startup publishes no generated connection string for other processes to pick up
#### Scenario: Explicit connection string points to the embedded database
- **WHEN** the operator explicitly supplies the previously published fixed connection string for the embedded database
- **THEN** the application cannot authenticate after startup rotates the internal role's password
- **AND** the operator must remove that explicit value so startup can supply the generated credential
+
+### Requirement: Console commands reach the metadata database of a running container
+
+A console command executed inside an already-running container SHALL resolve the metadata-database connection the same way the application did, and SHALL connect successfully whenever the application itself is connected. This SHALL hold for a container using the embedded database and for one pointed at an external metadata database.
+
+An operator-supplied connection string SHALL take precedence over the one startup generated. A console command SHALL NOT need any argument, file or environment value beyond what the operator already supplied to the container.
+
+#### Scenario: Password reset on a fresh instance
+
+- **WHEN** an operator runs the documented password-reset command inside a running container that uses the embedded database
+- **THEN** the command connects to the metadata database and sets the new password
+- **AND** the operator can sign in with it
+
+#### Scenario: Console command against an external metadata database
+
+- **WHEN** the operator supplied a connection string for an external metadata database and runs a console command
+- **THEN** the command connects to that external database
+
+#### Scenario: Console command while the application is running
+
+- **WHEN** a console command runs while the application holds its own connection to the embedded database
+- **THEN** both connect with the same credential and neither disturbs the other
+
+### Requirement: Missing metadata-database configuration is reported as such
+
+When no metadata-database connection string is available from any source, a starting process SHALL report that the configuration is missing and SHALL NOT attempt a connection with a default credential. A rejected credential and an absent configuration SHALL produce distinguishable messages.
+
+A process that never opens the metadata database SHALL be exempt from this requirement, because container startup runs the storage probe before the embedded database exists.
+
+#### Scenario: No connection string anywhere
+
+- **WHEN** a process starts in a container where startup published no connection string and the operator supplied none
+- **THEN** it reports the metadata-database configuration as missing
+- **AND** the message does not describe an authentication failure
+
+#### Scenario: Storage probe before the database exists
+
+- **WHEN** container startup runs the storage probe, before any metadata-database credential exists
+- **THEN** the probe completes on its own merits rather than being refused for a missing connection string
+
+#### Scenario: Wrong credential supplied
+
+- **WHEN** a process starts with a connection string whose password the database rejects
+- **THEN** it reports an authentication failure rather than a missing configuration
+
+### Requirement: The shared internal credential stays inside the container
+
+The published connection string SHALL be readable only by the account that runs Databasus and by the container's privileged account. Any other account inside the container SHALL be refused. The value SHALL NOT appear in logs, in the image, or on any volume the operator mounts.
+
+#### Scenario: Another account in the container
+
+- **WHEN** a process running under an operating-system account other than the Databasus runtime account attempts to read the published connection string
+- **THEN** the read is refused
+
+#### Scenario: Operator inspects the mounted data volume
+
+- **WHEN** the operator inspects the mounted data directory after the container has started
+- **THEN** the generated password is absent from it
+
+#### Scenario: Operator inspects a stopped container's image
+
+- **WHEN** the operator inspects the distributed image
+- **THEN** it contains no metadata-database connection string usable against the embedded database