From c04a04ea29e5ce3aee26e96eea6ecf82b34abf04 Mon Sep 17 00:00:00 2001 From: Robin Appelman Date: Wed, 4 Nov 2026 00:57:16 +0100 Subject: [PATCH] add option for serving jwt info --- Cargo.lock | 35 +++++++++++++++++ Cargo.toml | 4 +- README.md | 21 ++++++++++ nix/module.nix | 35 +++++++++++++++-- src/config.rs | 47 +++++++++++++++++++---- src/error.rs | 11 ++++++ src/jwt.rs | 101 ++++++++++++++++++++++++++++++++++++++++++++++--- src/main.rs | 24 +++++++++--- 8 files changed, 256 insertions(+), 22 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 5ed8503..75f6fa9 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -39,6 +39,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "31b698c5f9a010f6573133b09e0de5408834d0c82f8d7475a89fc1867a71cd90" dependencies = [ "axum-core", + "axum-macros", "bytes", "form_urlencoded", "futures-util", @@ -84,6 +85,38 @@ dependencies = [ "tracing", ] +[[package]] +name = "axum-extra" +version = "0.12.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "be44683b41ccb9ab2d23a5230015c9c3c55be97a25e4428366de8873103f7970" +dependencies = [ + "axum", + "axum-core", + "bytes", + "futures-core", + "futures-util", + "http", + "http-body", + "http-body-util", + "mime", + "pin-project-lite", + "tower-layer", + "tower-service", + "tracing", +] + +[[package]] +name = "axum-macros" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7aa268c23bfbbd2c4363b9cd302a4f504fb2a9dfe7e3451d66f35dd392e20aca" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "base16ct" version = "0.2.0" @@ -1302,6 +1335,7 @@ version = "0.3.0" dependencies = [ "atom_syndication", "axum", + "axum-extra", "ctrlc", "jsonwebtoken", "main_error", @@ -1311,6 +1345,7 @@ dependencies = [ "serde_json", "thiserror", "time", + "tokio", "toml", "tracing", "tracing-subscriber", diff --git a/Cargo.toml b/Cargo.toml index f0ce735..9bde38f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -8,7 +8,8 @@ license = "MIT" [dependencies] atom_syndication = "0.12.10" -axum = "0.8.9" +axum = { version = "0.8.9", features = ["json", "macros"] } +axum-extra = "0.12.6" ctrlc = "3.5.2" jsonwebtoken = { version = "11.1.0", features = ["rust_crypto"] } main_error = "0.1.2" @@ -18,6 +19,7 @@ serde = { version = "1.0.216", features = ["derive"] } serde_json = "1.0.134" thiserror = "2.0.9" time = { version = "0.3.37", features = ["serde", "serde-well-known"] } +tokio = { version = "1.54.1", features = ["macros", "net", "rt"] } toml = "1.1.8" tracing = "0.1.41" tracing-subscriber = "0.3.19" diff --git a/README.md b/README.md index 7758cb1..e08ac94 100644 --- a/README.md +++ b/README.md @@ -35,6 +35,27 @@ feed = "docker-hub://matrixdotorg/synapse" hook = "https://hook.example.com/hook2/call" ``` +### JWT Authorization + +rss-webhook-trigger supports generating JWT tokens to use for authorization. This can be used to authenticate against various services without the need for long-lived keys. + +This current has been tested with [Forgejo's Authorized Integrations](https://forgejo.org/docs/latest/user/api/authorized-integrations). + +```toml +[jwt] +key = "RS256 JWT key, or path to the key" +issuer = "https://example.com" +# optionally, serve `/.well-known/openid-configuration` and `/.well-known/keys` with the key information +listen = { address = "0.0.0.0", port = "3000" } +# listen = {path = "/var/run/webhook.sock" } + +[[feed]] +feed = "https://example.com/feed3.xml" +hook = "https://hook.example.com/hook3/call" +headers = { authorization = {type = "jwt", aud: "...."} } +body = { event_type = "build" } +``` + ### Usage in NixOS A NixOS module is included and can be used like this: diff --git a/nix/module.nix b/nix/module.nix index 15c68fd..ade05c5 100644 --- a/nix/module.nix +++ b/nix/module.nix @@ -19,9 +19,37 @@ in { description = "Configuration for generating JWT authorization tokens"; type = types.nullOr (types.submodule { options = { - secret = mkOption { + key = mkOption { type = types.str; - description = "JWT secret"; + description = "JWT RS256 key"; + }; + issuer = mkOption { + type = types.str; + description = "JWT issuer"; + }; + listen = mkOption { + type = + types.either (types.submodule { + options = { + path = mkOption { + type = types.path; + description = "UNIX socket path to listen om"; + }; + }; + }) (types.submodule { + options = { + address = mkOption { + type = types.str; + description = "IP address to listen on"; + }; + port = mkOption { + type = types.port; + description = "port to listen on"; + }; + }; + }); + description = "Serve openid-configuration and JWT keys at the specified address or socket"; + default = {path = "/var/run/rss-webhook-trigger/jwt.sock";}; }; }; }); @@ -95,9 +123,10 @@ in { ProtectHostname = true; LockPersonality = true; ProtectKernelTunables = true; - RestrictAddressFamilies = "AF_INET AF_INET6"; + RestrictAddressFamilies = ["AF_INET" "AF_INET6" "AF_UNIX"]; RestrictRealtime = true; ProtectProc = "noaccess"; + RuntimeDirectory = "rss-webhook-trigger"; SystemCallFilter = ["@system-service" "~@resources" "~@privileged"]; IPAddressDeny = "localhost link-local multicast"; }; diff --git a/src/config.rs b/src/config.rs index a8909b8..e09abaf 100644 --- a/src/config.rs +++ b/src/config.rs @@ -1,4 +1,4 @@ -use crate::error::ConfigError; +use crate::error::{ConfigError, JwtError}; use jsonwebtoken::EncodingKey; use secretfile::{load, SecretError}; use serde::de::Error; @@ -7,7 +7,8 @@ use serde_json::Value; use std::collections::HashMap; use std::convert::TryFrom; use std::fs::read_to_string; -use std::path::Path; +use std::net::IpAddr; +use std::path::{Path, PathBuf}; use std::time::Duration; #[derive(Debug, Deserialize)] @@ -17,27 +18,57 @@ pub struct Config { pub feed: Vec, } -#[derive(Debug, Deserialize)] +#[derive(Debug, Deserialize, Clone)] #[serde(try_from = "JwtConfigRaw")] pub struct JwtConfig { - pub secret: EncodingKey, + pub key: EncodingKey, pub issuer: String, + pub listen: Option, } #[derive(Debug, Deserialize)] struct JwtConfigRaw { - secret: String, + key: String, issuer: String, + listen: Option, +} + +#[derive(Debug, Deserialize)] +pub struct RawListen { + path: Option, + address: Option, + port: Option, +} + +impl TryFrom for Listen { + type Error = &'static str; + + fn try_from(value: RawListen) -> std::result::Result { + match (value.path, value.address, value.port) { + (Some(path), None, None) => Ok(Listen::Socket { path }), + (None, Some(address), Some(port)) => Ok(Listen::Tcp { address, port }), + _ => Err("invalid listen section"), + } + } +} + +#[derive(Debug, Deserialize, Clone)] +#[serde(try_from = "RawListen")] +pub enum Listen { + Socket { path: PathBuf }, + Tcp { address: IpAddr, port: u16 }, } impl TryFrom for JwtConfig { - type Error = SecretError; + type Error = JwtError; fn try_from(value: JwtConfigRaw) -> Result { - let secret = load_secret(value.secret)?; + let secret = load_secret(value.key)?; + Ok(JwtConfig { - secret: EncodingKey::from_secret(secret.as_bytes()), + key: EncodingKey::from_rsa_pem(&secret.as_bytes())?, issuer: value.issuer, + listen: value.listen, }) } } diff --git a/src/error.rs b/src/error.rs index 3e80251..3b531ee 100644 --- a/src/error.rs +++ b/src/error.rs @@ -1,3 +1,4 @@ +use secretfile::SecretError; use std::path::PathBuf; use std::str::FromStr; use thiserror::Error; @@ -65,6 +66,8 @@ pub enum FetchError { pub enum JwtError { #[error("No JWT secret configured")] NoSecret, + #[error("Error reading secret: {0}")] + Load(#[from] SecretError), #[error("Error loading JWT secret: {0}")] DecodeKey(#[from] jsonwebtoken::errors::Error), } @@ -76,3 +79,11 @@ pub enum TriggerError { #[error(transparent)] Jwt(#[from] JwtError), } + +#[derive(Debug, Error)] +pub enum ServeJwtError { + #[error(transparent)] + Jwt(#[from] JwtError), + #[error(transparent)] + Io(#[from] std::io::Error), +} diff --git a/src/jwt.rs b/src/jwt.rs index 7c7ef2d..ce83879 100644 --- a/src/jwt.rs +++ b/src/jwt.rs @@ -1,17 +1,42 @@ -use std::time::{SystemTime, UNIX_EPOCH}; +use std::{ + fs::{remove_file, set_permissions}, + net::SocketAddr, + os::unix::fs::PermissionsExt, + sync::Arc, + time::{SystemTime, UNIX_EPOCH}, +}; -use jsonwebtoken::{encode, Header}; +use axum::{Json, Router, extract::State, response::IntoResponse, routing::get, serve}; +use jsonwebtoken::{ + Algorithm, Header, encode, + jwk::{Jwk, JwkSet, PublicKeyUse}, +}; use serde::{Deserialize, Serialize}; +use tokio::net::{TcpListener, UnixListener}; -use crate::{config::Config, error::JwtError}; +use crate::{ + config::{Config, JwtConfig, Listen}, + error::{JwtError, ServeJwtError}, +}; #[derive(Debug, Serialize, Deserialize)] struct Claims<'a> { aud: &'a str, exp: u64, + iat: u64, iss: &'a str, } +#[derive(Debug, Serialize, Clone)] +struct OpenIdConfiguration { + issuer: String, + jwks_uri: String, + claims_supported: &'static [&'static str], + subject_types_supported: &'static [&'static str], + id_token_signing_alg_values_supported: &'static [&'static str], + response_types_supported: &'static [&'static str], +} + pub fn generate_token(config: &Config, aud: &str) -> Result { let now = SystemTime::now() .duration_since(UNIX_EPOCH) @@ -21,11 +46,77 @@ pub fn generate_token(config: &Config, aud: &str) -> Result { let claims = Claims { aud, + iat: now, iss: &config.issuer, exp: now + 3600, }; - let secret = &config.secret; - let token = encode(&Header::default(), &claims, secret)?; + let secret = &config.key; + let token = encode(&Header::new(Algorithm::RS256), &claims, secret)?; Ok(token) } + +fn get_key_set(config: &JwtConfig) -> Result { + let mut jwk = Jwk::from_encoding_key(&config.key, Algorithm::RS256)?; + jwk.common.public_key_use = Some(PublicKeyUse::Signature); + Ok(JwkSet { keys: vec![jwk] }) +} + +struct AppState { + openid_config: OpenIdConfiguration, + keys: JwkSet, +} + +pub async fn serve_well_known(config: JwtConfig, listen: Listen) -> Result<(), ServeJwtError> { + let keys = get_key_set(&config)?; + let openid_config = OpenIdConfiguration { + jwks_uri: format!("{}/.well-known/keys", config.issuer.trim_end_matches('/')), + issuer: config.issuer, + claims_supported: &["aud", "exp", "iat", "iss"], + subject_types_supported: &["public"], + id_token_signing_alg_values_supported: &["RS256"], + response_types_supported: &["id_token"], + }; + let state = Arc::new(AppState { + openid_config, + keys, + }); + + let app = Router::new() + .route("/.well-known/openid-configuration", get(serve_config)) + .route("/.well-known/keys", get(serve_keys)) + .with_state(state); + + match listen { + Listen::Tcp { address, port } => { + let service = app.into_make_service(); + let addr = SocketAddr::from((address, port)); + let listener = TcpListener::bind(addr).await?; + println!("listening on http://{}", listener.local_addr()?); + serve(listener, service).await?; + } + Listen::Socket { path } => { + println!("listening on {}", path.display()); + remove_file(&path).ok(); + + let listener = UnixListener::bind(&path)?; + set_permissions(&path, PermissionsExt::from_mode(0o666))?; + + serve(listener, app.into_make_service()).await?; + println!("done?"); + remove_file(path).ok(); + } + } + + Ok(()) +} + +#[axum::debug_handler] +async fn serve_config(State(app): State>) -> impl IntoResponse { + Json(app.openid_config.clone()) +} + +#[axum::debug_handler] +async fn serve_keys(State(app): State>) -> impl IntoResponse { + Json(app.keys.clone()) +} diff --git a/src/main.rs b/src/main.rs index 53339be..66ca33e 100644 --- a/src/main.rs +++ b/src/main.rs @@ -6,19 +6,19 @@ mod jwt; use crate::config::{Config, FeedConfig, HeaderVal}; use crate::error::{FetchError, FetchFeedError, HubError, ParseFeedError, TriggerError}; -use crate::fetcher::{next_fetch, CacheHeaders, FetchPlan, FetchResponse}; -use crate::jwt::generate_token; +use crate::fetcher::{CacheHeaders, FetchPlan, FetchResponse, next_fetch}; +use crate::jwt::{generate_token, serve_well_known}; use main_error::MainResult; -use std::collections::hash_map::DefaultHasher; use std::collections::HashMap; +use std::collections::hash_map::DefaultHasher; use std::hash::{Hash, Hasher}; use std::str::FromStr; use std::sync::atomic::{AtomicBool, Ordering}; -use std::thread::sleep; +use std::thread::{sleep, spawn}; use std::time::{Duration, Instant}; use tracing::{debug, error, info, instrument, warn}; -use ureq::http::header::{HeaderValue, USER_AGENT}; use ureq::http::Response; +use ureq::http::header::{HeaderValue, USER_AGENT}; use ureq::{Agent, Body}; const FETCHER_USER_AGENT: &str = concat!( @@ -47,6 +47,20 @@ fn main() -> MainResult { let config = Config::from_file(&file)?; + if let Some(jwt_config) = config.jwt.clone() { + if let Some(listen) = jwt_config.listen.clone() { + spawn(|| { + let rt = tokio::runtime::Builder::new_current_thread() + .enable_io() + .build() + .expect("Setup tokio"); + if let Err(e) = rt.block_on(serve_well_known(jwt_config, listen)) { + eprintln!("{e:#}"); + } + }); + } + } + info!("Running rss trigger for {} feeds", config.feed.len()); ctrlc::set_handler(|| RUNNING.store(false, Ordering::SeqCst))?;