diff --git a/Cargo.lock b/Cargo.lock index 97cdd45..8368191 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -336,6 +336,16 @@ version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b0f477b951e452a0b6b4a10b53ccd569042d1d01729b519e02074a9c0958a063" +[[package]] +name = "assert-json-diff" +version = "2.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47e4f2b81832e72834d7518d8487a0396a28cc408186a2e8854c0f98011faf12" +dependencies = [ + "serde", + "serde_json", +] + [[package]] name = "async-lock" version = "3.4.2" @@ -972,6 +982,7 @@ dependencies = [ "aws-sdk-s3", "aws-sigv4", "aws-smithy-runtime-api", + "base64 0.22.1", "bytes", "clap", "futures", @@ -980,6 +991,7 @@ dependencies = [ "iceberg-catalog-glue", "iceberg-catalog-rest", "iceberg-storage-opendal", + "mockito", "reqsign-core", "reqwest 0.12.28", "serde", @@ -1257,6 +1269,15 @@ version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570" +[[package]] +name = "colored" +version = "3.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "faf9468729b8cbcea668e36183cb69d317348c2e08e994829fb56ebfdfbaac34" +dependencies = [ + "windows-sys 0.61.2", +] + [[package]] name = "combine" version = "4.6.9" @@ -2229,6 +2250,7 @@ dependencies = [ "http 1.5.0", "http-body 1.1.0", "httparse", + "httpdate", "itoa", "pin-project-lite", "smallvec", @@ -2946,6 +2968,31 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "mockito" +version = "1.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "90820618712cab19cfc46b274c6c22546a82affcb3c3bdf0f29e3db8e1bb92c0" +dependencies = [ + "assert-json-diff", + "bytes", + "colored", + "futures-core", + "http 1.5.0", + "http-body 1.1.0", + "http-body-util", + "hyper 1.12.0", + "hyper-util", + "log", + "pin-project-lite", + "rand 0.9.5", + "regex", + "serde_json", + "serde_urlencoded", + "similar", + "tokio", +] + [[package]] name = "moka" version = "0.12.16" @@ -4320,6 +4367,12 @@ version = "0.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e" +[[package]] +name = "similar" +version = "2.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbbb5d9659141646ae647b42fe094daf6c6192d1620870b449d9557f748b2daa" + [[package]] name = "slab" version = "0.4.12" diff --git a/Cargo.toml b/Cargo.toml index 1ad3959..c37550b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -17,8 +17,9 @@ aws-credential-types = "1.2.10" aws-sdk-s3 = "1.115.0" aws-sigv4 = "1.6.3" aws-smithy-runtime-api = "1.19.1" +base64 = "0.22.1" bytes = "1.11.0" -clap = { version = "4.5.53", features = ["derive"] } +clap = { version = "4.5.53", features = ["derive", "env"] } futures = "0.3.31" http = "1.3.1" iceberg = "0.11.0" @@ -33,3 +34,6 @@ tokio = { version = "1.48.0", features = ["full"] } tracing = "0.1.41" tracing-subscriber = { version = "0.3.20", features = ["env-filter"] } url = "2.5.7" + +[dev-dependencies] +mockito = "1" diff --git a/README.md b/README.md index a4fcd87..1c6d63f 100644 --- a/README.md +++ b/README.md @@ -55,6 +55,33 @@ bergr rest https://glue.us-west-2.amazonaws.com/iceberg --warehouse 123456789012 Glue's REST endpoint needs `glue:GetCatalog` and `lakeformation:GetDataAccess` permissions, in addition to those the `glue` command needs. +#### Authentication + +Choose how to authenticate with `--auth`, or set `BERGR_REST_AUTH`. Each type reads its settings, including secrets, from environment variables, so secrets never appear in shell history or `ps`. + +| `--auth` | Reads | +|---|---| +| `auto` (default) | Behaves as `sigv4` for AWS Glue endpoints, otherwise `none` | +| `none` | nothing | +| `sigv4` | the standard AWS credential variables and profile | +| `bearer` | `BERGR_REST_BEARER_TOKEN` | +| `basic` | `BERGR_REST_BASIC_USER`, `BERGR_REST_BASIC_PASSWORD` | +| `oauth2` | `BERGR_REST_OAUTH2_CREDENTIAL` (`client_id:secret`); optionally `BERGR_REST_OAUTH2_SCOPE` and `BERGR_REST_OAUTH2_SERVER_URI` | + +```bash +BERGR_REST_BEARER_TOKEN="$(cat ~/.config/my-catalog-token)" \ + bergr rest --auth bearer https://catalog.example.com namespaces +``` + +With `oauth2`, bergr exchanges the credential for a token at `/v1/oauth/tokens` (or `BERGR_REST_OAUTH2_SERVER_URI`, if set), asking for the `catalog` scope unless `BERGR_REST_OAUTH2_SCOPE` says otherwise. Some catalogs need a specific scope: [Apache Polaris](https://polaris.apache.org/), for example, wants `PRINCIPAL_ROLE:ALL`. + +```bash +BERGR_REST_OAUTH2_CREDENTIAL="$(cat ~/.config/polaris-credential)" BERGR_REST_OAUTH2_SCOPE=PRINCIPAL_ROLE:ALL \ + bergr rest --auth oauth2 http://localhost:8181/api/catalog --warehouse quickstart_catalog namespaces +``` + +`bearer` and `oauth2` correspond to the Iceberg REST catalog properties `token`, `credential`, `scope` and `oauth2-server-uri`. `sigv4` currently only supports AWS Glue endpoints (`glue..amazonaws.com`). + ### Direct access via metadata file location ```bash diff --git a/src/basic_auth.rs b/src/basic_auth.rs new file mode 100644 index 0000000..32c5efb --- /dev/null +++ b/src/basic_auth.rs @@ -0,0 +1,95 @@ +//! HTTP basic authentication for REST catalogs, which iceberg-catalog-rest doesn't provide + +use async_trait::async_trait; +use base64::Engine; +use base64::engine::general_purpose::STANDARD; +use http::HeaderValue; +use http::header::AUTHORIZATION; +use iceberg::sensitive::SensitiveString; +use iceberg::{Error, ErrorKind, Result}; +use iceberg_catalog_rest::{AuthManager, AuthSession, HttpClient, HttpRequest}; +use std::collections::HashMap; +use std::sync::Arc; + +/// An [`AuthManager`] that adds an `Authorization: Basic …` header to every request. +#[derive(Debug, Clone)] +pub struct BasicAuthManager { + session: Arc, +} + +impl BasicAuthManager { + pub fn new(user: &str, password: &SensitiveString) -> Result { + let credentials = STANDARD.encode(format!("{user}:{}", password.expose())); + let mut header = HeaderValue::try_from(format!("Basic {credentials}")).map_err(|e| { + Error::new(ErrorKind::DataInvalid, "invalid basic auth header").with_source(e) + })?; + header.set_sensitive(true); + Ok(Self { + session: Arc::new(BasicAuthSession { header }), + }) + } +} + +#[async_trait] +impl AuthManager for BasicAuthManager { + async fn init_session( + &self, + _client: &HttpClient, + _props: &HashMap, + ) -> Result> { + Ok(Box::new(self.session.as_ref().clone())) + } + + async fn catalog_session( + &self, + _client: &HttpClient, + _props: &HashMap, + ) -> Result> { + Ok(self.session.clone()) + } +} + +/// Holds the header value marked sensitive, so `Debug` output doesn't show it. +#[derive(Debug, Clone)] +struct BasicAuthSession { + header: HeaderValue, +} + +#[async_trait] +impl AuthSession for BasicAuthSession { + async fn authenticate(&self, request: &mut HttpRequest) -> Result<()> { + request + .headers_mut() + .insert(AUTHORIZATION, self.header.clone()); + Ok(()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn manager() -> BasicAuthManager { + BasicAuthManager::new("alice", &"s3cret".to_string().into()).unwrap() + } + + #[tokio::test] + async fn adds_basic_auth_header() { + let mut request = HttpRequest::new( + reqwest::Client::new() + .get("https://catalog.example.com/v1/config") + .build() + .unwrap(), + ); + manager().session.authenticate(&mut request).await.unwrap(); + + // "alice:s3cret", base64-encoded + assert_eq!(request.headers()[AUTHORIZATION], "Basic YWxpY2U6czNjcmV0"); + } + + #[test] + fn debug_output_redacts_credentials() { + let debug = format!("{:?}", manager()); + assert!(!debug.contains("YWxpY2U6czNjcmV0"), "{debug}"); + } +} diff --git a/src/cli.rs b/src/cli.rs index 8d13e09..f14a0e9 100644 --- a/src/cli.rs +++ b/src/cli.rs @@ -1,3 +1,4 @@ +use crate::rest_auth::AuthType; use clap::{Parser, Subcommand}; /// bergr: A tool for inspecting Apache Iceberg tables @@ -36,6 +37,11 @@ pub enum Commands { #[arg(long)] warehouse: Option, + /// How to authenticate to the catalog. Settings, including secrets, are read from + /// environment variables, never from arguments. + #[arg(long, value_enum, env = "BERGR_REST_AUTH", default_value_t = AuthType::Auto)] + auth: AuthType, + #[command(subcommand)] command: CatalogCommands, }, diff --git a/src/lib.rs b/src/lib.rs index 4a1e41d..b55c68f 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,9 +1,11 @@ pub mod aws; +pub mod basic_auth; pub mod catalog_commands; pub mod cli; pub mod error; pub mod file_existence; pub mod rest; +pub mod rest_auth; pub mod sigv4; pub mod table_commands; pub mod terminal_output; diff --git a/src/main.rs b/src/main.rs index 30d9876..f9bb78c 100644 --- a/src/main.rs +++ b/src/main.rs @@ -5,7 +5,7 @@ use bergr::catalog_commands::handle_catalog_command; use bergr::cli::{Cli, Commands}; use bergr::error::ExpectedError; use bergr::rest::rest_catalog; -use bergr::sigv4::SigningScope; +use bergr::rest_auth::RestAuth; use bergr::table_commands::{handle_table_command, load_table}; use bergr::terminal_output::TerminalOutput; use clap::Parser; @@ -77,11 +77,12 @@ async fn run(command: Commands) -> Result<()> { Commands::Rest { uri, warehouse, + auth, command, } => { let mut output = TerminalOutput::new(); - match SigningScope::from_uri(&uri) { - Some(scope) => { + match RestAuth::resolve(auth, &uri, |name| std::env::var(name).ok())? { + RestAuth::SigV4(scope) => { let aws_config = get_aws_config() .await .to_builder() @@ -92,8 +93,8 @@ async fn run(command: Commands) -> Result<()> { let s3 = aws_sdk_s3::Client::new(&aws_config); handle_catalog_command(&catalog, command, &mut output, Some(&s3)).await?; } - None => { - let catalog = rest_catalog(&uri, warehouse.as_deref()).await?; + RestAuth::Http(auth) => { + let catalog = rest_catalog(&uri, warehouse.as_deref(), &auth).await?; handle_catalog_command(&catalog, command, &mut output, None).await?; } } diff --git a/src/rest.rs b/src/rest.rs index bd16587..ef4f5a9 100644 --- a/src/rest.rs +++ b/src/rest.rs @@ -1,9 +1,12 @@ //! REST catalog integration utilities +use crate::basic_auth::BasicAuthManager; +use crate::rest_auth::HttpAuth; use anyhow::Result; use iceberg::CatalogBuilder; use iceberg_catalog_rest::{ - REST_CATALOG_PROP_URI, REST_CATALOG_PROP_WAREHOUSE, RestCatalog, RestCatalogBuilder, + AUTH_TYPE_NONE, AUTH_TYPE_OAUTH2, REST_CATALOG_PROP_AUTH_TYPE, REST_CATALOG_PROP_URI, + REST_CATALOG_PROP_WAREHOUSE, RestCatalog, RestCatalogBuilder, }; use std::collections::HashMap; @@ -25,27 +28,66 @@ pub fn rest_catalog_props(uri: &str, warehouse: Option<&str>) -> HashMap HashMap { + let entries: Vec<(&str, Option<&str>)> = match auth { + HttpAuth::None => vec![(REST_CATALOG_PROP_AUTH_TYPE, Some(AUTH_TYPE_NONE))], + HttpAuth::Bearer { token } => vec![ + (REST_CATALOG_PROP_AUTH_TYPE, Some(AUTH_TYPE_OAUTH2)), + ("token", Some(token.expose())), + ], + HttpAuth::OAuth2 { + credential, + scope, + server_uri, + } => vec![ + (REST_CATALOG_PROP_AUTH_TYPE, Some(AUTH_TYPE_OAUTH2)), + ("credential", Some(credential.expose())), + ("scope", scope.as_deref()), + ("oauth2-server-uri", server_uri.as_deref()), + ], + HttpAuth::Basic { .. } => vec![], + }; + entries + .into_iter() + .filter_map(|(key, value)| value.map(|v| (key.to_string(), v.to_string()))) + .collect() +} + +/// Create a REST catalog with the given URI, optional warehouse location, and authentication /// /// # Arguments /// /// * `uri` - The REST catalog endpoint URL (e.g., "http://localhost:8181") /// * `warehouse` - Optional warehouse location (e.g., "s3://my-bucket/warehouse") +/// * `auth` - How to authenticate requests to the catalog /// /// # Returns /// /// A configured `RestCatalog` instance -pub async fn rest_catalog(uri: &str, warehouse: Option<&str>) -> Result { - let catalog = RestCatalogBuilder::default() - .load("rest", rest_catalog_props(uri, warehouse)) - .await?; +pub async fn rest_catalog( + uri: &str, + warehouse: Option<&str>, + auth: &HttpAuth, +) -> Result { + let mut props = rest_catalog_props(uri, warehouse); + props.extend(auth_props(auth)); + + let builder = match auth { + HttpAuth::Basic { user, password } => { + RestCatalogBuilder::default().with_auth_manager(BasicAuthManager::new(user, password)?) + } + _ => RestCatalogBuilder::default(), + }; - Ok(catalog) + Ok(builder.load("rest", props).await?) } #[cfg(test)] mod tests { use super::*; + use iceberg::Catalog; + use mockito::{Matcher, Server, ServerGuard}; #[tokio::test] async fn test_rest_catalog_builder() -> Result<()> { @@ -57,7 +99,7 @@ mod tests { let warehouse = Some("s3://test-warehouse"); // This should succeed - the catalog is created lazily - let result = rest_catalog(uri, warehouse).await; + let result = rest_catalog(uri, warehouse, &HttpAuth::None).await; // The catalog should be created successfully assert!( @@ -74,7 +116,7 @@ mod tests { let uri = "http://localhost:8181"; // Test that it works without an explicit warehouse (uses default) - let result = rest_catalog(uri, None).await; + let result = rest_catalog(uri, None, &HttpAuth::None).await; // Should succeed with default warehouse assert!( @@ -96,7 +138,7 @@ mod tests { ]; for uri in test_cases { - let result = rest_catalog(uri, None).await; + let result = rest_catalog(uri, None, &HttpAuth::None).await; assert!( result.is_ok(), "Catalog creation should succeed for URI {}: {:?}", @@ -107,4 +149,86 @@ mod tests { Ok(()) } + + /// Expect `GET /v1/config` and `GET /v1/namespaces`, each with the given `Authorization` + /// header, then list namespaces with `auth`. + async fn list_namespaces_expecting( + server: &mut ServerGuard, + auth: &HttpAuth, + authorization: Matcher, + ) -> Result<()> { + let config = server + .mock("GET", "/v1/config") + .match_query(Matcher::Any) + .match_header("authorization", authorization.clone()) + .with_body(r#"{"defaults": {}, "overrides": {}}"#) + .create_async() + .await; + let namespaces = server + .mock("GET", "/v1/namespaces") + .match_header("authorization", authorization) + .with_body(r#"{"namespaces": []}"#) + .create_async() + .await; + + let catalog = rest_catalog(&server.url(), None, auth).await?; + catalog.list_namespaces(None).await?; + + config.assert_async().await; + namespaces.assert_async().await; + Ok(()) + } + + #[tokio::test] + async fn none_sends_no_authorization() -> Result<()> { + let mut server = Server::new_async().await; + list_namespaces_expecting(&mut server, &HttpAuth::None, Matcher::Missing).await + } + + #[tokio::test] + async fn bearer_sends_token() -> Result<()> { + let mut server = Server::new_async().await; + let auth = HttpAuth::Bearer { + token: "tok".to_string().into(), + }; + list_namespaces_expecting(&mut server, &auth, "Bearer tok".into()).await + } + + #[tokio::test] + async fn basic_sends_credentials() -> Result<()> { + let mut server = Server::new_async().await; + let auth = HttpAuth::Basic { + user: "alice".into(), + password: "s3cret".to_string().into(), + }; + list_namespaces_expecting(&mut server, &auth, "Basic YWxpY2U6czNjcmV0".into()).await + } + + #[tokio::test] + async fn oauth2_exchanges_credential_for_token() -> Result<()> { + let mut server = Server::new_async().await; + let tokens = server + .mock("POST", "/v1/oauth/tokens") + .match_body(Matcher::AllOf(vec![ + Matcher::UrlEncoded("grant_type".into(), "client_credentials".into()), + Matcher::UrlEncoded("client_id".into(), "id".into()), + Matcher::UrlEncoded("client_secret".into(), "secret".into()), + Matcher::UrlEncoded("scope".into(), "PRINCIPAL_ROLE:ALL".into()), + ])) + .with_body( + r#"{"access_token": "exchanged", "token_type": "bearer", + "issued_token_type": "urn:ietf:params:oauth:token-type:access_token"}"#, + ) + .create_async() + .await; + let auth = HttpAuth::OAuth2 { + credential: "id:secret".to_string().into(), + scope: Some("PRINCIPAL_ROLE:ALL".into()), + server_uri: None, + }; + + list_namespaces_expecting(&mut server, &auth, "Bearer exchanged".into()).await?; + tokens.assert_async().await; + Ok(()) + } } diff --git a/src/rest_auth.rs b/src/rest_auth.rs new file mode 100644 index 0000000..4cb1bae --- /dev/null +++ b/src/rest_auth.rs @@ -0,0 +1,316 @@ +//! Authentication settings for REST catalogs +//! +//! Settings, including secrets, are only ever read from environment variables, never from +//! command-line arguments, which are visible in `ps` and end up in shell history. + +use crate::error::ExpectedError; +use crate::sigv4::SigningScope; +use anyhow::Result; +use clap::ValueEnum; +use iceberg::sensitive::SensitiveString; + +pub const BEARER_TOKEN: &str = "BERGR_REST_BEARER_TOKEN"; +pub const BASIC_USER: &str = "BERGR_REST_BASIC_USER"; +pub const BASIC_PASSWORD: &str = "BERGR_REST_BASIC_PASSWORD"; +pub const OAUTH2_CREDENTIAL: &str = "BERGR_REST_OAUTH2_CREDENTIAL"; +pub const OAUTH2_SCOPE: &str = "BERGR_REST_OAUTH2_SCOPE"; +pub const OAUTH2_SERVER_URI: &str = "BERGR_REST_OAUTH2_SERVER_URI"; + +/// How `bergr rest` authenticates to the catalog +#[derive(ValueEnum, Debug, Clone, Copy, PartialEq, Eq, Default)] +pub enum AuthType { + /// `sigv4` for AWS Glue endpoints (glue..amazonaws.com), otherwise `none` + #[default] + Auto, + /// No authentication + None, + /// AWS SigV4 signing, with the standard AWS credential variables and profile; region and + /// signing name come from the AWS Glue hostname + Sigv4, + /// Bearer token from BERGR_REST_BEARER_TOKEN (iceberg-catalog-rest's `token`) + Bearer, + /// HTTP basic authentication, from BERGR_REST_BASIC_USER and BERGR_REST_BASIC_PASSWORD + Basic, + /// OAuth2 client credentials from BERGR_REST_OAUTH2_CREDENTIAL (`client_id:secret`), and + /// optionally BERGR_REST_OAUTH2_SCOPE and BERGR_REST_OAUTH2_SERVER_URI (iceberg-catalog-rest's + /// `credential`, `scope` and `oauth2-server-uri`) + Oauth2, +} + +impl AuthType { + fn name(self) -> String { + self.to_possible_value() + .map(|value| value.get_name().to_string()) + .unwrap_or_default() + } +} + +/// Authentication for a REST catalog, with its settings resolved +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum RestAuth { + /// Sign requests with AWS SigV4, which needs AWS configuration to build + SigV4(SigningScope), + /// Authenticate with HTTP headers alone + Http(HttpAuth), +} + +/// Authentication schemes that need nothing beyond their settings +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum HttpAuth { + None, + Bearer { + token: SensitiveString, + }, + Basic { + user: String, + password: SensitiveString, + }, + OAuth2 { + credential: SensitiveString, + scope: Option, + server_uri: Option, + }, +} + +fn user_input(message: String) -> anyhow::Error { + ExpectedError::UserInput(message).into() +} + +impl RestAuth { + /// Resolve `auth_type` for the catalog at `uri`, reading settings with `lookup` + /// (normally `std::env::var`). An empty setting counts as unset. + pub fn resolve( + auth_type: AuthType, + uri: &str, + lookup: impl Fn(&str) -> Option, + ) -> Result { + let optional = |name: &str| lookup(name).filter(|value| !value.is_empty()); + let required = |name: &str| { + optional(name) + .ok_or_else(|| user_input(format!("--auth {} requires {name}", auth_type.name()))) + }; + + match auth_type { + AuthType::Auto => Ok(SigningScope::from_uri(uri) + .map(RestAuth::SigV4) + .unwrap_or(RestAuth::Http(HttpAuth::None))), + AuthType::None => Ok(RestAuth::Http(HttpAuth::None)), + AuthType::Sigv4 => SigningScope::from_uri(uri).map(RestAuth::SigV4).ok_or_else(|| { + user_input(format!( + "--auth sigv4 only supports AWS Glue endpoints (glue..amazonaws.com), not {uri}" + )) + }), + AuthType::Bearer => Ok(RestAuth::Http(HttpAuth::Bearer { + token: required(BEARER_TOKEN)?.into(), + })), + AuthType::Basic => { + let user = required(BASIC_USER)?; + if user.contains(':') { + return Err(user_input(format!("{BASIC_USER} must not contain ':'"))); + } + Ok(RestAuth::Http(HttpAuth::Basic { + user, + password: required(BASIC_PASSWORD)?.into(), + })) + } + AuthType::Oauth2 => Ok(RestAuth::Http(HttpAuth::OAuth2 { + credential: required(OAUTH2_CREDENTIAL)?.into(), + scope: optional(OAUTH2_SCOPE), + server_uri: optional(OAUTH2_SERVER_URI), + })), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::collections::HashMap; + + const GLUE_URI: &str = "https://glue.us-west-2.amazonaws.com/iceberg"; + const OTHER_URI: &str = "https://catalog.example.com"; + + fn resolve(auth_type: AuthType, uri: &str, vars: &[(&str, &str)]) -> Result { + let env: HashMap = vars + .iter() + .map(|(k, v)| (k.to_string(), v.to_string())) + .collect(); + RestAuth::resolve(auth_type, uri, |name| env.get(name).cloned()) + } + + fn error_message(result: Result) -> String { + let err = result.expect_err("should fail"); + assert!( + err.downcast_ref::().is_some(), + "should be a user-input error: {err:?}" + ); + err.to_string() + } + + fn glue_scope() -> SigningScope { + SigningScope { + service: "glue".into(), + region: "us-west-2".into(), + } + } + + #[test] + fn auto_signs_glue_requests() { + assert_eq!( + resolve(AuthType::Auto, GLUE_URI, &[]).unwrap(), + RestAuth::SigV4(glue_scope()) + ); + } + + #[test] + fn auto_is_none_for_other_catalogs() { + assert_eq!( + resolve(AuthType::Auto, OTHER_URI, &[(BEARER_TOKEN, "ignored")]).unwrap(), + RestAuth::Http(HttpAuth::None) + ); + } + + #[test] + fn none_disables_signing_for_glue() { + assert_eq!( + resolve(AuthType::None, GLUE_URI, &[]).unwrap(), + RestAuth::Http(HttpAuth::None) + ); + } + + #[test] + fn sigv4_for_glue() { + assert_eq!( + resolve(AuthType::Sigv4, GLUE_URI, &[]).unwrap(), + RestAuth::SigV4(glue_scope()) + ); + } + + #[test] + fn sigv4_rejects_unrecognised_endpoints() { + assert!(error_message(resolve(AuthType::Sigv4, OTHER_URI, &[])).contains("AWS Glue")); + } + + #[test] + fn bearer_reads_token() { + assert_eq!( + resolve(AuthType::Bearer, OTHER_URI, &[(BEARER_TOKEN, "tok")]).unwrap(), + RestAuth::Http(HttpAuth::Bearer { + token: "tok".to_string().into() + }) + ); + } + + #[test] + fn bearer_requires_token() { + assert_eq!( + error_message(resolve(AuthType::Bearer, OTHER_URI, &[])), + "--auth bearer requires BERGR_REST_BEARER_TOKEN" + ); + } + + #[test] + fn empty_setting_counts_as_unset() { + assert_eq!( + error_message(resolve(AuthType::Bearer, OTHER_URI, &[(BEARER_TOKEN, "")])), + "--auth bearer requires BERGR_REST_BEARER_TOKEN" + ); + } + + #[test] + fn basic_reads_user_and_password() { + assert_eq!( + resolve( + AuthType::Basic, + OTHER_URI, + &[(BASIC_USER, "alice"), (BASIC_PASSWORD, "s3cret")] + ) + .unwrap(), + RestAuth::Http(HttpAuth::Basic { + user: "alice".into(), + password: "s3cret".to_string().into() + }) + ); + } + + #[test] + fn basic_requires_password() { + assert_eq!( + error_message(resolve( + AuthType::Basic, + OTHER_URI, + &[(BASIC_USER, "alice")] + )), + "--auth basic requires BERGR_REST_BASIC_PASSWORD" + ); + } + + #[test] + fn basic_rejects_colon_in_user() { + assert_eq!( + error_message(resolve( + AuthType::Basic, + OTHER_URI, + &[(BASIC_USER, "al:ice"), (BASIC_PASSWORD, "s3cret")] + )), + "BERGR_REST_BASIC_USER must not contain ':'" + ); + } + + #[test] + fn oauth2_reads_credential_and_options() { + assert_eq!( + resolve( + AuthType::Oauth2, + OTHER_URI, + &[ + (OAUTH2_CREDENTIAL, "id:secret"), + (OAUTH2_SCOPE, "PRINCIPAL_ROLE:ALL"), + (OAUTH2_SERVER_URI, "https://auth.example.com/token"), + ] + ) + .unwrap(), + RestAuth::Http(HttpAuth::OAuth2 { + credential: "id:secret".to_string().into(), + scope: Some("PRINCIPAL_ROLE:ALL".into()), + server_uri: Some("https://auth.example.com/token".into()), + }) + ); + } + + #[test] + fn oauth2_options_are_optional() { + assert_eq!( + resolve( + AuthType::Oauth2, + OTHER_URI, + &[(OAUTH2_CREDENTIAL, "secret")] + ) + .unwrap(), + RestAuth::Http(HttpAuth::OAuth2 { + credential: "secret".to_string().into(), + scope: None, + server_uri: None, + }) + ); + } + + #[test] + fn oauth2_requires_credential() { + assert_eq!( + error_message(resolve(AuthType::Oauth2, OTHER_URI, &[])), + "--auth oauth2 requires BERGR_REST_OAUTH2_CREDENTIAL" + ); + } + + #[test] + fn debug_output_redacts_secrets() { + let auth = resolve( + AuthType::Basic, + OTHER_URI, + &[(BASIC_USER, "alice"), (BASIC_PASSWORD, "s3cret")], + ) + .unwrap(); + assert!(!format!("{auth:?}").contains("s3cret")); + } +}