签名 URL 与 webhook
本篇签发带有效期的防篡改退订链接,并实现按原始请求体校验 HMAC 签名的入站 webhook 接口。适用于邮件免登录操作链接,以及安全接收第三方支付或代码托管平台的事件回调。
编写签名与回调接口#
工程基础见 第一个应用 与 HTTP 路由。生产环境中入站 webhook 遵循「先验原始字节签名与时间窗、再拦截重放、最后按事件 ID 幂等入库」的处理顺序:
flowchart LR
A["1. VerifiedWebhook 校验原始字节签名"] --> B["2. cache.once 拦截窗口内重放"]
B --> C["3. hook.json 解码并幂等落库"]第 1 步,新建 Cargo.toml:
[package]
name = "guide-signing-webhooks"
version = "0.0.5-alpha"
edition = "2024"
rust-version = "1.98.1"
[dependencies]
kxed = "0.0.5-alpha"第 2 步,新建 config/webhooks.toml,配置回调共享密钥(线上通过环境变量 KXED__WEBHOOKS__BILLING__SECRET 注入,切勿提交真实密钥):
[billing]
secret = "local-test-secret"第 3 步,实现退订签名链接与回调验签接口,写 src/main.rs:
use kxed::prelude::*;
use std::time::Duration;
/// `NAME` 对应配置段 `[webhooks.billing]`。
struct Billing;
impl WebhookSource for Billing {
const NAME: &'static str = "billing";
}
#[derive(Deserialize)]
struct BillingEvent {
id: String,
}
/// 签发 24 小时有效的退订链接;路径、查询参数或过期时间任一处被改动都会验签失败。
async fn invite(ctx: AppCtx) -> Result<String, AppErr> {
let link = ctx
.signer()?
.sign_url("/unsubscribe?u=7", Some(Duration::from_secs(86_400)))?;
Ok(format!("{link}\n"))
}
async fn unsubscribe() -> &'static str {
"unsubscribed\n"
}
/// 框架先按原始请求体校验签名,通过后业务再调用 `hook.json()` 反序列化。
async fn billing_hook(hook: VerifiedWebhook<Billing>) -> Result<String, AppErr> {
let event: BillingEvent = hook.json()?;
Ok(format!("received {}\n", event.id))
}
#[kxed::main]
async fn main() -> kxed::Result<()> {
App::new()
.webhook::<Billing>()
.routes(|router| {
router
.route("/invite", get(invite))
.route("/unsubscribe", get(unsubscribe).layer(require_signature()))
.route("/hooks/billing", post(billing_hook));
})
.run()
.await
}.webhook::<Billing>()将该回调源纳入./app config check与启动预检,密钥缺失时在启动阶段立即报错,并对配置文件中拼错的未注册来源名给出告警。- 签名 URL 与应用加解密依赖
app.key主密钥;默认Kxed协议的内部 webhook 若未单独配置secret,也会从app.key安全派生密钥。
验证#
先生成一把 64 字节随机 app.key 写入本地配置,然后启动应用:
printf 'key = "%s"\n' "$(openssl rand 64 | base64 | tr -d '\n')" > config/app.tomlcargo run获取退订签名链接,依次访问原链接、篡改参数 u=8 的链接与去掉签名的裸链接:
LINK=$(curl --fail --silent http://127.0.0.1:8080/invite)
curl --fail --silent "http://127.0.0.1:8080$LINK"
curl --silent --output /dev/null --write-out '%{http_code}\n' "http://127.0.0.1:8080$(printf '%s' "$LINK" | sed 's/u=7/u=8/')"
curl --silent --output /dev/null --write-out '%{http_code}\n' 'http://127.0.0.1:8080/unsubscribe?u=7'预期输出:
unsubscribed
403
403按 kxed 格式对 <时间戳>.<body> 计算 HMAC-SHA256,分别发送合法回调与篡改请求体的回调:
TS=$(date +%s)
BODY='{"id":"evt_1"}'
SIG=$(printf '%s.%s' "$TS" "$BODY" | openssl dgst -sha256 -hmac 'local-test-secret' | sed 's/^.*= //')
curl --fail --silent -H "kxed-timestamp: $TS" -H "kxed-signature: sha256=$SIG" -d "$BODY" http://127.0.0.1:8080/hooks/billing
curl --silent --output /dev/null --write-out '%{http_code}\n' -H "kxed-timestamp: $TS" -H "kxed-signature: sha256=$SIG" -d '{"id":"evt_2"}' http://127.0.0.1:8080/hooks/billing预期输出:
received evt_1
403- 原样访问签名 URL 返回
unsubscribed,篡改查询参数或移除签名参数均被require_signature()拒绝并返回403。 - 回调签名与原始字节一致时返回
received evt_1,复用同一签名替换 JSON 内容返回403。
加密与签名#
生产环境使用 openssl rand 64 | base64 | tr -d '\n' 生成 KXED__APP__KEY,同一集群的所有节点必须配置相同的主密钥。框架基于主密钥提供四类防篡改与加密能力:
| 调用入口 | 是否加密隐藏内容 | 典型用途 |
|---|---|---|
ctx.signer()?.sign_url(path, ttl) + require_signature() | 否(URL 参数可见,防篡改) | 邮件退订链接、临时文件下载链接、免登录确认跳转 |
ctx.signer()?.sign_token(purpose, &data, ttl) | 否(载荷可读,防伪造) | 跨步表单状态传递、短期一次性验证凭据 |
ctx.crypto()?.encrypt_json(purpose, &data) | 是(AEAD 密文) | 数据库存储第三方 API 密钥、敏感卡号或隐私字段 |
cookies.add_private(cookie) / add_signed(cookie) | private 加密,signed 仅防篡改 | 客户端保存敏感购物车状态或防篡改偏好设置 |
签名链接、短期签名凭据、JSON 字段加密与私有 Cookie 的调用方式如下:
use std::time::Duration;
async fn invite(ctx: AppCtx) -> Result<String, AppErr> {
let link = ctx.signer()?.sign_url("/unsubscribe?u=7", Some(Duration::from_secs(86_400)))?;
let token = ctx.signer()?.sign_token("invite", &7u64, Duration::from_secs(3_600))?;
let secret = ctx.crypto()?.encrypt_json("billing card", &kxed::serde_json::json!({"card": "4242"}))?;
Ok(format!("{link} {token} {secret}"))
}
async fn cart(cookies: Cookies) -> Result<&'static str, AppErr> {
cookies.add_private(Cookie::new("cart", "sku-7"))?;
Ok("ok")
}
router.route("/unsubscribe", get(|| async { "unsubscribed" }).layer(require_signature()));- 用途隔离与错误码:
sign_token与encrypt_json的第一个参数purpose绑定了业务用途,不同用途串签出的密文无法互相解密;签名不符或过期统一返回 403signature_invalid(sign_url在配置了app.url时自动拼成完整绝对地址)。 - 无感密钥轮换:更换主密钥时,把新密钥写入
app.key、旧密钥追加到app.previous_keys数组,过渡期内旧链接与存量密文仍可正常验证解密(详见 crypto README)。 - Cookie 安全默认项:
Cookies::add系列默认附加Secure属性(仅当app.url显式写成http://时省略);过期时间同时写入签名载荷内部,客户端篡改浏览器 Cookie 有效期无效。
接收 webhook#
对接外部平台回调时,在 impl WebhookSource 中指定 const SCHEME: WebhookScheme,并在 webhooks.<name>.secret 配置平台提供的签名密钥:
| 回调来源 | SCHEME 取值 | 自动校验的请求头 | secret 填什么 |
|---|---|---|---|
| Stripe | Stripe | Stripe-Signature(t=、v1=) | Stripe 后台提供的 whsec_... |
| GitHub | Github | X-Hub-Signature-256 | GitHub Webhook 设置中的 Secret |
| Standard Webhooks(Svix、Clerk、Resend 等) | StandardWebhooks | webhook-id、webhook-timestamp、webhook-signature(兼容 svix- 前缀) | whsec_ 开头的 Base64 密钥 |
| 自研服务或另一个 kxed 应用 | Kxed(默认) | Kxed-Signature、Kxed-Timestamp | 双方约定的随机密钥串 |
- 时间窗与平滑轮换:第三方协议必须配置
secret;缺少请求头、签名不匹配或时间戳偏差超过 5 分钟(GitHub 无时间戳头除外)统一返回 403signature_invalid。平台轮换密钥时将旧密钥放入webhooks.<name>.previous_secrets即可平滑过渡。 - 重放拦截:开启
cache(集群配 Redis)后调ctx.cache()?.once(&hook, async { .. }).await?拦截窗口内重放(首次返回Some,重复或处理中返回None,报错自动释放锁)。 - 落库幂等兜底:上游超时重投可能刷新时间戳并生成新签名,数据库表仍须对事件 ID 建唯一索引(见
SECURITY.md)。 - 跨服务隔离与出站投递:跨应用回调请配独立
secret,勿共用app.key;出站与测试调ctx.webhook::<Billing>()?.sign(&body)生成签名头,重试交由 Task 处理(见 webhook 示例)。
常见排错#
| 现象 | 原因 | 解决方法 |
|---|---|---|
签发链接或加解密返回 500 app_key_missing | 未配置主密钥 app.key | 运行 openssl rand 64 | base64 | tr -d '\n' 生成密钥写入 config/app.toml 或 KXED__APP__KEY |
访问刚签发的链接返回 403 signature_invalid | 前置反向代理剥离了 URL 路径前缀,或多节点 app.key 不一致 | 按代理转发给后端的实际路径签名,确保全集群节点共用同一把 app.key |
第三方 Webhook 始终返回 403 signature_invalid | SCHEME 与平台不匹配、填成了 API Key 而非 Webhook whsec_ 密钥,或服务器时钟偏差超 5 分钟 | 核对 WebhookSource::SCHEME 与平台签名密钥,校准机器 NTP 时间,确保 VerifiedWebhook 排在提取参数首位 |
参考#
- crypto README:密钥派生算法、密文格式与存量数据轮换步骤
- SPEC 的加密与签名:各平台 webhook 的签名原文拼接与去重键规则
- webhook 示例:包含出站投递重试、死信与入站验签的完整工程
- 认证:用户登录会话、受保护路由与角色授权