From 65951488b7a1019c09dd91ffab5d297adab2a7c5 Mon Sep 17 00:00:00 2001 From: root Date: Thu, 22 Oct 2026 15:16:05 +0000 Subject: [PATCH] Part B: OpenID Connect provider (authorization code + PKCE) Any app can now sign users in with a standard OIDC library: - Discovery, JWKS (RSA-2048 key generated on first start, published with os.link, mode 0600, RFC 7638 kid), /authorize, /token, /userinfo. - Confidential clients (client_secret_basic / client_secret_post), PKCE S256, nonce, prompt=none|login, iss response parameter; codes bound to the SSO session, single use with token revocation on replay (also after purge). - Opaque 10-minute access tokens for /userinfo; RS256 ID tokens with a stable sub (users.public_id). One TeleLogin login serves all apps. - Admin CLI: app add --redirect-uri, app redirect-uri add|remove, app rotate-secret (secrets printed once, never shown again). - Cascades on unlink / user remove / app remove; purge retention rule. - docs/INTEGRATION.md Mode 1 guide and examples/oidc_fastapi (Authlib). Built by Codex from the reviewed plan; inspected twice by fresh Claude sessions (first: 6 findings fixed by Codex; second: APPROVED with three optional low findings deferred to Part C). The test suite now uses a temporary OIDC key path so no key is written into the checkout, and data/ is gitignored. Verification: 161 tests pass (also with -W error), ruff clean; Authlib end-to-end test with a path prefix; live run of the example app against a real TeleLogin server completed a full login. Co-Authored-By: Claude Opus 5.5 --- .env.example | 5 + .gitignore | 5 + README.md | 17 +- docker/docker-compose.yml | 3 + docker/env.example | 5 + docs/INTEGRATION.md | 73 ++++- examples/oidc_fastapi/app.py | 46 +++ examples/oidc_fastapi/requirements.txt | 6 + requirements-dev.txt | 3 + requirements.txt | 1 + src/admin.py | 43 ++- src/app.py | 3 + src/config.py | 4 + src/database/sqlite.py | 7 +- src/web/oidc.py | 237 +++++++++++++++ tests/conftest.py | 19 +- tests/fixtures/part_a_7e7632d.sql | 35 +++ tests/test_admin.py | 54 ++++ tests/test_oidc.py | 393 +++++++++++++++++++++++++ 19 files changed, 949 insertions(+), 10 deletions(-) create mode 100644 examples/oidc_fastapi/app.py create mode 100644 examples/oidc_fastapi/requirements.txt create mode 100644 src/web/oidc.py create mode 100644 tests/fixtures/part_a_7e7632d.sql create mode 100644 tests/test_oidc.py diff --git a/.env.example b/.env.example index 86257d1..008e399 100644 --- a/.env.example +++ b/.env.example @@ -41,3 +41,8 @@ SSO_COOKIE_SECURE=true # Optional shared parent domain; every subdomain must be trusted SSO_COOKIE_DOMAIN= REGISTRATION_MODE=open + +# Keep the private signing key persistent and readable only by the API user. +OIDC_KEY_FILE=data/oidc-signing-key.pem +OIDC_CODE_TTL_SECONDS=60 +OIDC_TOKEN_TTL_SECONDS=600 diff --git a/.gitignore b/.gitignore index 0610426..b98b914 100644 --- a/.gitignore +++ b/.gitignore @@ -222,3 +222,8 @@ __marimo__/ # Disposable real-proxy test configuration and cookie jars tests/e2e/.run-*/ + +# Runtime data and private keys; retain disposable e2e certificate fixtures. +/data/ +*.pem +!tests/e2e/certs/*.pem diff --git a/README.md b/README.md index 027b6c0..e11ff1e 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,7 @@ TeleLogin also protects apps with **forward auth**: one Telegram confirmation cr browser session, and nginx, Traefik or Caddy supplies the app's verified identity. Per-app allowlists (default) or `all` policies control access. See [Integration guide](docs/INTEGRATION.md) for both shared-host/path-prefix and sibling-subdomain deployments, proxy snippets and the operator CLI. -OpenID Connect is coming in a later release. +OpenID Connect supports confidential clients with authorization code flow and PKCE S256. **Deployment change:** the development Compose API port now binds to `127.0.0.1` only. Configure a local reverse proxy, or use a private Docker network with no published API port. `GET /` now serves @@ -34,6 +34,7 @@ Telegram login confirmation using FastAPI, a Telegram bot and SQLite. Python 3.1 ## Features +- OpenID Connect discovery, RS256 ID tokens, opaque access tokens, and shared browser SSO. - Telegram deep-link registration, number matching and Deny login buttons. - SQLite persistence with atomic registration linking and login transitions. - Expiring registration tokens and login requests, with one-time access/refresh token delivery. @@ -128,6 +129,9 @@ Both templates declare all supported variables. Required secrets must be supplie | REFRESH_TOKEN_TTL_DAYS | 30; fixed session lifetime from creation | | LOGIN_HISTORY_RETENTION_DAYS | 30; login history and session metadata retention | | PURGE_INTERVAL_SECONDS | 3600; cleanup interval, also run at startup | +| OIDC_KEY_FILE | data/oidc-signing-key.pem; persistent private RSA signing key | +| OIDC_CODE_TTL_SECONDS | 60; authorization code lifetime | +| OIDC_TOKEN_TTL_SECONDS | 600; access token and ID token lifetime | | DEBUG | false | | CORS_ORIGINS | [] (JSON list) | | LOGIN_REQUEST_TTL_SECONDS | 120 | @@ -173,6 +177,11 @@ Both templates declare all supported variables. Required secrets must be supplie | GET /login | Hosted browser login; optional app and rd parameters | | GET /health | 200 {"status":"ok"} after a database query | | POST /register | {"username":"alice"}; returns Telegram registration link; duplicate username 400 | +| GET /.well-known/openid-configuration | OIDC discovery | +| GET /jwks.json | Public RSA signing key | +| GET /authorize | Authorization code flow | +| POST /token | Form-encoded code redemption with client authentication | +| GET, POST /userinfo | Opaque Bearer token identity | | POST /auth/link-telegram | Internal: {"token":"...","telegram_id":42}; atomic single-use registration link | | POST /auth/start-login | {"username":"alice"}; always returns pending login_id and verification_code unless rate limited | | POST /auth/confirm-login | Internal: {"login_id":"...","telegram_id":42,"verification_code":42}; owner approves pending unexpired login; returns only {"status":"authenticated"}, wrong code denies with 400 | @@ -348,3 +357,9 @@ otherwise that simulation is skipped. TeleLogin is distributed under the Apache License, Version 2.0. See [LICENSE](LICENSE) for the full terms. + +## OpenID Connect integration + +TeleLogin supports confidential OIDC clients with authorization code flow, PKCE S256, RS256 ID +tokens, and shared browser SSO. See [the integration guide](docs/INTEGRATION.md#mode-1-openid-connect) +and [the Authlib example](examples/oidc_fastapi/app.py). diff --git a/docker/docker-compose.yml b/docker/docker-compose.yml index 8228886..c8be033 100644 --- a/docker/docker-compose.yml +++ b/docker/docker-compose.yml @@ -26,6 +26,9 @@ services: - SSO_COOKIE_NAME=${SSO_COOKIE_NAME:-tl_sso} - SSO_COOKIE_SECURE=${SSO_COOKIE_SECURE:-true} - SSO_COOKIE_DOMAIN=${SSO_COOKIE_DOMAIN:-} + - OIDC_KEY_FILE=${OIDC_KEY_FILE:-data/oidc-signing-key.pem} + - OIDC_CODE_TTL_SECONDS=${OIDC_CODE_TTL_SECONDS:-60} + - OIDC_TOKEN_TTL_SECONDS=${OIDC_TOKEN_TTL_SECONDS:-600} - REGISTRATION_MODE=${REGISTRATION_MODE:-open} - DEBUG=${DEBUG:-false} - CORS_ORIGINS=${CORS_ORIGINS:-[]} diff --git a/docker/env.example b/docker/env.example index 4d6acc4..d3352e8 100644 --- a/docker/env.example +++ b/docker/env.example @@ -44,3 +44,8 @@ SSO_COOKIE_SECURE=true # Optional shared parent domain; every subdomain must be trusted SSO_COOKIE_DOMAIN= REGISTRATION_MODE=open + +# Keep the private signing key persistent and readable only by the API user. +OIDC_KEY_FILE=data/oidc-signing-key.pem +OIDC_CODE_TTL_SECONDS=60 +OIDC_TOKEN_TTL_SECONDS=600 diff --git a/docs/INTEGRATION.md b/docs/INTEGRATION.md index a43aee1..e9f1842 100644 --- a/docs/INTEGRATION.md +++ b/docs/INTEGRATION.md @@ -135,11 +135,13 @@ Shell access is admin access. `gen-secrets` needs no `.env` or database and prin `SECRET_KEY` and `INTERNAL_API_KEY` assignments. Never share them. ```text -app add ID --name NAME [--policy allowlist|all] +app add ID --name NAME [--policy allowlist|all] [--redirect-uri URI ...] app list | app show ID | app remove ID app policy ID allowlist|all app allow ID USERNAME | app disallow ID USERNAME app origin add|remove ID ORIGIN +app redirect-uri add|remove ID URI +app rotate-secret ID user invite USERNAME | user list | user remove USERNAME gen-secrets ``` @@ -149,7 +151,74 @@ as unlink. `app remove` also removes its allowlist. No stored secret is printed. ## Mode 1: OpenID Connect -Coming in a later release. This build has no OIDC endpoints or client credentials. +Use Mode 1 for apps on unrelated domains or apps with a standard OIDC client library. +The operator trusts every registered app; there is no consent screen. + +1. Register a confidential client and its exact callback URL: + + ```sh + python -m src.admin app add myapp --name "My App" --redirect-uri https://app.example.com/callback + python -m src.admin app allow myapp alice + ``` + + Save the printed client secret: it is shown once and only its SHA-256 hash is stored. + Repeat `--redirect-uri` for additional callback URLs. Alternatively use + `app redirect-uri add myapp URI`; adding the first URI generates a secret if needed. + `app rotate-secret myapp` replaces the secret immediately; update the app configuration. + Redirect URIs must use HTTPS, except HTTP on localhost/127.0.0.1 for development; fragments + and credentials are forbidden. Matching is exact, including path and query. + To admit every linked user instead, run `app policy myapp all`. +2. Configure your OIDC library: + + | Setting | Value | + |---|---| + | Issuer | Your `PUBLIC_URL`, e.g. `https://auth.example.com` | + | Discovery URL | `PUBLIC_URL/.well-known/openid-configuration` | + | Client ID | `myapp` | + | Client secret | The value printed by the CLI | + | Scopes | `openid profile` | + | Redirect URI | The exact registered callback URL | + | Flow | Authorization code; PKCE S256 recommended | + | Client authentication | `client_secret_basic` or `client_secret_post` | + + With a path prefix, issuer is e.g. `https://example.com/telelogin` and discovery is + `https://example.com/telelogin/.well-known/openid-configuration`. Keep that prefix in all URLs. +3. Use the [Authlib FastAPI example](../examples/oidc_fastapi/app.py): install its + `requirements.txt`, set `OIDC_ISSUER`, `OIDC_CLIENT_ID`, `OIDC_CLIENT_SECRET`, and a random + `SESSION_SECRET`, then run `uvicorn app:app --host 127.0.0.1 --port 9000` from that directory. + Register the public `/callback` URL first. Put it behind an HTTPS proxy; for plain HTTP + local development only, set `COOKIE_SECURE=false`. The example stores identity in a signed + session cookie and its logout clears that app session. It does not store bearer tokens in + the cookie. A typical Authlib registration is: + + ```python + oauth.register( + "telelogin", client_id=client_id, client_secret=client_secret, + server_metadata_url=issuer + "/.well-known/openid-configuration", + client_kwargs={"scope": "openid profile", "code_challenge_method": "S256"}, + ) + ``` + +The stable UUID `sub` identifies the user. `profile` adds `preferred_username` and `name`. +ID tokens are signed with RS256 and a public key from `/jwks.json`; access tokens are opaque, +last 10 minutes by default, and work only at `/userinfo`. Raw API HS256 tokens and OIDC tokens +are mutually unusable. Codes are single use; replay revokes the access tokens issued from that +code. Removing app access also prevents `/userinfo` and code redemption. + +Only confidential clients with a backend and a secret are supported. Browser-only SPAs should +use Mode 2 or a small backend. There are no OIDC refresh tokens, dynamic registration, consent +screens, RP-initiated logout, or back-channel logout. `max_age`, `claims`, and `ui_locales` are +unsupported and ignored. `prompt=none` fails with `login_required` without a browser session; +`prompt=login` forces a new Telegram confirmation. Otherwise the browser session is reused. +Revoking a TeleLogin browser session blocks new codes and unredeemed codes. It does not end +sessions that an OIDC app has created itself; already issued OIDC access tokens last until expiry +unless replayed or app access is removed. Unlink and user/app removal delete associated grants. + +The API generates `OIDC_KEY_FILE` on first startup with mode 0600. Persist this file alongside +SQLite data and keep it private. For manual key rotation: stop the API, back up the old key +securely, remove the key file, and restart to generate a new one. Existing ID tokens stop +validating after clients refresh their JWKS cache; coordinate app reauthentication and cache +refresh with the rotation. Automated rotation and overlapping signing keys are unsupported. ## Advanced: custom UI with the raw API diff --git a/examples/oidc_fastapi/app.py b/examples/oidc_fastapi/app.py new file mode 100644 index 0000000..3194eb4 --- /dev/null +++ b/examples/oidc_fastapi/app.py @@ -0,0 +1,46 @@ +"""Run: uvicorn app:app --host 127.0.0.1 --port 9000 (behind HTTPS in production).""" +import os + +from authlib.integrations.starlette_client import OAuth +from fastapi import FastAPI, Request +from fastapi.responses import HTMLResponse, RedirectResponse +from starlette.middleware.sessions import SessionMiddleware +import html + +app = FastAPI() +app.add_middleware(SessionMiddleware, secret_key=os.environ['SESSION_SECRET'], + https_only=os.getenv('COOKIE_SECURE', 'true') == 'true') +oauth = OAuth() +oauth.register('telelogin', client_id=os.environ['OIDC_CLIENT_ID'], + client_secret=os.environ['OIDC_CLIENT_SECRET'], + server_metadata_url=os.getenv('OIDC_ISSUER', 'https://auth.example.com') + '/.well-known/openid-configuration', + client_kwargs={'scope': 'openid profile', 'code_challenge_method': 'S256'}) + + +@app.get('/') +async def home(request: Request): + user = request.session.get('user') + if not user: + return HTMLResponse('Sign in') + return HTMLResponse('Signed in as ' + html.escape(user.get('preferred_username', user['sub'])) + + '
') + + +@app.get('/login') +async def login(request: Request): + return await oauth.telelogin.authorize_redirect(request, str(request.url_for('callback'))) + + +@app.get('/callback') +async def callback(request: Request): + token = await oauth.telelogin.authorize_access_token(request) + request.session['user'] = dict(token['userinfo']) + return RedirectResponse('/', 303) + + +@app.post('/logout') +async def logout(request: Request): + if request.headers.get('origin') != str(request.base_url).rstrip('/'): + return HTMLResponse('Invalid Origin', 403) + request.session.clear() + return RedirectResponse('/', 303) diff --git a/examples/oidc_fastapi/requirements.txt b/examples/oidc_fastapi/requirements.txt new file mode 100644 index 0000000..ba8dc4b --- /dev/null +++ b/examples/oidc_fastapi/requirements.txt @@ -0,0 +1,6 @@ +fastapi==0.159.1 +uvicorn[standard]==0.54.0 +authlib==1.8.0 +httpx2==2.13.1 +cryptography==50.0.2 +itsdangerous==2.2.0 diff --git a/requirements-dev.txt b/requirements-dev.txt index 1ca15e1..e4838a7 100644 --- a/requirements-dev.txt +++ b/requirements-dev.txt @@ -2,3 +2,6 @@ pytest==9.1.1 pytest-asyncio==1.4.0 ruff==0.17.1 +authlib==1.8.0 +httpx2==2.13.1 +itsdangerous==2.2.0 diff --git a/requirements.txt b/requirements.txt index 2be3165..968e27f 100644 --- a/requirements.txt +++ b/requirements.txt @@ -9,3 +9,4 @@ aiosqlite==0.22.1 PyJWT==2.15.1 tldextract==5.4.0 +cryptography==50.0.2 diff --git a/src/admin.py b/src/admin.py index e2c9970..74a94ca 100644 --- a/src/admin.py +++ b/src/admin.py @@ -1,4 +1,5 @@ """Operator CLI. Shell access is administrative access.""" +import hashlib import argparse import asyncio import json @@ -18,6 +19,13 @@ def parser(): add.add_argument('id') add.add_argument('--name', required=True) add.add_argument('--policy', choices=['allowlist', 'all'], default='allowlist') + add.add_argument('--redirect-uri', action='append', default=[]) + apps.add_parser('rotate-secret').add_argument('id') + redirects = apps.add_parser('redirect-uri').add_subparsers(dest='operation', required=True) + for action in ('add', 'remove'): + a = redirects.add_parser(action) + a.add_argument('id') + a.add_argument('uri') apps.add_parser('list') for action in ('show', 'remove'): apps.add_parser(action).add_argument('id') @@ -55,6 +63,17 @@ def validated_origin(value): return normalized +def validated_redirect(value): + parsed = urlsplit(value) + if (not parsed.hostname or parsed.username or parsed.password or parsed.fragment + or "#" in value or "\\" in value or any(ord(c) <= 32 or ord(c) == 127 for c in value) + or parsed.scheme not in ('https', 'http') + or (parsed.scheme == 'http' and parsed.hostname not in ('localhost', '127.0.0.1'))): + raise ValueError('Redirect URI must be absolute HTTPS (HTTP only on localhost/127.0.0.1), without fragment or credentials') + parsed.port + return value + + async def run(args): import aiosqlite from src.database.sqlite import SQLiteDatabase @@ -83,12 +102,13 @@ async def run(args): user = await (await conn.execute('SELECT id FROM users WHERE username=?', (args.username,))).fetchone() if not user: raise ValueError('Unknown username') - for table in ('app_users', 'sessions', 'registration_tokens', 'login_requests'): + for table in ('oidc_tokens', 'oidc_codes', 'app_users', 'sessions', 'registration_tokens', 'login_requests'): await conn.execute(f'DELETE FROM {table} WHERE user_id=?', (user['id'],)) await conn.execute('DELETE FROM users WHERE id=?', (user['id'],)) await conn.commit() print('User removed') return + secret = None async with aiosqlite.connect(db.db_path) as conn: conn.row_factory = aiosqlite.Row await conn.execute('BEGIN IMMEDIATE') @@ -99,7 +119,9 @@ async def run(args): if args.action == 'add': if not re.fullmatch(r'[a-z0-9][a-z0-9-]{0,39}', args.id): raise ValueError('App id must match ^[a-z0-9][a-z0-9-]{0,39}$') - await conn.execute('INSERT INTO apps(id,name,access_policy,created_at) VALUES (?,?,?,?)', (args.id, args.name, args.policy, time.time())) + uris = [validated_redirect(uri) for uri in args.redirect_uri] + secret = secrets.token_urlsafe(32) if uris else None + await conn.execute('INSERT INTO apps(id,name,access_policy,created_at,redirect_uris,secret_hash) VALUES (?,?,?,?,?,?)', (args.id, args.name, args.policy, time.time(), json.dumps(uris), hashlib.sha256(secret.encode()).hexdigest() if secret else None)) else: app = await (await conn.execute('SELECT * FROM apps WHERE id=?', (args.id,))).fetchone() if not app: @@ -111,8 +133,21 @@ async def run(args): print(json.dumps(data, ensure_ascii=False)) return if args.action == 'remove': - await conn.execute('DELETE FROM app_users WHERE app_id=?', (args.id,)) + for table in ('oidc_tokens', 'oidc_codes', 'app_users'): + await conn.execute(f'DELETE FROM {table} WHERE app_id=?', (args.id,)) await conn.execute('DELETE FROM apps WHERE id=?', (args.id,)) + elif args.action in ('rotate-secret', 'redirect-uri'): + if args.action == 'redirect-uri': + value = validated_redirect(args.uri) + uris = json.loads(app['redirect_uris']) + if args.operation == 'add' and value not in uris: + uris.append(value) + if args.operation == 'remove' and value in uris: + uris.remove(value) + await conn.execute('UPDATE apps SET redirect_uris=? WHERE id=?', (json.dumps(uris), args.id)) + if args.action == 'rotate-secret' or (args.operation == 'add' and not app['secret_hash']): + secret = secrets.token_urlsafe(32) + await conn.execute('UPDATE apps SET secret_hash=? WHERE id=?', (hashlib.sha256(secret.encode()).hexdigest(), args.id)) elif args.action == 'policy': await conn.execute('UPDATE apps SET access_policy=? WHERE id=?', (args.policy, args.id)) elif args.action in ('allow', 'disallow'): @@ -135,7 +170,7 @@ async def run(args): origins.remove(value) await conn.execute('UPDATE apps SET origins=? WHERE id=?', (json.dumps(origins), args.id)) await conn.commit() - print('OK') + print('Client secret: ' + secret if secret else 'OK') def main(): diff --git a/src/app.py b/src/app.py index c092671..f38f269 100644 --- a/src/app.py +++ b/src/app.py @@ -16,6 +16,7 @@ from src.config import settings from src.database.sqlite import SQLiteDatabase from src.web.routes import router +from src.web.oidc import router as oidc_router, load_key from src.web.sso import router as sso_router @@ -28,6 +29,7 @@ async def lifespan(app: FastAPI): # Startup: Initialize database tables app.state.db = SQLiteDatabase() await app.state.db.init_db() + app.state.oidc_key = load_key(settings.OIDC_KEY_FILE) app.state.limiter = RateLimiter() app.state.login_html = Path(__file__).with_name("web").joinpath("templates/index.html").read_text(encoding="utf-8") async def purge_once(): @@ -77,6 +79,7 @@ async def __call__(self, scope, receive, send): # Include routes app.include_router(router) app.include_router(sso_router) +app.include_router(oidc_router) @app.get("/health") async def health(db=Depends(get_db)): diff --git a/src/config.py b/src/config.py index 6794818..54c21d9 100644 --- a/src/config.py +++ b/src/config.py @@ -32,6 +32,10 @@ class Settings(BaseSettings): LOGIN_HISTORY_RETENTION_DAYS: int = Field(default=30, gt=0) PURGE_INTERVAL_SECONDS: float = Field(default=3600, gt=0) + OIDC_KEY_FILE: str = "data/oidc-signing-key.pem" + OIDC_CODE_TTL_SECONDS: int = Field(default=60, gt=0) + OIDC_TOKEN_TTL_SECONDS: int = Field(default=600, gt=0) + PUBLIC_URL: str = "http://localhost:8000" SSO_COOKIE_NAME: str = "tl_sso" SSO_COOKIE_SECURE: bool = True diff --git a/src/database/sqlite.py b/src/database/sqlite.py index 322daeb..dcbaa66 100644 --- a/src/database/sqlite.py +++ b/src/database/sqlite.py @@ -94,6 +94,9 @@ async def init_db(self): await db.execute("CREATE UNIQUE INDEX IF NOT EXISTS idx_users_public_id ON users(public_id)") await db.execute("CREATE TABLE IF NOT EXISTS apps (id TEXT PRIMARY KEY, name TEXT NOT NULL, access_policy TEXT NOT NULL DEFAULT 'allowlist' CHECK(access_policy IN ('allowlist','all')), secret_hash TEXT, redirect_uris TEXT NOT NULL DEFAULT '[]', origins TEXT NOT NULL DEFAULT '[]', created_at REAL NOT NULL)") await db.execute("CREATE TABLE IF NOT EXISTS app_users (app_id TEXT NOT NULL REFERENCES apps(id), user_id INTEGER NOT NULL REFERENCES users(id), PRIMARY KEY(app_id,user_id))") + await db.execute("CREATE TABLE IF NOT EXISTS oidc_codes (code_hash TEXT PRIMARY KEY, app_id TEXT, user_id INTEGER, session_id TEXT, redirect_uri TEXT, scope TEXT, nonce TEXT, code_challenge TEXT, auth_time REAL, expires_at REAL, used_at REAL)") + await db.execute("CREATE TABLE IF NOT EXISTS oidc_tokens (token_hash TEXT PRIMARY KEY, app_id TEXT, user_id INTEGER, code_hash TEXT, scope TEXT, expires_at REAL, revoked_at REAL)") + await db.execute("CREATE INDEX IF NOT EXISTS idx_oidc_tokens_code ON oidc_tokens(code_hash)") await db.commit() async def create_user(self, username: str) -> User: @@ -302,7 +305,7 @@ async def account_action(self, telegram_id, action, session_id=None): return None await db.execute("UPDATE sessions SET revoked_at=COALESCE(revoked_at,?) WHERE user_id=?" + (' AND id=?' if session_id is not None else ''), (now,uid,session_id) if session_id is not None else (now,uid)) elif action == 'delete': - for table in ('app_users','sessions','registration_tokens','login_requests'): + for table in ('oidc_tokens','oidc_codes','app_users','sessions','registration_tokens','login_requests'): await db.execute(f"DELETE FROM {table} WHERE user_id=?", (uid,)) await db.execute("DELETE FROM users WHERE id=?", (uid,)) await db.commit() @@ -312,6 +315,8 @@ async def purge_old(self, retention_seconds): cutoff = time.time() - retention_seconds async with aiosqlite.connect(self.db_path) as db: await db.execute("BEGIN IMMEDIATE") + await db.execute("DELETE FROM oidc_codes WHERE expires_at 1 for name in ('client_id', 'redirect_uri')): + return HTMLResponse('Repeated client_id or redirect URI', 400) + app = await db.get_app(q.get('client_id')) + uri = q.get('redirect_uri') + if not app or not app['secret_hash'] or not uri or uri not in json.loads(app['redirect_uris']): + return HTMLResponse('Invalid client or redirect URI', 400) + values = {'iss': settings.PUBLIC_URL} + if 'state' in q: + values['state'] = q['state'] + + def error(code, description): + return redirect(uri, dict(values, error=code, error_description=description)) + + if any(len(q.getlist(name)) > 1 for name in q): + return error('invalid_request', 'Repeated authorization parameter') + if q.get('response_type') != 'code': + return error('unsupported_response_type', 'Only code is supported') + scopes = q.get('scope', '').split() + if 'openid' not in scopes: + return error('invalid_scope', 'openid scope required') + challenge = q.get('code_challenge') + if (q.get('code_challenge_method') not in (None, 'S256') or + (challenge is not None and (q.get('code_challenge_method') != 'S256' or not re.fullmatch(r'[A-Za-z0-9._~-]{43,128}', challenge))) or + ('code_challenge_method' in q and challenge is None)): + return error('invalid_request', 'Invalid PKCE challenge') + if 'request' in q or 'request_uri' in q: + return error('request_not_supported', 'Request objects are unsupported') + prompts = q.get('prompt', '').split() + session = await db.browser_session(request.cookies.get(settings.SSO_COOKIE_NAME)) + if not session or 'login' in prompts: + if 'none' in prompts: + return error('login_required', 'Browser login required') + continuation = settings.PUBLIC_URL + '/authorize?' + urlencode([(k, v) for k, v in q.multi_items() if not (k == 'prompt' and 'login' in prompts)]) + if return_url(continuation, app) is None: + return error('invalid_request', 'authorization request too long or invalid') + params = dict(app=app['id'], rd=continuation) + if 'login' in prompts: + params['force'] = '1' + return RedirectResponse(settings.PUBLIC_URL + '/login?' + urlencode(params), 302) + if not await db.allowed(app, session): + return error('access_denied', 'User is not allowed') + code = secrets.token_urlsafe(32) + async with aiosqlite.connect(db.db_path) as conn: + await conn.execute('BEGIN IMMEDIATE') + active = await (await conn.execute("SELECT 1 FROM sessions WHERE id=? AND kind='sso' AND revoked_at IS NULL AND expires_at>?", (session['id'], time.time()))).fetchone() + if not active or not await allowed(conn, app['id'], session['user_id']): + return error('access_denied', 'Browser session or app access revoked') + await conn.execute('INSERT INTO oidc_codes VALUES (?,?,?,?,?,?,?,?,?,?,NULL)', + (digest(code), app['id'], session['user_id'], session['id'], uri, ' '.join(s for s in ('openid', 'profile') if s in scopes), q.get('nonce'), challenge, session['created_at'], time.time()+settings.OIDC_CODE_TTL_SECONDS)) + await conn.commit() + return redirect(uri, dict(values, code=code)) + + +def oauth_error(code, description, basic=False): + headers = {'Cache-Control': 'no-store', 'Pragma': 'no-cache'} + if basic: + headers['WWW-Authenticate'] = 'Basic' + return JSONResponse({'error': code, 'error_description': description}, 401 if code == 'invalid_client' else 400, headers=headers) + + +async def form(request): + if request.headers.get('content-type', '').split(';')[0].lower() != 'application/x-www-form-urlencoded': + return {} + try: + pairs = parse_qsl((await request.body()).decode(), keep_blank_values=True) + if len(dict(pairs)) != len(pairs): + return {} + return dict(pairs) + except UnicodeError: + return {} + + +async def allowed(conn, app_id, user_id): + return await (await conn.execute("SELECT u.* FROM users u JOIN apps a ON a.id=? WHERE u.id=? AND u.telegram_id IS NOT NULL AND (a.access_policy='all' OR EXISTS (SELECT 1 FROM app_users WHERE app_id=a.id AND user_id=u.id))", (app_id, user_id))).fetchone() + + +@router.post('/token') +async def token(request: Request, db=Depends(get_db)): + body = await form(request) + authorization = request.headers.get('authorization') + basic = authorization is not None + client_id, secret = body.get('client_id'), body.get('client_secret') + if basic: + try: + scheme, encoded = authorization.split(' ', 1) + if scheme.lower() != 'basic' or 'client_secret' in body: + raise ValueError() + client_id, secret = (unquote_plus(v) for v in base64.b64decode(encoded, validate=True).decode().split(':', 1)) + if 'client_id' in body and body['client_id'] != client_id: + raise ValueError() + except (ValueError, UnicodeError): + return oauth_error('invalid_client', 'Invalid client authentication', True) + app = await db.get_app(client_id) + if not app or not app['secret_hash'] or not secret or not hmac.compare_digest(digest(secret), app['secret_hash']): + return oauth_error('invalid_client', 'Invalid client authentication', basic) + if body.get('grant_type') != 'authorization_code': + return oauth_error('unsupported_grant_type', 'Only authorization_code is supported') + code_hash = digest(body.get('code', '')) + async with aiosqlite.connect(db.db_path) as conn: + conn.row_factory = aiosqlite.Row + await conn.execute('BEGIN IMMEDIATE') + row = await (await conn.execute('SELECT * FROM oidc_codes WHERE code_hash=?', (code_hash,))).fetchone() + now = time.time() + if not row or row['used_at'] is not None: + await conn.execute('UPDATE oidc_tokens SET revoked_at=? WHERE code_hash=?', (now, code_hash)) + await conn.commit() + return oauth_error('invalid_grant', 'Unknown or used code') + verifier = body.get('code_verifier') + valid_pkce = (verifier is None if row['code_challenge'] is None else + bool(verifier and re.fullmatch(r'[A-Za-z0-9._~-]{43,128}', verifier) and hmac.compare_digest(b64(hashlib.sha256(verifier.encode()).digest()), row['code_challenge']))) + user = await allowed(conn, app['id'], row['user_id']) + session = await (await conn.execute("SELECT 1 FROM sessions WHERE id=? AND user_id=? AND kind='sso' AND revoked_at IS NULL AND expires_at>?", (row['session_id'], row['user_id'], now))).fetchone() + if row['app_id'] != app['id'] or row['redirect_uri'] != body.get('redirect_uri') or row['expires_at'] <= now or not valid_pkce or not user or not session: + return oauth_error('invalid_grant', 'Invalid authorization grant') + access = secrets.token_urlsafe(32) + claims = dict(iss=settings.PUBLIC_URL, sub=user['public_id'], aud=app['id'], iat=int(now), exp=int(now)+settings.OIDC_TOKEN_TTL_SECONDS, auth_time=int(row['auth_time'])) + if row['nonce'] is not None: + claims['nonce'] = row['nonce'] + if 'profile' in row['scope'].split(): + claims.update(preferred_username=user['username'], name=user['username']) + key, jwk = request.app.state.oidc_key + id_token = jwt.encode(claims, key, algorithm='RS256', headers={'kid': jwk['kid']}) + await conn.execute('UPDATE oidc_codes SET used_at=? WHERE code_hash=?', (now, code_hash)) + await conn.execute('INSERT INTO oidc_tokens VALUES (?,?,?,?,?,?,NULL)', (digest(access), app['id'], user['id'], code_hash, row['scope'], now+settings.OIDC_TOKEN_TTL_SECONDS)) + await conn.commit() + return JSONResponse(dict(access_token=access, token_type='Bearer', expires_in=settings.OIDC_TOKEN_TTL_SECONDS, scope=row['scope'], id_token=id_token), headers={'Cache-Control': 'no-store', 'Pragma': 'no-cache'}) + + +@router.get('/userinfo', operation_id='oidc_userinfo_get') +async def userinfo_get(request: Request, db=Depends(get_db)): + return await userinfo(request, db) + + +@router.post('/userinfo', operation_id='oidc_userinfo_post') +async def userinfo_post(request: Request, db=Depends(get_db)): + return await userinfo(request, db) + + +async def userinfo(request: Request, db): + header = request.headers.get('authorization', '').split() + if len(header) == 2 and header[0].lower() == 'bearer': + async with aiosqlite.connect(db.db_path) as conn: + conn.row_factory = aiosqlite.Row + row = await (await conn.execute('SELECT * FROM oidc_tokens WHERE token_hash=? AND revoked_at IS NULL AND expires_at>?', (digest(header[1]), time.time()))).fetchone() + user = await allowed(conn, row['app_id'], row['user_id']) if row else None + if user: + result = {'sub': user['public_id']} + if 'profile' in row['scope'].split(): + result.update(preferred_username=user['username'], name=user['username']) + return JSONResponse(result, headers={'Cache-Control': 'no-store'}) + return JSONResponse({'error': 'invalid_token'}, 401, headers={'WWW-Authenticate': 'Bearer error="invalid_token"', 'Cache-Control': 'no-store'}) diff --git a/tests/conftest.py b/tests/conftest.py index 5a6990c..699eaf7 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -1,9 +1,24 @@ +import atexit import os +from pathlib import Path +import tempfile + +import pytest + +# Set before importing settings/app; all lifespan tests share this temporary key. +_oidc_directory = tempfile.TemporaryDirectory(prefix="telelogin-test-keys-") +atexit.register(_oidc_directory.cleanup) +os.environ["OIDC_KEY_FILE"] = str(Path(_oidc_directory.name) / "oidc-signing-key.pem") os.environ.update(BOT_TOKEN="123:test", SECRET_KEY="s" * 32, INTERNAL_API_KEY="i" * 32) -import pytest -from src.database.sqlite import SQLiteDatabase +from src.database.sqlite import SQLiteDatabase # noqa: E402 (test environment must precede settings) + + +@pytest.fixture(scope="session", autouse=True) +def no_checkout_signing_key(): + yield + assert not (Path(__file__).resolve().parents[1] / "data/oidc-signing-key.pem").exists() @pytest.fixture diff --git a/tests/fixtures/part_a_7e7632d.sql b/tests/fixtures/part_a_7e7632d.sql new file mode 100644 index 0000000..caff698 --- /dev/null +++ b/tests/fixtures/part_a_7e7632d.sql @@ -0,0 +1,35 @@ +-- Schema captured from SQLiteDatabase.init_db at 7e7632d (Part A). +CREATE TABLE app_users (app_id TEXT NOT NULL REFERENCES apps(id), user_id INTEGER NOT NULL REFERENCES users(id), PRIMARY KEY(app_id,user_id)); + +CREATE TABLE apps (id TEXT PRIMARY KEY, name TEXT NOT NULL, access_policy TEXT NOT NULL DEFAULT 'allowlist' CHECK(access_policy IN ('allowlist','all')), secret_hash TEXT, redirect_uris TEXT NOT NULL DEFAULT '[]', origins TEXT NOT NULL DEFAULT '[]', created_at REAL NOT NULL); + +CREATE TABLE login_requests ( + id TEXT PRIMARY KEY, + user_id INTEGER NOT NULL, + status TEXT DEFAULT 'pending', + session_token TEXT, + created_at DATETIME DEFAULT CURRENT_TIMESTAMP, expires_at REAL, token_delivered_at REAL, ip TEXT, user_agent TEXT, verification_code INTEGER, refresh_token TEXT, purpose TEXT NOT NULL DEFAULT 'api', app_id TEXT, return_to TEXT, + FOREIGN KEY (user_id) REFERENCES users (id) + ); + +CREATE TABLE registration_tokens (token_hash TEXT PRIMARY KEY, user_id INTEGER NOT NULL REFERENCES users(id), expires_at REAL NOT NULL, used_at REAL); + +CREATE TABLE sessions (id TEXT PRIMARY KEY, user_id INTEGER NOT NULL REFERENCES users(id), refresh_hash TEXT UNIQUE NOT NULL, previous_refresh_hash TEXT, created_at REAL NOT NULL, expires_at REAL NOT NULL, last_used_at REAL, revoked_at REAL, ip TEXT, user_agent TEXT, kind TEXT NOT NULL DEFAULT 'api'); + +CREATE TABLE users ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + username TEXT UNIQUE NOT NULL, + telegram_id INTEGER, + created_at DATETIME DEFAULT CURRENT_TIMESTAMP, + linked_at DATETIME + , public_id TEXT); + +CREATE INDEX idx_login_requests_user_id ON login_requests(user_id); + +CREATE INDEX idx_sessions_user ON sessions(user_id); + +CREATE UNIQUE INDEX idx_users_public_id ON users(public_id); + +CREATE UNIQUE INDEX idx_users_telegram_id ON users(telegram_id) WHERE telegram_id IS NOT NULL; + +CREATE INDEX idx_users_username ON users(username); diff --git a/tests/test_admin.py b/tests/test_admin.py index 32c1431..ab2be6b 100644 --- a/tests/test_admin.py +++ b/tests/test_admin.py @@ -111,3 +111,57 @@ async def test_allow_rejects_unlinked_user(db, monkeypatch): user = await db.get_user_by_username('alice') await db.consume_and_link(await tokens.generate_registration_token(user.id), 42) await admin.run(args('app', 'allow', 'demo', 'alice')) + + +async def test_oidc_client_commands(db, monkeypatch, capsys): + import hashlib + import sqlite3 + monkeypatch.setattr(settings, 'DB_URL', 'sqlite:///' + db.db_path) + uri = 'https://client.example/callback' + await admin.run(args('app', 'add', 'oidc', '--name', 'Client', '--redirect-uri', uri, '--redirect-uri', 'http://localhost:9000/callback')) + secret = capsys.readouterr().out.strip().split('Client secret: ')[1] + app = await db.get_app('oidc') + assert app['secret_hash'] == hashlib.sha256(secret.encode()).hexdigest() + assert json.loads(app['redirect_uris']) == [uri, 'http://localhost:9000/callback'] + for action in ('show', 'list'): + await admin.run(args('app', action, *(['oidc'] if action == 'show' else []))) + output = capsys.readouterr().out + assert secret not in output and app['secret_hash'] not in output and 'secret_hash' not in output + await admin.run(args('app', 'rotate-secret', 'oidc')) + replacement = capsys.readouterr().out.strip().split('Client secret: ')[1] + assert replacement != secret + assert (await db.get_app('oidc'))['secret_hash'] == hashlib.sha256(replacement.encode()).hexdigest() + await admin.run(args('app', 'redirect-uri', 'remove', 'oidc', uri)) + assert uri not in json.loads((await db.get_app('oidc'))['redirect_uris']) + await admin.run(args('app', 'add', 'forward', '--name', 'Forward')) + capsys.readouterr() + await admin.run(args('app', 'redirect-uri', 'add', 'forward', uri)) + assert 'Client secret: ' in capsys.readouterr().out + await admin.run(args('app', 'redirect-uri', 'add', 'forward', uri)) + assert capsys.readouterr().out.strip() == 'OK' + with sqlite3.connect(db.db_path) as conn: + conn.execute("INSERT INTO oidc_codes(code_hash,app_id) VALUES ('code','oidc')") + conn.execute("INSERT INTO oidc_tokens(token_hash,app_id) VALUES ('token','oidc')") + await admin.run(args('app', 'remove', 'oidc')) + with sqlite3.connect(db.db_path) as conn: + for table in ('oidc_codes', 'oidc_tokens'): + assert conn.execute(f'SELECT count(*) FROM {table}').fetchone()[0] == 0 + + +@pytest.mark.parametrize('uri', ['https://client.example/cb#fragment', 'http://client.example/cb', '/callback', 'https://user@client.example/cb', 'javascript:alert(1)', 'https://client.example/\ncb', 'https://client.example/cb#']) +def test_invalid_redirect_uris(uri): + with pytest.raises(ValueError): + admin.validated_redirect(uri) + + +async def test_admin_user_remove_oidc_cascade(db, monkeypatch, capsys): + import sqlite3 + monkeypatch.setattr(settings, 'DB_URL', 'sqlite:///' + db.db_path) + user = await db.create_user('delete-me') + with sqlite3.connect(db.db_path) as conn: + conn.execute('INSERT INTO oidc_codes(code_hash,user_id) VALUES (?,?)', ('code', user.id)) + conn.execute('INSERT INTO oidc_tokens(token_hash,user_id) VALUES (?,?)', ('token', user.id)) + await admin.run(args('user', 'remove', 'delete-me')) + with sqlite3.connect(db.db_path) as conn: + for table in ('oidc_codes', 'oidc_tokens'): + assert conn.execute(f'SELECT count(*) FROM {table}').fetchone()[0] == 0 diff --git a/tests/test_oidc.py b/tests/test_oidc.py new file mode 100644 index 0000000..ac4d8d9 --- /dev/null +++ b/tests/test_oidc.py @@ -0,0 +1,393 @@ +"""OIDC interoperability, grant isolation and lifecycle tests.""" +from concurrent.futures import ThreadPoolExecutor +import hashlib +import importlib.util +import json +from pathlib import Path +import sqlite3 +import time +from unittest.mock import AsyncMock +from urllib.parse import parse_qs, urlsplit + +from authlib.integrations.httpx_client import AsyncOAuth2Client +from authlib.oidc.core import CodeIDToken +from joserfc import jwt +from joserfc.jwk import KeySet +import httpx2 +import pytest +from fastapi import FastAPI + +from src.app import app +from src.config import settings +from src.web.oidc import digest, load_key +from src.web.security import RateLimiter +from test_security import linked + +BASE = 'http://testserver/telelogin' +URI = 'https://client.example.com/callback?existing=1' +SECRET = 'client-secret' + + +@pytest.fixture +async def oidc(db, monkeypatch, tmp_path): + monkeypatch.setattr(settings, 'PUBLIC_URL', BASE) + monkeypatch.setattr(settings, 'SSO_COOKIE_SECURE', False) + monkeypatch.setattr(settings, 'SSO_COOKIE_DOMAIN', '') + monkeypatch.setattr(app.state, 'db', db, raising=False) + monkeypatch.setattr(app.state, 'oidc_key', load_key(tmp_path / 'key.pem'), raising=False) + monkeypatch.setattr(app.state, 'limiter', RateLimiter(), raising=False) + monkeypatch.setattr(app.state, 'login_html', Path('src/web/templates/index.html').read_text(), raising=False) + monkeypatch.setattr('src.services.auth_service.AuthService.send_login_notification', AsyncMock()) + user = await linked(db) + with sqlite3.connect(db.db_path) as conn: + conn.execute('INSERT INTO apps VALUES (?,?,?,?,?,?,?)', ('demo', 'Demo', 'all', digest(SECRET), json.dumps([URI]), '[]', time.time())) + mounted = FastAPI() + mounted.mount('/telelogin', app) + async with httpx2.AsyncClient(transport=httpx2.ASGITransport(app=mounted), base_url=BASE + '/') as client: + yield client, mounted, user + + +async def browser(client): + start = (await client.post('sso/start', json={'username': 'alice', 'app': 'demo'})).json() + result = await client.post('auth/confirm-login', json=dict(login_id=start['login_id'], telegram_id=42, verification_code=start['verification_code']), headers={'X-Internal-Key': settings.INTERNAL_API_KEY}) + assert result.status_code == 200, result.text + result = await client.post('sso/complete', json={'login_id': start['login_id']}) + assert result.json()['status'] == 'approved' + + +def params(**extra): + return dict(client_id='demo', redirect_uri=URI, response_type='code', scope='openid profile', state='state', **extra) + + +async def code(client, **extra): + response = await client.get('authorize', params=params(**extra)) + assert response.status_code == 302 + values = parse_qs(urlsplit(response.headers['location']).query) + assert values['iss'] == [BASE] + return values['code'][0] + + +async def redeem(client, value, **extra): + body = dict(grant_type='authorization_code', client_id='demo', client_secret=SECRET, redirect_uri=URI, code=value) + body.update(extra) + return await client.post('token', data=body) + + +async def test_authlib_prefix_flow(oidc): + client, mounted, user = oidc + discovery = (await client.get('.well-known/openid-configuration')).json() + assert discovery['issuer'] == BASE + async with AsyncOAuth2Client('demo', SECRET, transport=httpx2.ASGITransport(app=mounted), code_challenge_method='S256') as oauth: + verifier = 'v' * 64 + url, state = oauth.create_authorization_url(discovery['authorization_endpoint'], redirect_uri=URI, scope='openid profile', code_verifier=verifier, nonce='nonce') + first = await client.get(url) + login = first.headers['location'] + assert login.startswith(BASE + '/login?') + continuation = parse_qs(urlsplit(login).query)['rd'][0] + assert continuation.startswith(BASE + '/authorize?') + await browser(client) + result = await client.get(continuation) + callback = result.headers['location'] + assert parse_qs(urlsplit(callback).query)['state'] == [state] + token = await oauth.fetch_token(discovery['token_endpoint'], authorization_response=callback, state=state, redirect_uri=URI, code_verifier=verifier) + keys = (await client.get(discovery['jwks_uri'])).json() + decoded = jwt.decode(token['id_token'], KeySet.import_key_set(keys), algorithms=['RS256']) + claims = CodeIDToken(decoded.claims, decoded.header, options={'iss': {'essential': True, 'value': BASE}, 'aud': {'essential': True, 'value': 'demo'}, 'nonce': {'essential': True, 'value': 'nonce'}}, params={'client_id': 'demo', 'nonce': 'nonce'}) + claims.validate() + assert claims['sub'] == user.public_id + info = await oauth.get(discovery['userinfo_endpoint']) + assert info.json() == {'sub': user.public_id, 'name': 'alice', 'preferred_username': 'alice'} + + +async def test_authorization_errors(oidc, db): + client, _, _ = oidc + bad = params() + bad['redirect_uri'] = 'https://evil.example/callback' + result = await client.get('authorize', params=bad) + assert result.status_code == 400 and 'location' not in result.headers + result = await client.get('authorize', params=params(prompt='none')) + assert 'error=login_required' in result.headers['location'] + await browser(client) + result = await client.get('authorize', params=params(prompt='login')) + assert 'force=1' in result.headers['location'] + login = await client.get(result.headers['location']) + assert login.status_code == 200 + for key, value, expected in [('response_type', 'token', 'unsupported_response_type'), ('scope', 'profile', 'invalid_scope'), ('request_uri', 'https://evil', 'request_not_supported'), ('code_challenge_method', 'plain', 'invalid_request')]: + query = params() + query[key] = value + result = await client.get('authorize', params=query) + assert 'error=' + expected in result.headers['location'] + with sqlite3.connect(db.db_path) as conn: + conn.execute("UPDATE apps SET access_policy='allowlist'") + result = await client.get('authorize', params=params()) + assert 'error=access_denied' in result.headers['location'] + + +@pytest.mark.parametrize('failure', ['wrong-secret', 'expired', 'revoked', 'missing-verifier', 'mismatch', 'unexpected-verifier', 'redirect', 'disallowed']) +async def test_invalid_grants(oidc, db, failure): + client, _, _ = oidc + await browser(client) + pkce = failure in ('missing-verifier', 'mismatch') + value = await code(client, **({'code_challenge': 'a'*43, 'code_challenge_method': 'S256'} if pkce else {})) + extra = {} + if failure == 'wrong-secret': + extra['client_secret'] = 'wrong' + if failure in ('mismatch', 'unexpected-verifier'): + extra['code_verifier'] = 'b'*43 + if failure == 'redirect': + extra['redirect_uri'] = 'https://other.example/' + with sqlite3.connect(db.db_path) as conn: + if failure == 'expired': + conn.execute('UPDATE oidc_codes SET expires_at=0') + if failure == 'revoked': + conn.execute('UPDATE sessions SET revoked_at=1') + if failure == 'disallowed': + conn.execute("UPDATE apps SET access_policy='allowlist'") + result = await redeem(client, value, **extra) + assert result.status_code == (401 if failure == 'wrong-secret' else 400) + assert result.json()['error'] == ('invalid_client' if failure == 'wrong-secret' else 'invalid_grant') + + +@pytest.mark.parametrize('purge', [False, True]) +async def test_replay_revokes_tokens(oidc, db, purge): + client, _, _ = oidc + await browser(client) + value = await code(client) + result = await redeem(client, value) + assert result.status_code == 200 + token = result.json()['access_token'] + assert (await client.get('userinfo', headers={'Authorization': 'Bearer '+token})).status_code == 200 + if purge: + with sqlite3.connect(db.db_path) as conn: + conn.execute('UPDATE oidc_codes SET expires_at=?', (time.time()-1,)) + await db.purge_old(86400) + with sqlite3.connect(db.db_path) as conn: + assert conn.execute('SELECT count(*) FROM oidc_codes').fetchone()[0] == 1 + # Even a missing code must retain replay protection through the tokens. + conn.execute('DELETE FROM oidc_codes') + assert (await redeem(client, value)).json()['error'] == 'invalid_grant' + assert (await client.get('userinfo', headers={'Authorization': 'Bearer '+token})).status_code == 401 + + +async def test_token_isolation_and_revocation(oidc, db): + client, _, user = oidc + await browser(client) + value = await code(client) + result = (await redeem(client, value)).json() + assert (await client.get('auth/me', headers={'Authorization': 'Bearer '+result['access_token']})).status_code == 401 + api = db.access({'id': user.id, 'username': user.username}, 'sid') + assert (await client.get('userinfo', headers={'Authorization': 'Bearer '+api})).status_code == 401 + await db.account_action(42, 'revoke') + result = await client.get('authorize', params=params(prompt='none')) + assert 'login_required' in result.headers['location'] + await db.account_action(42, 'delete') + with sqlite3.connect(db.db_path) as conn: + for table in ('oidc_codes', 'oidc_tokens'): + assert conn.execute(f'SELECT count(*) FROM {table}').fetchone()[0] == 0 + + +def test_keys_concurrent_and_reused(tmp_path): + filename = tmp_path / 'key.pem' + with ThreadPoolExecutor(2) as pool: + keys = list(pool.map(load_key, [filename, filename])) + assert keys[0][1] == keys[1][1] == load_key(filename)[1] + assert filename.stat().st_mode & 0o777 == 0o600 + jwk = keys[0][1] + from src.web.oidc import b64 + canonical = json.dumps({k: jwk[k] for k in ('e', 'kty', 'n')}, sort_keys=True, separators=(',', ':')) + assert jwk['kid'] == b64(hashlib.sha256(canonical.encode()).digest()) + assert list(tmp_path.iterdir()) == [filename] + + +async def test_part_a_schema_migration(tmp_path): + from src.database.sqlite import SQLiteDatabase + database = SQLiteDatabase(str(tmp_path / 'part-a.db')) + tables = ('users', 'sessions', 'login_requests', 'apps', 'app_users', 'registration_tokens') + with sqlite3.connect(database.db_path) as conn: + conn.executescript(Path('tests/fixtures/part_a_7e7632d.sql').read_text()) + conn.execute("INSERT INTO users(id,username,telegram_id,public_id) VALUES (1,'alice',42,'stable-public-id')") + conn.execute("INSERT INTO apps(id,name,created_at) VALUES ('demo','Demo',100)") + conn.execute("INSERT INTO app_users VALUES ('demo',1)") + for kind in ('api', 'sso'): + conn.execute('INSERT INTO sessions(id,user_id,refresh_hash,created_at,expires_at,kind) VALUES (?,1,?,100,200,?)', (kind, kind+'-hash', kind)) + conn.execute("INSERT INTO login_requests(id,user_id,status,expires_at,purpose,app_id) VALUES (?,1,'pending',200,?,'demo')", (kind, kind)) + conn.execute("INSERT INTO registration_tokens VALUES ('registration-hash',1,200,NULL)") + before = {table: conn.execute(f'SELECT * FROM {table} ORDER BY rowid').fetchall() for table in tables} + assert not conn.execute("SELECT name FROM sqlite_master WHERE name LIKE 'oidc_%'").fetchall() + await database.init_db() + await database.init_db() + with sqlite3.connect(database.db_path) as conn: + for table in tables: + assert conn.execute(f'SELECT * FROM {table} ORDER BY rowid').fetchall() == before[table] + for table in ('oidc_codes', 'oidc_tokens'): + assert conn.execute(f'SELECT * FROM {table}').fetchall() == [] + + +def test_example_import(monkeypatch): + monkeypatch.setenv('OIDC_CLIENT_ID', 'demo') + monkeypatch.setenv('OIDC_CLIENT_SECRET', SECRET) + monkeypatch.setenv('SESSION_SECRET', 's'*32) + spec = importlib.util.spec_from_file_location('oidc_example', 'examples/oidc_fastapi/app.py') + spec.loader.exec_module(importlib.util.module_from_spec(spec)) + + +async def test_code_retention(db): + with sqlite3.connect(db.db_path) as conn: + for name, expiry in [('recent', time.time()-1), ('old', time.time()-settings.OIDC_TOKEN_TTL_SECONDS-10)]: + conn.execute('INSERT INTO oidc_codes(code_hash,expires_at) VALUES (?,?)', (name, expiry)) + conn.execute('INSERT INTO oidc_tokens(token_hash,expires_at) VALUES (?,?)', (name, expiry)) + await db.purge_old(86400) + with sqlite3.connect(db.db_path) as conn: + assert conn.execute('SELECT code_hash FROM oidc_codes').fetchall() == [('recent',)] + assert conn.execute('SELECT count(*) FROM oidc_tokens').fetchone()[0] == 0 + + +async def test_client_authentication_and_profile_scope(oidc): + import base64 + client, _, _ = oidc + await browser(client) + for auth, data in [(None, {}), ('Basic invalid!', {}), ('Basic '+base64.b64encode(b'demo:client-secret').decode(), {'client_id': 'demo', 'client_secret': SECRET})]: + headers = {'Authorization': auth} if auth else {} + response = await client.post('token', data=dict(grant_type='authorization_code', **data), headers=headers) + assert response.status_code == 401 + if auth: + assert response.headers['www-authenticate'] == 'Basic' + response = await redeem(client, 'missing', grant_type='refresh_token') + assert response.json()['error'] == 'unsupported_grant_type' + query = params() + query['scope'] = 'openid unknown' + response = await client.get('authorize', params=query) + value = parse_qs(urlsplit(response.headers['location']).query)['code'][0] + response = await redeem(client, value) + assert response.headers['cache-control'] == 'no-store' + assert response.headers['pragma'] == 'no-cache' + token = response.json()['access_token'] + result = await client.post('userinfo', headers={'Authorization': 'Bearer '+token}) + assert list(result.json()) == ['sub'] + assert (await client.get('userinfo', params={'access_token': token})).status_code == 401 + + +async def test_expired_token_and_removed_access(oidc, db): + client, _, _ = oidc + await browser(client) + token = (await redeem(client, await code(client))).json()['access_token'] + with sqlite3.connect(db.db_path) as conn: + conn.execute('UPDATE oidc_tokens SET expires_at=0') + assert (await client.get('userinfo', headers={'Authorization': 'Bearer '+token})).status_code == 401 + token = (await redeem(client, await code(client))).json()['access_token'] + with sqlite3.connect(db.db_path) as conn: + conn.execute("UPDATE apps SET access_policy='allowlist'") + assert (await client.get('userinfo', headers={'Authorization': 'Bearer '+token})).status_code == 401 + + +@pytest.fixture +async def oidc_without_db(monkeypatch): + from types import SimpleNamespace + monkeypatch.setattr(settings, 'PUBLIC_URL', BASE) + fake = SimpleNamespace(get_app=AsyncMock(return_value={'id': 'demo', 'secret_hash': digest(SECRET), 'redirect_uris': json.dumps([URI]), 'origins': '[]'}), browser_session=AsyncMock(return_value=None)) + monkeypatch.setattr(app.state, 'db', fake, raising=False) + from src.web.dependencies import get_db + + async def fake_db(): + return fake + + monkeypatch.setattr(app, 'dependency_overrides', {**app.dependency_overrides, get_db: fake_db}) + async with httpx2.AsyncClient(transport=httpx2.ASGITransport(app=app), base_url='http://testserver') as client: + yield client + + +async def test_continuation_rejected_before_login(oidc_without_db): + query = params() + query['state'] = 'x' * 2048 + response = await oidc_without_db.get('/authorize', params=query) + assert response.status_code == 302 + target = urlsplit(response.headers['location']) + assert target.netloc == 'client.example.com' + values = parse_qs(target.query) + assert values['error'] == ['invalid_request'] + assert values['error_description'] == ['authorization request too long or invalid'] + assert values['state'] == [query['state']] + assert values['iss'] == [BASE] + + +@pytest.mark.parametrize('name', ['client_id', 'redirect_uri', 'state', 'scope', 'response_type', 'nonce', 'unknown']) +async def test_duplicate_authorization_parameters(oidc_without_db, name): + query = list(params().items()) + # Identical duplicates are also invalid; unknown parameters cannot repeat either. + query += [(name, params().get(name, 'value'))] + if name not in params(): + query += [(name, 'value')] + response = await oidc_without_db.get('/authorize', params=query) + if name in ('client_id', 'redirect_uri'): + assert response.status_code == 400 + assert 'location' not in response.headers + assert response.headers['content-type'].startswith('text/html') + else: + assert response.status_code == 302 + values = parse_qs(urlsplit(response.headers['location']).query) + assert values['error'] == ['invalid_request'] + assert values['state'] == ['state'] + assert values['iss'] == [BASE] + + +async def test_openapi_without_warnings(monkeypatch): + import warnings + monkeypatch.setattr(app, 'openapi_schema', None) + with warnings.catch_warnings(): + warnings.simplefilter('error') + async with httpx2.AsyncClient(transport=httpx2.ASGITransport(app=app), base_url='http://testserver') as client: + response = await client.get('/openapi.json') + assert response.status_code == 200 + paths = response.json()['paths']['/userinfo'] + assert paths['get']['operationId'] != paths['post']['operationId'] + + +def test_existing_key_permissions_warning(tmp_path, caplog): + key = tmp_path / 'signing.pem' + load_key(key) + assert not caplog.records + key.chmod(0o644) + with caplog.at_level('WARNING', logger='src.web.oidc'): + load_key(key) + assert 'group/others' in caplog.text + assert '0600' in caplog.text + assert key.read_text() not in caplog.text + + +async def test_lifespan_key_outside_checkout(monkeypatch): + from types import SimpleNamespace + from src.app import lifespan + root = Path(__file__).resolve().parents[1] + key = Path(settings.OIDC_KEY_FILE).resolve() + assert not key.is_relative_to(root) + database = SimpleNamespace(init_db=AsyncMock(), purge_old=AsyncMock()) + monkeypatch.setattr('src.app.SQLiteDatabase', lambda: database) + # Restore state on teardown even though lifespan assigns these attributes. + for name in ('db', 'oidc_key', 'limiter', 'login_html'): + monkeypatch.setattr(app.state, name, getattr(app.state, name, None), raising=False) + async with lifespan(app): + assert key.exists() + assert not (root / 'data/oidc-signing-key.pem').exists() + assert not (root / 'data/oidc-signing-key.pem').exists() + + +@pytest.mark.parametrize('body_auth', ['matching', 'mismatching', 'secret']) +async def test_basic_body_client_id_interop(oidc, body_auth): + import base64 + client, _, _ = oidc + await browser(client) + value = await code(client) + body = dict(grant_type='authorization_code', redirect_uri=URI, code=value, client_id='demo') + if body_auth == 'mismatching': + body['client_id'] = 'other' + if body_auth == 'secret': + body['client_secret'] = SECRET + authorization = 'Basic ' + base64.b64encode(b'demo:client-secret').decode() + response = await client.post('token', data=body, headers={'Authorization': authorization}) + if body_auth == 'matching': + assert response.status_code == 200, response.text + assert response.json()['token_type'] == 'Bearer' + else: + assert response.status_code == 401 + assert response.json()['error'] == 'invalid_client' + assert response.headers['www-authenticate'] == 'Basic'