| 1 | package AWS::Signature::V4::Credentials; | ||
| 2 | use v5.24; | ||
| 3 | use Moo; | ||
| 4 | use AWS::Signature::V4::Error qw< fail shown >; | ||
| 5 | use Digest::SHA qw< hmac_sha256 hmac_sha256_hex >; | ||
| 6 | use experimental qw< signatures >; | ||
| 7 | use namespace::clean; | ||
| 8 | |||
| 9 | # The credentials-based variant (AWS4-HMAC-SHA256). The options are the ones | ||
| 10 | # of the "credentials" option of AWS::Signature::V4. | ||
| 11 | has [qw< access_key_id secret_access_key session_token >] => (is => 'ro'); | ||
| 12 | |||
| 13 | sub BUILD ($self, $args) { | ||
| 14 | if (my ($name) = sort(grep { !m{\A(?:access_key_id|secret_access_key|session_token)\z} } keys $args->%*)) { | ||
| 15 | fail 400, 'unknown option "' . shown($name) . '" in credentials'; | ||
| 16 | } | ||
| 17 | for my $name (qw< access_key_id secret_access_key >) { | ||
| 18 | my $value = $self->$name; # empty is like missing, AWS would refuse it | ||
| 19 | defined $value && length $value or fail 400, "missing credentials/$name"; | ||
| 20 | } | ||
| 21 | return; | ||
| 22 | } | ||
| 23 | |||
| 24 | # ---- what AWS::Signature::V4 wants from a variant -------------------------- | ||
| 25 | |||
| 26 | sub algorithm ($self) { 'AWS4-HMAC-SHA256' } | ||
| 27 | |||
| 28 | # identifies who signs, in the Credential part of the authorization | ||
| 29 | sub credential_id ($self) { $self->access_key_id } | ||
| 30 | |||
| 31 | # the key derived from the secret, for a scope like "20150830/us-east-1/iam/aws4_request" | ||
| 32 | sub signing_key ($self, $scope) { | ||
| 33 | my ($date, $region, $service, $terminator) = split m{/}, $scope, 4; | ||
| 34 | my $key = 'AWS4' . $self->secret_access_key; | ||
| 35 | $key = hmac_sha256($_, $key) for $date, $region, $service, $terminator; | ||
| 36 | return $key; | ||
| 37 | } | ||
| 38 | |||
| 39 | # hex signature of the string to sign | ||
| 40 | sub signature ($self, $scope, $string_to_sign) { | ||
| 41 | return hmac_sha256_hex($string_to_sign, $self->signing_key($scope)); | ||
| 42 | } | ||
| 43 | |||
| 44 | # what goes with the request besides the signature, as (name => value) pairs | ||
| 45 | sub extra_fields ($self) { | ||
| 46 | my $token = $self->session_token; # empty, e.g. from an empty variable: none | ||
| 47 | return defined $token && length $token ? ('X-Amz-Security-Token' => $token) : (); | ||
| 48 | } | ||
| 49 | |||
| 50 | # signed chunks need the derived key | ||
| 51 | sub can_sign_chunks ($self) { 1 } | ||
| 52 | |||
| 53 | 1; |