Repository navigation
Harden token lifecycle: shared JWT validation, persisted revocation, hashed API keys #1459
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
+971
−82
Merged
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
bcbf014
Harden token lifecycle: shared JWT validation, persisted revocation, …
Tim020 9942f2a
Keep existing API keys working: lazy bcrypt-to-SHA-256 upgrade with r…
Tim020 f73adec
Merge origin/dev into feature/security-token-lifecycle
Tim020 30cc1a5
Remove absolute session cap (auth_time) from token lifecycle changes
Tim020 51cf770
Address review: fail-safe revocation load, verified-only revoke, boun…
Tim020 0411384
Guard release of the rate-limit reservation when it already aged out
Tim020 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
44 changes: 44 additions & 0 deletions
44
server/alembic_config/versions/d91e929f2e32_persist_revoked_tokens.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,44 @@ | ||
| """Persist revoked tokens | ||
|
|
||
| Revision ID: d91e929f2e32 | ||
| Revises: 0b3fa405e05b | ||
| Create Date: 2026-10-19 21:17:12.234277 | ||
|
|
||
| """ | ||
|
|
||
| from typing import Sequence | ||
|
|
||
| import sqlalchemy as sa | ||
| from alembic import op | ||
|
|
||
|
|
||
| # revision identifiers, used by Alembic. | ||
| revision: str = "d91e929f2e32" | ||
| down_revision: str | None = "0b3fa405e05b" | ||
| branch_labels: str | Sequence[str] | None = None | ||
| depends_on: str | Sequence[str] | None = None | ||
|
|
||
|
|
||
| def upgrade() -> None: | ||
| # ### commands auto generated by Alembic - please adjust! ### | ||
| op.create_table( | ||
| "revoked_token", | ||
| sa.Column("jti", sa.String(), nullable=False), | ||
| sa.Column("expires_at", sa.Integer(), nullable=False), | ||
| sa.PrimaryKeyConstraint("jti", name=op.f("pk_revoked_token")), | ||
| ) | ||
| with op.batch_alter_table("revoked_token", schema=None) as batch_op: | ||
| batch_op.create_index( | ||
| batch_op.f("ix_revoked_token_expires_at"), ["expires_at"], unique=False | ||
| ) | ||
|
|
||
| # ### end Alembic commands ### | ||
|
|
||
|
|
||
| def downgrade() -> None: | ||
| # ### commands auto generated by Alembic - please adjust! ### | ||
| with op.batch_alter_table("revoked_token", schema=None) as batch_op: | ||
| batch_op.drop_index(batch_op.f("ix_revoked_token_expires_at")) | ||
|
|
||
| op.drop_table("revoked_token") | ||
| # ### end Alembic commands ### |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Empty file.
Empty file.
60 changes: 60 additions & 0 deletions
60
server/test/alembic_config/versions/test_persist_revoked_tokens.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,60 @@ | ||
| import importlib.util | ||
| import os | ||
| import tempfile | ||
| from unittest import TestCase | ||
|
|
||
| import sqlalchemy as sa | ||
| from alembic.migration import MigrationContext | ||
| from alembic.operations import Operations | ||
|
|
||
|
|
||
| VERSIONS_DIR = os.path.join( | ||
| os.path.dirname(__file__), "..", "..", "..", "alembic_config", "versions" | ||
| ) | ||
|
|
||
|
|
||
| def _load_migration(): | ||
| name = next(f for f in os.listdir(VERSIONS_DIR) if f.startswith("d91e929f2e32")) | ||
| spec = importlib.util.spec_from_file_location( | ||
| "persist_revoked_tokens", os.path.join(VERSIONS_DIR, name) | ||
| ) | ||
| module = importlib.util.module_from_spec(spec) | ||
| spec.loader.exec_module(module) | ||
| return module | ||
|
|
||
|
|
||
| class TestPersistRevokedTokensMigration(TestCase): | ||
| def test_upgrade_creates_table_and_leaves_api_tokens_untouched(self): | ||
| module = _load_migration() | ||
| with tempfile.TemporaryDirectory() as tmp: | ||
| engine = sa.create_engine(f"sqlite:///{os.path.join(tmp, 'db.sqlite')}") | ||
| with engine.begin() as conn: | ||
| conn.execute( | ||
| sa.text( | ||
| "CREATE TABLE user (id INTEGER PRIMARY KEY, api_token TEXT)" | ||
| ) | ||
| ) | ||
| conn.execute( | ||
| sa.text( | ||
| "INSERT INTO user (id, api_token) VALUES (1, '$2b$12$abc'), (2, NULL)" | ||
| ) | ||
| ) | ||
| with Operations.context(MigrationContext.configure(conn)): | ||
| module.upgrade() | ||
| tokens = conn.execute( | ||
| sa.text("SELECT api_token FROM user ORDER BY id") | ||
| ).all() | ||
| self.assertEqual([("$2b$12$abc",), (None,)], [tuple(r) for r in tokens]) | ||
| self.assertIn("revoked_token", sa.inspect(conn).get_table_names()) | ||
| engine.dispose() | ||
|
|
||
| def test_downgrade_drops_table(self): | ||
| module = _load_migration() | ||
| with tempfile.TemporaryDirectory() as tmp: | ||
| engine = sa.create_engine(f"sqlite:///{os.path.join(tmp, 'db.sqlite')}") | ||
| with engine.begin() as conn: | ||
| with Operations.context(MigrationContext.configure(conn)): | ||
| module.upgrade() | ||
| module.downgrade() | ||
| self.assertNotIn("revoked_token", sa.inspect(conn).get_table_names()) | ||
| engine.dispose() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,54 @@ | ||
| import hashlib | ||
|
|
||
| import bcrypt | ||
| from tornado import escape | ||
|
|
||
| from models.user import User | ||
| from test.conftest import DigiScriptTestCase | ||
| from test.helpers.auth_fixtures import craft_token, make_user | ||
|
|
||
|
|
||
| class TestApiTokenV1API(DigiScriptTestCase): | ||
| def _auth(self, user_id: int) -> dict: | ||
| return {"Authorization": f"Bearer {craft_token(self._app, user_id)}"} | ||
|
|
||
| def _post(self, path: str, user_id: int): | ||
| return self.fetch( | ||
| path, | ||
| method="POST", | ||
| body=escape.json_encode({}), | ||
| headers=self._auth(user_id), | ||
| ) | ||
|
|
||
| def _whoami(self, key: str): | ||
| return self.fetch("/api/v1/auth", headers={"X-API-Key": key}) | ||
|
|
||
| def test_generated_key_is_stored_as_sha256_and_authenticates(self): | ||
| user_id = make_user(self._app) | ||
| response = self._post("/api/v1/auth/api-token/generate", user_id) | ||
| self.assertEqual(200, response.code) | ||
| key = escape.json_decode(response.body)["api_token"] | ||
| with self._app.get_db().sessionmaker() as session: | ||
| stored = session.get(User, user_id).api_token | ||
| self.assertEqual(hashlib.sha256(key.encode()).hexdigest(), stored) | ||
| self.assertEqual(200, self._whoami(key).code) | ||
|
|
||
| def test_revoked_key_stops_authenticating(self): | ||
| user_id = make_user(self._app) | ||
| key = escape.json_decode( | ||
| self._post("/api/v1/auth/api-token/generate", user_id).body | ||
| )["api_token"] | ||
| self.assertEqual(200, self._post("/api/v1/auth/api-token/revoke", user_id).code) | ||
| self.assertEqual(401, self._whoami(key).code) | ||
|
|
||
| def test_regenerating_replaces_a_legacy_key(self): | ||
| user_id = make_user(self._app) | ||
| with self._app.get_db().sessionmaker() as session: | ||
| session.get(User, user_id).api_token = bcrypt.hashpw( | ||
| b"old-legacy-key", bcrypt.gensalt(4) | ||
| ).decode() | ||
| session.commit() | ||
| response = self._post("/api/v1/auth/api-token/generate", user_id) | ||
| key = escape.json_decode(response.body)["api_token"] | ||
| self.assertEqual(200, self._whoami(key).code) | ||
| self.assertEqual(401, self._whoami("old-legacy-key").code) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,51 @@ | ||
| import hashlib | ||
|
|
||
| from tornado import escape | ||
|
|
||
| from models.user import User | ||
| from test.conftest import DigiScriptTestCase | ||
| from test.helpers.auth_fixtures import craft_token, make_user | ||
|
|
||
|
|
||
| class TestUsersTokenV2API(DigiScriptTestCase): | ||
| def _headers(self, user_id: int) -> dict: | ||
| return {"Authorization": f"Bearer {craft_token(self._app, user_id)}"} | ||
|
|
||
| def _whoami(self, key: str): | ||
| return self.fetch("/api/v1/auth", headers={"X-API-Key": key}) | ||
|
|
||
| def test_generated_key_is_stored_as_sha256_and_authenticates(self): | ||
| user_id = make_user(self._app) | ||
| response = self.fetch( | ||
| "/api/v2/users/token", | ||
| method="POST", | ||
| body=escape.json_encode({}), | ||
| headers=self._headers(user_id), | ||
| ) | ||
| self.assertEqual(200, response.code) | ||
| key = escape.json_decode(response.body)["api_token"] | ||
| with self._app.get_db().sessionmaker() as session: | ||
| stored = session.get(User, user_id).api_token | ||
| self.assertEqual(hashlib.sha256(key.encode()).hexdigest(), stored) | ||
|
Tim020 marked this conversation as resolved.
Dismissed
|
||
| self.assertEqual(200, self._whoami(key).code) | ||
|
|
||
| def test_has_token_reflects_state_and_delete_revokes_key(self): | ||
| user_id = make_user(self._app) | ||
| headers = self._headers(user_id) | ||
| has = lambda: escape.json_decode( # noqa: E731 | ||
| self.fetch("/api/v2/users/token", headers=headers).body | ||
| )["has_token"] | ||
| self.assertFalse(has()) | ||
| key = escape.json_decode( | ||
| self.fetch( | ||
| "/api/v2/users/token", | ||
| method="POST", | ||
| body=escape.json_encode({}), | ||
| headers=headers, | ||
| ).body | ||
| )["api_token"] | ||
| self.assertTrue(has()) | ||
| response = self.fetch("/api/v2/users/token", method="DELETE", headers=headers) | ||
| self.assertEqual(200, response.code) | ||
| self.assertFalse(has()) | ||
| self.assertEqual(401, self._whoami(key).code) | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.