cloud-sdk-reqwest 1.0.0

Optional provider-neutral reqwest transport boundary for cloud-sdk.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
use core::fmt;
use reqwest::Url;
use std::net::Ipv4Addr;
use std::str::FromStr;
use std::string::String;
#[cfg(test)]
use std::string::ToString;

use cloud_sdk::transport::{
    AcknowledgedCustomEndpoint, CustomEndpointAcknowledgement, EndpointIdentity,
    EndpointIdentityError, EndpointPolicy, EndpointScheme, MAX_ENDPOINT_BASE_PATH_BYTES,
    MAX_ENDPOINT_HOST_BYTES, RequestTarget,
};

/// Maximum endpoint input accepted before URL parsing or allocation.
///
/// This covers `https://`, a maximum-length host, `:65535`, and a
/// maximum-length base path.
pub const MAX_CONFIGURED_ENDPOINT_BYTES: usize =
    "https://".len() + MAX_ENDPOINT_HOST_BYTES + 1 + 5 + MAX_ENDPOINT_BASE_PATH_BYTES;

/// HTTPS endpoint validation or target-composition error.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum EndpointError {
    /// The raw endpoint exceeds [`MAX_CONFIGURED_ENDPOINT_BYTES`].
    InputTooLong,
    /// The endpoint is not a valid absolute URL.
    InvalidUrl,
    /// Public endpoints must use HTTPS.
    HttpsRequired,
    /// A host is required.
    MissingHost,
    /// URL user information is forbidden.
    CredentialsForbidden,
    /// The configured authority uses a non-canonical or ambiguous host form.
    AmbiguousAuthority,
    /// Base endpoint queries are forbidden.
    QueryForbidden,
    /// Base endpoint fragments are forbidden.
    FragmentForbidden,
    /// Non-root endpoint paths must not end in `/`.
    TrailingSlash,
    /// URL parsing changed the exact configured base plus target bytes.
    TargetNormalized,
    /// Allocation failed during target composition.
    AllocationFailed,
    /// The normalized endpoint could not be represented by the shared identity contract.
    IdentityRejected,
    /// The endpoint is not admitted by the supplied provider policy.
    PolicyRejected,
}

impl_static_error!(EndpointError,
    Self::InputTooLong => "endpoint input exceeds the length limit",
    Self::InvalidUrl => "endpoint URL is invalid",
    Self::HttpsRequired => "endpoint must use HTTPS",
    Self::MissingHost => "endpoint host is missing",
    Self::CredentialsForbidden => "endpoint credentials are forbidden",
    Self::AmbiguousAuthority => "endpoint authority is ambiguous or non-canonical",
    Self::QueryForbidden => "endpoint query is forbidden",
    Self::FragmentForbidden => "endpoint fragment is forbidden",
    Self::TrailingSlash => "endpoint path has a forbidden trailing slash",
    Self::TargetNormalized => "request target was normalized or changed origin",
    Self::AllocationFailed => "request-target allocation failed",
    Self::IdentityRejected => "endpoint identity is invalid",
    Self::PolicyRejected => "endpoint is not admitted by provider policy",
);

/// Validated HTTPS API endpoint, optionally including a fixed base path.
#[derive(Clone)]
pub struct HttpsEndpoint {
    base: Url,
    prefix: String,
}

/// Provider-policy-bound IPv4 link-local HTTP endpoint for metadata services.
///
/// This type cannot carry credentials and is accepted only by explicit raw
/// client constructors. It rejects DNS names, non-link-local addresses,
/// non-default ports, and destinations outside the supplied fixed policy.
#[derive(Clone)]
pub struct LinkLocalHttpEndpoint {
    inner: HttpsEndpoint,
}

impl fmt::Debug for LinkLocalHttpEndpoint {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str("LinkLocalHttpEndpoint([redacted])")
    }
}

impl LinkLocalHttpEndpoint {
    /// Validates one direct HTTP metadata destination against provider policy.
    pub fn new_with_policy(value: &str, policy: EndpointPolicy<'_>) -> Result<Self, EndpointError> {
        let inner = HttpsEndpoint::new_inner(value, false)?;
        let identity = inner
            .identity()
            .map_err(|_| EndpointError::IdentityRejected)?;
        let address =
            Ipv4Addr::from_str(identity.host()).map_err(|_| EndpointError::PolicyRejected)?;
        if identity.scheme() != EndpointScheme::Http
            || identity.effective_port() != 80
            || !address.is_link_local()
        {
            return Err(EndpointError::PolicyRejected);
        }
        policy
            .verify(identity)
            .map_err(|_| EndpointError::PolicyRejected)?;
        Ok(Self { inner })
    }

    /// Returns the normalized endpoint identity.
    pub fn identity(&self) -> Result<EndpointIdentity<'_>, EndpointIdentityError> {
        self.inner.identity()
    }

    pub(crate) fn into_inner(self) -> HttpsEndpoint {
        self.inner
    }
}

impl fmt::Debug for HttpsEndpoint {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str("HttpsEndpoint([redacted])")
    }
}

impl HttpsEndpoint {
    /// Validates an endpoint and requires admission by a provider-owned policy.
    ///
    /// This is the preferred constructor for official and region-derived
    /// provider destinations.
    pub fn new_with_policy(value: &str, policy: EndpointPolicy<'_>) -> Result<Self, EndpointError> {
        let endpoint = Self::new_inner(value, true)?;
        policy
            .verify(
                endpoint
                    .identity()
                    .map_err(|_| EndpointError::IdentityRejected)?,
            )
            .map_err(|_| EndpointError::PolicyRejected)?;
        Ok(endpoint)
    }

    /// Explicitly trusts and validates a custom HTTPS credential destination.
    ///
    /// The transport sends its bearer token to this origin. `value` must come
    /// from trusted operator configuration and must never be controlled by a
    /// tenant, request payload, or other untrusted input.
    ///
    /// ```compile_fail
    /// use cloud_sdk_reqwest::blocking::HttpsEndpoint;
    ///
    /// let endpoint = HttpsEndpoint::new_custom("https://api.example.test/v1");
    /// ```
    pub fn new_custom(
        value: &str,
        acknowledgement: CustomEndpointAcknowledgement,
    ) -> Result<Self, EndpointError> {
        let endpoint = Self::new_inner(value, true)?;
        let identity = endpoint
            .identity()
            .map_err(|_| EndpointError::IdentityRejected)?;
        EndpointPolicy::acknowledged_custom(AcknowledgedCustomEndpoint::new(
            identity,
            acknowledgement,
        ))
        .verify(identity)
        .map_err(|_| EndpointError::PolicyRejected)?;
        Ok(endpoint)
    }

    fn new_inner(value: &str, require_https: bool) -> Result<Self, EndpointError> {
        if value.len() > MAX_CONFIGURED_ENDPOINT_BYTES {
            return Err(EndpointError::InputTooLong);
        }
        validate_raw_authority(value)?;
        let configured_path = validate_configured_base_path(value)?;
        let base = Url::parse(value).map_err(|_| EndpointError::InvalidUrl)?;
        if base.path() != configured_path {
            return Err(EndpointError::TargetNormalized);
        }
        if require_https && base.scheme() != "https" {
            return Err(EndpointError::HttpsRequired);
        }
        if base.host_str().is_none() {
            return Err(EndpointError::MissingHost);
        }
        if !base.username().is_empty() || base.password().is_some() {
            return Err(EndpointError::CredentialsForbidden);
        }
        if base.query().is_some() {
            return Err(EndpointError::QueryForbidden);
        }
        if base.fragment().is_some() {
            return Err(EndpointError::FragmentForbidden);
        }
        if base.path() != "/" && base.path().ends_with('/') {
            return Err(EndpointError::TrailingSlash);
        }

        let mut prefix = String::from(base.as_str());
        if base.path() == "/" {
            prefix.pop();
        }
        let endpoint = Self { base, prefix };
        endpoint
            .identity()
            .map_err(|_| EndpointError::IdentityRejected)?;
        Ok(endpoint)
    }

    /// Returns the normalized scheme, host, effective port, and base path.
    pub fn identity(&self) -> Result<EndpointIdentity<'_>, EndpointIdentityError> {
        let scheme = match self.base.scheme() {
            "https" => EndpointScheme::Https,
            "http" => EndpointScheme::Http,
            _ => return Err(EndpointIdentityError::InvalidBasePath),
        };
        let host = self
            .base
            .host_str()
            .ok_or(EndpointIdentityError::EmptyHost)?;
        let port = self
            .base
            .port_or_known_default()
            .ok_or(EndpointIdentityError::InvalidPort)?;
        EndpointIdentity::new(scheme, host, port, self.base.path())
    }

    pub(crate) fn compose(&self, target: RequestTarget<'_>) -> Result<Url, EndpointError> {
        let mut absolute = self.prefix.clone();
        absolute
            .try_reserve_exact(target.as_str().len())
            .map_err(|_| EndpointError::AllocationFailed)?;
        absolute.push_str(target.as_str());
        let url = Url::parse(&absolute).map_err(|_| EndpointError::InvalidUrl)?;
        if url.as_str() != absolute {
            return Err(EndpointError::TargetNormalized);
        }
        self.verify_origin(&url)?;
        Ok(url)
    }

    pub(crate) fn verify_origin(&self, url: &Url) -> Result<(), EndpointError> {
        if url.scheme() != self.base.scheme()
            || url.host_str() != self.base.host_str()
            || url.port_or_known_default() != self.base.port_or_known_default()
            || !url.username().is_empty()
            || url.password().is_some()
        {
            return Err(EndpointError::TargetNormalized);
        }
        Ok(())
    }

    #[cfg(test)]
    pub(crate) fn local_http(value: &str) -> Result<Self, EndpointError> {
        let endpoint = Self::new_inner(value, false)?;
        if endpoint.base.scheme() != "http"
            || !endpoint.base.host().is_some_and(|host| {
                let text = host.to_string();
                text.strip_prefix('[')
                    .and_then(|value| value.strip_suffix(']'))
                    .unwrap_or(&text)
                    .parse::<std::net::IpAddr>()
                    .is_ok_and(|ip| ip.is_loopback())
            })
        {
            return Err(EndpointError::HttpsRequired);
        }
        Ok(endpoint)
    }
}

fn validate_raw_authority(value: &str) -> Result<(), EndpointError> {
    let (scheme, remainder) = value.split_once("://").ok_or(EndpointError::InvalidUrl)?;
    if scheme.is_empty()
        || !scheme.is_ascii()
        || scheme.bytes().any(|byte| byte.is_ascii_uppercase())
    {
        return Err(EndpointError::AmbiguousAuthority);
    }
    let authority_end = remainder.find(['/', '?', '#']).unwrap_or(remainder.len());
    let authority = remainder
        .get(..authority_end)
        .ok_or(EndpointError::AmbiguousAuthority)?;
    if authority.is_empty() {
        return Err(EndpointError::MissingHost);
    }
    if authority.contains('@') {
        return Err(EndpointError::CredentialsForbidden);
    }
    if !authority.is_ascii() || authority.contains(['%', '\\']) {
        return Err(EndpointError::AmbiguousAuthority);
    }

    let (host, port) = split_host_port(authority)?;
    if host.bytes().any(|byte| byte.is_ascii_uppercase()) {
        return Err(EndpointError::AmbiguousAuthority);
    }
    if let Some(port) = port
        && (port.is_empty()
            || !port.bytes().all(|byte| byte.is_ascii_digit())
            || port.len() > 1 && port.starts_with('0')
            || port
                .parse::<u16>()
                .ok()
                .filter(|value| *value != 0)
                .is_none())
    {
        return Err(EndpointError::AmbiguousAuthority);
    }
    EndpointIdentity::new(EndpointScheme::Https, host, 1, "/")
        .map(|_| ())
        .map_err(|_| EndpointError::AmbiguousAuthority)
}

fn split_host_port(authority: &str) -> Result<(&str, Option<&str>), EndpointError> {
    if authority.starts_with('[') {
        let close = authority
            .find(']')
            .ok_or(EndpointError::AmbiguousAuthority)?;
        let host_end = close
            .checked_add(1)
            .ok_or(EndpointError::AmbiguousAuthority)?;
        let host = authority
            .get(..host_end)
            .ok_or(EndpointError::AmbiguousAuthority)?;
        let suffix = authority
            .get(host_end..)
            .ok_or(EndpointError::AmbiguousAuthority)?;
        if suffix.is_empty() {
            return Ok((host, None));
        }
        let port = suffix
            .strip_prefix(':')
            .ok_or(EndpointError::AmbiguousAuthority)?;
        return Ok((host, Some(port)));
    }
    if authority.matches(':').count() > 1 {
        return Err(EndpointError::AmbiguousAuthority);
    }
    Ok(match authority.rsplit_once(':') {
        Some((host, port)) => (host, Some(port)),
        None => (authority, None),
    })
}

fn validate_configured_base_path(value: &str) -> Result<&str, EndpointError> {
    let (_, authority_and_path) = value.split_once("://").ok_or(EndpointError::InvalidUrl)?;
    let suffix_start = authority_and_path
        .find(['/', '?', '#'])
        .unwrap_or(authority_and_path.len());
    let suffix = authority_and_path
        .get(suffix_start..)
        .ok_or(EndpointError::IdentityRejected)?;
    let path = if suffix.starts_with('/') {
        let path_end = suffix.find(['?', '#']).unwrap_or(suffix.len());
        suffix
            .get(..path_end)
            .ok_or(EndpointError::IdentityRejected)?
    } else {
        "/"
    };
    if path.len() > MAX_ENDPOINT_BASE_PATH_BYTES
        || path.contains("//")
        || path.split('/').any(|part| matches!(part, "." | ".."))
        || !path
            .bytes()
            .all(|byte| byte.is_ascii_graphic() && !matches!(byte, b'\\' | b'%' | b'?' | b'#'))
    {
        return Err(EndpointError::IdentityRejected);
    }
    Ok(path)
}

#[cfg(test)]
mod link_local_tests {
    use cloud_sdk::transport::{EndpointIdentity, EndpointPolicy, EndpointScheme};

    use super::{EndpointError, LinkLocalHttpEndpoint};

    #[test]
    fn link_local_http_requires_exact_provider_policy() {
        let identity = EndpointIdentity::new(EndpointScheme::Http, "169.254.169.254", 80, "/")
            .unwrap_or_else(|_| unreachable!("valid fixed endpoint"));
        let policy = EndpointPolicy::fixed(identity);
        let endpoint = LinkLocalHttpEndpoint::new_with_policy("http://169.254.169.254", policy);
        let Ok(endpoint) = endpoint else {
            unreachable!("fixed link-local endpoint was rejected");
        };
        assert_eq!(endpoint.identity(), Ok(identity));

        for value in [
            "https://169.254.169.254",
            "http://10.0.0.1",
            "http://169.254.169.253",
            "http://169.254.169.254:81",
            "http://169.254.169.254/2009-04-04/meta-data",
        ] {
            assert!(matches!(
                LinkLocalHttpEndpoint::new_with_policy(value, policy),
                Err(EndpointError::PolicyRejected)
            ));
        }
    }
}