-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathdispatch.rs
More file actions
367 lines (330 loc) · 12.6 KB
/
dispatch.rs
File metadata and controls
367 lines (330 loc) · 12.6 KB
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
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
use anyhow::{Context, Result, bail};
use camino::Utf8PathBuf;
use chrono::{DateTime, Utc};
use clap::{CommandFactory, Parser};
use semver::Version;
use tufaceous_artifact::{ArtifactKind, ArtifactVersion, ArtifactsDocument};
use tufaceous_lib::assemble::{ArtifactManifest, OmicronRepoAssembler};
use tufaceous_lib::{
AddArtifact, ArchiveExtractor, IncludeInstallinatorDocument, Key,
OmicronRepo,
};
#[derive(Debug, Parser)]
pub struct Args {
#[clap(subcommand)]
command: Command,
#[clap(
short = 'k',
long = "key",
env = "TUFACEOUS_KEY",
required = false,
global = true
)]
keys: Vec<Key>,
#[clap(long, value_parser = crate::date::parse_duration_or_datetime, default_value = "7d", global = true)]
expiry: DateTime<Utc>,
/// TUF repository path (default: current working directory)
#[clap(short = 'r', long, global = true)]
repo: Option<Utf8PathBuf>,
}
impl Args {
/// Executes these arguments.
pub async fn exec(self, log: &slog::Logger) -> Result<()> {
let repo_path = match self.repo {
Some(repo) => repo,
None => std::env::current_dir()?.try_into()?,
};
match self.command {
// TODO-cleanup: we no longer use the init and add commands in
// production. We should get rid of these options and direct users
// towards assemble. (If necessary, we should build tooling for
// making it easy to build up a manifest that can then be
// assembled.)
Command::Init { system_version, no_generate_key } => {
let keys = maybe_generate_keys(self.keys, no_generate_key)?;
let root =
tufaceous_lib::root::new_root(keys.clone(), self.expiry)
.await?;
let repo = OmicronRepo::initialize(
log,
&repo_path,
system_version,
keys,
root,
self.expiry,
IncludeInstallinatorDocument::Yes,
)
.await?;
slog::info!(
log,
"Initialized TUF repository in {}",
repo.repo_path()
);
Ok(())
}
Command::Add {
kind,
allow_unknown_kinds,
path,
name,
version,
allow_non_semver,
} => {
if !allow_unknown_kinds {
// Try converting kind to a known kind.
if kind.to_known().is_none() {
// Simulate a failure to parse (though ideally there would
// be a way to also specify the underlying error -- there
// doesn't appear to be a public API to do so in clap 4).
let mut error = clap::Error::new(
clap::error::ErrorKind::ValueValidation,
)
.with_cmd(&Args::command());
error.insert(
clap::error::ContextKind::InvalidArg,
clap::error::ContextValue::String(
"<KIND>".to_owned(),
),
);
error.insert(
clap::error::ContextKind::InvalidValue,
clap::error::ContextValue::String(kind.to_string()),
);
error.exit();
}
}
if !allow_non_semver {
if let Err(error) = version.as_str().parse::<Version>() {
let error = Args::command().error(
clap::error::ErrorKind::ValueValidation,
format!(
"version `{version}` is not valid semver \
(pass in --allow-non-semver to override): {error}"
),
);
error.exit();
}
}
let repo = OmicronRepo::load_untrusted_ignore_expiration(
log, &repo_path,
)
.await?;
let mut editor = repo.into_editor().await?;
let new_artifact =
AddArtifact::from_path(kind, name, version, path)?;
editor
.add_artifact(&new_artifact)
.context("error adding artifact")?;
editor
.sign_and_finish(
self.keys,
self.expiry,
IncludeInstallinatorDocument::Yes,
)
.await?;
println!(
"added {} {}, version {}",
new_artifact.kind(),
new_artifact.name(),
new_artifact.version()
);
Ok(())
}
Command::Archive { output_path } => {
// The filename must end with "zip".
if output_path.extension() != Some("zip") {
bail!("output path `{output_path}` must end with .zip");
}
let repo = OmicronRepo::load_untrusted_ignore_expiration(
log, &repo_path,
)
.await?;
repo.archive(&output_path)?;
Ok(())
}
Command::Extract {
archive_file,
dest,
no_installinator_document,
} => {
let mut extractor = ArchiveExtractor::from_path(&archive_file)?;
extractor.extract(&dest)?;
// Now load the repository and ensure it's valid.
let repo = OmicronRepo::load_untrusted(log, &dest)
.await
.with_context(|| {
format!(
"error loading extracted repository at `{dest}` \
(extracted files are still available)"
)
})?;
let artifacts =
repo.read_artifacts().await.with_context(|| {
format!(
"error loading {} from extracted archive \
at `{dest}`",
ArtifactsDocument::FILE_NAME
)
})?;
if !no_installinator_document {
// There should be a reference to an installinator document
// within artifacts_document.
let installinator_doc_artifact = artifacts
.artifacts
.iter()
.find(|artifact| {
artifact.kind
== ArtifactKind::INSTALLINATOR_DOCUMENT
})
.context(
"could not find artifact with kind \
`installinator_document` within artifacts.json",
)?;
repo.read_installinator_document(
&installinator_doc_artifact.target,
)
.await
.with_context(|| {
format!(
"error loading {} from extracted archive \
at `{dest}`",
installinator_doc_artifact.target,
)
})?;
}
Ok(())
}
Command::Assemble {
manifest_path,
output_path,
build_dir,
no_generate_key,
skip_all_present,
allow_non_semver,
no_installinator_document,
} => {
// The filename must end with "zip".
if output_path.extension() != Some("zip") {
bail!("output path `{output_path}` must end with .zip");
}
let manifest = ArtifactManifest::from_path(&manifest_path)
.context("error reading manifest")?;
if !allow_non_semver {
manifest.verify_all_semver()?;
}
if !skip_all_present {
manifest.verify_all_present()?;
}
let keys = maybe_generate_keys(self.keys, no_generate_key)?;
let mut assembler = OmicronRepoAssembler::new(
log,
manifest,
keys,
self.expiry,
if no_installinator_document {
IncludeInstallinatorDocument::No
} else {
IncludeInstallinatorDocument::Yes
},
output_path,
);
if let Some(dir) = build_dir {
assembler.set_build_dir(dir);
}
assembler.build().await?;
Ok(())
}
}
}
}
#[derive(Debug, Parser)]
enum Command {
/// Create a new rack update TUF repository
Init {
/// The system version.
system_version: Version,
/// Disable random key generation and exit if no keys are provided
#[clap(long)]
no_generate_key: bool,
},
Add {
/// The kind of artifact this is.
kind: ArtifactKind,
/// Allow artifact kinds that aren't known to tufaceous
#[clap(long)]
allow_unknown_kinds: bool,
/// Path to the artifact.
path: Utf8PathBuf,
/// Override the name for this artifact (default: filename with extension stripped)
#[clap(long)]
name: Option<String>,
/// Artifact version.
///
/// This is required to be semver by default, but can be overridden with
/// --allow-non-semver.
version: ArtifactVersion,
/// Allow versions to be non-semver.
///
/// Transitional option for v13 -> v14. After v14, versions will be
/// allowed to be non-semver by default.
#[clap(long)]
allow_non_semver: bool,
},
/// Archives this repository to a zip file.
Archive {
/// The path to write the archive to (must end with .zip).
output_path: Utf8PathBuf,
},
/// Validates and extracts a repository created by the `archive` command.
Extract {
/// The file to extract.
archive_file: Utf8PathBuf,
/// The destination to extract the file to.
dest: Utf8PathBuf,
/// Indicate that the file does not contain an installinator document.
#[clap(long)]
no_installinator_document: bool,
},
/// Assembles a repository from a provided manifest.
Assemble {
/// Path to artifact manifest.
manifest_path: Utf8PathBuf,
/// The path to write the archive to (must end with .zip).
output_path: Utf8PathBuf,
/// Directory to use for building artifacts [default: temporary directory]
#[clap(long)]
build_dir: Option<Utf8PathBuf>,
/// Disable random key generation and exit if no keys are provided
#[clap(long)]
no_generate_key: bool,
/// Skip checking to ensure all expected artifacts are present.
#[clap(long)]
skip_all_present: bool,
/// Allow versions to be non-semver.
///
/// Transitional option for v13 -> v14. After v14, versions will be
/// allowed to be non-semver by default.
#[clap(long)]
allow_non_semver: bool,
/// Do not include the installinator document.
///
/// Transitional option for v15 -> v16, meant to be used for testing.
#[clap(long)]
no_installinator_document: bool,
},
}
fn maybe_generate_keys(
keys: Vec<Key>,
no_generate_key: bool,
) -> Result<Vec<Key>> {
Ok(if !no_generate_key && keys.is_empty() {
let key = Key::generate_ed25519()?;
crate::hint::generated_key(&key);
vec![key]
} else {
keys
})
}