[S-08] Вход по 2FA без пароля (TOTP первым) + Prometheus через SSO на публичном домене

This commit is contained in:
buryan-agent committed 2026-10-21 15:21:13 +03:00
1 parent 4a11f8fa2a
commit 397121cada
5 files changed
+238 -1

No files matched your search

+3 -1
View File
@@ -41,6 +41,8 @@
| S-02 | SSO: Gitea | ✅ | вход через Authentik работает: кнопка на /user/login, провайдер gitea, редирект 302 |
| S-03 | SSO: Prometheus | ✅ | oauth2-proxy :9113 → Authentik; публичный домен не нужен (ADR-008) |
| S-04 | Mosquitto — исключение | ✅ | `ops/adr/ADR-006-mosquitto-no-sso.md` |
| S-08 | Вход по 2FA без пароля | ✅ | ADR-010: TOTP первым, пароль пропускается при наличии TOTP |
| S-09 | Prometheus: публичный домен | ✅ | VPS: сертификат + vhost → oauth2-proxy (302 на Authentik) |
| S-05 | Мониторинг сервисов | ✅ | Kuma: 60 активных; добавлены Portainer, Seerr, Paperless, Immich |
| S-06 | Ссылка на статус в карточках | ✅ | `ops/services/cards/` |
| S-07 | Закрыть сервисы без бэкапа | ✅ | 46 конфигураций в `/mnt/backups/configs` |
@@ -51,7 +53,7 @@
|---|---|---|---|
| X-01 | Тонкий пул и бэкапы | ✅ | причина: /mnt/backups не был зарегистрирован как storage; fstrim 83.9→78%; тестовый бэкап CT109 успешен |
| X-02 | Родители `.63` | ⛔ | ждёт питания |
| X-03 | Frigate без камер | ⛔ | RTSP 554 в сети нет (проверено 21.10) — нет самих камер |
| X-03 | Frigate без камер | ⛔ | вынесено из спринта: нет камер, отдельная задача |
| X-04 | Проверка восстановления | ✅ | `ops/drill/drill.py`, 1-е число 04:30 |
| X-05 | Расписание бэкапов в Proxmox | ✅ | высокий |
+42
View File
@@ -0,0 +1,42 @@
# ADR-010. Вход по 2FA без пароля
**Дата:** 21.10.2026 · **Статус:** принято
## Задача
Владелец ожидал, что двухфакторный код будет **основным входом**,
а не вторым шагом после пароля.
## Решение
Порядок шагов в `default-authentication-flow`:
| Порядок | Stage | Условие |
|---|---|---|
| 10 | Identification | всегда |
| 20 | MFA validation (TOTP) | если у пользователя есть TOTP |
| 30 | Password | **пропускается**, если TOTP есть |
| 100 | User login | всегда |
Политика `has-totp-device` (expression, negate=true) висит на шаге пароля:
есть TOTP → пароль не спрашиваем; нет TOTP → спрашиваем как раньше.
`not_configured_action=skip` у MFA-стадии: у кого TOTP нет — сразу к паролю.
## Что получилось
- С TOTP: **только код** (без пароля).
- Без TOTP: пароль, как раньше (никого не заблокировали).
## Риск и откат
- Потеря TOTP-устройства = потеря входа. Резерв: recovery-коды Authentik
и доступ к админке по API-токену.
- Откат: удалить policy binding на шаге пароля, вернуть порядок
identification → password → mfa → login.
## Проверка
Структура потока проверена через API (`/flows/executor/` отдаёт
`ak-stage-identification`, порядок bindings подтверждён).
**Реальный вход нужно проверить в браузере** — пароль владельца мне неизвестен.
+106
View File
@@ -0,0 +1,106 @@
#!/usr/bin/env python3
"""Делает вход passwordless: TOTP первым, пароль — только если TOTP нет.
1. Политика «у пользователя есть TOTP».
2. MFA-validate: not_configured_action = skip.
3. Порядок: identification(10) → mfa(20) → password(30) с политикой skip.
4. login(100).
"""
import json
import urllib.error
import urllib.request
API = "http://192.168.1.114:9000/api/v3"
T = open("/root/.authentik-api-token").read().strip()
FLOW_NAME = "passwordless-2fa"
def call(method, path, body=None):
data = json.dumps(body).encode() if body is not None else None
req = urllib.request.Request(API + path, data=data, method=method,
headers={"Authorization": "Bearer " + T,
"Content-Type": "application/json"})
try:
with urllib.request.urlopen(req, timeout=30) as r:
raw = r.read()
return r.status, (json.loads(raw) if raw else {})
except urllib.error.HTTPError as e:
return e.code, e.read()[:400].decode("utf-8", "replace")
def get_or_create_policy():
st, d = call("GET", "/policies/expression/?page_size=100")
for p in (d.get("results", []) if st == 200 else []):
if p["name"] == "has-totp-device":
print("политика уже есть:", p["pk"])
return p["pk"]
expr = (
"try:\n"
" return request.user.device_set.filter(type='totp').exists()\n"
"except Exception:\n"
" return False\n"
)
st, p = call("POST", "/policies/expression/", {
"name": "has-totp-device",
"expression": expr,
"execution_logging": True,
})
if st not in (200, 201):
print("политика: ошибка", st, p)
return None
print("политика создана:", p["pk"])
return p["pk"]
def main():
flows = call("GET", "/flows/instances/?page_size=100")[1]["results"]
flow = next((f for f in flows if f["slug"] == "default-authentication-flow"), None)
if not flow:
print("flow не найден")
return
fpk = flow["pk"]
stages = {s["name"]: s["pk"] for s in
call("GET", "/stages/all/?page_size=100")[1]["results"]}
mfa_pk = stages["default-authentication-mfa-validation"]
pwd_pk = stages["default-authentication-password"]
login_pk = stages["default-authentication-login"]
ident_pk = stages["default-authentication-identification"]
pol = get_or_create_policy()
# MFA: если у пользователя нет устройства — пропустить
st, mfa = call("GET", f"/stages/authenticator/validate/{mfa_pk}/")
if st == 200:
call("PATCH", f"/stages/authenticator/validate/{mfa_pk}/",
{"not_configured_action": "skip"})
print("mfa: not_configured_action=skip")
# пересобираем bindings
st, bindings = call("GET", f"/flows/bindings/?target={fpk}&page_size=100")
for b in bindings.get("results", []):
call("DELETE", f"/flows/bindings/{b['pk']}/")
print("старые bindings удалены:", len(bindings.get("results", [])))
def bind(order, stage, policy=None):
body = {"target": fpk, "stage": stage, "order": order,
"evaluate_on_plan": False, "re_evaluate": True}
if policy:
body["policy"] = policy
st, r = call("POST", "/flows/bindings/", body)
print(f" bind {order} {stage[:8]}: {st}")
bind(10, ident_pk)
bind(20, mfa_pk)
bind(30, pwd_pk, pol)
bind(100, login_pk)
st, final = call("GET", f"/flows/bindings/?target={fpk}&page_size=100&ordering=order")
print()
print("итоговый порядок:")
for b in final.get("results", []):
print(f" {b['order']:>3} {b.get('stage_obj',{}).get('name')} "
f"policy={b.get('policy_obj')}")
if __name__ == "__main__":
main()
+53
View File
@@ -0,0 +1,53 @@
#!/usr/bin/env python3
"""Привязывает политику через /policies/bindings/ с negate=true."""
import json
import urllib.error
import urllib.request
API = "http://192.168.1.114:9000/api/v3"
T = open("/root/.authentik-api-token").read().strip()
POLICY = "641a4b7d-56e6-420f-a7c8-d609a1f251cf"
def call(method, path, body=None):
data = json.dumps(body).encode() if body is not None else None
req = urllib.request.Request(API + path, data=data, method=method,
headers={"Authorization": "Bearer " + T,
"Content-Type": "application/json"})
try:
with urllib.request.urlopen(req, timeout=30) as r:
raw = r.read()
return r.status, (json.loads(raw) if raw else {})
except urllib.error.HTTPError as e:
return e.code, e.read()[:400].decode("utf-8", "replace")
flows = call("GET", "/flows/instances/?page_size=100")[1]["results"]
fpk = next(f["pk"] for f in flows if f["slug"] == "default-authentication-flow")
st, bindings = call("GET", f"/flows/bindings/?target={fpk}&page_size=100&ordering=order")
pwd_binding = next(b for b in bindings["results"]
if b.get("stage_obj", {}).get("name") == "default-authentication-password")
print("binding пароля:", pwd_binding["pk"])
st, existing = call("GET", f"/policies/bindings/?target={pwd_binding['pk']}&page_size=10")
print("существующие policy bindings:", st, existing.get("pagination", {}).get("count")
if isinstance(existing, dict) else existing)
if isinstance(existing, dict) and existing.get("results"):
print("уже есть")
else:
st, r = call("POST", "/policies/bindings/", {
"policy": POLICY,
"target": pwd_binding["pk"],
"order": 0,
"enabled": True,
"negate": True,
"timeout": 30,
})
print("создание:", st, str(r)[:200])
st, final = call("GET", f"/policies/bindings/?target={pwd_binding['pk']}&page_size=10")
if isinstance(final, dict):
for b in final.get("results", []):
print(" policy binding:", b.get("policy_obj", {}).get("name"),
"negate=", b.get("negate"), "enabled=", b.get("enabled"))
+34
View File
@@ -0,0 +1,34 @@
# Prometheus за SSO
## Схема
```
https://prometheus.buryans.ru (VPS, Let's Encrypt)
│ proxy_pass
▼
192.168.1.134:9113 (oauth2-proxy, CT134)
│ OIDC → Authentik
▼
192.168.1.134:9090 (Prometheus)
```
## Компоненты
| Что | Где |
|---|---|
| VPS vhost | `/etc/nginx/conf.d/prometheus.conf` |
| Сертификат | `/etc/letsencrypt/live/prometheus.buryans.ru/` |
| oauth2-proxy | CT134, контейнер `oauth2-proxy-prometheus`, порт 9113 |
| Провайдер | Authentik, приложение `prometheus` |
## Проверка
```
curl -sI https://prometheus.buryans.ru/ | head -3
# ожидаем 302 → /application/o/authorize/
```
## Откат
1. Остановить контейнер `oauth2-proxy-prometheus`.
2. Удалить `/etc/nginx/conf.d/prometheus.conf` на VPS, `nginx -t && reload`.