IPAM Manager: API, UI-админка, журнал аудита
Backend (FastAPI, SQLAlchemy 2, Alembic, PostgreSQL 16): - организации, VRF, префиксы (дерево, использование, автоназначение), адреса, операторы связи, устройства и типы устройств; JWT, роли admin/viewer; - VRF принадлежит организации (составной FK), смена VRF у префикса переносит поддерево, имя VRF уникально в организации; - журнал аудита: поиск и фильтры, ротация (срок/количество), очистка по паролю с блокировкой, IP клиента и метаданные запроса (X-Forwarded-For только от TRUSTED_PROXIES). UI (web/, без сборки): экраны и диалоги по макетам «IPAM Manager», кликабельные строки реестров, локальные шрифты IBM Plex, собственные выпадающие списки. Окружение: docker-compose (postgres + app), миграции Alembic 0001-0004, scripts/gen_env.py, scripts/seed_demo.py, 11 автотестов (pytest). Документация: README.md и docs/changes/001-005 (планы и итоги). Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
commit
a846d30872
64 files changed
+4194
No files matched your search
Whitespace-only changes.
Whitespace-only changes.
Whitespace-only changes.
@@ -0,0 +1,28 @@
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.db import get_db
|
||||
from app.models import User
|
||||
from app.schemas import LoginIn, TokenOut, UserOut
|
||||
from app.security import create_token, current_user, verify_password
|
||||
from app.services import ANONYMOUS, audit
|
||||
|
||||
router = APIRouter(prefix="/auth", tags=["auth"])
|
||||
|
||||
|
||||
@router.post("/login", response_model=TokenOut)
|
||||
def login(body: LoginIn, db: Session = Depends(get_db)):
|
||||
user = db.scalar(select(User).where(User.username == body.username, User.is_active))
|
||||
if user is None or not verify_password(body.password, user.password_hash):
|
||||
audit(db, ANONYMOUS, "session", None, "failed", body.username[:100], message="Неудачная попытка входа в UI")
|
||||
db.commit()
|
||||
raise HTTPException(401, "Неверный логин или пароль")
|
||||
audit(db, user, "session", None, "login", user.username, message=f"Вход в UI: {user.username}")
|
||||
db.commit()
|
||||
return TokenOut(access_token=create_token(user))
|
||||
|
||||
|
||||
@router.get("/me", response_model=UserOut)
|
||||
def me(user: User = Depends(current_user)):
|
||||
return user
|
||||
@@ -0,0 +1,168 @@
|
||||
"""Журнал: поиск и фильтры, запись, настройки ротации, очистка с подтверждением пароля."""
|
||||
import ipaddress
|
||||
import uuid
|
||||
from datetime import date, datetime, time, timedelta, timezone
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query
|
||||
from pydantic import BaseModel, Field
|
||||
from sqlalchemy import String, cast, delete, func, or_, select
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app import schemas as s
|
||||
from app.db import get_db
|
||||
from app.models import AuditLog, ClearAttempt, User
|
||||
from app.rotation import get_settings, rotate, save_settings
|
||||
from app.security import admin_user, current_user, verify_password
|
||||
from app.services import audit, commit
|
||||
|
||||
router = APIRouter(dependencies=[Depends(current_user)], tags=["journal"])
|
||||
MAX_ATTEMPTS = 5
|
||||
LOCK_MINUTES = 10
|
||||
|
||||
|
||||
def _escape_like(q: str) -> str:
|
||||
return q.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_")
|
||||
|
||||
|
||||
def _filtered(stmt, event_type: str, entity_type: str, actor: str, date_from: date | None, date_to: date | None, q: str, client_ip: str = ""):
|
||||
if event_type:
|
||||
et, _, action = event_type.partition(".")
|
||||
stmt = stmt.where(AuditLog.entity_type == et, AuditLog.action == action)
|
||||
if entity_type:
|
||||
stmt = stmt.where(AuditLog.entity_type == entity_type)
|
||||
if actor:
|
||||
stmt = stmt.where(AuditLog.username == actor.removeprefix("ui:"))
|
||||
if client_ip.strip():
|
||||
try:
|
||||
net = ipaddress.ip_network(client_ip.strip(), strict=False) # точный IP или подсеть
|
||||
except ValueError:
|
||||
raise HTTPException(422, "Некорректный IP-адрес или подсеть")
|
||||
stmt = stmt.where(AuditLog.client_ip.op("<<=")(str(net)))
|
||||
if date_from:
|
||||
stmt = stmt.where(AuditLog.ts >= datetime.combine(date_from, time.min, timezone.utc))
|
||||
if date_to:
|
||||
stmt = stmt.where(AuditLog.ts < datetime.combine(date_to + timedelta(days=1), time.min, timezone.utc))
|
||||
if q.strip():
|
||||
term = _escape_like(q.strip())
|
||||
like = f"%{term}%"
|
||||
uid_prefix = _escape_like(q.strip().removeprefix("evt_").lower()) + "%"
|
||||
stmt = stmt.where(or_(
|
||||
AuditLog.message.ilike(like, escape="\\"), AuditLog.entity_label.ilike(like, escape="\\"),
|
||||
cast(AuditLog.uid, String).ilike(uid_prefix, escape="\\"),
|
||||
func.host(AuditLog.client_ip).ilike(f"{term}%", escape="\\"),
|
||||
))
|
||||
return stmt
|
||||
|
||||
|
||||
@router.get("/audit", response_model=s.Page[s.AuditOut])
|
||||
def list_audit(
|
||||
event_type: str = "", entity_type: str = "", actor: str = "", date_from: date | None = None, date_to: date | None = None,
|
||||
q: str = "", client_ip: str = "", limit: int = Query(100, le=500), offset: int = 0, db: Session = Depends(get_db),
|
||||
):
|
||||
stmt = _filtered(select(AuditLog), event_type, entity_type, actor, date_from, date_to, q, client_ip)
|
||||
total = db.scalar(select(func.count()).select_from(stmt.subquery())) or 0
|
||||
rows = db.scalars(stmt.order_by(AuditLog.id.desc()).limit(limit).offset(offset)).all()
|
||||
return s.Page(items=[s.AuditOut.from_row(r) for r in rows], total=total)
|
||||
|
||||
|
||||
class Summary(BaseModel):
|
||||
total: int
|
||||
oldest_ts: datetime | None
|
||||
retention_days: int
|
||||
max_entries: int
|
||||
|
||||
|
||||
@router.get("/audit/summary", response_model=Summary)
|
||||
def summary(db: Session = Depends(get_db)):
|
||||
cfg = get_settings(db)
|
||||
total, oldest = db.execute(select(func.count(), func.min(AuditLog.ts))).one()
|
||||
return Summary(total=total, oldest_ts=oldest, **cfg)
|
||||
|
||||
|
||||
class Facets(BaseModel):
|
||||
event_types: list[str]
|
||||
entity_types: list[str]
|
||||
actors: list[str]
|
||||
|
||||
|
||||
@router.get("/audit/facets", response_model=Facets)
|
||||
def facets(db: Session = Depends(get_db)):
|
||||
pairs = db.execute(select(AuditLog.entity_type, AuditLog.action).distinct().order_by(AuditLog.entity_type, AuditLog.action)).all()
|
||||
users = db.scalars(select(AuditLog.username).distinct().order_by(AuditLog.username)).all()
|
||||
return Facets(
|
||||
event_types=[f"{e}.{a}" for e, a in pairs], entity_types=sorted({e for e, _ in pairs}),
|
||||
actors=[u if u in ("system", "anonymous") else f"ui:{u}" for u in users],
|
||||
)
|
||||
|
||||
|
||||
@router.get("/audit/{uid}", response_model=s.AuditOut)
|
||||
def get_entry(uid: uuid.UUID, db: Session = Depends(get_db)):
|
||||
row = db.scalar(select(AuditLog).where(AuditLog.uid == uid))
|
||||
if row is None:
|
||||
raise HTTPException(404, "Запись не найдена")
|
||||
return s.AuditOut.from_row(row)
|
||||
|
||||
|
||||
# ------------------------------------------------------------------- настройки
|
||||
class JournalSettings(BaseModel):
|
||||
retention_days: int = Field(ge=0, le=3650)
|
||||
max_entries: int = Field(ge=0, le=10_000_000)
|
||||
|
||||
|
||||
@router.get("/journal/settings", response_model=JournalSettings)
|
||||
def read_settings(db: Session = Depends(get_db)):
|
||||
return get_settings(db)
|
||||
|
||||
|
||||
class SettingsSaved(JournalSettings):
|
||||
deleted: int
|
||||
|
||||
|
||||
@router.put("/journal/settings", response_model=SettingsSaved)
|
||||
def update_settings(body: JournalSettings, db: Session = Depends(get_db), user: User = Depends(admin_user)):
|
||||
old = get_settings(db)
|
||||
new = body.model_dump()
|
||||
save_settings(db, new)
|
||||
changed = {k: f"{old[k]} → {v}" for k, v in new.items() if old[k] != v}
|
||||
audit(db, user, "journal", None, "settings_updated", "settings", changed or None,
|
||||
message="Настройки журнала: " + ("; ".join(f"{k} {v}" for k, v in changed.items()) or "без изменений"))
|
||||
commit(db)
|
||||
result = rotate(db) or {"by_age": 0, "by_count": 0} # ротация сразу при сохранении
|
||||
return SettingsSaved(**new, deleted=result["by_age"] + result["by_count"])
|
||||
|
||||
|
||||
# --------------------------------------------------------------------- очистка
|
||||
class ClearIn(BaseModel):
|
||||
password: str
|
||||
|
||||
|
||||
def _lock_state(db: Session, user_id: int) -> tuple[int, int]:
|
||||
"""(неудачных за окно, секунд до конца блокировки). Блокировка — LOCK_MINUTES после 5-й неудачи в пределах окна."""
|
||||
now = datetime.now(timezone.utc)
|
||||
last = db.scalars(select(ClearAttempt.ts).where(ClearAttempt.user_id == user_id).order_by(ClearAttempt.id.desc()).limit(MAX_ATTEMPTS)).all()
|
||||
window = timedelta(minutes=LOCK_MINUTES)
|
||||
in_window = sum(1 for ts in last if now - ts <= window)
|
||||
if len(last) == MAX_ATTEMPTS and last[0] - last[-1] <= window:
|
||||
remaining = (last[0] + window - now).total_seconds()
|
||||
if remaining > 0:
|
||||
return MAX_ATTEMPTS, int(remaining) + 1
|
||||
return in_window, 0
|
||||
|
||||
|
||||
@router.post("/journal/clear")
|
||||
def clear_journal(body: ClearIn, db: Session = Depends(get_db), user: User = Depends(admin_user)):
|
||||
used, retry = _lock_state(db, user.id)
|
||||
if retry:
|
||||
raise HTTPException(429, {"message": "Слишком много неверных попыток", "retry_after_seconds": retry})
|
||||
if not verify_password(body.password, user.password_hash):
|
||||
db.add(ClearAttempt(user_id=user.id))
|
||||
db.commit()
|
||||
used, retry = _lock_state(db, user.id)
|
||||
if retry:
|
||||
raise HTTPException(429, {"message": "Слишком много неверных попыток", "retry_after_seconds": retry})
|
||||
raise HTTPException(403, {"message": "Неверный пароль", "attempts_left": MAX_ATTEMPTS - used})
|
||||
deleted = db.execute(delete(AuditLog)).rowcount
|
||||
db.execute(delete(ClearAttempt).where(ClearAttempt.user_id == user.id))
|
||||
audit(db, user, "journal", None, "cleared", "clear", {"deleted": deleted}, message=f"Журнал очищен: удалено записей {deleted}")
|
||||
commit(db)
|
||||
return {"deleted": deleted}
|
||||
@@ -0,0 +1,45 @@
|
||||
from fastapi import APIRouter, Depends, Query
|
||||
from pydantic import BaseModel
|
||||
from sqlalchemy import func, select
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app import schemas as s
|
||||
from app.api.v1.prefixes import _prefix_outs
|
||||
from app.db import get_db
|
||||
from app.models import Address, AddressStatus, AuditLog, Prefix, PrefixStatus, Vrf
|
||||
from app.security import current_user
|
||||
from app.services import capacity, utilization
|
||||
|
||||
router = APIRouter(dependencies=[Depends(current_user)])
|
||||
|
||||
|
||||
class Overview(BaseModel):
|
||||
prefixes: int
|
||||
vrfs: int
|
||||
assigned: int
|
||||
capacity: int
|
||||
utilization: int
|
||||
reserved: int
|
||||
top_prefixes: list[s.PrefixOut]
|
||||
recent_changes: list[s.AuditOut]
|
||||
|
||||
|
||||
@router.get("/overview", response_model=Overview, tags=["overview"])
|
||||
def overview(db: Session = Depends(get_db)):
|
||||
prefixes = db.scalars(select(Prefix).where(Prefix.status == PrefixStatus.active)).all()
|
||||
outs = _prefix_outs(db, list(prefixes))
|
||||
parents = {p.parent_id for p in outs if p.parent_id}
|
||||
leaves = [p for p in outs if p.id not in parents] # ёмкость считаем по листьям, чтобы не удваивать
|
||||
leaves4 = [p for p in leaves if p.family == 4] # IPv6-пространство несопоставимо по размеру — в метрики использования не входит
|
||||
cap = sum(p.capacity for p in leaves4)
|
||||
v4 = func.family(Address.address) == 4
|
||||
assigned = db.scalar(select(func.count()).select_from(Address).where(Address.status == AddressStatus.assigned, v4)) or 0
|
||||
reserved = db.scalar(select(func.count()).select_from(Address).where(Address.status == AddressStatus.reserved, v4)) or 0
|
||||
top = sorted((p for p in leaves4 if p.capacity > 1), key=lambda p: p.utilization, reverse=True)[:4]
|
||||
recent = db.scalars(select(AuditLog).order_by(AuditLog.id.desc()).limit(4)).all()
|
||||
return Overview(
|
||||
prefixes=db.scalar(select(func.count()).select_from(Prefix)) or 0,
|
||||
vrfs=db.scalar(select(func.count()).select_from(Vrf)) or 0,
|
||||
assigned=assigned, capacity=cap, utilization=utilization(assigned, cap), reserved=reserved,
|
||||
top_prefixes=top, recent_changes=[s.AuditOut.from_row(r) for r in recent],
|
||||
)
|
||||
@@ -0,0 +1,329 @@
|
||||
import ipaddress
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query
|
||||
from sqlalchemy import String, and_, cast, func, or_, select, update
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app import schemas as s
|
||||
from app.db import get_db
|
||||
from app.models import Address, AddressStatus, Device, Organization, Prefix, PrefixStatus, User, Vrf
|
||||
from app.security import admin_user, current_user
|
||||
from app.services import (
|
||||
MAX_CAPACITY, apply_update, audit, capacity, commit, count, flush, get_or_404, next_free, utilization,
|
||||
)
|
||||
|
||||
router = APIRouter(dependencies=[Depends(current_user)], tags=["prefixes"])
|
||||
FREE_LISTING_LIMIT = 4096 # «свободные» строки показываем, только если подсеть не больше /20
|
||||
|
||||
|
||||
# -------------------------------------------------------------------- prefixes
|
||||
def _usage(db: Session, ids: list[int]) -> dict[int, tuple[int, int]]:
|
||||
"""{prefix_id: (assigned, stored)} с учётом вложенных префиксов того же VRF."""
|
||||
if not ids:
|
||||
return {}
|
||||
p, c = Prefix.__table__.alias("p"), Prefix.__table__.alias("c")
|
||||
a = Address.__table__
|
||||
rows = db.execute(
|
||||
select(
|
||||
p.c.id,
|
||||
func.count().filter(a.c.status == AddressStatus.assigned),
|
||||
func.count(a.c.id),
|
||||
)
|
||||
.select_from(p.join(c, and_(c.c.vrf_id == p.c.vrf_id, c.c.prefix.op("<<=")(p.c.prefix)))
|
||||
.join(a, a.c.prefix_id == c.c.id))
|
||||
.where(p.c.id.in_(ids))
|
||||
.group_by(p.c.id)
|
||||
).all()
|
||||
return {r[0]: (r[1], r[2]) for r in rows}
|
||||
|
||||
|
||||
def _depths(db: Session, organization_id: int) -> dict[int, int]:
|
||||
parents = dict(db.execute(select(Prefix.id, Prefix.parent_id).where(Prefix.organization_id == organization_id)).all())
|
||||
|
||||
def depth(i: int) -> int:
|
||||
d = 0
|
||||
while parents.get(i) is not None:
|
||||
i, d = parents[i], d + 1
|
||||
return d
|
||||
|
||||
return {i: depth(i) for i in parents}
|
||||
|
||||
|
||||
def _capacities(db: Session, organization_id: int) -> dict[int, int]:
|
||||
"""Ёмкость листа — размер подсети; ёмкость родителя — сумма ёмкостей вложенных листьев."""
|
||||
rows = db.execute(select(Prefix.id, Prefix.parent_id, Prefix.prefix).where(Prefix.organization_id == organization_id)).all()
|
||||
kids: dict[int, list[int]] = {}
|
||||
for i, parent, _ in rows:
|
||||
if parent is not None:
|
||||
kids.setdefault(parent, []).append(i)
|
||||
own = {i: capacity(str(cidr)) for i, _, cidr in rows}
|
||||
memo: dict[int, int] = {}
|
||||
|
||||
def cap(i: int) -> int:
|
||||
if i not in memo:
|
||||
memo[i] = sum(cap(k) for k in kids[i]) if i in kids else own[i]
|
||||
return memo[i]
|
||||
|
||||
return {i: min(cap(i), MAX_CAPACITY) for i in own}
|
||||
|
||||
|
||||
def _prefix_outs(db: Session, rows: list[Prefix]) -> list[s.PrefixOut]:
|
||||
usage = _usage(db, [r.id for r in rows])
|
||||
depths: dict[int, int] = {}
|
||||
caps: dict[int, int] = {}
|
||||
for org_id in {r.organization_id for r in rows}:
|
||||
depths.update(_depths(db, org_id))
|
||||
caps.update(_capacities(db, org_id))
|
||||
out = []
|
||||
for r in rows:
|
||||
used, stored = usage.get(r.id, (0, 0))
|
||||
cap = caps.get(r.id, capacity(str(r.prefix)))
|
||||
out.append(s.PrefixOut(
|
||||
id=r.id, organization_id=r.organization_id, vrf_id=r.vrf_id, vrf_name=r.vrf.name,
|
||||
prefix=str(r.prefix), family=ipaddress.ip_network(str(r.prefix)).version,
|
||||
description=r.description, status=r.status, parent_id=r.parent_id, depth=depths.get(r.id, 0),
|
||||
is_pool=r.is_pool, note=r.note, used=used, capacity=cap,
|
||||
utilization=utilization(used, cap), addresses_count=stored,
|
||||
))
|
||||
return out
|
||||
|
||||
|
||||
def attach_to_tree(db: Session, p: Prefix, keep_parent: bool = False, exclude: frozenset[int] = frozenset()) -> None:
|
||||
"""Вписывает префикс в дерево его VRF: находит самого узкого родителя и забирает под себя
|
||||
вложенные префиксы, чей текущий родитель шире (exclude — уже подчинённые ему, при переносе поддерева)."""
|
||||
cidr = str(p.prefix)
|
||||
if not keep_parent:
|
||||
p.parent_id = db.scalar(
|
||||
select(Prefix.id)
|
||||
.where(Prefix.vrf_id == p.vrf_id, Prefix.id != p.id, Prefix.prefix.op(">>")(cidr))
|
||||
.order_by(func.masklen(Prefix.prefix).desc()).limit(1)
|
||||
)
|
||||
plen = ipaddress.ip_network(cidr).prefixlen
|
||||
inner = db.scalars(
|
||||
select(Prefix).where(Prefix.vrf_id == p.vrf_id, Prefix.id != p.id, Prefix.prefix.op("<<")(cidr))
|
||||
).all()
|
||||
for c in inner:
|
||||
if c.id in exclude:
|
||||
continue
|
||||
cur = db.get(Prefix, c.parent_id) if c.parent_id else None
|
||||
if cur is None or ipaddress.ip_network(str(cur.prefix)).prefixlen < plen:
|
||||
c.parent_id = p.id
|
||||
|
||||
|
||||
def _subtree(db: Session, root: Prefix) -> list[Prefix]:
|
||||
"""Префикс и все вложенные по цепочке parent_id."""
|
||||
result, frontier = [root], [root.id]
|
||||
while frontier:
|
||||
kids = db.scalars(select(Prefix).where(Prefix.parent_id.in_(frontier))).all()
|
||||
result += kids
|
||||
frontier = [k.id for k in kids]
|
||||
return result
|
||||
|
||||
|
||||
def _move_to_vrf(db: Session, p: Prefix, vrf_id: int) -> tuple[dict, int]:
|
||||
"""Переносит префикс с поддеревом в другой VRF той же организации; возвращает (diff, число префиксов)."""
|
||||
vrf = get_or_404(db, Vrf, vrf_id, "VRF")
|
||||
if vrf.organization_id != p.organization_id:
|
||||
raise HTTPException(422, "Целевой VRF принадлежит другой организации")
|
||||
subtree = _subtree(db, p)
|
||||
taken = db.scalars(select(Prefix.prefix).where(Prefix.vrf_id == vrf.id, Prefix.prefix.in_([str(m.prefix) for m in subtree]))).all()
|
||||
if taken:
|
||||
raise HTTPException(409, f"В VRF «{vrf.name}» уже есть: {', '.join(str(x) for x in taken)}")
|
||||
old_name = p.vrf.name
|
||||
for m in subtree:
|
||||
m.vrf = vrf
|
||||
p.parent_id = None
|
||||
db.flush()
|
||||
attach_to_tree(db, p, exclude=frozenset(m.id for m in subtree))
|
||||
return {"vrf": f"{old_name} → {vrf.name}", "moved": len(subtree)}, len(subtree)
|
||||
|
||||
|
||||
@router.get("/prefixes", response_model=s.Page[s.PrefixOut])
|
||||
def list_prefixes(
|
||||
organization_id: int | None = None, vrf_id: int | None = None, status: PrefixStatus | None = None,
|
||||
family: int | None = Query(None, ge=4, le=6), q: str = "",
|
||||
limit: int = Query(100, le=1000), offset: int = 0, db: Session = Depends(get_db),
|
||||
):
|
||||
stmt = select(Prefix)
|
||||
if organization_id:
|
||||
stmt = stmt.where(Prefix.organization_id == organization_id)
|
||||
if vrf_id:
|
||||
stmt = stmt.where(Prefix.vrf_id == vrf_id)
|
||||
if status:
|
||||
stmt = stmt.where(Prefix.status == status)
|
||||
if family:
|
||||
stmt = stmt.where(func.family(Prefix.prefix) == (4 if family == 4 else 6))
|
||||
if q:
|
||||
stmt = stmt.where(or_(cast(Prefix.prefix, String).ilike(f"%{q.strip()}%"), Prefix.description.ilike(f"%{q.strip()}%")))
|
||||
total = count(db, stmt)
|
||||
rows = db.scalars(stmt.order_by(Prefix.vrf_id, Prefix.prefix).limit(limit).offset(offset)).all()
|
||||
return s.Page(items=_prefix_outs(db, list(rows)), total=total)
|
||||
|
||||
|
||||
@router.get("/prefixes/{id}", response_model=s.PrefixOut)
|
||||
def get_prefix(id: int, db: Session = Depends(get_db)):
|
||||
return _prefix_outs(db, [get_or_404(db, Prefix, id, "Префикс")])[0]
|
||||
|
||||
|
||||
@router.post("/prefixes", response_model=s.PrefixOut, status_code=201)
|
||||
def create_prefix(body: s.PrefixIn, db: Session = Depends(get_db), user: User = Depends(admin_user)):
|
||||
vrf = get_or_404(db, Vrf, body.vrf_id, "VRF")
|
||||
if vrf.organization_id != body.organization_id:
|
||||
raise HTTPException(422, "VRF принадлежит другой организации")
|
||||
get_or_404(db, Organization, body.organization_id, "Организация")
|
||||
if db.scalar(select(Prefix.id).where(Prefix.vrf_id == vrf.id, Prefix.prefix == body.prefix)):
|
||||
raise HTTPException(409, "Такой префикс уже есть в этом VRF")
|
||||
|
||||
parent_id = body.parent_id
|
||||
if parent_id is not None:
|
||||
parent = get_or_404(db, Prefix, parent_id, "Родительский префикс")
|
||||
if parent.vrf_id != vrf.id or not ipaddress.ip_network(body.prefix).subnet_of(ipaddress.ip_network(str(parent.prefix))):
|
||||
raise HTTPException(422, "Родительский префикс должен содержать новый и быть в том же VRF")
|
||||
p = Prefix(**{**body.model_dump(), "parent_id": parent_id})
|
||||
db.add(p)
|
||||
flush(db, "Такой префикс уже есть в этом VRF")
|
||||
attach_to_tree(db, p, keep_parent=parent_id is not None)
|
||||
audit(db, user, "prefix", p, "created", str(p.prefix), {"vrf": vrf.name})
|
||||
commit(db, "Такой префикс уже есть в этом VRF")
|
||||
return _prefix_outs(db, [p])[0]
|
||||
|
||||
|
||||
@router.patch("/prefixes/{id}", response_model=s.PrefixOut)
|
||||
def update_prefix(id: int, body: s.PrefixUpdate, db: Session = Depends(get_db), user: User = Depends(admin_user)):
|
||||
p = get_or_404(db, Prefix, id, "Префикс")
|
||||
data = body.model_dump(exclude_unset=True, exclude_none=True)
|
||||
new_vrf = data.pop("vrf_id", None)
|
||||
changed = {k: str(v) for k, v in apply_update(p, data).items()}
|
||||
if new_vrf is not None and new_vrf != p.vrf_id:
|
||||
changed.update(_move_to_vrf(db, p, new_vrf)[0])
|
||||
audit(db, user, "prefix", p, "updated", str(p.prefix), changed)
|
||||
commit(db)
|
||||
return _prefix_outs(db, [p])[0]
|
||||
|
||||
|
||||
@router.delete("/prefixes/{id}", status_code=204)
|
||||
def delete_prefix(id: int, force: bool = False, db: Session = Depends(get_db), user: User = Depends(admin_user)):
|
||||
p = get_or_404(db, Prefix, id, "Префикс")
|
||||
if not force and count(db, select(Address.id).where(Address.prefix_id == id)):
|
||||
raise HTTPException(409, "В префиксе есть адреса; удалите их или используйте force=true")
|
||||
db.execute(update(Prefix).where(Prefix.parent_id == id).values(parent_id=p.parent_id))
|
||||
audit(db, user, "prefix", p, "deleted", str(p.prefix))
|
||||
db.delete(p)
|
||||
commit(db)
|
||||
|
||||
|
||||
# ------------------------------------------------------------------- addresses
|
||||
def _addr_out(a: Address, device_name: str | None = None) -> s.AddressOut:
|
||||
return s.AddressOut(
|
||||
id=a.id, prefix_id=a.prefix_id, address=s.ip_text(a.address), status=a.status.value,
|
||||
dns_name=a.dns_name, description=a.description, device_id=a.device_id, device_name=device_name,
|
||||
note=a.note, updated_at=a.updated_at,
|
||||
)
|
||||
|
||||
|
||||
def _check_device(db: Session, prefix: Prefix, device_id: int | None):
|
||||
if device_id is not None:
|
||||
d = get_or_404(db, Device, device_id, "Устройство")
|
||||
if d.organization_id != prefix.organization_id:
|
||||
raise HTTPException(422, "Устройство принадлежит другой организации")
|
||||
|
||||
|
||||
@router.get("/prefixes/{id}/addresses", response_model=s.AddressPage)
|
||||
def list_addresses(
|
||||
id: int, status: str = "", q: str = "", limit: int = Query(100, le=500), offset: int = 0,
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
"""status: assigned | reserved | deprecated | free | пусто (все; свободные подмешиваются для малых подсетей)."""
|
||||
p = get_or_404(db, Prefix, id, "Префикс")
|
||||
cap = capacity(str(p.prefix))
|
||||
counts = dict(db.execute(select(Address.status, func.count()).where(Address.prefix_id == id).group_by(Address.status)).all())
|
||||
stored = sum(counts.values())
|
||||
summary = s.AddressSummary(
|
||||
assigned=counts.get(AddressStatus.assigned, 0), reserved=counts.get(AddressStatus.reserved, 0),
|
||||
deprecated=counts.get(AddressStatus.deprecated, 0), free=max(cap - stored, 0), capacity=cap,
|
||||
)
|
||||
if status and status not in {"free", *(x.value for x in AddressStatus)}:
|
||||
raise HTTPException(422, "Неизвестный статус")
|
||||
|
||||
stmt = select(Address, Device.name).outerjoin(Device, Device.id == Address.device_id).where(Address.prefix_id == id)
|
||||
if status and status != "free":
|
||||
stmt = stmt.where(Address.status == AddressStatus(status))
|
||||
if q:
|
||||
like = f"%{q.strip()}%"
|
||||
stmt = stmt.where(or_(func.host(Address.address).ilike(like), Address.dns_name.ilike(like), Address.description.ilike(like)))
|
||||
rows = [_addr_out(a, dn) for a, dn in db.execute(stmt.order_by(Address.address)).all()] if status != "free" else []
|
||||
|
||||
net = ipaddress.ip_network(str(p.prefix))
|
||||
want_free = status == "free" or (not status and not q and cap <= FREE_LISTING_LIMIT)
|
||||
if want_free:
|
||||
used = {ipaddress.ip_address(s.ip_text(a)) for a in db.scalars(select(Address.address).where(Address.prefix_id == id))}
|
||||
hosts = net.hosts() if net.version == 4 and net.prefixlen <= 30 else iter(net)
|
||||
need = offset + limit if status == "free" else cap
|
||||
free = []
|
||||
for ip in hosts:
|
||||
if ip not in used:
|
||||
free.append(s.AddressOut(id=None, prefix_id=id, address=str(ip), status="free"))
|
||||
if len(free) >= need:
|
||||
break
|
||||
rows = sorted(rows + free, key=lambda r: ipaddress.ip_address(r.address))
|
||||
total = summary.free if status == "free" else (len(rows) if want_free or q or status else stored)
|
||||
return s.AddressPage(items=rows[offset:offset + limit], total=total, summary=summary)
|
||||
|
||||
|
||||
@router.post("/prefixes/{id}/addresses", response_model=s.AddressOut, status_code=201)
|
||||
def create_address(id: int, body: s.AddressIn, db: Session = Depends(get_db), user: User = Depends(admin_user)):
|
||||
p = get_or_404(db, Prefix, id, "Префикс")
|
||||
if ipaddress.ip_address(body.address) not in ipaddress.ip_network(str(p.prefix)):
|
||||
raise HTTPException(422, f"Адрес {body.address} не принадлежит префиксу {p.prefix}")
|
||||
_check_device(db, p, body.device_id)
|
||||
a = Address(prefix_id=id, **body.model_dump())
|
||||
db.add(a)
|
||||
flush(db, "Адрес уже есть в этом префиксе")
|
||||
audit(db, user, "address", a, "assigned" if a.status == AddressStatus.assigned else "created", body.address)
|
||||
commit(db, "Адрес уже есть в этом префиксе")
|
||||
db.refresh(a)
|
||||
return _addr_out(a)
|
||||
|
||||
|
||||
@router.post("/prefixes/{id}/addresses/next", response_model=s.AddressOut, status_code=201)
|
||||
def allocate_next(
|
||||
id: int, body: s.AddressUpdate | None = None, db: Session = Depends(get_db), user: User = Depends(admin_user)
|
||||
):
|
||||
"""Автоназначение первого свободного адреса; только для префиксов с флагом is_pool."""
|
||||
p = get_or_404(db, Prefix, id, "Префикс")
|
||||
if not p.is_pool:
|
||||
raise HTTPException(422, "Префикс не является пулом для автоназначения")
|
||||
ip = next_free(db, id, str(p.prefix))
|
||||
if ip is None:
|
||||
raise HTTPException(409, "В префиксе нет свободных адресов")
|
||||
data = body.model_dump(exclude_unset=True, exclude_none=True) if body else {}
|
||||
_check_device(db, p, data.get("device_id"))
|
||||
a = Address(prefix_id=id, address=ip, **data)
|
||||
db.add(a)
|
||||
flush(db, "Адрес уже занят, повторите запрос")
|
||||
audit(db, user, "address", a, "assigned", ip)
|
||||
commit(db, "Адрес уже занят, повторите запрос")
|
||||
db.refresh(a)
|
||||
return _addr_out(a)
|
||||
|
||||
|
||||
@router.patch("/addresses/{id}", response_model=s.AddressOut)
|
||||
def update_address(id: int, body: s.AddressUpdate, db: Session = Depends(get_db), user: User = Depends(admin_user)):
|
||||
a = get_or_404(db, Address, id, "Адрес")
|
||||
data = body.model_dump(exclude_unset=True)
|
||||
if data.get("dns_name"):
|
||||
s.AddressIn(address=s.ip_text(a.address), dns_name=data["dns_name"]) # валидация FQDN
|
||||
_check_device(db, db.get(Prefix, a.prefix_id), data.get("device_id"))
|
||||
changed = apply_update(a, data)
|
||||
audit(db, user, "address", a, "updated", s.ip_text(a.address), {k: str(v) for k, v in changed.items()})
|
||||
commit(db)
|
||||
db.refresh(a)
|
||||
return _addr_out(a)
|
||||
|
||||
|
||||
@router.delete("/addresses/{id}", status_code=204)
|
||||
def delete_address(id: int, db: Session = Depends(get_db), user: User = Depends(admin_user)):
|
||||
a = get_or_404(db, Address, id, "Адрес")
|
||||
audit(db, user, "address", a, "deleted", s.ip_text(a.address))
|
||||
db.delete(a)
|
||||
commit(db)
|
||||
@@ -0,0 +1,298 @@
|
||||
"""Справочники: организации, VRF, операторы, типы устройств, устройства."""
|
||||
from fastapi import APIRouter, Depends, Query
|
||||
from sqlalchemy import String, cast, func, or_, select
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app import schemas as s
|
||||
from app.db import get_db
|
||||
from app.models import (
|
||||
Address, AddressStatus, Device, DeviceType, Isp, IspNetwork, Organization, Prefix, User, Vrf,
|
||||
)
|
||||
from app.security import admin_user, current_user
|
||||
from app.services import apply_update, audit, commit, count, flush, get_or_404
|
||||
from fastapi import HTTPException
|
||||
|
||||
router = APIRouter(dependencies=[Depends(current_user)])
|
||||
|
||||
|
||||
def _like(q: str) -> str:
|
||||
return f"%{q.strip()}%"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- organizations
|
||||
def _org_out(db: Session, o: Organization) -> s.OrgOut:
|
||||
out = s.OrgOut.model_validate(o)
|
||||
out.prefixes_count = count(db, select(Prefix.id).where(Prefix.organization_id == o.id))
|
||||
out.addresses_count = count(
|
||||
db, select(Address.id).join(Prefix).where(Prefix.organization_id == o.id, Address.status == AddressStatus.assigned)
|
||||
)
|
||||
return out
|
||||
|
||||
|
||||
@router.get("/organizations", response_model=s.Page[s.OrgOut], tags=["organizations"])
|
||||
def list_orgs(q: str = "", limit: int = Query(100, le=500), offset: int = 0, db: Session = Depends(get_db)):
|
||||
stmt = select(Organization)
|
||||
if q:
|
||||
stmt = stmt.where(or_(*(c.ilike(_like(q)) for c in (Organization.name, Organization.short_name, Organization.inn, Organization.address))))
|
||||
total = count(db, stmt)
|
||||
rows = db.scalars(stmt.order_by(Organization.id).limit(limit).offset(offset)).all()
|
||||
return s.Page(items=[_org_out(db, o) for o in rows], total=total)
|
||||
|
||||
|
||||
@router.get("/organizations/{id}", response_model=s.OrgOut, tags=["organizations"])
|
||||
def get_org(id: int, db: Session = Depends(get_db)):
|
||||
return _org_out(db, get_or_404(db, Organization, id, "Организация"))
|
||||
|
||||
|
||||
@router.post("/organizations", response_model=s.OrgOut, status_code=201, tags=["organizations"])
|
||||
def create_org(body: s.OrgIn, db: Session = Depends(get_db), user: User = Depends(admin_user)):
|
||||
o = Organization(**body.model_dump())
|
||||
db.add(o)
|
||||
flush(db, "Организация с таким названием или ИНН уже существует")
|
||||
db.add(Vrf(organization_id=o.id, name="default"))
|
||||
audit(db, user, "organization", o, "created", o.name)
|
||||
commit(db, "Организация с таким названием или ИНН уже существует")
|
||||
return _org_out(db, o)
|
||||
|
||||
|
||||
@router.patch("/organizations/{id}", response_model=s.OrgOut, tags=["organizations"])
|
||||
def update_org(id: int, body: s.OrgIn, db: Session = Depends(get_db), user: User = Depends(admin_user)):
|
||||
o = get_or_404(db, Organization, id, "Организация")
|
||||
changed = apply_update(o, body.model_dump())
|
||||
audit(db, user, "organization", o, "updated", o.name, changed)
|
||||
commit(db, "Организация с таким названием или ИНН уже существует")
|
||||
return _org_out(db, o)
|
||||
|
||||
|
||||
@router.delete("/organizations/{id}", status_code=204, tags=["organizations"])
|
||||
def delete_org(id: int, db: Session = Depends(get_db), user: User = Depends(admin_user)):
|
||||
o = get_or_404(db, Organization, id, "Организация")
|
||||
busy = count(db, select(Prefix.id).where(Prefix.organization_id == id)) or count(
|
||||
db, select(Device.id).where(Device.organization_id == id)) or count(db, select(Isp.id).where(Isp.organization_id == id))
|
||||
if busy:
|
||||
raise HTTPException(409, "Нельзя удалить: у организации есть префиксы, устройства или операторы")
|
||||
for v in db.scalars(select(Vrf).where(Vrf.organization_id == id)):
|
||||
db.delete(v)
|
||||
audit(db, user, "organization", o, "deleted", o.name)
|
||||
db.delete(o)
|
||||
commit(db)
|
||||
|
||||
|
||||
# ------------------------------------------------------------------------- VRF
|
||||
def _vrf_out(db: Session, v: Vrf) -> s.VrfOut:
|
||||
out = s.VrfOut.model_validate(v)
|
||||
out.prefixes_count = count(db, select(Prefix.id).where(Prefix.vrf_id == v.id))
|
||||
return out
|
||||
|
||||
|
||||
@router.get("/vrfs", response_model=s.Page[s.VrfOut], tags=["vrf"])
|
||||
def list_vrfs(organization_id: int | None = None, db: Session = Depends(get_db)):
|
||||
stmt = select(Vrf)
|
||||
if organization_id:
|
||||
stmt = stmt.where(Vrf.organization_id == organization_id)
|
||||
rows = db.scalars(stmt.order_by(Vrf.id)).all()
|
||||
return s.Page(items=[_vrf_out(db, v) for v in rows], total=len(rows))
|
||||
|
||||
|
||||
@router.post("/vrfs", response_model=s.VrfOut, status_code=201, tags=["vrf"])
|
||||
def create_vrf(body: s.VrfIn, db: Session = Depends(get_db), user: User = Depends(admin_user)):
|
||||
get_or_404(db, Organization, body.organization_id, "Организация")
|
||||
v = Vrf(**body.model_dump())
|
||||
db.add(v)
|
||||
flush(db, "VRF с таким названием уже есть в организации")
|
||||
audit(db, user, "vrf", v, "created", v.name)
|
||||
commit(db, "VRF с таким названием уже есть в организации")
|
||||
return _vrf_out(db, v)
|
||||
|
||||
|
||||
@router.patch("/vrfs/{id}", response_model=s.VrfOut, tags=["vrf"])
|
||||
def update_vrf(id: int, body: s.VrfUpdate, db: Session = Depends(get_db), user: User = Depends(admin_user)):
|
||||
v = get_or_404(db, Vrf, id, "VRF")
|
||||
changed = apply_update(v, body.model_dump(exclude_unset=True, exclude_none=True))
|
||||
audit(db, user, "vrf", v, "updated", v.name, changed)
|
||||
commit(db, "VRF с таким названием уже есть в организации")
|
||||
return _vrf_out(db, v)
|
||||
|
||||
|
||||
@router.delete("/vrfs/{id}", status_code=204, tags=["vrf"])
|
||||
def delete_vrf(id: int, db: Session = Depends(get_db), user: User = Depends(admin_user)):
|
||||
v = get_or_404(db, Vrf, id, "VRF")
|
||||
if count(db, select(Prefix.id).where(Prefix.vrf_id == id)):
|
||||
raise HTTPException(409, "Нельзя удалить: VRF используется префиксами")
|
||||
audit(db, user, "vrf", v, "deleted", v.name)
|
||||
db.delete(v)
|
||||
commit(db)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- device types
|
||||
def _type_out(db: Session, t: DeviceType) -> s.DeviceTypeOut:
|
||||
out = s.DeviceTypeOut.model_validate(t)
|
||||
out.devices_count = count(db, select(Device.id).where(Device.device_type_id == t.id))
|
||||
return out
|
||||
|
||||
|
||||
@router.get("/device-types", response_model=s.Page[s.DeviceTypeOut], tags=["devices"])
|
||||
def list_types(db: Session = Depends(get_db)):
|
||||
rows = db.scalars(select(DeviceType).order_by(DeviceType.id)).all()
|
||||
return s.Page(items=[_type_out(db, t) for t in rows], total=len(rows))
|
||||
|
||||
|
||||
@router.post("/device-types", response_model=s.DeviceTypeOut, status_code=201, tags=["devices"])
|
||||
def create_type(body: s.DeviceTypeIn, db: Session = Depends(get_db), user: User = Depends(admin_user)):
|
||||
t = DeviceType(name=body.name)
|
||||
db.add(t)
|
||||
flush(db, "Тип с таким названием уже существует")
|
||||
audit(db, user, "device_type", t, "created", t.name)
|
||||
commit(db, "Тип с таким названием уже существует")
|
||||
return _type_out(db, t)
|
||||
|
||||
|
||||
@router.patch("/device-types/{id}", response_model=s.DeviceTypeOut, tags=["devices"])
|
||||
def update_type(id: int, body: s.DeviceTypeIn, db: Session = Depends(get_db), user: User = Depends(admin_user)):
|
||||
t = get_or_404(db, DeviceType, id, "Тип")
|
||||
changed = apply_update(t, {"name": body.name})
|
||||
audit(db, user, "device_type", t, "updated", t.name, changed)
|
||||
commit(db, "Тип с таким названием уже существует")
|
||||
return _type_out(db, t)
|
||||
|
||||
|
||||
@router.delete("/device-types/{id}", status_code=204, tags=["devices"])
|
||||
def delete_type(id: int, db: Session = Depends(get_db), user: User = Depends(admin_user)):
|
||||
t = get_or_404(db, DeviceType, id, "Тип")
|
||||
if t.is_default:
|
||||
raise HTTPException(409, "Нельзя удалить тип по умолчанию")
|
||||
if count(db, select(Device.id).where(Device.device_type_id == id)):
|
||||
raise HTTPException(409, "Нельзя удалить: тип используется устройствами")
|
||||
audit(db, user, "device_type", t, "deleted", t.name)
|
||||
db.delete(t)
|
||||
commit(db)
|
||||
|
||||
|
||||
# --------------------------------------------------------------------- devices
|
||||
def _device_out(db: Session, d: Device) -> s.DeviceOut:
|
||||
rows = db.execute(
|
||||
select(Address.address, Address.prefix_id, Address.status).where(Address.device_id == d.id).order_by(Address.address)
|
||||
).all()
|
||||
t = db.get(DeviceType, d.device_type_id)
|
||||
return s.DeviceOut(
|
||||
id=d.id, name=d.name, device_type_id=d.device_type_id, device_type_name=t.name,
|
||||
organization_id=d.organization_id, mac=d.mac, note=d.note,
|
||||
ip_addresses=[s.ip_text(r[0]) for r in rows], first_prefix_id=rows[0][1] if rows else None,
|
||||
all_deprecated=bool(rows) and all(r[2] == AddressStatus.deprecated for r in rows),
|
||||
)
|
||||
|
||||
|
||||
@router.get("/devices", response_model=s.Page[s.DeviceOut], tags=["devices"])
|
||||
def list_devices(
|
||||
organization_id: int | None = None, device_type_id: int | None = None, q: str = "",
|
||||
limit: int = Query(100, le=500), offset: int = 0, db: Session = Depends(get_db),
|
||||
):
|
||||
stmt = select(Device)
|
||||
if organization_id:
|
||||
stmt = stmt.where(Device.organization_id == organization_id)
|
||||
if device_type_id:
|
||||
stmt = stmt.where(Device.device_type_id == device_type_id)
|
||||
if q:
|
||||
ip_match = select(Address.device_id).where(func.host(Address.address).ilike(_like(q)))
|
||||
stmt = stmt.where(or_(Device.name.ilike(_like(q)), Device.note.ilike(_like(q)), Device.id.in_(ip_match)))
|
||||
total = count(db, stmt)
|
||||
rows = db.scalars(stmt.order_by(Device.id).limit(limit).offset(offset)).all()
|
||||
return s.Page(items=[_device_out(db, d) for d in rows], total=total)
|
||||
|
||||
|
||||
@router.post("/devices", response_model=s.DeviceOut, status_code=201, tags=["devices"])
|
||||
def create_device(body: s.DeviceIn, db: Session = Depends(get_db), user: User = Depends(admin_user)):
|
||||
get_or_404(db, Organization, body.organization_id, "Организация")
|
||||
get_or_404(db, DeviceType, body.device_type_id, "Тип")
|
||||
d = Device(**body.model_dump())
|
||||
db.add(d)
|
||||
flush(db, "Устройство с таким именем уже есть в организации")
|
||||
audit(db, user, "device", d, "created", d.name)
|
||||
commit(db, "Устройство с таким именем уже есть в организации")
|
||||
return _device_out(db, d)
|
||||
|
||||
|
||||
@router.get("/devices/{id}", response_model=s.DeviceOut, tags=["devices"])
|
||||
def get_device(id: int, db: Session = Depends(get_db)):
|
||||
return _device_out(db, get_or_404(db, Device, id, "Устройство"))
|
||||
|
||||
|
||||
@router.patch("/devices/{id}", response_model=s.DeviceOut, tags=["devices"])
|
||||
def update_device(id: int, body: s.DeviceUpdate, db: Session = Depends(get_db), user: User = Depends(admin_user)):
|
||||
d = get_or_404(db, Device, id, "Устройство")
|
||||
data = body.model_dump(exclude_unset=True, exclude_none=True)
|
||||
if "device_type_id" in data:
|
||||
get_or_404(db, DeviceType, data["device_type_id"], "Тип")
|
||||
changed = apply_update(d, data)
|
||||
audit(db, user, "device", d, "updated", d.name, changed)
|
||||
commit(db, "Устройство с таким именем уже есть в организации")
|
||||
return _device_out(db, d)
|
||||
|
||||
|
||||
@router.delete("/devices/{id}", status_code=204, tags=["devices"])
|
||||
def delete_device(id: int, db: Session = Depends(get_db), user: User = Depends(admin_user)):
|
||||
d = get_or_404(db, Device, id, "Устройство")
|
||||
audit(db, user, "device", d, "deleted", d.name)
|
||||
db.delete(d)
|
||||
commit(db)
|
||||
|
||||
|
||||
# ------------------------------------------------------------------------ ISPs
|
||||
def _isp_out(db: Session, i: Isp) -> s.IspOut:
|
||||
org = db.get(Organization, i.organization_id)
|
||||
return s.IspOut(
|
||||
id=i.id, name=i.name, organization_id=i.organization_id, organization_name=org.name,
|
||||
networks=[str(n.cidr) for n in i.networks], hotline=i.hotline,
|
||||
contract_number=i.contract_number, note=i.note,
|
||||
)
|
||||
|
||||
|
||||
@router.get("/isps", response_model=s.Page[s.IspOut], tags=["isps"])
|
||||
def list_isps(
|
||||
organization_id: int | None = None, q: str = "", limit: int = Query(100, le=500), offset: int = 0,
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
stmt = select(Isp)
|
||||
if organization_id:
|
||||
stmt = stmt.where(Isp.organization_id == organization_id)
|
||||
if q:
|
||||
nets = select(IspNetwork.isp_id).where(cast(IspNetwork.cidr, String).ilike(_like(q)))
|
||||
orgs = select(Organization.id).where(Organization.name.ilike(_like(q)))
|
||||
stmt = stmt.where(or_(Isp.name.ilike(_like(q)), Isp.id.in_(nets), Isp.organization_id.in_(orgs)))
|
||||
total = count(db, stmt)
|
||||
rows = db.scalars(stmt.order_by(Isp.id).limit(limit).offset(offset)).all()
|
||||
return s.Page(items=[_isp_out(db, i) for i in rows], total=total)
|
||||
|
||||
|
||||
@router.post("/isps", response_model=s.IspOut, status_code=201, tags=["isps"])
|
||||
def create_isp(body: s.IspIn, db: Session = Depends(get_db), user: User = Depends(admin_user)):
|
||||
get_or_404(db, Organization, body.organization_id, "Организация")
|
||||
data = body.model_dump()
|
||||
nets = data.pop("networks")
|
||||
i = Isp(**data, networks=[IspNetwork(cidr=n) for n in nets])
|
||||
db.add(i)
|
||||
db.flush()
|
||||
audit(db, user, "isp", i, "created", i.name)
|
||||
commit(db)
|
||||
return _isp_out(db, i)
|
||||
|
||||
|
||||
@router.put("/isps/{id}", response_model=s.IspOut, tags=["isps"])
|
||||
def update_isp(id: int, body: s.IspIn, db: Session = Depends(get_db), user: User = Depends(admin_user)):
|
||||
i = get_or_404(db, Isp, id, "Оператор")
|
||||
get_or_404(db, Organization, body.organization_id, "Организация")
|
||||
data = body.model_dump()
|
||||
nets = data.pop("networks")
|
||||
changed = apply_update(i, data)
|
||||
i.networks = [IspNetwork(cidr=n) for n in nets]
|
||||
audit(db, user, "isp", i, "updated", i.name, changed)
|
||||
commit(db)
|
||||
return _isp_out(db, i)
|
||||
|
||||
|
||||
@router.delete("/isps/{id}", status_code=204, tags=["isps"])
|
||||
def delete_isp(id: int, db: Session = Depends(get_db), user: User = Depends(admin_user)):
|
||||
i = get_or_404(db, Isp, id, "Оператор")
|
||||
audit(db, user, "isp", i, "deleted", i.name)
|
||||
db.delete(i)
|
||||
commit(db)
|
||||
@@ -0,0 +1,15 @@
|
||||
from pydantic_settings import BaseSettings, SettingsConfigDict
|
||||
|
||||
|
||||
class Settings(BaseSettings):
|
||||
model_config = SettingsConfigDict(env_file=".env", extra="ignore")
|
||||
|
||||
database_url: str = "postgresql+psycopg://ipam:ipam@localhost:55432/ipam"
|
||||
jwt_secret: str = "dev-only-secret"
|
||||
jwt_ttl_minutes: int = 480
|
||||
admin_username: str = "admin"
|
||||
admin_password: str = ""
|
||||
trusted_proxies: str = "" # CIDR через запятую: от них принимается X-Forwarded-For
|
||||
|
||||
|
||||
settings = Settings()
|
||||
@@ -0,0 +1,12 @@
|
||||
from sqlalchemy import create_engine
|
||||
from sqlalchemy.orm import sessionmaker
|
||||
|
||||
from app.config import settings
|
||||
|
||||
engine = create_engine(settings.database_url, pool_pre_ping=True)
|
||||
SessionLocal = sessionmaker(engine, expire_on_commit=False)
|
||||
|
||||
|
||||
def get_db():
|
||||
with SessionLocal() as db:
|
||||
yield db
|
||||
+81
@@ -0,0 +1,81 @@
|
||||
import asyncio
|
||||
from contextlib import asynccontextmanager
|
||||
from pathlib import Path
|
||||
|
||||
from fastapi import APIRouter, FastAPI, HTTPException, Request
|
||||
from fastapi.exceptions import RequestValidationError
|
||||
from fastapi.responses import JSONResponse
|
||||
from fastapi.staticfiles import StaticFiles
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
|
||||
from app.api.v1 import auth, journal, overview, prefixes, refs
|
||||
from app.config import settings
|
||||
from app.db import SessionLocal
|
||||
from app.models import DeviceType, Role, User
|
||||
from app.request_context import RequestContextMiddleware
|
||||
from app.rotation import rotation_loop
|
||||
from app.security import hash_password
|
||||
|
||||
DEFAULT_TYPES = ["Сервер", "Сетевое оборудование", "Сетевое хранилище", "Рабочая станция", "Другое"]
|
||||
|
||||
|
||||
def seed():
|
||||
with SessionLocal() as db:
|
||||
if not db.scalar(select(User.id).limit(1)) and settings.admin_password:
|
||||
db.add(User(username=settings.admin_username, password_hash=hash_password(settings.admin_password), role=Role.admin))
|
||||
if not db.scalar(select(DeviceType.id).limit(1)):
|
||||
db.add_all(DeviceType(name=n, is_default=(n == "Другое")) for n in DEFAULT_TYPES)
|
||||
db.commit()
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(_: FastAPI):
|
||||
seed()
|
||||
task = asyncio.create_task(rotation_loop())
|
||||
yield
|
||||
task.cancel()
|
||||
|
||||
|
||||
app = FastAPI(title="IPAM Manager API", version="1.0.0", lifespan=lifespan)
|
||||
app.add_middleware(RequestContextMiddleware)
|
||||
|
||||
api = APIRouter(prefix="/api/v1")
|
||||
for r in (auth.router, overview.router, refs.router, prefixes.router, journal.router):
|
||||
api.include_router(r)
|
||||
app.include_router(api)
|
||||
|
||||
|
||||
@app.exception_handler(HTTPException)
|
||||
async def http_error(_: Request, exc: HTTPException):
|
||||
extra = exc.detail if isinstance(exc.detail, dict) else {"message": exc.detail} # dict — доп. поля (attempts_left и т.п.)
|
||||
return JSONResponse({"code": exc.status_code, "fields": {}, **extra}, status_code=exc.status_code, headers=exc.headers)
|
||||
|
||||
|
||||
@app.exception_handler(IntegrityError)
|
||||
async def integrity_error(_: Request, exc: IntegrityError): # страховка: нарушение ограничения БД не должно давать 500
|
||||
return JSONResponse({"code": 409, "message": "Конфликт с существующими данными", "fields": {}}, status_code=409)
|
||||
|
||||
|
||||
@app.exception_handler(RequestValidationError)
|
||||
async def validation_error(_: Request, exc: RequestValidationError):
|
||||
fields = {".".join(str(x) for x in e["loc"][1:]): e["msg"].removeprefix("Value error, ") for e in exc.errors()}
|
||||
return JSONResponse({"code": 422, "message": "Ошибка валидации", "fields": fields}, status_code=422)
|
||||
|
||||
|
||||
@app.get("/healthz", include_in_schema=False)
|
||||
def healthz():
|
||||
return {"status": "ok"}
|
||||
|
||||
|
||||
web = Path(__file__).resolve().parent.parent / "web"
|
||||
if web.is_dir():
|
||||
class RevalidatedStatic(StaticFiles):
|
||||
"""Статика с обязательной ревалидацией по ETag: браузер не держит устаревший UI после обновления."""
|
||||
|
||||
async def get_response(self, path, scope):
|
||||
response = await super().get_response(path, scope)
|
||||
response.headers["Cache-Control"] = "no-cache"
|
||||
return response
|
||||
|
||||
app.mount("/", RevalidatedStatic(directory=web, html=True), name="web")
|
||||
+169
@@ -0,0 +1,169 @@
|
||||
import enum
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
|
||||
from sqlalchemy import (
|
||||
BigInteger, Boolean, DateTime, Enum, ForeignKey, ForeignKeyConstraint, Index, Integer, String, Text,
|
||||
UniqueConstraint, func, text,
|
||||
)
|
||||
from sqlalchemy.dialects.postgresql import CIDR, INET, JSONB, UUID
|
||||
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column, relationship
|
||||
|
||||
|
||||
class Base(DeclarativeBase):
|
||||
pass
|
||||
|
||||
|
||||
class PrefixStatus(str, enum.Enum):
|
||||
active = "active"
|
||||
reserved = "reserved"
|
||||
deprecated = "deprecated"
|
||||
|
||||
|
||||
class AddressStatus(str, enum.Enum):
|
||||
assigned = "assigned"
|
||||
reserved = "reserved"
|
||||
deprecated = "deprecated"
|
||||
|
||||
|
||||
class Role(str, enum.Enum):
|
||||
admin = "admin"
|
||||
viewer = "viewer"
|
||||
|
||||
|
||||
class Organization(Base):
|
||||
__tablename__ = "organizations"
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
name: Mapped[str] = mapped_column(String(255), unique=True)
|
||||
short_name: Mapped[str] = mapped_column(String(100), default="")
|
||||
inn: Mapped[str] = mapped_column(String(12), unique=True)
|
||||
address: Mapped[str] = mapped_column(String(500), default="")
|
||||
contact_person: Mapped[str] = mapped_column(String(255), default="")
|
||||
phone: Mapped[str] = mapped_column(String(50), default="")
|
||||
email: Mapped[str] = mapped_column(String(255), default="")
|
||||
note: Mapped[str] = mapped_column(Text, default="")
|
||||
|
||||
|
||||
class Vrf(Base):
|
||||
__tablename__ = "vrfs"
|
||||
# (id, organization_id) — цель составного FK префиксов: VRF префикса всегда из его организации
|
||||
__table_args__ = (UniqueConstraint("id", "organization_id", name="uq_vrfs_id_organization_id"),)
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
organization_id: Mapped[int] = mapped_column(ForeignKey("organizations.id"))
|
||||
name: Mapped[str] = mapped_column(String(100))
|
||||
route_target: Mapped[str] = mapped_column(String(50), default="")
|
||||
note: Mapped[str] = mapped_column(Text, default="")
|
||||
|
||||
|
||||
Index("uq_vrfs_org_lower_name", Vrf.organization_id, func.lower(Vrf.name), unique=True) # имя VRF уникально в организации без учёта регистра
|
||||
|
||||
|
||||
class Prefix(Base):
|
||||
__tablename__ = "prefixes"
|
||||
__table_args__ = (
|
||||
UniqueConstraint("vrf_id", "prefix"),
|
||||
ForeignKeyConstraint(["vrf_id", "organization_id"], ["vrfs.id", "vrfs.organization_id"], name="fk_prefixes_vrf_org"),
|
||||
)
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
organization_id: Mapped[int] = mapped_column(ForeignKey("organizations.id"), index=True)
|
||||
vrf_id: Mapped[int] = mapped_column(ForeignKey("vrfs.id"), index=True)
|
||||
prefix: Mapped[str] = mapped_column(CIDR)
|
||||
description: Mapped[str] = mapped_column(String(500), default="")
|
||||
status: Mapped[PrefixStatus] = mapped_column(Enum(PrefixStatus, name="prefix_status"), default=PrefixStatus.active)
|
||||
parent_id: Mapped[int | None] = mapped_column(ForeignKey("prefixes.id", ondelete="SET NULL"))
|
||||
is_pool: Mapped[bool] = mapped_column(Boolean, default=False)
|
||||
note: Mapped[str] = mapped_column(Text, default="")
|
||||
|
||||
vrf: Mapped[Vrf] = relationship(primaryjoin="Prefix.vrf_id == Vrf.id", foreign_keys=[vrf_id])
|
||||
|
||||
|
||||
class Isp(Base):
|
||||
__tablename__ = "isps"
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
name: Mapped[str] = mapped_column(String(255))
|
||||
organization_id: Mapped[int] = mapped_column(ForeignKey("organizations.id"), index=True)
|
||||
contract_number: Mapped[str] = mapped_column(String(100), default="")
|
||||
hotline: Mapped[str] = mapped_column(String(50), default="")
|
||||
note: Mapped[str] = mapped_column(Text, default="")
|
||||
|
||||
networks: Mapped[list["IspNetwork"]] = relationship(cascade="all, delete-orphan", order_by="IspNetwork.id")
|
||||
|
||||
|
||||
class IspNetwork(Base):
|
||||
__tablename__ = "isp_networks"
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
isp_id: Mapped[int] = mapped_column(ForeignKey("isps.id", ondelete="CASCADE"), index=True)
|
||||
cidr: Mapped[str] = mapped_column(CIDR)
|
||||
|
||||
|
||||
class DeviceType(Base):
|
||||
__tablename__ = "device_types"
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
name: Mapped[str] = mapped_column(String(100), unique=True)
|
||||
is_default: Mapped[bool] = mapped_column(Boolean, default=False)
|
||||
|
||||
|
||||
class Device(Base):
|
||||
__tablename__ = "devices"
|
||||
__table_args__ = (UniqueConstraint("organization_id", "name"),)
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
name: Mapped[str] = mapped_column(String(255))
|
||||
device_type_id: Mapped[int] = mapped_column(ForeignKey("device_types.id"))
|
||||
organization_id: Mapped[int] = mapped_column(ForeignKey("organizations.id"), index=True)
|
||||
mac: Mapped[str] = mapped_column(String(17), default="")
|
||||
note: Mapped[str] = mapped_column(Text, default="")
|
||||
|
||||
|
||||
class Address(Base):
|
||||
__tablename__ = "addresses"
|
||||
__table_args__ = (UniqueConstraint("prefix_id", "address"),)
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
prefix_id: Mapped[int] = mapped_column(ForeignKey("prefixes.id", ondelete="CASCADE"), index=True)
|
||||
address: Mapped[str] = mapped_column(INET)
|
||||
status: Mapped[AddressStatus] = mapped_column(Enum(AddressStatus, name="address_status"), default=AddressStatus.assigned)
|
||||
dns_name: Mapped[str] = mapped_column(String(255), default="")
|
||||
description: Mapped[str] = mapped_column(String(500), default="")
|
||||
device_id: Mapped[int | None] = mapped_column(ForeignKey("devices.id", ondelete="SET NULL"), index=True)
|
||||
note: Mapped[str] = mapped_column(Text, default="")
|
||||
updated_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now(), onupdate=func.now())
|
||||
|
||||
|
||||
class User(Base):
|
||||
__tablename__ = "users"
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
username: Mapped[str] = mapped_column(String(100), unique=True)
|
||||
password_hash: Mapped[str] = mapped_column(String(255))
|
||||
role: Mapped[Role] = mapped_column(Enum(Role, name="user_role"), default=Role.admin)
|
||||
is_active: Mapped[bool] = mapped_column(Boolean, default=True)
|
||||
|
||||
|
||||
class AuditLog(Base):
|
||||
__tablename__ = "audit_log"
|
||||
id: Mapped[int] = mapped_column(BigInteger, primary_key=True)
|
||||
ts: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now(), index=True)
|
||||
username: Mapped[str] = mapped_column(String(100))
|
||||
entity_type: Mapped[str] = mapped_column(String(50), index=True)
|
||||
entity_id: Mapped[int | None] = mapped_column(Integer)
|
||||
entity_label: Mapped[str] = mapped_column(String(255))
|
||||
action: Mapped[str] = mapped_column(String(20))
|
||||
diff: Mapped[dict | None] = mapped_column(JSONB)
|
||||
uid: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), server_default=text("gen_random_uuid()"), unique=True)
|
||||
message: Mapped[str] = mapped_column(Text, default="", server_default="")
|
||||
client_ip: Mapped[str | None] = mapped_column(INET, index=True) # IP клиента запроса; NULL для системных событий
|
||||
meta: Mapped[dict | None] = mapped_column(JSONB) # user_agent, method, path, request_id
|
||||
|
||||
__table_args__ = (Index("ix_audit_log_entity_type_action", "entity_type", "action"),)
|
||||
|
||||
|
||||
class AppSetting(Base):
|
||||
__tablename__ = "app_settings"
|
||||
key: Mapped[str] = mapped_column(String(50), primary_key=True)
|
||||
value: Mapped[dict] = mapped_column(JSONB)
|
||||
|
||||
|
||||
class ClearAttempt(Base):
|
||||
"""Неудачные попытки подтверждения пароля при очистке журнала (для блокировки)."""
|
||||
__tablename__ = "clear_attempts"
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
user_id: Mapped[int] = mapped_column(ForeignKey("users.id", ondelete="CASCADE"), index=True)
|
||||
ts: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
|
||||
@@ -0,0 +1,74 @@
|
||||
"""Контекст HTTP-запроса для журнала аудита: IP клиента, User-Agent, метод, путь, request_id."""
|
||||
import ipaddress
|
||||
import uuid
|
||||
from contextvars import ContextVar
|
||||
|
||||
from app.config import settings
|
||||
|
||||
request_meta: ContextVar[dict | None] = ContextVar("request_meta", default=None)
|
||||
|
||||
|
||||
def _parse(value: str):
|
||||
try:
|
||||
ip = ipaddress.ip_address(value.strip())
|
||||
except ValueError:
|
||||
return None
|
||||
return ip.ipv4_mapped if getattr(ip, "ipv4_mapped", None) else ip # ::ffff:a.b.c.d -> a.b.c.d
|
||||
|
||||
|
||||
def parse_networks(raw: str) -> list:
|
||||
nets = []
|
||||
for item in raw.split(","):
|
||||
if item.strip():
|
||||
nets.append(ipaddress.ip_network(item.strip(), strict=False))
|
||||
return nets
|
||||
|
||||
|
||||
def resolve_client_ip(peer: str | None, x_forwarded_for: str | None, trusted: list) -> str | None:
|
||||
"""IP клиента. X-Forwarded-For учитывается только от доверенного пира (иначе заголовок можно подделать):
|
||||
идём по цепочке справа налево и берём первый адрес, не принадлежащий доверенным прокси."""
|
||||
peer_ip = _parse(peer) if peer else None
|
||||
if peer_ip is None:
|
||||
return None
|
||||
is_trusted = lambda ip: any(ip in net for net in trusted) # noqa: E731
|
||||
if not x_forwarded_for or not is_trusted(peer_ip):
|
||||
return str(peer_ip)
|
||||
for part in reversed([p for p in x_forwarded_for.split(",") if p.strip()]):
|
||||
ip = _parse(part)
|
||||
if ip is None:
|
||||
return str(peer_ip) # мусор в заголовке — доверяем только сокету
|
||||
if not is_trusted(ip):
|
||||
return str(ip)
|
||||
return str(peer_ip)
|
||||
|
||||
|
||||
class RequestContextMiddleware:
|
||||
"""ASGI-middleware: кладёт метаданные запроса в ContextVar и возвращает X-Request-ID."""
|
||||
|
||||
def __init__(self, app):
|
||||
self.app = app
|
||||
self.trusted = parse_networks(settings.trusted_proxies)
|
||||
|
||||
async def __call__(self, scope, receive, send):
|
||||
if scope["type"] != "http":
|
||||
return await self.app(scope, receive, send)
|
||||
headers = {k.decode("latin-1").lower(): v.decode("latin-1") for k, v in scope["headers"]}
|
||||
request_id = uuid.uuid4().hex[:12]
|
||||
peer = scope["client"][0] if scope.get("client") else None
|
||||
token = request_meta.set({
|
||||
"client_ip": resolve_client_ip(peer, headers.get("x-forwarded-for"), self.trusted),
|
||||
"meta": {
|
||||
"user_agent": headers.get("user-agent", "")[:255], "method": scope["method"],
|
||||
"path": scope["path"], "request_id": request_id, # только путь — без query-строки
|
||||
},
|
||||
})
|
||||
|
||||
async def send_with_id(message):
|
||||
if message["type"] == "http.response.start":
|
||||
message["headers"] = [*message.get("headers", []), (b"x-request-id", request_id.encode())]
|
||||
await send(message)
|
||||
|
||||
try:
|
||||
await self.app(scope, receive, send_with_id)
|
||||
finally:
|
||||
request_meta.reset(token)
|
||||
@@ -0,0 +1,74 @@
|
||||
"""Настройки и ротация журнала: удаление записей старше срока и самых старых сверх лимита."""
|
||||
import asyncio
|
||||
import logging
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
from sqlalchemy import delete, func, select
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.db import SessionLocal
|
||||
from app.models import AppSetting, AuditLog
|
||||
from app.services import SYSTEM, audit
|
||||
|
||||
log = logging.getLogger("ipam.rotation")
|
||||
DEFAULTS = {"retention_days": 90, "max_entries": 100_000}
|
||||
LOCK_KEY = 703001 # advisory lock: одна ротация за раз, даже при нескольких репликах
|
||||
INTERVAL_SECONDS = 3600
|
||||
|
||||
|
||||
def get_settings(db: Session) -> dict:
|
||||
row = db.get(AppSetting, "journal")
|
||||
return {**DEFAULTS, **(row.value if row else {})}
|
||||
|
||||
|
||||
def save_settings(db: Session, values: dict) -> None:
|
||||
row = db.get(AppSetting, "journal")
|
||||
if row is None:
|
||||
db.add(AppSetting(key="journal", value=values))
|
||||
else:
|
||||
row.value = values
|
||||
|
||||
|
||||
def rotate(db: Session) -> dict | None:
|
||||
"""Возвращает {'by_age', 'by_count'} или None, если ротацию уже выполняет другой процесс."""
|
||||
if not db.scalar(select(func.pg_try_advisory_xact_lock(LOCK_KEY))):
|
||||
db.rollback()
|
||||
return None
|
||||
cfg = get_settings(db)
|
||||
by_age = by_count = 0
|
||||
if cfg["retention_days"] > 0:
|
||||
cutoff = datetime.now(timezone.utc) - timedelta(days=cfg["retention_days"])
|
||||
by_age = db.execute(delete(AuditLog).where(AuditLog.ts < cutoff)).rowcount
|
||||
if cfg["max_entries"] > 0:
|
||||
total = db.scalar(select(func.count()).select_from(AuditLog)) or 0
|
||||
if total > cfg["max_entries"]:
|
||||
# удаляем с запасом в одну запись — под сводную запись о ротации, чтобы итог не превышал лимит
|
||||
n = total - cfg["max_entries"] + 1
|
||||
by_count = db.execute(delete(AuditLog).where(AuditLog.id.in_(select(AuditLog.id).order_by(AuditLog.id).limit(n)))).rowcount
|
||||
if by_age or by_count:
|
||||
parts = []
|
||||
if by_age:
|
||||
parts.append(f"старше {cfg['retention_days']} дн.: {by_age}")
|
||||
if by_count:
|
||||
parts.append(f"сверх лимита {cfg['max_entries']}: {by_count}")
|
||||
audit(db, SYSTEM, "journal", None, "rotated", "rotation", {"by_age": by_age, "by_count": by_count},
|
||||
message="Ротация журнала: удалено " + "; ".join(parts))
|
||||
db.commit()
|
||||
return {"by_age": by_age, "by_count": by_count}
|
||||
|
||||
|
||||
def run_rotation() -> None:
|
||||
try:
|
||||
with SessionLocal() as db:
|
||||
result = rotate(db)
|
||||
if result and (result["by_age"] or result["by_count"]):
|
||||
log.info("journal rotated: %s", result)
|
||||
except Exception: # фоновая задача не должна падать
|
||||
log.exception("journal rotation failed")
|
||||
|
||||
|
||||
async def rotation_loop() -> None:
|
||||
await asyncio.sleep(30)
|
||||
while True:
|
||||
await asyncio.to_thread(run_rotation)
|
||||
await asyncio.sleep(INTERVAL_SECONDS)
|
||||
+301
@@ -0,0 +1,301 @@
|
||||
import ipaddress
|
||||
import re
|
||||
from datetime import datetime
|
||||
from typing import Annotated, Generic, TypeVar
|
||||
|
||||
from pydantic import AfterValidator, BaseModel, ConfigDict, EmailStr, Field, field_validator
|
||||
|
||||
from app.models import AddressStatus, PrefixStatus
|
||||
|
||||
T = TypeVar("T")
|
||||
|
||||
|
||||
def _cidr(v: str) -> str:
|
||||
try:
|
||||
return str(ipaddress.ip_network(v.strip(), strict=True))
|
||||
except ValueError:
|
||||
raise ValueError("Некорректный CIDR (пример: 10.30.0.0/24, биты хоста должны быть нулевыми)")
|
||||
|
||||
|
||||
def _ip(v: str) -> str:
|
||||
try:
|
||||
return str(ipaddress.ip_address(v.strip()))
|
||||
except ValueError:
|
||||
raise ValueError("Некорректный IP-адрес")
|
||||
|
||||
|
||||
Cidr = Annotated[str, AfterValidator(_cidr)]
|
||||
IpAddr = Annotated[str, AfterValidator(_ip)]
|
||||
_FQDN = re.compile(r"^(?=.{1,253}$)([A-Za-z0-9_]([A-Za-z0-9_-]{0,61}[A-Za-z0-9_])?)(\.[A-Za-z0-9_]([A-Za-z0-9_-]{0,61}[A-Za-z0-9_])?)*$")
|
||||
_MAC = re.compile(r"^([0-9A-Fa-f]{2}[:-]){5}[0-9A-Fa-f]{2}$")
|
||||
|
||||
|
||||
class Page(BaseModel, Generic[T]):
|
||||
items: list[T]
|
||||
total: int
|
||||
|
||||
|
||||
class ORM(BaseModel):
|
||||
model_config = ConfigDict(from_attributes=True)
|
||||
|
||||
|
||||
# --- auth
|
||||
class LoginIn(BaseModel):
|
||||
username: str
|
||||
password: str
|
||||
|
||||
|
||||
class TokenOut(BaseModel):
|
||||
access_token: str
|
||||
token_type: str = "bearer"
|
||||
|
||||
|
||||
class UserOut(ORM):
|
||||
username: str
|
||||
role: str
|
||||
|
||||
|
||||
# --- organizations
|
||||
class OrgIn(BaseModel):
|
||||
name: str = Field(min_length=1, max_length=255)
|
||||
short_name: str = Field("", max_length=100)
|
||||
inn: str = Field(pattern=r"^(\d{10}|\d{12})$")
|
||||
address: str = Field("", max_length=500)
|
||||
contact_person: str = ""
|
||||
phone: str = ""
|
||||
email: EmailStr | str = ""
|
||||
note: str = ""
|
||||
|
||||
@field_validator("email")
|
||||
@classmethod
|
||||
def _email(cls, v):
|
||||
return str(v)
|
||||
|
||||
|
||||
class OrgOut(ORM, OrgIn):
|
||||
id: int
|
||||
prefixes_count: int = 0
|
||||
addresses_count: int = 0
|
||||
|
||||
|
||||
# --- vrf
|
||||
class VrfIn(BaseModel):
|
||||
organization_id: int
|
||||
name: str = Field(min_length=1, max_length=100)
|
||||
route_target: str = Field("", max_length=50, pattern=r"^(\d+:\d+)?$")
|
||||
note: str = ""
|
||||
|
||||
|
||||
class VrfUpdate(BaseModel):
|
||||
name: str | None = Field(None, min_length=1, max_length=100)
|
||||
route_target: str | None = Field(None, max_length=50, pattern=r"^(\d+:\d+)?$")
|
||||
note: str | None = None
|
||||
|
||||
|
||||
class VrfOut(ORM):
|
||||
id: int
|
||||
organization_id: int
|
||||
name: str
|
||||
route_target: str
|
||||
note: str
|
||||
prefixes_count: int = 0
|
||||
|
||||
|
||||
# --- device types / devices
|
||||
class DeviceTypeIn(BaseModel):
|
||||
name: str = Field(min_length=1, max_length=100)
|
||||
|
||||
|
||||
class DeviceTypeOut(ORM):
|
||||
id: int
|
||||
name: str
|
||||
is_default: bool
|
||||
devices_count: int = 0
|
||||
|
||||
|
||||
class DeviceIn(BaseModel):
|
||||
name: str = Field(min_length=1, max_length=255)
|
||||
device_type_id: int
|
||||
organization_id: int
|
||||
mac: str = ""
|
||||
note: str = ""
|
||||
|
||||
@field_validator("name")
|
||||
@classmethod
|
||||
def _name(cls, v):
|
||||
if not _FQDN.match(v):
|
||||
raise ValueError("Некорректное имя устройства (hostname)")
|
||||
return v
|
||||
|
||||
@field_validator("mac")
|
||||
@classmethod
|
||||
def _mac(cls, v):
|
||||
if v and not _MAC.match(v):
|
||||
raise ValueError("Некорректный MAC-адрес (AA:BB:CC:DD:EE:FF)")
|
||||
return v.upper().replace("-", ":")
|
||||
|
||||
|
||||
class DeviceUpdate(BaseModel):
|
||||
name: str | None = None
|
||||
device_type_id: int | None = None
|
||||
mac: str | None = None
|
||||
note: str | None = None
|
||||
|
||||
|
||||
class DeviceOut(ORM):
|
||||
id: int
|
||||
name: str
|
||||
device_type_id: int
|
||||
device_type_name: str
|
||||
organization_id: int
|
||||
mac: str
|
||||
note: str
|
||||
ip_addresses: list[str] = []
|
||||
first_prefix_id: int | None = None
|
||||
all_deprecated: bool = False
|
||||
|
||||
|
||||
# --- isp
|
||||
class IspIn(BaseModel):
|
||||
name: str = Field(min_length=1, max_length=255)
|
||||
organization_id: int
|
||||
networks: list[Cidr] = []
|
||||
hotline: str = Field("", max_length=50)
|
||||
contract_number: str = Field("", max_length=100)
|
||||
note: str = ""
|
||||
|
||||
|
||||
class IspOut(ORM):
|
||||
id: int
|
||||
name: str
|
||||
organization_id: int
|
||||
organization_name: str
|
||||
networks: list[str]
|
||||
hotline: str
|
||||
contract_number: str
|
||||
note: str
|
||||
|
||||
|
||||
# --- prefixes
|
||||
class PrefixIn(BaseModel):
|
||||
organization_id: int
|
||||
vrf_id: int
|
||||
prefix: Cidr
|
||||
description: str = Field("", max_length=500)
|
||||
status: PrefixStatus = PrefixStatus.active
|
||||
parent_id: int | None = None
|
||||
is_pool: bool = False
|
||||
note: str = ""
|
||||
|
||||
|
||||
class PrefixUpdate(BaseModel):
|
||||
vrf_id: int | None = None
|
||||
description: str | None = Field(None, max_length=500)
|
||||
status: PrefixStatus | None = None
|
||||
is_pool: bool | None = None
|
||||
note: str | None = None
|
||||
|
||||
|
||||
class PrefixOut(ORM):
|
||||
id: int
|
||||
organization_id: int
|
||||
vrf_id: int
|
||||
vrf_name: str
|
||||
prefix: str
|
||||
family: int
|
||||
description: str
|
||||
status: PrefixStatus
|
||||
parent_id: int | None
|
||||
depth: int
|
||||
is_pool: bool
|
||||
note: str
|
||||
used: int
|
||||
capacity: int
|
||||
utilization: int
|
||||
addresses_count: int
|
||||
|
||||
|
||||
# --- addresses
|
||||
class AddressIn(BaseModel):
|
||||
address: IpAddr
|
||||
status: AddressStatus = AddressStatus.assigned
|
||||
dns_name: str = ""
|
||||
description: str = Field("", max_length=500)
|
||||
device_id: int | None = None
|
||||
note: str = ""
|
||||
|
||||
@field_validator("dns_name")
|
||||
@classmethod
|
||||
def _dns(cls, v):
|
||||
if v and not _FQDN.match(v):
|
||||
raise ValueError("Некорректное DNS-имя (FQDN)")
|
||||
return v
|
||||
|
||||
|
||||
class AddressUpdate(BaseModel):
|
||||
status: AddressStatus | None = None
|
||||
dns_name: str | None = None
|
||||
description: str | None = Field(None, max_length=500)
|
||||
device_id: int | None = None
|
||||
note: str | None = None
|
||||
|
||||
|
||||
class AddressOut(BaseModel):
|
||||
id: int | None
|
||||
prefix_id: int
|
||||
address: str
|
||||
status: str # assigned | reserved | deprecated | free
|
||||
dns_name: str = ""
|
||||
description: str = ""
|
||||
device_id: int | None = None
|
||||
device_name: str | None = None
|
||||
note: str = ""
|
||||
updated_at: datetime | None = None
|
||||
|
||||
|
||||
class AddressSummary(BaseModel):
|
||||
assigned: int
|
||||
reserved: int
|
||||
deprecated: int
|
||||
free: int
|
||||
capacity: int
|
||||
|
||||
|
||||
class AddressPage(Page[AddressOut]):
|
||||
summary: AddressSummary
|
||||
|
||||
|
||||
class AuditOut(ORM):
|
||||
id: int
|
||||
uid: str
|
||||
short_id: str
|
||||
ts: datetime
|
||||
username: str
|
||||
actor: str
|
||||
entity_type: str
|
||||
entity_id: int | None
|
||||
entity_label: str
|
||||
action: str
|
||||
event_type: str
|
||||
message: str
|
||||
diff: dict | None
|
||||
client_ip: str | None = None
|
||||
meta: dict | None = None
|
||||
|
||||
@classmethod
|
||||
def from_row(cls, r) -> "AuditOut":
|
||||
return cls(
|
||||
id=r.id, uid=str(r.uid), short_id=str(r.uid)[:8], ts=r.ts, username=r.username,
|
||||
actor=r.username if r.username in ("system", "anonymous") else f"ui:{r.username}",
|
||||
entity_type=r.entity_type, entity_id=r.entity_id, entity_label=r.entity_label, action=r.action,
|
||||
event_type=f"{r.entity_type}.{r.action}", message=r.message, diff=r.diff,
|
||||
client_ip=ip_text(r.client_ip) if r.client_ip is not None else None, meta=r.meta,
|
||||
)
|
||||
|
||||
|
||||
def ip_text(v) -> str:
|
||||
"""psycopg отдаёт inet/cidr объектами ipaddress; для хоста убираем /32 и /128."""
|
||||
text = str(v)
|
||||
if text.endswith("/32") or text.endswith("/128"):
|
||||
return text.rsplit("/", 1)[0]
|
||||
return text
|
||||
@@ -0,0 +1,53 @@
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
import jwt
|
||||
from argon2 import PasswordHasher
|
||||
from argon2.exceptions import VerifyMismatchError
|
||||
from fastapi import Depends, HTTPException
|
||||
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.config import settings
|
||||
from app.db import get_db
|
||||
from app.models import Role, User
|
||||
|
||||
_ph = PasswordHasher()
|
||||
_bearer = HTTPBearer(auto_error=False)
|
||||
|
||||
|
||||
def hash_password(password: str) -> str:
|
||||
return _ph.hash(password)
|
||||
|
||||
|
||||
def verify_password(password: str, hashed: str) -> bool:
|
||||
try:
|
||||
return _ph.verify(hashed, password)
|
||||
except VerifyMismatchError:
|
||||
return False
|
||||
|
||||
|
||||
def create_token(user: User) -> str:
|
||||
exp = datetime.now(timezone.utc) + timedelta(minutes=settings.jwt_ttl_minutes)
|
||||
return jwt.encode({"sub": user.username, "exp": exp}, settings.jwt_secret, algorithm="HS256")
|
||||
|
||||
|
||||
def current_user(
|
||||
cred: HTTPAuthorizationCredentials | None = Depends(_bearer), db: Session = Depends(get_db)
|
||||
) -> User:
|
||||
if cred is None:
|
||||
raise HTTPException(401, "Требуется авторизация")
|
||||
try:
|
||||
username = jwt.decode(cred.credentials, settings.jwt_secret, algorithms=["HS256"])["sub"]
|
||||
except jwt.PyJWTError:
|
||||
raise HTTPException(401, "Недействительный токен")
|
||||
user = db.scalar(select(User).where(User.username == username, User.is_active))
|
||||
if user is None:
|
||||
raise HTTPException(401, "Пользователь не найден")
|
||||
return user
|
||||
|
||||
|
||||
def admin_user(user: User = Depends(current_user)) -> User:
|
||||
if user.role != Role.admin:
|
||||
raise HTTPException(403, "Недостаточно прав")
|
||||
return user
|
||||
+107
@@ -0,0 +1,107 @@
|
||||
import ipaddress
|
||||
from types import SimpleNamespace
|
||||
|
||||
from fastapi import HTTPException
|
||||
from sqlalchemy import func, select
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.request_context import request_meta
|
||||
from app.models import Address, AuditLog, Base
|
||||
|
||||
MAX_CAPACITY = 2**53 - 1
|
||||
|
||||
|
||||
SYSTEM = SimpleNamespace(username="system")
|
||||
ANONYMOUS = SimpleNamespace(username="anonymous")
|
||||
_NOUNS = {
|
||||
"organization": ("Организация", "f"), "vrf": ("VRF", "m"), "prefix": ("Префикс", "m"), "address": ("Адрес", "m"),
|
||||
"device": ("Устройство", "n"), "device_type": ("Тип устройства", "m"), "isp": ("Оператор", "m"),
|
||||
}
|
||||
_VERBS = {
|
||||
"created": ("создан", "создана", "создано"), "updated": ("изменён", "изменена", "изменено"),
|
||||
"deleted": ("удалён", "удалена", "удалено"), "assigned": ("назначен", "назначена", "назначено"),
|
||||
}
|
||||
|
||||
|
||||
def make_message(entity_type: str, action: str, label: str, diff: dict | None = None) -> str:
|
||||
noun, gender = _NOUNS.get(entity_type, (entity_type, "m"))
|
||||
verb = _VERBS.get(action, (action,) * 3)["mfn".index(gender)]
|
||||
text = f"{noun} {label} {verb}"
|
||||
if action == "updated" and diff:
|
||||
text += ": " + ", ".join(diff)
|
||||
return text
|
||||
|
||||
|
||||
def actor_of(username: str) -> str:
|
||||
"""Актор для журнала: служебные — как есть, пользователи UI — с префиксом ui:."""
|
||||
return username if username in ("system", "anonymous") else f"ui:{username}"
|
||||
|
||||
|
||||
def audit(db: Session, user, entity_type: str, entity, action: str, label: str, diff: dict | None = None, message: str | None = None):
|
||||
ctx = None if user is SYSTEM else request_meta.get() # системные события (ротация) — без IP, даже если запущены из запроса
|
||||
db.add(AuditLog(
|
||||
username=user.username, entity_type=entity_type, entity_id=getattr(entity, "id", None),
|
||||
entity_label=label, action=action, diff=diff,
|
||||
message=message or make_message(entity_type, action, label, diff),
|
||||
client_ip=ctx["client_ip"] if ctx else None, meta=ctx["meta"] if ctx else None,
|
||||
))
|
||||
|
||||
|
||||
def commit(db: Session, conflict_msg: str = "Запись с такими значениями уже существует"):
|
||||
try:
|
||||
db.commit()
|
||||
except IntegrityError:
|
||||
db.rollback()
|
||||
raise HTTPException(409, conflict_msg)
|
||||
|
||||
|
||||
def flush(db: Session, conflict_msg: str = "Запись с такими значениями уже существует"):
|
||||
"""flush с тем же переводом нарушений уникальности в 409, что и commit."""
|
||||
try:
|
||||
db.flush()
|
||||
except IntegrityError:
|
||||
db.rollback()
|
||||
raise HTTPException(409, conflict_msg)
|
||||
|
||||
|
||||
def get_or_404(db: Session, model: type[Base], id_: int, what: str = "Объект"):
|
||||
obj = db.get(model, id_)
|
||||
if obj is None:
|
||||
raise HTTPException(404, f"{what} не найден")
|
||||
return obj
|
||||
|
||||
|
||||
def capacity(prefix: str) -> int:
|
||||
net = ipaddress.ip_network(prefix)
|
||||
n = net.num_addresses
|
||||
if net.version == 4 and net.prefixlen <= 30:
|
||||
n -= 2 # сеть и broadcast
|
||||
return min(n, MAX_CAPACITY)
|
||||
|
||||
|
||||
def utilization(used: int, cap: int) -> int:
|
||||
return round(used * 100 / cap) if cap else 0
|
||||
|
||||
|
||||
def apply_update(obj, data: dict) -> dict:
|
||||
changed = {}
|
||||
for k, v in data.items():
|
||||
if getattr(obj, k) != v:
|
||||
changed[k] = v
|
||||
setattr(obj, k, v)
|
||||
return changed
|
||||
|
||||
|
||||
def count(db: Session, stmt) -> int:
|
||||
return db.scalar(select(func.count()).select_from(stmt.subquery())) or 0
|
||||
|
||||
|
||||
def next_free(db: Session, prefix_id: int, prefix: str) -> str | None:
|
||||
net = ipaddress.ip_network(prefix)
|
||||
used = {ipaddress.ip_address(a) for a in db.scalars(select(Address.address).where(Address.prefix_id == prefix_id))}
|
||||
hosts = net.hosts() if net.version == 4 and net.prefixlen <= 30 else iter(net)
|
||||
for ip in hosts:
|
||||
if ip not in used:
|
||||
return str(ip)
|
||||
return None
|
||||
Reference in new issue
Block a user