Skip to content

Commit

Permalink
Fix multipart requests
Browse files Browse the repository at this point in the history
This patch fixes the implementation of multipart requests that were
previously just ignored.

Fixes: #20
  • Loading branch information
robin-nitrokey committed May 15, 2024
1 parent ea9859b commit c7cbe7b
Show file tree
Hide file tree
Showing 8 changed files with 214 additions and 3 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 @@
### Bugfixes

- Return `Error::ResponseError` instead of `Error::Transport` for API errors ([#21](https://github.com/Nitrokey/nethsm-sdk-rs/issues/21))
- Fix multipart requests, namely `system_restore_post` ([#20](https://github.com/Nitrokey/nethsm-sdk-rs/issues/20))

[All Changes](https://github.com/Nitrokey/nethsm-sdk-rs/compare/v1.0.1...HEAD)

Expand Down
3 changes: 3 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@ exclude = [
]

[dependencies]
mime = "0.3"
multipart = { version = "0.18", default-features = false, features = ["client"] }
serde = { default-features = false, version = "^1.0" }
serde_derive = "^1.0"
serde_json = { default-features = false, version = "^1.0" }
Expand All @@ -27,6 +29,7 @@ ureq = { version = "2", features = ["json", "tls"], default-features = false }
base64 = { version = "0.21", default-features = false, features = ["alloc"] }

[dev-dependencies]
chrono = "0.4.38"
env_logger = "0.11.3"
rustainers = "0.12.0"
rustls = { version = "0.22.4" }
Expand Down
3 changes: 3 additions & 0 deletions generator/src/main/resources/crust/Cargo.mustache
Original file line number Diff line number Diff line change
Expand Up @@ -41,8 +41,11 @@ serde_json = { default-features = false, version = "^1.0" }
url = "^2.2"
ureq = { version = "2", features = ["json", "tls"], default-features = false }
base64 = { version = "0.21", default-features = false, features = ["alloc"] }
mime = "0.3"
multipart = { version = "0.18", default-features = false, features = ["client"] }

[dev-dependencies]
chrono = "0.4.38"
env_logger = "0.11.3"
rustainers = "0.12.0"
rustls = { version = "0.22.4" }
Expand Down
40 changes: 40 additions & 0 deletions generator/src/main/resources/crust/reqwest/api.mustache
Original file line number Diff line number Diff line change
Expand Up @@ -285,6 +285,45 @@ pub fn {{{operationId}}}(configuration: &configuration::Configuration, {{#allPar
local_var_req_builder = local_var_req_builder.set("accept", accept_str);
{{/hasProduces}}

{{#isMultipart}}
let mut local_var_multipart = ::multipart::client::lazy::Multipart::new();

{{#hasFormParams}}
{{#formParams}}
{{#isFile}}
if let Some({{{paramName}}}) = {{{paramName}}} {
local_var_multipart.add_stream(
"{{{baseName}}}",
::std::io::Cursor::new({{{paramName}}}),
None::<&str>,
None,
);
}
{{/isFile}}
{{/formParams}}
{{#formParams}}
{{^isFile}}
if let Some({{{paramName}}}) = {{{paramName}}} {
let {{{paramName}}} = ::serde_json::to_vec(&{{{paramName}}})?;
local_var_multipart.add_stream(
"{{{baseName}}}",
::std::io::Cursor::new({{{paramName}}}),
None::<&str>,
None,
);
}
{{/isFile}}
{{/formParams}}
{{/hasFormParams}}

let local_var_multipart = local_var_multipart.prepare()?;
local_var_req_builder = local_var_req_builder.set(
"content-type",
&format!("multipart/form-data; boundary={}", local_var_multipart.boundary()),
);
let local_var_result = local_var_req_builder.send(local_var_multipart);
{{/isMultipart}}
{{^isMultipart}}
{{#vendorExtensions.x-consumeMultipleMediaTypes}}
{{#hasBodyParam}}{{#bodyParams}}
let body_json = body.is_json();
Expand Down Expand Up @@ -328,6 +367,7 @@ pub fn {{{operationId}}}(configuration: &configuration::Configuration, {{#allPar
{{^hasBodyParam}}
let local_var_result = local_var_req_builder.call();
{{/hasBodyParam}}
{{/isMultipart}}

let local_var_resp = local_var_result.or_else(|err| match err {
ureq::Error::Status(_status, resp) => Ok(resp),
Expand Down
21 changes: 21 additions & 0 deletions generator/src/main/resources/crust/reqwest/api_mod.mustache
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,10 @@ pub struct ResponseContent<T> {

#[derive(Debug)]
pub enum Error<T> {
Multipart {
field: Option<String>,
error: std::io::Error,
},
Ureq(ureq::Error),
Serde(serde_json::Error),
Io(std::io::Error),
Expand All @@ -38,6 +42,13 @@ pub enum Error<T> {
impl <T> fmt::Display for Error<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let (module, e) = match self {
Error::Multipart { field, error } => {
let error = match field {
Some(field) => format!("failed to encode {field}: {error}"),
None => error.to_string(),
};
("multipart", error)
}
Error::Ureq(e) => ("ureq", e.to_string()),
Error::Serde(e) => ("serde", e.to_string()),
Error::Io(e) => ("IO", e.to_string()),
Expand All @@ -51,6 +62,7 @@ impl <T> fmt::Display for Error<T> {
impl <T: fmt::Debug> error::Error for Error<T> {
fn source(&self) -> Option<&(dyn error::Error + 'static)> {
Some(match self {
Error::Multipart { error, .. } => error,
Error::Ureq(e) => e,
Error::Serde(e) => e,
Error::Io(e) => e,
Expand All @@ -60,6 +72,15 @@ impl <T: fmt::Debug> error::Error for Error<T> {
}
}

impl<T> From<multipart::client::lazy::LazyError<'_, std::io::Error>> for Error<T> {
fn from(e: multipart::client::lazy::LazyError<'_, std::io::Error>) -> Self {
Self::Multipart {
field: e.field_name.map(|s| s.into_owned()),
error: e.error,
}
}
}
impl <T> From<ureq::Error> for Error<T> {
fn from(e: ureq::Error) -> Self {
Error::Ureq(e)
Expand Down
30 changes: 28 additions & 2 deletions src/apis/default_api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3591,9 +3591,35 @@ pub fn system_restore_post(
local_var_req_builder = local_var_req_builder.set("user-agent", local_var_user_agent);
}

local_var_req_builder = local_var_req_builder.set("content-type", "multipart/form-data");
let mut local_var_multipart = ::multipart::client::lazy::Multipart::new();

if let Some(backup_file) = backup_file {
local_var_multipart.add_stream(
"backup_file",
::std::io::Cursor::new(backup_file),
None::<&str>,
None,
);
}
if let Some(arguments) = arguments {
let arguments = ::serde_json::to_vec(&arguments)?;
local_var_multipart.add_stream(
"arguments",
::std::io::Cursor::new(arguments),
None::<&str>,
None,
);
}

let local_var_result = local_var_req_builder.call();
let local_var_multipart = local_var_multipart.prepare()?;
local_var_req_builder = local_var_req_builder.set(
"content-type",
&format!(
"multipart/form-data; boundary={}",
local_var_multipart.boundary()
),
);
let local_var_result = local_var_req_builder.send(local_var_multipart);

let local_var_resp = local_var_result.or_else(|err| match err {
ureq::Error::Status(_status, resp) => Ok(resp),
Expand Down
21 changes: 21 additions & 0 deletions src/apis/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,10 @@ pub struct ResponseContent<T> {

#[derive(Debug)]
pub enum Error<T> {
Multipart {
field: Option<String>,
error: std::io::Error,
},
Ureq(ureq::Error),
Serde(serde_json::Error),
Io(std::io::Error),
Expand All @@ -36,6 +40,13 @@ pub enum Error<T> {
impl<T> fmt::Display for Error<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let (module, e) = match self {
Error::Multipart { field, error } => {
let error = match field {
Some(field) => format!("failed to encode {field}: {error}"),
None => error.to_string(),
};
("multipart", error)
}
Error::Ureq(e) => ("ureq", e.to_string()),
Error::Serde(e) => ("serde", e.to_string()),
Error::Io(e) => ("IO", e.to_string()),
Expand All @@ -49,6 +60,7 @@ impl<T> fmt::Display for Error<T> {
impl<T: fmt::Debug> error::Error for Error<T> {
fn source(&self) -> Option<&(dyn error::Error + 'static)> {
Some(match self {
Error::Multipart { error, .. } => error,
Error::Ureq(e) => e,
Error::Serde(e) => e,
Error::Io(e) => e,
Expand All @@ -58,6 +70,15 @@ impl<T: fmt::Debug> error::Error for Error<T> {
}
}

impl<T> From<multipart::client::lazy::LazyError<'_, std::io::Error>> for Error<T> {
fn from(e: multipart::client::lazy::LazyError<'_, std::io::Error>) -> Self {
Self::Multipart {
field: e.field_name.map(|s| s.into_owned()),
error: e.error,
}
}
}

impl<T> From<ureq::Error> for Error<T> {
fn from(e: ureq::Error) -> Self {
Error::Ureq(e)
Expand Down
98 changes: 97 additions & 1 deletion tests/basic.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,16 @@
mod utils;

use nethsm_sdk_rs::apis::{default_api, Error};
use std::collections::BTreeSet;

use chrono::Utc;
use nethsm_sdk_rs::{
apis::{configuration::Configuration, default_api, Error},
models::{
BackupPassphraseConfig, KeyGenerateRequestData, KeyMechanism, KeyType,
ProvisionRequestData, RestoreRequestArguments, SystemState, UnlockRequestData,
UserPostData, UserRole,
},
};

#[tokio::test]
async fn test_health_state() {
Expand Down Expand Up @@ -31,3 +41,89 @@ async fn test_error() {
})
.await
}
#[tokio::test]
async fn test_restore_unprovisioned() {
let admin_passphrase = "adminadmin";
let backup_passphrase = "backupbackup";
let unlock_passphrase = "unlockunlock";

let (generated_keys, backup) = utils::with_container(|mut config| {
let request = ProvisionRequestData {
unlock_passphrase: unlock_passphrase.to_owned(),
admin_passphrase: admin_passphrase.to_owned(),
system_time: Utc::now().to_rfc3339(),
};
default_api::provision_post(&config, request).unwrap();

config.basic_auth = Some(("admin".to_owned(), Some(admin_passphrase.to_owned())));

let request = KeyGenerateRequestData {
r#type: KeyType::Rsa,
length: Some(2048),
mechanisms: vec![KeyMechanism::RsaDecryptionRaw],
..Default::default()
};
let key_id = default_api::keys_generate_post(&config, request)
.unwrap()
.entity
.id;
let keys = BTreeSet::from([key_id]);

assert_eq!(list_keys(&config), keys);

let request = BackupPassphraseConfig {
new_passphrase: backup_passphrase.to_owned(),
current_passphrase: String::new(),
};
default_api::config_backup_passphrase_put(&config, request).unwrap();

let request = UserPostData {
real_name: "Backup User".to_owned(),
role: UserRole::Backup,
passphrase: backup_passphrase.to_owned(),
};
default_api::users_user_id_put(&config, "backup", request).unwrap();

config.basic_auth = Some(("backup".to_owned(), Some(backup_passphrase.to_owned())));

let backup = default_api::system_backup_post(&config).unwrap().entity;

(keys, backup)
})
.await;

let restored_keys = utils::with_container(|mut config| {
let state = default_api::health_state_get(&config).unwrap().entity.state;
assert_eq!(state, SystemState::Unprovisioned);

let request = RestoreRequestArguments {
backup_passphrase: Some(backup_passphrase.to_owned()),
system_time: Some(Utc::now().to_rfc3339()),
};
default_api::system_restore_post(&config, Some(request), Some(backup)).unwrap();

let state = default_api::health_state_get(&config).unwrap().entity.state;
assert_eq!(state, SystemState::Locked);

let request = UnlockRequestData {
passphrase: unlock_passphrase.to_owned(),
};
default_api::unlock_post(&config, request).unwrap();

config.basic_auth = Some(("admin".to_owned(), Some(admin_passphrase.to_owned())));

list_keys(&config)
})
.await;

assert_eq!(generated_keys, restored_keys);
}

fn list_keys(config: &Configuration) -> BTreeSet<String> {
default_api::keys_get(&config, None)
.unwrap()
.entity
.into_iter()
.map(|item| item.id)
.collect()
}

0 comments on commit c7cbe7b

Please sign in to comment.