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

Private endpoints #2418

Merged
merged 1 commit into from
Apr 4, 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
22 changes: 21 additions & 1 deletion crates/http/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,32 @@ pub struct HttpTriggerConfig {
/// Component ID to invoke
pub component: String,
/// HTTP route the component will be invoked for
pub route: String,
pub route: HttpTriggerRouteConfig,
/// The HTTP executor the component requires
#[serde(default)]
pub executor: Option<HttpExecutorType>,
}

/// An HTTP trigger route
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(untagged)]
pub enum HttpTriggerRouteConfig {
Route(String),
IsRoutable(bool),
}

impl Default for HttpTriggerRouteConfig {
fn default() -> Self {
Self::Route(Default::default())
}
}

impl<T: Into<String>> From<T> for HttpTriggerRouteConfig {
fn from(value: T) -> Self {
Self::Route(value.into())
}
}

/// The executor for the HTTP component.
/// The component can either implement the Spin HTTP interface,
/// the `wasi-http` interface, or the Wagi CGI interface.
Expand Down
85 changes: 65 additions & 20 deletions crates/http/src/routes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ use http::Uri;
use indexmap::IndexMap;
use std::{borrow::Cow, fmt};

use crate::config::HttpTriggerRouteConfig;

/// Router for the HTTP trigger.
#[derive(Clone, Debug)]
pub struct Router {
Expand All @@ -15,6 +17,7 @@ pub struct Router {
}

/// A detected duplicate route.
#[derive(Debug)] // Needed to call `expect_err` on `Router::build`
pub struct DuplicateRoute {
/// The duplicated route pattern.
pub route: RoutePattern,
Expand All @@ -28,14 +31,23 @@ impl Router {
/// Builds a router based on application configuration.
pub fn build<'a>(
base: &str,
component_routes: impl IntoIterator<Item = (&'a str, &'a str)>,
component_routes: impl IntoIterator<Item = (&'a str, &'a HttpTriggerRouteConfig)>,
) -> Result<(Self, Vec<DuplicateRoute>)> {
let mut routes = IndexMap::new();
let mut duplicates = vec![];

let routes_iter = component_routes.into_iter().map(|(component_id, route)| {
(RoutePattern::from(base, route), component_id.to_string())
});
let routes_iter = component_routes
.into_iter()
.filter_map(|(component_id, route)| {
match route {
HttpTriggerRouteConfig::Route(r) => {
Some(Ok((RoutePattern::from(base, r), component_id.to_string())))
}
HttpTriggerRouteConfig::IsRoutable(false) => None,
HttpTriggerRouteConfig::IsRoutable(true) => Some(Err(anyhow!("route must be a string pattern or 'false': component '{component_id}' has route = 'true'"))),
}
})
.collect::<Result<Vec<_>>>()?;

for (route, component_id) in routes_iter {
let replaced = routes.insert(route.clone(), component_id.clone());
Expand Down Expand Up @@ -417,10 +429,10 @@ mod route_tests {
let (routes, duplicates) = Router::build(
"/",
vec![
("/", "/"),
("/foo", "/foo"),
("/bar", "/bar"),
("/whee/...", "/whee/..."),
("/", &"/".into()),
("/foo", &"/foo".into()),
("/bar", &"/bar".into()),
("/whee/...", &"/whee/...".into()),
],
)
.unwrap();
Expand All @@ -434,10 +446,10 @@ mod route_tests {
let (routes, _) = Router::build(
"/",
vec![
("/", "/"),
("/foo", "/foo"),
("/bar", "/bar"),
("/whee/...", "/whee/..."),
("/", &"/".into()),
("/foo", &"/foo".into()),
("/bar", &"/bar".into()),
("/whee/...", &"/whee/...".into()),
],
)
.unwrap();
Expand All @@ -453,10 +465,10 @@ mod route_tests {
let (routes, duplicates) = Router::build(
"/",
vec![
("/", "/"),
("first /foo", "/foo"),
("second /foo", "/foo"),
("/whee/...", "/whee/..."),
("/", &"/".into()),
("first /foo", &"/foo".into()),
("second /foo", &"/foo".into()),
("/whee/...", &"/whee/...".into()),
],
)
.unwrap();
Expand All @@ -470,10 +482,10 @@ mod route_tests {
let (routes, duplicates) = Router::build(
"/",
vec![
("/", "/"),
("first /foo", "/foo"),
("second /foo", "/foo"),
("/whee/...", "/whee/..."),
("/", &"/".into()),
("first /foo", &"/foo".into()),
("second /foo", &"/foo".into()),
("/whee/...", &"/whee/...".into()),
],
)
.unwrap();
Expand All @@ -482,4 +494,37 @@ mod route_tests {
assert_eq!("first /foo", duplicates[0].replaced_id);
assert_eq!("second /foo", duplicates[0].effective_id);
}

#[test]
fn unroutable_routes_are_skipped() {
let (routes, _) = Router::build(
"/",
vec![
("/", &"/".into()),
("/foo", &"/foo".into()),
("private", &HttpTriggerRouteConfig::IsRoutable(false)),
("/whee/...", &"/whee/...".into()),
],
)
.unwrap();

assert_eq!(3, routes.routes.len());
assert!(!routes.routes.values().any(|c| c == "private"));
}

#[test]
fn unroutable_routes_have_to_be_unroutable_thats_just_common_sense() {
let e = Router::build(
"/",
vec![
("/", &"/".into()),
("/foo", &"/foo".into()),
("bad component", &HttpTriggerRouteConfig::IsRoutable(true)),
("/whee/...", &"/whee/...".into()),
],
)
.expect_err("should not have accepted a 'route = true'");

assert!(e.to_string().contains("bad component"));
}
}
8 changes: 5 additions & 3 deletions crates/testing/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,9 @@ use spin_app::{
AppComponent, Loader,
};
use spin_core::{Component, StoreBuilder};
use spin_http::config::{HttpExecutorType, HttpTriggerConfig, WagiTriggerConfig};
use spin_http::config::{
HttpExecutorType, HttpTriggerConfig, HttpTriggerRouteConfig, WagiTriggerConfig,
};
use spin_trigger::{HostComponentInitData, RuntimeConfig, TriggerExecutor, TriggerExecutorBuilder};
use tokio::fs;

Expand Down Expand Up @@ -68,7 +70,7 @@ impl HttpTestConfig {
self.module_path(Path::new(TEST_PROGRAM_PATH).join(name))
}

pub fn http_spin_trigger(&mut self, route: impl Into<String>) -> &mut Self {
pub fn http_spin_trigger(&mut self, route: impl Into<HttpTriggerRouteConfig>) -> &mut Self {
self.http_trigger_config = HttpTriggerConfig {
component: "test-component".to_string(),
route: route.into(),
Expand All @@ -79,7 +81,7 @@ impl HttpTestConfig {

pub fn http_wagi_trigger(
&mut self,
route: impl Into<String>,
route: impl Into<HttpTriggerRouteConfig>,
wagi_config: WagiTriggerConfig,
) -> &mut Self {
self.http_trigger_config = HttpTriggerConfig {
Expand Down
13 changes: 9 additions & 4 deletions crates/trigger-http/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ use spin_core::{Engine, OutboundWasiHttpHandler};
use spin_http::{
app_info::AppInfo,
body,
config::{HttpExecutorType, HttpTriggerConfig},
config::{HttpExecutorType, HttpTriggerConfig, HttpTriggerRouteConfig},
routes::{RoutePattern, Router},
};
use spin_outbound_networking::{
Expand Down Expand Up @@ -119,7 +119,7 @@ impl TriggerExecutor for HttpTrigger {

let component_routes = engine
.trigger_configs()
.map(|(_, config)| (config.component.as_str(), config.route.as_str()));
.map(|(_, config)| (config.component.as_str(), &config.route));

let (router, duplicate_routes) = Router::build(&base, component_routes)?;

Expand Down Expand Up @@ -257,14 +257,19 @@ impl HttpTrigger {

let executor = trigger.executor.as_ref().unwrap_or(&HttpExecutorType::Http);

let raw_route = match &trigger.route {
HttpTriggerRouteConfig::Route(r) => r.as_str(),
HttpTriggerRouteConfig::IsRoutable(_) => "/...",
};

let res = match executor {
HttpExecutorType::Http => {
HttpHandlerExecutor
.execute(
self.engine.clone(),
component_id,
&self.base,
&trigger.route,
raw_route,
req,
addr,
)
Expand All @@ -279,7 +284,7 @@ impl HttpTrigger {
self.engine.clone(),
component_id,
&self.base,
&trigger.route,
raw_route,
req,
addr,
)
Expand Down
2 changes: 1 addition & 1 deletion tests/runtime-tests/tests/internal-http/spin.toml
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ source = "%{source=internal-http-front}"
allowed_outbound_hosts = ["http://middle.spin.internal"]

[[trigger.http]]
route = "/middle/..."
route = false
component = "middle"

[component.middle]
Expand Down
Loading