solidb 1.0.2

A lightweight, high-performance structured database server written in Rust.
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
use super::system::AppState;
use crate::error::DbError;
use crate::server::auth::Claims;
use crate::server::authorization::{AuthorizationService, PermissionAction};
use crate::sync::{LogEntry, Operation};
use axum::{
    extract::{Extension, Path, State},
    http::HeaderMap,
    response::Json,
};
use serde::{Deserialize, Serialize};

#[derive(Debug, Deserialize)]
pub struct AuthParams {
    pub token: String,
    pub htmx: Option<String>,
}

#[derive(Debug, Deserialize)]
pub struct LoginRequest {
    pub username: String,
    pub password: String,
}

#[derive(Debug, Serialize)]
pub struct LoginResponse {
    pub token: String,
}

#[derive(Debug, Deserialize)]
pub struct ChangePasswordRequest {
    pub current_password: String,
    pub new_password: String,
}

#[derive(Debug, Serialize)]
pub struct ChangePasswordResponse {
    pub status: String,
}

// ==================== API Key Types ====================

#[derive(Debug, Deserialize)]
pub struct CreateApiKeyRequest {
    pub name: String,
    #[serde(default)]
    pub roles: Vec<String>,
    pub scoped_databases: Option<Vec<String>>,
}

#[derive(Debug, Serialize)]
pub struct CreateApiKeyResponse {
    pub id: String,
    pub name: String,
    pub key: String, // Raw key - only returned on creation!
    pub created_at: String,
    pub roles: Vec<String>,
    pub scoped_databases: Option<Vec<String>>,
}

#[derive(Debug, Serialize)]
pub struct ListApiKeysResponse {
    pub keys: Vec<crate::server::auth::ApiKeyListItem>,
}

#[derive(Debug, Serialize)]
pub struct DeleteApiKeyResponse {
    pub deleted: bool,
}

/// Handler for changing the current user's password
pub async fn change_password_handler(
    State(state): State<AppState>,
    axum::Extension(claims): axum::Extension<crate::server::auth::Claims>,
    Json(req): Json<ChangePasswordRequest>,
) -> Result<Json<ChangePasswordResponse>, DbError> {
    // 1. Get _system database
    let db = state.storage.get_database("_system")?;

    // 2. Get _admins collection
    let collection = db.system_collection("_admins")?;

    // 3. Get current user document
    let doc = match collection.get(&claims.sub) {
        Ok(d) => d,
        Err(DbError::DocumentNotFound(_)) => {
            return Err(DbError::BadRequest("User not found".to_string()));
        }
        Err(e) => return Err(e),
    };

    // 4. Deserialize user
    let user: crate::server::auth::User = serde_json::from_value(doc.to_value())
        .map_err(|_| DbError::InternalError("Corrupted user data".to_string()))?;

    // 5. Verify current password
    if !crate::server::auth::verify_password_blocking(&req.current_password, &user.password_hash)
        .await
    {
        return Err(DbError::BadRequest(
            "Current password is incorrect".to_string(),
        ));
    }

    if req.new_password.len() < 12 {
        return Err(DbError::BadRequest(
            "Password must be at least 12 characters".to_string(),
        ));
    }

    // 6. Hash new password
    let new_hash = crate::server::auth::hash_password_blocking(&req.new_password).await?;

    // 7. Update user document
    let updated_user = crate::server::auth::User {
        username: user.username.clone(),
        password_hash: new_hash,
    };

    let updated_value = serde_json::to_value(&updated_user)
        .map_err(|e| DbError::InternalError(format!("Serialization error: {}", e)))?;

    collection.update(&claims.sub, updated_value.clone())?;

    // Record write for replication
    if let Some(ref log) = state.replication_log {
        let entry = LogEntry {
            sequence: 0,             // Auto
            node_id: "".to_string(), // Auto
            database: "_system".to_string(),
            collection: "_admins".to_string(),
            operation: Operation::Update,
            key: claims.sub.clone(),
            data: serde_json::to_vec(&updated_value).ok(),
            timestamp: chrono::Utc::now().timestamp_millis() as u64,
            origin_sequence: None,
        };
        let _ = log.append(entry);
    }

    Ok(Json(ChangePasswordResponse {
        status: "password_updated".to_string(),
    }))
}

/// Handler for creating a new API key
pub async fn create_api_key_handler(
    State(state): State<AppState>,
    Extension(claims): Extension<Claims>,
    Json(req): Json<CreateApiKeyRequest>,
) -> Result<Json<CreateApiKeyResponse>, DbError> {
    AuthorizationService::check_permission(&claims, &state, PermissionAction::Admin, None).await?;
    // Generate key
    let (raw_key, key_hash) = crate::server::auth::AuthService::generate_api_key();

    // Create unique ID
    let id = uuid::Uuid::new_v4().to_string();
    let created_at = chrono::Utc::now().to_rfc3339();

    // Store in _system/_api_keys
    let db = state.storage.get_database("_system")?;

    // Ensure collection exists
    if let Err(DbError::CollectionNotFound(_)) =
        db.system_collection(crate::server::auth::API_KEYS_COLL)
    {
        db.create_collection(crate::server::auth::API_KEYS_COLL.to_string(), None)?;
    }

    let collection = db.system_collection(crate::server::auth::API_KEYS_COLL)?;

    if req.roles.is_empty() {
        return Err(DbError::BadRequest(
            "API keys must declare at least one role (empty roles no longer default to admin)"
                .to_string(),
        ));
    }
    let roles = req.roles.clone();

    let api_key = crate::server::auth::ApiKey {
        id: id.clone(),
        name: req.name.clone(),
        key_hash,
        created_at: created_at.clone(),
        roles: roles.clone(),
        scoped_databases: req.scoped_databases.clone(),
        expires_at: None,
    };

    let doc_value = serde_json::to_value(&api_key)
        .map_err(|e| DbError::InternalError(format!("Serialization error: {}", e)))?;

    collection.insert(doc_value.clone())?;

    // Update the in-memory API key cache so this new key can authenticate
    // requests immediately (O(1) lookup) without waiting for a lazy
    // full-collection scan on the first request.
    crate::server::auth::api_key_cache().insert(api_key.clone());

    // Record write for replication
    if let Some(ref log) = state.replication_log {
        let entry = LogEntry {
            sequence: 0,
            node_id: "".to_string(),
            database: "_system".to_string(),
            collection: crate::server::auth::API_KEYS_COLL.to_string(),
            operation: Operation::Insert,
            key: id.clone(),
            data: serde_json::to_vec(&doc_value).ok(),
            timestamp: chrono::Utc::now().timestamp_millis() as u64,
            origin_sequence: None,
        };
        let _ = log.append(entry);
    }

    tracing::info!("API key '{}' created", req.name);

    // Return response with the raw key (only time it's shown!)
    Ok(Json(CreateApiKeyResponse {
        id,
        name: req.name,
        key: raw_key,
        created_at,
        roles,
        scoped_databases: req.scoped_databases,
    }))
}

/// Handler for listing API keys (without the actual keys)
pub async fn list_api_keys_handler(
    State(state): State<AppState>,
    Extension(claims): Extension<Claims>,
) -> Result<Json<ListApiKeysResponse>, DbError> {
    AuthorizationService::check_permission(&claims, &state, PermissionAction::Admin, None).await?;
    let db = state.storage.get_database("_system")?;

    // Return empty if collection doesn't exist
    let collection = match db.system_collection(crate::server::auth::API_KEYS_COLL) {
        Ok(c) => c,
        Err(DbError::CollectionNotFound(_)) => {
            return Ok(Json(ListApiKeysResponse { keys: vec![] }));
        }
        Err(e) => return Err(e),
    };

    let mut keys = Vec::new();
    for doc in collection.scan(None) {
        let api_key: crate::server::auth::ApiKey = serde_json::from_value(doc.to_value())
            .map_err(|_| DbError::InternalError("Corrupted API key data".to_string()))?;

        keys.push(crate::server::auth::ApiKeyListItem {
            id: api_key.id,
            name: api_key.name,
            created_at: api_key.created_at,
            roles: api_key.roles,
            scoped_databases: api_key.scoped_databases,
        });
    }

    Ok(Json(ListApiKeysResponse { keys }))
}

/// Handler for deleting an API key
pub async fn delete_api_key_handler(
    State(state): State<AppState>,
    Extension(claims): Extension<Claims>,
    Path(key_id): Path<String>,
) -> Result<Json<DeleteApiKeyResponse>, DbError> {
    AuthorizationService::check_permission(&claims, &state, PermissionAction::Admin, None).await?;
    let db = state.storage.get_database("_system")?;
    let collection = db.system_collection(crate::server::auth::API_KEYS_COLL)?;

    collection.delete(&key_id)?;

    // Drop the key from the in-memory cache so a deleted key can no longer
    // authenticate (even if the raw key is still being presented).
    crate::server::auth::api_key_cache().remove_by_id(&key_id);

    // Record write for replication
    if let Some(ref log) = state.replication_log {
        let entry = LogEntry {
            sequence: 0,
            node_id: "".to_string(),
            database: "_system".to_string(),
            collection: crate::server::auth::API_KEYS_COLL.to_string(),
            operation: Operation::Delete,
            key: key_id.clone(),
            data: None,
            timestamp: chrono::Utc::now().timestamp_millis() as u64,
            origin_sequence: None,
        };
        let _ = log.append(entry);
    }

    tracing::info!("API key '{}' deleted", key_id);

    Ok(Json(DeleteApiKeyResponse { deleted: true }))
}

pub async fn login_handler(
    State(state): State<AppState>,
    // `Result` (not `Option`): tests build the router without connect info,
    // and axum 0.8's `Option<T>` extractor requires OptionalFromRequestParts,
    // which ConnectInfo doesn't implement.
    peer: Result<
        axum::extract::ConnectInfo<std::net::SocketAddr>,
        axum::extract::rejection::ExtensionRejection,
    >,
    headers: HeaderMap,
    Json(req): Json<LoginRequest>,
) -> Result<Json<LoginResponse>, DbError> {
    // Extract client IP for rate limiting. The socket peer address is
    // authoritative; X-Forwarded-For / X-Real-IP are client-controlled and
    // only consulted when SOLIDB_TRUST_PROXY_HEADERS is set (i.e. the
    // server is behind a proxy that overwrites them). Trusting them by
    // default would let one machine rotate fake IPs past the rate limit.
    let socket_ip = peer
        .ok()
        .map(|axum::extract::ConnectInfo(addr)| addr.ip().to_string());
    let client_ip = if crate::server::auth::trust_proxy_headers() {
        headers
            .get("X-Forwarded-For")
            .and_then(|h| h.to_str().ok())
            .and_then(|s| s.split(',').next())
            .map(|s| s.trim().to_string())
            .or_else(|| {
                headers
                    .get("X-Real-IP")
                    .and_then(|h| h.to_str().ok())
                    .map(|s| s.to_string())
            })
            .or(socket_ip)
            .unwrap_or_else(|| "unknown".to_string())
    } else {
        socket_ip.unwrap_or_else(|| "unknown".to_string())
    };

    // Rate limit on (client IP, username), counting only *failed* attempts:
    // parallel legitimate logins (e.g. a local test runner's workers all
    // hitting 127.0.0.1) can't exhaust the budget, and one app looping on
    // bad credentials doesn't lock other users out of the same host.
    let rate_bucket = format!("{}|{}", client_ip, req.username);
    crate::server::auth::check_rate_limit(&rate_bucket)?;
    // 1. Get _system database
    let db = state.storage.get_database("_system")?;

    // 2. Get _admins collection (create with default admin if missing)
    let collection = match db.system_collection("_admins") {
        Ok(c) => c,
        Err(DbError::CollectionNotFound(_)) => {
            // Collection doesn't exist - initialize auth (creates collection and default admin)
            tracing::warn!("_admins collection not found, initializing...");
            crate::server::auth::AuthService::init(
                &state.storage,
                state.replication_log.as_deref(),
                state.storage.data_dir(),
            )?;
            db.system_collection("_admins")?
        }
        Err(e) => return Err(e),
    };

    // 3. Check if collection is empty (also create default admin)
    if collection.count() == 0 {
        tracing::warn!("_admins collection empty, creating default admin...");
        crate::server::auth::AuthService::init(
            &state.storage,
            state.replication_log.as_deref(),
            state.storage.data_dir(),
        )?;
    }

    // 4. Get user document
    // We expect the username to be the _key
    let doc = match collection.get(&req.username) {
        Ok(d) => d,
        Err(DbError::DocumentNotFound(_)) => {
            crate::server::auth::record_login_failure(&rate_bucket);
            // Return generic error for security
            return Err(DbError::BadRequest("Invalid credentials".to_string()));
        }
        Err(e) => return Err(e),
    };

    // 5. Deserialize user
    let user: crate::server::auth::User = serde_json::from_value(doc.to_value()).map_err(|e| {
        tracing::error!("Failed to deserialize user '{}': {}", req.username, e);
        DbError::InternalError("Corrupted user data".to_string())
    })?;

    // 6. Verify password
    if !crate::server::auth::verify_password_blocking(&req.password, &user.password_hash).await {
        crate::server::auth::record_login_failure(&rate_bucket);
        tracing::warn!(
            "Password verification failed for user '{}' from {}",
            req.username,
            client_ip
        );
        return Err(DbError::BadRequest("Invalid credentials".to_string()));
    }

    // Successful login: reset this bucket's failure count.
    crate::server::auth::clear_login_failures(&rate_bucket);

    // 7. Generate Token with roles
    let roles = crate::server::auth::AuthService::get_user_roles(&state.storage, &user.username);
    let token =
        crate::server::auth::AuthService::create_jwt_with_roles(&user.username, roles, None)?;

    Ok(Json(LoginResponse { token }))
}

/// Response for livequery token endpoint
#[derive(Debug, Serialize)]
pub struct LiveQueryTokenResponse {
    pub token: String,
    pub expires_in: u32, // seconds until expiration
}

/// Generate a short-lived JWT token for live query WebSocket connections.
/// This endpoint requires authentication (regular JWT or API key).
/// The returned token is valid for 30 seconds - just enough to establish a WebSocket connection.
/// This allows clients to connect to live queries without exposing long-lived admin tokens.
pub async fn livequery_token_handler(
    Extension(claims): Extension<crate::server::auth::Claims>,
) -> Result<Json<LiveQueryTokenResponse>, DbError> {
    // The short-lived token inherits the requester's identity, roles and
    // database scope so WebSocket subscription authz applies to it.
    let token = crate::server::auth::AuthService::create_livequery_jwt(
        &claims.sub,
        claims.roles.clone(),
        claims.scoped_databases.clone(),
    )?;
    Ok(Json(LiveQueryTokenResponse {
        token,
        expires_in: 2,
    }))
}