adk_auth/sso/
algorithm.rs1use std::fmt;
4use std::str::FromStr;
5
6use super::TokenError;
7
8#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
33#[non_exhaustive]
34pub enum JwtAlgorithm {
35 RS256,
37 RS384,
39 RS512,
41 PS256,
43 PS384,
45 PS512,
47 ES256,
49 ES384,
51}
52
53impl JwtAlgorithm {
54 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 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}