Skip to content

Commit

Permalink
Adopt use_small_heuristics for google3 compatibility
Browse files Browse the repository at this point in the history
  • Loading branch information
brandonweeks committed Jan 27, 2025
1 parent 1e2020d commit dd8482f
Show file tree
Hide file tree
Showing 13 changed files with 121 additions and 344 deletions.
42 changes: 21 additions & 21 deletions native-pkcs11-core/src/attribute.rs
Original file line number Diff line number Diff line change
Expand Up @@ -286,18 +286,18 @@ impl TryFrom<CK_ATTRIBUTE> for Attribute {
AttributeType::AlwaysSensitive => {
Ok(Attribute::AlwaysSensitive(try_u8_into_bool(val)?))
}
AttributeType::Application => Ok(Attribute::Application(CString::from_vec_with_nul(
val.to_vec(),
)?)),
AttributeType::Application => {
Ok(Attribute::Application(CString::from_vec_with_nul(val.to_vec())?))
}
AttributeType::CertificateCategory => Ok(Attribute::CertificateCategory(
CK_CERTIFICATE_CATEGORY::from_ne_bytes(val.try_into()?),
)),
AttributeType::CertificateType => Ok(Attribute::CertificateType(
CK_CERTIFICATE_TYPE::from_ne_bytes(val.try_into()?),
)),
AttributeType::Class => Ok(Attribute::Class(CK_OBJECT_CLASS::from_ne_bytes(
val.try_into()?,
))),
AttributeType::CertificateType => {
Ok(Attribute::CertificateType(CK_CERTIFICATE_TYPE::from_ne_bytes(val.try_into()?)))
}
AttributeType::Class => {
Ok(Attribute::Class(CK_OBJECT_CLASS::from_ne_bytes(val.try_into()?)))
}
AttributeType::Coefficient => Ok(Attribute::Coefficient(val.to_vec())),
AttributeType::Decrypt => Ok(Attribute::Decrypt(try_u8_into_bool(val)?)),
AttributeType::Derive => Ok(Attribute::Derive(try_u8_into_bool(val)?)),
Expand All @@ -309,25 +309,25 @@ impl TryFrom<CK_ATTRIBUTE> for Attribute {
AttributeType::Extractable => Ok(Attribute::Extractable(try_u8_into_bool(val)?)),
AttributeType::Id => Ok(Attribute::Id(val.to_vec())),
AttributeType::Issuer => Ok(Attribute::Issuer(val.to_vec())),
AttributeType::KeyType => Ok(Attribute::KeyType(CK_KEY_TYPE::from_ne_bytes(
val.try_into()?,
))),
AttributeType::KeyType => {
Ok(Attribute::KeyType(CK_KEY_TYPE::from_ne_bytes(val.try_into()?)))
}
AttributeType::Label => Ok(Attribute::Label(String::from_utf8(val.to_vec())?)),
AttributeType::Local => Ok(Attribute::Local(try_u8_into_bool(val)?)),
AttributeType::Modulus => Ok(Attribute::Modulus(val.to_vec())),
AttributeType::ModulusBits => Ok(Attribute::ModulusBits(CK_ULONG::from_ne_bytes(
val.try_into()?,
))),
AttributeType::ModulusBits => {
Ok(Attribute::ModulusBits(CK_ULONG::from_ne_bytes(val.try_into()?)))
}
AttributeType::NeverExtractable => {
Ok(Attribute::NeverExtractable(try_u8_into_bool(val)?))
}
AttributeType::Prime1 => Ok(Attribute::Prime1(val.to_vec())),
AttributeType::Prime2 => Ok(Attribute::Prime2(val.to_vec())),
AttributeType::Private => Ok(Attribute::Private(try_u8_into_bool(val)?)),
AttributeType::PrivateExponent => Ok(Attribute::PrivateExponent(val.to_vec())),
AttributeType::ProfileId => Ok(Attribute::ProfileId(CK_ULONG::from_ne_bytes(
val.try_into()?,
))),
AttributeType::ProfileId => {
Ok(Attribute::ProfileId(CK_ULONG::from_ne_bytes(val.try_into()?)))
}
AttributeType::PublicExponent => Ok(Attribute::PublicExponent(val.to_vec())),
AttributeType::Sensitive => Ok(Attribute::Sensitive(try_u8_into_bool(val)?)),
AttributeType::SerialNumber => Ok(Attribute::SerialNumber(val.to_vec())),
Expand All @@ -338,9 +338,9 @@ impl TryFrom<CK_ATTRIBUTE> for Attribute {
AttributeType::Trusted => Ok(Attribute::Trusted(try_u8_into_bool(val)?)),
AttributeType::Unwrap => Ok(Attribute::Unwrap(try_u8_into_bool(val)?)),
AttributeType::Value => Ok(Attribute::Value(val.to_vec())),
AttributeType::ValueLen => Ok(Attribute::ValueLen(CK_ULONG::from_ne_bytes(
val.try_into()?,
))),
AttributeType::ValueLen => {
Ok(Attribute::ValueLen(CK_ULONG::from_ne_bytes(val.try_into()?)))
}
AttributeType::Verify => Ok(Attribute::Verify(try_u8_into_bool(val)?)),
AttributeType::VerifyRecover => Ok(Attribute::VerifyRecover(try_u8_into_bool(val)?)),
AttributeType::Wrap => Ok(Attribute::Wrap(try_u8_into_bool(val)?)),
Expand Down
16 changes: 7 additions & 9 deletions native-pkcs11-core/src/mechanism.rs
Original file line number Diff line number Diff line change
Expand Up @@ -133,15 +133,13 @@ impl From<Mechanism> for SignatureAlgorithm {
Mechanism::RsaPkcsSha256 => SignatureAlgorithm::RsaPkcs1v15Sha256,
Mechanism::RsaPkcsSha384 => SignatureAlgorithm::RsaPkcs1v15Sha384,
Mechanism::RsaPkcsSha512 => SignatureAlgorithm::RsaPkcs1v15Sha512,
Mechanism::RsaPss {
digest_algorithm,
mask_generation_function,
salt_length,
} => SignatureAlgorithm::RsaPss {
digest: digest_algorithm,
mask_generation_function,
salt_length,
},
Mechanism::RsaPss { digest_algorithm, mask_generation_function, salt_length } => {
SignatureAlgorithm::RsaPss {
digest: digest_algorithm,
mask_generation_function,
salt_length,
}
}
}
}
}
35 changes: 16 additions & 19 deletions native-pkcs11-core/src/object.rs
Original file line number Diff line number Diff line change
Expand Up @@ -78,9 +78,9 @@ impl Object {
pub fn attribute(&self, type_: AttributeType) -> Option<Attribute> {
match self {
Object::Certificate(cert) => match type_ {
AttributeType::CertificateCategory => Some(Attribute::CertificateCategory(
CK_CERTIFICATE_CATEGORY_UNSPECIFIED,
)),
AttributeType::CertificateCategory => {
Some(Attribute::CertificateCategory(CK_CERTIFICATE_CATEGORY_UNSPECIFIED))
}
AttributeType::CertificateType => Some(Attribute::CertificateType(CKC_X_509)),
AttributeType::Class => Some(Attribute::Class(CKO_CERTIFICATE)),
AttributeType::Id => Some(Attribute::Id(cert.public_key().public_key_hash())),
Expand Down Expand Up @@ -112,31 +112,28 @@ impl Object {
AttributeType::Label => Some(Attribute::Label(private_key.label())),
AttributeType::Local => Some(Attribute::Local(false)),
AttributeType::Modulus => {
let modulus = private_key
.find_public_key(backend())
.ok()
.flatten()
.and_then(|public_key| {
let modulus = private_key.find_public_key(backend()).ok().flatten().and_then(
|public_key| {
let der = public_key.to_der();
RsaPublicKey::from_der(&der)
.map(|pk| pk.modulus.as_bytes().to_vec())
.ok()
});
},
);
modulus.map(Attribute::Modulus)
}
AttributeType::NeverExtractable => Some(Attribute::NeverExtractable(true)),
AttributeType::Private => Some(Attribute::Private(true)),
AttributeType::PublicExponent => {
let public_exponent = private_key
.find_public_key(backend())
.ok()
.flatten()
.and_then(|public_key| {
let der = public_key.to_der();
RsaPublicKey::from_der(&der)
.map(|pk| pk.public_exponent.as_bytes().to_vec())
.ok()
});
let public_exponent =
private_key.find_public_key(backend()).ok().flatten().and_then(
|public_key| {
let der = public_key.to_der();
RsaPublicKey::from_der(&der)
.map(|pk| pk.public_exponent.as_bytes().to_vec())
.ok()
},
);
public_exponent.map(Attribute::PublicExponent)
}
AttributeType::Sensitive => Some(Attribute::Sensitive(true)),
Expand Down
12 changes: 4 additions & 8 deletions native-pkcs11-keychain/src/macos/backend.rs
Original file line number Diff line number Diff line change
Expand Up @@ -149,10 +149,8 @@ impl Backend for KeychainBackend {
let keys = sec_keys
.into_iter()
.filter_map(|sec_key| {
let label: Option<String> = sec_key
.attributes()
.find(unsafe { kSecAttrLabel }.to_void())
.map(|label| {
let label: Option<String> =
sec_key.attributes().find(unsafe { kSecAttrLabel }.to_void()).map(|label| {
unsafe { CFString::wrap_under_get_rule(label.cast()) }.to_string()
});
let label: String = label.unwrap_or_default();
Expand All @@ -172,10 +170,8 @@ impl Backend for KeychainBackend {
let keys = sec_keys
.into_iter()
.filter_map(|sec_key| {
let label: Option<String> = sec_key
.attributes()
.find(unsafe { kSecAttrLabel }.to_void())
.map(|label| {
let label: Option<String> =
sec_key.attributes().find(unsafe { kSecAttrLabel }.to_void()).map(|label| {
unsafe { CFString::wrap_under_get_rule(label.cast()) }.to_string()
});
let label: String = label.unwrap_or_default();
Expand Down
36 changes: 9 additions & 27 deletions native-pkcs11-keychain/src/macos/key.rs
Original file line number Diff line number Diff line change
Expand Up @@ -160,10 +160,7 @@ impl PrivateKey for KeychainPrivateKey {

fn sec_key_algorithm(sec_key: &SecKey) -> Result<KeyAlgorithm> {
let attributes = sec_key.attributes();
if attributes
.find(unsafe { kSecAttrTokenID }.to_void())
.is_some()
{
if attributes.find(unsafe { kSecAttrTokenID }.to_void()).is_some() {
// The only possible kSecAttrtokenID is kSecAttrTokenIDSecureEnclave.
//
// SecureEnclave keys do not have kSecAttrKeyType populated, but we can
Expand Down Expand Up @@ -194,9 +191,7 @@ pub struct KeychainPublicKey {
impl KeychainPublicKey {
#[instrument]
pub fn new(sec_key: SecKey, label: impl Into<String> + Debug) -> Result<Self> {
let der = sec_key
.external_representation()
.ok_or("no external representation")?;
let der = sec_key.external_representation().ok_or("no external representation")?;
let key_ty = sec_key_algorithm(&sec_key)?;
Ok(Self {
public_key_hash: sec_key.application_label().ok_or("no application_label")?,
Expand Down Expand Up @@ -396,14 +391,8 @@ mod test {
#[serial]
fn key_lifecycle() -> Result<()> {
for (key_alg, sig_alg) in [
(
Algorithm::ECC,
security_framework_sys::key::Algorithm::ECDSASignatureDigestX962,
),
(
Algorithm::RSA,
security_framework_sys::key::Algorithm::RSASignatureDigestPKCS1v15Raw,
),
(Algorithm::ECC, security_framework_sys::key::Algorithm::ECDSASignatureDigestX962),
(Algorithm::RSA, security_framework_sys::key::Algorithm::RSASignatureDigestPKCS1v15Raw),
] {
let label = &random_label();

Expand All @@ -427,10 +416,7 @@ mod test {
let sig_valid = loaded_pubkey.verify_signature(sig_alg, &payload, &signature)?;
assert!(sig_valid);

assert_eq!(
loaded_pubkey.external_representation().unwrap().to_vec(),
first_pubkey
);
assert_eq!(loaded_pubkey.external_representation().unwrap().to_vec(), first_pubkey);

loaded_key.public_key().ok_or("no pubkey")?.delete()?;
loaded_key.delete()?;
Expand Down Expand Up @@ -505,18 +491,14 @@ mod test {

let label = random_label();
let key1 = SecKey::new(
GenerateKeyOptions::default()
.set_key_type(KeyType::ec())
.set_label(&label),
GenerateKeyOptions::default().set_key_type(KeyType::ec()).set_label(&label),
)?;

let pubkey_hash = key1.public_key().unwrap().application_label().unwrap();

ItemAddOptions::new(security_framework::item::ItemAddValue::Ref(AddRef::Key(
key1,
)))
.set_label(&label)
.add()?;
ItemAddOptions::new(security_framework::item::ItemAddValue::Ref(AddRef::Key(key1)))
.set_label(&label)
.add()?;

// NOTE(kcking): this fails to find the generated key, most likely
// because application_label is not automatically populated by
Expand Down
5 changes: 1 addition & 4 deletions native-pkcs11-keychain/src/macos/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,10 +43,7 @@ impl std::error::Error for Error {}

impl<E: Into<ErrorKind>> From<E> for Error {
fn from(e: E) -> Self {
Error {
error: e.into(),
context: SpanTrace::capture(),
}
Error { error: e.into(), context: SpanTrace::capture() }
}
}

Expand Down
16 changes: 3 additions & 13 deletions native-pkcs11-traits/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -68,11 +68,7 @@ pub enum SignatureAlgorithm {
RsaPkcs1v15Sha384,
RsaPkcs1v15Sha256,
RsaPkcs1v15Sha512,
RsaPss {
digest: DigestType,
mask_generation_function: DigestType,
salt_length: u64,
},
RsaPss { digest: DigestType, mask_generation_function: DigestType, salt_length: u64 },
}

pub trait PrivateKey: Send + Sync {
Expand All @@ -89,9 +85,7 @@ pub trait PrivateKey: Send + Sync {

impl std::fmt::Debug for dyn PrivateKey {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("PrivateKey")
.field("label", &self.label())
.finish_non_exhaustive()
f.debug_struct("PrivateKey").field("label", &self.label()).finish_non_exhaustive()
}
}

Expand Down Expand Up @@ -211,9 +205,5 @@ pub trait Backend: Send + Sync {
pub fn random_label() -> String {
use rand::{distr::Alphanumeric, Rng};
String::from("bumpkey ")
+ &rand::rng()
.sample_iter(&Alphanumeric)
.take(32)
.map(char::from)
.collect::<String>()
+ &rand::rng().sample_iter(&Alphanumeric).take(32).map(char::from).collect::<String>()
}
Loading

0 comments on commit dd8482f

Please sign in to comment.