fix(review): 处理全量审查剩余项(M4-M8/M11/M12 + 21 条 low)
后端
- asset_service: delete_asset 先清 subdomains/site_certs 子表(SQLite 不强制
FK 且 assets.id 无 AUTOINCREMENT,删最大 id 后新建会复用 rowid 导致孤儿误挂);
metrics.db 清理改 best-effort,不再让已成功的删除返回 500
- provider_service: slug 唯一约束竞态补 IntegrityError 兜底(与 account_service 一致)
- account_service/sync_service: raise HTTPException 补 from e,保留原始异常链
- sync_service: 删死代码 _load_config;新增 BalanceUnsupported,平台无余额接口时
计入 skipped 而不是静默当作失败;到期日写库前归一
- ai: 删掉 OpenAI 早已下线的 billing 余额接口实现,能力探测如实报「不支持」
- adapters/base: _overridden 改走 MRO,中间层基类实现的能力不再被误判为未实现
- core/timeutils: 删死代码 utcnow_iso(注释声称 Z 后缀,实际输出 +00:00)
- main: lifespan 退出时 await 被 cancel 的清理任务,避免 pending task 被销毁
- ssl_service: 写 site_certs/subdomains 前校验 asset_id 存在,杜绝悬空引用;
到期阈值贯穿 _judge_status/_apply_probe/check_one/check_all_site_certs
- routers/credentials、accounts: 明文密码 GET 补 Cache-Control: no-store
- routers/stats: /stats/expiring 的 Query 描述与实际语义对齐(不设下界,含已过期)
Agent
- collector: 解析 sshd_config 的 Include(含 sshd_config.d/*.conf,按 sshd 语义
「首次出现的值生效」),未显式配置的关键字按编译默认值判定,消除假 pass;
防火墙检测改用 iptables -S 统计 -A 规则行并读 INPUT 策略(-L -n 恒有链头输出)
- reporter: 4xx(除 429)不再重试直接退出,429 优先按 Retry-After 退避
安全与部署
- core/security: require_agent_key 改为对外 fail-closed——tailnet/本机放行,
外部来源未配 AGENT_KEY 时一律 401(此前全放行,而服务默认监听 0.0.0.0,
公网上任何人可伪造监控指标与安全检查结果)
- main: 启动时把「未配 API_KEY/AGENT_KEY 则外部来源不可用」打进日志
- run.sh: HOST/PORT 可用环境变量覆盖,并说明默认 0.0.0.0 的权衡
- deploy/setup.sh: 新装时自动生成随机 API_KEY/AGENT_KEY 并提示同步到各 VPS;
注册 vps-cert-check.timer
- deploy/vps-cert-check.{service,timer}: 新增每日 09:30 的站点证书到期探测
(此前 check_site_certs.py 没有任何 unit,证书提醒不会自动跑)
- deploy/update.sh: sync_units 对 timer 用 enable --now(新增 timer 只 restart
不会建开机自启软链),主服务 unit 变更后额外 restart;pip 安装失败不再被吞
- scripts/check_site_certs.py: threshold 参数真正生效并打印
- scripts/make_migration_bundle.py: 缺 assets.db 直接 abort;umask 077 + chmod 600
(包内含 .env 的 MASTER_KEY 与 escrow,不能默认 644 落在 /tmp)
- scripts/restore_migration_bundle.py: 校验之外补必备文件预检,缺文件在触碰
目标机状态之前就 abort
前端
- store: 拆分列表口径 assets 与统计口径 allAssets(无筛选时同源,不重复请求);
删除已无消费者的 expiring/loadExpiring(每次 loadAll 白发一个请求)
- dashboard/monitor/providers/subscriptions/modals: 统计与计数改用 allAssets,
资产页的筛选(含统计卡片点击跳转带的筛选)不再让其他视图的数字缩水
- modals: 账号同步后补 loadOverview;settings: 导入后改 loadAll
- api: countdownText 支持 unit/empty 选项,monitor/domains 各自的实现改为委托,
assets/domains/subscriptions 的到期列不再直出「(-3天)」
- servers: cpu/mem/disk 百分比统一判空,采样缺项不再渲染「null%」
- assets: 同步 AI 余额的结果提示区分 skipped(平台无余额接口)与 failed
- modals: 修正凭据库头注释——2FA 动态码是选填 + 可事后补验,与实现一致
测试
- 新增 tests/test_agent_collector.py(8 条)、tests/test_security.py(11 条)
- 全量 113 passed;改动 JS 均通过 node --check,deploy 脚本通过 bash -n
- 浏览器实测:筛选态下总览/监控中心/平台页/付费资产的统计仍为全量口径,
到期文案与 null 百分比渲染正确,console 零报错
This commit is contained in:
@@ -0,0 +1,139 @@
|
||||
"""VPS Agent 安全检查采集测试
|
||||
|
||||
覆盖两处「假 pass」回归:
|
||||
|
||||
1. ssh_config:只读 /etc/ssh/sshd_config 会漏掉 Include 展开的 sshd_config.d/*.conf
|
||||
(Debian/Ubuntu 云镜像把加固项放在那里),且关键字缺失时被当成 unknown 直接放过;
|
||||
实际 PasswordAuthentication 的 sshd 默认值就是 yes,这类机器是开着密码登录的。
|
||||
2. firewall:`iptables -L -n` 即使零规则也会输出链头,拿 stdout 非空判「有规则」
|
||||
会永远 pass;改用 `iptables -S` 统计 -A 规则行并结合 INPUT 策略判断。
|
||||
|
||||
运行:.venv/bin/pytest tests/test_agent_collector.py -v
|
||||
"""
|
||||
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
AGENT_DIR = Path(__file__).resolve().parent.parent / "agent"
|
||||
if str(AGENT_DIR) not in sys.path:
|
||||
sys.path.insert(0, str(AGENT_DIR))
|
||||
|
||||
import collector # noqa: E402 (agent 目录不是包,按路径导入)
|
||||
|
||||
|
||||
@pytest.fixture()
|
||||
def sshd_tree(tmp_path, monkeypatch):
|
||||
"""把 collector.SSHD_CONFIG 指向 tmp 下的假配置树"""
|
||||
main = tmp_path / "sshd_config"
|
||||
dropin_dir = tmp_path / "sshd_config.d"
|
||||
dropin_dir.mkdir()
|
||||
monkeypatch.setattr(collector, "SSHD_CONFIG", str(main))
|
||||
return main, dropin_dir
|
||||
|
||||
|
||||
def test_ssh_config_reads_included_dropins(sshd_tree):
|
||||
"""加固项写在 sshd_config.d/*.conf 时必须被读到,不能误报 warn"""
|
||||
main, dropin_dir = sshd_tree
|
||||
main.write_text(
|
||||
f"Include {dropin_dir}/*.conf\n\n# 主文件里是未加固的旧值\nPermitRootLogin yes\n"
|
||||
)
|
||||
(dropin_dir / "50-cloud.conf").write_text(
|
||||
"PermitRootLogin prohibit-password\nPasswordAuthentication no\n"
|
||||
)
|
||||
|
||||
result = collector._check_ssh_config()
|
||||
|
||||
assert result["status"] == "pass"
|
||||
assert "PermitRootLogin=prohibit-password" in result["detail"]
|
||||
assert "PasswordAuthentication=no" in result["detail"]
|
||||
|
||||
|
||||
def test_ssh_config_first_value_wins(sshd_tree):
|
||||
"""sshd 语义是「首次出现的值生效」:Include 在顶部时 drop-in 优先于主文件"""
|
||||
main, dropin_dir = sshd_tree
|
||||
main.write_text(f"Include {dropin_dir}/*.conf\nPasswordAuthentication yes\n")
|
||||
(dropin_dir / "60-hardening.conf").write_text("PasswordAuthentication no\n")
|
||||
|
||||
result = collector._check_ssh_config()
|
||||
|
||||
assert result["status"] == "pass"
|
||||
assert "PasswordAuthentication=no" in result["detail"]
|
||||
|
||||
|
||||
def test_ssh_config_missing_keys_use_sshd_defaults(sshd_tree):
|
||||
"""关键字没写 ≠ 安全:PasswordAuthentication 默认 yes,必须告警而不是 pass"""
|
||||
main, _ = sshd_tree
|
||||
main.write_text("# 空配置,两个关键字都没写\nPort 22\n")
|
||||
|
||||
result = collector._check_ssh_config()
|
||||
|
||||
assert result["status"] == "warn"
|
||||
assert "PasswordAuthentication=yes" in result["detail"]
|
||||
assert "未显式配置" in result["detail"]
|
||||
assert "关闭密码登录" in result["suggestion"]
|
||||
|
||||
|
||||
def test_ssh_config_unreadable_is_unknown(monkeypatch):
|
||||
"""读不到主配置时如实报 unknown,不能默认放行"""
|
||||
monkeypatch.setattr(collector, "SSHD_CONFIG", "/nonexistent/sshd_config")
|
||||
|
||||
result = collector._check_ssh_config()
|
||||
|
||||
assert result["status"] == "unknown"
|
||||
assert "无法读取" in result["detail"]
|
||||
|
||||
|
||||
def _fake_run(monkeypatch, iptables_output: str):
|
||||
"""ufw 不存在(走 iptables 分支),iptables -S 返回指定输出"""
|
||||
|
||||
def run(cmd, **kwargs):
|
||||
if cmd[0] == "ufw":
|
||||
raise FileNotFoundError("ufw not installed")
|
||||
return subprocess.CompletedProcess(cmd, 0, stdout=iptables_output, stderr="")
|
||||
|
||||
monkeypatch.setattr(collector.subprocess, "run", run)
|
||||
|
||||
|
||||
def test_firewall_no_rules_is_warn(monkeypatch):
|
||||
"""零规则时 -S 仍有 -P 行,不能据此判 pass"""
|
||||
_fake_run(monkeypatch, "-P INPUT ACCEPT\n-P FORWARD ACCEPT\n-P OUTPUT ACCEPT\n")
|
||||
|
||||
result = collector._check_firewall()
|
||||
|
||||
assert result["status"] == "warn"
|
||||
assert "无过滤规则" in result["detail"]
|
||||
assert result["suggestion"]
|
||||
|
||||
|
||||
def test_firewall_with_rules_is_pass(monkeypatch):
|
||||
_fake_run(
|
||||
monkeypatch,
|
||||
"-P INPUT ACCEPT\n-A INPUT -i lo -j ACCEPT\n-A INPUT -p tcp -m tcp --dport 22 -j ACCEPT\n",
|
||||
)
|
||||
|
||||
result = collector._check_firewall()
|
||||
|
||||
assert result["status"] == "pass"
|
||||
assert "2 条规则" in result["detail"]
|
||||
|
||||
|
||||
def test_firewall_drop_policy_without_rules_is_pass(monkeypatch):
|
||||
"""没有 -A 规则但 INPUT 策略是 DROP,本身就是有效防护"""
|
||||
_fake_run(monkeypatch, "-P INPUT DROP\n-P FORWARD DROP\n-P OUTPUT ACCEPT\n")
|
||||
|
||||
result = collector._check_firewall()
|
||||
|
||||
assert result["status"] == "pass"
|
||||
assert "INPUT 策略 DROP" in result["detail"]
|
||||
|
||||
|
||||
def test_firewall_unknown_when_no_tool(monkeypatch):
|
||||
def run(cmd, **kwargs):
|
||||
raise FileNotFoundError(cmd[0])
|
||||
|
||||
monkeypatch.setattr(collector.subprocess, "run", run)
|
||||
|
||||
assert collector._check_firewall()["status"] == "unknown"
|
||||
@@ -0,0 +1,121 @@
|
||||
"""API Key / Agent Key 鉴权边界测试
|
||||
|
||||
锁死两条不可回退的行为:
|
||||
|
||||
1. 可信来源判定:tailnet(100.64.0.0/10)与本机回环放行;仅当请求确实来自回环时
|
||||
才信任 X-Forwarded-For(tailscale serve 转发场景),防止外部直连伪造 XFF 绕过。
|
||||
2. 未配置密钥时对外部来源必须**拒绝**(fail-closed)。Agent 上报此前是「未配 key
|
||||
就全放行」,而服务默认监听 0.0.0.0,公网上任何人都能伪造监控数据上报。
|
||||
|
||||
运行:.venv/bin/pytest tests/test_security.py -v
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
|
||||
import pytest
|
||||
from fastapi import HTTPException
|
||||
from starlette.requests import Request
|
||||
|
||||
from app.core.config import settings
|
||||
from app.core.security import require_agent_key, require_api_key
|
||||
|
||||
TAILNET_IP = "100.89.0.5"
|
||||
PUBLIC_IP = "203.0.113.7"
|
||||
|
||||
|
||||
def _request(client_ip: str = PUBLIC_IP, headers: dict = None) -> Request:
|
||||
"""构造最小 Request:只需 client 与 headers 两个属性"""
|
||||
scope = {
|
||||
"type": "http",
|
||||
"method": "POST",
|
||||
"path": "/api/agent/report",
|
||||
"client": (client_ip, 40000) if client_ip else None,
|
||||
"headers": [
|
||||
(k.lower().encode(), v.encode()) for k, v in (headers or {}).items()
|
||||
],
|
||||
}
|
||||
return Request(scope)
|
||||
|
||||
|
||||
def _run(coro):
|
||||
return asyncio.run(coro)
|
||||
|
||||
|
||||
def _assert_401(coro):
|
||||
with pytest.raises(HTTPException) as exc:
|
||||
_run(coro)
|
||||
assert exc.value.status_code == 401
|
||||
return exc.value
|
||||
|
||||
|
||||
# ----------------------------- 可信来源放行 ----------------------------- #
|
||||
def test_tailnet_source_allowed_without_key(monkeypatch):
|
||||
"""走 tailnet IP 上报的 Agent 不受密钥缺失影响"""
|
||||
monkeypatch.setattr(settings, "AGENT_KEY", "")
|
||||
_run(require_agent_key(_request(TAILNET_IP), None)) # 不抛异常即通过
|
||||
|
||||
|
||||
def test_loopback_source_allowed_without_key(monkeypatch):
|
||||
monkeypatch.setattr(settings, "API_KEY", "")
|
||||
_run(require_api_key(_request("127.0.0.1"), None))
|
||||
|
||||
|
||||
def test_loopback_xff_tailnet_allowed(monkeypatch):
|
||||
"""tailscale serve 转发:peer 是回环、真实来源在 XFF 里且属于 tailnet"""
|
||||
monkeypatch.setattr(settings, "API_KEY", "")
|
||||
req = _request("127.0.0.1", {"X-Forwarded-For": TAILNET_IP})
|
||||
_run(require_api_key(req, None))
|
||||
|
||||
|
||||
def test_xff_from_public_source_is_ignored(monkeypatch):
|
||||
"""外部直连时伪造 XFF 不能绕过鉴权(只有回环来源的 XFF 才可信)"""
|
||||
monkeypatch.setattr(settings, "API_KEY", "secret")
|
||||
req = _request(PUBLIC_IP, {"X-Forwarded-For": TAILNET_IP})
|
||||
exc = _assert_401(require_api_key(req, None))
|
||||
assert "API Key" in exc.detail
|
||||
|
||||
|
||||
def test_loopback_xff_public_still_requires_key(monkeypatch):
|
||||
"""回环转发但真实来源是公网 IP(funnel 之外的代理场景)→ 仍需 key"""
|
||||
monkeypatch.setattr(settings, "API_KEY", "")
|
||||
req = _request("127.0.0.1", {"X-Forwarded-For": PUBLIC_IP})
|
||||
_assert_401(require_api_key(req, None))
|
||||
|
||||
|
||||
def test_funnel_request_forces_key_even_from_tailnet_ip(monkeypatch):
|
||||
"""funnel 公网流量强制校验,即使来源 IP 恰在 tailnet 网段(双保险)"""
|
||||
monkeypatch.setattr(settings, "AGENT_KEY", "")
|
||||
req = _request(TAILNET_IP, {"Tailscale-Funnel-Request": "?1"})
|
||||
_assert_401(require_agent_key(req, None))
|
||||
|
||||
|
||||
# ----------------------------- 外部来源 fail-closed ----------------------------- #
|
||||
def test_agent_key_unset_rejects_external(monkeypatch):
|
||||
"""未配 AGENT_KEY 时,外部来源必须 401(此前是全放行)"""
|
||||
monkeypatch.setattr(settings, "AGENT_KEY", "")
|
||||
exc = _assert_401(require_agent_key(_request(PUBLIC_IP), None))
|
||||
assert "AGENT_KEY" in exc.detail
|
||||
|
||||
|
||||
def test_api_key_unset_rejects_external(monkeypatch):
|
||||
monkeypatch.setattr(settings, "API_KEY", "")
|
||||
_assert_401(require_api_key(_request(PUBLIC_IP), None))
|
||||
|
||||
|
||||
def test_agent_key_valid_and_invalid(monkeypatch):
|
||||
monkeypatch.setattr(settings, "AGENT_KEY", "sekret")
|
||||
_run(require_agent_key(_request(PUBLIC_IP), "sekret")) # 正确 key 放行
|
||||
_assert_401(require_agent_key(_request(PUBLIC_IP), "wrong"))
|
||||
_assert_401(require_agent_key(_request(PUBLIC_IP), None))
|
||||
|
||||
|
||||
def test_api_key_valid_and_invalid(monkeypatch):
|
||||
monkeypatch.setattr(settings, "API_KEY", "sekret")
|
||||
_run(require_api_key(_request(PUBLIC_IP), "sekret"))
|
||||
_assert_401(require_api_key(_request(PUBLIC_IP), "wrong"))
|
||||
|
||||
|
||||
def test_unknown_client_is_not_trusted(monkeypatch):
|
||||
"""拿不到 client(如某些代理场景)时按不可信处理,不能默认放行"""
|
||||
monkeypatch.setattr(settings, "AGENT_KEY", "")
|
||||
_assert_401(require_agent_key(_request(None), None))
|
||||
Reference in New Issue
Block a user