Skip to content

Commit

Permalink
feat(rust): improve display implementation for identity-related models
Browse files Browse the repository at this point in the history
  • Loading branch information
SanjoDeundiak committed Aug 22, 2023
1 parent 704d533 commit 47c9ef3
Show file tree
Hide file tree
Showing 10 changed files with 429 additions and 96 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ pub mod base;
pub mod credentials;
pub mod flow_controls;
pub mod forwarder;
pub mod identity;
pub mod policy;
pub mod portal;
pub mod secure_channel;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ use crate::{
};
use clap::Args;

use crate::util::output::CredentialAndPurposeKeyDisplay;
use miette::{miette, IntoDiagnostic};
use ockam::identity::utils::AttributesBuilder;
use ockam::identity::{
Expand Down Expand Up @@ -104,7 +105,10 @@ async fn run_impl(
.await
.into_diagnostic()?;

print_encodable(credential, &cmd.encode_format)?;
print_encodable(
CredentialAndPurposeKeyDisplay(credential),
&cmd.encode_format,
)?;

Ok(())
}
38 changes: 28 additions & 10 deletions implementations/rust/ockam/ockam_command/src/credential/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,16 +10,18 @@ use colorful::Colorful;
pub(crate) use get::GetCommand;
pub(crate) use issue::IssueCommand;
pub(crate) use list::ListCommand;
use ockam::identity::Identifier;
use ockam::identity::{Identifier, Identities, Identity};
use ockam_api::cli_state::{CredentialState, StateItemTrait};
pub(crate) use present::PresentCommand;
pub(crate) use show::ShowCommand;
use std::sync::Arc;
pub(crate) use store::StoreCommand;
pub(crate) use verify::VerifyCommand;

use crate::util::output::Output;
use crate::util::output::{CredentialAndPurposeKeyDisplay, Output};
use crate::{CommandGlobalOpts, Result};
use clap::{Args, Subcommand};
use miette::IntoDiagnostic;
use ockam::identity::models::CredentialAndPurposeKey;
use ockam_api::cli_state::traits::StateDirTrait;

Expand Down Expand Up @@ -57,15 +59,29 @@ impl CredentialCommand {
}
}

pub async fn identities(vault_name: &str, opts: &CommandGlobalOpts) -> Result<Arc<Identities>> {
let vault = opts.state.vaults.get(vault_name)?.get().await?;
let identities = opts.state.get_identities(vault).await?;

Ok(identities)
}

pub async fn identity(identity: &str, identities: Arc<Identities>) -> Result<Identity> {
let identity_as_bytes = hex::decode(identity)?;

let identity = identities
.identities_creation()
.import(None, &identity_as_bytes)
.await?;

Ok(identity)
}

pub async fn validate_encoded_cred(
encoded_cred: &[u8],
identities: Arc<Identities>,
issuer: &Identifier,
vault: &str,
opts: &CommandGlobalOpts,
) -> Result<()> {
let vault = opts.state.vaults.get(vault)?.get().await?;
let identities = opts.state.get_identities(vault).await?;

let cred: CredentialAndPurposeKey = minicbor::decode(encoded_cred)?;

identities
Expand All @@ -89,17 +105,19 @@ impl CredentialOutput {
vault_name: &str,
) -> Result<Self> {
let config = state.config();

let identities = identities(vault_name, opts).await.into_diagnostic()?;

let is_verified = validate_encoded_cred(
&config.encoded_credential,
identities,
&config.issuer_identifier,
vault_name,
opts,
)
.await
.is_ok();

let credential = config.credential()?;
let credential = hex::encode(minicbor::to_vec(credential)?);
let credential = format!("{}", CredentialAndPurposeKeyDisplay(credential));

let output = Self {
name: state.name().to_string(),
Expand Down
19 changes: 15 additions & 4 deletions implementations/rust/ockam/ockam_command/src/credential/show.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
use clap::{arg, Args};
use colorful::Colorful;
use miette::IntoDiagnostic;
use ockam::Context;
use ockam_api::cli_state::{StateDirTrait, StateItemTrait};

use crate::util::output::Output;
use crate::credential::identities;
use crate::util::output::CredentialAndPurposeKeyDisplay;
use crate::{
credential::validate_encoded_cred, util::node_rpc, vault::default_vault_name, CommandGlobalOpts,
};
Expand Down Expand Up @@ -42,11 +44,20 @@ pub(crate) async fn display_credential(
let cred = opts.state.credentials.get(cred_name)?;
let cred_config = cred.config();

let identities = identities(vault_name, opts).await?;
identities
.identities_creation()
.import(
Some(&cred_config.issuer_identifier),
&cred_config.encoded_issuer_change_history,
)
.await
.into_diagnostic()?;

let is_verified = match validate_encoded_cred(
&cred_config.encoded_credential,
identities,
&cred_config.issuer_identifier,
vault_name,
opts,
)
.await
{
Expand All @@ -56,7 +67,7 @@ pub(crate) async fn display_credential(

let cred = cred_config.credential()?;
println!("Credential: {cred_name} {is_verified}");
println!("{}", cred.output()?);
println!("{}", CredentialAndPurposeKeyDisplay(cred));

Ok(())
}
34 changes: 16 additions & 18 deletions implementations/rust/ockam/ockam_command/src/credential/store.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,13 @@ use crate::{
terminal::OckamColor,
util::{node_rpc, random_name},
vault::default_vault_name,
CommandGlobalOpts, Result,
CommandGlobalOpts,
};
use colorful::Colorful;
use miette::miette;

use crate::credential::{identities, identity};
use clap::Args;
use ockam::identity::{identities, Identity};
use ockam::Context;
use ockam_api::cli_state::{CredentialConfig, StateDirTrait};
use tokio::{sync::Mutex, try_join};
Expand All @@ -39,18 +39,6 @@ impl StoreCommand {
pub fn run(self, opts: CommandGlobalOpts) {
node_rpc(run_impl, (opts, self));
}

pub async fn identity(&self) -> Result<Identity> {
let identity_as_bytes = match hex::decode(&self.issuer) {
Ok(b) => b,
Err(e) => return Err(miette!(e).into()),
};
let identity = identities()
.identities_creation()
.import(None, &identity_as_bytes)
.await?;
Ok(identity)
}
}

async fn run_impl(
Expand All @@ -66,7 +54,10 @@ async fn run_impl(

let send_req = async {
let cred_as_str = match (&cmd.credential, &cmd.credential_path) {
(_, Some(credential_path)) => tokio::fs::read_to_string(credential_path).await?,
(_, Some(credential_path)) => tokio::fs::read_to_string(credential_path)
.await?
.trim()
.to_string(),
(Some(credential), _) => credential.to_string(),
_ => {
*is_finished.lock().await = true;
Expand All @@ -81,7 +72,15 @@ async fn run_impl(
.clone()
.unwrap_or_else(|| default_vault_name(&opts.state));

let issuer = match cmd.identity().await {
let identities = match identities(&vault_name, &opts).await {
Ok(i) => i,
Err(_) => {
*is_finished.lock().await = true;
return Err(miette!("Invalid state").into());
}
};

let issuer = match identity(&cmd.issuer, identities.clone()).await {
Ok(i) => i,
Err(_) => {
*is_finished.lock().await = true;
Expand All @@ -90,8 +89,7 @@ async fn run_impl(
};

let cred = hex::decode(&cred_as_str)?;
if let Err(e) = validate_encoded_cred(&cred, issuer.identifier(), &vault_name, &opts).await
{
if let Err(e) = validate_encoded_cred(&cred, identities, issuer.identifier()).await {
*is_finished.lock().await = true;
return Err(miette!("Credential is invalid\n{}", e).into());
}
Expand Down
42 changes: 20 additions & 22 deletions implementations/rust/ockam/ockam_command/src/credential/verify.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
use std::path::PathBuf;

use crate::{
fmt_err, fmt_log, fmt_ok, util::node_rpc, vault::default_vault_name, CommandGlobalOpts, Result,
fmt_err, fmt_log, fmt_ok, util::node_rpc, vault::default_vault_name, CommandGlobalOpts,
};
use miette::miette;

use crate::credential::{identities, identity};
use clap::Args;
use colorful::Colorful;
use ockam::identity::{identities, Identity};
use ockam::Context;
use tokio::{sync::Mutex, try_join};

Expand All @@ -32,18 +32,6 @@ impl VerifyCommand {
pub fn run(self, opts: CommandGlobalOpts) {
node_rpc(run_impl, (opts, self));
}

pub async fn issuer(&self) -> Result<Identity> {
let identity_as_bytes = match hex::decode(&self.issuer) {
Ok(b) => b,
Err(e) => return Err(miette!(e).into()),
};
let identity = identities()
.identities_creation()
.import(None, &identity_as_bytes)
.await?;
Ok(identity)
}
}

async fn run_impl(
Expand All @@ -57,7 +45,10 @@ async fn run_impl(

let send_req = async {
let cred_as_str = match (&cmd.credential, &cmd.credential_path) {
(_, Some(credential_path)) => tokio::fs::read_to_string(credential_path).await?,
(_, Some(credential_path)) => tokio::fs::read_to_string(credential_path)
.await?
.trim()
.to_string(),
(Some(credential), _) => credential.clone(),
_ => {
*is_finished.lock().await = true;
Expand All @@ -72,20 +63,27 @@ async fn run_impl(
.clone()
.unwrap_or_else(|| default_vault_name(&opts.state));

let issuer = match cmd.issuer().await {
let identities = match identities(&vault_name, &opts).await {
Ok(i) => i,
Err(_) => {
*is_finished.lock().await = true;
return Err(miette!("Invalid state").into());
}
};

let issuer = match identity(&cmd.issuer, identities.clone()).await {
Ok(i) => i,
Err(_) => {
*is_finished.lock().await = true;
return Ok((false, "Issuer is invalid".to_string()));
return Err(miette!("Issuer is invalid").into());
}
};

let cred = hex::decode(&cred_as_str)?;
let is_valid =
match validate_encoded_cred(&cred, issuer.identifier(), &vault_name, &opts).await {
Ok(_) => (true, String::new()),
Err(e) => (false, e.to_string()),
};
let is_valid = match validate_encoded_cred(&cred, identities, issuer.identifier()).await {
Ok(_) => (true, String::new()),
Err(e) => (false, e.to_string()),
};

*is_finished.lock().await = true;
Ok(is_valid)
Expand Down
50 changes: 21 additions & 29 deletions implementations/rust/ockam/ockam_command/src/identity/show.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
use crate::identity::{get_identity_name, initialize_identity_if_default};
use crate::util::output::Output;
use crate::util::output::{IdentifierDisplay, IdentityDisplay};
use crate::util::{node_rpc, println_output};
use crate::{docs, CommandGlobalOpts, EncodeFormat, Result};
use crate::{docs, CommandGlobalOpts, EncodeFormat};
use clap::Args;
use core::fmt::Write;
use miette::IntoDiagnostic;
use ockam::identity::Identity;
use ockam_api::cli_state::traits::{StateDirTrait, StateItemTrait};
use ockam_api::nodes::models::identity::{LongIdentityResponse, ShortIdentityResponse};
use ockam_node::Context;
use ockam_vault::Vault;

const LONG_ABOUT: &str = include_str!("./static/show/long_about.txt");
const PREVIEW_TAG: &str = include_str!("../static/preview_tag.txt");
Expand Down Expand Up @@ -48,45 +48,37 @@ impl ShowCommand {
let (opts, cmd) = options;
let name = get_identity_name(&opts.state, &cmd.name);
let state = opts.state.identities.get(&name)?;
let identifier = state.config().identifier();
if cmd.full {
let identifier = state.config().identifier();
let identity = opts
let change_history = opts
.state
.identities
.identities_repository()
.await?
.get_identity(&identifier)
.await
.into_diagnostic()?
.export()
.into_diagnostic()?;

if Some(EncodeFormat::Hex) == cmd.encoding {
println_output(identity, &opts.global_args.output_format)?;
println_output(
hex::encode(change_history.export().into_diagnostic()?),
&opts.global_args.output_format,
)?;
} else {
let output = LongIdentityResponse::new(identity);
println_output(output, &opts.global_args.output_format)?;
let identity = Identity::import_from_change_history(
Some(&identifier),
change_history,
Vault::create_verifying_vault(),
)
.await
.into_diagnostic()?;
let identity_display = IdentityDisplay(identity);
println_output(identity_display, &opts.global_args.output_format)?;
}
} else {
let output = ShortIdentityResponse::new(state.config().identifier());
println_output(output, &opts.global_args.output_format)?;
let identifier_display = IdentifierDisplay(identifier);
println_output(identifier_display, &opts.global_args.output_format)?;
}
Ok(())
}
}

impl Output for LongIdentityResponse {
fn output(&self) -> Result<String> {
let mut w = String::new();
write!(w, "{}", hex::encode(&self.identity_change_history))?;
Ok(w)
}
}

impl Output for ShortIdentityResponse {
fn output(&self) -> Result<String> {
let mut w = String::new();
write!(w, "{}", self.identity_id)?;
Ok(w)
}
}
2 changes: 2 additions & 0 deletions implementations/rust/ockam/ockam_command/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@
//!
//! For more information please visit the [command guide](https://docs.ockam.io/reference/command)
extern crate core;

mod admin;
mod authenticated;
mod authority;
Expand Down
Loading

0 comments on commit 47c9ef3

Please sign in to comment.