identity_storage/key_storage/jwk_storage.rs
1// Copyright 2020-2023 IOTA Stiftung
2// SPDX-License-Identifier: Apache-2.0
3
4use crate::key_storage::KeyId;
5use crate::key_storage::KeyStorageError;
6use crate::key_storage::KeyType;
7use async_trait::async_trait;
8use identity_verification::jose::jwk::Jwk;
9use identity_verification::jose::jws::JwsAlgorithm;
10
11use super::jwk_gen_output::JwkGenOutput;
12
13/// Result of key storage operations.
14pub type KeyStorageResult<T> = Result<T, KeyStorageError>;
15
16#[cfg(not(feature = "send-sync-storage"))]
17mod storage_sub_trait {
18 pub trait StorageSendSyncMaybe {}
19 impl<S: super::JwkStorage> StorageSendSyncMaybe for S {}
20}
21
22#[cfg(feature = "send-sync-storage")]
23mod storage_sub_trait {
24 pub trait StorageSendSyncMaybe: Send + Sync {}
25 impl<S: Send + Sync + super::JwkStorage> StorageSendSyncMaybe for S {}
26}
27
28/// Secure storage for cryptographic keys represented as JWKs.
29#[cfg_attr(not(feature = "send-sync-storage"), async_trait(?Send))]
30#[cfg_attr(feature = "send-sync-storage", async_trait)]
31pub trait JwkStorage: storage_sub_trait::StorageSendSyncMaybe {
32 /// Generate a new key represented as a JSON Web Key.
33 ///
34 /// It is recommended that the implementer exposes constants for the supported [`KeyType`].
35 async fn generate(&self, key_type: KeyType, alg: JwsAlgorithm) -> KeyStorageResult<JwkGenOutput>;
36
37 /// Insert an existing JSON Web Key into the storage.
38 ///
39 /// All private key components of the `jwk` must be set.
40 async fn insert(&self, jwk: Jwk) -> KeyStorageResult<KeyId>;
41
42 /// Sign the provided `data` using the private key identified by `key_id` according to the requirements of
43 /// the corresponding `public_key` (see [`Jwk::alg`](Jwk::alg()) etc.).
44 ///
45 /// # Note
46 ///
47 /// High level methods from this library calling this method are designed to always pass a `public_key` that
48 /// corresponds to `key_id` and additional checks for this in the `sign` implementation are normally not required.
49 /// This is however based on the expectation that the key material associated with a given [`KeyId`] is immutable.
50 async fn sign(&self, key_id: &KeyId, data: &[u8], public_key: &Jwk) -> KeyStorageResult<Vec<u8>>;
51
52 /// Deletes the key identified by `key_id`.
53 ///
54 /// If the corresponding key does not exist in storage, a [`KeyStorageError`] with kind
55 /// [`KeyNotFound`](crate::key_storage::KeyStorageErrorKind::KeyNotFound) must be returned.
56 ///
57 /// # Warning
58 ///
59 /// This operation cannot be undone. The keys are purged permanently.
60 async fn delete(&self, key_id: &KeyId) -> KeyStorageResult<()>;
61
62 /// Returns `true` if the key with the given `key_id` exists in storage, `false` otherwise.
63 async fn exists(&self, key_id: &KeyId) -> KeyStorageResult<bool>;
64}