forked from aws-amplify/aws-sdk-ios
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAWSS3PreSignedURL.m
320 lines (262 loc) · 14.3 KB
/
AWSS3PreSignedURL.m
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
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
/**
Copyright 2010-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License").
You may not use this file except in compliance with the License.
A copy of the License is located at
http://aws.amazon.com/apache2.0
or in the "license" file accompanying this file. This file is distributed
on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
express or implied. See the License for the specific language governing
permissions and limitations under the License.
*/
#import "AWSS3PreSignedURL.h"
#import "AWSCategory.h"
#import "AWSSignature.h"
#import "AWSLogging.h"
#import <Bolts/Bolts.h>
#import "AWSSynchronizedMutableDictionary.h"
#import <CommonCrypto/CommonCrypto.h>
NSString *const AWSS3PresignedURLErrorDomain = @"com.amazonaws.AWSS3PresignedURLErrorDomain";
@interface AWSS3PreSignedURLBuilder()
@property (nonatomic, strong) AWSServiceConfiguration *configuration;
@end
@interface AWSServiceConfiguration()
@property (nonatomic, strong) AWSEndpoint *endpoint;
@end
@implementation AWSS3PreSignedURLBuilder
static AWSSynchronizedMutableDictionary *_serviceClients = nil;
+ (instancetype)defaultS3PreSignedURLBuilder {
if (![AWSServiceManager defaultServiceManager].defaultServiceConfiguration) {
return nil;
}
static AWSS3PreSignedURLBuilder *_defaultS3PreSignedURLBuilder = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
_defaultS3PreSignedURLBuilder = [[AWSS3PreSignedURLBuilder alloc] initWithConfiguration:[AWSServiceManager defaultServiceManager].defaultServiceConfiguration];
#pragma clang diagnostic pop
});
return _defaultS3PreSignedURLBuilder;
}
+ (void)registerS3PreSignedURLBuilderWithConfiguration:(AWSServiceConfiguration *)configuration forKey:(NSString *)key {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_serviceClients = [AWSSynchronizedMutableDictionary new];
});
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
[_serviceClients setObject:[[AWSS3PreSignedURLBuilder alloc] initWithConfiguration:configuration]
forKey:key];
#pragma clang diagnostic pop
}
+ (instancetype)S3PreSignedURLBuilderForKey:(NSString *)key {
return [_serviceClients objectForKey:key];
}
+ (void)removeS3PreSignedURLBuilderForKey:(NSString *)key {
[_serviceClients removeObjectForKey:key];
}
- (instancetype)init {
@throw [NSException exceptionWithName:NSInternalInconsistencyException
reason:@"`- init` is not a valid initializer. Use `+ defaultS3PreSignedURLBuilder` or `+ S3PreSignedURLBuilderForKey:` instead."
userInfo:nil];
return nil;
}
- (instancetype)initWithConfiguration:(AWSServiceConfiguration *)configuration {
if (self = [super init]) {
_configuration = configuration;
_configuration.endpoint = [[AWSEndpoint alloc] initWithRegion:_configuration.regionType
service:AWSServiceS3
useUnsafeURL:NO];
}
return self;
}
- (BFTask *)getPreSignedURL:(AWSS3GetPreSignedURLRequest *)getPreSignedURLRequest {
return [[BFTask taskWithResult:nil] continueWithBlock:^id(BFTask *task) {
//retrive parameters from request;
NSString *bucketName = getPreSignedURLRequest.bucket;
NSString *keyName = getPreSignedURLRequest.key;
AWSHTTPMethod httpMethod = getPreSignedURLRequest.HTTPMethod;
AWSServiceConfiguration *configuration = self.configuration;
id<AWSCredentialsProvider>credentialProvider = configuration.credentialsProvider;
AWSEndpoint *endpoint = self.configuration.endpoint;
NSDate *expires = getPreSignedURLRequest.expires;
NSString *versionId = getPreSignedURLRequest.versionId;
//validate endpoint
if (!endpoint) {
return [BFTask taskWithError:[NSError errorWithDomain:AWSS3PresignedURLErrorDomain
code:AWSS3PresignedURLErrorEndpointIsNil
userInfo:@{NSLocalizedDescriptionKey: @"endpoint in configuration can not be nil"}]
];
} else if (endpoint.serviceType != AWSServiceS3) {
return [BFTask taskWithError:[NSError errorWithDomain:AWSS3PresignedURLErrorDomain
code:AWSS3PresignedURLErrorInvalidServiceType
userInfo:@{NSLocalizedDescriptionKey: @"Invalid serviceType: serviceType in endpoint must be AWSServiceS3"}]
];
}
//validate credentialProvider
if (!credentialProvider) {
return [BFTask taskWithError:[NSError errorWithDomain:AWSS3PresignedURLErrorDomain
code:AWSS3PreSignedURLErrorCredentialProviderIsNil
userInfo:@{NSLocalizedDescriptionKey: @"credentialProvider in configuration can not be nil"}]
];
}
//validate expiration date if using temporary token and refresh it if condition met
if ([credentialProvider respondsToSelector:@selector(expiration)]) {
if ([credentialProvider respondsToSelector:@selector(refresh)]) {
if ([credentialProvider.expiration timeIntervalSinceNow] < getPreSignedURLRequest.minimumCredentialsExpirationInterval) {
//need to refresh temp credential
[[credentialProvider refresh] waitUntilFinished];
}
}
}
//validate accessKey
if ([credentialProvider respondsToSelector:@selector(accessKey)] && [credentialProvider.accessKey length] > 0) {
//continue to process.
} else {
return [BFTask taskWithError:[NSError errorWithDomain:AWSS3PresignedURLErrorDomain
code:AWSS3PresignedURLErrorAccessKeyIsNil
userInfo:@{NSLocalizedDescriptionKey: @"accessKey in credentialProvider can not be nil"}]
];
}
//validate secretKey
if ([credentialProvider respondsToSelector:@selector(secretKey)] && [credentialProvider.secretKey length] > 0) {
//continue to process.
} else {
return [BFTask taskWithError:[NSError errorWithDomain:AWSS3PresignedURLErrorDomain
code:AWSS3PresignedURLErrorSecretKeyIsNil
userInfo:@{NSLocalizedDescriptionKey: @"secretKey in credentialProvider can not be nil"}]
];
}
//validate bucketName
if (!bucketName || [bucketName length] < 1) {
return [BFTask taskWithError:[NSError errorWithDomain:AWSS3PresignedURLErrorDomain
code:AWSS3PresignedURLErrorBucketNameIsNil
userInfo:@{NSLocalizedDescriptionKey: @"S3 bucket can not be nil or empty"}]
];
}
//validate keyName
if (!keyName || [keyName length] < 1) {
return [BFTask taskWithError:[NSError errorWithDomain:AWSS3PresignedURLErrorDomain
code:AWSS3PresignedURLErrorKeyNameIsNil
userInfo:@{NSLocalizedDescriptionKey: @"S3 key can not be nil or empty"}]
];
}
//validate expires Date
if (!expires) {
return [BFTask taskWithError:[NSError errorWithDomain:AWSS3PresignedURLErrorDomain
code:AWSS3PresignedURLErrorInvalidExpiresDate
userInfo:@{NSLocalizedDescriptionKey: @"expires can not be nil"}]
];
}else if ([expires timeIntervalSinceNow] < 0.0) {
return [BFTask taskWithError:[NSError errorWithDomain:AWSS3PresignedURLErrorDomain
code:AWSS3PresignedURLErrorInvalidExpiresDate
userInfo:@{NSLocalizedDescriptionKey: @"expires can not be in past"}]
];
}
//validate httpMethod
switch (httpMethod) {
case AWSHTTPMethodGET:
case AWSHTTPMethodPUT:
case AWSHTTPMethodHEAD:
case AWSHTTPMethodDELETE:
break;
default:
return [BFTask taskWithError:[NSError errorWithDomain:AWSS3PresignedURLErrorDomain
code:AWSS3PresignedURLErrorUnsupportedHTTPVerbs
userInfo:@{NSLocalizedDescriptionKey: @"unsupported HTTP Method, currently only support AWSHTTPMethodGET, AWSHTTPMethodPUT, AWSHTTPMethodHEAD, AWSHTTPMethodDELETE"}]
];
break;
}
//generate baseURL String (use virtualHostStyle if possible)
NSString *keyPath = nil;
if (bucketName == nil || [self aws_isVirtualHostedStyleCompliant:bucketName]) {
keyPath = (keyName == nil ? @"" : [NSString stringWithFormat:@"%@", [keyName aws_stringWithURLEncodingPath]]);
} else {
keyPath = (keyName == nil ? [NSString stringWithFormat:@"%@", bucketName] : [NSString stringWithFormat:@"%@/%@", bucketName, [keyName aws_stringWithURLEncodingPath]]);
}
//generate correct hostName (use virtualHostStyle if possible)
NSString *host = nil;
if (bucketName && [self aws_isVirtualHostedStyleCompliant:bucketName]) {
host = [NSString stringWithFormat:@"%@.%@", bucketName, endpoint.hostName];
} else {
host = endpoint.hostName;
}
//generate queryString
NSMutableString *queryString = [NSMutableString stringWithCapacity:512];
//security Token
if ([credentialProvider respondsToSelector:@selector(sessionKey)] && [credentialProvider.sessionKey length] > 0) {
[queryString appendFormat:@"%@=%@&", @"x-amz-security-token", [credentialProvider.sessionKey aws_stringWithURLEncoding]];
}
[queryString appendFormat:@"%@=%@", @"AWSAccessKeyId", [credentialProvider.accessKey aws_stringWithURLEncoding]];
// Add expire time
int32_t expireTimestamp = (int32_t)[expires timeIntervalSince1970];
[queryString appendFormat:@"&%@=%d", @"Expires", expireTimestamp];
// Version
if (versionId) {
[queryString appendFormat:@"&%@=%@", @"versionId", [versionId aws_stringWithURLEncoding]];
}
// ============= generate the signature string ===================
/* String to Sign Format:
*
* HTTP-VERB + "\n" +
* Content-MD5 + "\n" + (Optional)
* Content-Type + "\n" + (Optional)
* Expires + "\n" +
* CanonicalizedAmzHeaders +
* CanonicalizedResource;
*/
//Content-Type or Content-MD5 are optional for PUT requests and meaningless for GET requests), substitute the empty string ("") for that position.
NSString *contentMd5 = @"";
NSString *contentType = @"";
if (httpMethod == AWSHTTPMethodPUT && getPreSignedURLRequest.contentType) {
contentType = getPreSignedURLRequest.contentType;
}
NSMutableString *canonicalizedAmzHeaders = [NSMutableString stringWithFormat:@""];
if ([credentialProvider respondsToSelector:@selector(sessionKey)] && [credentialProvider.sessionKey length] > 0) {
[canonicalizedAmzHeaders appendFormat:@"%@:%@\n",@"x-amz-security-token",credentialProvider.sessionKey];
}
NSString *canonicalizedResource = @"";
if (nil == keyName || [keyName length] < 1) {
if (nil == bucketName || [bucketName length] < 1) {
canonicalizedResource = @"/";
}
else {
if ( [self aws_isVirtualHostedStyleCompliant:bucketName]) {
canonicalizedResource = [NSString stringWithFormat:@"/%@/", bucketName];
}else {
canonicalizedResource = [NSString stringWithFormat:@"/%@", bucketName];
}
}
}
else {
canonicalizedResource = [NSString stringWithFormat:@"/%@/%@", bucketName, [keyName aws_stringWithURLEncodingPath]];
}
NSString *stringToSign = [NSString stringWithFormat:@"%@\n%@\n%@\n%d\n%@%@",
[NSString aws_stringWithHTTPMethod:httpMethod],
contentMd5,
contentType,
expireTimestamp,
canonicalizedAmzHeaders,
canonicalizedResource];
/* Signature Format:
* URL-Encode( Base64( HMAC-SHA1( YourSecretAccessKeyID, UTF-8-Encoding-Of( StringToSign ) ) ) );
*/
NSString *signature = [[AWSSignatureSignerUtility HMACSign:[stringToSign dataUsingEncoding:NSUTF8StringEncoding]
withKey:credentialProvider.secretKey
usingAlgorithm:kCCHmacAlgSHA1] aws_stringWithURLEncoding];
[queryString appendFormat:@"&%@=%@",@"Signature",signature];
// ============= generate the signature string (END)===================
NSURL *result = [NSURL URLWithString:[NSString stringWithFormat:@"%@://%@/%@?%@", endpoint.useUnsafeURL?@"http":@"https", host, keyPath, queryString]];
return [BFTask taskWithResult:result];
}];
}
@end
@implementation AWSS3GetPreSignedURLRequest
- (instancetype)init {
if ( self = [super init] ) {
self.minimumCredentialsExpirationInterval = 50*60;
}
return self;
}
@end