add option for serving jwt info

This commit is contained in:
Robin Appelman 2026-11-04 00:57:16 +01:00
commit c04a04ea29
Signed by: robin
SSH key fingerprint: SHA256:kifqgrqnut7q1YUIrI0AdMNC23qiKAS/T9uGFmIYvbE
8 changed files with 256 additions and 22 deletions

View file

@ -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,
})
}
}

View file

@ -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),
}

View file

@ -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())
}

View file

@ -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))?;