pubky-homeserver 0.10.0

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
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
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
use crate::persistence::sql::entry::{EntryEntity, EntryRepository};
use crate::shared::{HttpError, HttpResult};
use crate::{
    client_server::{
        auth::{has_read_permission, AuthSession},
        middleware::pubky_host::PubkyHost,
        query_params::ListQueryParams,
        AppState,
    },
    shared::webdav::{EntryPath, WebDavPathAxum},
};
use axum::{
    body::Body,
    extract::{Path, State},
    http::{header, HeaderMap, HeaderValue, Response, StatusCode},
    response::IntoResponse,
};
use httpdate::HttpDate;
use sqlx::types::chrono::{DateTime, Utc};
use std::str::FromStr;
use std::time::SystemTime;

pub async fn head(
    State(state): State<AppState>,
    session: Option<AuthSession>,
    pubky: PubkyHost,
    Path(path): Path<WebDavPathAxum>,
) -> HttpResult<impl IntoResponse> {
    has_read_permission(session.as_ref(), Some(pubky.public_key()), path.inner())?;

    state
        .user_service
        .get_or_http_error(pubky.public_key(), false)
        .await?;

    let entry_path = EntryPath::new(pubky.public_key().clone(), path.inner().clone());

    let entry = state
        .file_service
        .get_info(&entry_path, &mut state.sql_db.pool().into())
        .await?;
    let response = entry.to_response_headers().into_response();
    Ok(response)
}

#[axum::debug_handler]
pub async fn get(
    State(state): State<AppState>,
    headers: HeaderMap,
    session: Option<AuthSession>,
    pubky: PubkyHost,
    Path(path): Path<WebDavPathAxum>,
    params: ListQueryParams,
) -> HttpResult<impl IntoResponse> {
    has_read_permission(session.as_ref(), Some(pubky.public_key()), path.inner())?;

    let public_key = pubky.public_key().clone();
    let entry_path = EntryPath::new(public_key.clone(), path.inner().clone());
    if entry_path.path().is_directory() {
        return list(state, &entry_path, params).await;
    }

    let entry = state
        .file_service
        .get_info(&entry_path, &mut state.sql_db.pool().into())
        .await?;

    // Per RFC 7232 §3: If-None-Match has precedence over If-Modified-Since.
    if let Some(request_etag) = headers
        .get(header::IF_NONE_MATCH)
        .and_then(|h| h.to_str().ok())
    {
        let current_etag = format!(
            "\"{}\"",
            base64::Engine::encode(
                &base64::engine::general_purpose::STANDARD,
                entry.content_hash.as_bytes()
            )
        );
        if request_etag
            .trim()
            .split(',')
            .map(|s| s.trim())
            .any(|tag| tag == current_etag)
        {
            return not_modified_response(&entry);
        }
    } else if let Some(condition_http_date) = headers
        .get(header::IF_MODIFIED_SINCE)
        .and_then(|h| h.to_str().ok())
        .and_then(|s| HttpDate::from_str(s).ok())
    {
        let entry_http_date: HttpDate = to_http_date(&entry.modified_at);
        if condition_http_date >= entry_http_date {
            return not_modified_response(&entry);
        }
    }

    let stream = state.file_service.get_stream(&entry_path).await?;
    let body_stream = Body::from_stream(stream);
    let mut response = entry.to_response_headers().into_response();
    *response.body_mut() = body_stream;
    Ok(response)
}

async fn list(
    state: AppState,
    entry_path: &EntryPath,
    params: ListQueryParams,
) -> HttpResult<Response<Body>> {
    let contains_dir =
        EntryRepository::contains_directory(entry_path, &mut state.sql_db.pool().into()).await?;
    if !contains_dir {
        return Err(HttpError::new_with_message(
            StatusCode::NOT_FOUND,
            "Directory Not Found",
        ));
    }

    let parsed_cursor = match parse_cursor(params.cursor) {
        Ok(cursor) => cursor,
        Err(_) => {
            return Err(HttpError::new_with_message(
                StatusCode::BAD_REQUEST,
                "Invalid cursor",
            ))
        }
    };

    let entries = if params.shallow {
        EntryRepository::list_shallow(
            entry_path,
            params.limit,
            parsed_cursor,
            params.reverse,
            &mut state.sql_db.pool().into(),
        )
        .await?
    } else {
        EntryRepository::list_deep(
            entry_path,
            params.limit,
            parsed_cursor,
            params.reverse,
            &mut state.sql_db.pool().into(),
        )
        .await?
    };
    let pubky_urls = entries
        .iter()
        .map(|entry| format!("pubky://{}", entry))
        .collect::<Vec<_>>();

    Ok(Response::builder()
        .status(StatusCode::OK)
        .header(header::CONTENT_TYPE, "text/plain")
        .body(Body::from(pubky_urls.join("\n")))?)
}

/// Parse the cursor if it is present.
/// If the cursor is not present, returns None.
/// If the cursor is present and valid, returns the EntryPath.
fn parse_cursor(cursor: Option<String>) -> anyhow::Result<Option<EntryPath>> {
    let cursor = match cursor {
        Some(cursor) => cursor,
        None => return Ok(None),
    };

    let cursor = cursor.trim_start_matches("pubky://");
    let path = EntryPath::from_str(cursor)?;
    Ok(Some(path))
}

/// Creates the Not Modified response based on the entry data.
fn not_modified_response(entry: &EntryEntity) -> HttpResult<Response<Body>> {
    Ok(Response::builder()
        .status(StatusCode::NOT_MODIFIED)
        .header(
            header::ETAG,
            format!(
                "\"{}\"",
                base64::Engine::encode(
                    &base64::engine::general_purpose::STANDARD,
                    entry.content_hash.as_bytes()
                )
            ),
        )
        .header(
            header::LAST_MODIFIED,
            to_http_date(&entry.modified_at).to_string().as_str(),
        )
        .header(header::VARY, "pubky-host")
        .header(header::CACHE_CONTROL, "private, must-revalidate")
        .body(Body::empty())?)
}

/// Convert a `NaiveDateTime` to a `HttpDate`.
fn to_http_date(date: &sqlx::types::chrono::NaiveDateTime) -> HttpDate {
    let sys_datetime = SystemTime::from(DateTime::<Utc>::from_naive_utc_and_offset(*date, Utc));
    httpdate::HttpDate::from(sys_datetime)
}

impl EntryEntity {
    pub fn to_response_headers(&self) -> HeaderMap {
        let mut headers = HeaderMap::new();
        headers.insert(header::CONTENT_LENGTH, self.content_length.into());
        headers.insert(
            header::LAST_MODIFIED,
            HeaderValue::from_str(to_http_date(&self.modified_at).to_string().as_str())
                .expect("http date is valid header value"),
        );
        headers.insert(
            header::CONTENT_TYPE,
            self.content_type
                .clone()
                .try_into()
                .or(HeaderValue::from_str(""))
                .expect("valid header value"),
        );
        headers.insert(
            header::ETAG,
            format!(
                "\"{}\"",
                base64::Engine::encode(
                    &base64::engine::general_purpose::STANDARD,
                    self.content_hash.as_bytes()
                )
            )
            .try_into()
            .expect("base64 string is valid"),
        );
        // tenant-aware caching
        headers.insert(header::VARY, HeaderValue::from_static("pubky-host"));
        headers.insert(
            header::CACHE_CONTROL,
            HeaderValue::from_static("private, must-revalidate"),
        );
        headers
    }
}

#[cfg(test)]
mod tests {
    use axum::http::{header, HeaderMap, Method, StatusCode};
    use axum::Router;
    use axum_test::TestServer;
    use pubky_common::{
        auth::AuthToken,
        capabilities::Capability,
        crypto::{Keypair, PublicKey},
    };

    use crate::app_context::AppContext;
    use crate::client_server::ClientServer;

    async fn create_user_with_capabilities(
        server: &axum_test::TestServer,
        keypair: &Keypair,
        capabilities: Vec<Capability>,
    ) -> anyhow::Result<String> {
        let auth_token = AuthToken::sign(keypair, capabilities);
        let body_bytes: axum::body::Bytes = auth_token.serialize().into();
        let response = server
            .post("/signup")
            .add_header("host", keypair.public_key().to_z32())
            .bytes(body_bytes)
            .expect_success()
            .await;

        let header_value = response
            .headers()
            .get(header::SET_COOKIE)
            .and_then(|h| h.to_str().ok())
            .expect("should return a set-cookie header")
            .to_string();

        Ok(header_value)
    }

    pub async fn create_root_user(
        server: &axum_test::TestServer,
        keypair: &Keypair,
    ) -> anyhow::Result<String> {
        create_user_with_capabilities(server, keypair, vec![Capability::root()]).await
    }

    async fn sign_in_with_capabilities(
        server: &axum_test::TestServer,
        keypair: &Keypair,
        capabilities: Vec<Capability>,
    ) -> anyhow::Result<String> {
        let auth_token = AuthToken::sign(keypair, capabilities);
        let body_bytes: axum::body::Bytes = auth_token.serialize().into();
        let response = server
            .post("/session")
            .add_header("host", keypair.public_key().to_z32())
            .bytes(body_bytes)
            .expect_success()
            .await;

        Ok(response
            .headers()
            .get(header::SET_COOKIE)
            .and_then(|h| h.to_str().ok())
            .expect("should return a set-cookie header")
            .to_string())
    }

    async fn create_environment_with_keypair(
    ) -> anyhow::Result<(AppContext, Router, TestServer, Keypair, String)> {
        let context = AppContext::test().await;
        let router = ClientServer::create_router(&context)?;
        let server = axum_test::TestServer::new(router.clone()).unwrap();

        let keypair = Keypair::random();
        let cookie = create_root_user(&server, &keypair).await?.to_string();

        Ok((context, router, server, keypair, cookie))
    }

    pub async fn create_environment(
    ) -> anyhow::Result<(AppContext, Router, TestServer, PublicKey, String)> {
        let (context, router, server, keypair, cookie) = create_environment_with_keypair().await?;
        let public_key = keypair.public_key();

        Ok((context, router, server, public_key, cookie))
    }

    fn header_value(headers: &HeaderMap, name: header::HeaderName) -> Option<&str> {
        headers.get(name).and_then(|value| value.to_str().ok())
    }

    fn assert_private_cache_policy(headers: &HeaderMap) {
        assert_eq!(
            header_value(headers, header::CACHE_CONTROL),
            Some("no-store")
        );
        assert_eq!(
            header_value(headers, header::VARY),
            Some("pubky-host, Authorization, Cookie")
        );
    }

    fn assert_no_validators(headers: &HeaderMap) {
        assert!(!headers.contains_key(header::ETAG));
        assert!(!headers.contains_key(header::LAST_MODIFIED));
    }

    fn assert_validators_present(headers: &HeaderMap) {
        assert!(headers.contains_key(header::ETAG));
        assert!(headers.contains_key(header::LAST_MODIFIED));
    }

    #[tokio::test]
    #[pubky_test_utils::test]
    async fn invalid_path_aliases_cannot_modify_canonical_file() {
        let (_, _, server, public_key, cookie) = create_environment().await.unwrap();

        server
            .put("/pub/report")
            .add_header("host", public_key.z32())
            .add_header(header::COOKIE, cookie.clone())
            .text("original")
            .expect_success()
            .await;

        for alias in [
            "/pub/report%20",
            "/pub/report%C2%A0",
            "/pub/report%E3%80%80",
            "/pub/scope/%5C..%5Creport",
        ] {
            server
                .put(alias)
                .add_header("host", public_key.z32())
                .add_header(header::COOKIE, cookie.clone())
                .text("overwritten")
                .expect_failure()
                .await
                .assert_status(StatusCode::BAD_REQUEST);

            server
                .delete(alias)
                .add_header("host", public_key.z32())
                .add_header(header::COOKIE, cookie.clone())
                .expect_failure()
                .await
                .assert_status(StatusCode::BAD_REQUEST);
        }

        let response = server
            .get("/pub/report")
            .add_header("host", public_key.z32())
            .expect_success()
            .await;
        assert_eq!(response.text(), "original");
    }

    #[tokio::test]
    #[pubky_test_utils::test]
    async fn if_last_modified() {
        let (_context, _router, server, public_key, cookie) = create_environment().await.unwrap();

        let data = vec![1_u8, 2, 3, 4, 5];

        server
            .put("/pub/foo")
            .add_header("host", public_key.z32())
            .add_header(header::COOKIE, cookie)
            .bytes(data.into())
            .expect_success()
            .await;

        let response = server
            .get("/pub/foo")
            .add_header("host", public_key.z32())
            .expect_success()
            .await;

        let response = server
            .get("/pub/foo")
            .add_header("host", public_key.z32())
            .add_header(
                header::IF_MODIFIED_SINCE,
                response.headers().get(header::LAST_MODIFIED).unwrap(),
            )
            .await;

        response.assert_status(StatusCode::NOT_MODIFIED);
    }

    #[tokio::test]
    #[pubky_test_utils::test]
    async fn if_none_match() {
        let (_, _, server, public_key, cookie) = create_environment().await.unwrap();

        let data = vec![1_u8, 2, 3, 4, 5];

        server
            .put("/pub/foo")
            .add_header("host", public_key.z32())
            .add_header(header::COOKIE, cookie)
            .bytes(data.into())
            .expect_success()
            .await;

        let response = server
            .get("/pub/foo")
            .add_header("host", public_key.z32())
            .expect_success()
            .await;

        let response = server
            .get("/pub/foo")
            .add_header("host", public_key.z32())
            .add_header(
                header::IF_NONE_MATCH,
                response.headers().get(header::ETAG).unwrap(),
            )
            .await;

        response.assert_status(StatusCode::NOT_MODIFIED);
    }

    #[tokio::test]
    #[pubky_test_utils::test]
    async fn test_content_with_magic_bytes() {
        let (_, _, server, public_key, cookie) = create_environment().await.unwrap();

        let data = vec![0x89_u8, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A];

        server
            .put("/pub/foo")
            .add_header("host", public_key.z32())
            .add_header(header::COOKIE, cookie)
            .bytes(data.into())
            .expect_success()
            .await;

        let response = server
            .get("/pub/foo")
            .add_header("host", public_key.z32())
            .await;

        response.assert_header(header::CONTENT_TYPE, "image/png");
    }

    #[tokio::test]
    #[pubky_test_utils::test]
    async fn test_content_by_extension() {
        let (_, _, server, public_key, cookie) = create_environment().await.unwrap();

        let data = vec![108, 111, 114, 101, 109, 32, 105, 112, 115, 117, 109];

        server
            .put("/pub/text.txt")
            .add_header("host", public_key.z32())
            .add_header(header::COOKIE, cookie)
            .bytes(data.into())
            .expect_success()
            .await;

        let response = server
            .get("/pub/text.txt")
            .add_header("host", public_key.z32())
            .await;

        response.assert_header(header::CONTENT_TYPE, "text/plain");
    }
    #[tokio::test]
    async fn if_none_match_precedes_if_modified_since() {
        let (_, _, server, public_key, cookie) = create_environment().await.unwrap();

        // Write v1
        server
            .put("/pub/foo")
            .add_header("host", public_key.z32())
            .add_header(header::COOKIE, cookie.clone())
            .bytes(Vec::from("alice").into())
            .expect_success()
            .await;

        // Baseline GET to capture ETag and Last-Modified
        let base = server
            .get("/pub/foo")
            .add_header("host", public_key.z32())
            .expect_success()
            .await;
        let etag_v1 = base
            .headers()
            .get(header::ETAG)
            .unwrap()
            .to_str()
            .unwrap()
            .to_string();
        let lm_v1 = base.headers().get(header::LAST_MODIFIED).unwrap().clone();

        // Overwrite with different content but same-second timestamp likely
        server
            .put("/pub/foo")
            .add_header("host", public_key.z32())
            .add_header(header::COOKIE, cookie.clone())
            .bytes(Vec::from("bob").into())
            .expect_success()
            .await;

        // Conditional GET that sends both validators; must return 200 because ETag changed.
        let r = server
            .get("/pub/foo")
            .add_header("host", public_key.z32())
            .add_header(header::IF_NONE_MATCH, etag_v1)
            .add_header(header::IF_MODIFIED_SINCE, lm_v1)
            .await;
        r.assert_status(StatusCode::OK);
    }

    #[tokio::test]
    #[pubky_test_utils::test]
    async fn pub_get_stays_anonymous_after_dual_root_switch() {
        // Regression: switching the read extractor to the dual-root one must
        // not break anonymous `/pub/` reads.
        let (_, _, server, public_key, cookie) = create_environment().await.unwrap();

        server
            .put("/pub/foo.txt")
            .add_header("host", public_key.z32())
            .add_header(header::COOKIE, cookie)
            .bytes(Vec::from("public").into())
            .expect_success()
            .await;

        // No cookie → still 200.
        server
            .get("/pub/foo.txt")
            .add_header("host", public_key.z32())
            .expect_success()
            .await;
    }

    #[tokio::test]
    #[pubky_test_utils::test]
    async fn priv_get_requires_authentication() {
        let (_, _, server, public_key, cookie) = create_environment().await.unwrap();

        // Owner writes a private file.
        server
            .put("/priv/secret.txt")
            .add_header("host", public_key.z32())
            .add_header(header::COOKIE, cookie.clone())
            .bytes(Vec::from("top secret").into())
            .expect_success()
            .await;

        // Anonymous read → 401.
        server
            .get("/priv/secret.txt")
            .add_header("host", public_key.z32())
            .await
            .assert_status(StatusCode::UNAUTHORIZED);

        // Owner read → 200 with the body.
        let resp = server
            .get("/priv/secret.txt")
            .add_header("host", public_key.z32())
            .add_header(header::COOKIE, cookie)
            .expect_success()
            .await;
        assert_eq!(resp.text(), "top secret");
    }

    #[tokio::test]
    #[pubky_test_utils::test]
    async fn priv_get_is_not_an_existence_oracle() {
        let (_, _, server, public_key, cookie) = create_environment().await.unwrap();

        // One private file exists; another path is absent.
        server
            .put("/priv/exists.txt")
            .add_header("host", public_key.z32())
            .add_header(header::COOKIE, cookie.clone())
            .bytes(Vec::from("data").into())
            .expect_success()
            .await;

        // Anonymous: existing and absent must return the SAME status (401), so
        // the response cant be used to probe which private paths exist.
        server
            .get("/priv/exists.txt")
            .add_header("host", public_key.z32())
            .await
            .assert_status(StatusCode::UNAUTHORIZED);
        server
            .get("/priv/absent.txt")
            .add_header("host", public_key.z32())
            .await
            .assert_status(StatusCode::UNAUTHORIZED);

        // Authorized: 404 for the absent file.
        server
            .get("/priv/absent.txt")
            .add_header("host", public_key.z32())
            .add_header(header::COOKIE, cookie)
            .await
            .assert_status(StatusCode::NOT_FOUND);
    }

    #[tokio::test]
    #[pubky_test_utils::test]
    async fn priv_head_mirrors_get() {
        let (_, _, server, public_key, cookie) = create_environment().await.unwrap();

        server
            .put("/priv/secret.txt")
            .add_header("host", public_key.z32())
            .add_header(header::COOKIE, cookie.clone())
            .bytes(Vec::from("hello").into())
            .expect_success()
            .await;

        // Anonymous HEAD → 401.
        server
            .method(Method::HEAD, "/priv/secret.txt")
            .add_header("host", public_key.z32())
            .await
            .assert_status(StatusCode::UNAUTHORIZED);

        // Owner HEAD on the existing file → 200.
        server
            .method(Method::HEAD, "/priv/secret.txt")
            .add_header("host", public_key.z32())
            .add_header(header::COOKIE, cookie.clone())
            .await
            .assert_status(StatusCode::OK);

        // Owner HEAD on an absent file → 404.
        server
            .method(Method::HEAD, "/priv/absent.txt")
            .add_header("host", public_key.z32())
            .add_header(header::COOKIE, cookie)
            .await
            .assert_status(StatusCode::NOT_FOUND);
    }

    #[tokio::test]
    #[pubky_test_utils::test]
    async fn priv_conditional_get_is_authorized_first() {
        let (_, _, server, public_key, cookie) = create_environment().await.unwrap();

        server
            .put("/priv/secret.txt")
            .add_header("host", public_key.z32())
            .add_header(header::COOKIE, cookie.clone())
            .bytes(Vec::from("v1").into())
            .expect_success()
            .await;

        // Capture the real ETag as the owner.
        let owned = server
            .get("/priv/secret.txt")
            .add_header("host", public_key.z32())
            .add_header(header::COOKIE, cookie)
            .expect_success()
            .await;
        let etag = owned.headers().get(header::ETAG).unwrap().clone();

        // Anonymous GET with the real ETag → still 401, not 304.
        server
            .get("/priv/secret.txt")
            .add_header("host", public_key.z32())
            .add_header(header::IF_NONE_MATCH, etag)
            .await
            .assert_status(StatusCode::UNAUTHORIZED);
    }

    #[tokio::test]
    #[pubky_test_utils::test]
    async fn priv_directory_listing_requires_auth() {
        // listing a `/priv/` directory is gated exactly like a file read.
        // Anonymous callers can't enumerate private paths, the owner can.
        let (_, _, server, public_key, cookie) = create_environment().await.unwrap();

        // Owner writes two files under a private directory.
        for name in ["a.txt", "b.txt"] {
            server
                .put(&format!("/priv/app/{name}"))
                .add_header("host", public_key.z32())
                .add_header(header::COOKIE, cookie.clone())
                .bytes(Vec::from("x").into())
                .expect_success()
                .await;
        }

        // Anonymous listing of the private directory → 401 (no enumeration), and
        // the same for a nonexistent directory.
        server
            .get("/priv/app/")
            .add_header("host", public_key.z32())
            .await
            .assert_status(StatusCode::UNAUTHORIZED);
        server
            .get("/priv/nope/")
            .add_header("host", public_key.z32())
            .await
            .assert_status(StatusCode::UNAUTHORIZED);

        // Owner lists the directory → 200 with both entries.
        let resp = server
            .get("/priv/app/")
            .add_header("host", public_key.z32())
            .add_header(header::COOKIE, cookie)
            .expect_success()
            .await;
        let body = resp.text();
        assert!(
            body.contains("/priv/app/a.txt"),
            "listing should include a.txt, got: {body}"
        );
        assert!(
            body.contains("/priv/app/b.txt"),
            "listing should include b.txt, got: {body}"
        );
    }

    #[tokio::test]
    #[pubky_test_utils::test]
    async fn priv_responses_use_no_store_and_auth_vary() {
        let (_, _, server, keypair, cookie) = create_environment_with_keypair().await.unwrap();
        let public_key = keypair.public_key();

        server
            .put("/priv/secret.txt")
            .add_header("host", public_key.z32())
            .add_header(header::COOKIE, cookie.clone())
            .bytes(Vec::from("top secret").into())
            .expect_success()
            .await;
        server
            .put("/priv/app/a.txt")
            .add_header("host", public_key.z32())
            .add_header(header::COOKIE, cookie.clone())
            .bytes(Vec::from("a").into())
            .expect_success()
            .await;

        let ok = server
            .get("/priv/secret.txt")
            .add_header("host", public_key.z32())
            .add_header(header::COOKIE, cookie.clone())
            .expect_success()
            .await;
        assert_private_cache_policy(ok.headers());
        assert_validators_present(ok.headers());

        let not_modified = server
            .get("/priv/secret.txt")
            .add_header("host", public_key.z32())
            .add_header(header::COOKIE, cookie.clone())
            .add_header(
                header::IF_NONE_MATCH,
                ok.headers().get(header::ETAG).unwrap(),
            )
            .await;
        not_modified.assert_status(StatusCode::NOT_MODIFIED);
        assert_private_cache_policy(not_modified.headers());
        assert_validators_present(not_modified.headers());

        let head = server
            .method(Method::HEAD, "/priv/secret.txt")
            .add_header("host", public_key.z32())
            .add_header(header::COOKIE, cookie.clone())
            .await;
        head.assert_status(StatusCode::OK);
        assert_private_cache_policy(head.headers());
        assert_validators_present(head.headers());

        let listing = server
            .get("/priv/app/")
            .add_header("host", public_key.z32())
            .add_header(header::COOKIE, cookie.clone())
            .expect_success()
            .await;
        assert_private_cache_policy(listing.headers());

        let unauthorized = server
            .get("/priv/secret.txt")
            .add_header("host", public_key.z32())
            .await;
        unauthorized.assert_status(StatusCode::UNAUTHORIZED);
        assert_private_cache_policy(unauthorized.headers());
        assert_no_validators(unauthorized.headers());

        let write_only_cookie = sign_in_with_capabilities(
            &server,
            &keypair,
            vec![Capability::write("/priv/").unwrap()],
        )
        .await
        .unwrap();
        let forbidden = server
            .get("/priv/secret.txt")
            .add_header("host", public_key.z32())
            .add_header(header::COOKIE, write_only_cookie)
            .await;
        forbidden.assert_status(StatusCode::FORBIDDEN);
        assert_private_cache_policy(forbidden.headers());
        assert_no_validators(forbidden.headers());

        let missing = server
            .get("/priv/missing.txt")
            .add_header("host", public_key.z32())
            .add_header(header::COOKIE, cookie)
            .await;
        missing.assert_status(StatusCode::NOT_FOUND);
        assert_private_cache_policy(missing.headers());
        assert_no_validators(missing.headers());
    }

    #[tokio::test]
    #[pubky_test_utils::test]
    async fn pub_headers_are_unchanged_by_private_cache_policy() {
        let (_, _, server, public_key, cookie) = create_environment().await.unwrap();

        server
            .put("/pub/file.txt")
            .add_header("host", public_key.z32())
            .add_header(header::COOKIE, cookie.clone())
            .bytes(Vec::from("public").into())
            .expect_success()
            .await;
        server
            .put("/pub/app/a.txt")
            .add_header("host", public_key.z32())
            .add_header(header::COOKIE, cookie)
            .bytes(Vec::from("a").into())
            .expect_success()
            .await;

        let ok = server
            .get("/pub/file.txt")
            .add_header("host", public_key.z32())
            .expect_success()
            .await;
        assert_eq!(
            header_value(ok.headers(), header::CACHE_CONTROL),
            Some("private, must-revalidate")
        );
        assert_eq!(header_value(ok.headers(), header::VARY), Some("pubky-host"));
        assert_validators_present(ok.headers());

        let not_modified = server
            .get("/pub/file.txt")
            .add_header("host", public_key.z32())
            .add_header(
                header::IF_NONE_MATCH,
                ok.headers().get(header::ETAG).unwrap(),
            )
            .await;
        not_modified.assert_status(StatusCode::NOT_MODIFIED);
        assert_eq!(
            header_value(not_modified.headers(), header::CACHE_CONTROL),
            Some("private, must-revalidate")
        );
        assert_eq!(
            header_value(not_modified.headers(), header::VARY),
            Some("pubky-host")
        );
        assert_validators_present(not_modified.headers());

        let listing = server
            .get("/pub/app/")
            .add_header("host", public_key.z32())
            .expect_success()
            .await;
        assert!(header_value(listing.headers(), header::CACHE_CONTROL).is_none());
    }
}