Skip to content

Commit

Permalink
Merge pull request #162 from alan-turing-institute/94-cr-cli
Browse files Browse the repository at this point in the history
Challenge-response for attestation
  • Loading branch information
pwochner authored Oct 7, 2024
2 parents 20fbf78 + 563a438 commit d7cb63d
Show file tree
Hide file tree
Showing 30 changed files with 3,008 additions and 18 deletions.
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -32,5 +32,8 @@ outputs/
# dist paths
**/dist

# Python venv
.venv

# OS
.DS_Store
3 changes: 3 additions & 0 deletions trustchain-cli/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,12 @@ path = "src/bin/main.rs"
trustchain-core = { path = "../trustchain-core" }
trustchain-ion = { path = "../trustchain-ion" }
trustchain-api = { path = "../trustchain-api" }
trustchain-http = { path = "../trustchain-http" }


clap = { version = "4.0.32", features = ["derive", "cargo"] }
did-ion = { git = "https://github.com/alan-turing-institute/ssi.git", rev = "1aa3223a384ee71df1333bbce04af445e852eab5" }
josekit = "0.8"
lazy_static = "1.4.0"
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
Expand Down
256 changes: 253 additions & 3 deletions trustchain-cli/src/bin/main.rs
Original file line number Diff line number Diff line change
@@ -1,21 +1,32 @@
//! Trustchain CLI binary
use clap::{arg, ArgAction, Command};
use core::panic;
use serde_json::to_string_pretty;
use ssi::{jsonld::ContextLoader, ldp::LinkedDataDocument, vc::Credential};
use std::{
fs::File,
io::{stdin, BufReader},
io::{self, stdin, BufReader},
path::Path,
path::PathBuf,
};
use trustchain_api::{
api::{TrustchainDIDAPI, TrustchainDataAPI, TrustchainVCAPI},
TrustchainAPI,
};
use trustchain_cli::config::cli_config;
use trustchain_core::{
utils::extract_keys,
vc::{CredentialError, DataCredentialError},
verifier::Verifier,
JSON_FILE_EXTENSION,
JSON_FILE_EXTENSION, TRUSTCHAIN_DATA,
};
use trustchain_http::{
attestation_encryption_utils::ssi_to_josekit_jwk,
attestation_utils::{
CRState, ElementwiseSerializeDeserialize, IdentityCRInitiation, TrustchainCRError,
},
attestor::present_identity_challenge,
requester::{identity_response, initiate_content_challenge, initiate_identity_challenge},
};
use trustchain_ion::{
attest::attest_operation,
Expand Down Expand Up @@ -109,15 +120,71 @@ fn cli() -> Command {
.arg(arg!(-v - -verbose).action(ArgAction::Count))
.arg(arg!(-f --data_file <DATA_FILE>).required(true))
.arg(arg!(-c --credential_file <CREDENTIAL_FILE>).required(true))
.arg(arg!(-t --root_event_time <ROOT_EVENT_TIME>).required(false)),
.arg(arg!(-t --root_event_time <ROOT_EVENT_TIME>).required(false))
),
)
.subcommand(
Command::new("cr")
.about("Challenge-response functionality for attestation challenge response process (identity and content challenge-response).")
.subcommand_required(true)
.arg_required_else_help(true)
.allow_external_subcommands(true)
.subcommand(
Command::new("identity")
.about("Identity challenge-response functionality: initiate, present, respond.")
.arg(arg!(-v - -verbose).action(ArgAction::SetTrue))
.arg(arg!(-f --file_path <FILE_PATH>).required(false))
.subcommand(
Command::new("initiate")
.about("Initiates a new identity challenge-response process.")
.arg(arg!(-v - -verbose).action(ArgAction::Count))
.arg(arg!(-d --did <ATTESTOR_DID>).required(true))
)
.subcommand(
Command::new("present")
.about("Produce challenge for identity CR to be presented to requestor.")
.arg(arg!(-v - -verbose).action(ArgAction::Count))
.arg(arg!(-p --path <TEMP_P_KEY_ID_FOR_PATH>).required(true))
.arg(arg!(-d --did <ATTESTOR_DID>).required(true))
)
.subcommand(
Command::new("respond")
.about("Produce response for identity challenge to be posted to attestor.")
.arg(arg!(-v - -verbose).action(ArgAction::Count))
.arg(arg!(-p --path <TEMP_P_KEY_ID_FOR_PATH>).required(true))
.arg(arg!(-d --did <ATTESTOR_DID>).required(true))
)
)
.subcommand(
Command::new("content")
.about("Content challenge-response functionality: initiate, respond.")
.arg(arg!(-v - -verbose).action(ArgAction::SetTrue))
.arg(arg!(-f --file_path <FILE_PATH>).required(false))
.subcommand(
Command::new("initiate")
.about("Initiates the content challenge-response process.")
.arg(arg!(-v - -verbose).action(ArgAction::Count))
.arg(arg!(-d --did <ATTESTOR_DID>).required(true))
.arg(arg!(--ddid <CANDIDATE_DOWNSTREAM_DID>).required(true))
.arg(arg!(-p --path <TEMP_P_KEY_ID_FOR_PATH>).required(true))
)
)
.subcommand(
Command::new("complete")
.about("Check if challenge-response for attestation request has been completed.")
.arg(arg!(-v - -verbose).action(ArgAction::SetTrue))
.arg(arg!(-p --path <TEMP_P_KEY_ID_FOR_PATH>).required(true))
.arg(arg!(-e --entity <ATTESTOR_OR_REQUESTER>).required(true))
)

)
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let matches = cli().get_matches();
let endpoint = cli_config().ion_endpoint.to_address();
let root_event_time: u32 = cli_config().root_event_time;
let verifier = TrustchainVerifier::new(trustchain_resolver(&endpoint));
let resolver = verifier.resolver();
let mut context_loader = ContextLoader::default();
Expand Down Expand Up @@ -302,6 +369,189 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
_ => panic!("Unrecognised VC subcommand."),
}
}
Some(("cr", sub_matches)) => match sub_matches.subcommand() {
Some(("identity", sub_matches)) => match sub_matches.subcommand() {
Some(("initiate", sub_matches)) => {
// verify DID before resolving and extracting endpoint
let did = sub_matches.get_one::<String>("did").unwrap();
let _result = verifier.verify(did, root_event_time.into()).await?;
let (_, doc, _) = TrustchainAPI::resolve(did, resolver).await?;
let services = doc.unwrap().service;

// user promt for org name and operator name
println!("Please enter your organisation name: ");
let mut org_name = String::new();
io::stdin()
.read_line(&mut org_name)
.expect("Failed to read line");

let mut op_name = String::new();
println!("Please enter your operator name: ");
io::stdin()
.read_line(&mut op_name)
.expect("Failed to read line");

println!("Organisation name: {}", org_name);
println!("Operator name: {}", op_name);
// initiate identity challenge
let (identity_cr_initiation, path) = initiate_identity_challenge(
org_name.trim(),
op_name.trim(),
&services.unwrap(),
)
.await?;
identity_cr_initiation.elementwise_serialize(&path)?;
println!("Successfully initiated attestation request.");
println!("You will receive more information on the challenge-response process via alternative communication channel.");
}
Some(("present", sub_matches)) => {
// get attestation request path from provided input
let trustchain_dir: String = std::env::var(TRUSTCHAIN_DATA)
.map_err(|_| TrustchainCRError::FailedAttestationRequest)?;
let path_to_check = sub_matches.get_one::<String>("path").unwrap();
let did = sub_matches.get_one::<String>("did").unwrap();
let path = PathBuf::new()
.join(trustchain_dir)
.join("attestor")
.join("attestation_requests")
.join(path_to_check);
if !path.exists() {
panic!("Provided attestation request not found. Path does not exist.");
}
let identity_initiation = IdentityCRInitiation::new()
.elementwise_deserialize(&path)
.unwrap();
// Show requester information to user and ask for confirmation to proceed
println!("---------------------------------");
println!("Requester information: ");
println!(
"{:?}",
identity_initiation
.as_ref()
.unwrap()
.requester_details
.as_ref()
.unwrap()
);
println!("---------------------------------");
println!("Recognise this attestation request and want to proceed? (y/n)");
let mut prompt = String::new();
io::stdin()
.read_line(&mut prompt)
.expect("Failed to read line");
let prompt = prompt.trim();
if prompt != "y" && prompt != "yes" {
println!("Aborting attestation request.");
return Ok(());
}

let temp_p_key = identity_initiation.unwrap().temp_p_key.unwrap();

// call function to present challenge
let identity_challenge = present_identity_challenge(did, &temp_p_key)?;

// print signed and encrypted payload to terminal
let payload = identity_challenge
.identity_challenge_signature
.as_ref()
.unwrap();
println!("---------------------------------");
println!("Signed and encrypted challenge:");
println!("{:?}", payload);
println!("---------------------------------");
println!("Please send the above challenge to the requester via alternative channels.");
println!("Before responding using the 'respond' subcommand, the requester has to save the challenge to a file named 'identity_challenge_signature.json' in the corresponding attestation request directory.");
println!("---------------------------------");

// serialise struct
identity_challenge.elementwise_serialize(&path)?;
}
Some(("respond", sub_matches)) => {
// get attestation request path from provided input
let trustchain_dir: String = std::env::var(TRUSTCHAIN_DATA)
.map_err(|_| TrustchainCRError::FailedAttestationRequest)?;
let path_to_check = sub_matches.get_one::<String>("path").unwrap();
let path = PathBuf::new()
.join(trustchain_dir)
.join("requester")
.join("attestation_requests")
.join(path_to_check);
if !path.exists() {
panic!("Provided attestation request not found. Path does not exist.");
}
let did = sub_matches.get_one::<String>("did").unwrap();
let (_, doc, _) = TrustchainAPI::resolve(did, resolver).await?;
let doc = doc.unwrap();
// extract attestor public key from did document
let public_keys = extract_keys(&doc);
let attestor_public_key_ssi = public_keys.first().unwrap();
let public_key = ssi_to_josekit_jwk(attestor_public_key_ssi).unwrap();
// service endpoint
let services = doc.service.unwrap();
let identity_challenge_response =
identity_response(&path, &services, &public_key).await?;
// serialise struct
identity_challenge_response.elementwise_serialize(&path)?;
}
_ => panic!("Unrecognised CR identity subcommand."),
},
Some(("content", sub_matches)) => match sub_matches.subcommand() {
Some(("initiate", sub_matches)) => {
let did = sub_matches.get_one::<String>("did").unwrap();
let ddid = sub_matches.get_one::<String>("ddid").unwrap();
let path_to_check = sub_matches.get_one::<String>("path").unwrap();

// check attestation request path
let trustchain_dir: String = std::env::var(TRUSTCHAIN_DATA)
.map_err(|_| TrustchainCRError::FailedAttestationRequest)?;
let path = PathBuf::new()
.join(trustchain_dir)
.join("requester")
.join("attestation_requests")
.join(path_to_check);
if !path.exists() {
panic!("Provided attestation request not found. Path does not exist.");
}

// resolve DID, get services and attestor public key
let (_, doc, _) = TrustchainAPI::resolve(did, resolver).await?;
let doc = doc.unwrap();
let public_keys = extract_keys(&doc);
let attestor_public_key_ssi = public_keys.first().unwrap();
let attestor_public_key = ssi_to_josekit_jwk(attestor_public_key_ssi).unwrap();
let services = &doc.service.unwrap();

let (content_initiation, content_challenge) =
initiate_content_challenge(&path, ddid, services, &attestor_public_key)
.await?;
content_initiation.elementwise_serialize(&path)?;
content_challenge.elementwise_serialize(&path)?;
}
_ => panic!("Unrecognised CR content subcommand."),
},
Some(("complete", sub_matches)) => {
let path_to_check = sub_matches.get_one::<String>("path").unwrap();
let entity = sub_matches.get_one::<String>("entity").unwrap();
let trustchain_dir: String = std::env::var(TRUSTCHAIN_DATA)
.map_err(|_| TrustchainCRError::FailedAttestationRequest)?;
let path = PathBuf::new()
.join(trustchain_dir)
.join(entity)
.join("attestation_requests")
.join(path_to_check);
let cr_state = CRState::new()
.elementwise_deserialize(&path)
.unwrap()
.unwrap();
let current_state = cr_state.check_cr_status().unwrap();

println!(
"State of attestation challenge-response process: {:?}",
current_state
);
}
_ => panic!("Unrecognised CR subcommand."),
},
Some(("data", sub_matches)) => {
let verifier = TrustchainVerifier::new(trustchain_resolver(&endpoint));
let resolver = verifier.resolver();
Expand Down
2 changes: 1 addition & 1 deletion trustchain-core/src/attestor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ pub enum AttestorError {
SigningError(String, String),
}

/// An upstream entity that attests to a downstream DID.
/// An upstream entity that attests to a downstream DID (attestor).
pub trait Attestor: Subject {
/// Attests to a DID Document. Subject attests to a DID document by signing the document with (one of) its private signing key(s).
/// It doesn't matter which signing key you use, there's the option to pick one using the key index.
Expand Down
2 changes: 1 addition & 1 deletion trustchain-core/src/graph.rs
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ fn read_chains(chains: &Vec<DIDChain>, label_width: usize) -> DiGraph<String, St
}

// Update did
did = ddid.to_owned();
ddid.clone_into(&mut did);
level += 1;
}
}
Expand Down
5 changes: 5 additions & 0 deletions trustchain-core/src/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,9 @@ pub fn init() {
// Include test signing keys for two resolvable DIDs
let root_plus_1_did_suffix = "EiBVpjUxXeSRJpvj2TewlX9zNF3GKMCKWwGmKBZqF6pk_A";
let root_plus_2_did_suffix = "EiAtHHKFJWAk5AsM3tgCut3OiBY4ekHTf66AAjoysXL65Q";
let root_plus_2_candidate_did_suffix = "EiCDmY0qxsde9AdIwMf2tUKOiMo4aHnoWaPBRCeGt7iMHA";
// TODO: move to data as for the other keys
let root_plus_2_candidate_signing_key: &str = r#"{"kty":"EC","crv":"secp256k1","x":"WzbWcgvvq21xKDTsvANakBSI3nJKDSmNa99usFmYJ0E","y":"vAFo1gkFqgEE3QsX1xlmHcoKxs5AuDqc18kkYEGVwDk","d":"LHt66ri5ykeVqEZwbzboJevbh5UEZkT8r8etsjg3KeE"}"#;
let root_plus_1_signing_jwk: JWK = serde_json::from_str(ROOT_PLUS_1_SIGNING_KEY).unwrap();
let root_plus_2_signing_jwks: Vec<JWK> =
serde_json::from_str(ROOT_PLUS_2_SIGNING_KEYS).unwrap();
Expand All @@ -55,6 +58,8 @@ pub fn init() {
false,
)
.unwrap();
let root_plus_2_candidate_signing_jwk: JWK = serde_json::from_str(root_plus_2_candidate_signing_key).unwrap();
utils_key_manager.save_keys(root_plus_2_candidate_did_suffix, KeyType::SigningKey, &OneOrMany::One(root_plus_2_candidate_signing_jwk), false).unwrap();
});
}

Expand Down
1 change: 1 addition & 0 deletions trustchain-ffi/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ crate-type = ["cdylib", "staticlib", "lib"]
trustchain-core = { path = "../trustchain-core" }
trustchain-ion = { path = "../trustchain-ion" }
trustchain-api = { path = "../trustchain-api" }
trustchain-http = { path = "../trustchain-http" }

anyhow = "1.0"
chrono = "0.4.26"
Expand Down
4 changes: 2 additions & 2 deletions trustchain-ffi/src/gui.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use tokio::runtime::Runtime;
use trustchain_api::{api::TrustchainDIDAPI, TrustchainAPI};
use trustchain_core::chain::DIDChain;
use trustchain_core::verifier::Verifier;
use trustchain_ion::{get_ion_resolver, verifier::IONVerifier};
use trustchain_ion::{get_ion_resolver, verifier::TrustchainVerifier};

/// Example greet function.
pub fn greet() -> String {
Expand All @@ -30,7 +30,7 @@ pub fn verify_prototype(did: String, root_timestamp: u32) -> DIDChain {
rt.block_on(async {
// Construct a Trustchain Resolver from a Sidetree (ION) DIDMethod.
let resolver = get_ion_resolver("http://localhost:3000/");
let verifier = IONVerifier::new(resolver);
let verifier = TrustchainVerifier::new(resolver);

verifier.verify(&did, root_timestamp).await.unwrap()
})
Expand Down
Loading

0 comments on commit d7cb63d

Please sign in to comment.