-
-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathapi.rs
128 lines (112 loc) · 3.51 KB
/
api.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
use actix_web::{get, web, HttpResponse, Responder};
use anyhow::Result;
use regex::Regex;
use serde::{Deserialize, Serialize};
use crate::auth::{Auth, CfWorkerStore};
use crate::state::State;
#[get("/api/status")]
pub async fn api_status() -> impl Responder {
let status = ApiStatus {
tunnels_count: 0,
tunels: "kaichao".to_string(),
};
HttpResponse::Ok().json(status)
}
/// Request proxy endpoint
#[get("/{endpoint}")]
pub async fn request_endpoint(
endpoint: web::Path<String>,
info: web::Query<AuthInfo>,
state: web::Data<State>,
) -> impl Responder {
log::debug!("Request proxy endpoint, {}", endpoint);
log::debug!("Require auth: {}", state.require_auth);
match validate_endpoint(&endpoint) {
Ok(true) => (),
Ok(false) => {
return HttpResponse::BadRequest().body(
"Request subdomain is invalid, only chars in lowercase and numbers are allowed",
)
}
Err(err) => {
return HttpResponse::InternalServerError().body(format!("Server Error: {:?}", err))
}
}
if state.require_auth {
let credential = match info.credential.clone() {
Some(val) => val,
None => {
return HttpResponse::BadRequest().body("Request Error: credential param is empty.")
}
};
match CfWorkerStore
.credential_is_valid(&credential, &endpoint)
.await
{
Ok(true) => (),
Ok(false) => {
return HttpResponse::BadRequest()
.body("Error: credential is not valid.".to_string())
}
Err(err) => {
log::error!("Server error: {:?}", err);
return HttpResponse::InternalServerError()
.body(format!("Server Error: {:?}", err));
}
};
}
let mut manager = state.manager.lock().await;
match manager.put(endpoint.to_string()).await {
Ok(port) => {
let schema = if state.secure { "https" } else { "http" };
let info = ProxyInfo {
id: endpoint.to_string(),
port,
max_conn_count: state.max_sockets,
url: format!("{}://{}.{}", schema, endpoint, state.domain),
};
log::debug!("Proxy info, {:?}", info);
HttpResponse::Ok().json(info)
}
Err(e) => {
log::error!("Client manager failed to put proxy endpoint: {:?}", e);
HttpResponse::InternalServerError().body(format!("Error: {:?}", e))
}
}
}
fn validate_endpoint(endpoint: &str) -> Result<bool> {
// Don't allow A-Z uppercase since it will convert to lowercase in browser
let re = Regex::new("^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$")?;
Ok(re.is_match(endpoint))
}
#[derive(Debug, Deserialize)]
pub struct AuthInfo {
credential: Option<String>,
}
#[derive(Debug, Serialize, Deserialize)]
struct ApiStatus {
tunnels_count: u16,
tunels: String,
}
#[derive(Debug, Serialize, Deserialize)]
struct ProxyInfo {
id: String,
port: u16,
max_conn_count: u8,
url: String,
}
#[cfg(test)]
mod tests {
use crate::api::validate_endpoint;
#[test]
fn validate_endpoint_works() {
let endpoints = [
"demo",
"123",
"did-key-zq3shkkuzlvqefghdgzgfmux8vgkgvwsla83w2oekhzxocw2n",
];
for endpoint in endpoints {
assert!(validate_endpoint(endpoint).unwrap());
}
}
}