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

Add credential loader helper #98

Closed
wants to merge 1 commit 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
72 changes: 72 additions & 0 deletions src/credential.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
use std::{env, ffi::OsStr, fs, io, path::PathBuf};

/// Credential loader for units.
///
/// Credentials are read by systemd on unit startup and exported by their ID.
///
/// **Note**: only the user associated with the unit and the superuser may access credentials.
///
/// More documentation: <https://www.freedesktop.org/software/systemd/man/systemd.exec.html#Credentials>
#[derive(Clone, Debug)]
pub struct CredentialLoader {
dir: PathBuf,
}

impl CredentialLoader {
/// Attempt to initiate a loader, returning [`None`] if no credentials are available.
pub fn new() -> Option<Self> {
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This should probably be called open() and return a Result<Self> instead.

To check whether the credentials store is available or not, let's add a dedicated CredentialLoader::credentials_directory() -> Option<PathBuf> on the side.

let dir: PathBuf = env::var_os("CREDENTIALS_DIRECTORY")?.into();

if dir.is_dir() {
Some(Self { dir })
} else {
None
}
}

/// Get a credential by its ID.
///
/// # Examples
/// ```no_run
/// use libsystemd::CredentialLoader;
///
/// if let Some(loader) = CredentialLoader::new() {
/// let key = "token";
/// match loader.get("token") {
/// Ok(val) => println!("{}: {}", key, String::from_utf8_lossy(&val)),
/// Err(e) => println!("couldn't retreive {}: {}", key, e),
/// }
/// }
/// ```
pub fn get<K: AsRef<OsStr>>(&self, id: K) -> io::Result<Vec<u8>> {
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'd be happier if we return a std::fs::File instead of a vector of bytes.
The rationale is that it will allow the caller to read the content at a later time, not having to keep the secret in memory since the beginning.

self._get(id.as_ref())
}

fn _get(&self, id: &OsStr) -> io::Result<Vec<u8>> {
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please note that the systemd docs says ASCII string suitable as filename in the filesystem.
Thus I think we should have some basic sanity check to detect /, empty string, null bytes and such.
This is to avoid ending up with ../../../../etc/passwd or similar.

let path: PathBuf = [self.dir.as_ref(), id].iter().collect();

fs::read(path)
}

/// An iterator over this units credentials.
///
/// # Examples
/// ```no_run
/// use libsystemd::CredentialLoader;
///
/// if let Some(loader) = CredentialLoader::new() {
/// for entry in loader.iter() {
/// match entry {
/// Ok(entry) => {
/// let key = entry.file_name();
/// println!("{:?}: {}", key, String::from_utf8_lossy(&loader.get(&key)?))
/// }
/// Err(e) => println!("couldn't list some credential: {}", e),
/// }
/// }
/// }
/// # Ok::<(), std::io::Error>(())
pub fn iter(&self) -> fs::ReadDir {
self.dir.read_dir().expect("path exists")
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If you need this kind of listing primitive, then let's store a https://docs.rs/nix/latest/nix/dir/struct.Dir.html internally and directly wire our method to Dir::iter().

}
}
3 changes: 3 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@

/// Interfaces for socket-activated services.
pub mod activation;
mod credential;
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's call this credentials (plural) and do a pub mod credentials here.

/// Interfaces for systemd-aware daemons.
pub mod daemon;
/// Error handling.
Expand All @@ -34,3 +35,5 @@ pub mod logging;
pub mod sysusers;
/// Helpers for working with systemd units.
pub mod unit;

pub use credential::CredentialLoader;