Files
lukasandClaude Opus 5.5 addb2232a1 Security hardening from the assessment; testing fixes
Security (ultimo-security-report.md):
- Security headers on every response, the app shell included: they lived at
  server level and nginx dropped them in any location with its own header.
  CSP, framing, nosniff, referrer, permissions (docker/nginx-security.conf).
- Plain HTTP forwarded by the reverse proxy is redirected to HTTPS; HSTS on
  HTTPS responses. server_tokens off.
- Cross-site state-changing /api requests refused (login CSRF), WebSocket too.
- Validation errors in the usual error shape, without the request model.
- New-password policy: max 128, common/own-address/repeated refused,
  breached-password check (HIBP k-anonymity, fails open).
- Message HTML: links keep only http(s)/mailto (sanitizer v6); the HTML
  endpoint carries its own no-script CSP.
- Outbound fetches pinned to the checked IP (DNS rebinding); external
  IMAP/SMTP servers re-checked before each connection; CGNAT and mapped
  addresses counted as non-public.

Fixes from testing:
- IDLE loop catches up before idling: mail that came while the worker was
  away no longer waits up to 10 minutes.
- Restore from Spam/Trash/Archive moves only the removed messages, not your
  reply in Sent.
- Narrow desktop list stacks sender/subject/snippet (subject was squeezed
  to nothing at the default width), with hover actions.
- Phone: wide emails scale to fit the screen.
- Singular forms ("1 message"); no zip button for a single attachment;
  app passwords no longer claim "never used" for mail apps.
- ruff format across the backend.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 22:08:06 +02:00

140 lines
4.6 KiB
Python

"""Saved searches CRUD — stored queries shown as virtual mailboxes (SPEC §12 M2)."""
from __future__ import annotations
import uuid
from collections.abc import AsyncIterator
from dataclasses import dataclass
import httpx
import pytest_asyncio
from httpx import ASGITransport
from sqlalchemy import delete
from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine
from sqlalchemy.pool import NullPool
from app.config import get_settings
from app.identity.passwords import hash_password
from app.identity.sessions import create_session
from app.main import create_app
from app.models import User
CSRF = "csrf"
@dataclass
class Ctx:
client: httpx.AsyncClient
user_id: uuid.UUID
def _hdr() -> dict[str, str]:
return {"X-CSRF": CSRF}
@pytest_asyncio.fixture
async def ctx() -> AsyncIterator[Ctx]:
engine = create_async_engine(get_settings().database_url, poolclass=NullPool)
sm = async_sessionmaker(engine, expire_on_commit=False)
session = sm()
user = User(handle=f"ss{uuid.uuid4().hex[:8]}@test.local", password_hash=hash_password("pw"))
session.add(user)
await session.commit()
token = await create_session(user.id, "pytest")
client = httpx.AsyncClient(
transport=ASGITransport(app=create_app()),
base_url="http://testserver",
cookies={"session": token, "csrf": CSRF},
)
try:
yield Ctx(client=client, user_id=user.id)
finally:
await client.aclose()
await session.execute(delete(User).where(User.id == user.id))
await session.commit()
await session.close()
await engine.dispose()
async def test_saved_search_crud_and_upsert(ctx: Ctx) -> None:
# Empty to start.
resp = await ctx.client.get("/api/saved-searches")
assert resp.status_code == 200
assert resp.json() == []
# Create.
resp = await ctx.client.post(
"/api/saved-searches",
json={"name": "Unread from boss", "query": "is:unread from:boss"},
headers=_hdr(),
)
assert resp.status_code == 200
created = resp.json()
assert created["name"] == "Unread from boss"
assert created["query"] == "is:unread from:boss"
assert created["pinned"] is True
sid = created["id"]
# It lists back.
resp = await ctx.client.get("/api/saved-searches")
assert [s["name"] for s in resp.json()] == ["Unread from boss"]
# Re-saving under the same name upserts (updates query, keeps a single row).
resp = await ctx.client.post(
"/api/saved-searches",
json={"name": "Unread from boss", "query": "is:unread from:ceo"},
headers=_hdr(),
)
assert resp.status_code == 200
assert resp.json()["id"] == sid # same row
assert resp.json()["query"] == "is:unread from:ceo"
rows = (await ctx.client.get("/api/saved-searches")).json()
assert len(rows) == 1 and rows[0]["query"] == "is:unread from:ceo"
# Delete.
resp = await ctx.client.delete(f"/api/saved-searches/{sid}", headers=_hdr())
assert resp.status_code == 200
assert (await ctx.client.get("/api/saved-searches")).json() == []
# Deleting a missing row 404s.
resp = await ctx.client.delete(f"/api/saved-searches/{uuid.uuid4()}", headers=_hdr())
assert resp.status_code == 404
async def test_saved_search_requires_csrf(ctx: Ctx) -> None:
# No CSRF header -> rejected (state-changing route).
resp = await ctx.client.post("/api/saved-searches", json={"name": "x", "query": "y"})
assert resp.status_code == 403
async def test_saved_search_is_per_user(ctx: Ctx) -> None:
await ctx.client.post(
"/api/saved-searches",
json={"name": "Mine", "query": "in:inbox"},
headers=_hdr(),
)
# A different user's client sees none of the above.
other = User(handle=f"ss{uuid.uuid4().hex[:8]}@test.local", password_hash=hash_password("pw"))
engine = create_async_engine(get_settings().database_url, poolclass=NullPool)
sm = async_sessionmaker(engine, expire_on_commit=False)
session = sm()
session.add(other)
await session.commit()
token = await create_session(other.id, "pytest")
try:
client = httpx.AsyncClient(
transport=ASGITransport(app=create_app()),
base_url="http://testserver",
cookies={"session": token, "csrf": CSRF},
)
try:
assert (await client.get("/api/saved-searches")).json() == []
finally:
await client.aclose()
finally:
await session.execute(delete(User).where(User.id == other.id))
await session.commit()
await session.close()
await engine.dispose()