biscuit-cli 0.6.0-beta.2

a CLI to manipulate biscuit tokens
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
/*
 * SPDX-FileCopyrightText: 2021 Clément Delafargue <clement@delafargue.name>
 *
 * SPDX-License-Identifier: BSD-3-Clause
 */
use anyhow::{bail, Result};
use biscuit_auth::{
    builder::BlockBuilder,
    builder_ext::BuilderExt,
    Biscuit, {KeyPair, PrivateKey},
};
use clap::Parser;
use std::io;
use std::io::Write;
use std::path::PathBuf;

mod cli;
mod errors;
mod input;
mod inspect;

use cli::*;
use input::*;
use inspect::*;

fn handle_command(cmd: &SubCommand) -> Result<()> {
    match cmd {
        SubCommand::KeyPairCmd(key_pair_cmd) => handle_keypair(key_pair_cmd),
        SubCommand::Inspect(inspect) => handle_inspect(inspect),
        SubCommand::InspectSnapshot(inspect_snapshot) => handle_inspect_snapshot(inspect_snapshot),
        SubCommand::Generate(generate) => handle_generate(generate),
        SubCommand::Attenuate(attenuate) => handle_attenuate(attenuate),
        SubCommand::GenerateThirdPartyBlockRequest(generate_request) => {
            handle_generate_request(generate_request)
        }
        SubCommand::GenerateThirdPartyBlock(generate_third_party_block) => {
            handle_generate_third_party_block(generate_third_party_block)
        }
        SubCommand::AppendThirdPartyBlock(append_third_party_block) => {
            handle_append_third_party_block(append_third_party_block)
        }
        SubCommand::Seal(seal) => handle_seal(seal),
    }
}

fn handle_keypair(key_pair_cmd: &KeyPairCmd) -> Result<()> {
    let stdin_path = PathBuf::from("-");
    let private_key_from = &match (
        &key_pair_cmd.from_private_key,
        &key_pair_cmd.from_file,
        &key_pair_cmd.from_format,
    ) {
        (Some(_), _, KeyFormat::Raw) => {
            bail!("raw key input is only allowed from a file or stdin")
        }
        (Some(str), None, KeyFormat::Hex) => Some(KeyBytes::HexString(str.to_owned())),
        (Some(str), None, KeyFormat::Pem) => Some(KeyBytes::PemString(str.to_owned())),
        (None, Some(path), f) if path == &stdin_path => Some(KeyBytes::FromStdin(*f)),
        (None, Some(path), f) => Some(KeyBytes::FromFile(*f, path.to_path_buf())),
        (None, None, _) => None,
        // the other combinations are prevented by clap
        _ => unreachable!(),
    };

    let private_key: Option<PrivateKey> = if let Some(f) = private_key_from {
        Some(read_private_key_from(f, &key_pair_cmd.from_algorithm)?)
    } else {
        None
    };

    let key_pair = if let Some(private) = private_key {
        KeyPair::from(&private)
    } else {
        KeyPair::new_with_algorithm(key_pair_cmd.key_algorithm.0)
    };

    match (
        &key_pair_cmd.only_private_key,
        &key_pair_cmd.only_public_key,
        &key_pair_cmd.key_output_format,
    ) {
        (false, false, KeyFormat::Raw) => {
            bail!("Only a single key can be returned in a binary format")
        }
        (false, false, KeyFormat::Hex) => {
            if private_key_from.is_some() {
                println!("Generating a keypair from the provided private key");
            } else {
                println!("Generating a new random keypair");
            }
            println!("Private key: {}", key_pair.private().to_prefixed_string());
            println!("Public key: {}", key_pair.public());
        }
        (false, false, KeyFormat::Pem) => {
            if private_key_from.is_some() {
                println!("Generating a keypair for the provided private key");
            } else {
                println!("Generating a new random keypair");
            }
            println!(
                "{}{}",
                *key_pair.private().to_pem()?,
                key_pair.public().to_pem()?
            );
        }
        (true, false, KeyFormat::Raw) => {
            let _ = io::stdout().write_all(&key_pair.private().to_bytes());
        }
        (true, false, KeyFormat::Hex) => {
            println!("{}", key_pair.private().to_prefixed_string());
        }
        (true, false, KeyFormat::Pem) => {
            println!("{}", *key_pair.private().to_pem()?);
        }
        (false, true, KeyFormat::Raw) => {
            let _ = io::stdout().write_all(&key_pair.public().to_bytes());
        }
        (false, true, KeyFormat::Hex) => {
            println!("{}", key_pair.public());
        }
        (false, true, KeyFormat::Pem) => {
            println!("{}", key_pair.public().to_pem()?);
        }
        // the other combinations are prevented by clap
        _ => unreachable!(),
    }
    Ok(())
}

fn handle_generate(generate: &Generate) -> Result<()> {
    let authority_from = match &generate.authority_file {
        Some(path) if path == &PathBuf::from("-") => DatalogInput::FromStdin,
        Some(path) => DatalogInput::FromFile(path.to_path_buf()),
        None => DatalogInput::FromEditor,
    };

    let private_key: Result<PrivateKey> = read_private_key_from(
        &match (
            &generate.private_key_args.private_key,
            &generate.private_key_args.private_key_file,
            &generate.private_key_args.private_key_format,
        ) {
            (Some(str), None, KeyFormat::Hex) => KeyBytes::HexString(str.to_owned()),
            (Some(str), None, KeyFormat::Pem) => KeyBytes::PemString(str.to_owned()),
            (None, Some(file), f) => KeyBytes::FromFile(*f, file.to_path_buf()),
            // the other combinations are prevented by clap
            _ => unreachable!(),
        },
        &generate.private_key_args.private_key_algorithm,
    );

    let root = KeyPair::from(&private_key?);
    let mut builder = Biscuit::builder();
    builder = read_authority_from(
        &authority_from,
        &generate.param_arg.param,
        &generate.context,
        builder,
    )?;

    if let Some(ttl) = &generate.add_ttl {
        builder = builder.check_expiration_date(ttl.to_datetime().into());
    }
    if let Some(root_key_id) = &generate.root_key_id {
        builder = builder.root_key_id(*root_key_id);
    }
    let biscuit = builder.build(&root).expect("Error building biscuit"); // todo display error
    let encoded = if generate.raw {
        biscuit.to_vec().expect("Error serializing token")
    } else {
        biscuit
            .to_base64()
            .expect("Error serializing token")
            .into_bytes()
    };
    let _ = io::stdout().write_all(&encoded);
    Ok(())
}

fn handle_attenuate(attenuate: &Attenuate) -> Result<()> {
    let biscuit_format = if attenuate.biscuit_input_args.raw_input {
        BiscuitFormat::RawBiscuit
    } else {
        BiscuitFormat::Base64Biscuit
    };

    let biscuit_from = if attenuate.biscuit_input_args.biscuit_file == PathBuf::from("-") {
        BiscuitBytes::FromStdin(biscuit_format)
    } else {
        BiscuitBytes::FromFile(
            biscuit_format,
            attenuate.biscuit_input_args.biscuit_file.clone(),
        )
    };

    let block_from = match (
        &attenuate.block_args.block_file,
        &attenuate.block_args.block,
    ) {
        (Some(file), None) => DatalogInput::FromFile(file.to_path_buf()),
        (None, Some(str)) => DatalogInput::DatalogString(str.to_owned()),
        (None, None) => DatalogInput::FromEditor,
        // the other combinations are prevented by clap
        _ => unreachable!(),
    };

    ensure_no_input_conflict(&block_from, &biscuit_from)?;

    let biscuit = read_biscuit_from(&biscuit_from)?;
    let mut block_builder = BlockBuilder::new();

    block_builder = read_block_from(
        &block_from,
        &attenuate.param_arg.param,
        &attenuate.block_args.context,
        block_builder,
    )?;

    if let Some(ttl) = &attenuate.block_args.add_ttl {
        block_builder = block_builder.check_expiration_date(ttl.to_datetime().into());
    }

    let new_biscuit = biscuit.append(block_builder)?;
    let encoded = if attenuate.raw_output {
        new_biscuit.to_vec()?
    } else {
        new_biscuit.to_base64()?.into_bytes()
    };
    let _ = io::stdout().write_all(&encoded);
    Ok(())
}

fn handle_generate_request(generate_request: &GenerateThirdPartyBlockRequest) -> Result<()> {
    let biscuit_format = if generate_request.biscuit_input_args.raw_input {
        BiscuitFormat::RawBiscuit
    } else {
        BiscuitFormat::Base64Biscuit
    };

    let biscuit_from = if generate_request.biscuit_input_args.biscuit_file == PathBuf::from("-") {
        BiscuitBytes::FromStdin(biscuit_format)
    } else {
        BiscuitBytes::FromFile(
            biscuit_format,
            generate_request.biscuit_input_args.biscuit_file.clone(),
        )
    };

    let biscuit = read_biscuit_from(&biscuit_from)?;

    let request = biscuit.third_party_request()?;

    let encoded = if generate_request.raw_output {
        request.serialize()?
    } else {
        request.serialize_base64()?.into_bytes()
    };
    let _ = io::stdout().write_all(&encoded);
    Ok(())
}

fn handle_generate_third_party_block(
    generate_third_party_block: &GenerateThirdPartyBlock,
) -> Result<()> {
    let block_format = if generate_third_party_block.raw_input {
        BiscuitFormat::RawBiscuit
    } else {
        BiscuitFormat::Base64Biscuit
    };

    let request_from = if generate_third_party_block.request_file == PathBuf::from("-") {
        BiscuitBytes::FromStdin(block_format)
    } else {
        BiscuitBytes::FromFile(
            block_format,
            generate_third_party_block.request_file.clone(),
        )
    };

    let block_from = match (
        &generate_third_party_block.block_args.block_file,
        &generate_third_party_block.block_args.block,
    ) {
        (Some(file), None) => DatalogInput::FromFile(file.to_path_buf()),
        (None, Some(str)) => DatalogInput::DatalogString(str.to_owned()),
        (None, None) => DatalogInput::FromEditor,
        // the other combinations are prevented by clap
        _ => unreachable!(),
    };

    ensure_no_input_conflict(&block_from, &request_from)?;

    let private_key: Result<PrivateKey> = read_private_key_from(
        &match (
            &generate_third_party_block.private_key_args.private_key,
            &generate_third_party_block.private_key_args.private_key_file,
            &generate_third_party_block
                .private_key_args
                .private_key_format,
        ) {
            (Some(hex_string), None, KeyFormat::Hex) => KeyBytes::HexString(hex_string.to_owned()),
            (Some(pem_string), None, KeyFormat::Pem) => KeyBytes::PemString(pem_string.to_owned()),
            (None, Some(file), KeyFormat::Raw) => {
                KeyBytes::FromFile(KeyFormat::Raw, file.to_path_buf())
            }
            (None, Some(file), f) => KeyBytes::FromFile(*f, file.to_path_buf()),
            // the other combinations are prevented by clap
            _ => unreachable!(),
        },
        &generate_third_party_block
            .private_key_args
            .private_key_algorithm,
    );

    let request = read_request_from(&request_from)?;

    let mut builder = BlockBuilder::new();
    builder = read_block_from(
        &block_from,
        &generate_third_party_block.param_arg.param,
        &generate_third_party_block.block_args.context,
        builder,
    )?;

    if let Some(ttl) = &generate_third_party_block.block_args.add_ttl {
        builder = builder.check_expiration_date(ttl.to_datetime().into());
    }

    let block = request.create_block(&private_key?, builder)?;

    let encoded = if generate_third_party_block.raw_output {
        block.serialize()?
    } else {
        block.serialize_base64()?.into_bytes()
    };
    let _ = io::stdout().write_all(&encoded);
    Ok(())
}

fn handle_append_third_party_block(append_third_party_block: &AppendThirdPartyBlock) -> Result<()> {
    let biscuit_format = if append_third_party_block.biscuit_input_args.raw_input {
        BiscuitFormat::RawBiscuit
    } else {
        BiscuitFormat::Base64Biscuit
    };

    let biscuit_from =
        if append_third_party_block.biscuit_input_args.biscuit_file == PathBuf::from("-") {
            BiscuitBytes::FromStdin(biscuit_format)
        } else {
            BiscuitBytes::FromFile(
                biscuit_format,
                append_third_party_block
                    .biscuit_input_args
                    .biscuit_file
                    .clone(),
            )
        };

    let block_file_format = if append_third_party_block.raw_block_contents {
        BiscuitFormat::RawBiscuit
    } else {
        BiscuitFormat::Base64Biscuit
    };

    let block_from = match (
        &append_third_party_block.block_contents_file,
        &append_third_party_block.block_contents,
    ) {
        (Some(file), None) if file == &PathBuf::from("-") => {
            BiscuitBytes::FromStdin(block_file_format)
        }
        (Some(file), None) => BiscuitBytes::FromFile(block_file_format, file.to_path_buf()),
        (None, Some(str)) => BiscuitBytes::Base64String(str.to_owned()),
        // the other combinations are prevented by clap
        _ => unreachable!(),
    };

    ensure_no_input_conflict_third_party(&block_from, &biscuit_from)?;

    let biscuit = read_biscuit_from(&biscuit_from)?;

    let new_biscuit = append_third_party_from(&biscuit, &block_from)?;

    let encoded = if append_third_party_block.raw_output {
        new_biscuit.to_vec()?
    } else {
        new_biscuit.to_base64()?.into_bytes()
    };
    let _ = io::stdout().write_all(&encoded);
    Ok(())
}

fn handle_seal(seal: &Seal) -> Result<()> {
    let biscuit_format = if seal.biscuit_input_args.raw_input {
        BiscuitFormat::RawBiscuit
    } else {
        BiscuitFormat::Base64Biscuit
    };

    let biscuit_from = if seal.biscuit_input_args.biscuit_file == PathBuf::from("-") {
        BiscuitBytes::FromStdin(biscuit_format)
    } else {
        BiscuitBytes::FromFile(biscuit_format, seal.biscuit_input_args.biscuit_file.clone())
    };

    let biscuit = read_biscuit_from(&biscuit_from)?;
    let new_biscuit = biscuit.seal()?;
    let encoded = if seal.raw_output {
        new_biscuit.to_vec()?
    } else {
        new_biscuit.to_base64()?.into_bytes()
    };
    let _ = io::stdout().write_all(&encoded);
    Ok(())
}

pub fn main() -> Result<()> {
    let opts: Opts = Opts::parse();
    handle_command(&opts.subcmd)
}