graphforge-cli 0.6.0-rc.8

GraphForge command-line interface
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
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
//! Fetch and verify one exact ontology module from a Hub repository.
//!
//! This applies the clone pipeline's discovery, transport, staging, and download
//! safety to one per-module package object instead of the Project package. It
//! reuses the parent module's private pieces, so the two commands cannot drift
//! apart. Sub-issue of #1732.

use super::{
    CloneStaging, DiscoveryCredentials, DownloadControl, DownloadReport, HttpTransport,
    MAX_METADATA_BYTES, RETRY_POLICY, RetryPolicy, Transport, acquire_staging, canonical_name,
    download_with_progress, endpoint, ensure_destination_absent, fetch_discovery_with_attempts,
    parse_input_at, portable_error, protocol_error, read_bounded, release_staging, storage,
    validation,
};
use clap::Args;
use graphforge_api::{
    DiscoveryOntologyModuleRequest, OntologyModuleId, PortableLimits, ResolvedOntologyModule,
    resolve_discovered_ontology_module,
};
use graphforge_discovery::{
    DiscoveryLimits, DiscoveryManifest, ExactIdentity, ItemId, ObjectDescriptor, RefSet,
    RepositoryIdentity, Sha256Digest,
};
use serde::Serialize;
use std::fs::File;
use std::io::Write;
use std::path::{Path, PathBuf};
use url::Url;

mod item_fetch;

/// Bound on one per-module package object; a module never needs the bundle bound.
const MAX_MODULE_PACKAGE_BYTES: u64 = 64 * 1024 * 1024;

/// Fetch and verify one exact ontology module from a Hub repository without
/// downloading its Project package.
#[derive(Args)]
pub(crate) struct ModuleFetchArgs {
    /// Permanent item ID, canonical item URI, ID/authored-version, or owner/repository.
    #[arg(value_name = "REF")]
    pub repository: String,
    /// Exact module ontology identifier, as advertised by the repository.
    #[arg(long)]
    pub ontology_id: Option<String>,
    /// Exact module authored version, as advertised by the repository.
    #[arg(long)]
    pub version: Option<String>,
    /// Exact canonical content digest: 64 lowercase hexadecimal digits,
    /// optionally prefixed with `sha256:`.
    #[arg(long)]
    pub digest: Option<String>,
    /// New file that receives the verified module document; never overwritten.
    #[arg(long)]
    pub output: PathBuf,
    /// HTTPS Hub base URL; defaults to https://graphforge.sh.
    #[arg(long)]
    pub hub: Option<String>,
    /// Read the separate x-vercel-protection-bypass secret from this environment variable.
    /// It is sent only to the configured Hub's discovery endpoints, never package objects.
    #[arg(long)]
    pub protection_bypass_env: Option<String>,
}

#[derive(Serialize)]
struct ModuleFetchResult {
    contract: &'static str,
    repository: String,
    module: OntologyModuleId,
    package_digest: String,
    module_sha256: String,
    output: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    moved_from: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    moved_to: Option<String>,
}

pub(crate) fn run_module_fetch(
    args: &ModuleFetchArgs,
    json: bool,
    output: &mut dyn Write,
) -> Result<(), graphforge_api::GfError> {
    run_module_fetch_with(&HttpTransport::new(), args, json, output, &RETRY_POLICY)
}

pub(super) fn run_module_fetch_with(
    transport: &dyn Transport,
    args: &ModuleFetchArgs,
    json: bool,
    output: &mut dyn Write,
    retry: &RetryPolicy,
) -> Result<(), graphforge_api::GfError> {
    let result = run_module_fetch_job(transport, args, retry)?;
    write_module_fetch_result(&result, json, output)
}

fn write_module_fetch_result(
    result: &ModuleFetchResult,
    json: bool,
    output: &mut dyn Write,
) -> Result<(), graphforge_api::GfError> {
    if json {
        serde_json::to_writer(&mut *output, result)
            .map_err(|e| graphforge_api::GfError::Execution(e.to_string()))?;
        writeln!(output).map_err(storage)?;
    } else {
        if let (Some(from), Some(to)) = (&result.moved_from, &result.moved_to) {
            writeln!(output, "Repository moved from {from} to {to}").map_err(storage)?;
        }
        writeln!(
            output,
            "Fetched ontology module {} {} from {} to {}",
            result.module.ontology_id,
            result.module.authored_version,
            result.repository,
            result.output
        )
        .map_err(storage)?;
    }
    Ok(())
}

/// Build the exact module identity the caller asks for. The digest is the
/// canonical content digest, which is not the package digest nor the document's
/// file SHA-256.
fn digest_pin(args: &ModuleFetchArgs) -> Result<Option<Sha256Digest>, graphforge_api::GfError> {
    let Some(digest) = args.digest.as_deref() else {
        return Ok(None);
    };
    let hex = digest.strip_prefix("sha256:").unwrap_or(digest);
    let content_digest = Sha256Digest(format!("sha256:{hex}"));
    content_digest.validate().map_err(|_| {
        validation(
            "hub.invalid_identity",
            "--digest must be 64 lowercase hexadecimal digits, optionally prefixed with sha256:",
        )
    })?;
    Ok(Some(content_digest))
}

fn normalized_id(id: &str) -> String {
    ItemId::parse_reference(id).map_or_else(|_| id.into(), |id| id.to_uri())
}

fn repository_module(
    id: &str,
    version: &str,
    manifest: &DiscoveryManifest,
    pin: Option<Sha256Digest>,
) -> Result<ExactIdentity, graphforge_api::GfError> {
    let id = normalized_id(id);
    let version = version.to_owned();
    if let Some(content_digest) = pin {
        return Ok(ExactIdentity {
            id,
            version,
            content_digest,
        });
    }
    let mut matches = manifest
        .ontology
        .iter()
        .flat_map(|inventory| &inventory.modules)
        .filter(|module| module.id == id && module.version == version);
    let selected = matches
        .next()
        .ok_or_else(|| validation("hub.missing_object", "ontology module is not advertised"))?;
    if matches.next().is_some() {
        return Err(validation(
            "hub.invalid_identity",
            "module identity is ambiguous; provide --digest",
        ));
    }
    Ok(selected.identity())
}

/// Refuse an existing output, or one whose directory is absent, before any I/O.
fn ensure_output_available(output: &Path) -> Result<(), graphforge_api::GfError> {
    let directory = match output.parent() {
        Some(parent) if !parent.as_os_str().is_empty() => parent,
        _ => Path::new("."),
    };
    if !std::fs::metadata(directory).is_ok_and(|metadata| metadata.is_dir()) {
        return Err(validation(
            "hub.destination_conflict",
            "output directory does not exist",
        ));
    }
    ensure_destination_absent(output)
}

fn fetch_document(
    transport: &dyn Transport,
    url: &Url,
    credentials: Option<&DiscoveryCredentials>,
    retry: &RetryPolicy,
) -> Result<Vec<u8>, graphforge_api::GfError> {
    let mut attempts = 0;
    read_bounded(
        fetch_discovery_with_attempts(
            transport,
            url,
            credentials,
            MAX_METADATA_BYTES as u64,
            &mut attempts,
            retry,
        )?,
        MAX_METADATA_BYTES,
    )
}

pub(super) fn resolve_module_with(
    transport: &dyn Transport,
    args: &ModuleFetchArgs,
    retry: &RetryPolicy,
) -> Result<
    (
        ResolvedOntologyModule,
        Option<graphforge_discovery::RepositoryMoved>,
    ),
    graphforge_api::GfError,
> {
    resolve_module_with_lookup(transport, args, retry, |name| std::env::var(name))
}

pub(super) fn resolve_module_with_lookup(
    transport: &dyn Transport,
    args: &ModuleFetchArgs,
    retry: &RetryPolicy,
    credential_lookup: impl Fn(&str) -> Result<String, std::env::VarError>,
) -> Result<
    (
        ResolvedOntologyModule,
        Option<graphforge_discovery::RepositoryMoved>,
    ),
    graphforge_api::GfError,
> {
    if let Some(reference) = item_fetch::parse_reference(&args.repository)? {
        return item_fetch::fetch(transport, args, &reference, retry, credential_lookup);
    }
    let (identity, base) = parse_input_at(&args.repository, args.hub.as_deref())?;
    let (Some(ontology_id), Some(version)) = (args.ontology_id.as_deref(), args.version.as_deref())
    else {
        return Err(validation(
            "hub.invalid_identity",
            "owner/repository fetch requires --ontology-id and --version",
        ));
    };
    if ontology_id.is_empty() || version.is_empty() {
        return Err(validation(
            "hub.invalid_identity",
            "module ID and version must not be empty",
        ));
    }
    let pin = digest_pin(args)?;
    ensure_output_available(&args.output)?;
    let credentials = DiscoveryCredentials::load(
        &base,
        None,
        args.protection_bypass_env.as_deref(),
        credential_lookup,
    )?;
    let move_transport = crate::hub_http::RepositoryMoveTransport::new(transport, &identity, &base)
        .with_credentials(credentials.as_ref());
    let transport = &move_transport as &dyn Transport;
    let refs_bytes = fetch_document(
        transport,
        &endpoint(&base, "refs"),
        credentials.as_ref(),
        retry,
    )?;
    let (_, current_base, _) = move_transport.resolved(false)?;
    let manifest_bytes = fetch_document(
        transport,
        &endpoint(&current_base, "manifest"),
        credentials.as_ref(),
        retry,
    )?;
    let (identity, _, moved) = move_transport.resolved(false)?;
    let limits = DiscoveryLimits {
        max_response_bytes: MAX_METADATA_BYTES,
        max_module_package_bytes: MAX_MODULE_PACKAGE_BYTES,
        ..DiscoveryLimits::default()
    };
    let refs = RefSet::from_json(&refs_bytes, limits).map_err(|error| protocol_error(&error))?;
    let manifest = DiscoveryManifest::from_json(&manifest_bytes, limits)
        .map_err(|error| protocol_error(&error))?;
    if refs.repository != identity || manifest.repository != identity {
        return Err(validation("hub.integrity", "discovery repository mismatch"));
    }
    refs.validate_manifest(&manifest)
        .map_err(|error| protocol_error(&error))?;
    let module = repository_module(ontology_id, version, &manifest, pin)?;
    let (_, _, object) = manifest
        .ontology_module_selection(&module)
        .map_err(|error| protocol_error(&error))?;
    let staging = acquire_staging(&args.output)?;
    let result = download_and_resolve_module(
        transport,
        &identity,
        &module,
        &manifest_bytes,
        &refs_bytes,
        object,
        limits,
        &staging,
        retry,
    );
    release_staging(staging);
    result.map(|resolved| (resolved, moved))
}

// `release_staging` removes everything this fetch staged, on success and on
// failure alike: the document is already published, and the package is cheap
// to download again.

#[allow(clippy::too_many_arguments)]
fn download_and_resolve_module(
    transport: &dyn Transport,
    identity: &RepositoryIdentity,
    module: &ExactIdentity,
    manifest_bytes: &[u8],
    refs_bytes: &[u8],
    object: &ObjectDescriptor,
    limits: DiscoveryLimits,
    staging: &CloneStaging,
    retry: &RetryPolicy,
) -> Result<ResolvedOntologyModule, graphforge_api::GfError> {
    download_with_progress(
        transport,
        object,
        &staging.partial,
        &mut DownloadReport::default(),
        &mut DownloadControl::quiet(retry),
    )?;
    let resolved = resolve_discovered_ontology_module(&DiscoveryOntologyModuleRequest {
        manifest_json: manifest_bytes,
        refs_json: refs_bytes,
        expected_repository: identity,
        module,
        package: &staging.partial,
        discovery_limits: limits,
        portable_limits: PortableLimits::default(),
        cancelled: None,
    })
    .map_err(portable_error)?;
    Ok(resolved)
}

fn run_module_fetch_job(
    transport: &dyn Transport,
    args: &ModuleFetchArgs,
    retry: &RetryPolicy,
) -> Result<ModuleFetchResult, graphforge_api::GfError> {
    let (resolved, moved) = resolve_module_with(transport, args, retry)?;
    let parent = args
        .output
        .parent()
        .filter(|path| !path.as_os_str().is_empty())
        .unwrap_or(Path::new("."));
    let mut staged = tempfile::NamedTempFile::new_in(parent).map_err(storage)?;
    staged.write_all(resolved.document()).map_err(storage)?;
    staged.as_file().sync_all().map_err(storage)?;
    publish_without_replacing(staged.path(), &args.output)?;
    Ok(ModuleFetchResult {
        contract: "graphforge-hub-module-fetch/1",
        repository: canonical_name(resolved.repository()),
        module: resolved.module().clone(),
        package_digest: resolved.package_digest().to_owned(),
        module_sha256: resolved.module_sha256().to_owned(),
        output: args.output.display().to_string(),
        moved_from: moved.as_ref().map(|m| m.moved_from.canonical_name()),
        moved_to: moved.as_ref().map(|m| m.moved_to.canonical_name()),
    })
}

/// Publish `staged` at `output` atomically. A hard link fails if `output`
/// exists, even as a dangling symlink, so a file created after the up-front
/// check is never overwritten (a rename would replace it silently).
fn publish_without_replacing(staged: &Path, output: &Path) -> Result<(), graphforge_api::GfError> {
    match std::fs::hard_link(staged, output) {
        Ok(()) => {}
        Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => {
            return Err(validation(
                "hub.destination_conflict",
                "destination already exists",
            ));
        }
        Err(error) => return Err(hard_link_error(error)),
    }
    if let Some(parent) = output
        .parent()
        .filter(|parent| !parent.as_os_str().is_empty())
    {
        let _ = File::open(parent).and_then(|directory| directory.sync_all());
    }
    Ok(())
}

/// Classify a failed hard link. A filesystem that cannot hard-link (for example
/// FAT or some network and FUSE mounts) cannot publish the output without
/// risking replacement of a concurrently created file, so it is refused with a
/// stable code. Any other failure (permissions, space, I/O) stays a storage error.
fn hard_link_error(error: std::io::Error) -> graphforge_api::GfError {
    #[cfg(unix)]
    let unsupported = error.raw_os_error().is_some_and(|code| {
        code == libc::EPERM || code == libc::ENOTSUP || code == libc::EOPNOTSUPP
    });
    #[cfg(not(unix))]
    let unsupported = false;
    if unsupported || error.kind() == std::io::ErrorKind::Unsupported {
        validation(
            "hub.destination_conflict",
            "output filesystem cannot publish atomically",
        )
    } else {
        storage(error)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    mod authentication;
    mod item_ids;
    use crate::hub_clone::tests::{RecordingTransport, Scripted, response};
    use crate::hub_clone::{HttpResponse, hash_reader};
    use crate::hub_clone::{TEST_RETRY_POLICY, clear_staging, remove_staging_dir};
    use std::sync::Mutex;

    const FIXTURE_REFS: &[u8] =
        include_bytes!("../../../../tests/fixtures/hub/generated/v1/refs.json");
    const FIXTURE_MANIFEST: &[u8] =
        include_bytes!("../../../../tests/fixtures/hub/generated/v1/manifest.json");

    fn fixture_module_package() -> Vec<u8> {
        let manifest =
            DiscoveryManifest::from_json(FIXTURE_MANIFEST, DiscoveryLimits::default()).unwrap();
        let module = &manifest.ontology.as_ref().unwrap().modules[0];
        let hex = module.content_digest.0.strip_prefix("sha256:").unwrap();
        std::fs::read(format!(
            "{}/../../tests/fixtures/hub/generated/v1/objects/ontology-module-{hex}.gfpb",
            env!("CARGO_MANIFEST_DIR")
        ))
        .unwrap()
    }

    /// Fetch arguments for the fixture's only advertised module.
    fn fixture_module_args(output: &Path) -> ModuleFetchArgs {
        let manifest =
            DiscoveryManifest::from_json(FIXTURE_MANIFEST, DiscoveryLimits::default()).unwrap();
        let module = &manifest.ontology.as_ref().unwrap().modules[0];
        ModuleFetchArgs {
            repository: "opendata/openalex".into(),
            ontology_id: Some(module.id.clone()),
            version: Some(module.version.clone()),
            digest: Some(module.content_digest.0.clone()),
            output: output.to_path_buf(),
            hub: None,
            protection_bypass_env: None,
        }
    }

    /// The fixture manifest after `change`, as bytes.
    fn changed_fixture_manifest(change: impl FnOnce(&mut serde_json::Value)) -> Vec<u8> {
        let mut manifest: serde_json::Value = serde_json::from_slice(FIXTURE_MANIFEST).unwrap();
        change(&mut manifest);
        serde_json::to_vec(&manifest).unwrap()
    }

    /// The transport object entry of the fixture's only module package.
    fn module_object_entry(manifest: &mut serde_json::Value) -> &mut serde_json::Value {
        let digest = manifest["ontology"]["modules"][0]["package"]["object_digest"].clone();
        manifest["objects"]
            .as_array_mut()
            .unwrap()
            .iter_mut()
            .find(|object| object["digest"] == digest)
            .unwrap()
    }

    fn module_transport(manifest: &[u8], object: &[u8]) -> RecordingTransport {
        RecordingTransport {
            inner: Scripted::new(vec![
                response(200, None, FIXTURE_REFS),
                response(200, None, manifest),
                response(200, None, object),
            ]),
            requested: Mutex::new(Vec::new()),
        }
    }

    fn fetch_module(
        transport: &dyn Transport,
        args: &ModuleFetchArgs,
    ) -> Result<serde_json::Value, graphforge_api::GfError> {
        let mut output = Vec::new();
        run_module_fetch_with(transport, args, true, &mut output, &TEST_RETRY_POLICY)?;
        Ok(serde_json::from_slice(&output).unwrap())
    }

    fn directory_entries(directory: &Path) -> Vec<String> {
        let mut names: Vec<_> = std::fs::read_dir(directory)
            .unwrap()
            .map(|entry| entry.unwrap().file_name().to_string_lossy().into_owned())
            .collect();
        names.sort();
        names
    }

    /// Run a fetch that must fail with `code`; return the requested URLs.
    fn assert_module_fetch_fails(
        code: &str,
        transport: &RecordingTransport,
        args: &ModuleFetchArgs,
        directory: &Path,
        expected_entries: &[&str],
    ) -> Vec<String> {
        let error = fetch_module(transport, args).unwrap_err().to_string();
        assert!(error.contains(code), "expected {code}, got {error}");
        assert_eq!(
            directory_entries(directory),
            expected_entries,
            "a failed fetch leaves no output or staging file"
        );
        transport.requested.lock().unwrap().clone()
    }

    #[test]
    fn module_fetch_follows_one_verified_move_without_changing_package_bytes() {
        let mut manifest =
            DiscoveryManifest::from_json(FIXTURE_MANIFEST, DiscoveryLimits::default()).unwrap();
        let old = manifest.repository.clone();
        let new = graphforge_discovery::RepositoryIdentity::parse("research/renamed").unwrap();
        manifest.repository = new.clone();
        let manifest_bytes = manifest.to_canonical_json().unwrap();
        let mut refs = RefSet::from_json(FIXTURE_REFS, DiscoveryLimits::default()).unwrap();
        refs.repository = new.clone();
        for reference in &mut refs.refs {
            reference.validator = manifest.canonical_digest().unwrap();
        }
        let refs_bytes = refs.to_canonical_json().unwrap();
        let body = serde_json::to_vec(&graphforge_discovery::RepositoryMoved {
            format: "graphforge-repository-moved/1".into(),
            moved_from: old,
            moved_to: new,
        })
        .unwrap();
        let redirect = |suffix| {
            let mut r = response(308, None, &body);
            r.location = Some(format!(
                "https://graphforge.sh/research/renamed/.gf/{suffix}"
            ));
            r
        };
        let package = fixture_module_package();
        let transport = RecordingTransport {
            inner: Scripted::new(vec![
                redirect("refs"),
                redirect("manifest"),
                response(200, None, &refs_bytes),
                response(200, None, &manifest_bytes),
                response(200, None, &package),
            ]),
            requested: Mutex::new(Vec::new()),
        };
        let root = tempfile::tempdir().unwrap();
        let args = fixture_module_args(&root.path().join("module.json"));
        let receipt = fetch_module(&transport, &args).unwrap();
        assert_eq!(receipt["repository"], "research/renamed");
        assert_eq!(receipt["moved_from"], "opendata/openalex");
        assert_eq!(receipt["moved_to"], "research/renamed");
        assert!(args.output.is_file());
        assert_eq!(transport.inner.remaining(), 0);
        let requests = transport.requested.lock().unwrap();
        assert_eq!(requests.len(), 5);
        assert_eq!(
            requests[4],
            manifest
                .ontology_module_selection(&ExactIdentity {
                    id: args.ontology_id.clone().unwrap(),
                    version: args.version.clone().unwrap(),
                    content_digest: Sha256Digest(args.digest.clone().unwrap())
                })
                .unwrap()
                .2
                .locations[0]
        );
    }

    #[test]
    fn module_fetch_rejects_foreign_move_before_target_request_or_output() {
        let body = serde_json::to_vec(&graphforge_discovery::RepositoryMoved {
            format: "graphforge-repository-moved/1".into(),
            moved_from: graphforge_discovery::RepositoryIdentity::parse("opendata/openalex")
                .unwrap(),
            moved_to: graphforge_discovery::RepositoryIdentity::parse("research/renamed").unwrap(),
        })
        .unwrap();
        let mut redirect = response(308, None, &body);
        redirect.location = Some("https://foreign.example/research/renamed/.gf/refs".into());
        let transport = RecordingTransport {
            inner: Scripted::new(vec![redirect]),
            requested: Mutex::new(Vec::new()),
        };
        let root = tempfile::tempdir().unwrap();
        let args = fixture_module_args(&root.path().join("module.json"));
        let requests =
            assert_module_fetch_fails("hub.integrity_failure", &transport, &args, root.path(), &[]);
        assert_eq!(
            requests,
            ["https://graphforge.sh/opendata/openalex/.gf/refs"]
        );
        assert_eq!(transport.inner.remaining(), 0);
    }

    #[test]
    fn module_fetch_requests_only_the_module_package_and_writes_the_verified_document() {
        let manifest =
            DiscoveryManifest::from_json(FIXTURE_MANIFEST, DiscoveryLimits::default()).unwrap();
        let package = fixture_module_package();
        let transport = module_transport(FIXTURE_MANIFEST, &package);
        let root = tempfile::tempdir().unwrap();
        let output = root.path().join("works.json");
        let args = fixture_module_args(&output);
        let receipt = fetch_module(&transport, &args).unwrap();

        assert_eq!(transport.inner.remaining(), 0);
        let identity = ExactIdentity {
            id: args.ontology_id.clone().unwrap(),
            version: args.version.clone().unwrap(),
            content_digest: Sha256Digest(args.digest.clone().unwrap()),
        };
        let (descriptor, advertised, module_object) =
            manifest.ontology_module_selection(&identity).unwrap();
        assert_eq!(
            transport.requested.lock().unwrap().clone(),
            [
                "https://graphforge.sh/opendata/openalex/.gf/refs".to_owned(),
                "https://graphforge.sh/opendata/openalex/.gf/manifest".to_owned(),
                module_object.locations[0].clone(),
            ],
            "refs, manifest, and the module object; never the Project package or summary"
        );
        assert_ne!(module_object.digest, manifest.package.object_digest);

        // The output is exactly the document the verified package carries.
        let package_path = root.path().join("expected.gfpb");
        std::fs::write(&package_path, &package).unwrap();
        let expected = resolve_discovered_ontology_module(&DiscoveryOntologyModuleRequest {
            manifest_json: FIXTURE_MANIFEST,
            refs_json: FIXTURE_REFS,
            expected_repository: &RepositoryIdentity::parse("opendata/openalex").unwrap(),
            module: &identity,
            package: &package_path,
            discovery_limits: DiscoveryLimits::default(),
            portable_limits: PortableLimits::default(),
            cancelled: None,
        })
        .unwrap();
        let written = std::fs::read(&output).unwrap();
        assert_eq!(written, expected.document());
        assert!(!written.is_empty());

        let document_sha256 = hash_reader(&mut std::io::Cursor::new(&written)).unwrap();
        assert_eq!(
            receipt,
            serde_json::json!({
                "contract": "graphforge-hub-module-fetch/1",
                "repository": "opendata/openalex",
                "module": {
                    "ontology_id": descriptor.id,
                    "authored_version": descriptor.version,
                    "canonical_digest": descriptor.content_digest.0.strip_prefix("sha256:").unwrap(),
                },
                "package_digest": advertised.package_digest.0,
                "module_sha256": document_sha256.strip_prefix("sha256:").unwrap(),
                "output": output.display().to_string(),
            })
        );
        assert_eq!(
            directory_entries(root.path()),
            ["expected.gfpb", "works.json"],
            "staging is removed after a successful fetch"
        );
    }

    #[test]
    fn module_fetch_accepts_a_bare_hex_digest_and_a_custom_hub() {
        let package = fixture_module_package();
        let transport = module_transport(FIXTURE_MANIFEST, &package);
        let root = tempfile::tempdir().unwrap();
        let mut args = fixture_module_args(&root.path().join("works.json"));
        // The main fetch test passes the `sha256:`-prefixed form.
        args.digest = Some(
            args.digest
                .as_deref()
                .unwrap()
                .strip_prefix("sha256:")
                .unwrap()
                .to_owned(),
        );
        args.hub = Some("https://hub.example/prefix/".into());
        fetch_module(&transport, &args).unwrap();
        let requested = transport.requested.lock().unwrap().clone();
        assert_eq!(
            requested[..2],
            [
                "https://hub.example/prefix/opendata/openalex/.gf/refs",
                "https://hub.example/prefix/opendata/openalex/.gf/manifest",
            ]
        );
    }

    #[test]
    fn module_fetch_rejects_malformed_inputs_before_any_request() {
        let root = tempfile::tempdir().unwrap();
        let good = fixture_module_args(&root.path().join("works.json"));
        let digest = good.digest.clone();
        let hex = digest
            .as_deref()
            .unwrap()
            .strip_prefix("sha256:")
            .unwrap()
            .to_owned();
        for (change, code) in [
            (
                Box::new(|args: &mut ModuleFetchArgs| args.digest = Some(hex.to_uppercase()))
                    as Box<dyn Fn(&mut ModuleFetchArgs)>,
                "hub.invalid_identity",
            ),
            (
                Box::new(|args| args.digest = Some(hex[..63].to_owned())),
                "hub.invalid_identity",
            ),
            (
                Box::new(|args| args.repository = "not a repository".into()),
                "hub.invalid_identity",
            ),
            (
                Box::new(|args| args.hub = Some("http://hub.example".into())),
                "hub.unsafe_location",
            ),
            (
                Box::new(|args| args.hub = Some("https://127.0.0.1".into())),
                "hub.unsafe_location",
            ),
            (
                Box::new(|args| args.hub = Some("https://user@hub.example".into())),
                "hub.unsafe_location",
            ),
            (
                Box::new(|args| {
                    args.repository = "https://hub.example/opendata/openalex".into();
                    args.hub = Some("https://other.example".into());
                }),
                "hub.invalid_identity",
            ),
            (
                Box::new(|args| args.output = root.path().join("absent-directory/works.json")),
                "hub.destination_conflict",
            ),
        ] {
            let mut args = fixture_module_args(&good.output);
            change(&mut args);
            let transport = module_transport(FIXTURE_MANIFEST, b"unused");
            let requested = assert_module_fetch_fails(code, &transport, &args, root.path(), &[]);
            assert!(requested.is_empty(), "{code}: {requested:?}");
        }
    }

    #[test]
    fn module_fetch_rejects_unsafe_object_locations_before_requesting_the_object() {
        for location in [
            "http://data.example/objects/module",
            "https://user:secret@data.example/objects/module",
            "https://10.0.0.1/objects/module",
            "https://127.0.0.1/objects/module",
        ] {
            let manifest = changed_fixture_manifest(|manifest| {
                module_object_entry(manifest)["locations"] = serde_json::json!([location]);
            });
            let root = tempfile::tempdir().unwrap();
            let args = fixture_module_args(&root.path().join("works.json"));
            let transport = module_transport(&manifest, &fixture_module_package());
            let requested = assert_module_fetch_fails(
                "hub.unsafe_location",
                &transport,
                &args,
                root.path(),
                &[],
            );
            assert_eq!(requested.len(), 2, "{location}: only refs and manifest");
            assert_eq!(transport.inner.remaining(), 1, "{location}");
        }
    }

    #[test]
    fn module_fetch_of_an_unadvertised_identity_is_a_missing_object() {
        let package = fixture_module_package();
        let root = tempfile::tempdir().unwrap();
        for change in [
            Box::new(|args: &mut ModuleFetchArgs| args.version = Some("9999.01".into()))
                as Box<dyn Fn(&mut ModuleFetchArgs)>,
            Box::new(|args| {
                args.ontology_id = Some("https://graphforge.sh/ont_kdeke08bwg6cheea".into())
            }),
            Box::new(|args| args.digest = Some("0".repeat(64))),
        ] {
            let mut args = fixture_module_args(&root.path().join("works.json"));
            change(&mut args);
            let transport = module_transport(FIXTURE_MANIFEST, &package);
            let requested = assert_module_fetch_fails(
                "hub.missing_object",
                &transport,
                &args,
                root.path(),
                &[],
            );
            assert_eq!(requested.len(), 2, "no object is requested: {requested:?}");
        }
        // An advertised module without a per-module package has no object to fetch.
        let manifest = changed_fixture_manifest(|manifest| {
            manifest["ontology"]["modules"][0]
                .as_object_mut()
                .unwrap()
                .remove("package");
        });
        let args = fixture_module_args(&root.path().join("works.json"));
        let transport = module_transport(&manifest, &package);
        let requested =
            assert_module_fetch_fails("hub.missing_object", &transport, &args, root.path(), &[]);
        assert_eq!(requested.len(), 2);
    }

    #[test]
    fn module_fetch_enforces_the_module_byte_bound() {
        let package = fixture_module_package();
        // A descriptor larger than the module bound fails before the object is requested.
        let manifest = changed_fixture_manifest(|manifest| {
            module_object_entry(manifest)["length"] =
                serde_json::json!(MAX_MODULE_PACKAGE_BYTES + 1);
        });
        let root = tempfile::tempdir().unwrap();
        let args = fixture_module_args(&root.path().join("works.json"));
        let transport = module_transport(&manifest, &package);
        let requested =
            assert_module_fetch_fails("hub.limit_exceeded", &transport, &args, root.path(), &[]);
        assert_eq!(requested.len(), 2);

        // A body longer than the declared length is cut off and rejected.
        let mut longer = package.clone();
        longer.push(0);
        let transport = module_transport(FIXTURE_MANIFEST, &longer);
        let requested =
            assert_module_fetch_fails("hub.limit_exceeded", &transport, &args, root.path(), &[]);
        assert_eq!(requested.len(), 3);

        // A body shorter than the declared length is incomplete, not accepted.
        let transport = module_transport(FIXTURE_MANIFEST, &package[..package.len() - 1]);
        assert_module_fetch_fails("hub.interrupted", &transport, &args, root.path(), &[]);
    }

    #[test]
    fn module_fetch_rejects_corrupt_bytes_and_publishes_nothing() {
        let package = fixture_module_package();
        let root = tempfile::tempdir().unwrap();
        let args = fixture_module_args(&root.path().join("works.json"));

        // Same length, different bytes: the transport digest disagrees.
        let mut corrupt = package.clone();
        let middle = corrupt.len() / 2;
        corrupt[middle] ^= 0xff;
        let transport = module_transport(FIXTURE_MANIFEST, &corrupt);
        let requested =
            assert_module_fetch_fails("hub.integrity", &transport, &args, root.path(), &[]);
        assert_eq!(requested.len(), 3);

        // Bytes that match their transport digest but are not a valid package
        // are rejected by the portable verifier.
        let garbage = vec![7_u8; package.len()];
        let garbage_digest = hash_reader(&mut std::io::Cursor::new(&garbage)).unwrap();
        let manifest = changed_fixture_manifest(|manifest| {
            let advertised = manifest["ontology"]["modules"][0]["package"]["object_digest"].clone();
            module_object_entry(manifest)["digest"] = serde_json::json!(garbage_digest);
            manifest["ontology"]["modules"][0]["package"]["object_digest"] =
                serde_json::json!(garbage_digest);
            assert_ne!(advertised, serde_json::json!(garbage_digest));
            manifest["objects"]
                .as_array_mut()
                .unwrap()
                .sort_by(|a, b| a["digest"].as_str().cmp(&b["digest"].as_str()));
        });
        let transport = module_transport(&manifest, &garbage);
        assert_module_fetch_fails("hub.package.", &transport, &args, root.path(), &[]);

        // A genuine package that is not the advertised one fails the identity binding.
        let manifest = changed_fixture_manifest(|manifest| {
            manifest["ontology"]["modules"][0]["package"]["package_digest"] =
                serde_json::json!(format!("sha256:{}", "e".repeat(64)));
        });
        let transport = module_transport(&manifest, &package);
        assert_module_fetch_fails(
            "hub.package.package_digest_mismatch",
            &transport,
            &args,
            root.path(),
            &[],
        );

        // A package whose verified manifest names another producer than the
        // advertisement is refused, even though its digest matches.
        let manifest = changed_fixture_manifest(|manifest| {
            manifest["ontology"]["modules"][0]["package"]["producing_core_version"] =
                serde_json::json!("0.0.1");
        });
        let transport = module_transport(&manifest, &package);
        assert_module_fetch_fails(
            "hub.package.producing_core_version_mismatch",
            &transport,
            &args,
            root.path(),
            &[],
        );
    }

    #[test]
    fn module_fetch_refuses_an_existing_output_without_touching_it() {
        let root = tempfile::tempdir().unwrap();
        let output = root.path().join("works.json");
        std::fs::write(&output, b"precious").unwrap();
        let args = fixture_module_args(&output);
        let transport = module_transport(FIXTURE_MANIFEST, &fixture_module_package());
        let requested = assert_module_fetch_fails(
            "hub.destination_conflict",
            &transport,
            &args,
            root.path(),
            &["works.json"],
        );
        assert!(requested.is_empty(), "refused before any request");
        assert_eq!(std::fs::read(&output).unwrap(), b"precious");
    }

    #[cfg(unix)]
    #[test]
    fn module_fetch_refuses_a_dangling_symlink_output() {
        let root = tempfile::tempdir().unwrap();
        let output = root.path().join("works.json");
        std::os::unix::fs::symlink(root.path().join("elsewhere"), &output).unwrap();
        let args = fixture_module_args(&output);
        let transport = module_transport(FIXTURE_MANIFEST, &fixture_module_package());
        assert_module_fetch_fails(
            "hub.destination_conflict",
            &transport,
            &args,
            root.path(),
            &["works.json"],
        );
        assert!(!root.path().join("elsewhere").exists());
    }

    /// Creates `output` the moment the module object is requested.
    struct CreatesOutputDuringFetch {
        inner: RecordingTransport,
        output: PathBuf,
    }

    impl Transport for CreatesOutputDuringFetch {
        fn get(
            &self,
            url: &Url,
            range: Option<u64>,
            if_range: Option<&str>,
            limit: u64,
        ) -> Result<HttpResponse, graphforge_api::GfError> {
            if self.inner.requested.lock().unwrap().len() == 2 {
                std::fs::write(&self.output, b"created concurrently").unwrap();
            }
            self.inner.get(url, range, if_range, limit)
        }
    }

    #[cfg(unix)]
    #[test]
    fn a_filesystem_without_hard_links_is_a_stable_conflict_not_a_storage_error() {
        for code in [libc::EPERM, libc::ENOTSUP, libc::EOPNOTSUPP] {
            let error = hard_link_error(std::io::Error::from_raw_os_error(code)).to_string();
            assert!(
                error.contains("hub.destination_conflict")
                    && error.contains("output filesystem cannot publish atomically"),
                "{code}: {error}"
            );
        }
        // Permission to write the directory is a different failure.
        let error = hard_link_error(std::io::Error::from_raw_os_error(libc::EACCES)).to_string();
        assert!(!error.contains("hub.destination_conflict"), "{error}");
    }

    #[test]
    fn staging_release_empties_it_under_the_lock_and_never_clobbers_a_new_lock() {
        let root = tempfile::tempdir().unwrap();
        let output = root.path().join("works.json");
        let staging = acquire_staging(&output).unwrap();
        let staging_root = staging.root.clone();
        for name in ["package.part", "package.resume.json", "module.out"] {
            std::fs::write(staging_root.join(name), b"staged").unwrap();
        }
        clear_staging(&staging);
        assert_eq!(
            directory_entries(&staging_root),
            Vec::<String>::new(),
            "contents and lock file go while the lock is held"
        );
        // A concurrent fetch re-creates its lock while ours is being released;
        // our final removal fails harmlessly and leaves its staging alone.
        let concurrent = acquire_staging(&output).unwrap();
        std::fs::write(&concurrent.partial, b"theirs").unwrap();
        drop(staging);
        remove_staging_dir(&staging_root);
        assert_eq!(
            std::fs::read(&concurrent.partial).unwrap(),
            b"theirs",
            "the concurrent fetch's files survive"
        );
        assert!(
            acquire_staging(&output)
                .is_err_and(|error| error.to_string().contains("hub.concurrent_clone")),
            "its lock still excludes a third fetch"
        );
        drop(concurrent);

        // The real release leaves nothing behind.
        let staging = acquire_staging(&output).unwrap();
        std::fs::write(&staging.partial, b"staged").unwrap();
        release_staging(staging);
        assert!(!staging_root.exists());
        assert_eq!(directory_entries(root.path()), Vec::<String>::new());
    }

    #[test]
    fn module_fetch_never_replaces_an_output_created_during_the_fetch() {
        let root = tempfile::tempdir().unwrap();
        let output = root.path().join("works.json");
        let transport = CreatesOutputDuringFetch {
            inner: module_transport(FIXTURE_MANIFEST, &fixture_module_package()),
            output: output.clone(),
        };
        let error = fetch_module(&transport, &fixture_module_args(&output))
            .unwrap_err()
            .to_string();
        assert!(error.contains("hub.destination_conflict"), "{error}");
        assert_eq!(std::fs::read(&output).unwrap(), b"created concurrently");
        assert_eq!(directory_entries(root.path()), ["works.json"]);
    }
}