forked from mxx1111/Homelab
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
676 lines (568 loc) · 28.3 KB
/
Copy pathmain.py
File metadata and controls
676 lines (568 loc) · 28.3 KB
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
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
from __future__ import annotations
import logging
import time
import uuid
from datetime import datetime
from contextlib import asynccontextmanager
from pathlib import Path
from typing import Optional
from fastapi import Body, FastAPI, Header, HTTPException, Query, Request
from fastapi.responses import FileResponse, JSONResponse
from fastapi.staticfiles import StaticFiles
from .actions import ActionError, Actions, snapshot_plan
from .alerts import AlertEngine
from .auth import COOKIE, Auth
from .cache import Store
from .collectors import REGISTRY
from . import demo
from .collectors.crowdsec import search_decisions
from .config import CONFIG, CONFIG_PATH
from .firewall import DURATIONS, FirewallError, LapiClient, Whitelist
from .history import History
from .notify import Notifier
from .security_center import SecurityCenter
logging.basicConfig(level=logging.INFO,
format="%(asctime)s %(levelname)s %(name)s %(message)s")
log = logging.getLogger("homelab")
FRONTEND_DIR = Path(__file__).resolve().parent.parent / "frontend"
STARTED_AT = time.time()
history = History(CONFIG)
security_center = SecurityCenter(CONFIG, history)
notifier = Notifier(CONFIG)
alert_engine = AlertEngine(CONFIG, history, notifier)
lapi = LapiClient(CONFIG)
whitelist = Whitelist(CONFIG, history, lapi)
DEMO = demo.enabled(CONFIG)
# 演示模式换掉整个采集器注册表:真实采集器一个都不会被调用,
# 容器里也就不需要挂载任何宿主机路径
store = Store(demo.REGISTRY if DEMO else REGISTRY, CONFIG, history=history,
alerts=alert_engine, whitelist=whitelist)
actions = Actions(CONFIG)
auth = Auth(CONFIG)
FIREWALL_CFG = CONFIG.get("firewall") or {}
FIREWALL_ENABLED = bool(FIREWALL_CFG.get("enabled", True))
WRITE_TOKEN = str(FIREWALL_CFG.get("write_token") or "")
# 没配令牌时默认拒绝所有写操作。面板能封 IP、能重启容器,而它自己没有登录体系,
# "不配就放行"等于给每个把它反代出去的人留一个无认证的 root 后门。
# 只读功能不受影响;确实在可信内网里图省事,才显式打开这个开关
ALLOW_ANON_WRITE = bool(FIREWALL_CFG.get("allow_anonymous_write", False))
@asynccontextmanager
async def lifespan(_app: FastAPI):
log.info("配置文件: %s", CONFIG_PATH)
log.info("防火墙写操作: %s | 容器操作: %s | 推送: %s",
"开" if FIREWALL_ENABLED else "关",
"开" if actions.enabled else "关",
"开" if notifier.enabled else "关")
if DEMO:
log.warning("演示模式:全部采集器返回仿真数据,不读取宿主机任何信息;"
"写操作落在内存沙盒,每 %d 分钟重置", demo.RESET_SECONDS // 60)
if auth.enabled:
log.info("面板登录: 已开启(用户 %s,会话 %g 小时)",
auth.username, auth.session_hours)
if auth.plaintext:
log.warning("auth.password 是明文。生成散列后替换掉它:"
"docker exec <容器> python -m backend.hashpw '你的密码'")
else:
log.warning("面板登录: 未开启。面板能操作所有接入节点的防火墙,"
"只在完全可信的网络里才可以这样跑")
if WRITE_TOKEN:
log.info("写操作认证: 需令牌")
elif ALLOW_ANON_WRITE:
log.warning("写操作认证: 已关闭(allow_anonymous_write)。"
"任何能访问本面板的人都可以封禁 IP 和操作容器,"
"确保它只暴露在可信网络里")
else:
log.info("写操作认证: 已锁定(未配置 write_token,写接口一律 403)")
history.start()
if DEMO:
seeded = demo.seed_history(history)
if seeded:
log.info("演示模式:已播种 %d 条历史采样(过去 7 天)", seeded)
await store.start()
yield
await store.stop()
history.stop()
app = FastAPI(title="Homelab Dashboard", version="0.5.0",
docs_url="/api/docs", lifespan=lifespan)
# GET 不记:面板每 5 秒轮询一次 /api/summary,全记下来一天几万条,
# 有用的写操作反而被埋掉。首页访问按 IP 每小时记一条,够看"谁在用面板"
AUDIT_METHODS = {"POST", "PUT", "PATCH", "DELETE"}
_last_visit = {}
def _client_ip(request: Request):
"""面板可能被反代,优先取 X-Forwarded-For 的第一跳"""
xff = request.headers.get("x-forwarded-for")
if xff:
ip = xff.split(",")[0].strip()
else:
ip = request.headers.get("x-real-ip") or (
request.client.host if request.client else "?")
# 演示实例是公开的,审计页人人可见。记完整 IP 等于把每个访客的地址
# 展示给所有其他访客——他们并没有同意这件事。掩掉后半段,
# 既能演示"审计能区分不同来源",又不泄漏到个人
return demo.mask_ip(ip) if DEMO else ip
@app.middleware("http")
async def audit_middleware(request: Request, call_next):
started = time.perf_counter()
response = await call_next(request)
elapsed = (time.perf_counter() - started) * 1000
path = request.url.path
if request.method in AUDIT_METHODS and path.startswith("/api/"):
history.record_audit(_client_ip(request), request.method, path,
response.status_code, elapsed,
ua=request.headers.get("user-agent"))
elif path == "/" and request.method == "GET":
ip = _client_ip(request)
now = time.time()
if now - _last_visit.get(ip, 0) > 3600:
_last_visit[ip] = now
history.record_audit(ip, "GET", "/", response.status_code, elapsed,
detail="打开面板",
ua=request.headers.get("user-agent"))
return response
# 登录本身、健康检查、前端静态资源不需要会话,否则连登录页都打不开
OPEN_PATHS = ("/api/auth/", "/api/health")
@app.middleware("http")
async def auth_middleware(request: Request, call_next):
"""未登录时挡掉所有 API。
只挡 /api/,前端页面照常返回——页面拿不到数据会自己弹登录框,
比服务端重定向省事,也不用管前端路由。
"""
path = request.url.path
if (not auth.enabled or not path.startswith("/api/")
or path.startswith(OPEN_PATHS)):
return await call_next(request)
if auth.valid(request.cookies.get(COOKIE)):
return await call_next(request)
# 带对 write_token 的请求也放行。不然中间件会挡在 _guard 前面,
# 脚本调用(curl 封个 IP)这条路等于被登录功能顺手砍掉了
if WRITE_TOKEN and request.headers.get("x-panel-token") == WRITE_TOKEN:
return await call_next(request)
return JSONResponse({"detail": "未登录"}, status_code=401)
def _logged_in(request: Request):
return auth.enabled and auth.valid(request.cookies.get(COOKIE))
def _guard(request: Request, token: Optional[str], what="写操作"):
"""写操作的统一前置检查。
两条路都认:已登录的会话,或者带对 write_token 的请求。
保留后者是为了脚本调用——curl 一条命令封个 IP,不必先走登录换 cookie。
"""
who = request.client.host if request.client else "?"
if _logged_in(request):
return
if not WRITE_TOKEN:
if ALLOW_ANON_WRITE:
return
log.warning("拒绝来自 %s 的%s:未配置 write_token", who, what)
raise HTTPException(
status_code=403,
detail="写操作已锁定。在 config.yaml 的 firewall.write_token 填一串随机字符,"
"或在可信内网里设 allow_anonymous_write: true")
if token != WRITE_TOKEN:
log.warning("拒绝来自 %s 的%s:token 不匹配", who, what)
raise HTTPException(status_code=401, detail="缺少或错误的操作令牌")
@app.get("/api/auth/state")
def auth_state(request: Request):
"""前端启动时问一次:要不要登录、现在登没登。未登录也能调,否则没法判断"""
return {"enabled": auth.enabled,
"logged_in": _logged_in(request),
"username": auth.username if auth.enabled else None,
"locked_for": auth.locked_for(_client_ip(request))}
@app.post("/api/auth/login")
async def auth_login(request: Request, payload: dict = Body(...)):
if not auth.enabled:
raise HTTPException(status_code=400, detail="未启用登录")
ip = _client_ip(request)
left = auth.locked_for(ip)
if left:
# 锁定期内连密码都不校验,免得给人当探测口令是否正确的信道
raise HTTPException(status_code=429,
detail=f"失败次数过多,请 {left} 秒后再试")
token = auth.login(str(payload.get("username") or ""),
str(payload.get("password") or ""), ip)
if not token:
history.record_audit(ip, "POST", "/api/auth/login", 401, 0,
detail="登录失败", ua=request.headers.get("user-agent"))
raise HTTPException(status_code=401, detail="用户名或密码不对")
history.record_event("auth", "info", f"login:{ip}", f"{auth.username} 登录面板", ip)
resp = JSONResponse({"ok": True, "username": auth.username})
resp.set_cookie(
COOKIE, token, max_age=int(auth.session_hours * 3600),
httponly=True, # JS 读不到,XSS 也偷不走会话
samesite="lax", # 跨站表单提交带不上,挡掉 CSRF
# 内网多半用 http 访问,写死 secure=True 会导致 cookie 根本不生效,
# 表现为"登录成功但立刻又要登录"。按实际请求协议决定
secure=request.url.scheme == "https",
path="/")
return resp
@app.post("/api/auth/logout")
def auth_logout(request: Request):
auth.logout(request.cookies.get(COOKIE))
resp = JSONResponse({"ok": True})
resp.delete_cookie(COOKIE, path="/")
return resp
@app.get("/api/health")
def health():
return {"ok": True, "uptime_seconds": int(time.time() - STARTED_AT),
"config_path": CONFIG_PATH}
@app.get("/api/summary")
def summary():
snap = store.snapshot()
snap["alerts"] = alert_engine.snapshot()
snap["site_name"] = alert_engine.site_name
if DEMO:
if demo.SANDBOX.maybe_reset():
# 告警规则存在 SQLite 里,不在内存沙盒中,得单独清
history.clear_setting("alert_rules")
history.clear_setting("muted")
alert_engine.reload_settings()
log.info("演示沙盒已重置")
snap["demo"] = True
return JSONResponse(snap)
@app.get("/api/section/{name}")
def section(name: str):
data = store.section(name)
if data is None:
raise HTTPException(status_code=404, detail=f"未知采集器: {name}")
return JSONResponse(data)
# ---------- 历史 ----------
@app.get("/api/history/series")
def history_series(metric: str = Query(...), hours: int = Query(24, ge=1, le=2160),
points: int = Query(120, ge=10, le=600)):
return {"metric": metric, "hours": hours,
"points": history.series(metric, hours, points)}
@app.get("/api/history/multi")
def history_multi(metrics: str = Query(...), hours: int = Query(24, ge=1, le=2160),
points: int = Query(120, ge=10, le=600)):
"""一次取多条曲线,前端画一屏图只发一个请求"""
names = [m.strip() for m in metrics.split(",") if m.strip()][:12]
return {"hours": hours,
"series": {m: history.series(m, hours, points) for m in names}}
@app.get("/api/history/metrics")
def history_metrics():
return {"metrics": history.metric_names(), "stats": history.stats()}
@app.get("/api/history/events")
def history_events(limit: int = Query(100, ge=1, le=500),
kind: Optional[str] = None, hours: Optional[int] = None):
return {"events": history.events(limit=limit, kind=kind, since_hours=hours)}
@app.get("/api/history/growth")
def history_growth(hours: int = Query(168, ge=24, le=2160)):
"""各存储卷的增长速度与预计写满时间"""
out = {}
storage_sec = (store.section("storage") or {}).get("data") or {}
for vol in storage_sec.get("volumes") or []:
if vol.get("ok") and vol.get("label"):
out[vol["label"]] = history.growth(f"vol:{vol['label']}", hours)
return {"hours": hours, "volumes": out}
# ---------- 安全中心 ----------
@app.get("/api/security/overview")
def security_overview(hours: int = Query(168, ge=1, le=2160),
limit: int = Query(100, ge=1, le=500)):
sections = store.snapshot().get("sections") or {}
return {
"coverage": security_center.coverage(sections),
"incidents": security_center.incidents(sections, hours, limit),
"appsec": security_center.appsec(sections),
"map": security_center.map_options(),
"changes": history.security_changes(50),
"write_enabled": FIREWALL_ENABLED,
}
@app.patch("/api/security/incidents/{key:path}")
def security_incident_update(key: str, request: Request, payload: dict = Body(...),
x_panel_token: Optional[str] = Header(default=None)):
_guard(request, x_panel_token, "更新安全事件")
try:
result = security_center.incident_update(
key, str(payload.get("status") or "open"),
str(payload.get("note") or ""), bool(payload.get("false_positive", False)))
except (ValueError, RuntimeError) as exc:
raise HTTPException(status_code=400, detail=str(exc)) from None
history.record_event("security", "info", f"incident:{key}",
f"安全事件更新为 {result['status']}", result.get("note"))
return {"ok": True, "key": key, **result}
@app.get("/api/security/cti/{ip}")
def security_cti(ip: str):
try:
return security_center.cti(ip)
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from None
except Exception as exc: # noqa: BLE001 外部情报失败不暴露堆栈/密钥
raise HTTPException(status_code=502, detail=f"CTI 查询失败: {str(exc)[:160]}") from None
@app.post("/api/security/changes/ban")
async def security_safe_ban(request: Request, payload: dict = Body(...),
x_panel_token: Optional[str] = Header(default=None)):
"""带基线、留痕和自动回滚的临时封禁。
它复用已有 CrowdSec LAPI,不直接改 iptables。操作后只重采现有探针;如果
原本正常的服务或节点变坏,立即撤销本次封禁。
"""
if not FIREWALL_ENABLED:
raise HTTPException(status_code=403, detail="防火墙写操作已禁用")
_guard(request, x_panel_token, "安全变更")
target = str(payload.get("ip") or "").strip()
duration = str(payload.get("duration") or "4h")
reason = str(payload.get("reason") or "安全中心临时封禁")[:200]
try:
target, _scope = lapi.validate(target)
except FirewallError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from None
sections = store.snapshot().get("sections") or {}
current = ((sections.get("crowdsec") or {}).get("data") or {}).get("decisions") or []
if any(x.get("ip") == target for x in current):
raise HTTPException(status_code=400, detail=f"{target} 已在封禁列表中,本次未改动")
before = security_center.preflight(sections)
change_id = uuid.uuid4().hex
change = {"id": change_id, "kind": "crowdsec", "target": target,
"action": "ban", "status": "pending", "before": before,
"ts": int(time.time()), "detail": reason}
try:
history.security_change_add(change)
result = lapi.ban(target, duration, reason)
except (FirewallError, RuntimeError) as exc:
history.security_change_update(change_id, "failed", detail=str(exc))
raise HTTPException(status_code=400, detail=str(exc)) from None
expires_at = None
try:
expires_at = int(datetime.fromisoformat(result["until"]).timestamp())
except (KeyError, TypeError, ValueError):
pass
history.security_change_update(change_id, "applied", after=result,
detail=f"{reason};到期 {result.get('until') or '?'}")
history.security_change_expiry(change_id, expires_at)
await store.refresh("crowdsec")
for name in ("services", "nodes"):
await store.refresh(name)
after_sections = store.snapshot().get("sections") or {}
regressions = security_center.regressions(before, after_sections)
if regressions:
try:
rolled = lapi.unban(result["ip"])
await store.refresh("crowdsec")
history.security_change_update(
change_id, "auto_rolled_back", after=rolled,
detail=";".join(regressions))
except FirewallError as exc:
history.security_change_update(
change_id, "rollback_failed", detail=";".join(regressions) + f";{exc}")
raise HTTPException(status_code=409,
detail="健康检查发现回归,已尝试自动回滚:" + ";".join(regressions))
history.record_event("security-change", "warn", f"security-ban:{change_id}",
f"安全中心临时封禁 {result['ip']}",
f"{result['duration_label']};{reason}")
return {"ok": True, "change_id": change_id, "result": result,
"preflight": before, "regressions": []}
@app.post("/api/security/changes/{change_id}/rollback")
async def security_change_rollback(change_id: str, request: Request,
x_panel_token: Optional[str] = Header(default=None)):
_guard(request, x_panel_token, "回滚安全变更")
change = history.security_change(change_id)
if not change:
raise HTTPException(status_code=404, detail="找不到这条安全变更")
if change.get("action") != "ban" or change.get("status") != "applied":
raise HTTPException(status_code=400, detail="这条变更当前不可回滚")
try:
result = lapi.unban(change["target"])
except FirewallError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from None
history.security_change_update(change_id, "rolled_back", after=result,
detail="用户从安全中心回滚")
rollback_id = uuid.uuid4().hex
history.security_change_add({
"id": rollback_id, "kind": "crowdsec", "target": change["target"],
"action": "unban", "status": "applied", "rollback_of": change_id,
"before": change, "after": result, "detail": "回滚临时封禁",
})
await store.refresh("crowdsec")
history.record_event("security-change", "info", f"security-rollback:{change_id}",
f"已回滚封禁 {change['target']}", None)
return {"ok": True, "change_id": change_id, "rollback_id": rollback_id,
"result": result}
# ---------- 防火墙 ----------
@app.get("/api/firewall/meta")
def firewall_meta(request: Request):
# 判断口径必须和 _guard 一致,否则界面会和实际行为对不上:
# 已登录的会话本来就能写,再提示"写操作已锁定"就是假警报
logged_in = _logged_in(request)
return {
"enabled": FIREWALL_ENABLED,
# 登录之后不需要令牌,前端也就不该再显示那个输入框
"token_required": bool(WRITE_TOKEN) and not logged_in,
"logged_in": logged_in,
# 前端据此提示"写操作被锁",而不是让用户点了按钮才吃一个 403
"write_locked": not logged_in and not WRITE_TOKEN and not ALLOW_ANON_WRITE,
"durations": [{"value": k, "label": v} for k, v in DURATIONS.items()],
"protected_networks": lapi.protected,
"actions_enabled": actions.enabled,
"protected_containers": sorted(actions.protected),
"notify_enabled": notifier.enabled,
"whitelist_enabled": whitelist.enabled,
}
@app.get("/api/firewall/search")
def firewall_search(q: str = Query(..., min_length=1),
limit: int = Query(200, ge=1, le=1000)):
"""封禁列表没有全量下发给前端(社区黑名单上万条),搜索直接查库"""
if DEMO:
return {"query": q, "items": demo.search(q, limit)}
try:
return {"query": q, "items": search_decisions(CONFIG, q, limit)}
except Exception as exc: # noqa: BLE001
raise HTTPException(status_code=400, detail=str(exc)[:200]) from None
# ---------- 白名单 ----------
@app.get("/api/firewall/whitelist")
def whitelist_list():
return {"enabled": whitelist.enabled, "items": whitelist.entries(),
"recent_released": store.last_released[-20:]}
@app.post("/api/firewall/whitelist")
async def whitelist_add(request: Request, payload: dict = Body(...),
x_panel_token: Optional[str] = Header(default=None)):
_guard(request, x_panel_token, "加白名单")
try:
result = whitelist.add(payload.get("ip"), payload.get("note") or "")
except FirewallError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from None
except RuntimeError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from None
log.info("加入白名单 %s", result["ip"])
history.record_event("whitelist", "info", f"whitelist-add:{result['ip']}",
f"加入白名单 {result['ip']}",
payload.get("note") or None)
if result.get("released"):
await store.refresh("crowdsec")
return result
@app.delete("/api/firewall/whitelist/{ip:path}")
def whitelist_remove(ip: str, request: Request,
x_panel_token: Optional[str] = Header(default=None)):
_guard(request, x_panel_token, "移除白名单")
try:
result = whitelist.remove(ip)
except FirewallError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from None
log.info("移出白名单 %s", ip)
history.record_event("whitelist", "info", f"whitelist-del:{ip}",
f"移出白名单 {ip}", None)
return result
@app.post("/api/firewall/ban")
async def firewall_ban(request: Request, payload: dict = Body(...),
x_panel_token: Optional[str] = Header(default=None)):
if not FIREWALL_ENABLED:
raise HTTPException(status_code=403, detail="防火墙写操作已在 config.yaml 中禁用")
_guard(request, x_panel_token, "封禁")
try:
result = lapi.ban(payload.get("ip"), payload.get("duration") or "4h",
payload.get("reason") or "")
except FirewallError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from None
log.info("封禁 %s %s", result["ip"], result["duration"])
history.record_event("ban", "warn", f"ban:{result['ip']}",
f"手动封禁 {result['ip']}",
f"{result['duration_label']} {result.get('reason') or ''}")
await store.refresh("crowdsec")
return result
@app.post("/api/firewall/unban")
async def firewall_unban(request: Request, payload: dict = Body(...),
x_panel_token: Optional[str] = Header(default=None)):
if not FIREWALL_ENABLED:
raise HTTPException(status_code=403, detail="防火墙写操作已在 config.yaml 中禁用")
_guard(request, x_panel_token, "解封")
try:
result = lapi.unban(payload.get("ip"))
except FirewallError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from None
log.info("解封 %s,移除 %d 条决策", result["ip"], result["removed"])
history.record_event("ban", "info", f"unban:{result['ip']}",
f"解封 {result['ip']}", f"移除 {result['removed']} 条决策")
await store.refresh("crowdsec")
return result
# ---------- 容器操作 ----------
@app.post("/api/containers/{name}/{action}")
async def container_action(name: str, action: str, request: Request,
x_panel_token: Optional[str] = Header(default=None)):
_guard(request, x_panel_token, f"容器{action}")
try:
result = actions.container(name, action)
except ActionError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from None
history.record_event("action", "info", f"container:{name}",
f"容器 {name} 执行 {action}", None)
await store.refresh("containers")
return result
@app.get("/api/containers/{name}/logs")
def container_logs(name: str, lines: int = Query(200, ge=1, le=1000)):
try:
return actions.logs(name, lines)
except ActionError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from None
# ---------- 快照 ----------
@app.get("/api/snapshots")
def snapshots(keep: int = Query(10, ge=1, le=200)):
if DEMO:
return demo.snapshots()
return snapshot_plan(CONFIG, store.snapshot().get("sections") or {}, keep=keep)
# ---------- 告警 ----------
# ---------- 审计 ----------
@app.get("/api/audit")
def audit_log(limit: int = Query(200, ge=1, le=1000),
hours: Optional[int] = None, failed: bool = False):
return {"items": history.audit(limit=limit, hours=hours, only_failed=failed),
"summary": history.audit_summary(hours or 168)}
@app.get("/api/alerts")
def alerts_now():
return alert_engine.snapshot()
@app.get("/api/alerts/settings")
def alerts_settings():
return alert_engine.settings_view()
@app.put("/api/alerts/settings")
def alerts_settings_update(request: Request, payload: dict = Body(...),
x_panel_token: Optional[str] = Header(default=None)):
_guard(request, x_panel_token, "改告警规则")
try:
alert_engine.update_rules(payload.get("rules") or {},
payload.get("global") or {})
except RuntimeError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from None
log.info("告警规则已更新")
history.record_event("config", "info", "alert-rules", "告警规则已修改", None)
return alert_engine.settings_view()
@app.post("/api/alerts/mute")
def alerts_mute(request: Request, payload: dict = Body(...),
x_panel_token: Optional[str] = Header(default=None)):
"""忽略某条告警。硬盘服役年限这类不会自愈的告警,提醒一次就够了"""
_guard(request, x_panel_token, "忽略告警")
key = (payload.get("key") or "").strip()
if not key:
raise HTTPException(status_code=400, detail="缺少 key")
hours = payload.get("hours")
try:
until = alert_engine.mute(key, float(hours) if hours else None)
except RuntimeError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from None
history.record_event("config", "info", f"mute:{key}", f"忽略告警 {key}",
f"{hours} 小时" if hours else "永久")
return {"ok": True, "key": key, "until": until or None}
@app.delete("/api/alerts/mute/{key:path}")
def alerts_unmute(key: str, request: Request,
x_panel_token: Optional[str] = Header(default=None)):
_guard(request, x_panel_token, "恢复告警")
if not alert_engine.unmute(key):
raise HTTPException(status_code=400, detail=f"{key} 不在忽略列表")
history.record_event("config", "info", f"unmute:{key}", f"恢复告警 {key}", None)
return {"ok": True, "key": key}
@app.post("/api/alerts/test")
def alerts_test(request: Request, x_panel_token: Optional[str] = Header(default=None)):
"""发一条测试推送,验证 Server 酱配置是否正确"""
_guard(request, x_panel_token, "测试推送")
if not notifier.enabled:
raise HTTPException(
status_code=400,
detail="推送未启用。在 config.yaml 的 notify 段填 sendkey 并设 enabled: true")
err = notifier.send(f"[{alert_engine.site_name}] 测试推送",
"如果你收到这条,说明 Server 酱配置正确。\n\n"
f"时间 {time.strftime('%Y-%m-%d %H:%M:%S')}")
if err:
raise HTTPException(status_code=400, detail=err)
return {"ok": True, "message": "已发送,检查你的 Server 酱通道"}
@app.get("/")
def index():
page = FRONTEND_DIR / "index.html"
if not page.exists():
raise HTTPException(status_code=404, detail="前端未构建")
return FileResponse(page)
if FRONTEND_DIR.exists():
app.mount("/static", StaticFiles(directory=FRONTEND_DIR), name="static")