Skip to content

feat: add import/export API and cli #727

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions Cargo.lock

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

85 changes: 85 additions & 0 deletions manufacturing-server/src/handlers/mgmt.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
use std::fs::File;

use fdo_data_formats::types::Guid;

use std::io::prelude::*;
use std::io::Read;

#[derive(Debug)]
#[allow(dead_code)]
struct HandleOVFailure(anyhow::Error);
impl warp::reject::Reject for HandleOVFailure {}

pub(crate) async fn handler_ov(
guid: Guid,
udt: crate::ManufacturingServiceUDT,
) -> Result<impl warp::Reply, warp::Rejection> {
let ov_opt = udt
.ownership_voucher_store
.load_data(&guid)
.await
.map_err(|e| warp::reject::custom(HandleOVFailure(e.into())))?;
if ov_opt.is_none() {
return Err(warp::reject::not_found());
}
let ov_pem = ov_opt
.unwrap()
.to_pem()
.map_err(|e| warp::reject::custom(HandleOVFailure(e.into())))?;
Ok(warp::reply::with_header(
ov_pem,
"Content-Type",
warp::http::header::HeaderValue::from_static("application/x-pem-file"),
))
}

#[derive(Debug)]
#[allow(dead_code)]
struct ExportFailure(anyhow::Error);
impl warp::reject::Reject for ExportFailure {}

pub(crate) async fn handler_export(
udt: crate::ManufacturingServiceUDT,
) -> Result<impl warp::Reply, warp::Rejection> {
let ovs = udt
.ownership_voucher_store
.load_all_data()
.await
.map_err(|e| warp::reject::custom(ExportFailure(e.into())))?;
if ovs.is_empty() {
return Err(warp::reject::not_found());
}
let tmp_dir = tempfile::tempdir_in("manufacturer-server-ovs")
.map_err(|e| warp::reject::custom(ExportFailure(e.into())))?;
for ov in ovs {
let file_path = tmp_dir.path().join(ov.header().guid().to_string());
let mut tmp_file =
File::create(file_path).map_err(|e| warp::reject::custom(ExportFailure(e.into())))?;
tmp_file
.write_all(
ov.to_pem()
.map_err(|e| warp::reject::custom(ExportFailure(e.into())))?
.as_bytes(),
)
.map_err(|e| warp::reject::custom(ExportFailure(e.into())))?;
}
let tmp_dir_archive = tempfile::tempdir_in("manufacturer-server-ovs-archive")
.map_err(|e| warp::reject::custom(ExportFailure(e.into())))?;
let tar_gz = File::create(tmp_dir_archive.path().join("ovs.tar.gz"))
.map_err(|e| warp::reject::custom(ExportFailure(e.into())))?;
let mut tar = tar::Builder::new(tar_gz);
tar.append_dir_all(".", tmp_dir)
.map_err(|e| warp::reject::custom(ExportFailure(e.into())))?;
tar.finish()
.map_err(|e| warp::reject::custom(ExportFailure(e.into())))?;
let mut file = File::open(tmp_dir_archive.path().join("ovs.tar.gz"))
.map_err(|e| warp::reject::custom(ExportFailure(e.into())))?;
let mut data: Vec<u8> = Vec::new();
file.read_to_end(&mut data)
.map_err(|e| warp::reject::custom(ExportFailure(e.into())))?;
Ok(warp::reply::with_header(
data,
"Content-Type",
warp::http::header::HeaderValue::from_static("application/x-tar"),
))
}
1 change: 1 addition & 0 deletions manufacturing-server/src/handlers/mod.rs
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
pub(super) mod di;
pub(super) mod diun;
pub(super) mod mgmt;
107 changes: 12 additions & 95 deletions manufacturing-server/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,31 +1,29 @@
use std::collections::BTreeMap;
use std::convert::{TryFrom, TryInto};
use std::fs::{self, File};
use std::io::Read;
use std::fs;

use std::str::FromStr;
use std::sync::Arc;

use fdo_data_formats::{constants::ErrorCode, ProtocolVersion};
use fdo_data_formats::ProtocolVersion;
use fdo_store::Store;

use warp::{Filter, Rejection};
use handlers::mgmt;
use warp::Filter;

use anyhow::{bail, Context, Error, Result};
use openssl::{
pkey::{PKey, Private},
x509::X509,
};
use serde_yaml::Value;
use tempfile::TempDir;
use tokio::signal::unix::{signal, SignalKind};
use warp::reply::Response;

use fdo_data_formats::{
constants::{KeyStorageType, MfgStringType, PublicKeyType, RendezvousVariable},
ownershipvoucher::OwnershipVoucher,
publickey::{PublicKey, X5Chain},
types::{Guid, RendezvousInfo},
Serializable,
};
use fdo_util::servers::{
configuration::manufacturing_server::{DiunSettings, ManufacturingServerSettings},
Expand Down Expand Up @@ -275,97 +273,16 @@ async fn main() -> Result<()> {
// Initialize handlers
let hello = warp::path::end().map(|| "Hello from the manufacturing server");
let ud = user_data.clone();
let handler_ovs = warp::path!("ov" / String)
let handler_ovs = warp::path!("ov" / Guid)
.map(move |guid| (guid, ud.clone()))
.and_then(
|(guid, ud): (String, Arc<ManufacturingServiceUD>)| async move {
let typed_guid = match Guid::from_str(&guid) {
Ok(v) => v,
Err(e) => {
return Err(Rejection::from(fdo_http_wrapper::server::Error::new(
ErrorCode::InternalServerError,
fdo_data_formats::constants::MessageType::Invalid,
&e.to_string(),
)))
}
};
let ov = match ud.ownership_voucher_store.load_data(&typed_guid).await {
Ok(ov) => ov.unwrap(),
Err(e) => {
return Err(Rejection::from(fdo_http_wrapper::server::Error::new(
ErrorCode::InternalServerError,
fdo_data_formats::constants::MessageType::Invalid,
&format!("Error loading ownership voucher with guid {}: {}", guid, e),
)))
}
};
let ov_pem = match ov.to_pem() {
Ok(v) => v,
Err(e) => {
return Err(Rejection::from(fdo_http_wrapper::server::Error::new(
ErrorCode::InternalServerError,
fdo_data_formats::constants::MessageType::Invalid,
&format!("Error converting ownership voucher to pem: {}", e),
)))
}
};
let mut res = Response::new(ov_pem.into());
res.headers_mut().insert(
"Content-Type",
warp::http::header::HeaderValue::from_static("application/x-pem-file"),
);
Ok(res)
},
);
.untuple_one()
.and_then(mgmt::handler_ov);

let ud = user_data.clone();
let handler_export = warp::post()
.and(warp::path("export").map(move || (ud.clone())).and_then(
|ud: Arc<ManufacturingServiceUD>| async move {
match ud.ownership_voucher_store.load_all_data().await {
Ok(ovs) => Ok(ovs),
Err(_) => Err(Rejection::from(fdo_http_wrapper::server::Error::new(
ErrorCode::InternalServerError,
fdo_data_formats::constants::MessageType::Invalid,
"Error loading ownership vouchers",
))),
}
},
))
.map(|ovs: Vec<OwnershipVoucher>| {
if ovs.is_empty() {
let mut res = Response::new("".into());
*res.status_mut() = warp::http::StatusCode::NOT_FOUND;
return res;
}
let tmp_dir = TempDir::with_prefix("manufacturer-server-ovs").unwrap();
for ov in ovs {
let file_path = tmp_dir.path().join(ov.header().guid().to_string());
let tmp_file = File::create(file_path).unwrap();
OwnershipVoucher::serialize_to_writer(&ov, &tmp_file).unwrap();
}
let tmp_dir_archive = TempDir::with_prefix("manufacturer-server-ovs-archive").unwrap();
let tar_gz = File::create(tmp_dir_archive.path().join("ovs.tar.gz")).unwrap();
let mut tar = tar::Builder::new(tar_gz);
tar.append_dir_all(".", tmp_dir).unwrap();
tar.finish().unwrap();
let mut file = File::open(tmp_dir_archive.path().join("ovs.tar.gz")).unwrap();
let mut data: Vec<u8> = Vec::new();
match file.read_to_end(&mut data) {
Err(why) => {
let mut res = Response::new(why.to_string().into());
*res.status_mut() = warp::http::StatusCode::INTERNAL_SERVER_ERROR;
res
}
Ok(_) => {
let mut res = Response::new(data.into());
res.headers_mut().insert(
"Content-Type",
warp::http::header::HeaderValue::from_static("application/x-tar"),
);
res
}
}
});
.and(warp::path("export"))
.map(move || (ud.clone()))
.and_then(mgmt::handler_export);

// DI
let handler_di_app_start = fdo_http_wrapper::server::fdo_request_filter(
Expand Down
1 change: 1 addition & 0 deletions owner-onboarding-server/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ log = "0.4"
serde_yaml = "0.9"
time = "0.3"
hex = "0.4"
bytes = "1.8.0"

fdo-data-formats = { path = "../data-formats", version = "0.5.2" }
fdo-http-wrapper = { path = "../http-wrapper", version = "0.5.2", features = ["server", "client"] }
Expand Down
24 changes: 24 additions & 0 deletions owner-onboarding-server/src/handlers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ use std::{collections::HashSet, str::FromStr};
use fdo_data_formats::{
constants::{DeviceSigType, ErrorCode, HeaderKeys},
messages::Message,
ownershipvoucher::OwnershipVoucher,
types::{
COSEHeaderMap, COSESign, CipherSuite, Guid, KeyDeriveSide, KeyExchange, Nonce,
RendezvousInfo, SigInfo, TO2ProveDevicePayload, TO2ProveOVHdrPayload,
Expand Down Expand Up @@ -680,3 +681,26 @@ pub(crate) async fn report_to_rendezvous_handler(
.map_err(|e| warp::reject::custom(RtrFailure(e)))?;
Ok(warp::reply::Response::new("ok".into()))
}

#[derive(Debug)]
#[allow(dead_code)]
struct ImportFailure(anyhow::Error);
impl warp::reject::Reject for ImportFailure {}

pub(crate) async fn handler_import(
udt: crate::OwnerServiceUDT,
bytes: bytes::Bytes,
) -> Result<impl warp::Reply, warp::Rejection> {
let ovs = OwnershipVoucher::many_from_pem(&bytes)
.map_err(|e| warp::reject::custom(ImportFailure(e.into())))?;
log::info!("Importing {} ownership voucher(s)", ovs.len());
// TODO(runcom): handler this better in case only partial import is done
for ov in ovs {
let guid = ov.header().guid().clone();
udt.ownership_voucher_store
.store_data(guid, ov)
.await
.map_err(|e| warp::reject::custom(ImportFailure(e.into())))?;
}
Ok(warp::reply::Response::new("ok".into()))
}
10 changes: 10 additions & 0 deletions owner-onboarding-server/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -547,6 +547,15 @@ async fn main() -> Result<()> {
let hello = warp::get().map(|| "Hello from the owner onboarding service");
let handler_ping = fdo_http_wrapper::server::ping_handler();

let ud = user_data.clone();
let handler_import = warp::post()
.and(warp::path("import"))
.and(warp::body::content_length_limit(1024 * 16))
.and(warp::body::bytes())
.map(move |bytes: bytes::Bytes| (ud.clone(), bytes))
.untuple_one()
.and_then(handlers::handler_import);

// TO2
let handler_to2_hello_device = fdo_http_wrapper::server::fdo_request_filter(
ProtocolVersion::Version1_1,
Expand Down Expand Up @@ -606,6 +615,7 @@ async fn main() -> Result<()> {
.or(handler_to2_device_service_info)
.or(handler_to2_done),
)
.or(handler_import) // TODO(runcom): needs authentication with API key at least!
.recover(fdo_http_wrapper::server::handle_rejection)
.with(warp::log("owner-onboarding-service"));

Expand Down
Loading
Loading