Rinomina: crate akode-*, cartelle akode-rs/ e akode-cli/, binario akode, ~/.akode, AKODE_* (A)
Riapplica la fase 5 di aKode (86e7c72e) sulla base ripulita:
- crate codex-* -> akode-*, codex-rs -> akode-rs, codex-cli -> akode-cli, binario e ausiliari akode;
- ~/.codex -> ~/.akode, CODEX_HOME -> AKODE_HOME, variabili CODEX_* -> AKODE_*, .codex/ -> .akode/ di progetto;
nessun fallback a ~/.codex o a CODEX_*;
- testi per l'utente "Codex" -> "aKode"; testi verso il modello e istruzioni di sistema invariati;
- snapshot insta rinominati (non ancora rigenerati).
I conflitti con la base ripulita sono stati risolti riapplicando la rinomina ai file senza le
funzioni di imeAI (script di mappa dei token per file).
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
6
akode-rs/aws-auth/BUILD.bazel
Normal file
6
akode-rs/aws-auth/BUILD.bazel
Normal file
@@ -0,0 +1,6 @@
|
||||
load("//:defs.bzl", "codex_rust_crate")
|
||||
|
||||
codex_rust_crate(
|
||||
name = "aws-auth",
|
||||
crate_name = "akode_aws_auth",
|
||||
)
|
||||
37
akode-rs/aws-auth/Cargo.toml
Normal file
37
akode-rs/aws-auth/Cargo.toml
Normal file
@@ -0,0 +1,37 @@
|
||||
[package]
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
name = "akode-aws-auth"
|
||||
version.workspace = true
|
||||
|
||||
[lib]
|
||||
doctest = false
|
||||
name = "akode_aws_auth"
|
||||
path = "src/lib.rs"
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
akode-http-client = { workspace = true }
|
||||
aws-config = { workspace = true, features = ["credentials-login"] }
|
||||
aws-credential-types = { workspace = true }
|
||||
aws-sigv4 = { workspace = true }
|
||||
aws-smithy-runtime-api = { workspace = true }
|
||||
aws-smithy-types = { workspace = true }
|
||||
aws-types = { workspace = true }
|
||||
bytes = { workspace = true }
|
||||
http = { workspace = true }
|
||||
http-body = "1.0.1"
|
||||
http-body-util = "0.1.3"
|
||||
url = { workspace = true }
|
||||
thiserror = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
pretty_assertions = { workspace = true }
|
||||
rcgen = { workspace = true }
|
||||
rustls = { workspace = true }
|
||||
tempfile = { workspace = true }
|
||||
tokio-rustls = { workspace = true }
|
||||
akode-utils-rustls-provider = { workspace = true }
|
||||
tokio = { workspace = true, features = ["io-util", "macros", "net", "rt-multi-thread", "time"] }
|
||||
43
akode-rs/aws-auth/src/config.rs
Normal file
43
akode-rs/aws-auth/src/config.rs
Normal file
@@ -0,0 +1,43 @@
|
||||
//! Loads AWS SDK configuration with the application's HTTP client.
|
||||
|
||||
use aws_config::BehaviorVersion;
|
||||
use aws_config::SdkConfig;
|
||||
use aws_credential_types::provider::SharedCredentialsProvider;
|
||||
use aws_types::region::Region;
|
||||
use akode_http_client::HttpClientFactory;
|
||||
|
||||
use crate::AwsAuthConfig;
|
||||
use crate::AwsAuthError;
|
||||
|
||||
pub(crate) async fn load_sdk_config(
|
||||
config: &AwsAuthConfig,
|
||||
factory: &HttpClientFactory,
|
||||
) -> Result<SdkConfig, AwsAuthError> {
|
||||
if config.service.trim().is_empty() {
|
||||
return Err(AwsAuthError::EmptyService);
|
||||
}
|
||||
let mut loader = aws_config::defaults(BehaviorVersion::latest())
|
||||
.http_client(crate::transport::http_client(factory.clone()));
|
||||
if let Some(profile) = config.profile.as_ref() {
|
||||
loader = loader.profile_name(profile);
|
||||
}
|
||||
if let Some(region) = config.region.as_ref() {
|
||||
loader = loader.region(Region::new(region.clone()));
|
||||
}
|
||||
Ok(loader.load().await)
|
||||
}
|
||||
|
||||
pub(crate) fn credentials_provider(
|
||||
sdk_config: &SdkConfig,
|
||||
) -> Result<SharedCredentialsProvider, AwsAuthError> {
|
||||
sdk_config
|
||||
.credentials_provider()
|
||||
.ok_or(AwsAuthError::MissingCredentialsProvider)
|
||||
}
|
||||
|
||||
pub(crate) fn resolved_region(sdk_config: &SdkConfig) -> Result<String, AwsAuthError> {
|
||||
sdk_config
|
||||
.region()
|
||||
.map(ToString::to_string)
|
||||
.ok_or(AwsAuthError::MissingRegion)
|
||||
}
|
||||
69
akode-rs/aws-auth/src/discovery.rs
Normal file
69
akode-rs/aws-auth/src/discovery.rs
Normal file
@@ -0,0 +1,69 @@
|
||||
use aws_config::profile::ProfileFileCredentialsProvider;
|
||||
use aws_config::provider_config::ProviderConfig;
|
||||
use aws_credential_types::provider::ProvideCredentials;
|
||||
use aws_types::os_shim_internal::Env;
|
||||
use aws_types::os_shim_internal::Fs;
|
||||
use aws_types::region::Region;
|
||||
|
||||
use crate::AwsAuthError;
|
||||
|
||||
/// A named AWS profile and the region configured directly on that profile.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct AwsProfile {
|
||||
pub name: String,
|
||||
pub region: Option<String>,
|
||||
}
|
||||
|
||||
/// Discovers AWS profiles using the SDK's shared config and credentials files.
|
||||
pub async fn discover_aws_profiles() -> Result<Vec<AwsProfile>, AwsAuthError> {
|
||||
let profiles = aws_config::profile::load(
|
||||
&Fs::real(),
|
||||
&Env::real(),
|
||||
&Default::default(),
|
||||
/*selected_profile_override*/ None,
|
||||
)
|
||||
.await?;
|
||||
let selected_profile = profiles.selected_profile();
|
||||
let mut discovered = profiles
|
||||
.profiles()
|
||||
.filter_map(|name| {
|
||||
profiles.get_profile(name).map(|profile| AwsProfile {
|
||||
name: name.to_string(),
|
||||
region: profile.get("region").map(str::to_string),
|
||||
})
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
discovered.sort_by(|left, right| {
|
||||
(left.name != selected_profile, &left.name)
|
||||
.cmp(&(right.name != selected_profile, &right.name))
|
||||
});
|
||||
|
||||
Ok(discovered)
|
||||
}
|
||||
|
||||
/// Resolves credentials only from the selected AWS profile.
|
||||
pub async fn validate_aws_profile(
|
||||
profile: &str,
|
||||
region: &str,
|
||||
factory: akode_http_client::HttpClientFactory,
|
||||
) -> Result<(), AwsAuthError> {
|
||||
profile_credentials_provider(profile, region, factory)
|
||||
.provide_credentials()
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn profile_credentials_provider(
|
||||
profile: &str,
|
||||
region: &str,
|
||||
factory: akode_http_client::HttpClientFactory,
|
||||
) -> ProfileFileCredentialsProvider {
|
||||
let config = ProviderConfig::without_region()
|
||||
.with_region(Some(Region::new(region.to_string())))
|
||||
.with_http_client(crate::transport::http_client(factory));
|
||||
ProfileFileCredentialsProvider::builder()
|
||||
.configure(&config)
|
||||
.profile_name(profile)
|
||||
.build()
|
||||
}
|
||||
319
akode-rs/aws-auth/src/lib.rs
Normal file
319
akode-rs/aws-auth/src/lib.rs
Normal file
@@ -0,0 +1,319 @@
|
||||
mod config;
|
||||
mod discovery;
|
||||
mod signing;
|
||||
mod transport;
|
||||
|
||||
use std::sync::Arc;
|
||||
use std::time::SystemTime;
|
||||
|
||||
use aws_credential_types::provider::ProvideCredentials;
|
||||
use aws_credential_types::provider::SharedCredentialsProvider;
|
||||
use bytes::Bytes;
|
||||
use http::HeaderMap;
|
||||
use http::Method;
|
||||
use thiserror::Error;
|
||||
|
||||
pub use discovery::AwsProfile;
|
||||
pub use discovery::discover_aws_profiles;
|
||||
pub use discovery::validate_aws_profile;
|
||||
|
||||
/// AWS auth configuration used to resolve credentials and sign requests.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct AwsAuthConfig {
|
||||
pub profile: Option<String>,
|
||||
pub region: Option<String>,
|
||||
pub service: String,
|
||||
}
|
||||
|
||||
/// Static AWS access keys supplied by a caller instead of the default SDK chain.
|
||||
#[derive(Clone, PartialEq, Eq)]
|
||||
pub struct AwsAccessKeys {
|
||||
pub access_key_id: String,
|
||||
pub secret_access_key: String,
|
||||
pub session_token: Option<String>,
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for AwsAccessKeys {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("AwsAccessKeys")
|
||||
.field("access_key_id", &"<redacted>")
|
||||
.field("secret_access_key", &"<redacted>")
|
||||
.field(
|
||||
"session_token",
|
||||
&self.session_token.as_ref().map(|_| "<redacted>"),
|
||||
)
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
||||
/// Supplies AWS access keys on demand without exposing AWS SDK credential types to callers.
|
||||
///
|
||||
/// Implementations should return current credentials for every call so request signing can
|
||||
/// observe credential refreshes. Errors must not contain credentials or command output.
|
||||
/// These caller-supplied providers require unrestricted network policy because their I/O
|
||||
/// runs outside the shared AWS HTTP transport.
|
||||
pub trait AwsCredentialsProvider: std::fmt::Debug + Send + Sync {
|
||||
fn credentials(
|
||||
&self,
|
||||
) -> impl std::future::Future<Output = std::io::Result<AwsAccessKeys>> + Send;
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct AwsCredentialsProviderAdapter<P>(Arc<P>, akode_http_client::NetworkPolicy);
|
||||
|
||||
#[derive(Debug, Error)]
|
||||
#[error("{0}")]
|
||||
struct ProvidedCredentialsError(std::io::Error);
|
||||
|
||||
impl<P: AwsCredentialsProvider> ProvideCredentials for AwsCredentialsProviderAdapter<P> {
|
||||
fn provide_credentials<'a>(
|
||||
&'a self,
|
||||
) -> aws_credential_types::provider::future::ProvideCredentials<'a>
|
||||
where
|
||||
Self: 'a,
|
||||
{
|
||||
aws_credential_types::provider::future::ProvideCredentials::new(async move {
|
||||
let permit = self.1.acquire_for_unsupported_sdk().map_err(
|
||||
aws_credential_types::provider::error::CredentialsError::invalid_configuration,
|
||||
)?;
|
||||
let access_keys = permit.run(self.0.credentials()).await
|
||||
.map_err(aws_credential_types::provider::error::CredentialsError::invalid_configuration)?
|
||||
.map_err(|error| {
|
||||
let error = ProvidedCredentialsError(error);
|
||||
match error.0.kind() {
|
||||
std::io::ErrorKind::InvalidData
|
||||
| std::io::ErrorKind::InvalidInput
|
||||
| std::io::ErrorKind::NotFound
|
||||
| std::io::ErrorKind::PermissionDenied => {
|
||||
aws_credential_types::provider::error::CredentialsError::invalid_configuration(error)
|
||||
}
|
||||
_ => aws_credential_types::provider::error::CredentialsError::provider_error(error),
|
||||
}
|
||||
})?;
|
||||
|
||||
Ok(aws_credential_types::Credentials::new(
|
||||
access_keys.access_key_id,
|
||||
access_keys.secret_access_key,
|
||||
access_keys.session_token,
|
||||
/*expires_after*/ None,
|
||||
"codex-bedrock-credential-export",
|
||||
))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Generic HTTP request shape consumed by SigV4 signing.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct AwsRequestToSign {
|
||||
pub method: Method,
|
||||
pub url: String,
|
||||
pub headers: HeaderMap,
|
||||
pub body: Bytes,
|
||||
}
|
||||
|
||||
/// Signed request parts returned to the caller.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct AwsSignedRequest {
|
||||
pub url: String,
|
||||
pub headers: HeaderMap,
|
||||
}
|
||||
|
||||
/// Errors returned by credential loading or SigV4 signing.
|
||||
#[derive(Debug, Error)]
|
||||
pub enum AwsAuthError {
|
||||
#[error(transparent)]
|
||||
Policy(#[from] akode_http_client::NetworkPolicyDenied),
|
||||
#[error("AWS service name must not be empty")]
|
||||
EmptyService,
|
||||
#[error("AWS profile must be configured")]
|
||||
MissingProfile,
|
||||
#[error("AWS SDK config did not resolve a credentials provider")]
|
||||
MissingCredentialsProvider,
|
||||
#[error("AWS SDK config did not resolve a region")]
|
||||
MissingRegion,
|
||||
#[error("failed to load AWS profiles: {0}")]
|
||||
ProfileLoad(#[from] aws_config::profile::ProfileFileLoadError),
|
||||
#[error("failed to load AWS credentials: {0}")]
|
||||
Credentials(#[from] aws_credential_types::provider::error::CredentialsError),
|
||||
#[error("request URL is not a valid URL: {0}")]
|
||||
InvalidUrl(#[source] url::ParseError),
|
||||
#[error("request URL is not a valid URI: {0}")]
|
||||
InvalidUri(#[source] http::uri::InvalidUri),
|
||||
#[error("failed to construct HTTP request for signing: {0}")]
|
||||
BuildHttpRequest(#[source] http::Error),
|
||||
#[error("request contains a non-UTF8 header value: {0}")]
|
||||
InvalidHeaderValue(#[source] http::header::ToStrError),
|
||||
#[error("failed to build signable request: {0}")]
|
||||
SigningRequest(#[source] aws_sigv4::http_request::SigningError),
|
||||
#[error("failed to build SigV4 signing params: {0}")]
|
||||
SigningParams(String),
|
||||
#[error("SigV4 signing failed: {0}")]
|
||||
SigningFailure(#[source] aws_sigv4::http_request::SigningError),
|
||||
}
|
||||
|
||||
/// Loaded AWS auth context that can sign outbound HTTP requests.
|
||||
#[derive(Clone)]
|
||||
pub struct AwsAuthContext {
|
||||
network_policy: akode_http_client::NetworkPolicy,
|
||||
credentials_provider: SharedCredentialsProvider,
|
||||
region: String,
|
||||
service: String,
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for AwsAuthContext {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("AwsAuthContext")
|
||||
.field("region", &self.region)
|
||||
.field("service", &self.service)
|
||||
.finish_non_exhaustive()
|
||||
}
|
||||
}
|
||||
|
||||
impl AwsAuthContext {
|
||||
pub async fn load(
|
||||
config: AwsAuthConfig,
|
||||
factory: akode_http_client::HttpClientFactory,
|
||||
) -> Result<Self, AwsAuthError> {
|
||||
let sdk_config = config::load_sdk_config(&config, &factory).await?;
|
||||
Ok(Self {
|
||||
network_policy: factory.network_policy().clone(),
|
||||
credentials_provider: config::credentials_provider(&sdk_config)?,
|
||||
region: config::resolved_region(&sdk_config)?,
|
||||
service: config.service.trim().to_string(),
|
||||
})
|
||||
}
|
||||
|
||||
pub async fn load_with_access_keys(
|
||||
config: AwsAuthConfig,
|
||||
access_keys: AwsAccessKeys,
|
||||
factory: akode_http_client::HttpClientFactory,
|
||||
) -> Result<Self, AwsAuthError> {
|
||||
if config.service.trim().is_empty() {
|
||||
return Err(AwsAuthError::EmptyService);
|
||||
}
|
||||
let region = match config.region.as_ref() {
|
||||
Some(region) => region.clone(),
|
||||
None => config::resolved_region(&config::load_sdk_config(&config, &factory).await?)?,
|
||||
};
|
||||
Ok(Self {
|
||||
network_policy: factory.network_policy().clone(),
|
||||
credentials_provider: SharedCredentialsProvider::new(
|
||||
aws_credential_types::Credentials::new(
|
||||
access_keys.access_key_id,
|
||||
access_keys.secret_access_key,
|
||||
access_keys.session_token,
|
||||
/*expires_after*/ None,
|
||||
"codex-managed-bedrock-access-keys",
|
||||
),
|
||||
),
|
||||
region,
|
||||
service: config.service.trim().to_string(),
|
||||
})
|
||||
}
|
||||
|
||||
pub async fn load_with_credentials_provider(
|
||||
config: AwsAuthConfig,
|
||||
provider: Arc<impl AwsCredentialsProvider + 'static>,
|
||||
factory: akode_http_client::HttpClientFactory,
|
||||
) -> Result<Self, AwsAuthError> {
|
||||
let mut context = Self::load(config, factory).await?;
|
||||
context.credentials_provider = SharedCredentialsProvider::new(
|
||||
AwsCredentialsProviderAdapter(provider, context.network_policy.clone()),
|
||||
);
|
||||
Ok(context)
|
||||
}
|
||||
|
||||
pub async fn load_profile(
|
||||
config: AwsAuthConfig,
|
||||
factory: akode_http_client::HttpClientFactory,
|
||||
) -> Result<Self, AwsAuthError> {
|
||||
let profile = config.profile.clone().ok_or(AwsAuthError::MissingProfile)?;
|
||||
let mut context = Self::load(config, factory.clone()).await?;
|
||||
context.credentials_provider = SharedCredentialsProvider::new(
|
||||
discovery::profile_credentials_provider(&profile, &context.region, factory),
|
||||
);
|
||||
Ok(context)
|
||||
}
|
||||
|
||||
pub fn region(&self) -> &str {
|
||||
&self.region
|
||||
}
|
||||
|
||||
pub fn service(&self) -> &str {
|
||||
&self.service
|
||||
}
|
||||
|
||||
pub async fn sign(&self, request: AwsRequestToSign) -> Result<AwsSignedRequest, AwsAuthError> {
|
||||
self.sign_at(request, SystemTime::now()).await
|
||||
}
|
||||
|
||||
async fn sign_at(
|
||||
&self,
|
||||
request: AwsRequestToSign,
|
||||
time: SystemTime,
|
||||
) -> Result<AwsSignedRequest, AwsAuthError> {
|
||||
let url = request
|
||||
.url
|
||||
.parse::<url::Url>()
|
||||
.map_err(AwsAuthError::InvalidUrl)?;
|
||||
let permit = self.network_policy.acquire(&url)?;
|
||||
let credentials = permit
|
||||
.run(self.credentials_provider.provide_credentials())
|
||||
.await?
|
||||
.map_err(|error| {
|
||||
let mut source: &(dyn std::error::Error + 'static) = &error;
|
||||
loop {
|
||||
if let Some(policy) =
|
||||
source.downcast_ref::<akode_http_client::NetworkPolicyDenied>()
|
||||
{
|
||||
return AwsAuthError::Policy(*policy);
|
||||
}
|
||||
match source.source() {
|
||||
Some(next) => source = next,
|
||||
None => return AwsAuthError::Credentials(error),
|
||||
}
|
||||
}
|
||||
})?;
|
||||
signing::sign_request(&credentials, &self.region, &self.service, request, time)
|
||||
}
|
||||
}
|
||||
|
||||
impl AwsAuthError {
|
||||
/// Returns the caller-supplied credential error without exposing SDK error sources.
|
||||
pub fn credentials_provider_error(&self) -> Option<&std::io::Error> {
|
||||
let Self::Credentials(error) = self else {
|
||||
return None;
|
||||
};
|
||||
std::error::Error::source(error)?
|
||||
.downcast_ref::<ProvidedCredentialsError>()
|
||||
.map(|error| &error.0)
|
||||
}
|
||||
|
||||
/// Returns whether retrying the outbound request can reasonably recover from this auth error.
|
||||
pub fn is_retryable(&self) -> bool {
|
||||
match self {
|
||||
AwsAuthError::Credentials(error) => matches!(
|
||||
error,
|
||||
aws_credential_types::provider::error::CredentialsError::ProviderTimedOut(_)
|
||||
| aws_credential_types::provider::error::CredentialsError::ProviderError(_)
|
||||
),
|
||||
AwsAuthError::Policy(_)
|
||||
| AwsAuthError::EmptyService
|
||||
| AwsAuthError::MissingProfile
|
||||
| AwsAuthError::MissingCredentialsProvider
|
||||
| AwsAuthError::MissingRegion
|
||||
| AwsAuthError::ProfileLoad(_)
|
||||
| AwsAuthError::InvalidUrl(_)
|
||||
| AwsAuthError::InvalidUri(_)
|
||||
| AwsAuthError::BuildHttpRequest(_)
|
||||
| AwsAuthError::InvalidHeaderValue(_)
|
||||
| AwsAuthError::SigningRequest(_)
|
||||
| AwsAuthError::SigningParams(_)
|
||||
| AwsAuthError::SigningFailure(_) => false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "lib_tests.rs"]
|
||||
mod tests;
|
||||
219
akode-rs/aws-auth/src/lib_tests.rs
Normal file
219
akode-rs/aws-auth/src/lib_tests.rs
Normal file
@@ -0,0 +1,219 @@
|
||||
#![cfg(test)]
|
||||
|
||||
//! Unit tests for the crate and its related test suites.
|
||||
|
||||
use std::time::Duration;
|
||||
use std::time::UNIX_EPOCH;
|
||||
|
||||
use aws_credential_types::Credentials;
|
||||
use aws_credential_types::provider::error::CredentialsError;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
use super::*;
|
||||
|
||||
fn test_context(session_token: Option<&str>) -> AwsAuthContext {
|
||||
AwsAuthContext {
|
||||
network_policy: Default::default(),
|
||||
credentials_provider: SharedCredentialsProvider::new(Credentials::new(
|
||||
"AKIDEXAMPLE",
|
||||
"wJalrXUtnFEMI/K7MDENG+bPxRfiCYEXAMPLEKEY",
|
||||
session_token.map(str::to_string),
|
||||
/*expires_after*/ None,
|
||||
"unit-test",
|
||||
)),
|
||||
region: "us-east-1".to_string(),
|
||||
service: "bedrock".to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn test_request() -> AwsRequestToSign {
|
||||
let mut headers = HeaderMap::new();
|
||||
headers.insert(
|
||||
http::header::CONTENT_TYPE,
|
||||
http::HeaderValue::from_static("application/json"),
|
||||
);
|
||||
headers.insert("x-test-header", http::HeaderValue::from_static("present"));
|
||||
AwsRequestToSign {
|
||||
method: Method::POST,
|
||||
url: "https://bedrock-runtime.us-east-1.amazonaws.com/v1/responses".to_string(),
|
||||
headers,
|
||||
body: Bytes::from_static(br#"{"model":"openai.gpt-oss-120b-1:0"}"#),
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn sign_adds_sigv4_headers_and_preserves_existing_headers() {
|
||||
let signed = test_context(/*session_token*/ None)
|
||||
.sign_at(
|
||||
test_request(),
|
||||
UNIX_EPOCH + Duration::from_secs(1_700_000_000),
|
||||
)
|
||||
.await
|
||||
.expect("request should sign");
|
||||
|
||||
assert_eq!(
|
||||
signing::header_value(&signed.headers, http::header::CONTENT_TYPE.as_str()),
|
||||
Some("application/json".to_string())
|
||||
);
|
||||
assert_eq!(
|
||||
signing::header_value(&signed.headers, "x-test-header"),
|
||||
Some("present".to_string())
|
||||
);
|
||||
assert_eq!(
|
||||
signed.url,
|
||||
"https://bedrock-runtime.us-east-1.amazonaws.com/v1/responses"
|
||||
);
|
||||
assert!(
|
||||
signing::header_value(&signed.headers, http::header::AUTHORIZATION.as_str())
|
||||
.is_some_and(|value| value.starts_with("AWS4-HMAC-SHA256 "))
|
||||
);
|
||||
assert!(signing::header_value(&signed.headers, "x-amz-date").is_some());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn credentials_provider_adapter_converts_keys_and_provider_failures() {
|
||||
#[derive(Debug)]
|
||||
struct TestCredentialsProvider(Result<AwsAccessKeys, std::io::ErrorKind>);
|
||||
|
||||
impl AwsCredentialsProvider for TestCredentialsProvider {
|
||||
async fn credentials(&self) -> std::io::Result<AwsAccessKeys> {
|
||||
self.0
|
||||
.clone()
|
||||
.map_err(|kind| std::io::Error::new(kind, "credential export failed"))
|
||||
}
|
||||
}
|
||||
|
||||
let credentials = AwsCredentialsProviderAdapter(
|
||||
Arc::new(TestCredentialsProvider(Ok(AwsAccessKeys {
|
||||
access_key_id: "access-key-id".to_string(),
|
||||
secret_access_key: "secret-access-key".to_string(),
|
||||
session_token: Some("session-token".to_string()),
|
||||
}))),
|
||||
Default::default(),
|
||||
)
|
||||
.provide_credentials()
|
||||
.await
|
||||
.expect("exported credentials should be available");
|
||||
|
||||
assert_eq!(
|
||||
credentials,
|
||||
Credentials::new(
|
||||
"access-key-id",
|
||||
"secret-access-key",
|
||||
Some("session-token".to_string()),
|
||||
/*expires_after*/ None,
|
||||
"codex-bedrock-credential-export",
|
||||
)
|
||||
);
|
||||
|
||||
for (kind, retryable) in [
|
||||
(std::io::ErrorKind::Other, true),
|
||||
(std::io::ErrorKind::TimedOut, true),
|
||||
(std::io::ErrorKind::InvalidData, false),
|
||||
(std::io::ErrorKind::InvalidInput, false),
|
||||
(std::io::ErrorKind::NotFound, false),
|
||||
(std::io::ErrorKind::PermissionDenied, false),
|
||||
] {
|
||||
let error = AwsCredentialsProviderAdapter(
|
||||
Arc::new(TestCredentialsProvider(Err(kind))),
|
||||
Default::default(),
|
||||
)
|
||||
.provide_credentials()
|
||||
.await
|
||||
.expect_err("credential export failure should be propagated");
|
||||
let error = AwsAuthError::Credentials(error);
|
||||
assert_eq!(
|
||||
(
|
||||
error.is_retryable(),
|
||||
error
|
||||
.credentials_provider_error()
|
||||
.map(|error| (error.kind(), error.to_string())),
|
||||
),
|
||||
(
|
||||
retryable,
|
||||
Some((kind, "credential export failed".to_string()))
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn credentials_provider_failures_are_retryable() {
|
||||
assert!(
|
||||
AwsAuthError::Credentials(CredentialsError::provider_error("temporarily unavailable"))
|
||||
.is_retryable()
|
||||
);
|
||||
assert!(
|
||||
AwsAuthError::Credentials(CredentialsError::provider_timed_out(Duration::from_secs(1)))
|
||||
.is_retryable()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deterministic_aws_auth_errors_are_not_retryable() {
|
||||
assert!(!AwsAuthError::EmptyService.is_retryable());
|
||||
assert!(!AwsAuthError::MissingProfile.is_retryable());
|
||||
assert!(!AwsAuthError::Credentials(CredentialsError::not_loaded_no_source()).is_retryable());
|
||||
assert!(
|
||||
!AwsAuthError::Credentials(CredentialsError::invalid_configuration("bad profile"))
|
||||
.is_retryable()
|
||||
);
|
||||
assert!(
|
||||
!AwsAuthError::Credentials(CredentialsError::unhandled("unexpected response"))
|
||||
.is_retryable()
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn sign_includes_session_token_when_credentials_have_one() {
|
||||
let signed = test_context(Some("session-token"))
|
||||
.sign_at(
|
||||
test_request(),
|
||||
UNIX_EPOCH + Duration::from_secs(1_700_000_000),
|
||||
)
|
||||
.await
|
||||
.expect("request should sign");
|
||||
|
||||
assert_eq!(
|
||||
signing::header_value(&signed.headers, "x-amz-security-token"),
|
||||
Some("session-token".to_string())
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn load_rejects_invalid_configuration() {
|
||||
let config = AwsAuthConfig {
|
||||
profile: None,
|
||||
region: None,
|
||||
service: " ".to_string(),
|
||||
};
|
||||
let err = AwsAuthContext::load(
|
||||
config,
|
||||
akode_http_client::HttpClientFactory::new(
|
||||
akode_http_client::OutboundProxyPolicy::ReqwestDefault,
|
||||
),
|
||||
)
|
||||
.await
|
||||
.expect_err("empty service should be rejected");
|
||||
|
||||
assert_eq!(err.to_string(), "AWS service name must not be empty");
|
||||
|
||||
let config = AwsAuthConfig {
|
||||
profile: None,
|
||||
region: Some("us-east-1".to_string()),
|
||||
service: "bedrock".to_string(),
|
||||
};
|
||||
let err = AwsAuthContext::load_profile(
|
||||
config,
|
||||
akode_http_client::HttpClientFactory::new(
|
||||
akode_http_client::OutboundProxyPolicy::ReqwestDefault,
|
||||
),
|
||||
)
|
||||
.await
|
||||
.expect_err("profile auth should require a configured profile");
|
||||
|
||||
assert_eq!(err.to_string(), "AWS profile must be configured");
|
||||
}
|
||||
|
||||
#[path = "network_policy_tests.rs"]
|
||||
mod network_policy_tests;
|
||||
469
akode-rs/aws-auth/src/network_policy_tests.rs
Normal file
469
akode-rs/aws-auth/src/network_policy_tests.rs
Normal file
@@ -0,0 +1,469 @@
|
||||
//! Exercises policy on AWS SDK HTTP and the SDK's credential selection.
|
||||
|
||||
use crate::AwsAuthError::Policy;
|
||||
use crate::*;
|
||||
use aws_config::provider_config::ProviderConfig;
|
||||
use akode_http_client::DestinationPolicy;
|
||||
use akode_http_client::NetworkPolicyDenied::Revoked;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::error::Error;
|
||||
use tokio::io::AsyncReadExt;
|
||||
use tokio::io::AsyncWriteExt;
|
||||
use tokio::time::timeout;
|
||||
|
||||
#[tokio::test]
|
||||
async fn real_imds_credentials_stop_after_policy_revocation() -> Result<(), Box<dyn Error>> {
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await?;
|
||||
let controller = akode_http_client::NetworkPolicyController::default();
|
||||
let policy = controller.policy();
|
||||
let factory = akode_http_client::HttpClientFactory::new(
|
||||
akode_http_client::OutboundProxyPolicy::ReqwestDefault,
|
||||
)
|
||||
.with_network_policy(policy.clone().for_current_account());
|
||||
let http_client = crate::transport::http_client(factory);
|
||||
let imds_client = aws_config::imds::Client::builder()
|
||||
.configure(&ProviderConfig::default().with_http_client(http_client))
|
||||
.endpoint(format!("http://{}", listener.local_addr()?))
|
||||
.unwrap()
|
||||
.build();
|
||||
let credentials_provider = aws_config::imds::credentials::ImdsCredentialsProvider::builder()
|
||||
.profile("test-role")
|
||||
.imds_client(imds_client.clone())
|
||||
.build();
|
||||
let context = AwsAuthContext {
|
||||
network_policy: policy.clone().for_current_account(),
|
||||
credentials_provider: SharedCredentialsProvider::new(credentials_provider),
|
||||
region: "us-east-1".into(),
|
||||
service: "bedrock".into(),
|
||||
};
|
||||
let request = crate::tests::test_request();
|
||||
let server = async {
|
||||
let mut credentials_sent = false;
|
||||
loop {
|
||||
let (mut socket, _) = listener.accept().await?;
|
||||
let mut headers = Vec::new();
|
||||
while !headers.ends_with(b"\r\n\r\n") {
|
||||
headers.push(socket.read_u8().await?);
|
||||
}
|
||||
let body = if headers.starts_with(b"PUT /latest/api/token ") {
|
||||
"test-token"
|
||||
} else if credentials_sent {
|
||||
return Ok::<_, std::io::Error>(socket);
|
||||
} else {
|
||||
credentials_sent = true;
|
||||
r#"{"Code":"Success","AccessKeyId":"test-key","SecretAccessKey":"test-secret","Token":"test-session","Expiration":"2099-01-01T00:00:00Z"}"#
|
||||
};
|
||||
let response = format!(
|
||||
"HTTP/1.1 200 OK\r\nx-aws-ec2-metadata-token-ttl-seconds: 21600\r\nConnection: close\r\n\r\n{body}"
|
||||
);
|
||||
socket.write_all(response.as_bytes()).await?;
|
||||
}
|
||||
};
|
||||
controller.publish(policy.revision(), DestinationPolicy::Unrestricted);
|
||||
let signing = async {
|
||||
context.sign(request.clone()).await.unwrap();
|
||||
context.sign(request.clone()).await
|
||||
};
|
||||
tokio::pin!(signing);
|
||||
let timeout_duration = std::time::Duration::from_secs(/*secs*/ 5);
|
||||
let mut socket = tokio::select! {
|
||||
result = &mut signing => panic!("signing finished before revocation: {result:?}"),
|
||||
socket = timeout(timeout_duration, server) => socket??,
|
||||
};
|
||||
let restricted = DestinationPolicy::Restricted {
|
||||
allowed_hosts: Default::default(),
|
||||
};
|
||||
controller.publish(policy.revision(), restricted);
|
||||
let revoked = timeout(timeout_duration, signing).await?;
|
||||
assert!(matches!(revoked, Err(Policy(Revoked))));
|
||||
assert_eq!(timeout(timeout_duration, socket.read(&mut [0])).await??, 0);
|
||||
// The model remains allowed while metadata traffic is denied before connecting.
|
||||
controller.publish(
|
||||
policy.revision(),
|
||||
DestinationPolicy::Restricted {
|
||||
allowed_hosts: ["bedrock-runtime.us-east-1.amazonaws.com".to_string()].into(),
|
||||
},
|
||||
);
|
||||
context.sign(request.clone()).await?;
|
||||
let fresh = AwsAuthContext {
|
||||
credentials_provider: SharedCredentialsProvider::new(
|
||||
aws_config::imds::credentials::ImdsCredentialsProvider::builder()
|
||||
.profile("test-role")
|
||||
.imds_client(imds_client)
|
||||
.build(),
|
||||
),
|
||||
..context.clone()
|
||||
};
|
||||
let denied = fresh.sign(request.clone()).await;
|
||||
assert!(
|
||||
matches!(
|
||||
&denied,
|
||||
Err(Policy(akode_http_client::NetworkPolicyDenied::Destination))
|
||||
),
|
||||
"{denied:?}"
|
||||
);
|
||||
assert!(
|
||||
timeout(
|
||||
std::time::Duration::from_millis(/*millis*/ 100),
|
||||
listener.accept()
|
||||
)
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn allowlisted_static_keys_send_sigv4_and_denied_destination_sends_nothing()
|
||||
-> Result<(), Box<dyn Error>> {
|
||||
akode_utils_rustls_provider::ensure_rustls_crypto_provider();
|
||||
let certificate = rcgen::generate_simple_self_signed(vec!["127.0.0.1".to_string()])?;
|
||||
let trust = akode_http_client::HttpClientTlsConfig::default()
|
||||
.with_root_certificate_pem(certificate.cert.pem().as_bytes())?;
|
||||
let tls = tokio_rustls::TlsAcceptor::from(Arc::new(
|
||||
rustls::ServerConfig::builder()
|
||||
.with_no_client_auth()
|
||||
.with_single_cert(
|
||||
vec![certificate.cert.der().clone()],
|
||||
certificate.signing_key.into(),
|
||||
)?,
|
||||
));
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await?;
|
||||
let url = format!("https://{}/v1/responses", listener.local_addr()?);
|
||||
let controller = akode_http_client::NetworkPolicyController::default();
|
||||
let policy = controller.policy();
|
||||
controller.publish(
|
||||
policy.revision(),
|
||||
DestinationPolicy::Restricted {
|
||||
allowed_hosts: ["127.0.0.1".to_string()].into(),
|
||||
},
|
||||
);
|
||||
let factory = akode_http_client::HttpClientFactory::new(
|
||||
akode_http_client::OutboundProxyPolicy::ReqwestDefault,
|
||||
)
|
||||
.with_network_policy(policy.for_current_account());
|
||||
let context = AwsAuthContext::load_with_access_keys(
|
||||
AwsAuthConfig {
|
||||
profile: Some("unused-profile".into()),
|
||||
region: Some("us-east-1".into()),
|
||||
service: "bedrock".into(),
|
||||
},
|
||||
AwsAccessKeys {
|
||||
access_key_id: "static-key".into(),
|
||||
secret_access_key: "static-secret".into(),
|
||||
session_token: None,
|
||||
},
|
||||
factory.clone(),
|
||||
)
|
||||
.await?;
|
||||
let request = AwsRequestToSign {
|
||||
url: url.clone(),
|
||||
..crate::tests::test_request()
|
||||
};
|
||||
let signed = context.sign(request.clone()).await?;
|
||||
let client = akode_http_client::HttpClientBuilder::new().build_with_tls(
|
||||
&factory,
|
||||
akode_http_client::ClientRouteClass::Api,
|
||||
trust,
|
||||
);
|
||||
let server = async {
|
||||
let (socket, _) = listener.accept().await?;
|
||||
let mut socket = tls.accept(socket).await?;
|
||||
let mut headers = Vec::new();
|
||||
while !headers.ends_with(b"\r\n\r\n") {
|
||||
headers.push(socket.read_u8().await?);
|
||||
}
|
||||
socket
|
||||
.write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\nConnection: close\r\n\r\n{}")
|
||||
.await?;
|
||||
Ok::<_, Box<dyn Error>>(String::from_utf8(headers)?)
|
||||
};
|
||||
let (response, headers) = tokio::join!(
|
||||
client
|
||||
.post(&signed.url)
|
||||
.headers(signed.headers)
|
||||
.body(request.body.clone())
|
||||
.send(),
|
||||
server
|
||||
);
|
||||
assert!(response?.status().is_success());
|
||||
assert!(headers?.contains("Credential=static-key/"));
|
||||
controller.publish(
|
||||
controller.policy().revision(),
|
||||
DestinationPolicy::Restricted {
|
||||
allowed_hosts: Default::default(),
|
||||
},
|
||||
);
|
||||
assert!(matches!(
|
||||
context.sign(request).await,
|
||||
Err(Policy(akode_http_client::NetworkPolicyDenied::Destination))
|
||||
));
|
||||
assert!(
|
||||
timeout(
|
||||
std::time::Duration::from_millis(/*millis*/ 100),
|
||||
listener.accept()
|
||||
)
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn sdk_credentials_preserve_profile_processes_and_environment_precedence()
|
||||
-> Result<(), Box<dyn Error>> {
|
||||
for case in [
|
||||
"restricted-static",
|
||||
"restricted-process",
|
||||
"unrestricted-process",
|
||||
"unrestricted-offset-process",
|
||||
"restricted-role-process",
|
||||
"unrestricted-role-process",
|
||||
"env-precedence",
|
||||
"profile-precedence",
|
||||
] {
|
||||
let home = tempfile::tempdir()?;
|
||||
let marker = home.path().join("process-started");
|
||||
let expiration = if case == "unrestricted-offset-process" {
|
||||
"2099-01-01T01:30:00+01:30"
|
||||
} else {
|
||||
"2099-01-01T00:00:00Z"
|
||||
};
|
||||
let json = format!(
|
||||
r#"{{"Version":1,"AccessKeyId":"process-key","SecretAccessKey":"process-secret","Expiration":"{expiration}"}}"#
|
||||
);
|
||||
std::fs::write(home.path().join("credentials-output.json"), &json)?;
|
||||
let command = if cfg!(windows) {
|
||||
"echo started > process-started & type credentials-output.json".to_string()
|
||||
} else {
|
||||
format!(
|
||||
"printf started > '{}' && printf '%s' '{json}'",
|
||||
marker.to_string_lossy().replace('\'', "'\\''")
|
||||
)
|
||||
};
|
||||
let contents = if matches!(case, "restricted-static" | "profile-precedence") {
|
||||
"[managed]\naws_access_key_id = profile-key\naws_secret_access_key = profile-secret\n"
|
||||
.to_string()
|
||||
} else {
|
||||
format!(
|
||||
"[managed]\ncredential_process = {command}\naws_access_key_id = fallback-key\naws_secret_access_key = fallback-secret\n"
|
||||
)
|
||||
};
|
||||
let credentials = home.path().join("credentials");
|
||||
let config = home.path().join("config");
|
||||
std::fs::write(&credentials, contents)?;
|
||||
std::fs::write(
|
||||
&config,
|
||||
if case.contains("role-process") {
|
||||
"[profile managed] # SDK accepts section comments\nrole_arn = arn:aws:iam::123456789012:role/test\nsource_profile = managed # self source\n"
|
||||
} else {
|
||||
""
|
||||
},
|
||||
)?;
|
||||
let role_request = if case == "unrestricted-role-process" {
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await?;
|
||||
let endpoint = format!("http://{}", listener.local_addr()?);
|
||||
let server = tokio::spawn(async move {
|
||||
let (mut socket, _) = listener.accept().await?;
|
||||
let mut headers = Vec::new();
|
||||
while !headers.ends_with(b"\r\n\r\n") {
|
||||
headers.push(socket.read_u8().await?);
|
||||
}
|
||||
let headers = String::from_utf8(headers).map_err(std::io::Error::other)?;
|
||||
let content_length = headers
|
||||
.lines()
|
||||
.find_map(|line| {
|
||||
let (name, value) = line.split_once(':')?;
|
||||
name.eq_ignore_ascii_case("content-length")
|
||||
.then(|| value.trim().parse::<usize>())
|
||||
})
|
||||
.transpose()
|
||||
.map_err(std::io::Error::other)?
|
||||
.unwrap_or_default();
|
||||
// Drain the POST body before closing so Windows does not reset the response.
|
||||
socket.read_exact(&mut vec![0; content_length]).await?;
|
||||
let body = "<AssumeRoleResponse><AssumeRoleResult><Credentials><AccessKeyId>assumed-key</AccessKeyId><SecretAccessKey>assumed-secret</SecretAccessKey><SessionToken>assumed-token</SessionToken><Expiration>2099-01-01T00:00:00Z</Expiration></Credentials></AssumeRoleResult></AssumeRoleResponse>";
|
||||
socket.write_all(format!("HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", body.len()).as_bytes()).await?;
|
||||
Ok::<_, std::io::Error>(headers)
|
||||
});
|
||||
Some((endpoint, server))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let mut child = std::process::Command::new(std::env::current_exe()?);
|
||||
child
|
||||
.current_dir(home.path())
|
||||
.args([
|
||||
"--ignored",
|
||||
"--exact",
|
||||
"tests::network_policy_tests::sdk_profile_probe",
|
||||
])
|
||||
.env("AKODE_AWS_PROFILE_PROBE_CASE", case)
|
||||
.env("AWS_CONFIG_FILE", config)
|
||||
.env("AWS_SHARED_CREDENTIALS_FILE", credentials)
|
||||
.env("AWS_EC2_METADATA_DISABLED", "true")
|
||||
.env_remove("AWS_ACCESS_KEY_ID")
|
||||
.env_remove("AWS_SECRET_ACCESS_KEY")
|
||||
.env_remove("SECRET_ACCESS_KEY")
|
||||
.env_remove("AWS_SESSION_TOKEN");
|
||||
if matches!(case, "env-precedence" | "profile-precedence") {
|
||||
child
|
||||
.env("AWS_ACCESS_KEY_ID", "env-key")
|
||||
.env("AWS_SECRET_ACCESS_KEY", "env-secret");
|
||||
}
|
||||
if let Some((endpoint, _)) = &role_request {
|
||||
child.env("AWS_ENDPOINT_URL_STS", endpoint);
|
||||
}
|
||||
let output = tokio::task::spawn_blocking(move || child.output()).await??;
|
||||
assert!(
|
||||
output.status.success(),
|
||||
"{case}: {}\n{}",
|
||||
String::from_utf8_lossy(&output.stdout),
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
assert_eq!(marker.exists(), case.contains("process"), "{case}");
|
||||
if let Some((_, server)) = role_request {
|
||||
assert!(server.await??.contains("Credential=process-key/"));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn sdk_default_credentials_keep_endpoint_modes_from_environment_and_profile()
|
||||
-> Result<(), Box<dyn Error>> {
|
||||
for case in ["endpoint-modes-env", "endpoint-modes-profile"] {
|
||||
let home = tempfile::tempdir()?;
|
||||
let credentials = home.path().join("credentials");
|
||||
let config = home.path().join("config");
|
||||
std::fs::write(
|
||||
&credentials,
|
||||
"[source]\naws_access_key_id = source-key\naws_secret_access_key = source-secret\n",
|
||||
)?;
|
||||
let mut profile = "[profile managed]\nrole_arn = arn:aws:iam::123456789012:role/test\nsource_profile = source\n".to_string();
|
||||
if case == "endpoint-modes-profile" {
|
||||
profile.push_str("use_fips_endpoint = true\nuse_dualstack_endpoint = true\n");
|
||||
}
|
||||
std::fs::write(&config, profile)?;
|
||||
let proxy = tokio::net::TcpListener::bind("127.0.0.1:0").await?;
|
||||
let proxy_url = format!("http://{}", proxy.local_addr()?);
|
||||
let server = tokio::spawn(async move {
|
||||
let (mut socket, _) = proxy.accept().await?;
|
||||
let mut headers = Vec::new();
|
||||
while !headers.ends_with(b"\r\n\r\n") {
|
||||
headers.push(socket.read_u8().await?);
|
||||
}
|
||||
socket
|
||||
.write_all(b"HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\n\r\n")
|
||||
.await?;
|
||||
String::from_utf8(headers).map_err(std::io::Error::other)
|
||||
});
|
||||
let mut child = std::process::Command::new(std::env::current_exe()?);
|
||||
child
|
||||
.args([
|
||||
"--ignored",
|
||||
"--exact",
|
||||
"tests::network_policy_tests::sdk_profile_probe",
|
||||
])
|
||||
.env("AKODE_AWS_PROFILE_PROBE_CASE", case)
|
||||
.env("AWS_CONFIG_FILE", config)
|
||||
.env("AWS_SHARED_CREDENTIALS_FILE", credentials)
|
||||
.env("AWS_EC2_METADATA_DISABLED", "true")
|
||||
.env("AWS_MAX_ATTEMPTS", "1")
|
||||
.env("HTTPS_PROXY", &proxy_url)
|
||||
.env("https_proxy", proxy_url)
|
||||
.env("NO_PROXY", "")
|
||||
.env("no_proxy", "");
|
||||
for variable in [
|
||||
"AWS_ACCESS_KEY_ID",
|
||||
"AWS_SECRET_ACCESS_KEY",
|
||||
"SECRET_ACCESS_KEY",
|
||||
"AWS_SESSION_TOKEN",
|
||||
"AWS_ENDPOINT_URL",
|
||||
"AWS_ENDPOINT_URL_STS",
|
||||
"AWS_USE_FIPS_ENDPOINT",
|
||||
"AWS_USE_DUALSTACK_ENDPOINT",
|
||||
] {
|
||||
child.env_remove(variable);
|
||||
}
|
||||
if case == "endpoint-modes-env" {
|
||||
child
|
||||
.env("AWS_USE_FIPS_ENDPOINT", "true")
|
||||
.env("AWS_USE_DUALSTACK_ENDPOINT", "true");
|
||||
}
|
||||
let output = tokio::task::spawn_blocking(move || child.output()).await??;
|
||||
assert!(
|
||||
output.status.success(),
|
||||
"{case}: {}\n{}",
|
||||
String::from_utf8_lossy(&output.stdout),
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
let request = timeout(std::time::Duration::from_secs(/*secs*/ 5), server).await???;
|
||||
assert!(request.starts_with("CONNECT sts-fips.us-east-1.api.aws:443 "));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "isolated AWS environment fixture"]
|
||||
fn sdk_profile_probe() -> Result<(), Box<dyn Error>> {
|
||||
let case = std::env::var("AKODE_AWS_PROFILE_PROBE_CASE")?;
|
||||
tokio::runtime::Runtime::new()?.block_on(async {
|
||||
let controller = akode_http_client::NetworkPolicyController::default();
|
||||
let policy = controller.policy();
|
||||
let destination = if case.starts_with("unrestricted") {
|
||||
DestinationPolicy::Unrestricted
|
||||
} else {
|
||||
let mut allowed_hosts = ["bedrock-runtime.us-east-1.amazonaws.com".to_string()]
|
||||
.into_iter()
|
||||
.collect::<std::collections::BTreeSet<_>>();
|
||||
if case.starts_with("endpoint-modes-") {
|
||||
allowed_hosts.insert("sts-fips.us-east-1.api.aws".to_string());
|
||||
}
|
||||
DestinationPolicy::Restricted { allowed_hosts }
|
||||
};
|
||||
controller.publish(policy.revision(), destination);
|
||||
let factory = akode_http_client::HttpClientFactory::new(
|
||||
akode_http_client::OutboundProxyPolicy::ReqwestDefault,
|
||||
)
|
||||
.with_network_policy(policy.for_current_account());
|
||||
let config = AwsAuthConfig {
|
||||
profile: Some("managed".into()),
|
||||
region: Some("us-east-1".into()),
|
||||
service: "bedrock".into(),
|
||||
};
|
||||
let context = if case == "env-precedence" || case.starts_with("endpoint-modes-") {
|
||||
AwsAuthContext::load(config, factory).await?
|
||||
} else {
|
||||
AwsAuthContext::load_profile(config, factory).await?
|
||||
};
|
||||
let signed = context.sign(crate::tests::test_request()).await;
|
||||
if case.starts_with("endpoint-modes-") {
|
||||
assert!(
|
||||
matches!(signed, Err(AwsAuthError::Credentials(_))),
|
||||
"{signed:?}"
|
||||
);
|
||||
} else if case == "restricted-role-process" {
|
||||
assert!(
|
||||
matches!(
|
||||
signed,
|
||||
Err(Policy(akode_http_client::NetworkPolicyDenied::Destination))
|
||||
),
|
||||
"{signed:?}"
|
||||
);
|
||||
} else {
|
||||
let key = match case.as_str() {
|
||||
"restricted-static" | "profile-precedence" => "profile-key",
|
||||
"env-precedence" => "env-key",
|
||||
"unrestricted-role-process" => "assumed-key",
|
||||
_ => "process-key",
|
||||
};
|
||||
assert!(
|
||||
signed?.headers[http::header::AUTHORIZATION]
|
||||
.to_str()?
|
||||
.contains(&format!("Credential={key}/"))
|
||||
);
|
||||
}
|
||||
Ok::<_, Box<dyn Error>>(())
|
||||
})
|
||||
}
|
||||
76
akode-rs/aws-auth/src/signing.rs
Normal file
76
akode-rs/aws-auth/src/signing.rs
Normal file
@@ -0,0 +1,76 @@
|
||||
use std::str::FromStr;
|
||||
use std::time::SystemTime;
|
||||
|
||||
use aws_credential_types::Credentials;
|
||||
use aws_sigv4::http_request::SignableBody;
|
||||
use aws_sigv4::http_request::SignableRequest;
|
||||
use aws_sigv4::http_request::SigningSettings;
|
||||
use aws_sigv4::http_request::sign;
|
||||
use aws_sigv4::sign::v4;
|
||||
use http::Request;
|
||||
use http::Uri;
|
||||
|
||||
use crate::AwsAuthError;
|
||||
use crate::AwsRequestToSign;
|
||||
use crate::AwsSignedRequest;
|
||||
|
||||
pub(crate) fn sign_request(
|
||||
credentials: &Credentials,
|
||||
region: &str,
|
||||
service: &str,
|
||||
request: AwsRequestToSign,
|
||||
time: SystemTime,
|
||||
) -> Result<AwsSignedRequest, AwsAuthError> {
|
||||
let signable_headers = request
|
||||
.headers
|
||||
.iter()
|
||||
.map(|(name, value)| {
|
||||
Ok::<_, AwsAuthError>((
|
||||
name.as_str(),
|
||||
value.to_str().map_err(AwsAuthError::InvalidHeaderValue)?,
|
||||
))
|
||||
})
|
||||
.collect::<Result<Vec<_>, _>>()?;
|
||||
let signable_request = SignableRequest::new(
|
||||
request.method.as_str(),
|
||||
request.url.as_str(),
|
||||
signable_headers.into_iter(),
|
||||
SignableBody::Bytes(request.body.as_ref()),
|
||||
)
|
||||
.map_err(AwsAuthError::SigningRequest)?;
|
||||
let identity = credentials.clone().into();
|
||||
|
||||
let signing_params = v4::SigningParams::builder()
|
||||
.identity(&identity)
|
||||
.region(region)
|
||||
.name(service)
|
||||
.time(time)
|
||||
.settings(SigningSettings::default())
|
||||
.build()
|
||||
.map_err(|err| AwsAuthError::SigningParams(err.to_string()))?;
|
||||
let (instructions, _signature) = sign(signable_request, &signing_params.into())
|
||||
.map_err(AwsAuthError::SigningFailure)?
|
||||
.into_parts();
|
||||
|
||||
let uri = Uri::from_str(&request.url).map_err(AwsAuthError::InvalidUri)?;
|
||||
let mut http_request = Request::builder()
|
||||
.method(request.method)
|
||||
.uri(uri)
|
||||
.body(())
|
||||
.map_err(AwsAuthError::BuildHttpRequest)?;
|
||||
*http_request.headers_mut() = request.headers;
|
||||
instructions.apply_to_request_http1x(&mut http_request);
|
||||
|
||||
Ok(AwsSignedRequest {
|
||||
url: http_request.uri().to_string(),
|
||||
headers: http_request.headers().clone(),
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) fn header_value(headers: &http::HeaderMap, name: &str) -> Option<String> {
|
||||
headers
|
||||
.get(name)
|
||||
.and_then(|value| value.to_str().ok())
|
||||
.map(str::to_string)
|
||||
}
|
||||
119
akode-rs/aws-auth/src/transport.rs
Normal file
119
akode-rs/aws-auth/src/transport.rs
Normal file
@@ -0,0 +1,119 @@
|
||||
//! Routes AWS credential and region HTTP through the application-owned client.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::pin::Pin;
|
||||
use std::sync::Mutex;
|
||||
use std::task::Context;
|
||||
use std::task::Poll;
|
||||
use std::time::Duration;
|
||||
|
||||
use aws_smithy_runtime_api::client::http::HttpConnector;
|
||||
use aws_smithy_runtime_api::client::http::HttpConnectorFuture;
|
||||
use aws_smithy_runtime_api::client::http::SharedHttpClient;
|
||||
use aws_smithy_runtime_api::client::http::SharedHttpConnector;
|
||||
use aws_smithy_runtime_api::client::http::http_client_fn;
|
||||
use aws_smithy_runtime_api::client::orchestrator::HttpRequest;
|
||||
use aws_smithy_runtime_api::client::orchestrator::HttpResponse;
|
||||
use aws_smithy_runtime_api::client::result::ConnectorError;
|
||||
use aws_smithy_types::body::SdkBody;
|
||||
use bytes::Bytes;
|
||||
use akode_http_client::ClientRouteClass;
|
||||
use akode_http_client::HttpClient;
|
||||
use akode_http_client::HttpClientBuilder;
|
||||
use akode_http_client::HttpClientFactory;
|
||||
use akode_http_client::HttpError;
|
||||
use akode_http_client::RouteAwareClientPool;
|
||||
use http_body_util::BodyExt;
|
||||
|
||||
pub(crate) fn http_client(factory: HttpClientFactory) -> SharedHttpClient {
|
||||
let connectors = Mutex::new(HashMap::new());
|
||||
http_client_fn(move |settings, _| {
|
||||
let timeouts = (settings.connect_timeout(), settings.read_timeout());
|
||||
connectors
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
.entry(timeouts)
|
||||
.or_insert_with(|| {
|
||||
// Smithy's default connector does not follow redirects. Keep that behavior
|
||||
// so signed headers and metadata tokens cannot be sent to another origin.
|
||||
let mut builder = HttpClientBuilder::new()
|
||||
.without_redirects()
|
||||
.without_request_logging();
|
||||
if let Some(timeout) = timeouts.0 {
|
||||
builder = builder.connect_timeout(timeout);
|
||||
}
|
||||
SharedHttpConnector::new(CredentialConnector {
|
||||
client: RouteAwareClientPool::with_builder(
|
||||
factory.clone(),
|
||||
ClientRouteClass::Auth,
|
||||
builder,
|
||||
)
|
||||
.into_client(),
|
||||
read_timeout: timeouts.1,
|
||||
})
|
||||
})
|
||||
.clone()
|
||||
})
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct CredentialConnector {
|
||||
client: HttpClient,
|
||||
read_timeout: Option<Duration>,
|
||||
}
|
||||
|
||||
impl HttpConnector for CredentialConnector {
|
||||
fn call(&self, request: HttpRequest) -> HttpConnectorFuture {
|
||||
let client = self.client.clone();
|
||||
let read_timeout = self.read_timeout;
|
||||
HttpConnectorFuture::new(async move {
|
||||
let request = request
|
||||
.try_into_http1x()
|
||||
.map_err(|error| ConnectorError::user(Box::new(error)))?;
|
||||
let (parts, body) = request.into_parts();
|
||||
let mut request = client
|
||||
.request(parts.method, parts.uri.to_string())
|
||||
.headers(parts.headers)
|
||||
.version(parts.version);
|
||||
if let Some(timeout) = read_timeout {
|
||||
request = request.timeout(timeout);
|
||||
}
|
||||
request = match body.bytes() {
|
||||
Some(bytes) => request.body(Bytes::copy_from_slice(bytes)),
|
||||
None => request.body_stream(body.into_data_stream()),
|
||||
};
|
||||
let response = request.send().await.map_err(|error| match error {
|
||||
HttpError::Policy(error) => ConnectorError::user(Box::new(error)),
|
||||
error if error.is_timeout() => ConnectorError::timeout(Box::new(error)),
|
||||
error if error.is_connect() => ConnectorError::io(Box::new(error)),
|
||||
error => ConnectorError::user(Box::new(error)),
|
||||
})?;
|
||||
HttpResponse::try_from(
|
||||
response
|
||||
.into_http_response()
|
||||
.map(|body| SdkBody::from_body_1_x(SyncBody(Mutex::new(Box::pin(body))))),
|
||||
)
|
||||
.map_err(|error| ConnectorError::user(Box::new(error)))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Smithy requires Sync bodies; the shared client's cancellation future is only Send.
|
||||
// Polling stays synchronous, while the body retains policy checks for every frame.
|
||||
struct SyncBody<B>(Mutex<Pin<Box<B>>>);
|
||||
|
||||
impl<B: http_body::Body> http_body::Body for SyncBody<B> {
|
||||
type Data = B::Data;
|
||||
type Error = B::Error;
|
||||
|
||||
fn poll_frame(
|
||||
self: Pin<&mut Self>,
|
||||
cx: &mut Context<'_>,
|
||||
) -> Poll<Option<Result<http_body::Frame<Self::Data>, Self::Error>>> {
|
||||
self.0
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
.as_mut()
|
||||
.poll_frame(cx)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user