Skip to content

Commit

Permalink
[rust] add support for withAWSV4Signature option in reqwest (OpenAPIT…
Browse files Browse the repository at this point in the history
…ools#11193)

Signed-off-by: Jérôme Jutteau <[email protected]>
  • Loading branch information
jerome-jutteau committed Feb 23, 2022
1 parent 6e7c39e commit 2d28dc0
Show file tree
Hide file tree
Showing 6 changed files with 99 additions and 0 deletions.
1 change: 1 addition & 0 deletions docs/generators/rust.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl
|supportAsync|If set, generate async function call instead. This option is for 'reqwest' library only| |true|
|supportMultipleResponses|If set, return type wraps an enum of all possible 2xx schemas. This option is for 'reqwest' library only| |false|
|useSingleRequestParameter|Setting this property to true will generate functions with a single argument containing all API endpoint parameters instead of one argument per parameter.| |false|
|withAWSV4Signature|whether to include AWS v4 signature support| |false|

## IMPORT MAPPING

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ public class RustClientCodegen extends DefaultCodegen implements CodegenConfig {
private boolean useSingleRequestParameter = false;
private boolean supportAsync = true;
private boolean supportMultipleResponses = false;
private boolean withAWSV4Signature = false;

public static final String PACKAGE_NAME = "packageName";
public static final String PACKAGE_VERSION = "packageVersion";
Expand Down Expand Up @@ -181,6 +182,8 @@ public RustClientCodegen() {
cliOptions.add(new CliOption(SUPPORT_MULTIPLE_RESPONSES, "If set, return type wraps an enum of all possible 2xx schemas. This option is for 'reqwest' library only", SchemaTypeUtil.BOOLEAN_TYPE)
.defaultValue(Boolean.FALSE.toString()));
cliOptions.add(new CliOption(CodegenConstants.ENUM_NAME_SUFFIX, CodegenConstants.ENUM_NAME_SUFFIX_DESC).defaultValue(this.enumSuffix));
cliOptions.add(new CliOption(CodegenConstants.WITH_AWSV4_SIGNATURE_COMMENT, CodegenConstants.WITH_AWSV4_SIGNATURE_COMMENT_DESC, SchemaTypeUtil.BOOLEAN_TYPE)
.defaultValue(Boolean.FALSE.toString()));

supportedLibraries.put(HYPER_LIBRARY, "HTTP client: Hyper.");
supportedLibraries.put(REQWEST_LIBRARY, "HTTP client: Reqwest.");
Expand Down Expand Up @@ -249,6 +252,10 @@ public Map<String, Object> postProcessAllModels(Map<String, Object> objs) {
public void processOpts() {
super.processOpts();

if (additionalProperties.containsKey(CodegenConstants.WITH_AWSV4_SIGNATURE_COMMENT)) {
withAWSV4Signature = Boolean.parseBoolean(additionalProperties.get(CodegenConstants.WITH_AWSV4_SIGNATURE_COMMENT).toString());
}

if (additionalProperties.containsKey(CodegenConstants.ENUM_NAME_SUFFIX)) {
enumSuffix = additionalProperties.get(CodegenConstants.ENUM_NAME_SUFFIX).toString();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,11 @@ version = "^0.11"
features = ["json", "multipart"]
{{/supportAsync}}
{{/reqwest}}
{{#withAWSV4Signature}}
aws-sigv4 = "0.3.0"
http = "0.2.5"
secrecy = "0.8.0"
{{/withAWSV4Signature}}

[dev-dependencies]
{{#hyper}}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,30 @@ pub {{#supportAsync}}async {{/supportAsync}}fn {{{operationId}}}(configuration:
{{/isApiKey}}
{{/authMethods}}
{{/hasAuthMethods}}
{{#hasAuthMethods}}
{{#withAWSV4Signature}}
if let Some(ref local_var_aws_v4_key) = local_var_configuration.aws_v4_key {
let local_var_new_headers = match local_var_aws_v4_key.sign(
&local_var_uri_str,
"{{{httpMethod}}}",
{{#hasBodyParam}}
{{#bodyParams}}
&serde_json::to_string(&{{{paramName}}}).expect("param should serialize to string"),
{{/bodyParams}}
{{/hasBodyParam}}
{{^hasBodyParam}}
&"",
{{/hasBodyParam}}
) {
Ok(new_headers) => new_headers,
Err(err) => return Err(Error::AWSV4SignatureError(err)),
};
for (local_var_name, local_var_value) in local_var_new_headers.iter() {
local_var_req_builder = local_var_req_builder.header(local_var_name.as_str(), local_var_value.as_str());
}
}
{{/withAWSV4Signature}}
{{/hasAuthMethods}}
if let Some(ref local_var_user_agent) = local_var_configuration.user_agent {
local_var_req_builder = local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone());
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
use std::error;
use std::fmt;
{{#withAWSV4Signature}}
use aws_sigv4;
{{/withAWSV4Signature}}

#[derive(Debug, Clone)]
pub struct ResponseContent<T> {
Expand All @@ -14,6 +17,9 @@ pub enum Error<T> {
Serde(serde_json::Error),
Io(std::io::Error),
ResponseError(ResponseContent<T>),
{{#withAWSV4Signature}}
AWSV4SignatureError(aws_sigv4::http_request::Error),
{{/withAWSV4Signature}}
}

impl <T> fmt::Display for Error<T> {
Expand All @@ -23,6 +29,9 @@ impl <T> fmt::Display for Error<T> {
Error::Serde(e) => ("serde", e.to_string()),
Error::Io(e) => ("IO", e.to_string()),
Error::ResponseError(e) => ("response", format!("status code {}", e.status)),
{{#withAWSV4Signature}}
Error::AWSV4SignatureError(e) => ("aws v4 signature", e.to_string()),
{{/withAWSV4Signature}}
};
write!(f, "error in {}: {}", module, e)
}
Expand All @@ -35,6 +44,9 @@ impl <T: fmt::Debug> error::Error for Error<T> {
Error::Serde(e) => e,
Error::Io(e) => e,
Error::ResponseError(_) => return None,
{{#withAWSV4Signature}}
Error::AWSV4SignatureError(_) => return None,
{{/withAWSV4Signature}}
})
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,13 @@

use reqwest;

{{#withAWSV4Signature}}
use std::time::SystemTime;
use aws_sigv4::http_request::{sign, SigningSettings, SigningParams, SignableRequest};
use http;
use secrecy::{SecretString, ExposeSecret};
{{/withAWSV4Signature}}

#[derive(Debug, Clone)]
pub struct Configuration {
pub base_path: String,
Expand All @@ -11,6 +18,9 @@ pub struct Configuration {
pub oauth_access_token: Option<String>,
pub bearer_access_token: Option<String>,
pub api_key: Option<ApiKey>,
{{#withAWSV4Signature}}
pub aws_v4_key: Option<AWSv4Key>,
{{/withAWSV4Signature}}
// TODO: take an oauth2 token source, similar to the go one
}

Expand All @@ -22,6 +32,45 @@ pub struct ApiKey {
pub key: String,
}

{{#withAWSV4Signature}}
#[derive(Debug, Clone)]
pub struct AWSv4Key {
pub access_key: String,
pub secret_key: SecretString,
pub region: String,
pub service: String,
}

impl AWSv4Key {
pub fn sign(&self, uri: &str, method: &str, body: &str) -> Result<Vec::<(String, String)>, aws_sigv4::http_request::Error> {
let request = http::Request::builder()
.uri(uri)
.method(method)
.body(body).unwrap();
let signing_settings = SigningSettings::default();
let signing_params = SigningParams::builder()
.access_key(self.access_key.as_str())
.secret_key(self.secret_key.expose_secret().as_str())
.region(self.region.as_str())
.service_name(self.service.as_str())
.time(SystemTime::now())
.settings(signing_settings)
.build()
.unwrap();
let signable_request = SignableRequest::from(&request);
let (mut signing_instructions, _signature) = sign(signable_request, &signing_params)?.into_parts();
let mut additional_headers = Vec::<(String, String)>::new();
if let Some(new_headers) = signing_instructions.take_headers() {
for (name, value) in new_headers.into_iter() {
additional_headers.push((name.expect("header should have name").to_string(),
value.to_str().expect("header value should be a string").to_string()));
}
}
return Ok(additional_headers);
}
}
{{/withAWSV4Signature}}

impl Configuration {
pub fn new() -> Configuration {
Configuration::default()
Expand All @@ -38,6 +87,7 @@ impl Default for Configuration {
oauth_access_token: None,
bearer_access_token: None,
api_key: None,
{{#withAWSV4Signature}} aws_v4_key: None,{{/withAWSV4Signature}}
}
}
}

0 comments on commit 2d28dc0

Please sign in to comment.