diff --git a/implementations/rust/ockam/ockam_api/src/vault.rs b/implementations/rust/ockam/ockam_api/src/vault.rs index ef21052dfa2..2ad55f808e1 100644 --- a/implementations/rust/ockam/ockam_api/src/vault.rs +++ b/implementations/rust/ockam/ockam_api/src/vault.rs @@ -7,7 +7,7 @@ use minicbor::{Decoder, Encode}; use models::*; use ockam_core::api::{Error, Id, Method, Request, Response, Status}; use ockam_core::vault::{ - AsymmetricVault, Hasher, KeyId, SecretVault, Signature, Signer, SymmetricVault, Verifier, + AsymmetricVault, Hasher, KeyId, KeyVault, Signature, Signer, SymmetricVault, Verifier, }; use ockam_core::CowStr; use ockam_core::{Result, Routed, Worker}; @@ -114,13 +114,13 @@ impl VaultService { match args.operation() { GetSecretRequestOperation::GetAttributes => { - let resp = self.vault.secret_attributes_get(&key_id).await?; + let resp = self.vault.get_key_attributes(&key_id).await?; let body = GetSecretAttributesResponse::new(resp); Self::ok_response(req, Some(body), enc) } GetSecretRequestOperation::GetSecretBytes => { - let resp = self.vault.secret_export(&key_id).await?; + let resp = self.vault.export_key(&key_id).await?; let body = ExportSecretResponse::new(resp); Self::ok_response(req, Some(body), enc) @@ -130,7 +130,7 @@ impl VaultService { ["secrets", key_id, "public_key"] => { let key_id: KeyId = key_id.to_string(); - let public_key = self.vault.secret_public_key_get(&key_id).await?; + let public_key = self.vault.get_public_key(&key_id).await?; let body = PublicKeyResponse::new(public_key); Self::ok_response(req, Some(body), enc) @@ -148,8 +148,8 @@ impl VaultService { let attributes = *args.attributes(); let key_id = match args.into_secret() { - Some(secret) => self.vault.secret_import(secret, attributes).await?, - None => self.vault.secret_generate(attributes).await?, + Some(secret) => self.vault.import_key(secret, attributes).await?, + None => self.vault.generate_key(attributes).await?, }; let body = CreateSecretResponse::new(key_id); @@ -294,7 +294,7 @@ impl VaultService { ["secrets", key_id] => { let key_id: KeyId = key_id.to_string(); - self.vault.secret_destroy(key_id).await?; + self.vault.destroy_key(key_id).await?; #[allow(unused_qualifications)] Self::ok_response(req, Option::<()>::None, enc) diff --git a/implementations/rust/ockam/ockam_api/src/vault/models/hasher_request.rs b/implementations/rust/ockam/ockam_api/src/vault/models/hasher_request.rs index cf670027246..978c9e76869 100644 --- a/implementations/rust/ockam/ockam_api/src/vault/models/hasher_request.rs +++ b/implementations/rust/ockam/ockam_api/src/vault/models/hasher_request.rs @@ -1,7 +1,7 @@ use minicbor::{Decode, Encode}; use ockam_core::{CowBytes, CowStr}; -use ockam_core::vault::SecretAttributes; +use ockam_core::vault::KeyAttributes; #[cfg(feature = "tag")] use ockam_core::TypeTag; @@ -37,7 +37,7 @@ pub struct HkdfSha256Request<'a> { #[b(2)] info: CowBytes<'a>, #[b(3)] ikm: Option>, // TODO: Can be tinyvec - #[n(4)] output_attributes: Vec, + #[n(4)] output_attributes: Vec, } impl<'a> HkdfSha256Request<'a> { @@ -45,7 +45,7 @@ impl<'a> HkdfSha256Request<'a> { salt: impl Into>, info: impl Into>, ikm: Option>>, - output_attributes: impl Into>, + output_attributes: impl Into>, ) -> Self { Self { #[cfg(feature = "tag")] @@ -65,7 +65,7 @@ impl<'a> HkdfSha256Request<'a> { pub fn ikm(&self) -> Option<&str> { self.ikm.as_deref() } - pub fn output_attributes(&self) -> &[SecretAttributes] { + pub fn output_attributes(&self) -> &[KeyAttributes] { &self.output_attributes } } diff --git a/implementations/rust/ockam/ockam_api/src/vault/models/secret_request.rs b/implementations/rust/ockam/ockam_api/src/vault/models/secret_request.rs index e8ec0026fca..a155401537e 100644 --- a/implementations/rust/ockam/ockam_api/src/vault/models/secret_request.rs +++ b/implementations/rust/ockam/ockam_api/src/vault/models/secret_request.rs @@ -1,6 +1,6 @@ use minicbor::{Decode, Encode}; -use ockam::vault::Secret; -use ockam_core::vault::SecretAttributes; +use ockam::vault::Key; +use ockam_core::vault::KeyAttributes; #[cfg(feature = "tag")] use ockam_core::TypeTag; @@ -11,25 +11,25 @@ use ockam_core::TypeTag; pub struct CreateSecretRequest { #[cfg(feature = "tag")] #[n(0)] tag: TypeTag<8005583>, - #[n(1)] attributes: SecretAttributes, - #[n(2)] secret: Option, + #[n(1)] attributes: KeyAttributes, + #[n(2)] secret: Option, } impl CreateSecretRequest { /// Path to the main storage file - pub fn attributes(&self) -> &SecretAttributes { + pub fn attributes(&self) -> &KeyAttributes { &self.attributes } - pub fn secret(&self) -> Option<&Secret> { + pub fn secret(&self) -> Option<&Key> { self.secret.as_ref() } - pub fn into_secret(self) -> Option { + pub fn into_secret(self) -> Option { self.secret } - pub fn new_generate(attributes: SecretAttributes) -> Self { + pub fn new_generate(attributes: KeyAttributes) -> Self { Self { #[cfg(feature = "tag")] tag: TypeTag, @@ -38,7 +38,7 @@ impl CreateSecretRequest { } } - pub fn new_import(attributes: SecretAttributes, secret: Secret) -> Self { + pub fn new_import(attributes: KeyAttributes, secret: Key) -> Self { Self { #[cfg(feature = "tag")] tag: TypeTag, diff --git a/implementations/rust/ockam/ockam_api/src/vault/models/secret_response.rs b/implementations/rust/ockam/ockam_api/src/vault/models/secret_response.rs index bc96e897dd0..e5b21afbf12 100644 --- a/implementations/rust/ockam/ockam_api/src/vault/models/secret_response.rs +++ b/implementations/rust/ockam/ockam_api/src/vault/models/secret_response.rs @@ -1,6 +1,6 @@ use minicbor::{Decode, Encode}; -use ockam::vault::Secret; -use ockam_core::vault::{PublicKey, SecretAttributes}; +use ockam::vault::Key; +use ockam_core::vault::{KeyAttributes, PublicKey}; use ockam_core::CowStr; #[cfg(feature = "tag")] @@ -35,15 +35,15 @@ impl<'a> CreateSecretResponse<'a> { pub struct ExportSecretResponse { #[cfg(feature = "tag")] #[n(0)] tag: TypeTag<9094765>, - #[n(1)] secret: Secret + #[n(1)] secret: Key } impl ExportSecretResponse { - pub fn secret(&self) -> &Secret { + pub fn secret(&self) -> &Key { &self.secret } - pub fn new(secret: Secret) -> Self { + pub fn new(secret: Key) -> Self { Self { #[cfg(feature = "tag")] tag: TypeTag, @@ -58,14 +58,14 @@ impl ExportSecretResponse { pub struct GetSecretAttributesResponse { #[cfg(feature = "tag")] #[n(0)] tag: TypeTag<9257276>, - #[b(1)] attributes: SecretAttributes, + #[b(1)] attributes: KeyAttributes, } impl GetSecretAttributesResponse { - pub fn attributes(&self) -> &SecretAttributes { + pub fn attributes(&self) -> &KeyAttributes { &self.attributes } - pub fn new(attributes: SecretAttributes) -> Self { + pub fn new(attributes: KeyAttributes) -> Self { Self { #[cfg(feature = "tag")] tag: TypeTag, diff --git a/implementations/rust/ockam/ockam_api/tests/vault.rs b/implementations/rust/ockam/ockam_api/tests/vault.rs index 4b87858e447..51f3a93bf8f 100644 --- a/implementations/rust/ockam/ockam_api/tests/vault.rs +++ b/implementations/rust/ockam/ockam_api/tests/vault.rs @@ -5,7 +5,7 @@ use ockam_api::vault::models::{ }; use ockam_api::vault::VaultService; use ockam_core::api::{Request, Response, Status}; -use ockam_core::vault::{SecretAttributes, SecretPersistence, SecretType}; +use ockam_core::vault::{KeyAttributes, KeyPersistence, KeyType}; use ockam_core::{route, AllowAll, Result}; use ockam_node::Context; use ockam_vault::Vault; @@ -19,9 +19,9 @@ async fn full_flow(ctx: &mut Context) -> Result<()> { .await?; // Generate Ed25519 Key - let body = CreateSecretRequest::new_generate(SecretAttributes::new( - SecretType::Ed25519, - SecretPersistence::Ephemeral, + let body = CreateSecretRequest::new_generate(KeyAttributes::new( + KeyType::Ed25519, + KeyPersistence::Ephemeral, 0, )); diff --git a/implementations/rust/ockam/ockam_command/src/vault/mod.rs b/implementations/rust/ockam/ockam_command/src/vault/mod.rs index 414f63b69dd..49a3ba9de6a 100644 --- a/implementations/rust/ockam/ockam_command/src/vault/mod.rs +++ b/implementations/rust/ockam/ockam_command/src/vault/mod.rs @@ -4,8 +4,8 @@ use anyhow::anyhow; use clap::{Args, Subcommand}; use ockam::Context; use ockam_api::cli_state; -use ockam_core::vault::{Secret, SecretAttributes, SecretPersistence, SecretType, SecretVault}; -use ockam_identity::{Identity, IdentityStateConst, KeyAttributes}; +use ockam_core::vault::{Key, KeyAttributes, KeyPersistence, KeyType, KeyVault}; +use ockam_identity::{Identity, IdentityStateConst}; use rand::prelude::random; use std::path::PathBuf; @@ -91,15 +91,14 @@ async fn run_impl(ctx: Context, (opts, cmd): (CommandGlobalOpts, VaultCommand)) } let v = v_config.get().await?; let idt = { - let attrs = - SecretAttributes::new(SecretType::NistP256, SecretPersistence::Persistent, 32); - let kid = v.secret_import(Secret::Aws(key_id), attrs).await?; - let attrs = KeyAttributes::new(IdentityStateConst::ROOT_LABEL.to_string(), attrs); + let attrs = KeyAttributes::new(KeyType::NistP256, KeyPersistence::Persistent, 32); + let kid = v.import_key(Key::Aws(key_id), attrs).await?; Identity::create_with_external_key_ext( &ctx, &opts.state.identities.authenticated_storage().await?, &v, &kid, + IdentityStateConst::ROOT_LABEL.to_string(), attrs, ) .await? diff --git a/implementations/rust/ockam/ockam_core/src/vault/hasher.rs b/implementations/rust/ockam/ockam_core/src/vault/hasher.rs index b273dd45ac4..543bfb22eb5 100644 --- a/implementations/rust/ockam/ockam_core/src/vault/hasher.rs +++ b/implementations/rust/ockam/ockam_core/src/vault/hasher.rs @@ -1,4 +1,4 @@ -use crate::vault::{KeyId, SecretAttributes, SmallBuffer}; +use crate::vault::{KeyAttributes, KeyId, SmallBuffer}; use crate::Result; use crate::{async_trait, compat::boxed::Box}; @@ -15,6 +15,6 @@ pub trait Hasher { salt: &KeyId, info: &[u8], ikm: Option<&KeyId>, - output_attributes: SmallBuffer, + output_attributes: SmallBuffer, ) -> Result>; } diff --git a/implementations/rust/ockam/ockam_core/src/vault/secret_vault.rs b/implementations/rust/ockam/ockam_core/src/vault/secret_vault.rs index cd89f1ef894..6e1ee884f2b 100644 --- a/implementations/rust/ockam/ockam_core/src/vault/secret_vault.rs +++ b/implementations/rust/ockam/ockam_core/src/vault/secret_vault.rs @@ -1,27 +1,27 @@ -use crate::vault::{KeyId, PublicKey, SecretAttributes}; +use crate::vault::{KeyAttributes, KeyId, PublicKey}; use crate::Result; use crate::{async_trait, compat::boxed::Box}; -use super::Secret; +use super::Key; /// Defines the `Secret` management interface for Ockam Vaults. /// /// # Examples /// -/// See `ockam_vault::SoftwareVault` for a usage example. +/// See `ockam_vault::Vault` for a usage example. /// #[async_trait] -pub trait SecretVault { - /// Generate a fresh secret with the given attributes. - async fn secret_generate(&self, attributes: SecretAttributes) -> Result; - /// Import a secret with the given attributes from binary form into the vault. - async fn secret_import(&self, secret: Secret, attributes: SecretAttributes) -> Result; - /// Export a secret key to the binary form represented as [`SecretKey`]. - async fn secret_export(&self, key_id: &KeyId) -> Result; - /// Return the attributes for a secret. - async fn secret_attributes_get(&self, key_id: &KeyId) -> Result; +pub trait KeyVault { + /// Generate a fresh key with the given attributes. + async fn generate_key(&self, attributes: KeyAttributes) -> Result; + /// Import a key with the given attributes from binary form into the vault. + async fn import_key(&self, secret: Key, attributes: KeyAttributes) -> Result; + /// Export a key to the binary form represented as [`SecretKey`]. + async fn export_key(&self, key_id: &KeyId) -> Result; + /// Return the attributes for a key. + async fn get_key_attributes(&self, key_id: &KeyId) -> Result; /// Return the associated public key given the secret key. - async fn secret_public_key_get(&self, key_id: &KeyId) -> Result; - /// Remove a secret from the vault. - async fn secret_destroy(&self, key_id: KeyId) -> Result<()>; + async fn get_public_key(&self, key_id: &KeyId) -> Result; + /// Remove a key from the vault. + async fn destroy_key(&self, key_id: KeyId) -> Result<()>; } diff --git a/implementations/rust/ockam/ockam_core/src/vault/test_support/asymmetric_impl.rs b/implementations/rust/ockam/ockam_core/src/vault/test_support/asymmetric_impl.rs index 2c28b457ff9..1f006e232e9 100644 --- a/implementations/rust/ockam/ockam_core/src/vault/test_support/asymmetric_impl.rs +++ b/implementations/rust/ockam/ockam_core/src/vault/test_support/asymmetric_impl.rs @@ -1,18 +1,17 @@ use crate::vault::{ - AsymmetricVault, SecretAttributes, SecretPersistence, SecretType, SecretVault, - CURVE25519_SECRET_LENGTH_U32, + AsymmetricVault, KeyAttributes, KeyPersistence, KeyType, KeyVault, CURVE25519_SECRET_LENGTH_U32, }; -pub async fn ec_diffie_hellman_curve25519(vault: &mut (impl AsymmetricVault + SecretVault)) { - let attributes = SecretAttributes::new( - SecretType::X25519, - SecretPersistence::Ephemeral, +pub async fn ec_diffie_hellman_curve25519(vault: &mut (impl AsymmetricVault + KeyVault)) { + let attributes = KeyAttributes::new( + KeyType::X25519, + KeyPersistence::Ephemeral, CURVE25519_SECRET_LENGTH_U32, ); - let sk_ctx_1 = vault.secret_generate(attributes).await.unwrap(); - let sk_ctx_2 = vault.secret_generate(attributes).await.unwrap(); - let pk_1 = vault.secret_public_key_get(&sk_ctx_1).await.unwrap(); - let pk_2 = vault.secret_public_key_get(&sk_ctx_2).await.unwrap(); + let sk_ctx_1 = vault.generate_key(attributes).await.unwrap(); + let sk_ctx_2 = vault.generate_key(attributes).await.unwrap(); + let pk_1 = vault.get_public_key(&sk_ctx_1).await.unwrap(); + let pk_2 = vault.get_public_key(&sk_ctx_2).await.unwrap(); let res1 = vault.ec_diffie_hellman(&sk_ctx_1, &pk_2).await; assert!(res1.is_ok()); diff --git a/implementations/rust/ockam/ockam_core/src/vault/test_support/hasher_impl.rs b/implementations/rust/ockam/ockam_core/src/vault/test_support/hasher_impl.rs index b113f1647b7..b200e9e6bef 100644 --- a/implementations/rust/ockam/ockam_core/src/vault/test_support/hasher_impl.rs +++ b/implementations/rust/ockam/ockam_core/src/vault/test_support/hasher_impl.rs @@ -1,6 +1,4 @@ -use crate::vault::{ - Hasher, Secret, SecretAttributes, SecretKey, SecretPersistence, SecretType, SecretVault, -}; +use crate::vault::{Hasher, Key, KeyAttributes, KeyPersistence, KeyType, KeyVault, PrivateKey}; use hex::encode; pub async fn sha256(vault: &mut impl Hasher) { @@ -13,30 +11,30 @@ pub async fn sha256(vault: &mut impl Hasher) { ); } -pub async fn hkdf(vault: &mut (impl Hasher + SecretVault)) { +pub async fn hkdf(vault: &mut (impl Hasher + KeyVault)) { let salt_value = b"hkdf_test"; - let attributes = SecretAttributes::new( - SecretType::Buffer, - crate::vault::SecretPersistence::Ephemeral, + let attributes = KeyAttributes::new( + KeyType::Buffer, + crate::vault::KeyPersistence::Ephemeral, salt_value.len() as u32, ); let salt = vault - .secret_import(Secret::Key(SecretKey::new(salt_value.to_vec())), attributes) + .import_key(Key::Key(PrivateKey::new(salt_value.to_vec())), attributes) .await .unwrap(); let ikm_value = b"a"; - let attributes = SecretAttributes::new( - SecretType::Buffer, - SecretPersistence::Ephemeral, + let attributes = KeyAttributes::new( + KeyType::Buffer, + KeyPersistence::Ephemeral, ikm_value.len() as u32, ); let ikm = vault - .secret_import(Secret::Key(SecretKey::new(ikm_value.to_vec())), attributes) + .import_key(Key::Key(PrivateKey::new(ikm_value.to_vec())), attributes) .await .unwrap(); - let attributes = SecretAttributes::new(SecretType::Buffer, SecretPersistence::Ephemeral, 24u32); + let attributes = KeyAttributes::new(KeyType::Buffer, KeyPersistence::Ephemeral, 24u32); let res = vault .hkdf_sha256(&salt, b"", Some(&ikm), vec![attributes]) @@ -44,7 +42,7 @@ pub async fn hkdf(vault: &mut (impl Hasher + SecretVault)) { assert!(res.is_ok()); let digest = res.unwrap(); assert_eq!(digest.len(), 1); - let digest = vault.secret_export(&digest[0]).await.unwrap(); + let digest = vault.export_key(&digest[0]).await.unwrap(); assert_eq!( encode(digest.cast_as_key().as_ref()), "921ab9f260544b71941dbac2ca2d42c417aa07b53e055a8f" diff --git a/implementations/rust/ockam/ockam_core/src/vault/test_support/key_id_impl.rs b/implementations/rust/ockam/ockam_core/src/vault/test_support/key_id_impl.rs index 47e0f22ec9b..3408d438339 100644 --- a/implementations/rust/ockam/ockam_core/src/vault/test_support/key_id_impl.rs +++ b/implementations/rust/ockam/ockam_core/src/vault/test_support/key_id_impl.rs @@ -1,5 +1,5 @@ use crate::vault::{ - AsymmetricVault, PublicKey, SecretAttributes, SecretPersistence, SecretType, SecretVault, + AsymmetricVault, KeyAttributes, KeyPersistence, KeyType, KeyVault, PublicKey, CURVE25519_SECRET_LENGTH_U32, }; use hex::decode; @@ -7,7 +7,7 @@ use hex::decode; pub async fn compute_key_id_for_public_key(vault: &mut impl AsymmetricVault) { let public = decode("68858ea1ea4e1ade755df7fb6904056b291d9781eb5489932f46e32f12dd192a").unwrap(); - let public = PublicKey::new(public.to_vec(), SecretType::X25519); + let public = PublicKey::new(public.to_vec(), KeyType::X25519); let key_id = vault.compute_key_id_for_public_key(&public).await.unwrap(); @@ -17,23 +17,23 @@ pub async fn compute_key_id_for_public_key(vault: &mut impl AsymmetricVault) { ); } -pub async fn secret_by_key_id(vault: &mut (impl AsymmetricVault + SecretVault)) { +pub async fn secret_by_key_id(vault: &mut (impl AsymmetricVault + KeyVault)) { let attributes_set = [ - SecretAttributes::new( - SecretType::X25519, - SecretPersistence::Ephemeral, + KeyAttributes::new( + KeyType::X25519, + KeyPersistence::Ephemeral, CURVE25519_SECRET_LENGTH_U32, ), - SecretAttributes::new( - SecretType::Ed25519, - SecretPersistence::Ephemeral, + KeyAttributes::new( + KeyType::Ed25519, + KeyPersistence::Ephemeral, CURVE25519_SECRET_LENGTH_U32, ), ]; for attributes in attributes_set { - let secret = vault.secret_generate(attributes).await.unwrap(); - let public = vault.secret_public_key_get(&secret).await.unwrap(); + let secret = vault.generate_key(attributes).await.unwrap(); + let public = vault.get_public_key(&secret).await.unwrap(); let key_id = vault.compute_key_id_for_public_key(&public).await.unwrap(); diff --git a/implementations/rust/ockam/ockam_core/src/vault/test_support/secret_impl.rs b/implementations/rust/ockam/ockam_core/src/vault/test_support/secret_impl.rs index fda69395d45..f17b14631ec 100644 --- a/implementations/rust/ockam/ockam_core/src/vault/test_support/secret_impl.rs +++ b/implementations/rust/ockam/ockam_core/src/vault/test_support/secret_impl.rs @@ -1,64 +1,64 @@ use crate::vault::{ - Secret, SecretAttributes, SecretKey, SecretPersistence, SecretType, SecretVault, + Key, KeyAttributes, KeyPersistence, KeyType, KeyVault, PrivateKey, CURVE25519_PUBLIC_LENGTH_USIZE, CURVE25519_SECRET_LENGTH_U32, }; use hex::{decode, encode}; -pub async fn new_public_keys(vault: &mut impl SecretVault) { - let attributes = SecretAttributes::new( - SecretType::Ed25519, - SecretPersistence::Ephemeral, +pub async fn new_public_keys(vault: &mut impl KeyVault) { + let attributes = KeyAttributes::new( + KeyType::Ed25519, + KeyPersistence::Ephemeral, CURVE25519_SECRET_LENGTH_U32, ); - let res = vault.secret_generate(attributes).await; + let res = vault.generate_key(attributes).await; assert!(res.is_ok()); let ed_ctx_1 = res.unwrap(); - let res = vault.secret_public_key_get(&ed_ctx_1).await; + let res = vault.get_public_key(&ed_ctx_1).await; assert!(res.is_ok()); let pk_1 = res.unwrap(); assert_eq!(pk_1.data().len(), CURVE25519_PUBLIC_LENGTH_USIZE); - let attributes = SecretAttributes::new( - SecretType::X25519, - SecretPersistence::Ephemeral, + let attributes = KeyAttributes::new( + KeyType::X25519, + KeyPersistence::Ephemeral, CURVE25519_SECRET_LENGTH_U32, ); - let res = vault.secret_generate(attributes).await; + let res = vault.generate_key(attributes).await; assert!(res.is_ok()); let x25519_ctx_1 = res.unwrap(); - let res = vault.secret_public_key_get(&x25519_ctx_1).await; + let res = vault.get_public_key(&x25519_ctx_1).await; assert!(res.is_ok()); let pk_1 = res.unwrap(); assert_eq!(pk_1.data().len(), CURVE25519_PUBLIC_LENGTH_USIZE); } -pub async fn new_secret_keys(vault: &mut impl SecretVault) { - let types = [(SecretType::X25519, 32), (SecretType::Buffer, 24)]; +pub async fn new_secret_keys(vault: &mut impl KeyVault) { + let types = [(KeyType::X25519, 32), (KeyType::Buffer, 24)]; for (t, s) in &types { - let attributes = SecretAttributes::new(*t, SecretPersistence::Ephemeral, *s); - let res = vault.secret_generate(attributes).await; + let attributes = KeyAttributes::new(*t, KeyPersistence::Ephemeral, *s); + let res = vault.generate_key(attributes).await; assert!(res.is_ok()); let sk_ctx = res.unwrap(); - let sk = vault.secret_export(&sk_ctx).await.unwrap(); + let sk = vault.export_key(&sk_ctx).await.unwrap(); assert_eq!(sk.cast_as_key().as_ref().len() as u32, *s); - vault.secret_destroy(sk_ctx).await.unwrap(); + vault.destroy_key(sk_ctx).await.unwrap(); } } -pub async fn secret_import_export(vault: &mut impl SecretVault) { - let attributes = SecretAttributes::new( - SecretType::X25519, - SecretPersistence::Ephemeral, +pub async fn secret_import_export(vault: &mut impl KeyVault) { + let attributes = KeyAttributes::new( + KeyType::X25519, + KeyPersistence::Ephemeral, CURVE25519_SECRET_LENGTH_U32, ); let secret_str = "98d589b0dce92c9e2442b3093718138940bff71323f20b9d158218b89c3cec6e"; let secret = vault - .secret_import( - Secret::Key(SecretKey::new(decode(secret_str).unwrap())), + .import_key( + Key::Key(PrivateKey::new(decode(secret_str).unwrap())), attributes, ) .await @@ -67,7 +67,7 @@ pub async fn secret_import_export(vault: &mut impl SecretVault) { assert_eq!( encode( vault - .secret_export(&secret) + .export_key(&secret) .await .unwrap() .cast_as_key() @@ -76,11 +76,11 @@ pub async fn secret_import_export(vault: &mut impl SecretVault) { secret_str ); - let attributes = SecretAttributes::new(SecretType::Buffer, SecretPersistence::Ephemeral, 24u32); + let attributes = KeyAttributes::new(KeyType::Buffer, KeyPersistence::Ephemeral, 24u32); let secret_str = "5f791cc52297f62c7b8829b15f828acbdb3c613371d21aa1"; let secret = vault - .secret_import( - Secret::Key(SecretKey::new(decode(secret_str).unwrap())), + .import_key( + Key::Key(PrivateKey::new(decode(secret_str).unwrap())), attributes, ) .await @@ -89,7 +89,7 @@ pub async fn secret_import_export(vault: &mut impl SecretVault) { assert_eq!( encode( vault - .secret_export(&secret) + .export_key(&secret) .await .unwrap() .cast_as_key() @@ -99,24 +99,18 @@ pub async fn secret_import_export(vault: &mut impl SecretVault) { ); } -pub async fn secret_attributes_get(vault: &mut impl SecretVault) { - let attributes = SecretAttributes::new( - SecretType::X25519, - SecretPersistence::Ephemeral, +pub async fn secret_attributes_get(vault: &mut impl KeyVault) { + let attributes = KeyAttributes::new( + KeyType::X25519, + KeyPersistence::Ephemeral, CURVE25519_SECRET_LENGTH_U32, ); - let secret = vault.secret_generate(attributes).await.unwrap(); - assert_eq!( - vault.secret_attributes_get(&secret).await.unwrap(), - attributes - ); + let secret = vault.generate_key(attributes).await.unwrap(); + assert_eq!(vault.get_key_attributes(&secret).await.unwrap(), attributes); - let attributes = SecretAttributes::new(SecretType::Buffer, SecretPersistence::Ephemeral, 24u32); + let attributes = KeyAttributes::new(KeyType::Buffer, KeyPersistence::Ephemeral, 24u32); - let secret = vault.secret_generate(attributes).await.unwrap(); - assert_eq!( - vault.secret_attributes_get(&secret).await.unwrap(), - attributes - ); + let secret = vault.generate_key(attributes).await.unwrap(); + assert_eq!(vault.get_key_attributes(&secret).await.unwrap(), attributes); } diff --git a/implementations/rust/ockam/ockam_core/src/vault/test_support/signer_impl.rs b/implementations/rust/ockam/ockam_core/src/vault/test_support/signer_impl.rs index d231fd4a9aa..2903b804509 100644 --- a/implementations/rust/ockam/ockam_core/src/vault/test_support/signer_impl.rs +++ b/implementations/rust/ockam/ockam_core/src/vault/test_support/signer_impl.rs @@ -1,25 +1,25 @@ use crate::vault::{ - SecretAttributes, SecretPersistence, SecretType, SecretVault, Signer, Verifier, + KeyAttributes, KeyPersistence, KeyType, KeyVault, Signer, Verifier, CURVE25519_SECRET_LENGTH_U32, }; -pub async fn sign(vault: &mut (impl Signer + Verifier + SecretVault)) { +pub async fn sign(vault: &mut (impl Signer + Verifier + KeyVault)) { for attributes in [ - SecretAttributes::new( - SecretType::X25519, - SecretPersistence::Ephemeral, + KeyAttributes::new( + KeyType::X25519, + KeyPersistence::Ephemeral, CURVE25519_SECRET_LENGTH_U32, ), - SecretAttributes::new( - SecretType::Ed25519, - SecretPersistence::Ephemeral, + KeyAttributes::new( + KeyType::Ed25519, + KeyPersistence::Ephemeral, CURVE25519_SECRET_LENGTH_U32, ), ] { - let secret = vault.secret_generate(attributes).await.unwrap(); + let secret = vault.generate_key(attributes).await.unwrap(); let res = vault.sign(&secret, b"hello world!").await; assert!(res.is_ok()); - let pubkey = vault.secret_public_key_get(&secret).await.unwrap(); + let pubkey = vault.get_public_key(&secret).await.unwrap(); let signature = res.unwrap(); let res = vault .verify(&signature, &pubkey, b"hello world!") diff --git a/implementations/rust/ockam/ockam_core/src/vault/test_support/symmetric_impl.rs b/implementations/rust/ockam/ockam_core/src/vault/test_support/symmetric_impl.rs index 753c0e543e0..e5d2d57c068 100644 --- a/implementations/rust/ockam/ockam_core/src/vault/test_support/symmetric_impl.rs +++ b/implementations/rust/ockam/ockam_core/src/vault/test_support/symmetric_impl.rs @@ -1,19 +1,18 @@ use crate::vault::{ - SecretAttributes, SecretPersistence, SecretType, SecretVault, SymmetricVault, - AES128_SECRET_LENGTH_U32, + KeyAttributes, KeyPersistence, KeyType, KeyVault, SymmetricVault, AES128_SECRET_LENGTH_U32, }; -pub async fn encryption(vault: &mut (impl SymmetricVault + SecretVault)) { +pub async fn encryption(vault: &mut (impl SymmetricVault + KeyVault)) { let message = b"Ockam Test Message"; let nonce = b"TestingNonce"; let aad = b"Extra payload data"; - let attributes = SecretAttributes::new( - SecretType::Aes, - SecretPersistence::Ephemeral, + let attributes = KeyAttributes::new( + KeyType::Aes, + KeyPersistence::Ephemeral, AES128_SECRET_LENGTH_U32, ); - let ctx = &vault.secret_generate(attributes).await.unwrap(); + let ctx = &vault.generate_key(attributes).await.unwrap(); let res = vault .aead_aes_gcm_encrypt(ctx, message.as_ref(), nonce.as_ref(), aad.as_ref()) .await; diff --git a/implementations/rust/ockam/ockam_core/src/vault/types.rs b/implementations/rust/ockam/ockam_core/src/vault/types.rs index 5b65c5dd119..9bd94793118 100644 --- a/implementations/rust/ockam/ockam_core/src/vault/types.rs +++ b/implementations/rust/ockam/ockam_core/src/vault/types.rs @@ -33,8 +33,8 @@ pub const AES128_SECRET_LENGTH_USIZE: usize = 16; cfg_if! { if #[cfg(not(feature = "alloc"))] { - /// Secret Key Vector. The maximum size is 32 bytes. - pub type SecretKeyVec = heapless::Vec; + /// Private Key Vector. The maximum size is 32 bytes. + pub type PrivateKeyVec = heapless::Vec; /// Public Key Vector. The maximum size is 65 bytes. pub type PublicKeyVec = heapless::Vec; /// Buffer for small vectors (e.g. an array of attributes). The maximum length is 4 elements. @@ -55,8 +55,8 @@ cfg_if! { else { use alloc::vec::Vec; use alloc::string::String; - /// Secret Key Vector. - pub type SecretKeyVec = Vec; + /// Private Key Vector. + pub type PrivateKeyVec = Vec; /// Public Key Vector. pub type PublicKeyVec = Vec; /// Buffer for small vectors. (e.g. an array of attributes) @@ -70,33 +70,33 @@ cfg_if! { } } -/// Binary representation of a Secret. +/// Binary representation of a Private key. #[derive(Serialize, Deserialize, Clone, Zeroize, Encode, Decode)] #[zeroize(drop)] #[cbor(transparent)] -pub struct SecretKey(#[n(0)] SecretKeyVec); +pub struct PrivateKey(#[n(0)] PrivateKeyVec); -impl SecretKey { - /// Create a new secret key. - pub fn new(data: SecretKeyVec) -> Self { +impl PrivateKey { + /// Create a new private key. + pub fn new(data: PrivateKeyVec) -> Self { Self(data) } } -impl core::fmt::Debug for SecretKey { +impl core::fmt::Debug for PrivateKey { fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { - f.pad("") + f.pad("") } } -impl Eq for SecretKey {} -impl PartialEq for SecretKey { +impl Eq for PrivateKey {} +impl PartialEq for PrivateKey { fn eq(&self, o: &Self) -> bool { subtle::ConstantTimeEq::ct_eq(&self.0[..], &o.0[..]).into() } } -impl AsRef<[u8]> for SecretKey { +impl AsRef<[u8]> for PrivateKey { fn as_ref(&self) -> &[u8] { &self.0 } @@ -112,7 +112,7 @@ pub struct PublicKey { #[serde(skip)] #[n(0)] tag: TypeTag<8922437>, #[b(1)] data: PublicKeyVec, - #[n(2)] stype: SecretType, + #[n(2)] stype: KeyType, } impl Eq for PublicKey {} @@ -128,15 +128,15 @@ impl PublicKey { pub fn data(&self) -> &[u8] { &self.data } - /// Corresponding secret key type. - pub fn stype(&self) -> SecretType { + /// Corresponding private key type. + pub fn stype(&self) -> KeyType { self.stype } } impl PublicKey { /// Create a new public key. - pub fn new(data: PublicKeyVec, stype: SecretType) -> Self { + pub fn new(data: PublicKeyVec, stype: KeyType) -> Self { PublicKey { #[cfg(feature = "tag")] tag: TypeTag, @@ -183,11 +183,11 @@ impl From for SignatureVec { } } -/// All possible [`SecretType`]s +/// All possible [`KeyType`]s #[derive(Serialize, Deserialize, Copy, Clone, Debug, Encode, Decode, Eq, PartialEq, Zeroize)] #[rustfmt::skip] #[cbor(index_only)] -pub enum SecretType { +pub enum KeyType { /// Secret buffer #[n(1)] Buffer, /// AES key @@ -200,53 +200,62 @@ pub enum SecretType { #[n(5)] NistP256 } -/// All possible [`SecretKey`] persistence types +/// All possible [`PrivateKey`] persistence types #[derive(Serialize, Deserialize, Copy, Clone, Encode, Decode, Debug, Eq, PartialEq)] #[rustfmt::skip] #[cbor(index_only)] -pub enum SecretPersistence { - /// An ephemeral/temporary secret +pub enum KeyPersistence { + /// An ephemeral/temporary key #[n(1)] Ephemeral, - /// A persistent secret + /// A persistent key #[n(2)] Persistent, } /// Attributes for a specific vault. #[derive(Serialize, Deserialize, Copy, Encode, Decode, Clone, Debug, Eq, PartialEq)] #[rustfmt::skip] -pub struct SecretAttributes { - #[n(1)] stype: SecretType, - #[n(2)] persistence: SecretPersistence, +pub struct KeyAttributes { + #[n(1)] stype: KeyType, + #[n(2)] persistence: KeyPersistence, #[n(3)] length: u32, } -impl SecretAttributes { - /// Return the type of the secret. - pub fn stype(&self) -> SecretType { +impl KeyAttributes { + /// Return the type of the key. + pub fn stype(&self) -> KeyType { self.stype } - /// Return the persistence of the secret. - pub fn persistence(&self) -> SecretPersistence { + /// Return the persistence of the key. + pub fn persistence(&self) -> KeyPersistence { self.persistence } - /// Return the length of the secret. + /// Return the length of the key. pub fn length(&self) -> u32 { self.length } } -impl SecretAttributes { - /// Create a new secret attribute. - pub fn new(stype: SecretType, persistence: SecretPersistence, length: u32) -> Self { - SecretAttributes { +impl KeyAttributes { + /// Create a new key attribute. + pub fn new(stype: KeyType, persistence: KeyPersistence, length: u32) -> Self { + KeyAttributes { stype, persistence, length, } } + + /// Create default key attributes + pub fn default_attributes() -> Self { + KeyAttributes::new( + KeyType::Ed25519, + KeyPersistence::Persistent, + CURVE25519_SECRET_LENGTH_U32, + ) + } } -impl fmt::Display for SecretAttributes { +impl fmt::Display for KeyAttributes { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!( f, @@ -258,18 +267,18 @@ impl fmt::Display for SecretAttributes { } } -/// A public key +/// A public key + the key id of its private key #[derive(Clone, Debug, Zeroize)] #[zeroize(drop)] pub struct KeyPair { - secret: KeyId, + key_id: KeyId, public: PublicKey, } impl KeyPair { - /// Secret key - pub fn secret(&self) -> &KeyId { - &self.secret + /// KeyId of the private key + pub fn key_id(&self) -> &KeyId { + &self.key_id } /// Public Key pub fn public(&self) -> &PublicKey { @@ -279,86 +288,89 @@ impl KeyPair { impl KeyPair { /// Create a new key pair - pub fn new(secret: KeyId, public: PublicKey) -> Self { - Self { secret, public } + pub fn new(key_id: KeyId, public_key: PublicKey) -> Self { + Self { + key_id, + public: public_key, + } } } -/// Secret stored in a Vault Storage +/// Private key stored in a Vault Storage #[derive(Debug, Eq, PartialEq, Clone)] pub struct VaultEntry { - key_attributes: SecretAttributes, - secret: Secret, + key_attributes: KeyAttributes, + key: Key, } -/// A secret key or reference. +/// A private key or reference. #[derive(Debug, Eq, PartialEq, Clone, Serialize, Deserialize, Encode, Decode)] #[rustfmt::skip] -pub enum Secret { - /// A secret key. - #[n(0)] Key(#[n(0)] SecretKey), - /// Reference to an unmanaged, external secret key of AWS KMS. +pub enum Key { + /// A private key. + #[n(0)] Key(#[n(0)] PrivateKey), + /// Reference to an unmanaged, external private key of AWS KMS. #[n(1)] Aws(#[n(1)] KeyId) } -impl Secret { - /// Treat this secret as a secret key and pull the key out. - /// +impl Key { + /// Treat this private key as a key (not a KeyId) and pull it out. + /// TODO: this code will be removed with the extraction of a proper AWS KMS vault implementation /// # Panics /// - /// If the secret does not hold a key. - pub fn cast_as_key(&self) -> &SecretKey { - self.try_as_key().expect("`Secret` holds a key") + /// If the key entry does not hold a private key. + pub fn cast_as_key(&self) -> &PrivateKey { + self.try_as_key().expect("`Key` holds a key") } - /// Treat this secret as a secret key and try to pull the key out. - pub fn try_as_key(&self) -> Result<&SecretKey, Error> { - if let Secret::Key(k) = self { + /// Treat this key as a private key and try to pull the key out. + pub fn try_as_key(&self) -> Result<&PrivateKey, Error> { + if let Key::Key(k) = self { Ok(k) } else { Err(Error::new( Origin::Other, Kind::Misuse, - "`Secret` does not hold a key", + "`Key` does not hold a key", )) } } } impl VaultEntry { - /// Secret's Attributes - pub fn key_attributes(&self) -> SecretAttributes { + /// Private key Attributes + pub fn key_attributes(&self) -> KeyAttributes { self.key_attributes } - /// Get the secret part of this vault entry. - pub fn secret(&self) -> &Secret { - &self.secret + /// Get the key part of this vault entry. + pub fn key(&self) -> &Key { + &self.key } } impl VaultEntry { /// Create a new vault entry. - pub fn new(key_attributes: SecretAttributes, secret: Secret) -> Self { + pub fn new(key_attributes: KeyAttributes, key: Key) -> Self { VaultEntry { key_attributes, - secret, + key, } } - /// Create a new vault entry with a secret key. - pub fn new_key(key_attributes: SecretAttributes, key: SecretKey) -> Self { + /// Create a new vault entry with a private key. + pub fn new_key(key_attributes: KeyAttributes, key: PrivateKey) -> Self { VaultEntry { key_attributes, - secret: Secret::Key(key), + key: Key::Key(key), } } - /// Create a new vault entry with an external secret key from AWS KMS. - pub fn new_aws(key_attributes: SecretAttributes, kid: KeyId) -> Self { + /// Create a new vault entry with an external private key from AWS KMS. + pub fn new_aws(key_attributes: KeyAttributes, kid: KeyId) -> Self { VaultEntry { key_attributes, - secret: Secret::Aws(kid), + key: Key::Aws(kid), } } } diff --git a/implementations/rust/ockam/ockam_ffi/src/vault.rs b/implementations/rust/ockam/ockam_ffi/src/vault.rs index 9c14a8eaccd..0acfd05c3bb 100644 --- a/implementations/rust/ockam/ockam_ffi/src/vault.rs +++ b/implementations/rust/ockam/ockam_ffi/src/vault.rs @@ -7,7 +7,7 @@ use lazy_static::lazy_static; use ockam_core::compat::collections::BTreeMap; use ockam_core::compat::sync::Arc; use ockam_core::vault::{ - AsymmetricVault, Hasher, KeyId, PublicKey, Secret, SecretAttributes, SecretKey, SecretVault, + AsymmetricVault, Hasher, Key, KeyAttributes, KeyId, KeyVault, PrivateKey, PublicKey, SymmetricVault, }; use ockam_core::{Error, Result}; @@ -153,7 +153,7 @@ pub extern "C" fn ockam_vault_secret_generate( *secret = block_future(async move { let entry = get_vault_entry(context).await?; let atts = attributes.try_into()?; - let key_id = entry.vault.secret_generate(atts).await?; + let key_id = entry.vault.generate_key(atts).await?; let index = entry.insert(key_id).await; @@ -180,8 +180,8 @@ pub extern "C" fn ockam_vault_secret_import( let secret_data = unsafe { core::slice::from_raw_parts(input, input_length as usize) }; - let secret = Secret::Key(SecretKey::new(secret_data.to_vec())); - let key_id = entry.vault.secret_import(secret, atts).await?; + let secret = Key::Key(PrivateKey::new(secret_data.to_vec())); + let key_id = entry.vault.import_key(secret, atts).await?; let index = entry.insert(key_id).await; @@ -205,7 +205,7 @@ pub extern "C" fn ockam_vault_secret_export( block_future(async move { let entry = get_vault_entry(context).await?; let key_id = entry.get(secret).await?; - let key = entry.vault.secret_export(&key_id).await?; + let key = entry.vault.export_key(&key_id).await?; if output_buffer_size < key.try_as_key()?.as_ref().len() as u32 { return Err(FfiError::BufferTooSmall.into()); } @@ -238,7 +238,7 @@ pub extern "C" fn ockam_vault_secret_publickey_get( block_future(async move { let entry = get_vault_entry(context).await?; let key_id = entry.get(secret).await?; - let key = entry.vault.secret_public_key_get(&key_id).await?; + let key = entry.vault.get_public_key(&key_id).await?; if output_buffer_size < key.data().len() as u32 { return Err(FfiError::BufferTooSmall.into()); } @@ -264,7 +264,7 @@ pub extern "C" fn ockam_vault_secret_attributes_get( *attributes = block_future(async move { let entry = get_vault_entry(context).await?; let key_id = entry.get(secret).await?; - let atts = entry.vault.secret_attributes_get(&key_id).await?; + let atts = entry.vault.get_key_attributes(&key_id).await?; Ok::(atts.into()) })?; Ok(()) @@ -280,7 +280,7 @@ pub extern "C" fn ockam_vault_secret_destroy( match block_future(async move { let entry = get_vault_entry(context).await?; let key_id = entry.take(secret).await?; - entry.vault.secret_destroy(key_id).await?; + entry.vault.destroy_key(key_id).await?; Ok::<(), Error>(()) }) { Ok(_) => FfiOckamError::none(), @@ -307,7 +307,7 @@ pub extern "C" fn ockam_vault_ecdh( *shared_secret = block_future(async move { let entry = get_vault_entry(context).await?; let key_id = entry.get(secret).await?; - let atts = entry.vault.secret_attributes_get(&key_id).await?; + let atts = entry.vault.get_key_attributes(&key_id).await?; let pubkey = PublicKey::new(peer_publickey.to_vec(), atts.stype()); let shared_ctx = entry.vault.ec_diffie_hellman(&key_id, &pubkey).await?; let index = entry.insert(shared_ctx).await; @@ -345,9 +345,9 @@ pub extern "C" fn ockam_vault_hkdf_sha256( let array: &[FfiSecretAttributes] = unsafe { slice::from_raw_parts(derived_outputs_attributes, derived_outputs_count) }; - let mut output_attributes = Vec::::with_capacity(array.len()); + let mut output_attributes = Vec::::with_capacity(array.len()); for x in array.iter() { - output_attributes.push(SecretAttributes::try_from(*x)?); + output_attributes.push(KeyAttributes::try_from(*x)?); } // TODO: Hardcoded to be empty for now because any changes diff --git a/implementations/rust/ockam/ockam_ffi/src/vault_types.rs b/implementations/rust/ockam/ockam_ffi/src/vault_types.rs index 0f6b9f63070..d34927c0e10 100644 --- a/implementations/rust/ockam/ockam_ffi/src/vault_types.rs +++ b/implementations/rust/ockam/ockam_ffi/src/vault_types.rs @@ -1,7 +1,7 @@ #![allow(conflicting_repr_hints)] use crate::FfiError; -use ockam_core::vault::{SecretAttributes, SecretPersistence, SecretType}; +use ockam_core::vault::{KeyAttributes, KeyPersistence, KeyType}; /// Represents a handle id for the secret key pub type SecretKeyHandle = u64; @@ -64,40 +64,40 @@ impl FfiSecretAttributes { } } -impl From for FfiSecretAttributes { - fn from(attrs: SecretAttributes) -> Self { +impl From for FfiSecretAttributes { + fn from(attrs: KeyAttributes) -> Self { let stype = match attrs.stype() { - SecretType::Buffer => 0, - SecretType::Aes => 1, - SecretType::X25519 => 2, - SecretType::Ed25519 => 3, - SecretType::NistP256 => 4, + KeyType::Buffer => 0, + KeyType::Aes => 1, + KeyType::X25519 => 2, + KeyType::Ed25519 => 3, + KeyType::NistP256 => 4, }; let persistence = match attrs.persistence() { - SecretPersistence::Ephemeral => 0, - SecretPersistence::Persistent => 1, + KeyPersistence::Ephemeral => 0, + KeyPersistence::Persistent => 1, }; Self::new(stype, persistence, attrs.length()) } } -impl TryFrom for SecretAttributes { +impl TryFrom for KeyAttributes { type Error = FfiError; fn try_from(attrs: FfiSecretAttributes) -> Result { let stype = match attrs.stype() { - 0 => Ok(SecretType::Buffer), - 1 => Ok(SecretType::Aes), - 2 => Ok(SecretType::X25519), - 3 => Ok(SecretType::Ed25519), + 0 => Ok(KeyType::Buffer), + 1 => Ok(KeyType::Aes), + 2 => Ok(KeyType::X25519), + 3 => Ok(KeyType::Ed25519), _ => Err(FfiError::InvalidParam), }?; let persistence = match attrs.persistence() { - 0 => Ok(SecretPersistence::Ephemeral), - 1 => Ok(SecretPersistence::Persistent), + 0 => Ok(KeyPersistence::Ephemeral), + 1 => Ok(KeyPersistence::Persistent), _ => Err(FfiError::InvalidParam), }?; diff --git a/implementations/rust/ockam/ockam_identity/src/change.rs b/implementations/rust/ockam/ockam_identity/src/change.rs index 53326fab50d..399fe24010a 100644 --- a/implementations/rust/ockam/ockam_identity/src/change.rs +++ b/implementations/rust/ockam/ockam_identity/src/change.rs @@ -38,8 +38,8 @@ impl IdentityChange { pub(crate) fn label(&self) -> &str { match self { - IdentityChange::CreateKey(data) => data.key_attributes().label(), - IdentityChange::RotateKey(data) => data.key_attributes().label(), + IdentityChange::CreateKey(data) => data.key_label(), + IdentityChange::RotateKey(data) => data.key_label(), } } @@ -65,7 +65,7 @@ impl IdentityChange { pub struct IdentitySignedChange { identifier: ChangeIdentifier, change: IdentityChange, - signatures: Vec, + signatures: Vec, } impl IdentitySignedChange { @@ -78,7 +78,7 @@ impl IdentitySignedChange { &self.change } /// Signatures are used to check change validity. - pub fn signatures(&self) -> &[Signature] { + pub fn signatures(&self) -> &[IdentityChangeSignature] { &self.signatures } } @@ -88,7 +88,7 @@ impl IdentitySignedChange { pub fn new( identifier: ChangeIdentifier, change: IdentityChange, - signatures: Vec, + signatures: Vec, ) -> Self { Self { identifier, diff --git a/implementations/rust/ockam/ockam_identity/src/change/create_key.rs b/implementations/rust/ockam/ockam_identity/src/change/create_key.rs index a451ea1f599..4a45f6ef1a2 100644 --- a/implementations/rust/ockam/ockam_identity/src/change/create_key.rs +++ b/implementations/rust/ockam/ockam_identity/src/change/create_key.rs @@ -1,10 +1,11 @@ use crate::authenticated_storage::AuthenticatedStorage; -use crate::change::{IdentityChange, IdentitySignedChange, Signature, SignatureType}; +use crate::change::{IdentityChange, IdentityChangeSignature, IdentitySignedChange, SignatureType}; use crate::change_history::IdentityChangeHistory; use crate::IdentityError::InvalidInternalState; -use crate::{ChangeIdentifier, Identity, IdentityError, IdentityVault, KeyAttributes}; +use crate::{ChangeIdentifier, Identity, IdentityError, IdentityVault}; use core::fmt; -use ockam_core::vault::{KeyId, PublicKey}; +use ockam_core::compat::string::String; +use ockam_core::vault::{KeyAttributes, KeyId, PublicKey}; use ockam_core::{Encodable, Result}; use serde::{Deserialize, Serialize}; @@ -12,11 +13,16 @@ use serde::{Deserialize, Serialize}; #[derive(Serialize, Deserialize, Debug, Clone)] pub struct CreateKeyChangeData { prev_change_id: ChangeIdentifier, + key_label: String, key_attributes: KeyAttributes, public_key: PublicKey, } impl CreateKeyChangeData { + /// Return key attributes + pub fn key_label(&self) -> &String { + &self.key_label + } /// Return key attributes pub fn key_attributes(&self) -> &KeyAttributes { &self.key_attributes @@ -35,11 +41,13 @@ impl CreateKeyChangeData { /// Create new CreateKeyChangeData pub fn new( prev_change_id: ChangeIdentifier, + key_label: String, key_attributes: KeyAttributes, public_key: PublicKey, ) -> Self { Self { prev_change_id, + key_label, key_attributes, public_key, } @@ -50,8 +58,9 @@ impl fmt::Display for CreateKeyChangeData { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!( f, - "prev_change_id:{} key attibutes:{} public key:{}", + "prev_change_id:{} key label:{} key attributes:{} public key:{}", self.prev_change_id(), + self.key_label(), self.key_attributes(), self.public_key() ) @@ -67,9 +76,7 @@ impl Identity { if let Some(s) = secret { Ok(s.clone()) } else { - vault - .secret_generate(key_attributes.secret_attributes()) - .await + vault.generate_key(*key_attributes).await } } @@ -77,15 +84,16 @@ impl Identity { pub(crate) async fn make_create_key_change_static( secret: Option<&KeyId>, prev_id: ChangeIdentifier, + key_label: String, key_attributes: KeyAttributes, root_key: Option<&KeyId>, vault: &V, ) -> Result { let secret_key = Self::generate_key_if_needed(secret, &key_attributes, vault).await?; - let public_key = vault.secret_public_key_get(&secret_key).await?; + let public_key = vault.get_public_key(&secret_key).await?; - let data = CreateKeyChangeData::new(prev_id, key_attributes, public_key); + let data = CreateKeyChangeData::new(prev_id, key_label, key_attributes, public_key); let change_block = IdentityChange::CreateKey(data); let change_block_binary = change_block @@ -96,7 +104,7 @@ impl Identity { let change_id = ChangeIdentifier::from_hash(change_id); let self_signature = vault.sign(&secret_key, change_id.as_ref()).await?; - let self_signature = Signature::new(SignatureType::SelfSign, self_signature); + let self_signature = IdentityChangeSignature::new(SignatureType::SelfSign, self_signature); let mut signatures = vec![self_signature]; @@ -104,7 +112,8 @@ impl Identity { // If there is no root_key - we're creating new identity, so we just generated root_key if let Some(root_key) = root_key { let root_signature = vault.sign(root_key, change_id.as_ref()).await?; - let root_signature = Signature::new(SignatureType::RootSign, root_signature); + let root_signature = + IdentityChangeSignature::new(SignatureType::RootSign, root_signature); signatures.push(root_signature); } @@ -118,15 +127,13 @@ impl Identity { pub(crate) async fn make_create_key_change( &self, secret: Option<&KeyId>, + key_label: String, key_attributes: KeyAttributes, ) -> Result { let change_history = self.change_history.read().await; // Creating key after it was revoked is forbidden - if IdentityChangeHistory::find_last_key_change( - change_history.as_ref(), - key_attributes.label(), - ) - .is_ok() + if IdentityChangeHistory::find_last_key_change(change_history.as_ref(), key_label.as_str()) + .is_ok() { return Err(InvalidInternalState.into()); } @@ -139,7 +146,14 @@ impl Identity { let root_secret = self.get_root_secret_key().await?; let root_key = Some(&root_secret); - Self::make_create_key_change_static(secret, prev_id, key_attributes, root_key, &self.vault) - .await + Self::make_create_key_change_static( + secret, + prev_id, + key_label, + key_attributes, + root_key, + &self.vault, + ) + .await } } diff --git a/implementations/rust/ockam/ockam_identity/src/change/rotate_key.rs b/implementations/rust/ockam/ockam_identity/src/change/rotate_key.rs index f9a671b064f..7d152228fcc 100644 --- a/implementations/rust/ockam/ockam_identity/src/change/rotate_key.rs +++ b/implementations/rust/ockam/ockam_identity/src/change/rotate_key.rs @@ -1,21 +1,18 @@ use crate::authenticated_storage::AuthenticatedStorage; -use crate::change::{IdentityChange, IdentitySignedChange, Signature, SignatureType}; +use crate::change::{IdentityChange, IdentityChangeSignature, IdentitySignedChange, SignatureType}; use crate::change_history::IdentityChangeHistory; -use crate::{ChangeIdentifier, Identity, IdentityError, IdentityVault, KeyAttributes}; +use crate::{ChangeIdentifier, Identity, IdentityError, IdentityVault}; use core::fmt; -use ockam_core::vault::PublicKey; +use ockam_core::compat::string::String; +use ockam_core::vault::{KeyAttributes, PublicKey}; use ockam_core::{Encodable, Result}; use serde::{Deserialize, Serialize}; -/// RotateKeyChangeData -#[derive(Serialize, Deserialize, Debug, Clone)] -pub struct RotateKeyChangeData { - prev_change_id: ChangeIdentifier, - key_attributes: KeyAttributes, - public_key: PublicKey, -} - impl RotateKeyChangeData { + /// Return key label + pub fn key_label(&self) -> &String { + &self.key_label + } /// Return key attributes pub fn key_attributes(&self) -> &KeyAttributes { &self.key_attributes @@ -30,15 +27,26 @@ impl RotateKeyChangeData { } } +/// RotateKeyChangeData +#[derive(Serialize, Deserialize, Debug, Clone)] +pub struct RotateKeyChangeData { + prev_change_id: ChangeIdentifier, + key_label: String, + key_attributes: KeyAttributes, + public_key: PublicKey, +} + impl RotateKeyChangeData { /// Create RotateKeyChangeData pub fn new( prev_change_id: ChangeIdentifier, + key_label: String, key_attributes: KeyAttributes, public_key: PublicKey, ) -> Self { Self { prev_change_id, + key_label, key_attributes, public_key, } @@ -49,8 +57,9 @@ impl fmt::Display for RotateKeyChangeData { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!( f, - "prev_change_id:{} key attibutes:{} public key:{}", + "prev_change_id:{} key label:{} key attributes:{} public key:{}", self.prev_change_id(), + self.key_label(), self.key_attributes(), self.public_key() ) @@ -61,6 +70,7 @@ impl Identity { /// Rotate key change pub(crate) async fn make_rotate_key_change( &self, + key_label: String, key_attributes: KeyAttributes, ) -> Result { let change_history = self.change_history.read().await; @@ -68,19 +78,22 @@ impl Identity { let last_change_in_chain = IdentityChangeHistory::find_last_key_change( change_history.as_ref(), - key_attributes.label(), + key_label.as_str(), )? .clone(); let last_key_in_chain = Self::get_secret_key_from_change(&last_change_in_chain, &self.vault).await?; - let secret_attributes = key_attributes.secret_attributes(); + let secret_key = self.vault.generate_key(key_attributes).await?; + let public_key = self.vault.get_public_key(&secret_key).await?; - let secret_key = self.vault.secret_generate(secret_attributes).await?; - let public_key = self.vault.secret_public_key_get(&secret_key).await?; - - let data = RotateKeyChangeData::new(prev_change_id, key_attributes, public_key); + let data = RotateKeyChangeData::new( + prev_change_id, + key_label.clone(), + key_attributes, + public_key, + ); let change_block = IdentityChange::RotateKey(data); let change_block_binary = change_block @@ -91,18 +104,18 @@ impl Identity { let change_id = ChangeIdentifier::from_hash(change_id); let self_signature = self.vault.sign(&secret_key, change_id.as_ref()).await?; - let self_signature = Signature::new(SignatureType::SelfSign, self_signature); + let self_signature = IdentityChangeSignature::new(SignatureType::SelfSign, self_signature); let root_key = self.get_root_secret_key().await?; let root_signature = self.vault.sign(&root_key, change_id.as_ref()).await?; - let root_signature = Signature::new(SignatureType::RootSign, root_signature); + let root_signature = IdentityChangeSignature::new(SignatureType::RootSign, root_signature); let prev_signature = self .vault .sign(&last_key_in_chain, change_id.as_ref()) .await?; - let prev_signature = Signature::new(SignatureType::PrevSign, prev_signature); + let prev_signature = IdentityChangeSignature::new(SignatureType::PrevSign, prev_signature); let signed_change = IdentitySignedChange::new( change_id, diff --git a/implementations/rust/ockam/ockam_identity/src/identity.rs b/implementations/rust/ockam/ockam_identity/src/identity.rs index 1fd250e5d23..f7f42386009 100644 --- a/implementations/rust/ockam/ockam_identity/src/identity.rs +++ b/implementations/rust/ockam/ockam_identity/src/identity.rs @@ -4,8 +4,8 @@ use crate::change::IdentitySignedChange; use crate::change_history::{IdentityChangeHistory, IdentityHistoryComparison}; use crate::credential::Credential; use crate::{ - ChangeIdentifier, IdentityError, IdentityIdentifier, IdentityVault, KeyAttributes, - PublicIdentity, SecureChannelRegistry, + ChangeIdentifier, IdentityError, IdentityIdentifier, IdentityVault, PublicIdentity, + SecureChannelRegistry, }; use ockam_core::compat::{ boxed::Box, @@ -13,12 +13,12 @@ use ockam_core::compat::{ sync::Arc, vec::Vec, }; -use ockam_core::vault::{SecretPersistence, SecretType, Signature, CURVE25519_SECRET_LENGTH_U32}; +use ockam_core::vault::{KeyPersistence, KeyType, Signature, CURVE25519_SECRET_LENGTH_U32}; use ockam_core::{Address, Result}; use ockam_core::{AsyncTryClone, DenyAll}; use ockam_node::compat::asynchronous::RwLock; use ockam_node::Context; -use ockam_vault::{KeyId, SecretAttributes}; +use ockam_vault::{KeyAttributes, KeyId}; /// Identity implementation #[derive(AsyncTryClone)] @@ -111,7 +111,8 @@ impl Identity { secure_channel_registry: SecureChannelRegistry, vault: &V, kid: Option<&KeyId>, - key_attribs: KeyAttributes, + key_label: String, + key_attributes: KeyAttributes, ) -> Result { let child_ctx = ctx .new_detached( @@ -125,7 +126,8 @@ impl Identity { let create_key_change = Self::make_create_key_change_static( kid, initial_change_id, - key_attribs.clone(), + key_label, + key_attributes, None, vault, ) @@ -162,12 +164,9 @@ impl Identity { /// Create an `Identity`. Extended version pub async fn create_ext(ctx: &Context, authenticated_storage: &S, vault: &V) -> Result { let attrs = KeyAttributes::new( - IdentityStateConst::ROOT_LABEL.to_string(), - SecretAttributes::new( - SecretType::Ed25519, - SecretPersistence::Persistent, - CURVE25519_SECRET_LENGTH_U32, - ), + KeyType::Ed25519, + KeyPersistence::Persistent, + CURVE25519_SECRET_LENGTH_U32, ); Self::create_impl( ctx, @@ -175,6 +174,7 @@ impl Identity { SecureChannelRegistry::new(), vault, None, + IdentityStateConst::ROOT_LABEL.to_string(), attrs, ) .await @@ -186,6 +186,7 @@ impl Identity { authenticated_storage: &S, vault: &V, kid: &KeyId, + label: String, attrs: KeyAttributes, ) -> Result { Self::create_impl( @@ -194,6 +195,7 @@ impl Identity { SecureChannelRegistry::new(), vault, Some(kid), + label, attrs, ) .await @@ -204,12 +206,9 @@ impl Identity { /// Create an `Identity` with a new secret key and `InMemoryStorage` pub async fn create(ctx: &Context, vault: &V) -> Result { let attrs = KeyAttributes::new( - IdentityStateConst::ROOT_LABEL.to_string(), - SecretAttributes::new( - SecretType::Ed25519, - SecretPersistence::Persistent, - CURVE25519_SECRET_LENGTH_U32, - ), + KeyType::Ed25519, + KeyPersistence::Persistent, + CURVE25519_SECRET_LENGTH_U32, ); Self::create_impl( ctx, @@ -217,6 +216,7 @@ impl Identity { SecureChannelRegistry::new(), vault, None, + IdentityStateConst::ROOT_LABEL.to_string(), attrs, ) .await @@ -227,6 +227,7 @@ impl Identity { ctx: &Context, vault: &V, kid: &KeyId, + label: String, attrs: KeyAttributes, ) -> Result { Self::create_impl( @@ -235,6 +236,7 @@ impl Identity { SecureChannelRegistry::new(), vault, Some(kid), + label, attrs, ) .await @@ -311,20 +313,19 @@ impl Identity { /// Generate and add a new key to this `Identity` with a given `label` pub async fn create_key(&self, label: String) -> Result<()> { - let key_attribs = KeyAttributes::default_with_label(label); - - let change = self.make_create_key_change(None, key_attribs).await?; + let change = self + .make_create_key_change(None, label, KeyAttributes::default_attributes()) + .await?; self.add_change(change).await } /// Add a new key to this `Identity` with a given `label` - pub async fn add_key(&self, label: String, secret: &KeyId) -> Result<()> { - let secret_attributes = self.vault.secret_attributes_get(secret).await?; - let key_attribs = KeyAttributes::new(label, secret_attributes); + pub async fn add_key(&self, label: String, key_id: &KeyId) -> Result<()> { + let key_attributes = self.vault.get_key_attributes(key_id).await?; let change = self - .make_create_key_change(Some(secret), key_attribs) + .make_create_key_change(Some(key_id), label, key_attributes) .await?; self.add_change(change).await @@ -333,7 +334,7 @@ impl Identity { /// Rotate an existing key with a given label pub async fn rotate_key(&self, label: &str) -> Result<()> { let change = self - .make_rotate_key_change(KeyAttributes::default_with_label(label.to_string())) + .make_rotate_key_change(label.to_string(), KeyAttributes::default_attributes()) .await?; self.add_change(change).await @@ -342,9 +343,10 @@ impl Identity { /// Rotate this `Identity` root key pub async fn rotate_root_key(&self) -> Result<()> { let change = self - .make_rotate_key_change(KeyAttributes::default_with_label( + .make_rotate_key_change( IdentityStateConst::ROOT_LABEL.to_string(), - )) + KeyAttributes::default_attributes(), + ) .await?; self.add_change(change).await diff --git a/implementations/rust/ockam/ockam_identity/src/invalid_signatures_tests.rs b/implementations/rust/ockam/ockam_identity/src/invalid_signatures_tests.rs index 007cb2568ac..2e80679686e 100644 --- a/implementations/rust/ockam/ockam_identity/src/invalid_signatures_tests.rs +++ b/implementations/rust/ockam/ockam_identity/src/invalid_signatures_tests.rs @@ -3,8 +3,8 @@ use crate::change::IdentitySignedChange; use crate::change_history::IdentityChangeHistory; use crate::{Identity, IdentityVault, PublicIdentity}; use ockam_core::vault::{ - AsymmetricVault, Buffer, Hasher, KeyId, PublicKey, Secret, SecretAttributes, SecretVault, - Signature, Signer, SmallBuffer, SymmetricVault, Verifier, + AsymmetricVault, Buffer, Hasher, Key, KeyAttributes, KeyId, KeyVault, PublicKey, Signature, + Signer, SmallBuffer, SymmetricVault, Verifier, }; use ockam_core::{async_trait, compat::boxed::Box}; use ockam_core::{AsyncTryClone, Result}; @@ -113,29 +113,29 @@ impl CrazyVault { } #[async_trait] -impl SecretVault for CrazyVault { - async fn secret_generate(&self, attributes: SecretAttributes) -> Result { - self.vault.secret_generate(attributes).await +impl KeyVault for CrazyVault { + async fn generate_key(&self, attributes: KeyAttributes) -> Result { + self.vault.generate_key(attributes).await } - async fn secret_import(&self, secret: Secret, attributes: SecretAttributes) -> Result { - self.vault.secret_import(secret, attributes).await + async fn import_key(&self, secret: Key, attributes: KeyAttributes) -> Result { + self.vault.import_key(secret, attributes).await } - async fn secret_export(&self, key_id: &KeyId) -> Result { - self.vault.secret_export(key_id).await + async fn export_key(&self, key_id: &KeyId) -> Result { + self.vault.export_key(key_id).await } - async fn secret_attributes_get(&self, key_id: &KeyId) -> Result { - self.vault.secret_attributes_get(key_id).await + async fn get_key_attributes(&self, key_id: &KeyId) -> Result { + self.vault.get_key_attributes(key_id).await } - async fn secret_public_key_get(&self, key_id: &KeyId) -> Result { - self.vault.secret_public_key_get(key_id).await + async fn get_public_key(&self, key_id: &KeyId) -> Result { + self.vault.get_public_key(key_id).await } - async fn secret_destroy(&self, key_id: KeyId) -> Result<()> { - self.vault.secret_destroy(key_id).await + async fn destroy_key(&self, key_id: KeyId) -> Result<()> { + self.vault.destroy_key(key_id).await } } @@ -177,7 +177,7 @@ impl Hasher for CrazyVault { salt: &KeyId, info: &[u8], ikm: Option<&KeyId>, - output_attributes: SmallBuffer, + output_attributes: SmallBuffer, ) -> Result> { self.vault .hkdf_sha256(salt, info, ikm, output_attributes) diff --git a/implementations/rust/ockam/ockam_identity/src/key_attributes.rs b/implementations/rust/ockam/ockam_identity/src/key_attributes.rs deleted file mode 100644 index f63b61fc043..00000000000 --- a/implementations/rust/ockam/ockam_identity/src/key_attributes.rs +++ /dev/null @@ -1,55 +0,0 @@ -use core::fmt; -use ockam_core::compat::string::String; -use ockam_core::vault::{SecretPersistence, SecretType, CURVE25519_SECRET_LENGTH_U32}; -use ockam_vault::SecretAttributes; -use serde::{Deserialize, Serialize}; - -/// Attributes that are used to identify a key -#[derive(Serialize, Deserialize, Debug, Clone, Eq, PartialEq)] -pub struct KeyAttributes { - label: String, - secret_attributes: SecretAttributes, -} - -impl KeyAttributes { - /// Human-readable key name - pub fn label(&self) -> &str { - &self.label - } - /// `SecretAttributes` of the key - pub fn secret_attributes(&self) -> SecretAttributes { - self.secret_attributes - } -} - -impl KeyAttributes { - /// Default key with given label. (Ed25519, Persistent) - pub fn default_with_label(label: impl Into) -> Self { - Self::new( - label.into(), - SecretAttributes::new( - SecretType::Ed25519, - SecretPersistence::Persistent, - CURVE25519_SECRET_LENGTH_U32, - ), - ) - } - - /// Constructor - pub fn new(label: String, secret_attributes: SecretAttributes) -> Self { - Self { - label, - secret_attributes, - } - } -} -impl fmt::Display for KeyAttributes { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!( - f, - " label:{}, secrets:{}", - self.label(), - self.secret_attributes() - ) - } -} diff --git a/implementations/rust/ockam/ockam_identity/src/lib.rs b/implementations/rust/ockam/ockam_identity/src/lib.rs index 2eede7559af..015678ca960 100644 --- a/implementations/rust/ockam/ockam_identity/src/lib.rs +++ b/implementations/rust/ockam/ockam_identity/src/lib.rs @@ -19,7 +19,7 @@ extern crate core; extern crate alloc; use ockam_core::AsyncTryClone; -use ockam_vault::{Hasher, SecretVault, Signer, Verifier}; +use ockam_vault::{Hasher, KeyVault, Signer, Verifier}; use crate::IdentityError; @@ -44,14 +44,12 @@ mod channel; mod identifiers; mod identity; mod identity_builder; -mod key_attributes; mod public_identity; pub use channel::*; pub use identifiers::*; pub use identity::*; pub use identity_builder::*; -pub use key_attributes::*; pub use public_identity::*; mod signature; @@ -61,18 +59,11 @@ mod invalid_signatures_tests; /// Traits required for a Vault implementation suitable for use in an Identity pub trait IdentityVault: - SecretVault + SecureChannelVault + Hasher + Signer + Verifier + AsyncTryClone + Send + 'static + KeyVault + SecureChannelVault + Hasher + Signer + Verifier + AsyncTryClone + Send + 'static { } impl IdentityVault for D where - D: SecretVault - + SecureChannelVault - + Hasher - + Signer - + Verifier - + AsyncTryClone - + Send - + 'static + D: KeyVault + SecureChannelVault + Hasher + Signer + Verifier + AsyncTryClone + Send + 'static { } diff --git a/implementations/rust/ockam/ockam_identity/src/signature.rs b/implementations/rust/ockam/ockam_identity/src/signature.rs index 303a84a9823..dc006c0beca 100644 --- a/implementations/rust/ockam/ockam_identity/src/signature.rs +++ b/implementations/rust/ockam/ockam_identity/src/signature.rs @@ -1,5 +1,5 @@ use core::fmt; -use ockam_core::vault::Signature as OckamVaultSignature; +use ockam_core::vault::Signature; use serde::{Deserialize, Serialize}; /// Types of proof signatures. @@ -15,30 +15,30 @@ pub enum SignatureType { /// Signature, its type and data #[derive(Serialize, Deserialize, Debug, Clone)] -pub struct Signature { +pub struct IdentityChangeSignature { stype: SignatureType, - data: OckamVaultSignature, + data: Signature, } -impl Signature { +impl IdentityChangeSignature { /// Return the signature type pub fn stype(&self) -> &SignatureType { &self.stype } /// Return signature data - pub fn data(&self) -> &OckamVaultSignature { + pub fn data(&self) -> &Signature { &self.data } } -impl Signature { +impl IdentityChangeSignature { /// Create a new signature - pub fn new(stype: SignatureType, data: OckamVaultSignature) -> Self { - Signature { stype, data } + pub fn new(stype: SignatureType, data: Signature) -> Self { + IdentityChangeSignature { stype, data } } } -impl fmt::Display for Signature { +impl fmt::Display for IdentityChangeSignature { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{:?} {}", self.stype(), hex::encode(self.data())) } diff --git a/implementations/rust/ockam/ockam_identity/tests/tests.rs b/implementations/rust/ockam/ockam_identity/tests/tests.rs index ef2ba3ab794..b41110a1217 100644 --- a/implementations/rust/ockam/ockam_identity/tests/tests.rs +++ b/implementations/rust/ockam/ockam_identity/tests/tests.rs @@ -1,5 +1,5 @@ use ockam_core::errcode::{Kind, Origin}; -use ockam_core::vault::{SecretAttributes, SecretPersistence, SecretType, SecretVault}; +use ockam_core::vault::{KeyAttributes, KeyPersistence, KeyType, KeyVault}; use ockam_core::{Error, Result}; use ockam_identity::Identity; use ockam_node::Context; @@ -147,9 +147,9 @@ async fn add_key(ctx: &mut Context) -> Result<()> { let e = Identity::create(ctx, &vault).await?; let key = vault - .secret_generate(SecretAttributes::new( - SecretType::Ed25519, - SecretPersistence::Ephemeral, + .generate_key(KeyAttributes::new( + KeyType::Ed25519, + KeyPersistence::Ephemeral, 32, )) .await?; diff --git a/implementations/rust/ockam/ockam_key_exchange_x3dh/src/initiator.rs b/implementations/rust/ockam/ockam_key_exchange_x3dh/src/initiator.rs index ff5bffdef06..abe5094594e 100644 --- a/implementations/rust/ockam/ockam_key_exchange_x3dh/src/initiator.rs +++ b/implementations/rust/ockam/ockam_key_exchange_x3dh/src/initiator.rs @@ -2,7 +2,7 @@ use crate::{PreKeyBundle, X3DHError, X3dhVault, CSUITE}; use alloc::vec; use ockam_core::vault::Signature as GenericSignature; use ockam_core::vault::{ - KeyId, SecretAttributes, SecretPersistence, SecretType, AES256_SECRET_LENGTH_U32, + KeyAttributes, KeyId, KeyPersistence, KeyType, AES256_SECRET_LENGTH_U32, CURVE25519_SECRET_LENGTH_U32, }; use ockam_core::Result; @@ -12,7 +12,7 @@ use ockam_core::{ string::{String, ToString}, vec::Vec, }, - vault::{Secret, SecretKey}, + vault::{Key, PrivateKey}, }; use ockam_key_exchange_core::{CompletedKeyExchange, KeyExchanger}; @@ -48,13 +48,13 @@ impl Initiator { async fn prologue(&mut self) -> Result<()> { if self.identity_key.is_none() { - let p_atts = SecretAttributes::new( - SecretType::X25519, - SecretPersistence::Persistent, + let p_atts = KeyAttributes::new( + KeyType::X25519, + KeyPersistence::Persistent, CURVE25519_SECRET_LENGTH_U32, ); - self.identity_key = Some(self.vault.secret_generate(p_atts).await?); + self.identity_key = Some(self.vault.generate_key(p_atts).await?); } Ok(()) } @@ -85,20 +85,17 @@ impl KeyExchanger for Initiator { InitiatorState::GenerateEphemeralIdentityKey => { self.prologue().await?; let identity_key = self.identity_key.as_ref().ok_or(X3DHError::InvalidState)?; - let pubkey = self.vault.secret_public_key_get(identity_key).await?; + let pubkey = self.vault.get_public_key(identity_key).await?; let ephemeral_identity_key = self .vault - .secret_generate(SecretAttributes::new( - SecretType::X25519, - SecretPersistence::Ephemeral, + .generate_key(KeyAttributes::new( + KeyType::X25519, + KeyPersistence::Ephemeral, CURVE25519_SECRET_LENGTH_U32, )) .await?; - let ephemeral_pubkey = self - .vault - .secret_public_key_get(&ephemeral_identity_key) - .await?; + let ephemeral_pubkey = self.vault.get_public_key(&ephemeral_identity_key).await?; self.ephemeral_identity_key = Some(ephemeral_identity_key); self.state = InitiatorState::ProcessPreKeyBundle; @@ -151,45 +148,37 @@ impl KeyExchanger for Initiator { .ec_diffie_hellman(ephemeral_identity_key, &prekey_bundle.one_time_prekey) .await?; let mut ikm_bytes = vec![0xFFu8; 32]; // FIXME: Why is it here? - ikm_bytes.extend_from_slice( - self.vault.secret_export(&dh1).await?.try_as_key()?.as_ref(), - ); - ikm_bytes.extend_from_slice( - self.vault.secret_export(&dh2).await?.try_as_key()?.as_ref(), - ); - ikm_bytes.extend_from_slice( - self.vault.secret_export(&dh3).await?.try_as_key()?.as_ref(), - ); - ikm_bytes.extend_from_slice( - self.vault.secret_export(&dh4).await?.try_as_key()?.as_ref(), - ); + ikm_bytes + .extend_from_slice(self.vault.export_key(&dh1).await?.try_as_key()?.as_ref()); + ikm_bytes + .extend_from_slice(self.vault.export_key(&dh2).await?.try_as_key()?.as_ref()); + ikm_bytes + .extend_from_slice(self.vault.export_key(&dh3).await?.try_as_key()?.as_ref()); + ikm_bytes + .extend_from_slice(self.vault.export_key(&dh4).await?.try_as_key()?.as_ref()); let ikm = self .vault - .secret_import( - Secret::Key(SecretKey::new(ikm_bytes.clone())), - SecretAttributes::new( - SecretType::Buffer, - SecretPersistence::Ephemeral, + .import_key( + Key::Key(PrivateKey::new(ikm_bytes.clone())), + KeyAttributes::new( + KeyType::Buffer, + KeyPersistence::Ephemeral, ikm_bytes.len() as u32, ), ) .await?; let salt = self .vault - .secret_import( - Secret::Key(SecretKey::new(vec![0u8; 32])), - SecretAttributes::new( - SecretType::Buffer, - SecretPersistence::Ephemeral, - 32u32, - ), + .import_key( + Key::Key(PrivateKey::new(vec![0u8; 32])), + KeyAttributes::new(KeyType::Buffer, KeyPersistence::Ephemeral, 32u32), ) .await?; - let atts = SecretAttributes::new( - SecretType::Aes, - SecretPersistence::Persistent, + let atts = KeyAttributes::new( + KeyType::Aes, + KeyPersistence::Persistent, AES256_SECRET_LENGTH_U32, ); diff --git a/implementations/rust/ockam/ockam_key_exchange_x3dh/src/lib.rs b/implementations/rust/ockam/ockam_key_exchange_x3dh/src/lib.rs index 876cca1252d..d9b483a6ca7 100644 --- a/implementations/rust/ockam/ockam_key_exchange_x3dh/src/lib.rs +++ b/implementations/rust/ockam/ockam_key_exchange_x3dh/src/lib.rs @@ -8,7 +8,7 @@ extern crate alloc; use arrayref::array_ref; use ockam_core::vault::{ - AsymmetricVault, Hasher, PublicKey, SecretType, SecretVault, Signer, SymmetricVault, Verifier, + AsymmetricVault, Hasher, KeyType, KeyVault, PublicKey, Signer, SymmetricVault, Verifier, }; use ockam_core::{compat::vec::Vec, AsyncTryClone}; use zeroize::Zeroize; @@ -83,11 +83,10 @@ impl TryFrom<&[u8]> for PreKeyBundle { if data.len() != Self::SIZE { return Err(X3DHError::MessageLenMismatch.into()); } - let identity_key = PublicKey::new(array_ref![data, 0, 32].to_vec(), SecretType::X25519); - let signed_prekey = PublicKey::new(array_ref![data, 32, 32].to_vec(), SecretType::X25519); + let identity_key = PublicKey::new(array_ref![data, 0, 32].to_vec(), KeyType::X25519); + let signed_prekey = PublicKey::new(array_ref![data, 32, 32].to_vec(), KeyType::X25519); let signature_prekey = Signature(*array_ref![data, 64, 64]); - let one_time_prekey = - PublicKey::new(array_ref![data, 128, 32].to_vec(), SecretType::X25519); + let one_time_prekey = PublicKey::new(array_ref![data, 128, 32].to_vec(), KeyType::X25519); Ok(Self { identity_key, signed_prekey, @@ -101,7 +100,7 @@ const CSUITE: &[u8] = b"X3DH_25519_AESGCM_SHA256\0\0\0\0\0\0\0\0"; /// Vault with X3DH required functionality pub trait X3dhVault: - SecretVault + KeyVault + Signer + Verifier + AsymmetricVault @@ -115,7 +114,7 @@ pub trait X3dhVault: } impl X3dhVault for D where - D: SecretVault + D: KeyVault + Signer + Verifier + AsymmetricVault @@ -167,13 +166,13 @@ mod tests { assert_eq!(initiator.h(), responder.h()); - let s1 = vault.secret_export(initiator.encrypt_key()).await?; - let s2 = vault.secret_export(responder.decrypt_key()).await?; + let s1 = vault.export_key(initiator.encrypt_key()).await?; + let s2 = vault.export_key(responder.decrypt_key()).await?; assert_eq!(s1, s2); - let s1 = vault.secret_export(initiator.decrypt_key()).await?; - let s2 = vault.secret_export(responder.encrypt_key()).await?; + let s1 = vault.export_key(initiator.decrypt_key()).await?; + let s2 = vault.export_key(responder.encrypt_key()).await?; assert_eq!(s1, s2); ctx.stop().await diff --git a/implementations/rust/ockam/ockam_key_exchange_x3dh/src/responder.rs b/implementations/rust/ockam/ockam_key_exchange_x3dh/src/responder.rs index 82ef61c785c..533dde61f1a 100644 --- a/implementations/rust/ockam/ockam_key_exchange_x3dh/src/responder.rs +++ b/implementations/rust/ockam/ockam_key_exchange_x3dh/src/responder.rs @@ -2,7 +2,7 @@ use crate::{PreKeyBundle, Signature, X3DHError, X3dhVault, CSUITE}; use alloc::vec; use arrayref::array_ref; use ockam_core::vault::{ - KeyId, PublicKey, SecretAttributes, SecretPersistence, SecretType, AES256_SECRET_LENGTH_U32, + KeyAttributes, KeyId, KeyPersistence, KeyType, PublicKey, AES256_SECRET_LENGTH_U32, CURVE25519_SECRET_LENGTH_U32, }; use ockam_core::Result; @@ -12,7 +12,7 @@ use ockam_core::{ string::{String, ToString}, vec::Vec, }, - vault::{Secret, SecretKey}, + vault::{Key, PrivateKey}, }; use ockam_key_exchange_core::{CompletedKeyExchange, KeyExchanger}; @@ -50,21 +50,21 @@ impl Responder { } async fn prologue(&mut self) -> Result<()> { - let p_atts = SecretAttributes::new( - SecretType::X25519, - SecretPersistence::Persistent, + let p_atts = KeyAttributes::new( + KeyType::X25519, + KeyPersistence::Persistent, CURVE25519_SECRET_LENGTH_U32, ); - let e_atts = SecretAttributes::new( - SecretType::X25519, - SecretPersistence::Ephemeral, + let e_atts = KeyAttributes::new( + KeyType::X25519, + KeyPersistence::Ephemeral, CURVE25519_SECRET_LENGTH_U32, ); if self.identity_key.is_none() { - self.identity_key = Some(self.vault.secret_generate(p_atts).await?); + self.identity_key = Some(self.vault.generate_key(p_atts).await?); } - self.signed_prekey = Some(self.vault.secret_generate(p_atts).await?); - self.one_time_prekey = Some(self.vault.secret_generate(e_atts).await?); + self.signed_prekey = Some(self.vault.generate_key(p_atts).await?); + self.one_time_prekey = Some(self.vault.generate_key(e_atts).await?); Ok(()) } } @@ -104,16 +104,13 @@ impl KeyExchanger for Responder { .one_time_prekey .as_ref() .ok_or(X3DHError::InvalidState)?; - let signed_prekey_pub = self.vault.secret_public_key_get(signed_prekey).await?; + let signed_prekey_pub = self.vault.get_public_key(signed_prekey).await?; let signature = self .vault .sign(identity_secret_key, signed_prekey_pub.data()) .await?; - let identity_key = self - .vault - .secret_public_key_get(identity_secret_key) - .await?; - let one_time_prekey_pub = self.vault.secret_public_key_get(one_time_prekey).await?; + let identity_key = self.vault.get_public_key(identity_secret_key).await?; + let one_time_prekey_pub = self.vault.get_public_key(one_time_prekey).await?; if signature.as_ref().len() != 64 { return Err(X3DHError::SignatureLenMismatch.into()); } @@ -142,9 +139,9 @@ impl KeyExchanger for Responder { self.prologue().await?; let other_identity_pubkey = - PublicKey::new(array_ref![response, 0, 32].to_vec(), SecretType::X25519); + PublicKey::new(array_ref![response, 0, 32].to_vec(), KeyType::X25519); let other_ephemeral_pubkey = - PublicKey::new(array_ref![response, 32, 32].to_vec(), SecretType::X25519); + PublicKey::new(array_ref![response, 32, 32].to_vec(), KeyType::X25519); let signed_prekey = self.signed_prekey.as_ref().ok_or(X3DHError::InvalidState)?; let one_time_prekey = self @@ -172,44 +169,36 @@ impl KeyExchanger for Responder { .ec_diffie_hellman(one_time_prekey, &other_ephemeral_pubkey) .await?; let mut ikm_bytes = vec![0xFFu8; 32]; // FIXME - ikm_bytes.extend_from_slice( - self.vault.secret_export(&dh1).await?.try_as_key()?.as_ref(), - ); - ikm_bytes.extend_from_slice( - self.vault.secret_export(&dh2).await?.try_as_key()?.as_ref(), - ); - ikm_bytes.extend_from_slice( - self.vault.secret_export(&dh3).await?.try_as_key()?.as_ref(), - ); - ikm_bytes.extend_from_slice( - self.vault.secret_export(&dh4).await?.try_as_key()?.as_ref(), - ); + ikm_bytes + .extend_from_slice(self.vault.export_key(&dh1).await?.try_as_key()?.as_ref()); + ikm_bytes + .extend_from_slice(self.vault.export_key(&dh2).await?.try_as_key()?.as_ref()); + ikm_bytes + .extend_from_slice(self.vault.export_key(&dh3).await?.try_as_key()?.as_ref()); + ikm_bytes + .extend_from_slice(self.vault.export_key(&dh4).await?.try_as_key()?.as_ref()); let ikm = self .vault - .secret_import( - Secret::Key(SecretKey::new(ikm_bytes.clone())), - SecretAttributes::new( - SecretType::Buffer, - SecretPersistence::Ephemeral, + .import_key( + Key::Key(PrivateKey::new(ikm_bytes.clone())), + KeyAttributes::new( + KeyType::Buffer, + KeyPersistence::Ephemeral, ikm_bytes.len() as u32, ), ) .await?; let salt = self .vault - .secret_import( - Secret::Key(SecretKey::new(vec![0u8; 32])), - SecretAttributes::new( - SecretType::Buffer, - SecretPersistence::Ephemeral, - 32u32, - ), + .import_key( + Key::Key(PrivateKey::new(vec![0u8; 32])), + KeyAttributes::new(KeyType::Buffer, KeyPersistence::Ephemeral, 32u32), ) .await?; - let atts = SecretAttributes::new( - SecretType::Aes, - SecretPersistence::Persistent, + let atts = KeyAttributes::new( + KeyType::Aes, + KeyPersistence::Persistent, AES256_SECRET_LENGTH_U32, ); diff --git a/implementations/rust/ockam/ockam_key_exchange_xx/src/lib.rs b/implementations/rust/ockam/ockam_key_exchange_xx/src/lib.rs index a3868d101bb..db9cc3ce868 100644 --- a/implementations/rust/ockam/ockam_key_exchange_xx/src/lib.rs +++ b/implementations/rust/ockam/ockam_key_exchange_xx/src/lib.rs @@ -39,19 +39,12 @@ pub const AES_GCM_TAGSIZE_USIZE: usize = 16; /// Vault with XX required functionality pub trait XXVault: - SecretVault + Hasher + AsymmetricVault + SymmetricVault + AsyncTryClone + Send + Sync + 'static + KeyVault + Hasher + AsymmetricVault + SymmetricVault + AsyncTryClone + Send + Sync + 'static { } impl XXVault for D where - D: SecretVault - + Hasher - + AsymmetricVault - + SymmetricVault - + AsyncTryClone - + Send - + Sync - + 'static + D: KeyVault + Hasher + AsymmetricVault + SymmetricVault + AsyncTryClone + Send + Sync + 'static { } @@ -62,7 +55,7 @@ mod responder; pub use responder::*; mod new_key_exchanger; pub use new_key_exchanger::*; -use ockam_core::vault::{AsymmetricVault, Hasher, SecretVault, SymmetricVault}; +use ockam_core::vault::{AsymmetricVault, Hasher, KeyVault, SymmetricVault}; #[cfg(test)] mod tests { @@ -103,13 +96,13 @@ mod tests { assert_eq!(initiator.h(), responder.h()); - let s1 = vault.secret_export(initiator.encrypt_key()).await.unwrap(); - let s2 = vault.secret_export(responder.decrypt_key()).await.unwrap(); + let s1 = vault.export_key(initiator.encrypt_key()).await.unwrap(); + let s2 = vault.export_key(responder.decrypt_key()).await.unwrap(); assert_eq!(s1, s2); - let s1 = vault.secret_export(initiator.decrypt_key()).await.unwrap(); - let s2 = vault.secret_export(responder.encrypt_key()).await.unwrap(); + let s1 = vault.export_key(initiator.decrypt_key()).await.unwrap(); + let s2 = vault.export_key(responder.encrypt_key()).await.unwrap(); assert_eq!(s1, s2); diff --git a/implementations/rust/ockam/ockam_key_exchange_xx/src/state.rs b/implementations/rust/ockam/ockam_key_exchange_xx/src/state.rs index c3ff0815306..cc87e2a378a 100644 --- a/implementations/rust/ockam/ockam_key_exchange_xx/src/state.rs +++ b/implementations/rust/ockam/ockam_key_exchange_xx/src/state.rs @@ -1,6 +1,6 @@ use crate::{XXError, XXVault, AES_GCM_TAGSIZE_USIZE, SHA256_SIZE_USIZE}; use ockam_core::vault::{ - KeyId, PublicKey, SecretAttributes, SecretPersistence, SecretType, AES256_SECRET_LENGTH_U32, + KeyAttributes, KeyId, KeyPersistence, KeyType, PublicKey, AES256_SECRET_LENGTH_U32, CURVE25519_PUBLIC_LENGTH_USIZE, CURVE25519_SECRET_LENGTH_U32, }; use ockam_core::{compat::vec::Vec, Result}; @@ -56,8 +56,8 @@ impl State { } impl State { - fn get_symmetric_key_type_and_length(&self) -> (SecretType, u32) { - (SecretType::Aes, AES256_SECRET_LENGTH_U32) + fn get_symmetric_key_type_and_length(&self) -> (KeyType, u32) { + (KeyType::Aes, AES256_SECRET_LENGTH_U32) } fn get_protocol_name(&self) -> &'static [u8] { @@ -66,31 +66,24 @@ impl State { /// Create a new `HandshakeState` starting with the prologue async fn prologue(&mut self) -> Result<()> { - let attributes = SecretAttributes::new( - SecretType::X25519, - SecretPersistence::Ephemeral, + let attributes = KeyAttributes::new( + KeyType::X25519, + KeyPersistence::Ephemeral, CURVE25519_SECRET_LENGTH_U32, ); // 1. Generate a static key pair for this handshake and set it to `s` if let Some(ik) = &self.identity_key { - self.identity_public_key = Some(self.vault.secret_public_key_get(ik).await?); + self.identity_public_key = Some(self.vault.get_public_key(ik).await?); } else { - let static_secret_handle = self.vault.secret_generate(attributes).await?; - self.identity_public_key = Some( - self.vault - .secret_public_key_get(&static_secret_handle) - .await?, - ); + let static_secret_handle = self.vault.generate_key(attributes).await?; + self.identity_public_key = + Some(self.vault.get_public_key(&static_secret_handle).await?); self.identity_key = Some(static_secret_handle) }; // 2. Generate an ephemeral key pair for this handshake and set it to e - let ephemeral_secret_handle = self.vault.secret_generate(attributes).await?; - self.ephemeral_public = Some( - self.vault - .secret_public_key_get(&ephemeral_secret_handle) - .await?, - ); + let ephemeral_secret_handle = self.vault.generate_key(attributes).await?; + self.ephemeral_public = Some(self.vault.get_public_key(&ephemeral_secret_handle).await?); self.ephemeral_secret = Some(ephemeral_secret_handle); // 3. Set k to empty, Set n to 0 @@ -164,9 +157,9 @@ impl State { let ck = self.dh_state.ck().ok_or(XXError::InvalidState)?; let symmetric_key_info = self.get_symmetric_key_type_and_length(); - let attributes = SecretAttributes::new( + let attributes = KeyAttributes::new( symmetric_key_info.0, - SecretPersistence::Ephemeral, + KeyPersistence::Ephemeral, symmetric_key_info.1, ); let mut hkdf_output = self @@ -233,7 +226,7 @@ impl State { let mut index_l = 0; let mut index_r = public_key_size; let re = &message[..index_r]; - let re = PublicKey::new(re.to_vec(), SecretType::X25519); + let re = PublicKey::new(re.to_vec(), KeyType::X25519); index_l += public_key_size; index_r += public_key_size + AES_GCM_TAGSIZE_USIZE; let encrypted_rs_and_tag = &message[index_l..index_r]; @@ -244,7 +237,7 @@ impl State { self.remote_ephemeral_public_key = Some(re); let (rs, h) = self.decrypt_and_mix_hash(encrypted_rs_and_tag).await?; self.h = Some(h); - let rs = PublicKey::new(rs, SecretType::X25519); + let rs = PublicKey::new(rs, KeyType::X25519); self.dh_state.dh(&ephemeral_secret_handle, &rs).await?; self._remote_static_public_key = Some(rs); self.nonce = 0; @@ -302,7 +295,7 @@ impl State { } let re = &message_1[..public_key_size]; - let re = PublicKey::new(re.to_vec(), SecretType::X25519); + let re = PublicKey::new(re.to_vec(), KeyType::X25519); self.h = Some(self.mix_hash(re.data()).await?); self.h = Some(self.mix_hash(&message_1[public_key_size..]).await?); self.remote_ephemeral_public_key = Some(re); @@ -361,7 +354,7 @@ impl State { .decrypt_and_mix_hash(&message_3[..public_key_size + AES_GCM_TAGSIZE_USIZE]) .await?; self.h = Some(h); - let rs = PublicKey::new(rs, SecretType::X25519); + let rs = PublicKey::new(rs, KeyType::X25519); self.dh_state.dh(ephemeral_secret, &rs).await?; self.nonce = 0; let (payload, h) = self @@ -386,8 +379,8 @@ mod tests { use crate::{Initiator, Responder, XXVault}; use hex::{decode, encode}; use ockam_core::vault::{ - Secret, SecretAttributes, SecretKey, SecretPersistence, SecretType, SecretVault, - SymmetricVault, CURVE25519_SECRET_LENGTH_U32, + Key, KeyAttributes, KeyPersistence, KeyType, KeyVault, PrivateKey, SymmetricVault, + CURVE25519_SECRET_LENGTH_U32, }; use ockam_core::Result; use ockam_key_exchange_core::KeyExchanger; @@ -408,10 +401,7 @@ mod tests { assert!(res.is_ok()); assert_eq!(state.h.unwrap(), exp_h); - let ck = vault - .secret_export(&state.dh_state.ck.unwrap()) - .await - .unwrap(); + let ck = vault.export_key(&state.dh_state.ck.unwrap()).await.unwrap(); assert_eq!( ck.cast_as_key().as_ref(), @@ -639,34 +629,31 @@ mod tests { static_private: &str, ephemeral_private: &str, ) -> State { - let attributes = SecretAttributes::new( - SecretType::X25519, - SecretPersistence::Ephemeral, + let attributes = KeyAttributes::new( + KeyType::X25519, + KeyPersistence::Ephemeral, CURVE25519_SECRET_LENGTH_U32, ); // Static x25519 for this handshake, `s` let static_secret_handle = vault - .secret_import( - Secret::Key(SecretKey::new(decode(static_private).unwrap())), + .import_key( + Key::Key(PrivateKey::new(decode(static_private).unwrap())), attributes, ) .await .unwrap(); - let static_public_key = vault - .secret_public_key_get(&static_secret_handle) - .await - .unwrap(); + let static_public_key = vault.get_public_key(&static_secret_handle).await.unwrap(); // Ephemeral x25519 for this handshake, `e` let ephemeral_secret_handle = vault - .secret_import( - Secret::Key(SecretKey::new(decode(ephemeral_private).unwrap())), + .import_key( + Key::Key(PrivateKey::new(decode(ephemeral_private).unwrap())), attributes, ) .await .unwrap(); let ephemeral_public_key = vault - .secret_public_key_get(&ephemeral_secret_handle) + .get_public_key(&ephemeral_secret_handle) .await .unwrap(); @@ -676,13 +663,10 @@ mod tests { .unwrap(); let ck = *b"Noise_XX_25519_AESGCM_SHA256\0\0\0\0"; - let attributes = SecretAttributes::new( - SecretType::Buffer, - SecretPersistence::Ephemeral, - ck.len() as u32, - ); + let attributes = + KeyAttributes::new(KeyType::Buffer, KeyPersistence::Ephemeral, ck.len() as u32); let ck = vault - .secret_import(Secret::Key(SecretKey::new(ck[..].to_vec())), attributes) + .import_key(Key::Key(PrivateKey::new(ck[..].to_vec())), attributes) .await .unwrap(); diff --git a/implementations/rust/ockam/ockam_key_exchange_xx/src/state/dh_state.rs b/implementations/rust/ockam/ockam_key_exchange_xx/src/state/dh_state.rs index 3fc66d5aaf3..1c012805ea1 100644 --- a/implementations/rust/ockam/ockam_key_exchange_xx/src/state/dh_state.rs +++ b/implementations/rust/ockam/ockam_key_exchange_xx/src/state/dh_state.rs @@ -1,6 +1,6 @@ use crate::{XXError, XXVault, SHA256_SIZE_U32}; use ockam_core::vault::{ - KeyId, PublicKey, Secret, SecretAttributes, SecretKey, SecretPersistence, SecretType, + Key, KeyAttributes, KeyId, KeyPersistence, KeyType, PrivateKey, PublicKey, AES256_SECRET_LENGTH_U32, }; use ockam_core::Result; @@ -21,14 +21,11 @@ impl DhState { } pub(crate) async fn new(protocol_name: &[u8; 32], vault: V) -> Result { - let attributes = SecretAttributes::new( - SecretType::Buffer, - SecretPersistence::Ephemeral, - SHA256_SIZE_U32, - ); + let attributes = + KeyAttributes::new(KeyType::Buffer, KeyPersistence::Ephemeral, SHA256_SIZE_U32); - let sk = Secret::Key(SecretKey::new(protocol_name.to_vec())); - let ck = vault.secret_import(sk, attributes).await?; + let sk = Key::Key(PrivateKey::new(protocol_name.to_vec())); + let ck = vault.import_key(sk, attributes).await?; Ok(Self { key: None, @@ -48,24 +45,21 @@ impl DhState { } impl DhState { - pub(crate) fn get_symmetric_key_type_and_length(&self) -> (SecretType, u32) { - (SecretType::Aes, AES256_SECRET_LENGTH_U32) + pub(crate) fn get_symmetric_key_type_and_length(&self) -> (KeyType, u32) { + (KeyType::Aes, AES256_SECRET_LENGTH_U32) } /// Perform the diffie-hellman computation pub(crate) async fn dh(&mut self, secret_handle: &KeyId, public_key: &PublicKey) -> Result<()> { let ck = self.ck.as_ref().ok_or(XXError::InvalidState)?; - let attributes_ck = SecretAttributes::new( - SecretType::Buffer, - SecretPersistence::Ephemeral, - SHA256_SIZE_U32, - ); + let attributes_ck = + KeyAttributes::new(KeyType::Buffer, KeyPersistence::Ephemeral, SHA256_SIZE_U32); let symmetric_secret_info = self.get_symmetric_key_type_and_length(); - let attributes_k = SecretAttributes::new( + let attributes_k = KeyAttributes::new( symmetric_secret_info.0, - SecretPersistence::Ephemeral, + KeyPersistence::Ephemeral, symmetric_secret_info.1, ); @@ -85,14 +79,14 @@ impl DhState { let key = self.key.take(); if key.is_some() { - self.vault.secret_destroy(key.unwrap()).await?; + self.vault.destroy_key(key.unwrap()).await?; } self.key = Some(hkdf_output.pop().unwrap()); let ck = self.ck.take(); - self.vault.secret_destroy(ck.unwrap()).await?; + self.vault.destroy_key(ck.unwrap()).await?; self.ck = Some(hkdf_output.pop().unwrap()); Ok(()) diff --git a/implementations/rust/ockam/ockam_vault/src/asymmetric_impl.rs b/implementations/rust/ockam/ockam_vault/src/asymmetric_impl.rs index 676a1a9ae0b..07927d84764 100644 --- a/implementations/rust/ockam/ockam_vault/src/asymmetric_impl.rs +++ b/implementations/rust/ockam/ockam_vault/src/asymmetric_impl.rs @@ -1,8 +1,8 @@ use crate::{Vault, VaultError}; use arrayref::array_ref; use ockam_core::vault::{ - AsymmetricVault, Buffer, Hasher, KeyId, PublicKey, Secret, SecretAttributes, SecretKey, - SecretPersistence, SecretType, SecretVault, VaultEntry, CURVE25519_PUBLIC_LENGTH_USIZE, + AsymmetricVault, Buffer, Hasher, Key, KeyAttributes, KeyId, KeyPersistence, KeyType, KeyVault, + PrivateKey, PublicKey, VaultEntry, CURVE25519_PUBLIC_LENGTH_USIZE, CURVE25519_SECRET_LENGTH_USIZE, }; use ockam_core::Result; @@ -11,8 +11,8 @@ use ockam_core::{async_trait, compat::boxed::Box}; impl Vault { fn ecdh_internal(vault_entry: &VaultEntry, peer_public_key: &PublicKey) -> Result> { match vault_entry.key_attributes().stype() { - SecretType::X25519 => { - let key = vault_entry.secret().try_as_key()?; + KeyType::X25519 => { + let key = vault_entry.key().try_as_key()?; if peer_public_key.data().len() != CURVE25519_PUBLIC_LENGTH_USIZE || key.as_ref().len() != CURVE25519_SECRET_LENGTH_USIZE { @@ -32,7 +32,7 @@ impl Vault { let secret = sk.diffie_hellman(&pk_t); Ok(secret.as_bytes().to_vec()) } - SecretType::NistP256 | SecretType::Buffer | SecretType::Aes | SecretType::Ed25519 => { + KeyType::NistP256 | KeyType::Buffer | KeyType::Aes | KeyType::Ed25519 => { Err(VaultError::UnknownEcdhKeyType.into()) } } @@ -54,12 +54,9 @@ impl AsymmetricVault for Vault { // Prevent dead-lock by freeing entries lock, since we don't need it drop(entries); - let attributes = SecretAttributes::new( - SecretType::Buffer, - SecretPersistence::Ephemeral, - dh.len() as u32, - ); - self.secret_import(Secret::Key(SecretKey::new(dh)), attributes) + let attributes = + KeyAttributes::new(KeyType::Buffer, KeyPersistence::Ephemeral, dh.len() as u32); + self.import_key(Key::Key(PrivateKey::new(dh)), attributes) .await } diff --git a/implementations/rust/ockam/ockam_vault/src/aws.rs b/implementations/rust/ockam/ockam_vault/src/aws.rs index 18f7acbee29..379b47a5572 100644 --- a/implementations/rust/ockam/ockam_vault/src/aws.rs +++ b/implementations/rust/ockam/ockam_vault/src/aws.rs @@ -3,7 +3,7 @@ use aws_sdk_kms::error::{ScheduleKeyDeletionError, ScheduleKeyDeletionErrorKind} use aws_sdk_kms::model::{KeySpec, KeyUsageType, MessageType, SigningAlgorithmSpec}; use aws_sdk_kms::types::{Blob, SdkError}; use aws_sdk_kms::Client; -use ockam_core::vault::SecretType; +use ockam_core::vault::KeyType; use ockam_core::vault::{KeyId, PublicKey, Signature}; use ockam_core::Result; use sha2::{Digest, Sha256}; @@ -126,7 +126,7 @@ impl Kms { } if let Some(k) = output.public_key() { log::debug!(%kid, "received public key"); - return Ok(PublicKey::new(k.as_ref().to_vec(), SecretType::NistP256)); + return Ok(PublicKey::new(k.as_ref().to_vec(), KeyType::NistP256)); } log::error!(%kid, "key type not supported to get a public key"); Err(Error::UnsupportedKeyType.into()) @@ -258,10 +258,10 @@ mod tests { let pky = kms.public_key(&keyid).await.unwrap(); let vlt = Vault::create(); { - use ockam_core::vault::{SecretAttributes, SecretPersistence, SecretType, SecretVault}; - let att = SecretAttributes::new(SecretType::NistP256, SecretPersistence::Ephemeral, 32); - let kid = vlt.secret_generate(att).await.unwrap(); - let pky = vlt.secret_public_key_get(&kid).await.unwrap(); + use ockam_core::vault::{KeyAttributes, KeyPersistence, KeyType, KeyVault}; + let att = KeyAttributes::new(KeyType::NistP256, KeyPersistence::Ephemeral, 32); + let kid = vlt.generate_key(att).await.unwrap(); + let pky = vlt.get_public_key(&kid).await.unwrap(); let sig = vlt.sign(&kid, &msg[..]).await.unwrap(); assert!(vlt.verify(&sig, &pky, msg).await.unwrap()) } diff --git a/implementations/rust/ockam/ockam_vault/src/hasher_impl.rs b/implementations/rust/ockam/ockam_vault/src/hasher_impl.rs index ff6cf630c70..9a4659b859e 100644 --- a/implementations/rust/ockam/ockam_vault/src/hasher_impl.rs +++ b/implementations/rust/ockam/ockam_vault/src/hasher_impl.rs @@ -3,8 +3,8 @@ use crate::VaultError; use arrayref::array_ref; use ockam_core::compat::vec::Vec; use ockam_core::vault::{ - Hasher, KeyId, Secret, SecretAttributes, SecretKey, SecretType, SecretVault, - AES128_SECRET_LENGTH_USIZE, AES256_SECRET_LENGTH_USIZE, + Hasher, Key, KeyAttributes, KeyId, KeyType, KeyVault, PrivateKey, AES128_SECRET_LENGTH_USIZE, + AES256_SECRET_LENGTH_USIZE, }; use ockam_core::{async_trait, compat::boxed::Box, Result}; use sha2::{Digest, Sha256}; @@ -24,7 +24,7 @@ impl Hasher for Vault { salt: &KeyId, info: &[u8], ikm: Option<&KeyId>, - output_attributes: Vec, + output_attributes: Vec, ) -> Result> { self.preload_from_storage(salt).await; if let Some(ikm) = ikm { @@ -36,8 +36,8 @@ impl Hasher for Vault { let ikm: Result<&[u8]> = match ikm { Some(ikm) => { let ikm = entries.get(ikm).ok_or(VaultError::EntryNotFound)?; - if ikm.key_attributes().stype() == SecretType::Buffer { - Ok(ikm.secret().try_as_key()?.as_ref()) + if ikm.key_attributes().stype() == KeyType::Buffer { + Ok(ikm.key().try_as_key()?.as_ref()) } else { Err(VaultError::InvalidKeyType.into()) } @@ -49,7 +49,7 @@ impl Hasher for Vault { let salt = entries.get(salt).ok_or(VaultError::EntryNotFound)?; - if salt.key_attributes().stype() != SecretType::Buffer { + if salt.key_attributes().stype() != KeyType::Buffer { return Err(VaultError::InvalidKeyType.into()); } @@ -58,7 +58,7 @@ impl Hasher for Vault { let okm = { let mut okm = vec![0u8; okm_len]; - let prk = hkdf::Hkdf::::new(Some(salt.secret().try_as_key()?.as_ref()), ikm); + let prk = hkdf::Hkdf::::new(Some(salt.key().try_as_key()?.as_ref()), ikm); prk.expand(info, okm.as_mut_slice()) .map_err(|_| Into::::into(VaultError::HkdfExpandError))?; @@ -73,15 +73,15 @@ impl Hasher for Vault { for attributes in output_attributes { let length = attributes.length() as usize; - if attributes.stype() == SecretType::Aes { + if attributes.stype() == KeyType::Aes { if length != AES256_SECRET_LENGTH_USIZE && length != AES128_SECRET_LENGTH_USIZE { return Err(VaultError::InvalidAesKeyLength.into()); } - } else if attributes.stype() != SecretType::Buffer { + } else if attributes.stype() != KeyType::Buffer { return Err(VaultError::InvalidHkdfOutputType.into()); } - let secret = Secret::Key(SecretKey::new(okm[index..index + length].to_vec())); - let secret = self.secret_import(secret, attributes).await?; + let secret = Key::Key(PrivateKey::new(okm[index..index + length].to_vec())); + let secret = self.import_key(secret, attributes).await?; secrets.push(secret); index += 32; diff --git a/implementations/rust/ockam/ockam_vault/src/lib.rs b/implementations/rust/ockam/ockam_vault/src/lib.rs index 9971ee0910c..b5e85367a5d 100644 --- a/implementations/rust/ockam/ockam_vault/src/lib.rs +++ b/implementations/rust/ockam/ockam_vault/src/lib.rs @@ -41,9 +41,7 @@ mod verifier_impl; mod xeddsa; // Re-export types commonly used by higher level APIs -pub use ockam_core::vault::{ - Hasher, KeyId, PublicKey, SecretAttributes, SecretVault, Signer, Verifier, -}; +pub use ockam_core::vault::{Hasher, KeyAttributes, KeyId, KeyVault, PublicKey, Signer, Verifier}; pub use asymmetric_impl::*; pub use error::*; diff --git a/implementations/rust/ockam/ockam_vault/src/secret_impl.rs b/implementations/rust/ockam/ockam_vault/src/secret_impl.rs index 2da214cd5c9..faa7787dfb2 100644 --- a/implementations/rust/ockam/ockam_vault/src/secret_impl.rs +++ b/implementations/rust/ockam/ockam_vault/src/secret_impl.rs @@ -4,8 +4,8 @@ use arrayref::array_ref; use cfg_if::cfg_if; use ockam_core::compat::rand::{thread_rng, RngCore}; use ockam_core::vault::{ - AsymmetricVault, KeyId, PublicKey, Secret, SecretAttributes, SecretKey, SecretPersistence, - SecretType, SecretVault, VaultEntry, AES128_SECRET_LENGTH_U32, AES256_SECRET_LENGTH_U32, + AsymmetricVault, Key, KeyAttributes, KeyId, KeyPersistence, KeyType, KeyVault, PrivateKey, + PublicKey, VaultEntry, AES128_SECRET_LENGTH_U32, AES256_SECRET_LENGTH_U32, CURVE25519_SECRET_LENGTH_USIZE, }; use ockam_core::{async_trait, compat::boxed::Box, Result}; @@ -15,13 +15,9 @@ use crate::error::{from_ecurve, from_pkcs8}; impl Vault { /// Compute key id from secret and attributes. Only Curve25519 and Buffer types are supported - async fn compute_key_id( - &self, - secret: &Secret, - attributes: &SecretAttributes, - ) -> Result { + async fn compute_key_id(&self, secret: &Key, attributes: &KeyAttributes) -> Result { Ok(match attributes.stype() { - SecretType::X25519 => { + KeyType::X25519 => { // FIXME: Check secret length let secret = secret.try_as_key()?.as_ref(); let sk = x25519_dalek::StaticSecret::from(*array_ref![ @@ -33,26 +29,26 @@ impl Vault { self.compute_key_id_for_public_key(&PublicKey::new( public.as_bytes().to_vec(), - SecretType::X25519, + KeyType::X25519, )) .await? } - SecretType::Ed25519 => { + KeyType::Ed25519 => { let sk = ed25519_dalek::SecretKey::from_bytes(secret.try_as_key()?.as_ref()) .map_err(|_| VaultError::InvalidEd25519Secret)?; let public = ed25519_dalek::PublicKey::from(&sk); self.compute_key_id_for_public_key(&PublicKey::new( public.as_bytes().to_vec(), - SecretType::Ed25519, + KeyType::Ed25519, )) .await? } - SecretType::NistP256 => '_block: { + KeyType::NistP256 => '_block: { #[cfg(feature = "aws")] - if attributes.persistence() == SecretPersistence::Persistent { + if attributes.persistence() == KeyPersistence::Persistent { if let Some(kms) = &self.aws_kms { - if let Secret::Aws(kid) = secret { + if let Key::Aws(kid) = secret { let pk = kms.public_key(kid).await?; break '_block self.compute_key_id_for_public_key(&pk).await?; } @@ -67,7 +63,7 @@ impl Vault { } } } - SecretType::Buffer | SecretType::Aes => { + KeyType::Buffer | KeyType::Aes => { // NOTE: Buffer and Aes secrets in the system are ephemeral and it should be fine, // that every time we import the same secret - it gets different KeyId value. // However, if we decide to have persistent Buffer or Aes secrets, that should be @@ -81,7 +77,7 @@ impl Vault { } /// Validate secret key. - pub fn check_secret(&self, secret: &[u8], attributes: &SecretAttributes) -> Result<()> { + pub fn check_secret(&self, secret: &[u8], attributes: &KeyAttributes) -> Result<()> { if secret.len() != attributes.length() as usize { return Err(VaultError::InvalidSecretLength.into()); } @@ -89,7 +85,7 @@ impl Vault { } async fn store_secret(&self, key_id: &KeyId, vault_entry: &VaultEntry) -> Result<()> { - if vault_entry.key_attributes().persistence() == SecretPersistence::Persistent { + if vault_entry.key_attributes().persistence() == KeyPersistence::Persistent { if let Some(storage) = &self.storage { storage.store(key_id, vault_entry).await?; } @@ -100,11 +96,11 @@ impl Vault { } #[async_trait] -impl SecretVault for Vault { +impl KeyVault for Vault { /// Generate fresh secret. Only Curve25519 and Buffer types are supported - async fn secret_generate(&self, attributes: SecretAttributes) -> Result { + async fn generate_key(&self, attributes: KeyAttributes) -> Result { let secret = match attributes.stype() { - SecretType::X25519 | SecretType::Ed25519 => { + KeyType::X25519 | KeyType::Ed25519 => { let bytes = { let mut rng = thread_rng(); let mut bytes = vec![0u8; CURVE25519_SECRET_LENGTH_USIZE]; @@ -112,10 +108,10 @@ impl SecretVault for Vault { bytes }; - Secret::Key(SecretKey::new(bytes)) + Key::Key(PrivateKey::new(bytes)) } - SecretType::Buffer => { - if attributes.persistence() != SecretPersistence::Ephemeral { + KeyType::Buffer => { + if attributes.persistence() != KeyPersistence::Ephemeral { return Err(VaultError::InvalidKeyType.into()); }; let key = { @@ -125,15 +121,15 @@ impl SecretVault for Vault { key }; - Secret::Key(SecretKey::new(key)) + Key::Key(PrivateKey::new(key)) } - SecretType::Aes => { + KeyType::Aes => { if attributes.length() != AES256_SECRET_LENGTH_U32 && attributes.length() != AES128_SECRET_LENGTH_U32 { return Err(VaultError::InvalidAesKeyLength.into()); }; - if attributes.persistence() != SecretPersistence::Ephemeral { + if attributes.persistence() != KeyPersistence::Ephemeral { return Err(VaultError::InvalidKeyType.into()); }; let key = { @@ -143,14 +139,14 @@ impl SecretVault for Vault { key }; - Secret::Key(SecretKey::new(key)) + Key::Key(PrivateKey::new(key)) } - SecretType::NistP256 => '_block: { + KeyType::NistP256 => '_block: { #[cfg(feature = "aws")] - if attributes.persistence() == SecretPersistence::Persistent { + if attributes.persistence() == KeyPersistence::Persistent { if let Some(kms) = &self.aws_kms { let aws_id = kms.create_key().await?; - break '_block Secret::Aws(aws_id); + break '_block Key::Aws(aws_id); } } cfg_if! { @@ -160,7 +156,7 @@ impl SecretVault for Vault { let sec = SigningKey::random(& mut thread_rng()); let sec = p256::SecretKey::from_be_bytes(&sec.to_bytes()).map_err(from_ecurve)?; let doc = sec.to_pkcs8_der().map_err(from_pkcs8)?; - Secret::Key(SecretKey::new(doc.as_bytes().to_vec())) + Key::Key(PrivateKey::new(doc.as_bytes().to_vec())) } else { compile_error!("NIST P-256 requires feature `rustcrypto`") } @@ -182,8 +178,8 @@ impl SecretVault for Vault { } #[tracing::instrument(skip_all, err)] - async fn secret_import(&self, secret: Secret, attributes: SecretAttributes) -> Result { - if let Secret::Key(sk) = &secret { + async fn import_key(&self, secret: Key, attributes: KeyAttributes) -> Result { + if let Key::Key(sk) = &secret { self.check_secret(sk.as_ref(), &attributes)? } let key_id = self.compute_key_id(&secret, &attributes).await?; @@ -199,18 +195,18 @@ impl SecretVault for Vault { Ok(key_id) } - async fn secret_export(&self, key_id: &KeyId) -> Result { + async fn export_key(&self, key_id: &KeyId) -> Result { self.preload_from_storage(key_id).await; let entries = self.data.entries.read().await; if let Some(entry) = entries.get(key_id) { - return Ok(entry.secret().clone()); + return Ok(entry.key().clone()); } Err(VaultError::EntryNotFound.into()) } - async fn secret_attributes_get(&self, key_id: &KeyId) -> Result { + async fn get_key_attributes(&self, key_id: &KeyId) -> Result { self.preload_from_storage(key_id).await; let entries = self.data.entries.read().await; @@ -222,47 +218,46 @@ impl SecretVault for Vault { } /// Extract public key from secret. Only Curve25519 type is supported - async fn secret_public_key_get(&self, key_id: &KeyId) -> Result { + async fn get_public_key(&self, key_id: &KeyId) -> Result { self.preload_from_storage(key_id).await; let entries = self.data.entries.read().await; let entry = entries.get(key_id).ok_or(VaultError::EntryNotFound)?; match entry.key_attributes().stype() { - SecretType::X25519 => { - if entry.secret().try_as_key()?.as_ref().len() != CURVE25519_SECRET_LENGTH_USIZE { + KeyType::X25519 => { + if entry.key().try_as_key()?.as_ref().len() != CURVE25519_SECRET_LENGTH_USIZE { return Err(VaultError::InvalidPrivateKeyLen.into()); } let sk = x25519_dalek::StaticSecret::from(*array_ref![ - entry.secret().try_as_key()?.as_ref(), + entry.key().try_as_key()?.as_ref(), 0, CURVE25519_SECRET_LENGTH_USIZE ]); let pk = x25519_dalek::PublicKey::from(&sk); - Ok(PublicKey::new(pk.to_bytes().to_vec(), SecretType::X25519)) + Ok(PublicKey::new(pk.to_bytes().to_vec(), KeyType::X25519)) } - SecretType::Ed25519 => { - if entry.secret().try_as_key()?.as_ref().len() != CURVE25519_SECRET_LENGTH_USIZE { + KeyType::Ed25519 => { + if entry.key().try_as_key()?.as_ref().len() != CURVE25519_SECRET_LENGTH_USIZE { return Err(VaultError::InvalidPrivateKeyLen.into()); } - let sk = - ed25519_dalek::SecretKey::from_bytes(entry.secret().try_as_key()?.as_ref()) - .map_err(|_| VaultError::InvalidEd25519Secret)?; + let sk = ed25519_dalek::SecretKey::from_bytes(entry.key().try_as_key()?.as_ref()) + .map_err(|_| VaultError::InvalidEd25519Secret)?; let pk = ed25519_dalek::PublicKey::from(&sk); - Ok(PublicKey::new(pk.to_bytes().to_vec(), SecretType::Ed25519)) + Ok(PublicKey::new(pk.to_bytes().to_vec(), KeyType::Ed25519)) } - SecretType::NistP256 => { + KeyType::NistP256 => { #[cfg(feature = "aws")] if let Some(kms) = &self.aws_kms { - if let Secret::Aws(kid) = entry.secret() { + if let Key::Aws(kid) = entry.key() { return kms.public_key(kid).await; } } cfg_if! { if #[cfg(feature = "rustcrypto")] { - if let Secret::Key(sk) = entry.secret() { + if let Key::Key(sk) = entry.key() { public_key(sk.as_ref()) } else { Err(VaultError::InvalidKeyType.into()) @@ -272,18 +267,18 @@ impl SecretVault for Vault { } } } - SecretType::Buffer | SecretType::Aes => Err(VaultError::InvalidKeyType.into()), + KeyType::Buffer | KeyType::Aes => Err(VaultError::InvalidKeyType.into()), } } /// Remove secret from memory - async fn secret_destroy(&self, key_id: KeyId) -> Result<()> { - let attrs = self.secret_attributes_get(&key_id).await?; + async fn destroy_key(&self, key_id: KeyId) -> Result<()> { + let attrs = self.get_key_attributes(&key_id).await?; // Acquire lock to avoid race conditions let mut entries = self.data.entries.write().await; - let res = if attrs.persistence() == SecretPersistence::Persistent { + let res = if attrs.persistence() == KeyPersistence::Persistent { if let Some(storage) = &self.storage { storage.delete(&key_id).await.map(|_| ()) } else { @@ -299,7 +294,7 @@ impl SecretVault for Vault { { #[cfg(feature = "aws")] if let Some(kms) = &self.aws_kms { - if let Secret::Aws(kid) = _entry.secret() { + if let Key::Aws(kid) = _entry.key() { if !kms.delete_key(kid).await? { return Err(VaultError::EntryNotFound.into()); } @@ -320,16 +315,16 @@ fn public_key(secret: &[u8]) -> Result { .verifying_key() .to_public_key_der() .map_err(from_pkcs8)?; - Ok(PublicKey::new(pky.as_ref().to_vec(), SecretType::NistP256)) + Ok(PublicKey::new(pky.as_ref().to_vec(), KeyType::NistP256)) } #[cfg(test)] mod tests { - use ockam_core::vault::{Secret, SecretKey}; + use ockam_core::vault::{Key, PrivateKey}; use crate::{ - ockam_core::vault::{SecretPersistence, SecretType, CURVE25519_SECRET_LENGTH_U32}, - SecretAttributes, SecretVault, Vault, + ockam_core::vault::{KeyPersistence, KeyType, CURVE25519_SECRET_LENGTH_U32}, + KeyAttributes, KeyVault, Vault, }; fn new_vault() -> Vault { @@ -348,10 +343,10 @@ mod tests { #[ockam_macros::vault_test] fn secret_attributes_get() {} - fn new_x255519_attrs() -> Option { - Some(SecretAttributes::new( - SecretType::X25519, - SecretPersistence::Ephemeral, + fn new_x255519_attrs() -> Option { + Some(KeyAttributes::new( + KeyType::X25519, + KeyPersistence::Ephemeral, CURVE25519_SECRET_LENGTH_U32, )) } @@ -366,7 +361,7 @@ mod tests { let attrs = new_x255519_attrs().unwrap(); let vault = new_vault(); let key_id = vault - .secret_import(Secret::Key(SecretKey::new(bytes_c25519)), attrs) + .import_key(Key::Key(PrivateKey::new(bytes_c25519)), attrs) .await .unwrap(); assert_eq!( diff --git a/implementations/rust/ockam/ockam_vault/src/signer_impl.rs b/implementations/rust/ockam/ockam_vault/src/signer_impl.rs index d7782ad61cf..16a1d5fe8eb 100644 --- a/implementations/rust/ockam/ockam_vault/src/signer_impl.rs +++ b/implementations/rust/ockam/ockam_vault/src/signer_impl.rs @@ -1,11 +1,11 @@ use crate::vault::Vault; use crate::VaultError; use cfg_if::cfg_if; -use ockam_core::vault::{KeyId, SecretType, Signature, Signer}; +use ockam_core::vault::{KeyId, KeyType, Signature, Signer}; use ockam_core::{async_trait, compat::boxed::Box, Result}; #[cfg(feature = "aws")] -use ockam_core::vault::Secret; +use ockam_core::vault::Key; #[cfg(feature = "rustcrypto")] use crate::error::from_pkcs8; @@ -20,12 +20,12 @@ impl Signer for Vault { let entry = entries.get(secret_key).ok_or(VaultError::EntryNotFound)?; match entry.key_attributes().stype() { - SecretType::X25519 => { + KeyType::X25519 => { use crate::xeddsa::XEddsaSigner; use arrayref::array_ref; use ockam_core::compat::rand::{thread_rng, RngCore}; use ockam_core::vault::CURVE25519_SECRET_LENGTH_USIZE; - let key = entry.secret().try_as_key()?.as_ref(); + let key = entry.key().try_as_key()?.as_ref(); if key.len() != CURVE25519_SECRET_LENGTH_USIZE { return Err(VaultError::InvalidX25519SecretLength.into()); } @@ -41,9 +41,9 @@ impl Signer for Vault { .xeddsa_sign(data.as_ref(), &nonce); Ok(Signature::new(sig.to_vec())) } - SecretType::Ed25519 => { + KeyType::Ed25519 => { use ed25519_dalek::Signer; - let key = entry.secret().try_as_key()?.as_ref(); + let key = entry.key().try_as_key()?.as_ref(); let sk = ed25519_dalek::SecretKey::from_bytes(key).unwrap(); let pk = ed25519_dalek::PublicKey::from(&sk); @@ -55,14 +55,14 @@ impl Signer for Vault { let sig = kp.sign(data.as_ref()); Ok(Signature::new(sig.to_bytes().to_vec())) } - SecretType::NistP256 => { + KeyType::NistP256 => { #[cfg(feature = "aws")] if let Some(kms) = &self.aws_kms { - if let Secret::Aws(kid) = entry.secret() { + if let Key::Aws(kid) = entry.key() { return kms.sign(kid, data).await; } } - let key = entry.secret().try_as_key()?.as_ref(); + let key = entry.key().try_as_key()?.as_ref(); cfg_if! { if #[cfg(feature = "rustcrypto")] { use p256::ecdsa::{self, signature::Signer as _}; @@ -76,7 +76,7 @@ impl Signer for Vault { } } } - SecretType::Buffer | SecretType::Aes => Err(VaultError::InvalidKeyType.into()), + KeyType::Buffer | KeyType::Aes => Err(VaultError::InvalidKeyType.into()), } } } diff --git a/implementations/rust/ockam/ockam_vault/src/storage/file_storage.rs b/implementations/rust/ockam/ockam_vault/src/storage/file_storage.rs index 312cad1b568..ca0296e4b83 100644 --- a/implementations/rust/ockam/ockam_vault/src/storage/file_storage.rs +++ b/implementations/rust/ockam/ockam_vault/src/storage/file_storage.rs @@ -3,7 +3,7 @@ use fs2::FileExt; //locking use ockam_core::compat::boxed::Box; use ockam_core::errcode::{Kind, Origin}; use ockam_core::vault::storage::Storage; -use ockam_core::vault::{KeyId, Secret, SecretAttributes, SecretPersistence, VaultEntry}; +use ockam_core::vault::{Key, KeyAttributes, KeyId, KeyPersistence, VaultEntry}; use ockam_core::{async_trait, Error, Result}; use ockam_node::tokio::task::{self, JoinError}; use serde::{Deserialize, Serialize}; @@ -14,8 +14,8 @@ use std::path::{Path, PathBuf}; #[derive(Serialize, Deserialize, Debug)] struct LegacyVaultEntry { key_id: Option, - key_attributes: SecretAttributes, - key: Secret, + key_attributes: KeyAttributes, + key: Key, } #[derive(Serialize, Deserialize, Debug)] @@ -184,7 +184,7 @@ impl Storage for FileStorage { async fn store(&self, key_id: &KeyId, key: &VaultEntry) -> Result<()> { let key_id = key_id.clone(); let attributes = key.key_attributes(); - let key = key.secret().clone(); + let key = key.key().clone(); let t = move |v: LegacySerializedVault| { let new_entry = ( 0, @@ -216,7 +216,7 @@ impl Storage for FileStorage { .find(|x| { if let Some(id) = &x.1.key_id { id.eq(&key_id) - && x.1.key_attributes.persistence() == SecretPersistence::Persistent + && x.1.key_attributes.persistence() == KeyPersistence::Persistent } else { false } @@ -258,7 +258,7 @@ mod tests { use crate::Vault; use ockam_core::compat::join; use ockam_core::compat::rand::RngCore; - use ockam_core::vault::{SecretType, SecretVault}; + use ockam_core::vault::{KeyType, KeyVault}; use rand::thread_rng; use std::sync::Arc; @@ -278,24 +278,21 @@ mod tests { let storage = Arc::new(storage); let vault = Vault::new(Some(storage.clone())); - let attributes10 = - SecretAttributes::new(SecretType::Ed25519, SecretPersistence::Persistent, 0); - let attributes20 = - SecretAttributes::new(SecretType::X25519, SecretPersistence::Persistent, 0); - let attributes3 = - SecretAttributes::new(SecretType::X25519, SecretPersistence::Ephemeral, 0); + let attributes10 = KeyAttributes::new(KeyType::Ed25519, KeyPersistence::Persistent, 0); + let attributes20 = KeyAttributes::new(KeyType::X25519, KeyPersistence::Persistent, 0); + let attributes3 = KeyAttributes::new(KeyType::X25519, KeyPersistence::Ephemeral, 0); - let key_id1 = vault.secret_generate(attributes10).await.unwrap(); - let key_id2 = vault.secret_generate(attributes20).await.unwrap(); - let key_id3 = vault.secret_generate(attributes3).await.unwrap(); + let key_id1 = vault.generate_key(attributes10).await.unwrap(); + let key_id2 = vault.generate_key(attributes20).await.unwrap(); + let key_id3 = vault.generate_key(attributes3).await.unwrap(); let vault = Vault::new(Some(storage.clone())); - let attributes11 = vault.secret_attributes_get(&key_id1).await.unwrap(); + let attributes11 = vault.get_key_attributes(&key_id1).await.unwrap(); assert_eq!(attributes10, attributes11); - let attributes21 = vault.secret_attributes_get(&key_id2).await.unwrap(); + let attributes21 = vault.get_key_attributes(&key_id2).await.unwrap(); assert_eq!(attributes20, attributes21); - let attributes31 = vault.secret_attributes_get(&key_id3).await; + let attributes31 = vault.get_key_attributes(&key_id3).await; assert!(attributes31.is_err()); } @@ -316,17 +313,14 @@ mod tests { let storage = Arc::new(storage); let vault = Vault::new(Some(storage.clone())); - let attributes1 = - SecretAttributes::new(SecretType::Ed25519, SecretPersistence::Persistent, 0); - let attributes2 = - SecretAttributes::new(SecretType::Ed25519, SecretPersistence::Persistent, 0); - let attributes3 = - SecretAttributes::new(SecretType::Ed25519, SecretPersistence::Persistent, 0); + let attributes1 = KeyAttributes::new(KeyType::Ed25519, KeyPersistence::Persistent, 0); + let attributes2 = KeyAttributes::new(KeyType::Ed25519, KeyPersistence::Persistent, 0); + let attributes3 = KeyAttributes::new(KeyType::Ed25519, KeyPersistence::Persistent, 0); let (key_id1, key_id2, key_id3) = join!( - vault.secret_generate(attributes1), - vault.secret_generate(attributes2), - vault.secret_generate(attributes3) + vault.generate_key(attributes1), + vault.generate_key(attributes2), + vault.generate_key(attributes3) ); let key_id1 = key_id1.unwrap(); @@ -334,9 +328,9 @@ mod tests { let key_id3 = key_id3.unwrap(); let (attributes12, attributes22, attributes32) = join!( - vault.secret_attributes_get(&key_id1), - vault.secret_attributes_get(&key_id2), - vault.secret_attributes_get(&key_id3) + vault.get_key_attributes(&key_id1), + vault.get_key_attributes(&key_id2), + vault.get_key_attributes(&key_id3) ); assert_eq!(attributes1, attributes12.unwrap()); diff --git a/implementations/rust/ockam/ockam_vault/src/symmetric_impl.rs b/implementations/rust/ockam/ockam_vault/src/symmetric_impl.rs index fd9dd4ed788..92b5a14d6da 100644 --- a/implementations/rust/ockam/ockam_vault/src/symmetric_impl.rs +++ b/implementations/rust/ockam/ockam_vault/src/symmetric_impl.rs @@ -2,8 +2,8 @@ use crate::{Vault, VaultError}; use aes_gcm::aead::{generic_array::GenericArray, Aead, NewAead, Payload}; use aes_gcm::{Aes128Gcm, Aes256Gcm}; use ockam_core::vault::{ - Buffer, KeyId, SecretType, SymmetricVault, AES128_SECRET_LENGTH_U32, - AES128_SECRET_LENGTH_USIZE, AES256_SECRET_LENGTH_U32, AES256_SECRET_LENGTH_USIZE, + Buffer, KeyId, KeyType, SymmetricVault, AES128_SECRET_LENGTH_U32, AES128_SECRET_LENGTH_USIZE, + AES256_SECRET_LENGTH_U32, AES256_SECRET_LENGTH_USIZE, }; use ockam_core::{async_trait, compat::boxed::Box, Result}; @@ -21,7 +21,7 @@ impl SymmetricVault for Vault { let entries = self.data.entries.read().await; let entry = entries.get(key_id).ok_or(VaultError::EntryNotFound)?; - if entry.key_attributes().stype() != SecretType::Aes { + if entry.key_attributes().stype() != KeyType::Aes { return Err(VaultError::AeadAesGcmEncrypt.into()); } @@ -33,7 +33,7 @@ impl SymmetricVault for Vault { match entry.key_attributes().length() { AES128_SECRET_LENGTH_U32 => { - let key = entry.secret().try_as_key()?.as_ref(); + let key = entry.key().try_as_key()?.as_ref(); if key.len() != AES128_SECRET_LENGTH_USIZE { return Err(VaultError::AeadAesGcmEncrypt.into()); } @@ -44,7 +44,7 @@ impl SymmetricVault for Vault { .map_err(|_| VaultError::AeadAesGcmEncrypt.into()) } AES256_SECRET_LENGTH_U32 => { - let key = entry.secret().try_as_key()?.as_ref(); + let key = entry.key().try_as_key()?.as_ref(); if key.len() != AES256_SECRET_LENGTH_USIZE { return Err(VaultError::AeadAesGcmEncrypt.into()); } @@ -70,7 +70,7 @@ impl SymmetricVault for Vault { let entries = self.data.entries.read().await; let entry = entries.get(key_id).ok_or(VaultError::EntryNotFound)?; - if entry.key_attributes().stype() != SecretType::Aes { + if entry.key_attributes().stype() != KeyType::Aes { return Err(VaultError::AeadAesGcmEncrypt.into()); } @@ -82,7 +82,7 @@ impl SymmetricVault for Vault { match entry.key_attributes().length() { AES128_SECRET_LENGTH_U32 => { - let key = entry.secret().try_as_key()?.as_ref(); + let key = entry.key().try_as_key()?.as_ref(); if key.len() != AES128_SECRET_LENGTH_USIZE { return Err(VaultError::AeadAesGcmEncrypt.into()); } @@ -92,7 +92,7 @@ impl SymmetricVault for Vault { .map_err(|_| VaultError::AeadAesGcmEncrypt.into()) } AES256_SECRET_LENGTH_U32 => { - let key = entry.secret().try_as_key()?.as_ref(); + let key = entry.key().try_as_key()?.as_ref(); if key.len() != AES256_SECRET_LENGTH_USIZE { return Err(VaultError::AeadAesGcmEncrypt.into()); } diff --git a/implementations/rust/ockam/ockam_vault/src/vault.rs b/implementations/rust/ockam/ockam_vault/src/vault.rs index c3e1bb5bb69..2f8dafb17e8 100644 --- a/implementations/rust/ockam/ockam_vault/src/vault.rs +++ b/implementations/rust/ockam/ockam_vault/src/vault.rs @@ -9,19 +9,19 @@ use ockam_node::compat::asynchronous::RwLock; /// ``` /// use ockam_vault::Vault; /// use ockam_core::Result; -/// use ockam_core::vault::{SecretAttributes, SecretType, SecretPersistence, CURVE25519_SECRET_LENGTH_U32, SecretVault, Signer, Verifier}; +/// use ockam_core::vault::{KeyAttributes, KeyType, KeyPersistence, CURVE25519_SECRET_LENGTH_U32, KeyVault, Signer, Verifier}; /// /// async fn example() -> Result<()> { /// let mut vault = Vault::default(); /// -/// let mut attributes = SecretAttributes::new( -/// SecretType::X25519, -/// SecretPersistence::Ephemeral, +/// let mut attributes = KeyAttributes::new( +/// KeyType::X25519, +/// KeyPersistence::Ephemeral, /// CURVE25519_SECRET_LENGTH_U32, /// ); /// -/// let secret = vault.secret_generate(attributes).await?; -/// let public = vault.secret_public_key_get(&secret).await?; +/// let secret = vault.generate_key(attributes).await?; +/// let public = vault.get_public_key(&secret).await?; /// /// let data = "Very important stuff".as_bytes(); /// diff --git a/implementations/rust/ockam/ockam_vault/src/verifier_impl.rs b/implementations/rust/ockam/ockam_vault/src/verifier_impl.rs index 07ff72b5baf..82c0bde5194 100644 --- a/implementations/rust/ockam/ockam_vault/src/verifier_impl.rs +++ b/implementations/rust/ockam/ockam_vault/src/verifier_impl.rs @@ -1,9 +1,7 @@ use crate::vault::Vault; use crate::VaultError; use cfg_if::cfg_if; -use ockam_core::vault::{ - PublicKey, SecretType, Signature, Verifier, CURVE25519_PUBLIC_LENGTH_USIZE, -}; +use ockam_core::vault::{KeyType, PublicKey, Signature, Verifier, CURVE25519_PUBLIC_LENGTH_USIZE}; use ockam_core::{async_trait, compat::boxed::Box, Result}; #[cfg(feature = "rustcrypto")] @@ -19,7 +17,7 @@ impl Verifier for Vault { data: &[u8], ) -> Result { match public_key.stype() { - SecretType::X25519 => { + KeyType::X25519 => { if public_key.data().len() != CURVE25519_PUBLIC_LENGTH_USIZE || signature.as_ref().len() != 64 { @@ -37,7 +35,7 @@ impl Verifier for Vault { )); Ok(public_key.xeddsa_verify(data.as_ref(), signature_array)) } - SecretType::Ed25519 => { + KeyType::Ed25519 => { if public_key.data().len() != CURVE25519_PUBLIC_LENGTH_USIZE || signature.as_ref().len() != 64 { @@ -49,7 +47,7 @@ impl Verifier for Vault { let public_key = ed25519_dalek::PublicKey::from_bytes(public_key.data()).unwrap(); Ok(public_key.verify(data.as_ref(), &signature).is_ok()) } - SecretType::NistP256 => { + KeyType::NistP256 => { cfg_if! { if #[cfg(feature = "rustcrypto")] { use p256::ecdsa::{VerifyingKey, Signature, signature::Verifier as _}; @@ -62,7 +60,7 @@ impl Verifier for Vault { } } } - SecretType::Buffer | SecretType::Aes => Err(VaultError::InvalidPublicKey.into()), + KeyType::Buffer | KeyType::Aes => Err(VaultError::InvalidPublicKey.into()), } } }