Skip to content

Commit d17e475

Browse files
committed
Builder pattern for IO
1 parent 1b361ee commit d17e475

File tree

10 files changed

+64
-58
lines changed

10 files changed

+64
-58
lines changed

intel-sgx/dcap-artifact-retrieval/src/cli.rs

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88
use std::path::{Path, PathBuf};
99

1010
use clap::clap_app;
11-
use pcs::{PckID, DcapArtifactIssuer, WriteOption};
11+
use pcs::{PckID, DcapArtifactIssuer, WriteOptionsBuilder};
1212
use reqwest::Url;
1313
use rustc_serialize::hex::ToHex;
1414
use serde::de::{value, IntoDeserializer};
@@ -72,7 +72,7 @@ fn download_dcap_artifacts(
7272
// instead we mimic it using pckcert API.
7373
let pckcerts = prov_client.pckcerts_with_fallback(&pckid)?;
7474

75-
let pckcerts_file = pckcerts.store(output_dir, pckid.qe_id.as_slice(), WriteOption { overwrite: true })?;
75+
let pckcerts_file = pckcerts.store(output_dir, pckid.qe_id.as_slice(), WriteOptionsBuilder::new().build())?;
7676

7777
if verbose {
7878
println!(" pckcerts: {}", pckcerts_file.unwrap().display());
@@ -82,7 +82,7 @@ fn download_dcap_artifacts(
8282
let evaluation_data_numbers = prov_client
8383
.tcb_evaluation_data_numbers()?;
8484

85-
let file = evaluation_data_numbers.write_to_file(output_dir, WriteOption { overwrite: true })?;
85+
let file = evaluation_data_numbers.write_to_file(output_dir, WriteOptionsBuilder::new().build())?;
8686
if verbose {
8787
println!(" tcb evaluation data numbers: {}\n", file.unwrap().display());
8888
}
@@ -93,7 +93,7 @@ fn download_dcap_artifacts(
9393

9494
match tcb_info {
9595
Ok(tcb_info) => {
96-
let file = tcb_info.store(output_dir, WriteOption { overwrite: true })?;
96+
let file = tcb_info.store(output_dir, WriteOptionsBuilder::new().build())?;
9797
if verbose {
9898
println!(" tcb info: {}", file.unwrap().display());
9999
}
@@ -114,7 +114,7 @@ fn download_dcap_artifacts(
114114

115115
match qe_identity {
116116
Ok(qe_identity) => {
117-
let file = qe_identity.write_to_file(output_dir, WriteOption { overwrite: true })?;
117+
let file = qe_identity.write_to_file(output_dir, WriteOptionsBuilder::new().build())?;
118118
if verbose {
119119
println!(" qe identity: {}\n", file.unwrap().display());
120120
}
@@ -132,15 +132,15 @@ fn download_dcap_artifacts(
132132
}
133133
let pckcrl = prov_client
134134
.pckcrl(DcapArtifactIssuer::PCKProcessorCA)
135-
.and_then(|crl| crl.write_to_file_as(output_dir, DcapArtifactIssuer::PCKProcessorCA, WriteOption { overwrite: true }).map_err(|e| e.into()))?;
135+
.and_then(|crl| crl.write_to_file_as(output_dir, DcapArtifactIssuer::PCKProcessorCA, WriteOptionsBuilder::new().build()).map_err(|e| e.into()))?;
136136
if verbose {
137137
println!("==[ generic ]==");
138138
println!(" PCKProcessorCA Crl: {}", pckcrl.unwrap().display());
139139
}
140140

141141
let pckcrl = prov_client
142142
.pckcrl(DcapArtifactIssuer::PCKPlatformCA)
143-
.and_then(|crl| crl.write_to_file_as(output_dir, DcapArtifactIssuer::PCKPlatformCA, WriteOption { overwrite: true }).map_err(|e| e.into()))?;
143+
.and_then(|crl| crl.write_to_file_as(output_dir, DcapArtifactIssuer::PCKPlatformCA, WriteOptionsBuilder::new().build()).map_err(|e| e.into()))?;
144144
if verbose {
145145
println!(" PCKPlatformCA Crl: {}", pckcrl.unwrap().display());
146146
}

intel-sgx/dcap-artifact-retrieval/src/provisioning_client/intel.rs

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -591,7 +591,7 @@ mod tests {
591591

592592
use pcs::{
593593
DcapArtifactIssuer, EnclaveIdentity, Fmspc, PckID, Platform, RawTcbEvaluationDataNumbers,
594-
TcbEvaluationDataNumbers, WriteOption,
594+
TcbEvaluationDataNumbers, WriteOptionsBuilder,
595595
};
596596

597597
use crate::provisioning_client::{
@@ -640,7 +640,7 @@ mod tests {
640640
"Intel SGX Root CA"
641641
);
642642
pcks.fmspc().unwrap();
643-
pcks.store(OUTPUT_TEST_DIR, pckid.qe_id.as_slice(), WriteOption { overwrite: true }).unwrap();
643+
pcks.store(OUTPUT_TEST_DIR, pckid.qe_id.as_slice(), WriteOptionsBuilder::new().build()).unwrap();
644644
}
645645
}
646646
}
@@ -870,7 +870,7 @@ mod tests {
870870
.unwrap();
871871
assert!(client
872872
.tcbinfo(&pckcerts.fmspc().unwrap(), None)
873-
.and_then(|tcb| { Ok(tcb.store(OUTPUT_TEST_DIR, WriteOption { overwrite: true }).unwrap()) })
873+
.and_then(|tcb| { Ok(tcb.store(OUTPUT_TEST_DIR, WriteOptionsBuilder::new().build()).unwrap()) })
874874
.is_ok());
875875
}
876876
}
@@ -942,7 +942,7 @@ mod tests {
942942
Err(super::Error::PCSError(status_code, _)) if status_code == super::StatusCode::Gone => continue,
943943
res @Err(_) => res.unwrap(),
944944
};
945-
tcb.store(OUTPUT_TEST_DIR, WriteOption { overwrite: true }).unwrap();
945+
tcb.store(OUTPUT_TEST_DIR, WriteOptionsBuilder::new().build()).unwrap();
946946
}
947947
}
948948
}
@@ -1024,7 +1024,7 @@ mod tests {
10241024
let client = intel_builder.build(reqwest_client());
10251025
assert!(client
10261026
.pckcrl(ca)
1027-
.and_then(|crl| { Ok(crl.write_to_file(OUTPUT_TEST_DIR, WriteOption { overwrite: true }).unwrap()) })
1027+
.and_then(|crl| { Ok(crl.write_to_file(OUTPUT_TEST_DIR, WriteOptionsBuilder::new().build()).unwrap()) })
10281028
.is_ok());
10291029
}
10301030
}
@@ -1096,7 +1096,7 @@ mod tests {
10961096
let client = intel_builder.build(reqwest_client());
10971097
let qe_id = client.qe_identity(None).unwrap();
10981098
assert_eq!(qe_id.enclave_type(), EnclaveIdentity::QE);
1099-
assert!(qe_id.write_to_file(OUTPUT_TEST_DIR, WriteOption { overwrite: true }).is_ok());
1099+
assert!(qe_id.write_to_file(OUTPUT_TEST_DIR, WriteOptionsBuilder::new().build()).is_ok());
11001100
}
11011101
}
11021102

@@ -1108,7 +1108,7 @@ mod tests {
11081108
let client = intel_builder.build(reqwest_client());
11091109
let qe_id = client.tdqe_identity(None).unwrap();
11101110
assert_eq!(qe_id.enclave_type(), EnclaveIdentity::TDQE);
1111-
assert!(qe_id.write_to_file(OUTPUT_TEST_DIR, WriteOption { overwrite: true }).is_ok());
1111+
assert!(qe_id.write_to_file(OUTPUT_TEST_DIR, WriteOptionsBuilder::new().build()).is_ok());
11121112
}
11131113

11141114
#[test]

intel-sgx/dcap-artifact-retrieval/src/provisioning_client/pccs.rs

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -441,7 +441,7 @@ mod tests {
441441

442442
use pcs::{
443443
EnclaveIdentity, Fmspc, PckID, Platform, RawTcbEvaluationDataNumbers,
444-
TcbEvaluationDataNumbers, WriteOption,
444+
TcbEvaluationDataNumbers, WriteOptionsBuilder,
445445
};
446446

447447
use super::Client;
@@ -633,7 +633,7 @@ mod tests {
633633

634634
assert!(client
635635
.tcbinfo(&pckcerts.fmspc().unwrap(), None)
636-
.and_then(|tcb| { Ok(tcb.store(OUTPUT_TEST_DIR, WriteOption { overwrite: true }).unwrap()) })
636+
.and_then(|tcb| { Ok(tcb.store(OUTPUT_TEST_DIR, WriteOptionsBuilder::new().build()).unwrap()) })
637637
.is_ok());
638638
}
639639
}
@@ -676,7 +676,7 @@ mod tests {
676676
Err(super::Error::PCSError(status_code, _)) if status_code == super::StatusCode::Gone => continue,
677677
res @Err(_) => res.unwrap(),
678678
};
679-
tcb.store(OUTPUT_TEST_DIR, WriteOption { overwrite: true }).unwrap();
679+
tcb.store(OUTPUT_TEST_DIR, WriteOptionsBuilder::new().build()).unwrap();
680680
}
681681
}
682682
}
@@ -731,11 +731,11 @@ mod tests {
731731
let client = make_client(api_version);
732732
assert!(client
733733
.pckcrl(DcapArtifactIssuer::PCKProcessorCA)
734-
.and_then(|crl| Ok(crl.write_to_file(OUTPUT_TEST_DIR, WriteOption { overwrite: true }).unwrap()))
734+
.and_then(|crl| Ok(crl.write_to_file(OUTPUT_TEST_DIR, WriteOptionsBuilder::new().build()).unwrap()))
735735
.is_ok());
736736
assert!(client
737737
.pckcrl(DcapArtifactIssuer::PCKPlatformCA)
738-
.and_then(|crl| Ok(crl.write_to_file(OUTPUT_TEST_DIR, WriteOption { overwrite: true }).unwrap()))
738+
.and_then(|crl| Ok(crl.write_to_file(OUTPUT_TEST_DIR, WriteOptionsBuilder::new().build()).unwrap()))
739739
.is_ok());
740740
}
741741
}
@@ -784,7 +784,7 @@ mod tests {
784784
let client = make_client(api_version);
785785
let qe_id = client.qe_identity(None);
786786
assert!(qe_id.is_ok());
787-
assert!(qe_id.unwrap().write_to_file(OUTPUT_TEST_DIR, WriteOption { overwrite: true }).is_ok());
787+
assert!(qe_id.unwrap().write_to_file(OUTPUT_TEST_DIR, WriteOptionsBuilder::new().build()).is_ok());
788788
}
789789
}
790790

intel-sgx/pcs/src/io.rs

Lines changed: 29 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -13,41 +13,47 @@ use serde::de::DeserializeOwned;
1313

1414
use crate::Error;
1515

16-
pub struct WriteOption {
17-
pub overwrite: bool
16+
17+
pub struct WriteOptions {
18+
no_overwrite: bool,
19+
}
20+
21+
pub struct WriteOptionsBuilder {
22+
no_overwrite: bool,
1823
}
1924

20-
/// Write given object in json to given filename under given dir (override existing file).
21-
pub fn write_to_file<T: serde::ser::Serialize>(obj: &T, dir: &str, filename: &str, options: WriteOption) -> Result<Option<PathBuf>, Error> {
25+
impl WriteOptionsBuilder {
26+
pub fn new() -> Self {
27+
Self {
28+
no_overwrite: false
29+
}
30+
}
31+
32+
pub fn disallow_overwrite(mut self) -> Self {
33+
self.no_overwrite = true;
34+
self
35+
}
36+
37+
pub fn build(self) -> WriteOptions {
38+
WriteOptions {
39+
no_overwrite : self.no_overwrite,
40+
}
41+
}
42+
}
43+
44+
/// Write given object in json to given filename under given dir.
45+
pub fn write_to_file<T: serde::ser::Serialize>(obj: &T, dir: &str, filename: &str, options: WriteOptions) -> Result<Option<PathBuf>, Error> {
2246
let path = Path::new(dir);
2347
let path = path.join(filename);
2448

25-
if !options.overwrite && path.exists() {
49+
if options.no_overwrite && path.exists() {
2650
return Ok(None)
2751
}
2852

2953
write_to_path(&path, obj)?;
3054
Ok(Some(path))
3155
}
3256

33-
/// Write given object in json to given filename under given dir if file is not exist.
34-
///
35-
/// - Returns `Ok(None)` if file already exist.
36-
/// - Returns `Ok(Some(filename))` if succeed to write to new file.
37-
// pub fn write_to_file_if_not_exist<T: serde::ser::Serialize>(
38-
// obj: &T,
39-
// dir: &str,
40-
// filename: &str,
41-
// ) -> Result<Option<PathBuf>, Error> {
42-
// let path = Path::new(dir);
43-
// let path = path.join(filename);
44-
// if path.exists() {
45-
// return Ok(None);
46-
// }
47-
// write_to_path(&path, obj)?;
48-
// Ok(Some(path))
49-
// }
50-
5157
fn write_to_path<T: serde::ser::Serialize>(path: &PathBuf, obj: &T) -> Result<(), Error> {
5258
let mut fp = File::create(&path)?;
5359

intel-sgx/pcs/src/lib.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@ pub use crate::pckcrt::{PckCert, PckCerts, SGXPCKCertificateExtension, SGXType,
3232
pub use crate::qe_identity::{EnclaveIdentity, QeIdentity, QeIdentitySigned};
3333
pub use crate::tcb_info::{AdvisoryID, Fmspc, TcbInfo, TcbData, TcbLevel, TdxModule, TdxModuleIdentity, TdxModuleTcbLevel, TdxModuleTcbLevelIsvSvn, PlatformTypeForTcbInfo};
3434
pub use crate::tcb_evaluation_data_numbers::{RawTcbEvaluationDataNumbers, TcbEvalNumber, TcbEvaluationDataNumbers, TcbPolicy};
35-
pub use crate::io::WriteOption;
35+
pub use crate::io::{WriteOptions, WriteOptionsBuilder};
3636

3737
mod io;
3838
mod iso8601;

intel-sgx/pcs/src/pckcrl.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ use {
1919
};
2020

2121

22-
use crate::io::WriteOption;
22+
use crate::io::WriteOptions;
2323
use crate::io::{self};
2424
use crate::{DcapArtifactIssuer, Error, Unverified, VerificationType, Verified};
2525

@@ -118,12 +118,12 @@ impl<V: VerificationType> PckCrl<V> {
118118
}
119119

120120
#[cfg(feature = "verify")]
121-
pub fn write_to_file(&self, output_dir: &str, option: WriteOption) -> Result<Option<PathBuf>, Error> {
121+
pub fn write_to_file(&self, output_dir: &str, option: WriteOptions) -> Result<Option<PathBuf>, Error> {
122122
let filename = self.filename()?;
123123
io::write_to_file(&self, output_dir, &filename, option)
124124
}
125125

126-
pub fn write_to_file_as(&self, output_dir: &str, ca: DcapArtifactIssuer, option: WriteOption) -> Result<Option<PathBuf>, Error> {
126+
pub fn write_to_file_as(&self, output_dir: &str, ca: DcapArtifactIssuer, option: WriteOptions) -> Result<Option<PathBuf>, Error> {
127127
let filename = Self::filename_from_ca(ca);
128128
io::write_to_file(&self, output_dir, &filename, option)
129129
}

intel-sgx/pcs/src/pckcrt.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@ use {
3232
super::{DcapArtifactIssuer, PckCrl},
3333
};
3434

35-
use crate::io::{self, WriteOption};
35+
use crate::io::{self, WriteOptions};
3636
use crate::tcb_info::{Fmspc, TcbData, TcbLevel};
3737
use crate::{CpuSvn, Error, Unverified, VerificationType, Verified, platform};
3838

@@ -502,7 +502,7 @@ impl PckCerts {
502502
format!("{}.certs", base16::encode_lower(qe_id))
503503
}
504504

505-
pub fn store(&self, output_dir: &str, qe_id: &[u8], option: WriteOption) -> Result<Option<PathBuf>, Error> {
505+
pub fn store(&self, output_dir: &str, qe_id: &[u8], option: WriteOptions) -> Result<Option<PathBuf>, Error> {
506506
let filename = PckCerts::filename(qe_id);
507507
io::write_to_file(&self, output_dir, &filename, option)
508508
}
@@ -724,7 +724,7 @@ impl<V: VerificationType> PckCert<V> {
724724
&self.cert
725725
}
726726

727-
pub fn write_to_file(&self, output_dir: &str, filename: &str, option: WriteOption) -> Result<Option<PathBuf>, Error> {
727+
pub fn write_to_file(&self, output_dir: &str, filename: &str, option: WriteOptions) -> Result<Option<PathBuf>, Error> {
728728
io::write_to_file(&self, output_dir, &filename, option)
729729
}
730730

intel-sgx/pcs/src/qe_identity.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ use {
2020
pkix::pem::PEM_CERTIFICATE, pkix::x509::GenericCertificate, pkix::FromBer, std::ops::Deref,
2121
};
2222

23-
use crate::io::{self, WriteOption};
23+
use crate::io::{self, WriteOptions};
2424
use crate::{Error, TcbStatus, Unverified, VerificationType, Verified};
2525

2626
#[derive(Serialize, Default, Deserialize, Clone, Debug, PartialEq, Eq)]
@@ -374,7 +374,7 @@ impl QeIdentitySigned {
374374
io::compose_filename(Self::filename_prefix(enclave_type), Self::FILENAME_EXTENSION, evaluation_data_number)
375375
}
376376

377-
pub fn write_to_file(&self, output_dir: &str, option: WriteOption) -> Result<Option<PathBuf>, Error> {
377+
pub fn write_to_file(&self, output_dir: &str, option: WriteOptions) -> Result<Option<PathBuf>, Error> {
378378
let id = QeIdentity::<Unverified>::try_from(self)?;
379379
let filename = Self::create_filename(&self.enclave_type, Some(id.tcb_evaluation_data_number));
380380
io::write_to_file(&self, output_dir, &filename, option)

intel-sgx/pcs/src/tcb_evaluation_data_numbers.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
use chrono::{DateTime, Duration, Utc};
2-
use crate::{EnclaveIdentity, Error, Fmspc, Platform, QeIdentity, QeIdentitySigned, TcbData, TcbInfo, TcbStatus, Unverified, VerificationType, Verified, io::{self, WriteOption}, pckcrt::TcbComponents, platform};
2+
use crate::{EnclaveIdentity, Error, Fmspc, Platform, QeIdentity, QeIdentitySigned, TcbData, TcbInfo, TcbStatus, Unverified, VerificationType, Verified, io::{self, WriteOptions}, pckcrt::TcbComponents, platform};
33
use serde::{Deserialize, Deserializer, Serialize};
44
use serde_json::value::RawValue;
55
use std::marker::PhantomData;
@@ -223,7 +223,7 @@ impl RawTcbEvaluationDataNumbers {
223223
&self.ca_chain
224224
}
225225

226-
pub fn write_to_file(&self, output_dir: &str, option: WriteOption) -> Result<Option<PathBuf>, Error> {
226+
pub fn write_to_file(&self, output_dir: &str, option: WriteOptions) -> Result<Option<PathBuf>, Error> {
227227
io::write_to_file(&self, output_dir, Self::DEFAULT_FILENAME, option)
228228
}
229229

intel-sgx/pcs/src/tcb_info.rs

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ use {
1919
pkix::pem::PEM_CERTIFICATE, pkix::x509::GenericCertificate, pkix::FromBer, std::ops::Deref,
2020
};
2121

22-
use crate::io::WriteOption;
22+
use crate::io::WriteOptions;
2323
use crate::pckcrt::PlatformTypeForTcbComponent;
2424
use crate::{PlatformType, pckcrt::{TcbComponent, TcbComponents}, platform};
2525
use crate::{io, CpuSvn, Error, PceIsvsvn, Platform, TcbStatus, Unverified, VerificationType, Verified};
@@ -612,7 +612,7 @@ impl<T: PlatformTypeForTcbInfo<T>> TcbInfo<T> {
612612
io::compose_filename(fmspc, file_extension.as_str(), evaluation_data_number)
613613
}
614614

615-
pub fn store(&self, output_dir: &str, option: WriteOption) -> Result<Option<PathBuf>, Error> {
615+
pub fn store(&self, output_dir: &str, option: WriteOptions) -> Result<Option<PathBuf>, Error> {
616616
let data = TcbData::<T, Unverified>::parse(&self.raw_tcb_info)?;
617617
let filename = Self::create_filename(&data.fmspc.to_string(), Some(data.tcb_evaluation_data_number));
618618
io::write_to_file(&self, output_dir, &filename, option)
@@ -750,7 +750,7 @@ mod tests {
750750
#[test]
751751
#[cfg(not(target_env = "sgx"))]
752752
fn read_tcb_info() {
753-
use crate::io::WriteOption;
753+
use crate::WriteOptionsBuilder;
754754

755755
let info =
756756
TcbInfo::<platform::SGX>::restore("./tests/data/", &Fmspc::try_from("00906ea10000").expect("static fmspc"), None).expect("validated");
@@ -766,7 +766,7 @@ mod tests {
766766
// Test serialization/deserialization
767767
let temp_dir = TempDir::new("tempdir").unwrap();
768768
let path = temp_dir.path().as_os_str().to_str().unwrap();
769-
info.store(&path, WriteOption { overwrite: true }).unwrap();
769+
info.store(&path, WriteOptionsBuilder::new().build()).unwrap();
770770
let info2 = TcbInfo::restore(&path, &Fmspc::try_from("00906ea10000").expect("static fmspc"), Some(8)).unwrap();
771771
assert_eq!(info, info2);
772772
}

0 commit comments

Comments
 (0)