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
use tink_core::{utils::wrap_err, TinkError};
pub const GCP_PREFIX: &str = "gcp-kms://";
pub struct GcpClient {
key_uri_prefix: String,
sa_key: Option<yup_oauth2::ServiceAccountKey>,
}
impl GcpClient {
pub fn new(uri_prefix: &str) -> Result<GcpClient, TinkError> {
if !uri_prefix.to_lowercase().starts_with(GCP_PREFIX) {
return Err(format!("uri_prefix must start with {}", GCP_PREFIX).into());
}
Ok(GcpClient {
key_uri_prefix: uri_prefix.to_string(),
sa_key: None,
})
}
pub fn new_with_credentials(
uri_prefix: &str,
credential_path: &std::path::Path,
) -> Result<GcpClient, TinkError> {
if !uri_prefix.to_lowercase().starts_with(GCP_PREFIX) {
return Err(format!("uri_prefix must start with {}", GCP_PREFIX).into());
}
let credential_path = credential_path.to_string_lossy();
if credential_path.is_empty() {
return Err("invalid credential path".into());
}
let data = std::fs::read(credential_path.as_ref())
.map_err(|e| wrap_err("failed to read credentials", e))?;
let sa_key: yup_oauth2::ServiceAccountKey = serde_json::from_slice(&data)
.map_err(|e| wrap_err("failed to decode credentials", e))?;
Ok(GcpClient {
key_uri_prefix: uri_prefix.to_string(),
sa_key: Some(sa_key),
})
}
}
impl tink_core::registry::KmsClient for GcpClient {
fn supported(&self, key_uri: &str) -> bool {
key_uri.starts_with(&self.key_uri_prefix)
}
fn get_aead(&self, key_uri: &str) -> Result<Box<dyn tink_core::Aead>, tink_core::TinkError> {
if !self.supported(key_uri) {
return Err("unsupported key_uri".into());
}
let uri = if let Some(rest) = key_uri.strip_prefix(GCP_PREFIX) {
rest
} else {
key_uri
};
Ok(Box::new(crate::GcpAead::new(uri, &self.sa_key)?))
}
}