TASK-011: Remove session token prefix from log output

Replace sensitive token fragments in structured logs with:
- login(): Use session_id=session.id (database row ID) instead of token_prefix
- logout(): Use token_hash (SHA256 one-way hash, first 12 chars) instead of token_prefix

This prevents partial token material leakage into log aggregation systems while
maintaining useful session correlation via hashed tokens or database IDs.

Also updated Backend-Development.md to clarify logging conventions for
sensitive data handling.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
This commit is contained in:
2026-04-26 13:19:26 +02:00
parent 8698b89f6a
commit 5b24a9c142
3 changed files with 15 additions and 33 deletions

View File

@@ -246,10 +246,13 @@ async def lifespan(app: FastAPI) -> AsyncGenerator[None]:
- Use **structlog** for every log message.
- Bind contextual key-value pairs — never format strings manually.
- Log levels: `debug` for development detail, `info` for operational events, `warning` for recoverable issues, `error` for failures, `critical` for fatal problems.
- Never log sensitive data (passwords, tokens, session IDs).
- **Never log sensitive data** (passwords, tokens, session tokens, raw credentials, private keys).
- For session correlation without leaking token material, use a one-way hash fragment: `hashlib.sha256(token.encode()).hexdigest()[:12]`.
- Use numeric database IDs for entity correlation instead of raw identifiers: `session_id=session.id` instead of `token=session.token`.
```python
import structlog
import hashlib
log: structlog.stdlib.BoundLogger = structlog.get_logger()
@@ -261,6 +264,12 @@ async def ban_ip(ip: str, jail: str) -> None:
except BanError as exc:
log.error("ban_failed", ip=ip, jail=jail, error=str(exc))
raise
async def logout_session(db: aiosqlite.Connection, token: str) -> None:
# Use a one-way hash for token correlation in logs
token_hash = hashlib.sha256(token.encode()).hexdigest()[:12]
await session_repo.delete_session(db, token)
log.info("session_terminated", token_hash=token_hash)
```
---