Catalyst / admin/Syanpse-Vanguard 14.8 GB / 57.8 GB 40.0 GB free
Help Sign in

admin / Syanpse-Vanguard

public
Code Issues Pull requests Pipelines Packages Security Insights Wiki Settings
Syanpse-Vanguard / synapse-vanguard-v3 / sv / api.py 20998 B · main
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
"""Control-plane + query API (the UI backend). Every route is RBAC-guarded.

Milestone-3 surface:
  GET  /                         -> IronNode web dashboard (self-contained)
  POST /v1/auth/login            -> JWT
  POST /v1/search                -> query events (LOG_READ)
  GET  /v1/agents                -> list agents (AGENT_MANAGE)
  POST /v1/agents/{id}/revoke    -> revoke an agent (AGENT_MANAGE)
"""
from __future__ import annotations

from contextlib import asynccontextmanager
from importlib import resources

from fastapi import APIRouter, Depends, FastAPI, HTTPException, Request, status
from fastapi.responses import FileResponse, HTMLResponse
from pydantic import BaseModel

from sv.auth.deps import requires
from sv.auth.rbac import Permission, Role
from sv.auth.session import User, current_user, issue_token
from sv.auth.users import (count_admins, create_user, get_user_by_id,
                           get_user_by_username, list_users, set_disabled,
                           set_password, set_role, verify_password)
from sv.config import settings
from sv.bootstrap import shutdown, startup
from sv.ingest import registry
from sv.query.builder import SearchRequest, build_search
from sv.query.guard import guard_search
from sv.storage.base import Query


@asynccontextmanager
async def lifespan(app: FastAPI):
    from sv.metrics import EpsMeter
    engine, _ = await startup(with_broker=False)
    app.state.engine = engine
    app.state.eps_meter = EpsMeter()  # standalone API has no ingest; stays at 0
    try:
        yield
    finally:
        await shutdown(engine, None)


# Routes live on a router so they can be served standalone (this module's `app`)
# or mounted into the consolidated single-process app (sv.main).
router = APIRouter()

_DASHBOARD_HTML = resources.files("sv.web").joinpath("index.html").read_text(encoding="utf-8")
_ASSETS_DIR = resources.files("sv.web").joinpath("assets")

_ASSET_TYPES = {".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg",
                ".svg": "image/svg+xml", ".webp": "image/webp", ".ico": "image/x-icon"}


@router.get("/", response_class=HTMLResponse, include_in_schema=False)
async def dashboard() -> str:
    """Serve the self-contained IronNode dashboard (same-origin with the API, so
    no CORS needed and no external asset fetches — data-sovereign by default)."""
    return _DASHBOARD_HTML


@router.get("/assets/{name}", include_in_schema=False)
async def asset(name: str):
    """Serve branding assets (logo, favicon) from sv/web/assets. Filename-only —
    no path separators — so this cannot traverse outside the assets directory."""
    if "/" in name or "\\" in name or name.startswith("."):
        raise HTTPException(status.HTTP_400_BAD_REQUEST, "invalid asset name")
    import os
    ext = os.path.splitext(name)[1].lower()
    if ext not in _ASSET_TYPES:
        raise HTTPException(status.HTTP_404_NOT_FOUND, "not found")
    path = _ASSETS_DIR.joinpath(name)
    if not path.is_file():
        raise HTTPException(status.HTTP_404_NOT_FOUND, "not found")
    return FileResponse(str(path), media_type=_ASSET_TYPES[ext])


class LoginRequest(BaseModel):
    username: str
    password: str


class LoginResponse(BaseModel):
    access_token: str
    token_type: str = "bearer"
    role: str


@router.post("/v1/auth/login", response_model=LoginResponse)
async def login(body: LoginRequest, request: Request) -> LoginResponse:
    engine = request.app.state.engine
    row = await get_user_by_username(engine, body.username)
    if not row or row["disabled"] or not verify_password(body.password, row["password_hash"]):
        raise HTTPException(status.HTTP_401_UNAUTHORIZED, "invalid credentials")
    role = Role(row["role"])
    from uuid import UUID
    token = issue_token(row["id"], row["username"], role, UUID(row["tenant_id"]))
    return LoginResponse(access_token=token, role=role.value)


@router.post("/v1/search")
async def search(
    body: SearchRequest,
    request: Request,
    user: User = Depends(requires(Permission.LOG_READ)),
) -> dict:
    guard_search(user)                                  # defense in depth
    try:
        query = build_search(body, user.tenant_id)      # tenant isolation enforced here
    except ValueError as exc:
        raise HTTPException(status.HTTP_400_BAD_REQUEST, str(exc))
    table = await request.app.state.engine.execute(query)
    return {"count": table.num_rows, "rows": table.to_pylist()}


@router.get("/v1/agents")
async def list_agents(
    request: Request,
    user: User = Depends(requires(Permission.AGENT_MANAGE)),
) -> dict:
    rows = await request.app.state.engine.fetchall(Query(
        "SELECT id, hostname, platform, agent_version, last_ip, last_seq, revoked, "
        "enrolled_ts, last_seen_ts FROM agents WHERE tenant_id = ? ORDER BY hostname",
        [str(user.tenant_id)],
    ))
    return {"agents": rows}


@router.get("/v1/metrics")
async def metrics(request: Request, user: User = Depends(current_user)) -> dict:
    """Ingest receive-rate (events/sec) + totals for the dashboard header."""
    meter = getattr(request.app.state, "eps_meter", None)
    row = await request.app.state.engine.fetchone(Query(
        "SELECT COUNT(*) AS n FROM events WHERE tenant_id = ?",
        [str(user.tenant_id)],
    ))
    return {
        "eps": round(meter.eps(), 2) if meter else 0.0,
        "received_total": meter.total if meter else 0,
        "events_stored": (row["n"] if row else 0),
        "window_s": meter.window_s if meter else 0,
    }


# ============================ Admin menu APIs ==============================
# All guarded by TENANT_ADMIN-only permissions (USER_MANAGE / SYSTEM_CONFIG /
# AGENT_MANAGE), which only the admin role holds.

class CreateUserReq(BaseModel):
    username: str
    password: str
    role: str


class StatusReq(BaseModel):
    disabled: bool


class RoleReq(BaseModel):
    role: str


class PasswordReq(BaseModel):
    password: str


def _role_or_400(value: str) -> Role:
    try:
        return Role(value)
    except ValueError:
        raise HTTPException(status.HTTP_400_BAD_REQUEST, f"invalid role: {value}")


# ---- Users ----------------------------------------------------------------
@router.get("/v1/admin/users")
async def admin_list_users(request: Request,
                           user: User = Depends(requires(Permission.USER_MANAGE))) -> dict:
    return {"users": await list_users(request.app.state.engine, user.tenant_id)}


@router.post("/v1/admin/users")
async def admin_create_user(body: CreateUserReq, request: Request,
                            user: User = Depends(requires(Permission.USER_MANAGE))) -> dict:
    role = _role_or_400(body.role)
    if len(body.password) < 8:
        raise HTTPException(status.HTTP_400_BAD_REQUEST, "password must be at least 8 characters")
    if await get_user_by_username(request.app.state.engine, body.username):
        raise HTTPException(status.HTTP_409_CONFLICT, "username already exists")
    uid = await create_user(request.app.state.engine, body.username, body.password,
                            role, user.tenant_id)
    return {"id": uid}


@router.post("/v1/admin/users/{uid}/status")
async def admin_user_status(uid: str, body: StatusReq, request: Request,
                            user: User = Depends(requires(Permission.USER_MANAGE))) -> dict:
    if uid == user.id and body.disabled:
        raise HTTPException(status.HTTP_400_BAD_REQUEST, "you cannot disable your own account")
    engine = request.app.state.engine
    target = await get_user_by_id(engine, uid)
    if not target:
        raise HTTPException(status.HTTP_404_NOT_FOUND, "user not found")
    if body.disabled and target["role"] == Role.TENANT_ADMIN.value \
            and await count_admins(engine, user.tenant_id) <= 1:
        raise HTTPException(status.HTTP_400_BAD_REQUEST, "cannot disable the last admin")
    await set_disabled(engine, uid, body.disabled)
    return {"id": uid, "disabled": body.disabled}


@router.post("/v1/admin/users/{uid}/role")
async def admin_user_role(uid: str, body: RoleReq, request: Request,
                          user: User = Depends(requires(Permission.USER_MANAGE))) -> dict:
    role = _role_or_400(body.role)
    if uid == user.id:
        raise HTTPException(status.HTTP_400_BAD_REQUEST, "you cannot change your own role")
    engine = request.app.state.engine
    target = await get_user_by_id(engine, uid)
    if not target:
        raise HTTPException(status.HTTP_404_NOT_FOUND, "user not found")
    if target["role"] == Role.TENANT_ADMIN.value and role != Role.TENANT_ADMIN \
            and await count_admins(engine, user.tenant_id) <= 1:
        raise HTTPException(status.HTTP_400_BAD_REQUEST, "cannot demote the last admin")
    await set_role(engine, uid, role)
    return {"id": uid, "role": role.value}


@router.post("/v1/admin/users/{uid}/password")
async def admin_user_password(uid: str, body: PasswordReq, request: Request,
                              user: User = Depends(requires(Permission.USER_MANAGE))) -> dict:
    if len(body.password) < 8:
        raise HTTPException(status.HTTP_400_BAD_REQUEST, "password must be at least 8 characters")
    await set_password(request.app.state.engine, uid, body.password)
    return {"id": uid, "reset": True}


# ---- Agent management (enrollment info) -----------------------------------
@router.get("/v1/admin/enrollment")
async def admin_enrollment(user: User = Depends(requires(Permission.AGENT_MANAGE))) -> dict:
    return {
        "enrollment_token": settings.enrollment_token,
        "mtls_enabled": settings.mtls_enabled,
        "hint": "Give this token + the server URL to a new agent. It is one-time; "
                "each agent stores its own ingest token after enrolling.",
    }


# ---- Ingress API key (for external Synapse apps, e.g. IronNode) ------------
def _events_url(request: Request) -> str:
    base = str(request.base_url).rstrip("/")
    return f"{base}/v1/ingest/events"


@router.get("/v1/admin/ingress-key")
async def admin_ingress_get(request: Request,
                            user: User = Depends(requires(Permission.INTEGRATION_WRITE))) -> dict:
    from sv import ingress
    cfg = await ingress.get_config(request.app.state.engine, user.tenant_id)
    return {
        "configured": cfg is not None,
        "enabled": cfg["enabled"] if cfg else False,
        "api_key": cfg["api_key"] if cfg else None,   # full key for admin copy-out
        "url": _events_url(request),
    }


@router.post("/v1/admin/ingress-key/generate")
async def admin_ingress_generate(request: Request,
                                 user: User = Depends(requires(Permission.INTEGRATION_WRITE))) -> dict:
    from sv import ingress
    key = await ingress.generate(request.app.state.engine, user.tenant_id)
    return {"api_key": key, "enabled": True, "url": _events_url(request)}


@router.post("/v1/admin/ingress-key/toggle")
async def admin_ingress_toggle(body: StatusReq, request: Request,
                               user: User = Depends(requires(Permission.INTEGRATION_WRITE))) -> dict:
    from sv import ingress
    ok = await ingress.set_enabled(request.app.state.engine, not body.disabled, user.tenant_id)
    if not ok:
        raise HTTPException(status.HTTP_400_BAD_REQUEST, "no ingress key configured yet")
    return {"enabled": not body.disabled}


# ---- Keyword alert rules --------------------------------------------------
class CreateAlertRuleReq(BaseModel):
    name: str
    keywords: list[str]
    match_mode: str = "any"     # any | all
    severity: int = 1           # default ALERT
    webhook_id: str | None = None   # optional: fire this webhook on match


class DeleteIdsReq(BaseModel):
    ids: list[str]


@router.get("/v1/admin/alert-rules")
async def admin_alert_rules_list(request: Request,
                                 user: User = Depends(requires(Permission.SYSTEM_CONFIG))) -> dict:
    from sv import alerts
    return {"rules": await alerts.list_rules(request.app.state.engine, user.tenant_id)}


@router.post("/v1/admin/alert-rules")
async def admin_alert_rules_create(body: CreateAlertRuleReq, request: Request,
                                   user: User = Depends(requires(Permission.SYSTEM_CONFIG))) -> dict:
    from sv import alerts
    kws = [k.strip() for k in body.keywords if k and k.strip()]
    if not body.name.strip():
        raise HTTPException(status.HTTP_400_BAD_REQUEST, "name is required")
    if not kws:
        raise HTTPException(status.HTTP_400_BAD_REQUEST, "at least one keyword is required")
    rid = await alerts.create_rule(request.app.state.engine, body.name.strip(), kws,
                                   body.match_mode, body.severity,
                                   webhook_id=body.webhook_id, tenant_id=user.tenant_id)
    return {"id": rid}


@router.post("/v1/admin/alert-rules/{rid}/toggle")
async def admin_alert_rules_toggle(rid: str, body: StatusReq, request: Request,
                                   user: User = Depends(requires(Permission.SYSTEM_CONFIG))) -> dict:
    from sv import alerts
    await alerts.set_enabled(request.app.state.engine, rid, not body.disabled, user.tenant_id)
    return {"id": rid, "enabled": not body.disabled}


@router.post("/v1/admin/alert-rules/delete")
async def admin_alert_rules_delete(body: DeleteIdsReq, request: Request,
                                   user: User = Depends(requires(Permission.SYSTEM_CONFIG))) -> dict:
    from sv import alerts
    n = await alerts.delete_rules(request.app.state.engine, body.ids, user.tenant_id)
    return {"deleted": n}


# ---- False-positive tuning (suppressions) — Analyst OR Admin --------------
class CreateSuppressionReq(BaseModel):
    alert_name: str | None = None
    host: str | None = None
    source_type: str | None = None
    message_contains: str | None = None
    note: str | None = None


@router.get("/v1/suppressions")
async def suppressions_list(request: Request,
                            user: User = Depends(requires(Permission.RULE_WRITE))) -> dict:
    from sv import suppressions
    return {"suppressions": await suppressions.list_suppressions(request.app.state.engine, user.tenant_id)}


@router.post("/v1/suppressions")
async def suppressions_create(body: CreateSuppressionReq, request: Request,
                              user: User = Depends(requires(Permission.RULE_WRITE))) -> dict:
    from sv import suppressions
    fields = body.model_dump()
    if not any((fields.get(f) or "").strip() for f in suppressions.MATCH_FIELDS):
        raise HTTPException(status.HTTP_400_BAD_REQUEST,
                            "provide at least one of: alert name, host, source type, message text")
    sid = await suppressions.create_suppression(request.app.state.engine, fields,
                                                created_by=user.username, tenant_id=user.tenant_id)
    return {"id": sid}


@router.post("/v1/suppressions/{sid}/toggle")
async def suppressions_toggle(sid: str, body: StatusReq, request: Request,
                              user: User = Depends(requires(Permission.RULE_WRITE))) -> dict:
    from sv import suppressions
    await suppressions.set_enabled(request.app.state.engine, sid, not body.disabled, user.tenant_id)
    return {"id": sid, "enabled": not body.disabled}


@router.post("/v1/suppressions/delete")
async def suppressions_delete(body: DeleteIdsReq, request: Request,
                              user: User = Depends(requires(Permission.RULE_WRITE))) -> dict:
    from sv import suppressions
    n = await suppressions.delete_suppressions(request.app.state.engine, body.ids, user.tenant_id)
    return {"deleted": n}


# ---- Outbound webhooks (Vanguard -> IronNode etc.) ------------------------
class CreateWebhookReq(BaseModel):
    name: str
    url: str
    secret: str | None = None
    min_severity: int = 2


class DeleteWebhooksReq(BaseModel):
    ids: list[str]


@router.get("/v1/admin/webhooks")
async def admin_webhooks_list(request: Request,
                              user: User = Depends(requires(Permission.INTEGRATION_WRITE))) -> dict:
    from sv import webhooks
    rows = await webhooks.list_webhooks(request.app.state.engine, user.tenant_id)
    for r in rows:                       # never expose the signing secret
        r["has_secret"] = bool(r.pop("secret", None))
    return {"webhooks": rows}


@router.post("/v1/admin/webhooks")
async def admin_webhooks_create(body: CreateWebhookReq, request: Request,
                                user: User = Depends(requires(Permission.INTEGRATION_WRITE))) -> dict:
    from sv import webhooks
    if not (body.url.startswith("http://") or body.url.startswith("https://")):
        raise HTTPException(status.HTTP_400_BAD_REQUEST, "url must start with http:// or https://")
    if not body.name.strip():
        raise HTTPException(status.HTTP_400_BAD_REQUEST, "name is required")
    wid = await webhooks.create_webhook(
        request.app.state.engine, body.name.strip(), body.url.strip(),
        body.secret, body.min_severity, user.tenant_id)
    return {"id": wid}


@router.post("/v1/admin/webhooks/{wid}/toggle")
async def admin_webhooks_toggle(wid: str, body: StatusReq, request: Request,
                                user: User = Depends(requires(Permission.INTEGRATION_WRITE))) -> dict:
    from sv import webhooks
    await webhooks.set_enabled(request.app.state.engine, wid, not body.disabled, user.tenant_id)
    return {"id": wid, "enabled": not body.disabled}


@router.post("/v1/admin/webhooks/delete")
async def admin_webhooks_delete(body: DeleteWebhooksReq, request: Request,
                                user: User = Depends(requires(Permission.INTEGRATION_WRITE))) -> dict:
    from sv import webhooks
    n = await webhooks.delete_webhooks(request.app.state.engine, body.ids, user.tenant_id)
    return {"deleted": n}


@router.post("/v1/admin/webhooks/{wid}/test")
async def admin_webhooks_test(wid: str, request: Request,
                              user: User = Depends(requires(Permission.INTEGRATION_WRITE))) -> dict:
    from sv import webhooks
    return await webhooks.send_test(request.app.state.engine, wid, user.tenant_id)


# ---- Ingestion / data sources ---------------------------------------------
@router.get("/v1/admin/ingestion")
async def admin_ingestion(request: Request,
                          user: User = Depends(requires(Permission.SYSTEM_CONFIG))) -> dict:
    engine = request.app.state.engine
    tid = str(user.tenant_id)
    meter = getattr(request.app.state, "eps_meter", None)
    by_source = await engine.fetchall(Query(
        "SELECT source_type, COUNT(*) AS events, MAX(ingested_ts) AS last_seen "
        "FROM events WHERE tenant_id = ? GROUP BY source_type ORDER BY events DESC",
        [tid],
    ))
    agents = await engine.fetchall(Query(
        "SELECT hostname, platform, channels, last_ip, last_seq, last_seen_ts "
        "FROM agents WHERE tenant_id = ? AND revoked = FALSE ORDER BY hostname", [tid],
    ))
    return {
        "eps": round(meter.eps(), 2) if meter else 0.0,
        "received_total": meter.total if meter else 0,
        "by_source": by_source,
        "agents": agents,
    }


# ---- System settings (read-mostly; secrets never returned) ----------------
@router.get("/v1/admin/system")
async def admin_system(request: Request,
                       user: User = Depends(requires(Permission.SYSTEM_CONFIG))) -> dict:
    from sv import __version__
    engine = request.app.state.engine
    tid = str(user.tenant_id)

    async def _count(table: str) -> int:
        row = await engine.fetchone(Query(f"SELECT COUNT(*) AS n FROM {table} WHERE tenant_id = ?", [tid]))
        return row["n"] if row else 0

    return {
        "version": __version__,
        "storage_backend": settings.storage_backend,
        "broker": settings.broker,
        "mtls_enabled": settings.mtls_enabled,
        "duckdb_path": settings.duckdb_path,
        "cold_dir": settings.cold_dir,
        "vault_configured": len(settings.vault_key) == 64,
        "jwt_configured": bool(settings.jwt_secret) and settings.jwt_secret != "dev-insecure-change-me",
        "events_stored": await _count("events"),
        "agents_total": await _count("agents"),
        "users_total": await _count("users"),
    }


@router.post("/v1/agents/{agent_id}/revoke")
async def revoke_agent(
    agent_id: str,
    request: Request,
    user: User = Depends(requires(Permission.AGENT_MANAGE)),
) -> dict:
    await registry.revoke(request.app.state.engine, agent_id)
    return {"revoked": agent_id}


@router.get("/v1/me")
async def me(user: User = Depends(current_user)) -> dict:
    return {"username": user.username, "role": user.role.value,
            "tenant_id": str(user.tenant_id)}


@router.get("/healthz")
async def healthz():
    return {"status": "ok"}


app = FastAPI(title="Synapse-Vanguard API", lifespan=lifespan)
app.include_router(router)