1use gaxi::grpc::tonic::transport::{Certificate, ClientTlsConfig, Identity};
18use std::fs;
19use std::io::Error as IoError;
20use std::path::Path;
21use thiserror::Error;
22use url::Url;
23
24#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
26#[non_exhaustive]
27pub enum InstanceType {
28 #[default]
30 Cloud,
31 Omni,
33}
34
35#[derive(Clone, Debug, Default, PartialEq, Eq)]
37pub struct TlsConfig {
38 root_certificate: Option<Vec<u8>>,
39 client_certificate: Option<Vec<u8>>,
40 client_private_key: Option<Vec<u8>>,
41 domain_name_override: Option<String>,
42}
43
44impl TlsConfig {
45 pub fn new() -> Self {
54 Self::default()
55 }
56
57 pub fn with_root_certificate_pem(mut self, root_certificate_pem: impl Into<Vec<u8>>) -> Self {
66 self.root_certificate = Some(root_certificate_pem.into());
67 self
68 }
69
70 pub fn with_root_certificate_file(self, path: impl AsRef<Path>) -> Result<Self, TlsError> {
83 let root_certificate_bytes = fs::read(path)?;
84 Ok(self.with_root_certificate_pem(root_certificate_bytes))
85 }
86
87 pub fn with_client_certificate_pem(
97 mut self,
98 client_certificate_pem: impl Into<Vec<u8>>,
99 client_private_key_pem: impl Into<Vec<u8>>,
100 ) -> Self {
101 self.client_certificate = Some(client_certificate_pem.into());
102 self.client_private_key = Some(client_private_key_pem.into());
103 self
104 }
105
106 pub fn with_client_certificate_file(
120 self,
121 certificate_path: impl AsRef<Path>,
122 private_key_path: impl AsRef<Path>,
123 ) -> Result<Self, TlsError> {
124 let certificate_bytes = fs::read(certificate_path)?;
125 let private_key_bytes = fs::read(private_key_path)?;
126 Ok(self.with_client_certificate_pem(certificate_bytes, private_key_bytes))
127 }
128
129 pub fn with_domain_name_override(mut self, domain_name: impl Into<String>) -> Self {
137 self.domain_name_override = Some(domain_name.into());
138 self
139 }
140
141 pub fn root_certificate(&self) -> Option<&[u8]> {
143 self.root_certificate.as_deref()
144 }
145
146 pub fn client_certificate(&self) -> Option<&[u8]> {
148 self.client_certificate.as_deref()
149 }
150
151 pub fn client_private_key(&self) -> Option<&[u8]> {
153 self.client_private_key.as_deref()
154 }
155
156 pub fn domain_name_override(&self) -> Option<&str> {
158 self.domain_name_override.as_deref()
159 }
160
161 pub fn has_custom_certificates(&self) -> bool {
163 self.root_certificate.is_some()
164 || self.client_certificate.is_some()
165 || self.client_private_key.is_some()
166 }
167
168 pub fn validate(&self) -> Result<(), TlsError> {
174 match (&self.client_certificate, &self.client_private_key) {
175 (Some(_), None) => Err(TlsError::MissingClientKey),
176 (None, Some(_)) => Err(TlsError::MissingClientCertificate),
177 _ => Ok(()),
178 }
179 }
180
181 pub(crate) fn to_tonic_client_tls_config(&self) -> Option<ClientTlsConfig> {
183 if !self.has_custom_certificates() && self.domain_name_override.is_none() {
184 return None;
185 }
186
187 let mut tls = ClientTlsConfig::new();
188 if let Some(root_certificate) = &self.root_certificate {
189 let certificate = Certificate::from_pem(root_certificate);
190 tls = tls.ca_certificate(certificate);
191 } else {
192 tls = tls.with_enabled_roots();
193 }
194 if let Some(client_certificate) = &self.client_certificate
195 && let Some(client_private_key) = &self.client_private_key
196 {
197 let identity = Identity::from_pem(client_certificate, client_private_key);
198 tls = tls.identity(identity);
199 }
200 if let Some(domain_name) = &self.domain_name_override {
201 tls = tls.domain_name(domain_name);
202 }
203 Some(tls)
204 }
205}
206
207#[derive(Debug, Error)]
209#[non_exhaustive]
210pub enum TlsError {
211 #[error("client certificate was provided without a client private key for mTLS")]
213 MissingClientKey,
214
215 #[error("client private key was provided without a client certificate for mTLS")]
217 MissingClientCertificate,
218
219 #[error("cannot use plaintext connection and provide TLS certificates at the same time")]
221 PlaintextWithTls,
222
223 #[error("failed to read certificate or key file: {0}")]
225 Io(#[from] IoError),
226}
227
228pub(crate) fn is_plaintext_endpoint(endpoint: &str) -> bool {
230 let trimmed = endpoint.trim();
231 match Url::parse(trimmed) {
232 Ok(url) => url.scheme() != "https",
233 Err(_) => !trimmed
234 .get(..8)
235 .is_some_and(|s| s.eq_ignore_ascii_case("https://")),
236 }
237}
238
239pub(crate) fn format_database_name(name: &str) -> String {
243 let trimmed = name.trim();
244 if trimmed.is_empty() {
245 return trimmed.to_string();
246 }
247
248 let parts: Vec<&str> = trimmed.split('/').collect();
249 match parts.as_slice() {
250 [
251 "projects",
252 _project,
253 "instances",
254 _instance,
255 "databases",
256 _database,
257 ] => trimmed.to_string(),
258 ["instances", instance, "databases", database] => {
259 format!(
260 "projects/default/instances/{}/databases/{}",
261 instance, database
262 )
263 }
264 ["databases", database] => {
265 format!("projects/default/instances/default/databases/{}", database)
266 }
267 [database] => {
268 format!("projects/default/instances/default/databases/{}", database)
269 }
270 _ => trimmed.to_string(),
271 }
272}
273
274#[cfg(test)]
275mod tests {
276 use super::*;
277 use crate::client::{Spanner, SpannerBuilderExt};
278 use static_assertions::assert_impl_all;
279 use std::env::temp_dir;
280 use std::error::Error as StdError;
281 use std::fmt::Debug;
282 use std::path::PathBuf;
283
284 const SAMPLE_CA_PEM: &[u8] = include_bytes!("../../../testdata/tls/ca_cert.pem");
285 const SAMPLE_CERT_PEM: &[u8] = include_bytes!("../../../testdata/tls/server_cert.pem");
286 const SAMPLE_KEY_PEM: &[u8] = include_bytes!("../../../testdata/tls/server_key.pem");
287
288 #[test]
289 fn traits() {
290 assert_impl_all!(InstanceType: Send, Sync, Debug, Clone, Copy, PartialEq, Eq);
291 assert_impl_all!(TlsConfig: Send, Sync, Debug, Clone, Default, PartialEq, Eq);
292 assert_impl_all!(TlsError: Send, Sync, Debug, StdError);
293 }
294
295 #[test]
296 fn format_database_name_resolution() {
297 assert_eq!(
298 format_database_name("projects/p/instances/i/databases/d"),
299 "projects/p/instances/i/databases/d"
300 );
301 assert_eq!(
302 format_database_name("instances/i/databases/d"),
303 "projects/default/instances/i/databases/d"
304 );
305 assert_eq!(
306 format_database_name("databases/d"),
307 "projects/default/instances/default/databases/d"
308 );
309 assert_eq!(
310 format_database_name("retail-sample"),
311 "projects/default/instances/default/databases/retail-sample"
312 );
313 assert_eq!(format_database_name(""), "");
314 }
315
316 #[test]
317 fn plaintext_endpoint_detection() {
318 assert!(is_plaintext_endpoint("http://localhost:15000"));
319 assert!(is_plaintext_endpoint("HTTP://localhost:15000"));
320 assert!(!is_plaintext_endpoint("https://spanner.internal:15000"));
321 assert!(!is_plaintext_endpoint("HTTPS://spanner.internal:15000"));
322 assert!(is_plaintext_endpoint("127.0.0.1:15000"));
323 assert!(is_plaintext_endpoint("localhost:15000"));
324 assert!(is_plaintext_endpoint("http://not a valid url:1234"));
325 assert!(!is_plaintext_endpoint("https://not a valid url:1234"));
326 assert!(!is_plaintext_endpoint("HTTPS://not a valid url:1234"));
327 assert!(is_plaintext_endpoint(""));
328 assert!(is_plaintext_endpoint("a"));
329 assert!(is_plaintext_endpoint("https:"));
330 assert!(is_plaintext_endpoint("🦀"));
331 }
332
333 fn create_test_temp_dir() -> PathBuf {
334 let path = temp_dir().join(format!("spanner-omni-test-{}", rand::random::<u64>()));
335 fs::create_dir_all(&path).expect("failed to create temporary test directory");
336 path
337 }
338
339 #[test]
340 fn tls_config_empty_is_valid() {
341 let config = TlsConfig::new();
342 assert!(!config.has_custom_certificates());
343 assert!(config.root_certificate().is_none());
344 assert!(config.client_certificate().is_none());
345 assert!(config.client_private_key().is_none());
346 assert!(config.domain_name_override().is_none());
347 assert!(config.validate().is_ok());
348 assert!(config.to_tonic_client_tls_config().is_none());
349 }
350
351 #[test]
352 fn tls_config_with_domain_name_override_only() {
353 let config = TlsConfig::new().with_domain_name_override("spanner.internal");
354 assert!(!config.has_custom_certificates());
355 assert_eq!(config.domain_name_override(), Some("spanner.internal"));
356 assert!(config.validate().is_ok());
357 assert!(config.to_tonic_client_tls_config().is_some());
358 }
359
360 #[test]
361 fn tls_config_with_root_ca_pem() {
362 let config = TlsConfig::new().with_root_certificate_pem(SAMPLE_CA_PEM);
363 assert!(config.has_custom_certificates());
364 assert_eq!(config.root_certificate(), Some(SAMPLE_CA_PEM));
365 assert!(config.validate().is_ok());
366 assert!(config.to_tonic_client_tls_config().is_some());
367 }
368
369 #[test]
370 fn tls_config_with_root_ca_file() {
371 let test_temp_dir = create_test_temp_dir();
372 let ca_path = test_temp_dir.join("ca.pem");
373 fs::write(&ca_path, SAMPLE_CA_PEM).expect("write ca.pem");
374
375 let config = TlsConfig::new()
376 .with_root_certificate_file(&ca_path)
377 .expect("load root certificate file");
378 assert_eq!(config.root_certificate(), Some(SAMPLE_CA_PEM));
379 assert!(config.validate().is_ok());
380 let _ = fs::remove_dir_all(&test_temp_dir);
381 }
382
383 #[test]
384 fn tls_config_with_root_ca_missing_file_fails() {
385 let result = TlsConfig::new().with_root_certificate_file("/nonexistent/path/to/ca.pem");
386 assert!(
387 result.is_err(),
388 "expected error when Root CA file does not exist"
389 );
390 }
391
392 #[test]
393 fn tls_config_with_mtls_pem() {
394 let config = TlsConfig::new()
395 .with_root_certificate_pem(SAMPLE_CA_PEM)
396 .with_client_certificate_pem(SAMPLE_CERT_PEM, SAMPLE_KEY_PEM)
397 .with_domain_name_override("spanner.internal");
398
399 assert!(config.has_custom_certificates());
400 assert_eq!(config.root_certificate(), Some(SAMPLE_CA_PEM));
401 assert_eq!(config.client_certificate(), Some(SAMPLE_CERT_PEM));
402 assert_eq!(config.client_private_key(), Some(SAMPLE_KEY_PEM));
403 assert_eq!(config.domain_name_override(), Some("spanner.internal"));
404 assert!(config.validate().is_ok());
405 assert!(config.to_tonic_client_tls_config().is_some());
406 }
407
408 #[test]
409 fn tls_config_with_mtls_files() {
410 let test_temp_dir = create_test_temp_dir();
411 let cert_path = test_temp_dir.join("client.pem");
412 let key_path = test_temp_dir.join("client.key");
413 fs::write(&cert_path, SAMPLE_CERT_PEM).expect("write client.pem");
414 fs::write(&key_path, SAMPLE_KEY_PEM).expect("write client.key");
415
416 let config = TlsConfig::new()
417 .with_client_certificate_file(&cert_path, &key_path)
418 .expect("load client certificate and key files");
419
420 assert_eq!(config.client_certificate(), Some(SAMPLE_CERT_PEM));
421 assert_eq!(config.client_private_key(), Some(SAMPLE_KEY_PEM));
422 assert!(config.validate().is_ok());
423 let _ = fs::remove_dir_all(&test_temp_dir);
424 }
425
426 #[test]
427 fn tls_config_client_cert_without_key_fails_validation() {
428 let mut config = TlsConfig::new();
429 config.client_certificate = Some(SAMPLE_CERT_PEM.to_vec());
430 let validation_result = config.validate();
431 assert!(
432 matches!(validation_result, Err(TlsError::MissingClientKey)),
433 "expected MissingClientKey, got {:?}",
434 validation_result
435 );
436 }
437
438 #[test]
439 fn tls_config_client_key_without_cert_fails_validation() {
440 let mut config = TlsConfig::new();
441 config.client_private_key = Some(SAMPLE_KEY_PEM.to_vec());
442 let validation_result = config.validate();
443 assert!(
444 matches!(validation_result, Err(TlsError::MissingClientCertificate)),
445 "expected MissingClientCertificate, got {:?}",
446 validation_result
447 );
448 }
449
450 #[test]
451 fn tls_config_missing_client_cert_file_fails() {
452 let test_temp_dir = create_test_temp_dir();
453 let key_path = test_temp_dir.join("client.key");
454 fs::write(&key_path, SAMPLE_KEY_PEM).expect("write client.key");
455
456 let result =
457 TlsConfig::new().with_client_certificate_file("/nonexistent/client.pem", &key_path);
458 assert!(
459 result.is_err(),
460 "expected error when client certificate file does not exist"
461 );
462 let _ = fs::remove_dir_all(&test_temp_dir);
463 }
464
465 #[test]
466 fn tls_config_missing_client_key_file_fails() {
467 let test_temp_dir = create_test_temp_dir();
468 let cert_path = test_temp_dir.join("client.pem");
469 fs::write(&cert_path, SAMPLE_CERT_PEM).expect("write client.pem");
470
471 let result =
472 TlsConfig::new().with_client_certificate_file(&cert_path, "/nonexistent/client.key");
473 assert!(
474 result.is_err(),
475 "expected error when client private key file does not exist"
476 );
477 let _ = fs::remove_dir_all(&test_temp_dir);
478 }
479
480 #[tokio::test]
481 async fn spanner_with_instance_type() {
482 let spanner = Spanner::builder()
483 .with_instance_type(InstanceType::Omni)
484 .build()
485 .await
486 .expect("build client");
487 assert_eq!(spanner.instance_type(), InstanceType::Omni);
488 }
489
490 #[tokio::test]
491 async fn spanner_with_omni_tls_automatically_sets_omni_instance_type() {
492 let tls_config = TlsConfig::new().with_root_certificate_pem(SAMPLE_CA_PEM);
493 let spanner = Spanner::builder()
494 .with_endpoint("https://spanner.internal:15000")
495 .with_omni_tls(tls_config)
496 .build()
497 .await
498 .expect("build client");
499 assert_eq!(spanner.instance_type(), InstanceType::Omni);
500 }
501
502 #[tokio::test]
503 async fn spanner_builder_with_omni_tls_populates_tonic_tls_extension() {
504 let tls_config = TlsConfig::new()
505 .with_root_certificate_pem(SAMPLE_CA_PEM)
506 .with_client_certificate_pem(SAMPLE_CERT_PEM, SAMPLE_KEY_PEM)
507 .with_domain_name_override("spanner.internal");
508 let spanner = Spanner::builder()
509 .with_endpoint("https://spanner.internal:15000")
510 .with_omni_tls(tls_config)
511 .build()
512 .await
513 .expect("build client");
514 assert_eq!(spanner.instance_type(), InstanceType::Omni);
515 assert!(
516 spanner.config.extensions.get::<ClientTlsConfig>().is_some(),
517 "expected ClientTlsConfig to be inserted into extensions for transport channel"
518 );
519 }
520
521 #[tokio::test]
522 async fn spanner_plaintext_endpoint_with_tls_certificates_fails() {
523 let tls_config = TlsConfig::new().with_root_certificate_pem(SAMPLE_CA_PEM);
524 let result = Spanner::builder()
525 .with_endpoint("http://localhost:15000")
526 .with_omni_tls(tls_config)
527 .build()
528 .await;
529 assert!(
530 result.is_err(),
531 "expected error when combining plaintext endpoint with TLS certificates"
532 );
533 }
534
535 #[tokio::test]
536 async fn spanner_invalid_tls_config_fails_build() {
537 let mut invalid_tls_config = TlsConfig::new();
538 invalid_tls_config.client_certificate = Some(SAMPLE_CERT_PEM.to_vec());
539 let result = Spanner::builder()
540 .with_omni_tls(invalid_tls_config)
541 .build()
542 .await;
543 assert!(
544 result.is_err(),
545 "expected builder error when TLS configuration fails validation"
546 );
547 }
548
549 #[tokio::test]
550 #[ignore = "requires live Omni instance at localhost:15000"]
551 async fn query_local_omni_instance() {
552 let spanner = Spanner::builder()
553 .with_endpoint("http://localhost:15000")
554 .with_instance_type(InstanceType::Omni)
555 .build()
556 .await
557 .expect("build client");
558
559 let database_client = spanner
560 .database_client("retail-sample")
561 .build()
562 .await
563 .expect("build db client");
564
565 let transaction = database_client.single_use().build();
566 let mut result_set = transaction
567 .execute_query("SELECT * FROM Products LIMIT 5")
568 .await
569 .expect("execute query");
570
571 let mut count = 0;
572 while let Some(row) = result_set.next().await {
573 let row = row.expect("read row");
574 println!("Fetched Omni row {}: {:?}", count, row);
575 count += 1;
576 }
577 println!("Successfully queried Omni! Total rows fetched: {}", count);
578 }
579}