Skip to content

Commit

Permalink
Update nitrokey to v0.8.0
Browse files Browse the repository at this point in the history
This patch updates the nitrokey dependency to version 0.8.0 and applies
all breaking changes (Config fields renaming, DeviceWrapper and Model
non-exhaustiveness, changed Display implementation for Model).
  • Loading branch information
robinkrahl authored and d-e-s-o committed Jan 11, 2021
1 parent 3152a6d commit f18fdc6
Show file tree
Hide file tree
Showing 11 changed files with 63 additions and 47 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ Unreleased
- Added the `termion` dependency in version `1.5.5`
- Added SD card usage information to the output of the `status` command for
Storage devices
- Bumped `nitrokey` dependency to `0.8.0`


0.3.5
Expand Down
8 changes: 4 additions & 4 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ version = "0.2"
version = "0.1"

[dependencies.nitrokey]
version = "0.7.1"
version = "0.8"

[dependencies.progressing]
version = "3.0.2"
Expand Down
2 changes: 1 addition & 1 deletion src/arg_util.rs
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ macro_rules! Command {
macro_rules! Enum {
( $(#[$docs:meta])* $name:ident, [ $( $var:ident => $str:expr, ) *] ) => {
$(#[$docs])*
#[derive(Clone, Copy, Debug, PartialEq)]
#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
pub enum $name {
$(
$var,
Expand Down
14 changes: 14 additions & 0 deletions src/args.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
// Copyright (C) 2020 The Nitrocli Developers
// SPDX-License-Identifier: GPL-3.0-or-later

use std::convert;

/// Provides access to a Nitrokey device
#[derive(Debug, structopt::StructOpt)]
#[structopt(name = "nitrocli")]
Expand Down Expand Up @@ -59,6 +61,18 @@ impl From<DeviceModel> for nitrokey::Model {
}
}

impl convert::TryFrom<nitrokey::Model> for DeviceModel {
type Error = anyhow::Error;

fn try_from(model: nitrokey::Model) -> Result<DeviceModel, anyhow::Error> {
match model {
nitrokey::Model::Pro => Ok(DeviceModel::Pro),
nitrokey::Model::Storage => Ok(DeviceModel::Storage),
_ => Err(anyhow::anyhow!("Unsupported device model: {}", model)),
}
}
}

impl<'de> serde::Deserialize<'de> for DeviceModel {
fn deserialize<D>(deserializer: D) -> Result<DeviceModel, D::Error>
where
Expand Down
28 changes: 9 additions & 19 deletions src/commands.rs
Original file line number Diff line number Diff line change
Expand Up @@ -370,11 +370,7 @@ fn print_storage_status(
}

/// Query and pretty print the status that is common to all Nitrokey devices.
fn print_status(
ctx: &mut Context<'_>,
model: &'static str,
device: &nitrokey::DeviceWrapper<'_>,
) -> anyhow::Result<()> {
fn print_status(ctx: &mut Context<'_>, device: &nitrokey::DeviceWrapper<'_>) -> anyhow::Result<()> {
let serial_number = device
.get_serial_number()
.context("Could not query the serial number")?;
Expand All @@ -387,7 +383,7 @@ fn print_status(
firmware version: {fwv}
user retry count: {urc}
admin retry count: {arc}"#,
model = model,
model = device.get_model(),
id = serial_number,
fwv = device
.get_firmware_version()
Expand Down Expand Up @@ -416,13 +412,7 @@ fn print_status(

/// Inquire the status of the nitrokey.
pub fn status(ctx: &mut Context<'_>) -> anyhow::Result<()> {
with_device(ctx, |ctx, device| {
let model = match device {
nitrokey::DeviceWrapper::Pro(_) => "Pro",
nitrokey::DeviceWrapper::Storage(_) => "Storage",
};
print_status(ctx, model, &device)
})
with_device(ctx, |ctx, device| print_status(ctx, &device))
}

/// List the attached Nitrokey devices.
Expand Down Expand Up @@ -671,9 +661,9 @@ pub fn config_get(ctx: &mut Context<'_>) -> anyhow::Result<()> {
capslock binding: {cl}
scrollock binding: {sl}
require user PIN for OTP: {otp}"#,
nl = format_option(config.numlock),
cl = format_option(config.capslock),
sl = format_option(config.scrollock),
nl = format_option(config.num_lock),
cl = format_option(config.caps_lock),
sl = format_option(config.scroll_lock),
otp = config.user_password,
)?;
Ok(())
Expand Down Expand Up @@ -702,9 +692,9 @@ pub fn config_set(ctx: &mut Context<'_>, args: args::ConfigSetArgs) -> anyhow::R
.get_config()
.context("Failed to get current configuration")?;
let config = nitrokey::Config {
numlock: numlock.or(config.numlock),
capslock: capslock.or(config.capslock),
scrollock: scrollock.or(config.scrollock),
num_lock: numlock.or(config.num_lock),
caps_lock: capslock.or(config.caps_lock),
scroll_lock: scrollock.or(config.scroll_lock),
user_password: otp_pin.unwrap_or(config.user_password),
};
device
Expand Down
4 changes: 2 additions & 2 deletions src/pinentry.rs
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ impl SecretEntry for PinEntry {

fn description(&self, mode: Mode) -> CowStr {
format!(
"{} for\rNitrokey {} {}",
"{} for\r {} {}",
match self.pin_type {
args::PinType::Admin => match mode {
Mode::Choose => "Please enter a new admin PIN",
Expand Down Expand Up @@ -135,7 +135,7 @@ impl SecretEntry for PwdEntry {

fn description(&self, mode: Mode) -> CowStr {
format!(
"{} for\rNitrokey {} {}",
"{} for\r {} {}",
match mode {
Mode::Choose => "Please enter a new hidden volume password",
Mode::Confirm => "Please confirm the new hidden volume password",
Expand Down
2 changes: 1 addition & 1 deletion src/tests/list.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ fn not_connected() -> anyhow::Result<()> {
fn connected(model: nitrokey::Model) -> anyhow::Result<()> {
let re = regex::Regex::new(
r#"^USB path\tmodel\tserial number
([[:^space:]]+\t(Pro|Storage|unknown)\t0x[[:xdigit:]]+
([[:^space:]]+\t(Nitrokey Pro|Nitrokey Storage|unknown)\t0x[[:xdigit:]]+
)+$"#,
)
.unwrap();
Expand Down
1 change: 1 addition & 0 deletions src/tests/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,7 @@ impl Nitrocli {
match model {
nitrokey::Model::Pro => "--model=pro",
nitrokey::Model::Storage => "--model=storage",
_ => panic!("Unexpected model in test suite: {}", model),
}
}

Expand Down
44 changes: 27 additions & 17 deletions src/tests/run.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,13 @@
// SPDX-License-Identifier: GPL-3.0-or-later

use std::collections;
use std::convert;
use std::convert::TryInto as _;
use std::ops;
use std::path;

use super::*;
use crate::args;

#[test]
fn no_command_or_option() {
Expand Down Expand Up @@ -173,32 +176,33 @@ fn connect_wrong_usb_path(_model: nitrokey::Model) {
fn connect_model(_model: nitrokey::Model) -> anyhow::Result<()> {
let devices = nitrokey::list_devices()?;
let mut model_counts = collections::BTreeMap::new();
let _ = model_counts.insert(nitrokey::Model::Pro.to_string(), 0);
let _ = model_counts.insert(nitrokey::Model::Storage.to_string(), 0);
for model in devices.iter().filter_map(|d| d.model) {
*model_counts.entry(model.to_string()).or_default() += 1;
let _ = model_counts.insert(args::DeviceModel::Pro, 0);
let _ = model_counts.insert(args::DeviceModel::Storage, 0);
for nkmodel in devices.iter().filter_map(|d| d.model) {
let model = nkmodel.try_into().expect("Unexpected Nitrokey model");
*model_counts.entry(model).or_default() += 1;
}

for (model, count) in model_counts {
let res = Nitrocli::new().handle(&["status", &format!("--model={}", model.to_lowercase())]);
let res = Nitrocli::new().handle(&["status", &format!("--model={}", model)]);
if count == 0 {
let err = res.unwrap_err().to_string();
assert_eq!(
err,
format!(
"Nitrokey device not found (filter: model={})",
model.to_lowercase()
)
format!("Nitrokey device not found (filter: model={})", model)
);
} else if count == 1 {
assert!(res?.contains(&format!("model: {}\n", model)));
assert!(res?.contains(&format!(
"model: {}\n",
nitrokey::Model::from(model)
)));
} else {
let err = res.unwrap_err().to_string();
assert_eq!(
err,
format!(
"Multiple Nitrokey devices found (filter: model={}). ",
model.to_lowercase()
model
) + "Use the --model, --serial-number, and --usb-path options to select one"
);
}
Expand All @@ -211,11 +215,14 @@ fn connect_model(_model: nitrokey::Model) -> anyhow::Result<()> {
fn connect_usb_path_model_serial(_model: nitrokey::Model) -> anyhow::Result<()> {
let devices = nitrokey::list_devices()?;
for device in devices {
let model = device.model.map(|nkmodel| {
convert::TryInto::<args::DeviceModel>::try_into(nkmodel).expect("Unexpected Nitrokey model")
});
let mut args = Vec::new();
args.push("status".to_owned());
args.push(format!("--usb-path={}", device.path));
if let Some(model) = device.model {
args.push(format!("--model={}", model.to_string().to_lowercase()));
if let Some(model) = model {
args.push(format!("--model={}", model));
}
if let Some(sn) = device.serial_number {
args.push(format!("--serial-number={}", sn));
Expand All @@ -236,22 +243,25 @@ fn connect_usb_path_model_serial(_model: nitrokey::Model) -> anyhow::Result<()>
fn connect_usb_path_model_wrong_serial(_model: nitrokey::Model) -> anyhow::Result<()> {
let devices = nitrokey::list_devices()?;
for device in devices {
let model = device.model.map(|nkmodel| {
convert::TryInto::<args::DeviceModel>::try_into(nkmodel).expect("Unexpected Nitrokey model")
});
let mut args = Vec::new();
args.push("status".to_owned());
args.push(format!("--usb-path={}", device.path));
if let Some(model) = device.model {
args.push(format!("--model={}", model.to_string().to_lowercase()));
if let Some(model) = model {
args.push(format!("--model={}", model));
}
args.push("--serial-number=0xdeadbeef".to_owned());

let res = Nitrocli::new().handle(&args.iter().map(ops::Deref::deref).collect::<Vec<_>>());
let err = res.unwrap_err().to_string();
if let Some(model) = device.model {
if let Some(model) = model {
assert_eq!(
err,
format!(
"Nitrokey device not found (filter: model={}, serial number in [0xdeadbeef], usb path={})",
model.to_string().to_lowercase(),
model,
device.path
)
);
Expand Down
4 changes: 2 additions & 2 deletions src/tests/status.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ fn not_found() {
fn output_pro(model: nitrokey::Model) -> anyhow::Result<()> {
let re = regex::Regex::new(
r#"^Status:
model: Pro
model: Nitrokey Pro
serial number: 0x[[:xdigit:]]{8}
firmware version: v\d+\.\d+
user retry count: [0-3]
Expand All @@ -43,7 +43,7 @@ $"#,
fn output_storage(model: nitrokey::Model) -> anyhow::Result<()> {
let re = regex::Regex::new(
r#"^Status:
model: Storage
model: Nitrokey Storage
serial number: 0x[[:xdigit:]]{8}
firmware version: v\d+\.\d+
user retry count: [0-3]
Expand Down

0 comments on commit f18fdc6

Please sign in to comment.