Files
stackpilot/backend/tests/test_schema_migration.py
menzeljandClaude Opus 5 41a21b5a25
CI / check (push) Successful in 7m7s
CI / build-and-push (push) Successful in 1m44s
Make tokens revocable and move the refresh token out of localStorage (0.46.0)
F5 — A token was valid until it expired, full stop. Resetting a compromised
account's password changed nothing for whoever held its tokens (up to 30 days
for a refresh token), demoting or disabling an account only took effect once
the same clock ran out, and logout was purely client-side.

Every account now has a token_version, every token is minted carrying it, and
every request compares the two. Bumping it is the revoke switch, pulled on the
three changes that alter what an account may do: password, role, active flag.
"Sign out everywhere" in the user menu bumps your own. Plain "Sign out" only
drops the cookie, because signing out on your phone should not kill your
desktop session.

The refresh token left localStorage for an httpOnly cookie (SameSite=Lax,
scoped to /api/auth), and the access token is now held in memory only. A
successful XSS can still act inside the open page but can no longer walk off
with 30 days of access. The cookie is marked Secure only when the request
arrived over HTTPS — request.url.scheme is trustworthy since the F4 fix — so a
plain-HTTP homelab keeps working. Any refresh token an older build left in
localStorage is deleted on first load. Scripted clients that cannot hold a
cookie can still ask for it in the body with ?in_body=true.

F9 comes with it, as predicted: the WebSocket helpers read the role off the
live user instead of the token's claim. /ws/exec is root-equivalent on the
host, and a token minted while the account was an admin stayed syntactically
valid after a demotion.

The sharp edge was the migration, not the feature. _ensure_model_columns emits
ADD COLUMN without a DEFAULT, so SQLite would have filled token_version with
NULL on every existing install, every version check would have failed against
it, and the upgrade would have locked out every user everywhere. The helper now
renders NOT NULL DEFAULT <literal> for scalar defaults; test_schema_migration
builds a genuinely old-shaped user table and asserts the backfill. The version
comparison also tolerates NULL as 1, so a database migrated by some other route
still works.

Writing that test surfaced an undocumented precondition: _ensure_model_columns
does nothing unless `models` has been imported, since SQLModel.metadata is
empty until then. It holds in production because init_db imports first; now it
says so.

The authorization matrix did its job — adding two auth routes failed the suite
until both were classified, which is exactly the review moment it exists for.

30 new tests (698 total). Upgrading signs everyone out once.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Dk43rmEeRfYi5wsLDbmfyG
2026-08-31 13:31:00 +02:00

129 lines
4.3 KiB
Python

"""Adding a column to a database that already exists.
There is no Alembic here: ``_ensure_model_columns`` diffs each model against
the live table and ``ADD COLUMN``s what is missing. That covers the only kind
of change made so far, but it has a sharp edge — SQLite fills an added column
with NULL unless the statement carries a DEFAULT.
``User.token_version`` is where that edge would have cut: existing rows would
have come back NULL, every token's version check would have failed against it,
and the upgrade would have signed out every user on every install. So the
helper now renders a DEFAULT for scalar defaults, and this file pins that
behaviour against a genuinely old-shaped table.
"""
from __future__ import annotations
import pytest
from sqlalchemy import create_engine, inspect, text
@pytest.fixture
def legacy_db(tmp_path, monkeypatch):
"""A database whose ``user`` table predates ``token_version``."""
import database
import models # noqa: F401 — populates SQLModel.metadata
db_file = tmp_path / "legacy.db"
engine = create_engine(f"sqlite:///{db_file}")
with engine.begin() as conn:
conn.execute(
text(
"""
CREATE TABLE user (
id INTEGER NOT NULL PRIMARY KEY,
username VARCHAR NOT NULL,
hashed_password VARCHAR NOT NULL,
role VARCHAR NOT NULL,
is_active BOOLEAN NOT NULL,
created_at DATETIME NOT NULL
)
"""
)
)
conn.execute(
text(
"INSERT INTO user (id, username, hashed_password, role, is_active,"
" created_at) VALUES (1, 'olduser', 'x', 'admin', 1, '2026-01-01')"
)
)
monkeypatch.setattr(database, "engine", engine)
return engine
def test_the_new_column_is_added_and_backfilled(legacy_db):
import database
assert "token_version" not in {c["name"] for c in inspect(legacy_db).get_columns("user")}
database._ensure_model_columns()
columns = {c["name"]: c for c in inspect(legacy_db).get_columns("user")}
assert "token_version" in columns
with legacy_db.begin() as conn:
value = conn.execute(text("SELECT token_version FROM user WHERE id = 1")).scalar()
assert value == 1, "existing rows must be backfilled, not left NULL"
def test_the_existing_row_survives_untouched(legacy_db):
import database
database._ensure_model_columns()
with legacy_db.begin() as conn:
row = conn.execute(text("SELECT username, role FROM user WHERE id = 1")).one()
assert row.username == "olduser"
assert row.role == "admin"
def test_running_it_twice_changes_nothing(legacy_db):
import database
database._ensure_model_columns()
database._ensure_model_columns() # must not raise "duplicate column name"
with legacy_db.begin() as conn:
assert conn.execute(text("SELECT token_version FROM user")).scalar() == 1
@pytest.mark.parametrize(
"value,expected",
[
(1, "1"),
(0, "0"),
(True, "1"),
(False, "0"),
("user", "'user'"),
("it's", "'it''s'"), # quotes escaped, not injected
],
)
def test_default_literals_are_rendered_and_escaped(value, expected):
from sqlalchemy import Column, Integer
import database
column = Column("c", Integer, default=value)
assert database._default_literal(column) == expected
def test_callable_defaults_have_no_literal():
"""``default_factory`` (a timestamp, say) has no fixed value to backfill —
such a column is added nullable, as before."""
from sqlalchemy import Column, DateTime
import database
from models.user import User
assert database._default_literal(Column("c", DateTime, default=lambda: 1)) is None
assert database._default_literal(User.__table__.columns["created_at"]) is None
def test_the_live_schema_matches_the_models(db):
"""Belt and braces on the real database the rest of the suite uses."""
from sqlmodel import SQLModel
import database
inspector = inspect(database.engine)
for table_name, table in SQLModel.metadata.tables.items():
live = {c["name"] for c in inspector.get_columns(table_name)}
missing = {c.name for c in table.columns} - live
assert not missing, f"{table_name} is missing {missing}"