-
Notifications
You must be signed in to change notification settings - Fork 88
Expand file tree
/
Copy pathreq-auth-aws.R
More file actions
256 lines (226 loc) · 7.59 KB
/
Copy pathreq-auth-aws.R
File metadata and controls
256 lines (226 loc) · 7.59 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
#' Sign a request with the AWS SigV4 signing protocol
#'
#' This is a custom auth protocol implemented by AWS.
#'
#' @inheritParams req_perform
#' @param aws_access_key_id,aws_secret_access_key AWS key and secret.
#' @param aws_session_token AWS session token, if required.
#' @param aws_service,aws_region The AWS service and region to use for the
#' request. If not supplied, will be automatically parsed from the URL
#' hostname.
#' @export
#' @examplesIf httr2:::has_paws_credentials()
#' creds <- paws.common::locate_credentials()
#' model_id <- "anthropic.claude-3-5-sonnet-20240620-v1:0"
#' req <- request("https://bedrock-runtime.us-east-1.amazonaws.com")
#' # https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_Converse.html
#' req <- req_url_path_append(req, "model", model_id, "converse")
#' req <- req_body_json(req, list(
#' messages = list(list(
#' role = "user",
#' content = list(list(text = "What's your name?"))
#' ))
#' ))
#' req <- req_auth_aws_v4(
#' req,
#' aws_access_key_id = creds$access_key_id,
#' aws_secret_access_key = creds$secret_access_key,
#' aws_session_token = creds$session_token
#' )
#' resp <- req_perform_connection(req)
#' str(resp_body_json(resp))
req_auth_aws_v4 <- function(
req,
aws_access_key_id,
aws_secret_access_key,
aws_session_token = NULL,
aws_service = NULL,
aws_region = NULL
) {
check_request(req)
check_string(aws_access_key_id)
check_string(aws_secret_access_key)
check_string(aws_session_token, allow_null = TRUE)
check_string(aws_service, allow_null = TRUE)
check_string(aws_region, allow_null = TRUE)
req_auth_sign(
req,
fun = auth_aws_sign,
params = list(
aws_access_key_id = aws_access_key_id,
aws_secret_access_key = aws_secret_access_key,
aws_session_token = aws_session_token,
aws_service = aws_service,
aws_region = aws_region
),
# auth_aws_sign doesn't have anything to cache, but still need to provide
# a cache argument because the req_auth_sign machinery expects it
cache = cache_noop()
)
}
auth_aws_sign <- function(
req,
aws_access_key_id,
aws_secret_access_key,
aws_session_token = NULL,
aws_service = NULL,
aws_region = NULL,
cache
) {
current_time <- Sys.time()
type <- req_get_body_type(req)
body <- switch(
type,
empty = "",
json = req_body_render(req),
form = req_body_render(req),
cli::cli_abort(
"Unsupported body type: {type}",
call = quote(req_auth_aws_v4())
)
)
body_sha256 <- openssl::sha256(body)
# We begin by adding some necessary headers that must be added before
# canoncalization even thought they aren't documented until later
req <- req_aws_headers(
req,
current_time = current_time,
aws_session_token = aws_session_token,
body_sha256 = body_sha256
)
signature <- aws_v4_signature(
method = req_get_method(req),
url = req$url,
headers = as.list(req_get_headers(req, "reveal")),
body_sha256 = body_sha256,
current_time = current_time,
aws_service = aws_service,
aws_region = aws_region,
aws_access_key_id = aws_access_key_id,
aws_secret_access_key = aws_secret_access_key
)
req_headers(req, Authorization = signature$Authorization)
}
req_aws_headers <- function(req, current_time, aws_session_token, body_sha256) {
RequestDateTime <- format(current_time, "%Y%m%dT%H%M%SZ", tz = "UTC")
req_headers(
req,
"x-amz-date" = RequestDateTime,
"x-amz-security-token" = aws_session_token,
.redact = "x-amz-security-token"
)
}
# https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_sigv-create-signed-request.html
aws_v4_signature <- function(
method,
url,
headers,
body_sha256,
aws_access_key_id,
aws_secret_access_key,
current_time = Sys.time(),
aws_service = NULL,
aws_region = NULL
) {
parsed_url <- url_parse(url)
if (is.null(aws_service) || is.null(aws_region)) {
host <- strsplit(parsed_url$hostname, ".", fixed = TRUE)[[1]]
aws_service <- aws_service %||%
strsplit(host[[1]], "-", fixed = TRUE)[[1]][[1]]
aws_region <- aws_region %||% host[[2]]
}
# S3 requires a single encoding pass; other services encode existing escapes.
if (aws_service == "s3") {
path <- parsed_url$path
} else {
path <- curl::curl_parse_url(url, decode = FALSE)$path
}
# 1. Create a canonical request
# https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_sigv-create-signed-request.html#create-canonical-request
HTTPMethod <- method
CanonicalURI <- aws_escape_path(path)
if (is.null(parsed_url$query)) {
CanonicalQueryString <- ""
} else {
sorted_query <- parsed_url$query[order(names(parsed_url$query))]
CanonicalQueryString <- url_query_build(sorted_query)
}
headers$host <- parsed_url$hostname
names(headers) <- tolower(names(headers))
headers <- headers[order(names(headers))]
headers[] <- trimws(headers)
headers[] <- gsub(" {2,}", " ", headers)
CanonicalHeaders <- paste0(names(headers), ":", headers, "\n", collapse = "")
SignedHeaders <- paste0(names(headers), collapse = ";")
CanonicalRequest <- paste_c(
c(HTTPMethod, "\n"),
c(CanonicalURI, "\n"),
c(CanonicalQueryString, "\n"),
c(CanonicalHeaders, "\n"),
c(SignedHeaders, "\n"),
body_sha256
)
# 2. Create the hash of the canonical request
# https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_sigv-create-signed-request.html
HashedCanonicalRequest <- openssl::sha256(CanonicalRequest)
# 3. Create the string to sign
# https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_sigv-create-signed-request.html#create-string-to-sign
Algorithm <- "AWS4-HMAC-SHA256"
RequestDateTime <- format(current_time, "%Y%m%dT%H%M%SZ", tz = "UTC")
Date <- format(current_time, "%Y%m%d", tz = "UTC")
CredentialScope <- file.path(Date, aws_region, aws_service, "aws4_request")
string_to_sign <- paste_c(
c(Algorithm, "\n"),
c(RequestDateTime, "\n"),
c(CredentialScope, "\n"),
HashedCanonicalRequest
)
# 4. Derive a signing key
# https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_sigv-create-signed-request.html#derive-signing-key
DateKey <- hmac_sha256(paste0("AWS4", aws_secret_access_key), Date)
DateRegionKey <- hmac_sha256(DateKey, aws_region)
DateRegionServiceKey <- hmac_sha256(DateRegionKey, aws_service)
SigningKey <- hmac_sha256(DateRegionServiceKey, "aws4_request")
# 5. Calculate signature
# https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_sigv-create-signed-request.html#calculate-signature
signature <- hmac_sha256(SigningKey, string_to_sign)
signature <- paste0(as.character(signature), collapse = "")
# 6. Add the signature to the request
# https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_sigv-create-signed-request.html#calculate-signature
credential <- file.path(aws_access_key_id, CredentialScope)
Authorization <- paste_c(
c(Algorithm, " "),
c("Credential=", credential, ","),
c("SignedHeaders=", SignedHeaders, ","),
c("Signature=", signature)
)
list(
CanonicalRequest = CanonicalRequest,
string_to_sign = string_to_sign,
SigningKey = SigningKey,
Authorization = Authorization
)
}
aws_escape_path <- function(path) {
path <- path %||% "/"
segments <- strsplit(path, "/", fixed = TRUE)[[1]]
out <- paste(curl::curl_escape(segments), collapse = "/")
if (grepl("/$", path)) {
out <- paste0(out, "/")
}
out
}
hmac_sha256 <- function(key, value) {
openssl::sha256(charToRaw(value), key)
}
has_paws_credentials <- function() {
tryCatch(
{
paws.common::locate_credentials()
TRUE
},
error = function(e) {
FALSE
}
)
}