fix(webpush): remove hardcoded VAPID keys and expose runtime public-key API

This commit is contained in:
jxxghp
2026-11-22 12:54:30 +08:00
parent dad4782d8a
commit b4a6dd4846
14 changed files with 311 additions and 18 deletions

View File

@@ -35,6 +35,7 @@ from app.schemas.message import MessageHistoryItem as _SchemaMessageHistoryItem
from app.schemas.message import Subscription as _SchemaSubscription
from app.schemas.message import SubscriptionMessage as _SchemaSubscriptionMessage
from app.schemas.message import WebMessageItem as _SchemaWebMessageItem
from app.schemas.message import WebPushPublicKeyData as _SchemaWebPushPublicKeyData
from app.schemas.response import Response as _SchemaResponse
from app.schemas.token import TokenPayload as _SchemaTokenPayload
from app.schemas.types import NotificationChannel, SystemConfigKey
@@ -364,6 +365,29 @@ def incoming_verify(
return vocechat_verify()
@router.get(
"/webpush/public-key",
summary="获取客户端webpush公钥",
response_model=_SchemaResponse[_SchemaWebPushPublicKeyData],
)
def get_webpush_public_key(
_: _SchemaTokenPayload = Depends(verify_token),
) -> _SchemaResponse[_SchemaWebPushPublicKeyData]:
"""
返回当前实例用于浏览器 Web Push 订阅的 VAPID 公钥
"""
public_key = get_api_runtime_config_snapshot().vapid_public_key
if not public_key:
return _SchemaResponse(
success=False,
message="未配置有效的 WebPush VAPID 公钥",
)
return _SchemaResponse(
success=True,
data=_SchemaWebPushPublicKeyData(public_key=public_key),
)
@router.post(
"/webpush/subscribe",
summary="客户端webpush通知订阅",
@@ -397,6 +421,7 @@ def send_notification(
if not subscriptions:
return _SchemaResponse(success=True, message="没有可发送的浏览器通知")
api_config = get_api_runtime_config_snapshot()
success_count = 0
failure_count = 0
for sub in subscriptions:
@@ -404,8 +429,8 @@ def send_notification(
send_webpush(
subscription=sub,
data=json.dumps(payload.model_dump()),
vapid_private_key=get_api_runtime_config_snapshot().vapid_private_key,
vapid_subject=get_api_runtime_config_snapshot().vapid_subject,
vapid_private_key=api_config.vapid_private_key,
vapid_subject=api_config.vapid_subject,
**webpush_options_for_endpoint(sub.get("endpoint")),
)
success_count += 1

View File

@@ -632,7 +632,9 @@ async def get_env_setting(
"""
查询系统环境变量,包括当前版本号(仅管理员)
"""
info = get_runtime_settings().snapshot(exclude={"SECRET_KEY", "RESOURCE_SECRET_KEY"})
info = get_runtime_settings().snapshot(
exclude={"SECRET_KEY", "RESOURCE_SECRET_KEY", "VAPID_PRIVATE_KEY"}
)
# GitHub Token 只通过专用授权状态接口返回脱敏摘要,不能随系统设置快照进入浏览器。
if "GITHUB_TOKEN" in info:
info["GITHUB_TOKEN"] = None

View File

@@ -234,6 +234,7 @@ class ApiRuntimeConfig:
:param movie_rename_format: 电影重命名格式
:param television_rename_format: 电视剧文件的重命名模板
:param music_rename_format: 音乐重命名格式
:param vapid_public_key: Web Push 浏览器订阅使用的 VAPID 公钥
:param vapid_private_key: Web Push 消息签名使用的 VAPID 私钥
:param vapid_subject: Web Push VAPID 声明中的联系地址或主体标识
:param cookiecloud_enable_local: CookieCloud是否启动本地服务
@@ -261,6 +262,7 @@ class ApiRuntimeConfig:
movie_rename_format: str = ""
television_rename_format: str = ""
music_rename_format: str = ""
vapid_public_key: str = ""
vapid_private_key: str = ""
vapid_subject: str = ""
cookiecloud_enable_local: bool = False

View File

@@ -529,7 +529,9 @@ _RESTART_REQUIRED_GROUPS = {
"system_update",
}
# 所在分组需要重启,但由调用方逐次读取、修改后立即生效的例外项。
_IMMEDIATE_SETTINGS_IN_RESTART_GROUPS = frozenset({"API_DOCS_ENABLE"})
_IMMEDIATE_SETTINGS_IN_RESTART_GROUPS = frozenset(
{"API_DOCS_ENABLE", "VAPID_PUBLIC_KEY", "VAPID_PRIVATE_KEY", "VAPID_SUBJECT"}
)
def _load_source_catalog() -> dict[str, Any]:

View File

@@ -1351,6 +1351,21 @@
"group": "plugins",
"source_file": "app/runtime/config.py"
},
"VAPID_PRIVATE_KEY": {
"description": "Web Push VAPID 私钥(base64url 编码的 P-256 私钥),留空时使用运行期内置默认值;需与 VAPID_PUBLIC_KEY 成对配置",
"group": "security",
"source_file": "app/runtime/config.py"
},
"VAPID_PUBLIC_KEY": {
"description": "Web Push VAPID 公钥(base64url 编码的未压缩 P-256 公钥),留空时使用运行期内置默认值;需与 VAPID_PRIVATE_KEY 成对配置",
"group": "security",
"source_file": "app/runtime/config.py"
},
"VAPID_SUBJECT": {
"description": "Web Push VAPID 联系主体(mailto: 或 https:// 地址),留空时默认使用超级管理员邮箱地址",
"group": "security",
"source_file": "app/runtime/config.py"
},
"WALLPAPER": {
"description": "登录页面壁纸来源:空字符串表示无壁纸,另支持 tmdb/bing/mediaserver/customize/static",
"group": "personalization",

View File

@@ -50,8 +50,9 @@ MASKED_FIELDS = {
"RESOURCE_SECRET_KEY",
"SECRET_KEY",
"SUPERUSER_PASSWORD",
"VAPID_PRIVATE_KEY",
}
MASKED_SUFFIXES = ("_TOKEN", "_PASSWORD", "_SECRET", "_API_KEY")
MASKED_SUFFIXES = ("_TOKEN", "_PASSWORD", "_SECRET", "_API_KEY", "_PRIVATE_KEY")
CONTEXT_SETTINGS = {"help_option_names": ["-h", "--help"]}
PREPARED_UPDATE_ROOT = get_runtime_setting("TEMP_PATH") / "moviepilot-update"
PREPARED_UPDATE_MANIFEST = PREPARED_UPDATE_ROOT / "install.json"

View File

@@ -101,6 +101,9 @@ class WebPushModule(_ModuleBase, _MessageBase[object]):
else:
caption = message.text
content = ""
vapid_config = get_runtime_setting("VAPID") or {}
vapid_private_key = str(vapid_config.get("privateKey") or "")
vapid_subject = str(vapid_config.get("subject") or "")
for sub in webpush_registry.list():
logger.debug(f"给 {sub} 发送WebPush:{caption} {content}")
try:
@@ -118,8 +121,8 @@ class WebPushModule(_ModuleBase, _MessageBase[object]):
"body": content,
"url": message.link or "/?shotcut=message"
}),
vapid_private_key=get_runtime_setting('VAPID').get("privateKey"),
vapid_subject=get_runtime_setting('VAPID').get("subject"),
vapid_private_key=vapid_private_key,
vapid_subject=vapid_subject,
**webpush_options,
)
except WebPushDeliveryError as err:

View File

@@ -735,6 +735,21 @@ class ConfigModel(BaseModel):
default=False,
description='是否开放 API 文档;开放 /docs、/redoc 与 /api/v1/openapi.json,文档首次生成后常驻约 20–30MB 内存,修改后立即生效',
)
VAPID_PUBLIC_KEY: Optional[str] = Field(
default=None,
description='Web Push VAPID 公钥(base64url 编码的未压缩 P-256 公钥),留空时使用运行期内置默认值;需与 VAPID_PRIVATE_KEY 成对配置',
)
VAPID_PRIVATE_KEY: Annotated[
Optional[str],
SettingPolicy(sensitive=True),
] = Field(
default=None,
description='Web Push VAPID 私钥(base64url 编码的 P-256 私钥),留空时使用运行期内置默认值;需与 VAPID_PUBLIC_KEY 成对配置',
)
VAPID_SUBJECT: Optional[str] = Field(
default=None,
description='Web Push VAPID 联系主体(mailto: 或 https:// 地址),留空时默认使用超级管理员邮箱地址',
)
# 工作流配置
WORKFLOW_STATISTIC_SHARE: bool = Field(default=True, description='工作流数据共享')
@@ -902,6 +917,7 @@ class Settings(BaseSettings, ConfigModel, LogConfigModel):
:cvar model_config: 来源优先级为构造参数、环境变量、环境文件、secrets、默认值
:ivar _secret_fields: 存在外部 secret 的字段名,包含被高优先级来源遮蔽或无效的文件
:ivar _runtime_defaults: 运行期注入的受保护默认键值,不参与持久化、环境变量导出或模型序列化
"""
model_config = SettingsConfigDict(
@@ -911,6 +927,7 @@ class Settings(BaseSettings, ConfigModel, LogConfigModel):
secrets_dir=_get_secrets_dir(),
)
_secret_fields: set[str] = PrivateAttr(default_factory=set)
_runtime_defaults: dict[str, Any] = PrivateAttr(default_factory=dict)
@classmethod
def settings_customise_sources(
@@ -1521,11 +1538,32 @@ class Settings(BaseSettings, ConfigModel, LogConfigModel):
def VAPID(self) -> dict[str, str]:
"""
返回 Web Push 使用的 VAPID 配置。
优先使用显式成对配置的自定义密钥;均留空时回退到运行期注入的默认密钥对,
仅配置单边密钥时返回空密钥以避免公私钥错配。
"""
subject = (self.VAPID_SUBJECT or "").strip() or (
f"mailto:{self.SUPERUSER or 'moviepilot'}@movie-pilot.org"
)
custom_public = (self.VAPID_PUBLIC_KEY or "").strip()
custom_private = (self.VAPID_PRIVATE_KEY or "").strip()
if custom_public and custom_private:
return {
"subject": subject,
"publicKey": custom_public,
"privateKey": custom_private,
}
if custom_public or custom_private:
logger.warning("VAPID_PUBLIC_KEY 与 VAPID_PRIVATE_KEY 必须成对配置,当前仅配置了其中一项")
return {
"subject": subject,
"publicKey": "",
"privateKey": "",
}
return {
"subject": f"mailto:{self.SUPERUSER or 'moviepilot'}@movie-pilot.org",
"publicKey": "BH3w49sZA6jXUnE-yt4jO6VKh73lsdsvwoJ6Hx7fmPIDKoqGiUl2GEoZzy-iJfn4SfQQcx7yQdHf9RknwrL_lSM",
"privateKey": "JTixnYY0vEw97t9uukfO3UWKfHKJdT5kCQDiv3gu894",
"subject": subject,
"publicKey": str(self._runtime_defaults.get("VAPID_PUBLIC_KEY") or "").strip(),
"privateKey": str(self._runtime_defaults.get("VAPID_PRIVATE_KEY") or "").strip(),
}
def MP_DOMAIN(self, url: Optional[str] = None) -> Optional[str]:

View File

@@ -603,6 +603,7 @@ SCHEMA_EXPORTS = {
'ValueData': ('app.schemas.common', 'ValueData'),
'WINDOWS_DRIVE_PATTERN': ('app.schemas.file', 'WINDOWS_DRIVE_PATTERN'),
'WebMessageItem': ('app.schemas.message', 'WebMessageItem'),
'WebPushPublicKeyData': ('app.schemas.message', 'WebPushPublicKeyData'),
'WebhookEventInfo': ('app.schemas.mediaserver', 'WebhookEventInfo'),
'WechatClawBotData': ('app.schemas.notification', 'WechatClawBotData'),
'WechatClawBotKnownTarget': ('app.schemas.notification', 'WechatClawBotKnownTarget'),

View File

@@ -391,6 +391,14 @@ class Subscription(BaseModel):
keys: Optional[dict[str, str]] = Field(default_factory=dict, description="推送订阅的加密公钥与认证密钥")
class WebPushPublicKeyData(BaseModel):
"""
浏览器 Web Push 订阅使用的 VAPID 公钥响应数据。
"""
public_key: str = Field(description="base64url 编码的未压缩 P-256 VAPID 公钥")
class SubscriptionMessage(BaseModel):
"""
客户端订阅消息体。

View File

@@ -154,6 +154,7 @@ def build_api_runtime_config(settings: Settings) -> ApiRuntimeConfig:
"""
从可热更新的部署设置构建一次 API 请求配置快照。
"""
vapid = settings.VAPID
return ApiRuntimeConfig(
access_token_expire_minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES,
btrfs_fsid_dedup=settings.BTRFS_FSID_DEDUP,
@@ -170,8 +171,9 @@ def build_api_runtime_config(settings: Settings) -> ApiRuntimeConfig:
movie_rename_format=settings.RENAME_FORMAT(MediaType.MOVIE),
television_rename_format=settings.RENAME_FORMAT(MediaType.TV),
music_rename_format=settings.RENAME_FORMAT(MediaType.MUSIC),
vapid_private_key=settings.VAPID.get("privateKey", ""),
vapid_subject=settings.VAPID.get("subject", ""),
vapid_public_key=vapid.get("publicKey", ""),
vapid_private_key=vapid.get("privateKey", ""),
vapid_subject=vapid.get("subject", ""),
cookiecloud_enable_local=bool(settings.COOKIECLOUD_ENABLE_LOCAL),
cookiecloud_auth_header=settings.COOKIECLOUD_AUTH_HEADER,
cookie_path=settings.COOKIE_PATH,

View File

@@ -189,10 +189,11 @@ def test_transfer_history_clear_requires_superuser():
def test_webpush_send_requires_superuser_and_subscribe_accepts_login_user():
"""
主动推送到全部浏览器订阅只允许管理员,订阅本身保持登录用户可用。
主动推送到全部浏览器订阅只允许管理员,订阅与读取公钥保持登录用户可用。
"""
assert _dependency_of(message_endpoint.send_notification, "_") is get_current_active_superuser
assert _dependency_of(message_endpoint.subscribe, "_") is verify_token
assert _dependency_of(message_endpoint.get_webpush_public_key, "_") is verify_token
def test_global_mutations_and_agent_file_access_keep_privilege_boundaries():

View File

@@ -169,12 +169,36 @@ def test_no_response_is_reported(browser, vapid):
send_webpush(browser.subscription, "x", vapid.private_key, "mailto:a@b.c")
def test_host_configured_vapid_key_signs(browser):
def test_host_configured_vapid_key_signs(browser, vapid, monkeypatch):
"""
宿主内置的 VAPID 私钥(base64url 原始格式)可以签出有效的 Authorization 头。
运行期注入的默认 VAPID 密钥对可以签出有效的 Authorization 头,且宿主源码不内置明文密钥。
"""
from app.runtime.config import settings
from app.runtime.settings import get_runtime_setting
public_b64 = _b64url(
vapid.public_key.public_bytes(
serialization.Encoding.X962,
serialization.PublicFormat.UncompressedPoint,
)
)
monkeypatch.setattr(settings, "VAPID_PUBLIC_KEY", None)
monkeypatch.setattr(settings, "VAPID_PRIVATE_KEY", None)
monkeypatch.setattr(settings, "VAPID_SUBJECT", None)
monkeypatch.setattr(settings, "_runtime_defaults", {})
empty_vapid = get_runtime_setting("VAPID")
assert empty_vapid["publicKey"] == ""
assert empty_vapid["privateKey"] == ""
monkeypatch.setattr(
settings,
"_runtime_defaults",
{
"VAPID_PUBLIC_KEY": public_b64,
"VAPID_PRIVATE_KEY": vapid.private_key,
},
)
vapid_config = get_runtime_setting("VAPID")
captured, patcher = _post()
with patcher:
@@ -184,3 +208,65 @@ def test_host_configured_vapid_key_signs(browser):
for item in captured["headers"]["Authorization"].partition(" ")[2].split(",")
)
assert _b64url(base64.urlsafe_b64decode(fields["k"] + "==")) == vapid_config["publicKey"]
def test_custom_vapid_settings_override_runtime_defaults_and_reject_partial_pair(browser, vapid, monkeypatch):
"""
显式成对配置的 VAPID 密钥与主体应优先于运行期默认值;仅配置单边密钥时不得混用默认值。
"""
from app.runtime.config import settings
other = Vapid()
other.generate_keys()
other_private = _b64url(other.private_key.private_numbers().private_value.to_bytes(32, "big"))
other_public = _b64url(
other.public_key.public_bytes(
serialization.Encoding.X962,
serialization.PublicFormat.UncompressedPoint,
)
)
default_public = _b64url(
vapid.public_key.public_bytes(
serialization.Encoding.X962,
serialization.PublicFormat.UncompressedPoint,
)
)
monkeypatch.setattr(
settings,
"_runtime_defaults",
{
"VAPID_PUBLIC_KEY": default_public,
"VAPID_PRIVATE_KEY": vapid.private_key,
},
)
monkeypatch.setattr(settings, "VAPID_PUBLIC_KEY", other_public)
monkeypatch.setattr(settings, "VAPID_PRIVATE_KEY", other_private)
monkeypatch.setattr(settings, "VAPID_SUBJECT", "mailto:custom@example.com")
vapid_config = settings.VAPID
assert vapid_config == {
"subject": "mailto:custom@example.com",
"publicKey": other_public,
"privateKey": other_private,
}
captured, patcher = _post()
with patcher:
send_webpush(browser.subscription, "x", vapid_config["privateKey"], vapid_config["subject"])
fields = dict(
item.strip().split("=", 1)
for item in captured["headers"]["Authorization"].partition(" ")[2].split(",")
)
assert _b64url(base64.urlsafe_b64decode(fields["k"] + "==")) == other_public
# 仅配置公钥或仅配置私钥时必须失效,避免公私钥错配。
monkeypatch.setattr(settings, "VAPID_PRIVATE_KEY", None)
partial_public = settings.VAPID
assert partial_public["publicKey"] == ""
assert partial_public["privateKey"] == ""
monkeypatch.setattr(settings, "VAPID_PUBLIC_KEY", None)
monkeypatch.setattr(settings, "VAPID_PRIVATE_KEY", other_private)
partial_private = settings.VAPID
assert partial_private["publicKey"] == ""
assert partial_private["privateKey"] == ""

View File

@@ -97,7 +97,11 @@ def test_send_notification_reports_all_delivery_failures(monkeypatch):
monkeypatch.setattr(
message_endpoint,
"get_api_runtime_config_snapshot",
lambda: SimpleNamespace(vapid_private_key="private", vapid_subject="mailto:test@example.com"),
lambda: SimpleNamespace(
vapid_public_key="public-key",
vapid_private_key="private",
vapid_subject="mailto:test@example.com",
),
)
from app.adapters.network.webpush import WebPushDeliveryError
@@ -125,7 +129,11 @@ def test_send_notification_reports_partial_delivery(monkeypatch):
monkeypatch.setattr(
message_endpoint,
"get_api_runtime_config_snapshot",
lambda: SimpleNamespace(vapid_private_key="private", vapid_subject="mailto:test@example.com"),
lambda: SimpleNamespace(
vapid_public_key="public-key",
vapid_private_key="private",
vapid_subject="mailto:test@example.com",
),
)
from app.adapters.network.webpush import WebPushDeliveryError
@@ -159,7 +167,11 @@ def _webpush_send_client(monkeypatch, user) -> tuple[TestClient, list[dict]]:
monkeypatch.setattr(
message_endpoint,
"get_api_runtime_config_snapshot",
lambda: SimpleNamespace(vapid_private_key="private", vapid_subject="mailto:test@example.com"),
lambda: SimpleNamespace(
vapid_public_key="public-key",
vapid_private_key="private",
vapid_subject="mailto:test@example.com",
),
)
monkeypatch.setattr(
"app.adapters.network.webpush.send_webpush",
@@ -255,3 +267,98 @@ def test_send_notification_allows_api_token(monkeypatch):
assert response.status_code == 200
assert response.json()["success"] is True
assert len(deliveries) == 1
def test_webpush_public_key_returns_active_key_for_logged_in_user(monkeypatch):
"""
已登录用户应能通过专用接口获取当前实例的 VAPID 公钥,匿名请求则被拒绝。
"""
user = _user(superuser=False)
client, _deliveries = _webpush_send_client(monkeypatch, user)
with client:
unauthenticated = client.get("/message/webpush/public-key")
authenticated = client.get(
"/message/webpush/public-key",
headers=_bearer(user),
)
assert unauthenticated.status_code in {401, 403}
assert authenticated.status_code == 200
assert authenticated.json() == {
"success": True,
"message": "",
"data": {"public_key": "public-key"},
}
def test_webpush_public_key_reports_unavailable_when_missing(monkeypatch):
"""
当前实例未获得有效 VAPID 公钥时,接口应返回明确的失败响应。
"""
user = _user(superuser=True)
client, _deliveries = _webpush_send_client(monkeypatch, user)
monkeypatch.setattr(
message_endpoint,
"get_api_runtime_config_snapshot",
lambda: SimpleNamespace(
vapid_public_key="",
vapid_private_key="",
vapid_subject="mailto:test@example.com",
),
)
with client:
response = client.get(
"/message/webpush/public-key",
headers=_bearer(user),
)
assert response.status_code == 200
body = response.json()
assert body["success"] is False
assert body["data"] is None
def test_vapid_private_key_is_excluded_from_env_and_cli_defaults(monkeypatch):
"""
VAPID 私钥必须被系统环境接口排除、被安全识别为凭据并在 CLI 中默认脱敏。
"""
import asyncio
from unittest.mock import Mock
from app import cli as cli_module
from app.api.endpoints import system as system_endpoint
from app.application.security.secrets import is_secret_setting_key
assert is_secret_setting_key("VAPID_PRIVATE_KEY") is True
assert "VAPID_PRIVATE_KEY" in cli_module.MASKED_FIELDS
captured_excludes: list[set[str]] = []
def fake_snapshot(*, exclude=None):
"""
记录 /system/env 排除的敏感配置键集合。
"""
captured_excludes.append(set(exclude or ()))
return {"VAPID_PUBLIC_KEY": "pub"}
monkeypatch.setattr(
system_endpoint,
"get_runtime_settings",
lambda: SimpleNamespace(snapshot=fake_snapshot),
)
monkeypatch.setattr(system_endpoint, "get_app_version", lambda: "test")
monkeypatch.setattr(system_endpoint, "get_frontend_version", lambda: "frontend-test")
monkeypatch.setattr(
system_endpoint,
"SitesHelper",
Mock(return_value=SimpleNamespace(auth_version="auth", indexer_version="indexer")),
)
runtime = SimpleNamespace(system=SimpleNamespace(runtime_features=lambda: {}))
resp = asyncio.run(system_endpoint.get_env_setting(_="token", runtime=runtime))
assert resp.success is True
assert captured_excludes and "VAPID_PRIVATE_KEY" in captured_excludes[0]
assert "VAPID_PRIVATE_KEY" not in resp.data