Skip to content

Commit

Permalink
feat: a bunch more client work
Browse files Browse the repository at this point in the history
  • Loading branch information
sstelfox committed Feb 18, 2024
1 parent 5719638 commit 79396c8
Show file tree
Hide file tree
Showing 14 changed files with 84 additions and 80 deletions.
1 change: 1 addition & 0 deletions Cargo.lock

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

3 changes: 2 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ edition = "2021"

[features]
default = ["banyan-api", "pem", "strict", "tomb-compat"]
banyan-api = ["reqwest", "serde", "serde_json"]
banyan-api = ["reqwest", "serde", "serde_json", "url"]
pem = ["p384/pem", "p384/pkcs8"]
strict = []
tomb-compat = ["banyan-api"]
Expand Down Expand Up @@ -49,6 +49,7 @@ reqwest = { version = "^0.11", default-features = false, optional = true, featur
] }
serde = { version = "^1", features = ["derive"], optional = true }
serde_json = { version = "^1", optional = true }
url = { version = "^2", optional = true }

[[bin]]
name = "banyanfs"
Expand Down
2 changes: 2 additions & 0 deletions build.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
#![allow(clippy::vec_init_then_push)]

use time::format_description::well_known::Rfc3339;
use time::OffsetDateTime;

Expand Down
5 changes: 5 additions & 0 deletions src/api/client/auth.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
#![allow(dead_code)]
#![allow(unused_imports)]
#![allow(unused_variables)]


88 changes: 52 additions & 36 deletions src/api/api_client.rs → src/api/client/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,69 +2,75 @@
#![allow(unused_imports)]
#![allow(unused_variables)]

mod auth;
mod traits;

pub(crate) use traits::{ApiRequestTrait, ApiResponseTrait};

use std::collections::BTreeMap;
use std::sync::Arc;

use async_std::sync::RwLock;
use reqwest::header::{HeaderMap, HeaderValue};
use reqwest::{Client, Method, Response, Url};
use serde::de::DeserializeOwned;
use reqwest::{Client as RClient, Method, Response, Url};
use serde::{Deserialize, Serialize};
use time::OffsetDateTime;
use zeroize::{Zeroize, ZeroizeOnDrop};

use crate::codec::crypto::SigningKey;

const PLATFORM_AUDIENCE: &str = "banyan-platform";

pub(crate) trait ApiRequestTrait {
type Response: ApiResponseTrait + DeserializeOwned;

fn requires_auth(&self) -> bool;
}

pub(crate) trait ApiResponseTrait: Sized {
fn from_response(response: Response) -> Result<Self, ApiError>;
}
pub(crate) const PLATFORM_AUDIENCE: &str = "banyan-platform";

#[derive(Clone)]
pub struct ApiClient {
auth: Option<ApiAuth>,
base_url: Url,
client: Client,
client: RClient,
}

impl ApiClient {
pub(crate) async fn call<T>(&self, request: &T) -> Result<T::Response, ApiError>
where
T: ApiRequestTrait,
{
todo!()
}
pub fn anonymous(base_url: &str) -> Result<Self, ApiClientError> {
let client = default_reqwest_client()?;
let base_url = Url::parse(base_url)?;

pub fn new(base_url: Url) -> Self {
Self {
Ok(Self {
auth: None,
base_url,
client: default_reqwest_client(),
}
client,
})
}

pub fn with_auth(base_url: Url, account_id: String, key: Arc<SigningKey>) -> Self {
pub fn authenticated(
base_url: &str,
account_id: &str,
key: Arc<SigningKey>,
) -> Result<Self, ApiClientError> {
let base_url = Url::parse(base_url)?;
let auth = Some(ApiAuth::new(account_id, key));
let client = default_reqwest_client()?;

Self {
Ok(Self {
auth,
base_url,
client: default_reqwest_client(),
}
client,
})
}

pub(crate) async fn call<T>(&self, request: &T) -> Result<T::Response, ApiError>
where
T: ApiRequestTrait,
{
todo!()
}
}

fn default_reqwest_client() -> Client {
fn default_reqwest_client() -> Result<RClient, ApiClientError> {
let mut default_headers = HeaderMap::new();
default_headers.insert("Content-Type", HeaderValue::from_static("application/json"));

let client = RClient::builder()
.default_headers(default_headers)
.build()?;

todo!()
}

Expand All @@ -78,7 +84,12 @@ pub(crate) struct ApiAuth {
}

impl ApiAuth {
pub fn new(account_id: String, key: Arc<SigningKey>) -> Self {
async fn core_token(&self) -> Result<String, CoreTokenError> {
self.core_token.get(&self.account_id, &self.key).await
}

pub fn new(account_id: impl Into<String>, key: Arc<SigningKey>) -> Self {
let account_id = account_id.into();
let core_token = CoreToken::default();
let storage_tokens = StorageTokens::default();

Expand All @@ -91,10 +102,6 @@ impl ApiAuth {
}
}

async fn core_token(&self) -> Result<String, CoreTokenError> {
self.core_token.get(&self.account_id, &self.key).await
}

async fn storage_token(&self, host: &str) -> Result<String, StorageTokenError> {
self.storage_tokens
.get(host, &self.account_id, &self.key)
Expand Down Expand Up @@ -189,7 +196,16 @@ pub struct ApiError {
}

#[derive(Debug, Deserialize)]
pub struct RawApiError {
pub(crate) struct RawApiError {
#[serde(rename = "msg")]
pub message: String,
}

#[derive(Debug, thiserror::Error)]
pub enum ApiClientError {
#[error("provided URL wasn't valid: {0}")]
BadUrl(#[from] url::ParseError),

#[error("underlying HTTP client error: {0}")]
Reqwest(#[from] reqwest::Error),
}
11 changes: 11 additions & 0 deletions src/api/client/traits.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
#![allow(dead_code)]
#![allow(unused_imports)]
#![allow(unused_variables)]

use serde::de::DeserializeOwned;

pub(crate) trait ApiRequestTrait {
type Response: ApiResponseTrait + DeserializeOwned;
}

pub(crate) trait ApiResponseTrait: Sized {}
4 changes: 2 additions & 2 deletions src/api/mod.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
mod api_client;
mod client;

pub use api_client::ApiClient;
pub use client::ApiClient;
1 change: 0 additions & 1 deletion src/codec/crypto/verifying_key.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ use std::ops::Deref;
use async_trait::async_trait;
use ecdsa::signature::rand_core::CryptoRngCore;
use elliptic_curve::pkcs8::EncodePublicKey;
use elliptic_curve::sec1::{FromEncodedPoint, ToEncodedPoint};
use futures::{AsyncWrite, AsyncWriteExt};
use nom::bytes::streaming::take;
use nom::error::ErrorKind;
Expand Down
20 changes: 0 additions & 20 deletions src/codec/header/encrypted_content_payload_entry.rs

This file was deleted.

2 changes: 0 additions & 2 deletions src/codec/header/mod.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
mod content_options;
mod data_header;
mod encrypted_content_payload_entry;
mod format_header;
mod identity_header;
mod key_access_settings;
Expand All @@ -10,7 +9,6 @@ mod public_settings;

pub use content_options::ContentOptions;
pub use data_header::DataHeader;
pub use encrypted_content_payload_entry::EncryptedContentPayloadEntry;
pub use format_header::FormatHeader;
pub use identity_header::IdentityHeader;
pub use key_access_settings::{KeyAccessSettings, KeyAccessSettingsBuilder};
Expand Down
2 changes: 1 addition & 1 deletion src/filesystem/drive/access.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use std::io::{Error as StdError, ErrorKind as StdErrorKind};
use elliptic_curve::rand_core::CryptoRngCore;
use futures::io::{AsyncWrite, AsyncWriteExt};

use crate::codec::crypto::{AccessKey, Nonce, VerifyingKey};
use crate::codec::crypto::{AccessKey, VerifyingKey};
use crate::codec::header::KeyAccessSettings;
use crate::codec::{ActorId, ActorSettings, AsyncEncodable};

Expand Down
13 changes: 5 additions & 8 deletions src/filesystem/drive/file_handle.rs
Original file line number Diff line number Diff line change
@@ -1,19 +1,16 @@
use std::sync::Arc;

use async_std::sync::RwLock;
use elliptic_curve::rand_core::CryptoRngCore;
use tracing::{debug, instrument, trace, Instrument, Level};

use crate::codec::*;
use crate::filesystem::nodes::{Node, NodeId, NodeKind};
use crate::filesystem::nodes::NodeId;

use crate::codec::crypto::SigningKey;
use crate::filesystem::drive::{InnerDrive, WalkState};
use crate::filesystem::drive::InnerDrive;

pub struct FileHandle {
current_key: Arc<SigningKey>,
node_id: NodeId,
inner: Arc<RwLock<InnerDrive>>,
_current_key: Arc<SigningKey>,
_node_id: NodeId,
_inner: Arc<RwLock<InnerDrive>>,
}

impl FileHandle {}
2 changes: 1 addition & 1 deletion src/filesystem/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ pub mod nodes;

pub(crate) use content_reference::ContentReference;
pub(crate) use file_content::FileContent;
pub(crate) use nodes::NodeBuilder;
pub use nodes::{Node, NodeName};
pub(crate) use nodes::{NodeBuilder, NodeBuilderError};

pub use drive::{DirectoryHandle, Drive, DriveAccess, DriveLoader, DriveLoaderError, FileHandle};
10 changes: 2 additions & 8 deletions src/wasm/tomb_compat/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@ pub use wasm_snapshot::WasmSnapshot;

use std::sync::Arc;

use reqwest::Url;
use tracing::debug;
use wasm_bindgen::prelude::*;
use zeroize::Zeroize;
Expand Down Expand Up @@ -137,14 +136,9 @@ impl TombCompat {
};
private_key_pem.zeroize();

let api_endpoint = match reqwest::Url::parse(&api_endpoint) {
Ok(url) => url,
Err(e) => panic!("Failed to parse api endpoint: {}", e),
};

let client = ApiClient::with_auth(api_endpoint, account_id, key.clone());
let client = ApiClient::authenticated(&api_endpoint, &account_id, key.clone()).unwrap();

debug!(key_id = ?key.key_id(), "initialized new TombWasm instance");
debug!(account_id, key_id = ?key.key_id(), "initialized new TombWasm instance");

Self { client, key }
}
Expand Down

0 comments on commit 79396c8

Please sign in to comment.