-
Notifications
You must be signed in to change notification settings - Fork 24
/
client.dart
279 lines (241 loc) · 10.1 KB
/
client.dart
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
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:meta/meta.dart';
import 'package:crypto/crypto.dart';
import 'package:http_client/console.dart' as http;
import 'package:xml/xml.dart' as xml;
import 'bucket.dart';
const defaultChunkSize = 65536;
class ClientException implements Exception {
final int statusCode;
final String reasonPhrase;
final Map<String, String> responseHeaders;
final String responseBody;
const ClientException(this.statusCode, this.reasonPhrase,
this.responseHeaders, this.responseBody);
String toString() {
return "DOException { statusCode: ${statusCode}, reasonPhrase: \"${reasonPhrase}\", responseBody: \"${responseBody}\" }";
}
}
class Client {
final String region;
final String accessKey;
final String secretKey;
final String sessionToken;
final String service;
@protected
final http.Client httpClient;
Client(
{@required this.region,
@required this.accessKey,
@required this.secretKey,
@required this.service,
this.sessionToken,
http.Client httpClient})
: this.httpClient =
httpClient == null ? http.ConsoleClient() : httpClient {
assert(this.region != null);
assert(this.accessKey != null);
assert(this.secretKey != null);
}
@protected
Future<xml.XmlDocument> getUri(Uri uri) async {
http.Request request = http.Request('GET', uri, headers: http.Headers());
signRequest(request, contentSha256: await sha256.convert(''.codeUnits));
http.Response response = await httpClient.send(request);
BytesBuilder builder = BytesBuilder(copy: false);
await response.body.forEach(builder.add);
String body = utf8.decode(builder.toBytes());
if (response.statusCode != 200) {
throw ClientException(response.statusCode, response.reasonPhrase,
response.headers.toSimpleMap(), body);
}
xml.XmlDocument doc = xml.XmlDocument.parse(body);
return doc;
}
String _uriEncode(String str) {
return Uri.encodeQueryComponent(str).replaceAll('+', '%20');
}
String _trimAll(String str) {
String res = str.trim();
int len;
do {
len = res.length;
res = res.replaceAll(' ', ' ');
} while (res.length != len);
return res;
}
@protected
String signRequest(http.Request request,
{Digest contentSha256, int expires = 86400}) {
// Build canonical request
String httpMethod = request.method;
String canonicalURI = request.uri.path;
String host = request.uri.host;
// String service = 's3';
DateTime date = DateTime.now().toUtc();
String dateIso8601 = date.toIso8601String();
dateIso8601 = dateIso8601
.substring(0, dateIso8601.indexOf('.'))
.replaceAll(':', '')
.replaceAll('-', '') +
'Z';
String dateYYYYMMDD = date.year.toString().padLeft(4, '0') +
date.month.toString().padLeft(2, '0') +
date.day.toString().padLeft(2, '0');
/*dateIso8601 = "20130524T000000Z";
dateYYYYMMDD = "20130524";
hashedPayload = null;*/
String hashedPayloadStr =
contentSha256 == null ? 'UNSIGNED-PAYLOAD' : '$contentSha256';
String credential =
'${accessKey}/${dateYYYYMMDD}/${region}/${service}/aws4_request';
// Build canonical headers string
Map<String, List<String>> headers = Map<String, List<String>>();
request.headers.add('x-amz-date', dateIso8601); // Set date in header
if (contentSha256 != null) {
request.headers.add('x-amz-content-sha256',
hashedPayloadStr); // Set payload hash in header
}
request.headers.keys.forEach(
(String name) => (headers[name.toLowerCase()] = request.headers[name]));
headers['host'] = [host]; // Host is a builtin header
List<String> headerNames = headers.keys.toList()..sort();
String canonicalHeaders = headerNames
.map((s) =>
(headers[s].map((v) => ('${s}:${_trimAll(v)}')).join('\n') + '\n'))
.join();
String signedHeaders = headerNames.join(';');
// Build canonical query string
Map<String, String> queryParameters = Map<String, String>()
..addAll(request.uri.queryParameters);
List<String> queryKeys = queryParameters.keys.toList()..sort();
String canonicalQueryString = queryKeys
.map((s) => '${_uriEncode(s)}=${_uriEncode(queryParameters[s])}')
.join('&');
// Sign headers
String canonicalRequest =
'${httpMethod}\n${canonicalURI}\n${canonicalQueryString}\n${canonicalHeaders}\n${signedHeaders}\n$hashedPayloadStr';
// print('\n>>>>>> canonical request \n' + canonicalRequest + '\n<<<<<<\n');
Digest canonicalRequestHash = sha256.convert(utf8.encode(
canonicalRequest)); //_hmacSha256.convert(utf8.encode(canonicalRequest));
String stringToSign =
'AWS4-HMAC-SHA256\n${dateIso8601}\n${dateYYYYMMDD}/${region}/${service}/aws4_request\n$canonicalRequestHash';
// print('\n>>>>>> string to sign \n' + stringToSign + '\n<<<<<<\n');
Digest dateKey = Hmac(sha256, utf8.encode("AWS4${secretKey}"))
.convert(utf8.encode(dateYYYYMMDD));
Digest dateRegionKey =
Hmac(sha256, dateKey.bytes).convert(utf8.encode(region));
Digest dateRegionServiceKey =
Hmac(sha256, dateRegionKey.bytes).convert(utf8.encode(service));
Digest signingKey = Hmac(sha256, dateRegionServiceKey.bytes)
.convert(utf8.encode("aws4_request"));
Digest signature =
Hmac(sha256, signingKey.bytes).convert(utf8.encode(stringToSign));
// Set signature in header
request.headers.add('Authorization',
'AWS4-HMAC-SHA256 Credential=${credential}, SignedHeaders=${signedHeaders}, Signature=$signature');
return null;
}
@protected
Map<String, String> composeChunkRequestHeaders(
{Uri uri,
String dateIso8601,
String dateYYYYMMDD,
String contentType,
int contentLength,
int chunkContentLengthWithMeta,
Permissions permissions,
Map<String, String> meta}) {
// Build canonical request
String httpMethod = 'PUT';
String canonicalURI = uri.path;
String host = uri.host;
String credential =
'${accessKey}/${dateYYYYMMDD}/${region}/${service}/aws4_request';
Map<String, String> resultHeaders = {
'x-amz-date': dateIso8601, // Set date in header
'x-amz-content-sha256':
'STREAMING-AWS4-HMAC-SHA256-PAYLOAD', // Set payload hash in header
'Content-Encoding': 'aws-chunked',
'Content-Type': contentType,
// 'Expect': '100-continue',
// 'x-amz-storage-class': 'REDUCED_REDUNDANCY',
'Content-Length': chunkContentLengthWithMeta.toString(),
'x-amz-decoded-content-length': contentLength.toString()
};
if (meta != null) {
for (MapEntry<String, String> me in meta.entries) {
resultHeaders["x-amz-meta-${me.key}"] = me.value;
}
}
if (permissions == Permissions.public) {
resultHeaders['x-amz-acl'] = 'public-read';
}
// Build canonical headers string
Map<String, List<String>> headers = Map<String, List<String>>();
resultHeaders.keys.forEach((String name) => (headers[name.toLowerCase()] =
resultHeaders[name] is List
? resultHeaders[name]
: [resultHeaders[name]]));
headers['host'] = [host]; // Host is a builtin header
List<String> headerNames = headers.keys.toList()..sort();
String canonicalHeaders = headerNames
.map((s) =>
(headers[s].map((v) => ('${s}:${_trimAll(v)}')).join('\n') + '\n'))
.join();
String signedHeaders = headerNames.join(';');
// Build canonical query string
Map<String, String> queryParameters = Map<String, String>()
..addAll(uri.queryParameters);
List<String> queryKeys = queryParameters.keys.toList()..sort();
String canonicalQueryString = queryKeys
.map((s) => '${_uriEncode(s)}=${_uriEncode(queryParameters[s])}')
.join('&');
// Sign headers
String canonicalRequest =
'${httpMethod}\n${canonicalURI}\n${canonicalQueryString}\n${canonicalHeaders}\n${signedHeaders}\nSTREAMING-AWS4-HMAC-SHA256-PAYLOAD';
// print('\n>>>>>> canonical request \n' + canonicalRequest + '\n<<<<<<\n');
Digest canonicalRequestHash = sha256.convert(utf8.encode(
canonicalRequest)); //_hmacSha256.convert(utf8.encode(canonicalRequest));
String stringToSign =
'AWS4-HMAC-SHA256\n${dateIso8601}\n${dateYYYYMMDD}/${region}/${service}/aws4_request\n$canonicalRequestHash';
// print('\n>>>>>> string to sign \n' + stringToSign + '\n<<<<<<\n');
Digest dateKey = Hmac(sha256, utf8.encode("AWS4${secretKey}"))
.convert(utf8.encode(dateYYYYMMDD));
Digest dateRegionKey =
Hmac(sha256, dateKey.bytes).convert(utf8.encode(region));
Digest dateRegionServiceKey =
Hmac(sha256, dateRegionKey.bytes).convert(utf8.encode(service));
Digest signingKey = Hmac(sha256, dateRegionServiceKey.bytes)
.convert(utf8.encode("aws4_request"));
Digest signature =
Hmac(sha256, signingKey.bytes).convert(utf8.encode(stringToSign));
// Set signature in header
resultHeaders['Authorization'] =
'AWS4-HMAC-SHA256 Credential=${credential}, SignedHeaders=${signedHeaders}, Signature=$signature';
return resultHeaders;
}
String calculateChunkedSignature(
List<int> data,
String prevSignature, {
String dateIso8601,
String dateYYYYMMDD,
}) {
String stringToSign =
'AWS4-HMAC-SHA256-PAYLOAD\n${dateIso8601}\n${dateYYYYMMDD}/${region}/${service}/aws4_request\n$prevSignature\n${sha256.convert([])}\n${sha256.convert(data)}';
// print('\n>>>>>> chunk string to sign \n' + stringToSign + '\n<<<<<<\n');
Digest dateKey = Hmac(sha256, utf8.encode("AWS4${secretKey}"))
.convert(utf8.encode(dateYYYYMMDD));
Digest dateRegionKey =
Hmac(sha256, dateKey.bytes).convert(utf8.encode(region));
Digest dateRegionServiceKey =
Hmac(sha256, dateRegionKey.bytes).convert(utf8.encode(service));
Digest signingKey = Hmac(sha256, dateRegionServiceKey.bytes)
.convert(utf8.encode("aws4_request"));
Digest signature =
Hmac(sha256, signingKey.bytes).convert(utf8.encode(stringToSign));
return '$signature';
}
}