Skip to main content

adk_auth/sso/
algorithm.rs

1//! The JWS algorithms a JWKS validator accepts.
2
3use std::fmt;
4use std::str::FromStr;
5
6use super::TokenError;
7
8/// A JWS signature algorithm that [`JwtValidator`](super::JwtValidator) can verify against
9/// the public keys of a JWKS.
10///
11/// Only asymmetric RSA and EC algorithms are listed: a symmetric algorithm (`HS256`, ...)
12/// would verify with a secret anyone can read from the JWKS, so it cannot be expressed, and
13/// `none` is never accepted. The enum is ADK-owned, so a new major release of the JWT
14/// library underneath does not change this API.
15///
16/// # Example
17///
18/// ```rust
19/// use adk_auth::sso::{JwtAlgorithm, JwtValidator};
20///
21/// let validator = JwtValidator::builder()
22///     .issuer("https://issuer.example.com")
23///     .audience("https://api.example.com")
24///     .jwks_uri("https://issuer.example.com/.well-known/jwks.json")
25///     .algorithm(JwtAlgorithm::RS256)
26///     .algorithm("ES256".parse::<JwtAlgorithm>()?)
27///     .build()?;
28///
29/// assert!("HS256".parse::<JwtAlgorithm>().is_err());
30/// # Ok::<(), adk_auth::sso::TokenError>(())
31/// ```
32#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
33#[non_exhaustive]
34pub enum JwtAlgorithm {
35    /// RSASSA-PKCS1-v1_5 with SHA-256.
36    RS256,
37    /// RSASSA-PKCS1-v1_5 with SHA-384.
38    RS384,
39    /// RSASSA-PKCS1-v1_5 with SHA-512.
40    RS512,
41    /// RSASSA-PSS with SHA-256.
42    PS256,
43    /// RSASSA-PSS with SHA-384.
44    PS384,
45    /// RSASSA-PSS with SHA-512.
46    PS512,
47    /// ECDSA on P-256 with SHA-256.
48    ES256,
49    /// ECDSA on P-384 with SHA-384.
50    ES384,
51}
52
53impl JwtAlgorithm {
54    /// The algorithm's JWS name, as it appears in a token's `alg` header.
55    ///
56    /// # Example
57    ///
58    /// ```rust
59    /// use adk_auth::sso::JwtAlgorithm;
60    ///
61    /// assert_eq!(JwtAlgorithm::PS256.as_str(), "PS256");
62    /// ```
63    pub fn as_str(self) -> &'static str {
64        match self {
65            Self::RS256 => "RS256",
66            Self::RS384 => "RS384",
67            Self::RS512 => "RS512",
68            Self::PS256 => "PS256",
69            Self::PS384 => "PS384",
70            Self::PS512 => "PS512",
71            Self::ES256 => "ES256",
72            Self::ES384 => "ES384",
73        }
74    }
75
76    pub(crate) fn to_jsonwebtoken(self) -> jsonwebtoken::Algorithm {
77        match self {
78            Self::RS256 => jsonwebtoken::Algorithm::RS256,
79            Self::RS384 => jsonwebtoken::Algorithm::RS384,
80            Self::RS512 => jsonwebtoken::Algorithm::RS512,
81            Self::PS256 => jsonwebtoken::Algorithm::PS256,
82            Self::PS384 => jsonwebtoken::Algorithm::PS384,
83            Self::PS512 => jsonwebtoken::Algorithm::PS512,
84            Self::ES256 => jsonwebtoken::Algorithm::ES256,
85            Self::ES384 => jsonwebtoken::Algorithm::ES384,
86        }
87    }
88}
89
90impl fmt::Display for JwtAlgorithm {
91    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
92        f.write_str(self.as_str())
93    }
94}
95
96impl FromStr for JwtAlgorithm {
97    type Err = TokenError;
98
99    /// Parses a JWS algorithm name, matching case exactly as JWS does.
100    ///
101    /// # Errors
102    ///
103    /// Returns [`TokenError::UnsupportedAlgorithm`] for a symmetric algorithm, `none`, EdDSA,
104    /// or any name that is not an RSA or EC algorithm listed above.
105    fn from_str(name: &str) -> Result<Self, Self::Err> {
106        match name {
107            "RS256" => Ok(Self::RS256),
108            "RS384" => Ok(Self::RS384),
109            "RS512" => Ok(Self::RS512),
110            "PS256" => Ok(Self::PS256),
111            "PS384" => Ok(Self::PS384),
112            "PS512" => Ok(Self::PS512),
113            "ES256" => Ok(Self::ES256),
114            "ES384" => Ok(Self::ES384),
115            other => Err(TokenError::UnsupportedAlgorithm(format!(
116                "'{other}' cannot be verified against a JWKS. Use one of RS256, RS384, RS512, PS256, PS384, PS512, ES256 or ES384."
117            ))),
118        }
119    }
120}
121
122#[cfg(test)]
123mod tests {
124    use super::JwtAlgorithm;
125    use crate::sso::TokenError;
126
127    const ALL: [JwtAlgorithm; 8] = [
128        JwtAlgorithm::RS256,
129        JwtAlgorithm::RS384,
130        JwtAlgorithm::RS512,
131        JwtAlgorithm::PS256,
132        JwtAlgorithm::PS384,
133        JwtAlgorithm::PS512,
134        JwtAlgorithm::ES256,
135        JwtAlgorithm::ES384,
136    ];
137
138    #[test]
139    fn every_algorithm_round_trips_through_its_jws_name() {
140        for algorithm in ALL {
141            assert_eq!(algorithm.as_str().parse::<JwtAlgorithm>().unwrap(), algorithm);
142            assert_eq!(algorithm.to_string(), algorithm.as_str());
143            assert_eq!(format!("{:?}", algorithm.to_jsonwebtoken()), algorithm.as_str());
144        }
145    }
146
147    #[test]
148    fn symmetric_none_and_unknown_names_are_refused() {
149        for name in ["HS256", "HS384", "HS512", "none", "None", "EdDSA", "rs256", ""] {
150            let refused = name.parse::<JwtAlgorithm>();
151            assert!(matches!(&refused, Err(TokenError::UnsupportedAlgorithm(_))), "{name}");
152        }
153    }
154}