1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
//! Create and check API keys.
//!
//! This is the standalone helper. If you want keys stored and
//! checked for you, see [`crate::tenancy::auth_backends`].
//!
//! ## Format
//!
//! A key is `{prefix}.{secret}`:
//! - `prefix` — 8 hex chars, public. Index it so you can find the
//! row without scanning the table.
//! - `secret` — 32 hex chars. Never store it. Store only the
//! argon2id hash, and show the plaintext to the user once, at
//! creation.
//!
//! ## Quick start
//!
//! ```ignore
//! use rustango::api_keys::{generate_key, verify_key, hash_secret};
//!
//! // Issuing a new key:
//! let (full_token, prefix, hash) = generate_key()?;
//! // Send `full_token` to the user once. Store `prefix` + `hash` in your DB.
//!
//! // Verifying an inbound key:
//! let inbound = "abc12345.f9a7d2..."; // from request header
//! let parts = inbound.split_once('.').ok_or("bad format")?;
//! // Look up the row by parts.0 (prefix), then:
//! if verify_key(parts.1, &stored_hash)? {
//! // authenticated
//! }
//! ```
// This module owns the sync calls the lint bans elsewhere.
#![allow(clippy::disallowed_methods)]
use rand::{rngs::OsRng, RngCore};
use crate::passwords::PasswordError;
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum ApiKeyError {
#[error("hashing failed: {0}")]
Hash(String),
#[error("verification error: {0}")]
Verify(String),
/// No hashing slot freed up in time; see [`PasswordError::Busy`].
#[error("password hashing is busy")]
Busy,
}
impl From<PasswordError> for ApiKeyError {
fn from(e: PasswordError) -> Self {
match e {
PasswordError::Hash(m) => Self::Hash(m),
PasswordError::Verify(m) => Self::Verify(m),
PasswordError::Busy => Self::Busy,
}
}
}
/// Make a new API key. Returns `(full_token, prefix, hash)`.
///
/// Give `full_token` to the user. Store only `prefix` and `hash`;
/// storing the token would let anyone who reads your database use
/// the key. From async code use [`generate_key_async`].
///
/// # Errors
/// [`ApiKeyError::Hash`] if argon2 fails, which is very rare.
pub fn generate_key() -> Result<(String, String, String), ApiKeyError> {
let (prefix, secret) = new_token();
let hash = hash_secret(&secret)?;
Ok((format!("{prefix}.{secret}"), prefix, hash))
}
/// [`generate_key`] with the hash on the blocking pool.
///
/// # Errors
/// As [`generate_key`], or [`ApiKeyError::Busy`].
pub async fn generate_key_async() -> Result<(String, String, String), ApiKeyError> {
let (prefix, secret) = new_token();
let hash = hash_secret_async(&secret).await?;
Ok((format!("{prefix}.{secret}"), prefix, hash))
}
/// A fresh `(prefix, secret)` pair from `OsRng`: the secret is a
/// bearer credential, so it needs a cryptographic source.
fn new_token() -> (String, String) {
let mut prefix_bytes: [u8; 4] = [0; 4];
OsRng.fill_bytes(&mut prefix_bytes);
let mut secret_bytes: [u8; 16] = [0; 16];
OsRng.fill_bytes(&mut secret_bytes);
(to_hex(&prefix_bytes), to_hex(&secret_bytes))
}
/// Hash a secret with argon2id via [`crate::passwords::hash`]. The
/// result is a PHC string (`$argon2id$v=19$...`). Store this, never
/// the secret. From async code use [`hash_secret_async`].
///
/// # Errors
/// [`ApiKeyError::Hash`] if argon2 fails.
pub fn hash_secret(secret: &str) -> Result<String, ApiKeyError> {
Ok(crate::passwords::hash(secret)?)
}
/// [`hash_secret`] on the blocking pool.
///
/// # Errors
/// As [`hash_secret`], or [`ApiKeyError::Busy`].
pub async fn hash_secret_async(secret: &str) -> Result<String, ApiKeyError> {
Ok(crate::passwords::hash_async(secret).await?)
}
/// Check a plaintext secret against a stored argon2 hash, in constant
/// time. Never use `==`. `Ok(true)` means the secret matches. From
/// async code use [`verify_key_async`].
///
/// # Errors
/// [`ApiKeyError::Verify`] if `stored_hash` is not a valid argon2
/// PHC string.
pub fn verify_key(secret: &str, stored_hash: &str) -> Result<bool, ApiKeyError> {
Ok(crate::passwords::verify(secret, stored_hash)?)
}
/// [`verify_key`] on the blocking pool.
///
/// # Errors
/// As [`verify_key`], or [`ApiKeyError::Busy`].
pub async fn verify_key_async(secret: &str, stored_hash: &str) -> Result<bool, ApiKeyError> {
Ok(crate::passwords::verify_async(secret, stored_hash).await?)
}
/// Split a `{prefix}.{secret}` token, or `None` if it is malformed.
#[must_use]
pub fn split_token(token: &str) -> Option<(&str, &str)> {
let (prefix, secret) = token.split_once('.')?;
if prefix.len() != 8 || secret.is_empty() {
return None;
}
Some((prefix, secret))
}
fn to_hex(bytes: &[u8]) -> String {
bytes.iter().map(|b| format!("{b:02x}")).collect()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn generate_returns_well_formed_token() {
let (token, prefix, hash) = generate_key().unwrap();
assert_eq!(prefix.len(), 8);
assert!(token.starts_with(&prefix));
assert!(token.contains('.'));
assert!(hash.starts_with("$argon2id$"));
}
#[test]
fn each_generation_is_unique() {
let (t1, p1, _) = generate_key().unwrap();
let (t2, p2, _) = generate_key().unwrap();
assert_ne!(t1, t2);
assert_ne!(p1, p2);
}
#[test]
fn verify_key_succeeds_for_correct_secret() {
let (token, _, hash) = generate_key().unwrap();
let (_, secret) = split_token(&token).unwrap();
assert!(verify_key(secret, &hash).unwrap());
}
#[test]
fn verify_key_fails_for_wrong_secret() {
let (_, _, hash) = generate_key().unwrap();
assert!(!verify_key("wrong-secret", &hash).unwrap());
}
#[tokio::test]
async fn async_variants_match_the_sync_ones() {
let (token, _, hash) = generate_key_async().await.unwrap();
let (_, secret) = split_token(&token).unwrap();
assert!(verify_key_async(secret, &hash).await.unwrap());
assert!(verify_key(secret, &hash_secret_async(secret).await.unwrap()).unwrap());
assert!(!verify_key_async("wrong", &hash).await.unwrap());
}
#[test]
fn verify_invalid_hash_returns_error() {
let r = verify_key("anything", "not-a-valid-hash");
assert!(r.is_err());
}
#[test]
fn split_token_valid_format() {
let result = split_token("abcd1234.deadbeef");
assert_eq!(result, Some(("abcd1234", "deadbeef")));
}
#[test]
fn split_token_missing_dot() {
assert_eq!(split_token("noTdotHere"), None);
}
#[test]
fn split_token_wrong_prefix_length() {
assert_eq!(split_token("short.secret"), None);
assert_eq!(split_token("toolongprefix.secret"), None);
}
#[test]
fn split_token_empty_secret() {
assert_eq!(split_token("abcd1234."), None);
}
}