fix: refuse unknown built-in PostgreSQL data versions (#32489)

<!-- Authored with Coder Agents on behalf of @Emyrk -->

Refs
https://linear.app/codercom/issue/CORE-634/upgrade-embedded-postgresql-to-a-non-eol-version.
Precedes #32144.

Refuse to start built-in PostgreSQL when an existing data directory has
a missing or unsupported version, rather than letting embedded-postgres
replace its data.

- An existing `PG_VERSION` other than 13, including 18 or 19, now
returns an error without starting PostgreSQL.
- A missing marker also returns recovery guidance instead of
initializing over existing data.
- Fresh databases and existing PostgreSQL 13 databases keep their
current behavior.
- Development database recovery uses the same guard.

<details><summary>Agent context</summary>

The bundled embedded-postgres v1 library can delete an existing data
directory whose version does not match its PostgreSQL 13 binary. This
change checks the directory before invoking the library, without
changing the binary version or migrating data. Only Coder builds
containing this guard gain the protection; already-released older
binaries remain unchanged.

</details>

---

<sub>Coder Agents on behalf of @Emyrk.</sub>
This commit is contained in:
Steven Masley authored and GitHub committed 2026-11-20 13:43:07 -06:00
1 parent 41ab09f075
commit 462b474729
6 files changed
+111

No files matched your search

+39
View File
@@ -0,0 +1,39 @@
package config
import (
"errors"
"os"
"path/filepath"
"strings"
"golang.org/x/xerrors"
)
// ValidateBuiltinPostgresVersion refuses to start over existing data that this
// Coder release cannot read. Embedded-postgres otherwise removes that data.
func ValidateBuiltinPostgresVersion(postgresPath string) error {
dataPath := filepath.Join(postgresPath, "data")
_, err := os.Stat(dataPath)
if errors.Is(err, os.ErrNotExist) {
return nil
}
if err != nil {
return xerrors.Errorf("inspect built-in PostgreSQL data directory: %w", err)
}
versionPath := filepath.Join(dataPath, "PG_VERSION")
contents, err := os.ReadFile(versionPath)
if err != nil {
advice := "Check that Coder can read the file and data directory before retrying."
if errors.Is(err, os.ErrNotExist) {
advice = "Restore the data directory from a backup, or if this is an unused new deployment, move it aside and restart. Do not create PG_VERSION manually."
}
return xerrors.Errorf("read built-in PostgreSQL version in %s: %w; data was not changed. %s", dataPath, err, advice)
}
version := strings.TrimSuffix(string(contents), "\n")
if version != "13" {
return xerrors.Errorf("unsupported built-in PostgreSQL version %q in %s; data was not changed", version, versionPath)
}
return nil
}
+21
View File
@@ -0,0 +1,21 @@
package config_test
import (
"os"
"path/filepath"
"testing"
"github.com/stretchr/testify/require"
"github.com/coder/coder/v2/cli/config"
)
func TestValidateBuiltinPostgresVersionAcceptsExisting13(t *testing.T) {
t.Parallel()
postgresPath := t.TempDir()
dataPath := filepath.Join(postgresPath, "data")
require.NoError(t, os.Mkdir(dataPath, 0o700))
require.NoError(t, os.WriteFile(filepath.Join(dataPath, "PG_VERSION"), []byte("13\n"), 0o600))
require.NoError(t, config.ValidateBuiltinPostgresVersion(postgresPath))
}
+3
View File
@@ -2476,6 +2476,9 @@ func startBuiltinPostgres(ctx context.Context, cfg config.Root, logger slog.Logg
if usr.Uid == "0" {
return "", nil, xerrors.New("The built-in PostgreSQL cannot run as the root user. Create a non-root user and run again!")
}
if err := config.ValidateBuiltinPostgresVersion(cfg.PostgresPath()); err != nil {
return "", nil, err
}
cachePath := filepath.Join(cfg.PostgresPath(), "cache")
if customCacheDir != "" {
+42
View File
@@ -5,6 +5,8 @@ import (
"context"
"crypto/tls"
"net/http"
"os"
"path/filepath"
"testing"
"github.com/spf13/pflag"
@@ -14,11 +16,51 @@ import (
"cdr.dev/slog/v3"
"cdr.dev/slog/v3/sloggers/sloghuman"
"github.com/coder/coder/v2/cli/config"
"github.com/coder/coder/v2/codersdk"
"github.com/coder/coder/v2/testutil"
"github.com/coder/serpent"
)
func TestStartBuiltinPostgresRejectsUnknownVersion(t *testing.T) {
t.Parallel()
for _, tc := range []struct {
name string
version string
wantErr string
}{
{name: "Future19", version: "19\n", wantErr: "unsupported built-in PostgreSQL version"},
{name: "MissingMarker", wantErr: "Do not create PG_VERSION manually"},
{name: "Malformed13", version: "13 \n", wantErr: "unsupported built-in PostgreSQL version"},
} {
t.Run(tc.name, func(t *testing.T) {
t.Parallel()
cfg := config.Root(t.TempDir())
dataDir := filepath.Join(cfg.PostgresPath(), "data")
require.NoError(t, os.MkdirAll(dataDir, 0o700))
if tc.version != "" {
require.NoError(t, os.WriteFile(filepath.Join(dataDir, "PG_VERSION"), []byte(tc.version), 0o600))
}
keepPath := filepath.Join(dataDir, "keep")
require.NoError(t, os.WriteFile(keepPath, []byte("existing data"), 0o600))
require.NoError(t, cfg.PostgresPort().Write("59999"))
_, stopPG, err := startBuiltinPostgres(t.Context(), cfg, testutil.Logger(t), "")
if stopPG != nil {
require.NoError(t, stopPG())
}
require.ErrorContains(t, err, tc.wantErr)
contents, readErr := os.ReadFile(keepPath)
require.NoError(t, readErr)
require.Equal(t, "existing data", string(contents))
_, readErr = cfg.PostgresPassword().Read()
require.ErrorIs(t, readErr, os.ErrNotExist)
})
}
}
func Test_configureServerTLS(t *testing.T) {
t.Parallel()
t.Run("DefaultNoInsecureCiphers", func(t *testing.T) {
+2
View File
@@ -110,6 +110,8 @@ You must have the certificate `.key` and `.crt` files in your working directory
Coder uses a PostgreSQL database to store users, workspace metadata, and other deployment information.
Use `CODER_PG_CONNECTION_URL` to set the database that Coder connects to.
If unset, PostgreSQL binaries will be downloaded from Maven (<https://repo1.maven.org/maven2>) and store all data in the config root.
The built-in database uses PostgreSQL 13.
If its data directory exists but `PG_VERSION` is missing or does not identify version 13, Coder refuses to start and leaves the data unchanged.
> [!NOTE]
> Postgres 13 is the minimum supported version.
+4
View File
@@ -21,6 +21,7 @@ import (
"golang.org/x/xerrors"
"cdr.dev/slog/v3"
"github.com/coder/coder/v2/cli/config"
)
const trackingDDL = `
@@ -60,6 +61,9 @@ func recoverDB(ctx context.Context, logger slog.Logger, cfg *devConfig) error {
}
return nil
}
if err := config.ValidateBuiltinPostgresVersion(pgDir); err != nil {
return err
}
stopPG, err := startTempPostgresSetURL(ctx, logger, cfg, &pgURL)
if err != nil {
return xerrors.Errorf(