mirror of
https://codeberg.org/icewind/rss-webhook-trigger.git
synced 2026-11-30 12:10:50 +01:00
add option for serving jwt info
This commit is contained in:
parent
766a820f96
commit
c04a04ea29
8 changed files with 256 additions and 22 deletions
35
Cargo.lock
generated
35
Cargo.lock
generated
|
|
@ -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",
|
||||
|
|
|
|||
|
|
@ -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"
|
||||
|
|
|
|||
21
README.md
21
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:
|
||||
|
|
|
|||
|
|
@ -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";
|
||||
};
|
||||
|
|
|
|||
|
|
@ -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<FeedConfig>,
|
||||
}
|
||||
|
||||
#[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<Listen>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct JwtConfigRaw {
|
||||
secret: String,
|
||||
key: String,
|
||||
issuer: String,
|
||||
listen: Option<Listen>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub struct RawListen {
|
||||
path: Option<PathBuf>,
|
||||
address: Option<IpAddr>,
|
||||
port: Option<u16>,
|
||||
}
|
||||
|
||||
impl TryFrom<RawListen> for Listen {
|
||||
type Error = &'static str;
|
||||
|
||||
fn try_from(value: RawListen) -> std::result::Result<Self, Self::Error> {
|
||||
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<JwtConfigRaw> for JwtConfig {
|
||||
type Error = SecretError;
|
||||
type Error = JwtError;
|
||||
|
||||
fn try_from(value: JwtConfigRaw) -> Result<Self, Self::Error> {
|
||||
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,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
|
|
|||
11
src/error.rs
11
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),
|
||||
}
|
||||
|
|
|
|||
101
src/jwt.rs
101
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<String, JwtError> {
|
||||
let now = SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
|
|
@ -21,11 +46,77 @@ pub fn generate_token(config: &Config, aud: &str) -> Result<String, JwtError> {
|
|||
|
||||
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<JwkSet, JwtError> {
|
||||
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<Arc<AppState>>) -> impl IntoResponse {
|
||||
Json(app.openid_config.clone())
|
||||
}
|
||||
|
||||
#[axum::debug_handler]
|
||||
async fn serve_keys(State(app): State<Arc<AppState>>) -> impl IntoResponse {
|
||||
Json(app.keys.clone())
|
||||
}
|
||||
|
|
|
|||
24
src/main.rs
24
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))?;
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue