Skip to main content

koan_core/
auth.rs

1//! Authentication primitives: Ed25519 JWT signing, Argon2id password hashing.
2//!
3//! Ed25519 keypair is generated once and stored in the config directory.
4//! JWTs use EdDSA (Ed25519) for signing — 128-bit security, tiny keys, fast.
5
6use std::fs;
7use std::path::PathBuf;
8use std::time::{SystemTime, UNIX_EPOCH};
9
10use jsonwebtoken::{Algorithm, DecodingKey, EncodingKey, Header, Validation};
11use ring::signature::KeyPair;
12use serde::{Deserialize, Serialize};
13use thiserror::Error;
14
15use crate::config;
16
17// ---------------------------------------------------------------------------
18// Errors
19// ---------------------------------------------------------------------------
20
21#[derive(Debug, Error)]
22pub enum AuthError {
23    #[error("jwt error: {0}")]
24    Jwt(#[from] jsonwebtoken::errors::Error),
25    #[error("argon2 hash error: {0}")]
26    Hash(String),
27    #[error("password verification failed")]
28    InvalidPassword,
29    #[error("io error: {0}")]
30    Io(#[from] std::io::Error),
31    #[error("keypair not found — run `koan auth setup` first")]
32    NoKeypair,
33    #[error("{0}")]
34    Other(String),
35}
36
37// ---------------------------------------------------------------------------
38// Roles
39// ---------------------------------------------------------------------------
40
41#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
42#[serde(rename_all = "lowercase")]
43pub enum Role {
44    Admin,
45    User,
46    Readonly,
47}
48
49impl Role {
50    pub fn as_str(&self) -> &'static str {
51        match self {
52            Role::Admin => "admin",
53            Role::User => "user",
54            Role::Readonly => "readonly",
55        }
56    }
57
58    /// Returns true if this role has at least the given permission level.
59    /// Admin > User > Readonly.
60    pub fn has_permission(&self, required: Role) -> bool {
61        match required {
62            Role::Readonly => true,
63            Role::User => matches!(self, Role::Admin | Role::User),
64            Role::Admin => matches!(self, Role::Admin),
65        }
66    }
67}
68
69impl std::str::FromStr for Role {
70    type Err = String;
71
72    fn from_str(s: &str) -> Result<Self, Self::Err> {
73        match s {
74            "admin" => Ok(Role::Admin),
75            "user" => Ok(Role::User),
76            "readonly" => Ok(Role::Readonly),
77            _ => Err(format!("invalid role: '{s}'")),
78        }
79    }
80}
81
82impl std::fmt::Display for Role {
83    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
84        f.write_str(self.as_str())
85    }
86}
87
88// ---------------------------------------------------------------------------
89// JWT Claims
90// ---------------------------------------------------------------------------
91
92#[derive(Debug, Serialize, Deserialize)]
93pub struct Claims {
94    /// Subject — user ID.
95    pub sub: i64,
96    /// Username.
97    pub username: String,
98    /// Role.
99    pub role: String,
100    /// Issued at (unix timestamp).
101    pub iat: u64,
102    /// Expiration (unix timestamp).
103    pub exp: u64,
104}
105
106// ---------------------------------------------------------------------------
107// Password hashing (Argon2id)
108// ---------------------------------------------------------------------------
109
110/// Hash a password using Argon2id with a random salt.
111pub fn hash_password(password: &str) -> Result<String, AuthError> {
112    use argon2::Argon2;
113    use argon2::password_hash::{PasswordHasher, SaltString, rand_core::OsRng};
114
115    let salt = SaltString::generate(&mut OsRng);
116    let argon2 = Argon2::default();
117    argon2
118        .hash_password(password.as_bytes(), &salt)
119        .map(|h| h.to_string())
120        .map_err(|e| AuthError::Hash(e.to_string()))
121}
122
123/// Verify a password against an Argon2id hash.
124pub fn verify_password(password: &str, hash: &str) -> Result<(), AuthError> {
125    use argon2::Argon2;
126    use argon2::password_hash::{PasswordHash, PasswordVerifier};
127
128    let parsed = PasswordHash::new(hash).map_err(|e| AuthError::Hash(e.to_string()))?;
129    Argon2::default()
130        .verify_password(password.as_bytes(), &parsed)
131        .map_err(|_| AuthError::InvalidPassword)
132}
133
134// ---------------------------------------------------------------------------
135// Ed25519 Keypair management
136// ---------------------------------------------------------------------------
137
138pub fn keypair_dir() -> PathBuf {
139    config::config_dir().join("auth")
140}
141
142fn private_key_path() -> PathBuf {
143    keypair_dir().join("ed25519.pem")
144}
145
146fn public_key_path() -> PathBuf {
147    keypair_dir().join("ed25519.pub.pem")
148}
149
150/// Generate a new Ed25519 keypair and write PEM files to the config dir.
151/// Returns (private_pem, public_pem).
152pub fn generate_keypair() -> Result<(Vec<u8>, Vec<u8>), AuthError> {
153    let dir = keypair_dir();
154    fs::create_dir_all(&dir)?;
155
156    // Ensure the auth directory is gitignored — keys must never be committed.
157    let gitignore = dir.join(".gitignore");
158    if !gitignore.exists() {
159        let _ = fs::write(&gitignore, "*\n");
160    }
161
162    // Generate Ed25519 keypair using ring (via jsonwebtoken's internal ring dep).
163    // jsonwebtoken's EncodingKey::from_ed_pem expects PKCS8 PEM.
164    let rng = ring::rand::SystemRandom::new();
165    let pkcs8_doc = ring::signature::Ed25519KeyPair::generate_pkcs8(&rng)
166        .map_err(|e| AuthError::Other(format!("keypair generation failed: {}", e)))?;
167
168    let private_pem = pem::encode(&pem::Pem::new("PRIVATE KEY", pkcs8_doc.as_ref()));
169
170    // Extract public key from the keypair.
171    let kp = ring::signature::Ed25519KeyPair::from_pkcs8(pkcs8_doc.as_ref())
172        .map_err(|e| AuthError::Other(format!("keypair parse failed: {}", e)))?;
173    let pub_bytes = kp.public_key().as_ref();
174
175    // Wrap public key in SubjectPublicKeyInfo DER (for Ed25519 this is a fixed prefix + 32 bytes).
176    // OID 1.3.101.112 = id-EdDSA (Ed25519).
177    let mut spki = vec![
178        0x30, 0x2a, // SEQUENCE, 42 bytes total
179        0x30, 0x05, // SEQUENCE (AlgorithmIdentifier), 5 bytes
180        0x06, 0x03, 0x2b, 0x65, 0x70, // OID 1.3.101.112
181        0x03, 0x21, 0x00, // BIT STRING, 33 bytes, 0 unused bits
182    ];
183    spki.extend_from_slice(pub_bytes);
184    let public_pem = pem::encode(&pem::Pem::new("PUBLIC KEY", spki));
185
186    // Write key files with restrictive permissions set BEFORE writing content
187    // to avoid a window where the file exists with default (world-readable) mode.
188    #[cfg(unix)]
189    {
190        use std::fs::OpenOptions;
191        use std::io::Write;
192        use std::os::unix::fs::OpenOptionsExt;
193        use std::os::unix::fs::PermissionsExt;
194
195        let mut f = OpenOptions::new()
196            .write(true)
197            .create(true)
198            .truncate(true)
199            .mode(0o600)
200            .open(private_key_path())?;
201        f.write_all(private_pem.as_bytes())?;
202
203        let mut f = OpenOptions::new()
204            .write(true)
205            .create(true)
206            .truncate(true)
207            .mode(0o644)
208            .open(public_key_path())?;
209        f.write_all(public_pem.as_bytes())?;
210
211        let _ = fs::set_permissions(&dir, fs::Permissions::from_mode(0o700));
212    }
213
214    #[cfg(not(unix))]
215    {
216        fs::write(private_key_path(), &private_pem)?;
217        fs::write(public_key_path(), &public_pem)?;
218    }
219
220    Ok((private_pem.into_bytes(), public_pem.into_bytes()))
221}
222
223/// Load the Ed25519 keypair from disk. Returns (private_pem, public_pem).
224pub fn load_keypair() -> Result<(Vec<u8>, Vec<u8>), AuthError> {
225    let priv_path = private_key_path();
226    let pub_path = public_key_path();
227
228    if !priv_path.exists() || !pub_path.exists() {
229        return Err(AuthError::NoKeypair);
230    }
231
232    let private_pem = fs::read(&priv_path)?;
233    let public_pem = fs::read(&pub_path)?;
234    Ok((private_pem, public_pem))
235}
236
237/// Load or generate the keypair. Generates if missing.
238pub fn load_or_generate_keypair() -> Result<(Vec<u8>, Vec<u8>), AuthError> {
239    match load_keypair() {
240        Ok(kp) => Ok(kp),
241        Err(AuthError::NoKeypair) => generate_keypair(),
242        Err(e) => Err(e),
243    }
244}
245
246// ---------------------------------------------------------------------------
247// JWT encode / decode
248// ---------------------------------------------------------------------------
249
250/// Mint a new access token.
251pub fn mint_access_token(
252    private_pem: &[u8],
253    user_id: i64,
254    username: &str,
255    role: Role,
256    ttl_secs: u64,
257) -> Result<String, AuthError> {
258    let now = SystemTime::now()
259        .duration_since(UNIX_EPOCH)
260        .unwrap()
261        .as_secs();
262
263    let claims = Claims {
264        sub: user_id,
265        username: username.to_string(),
266        role: role.as_str().to_string(),
267        iat: now,
268        exp: now + ttl_secs,
269    };
270
271    let key = EncodingKey::from_ed_pem(private_pem)?;
272    let header = Header::new(Algorithm::EdDSA);
273    let token = jsonwebtoken::encode(&header, &claims, &key)?;
274    Ok(token)
275}
276
277/// Validate an access token and return its claims.
278pub fn validate_access_token(public_pem: &[u8], token: &str) -> Result<Claims, AuthError> {
279    let key = DecodingKey::from_ed_pem(public_pem)?;
280    let mut validation = Validation::new(Algorithm::EdDSA);
281    // Only require exp (expiry). sub and iat are custom fields, not JWT spec strings.
282    validation.set_required_spec_claims(&["exp"]);
283
284    let data = jsonwebtoken::decode::<Claims>(token, &key, &validation)?;
285    Ok(data.claims)
286}
287
288// ---------------------------------------------------------------------------
289// Time helpers
290// ---------------------------------------------------------------------------
291
292pub fn now_unix() -> u64 {
293    SystemTime::now()
294        .duration_since(UNIX_EPOCH)
295        .unwrap()
296        .as_secs()
297}
298
299/// Parse a duration string like "15m", "7d", "24h", "3600s" into seconds.
300pub fn parse_duration_secs(s: &str) -> Option<u64> {
301    let s = s.trim();
302    if s.is_empty() {
303        return None;
304    }
305
306    let (num_str, multiplier) = if let Some(n) = s.strip_suffix('d') {
307        (n, 86400)
308    } else if let Some(n) = s.strip_suffix('h') {
309        (n, 3600)
310    } else if let Some(n) = s.strip_suffix('m') {
311        (n, 60)
312    } else if let Some(n) = s.strip_suffix('s') {
313        (n, 1)
314    } else {
315        (s, 1)
316    };
317
318    let num: u64 = num_str.parse().ok()?;
319    Some(num * multiplier)
320}
321
322// ---------------------------------------------------------------------------
323// Tests
324// ---------------------------------------------------------------------------
325
326#[cfg(test)]
327mod tests {
328    use super::*;
329
330    #[test]
331    fn password_hash_and_verify() {
332        let password = "hunter2";
333        let hash = hash_password(password).unwrap();
334        assert!(hash.starts_with("$argon2"));
335        verify_password(password, &hash).unwrap();
336    }
337
338    #[test]
339    fn password_verify_wrong() {
340        let hash = hash_password("correct").unwrap();
341        let result = verify_password("wrong", &hash);
342        assert!(matches!(result, Err(AuthError::InvalidPassword)));
343    }
344
345    #[test]
346    fn keypair_generate_and_jwt_roundtrip() {
347        let (priv_pem, pub_pem) = generate_keypair().unwrap();
348
349        let token = mint_access_token(&priv_pem, 42, "testuser", Role::Admin, 3600).unwrap();
350        let claims = validate_access_token(&pub_pem, &token).unwrap();
351
352        assert_eq!(claims.sub, 42);
353        assert_eq!(claims.username, "testuser");
354        assert_eq!(claims.role, "admin");
355    }
356
357    #[test]
358    fn expired_token_rejected() {
359        let (priv_pem, pub_pem) = generate_keypair().unwrap();
360        // Manually create a token that expired 10 minutes ago.
361        let now = std::time::SystemTime::now()
362            .duration_since(std::time::UNIX_EPOCH)
363            .unwrap()
364            .as_secs();
365        let claims = Claims {
366            sub: 1,
367            username: "user".into(),
368            role: "user".into(),
369            iat: now - 1200,
370            exp: now - 600, // expired 10 min ago
371        };
372        let key = jsonwebtoken::EncodingKey::from_ed_pem(&priv_pem).unwrap();
373        let header = jsonwebtoken::Header::new(jsonwebtoken::Algorithm::EdDSA);
374        let token = jsonwebtoken::encode(&header, &claims, &key).unwrap();
375        let result = validate_access_token(&pub_pem, &token);
376        assert!(result.is_err());
377    }
378
379    #[test]
380    fn role_permissions() {
381        assert!(Role::Admin.has_permission(Role::Admin));
382        assert!(Role::Admin.has_permission(Role::User));
383        assert!(Role::Admin.has_permission(Role::Readonly));
384
385        assert!(!Role::User.has_permission(Role::Admin));
386        assert!(Role::User.has_permission(Role::User));
387        assert!(Role::User.has_permission(Role::Readonly));
388
389        assert!(!Role::Readonly.has_permission(Role::Admin));
390        assert!(!Role::Readonly.has_permission(Role::User));
391        assert!(Role::Readonly.has_permission(Role::Readonly));
392    }
393
394    #[test]
395    fn parse_duration() {
396        assert_eq!(parse_duration_secs("15m"), Some(900));
397        assert_eq!(parse_duration_secs("7d"), Some(604800));
398        assert_eq!(parse_duration_secs("24h"), Some(86400));
399        assert_eq!(parse_duration_secs("3600s"), Some(3600));
400        assert_eq!(parse_duration_secs("3600"), Some(3600));
401        assert_eq!(parse_duration_secs(""), None);
402    }
403}