Skip to main content

tuwunel_core/config/
jwt.rs

1//! Turns the JWT key settings into signing and verifying keys and an algorithm.
2//!
3//! Every use of the key, format and algorithm settings goes through these
4//! conversions. The startup and reload check refuses an empty key and an
5//! unknown format, so either fails before the first login, while a key that
6//! does not decode fails at login.
7
8use 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
22/// Spellings of the `format` directive, matched without regard to case.
23///
24/// B64HMAC is the documented spelling; HMACB64 was the only one accepted before
25/// it and is kept for existing configurations.
26const 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/// Decodes the configured key for verifying tokens.
35///
36/// Fails when the key is empty, when the format is not one of the supported
37/// spellings, or when the key does not parse in that format.
38#[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/// Borrows the configured key, refusing an empty one.
54///
55/// An empty key is an empty secret in either shared-secret format and never a
56/// valid PEM key, so no format can use one.
57#[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/// Decodes the configured key for signing tokens.
70///
71/// Only the shared-secret formats can sign. An ECDSA or EDDSA key is the
72/// issuer's public key, which verifies but never signs.
73#[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/// Parses the configured signature algorithm.
90///
91/// Fails with a `jwt.algorithm` configuration error naming the value when the
92/// algorithm name is not recognized.
93#[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}