-
Notifications
You must be signed in to change notification settings - Fork 63
Expand file tree
/
Copy pathraw_simulator.py
More file actions
2165 lines (1954 loc) · 79.8 KB
/
raw_simulator.py
File metadata and controls
2165 lines (1954 loc) · 79.8 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
######################################################################
#
# File: b2sdk/_internal/raw_simulator.py
#
# Copyright 2021 Backblaze Inc. All Rights Reserved.
#
# License https://www.backblaze.com/using_b2_code.html
#
######################################################################
from __future__ import annotations
import collections
import dataclasses
import io
import logging
import random
import re
import threading
import time
from contextlib import contextmanager
from typing import Iterable
from requests.structures import CaseInsensitiveDict
from .b2http import ResponseContextManager
from .encryption.setting import EncryptionMode, EncryptionSetting
from .exception import (
AccessDenied,
BadJson,
BadRequest,
BadUploadUrl,
ChecksumMismatch,
Conflict,
CopySourceTooBig,
DisablingFileLockNotSupported,
DuplicateBucketName,
FileNotPresent,
FileSha1Mismatch,
InvalidAuthToken,
InvalidMetadataDirective,
MissingPart,
NonExistentBucket,
PartSha1Mismatch,
ResourceNotFound,
SourceReplicationConflict,
SSECKeyError,
Unauthorized,
UnsatisfiableRange,
)
from .file_lock import (
NO_RETENTION_BUCKET_SETTING,
BucketRetentionSetting,
FileRetentionSetting,
LegalHold,
RetentionMode,
)
from .file_version import UNVERIFIED_CHECKSUM_PREFIX
from .http_constants import FILE_INFO_HEADER_PREFIX, HEX_DIGITS_AT_END
from .raw_api import (
ALL_CAPABILITIES,
AbstractRawApi,
LifecycleRule,
MetadataDirectiveMode,
NotificationRule,
NotificationRuleResponse,
)
from .replication.setting import ReplicationConfiguration
from .replication.types import ReplicationStatus
from .stream.hashing import StreamWithHash
from .utils import ConcurrentUsedAuthTokenGuard, b2_url_decode, b2_url_encode, hex_sha1_of_bytes
logger = logging.getLogger(__name__)
def get_bytes_range(data_bytes, bytes_range):
"""Slice bytes array using bytes range"""
if bytes_range is None:
return data_bytes
if bytes_range[0] > bytes_range[1]:
raise UnsatisfiableRange()
if bytes_range[0] < 0:
raise UnsatisfiableRange()
if bytes_range[1] > len(data_bytes):
raise UnsatisfiableRange()
return data_bytes[bytes_range[0] : bytes_range[1] + 1]
class KeySimulator:
"""
Hold information about one application key, which can be either
a master application key, or one created with create_key().
"""
def __init__(
self,
account_id,
name,
application_key_id,
key,
capabilities,
expiration_timestamp_or_none,
buckets_or_none,
name_prefix_or_none,
):
self.name = name
self.account_id = account_id
self.application_key_id = application_key_id
self.key = key
self.capabilities = capabilities
self.expiration_timestamp_or_none = expiration_timestamp_or_none
self.buckets_or_none = buckets_or_none
self.name_prefix_or_none = name_prefix_or_none
def _get_bucket_ids(self):
if self.buckets_or_none is None:
return None
return [item['id'] for item in self.buckets_or_none]
def as_key(self):
return dict(
accountId=self.account_id,
bucketIds=self._get_bucket_ids(),
applicationKeyId=self.application_key_id,
capabilities=self.capabilities,
expirationTimestamp=self.expiration_timestamp_or_none
and self.expiration_timestamp_or_none * 1000,
keyName=self.name,
namePrefix=self.name_prefix_or_none,
)
def as_created_key(self):
"""
Return the dict returned by b2_create_key.
This is just like the one for b2_list_keys, but also includes the secret key.
"""
result = self.as_key()
result['applicationKey'] = self.key
return result
def get_allowed(self):
"""
Return the 'allowed' structure to include in the response from b2_authorize_account.
"""
return dict(
buckets=self.buckets_or_none,
capabilities=self.capabilities,
namePrefix=self.name_prefix_or_none,
)
class PartSimulator:
def __init__(self, file_id, part_number, content_length, content_sha1, part_data):
self.file_id = file_id
self.part_number = part_number
self.content_length = content_length
self.content_sha1 = content_sha1
self.part_data = part_data
def as_list_parts_dict(self):
return dict(
fileId=self.file_id,
partNumber=self.part_number,
contentLength=self.content_length,
contentSha1=self.content_sha1,
)
class FileSimulator:
"""
One of three: an unfinished large file, a finished file, or a deletion marker.
"""
CHECK_ENCRYPTION = True
SPECIAL_FILE_INFOS = { # when downloading, these file info keys are translated to specialized headers
'b2-content-disposition': 'Content-Disposition',
'b2-content-language': 'Content-Language',
'b2-expires': 'Expires',
'b2-cache-control': 'Cache-Control',
'b2-content-encoding': 'Content-Encoding',
}
def __init__(
self,
account_id,
bucket,
file_id,
action,
name,
content_type,
content_sha1,
file_info,
data_bytes,
upload_timestamp,
range_=None,
server_side_encryption: EncryptionSetting | None = None,
file_retention: FileRetentionSetting | None = None,
legal_hold: LegalHold = LegalHold.UNSET,
replication_status: ReplicationStatus | None = None,
):
if action == 'hide':
assert server_side_encryption is None
else:
assert server_side_encryption is not None
self.account_id = account_id
self.bucket = bucket
self.file_id = file_id
self.action = action
self.name = name
if data_bytes is not None:
self.content_length = len(data_bytes)
self.content_type = content_type
self.content_sha1 = content_sha1
if content_sha1 and content_sha1 != 'none' and len(content_sha1) != 40:
raise ValueError(content_sha1)
self.file_info = file_info
self.data_bytes = data_bytes
self.upload_timestamp = upload_timestamp
self.range_ = range_
self.server_side_encryption = server_side_encryption
self.file_retention = file_retention
self.legal_hold = legal_hold if legal_hold is not None else LegalHold.UNSET
self.replication_status = replication_status
if action == 'start':
self.parts = []
@classmethod
@contextmanager
def dont_check_encryption(cls):
cls.CHECK_ENCRYPTION = False
yield
cls.CHECK_ENCRYPTION = True
def sort_key(self):
"""
Return a key that can be used to sort the files in a
bucket in the order that b2_list_file_versions returns them.
"""
return (self.name, self.file_id)
def as_download_headers(
self, account_auth_token_or_none: str | None = None, range_: tuple[int, int] | None = None
) -> dict[str, str]:
if self.data_bytes is None:
content_length = 0
elif range_ is not None:
if range_[1] >= len(self.data_bytes): # requested too much
content_length = len(self.data_bytes)
else:
content_length = range_[1] - range_[0] + 1
else:
content_length = len(self.data_bytes)
headers = CaseInsensitiveDict(
{
'content-length': str(content_length),
'content-type': self.content_type,
'x-bz-content-sha1': self.content_sha1,
'x-bz-upload-timestamp': str(self.upload_timestamp),
'x-bz-file-id': self.file_id,
'x-bz-file-name': b2_url_encode(self.name),
}
)
for key, value in self.file_info.items():
key_lower = key.lower()
if key_lower in self.SPECIAL_FILE_INFOS:
headers[self.SPECIAL_FILE_INFOS[key_lower]] = value
else:
headers[FILE_INFO_HEADER_PREFIX + key] = b2_url_encode(value)
if account_auth_token_or_none is not None and self.bucket.is_file_lock_enabled:
not_permitted = []
if not self.is_allowed_to_read_file_retention(account_auth_token_or_none):
not_permitted.append('X-Bz-File-Retention-Mode')
not_permitted.append('X-Bz-File-Retain-Until-Timestamp')
else:
if self.file_retention is not None:
self.file_retention.add_to_to_upload_headers(headers)
if not self.is_allowed_to_read_file_legal_hold(account_auth_token_or_none):
not_permitted.append('X-Bz-File-Legal-Hold')
else:
headers['X-Bz-File-Legal-Hold'] = self.legal_hold and 'on' or 'off'
if not_permitted:
headers['X-Bz-Client-Unauthorized-To-Read'] = ','.join(not_permitted)
if self.server_side_encryption is not None:
if self.server_side_encryption.mode == EncryptionMode.SSE_B2:
headers['X-Bz-Server-Side-Encryption'] = self.server_side_encryption.algorithm.value
elif self.server_side_encryption.mode == EncryptionMode.SSE_C:
headers['X-Bz-Server-Side-Encryption-Customer-Algorithm'] = (
self.server_side_encryption.algorithm.value
)
headers['X-Bz-Server-Side-Encryption-Customer-Key-Md5'] = (
self.server_side_encryption.key.key_md5()
)
elif self.server_side_encryption.mode in (EncryptionMode.NONE, EncryptionMode.UNKNOWN):
pass
else:
raise ValueError(f'Unsupported encryption mode: {self.server_side_encryption.mode}')
if range_ is not None:
headers['Content-Range'] = 'bytes %d-%d/%d' % (
range_[0],
range_[0] + content_length - 1,
len(self.data_bytes),
)
return headers
def as_upload_result(self, account_auth_token):
result = dict(
fileId=self.file_id,
fileName=self.name,
accountId=self.account_id,
bucketId=self.bucket.bucket_id,
contentLength=len(self.data_bytes) if self.data_bytes is not None else 0,
contentType=self.content_type,
contentSha1=self.content_sha1,
fileInfo=self.file_info,
action=self.action,
uploadTimestamp=self.upload_timestamp,
replicationStatus=self.replication_status and self.replication_status.value,
)
if self.server_side_encryption is not None:
result['serverSideEncryption'] = (
self.server_side_encryption.serialize_to_json_for_request()
)
result['fileRetention'] = self._file_retention_dict(account_auth_token)
result['legalHold'] = self._legal_hold_dict(account_auth_token)
return result
def as_list_files_dict(self, account_auth_token):
result = dict(
accountId=self.account_id,
bucketId=self.bucket.bucket_id,
fileId=self.file_id,
fileName=self.name,
contentLength=len(self.data_bytes) if self.data_bytes is not None else 0,
contentType=self.content_type,
contentSha1=self.content_sha1,
fileInfo=self.file_info,
action=self.action,
uploadTimestamp=self.upload_timestamp,
replicationStatus=self.replication_status and self.replication_status.value,
)
if self.server_side_encryption is not None:
result['serverSideEncryption'] = (
self.server_side_encryption.serialize_to_json_for_request()
)
result['fileRetention'] = self._file_retention_dict(account_auth_token)
result['legalHold'] = self._legal_hold_dict(account_auth_token)
return result
def is_allowed_to_read_file_retention(self, account_auth_token):
return self.bucket._check_capability(account_auth_token, 'readFileRetentions')
def is_allowed_to_read_file_legal_hold(self, account_auth_token):
return self.bucket._check_capability(account_auth_token, 'readFileLegalHolds')
def as_start_large_file_result(self, account_auth_token):
result = dict(
fileId=self.file_id,
fileName=self.name,
accountId=self.account_id,
bucketId=self.bucket.bucket_id,
contentType=self.content_type,
fileInfo=self.file_info,
uploadTimestamp=self.upload_timestamp,
replicationStatus=self.replication_status and self.replication_status.value,
)
if self.server_side_encryption is not None:
result['serverSideEncryption'] = (
self.server_side_encryption.serialize_to_json_for_request()
)
result['fileRetention'] = self._file_retention_dict(account_auth_token)
result['legalHold'] = self._legal_hold_dict(account_auth_token)
return result
def _file_retention_dict(self, account_auth_token):
if not self.is_allowed_to_read_file_retention(account_auth_token):
return {
'isClientAuthorizedToRead': False,
'value': None,
}
file_lock_configuration = {'isClientAuthorizedToRead': True}
if self.file_retention is None:
file_lock_configuration['value'] = {'mode': None}
else:
file_lock_configuration['value'] = {'mode': self.file_retention.mode.value}
if self.file_retention.retain_until is not None:
file_lock_configuration['value']['retainUntilTimestamp'] = (
self.file_retention.retain_until
)
return file_lock_configuration
def _legal_hold_dict(self, account_auth_token):
if not self.is_allowed_to_read_file_legal_hold(account_auth_token):
return {
'isClientAuthorizedToRead': False,
'value': None,
}
return {
'isClientAuthorizedToRead': True,
'value': self.legal_hold.value,
}
def add_part(self, part_number, part):
while len(self.parts) < part_number + 1:
self.parts.append(None)
self.parts[part_number] = part
def finish(self, part_sha1_array):
last_part_number = max(part.part_number for part in self.parts if part is not None)
for part_number in range(1, last_part_number + 1):
if self.parts[part_number] is None:
raise MissingPart(part_number)
my_part_sha1_array = [
self.parts[part_number].content_sha1 for part_number in range(1, last_part_number + 1)
]
if part_sha1_array != my_part_sha1_array:
raise ChecksumMismatch(
'sha1', expected=str(part_sha1_array), actual=str(my_part_sha1_array)
)
self.data_bytes = b''.join(
self.parts[part_number].part_data for part_number in range(1, last_part_number + 1)
)
self.content_length = len(self.data_bytes)
self.action = 'upload'
def is_visible(self):
"""
Does this file show up in b2_list_file_names?
"""
return self.action == 'upload'
def list_parts(self, start_part_number, max_part_count):
start_part_number = start_part_number or 1
max_part_count = max_part_count or 100
parts = [
part.as_list_parts_dict()
for part in self.parts
if part is not None and start_part_number <= part.part_number
]
if len(parts) <= max_part_count:
next_part_number = None
else:
next_part_number = parts[max_part_count]['partNumber']
parts = parts[:max_part_count]
return dict(parts=parts, nextPartNumber=next_part_number)
def check_encryption(self, request_encryption: EncryptionSetting | None):
if not self.CHECK_ENCRYPTION:
return
file_mode, file_secret = self._get_encryption_mode_and_secret(self.server_side_encryption)
request_mode, request_secret = self._get_encryption_mode_and_secret(request_encryption)
if file_mode in (None, EncryptionMode.NONE):
assert request_mode in (None, EncryptionMode.NONE)
elif file_mode == EncryptionMode.SSE_B2:
assert request_mode in (None, EncryptionMode.NONE, EncryptionMode.SSE_B2)
elif file_mode == EncryptionMode.SSE_C:
if request_mode != EncryptionMode.SSE_C or file_secret != request_secret:
raise SSECKeyError()
else:
raise ValueError('Unsupported EncryptionMode: %s' % (file_mode))
def _get_encryption_mode_and_secret(self, encryption: EncryptionSetting | None):
if encryption is None:
return None, None
mode = encryption.mode
if encryption.key is None:
secret = None
else:
secret = encryption.key.secret
return mode, secret
@dataclasses.dataclass
class FakeRequest:
url: str
headers: CaseInsensitiveDict
@dataclasses.dataclass
class FakeRaw:
data_bytes: bytes
_position: int = 0
def tell(self):
return self._position
def read(self, size):
data = self.data_bytes[self._position : self._position + size]
self._position += len(data)
return data
class FakeResponse:
def __init__(self, account_auth_token_or_none, file_sim, url, range_=None):
self.raw = FakeRaw(file_sim.data_bytes)
self.headers = file_sim.as_download_headers(account_auth_token_or_none, range_)
self.url = url
self.range_ = range_
if range_ is not None:
self.data_bytes = self.data_bytes[range_[0] : range_[1] + 1]
@property
def data_bytes(self):
return self.raw.data_bytes
@data_bytes.setter
def data_bytes(self, value):
self.raw = FakeRaw(value)
def iter_content(self, chunk_size=1):
rnd = random.Random(self.url)
while True:
chunk = self.raw.read(chunk_size)
if chunk:
time.sleep(rnd.random() * 0.01)
yield chunk
else:
break
@property
def request(self):
headers = CaseInsensitiveDict()
if self.range_ is not None:
headers['Range'] = '{}-{}'.format(*self.range_)
return FakeRequest(self.url, headers)
def close(self):
pass
def __enter__(self):
return self
def __exit__(self, *args):
self.close()
class BucketSimulator:
# File IDs start at 9999 and count down, so they sort in the order
# returned by list_file_versions. The IDs are strings.
FIRST_FILE_NUMBER = 9999
FIRST_FILE_ID = str(FIRST_FILE_NUMBER)
FILE_SIMULATOR_CLASS = FileSimulator
RESPONSE_CLASS = FakeResponse
MAX_SIMPLE_COPY_SIZE = 200 # should be same as RawSimulator.MIN_PART_SIZE
def __init__(
self,
api,
account_id,
bucket_id,
bucket_name,
bucket_type,
bucket_info=None,
cors_rules=None,
lifecycle_rules: list[LifecycleRule] | None = None,
options_set=None,
default_server_side_encryption=None,
is_file_lock_enabled: bool | None = None,
replication: ReplicationConfiguration | None = None,
):
assert bucket_type in ['allPrivate', 'allPublic']
self.api = api
self.account_id = account_id
self.bucket_name = bucket_name
self.bucket_id = bucket_id
self.bucket_type = bucket_type
self.bucket_info = bucket_info or {}
self.cors_rules = cors_rules or []
self.lifecycle_rules = lifecycle_rules or []
self._notification_rules = []
self.options_set = options_set or set()
self.revision = 1
self.upload_url_counter = iter(range(200))
# File IDs count down, so that the most recent will come first when they are sorted.
self.file_id_counter = iter(range(self.FIRST_FILE_NUMBER, 0, -1))
self.upload_timestamp_counter = iter(range(5000, 9999))
self.file_id_to_file: dict[str, FileSimulator] = dict()
self.file_name_and_id_to_file: dict[tuple[str, str], FileSimulator] = dict()
if default_server_side_encryption is None:
default_server_side_encryption = EncryptionSetting(mode=EncryptionMode.NONE)
self.default_server_side_encryption = default_server_side_encryption
self.is_file_lock_enabled = is_file_lock_enabled
self.default_retention = NO_RETENTION_BUCKET_SETTING
self.replication = replication
if self.replication is not None:
assert (
self.replication.asReplicationSource is None
or self.replication.asReplicationSource.rules
)
assert (
self.replication.asReplicationDestination is None
or self.replication.asReplicationDestination.sourceToDestinationKeyMapping
)
def get_file(self, file_id, file_name) -> FileSimulator:
try:
return self.file_name_and_id_to_file[(file_name, file_id)]
except KeyError:
raise FileNotPresent(file_id_or_name=file_id)
def is_allowed_to_read_bucket_encryption_setting(self, account_auth_token):
return self._check_capability(account_auth_token, 'readBucketEncryption')
def is_allowed_to_read_bucket_retention(self, account_auth_token):
return self._check_capability(account_auth_token, 'readBucketRetentions')
def _check_capability(self, account_auth_token, capability):
try:
key = self.api.auth_token_to_key[account_auth_token]
except KeyError:
# looks like it's an upload token
# fortunately BucketSimulator makes it easy to retrieve the true account_auth_token
# from an upload url
real_auth_token = account_auth_token.split('/')[-1]
# Strip the _upload_<id> suffix if present to get the base account auth token
if '_upload_' in real_auth_token:
real_auth_token = real_auth_token.split('_upload_')[0]
key = self.api.auth_token_to_key[real_auth_token]
capabilities = key.get_allowed()['capabilities']
return capability in capabilities
def bucket_dict(self, account_auth_token):
default_sse = {'isClientAuthorizedToRead': False}
if self.is_allowed_to_read_bucket_encryption_setting(account_auth_token):
default_sse['isClientAuthorizedToRead'] = True
default_sse['value'] = {'mode': self.default_server_side_encryption.mode.value}
if self.default_server_side_encryption.algorithm is not None:
default_sse['value']['algorithm'] = (
self.default_server_side_encryption.algorithm.value
)
else:
default_sse['value'] = {'mode': EncryptionMode.UNKNOWN.value}
if self.is_allowed_to_read_bucket_retention(account_auth_token):
file_lock_configuration = {
'isClientAuthorizedToRead': True,
'value': {
'defaultRetention': {
'mode': self.default_retention.mode.value,
'period': self.default_retention.period.as_dict()
if self.default_retention.period
else None,
},
'isFileLockEnabled': self.is_file_lock_enabled,
},
}
else:
file_lock_configuration = {'isClientAuthorizedToRead': False, 'value': None}
replication = self.replication and {
'isClientAuthorizedToRead': True,
'value': self.replication.as_dict(),
}
return dict(
accountId=self.account_id,
bucketName=self.bucket_name,
bucketId=self.bucket_id,
bucketType=self.bucket_type,
bucketInfo=self.bucket_info,
corsRules=self.cors_rules,
lifecycleRules=self.lifecycle_rules,
options=self.options_set,
revision=self.revision,
defaultServerSideEncryption=default_sse,
fileLockConfiguration=file_lock_configuration,
replicationConfiguration=replication,
)
def cancel_large_file(self, file_id):
file_sim = self.file_id_to_file[file_id]
key = (file_sim.name, file_id)
del self.file_name_and_id_to_file[key]
del self.file_id_to_file[file_id]
return dict(
accountId=self.account_id,
bucketId=self.bucket_id,
fileId=file_id,
fileName=file_sim.name,
)
def delete_file_version(
self, account_auth_token, file_id, file_name, bypass_governance: bool = False
):
key = (file_name, file_id)
file_sim = self.get_file(file_id, file_name)
if file_sim.file_retention:
if file_sim.file_retention.retain_until and file_sim.file_retention.retain_until > int(
time.time()
):
if file_sim.file_retention.mode == RetentionMode.COMPLIANCE:
raise AccessDenied()
elif file_sim.file_retention.mode == RetentionMode.GOVERNANCE:
if not bypass_governance:
raise AccessDenied()
if not self._check_capability(account_auth_token, 'bypassGovernance'):
raise AccessDenied()
del self.file_name_and_id_to_file[key]
del self.file_id_to_file[file_id]
return dict(fileId=file_id, fileName=file_name, uploadTimestamp=file_sim.upload_timestamp)
def download_file_by_id(
self,
account_auth_token_or_none,
file_id,
url,
range_=None,
encryption: EncryptionSetting | None = None,
):
file_sim = self.file_id_to_file[file_id]
file_sim.check_encryption(encryption)
return self._download_file_sim(account_auth_token_or_none, file_sim, url, range_=range_)
def download_file_by_name(
self,
account_auth_token_or_none,
file_name,
url,
range_=None,
encryption: EncryptionSetting | None = None,
):
files = self.list_file_names(self.api.current_token, file_name, 1)[
'files'
] # token is not important here
if len(files) == 0:
raise FileNotPresent(file_id_or_name=file_name)
file_dict = files[0]
if file_dict['fileName'] != file_name:
raise FileNotPresent(file_id_or_name=file_name)
file_sim = self.file_name_and_id_to_file[(file_name, file_dict['fileId'])]
if not file_sim.is_visible():
raise FileNotPresent(file_id_or_name=file_name)
file_sim.check_encryption(encryption)
return self._download_file_sim(account_auth_token_or_none, file_sim, url, range_=range_)
def _download_file_sim(self, account_auth_token_or_none, file_sim, url, range_=None):
return ResponseContextManager(
self.RESPONSE_CLASS(
account_auth_token_or_none,
file_sim,
url,
range_,
)
)
def finish_large_file(self, account_auth_token, file_id, part_sha1_array):
file_sim = self.file_id_to_file[file_id]
file_sim.finish(part_sha1_array)
return file_sim.as_upload_result(account_auth_token)
def get_file_info_by_id(self, account_auth_token, file_id):
return self.file_id_to_file[file_id].as_upload_result(account_auth_token)
def get_file_info_by_name(self, account_auth_token, file_name):
# Sorting files by name and ID, so lower ID (newer upload) is returned first.
for (name, id), file in sorted(self.file_name_and_id_to_file.items()):
if file_name == name:
return file.as_download_headers(account_auth_token_or_none=account_auth_token)
raise FileNotPresent(file_id_or_name=file_name, bucket_name=self.bucket_name)
def get_upload_url(self, account_auth_token):
upload_id = next(self.upload_url_counter)
# Generate a unique upload authorization token by appending upload_id to account token
# This ensures each upload URL has a different auth token, matching real B2 API behavior
unique_upload_token = '%s_upload_%d' % (account_auth_token, upload_id)
upload_url = 'https://upload.example.com/%s/%d/%s' % (
self.bucket_id,
upload_id,
unique_upload_token,
)
return dict(bucketId=self.bucket_id, uploadUrl=upload_url, authorizationToken=upload_url)
def get_upload_part_url(self, account_auth_token, file_id):
upload_url = 'https://upload.example.com/part/%s/%d/%s' % (
file_id,
random.randint(1, 10**9),
account_auth_token,
)
return dict(bucketId=self.bucket_id, uploadUrl=upload_url, authorizationToken=upload_url)
def hide_file(self, account_auth_token, file_name):
file_id = self._next_file_id()
file_sim = self.FILE_SIMULATOR_CLASS(
self.account_id,
self,
file_id,
'hide',
file_name,
None,
'none',
{},
b'',
next(self.upload_timestamp_counter),
)
self.file_id_to_file[file_id] = file_sim
self.file_name_and_id_to_file[file_sim.sort_key()] = file_sim
return file_sim.as_list_files_dict(account_auth_token)
def update_file_retention(
self,
account_auth_token,
file_id,
file_name,
file_retention: FileRetentionSetting,
bypass_governance: bool = False,
):
file_sim = self.file_id_to_file[file_id]
assert self.is_file_lock_enabled
assert file_sim.name == file_name
# TODO: check bypass etc
file_sim.file_retention = file_retention
return {
'fileId': file_id,
'fileName': file_name,
'fileRetention': file_sim.file_retention.serialize_to_json_for_request(),
}
def update_file_legal_hold(
self,
account_auth_token,
file_id,
file_name,
legal_hold: LegalHold,
):
file_sim = self.file_id_to_file[file_id]
assert self.is_file_lock_enabled
assert file_sim.name == file_name
file_sim.legal_hold = legal_hold
return {
'fileId': file_id,
'fileName': file_name,
'legalHold': legal_hold.to_server(),
}
def copy_file(
self,
account_auth_token,
file_id,
new_file_name,
bytes_range=None,
metadata_directive=None,
content_type=None,
file_info=None,
destination_bucket_id=None,
destination_server_side_encryption: EncryptionSetting | None = None,
source_server_side_encryption: EncryptionSetting | None = None,
file_retention: FileRetentionSetting | None = None,
legal_hold: LegalHold | None = None,
):
if metadata_directive is not None:
assert metadata_directive in tuple(MetadataDirectiveMode), metadata_directive
if metadata_directive is MetadataDirectiveMode.COPY and (
content_type is not None or file_info is not None
):
raise InvalidMetadataDirective(
'content_type and file_info should be None when metadata_directive is COPY'
)
elif metadata_directive is MetadataDirectiveMode.REPLACE and content_type is None:
raise InvalidMetadataDirective(
'content_type cannot be None when metadata_directive is REPLACE'
)
file_sim = self.file_id_to_file[file_id]
file_sim.check_encryption(source_server_side_encryption)
new_file_id = self._next_file_id()
data_bytes = get_bytes_range(file_sim.data_bytes, bytes_range)
if len(data_bytes) > self.MAX_SIMPLE_COPY_SIZE:
raise CopySourceTooBig(
'Copy source too big: %i' % (len(data_bytes),),
'bad_request',
len(data_bytes),
)
destination_bucket = self.api.bucket_id_to_bucket.get(destination_bucket_id, self)
sse = destination_server_side_encryption or self.default_server_side_encryption
copy_file_sim = self.FILE_SIMULATOR_CLASS(
self.account_id,
destination_bucket,
new_file_id,
'upload',
new_file_name,
file_sim.content_type,
hex_sha1_of_bytes(
data_bytes
), # we hash here again because bytes_range may not cover the full source
file_sim.file_info,
data_bytes,
next(self.upload_timestamp_counter),
server_side_encryption=sse,
file_retention=file_retention,
legal_hold=legal_hold,
)
destination_bucket.file_id_to_file[copy_file_sim.file_id] = copy_file_sim
destination_bucket.file_name_and_id_to_file[copy_file_sim.sort_key()] = copy_file_sim
if metadata_directive is MetadataDirectiveMode.REPLACE:
copy_file_sim.content_type = content_type
copy_file_sim.file_info = file_info or file_sim.file_info
## long term storage of that file has action="upload", but here we need to return action="copy", just this once
# class TestFileVersionFactory(FileVersionFactory):
# FILE_VERSION_CLASS = self.FILE_SIMULATOR_CLASS
# file_version_dict = copy_file_sim.as_upload_result(account_auth_token)
# del file_version_dict['action']
# print(file_version_dict)
# copy_file_sim_with_action_copy = TestFileVersionFactory(self.api).from_api_response(file_version_dict, force_action='copy')
# return copy_file_sim_with_action_copy
# TODO: the code above cannot be used right now because FileSimulator.__init__ is incompatible with FileVersionFactory / FileVersion.__init__ - refactor is needed
# for now we'll just return the newly constructed object with a copy action...
return self.FILE_SIMULATOR_CLASS(
self.account_id,
destination_bucket,
new_file_id,
'copy',
new_file_name,
copy_file_sim.content_type,
copy_file_sim.content_sha1,
copy_file_sim.file_info,
data_bytes,
copy_file_sim.upload_timestamp,
server_side_encryption=sse,
file_retention=file_retention,
legal_hold=legal_hold,
)
def list_file_names(
self,
account_auth_token,
start_file_name=None,
max_file_count=None,
prefix=None,
):
assert (
prefix is None or start_file_name is None or start_file_name.startswith(prefix)
), locals()
start_file_name = start_file_name or ''
max_file_count = max_file_count or 100
result_files = []
next_file_name = None
prev_file_name = None
for key in sorted(self.file_name_and_id_to_file):
(file_name, file_id) = key
assert file_id
if start_file_name <= file_name and file_name != prev_file_name:
if prefix is not None and not file_name.startswith(prefix):
break
prev_file_name = file_name
file_sim = self.file_name_and_id_to_file[key]
if file_sim.is_visible():
result_files.append(file_sim.as_list_files_dict(account_auth_token))
if len(result_files) == max_file_count:
next_file_name = file_sim.name + ' '
break
else:
logger.debug('skipping invisible file during listing: %s', key)
return dict(files=result_files, nextFileName=next_file_name)
def list_file_versions(
self,
account_auth_token,
start_file_name=None,
start_file_id=None,
max_file_count=None,
prefix=None,
):
assert (
prefix is None or start_file_name is None or start_file_name.startswith(prefix)
), locals()
start_file_name = start_file_name or ''
start_file_id = start_file_id or ''
max_file_count = max_file_count or 100
result_files = []
next_file_name = None
next_file_id = None
for key in sorted(self.file_name_and_id_to_file):
(file_name, file_id) = key
if (start_file_name < file_name) or (
start_file_name == file_name
and (start_file_id == '' or int(start_file_id) <= int(file_id))
):
file_sim = self.file_name_and_id_to_file[key]