From ae5fa31633b2142c9505ed6c58786f18ca3928a4 Mon Sep 17 00:00:00 2001 From: root Date: Thu, 22 Oct 2026 14:39:48 +0000 Subject: [PATCH] Part A: hosted login, app registry and forward auth (nginx, Traefik, Caddy) TeleLogin can now protect any app behind a reverse proxy with no app code: - Hosted browser login (/login, /sso/start, /sso/complete, /logout) with a revocable SSO session created at Telegram approval and an HttpOnly cookie delivered once; optional SSO_COOKIE_DOMAIN for sibling subdomains (public suffixes rejected offline via tldextract). - /sso/verify forward-auth endpoint (401 + X-TeleLogin-Login for nginx, redirect=1 for Traefik/Caddy) returning percent-encoded X-TeleLogin-User and a stable X-TeleLogin-User-Id (new users.public_id). - App registry with per-app access policy (allowlist|all), allowlist and trusted return origins; app-scoped redirect validation. - Operator CLI (python -m src.admin): app add/list/show/remove/policy/ allow/disallow/origin, user invite/list/remove, gen-secrets. - REGISTRATION_MODE=open|closed; API port now bound to 127.0.0.1. - Proxy examples for nginx, Traefik and Caddy (prefix and subdomain shapes), docs/INTEGRATION.md, and a real-proxy e2e suite run in CI. Built by Codex from the reviewed plan (Codex plan review, 5 rounds). Inspected twice by fresh Claude sessions; findings of the first inspection fixed by Codex. The three findings of the second inspection were fixed by Claude and are NOT covered by an independent inspection (budget exhausted, user decision): FORWARDED_ALLOW_IPS default '*' for the loopback-bound Compose port, stripping underscore identity-header variants in all proxy examples (+ e2e check), and /sso/complete persisting 'denied' after a pre-collection revoke (+ test). Verification: 119 tests pass, ruff clean, no deprecation warnings; e2e passes for nginx, Traefik and Caddy in prefix and subdomain shapes. Co-Authored-By: Claude Opus 5.5 --- .env.example | 9 + .gitattributes | 6 + .github/workflows/ci.yml | 12 ++ .gitignore | 3 + README.md | 51 ++++- docker/docker-compose.yml | 20 +- docker/env.example | 13 +- docs/INTEGRATION.md | 159 ++++++++++++++ examples/caddy/Caddyfile | 23 ++ examples/caddy/prefix.Caddyfile | 24 +++ examples/nginx/prefix.conf | 13 ++ examples/nginx/protect-app.conf | 12 ++ examples/nginx/subdomain.conf | 36 ++++ examples/nginx/telelogin.conf | 19 ++ examples/traefik/docker-labels.yml | 26 +++ examples/traefik/dynamic.yml | 40 ++++ examples/traefik/prefix.yml | 19 ++ requirements.txt | 2 + src/admin.py | 155 ++++++++++++++ src/app.py | 28 +-- src/bot.py | 12 +- src/config.py | 36 +++- src/database/sqlite.py | 95 +++++++-- src/models/user.py | 2 + src/services/auth_service.py | 4 +- src/web/routes.py | 3 + src/web/sso.py | 189 ++++++++++++++++ src/web/templates/index.html | 8 +- tests/e2e/certs/cert.pem | 20 ++ tests/e2e/certs/key.pem | 28 +++ tests/e2e/check_forward_auth.py | 81 +++++++ tests/e2e/docker-compose.e2e.yml | 47 ++++ tests/e2e/forward_auth.sh | 83 ++++++++ tests/test_admin.py | 113 ++++++++++ tests/test_phase2.py | 5 +- tests/test_sso.py | 332 +++++++++++++++++++++++++++++ 36 files changed, 1675 insertions(+), 53 deletions(-) create mode 100644 docs/INTEGRATION.md create mode 100644 examples/caddy/Caddyfile create mode 100644 examples/caddy/prefix.Caddyfile create mode 100644 examples/nginx/prefix.conf create mode 100644 examples/nginx/protect-app.conf create mode 100644 examples/nginx/subdomain.conf create mode 100644 examples/nginx/telelogin.conf create mode 100644 examples/traefik/docker-labels.yml create mode 100644 examples/traefik/dynamic.yml create mode 100644 examples/traefik/prefix.yml create mode 100644 src/admin.py create mode 100644 src/web/sso.py create mode 100644 tests/e2e/certs/cert.pem create mode 100644 tests/e2e/certs/key.pem create mode 100644 tests/e2e/check_forward_auth.py create mode 100644 tests/e2e/docker-compose.e2e.yml create mode 100755 tests/e2e/forward_auth.sh create mode 100644 tests/test_admin.py create mode 100644 tests/test_sso.py diff --git a/.env.example b/.env.example index 2dab20e..86257d1 100644 --- a/.env.example +++ b/.env.example @@ -32,3 +32,12 @@ API_PORT=8000 REFRESH_TOKEN_TTL_DAYS=30 LOGIN_HISTORY_RETENTION_DAYS=30 PURGE_INTERVAL_SECONDS=3600 + +# Public browser URL (may include a proxy-stripped path prefix) +PUBLIC_URL=http://localhost:8000 +SSO_COOKIE_NAME=tl_sso +# false only for plain HTTP local development +SSO_COOKIE_SECURE=true +# Optional shared parent domain; every subdomain must be trusted +SSO_COOKIE_DOMAIN= +REGISTRATION_MODE=open diff --git a/.gitattributes b/.gitattributes index b9c8a56..15848e2 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1 +1,7 @@ docker/entrypoint.sh text eol=lf +tests/e2e/*.sh text eol=lf +examples/nginx/*.conf text eol=lf +examples/traefik/*.yml text eol=lf +examples/caddy/* text eol=lf +tests/e2e/*.yml text eol=lf +tests/e2e/certs/*.pem text eol=lf diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 5a0afa9..2cd2225 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -78,3 +78,15 @@ jobs: - name: Tear down if: always() run: docker compose -f docker/docker-compose.yml down -v + + e2e: + name: Forward auth (${{ matrix.proxy }}) + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + proxy: [nginx, traefik, caddy] + steps: + - uses: actions/checkout@v4 + - name: Real proxy tests + run: tests/e2e/forward_auth.sh ${{ matrix.proxy }} diff --git a/.gitignore b/.gitignore index 16f607b..0610426 100644 --- a/.gitignore +++ b/.gitignore @@ -219,3 +219,6 @@ cython_debug/ marimo/_static/ marimo/_lsp/ __marimo__/ + +# Disposable real-proxy test configuration and cookie jars +tests/e2e/.run-*/ diff --git a/README.md b/README.md index 9a83718..027b6c0 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,35 @@ # TeleLogin +TeleLogin also protects apps with **forward auth**: one Telegram confirmation creates a reusable +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. + +**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 +a browser account page instead of JSON. `/health` remains unchanged. + +| Browser/SSO setting | Default | Purpose | +| --- | --- | --- | +| `PUBLIC_URL` | `http://localhost:8000` | External base URL, including any proxy-stripped prefix | +| `SSO_COOKIE_NAME` | `tl_sso` | Browser cookie name | +| `SSO_COOKIE_SECURE` | `true` | Set false only for plain HTTP local development | +| `SSO_COOKIE_DOMAIN` | empty | Host-only; set a validated trusted parent domain for sibling apps | +| `REGISTRATION_MODE` | `open` | `closed` requires CLI user invitations | + +| Browser endpoint | Method | Purpose | +| --- | --- | --- | +| `/` | GET | Account page with sign-in/logout | +| `/login?app=ID&rd=URL` | GET | Hosted Telegram login | +| `/sso/start` | POST JSON | Begin browser login (username, optional app and rd) | +| `/sso/complete` | POST JSON | Poll login_id; deliver browser cookie once | +| `/sso/verify` | GET | Proxy forward-auth; app header/query, optional redirect=1 | +| `/logout?app=ID&rd=URL` | GET | Logout confirmation | +| `/sso/logout` | POST JSON/form | Revoke browser session, clear cookie, redirect | + + + Telegram login confirmation using FastAPI, a Telegram bot and SQLite. Python 3.11+. ## Features @@ -108,7 +138,7 @@ Both templates declare all supported variables. Required secrets must be supplie | API_PORT | 8000; host published port in Compose (internal API stays 8000) | | API_BASE_URL | http://api:8000 (Docker), http://localhost:8000 (local template); bot calls API | | BOT_NOTIFY_URL | http://bot:8001/notify-login (Docker), localhost:8001 (local template); API calls bot | -| FORWARDED_ALLOW_IPS | 127.0.0.1; trusted proxy addresses | +| FORWARDED_ALLOW_IPS | Trusted proxy addresses. 127.0.0.1 when running uvicorn directly; the Docker Compose default is `*` because the port is published on 127.0.0.1 only | ## Flow Overview @@ -139,8 +169,8 @@ Both templates declare all supported variables. Required secrets must be supplie | Method and path | Behavior | | --- | --- | -| GET / | JSON service information | -| GET /login | Browser login page | +| GET / | Browser account page (HTML) | +| 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 | | POST /auth/link-telegram | Internal: {"token":"...","telegram_id":42}; atomic single-use registration link | @@ -185,7 +215,8 @@ once. Concurrent requests share a refresh promise; storage is rechecked before refresh. Where available, Web Locks serializes refreshes across browser tabs using `telelogin-refresh`. Without Web Locks, simultaneous refreshes across tabs remain possible and can trigger reuse revocation. `login(username, onStatusChange, onCode)` -exposes the browser code through `onCode`. The `/login` page uses sessionStorage. +exposes the browser code through `onCode`. The `/login` page uses the SSO cookie flow. The raw API and JavaScript client +are the option for storing tokens in the browser. Telegram commands (private chat only — in groups the bot refuses them, so IPs and browsers are never shown to other members): `/status` shows the linked account and last five login requests; @@ -273,10 +304,14 @@ the response. Registration still reveals duplicate usernames. Keep login IDs and Rate limits are in memory: run one worker; limits are not shared across instances. Username limits allow an attacker to temporarily lock out a known username. -Terminate HTTPS at Caddy or Nginx. Set FORWARDED_ALLOW_IPS to the actual proxy IP(s) -so Uvicorn can use forwarded client addresses for IP limits. The loopback default trusts -only local proxies. Restrict network access to the API and notification service; do not -trust arbitrary forwarded headers or use '*' on an externally reachable API. +Terminate HTTPS at a reverse proxy (nginx, Traefik or Caddy). Uvicorn must trust the proxy so +that IP rate limits and the IP shown in Telegram confirmations are the real client address. A +proxy on the host reaches the container through the Docker gateway (e.g. 172.17.0.1), never +from 127.0.0.1, so the Compose default is `FORWARDED_ALLOW_IPS=*`, which is safe only because the +API port is published on 127.0.0.1. If you publish the port on another interface, set the proxy's +exact address instead. When running uvicorn directly on the host, 127.0.0.1 is correct. Restrict +network access to the API and notification service and never use '*' on an externally reachable +API. Privacy: real linked login requests and sessions record the requesting IP and user-agent (at most 200 characters; notifications show at most 100). Fictitious diff --git a/docker/docker-compose.yml b/docker/docker-compose.yml index 37a4b62..8228886 100644 --- a/docker/docker-compose.yml +++ b/docker/docker-compose.yml @@ -5,7 +5,7 @@ services: context: .. dockerfile: docker/Dockerfile ports: - - "${API_PORT:-8000}:8000" + - "127.0.0.1:${API_PORT:-8000}:8000" environment: - BOT_TOKEN=${BOT_TOKEN} - BOT_USERNAME=${BOT_USERNAME:-YourBot} @@ -14,12 +14,19 @@ services: - INTERNAL_API_KEY=${INTERNAL_API_KEY} - API_BASE_URL=${API_BASE_URL:-http://api:8000} - BOT_NOTIFY_URL=${BOT_NOTIFY_URL:-http://bot:8001/notify-login} - - FORWARDED_ALLOW_IPS=${FORWARDED_ALLOW_IPS:-127.0.0.1} + # '*' is safe only because the port is published on 127.0.0.1: a proxy on the host reaches + # the container from the Docker gateway address, never from 127.0.0.1. + - FORWARDED_ALLOW_IPS=${FORWARDED_ALLOW_IPS:-*} - ALGORITHM=${ALGORITHM:-HS256} - ACCESS_TOKEN_EXPIRE_MINUTES=${ACCESS_TOKEN_EXPIRE_MINUTES:-15} - REFRESH_TOKEN_TTL_DAYS=${REFRESH_TOKEN_TTL_DAYS:-30} - LOGIN_HISTORY_RETENTION_DAYS=${LOGIN_HISTORY_RETENTION_DAYS:-30} - PURGE_INTERVAL_SECONDS=${PURGE_INTERVAL_SECONDS:-3600} + - PUBLIC_URL=${PUBLIC_URL:-http://localhost:8000} + - SSO_COOKIE_NAME=${SSO_COOKIE_NAME:-tl_sso} + - SSO_COOKIE_SECURE=${SSO_COOKIE_SECURE:-true} + - SSO_COOKIE_DOMAIN=${SSO_COOKIE_DOMAIN:-} + - REGISTRATION_MODE=${REGISTRATION_MODE:-open} - DEBUG=${DEBUG:-false} - CORS_ORIGINS=${CORS_ORIGINS:-[]} - LOGIN_REQUEST_TTL_SECONDS=${LOGIN_REQUEST_TTL_SECONDS:-120} @@ -54,12 +61,19 @@ services: - INTERNAL_API_KEY=${INTERNAL_API_KEY} - API_BASE_URL=${API_BASE_URL:-http://api:8000} - BOT_NOTIFY_URL=${BOT_NOTIFY_URL:-http://bot:8001/notify-login} - - FORWARDED_ALLOW_IPS=${FORWARDED_ALLOW_IPS:-127.0.0.1} + # '*' is safe only because the port is published on 127.0.0.1: a proxy on the host reaches + # the container from the Docker gateway address, never from 127.0.0.1. + - FORWARDED_ALLOW_IPS=${FORWARDED_ALLOW_IPS:-*} - ALGORITHM=${ALGORITHM:-HS256} - ACCESS_TOKEN_EXPIRE_MINUTES=${ACCESS_TOKEN_EXPIRE_MINUTES:-15} - REFRESH_TOKEN_TTL_DAYS=${REFRESH_TOKEN_TTL_DAYS:-30} - LOGIN_HISTORY_RETENTION_DAYS=${LOGIN_HISTORY_RETENTION_DAYS:-30} - PURGE_INTERVAL_SECONDS=${PURGE_INTERVAL_SECONDS:-3600} + - PUBLIC_URL=${PUBLIC_URL:-http://localhost:8000} + - SSO_COOKIE_NAME=${SSO_COOKIE_NAME:-tl_sso} + - SSO_COOKIE_SECURE=${SSO_COOKIE_SECURE:-true} + - SSO_COOKIE_DOMAIN=${SSO_COOKIE_DOMAIN:-} + - REGISTRATION_MODE=${REGISTRATION_MODE:-open} - DEBUG=${DEBUG:-false} - LOGIN_REQUEST_TTL_SECONDS=${LOGIN_REQUEST_TTL_SECONDS:-120} volumes: diff --git a/docker/env.example b/docker/env.example index 5a211b1..4d6acc4 100644 --- a/docker/env.example +++ b/docker/env.example @@ -28,8 +28,19 @@ CORS_ORIGINS=[] API_BASE_URL=http://api:8000 BOT_NOTIFY_URL=http://bot:8001/notify-login -FORWARDED_ALLOW_IPS=127.0.0.1 +# A host proxy reaches the container from the Docker gateway (e.g. 172.17.0.1), not 127.0.0.1. +# '*' is safe only while the API port is published on 127.0.0.1 (the compose default). +FORWARDED_ALLOW_IPS=* REFRESH_TOKEN_TTL_DAYS=30 LOGIN_HISTORY_RETENTION_DAYS=30 PURGE_INTERVAL_SECONDS=3600 + +# Public browser URL (may include a proxy-stripped path prefix) +PUBLIC_URL=http://localhost:8000 +SSO_COOKIE_NAME=tl_sso +# false only for plain HTTP local development +SSO_COOKIE_SECURE=true +# Optional shared parent domain; every subdomain must be trusted +SSO_COOKIE_DOMAIN= +REGISTRATION_MODE=open diff --git a/docs/INTEGRATION.md b/docs/INTEGRATION.md new file mode 100644 index 0000000..a43aee1 --- /dev/null +++ b/docs/INTEGRATION.md @@ -0,0 +1,159 @@ +# Integrating an app with TeleLogin + +TeleLogin is self-hosted: the operator owns the bot, registers trusted apps and controls access. +One Telegram confirmation creates a browser session lasting `REFRESH_TOKEN_TTL_DAYS` (30 days by + default). Connected apps reuse it. No app consent screen is shown: register only apps you trust. + +## Which mode do I need? + +| Mode | Use when | Integration | +| --- | --- | --- | +| Forward auth (Mode 2) | Your app shares TeleLogin's origin or a trusted parent domain | Reverse proxy configuration; no app login code | +| OpenID Connect (Mode 1) | An app uses a standard OIDC library or an unrelated domain | Coming in a later release | +| Raw API | You need a custom login UI and token lifecycle | Existing `/register` and `/auth/*` API, [README](../README.md) | + +## Mode 2: forward auth + +1. Configure `PUBLIC_URL` to the externally visible TeleLogin base URL, without a trailing slash. + Set up your bot and API as described in the README. Register a user via `POST /register` and + follow the returned Telegram link, or invite one with + `docker compose -f docker/docker-compose.yml exec api python -m src.admin user invite alice`. + With `REGISTRATION_MODE=closed`, only CLI invitations create users. +2. Register your app on the server: + ```sh + docker compose -f docker/docker-compose.yml exec api python -m src.admin app add myapp --name 'My App' + docker compose -f docker/docker-compose.yml exec api python -m src.admin app allow myapp alice + ``` + Default policy is `allowlist`; each username must already exist and be linked to Telegram. + To allow every registered, linked user instead: + ```sh + docker compose -f docker/docker-compose.yml exec api python -m src.admin app policy myapp all + ``` +3. Choose a deployment shape: + + | Shape | Settings | App return URLs | + | --- | --- | --- | + | Shared host, prefix | `PUBLIC_URL=https://example.com/telelogin`, empty `SSO_COOKIE_DOMAIN` | Same origin, e.g. `https://example.com/demo/` | + | Own subdomain, sibling app | `PUBLIC_URL=https://auth.example.com`, `SSO_COOKIE_DOMAIN=example.com` | Register each app origin, e.g. `https://app.example.com` | + + In the sibling shape, restart API and bot with the updated settings, then run: + ```sh + docker compose -f docker/docker-compose.yml exec api python -m src.admin app origin add myapp https://app.example.com + ``` + The origin must receive the configured cookie. Origins have no path, query or fragment. HTTPS + is required except localhost/127.0.0.1 development. Cookie domains must be a non-public parent + of the public host: `co.uk`, `github.io`, IPs and leading dots are rejected. Validation uses an + offline bundled Public Suffix List, including private suffixes. +4. Install a proxy configuration from the examples below. Replace hostnames, upstreams and `myapp` + with your values. The proxy strips `/telelogin` for the prefix shape: API routes remain at `/`. + Every generated absolute link uses `PUBLIC_URL`; browser fetches are prefix-relative. +5. Read `X-TeleLogin-User` in your app. It is UTF-8 percent-encoded; URL-decode it with e.g. + `urllib.parse.unquote(value)` in Python. `X-TeleLogin-User-Id` is the stable UUID identity. + Unicode, spaces, percent signs and control characters remain safe in the ASCII header. +6. Link to `PUBLIC_URL/logout?app=myapp&rd=`. GET only asks for + confirmation; POST revokes the browser session and clears its cookie. Other connected apps + require a new confirmation on their next protected request. + +## Proxy examples + +These configs target **nginx 1.29**, **Traefik v3.5**, and **Caddy 2.10**. The real-proxy harness is +`tests/e2e/forward_auth.sh nginx|traefik|caddy`. Run each separately from the repository root with +Docker Compose, bash, curl and python3. It builds the API locally and uses disposable containers. +It uses the shipped TLS configs with only app-id/upstream substitutions and a checked-in public +self-signed test certificate (`curl --insecure` only in the harness). +All three proxies cover both the prefix and sibling-subdomain shapes. No real bot is needed. +Local ports default to 18080 (proxy) and 18000 (internal test API); override `E2E_PORT` and +`E2E_API_PORT` if necessary. The API test port is bound to loopback and removed afterward. + +### nginx + +For a shared host, copy [telelogin.conf](../examples/nginx/telelogin.conf) and +[protect-app.conf](../examples/nginx/protect-app.conf) into `/etc/nginx/`, then adapt the +[prefix server](../examples/nginx/prefix.conf). For sibling subdomains use +[subdomain.conf](../examples/nginx/subdomain.conf) and the same `protect-app.conf`. +The app id is `set $telelogin_app myapp` in the protection snippet, included inside the app location. +Install your own TLS certificate/key at the paths shown in the server blocks. The app upstream placeholder is `127.0.0.1:9000`. + +nginx uses `auth_request`: 401 becomes a 302 via `X-TeleLogin-Login` and a named location. +TeleLogin has already encoded that login URL. The snippet overwrites both identity headers and +blocks public access to `/internal/*`. Keep the verify location `internal`. + +### Traefik + +Load [dynamic.yml](../examples/traefik/dynamic.yml) through the file provider, replacing the app +upstream `echo:80`, and enable a TLS entrypoint; install your certificate/key at the shown paths. The app id is in the +forwardAuth `address` query. Set `trustForwardHeader: false`; the header-removal middleware must +run before forwardAuth. `authResponseHeaders` copies TeleLogin's verified identity into the app +request. `redirect=1` makes unauthenticated responses directly redirect browsers. + +For a shared host replace its routers with [prefix.yml](../examples/traefik/prefix.yml), merging +its `telelogin-prefix` middleware into the existing middlewares map. This strips the public prefix +only on the TeleLogin router. [docker-labels.yml](../examples/traefik/docker-labels.yml) provides an +alternative Docker-provider override, including prefix instructions (same rules as dynamic.yml, +not run by the e2e test). Attach proxy, API and app to +a shared private Docker network and disable the API's published port. + +### Caddy + +Adapt [Caddyfile](../examples/caddy/Caddyfile) for sibling subdomains, or +[prefix.Caddyfile](../examples/caddy/prefix.Caddyfile) for a shared host. Install your certificate/key at the paths shown (or replace the `tls` directive with your +normal Caddy certificate automation). The app id is the `app=myapp` query in `forward_auth`'s `uri`. The `route` block +preserves header-removal-before-auth ordering, then `copy_headers` supplies the verified identity. +`handle_path /telelogin/*` strips the prefix in the shared-host shape. + +## Security and operation + +- Trust `X-TeleLogin-*` identity headers only from your proxy. The app must be reachable only + through that proxy; every configuration overwrites or strips client-supplied identity headers, including the + underscore variants (`X_TeleLogin_User`), because some app servers (CGI/FastCGI such as PHP-FPM, + some WSGI servers) treat `_` and `-` as the same header name. +- `SSO_COOKIE_DOMAIN` shares the browser credential with **every subdomain** of that domain. + Use it only when all subdomains are trusted. A registered app origin controls redirects; it + does not isolate cookies. Unrelated domains require Mode 1 in a later release. +- Keep `SSO_COOKIE_SECURE=true` for HTTPS. Set false only for plain HTTP local development. + Cookies are HttpOnly, SameSite=Lax, Path=/; empty domain means host-only. Browser POST endpoints + require JSON (logout also accepts form data) and reject an Origin other than `PUBLIC_URL`'s + origin. Raw API CORS settings do not enable CORS on `/sso/*`. +- The development Compose API port is now **127.0.0.1:${API_PORT:-8000}**, a breaking deployment + change. A proxy on the host reaches the container from the Docker gateway address (e.g. + 172.17.0.1), not 127.0.0.1, so a `127.0.0.1` value never matches and every visitor would share + one IP for rate limits and Telegram confirmations; the Compose default is therefore + `FORWARDED_ALLOW_IPS='*'`, safe only while the port is published on 127.0.0.1. Docker proxies should remove published ports and use a private shared network; + set `FORWARDED_ALLOW_IPS` to that network's range, or `*` only when nothing else can reach the + container. Proxies must set `X-Forwarded-For`. Never expose `/internal/*` publicly. +- `/sso/verify` returns 200 with identity for allowed users, 401 (or 302 with `redirect=1`) for + missing/revoked/expired sessions, and 403 for authenticated users without app access. Header + `X-TeleLogin-App` and query `app` must agree when both are sent. All responses are `no-store`. +- Revoke sessions using the bot's `/sessions` (`browser` versus `app/API`) or revoke-all controls. + `/auth/logout-all` revokes both kinds. Unlink/delete removes the account, sessions and allowlist + memberships. Return URLs are app-scoped and default to `PUBLIC_URL/` if invalid. + +## Operator CLI + +Run `python -m src.admin --help` on the server (or `docker compose … exec api python -m src.admin`). +Shell access is admin access. `gen-secrets` needs no `.env` or database and prints random +`SECRET_KEY` and `INTERNAL_API_KEY` assignments. Never share them. + +```text +app add ID --name NAME [--policy allowlist|all] +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 +user invite USERNAME | user list | user remove USERNAME +gen-secrets +``` + +`user invite` prints a one-use expiring Telegram link; `user remove` has the same deletion cascade +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. + +## Advanced: custom UI with the raw API + +The existing `/register`, `/auth/*`, `/internal/*` and JavaScript client retain their API behavior. +See the [API documentation and JS client](../README.md). Raw API clients own their login page, +number-matching polling, token storage/rotation and logout. Browser SSO cookies cannot be used as +API refresh tokens, and API tokens cannot authorize forward-auth requests. diff --git a/examples/caddy/Caddyfile b/examples/caddy/Caddyfile new file mode 100644 index 0000000..206e6e5 --- /dev/null +++ b/examples/caddy/Caddyfile @@ -0,0 +1,23 @@ +# Caddy 2.10. PUBLIC_URL=https://auth.example.com; SSO_COOKIE_DOMAIN=example.com. +auth.example.com { + tls /etc/caddy/certs/cert.pem /etc/caddy/certs/key.pem + @internal path /internal/* + respond @internal 404 + reverse_proxy telelogin:8000 +} +app.example.com { + tls /etc/caddy/certs/cert.pem /etc/caddy/certs/key.pem + route { + request_header -X-TeleLogin-User + request_header -X-TeleLogin-User-Id + # Underscore variants: some app servers (CGI/FastCGI, some WSGI) treat _ like -. + request_header -X_TeleLogin_User + request_header -X_TeleLogin_User_Id + # myapp is the id registered with src.admin app add. + forward_auth telelogin:8000 { + uri /sso/verify?app=myapp&redirect=1 + copy_headers X-TeleLogin-User X-TeleLogin-User-Id + } + reverse_proxy echo:80 + } +} diff --git a/examples/caddy/prefix.Caddyfile b/examples/caddy/prefix.Caddyfile new file mode 100644 index 0000000..e1ddec6 --- /dev/null +++ b/examples/caddy/prefix.Caddyfile @@ -0,0 +1,24 @@ +# Alternative deployment: PUBLIC_URL=https://example.com/telelogin (host-only cookie). +example.com { + tls /etc/caddy/certs/cert.pem /etc/caddy/certs/key.pem + handle /telelogin/internal/* { + respond 404 + } + handle_path /telelogin/* { + reverse_proxy telelogin:8000 + } + handle /demo/* { + route { + request_header -X-TeleLogin-User + request_header -X-TeleLogin-User-Id + # Underscore variants: some app servers (CGI/FastCGI, some WSGI) treat _ like -. + request_header -X_TeleLogin_User + request_header -X_TeleLogin_User_Id + forward_auth telelogin:8000 { + uri /sso/verify?app=myapp&redirect=1 + copy_headers X-TeleLogin-User X-TeleLogin-User-Id + } + reverse_proxy echo:80 + } + } +} diff --git a/examples/nginx/prefix.conf b/examples/nginx/prefix.conf new file mode 100644 index 0000000..055459f --- /dev/null +++ b/examples/nginx/prefix.conf @@ -0,0 +1,13 @@ +# http {} scope; PUBLIC_URL=https://example.com/telelogin. +# Install your TLS certificate and key at the paths below. +server { + listen 443 ssl; + ssl_certificate /etc/nginx/certs/cert.pem; + ssl_certificate_key /etc/nginx/certs/key.pem; + server_name example.com; + include /etc/nginx/telelogin.conf; + location /demo/ { + include /etc/nginx/protect-app.conf; + proxy_pass http://127.0.0.1:9000; + } +} diff --git a/examples/nginx/protect-app.conf b/examples/nginx/protect-app.conf new file mode 100644 index 0000000..68ec820 --- /dev/null +++ b/examples/nginx/protect-app.conf @@ -0,0 +1,12 @@ +# Include inside the app location. Register this id with src.admin app add. +set $telelogin_app myapp; +auth_request /_telelogin_verify; +auth_request_set $telelogin_user $upstream_http_x_telelogin_user; +auth_request_set $telelogin_user_id $upstream_http_x_telelogin_user_id; +auth_request_set $telelogin_login $upstream_http_x_telelogin_login; +error_page 401 = @telelogin_login; +proxy_set_header X-TeleLogin-User $telelogin_user; +proxy_set_header X-TeleLogin-User-Id $telelogin_user_id; +# nginx drops underscore headers unless underscores_in_headers is on; strip them anyway. +proxy_set_header X_TeleLogin_User ""; +proxy_set_header X_TeleLogin_User_Id ""; diff --git a/examples/nginx/subdomain.conf b/examples/nginx/subdomain.conf new file mode 100644 index 0000000..18338de --- /dev/null +++ b/examples/nginx/subdomain.conf @@ -0,0 +1,36 @@ +# http {} scope. PUBLIC_URL=https://auth.example.com; SSO_COOKIE_DOMAIN=example.com. +# Install your TLS certificate and key at the paths below. +server { + listen 443 ssl; + ssl_certificate /etc/nginx/certs/cert.pem; + ssl_certificate_key /etc/nginx/certs/key.pem; + server_name auth.example.com; + location ^~ /internal/ { return 404; } + location / { + proxy_pass http://127.0.0.1:8000; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + proxy_set_header X-Forwarded-Host $http_host; + } +} +server { + listen 443 ssl; + ssl_certificate /etc/nginx/certs/cert.pem; + ssl_certificate_key /etc/nginx/certs/key.pem; + server_name app.example.com; + location = /_telelogin_verify { + internal; + proxy_pass http://127.0.0.1:8000/sso/verify; + proxy_method GET; + proxy_pass_request_body off; + proxy_set_header Content-Length ""; + proxy_set_header X-TeleLogin-App $telelogin_app; + proxy_set_header X-Original-URL $scheme://$http_host$request_uri; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + } + location @telelogin_login { return 302 $telelogin_login; } + location / { + include /etc/nginx/protect-app.conf; + proxy_pass http://127.0.0.1:9000; + } +} diff --git a/examples/nginx/telelogin.conf b/examples/nginx/telelogin.conf new file mode 100644 index 0000000..a4c27c5 --- /dev/null +++ b/examples/nginx/telelogin.conf @@ -0,0 +1,19 @@ +# Include at server scope on example.com; PUBLIC_URL=https://example.com/telelogin. +location ^~ /telelogin/internal/ { return 404; } +location ^~ /telelogin/ { + proxy_pass http://127.0.0.1:8000/; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + proxy_set_header X-Forwarded-Host $http_host; +} +location = /_telelogin_verify { + internal; + proxy_pass http://127.0.0.1:8000/sso/verify; + proxy_method GET; + proxy_pass_request_body off; + proxy_set_header Content-Length ""; + proxy_set_header X-TeleLogin-App $telelogin_app; + proxy_set_header X-Original-URL $scheme://$http_host$request_uri; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; +} +location @telelogin_login { return 302 $telelogin_login; } diff --git a/examples/traefik/docker-labels.yml b/examples/traefik/docker-labels.yml new file mode 100644 index 0000000..3690cf8 --- /dev/null +++ b/examples/traefik/docker-labels.yml @@ -0,0 +1,26 @@ +# Compose override fragment. Configure Traefik's Docker provider and a shared network. +# TeleLogin must not publish its API port in this Docker-proxy shape. +services: + api: + labels: + - traefik.enable=true + - traefik.http.routers.auth.rule=Host(`auth.example.com`) && !PathPrefix(`/internal/`) + - traefik.http.routers.auth.tls=true + - traefik.http.services.telelogin.loadbalancer.server.port=8000 + - traefik.http.middlewares.telelogin-auth.forwardauth.address=http://api:8000/sso/verify?app=myapp&redirect=1 + - traefik.http.middlewares.telelogin-auth.forwardauth.trustForwardHeader=false + - traefik.http.middlewares.telelogin-auth.forwardauth.authResponseHeaders=X-TeleLogin-User,X-TeleLogin-User-Id + - traefik.http.middlewares.strip-identity.headers.customrequestheaders.X-TeleLogin-User= + - traefik.http.middlewares.strip-identity.headers.customrequestheaders.X-TeleLogin-User-Id= + - traefik.http.middlewares.strip-identity.headers.customrequestheaders.X_TeleLogin_User= + - traefik.http.middlewares.strip-identity.headers.customrequestheaders.X_TeleLogin_User_Id= + your-app: + labels: + - traefik.enable=true + - traefik.http.routers.app.rule=Host(`app.example.com`) + - traefik.http.routers.app.tls=true + - traefik.http.routers.app.middlewares=strip-identity,telelogin-auth + - traefik.http.services.app.loadbalancer.server.port=9000 +# Prefix alternative: change auth rule to Host(`example.com`) && PathPrefix(`/telelogin/`) +# && !PathPrefix(`/telelogin/internal/`), add router auth.middlewares=telelogin-prefix, +# and middleware telelogin-prefix.stripprefix.prefixes=/telelogin. diff --git a/examples/traefik/dynamic.yml b/examples/traefik/dynamic.yml new file mode 100644 index 0000000..e0d64b9 --- /dev/null +++ b/examples/traefik/dynamic.yml @@ -0,0 +1,40 @@ +# Traefik v3.5 file provider. PUBLIC_URL=https://auth.example.com. +# Configure a TLS entrypoint and install your certificate/key at the paths below. +http: + routers: + auth: + rule: 'Host(`auth.example.com`) && !PathPrefix(`/internal/`)' + tls: {} + service: telelogin + app: + rule: 'Host(`app.example.com`)' + tls: {} + service: demo + middlewares: [strip-identity, telelogin-auth] + middlewares: + strip-identity: + headers: + customRequestHeaders: + X-TeleLogin-User: '' + X-TeleLogin-User-Id: '' + # Underscore variants: some app servers (CGI/FastCGI, some WSGI) treat _ like -. + X_TeleLogin_User: '' + X_TeleLogin_User_Id: '' + telelogin-auth: + forwardAuth: + # myapp is the registered app id; the response redirects unauthenticated browsers. + address: http://telelogin:8000/sso/verify?app=myapp&redirect=1 + authResponseHeaders: [X-TeleLogin-User, X-TeleLogin-User-Id] + trustForwardHeader: false + services: + telelogin: + loadBalancer: + servers: [{url: 'http://telelogin:8000'}] + demo: + loadBalancer: + servers: [{url: 'http://echo:80'}] + +tls: + certificates: + - certFile: /etc/traefik/certs/cert.pem + keyFile: /etc/traefik/certs/key.pem diff --git a/examples/traefik/prefix.yml b/examples/traefik/prefix.yml new file mode 100644 index 0000000..38f7033 --- /dev/null +++ b/examples/traefik/prefix.yml @@ -0,0 +1,19 @@ +# Alternative routers: merge with dynamic.yml's middlewares/services, replacing routers. +# PUBLIC_URL=https://example.com/telelogin. +http: + routers: + auth: + rule: 'Host(`example.com`) && PathPrefix(`/telelogin/`) && !PathPrefix(`/telelogin/internal/`)' + priority: 100 + tls: {} + service: telelogin + middlewares: [telelogin-prefix] + app: + rule: 'Host(`example.com`) && PathPrefix(`/demo/`)' + tls: {} + service: demo + middlewares: [strip-identity, telelogin-auth] + middlewares: + telelogin-prefix: + stripPrefix: + prefixes: [/telelogin] diff --git a/requirements.txt b/requirements.txt index eb63dcb..2be3165 100644 --- a/requirements.txt +++ b/requirements.txt @@ -7,3 +7,5 @@ httpx==0.28.1 python-telegram-bot==22.8 aiosqlite==0.22.1 PyJWT==2.15.1 + +tldextract==5.4.0 diff --git a/src/admin.py b/src/admin.py new file mode 100644 index 0000000..e2c9970 --- /dev/null +++ b/src/admin.py @@ -0,0 +1,155 @@ +"""Operator CLI. Shell access is administrative access.""" +import argparse +import asyncio +import json +import re +import secrets +import sys +import time +from urllib.parse import urlsplit + + +def parser(): + p = argparse.ArgumentParser(description=__doc__) + sub = p.add_subparsers(dest='group', required=True) + sub.add_parser('gen-secrets') + apps = sub.add_parser('app').add_subparsers(dest='action', required=True) + add = apps.add_parser('add') + add.add_argument('id') + add.add_argument('--name', required=True) + add.add_argument('--policy', choices=['allowlist', 'all'], default='allowlist') + apps.add_parser('list') + for action in ('show', 'remove'): + apps.add_parser(action).add_argument('id') + policy = apps.add_parser('policy') + policy.add_argument('id') + policy.add_argument('policy', choices=['allowlist', 'all']) + for action in ('allow', 'disallow'): + a = apps.add_parser(action) + a.add_argument('id') + a.add_argument('username') + origins = apps.add_parser('origin').add_subparsers(dest='operation', required=True) + for action in ('add', 'remove'): + a = origins.add_parser(action) + a.add_argument('id') + a.add_argument('origin') + users = sub.add_parser('user').add_subparsers(dest='action', required=True) + users.add_parser('list') + for action in ('invite', 'remove'): + users.add_parser(action).add_argument('username') + return p + + +def validated_origin(value): + from src.config import settings + from src.web.sso import origin + parsed = urlsplit(value) + normalized = origin(value) + if (parsed.path or parsed.query or parsed.fragment or '\\' in value + or (parsed.scheme != 'https' and parsed.hostname not in ('localhost', '127.0.0.1'))): + raise ValueError('Origin must be https://host[:port] (http allowed only for localhost/127.0.0.1)') + host = parsed.hostname.lower() + domain = settings.SSO_COOKIE_DOMAIN + if host != urlsplit(settings.PUBLIC_URL).hostname and not (domain and (host == domain or host.endswith('.' + domain))): + raise ValueError('Origin cannot receive the cookie; configure SSO_COOKIE_DOMAIN to a shared parent domain') + return normalized + + +async def run(args): + import aiosqlite + from src.database.sqlite import SQLiteDatabase + from src.services.token_service import TokenService + if args.group == 'user' and args.action == 'invite': + from src.web.schemas import RegisterRequest + args.username = RegisterRequest(username=args.username).username + db = SQLiteDatabase() + await db.init_db() + if args.group == 'user': + if args.action == 'invite': + try: + user = await db.create_user(args.username) + except aiosqlite.IntegrityError: + raise ValueError('Username already exists') from None + tokens = TokenService(db) + print(tokens.create_telegram_link(await tokens.generate_registration_token(user.id))) + return + async with aiosqlite.connect(db.db_path) as conn: + conn.row_factory = aiosqlite.Row + if args.action == 'list': + rows = await (await conn.execute('SELECT username,telegram_id,public_id FROM users ORDER BY username')).fetchall() + print(json.dumps([dict(r) for r in rows], ensure_ascii=False)) + return + await conn.execute('BEGIN IMMEDIATE') + 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'): + 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 + async with aiosqlite.connect(db.db_path) as conn: + conn.row_factory = aiosqlite.Row + await conn.execute('BEGIN IMMEDIATE') + if args.action == 'list': + rows = await (await conn.execute('SELECT id,name,access_policy,origins FROM apps ORDER BY id')).fetchall() + print(json.dumps([dict(r) for r in rows], ensure_ascii=False)) + return + 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())) + else: + app = await (await conn.execute('SELECT * FROM apps WHERE id=?', (args.id,))).fetchone() + if not app: + raise ValueError('Unknown app') + if args.action == 'show': + data = dict(app) + data.pop('secret_hash') + data['allowlist'] = [r[0] for r in await (await conn.execute('SELECT u.username FROM app_users a JOIN users u ON u.id=a.user_id WHERE a.app_id=? ORDER BY u.username', (args.id,))).fetchall()] + print(json.dumps(data, ensure_ascii=False)) + return + if args.action == 'remove': + await conn.execute('DELETE FROM app_users WHERE app_id=?', (args.id,)) + await conn.execute('DELETE FROM apps WHERE id=?', (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'): + user = await (await conn.execute('SELECT id,telegram_id FROM users WHERE username=?', (args.username,))).fetchone() + if not user: + raise ValueError('Unknown username') + if args.action == 'allow': + if user['telegram_id'] is None: + raise ValueError('user exists but has not linked Telegram yet') + await conn.execute('INSERT OR IGNORE INTO app_users VALUES (?,?)', (args.id, user[0])) + else: + await conn.execute('DELETE FROM app_users WHERE app_id=? AND user_id=?', (args.id, user[0])) + elif args.action == 'origin': + from src.web.sso import origin + value = validated_origin(args.origin) if args.operation == 'add' else origin(args.origin) + origins = json.loads(app['origins']) + if args.operation == 'add' and value not in origins: + origins.append(value) + if args.operation == 'remove' and value in origins: + origins.remove(value) + await conn.execute('UPDATE apps SET origins=? WHERE id=?', (json.dumps(origins), args.id)) + await conn.commit() + print('OK') + + +def main(): + args = parser().parse_args() + if args.group == 'gen-secrets': + print('SECRET_KEY=' + secrets.token_urlsafe(32)) + print('INTERNAL_API_KEY=' + secrets.token_urlsafe(32)) + return + try: + asyncio.run(run(args)) + except Exception as exc: + print(f'Error: {exc}', file=sys.stderr) + sys.exit(1) + + +if __name__ == '__main__': + main() diff --git a/src/app.py b/src/app.py index e02bc2e..c092671 100644 --- a/src/app.py +++ b/src/app.py @@ -6,7 +6,6 @@ import asyncio import logging from pathlib import Path -from fastapi.responses import HTMLResponse from src.web.dependencies import get_db from src.web.security import RateLimiter from fastapi import Depends @@ -17,10 +16,15 @@ from src.config import settings from src.database.sqlite import SQLiteDatabase from src.web.routes import router +from src.web.sso import router as sso_router @asynccontextmanager async def lifespan(app: FastAPI): + if settings.PUBLIC_URL == "http://localhost:8000" and not settings.DEBUG: + logging.getLogger(__name__).warning("PUBLIC_URL is still the localhost default with DEBUG=false") + if settings.PUBLIC_URL.startswith("https:") and not settings.SSO_COOKIE_SECURE: + logging.getLogger(__name__).warning("PUBLIC_URL uses HTTPS but SSO_COOKIE_SECURE=false") # Startup: Initialize database tables app.state.db = SQLiteDatabase() await app.state.db.init_db() @@ -53,9 +57,17 @@ async def purge(): lifespan=lifespan ) +class APICORSMiddleware(CORSMiddleware): + async def __call__(self, scope, receive, send): + if scope.get('path', '').startswith('/sso/'): + await self.app(scope, receive, send) + else: + await super().__call__(scope, receive, send) + + # Configure CORS for browser clients app.add_middleware( - CORSMiddleware, + APICORSMiddleware, allow_origins=settings.CORS_ORIGINS, # In production, specify your frontend domain allow_credentials=True, allow_methods=["*"], @@ -64,17 +76,7 @@ async def purge(): # Include routes app.include_router(router) - -@app.get("/") -async def root(): - return {"message": "TeleLogin API", "status": "running"} - - - -@app.get("/login", response_class=HTMLResponse) -async def login(): - return HTMLResponse(app.state.login_html) - +app.include_router(sso_router) @app.get("/health") async def health(db=Depends(get_db)): diff --git a/src/bot.py b/src/bot.py index de45123..e550e2a 100644 --- a/src/bot.py +++ b/src/bot.py @@ -174,7 +174,7 @@ async def sessions_command(self, update, context): return sessions = sorted(response.json()['sessions'], key=lambda row: (row['last_used_at'] if row['last_used_at'] is not None else row['created_at'], row['created_at'], row['id']), reverse=True) for row in sessions[:10]: - await update.message.reply_text(f"Created: {row['created_at']}\nLast used: {row['last_used_at']}\nIP: {row['ip']}\nBrowser: {row['user_agent']}", reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton('Revoke', callback_data=f"revoke_session:{row['id']}")]])) + await update.message.reply_text(f"Type: {'browser' if row.get('kind') == 'sso' else 'app/API'}\nCreated: {row['created_at']}\nLast used: {row['last_used_at']}\nIP: {row['ip']}\nBrowser: {row['user_agent']}", reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton('Revoke', callback_data=f"revoke_session:{row['id']}")]])) summary = f'{len(sessions) - 10} more not shown' if len(sessions) > 10 else 'Sessions' await update.message.reply_text(summary, reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton('Revoke all', callback_data='revoke_all')]])) except Exception: @@ -232,7 +232,7 @@ async def button_callback(self, update: Update, context: ContextTypes.DEFAULT_TY except Exception: await query.edit_message_text('Unable to process request') - async def send_login_notification(self, telegram_id: int, login_id: str, username: str, verification_code: int, requested_at: str, ip: str, user_agent: str): + async def send_login_notification(self, telegram_id: int, login_id: str, username: str, verification_code: int, requested_at: str, ip: str, user_agent: str, app_name: str | None = None): """Send login confirmation request to user""" logger.info(f"Sending login notification to telegram_id={telegram_id}, login_ref={log_ref(login_id)}") sys.stderr.flush() @@ -248,7 +248,8 @@ async def send_login_notification(self, telegram_id: int, login_id: str, usernam try: await self.app.bot.send_message( chat_id=telegram_id, - text=f"🔐 Login Request\n\n" + text=(f"🔐 Login request for {app_name}\n\n" if app_name else "🔐 Login Request\n\n") + + f"Username: {username}\n\n" f"Time UTC: {requested_at}\nIP: {ip}\nBrowser: {user_agent[:100]}\nTap the code shown in your browser; if this was not you, press Deny", reply_markup=reply_markup @@ -275,11 +276,12 @@ async def handle_login_notification(self, request): or type(code) is not int or not 10 <= code <= 99 or not isinstance(data.get('requested_at'), str) or not data['requested_at'] or not isinstance(data.get('ip'), str) - or not isinstance(data.get('user_agent'), str)): + or not isinstance(data.get('user_agent'), str) + or (data.get('app_name') is not None and not isinstance(data['app_name'], str))): return web.json_response({'error': 'Missing required fields'}, status=400) # Send notification via Telegram - await self.send_login_notification(telegram_id, login_id, username, data["verification_code"], data["requested_at"], data["ip"], data["user_agent"]) + await self.send_login_notification(telegram_id, login_id, username, data["verification_code"], data["requested_at"], data["ip"], data["user_agent"], data.get("app_name")) return web.json_response({'success': True}) except Exception as e: diff --git a/src/config.py b/src/config.py index 9393b00..6794818 100644 --- a/src/config.py +++ b/src/config.py @@ -2,7 +2,10 @@ Configuration management Loads environment variables and application settings """ -from pydantic import Field +from pydantic import Field, model_validator +from urllib.parse import urlsplit, urlunsplit +import ipaddress +import tldextract from pydantic_settings import BaseSettings, SettingsConfigDict @@ -29,6 +32,37 @@ class Settings(BaseSettings): LOGIN_HISTORY_RETENTION_DAYS: int = Field(default=30, gt=0) PURGE_INTERVAL_SECONDS: float = Field(default=3600, gt=0) + PUBLIC_URL: str = "http://localhost:8000" + SSO_COOKIE_NAME: str = "tl_sso" + SSO_COOKIE_SECURE: bool = True + SSO_COOKIE_DOMAIN: str = "" + REGISTRATION_MODE: str = "open" + + @model_validator(mode="after") + def validate_sso(self): + url = urlsplit(self.PUBLIC_URL) + if (url.scheme not in ("http", "https") or not url.hostname or url.username + or url.password or url.query or url.fragment or "\\" in self.PUBLIC_URL): + raise ValueError("PUBLIC_URL must be an absolute http(s) URL without credentials, query or fragment") + url.port # Reject invalid ports. + self.PUBLIC_URL = urlunsplit((url.scheme, url.netloc.lower(), url.path.rstrip("/"), "", "")) + if self.REGISTRATION_MODE not in ("open", "closed"): + raise ValueError("REGISTRATION_MODE must be open or closed") + domain = self.SSO_COOKIE_DOMAIN + if domain: + try: + ipaddress.ip_address(domain) + is_ip = True + except ValueError: + is_ip = False + extract = tldextract.TLDExtract(suffix_list_urls=(), cache_dir=None, include_psl_private_domains=True) + if (domain != domain.lower() or domain.startswith(".") or domain.endswith(".") + or "." not in domain or is_ip or not extract(domain).domain + or any(not part or not all(c.isascii() and (c.isalnum() or c == "-") for c in part) for part in domain.split(".")) + or not (url.hostname == domain or url.hostname.endswith("." + domain))): + raise ValueError("SSO_COOKIE_DOMAIN must be a non-public parent domain of PUBLIC_URL, without a leading dot or IP address") + return self + # Application DEBUG: bool = False diff --git a/src/database/sqlite.py b/src/database/sqlite.py index 64e921d..322daeb 100644 --- a/src/database/sqlite.py +++ b/src/database/sqlite.py @@ -80,19 +80,34 @@ async def init_db(self): await db.execute("CREATE TABLE IF NOT EXISTS 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)") await db.execute("CREATE INDEX IF NOT EXISTS idx_sessions_user ON sessions(user_id)") + for table, additions in { + 'users': [('public_id', 'TEXT')], + 'login_requests': [('purpose', "TEXT NOT NULL DEFAULT 'api'"), ('app_id', 'TEXT'), ('return_to', 'TEXT')], + 'sessions': [('kind', "TEXT NOT NULL DEFAULT 'api'")], + }.items(): + cols = {r[1] for r in await (await db.execute(f"PRAGMA table_info({table})")).fetchall()} + for name, kind in additions: + if name not in cols: + await db.execute(f"ALTER TABLE {table} ADD COLUMN {name} {kind}") + for row in await (await db.execute("SELECT id FROM users WHERE public_id IS NULL")).fetchall(): + await db.execute("UPDATE users SET public_id=? WHERE id=?", (str(uuid.uuid4()), row[0])) + 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.commit() async def create_user(self, username: str) -> User: """Create a new user""" async with aiosqlite.connect(self.db_path) as db: + public_id = str(uuid.uuid4()) cursor = await db.execute( - "INSERT INTO users (username) VALUES (?)", - (username,) + "INSERT INTO users (username, public_id) VALUES (?, ?)", + (username, public_id) ) await db.commit() user_id = cursor.lastrowid - return User(id=user_id, username=username) + return User(id=user_id, username=username, public_id=public_id) async def get_user_by_username(self, username: str) -> User | None: """Get user by username""" @@ -169,7 +184,7 @@ async def take_login_status(self, login_id): await db.commit() return None result = {"status": row["status"]} - if row["status"] == "approved" and row["session_token"]: + if row["purpose"] == "api" and row["status"] == "approved" and row["session_token"]: result["session_token"] = row["session_token"] result["refresh_token"] = row["refresh_token"] cursor = await db.execute("UPDATE login_requests SET session_token=NULL, refresh_token=NULL, token_delivered_at=? WHERE id=? AND status='approved' AND session_token IS NOT NULL", (time.time(), login_id)) @@ -200,14 +215,14 @@ async def consume_and_link(self, token, telegram_id): await db.rollback() raise ValueError("Telegram already linked to another account") from None - async def start_request(self, username, ip, user_agent): + async def start_request(self, username, ip, user_agent, purpose="api", app_id=None, return_to=None): code = secrets.randbelow(90) + 10 login_id = str(uuid.uuid4()) async with aiosqlite.connect(self.db_path) as db: db.row_factory = aiosqlite.Row await db.execute("BEGIN IMMEDIATE") user = await (await db.execute("SELECT * FROM users WHERE username=? AND telegram_id IS NOT NULL", (username,))).fetchone() - await db.execute("INSERT INTO login_requests (id,user_id,expires_at,verification_code,ip,user_agent) VALUES (?,?,?,?,?,?)", (login_id, user['id'] if user else 0, time.time()+settings.LOGIN_REQUEST_TTL_SECONDS, code, ip if user else None, user_agent[:200] if user else None)) + await db.execute("INSERT INTO login_requests (id,user_id,expires_at,verification_code,ip,user_agent,purpose,app_id,return_to) VALUES (?,?,?,?,?,?,?,?,?)", (login_id, user['id'] if user else 0, time.time()+settings.LOGIN_REQUEST_TTL_SECONDS, code, ip if user else None, user_agent[:200] if user else None, purpose, app_id, return_to)) await db.commit() return login_id, code, dict(user) if user else None @@ -228,10 +243,10 @@ async def approve(self, login_id, telegram_id, code): await db.commit() return 'wrong' sid, refresh = str(uuid.uuid4()), secrets.token_urlsafe(32) - token = self.access({'id': row['user_id'], 'username': row['username']}, sid) + token = refresh if row['purpose'] == 'sso' else self.access({'id': row['user_id'], 'username': row['username']}, sid) now = time.time() - await db.execute("INSERT INTO sessions (id,user_id,refresh_hash,created_at,expires_at,ip,user_agent) VALUES (?,?,?,?,?,?,?)", (sid,row['user_id'],hashlib.sha256(refresh.encode()).hexdigest(),now,now+settings.REFRESH_TOKEN_TTL_DAYS*86400,row['ip'],row['user_agent'])) - await db.execute("UPDATE login_requests SET status='approved',session_token=?,refresh_token=? WHERE id=?", (token,refresh,login_id)) + await db.execute("INSERT INTO sessions (id,user_id,refresh_hash,created_at,expires_at,ip,user_agent,kind) VALUES (?,?,?,?,?,?,?,?)", (sid,row['user_id'],hashlib.sha256(refresh.encode()).hexdigest(),now,now+settings.REFRESH_TOKEN_TTL_DAYS*86400,row['ip'],row['user_agent'],row['purpose'])) + await db.execute("UPDATE login_requests SET status='approved',session_token=?,refresh_token=? WHERE id=?", (token,refresh if row['purpose'] == 'api' else None,login_id)) await db.commit() return {'status': 'authenticated'} @@ -241,7 +256,7 @@ async def session(self, payload, allow_revoked=False, revoke=None): if revoke: # Read-only validation (/auth/me) needs no write lock: the single SELECT is atomic await db.execute("BEGIN IMMEDIATE") - row = await (await db.execute("SELECT s.*,u.username FROM sessions s JOIN users u ON u.id=s.user_id WHERE s.id=? AND s.user_id=? AND s.expires_at>?", (payload.get('sid'),payload.get('user_id'),time.time()))).fetchone() + row = await (await db.execute("SELECT s.*,u.username FROM sessions s JOIN users u ON u.id=s.user_id WHERE s.kind='api' AND s.id=? AND s.user_id=? AND s.expires_at>?", (payload.get('sid'),payload.get('user_id'),time.time()))).fetchone() if not row or (row['revoked_at'] is not None and not allow_revoked): return None if revoke: @@ -254,7 +269,7 @@ async def refresh(self, token): async with aiosqlite.connect(self.db_path) as db: db.row_factory = aiosqlite.Row await db.execute("BEGIN IMMEDIATE") - row = await (await db.execute("SELECT s.*,u.username FROM sessions s JOIN users u ON u.id=s.user_id WHERE (refresh_hash=? OR previous_refresh_hash=?) AND revoked_at IS NULL AND expires_at>?", (digest,digest,time.time()))).fetchone() + row = await (await db.execute("SELECT s.*,u.username FROM sessions s JOIN users u ON u.id=s.user_id WHERE s.kind='api' AND (refresh_hash=? OR previous_refresh_hash=?) AND revoked_at IS NULL AND expires_at>?", (digest,digest,time.time()))).fetchone() if not row: return None if row['previous_refresh_hash'] == digest: @@ -275,7 +290,7 @@ async def account_action(self, telegram_id, action, session_id=None): if not user: return None uid, now = user['id'], time.time() - sessions = [dict(r) for r in await (await db.execute("SELECT id,created_at,last_used_at,ip,user_agent FROM sessions WHERE user_id=? AND revoked_at IS NULL AND expires_at>? ORDER BY COALESCE(last_used_at,created_at) DESC, created_at DESC, id", (uid,now))).fetchall()] + sessions = [dict(r) for r in await (await db.execute("SELECT id,kind,created_at,last_used_at,ip,user_agent FROM sessions WHERE user_id=? AND revoked_at IS NULL AND expires_at>? ORDER BY COALESCE(last_used_at,created_at) DESC, created_at DESC, id", (uid,now))).fetchall()] result = {'status':'ok'} if action == 'account': recent = [dict(r) for r in await (await db.execute("SELECT created_at,CASE WHEN status='pending' AND expires_at<=? THEN 'expired' ELSE status END AS status,ip,user_agent FROM login_requests WHERE user_id=? ORDER BY created_at DESC, rowid DESC LIMIT 5", (now,uid))).fetchall()] @@ -287,7 +302,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 ('sessions','registration_tokens','login_requests'): + for table in ('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() @@ -301,3 +316,57 @@ async def purge_old(self, retention_seconds): await db.execute("DELETE FROM sessions WHERE expires_at?", (hashlib.sha256(secret.encode()).hexdigest(), now))).fetchone() + if not row: + return None + if revoke: + await db.execute('UPDATE sessions SET revoked_at=? WHERE id=?', (now, row['id'])) + elif row['last_used_at'] is None or row['last_used_at'] < now - 300: + await db.execute('UPDATE sessions SET last_used_at=? WHERE id=? AND (last_used_at IS NULL OR last_used_at? AND u.telegram_id IS NOT NULL", (digest, time.time()))).fetchone() + await db.execute('UPDATE login_requests SET session_token=NULL,token_delivered_at=? WHERE id=?', (time.time(), login_id)) + if active: + result.update(secret=row['session_token'], redirect=row['return_to'] or settings.PUBLIC_URL + '/') + else: + await db.execute("UPDATE login_requests SET status='denied' WHERE id=?", (login_id,)) + result['status'] = 'denied' + await db.commit() + return result diff --git a/src/models/user.py b/src/models/user.py index 7faa581..85b1ec2 100644 --- a/src/models/user.py +++ b/src/models/user.py @@ -14,6 +14,8 @@ class User: created_at: Optional[datetime] = None linked_at: Optional[datetime] = None + public_id: str | None = None + def is_linked(self) -> bool: """Check if user has linked Telegram account""" return self.telegram_id is not None diff --git a/src/services/auth_service.py b/src/services/auth_service.py index f0da543..e6ed6ee 100644 --- a/src/services/auth_service.py +++ b/src/services/auth_service.py @@ -16,10 +16,10 @@ async def start_login(self, username, background_tasks, ip="unknown", user_agent background_tasks.add_task(self.send_login_notification, user['telegram_id'], login_id, username, code, datetime.now(timezone.utc).isoformat(), ip, user_agent[:200]) return {'login_id':login_id,'status':'pending','verification_code':code} - async def send_login_notification(self, telegram_id, login_id, username, verification_code, requested_at, ip, user_agent): + async def send_login_notification(self, telegram_id, login_id, username, verification_code, requested_at, ip, user_agent, app_name=None): try: async with httpx.AsyncClient(timeout=15) as client: - response = await client.post(settings.BOT_NOTIFY_URL, headers={'X-Internal-Key':settings.INTERNAL_API_KEY}, json=dict(telegram_id=telegram_id,login_id=login_id,username=username,verification_code=verification_code,requested_at=requested_at,ip=ip,user_agent=user_agent)) + response = await client.post(settings.BOT_NOTIFY_URL, headers={'X-Internal-Key':settings.INTERNAL_API_KEY}, json=dict(telegram_id=telegram_id,login_id=login_id,username=username,verification_code=verification_code,requested_at=requested_at,ip=ip,user_agent=user_agent,app_name=app_name)) response.raise_for_status() except Exception: logger.warning('Login notification failed') diff --git a/src/web/routes.py b/src/web/routes.py index 35ad5c0..c26750f 100644 --- a/src/web/routes.py +++ b/src/web/routes.py @@ -2,6 +2,7 @@ API routes definition FastAPI router with all endpoints """ +from src.config import settings from src.utils.crypto import verify_token from fastapi import APIRouter, BackgroundTasks, Depends, HTTPException, Request @@ -28,6 +29,8 @@ async def register(request: RegisterRequest, http_request: Request, limiter=Depe """ Register a new user and get Telegram link """ + if settings.REGISTRATION_MODE == "closed": + raise HTTPException(403, "Registration is closed; ask the operator for an invitation") limiter.check("register", request.username, http_request.client.host if http_request.client else "unknown") # Create user user = await user_service.create_user(request.username) diff --git a/src/web/sso.py b/src/web/sso.py new file mode 100644 index 0000000..49d11b9 --- /dev/null +++ b/src/web/sso.py @@ -0,0 +1,189 @@ +"""Hosted browser login and forward authentication.""" +import html +import json +import logging +import re +from urllib.parse import parse_qs, quote, unquote, urlencode, urlsplit + +from fastapi import APIRouter, BackgroundTasks, Depends, HTTPException, Request +from fastapi.responses import HTMLResponse, JSONResponse, RedirectResponse, Response + +from src.config import settings +from src.services.auth_service import AuthService +from src.web.dependencies import get_db, get_limiter +from src.web.schemas import LoginStartRequest, LoginStatusRequest + +router = APIRouter() +logger = logging.getLogger(__name__) + + +def origin(url): + parsed = urlsplit(url) + if parsed.scheme not in ('http', 'https') or not parsed.hostname or parsed.username or parsed.password: + raise ValueError('Invalid origin') + port = parsed.port + host = parsed.hostname.lower() + if ':' in host: + host = '[' + host + ']' + return f'{parsed.scheme.lower()}://{host}' + (f':{port}' if port and port != (443 if parsed.scheme == 'https' else 80) else '') + + +def return_url(value, app=None): + """Return an approved absolute target, or None. Reject ambiguous encodings.""" + if not isinstance(value, str) or not value or len(value) > 2048 or '\\' in value or any(ord(c) < 32 or ord(c) == 127 for c in value): + return None + # Reject encoded controls, backslashes and network-path references too, while + # permitting ordinary encoded path/query values such as ?next=a%2Fb. + decoded = value + for _ in range(len(value)): + next_value = unquote(decoded) + if next_value == decoded: + break + decoded = next_value + if "\\" in decoded or decoded.startswith('//') or any(ord(c) < 32 or ord(c) == 127 for c in decoded): + return None + if value.startswith('/') and not value.startswith('//'): + return origin(settings.PUBLIC_URL) + value + try: + allowed = [origin(settings.PUBLIC_URL)] + (json.loads(app['origins']) if app else []) + if origin(value) in allowed: + return value + except (ValueError, TypeError): + pass + return None + + +def csrf(request, form=False): + content_type = request.headers.get('content-type', '').split(';')[0].lower() + if content_type not in (('application/json', 'application/x-www-form-urlencoded') if form else ('application/json',)): + raise HTTPException(403, 'Content-Type must be application/json' + (' or form' if form else '')) + if 'origin' in request.headers and request.headers['origin'] != origin(settings.PUBLIC_URL): + raise HTTPException(403, 'Invalid Origin') + + +def cookie(response, value='', clear=False): + response.set_cookie(settings.SSO_COOKIE_NAME, value, max_age=0 if clear else settings.REFRESH_TOKEN_TTL_DAYS * 86400, + httponly=True, secure=settings.SSO_COOKIE_SECURE, samesite='lax', path='/', domain=settings.SSO_COOKIE_DOMAIN or None) + + +@router.get('/login') +async def login(request: Request, db=Depends(get_db)): + app = await db.get_app(request.query_params.get('app')) + rd = return_url(request.query_params.get('rd'), app) + session = await db.browser_session(request.cookies.get(settings.SSO_COOKIE_NAME)) + if session and rd and request.query_params.get('force') != '1': + return RedirectResponse(rd, 302) + title = 'Sign in to ' + app['name'] if app else 'Secure authentication via Telegram' + page = request.app.state.login_html.replace('Secure authentication via Telegram', html.escape(title)) + return HTMLResponse(page) + + +@router.get('/') +async def home(request: Request, db=Depends(get_db)): + session = await db.browser_session(request.cookies.get(settings.SSO_COOKIE_NAME)) + base = html.escape(settings.PUBLIC_URL, quote=True) + body = (f'Signed in as {html.escape(session["username"])}
' if session else f'Sign in') + return HTMLResponse('TeleLogin' + body + '') + + +@router.post('/sso/start') +async def start(request: Request, background_tasks: BackgroundTasks, db=Depends(get_db), limiter=Depends(get_limiter)): + csrf(request) + try: + body = await request.json() + if not isinstance(body, dict): + raise ValueError('Expected object') + except ValueError: + raise HTTPException(422, 'Invalid JSON object') from None + try: + username = LoginStartRequest(**body).username + except (ValueError, TypeError): + raise HTTPException(422, 'Invalid username') from None + ip = request.client.host if request.client else 'unknown' + limiter.check('login', username, ip) + app = await db.get_app(body.get('app')) + rd = return_url(body.get('rd'), app) or settings.PUBLIC_URL + '/' + login_id, code, user = await db.start_request(username, ip, request.headers.get('user-agent', ''), 'sso', app['id'] if app else None, rd) + if user: + import datetime + background_tasks.add_task(AuthService(db).send_login_notification, user['telegram_id'], login_id, username, code, + datetime.datetime.now(datetime.timezone.utc).isoformat(), ip, request.headers.get('user-agent', '')[:200], app['name'] if app else None) + return {'login_id': login_id, 'status': 'pending', 'verification_code': code} + + +@router.post('/sso/complete') +async def complete(request: Request, db=Depends(get_db)): + csrf(request) + try: + body = LoginStatusRequest(**await request.json()) + except (ValueError, TypeError): + raise HTTPException(422, 'Invalid login_id') from None + result = await db.complete_browser_login(body.login_id) + if result is None: + raise HTTPException(404, 'Login request not found') + secret = result.pop('secret', None) + response = JSONResponse(result) + if secret: + cookie(response, secret) + return response + + +@router.get('/logout') +async def logout_page(request: Request, db=Depends(get_db)): + app_id = request.query_params.get('app', '') + app = await db.get_app(app_id) + rd = return_url(request.query_params.get('rd'), app) or settings.PUBLIC_URL + '/login' + return HTMLResponse(f'Log out
') + + +@router.post('/sso/logout') +async def logout(request: Request, db=Depends(get_db)): + csrf(request, form=True) + try: + if request.headers.get('content-type', '').split(';')[0].lower() == 'application/json': + body = await request.json() + if not isinstance(body, dict): + raise ValueError('Expected object') + else: + # URL-encoded forms need no multipart parser dependency. + fields = parse_qs((await request.body()).decode('utf-8'), keep_blank_values=True) + body = {key: values[-1] for key, values in fields.items()} + except (ValueError, UnicodeError): + raise HTTPException(422, 'Invalid logout body') from None + app = await db.get_app(body.get('app')) + rd = return_url(body.get('rd'), app) or settings.PUBLIC_URL + '/login' + await db.browser_session(request.cookies.get(settings.SSO_COOKIE_NAME), revoke=True) + response = RedirectResponse(rd, 303) + cookie(response, clear=True) + return response + + +@router.get('/sso/verify') +async def verify(request: Request, db=Depends(get_db)): + headers = {'Cache-Control': 'no-store'} + header, query = request.headers.get('x-telelogin-app'), request.query_params.get('app') + redirect = request.query_params.get('redirect') == '1' + if header is not None and query is not None and header != query: + return Response(status_code=403, headers=headers) + app_id = header if header is not None else query + app = await db.get_app(app_id) + if not app and (app_id is None or re.fullmatch(r'[a-z0-9][a-z0-9-]{0,39}', app_id)): + logger.warning('Missing or unknown forward-auth app: %s', repr(app_id)[:80]) + session = await db.browser_session(request.cookies.get(settings.SSO_COOKIE_NAME)) + if not session: + original = request.headers.get('x-original-url') + if original is None: + original = request.headers.get('x-forwarded-proto', '') + '://' + request.headers.get('x-forwarded-host', '') + request.headers.get('x-forwarded-uri', '') + params = {'app': app_id or ''} + rd = return_url(original, app) + if rd: + params['rd'] = rd + target = settings.PUBLIC_URL + '/login?' + urlencode(params) + if redirect: + return RedirectResponse(target, 302, headers=headers) + headers['X-TeleLogin-Login'] = target + return Response(status_code=401, headers=headers) + if not await db.allowed(app, session): + return HTMLResponse('Access denied' if redirect else '', 403, headers=headers) + headers.update({'X-TeleLogin-User': quote(session['username'], safe=''), 'X-TeleLogin-User-Id': session['public_id']}) + return Response(status_code=200, headers=headers) diff --git a/src/web/templates/index.html b/src/web/templates/index.html index 96c4387..a459d81 100644 --- a/src/web/templates/index.html +++ b/src/web/templates/index.html @@ -93,16 +93,14 @@

🔐 TeleLogin

} finally { clearTimeout(timer); } } try { - const {login_id, verification_code} = await request('/auth/start-login', {username}); + const {login_id, verification_code} = await request('sso/start', {username, app: new URLSearchParams(location.search).get('app'), rd: new URLSearchParams(location.search).get('rd')}); message.style.fontSize = "1.5rem"; message.textContent = `Tap code ${verification_code} in Telegram`; while (Date.now() + 2000 < deadline) { await new Promise(resolve => setTimeout(resolve, 2000)); - const data = await request('/auth/status', {login_id}); + const data = await request('sso/complete', {login_id}); if (data.status === 'approved') { - if (!data.session_token) throw new Error('Session token already retrieved'); - sessionStorage.setItem('telelogin_session_token', data.session_token); - sessionStorage.setItem('telelogin_refresh_token', data.refresh_token); + if (data.redirect) location.assign(data.redirect); status.className = 'status success'; message.textContent = '✓ Login successful!'; return; diff --git a/tests/e2e/certs/cert.pem b/tests/e2e/certs/cert.pem new file mode 100644 index 0000000..4234cf6 --- /dev/null +++ b/tests/e2e/certs/cert.pem @@ -0,0 +1,20 @@ +-----BEGIN CERTIFICATE----- +MIIDNjCCAh6gAwIBAgIUGO6KU95/i4o0uRuNe/0Ip2uLG/kwDQYJKoZIhvcNAQEL +BQAwFjEUMBIGA1UEAwwLZXhhbXBsZS5jb20wIBcNMjYxMDIyMTQxMjQ4WhgPMjEy +NjA5MjgxNDEyNDhaMBYxFDASBgNVBAMMC2V4YW1wbGUuY29tMIIBIjANBgkqhkiG +9w0BAQEFAAOCAQ8AMIIBCgKCAQEAyp7Ri/1RIMA9nxADQk+1eZfIsJU2h2ry2rFK +gegcDy5MlC+KuxOkXibNcgLK6z5GkDPR1KCZEIYiFXjI1sujecdDqnD7+FXOLzWc +Ddp/2bD4VP209PSmu3fWQ73QFKCS8AAqRrJ/MHGG3rfuYst0cADNAUi4ANtJkFPv +T7hdQWWEeqv+bSyNRtYACu82prWqzKGH0k9KtHTP1QTkg/GGy+eEH51Y6zb0zbxx +wZNTDzH8pSc6Kel+qWzlNFG0jmPMo8rem3BwSj71T1v9l7bOGx1dXxGLaRVQYLQa +PxBqxf+o/TJmEckKiX4OGAaPEoVJSEZUcMI/dAlbjadZ1yawGQIDAQABo3oweDAd +BgNVHQ4EFgQUuKcGMv315vSF0j74fpDxwL9op54wHwYDVR0jBBgwFoAUuKcGMv31 +5vSF0j74fpDxwL9op54wDwYDVR0TAQH/BAUwAwEB/zAlBgNVHREEHjAcggtleGFt +cGxlLmNvbYINKi5leGFtcGxlLmNvbTANBgkqhkiG9w0BAQsFAAOCAQEAMWqrSs5W +keIIltQopsGznieRl/KKTKURaZ4MIlEhoGQE3Zrv0Bk3AqHjtrwbYzTwrfeQSi63 +pS9+Ezd0T4+05/dKwCfHMURXyKvclZLkWeKeefSA7VaL65ukueq3iJjiixTVz8sS +fvEH4Gcz9oBaeSmhbBJwVxQq3S5ywf/aFN2iTw7PsPlmwEzosjatPdsYp2xRHQ7m +00bIzmfEjWHu4yLibSyGuJN77057Owl7i8XjcAqLb+vs9KJc1c47YgkAhFy7Cnf8 +TjRZPbQh9hlzxyuNCMr9Funm0cc0uNho9Id12F8NMMBQ6hcWmjhLhc4b1qYlQEjI +17xkZQ7prvfpXA== +-----END CERTIFICATE----- diff --git a/tests/e2e/certs/key.pem b/tests/e2e/certs/key.pem new file mode 100644 index 0000000..6d7ed0e --- /dev/null +++ b/tests/e2e/certs/key.pem @@ -0,0 +1,28 @@ +-----BEGIN PRIVATE KEY----- +MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDKntGL/VEgwD2f +EANCT7V5l8iwlTaHavLasUqB6BwPLkyUL4q7E6ReJs1yAsrrPkaQM9HUoJkQhiIV +eMjWy6N5x0OqcPv4Vc4vNZwN2n/ZsPhU/bT09Ka7d9ZDvdAUoJLwACpGsn8wcYbe +t+5iy3RwAM0BSLgA20mQU+9PuF1BZYR6q/5tLI1G1gAK7zamtarMoYfST0q0dM/V +BOSD8YbL54QfnVjrNvTNvHHBk1MPMfylJzop6X6pbOU0UbSOY8yjyt6bcHBKPvVP +W/2Xts4bHV1fEYtpFVBgtBo/EGrF/6j9MmYRyQqJfg4YBo8ShUlIRlRwwj90CVuN +p1nXJrAZAgMBAAECggEAD4GjCMMcq9R6gstPbIo8Ga+fiMAKmcd6CXmK+bEhQJoq ++yY+SD3jFN+EVobXL7Sm4s9MbijSPfz968XAHQwdmSrCR295IRK0AlHofPjtUuQj +xSFbcWmtvugXajzDCWkWha6Fjb6IVFVD3JSX9lCaux2cks4VYt9lXFnIFUJHRMNU +yYsiEYCT86ICrx71IoQ/zf0S+cwZXVP1gD40x2BflG5AQ9lsIoiR3jP8ZTzabxkj +OfMohsCggBHaFgAgdazFxqyk/kJBUvEAIeZM1u/KfKy5/Z8kccgvAgUunTo+sTuE +Yz7JcdGk5GrZRwCISIZE+ihm7D+PI3s/RebAsEbHGQKBgQDj6JtBlnvqKSeTOVSI +idgcFXNGe6R6xgZa288LibeDUmDPB5esDUS+QkfPWjUOhLdYOSDi63SabbWuyj6h +OZCy57rT/QwyA3czLI0MqqfwXGH0OZPBZgq76dCLGJBrEC1yr2Fc0e4QdFtycMSi ++ylP4pQW819XfXYKDnHto1/IHQKBgQDjmEVhq860AACjHtlFEfLMy7SmaGaClM+m +MWWSDPoI8jkdKbLV1ItET+W2YA57DleCS8w7H9/wUfOwaWZtwxAfm2ztz4GwrTRf +GDHzL25lDvv+4p6uob/J+Kck9m0D8qb5Pp9p8VK1yRiekgIhh3G+UfMCEcqNXKoy +lWKQhFkfLQKBgEe4m6M4SCaYbOvXztJpDqlH1s8HeetpBfbx1WY8IJQjCHQeX4y1 +YDy/fvmx2aCIA2qwD7lZf4hZniMzYiI6i17BrfmoWH4kuQ5RptGlotPxPqIsvGLQ +SfB41DfxswD+Rk8hAfLD3bcv5tdMxZTElWueUhwm2ood4Veo1BGEqE/BAoGBAOIW +br3i3TiEVB221GC/vrFgnrk8NrD7QPe4VEzspSlj7gahWK0AMcSPlgNAksH9ckLW +JzCIrn3d+zVAzua0gnzTejcXDp9CwCbDM0N/16t+YihGWRnjRlFNuESIo6zrTKGG +avfkKaS5+sHzCzjhgsVsRPnGUK9y4QPU0A/92UaVAoGAbqg+J3aOmgSvfgYs1Z1y +aqvl2TxLo4kp+6z3ihnABbr1/nR0U+zgqaKqjvtsYnQrL2E1RC5NxneaSo8hjwTo +1M4Jsrw/LPmeb6fOThjGO3RrIedalWJzTQRxP3PuTJH+MOLQQu4QcF9jWHa+U3/H +hHyxcmuGwVknDxTU15pLWg8= +-----END PRIVATE KEY----- diff --git a/tests/e2e/check_forward_auth.py b/tests/e2e/check_forward_auth.py new file mode 100644 index 0000000..9a31223 --- /dev/null +++ b/tests/e2e/check_forward_auth.py @@ -0,0 +1,81 @@ +"""Curl-driven real-proxy assertions; invoked by forward_auth.sh.""" +import json +import os +from pathlib import Path +import subprocess +from urllib.parse import parse_qs, urlsplit + +port = os.environ['E2E_PORT'] +base = os.environ['E2E_PUBLIC_URL'] +prefix = os.environ['E2E_SHAPE'] == 'prefix' +app = f'https://{"example.com" if prefix else "app.example.com"}:{port}' +api = 'http://127.0.0.1:' + os.environ['E2E_API_PORT'] +work = Path(os.environ['E2E_CONFIG_DIR']) +key = {'X-Internal-Key': 'e2e-placeholder-internal-key-00000000'} + + +def request(url, data=None, headers=None, jar=None): + cmd = ['curl', '--insecure', '--noproxy', '*', '-sS', '--max-time', '15', '-D', str(work / 'headers'), '-o', str(work / 'body'), '-w', '%{http_code}'] + for host in ('auth.example.com', 'app.example.com', 'example.com'): + cmd += ['--resolve', f'{host}:{port}:127.0.0.1'] + if jar: + cmd += ['-b', str(work / jar), '-c', str(work / jar)] + for name, value in (headers or {}).items(): + cmd += ['-H', name + ': ' + value] + if data is not None: + cmd += ['-H', 'Content-Type: application/json', '--data', json.dumps(data)] + status = int(subprocess.check_output(cmd + [url], text=True)) + response_headers = {} + for line in (work / 'headers').read_text().splitlines()[1:]: + if ':' in line: + name, value = line.split(':', 1) + response_headers[name.lower()] = value.strip() + return status, response_headers, (work / 'body').read_text() + + +def admin(*args): + subprocess.run(['docker', 'compose', '-p', 'telelogin-e2e-' + os.environ['E2E_PROXY'], '-f', 'tests/e2e/docker-compose.e2e.yml', 'exec', '-T', 'telelogin', 'python', '-m', 'src.admin', *args], check=True) + + +def login(username, telegram, jar): + status, _, body = request(api + '/register', {'username': username}) + assert status == 200, body + token = parse_qs(urlsplit(json.loads(body)['link']).query)['start'][0] + assert request(api + '/auth/link-telegram', {'token': token, 'telegram_id': telegram}, key)[0] == 200 + status, _, body = request(base + '/sso/start', {'username': username, 'app': 'demo', 'rd': app + '/demo/x'}) + assert status == 200, body + started = json.loads(body) + assert request(api + '/auth/confirm-login', {'login_id': started['login_id'], 'verification_code': started['verification_code'], 'telegram_id': telegram}, key)[0] == 200 + status, headers, body = request(base + '/sso/complete', {'login_id': started['login_id']}, jar=jar) + assert status == 200 and json.loads(body)['status'] == 'approved', body + assert 'httponly' in headers['set-cookie'].lower() + assert ('domain=example.com' in headers['set-cookie'].lower()) == (not prefix) + + +admin('app', 'add', 'demo', '--name', 'Demo') +if not prefix: + admin('app', 'origin', 'add', 'demo', app) +original = app + '/demo/x?a=1&b=2' +status, headers, body = request(original) +assert status == 302, (status, headers, body) +location = headers['location'] +assert location.startswith(base + '/login?'), location +query = parse_qs(urlsplit(location).query) +assert query['app'] == ['demo'] and query['rd'] == [original], location +assert request(app + '/demo/x', {'probe': 'unauthenticated'})[0] == 302 +login('alice', 42, 'alice.cookies') +admin('app', 'allow', 'demo', 'alice') +status, _, body = request(app + '/demo/x', jar='alice.cookies') +assert status == 200 and 'X-Telelogin-User: alice' in body, (status, body) +status, _, body = request(app + '/demo/x', {'probe': 'authenticated'}, jar='alice.cookies') +assert status == 200 and 'X-Telelogin-User: alice' in body, (status, body) +status, _, body = request(app + '/demo/x', headers={'X-TeleLogin-User': 'spoof', 'X-TeleLogin-User-Id': 'spoof'}, jar='alice.cookies') +assert status == 200 and 'X-Telelogin-User: alice' in body and 'spoof' not in body, body +login('bob', 43, 'bob.cookies') +status, _, body = request(app + '/demo/x', headers={'X_TeleLogin_User': 'spoofu', 'X_TeleLogin_User_Id': 'spoofu'}, jar='alice.cookies') +assert status == 200 and 'spoofu' not in body, body +assert request(app + '/demo/x', jar='bob.cookies')[0] == 403 +assert request(base + '/internal/account', {'telegram_id': 42}, key)[0] == 404 +assert request(base + '/sso/logout', {}, jar='alice.cookies')[0] == 303 +assert request(app + '/demo/x', jar='alice.cookies')[0] == 302 +print('Redirect, cookie, identity, spoof, allowlist, internal isolation and logout checks passed') diff --git a/tests/e2e/docker-compose.e2e.yml b/tests/e2e/docker-compose.e2e.yml new file mode 100644 index 0000000..acb3de6 --- /dev/null +++ b/tests/e2e/docker-compose.e2e.yml @@ -0,0 +1,47 @@ +services: + telelogin: + build: + context: ../.. + dockerfile: docker/Dockerfile + environment: + BOT_TOKEN: '0:e2e-placeholder' + SECRET_KEY: e2e-placeholder-secret-key-0000000000 + INTERNAL_API_KEY: e2e-placeholder-internal-key-00000000 + DB_URL: sqlite:///data/e2e.sqlite3 + PUBLIC_URL: ${E2E_PUBLIC_URL} + SSO_COOKIE_SECURE: 'true' + SSO_COOKIE_DOMAIN: ${E2E_COOKIE_DOMAIN:-} + BOT_NOTIFY_URL: http://127.0.0.1:1/notify-login + FORWARDED_ALLOW_IPS: '*' + RATE_LIMIT_USERNAME: '200' + RATE_LIMIT_IP: '500' + ports: ['127.0.0.1:${E2E_API_PORT:-18000}:8000'] + echo: + image: traefik/whoami:v1.11 + nginx: + image: nginx:1.29 + profiles: [nginx] + ports: ['127.0.0.1:${E2E_PORT:-18080}:443'] + volumes: + - ${E2E_CONFIG_DIR}/nginx.conf:/etc/nginx/conf.d/default.conf:ro + - ./certs:/etc/nginx/certs:ro + - ${E2E_CONFIG_DIR}/telelogin.conf:/etc/nginx/telelogin.conf:ro + - ${E2E_CONFIG_DIR}/protect-app.conf:/etc/nginx/protect-app.conf:ro + depends_on: [telelogin, echo] + traefik: + image: traefik:v3.5 + profiles: [traefik] + command: [--entrypoints.websecure.address=:443, --providers.file.filename=/etc/traefik/dynamic.yml] + ports: ['127.0.0.1:${E2E_PORT:-18080}:443'] + volumes: + - ${E2E_CONFIG_DIR}/dynamic.yml:/etc/traefik/dynamic.yml:ro + - ./certs:/etc/traefik/certs:ro + depends_on: [telelogin, echo] + caddy: + image: caddy:2.10 + profiles: [caddy] + ports: ['127.0.0.1:${E2E_PORT:-18080}:443'] + volumes: + - ${E2E_CONFIG_DIR}/Caddyfile:/etc/caddy/Caddyfile:ro + - ./certs:/etc/caddy/certs:ro + depends_on: [telelogin, echo] diff --git a/tests/e2e/forward_auth.sh b/tests/e2e/forward_auth.sh new file mode 100755 index 0000000..0158ccb --- /dev/null +++ b/tests/e2e/forward_auth.sh @@ -0,0 +1,83 @@ +#!/usr/bin/env bash +set -euo pipefail +cd "$(dirname "$0")/../.." +proxy=${1:?Usage: tests/e2e/forward_auth.sh nginx|traefik|caddy} +case "$proxy" in nginx|traefik|caddy) ;; *) echo 'Unknown proxy' >&2; exit 2 ;; esac +export E2E_PORT=${E2E_PORT:-18080} E2E_API_PORT=${E2E_API_PORT:-18000} +export E2E_CONFIG_DIR +E2E_CONFIG_DIR=$(mktemp -d "$PWD/tests/e2e/.run-XXXXXX") +compose=(docker compose -p "telelogin-e2e-$proxy" -f tests/e2e/docker-compose.e2e.yml --profile "$proxy") +cleanup() { + result=$? + if ((result)); then "${compose[@]}" logs --no-color || true; fi + "${compose[@]}" down -v --remove-orphans || true + rm -rf "$E2E_CONFIG_DIR" +} +trap cleanup EXIT +shapes=(prefix subdomain) +for shape in "${shapes[@]}"; do + export E2E_SHAPE=$shape E2E_PROXY=$proxy + if [[ $shape == prefix ]]; then + export E2E_PUBLIC_URL="https://example.com:$E2E_PORT/telelogin" E2E_COOKIE_DOMAIN='' + else + export E2E_PUBLIC_URL="https://auth.example.com:$E2E_PORT" E2E_COOKIE_DOMAIN=example.com + fi + # Use shipped TLS configurations and the public test certificate. Only + # app id and upstreams change; the auth directives are not rewritten. + python3 - <<'PY' +import os +from pathlib import Path +out = Path(os.environ['E2E_CONFIG_DIR']) +proxy, shape = os.environ['E2E_PROXY'], os.environ['E2E_SHAPE'] +if proxy == 'nginx': + for source, target in [(shape + '.conf', 'nginx.conf'), ('telelogin.conf', 'telelogin.conf'), ('protect-app.conf', 'protect-app.conf')]: + text = Path('examples/nginx', source).read_text().replace('127.0.0.1:8000', 'telelogin:8000').replace('127.0.0.1:9000', 'echo:80').replace('myapp', 'demo') + (out / target).write_text(text) +elif proxy == 'traefik': + text = Path('examples/traefik/dynamic.yml').read_text() + if shape == 'prefix': + # Merge the shipped prefix routers/middleware with the shared auth + # middleware, services and TLS settings; no auth directives change. + prefix = Path('examples/traefik/prefix.yml').read_text() + routers, prefix_middlewares = prefix.split(' middlewares:\n', 1) + _, shared = text.split(' middlewares:\n', 1) + middlewares, services = shared.split(' services:\n', 1) + text = routers + ' middlewares:\n' + middlewares + prefix_middlewares + ' services:\n' + services + (out / 'dynamic.yml').write_text(text.replace('myapp', 'demo')) +else: + text = Path('examples/caddy', 'prefix.Caddyfile' if shape == 'prefix' else 'Caddyfile').read_text().replace('myapp', 'demo') + (out / 'Caddyfile').write_text(text) +PY + "${compose[@]}" up -d --build "$proxy" + api_ready=false + for attempt in {1..60}; do + if curl --noproxy '*' --connect-timeout 1 --max-time 2 -fsS "http://127.0.0.1:$E2E_API_PORT/health" >/dev/null 2>&1; then + api_ready=true + break + fi + sleep 1 + done + if [[ $api_ready != true ]]; then + echo "API did not become ready ($proxy $shape)" >&2 + exit 1 + fi + app_host=app.example.com + if [[ $shape == prefix ]]; then app_host=example.com; fi + proxy_ready=false + for attempt in {1..60}; do + status=$(curl --noproxy '*' --insecure --connect-timeout 1 --max-time 2 -sS -o /dev/null -w '%{http_code}' \ + --resolve "$app_host:$E2E_PORT:127.0.0.1" "https://$app_host:$E2E_PORT/demo/x" 2>/dev/null) || status=000 + if [[ $status == 302 || $status == 401 ]]; then + proxy_ready=true + break + fi + sleep 1 + done + if [[ $proxy_ready != true ]]; then + echo "Proxy did not become ready ($proxy $shape; last HTTP status $status)" >&2 + exit 1 + fi + python3 tests/e2e/check_forward_auth.py + "${compose[@]}" down -v --remove-orphans + echo "PASS: $proxy $shape" +done diff --git a/tests/test_admin.py b/tests/test_admin.py new file mode 100644 index 0000000..32c1431 --- /dev/null +++ b/tests/test_admin.py @@ -0,0 +1,113 @@ +import json +import os +from pathlib import Path +import subprocess +import sys +from unittest.mock import patch + +import pytest + +from src import admin +from src.config import settings +from src.services.token_service import TokenService + + +def args(*values): + return admin.parser().parse_args(values) + + +def test_gen_secrets_without_settings(tmp_path): + env = {k: v for k, v in os.environ.items() if k not in ('BOT_TOKEN', 'SECRET_KEY', 'INTERNAL_API_KEY')} + env['PYTHONPATH'] = str(Path.cwd()) + result = subprocess.run([sys.executable, '-m', 'src.admin', 'gen-secrets'], cwd=tmp_path, env=env, text=True, capture_output=True, check=True) + lines = dict(line.split('=', 1) for line in result.stdout.splitlines()) + assert set(lines) == {'SECRET_KEY', 'INTERNAL_API_KEY'} + assert all(len(value) >= 43 for value in lines.values()) + + +async def test_admin_app_lifecycle(db, monkeypatch, capsys): + monkeypatch.setattr(settings, 'DB_URL', 'sqlite:///' + db.db_path) + monkeypatch.setattr(settings, 'PUBLIC_URL', 'https://auth.example.com') + monkeypatch.setattr(settings, 'SSO_COOKIE_DOMAIN', 'example.com') + await admin.run(args('user', 'invite', 'alice')) + link = capsys.readouterr().out.strip() + assert link.startswith('https://t.me/') + await db.consume_and_link(link.split('?start=')[1], 42) + await admin.run(args('app', 'add', 'demo', '--name', 'Demo')) + await admin.run(args('app', 'allow', 'demo', 'alice')) + await admin.run(args('app', 'origin', 'add', 'demo', 'https://APP.example.com')) + assert json.loads((await db.get_app('demo'))['origins']) == ['https://app.example.com'] + await admin.run(args('app', 'show', 'demo')) + output = capsys.readouterr().out + assert 'alice' in output and 'secret_hash' not in output + for command in [('app', 'list'), ('user', 'list'), ('app', 'policy', 'demo', 'all'), ('app', 'disallow', 'demo', 'alice'), ('app', 'origin', 'remove', 'demo', 'https://app.example.com')]: + await admin.run(args(*command)) + assert (await db.get_app('demo'))['access_policy'] == 'all' + for command in [('app', 'add', 'BAD', '--name', 'Invalid'), ('app', 'show', 'missing'), ('app', 'allow', 'demo', 'missing'), ('app', 'origin', 'add', 'demo', 'https://evil.test')]: + with pytest.raises(ValueError): + await admin.run(args(*command)) + await admin.run(args('app', 'allow', 'demo', 'alice')) + await admin.run(args('app', 'remove', 'demo')) + assert await db.get_app('demo') is None + await admin.run(args('user', 'remove', 'alice')) + assert await db.get_user_by_username('alice') is None + + +@pytest.mark.parametrize('value', ['https://evil.test', 'https://app.example.com/path', 'https://app.example.com?q=1', 'http://app.example.com', 'https://auth.example.com#fragment', 'https://user@auth.example.com']) +def test_invalid_origins(value, monkeypatch): + monkeypatch.setattr(settings, 'PUBLIC_URL', 'https://auth.example.com') + monkeypatch.setattr(settings, 'SSO_COOKIE_DOMAIN', '') + with pytest.raises(ValueError): + admin.validated_origin(value) + + +async def test_invite_with_closed_registration(db, monkeypatch, capsys): + monkeypatch.setattr(settings, 'DB_URL', 'sqlite:///' + db.db_path) + monkeypatch.setattr(settings, 'REGISTRATION_MODE', 'closed') + await admin.run(args('user', 'invite', 'alice')) + token = capsys.readouterr().out.strip().split('?start=')[1] + await db.consume_and_link(token, 42) + assert (await db.get_user_by_telegram_id(42)).username == 'alice' + with pytest.raises(ValueError): + await db.consume_and_link(token, 43) + with patch.object(TokenService, 'create_telegram_link', return_value='link'): + await admin.run(args('user', 'invite', 'bob')) + + +@pytest.mark.parametrize('username', ['', 'ab', 'x' * 51]) +def test_invite_invalid_username_exits_one(username, monkeypatch, capsys): + monkeypatch.setattr(sys, 'argv', ['admin', 'user', 'invite', username]) + with patch('src.database.sqlite.SQLiteDatabase') as database: + with pytest.raises(SystemExit) as exc: + admin.main() + assert exc.value.code == 1 + database.assert_not_called() + assert 'username' in capsys.readouterr().err.lower() + + +def test_invite_duplicate_exits_one(monkeypatch, capsys): + import aiosqlite + from unittest.mock import AsyncMock + monkeypatch.setattr(sys, 'argv', ['admin', 'user', 'invite', 'alice']) + with patch('src.database.sqlite.SQLiteDatabase') as database: + database.return_value.init_db = AsyncMock() + database.return_value.create_user = AsyncMock(side_effect=aiosqlite.IntegrityError('UNIQUE constraint failed: users.username')) + with pytest.raises(SystemExit) as exc: + admin.main() + assert exc.value.code == 1 + assert 'Username already exists' in capsys.readouterr().err + + +async def test_allow_rejects_unlinked_user(db, monkeypatch): + monkeypatch.setattr(settings, 'DB_URL', 'sqlite:///' + db.db_path) + await db.create_user('alice') + await admin.run(args('app', 'add', 'demo', '--name', 'Demo')) + with pytest.raises(ValueError, match='user exists but has not linked Telegram yet'): + await admin.run(args('app', 'allow', 'demo', 'alice')) + import sqlite3 + with sqlite3.connect(db.db_path) as conn: + assert conn.execute('SELECT COUNT(*) FROM app_users').fetchone()[0] == 0 + tokens = TokenService(db) + 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')) diff --git a/tests/test_phase2.py b/tests/test_phase2.py index edd1fa8..12079f4 100644 --- a/tests/test_phase2.py +++ b/tests/test_phase2.py @@ -41,8 +41,9 @@ async def test_lifespan_health_login(tmp_path, monkeypatch): assert (await client.get('/health')).json() == {'status': 'ok'} response = await client.get('/login') assert response.status_code == 200 and 'text/html' in response.headers['content-type'] - assert '/auth/status' in response.text and 'setInterval' not in response.text - assert (await client.get('/')).json()['message'] == 'TeleLogin API' + assert "request('sso/complete'" in response.text and 'setInterval' not in response.text + assert "request('/sso/" not in response.text + assert 'Sign in' in (await client.get('/')).text finally: app.state._state.clear() app.state._state.update(previous_state) diff --git a/tests/test_sso.py b/tests/test_sso.py new file mode 100644 index 0000000..ea436e9 --- /dev/null +++ b/tests/test_sso.py @@ -0,0 +1,332 @@ +import asyncio +import hashlib +import json +from pathlib import Path +import socket +import sqlite3 +import time +from unittest.mock import AsyncMock +from urllib.parse import parse_qs, unquote, urlsplit + +import httpx +import pytest +from pydantic import ValidationError + +from src.app import app +from src.config import Settings, settings +from src.database.sqlite import SQLiteDatabase +from src.web.security import RateLimiter +from src.web.sso import return_url +from test_phase3 import issue, headers +from test_security import linked + +INTERNAL = {'X-Internal-Key': settings.INTERNAL_API_KEY} + + +@pytest.fixture +async def client(db, monkeypatch): + monkeypatch.setattr(settings, 'PUBLIC_URL', 'http://test/telelogin') + 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, '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()) + async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url='http://test') as client: + yield client + + +def add_app(db, name='demo', policy='allowlist', origins=None): + with sqlite3.connect(db.db_path) as conn: + conn.execute('INSERT INTO apps(id,name,access_policy,origins,created_at) VALUES (?,?,?,?,?)', (name, 'Demo ', policy, json.dumps(origins or []), time.time())) + + +def allow(db, user, app_id='demo'): + with sqlite3.connect(db.db_path) as conn: + conn.execute('INSERT INTO app_users VALUES (?,?)', (app_id, user.id)) + + +async def start(client, username='alice', **extra): + response = await client.post('/sso/start', json={'username': username, 'app': 'demo', **extra}) + assert response.status_code == 200, response.text + return response.json() + + +async def approve(client, data, telegram_id=42): + response = await client.post('/auth/confirm-login', json={'login_id': data['login_id'], 'telegram_id': telegram_id, 'verification_code': data['verification_code']}, headers=INTERNAL) + assert response.status_code == 200, response.text + + +async def complete(client, data): + return await client.post('/sso/complete', json={'login_id': data['login_id']}) + + +async def test_approval_delivery_purpose_and_cookie(db, client, monkeypatch): + await linked(db) + add_app(db, policy='all') + monkeypatch.setattr(settings, 'SSO_COOKIE_SECURE', True) + monkeypatch.setattr(settings, 'SSO_COOKIE_DOMAIN', 'test.example.com') + data = await start(client, rd='/demo') + assert (await complete(client, data)).json() == {'status': 'pending'} + await approve(client, data) + row = await db.get_login_request(data['login_id']) + secret = row['session_token'] + assert row['refresh_token'] is None + with sqlite3.connect(db.db_path) as conn: + assert conn.execute('SELECT kind, refresh_hash FROM sessions').fetchone() == ('sso', hashlib.sha256(secret.encode()).hexdigest()) + assert (await client.post('/auth/status', json={'login_id': data['login_id']})).json() == {'status': 'approved'} + response = await complete(client, data) + assert response.json() == {'status': 'approved', 'redirect': 'http://test/demo'} + cookie = response.headers['set-cookie'] + assert cookie.startswith('tl_sso=') + for attr in ('Domain=test.example.com', 'HttpOnly', 'Max-Age=2592000', 'Path=/', 'SameSite=lax', 'Secure'): + assert attr in cookie + assert 'set-cookie' not in (await complete(client, data)).headers + assert (await db.get_login_request(data['login_id']))['session_token'] is None + assert (await client.post('/auth/refresh', json={'refresh_token': secret})).status_code == 401 + api, code, _ = await db.start_request('alice', 'ip', 'ua') + assert (await complete(client, {'login_id': api})).status_code == 404 + await db.approve(api, 42, code) + assert 'session_token' in (await db.take_login_status(api)) + + +@pytest.mark.parametrize('revoke', ['bot', 'api', 'delete']) +async def test_revoke_before_collection(db, client, revoke): + await linked(db) + token = await issue(db) + data = await start(client) + await approve(client, data) + if revoke == 'api': + assert (await client.post('/auth/logout-all', headers=headers(token['session_token']))).status_code == 200 + else: + path = '/internal/sessions/revoke' if revoke == 'bot' else '/internal/account/delete' + assert (await client.post(path, json={'telegram_id': 42}, headers=INTERNAL)).status_code == 200 + response = await complete(client, data) + assert response.status_code == (404 if revoke == 'delete' else 200) + if revoke != 'delete': + assert response.json() == {'status': 'denied'} + # A retry and the login history must keep reporting denied, not approved + retry = await complete(client, data) + assert retry.json() == {'status': 'denied'} and 'set-cookie' not in retry.headers + assert (await db.get_login_request(data['login_id']))['status'] == 'denied' + assert 'set-cookie' not in response.headers + + +@pytest.mark.parametrize('username', ['用户甲', 'has spaces', '100%', 'control\r\n\x01']) +async def test_unicode_header_and_verify_matrix(db, client, username): + user = await linked(db, username) + add_app(db) + allow(db, user) + data = await start(client, username) + await approve(client, data) + await complete(client, data) + response = await client.get('/sso/verify', headers={'X-TeleLogin-App': 'demo'}) + assert response.status_code == 200 + assert unquote(response.headers['X-TeleLogin-User']) == username + assert response.headers['X-TeleLogin-User-Id'] == user.public_id + assert response.text == '' and response.headers['cache-control'] == 'no-store' + assert (await client.get('/sso/verify?app=demo')).status_code == 200 + for path, hdr in [('/sso/verify', {}), ('/sso/verify?app=missing', {}), ('/sso/verify?app=other', {'X-TeleLogin-App': 'demo'})]: + assert (await client.get(path, headers=hdr)).status_code == 403 + with sqlite3.connect(db.db_path) as conn: + before = conn.execute('SELECT last_used_at FROM sessions').fetchone()[0] + await client.get('/sso/verify?app=demo') + with sqlite3.connect(db.db_path) as conn: + assert conn.execute('SELECT last_used_at FROM sessions').fetchone()[0] == before + conn.execute('DELETE FROM app_users') + assert (await client.get('/sso/verify?app=demo')).status_code == 403 + with sqlite3.connect(db.db_path) as conn: + conn.execute("UPDATE apps SET access_policy='all'") + assert (await client.get('/sso/verify?app=demo')).status_code == 200 + with sqlite3.connect(db.db_path) as conn: + conn.execute('UPDATE users SET telegram_id=NULL') + assert (await client.get('/sso/verify?app=demo')).status_code == 403 + with sqlite3.connect(db.db_path) as conn: + conn.execute('UPDATE sessions SET expires_at=0') + assert (await client.get('/sso/verify?app=demo')).status_code == 401 + + +async def test_verify_redirects_and_revocation(db, client): + await linked(db) + add_app(db, origins=['https://app.example.com'], policy='all') + original = 'https://app.example.com/x?a=1&b=%E7%94%A8%E6%88%B7' + response = await client.get('/sso/verify?app=demo', headers={'X-Original-URL': original}) + assert response.status_code == 401 + target = response.headers['x-telelogin-login'] + assert parse_qs(urlsplit(target).query)['app'] == ['demo'] + assert parse_qs(urlsplit(target).query)['rd'] == [original] + response = await client.get('/sso/verify?app=demo&redirect=1', headers={'X-Forwarded-Proto': 'https', 'X-Forwarded-Host': 'app.example.com', 'X-Forwarded-Uri': '/x?a=1&b=2'}) + assert response.status_code == 302 + assert parse_qs(urlsplit(response.headers['location']).query)['rd'] == ['https://app.example.com/x?a=1&b=2'] + response = await client.get('/sso/verify?app=demo', headers={'X-Original-URL': 'https://evil.test'}) + assert 'rd' not in parse_qs(urlsplit(response.headers['x-telelogin-login']).query) + data = await start(client) + await approve(client, data) + await complete(client, data) + sessions = (await db.account_action(42, 'sessions'))['sessions'] + assert sessions[0]['kind'] == 'sso' + assert (await client.post('/internal/sessions/revoke', json={'telegram_id': 42, 'session_id': sessions[0]['id']}, headers=INTERNAL)).status_code == 200 + assert (await client.get('/sso/verify?app=demo')).status_code == 401 + + +@pytest.mark.parametrize('target', ['//evil', '/\\evil', 'https://evil', 'https://test.evil', 'javascript:x', 'http://test@evil', '/%5cevil', '/%2fevil', '/%252fevil', 'http://test/\r\nx', 'https://sibling.example.com']) +def test_redirect_rejections(target, monkeypatch): + monkeypatch.setattr(settings, 'PUBLIC_URL', 'http://test/telelogin') + assert return_url(target) is None + + +def test_redirect_context(monkeypatch): + monkeypatch.setattr(settings, 'PUBLIC_URL', 'http://test/telelogin') + app_x = {'origins': '["https://app.example.com"]'} + assert return_url('/local', app_x) == 'http://test/local' + assert return_url('https://app.example.com/x?q=用户&a=2', app_x) + assert return_url('https://app.example.com', {'origins': '[]'}) is None + assert return_url('http://test:80/path') + assert return_url('http://test:81/path') is None + assert return_url('/' + 'x' * 2048) is None + + +async def test_csrf_logout_pages_and_dummy(db, client): + await linked(db) + add_app(db, policy='all') + for endpoint in ('start', 'complete', 'logout'): + assert (await client.post('/sso/' + endpoint, json={}, headers={'Origin': 'https://evil.test'})).status_code == 403 + assert (await client.post('/sso/' + endpoint, content='{}')).status_code == 403 + for username in ('missing', 'unlinked'): + if username == 'unlinked': + await db.create_user(username) + data = await start(client, username) + assert set(data) == {'status', 'verification_code', 'login_id'} + assert (await db.get_login_request(data['login_id']))['user_id'] == 0 + data = await start(client, rd='/app') + await approve(client, data) + await complete(client, data) + response = await client.get('/login?app=demo&rd=/app') + assert response.status_code == 302 and response.headers['location'] == 'http://test/app' + assert (await client.get('/login?app=demo&rd=/app&force=1')).status_code == 200 + assert 'Sign in to Demo <app>' in (await client.get('/login?app=demo')).text + assert 'Signed in as alice' in (await client.get('/')).text + assert 'Confirm logout' in (await client.get('/logout?app=demo&rd=/app')).text + assert (await client.get('/sso/verify?app=demo')).status_code == 200 + response = await client.post('/sso/logout', data={'app': 'demo', 'rd': '/app'}, headers={'Origin': 'http://test'}) + assert response.status_code == 303 and response.headers['location'] == 'http://test/app' + assert 'Max-Age=0' in response.headers['set-cookie'] + assert (await client.get('/sso/verify?app=demo')).status_code == 401 + assert 'Sign in' in (await client.get('/')).text + assert (await client.post('/sso/logout', json={})).headers['location'] == 'http://test/telelogin/login' + + +async def test_wrong_code_expiry_and_delete_cascade(db, client): + user = await linked(db) + add_app(db) + allow(db, user) + data = await start(client) + assert (await client.post('/auth/confirm-login', json={'login_id': data['login_id'], 'telegram_id': 42, 'verification_code': 10 if data['verification_code'] != 10 else 11}, headers=INTERNAL)).status_code == 400 + assert (await complete(client, data)).json()['status'] == 'denied' + data = await start(client) + with sqlite3.connect(db.db_path) as conn: + conn.execute('UPDATE login_requests SET expires_at=0') + assert (await complete(client, data)).json()['status'] == 'expired' + await db.account_action(42, 'delete') + with sqlite3.connect(db.db_path) as conn: + assert conn.execute('SELECT COUNT(*) FROM app_users').fetchone()[0] == 0 + + +@pytest.mark.parametrize('domain', ['127.0.0.1', 'localhost', '.example.com', 'other.com', 'co.uk', 'github.io']) +def test_invalid_cookie_domain(domain): + host = 'auth.' + domain if domain in ('co.uk', 'github.io') else 'auth.example.com' + with pytest.raises(ValidationError): + Settings(PUBLIC_URL='https://' + host, SSO_COOKIE_DOMAIN=domain, _env_file=None) + + +def test_offline_psl_and_public_url(monkeypatch): + monkeypatch.setattr(socket, 'create_connection', lambda *a, **k: pytest.fail('Network used')) + monkeypatch.setattr(socket.socket, 'connect', lambda *a, **k: pytest.fail('Network used')) + value = Settings(PUBLIC_URL='https://auth.example.co.uk/prefix/', SSO_COOKIE_DOMAIN='example.co.uk', _env_file=None) + assert value.PUBLIC_URL == 'https://auth.example.co.uk/prefix' + for url in ('ftp://host', 'https://host/?q=1', 'https://host/#x', 'https://user@host'): + with pytest.raises(ValidationError): + Settings(PUBLIC_URL=url, _env_file=None) + + +async def test_closed_registration(db, client, monkeypatch): + monkeypatch.setattr(settings, 'REGISTRATION_MODE', 'closed') + assert (await client.post('/register', json={'username': 'alice'})).status_code == 403 + + +async def test_baseline_migration(tmp_path, client, monkeypatch): + path = tmp_path / 'old.db' + with sqlite3.connect(path) as conn: + conn.executescript(''' + 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); + 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); + CREATE TABLE sessions(id TEXT PRIMARY KEY,user_id INTEGER NOT NULL,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); + INSERT INTO users(username,telegram_id) VALUES ('alice',42),('bob',43); + INSERT INTO sessions(id,user_id,refresh_hash,created_at,expires_at) VALUES ('old',1,'hash',1,9999999999); + ''') + db = SQLiteDatabase(str(path)) + await db.init_db() + await db.init_db() + monkeypatch.setattr(app.state, 'db', db) + assert (await client.post('/register', json={'username': 'alice'})).status_code == 400 + a = await db.get_user_by_username('alice') + assert a.public_id and a == await db.get_user_by_telegram_id(42) + assert a.public_id != (await db.get_user_by_username('bob')).public_id + with pytest.raises(sqlite3.IntegrityError): + await db.create_user('alice') + with sqlite3.connect(path) as conn: + assert conn.execute('SELECT kind FROM sessions').fetchone()[0] == 'api' + + +async def test_concurrent_cookie_delivery(db, client): + await linked(db) + data = await start(client) + await approve(client, data) + responses = await asyncio.gather(complete(client, data), complete(client, data)) + assert sum('set-cookie' in response.headers for response in responses) == 1 + assert all(response.json()['status'] == 'approved' for response in responses) + + +async def test_shared_login_rate_limit(db, client, monkeypatch): + monkeypatch.setattr(settings, 'RATE_LIMIT_USERNAME', 1) + assert (await client.post('/auth/start-login', json={'username': 'missing'})).status_code == 200 + assert (await client.post('/sso/start', json={'username': 'missing'})).status_code == 429 + + +async def test_throttle_invalid_cookie_and_notification(db, client, monkeypatch): + await linked(db) + add_app(db, policy='all') + notify = AsyncMock() + monkeypatch.setattr('src.services.auth_service.AuthService.send_login_notification', notify) + data = await start(client) + assert notify.call_args.args[-1] == 'Demo ' + await approve(client, data) + await complete(client, data) + await client.get('/sso/verify?app=demo') + with sqlite3.connect(db.db_path) as conn: + conn.execute('UPDATE sessions SET last_used_at=?', (time.time() - 301,)) + await client.get('/sso/verify?app=demo') + with sqlite3.connect(db.db_path) as conn: + assert conn.execute('SELECT last_used_at FROM sessions').fetchone()[0] > time.time() - 2 + client.cookies.clear() + client.cookies.set(settings.SSO_COOKIE_NAME, 'invalid') + assert (await client.get('/sso/verify?app=demo')).status_code == 401 + response = await client.options('/sso/start', headers={'Origin': 'http://test', 'Access-Control-Request-Method': 'POST'}) + assert 'access-control-allow-origin' not in response.headers + + +@pytest.mark.parametrize('app_id,logged', [(None, True), ('', False), ('unknown-app', True), ('bad\r\nvalue', False), ('x' * 10000, False), ('BAD', False)]) +async def test_verify_warning_log_is_bounded(app_id, logged, caplog): + from types import SimpleNamespace + from starlette.requests import Request + from src.web.sso import verify + request = Request({'type': 'http', 'method': 'GET', 'path': '/sso/verify', 'query_string': b'', + 'headers': [] if app_id is None else [(b'x-telelogin-app', app_id.encode())]}) + db = SimpleNamespace(get_app=AsyncMock(return_value=None), browser_session=AsyncMock(return_value=None)) + with caplog.at_level('WARNING', logger='src.web.sso'): + response = await verify(request, db) + assert response.status_code == 401 + records = [r for r in caplog.records if r.name == 'src.web.sso'] + assert len(records) == int(logged) + if logged: + assert records[0].getMessage() == 'Missing or unknown forward-auth app: ' + repr(app_id)[:80]