OXYGENHUB
# f53cbe7a204e oxygen / crates / oxy-server / tests / http.rs
27.6 KiB · Rust · last changed Fall back to a parent's token when a stored one is refused; send the signer's identity with a bookmark move 22 days ago source blame history raw
1
//! End-to-end: a real server on a loopback port, clients over HTTP.
2
3
use oxy_core::repo::{Repo, SignatureStatus};
4
use std::fs;
5
use std::net::TcpListener;
6
use std::path::Path;
7
8
fn write(root: &Path, rel: &str, content: &[u8]) {
9
    let p = root.join(rel);
10
    fs::create_dir_all(p.parent().unwrap()).unwrap();
11
    fs::write(p, content).unwrap();
12
}
13
14
/// Point `$OXY_HOME` at a throwaway directory once per test process so no
15
/// test reads or writes the developer's real user configuration or keys.
16
fn hermetic() {
17
    static ONCE: std::sync::Once = std::sync::Once::new();
18
    static DIR: std::sync::OnceLock<tempfile::TempDir> = std::sync::OnceLock::new();
19
    ONCE.call_once(|| {
20
        let d = tempfile::tempdir().unwrap();
21
        std::env::set_var("OXY_HOME", d.path());
22
        DIR.set(d).ok();
23
    });
24
}
25
26
fn start(root: &Path, tokens: Vec<String>) -> String {
27
    start_with(root, tokens, None)
28
}
29
30
fn start_with(root: &Path, tokens: Vec<String>, tls: Option<oxy_server::TlsFiles>) -> String {
31
    let listener = TcpListener::bind("127.0.0.1:0").unwrap();
32
    let port = listener.local_addr().unwrap().port();
33
    let scheme = if tls.is_some() { "https" } else { "http" };
34
    let cfg = oxy_server::ServerConfig {
35
        root: root.to_path_buf(),
36
        tokens,
37
        tls,
38
    };
39
    std::thread::spawn(move || oxy_server::run_blocking(listener, cfg).unwrap());
40
    // Give the acceptor a moment; the first request otherwise races the bind.
41
    std::thread::sleep(std::time::Duration::from_millis(50));
42
    format!("{scheme}://127.0.0.1:{port}")
43
}
44
45
/// A self-signed certificate for 127.0.0.1 written to `dir`: (cert, key).
46
fn self_signed(dir: &Path) -> (std::path::PathBuf, std::path::PathBuf) {
47
    fs::create_dir_all(dir).unwrap();
48
    let ck =
49
        rcgen::generate_simple_self_signed(vec!["127.0.0.1".into(), "localhost".into()]).unwrap();
50
    let cert = dir.join("cert.pem");
51
    let key = dir.join("key.pem");
52
    fs::write(&cert, ck.cert.pem()).unwrap();
53
    fs::write(&key, ck.signing_key.serialize_pem()).unwrap();
54
    (cert, key)
55
}
56
57
#[test]
58
fn clone_push_pull_over_http() {
59
    hermetic();
60
    let dir = tempfile::tempdir().unwrap();
61
    let root = dir.path();
62
    let served = root.join("served");
63
    Repo::init(&served.join("origin")).unwrap();
64
    let base = start(&served, vec![]);
65
    let url = format!("{base}/origin");
66
67
    let mut a = Repo::clone(&url, &root.join("a"))
68
        .unwrap()
69
        .with_home(root.join("home"));
70
    let (key, _) = a
71
        .create_identity(
72
            "Ada",
73
            "[email protected]",
74
            oxy_core::repo::IdentityScope::Repo,
75
        )
76
        .unwrap();
77
    write(&root.join("a"), "f.txt", b"hello\n");
78
    let h1 = a.commit("hello", &[]).unwrap();
79
    let r = a.push("origin", false).unwrap();
80
    assert!(r[0].ok, "{}", r[0].reason);
81
82
    let origin = Repo::open(&served.join("origin")).unwrap();
83
    assert_eq!(origin.bookmark_heads().unwrap(), vec![h1]);
84
    assert!(
85
        matches!(origin.authenticate_change(&h1).unwrap(), SignatureStatus::Valid { key: k, sealed: true, .. } if k == key)
86
    );
87
88
    let b = Repo::clone(&url, &root.join("b")).unwrap();
89
    assert_eq!(fs::read(root.join("b/f.txt")).unwrap(), b"hello\n");
90
    write(&root.join("b"), "g.txt", b"g\n");
91
    let h2 = b.commit("g", &[]).unwrap();
92
    assert!(b.push("origin", false).unwrap()[0].ok);
93
94
    let pr = a.pull("origin").unwrap();
95
    assert!(pr.changed && pr.checked_out);
96
    assert_eq!(fs::read(root.join("a/g.txt")).unwrap(), b"g\n");
97
    let mut heads = a.bookmark_heads().unwrap();
98
    heads.sort();
99
    let mut want = vec![h1, h2];
100
    want.sort();
101
    assert_eq!(heads, want);
102
103
    // Unknown repositories and names the server refuses are surfaced as errors.
104
    let err = Repo::clone(&format!("{base}/nope"), &root.join("c"))
105
        .err()
106
        .unwrap()
107
        .to_string();
108
    assert!(err.contains("404"), "{err}");
109
    fs::create_dir_all(served.join(".hidden/.oxy")).unwrap();
110
    assert!(Repo::clone(&format!("{base}/.hidden"), &root.join("d"))
111
        .err()
112
        .unwrap()
113
        .to_string()
114
        .contains("404"));
115
}
116
117
#[test]
118
fn objects_endpoint_serves_lazy_blobs() {
119
    hermetic();
120
    let dir = tempfile::tempdir().unwrap();
121
    let root = dir.path();
122
    let served = root.join("served");
123
    let origin = Repo::init(&served.join("origin")).unwrap();
124
    let big: Vec<u8> = (0..300_000u32).map(|i| (i % 253) as u8).collect(); // has NUL bytes: opaque
125
    write(&served.join("origin"), "big.bin", &big);
126
    write(&served.join("origin"), "t.txt", b"t\n");
127
    origin.commit("big", &[]).unwrap();
128
    let base = start(&served, vec![]);
129
    let url = format!("{base}/origin");
130
    let a = Repo::clone_with(&url, &root.join("a"), Some(1000), &[]).unwrap();
131
    assert_eq!(
132
        fs::read(root.join("a/big.bin")).unwrap(),
133
        big,
134
        "fetched through the objects endpoint during checkout"
135
    );
136
    assert!(!a.snapshot("status").unwrap().changed);
137
}
138
139
#[test]
140
fn push_requires_a_token_when_configured() {
141
    hermetic();
142
    let dir = tempfile::tempdir().unwrap();
143
    let root = dir.path();
144
    let served = root.join("served");
145
    Repo::init(&served.join("origin")).unwrap();
146
    let base = start(&served, vec!["s3cret".into()]);
147
    let url = format!("{base}/origin");
148
149
    // Reads are open.
150
    let mut a = Repo::clone(&url, &root.join("a")).unwrap();
151
    write(&root.join("a"), "f.txt", b"x\n");
152
    a.commit("x", &[]).unwrap();
153
    let err = a.push("origin", false).err().unwrap().to_string();
154
    assert!(err.contains("401"), "{err}");
155
156
    a.config.set("remote.origin.token", "wrong").unwrap();
157
    a.save_config().unwrap();
158
    assert!(a
159
        .push("origin", false)
160
        .err()
161
        .unwrap()
162
        .to_string()
163
        .contains("401"));
164
165
    a.config.set("remote.origin.token", "s3cret").unwrap();
166
    a.save_config().unwrap();
167
    assert!(a.push("origin", false).unwrap()[0].ok);
168
    let origin = Repo::open(&served.join("origin")).unwrap();
169
    assert_eq!(origin.bookmark_heads().unwrap().len(), 1);
170
}
171
172
#[test]
173
fn https_with_a_self_signed_certificate() {
174
    hermetic();
175
    let dir = tempfile::tempdir().unwrap();
176
    let root = dir.path();
177
    let served = root.join("served");
178
    Repo::init(&served.join("origin")).unwrap();
179
    let (cert, key) = self_signed(root);
180
    let base = start_with(
181
        &served,
182
        vec![],
183
        Some(oxy_server::TlsFiles {
184
            cert: cert.clone(),
185
            key,
186
        }),
187
    );
188
    let url = format!("{base}/origin");
189
190
    // Without trusting the certificate the clone fails; with `OXY_CA` it works.
191
    let err = Repo::clone(&url, &root.join("untrusted"))
192
        .err()
193
        .unwrap()
194
        .to_string();
195
    assert!(
196
        err.contains("certificate")
197
            || err.contains("tls")
198
            || err.contains("TLS")
199
            || err.contains("handshake"),
200
        "{err}"
201
    );
202
    std::env::set_var("OXY_CA", &cert);
203
    let mut a = Repo::clone(&url, &root.join("a")).unwrap();
204
    std::env::remove_var("OXY_CA");
205
    // Persist the trust for this remote so later commands need no env var.
206
    a.config
207
        .set("remote.origin.ca", cert.to_str().unwrap())
208
        .unwrap();
209
    a.save_config().unwrap();
210
    write(&root.join("a"), "f.txt", b"tls\n");
211
    let h = a.commit("over tls", &[]).unwrap();
212
    assert!(a.push("origin", false).unwrap()[0].ok);
213
    let origin = Repo::open(&served.join("origin")).unwrap();
214
    assert_eq!(origin.bookmark_heads().unwrap(), vec![h]);
215
    // A wrong CA is refused.
216
    let (other_cert, _) = self_signed(&root.join("other"));
217
    a.config
218
        .set("remote.origin.ca", other_cert.to_str().unwrap())
219
        .unwrap();
220
    a.save_config().unwrap();
221
    assert!(a.fetch("origin").is_err());
222
}
223
224
/// Eight clones push independent changes at the same moment. The server
225
/// serialises pushes per repository, so every push either lands or is
226
/// refused because the bookmark moved, and a pull-then-push retry lands it.
227
#[test]
228
fn concurrent_pushes_are_serialised() {
229
    hermetic();
230
    let dir = tempfile::tempdir().unwrap();
231
    let root = dir.path();
232
    let served = root.join("served");
233
    Repo::init(&served.join("origin")).unwrap();
234
    let base = start(&served, vec![]);
235
    let url = format!("{base}/origin");
236
    const N: usize = 8;
237
    let mut clones = Vec::new();
238
    for i in 0..N {
239
        let path = root.join(format!("c{i}"));
240
        Repo::clone(&url, &path).unwrap();
241
        clones.push(path);
242
    }
243
    let barrier = std::sync::Arc::new(std::sync::Barrier::new(N));
244
    let mut handles = Vec::new();
245
    for (i, path) in clones.into_iter().enumerate() {
246
        let barrier = barrier.clone();
247
        handles.push(std::thread::spawn(move || {
248
            let repo = Repo::open(&path).unwrap();
249
            write(
250
                &path,
251
                &format!("file-{i}.txt"),
252
                format!("from clone {i}\n").as_bytes(),
253
            );
254
            let h = repo.commit(&format!("change {i}"), &[]).unwrap();
255
            barrier.wait();
256
            // A push is refused either up front (the remote moved since the
257
            // clone's last fetch) or by the server's compare-and-swap; both
258
            // are answered by pulling and pushing again.
259
            for attempt in 0..(N * 4) {
260
                match repo.push("origin", false) {
261
                    Ok(r) if r.iter().all(|x| x.ok) => return (h, attempt),
262
                    Ok(_) => {}
263
                    Err(e)
264
                        if e.to_string().contains("pull first")
265
                            || e.to_string().contains("moved") => {}
266
                    Err(e) => panic!("clone {i}: {e}"),
267
                }
268
                repo.pull("origin")
269
                    .unwrap_or_else(|e| panic!("clone {i} pull: {e}"));
270
            }
271
            panic!("clone {i} never managed to push");
272
        }));
273
    }
274
    let mut hashes = Vec::new();
275
    let mut total_rejected = 0;
276
    for h in handles {
277
        let (hash, attempts) = h.join().unwrap();
278
        hashes.push(hash);
279
        total_rejected += attempts;
280
    }
281
    let origin = Repo::open(&served.join("origin")).unwrap();
282
    let mut heads = origin.bookmark_heads().unwrap();
283
    heads.sort();
284
    hashes.sort();
285
    assert_eq!(heads, hashes, "every independent change is a head");
286
    let snap = origin.load_state(&heads).unwrap().materialize();
287
    for i in 0..N {
288
        assert!(snap.files.contains_key(&format!("file-{i}.txt")));
289
    }
290
    assert!(!snap.is_conflicted());
291
    eprintln!("{total_rejected} pushes were refused for a moved bookmark and retried");
292
    // The operation log is a single chain: each accepted push builds on the last.
293
    let ops = origin.op_log().unwrap();
294
    assert!(ops.len() > N);
295
}
296
297
#[test]
298
fn a_bare_repository_is_served_and_browsed_without_a_working_copy() {
299
    hermetic();
300
    let dir = tempfile::tempdir().unwrap();
301
    let root = dir.path();
302
    let served = root.join("served");
303
    let hosted = Repo::init_bare(&served.join("lib")).unwrap();
304
    assert!(hosted.is_bare());
305
    assert!(
306
        hosted.working_copy().is_err(),
307
        "a bare repository has no working copy"
308
    );
309
    assert!(!served.join("lib").join(".oxy").join("workspace").exists());
310
    let base = start(&served, vec![]);
311
    let url = format!("{base}/lib");
312
313
    // A client clones the empty repository, commits twice, and pushes.
314
    let work = root.join("work");
315
    let client = Repo::clone(&url, &work).unwrap();
316
    write(&work, "src/lib.rs", b"pub fn one() {}\n");
317
    client.snapshot("test").unwrap();
318
    let c1 = client.commit("one", &[]).unwrap();
319
    write(&work, "src/lib.rs", b"pub fn one() {}\npub fn two() {}\n");
320
    client.snapshot("test").unwrap();
321
    let c2 = client.commit("two", &[]).unwrap();
322
    let results = client.push("origin", false).unwrap();
323
    assert!(results.iter().all(|r| r.ok), "{results:?}");
324
325
    // The host reads history, files and blame from the bookmark's state alone.
326
    let hosted = Repo::open(&served.join("lib")).unwrap();
327
    assert!(hosted.is_bare());
328
    let heads = hosted.bookmark_heads().unwrap();
329
    assert_eq!(heads, vec![c2]);
330
    let log = hosted.log().unwrap();
331
    assert_eq!(log.iter().map(|e| e.hash).collect::<Vec<_>>(), vec![c2, c1]);
332
    assert!(log.iter().all(|e| !e.is_working_copy));
333
    assert_eq!(hosted.log_state(&[c1]).unwrap().len(), 1);
334
    assert_eq!(
335
        hosted.file_at("src/lib.rs", Some(&heads)).unwrap(),
336
        b"pub fn one() {}\npub fn two() {}\n"
337
    );
338
    let blame = hosted.blame_in("src/lib.rs", &heads).unwrap();
339
    assert_eq!(
340
        blame.iter().map(|l| l.hash).collect::<Vec<_>>(),
341
        vec![c1, c2]
342
    );
343
    assert_eq!(hosted.log_for_path("src/lib.rs").unwrap().len(), 2);
344
    assert_eq!(hosted.diff_files(Some(&c2)).unwrap().len(), 1);
345
    assert!(matches!(
346
        hosted.verify_change(&c2).unwrap(),
347
        SignatureStatus::Unsigned | SignatureStatus::Valid { .. }
348
    ));
349
350
    // Snapshotting a bare repository is refused rather than inventing a working copy.
351
    assert!(hosted.snapshot("test").is_err());
352
}
353
354
/// A host embeds the protocol with its own backend: names with an owner
355
/// segment, reads gated per repository, and a push hook.
356
#[test]
357
fn a_custom_backend_embeds_the_protocol() {
358
    use axum::extract::{Path as AxPath, State};
359
    use axum::http::{HeaderMap, Method, StatusCode};
360
    use axum::response::{IntoResponse, Response};
361
    use oxy_server::{Access, Backend, Endpoint, Failure, Server};
362
    use std::sync::{Arc, Mutex};
363
364
    struct Hub {
365
        root: std::path::PathBuf,
366
        pushes: Arc<Mutex<Vec<String>>>,
367
    }
368
    impl Backend for Hub {
369
        fn open(&self, name: &str) -> Result<Repo, Failure> {
370
            let Some((owner, repo)) = name.split_once('/') else {
371
                return Err(Failure(StatusCode::NOT_FOUND, "no such repository".into()));
372
            };
373
            let dir = self.root.join(owner).join(repo);
374
            if !dir.join(".oxy").is_dir() {
375
                return Err(Failure(StatusCode::NOT_FOUND, "no such repository".into()));
376
            }
377
            Repo::open(&dir).map_err(|e| Failure(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))
378
        }
379
        fn authorize(
380
            &self,
381
            name: &str,
382
            access: Access,
383
            headers: &HeaderMap,
384
        ) -> Result<(), Failure> {
385
            // `secret/*` is private: unknown to anyone without the token, even for reads.
386
            let token = oxy_server::bearer_token(headers);
387
            if name.starts_with("secret/") && token != Some("s3cret") {
388
                return Err(Failure(StatusCode::NOT_FOUND, "no such repository".into()));
389
            }
390
            if access == Access::Push && token.is_none() {
391
                return Err(Failure(StatusCode::UNAUTHORIZED, "sign in to push".into()));
392
            }
393
            Ok(())
394
        }
395
        fn after_push(
396
            &self,
397
            name: &str,
398
            report: &oxy_core::repo::PushReport,
399
            _headers: &HeaderMap,
400
        ) {
401
            self.pushes.lock().unwrap().push(format!(
402
                "{name}: {} ok, {} updated to {} head(s), {} imported",
403
                report.results.iter().filter(|r| r.ok).count(),
404
                report.updated.len(),
405
                report.updated.first().map(|u| u.heads.len()).unwrap_or(0),
406
                report.imported.len()
407
            ));
408
        }
409
    }
410
    async fn route(
411
        State(server): State<Arc<Server>>,
412
        AxPath((owner, repo, endpoint)): AxPath<(String, String, String)>,
413
        method: Method,
414
        headers: HeaderMap,
415
        body: axum::body::Bytes,
416
    ) -> Response {
417
        match Endpoint::parse(&endpoint) {
418
            Some(e) => {
419
                server
420
                    .handle(format!("{owner}/{repo}"), e, &method, &headers, body)
421
                    .await
422
            }
423
            None => Failure(StatusCode::NOT_FOUND, "no such endpoint".into()).into_response(),
424
        }
425
    }
426
427
    hermetic();
428
    let dir = tempfile::tempdir().unwrap();
429
    let root = dir.path();
430
    Repo::init_bare(&root.join("repos/andy/app")).unwrap();
431
    Repo::init_bare(&root.join("repos/secret/plans")).unwrap();
432
    let pushes = Arc::new(Mutex::new(Vec::new()));
433
    let server = Server::new(Hub {
434
        root: root.join("repos"),
435
        pushes: pushes.clone(),
436
    });
437
    let listener = TcpListener::bind("127.0.0.1:0").unwrap();
438
    let port = listener.local_addr().unwrap().port();
439
    std::thread::spawn(move || {
440
        let rt = tokio::runtime::Builder::new_multi_thread()
441
            .enable_all()
442
            .build()
443
            .unwrap();
444
        rt.block_on(async move {
445
            listener.set_nonblocking(true).unwrap();
446
            let app = axum::Router::new()
447
                .route(
448
                    "/{owner}/{repo}/oxy/v1/{endpoint}",
449
                    axum::routing::any(route),
450
                )
451
                .with_state(server);
452
            axum::serve(tokio::net::TcpListener::from_std(listener).unwrap(), app)
453
                .await
454
                .unwrap();
455
        });
456
    });
457
    std::thread::sleep(std::time::Duration::from_millis(50));
458
    let base = format!("http://127.0.0.1:{port}");
459
460
    // Anonymous clone of the public repository works; the private one does not exist for outsiders.
461
    let work = root.join("work");
462
    let client = Repo::clone(&format!("{base}/andy/app"), &work).unwrap();
463
    assert!(Repo::clone(&format!("{base}/secret/plans"), &root.join("nope")).is_err());
464
465
    // A push needs a token; with one it lands and the hook sees it.
466
    write(&work, "a.txt", b"a\n");
467
    client.snapshot("test").unwrap();
468
    client.commit("a", &[]).unwrap();
469
    assert!(
470
        client.push("origin", false).is_err(),
471
        "anonymous push must be refused"
472
    );
473
    let mut client = client;
474
    client.config.set("remote.origin.token", "s3cret").unwrap();
475
    let results = client.push("origin", false).unwrap();
476
    assert!(results.iter().all(|r| r.ok), "{results:?}");
477
    assert_eq!(
478
        pushes.lock().unwrap().as_slice(),
479
        ["andy/app: 1 ok, 1 updated to 1 head(s), 1 imported"]
480
    );
481
482
    let hosted = Repo::open(&root.join("repos/andy/app")).unwrap();
483
    assert_eq!(hosted.bookmark_heads().unwrap().len(), 1);
484
}
485
486
/// A hosted repository created unbound adopts the id of the first
487
/// repository pushed to it; before that it cannot be cloned or fetched.
488
#[test]
489
fn an_unbound_repository_adopts_the_first_pushers_id() {
490
    hermetic();
491
    let dir = tempfile::tempdir().unwrap();
492
    let root = dir.path();
493
    let served = root.join("served");
494
    let hosted = Repo::init_bare_unbound(&served.join("lib")).unwrap();
495
    assert!(hosted.is_unbound());
496
    assert_eq!(hosted.id().unwrap(), [0; 16]);
497
    let base = start(&served, vec![]);
498
    let url = format!("{base}/lib");
499
    assert!(Repo::clone(&url, &root.join("early"))
500
        .err()
501
        .unwrap()
502
        .to_string()
503
        .contains("unbound"));
504
505
    // An existing repository with its own id and history.
506
    let work = root.join("work");
507
    let mut local = Repo::init(&work).unwrap();
508
    let my_id = local.id().unwrap();
509
    write(&work, "a.txt", b"a\n");
510
    local.snapshot("test").unwrap();
511
    local.commit("a", &[]).unwrap();
512
    local.config.set("remote.origin.url", &url).unwrap();
513
    local.save_config().unwrap();
514
    assert!(
515
        local
516
            .fetch("origin")
517
            .err()
518
            .unwrap()
519
            .to_string()
520
            .contains("unbound"),
521
        "fetching an unbound remote is refused"
522
    );
523
    let results = local.push("origin", false).unwrap();
524
    assert!(results.iter().all(|r| r.ok), "{results:?}");
525
526
    let hosted = Repo::open(&served.join("lib")).unwrap();
527
    assert!(!hosted.is_unbound());
528
    assert_eq!(hosted.id().unwrap(), my_id, "bound to the pusher's id");
529
    assert_eq!(hosted.bookmark_heads().unwrap().len(), 1);
530
    // From now on it is an ordinary remote: clones share the id, other repositories are refused.
531
    let cloned = Repo::clone(&url, &root.join("late")).unwrap();
532
    assert_eq!(cloned.id().unwrap(), my_id);
533
    let mut other = Repo::init(&root.join("other")).unwrap();
534
    other.config.set("remote.origin.url", &url).unwrap();
535
    other.save_config().unwrap();
536
    write(&root.join("other"), "b.txt", b"b\n");
537
    other.snapshot("test").unwrap();
538
    other.commit("b", &[]).unwrap();
539
    assert!(other
540
        .push("origin", false)
541
        .err()
542
        .unwrap()
543
        .to_string()
544
        .contains("different repository"));
545
}
546
547
/// History made before an identity existed (zero author) is adopted by
548
/// the pusher's seal, so it passes a server that enforces a policy.
549
#[test]
550
fn anonymous_history_is_adopted_by_the_pushers_seal() {
551
    hermetic();
552
    let dir = tempfile::tempdir().unwrap();
553
    let root = dir.path();
554
    let served = root.join("served");
555
    Repo::init_bare_unbound(&served.join("app")).unwrap();
556
    let base = start(&served, vec![]);
557
    let url = format!("{base}/app");
558
559
    // Two anonymous changes, then an identity and a policy naming it.
560
    let work = root.join("work");
561
    let mut local = Repo::init(&work).unwrap();
562
    write(&work, "a.txt", b"a\n");
563
    local.snapshot("test").unwrap();
564
    let anon = local.commit("before identity", &[]).unwrap();
565
    local
566
        .create_identity(
567
            "Andy",
568
            "[email protected]",
569
            oxy_core::repo::IdentityScope::Repo,
570
        )
571
        .unwrap();
572
    local.policy_init().unwrap();
573
    write(&work, "b.txt", b"b\n");
574
    local.snapshot("test").unwrap();
575
    let mine = local.commit("after identity", &[]).unwrap();
576
    assert!(matches!(
577
        local.authenticate_change(&anon).unwrap(),
578
        SignatureStatus::Unsigned
579
    ));
580
    local.config.set("remote.origin.url", &url).unwrap();
581
    local.save_config().unwrap();
582
    let results = local.push("origin", false).unwrap();
583
    assert!(results.iter().all(|r| r.ok), "{results:?}");
584
585
    // The server holds the policy and both changes verify: sealed by the adopter.
586
    let hosted = Repo::open(&served.join("app")).unwrap();
587
    assert!(hosted.current_policy().unwrap().is_some());
588
    for h in [anon, mine] {
589
        assert!(
590
            matches!(hosted.authenticate_change(&h).unwrap(), SignatureStatus::Valid { sealed: true, name, .. } if name == "Andy"),
591
            "{h}"
592
        );
593
    }
594
    // A change that names another author still cannot be sealed by someone else.
595
    let stranger = root.join("stranger");
596
    let mut other = Repo::init(&stranger).unwrap();
597
    other
598
        .create_identity(
599
            "Mallory",
600
            "[email protected]",
601
            oxy_core::repo::IdentityScope::Repo,
602
        )
603
        .unwrap();
604
    write(&stranger, "c.txt", b"c\n");
605
    other.snapshot("test").unwrap();
606
    let theirs = other.commit("mallory's", &[]).unwrap();
607
    assert!(matches!(
608
        other.authenticate_change(&theirs).unwrap(),
609
        SignatureStatus::Unsigned
610
    ));
611
    let bundle = other.bundle_for(&[theirs]).unwrap();
612
    local.import_bundle(&bundle, false).unwrap();
613
    local.seal(&[theirs]).unwrap();
614
    assert!(
615
        matches!(local.authenticate_change(&theirs).unwrap(), SignatureStatus::Invalid(why) if why.contains("neither the author nor a delegate"))
616
    );
617
}
618
619
/// `oxy push --delete` over HTTP: a bare repository's bookmark goes, and
620
/// its default (the served repository's own bookmark) is refused by the
621
/// backend (spec §16.4).
622
#[test]
623
fn bookmarks_are_deleted_over_http_but_never_the_default() {
624
    hermetic();
625
    let dir = tempfile::tempdir().unwrap();
626
    let root = dir.path();
627
    let served = root.join("served");
628
    let hosted = Repo::init_bare(&served.join("lib")).unwrap();
629
    let base = start(&served, vec![]);
630
    let work = root.join("work");
631
    let client = Repo::clone(&format!("{base}/lib"), &work).unwrap();
632
    write(&work, "a.txt", b"a\n");
633
    client.commit("a", &[]).unwrap();
634
    assert!(client.push("origin", false).unwrap()[0].ok);
635
    client.bookmark_create("feature/x", None).unwrap();
636
    assert!(client.push_bookmark("origin", "feature/x", false).unwrap()[0].ok);
637
    let r = client.push_delete("origin", "feature/x").unwrap();
638
    assert!(r[0].ok, "{r:?}");
639
    assert!(!hosted.view().unwrap().bookmarks.contains_key("feature/x"));
640
    let r = client.push_delete("origin", "main").unwrap();
641
    assert!(
642
        !r[0].ok && r[0].reason.contains("default bookmark"),
643
        "{r:?}"
644
    );
645
    assert!(hosted.view().unwrap().bookmarks.contains_key("main"));
646
}
647
648
/// A push the server cannot store says which bookmark and what failed, so
649
/// it can be diagnosed from the client's message alone.
650
#[cfg(unix)]
651
#[test]
652
fn a_refused_push_names_the_bookmark_and_the_step() {
653
    hermetic();
654
    let dir = tempfile::tempdir().unwrap();
655
    let root = dir.path();
656
    let served = root.join("served");
657
    Repo::init_bare(&served.join("lib")).unwrap();
658
    // Break the server's attestation store for writing only: reading finds
659
    // nothing there, storing a new attestation fails.
660
    let attest = served.join("lib/.oxy/attest");
661
    fs::create_dir_all(&attest).unwrap();
662
    {
663
        use std::os::unix::fs::PermissionsExt;
664
        fs::set_permissions(&attest, fs::Permissions::from_mode(0o555)).unwrap();
665
    }
666
    let base = start(&served, vec![]);
667
    let work = root.join("work");
668
    let mut client = Repo::clone(&format!("{base}/lib"), &work)
669
        .unwrap()
670
        .with_home(root.join("home"));
671
    client
672
        .create_identity(
673
            "Ada",
674
            "[email protected]",
675
            oxy_core::repo::IdentityScope::Repo,
676
        )
677
        .unwrap();
678
    write(&work, "a.txt", b"a\n");
679
    client.commit("a", &[]).unwrap();
680
    client.bookmark_create("feature/x", None).unwrap();
681
    let r = client.push_bookmark("origin", "feature/x", false).unwrap();
682
    assert!(!r[0].ok);
683
    assert!(
684
        r[0].reason.contains("\"feature/x\"") && r[0].reason.contains("storing the attestation"),
685
        "{}",
686
        r[0].reason
687
    );
688
    {
689
        use std::os::unix::fs::PermissionsExt;
690
        fs::set_permissions(&attest, fs::Permissions::from_mode(0o755)).unwrap();
691
    }
692
}
693
694
/// oxygen#112: a subrepo checkout whose stored login for the hub is stale
695
/// pushes with the token its parent checkout holds for the same hub, once
696
/// the stale one is refused; a token the subrepo sets itself is never
697
/// swapped for another.
698
#[test]
699
fn a_refused_stored_token_falls_back_to_the_parents() {
700
    hermetic();
701
    let dir = tempfile::tempdir().unwrap();
702
    let root = dir.path();
703
    let served = root.join("served");
704
    Repo::init(&served.join("parent")).unwrap();
705
    Repo::init(&served.join("child")).unwrap();
706
    let base = start(&served, vec!["good".into()]);
707
708
    let work = root.join("work");
709
    let mut parent = Repo::clone(&format!("{base}/parent"), &work).unwrap();
710
    parent.config.set("remote.origin.token", "good").unwrap();
711
    parent.save_config().unwrap();
712
    // The subrepo's own home holds a stale login for this hub.
713
    let home = root.join("home");
714
    oxy_core::credentials::Credentials::at(&home)
715
        .save(&base, "stale", Some("andy"), None)
716
        .unwrap();
717
    let nested = work.join("deps").join("child");
718
    let mut child = Repo::clone(&format!("{base}/child"), &nested)
719
        .unwrap()
720
        .with_home(&home);
721
    let options = child.options_for_url(&format!("{base}/child"));
722
    assert_eq!(
723
        options.token.as_deref(),
724
        Some("stale"),
725
        "the stored login comes first"
726
    );
727
    assert_eq!(
728
        options.fallback_tokens,
729
        vec!["good".to_string()],
730
        "the parent's, to fall back on"
731
    );
732
    write(&nested, "c.txt", b"child\n");
733
    child.commit("child work", &[]).unwrap();
734
    let pushed = child.push("origin", false).unwrap();
735
    assert!(pushed[0].ok, "{}", pushed[0].reason);
736
    assert_eq!(
737
        Repo::open(&served.join("child"))
738
            .unwrap()
739
            .bookmark_heads()
740
            .unwrap()
741
            .len(),
742
        1
743
    );
744
745
    // Its own token, if wrong, stays wrong: what a checkout sets is its choice.
746
    child.config.set("remote.origin.token", "wrong").unwrap();
747
    child.save_config().unwrap();
748
    write(&nested, "d.txt", b"more\n");
749
    child.commit("more", &[]).unwrap();
750
    let err = child.push("origin", false).err().unwrap().to_string();
751
    assert!(err.contains("401"), "{err}");
752
}