Skip to main content

spin_factor_outbound_http/
lib.rs

1pub mod intercept;
2pub mod runtime_config;
3mod spin;
4mod wasi;
5pub mod wasi_2023_10_18;
6pub mod wasi_2023_11_10;
7pub mod wasi_2026_03_15;
8
9use std::{net::SocketAddr, sync::Arc};
10
11use anyhow::Context;
12use http::{
13    HeaderValue, Uri,
14    uri::{Authority, Parts, PathAndQuery, Scheme},
15};
16use intercept::OutboundHttpInterceptor;
17use runtime_config::RuntimeConfig;
18use spin_factor_otel::OtelFactorState;
19use spin_factor_outbound_networking::{
20    ComponentTlsClientConfigs, ConnectionSemaphore, OutboundNetworkingFactor,
21    build_connection_semaphore,
22    config::{allowed_hosts::OutboundAllowedHosts, blocked_networks::BlockedNetworks},
23};
24use spin_factors::{
25    ConfigureAppContext, Factor, FactorData, PrepareContext, RuntimeFactors, SelfInstanceBuilder,
26    anyhow,
27};
28use wasmtime_wasi_http::WasiHttpCtx;
29
30pub use wasmtime_wasi_http::p2::{
31    HttpResult, bindings::http::types::ErrorCode, body::HyperOutgoingBody,
32    types::HostFutureIncomingResponse,
33};
34
35#[derive(Default)]
36pub struct OutboundHttpFactor {
37    _priv: (),
38}
39
40impl Factor for OutboundHttpFactor {
41    type RuntimeConfig = RuntimeConfig;
42    type AppState = AppState;
43    type InstanceBuilder = InstanceState;
44
45    fn init<T: spin_factors::InitContext<Self>>(&mut self, ctx: &mut T) -> anyhow::Result<()> {
46        ctx.link_bindings(spin_world::v1::http::add_to_linker::<_, FactorData<Self>>)?;
47        wasi::add_to_linker(ctx)?;
48        Ok(())
49    }
50
51    fn configure_app<T: RuntimeFactors>(
52        &self,
53        mut ctx: ConfigureAppContext<T, Self>,
54    ) -> anyhow::Result<Self::AppState> {
55        let config = ctx.take_runtime_config().unwrap_or_default();
56        let networking = ctx.app_state::<OutboundNetworkingFactor>().ok();
57
58        Ok(AppState {
59            wasi_http_clients: wasi::HttpClients::new(config.connection_pooling_enabled),
60            connection_pooling_enabled: config.connection_pooling_enabled,
61            tcp_nodelay: config.tcp_nodelay,
62            semaphore: build_connection_semaphore(
63                networking,
64                "http",
65                config.max_concurrent_connections,
66                config.wait_timeout,
67            ),
68        })
69    }
70
71    fn prepare<T: RuntimeFactors>(
72        &self,
73        mut ctx: PrepareContext<T, Self>,
74    ) -> anyhow::Result<Self::InstanceBuilder> {
75        let outbound_networking = ctx.instance_builder::<OutboundNetworkingFactor>()?;
76        let allowed_hosts = outbound_networking.allowed_hosts();
77        let blocked_networks = outbound_networking.blocked_networks();
78        let component_tls_configs = outbound_networking.component_tls_configs();
79        let otel = OtelFactorState::from_prepare_context(&mut ctx)?;
80        let app_state = ctx.app_state();
81        Ok(InstanceState {
82            wasi_http_ctx: WasiHttpCtx::new(),
83            hooks: InstanceHttpHooks {
84                allowed_hosts,
85                blocked_networks,
86                component_tls_configs,
87                tcp_nodelay: app_state.tcp_nodelay,
88                self_request_origin: None,
89                request_interceptor: None,
90                spin_http_client: None,
91                wasi_http_clients: app_state.wasi_http_clients.clone(),
92                connection_pooling_enabled: app_state.connection_pooling_enabled,
93                semaphore: app_state.semaphore.clone(),
94                otel,
95            },
96        })
97    }
98}
99
100pub struct InstanceState {
101    wasi_http_ctx: WasiHttpCtx,
102    hooks: InstanceHttpHooks,
103}
104
105struct InstanceHttpHooks {
106    allowed_hosts: OutboundAllowedHosts,
107    blocked_networks: BlockedNetworks,
108    component_tls_configs: ComponentTlsClientConfigs,
109    self_request_origin: Option<SelfRequestOrigin>,
110    request_interceptor: Option<Arc<dyn OutboundHttpInterceptor>>,
111    // Connection-pooling client for 'fermyon:spin/http' interface
112    //
113    // TODO: We could move this to `AppState` like the
114    // `wasi:http/outgoing-handler` pool for consistency, although it's probably
115    // not a high priority given that `fermyon:spin/http` is deprecated anyway.
116    spin_http_client: Option<reqwest::Client>,
117    // Connection pooling clients for `wasi:http/outgoing-handler` interface
118    //
119    // This is a clone of `AppState::wasi_http_clients`, meaning it is shared
120    // among all instances of the app.
121    wasi_http_clients: wasi::HttpClients,
122    /// Whether connection pooling is enabled for this instance.
123    connection_pooling_enabled: bool,
124    /// Semaphore to limit concurrent outbound connections.
125    semaphore: ConnectionSemaphore,
126    /// Manages access to the OtelFactor state.
127    otel: OtelFactorState,
128    /// Enables TCP_NODELAY.
129    tcp_nodelay: bool,
130}
131
132impl InstanceState {
133    /// Sets the [`SelfRequestOrigin`] for this instance.
134    ///
135    /// This is used to handle outbound requests to relative URLs. If unset,
136    /// those requests will fail.
137    pub fn set_self_request_origin(&mut self, origin: SelfRequestOrigin) {
138        self.hooks.self_request_origin = Some(origin);
139    }
140
141    /// Sets a [`OutboundHttpInterceptor`] for this instance.
142    ///
143    /// Returns an error if it has already been called for this instance.
144    pub fn set_request_interceptor(
145        &mut self,
146        interceptor: impl OutboundHttpInterceptor + 'static,
147    ) -> anyhow::Result<()> {
148        if self.hooks.request_interceptor.is_some() {
149            anyhow::bail!("set_request_interceptor can only be called once");
150        }
151        self.hooks.request_interceptor = Some(Arc::new(interceptor));
152        Ok(())
153    }
154}
155
156impl SelfInstanceBuilder for InstanceState {}
157
158pub type Request = http::Request<wasmtime_wasi_http::p2::body::HyperOutgoingBody>;
159pub type Response = http::Response<wasmtime_wasi_http::p2::body::HyperIncomingBody>;
160
161/// SelfRequestOrigin indicates the base URI to use for "self" requests.
162#[derive(Clone, Debug)]
163pub struct SelfRequestOrigin {
164    pub scheme: Scheme,
165    pub authority: Authority,
166}
167
168impl SelfRequestOrigin {
169    pub fn create(scheme: Scheme, auth: &str) -> anyhow::Result<Self> {
170        Ok(SelfRequestOrigin {
171            scheme,
172            authority: auth
173                .parse()
174                .with_context(|| format!("address '{auth}' is not a valid authority"))?,
175        })
176    }
177
178    pub fn from_uri(uri: &Uri) -> anyhow::Result<Self> {
179        Ok(Self {
180            scheme: uri.scheme().context("URI missing scheme")?.clone(),
181            authority: uri.authority().context("URI missing authority")?.clone(),
182        })
183    }
184
185    fn into_uri(self, path_and_query: Option<PathAndQuery>) -> Uri {
186        let mut parts = Parts::default();
187        parts.scheme = Some(self.scheme);
188        parts.authority = Some(self.authority);
189        parts.path_and_query = path_and_query;
190        Uri::from_parts(parts).unwrap()
191    }
192
193    fn use_tls(&self) -> bool {
194        self.scheme == Scheme::HTTPS
195    }
196
197    fn host_header(&self) -> HeaderValue {
198        HeaderValue::from_str(self.authority.as_str()).unwrap()
199    }
200}
201
202impl std::fmt::Display for SelfRequestOrigin {
203    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
204        write!(f, "{}://{}", self.scheme, self.authority)
205    }
206}
207
208pub struct AppState {
209    // Connection pooling clients for `wasi:http/outgoing-handler` interface
210    wasi_http_clients: wasi::HttpClients,
211    /// Whether connection pooling is enabled for this app.
212    connection_pooling_enabled: bool,
213    /// Enables TCP_NODELAY on connection sockets.
214    tcp_nodelay: bool,
215    /// Semaphore to limit concurrent outbound connections.
216    semaphore: ConnectionSemaphore,
217}
218
219/// Removes IPs in the given [`BlockedNetworks`].
220///
221/// Returns [`ErrorCode::DestinationIpProhibited`] if all IPs are removed.
222fn remove_blocked_addrs(
223    blocked_networks: &BlockedNetworks,
224    addrs: &mut Vec<SocketAddr>,
225) -> Result<(), ErrorCode> {
226    if addrs.is_empty() {
227        return Ok(());
228    }
229    let blocked_addrs = blocked_networks.remove_blocked(addrs);
230    if addrs.is_empty() && !blocked_addrs.is_empty() {
231        tracing::error!(
232            "error.type" = "destination_ip_prohibited",
233            ?blocked_addrs,
234            "all destination IP(s) prohibited by runtime config"
235        );
236        return Err(ErrorCode::DestinationIpProhibited);
237    }
238    Ok(())
239}