Skip to content

Generate ztm certificates #406

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
May 29, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -55,4 +55,5 @@ colored = "2.1.0"
idgenerator = "2.0.0"
num_cpus = "1.16.0"
config = "0.14.0"
shadow-rs = "0.28.0"
shadow-rs = "0.28.0"
reqwest = "0.12.4"
25 changes: 18 additions & 7 deletions common/src/config.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
use std::path::PathBuf;
use c::{ConfigError, FileFormat};
use config as c;
use serde::{Deserialize, Serialize};

use std::path::PathBuf;

#[derive(Serialize, Deserialize, Debug, Default, Clone)]
pub struct Config {
Expand All @@ -12,6 +11,7 @@ pub struct Config {
pub storage: StorageConfig,
pub monorepo: MonoConfig,
pub pack: PackConfig,
pub relay: RelayConfig,
}

impl Config {
Expand All @@ -26,11 +26,8 @@ impl Config {
// config.get::<Self>(env!("CARGO_PKG_NAME"))
config.try_deserialize::<Config>()
}

}



#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct LogConfig {
pub log_path: PathBuf,
Expand Down Expand Up @@ -120,7 +117,6 @@ impl Default for MonoConfig {
}
}


#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct PackConfig {
pub pack_decode_mem_size: usize,
Expand All @@ -138,4 +134,19 @@ impl Default for PackConfig {
channel_message_size: 1_000_000,
}
}
}
}

#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct RelayConfig {
pub ca: String,
pub hub: String,
}

impl Default for RelayConfig {
fn default() -> Self {
Self {
ca: String::from("127.0.0.1:9999"),
hub: String::from("127.0.0.1:8888"),
}
}
}
10 changes: 7 additions & 3 deletions gateway/src/relay_server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,8 @@ use axum::routing::get;
use axum::Router;
use clap::Args;
use common::config::Config;
use common::model::{CommonOptions, GetParams};
use common::model::CommonOptions;
use gemini::RelayGetParams;
use jupiter::context::Context;
use regex::Regex;
use tower::ServiceBuilder;
Expand Down Expand Up @@ -83,12 +84,15 @@ pub async fn app(config: Config, host: String, port: u16) -> Router {
}

async fn get_method_router(
_state: State<AppState>,
Query(params): Query<GetParams>,
state: State<AppState>,
Query(params): Query<RelayGetParams>,
uri: Uri,
) -> Result<Response<Body>, (StatusCode, String)> {
let relay_config = state.context.config.relay.clone();
if Regex::new(r"/hello$").unwrap().is_match(uri.path()) {
return gemini::http::handler::hello_gemini(params).await;
} else if Regex::new(r"/certificate$").unwrap().is_match(uri.path()) {
return gemini::ztm::handler::get_ztm_certificate(relay_config, params).await;
}
Err((
StatusCode::NOT_FOUND,
Expand Down
6 changes: 5 additions & 1 deletion gemini/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -12,4 +12,8 @@ path = "src/lib.rs"

[dependencies]
common = { workspace = true }
axum = { workspace = true }
axum = { workspace = true }
serde = { workspace = true }
serde_json = { workspace = true }
reqwest = { workspace = true }
tracing = { workspace = true }
5 changes: 3 additions & 2 deletions gemini/src/http/handler.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,10 @@ use axum::{
body::Body,
http::{Response, StatusCode},
};
use common::model::GetParams;

pub async fn hello_gemini(_params: GetParams) -> Result<Response<Body>, (StatusCode, String)> {
use crate::RelayGetParams;

pub async fn hello_gemini(_params: RelayGetParams) -> Result<Response<Body>, (StatusCode, String)> {
Ok(Response::builder()
.body(Body::from("hello gemini"))
.unwrap())
Expand Down
8 changes: 8 additions & 0 deletions gemini/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1 +1,9 @@
use serde::Deserialize;

pub mod http;
pub mod ztm;

#[derive(Deserialize, Debug)]
pub struct RelayGetParams {
pub name: Option<String>,
}
91 changes: 91 additions & 0 deletions gemini/src/ztm/handler.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
use axum::{
body::Body,
http::{Response, StatusCode},
};
use common::config::RelayConfig;
use reqwest::Client;

use crate::RelayGetParams;

use super::{Agent, ZTMUserPermit};

pub async fn get_ztm_certificate(
config: RelayConfig,
params: RelayGetParams,
) -> Result<Response<Body>, (StatusCode, String)> {
if params.name.is_none() {
return Err((StatusCode::BAD_REQUEST, "not enough paras".to_string()));
}
let name = params.name.unwrap();
let ca_address = config.ca;
let hub_address = config.hub;

//1. GET {ca}/api/certificates/ca -> ca certificate
let url = format!("http://{ca_address}/api/certificates/ca");
let request_result = reqwest::get(url).await;
let ca_certificate = match handle_ztm_response(request_result).await {
Ok(s) => s,
Err(s) => {
return Err((StatusCode::INTERNAL_SERVER_ERROR, s));
}
};

//2. POST {ca}/api/certificates/{username} -> user private key
let url = format!("http://{ca_address}/api/certificates/{name}");
let client = Client::new();
let request_result = client.post(url).send().await;
let user_key = match handle_ztm_response(request_result).await {
Ok(s) => s,
Err(s) => {
return Err((StatusCode::INTERNAL_SERVER_ERROR, s));
}
};

//3. GET {ca}/api/certificates/{username} -> user certificate
let url = format!("http://{ca_address}/api/certificates/{name}");
let request_result = reqwest::get(url).await;
let user_certificate = match handle_ztm_response(request_result).await {
Ok(s) => s,
Err(s) => {
return Err((StatusCode::INTERNAL_SERVER_ERROR, s));
}
};

// Combine those into a json permit
let agent = Agent {
certificate: user_certificate.clone(),
private_key: user_key.clone(),
};

let permit = ZTMUserPermit {
ca: ca_certificate.clone(),
agent,
bootstraps: vec![hub_address],
};

let permit_json = serde_json::to_string(&permit).unwrap();
tracing::info!("new permit [{name}]: {permit_json}");

Ok(Response::builder()
.header("Content-Type", "application/json")
.body(Body::from(permit_json))
.unwrap())
}

pub async fn handle_ztm_response(
request_result: Result<reqwest::Response, reqwest::Error>,
) -> Result<String, String> {
match request_result {
Ok(res) => {
if res.status().is_success() {
Ok(res.text().await.unwrap())
} else {
Err(res.text().await.unwrap())
}
}
Err(e) => Err(e.to_string()),
}
}

#[cfg(test)]
mod tests {}
16 changes: 16 additions & 0 deletions gemini/src/ztm/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
use serde::{Deserialize, Serialize};

pub mod handler;

#[derive(Deserialize, Serialize, Debug)]
pub struct ZTMUserPermit {
pub ca: String,
pub agent: Agent,
pub bootstraps: Vec<String>,
}

#[derive(Deserialize, Serialize, Debug)]
pub struct Agent {
pub certificate: String,
pub private_key: String,
}
2 changes: 1 addition & 1 deletion libra/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ sha1 = { workspace = true }
bytes = { workspace = true }
chrono = { workspace = true }
futures = { workspace = true }
reqwest = { version = "0.12.4", features = ["stream"] }
reqwest = { workspace = true, features = ["stream"] }
tokio-util = { version = "0.7.11", features = ["io"] }
color-backtrace = "0.6.1"
colored = "2.1.0"
Expand Down
7 changes: 6 additions & 1 deletion mega/config.toml
Original file line number Diff line number Diff line change
Expand Up @@ -66,4 +66,9 @@ pack_decode_cache_path = "/tmp/.mega/cache"
clean_cache_after_decode = true

# The maximum meesage size in channel buffer while decode
channel_message_size = 1_000_000
channel_message_size = 1_000_000


[relay]
ca = "127.0.0.1:9999"
hub = "127.0.0.1:8888"
Loading