tuwunel_core/config/
jwt.rs1use super::JwtConfig;
9use crate::{
10 Err, Error, Result, err, implement,
11 jwt::{Algorithm, DecodingKey, EncodingKey, errors::Error as JwtError},
12};
13
14#[derive(Clone, Copy)]
15pub(super) enum KeyFormat {
16 Hmac,
17 B64Hmac,
18 Ecdsa,
19 Eddsa,
20}
21
22const KEY_FORMATS: [(&str, KeyFormat); 5] = [
27 ("HMAC", KeyFormat::Hmac),
28 ("B64HMAC", KeyFormat::B64Hmac),
29 ("HMACB64", KeyFormat::B64Hmac),
30 ("ECDSA", KeyFormat::Ecdsa),
31 ("EDDSA", KeyFormat::Eddsa),
32];
33
34#[implement(JwtConfig)]
39pub fn decoding_key(&self) -> Result<DecodingKey> {
40 let key = self.nonempty_key()?;
41
42 match self.key_format()? {
43 | KeyFormat::Hmac => Ok(DecodingKey::from_secret(key.as_bytes())),
44 | KeyFormat::B64Hmac =>
45 DecodingKey::from_base64_secret(key).map_err(invalid_key("base64")),
46 | KeyFormat::Ecdsa =>
47 DecodingKey::from_ec_pem(key.as_bytes()).map_err(invalid_key("ECDSA PEM")),
48 | KeyFormat::Eddsa =>
49 DecodingKey::from_ed_pem(key.as_bytes()).map_err(invalid_key("EDDSA PEM")),
50 }
51}
52
53#[implement(JwtConfig)]
58pub(super) fn nonempty_key(&self) -> Result<&str> {
59 if self.key.is_empty() {
60 return Err!(Config(
61 "jwt.key",
62 "JWT key is empty; set the shared secret or public key that verifies tokens."
63 ));
64 }
65
66 Ok(self.key.as_str())
67}
68
69#[implement(JwtConfig)]
74pub fn encoding_key(&self) -> Result<EncodingKey> {
75 let key = self.nonempty_key()?;
76 let format = self.format.as_str();
77
78 match self.key_format()? {
79 | KeyFormat::Hmac => Ok(EncodingKey::from_secret(key.as_bytes())),
80 | KeyFormat::B64Hmac =>
81 EncodingKey::from_base64_secret(key).map_err(invalid_key("base64")),
82 | KeyFormat::Ecdsa | KeyFormat::Eddsa => Err!(Config(
83 "jwt.format",
84 "An {format} key is a public key; signing needs the HMAC or B64HMAC format."
85 )),
86 }
87}
88
89#[implement(JwtConfig)]
94pub fn algorithm(&self) -> Result<Algorithm> {
95 let algorithm = self.algorithm.as_str();
96
97 algorithm.parse().map_err(|e| {
98 err!(Config("jwt.algorithm", "JWT algorithm {algorithm:?} is not recognized: {e}"))
99 })
100}
101
102#[implement(JwtConfig)]
103pub(super) fn key_format(&self) -> Result<KeyFormat> {
104 let format = self.format.as_str();
105
106 KEY_FORMATS
107 .iter()
108 .find(|(name, _)| name.eq_ignore_ascii_case(format))
109 .map(|&(_, kind)| kind)
110 .ok_or_else(|| {
111 err!(Config(
112 "jwt.format",
113 "Key format {format:?} is not supported; use HMAC, B64HMAC, ECDSA or EDDSA."
114 ))
115 })
116}
117
118fn invalid_key(encoding: &'static str) -> impl FnOnce(JwtError) -> Error {
119 move |e| err!(Config("jwt.key", "JWT key is not valid {encoding}: {e}"))
120}