From ae03334a64b1d7d6506ffb60a01f5c7f941900a6 Mon Sep 17 00:00:00 2001 From: Bryan Newbold Date: Sun, 6 Nov 2022 21:15:12 -0800 Subject: pds: partial clippy clean --- adenosine-pds/src/car.rs | 2 +- adenosine-pds/src/crypto.rs | 9 +++----- adenosine-pds/src/db.rs | 2 +- adenosine-pds/src/did.rs | 14 ++++++------ adenosine-pds/src/lib.rs | 48 +++++++++++++++++++++--------------------- adenosine-pds/src/models.rs | 2 -- adenosine-pds/src/mst.rs | 10 ++++----- adenosine-pds/src/repo.rs | 19 ++++++++--------- adenosine-pds/src/ucan_p256.rs | 19 ++++++----------- 9 files changed, 57 insertions(+), 68 deletions(-) diff --git a/adenosine-pds/src/car.rs b/adenosine-pds/src/car.rs index 63911e5..b14d0b1 100644 --- a/adenosine-pds/src/car.rs +++ b/adenosine-pds/src/car.rs @@ -56,7 +56,7 @@ async fn inner_car_loader( .await?; // pin the header (?) - if car_header.roots().len() >= 1 { + if !car_header.roots().is_empty() { db.alias(alias.as_bytes(), Some(&car_header.roots()[0]))?; } diff --git a/adenosine-pds/src/crypto.rs b/adenosine-pds/src/crypto.rs index 1fa6f4c..ba69dc6 100644 --- a/adenosine-pds/src/crypto.rs +++ b/adenosine-pds/src/crypto.rs @@ -1,8 +1,5 @@ use crate::P256KeyMaterial; use anyhow::{anyhow, ensure, Result}; -use k256; -use multibase; -use p256; use p256::ecdsa::signature::{Signer, Verifier}; use std::str::FromStr; use ucan::builder::UcanBuilder; @@ -52,7 +49,7 @@ impl KeyPair { } pub fn pubkey(&self) -> PubKey { - PubKey::P256(self.public.clone()) + PubKey::P256(self.public) } pub fn sign_bytes(&self, data: &[u8]) -> String { @@ -79,7 +76,7 @@ impl KeyPair { pub fn from_hex(hex: &str) -> Result { Ok(Self::from_bytes( - &data_encoding::HEXUPPER.decode(&hex.as_bytes())?, + &data_encoding::HEXUPPER.decode(hex.as_bytes())?, )?) } } @@ -218,7 +215,7 @@ fn test_did_secp256k1_p256() { ]; // test decode/encode did:key - for (hex, did) in pairs.iter() { + for (_hex, did) in pairs.iter() { assert_eq!(did, &PubKey::from_did_key(did).unwrap().to_did_key()); } diff --git a/adenosine-pds/src/db.rs b/adenosine-pds/src/db.rs index e6b957c..0fae769 100644 --- a/adenosine-pds/src/db.rs +++ b/adenosine-pds/src/db.rs @@ -119,7 +119,7 @@ impl AtpDatabase { did, name: username.to_string(), accessJwt: jwt.to_string(), - refreshJwt: jwt.to_string(), + refreshJwt: jwt, }) } diff --git a/adenosine-pds/src/did.rs b/adenosine-pds/src/did.rs index 389b090..cfec27c 100644 --- a/adenosine-pds/src/did.rs +++ b/adenosine-pds/src/did.rs @@ -62,9 +62,9 @@ impl CreateOp { op_type: "create".to_string(), prev: None, signingKey: signing_key, - recoveryKey: recovery_key.to_string(), - username: username.to_string(), - service: atp_pds.to_string(), + recoveryKey: recovery_key, + username: username, + service: atp_pds, }; let block = Block::::encode(DagCborCodec, Code::Sha2_256, &unsigned) .expect("encode DAG-CBOR"); @@ -79,7 +79,7 @@ impl CreateOp { let bin = block.data(); // hash SHA-256 let digest_bytes: Vec = data_encoding::HEXLOWER - .decode(&sha256::digest(bin).as_bytes()) + .decode(sha256::digest(bin).as_bytes()) .expect("SHA-256 digest is always hex string"); // encode base32 let digest_b32 = data_encoding::BASE32_NOPAD @@ -167,7 +167,7 @@ fn test_debug_did_signing() { Block::::encode(DagCborCodec, Code::Sha2_256, &op).expect("encode DAG-CBOR"); let op_bytes = block.data(); - let key_bytes = vec![ + let _key_bytes = vec![ 4, 30, 224, 8, 198, 84, 108, 1, 58, 193, 91, 176, 212, 45, 4, 36, 28, 252, 242, 95, 20, 85, 87, 246, 79, 134, 42, 113, 5, 216, 238, 235, 21, 146, 16, 88, 239, 217, 36, 252, 148, 197, 203, 22, 29, 2, 52, 152, 77, 208, 21, 88, 2, 85, 219, 212, 148, 139, 104, 200, 15, 119, 46, @@ -194,7 +194,7 @@ fn test_debug_did_signing() { ]; assert_eq!(encoded_bytes, op_bytes); - let sig_bytes = vec![ + let _sig_bytes = vec![ 131, 115, 47, 143, 89, 68, 79, 73, 121, 198, 70, 76, 91, 64, 171, 25, 18, 139, 244, 94, 123, 224, 205, 32, 241, 174, 36, 120, 199, 206, 199, 202, 216, 154, 2, 10, 247, 101, 138, 170, 85, 95, 142, 164, 50, 203, 92, 23, 247, 218, 231, 224, 78, 68, 55, 104, 243, 145, 243, @@ -269,7 +269,7 @@ fn test_debug_did_plc() { assert_eq!(op_bytes, encoded_bytes); let sha256_str = "cg2dfxdh5voabmdjzw2abw3sgvtjymknh2bmpvtwot7t2ih4v7za"; - let did_plc = "did:plc:cg2dfxdh5voabmdjzw2abw3s"; + let _did_plc = "did:plc:cg2dfxdh5voabmdjzw2abw3s"; let digest_bytes: Vec = data_encoding::HEXLOWER .decode(&sha256::digest(op_bytes).as_bytes()) diff --git a/adenosine-pds/src/lib.rs b/adenosine-pds/src/lib.rs index 5803782..917aa7e 100644 --- a/adenosine-pds/src/lib.rs +++ b/adenosine-pds/src/lib.rs @@ -83,7 +83,7 @@ pub fn run_server( repo: RepoStore::open(blockstore_db_path)?, atp_db: AtpDatabase::open(atp_db_path)?, pds_keypair: keypair, - pds_public_url: format!("http://localhost:{}", port).to_string(), + pds_public_url: format!("http://localhost:{}", port), tid_gen: TidLord::new(), }); @@ -129,7 +129,7 @@ fn ipld_into_json_value(val: Ipld) -> Value { Ipld::Float(v) => json!(v), Ipld::String(s) => Value::String(s), Ipld::Bytes(b) => Value::String(data_encoding::BASE64_NOPAD.encode(&b)), - Ipld::List(l) => Value::Array(l.into_iter().map(|v| ipld_into_json_value(v)).collect()), + Ipld::List(l) => Value::Array(l.into_iter().map(ipld_into_json_value).collect()), Ipld::Map(m) => Value::Object(serde_json::Map::from_iter( m.into_iter().map(|(k, v)| (k, ipld_into_json_value(v))), )), @@ -148,7 +148,7 @@ fn json_value_into_ipld(val: Value) -> Ipld { Value::String(s) => Ipld::String(s), // TODO: handle numbers better? Value::Number(v) => Ipld::Float(v.as_f64().unwrap()), - Value::Array(l) => Ipld::List(l.into_iter().map(|v| json_value_into_ipld(v)).collect()), + Value::Array(l) => Ipld::List(l.into_iter().map(json_value_into_ipld).collect()), Value::Object(m) => { let map: BTreeMap = BTreeMap::from_iter(m.into_iter().map(|(k, v)| { if k == "car" && v.is_string() { @@ -177,20 +177,20 @@ fn xrpc_check_auth_header( ) -> Result { let header = request .header("Authorization") - .ok_or(XrpcError::Forbidden(format!("require auth header")))?; + .ok_or(XrpcError::Forbidden("require auth header".to_string()))?; if !header.starts_with("Bearer ") { - Err(XrpcError::Forbidden(format!("require bearer token")))?; + Err(XrpcError::Forbidden("require bearer token".to_string()))?; } - let jwt = header.split(" ").nth(1).unwrap(); - let did = match srv.atp_db.check_auth_token(&jwt)? { + let jwt = header.split(' ').nth(1).unwrap(); + let did = match srv.atp_db.check_auth_token(jwt)? { Some(did) => did, - None => Err(XrpcError::Forbidden(format!("session token not found")))?, + None => Err(XrpcError::Forbidden("session token not found".to_string()))?, }; let did = Did::from_str(&did)?; if req_did.is_some() && Some(&did) != req_did { - Err(XrpcError::Forbidden(format!( - "can only modify your own repo" - )))?; + Err(XrpcError::Forbidden( + "can only modify your own repo".to_string(), + ))?; } Ok(did) } @@ -237,7 +237,7 @@ fn xrpc_get_handler( let mut record_list: Vec = vec![]; let mut srv = srv.lock().expect("service mutex"); let commit_cid = &srv.repo.lookup_commit(&did)?.unwrap(); - let last_commit = srv.repo.get_commit(&commit_cid)?; + let last_commit = srv.repo.get_commit(commit_cid)?; let full_map = srv.repo.mst_to_map(&last_commit.mst_cid)?; let prefix = format!("/{}/", collection); for (mst_key, cid) in full_map.iter() { @@ -291,9 +291,9 @@ fn xrpc_post_handler( // check if account already exists (fast path, also confirmed by database schema) let mut srv = srv.lock().unwrap(); if srv.atp_db.account_exists(&req.username, &req.email)? { - Err(XrpcError::BadRequest(format!( - "username or email already exists" - )))?; + Err(XrpcError::BadRequest( + "username or email already exists".to_string(), + ))?; }; debug!("trying to create new account: {}", &req.username); @@ -352,12 +352,12 @@ fn xrpc_post_handler( let _did = xrpc_check_auth_header(&mut srv, request, None)?; let header = request .header("Authorization") - .ok_or(XrpcError::Forbidden(format!("require auth header")))?; + .ok_or(XrpcError::Forbidden("require auth header".to_string()))?; if !header.starts_with("Bearer ") { - Err(XrpcError::Forbidden(format!("require bearer token")))?; + Err(XrpcError::Forbidden("require bearer token".to_string()))?; } - let jwt = header.split(" ").nth(1).expect("JWT in header"); - if !srv.atp_db.delete_session(&jwt)? { + let jwt = header.split(' ').nth(1).expect("JWT in header"); + if !srv.atp_db.delete_session(jwt)? { Err(anyhow!( "session token not found, even after using for auth" ))? @@ -371,7 +371,7 @@ fn xrpc_post_handler( let mut srv = srv.lock().unwrap(); let _auth_did = &xrpc_check_auth_header(&mut srv, request, Some(&did))?; let commit_cid = &srv.repo.lookup_commit(&did)?.unwrap(); - let last_commit = srv.repo.get_commit(&commit_cid)?; + let last_commit = srv.repo.get_commit(commit_cid)?; let mut mutations: Vec = Default::default(); for w in batch.writes.iter() { let m = match w.op_type.as_str() { @@ -380,7 +380,7 @@ fn xrpc_post_handler( // TODO: user input unwrap here w.rkey .as_ref() - .map(|t| Tid::from_str(&t).unwrap()) + .map(|t| Tid::from_str(t).unwrap()) .unwrap_or_else(|| srv.tid_gen.next_tid()), json_value_into_ipld(w.value.clone()), ), @@ -416,7 +416,7 @@ fn xrpc_post_handler( let _auth_did = &xrpc_check_auth_header(&mut srv, request, Some(&did))?; debug!("reading commit"); let commit_cid = &srv.repo.lookup_commit(&did)?.unwrap(); - let last_commit = srv.repo.get_commit(&commit_cid)?; + let last_commit = srv.repo.get_commit(commit_cid)?; let mutations: Vec = vec![Mutation::Create( collection, srv.tid_gen.next_tid(), @@ -447,7 +447,7 @@ fn xrpc_post_handler( let mut srv = srv.lock().unwrap(); let _auth_did = &xrpc_check_auth_header(&mut srv, request, Some(&did))?; let commit_cid = &srv.repo.lookup_commit(&did)?.unwrap(); - let last_commit = srv.repo.get_commit(&commit_cid)?; + let last_commit = srv.repo.get_commit(commit_cid)?; let mutations: Vec = vec![Mutation::Update( collection, tid, @@ -473,7 +473,7 @@ fn xrpc_post_handler( let mut srv = srv.lock().unwrap(); let _auth_did = &xrpc_check_auth_header(&mut srv, request, Some(&did))?; let commit_cid = &srv.repo.lookup_commit(&did)?.unwrap(); - let last_commit = srv.repo.get_commit(&commit_cid)?; + let last_commit = srv.repo.get_commit(commit_cid)?; let mutations: Vec = vec![Mutation::Delete(collection, tid)]; let new_mst_cid = srv.repo.update_mst(&last_commit.mst_cid, &mutations)?; let new_root_cid = srv.repo.write_root( diff --git a/adenosine-pds/src/models.rs b/adenosine-pds/src/models.rs index afadeea..97705af 100644 --- a/adenosine-pds/src/models.rs +++ b/adenosine-pds/src/models.rs @@ -1,5 +1,3 @@ -use serde; - #[allow(non_snake_case)] #[derive(Debug, serde::Deserialize, serde::Serialize, PartialEq, Eq)] pub struct AccountRequest { diff --git a/adenosine-pds/src/mst.rs b/adenosine-pds/src/mst.rs index 94e5f68..324d139 100644 --- a/adenosine-pds/src/mst.rs +++ b/adenosine-pds/src/mst.rs @@ -98,7 +98,7 @@ pub fn dump_mst_keys(db_path: &PathBuf) -> Result<()> { // print all the aliases for (alias, commit_cid) in all_aliases.iter() { - let did = String::from_utf8_lossy(&alias); + let did = String::from_utf8_lossy(alias); println!("{} -> {}", did, commit_cid); } @@ -164,7 +164,7 @@ fn leading_zeros(key: &str) -> u8 { let digest = sha256::digest(key); let digest = digest.as_bytes(); for i in 0..digest.len() { - if digest[i] != '0' as u8 { + if digest[i] != b'0' { return i as u8; } } @@ -182,7 +182,7 @@ pub fn generate_mst( let entry = WipEntry { height, key: key.clone(), - val: val.clone(), + val: *val, right: None, }; if let Some(node) = root { @@ -293,7 +293,7 @@ fn serialize_wip_tree( e: entries, }; let block = Block::::encode(DagCborCodec, Code::Sha2_256, &mst_node)?; - let cid = block.cid().clone(); + let cid = *block.cid(); db.put_block(block, None)?; Ok(cid) } @@ -331,7 +331,7 @@ pub fn repro_mst(car_path: &PathBuf) -> Result<()> { collect_mst_keys(&mut db, &root_node.data, &mut repo_map)?; // now re-generate nodes - let updated = generate_mst(&mut db, &mut repo_map)?; + let updated = generate_mst(&mut db, &repo_map)?; info!("original root: {}", root_node.data); info!("regenerated : {}", updated); diff --git a/adenosine-pds/src/repo.rs b/adenosine-pds/src/repo.rs index 442f81b..c75ba15 100644 --- a/adenosine-pds/src/repo.rs +++ b/adenosine-pds/src/repo.rs @@ -8,7 +8,6 @@ use libipld::multihash::Code; use libipld::prelude::Codec; use libipld::store::DefaultParams; use libipld::{Block, Cid, Ipld}; -use log::debug; use std::borrow::Cow; use std::collections::BTreeMap; use std::collections::HashSet; @@ -74,7 +73,7 @@ impl RepoStore { record: &S, ) -> Result { let block = Block::::encode(DagCborCodec, Code::Sha2_256, record)?; - let cid = block.cid().clone(); + let cid = *block.cid(); self.db .put_block(block, None) .context("writing IPLD DAG-CBOR record to blockstore")?; @@ -84,7 +83,7 @@ impl RepoStore { /// Returns CID that was inserted pub fn put_blob(&mut self, data: &[u8]) -> Result { let block = Block::::encode(libipld::raw::RawCodec, Code::Sha2_256, data)?; - let cid = block.cid().clone(); + let cid = *block.cid(); self.db .put_block(block, None) .context("writing non-record blob to blockstore")?; @@ -164,7 +163,7 @@ impl RepoStore { let mut collections: HashSet = Default::default(); // XXX: confirm that keys actually start with leading slash for k in map.keys() { - let coll = k.split("/").nth(1).unwrap(); + let coll = k.split('/').nth(1).unwrap(); collections.insert(coll.to_string()); } Ok(collections.into_iter().collect()) @@ -216,16 +215,16 @@ impl RepoStore { })?; self.db .alias(did.as_bytes().to_vec(), Some(&Cid::from_str(&commit_cid)?))?; - Ok(commit_cid.to_string()) + Ok(commit_cid) } pub fn mst_from_map(&mut self, map: &BTreeMap) -> Result { // TODO: not unwrap in iter - let mut cid_map: BTreeMap = BTreeMap::from_iter( + let cid_map: BTreeMap = BTreeMap::from_iter( map.iter() - .map(|(k, v)| (k.to_string(), Cid::from_str(&v).unwrap())), + .map(|(k, v)| (k.to_string(), Cid::from_str(v).unwrap())), ); - let mst_cid = generate_mst(&mut self.db, &mut cid_map)?; + let mst_cid = generate_mst(&mut self.db, &cid_map)?; Ok(mst_cid.to_string()) } @@ -237,7 +236,7 @@ impl RepoStore { Ok(cid_map) } - pub fn update_mst(&mut self, mst_cid: &str, mutations: &Vec) -> Result { + pub fn update_mst(&mut self, mst_cid: &str, mutations: &[Mutation]) -> Result { let mut cid_map = self.mst_to_cid_map(mst_cid)?; for m in mutations.iter() { match m { @@ -254,7 +253,7 @@ impl RepoStore { } } } - let mst_cid = generate_mst(&mut self.db, &mut cid_map)?; + let mst_cid = generate_mst(&mut self.db, &cid_map)?; Ok(mst_cid.to_string()) } diff --git a/adenosine-pds/src/ucan_p256.rs b/adenosine-pds/src/ucan_p256.rs index 21e8a9a..b8b6cd2 100644 --- a/adenosine-pds/src/ucan_p256.rs +++ b/adenosine-pds/src/ucan_p256.rs @@ -11,11 +11,6 @@ use ucan::crypto::KeyMaterial; pub use ucan::crypto::{did::P256_MAGIC_BYTES, JwtSignatureAlgorithm}; -pub fn bytes_to_p256_key(bytes: Vec) -> Result> { - let public_key = P256PublicKey::try_from(bytes.as_slice())?; - Ok(Box::new(P256KeyMaterial(public_key, None))) -} - #[derive(Clone)] pub struct P256KeyMaterial(pub P256PublicKey, pub Option); @@ -27,11 +22,7 @@ impl KeyMaterial for P256KeyMaterial { } async fn get_did(&self) -> Result { - let bytes = [ - P256_MAGIC_BYTES, - &self.0.to_encoded_point(true).to_bytes().to_vec(), - ] - .concat(); + let bytes = [P256_MAGIC_BYTES, &self.0.to_encoded_point(true).to_bytes()].concat(); Ok(format!("did:key:z{}", bs58::encode(bytes).into_string())) } @@ -55,8 +46,7 @@ impl KeyMaterial for P256KeyMaterial { #[cfg(test)] mod tests { - use super::{bytes_to_p256_key, P256KeyMaterial, P256_MAGIC_BYTES}; - use p256::ecdsa::signature::{Signer, Verifier}; + use super::{P256KeyMaterial, Result, P256_MAGIC_BYTES}; use p256::ecdsa::{SigningKey as P256PrivateKey, VerifyingKey as P256PublicKey}; use ucan::{ builder::UcanBuilder, @@ -64,6 +54,11 @@ mod tests { ucan::Ucan, }; + pub fn bytes_to_p256_key(bytes: Vec) -> Result> { + let public_key = P256PublicKey::try_from(bytes.as_slice())?; + Ok(Box::new(P256KeyMaterial(public_key, None))) + } + #[cfg_attr(not(target_arch = "wasm32"), tokio::test)] async fn it_can_sign_and_verify_a_ucan() { let private_key = P256PrivateKey::random(&mut p256::elliptic_curve::rand_core::OsRng); -- cgit v1.2.3