use async_trait::async_trait;
use clap::Parser;
use pingora_core::modules::http::HttpModules;
use pingora_core::server::configuration::Opt;
use pingora_core::server::Server;
use pingora_core::upstreams::peer::HttpPeer;
use pingora_core::Result;
use pingora_http::RequestHeader;
use pingora_proxy::{ProxyHttp, Session};
mod my_acl {
use super::*;
use pingora_core::modules::http::{HttpModule, HttpModuleBuilder, Module};
use pingora_error::{Error, ErrorType::HTTPStatus};
use std::any::Any;
struct MyAclCtx {
credential_header: String,
}
#[async_trait]
impl HttpModule for MyAclCtx {
async fn request_header_filter(&mut self, req: &mut RequestHeader) -> Result<()> {
let Some(auth) = req.headers.get(http::header::AUTHORIZATION) else {
return Error::e_explain(HTTPStatus(403), "Auth failed, no auth header");
};
if auth.as_bytes() != self.credential_header.as_bytes() {
Error::e_explain(HTTPStatus(403), "Auth failed, credential mismatch")
} else {
Ok(())
}
}
fn as_any(&self) -> &dyn Any {
self
}
fn as_any_mut(&mut self) -> &mut dyn Any {
self
}
}
pub struct MyAcl {
pub credential: String,
}
impl HttpModuleBuilder for MyAcl {
fn init(&self) -> Module {
Box::new(MyAclCtx {
credential_header: format!("basic {}", self.credential),
})
}
}
}
pub struct MyProxy;
#[async_trait]
impl ProxyHttp for MyProxy {
type CTX = ();
fn new_ctx(&self) -> Self::CTX {}
fn init_downstream_modules(&self, modules: &mut HttpModules) {
modules.add_module(Box::new(my_acl::MyAcl {
credential: "testcode".into(),
}))
}
async fn upstream_peer(
&self,
_session: &mut Session,
_ctx: &mut Self::CTX,
) -> Result<Box<HttpPeer>> {
let peer = Box::new(HttpPeer::new(
("1.1.1.1", 443),
true,
"one.one.one.one".to_string(),
));
Ok(peer)
}
}
fn main() {
env_logger::init();
let opt = Opt::parse();
let mut my_server = Server::new(Some(opt)).unwrap();
my_server.bootstrap();
let mut my_proxy = pingora_proxy::http_proxy_service(&my_server.configuration, MyProxy);
my_proxy.add_tcp("0.0.0.0:6193");
my_server.add_service(my_proxy);
my_server.run_forever();
}