Files
knock/crates/knock-core/src/auth/jwt.rs
T
JoshiCodes a469697af7 Auth types and OAuth 2.0 / OpenID Connect (M3, M4)
- Digest (MD5/SHA-256, -sess, auth/auth-int) with challenge round trip,
  self-signed JWT, AWS SigV4 (header and presigned), OAuth 1.0a,
  PKCS#12 client certificates; every type explains its computation
- OAuth: discovery, authorization code with PKCE over a loopback
  listener (knock:// and paste-by-hand as alternatives), client
  credentials, device code, password; tokens per issuer/client/scopes/
  environment in the keyring with auto refresh and one retry after 401
- Flow log with step timeline, raw exchanges, cURL export, plain-language
  diagnosis of provider errors, ID token validation incl. JWKS signature
- OAuth panel with redirect URI on top, token inspector, refresh,
  userinfo, introspection, revocation, logout and connection test
2026-11-27 16:53:32 +01:00

391 lines
16 KiB
Rust

//! Self-signed JWT bearer tokens.
use super::{AuthDebug, Res, Sent, Step, StepStatus};
use crate::model::AuthConfig;
use crate::prepare::Prepared;
use jsonwebtoken::{crypto::CryptoProvider, errors::ErrorKind, Algorithm, AlgorithmFamily, EncodingKey, Header};
use serde_json::{Map, Value};
use std::path::Path;
const ALGORITHMS: &str = "HS256, HS384, HS512, RS256, RS384, RS512, ES256, ES384 or EdDSA";
fn missing_warning(dbg: &mut AuthDebug, field: &str, missing: &[String]) {
if !missing.is_empty() {
dbg.warnings.push(format!(
"{field}: variable {} is not defined, sent as literal text",
missing.iter().map(|m| format!("{{{{{m}}}}}")).collect::<Vec<_>>().join(", ")
));
}
}
fn parse_algorithm(s: &str) -> Option<Algorithm> {
match s.trim().to_ascii_uppercase().as_str() {
"" | "HS256" => Some(Algorithm::HS256),
"HS384" => Some(Algorithm::HS384),
"HS512" => Some(Algorithm::HS512),
"RS256" => Some(Algorithm::RS256),
"RS384" => Some(Algorithm::RS384),
"RS512" => Some(Algorithm::RS512),
"ES256" => Some(Algorithm::ES256),
"ES384" => Some(Algorithm::ES384),
"EDDSA" => Some(Algorithm::EdDSA),
_ => None,
}
}
fn describe(alg: Algorithm) -> &'static str {
match alg {
Algorithm::HS256 => "HMAC with SHA-256",
Algorithm::HS384 => "HMAC with SHA-384",
Algorithm::HS512 => "HMAC with SHA-512",
Algorithm::RS256 => "RSA PKCS#1 v1.5 with SHA-256",
Algorithm::RS384 => "RSA PKCS#1 v1.5 with SHA-384",
Algorithm::RS512 => "RSA PKCS#1 v1.5 with SHA-512",
Algorithm::ES256 => "ECDSA P-256 with SHA-256",
Algorithm::ES384 => "ECDSA P-384 with SHA-384",
Algorithm::EdDSA => "Ed25519",
_ => "RSA-PSS",
}
}
/// Reads a PEM key given either inline or as a path relative to `root`.
pub(super) fn load_pem(value: &str, root: &Path) -> Result<(String, String), String> {
let v = value.trim();
if v.contains("-----BEGIN") {
let text = if !v.contains('\n') && v.contains("\\n") { v.replace("\\n", "\n") } else { v.to_string() };
return Ok((text, "inline PEM".into()));
}
let path = root.join(v);
std::fs::read_to_string(&path)
.map(|t| (t, path.display().to_string()))
.map_err(|e| format!("cannot read {}: {e}", path.display()))
}
fn pem_label(pem: &str) -> &str {
pem.lines()
.find_map(|l| l.trim().strip_prefix("-----BEGIN ").and_then(|r| r.strip_suffix("-----")))
.unwrap_or("")
}
fn key_for(family: AlgorithmFamily, pem: &[u8]) -> jsonwebtoken::errors::Result<EncodingKey> {
match family {
AlgorithmFamily::Rsa => EncodingKey::from_rsa_pem(pem),
AlgorithmFamily::Ec => EncodingKey::from_ec_pem(pem),
AlgorithmFamily::Ed => EncodingKey::from_ed_pem(pem),
AlgorithmFamily::Hmac => EncodingKey::from_secret(pem),
}
}
fn family_name(f: AlgorithmFamily) -> &'static str {
match f {
AlgorithmFamily::Rsa => "an RSA",
AlgorithmFamily::Ec => "an EC",
AlgorithmFamily::Ed => "an Ed25519",
AlgorithmFamily::Hmac => "an HMAC",
}
}
fn suggest(f: AlgorithmFamily) -> &'static str {
match f {
AlgorithmFamily::Rsa => "RS256",
AlgorithmFamily::Ec => "ES256 or ES384",
AlgorithmFamily::Ed => "EdDSA",
AlgorithmFamily::Hmac => "HS256",
}
}
pub(crate) fn ensure_provider() {
if CryptoProvider::try_get_default().is_none() {
let _ = jsonwebtoken::crypto::aws_lc::DEFAULT_PROVIDER.install_default();
}
}
fn now() -> i64 {
chrono::Utc::now().timestamp()
}
pub(super) fn apply(cfg: &AuthConfig, p: &mut Prepared, res: &Res<'_>, root: &Path, dbg: &mut AuthDebug) {
let started = std::time::Instant::now();
let alg_name = cfg.str("algorithm").unwrap_or("HS256");
let Some(alg) = parse_algorithm(alg_name) else {
dbg.steps.push(
Step::new("header", "Build header", StepStatus::Error, format!("algorithm '{alg_name}' is not supported"))
.hint(format!("Choose one of {ALGORITHMS}.")),
);
return;
};
// Header
let (header_text, m) = res("header");
missing_warning(dbg, "header", &m);
let mut header_obj = Map::new();
if !header_text.trim().is_empty() {
match serde_json::from_str::<Value>(&header_text) {
Ok(Value::Object(o)) => header_obj = o,
Ok(_) => {
dbg.steps.push(
Step::new("header", "Build header", StepStatus::Error, "extra header fields are not a JSON object")
.hint("Write the header fields as a JSON object, e.g. {\"kid\": \"my-key\"}."),
);
return;
}
Err(e) => {
dbg.steps.push(
Step::new("header", "Build header", StepStatus::Error, format!("header is not valid JSON: {e}"))
.hint("Fix the JSON in the header field. Variables are inserted as plain text, so string values still need quotes around them."),
);
return;
}
}
}
if let Some(a) = header_obj.get("alg").and_then(Value::as_str) {
if parse_algorithm(a) != Some(alg) {
dbg.warnings.push(format!("header alg '{a}' ignored, the token is signed with {alg:?}"));
}
}
header_obj.insert("alg".into(), serde_json::to_value(alg).unwrap_or(Value::Null));
header_obj.entry("typ").or_insert_with(|| Value::String("JWT".into()));
let header: Header = match serde_json::from_value(Value::Object(header_obj.clone())) {
Ok(h) => h,
Err(e) => {
dbg.steps.push(
Step::new("header", "Build header", StepStatus::Error, format!("invalid header field: {e}"))
.hint("Standard header fields such as kid, typ, cty, jku, x5u must be strings; crit must be a list of strings."),
);
return;
}
};
let header_json = serde_json::to_value(&header).unwrap_or(Value::Object(header_obj));
dbg.steps.push(
Step::new("header", "Build header", StepStatus::Ok, format!("{alg:?}, {}", describe(alg)))
.data(serde_json::json!({ "header": header_json, "algorithm": format!("{alg:?}"), "signature": describe(alg) })),
);
// Claims
let (claims_text, m) = res("claims");
missing_warning(dbg, "claims", &m);
let mut claims = if claims_text.trim().is_empty() {
Map::new()
} else {
match serde_json::from_str::<Value>(&claims_text) {
Ok(Value::Object(o)) => o,
Ok(_) => {
dbg.steps.push(
Step::new("claims", "Build claims", StepStatus::Error, "claims are not a JSON object")
.hint("Write the claims as a JSON object, e.g. {\"sub\": \"user-1\", \"aud\": \"api\"}."),
);
return;
}
Err(e) => {
dbg.steps.push(
Step::new("claims", "Build claims", StepStatus::Error, format!("claims are not valid JSON: {e}"))
.hint("Fix the JSON in the claims field. Variables are inserted as plain text, so string values still need quotes around them."),
);
return;
}
}
};
let expires_in = {
let (s, _) = res("expires_in");
s.trim()
.parse::<i64>()
.ok()
.or_else(|| cfg.fields.get("expires_in").and_then(Value::as_i64))
.unwrap_or(300)
};
let iat = now();
let mut added = Vec::new();
if !claims.contains_key("iat") {
claims.insert("iat".into(), iat.into());
added.push("iat");
}
if !claims.contains_key("exp") {
claims.insert("exp".into(), (iat + expires_in).into());
added.push("exp");
}
dbg.steps.push(
Step::new(
"claims",
"Build claims",
StepStatus::Ok,
if added.is_empty() {
format!("{} claims", claims.len())
} else {
format!("{} claims, added {}", claims.len(), added.join(" and "))
},
)
.data(serde_json::json!({ "claims": claims, "expires_in": expires_in })),
);
// Key
let family = alg.family();
let key = if family == AlgorithmFamily::Hmac {
let (secret, m) = res("secret");
missing_warning(dbg, "secret", &m);
if secret.is_empty() {
dbg.steps.push(
Step::new("sign", "Sign token", StepStatus::Error, "the secret is empty")
.hint(format!("{alg:?} signs with a shared secret. Set the secret field, or pick an RS/ES/EdDSA algorithm and a private key.")),
);
return;
}
match EncodingKey::from_secret(secret.as_bytes()) {
Ok(k) => k,
Err(e) => {
dbg.steps.push(Step::new("sign", "Sign token", StepStatus::Error, format!("invalid secret: {e}")));
return;
}
}
} else {
let (pk, m) = res("private_key");
missing_warning(dbg, "private_key", &m);
if pk.trim().is_empty() {
dbg.steps.push(
Step::new("sign", "Sign token", StepStatus::Error, "no private key set")
.hint(format!("{alg:?} needs {} private key in PEM format: a file path relative to the collection, or the PEM text itself (e.g. from a secret variable).", family_name(family))),
);
return;
}
let (pem, from) = match load_pem(&pk, root) {
Ok(x) => x,
Err(e) => {
dbg.steps.push(
Step::new("sign", "Sign token", StepStatus::Error, e)
.hint("The private key path is resolved relative to the collection folder. Check that the file exists, or paste the PEM text starting with -----BEGIN."),
);
return;
}
};
let label = pem_label(&pem).to_string();
ensure_provider();
match key_for(family, pem.as_bytes()) {
Ok(k) => k,
Err(e) => {
let actual = [AlgorithmFamily::Rsa, AlgorithmFamily::Ec, AlgorithmFamily::Ed]
.into_iter()
.find(|f| *f != family && key_for(*f, pem.as_bytes()).is_ok());
let hint = if let Some(f) = actual {
format!("The key in {from} is {} key, but {alg:?} needs {} key. Switch the algorithm to {} or use a matching key.", family_name(f), family_name(family), suggest(f))
} else if label.contains("PUBLIC") || label.contains("CERTIFICATE") {
format!("{from} holds a {label}. Signing needs the private key.")
} else if label == "EC PRIVATE KEY" {
"SEC1 EC keys are not supported. Convert it to PKCS#8: openssl pkcs8 -topk8 -nocrypt -in key.pem -out key-pkcs8.pem".into()
} else if label.contains("ENCRYPTED") {
"Encrypted private keys are not supported. Decrypt it first: openssl pkcs8 -in key.pem -out key-plain.pem".into()
} else {
format!("{from} is not a readable {} private key in PEM format.", family_name(family).trim_start_matches("an "))
};
dbg.steps.push(
Step::new("sign", "Sign token", StepStatus::Error, format!("cannot load key: {e}"))
.hint(hint)
.data(serde_json::json!({ "key_source": from, "pem_type": label })),
);
return;
}
}
};
ensure_provider();
let token = match jsonwebtoken::encode(&header, &Value::Object(claims), &key) {
Ok(t) => t,
Err(e) => {
let hint = match e.kind() {
ErrorKind::InvalidAlgorithm => format!("The key does not fit {alg:?}. Use {} key or switch the algorithm.", family_name(family)),
ErrorKind::InvalidRsaKey(_) | ErrorKind::RsaFailedSigning => "The RSA key was rejected. Keys must be at least 2048 bits.".into(),
ErrorKind::InvalidEcdsaKey => format!("The EC key was rejected. {alg:?} needs a {} key.", if alg == Algorithm::ES384 { "P-384" } else { "P-256" }),
ErrorKind::InvalidEddsaKey => "The Ed25519 key was rejected.".into(),
_ => "Check the key and the algorithm.".into(),
};
dbg.steps.push(Step::new("sign", "Sign token", StepStatus::Error, format!("signing failed: {e}")).hint(hint));
return;
}
};
let signature_len = token.rsplit('.').next().map(str::len).unwrap_or(0);
dbg.steps.push(
Step::new("sign", "Sign token", StepStatus::Ok, format!("signed with {alg:?}"))
.data(serde_json::json!({
"algorithm": format!("{alg:?}"),
"signature": describe(alg),
"signature_b64_len": signature_len,
"token_len": token.len(),
}))
.took(started),
);
let prefix = cfg.str("prefix").unwrap_or("Bearer");
let value = if prefix.is_empty() { token.clone() } else { format!("{prefix} {token}") };
p.set_header("Authorization", &value);
dbg.sent.push(Sent { location: "header".into(), name: "Authorization".into(), value });
}
#[cfg(test)]
mod tests {
use super::*;
use base64::Engine;
fn prepared() -> Prepared {
Prepared {
method: "GET".into(),
url: "https://example.org/".into(),
headers: vec![],
body: crate::prepare::PreparedBody::None,
settings: Default::default(),
missing: vec![],
cycles: vec![],
}
}
fn run(cfg: serde_json::Value) -> (Prepared, AuthDebug) {
let cfg: AuthConfig = serde_json::from_value(cfg).unwrap();
let res = |k: &str| -> (String, Vec<String>) { (cfg.string(k), vec![]) };
let mut p = prepared();
let mut dbg = AuthDebug::default();
apply(&cfg, &mut p, &res, Path::new("."), &mut dbg);
(p, dbg)
}
fn part(token: &str, i: usize) -> Value {
let raw = token.split('.').nth(i).unwrap();
serde_json::from_slice(&base64::engine::general_purpose::URL_SAFE_NO_PAD.decode(raw).unwrap()).unwrap()
}
#[test]
fn hs256_token_with_iat_exp_and_kid() {
let (p, dbg) = run(serde_json::json!({
"type": "jwt", "algorithm": "HS256", "secret": "s3cret",
"claims": "{\"sub\": \"u1\"}", "header": "{\"kid\": \"k1\"}", "expires_in": 60
}));
assert!(!dbg.failed(), "{:?}", dbg.steps);
let token = p.header("Authorization").unwrap().strip_prefix("Bearer ").unwrap();
let h = part(token, 0);
assert_eq!(h["alg"], "HS256");
assert_eq!(h["kid"], "k1");
let c = part(token, 1);
assert_eq!(c["sub"], "u1");
assert_eq!(c["exp"].as_i64().unwrap() - c["iat"].as_i64().unwrap(), 60);
let mut v = jsonwebtoken::Validation::new(Algorithm::HS256);
v.required_spec_claims.clear();
assert!(jsonwebtoken::decode::<Value>(token, &jsonwebtoken::DecodingKey::from_secret(b"s3cret").unwrap(), &v).is_ok());
}
#[test]
fn invalid_claims_and_missing_key_are_errors() {
let (_, dbg) = run(serde_json::json!({ "type": "jwt", "secret": "x", "claims": "{sub: 1}" }));
assert!(dbg.failed());
assert!(dbg.steps.last().unwrap().hint.is_some());
let (_, dbg) = run(serde_json::json!({ "type": "jwt", "algorithm": "RS256", "private_key": "nope/missing.pem" }));
assert!(dbg.failed());
}
#[test]
fn key_algorithm_mismatch() {
// Ed25519 PKCS#8 key from RFC 8410.
let pem = "-----BEGIN PRIVATE KEY-----\nMC4CAQAwBQYDK2VwBCIEINTuctv5E1hK1bbY8fdp+K06/nwoy/HU++CXqI9EdVhC\n-----END PRIVATE KEY-----\n";
let (_, dbg) = run(serde_json::json!({ "type": "jwt", "algorithm": "RS256", "private_key": pem }));
assert!(dbg.failed());
let (p, dbg) = run(serde_json::json!({ "type": "jwt", "algorithm": "EdDSA", "private_key": pem, "claims": "{}" }));
assert!(!dbg.failed(), "{:?}", dbg.steps);
assert!(p.header("Authorization").is_some());
}
}