From c1d2526837008be13c53c7713b0180dc0d51fb08 Mon Sep 17 00:00:00 2001 From: root Date: Thu, 22 Oct 2026 15:43:52 +0000 Subject: [PATCH] Part C: packaging for self-hosters (2.0.0) - Release workflow: on vX.Y.Z tags only, builds linux/amd64 + linux/arm64 and pushes ghcr.io//telelogin: (+ latest for final releases only) with OCI labels; never runs on branches or PRs. - deploy/: image-only docker-compose.yml, .env.example (secrets empty; known placeholder secrets are rejected at startup), and docker-compose.docker-proxy.yml for proxies running in Docker (no published API port; API reachable as `telelogin` on the compose network). - Version 2.0.0 (FastAPI version, /health reports it). - README quick start from zero to a protected app, CHANGELOG.md with breaking changes and upgrade steps, SECURITY.md, CONTRIBUTING.md. - docs/INTEGRATION.md: explicit upstream per topology (host proxy vs Docker proxy) and release-install admin commands. - Part B follow-ups: fsync + clear hard-link error in OIDC key creation, deterministic concurrent key test, example logout Origin via APP_ORIGIN. Built by Codex from the reviewed plan; inspected twice by fresh Claude sessions (first: 5 findings fixed by Codex; second: APPROVED with four optional low findings). Verification: 169 tests pass (also with -W error), ruff and actionlint clean, compose configs valid; two fresh-user walkthroughs of the quick start (host Caddy; Traefik in Docker with the shipped example unmodified) completed a full login. Co-Authored-By: Claude Opus 5.5 --- .gitattributes | 1 + .github/workflows/ci.yml | 3 + .github/workflows/release.yml | 51 +++++++++ CHANGELOG.md | 60 ++++++++++ CONTRIBUTING.md | 37 ++++++ README.md | 149 ++++++++++++++++++------- SECURITY.md | 13 +++ deploy/.env.example | 54 +++++++++ deploy/docker-compose.docker-proxy.yml | 5 + deploy/docker-compose.yml | 101 +++++++++++++++++ docker/docker-compose.yml | 4 +- docker/env.example | 8 +- docs/INTEGRATION.md | 89 +++++++++++++-- examples/oidc_fastapi/app.py | 5 +- src/__init__.py | 2 +- src/app.py | 5 +- src/config.py | 12 +- src/web/oidc.py | 9 ++ tests/test_oidc.py | 71 +++++++++++- tests/test_phase2.py | 17 ++- tests/test_security.py | 10 ++ 21 files changed, 641 insertions(+), 65 deletions(-) create mode 100644 .github/workflows/release.yml create mode 100644 CHANGELOG.md create mode 100644 CONTRIBUTING.md create mode 100644 SECURITY.md create mode 100644 deploy/.env.example create mode 100644 deploy/docker-compose.docker-proxy.yml create mode 100644 deploy/docker-compose.yml diff --git a/.gitattributes b/.gitattributes index 15848e2..0ab68c9 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1,3 +1,4 @@ +deploy/* text eol=lf docker/entrypoint.sh text eol=lf tests/e2e/*.sh text eol=lf examples/nginx/*.conf text eol=lf diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 2cd2225..e30d2e0 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -62,6 +62,9 @@ jobs: - name: Validate compose file run: docker compose -f docker/docker-compose.yml config --quiet + - name: Validate release compose file + run: docker compose -f deploy/docker-compose.yml config --quiet + - name: Build images run: docker compose -f docker/docker-compose.yml build diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..ac18fb4 --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,51 @@ +name: Release image + +on: + push: + tags: ['v*.*.*'] + +permissions: {} + +jobs: + release: + runs-on: ubuntu-latest + permissions: + contents: read + packages: write + steps: + - uses: actions/checkout@v4 + - uses: docker/setup-qemu-action@v3 + - uses: docker/setup-buildx-action@v3 + - name: Image name + id: image + env: + OWNER: ${{ github.repository_owner }} + TAG: ${{ github.ref_name }} + run: | + echo "name=ghcr.io/${OWNER,,}/telelogin" >> "$GITHUB_OUTPUT" + echo "version=${TAG#v}" >> "$GITHUB_OUTPUT" + - uses: docker/login-action@v3 + with: + registry: ghcr.io + username: ${{ github.actor }} + password: ${{ secrets.GITHUB_TOKEN }} + - uses: docker/metadata-action@v5 + id: meta + with: + images: ${{ steps.image.outputs.name }} + flavor: latest=auto + tags: | + type=semver,pattern={{version}} + labels: | + org.opencontainers.image.source=${{ github.server_url }}/${{ github.repository }} + org.opencontainers.image.description=Telegram authentication with forward auth and OpenID Connect + org.opencontainers.image.licenses=Apache-2.0 + org.opencontainers.image.version=${{ steps.image.outputs.version }} + - uses: docker/build-push-action@v6 + with: + context: . + file: docker/Dockerfile + platforms: linux/amd64,linux/arm64 + push: true + tags: ${{ steps.meta.outputs.tags }} + labels: ${{ steps.meta.outputs.labels }} diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..15a0e1c --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,60 @@ +# Changelog + +All notable changes are documented here, following [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). +Versions follow semantic versioning. + +## [2.0.0] - Unreleased + +### Added + +- Shared 30-day browser SSO sessions and forward auth for nginx, Traefik and Caddy. +- Operator CLI for apps, per-app allowlists, access policies and user invitations. +- Confidential OpenID Connect authorization code clients, PKCE S256, discovery, RS256 ID + tokens, JWKS and opaque access tokens for userinfo. +- Image release workflow for amd64/arm64 and image-only deployment files under `deploy/`. +- Integration guide, proxy examples, Authlib example and real proxy end-to-end checks. +- Stable public user identifiers, closed registration mode and configurable cookie domains. + +### Changed + +- Browser login uses a shared HttpOnly session cookie; raw API and JavaScript client remain available. +- Browser sessions appear in bot session management and participate in account deletion and revocation. +- Signing keys are persisted with concurrent first-start protection and durable publication. + +**Breaking changes** + +- Compose publishes the API port on `127.0.0.1` only; use a reverse proxy. +- Compose defaults `FORWARDED_ALLOW_IPS` to `*` for a proxy on the host. This is safe only + with the loopback binding or a private network restricted to trusted callers. +- `GET /` returns an HTML account page instead of JSON. +- `/login` uses the SSO cookie flow instead of storing API tokens in sessionStorage. +- `/health` now returns `{"status":"ok","version":"2.0.0"}`. + +### Security + +- API and SSO grants are separated; return URLs and app origins are validated per app. +- Browser POSTs enforce content types and same-origin checks; identity headers are encoded + and proxy examples remove spoofed headers. +- OIDC codes are single-use and client-bound; replay revokes associated access tokens. +- Private RSA keys use mode 0600; cookie domain checks use an offline public suffix snapshot. + +### Upgrading from 1.x + +1. Stop API and bot and back up your SQLite database, environment file and data volume. +2. Review the breaking changes above. Configure HTTPS and a reverse proxy, including + forwarded headers and blocking public access to internal endpoints. Update health-body consumers. +3. Keep `SECRET_KEY`, `INTERNAL_API_KEY`, bot credentials and your existing data volume. + For an existing Compose installation, keep its project name and volume mapping: moving + to `deploy/` changes the default project name and can create an empty volume. Set + `COMPOSE_PROJECT_NAME` to the old project name or explicitly map the existing volume. +4. Copy the release environment template and transfer existing settings; set `PUBLIC_URL`, + cookie settings and registration policy. Keep the generated OIDC key in the persistent + data volume and include it in backups. Do not regenerate existing secrets during upgrades. +5. Set `TELELOGIN_VERSION=2.0.0`, pull the image and start API and bot. Startup applies + idempotent schema migrations. Check `/health`, logs and a Telegram login. +6. Register apps and allow users as described in the integration guide. Update custom + browser integrations relying on `/login` tokens to use SSO or the raw API explicitly. + Legacy API tokens without a session id require a fresh login. + +Rollback requires restoring the backup and the previous image together; do not assume +an older server supports the migrated schema. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..db4d358 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,37 @@ +# Contributing + +Use Python 3.11+ and Node.js for the JavaScript client checks. From the checkout root: + +```bash +python3 -m venv .venv +.venv/bin/pip install -r requirements-dev.txt +cp .env.example .env +``` + +Configure the local bot credentials and secrets in `.env`. For development run +`.venv/bin/uvicorn src.app:app` and `.venv/bin/python -m src.bot` in separate terminals. + +Run the proof command before submitting a PR: + +```bash +.venv/bin/python -m pytest -q && .venv/bin/ruff check src tests && .venv/bin/python -W error::DeprecationWarning -m pytest -q +``` + +With Docker available, run each real proxy check: + +```bash +tests/e2e/forward_auth.sh nginx +tests/e2e/forward_auth.sh traefik +tests/e2e/forward_auth.sh caddy +``` + +Preserve existing line endings: Python under `src/` and `tests/`, `docker/*.yml` and +`docker/env.example` use CRLF. Markdown, workflow YAML, shell scripts, proxy examples and +new `deploy/` files use LF. Follow `.gitattributes`; avoid whole-file newline churn. + +PRs should describe the concrete problem, resulting behavior, relevant tests and any +limitations. Include regression coverage for behavior changes and update affected examples +and documentation. Never commit secrets, runtime databases or private keys. Maintainers +publish releases by tagging; a normal branch or PR does not run the release workflow. +Stable semantic version tags update `latest`; prerelease tags (for example `v2.1.0-rc.1`) +publish their version tag without moving `latest`. diff --git a/README.md b/README.md index e11ff1e..27b6d19 100644 --- a/README.md +++ b/README.md @@ -1,14 +1,82 @@ # 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 supports confidential clients with authorization code flow and PKCE S256. +TeleLogin provides Telegram-confirmed login through a self-hosted bot. Protect apps with +Mode 2 forward auth through nginx, Traefik or Caddy, connect standard clients with Mode 1 +OpenID Connect, or build a custom UI with the raw API. Shared browser sessions and per-app +access policies let connected apps reuse one Telegram confirmation. Python 3.11+. -**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. +## Quick start + +Run these commands from the root of this checkout with Docker Compose v2 installed. +The release image below becomes available when the maintainer publishes 2.0.0. +For a pre-release walkthrough, build it locally first: +`docker build -f docker/Dockerfile -t ghcr.io/downlevel/telelogin:2.0.0 .`. + +1. Create a Telegram bot with **@BotFather**. Save its token and username (without `@`). +2. Generate the two server secrets: + + ```bash + docker run --rm ghcr.io/downlevel/telelogin:2.0.0 python -m src.admin gen-secrets + cp deploy/.env.example deploy/.env + ``` + + Edit `deploy/.env`: fill `BOT_TOKEN`, `BOT_USERNAME`, `SECRET_KEY` and + `INTERNAL_API_KEY` with your values. Set `PUBLIC_URL` to your external HTTPS URL, + for example `https://auth.example.com` or `https://example.com/telelogin`. + Keep `SSO_COOKIE_SECURE=true`. For sibling apps, set `SSO_COOKIE_DOMAIN=example.com` + only if every subdomain is trusted. The domain must match your own deployment. +3. Start the services: + + ```bash + docker compose -f deploy/docker-compose.yml up -d + ``` + + Configure your HTTPS proxy using the matching [integration example](docs/INTEGRATION.md). + The API listens on host loopback port 8000; a Docker proxy instead needs a shared private + network and no published API port (see the guide). Proxy the configured public URL to + the API, stripping any path prefix, and block internal endpoints. +4. Invite yourself (works with both open and closed registration): + + ```bash + docker compose -f deploy/docker-compose.yml exec api python -m src.admin user invite alice + ``` + + The hosted `/login` page signs in existing users; it has no registration control. + Open the printed link and press Start in Telegram. Replace `alice` consistently with + your chosen username in these commands. +5. Register and authorize the first app: + + ```bash + docker compose -f deploy/docker-compose.yml exec api python -m src.admin app add myapp --name "My App" + docker compose -f deploy/docker-compose.yml exec api python -m src.admin app allow myapp alice + ``` + + For a sibling app, register its actual origin too: + + ```bash + docker compose -f deploy/docker-compose.yml exec api python -m src.admin app origin add myapp https://app.example.com + ``` + +6. Paste the nginx, Traefik or Caddy protection snippet from + [the integration guide](docs/INTEGRATION.md), using app id `myapp` and your actual + hostnames/upstream. Host proxy → `127.0.0.1:8000` (replace `8000` with `API_PORT`); proxy in Docker → `telelogin:8000` after joining the TeleLogin Compose network (`deploy_telelogin_network` by default). + For Docker, start with the [port-removal override and network setup](docs/INTEGRATION.md#docker-proxy-networking): + + ```bash + docker compose -f deploy/docker-compose.yml -f deploy/docker-compose.docker-proxy.yml up -d + ``` + + Keep the app reachable only through that proxy. Visit the app, + sign in and select the displayed number in Telegram. + +For an optional OIDC app, use `app add` with `--redirect-uri` and configure the printed +client secret, discovery URL and `openid profile` scopes as described in +[Mode 1](docs/INTEGRATION.md#mode-1-openid-connect). + +## Upgrading from 1.x + +Read the [breaking changes and upgrade steps](CHANGELOG.md#upgrading-from-1x) before +starting 2.0.0, especially the existing volume mapping and proxy settings. | Browser/SSO setting | Default | Purpose | | --- | --- | --- | @@ -29,9 +97,6 @@ a browser account page instead of JSON. `/health` remains unchanged. | `/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 - OpenID Connect discovery, RS256 ID tokens, opaque access tokens, and shared browser SSO. @@ -49,40 +114,44 @@ Telegram login confirmation using FastAPI, a Telegram bot and SQLite. Python 3.1 telelogin/ ├── src/ │ ├── app.py # FastAPI application and lifespan -│ ├── bot.py # Telegram bot and notification HTTP server +│ ├── admin.py # Operator CLI +│ ├── bot.py # Telegram bot and notification server │ ├── config.py # Validated environment settings -│ ├── database/ -│ │ ├── base.py # Database interface -│ │ └── sqlite.py # Schema, migrations and atomic operations -│ ├── models/user.py # User model -│ ├── services/ -│ │ ├── auth_service.py # Login and background notifications -│ │ ├── token_service.py # Persistent registration tokens -│ │ └── user_service.py # User operations -│ ├── utils/crypto.py # JWT signing and verification +│ ├── database/ # Schema, migrations and atomic operations +│ ├── models/ # User model +│ ├── services/ # Authentication, registration and user operations +│ ├── utils/ # API token signing and verification │ └── web/ -│ ├── dependencies.py # Application-scoped dependency providers -│ ├── routes.py # Authentication routes +│ ├── routes.py # Raw API +│ ├── sso.py # Browser sessions and forward auth +│ ├── oidc.py # OpenID Connect provider +│ ├── dependencies.py # Application-scoped providers │ ├── schemas.py # Request/response validation │ ├── security.py # Internal key checks and rate limiter -│ └── templates/index.html # Browser login page -├── tests/ -│ ├── conftest.py # Environment and temporary database fixtures -│ ├── test_security.py # Phase 1 security regressions -│ └── test_phase2.py # Architecture and integration checks -├── docker/ -│ ├── Dockerfile -│ ├── entrypoint.sh # Volume ownership migration and privilege drop -│ ├── docker-compose.yml -│ └── env.example +│ └── templates/index.html # Hosted login +├── deploy/ +│ ├── docker-compose.yml # Release images +│ ├── docker-compose.docker-proxy.yml # Remove published port for Docker proxies +│ └── .env.example # Release configuration template +├── docker/ # Development Compose, Dockerfile and entrypoint +├── docs/INTEGRATION.md # Deployment and app integration guide ├── examples/ -│ ├── curl_examples.md -│ └── js_client/ # JavaScript client and demo -├── .env.example +│ ├── nginx/ # Forward auth configurations +│ ├── traefik/ # Dynamic configuration and labels +│ ├── caddy/ # Forward auth Caddyfiles +│ ├── oidc_fastapi/ # Authlib client +│ ├── js_client/ # Raw API JavaScript client and demo +│ └── curl_examples.md +├── tests/ # Unit/integration tests and e2e/ proxy harness +├── .github/workflows/ # CI and tag-only image releases +├── .env.example # Local development configuration ├── .gitattributes ├── pyproject.toml ├── requirements.txt ├── requirements-dev.txt +├── CHANGELOG.md +├── SECURITY.md +├── CONTRIBUTING.md ├── README.md └── LICENSE ``` @@ -175,7 +244,7 @@ Both templates declare all supported variables. Required secrets must be supplie | --- | --- | | GET / | Browser account page (HTML) | | GET /login | Hosted browser login; optional app and rd parameters | -| GET /health | 200 {"status":"ok"} after a database query | +| GET /health | 200 {"status":"ok","version":"2.0.0"} after a database query | | POST /register | {"username":"alice"}; returns Telegram registration link; duplicate username 400 | | GET /.well-known/openid-configuration | OIDC discovery | | GET /jwks.json | Public RSA signing key | @@ -338,8 +407,10 @@ are present in both environment templates and Docker Compose. GitHub Actions (`.github/workflows/ci.yml`) runs on every push to main and every pull request: Ruff, the test suite on Python 3.11 and 3.12 (including the Node client -simulation and a warnings-as-errors pass), a compose validation, the image build and an -API smoke test (`/health`, `/auth/me` → 401). +simulation and a warnings-as-errors pass), development and deploy Compose validation, +the image build and an API smoke test (`/health`, `/auth/me` → 401). A separate e2e job +runs the real nginx, Traefik and Caddy forward-auth checks. Actionlint is a host review +check and is not run in CI. ```bash .venv/bin/python -m pytest -q && .venv/bin/ruff check src tests && .venv/bin/python -W error::DeprecationWarning -m pytest -q diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 0000000..2e8232c --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,13 @@ +# Security policy + +The supported version line is **2.x**. Use the latest available patch release. + +Report vulnerabilities privately using this repository's GitHub **Security → Report a +vulnerability** (private vulnerability reporting / Security Advisories). Include affected +versions, reproduction steps and impact. Do not disclose credentials or exploit details in +public issues. If private reporting is unavailable, ask the maintainers to enable it without +posting vulnerability details. + +Scope includes the TeleLogin server, Telegram bot and shipped integration examples. +Misconfigured deployments are out of scope, including exposed internal endpoints, untrusted +cookie subdomains, public backends bypassing the proxy, and trusting arbitrary forwarded headers. diff --git a/deploy/.env.example b/deploy/.env.example new file mode 100644 index 0000000..33951c0 --- /dev/null +++ b/deploy/.env.example @@ -0,0 +1,54 @@ +# Release deployment settings. Copy to deploy/.env; never commit secrets. +TELELOGIN_VERSION=2.0.0 + +# Telegram Bot Token (get from @BotFather) +BOT_TOKEN= + +# Database configuration (SQLite only) +DB_URL=sqlite:///data/db.sqlite3 + +# Security +# run gen-secrets and paste SECRET_KEY below +SECRET_KEY= + +# Application settings +DEBUG=false +ALGORITHM=HS256 +ACCESS_TOKEN_EXPIRE_MINUTES=15 +BOT_USERNAME=your_bot_username + +# API Port (default: 8000) +API_PORT=8000 + +# run gen-secrets and paste INTERNAL_API_KEY below +INTERNAL_API_KEY= +LOGIN_REQUEST_TTL_SECONDS=120 +REGISTRATION_TOKEN_TTL_SECONDS=1800 +RATE_LIMIT_WINDOW_SECONDS=600 +RATE_LIMIT_USERNAME=5 +RATE_LIMIT_IP=20 +CORS_ORIGINS=[] + +API_BASE_URL=http://api:8000 +BOT_NOTIFY_URL=http://bot:8001/notify-login +# 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=https://auth.example.com +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 + +# Keep the private signing key persistent and readable only by the API user. +OIDC_KEY_FILE=data/oidc-signing-key.pem +OIDC_CODE_TTL_SECONDS=60 +OIDC_TOKEN_TTL_SECONDS=600 diff --git a/deploy/docker-compose.docker-proxy.yml b/deploy/docker-compose.docker-proxy.yml new file mode 100644 index 0000000..307878b --- /dev/null +++ b/deploy/docker-compose.docker-proxy.yml @@ -0,0 +1,5 @@ +# Use with docker-compose.yml when the reverse proxy shares the Compose network. +# Requires Docker Compose 2.24.0+ for !reset. +services: + api: + ports: !reset [] diff --git a/deploy/docker-compose.yml b/deploy/docker-compose.yml new file mode 100644 index 0000000..48da68d --- /dev/null +++ b/deploy/docker-compose.yml @@ -0,0 +1,101 @@ +services: + # FastAPI backend + api: + image: ghcr.io/downlevel/telelogin:${TELELOGIN_VERSION:-2.0.0} + ports: + - "127.0.0.1:${API_PORT:-8000}:8000" + environment: + - BOT_TOKEN=${BOT_TOKEN} + - BOT_USERNAME=${BOT_USERNAME:-YourBot} + - DB_URL=${DB_URL:-sqlite:///data/db.sqlite3} + - SECRET_KEY=${SECRET_KEY} + - 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} + # '*' 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:-} + - OIDC_KEY_FILE=${OIDC_KEY_FILE:-data/oidc-signing-key.pem} + - OIDC_CODE_TTL_SECONDS=${OIDC_CODE_TTL_SECONDS:-60} + - OIDC_TOKEN_TTL_SECONDS=${OIDC_TOKEN_TTL_SECONDS:-600} + - REGISTRATION_MODE=${REGISTRATION_MODE:-open} + - DEBUG=${DEBUG:-false} + - CORS_ORIGINS=${CORS_ORIGINS:-[]} + - LOGIN_REQUEST_TTL_SECONDS=${LOGIN_REQUEST_TTL_SECONDS:-120} + - REGISTRATION_TOKEN_TTL_SECONDS=${REGISTRATION_TOKEN_TTL_SECONDS:-1800} + - RATE_LIMIT_WINDOW_SECONDS=${RATE_LIMIT_WINDOW_SECONDS:-600} + - RATE_LIMIT_USERNAME=${RATE_LIMIT_USERNAME:-5} + - RATE_LIMIT_IP=${RATE_LIMIT_IP:-20} + volumes: + - api_data:/app/data + healthcheck: + test: ["CMD", "python", "-c", "import urllib.request; urllib.request.urlopen('http://localhost:8000/health', timeout=5)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 30s + start_interval: 2s + restart: unless-stopped + networks: + telelogin_network: + aliases: + - telelogin + + # Telegram bot + bot: + image: ghcr.io/downlevel/telelogin:${TELELOGIN_VERSION:-2.0.0} + command: ["python", "-m", "src.bot"] + environment: + - BOT_TOKEN=${BOT_TOKEN} + - BOT_USERNAME=${BOT_USERNAME:-YourBot} + - DB_URL=${DB_URL:-sqlite:///data/db.sqlite3} + - SECRET_KEY=${SECRET_KEY} + - 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} + # '*' 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: + - api_data:/app/data + depends_on: + api: + condition: service_healthy + healthcheck: + test: ["CMD", "python", "-c", "import urllib.request; urllib.request.urlopen('http://localhost:8001/health', timeout=5)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 30s + start_interval: 2s + restart: unless-stopped + networks: + - telelogin_network + +volumes: + api_data: + +networks: + telelogin_network: + driver: bridge diff --git a/docker/docker-compose.yml b/docker/docker-compose.yml index c8be033..720b2cb 100644 --- a/docker/docker-compose.yml +++ b/docker/docker-compose.yml @@ -48,7 +48,9 @@ services: start_interval: 2s restart: unless-stopped networks: - - telelogin_network + telelogin_network: + aliases: + - telelogin # Telegram bot bot: diff --git a/docker/env.example b/docker/env.example index d3352e8..a35bb14 100644 --- a/docker/env.example +++ b/docker/env.example @@ -1,13 +1,14 @@ # Environment variables for Docker deployment # Telegram Bot Token (get from @BotFather) -BOT_TOKEN=your_bot_token_here +BOT_TOKEN= # Database configuration (SQLite only) DB_URL=sqlite:///data/db.sqlite3 # Security -SECRET_KEY=your_secret_key_here_minimum_32_characters_long +# run gen-secrets and paste SECRET_KEY below +SECRET_KEY= # Application settings DEBUG=false @@ -18,7 +19,8 @@ BOT_USERNAME=your_bot_username # API Port (default: 8000) API_PORT=8000 -INTERNAL_API_KEY=replace_with_shared_random_secret_at_least_32_characters +# run gen-secrets and paste INTERNAL_API_KEY below +INTERNAL_API_KEY= LOGIN_REQUEST_TTL_SECONDS=120 REGISTRATION_TOKEN_TTL_SECONDS=1800 RATE_LIMIT_WINDOW_SECONDS=600 diff --git a/docs/INTEGRATION.md b/docs/INTEGRATION.md index e9f1842..ba9ddea 100644 --- a/docs/INTEGRATION.md +++ b/docs/INTEGRATION.md @@ -9,25 +9,28 @@ One Telegram confirmation creates a browser session lasting `REFRESH_TOKEN_TTL_D | 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 | +| OpenID Connect (Mode 1) | An app uses a standard OIDC library or an unrelated domain | Confidential clients; standard OIDC library | | Raw API | You need a custom login UI and token lifecycle | Existing `/register` and `/auth/*` API, [README](../README.md) | +All Compose commands below use the release installation in `deploy/`, run from the checkout +root. Developers using `docker/` substitute `docker/docker-compose.yml` for that path. + ## 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`. + `docker compose -f deploy/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 + docker compose -f deploy/docker-compose.yml exec api python -m src.admin app add myapp --name 'My App' + docker compose -f deploy/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 + docker compose -f deploy/docker-compose.yml exec api python -m src.admin app policy myapp all ``` 3. Choose a deployment shape: @@ -38,7 +41,7 @@ One Telegram confirmation creates a browser session lasting `REFRESH_TOKEN_TTL_D 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 + docker compose -f deploy/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 @@ -65,8 +68,56 @@ All three proxies cover both the prefix and sibling-subdomain shapes. No real bo 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. +### Docker proxy networking + +For a proxy on the host, keep the base Compose file and its loopback port binding. +For a proxy in Docker, remove the published API port with the shipped override (Docker +Compose 2.24.0+ is required for `!reset`): + +```sh +docker compose -f deploy/docker-compose.yml -f deploy/docker-compose.docker-proxy.yml up -d +``` + +Use both `-f` arguments on subsequent `up` commands so the port stays unpublished. +With the default project name `deploy`, the network is `deploy_telelogin_network`; if you +set `COMPOSE_PROJECT_NAME` or `-p`, replace `deploy` with that project name. The API has +network alias `telelogin`. The development project's default network is `docker_telelogin_network`. + +In the proxy's separate Compose file, attach its service to that existing network (merge +this into the proxy's configuration; retain any other networks it needs): + +```yaml +services: + proxy: + networks: + - telelogin +networks: + telelogin: + external: true + name: deploy_telelogin_network +``` + +Start TeleLogin first so the network exists. Alternatively, for an already running proxy +container named `caddy`, attach it with: + +```sh +docker network connect deploy_telelogin_network caddy +``` + +Replace `caddy` with your actual proxy container name; a manual attachment must be repeated +if that container is recreated. Attach the protected app to a network reachable by the proxy +as well, and replace the example app upstream separately. Only trusted containers may join +the TeleLogin network when `FORWARDED_ALLOW_IPS=*` is used. + +The Caddy and Traefik examples already use `telelogin:8000`. For host proxies replace that +TeleLogin upstream everywhere with `127.0.0.1:8000` (or your `API_PORT`). The nginx examples +use the host upstream; for Docker replace every TeleLogin `127.0.0.1:8000` upstream with +`telelogin:8000`. Preserve URL paths and trailing slashes when replacing upstreams. + ### nginx +Host proxy → `127.0.0.1:8000` (replace `8000` with `API_PORT`); proxy in Docker → `telelogin:8000` after joining the TeleLogin Compose network (`deploy_telelogin_network` by default). See [Docker proxy networking](#docker-proxy-networking) for the network attachment and port-removal override. + 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 @@ -80,6 +131,8 @@ blocks public access to `/internal/*`. Keep the verify location `internal`. ### Traefik +Host proxy → `127.0.0.1:8000` (replace `8000` with `API_PORT`); proxy in Docker → `telelogin:8000` after joining the TeleLogin Compose network (`deploy_telelogin_network` by default). See [Docker proxy networking](#docker-proxy-networking) for the network attachment and port-removal override. + 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 @@ -90,11 +143,12 @@ For a shared host replace its routers with [prefix.yml](../examples/traefik/pref 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. +not run by the e2e test). ### Caddy +Host proxy → `127.0.0.1:8000` (replace `8000` with `API_PORT`); proxy in Docker → `telelogin:8000` after joining the TeleLogin Compose network (`deploy_telelogin_network` by default). See [Docker proxy networking](#docker-proxy-networking) for the network attachment and port-removal override. + 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 @@ -109,7 +163,7 @@ preserves header-removal-before-auth ordering, then `copy_headers` supplies the 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. + does not isolate cookies. Unrelated domains require Mode 1. - 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 @@ -130,7 +184,8 @@ preserves header-removal-before-auth ordering, then `copy_headers` supplies the ## Operator CLI -Run `python -m src.admin --help` on the server (or `docker compose … exec api python -m src.admin`). +Run `docker compose -f deploy/docker-compose.yml exec api python -m src.admin --help`. +Prefix the subcommands below with `docker compose -f deploy/docker-compose.yml 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. @@ -157,8 +212,8 @@ The operator trusts every registered app; there is no consent screen. 1. Register a confidential client and its exact callback URL: ```sh - python -m src.admin app add myapp --name "My App" --redirect-uri https://app.example.com/callback - python -m src.admin app allow myapp alice + docker compose -f deploy/docker-compose.yml exec api python -m src.admin app add myapp --name "My App" --redirect-uri https://app.example.com/callback + docker compose -f deploy/docker-compose.yml exec api python -m src.admin app allow myapp alice ``` Save the printed client secret: it is shown once and only its SHA-256 hash is stored. @@ -226,3 +281,13 @@ The existing `/register`, `/auth/*`, `/internal/*` and JavaScript client retain 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. + +### Running the Authlib example behind a proxy + +Set `APP_ORIGIN` to the app's external origin (`scheme://host[:port]`, no path or +trailing slash), for example `https://app.example.com`. Logout compares the browser +Origin against this value; when unset it uses the origin part of `request.base_url`. +Behind a trusted reverse proxy, start uvicorn with `--proxy-headers +--forwarded-allow-ips ` so callback URLs use the external +scheme. Configure the proxy to preserve the external Host and set forwarded headers. +Never trust forwarded headers from arbitrary public callers. diff --git a/examples/oidc_fastapi/app.py b/examples/oidc_fastapi/app.py index 3194eb4..456674f 100644 --- a/examples/oidc_fastapi/app.py +++ b/examples/oidc_fastapi/app.py @@ -1,5 +1,6 @@ """Run: uvicorn app:app --host 127.0.0.1 --port 9000 (behind HTTPS in production).""" import os +from urllib.parse import urlsplit from authlib.integrations.starlette_client import OAuth from fastapi import FastAPI, Request @@ -40,7 +41,9 @@ async def callback(request: Request): @app.post('/logout') async def logout(request: Request): - if request.headers.get('origin') != str(request.base_url).rstrip('/'): + base = urlsplit(str(request.base_url)) + origin = os.getenv('APP_ORIGIN', f'{base.scheme}://{base.netloc}') + if request.headers.get('origin') != origin: return HTMLResponse('Invalid Origin', 403) request.session.clear() return RedirectResponse('/', 303) diff --git a/src/__init__.py b/src/__init__.py index 9a32325..1841333 100644 --- a/src/__init__.py +++ b/src/__init__.py @@ -1,2 +1,2 @@ """TeleLogin - Telegram-based authentication system""" -__version__ = "1.0.0" +__version__ = "2.0.0" diff --git a/src/app.py b/src/app.py index f38f269..a343bf6 100644 --- a/src/app.py +++ b/src/app.py @@ -13,6 +13,7 @@ from fastapi import FastAPI from fastapi.middleware.cors import CORSMiddleware +from src import __version__ from src.config import settings from src.database.sqlite import SQLiteDatabase from src.web.routes import router @@ -55,7 +56,7 @@ async def purge(): app = FastAPI( title="TeleLogin", description="Telegram-based authentication system", - version="1.0.0", + version=__version__, lifespan=lifespan ) @@ -84,7 +85,7 @@ async def __call__(self, scope, receive, send): @app.get("/health") async def health(db=Depends(get_db)): await db.ping() - return {"status": "ok"} + return {"status": "ok", "version": __version__} if __name__ == "__main__": diff --git a/src/config.py b/src/config.py index 54c21d9..22a689a 100644 --- a/src/config.py +++ b/src/config.py @@ -2,7 +2,7 @@ Configuration management Loads environment variables and application settings """ -from pydantic import Field, model_validator +from pydantic import Field, field_validator, model_validator from urllib.parse import urlsplit, urlunsplit import ipaddress import tldextract @@ -42,6 +42,16 @@ class Settings(BaseSettings): SSO_COOKIE_DOMAIN: str = "" REGISTRATION_MODE: str = "open" + @field_validator("SECRET_KEY", "INTERNAL_API_KEY") + @classmethod + def reject_placeholder_secrets(cls, value): + if value in { + "your_secret_key_here_minimum_32_characters_long", + "replace_with_shared_random_secret_at_least_32_characters", + }: + raise ValueError("Template placeholder is not a secret; run gen-secrets (python -m src.admin gen-secrets)") + return value + @model_validator(mode="after") def validate_sso(self): url = urlsplit(self.PUBLIC_URL) diff --git a/src/web/oidc.py b/src/web/oidc.py index 65a32ae..66940aa 100644 --- a/src/web/oidc.py +++ b/src/web/oidc.py @@ -43,10 +43,19 @@ def load_key(filename): try: with os.fdopen(fd, 'wb') as stream: stream.write(key.private_bytes(serialization.Encoding.PEM, serialization.PrivateFormat.PKCS8, serialization.NoEncryption())) + stream.flush() + os.fsync(stream.fileno()) try: os.link(temporary, path) except FileExistsError: pass + except OSError as exc: + raise OSError(f"Cannot publish OIDC key at {path}: key directory must support hard links, or pre-create the key file") from exc + directory_fd = os.open(path.parent, os.O_RDONLY | os.O_DIRECTORY) + try: + os.fsync(directory_fd) + finally: + os.close(directory_fd) finally: os.unlink(temporary) if path.stat().st_mode & 0o077: diff --git a/tests/test_oidc.py b/tests/test_oidc.py index ac4d8d9..3d6fc31 100644 --- a/tests/test_oidc.py +++ b/tests/test_oidc.py @@ -6,6 +6,7 @@ from pathlib import Path import sqlite3 import time +from threading import Barrier from unittest.mock import AsyncMock from urllib.parse import parse_qs, urlsplit @@ -186,11 +187,22 @@ async def test_token_isolation_and_revocation(oidc, db): assert conn.execute(f'SELECT count(*) FROM {table}').fetchone()[0] == 0 -def test_keys_concurrent_and_reused(tmp_path): +def test_keys_concurrent_and_reused(tmp_path, monkeypatch): + from src.web import oidc + barrier = Barrier(2) + original_generate = oidc.rsa.generate_private_key + + def generate(*args, **kwargs): + barrier.wait(timeout=10) + return original_generate(*args, **kwargs) + + monkeypatch.setattr(oidc.rsa, 'generate_private_key', generate) filename = tmp_path / 'key.pem' with ThreadPoolExecutor(2) as pool: keys = list(pool.map(load_key, [filename, filename])) - assert keys[0][1] == keys[1][1] == load_key(filename)[1] + on_disk = load_key(filename) + assert keys[0][1] == keys[1][1] == on_disk[1] + assert all(key[0].private_numbers() == on_disk[0].private_numbers() for key in keys) assert filename.stat().st_mode & 0o777 == 0o600 jwk = keys[0][1] from src.web.oidc import b64 @@ -199,6 +211,37 @@ def test_keys_concurrent_and_reused(tmp_path): assert list(tmp_path.iterdir()) == [filename] +def test_key_publication_failure_and_durability(tmp_path, monkeypatch): + from src.web import oidc + filename = tmp_path / 'key.pem' + events = [] + original_fsync = oidc.os.fsync + original_link = oidc.os.link + + def fsync(fd): + events.append('fsync') + return original_fsync(fd) + + def link(source, target): + events.append('link') + return original_link(source, target) + + monkeypatch.setattr(oidc.os, 'fsync', fsync) + monkeypatch.setattr(oidc.os, 'link', link) + load_key(filename) + assert events == ['fsync', 'link', 'fsync'] + filename.unlink() + + def unsupported_link(source, target): + raise OSError('unsupported filesystem') + + monkeypatch.setattr(oidc.os, 'link', unsupported_link) + with pytest.raises(OSError, match='must support hard links, or pre-create') as error: + load_key(filename) + assert str(error.value.__cause__) == 'unsupported filesystem' + assert list(tmp_path.iterdir()) == [] + + async def test_part_a_schema_migration(tmp_path): from src.database.sqlite import SQLiteDatabase database = SQLiteDatabase(str(tmp_path / 'part-a.db')) @@ -391,3 +434,27 @@ async def test_basic_body_client_id_interop(oidc, body_auth): assert response.status_code == 401 assert response.json()['error'] == 'invalid_client' assert response.headers['www-authenticate'] == 'Basic' + + +@pytest.mark.parametrize('configured', [False, True]) +async def test_example_logout_origin_with_prefix(monkeypatch, configured): + from starlette.requests import Request + monkeypatch.setenv('OIDC_CLIENT_ID', 'demo') + monkeypatch.setenv('OIDC_CLIENT_SECRET', SECRET) + monkeypatch.setenv('SESSION_SECRET', 's'*32) + if configured: + monkeypatch.setenv('APP_ORIGIN', 'https://external.example.com') + else: + monkeypatch.delenv('APP_ORIGIN', raising=False) + spec = importlib.util.spec_from_file_location('oidc_example', 'examples/oidc_fastapi/app.py') + example = importlib.util.module_from_spec(spec) + spec.loader.exec_module(example) + expected = 'https://external.example.com' if configured else 'https://app.example.com' + for origin, status in [(expected, 303), ('https://evil.example.com', 403)]: + session = {'user': {'sub': 'test'}} + request = Request({'type': 'http', 'scheme': 'https', 'server': ('app.example.com', 443), + 'path': '/prefix/logout', 'root_path': '/prefix', 'query_string': b'', + 'headers': [(b'host', b'app.example.com'), (b'origin', origin.encode())], + 'session': session}) + assert (await example.logout(request)).status_code == status + assert bool(session) == (status == 403) diff --git a/tests/test_phase2.py b/tests/test_phase2.py index 12079f4..ca5960b 100644 --- a/tests/test_phase2.py +++ b/tests/test_phase2.py @@ -5,6 +5,7 @@ import httpx import pytest +from src import __version__ from src.app import app from src.config import Settings, settings from src.services.auth_service import AuthService @@ -38,7 +39,7 @@ async def test_lifespan_health_login(tmp_path, monkeypatch): async with app.router.lifespan_context(app): assert isinstance(app.state.limiter, RateLimiter) async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url='http://test') as client: - assert (await client.get('/health')).json() == {'status': 'ok'} + assert (await client.get('/health')).json() == {'status': 'ok', 'version': __version__} response = await client.get('/login') assert response.status_code == 200 and 'text/html' in response.headers['content-type'] assert "request('sso/complete'" in response.text and 'setInterval' not in response.text @@ -49,11 +50,21 @@ async def test_lifespan_health_login(tmp_path, monkeypatch): app.state._state.update(previous_state) -@pytest.mark.parametrize('template', ['.env.example', 'docker/env.example']) +@pytest.mark.parametrize('template', ['.env.example', 'docker/env.example', 'deploy/.env.example']) def test_settings_templates(template, monkeypatch): for name in ('BOT_TOKEN', 'SECRET_KEY', 'INTERNAL_API_KEY'): monkeypatch.delenv(name, raising=False) - config = Settings(_env_file=Path(__file__).parents[1] / template) + from dotenv import dotenv_values + values = dict(dotenv_values(Path(__file__).parents[1] / template)) + # Compose consumes this setting; it is not passed to the application container. + values.pop('TELELOGIN_VERSION', None) + for name, value in values.items(): + monkeypatch.setenv(name, value) + with pytest.raises(ValueError, match='SECRET_KEY|INTERNAL_API_KEY'): + Settings(_env_file=None) + for name, value in dict(BOT_TOKEN='123:test', SECRET_KEY='s'*32, INTERNAL_API_KEY='i'*32).items(): + monkeypatch.setenv(name, value) + config = Settings(_env_file=None) assert config.API_PORT == 8000 assert len(config.SECRET_KEY) >= 32 and len(config.INTERNAL_API_KEY) >= 32 diff --git a/tests/test_security.py b/tests/test_security.py index 35e9100..be8167c 100644 --- a/tests/test_security.py +++ b/tests/test_security.py @@ -277,3 +277,13 @@ def test_telegram_library_debug_logging_disabled(monkeypatch): importlib.reload(src.bot) assert logging.getLogger("telegram").getEffectiveLevel() >= logging.INFO assert not logging.getLogger("telegram.ext.Application").isEnabledFor(logging.DEBUG) + + +@pytest.mark.parametrize('key', ['SECRET_KEY', 'INTERNAL_API_KEY']) +@pytest.mark.parametrize('placeholder', [ + 'your_secret_key_here_minimum_32_characters_long', + 'replace_with_shared_random_secret_at_least_32_characters', +]) +def test_settings_reject_template_secrets(key, placeholder): + with pytest.raises(ValueError, match='run gen-secrets'): + Settings(_env_file=None, **{key: placeholder})