Skip to content

Open-source AI teammates in Slack, Teams, Discord, Telegram and Mattermost. Self-host it, with any agent harness and any model.

test(config): pin down what a CA bundle does to the connection

Petr Bauch72796c46a3f0
diff --git a/core/tests/switch_core/test_config_db_ssl.py b/core/tests/switch_core/test_config_db_ssl.py
index 0f18c7158..3e2fb1d34 100644
--- a/core/tests/switch_core/test_config_db_ssl.py
+++ b/core/tests/switch_core/test_config_db_ssl.py
@@ -1,4 +1,12 @@
+import datetime
+import ssl
+from pathlib import Path
+
import pytest
+from cryptography import x509
+from cryptography.hazmat.primitives import hashes, serialization
+from cryptography.hazmat.primitives.asymmetric import ec
+from cryptography.x509.oid import NameOID
from switch_core.config import SwitchConfig
@@ -37,3 +45,59 @@ def test_non_disable_ssl_mode_forwards_ssl_connect_arg(mode: str) -> None:
def test_invalid_ssl_mode_raises() -> None:
with pytest.raises(ValueError, match="DB_SSL_MODE"):
_config(db_ssl_mode="bogus")
+
+
+def _ca_bundle(tmp_path: Path) -> str:
+ """A throwaway CA, standing in for the one a managed database is signed by."""
+ key = ec.generate_private_key(ec.SECP256R1())
+ name = x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, "Test Root CA")])
+ now = datetime.datetime.now(datetime.UTC)
+ certificate = (
+ x509.CertificateBuilder()
+ .subject_name(name)
+ .issuer_name(name)
+ .public_key(key.public_key())
+ .serial_number(x509.random_serial_number())
+ .not_valid_before(now - datetime.timedelta(minutes=5))
+ .not_valid_after(now + datetime.timedelta(days=1))
+ .add_extension(x509.BasicConstraints(ca=True, path_length=None), critical=True)
+ .sign(key, hashes.SHA256())
+ )
+ path = tmp_path / "ca.pem"
+ path.write_bytes(certificate.public_bytes(serialization.Encoding.PEM))
+ return str(path)
+
+
+def test_verify_full_checks_the_hostname_against_the_given_bundle(
+ tmp_path: Path,
+) -> None:
+ config = _config(db_ssl_mode="verify-full", db_ssl_root_cert=_ca_bundle(tmp_path))
+
+ context = config.db_connect_args["ssl"]
+
+ assert isinstance(context, ssl.SSLContext)
+ assert context.verify_mode == ssl.CERT_REQUIRED
+ assert context.check_hostname is True
+
+
+def test_verify_ca_verifies_the_issuer_but_not_the_hostname(tmp_path: Path) -> None:
+ """The difference that lets a deployment front the database with its own name."""
+ config = _config(db_ssl_mode="verify-ca", db_ssl_root_cert=_ca_bundle(tmp_path))
+
+ context = config.db_connect_args["ssl"]
+
+ assert isinstance(context, ssl.SSLContext)
+ assert context.verify_mode == ssl.CERT_REQUIRED
+ assert context.check_hostname is False
+
+
+def test_a_bundle_under_a_mode_that_would_ignore_it_raises(tmp_path: Path) -> None:
+ with pytest.raises(ValueError, match="DB_SSL_ROOT_CERT"):
+ _config(db_ssl_mode="require", db_ssl_root_cert=_ca_bundle(tmp_path))
+
+
+def test_a_bundle_that_is_not_there_raises(tmp_path: Path) -> None:
+ with pytest.raises(ValueError, match="is not a file"):
+ _config(
+ db_ssl_mode="verify-full", db_ssl_root_cert=str(tmp_path / "absent.pem")
+ )
diff --git a/docs/old/rds-migration.md b/docs/old/rds-migration.md
index cd12bec90..d6cf765fe 100644
--- a/docs/old/rds-migration.md
+++ b/docs/old/rds-migration.md
@@ -160,8 +160,10 @@ For a database of this size with an agreed downtime window, `pg_dump` /
`pg_restore` is both the simplest path and the one AWS recommends for a
homogeneous, whole-database migration. Logical replication (self-managed
publisher → RDS subscriber) is supported and is the fallback if the window
-turns out to be unacceptable — it does not carry sequences or DDL, so it trades
-a shorter outage for a fiddlier cutover.
+turns out to be unacceptable — it does not carry DDL, so it trades a shorter
+outage for a fiddlier cutover. The usual reason to fear it does not apply here:
+the schema has no sequences at all, every id being generated by the application,
+so there is nothing to reset behind a replicated cutover.
**Before the window**
@@ -181,14 +183,25 @@ a shorter outage for a fiddlier cutover.
6. Scale switch-core to zero. Writes must stop before the dump starts — a dump
taken from a live database is consistent but stale by the time it lands, and
the difference is lost messages.
-7. `pg_dump -Fc` each database; `pg_restore -j` into RDS. Restoring as a
- non-superuser can trip over ownership from the source; `--no-owner
- --no-privileges` and re-granting is the usual answer.
-8. Verify before switching anything: row counts per table on both sides, and
- that the notify trigger and function survived the restore
+7. `pg_dump -Fc` each database, then restore with
+
+ ```
+ pg_restore -j 4 --no-owner --no-privileges --exit-on-error -d switch switch.dump
+ ```
+
+ All three flags earn their place. Without the first two the restore tries to
+ `ALTER ... OWNER TO` the source's owner and every such statement fails,
+ because the RDS master user is not a superuser and cannot grant away
+ ownership it does not hold. Without `--exit-on-error` those failures are
+ *reported and ignored*: the tables and rows arrive, the summary says "errors
+ ignored on restore: N" among the output, and it is entirely possible to read
+ past it. The exit code is 1 either way, so trust the exit code over the
+ screen.
+8. Verify before switching anything, on both sides: row counts per table,
+ number of indexes, foreign keys and triggers, the `alembic_version` row, and
+ that the notify function and its trigger are there
(`\df switch_notify_message`, `\dS+ messages`). The trigger is what delivery
- depends on and it is exactly the sort of thing a restore with the wrong flags
- drops.
+ depends on and it is exactly what a restore with the wrong flags drops.
9. Point the chart at RDS (`postgresql.mode: existing`, `external.host`,
`sslMode`, the CA bundle) and deploy. Leave the old StatefulSet and its PVC
in place — that is the rollback.
@@ -208,7 +221,42 @@ after the switch — which is why step 10 comes before announcing success.
untested backup is a belief, not a backup, and proving it is the reason for
the whole exercise.
-## 8. Open questions
+## 8. What has been rehearsed, and what has not
+
+The cutover was walked through locally before any of it was proposed for real:
+two throwaway Postgres 16 containers, one standing in for the current
+in-cluster database and one for RDS — TLS on, and owned by a role with
+`CREATEDB`/`CREATEROLE` but deliberately **not** superuser, which is the shape
+of the RDS master user. A migrated schema with 500 messages and a binary blob
+was dumped from the first and restored into the second.
+
+Confirmed:
+
+- The restore carries everything that matters — 39 tables, 68 indexes, 63
+ foreign keys, the notify function and its trigger, the `alembic_version` row,
+ and a `bytea` blob byte-identical by checksum.
+- The ownership failure in step 7 is real: a restore without `--no-owner
+ --no-privileges` fails 40 statements as a non-superuser, and reports them as
+ ignored. With the flags it is clean.
+- `verify-full` connects against a server whose certificate is signed by the
+ supplied bundle, and refuses one signed by an unrelated CA.
+- **The hostname trap is real.** With a certificate naming only the server's
+ own hostname, connecting by any other name fails with `Hostname mismatch`
+ under `verify-full` and succeeds under `verify-ca`. That is exactly the
+ choice §5 describes, so make it deliberately.
+- Delivery survives the move: with the app connecting over `verify-full` to the
+ restored database, an insert into `messages` reached a live `LISTEN`
+ subscriber. Trigger, listener and TLS working together, which is the thing
+ worth proving.
+- Alembic connects over `verify-full` too — a separate code path from the
+ application engine, and the one the migration Job uses.
+- A `DB_SSL_ROOT_CERT` pointing nowhere is refused at startup, by name.
+
+Not covered, and only an instance can settle it: RDS Proxy pinning, failover
+behaviour, `rds.force_ssl`, and how long the dump and restore actually take at
+production size. Step 4 is still required.
+
+## 9. Open questions
- Which environments move, and in what order? Doing the lowest-traffic one
first is how the runbook gets debugged cheaply.