Skip to content

Commit

Permalink
Remove unrequired LoginCtx clones
Browse files Browse the repository at this point in the history
  • Loading branch information
sosthene-nitrokey committed Sep 9, 2024
1 parent c408fd9 commit bbff24a
Show file tree
Hide file tree
Showing 6 changed files with 35 additions and 64 deletions.
8 changes: 3 additions & 5 deletions pkcs11/src/backend/decrypt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,10 @@ pub struct DecryptCtx {
pub mechanism: Mechanism,
pub key_id: String,
pub data: Vec<u8>,
login_ctx: LoginCtx,
}

impl DecryptCtx {
pub fn init(mechanism: Mechanism, key: &Object, login_ctx: LoginCtx) -> Result<Self, Error> {
pub fn init(mechanism: Mechanism, key: &Object, login_ctx: &LoginCtx) -> Result<Self, Error> {
if !login_ctx.can_run_mode(crate::backend::login::UserMode::Operator) {
return Err(Error::NotLoggedIn(login::UserMode::Operator));
}
Expand All @@ -42,14 +41,13 @@ impl DecryptCtx {
mechanism,
key_id: key.id.clone(),
data: Vec::new(),
login_ctx,
})
}
pub fn update(&mut self, data: &[u8]) {
self.data.extend_from_slice(data);
}

pub fn decrypt_final(&mut self) -> Result<Vec<u8>, Error> {
pub fn decrypt_final(&mut self, login_ctx: &LoginCtx) -> Result<Vec<u8>, Error> {
if self.data.is_empty() {
return Err(Error::InvalidEncryptedDataLength);
}
Expand All @@ -72,7 +70,7 @@ impl DecryptCtx {

let key_id = self.key_id.as_str();

let output = self.login_ctx.try_(
let output = login_ctx.try_(
|api_config| {
default_api::keys_key_id_decrypt_post(
api_config,
Expand Down
19 changes: 6 additions & 13 deletions pkcs11/src/backend/encrypt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,11 +21,10 @@ pub struct EncryptCtx {
pub mechanism: Mechanism,
pub key_id: String,
pub data: Vec<u8>,
login_ctx: LoginCtx,
}

impl EncryptCtx {
pub fn init(mechanism: Mechanism, key: &Object, login_ctx: LoginCtx) -> Result<Self, Error> {
pub fn init(mechanism: Mechanism, key: &Object, login_ctx: &LoginCtx) -> Result<Self, Error> {
if !login_ctx.can_run_mode(crate::backend::login::UserMode::Operator) {
return Err(Error::NotLoggedIn(login::UserMode::Operator));
}
Expand Down Expand Up @@ -56,7 +55,6 @@ impl EncryptCtx {
mechanism,
key_id: key.id.clone(),
data: Vec::new(),
login_ctx,
})
}

Expand All @@ -70,7 +68,7 @@ impl EncryptCtx {
full_blocks * ENCRYPT_BLOCK_SIZE
}

pub fn encrypt_available_data(&mut self) -> Result<Vec<u8>, Error> {
pub fn encrypt_available_data(&mut self, login_ctx: &LoginCtx) -> Result<Vec<u8>, Error> {
let chunk_size = self.get_biggest_chunk_len();

// if there is no data to encrypt, return an empty vector
Expand All @@ -81,18 +79,13 @@ impl EncryptCtx {
// drain the data to encrypt from the data vector

let input_data = self.data.drain(..chunk_size).collect::<Vec<u8>>();
encrypt_data(
&self.key_id,
self.login_ctx.clone(),
&input_data,
&self.mechanism,
)
encrypt_data(&self.key_id, login_ctx, &input_data, &self.mechanism)
}

pub fn encrypt_final(&self) -> Result<Vec<u8>, Error> {
pub fn encrypt_final(&self, login_ctx: &LoginCtx) -> Result<Vec<u8>, Error> {
encrypt_data(
&self.key_id,
self.login_ctx.clone(),
login_ctx,
self.data.as_slice(),
&self.mechanism,
)
Expand All @@ -101,7 +94,7 @@ impl EncryptCtx {

fn encrypt_data(
key_id: &str,
login_ctx: LoginCtx,
login_ctx: &LoginCtx,
data: &[u8],
mechanism: &Mechanism,
) -> Result<Vec<u8>, Error> {
Expand Down
16 changes: 7 additions & 9 deletions pkcs11/src/backend/key.rs
Original file line number Diff line number Diff line change
Expand Up @@ -154,7 +154,7 @@ pub fn parse_attributes(template: &CkRawAttrTemplate) -> Result<ParsedAttributes

fn upload_certificate(
parsed_template: &ParsedAttributes,
login_ctx: LoginCtx,
login_ctx: &LoginCtx,
) -> Result<(String, ObjectKind, Option<Vec<u8>>), Error> {
let cert = parsed_template
.value
Expand Down Expand Up @@ -196,7 +196,7 @@ fn upload_certificate(

pub fn create_key_from_template(
template: CkRawAttrTemplate,
login_ctx: LoginCtx,
login_ctx: &LoginCtx,
) -> Result<(String, ObjectKind, Option<Vec<u8>>), Error> {
let parsed = parse_attributes(&template)?;

Expand Down Expand Up @@ -415,7 +415,7 @@ pub fn generate_key_from_template(
template: &CkRawAttrTemplate,
public_template: Option<&CkRawAttrTemplate>,
mechanism: &Mechanism,
login_ctx: LoginCtx,
login_ctx: &LoginCtx,
db: &Mutex<db::Db>,
) -> Result<Vec<(CK_OBJECT_HANDLE, Object)>, Error> {
let parsed = parse_attributes(template)?;
Expand Down Expand Up @@ -462,7 +462,7 @@ pub fn generate_key_from_template(
fn fetch_one_key(
key_id: &str,
raw_id: Option<Vec<u8>>,
login_ctx: LoginCtx,
login_ctx: &LoginCtx,
) -> Result<Vec<Object>, Error> {
if !login_ctx.can_run_mode(super::login::UserMode::OperatorOrAdministrator) {
return Err(Error::NotLoggedIn(
Expand Down Expand Up @@ -499,7 +499,7 @@ fn fetch_one_key(
pub fn fetch_key(
key_id: &str,
raw_id: Option<Vec<u8>>,
login_ctx: LoginCtx,
login_ctx: &LoginCtx,
db: &Mutex<db::Db>,
) -> Result<Vec<(CK_OBJECT_HANDLE, Object)>, Error> {
let objects = fetch_one_key(key_id, raw_id, login_ctx)?;
Expand All @@ -512,7 +512,7 @@ pub fn fetch_key(
fn fetch_one_certificate(
key_id: &str,
raw_id: Option<Vec<u8>>,
login_ctx: LoginCtx,
login_ctx: &LoginCtx,
) -> Result<Object, Error> {
if !login_ctx.can_run_mode(super::login::UserMode::OperatorOrAdministrator) {
return Err(Error::NotLoggedIn(
Expand All @@ -533,7 +533,7 @@ fn fetch_one_certificate(
pub fn fetch_certificate(
key_id: &str,
raw_id: Option<Vec<u8>>,
login_ctx: LoginCtx,
login_ctx: &LoginCtx,
db: &Mutex<db::Db>,
) -> Result<(CK_OBJECT_HANDLE, Object), Error> {
let object = fetch_one_certificate(key_id, raw_id, login_ctx)?;
Expand Down Expand Up @@ -571,12 +571,10 @@ pub fn fetch_one(
| Some(ObjectKind::PublicKey)
| Some(ObjectKind::SecretKey)
) {
let login_ctx = login_ctx.clone();
acc = fetch_one_key(&key.id, None, login_ctx)?;
}

if matches!(kind, None | Some(ObjectKind::Certificate)) {
let login_ctx = login_ctx.clone();
match fetch_one_certificate(&key.id, None, login_ctx) {
Ok(cert) => acc.push(cert),
Err(err) => {
Expand Down
7 changes: 4 additions & 3 deletions pkcs11/src/backend/login.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ use crate::config::{

use super::{ApiError, Error};

#[derive(Debug, Clone)]
#[derive(Debug)]
pub struct LoginCtx {
slot: Arc<Slot>,
/// If set to `Some`, this will be used to replace the slot's default value when performing requests
Expand Down Expand Up @@ -166,7 +166,7 @@ impl LoginCtx {
}

fn operator(&self) -> Option<Configuration> {
get_user_api_config(self.operator_config(), &self.next_instance())
get_user_api_config(self.operator_config(), self.next_instance())
}

fn administrator(&self) -> Option<Configuration> {
Expand Down Expand Up @@ -288,7 +288,7 @@ impl LoginCtx {
}
CKS_RW_USER_FUNCTIONS => {
let username = match self.operator_config() {
Some(ref user) => user.username.clone(),
Some(user) => user.username.clone(),
None => return CKR_USER_NOT_LOGGED_IN,
};

Expand Down Expand Up @@ -363,6 +363,7 @@ fn get_user_api_config(
api_config: &nethsm_sdk_rs::apis::configuration::Configuration,
) -> Option<nethsm_sdk_rs::apis::configuration::Configuration> {
let user = user?;

if user.password.is_none() {
return None;
}

Check failure on line 369 in pkcs11/src/backend/login.rs

View workflow job for this annotation

GitHub Actions / clippy

this block may be rewritten with the `?` operator

error: this block may be rewritten with the `?` operator --> pkcs11/src/backend/login.rs:367:5 | 367 | / if user.password.is_none() { 368 | | return None; 369 | | } | |_____^ help: replace it with: `user.password.as_ref()?;` | = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#question_mark = note: `-D clippy::question-mark` implied by `-D warnings` = help: to override `-D warnings` add `#[allow(clippy::question_mark)]`

Check failure on line 369 in pkcs11/src/backend/login.rs

View workflow job for this annotation

GitHub Actions / clippy

this block may be rewritten with the `?` operator

error: this block may be rewritten with the `?` operator --> pkcs11/src/backend/login.rs:367:5 | 367 | / if user.password.is_none() { 368 | | return None; 369 | | } | |_____^ help: replace it with: `user.password.as_ref()?;` | = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#question_mark = note: `-D clippy::question-mark` implied by `-D warnings` = help: to override `-D warnings` add `#[allow(clippy::question_mark)]`
Expand Down
41 changes: 13 additions & 28 deletions pkcs11/src/backend/session.rs
Original file line number Diff line number Diff line change
Expand Up @@ -202,11 +202,7 @@ impl Session {
}
}?;

self.sign_ctx = Some(SignCtx::init(
mechanism.clone(),
key,
self.login_ctx.clone(),
)?);
self.sign_ctx = Some(SignCtx::init(mechanism.clone(), key, &self.login_ctx)?);

Ok(())
}
Expand Down Expand Up @@ -236,7 +232,7 @@ impl Session {
.as_mut()
.ok_or(Error::OperationNotInitialized)?;

sign_ctx.sign_final()
sign_ctx.sign_final(&self.login_ctx)
}

pub fn sign(&mut self, data: &[u8]) -> Result<Vec<u8>, Error> {
Expand Down Expand Up @@ -271,11 +267,7 @@ impl Session {
}
}?;

self.encrypt_ctx = Some(EncryptCtx::init(
mechanism.clone(),
&key,
self.login_ctx.clone(),
)?);
self.encrypt_ctx = Some(EncryptCtx::init(mechanism.clone(), &key, &self.login_ctx)?);

Ok(())
}
Expand All @@ -296,7 +288,7 @@ impl Session {
.as_mut()
.ok_or(Error::OperationNotInitialized)?;

encrypt_ctx.encrypt_available_data()
encrypt_ctx.encrypt_available_data(&self.login_ctx)
}

pub fn encrypt_update(&mut self, data: &[u8]) -> Result<Vec<u8>, Error> {
Expand All @@ -319,7 +311,7 @@ impl Session {
.as_mut()
.ok_or(Error::OperationNotInitialized)?;

encrypt_ctx.encrypt_final()
encrypt_ctx.encrypt_final(&self.login_ctx)
}

pub fn encrypt(&mut self, data: &[u8]) -> Result<Vec<u8>, Error> {
Expand Down Expand Up @@ -354,11 +346,7 @@ impl Session {
}
}?;

self.decrypt_ctx = Some(DecryptCtx::init(
mechanism.clone(),
&key,
self.login_ctx.clone(),
)?);
self.decrypt_ctx = Some(DecryptCtx::init(mechanism.clone(), &key, &self.login_ctx)?);

Ok(())
}
Expand Down Expand Up @@ -394,7 +382,7 @@ impl Session {
.as_mut()
.ok_or(Error::OperationNotInitialized)?;

decrypt_ctx.decrypt_final()
decrypt_ctx.decrypt_final(&self.login_ctx)
}

pub fn decrypt(&mut self, data: &[u8]) -> Result<Vec<u8>, Error> {
Expand Down Expand Up @@ -442,7 +430,7 @@ impl Session {
results = fetch_key(
&key_id,
requirements.raw_id.clone(),
self.login_ctx.clone(),
&self.login_ctx,
&self.db.0,
)?;
}
Expand All @@ -453,7 +441,7 @@ impl Session {
match fetch_certificate(
&key_id,
requirements.raw_id,
self.login_ctx.clone(),
&self.login_ctx,
&self.db.0,
) {
Ok(cert) => {
Expand Down Expand Up @@ -598,21 +586,18 @@ impl Session {
return Err(Error::NotLoggedIn(super::login::UserMode::Administrator));
}

let login_ctx = self.login_ctx.clone();
let key_info = create_key_from_template(template, &self.login_ctx)?;

let key_info = create_key_from_template(template, login_ctx)?;

let login_ctx = self.login_ctx.clone();
let db = self.db.clone();

match key_info.1 {
ObjectKind::Certificate => Ok(vec![fetch_certificate(
&key_info.0,
None,
login_ctx,
&self.login_ctx,
&db.0,
)?]),
_ => fetch_key(&key_info.0, None, login_ctx, &db.0),
_ => fetch_key(&key_info.0, None, &self.login_ctx, &db.0),
}
}

Expand Down Expand Up @@ -678,7 +663,7 @@ impl Session {
template,
public_template,
mechanism,
self.login_ctx.clone(),
&self.login_ctx,
&self.db.0,
)
}
Expand Down
8 changes: 2 additions & 6 deletions pkcs11/src/backend/sign.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,10 @@ pub struct SignCtx {
pub sign_name: SignMode,
pub key: Object,
pub data: Vec<u8>,
pub login_ctx: LoginCtx,
}

impl SignCtx {
pub fn init(mechanism: Mechanism, key: Object, login_ctx: LoginCtx) -> Result<Self, Error> {
pub fn init(mechanism: Mechanism, key: Object, login_ctx: &LoginCtx) -> Result<Self, Error> {
trace!("key_type: {:?}", key.kind);

if !login_ctx.can_run_mode(crate::backend::login::UserMode::Operator) {
Expand Down Expand Up @@ -58,14 +57,13 @@ impl SignCtx {
key,
sign_name,
data: Vec::new(),
login_ctx,
})
}
pub fn update(&mut self, data: &[u8]) {
self.data.extend_from_slice(data);
}

pub fn sign_final(&self) -> Result<Vec<u8>, Error> {
pub fn sign_final(&self, login_ctx: &LoginCtx) -> Result<Vec<u8>, Error> {
// helper function to hash the data with the correct algorithm
fn hasher<D: Digest>(data: &[u8]) -> Vec<u8> {
let mut hasher = D::new();
Expand Down Expand Up @@ -102,8 +100,6 @@ impl SignCtx {
let mode = self.sign_name;
trace!("Signing with mode: {:?}", mode);

let login_ctx = self.login_ctx.clone();

let signature = login_ctx.try_(
|conf| {
default_api::keys_key_id_sign_post(
Expand Down

0 comments on commit bbff24a

Please sign in to comment.