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
//! Package metadata.
#![allow(missing_docs)]
#![deny(missing_debug_implementations)]

pub mod annotations;

use std::{collections::BTreeMap, str::FromStr};

use anyhow::{Context, Error};
use base64::Engine;
use indexmap::IndexMap;
use serde::{de::DeserializeOwned, Deserialize, Serialize};
use url::Url;
use wasmer_config::package::ModuleReference;

use crate::metadata::annotations::{FileSystemMappings, Wapm};

/// Manifest of the file, see spec `§2.3.1`
#[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Manifest {
    /// If this manifest was vendored from an external source, where did it originally
    /// come from? Necessary for vendoring dependencies.
    #[serde(skip, default)]
    pub origin: Option<String>,
    /// Dependencies of this file (internal or external)
    #[serde(default, rename = "use", skip_serializing_if = "IndexMap::is_empty")]
    pub use_map: IndexMap<String, UrlOrManifest>,
    /// Package version, author, license, etc. information
    #[serde(default, skip_serializing_if = "IndexMap::is_empty")]
    pub package: IndexMap<String, Annotation>,
    /// Atoms (executable files) in this container
    #[serde(default, skip_serializing_if = "IndexMap::is_empty")]
    pub atoms: IndexMap<String, Atom>,
    /// Commands that this container can execute (empty for library-only containers)
    #[serde(default, skip_serializing_if = "IndexMap::is_empty")]
    pub commands: IndexMap<String, Command>,
    /// Binding descriptions of this manifest
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub bindings: Vec<Binding>,
    /// Entrypoint (default command) to lookup in `self.commands` when invoking `wasmer run file.webc`
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub entrypoint: Option<String>,
}

impl Manifest {
    pub fn package_annotation<T>(&self, name: &str) -> Result<Option<T>, serde_cbor::Error>
    where
        T: DeserializeOwned,
    {
        if let Some(value) = self.package.get(name) {
            let annotation = serde_cbor::value::from_value(value.clone())?;
            return Ok(Some(annotation));
        }

        Ok(None)
    }

    pub fn atom_signature(&self, atom_name: &str) -> Result<AtomSignature, anyhow::Error> {
        self.atoms[atom_name].signature.parse()
    }
}

/// Well-known annotations.
impl Manifest {
    /// Get the package's [`Wapm`] annotations stored at [`Wapm::KEY`].
    pub fn wapm(&self) -> Result<Option<Wapm>, serde_cbor::Error> {
        self.package_annotation(Wapm::KEY)
    }

    /// Use Get the package's [`FileSystemMappings`] annotations stored at
    /// [`FileSystemMappings::KEY`].
    pub fn filesystem(&self) -> Result<Option<FileSystemMappings>, serde_cbor::Error> {
        self.package_annotation(FileSystemMappings::KEY)
    }

    pub fn update_filesystem(&mut self, mapping: FileSystemMappings) -> Result<(), anyhow::Error> {
        if let Some(value) = self.package.get_mut(FileSystemMappings::KEY) {
            let new_value = serde_cbor::value::to_value(mapping)?;
            *value = new_value;

            return Ok(());
        } else {
            anyhow::bail!("failed to get file system mappings");
        }
    }
}

#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum BindingsExtended {
    Wit(WitBindings),
    Wai(WaiBindings),
}

impl BindingsExtended {
    pub fn metadata_paths(&self) -> Vec<&str> {
        match self {
            BindingsExtended::Wit(w) => w.metadata_paths(),
            BindingsExtended::Wai(w) => w.metadata_paths(),
        }
    }

    /// The WebAssembly module these bindings annotate.
    pub fn module(&self) -> &str {
        match self {
            BindingsExtended::Wit(wit) => &wit.module,
            BindingsExtended::Wai(wai) => &wai.module,
        }
    }

    /// The URI pointing to the exports file exposed by these bindings.
    pub fn exports(&self) -> Option<&str> {
        match self {
            BindingsExtended::Wit(wit) => Some(&wit.exports),
            BindingsExtended::Wai(wai) => wai.exports.as_deref(),
        }
    }

    /// The URI pointing to the exports file exposed by these bindings.
    pub fn imports(&self) -> Vec<String> {
        match self {
            BindingsExtended::Wit(_) => Vec::new(),
            BindingsExtended::Wai(wai) => wai.imports.clone(),
        }
    }
}

#[derive(Default, Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct WitBindings {
    pub exports: String,
    pub module: String,
}

impl WitBindings {
    pub fn metadata_paths(&self) -> Vec<&str> {
        vec![&self.exports]
    }
}

#[derive(Default, Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct WaiBindings {
    pub exports: Option<String>,
    pub module: String,
    pub imports: Vec<String>,
}

impl WaiBindings {
    pub fn metadata_paths(&self) -> Vec<&str> {
        let mut paths: Vec<&str> = Vec::new();

        if let Some(export) = &self.exports {
            paths.push(export);
        }
        for import in &self.imports {
            paths.push(import);
        }

        paths
    }
}

#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct Binding {
    pub name: String,
    pub kind: String,
    pub annotations: serde_cbor::Value,
}

impl Binding {
    pub fn new_wit(name: String, kind: String, wit: WitBindings) -> Self {
        Self {
            name,
            kind,
            annotations: serde_cbor::from_slice(
                &serde_cbor::to_vec(&BindingsExtended::Wit(wit)).unwrap(),
            )
            .unwrap(),
        }
    }

    pub fn get_bindings(&self) -> Option<BindingsExtended> {
        serde_cbor::from_slice(&serde_cbor::to_vec(&self.annotations).ok()?).ok()
    }

    pub fn get_wai_bindings(&self) -> Option<WaiBindings> {
        match self.get_bindings() {
            Some(BindingsExtended::Wai(wai)) => Some(wai),
            _ => None,
        }
    }

    pub fn get_wit_bindings(&self) -> Option<WitBindings> {
        match self.get_bindings() {
            Some(BindingsExtended::Wit(wit)) => Some(wit),
            _ => None,
        }
    }
}

/// Same as `Manifest`, but doesn't require the `atom.signature`
#[derive(Default, Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct ManifestWithoutAtomSignatures {
    #[serde(skip, default)]
    pub origin: Option<String>,
    #[serde(default, rename = "use", skip_serializing_if = "IndexMap::is_empty")]
    pub use_map: IndexMap<String, UrlOrManifest>,
    #[serde(default, skip_serializing_if = "IndexMap::is_empty")]
    pub package: IndexMap<String, Annotation>,
    /// Atoms do not require a ".signature" field to be valid
    /// (SHA1 signature is calculated during packaging)
    #[serde(default, skip_serializing_if = "IndexMap::is_empty")]
    pub atoms: IndexMap<String, AtomWithoutSignature>,
    #[serde(default, skip_serializing_if = "IndexMap::is_empty")]
    pub commands: IndexMap<String, Command>,
    /// Binding descriptions of this manifest
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub bindings: Vec<Binding>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub entrypoint: Option<String>,
}

impl ManifestWithoutAtomSignatures {
    /// Returns the manifest with the "atom.signature" field filled out.
    /// `atom_signatures` is a map between the atom name and the SHA256 hash
    pub fn to_manifest(
        &self,
        atom_signatures: &BTreeMap<String, String>,
    ) -> Result<Manifest, Error> {
        let mut atoms = IndexMap::new();
        for (k, v) in self.atoms.iter() {
            let signature = atom_signatures
                .get(k)
                .with_context(|| format!("Could not find signature for atom {k:?}"))?;
            atoms.insert(
                k.clone(),
                Atom {
                    kind: v.kind.clone(),
                    signature: signature.clone(),
                },
            );
        }
        Ok(Manifest {
            origin: self.origin.clone(),
            use_map: self.use_map.clone(),
            package: self.package.clone(),
            atoms,
            bindings: self.bindings.clone(),
            commands: self.commands.clone(),
            entrypoint: self.entrypoint.clone(),
        })
    }
}

/// Dependency of this file, encoded as either a URL or a
/// manifest (in case of vendored dependencies)
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
#[serde(untagged)]
pub enum UrlOrManifest {
    /// External dependency
    Url(Url),
    /// Internal dependency (volume name = `user/package@version`)
    Manifest(Manifest),
    /// Registry-dependent dependency in a forma a la "namespace/package@version"
    RegistryDependentUrl(String),
}

impl UrlOrManifest {
    pub fn is_manifest(&self) -> bool {
        matches!(self, UrlOrManifest::Manifest(_))
    }

    pub fn is_url(&self) -> bool {
        matches!(self, UrlOrManifest::Url(_))
    }
}

/// Annotation = free-form metadata to be used by the atom
pub type Annotation = serde_cbor::Value;

/// Executable file, stored in the `.atoms` section of the file
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct AtomWithoutSignature {
    /// URL of the kind of the atom, usually `"webc.org/kind/wasm"`
    pub kind: Url,
}

/// Executable file, stored in the `.atoms` section of the file
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct Atom {
    /// URL of the kind of the atom, usually `"webc.org/kind/wasm"`
    pub kind: Url,
    /// Signature hash of the atom, usually `"sha256:xxxxx"`
    pub signature: String,
}

#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub enum AtomSignature {
    Sha256([u8; 32]),
}

impl AtomSignature {
    pub fn as_bytes(&self) -> &[u8] {
        match self {
            AtomSignature::Sha256(hash) => hash.as_slice(),
        }
    }
}

impl ToString for AtomSignature {
    fn to_string(&self) -> String {
        match self {
            AtomSignature::Sha256(bytes) => {
                let encoded = base64::prelude::BASE64_STANDARD.encode(bytes);
                format!("sha256:{encoded}")
            }
        }
    }
}

impl FromStr for AtomSignature {
    type Err = anyhow::Error;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let base64_encoded = s
            .strip_prefix("sha256:")
            .ok_or_else(|| anyhow::Error::msg("malformed atom signature"))?;

        let hash = base64::prelude::BASE64_STANDARD
            .decode(base64_encoded)
            .context("malformed base64 encoded hash")?;

        let hash: [u8; 32] = hash
            .as_slice()
            .try_into()
            .context("sha256 hash must be 32 bytes")?;

        Ok(Self::Sha256(hash))
    }
}

/// Command that can be run by a given implementation
#[derive(Debug, Default, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct Command {
    /// User-defined string specifying the type of runner to use to invoke the command
    ///
    /// The default value for this field is [`annotations::WASI_RUNNER_URI`].
    pub runner: String,
    /// User-defined map of free-form CBOR values that the runner can use as metadata
    /// when invoking the command
    pub annotations: IndexMap<String, Annotation>,
}

impl Command {
    pub fn annotation<T>(&self, name: &str) -> Result<Option<T>, serde_cbor::Error>
    where
        T: DeserializeOwned,
    {
        if let Some(value) = self.annotations.get(name) {
            let annotation = serde_cbor::value::from_value(value.clone())?;
            return Ok(Some(annotation));
        }

        Ok(None)
    }
}

/// Well-known annotations.
impl Command {
    pub fn wasi(&self) -> Result<Option<annotations::Wasi>, serde_cbor::Error> {
        self.annotation(annotations::Wasi::KEY)
    }

    pub fn wcgi(&self) -> Result<Option<annotations::Wcgi>, serde_cbor::Error> {
        self.annotation(annotations::Wcgi::KEY)
    }

    pub fn emscripten(&self) -> Result<Option<annotations::Emscripten>, serde_cbor::Error> {
        self.annotation(annotations::Emscripten::KEY)
    }

    pub fn atom(&self) -> Result<Option<annotations::Atom>, serde_cbor::Error> {
        // Check for the actual annotation exists
        if let Some(annotations) = self.annotation(annotations::Atom::KEY)? {
            return Ok(Some(annotations));
        }

        // Otherwise, let's polyfill using the fields removed in
        #[allow(deprecated)]
        let atom = if let Ok(Some(annotations::Wasi { atom, .. })) = self.wasi() {
            Some(atom)
        } else if let Ok(Some(annotations::Emscripten { atom, .. })) = self.emscripten() {
            atom
        } else {
            None
        };
        if let Some(atom) = atom {
            match ModuleReference::from_str(&atom) {
                Ok(ModuleReference::CurrentPackage { module }) => {
                    return Ok(Some(annotations::Atom::new(module, None)))
                }
                Ok(ModuleReference::Dependency { dependency, module }) => {
                    return Ok(Some(annotations::Atom::new(module, dependency)))
                }
                Err(_) => {}
            }
        }

        Ok(None)
    }
}

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

    #[test]
    fn deserialize_extended_wai_bindings() {
        let json = serde_json::json!({
            "wai": {
                "exports": "interface.wai",
                "module": "my-module",
                "imports": ["browser.wai", "fs.wai"],
            }
        });
        let bindings = BindingsExtended::deserialize(json).unwrap();

        assert_eq!(
            bindings,
            BindingsExtended::Wai(WaiBindings {
                exports: Some("interface.wai".to_string()),
                module: "my-module".to_string(),
                imports: vec!["browser.wai".to_string(), "fs.wai".to_string(),]
            })
        );
    }

    #[test]
    fn deserialize_extended_wit_bindings() {
        let json = serde_json::json!({
            "wit": {
                "exports": "interface.wit",
                "module": "my-module",
            }
        });
        let bindings = BindingsExtended::deserialize(json).unwrap();

        assert_eq!(
            bindings,
            BindingsExtended::Wit(WitBindings {
                exports: "interface.wit".to_string(),
                module: "my-module".to_string(),
            })
        );
    }
}