midenup 1.0.0-beta.1

The Miden toolchain manager
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
use std::{
    borrow::Cow,
    collections::BTreeMap,
    fmt,
    path::{Path, PathBuf},
};

use serde::{Deserialize, Serialize};

use crate::{
    manifest::{Component, ComponentKind},
    version::Authority,
};

#[derive(Debug, thiserror::Error)]
pub enum InvalidArtifactError {
    #[error("invalid artifact: no uri scheme for artifact {id} of {component}")]
    MissingScheme { id: String, component: String },
    #[error(
        "invalid artifact: invalid scheme for artifact {id} of {component}: expected file://, http://, or https://, got '{scheme}'"
    )]
    InvalidScheme {
        id: String,
        component: String,
        scheme: String,
    },
    #[error(
        "invalid artifact: %version substitution is invalid for artifact {id} of {component}: \
         component has no known semantic version"
    )]
    VersionUnavailable { id: String, component: String },
    #[error("invalid artifact: {substitution} is not defined for artifact {id} of {component}")]
    UndefinedSubstitution {
        id: String,
        component: String,
        substitution: &'static str,
    },
    #[error(
        "invalid artifact: uri is missing %target substitution for artifact {id} of {component} \
         when target is '{target}'"
    )]
    MissingTarget {
        id: String,
        component: String,
        target: String,
    },
}

/// All the artifacts that the [Component] contains.
#[derive(Serialize, Deserialize, Default, Debug, Clone, Hash, PartialEq)]
#[serde(transparent)]
pub struct Artifacts {
    pub(crate) artifacts: BTreeMap<String, Artifact>,
}

impl Artifacts {
    pub fn is_empty(&self) -> bool {
        self.artifacts.is_empty()
    }

    pub fn insert(&mut self, id: String, artifact: Artifact) -> bool {
        self.artifacts.insert(id, artifact).is_none()
    }

    /// Returns the `(artifact id, uri)` pairs that should be installed for `target`.
    ///
    /// The artifact id is the exact filename the artifact is installed as, so callers must use it
    /// to compute a destination path rather than inferring one from the URI.
    pub fn get_default_artifacts_for_target<'a>(
        &'a self,
        target: &str,
        component: &'a Component,
    ) -> Result<Vec<(&'a str, ArtifactUri)>, InvalidArtifactError> {
        match component.kind() {
            ComponentKind::Asset => self.get_artifacts_for_target(target, component),
            ComponentKind::CargoExtension { spec, .. } | ComponentKind::Executable { spec, .. } => {
                let id = spec.installed_executable.as_str();
                let artifact = self.get_artifact_for_target(id, target, component)?;
                Ok(artifact.into_iter().map(|uri| (id, uri)).collect())
            },
            // Never selected for installation, so it has no artifacts to resolve. The resolver
            // is the gate that rejects it; this arm just keeps the match total.
            ComponentKind::Command { .. } | ComponentKind::Unsupported { .. } => Ok(vec![]),
            ComponentKind::LegacyPackage { .. } | ComponentKind::Package => {
                self.get_artifacts_for_target(target, component)
            },
        }
    }

    /// Returns every declared `(artifact id, uri)` pair available for `target`.
    pub fn get_artifacts_for_target(
        &self,
        target: &str,
        component: &Component,
    ) -> Result<Vec<(&str, ArtifactUri)>, InvalidArtifactError> {
        let mut artifacts = Vec::with_capacity(self.artifacts.len());
        for (id, artifact) in self.artifacts.iter() {
            if let Some(uri) = artifact.get_uri_for(id, target, component)? {
                artifacts.push((id.as_str(), uri));
            }
        }

        Ok(artifacts)
    }

    pub fn get_artifact_for_target(
        &self,
        id: &str,
        target: &str,
        component: &Component,
    ) -> Result<Option<ArtifactUri>, InvalidArtifactError> {
        let Some(artifact) = self.artifacts.get(id) else {
            return Ok(None);
        };
        artifact.get_uri_for(id, target, component)
    }
}

/// Holds a URI used to fetch an artifact.
///
/// These URIs have the following format:
///
/// * `(https://|file://)<path>/<component name>(-<triplet>)?(<extension>)`
///
/// # Forward compatibility
///
/// Like every other schema type, an artifact preserves fields this build does not recognize
/// (spec section 4.4). It needs hand-written `Serialize`/`Deserialize` for the same reason
/// [crate::manifest::Component] does: `TargetSpecific` already flattens `substitutions`, so a
/// catch-all `#[serde(flatten)]` would capture the keys that flatten consumed and emit them twice.
///
/// Deserialization also dispatches on the presence of `targets` rather than falling back through an
/// untagged enum. An untagged fallback reports "data did not match any variant", which says nothing
/// about which field was actually wrong.
#[derive(Debug, Clone, Hash, PartialEq)]
pub enum Artifact {
    /// An artifact compiled for a specific target
    TargetSpecific {
        /// The URI from which to fetch this artifact, containing substitution patterns for the
        /// variable/target-sensitive portions of the artifact file.
        ///
        /// The basic URI format should use one of two schemes: `file://` or `http(s)://`, e.g.:
        ///
        /// ```
        /// file://path/to/artifacts/%basename-%target.%extension
        /// ```
        ///
        /// ```
        /// https://github.com/org/repo/releases/%version/download/%basename-%target.%extension
        /// ```
        ///
        /// The following substitutions and their values are available:
        ///
        /// * `%version` - the version of the containing component. This requires that the
        ///   component has an associated semantic version declared in the manifest, or an error
        ///   will be produced
        /// * `%basename` - the value of `basename` if present, defaults to the component name
        /// * `%extension` - the value of `extension`, if present
        /// * `%target` - the current target triple
        ///
        /// The only substitution required to be present is `%target` - the other substituions are
        /// optional, and can be used at your convenience.
        uri: String,
        /// Substitutions that apply to all targets
        substitutions: Option<Substitutions>,
        /// The supported target triples for this artifact, and their target-specific substitutions
        targets: BTreeMap<String, Substitutions>,
        /// An optional content digest. Recorded and round-tripped, never verified. See [Digest].
        digest: Option<Digest>,
        /// Fields declared by a newer schema that this build does not recognize.
        extra: crate::manifest::v3::unknown::Extra,
    },
    /// A non-executable/target-agnostic asset
    TargetAgnostic {
        /// The URI for this artifact, including the filename component
        ///
        /// The URI may contain the `%version` substitution string, which will be replaced with
        /// the version of the containing component. Note that `%version` requires that the
        /// component have an associated semantic version, or an error will be produced.
        uri: String,
        /// An optional content digest. Recorded and round-tripped, never verified. See [Digest].
        digest: Option<Digest>,
        /// Fields declared by a newer schema that this build does not recognize.
        extra: crate::manifest::v3::unknown::Extra,
    },
}

/// The typed shape of an artifact, without the unknown-field capture.
///
/// Kept in lockstep with [Artifact] by construction: it is what the hand-written impls below
/// serialize through, so "known" means exactly "what this emits".
#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(untagged, rename_all = "kebab-case")]
enum ArtifactFields {
    TargetSpecific {
        uri: String,
        #[serde(flatten, skip_serializing_if = "Option::is_none")]
        substitutions: Option<Substitutions>,
        targets: BTreeMap<String, Substitutions>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        digest: Option<Digest>,
    },
    TargetAgnostic {
        uri: String,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        digest: Option<Digest>,
    },
}

impl Artifact {
    fn fields(&self) -> ArtifactFields {
        match self {
            Self::TargetSpecific { uri, substitutions, targets, digest, .. } => {
                ArtifactFields::TargetSpecific {
                    uri: uri.clone(),
                    substitutions: substitutions.clone(),
                    targets: targets.clone(),
                    digest: digest.clone(),
                }
            },
            Self::TargetAgnostic { uri, digest, .. } => {
                ArtifactFields::TargetAgnostic { uri: uri.clone(), digest: digest.clone() }
            },
        }
    }

    fn extra(&self) -> &crate::manifest::v3::unknown::Extra {
        match self {
            Self::TargetSpecific { extra, .. } | Self::TargetAgnostic { extra, .. } => extra,
        }
    }
}

impl Serialize for Artifact {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        use serde::ser::Error;

        crate::manifest::v3::unknown::merge_extra(&self.fields(), self.extra())
            .map_err(S::Error::custom)?
            .serialize(serializer)
    }
}

impl<'de> Deserialize<'de> for Artifact {
    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        use serde::de::Error;

        let value = serde_json::Value::deserialize(deserializer)?;

        // `targets` is what distinguishes the two shapes, and saying so produces a better
        // diagnostic than the untagged fallback's "data did not match any variant" -- which names
        // no field at all.
        if value.get("targets").is_some_and(|targets| !targets.is_object()) {
            return Err(D::Error::custom(
                "an artifact's `targets` must be a map of target triple to substitutions",
            ));
        }

        let (fields, extra) = crate::manifest::v3::unknown::split_extra::<ArtifactFields>(value)
            .map_err(D::Error::custom)?;

        Ok(match fields {
            ArtifactFields::TargetSpecific { uri, substitutions, targets, digest } => {
                Self::TargetSpecific {
                    uri,
                    substitutions,
                    targets,
                    digest,
                    extra,
                }
            },
            ArtifactFields::TargetAgnostic { uri, digest } => {
                Self::TargetAgnostic { uri, digest, extra }
            },
        })
    }
}

impl Artifact {
    /// The declared content digest, if any. Never verified -- see [Digest].
    pub fn digest(&self) -> Option<&Digest> {
        match self {
            Self::TargetSpecific { digest, .. } | Self::TargetAgnostic { digest, .. } => {
                digest.as_ref()
            },
        }
    }
}

/// The value of user-defined substitutions in [Artifact] definitions
#[derive(Serialize, Deserialize, Default, Debug, Clone, Hash, PartialEq)]
pub struct Substitutions {
    /// The basename to use for the artifact, e.g. `foo` in `foo-aarch64-apple-darwin.ext`
    ///
    /// If not provided, the component name is used as the basename.
    ///
    /// The basename is only relevant if actually used via `%basename`
    #[serde(skip_serializing_if = "Option::is_none")]
    pub basename: Option<String>,
    /// The extension to use for this artifact, e.g. `masp`
    ///
    /// The default extension is determined by the component type
    #[serde(skip_serializing_if = "Option::is_none")]
    pub extension: Option<String>,
    /// Fields declared by a newer schema that this build does not recognize.
    #[serde(flatten)]
    pub extra: crate::manifest::v3::unknown::Extra,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ArtifactUri {
    File(PathBuf),
    Http(String),
}

impl ArtifactUri {
    pub fn file_name(&self) -> Option<&Path> {
        match self {
            Self::File(path) => path.file_name().map(Path::new),
            Self::Http(uri) => {
                let (_, last) = uri.rsplit_once('/')?;
                Some(Path::new(last.trim()))
            },
        }
    }
}

impl fmt::Display for ArtifactUri {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::File(path) => write!(f, "file://{}", path.display()),
            Self::Http(uri) => f.write_str(uri),
        }
    }
}

impl Artifact {
    pub fn get_uris_for(
        &self,
        id: &str,
        component: &Component,
    ) -> Result<Vec<ArtifactUri>, InvalidArtifactError> {
        let mut artifacts = vec![];
        match self {
            Self::TargetAgnostic { .. } => {
                if let Some(artifact) = self.get_uri_for(id, "", component)? {
                    artifacts.push(artifact);
                }
            },
            Self::TargetSpecific { targets, .. } => {
                for target in targets.keys() {
                    if let Some(artifact) = self.get_uri_for(id, target, component)? {
                        artifacts.push(artifact);
                    }
                }
            },
        }

        Ok(artifacts)
    }

    /// Returns the URI for the specified target, with the provided component details for use in
    /// substitution patterns:
    pub fn get_uri_for(
        &self,
        id: &str,
        target: &str,
        component: &Component,
    ) -> Result<Option<ArtifactUri>, InvalidArtifactError> {
        match self {
            Self::TargetAgnostic { uri, .. } => {
                let Some((scheme, rest)) = uri.split_once("://") else {
                    return Err(InvalidArtifactError::MissingScheme {
                        id: id.to_string(),
                        component: component.name.to_string(),
                    });
                };
                let rest = if rest.contains("%version") {
                    let Authority::Registry { version } = &component.version else {
                        return Err(InvalidArtifactError::VersionUnavailable {
                            id: id.to_string(),
                            component: component.name.to_string(),
                        });
                    };
                    Cow::Owned(rest.replace("%version", &version.to_string()))
                } else {
                    Cow::Borrowed(rest)
                };
                match scheme {
                    "file" => Ok(Some(ArtifactUri::File(PathBuf::from(rest.into_owned())))),
                    "http" | "https" => Ok(Some(ArtifactUri::Http(format!("{scheme}://{rest}")))),
                    scheme => Err(InvalidArtifactError::InvalidScheme {
                        id: id.to_string(),
                        component: component.name.to_string(),
                        scheme: scheme.to_string(),
                    }),
                }
            },
            Self::TargetSpecific { uri, substitutions, targets, .. } => {
                let Some(target_subs) = targets.get(target) else {
                    return Ok(None);
                };
                let basename = target_subs
                    .basename
                    .as_deref()
                    .or(substitutions.as_ref().and_then(|subs| subs.basename.as_deref()))
                    .unwrap_or(component.name.as_ref());
                let extension = target_subs
                    .extension
                    .as_deref()
                    .or(substitutions.as_ref().and_then(|subs| subs.extension.as_deref()));
                let Some((scheme, rest)) = uri.split_once("://") else {
                    return Err(InvalidArtifactError::MissingScheme {
                        id: id.to_string(),
                        component: component.name.to_string(),
                    });
                };
                if !rest.contains("%target") {
                    return Err(InvalidArtifactError::MissingTarget {
                        id: id.to_string(),
                        component: component.name.to_string(),
                        target: target.to_string(),
                    });
                }
                let rest = rest.replace("%target", target);
                let rest = if rest.contains("%version") {
                    let Authority::Registry { version } = &component.version else {
                        return Err(InvalidArtifactError::VersionUnavailable {
                            id: id.to_string(),
                            component: component.name.to_string(),
                        });
                    };
                    rest.replace("%version", &version.to_string())
                } else {
                    rest
                };
                let rest = if rest.contains("%extension") {
                    let extension =
                        extension.ok_or_else(|| InvalidArtifactError::UndefinedSubstitution {
                            id: id.to_string(),
                            component: component.name.to_string(),
                            substitution: "%extension",
                        })?;
                    rest.replace("%extension", extension)
                } else {
                    rest
                };
                let rest = rest.replace("%basename", basename);
                match scheme {
                    "file" => Ok(Some(ArtifactUri::File(PathBuf::from(rest)))),
                    "http" | "https" => Ok(Some(ArtifactUri::Http(format!("{scheme}://{rest}")))),
                    scheme => Err(InvalidArtifactError::InvalidScheme {
                        id: id.to_string(),
                        component: component.name.to_string(),
                        scheme: scheme.to_string(),
                    }),
                }
            },
        }
    }
}

/// A content digest declared for an artifact, e.g. `sha256:9f86d081...`.
///
/// Reserved, not enforced: the value is validated for shape, recorded, and round-tripped, but no
/// verification is performed against downloaded bytes. Turning verification on later is then a
/// behavior change rather than a schema break.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Digest {
    pub algorithm: String,
    pub hex: String,
}

#[derive(Debug, thiserror::Error, PartialEq, Eq)]
pub enum InvalidDigestError {
    #[error("invalid digest '{0}': expected the form '<algorithm>:<hex>'")]
    Malformed(String),
    #[error("invalid digest '{0}': the digest value must be non-empty lowercase hex")]
    NotHex(String),
}

impl core::str::FromStr for Digest {
    type Err = InvalidDigestError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let Some((algorithm, hex)) = s.split_once(':') else {
            return Err(InvalidDigestError::Malformed(s.to_string()));
        };
        if algorithm.is_empty() {
            return Err(InvalidDigestError::Malformed(s.to_string()));
        }
        if hex.is_empty() || !hex.bytes().all(|b| b.is_ascii_digit() || b.is_ascii_lowercase()) {
            return Err(InvalidDigestError::NotHex(s.to_string()));
        }
        if !hex.bytes().all(|b| b.is_ascii_hexdigit()) {
            return Err(InvalidDigestError::NotHex(s.to_string()));
        }
        Ok(Self {
            algorithm: algorithm.to_string(),
            hex: hex.to_string(),
        })
    }
}

impl fmt::Display for Digest {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}:{}", self.algorithm, self.hex)
    }
}

impl Serialize for Digest {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        serializer.serialize_str(&self.to_string())
    }
}

impl<'de> Deserialize<'de> for Digest {
    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        use serde::de::Error;
        let raw = String::deserialize(deserializer)?;
        raw.parse().map_err(D::Error::custom)
    }
}

#[cfg(test)]
mod digest_tests {
    use super::*;

    #[test]
    fn digest_parses_and_round_trips() {
        let d: Digest = "sha256:9f86d081884c7d659a2feaa0c55ad015".parse().unwrap();
        assert_eq!(d.algorithm, "sha256");
        assert_eq!(d.to_string(), "sha256:9f86d081884c7d659a2feaa0c55ad015");
    }

    #[test]
    fn malformed_digest_is_rejected() {
        assert!("9f86d081".parse::<Digest>().is_err(), "missing algorithm");
        assert!(":abc".parse::<Digest>().is_err(), "empty algorithm");
        assert!("sha256:".parse::<Digest>().is_err(), "empty hex");
        assert!("sha256:zzzz".parse::<Digest>().is_err(), "non-hex");
        assert!("sha256:ABCD".parse::<Digest>().is_err(), "uppercase hex");
    }

    /// The digest survives a manifest round-trip and is not verified against anything.
    #[test]
    fn digest_round_trips_through_a_manifest() {
        let src = serde_json::json!({
            "manifest_version": "3.0.0",
            "date": 1735689600,
            "channels": [{"name": "0.15.0", "components": [{
                "name": "core",
                "version": {"kind": "registry", "version": "0.23.4"},
                "kind": "package",
                "artifacts": {"core.masp": {
                    "uri": "https://example.invalid/core.masp",
                    "digest": "sha256:deadbeef"
                }}
            }]}]
        })
        .to_string();

        let m = crate::manifest::VersionedManifest::parse_str(&src).expect("parse");
        let out: serde_json::Value =
            serde_json::from_str(&serde_json::to_string(&m).unwrap()).unwrap();
        assert_eq!(
            out["channels"][0]["components"][0]["artifacts"]["core.masp"]["digest"],
            serde_json::json!("sha256:deadbeef")
        );
    }

    #[test]
    fn a_malformed_digest_fails_the_parse() {
        let src = serde_json::json!({
            "manifest_version": "3.0.0",
            "date": 1735689600,
            "channels": [{"name": "0.15.0", "components": [{
                "name": "core",
                "version": {"kind": "registry", "version": "0.23.4"},
                "kind": "package",
                "artifacts": {"core.masp": {
                    "uri": "https://example.invalid/core.masp",
                    "digest": "not-a-digest"
                }}
            }]}]
        })
        .to_string();

        assert!(crate::manifest::VersionedManifest::parse_str(&src).is_err());
    }
}

#[cfg(test)]
mod forward_compatibility_tests {
    use super::*;

    /// Spec section 4.4: *every* schema type preserves what this build does not understand,
    /// `Artifact` included. Without that, a newer publisher adding a field to an artifact -- a
    /// signature, say -- would lose it on the first `update-manifest` round trip.
    #[test]
    fn unknown_artifact_fields_round_trip() {
        for source in [
            serde_json::json!({
                "uri": "https://example.invalid/%target",
                "targets": {"aarch64-apple-darwin": {"basename": "vm"}},
                "signature": {"alg": "ed25519", "sig": "deadbeef"}
            }),
            serde_json::json!({
                "uri": "https://example.invalid/core.masp",
                "digest": "sha256:9f86d081884c7d659a2feaa0c55ad015",
                "provenance": ["a", "b"]
            }),
        ] {
            let artifact: Artifact = serde_json::from_value(source.clone()).expect("must parse");
            let out = serde_json::to_value(&artifact).expect("must serialize");
            assert_eq!(out, source, "an artifact must round-trip byte-for-byte");
        }
    }

    /// The capture must not duplicate keys that the flattened `substitutions` already consumed --
    /// the failure mode the hand-written impls exist to prevent.
    #[test]
    fn flattened_substitutions_are_not_duplicated_into_the_extras() {
        let source = serde_json::json!({
            "uri": "https://example.invalid/%target.%extension",
            "basename": "miden-vm",
            "extension": "tar.gz",
            "targets": {"aarch64-apple-darwin": {}}
        });

        let artifact: Artifact = serde_json::from_value(source.clone()).unwrap();
        let out = serde_json::to_value(&artifact).unwrap();

        assert_eq!(out, source);
        assert_eq!(
            out.as_object().unwrap().len(),
            4,
            "no key may appear twice: {}",
            serde_json::to_string(&out).unwrap()
        );
    }

    /// A malformed artifact names what is wrong with it, rather than reporting that no variant
    /// matched.
    #[test]
    fn a_malformed_targets_map_is_reported_as_such() {
        let err = serde_json::from_value::<Artifact>(serde_json::json!({
            "uri": "https://example.invalid/%target",
            "targets": ["aarch64-apple-darwin"]
        }))
        .expect_err("must reject");

        assert!(err.to_string().contains("targets"), "{err}");
    }
}