#![cfg(all(feature = "gateway", unix))]
use std::io::{BufRead, BufReader, Read, Write};
use std::net::{TcpListener, TcpStream};
use std::process::{Command, Stdio};
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
use encore::gateway::{
self, async_trait, Completed, ContinueExt as _, Decision, HeaderEdit, HookError, Hooks,
Middleware, RequestExt as _, RequestId, RequestView, ResponseExt as _, ResponseView, State,
};
use encore::ErrCode;
const LOG_ENV: &str = "ENCORE_GATEWAY_TEST_LOG";
struct Auth {
users: State<String>,
log: Mutex<std::fs::File>,
}
#[async_trait]
impl Middleware for Auth {
async fn on_request(&self, req: &RequestView) -> Result<Decision, HookError> {
let Some(user) = req
.header("authorization")
.and_then(|v| v.strip_prefix("Bearer "))
else {
return Ok(gateway::reject(ErrCode::Unauthenticated, "missing token"));
};
match req.path_param("id") {
Some("slow") => {
self.users.insert(req.id, user.to_string());
tokio::time::sleep(Duration::from_secs(5)).await;
}
Some("moved") => return Ok(gateway::respond(308, [("location", "/users/7")], "")),
Some("broken") => return Err(HookError::failed("the token store is down")),
_ => {}
}
self.users.insert(req.id, user.to_string());
let theme = req.cookie("theme").unwrap_or("none").to_string();
Ok(gateway::proceed()
.set_header("x-user", user)
.set_header("x-theme", theme)
.attribute("user.id", user)
.into())
}
async fn on_response(
&self,
req: RequestId,
resp: &ResponseView,
) -> Result<Vec<HeaderEdit>, HookError> {
Ok(vec![
HeaderEdit::Set {
name: "x-authenticated-as".into(),
value: self.users.get(req).unwrap_or_default(),
},
HeaderEdit::Set {
name: "x-upstream-type".into(),
value: resp.header("content-type").unwrap_or("none").into(),
},
])
}
fn on_complete(&self, done: &Completed) {
let line = serde_json::json!({
"path": done.request.path,
"status": done.status,
"rejected_by": done.rejected_by,
"user": self.users.get(done.request.id),
});
writeln!(self.log.lock().unwrap(), "{line}").unwrap();
}
fn on_finish(&self, req: RequestId) {
self.users.remove(req);
}
}
#[test]
fn program() {
let Ok(log) = std::env::var(LOG_ENV) else {
return;
};
let file = || std::fs::OpenOptions::new().append(true).open(&log).unwrap();
let auth = Auth {
users: State::new(),
log: Mutex::new(file()),
};
let rt = tokio::runtime::Runtime::new().unwrap();
rt.block_on(async {
gateway::serve([gateway::register(
"auth",
Hooks::REQUEST | Hooks::RESPONSE | Hooks::COMPLETE,
auth,
)
.timeout(Duration::from_millis(500))])
.await
.unwrap();
});
writeln!(file(), "{}", serde_json::json!({"stopped": true})).unwrap();
std::thread::sleep(Duration::from_secs(30));
}
#[derive(Debug, Clone)]
struct Seen {
head: String,
}
fn proxy(seen: Arc<Mutex<Vec<Seen>>>) -> String {
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
let addr = listener.local_addr().unwrap();
std::thread::spawn(move || {
for stream in listener.incoming() {
let Ok(mut stream) = stream else { continue };
let seen = seen.clone();
std::thread::spawn(move || loop {
let Some((head, _)) = read_message(&mut stream) else {
return;
};
seen.lock().unwrap().push(Seen { head });
let body = "hello from users";
let _ = write!(
stream,
"HTTP/1.1 200 OK\r\ncontent-type: text/plain\r\ncontent-length: {}\r\n\r\n{body}",
body.len()
);
});
}
});
format!("http://{addr}")
}
fn read_message(stream: &mut TcpStream) -> Option<(String, Vec<u8>)> {
let mut reader = BufReader::new(stream.try_clone().ok()?);
let mut head = String::new();
loop {
let mut line = String::new();
if reader.read_line(&mut line).ok()? == 0 {
return None;
}
if line == "\r\n" {
break;
}
head.push_str(&line.to_ascii_lowercase());
}
let length = head
.lines()
.find_map(|l| l.strip_prefix("content-length:"))
.map_or(0, |v| v.trim().parse().unwrap());
let mut body = vec![0; length];
reader.read_exact(&mut body).ok()?;
Some((head, body))
}
fn get(port: u16, path: &str, headers: &[(&str, &str)]) -> (u16, String, String) {
let mut stream = TcpStream::connect(("127.0.0.1", port)).unwrap();
stream
.set_read_timeout(Some(Duration::from_secs(10)))
.unwrap();
let mut req = format!("GET {path} HTTP/1.1\r\nhost: localhost\r\nconnection: close\r\n");
for (n, v) in headers {
req.push_str(&format!("{n}: {v}\r\n"));
}
req.push_str("\r\n");
stream.write_all(req.as_bytes()).unwrap();
let mut answer = String::new();
stream.read_to_string(&mut answer).unwrap();
let (head, body) = answer.split_once("\r\n\r\n").unwrap();
let status = head.split(' ').nth(1).unwrap().parse().unwrap();
(status, head.to_ascii_lowercase(), body.to_string())
}
fn runtime_config(proxy: &str) -> String {
serde_json::json!({
"environment": {
"app_id": "test-app", "app_slug": "test-app", "env_id": "test-env",
"env_name": "test", "env_type": "development", "cloud": "local",
},
"deployment": {
"deploy_id": "test-deploy",
"hosted_services": [{"name": "edge"}],
"hosted_gateways": ["edge"],
"service_discovery": {"services": {"users": {"base_url": format!("{proxy}/users")}}},
},
"infra": {"resources": {"gateways": [{
"rid": "gw:edge",
"encore_name": "edge",
"routes": [{"path": "/users/{id}", "methods": ["GET"], "service": "users"}],
}]}},
})
.to_string()
}
#[test]
fn a_gateway_program_serves_middleware_implementing_the_cores_trait() {
if std::env::var(LOG_ENV).is_ok() {
return;
}
let seen = Arc::new(Mutex::new(Vec::new()));
let proxy = proxy(seen.clone());
let port = TcpListener::bind("127.0.0.1:0")
.unwrap()
.local_addr()
.unwrap()
.port();
let dir = tempfile_dir();
let log = dir.join("completed.jsonl");
std::fs::write(&log, "").unwrap();
let mut child = Command::new(std::env::current_exe().unwrap())
.args(["program", "--exact", "--nocapture", "--test-threads=1"])
.env(LOG_ENV, &log)
.env("ENCORE_RUNTIME_CONFIG", runtime_config(&proxy))
.env("ENCORE_GATEWAY_LISTEN", format!("tcp:127.0.0.1:{port}"))
.stdout(Stdio::null())
.spawn()
.unwrap();
let deadline = Instant::now() + Duration::from_secs(30);
while TcpStream::connect(("127.0.0.1", port)).is_err() {
assert!(child.try_wait().unwrap().is_none(), "the program exited");
assert!(Instant::now() < deadline, "the program never listened");
std::thread::sleep(Duration::from_millis(50));
}
let (status, _, body) = get(port, "/users/7", &[]);
assert_eq!(status, 401, "{body}");
assert!(body.contains("\"unauthenticated\""), "{body}");
assert!(seen.lock().unwrap().is_empty());
let (status, head, body) = get(
port,
"/users/7",
&[
("authorization", "Bearer ada"),
("cookie", "session=abc; theme=\"dark\""),
],
);
assert_eq!((status, body.as_str()), (200, "hello from users"));
assert!(head.contains("x-authenticated-as: ada"), "{head}");
assert!(head.contains("x-upstream-type: text/plain"), "{head}");
let forwarded = seen.lock().unwrap()[0].head.clone();
assert!(forwarded.contains("x-user: ada"), "{forwarded}");
assert!(forwarded.contains("x-theme: dark"), "{forwarded}");
let (status, head, _) = get(port, "/users/moved", &[("authorization", "Bearer ada")]);
assert_eq!(status, 308);
assert!(head.contains("location: /users/7"), "{head}");
let (status, _, body) = get(port, "/users/slow", &[("authorization", "Bearer eve")]);
assert_eq!(status, 503, "{body}");
let (status, _, _) = get(port, "/users/broken", &[("authorization", "Bearer eve")]);
assert_eq!(status, 500);
assert_eq!(seen.lock().unwrap().len(), 1);
let killed = Command::new("kill")
.args(["-TERM", &child.id().to_string()])
.status()
.unwrap();
assert!(killed.success());
let deadline = Instant::now() + Duration::from_secs(20);
let status = loop {
if let Some(status) = child.try_wait().unwrap() {
break status;
}
if Instant::now() > deadline {
child.kill().unwrap();
panic!("the program did not exit after SIGTERM");
}
std::thread::sleep(Duration::from_millis(20));
};
assert!(status.success(), "{status:?}");
let lines: Vec<serde_json::Value> = std::fs::read_to_string(&log)
.unwrap()
.lines()
.map(|l| serde_json::from_str(l).unwrap())
.collect();
let line = |path: &str, user: serde_json::Value| {
lines
.iter()
.find(|l| l["path"] == path && l["user"] == user)
.unwrap_or_else(|| panic!("no completion of {path} for {user}: {lines:?}"))
};
assert_eq!(
line("/users/7", serde_json::Value::Null)["rejected_by"],
"auth"
);
assert_eq!(line("/users/7", "ada".into())["status"], 200);
assert_eq!(line("/users/moved", serde_json::Value::Null)["status"], 308);
assert_eq!(
line("/users/broken", serde_json::Value::Null)["status"],
500
);
assert_eq!(lines.last().unwrap(), &serde_json::json!({"stopped": true}));
}
fn tempfile_dir() -> std::path::PathBuf {
let dir = std::env::temp_dir().join(format!("encore-gateway-test-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
dir
}