-
Notifications
You must be signed in to change notification settings - Fork 193
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
AWS Endpoint Middleware #188
Changes from 1 commit
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,5 +1,5 @@ | ||
[package] | ||
name = "auth" | ||
name = "aws-auth" | ||
version = "0.1.0" | ||
authors = ["Russell Cohen <[email protected]>"] | ||
edition = "2018" | ||
|
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -3,13 +3,13 @@ | |
* SPDX-License-Identifier: Apache-2.0. | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. formatting only |
||
*/ | ||
|
||
use crate::{ProvideCredentials, Credentials, CredentialsError}; | ||
use std::env::VarError; | ||
use crate::{Credentials, CredentialsError, ProvideCredentials}; | ||
use std::collections::HashMap; | ||
use std::env::VarError; | ||
|
||
/// Load Credentials from Environment Variables | ||
pub struct EnvironmentVariableCredentialsProvider { | ||
env: Box<dyn Fn(&str) -> Result<String, VarError> + Send + Sync> | ||
env: Box<dyn Fn(&str) -> Result<String, VarError> + Send + Sync>, | ||
} | ||
|
||
impl EnvironmentVariableCredentialsProvider { | ||
|
@@ -21,8 +21,10 @@ impl EnvironmentVariableCredentialsProvider { | |
fn for_map(env: HashMap<String, String>) -> Self { | ||
EnvironmentVariableCredentialsProvider { | ||
env: Box::new(move |key: &str| { | ||
env.get(key).ok_or(VarError::NotPresent).map(|k|k.to_string()) | ||
}) | ||
env.get(key) | ||
.ok_or(VarError::NotPresent) | ||
.map(|k| k.to_string()) | ||
}), | ||
} | ||
} | ||
} | ||
|
@@ -36,31 +38,32 @@ const ENV_PROVIDER: &'static str = "EnvironmentVariable"; | |
impl ProvideCredentials for EnvironmentVariableCredentialsProvider { | ||
fn credentials(&self) -> Result<Credentials, CredentialsError> { | ||
let access_key = (self.env)("AWS_ACCESS_KEY_ID").map_err(to_cred_error)?; | ||
let secret_key = | ||
(self.env)("AWS_SECRET_ACCESS_KEY").or_else(|_|(self.env)("SECRET_ACCESS_KEY")).map_err(to_cred_error)?; | ||
let secret_key = (self.env)("AWS_SECRET_ACCESS_KEY") | ||
.or_else(|_| (self.env)("SECRET_ACCESS_KEY")) | ||
.map_err(to_cred_error)?; | ||
let session_token = (self.env)("AWS_SESSION_TOKEN").ok(); | ||
Ok(Credentials { | ||
access_key_id: access_key, | ||
secret_access_key: secret_key, | ||
session_token, | ||
expires_after: None, | ||
provider_name: ENV_PROVIDER | ||
provider_name: ENV_PROVIDER, | ||
}) | ||
} | ||
} | ||
|
||
fn to_cred_error(err: VarError) -> CredentialsError { | ||
match err { | ||
VarError::NotPresent => CredentialsError::CredentialsNotLoaded, | ||
e @ VarError::NotUnicode(_) => CredentialsError::Unhandled(Box::new(e)) | ||
e @ VarError::NotUnicode(_) => CredentialsError::Unhandled(Box::new(e)), | ||
} | ||
} | ||
|
||
#[cfg(test)] | ||
mod test { | ||
use crate::provider::EnvironmentVariableCredentialsProvider; | ||
use crate::{CredentialsError, ProvideCredentials}; | ||
use std::collections::HashMap; | ||
use crate::{ProvideCredentials, CredentialsError}; | ||
|
||
#[test] | ||
fn valid_no_token() { | ||
|
@@ -101,7 +104,6 @@ mod test { | |
assert_eq!(creds.session_token.unwrap(), "token"); | ||
assert_eq!(creds.access_key_id, "access"); | ||
assert_eq!(creds.secret_access_key, "secret"); | ||
|
||
} | ||
|
||
#[test] | ||
|
@@ -110,8 +112,8 @@ mod test { | |
let provider = EnvironmentVariableCredentialsProvider::for_map(env); | ||
let err = provider.credentials().expect_err("no credentials defined"); | ||
match err { | ||
CredentialsError::Unhandled(_ ) => panic!("wrong error type"), | ||
_ => () | ||
CredentialsError::Unhandled(_) => panic!("wrong error type"), | ||
_ => (), | ||
}; | ||
} | ||
|
||
|
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,13 @@ | ||
[package] | ||
name = "aws-endpoint" | ||
version = "0.1.0" | ||
authors = ["Russell Cohen <[email protected]>"] | ||
edition = "2018" | ||
description = "AWS Endpoint Support" | ||
|
||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html | ||
|
||
[dependencies] | ||
smithy-http = { path = "../../../rust-runtime/smithy-http"} | ||
aws-types = { path = "../aws-types" } | ||
http = "0.2.3" |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,161 @@ | ||
use aws_types::{Region, SigningRegion, SigningService}; | ||
use http::Uri; | ||
use smithy_http::endpoint::{Endpoint, EndpointPrefix}; | ||
use smithy_http::middleware::MapRequest; | ||
use smithy_http::operation::Request; | ||
use smithy_http::property_bag::PropertyBag; | ||
use std::error::Error; | ||
use std::fmt; | ||
use std::fmt::{Debug, Display, Formatter}; | ||
use std::str::FromStr; | ||
use std::sync::Arc; | ||
|
||
/// Endpoint to connect to an AWS Service | ||
/// | ||
/// An `AwsEndpoint` captures all necessary information needed to connect to an AWS service, including: | ||
/// - The URI of the endpoint (needed to actually send the request) | ||
/// - The name of the service (needed downstream for signing) | ||
/// - The signing region (which may differ from the actual region) | ||
#[derive(Clone)] | ||
pub struct AwsEndpoint { | ||
endpoint: Endpoint, | ||
signing_service: SigningService, | ||
signing_region: SigningRegion, | ||
} | ||
|
||
pub type BoxError = Box<dyn Error + Send + Sync + 'static>; | ||
|
||
/// Resolve the AWS Endpoint for a given region | ||
/// | ||
/// Each individual service will generate their own implementation of `ResolveAwsEndpoint`. This implementation | ||
/// may use endpoint discovery (if used by the service). The list of supported regions for a given service | ||
/// will be codegenerated from `endpoints.json`. | ||
pub trait ResolveAwsEndpoint: Send + Sync { | ||
// TODO: consider if we want modeled error variants here | ||
fn endpoint(&self, region: &Region) -> Result<AwsEndpoint, BoxError>; | ||
} | ||
|
||
/// Default AWS Endpoint Implementation | ||
/// | ||
/// This is used as a temporary stub. Prior to GA, this will be replaced with specifically generated endpoint | ||
/// resolvers for each service that model the endpoints for each service correctly. Some services differ | ||
/// from the standard endpoint pattern. | ||
pub struct DefaultAwsEndpointResolver { | ||
service: &'static str, | ||
} | ||
|
||
impl DefaultAwsEndpointResolver { | ||
pub fn for_service(service: &'static str) -> Self { | ||
Self { service } | ||
} | ||
} | ||
|
||
impl ResolveAwsEndpoint for DefaultAwsEndpointResolver { | ||
fn endpoint(&self, region: &Region) -> Result<AwsEndpoint, BoxError> { | ||
let uri = Uri::from_str(&format!( | ||
"https://{}.{}.amazonaws.com", | ||
region.as_ref(), | ||
self.service | ||
))?; | ||
Ok(AwsEndpoint { | ||
endpoint: Endpoint::mutable(uri), | ||
signing_region: region.clone().into(), | ||
signing_service: SigningService::from_static(self.service), | ||
}) | ||
} | ||
} | ||
|
||
type AwsEndpointProvider = Arc<dyn ResolveAwsEndpoint>; | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. question I see the term There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. No, good catch. Halfway through I was looking at your doc and decided I liked Resolver better since it was a bit more descriptive |
||
fn get_endpoint_provider(config: &PropertyBag) -> Option<&AwsEndpointProvider> { | ||
config.get() | ||
} | ||
|
||
pub fn set_endpoint_provider(provider: AwsEndpointProvider, config: &mut PropertyBag) { | ||
config.insert(provider); | ||
} | ||
|
||
/// Middleware Stage to Add an Endpoint to a Request | ||
/// | ||
/// AwsEndpointStage implements [`MapRequest`](smithy_http::middleware::MapRequest). It will: | ||
/// 1. Load an endpoint provider from the property bag. | ||
/// 2. Load an endpoint given the [`Region`](aws_types::Region) in the property bag. | ||
/// 3. Apply the endpoint to the URI in the request | ||
/// 4. Set the `SigningRegion` and `SigningService` in the property bag to drive downstream | ||
/// signing middleware. | ||
pub struct AwsEndpointStage; | ||
|
||
#[derive(Debug)] | ||
pub enum AwsEndpointStageError { | ||
NoEndpointProvider, | ||
NoRegion, | ||
EndpointResolutionError(BoxError), | ||
} | ||
|
||
impl Display for AwsEndpointStageError { | ||
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { | ||
Debug::fmt(self, f) | ||
} | ||
} | ||
impl Error for AwsEndpointStageError {} | ||
|
||
impl MapRequest for AwsEndpointStage { | ||
type Error = AwsEndpointStageError; | ||
|
||
fn apply(&self, request: Request) -> Result<Request, Self::Error> { | ||
request.augment(|mut http_req, config| { | ||
let provider = | ||
get_endpoint_provider(config).ok_or(AwsEndpointStageError::NoEndpointProvider)?; | ||
let region = config | ||
.get::<Region>() | ||
.ok_or(AwsEndpointStageError::NoRegion)?; | ||
let endpoint = provider | ||
.endpoint(region) | ||
.map_err(AwsEndpointStageError::EndpointResolutionError)?; | ||
config.insert(endpoint.signing_region); | ||
config.insert(endpoint.signing_service); | ||
endpoint | ||
.endpoint | ||
.set_endpoint(http_req.uri_mut(), config.get::<EndpointPrefix>()); | ||
Ok(http_req) | ||
}) | ||
} | ||
} | ||
|
||
#[cfg(test)] | ||
mod test { | ||
use crate::{set_endpoint_provider, AwsEndpointStage, DefaultAwsEndpointResolver}; | ||
use aws_types::{Region, SigningRegion, SigningService}; | ||
use http::Uri; | ||
use smithy_http::body::SdkBody; | ||
use smithy_http::middleware::MapRequest; | ||
use smithy_http::operation; | ||
use std::sync::Arc; | ||
|
||
#[test] | ||
fn default_endpoint_updates_request() { | ||
let provider = Arc::new(DefaultAwsEndpointResolver::for_service("kinesis")); | ||
let req = http::Request::new(SdkBody::from("")); | ||
let region = Region::new("us-east-1"); | ||
let mut req = operation::Request::new(req); | ||
{ | ||
let mut conf = req.config_mut(); | ||
conf.insert(region.clone()); | ||
set_endpoint_provider(provider, &mut conf); | ||
}; | ||
let req = AwsEndpointStage.apply(req).expect("should succeed"); | ||
assert_eq!( | ||
req.config().get(), | ||
Some(&SigningRegion::from(region.clone())) | ||
); | ||
assert_eq!( | ||
req.config().get(), | ||
Some(&SigningService::from_static("kinesis")) | ||
); | ||
|
||
let (req, _conf) = req.into_parts(); | ||
assert_eq!( | ||
req.uri(), | ||
&Uri::from_static("https://us-east-1.kinesis.amazonaws.com") | ||
); | ||
} | ||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,9 @@ | ||
[package] | ||
name = "aws-types" | ||
version = "0.1.0" | ||
authors = ["Russell Cohen <[email protected]>"] | ||
edition = "2018" | ||
|
||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html | ||
|
||
[dependencies] |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,58 @@ | ||
use std::borrow::Cow; | ||
use std::sync::Arc; | ||
|
||
/// The region to send requests to. | ||
/// | ||
/// The region MUST be specified on a request. It may be configured globally or on a | ||
/// per-client basis unless otherwise noted. A full list of regions is found in the | ||
/// "Regions and Endpoints" document. | ||
/// | ||
/// See http://docs.aws.amazon.com/general/latest/gr/rande.html for | ||
/// information on AWS regions. | ||
#[derive(Clone, Debug, PartialEq, Eq)] | ||
pub struct Region(Arc<String>); | ||
impl AsRef<str> for Region { | ||
fn as_ref(&self) -> &str { | ||
self.0.as_str() | ||
} | ||
} | ||
|
||
impl Region { | ||
pub fn new(region: impl Into<String>) -> Self { | ||
Self(Arc::new(region.into())) | ||
} | ||
} | ||
|
||
/// The region to use when signing requests | ||
/// | ||
/// Generally, user code will not need to interact with `SigningRegion`. See `[Region](crate::Region)`. | ||
#[derive(Clone, Debug, PartialEq, Eq)] | ||
pub struct SigningRegion(Arc<String>); | ||
impl AsRef<str> for SigningRegion { | ||
fn as_ref(&self) -> &str { | ||
self.0.as_str() | ||
} | ||
} | ||
|
||
impl From<Region> for SigningRegion { | ||
fn from(inp: Region) -> Self { | ||
SigningRegion(inp.0) | ||
} | ||
} | ||
|
||
/// The name of the service used to sign this request | ||
/// | ||
/// Generally, user code should never interact with `SigningService` directly | ||
#[derive(Clone, Debug, PartialEq, Eq)] | ||
pub struct SigningService(Cow<'static, str>); | ||
impl AsRef<str> for SigningService { | ||
fn as_ref(&self) -> &str { | ||
&self.0 | ||
} | ||
} | ||
|
||
impl SigningService { | ||
pub fn from_static(service: &'static str) -> Self { | ||
SigningService(Cow::Borrowed(service)) | ||
} | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
formatting only. the CI format gate isn't set up for the aws runtime yet.