feat: add GitHub sign-in and channel webhooks

This commit is contained in:
Loki 2026-10-24 15:02:42 +02:00
parent 45e89f9826
commit ff9c8f330e
Signed by: boba
GPG key ID: 253067914055423B
36 changed files with 3240 additions and 24 deletions

View file

@ -0,0 +1,178 @@
//! The only HTTP webhook surface accepts scoped delivery credentials, never management sessions.
use super::{MAX_BODY, management, now_ms, secrets, valid_content};
use crate::{
net::state::{BroadcastMsg, State as Gateway},
proto::{ChatMessagePayload, PacketId, encode_packet, to_payload},
};
use axum::{
Json, Router,
body::Bytes,
extract::{DefaultBodyLimit, Path, State},
http::{HeaderMap, StatusCode},
routing::post,
};
use serde::Deserialize;
pub fn router(state: Gateway) -> Router {
Router::new()
.route("/v1/webhooks/{id}", post(deliver))
.layer(DefaultBodyLimit::max(MAX_BODY))
.with_state(state)
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct Payload {
content: String,
}
fn header<'a>(headers: &'a HeaderMap, key: &str) -> Option<&'a str> {
headers.get(key)?.to_str().ok()
}
fn delivery_id(s: &str) -> bool {
(8..=128).contains(&s.len())
&& s.bytes()
.all(|b| b.is_ascii_alphanumeric() || b"-_.:".contains(&b))
}
pub async fn accept(
state: &Gateway,
id: &str,
headers: &HeaderMap,
body: &[u8],
) -> Result<bool, StatusCode> {
let _slot = state
.webhooks
.deliveries
.try_acquire()
.map_err(|_| StatusCode::TOO_MANY_REQUESTS)?;
if body.len() > MAX_BODY {
return Err(StatusCode::PAYLOAD_TOO_LARGE);
}
let hook = state
.storage
.hook(id)
.await
.map_err(|_| StatusCode::SERVICE_UNAVAILABLE)?
.filter(|h| h.revoked_at.is_none() && h.direction == "incoming")
.ok_or(StatusCode::UNAUTHORIZED)?;
let (content, delivery) = if hook.provider == "github" {
let key = state
.webhooks
.key()
.ok_or(StatusCode::SERVICE_UNAVAILABLE)?;
let secret = secrets::open(key, id, &hook.sealed_secret)
.map_err(|_| StatusCode::SERVICE_UNAVAILABLE)?;
if !secrets::verify(
&secret,
body,
header(headers, "x-hub-signature-256").unwrap_or_default(),
) {
return Err(StatusCode::UNAUTHORIZED);
}
let delivery = header(headers, "x-github-delivery")
.ok_or(StatusCode::BAD_REQUEST)?
.to_owned();
let event = header(headers, "x-github-event").ok_or(StatusCode::BAD_REQUEST)?;
if !["push", "pull_request", "issues", "release", "ping"].contains(&event) {
return Err(StatusCode::UNPROCESSABLE_ENTITY);
}
let data: serde_json::Value =
serde_json::from_slice(body).map_err(|_| StatusCode::BAD_REQUEST)?;
// Never copy arbitrary descriptions/URLs/mentions into chat: predictable provider summary only.
let repo = data
.pointer("/repository/full_name")
.and_then(|v| v.as_str())
.unwrap_or("repository");
let actor = data
.pointer("/sender/login")
.and_then(|v| v.as_str())
.unwrap_or("GitHub");
if [repo, actor].iter().any(|v| {
v.len() > 200
|| !v
.bytes()
.all(|b| b.is_ascii_alphanumeric() || b"-_./".contains(&b))
}) {
return Err(StatusCode::BAD_REQUEST);
}
(format!("GitHub · {repo}: {event} ({actor})"), delivery)
} else {
let supplied = header(headers, "authorization")
.and_then(|v| v.strip_prefix("Bearer "))
.filter(|v| v.len() == 64)
.ok_or(StatusCode::UNAUTHORIZED)?;
use subtle::ConstantTimeEq;
let actual = secrets::digest(supplied.as_bytes());
if !bool::from(actual.as_bytes().ct_eq(hook.token_hash.as_bytes())) {
return Err(StatusCode::UNAUTHORIZED);
}
let delivery = header(headers, "idempotency-key")
.map(str::to_owned)
.unwrap_or_else(|| uuid::Uuid::new_v4().to_string());
let payload: Payload = serde_json::from_slice(body).map_err(|_| StatusCode::BAD_REQUEST)?;
(payload.content, delivery)
};
if !delivery_id(&delivery) || !valid_content(&content) {
return Err(StatusCode::BAD_REQUEST);
}
if !state.webhooks.consume(id) {
return Err(StatusCode::TOO_MANY_REQUESTS);
}
// Permission removal, guild/channel deletion or a changed channel scope disables delivery immediately.
if management::authorize(state, &hook.creator_id, &hook.channel_id)
.await
.map_err(|_| StatusCode::SERVICE_UNAVAILABLE)?
.as_deref()
!= Some(hook.guild_id.as_str())
{
return Err(StatusCode::FORBIDDEN);
}
let msg = ChatMessagePayload {
message_id: uuid::Uuid::new_v4().to_string(),
channel_id: hook.channel_id,
sender_id: format!("webhook:{id}"),
content,
timestamp: now_ms(),
edited: false,
reply_to: None,
};
let added = state
.storage
.save_webhook_message(
&msg,
Some((id, &delivery, &secrets::digest(body), &hook.token_hash)),
)
.await
.map_err(|e| {
if e.to_string() == "idempotency conflict" {
StatusCode::CONFLICT
} else {
StatusCode::SERVICE_UNAVAILABLE
}
})?;
if added {
state.metrics.inc(&state.metrics.messages_sent);
let _ = state.broadcast.send(BroadcastMsg {
channel_id: Some(msg.channel_id.clone()),
exclude_session: None,
target_session_id: None,
data: encode_packet(PacketId::ChatMessage, 0, &to_payload(&msg)),
});
}
Ok(added)
}
async fn deliver(
State(state): State<Gateway>,
Path(id): Path<String>,
headers: HeaderMap,
body: Bytes,
) -> Result<(StatusCode, Json<serde_json::Value>), StatusCode> {
let added = accept(&state, &id, &headers, &body).await?;
Ok((
if added {
StatusCode::CREATED
} else {
StatusCode::OK
},
Json(serde_json::json!({"accepted":true,"duplicate":!added})),
))
}

View file

@ -0,0 +1,189 @@
//! Management is available only inside an authenticated encrypted LNEx session.
use super::{now_ms, policy, secrets};
use crate::{
domain::{permissions::Permissions, storage::webhooks::Hook},
handler::Ctx,
net::{io, state::State},
proto::*,
};
use anyhow::Result;
use prost::Message;
use tokio::io::{AsyncRead, AsyncWrite};
pub async fn authorize(state: &State, user: &str, channel: &str) -> Result<Option<String>> {
let Some((guild_id, owner, memberships)) = state.storage.webhook_scope(channel, user).await?
else {
return Ok(None);
};
if owner == user {
return Ok(Some(guild_id));
}
if memberships == 0 {
return Ok(None);
}
let roles = state.storage.get_user_role_perms(&guild_id, user).await?;
Ok(Permissions::from_role_perms(&roles)
.has(Permissions::MANAGE_WEBHOOKS)
.then_some(guild_id))
}
fn info(h: &Hook) -> WebhookInfo {
WebhookInfo {
id: h.id.clone(),
channel_id: h.channel_id.clone(),
name: h.name.clone(),
direction: h.direction.clone(),
provider: h.provider.clone(),
endpoint: h.endpoint.clone(),
created_at: h.created_at,
revoked: h.revoked_at.is_some(),
suspended_reason: h.suspended_reason.clone().unwrap_or_default(),
}
}
pub async fn handle<S: AsyncRead + AsyncWrite + Unpin>(
ctx: &mut Ctx<'_, S>,
session_id: &str,
pid: PacketId,
payload: &[u8],
) -> Result<()> {
let Some(session) = crate::domain::session::get(&ctx.state.sessions, session_id).await else {
return Ok(());
};
if !ctx.state.rate_limiter.try_consume(session_id) {
return error(ctx, "rate limited").await;
}
if payload.len() > 8192 {
return error(ctx, "webhook management payload too large").await;
}
let req = WebhookRequest::decode(payload)?;
let existing = if pid == PacketId::WebhookRotate || pid == PacketId::WebhookRevoke {
ctx.state.storage.hook(&req.id).await?
} else {
None
};
let channel = existing
.as_ref()
.map(|h| h.channel_id.as_str())
.unwrap_or(&req.channel_id);
let Some(guild) = authorize(ctx.state, &session.user_id, channel).await? else {
return error(ctx, "permission denied").await;
};
if pid == PacketId::WebhookList {
let hooks = ctx
.state
.storage
.hooks(channel)
.await?
.iter()
.map(info)
.collect();
return io::send_encrypted(
ctx.stream,
PacketId::WebhookListResult,
ctx.seq,
&to_payload(&WebhookListResult { hooks }),
ctx.crypto,
)
.await;
}
let mut secret = String::new();
let hook = if pid == PacketId::WebhookCreate {
if req.name.trim().is_empty()
|| req.name.chars().count() > 64
|| req.name.chars().any(char::is_control)
{
return error(ctx, "invalid name").await;
}
if !matches!(
(req.direction.as_str(), req.provider.as_str()),
("incoming", "generic" | "github") | ("outgoing", "generic")
) {
return error(ctx, "unsupported webhook type").await;
}
if req.direction == "outgoing" && policy::endpoint(&req.endpoint).is_err() {
return error(
ctx,
"HTTPS public endpoint required; no credentials/query/fragment",
)
.await;
}
let id = uuid::Uuid::new_v4().to_string();
secret = secrets::new_secret();
let sealed = if req.direction == "outgoing" || req.provider == "github" {
let Some(key) = ctx.state.webhooks.key() else {
return error(ctx, "webhook master key not configured").await;
};
secrets::seal(key, &id, &secret)?
} else {
Vec::new()
};
let h = Hook {
id,
channel_id: channel.into(),
guild_id: guild,
creator_id: session.user_id,
name: req.name,
direction: req.direction.clone(),
provider: req.provider,
endpoint: if req.direction == "outgoing" {
req.endpoint
} else {
String::new()
},
token_hash: secrets::digest(secret.as_bytes()),
sealed_secret: sealed,
created_at: now_ms(),
revoked_at: None,
suspended_reason: None,
};
ctx.state.storage.insert_hook(&h).await?;
h
} else {
let Some(mut h) = existing.filter(|h| h.revoked_at.is_none()) else {
return error(ctx, "webhook not found").await;
};
if pid == PacketId::WebhookRevoke {
ctx.state.storage.revoke_hook(&h.id).await?;
h.revoked_at = Some(now_ms());
} else {
secret = secrets::new_secret();
let sealed = if h.direction == "outgoing" || h.provider == "github" {
let Some(key) = ctx.state.webhooks.key() else {
return error(ctx, "webhook master key not configured").await;
};
secrets::seal(key, &h.id, &secret)?
} else {
Vec::new()
};
ctx.state
.storage
.rotate_hook(&h.id, &secrets::digest(secret.as_bytes()), &sealed)
.await?;
h.suspended_reason = None;
}
h
};
io::send_encrypted(
ctx.stream,
PacketId::WebhookResult,
ctx.seq,
&to_payload(&WebhookResult {
hook: Some(info(&hook)),
secret,
}),
ctx.crypto,
)
.await
}
async fn error<S: AsyncRead + AsyncWrite + Unpin>(ctx: &mut Ctx<'_, S>, msg: &str) -> Result<()> {
io::send_encrypted(
ctx.stream,
PacketId::Error,
ctx.seq,
&to_payload(&ErrorPayload {
code: ErrorCode::PermissionDenied as u32,
message: msg.into(),
}),
ctx.crypto,
)
.await
}

100
gateway/src/webhooks/mod.rs Normal file
View file

@ -0,0 +1,100 @@
//! Channel-scoped incoming integrations and bounded signed outgoing delivery.
pub mod incoming;
pub mod management;
pub mod outgoing;
pub mod policy;
pub mod secrets;
use anyhow::{Result, bail};
use std::{
collections::HashMap,
sync::{Mutex, OnceLock},
time::Instant,
};
pub const MAX_BODY: usize = 64 * 1024;
pub const MAX_CONTENT: usize = 4000;
/// Secrets are intentionally not Debug and never enter request URLs or logs.
pub struct Runtime {
deliveries: tokio::sync::Semaphore,
key: OnceLock<[u8; 32]>,
rates: Mutex<HashMap<String, (f64, Instant)>>,
}
impl Default for Runtime {
fn default() -> Self {
Self {
deliveries: tokio::sync::Semaphore::new(64),
key: OnceLock::new(),
rates: Mutex::new(HashMap::new()),
}
}
}
impl Runtime {
pub fn configure_from_env(&self) -> Result<()> {
if let Ok(encoded) = std::env::var("VNOX_WEBHOOK_SECRET_KEY") {
let raw = hex::decode(encoded.trim())
.ok()
.and_then(|v| v.try_into().ok());
let Some(key) = raw else {
bail!("VNOX_WEBHOOK_SECRET_KEY must contain exactly 32 hex-encoded bytes")
};
self.set_key(key)?;
}
Ok(())
}
pub fn set_key(&self, key: [u8; 32]) -> Result<()> {
self.key
.set(key)
.map_err(|_| anyhow::anyhow!("webhook master key already configured"))
}
pub fn key(&self) -> Option<&[u8; 32]> {
self.key.get()
}
pub fn consume(&self, id: &str) -> bool {
let Ok(mut rates) = self.rates.lock() else {
return false;
};
if rates.len() >= 4096 {
rates.retain(|_, (_, at)| at.elapsed().as_secs() < 300);
if !rates.contains_key(id) && rates.len() >= 4096 {
return false;
}
}
let (tokens, last) = rates.entry(id.into()).or_insert((10.0, Instant::now()));
*tokens = (*tokens + last.elapsed().as_secs_f64() * 2.0).min(10.0);
*last = Instant::now();
if *tokens < 1.0 {
return false;
}
*tokens -= 1.0;
true
}
}
pub(crate) fn now_ms() -> i64 {
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap_or_default()
.as_millis() as i64
}
pub(crate) fn valid_content(content: &str) -> bool {
let lowered = content.to_lowercase();
!content.trim().is_empty()
&& content.chars().count() <= MAX_CONTENT
&& !lowered.contains("@everyone")
&& !lowered.contains("@here")
&& !lowered.contains("<@")
&& !content
.chars()
.any(|c| c.is_control() && c != '\n' && c != '\t')
}
#[cfg(test)]
mod tests;

View file

@ -0,0 +1,81 @@
//! Single-process durable worker. Every attempt validates and pins all DNS results.
use super::{management, now_ms, policy, secrets};
use crate::{
domain::storage::webhooks::{Delivery, Hook},
net::state::State,
};
use std::time::Duration;
pub async fn run(state: State) {
let mut interval = tokio::time::interval(Duration::from_secs(1));
loop {
interval.tick().await;
let jobs = match state.storage.due_webhooks().await {
Ok(j) => j,
Err(_) => {
tracing::warn!("webhook outbox read failed");
continue;
}
};
for job in jobs {
let hook = match state.storage.hook(&job.hook_id).await {
Ok(Some(h)) if h.revoked_at.is_none() => h,
Ok(_) => {
let _ = state.storage.finish_webhook(&job, true).await;
continue;
}
Err(_) => {
tracing::warn!("webhook configuration read failed");
continue;
}
};
// Never forward channel contents after the integration creator loses permission.
let authorized = management::authorize(&state, &hook.creator_id, &hook.channel_id)
.await
.ok()
.flatten()
.as_deref()
== Some(hook.guild_id.as_str());
let success = authorized && attempt(&state, &hook, &job).await.is_ok();
if state.storage.finish_webhook(&job, success).await.is_err() {
tracing::warn!("webhook outbox update failed")
}
}
}
}
async fn attempt(state: &State, hook: &Hook, job: &Delivery) -> anyhow::Result<()> {
let key = state
.webhooks
.key()
.ok_or_else(|| anyhow::anyhow!("signing unavailable"))?;
let secret = secrets::open(key, &hook.id, &hook.sealed_secret)?;
let url = policy::endpoint(&hook.endpoint)?;
let addresses = policy::resolve(&url).await?;
let host = url
.host_str()
.ok_or_else(|| anyhow::anyhow!("missing host"))?;
let client = reqwest::Client::builder()
.https_only(true)
.no_proxy()
.redirect(reqwest::redirect::Policy::none())
.timeout(Duration::from_secs(10))
.resolve_to_addrs(host, &addresses)
.build()?;
let timestamp = (now_ms() / 1000).to_string();
let signed = format!("{timestamp}.{}", job.body);
let response = client
.post(url)
.header("content-type", "application/json")
.header("x-vnox-delivery", &job.id)
.header("x-vnox-timestamp", timestamp)
.header(
"x-vnox-signature",
format!("sha256={}", secrets::sign(&secret, signed.as_bytes())),
)
.body(job.body.clone())
.send()
.await?;
anyhow::ensure!(response.status().is_success(), "delivery not accepted");
// The response body is deliberately never buffered or logged.
Ok(())
}

View file

@ -0,0 +1,121 @@
use anyhow::{Result, bail};
use std::net::{IpAddr, SocketAddr};
use url::Url;
pub fn endpoint(value: &str) -> Result<Url> {
let url = Url::parse(value)?;
if url.scheme() != "https"
|| url.host_str().is_none()
|| !url.username().is_empty()
|| url.password().is_some()
|| url.fragment().is_some()
|| url.query().is_some()
|| value.len() > 2048
{
bail!("webhook target must be an HTTPS URL without credentials, query or fragment")
}
if let Ok(ip) = url
.host_str()
.unwrap_or_default()
.trim_matches(['[', ']'])
.parse::<IpAddr>()
&& !public_ip(ip)
{
bail!("webhook target address is not public")
}
Ok(url)
}
pub fn public_ip(ip: IpAddr) -> bool {
match ip {
IpAddr::V4(ip) => {
let [a, b, c, _] = ip.octets();
!(ip.is_private()
|| ip.is_loopback()
|| ip.is_link_local()
|| ip.is_broadcast()
|| ip.is_documentation()
|| ip.is_unspecified()
|| ip.is_multicast()
|| a == 0
|| a >= 224
|| (a == 100 && (64..=127).contains(&b))
|| (a == 192 && b == 0 && c == 0)
|| (a == 192 && b == 88 && c == 99)
|| (a == 198 && (b == 18 || b == 19)))
}
IpAddr::V6(ip) => {
if let Some(v4) = ip.to_ipv4_mapped() {
return public_ip(IpAddr::V4(v4));
}
let s = ip.segments();
(0x2000..=0x3fff).contains(&s[0])
&& s[0] != 0x2002
&& s[0] != 0x3ffe
&& !(s[0] == 0x2001 && (s[1] <= 0x01ff || s[1] == 0x0db8))
&& !(s[0] == 0x3fff && s[1] <= 0x0fff)
}
}
}
/// Resolve every attempt and pin the same validated addresses into the HTTP client.
/// Mixed public/private answers are rejected rather than trusting resolver ordering.
pub async fn resolve(url: &Url) -> Result<Vec<SocketAddr>> {
let host = url
.host_str()
.ok_or_else(|| anyhow::anyhow!("missing target host"))?
.trim_matches(['[', ']']);
let addresses = tokio::time::timeout(
std::time::Duration::from_secs(3),
tokio::net::lookup_host((host, url.port_or_known_default().unwrap_or(443))),
)
.await??
.collect::<Vec<_>>();
if addresses.len() > 32 || addresses.is_empty() || addresses.iter().any(|a| !public_ip(a.ip()))
{
bail!("webhook target DNS contains a non-public address")
}
Ok(addresses)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn denies_internal_special_and_mapped_addresses() {
for value in [
"127.0.0.1",
"10.1.2.3",
"169.254.169.254",
"100.64.0.1",
"192.0.0.1",
"198.18.0.1",
"224.0.0.1",
"::1",
"::ffff:127.0.0.1",
"fe80::1",
"fc00::1",
"2001:db8::1",
"2002:a00:1::1",
"3fff::1",
] {
assert!(!public_ip(value.parse().unwrap()), "{value}");
}
for value in ["8.8.8.8", "1.1.1.1", "2606:4700:4700::1111"] {
assert!(public_ip(value.parse().unwrap()))
}
}
#[test]
fn urls_require_clean_https_origin_and_path() {
for value in [
"http://example.org",
"https://user:pass@example.org",
"https://example.org/?token=x",
"https://127.0.0.1",
"file:///etc/passwd",
] {
assert!(endpoint(value).is_err());
}
assert!(endpoint("https://example.org/events").is_ok());
}
}

View file

@ -0,0 +1,93 @@
use anyhow::{Result, bail};
use chacha20poly1305::{
ChaCha20Poly1305, KeyInit, Nonce,
aead::{Aead, Payload},
};
use hmac::{Hmac, Mac};
use rand::Rng;
use sha2::{Digest, Sha256};
pub fn new_secret() -> String {
hex::encode(rand::random::<[u8; 32]>())
}
pub fn digest(secret: &[u8]) -> String {
hex::encode(Sha256::digest(secret))
}
pub fn seal(master: &[u8; 32], id: &str, secret: &str) -> Result<Vec<u8>> {
let cipher = ChaCha20Poly1305::new_from_slice(master)
.map_err(|_| anyhow::anyhow!("invalid webhook key"))?;
let mut nonce = [0u8; 12];
rand::rng().fill_bytes(&mut nonce);
let encrypted = cipher
.encrypt(
&Nonce::from(nonce),
Payload {
msg: secret.as_bytes(),
aad: id.as_bytes(),
},
)
.map_err(|_| anyhow::anyhow!("could not protect webhook signing secret"))?;
Ok([nonce.as_slice(), encrypted.as_slice()].concat())
}
pub fn open(master: &[u8; 32], id: &str, encoded: &[u8]) -> Result<String> {
if encoded.len() < 28 {
bail!("invalid protected webhook secret")
}
let nonce = <[u8; 12]>::try_from(&encoded[..12])?;
let cipher = ChaCha20Poly1305::new_from_slice(master)
.map_err(|_| anyhow::anyhow!("invalid webhook key"))?;
let plain = cipher
.decrypt(
&Nonce::from(nonce),
Payload {
msg: &encoded[12..],
aad: id.as_bytes(),
},
)
.map_err(|_| anyhow::anyhow!("webhook signing secret could not be opened"))?;
String::from_utf8(plain).map_err(|_| anyhow::anyhow!("invalid webhook signing secret"))
}
pub fn sign(secret: &str, body: &[u8]) -> String {
let mut mac = <Hmac<Sha256> as hmac::digest::KeyInit>::new_from_slice(secret.as_bytes())
.expect("HMAC permits any key length");
mac.update(body);
hex::encode(mac.finalize().into_bytes())
}
pub fn verify(secret: &str, body: &[u8], signature: &str) -> bool {
let Some(raw) = signature
.strip_prefix("sha256=")
.and_then(|s| hex::decode(s).ok())
else {
return false;
};
let Ok(mut mac) = <Hmac<Sha256> as hmac::digest::KeyInit>::new_from_slice(secret.as_bytes())
else {
return false;
};
mac.update(body);
mac.verify_slice(&raw).is_ok()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn github_reference_signature_and_tampering() {
let key = "It's a Secret to Everybody";
let body = b"Hello, World!";
let signature = "sha256=757107ea0eb2509fc211221cce984b8a37570b6d7586c22c46f4379c8b043e17";
assert!(verify(key, body, signature));
assert!(!verify(key, b"changed", signature));
}
#[test]
fn protected_secret_is_bound_to_hook_identity() {
let blob = seal(&[7; 32], "first", "secret").unwrap();
assert_eq!(open(&[7; 32], "first", &blob).unwrap(), "secret");
assert!(open(&[7; 32], "second", &blob).is_err());
assert!(open(&[8; 32], "first", &blob).is_err());
}
}

View file

@ -0,0 +1,436 @@
use super::*;
use crate::{
domain::{
channels, session,
storage::{Storage, webhooks::Hook},
},
net::state::State,
proto::ChatMessagePayload,
};
use axum::http::{HeaderMap, HeaderValue, StatusCode};
use std::sync::{Arc, atomic::AtomicUsize};
async fn fixture() -> (State, Hook, String) {
let storage = Storage::connect_sqlite(":memory:").await.unwrap();
let guild = storage.create_guild("owner", "test").await.unwrap();
storage
.create_channel("target", "target", "text", Some(&guild))
.await
.unwrap();
let config = toml::from_str(include_str!("../../../dev/config.toml")).unwrap();
let dir = std::env::temp_dir().join(format!("vnox-hook-test-{}", uuid::Uuid::new_v4()));
let identity =
crate::bootstrap::server_identity::ServerIdentity::load_or_generate(&dir).unwrap();
std::fs::remove_file(dir.join("server_identity.json")).unwrap();
std::fs::remove_dir(dir).unwrap();
let (broadcast, _) = tokio::sync::broadcast::channel(16);
let state = State::new(
session::new_store(),
channels::new_store(),
Arc::new(storage),
Arc::new(config),
Arc::new(identity),
broadcast,
crate::admin::metrics::Metrics::new(),
Arc::new(AtomicUsize::new(0)),
Arc::new(AtomicUsize::new(0)),
None,
);
state.webhooks.set_key([7; 32]).unwrap();
let secret = secrets::new_secret();
let hook = Hook {
id: "incoming".into(),
channel_id: "target".into(),
guild_id: guild,
creator_id: "owner".into(),
name: "CI".into(),
direction: "incoming".into(),
provider: "generic".into(),
endpoint: String::new(),
token_hash: secrets::digest(secret.as_bytes()),
sealed_secret: Vec::new(),
created_at: now_ms(),
revoked_at: None,
suspended_reason: None,
};
state.storage.insert_hook(&hook).await.unwrap();
(state, hook, secret)
}
fn headers(secret: &str, id: &str) -> HeaderMap {
let mut h = HeaderMap::new();
h.insert(
"authorization",
HeaderValue::from_str(&format!("Bearer {secret}")).unwrap(),
);
h.insert("idempotency-key", HeaderValue::from_str(id).unwrap());
h
}
#[tokio::test]
async fn incoming_auth_scope_identity_and_idempotency() {
let (s, h, key) = fixture().await;
let body = br#"{"content":"build passed"}"#;
assert_eq!(
incoming::accept(&s, &h.id, &HeaderMap::new(), body).await,
Err(StatusCode::UNAUTHORIZED)
);
assert_eq!(
incoming::accept(&s, &h.id, &headers(&"0".repeat(64), "delivery1"), body).await,
Err(StatusCode::UNAUTHORIZED)
);
let auth = headers(&key, "delivery1");
assert_eq!(incoming::accept(&s, &h.id, &auth, body).await, Ok(true));
assert_eq!(incoming::accept(&s, &h.id, &auth, body).await, Ok(false));
assert_eq!(
incoming::accept(&s, &h.id, &auth, br#"{"content":"other"}"#).await,
Err(StatusCode::CONFLICT)
);
let history = s.storage.get_history("target", 100).await.unwrap();
assert_eq!(history.len(), 1);
assert_eq!(history[0].sender_id, "webhook:incoming");
assert!(
s.storage
.get_history("general", 10)
.await
.unwrap()
.is_empty()
);
}
#[tokio::test]
async fn rejects_impersonation_mentions_large_payloads_and_revoked_keys() {
let (s, h, key) = fixture().await;
let auth = headers(&key, "delivery1");
for body in [
br#"{"content":"hello","sender_id":"owner"}"#.as_slice(),
br#"{"content":"@everyone"}"#,
br#"{"content":"<@123>"}"#,
] {
assert_eq!(
incoming::accept(&s, &h.id, &auth, body).await,
Err(StatusCode::BAD_REQUEST)
);
}
assert_eq!(
incoming::accept(&s, &h.id, &auth, &vec![b' '; MAX_BODY + 1]).await,
Err(StatusCode::PAYLOAD_TOO_LARGE)
);
let rotated = secrets::new_secret();
s.storage
.rotate_hook(&h.id, &secrets::digest(rotated.as_bytes()), &[])
.await
.unwrap();
assert_eq!(
incoming::accept(&s, &h.id, &auth, br#"{"content":"hi"}"#).await,
Err(StatusCode::UNAUTHORIZED)
);
s.storage.revoke_hook(&h.id).await.unwrap();
assert_eq!(
incoming::accept(
&s,
&h.id,
&headers(&rotated, "delivery2"),
br#"{"content":"hi"}"#
)
.await,
Err(StatusCode::UNAUTHORIZED)
);
}
#[tokio::test]
async fn management_requires_membership_even_with_stale_privileged_role() {
let (s, h, _) = fixture().await;
assert!(
management::authorize(&s, "owner", "target")
.await
.unwrap()
.is_some()
);
assert!(
management::authorize(&s, "stranger", "target")
.await
.unwrap()
.is_none()
);
assert!(
management::authorize(&s, "owner", "general")
.await
.unwrap()
.is_none()
);
s.storage
.add_guild_member(&h.guild_id, "member")
.await
.unwrap();
assert!(
management::authorize(&s, "member", "target")
.await
.unwrap()
.is_none()
);
if let crate::domain::storage::Pool::Sqlite(p) = &s.storage.pool {
sqlx::query("INSERT INTO member_roles(guild_id,user_id,role_id) SELECT guild_id,$1,id FROM roles WHERE guild_id=$2").bind("member").bind(&h.guild_id).execute(p).await.unwrap();
}
assert!(
management::authorize(&s, "member", "target")
.await
.unwrap()
.is_some()
);
s.storage
.remove_guild_member(&h.guild_id, "member")
.await
.unwrap();
assert!(
management::authorize(&s, "member", "target")
.await
.unwrap()
.is_none()
);
}
#[tokio::test]
async fn outbox_is_transactional_bounded_and_retries_are_finite() {
let (s, mut h, key) = fixture().await;
h.id = "outgoing".into();
h.direction = "outgoing".into();
h.endpoint = "https://example.com/hook".into();
h.sealed_secret = secrets::seal(&[7; 32], &h.id, &key).unwrap();
s.storage.insert_hook(&h).await.unwrap();
let msg = ChatMessagePayload {
message_id: "event1".into(),
channel_id: "target".into(),
sender_id: "owner".into(),
content: "hello".into(),
timestamp: now_ms(),
edited: false,
reply_to: None,
};
assert!(s.storage.save_webhook_message(&msg, None).await.unwrap());
assert!(!s.storage.save_webhook_message(&msg, None).await.unwrap());
let mut jobs = s.storage.due_webhooks().await.unwrap();
assert_eq!(jobs.len(), 1);
let job = jobs.pop().unwrap();
assert!(job.body.contains("message.created"));
s.storage.finish_webhook(&job, false).await.unwrap();
assert!(s.storage.due_webhooks().await.unwrap().is_empty());
let terminal = crate::domain::storage::webhooks::Delivery { attempts: 7, ..job };
s.storage.finish_webhook(&terminal, false).await.unwrap();
if let crate::domain::storage::Pool::Sqlite(p) = &s.storage.pool {
let (n,): (i64,) = sqlx::query_as("SELECT COUNT(*) FROM webhook_outbox")
.fetch_one(p)
.await
.unwrap();
assert_eq!(n, 0);
}
for i in 0..130 {
let mut m = msg.clone();
m.message_id = format!("event{i}");
s.storage.save_webhook_message(&m, None).await.unwrap();
}
assert_eq!(
s.storage
.hook(&h.id)
.await
.unwrap()
.unwrap()
.suspended_reason
.as_deref(),
Some("queue_full")
);
if let crate::domain::storage::Pool::Sqlite(p) = &s.storage.pool {
let (n,): (i64,) = sqlx::query_as("SELECT COUNT(*) FROM webhook_outbox")
.fetch_one(p)
.await
.unwrap();
assert_eq!(n, 128);
}
s.storage.revoke_hook(&h.id).await.unwrap();
assert!(s.storage.due_webhooks().await.unwrap().is_empty());
}
#[tokio::test]
async fn github_requires_valid_raw_body_signature_and_deduplicates() {
let (s, mut h, key) = fixture().await;
h.id = "github".into();
h.provider = "github".into();
h.sealed_secret = secrets::seal(&[7; 32], &h.id, &key).unwrap();
s.storage.insert_hook(&h).await.unwrap();
let body = br#"{"repository":{"full_name":"owner/repo"},"sender":{"login":"alice"}}"#;
let mut headers = HeaderMap::new();
headers.insert("x-github-delivery", HeaderValue::from_static("delivery1"));
headers.insert("x-github-event", HeaderValue::from_static("push"));
assert_eq!(
incoming::accept(&s, &h.id, &headers, body).await,
Err(StatusCode::UNAUTHORIZED)
);
headers.insert(
"x-hub-signature-256",
HeaderValue::from_str(&format!("sha256={}", secrets::sign(&key, body))).unwrap(),
);
assert_eq!(incoming::accept(&s, &h.id, &headers, body).await, Ok(true));
assert_eq!(incoming::accept(&s, &h.id, &headers, body).await, Ok(false));
assert_eq!(
incoming::accept(&s, &h.id, &headers, b"changed").await,
Err(StatusCode::UNAUTHORIZED)
);
}
#[tokio::test]
async fn http_delivery_route_enforces_auth_and_streamed_body_limit() {
let (state, hook, key) = fixture().await;
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let address = listener.local_addr().unwrap();
let task = tokio::spawn(async move {
axum::serve(listener, incoming::router(state))
.await
.unwrap()
});
let client = reqwest::Client::builder().no_proxy().build().unwrap();
let target = format!("http://{address}/v1/webhooks/{}", hook.id);
let response = client
.post(&target)
.json(&serde_json::json!({"content":"hello"}))
.send()
.await
.unwrap();
assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
let response = client
.post(&target)
.bearer_auth(&key)
.json(&serde_json::json!({"content":"hello"}))
.send()
.await
.unwrap();
assert_eq!(response.status(), StatusCode::CREATED);
let response = client
.post(&target)
.bearer_auth(&key)
.body(vec![b'x'; MAX_BODY + 1])
.send()
.await
.unwrap();
assert_eq!(response.status(), StatusCode::PAYLOAD_TOO_LARGE);
task.abort();
let _ = task.await;
}
#[test]
fn rate_limit_and_content_boundaries() {
let runtime = Runtime::default();
for _ in 0..10 {
assert!(runtime.consume("hook"))
}
assert!(!runtime.consume("hook"));
assert!(runtime.consume("another"));
assert!(valid_content(&"я".repeat(MAX_CONTENT)));
assert!(!valid_content(&"я".repeat(MAX_CONTENT + 1)));
assert!(!valid_content("@EVERYONE hi"));
assert!(!valid_content("\0"));
assert!(valid_content("line\nnext\ttab"));
}
#[tokio::test]
async fn lnex_management_rejects_stranger_and_creates_only_for_owner() {
use crate::proto::{PacketId, SessionCrypto, WebhookRequest, flags, to_payload};
let (s, _, _) = fixture().await;
let req = WebhookRequest {
id: String::new(),
channel_id: "target".into(),
name: "builds".into(),
direction: "incoming".into(),
provider: "generic".into(),
endpoint: String::new(),
};
for (user, expected) in [
("stranger", PacketId::Error),
("owner", PacketId::WebhookResult),
] {
let session = session::create(&s.sessions, user.into(), user.into()).await;
let crypto = SessionCrypto::derive(&[3; 32], &session.session_id);
let (mut stream, mut peer) = tokio::io::duplex(65536);
let mut seq = 0;
let mut ctx = crate::handler::Ctx {
stream: &mut stream,
seq: &mut seq,
crypto: &crypto,
state: &s,
};
management::handle(
&mut ctx,
&session.session_id,
PacketId::WebhookCreate,
&to_payload(&req),
)
.await
.unwrap();
let (header, _) = crate::net::io::read_packet(&mut peer).await.unwrap();
assert_eq!(header.packet_id, expected as u16);
assert_ne!(header.flags & flags::ENCRYPTED, 0);
}
let hooks = s.storage.hooks("target").await.unwrap();
assert_eq!(hooks.len(), 2);
assert!(hooks.iter().all(|h| h.creator_id == "owner"));
}
#[tokio::test]
async fn durable_outbox_and_receipts_survive_database_reopen() {
let (_, mut hook, secret) = fixture().await;
let path = std::env::temp_dir().join(format!("vnox-outbox-{}.sqlite", uuid::Uuid::new_v4()));
let database = Storage::connect_sqlite(path.to_str().unwrap())
.await
.unwrap();
database.insert_hook(&hook).await.unwrap();
hook.id = "outgoing".into();
hook.direction = "outgoing".into();
hook.sealed_secret = secrets::seal(&[7; 32], &hook.id, &secret).unwrap();
database.insert_hook(&hook).await.unwrap();
let msg = ChatMessagePayload {
message_id: "persistent".into(),
channel_id: "target".into(),
sender_id: "webhook:incoming".into(),
content: "hello".into(),
timestamp: now_ms(),
edited: false,
reply_to: None,
};
let hash = secrets::digest(b"body");
let token_hash = secrets::digest(secret.as_bytes());
database
.save_webhook_message(&msg, Some(("incoming", "delivery1", &hash, &token_hash)))
.await
.unwrap();
if let crate::domain::storage::Pool::Sqlite(p) = &database.pool {
p.close().await;
}
drop(database);
let reopened = Storage::connect_sqlite(path.to_str().unwrap())
.await
.unwrap();
assert_eq!(reopened.due_webhooks().await.unwrap().len(), 1);
assert_eq!(reopened.get_history("target", 10).await.unwrap().len(), 1);
assert!(
!reopened
.save_webhook_message(&msg, Some(("incoming", "delivery1", &hash, &token_hash)))
.await
.unwrap()
);
if let crate::domain::storage::Pool::Sqlite(p) = &reopened.pool {
p.close().await;
}
drop(reopened);
std::fs::remove_file(path).unwrap();
}
#[tokio::test]
async fn management_lists_active_hooks_after_many_revocations() {
let (state, mut hook, _) = fixture().await;
state.storage.revoke_hook(&hook.id).await.unwrap();
for index in 0..70 {
hook.id = format!("retired-{index}");
hook.created_at = index;
state.storage.insert_hook(&hook).await.unwrap();
state.storage.revoke_hook(&hook.id).await.unwrap();
}
hook.id = "current-integration".into();
hook.created_at = 100;
state.storage.insert_hook(&hook).await.unwrap();
let listed = state.storage.hooks("target").await.unwrap();
assert_eq!(listed.len(), 1);
assert_eq!(listed[0].id, "current-integration");
}