about summary refs log tree commit diff
path: root/kittybox-rs/indieauth/src/pkce.rs
blob: a0bc2915f24e9f5ac9bbd2d589a1f2e0755511e4 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
use serde::{Serialize, Deserialize};
use rand::{Rng, distributions::Alphanumeric};
use sha2::{Sha256, Digest};
use data_encoding::BASE64URL;

#[derive(PartialEq, Eq, Copy, Clone, Debug, Serialize, Deserialize)]
pub enum PKCEMethod {
    S256,
    Plain
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PKCEVerifier(String);

impl AsRef<str> for PKCEVerifier {
    fn as_ref(&self) -> &str {
        self.0.as_str()
    }
}
impl ToString for PKCEVerifier {
    fn to_string(&self) -> String {
        self.0.clone()
    }
}

impl PKCEVerifier {
    fn new() -> Self {
        let bytes = rand::thread_rng()
            .sample_iter(&Alphanumeric)
            .take(128)
            .collect::<Vec<u8>>();
        Self(String::from_utf8(bytes).unwrap())
    }
}

#[derive(Eq, PartialEq, Debug, Clone, Serialize, Deserialize)]
pub struct PKCEChallenge {
    code_challenge: String,
    method: PKCEMethod
}

impl PKCEChallenge {
    fn new(code_verifier: PKCEVerifier, method: PKCEMethod) -> Self {
        Self {
            code_challenge: match method {
                PKCEMethod::S256 => {
                    let mut hasher = Sha256::new();
                    hasher.update(code_verifier.as_ref());
                    BASE64URL.encode(&hasher.finalize())
                },
                PKCEMethod::Plain => code_verifier.to_string(),
            },
            method
        }
    }
    fn verify(&self, code_verifier: PKCEVerifier) -> bool {
        Self::new(code_verifier, self.method) == *self
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_pkce() {
        let verifier = PKCEVerifier::new();
        let challenge = PKCEChallenge::new(verifier.clone(), PKCEMethod::S256);

        assert!(challenge.verify(verifier));
    }

}