wimsey-cli 0.3.0

The wimsey command-line tool: issue, verify and inspect WIMSE credentials.
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
//! `wimsey` — a command-line tool for WIMSE workload credentials.
//!
//! Issues, verifies and inspects Workload Identity Tokens and Workload Proof
//! Tokens using Ed25519 keys stored as OKP JSON Web Keys.

mod httpsig;
mod key;

use std::path::{Path, PathBuf};

use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine};
use clap::{Parser, Subcommand};
use ed25519_dalek::SigningKey;
use serde_json::json;
use wimsey_identifier::WorkloadIdentifier;
use wimsey_wit::{Confirmation, Jwk, WitClaims};
use wimsey_wpt::WptClaims;

use crate::key::JwkKey;

/// A fallible result carrying a boxed error.
pub type Result<T> = std::result::Result<T, Box<dyn std::error::Error + Send + Sync>>;

#[derive(Parser)]
#[command(
    name = "wimsey",
    version,
    about = "A vendor-neutral WIMSE reference implementation"
)]
struct Cli {
    #[command(subcommand)]
    command: Command,
}

#[derive(Subcommand)]
enum Command {
    /// Ed25519 key management.
    Key {
        #[command(subcommand)]
        cmd: KeyCmd,
    },
    /// Workload Identity Token (WIT) operations.
    Wit {
        #[command(subcommand)]
        cmd: WitCmd,
    },
    /// Workload Proof Token (WPT) operations.
    Wpt {
        #[command(subcommand)]
        cmd: WptCmd,
    },
    /// HTTP Message Signature (RFC 9421) operations.
    Httpsig {
        // Boxed: the httpsig arguments are by far the widest of any subcommand,
        // and inlining them would size every `Command` to fit them.
        #[command(subcommand)]
        cmd: Box<httpsig::HttpsigCmd>,
    },
}

#[derive(Subcommand)]
enum KeyCmd {
    /// Generate a new Ed25519 private key as an OKP JWK.
    Generate {
        /// Optional 32-byte seed (Base64url) for a reproducible key. For testing
        /// only: a seed on the command line is visible to other processes.
        #[arg(long)]
        seed: Option<String>,
        /// Write to this file instead of stdout.
        #[arg(long)]
        out: Option<PathBuf>,
    },
    /// Print the public JWK for a private key file.
    Public {
        /// The private key file.
        #[arg(long, value_name = "FILE")]
        r#in: PathBuf,
        /// Write to this file instead of stdout.
        #[arg(long)]
        out: Option<PathBuf>,
    },
}

#[derive(Subcommand)]
enum WitCmd {
    /// Issue a WIT signed by the issuer key.
    Issue {
        /// The issuer's private key file.
        #[arg(long, value_name = "FILE")]
        issuer_key: PathBuf,
        /// The workload identifier, e.g. `spiffe://example.org/api`.
        #[arg(long)]
        sub: String,
        /// The issuer identifier. RECOMMENDED but optional per the draft; the
        /// `iss` claim is omitted when this is not given.
        #[arg(long)]
        iss: Option<String>,
        /// The confirmation (proof-of-possession) key file; its public half
        /// goes in the `cnf` claim.
        #[arg(long, value_name = "FILE")]
        cnf_key: PathBuf,
        /// Lifetime in seconds.
        #[arg(long, default_value_t = 3600)]
        ttl: u64,
        /// Optional JOSE `kid` header.
        #[arg(long)]
        kid: Option<String>,
        /// Optional token id; a random 128-bit value is used if omitted.
        #[arg(long)]
        jti: Option<String>,
        /// Override the current time (Unix seconds).
        #[arg(long)]
        now: Option<u64>,
    },
    /// Verify a WIT against the issuer's public key.
    Verify {
        /// The issuer's public (or private) key file.
        #[arg(long, value_name = "FILE")]
        issuer_jwk: PathBuf,
        /// The token value.
        #[arg(long, conflicts_with = "token_file")]
        token: Option<String>,
        /// A file containing the token.
        #[arg(long)]
        token_file: Option<PathBuf>,
        /// Require this issuer.
        #[arg(long)]
        expected_iss: Option<String>,
        /// Override the current time (Unix seconds). For testing only; pinning
        /// this defeats expiry checks.
        #[arg(long)]
        now: Option<u64>,
    },
    /// Decode a WIT's header and claims without verifying.
    Inspect {
        /// The token value.
        #[arg(long, conflicts_with = "token_file")]
        token: Option<String>,
        /// A file containing the token.
        #[arg(long)]
        token_file: Option<PathBuf>,
    },
}

#[derive(Subcommand)]
enum WptCmd {
    /// Create a WPT bound to a WIT, signed by the proof-of-possession key.
    New {
        /// The proof-of-possession private key file.
        #[arg(long, value_name = "FILE")]
        pop_key: PathBuf,
        /// The WIT this proof is bound to.
        #[arg(long)]
        wit: String,
        /// The audience (request target URI).
        #[arg(long)]
        aud: String,
        /// Lifetime in seconds.
        #[arg(long, default_value_t = 120)]
        ttl: u64,
        /// Optional proof id; a random 128-bit value is used if omitted.
        #[arg(long)]
        jti: Option<String>,
        /// Override the current time (Unix seconds).
        #[arg(long)]
        now: Option<u64>,
    },
    /// Verify a WPT: verify the WIT with the issuer key, then check the proof
    /// against the WIT's confirmation key.
    Verify {
        /// The issuer's public key file, used to verify the bound WIT.
        #[arg(long, value_name = "FILE")]
        issuer_jwk: PathBuf,
        /// The WIT the proof is bound to.
        #[arg(long)]
        wit: String,
        /// The audience the proof must be addressed to.
        #[arg(long)]
        aud: String,
        /// The proof value.
        #[arg(long)]
        proof: String,
        /// Require this issuer on the WIT.
        #[arg(long)]
        expected_iss: Option<String>,
        /// Override the current time (Unix seconds). For testing only.
        #[arg(long)]
        now: Option<u64>,
    },
}

fn main() {
    if let Err(err) = run(Cli::parse()) {
        eprintln!("error: {err}");
        std::process::exit(1);
    }
}

fn run(cli: Cli) -> Result<()> {
    match cli.command {
        Command::Key { cmd } => run_key(cmd),
        Command::Wit { cmd } => run_wit(cmd),
        Command::Wpt { cmd } => run_wpt(cmd),
        Command::Httpsig { cmd } => httpsig::run(*cmd),
    }
}

fn run_key(cmd: KeyCmd) -> Result<()> {
    match cmd {
        KeyCmd::Generate { seed, out } => {
            let signing_key = if let Some(seed) = seed {
                let bytes = URL_SAFE_NO_PAD.decode(seed.trim())?;
                let seed: [u8; 32] = bytes.try_into().map_err(|_| "seed is not 32 bytes")?;
                SigningKey::from_bytes(&seed)
            } else {
                let mut seed = [0u8; 32];
                getrandom::fill(&mut seed).map_err(|e| format!("getrandom: {e}"))?;
                SigningKey::from_bytes(&seed)
            };
            emit(
                &key::to_json(&JwkKey::from_signing_key(&signing_key))?,
                out.as_deref(),
            )
        }
        KeyCmd::Public { r#in, out } => {
            let jwk = key::load(&r#in)?;
            // Validate before exporting: with a private seed, re-derive the
            // public key so a mismatched `x` is rejected; otherwise confirm the
            // advertised public key is a valid Ed25519 key.
            // Validate before exporting: `signing_key` checks that `d` matches
            // `x`; `verifying_key` checks a public-only key is a real key.
            if jwk.d.is_some() {
                jwk.signing_key()?;
            } else {
                jwk.verifying_key()?;
            }
            emit(&key::to_json(&jwk.to_public())?, out.as_deref())
        }
    }
}

fn run_wit(cmd: WitCmd) -> Result<()> {
    match cmd {
        WitCmd::Issue {
            issuer_key,
            sub,
            iss,
            cnf_key,
            ttl,
            kid,
            jti,
            now,
        } => {
            let issuer = key::load(&issuer_key)?.signing_key()?;
            let cnf = key::load(&cnf_key)?.verifying_key()?;
            let iat = now.unwrap_or_else(wimsey_wit::now_unix);
            let exp = iat
                .checked_add(ttl)
                .ok_or("ttl overflows the expiry time")?;
            let claims = WitClaims {
                iss: iss.map(|s| s.trim().to_owned()),
                sub: WorkloadIdentifier::parse(sub.trim())?,
                iat: Some(iat),
                exp,
                jti: Some(jti.map_or_else(random_id, Ok)?),
                cnf: Confirmation {
                    jwk: Jwk::from_ed25519(&cnf),
                },
            };
            let token = wimsey_wit::issue(&claims, kid.as_deref(), &issuer)?;
            println!("{token}");
            Ok(())
        }
        WitCmd::Verify {
            issuer_jwk,
            token,
            token_file,
            expected_iss,
            now,
        } => {
            let key = key::load(&issuer_jwk)?.verifying_key()?;
            let token = read_token(token, token_file)?;
            let mut validation =
                wimsey_wit::Validation::at(now.unwrap_or_else(wimsey_wit::now_unix));
            if let Some(iss) = expected_iss {
                validation = validation.expect_issuer(iss.trim().to_owned());
            }
            let verified = wimsey_wit::verify(&token, &key, &validation)?;
            let out = json!({ "kid": verified.kid, "claims": verified.claims });
            println!("{}", serde_json::to_string_pretty(&out)?);
            Ok(())
        }
        WitCmd::Inspect { token, token_file } => {
            let token = read_token(token, token_file)?;
            let header: serde_json::Value = serde_json::from_slice(&decode_part(&token, 0)?)?;
            let claims: serde_json::Value = serde_json::from_slice(&decode_part(&token, 1)?)?;
            let out = json!({ "header": header, "claims": claims });
            println!("{}", serde_json::to_string_pretty(&out)?);
            Ok(())
        }
    }
}

fn run_wpt(cmd: WptCmd) -> Result<()> {
    match cmd {
        WptCmd::New {
            pop_key,
            wit,
            aud,
            ttl,
            jti,
            now,
        } => {
            let pop = key::load(&pop_key)?.signing_key()?;
            let iat = now.unwrap_or_else(wimsey_wit::now_unix);
            let exp = iat
                .checked_add(ttl)
                .ok_or("ttl overflows the expiry time")?;
            let claims = WptClaims {
                aud: aud.trim().to_owned(),
                exp,
                jti: jti.map_or_else(random_id, Ok)?,
                wth: wimsey_wpt::wit_thumbprint(wit.trim()),
                ath: None,
            };
            let proof = wimsey_wpt::issue(&claims, &pop)?;
            println!("{proof}");
            Ok(())
        }
        WptCmd::Verify {
            issuer_jwk,
            wit,
            aud,
            proof,
            expected_iss,
            now,
        } => {
            let wit = wit.trim();
            let now = now.unwrap_or_else(wimsey_wit::now_unix);

            // First establish trust in the WIT via the issuer key, then take the
            // confirmation key from the *verified* WIT.
            let issuer = key::load(&issuer_jwk)?.verifying_key()?;
            let mut wit_validation = wimsey_wit::Validation::at(now);
            if let Some(iss) = expected_iss {
                wit_validation = wit_validation.expect_issuer(iss.trim().to_owned());
            }
            let verified_wit = wimsey_wit::verify(wit, &issuer, &wit_validation)?;

            let validation = wimsey_wpt::Validation::new(now, aud.trim(), wit);
            let verified = wimsey_wpt::verify(proof.trim(), &verified_wit.pop_key, &validation)?;

            let out = json!({ "sub": verified_wit.claims.sub, "wpt": verified.claims });
            println!("{}", serde_json::to_string_pretty(&out)?);
            Ok(())
        }
    }
}

fn decode_part(token: &str, index: usize) -> Result<Vec<u8>> {
    let part = token
        .split('.')
        .nth(index)
        .ok_or("token does not have the expected number of parts")?;
    Ok(URL_SAFE_NO_PAD.decode(part)?)
}

fn read_token(token: Option<String>, token_file: Option<PathBuf>) -> Result<String> {
    match (token, token_file) {
        (Some(token), _) => Ok(token.trim().to_owned()),
        (None, Some(path)) => Ok(std::fs::read_to_string(path)?.trim().to_owned()),
        (None, None) => Err("provide --token or --token-file".into()),
    }
}

fn random_id() -> Result<String> {
    use std::fmt::Write as _;

    let mut bytes = [0u8; 16];
    getrandom::fill(&mut bytes).map_err(|e| format!("getrandom: {e}"))?;
    let mut id = String::with_capacity(bytes.len() * 2);
    for b in bytes {
        let _ = write!(id, "{b:02x}");
    }
    Ok(id)
}

fn emit(content: &str, out: Option<&Path>) -> Result<()> {
    match out {
        Some(path) => write_owner_only(path, content)?,
        None => println!("{content}"),
    }
    Ok(())
}

/// Writes `content` to `path` owner-only (mode 0600 on unix), atomically.
///
/// The bytes are written to a fresh temporary file created with the right
/// permissions from the start (`create_new` + `mode`), then renamed over the
/// destination. This avoids the race where an existing file is briefly readable
/// between opening and tightening it, and leaves no partial file on failure.
fn write_owner_only(path: &Path, content: &str) -> Result<()> {
    use std::io::Write as _;

    let mut temp_name = path
        .file_name()
        .ok_or("output path has no file name")?
        .to_os_string();
    temp_name.push(format!(".tmp-{}", random_id()?));
    let temp_path = match path.parent().filter(|p| !p.as_os_str().is_empty()) {
        Some(dir) => dir.join(&temp_name),
        None => PathBuf::from(&temp_name),
    };

    let mut options = std::fs::OpenOptions::new();
    options.write(true).create_new(true);
    #[cfg(unix)]
    {
        use std::os::unix::fs::OpenOptionsExt as _;
        options.mode(0o600);
    }

    let mut file = options
        .open(&temp_path)
        .map_err(|e| format!("creating temporary file: {e}"))?;
    let write_result = file
        .write_all(content.as_bytes())
        .and_then(|()| file.sync_all());
    // Close the handle before touching the file again; Windows refuses to
    // rename or delete a file that is still open.
    drop(file);

    if let Err(e) = write_result {
        let _ = std::fs::remove_file(&temp_path);
        return Err(e.into());
    }
    if let Err(e) = std::fs::rename(&temp_path, path) {
        let _ = std::fs::remove_file(&temp_path);
        return Err(format!("renaming temporary file: {e}").into());
    }
    Ok(())
}