-
Notifications
You must be signed in to change notification settings - Fork 21
Expand file tree
/
Copy pathLifecycleConfiguration.ts
More file actions
1436 lines (1380 loc) · 51.7 KB
/
LifecycleConfiguration.ts
File metadata and controls
1436 lines (1380 loc) · 51.7 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
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
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import assert from 'assert';
const { v4: uuid } = require('uuid');
import errors, { errorInstances } from '../errors';
import type { ArsenalError } from '../errors';
import LifecycleRule from './LifecycleRule';
import escapeForXml from '../s3middleware/escapeForXml';
import { Status } from './LifecycleRule';
const MAX_DAYS = 2147483647; // Max 32-bit signed binary integer.
// Possible lifecycle actions/rules that can be used esp. in supportedLifecycleRules
export const ValidLifecycleRules = [
'Expiration',
'NoncurrentVersionExpiration',
'AbortIncompleteMultipartUpload',
'Transition',
'NoncurrentVersionTransition',
] as const;
type LifecycleAction = typeof ValidLifecycleRules[number];
/**
* Format of xml request:
<LifecycleConfiguration>
<Rule>
<ID>id1</ID>
<Filter>
<Prefix>logs/</Prefix>
</Filter>
<Status>Enabled</Status>
<Expiration>
<Days>365</Days>
</Expiration>
</Rule>
<Rule>
<ID>DeleteAfterBecomingNonCurrent</ID>
<Filter>
<And>
<Prefix>logs/</Prefix>
<Tag>
<Key>key1</Key>
<Value>value1</Value>
</Tag>
</And>
</Filter>
<Status>Enabled</Status>
<NoncurrentVersionExpiration>
<NoncurrentDays>1</NoncurrentDays>
</NoncurrentVersionExpiration>
<AbortIncompleteMultipartUploads>
<DaysAfterInitiation>1</DaysAfterInitiation>
</AbortIncompleteMultipartUploads>
</Rule>
</LifecycleConfiguration>
*/
/**
* Format of config:
config = {
rules = [
{
ruleID: <value>,
ruleStatus: <value>,
filter: {
rulePrefix: <value>,
tags: [
{
key: <value>,
val: <value>
},
{
key: <value>,
val: <value>
}
]
},
actions: [
{
actionName: <value>,
days: <value>,
date: <value>,
deleteMarker: <value>
},
{
actionName: <value>,
days: <value>,
date: <value>,
deleteMarker: <value>,
},
]
}
]
};
*/
export type LifecycleConfigurationMetadata = {
rules: Rule[],
};
// This matches the XML structure of the rule, as generated by xml2js: so every field is actually
// an array, even if it only has one element.
export type LifecycleXMLRule = {
Prefix: string[];
Status: Status[];
ID?: string[];
Filter?: any[];
Transition?: any[];
NoncurrentVersionTransition?: any[];
Expiration?: any[];
NoncurrentVersionExpiration?: any[];
AbortIncompleteMultipartUpload?: any[];
};
export default class LifecycleConfiguration {
_parsedXML: any;
_ruleIDs: string[];
_tagKeys: string[];
_storageClasses: string[];
_supportedLifecycleRules: string[];
_config: {
error?: ArsenalError;
rules?: Rule[];
};
/**
* Create a Lifecycle Configuration instance
* @param xml - the parsed xml
* @param config - the CloudServer config
* @return - LifecycleConfiguration instance
*/
constructor(
xml: any,
config: {
replicationEndpoints: { site: string }[],
locationConstraints?: Record<string, { isCRR: boolean }>,
supportedLifecycleRules: string[],
}
) {
this._parsedXML = xml;
this._storageClasses = this._buildStorageClasses(config);
this._supportedLifecycleRules = config.supportedLifecycleRules;
this._ruleIDs = [];
this._tagKeys = [];
this._config = {};
}
/**
* Build the list of available storage classes for lifecycle transitions.
* This filters out any locations that are designated for cross-region
* replication (CRR), as transitions to these are not allowed.
* @param config - The CloudServer config
* @returns An array of valid storage class names.
*/
_buildStorageClasses(config: {
replicationEndpoints: { site: string }[],
locationConstraints?: Record<string, { isCRR: boolean }>,
}) {
return config.replicationEndpoints
.map(endpoint => endpoint.site)
.filter(site => !config.locationConstraints?.[site]?.isCRR);
}
/**
* Get the lifecycle configuration
* @return - the lifecycle configuration
*/
getLifecycleConfiguration() {
const rules = this._buildRulesArray();
if (rules.error) {
this._config.error = rules.error;
}
return this._config;
}
/**
* Build the this._config.rules array
* @return - contains error if any rule returned an error
* or parsing failed
*/
_buildRulesArray() {
this._config.rules = [];
if (!this._parsedXML || this._parsedXML === '') {
const msg = 'request xml is undefined or empty';
const error = errorInstances.MalformedXML.customizeDescription(msg);
return { error };
}
if (!this._parsedXML.LifecycleConfiguration &&
this._parsedXML.LifecycleConfiguration !== '') {
const msg = 'request xml does not include LifecycleConfiguration';
const error = errorInstances.MalformedXML.customizeDescription(msg);
return { error };
}
const lifecycleConf = this._parsedXML.LifecycleConfiguration;
const rulesArray: LifecycleXMLRule[] = lifecycleConf.Rule;
if (!rulesArray || !Array.isArray(rulesArray) || rulesArray.length === 0) {
const msg = 'missing required key \'Rules\' in LifecycleConfiguration';
const error = errorInstances.MissingRequiredParameter.customizeDescription(msg);
return { error };
}
if (rulesArray.length > 1000) {
const msg = 'request xml includes over max limit of 1000 rules';
const error = errorInstances.MalformedXML.customizeDescription(msg);
return { error };
}
const rules: any = {};
for (let i = 0; i < rulesArray.length; i++) {
const rule = this._parseRule(rulesArray[i]);
if (rule.error) {
rules.error = rule.error;
break;
} else {
this._config.rules.push(rule);
}
}
return rules;
}
/**
* Check that the prefix is valid
* @param prefix - The prefix to check
* @return - The error or null
*/
_checkPrefix(prefix: string) {
if (prefix.length > 1024) {
const msg = 'The maximum size of a prefix is 1024';
return errorInstances.InvalidRequest.customizeDescription(msg);
}
return null;
}
/**
* Parses the prefix of the config
* @param prefix - The prefix to parse
* @return - Contains error if parsing returned an error, otherwise
* it contains the parsed rule object
*/
_parsePrefix(prefix: string) {
const error = this._checkPrefix(prefix);
if (error) {
return { error };
}
return {
propName: 'prefix',
prefix,
};
}
/**
* Check that each xml rule is valid
* @param rule - a rule object from Rule array from this._parsedXml
* @return - contains error if any component returned an error
* or parsing failed, else contains parsed rule object
*
* Format of ruleObj:
* ruleObj = {
* ruleID: <value>,
* ruleStatus: <value>,
* filter: {
* rulePrefix: <value>,
* tags: [
* {
* key: <value>,
* val: <value>,
* }
* ]
* }
* actions: [
* {
* actionName: <value>,
* day: <value>,
* date: <value>,
* deleteMarker: <value>
* },
* ]
* }
*/
_parseRule(rule: LifecycleXMLRule) {
// Either Prefix or Filter must be included, but can be empty string
if ((!rule.Filter && rule.Filter !== '') && (!rule.Prefix && rule.Prefix !== '')) {
const msg = 'Rule xml does not include valid Filter or Prefix';
const error = errorInstances.MalformedXML.customizeDescription(msg);
return { error };
}
if (rule.Filter && rule.Prefix) {
const msg = 'Rule xml should not include both Filter and Prefix';
const error = errorInstances.MalformedXML.customizeDescription(msg);
return { error };
}
if (!rule.Status) {
const msg = 'Rule xml does not include Status';
const error = errorInstances.MissingRequiredParameter.customizeDescription(msg);
return { error };
}
const id = this._parseID(rule.ID!);
const status = this._parseStatus(rule.Status[0]);
const actions = this._parseAction(rule);
const rulePropArray: any[] = [id, status, actions];
if (rule.Prefix) {
// Backward compatibility with deprecated top-level prefix.
const prefix = this._parsePrefix(rule.Prefix[0]);
rulePropArray.push(prefix);
} else if (rule.Filter) {
const filter = this._parseFilter(rule.Filter[0]);
rulePropArray.push(filter);
}
const ruleObj: any = {};
for (let i = 0; i < rulePropArray.length; i++) {
const prop = rulePropArray[i];
if (prop.error) {
ruleObj.error = prop.error;
break;
} else {
const propName = prop.propName;
delete prop.propName;
if (prop[propName] !== undefined) {
ruleObj[propName] = prop[propName];
} else {
ruleObj[propName] = prop;
}
}
}
return ruleObj;
}
/**
* Check that filter component of rule is valid
* @param filter - filter object from a rule object
* @return - contains error if parsing failed, else contains
* parsed prefix and tag array
*
* Format of filterObj:
* filterObj = {
* error: <error>,
* propName: 'filter',
* rulePrefix: <value>,
* tags: [
* {
* key: <value>,
* val: <value>
* },
* {
* key: <value>,
* value: <value>
* }
* ]
* }
*/
_parseFilter(filter: any) {
// @ts-ignore
const filterObj: {
error?: ArsenalError;
propName: 'filter';
rulePrefix: string;
tags: { key: string; val: string }[]
} = {
propName: 'filter',
};
if (Array.isArray(filter)) {
// if Prefix was included, not Filter, filter will be Prefix array
// if more than one Prefix is included, we ignore all but the last
filterObj.rulePrefix = filter[filter.length - 1];
const error = this._checkPrefix(filterObj.rulePrefix);
if (error) {
filterObj.error = error;
}
return filterObj;
}
if (filter.And && (filter.Prefix || filter.Tag) ||
(filter.Prefix && filter.Tag)) {
const msg = 'Filter should only include one of And, Prefix, or Tag key';
const error = errorInstances.MalformedXML.customizeDescription(msg);
filterObj.error = error;
return filterObj;
}
if (filter.Prefix) {
filterObj.rulePrefix = filter.Prefix[filter.Prefix.length - 1];
const error = this._checkPrefix(filterObj.rulePrefix);
if (error) {
filterObj.error = error;
}
return filterObj;
}
if (filter.Tag) {
const tagObj = this._parseTags(filter.Tag);
if (tagObj.error) {
filterObj.error = tagObj.error;
return filterObj;
}
filterObj.tags = tagObj.tags;
return filterObj;
}
if (filter.And) {
const andF = filter.And[0];
if (!andF.Tag || (!andF.Prefix && andF.Tag.length < 2)) {
filterObj.error = errorInstances.MalformedXML.customizeDescription(
'And should include Prefix and Tags or more than one Tag');
return filterObj;
}
if (andF.Prefix && andF.Prefix.length >= 1) {
filterObj.rulePrefix = andF.Prefix[andF.Prefix.length - 1];
const error = this._checkPrefix(filterObj.rulePrefix);
if (error) {
filterObj.error = error;
return filterObj;
}
}
const tagObj = this._parseTags(andF.Tag);
if (tagObj.error) {
filterObj.error = tagObj.error;
return filterObj;
}
filterObj.tags = tagObj.tags;
return filterObj;
}
return filterObj;
}
/**
* Check that each tag object is valid
* @param tags - a tag object from a filter object
* @return - indicates whether tag object is valid
*
* Format of tagObj:
* tagObj = {
* error: <error>,
* tags: [
* {
* key: <value>,
* value: <value>,
* }
* ]
* }
*/
_parseTags(tags: { Key?: string; Value?: any[] }[]) {
// FIXME please
const tagObj: {
error?: ArsenalError;
tags: { key: string; val: string }[];
} = {
tags: [],
};
// reset _tagKeys to empty because keys cannot overlap within a rule,
// but different rules can have the same tag keys
this._tagKeys = [];
for (const tag of tags) {
if (!tag.Key || !tag.Value) {
const msg = 'Tag XML does not contain both Key and Value';
const err = errorInstances.MissingRequiredParameter.customizeDescription(msg);
tagObj.error = err;
break;
}
if (tag.Key[0].length < 1 || tag.Key[0].length > 128) {
tagObj.error = errorInstances.InvalidRequest.customizeDescription(
"A Tag's Key must be a length between 1 and 128"
);
break;
}
if (tag.Value[0].length < 0 || tag.Value[0].length > 256) {
tagObj.error = errorInstances.InvalidRequest.customizeDescription(
"A Tag's Value must be a length between 0 and 256"
);
break;
}
if (this._tagKeys.includes(tag.Key[0])) {
tagObj.error = errorInstances.InvalidRequest.customizeDescription(
'Tag Keys must be unique'
);
break;
}
this._tagKeys.push(tag.Key[0]);
tagObj.tags.push({
key: tag.Key[0],
val: tag.Value[0],
});
}
return tagObj;
}
/**
* Check that ID component of rule is valid
* @param id - contains id string at first index or empty
* @return - contains error if parsing failed or id is not unique,
* else contains parsed or generated id
*
* Format of idObj:
* idObj = {
* error: <error>,
* propName: 'ruleID',
* ruleID: <value>
* }
*/
_parseID(id: string[]) {
// @ts-ignore
const idObj:
| { error: ArsenalError; propName: 'ruleID', ruleID?: any }
| { propName: 'ruleID', ruleID: any } = { propName: 'ruleID' };
if (id && id[0].length > 255) {
const msg = 'Rule ID is greater than 255 characters long';
const error = errorInstances.InvalidArgument.customizeDescription(msg);
return { ...idObj, error };
}
if (!id || !id[0] || id[0] === '') {
// ID is optional property, but create one if not provided or is ''
// We generate 48-character alphanumeric, unique ID for rule
idObj.ruleID = Buffer.from(uuid()).toString('base64');
} else {
idObj.ruleID = id[0];
}
// Each ID in a list of rules must be unique.
if (this._ruleIDs.includes(idObj.ruleID)) {
const msg = 'Rule ID must be unique';
const error = errorInstances.InvalidRequest.customizeDescription(msg);
return { ...idObj, error };
}
this._ruleIDs.push(idObj.ruleID);
return idObj;
}
/**
* Check that status component of rule is valid
* @param status - status string
* @return - contains error if parsing failed, else contains
* parsed status
*
* Format of statusObj:
* statusObj = {
* error: <error>,
* propName: 'ruleStatus',
* ruleStatus: <value>
* }
*/
_parseStatus(status: string) {
const base: { propName: 'ruleStatus' } = { propName: 'ruleStatus' };
const validStatuses = ['Enabled', 'Disabled'];
if (!validStatuses.includes(status)) {
const msg = 'Status is not valid';
const error = errorInstances.MalformedXML.customizeDescription(msg);
return { ...base, error };
}
return { ...base, ruleStatus: status };
}
/**
* Finds the prefix and/or tags of the given rule and gets the error message
* @param rule - The rule to find the prefix in
* @return - The prefix of filter information
*/
_getRuleFilterDesc(rule: { Prefix?: string[]; Filter?: any[] }) {
if (rule.Prefix) {
return `prefix '${rule.Prefix[0]}'`;
}
// There must be a filter if no top-level prefix is provided. First
// check if there are multiple filters (i.e. `Filter.And`).
if (rule.Filter?.[0] === undefined || rule.Filter[0].And === undefined) {
const { Prefix, Tag } = rule.Filter?.[0] || {};
if (Prefix) {
return `filter '(prefix=${Prefix[0]})'`;
}
if (Tag) {
const { Key, Value } = Tag[0];
return `filter '(tag: key=${Key[0]}, value=${Value[0]})'`;
}
return 'filter (all)';
}
const filters: string[] = [];
const { Prefix, Tag } = rule.Filter[0].And[0];
if (Prefix) {
filters.push(`prefix=${Prefix[0]}`);
}
Tag.forEach((tag: { Key: string[]; Value: string[] }) => {
const { Key, Value } = tag;
filters.push(`tag: key=${Key[0]}, value=${Value[0]}`);
});
const joinedFilters = filters.join(' and ');
return `filter '(${joinedFilters})'`;
}
/**
* Checks the validity of the given field
* @param params - Given function parameters
* @param params.days - The value of the field to check
* @param params.field - The field name with the value
* @param params.ancestor - The immediate ancestor field
* @return Returns an error object or `null`
*/
_checkDays(params: { days: number; field: string; ancestor: string }) {
const { days, field, ancestor } = params;
if (days < 0) {
const msg = `'${field}' in ${ancestor} action must be nonnegative`;
return errorInstances.InvalidArgument.customizeDescription(msg);
}
if (days > MAX_DAYS) {
return errorInstances.MalformedXML.customizeDescription(
`'${field}' in ${ancestor} action must not exceed ${MAX_DAYS}`);
}
return null;
}
/**
* Checks the validity of the given storage class
* @param params - Given function parameters
* @param params.usedStorageClasses - Storage classes used in other
* rules
* @param params.storageClass - The storage class of the current
* rule
* @param params.ancestor - The immediate ancestor field
* @param params.prefix - The prefix of the rule
* @return Returns an error object or `null`
*/
_checkStorageClasses(params: {
usedStorageClasses: string[];
storageClass: string;
ancestor: string;
rule: { Prefix?: string[]; Filter?: any };
}) {
const { usedStorageClasses, storageClass, ancestor, rule } = params;
if (!this._storageClasses.includes(storageClass)) {
// This differs from the AWS message. This will help the user since
// the StorageClass does not conform to AWS specs.
const list = `'${this._storageClasses.join("', '")}'`;
const msg = `'StorageClass' must be one of ${list}, but provided: ${storageClass}`;
return errorInstances.MalformedXML.customizeDescription(msg);
}
if (usedStorageClasses.includes(storageClass)) {
const msg = `'StorageClass' must be different for '${ancestor}' ` +
`actions in same 'Rule' with ${this._getRuleFilterDesc(rule)}`;
return errorInstances.InvalidRequest.customizeDescription(msg);
}
return null;
}
/**
* Ensure that transition rules are at least a day apart from each other.
* @param params - Given function parameters
* @param [params.days] - The days of the current transition
* @param [params.date] - The date of the current transition
* @param params.storageClass - The storage class of the current
* rule
* @param params.rule - The current rule
*/
_checkTimeGap(params: {
days?: number;
date?: string;
storageClass: string;
rule: { Transition: any[]; Prefix?: string[]; Filter?: any };
}) {
const { days, date, storageClass, rule } = params;
const invalidTransition = rule.Transition.find(transition => {
if (storageClass === transition.StorageClass[0]) {
return false;
}
if (days !== undefined) {
return Number.parseInt(transition.Days[0], 10) === days;
}
if (date !== undefined) {
const timestamp = new Date(date).getTime();
const compareTimestamp = new Date(transition.Date[0]).getTime();
const oneDay = 24 * 60 * 60 * 1000; // Milliseconds in a day.
return Math.abs(timestamp - compareTimestamp) < oneDay;
}
return false;
});
if (invalidTransition) {
const timeType = days !== undefined ? 'Days' : 'Date';
const filterMsg = this._getRuleFilterDesc(rule);
const compareStorageClass = invalidTransition.StorageClass[0];
const msg = `'${timeType}' in the 'Transition' action for ` +
`StorageClass '${storageClass}' for ${filterMsg} must be at ` +
`least one day apart from ${filterMsg} in the 'Transition' ` +
`action for StorageClass '${compareStorageClass}'`;
return errorInstances.InvalidArgument.customizeDescription(msg);
}
return null;
}
/**
* Checks transition time type (i.e. 'Date' or 'Days') only occurs once
* across transitions and across transitions and expiration policies
* @param params - Given function parameters
* @param params.usedTimeType - The time type that has been used by
* another rule
* @param params.currentTimeType - the time type used by the
* current rule
* @param params.rule - The current rule
* @return Returns an error object or `null`
*/
_checkTimeType(params: {
usedTimeType: string | null;
currentTimeType: string;
rule: { Prefix?: string[]; Filter?: any; Expiration?: any[] };
}) {
const { usedTimeType, currentTimeType, rule } = params;
if (usedTimeType && usedTimeType !== currentTimeType) {
const msg = "Found mixed 'Date' and 'Days' based Transition " +
'actions in lifecycle rule for ' +
`${this._getRuleFilterDesc(rule)}`;
return errorInstances.InvalidRequest.customizeDescription(msg);
}
// Transition time type cannot differ from the expiration, if provided.
if (rule.Expiration &&
rule.Expiration[0][currentTimeType] === undefined) {
const msg = "Found mixed 'Date' and 'Days' based Expiration and " +
'Transition actions in lifecycle rule for ' +
`${this._getRuleFilterDesc(rule)}`;
return errorInstances.InvalidRequest.customizeDescription(msg);
}
return null;
}
/**
* Checks the validity of the given date
* @param date - The date the check
* @return Returns an error object or `null`
*/
_checkDate(date: string) {
const isoRegex = new RegExp(
'^(-?(?:[1-9][0-9]*)?[0-9]{4})' + // Year
'-(1[0-2]|0[1-9])' + // Month
'-(3[01]|0[1-9]|[12][0-9])' + // Day
'T(2[0-3]|[01][0-9])' + // Hour
':([0-5][0-9])' + // Minute
':([0-5][0-9])' + // Second
'(\\.[0-9]+)?' + // Fractional second
'(Z|[+-][01][0-9]:[0-5][0-9])?$', // Timezone
'g',
);
const matches = [...date.matchAll(isoRegex)];
if (matches.length !== 1) {
const msg = 'Date must be in ISO 8601 format';
return errorInstances.InvalidArgument.customizeDescription(msg);
}
// Check for a timezone in the last match group. If none, add a Z to indicate UTC.
if (!matches[0][matches[0].length-1]) {
date += 'Z';
}
const dateObj = new Date(date);
if (Number.isNaN(dateObj.getTime())) {
const msg = 'Date is not a valid date';
return errorInstances.InvalidArgument.customizeDescription(msg);
}
if (dateObj.getUTCHours() !== 0
|| dateObj.getUTCMinutes() !== 0
|| dateObj.getUTCSeconds() !== 0
|| dateObj.getUTCMilliseconds() !== 0) {
const msg = '\'Date\' must be at midnight GMT';
return errorInstances.InvalidArgument.customizeDescription(msg);
}
return null;
}
/**
* Parses the NonCurrentVersionTransition value
* @param rule - Rule object from Rule array from this._parsedXml
* @return - Contains error if parsing failed, otherwise contains
* the parsed nonCurrentVersionTransition array
*
* Format of result:
* result = {
* error: <error>,
* nonCurrentVersionTransition: [
* {
* noncurrentDays: <non-current-days>,
* storageClass: <storage-class>,
* },
* ...
* ]
* }
*/
_parseNoncurrentVersionTransition(rule: {
NoncurrentVersionTransition: any[];
Prefix?: string[];
Filter?: any;
}) {
const nonCurrentVersionTransition: {
noncurrentDays: number;
storageClass: string;
}[] = [];
const usedStorageClasses: string[] = [];
for (let i = 0; i < rule.NoncurrentVersionTransition.length; i++) {
const t = rule.NoncurrentVersionTransition[i]; // Transition object
const noncurrentDays: number | undefined =
t.NoncurrentDays && Number.parseInt(t.NoncurrentDays[0], 10);
const storageClass: string | undefined = t.StorageClass && t.StorageClass[0];
if (noncurrentDays === undefined || storageClass === undefined) {
return { error: errors.MalformedXML };
}
let error = this._checkDays({
days: noncurrentDays,
field: 'NoncurrentDays',
ancestor: 'NoncurrentVersionTransition',
});
if (error) {
return { error };
}
error = this._checkStorageClasses({
storageClass,
usedStorageClasses,
ancestor: 'NoncurrentVersionTransition',
rule,
});
if (error) {
return { error };
}
nonCurrentVersionTransition.push({ noncurrentDays, storageClass });
usedStorageClasses.push(storageClass);
}
return { nonCurrentVersionTransition };
}
/**
* Parses the Transition value
* @param rule - Rule object from Rule array from this._parsedXml
* @return - Contains error if parsing failed, otherwise contains
* the parsed transition array
*
* Format of result:
* result = {
* error: <error>,
* transition: [
* {
* days: <days>,
* date: <date>,
* storageClass: <storage-class>,
* },
* ...
* ]
* }
*/
_parseTransition(rule: {
Transition: any[];
Prefix?: string[];
Filter?: any;
}) {
const transition:
({ days: number; storageClass: string }
| { date: string; storageClass: string })[] = [];
const usedStorageClasses: string[] = [];
let usedTimeType: string | null = null;
for (let i = 0; i < rule.Transition.length; i++) {
const t = rule.Transition[i]; // Transition object
const days = t.Days && Number.parseInt(t.Days[0], 10);
const date = t.Date && t.Date[0];
const storageClass = t.StorageClass && t.StorageClass[0];
if ((days === undefined && date === undefined) ||
(days !== undefined && date !== undefined) ||
(storageClass === undefined)) {
return { error: errors.MalformedXML };
}
let error = this._checkStorageClasses({
storageClass,
usedStorageClasses,
ancestor: 'Transition',
rule,
});
if (error) {
return { error };
}
usedStorageClasses.push(storageClass);
if (days !== undefined) {
error = this._checkTimeType({
usedTimeType,
currentTimeType: 'Days',
rule,
});
if (error) {
return { error };
}
usedTimeType = 'Days';
error = this._checkDays({
days,
field: 'Days',
ancestor: 'Transition',
});
if (error) {
return { error };
}
transition.push({ days, storageClass });
}
if (date !== undefined) {
error = this._checkTimeType({
usedTimeType,
currentTimeType: 'Date',
rule,
});
if (error) {
return { error };
}
usedTimeType = 'Date';
error = this._checkDate(date);
if (error) {
return { error };
}
transition.push({ date, storageClass });
}
error = this._checkTimeGap({ days, date, storageClass, rule });
if (error) {
return { error };
}
}
return { transition };
}
/**
* Check that action component of rule is valid
* @param rule - a rule object from Rule array from this._parsedXml
* @return - contains error if parsing failed, else contains
* parsed action information
*
* Format of actionObj:
* actionsObj = {
* error: <error>,
* propName: 'action',
* actions: [
* {
* actionName: <value>,
* days: <value>,
* date: <value>,
* deleteMarker: <value>
* newerNoncurrentVersions: <value>,
* },
* ],
* }
*/
_parseAction(rule: LifecycleXMLRule) {
const actionsObj: {
error?: ArsenalError;
propName: 'actions';
actions: {
actionName: string;
days?: number;
date?: number;
deleteMarker?: boolean;
newerNoncurrentVersions?: number
}[];
} = {
propName: 'actions',
actions: [],
};
for (const action of ValidLifecycleRules) {
if (!rule[action]) {
continue;
}
const isRuleSupported = this._supportedLifecycleRules.includes(action);
if (!isRuleSupported) {
const msg = `${action} lifecycle action not implemented`;
const error = errorInstances.NotImplemented.customizeDescription(msg);
return { ...actionsObj, error };
}
actionsObj.actions.push({ actionName: action });
}
if (actionsObj.actions.length === 0) {
const msg = 'Rule does not include valid action';
const error = errorInstances.InvalidRequest.customizeDescription(msg);
return { ...actionsObj, error };
}
actionsObj.actions.forEach(a => {
const actionFn = `_parse${a.actionName}`;
const action = this[actionFn](rule);
if (action.error) {
actionsObj.error = action.error;
} else {
const actionTimes = [
'days',
'date',
'deleteMarker',
'transition',
'nonCurrentVersionTransition',
'newerNoncurrentVersions'
];
actionTimes.forEach(t => {
if (action[t]) {
a[t] = action[t];
}
});
}
});
return actionsObj;
}
/**
* Check that AbortIncompleteMultipartUpload action is valid
* @param rule - a rule object from Rule array from this._parsedXml
* @return - contains error if parsing failed, else contains
* parsed action time
*
* Format of abortObj:
* abortObj = {
* error: <error>,
* days: <value>
* }
*/
_parseAbortIncompleteMultipartUpload(rule: { AbortIncompleteMultipartUpload: any[]; Filter?: any[] }) {
const abortObj: { error?: ArsenalError, days?: number } = {};
let filter: any = null;
if (rule.Filter && rule.Filter[0]) {
if (rule.Filter[0].And) {