Required the API token for every runtime API route (#1045)

This commit is contained in:
Thorsten Sommer authored and GitHub committed 2026-10-11 10:07:07 +02:00
1 parent 4f966eed86
commit 8badadb35f
24 files changed
+231 -79

No files matched your search

+31 -1
View File
@@ -2,6 +2,7 @@ use log::error;
use rand::rngs::SysRng;
use rand::{Rng, SeedableRng};
use rand_chacha::ChaChaRng;
use subtle::ConstantTimeEq;
/// The API token data structure used to authenticate requests.
pub struct APIToken {
@@ -31,8 +32,12 @@ impl APIToken {
}
/// Validates the received token against the valid token.
///
/// The comparison takes the same time no matter where the two tokens differ. A comparison
/// which stops at the first difference would let the time of each refusal tell how much of a
/// guess was right.
pub fn validate(&self, received_token: &Self) -> bool {
received_token.to_hex_text() == self.to_hex_text()
received_token.to_hex_text().as_bytes().ct_eq(self.to_hex_text().as_bytes()).into()
}
}
@@ -50,4 +55,29 @@ pub fn generate_api_token() -> APIToken {
});
rng.fill_bytes(&mut token);
APIToken::from_bytes(token.to_vec())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn validate_accepts_only_the_identical_token() {
let valid_token = APIToken::from_hex_text("0123456789abcdef");
assert!(valid_token.validate(&APIToken::from_hex_text("0123456789abcdef")));
assert!(!valid_token.validate(&APIToken::from_hex_text("0123456789abcdee")));
assert!(!valid_token.validate(&APIToken::from_hex_text("1123456789abcdef")));
assert!(!valid_token.validate(&APIToken::from_hex_text("0123456789abcde")));
assert!(!valid_token.validate(&APIToken::from_hex_text("0123456789abcdef0")));
assert!(!valid_token.validate(&APIToken::from_hex_text("")));
}
#[test]
fn a_generated_token_validates_against_its_own_text() {
let token = generate_api_token();
assert_eq!(token.to_hex_text().len(), 64);
assert!(token.validate(&APIToken::from_hex_text(token.to_hex_text())));
}
}