wash-cli 0.28.1

wasmCloud Shell (wash) CLI tool
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
use std::{collections::HashMap, path::PathBuf};

use anyhow::{bail, Context, Result};
use oci_distribution::{
    client::{Client, ClientConfig, ClientProtocol},
    secrets::RegistryAuth,
    Reference,
};
use serde_json::json;
use tokio::fs::File;
use tokio::io::AsyncWriteExt;
use tracing::warn;
use wash_lib::registry::{
    pull_oci_artifact, push_oci_artifact, validate_artifact, OciPullOptions, OciPushOptions,
    SupportedArtifacts,
};
use wash_lib::{
    cli::{
        input_vec_to_hashmap,
        registry::{RegistryPingCommand, RegistryPullCommand, RegistryPushCommand},
        CommandOutput, OutputKind,
    },
    parser::get_config,
};
use wasmcloud_control_interface::RegistryCredential;

use crate::appearance::spinner::Spinner;

pub const SHOWER_EMOJI: &str = "\u{1F6BF}";
pub const PROVIDER_ARCHIVE_FILE_EXTENSION: &str = ".par.gz";
pub const WASM_FILE_EXTENSION: &str = ".wasm";

pub async fn registry_pull(
    cmd: RegistryPullCommand,
    output_kind: OutputKind,
) -> Result<CommandOutput> {
    let image: Reference = resolve_artifact_ref(&cmd.url, &cmd.registry.unwrap_or_default(), None)?;
    let spinner = Spinner::new(&output_kind)?;
    spinner.update_spinner_message(format!(" Downloading {} ...", image.whole()));

    let credentials = match (cmd.opts.user, cmd.opts.password) {
        (Some(user), Some(password)) => Ok(RegistryCredential {
            username: Some(user),
            password: Some(password),
            ..Default::default()
        }),
        _ => resolve_registry_credentials(image.registry()).await,
    }?;

    let artifact = pull_oci_artifact(
        image.whole(),
        OciPullOptions {
            digest: cmd.digest,
            allow_latest: cmd.allow_latest,
            user: credentials.username,
            password: credentials.password,
            insecure: cmd.opts.insecure,
        },
    )
    .await?;

    let outfile = write_artifact(&artifact, &image, cmd.destination).await?;

    spinner.finish_and_clear();

    let mut map = HashMap::new();
    map.insert("file".to_string(), json!(outfile));
    Ok(CommandOutput::new(
        format!("\n{SHOWER_EMOJI} Successfully pulled and validated {outfile}"),
        map,
    ))
}

pub async fn registry_ping(cmd: RegistryPingCommand) -> Result<CommandOutput> {
    let image: Reference = resolve_artifact_ref(&cmd.url, &cmd.registry.unwrap_or_default(), None)?;
    let mut client = Client::new(ClientConfig {
        protocol: if cmd.opts.insecure {
            ClientProtocol::Http
        } else {
            ClientProtocol::Https
        },
        ..Default::default()
    });

    let credentials = match (cmd.opts.user, cmd.opts.password) {
        (Some(user), Some(password)) => Ok(RegistryCredential {
            username: Some(user),
            password: Some(password),
            ..Default::default()
        }),
        _ => resolve_registry_credentials(image.registry()).await,
    }?;

    let Ok(credentials) = RegistryAuth::try_from(&credentials) else {
        bail!("failed to resolve registry credentials")
    };

    let (_, _) = client.pull_manifest(&image, &credentials).await?;
    Ok(CommandOutput::from("Pong!"))
}

pub async fn write_artifact(
    artifact: &[u8],
    image: &Reference,
    output: Option<String>,
) -> Result<String> {
    let file_extension = match validate_artifact(artifact).await? {
        SupportedArtifacts::Par => PROVIDER_ARCHIVE_FILE_EXTENSION,
        SupportedArtifacts::Wasm => WASM_FILE_EXTENSION,
    };
    // Output to provided file, or use artifact_name.file_extension
    let outfile = output.unwrap_or_else(|| {
        format!(
            "{}{file_extension}",
            image.repository().split('/').last().unwrap(),
        )
    });
    let mut f = File::create(&outfile).await?;
    f.write_all(artifact).await?;
    // https://github.com/wasmCloud/wash/issues/382 resolved by this
    // Files must be synced to ensure all bytes are written to disk
    f.sync_all().await?;
    Ok(outfile)
}

pub async fn registry_push(
    cmd: RegistryPushCommand,
    output_kind: OutputKind,
) -> Result<CommandOutput> {
    let image: Reference = resolve_artifact_ref(
        &cmd.url,
        &cmd.registry.unwrap_or_default(),
        cmd.config.clone(),
    )?;
    let artifact_url = image.whole();
    if artifact_url.starts_with("localhost:") && !cmd.opts.insecure {
        warn!(" Unless an SSL certificate has been installed, pushing to localhost without the --insecure option will fail")
    }

    let spinner = Spinner::new(&output_kind)?;
    spinner.update_spinner_message(format!(" Pushing {} to {} ...", cmd.artifact, artifact_url));

    let credentials = match (cmd.opts.user, cmd.opts.password) {
        (Some(user), Some(password)) => Ok(RegistryCredential {
            username: Some(user),
            password: Some(password),
            ..Default::default()
        }),
        _ => resolve_registry_credentials(image.registry()).await,
    }?;

    let annotations = match cmd.annotations {
        Some(annotations) => input_vec_to_hashmap(annotations).ok(),
        None => None,
    };

    let (maybe_tag, digest) = push_oci_artifact(
        artifact_url.clone(),
        cmd.artifact,
        OciPushOptions {
            config: cmd.config.map(PathBuf::from),
            allow_latest: cmd.allow_latest,
            user: credentials.username,
            password: credentials.password,
            insecure: cmd.opts.insecure,
            annotations,
        },
    )
    .await?;

    spinner.finish_and_clear();

    let mut map = HashMap::from_iter([
        ("url".to_string(), json!(artifact_url)),
        ("digest".to_string(), json!(digest)),
    ]);
    let text = if let Some(tag) = maybe_tag {
        map.insert("tag".to_string(), json!(tag));
        format!("{SHOWER_EMOJI} Successfully pushed {artifact_url}\n{tag}: digest: {digest}")
    } else {
        format!("{SHOWER_EMOJI} Successfully pushed {artifact_url}\ndigest: {digest}")
    };
    Ok(CommandOutput::new(text, map))
}

fn resolve_artifact_ref(
    url: &str,
    registry: &str,
    project_config: Option<PathBuf>,
) -> Result<Reference> {
    // NOTE: Image URLs must be all lower case for `oci_distribution::Reference` to parse them properly
    let url = url.trim().to_ascii_lowercase();
    let registry = registry.trim().to_ascii_lowercase();

    let image: Reference = url
        .parse()
        .context("failed to parse artifact url into oci image reference")?;

    if url == image.whole() {
        return Ok(image);
    }

    if !url.is_empty() && !registry.is_empty() {
        let image: Reference = format!("{}/{}", registry, url)
            .parse()
            .context("failed to parse artifact url from specified registry and repository")?;

        return Ok(image);
    }

    if !url.is_empty() && registry.is_empty() {
        let project_config = get_config(project_config, Some(true))?;
        let registry = project_config
            .common
            .registry
            .url
            .clone()
            .unwrap_or_default();

        if registry.is_empty() {
            bail!("Missing or invalid registry url configuration")
        }

        let image: Reference = format!("{}/{}", registry, url).parse().context(
            "failed to parse artifact url from specified repository and registry url configuration",
        )?;

        return Ok(image);
    }

    bail!("Unable to resolve artifact url from specified registry and repository")
}

async fn resolve_registry_credentials(registry: &str) -> Result<RegistryCredential> {
    let Ok(project_config) = get_config(None, Some(true)) else {
        return Ok(RegistryCredential::default());
    };

    project_config.resolve_registry_credentials(registry).await
}

#[cfg(test)]
mod tests {
    use anyhow::{ensure, Context as _, Result};
    use clap::Parser;
    use wash_lib::cli::registry::{RegistryCommand, RegistryPullCommand};

    use crate::common::registry_cmd::RegistryPushCommand;

    const ECHO_WASM: &str = "wasmcloud.azurecr.io/echo:0.2.0";
    const LOCAL_REGISTRY: &str = "localhost:5001";
    const TESTDIR: &str = "./tests/fixtures";

    // Partial wash command
    #[derive(Debug, Parser)]
    struct Cmd {
        #[clap(subcommand)]
        sub: RegistryCommand,
    }

    #[test]
    /// Enumerates multiple options of the `pull` command to ensure API doesn't
    /// change between versions. This test will fail if `wash reg pull`
    /// changes syntax, ordering of required elements, or flags.
    fn test_pull_comprehensive() -> Result<()> {
        // test basic `wash reg pull`
        let pull_basic: Cmd = Parser::try_parse_from(["wash", "pull", ECHO_WASM])
            .context("failed to perform reg pull")?;
        ensure!(matches!(
            pull_basic.sub,
            RegistryCommand::Pull(RegistryPullCommand { url, .. }) if url == ECHO_WASM,
        ));

        // test `wash reg pull`
        let pull_all_flags: Cmd =
            Parser::try_parse_from(["wash", "pull", ECHO_WASM, "--allow-latest", "--insecure"])
                .context("failed to pull with all flags")?;
        ensure!(matches!(
            pull_all_flags.sub,
            RegistryCommand::Pull(RegistryPullCommand {
                url,
                allow_latest,
                opts,
                ..
            }) if url == ECHO_WASM && allow_latest && opts.insecure
        ));

        // test `wash pull`
        let pull_all_options: Cmd = Parser::try_parse_from([
            "wash",
            "pull",
            ECHO_WASM,
            "--destination",
            TESTDIR,
            "--digest",
            "sha256:a17a163afa8447622055deb049587641a9e23243a6cc4411eb33bd4267214cf3",
            "--password",
            "password",
            "--user",
            "user",
        ])
        .context("wash pull with all options failed")?;
        ensure!(matches!(
            pull_all_options.sub,
            RegistryCommand::Pull(RegistryPullCommand {
                url,
                destination,
                digest,
                opts,
                ..
            }) if url == ECHO_WASM
                && destination == Some(TESTDIR.into())
                && digest == Some("sha256:a17a163afa8447622055deb049587641a9e23243a6cc4411eb33bd4267214cf3".into())
                && opts.user == Some("user".into())
                && opts.password == Some("password".into())
        ));

        Ok(())
    }

    #[test]
    /// Enumerates multiple options of the `push` command to ensure API doesn't
    /// change between versions. This test will fail if `wash reg push`
    /// changes syntax, ordering of required elements, or flags.
    fn test_push_comprehensive() {
        // Not explicitly used, just a placeholder for a directory
        const TESTDIR: &str = "./tests/fixtures";

        // Push echo.wasm and pull from local registry
        let echo_push_basic = &format!("{LOCAL_REGISTRY}/echo:pushbasic");
        let push_basic: Cmd = Parser::try_parse_from([
            "wash",
            "push",
            echo_push_basic,
            &format!("{TESTDIR}/echopush.wasm"),
            "--insecure",
        ])
        .unwrap();
        match push_basic.sub {
            RegistryCommand::Push(RegistryPushCommand {
                url,
                artifact,
                opts,
                ..
            }) => {
                assert_eq!(&url, echo_push_basic);
                assert_eq!(artifact, format!("{TESTDIR}/echopush.wasm"));
                assert!(opts.insecure);
            }
            _ => panic!("`reg push` constructed incorrect command"),
        };

        // Push logging.par.gz and pull from local registry
        let logging_push_all_flags = &format!("{LOCAL_REGISTRY}/logging:allflags");
        let push_all_flags: Cmd = Parser::try_parse_from([
            "wash",
            "push",
            logging_push_all_flags,
            &format!("{TESTDIR}/logging.par.gz"),
            "--insecure",
            "--allow-latest",
        ])
        .unwrap();
        match push_all_flags.sub {
            RegistryCommand::Push(RegistryPushCommand {
                url,
                artifact,
                opts,
                allow_latest,
                ..
            }) => {
                assert_eq!(&url, logging_push_all_flags);
                assert_eq!(artifact, format!("{TESTDIR}/logging.par.gz"));
                assert!(opts.insecure);
                assert!(allow_latest);
            }
            _ => panic!("`reg push` constructed incorrect command"),
        };

        // Push logging.par.gz to different tag and pull to confirm successful push
        let logging_push_all_options = &format!("{LOCAL_REGISTRY}/logging:alloptions");
        let push_all_options: Cmd = Parser::try_parse_from([
            "wash",
            "push",
            logging_push_all_options,
            &format!("{TESTDIR}/logging.par.gz"),
            "--allow-latest",
            "--insecure",
            "--config",
            &format!("{TESTDIR}/config.json"),
            "--password",
            "supers3cr3t",
            "--user",
            "localuser",
        ])
        .unwrap();
        match push_all_options.sub {
            RegistryCommand::Push(RegistryPushCommand {
                url,
                artifact,
                opts,
                allow_latest,
                config,
                ..
            }) => {
                assert_eq!(&url, logging_push_all_options);
                assert_eq!(artifact, format!("{TESTDIR}/logging.par.gz"));
                assert!(opts.insecure);
                assert!(allow_latest);
                assert_eq!(
                    format!("{}", config.unwrap().as_path().display()),
                    format!("{TESTDIR}/config.json")
                );
                assert_eq!(opts.user.unwrap(), "localuser");
                assert_eq!(opts.password.unwrap(), "supers3cr3t");
            }
            _ => panic!("`reg push` constructed incorrect command"),
        };
    }
}