Skip to content

Commit

Permalink
fix: storing credentials (#258)
Browse files Browse the repository at this point in the history
* Fix storing credentials

* Fix clippy
  • Loading branch information
ChaoticTempest authored Jan 10, 2023
1 parent 43a21c6 commit 9014f3a
Show file tree
Hide file tree
Showing 4 changed files with 37 additions and 16 deletions.
8 changes: 8 additions & 0 deletions workspaces/src/error/impls.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,14 @@ impl ErrorKind {
Error::message(self, msg)
}

pub(crate) fn full<T, E>(self, msg: T, error: E) -> Error
where
T: Into<Cow<'static, str>>,
E: Into<Box<dyn std::error::Error + Send + Sync>>,
{
Error::full(self, msg, error)
}

pub(crate) fn detailed(self, error: ExecutionFailure) -> Error {
Error::detailed(self, error)
}
Expand Down
18 changes: 11 additions & 7 deletions workspaces/src/rpc/tool.rs
Original file line number Diff line number Diff line change
Expand Up @@ -57,15 +57,20 @@ pub(crate) async fn url_create_account(
Ok(())
}

pub(crate) fn write_cred_to_file(path: &Path, id: &AccountId, sk: &SecretKey) {
let mut file = File::create(path).expect("Failed to create / write a key file.");
pub(crate) fn write_cred_to_file(path: &Path, id: &AccountId, sk: &SecretKey) -> Result<()> {
let mut file = File::create(path).map_err(|err| {
ErrorKind::Io.full(
format!("failed to open {path:?} for writing credentials"),
err,
)
})?;

#[cfg(unix)]
{
use std::os::unix::prelude::PermissionsExt;
let mut perm = file
.metadata()
.expect("Failed to retrieve key file metadata.")
.map_err(|err| ErrorKind::Io.full("Failed to retrieve key file metadata.", err))?
.permissions();

#[cfg(target_os = "macos")]
Expand All @@ -74,7 +79,7 @@ pub(crate) fn write_cred_to_file(path: &Path, id: &AccountId, sk: &SecretKey) {
perm.set_mode(libc::S_IWUSR | libc::S_IRUSR);

file.set_permissions(perm)
.expect("Failed to set permissions for a key file.");
.map_err(|err| ErrorKind::Io.full("Failed to set permissions for a key file.", err))?;
}

let content = serde_json::json!({
Expand All @@ -85,7 +90,6 @@ pub(crate) fn write_cred_to_file(path: &Path, id: &AccountId, sk: &SecretKey) {
.to_string()
.into_bytes();

if let Err(err) = file.write_all(&content) {
panic!("Failed to write a key file {}", err);
}
file.write_all(&content)
.map_err(|err| ErrorKind::Io.full("Failed to write a key file", err))
}
13 changes: 4 additions & 9 deletions workspaces/src/types/account.rs
Original file line number Diff line number Diff line change
Expand Up @@ -180,15 +180,10 @@ impl Account {

/// Store the credentials of this account locally in the directory provided.
pub async fn store_credentials(&self, save_dir: impl AsRef<Path>) -> Result<()> {
let savepath = save_dir.as_ref().to_path_buf();
std::fs::create_dir_all(save_dir).map_err(|e| ErrorKind::Io.custom(e))?;

let mut savepath = savepath.join(self.id().to_string());
savepath.set_extension("json");

crate::rpc::tool::write_cred_to_file(&savepath, self.id(), &self.secret_key().0);

Ok(())
let savepath = save_dir.as_ref();
std::fs::create_dir_all(&save_dir).map_err(|e| ErrorKind::Io.custom(e))?;
let savepath = savepath.join(format!("{}.json", self.id()));
crate::rpc::tool::write_cred_to_file(&savepath, self.id(), &self.secret_key().0)
}

/// Get the keys of this account. The public key can be retrieved from the secret key.
Expand Down
14 changes: 14 additions & 0 deletions workspaces/tests/create_account.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
#![recursion_limit = "256"]
use serde_json::{Map, Value};
use test_log::test;

use std::fs::File;
use std::path::Path;

#[test(tokio::test)]
async fn test_subaccount_creation() -> anyhow::Result<()> {
let worker = workspaces::sandbox().await?;
Expand All @@ -17,5 +21,15 @@ async fn test_subaccount_creation() -> anyhow::Result<()> {

assert_eq!(actual_id, expect_id);

// Check if the stored credentials match with the subaccount created.
let savedir = Path::new("../target/credentials");
sub.store_credentials(savedir).await?;
let creds = File::open(savedir.join(format!("{}.json", sub.id())))?;
let contents: Map<String, Value> = serde_json::from_reader(creds)?;
assert_eq!(
contents.get("account_id"),
Some(&Value::String(sub.id().to_string()))
);

Ok(())
}

0 comments on commit 9014f3a

Please sign in to comment.