Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -41,3 +41,8 @@ SSO_COOKIE_SECURE=true
# Optional shared parent domain; every subdomain must be trusted
SSO_COOKIE_DOMAIN=
REGISTRATION_MODE=open

# Keep the private signing key persistent and readable only by the API user.
OIDC_KEY_FILE=data/oidc-signing-key.pem
OIDC_CODE_TTL_SECONDS=60
OIDC_TOKEN_TTL_SECONDS=600
5 changes: 5 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -222,3 +222,8 @@ __marimo__/

# Disposable real-proxy test configuration and cookie jars
tests/e2e/.run-*/

# Runtime data and private keys; retain disposable e2e certificate fixtures.
/data/
*.pem
!tests/e2e/certs/*.pem
17 changes: 16 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ TeleLogin also protects apps with **forward auth**: one Telegram confirmation cr
browser session, and nginx, Traefik or Caddy supplies the app's verified identity. Per-app allowlists
(default) or `all` policies control access. See [Integration guide](docs/INTEGRATION.md) for both
shared-host/path-prefix and sibling-subdomain deployments, proxy snippets and the operator CLI.
OpenID Connect is coming in a later release.
OpenID Connect supports confidential clients with authorization code flow and PKCE S256.

**Deployment change:** the development Compose API port now binds to `127.0.0.1` only. Configure a
local reverse proxy, or use a private Docker network with no published API port. `GET /` now serves
Expand Down Expand Up @@ -34,6 +34,7 @@ Telegram login confirmation using FastAPI, a Telegram bot and SQLite. Python 3.1

## Features

- OpenID Connect discovery, RS256 ID tokens, opaque access tokens, and shared browser SSO.
- Telegram deep-link registration, number matching and Deny login buttons.
- SQLite persistence with atomic registration linking and login transitions.
- Expiring registration tokens and login requests, with one-time access/refresh token delivery.
Expand Down Expand Up @@ -128,6 +129,9 @@ Both templates declare all supported variables. Required secrets must be supplie
| REFRESH_TOKEN_TTL_DAYS | 30; fixed session lifetime from creation |
| LOGIN_HISTORY_RETENTION_DAYS | 30; login history and session metadata retention |
| PURGE_INTERVAL_SECONDS | 3600; cleanup interval, also run at startup |
| OIDC_KEY_FILE | data/oidc-signing-key.pem; persistent private RSA signing key |
| OIDC_CODE_TTL_SECONDS | 60; authorization code lifetime |
| OIDC_TOKEN_TTL_SECONDS | 600; access token and ID token lifetime |
| DEBUG | false |
| CORS_ORIGINS | [] (JSON list) |
| LOGIN_REQUEST_TTL_SECONDS | 120 |
Expand Down Expand Up @@ -173,6 +177,11 @@ Both templates declare all supported variables. Required secrets must be supplie
| GET /login | Hosted browser login; optional app and rd parameters |
| GET /health | 200 {"status":"ok"} after a database query |
| POST /register | {"username":"alice"}; returns Telegram registration link; duplicate username 400 |
| GET /.well-known/openid-configuration | OIDC discovery |
| GET /jwks.json | Public RSA signing key |
| GET /authorize | Authorization code flow |
| POST /token | Form-encoded code redemption with client authentication |
| GET, POST /userinfo | Opaque Bearer token identity |
| POST /auth/link-telegram | Internal: {"token":"...","telegram_id":42}; atomic single-use registration link |
| POST /auth/start-login | {"username":"alice"}; always returns pending login_id and verification_code unless rate limited |
| POST /auth/confirm-login | Internal: {"login_id":"...","telegram_id":42,"verification_code":42}; owner approves pending unexpired login; returns only {"status":"authenticated"}, wrong code denies with 400 |
Expand Down Expand Up @@ -348,3 +357,9 @@ otherwise that simulation is skipped.

TeleLogin is distributed under the Apache License, Version 2.0. See [LICENSE](LICENSE)
for the full terms.

## OpenID Connect integration

TeleLogin supports confidential OIDC clients with authorization code flow, PKCE S256, RS256 ID
tokens, and shared browser SSO. See [the integration guide](docs/INTEGRATION.md#mode-1-openid-connect)
and [the Authlib example](examples/oidc_fastapi/app.py).
3 changes: 3 additions & 0 deletions docker/docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,9 @@ services:
- SSO_COOKIE_NAME=${SSO_COOKIE_NAME:-tl_sso}
- SSO_COOKIE_SECURE=${SSO_COOKIE_SECURE:-true}
- SSO_COOKIE_DOMAIN=${SSO_COOKIE_DOMAIN:-}
- OIDC_KEY_FILE=${OIDC_KEY_FILE:-data/oidc-signing-key.pem}
- OIDC_CODE_TTL_SECONDS=${OIDC_CODE_TTL_SECONDS:-60}
- OIDC_TOKEN_TTL_SECONDS=${OIDC_TOKEN_TTL_SECONDS:-600}
- REGISTRATION_MODE=${REGISTRATION_MODE:-open}
- DEBUG=${DEBUG:-false}
- CORS_ORIGINS=${CORS_ORIGINS:-[]}
Expand Down
5 changes: 5 additions & 0 deletions docker/env.example
Original file line number Diff line number Diff line change
Expand Up @@ -44,3 +44,8 @@ SSO_COOKIE_SECURE=true
# Optional shared parent domain; every subdomain must be trusted
SSO_COOKIE_DOMAIN=
REGISTRATION_MODE=open

# Keep the private signing key persistent and readable only by the API user.
OIDC_KEY_FILE=data/oidc-signing-key.pem
OIDC_CODE_TTL_SECONDS=60
OIDC_TOKEN_TTL_SECONDS=600
73 changes: 71 additions & 2 deletions docs/INTEGRATION.md
Original file line number Diff line number Diff line change
Expand Up @@ -135,11 +135,13 @@ Shell access is admin access. `gen-secrets` needs no `.env` or database and prin
`SECRET_KEY` and `INTERNAL_API_KEY` assignments. Never share them.

```text
app add ID --name NAME [--policy allowlist|all]
app add ID --name NAME [--policy allowlist|all] [--redirect-uri URI ...]
app list | app show ID | app remove ID
app policy ID allowlist|all
app allow ID USERNAME | app disallow ID USERNAME
app origin add|remove ID ORIGIN
app redirect-uri add|remove ID URI
app rotate-secret ID
user invite USERNAME | user list | user remove USERNAME
gen-secrets
```
Expand All @@ -149,7 +151,74 @@ as unlink. `app remove` also removes its allowlist. No stored secret is printed.

## Mode 1: OpenID Connect

Coming in a later release. This build has no OIDC endpoints or client credentials.
Use Mode 1 for apps on unrelated domains or apps with a standard OIDC client library.
The operator trusts every registered app; there is no consent screen.

1. Register a confidential client and its exact callback URL:

```sh
python -m src.admin app add myapp --name "My App" --redirect-uri https://app.example.com/callback
python -m src.admin app allow myapp alice
```

Save the printed client secret: it is shown once and only its SHA-256 hash is stored.
Repeat `--redirect-uri` for additional callback URLs. Alternatively use
`app redirect-uri add myapp URI`; adding the first URI generates a secret if needed.
`app rotate-secret myapp` replaces the secret immediately; update the app configuration.
Redirect URIs must use HTTPS, except HTTP on localhost/127.0.0.1 for development; fragments
and credentials are forbidden. Matching is exact, including path and query.
To admit every linked user instead, run `app policy myapp all`.
2. Configure your OIDC library:

| Setting | Value |
|---|---|
| Issuer | Your `PUBLIC_URL`, e.g. `https://auth.example.com` |
| Discovery URL | `PUBLIC_URL/.well-known/openid-configuration` |
| Client ID | `myapp` |
| Client secret | The value printed by the CLI |
| Scopes | `openid profile` |
| Redirect URI | The exact registered callback URL |
| Flow | Authorization code; PKCE S256 recommended |
| Client authentication | `client_secret_basic` or `client_secret_post` |

With a path prefix, issuer is e.g. `https://example.com/telelogin` and discovery is
`https://example.com/telelogin/.well-known/openid-configuration`. Keep that prefix in all URLs.
3. Use the [Authlib FastAPI example](../examples/oidc_fastapi/app.py): install its
`requirements.txt`, set `OIDC_ISSUER`, `OIDC_CLIENT_ID`, `OIDC_CLIENT_SECRET`, and a random
`SESSION_SECRET`, then run `uvicorn app:app --host 127.0.0.1 --port 9000` from that directory.
Register the public `/callback` URL first. Put it behind an HTTPS proxy; for plain HTTP
local development only, set `COOKIE_SECURE=false`. The example stores identity in a signed
session cookie and its logout clears that app session. It does not store bearer tokens in
the cookie. A typical Authlib registration is:

```python
oauth.register(
"telelogin", client_id=client_id, client_secret=client_secret,
server_metadata_url=issuer + "/.well-known/openid-configuration",
client_kwargs={"scope": "openid profile", "code_challenge_method": "S256"},
)
```

The stable UUID `sub` identifies the user. `profile` adds `preferred_username` and `name`.
ID tokens are signed with RS256 and a public key from `/jwks.json`; access tokens are opaque,
last 10 minutes by default, and work only at `/userinfo`. Raw API HS256 tokens and OIDC tokens
are mutually unusable. Codes are single use; replay revokes the access tokens issued from that
code. Removing app access also prevents `/userinfo` and code redemption.

Only confidential clients with a backend and a secret are supported. Browser-only SPAs should
use Mode 2 or a small backend. There are no OIDC refresh tokens, dynamic registration, consent
screens, RP-initiated logout, or back-channel logout. `max_age`, `claims`, and `ui_locales` are
unsupported and ignored. `prompt=none` fails with `login_required` without a browser session;
`prompt=login` forces a new Telegram confirmation. Otherwise the browser session is reused.
Revoking a TeleLogin browser session blocks new codes and unredeemed codes. It does not end
sessions that an OIDC app has created itself; already issued OIDC access tokens last until expiry
unless replayed or app access is removed. Unlink and user/app removal delete associated grants.

The API generates `OIDC_KEY_FILE` on first startup with mode 0600. Persist this file alongside
SQLite data and keep it private. For manual key rotation: stop the API, back up the old key
securely, remove the key file, and restart to generate a new one. Existing ID tokens stop
validating after clients refresh their JWKS cache; coordinate app reauthentication and cache
refresh with the rotation. Automated rotation and overlapping signing keys are unsupported.

## Advanced: custom UI with the raw API

Expand Down
46 changes: 46 additions & 0 deletions examples/oidc_fastapi/app.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
"""Run: uvicorn app:app --host 127.0.0.1 --port 9000 (behind HTTPS in production)."""
import os

from authlib.integrations.starlette_client import OAuth
from fastapi import FastAPI, Request
from fastapi.responses import HTMLResponse, RedirectResponse
from starlette.middleware.sessions import SessionMiddleware
import html

app = FastAPI()
app.add_middleware(SessionMiddleware, secret_key=os.environ['SESSION_SECRET'],
https_only=os.getenv('COOKIE_SECURE', 'true') == 'true')
oauth = OAuth()
oauth.register('telelogin', client_id=os.environ['OIDC_CLIENT_ID'],
client_secret=os.environ['OIDC_CLIENT_SECRET'],
server_metadata_url=os.getenv('OIDC_ISSUER', 'https://auth.example.com') + '/.well-known/openid-configuration',
client_kwargs={'scope': 'openid profile', 'code_challenge_method': 'S256'})


@app.get('/')
async def home(request: Request):
user = request.session.get('user')
if not user:
return HTMLResponse('<a href="/login">Sign in</a>')
return HTMLResponse('Signed in as ' + html.escape(user.get('preferred_username', user['sub'])) +
'<form method="post" action="/logout"><button>Log out</button></form>')


@app.get('/login')
async def login(request: Request):
return await oauth.telelogin.authorize_redirect(request, str(request.url_for('callback')))


@app.get('/callback')
async def callback(request: Request):
token = await oauth.telelogin.authorize_access_token(request)
request.session['user'] = dict(token['userinfo'])
return RedirectResponse('/', 303)


@app.post('/logout')
async def logout(request: Request):
if request.headers.get('origin') != str(request.base_url).rstrip('/'):
return HTMLResponse('Invalid Origin', 403)
request.session.clear()
return RedirectResponse('/', 303)
6 changes: 6 additions & 0 deletions examples/oidc_fastapi/requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
fastapi==0.159.1
uvicorn[standard]==0.54.0
authlib==1.8.0
httpx2==2.13.1
cryptography==50.0.2
itsdangerous==2.2.0
3 changes: 3 additions & 0 deletions requirements-dev.txt
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,6 @@
pytest==9.1.1
pytest-asyncio==1.4.0
ruff==0.17.1
authlib==1.8.0
httpx2==2.13.1
itsdangerous==2.2.0
1 change: 1 addition & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -9,3 +9,4 @@ aiosqlite==0.22.1
PyJWT==2.15.1

tldextract==5.4.0
cryptography==50.0.2
43 changes: 39 additions & 4 deletions src/admin.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
"""Operator CLI. Shell access is administrative access."""
import hashlib
import argparse
import asyncio
import json
Expand All @@ -18,6 +19,13 @@ def parser():
add.add_argument('id')
add.add_argument('--name', required=True)
add.add_argument('--policy', choices=['allowlist', 'all'], default='allowlist')
add.add_argument('--redirect-uri', action='append', default=[])
apps.add_parser('rotate-secret').add_argument('id')
redirects = apps.add_parser('redirect-uri').add_subparsers(dest='operation', required=True)
for action in ('add', 'remove'):
a = redirects.add_parser(action)
a.add_argument('id')
a.add_argument('uri')
apps.add_parser('list')
for action in ('show', 'remove'):
apps.add_parser(action).add_argument('id')
Expand Down Expand Up @@ -55,6 +63,17 @@ def validated_origin(value):
return normalized


def validated_redirect(value):
parsed = urlsplit(value)
if (not parsed.hostname or parsed.username or parsed.password or parsed.fragment
or "#" in value or "\\" in value or any(ord(c) <= 32 or ord(c) == 127 for c in value)
or parsed.scheme not in ('https', 'http')
or (parsed.scheme == 'http' and parsed.hostname not in ('localhost', '127.0.0.1'))):
raise ValueError('Redirect URI must be absolute HTTPS (HTTP only on localhost/127.0.0.1), without fragment or credentials')
parsed.port
return value


async def run(args):
import aiosqlite
from src.database.sqlite import SQLiteDatabase
Expand Down Expand Up @@ -83,12 +102,13 @@ async def run(args):
user = await (await conn.execute('SELECT id FROM users WHERE username=?', (args.username,))).fetchone()
if not user:
raise ValueError('Unknown username')
for table in ('app_users', 'sessions', 'registration_tokens', 'login_requests'):
for table in ('oidc_tokens', 'oidc_codes', 'app_users', 'sessions', 'registration_tokens', 'login_requests'):
await conn.execute(f'DELETE FROM {table} WHERE user_id=?', (user['id'],))
await conn.execute('DELETE FROM users WHERE id=?', (user['id'],))
await conn.commit()
print('User removed')
return
secret = None
async with aiosqlite.connect(db.db_path) as conn:
conn.row_factory = aiosqlite.Row
await conn.execute('BEGIN IMMEDIATE')
Expand All @@ -99,7 +119,9 @@ async def run(args):
if args.action == 'add':
if not re.fullmatch(r'[a-z0-9][a-z0-9-]{0,39}', args.id):
raise ValueError('App id must match ^[a-z0-9][a-z0-9-]{0,39}$')
await conn.execute('INSERT INTO apps(id,name,access_policy,created_at) VALUES (?,?,?,?)', (args.id, args.name, args.policy, time.time()))
uris = [validated_redirect(uri) for uri in args.redirect_uri]
secret = secrets.token_urlsafe(32) if uris else None
await conn.execute('INSERT INTO apps(id,name,access_policy,created_at,redirect_uris,secret_hash) VALUES (?,?,?,?,?,?)', (args.id, args.name, args.policy, time.time(), json.dumps(uris), hashlib.sha256(secret.encode()).hexdigest() if secret else None))
else:
app = await (await conn.execute('SELECT * FROM apps WHERE id=?', (args.id,))).fetchone()
if not app:
Expand All @@ -111,8 +133,21 @@ async def run(args):
print(json.dumps(data, ensure_ascii=False))
return
if args.action == 'remove':
await conn.execute('DELETE FROM app_users WHERE app_id=?', (args.id,))
for table in ('oidc_tokens', 'oidc_codes', 'app_users'):
await conn.execute(f'DELETE FROM {table} WHERE app_id=?', (args.id,))
await conn.execute('DELETE FROM apps WHERE id=?', (args.id,))
elif args.action in ('rotate-secret', 'redirect-uri'):
if args.action == 'redirect-uri':
value = validated_redirect(args.uri)
uris = json.loads(app['redirect_uris'])
if args.operation == 'add' and value not in uris:
uris.append(value)
if args.operation == 'remove' and value in uris:
uris.remove(value)
await conn.execute('UPDATE apps SET redirect_uris=? WHERE id=?', (json.dumps(uris), args.id))
if args.action == 'rotate-secret' or (args.operation == 'add' and not app['secret_hash']):
secret = secrets.token_urlsafe(32)
await conn.execute('UPDATE apps SET secret_hash=? WHERE id=?', (hashlib.sha256(secret.encode()).hexdigest(), args.id))
elif args.action == 'policy':
await conn.execute('UPDATE apps SET access_policy=? WHERE id=?', (args.policy, args.id))
elif args.action in ('allow', 'disallow'):
Expand All @@ -135,7 +170,7 @@ async def run(args):
origins.remove(value)
await conn.execute('UPDATE apps SET origins=? WHERE id=?', (json.dumps(origins), args.id))
await conn.commit()
print('OK')
print('Client secret: ' + secret if secret else 'OK')


def main():
Expand Down
3 changes: 3 additions & 0 deletions src/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
from src.config import settings
from src.database.sqlite import SQLiteDatabase
from src.web.routes import router
from src.web.oidc import router as oidc_router, load_key
from src.web.sso import router as sso_router


Expand All @@ -28,6 +29,7 @@ async def lifespan(app: FastAPI):
# Startup: Initialize database tables
app.state.db = SQLiteDatabase()
await app.state.db.init_db()
app.state.oidc_key = load_key(settings.OIDC_KEY_FILE)
app.state.limiter = RateLimiter()
app.state.login_html = Path(__file__).with_name("web").joinpath("templates/index.html").read_text(encoding="utf-8")
async def purge_once():
Expand Down Expand Up @@ -77,6 +79,7 @@ async def __call__(self, scope, receive, send):
# Include routes
app.include_router(router)
app.include_router(sso_router)
app.include_router(oidc_router)

@app.get("/health")
async def health(db=Depends(get_db)):
Expand Down
4 changes: 4 additions & 0 deletions src/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,10 @@ class Settings(BaseSettings):
LOGIN_HISTORY_RETENTION_DAYS: int = Field(default=30, gt=0)
PURGE_INTERVAL_SECONDS: float = Field(default=3600, gt=0)

OIDC_KEY_FILE: str = "data/oidc-signing-key.pem"
OIDC_CODE_TTL_SECONDS: int = Field(default=60, gt=0)
OIDC_TOKEN_TTL_SECONDS: int = Field(default=600, gt=0)

PUBLIC_URL: str = "http://localhost:8000"
SSO_COOKIE_NAME: str = "tl_sso"
SSO_COOKIE_SECURE: bool = True
Expand Down
Loading
Loading