~ knotless Search/
↑↓ move↵ open⇧↵ all results

johnandersen777.bsky.social/vuln-notif

0
0
main
300 lines · 10.0 KB Raw History
//! Release project/version metadata records, links, and write preflight.
//! Reads checked-in fixtures and lexicons only; no network.

#[path = "../src/release/metadata.rs"]
mod metadata;

// `metadata.rs` is not yet declared by `src/release/mod.rs`; this shim lets
// the same file compile inside this test crate with its `crate::` imports.
mod constants {
    pub use vuln_notif::constants::*;
}

use serde_json::{Value, json};
use vuln_notif::constants::{
    CHANNEL_COLLECTION, MANIFEST_COLLECTION, PROJECT_COLLECTION, VERSION_COLLECTION,
};
use vuln_notif::db::DbHandle;
use vuln_notif::links::{extract_links, index_record};

use metadata::{
    GitMeta, ProjectMeta, Target, VersionMeta, assert_put_allowed, assert_same_did,
    build_manifest_artifacts, git_metadata_json, is_immutable, project_meta_record,
    version_meta_json,
};

const DID: &str = "did:plc:test";
const SLUG: &str = "acme-widget";
const PROJECT_URI: &str = "at://did:plc:test/software.release.project/acme-widget";

const PROJECT_META_FIXTURE: &str = include_str!("fixtures/metadata/project_meta.json");
const GIT_META_FIXTURE: &str = include_str!("fixtures/metadata/git_meta.json");
const MANIFEST_FIXTURE: &str = include_str!("fixtures/metadata/expected_manifest.json");
const PROJECT_META_LEXICON: &str = include_str!("../lexicons/com/nahdig/release.projectMeta.json");
const GIT_META_LEXICON: &str = include_str!("../lexicons/com/nahdig/release.gitMeta.json");

fn fixture(text: &str) -> Value {
    serde_json::from_str(text).expect("metadata fixture")
}

fn project_meta() -> ProjectMeta {
    ProjectMeta {
        description: Some("Widget toolkit".to_owned()),
        homepage: Some("https://example.com/acme-widget".to_owned()),
        license: Some("MIT".to_owned()),
        repository: Some("https://example.com/acme-widget.git".to_owned()),
        versioning_scheme: Some("semver".to_owned()),
    }
}

fn git_meta() -> GitMeta {
    GitMeta {
        repository: "https://example.com/acme-widget.git".to_owned(),
        revision: Some("refs/tags/v1.2.3".to_owned()),
        commit: Some("0123456789abcdef0123456789abcdef01234567".to_owned()),
    }
}

fn target() -> Target {
    Target {
        os: Some("linux".to_owned()),
        architectures: vec!["amd64".to_owned(), "arm64".to_owned()],
    }
}

fn manifest_artifacts() -> Vec<Value> {
    vec![
        json!({
            "$type": "software.release.defs#httpArtifact",
            "fileName": "acme-widget-1.2.3.tar.gz",
            "url": "https://example.com/acme-widget-1.2.3.tar.gz",
            "cid": "bafkreiacme",
            "size": 1024,
            "mimeType": "application/gzip",
        }),
        json!({
            "$type": "software.release.defs#blobArtifact",
            "fileName": "acme-widget-1.2.3-py3-none-any.whl",
            "blob": {
                "$type": "blob",
                "ref": {"$link": "bafkblob"},
                "mimeType": "application/zip",
                "size": 2048,
            },
        }),
    ]
}

#[test]
fn project_meta_record_matches_fixture_and_uses_slug_as_rkey() {
    let record = project_meta_record(DID, SLUG, &project_meta());
    assert_eq!(record, fixture(PROJECT_META_FIXTURE));
    assert_eq!(record["$type"], json!(metadata::PROJECT_META_COLLECTION));
    assert_eq!(record["name"], json!(SLUG));
    assert_eq!(record["versioningScheme"], json!("semver"));

    let project = record["project"].as_str().expect("project at-uri");
    assert_eq!(project, PROJECT_URI);
    assert_same_did(DID, project).unwrap();
    assert!(assert_same_did("did:plc:other", project).is_err());
    assert!(assert_same_did(DID, "https://example.com/acme-widget").is_err());
    assert!(assert_same_did(DID, "at://did:plc:test").is_err());
}

#[test]
fn project_meta_omits_absent_optional_fields() {
    let record = project_meta_record(DID, SLUG, &ProjectMeta::default());
    assert_eq!(
        record,
        json!({
            "$type": metadata::PROJECT_META_COLLECTION,
            "project": PROJECT_URI,
            "name": SLUG,
        })
    );
}

#[test]
fn git_metadata_fragment_matches_lexicon_shape() {
    let fragment = git_metadata_json(&git_meta());
    assert_eq!(fragment, fixture(GIT_META_FIXTURE));
    // The open artifact metadata union does not require a $type.
    assert!(fragment.get("$type").is_none());
}

#[test]
fn manifest_artifacts_attach_git_metadata_and_target() {
    let expected = fixture(MANIFEST_FIXTURE);
    let inputs = manifest_artifacts();

    let built = build_manifest_artifacts(&inputs, Some(&git_meta()), Some(&target()));
    assert_eq!(json!(built), expected["artifacts"]);
    assert_eq!(
        built[0]["$type"],
        json!("software.release.defs#httpArtifact")
    );
    assert_eq!(
        built[1]["$type"],
        json!("software.release.defs#blobArtifact")
    );
    assert_eq!(built[0]["metadata"], json!([fixture(GIT_META_FIXTURE)]));
    assert_eq!(
        built[1]["target"],
        json!({"os": "linux", "architectures": ["amd64", "arm64"]})
    );
    assert_eq!(
        built[0]["target"]["architectures"]
            .as_array()
            .unwrap()
            .len(),
        2
    );

    // With no metadata requested, fragments pass through unchanged.
    assert_eq!(build_manifest_artifacts(&inputs, None, None), inputs);

    // Existing metadata fragments are preserved and the git fragment appended.
    let mut with_metadata = inputs[0].clone();
    with_metadata["metadata"] = json!([{"$type": "com.example.extra", "note": "keep"}]);
    let built = build_manifest_artifacts(&[with_metadata], Some(&git_meta()), None);
    assert_eq!(built[0]["metadata"].as_array().unwrap().len(), 2);
    assert_eq!(built[0]["metadata"][0]["note"], json!("keep"));
    assert_eq!(built[0]["metadata"][1], fixture(GIT_META_FIXTURE));

    // Non-object fragments pass through untouched.
    let scalar = json!("not-an-artifact");
    assert_eq!(
        build_manifest_artifacts(
            std::slice::from_ref(&scalar),
            Some(&git_meta()),
            Some(&target())
        ),
        vec![scalar]
    );
}

#[test]
fn version_meta_json_exposes_labels_and_source_facts() {
    let meta = VersionMeta {
        published_at: Some("2026-01-02T03:04:05Z".to_owned()),
        raw_version: "v1.2.3".to_owned(),
        target: Some(target()),
        git: Some(git_meta()),
        changelog_uri: Some("https://example.com/acme-widget/changelog".to_owned()),
    };
    let value = version_meta_json(&meta);
    assert_eq!(value["versionLabels"], json!(["v1.2.3"]));
    assert_eq!(value["publishedAt"], json!("2026-01-02T03:04:05Z"));
    assert_eq!(
        value["changelog"],
        json!("https://example.com/acme-widget/changelog")
    );
    assert_eq!(value["target"]["os"], json!("linux"));
    assert_eq!(value["git"], fixture(GIT_META_FIXTURE));
    assert!(value.get("$type").is_none());

    let empty = version_meta_json(&VersionMeta::default());
    assert!(empty.get("versionLabels").is_none());
    assert_eq!(empty, json!({}));
}

#[tokio::test]
async fn project_meta_links_index_under_project() {
    let db = DbHandle::open_in_memory().await.unwrap();
    let record = project_meta_record(DID, SLUG, &project_meta());

    let links = extract_links(metadata::PROJECT_META_COLLECTION, &record);
    assert_eq!(links.len(), 1);
    assert_eq!(links[0].path, "project");
    assert_eq!(links[0].subject_uri, PROJECT_URI);
    assert_eq!(links[0].subject_cid, None);

    let src = format!("at://{DID}/{}/{SLUG}", metadata::PROJECT_META_COLLECTION);
    index_record(
        &db,
        DID,
        &src,
        Some("bafymeta"),
        metadata::PROJECT_META_COLLECTION,
        &record,
    )
    .await
    .unwrap();
    db.commit().await.unwrap();

    let rows = db
        .backlinks(
            DID,
            PROJECT_URI,
            Some(metadata::PROJECT_META_COLLECTION),
            Some("project"),
            10,
        )
        .await
        .unwrap();
    assert_eq!(rows.len(), 1);
    assert_eq!(rows[0].src_uri, src);
    assert_eq!(rows[0].src_cid.as_deref(), Some("bafymeta"));
    assert_eq!(rows[0].subject_cid, None);
}

#[test]
fn immutable_preflight_rejects_put_on_manifest_and_version() {
    for collection in [MANIFEST_COLLECTION, VERSION_COLLECTION] {
        assert!(is_immutable(collection), "{collection}");
        let error = assert_put_allowed(collection, true).unwrap_err();
        assert!(error.to_string().contains("immutable"), "{error}");
        assert!(
            assert_put_allowed(collection, false).is_ok(),
            "creating {collection} is allowed"
        );
    }
    for collection in [
        PROJECT_COLLECTION,
        CHANNEL_COLLECTION,
        metadata::PROJECT_META_COLLECTION,
    ] {
        assert!(!is_immutable(collection), "{collection}");
        assert!(assert_put_allowed(collection, true).is_ok(), "{collection}");
    }
}

#[test]
fn metadata_lexicons_expose_required_fields() {
    let project_meta = fixture(PROJECT_META_LEXICON);
    assert_eq!(project_meta["id"], json!("com.nahdig.release.projectMeta"));
    assert_eq!(project_meta["lexicon"], json!(1));
    let main = &project_meta["defs"]["main"];
    assert_eq!(main["type"], json!("record"));
    assert_eq!(main["key"], json!("any"));
    assert_eq!(main["record"]["required"], json!(["project", "name"]));
    assert_eq!(
        main["record"]["properties"]["project"]["format"],
        json!("at-uri")
    );
    assert_eq!(main["record"]["properties"]["name"]["maxLength"], json!(64));
    for name in [
        "description",
        "homepage",
        "license",
        "repository",
        "versioningScheme",
    ] {
        assert!(
            main["record"]["properties"][name].is_object(),
            "projectMeta missing {name}"
        );
    }

    let git_meta = fixture(GIT_META_LEXICON);
    assert_eq!(git_meta["id"], json!("com.nahdig.release.gitMeta"));
    assert_eq!(git_meta["lexicon"], json!(1));
    let main = &git_meta["defs"]["main"];
    assert_eq!(main["type"], json!("object"));
    for name in ["repository", "revision", "commit", "tag"] {
        assert!(
            main["properties"][name].is_object(),
            "gitMeta missing {name}"
        );
    }
}