Skip to content
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

Common lib implementation of secret interface #44

Merged
merged 4 commits into from
Oct 21, 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
14 changes: 14 additions & 0 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 @@ -58,6 +58,7 @@ runtime = { path = "crates/runtime", default-features = false }
http-service = { path = "crates/http-service" }
http-backend = { path = "crates/http-backend" }
dictionary = { path = "crates/dictionary" }
secret = { path = "crates/secret" }
hyper-tls = "0.6"
hyper-util = { version = "0.1", features = ["client", "client-legacy", "http1", "tokio"] }
http-body-util = "0.1"
Expand Down
1 change: 1 addition & 0 deletions crates/http-service/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ reactor = { path = "../reactor" }
runtime = { path = "../runtime" }
http-backend = { path = "../http-backend" }
dictionary = { path = "../dictionary" }
secret = { path = "../secret" }
nanoid = "0.4"
bytesize = "1.3.0"
futures = "0.3.30"
Expand Down
20 changes: 13 additions & 7 deletions crates/http-service/src/executor/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,10 @@ use hyper::body::{Body, Bytes};
use reactor::gcore::fastedge;
use runtime::store::StoreBuilder;
use runtime::{App, InstancePre, WasmEngine};
use secret::{Secret, SecretStrategy};
use smol_str::SmolStr;
use wasmtime_wasi::StdoutStream;

pub use wasi_http::WasiHttpExecutorImpl;
use wasmtime_wasi::StdoutStream;

pub(crate) static X_REAL_IP: &str = "x-real-ip";
pub(crate) static TRACEPARENT: &str = "traceparent";
Expand Down Expand Up @@ -48,17 +48,19 @@ pub trait ExecutorFactory<C> {

/// Execute context used by ['HttpService']
#[derive(Clone)]
pub struct HttpExecutorImpl<C> {
instance_pre: InstancePre<HttpState<C>>,
pub struct HttpExecutorImpl<C, T: SecretStrategy> {
instance_pre: InstancePre<HttpState<C, T>>,
store_builder: StoreBuilder,
backend: Backend<C>,
dictionary: Dictionary,
secret: Secret<T>,
}

#[async_trait]
impl<C> HttpExecutor for HttpExecutorImpl<C>
impl<C, T> HttpExecutor for HttpExecutorImpl<C, T>
where
C: Clone + Send + Sync + 'static,
T: SecretStrategy + Clone + Send + Sync,
{
async fn execute<B>(
&self,
Expand All @@ -75,21 +77,24 @@ where
}
}

impl<C> HttpExecutorImpl<C>
impl<C, T> HttpExecutorImpl<C, T>
where
C: Clone + Send + Sync + 'static,
T: SecretStrategy + Clone + Send,
{
pub fn new(
instance_pre: InstancePre<HttpState<C>>,
instance_pre: InstancePre<HttpState<C, T>>,
store_builder: StoreBuilder,
backend: Backend<C>,
dictionary: Dictionary,
secret: Secret<T>,
) -> Self {
Self {
instance_pre,
store_builder,
backend,
dictionary,
secret,
}
}

Expand Down Expand Up @@ -152,6 +157,7 @@ where
propagate_headers: parts.headers,
propagate_header_names,
dictionary: self.dictionary.clone(),
secret: self.secret.clone(),
};

let mut store = store_builder.build(state)?;
Expand Down
17 changes: 12 additions & 5 deletions crates/http-service/src/executor/wasi_http.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,23 +15,26 @@ use http_body_util::{BodyExt, Full};
use hyper::body::{Body, Bytes};
use runtime::store::StoreBuilder;
use runtime::InstancePre;
use secret::{Secret, SecretStrategy};
use smol_str::ToSmolStr;
use tracing::error;
use wasmtime_wasi_http::WasiHttpView;

/// Execute context used by ['HttpService']
#[derive(Clone)]
pub struct WasiHttpExecutorImpl<C> {
instance_pre: InstancePre<HttpState<C>>,
pub struct WasiHttpExecutorImpl<C, T: SecretStrategy> {
instance_pre: InstancePre<HttpState<C, T>>,
store_builder: StoreBuilder,
backend: Backend<C>,
dictionary: Dictionary,
secret: Secret<T>,
}

#[async_trait]
impl<C> HttpExecutor for WasiHttpExecutorImpl<C>
impl<C, T> HttpExecutor for WasiHttpExecutorImpl<C, T>
where
C: Clone + Send + Sync + 'static,
T: SecretStrategy + Clone + Send + Sync + 'static,
{
async fn execute<B>(
&self,
Expand All @@ -48,21 +51,24 @@ where
}
}

impl<C> WasiHttpExecutorImpl<C>
impl<C, T> WasiHttpExecutorImpl<C, T>
where
C: Clone + Send + Sync + 'static,
T: SecretStrategy + Clone + Send + 'static,
{
pub fn new(
instance_pre: InstancePre<HttpState<C>>,
instance_pre: InstancePre<HttpState<C, T>>,
store_builder: StoreBuilder,
backend: Backend<C>,
dictionary: Dictionary,
secret: Secret<T>,
) -> Self {
Self {
instance_pre,
store_builder,
backend,
dictionary,
secret,
}
}

Expand Down Expand Up @@ -135,6 +141,7 @@ where
propagate_headers,
propagate_header_names,
dictionary: self.dictionary.clone(),
secret: self.secret.clone(),
};

let mut store = store_builder.build(state).context("store build")?;
Expand Down
57 changes: 38 additions & 19 deletions crates/http-service/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ use runtime::util::metrics;
use runtime::util::stats::StatRow;
use runtime::util::stats::StatsWriter;
use runtime::{App, AppResult, ContextT, Router, WasmEngine, WasmEngineBuilder};
use secret::SecretStrategy;
use shellflip::ShutdownHandle;
use smol_str::SmolStr;
use state::HttpState;
Expand Down Expand Up @@ -56,29 +57,30 @@ pub struct HttpConfig {
pub backoff: u64,
}

pub struct HttpService<T: ContextT> {
engine: WasmEngine<HttpState<T::BackendConnector>>,
pub struct HttpService<T: ContextT, S: SecretStrategy> {
engine: WasmEngine<HttpState<T::BackendConnector, S>>,
context: T,
}

pub trait ContextHeaders {
fn append_headers(&self) -> impl Iterator<Item = (SmolStr, SmolStr)>;
}

impl<T> Service for HttpService<T>
impl<T, S> Service for HttpService<T, S>
where
T: ContextT
+ StatsWriter
+ Router
+ ContextHeaders
+ ExecutorFactory<HttpState<T::BackendConnector>>
+ ExecutorFactory<HttpState<T::BackendConnector, S>>
+ Sync
+ Send
+ 'static,
T::BackendConnector: Connect + Clone + Send + Sync + 'static,
T::Executor: HttpExecutor + Send + Sync,
S: SecretStrategy + Send + Sync + 'static,
{
type State = HttpState<T::BackendConnector>;
type State = HttpState<T::BackendConnector, S>;
type Config = HttpConfig;
type Context = T;

Expand Down Expand Up @@ -147,22 +149,25 @@ where
&mut data.as_mut().dictionary
})?;

reactor::gcore::fastedge::secret::add_to_linker(linker, |data| &mut data.as_mut().secret)?;

Ok(())
}
}

impl<T> HttpService<T>
impl<T, U> HttpService<T, U>
where
T: ContextT
+ StatsWriter
+ Router
+ ContextHeaders
+ ExecutorFactory<HttpState<T::BackendConnector>>
+ ExecutorFactory<HttpState<T::BackendConnector, U>>
+ Sync
+ Send
+ 'static,
T::BackendConnector: Clone + Send + Sync + 'static,
T::Executor: HttpExecutor + Send + Sync,
U: SecretStrategy,
{
async fn serve<S>(self: Arc<Self>, stream: S, _cancel: Arc<ShutdownHandle>)
where
Expand Down Expand Up @@ -566,10 +571,10 @@ mod tests {
use wasmtime::component::Component;
use wasmtime::{Engine, Module};

use super::*;
use crate::executor::HttpExecutorImpl;
use runtime::util::stats::StatRow;

use super::*;
use secret::Secret;

#[test_case("app.server.com", "server.com", "app"; "get app name from server_name header")]
fn test_app_name_from_request(server_name: &str, uri: &str, expected: &str) {
Expand Down Expand Up @@ -656,19 +661,29 @@ mod tests {
}
}

impl ExecutorFactory<HttpState<FastEdgeConnector>> for TestContext {
type Executor = HttpExecutorImpl<FastEdgeConnector>;
#[derive(Clone)]
struct TestSecret;

impl SecretStrategy for TestSecret {
fn get(&self, _key: String) -> Result<Option<Vec<u8>>> {
Ok(Some(b"secret".to_vec()))
}
}

impl ExecutorFactory<HttpState<FastEdgeConnector, TestSecret>> for TestContext {
type Executor = HttpExecutorImpl<FastEdgeConnector, TestSecret>;

fn get_executor(
&self,
name: SmolStr,
cfg: &App,
engine: &WasmEngine<HttpState<FastEdgeConnector>>,
engine: &WasmEngine<HttpState<FastEdgeConnector, TestSecret>>,
) -> Result<Self::Executor> {
let mut dictionary = Dictionary::new();
for (k, v) in cfg.env.iter() {
dictionary.insert(k.to_string(), v.to_string());
}
let secret = Secret::new(TestSecret);

let env = cfg.env.iter().collect::<Vec<(&SmolStr, &SmolStr)>>();

Expand All @@ -690,6 +705,7 @@ mod tests {
store_builder,
self.backend(),
dictionary,
secret,
))
}
}
Expand All @@ -710,6 +726,7 @@ mod tests {
plan: "test_plan".to_smolstr(),
status,
debug_until: None,
secrets: vec![],
})
}

Expand Down Expand Up @@ -750,7 +767,7 @@ mod tests {
engine: make_engine(),
};

let http_service: HttpService<TestContext> =
let http_service: HttpService<TestContext, TestSecret> =
assert_ok!(ServiceBuilder::new(context).build());

let res = assert_ok!(http_service.handle_request("1", req).await);
Expand Down Expand Up @@ -791,6 +808,7 @@ mod tests {
plan: "test_plan".to_smolstr(),
status: Status::Enabled,
debug_until: None,
secrets: vec![],
});

let context = TestContext {
Expand All @@ -799,7 +817,7 @@ mod tests {
engine: make_engine(),
};

let http_service: HttpService<TestContext> =
let http_service: HttpService<TestContext, TestSecret> =
assert_ok!(ServiceBuilder::new(context).build());

let res = assert_ok!(http_service.handle_request("2", req).await);
Expand Down Expand Up @@ -839,6 +857,7 @@ mod tests {
plan: "test_plan".to_smolstr(),
status: Status::Enabled,
debug_until: None,
secrets: vec![],
});

let context = TestContext {
Expand All @@ -847,7 +866,7 @@ mod tests {
engine: make_engine(),
};

let http_service: HttpService<TestContext> =
let http_service: HttpService<TestContext, TestSecret> =
assert_ok!(ServiceBuilder::new(context).build());

let res = assert_ok!(http_service.handle_request("3", req).await);
Expand Down Expand Up @@ -881,7 +900,7 @@ mod tests {
engine: make_engine(),
};

let http_service: HttpService<TestContext> =
let http_service: HttpService<TestContext, TestSecret> =
assert_ok!(ServiceBuilder::new(context).build());
let res = assert_ok!(http_service.handle_request("4", req).await);
assert_eq!(StatusCode::NOT_FOUND, res.status());
Expand All @@ -907,7 +926,7 @@ mod tests {
engine: make_engine(),
};

let http_service: HttpService<TestContext> =
let http_service: HttpService<TestContext, TestSecret> =
assert_ok!(ServiceBuilder::new(context).build());
let res = assert_ok!(http_service.handle_request("5", req).await);
assert_eq!(StatusCode::NOT_FOUND, res.status());
Expand All @@ -933,7 +952,7 @@ mod tests {
engine: make_engine(),
};

let http_service: HttpService<TestContext> =
let http_service: HttpService<TestContext, TestSecret> =
assert_ok!(ServiceBuilder::new(context).build());
let res = assert_ok!(http_service.handle_request("6", req).await);
assert_eq!(StatusCode::TOO_MANY_REQUESTS, res.status());
Expand All @@ -959,7 +978,7 @@ mod tests {
engine: make_engine(),
};

let http_service: HttpService<TestContext> =
let http_service: HttpService<TestContext, TestSecret> =
assert_ok!(ServiceBuilder::new(context).build());
let res = assert_ok!(http_service.handle_request("7", req).await);
assert_eq!(StatusCode::NOT_ACCEPTABLE, res.status());
Expand Down
Loading
Loading