Skip to main content

common_datasource/object_store/
gcs.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
15use std::collections::HashMap;
16
17use base64::Engine;
18use base64::prelude::BASE64_STANDARD;
19use object_store::ObjectStore;
20use object_store::remote_access::RemoteStorageAccess;
21use object_store::services::Gcs;
22use serde::Deserialize;
23
24use crate::error::{self, Result};
25use crate::object_store::{
26    connection_value, ensure_server_credentials_allowed, finish_remote_backend,
27};
28
29const ENDPOINT: &str = "endpoint";
30const CREDENTIAL: &str = "credential";
31const SCOPE: &str = "scope";
32
33pub fn is_supported_in_gcs(key: &str) -> bool {
34    [ENDPOINT, CREDENTIAL, SCOPE].contains(&key)
35}
36
37pub fn build_gcs_backend(
38    bucket: &str,
39    root: &str,
40    connection: &HashMap<String, String>,
41    remote_storage_access: &RemoteStorageAccess,
42) -> Result<ObjectStore> {
43    let mut builder = Gcs::default().root(root).bucket(bucket);
44
45    if let Some(scope) = connection.get(SCOPE) {
46        builder = builder.scope(scope);
47    }
48
49    if let Some(credential) = connection_value(connection, CREDENTIAL) {
50        let credential = service_account_credential(credential)?;
51        // The rebuilt credential always yields a provider. Disabling config
52        // load and VM metadata also empties the default chain behind it, in
53        // case reqsign ever parses the credential differently.
54        builder = builder
55            .credential(&credential)
56            .disable_config_load()
57            .disable_vm_metadata();
58    } else {
59        ensure_server_credentials_allowed(remote_storage_access, "GCS")?;
60    }
61
62    if let Some(endpoint) = connection.get(ENDPOINT) {
63        builder = builder.endpoint(endpoint);
64    }
65
66    finish_remote_backend(builder, remote_storage_access)
67}
68
69/// The credential file shape reqsign parses, limited to service account keys.
70///
71/// Other credential types make the server read local files, expand environment
72/// variables or call URLs taken from the credential.
73#[derive(Deserialize)]
74#[serde(tag = "type", rename_all = "snake_case")]
75enum CredentialFile {
76    ServiceAccount(ServiceAccountKey),
77}
78
79#[derive(Deserialize)]
80struct ServiceAccountKey {
81    private_key: String,
82    client_email: String,
83}
84
85/// Validates a service account key and rebuilds it with only the fields used
86/// for signing, so other fields such as `token_uri` never reach reqsign.
87fn service_account_credential(credential: &str) -> Result<String> {
88    // Errors must not include the decoded content, which holds a private key.
89    let key = BASE64_STANDARD
90        .decode(credential)
91        .ok()
92        .and_then(|decoded| serde_json::from_slice::<CredentialFile>(&decoded).ok())
93        .map(|CredentialFile::ServiceAccount(key)| key)
94        .filter(|key| !key.private_key.is_empty() && !key.client_email.is_empty());
95    if let Some(key) = key {
96        let rebuilt = serde_json::json!({
97            "type": "service_account",
98            "private_key": key.private_key,
99            "client_email": key.client_email,
100        });
101        Ok(BASE64_STANDARD.encode(rebuilt.to_string()))
102    } else {
103        error::InvalidConnectionSnafu {
104            msg: format!(
105                "{CREDENTIAL} must be a base64-encoded service_account key with private_key and client_email"
106            ),
107        }
108        .fail()
109    }
110}
111
112#[cfg(test)]
113mod tests {
114    use super::*;
115
116    #[test]
117    fn test_service_account_credential() {
118        let encode = |json: &str| BASE64_STANDARD.encode(json);
119        let rebuilt = service_account_credential(&encode(
120            r#"{"type":"service_account","private_key":"key","client_email":"a@b.iam.gserviceaccount.com","token_uri":"https://example.com"}"#,
121        ))
122        .unwrap();
123        let rebuilt: serde_json::Value =
124            serde_json::from_slice(&BASE64_STANDARD.decode(rebuilt).unwrap()).unwrap();
125        assert_eq!(
126            rebuilt,
127            serde_json::json!({
128                "type": "service_account",
129                "private_key": "key",
130                "client_email": "a@b.iam.gserviceaccount.com",
131            })
132        );
133        for invalid in [
134            "not base64".to_string(),
135            encode("not json"),
136            encode(r#"{"private_key":"key","client_email":"a@b"}"#),
137            encode(r#"{"type":"service_account","private_key":"key"}"#),
138            encode(r#"{"type":"service_account","private_key":"","client_email":"a@b"}"#),
139            encode(
140                r#"{"type":"external_account","audience":"a","subject_token_type":"t","token_url":"http://127.0.0.1/","credential_source":{"file":"/etc/passwd"}}"#,
141            ),
142            encode(
143                r#"{"type":"authorized_user","client_id":"a","client_secret":"b","refresh_token":"c"}"#,
144            ),
145        ] {
146            let err = service_account_credential(&invalid).unwrap_err();
147            assert!(!err.to_string().contains("/etc/passwd"));
148        }
149    }
150
151    #[test]
152    fn test_is_supported_in_gcs() {
153        assert!(is_supported_in_gcs(ENDPOINT));
154        assert!(is_supported_in_gcs(CREDENTIAL));
155        assert!(is_supported_in_gcs(SCOPE));
156        assert!(!is_supported_in_gcs("foo"));
157    }
158}