Skip to main content

viceroy_lib/component/
backend.rs

1use {
2    crate::component::bindings::fastly::compute::{backend, http_types, types},
3    crate::config::{Backend, ClientCertInfo},
4    crate::error::Error,
5    crate::sandbox::Sandbox,
6    crate::secret_store::SecretLookup,
7    crate::wiggle_abi::SecretStoreError,
8    http::HeaderValue,
9    http::Uri,
10    std::mem::take,
11    std::time::Duration,
12    wasmtime::component::{Resource, ResourceTable},
13};
14
15pub(crate) async fn register_dynamic_backend(
16    sandbox: &mut Sandbox,
17    table: &mut ResourceTable,
18    prefix: String,
19    target: String,
20    options: Resource<backend::DynamicBackendOptions>,
21) -> Result<Resource<String>, types::Error> {
22    let options = take(table.get_mut(&options)?);
23
24    let name = prefix.as_str();
25    let origin_name = target.as_str();
26
27    let override_host = if let Some(host_override) = options.host_override {
28        if host_override.is_empty() {
29            return Err(types::Error::InvalidArgument);
30        }
31
32        if host_override.len() > 1024 {
33            return Err(types::Error::InvalidArgument);
34        }
35
36        Some(HeaderValue::from_bytes(host_override.as_bytes())?)
37    } else {
38        None
39    };
40
41    let use_tls = options.use_tls;
42    let scheme = if use_tls { "https" } else { "http" };
43
44    let ca_certs = if use_tls {
45        if let Some(ca_cert) = options.ca_cert {
46            if ca_cert.is_empty() {
47                return Err(types::Error::InvalidArgument);
48            }
49
50            if ca_cert.len() > (64 * 1024) {
51                return Err(types::Error::InvalidArgument);
52            }
53
54            let mut byte_cursor = std::io::Cursor::new(ca_cert.as_bytes());
55            rustls_pemfile::certs(&mut byte_cursor).collect::<Result<Vec<_>, _>>()?
56        } else {
57            vec![]
58        }
59    } else {
60        vec![]
61    };
62
63    let mut cert_host = if let Some(cert_hostname) = options.cert_hostname {
64        if cert_hostname.is_empty() {
65            return Err(types::Error::InvalidArgument);
66        }
67
68        if cert_hostname.len() > 1024 {
69            return Err(types::Error::InvalidArgument);
70        }
71
72        Some(cert_hostname)
73    } else {
74        None
75    };
76
77    let use_sni = if let Some(sni_hostname) = options.sni_hostname {
78        if sni_hostname.is_empty() {
79            false
80        } else if sni_hostname.len() > 1024 {
81            return Err(types::Error::InvalidArgument);
82        } else {
83            if let Some(cert_host) = &cert_host {
84                if cert_host != &sni_hostname {
85                    // because we're using rustls, we cannot support distinct SNI and cert hostnames
86                    return Err(types::Error::InvalidArgument);
87                }
88            } else {
89                cert_host = Some(sni_hostname);
90            }
91
92            true
93        }
94    } else {
95        true
96    };
97
98    let client_cert = if let Some((client_cert, client_key)) = options.client_cert {
99        let key_lookup = sandbox
100            .secret_lookup(client_key)
101            .ok_or(Error::SecretStoreError(
102                SecretStoreError::InvalidSecretHandle(client_key),
103            ))?;
104        let key = match &key_lookup {
105            SecretLookup::Standard {
106                store_name,
107                secret_name,
108            } => sandbox
109                .secret_stores()
110                .get_store(store_name)
111                .ok_or(Error::SecretStoreError(
112                    SecretStoreError::InvalidSecretHandle(client_key),
113                ))?
114                .get_secret(secret_name)
115                .ok_or(Error::SecretStoreError(
116                    SecretStoreError::InvalidSecretHandle(client_key),
117                ))?
118                .plaintext(),
119
120            SecretLookup::Injected { plaintext } => plaintext,
121        };
122
123        Some(ClientCertInfo::new(client_cert.as_bytes(), key)?)
124    } else {
125        None
126    };
127
128    let grpc = options.grpc;
129
130    let first_byte_timeout = if options.first_byte_timeout != 0 {
131        Some(Duration::from_millis(options.first_byte_timeout as u64))
132    } else {
133        None
134    };
135
136    let between_bytes_timeout = if options.between_bytes_timeout != 0 {
137        Some(Duration::from_millis(options.between_bytes_timeout as u64))
138    } else {
139        None
140    };
141
142    let uri = Uri::builder()
143        .scheme(scheme)
144        .authority(origin_name)
145        .path_and_query("/")
146        .build()
147        .map_err(|_e| types::Error::InvalidArgument)?;
148
149    let new_backend = Backend {
150        uri,
151        override_host,
152        cert_host,
153        use_sni,
154        grpc,
155        first_byte_timeout,
156        between_bytes_timeout,
157        client_cert,
158        ca_certs,
159        health: crate::config::BackendHealth::Unknown,
160    };
161
162    if !sandbox.add_backend(name, new_backend) {
163        return Err(Error::BackendNameRegistryError(name.to_string()).into());
164    }
165
166    let res = table.push(prefix)?;
167
168    Ok(res)
169}
170
171pub(crate) fn exists(sandbox: &mut Sandbox, backend: &str) -> bool {
172    sandbox.backend(backend).is_some()
173}
174
175pub(crate) fn is_healthy(
176    sandbox: &mut Sandbox,
177    backend: &str,
178) -> Result<backend::BackendHealth, types::Error> {
179    let backend = sandbox.backend(backend).ok_or(Error::InvalidArgument)?;
180    match &backend.health {
181        crate::config::BackendHealth::Unknown => Ok(backend::BackendHealth::Unknown),
182        crate::config::BackendHealth::Healthy => Ok(backend::BackendHealth::Healthy),
183        crate::config::BackendHealth::Unhealthy => Ok(backend::BackendHealth::Unhealthy),
184    }
185}
186
187pub(crate) fn is_dynamic(sandbox: &mut Sandbox, backend: &str) -> Result<bool, types::Error> {
188    if sandbox.dynamic_backend(backend).is_some() {
189        Ok(true)
190    } else if sandbox.backend(backend).is_some() {
191        Ok(false)
192    } else {
193        Err(Error::InvalidArgument.into())
194    }
195}
196
197pub(crate) fn get_host(
198    sandbox: &mut Sandbox,
199    backend: &str,
200    max_len: u64,
201) -> Result<String, types::Error> {
202    let backend = sandbox.backend(backend).ok_or(Error::InvalidArgument)?;
203    let host = backend.uri.host().ok_or(Error::InvalidArgument)?;
204
205    if host.len() > usize::try_from(max_len).unwrap() {
206        // Report the required length, so that guests (and the adapter's `alloc_result!`) can
207        // retry with a large enough buffer.
208        return Err(types::Error::BufferLen(u64::try_from(host.len()).unwrap()));
209    }
210
211    Ok(host.to_owned())
212}
213
214pub(crate) fn get_override_host(
215    sandbox: &mut Sandbox,
216    backend: &str,
217    max_len: u64,
218) -> Result<Option<Vec<u8>>, types::Error> {
219    let backend = sandbox.backend(backend).ok_or(Error::InvalidArgument)?;
220    if let Some(host) = backend.override_host.as_ref() {
221        let host = host.to_str()?;
222
223        if host.len() > usize::try_from(max_len).unwrap() {
224            return Err(types::Error::BufferLen(u64::try_from(host.len()).unwrap()));
225        }
226
227        Ok(Some(host.as_bytes().to_owned()))
228    } else {
229        Ok(None)
230    }
231}
232
233pub(crate) fn get_port(sandbox: &mut Sandbox, backend: &str) -> Result<u16, types::Error> {
234    let backend = sandbox.backend(backend).ok_or(Error::InvalidArgument)?;
235    match backend.uri.port_u16() {
236        Some(port) => Ok(port),
237        None => {
238            if backend.uri.scheme() == Some(&http::uri::Scheme::HTTPS) {
239                Ok(443)
240            } else {
241                Ok(80)
242            }
243        }
244    }
245}
246
247pub(crate) fn get_connect_timeout_ms(
248    sandbox: &mut Sandbox,
249    backend: &str,
250) -> Result<u32, types::Error> {
251    // just doing this to get a different error if the backend doesn't exist
252    let _ = sandbox.backend(backend).ok_or(Error::InvalidArgument)?;
253    Err(Error::Unsupported {
254        msg: "connection timing is not actually supported in Viceroy",
255    }
256    .into())
257}
258
259pub(crate) fn get_first_byte_timeout_ms(
260    sandbox: &mut Sandbox,
261    backend: &str,
262) -> Result<u32, types::Error> {
263    // just doing this to get a different error if the backend doesn't exist
264    let _ = sandbox.backend(backend).ok_or(Error::InvalidArgument)?;
265    Err(Error::Unsupported {
266        msg: "connection timing is not actually supported in Viceroy",
267    }
268    .into())
269}
270
271pub(crate) fn get_between_bytes_timeout_ms(
272    sandbox: &mut Sandbox,
273    backend: &str,
274) -> Result<u32, types::Error> {
275    // just doing this to get a different error if the backend doesn't exist
276    let _ = sandbox.backend(backend).ok_or(Error::InvalidArgument)?;
277    Err(Error::Unsupported {
278        msg: "connection timing is not actually supported in Viceroy",
279    }
280    .into())
281}
282
283pub(crate) fn is_tls(sandbox: &mut Sandbox, backend: &str) -> Result<bool, types::Error> {
284    let backend = sandbox.backend(backend).ok_or(Error::InvalidArgument)?;
285    Ok(backend.uri.scheme() == Some(&http::uri::Scheme::HTTPS))
286}
287
288pub(crate) fn get_tls_min_version(
289    sandbox: &mut Sandbox,
290    backend: &str,
291) -> Result<Option<http_types::TlsVersion>, types::Error> {
292    // just doing this to get a different error if the backend doesn't exist
293    let _ = sandbox.backend(backend).ok_or(Error::InvalidArgument)?;
294    // health checks are not enabled in Viceroy :(
295    Err(Error::Unsupported {
296        msg: "tls version flags are not supported in Viceroy",
297    }
298    .into())
299}
300
301pub(crate) fn get_tls_max_version(
302    sandbox: &mut Sandbox,
303    backend: &str,
304) -> Result<Option<http_types::TlsVersion>, types::Error> {
305    // just doing this to get a different error if the backend doesn't exist
306    let _ = sandbox.backend(backend).ok_or(Error::InvalidArgument)?;
307    // health checks are not enabled in Viceroy :(
308    Err(Error::Unsupported {
309        msg: "tls version flags are not supported in Viceroy",
310    }
311    .into())
312}
313
314pub(crate) fn get_http_keepalive_time(
315    _sandbox: &mut Sandbox,
316    _backend: &str,
317) -> Result<backend::TimeoutMs, types::Error> {
318    Err(Error::Unsupported {
319        msg: "backend.get-http-keepalive-time is not supported in Viceroy",
320    }
321    .into())
322}
323
324pub(crate) fn get_tcp_keepalive_enable(
325    _sandbox: &mut Sandbox,
326    _backend: &str,
327) -> Result<bool, types::Error> {
328    Err(Error::Unsupported {
329        msg: "backend.get-tcp-keepalive-enable is not supported in Viceroy",
330    }
331    .into())
332}
333
334pub(crate) fn get_tcp_keepalive_interval(
335    _sandbox: &mut Sandbox,
336    _backend: &str,
337) -> Result<backend::TimeoutSecs, types::Error> {
338    Err(Error::Unsupported {
339        msg: "backend.get-tcp-keepalive-interval is not supported in Viceroy",
340    }
341    .into())
342}
343
344pub(crate) fn get_tcp_keepalive_probes(
345    _sandbox: &mut Sandbox,
346    _backend: &str,
347) -> Result<backend::ProbeCount, types::Error> {
348    Err(Error::Unsupported {
349        msg: "backend.get-tcp-keepalive-probes is not supported in Viceroy",
350    }
351    .into())
352}
353
354pub(crate) fn get_tcp_keepalive_time(
355    _sandbox: &mut Sandbox,
356    _backend: &str,
357) -> Result<backend::TimeoutSecs, types::Error> {
358    Err(Error::Unsupported {
359        msg: "backend.get_tcp_keepalive_time not supported in Viceroy",
360    }
361    .into())
362}