Skip to content

Commit 21418bf

Browse files
committed
Slightly simplified SealedData and ImportData types, by making the enum variants private.
1 parent 44479f5 commit 21418bf

5 files changed

Lines changed: 35 additions & 41 deletions

File tree

Cargo.lock

Lines changed: 2 additions & 2 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

src/context.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -7,8 +7,8 @@
77
use std::{ffi::c_char, fmt::Display, num::NonZeroUsize, os::raw::c_void, ptr, sync::RwLock};
88

99
use crate::{
10-
BaseErrorCode, BlobType, ErrorCode, FapiCallbacks, ImportData, InternalError, KeyFlags, NvFlags, PaddingFlags, QuoteFlags, QuoteResult, SealData,
11-
SealFlags, SignResult, TpmBlobs,
10+
BaseErrorCode, BlobType, ErrorCode, FapiCallbacks, ImportData, InternalError, KeyFlags, NvFlags, PaddingFlags, QuoteFlags, QuoteResult, SealFlags,
11+
SealedData, SignResult, TpmBlobs,
1212
callback::{CallbackManager, entry_point},
1313
fapi_sys::{self, FAPI_CONTEXT, TPM2_RC, TSS2_RC, constants::TSS2_RC_SUCCESS},
1414
flags::Flags,
@@ -716,7 +716,7 @@ impl FapiContext {
716716
seal_type: Option<&[SealFlags]>,
717717
pol_path: Option<&str>,
718718
auth_val: Option<&str>,
719-
data: SealData,
719+
data: SealedData,
720720
) -> Result<(), ErrorCode> {
721721
fail_if_opt_empty!(seal_type);
722722

src/lib.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -446,7 +446,7 @@ pub use callback::{AuthCbParam, BranchCbParam, Callbacks, Cancelled, CbResult, F
446446
pub use context::FapiContext;
447447
pub use error::{BaseErrorCode, ErrorCode, InternalError, Tpm2ErrFmt0, Tpm2ErrFmt1, Tpm2ErrorCode, Tpm2Warning};
448448
pub use flags::{BlobType, KeyFlags, NvFlags, PaddingFlags, QuoteFlags, SealFlags};
449-
pub use types::{ImportData, QuoteResult, SealData, SignResult, TpmBlobs};
449+
pub use types::{ImportData, QuoteResult, SealedData, SignResult, TpmBlobs};
450450
pub use version::{FapiVersion, VersionInfo, get_version};
451451

452452
// Re-export JSON module

src/types.rs

Lines changed: 25 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -34,20 +34,18 @@ macro_rules! opt_check {
3434
// Import Data
3535
// ==========================================================================
3636

37-
/// Variant that holds the actual import data
37+
/// Data to be imported, either a [`&JsonValue`](json::JsonValue) or a PEM encoded [`&str`](core::primitive::str).
38+
///
39+
/// Instances of this struct may be used with the [`FapiContext::import()`](crate::FapiContext::import) function.
3840
#[derive(Clone, Copy, Debug)]
3941
#[non_exhaustive]
40-
enum ImportVariant<'a> {
42+
pub enum ImportData<'a> {
43+
#[non_exhaustive]
4144
Pem(&'a str),
45+
#[non_exhaustive]
4246
Json(&'a JsonValue),
4347
}
4448

45-
/// Data to be imported, either a [`&JsonValue`](json::JsonValue) or a PEM encoded [`&str`](core::primitive::str).
46-
///
47-
/// Instances of this struct may be used with the [`FapiContext::import()`](crate::FapiContext::import) function.
48-
#[derive(Clone, Copy, Debug)]
49-
pub struct ImportData<'a>(ImportVariant<'a>);
50-
5149
impl<'a> ImportData<'a> {
5250
/// Attempts to create a new `ImportData` from the given `JsonValue` reference.
5351
///
@@ -56,7 +54,7 @@ impl<'a> ImportData<'a> {
5654
/// The JSON data will be validated, by the FAPI, when it is actually used.
5755
pub fn from_json(json_value: &'a JsonValue) -> Result<Self, ErrorCode> {
5856
if json_value.is_object() && (!json_value.is_empty()) {
59-
Ok(Self(ImportVariant::Json(json_value)))
57+
Ok(Self::Json(json_value))
6058
} else {
6159
Err(ErrorCode::InternalError(InternalError::InvalidArguments))
6260
}
@@ -73,7 +71,7 @@ impl<'a> ImportData<'a> {
7371
|| pem_data.starts_with("-----BEGIN RSA PRIVATE KEY-----")
7472
|| pem_data.starts_with("-----BEGIN EC PRIVATE KEY-----")
7573
{
76-
Ok(Self(ImportVariant::Pem(pem_data)))
74+
Ok(Self::Pem(pem_data))
7775
} else {
7876
Err(ERR_INVALID_ARGUMENTS)
7977
}
@@ -84,9 +82,9 @@ impl TryFrom<ImportData<'_>> for CStringHolder {
8482
type Error = ErrorCode;
8583

8684
fn try_from(data: ImportData) -> Result<Self, Self::Error> {
87-
match data.0 {
88-
ImportVariant::Json(json_value) => CStringHolder::try_from(json_value),
89-
ImportVariant::Pem(pem_data) => CStringHolder::try_from(pem_data),
85+
match data {
86+
ImportData::Json(json_value) => CStringHolder::try_from(json_value),
87+
ImportData::Pem(pem_data) => CStringHolder::try_from(pem_data),
9088
}
9189
}
9290
}
@@ -95,43 +93,40 @@ impl TryFrom<ImportData<'_>> for CStringHolder {
9593
// Seal Data
9694
// ==========================================================================
9795

98-
/// Variant that holds the actual seal data
99-
#[derive(Clone, Copy, Debug)]
100-
#[non_exhaustive]
101-
enum SealVariant<'a> {
102-
Size(NonZeroUsize),
103-
Data(&'a [u8]),
104-
}
105-
106-
/// The size of the sealed object and, optionally, the initial data
96+
/// The size of the sealed object and, optionally, the initial data.
10797
pub type RawSealInfo = (NonZeroUsize, CBinaryHolder);
10898

10999
/// Data to be sealed, either a non-zero size or some explicit data.
110100
///
111101
/// Instances of this struct may be used with the [`FapiContext::create_seal()`](crate::FapiContext::create_seal) function.
112102
#[derive(Clone, Copy, Debug)]
113-
pub struct SealData<'a>(SealVariant<'a>);
103+
#[non_exhaustive]
104+
pub enum SealedData<'a> {
105+
#[non_exhaustive]
106+
Data(&'a [u8]),
107+
Size(NonZeroUsize),
108+
}
114109

115-
impl<'a> SealData<'a> {
110+
impl<'a> SealedData<'a> {
116111
/// Creates a new `SealData` with the specified non-zero size.
117112
///
118113
/// The new sealed object will be created with the specified size and will be initialized by the TPM with random data.
119-
pub fn from_size(size: NonZeroUsize) -> Self {
120-
Self(SealVariant::Size(size))
114+
pub fn from_size(size: usize) -> Result<Self, ErrorCode> {
115+
Ok(Self::Size(NonZeroUsize::new(size).ok_or(ERR_INVALID_ARGUMENTS)?))
121116
}
122117

123118
/// Creates a new `SealData` containing the specified data.
124119
///
125120
/// The new sealed object will be created with a size of `data.len()` and it will be initialized with the given data.
126121
pub fn from_data(data: &'a [u8]) -> Result<Self, ErrorCode> {
127-
if !data.is_empty() { Ok(Self(SealVariant::Data(data))) } else { Err(ERR_INVALID_ARGUMENTS) }
122+
if !data.is_empty() { Ok(Self::Data(data)) } else { Err(ERR_INVALID_ARGUMENTS) }
128123
}
129124

130125
/// Returns the actual seal size and the associated data (if any)
131126
pub(crate) fn into_raw_data(self) -> Result<RawSealInfo, ErrorCode> {
132-
match self.0 {
133-
SealVariant::Size(size) => Ok((size, CBinaryHolder::empty())),
134-
SealVariant::Data(data) => {
127+
match self {
128+
Self::Size(size) => Ok((size, CBinaryHolder::empty())),
129+
Self::Data(data) => {
135130
let cstr_data = CBinaryHolder::try_from(data)?;
136131
let cstr_size = NonZeroUsize::new(cstr_data.len()).expect("Size must not be zero!");
137132
Ok((cstr_size, cstr_data))

tests/10_sealed_object_test.rs

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -18,8 +18,7 @@ use log::debug;
1818
use rand::SeedableRng;
1919
use rand_chacha::ChaChaRng;
2020
use serial_test::serial;
21-
use std::num::NonZeroUsize;
22-
use tss2_fapi_rs::{FapiContext, SealData, SealFlags};
21+
use tss2_fapi_rs::{FapiContext, SealFlags, SealedData};
2322

2423
const SEAL_TYPE_FLAGS: &[SealFlags] = &[SealFlags::NoDA];
2524

@@ -47,7 +46,7 @@ fn test_create_seal_random() {
4746
tpm_initialize!(context, PASSWORD, MyCallbacks::new(PASSWORD, None));
4847

4948
// Create new seal, if not already created
50-
match context.create_seal(key_path, Some(SEAL_TYPE_FLAGS), None, None, SealData::from_size(NonZeroUsize::new(32usize).unwrap())) {
49+
match context.create_seal(key_path, Some(SEAL_TYPE_FLAGS), None, None, SealedData::from_size(32usize).unwrap()) {
5150
Ok(_) => debug!("Seal created."),
5251
Err(error) => panic!("Seal creation has failed: {:?}", error),
5352
}
@@ -80,7 +79,7 @@ fn test_create_seal_data() {
8079
let sealed_data: [u8; 32usize] = generate_bytes(&mut rng);
8180

8281
// Create new seal, if not already created
83-
match context.create_seal(key_path, Some(SEAL_TYPE_FLAGS), None, None, SealData::from_data(&sealed_data[..]).unwrap()) {
82+
match context.create_seal(key_path, Some(SEAL_TYPE_FLAGS), None, None, SealedData::from_data(&sealed_data[..]).unwrap()) {
8483
Ok(_) => debug!("Seal created."),
8584
Err(error) => panic!("Seal creation has failed: {:?}", error),
8685
}
@@ -113,7 +112,7 @@ fn test_unseal() {
113112
let original_data: [u8; 128usize] = generate_bytes(&mut rng);
114113

115114
// Create new seal, if not already created
116-
match context.create_seal(key_path, Some(SEAL_TYPE_FLAGS), None, None, SealData::from_data(&original_data[..]).unwrap()) {
115+
match context.create_seal(key_path, Some(SEAL_TYPE_FLAGS), None, None, SealedData::from_data(&original_data[..]).unwrap()) {
117116
Ok(_) => debug!("Seal created."),
118117
Err(error) => panic!("Seal creation has failed: {:?}", error),
119118
}

0 commit comments

Comments
 (0)