modo/auth/apikey/
store.rs1use 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
15fn 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
25pub 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 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 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 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 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 if record.revoked_at.is_some() {
149 return Err(Error::unauthorized("invalid API key"));
150 }
151
152 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 if !token::verify_hash(parsed.secret, &record.key_hash) {
165 return Err(Error::unauthorized("invalid API key"));
166 }
167
168 self.maybe_touch(&record);
170
171 Ok(record.into_meta())
172 }
173
174 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 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 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 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}