mirror of
https://github.com/JoshiCodes/knock.git
synced 2026-12-04 15:29:40 +01:00
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
This commit is contained in:
Generated
+670
-16
File diff suppressed because it is too large
Load Diff
@@ -29,3 +29,10 @@ bytes = "1"
|
|||||||
futures-util = "0.3"
|
futures-util = "0.3"
|
||||||
http = "1"
|
http = "1"
|
||||||
keyring = { version = "3.6", features = ["sync-secret-service", "crypto-rust", "apple-native", "windows-native"] }
|
keyring = { version = "3.6", features = ["sync-secret-service", "crypto-rust", "apple-native", "windows-native"] }
|
||||||
|
hmac = "0.12"
|
||||||
|
sha1 = "0.10"
|
||||||
|
md-5 = "0.10"
|
||||||
|
hex = "0.4"
|
||||||
|
jsonwebtoken = { version = "12", default-features = false, features = ["aws_lc_rs", "use_pem"] }
|
||||||
|
rsa = { version = "0.9", features = ["sha1", "sha2"] }
|
||||||
|
p12-keystore = "0.4"
|
||||||
|
|||||||
@@ -0,0 +1,465 @@
|
|||||||
|
//! HTTP Digest (RFC 7616): MD5, MD5-sess, SHA-256, SHA-256-sess, qop auth / auth-int.
|
||||||
|
|
||||||
|
use super::{AuthDebug, Res, Sent, Step, StepStatus};
|
||||||
|
use crate::model::AuthConfig;
|
||||||
|
use crate::prepare::Prepared;
|
||||||
|
use md5::Md5;
|
||||||
|
use rand::RngCore;
|
||||||
|
use sha2::{Digest, Sha256};
|
||||||
|
|
||||||
|
#[derive(Debug, Default, PartialEq)]
|
||||||
|
struct Challenge {
|
||||||
|
realm: String,
|
||||||
|
nonce: String,
|
||||||
|
opaque: Option<String>,
|
||||||
|
qop: Vec<String>,
|
||||||
|
algorithm: Option<String>,
|
||||||
|
stale: bool,
|
||||||
|
userhash: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Splits `key=value, key="quoted, value"` pairs; keys are lowercased.
|
||||||
|
fn parse_params(s: &str) -> Option<Vec<(String, String)>> {
|
||||||
|
let mut out = Vec::new();
|
||||||
|
let mut chars = s.chars().peekable();
|
||||||
|
loop {
|
||||||
|
while matches!(chars.peek(), Some(c) if c.is_whitespace() || *c == ',') {
|
||||||
|
chars.next();
|
||||||
|
}
|
||||||
|
if chars.peek().is_none() {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
let mut key = String::new();
|
||||||
|
while let Some(&c) = chars.peek() {
|
||||||
|
if c == '=' || c.is_whitespace() {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
key.push(c);
|
||||||
|
chars.next();
|
||||||
|
}
|
||||||
|
while matches!(chars.peek(), Some(c) if c.is_whitespace()) {
|
||||||
|
chars.next();
|
||||||
|
}
|
||||||
|
if chars.next() != Some('=') || key.is_empty() {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
while matches!(chars.peek(), Some(c) if c.is_whitespace()) {
|
||||||
|
chars.next();
|
||||||
|
}
|
||||||
|
let mut value = String::new();
|
||||||
|
if chars.peek() == Some(&'"') {
|
||||||
|
chars.next();
|
||||||
|
let mut closed = false;
|
||||||
|
while let Some(c) = chars.next() {
|
||||||
|
match c {
|
||||||
|
'\\' => {
|
||||||
|
if let Some(n) = chars.next() {
|
||||||
|
value.push(n);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
'"' => {
|
||||||
|
closed = true;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
c => value.push(c),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !closed {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
while let Some(&c) = chars.peek() {
|
||||||
|
if c == ',' {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
value.push(c);
|
||||||
|
chars.next();
|
||||||
|
}
|
||||||
|
value = value.trim().to_string();
|
||||||
|
}
|
||||||
|
out.push((key.to_ascii_lowercase(), value));
|
||||||
|
}
|
||||||
|
Some(out)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn parse_challenge(header: &str) -> Result<Challenge, String> {
|
||||||
|
let h = header.trim();
|
||||||
|
let rest = match h.split_once(char::is_whitespace) {
|
||||||
|
Some((scheme, rest)) if scheme.eq_ignore_ascii_case("digest") => rest,
|
||||||
|
_ if h.eq_ignore_ascii_case("digest") => "",
|
||||||
|
_ => return Err("the challenge is not a Digest challenge".into()),
|
||||||
|
};
|
||||||
|
let params = parse_params(rest).ok_or("the challenge parameters are malformed")?;
|
||||||
|
let mut c = Challenge::default();
|
||||||
|
let mut has_nonce = false;
|
||||||
|
for (k, v) in params {
|
||||||
|
match k.as_str() {
|
||||||
|
"realm" => c.realm = v,
|
||||||
|
"nonce" => {
|
||||||
|
c.nonce = v;
|
||||||
|
has_nonce = true;
|
||||||
|
}
|
||||||
|
"opaque" => c.opaque = Some(v),
|
||||||
|
"qop" => {
|
||||||
|
c.qop = v.split(',').map(|q| q.trim().to_ascii_lowercase()).filter(|q| !q.is_empty()).collect()
|
||||||
|
}
|
||||||
|
"algorithm" => c.algorithm = Some(v),
|
||||||
|
"stale" => c.stale = v.eq_ignore_ascii_case("true"),
|
||||||
|
"userhash" => c.userhash = v.eq_ignore_ascii_case("true"),
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !has_nonce {
|
||||||
|
return Err("the challenge has no nonce".into());
|
||||||
|
}
|
||||||
|
Ok(c)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Copy)]
|
||||||
|
enum Algo {
|
||||||
|
Md5,
|
||||||
|
Sha256,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Algo {
|
||||||
|
fn hash(self, s: &[u8]) -> String {
|
||||||
|
match self {
|
||||||
|
Algo::Md5 => hex::encode(Md5::digest(s)),
|
||||||
|
Algo::Sha256 => hex::encode(Sha256::digest(s)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fn label(self) -> &'static str {
|
||||||
|
match self {
|
||||||
|
Algo::Md5 => "MD5",
|
||||||
|
Algo::Sha256 => "SHA-256",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// (hash function, session variant, canonical name)
|
||||||
|
fn algorithm(name: &str) -> Option<(Algo, bool, &'static str)> {
|
||||||
|
match name.to_ascii_uppercase().as_str() {
|
||||||
|
"MD5" => Some((Algo::Md5, false, "MD5")),
|
||||||
|
"MD5-SESS" => Some((Algo::Md5, true, "MD5-sess")),
|
||||||
|
"SHA-256" => Some((Algo::Sha256, false, "SHA-256")),
|
||||||
|
"SHA-256-SESS" => Some((Algo::Sha256, true, "SHA-256-sess")),
|
||||||
|
_ => None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
struct Input<'a> {
|
||||||
|
user: &'a str,
|
||||||
|
pass: &'a str,
|
||||||
|
method: &'a str,
|
||||||
|
uri: &'a str,
|
||||||
|
body: &'a [u8],
|
||||||
|
cnonce: &'a str,
|
||||||
|
nc: &'a str,
|
||||||
|
}
|
||||||
|
|
||||||
|
struct Computed {
|
||||||
|
ha1: String,
|
||||||
|
ha2: String,
|
||||||
|
response: String,
|
||||||
|
qop: Option<&'static str>,
|
||||||
|
formulas: [String; 3],
|
||||||
|
username: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn compute(c: &Challenge, algo: Algo, sess: bool, i: &Input<'_>) -> Computed {
|
||||||
|
let l = algo.label();
|
||||||
|
let mut ha1 = algo.hash(format!("{}:{}:{}", i.user, c.realm, i.pass).as_bytes());
|
||||||
|
let mut f1 = format!("HA1 = {l}({}:{}:•••)", i.user, c.realm);
|
||||||
|
if sess {
|
||||||
|
ha1 = algo.hash(format!("{ha1}:{}:{}", c.nonce, i.cnonce).as_bytes());
|
||||||
|
f1 = format!("HA1 = {l}({l}({}:{}:•••):nonce:cnonce)", i.user, c.realm);
|
||||||
|
}
|
||||||
|
let qop = if c.qop.iter().any(|q| q == "auth") {
|
||||||
|
Some("auth")
|
||||||
|
} else if c.qop.iter().any(|q| q == "auth-int") {
|
||||||
|
Some("auth-int")
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
};
|
||||||
|
let (ha2, f2) = if qop == Some("auth-int") {
|
||||||
|
let hb = algo.hash(i.body);
|
||||||
|
(
|
||||||
|
algo.hash(format!("{}:{}:{hb}", i.method, i.uri).as_bytes()),
|
||||||
|
format!("HA2 = {l}({}:{}:{l}(body))", i.method, i.uri),
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
(algo.hash(format!("{}:{}", i.method, i.uri).as_bytes()), format!("HA2 = {l}({}:{})", i.method, i.uri))
|
||||||
|
};
|
||||||
|
let (response, f3) = match qop {
|
||||||
|
Some(q) => (
|
||||||
|
algo.hash(format!("{ha1}:{}:{}:{}:{q}:{ha2}", c.nonce, i.nc, i.cnonce).as_bytes()),
|
||||||
|
format!("response = {l}(HA1:nonce:{}:cnonce:{q}:HA2)", i.nc),
|
||||||
|
),
|
||||||
|
None => (algo.hash(format!("{ha1}:{}:{ha2}", c.nonce).as_bytes()), format!("response = {l}(HA1:nonce:HA2)")),
|
||||||
|
};
|
||||||
|
let username =
|
||||||
|
if c.userhash { algo.hash(format!("{}:{}", i.user, c.realm).as_bytes()) } else { i.user.to_string() };
|
||||||
|
Computed { ha1, ha2, response, qop, formulas: [f1, f2, f3], username }
|
||||||
|
}
|
||||||
|
|
||||||
|
fn quote(s: &str) -> String {
|
||||||
|
format!("\"{}\"", s.replace('\\', "\\\\").replace('"', "\\\""))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn request_uri(url: &str) -> String {
|
||||||
|
match url::Url::parse(url) {
|
||||||
|
Ok(u) => match u.query() {
|
||||||
|
Some(q) => format!("{}?{q}", u.path()),
|
||||||
|
None => u.path().to_string(),
|
||||||
|
},
|
||||||
|
Err(_) => url.to_string(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn warn_field(dbg: &mut AuthDebug, field: &str, value: &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(", ")
|
||||||
|
));
|
||||||
|
} else if value.is_empty() {
|
||||||
|
dbg.warnings.push(format!("{field} resolved to an empty value"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Answers a `WWW-Authenticate: Digest ...` challenge by setting the
|
||||||
|
/// Authorization header on `p`. Returns false (with an error step in `dbg`)
|
||||||
|
/// when the challenge cannot be answered.
|
||||||
|
pub fn respond(cfg: &AuthConfig, p: &mut Prepared, challenge: &str, res: &Res<'_>, dbg: &mut AuthDebug) -> bool {
|
||||||
|
let started = std::time::Instant::now();
|
||||||
|
let c = match parse_challenge(challenge) {
|
||||||
|
Ok(c) => c,
|
||||||
|
Err(e) => {
|
||||||
|
dbg.steps.push(
|
||||||
|
Step::new("challenge", "Read server challenge", StepStatus::Error, e)
|
||||||
|
.hint("The server sent a WWW-Authenticate header knock cannot read. Check it in the response headers; it should look like Digest realm=\"…\", nonce=\"…\", qop=\"auth\".")
|
||||||
|
.data(serde_json::json!({ "raw": challenge })),
|
||||||
|
);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
dbg.steps.push(
|
||||||
|
Step::new(
|
||||||
|
"challenge",
|
||||||
|
"Read server challenge",
|
||||||
|
StepStatus::Ok,
|
||||||
|
format!(
|
||||||
|
"realm \"{}\", {}, qop {}",
|
||||||
|
c.realm,
|
||||||
|
c.algorithm.as_deref().unwrap_or("MD5"),
|
||||||
|
if c.qop.is_empty() { "none".to_string() } else { c.qop.join("/") }
|
||||||
|
),
|
||||||
|
)
|
||||||
|
.data(serde_json::json!({
|
||||||
|
"raw": challenge,
|
||||||
|
"realm": c.realm,
|
||||||
|
"nonce": c.nonce,
|
||||||
|
"opaque": c.opaque,
|
||||||
|
"qop": c.qop,
|
||||||
|
"algorithm": c.algorithm,
|
||||||
|
"stale": c.stale,
|
||||||
|
"userhash": c.userhash,
|
||||||
|
}))
|
||||||
|
.took(started),
|
||||||
|
);
|
||||||
|
|
||||||
|
let wanted = cfg.str("algorithm").unwrap_or("auto");
|
||||||
|
let (name, from) = if wanted.is_empty() || wanted.eq_ignore_ascii_case("auto") {
|
||||||
|
(c.algorithm.clone().unwrap_or_else(|| "MD5".into()), "challenge")
|
||||||
|
} else {
|
||||||
|
(wanted.to_string(), "config")
|
||||||
|
};
|
||||||
|
let Some((algo, sess, canonical)) = algorithm(&name) else {
|
||||||
|
dbg.steps.push(
|
||||||
|
Step::new("compute", "Compute response", StepStatus::Error, format!("algorithm '{name}' is not supported"))
|
||||||
|
.hint(if from == "challenge" {
|
||||||
|
"The server asks for an algorithm knock does not support. Supported are MD5, MD5-sess, SHA-256 and SHA-256-sess; configure the server to offer one of them."
|
||||||
|
} else {
|
||||||
|
"Set the algorithm to auto, MD5, MD5-sess, SHA-256 or SHA-256-sess."
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
return false;
|
||||||
|
};
|
||||||
|
if !c.qop.is_empty() && !c.qop.iter().any(|q| q == "auth" || q == "auth-int") {
|
||||||
|
dbg.steps.push(
|
||||||
|
Step::new("compute", "Compute response", StepStatus::Error, format!("qop '{}' is not supported", c.qop.join(",")))
|
||||||
|
.hint("The server only offers a quality of protection other than auth or auth-int. Configure it to offer qop=\"auth\"."),
|
||||||
|
);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if let Some(ca) = &c.algorithm {
|
||||||
|
if from == "config" && !ca.eq_ignore_ascii_case(canonical) {
|
||||||
|
dbg.warnings.push(format!("server asked for {ca}, answering with {canonical} as configured"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let started = std::time::Instant::now();
|
||||||
|
let (user, m1) = res("username");
|
||||||
|
let (pass, m2) = res("password");
|
||||||
|
warn_field(dbg, "username", &user, &m1);
|
||||||
|
warn_field(dbg, "password", &pass, &m2);
|
||||||
|
|
||||||
|
let mut raw = [0u8; 16];
|
||||||
|
rand::thread_rng().fill_bytes(&mut raw);
|
||||||
|
let cnonce = hex::encode(raw);
|
||||||
|
let nc = "00000001";
|
||||||
|
let uri = request_uri(&p.url);
|
||||||
|
let method = p.method.to_ascii_uppercase();
|
||||||
|
let body = p.body_bytes().to_vec();
|
||||||
|
let out = compute(
|
||||||
|
&c,
|
||||||
|
algo,
|
||||||
|
sess,
|
||||||
|
&Input { user: &user, pass: &pass, method: &method, uri: &uri, body: &body, cnonce: &cnonce, nc },
|
||||||
|
);
|
||||||
|
|
||||||
|
let mut parts = vec![
|
||||||
|
format!("username={}", quote(&out.username)),
|
||||||
|
format!("realm={}", quote(&c.realm)),
|
||||||
|
format!("nonce={}", quote(&c.nonce)),
|
||||||
|
format!("uri={}", quote(&uri)),
|
||||||
|
format!("algorithm={canonical}"),
|
||||||
|
format!("response={}", quote(&out.response)),
|
||||||
|
];
|
||||||
|
if let Some(q) = out.qop {
|
||||||
|
parts.push(format!("qop={q}"));
|
||||||
|
parts.push(format!("nc={nc}"));
|
||||||
|
parts.push(format!("cnonce={}", quote(&cnonce)));
|
||||||
|
}
|
||||||
|
if let Some(o) = &c.opaque {
|
||||||
|
parts.push(format!("opaque={}", quote(o)));
|
||||||
|
}
|
||||||
|
if c.userhash {
|
||||||
|
parts.push("userhash=true".into());
|
||||||
|
}
|
||||||
|
let value = format!("Digest {}", parts.join(", "));
|
||||||
|
p.set_header("Authorization", &value);
|
||||||
|
|
||||||
|
dbg.steps.push(
|
||||||
|
Step::new(
|
||||||
|
"compute",
|
||||||
|
"Compute response",
|
||||||
|
StepStatus::Ok,
|
||||||
|
format!("{canonical}, qop {}, response {}…", out.qop.unwrap_or("none"), &out.response[..8]),
|
||||||
|
)
|
||||||
|
.data(serde_json::json!({
|
||||||
|
"algorithm": canonical,
|
||||||
|
"algorithm_from": from,
|
||||||
|
"username": user,
|
||||||
|
"uri": uri,
|
||||||
|
"method": method,
|
||||||
|
"nonce": c.nonce,
|
||||||
|
"qop": out.qop,
|
||||||
|
"cnonce": out.qop.map(|_| cnonce.clone()),
|
||||||
|
"nc": out.qop.map(|_| nc),
|
||||||
|
"ha1_formula": out.formulas[0],
|
||||||
|
"ha1": out.ha1,
|
||||||
|
"ha2_formula": out.formulas[1],
|
||||||
|
"ha2": out.ha2,
|
||||||
|
"response_formula": out.formulas[2],
|
||||||
|
"response": out.response,
|
||||||
|
}))
|
||||||
|
.took(started),
|
||||||
|
);
|
||||||
|
dbg.sent.push(Sent { location: "header".into(), name: "Authorization".into(), value });
|
||||||
|
true
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn parses_quoted_values_with_commas() {
|
||||||
|
let c = parse_challenge(
|
||||||
|
r#"Digest realm="[email protected]", qop="auth, auth-int", algorithm=SHA-256, nonce="7ypf/xlj9XXwfDPEoM4URrv/xwf94BcCAzFZH4GiTo0v", opaque="FQhe/qaU925kfnzjCev0ciny7QMkPqMAFRtzCUYo5tdS", stale=FALSE"#,
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(c.realm, "[email protected]");
|
||||||
|
assert_eq!(c.qop, vec!["auth", "auth-int"]);
|
||||||
|
assert_eq!(c.algorithm.as_deref(), Some("SHA-256"));
|
||||||
|
assert!(!c.stale);
|
||||||
|
assert!(parse_challenge("Basic realm=\"x\"").is_err());
|
||||||
|
assert!(parse_challenge("Digest realm=\"x").is_err());
|
||||||
|
}
|
||||||
|
|
||||||
|
// RFC 7616 section 3.9.1
|
||||||
|
#[test]
|
||||||
|
fn rfc7616_example() {
|
||||||
|
let c = parse_challenge(
|
||||||
|
r#"Digest realm="[email protected]", qop="auth, auth-int", algorithm=MD5, nonce="7ypf/xlj9XXwfDPEoM4URrv/xwf94BcCAzFZH4GiTo0v", opaque="FQhe/qaU925kfnzjCev0ciny7QMkPqMAFRtzCUYo5tdS""#,
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
let input = Input {
|
||||||
|
user: "Mufasa",
|
||||||
|
pass: "Circle of Life",
|
||||||
|
method: "GET",
|
||||||
|
uri: "/dir/index.html",
|
||||||
|
body: b"",
|
||||||
|
cnonce: "f2/wE4q74E6zIJEtWaHKaf5wv/H5QzzpXusqGemxURZJ",
|
||||||
|
nc: "00000001",
|
||||||
|
};
|
||||||
|
let md5 = compute(&c, Algo::Md5, false, &input);
|
||||||
|
assert_eq!(md5.response, "8ca523f5e9506fed4657c9700eebdbec");
|
||||||
|
let sha = compute(&c, Algo::Sha256, false, &input);
|
||||||
|
assert_eq!(sha.response, "753927fa0e85d155564e2e272a28d1802ca10daf4496794697cf8db5856cb6c1");
|
||||||
|
}
|
||||||
|
|
||||||
|
// RFC 2617 section 3.5
|
||||||
|
#[test]
|
||||||
|
fn rfc2617_example() {
|
||||||
|
let c = parse_challenge(
|
||||||
|
r#"Digest realm="[email protected]", qop="auth,auth-int", nonce="dcd98b7102dd2f0e8b11d0f600bfb0c093", opaque="5ccc069c403ebaf9f0171e9517f40e41""#,
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
let out = compute(
|
||||||
|
&c,
|
||||||
|
Algo::Md5,
|
||||||
|
false,
|
||||||
|
&Input {
|
||||||
|
user: "Mufasa",
|
||||||
|
pass: "Circle Of Life",
|
||||||
|
method: "GET",
|
||||||
|
uri: "/dir/index.html",
|
||||||
|
body: b"",
|
||||||
|
cnonce: "0a4f113b",
|
||||||
|
nc: "00000001",
|
||||||
|
},
|
||||||
|
);
|
||||||
|
assert_eq!(out.response, "6629fae49393a05397450978507c4ef1");
|
||||||
|
assert!(!out.formulas.iter().any(|f| f.contains("Circle")));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn respond_sets_header() {
|
||||||
|
let cfg: AuthConfig =
|
||||||
|
serde_json::from_value(serde_json::json!({ "type": "digest", "algorithm": "auto" })).unwrap();
|
||||||
|
let mut p = Prepared {
|
||||||
|
method: "GET".into(),
|
||||||
|
url: "https://example.org/dir/index.html?a=1".into(),
|
||||||
|
headers: vec![],
|
||||||
|
body: crate::prepare::PreparedBody::None,
|
||||||
|
settings: Default::default(),
|
||||||
|
missing: vec![],
|
||||||
|
cycles: vec![],
|
||||||
|
};
|
||||||
|
let res = |k: &str| -> (String, Vec<String>) {
|
||||||
|
(if k == "username" { "Mufasa".into() } else { "pw".into() }, vec![])
|
||||||
|
};
|
||||||
|
let mut dbg = AuthDebug::default();
|
||||||
|
assert!(respond(&cfg, &mut p, r#"Digest realm="r", nonce="n", qop="auth""#, &res, &mut dbg));
|
||||||
|
let h = p.header("Authorization").unwrap();
|
||||||
|
assert!(h.starts_with("Digest username=\"Mufasa\""));
|
||||||
|
assert!(h.contains("uri=\"/dir/index.html?a=1\"") && h.contains("qop=auth") && h.contains("nc=00000001"));
|
||||||
|
assert!(!dbg.failed());
|
||||||
|
|
||||||
|
let mut dbg = AuthDebug::default();
|
||||||
|
assert!(!respond(&cfg, &mut p, r#"Digest realm="r", nonce="n", algorithm=SHA-512-256"#, &res, &mut dbg));
|
||||||
|
assert!(dbg.failed());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,390 @@
|
|||||||
|
//! 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());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,7 +1,17 @@
|
|||||||
//! Auth is never a black box: every auth type returns an [`AuthDebug`] that
|
//! Auth is never a black box: every auth type returns an [`AuthDebug`] that
|
||||||
//! says what was computed, what was attached and where it came from.
|
//! says what was computed, what was attached and where it came from.
|
||||||
|
|
||||||
|
mod digest;
|
||||||
|
pub(crate) mod jwt;
|
||||||
|
mod oauth1;
|
||||||
|
mod sigv4;
|
||||||
mod simple;
|
mod simple;
|
||||||
|
pub mod tls;
|
||||||
|
|
||||||
|
pub use digest::respond as digest_respond;
|
||||||
|
|
||||||
|
/// Resolves an auth config field: (value, names of undefined variables).
|
||||||
|
pub(crate) type Res<'a> = dyn Fn(&str) -> (String, Vec<String>) + 'a;
|
||||||
|
|
||||||
use crate::model::{Auth, AuthConfig};
|
use crate::model::{Auth, AuthConfig};
|
||||||
use crate::prepare::{EffectiveAuth, Prepared};
|
use crate::prepare::{EffectiveAuth, Prepared};
|
||||||
@@ -133,6 +143,7 @@ pub async fn apply(
|
|||||||
resolver: &Resolver,
|
resolver: &Resolver,
|
||||||
host: Option<&dyn AuthHost>,
|
host: Option<&dyn AuthHost>,
|
||||||
force_refresh: bool,
|
force_refresh: bool,
|
||||||
|
root: &std::path::Path,
|
||||||
) -> AuthDebug {
|
) -> AuthDebug {
|
||||||
let mut dbg = AuthDebug {
|
let mut dbg = AuthDebug {
|
||||||
origin: Some(format!("{:?}", eff.origin).to_lowercase()),
|
origin: Some(format!("{:?}", eff.origin).to_lowercase()),
|
||||||
@@ -155,6 +166,12 @@ pub async fn apply(
|
|||||||
"basic" => simple::basic(cfg, p, &res, &mut dbg),
|
"basic" => simple::basic(cfg, p, &res, &mut dbg),
|
||||||
"bearer" => simple::bearer(cfg, p, &res, &mut dbg),
|
"bearer" => simple::bearer(cfg, p, &res, &mut dbg),
|
||||||
"apikey" => simple::apikey(cfg, p, &res, &mut dbg),
|
"apikey" => simple::apikey(cfg, p, &res, &mut dbg),
|
||||||
|
"digest" => dbg.steps.push(
|
||||||
|
Step::new("challenge", "Wait for server challenge", StepStatus::Pending, "sent without credentials first; the 401 challenge decides the digest")
|
||||||
|
),
|
||||||
|
"jwt" => jwt::apply(cfg, p, &res, root, &mut dbg),
|
||||||
|
"awsv4" => sigv4::apply(cfg, p, &res, &mut dbg),
|
||||||
|
"oauth1" => oauth1::apply(cfg, p, &res, root, &mut dbg),
|
||||||
"oauth2" | "oidc" => {
|
"oauth2" | "oidc" => {
|
||||||
let Some(host) = host else {
|
let Some(host) = host else {
|
||||||
dbg.steps.push(Step::new("token", "Get token", StepStatus::Error, "OAuth is not available here"));
|
dbg.steps.push(Step::new("token", "Get token", StepStatus::Error, "OAuth is not available here"));
|
||||||
|
|||||||
@@ -0,0 +1,407 @@
|
|||||||
|
//! OAuth 1.0a request signing (RFC 5849).
|
||||||
|
|
||||||
|
use super::{AuthDebug, Res, Sent, Step, StepStatus};
|
||||||
|
use crate::model::AuthConfig;
|
||||||
|
use crate::prepare::{Prepared, PreparedBody};
|
||||||
|
use base64::Engine;
|
||||||
|
use hmac::{Hmac, Mac};
|
||||||
|
use percent_encoding::{utf8_percent_encode, AsciiSet, NON_ALPHANUMERIC};
|
||||||
|
use rand::RngCore;
|
||||||
|
use rsa::pkcs1::DecodeRsaPrivateKey;
|
||||||
|
use rsa::pkcs8::DecodePrivateKey;
|
||||||
|
use rsa::signature::{SignatureEncoding, Signer};
|
||||||
|
use rsa::RsaPrivateKey;
|
||||||
|
use sha1::Sha1;
|
||||||
|
use sha2::{Digest, Sha256};
|
||||||
|
use std::path::Path;
|
||||||
|
|
||||||
|
/// Everything except A-Z a-z 0-9 - _ . ~ (RFC 5849 section 3.6)
|
||||||
|
const RFC3986: &AsciiSet = &NON_ALPHANUMERIC.remove(b'-').remove(b'_').remove(b'.').remove(b'~');
|
||||||
|
|
||||||
|
fn enc(s: &str) -> String {
|
||||||
|
utf8_percent_encode(s, RFC3986).to_string()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn b64(b: &[u8]) -> String {
|
||||||
|
base64::engine::general_purpose::STANDARD.encode(b)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Copy, PartialEq, Debug)]
|
||||||
|
enum Method {
|
||||||
|
HmacSha1,
|
||||||
|
HmacSha256,
|
||||||
|
RsaSha1,
|
||||||
|
RsaSha256,
|
||||||
|
Plaintext,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Method {
|
||||||
|
fn parse(s: &str) -> Option<Self> {
|
||||||
|
match s.trim().to_ascii_uppercase().as_str() {
|
||||||
|
"" | "HMAC-SHA1" => Some(Self::HmacSha1),
|
||||||
|
"HMAC-SHA256" => Some(Self::HmacSha256),
|
||||||
|
"RSA-SHA1" => Some(Self::RsaSha1),
|
||||||
|
"RSA-SHA256" => Some(Self::RsaSha256),
|
||||||
|
"PLAINTEXT" => Some(Self::Plaintext),
|
||||||
|
_ => None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fn name(self) -> &'static str {
|
||||||
|
match self {
|
||||||
|
Self::HmacSha1 => "HMAC-SHA1",
|
||||||
|
Self::HmacSha256 => "HMAC-SHA256",
|
||||||
|
Self::RsaSha1 => "RSA-SHA1",
|
||||||
|
Self::RsaSha256 => "RSA-SHA256",
|
||||||
|
Self::Plaintext => "PLAINTEXT",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fn is_rsa(self) -> bool {
|
||||||
|
matches!(self, Self::RsaSha1 | Self::RsaSha256)
|
||||||
|
}
|
||||||
|
fn body_hash(self, body: &[u8]) -> String {
|
||||||
|
match self {
|
||||||
|
Self::HmacSha256 | Self::RsaSha256 => b64(&Sha256::digest(body)),
|
||||||
|
_ => b64(&Sha1::digest(body)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Base string URI (section 3.4.1.2): lowercase scheme and host, default port
|
||||||
|
/// dropped, no query or fragment.
|
||||||
|
fn base_uri(u: &url::Url) -> String {
|
||||||
|
let scheme = u.scheme().to_ascii_lowercase();
|
||||||
|
let host = u.host_str().unwrap_or_default().to_ascii_lowercase();
|
||||||
|
match u.port() {
|
||||||
|
Some(p) => format!("{scheme}://{host}:{p}{}", u.path()),
|
||||||
|
None => format!("{scheme}://{host}{}", u.path()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Normalized parameter string (section 3.4.1.3.2).
|
||||||
|
fn normalize(params: &[(String, String)]) -> String {
|
||||||
|
let mut enc_params: Vec<(String, String)> = params.iter().map(|(k, v)| (enc(k), enc(v))).collect();
|
||||||
|
enc_params.sort();
|
||||||
|
enc_params.iter().map(|(k, v)| format!("{k}={v}")).collect::<Vec<_>>().join("&")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn base_string(method: &str, u: &url::Url, params: &[(String, String)]) -> String {
|
||||||
|
format!("{}&{}&{}", method.to_ascii_uppercase(), enc(&base_uri(u)), enc(&normalize(params)))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn hmac_b64<M: Mac + hmac::digest::KeyInit>(key: &str, msg: &str) -> String {
|
||||||
|
let mut m = <M as Mac>::new_from_slice(key.as_bytes()).unwrap_or_else(|_| unreachable!());
|
||||||
|
m.update(msg.as_bytes());
|
||||||
|
b64(&m.finalize().into_bytes())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn rsa_key(pem: &str) -> Result<RsaPrivateKey, String> {
|
||||||
|
RsaPrivateKey::from_pkcs8_pem(pem)
|
||||||
|
.or_else(|_| RsaPrivateKey::from_pkcs1_pem(pem))
|
||||||
|
.map_err(|e| e.to_string())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn sign(method: Method, base: &str, key: &str, rsa: Option<&RsaPrivateKey>) -> Result<String, String> {
|
||||||
|
match method {
|
||||||
|
Method::HmacSha1 => Ok(hmac_b64::<Hmac<Sha1>>(key, base)),
|
||||||
|
Method::HmacSha256 => Ok(hmac_b64::<Hmac<Sha256>>(key, base)),
|
||||||
|
Method::Plaintext => Ok(key.to_string()),
|
||||||
|
Method::RsaSha1 | Method::RsaSha256 => {
|
||||||
|
let k = rsa.ok_or("no RSA key loaded")?.clone();
|
||||||
|
let sig = if method == Method::RsaSha1 {
|
||||||
|
rsa::pkcs1v15::SigningKey::<Sha1>::new(k).try_sign(base.as_bytes()).map(|s| s.to_vec())
|
||||||
|
} else {
|
||||||
|
rsa::pkcs1v15::SigningKey::<Sha256>::new(k).try_sign(base.as_bytes()).map(|s| s.to_vec())
|
||||||
|
};
|
||||||
|
sig.map(|s| b64(&s)).map_err(|e| e.to_string())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn is_form(p: &Prepared) -> bool {
|
||||||
|
p.header("Content-Type")
|
||||||
|
.map(|c| c.to_ascii_lowercase().starts_with("application/x-www-form-urlencoded"))
|
||||||
|
.unwrap_or(false)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn field(dbg: &mut AuthDebug, res: &Res<'_>, name: &str, required: bool) -> String {
|
||||||
|
let (v, missing) = res(name);
|
||||||
|
if !missing.is_empty() {
|
||||||
|
dbg.warnings.push(format!(
|
||||||
|
"{name}: variable {} is not defined, sent as literal text",
|
||||||
|
missing.iter().map(|m| format!("{{{{{m}}}}}")).collect::<Vec<_>>().join(", ")
|
||||||
|
));
|
||||||
|
} else if v.is_empty() && required {
|
||||||
|
dbg.warnings.push(format!("{name} resolved to an empty value"));
|
||||||
|
}
|
||||||
|
v
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) fn apply(cfg: &AuthConfig, p: &mut Prepared, res: &Res<'_>, root: &Path, dbg: &mut AuthDebug) {
|
||||||
|
let started = std::time::Instant::now();
|
||||||
|
let method_name = cfg.str("signature_method").unwrap_or("HMAC-SHA1");
|
||||||
|
let Some(method) = Method::parse(method_name) else {
|
||||||
|
dbg.steps.push(
|
||||||
|
Step::new("params", "Collect parameters", StepStatus::Error, format!("signature method '{method_name}' is not supported"))
|
||||||
|
.hint("Use HMAC-SHA1, HMAC-SHA256, RSA-SHA1, RSA-SHA256 or PLAINTEXT."),
|
||||||
|
);
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
let consumer_key = field(dbg, res, "consumer_key", true);
|
||||||
|
let consumer_secret = field(dbg, res, "consumer_secret", !method.is_rsa());
|
||||||
|
let token = field(dbg, res, "token", false);
|
||||||
|
let token_secret = field(dbg, res, "token_secret", false);
|
||||||
|
let realm = field(dbg, res, "realm", false);
|
||||||
|
let callback = field(dbg, res, "callback", false);
|
||||||
|
let verifier = field(dbg, res, "verifier", false);
|
||||||
|
let add_to = cfg.str("add_to").unwrap_or("header");
|
||||||
|
let u = match url::Url::parse(&p.url) {
|
||||||
|
Ok(u) => u,
|
||||||
|
Err(e) => {
|
||||||
|
dbg.steps.push(
|
||||||
|
Step::new("params", "Collect parameters", StepStatus::Error, format!("invalid URL: {e}"))
|
||||||
|
.hint("OAuth 1.0a signs the full URL. Make sure it is absolute and every variable in it resolves."),
|
||||||
|
);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
let rsa = if method.is_rsa() {
|
||||||
|
let (pk, _) = res("private_key");
|
||||||
|
if pk.trim().is_empty() {
|
||||||
|
dbg.steps.push(
|
||||||
|
Step::new("sign", "Sign request", StepStatus::Error, "no private key set")
|
||||||
|
.hint(format!("{} needs an RSA private key in PEM format: a file path relative to the collection, or the PEM text itself.", method.name())),
|
||||||
|
);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let (pem, from) = match super::jwt::load_pem(&pk, root) {
|
||||||
|
Ok(x) => x,
|
||||||
|
Err(e) => {
|
||||||
|
dbg.steps.push(
|
||||||
|
Step::new("sign", "Sign request", 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;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
match rsa_key(&pem) {
|
||||||
|
Ok(k) => Some(k),
|
||||||
|
Err(e) => {
|
||||||
|
dbg.steps.push(
|
||||||
|
Step::new("sign", "Sign request", StepStatus::Error, format!("cannot load RSA key: {e}"))
|
||||||
|
.hint(format!("{from} must hold an unencrypted RSA private key (BEGIN PRIVATE KEY or BEGIN RSA PRIVATE KEY).")),
|
||||||
|
);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
};
|
||||||
|
|
||||||
|
let form = is_form(p);
|
||||||
|
if add_to == "body" && !form && !p.body_bytes().is_empty() {
|
||||||
|
dbg.steps.push(
|
||||||
|
Step::new("params", "Collect parameters", StepStatus::Error, "body placement needs a form body")
|
||||||
|
.hint("OAuth parameters can only go into an application/x-www-form-urlencoded body. Switch the body to form-urlencoded or add the parameters to the header."),
|
||||||
|
);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if add_to == "body" && matches!(p.body, PreparedBody::Multipart { .. }) {
|
||||||
|
dbg.steps.push(
|
||||||
|
Step::new("params", "Collect parameters", StepStatus::Error, "body placement needs a form body")
|
||||||
|
.hint("Multipart bodies cannot carry OAuth parameters. Add them to the header or the query instead."),
|
||||||
|
);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut nonce = [0u8; 16];
|
||||||
|
rand::thread_rng().fill_bytes(&mut nonce);
|
||||||
|
let mut oauth: Vec<(String, String)> = vec![("oauth_consumer_key".into(), consumer_key)];
|
||||||
|
if !token.is_empty() {
|
||||||
|
oauth.push(("oauth_token".into(), token));
|
||||||
|
}
|
||||||
|
oauth.push(("oauth_signature_method".into(), method.name().into()));
|
||||||
|
oauth.push(("oauth_timestamp".into(), chrono::Utc::now().timestamp().to_string()));
|
||||||
|
oauth.push(("oauth_nonce".into(), hex::encode(nonce)));
|
||||||
|
oauth.push(("oauth_version".into(), "1.0".into()));
|
||||||
|
if !callback.is_empty() {
|
||||||
|
oauth.push(("oauth_callback".into(), callback));
|
||||||
|
}
|
||||||
|
if !verifier.is_empty() {
|
||||||
|
oauth.push(("oauth_verifier".into(), verifier));
|
||||||
|
}
|
||||||
|
if cfg.bool("include_body_hash", false) && !form {
|
||||||
|
oauth.push(("oauth_body_hash".into(), method.body_hash(p.body_bytes())));
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut params: Vec<(String, String)> = Vec::new();
|
||||||
|
let mut sources: Vec<serde_json::Value> = Vec::new();
|
||||||
|
for (k, v) in u.query_pairs() {
|
||||||
|
sources.push(serde_json::json!({ "name": k, "value": v, "from": "query" }));
|
||||||
|
params.push((k.into_owned(), v.into_owned()));
|
||||||
|
}
|
||||||
|
if form {
|
||||||
|
for (k, v) in url::form_urlencoded::parse(p.body_bytes()) {
|
||||||
|
sources.push(serde_json::json!({ "name": k, "value": v, "from": "body" }));
|
||||||
|
params.push((k.into_owned(), v.into_owned()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (k, v) in &oauth {
|
||||||
|
sources.push(serde_json::json!({ "name": k, "value": v, "from": "oauth" }));
|
||||||
|
}
|
||||||
|
params.extend(oauth.iter().cloned());
|
||||||
|
dbg.steps.push(
|
||||||
|
Step::new("params", "Collect parameters", StepStatus::Ok, format!("{} parameters, {}", params.len(), method.name()))
|
||||||
|
.data(serde_json::json!({ "parameters": sources, "normalized": normalize(¶ms) })),
|
||||||
|
);
|
||||||
|
|
||||||
|
let base = base_string(&p.method, &u, ¶ms);
|
||||||
|
dbg.steps.push(
|
||||||
|
Step::new("base_string", "Signature base string", StepStatus::Ok, format!("{} {}", p.method.to_ascii_uppercase(), base_uri(&u)))
|
||||||
|
.data(serde_json::json!({ "text": base })),
|
||||||
|
);
|
||||||
|
|
||||||
|
let key = format!("{}&{}", enc(&consumer_secret), enc(&token_secret));
|
||||||
|
let signature = match sign(method, &base, &key, rsa.as_ref()) {
|
||||||
|
Ok(s) => s,
|
||||||
|
Err(e) => {
|
||||||
|
dbg.steps.push(
|
||||||
|
Step::new("sign", "Sign request", StepStatus::Error, format!("signing failed: {e}"))
|
||||||
|
.hint("Check that the private key is a valid RSA key of at least 1024 bits."),
|
||||||
|
);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let key_desc = if method.is_rsa() {
|
||||||
|
format!("{} with the RSA private key", method.name())
|
||||||
|
} else {
|
||||||
|
format!("{}(consumer_secret&{}, base string)", method.name(), if token_secret.is_empty() { "" } else { "token_secret" })
|
||||||
|
};
|
||||||
|
dbg.steps.push(
|
||||||
|
Step::new("sign", "Sign request", StepStatus::Ok, format!("sent as {add_to}"))
|
||||||
|
.data(serde_json::json!({
|
||||||
|
"method": method.name(),
|
||||||
|
"key": key_desc,
|
||||||
|
"signature": if method == Method::Plaintext { "•••".to_string() } else { signature.clone() },
|
||||||
|
}))
|
||||||
|
.took(started),
|
||||||
|
);
|
||||||
|
|
||||||
|
oauth.push(("oauth_signature".into(), signature));
|
||||||
|
match add_to {
|
||||||
|
"query" => {
|
||||||
|
for (k, v) in &oauth {
|
||||||
|
if let Err(e) = p.add_query(k, v) {
|
||||||
|
dbg.steps.push(Step::new("attach", "Attach parameters", StepStatus::Error, e.to_string()));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
dbg.sent.push(Sent { location: "query".into(), name: k.clone(), value: v.clone() });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
"body" => {
|
||||||
|
let mut body = String::from_utf8_lossy(p.body_bytes()).into_owned();
|
||||||
|
let mut ser = url::form_urlencoded::Serializer::new(String::new());
|
||||||
|
for (k, v) in &oauth {
|
||||||
|
ser.append_pair(k, v);
|
||||||
|
dbg.sent.push(Sent { location: "body".into(), name: k.clone(), value: v.clone() });
|
||||||
|
}
|
||||||
|
if !body.is_empty() {
|
||||||
|
body.push('&');
|
||||||
|
}
|
||||||
|
body.push_str(&ser.finish());
|
||||||
|
if !form {
|
||||||
|
p.set_header("Content-Type", "application/x-www-form-urlencoded");
|
||||||
|
}
|
||||||
|
p.body = PreparedBody::Bytes { preview: body.clone(), data: body.into_bytes() };
|
||||||
|
}
|
||||||
|
_ => {
|
||||||
|
let mut parts = Vec::new();
|
||||||
|
if !realm.is_empty() {
|
||||||
|
parts.push(format!("realm=\"{}\"", realm.replace('\\', "\\\\").replace('"', "\\\"")));
|
||||||
|
}
|
||||||
|
parts.extend(oauth.iter().map(|(k, v)| format!("{}=\"{}\"", enc(k), enc(v))));
|
||||||
|
let value = format!("OAuth {}", parts.join(", "));
|
||||||
|
p.set_header("Authorization", &value);
|
||||||
|
dbg.sent.push(Sent { location: "header".into(), name: "Authorization".into(), value });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
// Example from the Twitter developer docs ("Creating a signature").
|
||||||
|
#[test]
|
||||||
|
fn twitter_example() {
|
||||||
|
let u = url::Url::parse("https://api.twitter.com/1.1/statuses/update.json?include_entities=true").unwrap();
|
||||||
|
let mut params: Vec<(String, String)> = u.query_pairs().map(|(k, v)| (k.into(), v.into())).collect();
|
||||||
|
let body = "status=Hello%20Ladies%20%2b%20Gentlemen%2c%20a%20signed%20OAuth%20request%21";
|
||||||
|
params.extend(url::form_urlencoded::parse(body.as_bytes()).map(|(k, v)| (k.into_owned(), v.into_owned())));
|
||||||
|
for (k, v) in [
|
||||||
|
("oauth_consumer_key", "xvz1evFS4wEEPTGEFPHBog"),
|
||||||
|
("oauth_nonce", "kYjzVBB8Y0ZFabxSWbWovY3uYSQ2pTgmZeNu2VS4cg"),
|
||||||
|
("oauth_signature_method", "HMAC-SHA1"),
|
||||||
|
("oauth_timestamp", "1318622958"),
|
||||||
|
("oauth_token", "370773112-GmHxMAgYyLbNEtIKZeRNFsMKPR9EyMZeS9weJAEb"),
|
||||||
|
("oauth_version", "1.0"),
|
||||||
|
] {
|
||||||
|
params.push((k.into(), v.into()));
|
||||||
|
}
|
||||||
|
let base = base_string("post", &u, ¶ms);
|
||||||
|
assert_eq!(
|
||||||
|
base,
|
||||||
|
"POST&https%3A%2F%2Fapi.twitter.com%2F1.1%2Fstatuses%2Fupdate.json&include_entities%3Dtrue%26oauth_consumer_key%3Dxvz1evFS4wEEPTGEFPHBog%26oauth_nonce%3DkYjzVBB8Y0ZFabxSWbWovY3uYSQ2pTgmZeNu2VS4cg%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1318622958%26oauth_token%3D370773112-GmHxMAgYyLbNEtIKZeRNFsMKPR9EyMZeS9weJAEb%26oauth_version%3D1.0%26status%3DHello%2520Ladies%2520%252B%2520Gentlemen%252C%2520a%2520signed%2520OAuth%2520request%2521"
|
||||||
|
);
|
||||||
|
let key = format!(
|
||||||
|
"{}&{}",
|
||||||
|
enc("kAcSOqF21Fu85e7zjz7ZN2U4ZRhfV3WpwPAoE3Z7kBw"),
|
||||||
|
enc("LswwdoUaIvS8ltyTt5jkRh4J50vUPVVHtR2YPi5kE")
|
||||||
|
);
|
||||||
|
assert_eq!(sign(Method::HmacSha1, &base, &key, None).unwrap(), "hCtSmYh+iHYCEqBWrE7C7hYmtUk=");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn base_uri_rules() {
|
||||||
|
let u = url::Url::parse("HTTP://Example.COM:80/r%20v/X?id=123").unwrap();
|
||||||
|
assert_eq!(base_uri(&u), "http://example.com/r%20v/X");
|
||||||
|
let u = url::Url::parse("https://www.example.net:8080/?q=1").unwrap();
|
||||||
|
assert_eq!(base_uri(&u), "https://www.example.net:8080/");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn header_and_form_body() {
|
||||||
|
let cfg: AuthConfig = serde_json::from_value(serde_json::json!({
|
||||||
|
"type": "oauth1", "consumer_key": "ck", "consumer_secret": "cs", "token": "t", "token_secret": "ts",
|
||||||
|
"realm": "Photos", "include_body_hash": true
|
||||||
|
}))
|
||||||
|
.unwrap();
|
||||||
|
let res = |k: &str| -> (String, Vec<String>) { (cfg.string(k), vec![]) };
|
||||||
|
let mut p = Prepared {
|
||||||
|
method: "POST".into(),
|
||||||
|
url: "https://example.org/x?b=2".into(),
|
||||||
|
headers: vec![("Content-Type".into(), "application/x-www-form-urlencoded".into())],
|
||||||
|
body: PreparedBody::Bytes { data: b"a=1".to_vec(), preview: "a=1".into() },
|
||||||
|
settings: Default::default(),
|
||||||
|
missing: vec![],
|
||||||
|
cycles: vec![],
|
||||||
|
};
|
||||||
|
let mut dbg = AuthDebug::default();
|
||||||
|
apply(&cfg, &mut p, &res, Path::new("."), &mut dbg);
|
||||||
|
assert!(!dbg.failed(), "{:?}", dbg.steps);
|
||||||
|
let h = p.header("Authorization").unwrap();
|
||||||
|
assert!(h.starts_with("OAuth realm=\"Photos\", oauth_consumer_key=\"ck\""));
|
||||||
|
assert!(h.contains("oauth_signature=\"") && !h.contains("oauth_body_hash"));
|
||||||
|
let base = dbg.steps[1].data["text"].as_str().unwrap();
|
||||||
|
assert!(base.contains("a%3D1") && base.contains("b%3D2"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rsa_sha256_signs() {
|
||||||
|
let mut rng = rand::thread_rng();
|
||||||
|
let key = RsaPrivateKey::new(&mut rng, 1024).unwrap();
|
||||||
|
let sig = sign(Method::RsaSha256, "GET&x&y", "", Some(&key)).unwrap();
|
||||||
|
assert_eq!(base64::engine::general_purpose::STANDARD.decode(sig).unwrap().len(), 128);
|
||||||
|
assert!(sign(Method::RsaSha1, "GET&x&y", "", None).is_err());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,353 @@
|
|||||||
|
//! AWS Signature Version 4.
|
||||||
|
|
||||||
|
use super::{AuthDebug, Res, Sent, Step, StepStatus};
|
||||||
|
use crate::model::AuthConfig;
|
||||||
|
use crate::prepare::{Prepared, PreparedBody};
|
||||||
|
use hmac::{Hmac, Mac};
|
||||||
|
use percent_encoding::{utf8_percent_encode, AsciiSet, NON_ALPHANUMERIC};
|
||||||
|
use sha2::{Digest, Sha256};
|
||||||
|
|
||||||
|
type HmacSha256 = Hmac<Sha256>;
|
||||||
|
|
||||||
|
/// Everything except A-Z a-z 0-9 - _ . ~
|
||||||
|
const RFC3986: &AsciiSet = &NON_ALPHANUMERIC.remove(b'-').remove(b'_').remove(b'.').remove(b'~');
|
||||||
|
|
||||||
|
const UNSIGNED: &str = "UNSIGNED-PAYLOAD";
|
||||||
|
const PRESIGN_EXPIRES: &str = "3600";
|
||||||
|
|
||||||
|
fn enc(s: &str) -> String {
|
||||||
|
utf8_percent_encode(s, RFC3986).to_string()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn hmac(key: &[u8], msg: &str) -> Vec<u8> {
|
||||||
|
// HMAC accepts keys of any length.
|
||||||
|
let mut m = HmacSha256::new_from_slice(key).unwrap_or_else(|_| unreachable!());
|
||||||
|
m.update(msg.as_bytes());
|
||||||
|
m.finalize().into_bytes().to_vec()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn sha256_hex(b: &[u8]) -> String {
|
||||||
|
hex::encode(Sha256::digest(b))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn decode(s: &str) -> String {
|
||||||
|
percent_encoding::percent_decode_str(s).decode_utf8_lossy().into_owned()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) struct Credentials<'a> {
|
||||||
|
pub secret_key: &'a str,
|
||||||
|
pub region: &'a str,
|
||||||
|
pub service: &'a str,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) struct Signed {
|
||||||
|
pub canonical_request: String,
|
||||||
|
pub string_to_sign: String,
|
||||||
|
pub scope: String,
|
||||||
|
pub signed_headers: String,
|
||||||
|
/// (label, hex) for kDate, kRegion, kService, kSigning
|
||||||
|
pub keys: Vec<(String, String)>,
|
||||||
|
pub signature: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn canonical_uri(path: &str, service: &str) -> String {
|
||||||
|
if path.is_empty() {
|
||||||
|
return "/".into();
|
||||||
|
}
|
||||||
|
let segments = path.split('/').map(|seg| {
|
||||||
|
if service == "s3" {
|
||||||
|
enc(&decode(seg))
|
||||||
|
} else {
|
||||||
|
// Non-S3 services encode the already encoded path a second time.
|
||||||
|
enc(&enc(&decode(seg)))
|
||||||
|
}
|
||||||
|
});
|
||||||
|
segments.collect::<Vec<_>>().join("/")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn canonical_query(query: Option<&str>) -> String {
|
||||||
|
let mut pairs: Vec<(String, String)> = query
|
||||||
|
.unwrap_or_default()
|
||||||
|
.split('&')
|
||||||
|
.filter(|s| !s.is_empty())
|
||||||
|
.map(|kv| {
|
||||||
|
let (k, v) = kv.split_once('=').unwrap_or((kv, ""));
|
||||||
|
(enc(&decode(&k.replace('+', " "))), enc(&decode(&v.replace('+', " "))))
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
pairs.sort();
|
||||||
|
pairs.iter().map(|(k, v)| format!("{k}={v}")).collect::<Vec<_>>().join("&")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn trim_value(v: &str) -> String {
|
||||||
|
v.split_whitespace().collect::<Vec<_>>().join(" ")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Pure signing: canonical request, string to sign, key derivation and
|
||||||
|
/// signature for the given request parts and timestamp (`YYYYMMDDTHHMMSSZ`).
|
||||||
|
pub(crate) fn sign(
|
||||||
|
method: &str,
|
||||||
|
url: &url::Url,
|
||||||
|
headers: &[(String, String)],
|
||||||
|
payload_hash: &str,
|
||||||
|
creds: &Credentials<'_>,
|
||||||
|
amz_date: &str,
|
||||||
|
) -> Signed {
|
||||||
|
let date = &amz_date[..amz_date.len().min(8)];
|
||||||
|
let mut hs: Vec<(String, String)> = Vec::new();
|
||||||
|
for (k, v) in headers {
|
||||||
|
let k = k.to_ascii_lowercase();
|
||||||
|
let v = trim_value(v);
|
||||||
|
match hs.iter_mut().find(|(n, _)| *n == k) {
|
||||||
|
Some((_, existing)) => {
|
||||||
|
existing.push(',');
|
||||||
|
existing.push_str(&v);
|
||||||
|
}
|
||||||
|
None => hs.push((k, v)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
hs.sort_by(|a, b| a.0.cmp(&b.0));
|
||||||
|
let canonical_headers: String = hs.iter().map(|(k, v)| format!("{k}:{v}\n")).collect();
|
||||||
|
let signed_headers = hs.iter().map(|(k, _)| k.as_str()).collect::<Vec<_>>().join(";");
|
||||||
|
|
||||||
|
let canonical_request = format!(
|
||||||
|
"{}\n{}\n{}\n{}\n{}\n{}",
|
||||||
|
method.to_ascii_uppercase(),
|
||||||
|
canonical_uri(url.path(), creds.service),
|
||||||
|
canonical_query(url.query()),
|
||||||
|
canonical_headers,
|
||||||
|
signed_headers,
|
||||||
|
payload_hash
|
||||||
|
);
|
||||||
|
let scope = format!("{date}/{}/{}/aws4_request", creds.region, creds.service);
|
||||||
|
let string_to_sign =
|
||||||
|
format!("AWS4-HMAC-SHA256\n{amz_date}\n{scope}\n{}", sha256_hex(canonical_request.as_bytes()));
|
||||||
|
|
||||||
|
let k_date = hmac(format!("AWS4{}", creds.secret_key).as_bytes(), date);
|
||||||
|
let k_region = hmac(&k_date, creds.region);
|
||||||
|
let k_service = hmac(&k_region, creds.service);
|
||||||
|
let k_signing = hmac(&k_service, "aws4_request");
|
||||||
|
let signature = hex::encode(hmac(&k_signing, &string_to_sign));
|
||||||
|
let keys = vec![
|
||||||
|
(format!("kDate = HMAC(\"AWS4\" + secret, \"{date}\")"), hex::encode(&k_date)),
|
||||||
|
(format!("kRegion = HMAC(kDate, \"{}\")", creds.region), hex::encode(&k_region)),
|
||||||
|
(format!("kService = HMAC(kRegion, \"{}\")", creds.service), hex::encode(&k_service)),
|
||||||
|
("kSigning = HMAC(kService, \"aws4_request\")".to_string(), hex::encode(&k_signing)),
|
||||||
|
];
|
||||||
|
Signed { canonical_request, string_to_sign, scope, signed_headers, keys, signature }
|
||||||
|
}
|
||||||
|
|
||||||
|
fn field(dbg: &mut AuthDebug, res: &Res<'_>, name: &str, required: bool) -> String {
|
||||||
|
let (v, missing) = res(name);
|
||||||
|
if !missing.is_empty() {
|
||||||
|
dbg.warnings.push(format!(
|
||||||
|
"{name}: variable {} is not defined, sent as literal text",
|
||||||
|
missing.iter().map(|m| format!("{{{{{m}}}}}")).collect::<Vec<_>>().join(", ")
|
||||||
|
));
|
||||||
|
} else if v.is_empty() && required {
|
||||||
|
dbg.warnings.push(format!("{name} resolved to an empty value"));
|
||||||
|
}
|
||||||
|
v.trim().to_string()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) fn apply(cfg: &AuthConfig, p: &mut Prepared, res: &Res<'_>, dbg: &mut AuthDebug) {
|
||||||
|
let started = std::time::Instant::now();
|
||||||
|
let access_key = field(dbg, res, "access_key", true);
|
||||||
|
let secret_key = field(dbg, res, "secret_key", true);
|
||||||
|
let session_token = field(dbg, res, "session_token", false);
|
||||||
|
let region = field(dbg, res, "region", true);
|
||||||
|
let service = field(dbg, res, "service", true);
|
||||||
|
let presign = cfg.str("sign_in") == Some("query");
|
||||||
|
|
||||||
|
if region.is_empty() || service.is_empty() {
|
||||||
|
dbg.steps.push(
|
||||||
|
Step::new("canonical", "Canonical request", StepStatus::Error, "region or service is empty")
|
||||||
|
.hint("Set region (e.g. eu-central-1) and service (e.g. s3, execute-api, lambda) in the auth settings."),
|
||||||
|
);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let mut url = match url::Url::parse(&p.url) {
|
||||||
|
Ok(u) => u,
|
||||||
|
Err(e) => {
|
||||||
|
dbg.steps.push(
|
||||||
|
Step::new("canonical", "Canonical request", StepStatus::Error, format!("invalid URL: {e}"))
|
||||||
|
.hint("SigV4 signs the full URL. Make sure it is absolute and every variable in it resolves."),
|
||||||
|
);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let host = match (url.host_str(), url.port()) {
|
||||||
|
(Some(h), Some(port)) => format!("{h}:{port}"),
|
||||||
|
(Some(h), None) => h.to_string(),
|
||||||
|
(None, _) => {
|
||||||
|
dbg.steps.push(
|
||||||
|
Step::new("canonical", "Canonical request", StepStatus::Error, "the URL has no host")
|
||||||
|
.hint("SigV4 signs the host header. Use an absolute URL such as https://s3.amazonaws.com/bucket/key."),
|
||||||
|
);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
let amz_date = chrono::Utc::now().format("%Y%m%dT%H%M%SZ").to_string();
|
||||||
|
let payload_hash = match &p.body {
|
||||||
|
PreparedBody::Multipart { .. } => UNSIGNED.to_string(),
|
||||||
|
_ if presign && service == "s3" => UNSIGNED.to_string(),
|
||||||
|
_ => sha256_hex(p.body_bytes()),
|
||||||
|
};
|
||||||
|
let creds = Credentials { secret_key: &secret_key, region: ®ion, service: &service };
|
||||||
|
let date = &amz_date[..8];
|
||||||
|
let scope = format!("{date}/{region}/{service}/aws4_request");
|
||||||
|
|
||||||
|
let mut attached: Vec<(&str, String, String)> = Vec::new();
|
||||||
|
let signed = if presign {
|
||||||
|
{
|
||||||
|
let mut q = url.query_pairs_mut();
|
||||||
|
q.append_pair("X-Amz-Algorithm", "AWS4-HMAC-SHA256");
|
||||||
|
q.append_pair("X-Amz-Credential", &format!("{access_key}/{scope}"));
|
||||||
|
q.append_pair("X-Amz-Date", &amz_date);
|
||||||
|
q.append_pair("X-Amz-Expires", PRESIGN_EXPIRES);
|
||||||
|
if !session_token.is_empty() {
|
||||||
|
q.append_pair("X-Amz-Security-Token", &session_token);
|
||||||
|
}
|
||||||
|
q.append_pair("X-Amz-SignedHeaders", "host");
|
||||||
|
}
|
||||||
|
let s = sign(&p.method, &url, &[("host".into(), host.clone())], &payload_hash, &creds, &amz_date);
|
||||||
|
url.query_pairs_mut().append_pair("X-Amz-Signature", &s.signature);
|
||||||
|
p.url = url.to_string();
|
||||||
|
attached.push(("query", "X-Amz-Credential".into(), format!("{access_key}/{scope}")));
|
||||||
|
if !session_token.is_empty() {
|
||||||
|
attached.push(("query", "X-Amz-Security-Token".into(), session_token.clone()));
|
||||||
|
}
|
||||||
|
attached.push(("query", "X-Amz-Signature".into(), s.signature.clone()));
|
||||||
|
s
|
||||||
|
} else {
|
||||||
|
p.set_header("x-amz-date", &amz_date);
|
||||||
|
p.set_header("x-amz-content-sha256", &payload_hash);
|
||||||
|
if !session_token.is_empty() {
|
||||||
|
p.set_header("x-amz-security-token", &session_token);
|
||||||
|
}
|
||||||
|
let mut to_sign: Vec<(String, String)> = vec![("host".into(), host.clone())];
|
||||||
|
for (k, v) in &p.headers {
|
||||||
|
let l = k.to_ascii_lowercase();
|
||||||
|
if l == "host" || l == "authorization" || l == "user-agent" || l == "expect" {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if l.starts_with("x-amz-") || l == "content-type" || l == "content-md5" || l == "range" {
|
||||||
|
to_sign.push((k.clone(), v.clone()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let s = sign(&p.method, &url, &to_sign, &payload_hash, &creds, &amz_date);
|
||||||
|
let value = format!(
|
||||||
|
"AWS4-HMAC-SHA256 Credential={access_key}/{}, SignedHeaders={}, Signature={}",
|
||||||
|
s.scope, s.signed_headers, s.signature
|
||||||
|
);
|
||||||
|
p.set_header("Authorization", &value);
|
||||||
|
attached.push(("header", "x-amz-date".into(), amz_date.clone()));
|
||||||
|
attached.push(("header", "x-amz-content-sha256".into(), payload_hash.clone()));
|
||||||
|
if !session_token.is_empty() {
|
||||||
|
attached.push(("header", "x-amz-security-token".into(), session_token.clone()));
|
||||||
|
}
|
||||||
|
attached.push(("header", "Authorization".into(), value));
|
||||||
|
s
|
||||||
|
};
|
||||||
|
|
||||||
|
dbg.steps.push(
|
||||||
|
Step::new(
|
||||||
|
"canonical",
|
||||||
|
"Canonical request",
|
||||||
|
StepStatus::Ok,
|
||||||
|
format!("{} {}, signed headers {}", p.method.to_ascii_uppercase(), url.path(), signed.signed_headers),
|
||||||
|
)
|
||||||
|
.data(serde_json::json!({
|
||||||
|
"text": signed.canonical_request,
|
||||||
|
"payload_hash": payload_hash,
|
||||||
|
"signed_headers": signed.signed_headers,
|
||||||
|
"sign_in": if presign { "query" } else { "header" },
|
||||||
|
})),
|
||||||
|
);
|
||||||
|
dbg.steps.push(
|
||||||
|
Step::new("string_to_sign", "String to sign", StepStatus::Ok, format!("scope {}", signed.scope))
|
||||||
|
.data(serde_json::json!({ "text": signed.string_to_sign, "date": amz_date, "scope": signed.scope })),
|
||||||
|
);
|
||||||
|
dbg.steps.push(
|
||||||
|
Step::new("signing_key", "Signing key derivation", StepStatus::Ok, "four HMAC-SHA256 rounds from the secret key")
|
||||||
|
.data(serde_json::json!(signed
|
||||||
|
.keys
|
||||||
|
.iter()
|
||||||
|
.map(|(label, hex)| serde_json::json!({ "step": label, "hex": hex }))
|
||||||
|
.collect::<Vec<_>>())),
|
||||||
|
);
|
||||||
|
dbg.steps.push(
|
||||||
|
Step::new(
|
||||||
|
"signature",
|
||||||
|
"Signature",
|
||||||
|
StepStatus::Ok,
|
||||||
|
format!("HMAC(kSigning, string to sign), sent as {}", if presign { "query" } else { "header" }),
|
||||||
|
)
|
||||||
|
.data(serde_json::json!({ "signature": signed.signature }))
|
||||||
|
.took(started),
|
||||||
|
);
|
||||||
|
for (location, name, value) in attached {
|
||||||
|
dbg.sent.push(Sent { location: location.into(), name, value });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
// GET iam ListUsers example from the AWS SigV4 documentation.
|
||||||
|
#[test]
|
||||||
|
fn aws_documented_example() {
|
||||||
|
let url = url::Url::parse("https://iam.amazonaws.com/?Action=ListUsers&Version=2010-05-08").unwrap();
|
||||||
|
let headers = vec![
|
||||||
|
("Host".to_string(), "iam.amazonaws.com".to_string()),
|
||||||
|
("Content-Type".to_string(), "application/x-www-form-urlencoded; charset=utf-8".to_string()),
|
||||||
|
("X-Amz-Date".to_string(), "20150830T123600Z".to_string()),
|
||||||
|
];
|
||||||
|
let creds = Credentials {
|
||||||
|
secret_key: "wJalrXUtnFEMI/K7MDENG+bPxRfiCYEXAMPLEKEY",
|
||||||
|
region: "us-east-1",
|
||||||
|
service: "iam",
|
||||||
|
};
|
||||||
|
let s = sign("GET", &url, &headers, &sha256_hex(b""), &creds, "20150830T123600Z");
|
||||||
|
assert_eq!(
|
||||||
|
s.canonical_request,
|
||||||
|
"GET\n/\nAction=ListUsers&Version=2010-05-08\ncontent-type:application/x-www-form-urlencoded; charset=utf-8\nhost:iam.amazonaws.com\nx-amz-date:20150830T123600Z\n\ncontent-type;host;x-amz-date\ne3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
s.string_to_sign,
|
||||||
|
"AWS4-HMAC-SHA256\n20150830T123600Z\n20150830/us-east-1/iam/aws4_request\nf536975d06c0309214f805bb90ccff089219ecd68b2577efef23edd43b7e1a59"
|
||||||
|
);
|
||||||
|
assert_eq!(s.keys[3].1, "c4afb1cc5771d871763a393e44b703571b55cc28424d1a5e86da6ed3c154a4b9");
|
||||||
|
assert_eq!(s.signature, "5d672d79c15b13162d9279b0855cfba6789a8edb4c82c400e06b5924a6f2b5d7");
|
||||||
|
}
|
||||||
|
|
||||||
|
// Presigned GET example from the S3 SigV4 query-string documentation.
|
||||||
|
#[test]
|
||||||
|
fn s3_presigned_example() {
|
||||||
|
let mut url = url::Url::parse("https://examplebucket.s3.amazonaws.com/test.txt").unwrap();
|
||||||
|
url.query_pairs_mut()
|
||||||
|
.append_pair("X-Amz-Algorithm", "AWS4-HMAC-SHA256")
|
||||||
|
.append_pair("X-Amz-Credential", "AKIAIOSFODNN7EXAMPLE/20130524/us-east-1/s3/aws4_request")
|
||||||
|
.append_pair("X-Amz-Date", "20130524T000000Z")
|
||||||
|
.append_pair("X-Amz-Expires", "86400")
|
||||||
|
.append_pair("X-Amz-SignedHeaders", "host");
|
||||||
|
let creds = Credentials {
|
||||||
|
secret_key: "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY",
|
||||||
|
region: "us-east-1",
|
||||||
|
service: "s3",
|
||||||
|
};
|
||||||
|
let headers = vec![("host".to_string(), "examplebucket.s3.amazonaws.com".to_string())];
|
||||||
|
let s = sign("GET", &url, &headers, UNSIGNED, &creds, "20130524T000000Z");
|
||||||
|
assert_eq!(s.signature, "aeeed9bbccd4d02ee5c0109b86d86835f995330da4c265957d157751f604d404");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn uri_and_query_encoding() {
|
||||||
|
assert_eq!(canonical_uri("/a b/c%2Fd", "s3"), "/a%20b/c%2Fd");
|
||||||
|
assert_eq!(canonical_uri("/a b", "execute-api"), "/a%2520b");
|
||||||
|
assert_eq!(canonical_uri("", "s3"), "/");
|
||||||
|
assert_eq!(canonical_query(Some("b=2&a=x y&a=1&c")), "a=1&a=x%20y&b=2&c=");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,9 +1,8 @@
|
|||||||
use super::{AuthDebug, Sent, Step, StepStatus};
|
use super::{AuthDebug, Res, Sent, Step, StepStatus};
|
||||||
use crate::model::AuthConfig;
|
use crate::model::AuthConfig;
|
||||||
use crate::prepare::Prepared;
|
use crate::prepare::Prepared;
|
||||||
use base64::Engine;
|
use base64::Engine;
|
||||||
|
|
||||||
type Res<'a> = dyn Fn(&str) -> (String, Vec<String>) + 'a;
|
|
||||||
|
|
||||||
fn check(dbg: &mut AuthDebug, field: &str, value: &str, missing: &[String]) {
|
fn check(dbg: &mut AuthDebug, field: &str, value: &str, missing: &[String]) {
|
||||||
if !missing.is_empty() {
|
if !missing.is_empty() {
|
||||||
|
|||||||
@@ -0,0 +1,121 @@
|
|||||||
|
//! Client certificate helpers.
|
||||||
|
|
||||||
|
use anyhow::{anyhow, bail};
|
||||||
|
use base64::Engine;
|
||||||
|
use p12_keystore::{error::Error as P12Error, KeyStore, KeyStoreEntry, Pkcs12ImportPolicy};
|
||||||
|
|
||||||
|
/// Converts a PKCS#12 bundle into PEM (certificate chain followed by the
|
||||||
|
/// private key), which is what the HTTP client accepts.
|
||||||
|
pub fn pkcs12_to_pem(der: &[u8], passphrase: &str) -> anyhow::Result<Vec<u8>> {
|
||||||
|
let store = KeyStore::from_pkcs12(der, passphrase, Pkcs12ImportPolicy::Relaxed).map_err(|e| match e {
|
||||||
|
P12Error::MacError(_) | P12Error::UnpadError => {
|
||||||
|
if passphrase.is_empty() {
|
||||||
|
anyhow!("the PKCS#12 file is protected by a passphrase, but none is set")
|
||||||
|
} else {
|
||||||
|
anyhow!("wrong passphrase for the PKCS#12 file")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
P12Error::UnsupportedEncryptionScheme | P12Error::UnsupportedMacAlgorithm => {
|
||||||
|
anyhow!("the PKCS#12 file uses an unsupported encryption ({e}); re-export it with AES-256 or 3DES")
|
||||||
|
}
|
||||||
|
other => anyhow!("not a readable PKCS#12 file: {other}"),
|
||||||
|
})?;
|
||||||
|
|
||||||
|
let mut certs: Vec<&[u8]> = Vec::new();
|
||||||
|
let mut key: Option<&[u8]> = None;
|
||||||
|
if let Some((_, chain)) = store.private_key_chain() {
|
||||||
|
key = Some(chain.key().as_der());
|
||||||
|
certs.extend(chain.certs().iter().map(|c| c.as_der()));
|
||||||
|
}
|
||||||
|
for (_, entry) in store.entries() {
|
||||||
|
match entry {
|
||||||
|
KeyStoreEntry::PrivateKeyChain(c) if key.is_none() => {
|
||||||
|
key = Some(c.key().as_der());
|
||||||
|
certs.extend(c.certs().iter().map(|c| c.as_der()));
|
||||||
|
}
|
||||||
|
KeyStoreEntry::Certificate(c) if !certs.contains(&c.as_der()) => certs.push(c.as_der()),
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let Some(key) = key else {
|
||||||
|
bail!("the PKCS#12 file contains no private key");
|
||||||
|
};
|
||||||
|
if certs.is_empty() {
|
||||||
|
bail!("the PKCS#12 file contains no certificate");
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut out = String::new();
|
||||||
|
for c in certs {
|
||||||
|
out.push_str(&pem_block("CERTIFICATE", c));
|
||||||
|
}
|
||||||
|
out.push_str(&pem_block("PRIVATE KEY", key));
|
||||||
|
Ok(out.into_bytes())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn pem_block(label: &str, der: &[u8]) -> String {
|
||||||
|
let b64 = base64::engine::general_purpose::STANDARD.encode(der);
|
||||||
|
let mut s = format!("-----BEGIN {label}-----\n");
|
||||||
|
for line in b64.as_bytes().chunks(64) {
|
||||||
|
s.push_str(std::str::from_utf8(line).unwrap_or_default());
|
||||||
|
s.push('\n');
|
||||||
|
}
|
||||||
|
s.push_str(&format!("-----END {label}-----\n"));
|
||||||
|
s
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
// Self-signed P-256 cert and key, AES-256-CBC, passphrase "hunter2".
|
||||||
|
const BUNDLE: &[&str] = &[
|
||||||
|
"MIIEBAIBAzCCA7IGCSqGSIb3DQEHAaCCA6MEggOfMIIDmzCCAkoGCSqGSIb3DQEHBqCCAjswggI3AgEAMIICMAYJKoZIhvcN",
|
||||||
|
"AQcBMF8GCSqGSIb3DQEFDTBSMDEGCSqGSIb3DQEFDDAkBBAeddhqb82yMMhXjwHIz/OPAgIIADAMBggqhkiG9w0CCQUAMB0G",
|
||||||
|
"CWCGSAFlAwQBKgQQF1Nb/vpbmCnmkpcrIQBq44CCAcDxpHu5WcMWrOMNWN+pFa9k1K50A6oYX4XaGnzan1JLafBpqcjHO6O0",
|
||||||
|
"43u3qMYn+RQgh3Q59Jf9+2I+1hNO4cP3clamvLIP5mUA2AmzVp6B5mb3wqvOOysOafv4zFgxSyl6vEhJjkg87UdyTynSjeki",
|
||||||
|
"W5G2RcSSyUO+0sCBj6y5kRpRbobVsO/UO5AT7IW7hXBXmE5fYqCt+U035rPVNtubgHS/mKg5b/nk7RN2y6h5YhCveGQC17BP",
|
||||||
|
"tQ2UKdc4EwK+U0O0ibkDFJgHbex9jof+x4Ne6w8tntSMBzojRCEJKmgyElcsEKTSx1uepjaGZ38/ZnNZhHn+rdLN3aGA0ukT",
|
||||||
|
"ACIe7d+mye80nwLt0dE8zGMPLViyN8hWs7DHiBx17WQeKpxSAZFNijOgiYbq/T3kAOoXdZniuRGqmp5EbNmhM2NE3EfBrIOr",
|
||||||
|
"IRfQWshgVxMRzOonzggdZPlccNY+04ngS6AvfrSPYHBqu/GQIZrMNQosr3+VlYsmotnhkAeEcjdwBYw86GMoyOot+mv9wZtv",
|
||||||
|
"Pu/LOeJXnCUa4fYPrr3gCK0MApP/WdqlYTOVmoXmWmjCrVejUYjzClOMiruAJYuUMIIBSQYJKoZIhvcNAQcBoIIBOgSCATYw",
|
||||||
|
"ggEyMIIBLgYLKoZIhvcNAQwKAQKggfcwgfQwXwYJKoZIhvcNAQUNMFIwMQYJKoZIhvcNAQUMMCQEEGVzh8heMGNxjIYdYpae",
|
||||||
|
"AWcCAggAMAwGCCqGSIb3DQIJBQAwHQYJYIZIAWUDBAEqBBA50AzZSSNOhbnv9knXgd7qBIGQjiOS5v6ImBkoqgLzr4Hqx+Ra",
|
||||||
|
"VEFYvCot4irCBUEMlBtq5o/nMabUrkMB1KpZSGtbV/pd457JHMT8A6B6O8Oxjy2R0IL5+ZF9Bgl2z3HlJY1Nyj66pV3jcg4J",
|
||||||
|
"ZOduBNEk0tWzn990wkgVqB9mYDiCo3PaNdHNZZt548Vm6Y7KSSSXOCTtBpsGf4JJ5iEpizv5MSUwIwYJKoZIhvcNAQkVMRYE",
|
||||||
|
"FDlvmfdfFnAmo13BqOTmGGP88BtUMEkwMTANBglghkgBZQMEAgEFAAQgNtGDm4SYoc9Sh3eMaaNTcgaFSPpV0ZAcdlfyvXmR",
|
||||||
|
"0HEEEBA69YVVCnj2q+FMLykb8xoCAggA",
|
||||||
|
];
|
||||||
|
|
||||||
|
fn bundle() -> Vec<u8> {
|
||||||
|
base64::engine::general_purpose::STANDARD.decode(BUNDLE.concat()).unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn converts_bundle() {
|
||||||
|
let pem = String::from_utf8(pkcs12_to_pem(&bundle(), "hunter2").unwrap()).unwrap();
|
||||||
|
let cert = pem.find("-----BEGIN CERTIFICATE-----").unwrap();
|
||||||
|
let key = pem.find("-----BEGIN PRIVATE KEY-----").unwrap();
|
||||||
|
assert!(cert < key);
|
||||||
|
assert_eq!(pem.matches("-----BEGIN").count(), 2);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn wrong_passphrase() {
|
||||||
|
let e = pkcs12_to_pem(&bundle(), "nope").unwrap_err().to_string();
|
||||||
|
assert!(e.contains("wrong passphrase"), "{e}");
|
||||||
|
let e = pkcs12_to_pem(&bundle(), "").unwrap_err().to_string();
|
||||||
|
assert!(e.contains("none is set"), "{e}");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rejects_garbage() {
|
||||||
|
assert!(pkcs12_to_pem(b"not a bundle", "x").is_err());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn pem_lines_wrap_at_64() {
|
||||||
|
let block = pem_block("CERTIFICATE", &[7u8; 100]);
|
||||||
|
assert!(block.lines().all(|l| l.len() <= 64 || l.starts_with("-----")));
|
||||||
|
assert!(block.ends_with("-----END CERTIFICATE-----\n"));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -3,6 +3,7 @@ pub mod checks;
|
|||||||
pub mod collection;
|
pub mod collection;
|
||||||
pub mod http;
|
pub mod http;
|
||||||
pub mod model;
|
pub mod model;
|
||||||
|
pub mod oauth;
|
||||||
pub mod prepare;
|
pub mod prepare;
|
||||||
pub mod run;
|
pub mod run;
|
||||||
pub mod secrets;
|
pub mod secrets;
|
||||||
|
|||||||
@@ -0,0 +1,189 @@
|
|||||||
|
use crate::model::AuthConfig;
|
||||||
|
use crate::vars::Resolver;
|
||||||
|
use indexmap::IndexMap;
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
pub const DEFAULT_PORT: u16 = 53127;
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
#[serde(rename_all = "snake_case")]
|
||||||
|
pub enum Grant {
|
||||||
|
AuthorizationCode,
|
||||||
|
ClientCredentials,
|
||||||
|
DeviceCode,
|
||||||
|
Password,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
#[serde(rename_all = "snake_case")]
|
||||||
|
pub enum ClientAuth {
|
||||||
|
Basic,
|
||||||
|
Post,
|
||||||
|
None,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
#[serde(rename_all = "snake_case")]
|
||||||
|
pub enum RedirectMode {
|
||||||
|
Loopback,
|
||||||
|
CustomScheme,
|
||||||
|
Manual,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// An OAuth config with every variable resolved.
|
||||||
|
#[derive(Debug, Clone, Serialize)]
|
||||||
|
pub struct OauthConfig {
|
||||||
|
pub name: String,
|
||||||
|
pub oidc: bool,
|
||||||
|
pub grant: Grant,
|
||||||
|
pub issuer: String,
|
||||||
|
pub authorize_url: String,
|
||||||
|
pub token_url: String,
|
||||||
|
pub userinfo_url: String,
|
||||||
|
pub jwks_url: String,
|
||||||
|
pub revocation_url: String,
|
||||||
|
pub introspection_url: String,
|
||||||
|
pub end_session_url: String,
|
||||||
|
pub device_url: String,
|
||||||
|
pub client_id: String,
|
||||||
|
pub client_secret: String,
|
||||||
|
pub client_auth: ClientAuth,
|
||||||
|
pub scopes: Vec<String>,
|
||||||
|
pub audience: String,
|
||||||
|
pub resource: String,
|
||||||
|
pub redirect_mode: RedirectMode,
|
||||||
|
pub redirect_host: String,
|
||||||
|
pub redirect_port: u16,
|
||||||
|
pub redirect_path: String,
|
||||||
|
/// Used as-is for manual mode (a fixed HTTPS page registered at the provider).
|
||||||
|
pub manual_redirect_uri: String,
|
||||||
|
pub pkce: bool,
|
||||||
|
pub username: String,
|
||||||
|
pub password: String,
|
||||||
|
pub authorize_params: IndexMap<String, String>,
|
||||||
|
pub token_params: IndexMap<String, String>,
|
||||||
|
/// Attach the id token instead of the access token.
|
||||||
|
pub use_id_token: bool,
|
||||||
|
pub auto_refresh: bool,
|
||||||
|
pub verify_tls: bool,
|
||||||
|
/// Variables that were undefined while resolving the config.
|
||||||
|
pub missing: Vec<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl OauthConfig {
|
||||||
|
pub fn from_auth(cfg: &AuthConfig, r: &Resolver) -> Self {
|
||||||
|
let mut missing = Vec::new();
|
||||||
|
let mut s = |k: &str| {
|
||||||
|
let x = r.resolve(cfg.str(k).unwrap_or_default());
|
||||||
|
missing.extend(x.missing);
|
||||||
|
x.value.trim().to_string()
|
||||||
|
};
|
||||||
|
let grant = match cfg.str("grant").unwrap_or("authorization_code") {
|
||||||
|
"client_credentials" => Grant::ClientCredentials,
|
||||||
|
"device_code" => Grant::DeviceCode,
|
||||||
|
"password" => Grant::Password,
|
||||||
|
_ => Grant::AuthorizationCode,
|
||||||
|
};
|
||||||
|
let client_auth = match cfg.str("client_auth").unwrap_or("basic") {
|
||||||
|
"post" | "client_secret_post" => ClientAuth::Post,
|
||||||
|
"none" => ClientAuth::None,
|
||||||
|
_ => ClientAuth::Basic,
|
||||||
|
};
|
||||||
|
let redirect_mode = match cfg.str("redirect_mode").unwrap_or("loopback") {
|
||||||
|
"custom_scheme" => RedirectMode::CustomScheme,
|
||||||
|
"manual" => RedirectMode::Manual,
|
||||||
|
_ => RedirectMode::Loopback,
|
||||||
|
};
|
||||||
|
let map = |k: &str, missing: &mut Vec<String>| -> IndexMap<String, String> {
|
||||||
|
let mut out = IndexMap::new();
|
||||||
|
if let Some(serde_json::Value::Object(m)) = cfg.fields.get(k) {
|
||||||
|
for (key, v) in m {
|
||||||
|
let x = r.resolve(&crate::model::scalar_to_string(v));
|
||||||
|
missing.extend(x.missing);
|
||||||
|
out.insert(key.clone(), x.value);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
out
|
||||||
|
};
|
||||||
|
let scopes_raw = s("scopes");
|
||||||
|
let port = cfg
|
||||||
|
.fields
|
||||||
|
.get("redirect_port")
|
||||||
|
.and_then(|v| v.as_u64().or_else(|| v.as_str().and_then(|s| s.parse().ok())))
|
||||||
|
.unwrap_or(DEFAULT_PORT as u64) as u16;
|
||||||
|
let mut out = OauthConfig {
|
||||||
|
name: cfg.str("name").filter(|s| !s.is_empty()).unwrap_or("default").to_string(),
|
||||||
|
oidc: cfg.kind == "oidc",
|
||||||
|
grant,
|
||||||
|
issuer: s("issuer").trim_end_matches('/').to_string(),
|
||||||
|
authorize_url: s("authorize_url"),
|
||||||
|
token_url: s("token_url"),
|
||||||
|
userinfo_url: s("userinfo_url"),
|
||||||
|
jwks_url: s("jwks_url"),
|
||||||
|
revocation_url: s("revocation_url"),
|
||||||
|
introspection_url: s("introspection_url"),
|
||||||
|
end_session_url: s("end_session_url"),
|
||||||
|
device_url: s("device_url"),
|
||||||
|
client_id: s("client_id"),
|
||||||
|
client_secret: s("client_secret"),
|
||||||
|
client_auth,
|
||||||
|
scopes: scopes_raw.split([' ', ',']).filter(|x| !x.is_empty()).map(str::to_string).collect(),
|
||||||
|
audience: s("audience"),
|
||||||
|
resource: s("resource"),
|
||||||
|
redirect_mode,
|
||||||
|
redirect_host: cfg.str("redirect_host").unwrap_or("127.0.0.1").to_string(),
|
||||||
|
redirect_port: port,
|
||||||
|
redirect_path: cfg.str("redirect_path").unwrap_or("/callback").to_string(),
|
||||||
|
manual_redirect_uri: s("redirect_uri"),
|
||||||
|
pkce: cfg.bool("pkce", true),
|
||||||
|
username: s("username"),
|
||||||
|
password: s("password"),
|
||||||
|
authorize_params: IndexMap::new(),
|
||||||
|
token_params: IndexMap::new(),
|
||||||
|
use_id_token: cfg.str("token_use") == Some("id_token"),
|
||||||
|
auto_refresh: cfg.bool("auto_refresh", true),
|
||||||
|
verify_tls: cfg.bool("verify_tls", true),
|
||||||
|
missing: Vec::new(),
|
||||||
|
};
|
||||||
|
out.authorize_params = map("authorize_params", &mut missing);
|
||||||
|
out.token_params = map("token_params", &mut missing);
|
||||||
|
if out.oidc && !out.scopes.iter().any(|x| x == "openid") {
|
||||||
|
out.scopes.insert(0, "openid".into());
|
||||||
|
}
|
||||||
|
missing.sort();
|
||||||
|
missing.dedup();
|
||||||
|
out.missing = missing;
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn redirect_uri(&self) -> String {
|
||||||
|
match self.redirect_mode {
|
||||||
|
RedirectMode::Loopback => {
|
||||||
|
let path = if self.redirect_path.starts_with('/') {
|
||||||
|
self.redirect_path.clone()
|
||||||
|
} else {
|
||||||
|
format!("/{}", self.redirect_path)
|
||||||
|
};
|
||||||
|
format!("http://{}:{}{}", self.redirect_host, self.redirect_port, path)
|
||||||
|
}
|
||||||
|
RedirectMode::CustomScheme => "knock://callback".into(),
|
||||||
|
RedirectMode::Manual => self.manual_redirect_uri.clone(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn scope_string(&self) -> String {
|
||||||
|
self.scopes.join(" ")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Tokens are stored per issuer, client, scopes and environment, so two
|
||||||
|
/// environments can be logged in at the same time.
|
||||||
|
pub fn store_key(&self, collection: &str, env: Option<&str>) -> String {
|
||||||
|
use sha2::{Digest, Sha256};
|
||||||
|
let mut scopes = self.scopes.clone();
|
||||||
|
scopes.sort();
|
||||||
|
let who = if self.issuer.is_empty() { &self.token_url } else { &self.issuer };
|
||||||
|
let raw = format!("{who}|{}|{}|{}|{}", self.client_id, scopes.join(" "), collection, env.unwrap_or(""));
|
||||||
|
let h = Sha256::digest(raw.as_bytes());
|
||||||
|
format!("oauth:{}", h.iter().take(12).map(|b| format!("{b:02x}")).collect::<String>())
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,130 @@
|
|||||||
|
//! Plain-language explanations for OAuth errors: why it happened and what to do.
|
||||||
|
|
||||||
|
use super::config::{ClientAuth, OauthConfig};
|
||||||
|
use super::Metadata;
|
||||||
|
|
||||||
|
pub fn token_error(error: &str, description: &str, cfg: &OauthConfig, meta: Option<&Metadata>, grant: &str) -> String {
|
||||||
|
let d = description.to_lowercase();
|
||||||
|
match error {
|
||||||
|
"redirect_uri_mismatch" => redirect_mismatch(cfg),
|
||||||
|
"invalid_grant" => {
|
||||||
|
let mut h = String::from("The provider rejected the grant. Usual causes:\n");
|
||||||
|
match grant {
|
||||||
|
"refresh_token" => h.push_str(
|
||||||
|
"• The refresh token expired, was revoked, or was rotated by an earlier refresh (many providers allow each refresh token only once).\n• The user logged out or changed the password.\nLog in again; knock does that automatically on the next send.",
|
||||||
|
),
|
||||||
|
"authorization_code" => {
|
||||||
|
h.push_str("• The authorization code was already used or is older than its lifetime (often 30-60 s).\n");
|
||||||
|
if cfg.pkce {
|
||||||
|
h.push_str("• The PKCE code_verifier does not match the code_challenge from the login.\n");
|
||||||
|
}
|
||||||
|
h.push_str("• redirect_uri in the token request differs from the one in the login.\nRun the login again; codes cannot be reused.");
|
||||||
|
}
|
||||||
|
"password" => h.push_str("• Wrong username or password, or the account needs interaction (MFA, consent) that the password grant cannot do."),
|
||||||
|
_ => h.push_str("• Check the grant type and its parameters."),
|
||||||
|
}
|
||||||
|
if d.contains("pkce") || d.contains("code_verifier") {
|
||||||
|
h.push_str("\nThe description mentions PKCE: the verifier sent does not match the challenge.");
|
||||||
|
}
|
||||||
|
h
|
||||||
|
}
|
||||||
|
"invalid_client" | "unauthorized_client" => {
|
||||||
|
let mut h = String::new();
|
||||||
|
if cfg.client_secret.is_empty() && cfg.client_auth != ClientAuth::None {
|
||||||
|
h.push_str("The client secret is empty. Store it with {{secret.clientSecret}} or switch to a public client (client authentication: none).\n");
|
||||||
|
}
|
||||||
|
let other = match cfg.client_auth {
|
||||||
|
ClientAuth::Basic => "client_secret_post (secret in the form body)",
|
||||||
|
ClientAuth::Post => "client_secret_basic (Authorization header)",
|
||||||
|
ClientAuth::None => "client_secret_basic or client_secret_post",
|
||||||
|
};
|
||||||
|
h.push_str(&format!("The provider did not accept the client credentials. Try {other}"));
|
||||||
|
if let Some(m) = meta {
|
||||||
|
if !m.token_endpoint_auth_methods.is_empty() {
|
||||||
|
h.push_str(&format!("; it supports {}", m.token_endpoint_auth_methods.join(", ")));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
h.push_str(".\n");
|
||||||
|
if error == "unauthorized_client" {
|
||||||
|
h.push_str(&format!("The client may not be allowed to use the {grant} grant. Enable it for this client at the provider."));
|
||||||
|
} else {
|
||||||
|
h.push_str("Also check that client id and secret belong together and to this realm/tenant.");
|
||||||
|
}
|
||||||
|
h
|
||||||
|
}
|
||||||
|
"invalid_scope" => {
|
||||||
|
let mut h = format!("At least one requested scope is unknown or not allowed for this client. Requested: {}.", cfg.scope_string());
|
||||||
|
if let Some(m) = meta {
|
||||||
|
if !m.scopes_supported.is_empty() {
|
||||||
|
let unknown: Vec<&String> = cfg.scopes.iter().filter(|s| !m.scopes_supported.contains(s)).collect();
|
||||||
|
if !unknown.is_empty() {
|
||||||
|
h.push_str(&format!(
|
||||||
|
"\nNot listed in the provider's discovery document: {}.",
|
||||||
|
unknown.iter().map(|s| s.as_str()).collect::<Vec<_>>().join(", ")
|
||||||
|
));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
h
|
||||||
|
}
|
||||||
|
"invalid_request" if d.contains("code_challenge") || d.contains("pkce") => pkce(cfg, meta),
|
||||||
|
"invalid_request" if d.contains("redirect") => redirect_mismatch(cfg),
|
||||||
|
"unsupported_grant_type" => format!("The provider does not support the {grant} grant at this endpoint, or not for this client."),
|
||||||
|
"access_denied" => "The user (or a policy) denied the request on the consent screen.".into(),
|
||||||
|
"authorization_pending" | "slow_down" => "Waiting for the user to finish the device login.".into(),
|
||||||
|
"expired_token" => "The device code expired before the user finished. Start the login again.".into(),
|
||||||
|
"consent_required" | "interaction_required" | "login_required" => {
|
||||||
|
"The provider needs the user to interact. Remove prompt=none from the extra parameters, or log in again.".into()
|
||||||
|
}
|
||||||
|
_ => {
|
||||||
|
if d.contains("redirect") {
|
||||||
|
redirect_mismatch(cfg)
|
||||||
|
} else if d.contains("pkce") || d.contains("code_challenge") {
|
||||||
|
pkce(cfg, meta)
|
||||||
|
} else {
|
||||||
|
"See the provider's description above and the full response in this step.".into()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn redirect_mismatch(cfg: &OauthConfig) -> String {
|
||||||
|
let uri = cfg.redirect_uri();
|
||||||
|
let mut h = format!(
|
||||||
|
"The redirect URI must match the one registered at the provider exactly, character for character.\nknock sent: {uri}\n"
|
||||||
|
);
|
||||||
|
if uri.contains("127.0.0.1") {
|
||||||
|
h.push_str(&format!("Also common: {}\n", uri.replace("127.0.0.1", "localhost")));
|
||||||
|
} else if uri.contains("localhost") {
|
||||||
|
h.push_str(&format!("Also common: {}\n", uri.replace("localhost", "127.0.0.1")));
|
||||||
|
}
|
||||||
|
h.push_str("Check port, http vs https, localhost vs 127.0.0.1 and a trailing slash. Copy the URI from the top of the OAuth settings into the provider's allowed redirect URIs.");
|
||||||
|
h
|
||||||
|
}
|
||||||
|
|
||||||
|
fn pkce(cfg: &OauthConfig, meta: Option<&Metadata>) -> String {
|
||||||
|
let mut h = if cfg.pkce {
|
||||||
|
"PKCE was sent (S256). The provider may expect a different method.".to_string()
|
||||||
|
} else {
|
||||||
|
"The provider requires PKCE. Turn on PKCE in the OAuth settings.".to_string()
|
||||||
|
};
|
||||||
|
if let Some(m) = meta {
|
||||||
|
if !m.code_challenge_methods.is_empty() {
|
||||||
|
h.push_str(&format!(" Supported methods: {}.", m.code_challenge_methods.join(", ")));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
h
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn connect_error(what: &str, err: &str) -> String {
|
||||||
|
let e = err.to_lowercase();
|
||||||
|
if e.contains("certificate") || e.contains("tls") || e.contains("handshake") || e.contains("unknown issuer") {
|
||||||
|
format!("TLS failed while reaching the {what}: {err}\nIf the provider uses a private CA, add it under Collection settings → Extra CA certificates. For a quick local test you can turn off TLS verification in the OAuth settings.")
|
||||||
|
} else if e.contains("dns") || e.contains("resolve") || e.contains("lookup") {
|
||||||
|
format!("The host of the {what} could not be resolved. Check the URL and your network/VPN.")
|
||||||
|
} else if e.contains("refused") {
|
||||||
|
format!("Connection refused by the {what}. Is the server running and the port right?")
|
||||||
|
} else {
|
||||||
|
format!("Could not reach the {what}: {err}")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,160 @@
|
|||||||
|
//! Small HTTP helper for the OAuth endpoints. Every call returns the full
|
||||||
|
//! exchange so the flow log can show it and offer it as cURL.
|
||||||
|
|
||||||
|
use crate::auth::Exchange;
|
||||||
|
use base64::Engine;
|
||||||
|
use std::time::Duration;
|
||||||
|
|
||||||
|
pub struct Http {
|
||||||
|
client: reqwest::Client,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct Reply {
|
||||||
|
pub exchange: Exchange,
|
||||||
|
pub status: u16,
|
||||||
|
pub json: Option<serde_json::Value>,
|
||||||
|
/// Seconds the server clock is ahead of ours, from the Date header.
|
||||||
|
pub skew: Option<i64>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Http {
|
||||||
|
pub fn new(verify_tls: bool) -> Self {
|
||||||
|
let client = reqwest::Client::builder()
|
||||||
|
.user_agent(concat!("knock/", env!("CARGO_PKG_VERSION")))
|
||||||
|
.tls_danger_accept_invalid_certs(!verify_tls)
|
||||||
|
.timeout(Duration::from_secs(30))
|
||||||
|
.redirect(reqwest::redirect::Policy::limited(5))
|
||||||
|
.build()
|
||||||
|
.expect("http client");
|
||||||
|
Self { client }
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn get(&self, url: &str, bearer: Option<&str>) -> Result<Reply, (Exchange, String)> {
|
||||||
|
let mut headers = vec![("Accept".to_string(), "application/json".to_string())];
|
||||||
|
if let Some(t) = bearer {
|
||||||
|
headers.push(("Authorization".into(), format!("Bearer {t}")));
|
||||||
|
}
|
||||||
|
self.send("GET", url, headers, String::new()).await
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn post_form(
|
||||||
|
&self,
|
||||||
|
url: &str,
|
||||||
|
params: &[(String, String)],
|
||||||
|
basic: Option<(&str, &str)>,
|
||||||
|
) -> Result<Reply, (Exchange, String)> {
|
||||||
|
let mut headers = vec![
|
||||||
|
("Content-Type".to_string(), "application/x-www-form-urlencoded".to_string()),
|
||||||
|
("Accept".to_string(), "application/json".to_string()),
|
||||||
|
];
|
||||||
|
if let Some((id, secret)) = basic {
|
||||||
|
// RFC 6749 2.3.1: form-encode both parts before base64.
|
||||||
|
let enc = |s: &str| url::form_urlencoded::byte_serialize(s.as_bytes()).collect::<String>();
|
||||||
|
let raw = format!("{}:{}", enc(id), enc(secret));
|
||||||
|
headers.push((
|
||||||
|
"Authorization".into(),
|
||||||
|
format!("Basic {}", base64::engine::general_purpose::STANDARD.encode(raw)),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
// The serializer is not Send, so it must be gone before the await.
|
||||||
|
let body = {
|
||||||
|
let mut ser = url::form_urlencoded::Serializer::new(String::new());
|
||||||
|
for (k, v) in params {
|
||||||
|
ser.append_pair(k, v);
|
||||||
|
}
|
||||||
|
ser.finish()
|
||||||
|
};
|
||||||
|
self.send("POST", url, headers, body).await
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn send(
|
||||||
|
&self,
|
||||||
|
method: &str,
|
||||||
|
url: &str,
|
||||||
|
headers: Vec<(String, String)>,
|
||||||
|
body: String,
|
||||||
|
) -> Result<Reply, (Exchange, String)> {
|
||||||
|
let mut ex = Exchange {
|
||||||
|
method: method.into(),
|
||||||
|
url: url.into(),
|
||||||
|
request_headers: headers.clone(),
|
||||||
|
request_body: body.clone(),
|
||||||
|
curl: to_curl(method, url, &headers, &body),
|
||||||
|
..Default::default()
|
||||||
|
};
|
||||||
|
let m = reqwest::Method::from_bytes(method.as_bytes()).unwrap_or(reqwest::Method::GET);
|
||||||
|
let mut rb = self.client.request(m, url);
|
||||||
|
for (k, v) in &headers {
|
||||||
|
rb = rb.header(k, v);
|
||||||
|
}
|
||||||
|
if !body.is_empty() {
|
||||||
|
rb = rb.body(body);
|
||||||
|
}
|
||||||
|
let resp = match rb.send().await {
|
||||||
|
Ok(r) => r,
|
||||||
|
Err(e) => {
|
||||||
|
let msg = describe(&e);
|
||||||
|
return Err((ex, msg));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let status = resp.status().as_u16();
|
||||||
|
ex.status = Some(status);
|
||||||
|
ex.response_headers = resp
|
||||||
|
.headers()
|
||||||
|
.iter()
|
||||||
|
.map(|(k, v)| (k.to_string(), String::from_utf8_lossy(v.as_bytes()).into_owned()))
|
||||||
|
.collect();
|
||||||
|
let skew = resp
|
||||||
|
.headers()
|
||||||
|
.get("date")
|
||||||
|
.and_then(|d| d.to_str().ok())
|
||||||
|
.and_then(|d| chrono::DateTime::parse_from_rfc2822(d).ok())
|
||||||
|
.map(|d| d.timestamp() - chrono::Utc::now().timestamp());
|
||||||
|
let text = resp.text().await.unwrap_or_default();
|
||||||
|
let json = serde_json::from_str(&text).ok().or_else(|| {
|
||||||
|
// Some old providers answer the token endpoint with a form body.
|
||||||
|
if text.contains('=') && !text.trim_start().starts_with('<') {
|
||||||
|
let m: serde_json::Map<String, serde_json::Value> = url::form_urlencoded::parse(text.as_bytes())
|
||||||
|
.map(|(k, v)| (k.into_owned(), serde_json::Value::String(v.into_owned())))
|
||||||
|
.collect();
|
||||||
|
(!m.is_empty()).then_some(serde_json::Value::Object(m))
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
}
|
||||||
|
});
|
||||||
|
ex.response_body = text;
|
||||||
|
Ok(Reply { exchange: ex, status, json, skew })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn describe(e: &reqwest::Error) -> String {
|
||||||
|
let mut msg = if e.is_timeout() {
|
||||||
|
"timed out".to_string()
|
||||||
|
} else if e.is_connect() {
|
||||||
|
"could not connect".to_string()
|
||||||
|
} else {
|
||||||
|
"request failed".to_string()
|
||||||
|
};
|
||||||
|
let mut src = std::error::Error::source(e);
|
||||||
|
while let Some(s) = src {
|
||||||
|
msg.push_str(": ");
|
||||||
|
msg.push_str(&s.to_string());
|
||||||
|
src = s.source();
|
||||||
|
}
|
||||||
|
msg
|
||||||
|
}
|
||||||
|
|
||||||
|
fn shell_quote(s: &str) -> String {
|
||||||
|
format!("'{}'", s.replace('\'', r"'\''"))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn to_curl(method: &str, url: &str, headers: &[(String, String)], body: &str) -> String {
|
||||||
|
let mut out = format!("curl -X {method} {}", shell_quote(url));
|
||||||
|
for (k, v) in headers {
|
||||||
|
out.push_str(&format!(" \\\n -H {}", shell_quote(&format!("{k}: {v}"))));
|
||||||
|
}
|
||||||
|
if !body.is_empty() {
|
||||||
|
out.push_str(&format!(" \\\n --data-raw {}", shell_quote(body)));
|
||||||
|
}
|
||||||
|
out
|
||||||
|
}
|
||||||
@@ -0,0 +1,126 @@
|
|||||||
|
//! ID token checks (OIDC Core 3.1.3.7): iss, aud, azp, exp, iat, nonce,
|
||||||
|
//! at_hash, and the signature against the provider's JWKS.
|
||||||
|
|
||||||
|
use base64::Engine;
|
||||||
|
use serde_json::{Map, Value};
|
||||||
|
|
||||||
|
pub fn decode_part(part: &str) -> Option<Value> {
|
||||||
|
let bytes = base64::engine::general_purpose::URL_SAFE_NO_PAD
|
||||||
|
.decode(part.trim_end_matches('='))
|
||||||
|
.ok()?;
|
||||||
|
serde_json::from_slice(&bytes).ok()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn claims(jwt: &str) -> Option<Map<String, Value>> {
|
||||||
|
let mut parts = jwt.split('.');
|
||||||
|
let _header = parts.next()?;
|
||||||
|
match decode_part(parts.next()?)? {
|
||||||
|
Value::Object(m) => Some(m),
|
||||||
|
_ => None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn header(jwt: &str) -> Option<Map<String, Value>> {
|
||||||
|
match decode_part(jwt.split('.').next()?)? {
|
||||||
|
Value::Object(m) => Some(m),
|
||||||
|
_ => None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Default, serde::Serialize)]
|
||||||
|
pub struct Report {
|
||||||
|
pub checks: Vec<String>,
|
||||||
|
pub errors: Vec<String>,
|
||||||
|
/// "valid", "invalid", or why it was not checked.
|
||||||
|
pub signature: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn validate(
|
||||||
|
jwt: &str,
|
||||||
|
issuer: &str,
|
||||||
|
client_id: &str,
|
||||||
|
nonce: Option<&str>,
|
||||||
|
access_token: Option<&str>,
|
||||||
|
skew: i64,
|
||||||
|
jwks: Option<&Value>,
|
||||||
|
) -> Report {
|
||||||
|
let mut r = Report::default();
|
||||||
|
let (Some(h), Some(c)) = (header(jwt), claims(jwt)) else {
|
||||||
|
r.errors.push("not a readable JWT".into());
|
||||||
|
r.signature = "not checked".into();
|
||||||
|
return r;
|
||||||
|
};
|
||||||
|
let now = chrono::Utc::now().timestamp() + skew;
|
||||||
|
|
||||||
|
let iss = c.get("iss").and_then(|v| v.as_str()).unwrap_or("");
|
||||||
|
if issuer.is_empty() {
|
||||||
|
r.checks.push("iss not compared (no issuer configured)".into());
|
||||||
|
} else if iss.trim_end_matches('/') == issuer.trim_end_matches('/') {
|
||||||
|
r.checks.push("iss ok".into());
|
||||||
|
} else {
|
||||||
|
r.errors.push(format!("iss is \"{iss}\", expected \"{issuer}\""));
|
||||||
|
}
|
||||||
|
|
||||||
|
let aud: Vec<String> = match c.get("aud") {
|
||||||
|
Some(Value::String(s)) => vec![s.clone()],
|
||||||
|
Some(Value::Array(a)) => a.iter().filter_map(|x| x.as_str().map(str::to_string)).collect(),
|
||||||
|
_ => vec![],
|
||||||
|
};
|
||||||
|
if aud.iter().any(|a| a == client_id) {
|
||||||
|
r.checks.push("aud ok".into());
|
||||||
|
} else {
|
||||||
|
r.errors.push(format!("aud {:?} does not contain the client id \"{client_id}\"", aud));
|
||||||
|
}
|
||||||
|
if aud.len() > 1 {
|
||||||
|
match c.get("azp").and_then(|v| v.as_str()) {
|
||||||
|
Some(azp) if azp == client_id => r.checks.push("azp ok".into()),
|
||||||
|
Some(azp) => r.errors.push(format!("azp is \"{azp}\", expected \"{client_id}\"")),
|
||||||
|
None => r.checks.push("azp missing (allowed)".into()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
match c.get("exp").and_then(|v| v.as_i64()) {
|
||||||
|
Some(exp) if exp > now - 30 => r.checks.push("not expired".into()),
|
||||||
|
Some(exp) => r.errors.push(format!("expired {} s ago", now - exp)),
|
||||||
|
None => r.errors.push("exp is missing".into()),
|
||||||
|
}
|
||||||
|
if let Some(iat) = c.get("iat").and_then(|v| v.as_i64()) {
|
||||||
|
if iat > now + 60 {
|
||||||
|
r.errors.push(format!("iat is {} s in the future; check the clocks", iat - now));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
match (nonce, c.get("nonce").and_then(|v| v.as_str())) {
|
||||||
|
(Some(want), Some(got)) if want == got => r.checks.push("nonce ok".into()),
|
||||||
|
(Some(_), Some(_)) => r.errors.push("nonce does not match the login request".into()),
|
||||||
|
(Some(_), None) => r.errors.push("nonce missing".into()),
|
||||||
|
(None, _) => {}
|
||||||
|
}
|
||||||
|
|
||||||
|
let alg = h.get("alg").and_then(|v| v.as_str()).unwrap_or("");
|
||||||
|
if let (Some(at), Some(want)) = (access_token, c.get("at_hash").and_then(|v| v.as_str())) {
|
||||||
|
use sha2::Digest;
|
||||||
|
let digest: Vec<u8> = match &alg[alg.len().saturating_sub(3)..] {
|
||||||
|
"384" => sha2::Sha384::digest(at.as_bytes()).to_vec(),
|
||||||
|
"512" => sha2::Sha512::digest(at.as_bytes()).to_vec(),
|
||||||
|
_ => sha2::Sha256::digest(at.as_bytes()).to_vec(),
|
||||||
|
};
|
||||||
|
let got = base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(&digest[..digest.len() / 2]);
|
||||||
|
if got == want {
|
||||||
|
r.checks.push("at_hash ok".into());
|
||||||
|
} else {
|
||||||
|
r.errors.push("at_hash does not match the access token".into());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
r.signature = match jwks {
|
||||||
|
None => "not checked (no JWKS)".into(),
|
||||||
|
Some(set) => super::jwks::verify(jwt, alg, h.get("kid").and_then(|v| v.as_str()), set),
|
||||||
|
};
|
||||||
|
if r.signature.starts_with("invalid") {
|
||||||
|
r.errors.push("signature does not verify against the provider's JWKS".into());
|
||||||
|
} else if r.signature == "valid" {
|
||||||
|
r.checks.push("signature ok".into());
|
||||||
|
}
|
||||||
|
r
|
||||||
|
}
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
//! ID token signature check against the provider's JWKS.
|
||||||
|
|
||||||
|
use jsonwebtoken::jwk::JwkSet;
|
||||||
|
use jsonwebtoken::{decode, Algorithm, DecodingKey, Validation};
|
||||||
|
use std::str::FromStr;
|
||||||
|
|
||||||
|
/// "valid", "invalid", or why the signature could not be checked.
|
||||||
|
pub fn verify(jwt: &str, alg: &str, kid: Option<&str>, set: &serde_json::Value) -> String {
|
||||||
|
crate::auth::jwt::ensure_provider();
|
||||||
|
let Ok(set) = serde_json::from_value::<JwkSet>(set.clone()) else {
|
||||||
|
return "not checked (JWKS unreadable)".into();
|
||||||
|
};
|
||||||
|
let Ok(algorithm) = Algorithm::from_str(alg) else {
|
||||||
|
return format!("not checked (algorithm {alg})");
|
||||||
|
};
|
||||||
|
if matches!(algorithm, Algorithm::HS256 | Algorithm::HS384 | Algorithm::HS512) {
|
||||||
|
return "not checked (HMAC-signed, needs the client secret)".into();
|
||||||
|
}
|
||||||
|
let jwk = match kid {
|
||||||
|
Some(k) => set.find(k),
|
||||||
|
None => set.keys.first(),
|
||||||
|
};
|
||||||
|
let Some(jwk) = jwk else {
|
||||||
|
return format!("invalid (no key with kid {} in the JWKS)", kid.unwrap_or("?"));
|
||||||
|
};
|
||||||
|
let Ok(key) = DecodingKey::from_jwk(jwk) else {
|
||||||
|
return "not checked (unsupported key type)".into();
|
||||||
|
};
|
||||||
|
let mut v = Validation::new(algorithm);
|
||||||
|
v.validate_exp = false;
|
||||||
|
v.validate_aud = false;
|
||||||
|
v.validate_nbf = false;
|
||||||
|
v.required_spec_claims.clear();
|
||||||
|
match decode::<serde_json::Value>(jwt, &key, &v) {
|
||||||
|
Ok(_) => "valid".into(),
|
||||||
|
Err(e) if matches!(e.kind(), jsonwebtoken::errors::ErrorKind::InvalidSignature) => "invalid".into(),
|
||||||
|
Err(e) => format!("not checked ({e})"),
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,90 @@
|
|||||||
|
//! The loopback listener for the authorization code redirect. Binds to
|
||||||
|
//! loopback only, takes exactly one matching callback and shuts down.
|
||||||
|
|
||||||
|
use anyhow::{anyhow, Context, Result};
|
||||||
|
use std::time::Duration;
|
||||||
|
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||||
|
use tokio::net::TcpListener;
|
||||||
|
|
||||||
|
pub const TIMEOUT: Duration = Duration::from_secs(300);
|
||||||
|
|
||||||
|
pub struct Listener {
|
||||||
|
listeners: Vec<TcpListener>,
|
||||||
|
path: String,
|
||||||
|
pub port: u16,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Listener {
|
||||||
|
pub async fn bind(host: &str, port: u16, path: &str) -> Result<Self> {
|
||||||
|
let mut listeners = Vec::new();
|
||||||
|
let addrs: &[&str] = if host == "localhost" { &["127.0.0.1", "[::1]"] } else { &["127.0.0.1"] };
|
||||||
|
let mut last_err = None;
|
||||||
|
for a in addrs {
|
||||||
|
match TcpListener::bind(format!("{a}:{port}")).await {
|
||||||
|
Ok(l) => listeners.push(l),
|
||||||
|
Err(e) => last_err = Some(e),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if listeners.is_empty() {
|
||||||
|
let e = last_err.map(|e| e.to_string()).unwrap_or_default();
|
||||||
|
return Err(anyhow!("port {port} is not available ({e}). Another program (or another knock login) uses it; pick a different port and register that redirect URI too"));
|
||||||
|
}
|
||||||
|
let path = if path.starts_with('/') { path.to_string() } else { format!("/{path}") };
|
||||||
|
Ok(Self { listeners, path, port })
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Waits for the callback and returns the full URL the browser requested.
|
||||||
|
pub async fn wait(self) -> Result<String> {
|
||||||
|
let path = self.path.clone();
|
||||||
|
let port = self.port;
|
||||||
|
let accept = async move {
|
||||||
|
loop {
|
||||||
|
let (mut sock, _) = match self.listeners.len() {
|
||||||
|
1 => self.listeners[0].accept().await?,
|
||||||
|
_ => tokio::select! {
|
||||||
|
r = self.listeners[0].accept() => r?,
|
||||||
|
r = self.listeners[1].accept() => r?,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
let mut buf = vec![0u8; 16 * 1024];
|
||||||
|
let n = tokio::time::timeout(Duration::from_secs(10), sock.read(&mut buf)).await.unwrap_or(Ok(0))?;
|
||||||
|
let head = String::from_utf8_lossy(&buf[..n]).to_string();
|
||||||
|
let target = head.lines().next().and_then(|l| l.split_whitespace().nth(1)).unwrap_or("").to_string();
|
||||||
|
let req_path = target.split('?').next().unwrap_or("");
|
||||||
|
if req_path != path {
|
||||||
|
let _ = sock.write_all(b"HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\nConnection: close\r\n\r\n").await;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let failed = target.contains("error=");
|
||||||
|
let body = page(failed);
|
||||||
|
let resp = format!(
|
||||||
|
"HTTP/1.1 200 OK\r\nContent-Type: text/html; charset=utf-8\r\nContent-Length: {}\r\nConnection: close\r\nCache-Control: no-store\r\n\r\n{body}",
|
||||||
|
body.len()
|
||||||
|
);
|
||||||
|
let _ = sock.write_all(resp.as_bytes()).await;
|
||||||
|
let _ = sock.shutdown().await;
|
||||||
|
return Ok::<String, anyhow::Error>(format!("http://127.0.0.1:{port}{target}"));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
tokio::time::timeout(TIMEOUT, accept)
|
||||||
|
.await
|
||||||
|
.map_err(|_| anyhow!("no callback within 5 minutes"))?
|
||||||
|
.context("callback listener failed")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn page(failed: bool) -> String {
|
||||||
|
let (title, text) = if failed {
|
||||||
|
("Login failed", "The provider sent an error. knock shows the details; you can close this tab.")
|
||||||
|
} else {
|
||||||
|
("Logged in", "knock received the response. You can close this tab.")
|
||||||
|
};
|
||||||
|
format!(
|
||||||
|
r#"<!doctype html><html><head><meta charset="utf-8"><title>knock · {title}</title>
|
||||||
|
<style>body{{margin:0;height:100vh;display:grid;place-items:center;background:#101318;color:#E3E7EC;font:15px system-ui,sans-serif}}
|
||||||
|
main{{text-align:center}}h1{{font-size:20px;color:#F4F6F8;margin:18px 0 6px}}p{{color:#A9B0BC;margin:0}}</style></head>
|
||||||
|
<body><main><svg width="56" height="56" viewBox="0 0 100 100" fill="none" stroke="{color}" stroke-linecap="round" stroke-linejoin="round"><circle cx="50" cy="50" r="36" stroke-width="12"/><path d="M45 40 L55 50 L45 60" stroke-width="10"/></svg>
|
||||||
|
<h1>{title}</h1><p>{text}</p></main></body></html>"#,
|
||||||
|
color = if failed { "#FF5C5C" } else { "#2EC4F1" }
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1,951 @@
|
|||||||
|
//! OAuth 2.0 and OpenID Connect. Every step of a flow is recorded so the
|
||||||
|
//! auth debugger can show exactly where and why it failed.
|
||||||
|
|
||||||
|
pub mod config;
|
||||||
|
pub mod diagnose;
|
||||||
|
pub mod http;
|
||||||
|
pub mod idtoken;
|
||||||
|
mod jwks;
|
||||||
|
pub mod loopback;
|
||||||
|
|
||||||
|
use crate::auth::{Step, StepStatus};
|
||||||
|
use base64::Engine;
|
||||||
|
use config::{ClientAuth, Grant, OauthConfig, RedirectMode};
|
||||||
|
use futures_util::future::BoxFuture;
|
||||||
|
use http::{Http, Reply};
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
use serde_json::{json, Value};
|
||||||
|
use std::collections::HashMap;
|
||||||
|
use std::sync::Mutex;
|
||||||
|
use std::time::Instant;
|
||||||
|
|
||||||
|
/// Refresh when the token has less than this many seconds left.
|
||||||
|
pub const REFRESH_SKEW: i64 = 30;
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
|
||||||
|
pub struct Metadata {
|
||||||
|
pub issuer: String,
|
||||||
|
pub authorization_endpoint: String,
|
||||||
|
pub token_endpoint: String,
|
||||||
|
pub userinfo_endpoint: String,
|
||||||
|
pub jwks_uri: String,
|
||||||
|
pub revocation_endpoint: String,
|
||||||
|
pub introspection_endpoint: String,
|
||||||
|
pub end_session_endpoint: String,
|
||||||
|
pub device_authorization_endpoint: String,
|
||||||
|
pub scopes_supported: Vec<String>,
|
||||||
|
pub grant_types_supported: Vec<String>,
|
||||||
|
pub code_challenge_methods: Vec<String>,
|
||||||
|
pub token_endpoint_auth_methods: Vec<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Metadata {
|
||||||
|
fn from_json(v: &Value) -> Self {
|
||||||
|
let s = |k: &str| v.get(k).and_then(|x| x.as_str()).unwrap_or_default().to_string();
|
||||||
|
let l = |k: &str| -> Vec<String> {
|
||||||
|
v.get(k)
|
||||||
|
.and_then(|x| x.as_array())
|
||||||
|
.map(|a| a.iter().filter_map(|x| x.as_str().map(str::to_string)).collect())
|
||||||
|
.unwrap_or_default()
|
||||||
|
};
|
||||||
|
Self {
|
||||||
|
issuer: s("issuer"),
|
||||||
|
authorization_endpoint: s("authorization_endpoint"),
|
||||||
|
token_endpoint: s("token_endpoint"),
|
||||||
|
userinfo_endpoint: s("userinfo_endpoint"),
|
||||||
|
jwks_uri: s("jwks_uri"),
|
||||||
|
revocation_endpoint: s("revocation_endpoint"),
|
||||||
|
introspection_endpoint: s("introspection_endpoint"),
|
||||||
|
end_session_endpoint: s("end_session_endpoint"),
|
||||||
|
device_authorization_endpoint: s("device_authorization_endpoint"),
|
||||||
|
scopes_supported: l("scopes_supported"),
|
||||||
|
grant_types_supported: l("grant_types_supported"),
|
||||||
|
code_challenge_methods: l("code_challenge_methods_supported"),
|
||||||
|
token_endpoint_auth_methods: l("token_endpoint_auth_methods_supported"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
|
||||||
|
pub struct TokenSet {
|
||||||
|
pub access_token: String,
|
||||||
|
#[serde(default)]
|
||||||
|
pub refresh_token: Option<String>,
|
||||||
|
#[serde(default)]
|
||||||
|
pub id_token: Option<String>,
|
||||||
|
#[serde(default)]
|
||||||
|
pub token_type: Option<String>,
|
||||||
|
#[serde(default)]
|
||||||
|
pub scope: Option<String>,
|
||||||
|
/// Unix seconds.
|
||||||
|
#[serde(default)]
|
||||||
|
pub expires_at: Option<i64>,
|
||||||
|
pub obtained_at: i64,
|
||||||
|
#[serde(default)]
|
||||||
|
pub skew: Option<i64>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl TokenSet {
|
||||||
|
pub fn seconds_left(&self) -> Option<i64> {
|
||||||
|
self.expires_at.map(|e| e - chrono::Utc::now().timestamp())
|
||||||
|
}
|
||||||
|
pub fn fresh(&self) -> bool {
|
||||||
|
self.seconds_left().is_none_or(|s| s > REFRESH_SKEW)
|
||||||
|
}
|
||||||
|
fn tokens_map(&self) -> Value {
|
||||||
|
let mut m = serde_json::Map::new();
|
||||||
|
m.insert("access_token".into(), Value::String(self.access_token.clone()));
|
||||||
|
if let Some(t) = &self.id_token {
|
||||||
|
m.insert("id_token".into(), Value::String(t.clone()));
|
||||||
|
}
|
||||||
|
if let Some(t) = &self.refresh_token {
|
||||||
|
m.insert("refresh_token".into(), Value::String(t.clone()));
|
||||||
|
}
|
||||||
|
json!({ "tokens": m })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What the app or CLI provides to a flow.
|
||||||
|
pub trait FlowHooks: Send + Sync {
|
||||||
|
fn interactive(&self) -> bool;
|
||||||
|
fn open_browser(&self, url: &str) -> Result<(), String>;
|
||||||
|
/// Custom scheme and manual mode: resolves with the callback URL (or a pasted code).
|
||||||
|
fn wait_external(&self) -> BoxFuture<'static, Option<String>>;
|
||||||
|
/// Live progress while a step is still running (listener up, waiting for user).
|
||||||
|
fn progress(&self, step: &Step);
|
||||||
|
fn device_prompt(&self, verification_uri: &str, user_code: &str, complete_uri: Option<&str>);
|
||||||
|
fn load_token(&self, key: &str) -> Option<TokenSet>;
|
||||||
|
fn save_token(&self, key: &str, t: &TokenSet);
|
||||||
|
fn delete_token(&self, key: &str);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Default, Serialize)]
|
||||||
|
pub struct FlowResult {
|
||||||
|
pub token: Option<String>,
|
||||||
|
pub tokens: Option<TokenSet>,
|
||||||
|
pub steps: Vec<Step>,
|
||||||
|
pub warnings: Vec<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
static DISCOVERY: Mutex<Option<HashMap<String, (Instant, Metadata)>>> = Mutex::new(None);
|
||||||
|
|
||||||
|
struct Flow<'a> {
|
||||||
|
cfg: &'a OauthConfig,
|
||||||
|
hooks: &'a dyn FlowHooks,
|
||||||
|
http: Http,
|
||||||
|
steps: Vec<Step>,
|
||||||
|
warnings: Vec<String>,
|
||||||
|
meta: Option<Metadata>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'a> Flow<'a> {
|
||||||
|
fn push(&mut self, s: Step) -> bool {
|
||||||
|
let ok = s.status != StepStatus::Error;
|
||||||
|
self.hooks.progress(&s);
|
||||||
|
self.steps.push(s);
|
||||||
|
ok
|
||||||
|
}
|
||||||
|
|
||||||
|
fn fail(mut self, s: Step) -> FlowResult {
|
||||||
|
self.push(s);
|
||||||
|
FlowResult { steps: self.steps, warnings: self.warnings, ..Default::default() }
|
||||||
|
}
|
||||||
|
|
||||||
|
fn done(self, t: TokenSet) -> FlowResult {
|
||||||
|
let token = if self.cfg.use_id_token { t.id_token.clone() } else { Some(t.access_token.clone()) };
|
||||||
|
FlowResult { token, tokens: Some(t), steps: self.steps, warnings: self.warnings }
|
||||||
|
}
|
||||||
|
|
||||||
|
fn check_config(&mut self) -> bool {
|
||||||
|
let c = self.cfg;
|
||||||
|
let t = Instant::now();
|
||||||
|
let mut problems = Vec::new();
|
||||||
|
if c.client_id.is_empty() {
|
||||||
|
problems.push("client id is empty".to_string());
|
||||||
|
}
|
||||||
|
if c.issuer.is_empty() && c.token_url.is_empty() {
|
||||||
|
problems.push("neither an issuer (for discovery) nor a token URL is set".to_string());
|
||||||
|
}
|
||||||
|
if c.grant == Grant::AuthorizationCode && c.issuer.is_empty() && c.authorize_url.is_empty() {
|
||||||
|
problems.push("the authorization code flow needs an authorize URL or an issuer".to_string());
|
||||||
|
}
|
||||||
|
if c.grant == Grant::Password && c.username.is_empty() {
|
||||||
|
problems.push("username is empty".to_string());
|
||||||
|
}
|
||||||
|
if c.redirect_mode == RedirectMode::Manual && c.grant == Grant::AuthorizationCode && c.manual_redirect_uri.is_empty() {
|
||||||
|
problems.push("manual redirect mode needs the redirect URI you registered".to_string());
|
||||||
|
}
|
||||||
|
if !c.missing.is_empty() {
|
||||||
|
self.warnings.push(format!(
|
||||||
|
"undefined variables in the OAuth settings: {}",
|
||||||
|
c.missing.iter().map(|m| format!("{{{{{m}}}}}")).collect::<Vec<_>>().join(", ")
|
||||||
|
));
|
||||||
|
}
|
||||||
|
if c.redirect_mode == RedirectMode::Loopback && c.redirect_host == "localhost" {
|
||||||
|
self.warnings.push("The redirect URI uses localhost. Many providers compare exactly; 127.0.0.1 is the safer choice (RFC 8252).".into());
|
||||||
|
}
|
||||||
|
let data = json!({
|
||||||
|
"grant": c.grant,
|
||||||
|
"client_id": c.client_id,
|
||||||
|
"client_auth": c.client_auth,
|
||||||
|
"scopes": c.scopes,
|
||||||
|
"redirect_uri": c.redirect_uri(),
|
||||||
|
"pkce": c.pkce,
|
||||||
|
});
|
||||||
|
if problems.is_empty() {
|
||||||
|
self.push(Step::new("config", "Check config", StepStatus::Ok, format!("{:?} grant, client {}", c.grant, c.client_id)).data(data).took(t))
|
||||||
|
} else {
|
||||||
|
self.push(
|
||||||
|
Step::new("config", "Check config", StepStatus::Error, problems.join("; "))
|
||||||
|
.hint("Fill in the missing fields in the OAuth settings of this request, folder or collection.")
|
||||||
|
.data(data),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn discover(&mut self) -> bool {
|
||||||
|
let c = self.cfg;
|
||||||
|
if c.issuer.is_empty() {
|
||||||
|
self.push(Step::new("discovery", "Discovery", StepStatus::Skipped, "no issuer set, using the endpoints entered by hand"));
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
if let Some((at, m)) = DISCOVERY.lock().unwrap().get_or_insert_with(HashMap::new).get(&c.issuer) {
|
||||||
|
if at.elapsed().as_secs() < 3600 {
|
||||||
|
self.meta = Some(m.clone());
|
||||||
|
self.push(Step::new("discovery", "Discovery", StepStatus::Skipped, "using the discovery document fetched earlier (cached for an hour)").data(serde_json::to_value(m).unwrap_or_default()));
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let t = Instant::now();
|
||||||
|
let mut tried = Vec::new();
|
||||||
|
for suffix in ["/.well-known/openid-configuration", "/.well-known/oauth-authorization-server"] {
|
||||||
|
let url = format!("{}{suffix}", c.issuer);
|
||||||
|
match self.http.get(&url, None).await {
|
||||||
|
Ok(Reply { status: 200, json: Some(v), exchange, .. }) => {
|
||||||
|
let m = Metadata::from_json(&v);
|
||||||
|
let mut st = Step::new("discovery", "Discovery", StepStatus::Ok, format!("found {}", url)).took(t);
|
||||||
|
st.exchange = Some(exchange);
|
||||||
|
st.data = serde_json::to_value(&m).unwrap_or_default();
|
||||||
|
if !m.issuer.is_empty() && m.issuer.trim_end_matches('/') != c.issuer {
|
||||||
|
self.warnings.push(format!(
|
||||||
|
"The discovery document says issuer \"{}\", the config says \"{}\". ID token validation will fail on iss.",
|
||||||
|
m.issuer, c.issuer
|
||||||
|
));
|
||||||
|
}
|
||||||
|
DISCOVERY.lock().unwrap().get_or_insert_with(HashMap::new).insert(c.issuer.clone(), (Instant::now(), m.clone()));
|
||||||
|
self.meta = Some(m);
|
||||||
|
return self.push(st);
|
||||||
|
}
|
||||||
|
Ok(r) => tried.push((url, format!("HTTP {}", r.status), Some(r.exchange))),
|
||||||
|
Err((ex, e)) => {
|
||||||
|
let mut st = Step::new("discovery", "Discovery", StepStatus::Error, format!("{url}: {e}"))
|
||||||
|
.hint(diagnose::connect_error("discovery endpoint", &e))
|
||||||
|
.took(t);
|
||||||
|
st.exchange = Some(ex);
|
||||||
|
return self.push(st);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let summary = tried.iter().map(|(u, s, _)| format!("{u} → {s}")).collect::<Vec<_>>().join("; ");
|
||||||
|
let mut st = Step::new("discovery", "Discovery", StepStatus::Error, "no discovery document found")
|
||||||
|
.hint(format!(
|
||||||
|
"Tried {summary}.\nCheck the issuer URL (for Keycloak: https://host/realms/<realm>, no trailing slash). Or clear the issuer and enter the endpoints by hand."
|
||||||
|
))
|
||||||
|
.took(t);
|
||||||
|
st.exchange = tried.into_iter().last().and_then(|x| x.2);
|
||||||
|
self.push(st)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn endpoint(&self, own: &str, from_meta: impl Fn(&Metadata) -> &String) -> String {
|
||||||
|
if !own.is_empty() {
|
||||||
|
return own.to_string();
|
||||||
|
}
|
||||||
|
self.meta.as_ref().map(|m| from_meta(m).clone()).unwrap_or_default()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn client_params(&self, params: &mut Vec<(String, String)>) -> Option<(String, String)> {
|
||||||
|
let c = self.cfg;
|
||||||
|
match c.client_auth {
|
||||||
|
ClientAuth::Basic if !c.client_secret.is_empty() => Some((c.client_id.clone(), c.client_secret.clone())),
|
||||||
|
ClientAuth::Post => {
|
||||||
|
params.push(("client_id".into(), c.client_id.clone()));
|
||||||
|
params.push(("client_secret".into(), c.client_secret.clone()));
|
||||||
|
None
|
||||||
|
}
|
||||||
|
_ => {
|
||||||
|
params.push(("client_id".into(), c.client_id.clone()));
|
||||||
|
None
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Token endpoint call shared by every grant.
|
||||||
|
async fn token_request(&mut self, grant: &str, mut params: Vec<(String, String)>, title: &str) -> Option<TokenSet> {
|
||||||
|
let c = self.cfg;
|
||||||
|
let url = self.endpoint(&c.token_url, |m| &m.token_endpoint);
|
||||||
|
if url.is_empty() {
|
||||||
|
self.push(Step::new("token", title, StepStatus::Error, "no token endpoint").hint("Set the token URL, or an issuer whose discovery document lists one."));
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
params.insert(0, ("grant_type".into(), grant.into()));
|
||||||
|
if !c.audience.is_empty() {
|
||||||
|
params.push(("audience".into(), c.audience.clone()));
|
||||||
|
}
|
||||||
|
if !c.resource.is_empty() {
|
||||||
|
params.push(("resource".into(), c.resource.clone()));
|
||||||
|
}
|
||||||
|
for (k, v) in &c.token_params {
|
||||||
|
params.push((k.clone(), v.clone()));
|
||||||
|
}
|
||||||
|
let basic = self.client_params(&mut params);
|
||||||
|
let t = Instant::now();
|
||||||
|
let reply = self.http.post_form(&url, ¶ms, basic.as_ref().map(|(a, b)| (a.as_str(), b.as_str()))).await;
|
||||||
|
let reply = match reply {
|
||||||
|
Ok(r) => r,
|
||||||
|
Err((ex, e)) => {
|
||||||
|
let mut st = Step::new("token", title, StepStatus::Error, e.clone()).hint(diagnose::connect_error("token endpoint", &e)).took(t);
|
||||||
|
st.exchange = Some(ex);
|
||||||
|
self.push(st);
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
self.handle_token_reply(reply, grant, title, t)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn handle_token_reply(&mut self, reply: Reply, grant: &str, title: &str, t: Instant) -> Option<TokenSet> {
|
||||||
|
let c = self.cfg;
|
||||||
|
let ok = (200..300).contains(&reply.status);
|
||||||
|
let body = reply.json.clone().unwrap_or(Value::Null);
|
||||||
|
if !ok || body.get("error").is_some() || body.get("access_token").is_none() {
|
||||||
|
let error = body.get("error").and_then(|v| v.as_str()).unwrap_or("");
|
||||||
|
let desc = body.get("error_description").and_then(|v| v.as_str()).unwrap_or("");
|
||||||
|
let summary = if error.is_empty() {
|
||||||
|
format!("HTTP {} without an access_token", reply.status)
|
||||||
|
} else if desc.is_empty() {
|
||||||
|
error.to_string()
|
||||||
|
} else {
|
||||||
|
format!("{error}: {desc}")
|
||||||
|
};
|
||||||
|
let hint = if error.is_empty() {
|
||||||
|
if reply.json.is_none() {
|
||||||
|
"The token endpoint did not answer with JSON. Is the URL right? The response body is shown below.".to_string()
|
||||||
|
} else {
|
||||||
|
"The response has no access_token. See the body below.".to_string()
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
diagnose::token_error(error, desc, c, self.meta.as_ref(), grant)
|
||||||
|
};
|
||||||
|
let mut st = Step::new("token", title, StepStatus::Error, summary).hint(hint).took(t);
|
||||||
|
st.data = json!({ "error": error, "error_description": desc, "status": reply.status });
|
||||||
|
st.exchange = Some(reply.exchange);
|
||||||
|
self.push(st);
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let mut st = Step::new("token", title, StepStatus::Ok, format!("HTTP {}", reply.status)).took(t);
|
||||||
|
st.exchange = Some(reply.exchange);
|
||||||
|
self.push(st);
|
||||||
|
|
||||||
|
let t = Instant::now();
|
||||||
|
let now = chrono::Utc::now().timestamp();
|
||||||
|
let get = |k: &str| body.get(k).and_then(|v| v.as_str()).map(str::to_string);
|
||||||
|
let expires_in = body.get("expires_in").and_then(|v| v.as_i64().or_else(|| v.as_str().and_then(|s| s.parse().ok())));
|
||||||
|
let mut ts = TokenSet {
|
||||||
|
access_token: get("access_token").unwrap_or_default(),
|
||||||
|
refresh_token: get("refresh_token"),
|
||||||
|
id_token: get("id_token"),
|
||||||
|
token_type: get("token_type"),
|
||||||
|
scope: get("scope"),
|
||||||
|
expires_at: expires_in.map(|e| now + e),
|
||||||
|
obtained_at: now,
|
||||||
|
skew: reply.skew,
|
||||||
|
};
|
||||||
|
if ts.expires_at.is_none() {
|
||||||
|
// Fall back to the JWT's own exp.
|
||||||
|
ts.expires_at = idtoken::claims(&ts.access_token).and_then(|c| c.get("exp").and_then(|v| v.as_i64()));
|
||||||
|
}
|
||||||
|
let mut notes = Vec::new();
|
||||||
|
if let Some(l) = ts.seconds_left() {
|
||||||
|
notes.push(format!("expires in {}", human(l)));
|
||||||
|
}
|
||||||
|
if ts.refresh_token.is_some() {
|
||||||
|
notes.push("refresh token received".into());
|
||||||
|
} else if grant != "client_credentials" {
|
||||||
|
notes.push("no refresh token (ask for offline_access if you need one)".into());
|
||||||
|
}
|
||||||
|
if let Some(granted) = &ts.scope {
|
||||||
|
let granted: Vec<&str> = granted.split(' ').collect();
|
||||||
|
let missing: Vec<&String> = c.scopes.iter().filter(|s| !granted.contains(&s.as_str())).collect();
|
||||||
|
if !missing.is_empty() {
|
||||||
|
self.warnings.push(format!(
|
||||||
|
"The provider granted fewer scopes than requested; missing: {}",
|
||||||
|
missing.iter().map(|s| s.as_str()).collect::<Vec<_>>().join(", ")
|
||||||
|
));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if let Some(s) = ts.skew {
|
||||||
|
if s.abs() > 30 {
|
||||||
|
self.warnings.push(format!("Your clock differs from the server by {} s. Token expiry checks may be off.", s));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
self.push(Step::new("parse", "Parse token response", StepStatus::Ok, notes.join(", ")).data(ts.tokens_map()).took(t));
|
||||||
|
Some(ts)
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn validate_id_token(&mut self, ts: &TokenSet, nonce: Option<&str>) -> bool {
|
||||||
|
let Some(id) = &ts.id_token else {
|
||||||
|
if self.cfg.oidc {
|
||||||
|
self.push(Step::new("idtoken", "Validate ID token", StepStatus::Warning, "no id_token in the response")
|
||||||
|
.hint("OpenID Connect needs the openid scope. The provider returned only OAuth tokens."));
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
};
|
||||||
|
let t = Instant::now();
|
||||||
|
let issuer = self.meta.as_ref().map(|m| m.issuer.clone()).filter(|s| !s.is_empty()).unwrap_or_else(|| self.cfg.issuer.clone());
|
||||||
|
let jwks = self.endpoint(&self.cfg.jwks_url, |m| &m.jwks_uri);
|
||||||
|
let jwks_doc = if jwks.is_empty() {
|
||||||
|
None
|
||||||
|
} else {
|
||||||
|
match self.http.get(&jwks, None).await {
|
||||||
|
Ok(r) if r.status == 200 => r.json,
|
||||||
|
_ => None,
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let report = idtoken::validate(id, &issuer, &self.cfg.client_id, nonce, Some(&ts.access_token), ts.skew.unwrap_or(0), jwks_doc.as_ref());
|
||||||
|
let status = if report.errors.is_empty() { StepStatus::Ok } else { StepStatus::Error };
|
||||||
|
let summary = if report.errors.is_empty() {
|
||||||
|
report.checks.join(", ")
|
||||||
|
} else {
|
||||||
|
report.errors.join("; ")
|
||||||
|
};
|
||||||
|
let mut st = Step::new("idtoken", "Validate ID token", status, summary).data(json!({ "checks": report.checks, "errors": report.errors, "signature": report.signature })).took(t);
|
||||||
|
if !report.errors.is_empty() {
|
||||||
|
st = st.hint("The token itself was issued, but it does not match what knock expected. A nonce mismatch means the callback belongs to another login; iss and aud mismatches point at a wrong issuer URL or client id.");
|
||||||
|
}
|
||||||
|
self.push(st)
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn refresh(&mut self, key: &str, rt: &str) -> Option<TokenSet> {
|
||||||
|
let params = vec![("refresh_token".to_string(), rt.to_string()), ("scope".into(), self.cfg.scope_string())];
|
||||||
|
let mut params = params;
|
||||||
|
if self.cfg.scopes.is_empty() {
|
||||||
|
params.pop();
|
||||||
|
}
|
||||||
|
let mut ts = self.token_request("refresh_token", params, "Refresh token").await?;
|
||||||
|
if ts.refresh_token.is_none() {
|
||||||
|
// Providers that do not rotate keep the old refresh token valid.
|
||||||
|
ts.refresh_token = Some(rt.to_string());
|
||||||
|
}
|
||||||
|
if ts.id_token.is_none() {
|
||||||
|
ts.id_token = self.hooks.load_token(key).and_then(|o| o.id_token);
|
||||||
|
}
|
||||||
|
Some(ts)
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn authorization_code(&mut self) -> Option<TokenSet> {
|
||||||
|
let c = self.cfg;
|
||||||
|
let auth_url = self.endpoint(&c.authorize_url, |m| &m.authorization_endpoint);
|
||||||
|
if auth_url.is_empty() {
|
||||||
|
self.push(Step::new("authorize", "Build authorize URL", StepStatus::Error, "no authorize endpoint"));
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let t = Instant::now();
|
||||||
|
let state = random_token(24);
|
||||||
|
let nonce = c.oidc.then(|| random_token(24));
|
||||||
|
let verifier = c.pkce.then(|| random_token(48));
|
||||||
|
let redirect = c.redirect_uri();
|
||||||
|
let mut params: Vec<(String, String)> = vec![
|
||||||
|
("response_type".into(), "code".into()),
|
||||||
|
("client_id".into(), c.client_id.clone()),
|
||||||
|
("redirect_uri".into(), redirect.clone()),
|
||||||
|
];
|
||||||
|
if !c.scopes.is_empty() {
|
||||||
|
params.push(("scope".into(), c.scope_string()));
|
||||||
|
}
|
||||||
|
params.push(("state".into(), state.clone()));
|
||||||
|
if let Some(n) = &nonce {
|
||||||
|
params.push(("nonce".into(), n.clone()));
|
||||||
|
}
|
||||||
|
if let Some(v) = &verifier {
|
||||||
|
use sha2::{Digest, Sha256};
|
||||||
|
let challenge = base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(Sha256::digest(v.as_bytes()));
|
||||||
|
params.push(("code_challenge".into(), challenge));
|
||||||
|
params.push(("code_challenge_method".into(), "S256".into()));
|
||||||
|
} else if let Some(m) = &self.meta {
|
||||||
|
if !m.code_challenge_methods.is_empty() {
|
||||||
|
self.warnings.push(format!(
|
||||||
|
"PKCE is off, but the provider supports it ({}). Many providers require it for public clients.",
|
||||||
|
m.code_challenge_methods.join(", ")
|
||||||
|
));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !c.audience.is_empty() {
|
||||||
|
params.push(("audience".into(), c.audience.clone()));
|
||||||
|
}
|
||||||
|
if !c.resource.is_empty() {
|
||||||
|
params.push(("resource".into(), c.resource.clone()));
|
||||||
|
}
|
||||||
|
for (k, v) in &c.authorize_params {
|
||||||
|
params.push((k.clone(), v.clone()));
|
||||||
|
}
|
||||||
|
let mut u = match url::Url::parse(&auth_url) {
|
||||||
|
Ok(u) => u,
|
||||||
|
Err(e) => {
|
||||||
|
self.push(Step::new("authorize", "Build authorize URL", StepStatus::Error, format!("invalid authorize URL: {e}")));
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
u.query_pairs_mut().extend_pairs(params.iter().map(|(a, b)| (a.as_str(), b.as_str())));
|
||||||
|
let full = u.to_string();
|
||||||
|
self.push(Step::new("authorize", "Build authorize URL", StepStatus::Ok, format!("redirect_uri {redirect}")).data(json!({ "url": full, "params": params })).took(t));
|
||||||
|
|
||||||
|
// Start listening before the browser opens, so a fast provider cannot race us.
|
||||||
|
let listener = if c.redirect_mode == RedirectMode::Loopback {
|
||||||
|
match loopback::Listener::bind(&c.redirect_host, c.redirect_port, &c.redirect_path).await {
|
||||||
|
Ok(l) => Some(l),
|
||||||
|
Err(e) => {
|
||||||
|
self.push(Step::new("listen", "Start callback listener", StepStatus::Error, e.to_string())
|
||||||
|
.hint(format!("Free port {} or change the redirect port (and register the new redirect URI at the provider).", c.redirect_port)));
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
};
|
||||||
|
|
||||||
|
let t = Instant::now();
|
||||||
|
if let Err(e) = self.hooks.open_browser(&full) {
|
||||||
|
self.push(Step::new("browser", "Open browser", StepStatus::Error, e).hint("Copy the authorize URL from the step above and open it yourself; knock keeps listening."));
|
||||||
|
} else {
|
||||||
|
self.push(Step::new("browser", "Open browser", StepStatus::Ok, "system browser opened").took(t));
|
||||||
|
}
|
||||||
|
|
||||||
|
let t = Instant::now();
|
||||||
|
let waiting = match c.redirect_mode {
|
||||||
|
RedirectMode::Loopback => format!("listening on 127.0.0.1:{} {} (5 min)", c.redirect_port, c.redirect_path),
|
||||||
|
RedirectMode::CustomScheme => "waiting for knock://callback (5 min)".into(),
|
||||||
|
RedirectMode::Manual => "paste the URL or code from the provider's page into knock".into(),
|
||||||
|
};
|
||||||
|
self.hooks.progress(&Step::new("callback", "Wait for callback", StepStatus::Pending, waiting.clone()));
|
||||||
|
let received = match listener {
|
||||||
|
Some(l) => l.wait().await.map_err(|e| e.to_string()),
|
||||||
|
None => match tokio::time::timeout(loopback::TIMEOUT, self.hooks.wait_external()).await {
|
||||||
|
Ok(Some(v)) => Ok(v),
|
||||||
|
Ok(None) => Err("cancelled".to_string()),
|
||||||
|
Err(_) => Err("no callback within 5 minutes".to_string()),
|
||||||
|
},
|
||||||
|
};
|
||||||
|
let callback = match received {
|
||||||
|
Ok(v) => v,
|
||||||
|
Err(e) => {
|
||||||
|
self.push(Step::new("callback", "Wait for callback", StepStatus::Error, e).hint(
|
||||||
|
"Common causes: the browser did not open (open the authorize URL by hand), the login is still open in a tab, a firewall blocks the port, or the provider redirects somewhere else (redirect URI or redirect mode mismatch).",
|
||||||
|
).took(t));
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
self.push(Step::new("callback", "Wait for callback", StepStatus::Ok, waiting).took(t));
|
||||||
|
|
||||||
|
// Manual mode accepts either the whole URL or only the code.
|
||||||
|
let pairs: Vec<(String, String)> = match url::Url::parse(&callback) {
|
||||||
|
Ok(u) => {
|
||||||
|
let mut p: Vec<(String, String)> = u.query_pairs().map(|(a, b)| (a.into_owned(), b.into_owned())).collect();
|
||||||
|
if let Some(f) = u.fragment() {
|
||||||
|
p.extend(url::form_urlencoded::parse(f.as_bytes()).map(|(a, b)| (a.into_owned(), b.into_owned())));
|
||||||
|
}
|
||||||
|
p
|
||||||
|
}
|
||||||
|
Err(_) => vec![("code".into(), callback.trim().to_string()), ("state".into(), state.clone())],
|
||||||
|
};
|
||||||
|
let get = |k: &str| pairs.iter().find(|(a, _)| a == k).map(|(_, b)| b.clone());
|
||||||
|
let rec = Step::new("received", "Callback received", StepStatus::Ok, "").data(json!({ "url": callback, "params": pairs }));
|
||||||
|
if let Some(err) = get("error") {
|
||||||
|
let desc = get("error_description").unwrap_or_default();
|
||||||
|
let hint = diagnose::token_error(&err, &desc, c, self.meta.as_ref(), "authorization_code");
|
||||||
|
let mut s = rec;
|
||||||
|
s.status = StepStatus::Error;
|
||||||
|
s.summary = if desc.is_empty() { err } else { format!("{err}: {desc}") };
|
||||||
|
s.hint = Some(hint);
|
||||||
|
self.push(s);
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let Some(code) = get("code") else {
|
||||||
|
let mut s = rec;
|
||||||
|
s.status = StepStatus::Error;
|
||||||
|
s.summary = "the callback has no code parameter".into();
|
||||||
|
s.hint = Some("Look at the raw callback URL. If it carries tokens in the fragment, the client is configured for the implicit flow at the provider.".into());
|
||||||
|
self.push(s);
|
||||||
|
return None;
|
||||||
|
};
|
||||||
|
let mut s = rec;
|
||||||
|
s.summary = "authorization code received".into();
|
||||||
|
self.push(s);
|
||||||
|
|
||||||
|
match get("state") {
|
||||||
|
Some(got) if got == state => {
|
||||||
|
self.push(Step::new("state", "Check state", StepStatus::Ok, "matches the login request"));
|
||||||
|
}
|
||||||
|
got => {
|
||||||
|
self.push(
|
||||||
|
Step::new("state", "Check state", StepStatus::Error, "state does not match")
|
||||||
|
.hint("Expected the state from this login. Usually two logins ran at the same time, or an old browser tab was reused. Close the old tabs and try again.")
|
||||||
|
.data(json!({ "expected": state, "received": got })),
|
||||||
|
);
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut params = vec![("code".to_string(), code), ("redirect_uri".to_string(), redirect)];
|
||||||
|
if let Some(v) = verifier {
|
||||||
|
params.push(("code_verifier".into(), v));
|
||||||
|
}
|
||||||
|
let ts = self.token_request("authorization_code", params, "Exchange code for tokens").await?;
|
||||||
|
if !self.validate_id_token(&ts, nonce.as_deref()).await {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
Some(ts)
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn device_code(&mut self) -> Option<TokenSet> {
|
||||||
|
let c = self.cfg;
|
||||||
|
let url = self.endpoint(&c.device_url, |m| &m.device_authorization_endpoint);
|
||||||
|
if url.is_empty() {
|
||||||
|
self.push(Step::new("device", "Request device code", StepStatus::Error, "no device authorization endpoint"));
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let mut params = vec![];
|
||||||
|
if !c.scopes.is_empty() {
|
||||||
|
params.push(("scope".to_string(), c.scope_string()));
|
||||||
|
}
|
||||||
|
let basic = self.client_params(&mut params);
|
||||||
|
let t = Instant::now();
|
||||||
|
let r = match self.http.post_form(&url, ¶ms, basic.as_ref().map(|(a, b)| (a.as_str(), b.as_str()))).await {
|
||||||
|
Ok(r) => r,
|
||||||
|
Err((ex, e)) => {
|
||||||
|
let mut st = Step::new("device", "Request device code", StepStatus::Error, e.clone()).hint(diagnose::connect_error("device endpoint", &e));
|
||||||
|
st.exchange = Some(ex);
|
||||||
|
self.push(st);
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let body = r.json.clone().unwrap_or(Value::Null);
|
||||||
|
let s = |k: &str| body.get(k).and_then(|v| v.as_str()).unwrap_or_default().to_string();
|
||||||
|
let device_code = s("device_code");
|
||||||
|
if device_code.is_empty() {
|
||||||
|
let mut st = Step::new("device", "Request device code", StepStatus::Error, format!("{} {}", s("error"), s("error_description")))
|
||||||
|
.hint(diagnose::token_error(&s("error"), &s("error_description"), c, self.meta.as_ref(), "device_code"));
|
||||||
|
st.exchange = Some(r.exchange);
|
||||||
|
self.push(st);
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let user_code = s("user_code");
|
||||||
|
let uri = if s("verification_uri").is_empty() { s("verification_url") } else { s("verification_uri") };
|
||||||
|
let complete = s("verification_uri_complete");
|
||||||
|
let mut interval = body.get("interval").and_then(|v| v.as_u64()).unwrap_or(5);
|
||||||
|
let expires = body.get("expires_in").and_then(|v| v.as_u64()).unwrap_or(600);
|
||||||
|
let mut st = Step::new("device", "Request device code", StepStatus::Ok, format!("code {user_code} at {uri}")).took(t);
|
||||||
|
st.exchange = Some(r.exchange);
|
||||||
|
self.push(st);
|
||||||
|
self.hooks.device_prompt(&uri, &user_code, (!complete.is_empty()).then_some(complete.as_str()));
|
||||||
|
let _ = self.hooks.open_browser(if complete.is_empty() { &uri } else { &complete });
|
||||||
|
|
||||||
|
let token_url = self.endpoint(&c.token_url, |m| &m.token_endpoint);
|
||||||
|
let started = Instant::now();
|
||||||
|
let t = Instant::now();
|
||||||
|
loop {
|
||||||
|
if started.elapsed().as_secs() > expires {
|
||||||
|
self.push(Step::new("poll", "Wait for user", StepStatus::Error, "the device code expired").hint("Start the login again and enter the code sooner."));
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
tokio::time::sleep(std::time::Duration::from_secs(interval)).await;
|
||||||
|
let mut params = vec![
|
||||||
|
("grant_type".to_string(), "urn:ietf:params:oauth:grant-type:device_code".to_string()),
|
||||||
|
("device_code".to_string(), device_code.clone()),
|
||||||
|
];
|
||||||
|
let basic = self.client_params(&mut params);
|
||||||
|
let r = self.http.post_form(&token_url, ¶ms, basic.as_ref().map(|(a, b)| (a.as_str(), b.as_str()))).await;
|
||||||
|
let Ok(r) = r else { continue };
|
||||||
|
let err = r.json.as_ref().and_then(|j| j.get("error")).and_then(|v| v.as_str()).unwrap_or("").to_string();
|
||||||
|
match err.as_str() {
|
||||||
|
"authorization_pending" => continue,
|
||||||
|
"slow_down" => {
|
||||||
|
interval += 5;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
"" => {
|
||||||
|
self.push(Step::new("poll", "Wait for user", StepStatus::Ok, "user finished the login").took(t));
|
||||||
|
// Device codes are single use: parse this reply, do not ask again.
|
||||||
|
return self.handle_token_reply(r, "urn:ietf:params:oauth:grant-type:device_code", "Fetch tokens", Instant::now());
|
||||||
|
}
|
||||||
|
_ => {
|
||||||
|
let mut st = Step::new("poll", "Wait for user", StepStatus::Error, err.clone())
|
||||||
|
.hint(diagnose::token_error(&err, "", c, self.meta.as_ref(), "device_code"));
|
||||||
|
st.exchange = Some(r.exchange);
|
||||||
|
self.push(st);
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Returns a usable token for the config, using the store, refresh or a new
|
||||||
|
/// login as needed. `force_refresh` skips the stored token (after a 401).
|
||||||
|
pub async fn obtain(cfg: &OauthConfig, key: &str, hooks: &dyn FlowHooks, force_refresh: bool) -> FlowResult {
|
||||||
|
let mut f = Flow { cfg, hooks, http: Http::new(cfg.verify_tls), steps: Vec::new(), warnings: Vec::new(), meta: None };
|
||||||
|
if !f.check_config() {
|
||||||
|
return f.fail(Step::new("done", "Get token", StepStatus::Skipped, "stopped because the config is incomplete"));
|
||||||
|
}
|
||||||
|
|
||||||
|
let stored = hooks.load_token(key);
|
||||||
|
if let Some(t) = &stored {
|
||||||
|
if !force_refresh && t.fresh() {
|
||||||
|
let left = t.seconds_left().map(|s| format!("token still valid for {}, no refresh needed", human(s))).unwrap_or_else(|| "token has no expiry, using it".into());
|
||||||
|
f.push(Step::new("stored", "Use stored token", StepStatus::Ok, left).data(t.tokens_map()));
|
||||||
|
return f.done(t.clone());
|
||||||
|
}
|
||||||
|
let why = if force_refresh { "the API answered 401, refreshing" } else { "token expires in less than 30 s" };
|
||||||
|
f.push(Step::new("stored", "Use stored token", StepStatus::Skipped, why));
|
||||||
|
} else {
|
||||||
|
f.push(Step::new("stored", "Use stored token", StepStatus::Skipped, "no token stored for this issuer, client, scopes and environment"));
|
||||||
|
}
|
||||||
|
|
||||||
|
if !f.discover().await {
|
||||||
|
return f.fail(Step::new("done", "Get token", StepStatus::Skipped, "stopped after discovery failed"));
|
||||||
|
}
|
||||||
|
|
||||||
|
if let Some(rt) = stored.as_ref().and_then(|t| t.refresh_token.clone()).filter(|_| cfg.auto_refresh) {
|
||||||
|
if let Some(ts) = f.refresh(key, &rt).await {
|
||||||
|
hooks.save_token(key, &ts);
|
||||||
|
f.push(Step::new("save", "Store token", StepStatus::Ok, "saved in the system keyring"));
|
||||||
|
return f.done(ts);
|
||||||
|
}
|
||||||
|
// Mark the failed refresh as recovered, not fatal, if a new login follows.
|
||||||
|
// A dead refresh token is not fatal: fall back to a fresh login
|
||||||
|
// (for client credentials simply a new token request).
|
||||||
|
if let Some(last) = f.steps.last_mut().filter(|s| s.status == StepStatus::Error) {
|
||||||
|
last.status = StepStatus::Warning;
|
||||||
|
last.hint = Some(format!("{} Falling back to a new login.", last.hint.clone().unwrap_or_default()));
|
||||||
|
}
|
||||||
|
hooks.delete_token(key);
|
||||||
|
}
|
||||||
|
|
||||||
|
let needs_user = matches!(cfg.grant, Grant::AuthorizationCode | Grant::DeviceCode);
|
||||||
|
if needs_user && !hooks.interactive() {
|
||||||
|
f.push(Step::new("login", "Log in", StepStatus::Skipped, "a browser login is needed; it starts when you send the request"));
|
||||||
|
return FlowResult { steps: f.steps, warnings: f.warnings, ..Default::default() };
|
||||||
|
}
|
||||||
|
|
||||||
|
let ts = match cfg.grant {
|
||||||
|
Grant::ClientCredentials => {
|
||||||
|
let mut p = Vec::new();
|
||||||
|
if !cfg.scopes.is_empty() {
|
||||||
|
p.push(("scope".to_string(), cfg.scope_string()));
|
||||||
|
}
|
||||||
|
f.token_request("client_credentials", p, "Request token").await
|
||||||
|
}
|
||||||
|
Grant::Password => {
|
||||||
|
f.warnings.push("The password grant is deprecated (OAuth 2.1 removes it). Use it only for legacy systems and tests.".into());
|
||||||
|
let mut p = vec![("username".to_string(), cfg.username.clone()), ("password".to_string(), cfg.password.clone())];
|
||||||
|
if !cfg.scopes.is_empty() {
|
||||||
|
p.push(("scope".to_string(), cfg.scope_string()));
|
||||||
|
}
|
||||||
|
let ts = f.token_request("password", p, "Request token").await;
|
||||||
|
if let Some(t) = &ts {
|
||||||
|
f.validate_id_token(t, None).await;
|
||||||
|
}
|
||||||
|
ts
|
||||||
|
}
|
||||||
|
Grant::AuthorizationCode => f.authorization_code().await,
|
||||||
|
Grant::DeviceCode => f.device_code().await,
|
||||||
|
};
|
||||||
|
let Some(ts) = ts else {
|
||||||
|
return FlowResult { steps: f.steps, warnings: f.warnings, ..Default::default() };
|
||||||
|
};
|
||||||
|
hooks.save_token(key, &ts);
|
||||||
|
f.push(Step::new("save", "Store token", StepStatus::Ok, "saved in the system keyring"));
|
||||||
|
if cfg.use_id_token && ts.id_token.is_none() {
|
||||||
|
return f.fail(Step::new("attach", "Pick token", StepStatus::Error, "the config attaches the ID token, but none was issued").hint("Add the openid scope, or attach the access token instead."));
|
||||||
|
}
|
||||||
|
f.done(ts)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Fetches discovery and checks that token endpoint and JWKS answer; with
|
||||||
|
/// client credentials it also requests a token. Nothing is stored.
|
||||||
|
pub async fn test_connection(cfg: &OauthConfig, hooks: &dyn FlowHooks) -> FlowResult {
|
||||||
|
let mut f = Flow { cfg, hooks, http: Http::new(cfg.verify_tls), steps: Vec::new(), warnings: Vec::new(), meta: None };
|
||||||
|
if !f.check_config() || !f.discover().await {
|
||||||
|
return FlowResult { steps: f.steps, warnings: f.warnings, ..Default::default() };
|
||||||
|
}
|
||||||
|
for (title, url) in [
|
||||||
|
("Reach token endpoint", f.endpoint(&cfg.token_url, |m| &m.token_endpoint)),
|
||||||
|
("Reach JWKS", f.endpoint(&cfg.jwks_url, |m| &m.jwks_uri)),
|
||||||
|
] {
|
||||||
|
if url.is_empty() {
|
||||||
|
f.push(Step::new("reach", title, StepStatus::Skipped, "no URL"));
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let t = Instant::now();
|
||||||
|
match f.http.get(&url, None).await {
|
||||||
|
Ok(r) => {
|
||||||
|
let mut st = Step::new("reach", title, StepStatus::Ok, format!("HTTP {} (any answer means it is reachable)", r.status)).took(t);
|
||||||
|
st.exchange = Some(r.exchange);
|
||||||
|
f.push(st);
|
||||||
|
}
|
||||||
|
Err((ex, e)) => {
|
||||||
|
let mut st = Step::new("reach", title, StepStatus::Error, e.clone()).hint(diagnose::connect_error(title, &e)).took(t);
|
||||||
|
st.exchange = Some(ex);
|
||||||
|
f.push(st);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if cfg.grant == Grant::ClientCredentials {
|
||||||
|
let mut p = Vec::new();
|
||||||
|
if !cfg.scopes.is_empty() {
|
||||||
|
p.push(("scope".to_string(), cfg.scope_string()));
|
||||||
|
}
|
||||||
|
f.token_request("client_credentials", p, "Request token").await;
|
||||||
|
}
|
||||||
|
FlowResult { steps: f.steps, warnings: f.warnings, ..Default::default() }
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
|
||||||
|
#[serde(rename_all = "snake_case")]
|
||||||
|
pub enum Action {
|
||||||
|
Userinfo,
|
||||||
|
Introspect,
|
||||||
|
Revoke,
|
||||||
|
Refresh,
|
||||||
|
Discovery,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Runs one step on its own, against the stored token, without a browser login.
|
||||||
|
pub async fn action(cfg: &OauthConfig, key: &str, hooks: &dyn FlowHooks, what: Action) -> FlowResult {
|
||||||
|
let mut f = Flow { cfg, hooks, http: Http::new(cfg.verify_tls), steps: Vec::new(), warnings: Vec::new(), meta: None };
|
||||||
|
if matches!(what, Action::Discovery) {
|
||||||
|
DISCOVERY.lock().unwrap().get_or_insert_with(HashMap::new).remove(&cfg.issuer);
|
||||||
|
f.discover().await;
|
||||||
|
return FlowResult { steps: f.steps, warnings: f.warnings, ..Default::default() };
|
||||||
|
}
|
||||||
|
let _ = f.discover().await;
|
||||||
|
let Some(t) = hooks.load_token(key) else {
|
||||||
|
f.push(Step::new("stored", "Load token", StepStatus::Error, "no token stored").hint("Send a request with this auth first, or use Log in."));
|
||||||
|
return FlowResult { steps: f.steps, warnings: f.warnings, ..Default::default() };
|
||||||
|
};
|
||||||
|
match what {
|
||||||
|
Action::Refresh => {
|
||||||
|
let Some(rt) = t.refresh_token.clone() else {
|
||||||
|
f.push(Step::new("token", "Refresh token", StepStatus::Error, "no refresh token stored").hint("The provider did not issue one. Ask for the offline_access scope or log in again."));
|
||||||
|
return FlowResult { steps: f.steps, warnings: f.warnings, ..Default::default() };
|
||||||
|
};
|
||||||
|
if let Some(ts) = f.refresh(key, &rt).await {
|
||||||
|
hooks.save_token(key, &ts);
|
||||||
|
f.push(Step::new("save", "Store token", StepStatus::Ok, "saved"));
|
||||||
|
return f.done(ts);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Action::Userinfo => {
|
||||||
|
let url = f.endpoint(&cfg.userinfo_url, |m| &m.userinfo_endpoint);
|
||||||
|
if url.is_empty() {
|
||||||
|
f.push(Step::new("userinfo", "UserInfo", StepStatus::Error, "no userinfo endpoint"));
|
||||||
|
} else {
|
||||||
|
let t0 = Instant::now();
|
||||||
|
match f.http.get(&url, Some(&t.access_token)).await {
|
||||||
|
Ok(r) => {
|
||||||
|
let ok = r.status == 200;
|
||||||
|
let mut st = Step::new("userinfo", "UserInfo", if ok { StepStatus::Ok } else { StepStatus::Error }, format!("HTTP {}", r.status)).took(t0);
|
||||||
|
st.data = r.json.clone().unwrap_or(Value::Null);
|
||||||
|
st.exchange = Some(r.exchange);
|
||||||
|
if !ok {
|
||||||
|
st = st.hint("The access token was not accepted by the userinfo endpoint. It needs the openid scope and must not be expired.");
|
||||||
|
}
|
||||||
|
f.push(st);
|
||||||
|
}
|
||||||
|
Err((ex, e)) => {
|
||||||
|
let mut st = Step::new("userinfo", "UserInfo", StepStatus::Error, e);
|
||||||
|
st.exchange = Some(ex);
|
||||||
|
f.push(st);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Action::Introspect | Action::Revoke => {
|
||||||
|
let (title, url) = if matches!(what, Action::Introspect) {
|
||||||
|
("Introspect token", f.endpoint(&cfg.introspection_url, |m| &m.introspection_endpoint))
|
||||||
|
} else {
|
||||||
|
("Revoke token", f.endpoint(&cfg.revocation_url, |m| &m.revocation_endpoint))
|
||||||
|
};
|
||||||
|
if url.is_empty() {
|
||||||
|
f.push(Step::new("x", title, StepStatus::Error, "the provider has no such endpoint"));
|
||||||
|
} else {
|
||||||
|
let token = if matches!(what, Action::Revoke) { t.refresh_token.clone().unwrap_or(t.access_token.clone()) } else { t.access_token.clone() };
|
||||||
|
let hint = if matches!(what, Action::Revoke) && t.refresh_token.is_some() { "refresh_token" } else { "access_token" };
|
||||||
|
let mut params = vec![("token".to_string(), token), ("token_type_hint".to_string(), hint.to_string())];
|
||||||
|
let basic = f.client_params(&mut params);
|
||||||
|
let t0 = Instant::now();
|
||||||
|
match f.http.post_form(&url, ¶ms, basic.as_ref().map(|(a, b)| (a.as_str(), b.as_str()))).await {
|
||||||
|
Ok(r) => {
|
||||||
|
let ok = (200..300).contains(&r.status);
|
||||||
|
let mut st = Step::new("x", title, if ok { StepStatus::Ok } else { StepStatus::Error }, format!("HTTP {}", r.status)).took(t0);
|
||||||
|
st.data = r.json.clone().unwrap_or(Value::Null);
|
||||||
|
st.exchange = Some(r.exchange);
|
||||||
|
f.push(st);
|
||||||
|
if ok && matches!(what, Action::Revoke) {
|
||||||
|
hooks.delete_token(key);
|
||||||
|
f.push(Step::new("forget", "Forget token", StepStatus::Ok, "removed from the keyring"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Err((ex, e)) => {
|
||||||
|
let mut st = Step::new("x", title, StepStatus::Error, e);
|
||||||
|
st.exchange = Some(ex);
|
||||||
|
f.push(st);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Action::Discovery => {}
|
||||||
|
}
|
||||||
|
FlowResult { steps: f.steps, warnings: f.warnings, ..Default::default() }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// RP-initiated logout URL, if the provider supports it.
|
||||||
|
pub fn logout_url(cfg: &OauthConfig, id_token: Option<&str>) -> Option<String> {
|
||||||
|
let base = if cfg.end_session_url.is_empty() {
|
||||||
|
DISCOVERY.lock().unwrap().as_ref()?.get(&cfg.issuer)?.1.end_session_endpoint.clone()
|
||||||
|
} else {
|
||||||
|
cfg.end_session_url.clone()
|
||||||
|
};
|
||||||
|
if base.is_empty() {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let mut u = url::Url::parse(&base).ok()?;
|
||||||
|
if let Some(t) = id_token {
|
||||||
|
u.query_pairs_mut().append_pair("id_token_hint", t);
|
||||||
|
}
|
||||||
|
u.query_pairs_mut().append_pair("client_id", &cfg.client_id);
|
||||||
|
Some(u.to_string())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn random_token(len: usize) -> String {
|
||||||
|
use rand::Rng;
|
||||||
|
const CHARS: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~";
|
||||||
|
let mut r = rand::thread_rng();
|
||||||
|
(0..len).map(|_| CHARS[r.gen_range(0..CHARS.len())] as char).collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn human(secs: i64) -> String {
|
||||||
|
let s = secs.abs();
|
||||||
|
let out = if s < 120 {
|
||||||
|
format!("{s} s")
|
||||||
|
} else if s < 7200 {
|
||||||
|
format!("{} min", s / 60)
|
||||||
|
} else if s < 172_800 {
|
||||||
|
format!("{} h", s / 3600)
|
||||||
|
} else {
|
||||||
|
format!("{} days", s / 86400)
|
||||||
|
};
|
||||||
|
if secs < 0 {
|
||||||
|
format!("{out} ago")
|
||||||
|
} else {
|
||||||
|
out
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -56,6 +56,18 @@ pub fn transport_for(ctx: &RequestContext, url: &str) -> TransportOptions {
|
|||||||
pem.push(b'\n');
|
pem.push(b'\n');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
if pem.is_empty() {
|
||||||
|
if let Some(p12) = &c.pkcs12 {
|
||||||
|
let pass = c.passphrase.as_deref().map(|x| r.apply(x)).unwrap_or_default();
|
||||||
|
match std::fs::read(ctx.root.join(r.apply(p12)))
|
||||||
|
.map_err(anyhow::Error::from)
|
||||||
|
.and_then(|der| auth::tls::pkcs12_to_pem(&der, &pass))
|
||||||
|
{
|
||||||
|
Ok(p) => pem = p,
|
||||||
|
Err(e) => tracing::warn!("client certificate {}: {e:#}", c.host),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
if !pem.is_empty() {
|
if !pem.is_empty() {
|
||||||
t.identity_pem = Some(pem);
|
t.identity_pem = Some(pem);
|
||||||
}
|
}
|
||||||
@@ -110,10 +122,11 @@ pub async fn execute(
|
|||||||
out.missing = base.missing.clone();
|
out.missing = base.missing.clone();
|
||||||
|
|
||||||
let is_oauth = matches!(&ctx.auth.auth, Auth::Config(c) if c.kind == "oauth2" || c.kind == "oidc");
|
let is_oauth = matches!(&ctx.auth.auth, Auth::Config(c) if c.kind == "oauth2" || c.kind == "oidc");
|
||||||
|
let is_digest = matches!(&ctx.auth.auth, Auth::Config(c) if c.kind == "digest");
|
||||||
let mut force_refresh = false;
|
let mut force_refresh = false;
|
||||||
loop {
|
loop {
|
||||||
let mut p = base.clone();
|
let mut p = base.clone();
|
||||||
out.auth = auth::apply(&ctx.auth, &mut p, &ctx.resolver, host, force_refresh).await;
|
out.auth = auth::apply(&ctx.auth, &mut p, &ctx.resolver, host, force_refresh, &ctx.root).await;
|
||||||
out.request = Some(sent(&p));
|
out.request = Some(sent(&p));
|
||||||
if out.auth.failed() {
|
if out.auth.failed() {
|
||||||
out.error = Some("authentication failed, see the Auth tab".into());
|
out.error = Some("authentication failed, see the Auth tab".into());
|
||||||
@@ -123,12 +136,69 @@ pub async fn execute(
|
|||||||
let jar = (ctx.collection_settings.cookies && !ctx.collection_id.is_empty())
|
let jar = (ctx.collection_settings.cookies && !ctx.collection_id.is_empty())
|
||||||
.then_some(ctx.collection_id.as_str());
|
.then_some(ctx.collection_id.as_str());
|
||||||
match engine.send(&p, &transport, jar).await {
|
match engine.send(&p, &transport, jar).await {
|
||||||
|
Ok(resp) if is_digest && resp.status == 401 => {
|
||||||
|
let challenge = resp
|
||||||
|
.headers
|
||||||
|
.iter()
|
||||||
|
.filter(|(k, _)| k.eq_ignore_ascii_case("www-authenticate"))
|
||||||
|
.map(|(_, v)| v.as_str())
|
||||||
|
.find(|v| v.trim_start().to_ascii_lowercase().starts_with("digest"));
|
||||||
|
let Some(challenge) = challenge else {
|
||||||
|
out.auth.steps.push(
|
||||||
|
auth::Step::new("challenge", "Read server challenge", auth::StepStatus::Error, "the 401 response has no Digest challenge")
|
||||||
|
.hint("The server does not ask for Digest auth. Check the WWW-Authenticate header in the response, it names the scheme the server wants."),
|
||||||
|
);
|
||||||
|
out.asserts = run_asserts(&req.assert, &resp);
|
||||||
|
out.response = Some(resp);
|
||||||
|
return out;
|
||||||
|
};
|
||||||
|
let challenge = challenge.to_string();
|
||||||
|
if let Some(Auth::Config(cfg)) = Some(&ctx.auth.auth) {
|
||||||
|
let resolver = &ctx.resolver;
|
||||||
|
let res = |key: &str| -> (String, Vec<String>) {
|
||||||
|
let r = resolver.resolve(cfg.str(key).unwrap_or_default());
|
||||||
|
(r.value, r.missing)
|
||||||
|
};
|
||||||
|
let mut p2 = p.clone();
|
||||||
|
let mut dbg = out.auth.clone();
|
||||||
|
dbg.steps.retain(|s| s.id != "challenge");
|
||||||
|
if !auth::digest_respond(cfg, &mut p2, &challenge, &res, &mut dbg) {
|
||||||
|
out.auth = dbg;
|
||||||
|
out.error = Some("authentication failed, see the Auth tab".into());
|
||||||
|
out.response = Some(resp);
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
for s in &dbg.sent {
|
||||||
|
ctx.resolver.note_secret(&s.value);
|
||||||
|
}
|
||||||
|
out.auth = dbg;
|
||||||
|
out.request = Some(sent(&p2));
|
||||||
|
match engine.send(&p2, &transport, jar).await {
|
||||||
|
Ok(resp) => {
|
||||||
|
if resp.status == 401 {
|
||||||
|
out.auth.steps.push(
|
||||||
|
auth::Step::new("verify", "Server checks digest", auth::StepStatus::Error, "still 401 after answering the challenge")
|
||||||
|
.hint("Wrong username or password, or the server wants a different algorithm or qop. Compare realm and algorithm in the steps above with the server's configuration."),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
out.asserts = run_asserts(&req.assert, &resp);
|
||||||
|
out.extracted = run_extracts(&req.extract, &resp);
|
||||||
|
out.response = Some(resp);
|
||||||
|
}
|
||||||
|
Err(e) => out.error = Some(format!("{e:#}")),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
Ok(resp) => {
|
Ok(resp) => {
|
||||||
if resp.status == 401 && is_oauth && !force_refresh && req.settings.retry_on_401 {
|
if resp.status == 401 && is_oauth && !force_refresh && req.settings.retry_on_401 {
|
||||||
force_refresh = true;
|
force_refresh = true;
|
||||||
out.retried = true;
|
out.retried = true;
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
if !out.auth.kind.is_empty() && out.auth.kind != "none" {
|
||||||
|
out.auth.steps.push(send_step(&out.auth, resp.status));
|
||||||
|
}
|
||||||
out.asserts = run_asserts(&req.assert, &resp);
|
out.asserts = run_asserts(&req.assert, &resp);
|
||||||
out.extracted = run_extracts(&req.extract, &resp);
|
out.extracted = run_extracts(&req.extract, &resp);
|
||||||
out.response = Some(resp);
|
out.response = Some(resp);
|
||||||
@@ -138,3 +208,32 @@ pub async fn execute(
|
|||||||
return out;
|
return out;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Last step of every auth timeline: did the API accept what was sent?
|
||||||
|
fn send_step(dbg: &AuthDebug, status: u16) -> auth::Step {
|
||||||
|
use auth::{Step, StepStatus};
|
||||||
|
if status != 401 && status != 403 {
|
||||||
|
return Step::new("send", "Send request", StepStatus::Ok, format!("HTTP {status}"));
|
||||||
|
}
|
||||||
|
let sent = dbg
|
||||||
|
.sent
|
||||||
|
.iter()
|
||||||
|
.map(|s| {
|
||||||
|
let v = if s.value.len() > 24 { format!("{}…", &s.value[..s.value.char_indices().nth(24).map(|x| x.0).unwrap_or(s.value.len())]) } else { s.value.clone() };
|
||||||
|
format!("{} {}: {v}", s.location, s.name)
|
||||||
|
})
|
||||||
|
.collect::<Vec<_>>()
|
||||||
|
.join(", ");
|
||||||
|
let mut hint = format!("Sent {sent}.\n");
|
||||||
|
if dbg.kind == "oauth2" || dbg.kind == "oidc" {
|
||||||
|
hint.push_str("The token was accepted by the provider but not by this API. Check in the token inspector that aud names this API and the needed scope is granted, and that the prefix (Bearer) is what the API expects.");
|
||||||
|
if status == 401 {
|
||||||
|
hint.push_str(" knock already tried one refresh if retry on 401 is on.");
|
||||||
|
}
|
||||||
|
} else if status == 403 {
|
||||||
|
hint.push_str("403 means the credentials were understood but lack permission for this resource.");
|
||||||
|
} else {
|
||||||
|
hint.push_str("Check the credentials and that the API expects this auth type. The response's WWW-Authenticate header names the scheme it wants.");
|
||||||
|
}
|
||||||
|
Step::new("send", "Send request", StepStatus::Error, format!("HTTP {status}: the API rejected the credentials")).hint(hint)
|
||||||
|
}
|
||||||
|
|||||||
@@ -0,0 +1,216 @@
|
|||||||
|
//! End-to-end OAuth flows against a tiny in-process provider.
|
||||||
|
|
||||||
|
use futures_util::future::BoxFuture;
|
||||||
|
use knock_core::auth::{Step, StepStatus};
|
||||||
|
use knock_core::model::AuthConfig;
|
||||||
|
use knock_core::oauth::{self, config::OauthConfig, FlowHooks, TokenSet};
|
||||||
|
use knock_core::vars::Resolver;
|
||||||
|
use std::collections::HashMap;
|
||||||
|
use std::sync::{Arc, Mutex};
|
||||||
|
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||||
|
use tokio::net::TcpListener;
|
||||||
|
|
||||||
|
#[derive(Default)]
|
||||||
|
struct Provider {
|
||||||
|
codes: HashMap<String, (String, Option<String>)>, // code -> (redirect_uri, code_challenge)
|
||||||
|
refreshes: u32,
|
||||||
|
reject_refresh: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn start_provider(state: Arc<Mutex<Provider>>) -> String {
|
||||||
|
let l = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||||
|
let base = format!("http://{}", l.local_addr().unwrap());
|
||||||
|
let base2 = base.clone();
|
||||||
|
tokio::spawn(async move {
|
||||||
|
loop {
|
||||||
|
let (mut s, _) = l.accept().await.unwrap();
|
||||||
|
let state = state.clone();
|
||||||
|
let base = base2.clone();
|
||||||
|
tokio::spawn(async move {
|
||||||
|
let mut buf = vec![0u8; 65536];
|
||||||
|
let n = s.read(&mut buf).await.unwrap_or(0);
|
||||||
|
let req = String::from_utf8_lossy(&buf[..n]).to_string();
|
||||||
|
let first = req.lines().next().unwrap_or("").to_string();
|
||||||
|
let target = first.split_whitespace().nth(1).unwrap_or("/").to_string();
|
||||||
|
let body = req.split("\r\n\r\n").nth(1).unwrap_or("").to_string();
|
||||||
|
let form: HashMap<String, String> = url::form_urlencoded::parse(body.as_bytes()).into_owned().collect();
|
||||||
|
let (status, extra_headers, payload) = route(&base, &target, &req, &form, &state);
|
||||||
|
let resp = format!(
|
||||||
|
"HTTP/1.1 {status}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n{extra_headers}\r\n{payload}",
|
||||||
|
payload.len()
|
||||||
|
);
|
||||||
|
let _ = s.write_all(resp.as_bytes()).await;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
base
|
||||||
|
}
|
||||||
|
|
||||||
|
fn route(base: &str, target: &str, raw: &str, form: &HashMap<String, String>, st: &Arc<Mutex<Provider>>) -> (String, String, String) {
|
||||||
|
let path = target.split('?').next().unwrap();
|
||||||
|
match path {
|
||||||
|
"/.well-known/openid-configuration" => (
|
||||||
|
"200 OK".into(),
|
||||||
|
String::new(),
|
||||||
|
serde_json::json!({
|
||||||
|
"issuer": base,
|
||||||
|
"authorization_endpoint": format!("{base}/authorize"),
|
||||||
|
"token_endpoint": format!("{base}/token"),
|
||||||
|
"scopes_supported": ["openid", "profile", "api"],
|
||||||
|
"code_challenge_methods_supported": ["S256"],
|
||||||
|
"token_endpoint_auth_methods_supported": ["client_secret_basic", "client_secret_post"]
|
||||||
|
})
|
||||||
|
.to_string(),
|
||||||
|
),
|
||||||
|
"/authorize" => {
|
||||||
|
let q: HashMap<String, String> = url::form_urlencoded::parse(target.split('?').nth(1).unwrap_or("").as_bytes()).into_owned().collect();
|
||||||
|
let code = format!("code-{}", q["state"].len());
|
||||||
|
st.lock().unwrap().codes.insert(code.clone(), (q["redirect_uri"].clone(), q.get("code_challenge").cloned()));
|
||||||
|
let loc = format!("{}?code={code}&state={}", q["redirect_uri"], q["state"]);
|
||||||
|
("302 Found".into(), format!("Location: {loc}\r\n"), String::new())
|
||||||
|
}
|
||||||
|
"/token" => {
|
||||||
|
let basic_ok = raw.contains("Authorization: Basic ") || raw.to_lowercase().contains("authorization: basic ");
|
||||||
|
if !basic_ok && form.get("client_secret").map(String::as_str) != Some("s3cret") {
|
||||||
|
return ("401 Unauthorized".into(), String::new(), r#"{"error":"invalid_client","error_description":"bad secret"}"#.into());
|
||||||
|
}
|
||||||
|
let ok = |extra: &str| {
|
||||||
|
(
|
||||||
|
"200 OK".to_string(),
|
||||||
|
String::new(),
|
||||||
|
format!(r#"{{"access_token":"at-{extra}","token_type":"Bearer","expires_in":3600,"refresh_token":"rt-1","scope":"api"}}"#),
|
||||||
|
)
|
||||||
|
};
|
||||||
|
match form.get("grant_type").map(String::as_str) {
|
||||||
|
Some("client_credentials") => ok("cc"),
|
||||||
|
Some("authorization_code") => {
|
||||||
|
let mut s = st.lock().unwrap();
|
||||||
|
let Some((redirect, challenge)) = s.codes.remove(&form["code"]) else {
|
||||||
|
return ("400 Bad Request".into(), String::new(), r#"{"error":"invalid_grant"}"#.into());
|
||||||
|
};
|
||||||
|
if redirect != form["redirect_uri"] {
|
||||||
|
return ("400 Bad Request".into(), String::new(), r#"{"error":"invalid_grant","error_description":"redirect_uri"}"#.into());
|
||||||
|
}
|
||||||
|
use base64::Engine;
|
||||||
|
use sha2::Digest;
|
||||||
|
let v = form.get("code_verifier").cloned().unwrap_or_default();
|
||||||
|
let calc = base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(sha2::Sha256::digest(v.as_bytes()));
|
||||||
|
if challenge.as_deref() != Some(calc.as_str()) {
|
||||||
|
return ("400 Bad Request".into(), String::new(), r#"{"error":"invalid_grant","error_description":"PKCE verification failed"}"#.into());
|
||||||
|
}
|
||||||
|
ok("code")
|
||||||
|
}
|
||||||
|
Some("refresh_token") => {
|
||||||
|
let mut s = st.lock().unwrap();
|
||||||
|
if s.reject_refresh {
|
||||||
|
return ("400 Bad Request".into(), String::new(), r#"{"error":"invalid_grant","error_description":"Token is not active"}"#.into());
|
||||||
|
}
|
||||||
|
s.refreshes += 1;
|
||||||
|
ok("refreshed")
|
||||||
|
}
|
||||||
|
_ => ("400 Bad Request".into(), String::new(), r#"{"error":"unsupported_grant_type"}"#.into()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ => ("404 Not Found".into(), String::new(), "{}".into()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Default)]
|
||||||
|
struct TestHooks {
|
||||||
|
store: Mutex<HashMap<String, TokenSet>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl FlowHooks for TestHooks {
|
||||||
|
fn interactive(&self) -> bool {
|
||||||
|
true
|
||||||
|
}
|
||||||
|
fn open_browser(&self, url: &str) -> Result<(), String> {
|
||||||
|
// The "browser": follow the provider's redirect to the loopback listener.
|
||||||
|
let url = url.to_string();
|
||||||
|
tokio::spawn(async move {
|
||||||
|
let c = reqwest::Client::builder().redirect(reqwest::redirect::Policy::limited(3)).build().unwrap();
|
||||||
|
let _ = c.get(url).send().await;
|
||||||
|
});
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
fn wait_external(&self) -> BoxFuture<'static, Option<String>> {
|
||||||
|
Box::pin(async { None })
|
||||||
|
}
|
||||||
|
fn progress(&self, _: &Step) {}
|
||||||
|
fn device_prompt(&self, _: &str, _: &str, _: Option<&str>) {}
|
||||||
|
fn load_token(&self, key: &str) -> Option<TokenSet> {
|
||||||
|
self.store.lock().unwrap().get(key).cloned()
|
||||||
|
}
|
||||||
|
fn save_token(&self, key: &str, t: &TokenSet) {
|
||||||
|
self.store.lock().unwrap().insert(key.into(), t.clone());
|
||||||
|
}
|
||||||
|
fn delete_token(&self, key: &str) {
|
||||||
|
self.store.lock().unwrap().remove(key);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn cfg(json: serde_json::Value) -> OauthConfig {
|
||||||
|
let a: AuthConfig = serde_json::from_value(json).unwrap();
|
||||||
|
OauthConfig::from_auth(&a, &Resolver::default())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn client_credentials_then_cached_then_refresh() {
|
||||||
|
let st = Arc::new(Mutex::new(Provider::default()));
|
||||||
|
let base = start_provider(st.clone()).await;
|
||||||
|
let c = cfg(serde_json::json!({ "type": "oauth2", "grant": "client_credentials", "issuer": base, "client_id": "knock", "client_secret": "s3cret", "scopes": "api" }));
|
||||||
|
let hooks = TestHooks::default();
|
||||||
|
let key = c.store_key("col", Some("local"));
|
||||||
|
|
||||||
|
let r = oauth::obtain(&c, &key, &hooks, false).await;
|
||||||
|
assert_eq!(r.token.as_deref(), Some("at-cc"), "{:#?}", r.steps);
|
||||||
|
assert!(r.steps.iter().any(|s| s.id == "discovery" && s.status == StepStatus::Ok));
|
||||||
|
|
||||||
|
let r = oauth::obtain(&c, &key, &hooks, false).await;
|
||||||
|
assert_eq!(r.token.as_deref(), Some("at-cc"));
|
||||||
|
assert!(r.steps.iter().any(|s| s.id == "stored" && s.status == StepStatus::Ok));
|
||||||
|
|
||||||
|
// After a 401 the token is refreshed.
|
||||||
|
let r = oauth::obtain(&c, &key, &hooks, true).await;
|
||||||
|
assert_eq!(r.token.as_deref(), Some("at-refreshed"), "{:#?}", r.steps);
|
||||||
|
assert_eq!(st.lock().unwrap().refreshes, 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn authorization_code_with_pkce_over_loopback() {
|
||||||
|
let st = Arc::new(Mutex::new(Provider::default()));
|
||||||
|
let base = start_provider(st.clone()).await;
|
||||||
|
let c = cfg(serde_json::json!({ "type": "oauth2", "issuer": base, "client_id": "knock", "client_secret": "s3cret", "scopes": "api", "redirect_port": 53199 }));
|
||||||
|
let hooks = TestHooks::default();
|
||||||
|
let key = c.store_key("col", None);
|
||||||
|
let r = oauth::obtain(&c, &key, &hooks, false).await;
|
||||||
|
assert_eq!(r.token.as_deref(), Some("at-code"), "{:#?}", r.steps);
|
||||||
|
let ids: Vec<&str> = r.steps.iter().map(|s| s.id.as_str()).collect();
|
||||||
|
for want in ["config", "discovery", "authorize", "browser", "callback", "received", "state", "token", "parse", "save"] {
|
||||||
|
assert!(ids.contains(&want), "missing step {want}: {ids:?}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn errors_are_explained() {
|
||||||
|
let st = Arc::new(Mutex::new(Provider::default()));
|
||||||
|
let base = start_provider(st.clone()).await;
|
||||||
|
let c = cfg(serde_json::json!({ "type": "oauth2", "grant": "client_credentials", "issuer": base, "client_id": "knock", "client_auth": "post", "client_secret": "wrong" }));
|
||||||
|
let hooks = TestHooks::default();
|
||||||
|
let r = oauth::obtain(&c, &c.store_key("c", None), &hooks, false).await;
|
||||||
|
assert!(r.token.is_none());
|
||||||
|
let failed = r.steps.iter().find(|s| s.status == StepStatus::Error).expect("an error step");
|
||||||
|
assert!(failed.summary.contains("invalid_client"), "{}", failed.summary);
|
||||||
|
let hint = failed.hint.clone().unwrap_or_default();
|
||||||
|
assert!(hint.contains("client_secret_basic"), "{hint}");
|
||||||
|
assert!(failed.exchange.as_ref().unwrap().curl.starts_with("curl -X POST"));
|
||||||
|
|
||||||
|
// A dead refresh token falls back to a new login (here: client credentials).
|
||||||
|
st.lock().unwrap().reject_refresh = true;
|
||||||
|
let c = cfg(serde_json::json!({ "type": "oauth2", "grant": "client_credentials", "issuer": base, "client_id": "knock", "client_secret": "s3cret" }));
|
||||||
|
let key = c.store_key("c", None);
|
||||||
|
hooks.save_token(&key, &TokenSet { access_token: "old".into(), refresh_token: Some("rt-dead".into()), expires_at: Some(0), obtained_at: 0, ..Default::default() });
|
||||||
|
let r = oauth::obtain(&c, &key, &hooks, false).await;
|
||||||
|
assert!(r.steps.iter().any(|s| s.id == "token" && s.summary.contains("invalid_grant") && s.status == StepStatus::Warning));
|
||||||
|
assert_eq!(r.token.as_deref(), Some("at-cc"), "{:#?}", r.steps);
|
||||||
|
}
|
||||||
@@ -34,3 +34,4 @@ tauri-plugin-deep-link = "2"
|
|||||||
rusqlite = { version = "0.37", features = ["bundled"] }
|
rusqlite = { version = "0.37", features = ["bundled"] }
|
||||||
notify = "8"
|
notify = "8"
|
||||||
futures-util = "0.3"
|
futures-util = "0.3"
|
||||||
|
regex = "1"
|
||||||
|
|||||||
@@ -309,7 +309,7 @@ pub struct ScopeArgs {
|
|||||||
pub env: Option<String>,
|
pub env: Option<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn build_context(state: &AppState, a: &ScopeArgs) -> anyhow::Result<RequestContext> {
|
pub fn build_context(app: &AppHandle, state: &AppState, a: &ScopeArgs) -> anyhow::Result<RequestContext> {
|
||||||
let globals = db::globals_load(&state.db.lock().unwrap()).unwrap_or_default();
|
let globals = db::globals_load(&state.db.lock().unwrap()).unwrap_or_default();
|
||||||
match &a.col {
|
match &a.col {
|
||||||
Some(col) => {
|
Some(col) => {
|
||||||
@@ -325,7 +325,7 @@ pub fn build_context(state: &AppState, a: &ScopeArgs) -> anyhow::Result<RequestC
|
|||||||
runtime: state.runtime_vars(col),
|
runtime: state.runtime_vars(col),
|
||||||
globals,
|
globals,
|
||||||
secrets: Arc::new(store),
|
secrets: Arc::new(store),
|
||||||
oauth: Some(Arc::new(crate::oauth::TokenLookup::new(state, &c, a.env.as_deref()))),
|
oauth: Some(Arc::new(crate::oauth::TokenLookup::new(app, &c, a.env.as_deref()))),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
None => {
|
None => {
|
||||||
@@ -352,8 +352,8 @@ pub struct VarsView {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
pub fn vars_list(state: State<'_, AppState>, args: ScopeArgs) -> Res<VarsView> {
|
pub fn vars_list(app: AppHandle, state: State<'_, AppState>, args: ScopeArgs) -> Res<VarsView> {
|
||||||
let ctx = build_context(&state, &args).map_err(errx)?;
|
let ctx = build_context(&app, &state, &args).map_err(errx)?;
|
||||||
Ok(VarsView {
|
Ok(VarsView {
|
||||||
vars: ctx.resolver.names(),
|
vars: ctx.resolver.names(),
|
||||||
dynamic: DYNAMIC_VARS.iter().map(|(a, b)| (a.to_string(), b.to_string())).collect(),
|
dynamic: DYNAMIC_VARS.iter().map(|(a, b)| (a.to_string(), b.to_string())).collect(),
|
||||||
@@ -410,7 +410,7 @@ pub struct SendResult {
|
|||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
pub async fn request_send(app: AppHandle, args: SendArgs) -> Res<SendResult> {
|
pub async fn request_send(app: AppHandle, args: SendArgs) -> Res<SendResult> {
|
||||||
let state = app.state::<AppState>();
|
let state = app.state::<AppState>();
|
||||||
let ctx = build_context(&state, &args.scope).map_err(errx)?;
|
let ctx = build_context(&app, &state, &args.scope).map_err(errx)?;
|
||||||
let engine = state.engine.clone();
|
let engine = state.engine.clone();
|
||||||
let req = args.scope.request.clone();
|
let req = args.scope.request.clone();
|
||||||
let host = crate::oauth::Host::new(app.clone(), args.scope.col.clone(), args.scope.env.clone());
|
let host = crate::oauth::Host::new(app.clone(), args.scope.col.clone(), args.scope.env.clone());
|
||||||
@@ -522,7 +522,7 @@ pub struct Preview {
|
|||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
pub async fn request_preview(app: AppHandle, args: ScopeArgs) -> Res<Preview> {
|
pub async fn request_preview(app: AppHandle, args: ScopeArgs) -> Res<Preview> {
|
||||||
let state = app.state::<AppState>();
|
let state = app.state::<AppState>();
|
||||||
let ctx = build_context(&state, &args).map_err(errx)?;
|
let ctx = build_context(&app, &state, &args).map_err(errx)?;
|
||||||
let mut p = match knock_core::prepare::prepare(&args.request, &ctx) {
|
let mut p = match knock_core::prepare::prepare(&args.request, &ctx) {
|
||||||
Ok(p) => p,
|
Ok(p) => p,
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
@@ -530,7 +530,7 @@ pub async fn request_preview(app: AppHandle, args: ScopeArgs) -> Res<Preview> {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
let host = crate::oauth::Host::preview(app.clone(), args.col.clone(), args.env.clone());
|
let host = crate::oauth::Host::preview(app.clone(), args.col.clone(), args.env.clone());
|
||||||
let auth = knock_core::auth::apply(&ctx.auth, &mut p, &ctx.resolver, Some(&host), false).await;
|
let auth = knock_core::auth::apply(&ctx.auth, &mut p, &ctx.resolver, Some(&host), false, &ctx.root).await;
|
||||||
Ok(Preview {
|
Ok(Preview {
|
||||||
request: Some(knock_core::run::SentRequest {
|
request: Some(knock_core::run::SentRequest {
|
||||||
method: p.method.clone(),
|
method: p.method.clone(),
|
||||||
|
|||||||
@@ -21,6 +21,7 @@ pub fn run() {
|
|||||||
.setup(|app| {
|
.setup(|app| {
|
||||||
let dir = app.path().app_data_dir()?;
|
let dir = app.path().app_data_dir()?;
|
||||||
app.manage(state::AppState::new(dir)?);
|
app.manage(state::AppState::new(dir)?);
|
||||||
|
app.manage(oauth::OauthState::default());
|
||||||
Ok(())
|
Ok(())
|
||||||
})
|
})
|
||||||
.invoke_handler(tauri::generate_handler![
|
.invoke_handler(tauri::generate_handler![
|
||||||
@@ -66,6 +67,11 @@ pub fn run() {
|
|||||||
commands::setting_set,
|
commands::setting_set,
|
||||||
commands::path_params,
|
commands::path_params,
|
||||||
commands::app_version,
|
commands::app_version,
|
||||||
|
oauth::oauth_status,
|
||||||
|
oauth::oauth_run,
|
||||||
|
oauth::oauth_callback,
|
||||||
|
oauth::oauth_deep_link,
|
||||||
|
oauth::oauth_cancel,
|
||||||
])
|
])
|
||||||
.run(tauri::generate_context!())
|
.run(tauri::generate_context!())
|
||||||
.expect("error while running knock");
|
.expect("error while running knock");
|
||||||
|
|||||||
+302
-21
@@ -1,21 +1,182 @@
|
|||||||
//! OAuth glue between the core flow code and the app (browser, keyring,
|
//! OAuth glue between the core flow code and the app: browser, callbacks,
|
||||||
//! flow log). Filled in with the OAuth milestone.
|
//! keyring token store, live progress and the flow history.
|
||||||
|
|
||||||
|
use crate::commands::{build_context, ScopeArgs};
|
||||||
|
use crate::db;
|
||||||
use crate::state::AppState;
|
use crate::state::AppState;
|
||||||
|
use futures_util::future::BoxFuture;
|
||||||
use knock_core::auth::{AuthHost, OauthResult, Step, StepStatus};
|
use knock_core::auth::{AuthHost, OauthResult, Step, StepStatus};
|
||||||
use knock_core::model::AuthConfig;
|
use knock_core::model::AuthConfig;
|
||||||
|
use knock_core::oauth::{self, config::OauthConfig, Action, FlowHooks, TokenSet};
|
||||||
|
use knock_core::secrets;
|
||||||
use knock_core::vars::{OauthLookup, Resolver};
|
use knock_core::vars::{OauthLookup, Resolver};
|
||||||
use knock_core::Collection;
|
use knock_core::Collection;
|
||||||
use tauri::AppHandle;
|
use serde::{Deserialize, Serialize};
|
||||||
|
use std::collections::HashMap;
|
||||||
|
use std::sync::{Arc, Mutex};
|
||||||
|
use tauri::{AppHandle, Emitter, Manager};
|
||||||
|
|
||||||
|
/// Process-wide OAuth state, managed by Tauri.
|
||||||
|
#[derive(Default)]
|
||||||
|
pub struct OauthState {
|
||||||
|
tokens: Mutex<HashMap<String, Option<TokenSet>>>,
|
||||||
|
/// One login per config at a time; parallel sends wait for it.
|
||||||
|
locks: Mutex<HashMap<String, Arc<tokio::sync::Mutex<()>>>>,
|
||||||
|
/// Waiting custom-scheme or manual callback.
|
||||||
|
pending: Mutex<Option<tokio::sync::oneshot::Sender<String>>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl OauthState {
|
||||||
|
fn lock_for(&self, key: &str) -> Arc<tokio::sync::Mutex<()>> {
|
||||||
|
self.locks.lock().unwrap().entry(key.to_string()).or_default().clone()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn load(&self, key: &str) -> Option<TokenSet> {
|
||||||
|
if let Some(t) = self.tokens.lock().unwrap().get(key) {
|
||||||
|
return t.clone();
|
||||||
|
}
|
||||||
|
let t = secrets::slot_get(key).and_then(|s| serde_json::from_str(&s).ok());
|
||||||
|
self.tokens.lock().unwrap().insert(key.to_string(), t.clone());
|
||||||
|
t
|
||||||
|
}
|
||||||
|
|
||||||
|
fn save(&self, key: &str, t: &TokenSet) {
|
||||||
|
self.tokens.lock().unwrap().insert(key.to_string(), Some(t.clone()));
|
||||||
|
if let Ok(s) = serde_json::to_string(t) {
|
||||||
|
if let Err(e) = secrets::slot_set(key, &s) {
|
||||||
|
tracing::warn!("keyring: {e:#}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn delete(&self, key: &str) {
|
||||||
|
self.tokens.lock().unwrap().insert(key.to_string(), None);
|
||||||
|
let _ = secrets::slot_delete(key);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Serialize)]
|
||||||
|
struct Progress {
|
||||||
|
key: String,
|
||||||
|
step: Step,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Serialize)]
|
||||||
|
struct DevicePrompt {
|
||||||
|
key: String,
|
||||||
|
uri: String,
|
||||||
|
code: String,
|
||||||
|
complete: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
struct Hooks {
|
||||||
|
app: AppHandle,
|
||||||
|
key: String,
|
||||||
|
interactive: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl FlowHooks for Hooks {
|
||||||
|
fn interactive(&self) -> bool {
|
||||||
|
self.interactive
|
||||||
|
}
|
||||||
|
fn open_browser(&self, url: &str) -> Result<(), String> {
|
||||||
|
use tauri_plugin_opener::OpenerExt;
|
||||||
|
self.app.opener().open_url(url, None::<&str>).map_err(|e| e.to_string())
|
||||||
|
}
|
||||||
|
fn wait_external(&self) -> BoxFuture<'static, Option<String>> {
|
||||||
|
let (tx, rx) = tokio::sync::oneshot::channel();
|
||||||
|
*self.app.state::<OauthState>().pending.lock().unwrap() = Some(tx);
|
||||||
|
let _ = self.app.emit("oauth-awaiting", &self.key);
|
||||||
|
Box::pin(async move { rx.await.ok() })
|
||||||
|
}
|
||||||
|
fn progress(&self, step: &Step) {
|
||||||
|
let _ = self.app.emit("oauth-progress", Progress { key: self.key.clone(), step: step.clone() });
|
||||||
|
}
|
||||||
|
fn device_prompt(&self, uri: &str, code: &str, complete: Option<&str>) {
|
||||||
|
let _ = self.app.emit(
|
||||||
|
"oauth-device",
|
||||||
|
DevicePrompt { key: self.key.clone(), uri: uri.into(), code: code.into(), complete: complete.map(str::to_string) },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
fn load_token(&self, key: &str) -> Option<TokenSet> {
|
||||||
|
self.app.state::<OauthState>().load(key)
|
||||||
|
}
|
||||||
|
fn save_token(&self, key: &str, t: &TokenSet) {
|
||||||
|
self.app.state::<OauthState>().save(key, t);
|
||||||
|
}
|
||||||
|
fn delete_token(&self, key: &str) {
|
||||||
|
self.app.state::<OauthState>().delete(key);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------- flow history
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
|
pub struct FlowRecord {
|
||||||
|
pub id: String,
|
||||||
|
pub at: String,
|
||||||
|
pub kind: String,
|
||||||
|
pub ok: bool,
|
||||||
|
pub steps: Vec<Step>,
|
||||||
|
pub warnings: Vec<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
const KEEP_FLOWS: usize = 20;
|
||||||
|
|
||||||
|
/// Flows are stored masked: the debugger shows live flows in clear text, but
|
||||||
|
/// nothing that lands on disk carries a token.
|
||||||
|
fn mask_steps(steps: &[Step]) -> Vec<Step> {
|
||||||
|
let re_jwt = regex_lite(r"eyJ[\w-]+\.[\w-]+\.[\w-]*");
|
||||||
|
steps
|
||||||
|
.iter()
|
||||||
|
.map(|s| {
|
||||||
|
let text = serde_json::to_string(s).unwrap_or_default();
|
||||||
|
let mut masked = re_jwt.replace_all(&text, "••••••").into_owned();
|
||||||
|
for k in ["access_token", "refresh_token", "id_token", "client_secret", "code", "code_verifier", "password", "device_code"] {
|
||||||
|
let re = regex_lite(&format!(r#"({k}\\?"?\s*[:=]\s*\\?"?)([^"&\s,}}\\]+)"#));
|
||||||
|
masked = re.replace_all(&masked, "$1••••••").into_owned();
|
||||||
|
}
|
||||||
|
serde_json::from_str(&masked).unwrap_or_else(|_| s.clone())
|
||||||
|
})
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn regex_lite(p: &str) -> regex::Regex {
|
||||||
|
regex::Regex::new(p).expect("static regex")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn record_flow(app: &AppHandle, key: &str, kind: &str, steps: &[Step], warnings: &[String]) -> String {
|
||||||
|
let id = uuid::Uuid::new_v4().to_string();
|
||||||
|
let rec = FlowRecord {
|
||||||
|
id: id.clone(),
|
||||||
|
at: chrono::Utc::now().to_rfc3339(),
|
||||||
|
kind: kind.into(),
|
||||||
|
ok: !steps.iter().any(|s| s.status == StepStatus::Error),
|
||||||
|
steps: mask_steps(steps),
|
||||||
|
warnings: warnings.to_vec(),
|
||||||
|
};
|
||||||
|
let state = app.state::<AppState>();
|
||||||
|
let db = state.db.lock().unwrap();
|
||||||
|
let k = format!("flows:{key}");
|
||||||
|
let mut list: Vec<FlowRecord> = db::kv_get(&db, &k).ok().flatten().and_then(|s| serde_json::from_str(&s).ok()).unwrap_or_default();
|
||||||
|
list.insert(0, rec);
|
||||||
|
list.truncate(KEEP_FLOWS);
|
||||||
|
let _ = db::kv_set(&db, &k, &serde_json::to_string(&list).unwrap_or_default());
|
||||||
|
id
|
||||||
|
}
|
||||||
|
|
||||||
|
fn remember_name(app: &AppHandle, col: &str, env: Option<&str>, name: &str, key: &str) {
|
||||||
|
let state = app.state::<AppState>();
|
||||||
|
let db = state.db.lock().unwrap();
|
||||||
|
let _ = db::kv_set(&db, &format!("oauth-name:{col}:{}:{name}", env.unwrap_or("")), key);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------- AuthHost
|
||||||
|
|
||||||
pub struct Host {
|
pub struct Host {
|
||||||
#[allow(dead_code)]
|
|
||||||
app: AppHandle,
|
app: AppHandle,
|
||||||
#[allow(dead_code)]
|
|
||||||
col: Option<String>,
|
col: Option<String>,
|
||||||
#[allow(dead_code)]
|
|
||||||
env: Option<String>,
|
env: Option<String>,
|
||||||
#[allow(dead_code)]
|
|
||||||
interactive: bool,
|
interactive: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -29,31 +190,151 @@ impl Host {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl AuthHost for Host {
|
impl AuthHost for Host {
|
||||||
fn oauth2_token(
|
fn oauth2_token(&self, cfg: &AuthConfig, resolver: &Resolver, force_refresh: bool) -> BoxFuture<'_, OauthResult> {
|
||||||
&self,
|
let oc = OauthConfig::from_auth(cfg, resolver);
|
||||||
_cfg: &AuthConfig,
|
let col = self.col.clone().unwrap_or_default();
|
||||||
_resolver: &Resolver,
|
let key = oc.store_key(&col, self.env.as_deref());
|
||||||
_force_refresh: bool,
|
let app = self.app.clone();
|
||||||
) -> futures_util::future::BoxFuture<'_, OauthResult> {
|
let interactive = self.interactive;
|
||||||
|
let env = self.env.clone();
|
||||||
Box::pin(async move {
|
Box::pin(async move {
|
||||||
OauthResult {
|
let lock = app.state::<OauthState>().lock_for(&key);
|
||||||
steps: vec![Step::new("token", "Get token", StepStatus::Error, "OAuth 2.0 is not wired up yet")],
|
let _guard = lock.lock().await;
|
||||||
..Default::default()
|
let hooks = Hooks { app: app.clone(), key: key.clone(), interactive };
|
||||||
|
let res = oauth::obtain(&oc, &key, &hooks, force_refresh).await;
|
||||||
|
let ran_something = res.steps.iter().any(|s| s.exchange.is_some());
|
||||||
|
let flow_id = (interactive && ran_something).then(|| record_flow(&app, &key, &format!("{:?}", oc.grant), &res.steps, &res.warnings));
|
||||||
|
if res.tokens.is_some() {
|
||||||
|
remember_name(&app, &col, env.as_deref(), &oc.name, &key);
|
||||||
}
|
}
|
||||||
|
OauthResult { token: res.token, steps: res.steps, flow_id, warnings: res.warnings }
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub struct TokenLookup;
|
/// `{{oauth.<name>.access_token}}` and friends.
|
||||||
|
pub struct TokenLookup {
|
||||||
|
app: AppHandle,
|
||||||
|
col: String,
|
||||||
|
env: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
impl TokenLookup {
|
impl TokenLookup {
|
||||||
pub fn new(_state: &AppState, _c: &Collection, _env: Option<&str>) -> Self {
|
pub fn new(app: &AppHandle, c: &Collection, env: Option<&str>) -> Self {
|
||||||
Self
|
Self { app: app.clone(), col: c.manifest.id.clone(), env: env.map(str::to_string) }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl OauthLookup for TokenLookup {
|
impl OauthLookup for TokenLookup {
|
||||||
fn oauth_value(&self, _config: &str, _field: &str) -> Option<String> {
|
fn oauth_value(&self, config: &str, field: &str) -> Option<String> {
|
||||||
None
|
let state = self.app.state::<AppState>();
|
||||||
|
let key = {
|
||||||
|
let db = state.db.lock().unwrap();
|
||||||
|
db::kv_get(&db, &format!("oauth-name:{}:{}:{config}", self.col, self.env.as_deref().unwrap_or(""))).ok().flatten()?
|
||||||
|
};
|
||||||
|
let t = self.app.state::<OauthState>().load(&key)?;
|
||||||
|
match field {
|
||||||
|
"access_token" => Some(t.access_token),
|
||||||
|
"id_token" => t.id_token,
|
||||||
|
"refresh_token" => t.refresh_token,
|
||||||
|
"token_type" => t.token_type,
|
||||||
|
"scope" => t.scope,
|
||||||
|
_ => None,
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------- commands
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
pub struct OauthArgs {
|
||||||
|
#[serde(flatten)]
|
||||||
|
pub scope: ScopeArgs,
|
||||||
|
pub cfg: AuthConfig,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize)]
|
||||||
|
pub struct OauthStatus {
|
||||||
|
pub key: String,
|
||||||
|
pub redirect_uri: String,
|
||||||
|
pub token: Option<TokenSet>,
|
||||||
|
pub flows: Vec<FlowRecord>,
|
||||||
|
pub logout_url: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn resolve(app: &AppHandle, a: &OauthArgs) -> Result<(OauthConfig, String), String> {
|
||||||
|
let state = app.state::<AppState>();
|
||||||
|
let ctx = build_context(app, &state, &a.scope).map_err(|e| format!("{e:#}"))?;
|
||||||
|
let oc = OauthConfig::from_auth(&a.cfg, &ctx.resolver);
|
||||||
|
let key = oc.store_key(a.scope.col.as_deref().unwrap_or(""), a.scope.env.as_deref());
|
||||||
|
Ok((oc, key))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
pub fn oauth_status(app: AppHandle, args: OauthArgs) -> Result<OauthStatus, String> {
|
||||||
|
let (oc, key) = resolve(&app, &args)?;
|
||||||
|
let token = app.state::<OauthState>().load(&key);
|
||||||
|
let flows = {
|
||||||
|
let state = app.state::<AppState>();
|
||||||
|
let db = state.db.lock().unwrap();
|
||||||
|
db::kv_get(&db, &format!("flows:{key}")).ok().flatten().and_then(|s| serde_json::from_str(&s).ok()).unwrap_or_default()
|
||||||
|
};
|
||||||
|
let logout_url = oauth::logout_url(&oc, token.as_ref().and_then(|t| t.id_token.as_deref()));
|
||||||
|
Ok(OauthStatus { key, redirect_uri: oc.redirect_uri(), token, flows, logout_url })
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize)]
|
||||||
|
pub struct FlowOutcome {
|
||||||
|
pub steps: Vec<Step>,
|
||||||
|
pub warnings: Vec<String>,
|
||||||
|
pub ok: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
pub async fn oauth_run(app: AppHandle, args: OauthArgs, what: String) -> Result<FlowOutcome, String> {
|
||||||
|
let (oc, key) = resolve(&app, &args)?;
|
||||||
|
let lock = app.state::<OauthState>().lock_for(&key);
|
||||||
|
let _guard = lock.lock().await;
|
||||||
|
let hooks = Hooks { app: app.clone(), key: key.clone(), interactive: true };
|
||||||
|
let res = match what.as_str() {
|
||||||
|
"login" => {
|
||||||
|
hooks.delete_token(&key);
|
||||||
|
oauth::obtain(&oc, &key, &hooks, true).await
|
||||||
|
}
|
||||||
|
"test" => oauth::test_connection(&oc, &hooks).await,
|
||||||
|
"logout" => {
|
||||||
|
hooks.delete_token(&key);
|
||||||
|
oauth::FlowResult { steps: vec![Step::new("forget", "Forget token", StepStatus::Ok, "removed from the keyring")], ..Default::default() }
|
||||||
|
}
|
||||||
|
other => {
|
||||||
|
let action: Action = serde_json::from_value(serde_json::Value::String(other.into())).map_err(|_| format!("unknown action {other}"))?;
|
||||||
|
oauth::action(&oc, &key, &hooks, action).await
|
||||||
|
}
|
||||||
|
};
|
||||||
|
if res.tokens.is_some() {
|
||||||
|
remember_name(&app, args.scope.col.as_deref().unwrap_or(""), args.scope.env.as_deref(), &oc.name, &key);
|
||||||
|
}
|
||||||
|
record_flow(&app, &key, &what, &res.steps, &res.warnings);
|
||||||
|
let ok = !res.steps.iter().any(|s| s.status == StepStatus::Error);
|
||||||
|
Ok(FlowOutcome { steps: res.steps, warnings: res.warnings, ok })
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Custom-scheme callback (knock://callback?...) or a URL/code pasted by hand.
|
||||||
|
#[tauri::command]
|
||||||
|
pub fn oauth_callback(app: AppHandle, url: String) -> Result<bool, String> {
|
||||||
|
let tx = app.state::<OauthState>().pending.lock().unwrap().take();
|
||||||
|
match tx {
|
||||||
|
Some(tx) => Ok(tx.send(url).is_ok()),
|
||||||
|
None => Ok(false),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
pub fn oauth_deep_link(app: AppHandle, url: String) -> Result<bool, String> {
|
||||||
|
oauth_callback(app, url)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
pub fn oauth_cancel(app: AppHandle) {
|
||||||
|
app.state::<OauthState>().pending.lock().unwrap().take();
|
||||||
|
}
|
||||||
|
|||||||
@@ -14,7 +14,6 @@ pub struct StoredBody {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub struct AppState {
|
pub struct AppState {
|
||||||
pub data_dir: PathBuf,
|
|
||||||
pub collections: RwLock<HashMap<String, Collection>>,
|
pub collections: RwLock<HashMap<String, Collection>>,
|
||||||
pub engine: Arc<Engine>,
|
pub engine: Arc<Engine>,
|
||||||
pub db: Mutex<Connection>,
|
pub db: Mutex<Connection>,
|
||||||
@@ -33,7 +32,6 @@ impl AppState {
|
|||||||
let db = db::open(&data_dir.join("knock.db"))?;
|
let db = db::open(&data_dir.join("knock.db"))?;
|
||||||
Ok(Self {
|
Ok(Self {
|
||||||
engine: Arc::new(Engine::new(data_dir.join("responses"))),
|
engine: Arc::new(Engine::new(data_dir.join("responses"))),
|
||||||
data_dir,
|
|
||||||
collections: RwLock::default(),
|
collections: RwLock::default(),
|
||||||
db: Mutex::new(db),
|
db: Mutex::new(db),
|
||||||
runtime: Mutex::default(),
|
runtime: Mutex::default(),
|
||||||
|
|||||||
@@ -109,3 +109,38 @@ export function errorText(e: unknown): string {
|
|||||||
if (e instanceof Error) return e.message;
|
if (e instanceof Error) return e.message;
|
||||||
return JSON.stringify(e);
|
return JSON.stringify(e);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface TokenSet {
|
||||||
|
access_token: string;
|
||||||
|
refresh_token?: string | null;
|
||||||
|
id_token?: string | null;
|
||||||
|
token_type?: string | null;
|
||||||
|
scope?: string | null;
|
||||||
|
expires_at?: number | null;
|
||||||
|
obtained_at: number;
|
||||||
|
skew?: number | null;
|
||||||
|
}
|
||||||
|
export interface FlowRecord {
|
||||||
|
id: string;
|
||||||
|
at: string;
|
||||||
|
kind: string;
|
||||||
|
ok: boolean;
|
||||||
|
steps: import('./types').Step[];
|
||||||
|
warnings: string[];
|
||||||
|
}
|
||||||
|
export interface OauthStatus {
|
||||||
|
key: string;
|
||||||
|
redirect_uri: string;
|
||||||
|
token: TokenSet | null;
|
||||||
|
flows: FlowRecord[];
|
||||||
|
logout_url: string | null;
|
||||||
|
}
|
||||||
|
export type OauthArgs = ScopeArgs & { cfg: import('./types').AuthConfig };
|
||||||
|
|
||||||
|
export const oauthApi = {
|
||||||
|
status: (args: OauthArgs) => invoke<OauthStatus>('oauth_status', { args }),
|
||||||
|
run: (args: OauthArgs, what: 'login' | 'test' | 'logout' | 'refresh' | 'userinfo' | 'introspect' | 'revoke' | 'discovery') =>
|
||||||
|
invoke<{ steps: import('./types').Step[]; warnings: string[]; ok: boolean }>('oauth_run', { args, what }),
|
||||||
|
callback: (url: string) => invoke<boolean>('oauth_callback', { url }),
|
||||||
|
cancel: () => invoke<void>('oauth_cancel')
|
||||||
|
};
|
||||||
|
|||||||
@@ -11,8 +11,9 @@
|
|||||||
auth: Auth;
|
auth: Auth;
|
||||||
tab?: Tab;
|
tab?: Tab;
|
||||||
level: 'request' | 'folder' | 'collection';
|
level: 'request' | 'folder' | 'collection';
|
||||||
|
col?: string | null;
|
||||||
}
|
}
|
||||||
let { auth = $bindable(), tab, level }: Props = $props();
|
let { auth = $bindable(), tab, level, col = null }: Props = $props();
|
||||||
|
|
||||||
let kind = $derived(typeof auth === 'string' ? auth : auth.type);
|
let kind = $derived(typeof auth === 'string' ? auth : auth.type);
|
||||||
let cfg = $derived(typeof auth === 'object' ? auth : null);
|
let cfg = $derived(typeof auth === 'object' ? auth : null);
|
||||||
@@ -74,7 +75,7 @@
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
{#if cfg?.type === 'oauth2' || cfg?.type === 'oidc'}
|
{#if cfg?.type === 'oauth2' || cfg?.type === 'oidc'}
|
||||||
<OAuthConfig cfg={cfg} {tab} />
|
<OAuthConfig cfg={cfg} {tab} col={tab?.col ?? col} />
|
||||||
{:else if cfg}
|
{:else if cfg}
|
||||||
{#each fields.filter(fieldVisible) as f (f.key)}
|
{#each fields.filter(fieldVisible) as f (f.key)}
|
||||||
<div class="flex items-start gap-3">
|
<div class="flex items-start gap-3">
|
||||||
|
|||||||
@@ -1,8 +1,391 @@
|
|||||||
<script lang="ts">
|
<script lang="ts">
|
||||||
import type { AuthConfig } from '$lib/types';
|
import { onMount } from 'svelte';
|
||||||
import type { Tab } from '$lib/state/workspace.svelte';
|
import { listen } from '@tauri-apps/api/event';
|
||||||
|
import { openUrl } from '@tauri-apps/plugin-opener';
|
||||||
|
import { CopyButton, TagInput, Switch, toast } from '@joshicodes/cock';
|
||||||
|
import Icon from '$lib/ui/Icon.svelte';
|
||||||
|
import VarInput from '$lib/ui/VarInput.svelte';
|
||||||
|
import KeyValueTable from '$lib/ui/KeyValueTable.svelte';
|
||||||
|
import TokenInspector from './TokenInspector.svelte';
|
||||||
|
import AuthDebugView from './AuthDebugView.svelte';
|
||||||
|
import { oauthApi, errorText, type OauthStatus, type FlowRecord } from '$lib/api';
|
||||||
|
import { ws, type Tab } from '$lib/state/workspace.svelte';
|
||||||
|
import { newRequest } from '$lib/request';
|
||||||
|
import { plain } from '$lib/plain.svelte';
|
||||||
|
import type { AuthConfig, AuthDebug, Json, KeyValue, Step } from '$lib/types';
|
||||||
|
import { RelativeTime } from '@joshicodes/cock';
|
||||||
|
|
||||||
let { cfg, tab }: { cfg: AuthConfig; tab?: Tab } = $props();
|
let { cfg, tab, col }: { cfg: AuthConfig; tab?: Tab; col?: string | null } = $props();
|
||||||
void cfg;
|
|
||||||
void tab;
|
let colId = $derived(tab?.col ?? col ?? null);
|
||||||
|
let status = $state<OauthStatus | null>(null);
|
||||||
|
let busy = $state<string | null>(null);
|
||||||
|
let live = $state<Step[]>([]);
|
||||||
|
let lastRun = $state<{ steps: Step[]; warnings: string[] } | null>(null);
|
||||||
|
let device = $state<{ uri: string; code: string; complete: string | null } | null>(null);
|
||||||
|
let awaiting = $state(false);
|
||||||
|
let pasted = $state('');
|
||||||
|
let shownFlow = $state<FlowRecord | null>(null);
|
||||||
|
let discovered = $state<Record<string, string | string[]>>({});
|
||||||
|
|
||||||
|
const str = (k: string) => {
|
||||||
|
const v = cfg[k];
|
||||||
|
return v === undefined || v === null ? '' : String(v);
|
||||||
|
};
|
||||||
|
const set = (k: string, v: Json | undefined) => {
|
||||||
|
if (v === '' || v === undefined || v === null) delete cfg[k];
|
||||||
|
else cfg[k] = v;
|
||||||
|
};
|
||||||
|
|
||||||
|
function args() {
|
||||||
|
return {
|
||||||
|
col: colId,
|
||||||
|
request_id: tab?.id ?? null,
|
||||||
|
request: plain(tab?.draft ?? newRequest()),
|
||||||
|
env: ws.env(colId),
|
||||||
|
cfg: plain(cfg)
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
let timer: ReturnType<typeof setTimeout>;
|
||||||
|
async function refreshStatus() {
|
||||||
|
try {
|
||||||
|
status = await oauthApi.status(args());
|
||||||
|
} catch {
|
||||||
|
status = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
$effect(() => {
|
||||||
|
JSON.stringify(cfg);
|
||||||
|
ws.env(colId);
|
||||||
|
clearTimeout(timer);
|
||||||
|
timer = setTimeout(refreshStatus, 200);
|
||||||
|
});
|
||||||
|
|
||||||
|
onMount(() => {
|
||||||
|
const subs = [
|
||||||
|
listen<{ key: string; step: Step }>('oauth-progress', (e) => {
|
||||||
|
if (status && e.payload.key !== status.key) return;
|
||||||
|
const i = live.findIndex((s) => s.id === e.payload.step.id);
|
||||||
|
if (i >= 0) live[i] = e.payload.step;
|
||||||
|
else live.push(e.payload.step);
|
||||||
|
}),
|
||||||
|
listen<{ key: string; uri: string; code: string; complete: string | null }>('oauth-device', (e) => {
|
||||||
|
if (!status || e.payload.key === status.key) device = e.payload;
|
||||||
|
}),
|
||||||
|
listen<string>('oauth-awaiting', (e) => {
|
||||||
|
if (!status || e.payload === status.key) awaiting = true;
|
||||||
|
})
|
||||||
|
];
|
||||||
|
return () => subs.forEach((p) => p.then((f) => f()));
|
||||||
|
});
|
||||||
|
|
||||||
|
async function run(what: Parameters<typeof oauthApi.run>[1]) {
|
||||||
|
busy = what;
|
||||||
|
live = [];
|
||||||
|
device = null;
|
||||||
|
lastRun = null;
|
||||||
|
try {
|
||||||
|
const r = await oauthApi.run(args(), what);
|
||||||
|
lastRun = r;
|
||||||
|
if (what === 'discovery') {
|
||||||
|
const d = r.steps.find((s) => s.id === 'discovery')?.data;
|
||||||
|
if (d && typeof d === 'object' && !Array.isArray(d)) discovered = d as Record<string, string | string[]>;
|
||||||
|
}
|
||||||
|
if (r.ok && what === 'login') toast.success('Logged in');
|
||||||
|
} catch (e) {
|
||||||
|
toast.error('OAuth action failed', { description: errorText(e) });
|
||||||
|
} finally {
|
||||||
|
busy = null;
|
||||||
|
awaiting = false;
|
||||||
|
device = null;
|
||||||
|
refreshStatus();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function sendPasted() {
|
||||||
|
if (!pasted.trim()) return;
|
||||||
|
await oauthApi.callback(pasted.trim());
|
||||||
|
pasted = '';
|
||||||
|
awaiting = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
let grant = $derived(str('grant') || 'authorization_code');
|
||||||
|
let mode = $derived(str('redirect_mode') || 'loopback');
|
||||||
|
let scopes = $derived(str('scopes').split(/[\s,]+/).filter(Boolean));
|
||||||
|
let scopeSuggestions = $derived(((discovered.scopes_supported as string[]) ?? []).filter((s) => !scopes.includes(s)));
|
||||||
|
let redirect = $derived(status?.redirect_uri ?? '');
|
||||||
|
let isLocalhost = $derived(redirect.includes('//localhost'));
|
||||||
|
|
||||||
|
let authParams = $state<KeyValue[]>([]);
|
||||||
|
let tokenParams = $state<KeyValue[]>([]);
|
||||||
|
$effect(() => {
|
||||||
|
authParams = Object.entries((cfg.authorize_params as Record<string, string>) ?? {}).map(([name, value]) => ({ name, value: String(value) }));
|
||||||
|
tokenParams = Object.entries((cfg.token_params as Record<string, string>) ?? {}).map(([name, value]) => ({ name, value: String(value) }));
|
||||||
|
});
|
||||||
|
const toObj = (rows: KeyValue[]) => {
|
||||||
|
const o = Object.fromEntries(rows.filter((r) => r.name && r.enabled !== false).map((r) => [r.name, r.value]));
|
||||||
|
return Object.keys(o).length ? o : undefined;
|
||||||
|
};
|
||||||
|
|
||||||
|
let expiresIn = $derived(status?.token?.expires_at ? status.token.expires_at - Math.floor(Date.now() / 1000) : null);
|
||||||
|
let showAdvanced = $state(false);
|
||||||
|
|
||||||
|
const asDebug = (steps: Step[], warnings: string[]): AuthDebug => ({ kind: str('type'), origin: null, source: null, steps, sent: [], warnings, flow_id: null });
|
||||||
|
|
||||||
|
const disc = (k: string) => (typeof discovered[k] === 'string' ? (discovered[k] as string) : '');
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
|
{#snippet row(label: string, help?: string)}
|
||||||
|
<span class="w-36 shrink-0 pt-1.5 text-fg-muted" title={help}>{label}</span>
|
||||||
|
{/snippet}
|
||||||
|
|
||||||
|
{#snippet field(key: string, label: string, placeholder = '', secret = false, help = '')}
|
||||||
|
<div class="flex items-start gap-3">
|
||||||
|
{@render row(label)}
|
||||||
|
<div class="flex min-w-0 max-w-xl flex-1 flex-col gap-1">
|
||||||
|
<div class="flex rounded border border-line bg-input">
|
||||||
|
<VarInput value={str(key)} {placeholder} {secret} oninput={(v) => set(key, v)} />
|
||||||
|
</div>
|
||||||
|
{#if help}<span class="text-[11.5px] text-fg-subtle">{help}</span>{/if}
|
||||||
|
{#if secret && str(key) && !str(key).includes('{{')}
|
||||||
|
<span class="flex items-center gap-1 text-[11.5px] text-post"><Icon name="alert" size={11} />Stored in the request file. Use <code class="mono">{`{{secret.${key}}}`}</code> instead.</span>
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{/snippet}
|
||||||
|
|
||||||
|
<div class="flex flex-col gap-4">
|
||||||
|
{#if grant === 'authorization_code'}
|
||||||
|
<div class="rounded border border-cyan-deep/60 bg-input px-3 py-2.5">
|
||||||
|
<div class="flex items-center gap-2">
|
||||||
|
<span class="k-label">Redirect URI</span>
|
||||||
|
<span class="flex-1"></span>
|
||||||
|
<select class="k-field !w-auto !py-0.5 !font-sans text-[12px]" value={mode} onchange={(e) => set('redirect_mode', (e.currentTarget as HTMLSelectElement).value === 'loopback' ? undefined : (e.currentTarget as HTMLSelectElement).value)}>
|
||||||
|
<option value="loopback">Loopback (127.0.0.1)</option>
|
||||||
|
<option value="custom_scheme">knock:// link</option>
|
||||||
|
<option value="manual">Paste by hand</option>
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
{#if mode === 'manual'}
|
||||||
|
<div class="mt-1.5 flex rounded border border-line bg-panel">
|
||||||
|
<VarInput value={str('redirect_uri')} placeholder="https://your-app.example.com/oauth/callback" oninput={(v) => set('redirect_uri', v)} />
|
||||||
|
</div>
|
||||||
|
<p class="mt-1.5 text-[12px] text-fg-muted">The provider redirects to this page. Copy the URL from the browser (or the code it shows) into knock when asked.</p>
|
||||||
|
{:else}
|
||||||
|
<div class="mt-1 flex items-center gap-2">
|
||||||
|
<code class="mono selectable min-w-0 flex-1 break-all text-[14px] text-strong">{redirect}</code>
|
||||||
|
<CopyButton value={redirect} size="sm" />
|
||||||
|
</div>
|
||||||
|
<p class="mt-1.5 text-[12px] text-fg-muted">Register exactly this URL at the provider as an allowed redirect URI.</p>
|
||||||
|
{#if isLocalhost}
|
||||||
|
<p class="mt-1 flex items-center gap-1.5 text-[12px] text-post"><Icon name="alert" size={12} />localhost and 127.0.0.1 are different URLs for most providers. 127.0.0.1 is recommended.</p>
|
||||||
|
{/if}
|
||||||
|
{#if mode === 'loopback'}
|
||||||
|
<div class="mt-2 flex items-center gap-2 text-[12px]">
|
||||||
|
<span class="text-fg-muted">Port</span>
|
||||||
|
<input class="k-field mono !w-24 !border-line !bg-panel" value={str('redirect_port') || '53127'} oninput={(e) => set('redirect_port', Number((e.currentTarget as HTMLInputElement).value) || undefined)} />
|
||||||
|
<span class="text-fg-muted">Host</span>
|
||||||
|
<select class="k-field !w-auto !border-line !bg-panel !font-sans" value={str('redirect_host') || '127.0.0.1'} onchange={(e) => set('redirect_host', (e.currentTarget as HTMLSelectElement).value === '127.0.0.1' ? undefined : 'localhost')}>
|
||||||
|
<option>127.0.0.1</option>
|
||||||
|
<option>localhost</option>
|
||||||
|
</select>
|
||||||
|
<span class="text-fg-muted">Path</span>
|
||||||
|
<input class="k-field mono !w-32 !border-line !bg-panel" value={str('redirect_path') || '/callback'} oninput={(e) => set('redirect_path', (e.currentTarget as HTMLInputElement).value === '/callback' ? undefined : (e.currentTarget as HTMLInputElement).value)} />
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
|
||||||
|
<div class="flex items-start gap-3">
|
||||||
|
{@render row('Grant')}
|
||||||
|
<select class="k-field !w-72 !border-line !bg-input !font-sans" value={grant} onchange={(e) => set('grant', (e.currentTarget as HTMLSelectElement).value === 'authorization_code' ? undefined : (e.currentTarget as HTMLSelectElement).value)}>
|
||||||
|
<option value="authorization_code">Authorization code + PKCE</option>
|
||||||
|
<option value="client_credentials">Client credentials</option>
|
||||||
|
<option value="device_code">Device code</option>
|
||||||
|
<option value="password">Password (deprecated)</option>
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="flex items-start gap-3">
|
||||||
|
{@render row('Issuer')}
|
||||||
|
<div class="flex min-w-0 max-w-xl flex-1 flex-col gap-1">
|
||||||
|
<div class="flex gap-2">
|
||||||
|
<div class="flex min-w-0 flex-1 rounded border border-line bg-input">
|
||||||
|
<VarInput value={str('issuer')} placeholder="https://sso.example.com/realms/main" oninput={(v) => set('issuer', v)} />
|
||||||
|
</div>
|
||||||
|
<button class="rounded border border-line px-3 text-[12px] hover:border-border-strong disabled:opacity-40" disabled={!str('issuer') || !!busy} onclick={() => run('discovery')}>{busy === 'discovery' ? 'Discovering…' : 'Discover'}</button>
|
||||||
|
</div>
|
||||||
|
<span class="text-[11.5px] text-fg-subtle">Endpoints, scopes and PKCE support come from /.well-known/openid-configuration. Leave empty to enter endpoints by hand.</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{@render field('client_id', 'Client ID')}
|
||||||
|
{#if str('client_auth') !== 'none'}
|
||||||
|
{@render field('client_secret', 'Client secret', '{{secret.clientSecret}}', true)}
|
||||||
|
{/if}
|
||||||
|
<div class="flex items-start gap-3">
|
||||||
|
{@render row('Client auth')}
|
||||||
|
<select class="k-field !w-72 !border-line !bg-input !font-sans" value={str('client_auth') || 'basic'} onchange={(e) => set('client_auth', (e.currentTarget as HTMLSelectElement).value === 'basic' ? undefined : (e.currentTarget as HTMLSelectElement).value)}>
|
||||||
|
<option value="basic">client_secret_basic (header)</option>
|
||||||
|
<option value="post">client_secret_post (body)</option>
|
||||||
|
<option value="none">none (public client)</option>
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="flex items-start gap-3">
|
||||||
|
{@render row('Scopes')}
|
||||||
|
<div class="flex min-w-0 max-w-xl flex-1 flex-col gap-1.5">
|
||||||
|
<TagInput value={scopes} placeholder="Add a scope…" onchange={(tags) => set('scopes', tags.join(' '))} />
|
||||||
|
{#if scopeSuggestions.length}
|
||||||
|
<div class="flex flex-wrap gap-1">
|
||||||
|
{#each scopeSuggestions.slice(0, 16) as s}
|
||||||
|
<button class="mono rounded border border-dashed border-line px-1.5 py-0.5 text-[11px] text-fg-muted hover:border-border-strong hover:text-fg" onclick={() => set('scopes', [...scopes, s].join(' '))}>+ {s}</button>
|
||||||
|
{/each}
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{#if grant === 'password'}
|
||||||
|
{@render field('username', 'Username')}
|
||||||
|
{@render field('password', 'Password', '{{secret.password}}', true)}
|
||||||
|
<p class="-mt-2 ml-[156px] text-[12px] text-post">The password grant is deprecated in OAuth 2.1. Use it only where nothing else works.</p>
|
||||||
|
{/if}
|
||||||
|
|
||||||
|
{#if !str('issuer') || showAdvanced}
|
||||||
|
{#each [['authorize_url', 'Authorize URL', 'authorization_endpoint'], ['token_url', 'Token URL', 'token_endpoint'], ['device_url', 'Device URL', 'device_authorization_endpoint'], ['userinfo_url', 'UserInfo URL', 'userinfo_endpoint'], ['jwks_url', 'JWKS URL', 'jwks_uri'], ['introspection_url', 'Introspection URL', 'introspection_endpoint'], ['revocation_url', 'Revocation URL', 'revocation_endpoint'], ['end_session_url', 'Logout URL', 'end_session_endpoint']] as [k, label, d]}
|
||||||
|
{#if (k !== 'authorize_url' || grant === 'authorization_code') && (k !== 'device_url' || grant === 'device_code')}
|
||||||
|
{@render field(k, label, disc(d) || (str('issuer') ? 'from discovery' : ''))}
|
||||||
|
{/if}
|
||||||
|
{/each}
|
||||||
|
{/if}
|
||||||
|
|
||||||
|
<button class="ml-[156px] flex w-fit items-center gap-1 text-[12px] text-fg-muted hover:text-fg" onclick={() => (showAdvanced = !showAdvanced)}>
|
||||||
|
<Icon name={showAdvanced ? 'chevron-down' : 'chevron-right'} size={11} />More settings
|
||||||
|
</button>
|
||||||
|
|
||||||
|
{#if showAdvanced}
|
||||||
|
{@render field('audience', 'Audience', '', false, 'Sent as audience= (Auth0, some gateways)')}
|
||||||
|
{@render field('resource', 'Resource', '', false, 'RFC 8707 resource indicator')}
|
||||||
|
{#if grant === 'authorization_code'}
|
||||||
|
<div class="flex items-center gap-3">
|
||||||
|
{@render row('PKCE (S256)')}
|
||||||
|
<Switch checked={cfg.pkce !== false} onchange={(v) => set('pkce', v ? undefined : false)} aria-label="PKCE" />
|
||||||
|
</div>
|
||||||
|
<div class="flex items-start gap-3">
|
||||||
|
{@render row('Login parameters', 'prompt, login_hint, acr_values, …')}
|
||||||
|
<div class="min-w-0 max-w-xl flex-1"><KeyValueTable bind:rows={authParams} namePlaceholder="prompt" valuePlaceholder="login" onchange={() => set('authorize_params', toObj(authParams))} /></div>
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
<div class="flex items-start gap-3">
|
||||||
|
{@render row('Token parameters')}
|
||||||
|
<div class="min-w-0 max-w-xl flex-1"><KeyValueTable bind:rows={tokenParams} onchange={() => set('token_params', toObj(tokenParams))} /></div>
|
||||||
|
</div>
|
||||||
|
<div class="flex items-start gap-3">
|
||||||
|
{@render row('Send token')}
|
||||||
|
<div class="flex flex-wrap items-center gap-2">
|
||||||
|
<select class="k-field !w-auto !border-line !bg-input !font-sans" value={str('token_use') || 'access_token'} onchange={(e) => set('token_use', (e.currentTarget as HTMLSelectElement).value === 'access_token' ? undefined : 'id_token')}>
|
||||||
|
<option value="access_token">Access token</option>
|
||||||
|
<option value="id_token">ID token</option>
|
||||||
|
</select>
|
||||||
|
<span class="text-fg-subtle">as</span>
|
||||||
|
<select class="k-field !w-auto !border-line !bg-input !font-sans" value={str('token_placement') || 'header'} onchange={(e) => set('token_placement', (e.currentTarget as HTMLSelectElement).value === 'header' ? undefined : (e.currentTarget as HTMLSelectElement).value)}>
|
||||||
|
<option value="header">Header</option>
|
||||||
|
<option value="query">Query parameter</option>
|
||||||
|
<option value="body">Body field</option>
|
||||||
|
</select>
|
||||||
|
<input class="k-field mono !w-36 !border-line !bg-input" placeholder={str('token_placement') === 'header' || !str('token_placement') ? 'Authorization' : 'access_token'} value={str('token_name')} oninput={(e) => set('token_name', (e.currentTarget as HTMLInputElement).value)} />
|
||||||
|
{#if !str('token_placement') || str('token_placement') === 'header'}
|
||||||
|
<input class="k-field mono !w-24 !border-line !bg-input" placeholder="Bearer" value={str('token_prefix')} oninput={(e) => set('token_prefix', (e.currentTarget as HTMLInputElement).value)} />
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{@render field('name', 'Share as', 'default', false, `Other requests can use {{oauth.${str('name') || 'default'}.access_token}}`)}
|
||||||
|
<div class="flex items-center gap-3">
|
||||||
|
{@render row('Auto refresh')}
|
||||||
|
<Switch checked={cfg.auto_refresh !== false} onchange={(v) => set('auto_refresh', v ? undefined : false)} aria-label="Auto refresh" />
|
||||||
|
</div>
|
||||||
|
<div class="flex items-center gap-3">
|
||||||
|
{@render row('Verify TLS')}
|
||||||
|
<Switch checked={cfg.verify_tls !== false} onchange={(v) => set('verify_tls', v ? undefined : false)} aria-label="Verify TLS" />
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
|
||||||
|
<!-- Token status and actions -->
|
||||||
|
<div class="mt-2 rounded border border-line">
|
||||||
|
<div class="flex flex-wrap items-center gap-2 border-b border-line px-3 py-2">
|
||||||
|
<span class="k-label mr-1">Token</span>
|
||||||
|
{#if status?.token}
|
||||||
|
<span class="text-[12px] {expiresIn !== null && expiresIn < 30 ? 'text-delete' : 'text-ok'}">
|
||||||
|
{expiresIn === null ? 'no expiry' : expiresIn > 0 ? `valid, expires in ${expiresIn < 120 ? expiresIn + ' s' : Math.round(expiresIn / 60) + ' min'}` : 'expired'}
|
||||||
|
</span>
|
||||||
|
{#if status.token.refresh_token}<span class="text-[12px] text-fg-subtle">· refresh token stored</span>{/if}
|
||||||
|
<span class="text-[12px] text-fg-subtle">· {ws.env(colId) ? `environment ${ws.env(colId)}` : 'no environment'}</span>
|
||||||
|
{:else}
|
||||||
|
<span class="text-[12px] text-fg-subtle">none stored for this environment</span>
|
||||||
|
{/if}
|
||||||
|
<span class="flex-1"></span>
|
||||||
|
<button class="rounded bg-accent px-3 py-1 text-[12px] font-bold text-accent-fg hover:bg-accent-hover disabled:opacity-40" disabled={!!busy} onclick={() => run('login')}>
|
||||||
|
{busy === 'login' ? 'Logging in…' : status?.token ? 'Log in again' : grant === 'client_credentials' ? 'Get token' : 'Log in'}
|
||||||
|
</button>
|
||||||
|
<button class="rounded border border-line px-2.5 py-1 text-[12px] hover:border-border-strong disabled:opacity-40" disabled={!!busy} onclick={() => run('test')}>Test connection</button>
|
||||||
|
</div>
|
||||||
|
{#if status?.token}
|
||||||
|
<div class="flex flex-wrap gap-1.5 border-b border-line px-3 py-2">
|
||||||
|
{#each [['refresh', 'Refresh'], ['userinfo', 'UserInfo'], ['introspect', 'Introspect'], ['revoke', 'Revoke'], ['logout', 'Forget token']] as [what, label]}
|
||||||
|
<button class="rounded px-2 py-0.5 text-[12px] text-fg-muted hover:bg-hover hover:text-fg disabled:opacity-40" disabled={!!busy} onclick={() => run(what as Parameters<typeof oauthApi.run>[1])}>{label}</button>
|
||||||
|
{/each}
|
||||||
|
{#if status.logout_url}
|
||||||
|
<button class="rounded px-2 py-0.5 text-[12px] text-fg-muted hover:bg-hover hover:text-fg" onclick={() => openUrl(status!.logout_url!)}>Log out at provider</button>
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
|
<div class="flex flex-col gap-2 p-3">
|
||||||
|
<TokenInspector name="access_token" token={status.token.access_token} skew={status.token.skew ?? null} scopes={scopes} audience={str('audience') || undefined} />
|
||||||
|
{#if status.token.id_token}<TokenInspector name="id_token" token={status.token.id_token} skew={status.token.skew ?? null} />{/if}
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
|
||||||
|
{#if device}
|
||||||
|
<div class="border-b border-line bg-input px-4 py-4 text-center">
|
||||||
|
<p class="text-fg-muted">Open <button class="text-accent hover:underline" onclick={() => openUrl(device!.complete ?? device!.uri)}>{device.uri}</button> and enter</p>
|
||||||
|
<p class="mono mt-2 text-[28px] font-bold tracking-[0.2em] text-strong">{device.code}</p>
|
||||||
|
<p class="mt-1 text-[12px] text-fg-subtle">knock is waiting in the background.</p>
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
{#if awaiting && mode !== 'loopback'}
|
||||||
|
<div class="flex flex-col gap-2 border-b border-line bg-input px-3 py-3">
|
||||||
|
<span class="text-[12px] text-fg">{mode === 'manual' ? 'Paste the URL of the page you landed on, or just the code:' : 'Waiting for the knock:// link. If the browser does not hand it over, paste the URL here:'}</span>
|
||||||
|
<div class="flex gap-2">
|
||||||
|
<input class="k-field mono flex-1 !border-line !bg-panel" bind:value={pasted} placeholder="https://…?code=…&state=…" onkeydown={(e) => e.key === 'Enter' && sendPasted()} />
|
||||||
|
<button class="rounded bg-accent px-3 text-[12px] font-bold text-accent-fg" onclick={sendPasted}>Continue</button>
|
||||||
|
<button class="px-2 text-[12px] text-fg-muted hover:text-fg" onclick={() => oauthApi.cancel()}>Cancel</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
|
||||||
|
{#if busy && live.length}
|
||||||
|
<div class="max-h-96 overflow-auto"><AuthDebugView debug={asDebug(live, [])} /></div>
|
||||||
|
{:else if lastRun && !shownFlow}
|
||||||
|
<div class="max-h-[32rem] overflow-auto"><AuthDebugView debug={asDebug(lastRun.steps, lastRun.warnings)} /></div>
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{#if status?.flows.length}
|
||||||
|
<div>
|
||||||
|
<div class="k-label mb-1.5">Last flows <span class="font-normal normal-case tracking-normal text-fg-subtle">(stored with secrets masked)</span></div>
|
||||||
|
{#each status.flows as fl (fl.id)}
|
||||||
|
<button class="flex w-full items-center gap-3 border-b border-line/60 py-1.5 text-left text-[12px] hover:bg-hover/40 {shownFlow?.id === fl.id ? 'bg-hover/50' : ''}" onclick={() => (shownFlow = shownFlow?.id === fl.id ? null : fl)}>
|
||||||
|
<Icon name={fl.ok ? 'check' : 'x'} size={12} class={fl.ok ? 'text-ok' : 'text-delete'} />
|
||||||
|
<span class="w-40 text-fg">{fl.kind.replace(/_/g, ' ')}</span>
|
||||||
|
<span class="min-w-0 flex-1 truncate text-fg-muted">{fl.steps.find((s) => s.status === 'error')?.summary ?? fl.steps.at(-1)?.summary ?? ''}</span>
|
||||||
|
<span class="text-fg-subtle"><RelativeTime date={fl.at} format="short" /></span>
|
||||||
|
</button>
|
||||||
|
{#if shownFlow?.id === fl.id}
|
||||||
|
<div class="max-h-[32rem] overflow-auto border-b border-line"><AuthDebugView debug={asDebug(fl.steps, fl.warnings)} /></div>
|
||||||
|
{/if}
|
||||||
|
{/each}
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
|
|||||||
@@ -81,7 +81,7 @@
|
|||||||
<section>
|
<section>
|
||||||
<h2 class="k-label mb-2">Auth</h2>
|
<h2 class="k-label mb-2">Auth</h2>
|
||||||
<p class="mb-2 text-[12px] text-fg-subtle">Default for every request that inherits.</p>
|
<p class="mb-2 text-[12px] text-fg-subtle">Default for every request that inherits.</p>
|
||||||
<div class="rounded border border-line"><AuthPanel bind:auth={m.auth!} level="collection" /></div>
|
<div class="rounded border border-line"><AuthPanel bind:auth={m.auth!} level="collection" {col} /></div>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
<section>
|
<section>
|
||||||
|
|||||||
@@ -67,7 +67,7 @@
|
|||||||
<section>
|
<section>
|
||||||
<h2 class="k-label mb-2">Auth</h2>
|
<h2 class="k-label mb-2">Auth</h2>
|
||||||
<p class="mb-2 text-[12px] text-fg-subtle">Requests in this folder that use "inherit" get this auth.</p>
|
<p class="mb-2 text-[12px] text-fg-subtle">Requests in this folder that use "inherit" get this auth.</p>
|
||||||
<div class="rounded border border-line"><AuthPanel bind:auth={meta.auth!} level="folder" /></div>
|
<div class="rounded border border-line"><AuthPanel bind:auth={meta.auth!} level="folder" {col} /></div>
|
||||||
</section>
|
</section>
|
||||||
<section>
|
<section>
|
||||||
<h2 class="k-label mb-2">Headers</h2>
|
<h2 class="k-label mb-2">Headers</h2>
|
||||||
|
|||||||
Reference in New Issue
Block a user