Merge pull request 'auth: fully percent-decode redirect code' (#125) from mcp-oauth-decode into main

This commit was merged in pull request #125.
This commit is contained in:
hermes committed 2026-10-06 10:57:15 +00:00
commit 15ccdc2697
1 file changed
+35 -5
+35 -5
View File
@@ -253,6 +253,31 @@ pub async fn refresh(k: Kind, cred: &Credential) -> Result<Credential> {
Ok(c)
}
/// Percent-decode `%XX` (UTF-8, invalid escapes kept as-is); `+` stays `+` (codes may contain it).
pub fn urldec(s: &str) -> String {
let b = s.as_bytes();
let mut out = Vec::with_capacity(b.len());
let mut i = 0;
while i < b.len() {
let hex = |c: u8| (c as char).to_digit(16);
match (
b[i],
b.get(i + 1).and_then(|&c| hex(c)),
b.get(i + 2).and_then(|&c| hex(c)),
) {
(b'%', Some(h), Some(l)) => {
out.push((h * 16 + l) as u8);
i += 3;
}
(c, ..) => {
out.push(c);
i += 1;
}
}
}
String::from_utf8_lossy(&out).into_owned()
}
/// Accepts a full redirect URL, `code#state`, a query string, or a bare code.
pub fn parse_code(input: &str) -> (Option<String>, Option<String>) {
let v = input.trim();
@@ -261,11 +286,7 @@ pub fn parse_code(input: &str) -> (Option<String>, Option<String>) {
let get = |key: &str| {
q.split(['&', '#'])
.find_map(|kv| kv.strip_prefix(&format!("{key}=")))
.map(|s| {
s.replace("%2B", "+")
.replace("%2F", "/")
.replace("%3D", "=")
})
.map(urldec)
};
return (get("code"), get("state"));
}
@@ -470,6 +491,15 @@ mod tests {
assert_eq!(parse_code(""), (None, None));
}
#[test]
fn code_is_fully_decoded() {
assert_eq!(
parse_code("/callback?code=a%3Ab%2Fc%2Bd+e%25&state=s%3D"),
(Some("a:b/c+d+e%".into()), Some("s=".into()))
);
assert_eq!(urldec("100%"), "100%");
}
#[test]
fn jwt_account() {
let p = URL_SAFE_NO_PAD