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
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
use super::{ApiPermission, DatabaseManager};
use alloy::primitives::Address;
use chrono::{DateTime, Utc};
use serde_json::Value as JsonValue;
use sqlx::{postgres::PgRow, Row};
use std::collections::HashSet;
use tracing::{error, info};
use uuid::Uuid;
/// Database model for API keys with additional metadata
#[derive(Debug, Clone)]
pub struct ApiKeyRecord {
/// Unique identifier for this API key
pub id: Uuid,
/// User ID associated with this API key
pub user_id: Uuid,
/// Ethereum wallet address associated with this user
pub address: Address,
/// API key string (bearer token)
pub api_key: String,
/// Human-readable name for the API key
pub name: String,
/// Set of permissions granted to this key
pub permissions: HashSet<ApiPermission>,
/// Optional rate limit override (requests per minute)
pub rate_limit: Option<u32>,
/// Timestamp when the key was created
pub created_at: DateTime<Utc>,
/// Timestamp when the key was last updated
pub updated_at: DateTime<Utc>,
/// Whether the key is currently active
pub is_active: bool,
/// Optional expiration timestamp
pub expires_at: Option<DateTime<Utc>>,
/// Optional description of the key's purpose
pub description: Option<String>,
}
impl ApiKeyRecord {
/// Checks if the API key is currently valid
pub fn is_valid(&self) -> bool {
if !self.is_active {
return false;
}
if let Some(expires_at) = self.expires_at {
if expires_at < Utc::now() {
return false;
}
}
true
}
/// Checks if the API key has the specified permission
pub fn has_permission(&self, permission: &ApiPermission) -> bool {
self.permissions.iter().any(|p| p.implies(permission))
}
}
/// Repository for API key CRUD operations
#[derive(Debug, Clone)]
pub struct ApiKeyRepository {
db: DatabaseManager,
}
/// Parameters for updating an existing API key record.
#[derive(Debug, Default)]
pub struct ApiKeyUpdate {
/// Optional new name for the API key.
pub name: Option<String>,
/// Optional new set of permissions.
pub permissions: Option<HashSet<ApiPermission>>,
/// Optional new rate limit.
pub rate_limit: Option<Option<u32>>,
/// Optional updated active flag.
pub is_active: Option<bool>,
/// Optional updated description.
pub description: Option<Option<String>>,
/// Optional updated expiration timestamp.
pub expires_at: Option<Option<DateTime<Utc>>>,
}
impl ApiKeyRepository {
/// Creates a new API key repository
pub fn new(db: DatabaseManager) -> Self {
Self { db }
}
/// Retrieves an API key by its key string
///
/// # Arguments
///
/// * `key` - The API key string
///
/// # Returns
///
/// Returns the API key record if found
///
/// # Errors
///
/// Returns an error if the database query fails
pub async fn get_by_key(&self, key: &str) -> sqlx::Result<Option<ApiKeyRecord>> {
let row = sqlx::query(
r#"
SELECT id, user_id, address, api_key, name, permissions, rate_limit, created_at, updated_at,
is_active, expires_at, description
FROM api_keys
WHERE api_key = $1
"#,
)
.bind(key)
.fetch_optional(self.db.pool())
.await?;
Ok(row.map(Self::row_to_record))
}
/// Retrieves all active API keys
///
/// # Returns
///
/// Returns a vector of all active API key records
///
/// # Errors
///
/// Returns an error if the database query fails
pub async fn get_all_active(&self) -> sqlx::Result<Vec<ApiKeyRecord>> {
let rows = sqlx::query(
r#"
SELECT id, user_id, address, api_key, name, permissions, rate_limit, created_at, updated_at,
is_active, expires_at, description
FROM api_keys
WHERE is_active = true
ORDER BY created_at DESC
"#,
)
.fetch_all(self.db.pool())
.await?;
Ok(rows.into_iter().map(Self::row_to_record).collect())
}
/// Creates a new API key
///
/// # Arguments
///
/// * `key` - The API key string
/// * `name` - Human-readable name for the key
/// * `permissions` - Set of permissions to grant
/// * `rate_limit` - Optional rate limit (requests per minute)
/// * `description` - Optional description
/// * `expires_at` - Optional expiration timestamp
/// * `user_id` - UUID of the user who owns this API key
///
/// # Returns
///
/// Returns the created API key record
///
/// # Errors
///
/// Returns an error if the database insert fails
#[allow(clippy::too_many_arguments)]
pub async fn create(
&self,
user_id: Uuid,
api_key: String,
name: String,
permissions: HashSet<ApiPermission>,
rate_limit: Option<u32>,
description: Option<String>,
expires_at: Option<DateTime<Utc>>,
) -> sqlx::Result<ApiKeyRecord> {
let permissions_json = Self::permissions_to_json(&permissions);
let row = sqlx::query(
r#"
INSERT INTO api_keys (user_id, address, api_key, name, permissions, rate_limit, description, expires_at)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8)
RETURNING id, user_id, address, api_key, name, permissions, rate_limit, created_at, updated_at,
is_active, expires_at, description
"#,
)
// Default to zero-address; callers should set the actual wallet address elsewhere.
.bind(user_id)
.bind(Address::ZERO.as_slice())
.bind(&api_key)
.bind(&name)
.bind(permissions_json)
.bind(rate_limit.map(|r| r as i32))
.bind(description)
.bind(expires_at)
.fetch_one(self.db.pool())
.await?;
info!("Created new API key: {} ({})", name, api_key);
Ok(Self::row_to_record(row))
}
/// Updates an existing API key
///
/// # Arguments
///
/// * `key` - The API key string
/// * `name` - Optional new name
/// * `permissions` - Optional new permissions set
/// * `rate_limit` - Optional new rate limit
/// * `is_active` - Optional new active status
/// * `description` - Optional new description
/// * `expires_at` - Optional new expiration timestamp
///
/// # Returns
///
/// Returns the updated API key record
///
/// # Errors
///
/// Returns an error if the database update fails or key not found
pub async fn update(&self, key: &str, update: ApiKeyUpdate) -> sqlx::Result<ApiKeyRecord> {
// Build dynamic update query
let mut query = String::from("UPDATE api_keys SET updated_at = NOW()");
let mut param_count = 1;
if update.name.is_some() {
param_count += 1;
query.push_str(&format!(", name = ${}", param_count));
}
if update.permissions.is_some() {
param_count += 1;
query.push_str(&format!(", permissions = ${}", param_count));
}
if update.rate_limit.is_some() {
param_count += 1;
query.push_str(&format!(", rate_limit = ${}", param_count));
}
if update.is_active.is_some() {
param_count += 1;
query.push_str(&format!(", is_active = ${}", param_count));
}
if update.description.is_some() {
param_count += 1;
query.push_str(&format!(", description = ${}", param_count));
}
if update.expires_at.is_some() {
param_count += 1;
query.push_str(&format!(", expires_at = ${}", param_count));
}
query.push_str(
" WHERE api_key = $1 RETURNING id, user_id, address, api_key, name, permissions, rate_limit, created_at, updated_at, is_active, expires_at, description",
);
let mut q = sqlx::query(&query).bind(key);
if let Some(n) = update.name {
q = q.bind(n);
}
if let Some(p) = update.permissions {
q = q.bind(Self::permissions_to_json(&p));
}
if let Some(r) = update.rate_limit {
q = q.bind(r.map(|v| v as i32));
}
if let Some(a) = update.is_active {
q = q.bind(a);
}
if let Some(d) = update.description {
q = q.bind(d);
}
if let Some(e) = update.expires_at {
q = q.bind(e);
}
let row = q.fetch_one(self.db.pool()).await?;
info!("Updated API key: {}", key);
Ok(Self::row_to_record(row))
}
/// Deletes an API key
///
/// # Arguments
///
/// * `key` - The API key string to delete
///
/// # Returns
///
/// Returns true if the key was deleted, false if not found
///
/// # Errors
///
/// Returns an error if the database delete fails
pub async fn delete(&self, key: &str) -> sqlx::Result<bool> {
let result = sqlx::query("DELETE FROM api_keys WHERE api_key = $1")
.bind(key)
.execute(self.db.pool())
.await?;
let deleted = result.rows_affected() > 0;
if deleted {
info!("Deleted API key: {}", key);
}
Ok(deleted)
}
/// Deactivates an API key (soft delete)
///
/// # Arguments
///
/// * `key` - The API key string to deactivate
///
/// # Returns
///
/// Returns true if the key was deactivated
///
/// # Errors
///
/// Returns an error if the database update fails
pub async fn deactivate(&self, key: &str) -> sqlx::Result<bool> {
let result = sqlx::query("UPDATE api_keys SET is_active = false, updated_at = NOW() WHERE api_key = $1")
.bind(key)
.execute(self.db.pool())
.await?;
let deactivated = result.rows_affected() > 0;
if deactivated {
info!("Deactivated API key: {}", key);
}
Ok(deactivated)
}
/// Converts a database row to ApiKeyRecord
fn row_to_record(row: PgRow) -> ApiKeyRecord {
let permissions_json: JsonValue = row.get("permissions");
let permissions = Self::json_to_permissions(&permissions_json);
let address_bytes: Vec<u8> = row.get("address");
let address = Address::from_slice(&address_bytes);
ApiKeyRecord {
id: row.get("id"),
user_id: row.get("user_id"),
address,
api_key: row.get("api_key"),
name: row.get("name"),
permissions,
rate_limit: row.get::<Option<i32>, _>("rate_limit").map(|r| r as u32),
created_at: row.get("created_at"),
updated_at: row.get("updated_at"),
is_active: row.get("is_active"),
expires_at: row.get("expires_at"),
description: row.get("description"),
}
}
/// Converts permissions HashSet to JSON array
fn permissions_to_json(permissions: &HashSet<ApiPermission>) -> JsonValue {
let perms: Vec<String> = permissions
.iter()
.filter_map(|p| serde_json::to_value(p).ok())
.filter_map(|v| v.as_str().map(String::from))
.collect();
JsonValue::Array(perms.into_iter().map(JsonValue::String).collect())
}
/// Converts JSON array to permissions HashSet
fn json_to_permissions(json: &JsonValue) -> HashSet<ApiPermission> {
match json {
JsonValue::Array(arr) => arr
.iter()
.filter_map(|v| v.as_str())
.filter_map(|s| serde_json::from_value(JsonValue::String(s.to_string())).ok())
.collect(),
_ => {
error!("Invalid permissions JSON format: {:?}", json);
HashSet::new()
}
}
}
}