token usage tightened with revocation

This commit is contained in:
2026-08-26 18:17:55 +02:00
parent 1a24d21d0a
commit 4049a197b9
13 changed files with 288 additions and 54 deletions
+24 -2
View File
@@ -13,7 +13,7 @@ from backend.app.services.auth_service import authenticate_user, find_user
from backend.app.services.email_service import send_password_reset_email, smtp_configured
from backend.app.services.email_verification import verify_email
from backend.app.services.password_reset import create_reset_token, reset_password
from backend.app.services.token_service import issue_token, revoke_token, validate_token
from backend.app.services.token_service import issue_token, revoke_token, rotate_refresh_token, validate_token
from backend.app.services.otp_service import verify_code
from backend.app.services.secret_store import decrypt_secret
from backend.app.services.email_addresses import verify_user_email_address
@@ -28,6 +28,12 @@ class LoginRequest(BaseModel):
email: str
password: str
otp: str | None = None
device_id: str | None = None
class RefreshTokenRequest(BaseModel):
refresh_token: str
device_id: str | None = None
class PasswordResetRequest(BaseModel):
@@ -62,16 +68,32 @@ def login(payload: LoginRequest, request: Request):
raise HTTPException(status_code=401, detail='One-time password required or invalid')
clear_login_failures(ip_address, email)
token_data = issue_token(user['id'], user['username'])
token_data = issue_token(user['id'], user['username'], payload.device_id)
return {
'access_token': token_data['access_token'],
'token_type': 'bearer',
'expires_at': token_data['expires_at'],
'refresh_token': token_data['refresh_token'],
'device_id': token_data['device_id'],
'user': {'id': user['id'], 'username': user['username'], 'email': user['email'], 'otp_enabled': bool(user['otp_enabled'])}
}
@router.post('/refresh')
def refresh_token_endpoint(payload: RefreshTokenRequest):
rotated = rotate_refresh_token(payload.refresh_token, payload.device_id)
if rotated is None:
raise HTTPException(status_code=401, detail='Refresh token is invalid, expired, or bound to another device')
return {
'access_token': rotated['access_token'],
'token_type': 'bearer',
'expires_at': rotated['expires_at'],
'refresh_token': rotated['refresh_token'],
'device_id': rotated['device_id'],
'user': {'id': rotated['user_id'], 'username': rotated['username']},
}
@router.get('/verify-email')
def verify_email_address(token: str):
if not verify_email(token):
+2 -1
View File
@@ -25,7 +25,8 @@ class Settings:
database_url: str = os.getenv('LINKLOG_DATABASE_URL', f'sqlite:///{DB_PATH}')
secret_key: str = os.getenv('LINKLOG_SECRET_KEY', 'dev-secret-key-change-me')
data_encryption_key: str = os.getenv('LINKLOG_DATA_ENCRYPTION_KEY', '')
token_expiry_days: int = int(os.getenv('LINKLOG_TOKEN_EXPIRY_DAYS', '30'))
token_expiry_minutes: int = int(os.getenv('LINKLOG_TOKEN_EXPIRY_MINUTES', '15'))
refresh_token_expiry_days: int = int(os.getenv('LINKLOG_REFRESH_TOKEN_EXPIRY_DAYS', '30'))
public_url: str = normalize_public_url(os.getenv('LINKLOG_PUBLIC_URL', 'http://localhost:8000'))
smtp_host: str = os.getenv('LINKLOG_SMTP_HOST', '')
smtp_port: int = int(os.getenv('LINKLOG_SMTP_PORT', '587'))
+6
View File
@@ -226,6 +226,12 @@ CREATE TABLE IF NOT EXISTS pending_primary_email_changes (
'''),
(14, '''
DROP TABLE IF EXISTS pending_primary_email_changes;
'''),
(15, '''
ALTER TABLE tokens ADD COLUMN device_id TEXT;
ALTER TABLE tokens ADD COLUMN token_family_id TEXT;
CREATE INDEX IF NOT EXISTS idx_tokens_device_id ON tokens(device_id);
CREATE INDEX IF NOT EXISTS idx_tokens_family_id ON tokens(token_family_id);
''')
]
+86 -21
View File
@@ -1,7 +1,7 @@
## Copyright © 2026 Olaf Kolkman
## SPDX-License-Identifier: GPL-3.0-or-later
from datetime import datetime, timezone
from datetime import datetime, timedelta, timezone
from hashlib import sha256
from uuid import uuid4
@@ -13,29 +13,42 @@ def hash_token(token: str) -> str:
return sha256(token.encode('utf-8')).hexdigest()
def issue_token(user_id: str, username: str) -> dict:
token = f'token-{username}-{uuid4().hex}'
expires_at = datetime.now(timezone.utc).replace(microsecond=0)
expires_at = expires_at.replace(day=expires_at.day + 30 if False else expires_at.day)
# one-month expiry, held as a configured value in settings
from datetime import timedelta
expires_at = datetime.now(timezone.utc) + timedelta(days=settings.token_expiry_days)
def _token_expiry() -> datetime:
return datetime.now(timezone.utc) + timedelta(minutes=settings.token_expiry_minutes)
def _persist_token(conn, user_id: str, token: str, token_type: str, expires_at: datetime,
device_id: str, family_id: str) -> None:
conn.execute(
'''
INSERT INTO tokens
(id, user_id, token_hash, token_type, expires_at, created_at, revoked, device_id, token_family_id)
VALUES (?, ?, ?, ?, ?, CURRENT_TIMESTAMP, 0, ?, ?)
''',
(str(uuid4()), user_id, hash_token(token), token_type, expires_at.isoformat(), device_id, family_id),
)
def issue_token(user_id: str, username: str, device_id: str | None = None) -> dict:
device_id = device_id.strip() if device_id and device_id.strip() else f'device-{uuid4().hex}'
family_id = str(uuid4())
access_token = f'token-{username}-{uuid4().hex}'
refresh_token = f'refresh-{username}-{uuid4().hex}'
access_expires_at = _token_expiry()
refresh_expires_at = datetime.now(timezone.utc) + timedelta(days=settings.refresh_token_expiry_days)
with get_connection() as conn:
conn.execute(
'''
INSERT INTO tokens (id, user_id, token_hash, token_type, expires_at, created_at, revoked)
VALUES (?, ?, ?, 'access', ?, CURRENT_TIMESTAMP, 0)
''',
(str(uuid4()), user_id, hash_token(token), expires_at.isoformat())
)
_persist_token(conn, user_id, access_token, 'access', access_expires_at, device_id, family_id)
_persist_token(conn, user_id, refresh_token, 'refresh', refresh_expires_at, device_id, family_id)
conn.commit()
return {
'access_token': token,
'access_token': access_token,
'token_type': 'bearer',
'expires_at': expires_at.isoformat(),
'refresh_token': f'refresh-{uuid4().hex}',
'expires_at': access_expires_at.isoformat(),
'refresh_token': refresh_token,
'device_id': device_id,
'token_family_id': family_id,
}
@@ -45,7 +58,7 @@ def validate_token(token: str) -> dict | None:
row = conn.execute(
'''
SELECT * FROM tokens
WHERE token_hash = ? AND revoked = 0 AND expires_at > ?
WHERE token_hash = ? AND token_type = 'access' AND revoked = 0 AND expires_at > ?
''',
(token_hash, datetime.now(timezone.utc).isoformat()),
).fetchone()
@@ -54,12 +67,64 @@ def validate_token(token: str) -> dict | None:
return dict(row)
def validate_refresh_token(token: str, device_id: str | None = None) -> dict | None:
with get_connection() as conn:
row = conn.execute(
'''
SELECT * FROM tokens
WHERE token_hash = ? AND token_type = 'refresh' AND revoked = 0 AND expires_at > ?
AND (? IS NULL OR device_id = ?)
''',
(hash_token(token), datetime.now(timezone.utc).isoformat(), device_id, device_id),
).fetchone()
return dict(row) if row else None
def rotate_refresh_token(refresh_token: str, device_id: str | None = None) -> dict | None:
current = validate_refresh_token(refresh_token, device_id)
with get_connection() as conn:
if current is None:
row = conn.execute(
'SELECT token_family_id FROM tokens WHERE token_hash = ? AND token_type = ? AND token_family_id IS NOT NULL',
(hash_token(refresh_token), 'refresh'),
).fetchone()
if row:
conn.execute('UPDATE tokens SET revoked = 1 WHERE token_family_id = ?', (row['token_family_id'],))
conn.commit()
return None
user = conn.execute('SELECT username FROM users WHERE id = ?', (current['user_id'],)).fetchone()
if user is None:
return None
family_id = current['token_family_id']
conn.execute('UPDATE tokens SET revoked = 1 WHERE token_family_id = ?', (family_id,))
new_access = f'token-{user["username"]}-{uuid4().hex}'
new_refresh = f'refresh-{user["username"]}-{uuid4().hex}'
access_expires_at = _token_expiry()
refresh_expires_at = datetime.now(timezone.utc) + timedelta(days=settings.refresh_token_expiry_days)
_persist_token(conn, current['user_id'], new_access, 'access', access_expires_at, current['device_id'], family_id)
_persist_token(conn, current['user_id'], new_refresh, 'refresh', refresh_expires_at, current['device_id'], family_id)
conn.commit()
return {
'access_token': new_access,
'token_type': 'bearer',
'expires_at': access_expires_at.isoformat(),
'refresh_token': new_refresh,
'device_id': current['device_id'],
'user_id': current['user_id'],
'username': user['username'],
}
def revoke_token(token: str) -> bool:
token_hash = hash_token(token)
with get_connection() as conn:
cursor = conn.execute(
'UPDATE tokens SET revoked = 1 WHERE token_hash = ?',
(token_hash,),
'''UPDATE tokens SET revoked = 1
WHERE token_hash = ? OR token_family_id = (
SELECT token_family_id FROM tokens WHERE token_hash = ?
)''',
(token_hash, token_hash),
)
conn.commit()
return cursor.rowcount > 0
+31
View File
@@ -68,6 +68,37 @@ def test_login_rate_limit_locks_out_after_five_failures_and_resets_on_success():
assert valid.status_code == 200
def test_refresh_token_rotates_and_reuse_revokes_family():
device_id = f'device-{uuid4().hex}'
login = client.post('/api/auth/login', json={
'email': 'alice@example.com',
'password': 'secret123',
'device_id': device_id,
})
assert login.status_code == 200
first = login.json()
rotated = client.post('/api/auth/refresh', json={
'refresh_token': first['refresh_token'],
'device_id': device_id,
})
assert rotated.status_code == 200
second = rotated.json()
assert second['refresh_token'] != first['refresh_token']
assert client.get('/api/auth/me', headers={'Authorization': f"Bearer {second['access_token']}"}).status_code == 200
reused = client.post('/api/auth/refresh', json={
'refresh_token': first['refresh_token'],
'device_id': device_id,
})
assert reused.status_code == 401
family_revoked = client.post('/api/auth/refresh', json={
'refresh_token': second['refresh_token'],
'device_id': device_id,
})
assert family_revoked.status_code == 401
def test_password_hashes_are_salted_and_legacy_hashes_upgrade_on_login():
from hashlib import sha256
from backend.app.database import hash_password
+2 -2
View File
@@ -10,7 +10,7 @@ def test_database_migrations_are_versioned_and_idempotent():
connection = sqlite3.connect(':memory:')
apply_migrations(connection)
assert get_schema_version(connection) == 14
assert get_schema_version(connection) == 15
tables = {
row[0]
for row in connection.execute(
@@ -27,6 +27,6 @@ def test_database_migrations_are_versioned_and_idempotent():
assert set(DEFAULT_TAGS) <= seeded_tags
apply_migrations(connection)
assert get_schema_version(connection) == 14
assert get_schema_version(connection) == 15
connection.close()