Skip to content

Commit

Permalink
Created a ParseError enum
Browse files Browse the repository at this point in the history
Added UTF parsing errors to enum
  • Loading branch information
Phillip Couto committed Nov 13, 2021
1 parent 8e2e80b commit 89e5ca3
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 6 deletions.
48 changes: 45 additions & 3 deletions src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@
use secret_service::Error as SsError;
#[cfg(target_os = "macos")]
use security_framework::base::Error as SfError;
use std::error;
use std::fmt;
use std::string::FromUtf8Error;
use std::{error, string::FromUtf16Error};

pub type Result<T> = ::std::result::Result<T, KeyringError>;

Expand All @@ -18,7 +18,9 @@ pub enum KeyringError {
WindowsVaultError,
NoBackendFound,
NoPasswordFound,
Parse(FromUtf8Error),
/// Parse errors are errors that occur when trying to parse the password
/// from the credential storage.
Parse(ParseError),
}

impl fmt::Display for KeyringError {
Expand Down Expand Up @@ -85,6 +87,46 @@ impl From<SfError> for KeyringError {

impl From<FromUtf8Error> for KeyringError {
fn from(err: FromUtf8Error) -> KeyringError {
KeyringError::Parse(err)
KeyringError::Parse(ParseError::FromUtf8(err))
}
}

impl From<FromUtf16Error> for KeyringError {
fn from(err: FromUtf16Error) -> KeyringError {
KeyringError::Parse(ParseError::FromUtf16(err))
}
}

/// ParseError is the enumeration of errors that can occur when parsing
/// a password from credential storage.
#[derive(Debug)]
pub enum ParseError {
/// FromUtf8 is an error that occured when trying to parse the password
/// as a UTF-8 string
FromUtf8(FromUtf8Error),
/// FromUtf16 is an error that occured when trying to parse the password
/// as a UTF-16 string
FromUtf16(FromUtf16Error),
}

impl error::Error for ParseError {
fn source(&self) -> Option<&(dyn error::Error + 'static)> {
match self {
ParseError::FromUtf8(e) => Some(e),
ParseError::FromUtf16(e) => Some(e),
}
}

fn cause(&self) -> Option<&dyn error::Error> {
self.source()
}
}

impl fmt::Display for ParseError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
ParseError::FromUtf8(e) => write!(f, "UTF-8 Error: {}", e),
ParseError::FromUtf16(e) => write!(f, "UTF-16 Error: {}", e),
}
}
}
5 changes: 2 additions & 3 deletions src/windows.rs
Original file line number Diff line number Diff line change
Expand Up @@ -130,15 +130,14 @@ impl<'a> Keyring<'a> {
LittleEndian::read_u16_into(blob, &mut blob_u16);

// Now can get utf8 string from the array
let password =
String::from_utf16(&blob_u16).map_err(|_| KeyringError::WindowsVaultError);
let password = String::from_utf16(&blob_u16).map(|pass| pass.to_string());

// Free the credential
unsafe {
CredFree(pcredential as *mut _);
}

password
Ok(password?)
}
}
}
Expand Down

0 comments on commit 89e5ca3

Please sign in to comment.