Skip to content

Commit

Permalink
feat: convert auth client to access client
Browse files Browse the repository at this point in the history
  • Loading branch information
Ma233 committed Aug 19, 2024
1 parent c710a80 commit b498daf
Show file tree
Hide file tree
Showing 8 changed files with 188 additions and 68 deletions.
42 changes: 31 additions & 11 deletions Cargo.lock

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

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ edition = "2021"

[dependencies]
async-trait = "0.1.81"
axum = "0.7.5"
clap = "4.5.4"
futures = "0.3.30"
hex = "0.4.3"
Expand Down
7 changes: 7 additions & 0 deletions proto/command_v1.proto
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,15 @@ message ConnectRelayResponse {
string relaied_multiaddr = 1;
}

message ExpirePeerAccessRequest {
string peer_id = 1;
}

message ExpirePeerAccessResponse {}

service CommandService {
rpc AddPeer(AddPeerRequest) returns (AddPeerResponse);
rpc CreateTunnelServer(CreateTunnelServerRequest) returns (CreateTunnelServerResponse);
rpc ConnectRelay(ConnectRelayRequest) returns (ConnectRelayResponse);
rpc ExpirePeerAccess(ExpirePeerAccessRequest) returns (ExpirePeerAccessResponse);
}
80 changes: 80 additions & 0 deletions src/access.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
use std::collections::HashMap;
use std::time::Duration;
use std::time::Instant;

use libp2p::PeerId;
use serde::Deserialize;

const ACCESS_TTL: Duration = Duration::from_secs(10 * 60);

pub struct AccessClient {
local_id: libp2p::PeerId,
endpoint: reqwest::Url,
client: reqwest::Client,
cache: HashMap<PeerId, (bool, Instant)>,
}

#[derive(Deserialize)]
struct AccessClientResponse {
data: bool,
}

impl AccessClient {
pub fn new(local_id: libp2p::PeerId, endpoint: reqwest::Url) -> AccessClient {
AccessClient {
local_id,
endpoint,
client: reqwest::Client::new(),
cache: HashMap::default(),
}
}

async fn request_endpoint(&mut self, peer: &PeerId) -> Result<bool, reqwest::Error> {
let url = self.endpoint.join("access-control").unwrap();
let params = [
("device", self.local_id.to_string()),
("token", peer.to_string()),
];

let response = self
.client
.get(url)
.query(&params)
.send()
.await?
.json::<AccessClientResponse>()
.await?;

Ok(response.data)
}

pub async fn is_valid(&mut self, peer: &PeerId) -> bool {
self.cache
.retain(|_, (_, created)| created.elapsed() < ACCESS_TTL);

if let Some((valid, _)) = self.cache.get(peer) {
return *valid;
}

match self.request_endpoint(peer).await {
Err(e) => {
tracing::error!(
"error while requesting access endpoint (will return false) for {}: {}",
peer,
e
);
false
}

Ok(valid) => {
self.cache.insert(*peer, (valid, Instant::now()));
valid
}
}
}

pub fn expire(&mut self, token: &PeerId) {
tracing::debug!("expire token: {} from cache", token);
self.cache.remove(token);
}
}
41 changes: 0 additions & 41 deletions src/auth.rs

This file was deleted.

13 changes: 13 additions & 0 deletions src/command.rs
Original file line number Diff line number Diff line change
Expand Up @@ -63,4 +63,17 @@ impl proto::command_service_server::CommandService for PProxyCommander {
.map(Response::new)
.map_err(|e| tonic::Status::internal(format!("{:?}", e)))
}

async fn expire_peer_access(
&self,
request: tonic::Request<proto::ExpirePeerAccessRequest>,
) -> std::result::Result<tonic::Response<proto::ExpirePeerAccessResponse>, tonic::Status> {
tracing::debug!("handle request: {:?}", request);

self.handle
.expire_peer_access(request.into_inner())
.await
.map(Response::new)
.map_err(|e| tonic::Status::internal(format!("{:?}", e)))
}
}
Loading

0 comments on commit b498daf

Please sign in to comment.