Skip to main content

modo/auth/apikey/
store.rs

1use std::sync::Arc;
2
3use chrono::Utc;
4
5use crate::db::Database;
6use crate::error::{Error, Result};
7use crate::id;
8
9use super::backend::ApiKeyBackend;
10use super::config::ApiKeyConfig;
11use super::sqlite::SqliteBackend;
12use super::token;
13use super::types::{ApiKeyCreated, ApiKeyMeta, ApiKeyRecord, CreateKeyRequest};
14
15/// UTC timestamp in ISO 8601 format with millisecond precision.
16fn now_utc() -> String {
17    Utc::now().format("%Y-%m-%dT%H:%M:%S%.3fZ").to_string()
18}
19
20struct Inner {
21    backend: Arc<dyn ApiKeyBackend>,
22    config: ApiKeyConfig,
23}
24
25/// Tenant-scoped API key store.
26///
27/// Handles key generation, SHA-256 hashing, constant-time verification,
28/// touch throttling, and delegates storage to the backend. Cheap to clone
29/// (wraps `Arc`).
30///
31/// # Example
32///
33/// ```rust,no_run
34/// # fn example(db: modo::db::Database) {
35/// use modo::auth::apikey::{ApiKeyConfig, ApiKeyStore};
36///
37/// let store = ApiKeyStore::new(db, ApiKeyConfig::default()).unwrap();
38/// # }
39/// ```
40pub struct ApiKeyStore(Arc<Inner>);
41
42impl Clone for ApiKeyStore {
43    fn clone(&self) -> Self {
44        Self(Arc::clone(&self.0))
45    }
46}
47
48impl ApiKeyStore {
49    /// Create from the built-in SQLite backend.
50    ///
51    /// Validates config at construction — fails fast on invalid prefix or
52    /// secret length.
53    ///
54    /// # Errors
55    ///
56    /// Returns an error if [`ApiKeyConfig::validate`] fails.
57    pub fn new(db: Database, config: ApiKeyConfig) -> Result<Self> {
58        config.validate()?;
59        Ok(Self(Arc::new(Inner {
60            backend: Arc::new(SqliteBackend::new(db)),
61            config,
62        })))
63    }
64
65    /// Create from a custom backend.
66    ///
67    /// Validates config at construction.
68    ///
69    /// # Errors
70    ///
71    /// Returns an error if [`ApiKeyConfig::validate`] fails.
72    pub fn from_backend(backend: Arc<dyn ApiKeyBackend>, config: ApiKeyConfig) -> Result<Self> {
73        config.validate()?;
74        Ok(Self(Arc::new(Inner { backend, config })))
75    }
76
77    /// Create a new API key. Returns the raw token (shown once).
78    ///
79    /// # Errors
80    ///
81    /// Returns `bad_request` if `tenant_id` or `name` is empty, or if
82    /// `expires_at` is not a valid RFC 3339 timestamp. Propagates backend
83    /// storage errors.
84    pub async fn create(&self, req: &CreateKeyRequest) -> Result<ApiKeyCreated> {
85        if req.tenant_id.is_empty() {
86            return Err(Error::bad_request("tenant_id is required"));
87        }
88        if req.name.is_empty() {
89            return Err(Error::bad_request("name is required"));
90        }
91        if let Some(ref exp) = req.expires_at {
92            chrono::DateTime::parse_from_rfc3339(exp)
93                .map_err(|_| Error::bad_request("expires_at must be a valid RFC 3339 timestamp"))?;
94        }
95
96        let ulid = id::ulid();
97        let secret = token::generate_secret(self.0.config.secret_length);
98        let raw_token = token::format_token(&self.0.config.prefix, &ulid, &secret);
99        let key_hash = token::hash_secret(&secret);
100        let now = now_utc();
101
102        let record = ApiKeyRecord {
103            id: ulid.clone(),
104            key_hash,
105            tenant_id: req.tenant_id.clone(),
106            name: req.name.clone(),
107            scopes: req.scopes.clone(),
108            expires_at: req.expires_at.clone(),
109            last_used_at: None,
110            created_at: now.clone(),
111            revoked_at: None,
112        };
113
114        self.0.backend.store(&record).await?;
115
116        Ok(ApiKeyCreated {
117            id: ulid,
118            raw_token,
119            name: req.name.clone(),
120            scopes: req.scopes.clone(),
121            tenant_id: req.tenant_id.clone(),
122            expires_at: req.expires_at.clone(),
123            created_at: now,
124        })
125    }
126
127    /// Verify a raw token. Returns metadata if valid.
128    ///
129    /// All failure cases return the same generic `unauthorized` error to
130    /// prevent enumeration.
131    ///
132    /// # Errors
133    ///
134    /// Returns `unauthorized` if the token is malformed, not found, revoked,
135    /// expired, or the hash does not match. Propagates backend lookup errors.
136    pub async fn verify(&self, raw_token: &str) -> Result<ApiKeyMeta> {
137        let parsed = token::parse_token(raw_token, &self.0.config.prefix)
138            .ok_or_else(|| Error::unauthorized("invalid API key"))?;
139
140        let record = self
141            .0
142            .backend
143            .lookup(parsed.id)
144            .await?
145            .ok_or_else(|| Error::unauthorized("invalid API key"))?;
146
147        // Revoked?
148        if record.revoked_at.is_some() {
149            return Err(Error::unauthorized("invalid API key"));
150        }
151
152        // Expired?
153        if let Some(ref exp) = record.expires_at {
154            if let Ok(exp_dt) = chrono::DateTime::parse_from_rfc3339(exp) {
155                if exp_dt <= Utc::now() {
156                    return Err(Error::unauthorized("invalid API key"));
157                }
158            } else {
159                return Err(Error::unauthorized("invalid API key"));
160            }
161        }
162
163        // Constant-time hash verification
164        if !token::verify_hash(parsed.secret, &record.key_hash) {
165            return Err(Error::unauthorized("invalid API key"));
166        }
167
168        // Touch throttling — fire-and-forget if threshold elapsed
169        self.maybe_touch(&record);
170
171        Ok(record.into_meta())
172    }
173
174    /// Revoke a key by ID.
175    ///
176    /// # Errors
177    ///
178    /// Returns `not_found` if no key with the given ID exists.
179    /// Propagates backend errors.
180    pub async fn revoke(&self, key_id: &str) -> Result<()> {
181        self.0
182            .backend
183            .lookup(key_id)
184            .await?
185            .ok_or_else(|| Error::not_found("API key not found"))?;
186
187        self.0.backend.revoke(key_id, &now_utc()).await
188    }
189
190    /// List all active keys for a tenant (no secrets).
191    ///
192    /// # Errors
193    ///
194    /// Propagates backend errors.
195    pub async fn list(&self, tenant_id: &str) -> Result<Vec<ApiKeyMeta>> {
196        let records = self.0.backend.list(tenant_id).await?;
197        Ok(records.into_iter().map(ApiKeyRecord::into_meta).collect())
198    }
199
200    /// Update `expires_at` (refresh/extend a key).
201    ///
202    /// # Errors
203    ///
204    /// Returns `bad_request` if `expires_at` is not a valid RFC 3339
205    /// timestamp. Returns `not_found` if no key with the given ID exists.
206    /// Propagates backend errors.
207    pub async fn refresh(&self, key_id: &str, expires_at: Option<&str>) -> Result<()> {
208        if let Some(exp) = expires_at {
209            chrono::DateTime::parse_from_rfc3339(exp)
210                .map_err(|_| Error::bad_request("expires_at must be a valid RFC 3339 timestamp"))?;
211        }
212
213        self.0
214            .backend
215            .lookup(key_id)
216            .await?
217            .ok_or_else(|| Error::not_found("API key not found"))?;
218
219        self.0.backend.update_expires_at(key_id, expires_at).await
220    }
221
222    /// Fire-and-forget touch if the threshold has elapsed.
223    ///
224    /// Best-effort: the spawned task may be lost on shutdown.
225    fn maybe_touch(&self, record: &ApiKeyRecord) {
226        let threshold_secs = self.0.config.touch_threshold_secs;
227        let should_touch = match &record.last_used_at {
228            None => true,
229            Some(last) => match chrono::DateTime::parse_from_rfc3339(last) {
230                Ok(last_dt) => {
231                    let elapsed = chrono::Utc::now()
232                        .signed_duration_since(last_dt)
233                        .num_seconds();
234                    elapsed >= threshold_secs as i64
235                }
236                Err(_) => true,
237            },
238        };
239
240        if should_touch {
241            let backend = self.0.backend.clone();
242            let key_id = record.id.clone();
243            tokio::spawn(async move {
244                if let Err(e) = backend.update_last_used(&key_id, &now_utc()).await {
245                    tracing::warn!(key_id, error = %e, "failed to update API key last_used_at");
246                }
247            });
248        }
249    }
250}