Skip to main content

object_store/
remote_access.rs

1// Copyright 2023 Greptime Team
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! Access policy for object storage locations supplied by SQL statements.
16
17use std::sync::Arc;
18
19use common_telemetry::warn;
20use http::{Request, Response};
21use opendal::{
22    Buffer, Error, ErrorKind, HttpBody, HttpRedirect, HttpTransport, HttpTransporter,
23    OperationContext,
24};
25use opendal_http_transport_reqwest::ReqwestTransport;
26use snafu::ResultExt;
27use url::Url;
28
29use crate::ObjectStore;
30use crate::error::{self, Result};
31
32/// How object stores built from SQL statements, such as `COPY`, `COPY DATABASE`,
33/// `EXPORT/IMPORT DATABASE` and external tables, may reach storage.
34#[derive(Clone, Debug)]
35pub struct RemoteStorageAccess {
36    /// Operation context with the restricted HTTP transport, if allowed hosts are set.
37    restricted_context: Option<OperationContext>,
38    allow_server_credentials: bool,
39}
40
41impl RemoteStorageAccess {
42    /// No host restriction, and server credentials are allowed.
43    pub fn unrestricted() -> Self {
44        Self {
45            restricted_context: None,
46            allow_server_credentials: true,
47        }
48    }
49
50    /// Creates the access policy. An empty `allowed_hosts` means no host restriction.
51    pub fn new(allowed_hosts: &[String], allow_server_credentials: bool) -> Result<Self> {
52        let restricted_context = if allowed_hosts.is_empty() {
53            None
54        } else {
55            let allowlist = HostAllowlist::parse(allowed_hosts)?;
56            // Redirects are not followed, otherwise the client could reach a host
57            // that was never checked. Other settings match the default transport
58            // used for SQL object stores without a restriction.
59            let client = reqwest::Client::builder()
60                .redirect(reqwest::redirect::Policy::none())
61                .build()
62                .context(error::BuildHttpClientSnafu)?;
63            let transport = AllowlistTransport {
64                inner: ReqwestTransport::new(client),
65                allowlist: Arc::new(allowlist),
66            };
67            Some(OperationContext::new().with_http_transport(HttpTransporter::new(transport)))
68        };
69        Ok(Self {
70            restricted_context,
71            allow_server_credentials,
72        })
73    }
74
75    /// Makes `store` send its requests through the restricted transport, if any.
76    pub fn apply(&self, store: ObjectStore) -> ObjectStore {
77        match &self.restricted_context {
78            Some(context) => store.with_context(context.clone()),
79            None => store,
80        }
81    }
82
83    /// Whether a store whose connection options carry no credentials may fall back to the
84    /// server's own credentials.
85    pub fn allow_server_credentials(&self) -> bool {
86        self.allow_server_credentials
87    }
88}
89
90#[derive(Debug, Clone, PartialEq, Eq)]
91enum HostPattern {
92    Exact(String),
93    /// Matches any subdomain of the domain, not the domain itself.
94    Subdomain(String),
95}
96
97#[derive(Debug, Clone, PartialEq, Eq)]
98struct AllowedHost {
99    host: HostPattern,
100    /// `None` matches any port.
101    port: Option<u16>,
102}
103
104/// Hosts that SQL object stores may connect to.
105///
106/// Entries are `host`, `host:port`, `*.domain` or `*.domain:port`. IPv6 addresses
107/// are written in brackets, e.g. `[::1]:9000`. Hosts are normalized the same way
108/// as request URLs, so `127.1` and `127.0.0.1` are the same host.
109#[derive(Debug, Clone)]
110pub(crate) struct HostAllowlist {
111    entries: Vec<AllowedHost>,
112}
113
114impl HostAllowlist {
115    pub(crate) fn parse(entries: &[String]) -> Result<Self> {
116        let entries = entries
117            .iter()
118            .map(|entry| {
119                parse_allowed_host(entry).map_err(|reason| {
120                    error::InvalidAllowedHostSnafu {
121                        entry: entry.clone(),
122                        reason,
123                    }
124                    .build()
125                })
126            })
127            .collect::<Result<Vec<_>>>()?;
128        Ok(Self { entries })
129    }
130
131    /// Checks the URL a request is sent to.
132    fn check(&self, target: &str) -> opendal::Result<()> {
133        let url = Url::parse(target).map_err(|err| {
134            Error::new(ErrorKind::PermissionDenied, "request URL is invalid").set_source(err)
135        })?;
136        let (Some(host), Some(port)) = (url.host_str(), url.port_or_known_default()) else {
137            return Err(Error::new(
138                ErrorKind::PermissionDenied,
139                "request URL has no host or port",
140            ));
141        };
142        let is_domain = matches!(url.host(), Some(url::Host::Domain(_)));
143        let allowed = self.entries.iter().any(|entry| {
144            let host_matches = match &entry.host {
145                HostPattern::Exact(expected) => host == expected,
146                HostPattern::Subdomain(domain) => {
147                    is_domain
148                        && host
149                            .strip_suffix(domain.as_str())
150                            .is_some_and(|prefix| prefix.len() > 1 && prefix.ends_with('.'))
151                }
152            };
153            host_matches && entry.port.is_none_or(|expected| expected == port)
154        });
155        if allowed {
156            Ok(())
157        } else {
158            // Credential providers swallow this error and try the next one, so
159            // the log is the only trace of a blocked credential request.
160            warn!("Blocked request to {host}:{port}, not in query.remote_allowed_hosts");
161            Err(Error::new(
162                ErrorKind::PermissionDenied,
163                "host is not in query.remote_allowed_hosts",
164            )
165            .with_context("host", format!("{host}:{port}")))
166        }
167    }
168}
169
170fn parse_allowed_host(entry: &str) -> std::result::Result<AllowedHost, String> {
171    let entry = entry.trim();
172    let (wildcard, rest) = match entry.strip_prefix("*.") {
173        Some(rest) => (true, rest),
174        None => (false, entry),
175    };
176    if rest.is_empty() || rest.contains(['/', '\\', '@', '*', '?', '#']) {
177        return Err("expected `host`, `host:port` or `*.domain`".to_string());
178    }
179
180    let (host, port) = if rest.starts_with('[') {
181        let end = rest
182            .find(']')
183            .ok_or_else(|| "unterminated IPv6 address".to_string())?;
184        let port = &rest[end + 1..];
185        let port = if port.is_empty() {
186            None
187        } else {
188            Some(
189                port.strip_prefix(':')
190                    .ok_or_else(|| "unexpected characters after IPv6 address".to_string())?,
191            )
192        };
193        (&rest[..=end], port)
194    } else {
195        match rest.split_once(':') {
196            Some((host, port)) => (host, Some(port)),
197            None => (rest, None),
198        }
199    };
200    let port = port
201        .map(|port| {
202            port.parse::<u16>()
203                .map_err(|_| format!("invalid port `{port}`"))
204        })
205        .transpose()?;
206
207    let url = Url::parse(&format!("http://{host}/")).map_err(|err| err.to_string())?;
208    let normalized = url
209        .host_str()
210        .ok_or_else(|| "missing host".to_string())?
211        .to_string();
212    let host = if wildcard {
213        if !matches!(url.host(), Some(url::Host::Domain(_))) {
214            return Err("wildcard entries must use a domain name".to_string());
215        }
216        HostPattern::Subdomain(normalized)
217    } else {
218        HostPattern::Exact(normalized)
219    };
220    Ok(AllowedHost { host, port })
221}
222
223struct AllowlistTransport {
224    inner: ReqwestTransport,
225    allowlist: Arc<HostAllowlist>,
226}
227
228impl HttpTransport for AllowlistTransport {
229    async fn fetch(&self, req: Request<Buffer>) -> opendal::Result<Response<HttpBody>> {
230        self.allowlist.check(&req.uri().to_string())?;
231        // The reqwest transport sends the request to this URL instead of the
232        // request URI when a service attaches the extension.
233        if let Some(redirect) = req.extensions().get::<HttpRedirect>() {
234            self.allowlist.check(redirect.uri().original_uri())?;
235        }
236        self.inner.fetch(req).await
237    }
238}
239
240#[cfg(test)]
241mod tests {
242    use opendal::services::{Gcs, S3};
243
244    use super::*;
245    use crate::ObjectStore;
246    use crate::test_util::{MockHttpServer, http_response as response};
247
248    fn allowlist(entries: &[&str]) -> HostAllowlist {
249        HostAllowlist::parse(&entries.iter().map(|s| s.to_string()).collect::<Vec<_>>()).unwrap()
250    }
251
252    #[test]
253    fn test_allowlist_matching() {
254        let list = allowlist(&[
255            "S3.US-EAST-1.amazonaws.com",
256            "*.storage.example.com",
257            "minio.internal:9000",
258            "127.1:9000",
259            "[::1]:9001",
260        ]);
261        for allowed in [
262            "https://s3.us-east-1.amazonaws.com/bucket/key",
263            "http://s3.us-east-1.amazonaws.com:8080/",
264            "https://bucket.storage.example.com/key",
265            "https://a.b.storage.example.com/key",
266            "http://minio.internal:9000/bucket",
267            "http://127.0.0.1:9000/bucket",
268            "http://2130706433:9000/bucket",
269            "http://[::1]:9001/bucket",
270        ] {
271            assert!(list.check(allowed).is_ok(), "{allowed}");
272        }
273        for denied in [
274            "https://storage.example.com/key",
275            "https://evilstorage.example.com/key",
276            "https://storage.example.com.evil.com/key",
277            "http://minio.internal/bucket",
278            "http://minio.internal:9001/bucket",
279            "http://127.0.0.1:9001/bucket",
280            "http://169.254.169.254/latest/meta-data/",
281            "http://[::1]:9000/bucket",
282        ] {
283            let err = list.check(denied).unwrap_err();
284            assert_eq!(err.kind(), ErrorKind::PermissionDenied, "{denied}");
285        }
286    }
287
288    #[test]
289    fn test_allowlist_rejects_invalid_entries() {
290        for entry in [
291            "",
292            "http://example.com",
293            "example.com/path",
294            "user@example.com",
295            "*.127.0.0.1",
296            "*.[::1]",
297            "example.com:port",
298            "example.com:70000",
299            "[::1",
300            "[::1]9000",
301            "minio.internal\\evil.com",
302            "a*.example.com",
303        ] {
304            assert!(
305                HostAllowlist::parse(&[entry.to_string()]).is_err(),
306                "{entry}"
307            );
308        }
309    }
310
311    fn restricted(entries: &[String]) -> OperationContext {
312        RemoteStorageAccess::new(entries, true)
313            .unwrap()
314            .restricted_context
315            .unwrap()
316    }
317
318    fn s3_store(endpoint: Option<&str>, region: &str, ctx: OperationContext) -> ObjectStore {
319        let mut builder = S3::default()
320            .bucket("bucket")
321            .region(region)
322            .access_key_id("ak")
323            .secret_access_key("sk");
324        if let Some(endpoint) = endpoint {
325            builder = builder.endpoint(endpoint);
326        }
327        ObjectStore::new(builder).unwrap().with_context(ctx)
328    }
329
330    #[tokio::test]
331    async fn test_restricted_transport_targets() {
332        let allowed = MockHttpServer::start(|head| {
333            if head.starts_with("GET") {
334                response("200 OK", &[], "data")
335            } else {
336                response("200 OK", &[("etag", "\"e\"".to_string())], "")
337            }
338        })
339        .await;
340        let denied = MockHttpServer::start(|_| response("200 OK", &[], "secret")).await;
341        let (allowed_port, denied_port) = (allowed.port, denied.port);
342        let ctx = restricted(&[format!("127.0.0.1:{allowed_port}")]);
343
344        // An allowed target can be written and read.
345        let store = s3_store(
346            Some(&format!("http://127.0.0.1:{allowed_port}")),
347            "us-east-1",
348            ctx.clone(),
349        );
350        store.write("key", "data").await.unwrap();
351        assert_eq!(store.read("key").await.unwrap().to_vec(), b"data");
352        assert_eq!(allowed.request_count(), 2);
353
354        // Endpoint pointing to another port.
355        let store = s3_store(
356            Some(&format!("http://127.0.0.1:{denied_port}")),
357            "us-east-1",
358            ctx.clone(),
359        );
360        let err = store.read("key").await.unwrap_err();
361        assert_eq!(err.kind(), ErrorKind::PermissionDenied);
362
363        // Without an endpoint, the region is substituted into the default endpoint
364        // template, which can change the host.
365        let store = s3_store(None, &format!("x@127.0.0.1:{denied_port}/#"), ctx.clone());
366        let err = store.read("key").await.unwrap_err();
367        assert_eq!(err.kind(), ErrorKind::PermissionDenied);
368        assert_eq!(denied.request_count(), 0);
369    }
370
371    #[tokio::test]
372    async fn test_restricted_transport_checks_redirect_extension() {
373        let denied = MockHttpServer::start(|_| response("200 OK", &[], "secret")).await;
374        let allowed = MockHttpServer::start(|_| response("200 OK", &[], "data")).await;
375        let ctx = restricted(&[format!("127.0.0.1:{}", allowed.port)]);
376        let mut req = Request::get(format!("http://127.0.0.1:{}/key", allowed.port))
377            .body(Buffer::new())
378            .unwrap();
379        req.extensions_mut().insert(HttpRedirect::new(
380            format!("http://127.0.0.1:{}/key", denied.port)
381                .parse()
382                .unwrap(),
383        ));
384        let Err(err) = ctx.http_transport().fetch(req).await else {
385            panic!("the redirect target must be checked");
386        };
387        assert_eq!(err.kind(), ErrorKind::PermissionDenied);
388        assert_eq!(allowed.request_count() + denied.request_count(), 0);
389    }
390
391    #[tokio::test]
392    async fn test_restricted_transport_does_not_follow_redirects() {
393        let denied = MockHttpServer::start(|_| response("200 OK", &[], "secret")).await;
394        let location = format!("http://127.0.0.1:{}/bucket/key", denied.port);
395        let allowed = MockHttpServer::start(move |_| {
396            response("302 Found", &[("location", location.clone())], "")
397        })
398        .await;
399        let allowed_port = allowed.port;
400        let ctx = restricted(&[format!("127.0.0.1:{allowed_port}")]);
401        let store = s3_store(
402            Some(&format!("http://127.0.0.1:{allowed_port}")),
403            "us-east-1",
404            ctx,
405        );
406        assert!(store.read("key").await.is_err());
407        assert_eq!(allowed.request_count(), 1);
408        assert_eq!(denied.request_count(), 0);
409    }
410
411    #[tokio::test]
412    async fn test_restricted_transport_checks_gcs_resumable_upload_session() {
413        let denied = MockHttpServer::start(|_| response("200 OK", &[], "{}")).await;
414        let session = format!("http://127.0.0.1:{}/upload/session", denied.port);
415        let allowed = MockHttpServer::start(move |_| {
416            response("200 OK", &[("location", session.clone())], "")
417        })
418        .await;
419        let allowed_port = allowed.port;
420        let ctx = restricted(&[format!("127.0.0.1:{allowed_port}")]);
421        let builder = Gcs::default()
422            .bucket("bucket")
423            .endpoint(&format!("http://127.0.0.1:{allowed_port}"))
424            .skip_signature();
425        let store = ObjectStore::new(builder).unwrap().with_context(ctx);
426
427        // Conditional writes use resumable uploads, whose later requests go to
428        // the session URL from the `Location` header.
429        let result = store
430            .write_with("key", vec![0u8; 1024])
431            .if_not_exists(true)
432            .await;
433        assert_eq!(result.unwrap_err().kind(), ErrorKind::PermissionDenied);
434        // The upload session was created on the allowed host, but no data was
435        // sent to the session URL it returned.
436        assert_eq!(allowed.request_count(), 1);
437        assert_eq!(denied.request_count(), 0);
438    }
439}