Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Search feature #169

Closed
wants to merge 14 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ platform-freebsd = ["linux-secret-service"]
platform-openbsd = ["linux-secret-service"]
platform-macos = ["security-framework"]
platform-ios = ["security-framework"]
platform-windows = ["windows-sys", "byteorder"]
platform-windows = ["windows-sys", "regex", "byteorder"]
linux-secret-service = ["linux-secret-service-rt-async-io-crypto-rust"]
linux-secret-service-rt-async-io-crypto-rust = ["secret-service/rt-async-io-crypto-rust"]
linux-secret-service-rt-tokio-crypto-rust = ["secret-service/rt-tokio-crypto-rust"]
Expand Down Expand Up @@ -51,6 +51,7 @@ secret-service = { version = "3", optional = true }

[target.'cfg(target_os = "windows")'.dependencies]
byteorder = { version = "1.2", optional = true }
regex = { version = "1.10.4", optional = true }
windows-sys = { version = "0.52", features = ["Win32_Foundation", "Win32_Security_Credentials"], optional = true }

[[example]]
Expand Down
30 changes: 29 additions & 1 deletion src/credential.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ in a thread-safe way, a requirement captured in the [CredentialBuilder] and
[CredentialApi] types that wrap them.
*/
use super::Result;
use std::any::Any;
use std::{any::Any, collections::HashMap};

/// The API that [credentials](Credential) implement.
pub trait CredentialApi {
Expand Down Expand Up @@ -91,3 +91,31 @@ impl std::fmt::Debug for CredentialBuilder {

/// A thread-safe implementation of the [CredentialBuilder API](CredentialBuilderApi).
pub type CredentialBuilder = dyn CredentialBuilderApi + Send + Sync;

/// The API that [credential search](CredentialSearch) implements.
pub trait CredentialSearchApi {
fn by(&self, by: &str, query: &str) -> Result<HashMap<String, HashMap<String, String>>>;
}

/// A thread-safe implementation of the [CredentialSearch API](CredentialSearchApi).
pub type CredentialSearch = dyn CredentialSearchApi + Send + Sync;

/// Type alias to shorten the long (and ugly) Credential Search Result HashMap.
pub type CredentialSearchResult = Result<HashMap<String, HashMap<String, String>>>;

/// The API that [credential list](CredentialList) implements.
pub trait CredentialListApi {
fn list_credentials(
search_result: Result<HashMap<String, HashMap<String, String>>>,
limit: Limit,
) -> Result<()>;
}

/// A thread-safe implementation of the [CredentialList API](CredentialListApi).
pub type CredentialList = dyn CredentialListApi + Send + Sync;

/// Type matching enum, allows for constraint of the amount of results returned to the user.
pub enum Limit {
All,
Max(i64),
}
243 changes: 124 additions & 119 deletions src/error.rs
Original file line number Diff line number Diff line change
@@ -1,119 +1,124 @@
/*!

Platform-independent error model.

There is an escape hatch here for surfacing platform-specific
error information returned by the platform-specific storage provider,
but (like all credential-related data) the concrete objects returned
must be both Send and Sync so credentials remain Send + Sync.
(Since most platform errors are integer error codes, this requirement
is not much of a burden on the platform-specific store providers.)

*/

use crate::Credential;

#[derive(Debug)]
/// Each variant of the `Error` enum provides a summary of the error.
/// More details, if relevant, are contained in the associated value,
/// which may be platform-specific.
///
/// Because future releases may add variants to this enum, clients should
/// always be prepared for that.
#[non_exhaustive]
pub enum Error {
/// This indicates runtime failure in the underlying
/// platform storage system. The details of the failure can
/// be retrieved from the attached platform error.
PlatformFailure(Box<dyn std::error::Error + Send + Sync>),
/// This indicates that the underlying secure storage
/// holding saved items could not be accessed. Typically this
/// is because of access rules in the platform; for example, it
/// might be that the credential store is locked. The underlying
/// platform error will typically give the reason.
NoStorageAccess(Box<dyn std::error::Error + Send + Sync>),
/// This indicates that there is no underlying credential
/// entry in the platform for this entry. Either one was
/// never set, or it was deleted.
NoEntry,
/// This indicates that the retrieved password blob was not
/// a UTF-8 string. The underlying bytes are available
/// for examination in the attached value.
BadEncoding(Vec<u8>),
/// This indicates that one of the entry's credential
/// attributes exceeded a
/// length limit in the underlying platform. The
/// attached values give the name of the attribute and
/// the platform length limit that was exceeded.
TooLong(String, u32),
/// This indicates that one of the entry's required credential
/// attributes was invalid. The
/// attached value gives the name of the attribute
/// and the reason it's invalid.
Invalid(String, String),
/// This indicates that there is more than one credential found in the store
/// that matches the entry. Its value is a vector of the matching credentials.
Ambiguous(Vec<Box<Credential>>),
}

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

impl std::fmt::Display for Error {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
match self {
Error::PlatformFailure(err) => write!(f, "Platform secure storage failure: {err}"),
Error::NoStorageAccess(err) => {
write!(f, "Couldn't access platform secure storage: {err}")
}
Error::NoEntry => write!(f, "No matching entry found in secure storage"),
Error::BadEncoding(_) => write!(f, "Password cannot be UTF-8 encoded"),
Error::TooLong(name, len) => write!(
f,
"Attribute '{name}' is longer than platform limit of {len} chars"
),
Error::Invalid(attr, reason) => {
write!(f, "Attribute {attr} is invalid: {reason}")
}
Error::Ambiguous(items) => {
write!(
f,
"Entry is matched by {} credendials: {items:?}",
items.len(),
)
}
}
}
}

impl std::error::Error for Error {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
Error::PlatformFailure(err) => Some(err.as_ref()),
Error::NoStorageAccess(err) => Some(err.as_ref()),
_ => None,
}
}
}

/// Try to interpret a byte vector as a password string
pub fn decode_password(bytes: Vec<u8>) -> Result<String> {
String::from_utf8(bytes).map_err(|err| Error::BadEncoding(err.into_bytes()))
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn test_bad_password() {
// malformed sequences here taken from:
// https://www.cl.cam.ac.uk/~mgk25/ucs/examples/UTF-8-test.txt
for bytes in [b"\x80".to_vec(), b"\xbf".to_vec(), b"\xed\xa0\xa0".to_vec()] {
match decode_password(bytes.clone()) {
Err(Error::BadEncoding(str)) => assert_eq!(str, bytes),
Err(other) => panic!("Bad password ({bytes:?}) decode gave wrong error: {other}"),
Ok(s) => panic!("Bad password ({bytes:?}) decode gave results: {s:?}"),
}
}
}
}
/*!

Platform-independent error model.

There is an escape hatch here for surfacing platform-specific
error information returned by the platform-specific storage provider,
but (like all credential-related data) the concrete objects returned
must be both Send and Sync so credentials remain Send + Sync.
(Since most platform errors are integer error codes, this requirement
is not much of a burden on the platform-specific store providers.)

*/

use crate::Credential;

#[derive(Debug)]
/// Each variant of the `Error` enum provides a summary of the error.
/// More details, if relevant, are contained in the associated value,
/// which may be platform-specific.
///
/// Because future releases may add variants to this enum, clients should
/// always be prepared for that.
#[non_exhaustive]
pub enum Error {
/// This indicates runtime failure in the underlying
/// platform storage system. The details of the failure can
/// be retrieved from the attached platform error.
PlatformFailure(Box<dyn std::error::Error + Send + Sync>),
/// This indicates that the underlying secure storage
/// holding saved items could not be accessed. Typically this
/// is because of access rules in the platform; for example, it
/// might be that the credential store is locked. The underlying
/// platform error will typically give the reason.
NoStorageAccess(Box<dyn std::error::Error + Send + Sync>),
/// This indicates that there is no underlying credential
/// entry in the platform for this entry. Either one was
/// never set, or it was deleted.
NoEntry,
/// This indicates that the retrieved password blob was not
/// a UTF-8 string. The underlying bytes are available
/// for examination in the attached value.
BadEncoding(Vec<u8>),
/// This indicates that one of the entry's credential
/// attributes exceeded a
/// length limit in the underlying platform. The
/// attached values give the name of the attribute and
/// the platform length limit that was exceeded.
TooLong(String, u32),
/// This indicates that one of the entry's required credential
/// attributes was invalid. The
/// attached value gives the name of the attribute
/// and the reason it's invalid.
Invalid(String, String),
/// This indicates that there is more than one credential found in the store
/// that matches the entry. Its value is a vector of the matching credentials.
Ambiguous(Vec<Box<Credential>>),

SearchError(String),
}

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

impl std::fmt::Display for Error {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
match self {
Error::PlatformFailure(err) => write!(f, "Platform secure storage failure: {err}"),
Error::NoStorageAccess(err) => {
write!(f, "Couldn't access platform secure storage: {err}")
}
Error::NoEntry => write!(f, "No matching entry found in secure storage"),
Error::BadEncoding(_) => write!(f, "Password cannot be UTF-8 encoded"),
Error::TooLong(name, len) => write!(
f,
"Attribute '{name}' is longer than platform limit of {len} chars"
),
Error::Invalid(attr, reason) => {
write!(f, "Attribute {attr} is invalid: {reason}")
}
Error::Ambiguous(items) => {
write!(
f,
"Entry is matched by {} credendials: {items:?}",
items.len(),
)
}
Error::SearchError(reason) => {
write!(f, "Error searching for credential: {}", reason)
}
}
}
}

impl std::error::Error for Error {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
Error::PlatformFailure(err) => Some(err.as_ref()),
Error::NoStorageAccess(err) => Some(err.as_ref()),
_ => None,
}
}
}

/// Try to interpret a byte vector as a password string
pub fn decode_password(bytes: Vec<u8>) -> Result<String> {
String::from_utf8(bytes).map_err(|err| Error::BadEncoding(err.into_bytes()))
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn test_bad_password() {
// malformed sequences here taken from:
// https://www.cl.cam.ac.uk/~mgk25/ucs/examples/UTF-8-test.txt
for bytes in [b"\x80".to_vec(), b"\xbf".to_vec(), b"\xed\xa0\xa0".to_vec()] {
match decode_password(bytes.clone()) {
Err(Error::BadEncoding(str)) => assert_eq!(str, bytes),
Err(other) => panic!("Bad password ({bytes:?}) decode gave wrong error: {other}"),
Ok(s) => panic!("Bad password ({bytes:?}) decode gave results: {s:?}"),
}
}
}
}
Loading