cargo fmt + clippy (#2241)

Signed-off-by: Samuel Cabrero <scabrero@suse.de>
This commit is contained in:
Samuel Cabrero 2023-10-26 21:40:24 -07:00 committed by GitHub
parent 18b4b7549f
commit 99ba97088d
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
14 changed files with 108 additions and 110 deletions

View file

@ -254,7 +254,7 @@ pub(crate) fn gen_private_key(
/// build up a CA certificate and key. /// build up a CA certificate and key.
pub(crate) fn build_ca(ca_config: Option<CAConfig>) -> Result<CaHandle, ErrorStack> { pub(crate) fn build_ca(ca_config: Option<CAConfig>) -> Result<CaHandle, ErrorStack> {
let ca_config = ca_config.unwrap_or(CAConfig::default()); let ca_config = ca_config.unwrap_or_default();
let ca_key = gen_private_key(&ca_config.key_type, Some(ca_config.key_bits))?; let ca_key = gen_private_key(&ca_config.key_type, Some(ca_config.key_bits))?;
@ -419,7 +419,7 @@ pub(crate) fn build_cert(
key_type: Option<KeyType>, key_type: Option<KeyType>,
key_bits: Option<u64>, key_bits: Option<u64>,
) -> Result<CertHandle, ErrorStack> { ) -> Result<CertHandle, ErrorStack> {
let key_type = key_type.unwrap_or(KeyType::default()); let key_type = key_type.unwrap_or_default();
let int_key = gen_private_key(&key_type, key_bits)?; let int_key = gen_private_key(&key_type, key_bits)?;
let mut req_builder = X509ReqBuilder::new()?; let mut req_builder = X509ReqBuilder::new()?;

View file

@ -26,6 +26,7 @@ impl WebError {
let mut res = self.into_response(); let mut res = self.into_response();
res.headers_mut().insert( res.headers_mut().insert(
ACCESS_CONTROL_ALLOW_ORIGIN, ACCESS_CONTROL_ALLOW_ORIGIN,
#[allow(clippy::expect_used)]
HeaderValue::from_str("*").expect("Header generation failed, this is weird."), HeaderValue::from_str("*").expect("Header generation failed, this is weird."),
); );
res res

View file

@ -756,7 +756,6 @@ impl Display for TaskName {
TaskName::LdapActor => "LDAP Acceptor Actor", TaskName::LdapActor => "LDAP Acceptor Actor",
TaskName::Replication => "Replication", TaskName::Replication => "Replication",
} }
.to_string()
) )
} }
} }

View file

@ -1293,7 +1293,6 @@ lazy_static! {
create_classes: vec![ create_classes: vec![
EntryClass::AccountPolicy, EntryClass::AccountPolicy,
], ],
..Default::default()
}; };
} }

View file

@ -438,7 +438,6 @@ lazy_static! {
// Enforce this is a system protected object // Enforce this is a system protected object
(Attribute::Class, EntryClass::System.to_value()), (Attribute::Class, EntryClass::System.to_value()),
], ],
..Default::default()
}; };
pub static ref IDM_ALL_ACCOUNTS: BuiltinGroup = BuiltinGroup { pub static ref IDM_ALL_ACCOUNTS: BuiltinGroup = BuiltinGroup {
@ -456,7 +455,6 @@ lazy_static! {
// Enforce this is a system protected object // Enforce this is a system protected object
(Attribute::Class, EntryClass::System.to_value()), (Attribute::Class, EntryClass::System.to_value()),
], ],
..Default::default()
}; };

View file

@ -35,19 +35,19 @@ pub(crate) struct AccountPolicy {
credential_policy: CredentialPolicy, credential_policy: CredentialPolicy,
} }
impl Into<Option<AccountPolicy>> for &EntrySealedCommitted { impl From<&EntrySealedCommitted> for Option<AccountPolicy> {
fn into(self) -> Option<AccountPolicy> { fn from(val: &EntrySealedCommitted) -> Self {
if !self.attribute_equality( if !val.attribute_equality(
Attribute::Class, Attribute::Class,
&EntryClass::AccountPolicy.to_partialvalue(), &EntryClass::AccountPolicy.to_partialvalue(),
) { ) {
return None; return None;
} }
let authsession_expiry = self let authsession_expiry = val
.get_ava_single_uint32(Attribute::AuthSessionExpiry) .get_ava_single_uint32(Attribute::AuthSessionExpiry)
.unwrap_or(MAXIMUM_AUTH_SESSION_EXPIRY); .unwrap_or(MAXIMUM_AUTH_SESSION_EXPIRY);
let privilege_expiry = self let privilege_expiry = val
.get_ava_single_uint32(Attribute::PrivilegeExpiry) .get_ava_single_uint32(Attribute::PrivilegeExpiry)
.unwrap_or(MAXIMUM_AUTH_PRIVILEGE_EXPIRY); .unwrap_or(MAXIMUM_AUTH_PRIVILEGE_EXPIRY);
let credential_policy = CredentialPolicy::default(); let credential_policy = CredentialPolicy::default();

View file

@ -714,6 +714,15 @@ impl AuthSessionState {
} }
} }
pub(crate) struct AuthSessionData<'a> {
pub(crate) account: Account,
pub(crate) account_policy: ResolvedAccountPolicy,
pub(crate) issue: AuthIssueSession,
pub(crate) webauthn: &'a Webauthn,
pub(crate) ct: Duration,
pub(crate) source: Source,
}
#[derive(Clone)] #[derive(Clone)]
/// The current state of an authentication session that is in progress. /// The current state of an authentication session that is in progress.
pub(crate) struct AuthSession { pub(crate) struct AuthSession {
@ -745,34 +754,26 @@ impl AuthSession {
/// Create a new auth session, based on the available credential handlers of the account. /// Create a new auth session, based on the available credential handlers of the account.
/// the session is a whole encapsulated unit of what we need to proceed, so that subsequent /// the session is a whole encapsulated unit of what we need to proceed, so that subsequent
/// or interleved write operations do not cause inconsistency in this process. /// or interleved write operations do not cause inconsistency in this process.
pub fn new( pub fn new(asd: AuthSessionData<'_>, privileged: bool) -> (Option<Self>, AuthState) {
account: Account,
account_policy: ResolvedAccountPolicy,
issue: AuthIssueSession,
privileged: bool,
webauthn: &Webauthn,
ct: Duration,
source: Source,
) -> (Option<Self>, AuthState) {
// During this setup, determine the credential handler that we'll be using // During this setup, determine the credential handler that we'll be using
// for this session. This is currently based on presentation of an application // for this session. This is currently based on presentation of an application
// id. // id.
let state = if account.is_within_valid_time(ct) { let state = if asd.account.is_within_valid_time(asd.ct) {
// We want the primary handler - this is where we make a decision // We want the primary handler - this is where we make a decision
// based on the anonymous ... in theory this could be cleaner // based on the anonymous ... in theory this could be cleaner
// and interact with the account more? // and interact with the account more?
if account.is_anonymous() { if asd.account.is_anonymous() {
AuthSessionState::Init(nonempty![CredHandler::Anonymous { AuthSessionState::Init(nonempty![CredHandler::Anonymous {
cred_id: account.uuid, cred_id: asd.account.uuid,
}]) }])
} else { } else {
// What's valid to use in this context? // What's valid to use in this context?
let mut handlers = Vec::new(); let mut handlers = Vec::new();
if let Some(cred) = &account.primary { if let Some(cred) = &asd.account.primary {
// TODO: Make it possible to have multiple creds. // TODO: Make it possible to have multiple creds.
// Probably means new authsession has to be failable // Probably means new authsession has to be failable
if let Ok(ch) = CredHandler::try_from((cred, webauthn)) { if let Ok(ch) = CredHandler::try_from((cred, asd.webauthn)) {
handlers.push(ch); handlers.push(ch);
} else { } else {
security_critical!( security_critical!(
@ -781,7 +782,7 @@ impl AuthSession {
} }
} }
if let Ok(ch) = CredHandler::try_from((&account.passkeys, webauthn)) { if let Ok(ch) = CredHandler::try_from((&asd.account.passkeys, asd.webauthn)) {
handlers.push(ch); handlers.push(ch);
}; };
@ -804,12 +805,12 @@ impl AuthSession {
} else { } else {
// We can proceed // We can proceed
let auth_session = AuthSession { let auth_session = AuthSession {
account, account: asd.account,
account_policy, account_policy: asd.account_policy,
state, state,
issue, issue: asd.issue,
intent: AuthIntent::InitialAuth { privileged }, intent: AuthIntent::InitialAuth { privileged },
source, source: asd.source,
}; };
// Get the set of mechanisms that can proceed. This is tied // Get the set of mechanisms that can proceed. This is tied
// to the session so that it can mutate state and have progression // to the session so that it can mutate state and have progression
@ -827,15 +828,10 @@ impl AuthSession {
/// will be used in this operation based on the credential id that was used in the /// will be used in this operation based on the credential id that was used in the
/// initial authentication. /// initial authentication.
pub(crate) fn new_reauth( pub(crate) fn new_reauth(
account: Account, asd: AuthSessionData<'_>,
account_policy: ResolvedAccountPolicy,
session_id: Uuid, session_id: Uuid,
session: &Session, session: &Session,
cred_id: Uuid, cred_id: Uuid,
issue: AuthIssueSession,
webauthn: &Webauthn,
ct: Duration,
source: Source,
) -> (Option<Self>, AuthState) { ) -> (Option<Self>, AuthState) {
/// An inner enum to allow us to more easily define state within this fn /// An inner enum to allow us to more easily define state within this fn
enum State { enum State {
@ -844,7 +840,7 @@ impl AuthSession {
Proceed(CredHandler), Proceed(CredHandler),
} }
let state = if account.is_within_valid_time(ct) { let state = if asd.account.is_within_valid_time(asd.ct) {
// Get the credential that matches this cred_id. // Get the credential that matches this cred_id.
// //
// To make this work "cleanly" we can't really nest a bunch of if // To make this work "cleanly" we can't really nest a bunch of if
@ -856,9 +852,9 @@ impl AuthSession {
let mut cred_handler = None; let mut cred_handler = None;
if let Some(primary) = account.primary.as_ref() { if let Some(primary) = asd.account.primary.as_ref() {
if primary.uuid == cred_id { if primary.uuid == cred_id {
if let Ok(ch) = CredHandler::try_from((primary, webauthn)) { if let Ok(ch) = CredHandler::try_from((primary, asd.webauthn)) {
// Update it. // Update it.
debug_assert!(cred_handler.is_none()); debug_assert!(cred_handler.is_none());
cred_handler = Some(ch); cred_handler = Some(ch);
@ -870,8 +866,8 @@ impl AuthSession {
} }
} }
if let Some(pk) = account.passkeys.get(&cred_id).map(|(_, pk)| pk) { if let Some(pk) = asd.account.passkeys.get(&cred_id).map(|(_, pk)| pk) {
if let Ok(ch) = CredHandler::try_from((cred_id, pk, webauthn)) { if let Ok(ch) = CredHandler::try_from((cred_id, pk, asd.webauthn)) {
// Update it. // Update it.
debug_assert!(cred_handler.is_none()); debug_assert!(cred_handler.is_none());
cred_handler = Some(ch); cred_handler = Some(ch);
@ -906,15 +902,15 @@ impl AuthSession {
State::Proceed(handler) => { State::Proceed(handler) => {
let allow = handler.next_auth_allowed(); let allow = handler.next_auth_allowed();
let auth_session = AuthSession { let auth_session = AuthSession {
account, account: asd.account,
account_policy, account_policy: asd.account_policy,
state: AuthSessionState::InProgress(handler), state: AuthSessionState::InProgress(handler),
issue, issue: asd.issue,
intent: AuthIntent::Reauth { intent: AuthIntent::Reauth {
session_id, session_id,
session_expiry, session_expiry,
}, },
source, source: asd.source,
}; };
let as_state = AuthState::Continue(allow); let as_state = AuthState::Continue(allow);
@ -1260,8 +1256,8 @@ mod tests {
use crate::idm::accountpolicy::ResolvedAccountPolicy; use crate::idm::accountpolicy::ResolvedAccountPolicy;
use crate::idm::audit::AuditEvent; use crate::idm::audit::AuditEvent;
use crate::idm::authsession::{ use crate::idm::authsession::{
AuthSession, BAD_AUTH_TYPE_MSG, BAD_BACKUPCODE_MSG, BAD_PASSWORD_MSG, BAD_TOTP_MSG, AuthSession, AuthSessionData, BAD_AUTH_TYPE_MSG, BAD_BACKUPCODE_MSG, BAD_PASSWORD_MSG,
BAD_WEBAUTHN_MSG, PW_BADLIST_MSG, BAD_TOTP_MSG, BAD_WEBAUTHN_MSG, PW_BADLIST_MSG,
}; };
use crate::idm::delayed::DelayedAction; use crate::idm::delayed::DelayedAction;
use crate::idm::AuthState; use crate::idm::AuthState;
@ -1296,16 +1292,15 @@ mod tests {
let anon_account: Account = BUILTIN_ACCOUNT_ANONYMOUS_V1.clone().into(); let anon_account: Account = BUILTIN_ACCOUNT_ANONYMOUS_V1.clone().into();
let (session, state) = AuthSession::new( let asd = AuthSessionData {
anon_account, account: anon_account,
ResolvedAccountPolicy::default(), account_policy: ResolvedAccountPolicy::default(),
AuthIssueSession::Token, issue: AuthIssueSession::Token,
false, webauthn: &webauthn,
&webauthn, ct: duration_from_epoch_now(),
duration_from_epoch_now(), source: Source::Internal,
Source::Internal, };
); let (session, state) = AuthSession::new(asd, false);
if let AuthState::Choose(auth_mechs) = state { if let AuthState::Choose(auth_mechs) = state {
assert!(auth_mechs.iter().any(|x| matches!(x, AuthMech::Anonymous))); assert!(auth_mechs.iter().any(|x| matches!(x, AuthMech::Anonymous)));
} else { } else {
@ -1333,15 +1328,15 @@ mod tests {
$webauthn:expr, $webauthn:expr,
$privileged:expr $privileged:expr
) => {{ ) => {{
let (session, state) = AuthSession::new( let asd = AuthSessionData {
$account.clone(), account: $account.clone(),
ResolvedAccountPolicy::default(), account_policy: ResolvedAccountPolicy::default(),
AuthIssueSession::Token, issue: AuthIssueSession::Token,
$privileged, webauthn: $webauthn,
$webauthn, ct: duration_from_epoch_now(),
duration_from_epoch_now(), source: Source::Internal,
Source::Internal, };
); let (session, state) = AuthSession::new(asd, $privileged);
let mut session = session.unwrap(); let mut session = session.unwrap();
if let AuthState::Choose(auth_mechs) = state { if let AuthState::Choose(auth_mechs) = state {
@ -1514,15 +1509,15 @@ mod tests {
$account:expr, $account:expr,
$webauthn:expr $webauthn:expr
) => {{ ) => {{
let (session, state) = AuthSession::new( let asd = AuthSessionData {
$account.clone(), account: $account.clone(),
ResolvedAccountPolicy::default(), account_policy: ResolvedAccountPolicy::default(),
AuthIssueSession::Token, issue: AuthIssueSession::Token,
false, webauthn: $webauthn,
$webauthn, ct: duration_from_epoch_now(),
duration_from_epoch_now(), source: Source::Internal,
Source::Internal, };
); let (session, state) = AuthSession::new(asd, false);
let mut session = session.expect("Session was unable to be created."); let mut session = session.expect("Session was unable to be created.");
if let AuthState::Choose(auth_mechs) = state { if let AuthState::Choose(auth_mechs) = state {
@ -1842,15 +1837,15 @@ mod tests {
$account:expr, $account:expr,
$webauthn:expr $webauthn:expr
) => {{ ) => {{
let (session, state) = AuthSession::new( let asd = AuthSessionData {
$account.clone(), account: $account.clone(),
ResolvedAccountPolicy::default(), account_policy: ResolvedAccountPolicy::default(),
AuthIssueSession::Token, issue: AuthIssueSession::Token,
false, webauthn: $webauthn,
$webauthn, ct: duration_from_epoch_now(),
duration_from_epoch_now(), source: Source::Internal,
Source::Internal, };
); let (session, state) = AuthSession::new(asd, false);
let mut session = session.unwrap(); let mut session = session.unwrap();
if let AuthState::Choose(auth_mechs) = state { if let AuthState::Choose(auth_mechs) = state {

View file

@ -2,7 +2,7 @@ use crate::prelude::*;
use crate::credential::softlock::CredSoftLock; use crate::credential::softlock::CredSoftLock;
use crate::idm::account::Account; use crate::idm::account::Account;
use crate::idm::authsession::AuthSession; use crate::idm::authsession::{AuthSession, AuthSessionData};
use crate::idm::event::AuthResult; use crate::idm::event::AuthResult;
use crate::idm::server::IdmServerAuthTransaction; use crate::idm::server::IdmServerAuthTransaction;
use crate::idm::AuthState; use crate::idm::AuthState;
@ -129,17 +129,16 @@ impl<'a> IdmServerAuthTransaction<'a> {
} }
// Create a re-auth session // Create a re-auth session
let (auth_session, state) = AuthSession::new_reauth( let asd: AuthSessionData = AuthSessionData {
account, account,
account_policy, account_policy,
ident.session_id,
session,
session_cred_id,
issue, issue,
self.webauthn, webauthn: self.webauthn,
ct, ct,
source, source,
); };
let (auth_session, state) =
AuthSession::new_reauth(asd, ident.session_id, session, session_cred_id);
// Push the re-auth session to the session maps. // Push the re-auth session to the session maps.
match auth_session { match auth_session {

View file

@ -30,7 +30,7 @@ use super::ldap::{LdapBoundToken, LdapSession};
use crate::credential::{softlock::CredSoftLock, Credential}; use crate::credential::{softlock::CredSoftLock, Credential};
use crate::idm::account::Account; use crate::idm::account::Account;
use crate::idm::audit::AuditEvent; use crate::idm::audit::AuditEvent;
use crate::idm::authsession::AuthSession; use crate::idm::authsession::{AuthSession, AuthSessionData};
use crate::idm::credupdatesession::CredentialUpdateSessionMutex; use crate::idm::credupdatesession::CredentialUpdateSessionMutex;
use crate::idm::delayed::{ use crate::idm::delayed::{
AuthSessionRecord, BackupCodeRemoval, DelayedAction, PasswordUpgrade, UnixPasswordUpgrade, AuthSessionRecord, BackupCodeRemoval, DelayedAction, PasswordUpgrade, UnixPasswordUpgrade,
@ -1022,15 +1022,16 @@ impl<'a> IdmServerAuthTransaction<'a> {
slock_ref slock_ref
}); });
let (auth_session, state) = AuthSession::new( let asd: AuthSessionData = AuthSessionData {
account, account,
account_policy, account_policy,
init.issue, issue: init.issue,
init.privileged, webauthn: self.webauthn,
self.webauthn,
ct, ct,
source, source,
); };
let (auth_session, state) = AuthSession::new(asd, init.privileged);
match auth_session { match auth_session {
Some(auth_session) => { Some(auth_session) => {

View file

@ -58,12 +58,9 @@ impl DefaultValues {
// We have to do this rather than get_uuid here because at this stage we haven't // We have to do this rather than get_uuid here because at this stage we haven't
// scheme validated the entry so it's uuid could be missing in theory. // scheme validated the entry so it's uuid could be missing in theory.
let e_uuid = match e.get_ava_single_uuid(Attribute::Uuid) { let Some(e_uuid) = e.get_ava_single_uuid(Attribute::Uuid) else {
Some(e_uuid) => e_uuid,
None => {
trace!("entry does not contain a uuid"); trace!("entry does not contain a uuid");
return Ok(()); return Ok(());
}
}; };
if e_uuid == UUID_IDM_ALL_ACCOUNTS { if e_uuid == UUID_IDM_ALL_ACCOUNTS {

View file

@ -1184,8 +1184,12 @@ impl QueryServer {
.expect("unable to acquire db_ticket for qsr") .expect("unable to acquire db_ticket for qsr")
}; };
#[allow(clippy::expect_used)]
QueryServerReadTransaction { QueryServerReadTransaction {
be_txn: self.be.read().unwrap(), be_txn: self
.be
.read()
.expect("unable to create backend read transaction"),
schema: self.schema.read(), schema: self.schema.read(),
d_info: self.d_info.read(), d_info: self.d_info.read(),
system_config: self.system_config.read(), system_config: self.system_config.read(),
@ -1223,8 +1227,13 @@ impl QueryServer {
.expect("unable to acquire db_ticket for qsw") .expect("unable to acquire db_ticket for qsw")
}; };
#[allow(clippy::expect_used)]
let mut be_txn = self
.be
.write()
.expect("unable to create backend write transaction");
let schema_write = self.schema.write(); let schema_write = self.schema.write();
let mut be_txn = self.be.write().unwrap();
let d_info = self.d_info.write(); let d_info = self.d_info.write();
let system_config = self.system_config.write(); let system_config = self.system_config.write();
let phase = self.phase.write(); let phase = self.phase.write();

View file

@ -1695,7 +1695,7 @@ impl Value {
Value::Iname(s) => s.clone(), Value::Iname(s) => s.clone(),
Value::Uuid(u) => u.as_hyphenated().to_string(), Value::Uuid(u) => u.as_hyphenated().to_string(),
// We display the tag and fingerprint. // We display the tag and fingerprint.
Value::SshKey(tag, key) => format!("{}: {}", tag, key.to_string()), Value::SshKey(tag, key) => format!("{}: {}", tag, key),
Value::Spn(n, r) => format!("{n}@{r}"), Value::Spn(n, r) => format!("{n}@{r}"),
_ => unreachable!( _ => unreachable!(
"You've specified the wrong type for the attribute, got: {:?}", "You've specified the wrong type for the attribute, got: {:?}",

View file

@ -44,7 +44,7 @@ impl ValueSetSshKey {
let map = data let map = data
.iter() .iter()
.map(|(tag, data)| { .map(|(tag, data)| {
SshPublicKey::from_string(&data) SshPublicKey::from_string(data)
.map_err(|err| { .map_err(|err| {
warn!(%tag, ?err, "discarding corrupted ssh public key"); warn!(%tag, ?err, "discarding corrupted ssh public key");
OperationError::VS0001IncomingReplSshPublicKey OperationError::VS0001IncomingReplSshPublicKey

View file

@ -14,7 +14,7 @@ impl GroupAccountPolicyOpt {
match self { match self {
GroupAccountPolicyOpt::Enable { name, copt } => { GroupAccountPolicyOpt::Enable { name, copt } => {
let client = copt.to_client(OpType::Write).await; let client = copt.to_client(OpType::Write).await;
if let Err(e) = client.group_account_policy_enable(&name).await { if let Err(e) = client.group_account_policy_enable(name).await {
handle_client_error(e, &copt.output_mode); handle_client_error(e, &copt.output_mode);
} else { } else {
println!("Group enabled for account policy."); println!("Group enabled for account policy.");
@ -23,7 +23,7 @@ impl GroupAccountPolicyOpt {
GroupAccountPolicyOpt::AuthSessionExpiry { name, expiry, copt } => { GroupAccountPolicyOpt::AuthSessionExpiry { name, expiry, copt } => {
let client = copt.to_client(OpType::Write).await; let client = copt.to_client(OpType::Write).await;
if let Err(e) = client if let Err(e) = client
.group_account_policy_authsession_expiry_set(&name, *expiry) .group_account_policy_authsession_expiry_set(name, *expiry)
.await .await
{ {
handle_client_error(e, &copt.output_mode); handle_client_error(e, &copt.output_mode);
@ -34,7 +34,7 @@ impl GroupAccountPolicyOpt {
GroupAccountPolicyOpt::PrivilegedSessionExpiry { name, expiry, copt } => { GroupAccountPolicyOpt::PrivilegedSessionExpiry { name, expiry, copt } => {
let client = copt.to_client(OpType::Write).await; let client = copt.to_client(OpType::Write).await;
if let Err(e) = client if let Err(e) = client
.group_account_policy_privilege_expiry_set(&name, *expiry) .group_account_policy_privilege_expiry_set(name, *expiry)
.await .await
{ {
handle_client_error(e, &copt.output_mode); handle_client_error(e, &copt.output_mode);