Skip to content

Commit

Permalink
Lint and format
Browse files Browse the repository at this point in the history
  • Loading branch information
ThetaSinner committed Apr 2, 2024
1 parent dd7cebb commit ac883f2
Show file tree
Hide file tree
Showing 12 changed files with 119 additions and 66 deletions.
2 changes: 2 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

9 changes: 7 additions & 2 deletions checked_cli/src/fetch.rs
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,11 @@ pub async fn fetch(fetch_args: FetchArgs) -> anyhow::Result<()> {

println!("Downloaded to {:?}", path);

let file = fetch_url.path_segments().ok_or_else(|| anyhow::anyhow!("Invalid URL"))?.last().ok_or_else(|| anyhow::anyhow!("Invalid URL"))?;
let file = fetch_url
.path_segments()
.ok_or_else(|| anyhow::anyhow!("Invalid URL"))?
.last()
.ok_or_else(|| anyhow::anyhow!("Invalid URL"))?;
std::fs::rename(path.clone(), file)?;

let decision = dialoguer::Confirm::new()
Expand Down Expand Up @@ -189,12 +193,13 @@ where
}

async fn report_progress(state: Arc<FetchState>) -> anyhow::Result<()> {
if let Err(_) = tokio::time::timeout(std::time::Duration::from_secs(5), async {
if tokio::time::timeout(std::time::Duration::from_secs(5), async {
while state.asset_size.load(std::sync::atomic::Ordering::Relaxed) == 0 {
tokio::time::sleep(std::time::Duration::from_millis(100)).await;
}
})
.await
.is_err()
{
return Ok(());
}
Expand Down
150 changes: 97 additions & 53 deletions checked_cli/src/hc_client.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,16 @@
use std::fs::{File, Permissions};
use std::io::Write;
use holochain_client::{AdminWebsocket, AppAgentWebsocket, AppStatusFilter, AuthorizeSigningCredentialsPayload, ClientAgentSigner, SigningCredentials};
use crate::common::get_store_dir;
use holochain_client::{
AdminWebsocket, AppAgentWebsocket, AppStatusFilter, AuthorizeSigningCredentialsPayload,
ClientAgentSigner, SigningCredentials,
};
use holochain_conductor_api::CellInfo;
use holochain_types::prelude::{AgentPubKey, CapSecret, CellId};
use holochain_types::websocket::AllowedOrigins;
use serde::{Deserialize, Serialize};
use crate::common::get_store_dir;
use std::fs::{File, Permissions};
use std::io::Write;

const DEFAULT_INSTALLED_APP_ID: &'static str = "checked";
const DEFAULT_INSTALLED_APP_ID: &str = "checked";

pub async fn get_authenticated_app_agent_client() -> anyhow::Result<AppAgentWebsocket> {
// TODO connect timeout not configurable! Really slow if Holochain is not running.
Expand All @@ -18,61 +21,84 @@ pub async fn get_authenticated_app_agent_client() -> anyhow::Result<AppAgentWebs

let app_port = find_or_create_app_interface(&mut admin_client).await?;

AppAgentWebsocket::connect(format!("localhost:{app_port}"), DEFAULT_INSTALLED_APP_ID.to_string(), signer.into()).await
AppAgentWebsocket::connect(
format!("localhost:{app_port}"),
DEFAULT_INSTALLED_APP_ID.to_string(),
signer.into(),
)
.await
}

async fn find_or_create_app_interface(admin_client: &mut AdminWebsocket) -> anyhow::Result<u16> {
let app_interfaces = admin_client.list_app_interfaces().await.map_err(|e| anyhow::anyhow!("Error listing app interfaces: {:?}", e))?;
let app_interfaces = admin_client
.list_app_interfaces()
.await
.map_err(|e| anyhow::anyhow!("Error listing app interfaces: {:?}", e))?;

// The client doesn't tell us what origins are set for each app interface so we have to pick one.
let app_port = match app_interfaces.first() {
Some(app_port) => {
*app_port
}
None => {
admin_client.attach_app_interface(0, AllowedOrigins::Any).await.map_err(|e| anyhow::anyhow!("Error attaching app interface: {:?}", e))?
}
Some(app_port) => *app_port,
None => admin_client
.attach_app_interface(0, AllowedOrigins::Any)
.await
.map_err(|e| anyhow::anyhow!("Error attaching app interface: {:?}", e))?,
};
Ok(app_port)
}

async fn load_or_create_signing_credentials(mut admin_client: &mut AdminWebsocket, signer: &mut ClientAgentSigner) -> anyhow::Result<()> {
async fn load_or_create_signing_credentials(
admin_client: &mut AdminWebsocket,
signer: &mut ClientAgentSigner,
) -> anyhow::Result<()> {
match try_load_credentials()? {
Some((cell_id, credentials)) => {
signer.add_credentials(cell_id, credentials);
}
None => {
let (cell_id, credentials) = create_new_credentials(&mut admin_client).await?;
let (cell_id, credentials) = create_new_credentials(admin_client).await?;
dump_credentials(cell_id.clone(), &credentials)?;
signer.add_credentials(cell_id, credentials);
}
}
Ok(())
}

async fn create_new_credentials(client: &mut AdminWebsocket) -> anyhow::Result<(CellId, SigningCredentials)> {
let apps = client.list_apps(Some(AppStatusFilter::Running)).await.map_err(|e| anyhow::anyhow!("Error listing apps: {:?}", e))?;

let app = apps.iter().find(|app| {
// TODO allow this to be overridden on the CLI.
app.installed_app_id == DEFAULT_INSTALLED_APP_ID
}).ok_or_else(|| anyhow::anyhow!("App `checked` not found"))?;

let cells = app.cell_info.get("checked").ok_or_else(|| anyhow::anyhow!("Role `checked` not found"))?;

let cell = cells.iter().find_map(|cell| {
match cell {
CellInfo::Provisioned(cell) if cell.name == "checked" => {
Some(cell)
}
_ => None
}
}).ok_or_else(|| anyhow::anyhow!("Cell `checked` not found"))?;

let credentials = client.authorize_signing_credentials(AuthorizeSigningCredentialsPayload {
cell_id: cell.cell_id.clone(),
functions: None, // For all, not documented!
}).await.map_err(|e| anyhow::anyhow!("Error authorizing signing credentials: {:?}", e))?;
async fn create_new_credentials(
client: &mut AdminWebsocket,
) -> anyhow::Result<(CellId, SigningCredentials)> {
let apps = client
.list_apps(Some(AppStatusFilter::Running))
.await
.map_err(|e| anyhow::anyhow!("Error listing apps: {:?}", e))?;

let app = apps
.iter()
.find(|app| {
// TODO allow this to be overridden on the CLI.
app.installed_app_id == DEFAULT_INSTALLED_APP_ID
})
.ok_or_else(|| anyhow::anyhow!("App `checked` not found"))?;

let cells = app
.cell_info
.get("checked")
.ok_or_else(|| anyhow::anyhow!("Role `checked` not found"))?;

let cell = cells
.iter()
.find_map(|cell| match cell {
CellInfo::Provisioned(cell) if cell.name == "checked" => Some(cell),
_ => None,
})
.ok_or_else(|| anyhow::anyhow!("Cell `checked` not found"))?;

let credentials = client
.authorize_signing_credentials(AuthorizeSigningCredentialsPayload {
cell_id: cell.cell_id.clone(),
functions: None, // For all, not documented!
})
.await
.map_err(|e| anyhow::anyhow!("Error authorizing signing credentials: {:?}", e))?;

Ok((cell.cell_id.clone(), credentials))
}
Expand All @@ -85,35 +111,48 @@ struct SavedCredentials {
cap_secret: CapSecret,
}

fn dump_credentials(cell_id: CellId, signing_credentials: &SigningCredentials) -> anyhow::Result<()> {
fn dump_credentials(
cell_id: CellId,
signing_credentials: &SigningCredentials,
) -> anyhow::Result<()> {
let saved = SavedCredentials {
cell_id: cell_id.clone(),
signing_agent_key: signing_credentials.signing_agent_key.clone(),
keypair: signing_credentials.keypair.to_keypair_bytes().to_vec(),
cap_secret: signing_credentials.cap_secret.clone(),
cap_secret: signing_credentials.cap_secret,
};

let serialized = serde_json::to_string(&saved).map_err(|e| anyhow::anyhow!("Error serializing credentials: {:?}", e))?;
let serialized = serde_json::to_string(&saved)
.map_err(|e| anyhow::anyhow!("Error serializing credentials: {:?}", e))?;

// generate_args.path
let credentials_path = get_credentials_path()?;

let mut f= File::options().create(true).write(true).truncate(true).open(&credentials_path).map_err(|e| anyhow::anyhow!("Error opening credentials file: {:?}", e))?;
let mut f = File::options()
.create(true)
.write(true)
.truncate(true)
.open(credentials_path)
.map_err(|e| anyhow::anyhow!("Error opening credentials file: {:?}", e))?;

if cfg!(unix) {
use std::os::unix::fs::PermissionsExt;
f.set_permissions(Permissions::from_mode(0o660)).map_err(|e| anyhow::anyhow!("Error setting permissions on credentials file: {:?}", e))?;
f.set_permissions(Permissions::from_mode(0o660))
.map_err(|e| {
anyhow::anyhow!("Error setting permissions on credentials file: {:?}", e)
})?;
}

f.write_all(serialized.as_bytes()).map_err(|e| anyhow::anyhow!("Error writing credentials file: {:?}", e))?;
f.write_all(serialized.as_bytes())
.map_err(|e| anyhow::anyhow!("Error writing credentials file: {:?}", e))?;

Ok(())
}

fn try_load_credentials() -> anyhow::Result<Option<(CellId, SigningCredentials)>> {
let credentials_path = get_credentials_path()?;

let f = match File::open(&credentials_path) {
let f = match File::open(credentials_path) {
Ok(f) => f,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
return Ok(None);
Expand All @@ -127,23 +166,28 @@ fn try_load_credentials() -> anyhow::Result<Option<(CellId, SigningCredentials)>
Ok(saved) => saved,
Err(e) => {
eprintln!("Saved credentials file is corrupt: {:?}", e);
return Ok(None)
return Ok(None);
}
};

let keypair = match ed25519_dalek::SigningKey::from_keypair_bytes(saved.keypair.as_slice().try_into().unwrap()) {
let keypair = match ed25519_dalek::SigningKey::from_keypair_bytes(
saved.keypair.as_slice().try_into().unwrap(),
) {
Ok(keypair) => keypair,
Err(e) => {
eprintln!("Saved credentials file is corrupt: {:?}", e);
return Ok(None)
return Ok(None);
}
};

Ok(Some((saved.cell_id, SigningCredentials {
signing_agent_key: saved.signing_agent_key,
keypair,
cap_secret: saved.cap_secret,
})))
Ok(Some((
saved.cell_id,
SigningCredentials {
signing_agent_key: saved.signing_agent_key,
keypair,
cap_secret: saved.cap_secret,
},
)))
}

fn get_credentials_path() -> anyhow::Result<std::path::PathBuf> {
Expand Down
6 changes: 3 additions & 3 deletions checked_cli/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,17 +1,17 @@
mod common;

pub mod cli;
mod fetch;
pub mod generate;
pub(crate) mod hc_client;
mod password;
pub mod sign;
pub mod verify;
mod fetch;
pub(crate) mod hc_client;

pub mod prelude {
pub use crate::cli::{Cli, Commands, GenerateArgs, SignArgs};
pub use crate::fetch::fetch;
pub use crate::generate::generate;
pub use crate::sign::sign;
pub use crate::verify::verify;
pub use crate::fetch::fetch;
}
2 changes: 1 addition & 1 deletion dnas/checked/zomes/coordinator/fetch/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use fetch_integrity::prelude::*;
use checked_types::*;
use fetch_integrity::prelude::*;
use hdk::prelude::hash_type::AnyLinkable;
use hdk::prelude::*;
use rand::prelude::IteratorRandom;
Expand Down
1 change: 1 addition & 0 deletions dnas/checked/zomes/coordinator/signing_keys/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -15,4 +15,5 @@ minisign-verify = { workspace = true }
chrono = { workspace = true }
nanoid = { workspace = true }

checked_types = { workspace = true }
signing_keys_integrity = { workspace = true }
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use crate::{convert_to_app_entry_type, key_collection::get_key_collections_reference_count};
use checked_types::*;
use hdk::prelude::*;
use signing_keys_integrity::prelude::*;

Expand Down
1 change: 1 addition & 0 deletions dnas/checked/zomes/integrity/signing_keys/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -17,4 +17,5 @@ regex = { workspace = true }
chrono = { workspace = true }
anyhow = { workspace = true }

checked_types = { workspace = true }
signing_keys_types = { workspace = true }
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,9 @@
use crate::convert::try_extract_entry_to_app_type;
use crate::prelude::*;
use checked_types::VerificationKeyType;
use hdi::prelude::*;
use signing_keys_types::{
MarkVfKeyDistOpt, VerificationKeyDist, VerificationKeyDistMark, VerificationKeyType,
};
use signing_keys_types::{MarkVfKeyDistOpt, VerificationKeyDist, VerificationKeyDistMark};

pub const VERIFICATION_KEY_NAME_MIN_LENGTH: usize = 3;
pub const MAX_VF_KEY_DIST_COMPROMISED_NOTE_LENGTH: usize = 120;
Expand Down
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,8 @@
"package": "npm run build:happ && npm run package -w ui && hc web-app pack workdir --recursive",
"build:happ": "npm run build:zomes && hc app pack workdir --recursive",
"build:zomes": "RUSTFLAGS='' CARGO_TARGET_DIR=target cargo build --release --target wasm32-unknown-unknown",
"lint": "npm run -w ui lint && npm run -w tests lint && cargo clippy",
"format": "npm run -w ui format && npm run -w tests format && cargo fmt"
"lint": "npm run -w ui lint && npm run -w tests lint && cargo clippy && cargo clippy --manifest-path ./checked_cli/Cargo.toml",
"format": "npm run -w ui format && npm run -w tests format && cargo fmt && cargo fmt --manifest-path ./checked_cli/Cargo.toml"
},
"devDependencies": {
"@holochain-playground/cli": "^0.1.1",
Expand Down
3 changes: 1 addition & 2 deletions types/checked_types/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use serde::{Serialize, Deserialize};
use holochain_zome_types::prelude::AgentPubKey;
use serde::{Deserialize, Serialize};

/// Supported key types for verification keys.
#[derive(Serialize, Deserialize, Clone, PartialEq, Debug)]
Expand All @@ -8,7 +8,6 @@ pub enum VerificationKeyType {
MiniSignEd25519,
}


#[derive(Serialize, Deserialize, Debug)]
pub struct PrepareFetchRequest {
pub fetch_url: String,
Expand Down
1 change: 1 addition & 0 deletions types/signing_keys/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
use checked_types::VerificationKeyType;
use chrono::{DateTime, Utc};
use hdk::prelude::*;

Expand Down

0 comments on commit ac883f2

Please sign in to comment.