pubky-homeserver 0.9.1

Pubky core's homeserver.
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
use axum::{
    extract::{Path, State},
    http::StatusCode,
    response::IntoResponse,
    Json,
};
use serde::Serialize;

use crate::shared::{
    user_quota::{UserQuota, UserQuotaPatch},
    HttpError, HttpResult, Z32Pubkey,
};

use super::super::app_state::AppState;

/// Response for `GET /users/{pubkey}/quota`.
///
/// Contains both the effective quota (overrides merged with system defaults)
/// and the raw per-user overrides, so callers can see what applies and what
/// was explicitly customised in a single request.
#[derive(Debug, Serialize)]
pub struct UserQuotaResponse {
    /// The effective quota: overrides merged with system defaults.
    /// All fields are always present (no fields omitted).
    pub effective: UserQuota,
    /// Only the per-user overrides. Fields using the system default are omitted.
    pub overrides: UserQuota,
}

/// GET /users/{pubkey}/quota — return both effective and override quotas.
pub async fn get_user_quota(
    State(state): State<AppState>,
    Path(pubkey): Path<Z32Pubkey>,
) -> HttpResult<impl IntoResponse> {
    let user = state
        .user_service
        .get_or_http_error(&pubkey.0, false)
        .await?;

    let overrides = user.quota();
    let effective =
        overrides.resolve_with_defaults(state.default_storage_mb, &state.default_quotas);

    Ok(Json(UserQuotaResponse {
        effective,
        overrides,
    }))
}

/// PATCH /users/{pubkey}/quota — update per-user custom limits.
///
/// Only fields present in the JSON body are updated; absent fields are left unchanged.
/// All fields follow the same semantics:
/// - absent → keep existing value
/// - `null` → reset to Default (use system default)
/// - `"unlimited"` → Unlimited (no limit)
/// - value → explicit custom limit
pub async fn patch_user_quota(
    State(state): State<AppState>,
    Path(pubkey): Path<Z32Pubkey>,
    Json(patch): Json<UserQuotaPatch>,
) -> HttpResult<impl IntoResponse> {
    patch
        .validate()
        .map_err(|e| HttpError::new_with_message(StatusCode::UNPROCESSABLE_ENTITY, e))?;

    state.user_service.patch_quota(&pubkey.0, &patch).await?;

    Ok(StatusCode::OK)
}

#[cfg(test)]
mod tests {
    use std::str::FromStr;

    use axum_test::TestServer;

    use super::*;
    use crate::admin_server::app::create_app;
    use crate::data_directory::quota_config::BandwidthQuota;
    use crate::persistence::files::FileService;
    use crate::AppContext;

    fn create_test_server(context: &AppContext) -> TestServer {
        TestServer::new(create_app(
            AppState::new(
                context.sql_db.clone(),
                FileService::new_from_context(context).unwrap(),
                "",
                context.user_service.clone(),
            ),
            "test",
        ))
        .unwrap()
    }

    /// Create a test server with system-wide defaults configured.
    fn create_test_server_with_defaults(context: &AppContext) -> TestServer {
        use crate::data_directory::DefaultQuotasToml;

        let mut state = AppState::new(
            context.sql_db.clone(),
            FileService::new_from_context(context).unwrap(),
            "",
            context.user_service.clone(),
        );
        state.default_storage_mb = Some(100);
        state.default_quotas = DefaultQuotasToml {
            rate_read: Some(BandwidthQuota::from_str("10mb/s").unwrap()),
            rate_write: Some(BandwidthQuota::from_str("5mb/s").unwrap()),
            ..Default::default()
        };
        TestServer::new(create_app(state, "test")).unwrap()
    }

    #[tokio::test]
    #[pubky_test_utils::test]
    async fn test_user_quota_crud() {
        use crate::persistence::sql::user::UserRepository;
        use pubky_common::crypto::Keypair;

        let context = AppContext::test().await;
        let server = create_test_server(&context);
        let keypair = Keypair::random();
        let pubkey = keypair.public_key();

        UserRepository::create(&pubkey, &mut context.sql_db.pool().into())
            .await
            .unwrap();

        let url = format!("/users/{}/quota", pubkey.z32());

        // GET fresh user: overrides empty, effective all "unlimited" (no system defaults)
        let response = server
            .get(&url)
            .add_header("X-Admin-Password", "test")
            .expect_success()
            .await;
        response.assert_status_ok();
        let json: serde_json::Value = response.json();
        assert_eq!(json["overrides"], serde_json::json!({}));
        assert_eq!(json["effective"]["storage_quota_mb"], "unlimited");
        assert_eq!(json["effective"]["rate_read"], "unlimited");
        assert_eq!(json["effective"]["rate_write"], "unlimited");

        // PATCH with partial body (absent fields = keep existing)
        let body = serde_json::json!({
            "storage_quota_mb": 500,
            "rate_read": "100mb/m"
        });
        server
            .patch(&url)
            .add_header("X-Admin-Password", "test")
            .content_type("application/json")
            .bytes(serde_json::to_vec(&body).unwrap().into())
            .expect_success()
            .await;

        // GET after PATCH: effective shows overrides + defaults, overrides shows only patched
        let response = server
            .get(&url)
            .add_header("X-Admin-Password", "test")
            .expect_success()
            .await;
        let json: serde_json::Value = response.json();
        assert_eq!(json["effective"]["storage_quota_mb"], 500);
        assert_eq!(json["effective"]["rate_read"], "100mb/m");
        assert_eq!(json["effective"]["rate_write"], "unlimited");
        assert_eq!(json["overrides"]["storage_quota_mb"], 500);
        assert_eq!(json["overrides"]["rate_read"], "100mb/m");
        assert!(json["overrides"].get("rate_write").is_none());

        // PATCH with null fields to reset to Default
        let body = serde_json::json!({
            "storage_quota_mb": null,
            "rate_read": null,
            "rate_write": null
        });
        server
            .patch(&url)
            .add_header("X-Admin-Password", "test")
            .content_type("application/json")
            .bytes(serde_json::to_vec(&body).unwrap().into())
            .expect_success()
            .await;

        // GET after reset: overrides empty again
        let response = server
            .get(&url)
            .add_header("X-Admin-Password", "test")
            .expect_success()
            .await;
        let json: serde_json::Value = response.json();
        assert_eq!(json["overrides"], serde_json::json!({}));
    }

    /// GET resolves Default fields against system-wide defaults in `effective`.
    #[tokio::test]
    #[pubky_test_utils::test]
    async fn test_get_effective_resolves_defaults() {
        use crate::persistence::sql::user::UserRepository;
        use pubky_common::crypto::Keypair;

        let context = AppContext::test().await;
        let server = create_test_server_with_defaults(&context);
        let keypair = Keypair::random();
        let pubkey = keypair.public_key();

        UserRepository::create(&pubkey, &mut context.sql_db.pool().into())
            .await
            .unwrap();

        let url = format!("/users/{}/quota", pubkey.z32());

        // Fresh user: effective shows system defaults, overrides empty
        let response = server
            .get(&url)
            .add_header("X-Admin-Password", "test")
            .expect_success()
            .await;
        let json: serde_json::Value = response.json();
        assert_eq!(json["effective"]["storage_quota_mb"], 100);
        assert_eq!(json["effective"]["rate_read"], "10mb/s");
        assert_eq!(json["effective"]["rate_write"], "5mb/s");
        assert_eq!(json["overrides"], serde_json::json!({}));

        // PATCH one field to a custom value
        let body = serde_json::json!({"storage_quota_mb": 500});
        server
            .patch(&url)
            .add_header("X-Admin-Password", "test")
            .content_type("application/json")
            .bytes(serde_json::to_vec(&body).unwrap().into())
            .expect_success()
            .await;

        // effective: storage overridden, rates still show system defaults
        let response = server
            .get(&url)
            .add_header("X-Admin-Password", "test")
            .expect_success()
            .await;
        let json: serde_json::Value = response.json();
        assert_eq!(json["effective"]["storage_quota_mb"], 500);
        assert_eq!(json["effective"]["rate_read"], "10mb/s");
        assert_eq!(json["effective"]["rate_write"], "5mb/s");
        assert_eq!(json["overrides"]["storage_quota_mb"], 500);
        assert!(json["overrides"].get("rate_read").is_none());

        // PATCH rate_read to unlimited
        let body = serde_json::json!({"rate_read": "unlimited"});
        server
            .patch(&url)
            .add_header("X-Admin-Password", "test")
            .content_type("application/json")
            .bytes(serde_json::to_vec(&body).unwrap().into())
            .expect_success()
            .await;

        // effective: unlimited overrides the system default
        let response = server
            .get(&url)
            .add_header("X-Admin-Password", "test")
            .expect_success()
            .await;
        let json: serde_json::Value = response.json();
        assert_eq!(json["effective"]["storage_quota_mb"], 500);
        assert_eq!(json["effective"]["rate_read"], "unlimited");
        assert_eq!(json["effective"]["rate_write"], "5mb/s");
        // overrides shows only the two explicit overrides
        assert_eq!(json["overrides"]["storage_quota_mb"], 500);
        assert_eq!(json["overrides"]["rate_read"], "unlimited");
        assert!(json["overrides"].get("rate_write").is_none());
    }

    #[tokio::test]
    #[pubky_test_utils::test]
    async fn test_user_quota_invalid_rate_rejected() {
        use crate::persistence::sql::user::UserRepository;
        use pubky_common::crypto::Keypair;

        let context = AppContext::test().await;
        let server = create_test_server(&context);
        let keypair = Keypair::random();
        let pubkey = keypair.public_key();

        UserRepository::create(&pubkey, &mut context.sql_db.pool().into())
            .await
            .unwrap();

        let url = format!("/users/{}/quota", pubkey.z32());

        let body = serde_json::json!({
            "rate_read": "rubbish"
        });
        let response = server
            .patch(&url)
            .add_header("X-Admin-Password", "test")
            .content_type("application/json")
            .bytes(serde_json::to_vec(&body).unwrap().into())
            .expect_failure()
            .await;
        response.assert_status(axum::http::StatusCode::UNPROCESSABLE_ENTITY);
    }

    #[tokio::test]
    #[pubky_test_utils::test]
    async fn test_user_quota_nonexistent_user() {
        let context = AppContext::test().await;
        let server = create_test_server(&context);
        let pubkey = pubky_common::crypto::Keypair::random().public_key();

        let url = format!("/users/{}/quota", pubkey.z32());

        let response = server
            .get(&url)
            .add_header("X-Admin-Password", "test")
            .expect_failure()
            .await;
        response.assert_status(axum::http::StatusCode::NOT_FOUND);
    }

    /// Default vs Unlimited are distinguishable in the overrides section.
    #[tokio::test]
    #[pubky_test_utils::test]
    async fn test_default_vs_unlimited_distinguishable() {
        use crate::persistence::sql::user::UserRepository;
        use pubky_common::crypto::Keypair;

        let context = AppContext::test().await;
        let server = create_test_server(&context);
        let keypair = Keypair::random();
        let pubkey = keypair.public_key();

        UserRepository::create(&pubkey, &mut context.sql_db.pool().into())
            .await
            .unwrap();

        let url = format!("/users/{}/quota", pubkey.z32());

        // PATCH: rate_read = "unlimited", rate_write absent (unchanged = Default)
        let body = serde_json::json!({
            "rate_read": "unlimited"
        });
        server
            .patch(&url)
            .add_header("X-Admin-Password", "test")
            .content_type("application/json")
            .bytes(serde_json::to_vec(&body).unwrap().into())
            .expect_success()
            .await;

        let response = server
            .get(&url)
            .add_header("X-Admin-Password", "test")
            .expect_success()
            .await;
        let json: serde_json::Value = response.json();
        // Unlimited → present as "unlimited" in overrides
        assert_eq!(json["overrides"]["rate_read"], "unlimited");
        // Default → absent from overrides
        assert!(json["overrides"].get("rate_write").is_none());
        assert!(json["overrides"].get("storage_quota_mb").is_none());
    }

    /// PATCH only updates the fields present in the body; absent fields are left unchanged.
    #[tokio::test]
    #[pubky_test_utils::test]
    async fn test_patch_user_quota_merges() {
        use crate::persistence::sql::user::UserRepository;
        use pubky_common::crypto::Keypair;

        let context = AppContext::test().await;
        let server = create_test_server(&context);
        let keypair = Keypair::random();
        let pubkey = keypair.public_key();

        UserRepository::create(&pubkey, &mut context.sql_db.pool().into())
            .await
            .unwrap();

        let url = format!("/users/{}/quota", pubkey.z32());

        // 1) Set all fields
        let body = serde_json::json!({
            "storage_quota_mb": 500,
            "rate_read": "100mb/m",
            "rate_write": "50mb/m"
        });
        server
            .patch(&url)
            .add_header("X-Admin-Password", "test")
            .content_type("application/json")
            .bytes(serde_json::to_vec(&body).unwrap().into())
            .expect_success()
            .await;

        // 2) PATCH only storage_quota_mb — others should be unchanged
        let patch = serde_json::json!({
            "storage_quota_mb": 200
        });
        server
            .patch(&url)
            .add_header("X-Admin-Password", "test")
            .content_type("application/json")
            .bytes(serde_json::to_vec(&patch).unwrap().into())
            .expect_success()
            .await;

        // 3) Verify overrides: storage_quota_mb changed, all others preserved
        let response = server
            .get(&url)
            .add_header("X-Admin-Password", "test")
            .expect_success()
            .await;
        let json: serde_json::Value = response.json();
        assert_eq!(json["overrides"]["storage_quota_mb"], 200);
        assert_eq!(json["overrides"]["rate_read"], "100mb/m");
        assert_eq!(json["overrides"]["rate_write"], "50mb/m");

        // 4) PATCH rate_write to "unlimited", leave rest unchanged
        let patch = serde_json::json!({
            "rate_write": "unlimited"
        });
        server
            .patch(&url)
            .add_header("X-Admin-Password", "test")
            .content_type("application/json")
            .bytes(serde_json::to_vec(&patch).unwrap().into())
            .expect_success()
            .await;

        let response = server
            .get(&url)
            .add_header("X-Admin-Password", "test")
            .expect_success()
            .await;
        let json: serde_json::Value = response.json();
        assert_eq!(json["overrides"]["storage_quota_mb"], 200);
        assert_eq!(json["overrides"]["rate_read"], "100mb/m");
        assert_eq!(json["overrides"]["rate_write"], "unlimited");

        // 5) Empty PATCH should change nothing
        let patch = serde_json::json!({});
        server
            .patch(&url)
            .add_header("X-Admin-Password", "test")
            .content_type("application/json")
            .bytes(serde_json::to_vec(&patch).unwrap().into())
            .expect_success()
            .await;

        let response = server
            .get(&url)
            .add_header("X-Admin-Password", "test")
            .expect_success()
            .await;
        let json: serde_json::Value = response.json();
        assert_eq!(json["overrides"]["storage_quota_mb"], 200);
        assert_eq!(json["overrides"]["rate_read"], "100mb/m");
        assert_eq!(json["overrides"]["rate_write"], "unlimited");
    }

    /// PATCH with invalid rate string should be rejected with 422.
    #[tokio::test]
    #[pubky_test_utils::test]
    async fn test_patch_invalid_rate_rejected() {
        use crate::persistence::sql::user::UserRepository;
        use pubky_common::crypto::Keypair;

        let context = AppContext::test().await;
        let server = create_test_server(&context);
        let keypair = Keypair::random();
        let pubkey = keypair.public_key();

        UserRepository::create(&pubkey, &mut context.sql_db.pool().into())
            .await
            .unwrap();

        let url = format!("/users/{}/quota", pubkey.z32());
        let patch = serde_json::json!({
            "rate_read": "rubbish"
        });
        let response = server
            .patch(&url)
            .add_header("X-Admin-Password", "test")
            .content_type("application/json")
            .bytes(serde_json::to_vec(&patch).unwrap().into())
            .expect_failure()
            .await;
        response.assert_status(axum::http::StatusCode::UNPROCESSABLE_ENTITY);
    }
}