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
use crate::config::Config;
use anyhow::{bail, Context, Result};
use cargo_component_core::{
    command::CommonOptions,
    keyring::{self, delete_signing_key, get_signing_key, get_signing_key_entry, set_signing_key},
    terminal::Colors,
};
use clap::{Args, Subcommand};
use p256::ecdsa::SigningKey;
use rand_core::OsRng;
use std::io::{self, Write};
use warg_client::RegistryUrl;
use warg_crypto::signing::PrivateKey;

/// Manage signing keys for publishing components to a registry.
#[derive(Args)]
#[clap(disable_version_flag = true)]
pub struct KeyCommand {
    /// The common command options.
    #[clap(flatten)]
    pub common: CommonOptions,

    /// The subcommand to execute.
    #[clap(subcommand)]
    pub command: KeySubcommand,
}

impl KeyCommand {
    /// Executes the command.
    pub async fn exec(self) -> Result<()> {
        log::debug!("executing key command");

        let config = Config::new(self.common.new_terminal())?;

        match self.command {
            KeySubcommand::Id(cmd) => cmd.exec().await,
            KeySubcommand::New(cmd) => cmd.exec(&config).await,
            KeySubcommand::Set(cmd) => cmd.exec(&config).await,
            KeySubcommand::Delete(cmd) => cmd.exec(&config).await,
        }
    }
}

/// The subcommand to execute.
#[derive(Subcommand)]
pub enum KeySubcommand {
    /// Print the Key ID of the signing key for a registry in the local keyring.
    Id(KeyIdCommand),
    /// Creates a new signing key for a registry in the local keyring.
    New(KeyNewCommand),
    /// Sets the signing key for a registry in the local keyring.
    Set(KeySetCommand),
    /// Deletes the signing key for a registry from the local keyring.
    Delete(KeyDeleteCommand),
}

/// Print the Key ID of the signing key for a registry in the local keyring.
#[derive(Args)]
pub struct KeyIdCommand {
    /// The key name of the signing key.
    #[clap(long, short, value_name = "NAME", default_value = "default")]
    pub key_name: String,
    /// The URL of the registry to print the Key ID for.
    #[clap(value_name = "URL")]
    pub url: RegistryUrl,
}

impl KeyIdCommand {
    /// Executes the command.
    pub async fn exec(self) -> Result<()> {
        let key = get_signing_key(&self.url, &self.key_name)?;
        println!(
            "{fingerprint}",
            fingerprint = key.public_key().fingerprint()
        );
        Ok(())
    }
}

/// Creates a new signing key for a registry in the local keyring.
#[derive(Args)]
#[clap(disable_version_flag = true)]
pub struct KeyNewCommand {
    /// The key name to use for the signing key.
    #[clap(long, short, value_name = "NAME", default_value = "default")]
    pub key_name: String,
    /// The URL of the registry to create a signing key for.
    #[clap(value_name = "URL")]
    pub url: RegistryUrl,
}

impl KeyNewCommand {
    /// Executes the command.
    pub async fn exec(self, config: &Config) -> Result<()> {
        let entry = get_signing_key_entry(&self.url, &self.key_name)?;

        match entry.get_password() {
            Err(keyring::Error::NoEntry) => {
                // no entry exists, so we can continue
            }
            Ok(_) | Err(keyring::Error::Ambiguous(_)) => {
                bail!(
                    "signing key `{name}` already exists for registry `{url}`",
                    name = self.key_name,
                    url = self.url
                );
            }
            Err(e) => {
                bail!(
                    "failed to get signing key `{name}` for registry `{url}`: {e}",
                    name = self.key_name,
                    url = self.url
                );
            }
        }

        let key = SigningKey::random(&mut OsRng).into();
        set_signing_key(&self.url, &self.key_name, &key)?;

        config.terminal().status(
            "Created",
            format!(
                "signing key `{name}` ({fingerprint}) for registry `{url}`",
                name = self.key_name,
                fingerprint = key.public_key().fingerprint(),
                url = self.url,
            ),
        )?;

        Ok(())
    }
}

/// Sets the signing key for a registry in the local keyring.
#[derive(Args)]
#[clap(disable_version_flag = true)]
pub struct KeySetCommand {
    /// The key name to use for the signing key.
    #[clap(long, short, value_name = "NAME", default_value = "default")]
    pub key_name: String,
    /// The URL of the registry to create a signing key for.
    #[clap(value_name = "URL")]
    pub url: RegistryUrl,
}

impl KeySetCommand {
    /// Executes the command.
    pub async fn exec(self, config: &Config) -> Result<()> {
        let key = PrivateKey::decode(
            rpassword::prompt_password("input signing key (expected format is `<alg>:<base64>`): ")
                .context("failed to read signing key")?,
        )
        .context("signing key is not in the correct format")?;

        set_signing_key(&self.url, &self.key_name, &key)?;

        config.terminal().status(
            "Set",
            format!(
                "signing key `{name}` ({fingerprint}) for registry `{url}`",
                name = self.key_name,
                fingerprint = key.public_key().fingerprint(),
                url = self.url,
            ),
        )?;

        Ok(())
    }
}

/// Deletes the signing key for a registry from the local keyring.
#[derive(Args)]
#[clap(disable_version_flag = true)]
pub struct KeyDeleteCommand {
    /// The key name to use for the signing key.
    #[clap(long, short, value_name = "NAME", default_value = "default")]
    pub key_name: String,
    /// The URL of the registry to create a signing key for.
    #[clap(value_name = "URL")]
    pub url: RegistryUrl,
}

impl KeyDeleteCommand {
    /// Executes the command.
    pub async fn exec(self, config: &Config) -> Result<()> {
        config.terminal().write_stdout(
            "⚠️  WARNING: this operation cannot be undone and the key will be permanently deleted ⚠️",
            Some(Colors::Yellow),
        )?;

        config.terminal().write_stdout(
            format!(
                "\nare you sure you want to delete signing key `{name}` for registry `{url}`? [type `yes` to confirm] ",
                name = self.key_name,
                url = self.url
            ),
            None,
        )?;

        io::stdout().flush().ok();

        let mut line = String::new();
        io::stdin().read_line(&mut line).ok();
        line.make_ascii_lowercase();

        if line.trim() != "yes" {
            config.terminal().note(format!(
                "skipping deletion of signing key for registry `{url}`",
                url = self.url,
            ))?;
            return Ok(());
        }

        delete_signing_key(&self.url, &self.key_name)?;

        config.terminal().status(
            "Deleted",
            format!(
                "signing key `{name}` for registry `{url}`",
                name = self.key_name,
                url = self.url,
            ),
        )?;

        Ok(())
    }
}