ironclaw 0.24.0

Secure personal AI assistant that protects your data and expands its capabilities on the fly
Documentation
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
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
//! User management API handlers (admin).

use std::sync::Arc;

use axum::{
    Json,
    extract::{Path, State},
    http::StatusCode,
};
use rand::RngCore;
use rand::rngs::OsRng;
use uuid::Uuid;

use crate::channels::web::auth::{AdminUser, AuthenticatedUser};
use crate::channels::web::server::GatewayState;
use crate::db::{Database, UserRecord};

/// Check whether `user_id` is the sole active admin. Returns true if demoting,
/// suspending, or deleting this user would leave zero admins.
async fn is_last_admin(store: &dyn Database, user_id: &str) -> Result<bool, String> {
    let users = store
        .list_users(Some("active"))
        .await
        .map_err(|e| e.to_string())?;
    let active_admins: Vec<_> = users.iter().filter(|u| u.role == "admin").collect();
    Ok(active_admins.len() == 1 && active_admins[0].id == user_id)
}

/// POST /api/admin/users — create a new user.
pub async fn users_create_handler(
    State(state): State<Arc<GatewayState>>,
    AdminUser(user): AdminUser,
    Json(body): Json<serde_json::Value>,
) -> Result<Json<serde_json::Value>, (StatusCode, String)> {
    let store = state.store.as_ref().ok_or((
        StatusCode::SERVICE_UNAVAILABLE,
        "Database not available".to_string(),
    ))?;

    let display_name = body
        .get("display_name")
        .and_then(|v| v.as_str())
        .map(|s| s.trim())
        .filter(|s| !s.is_empty())
        .ok_or((
            StatusCode::BAD_REQUEST,
            "Missing or empty 'display_name'".to_string(),
        ))?
        .to_string();

    let email = body
        .get("email")
        .and_then(|v| v.as_str())
        .map(|s| s.trim())
        .filter(|s| !s.is_empty())
        .map(String::from);
    let role = body
        .get("role")
        .and_then(|v| v.as_str())
        .unwrap_or("member")
        .to_string();
    if role != "admin" && role != "member" {
        return Err((
            StatusCode::BAD_REQUEST,
            "role must be 'admin' or 'member'".to_string(),
        ));
    }

    let user_id = Uuid::new_v4().to_string();

    let now = chrono::Utc::now();
    let user_record = UserRecord {
        id: user_id.clone(),
        email,
        display_name: display_name.clone(),
        status: "active".to_string(),
        role,
        created_at: now,
        updated_at: now,
        last_login_at: None,
        created_by: Some(user.user_id.clone()),
        metadata: serde_json::json!({}),
    };

    // Generate a first API token so the new user can authenticate immediately.
    // Hash the hex-encoded plaintext (what the user sends as Bearer token),
    // NOT the raw bytes — must match hash_token() in auth.rs.
    let mut token_bytes = [0u8; 32];
    OsRng.fill_bytes(&mut token_bytes);
    let plaintext_token = hex::encode(token_bytes);
    let token_hash = crate::channels::web::auth::hash_token(&plaintext_token);
    let token_prefix = &plaintext_token[..8];

    // Create user and initial token atomically — if either fails, both roll back.
    let _token_record = store
        .create_user_with_token(&user_record, "initial", &token_hash, token_prefix, None)
        .await
        .map_err(|e| {
            let msg = e.to_string();
            let lower = msg.to_ascii_lowercase();
            if lower.contains("unique")
                || lower.contains("duplicate")
                || lower.contains("already exists")
            {
                (StatusCode::CONFLICT, msg)
            } else {
                (StatusCode::INTERNAL_SERVER_ERROR, msg)
            }
        })?;

    Ok(Json(serde_json::json!({
        "id": user_record.id,
        "email": user_record.email,
        "display_name": user_record.display_name,
        "status": user_record.status,
        "role": user_record.role,
        "token": plaintext_token,
        "created_at": user_record.created_at.to_rfc3339(),
        "created_by": user_record.created_by,
    })))
}

/// GET /api/admin/users — list all users with inline usage stats.
pub async fn users_list_handler(
    State(state): State<Arc<GatewayState>>,
    AdminUser(_user): AdminUser,
) -> Result<Json<serde_json::Value>, (StatusCode, String)> {
    let store = state.store.as_ref().ok_or((
        StatusCode::SERVICE_UNAVAILABLE,
        "Database not available".to_string(),
    ))?;

    let users = store
        .list_users(None)
        .await
        .map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?;

    // Fetch per-user summary stats from DB (agent_jobs + llm_calls).
    let summary_stats = store
        .user_summary_stats(None)
        .await
        .map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?;

    let stats_map: std::collections::HashMap<String, _> = summary_stats
        .into_iter()
        .map(|s| (s.user_id.clone(), s))
        .collect();

    let mut users_json: Vec<serde_json::Value> = Vec::with_capacity(users.len());
    for u in users {
        let db_stats = stats_map.get(&u.id);
        let total_cost = db_stats.map_or(rust_decimal::Decimal::ZERO, |s| s.total_cost);

        // Last active: prefer DB timestamp, fall back to last_login_at.
        let last_active = db_stats.and_then(|s| s.last_active_at).or(u.last_login_at);

        users_json.push(serde_json::json!({
            "id": u.id,
            "email": u.email,
            "display_name": u.display_name,
            "status": u.status,
            "role": u.role,
            "created_at": u.created_at.to_rfc3339(),
            "updated_at": u.updated_at.to_rfc3339(),
            "last_login_at": u.last_login_at.map(|dt| dt.to_rfc3339()),
            "created_by": u.created_by,
            "job_count": db_stats.map_or(0, |s| s.job_count),
            "total_cost": total_cost.to_string(),
            "last_active_at": last_active.map(|dt| dt.to_rfc3339()),
        }));
    }

    Ok(Json(serde_json::json!({ "users": users_json })))
}

/// GET /api/admin/users/{id} — get a single user.
pub async fn users_detail_handler(
    State(state): State<Arc<GatewayState>>,
    AdminUser(_user): AdminUser,
    Path(id): Path<String>,
) -> Result<Json<serde_json::Value>, (StatusCode, String)> {
    let store = state.store.as_ref().ok_or((
        StatusCode::SERVICE_UNAVAILABLE,
        "Database not available".to_string(),
    ))?;

    let user_record = store
        .get_user(&id)
        .await
        .map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?
        .ok_or((StatusCode::NOT_FOUND, "User not found".to_string()))?;

    Ok(Json(serde_json::json!({
        "id": user_record.id,
        "email": user_record.email,
        "display_name": user_record.display_name,
        "status": user_record.status,
        "role": user_record.role,
        "created_at": user_record.created_at.to_rfc3339(),
        "updated_at": user_record.updated_at.to_rfc3339(),
        "last_login_at": user_record.last_login_at.map(|dt| dt.to_rfc3339()),
        "created_by": user_record.created_by,
        "metadata": user_record.metadata,
    })))
}

/// PATCH /api/admin/users/{id} — update a user's profile.
pub async fn users_update_handler(
    State(state): State<Arc<GatewayState>>,
    AdminUser(_user): AdminUser,
    Path(id): Path<String>,
    Json(body): Json<serde_json::Value>,
) -> Result<Json<serde_json::Value>, (StatusCode, String)> {
    let store = state.store.as_ref().ok_or((
        StatusCode::SERVICE_UNAVAILABLE,
        "Database not available".to_string(),
    ))?;

    // Verify the user exists.
    let existing = store
        .get_user(&id)
        .await
        .map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?
        .ok_or((StatusCode::NOT_FOUND, "User not found".to_string()))?;

    let display_name = body
        .get("display_name")
        .and_then(|v| v.as_str())
        .map(|s| s.trim())
        .filter(|s| !s.is_empty())
        .unwrap_or(&existing.display_name);

    let metadata = if let Some(m) = body.get("metadata") {
        if !m.is_object() {
            return Err((
                StatusCode::BAD_REQUEST,
                "metadata must be a JSON object".to_string(),
            ));
        }
        m
    } else {
        &existing.metadata
    };

    // Update role if provided and valid.
    if let Some(role) = body.get("role").and_then(|v| v.as_str()) {
        if role != "admin" && role != "member" {
            return Err((
                StatusCode::BAD_REQUEST,
                "role must be 'admin' or 'member'".to_string(),
            ));
        }
        if role != existing.role {
            // Prevent demoting the last admin.
            if existing.role == "admin"
                && role == "member"
                && is_last_admin(store.as_ref(), &id)
                    .await
                    .map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e))?
            {
                return Err((
                    StatusCode::CONFLICT,
                    "Cannot demote the last admin".to_string(),
                ));
            }
            store
                .update_user_role(&id, role)
                .await
                .map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?;
            // Evict cached auth so role change takes effect immediately.
            if let Some(ref db_auth) = state.db_auth {
                db_auth.invalidate_user(&id).await;
            }
        }
    }

    store
        .update_user_profile(&id, display_name, metadata)
        .await
        .map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?;

    // Re-fetch the updated record to return consistent data.
    let updated = store
        .get_user(&id)
        .await
        .map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?
        .ok_or((StatusCode::NOT_FOUND, "User not found".to_string()))?;

    Ok(Json(serde_json::json!({
        "id": updated.id,
        "email": updated.email,
        "display_name": updated.display_name,
        "status": updated.status,
        "role": updated.role,
        "created_at": updated.created_at.to_rfc3339(),
        "updated_at": updated.updated_at.to_rfc3339(),
        "metadata": updated.metadata,
    })))
}

/// POST /api/admin/users/{id}/suspend — suspend a user.
pub async fn users_suspend_handler(
    State(state): State<Arc<GatewayState>>,
    AdminUser(_user): AdminUser,
    Path(id): Path<String>,
) -> Result<Json<serde_json::Value>, (StatusCode, String)> {
    let store = state.store.as_ref().ok_or((
        StatusCode::SERVICE_UNAVAILABLE,
        "Database not available".to_string(),
    ))?;

    // Verify the user exists.
    store
        .get_user(&id)
        .await
        .map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?
        .ok_or((StatusCode::NOT_FOUND, "User not found".to_string()))?;

    // Prevent suspending the last admin.
    if is_last_admin(store.as_ref(), &id)
        .await
        .map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e))?
    {
        return Err((
            StatusCode::CONFLICT,
            "Cannot suspend the last admin".to_string(),
        ));
    }

    store
        .update_user_status(&id, "suspended")
        .await
        .map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?;

    // Evict cached auth so suspension takes effect immediately.
    if let Some(ref db_auth) = state.db_auth {
        db_auth.invalidate_user(&id).await;
    }

    Ok(Json(serde_json::json!({
        "id": id,
        "status": "suspended",
    })))
}

/// POST /api/admin/users/{id}/activate — activate a user.
pub async fn users_activate_handler(
    State(state): State<Arc<GatewayState>>,
    AdminUser(_user): AdminUser,
    Path(id): Path<String>,
) -> Result<Json<serde_json::Value>, (StatusCode, String)> {
    let store = state.store.as_ref().ok_or((
        StatusCode::SERVICE_UNAVAILABLE,
        "Database not available".to_string(),
    ))?;

    // Verify the user exists.
    store
        .get_user(&id)
        .await
        .map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?
        .ok_or((StatusCode::NOT_FOUND, "User not found".to_string()))?;

    store
        .update_user_status(&id, "active")
        .await
        .map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?;

    // Evict cached auth so reactivation takes effect immediately.
    if let Some(ref db_auth) = state.db_auth {
        db_auth.invalidate_user(&id).await;
    }

    Ok(Json(serde_json::json!({
        "id": id,
        "status": "active",
    })))
}

/// DELETE /api/admin/users/{id} — delete a user and all their data.
pub async fn users_delete_handler(
    State(state): State<Arc<GatewayState>>,
    AdminUser(_user): AdminUser,
    Path(id): Path<String>,
) -> Result<Json<serde_json::Value>, (StatusCode, String)> {
    let store = state.store.as_ref().ok_or((
        StatusCode::SERVICE_UNAVAILABLE,
        "Database not available".to_string(),
    ))?;

    // Prevent deleting the last admin.
    if is_last_admin(store.as_ref(), &id)
        .await
        .map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e))?
    {
        return Err((
            StatusCode::CONFLICT,
            "Cannot delete the last admin".to_string(),
        ));
    }

    let deleted = store
        .delete_user(&id)
        .await
        .map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?;

    if !deleted {
        return Err((StatusCode::NOT_FOUND, "User not found".to_string()));
    }

    Ok(Json(serde_json::json!({
        "id": id,
        "deleted": true,
    })))
}

/// GET /api/profile — get the authenticated user's own profile.
pub async fn profile_get_handler(
    State(state): State<Arc<GatewayState>>,
    AuthenticatedUser(user): AuthenticatedUser,
) -> Result<Json<serde_json::Value>, (StatusCode, String)> {
    let store = state.store.as_ref().ok_or((
        StatusCode::SERVICE_UNAVAILABLE,
        "Database not available".to_string(),
    ))?;

    let record = store
        .get_user(&user.user_id)
        .await
        .map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?
        .ok_or((StatusCode::NOT_FOUND, "User not found".to_string()))?;

    Ok(Json(serde_json::json!({
        "id": record.id,
        "email": record.email,
        "display_name": record.display_name,
        "status": record.status,
        "role": record.role,
        "created_at": record.created_at.to_rfc3339(),
        "last_login_at": record.last_login_at.map(|dt| dt.to_rfc3339()),
    })))
}

/// PATCH /api/profile — update the authenticated user's own profile.
pub async fn profile_update_handler(
    State(state): State<Arc<GatewayState>>,
    AuthenticatedUser(user): AuthenticatedUser,
    Json(body): Json<serde_json::Value>,
) -> Result<Json<serde_json::Value>, (StatusCode, String)> {
    let store = state.store.as_ref().ok_or((
        StatusCode::SERVICE_UNAVAILABLE,
        "Database not available".to_string(),
    ))?;

    let current = store
        .get_user(&user.user_id)
        .await
        .map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?
        .ok_or((StatusCode::NOT_FOUND, "User not found".to_string()))?;

    let display_name = body
        .get("display_name")
        .and_then(|v| v.as_str())
        .map(|s| s.trim())
        .filter(|s| !s.is_empty())
        .unwrap_or(&current.display_name);
    let metadata = if let Some(m) = body.get("metadata") {
        if !m.is_object() {
            return Err((
                StatusCode::BAD_REQUEST,
                "metadata must be a JSON object".to_string(),
            ));
        }
        m
    } else {
        &current.metadata
    };

    store
        .update_user_profile(&user.user_id, display_name, metadata)
        .await
        .map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?;

    Ok(Json(serde_json::json!({
        "id": user.user_id,
        "display_name": display_name,
        "updated": true,
    })))
}

/// GET /api/admin/usage — per-user LLM usage stats.
pub async fn usage_stats_handler(
    State(state): State<Arc<GatewayState>>,
    AdminUser(_user): AdminUser,
    axum::extract::Query(params): axum::extract::Query<std::collections::HashMap<String, String>>,
) -> Result<Json<serde_json::Value>, (StatusCode, String)> {
    let store = state.store.as_ref().ok_or((
        StatusCode::SERVICE_UNAVAILABLE,
        "Database not available".to_string(),
    ))?;

    let user_id = params.get("user_id").map(|s| s.as_str());
    let period = params.get("period").map(|s| s.as_str()).unwrap_or("day");
    let since = match period {
        "week" => chrono::Utc::now() - chrono::Duration::days(7),
        "month" => chrono::Utc::now() - chrono::Duration::days(30),
        _ => chrono::Utc::now() - chrono::Duration::days(1),
    };

    let stats = store
        .user_usage_stats(user_id, since)
        .await
        .map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?;

    let entries: Vec<serde_json::Value> = stats
        .iter()
        .map(|s| {
            serde_json::json!({
                "user_id": s.user_id,
                "model": s.model,
                "call_count": s.call_count,
                "input_tokens": s.input_tokens,
                "output_tokens": s.output_tokens,
                "total_cost": s.total_cost.to_string(),
            })
        })
        .collect();

    Ok(Json(serde_json::json!({
        "period": period,
        "since": since.to_rfc3339(),
        "usage": entries,
    })))
}