Аудит пользователей по всем сервисам + команда !users

identity_audit.py собирает учётные записи из Authentik, Matrix, Immich,
Paperless, Gitea и Jellyfin, объединяет их по почте или имени (union-find),
отбрасывает служебные аккаунты и строит матрицу «кто где заведён».

Результат: 7 человек. Immich и Paperless есть только у владельца, daniil не
заведён в Matrix. Таблица сохраняется в API (коллекция identity) и отдаётся
ботом по команде !users мгновенно.

Расписание: понедельник 08:00.

По пути: экранирование сломало файл ботов (литеральные \\n) — восстановлен
из репозитория и правка применена заново.
This commit is contained in:
buryan-agent committed 2026-10-19 21:06:07 +03:00
1 parent e5fe3e2382
commit f8963f6e94
3 files changed
+292

No files matched your search

+14
View File
@@ -274,6 +274,7 @@ class InfraBot(Bot):
self.cmd("inbox", "пожелания и просьбы, которые собрали боты")(lambda a: self._inbox())
self.cmd("sources", "источники событий и их активность")(lambda a: self._services_cmd(a))
self.cmd("history", "история по сервису: `!history kuma`")(lambda a: self._history_cmd(a))
self.cmd("users", "кто в каких сервисах есть: аудит доступов")(lambda a: self._users_cmd())
def _services_cmd(self, arg):
"""Источники событий: кто сколько присылает и когда последний раз."""
@@ -310,6 +311,19 @@ class InfraBot(Bot):
+ (f" — {title}" if title else ""))
return "\n".join(lines)
def _users_cmd(self):
"""Аудит пользователей: кто где заведён."""
data, err = core_api.get_data("identity", 1)
if err:
return f"Ядро не ответило: {err}"
items = (data or {}).get("items") or []
if not items:
return "Аудит ещё не запускался. Он идёт по понедельникам в 08:00."
payload = items[0].get("payload") or {}
table = payload.get("table") or "нет таблицы"
return ("**Доступы по сервисам**\n\n" + table
+ "\n\n_✓ — аккаунт есть, тире — нет. Обновляется по понедельникам._")
def _status(self, prom):
targets, err = prom.targets()
if err:
+55
View File
@@ -0,0 +1,55 @@
# Аудит пользователей
Показывает, кто в каких сервисах заведён — и где доступа не хватает.
Запуск: понедельник 08:00 (`/etc/cron.d/hub-identity`), лог
`/var/log/hub-identity.log`.
## Откуда берутся данные
| Сервис | Источник |
|---|---|
| Authentik | `authentik_db.authentik_core_user` |
| Matrix | `matrix_db.users` |
| Immich | `immich_db."user"` |
| Paperless | `paperless_db.auth_user` |
| Gitea | `gitea_db."user"` |
| Jellyfin | API `/Users` |
## Как объединяются записи
Один человек может называться по-разному: `Nikita` в Authentik, `@nikita:...`
в Matrix, `nikita` в Gitea. Записи объединяются, если совпадает почта **или**
имя (без учёта регистра и домена Matrix) — через union-find.
Служебные аккаунты отбрасываются: `bot_*`, `ak-*` (outpost), `agent-*`,
telegram-мосты (`telegram_*`), хэши и тестовые (`sso-check`).
## Результат прогона
```
| кто | Authenti | Matrix | Jellyfin | Immich | Paperles | Gitea |
| AlexTest | ✓ | ✓ | ✓ | — | — | ✓ |
| daniil | ✓ | — | ✓ | — | — | ✓ |
| elena | ✓ | ✓ | ✓ | — | — | ✓ |
| Nikita | ✓ | ✓ | ✓ | — | — | ✓ |
| polina | ✓ | ✓ | ✓ | — | — | ✓ |
| Roman | ✓ | — | ✓ | ✓ | ✓ | ✓ |
| sergey | ✓ | ✓ | ✓ | — | — | ✓ |
человек: 7 · с неполным доступом: 7
```
## Что это показало
* **Immich и Paperless** есть только у владельца — остальные шесть человек
туда не заведены.
* **daniil** не заведён в Matrix.
* Все остальные сервисы (Authentik, Jellyfin, Gitea) — у всех.
Это следующий практический шаг: завести людей в Immich и Paperless
(или решить, что им туда не нужно).
## В чате
Команда `!users` у бота Инфраструктура: таблица отдаётся из ядра
(коллекция `identity`), поэтому ответ мгновенный.
+223
View File
@@ -0,0 +1,223 @@
"""Аудит пользователей: кто есть в каком сервисе.
Собирает учётные записи из Authentik, Matrix, Immich, Paperless, Gitea,
Jellyfin и показывает, кого где не хватает.
Объединение: записи считаются одним человеком, если совпадает почта ИЛИ имя
(без учёта регистра и домена Matrix). Служебные аккаунты отбрасываются.
"""
import json
import os
import re
import subprocess
import sys
import urllib.request
JELLYFIN = os.environ.get("JELLYFIN_URL", "http://192.168.1.103:8096")
JELLYFIN_KEY = os.environ.get("JELLYFIN_KEY", "")
CORE = os.environ.get("CORE_URL", "http://127.0.0.1:9120")
SERVICES = ["Authentik", "Matrix", "Jellyfin", "Immich", "Paperless", "Gitea"]
QUERIES = {
"Authentik": ("authentik_db", "select coalesce(username,'') || '|' || coalesce(email,'') from authentik_core_user"),
"Matrix": ("matrix_db", "select name || '|' from users"),
"Immich": ("immich_db", "select coalesce(\"name\",'') || '|' || coalesce(email,'') from \"user\""),
"Paperless": ("paperless_db", "select coalesce(username,'') || '|' || coalesce(email,'') from auth_user"),
"Gitea": ("gitea_db", "select coalesce(name,'') || '|' || coalesce(email,'') from \"user\""),
}
# боты и служебные аккаунты
SKIP_EXACT = {
"media", "photo", "book", "home", "infra", "search", "digest", "cam",
"akadmin", "admin", "root", "anonymoususer", "consumer", "service",
"outpost", "relay", "sync", "bot", "infrastructure", "comms_agent",
"telegrambot", "sso-check", "sso_check",
}
SKIP_PREFIX = ("bot_", "bot-", "ak-", "agent-", "akoutpost", "service-",
"telegram_", "telegram-", "tg_")
def psql(db, sql, timeout=45):
path = "/tmp/idq.sql"
open(path, "w", encoding="utf-8").write(sql + ";\n")
try:
subprocess.run(["pct", "push", "151", path, path, "--perms", "644"],
capture_output=True, timeout=30)
out = subprocess.run(
["pct", "exec", "151", "--", "bash", "-c",
f"su - postgres -c 'psql -d {db} -tA -f {path}'"],
capture_output=True, text=True, timeout=timeout)
return (out.stdout or "").strip().splitlines(), (out.stderr or "").strip()[:100]
except Exception as e:
return [], str(e)[:100]
def jellyfin_users():
if not JELLYFIN_KEY:
return [], "нет ключа"
req = urllib.request.Request(f"{JELLYFIN}/Users",
headers={"Authorization": f'MediaBrowser Token="{JELLYFIN_KEY}"'})
try:
with urllib.request.urlopen(req, timeout=20) as r:
data = json.loads(r.read() or b"[]")
return [(u.get("Name", ""), "") for u in data], None
except Exception as e:
return [], str(e)[:100]
def clean_name(name):
n = (name or "").strip()
if n.startswith("@"):
n = n[1:].split(":")[0]
return n
def same_person(name, email):
"""Ключи, по которым запись может совпасть с другой."""
keys = set()
e = (email or "").strip().lower()
if e and "@" in e:
keys.add("e:" + e)
n = clean_name(name).lower()
if n:
keys.add("n:" + n)
return keys
def is_service(name, email):
n = clean_name(name).lower()
e = (email or "").strip().lower()
if not n:
return True
if n in SKIP_EXACT or n.startswith(SKIP_PREFIX):
return True
if re.fullmatch(r"[0-9a-f]{32,}", n):
return True
if re.fullmatch(r"[0-9a-f-]{36}", n):
return True
if e.endswith("@service.local"):
return True
return False
class Union:
def __init__(self):
self.parent = {}
def find(self, x):
self.parent.setdefault(x, x)
while self.parent[x] != x:
self.parent[x] = self.parent[self.parent[x]]
x = self.parent[x]
return x
def union(self, a, b):
ra, rb = self.find(a), self.find(b)
if ra != rb:
self.parent[rb] = ra
def collect():
rows = [] # (service, name, email)
errors = {}
for service, (db, sql) in QUERIES.items():
lines, err = psql(db, sql)
if err:
errors[service] = err
continue
for line in lines:
name, _, email = line.partition("|")
if not name.strip() or is_service(name, email):
continue
rows.append((service, clean_name(name), email.strip()))
lines, err = jellyfin_users()
if err:
errors["Jellyfin"] = err
else:
for name, email in lines:
if not name.strip() or is_service(name, email):
continue
rows.append(("Jellyfin", clean_name(name), email.strip()))
# объединяем по общим ключам (union-find)
u = Union()
for service, name, email in rows:
keys = sorted(same_person(name, email))
for k in keys[1:]:
u.union(keys[0], k)
groups = {}
for service, name, email in rows:
keys = sorted(same_person(name, email))
root = u.find(keys[0]) if keys else name.lower()
g = groups.setdefault(root, {"names": set(), "email": "", "services": {}})
g["names"].add(name)
if email and "@" in email and not g["email"]:
g["email"] = email
g["services"].setdefault(service, name)
people = {}
for root, g in groups.items():
label = sorted(g["names"], key=lambda x: (-len(x), x))[0]
people[root] = {"name": label, "email": g["email"], "services": g["services"]}
return people, errors
def render(people):
lines = ["| кто | " + " | ".join(s[:8] for s in SERVICES) + " |", "|" + "---|" * (len(SERVICES) + 1)]
gaps = 0
for key, info in sorted(people.items(), key=lambda kv: kv[1]["name"].lower()):
marks = ["✓" if s in info["services"] else "—" for s in SERVICES]
if "—" in marks:
gaps += 1
lines.append(f"| {info['name']} | " + " | ".join(marks) + " |")
lines.append("")
lines.append(f"человек: {len(people)} · с неполным доступом: {gaps}")
return "\n".join(lines), gaps
def main():
people, errors = collect()
text, gaps = render(people)
print("**Пользователи по сервисам**\n")
print(text)
if errors:
print("\nне удалось прочитать:")
for s, e in errors.items():
print(f" {s}: {e}")
# сохраняем таблицу для ботов
try:
import datetime
doc = {"key": datetime.datetime.now().strftime("%Y-%m-%d"),
"payload": {"table": text, "people": len(people), "gaps": gaps},
"tags": ["аудит", "доступ"]}
req2 = urllib.request.Request(f"{CORE}/data/identity",
data=json.dumps(doc, ensure_ascii=False).encode(),
method="POST", headers={"Content-Type": "application/json"})
urllib.request.urlopen(req2, timeout=15).read()
except Exception as e:
print("не сохранил таблицу:", str(e)[:80])
body = json.dumps({
"source": "identity-audit",
"type": "identity.audit",
"entity": {"kind": "аудит", "key": "identity", "title": "Пользователи"},
"payload": {"detail": f"человек: {len(people)}, с неполным доступом: {gaps}"},
}, ensure_ascii=False).encode()
req = urllib.request.Request(f"{CORE}/event", data=body, method="POST",
headers={"Content-Type": "application/json"})
try:
with urllib.request.urlopen(req, timeout=15):
pass
except Exception:
pass
return 0
if __name__ == "__main__":
sys.exit(main())