From 58efa84392c7c7fa6e8d29d47d18434797c3b001 Mon Sep 17 00:00:00 2001 From: Sophie <49928680+sophiecarreras@users.noreply.github.com> Date: Fri, 2 Oct 2026 04:32:34 -0300 Subject: [PATCH 001/113] test(sdkharness): lock.bypass_governance and lock.per_file_retention accept B2's 401 access_denied (#621) A delete of a governance-locked version without bypassGovernance is refused by B2 with 401 access_denied (b2sdk: Unauthorized), as this repository's raw-API contract test shows. The two repository-owned conformance checks accepted AccessDenied, RetentionWriteError, Conflict or BadRequest only. They now also accept Unauthorized whose code is access_denied, and still fail when the delete is allowed or refused for another reason (bad token, other 401 code, 5xx, network). Co-authored-by: Claude Sonnet 5.5 --- .../tests/conformance/lock.bypass_governance | 23 +++- .../tests/conformance/lock.per_file_retention | 23 +++- ...+sdkharness-lock-refusal.infrastructure.md | 1 + test/unit/test_sdkharness_lock_refusal.py | 113 ++++++++++++++++++ 4 files changed, 158 insertions(+), 2 deletions(-) create mode 100644 changelog.d/+sdkharness-lock-refusal.infrastructure.md create mode 100644 test/unit/test_sdkharness_lock_refusal.py diff --git a/.sdkharness/tests/conformance/lock.bypass_governance b/.sdkharness/tests/conformance/lock.bypass_governance index 257777a9c..570f778bb 100755 --- a/.sdkharness/tests/conformance/lock.bypass_governance +++ b/.sdkharness/tests/conformance/lock.bypass_governance @@ -18,6 +18,16 @@ delete is refused: 401 access_denied, "The delete was not allowed because Object Lock is enabled on the file." https://www.backblaze.com/apidocs/b2-delete-file-version +401 access_denied is accepted as the refusal. B2's raw-API contract test for this +exact call (test/integration/test_raw_api.py: `with pytest.raises(Unauthorized): +raw_api.delete_file_version(...)` on a governance-locked version, then the +bypassing delete succeeds) passes against real B2 with a 401, and b2sdk raises +Unauthorized (code access_denied) for it; the simulator's default profile answers +the same. A refusal for an unrelated reason is still a failure: an +InvalidAuthToken (bad or expired token), any other Unauthorized code, a 5xx or a +network error does not count. The exact error code and message are not verified +against real B2 (UNVERIFIED in the simulator ledger, docs/FIDELITY.md). + Written from bin/conformance/b2-sdk-python/files.upload, the reference check, and bin/conformance/README.md, the contract. It exercises b2sdk from this exact repository checkout; the API was taken from @@ -119,11 +129,15 @@ def step(name, action): raise Failure(name, name_of) from error -def refused(name, action, expected): +def refused(name, action, expected, *, access_denied_401=False): """Assert something is REFUSED, and record what refused it. `expected` is a tuple of exception class names. A different class -- or no exception at all -- is a Failure, because the refusal IS the claim here. + With `access_denied_401`, b2sdk's Unauthorized is also accepted, but only + when its code is `access_denied` (a 401 about Object Lock, as B2 answers a + delete without bypassGovernance); InvalidAuthToken and every other + Unauthorized code stay failures. """ try: action() @@ -133,6 +147,12 @@ def refused(name, action, expected): name_of = type(error).__name__ if name_of in expected: return name_of + if ( + access_denied_401 + and name_of == 'Unauthorized' + and getattr(error, 'code', None) == 'access_denied' + ): + return 'Unauthorized(access_denied)' raise Failure(name, f"refused with {name_of}, expected {'/'.join(expected)}") from error raise Failure(name, 'the call was permitted; the claim under test is that it is refused') @@ -269,6 +289,7 @@ def run(target: str) -> None: 'delete without bypass', lambda: bucket.delete_file_version(uploaded.id_, OBJECT_NAME), ('AccessDenied', 'RetentionWriteError', 'Conflict', 'BadRequest'), + access_denied_401=True, ) step( diff --git a/.sdkharness/tests/conformance/lock.per_file_retention b/.sdkharness/tests/conformance/lock.per_file_retention index d310bbd6f..93f28b829 100755 --- a/.sdkharness/tests/conformance/lock.per_file_retention +++ b/.sdkharness/tests/conformance/lock.per_file_retention @@ -20,6 +20,16 @@ and bypassGovernance "Must be specified and set to true if deleting a file version protected by Object Lock governance mode retention settings." https://www.backblaze.com/apidocs/b2-delete-file-version +401 access_denied is accepted as the refusal. B2's raw-API contract test for this +exact call (test/integration/test_raw_api.py: `with pytest.raises(Unauthorized): +raw_api.delete_file_version(...)` on a governance-locked version, then the +bypassing delete succeeds) passes against real B2 with a 401, and b2sdk raises +Unauthorized (code access_denied) for it; the simulator's default profile answers +the same. A refusal for an unrelated reason is still a failure: an +InvalidAuthToken (bad or expired token), any other Unauthorized code, a 5xx or a +network error does not count. The exact error code and message are not verified +against real B2 (UNVERIFIED in the simulator ledger, docs/FIDELITY.md). + Written from bin/conformance/b2-sdk-python/files.upload, the reference check, and bin/conformance/README.md, the contract. It exercises b2sdk from this exact repository checkout; the API was taken from @@ -121,11 +131,15 @@ def step(name, action): raise Failure(name, name_of) from error -def refused(name, action, expected): +def refused(name, action, expected, *, access_denied_401=False): """Assert something is REFUSED, and record what refused it. `expected` is a tuple of exception class names. A different class -- or no exception at all -- is a Failure, because the refusal IS the claim here. + With `access_denied_401`, b2sdk's Unauthorized is also accepted, but only + when its code is `access_denied` (a 401 about Object Lock, as B2 answers a + delete without bypassGovernance); InvalidAuthToken and every other + Unauthorized code stay failures. """ try: action() @@ -135,6 +149,12 @@ def refused(name, action, expected): name_of = type(error).__name__ if name_of in expected: return name_of + if ( + access_denied_401 + and name_of == 'Unauthorized' + and getattr(error, 'code', None) == 'access_denied' + ): + return 'Unauthorized(access_denied)' raise Failure(name, f"refused with {name_of}, expected {'/'.join(expected)}") from error raise Failure(name, 'the call was permitted; the claim under test is that it is refused') @@ -278,6 +298,7 @@ def run(target: str) -> None: 'delete without bypass', lambda: bucket.delete_file_version(uploaded.id_, OBJECT_NAME), ('AccessDenied', 'RetentionWriteError', 'Conflict', 'BadRequest'), + access_denied_401=True, ) finally: teardown(api, bucket) diff --git a/changelog.d/+sdkharness-lock-refusal.infrastructure.md b/changelog.d/+sdkharness-lock-refusal.infrastructure.md new file mode 100644 index 000000000..b30c9f913 --- /dev/null +++ b/changelog.d/+sdkharness-lock-refusal.infrastructure.md @@ -0,0 +1 @@ +Repository-owned conformance checks `lock.bypass_governance` and `lock.per_file_retention` accept the 401 `access_denied` that B2 answers for a delete of a governance-locked version without bypass, and still fail if the delete is allowed or refused for an unrelated reason. diff --git a/test/unit/test_sdkharness_lock_refusal.py b/test/unit/test_sdkharness_lock_refusal.py new file mode 100644 index 000000000..5c6ebf45f --- /dev/null +++ b/test/unit/test_sdkharness_lock_refusal.py @@ -0,0 +1,113 @@ +###################################################################### +# +# File: test/unit/test_sdkharness_lock_refusal.py +# +# Copyright 2026 Backblaze Inc. All Rights Reserved. +# +# License https://www.backblaze.com/using_b2_code.html +# +###################################################################### +from __future__ import annotations + +from importlib.machinery import SourceFileLoader +from importlib.util import module_from_spec, spec_from_loader +from pathlib import Path + +import pytest + +CONFORMANCE = Path(__file__).parents[2] / '.sdkharness' / 'tests' / 'conformance' +LEAVES = ('lock.bypass_governance', 'lock.per_file_retention') +EXPECTED = ('AccessDenied', 'RetentionWriteError', 'Conflict', 'BadRequest') + + +def load_leaf(name): + loader = SourceFileLoader(f'sdkharness_leaf_{name.replace(".", "_")}', str(CONFORMANCE / name)) + spec = spec_from_loader(loader.name, loader) + module = module_from_spec(spec) + loader.exec_module(module) + return module + + +# `refused` classifies by class name, as the leaves do, so these stand-ins carry +# b2sdk's names. Unauthorized carries the `code` b2sdk reads from the response. +class Unauthorized(Exception): + def __init__(self, code): + super().__init__(code) + self.code = code + + +class InvalidAuthToken(Unauthorized): + pass + + +class ServiceError(Exception): + pass + + +def raising(error): + def action(): + raise error + + return action + + +@pytest.mark.parametrize('leaf', LEAVES) +def test_401_access_denied_counts_as_the_refusal(leaf): + module = load_leaf(leaf) + got = module.refused( + 'delete without bypass', + raising(Unauthorized('access_denied')), + EXPECTED, + access_denied_401=True, + ) + assert got == 'Unauthorized(access_denied)' + + +@pytest.mark.parametrize('leaf', LEAVES) +def test_the_old_refusal_classes_are_still_accepted(leaf): + module = load_leaf(leaf) + AccessDenied = type('AccessDenied', (Exception,), {}) + assert ( + module.refused( + 'delete without bypass', raising(AccessDenied()), EXPECTED, access_denied_401=True + ) + == 'AccessDenied' + ) + + +@pytest.mark.parametrize('leaf', LEAVES) +def test_an_allowed_operation_still_fails(leaf): + module = load_leaf(leaf) + with pytest.raises(module.Failure, match='permitted'): + module.refused('delete without bypass', lambda: None, EXPECTED, access_denied_401=True) + + +@pytest.mark.parametrize('leaf', LEAVES) +@pytest.mark.parametrize( + 'error', + [ + InvalidAuthToken('expired_auth_token'), + Unauthorized('bad_auth_token'), + Unauthorized('email_not_verified'), + ServiceError('503'), + KeyError('404'), + ], + ids=['bad-token', 'other-401-code', 'unverified-email', '5xx', 'not-found'], +) +def test_an_unrelated_refusal_still_fails(leaf, error): + module = load_leaf(leaf) + with pytest.raises(module.Failure, match='refused with'): + module.refused('delete without bypass', raising(error), EXPECTED, access_denied_401=True) + + +@pytest.mark.parametrize('leaf', LEAVES) +def test_unauthorized_is_not_accepted_unless_asked(leaf): + module = load_leaf(leaf) + with pytest.raises(module.Failure): + module.refused('delete without bypass', raising(Unauthorized('access_denied')), EXPECTED) + + +@pytest.mark.parametrize('leaf', LEAVES) +def test_the_leaf_asks_for_the_401_on_its_delete_without_bypass(leaf): + source = (CONFORMANCE / leaf).read_text() + assert 'access_denied_401=True' in source From 408b698d8957d0aefbca8e2c535d459d11f6962a Mon Sep 17 00:00:00 2001 From: Sophie <49928680+sophiecarreras@users.noreply.github.com> Date: Fri, 2 Oct 2026 20:10:35 -0300 Subject: [PATCH 002/113] test(sdkharness): leaf-check unit tests skip __pycache__ and other non-leaf entries (#622) Co-authored-by: Claude Sonnet 5.5 --- .../+sdkharness-leaves-skip-pycache.infrastructure.md | 1 + .../test_sdkharness_conformance_resilience_contract.py | 10 +++++++++- 2 files changed, 10 insertions(+), 1 deletion(-) create mode 100644 changelog.d/+sdkharness-leaves-skip-pycache.infrastructure.md diff --git a/changelog.d/+sdkharness-leaves-skip-pycache.infrastructure.md b/changelog.d/+sdkharness-leaves-skip-pycache.infrastructure.md new file mode 100644 index 000000000..4d74b4253 --- /dev/null +++ b/changelog.d/+sdkharness-leaves-skip-pycache.infrastructure.md @@ -0,0 +1 @@ +Make the sdkharness leaf-check unit tests ignore `__pycache__` and other non-leaf entries. diff --git a/test/unit/test_sdkharness_conformance_resilience_contract.py b/test/unit/test_sdkharness_conformance_resilience_contract.py index e133e44f9..15d59f77e 100644 --- a/test/unit/test_sdkharness_conformance_resilience_contract.py +++ b/test/unit/test_sdkharness_conformance_resilience_contract.py @@ -110,10 +110,18 @@ def test_child_environment_scrubs_real_b2_credentials_and_pins_checkout(): LEAF_ROOT = Path(__file__).parents[2] / '.sdkharness' / 'tests' LEAVES = sorted( - path for level in ('conformance', 'resilience') for path in (LEAF_ROOT / level).iterdir() + path + for level in ('conformance', 'resilience') + for path in (LEAF_ROOT / level).iterdir() + if path.is_file() and not path.name.startswith(('__', '.')) ) +def test_leaves_are_regular_files_only(): + assert LEAVES + assert all(path.is_file() and not path.name.startswith('__') for path in LEAVES) + + def run_leaf(path, extra_environment): import os import subprocess From e4117e3ca8c4f3c20bcbda5db4f2592fb6f59843 Mon Sep 17 00:00:00 2001 From: Sophie <49928680+sophiecarreras@users.noreply.github.com> Date: Sat, 3 Oct 2026 21:45:35 -0300 Subject: [PATCH 003/113] Make sdkharness Python checks fail instead of skip on real errors (#623) Conformance leaves mapped Unauthorized/AccessDenied/ServiceError/ ConnectionError to COULD-NOT-RUN and any ImportError to missing-runtime, which the dispatcher turned into SKIP (exit 0). At a loopback simulator the harness supplies both server and credential, so those are defects. Only a genuinely absent b2sdk module (or a missing simulator URL) may be amber. - leaves: auth, access-denied, connection and service errors, URL errors and SDK ImportErrors are FAIL; only ModuleNotFoundError for b2sdk itself is missing-runtime - lib/contract.py: SKIP only for no-realm-option, missing-runtime, no-client-option, not-claimed; any other COULD-NOT-RUN reason is FAIL - scrub proxy variables in the dispatcher, the health check and every leaf (NO_PROXY pinned to 127.0.0.1) so a stray proxy cannot change a result - README: api.retry_after_503 and upload.retry_408 pass now - fix the garbled files.upload docstring and references to harness-only paths - unit tests: dead simulator port and SDK ImportError yield FAIL Co-authored-by: Claude Sonnet 5.5 --- .sdkharness/README.md | 15 +- .sdkharness/tests/conformance/bucket.cors | 44 ++--- .sdkharness/tests/conformance/bucket.crud | 32 ++-- .../tests/conformance/bucket.lifecycle | 32 ++-- .../conformance/bucket.notification_rules | 32 ++-- .../conformance/bucket.replication_config | 32 ++-- .../conformance/bucket.replication_helper | 32 ++-- .../tests/conformance/client.auth_persistence | 44 ++--- .sdkharness/tests/conformance/client.progress | 32 ++-- .../tests/conformance/client.simulator | 30 +-- .sdkharness/tests/conformance/client.sync | 32 ++-- .sdkharness/tests/conformance/enc.sse_b2 | 32 ++-- .sdkharness/tests/conformance/enc.sse_c | 32 ++-- .../tests/conformance/files.delete_version | 32 ++-- .../tests/conformance/files.download_by_id | 32 ++-- .../tests/conformance/files.download_content | 32 ++-- .sdkharness/tests/conformance/files.hide | 32 ++-- .sdkharness/tests/conformance/files.list | 32 ++-- .sdkharness/tests/conformance/files.metadata | 32 ++-- .../tests/conformance/files.server_side_copy | 34 ++-- .sdkharness/tests/conformance/files.upload | 38 ++-- .sdkharness/tests/conformance/keys.crud | 32 ++-- .../tests/conformance/keys.multi_bucket | 32 ++-- .../tests/conformance/large.compose_mixed | 32 ++-- .../tests/conformance/large.concurrent_parts | 32 ++-- .sdkharness/tests/conformance/large.multipart | 32 ++-- .../tests/conformance/large.parallel_download | 32 ++-- .sdkharness/tests/conformance/large.resume | 32 ++-- .../conformance/large.unbound_incremental | 32 ++-- .../tests/conformance/lock.bucket_default | 32 ++-- .../tests/conformance/lock.bypass_governance | 32 ++-- .sdkharness/tests/conformance/lock.legal_hold | 32 ++-- .../tests/conformance/lock.per_file_retention | 32 ++-- .../tests/conformance/urls.native_download | 42 +++-- .sdkharness/tests/health-golden-path | 4 + .sdkharness/tests/lib/contract.py | 14 +- .sdkharness/tests/lib/loopback_guard.py | 33 ++++ .sdkharness/tests/resilience/api.backoff_503 | 14 +- .../tests/resilience/api.retry_after_429 | 14 +- .../tests/resilience/api.retry_after_503 | 14 +- .../tests/resilience/auth.clock_expiry | 22 ++- .sdkharness/tests/resilience/auth.expired_401 | 14 +- .../tests/resilience/download.retry_503 | 14 +- .sdkharness/tests/resilience/part.retry_503 | 14 +- .../tests/resilience/upload.cap_exceeded_403 | 14 +- .../tests/resilience/upload.expired_token_401 | 14 +- .../tests/resilience/upload.get_url_503 | 14 +- .../resilience/upload.reset_before_response | 14 +- .../tests/resilience/upload.reset_mid_request | 14 +- .sdkharness/tests/resilience/upload.retry_408 | 14 +- .sdkharness/tests/resilience/upload.retry_500 | 14 +- .sdkharness/tests/resilience/upload.retry_503 | 14 +- .sdkharness/tests/resilience/upload.stall | 31 +-- ...sdkharness-fail-not-skip.infrastructure.md | 1 + test/unit/test_sdkharness_fail_not_skip.py | 176 ++++++++++++++++++ 55 files changed, 956 insertions(+), 632 deletions(-) create mode 100644 changelog.d/+sdkharness-fail-not-skip.infrastructure.md create mode 100644 test/unit/test_sdkharness_fail_not_skip.py diff --git a/.sdkharness/README.md b/.sdkharness/README.md index 0bfe3de13..00e0405a3 100644 --- a/.sdkharness/README.md +++ b/.sdkharness/README.md @@ -21,7 +21,9 @@ only the fixed simulator credential `test-key-id` / `test-key`, and the health check refuses any other `B2_TEST_APPLICATION_KEY*` pair before it reaches the SDK. The individual conformance and resilience check files refuse to run at all unless they are given a loopback simulator URL, so run them through the -dispatchers below, never with real `B2_*` values in the environment. +dispatchers below, never with real `B2_*` values in the environment. The +dispatchers also drop `HTTP_PROXY`, `HTTPS_PROXY`, `ALL_PROXY` (any case) and pin +`NO_PROXY` to `127.0.0.1`, so a proxy configured on the machine cannot change a result. Conformance owns 33 capability checks and resilience owns 16 injected-fault checks. Their small dispatchers validate the invocation, run the selected @@ -83,5 +85,12 @@ HEALTHCHECK_REALM_URL=$SDKHARNESS_SIMULATOR_URL B2_TEST_APPLICATION_KEY_ID=test- When you are done, stop the simulator with `kill "$SIM_PID"`. Each prints one `SDKHARNESS_RESULT` line. Scenario ids are in `tests.tsv`. -A `FAIL` for `api.retry_after_503`, `upload.retry_408` is a known SDK finding, not a setup problem. - +`api.retry_after_503` and `upload.retry_408` used to FAIL as known SDK findings; +both pass now, so there are no standing known findings listed here. `upload.stall` +reports `SKIP` because b2sdk documents no request-timeout option. A `FAIL` is a +real SDK or harness defect (or a simulator older than the checks expect), not a +setup problem. `SKIP` is reserved for a question that genuinely cannot be asked +(`no-realm-option`, `missing-runtime` when `b2sdk` is not installed at all, +`no-client-option`, `not-claimed`). An unreachable simulator, an authorization +error, an access-denied error, a connection error, or an SDK `ImportError` is +always a `FAIL`. diff --git a/.sdkharness/tests/conformance/bucket.cors b/.sdkharness/tests/conformance/bucket.cors index d370b27df..1b8b1a294 100755 --- a/.sdkharness/tests/conformance/bucket.cors +++ b/.sdkharness/tests/conformance/bucket.cors @@ -7,12 +7,12 @@ claims it): Action set a CORS rule set, then read it back Assert field-for-field equality - The card answers `partial` for this cell and states the boundary: CORS + The capability record answers `partial` for this cell and states the boundary: CORS round-trips as an UNTYPED dict with no typed model and no dedicated accessor, unlike lifecycle and notification rules. That boundary is the most falsifiable claim in the matrix, so it is asserted here too -- a typed CorsRule or a get/set_cors_rules accessor appearing upstream FAILS this - check, because the card would then be stale. + check, because the record would then be stale. EXPECTED VALUES -- B2's published contract, reviewed 2026-09-23. Every field sent here is a documented rule field (corsRuleName, allowedOrigins, @@ -24,13 +24,12 @@ b2_list_buckets returns corsRules. https://www.backblaze.com/docs/cloud-storage-cross-origin-resource-sharing-rules https://www.backblaze.com/apidocs/b2-update-bucket https://www.backblaze.com/apidocs/b2-list-buckets -The `partial` boundary leg tests the card's claim about b2sdk's own surface; +The `partial` boundary leg tests the capability's recorded claim about b2sdk's own surface; B2's docs do not speak to it. -Written from bin/conformance/b2-sdk-python/files.upload, the reference check, -and bin/conformance/README.md, the contract. It exercises b2sdk from this exact repository -checkout; the API was taken from -docs/sdks/b2-sdk-python/card.md and the published b2sdk docs; the assertion now lives with the SDK code it exercises. +Written from files.upload in this directory, the reference check. It exercises +b2sdk from this exact repository checkout; the API usage is taken from the +published b2sdk documentation. """ import os @@ -38,7 +37,7 @@ import sys import uuid sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'lib')) -from loopback_guard import refusal # noqa: E402 +from loopback_guard import missing_runtime, refusal # noqa: E402 SLUG = 'b2-sdk-python' CAPABILITY = 'bucket.cors' @@ -51,8 +50,10 @@ RULE = { 'maxAgeSeconds': 3600, } -# The closed reason set, mirrored from bin/conformance/README.md. The runner -# enforces it; naming one outside this tuple is a FAIL it manufactures. +# The closed reason set. `lib/contract.py` only turns `no-realm-option`, +# `missing-runtime` and `not-claimed` into a SKIP. `unreachable` and +# `unauthorized` are never reported at the simulator: the runner supplies both +# the server and the credential, so those are FAIL, not amber. REASONS = ( 'no-realm-option', 'unreachable', @@ -63,7 +64,7 @@ REASONS = ( ) # A requested target maps to a realm or to amber. `simulator` is the harness's -# own server (bin/simulator/serve.mjs), whose URL the runner exports as +# own loopback server, whose URL the dispatcher exports as # CONFORMANCE_SIMULATOR_URL; unset, there is nothing to reach: no-realm-option. REALMS = { 'simulator': os.environ.get('CONFORMANCE_SIMULATOR_URL') or None, @@ -92,7 +93,7 @@ class Amber(Exception): class Failure(Exception): - """A golden-path step that did not do what the card claims.""" + """A golden-path step that did not do what the capability requires.""" def __init__(self, step: str, detail: str) -> None: self.step = step @@ -116,8 +117,10 @@ def note(text: str) -> None: def step(name, action): """Run one golden-path step, converting the environment's own errors. - A credential NEVER reaches the detail: only the exception class name and, - for a classified network/auth error, the class that classified it. + A credential NEVER reaches the detail: only the exception class name. + Every error here is a FAIL: the runner supplies both the simulator and the + credential, so an auth error, access denied, connection error or SDK error + is a defect, never an amber (COULD-NOT-RUN) result. """ try: return action() @@ -125,10 +128,6 @@ def step(name, action): raise except Exception as error: # noqa: BLE001 -- classified below, never echoed name_of = type(error).__name__ - if name_of in ('Unauthorized', 'InvalidAuthToken', 'AccessDenied'): - raise Amber('unauthorized', f"{name_of} at step '{name}'") from error - if name_of in ('gaierror', 'ConnectionError', 'ServiceError', 'B2ConnectionError'): - raise Amber('unreachable', f"{name_of} at step '{name}'") from error raise Failure(name, name_of) from error @@ -173,6 +172,9 @@ def prepare(target): try: import b2sdk.v3 as b2 except ImportError as error: + if not missing_runtime(error): + # b2sdk is installed but broken: an SDK regression, not a missing runtime + raise Failure('import', type(error).__name__) from error raise Amber('missing-runtime', 'b2sdk is not installed') from error return b2, realm @@ -280,18 +282,18 @@ def run(target: str) -> None: if hasattr(b2, 'CorsRule'): raise Failure( 'boundary', - "b2sdk.v3 now exports a typed CorsRule; the card's `partial` answer is stale", + "b2sdk.v3 now exports a typed CorsRule; the capability's `partial` answer is stale", ) for accessor in ('get_cors_rules', 'set_cors_rules'): if hasattr(b2.Bucket, accessor): raise Failure( 'boundary', - f"Bucket.{accessor} now exists; the card's `partial` answer is stale", + f"Bucket.{accessor} now exists; the capability's `partial` answer is stale", ) if type(rule) is not dict: raise Failure( 'boundary', - f'the CORS rule is a {type(rule).__name__}, not the untyped dict the card records', + f'the CORS rule is a {type(rule).__name__}, not the untyped dict the record names', ) note('boundary held: CORS round-trips as a plain dict, with no typed model and no accessor') diff --git a/.sdkharness/tests/conformance/bucket.crud b/.sdkharness/tests/conformance/bucket.crud index de5cd1144..0a6874435 100755 --- a/.sdkharness/tests/conformance/bucket.crud +++ b/.sdkharness/tests/conformance/bucket.crud @@ -20,10 +20,9 @@ https://www.backblaze.com/apidocs/b2-update-bucket https://www.backblaze.com/apidocs/b2-delete-bucket https://www.backblaze.com/apidocs/b2-list-buckets -Written from bin/conformance/b2-sdk-python/files.upload, the reference check, -and bin/conformance/README.md, the contract. It exercises b2sdk from this exact repository -checkout; the API was taken from -docs/sdks/b2-sdk-python/card.md and the published b2sdk docs; the assertion now lives with the SDK code it exercises. +Written from files.upload in this directory, the reference check. It exercises +b2sdk from this exact repository checkout; the API usage is taken from the +published b2sdk documentation. """ import os @@ -31,13 +30,15 @@ import sys import uuid sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'lib')) -from loopback_guard import refusal # noqa: E402 +from loopback_guard import missing_runtime, refusal # noqa: E402 SLUG = 'b2-sdk-python' CAPABILITY = 'bucket.crud' -# The closed reason set, mirrored from bin/conformance/README.md. The runner -# enforces it; naming one outside this tuple is a FAIL it manufactures. +# The closed reason set. `lib/contract.py` only turns `no-realm-option`, +# `missing-runtime` and `not-claimed` into a SKIP. `unreachable` and +# `unauthorized` are never reported at the simulator: the runner supplies both +# the server and the credential, so those are FAIL, not amber. REASONS = ( 'no-realm-option', 'unreachable', @@ -48,7 +49,7 @@ REASONS = ( ) # A requested target maps to a realm or to amber. `simulator` is the harness's -# own server (bin/simulator/serve.mjs), whose URL the runner exports as +# own loopback server, whose URL the dispatcher exports as # CONFORMANCE_SIMULATOR_URL; unset, there is nothing to reach: no-realm-option. REALMS = { 'simulator': os.environ.get('CONFORMANCE_SIMULATOR_URL') or None, @@ -77,7 +78,7 @@ class Amber(Exception): class Failure(Exception): - """A golden-path step that did not do what the card claims.""" + """A golden-path step that did not do what the capability requires.""" def __init__(self, step: str, detail: str) -> None: self.step = step @@ -101,8 +102,10 @@ def note(text: str) -> None: def step(name, action): """Run one golden-path step, converting the environment's own errors. - A credential NEVER reaches the detail: only the exception class name and, - for a classified network/auth error, the class that classified it. + A credential NEVER reaches the detail: only the exception class name. + Every error here is a FAIL: the runner supplies both the simulator and the + credential, so an auth error, access denied, connection error or SDK error + is a defect, never an amber (COULD-NOT-RUN) result. """ try: return action() @@ -110,10 +113,6 @@ def step(name, action): raise except Exception as error: # noqa: BLE001 -- classified below, never echoed name_of = type(error).__name__ - if name_of in ('Unauthorized', 'InvalidAuthToken', 'AccessDenied'): - raise Amber('unauthorized', f"{name_of} at step '{name}'") from error - if name_of in ('gaierror', 'ConnectionError', 'ServiceError', 'B2ConnectionError'): - raise Amber('unreachable', f"{name_of} at step '{name}'") from error raise Failure(name, name_of) from error @@ -158,6 +157,9 @@ def prepare(target): try: import b2sdk.v3 as b2 except ImportError as error: + if not missing_runtime(error): + # b2sdk is installed but broken: an SDK regression, not a missing runtime + raise Failure('import', type(error).__name__) from error raise Amber('missing-runtime', 'b2sdk is not installed') from error return b2, realm diff --git a/.sdkharness/tests/conformance/bucket.lifecycle b/.sdkharness/tests/conformance/bucket.lifecycle index a8246e438..5013e4d7c 100755 --- a/.sdkharness/tests/conformance/bucket.lifecycle +++ b/.sdkharness/tests/conformance/bucket.lifecycle @@ -18,10 +18,9 @@ list." https://www.backblaze.com/docs/cloud-storage-lifecycle-rules https://www.backblaze.com/apidocs/b2-update-bucket -Written from bin/conformance/b2-sdk-python/files.upload, the reference check, -and bin/conformance/README.md, the contract. It exercises b2sdk from this exact repository -checkout; the API was taken from -docs/sdks/b2-sdk-python/card.md and the published b2sdk docs; the assertion now lives with the SDK code it exercises. +Written from files.upload in this directory, the reference check. It exercises +b2sdk from this exact repository checkout; the API usage is taken from the +published b2sdk documentation. """ import os @@ -29,15 +28,17 @@ import sys import uuid sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'lib')) -from loopback_guard import refusal # noqa: E402 +from loopback_guard import missing_runtime, refusal # noqa: E402 SLUG = 'b2-sdk-python' CAPABILITY = 'bucket.lifecycle' RULE = {'fileNamePrefix': 'st/', 'daysFromHidingToDeleting': 1} OTHER_FIELDS = ('daysFromUploadingToHiding', 'daysFromStartingToCancelingUnfinishedLargeFiles') -# The closed reason set, mirrored from bin/conformance/README.md. The runner -# enforces it; naming one outside this tuple is a FAIL it manufactures. +# The closed reason set. `lib/contract.py` only turns `no-realm-option`, +# `missing-runtime` and `not-claimed` into a SKIP. `unreachable` and +# `unauthorized` are never reported at the simulator: the runner supplies both +# the server and the credential, so those are FAIL, not amber. REASONS = ( 'no-realm-option', 'unreachable', @@ -48,7 +49,7 @@ REASONS = ( ) # A requested target maps to a realm or to amber. `simulator` is the harness's -# own server (bin/simulator/serve.mjs), whose URL the runner exports as +# own loopback server, whose URL the dispatcher exports as # CONFORMANCE_SIMULATOR_URL; unset, there is nothing to reach: no-realm-option. REALMS = { 'simulator': os.environ.get('CONFORMANCE_SIMULATOR_URL') or None, @@ -77,7 +78,7 @@ class Amber(Exception): class Failure(Exception): - """A golden-path step that did not do what the card claims.""" + """A golden-path step that did not do what the capability requires.""" def __init__(self, step: str, detail: str) -> None: self.step = step @@ -101,8 +102,10 @@ def note(text: str) -> None: def step(name, action): """Run one golden-path step, converting the environment's own errors. - A credential NEVER reaches the detail: only the exception class name and, - for a classified network/auth error, the class that classified it. + A credential NEVER reaches the detail: only the exception class name. + Every error here is a FAIL: the runner supplies both the simulator and the + credential, so an auth error, access denied, connection error or SDK error + is a defect, never an amber (COULD-NOT-RUN) result. """ try: return action() @@ -110,10 +113,6 @@ def step(name, action): raise except Exception as error: # noqa: BLE001 -- classified below, never echoed name_of = type(error).__name__ - if name_of in ('Unauthorized', 'InvalidAuthToken', 'AccessDenied'): - raise Amber('unauthorized', f"{name_of} at step '{name}'") from error - if name_of in ('gaierror', 'ConnectionError', 'ServiceError', 'B2ConnectionError'): - raise Amber('unreachable', f"{name_of} at step '{name}'") from error raise Failure(name, name_of) from error @@ -158,6 +157,9 @@ def prepare(target): try: import b2sdk.v3 as b2 except ImportError as error: + if not missing_runtime(error): + # b2sdk is installed but broken: an SDK regression, not a missing runtime + raise Failure('import', type(error).__name__) from error raise Amber('missing-runtime', 'b2sdk is not installed') from error return b2, realm diff --git a/.sdkharness/tests/conformance/bucket.notification_rules b/.sdkharness/tests/conformance/bucket.notification_rules index 62f690937..f0b2da921 100755 --- a/.sdkharness/tests/conformance/bucket.notification_rules +++ b/.sdkharness/tests/conformance/bucket.notification_rules @@ -16,10 +16,9 @@ https://www.backblaze.com/apidocs/b2-get-bucket-notification-rules The 2026-09-22 row asserted the secret is NOT echoed, which contradicts the docs. The secret is generated here and compared, never printed. -Written from bin/conformance/b2-sdk-python/files.upload, the reference check, -and bin/conformance/README.md, the contract. It exercises b2sdk from this exact repository -checkout; the API was taken from -docs/sdks/b2-sdk-python/card.md and the published b2sdk docs; the assertion now lives with the SDK code it exercises. +Written from files.upload in this directory, the reference check. It exercises +b2sdk from this exact repository checkout; the API usage is taken from the +published b2sdk documentation. """ import os @@ -29,7 +28,7 @@ import sys import uuid sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'lib')) -from loopback_guard import refusal # noqa: E402 +from loopback_guard import missing_runtime, refusal # noqa: E402 SLUG = 'b2-sdk-python' CAPABILITY = 'bucket.notification_rules' @@ -37,8 +36,10 @@ RULE_NAME = 'sdkharness-conf' EVENT_TYPES = ['b2:ObjectCreated:*'] WEBHOOK_URL = 'https://example.com/sdkharness-conf' -# The closed reason set, mirrored from bin/conformance/README.md. The runner -# enforces it; naming one outside this tuple is a FAIL it manufactures. +# The closed reason set. `lib/contract.py` only turns `no-realm-option`, +# `missing-runtime` and `not-claimed` into a SKIP. `unreachable` and +# `unauthorized` are never reported at the simulator: the runner supplies both +# the server and the credential, so those are FAIL, not amber. REASONS = ( 'no-realm-option', 'unreachable', @@ -49,7 +50,7 @@ REASONS = ( ) # A requested target maps to a realm or to amber. `simulator` is the harness's -# own server (bin/simulator/serve.mjs), whose URL the runner exports as +# own loopback server, whose URL the dispatcher exports as # CONFORMANCE_SIMULATOR_URL; unset, there is nothing to reach: no-realm-option. REALMS = { 'simulator': os.environ.get('CONFORMANCE_SIMULATOR_URL') or None, @@ -78,7 +79,7 @@ class Amber(Exception): class Failure(Exception): - """A golden-path step that did not do what the card claims.""" + """A golden-path step that did not do what the capability requires.""" def __init__(self, step: str, detail: str) -> None: self.step = step @@ -102,8 +103,10 @@ def note(text: str) -> None: def step(name, action): """Run one golden-path step, converting the environment's own errors. - A credential NEVER reaches the detail: only the exception class name and, - for a classified network/auth error, the class that classified it. + A credential NEVER reaches the detail: only the exception class name. + Every error here is a FAIL: the runner supplies both the simulator and the + credential, so an auth error, access denied, connection error or SDK error + is a defect, never an amber (COULD-NOT-RUN) result. """ try: return action() @@ -111,10 +114,6 @@ def step(name, action): raise except Exception as error: # noqa: BLE001 -- classified below, never echoed name_of = type(error).__name__ - if name_of in ('Unauthorized', 'InvalidAuthToken', 'AccessDenied'): - raise Amber('unauthorized', f"{name_of} at step '{name}'") from error - if name_of in ('gaierror', 'ConnectionError', 'ServiceError', 'B2ConnectionError'): - raise Amber('unreachable', f"{name_of} at step '{name}'") from error raise Failure(name, name_of) from error @@ -159,6 +158,9 @@ def prepare(target): try: import b2sdk.v3 as b2 except ImportError as error: + if not missing_runtime(error): + # b2sdk is installed but broken: an SDK regression, not a missing runtime + raise Failure('import', type(error).__name__) from error raise Amber('missing-runtime', 'b2sdk is not installed') from error return b2, realm diff --git a/.sdkharness/tests/conformance/bucket.replication_config b/.sdkharness/tests/conformance/bucket.replication_config index 5d5d95c89..19d7d0093 100755 --- a/.sdkharness/tests/conformance/bucket.replication_config +++ b/.sdkharness/tests/conformance/bucket.replication_config @@ -18,10 +18,9 @@ rules associated with one or more buckets." https://www.backblaze.com/apidocs/b2-update-bucket https://www.backblaze.com/docs/cloud-storage-create-a-cloud-replication-rule-with-the-native-api -Written from bin/conformance/b2-sdk-python/files.upload, the reference check, -and bin/conformance/README.md, the contract. It exercises b2sdk from this exact repository -checkout; the API was taken from -docs/sdks/b2-sdk-python/card.md and the published b2sdk docs; the assertion now lives with the SDK code it exercises. +Written from files.upload in this directory, the reference check. It exercises +b2sdk from this exact repository checkout; the API usage is taken from the +published b2sdk documentation. """ import os @@ -29,7 +28,7 @@ import sys import uuid sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'lib')) -from loopback_guard import refusal # noqa: E402 +from loopback_guard import missing_runtime, refusal # noqa: E402 SLUG = 'b2-sdk-python' CAPABILITY = 'bucket.replication_config' @@ -48,8 +47,10 @@ SOURCE_CAPABILITIES = [ 'writeBucketReplications', ] -# The closed reason set, mirrored from bin/conformance/README.md. The runner -# enforces it; naming one outside this tuple is a FAIL it manufactures. +# The closed reason set. `lib/contract.py` only turns `no-realm-option`, +# `missing-runtime` and `not-claimed` into a SKIP. `unreachable` and +# `unauthorized` are never reported at the simulator: the runner supplies both +# the server and the credential, so those are FAIL, not amber. REASONS = ( 'no-realm-option', 'unreachable', @@ -60,7 +61,7 @@ REASONS = ( ) # A requested target maps to a realm or to amber. `simulator` is the harness's -# own server (bin/simulator/serve.mjs), whose URL the runner exports as +# own loopback server, whose URL the dispatcher exports as # CONFORMANCE_SIMULATOR_URL; unset, there is nothing to reach: no-realm-option. REALMS = { 'simulator': os.environ.get('CONFORMANCE_SIMULATOR_URL') or None, @@ -89,7 +90,7 @@ class Amber(Exception): class Failure(Exception): - """A golden-path step that did not do what the card claims.""" + """A golden-path step that did not do what the capability requires.""" def __init__(self, step: str, detail: str) -> None: self.step = step @@ -113,8 +114,10 @@ def note(text: str) -> None: def step(name, action): """Run one golden-path step, converting the environment's own errors. - A credential NEVER reaches the detail: only the exception class name and, - for a classified network/auth error, the class that classified it. + A credential NEVER reaches the detail: only the exception class name. + Every error here is a FAIL: the runner supplies both the simulator and the + credential, so an auth error, access denied, connection error or SDK error + is a defect, never an amber (COULD-NOT-RUN) result. """ try: return action() @@ -122,10 +125,6 @@ def step(name, action): raise except Exception as error: # noqa: BLE001 -- classified below, never echoed name_of = type(error).__name__ - if name_of in ('Unauthorized', 'InvalidAuthToken', 'AccessDenied'): - raise Amber('unauthorized', f"{name_of} at step '{name}'") from error - if name_of in ('gaierror', 'ConnectionError', 'ServiceError', 'B2ConnectionError'): - raise Amber('unreachable', f"{name_of} at step '{name}'") from error raise Failure(name, name_of) from error @@ -170,6 +169,9 @@ def prepare(target): try: import b2sdk.v3 as b2 except ImportError as error: + if not missing_runtime(error): + # b2sdk is installed but broken: an SDK regression, not a missing runtime + raise Failure('import', type(error).__name__) from error raise Amber('missing-runtime', 'b2sdk is not installed') from error return b2, realm diff --git a/.sdkharness/tests/conformance/bucket.replication_helper b/.sdkharness/tests/conformance/bucket.replication_helper index 34483db07..ddb9a6908 100755 --- a/.sdkharness/tests/conformance/bucket.replication_helper +++ b/.sdkharness/tests/conformance/bucket.replication_helper @@ -22,10 +22,9 @@ ReplicationMonitor entry; counter_by_status appears only under b2sdk._internal search for the helper names. So "the status reports the expected counts" has no documented expected value; it is asserted only as at least one file counted. -Written from bin/conformance/b2-sdk-python/files.upload, the reference check, -and bin/conformance/README.md, the contract. It exercises b2sdk from this exact repository -checkout; the API was taken from -docs/sdks/b2-sdk-python/card.md and the published b2sdk docs; the assertion now lives with the SDK code it exercises. +Written from files.upload in this directory, the reference check. It exercises +b2sdk from this exact repository checkout; the API usage is taken from the +published b2sdk documentation. """ import io @@ -34,7 +33,7 @@ import sys import uuid sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'lib')) -from loopback_guard import refusal # noqa: E402 +from loopback_guard import missing_runtime, refusal # noqa: E402 SLUG = 'b2-sdk-python' CAPABILITY = 'bucket.replication_helper' @@ -43,8 +42,10 @@ PREFIX = 'st/' OBJECT_NAME = 'st/replicated.txt' PAYLOAD_SIZE = 256 -# The closed reason set, mirrored from bin/conformance/README.md. The runner -# enforces it; naming one outside this tuple is a FAIL it manufactures. +# The closed reason set. `lib/contract.py` only turns `no-realm-option`, +# `missing-runtime` and `not-claimed` into a SKIP. `unreachable` and +# `unauthorized` are never reported at the simulator: the runner supplies both +# the server and the credential, so those are FAIL, not amber. REASONS = ( 'no-realm-option', 'unreachable', @@ -55,7 +56,7 @@ REASONS = ( ) # A requested target maps to a realm or to amber. `simulator` is the harness's -# own server (bin/simulator/serve.mjs), whose URL the runner exports as +# own loopback server, whose URL the dispatcher exports as # CONFORMANCE_SIMULATOR_URL; unset, there is nothing to reach: no-realm-option. REALMS = { 'simulator': os.environ.get('CONFORMANCE_SIMULATOR_URL') or None, @@ -84,7 +85,7 @@ class Amber(Exception): class Failure(Exception): - """A golden-path step that did not do what the card claims.""" + """A golden-path step that did not do what the capability requires.""" def __init__(self, step: str, detail: str) -> None: self.step = step @@ -108,8 +109,10 @@ def note(text: str) -> None: def step(name, action): """Run one golden-path step, converting the environment's own errors. - A credential NEVER reaches the detail: only the exception class name and, - for a classified network/auth error, the class that classified it. + A credential NEVER reaches the detail: only the exception class name. + Every error here is a FAIL: the runner supplies both the simulator and the + credential, so an auth error, access denied, connection error or SDK error + is a defect, never an amber (COULD-NOT-RUN) result. """ try: return action() @@ -117,10 +120,6 @@ def step(name, action): raise except Exception as error: # noqa: BLE001 -- classified below, never echoed name_of = type(error).__name__ - if name_of in ('Unauthorized', 'InvalidAuthToken', 'AccessDenied'): - raise Amber('unauthorized', f"{name_of} at step '{name}'") from error - if name_of in ('gaierror', 'ConnectionError', 'ServiceError', 'B2ConnectionError'): - raise Amber('unreachable', f"{name_of} at step '{name}'") from error raise Failure(name, name_of) from error @@ -165,6 +164,9 @@ def prepare(target): try: import b2sdk.v3 as b2 except ImportError as error: + if not missing_runtime(error): + # b2sdk is installed but broken: an SDK regression, not a missing runtime + raise Failure('import', type(error).__name__) from error raise Amber('missing-runtime', 'b2sdk is not installed') from error return b2, realm diff --git a/.sdkharness/tests/conformance/client.auth_persistence b/.sdkharness/tests/conformance/client.auth_persistence index 46fb5b40b..65e835c60 100755 --- a/.sdkharness/tests/conformance/client.auth_persistence +++ b/.sdkharness/tests/conformance/client.auth_persistence @@ -21,10 +21,9 @@ cache. The nearest documented fact bounds, but does not promise, the reuse: b2_authorize_account's token "is valid for at most 24 hours." https://www.backblaze.com/apidocs/b2-authorize-account -Written from bin/conformance/b2-sdk-python/files.upload, the reference check, -and bin/conformance/README.md, the contract. It exercises b2sdk from this exact repository -checkout; the API was taken from -docs/sdks/b2-sdk-python/card.md and the published b2sdk docs; the assertion now lives with the SDK code it exercises. +Written from files.upload in this directory, the reference check. It exercises +b2sdk from this exact repository checkout; the API usage is taken from the +published b2sdk documentation. """ import os @@ -35,13 +34,15 @@ import tempfile import uuid sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'lib')) -from loopback_guard import refusal # noqa: E402 +from loopback_guard import missing_runtime, refusal # noqa: E402 SLUG = 'b2-sdk-python' CAPABILITY = 'client.auth_persistence' -# The closed reason set, mirrored from bin/conformance/README.md. The runner -# enforces it; naming one outside this tuple is a FAIL it manufactures. +# The closed reason set. `lib/contract.py` only turns `no-realm-option`, +# `missing-runtime` and `not-claimed` into a SKIP. `unreachable` and +# `unauthorized` are never reported at the simulator: the runner supplies both +# the server and the credential, so those are FAIL, not amber. REASONS = ( 'no-realm-option', 'unreachable', @@ -52,7 +53,7 @@ REASONS = ( ) # A requested target maps to a realm or to amber. `simulator` is the harness's -# own server (bin/simulator/serve.mjs), whose URL the runner exports as +# own loopback server, whose URL the dispatcher exports as # CONFORMANCE_SIMULATOR_URL; unset, there is nothing to reach: no-realm-option. REALMS = { 'simulator': os.environ.get('CONFORMANCE_SIMULATOR_URL') or None, @@ -81,7 +82,7 @@ class Amber(Exception): class Failure(Exception): - """A golden-path step that did not do what the card claims.""" + """A golden-path step that did not do what the capability requires.""" def __init__(self, step: str, detail: str) -> None: self.step = step @@ -105,8 +106,10 @@ def note(text: str) -> None: def step(name, action): """Run one golden-path step, converting the environment's own errors. - A credential NEVER reaches the detail: only the exception class name and, - for a classified network/auth error, the class that classified it. + A credential NEVER reaches the detail: only the exception class name. + Every error here is a FAIL: the runner supplies both the simulator and the + credential, so an auth error, access denied, connection error or SDK error + is a defect, never an amber (COULD-NOT-RUN) result. """ try: return action() @@ -114,10 +117,6 @@ def step(name, action): raise except Exception as error: # noqa: BLE001 -- classified below, never echoed name_of = type(error).__name__ - if name_of in ('Unauthorized', 'InvalidAuthToken', 'AccessDenied'): - raise Amber('unauthorized', f"{name_of} at step '{name}'") from error - if name_of in ('gaierror', 'ConnectionError', 'ServiceError', 'B2ConnectionError'): - raise Amber('unreachable', f"{name_of} at step '{name}'") from error raise Failure(name, name_of) from error @@ -162,6 +161,9 @@ def prepare(target): try: import b2sdk.v3 as b2 except ImportError as error: + if not missing_runtime(error): + # b2sdk is installed but broken: an SDK regression, not a missing runtime + raise Failure('import', type(error).__name__) from error raise Amber('missing-runtime', 'b2sdk is not installed') from error return b2, realm @@ -304,18 +306,6 @@ def run(target: str) -> None: if marker.startswith('CHILD error '): failed_with = marker[len('CHILD error ') :].strip() - if failed_with in ('Unauthorized', 'InvalidAuthToken', 'AccessDenied'): - raise Amber('unauthorized', f'{failed_with} in process 2') - if failed_with in ( - 'gaierror', - 'ConnectionError', - 'ServiceError', - 'B2ConnectionError', - 'UnknownHost', - ): - raise Amber('unreachable', f'{failed_with} in process 2') - if failed_with in ('ImportError', 'ModuleNotFoundError'): - raise Amber('missing-runtime', 'b2sdk is not installed for the second process') raise Failure('process 2', f'the second process failed with {failed_with}') fields = dict(part.split('=', 1) for part in marker.split() if '=' in part) diff --git a/.sdkharness/tests/conformance/client.progress b/.sdkharness/tests/conformance/client.progress index 8c39d3359..b085a0745 100755 --- a/.sdkharness/tests/conformance/client.progress +++ b/.sdkharness/tests/conformance/client.progress @@ -18,10 +18,9 @@ Progress reporting is client-side ergonomics; the B2 API has no progress surface, so the expected values (fires, non-decreasing, ends at the byte count) come from the scenario, not a Backblaze doc. -Written from bin/conformance/b2-sdk-python/files.upload, the reference check, -and bin/conformance/README.md, the contract. It exercises b2sdk from this exact repository -checkout; the API was taken from -docs/sdks/b2-sdk-python/card.md and the published b2sdk docs; the assertion now lives with the SDK code it exercises. +Written from files.upload in this directory, the reference check. It exercises +b2sdk from this exact repository checkout; the API usage is taken from the +published b2sdk documentation. """ import os @@ -30,15 +29,17 @@ import threading import uuid sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'lib')) -from loopback_guard import refusal # noqa: E402 +from loopback_guard import missing_runtime, refusal # noqa: E402 SLUG = 'b2-sdk-python' CAPABILITY = 'client.progress' OBJECT_NAME = 'st/progress.bin' PARTS_WANTED = 3 -# The closed reason set, mirrored from bin/conformance/README.md. The runner -# enforces it; naming one outside this tuple is a FAIL it manufactures. +# The closed reason set. `lib/contract.py` only turns `no-realm-option`, +# `missing-runtime` and `not-claimed` into a SKIP. `unreachable` and +# `unauthorized` are never reported at the simulator: the runner supplies both +# the server and the credential, so those are FAIL, not amber. REASONS = ( 'no-realm-option', 'unreachable', @@ -49,7 +50,7 @@ REASONS = ( ) # A requested target maps to a realm or to amber. `simulator` is the harness's -# own server (bin/simulator/serve.mjs), whose URL the runner exports as +# own loopback server, whose URL the dispatcher exports as # CONFORMANCE_SIMULATOR_URL; unset, there is nothing to reach: no-realm-option. REALMS = { 'simulator': os.environ.get('CONFORMANCE_SIMULATOR_URL') or None, @@ -78,7 +79,7 @@ class Amber(Exception): class Failure(Exception): - """A golden-path step that did not do what the card claims.""" + """A golden-path step that did not do what the capability requires.""" def __init__(self, step: str, detail: str) -> None: self.step = step @@ -102,8 +103,10 @@ def note(text: str) -> None: def step(name, action): """Run one golden-path step, converting the environment's own errors. - A credential NEVER reaches the detail: only the exception class name and, - for a classified network/auth error, the class that classified it. + A credential NEVER reaches the detail: only the exception class name. + Every error here is a FAIL: the runner supplies both the simulator and the + credential, so an auth error, access denied, connection error or SDK error + is a defect, never an amber (COULD-NOT-RUN) result. """ try: return action() @@ -111,10 +114,6 @@ def step(name, action): raise except Exception as error: # noqa: BLE001 -- classified below, never echoed name_of = type(error).__name__ - if name_of in ('Unauthorized', 'InvalidAuthToken', 'AccessDenied'): - raise Amber('unauthorized', f"{name_of} at step '{name}'") from error - if name_of in ('gaierror', 'ConnectionError', 'ServiceError', 'B2ConnectionError'): - raise Amber('unreachable', f"{name_of} at step '{name}'") from error raise Failure(name, name_of) from error @@ -159,6 +158,9 @@ def prepare(target): try: import b2sdk.v3 as b2 except ImportError as error: + if not missing_runtime(error): + # b2sdk is installed but broken: an SDK regression, not a missing runtime + raise Failure('import', type(error).__name__) from error raise Amber('missing-runtime', 'b2sdk is not installed') from error return b2, realm diff --git a/.sdkharness/tests/conformance/client.simulator b/.sdkharness/tests/conformance/client.simulator index 1936bfa18..6c15a402d 100755 --- a/.sdkharness/tests/conformance/client.simulator +++ b/.sdkharness/tests/conformance/client.simulator @@ -20,10 +20,9 @@ Shipping an in-process fake is packaging; no Backblaze doc page covers it. The fake models the same endpoints the API docs describe, but that is the tool's claim, so a PASS here says the tool and its own fake agree, nothing about B2. -Written from bin/conformance/b2-sdk-python/files.upload, the reference check, -and bin/conformance/README.md, the contract. It exercises b2sdk from this exact repository -checkout; the API was taken from -docs/sdks/b2-sdk-python/card.md and the published b2sdk docs; the assertion now lives with the SDK code it exercises. +Written from files.upload in this directory, the reference check. It exercises +b2sdk from this exact repository checkout; the API usage is taken from the +published b2sdk documentation. """ import io @@ -33,15 +32,17 @@ import sys import uuid sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'lib')) -from loopback_guard import refusal # noqa: E402 +from loopback_guard import missing_runtime, refusal # noqa: E402 SLUG = 'b2-sdk-python' CAPABILITY = 'client.simulator' OBJECT_NAME = 'st/simulator.txt' PAYLOAD_SIZE = 1024 -# The closed reason set, mirrored from bin/conformance/README.md. The runner -# enforces it; naming one outside this tuple is a FAIL it manufactures. +# The closed reason set. `lib/contract.py` only turns `no-realm-option`, +# `missing-runtime` and `not-claimed` into a SKIP. `unreachable` and +# `unauthorized` are never reported at the simulator: the runner supplies both +# the server and the credential, so those are FAIL, not amber. REASONS = ( 'no-realm-option', 'unreachable', @@ -65,7 +66,7 @@ class Amber(Exception): class Failure(Exception): - """A golden-path step that did not do what the card claims.""" + """A golden-path step that did not do what the capability requires.""" def __init__(self, step: str, detail: str) -> None: self.step = step @@ -89,8 +90,10 @@ def note(text: str) -> None: def step(name, action): """Run one golden-path step, converting the environment's own errors. - A credential NEVER reaches the detail: only the exception class name and, - for a classified network/auth error, the class that classified it. + A credential NEVER reaches the detail: only the exception class name. + Every error here is a FAIL: the runner supplies both the simulator and the + credential, so an auth error, access denied, connection error or SDK error + is a defect, never an amber (COULD-NOT-RUN) result. """ try: return action() @@ -98,10 +101,6 @@ def step(name, action): raise except Exception as error: # noqa: BLE001 -- classified below, never echoed name_of = type(error).__name__ - if name_of in ('Unauthorized', 'InvalidAuthToken', 'AccessDenied'): - raise Amber('unauthorized', f"{name_of} at step '{name}'") from error - if name_of in ('gaierror', 'ConnectionError', 'ServiceError', 'B2ConnectionError'): - raise Amber('unreachable', f"{name_of} at step '{name}'") from error raise Failure(name, name_of) from error @@ -197,6 +196,9 @@ def run(target: str) -> None: try: import b2sdk.v3 as b2 except ImportError as error: + if not missing_runtime(error): + # b2sdk is installed but broken: an SDK regression, not a missing runtime + raise Failure('import', type(error).__name__) from error raise Amber('missing-runtime', 'b2sdk is not installed') from error if not hasattr(b2, 'RawSimulator'): diff --git a/.sdkharness/tests/conformance/client.sync b/.sdkharness/tests/conformance/client.sync index 126049e97..8032ff5ea 100755 --- a/.sdkharness/tests/conformance/client.sync +++ b/.sdkharness/tests/conformance/client.sync @@ -26,10 +26,9 @@ https://www.backblaze.com/apidocs/b2-delete-file-version Which of hide/delete a delete policy issues, and the compare rule that decides a file changed, are the tool's semantics, not B2's. -Written from bin/conformance/b2-sdk-python/files.upload, the reference check, -and bin/conformance/README.md, the contract. It exercises b2sdk from this exact repository -checkout; the API was taken from -docs/sdks/b2-sdk-python/card.md and the published b2sdk docs; the assertion now lives with the SDK code it exercises. +Written from files.upload in this directory, the reference check. It exercises +b2sdk from this exact repository checkout; the API usage is taken from the +published b2sdk documentation. """ import io @@ -41,15 +40,17 @@ import time import uuid sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'lib')) -from loopback_guard import refusal # noqa: E402 +from loopback_guard import missing_runtime, refusal # noqa: E402 SLUG = 'b2-sdk-python' CAPABILITY = 'client.sync' REMOTE_PREFIX = 'st/sync' FILES = ('a.txt', 'b.txt', 'c.txt') -# The closed reason set, mirrored from bin/conformance/README.md. The runner -# enforces it; naming one outside this tuple is a FAIL it manufactures. +# The closed reason set. `lib/contract.py` only turns `no-realm-option`, +# `missing-runtime` and `not-claimed` into a SKIP. `unreachable` and +# `unauthorized` are never reported at the simulator: the runner supplies both +# the server and the credential, so those are FAIL, not amber. REASONS = ( 'no-realm-option', 'unreachable', @@ -60,7 +61,7 @@ REASONS = ( ) # A requested target maps to a realm or to amber. `simulator` is the harness's -# own server (bin/simulator/serve.mjs), whose URL the runner exports as +# own loopback server, whose URL the dispatcher exports as # CONFORMANCE_SIMULATOR_URL; unset, there is nothing to reach: no-realm-option. REALMS = { 'simulator': os.environ.get('CONFORMANCE_SIMULATOR_URL') or None, @@ -89,7 +90,7 @@ class Amber(Exception): class Failure(Exception): - """A golden-path step that did not do what the card claims.""" + """A golden-path step that did not do what the capability requires.""" def __init__(self, step: str, detail: str) -> None: self.step = step @@ -113,8 +114,10 @@ def note(text: str) -> None: def step(name, action): """Run one golden-path step, converting the environment's own errors. - A credential NEVER reaches the detail: only the exception class name and, - for a classified network/auth error, the class that classified it. + A credential NEVER reaches the detail: only the exception class name. + Every error here is a FAIL: the runner supplies both the simulator and the + credential, so an auth error, access denied, connection error or SDK error + is a defect, never an amber (COULD-NOT-RUN) result. """ try: return action() @@ -122,10 +125,6 @@ def step(name, action): raise except Exception as error: # noqa: BLE001 -- classified below, never echoed name_of = type(error).__name__ - if name_of in ('Unauthorized', 'InvalidAuthToken', 'AccessDenied'): - raise Amber('unauthorized', f"{name_of} at step '{name}'") from error - if name_of in ('gaierror', 'ConnectionError', 'ServiceError', 'B2ConnectionError'): - raise Amber('unreachable', f"{name_of} at step '{name}'") from error raise Failure(name, name_of) from error @@ -170,6 +169,9 @@ def prepare(target): try: import b2sdk.v3 as b2 except ImportError as error: + if not missing_runtime(error): + # b2sdk is installed but broken: an SDK regression, not a missing runtime + raise Failure('import', type(error).__name__) from error raise Amber('missing-runtime', 'b2sdk is not installed') from error return b2, realm diff --git a/.sdkharness/tests/conformance/enc.sse_b2 b/.sdkharness/tests/conformance/enc.sse_b2 index 8450614a4..92341bba7 100755 --- a/.sdkharness/tests/conformance/enc.sse_b2 +++ b/.sdkharness/tests/conformance/enc.sse_b2 @@ -24,10 +24,9 @@ for new files uploaded to this bucket", example {"mode": "SSE-B2", "algorithm": "AES256"}: https://www.backblaze.com/apidocs/b2-create-bucket -Written from bin/conformance/b2-sdk-python/files.upload, the reference check, -and bin/conformance/README.md, the contract. It exercises b2sdk from this exact repository -checkout; the API was taken from -docs/sdks/b2-sdk-python/card.md and the published b2sdk docs; the assertion now lives with the SDK code it exercises. +Written from files.upload in this directory, the reference check. It exercises +b2sdk from this exact repository checkout; the API usage is taken from the +published b2sdk documentation. """ import hashlib @@ -37,15 +36,17 @@ import sys import uuid sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'lib')) -from loopback_guard import refusal # noqa: E402 +from loopback_guard import missing_runtime, refusal # noqa: E402 SLUG = 'b2-sdk-python' CAPABILITY = 'enc.sse_b2' OBJECT_NAME = 'st/sse-b2.txt' PAYLOAD_SIZE = 1024 -# The closed reason set, mirrored from bin/conformance/README.md. The runner -# enforces it; naming one outside this tuple is a FAIL it manufactures. +# The closed reason set. `lib/contract.py` only turns `no-realm-option`, +# `missing-runtime` and `not-claimed` into a SKIP. `unreachable` and +# `unauthorized` are never reported at the simulator: the runner supplies both +# the server and the credential, so those are FAIL, not amber. REASONS = ( 'no-realm-option', 'unreachable', @@ -56,7 +57,7 @@ REASONS = ( ) # A requested target maps to a realm or to amber. `simulator` is the harness's -# own server (bin/simulator/serve.mjs), whose URL the runner exports as +# own loopback server, whose URL the dispatcher exports as # CONFORMANCE_SIMULATOR_URL; unset, there is nothing to reach: no-realm-option. REALMS = { 'simulator': os.environ.get('CONFORMANCE_SIMULATOR_URL') or None, @@ -85,7 +86,7 @@ class Amber(Exception): class Failure(Exception): - """A golden-path step that did not do what the card claims.""" + """A golden-path step that did not do what the capability requires.""" def __init__(self, step: str, detail: str) -> None: self.step = step @@ -109,8 +110,10 @@ def note(text: str) -> None: def step(name, action): """Run one golden-path step, converting the environment's own errors. - A credential NEVER reaches the detail: only the exception class name and, - for a classified network/auth error, the class that classified it. + A credential NEVER reaches the detail: only the exception class name. + Every error here is a FAIL: the runner supplies both the simulator and the + credential, so an auth error, access denied, connection error or SDK error + is a defect, never an amber (COULD-NOT-RUN) result. """ try: return action() @@ -118,10 +121,6 @@ def step(name, action): raise except Exception as error: # noqa: BLE001 -- classified below, never echoed name_of = type(error).__name__ - if name_of in ('Unauthorized', 'InvalidAuthToken', 'AccessDenied'): - raise Amber('unauthorized', f"{name_of} at step '{name}'") from error - if name_of in ('gaierror', 'ConnectionError', 'ServiceError', 'B2ConnectionError'): - raise Amber('unreachable', f"{name_of} at step '{name}'") from error raise Failure(name, name_of) from error @@ -166,6 +165,9 @@ def prepare(target): try: import b2sdk.v3 as b2 except ImportError as error: + if not missing_runtime(error): + # b2sdk is installed but broken: an SDK regression, not a missing runtime + raise Failure('import', type(error).__name__) from error raise Amber('missing-runtime', 'b2sdk is not installed') from error return b2, realm diff --git a/.sdkharness/tests/conformance/enc.sse_c b/.sdkharness/tests/conformance/enc.sse_c index faf10bf32..6b0e23a0e 100755 --- a/.sdkharness/tests/conformance/enc.sse_c +++ b/.sdkharness/tests/conformance/enc.sse_c @@ -41,10 +41,9 @@ cloud-storage-enable-server-side-encryption-with-the-native-api. The `sse_c_key_id` fileInfo entry is a b2sdk / CLI convention, not a B2 promise; the identity B2 documents is the key md5 on the download response (above). -Written from bin/conformance/b2-sdk-python/files.upload, the reference check, -and bin/conformance/README.md, the contract. It exercises b2sdk from this exact repository -checkout; the API was taken from -docs/sdks/b2-sdk-python/card.md and the published b2sdk docs; the assertion now lives with the SDK code it exercises. +Written from files.upload in this directory, the reference check. It exercises +b2sdk from this exact repository checkout; the API usage is taken from the +published b2sdk documentation. """ import base64 @@ -55,7 +54,7 @@ import sys import uuid sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'lib')) -from loopback_guard import refusal # noqa: E402 +from loopback_guard import missing_runtime, refusal # noqa: E402 SLUG = 'b2-sdk-python' CAPABILITY = 'enc.sse_c' @@ -63,8 +62,10 @@ OBJECT_NAME = 'st/sse-c.txt' PAYLOAD_SIZE = 1024 KEY_ID = 'sdkharness-conf' -# The closed reason set, mirrored from bin/conformance/README.md. The runner -# enforces it; naming one outside this tuple is a FAIL it manufactures. +# The closed reason set. `lib/contract.py` only turns `no-realm-option`, +# `missing-runtime` and `not-claimed` into a SKIP. `unreachable` and +# `unauthorized` are never reported at the simulator: the runner supplies both +# the server and the credential, so those are FAIL, not amber. REASONS = ( 'no-realm-option', 'unreachable', @@ -75,7 +76,7 @@ REASONS = ( ) # A requested target maps to a realm or to amber. `simulator` is the harness's -# own server (bin/simulator/serve.mjs), whose URL the runner exports as +# own loopback server, whose URL the dispatcher exports as # CONFORMANCE_SIMULATOR_URL; unset, there is nothing to reach: no-realm-option. REALMS = { 'simulator': os.environ.get('CONFORMANCE_SIMULATOR_URL') or None, @@ -104,7 +105,7 @@ class Amber(Exception): class Failure(Exception): - """A golden-path step that did not do what the card claims.""" + """A golden-path step that did not do what the capability requires.""" def __init__(self, step: str, detail: str) -> None: self.step = step @@ -128,8 +129,10 @@ def note(text: str) -> None: def step(name, action): """Run one golden-path step, converting the environment's own errors. - A credential NEVER reaches the detail: only the exception class name and, - for a classified network/auth error, the class that classified it. + A credential NEVER reaches the detail: only the exception class name. + Every error here is a FAIL: the runner supplies both the simulator and the + credential, so an auth error, access denied, connection error or SDK error + is a defect, never an amber (COULD-NOT-RUN) result. """ try: return action() @@ -137,10 +140,6 @@ def step(name, action): raise except Exception as error: # noqa: BLE001 -- classified below, never echoed name_of = type(error).__name__ - if name_of in ('Unauthorized', 'InvalidAuthToken', 'AccessDenied'): - raise Amber('unauthorized', f"{name_of} at step '{name}'") from error - if name_of in ('gaierror', 'ConnectionError', 'ServiceError', 'B2ConnectionError'): - raise Amber('unreachable', f"{name_of} at step '{name}'") from error raise Failure(name, name_of) from error @@ -185,6 +184,9 @@ def prepare(target): try: import b2sdk.v3 as b2 except ImportError as error: + if not missing_runtime(error): + # b2sdk is installed but broken: an SDK regression, not a missing runtime + raise Failure('import', type(error).__name__) from error raise Amber('missing-runtime', 'b2sdk is not installed') from error return b2, realm diff --git a/.sdkharness/tests/conformance/files.delete_version b/.sdkharness/tests/conformance/files.delete_version index 17a9f536c..73d2313c7 100755 --- a/.sdkharness/tests/conformance/files.delete_version +++ b/.sdkharness/tests/conformance/files.delete_version @@ -16,10 +16,9 @@ will become the current version, and be the one that you'll get when downloading by name." https://www.backblaze.com/apidocs/b2-delete-file-version -Written from bin/conformance/b2-sdk-python/files.upload, the reference check, -and bin/conformance/README.md, the contract. It exercises b2sdk from this exact repository -checkout; the API was taken from -docs/sdks/b2-sdk-python/card.md and the published b2sdk docs; the assertion now lives with the SDK code it exercises. +Written from files.upload in this directory, the reference check. It exercises +b2sdk from this exact repository checkout; the API usage is taken from the +published b2sdk documentation. """ import io @@ -28,7 +27,7 @@ import sys import uuid sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'lib')) -from loopback_guard import refusal # noqa: E402 +from loopback_guard import missing_runtime, refusal # noqa: E402 SLUG = 'b2-sdk-python' CAPABILITY = 'files.delete_version' @@ -36,8 +35,10 @@ PREFIX = 'st/' OBJECT_NAME = 'st/delete-version.txt' PAYLOAD_SIZE = 1024 -# The closed reason set, mirrored from bin/conformance/README.md. The runner -# enforces it; naming one outside this tuple is a FAIL it manufactures. +# The closed reason set. `lib/contract.py` only turns `no-realm-option`, +# `missing-runtime` and `not-claimed` into a SKIP. `unreachable` and +# `unauthorized` are never reported at the simulator: the runner supplies both +# the server and the credential, so those are FAIL, not amber. REASONS = ( 'no-realm-option', 'unreachable', @@ -48,7 +49,7 @@ REASONS = ( ) # A requested target maps to a realm or to amber. `simulator` is the harness's -# own server (bin/simulator/serve.mjs), whose URL the runner exports as +# own loopback server, whose URL the dispatcher exports as # CONFORMANCE_SIMULATOR_URL; unset, there is nothing to reach: no-realm-option. REALMS = { 'simulator': os.environ.get('CONFORMANCE_SIMULATOR_URL') or None, @@ -77,7 +78,7 @@ class Amber(Exception): class Failure(Exception): - """A golden-path step that did not do what the card claims.""" + """A golden-path step that did not do what the capability requires.""" def __init__(self, step: str, detail: str) -> None: self.step = step @@ -101,8 +102,10 @@ def note(text: str) -> None: def step(name, action): """Run one golden-path step, converting the environment's own errors. - A credential NEVER reaches the detail: only the exception class name and, - for a classified network/auth error, the class that classified it. + A credential NEVER reaches the detail: only the exception class name. + Every error here is a FAIL: the runner supplies both the simulator and the + credential, so an auth error, access denied, connection error or SDK error + is a defect, never an amber (COULD-NOT-RUN) result. """ try: return action() @@ -110,10 +113,6 @@ def step(name, action): raise except Exception as error: # noqa: BLE001 -- classified below, never echoed name_of = type(error).__name__ - if name_of in ('Unauthorized', 'InvalidAuthToken', 'AccessDenied'): - raise Amber('unauthorized', f"{name_of} at step '{name}'") from error - if name_of in ('gaierror', 'ConnectionError', 'ServiceError', 'B2ConnectionError'): - raise Amber('unreachable', f"{name_of} at step '{name}'") from error raise Failure(name, name_of) from error @@ -158,6 +157,9 @@ def prepare(target): try: import b2sdk.v3 as b2 except ImportError as error: + if not missing_runtime(error): + # b2sdk is installed but broken: an SDK regression, not a missing runtime + raise Failure('import', type(error).__name__) from error raise Amber('missing-runtime', 'b2sdk is not installed') from error return b2, realm diff --git a/.sdkharness/tests/conformance/files.download_by_id b/.sdkharness/tests/conformance/files.download_by_id index ddc2ab60f..16d2f6c40 100755 --- a/.sdkharness/tests/conformance/files.download_by_id +++ b/.sdkharness/tests/conformance/files.download_by_id @@ -16,10 +16,9 @@ the most recent version of the file." https://www.backblaze.com/docs/cloud-storage-file-versions https://www.backblaze.com/apidocs/b2-download-file-by-id -Written from bin/conformance/b2-sdk-python/files.upload, the reference check, -and bin/conformance/README.md, the contract. It exercises b2sdk from this exact repository -checkout; the API was taken from -docs/sdks/b2-sdk-python/card.md and the published b2sdk docs; the assertion now lives with the SDK code it exercises. +Written from files.upload in this directory, the reference check. It exercises +b2sdk from this exact repository checkout; the API usage is taken from the +published b2sdk documentation. """ import io @@ -28,15 +27,17 @@ import sys import uuid sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'lib')) -from loopback_guard import refusal # noqa: E402 +from loopback_guard import missing_runtime, refusal # noqa: E402 SLUG = 'b2-sdk-python' CAPABILITY = 'files.download_by_id' OBJECT_NAME = 'st/by-id.txt' PAYLOAD_SIZE = 1024 -# The closed reason set, mirrored from bin/conformance/README.md. The runner -# enforces it; naming one outside this tuple is a FAIL it manufactures. +# The closed reason set. `lib/contract.py` only turns `no-realm-option`, +# `missing-runtime` and `not-claimed` into a SKIP. `unreachable` and +# `unauthorized` are never reported at the simulator: the runner supplies both +# the server and the credential, so those are FAIL, not amber. REASONS = ( 'no-realm-option', 'unreachable', @@ -47,7 +48,7 @@ REASONS = ( ) # A requested target maps to a realm or to amber. `simulator` is the harness's -# own server (bin/simulator/serve.mjs), whose URL the runner exports as +# own loopback server, whose URL the dispatcher exports as # CONFORMANCE_SIMULATOR_URL; unset, there is nothing to reach: no-realm-option. REALMS = { 'simulator': os.environ.get('CONFORMANCE_SIMULATOR_URL') or None, @@ -76,7 +77,7 @@ class Amber(Exception): class Failure(Exception): - """A golden-path step that did not do what the card claims.""" + """A golden-path step that did not do what the capability requires.""" def __init__(self, step: str, detail: str) -> None: self.step = step @@ -100,8 +101,10 @@ def note(text: str) -> None: def step(name, action): """Run one golden-path step, converting the environment's own errors. - A credential NEVER reaches the detail: only the exception class name and, - for a classified network/auth error, the class that classified it. + A credential NEVER reaches the detail: only the exception class name. + Every error here is a FAIL: the runner supplies both the simulator and the + credential, so an auth error, access denied, connection error or SDK error + is a defect, never an amber (COULD-NOT-RUN) result. """ try: return action() @@ -109,10 +112,6 @@ def step(name, action): raise except Exception as error: # noqa: BLE001 -- classified below, never echoed name_of = type(error).__name__ - if name_of in ('Unauthorized', 'InvalidAuthToken', 'AccessDenied'): - raise Amber('unauthorized', f"{name_of} at step '{name}'") from error - if name_of in ('gaierror', 'ConnectionError', 'ServiceError', 'B2ConnectionError'): - raise Amber('unreachable', f"{name_of} at step '{name}'") from error raise Failure(name, name_of) from error @@ -157,6 +156,9 @@ def prepare(target): try: import b2sdk.v3 as b2 except ImportError as error: + if not missing_runtime(error): + # b2sdk is installed but broken: an SDK regression, not a missing runtime + raise Failure('import', type(error).__name__) from error raise Amber('missing-runtime', 'b2sdk is not installed') from error return b2, realm diff --git a/.sdkharness/tests/conformance/files.download_content b/.sdkharness/tests/conformance/files.download_content index eb98001a4..67ee991e4 100755 --- a/.sdkharness/tests/conformance/files.download_content +++ b/.sdkharness/tests/conformance/files.download_content @@ -15,10 +15,9 @@ headers, Content-Length and X-Bz-Content-Sha1 among them, "contain the same information they did when the file was uploaded". https://www.backblaze.com/apidocs/b2-download-file-by-name -Written from bin/conformance/b2-sdk-python/files.upload, the reference check, -and bin/conformance/README.md, the contract. It exercises b2sdk from this exact repository -checkout; the API was taken from -docs/sdks/b2-sdk-python/card.md and the published b2sdk docs; the assertion now lives with the SDK code it exercises. +Written from files.upload in this directory, the reference check. It exercises +b2sdk from this exact repository checkout; the API usage is taken from the +published b2sdk documentation. """ import hashlib @@ -28,15 +27,17 @@ import sys import uuid sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'lib')) -from loopback_guard import refusal # noqa: E402 +from loopback_guard import missing_runtime, refusal # noqa: E402 SLUG = 'b2-sdk-python' CAPABILITY = 'files.download_content' OBJECT_NAME = 'st/download.txt' PAYLOAD_SIZE = 1024 -# The closed reason set, mirrored from bin/conformance/README.md. The runner -# enforces it; naming one outside this tuple is a FAIL it manufactures. +# The closed reason set. `lib/contract.py` only turns `no-realm-option`, +# `missing-runtime` and `not-claimed` into a SKIP. `unreachable` and +# `unauthorized` are never reported at the simulator: the runner supplies both +# the server and the credential, so those are FAIL, not amber. REASONS = ( 'no-realm-option', 'unreachable', @@ -47,7 +48,7 @@ REASONS = ( ) # A requested target maps to a realm or to amber. `simulator` is the harness's -# own server (bin/simulator/serve.mjs), whose URL the runner exports as +# own loopback server, whose URL the dispatcher exports as # CONFORMANCE_SIMULATOR_URL; unset, there is nothing to reach: no-realm-option. REALMS = { 'simulator': os.environ.get('CONFORMANCE_SIMULATOR_URL') or None, @@ -76,7 +77,7 @@ class Amber(Exception): class Failure(Exception): - """A golden-path step that did not do what the card claims.""" + """A golden-path step that did not do what the capability requires.""" def __init__(self, step: str, detail: str) -> None: self.step = step @@ -100,8 +101,10 @@ def note(text: str) -> None: def step(name, action): """Run one golden-path step, converting the environment's own errors. - A credential NEVER reaches the detail: only the exception class name and, - for a classified network/auth error, the class that classified it. + A credential NEVER reaches the detail: only the exception class name. + Every error here is a FAIL: the runner supplies both the simulator and the + credential, so an auth error, access denied, connection error or SDK error + is a defect, never an amber (COULD-NOT-RUN) result. """ try: return action() @@ -109,10 +112,6 @@ def step(name, action): raise except Exception as error: # noqa: BLE001 -- classified below, never echoed name_of = type(error).__name__ - if name_of in ('Unauthorized', 'InvalidAuthToken', 'AccessDenied'): - raise Amber('unauthorized', f"{name_of} at step '{name}'") from error - if name_of in ('gaierror', 'ConnectionError', 'ServiceError', 'B2ConnectionError'): - raise Amber('unreachable', f"{name_of} at step '{name}'") from error raise Failure(name, name_of) from error @@ -157,6 +156,9 @@ def prepare(target): try: import b2sdk.v3 as b2 except ImportError as error: + if not missing_runtime(error): + # b2sdk is installed but broken: an SDK regression, not a missing runtime + raise Failure('import', type(error).__name__) from error raise Amber('missing-runtime', 'b2sdk is not installed') from error return b2, realm diff --git a/.sdkharness/tests/conformance/files.hide b/.sdkharness/tests/conformance/files.hide index 171cf3667..138ae8d80 100755 --- a/.sdkharness/tests/conformance/files.hide +++ b/.sdkharness/tests/conformance/files.hide @@ -22,10 +22,9 @@ The original stays reachable because "b2_download_file_by_id This operation downloads a specific version of a file by the given file ID." https://www.backblaze.com/docs/cloud-storage-file-versions -Written from bin/conformance/b2-sdk-python/files.upload, the reference check, -and bin/conformance/README.md, the contract. It exercises b2sdk from this exact repository -checkout; the API was taken from -docs/sdks/b2-sdk-python/card.md and the published b2sdk docs; the assertion now lives with the SDK code it exercises. +Written from files.upload in this directory, the reference check. It exercises +b2sdk from this exact repository checkout; the API usage is taken from the +published b2sdk documentation. """ import io @@ -34,7 +33,7 @@ import sys import uuid sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'lib')) -from loopback_guard import refusal # noqa: E402 +from loopback_guard import missing_runtime, refusal # noqa: E402 SLUG = 'b2-sdk-python' CAPABILITY = 'files.hide' @@ -42,8 +41,10 @@ PREFIX = 'st/' OBJECT_NAME = 'st/hide.txt' PAYLOAD_SIZE = 1024 -# The closed reason set, mirrored from bin/conformance/README.md. The runner -# enforces it; naming one outside this tuple is a FAIL it manufactures. +# The closed reason set. `lib/contract.py` only turns `no-realm-option`, +# `missing-runtime` and `not-claimed` into a SKIP. `unreachable` and +# `unauthorized` are never reported at the simulator: the runner supplies both +# the server and the credential, so those are FAIL, not amber. REASONS = ( 'no-realm-option', 'unreachable', @@ -54,7 +55,7 @@ REASONS = ( ) # A requested target maps to a realm or to amber. `simulator` is the harness's -# own server (bin/simulator/serve.mjs), whose URL the runner exports as +# own loopback server, whose URL the dispatcher exports as # CONFORMANCE_SIMULATOR_URL; unset, there is nothing to reach: no-realm-option. REALMS = { 'simulator': os.environ.get('CONFORMANCE_SIMULATOR_URL') or None, @@ -83,7 +84,7 @@ class Amber(Exception): class Failure(Exception): - """A golden-path step that did not do what the card claims.""" + """A golden-path step that did not do what the capability requires.""" def __init__(self, step: str, detail: str) -> None: self.step = step @@ -107,8 +108,10 @@ def note(text: str) -> None: def step(name, action): """Run one golden-path step, converting the environment's own errors. - A credential NEVER reaches the detail: only the exception class name and, - for a classified network/auth error, the class that classified it. + A credential NEVER reaches the detail: only the exception class name. + Every error here is a FAIL: the runner supplies both the simulator and the + credential, so an auth error, access denied, connection error or SDK error + is a defect, never an amber (COULD-NOT-RUN) result. """ try: return action() @@ -116,10 +119,6 @@ def step(name, action): raise except Exception as error: # noqa: BLE001 -- classified below, never echoed name_of = type(error).__name__ - if name_of in ('Unauthorized', 'InvalidAuthToken', 'AccessDenied'): - raise Amber('unauthorized', f"{name_of} at step '{name}'") from error - if name_of in ('gaierror', 'ConnectionError', 'ServiceError', 'B2ConnectionError'): - raise Amber('unreachable', f"{name_of} at step '{name}'") from error raise Failure(name, name_of) from error @@ -164,6 +163,9 @@ def prepare(target): try: import b2sdk.v3 as b2 except ImportError as error: + if not missing_runtime(error): + # b2sdk is installed but broken: an SDK regression, not a missing runtime + raise Failure('import', type(error).__name__) from error raise Amber('missing-runtime', 'b2sdk is not installed') from error return b2, realm diff --git a/.sdkharness/tests/conformance/files.list b/.sdkharness/tests/conformance/files.list index 2bcb8a325..2b4b1211f 100755 --- a/.sdkharness/tests/conformance/files.list +++ b/.sdkharness/tests/conformance/files.list @@ -18,10 +18,9 @@ b2_list_file_versions "Lists all versions of all files contained in one bucket" and supports the same prefix option. https://www.backblaze.com/apidocs/b2-list-file-versions -Written from bin/conformance/b2-sdk-python/files.upload, the reference check, -and bin/conformance/README.md, the contract. It exercises b2sdk from this exact repository -checkout; the API was taken from -docs/sdks/b2-sdk-python/card.md and the published b2sdk docs; the assertion now lives with the SDK code it exercises. +Written from files.upload in this directory, the reference check. It exercises +b2sdk from this exact repository checkout; the API usage is taken from the +published b2sdk documentation. """ import collections @@ -30,7 +29,7 @@ import sys import uuid sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'lib')) -from loopback_guard import refusal # noqa: E402 +from loopback_guard import missing_runtime, refusal # noqa: E402 SLUG = 'b2-sdk-python' CAPABILITY = 'files.list' @@ -39,8 +38,10 @@ INSIDE = ('st/list/a.txt', 'st/list/b.txt', 'st/list/c.txt') OUTSIDE = 'st/outside.txt' PAYLOAD_SIZE = 256 -# The closed reason set, mirrored from bin/conformance/README.md. The runner -# enforces it; naming one outside this tuple is a FAIL it manufactures. +# The closed reason set. `lib/contract.py` only turns `no-realm-option`, +# `missing-runtime` and `not-claimed` into a SKIP. `unreachable` and +# `unauthorized` are never reported at the simulator: the runner supplies both +# the server and the credential, so those are FAIL, not amber. REASONS = ( 'no-realm-option', 'unreachable', @@ -51,7 +52,7 @@ REASONS = ( ) # A requested target maps to a realm or to amber. `simulator` is the harness's -# own server (bin/simulator/serve.mjs), whose URL the runner exports as +# own loopback server, whose URL the dispatcher exports as # CONFORMANCE_SIMULATOR_URL; unset, there is nothing to reach: no-realm-option. REALMS = { 'simulator': os.environ.get('CONFORMANCE_SIMULATOR_URL') or None, @@ -80,7 +81,7 @@ class Amber(Exception): class Failure(Exception): - """A golden-path step that did not do what the card claims.""" + """A golden-path step that did not do what the capability requires.""" def __init__(self, step: str, detail: str) -> None: self.step = step @@ -104,8 +105,10 @@ def note(text: str) -> None: def step(name, action): """Run one golden-path step, converting the environment's own errors. - A credential NEVER reaches the detail: only the exception class name and, - for a classified network/auth error, the class that classified it. + A credential NEVER reaches the detail: only the exception class name. + Every error here is a FAIL: the runner supplies both the simulator and the + credential, so an auth error, access denied, connection error or SDK error + is a defect, never an amber (COULD-NOT-RUN) result. """ try: return action() @@ -113,10 +116,6 @@ def step(name, action): raise except Exception as error: # noqa: BLE001 -- classified below, never echoed name_of = type(error).__name__ - if name_of in ('Unauthorized', 'InvalidAuthToken', 'AccessDenied'): - raise Amber('unauthorized', f"{name_of} at step '{name}'") from error - if name_of in ('gaierror', 'ConnectionError', 'ServiceError', 'B2ConnectionError'): - raise Amber('unreachable', f"{name_of} at step '{name}'") from error raise Failure(name, name_of) from error @@ -161,6 +160,9 @@ def prepare(target): try: import b2sdk.v3 as b2 except ImportError as error: + if not missing_runtime(error): + # b2sdk is installed but broken: an SDK regression, not a missing runtime + raise Failure('import', type(error).__name__) from error raise Amber('missing-runtime', 'b2sdk is not installed') from error return b2, realm diff --git a/.sdkharness/tests/conformance/files.metadata b/.sdkharness/tests/conformance/files.metadata index 050e00f7c..d42dd5ef6 100755 --- a/.sdkharness/tests/conformance/files.metadata +++ b/.sdkharness/tests/conformance/files.metadata @@ -22,10 +22,9 @@ A custom field name "is converted to lower case when it is stored and returned in the fileInfo object" -- hence the lower-case key. https://www.backblaze.com/apidocs/b2-upload-file -Written from bin/conformance/b2-sdk-python/files.upload, the reference check, -and bin/conformance/README.md, the contract. It exercises b2sdk from this exact repository -checkout; the API was taken from -docs/sdks/b2-sdk-python/card.md and the published b2sdk docs; the assertion now lives with the SDK code it exercises. +Written from files.upload in this directory, the reference check. It exercises +b2sdk from this exact repository checkout; the API usage is taken from the +published b2sdk documentation. """ import hashlib @@ -34,7 +33,7 @@ import sys import uuid sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'lib')) -from loopback_guard import refusal # noqa: E402 +from loopback_guard import missing_runtime, refusal # noqa: E402 SLUG = 'b2-sdk-python' CAPABILITY = 'files.metadata' @@ -44,8 +43,10 @@ CONTENT_TYPE = 'text/x-sdkharness' INFO_KEY = 'sdkharness-conf' INFO_VALUE = 'fixture' -# The closed reason set, mirrored from bin/conformance/README.md. The runner -# enforces it; naming one outside this tuple is a FAIL it manufactures. +# The closed reason set. `lib/contract.py` only turns `no-realm-option`, +# `missing-runtime` and `not-claimed` into a SKIP. `unreachable` and +# `unauthorized` are never reported at the simulator: the runner supplies both +# the server and the credential, so those are FAIL, not amber. REASONS = ( 'no-realm-option', 'unreachable', @@ -56,7 +57,7 @@ REASONS = ( ) # A requested target maps to a realm or to amber. `simulator` is the harness's -# own server (bin/simulator/serve.mjs), whose URL the runner exports as +# own loopback server, whose URL the dispatcher exports as # CONFORMANCE_SIMULATOR_URL; unset, there is nothing to reach: no-realm-option. REALMS = { 'simulator': os.environ.get('CONFORMANCE_SIMULATOR_URL') or None, @@ -85,7 +86,7 @@ class Amber(Exception): class Failure(Exception): - """A golden-path step that did not do what the card claims.""" + """A golden-path step that did not do what the capability requires.""" def __init__(self, step: str, detail: str) -> None: self.step = step @@ -109,8 +110,10 @@ def note(text: str) -> None: def step(name, action): """Run one golden-path step, converting the environment's own errors. - A credential NEVER reaches the detail: only the exception class name and, - for a classified network/auth error, the class that classified it. + A credential NEVER reaches the detail: only the exception class name. + Every error here is a FAIL: the runner supplies both the simulator and the + credential, so an auth error, access denied, connection error or SDK error + is a defect, never an amber (COULD-NOT-RUN) result. """ try: return action() @@ -118,10 +121,6 @@ def step(name, action): raise except Exception as error: # noqa: BLE001 -- classified below, never echoed name_of = type(error).__name__ - if name_of in ('Unauthorized', 'InvalidAuthToken', 'AccessDenied'): - raise Amber('unauthorized', f"{name_of} at step '{name}'") from error - if name_of in ('gaierror', 'ConnectionError', 'ServiceError', 'B2ConnectionError'): - raise Amber('unreachable', f"{name_of} at step '{name}'") from error raise Failure(name, name_of) from error @@ -166,6 +165,9 @@ def prepare(target): try: import b2sdk.v3 as b2 except ImportError as error: + if not missing_runtime(error): + # b2sdk is installed but broken: an SDK regression, not a missing runtime + raise Failure('import', type(error).__name__) from error raise Amber('missing-runtime', 'b2sdk is not installed') from error return b2, realm diff --git a/.sdkharness/tests/conformance/files.server_side_copy b/.sdkharness/tests/conformance/files.server_side_copy index 8e9d15096..2d2076393 100755 --- a/.sdkharness/tests/conformance/files.server_side_copy +++ b/.sdkharness/tests/conformance/files.server_side_copy @@ -17,10 +17,9 @@ of this file" and contentSha1 is "The SHA1 of the bytes stored in the file", so an entire copy reports the source's sha1 under a new fileId. https://www.backblaze.com/apidocs/b2-copy-file -Written from bin/conformance/b2-sdk-python/files.upload, the reference check, -and bin/conformance/README.md, the contract. It exercises b2sdk from this exact repository -checkout; the API was taken from -docs/sdks/b2-sdk-python/card.md and the published b2sdk docs; the assertion now lives with the SDK code it exercises. +Written from files.upload in this directory, the reference check. It exercises +b2sdk from this exact repository checkout; the API usage is taken from the +published b2sdk documentation. """ import hashlib @@ -29,21 +28,23 @@ import sys import uuid sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'lib')) -from loopback_guard import refusal # noqa: E402 +from loopback_guard import missing_runtime, refusal # noqa: E402 SLUG = 'b2-sdk-python' CAPABILITY = 'files.server_side_copy' SOURCE_NAME = 'st/copy-source.bin' DEST_NAME = 'st/copy-dest.bin' # Single-part on purpose: the harness simulator reports a 5,000-byte -# recommendedPartSize (bin/simulator/serve.mjs, PROFILE); above it b2sdk uploads +# recommendedPartSize (the simulator's PROFILE); above it b2sdk uploads # the fixture as a large file, whose contentSha1 is "none", not the whole-file # hash this scenario asserts (https://www.backblaze.com/apidocs/b2-get-file-info). # Mirrors the TypeScript check. PAYLOAD_SIZE = 512 -# The closed reason set, mirrored from bin/conformance/README.md. The runner -# enforces it; naming one outside this tuple is a FAIL it manufactures. +# The closed reason set. `lib/contract.py` only turns `no-realm-option`, +# `missing-runtime` and `not-claimed` into a SKIP. `unreachable` and +# `unauthorized` are never reported at the simulator: the runner supplies both +# the server and the credential, so those are FAIL, not amber. REASONS = ( 'no-realm-option', 'unreachable', @@ -54,7 +55,7 @@ REASONS = ( ) # A requested target maps to a realm or to amber. `simulator` is the harness's -# own server (bin/simulator/serve.mjs), whose URL the runner exports as +# own loopback server, whose URL the dispatcher exports as # CONFORMANCE_SIMULATOR_URL; unset, there is nothing to reach: no-realm-option. REALMS = { 'simulator': os.environ.get('CONFORMANCE_SIMULATOR_URL') or None, @@ -83,7 +84,7 @@ class Amber(Exception): class Failure(Exception): - """A golden-path step that did not do what the card claims.""" + """A golden-path step that did not do what the capability requires.""" def __init__(self, step: str, detail: str) -> None: self.step = step @@ -107,8 +108,10 @@ def note(text: str) -> None: def step(name, action): """Run one golden-path step, converting the environment's own errors. - A credential NEVER reaches the detail: only the exception class name and, - for a classified network/auth error, the class that classified it. + A credential NEVER reaches the detail: only the exception class name. + Every error here is a FAIL: the runner supplies both the simulator and the + credential, so an auth error, access denied, connection error or SDK error + is a defect, never an amber (COULD-NOT-RUN) result. """ try: return action() @@ -116,10 +119,6 @@ def step(name, action): raise except Exception as error: # noqa: BLE001 -- classified below, never echoed name_of = type(error).__name__ - if name_of in ('Unauthorized', 'InvalidAuthToken', 'AccessDenied'): - raise Amber('unauthorized', f"{name_of} at step '{name}'") from error - if name_of in ('gaierror', 'ConnectionError', 'ServiceError', 'B2ConnectionError'): - raise Amber('unreachable', f"{name_of} at step '{name}'") from error raise Failure(name, name_of) from error @@ -164,6 +163,9 @@ def prepare(target): try: import b2sdk.v3 as b2 except ImportError as error: + if not missing_runtime(error): + # b2sdk is installed but broken: an SDK regression, not a missing runtime + raise Failure('import', type(error).__name__) from error raise Amber('missing-runtime', 'b2sdk is not installed') from error return b2, realm diff --git a/.sdkharness/tests/conformance/files.upload b/.sdkharness/tests/conformance/files.upload index 574451bc1..7ba36f299 100755 --- a/.sdkharness/tests/conformance/files.upload +++ b/.sdkharness/tests/conformance/files.upload @@ -1,11 +1,10 @@ #!/usr/bin/env python3 -"""THE REFERENCE CHECK — b2-sdk-python x files.upload. +"""Reference conformance check: b2-sdk-python x files.upload. -The other 134 checks are written from this one. Read bin/conformance/README.md -for the contract; this file is what obeying it looks like. +The other conformance checks in this directory follow the same structure; this +file is the simplest example of it. -Scenario (approved 2026-09-22, one per capability, identical on every tool that -claims it): +Scenario (one per capability, identical on every tool that claims it): Setup an ephemeral bucket and a 1 KiB payload of known sha1 Action upload it to st/upload.txt @@ -23,8 +22,8 @@ The round trip holds because b2_download_file_by_name returns headers that "contain the same information they did when the file was uploaded". https://www.backblaze.com/apidocs/b2-download-file-by-name -It exercises b2sdk from this exact repository checkout. The API was originally the API was taken from docs/sdks/b2-sdk-python/card.md and the -published b2sdk docs, which is what every check author does. +It exercises b2sdk from this exact repository checkout. The API usage is taken +from the published b2sdk documentation. """ import hashlib @@ -34,15 +33,17 @@ import sys import uuid sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'lib')) -from loopback_guard import refusal # noqa: E402 +from loopback_guard import missing_runtime, refusal # noqa: E402 SLUG = 'b2-sdk-python' CAPABILITY = 'files.upload' OBJECT_NAME = 'st/upload.txt' PAYLOAD_SIZE = 1024 -# The closed reason set, mirrored from bin/conformance/README.md. The runner -# enforces it; naming one outside this tuple is a FAIL it manufactures. +# The closed reason set. `lib/contract.py` only turns `no-realm-option`, +# `missing-runtime` and `not-claimed` into a SKIP. `unreachable` and +# `unauthorized` are never reported at the simulator: the runner supplies both +# the server and the credential, so those are FAIL, not amber. REASONS = ( 'no-realm-option', 'unreachable', @@ -53,7 +54,7 @@ REASONS = ( ) # A requested target maps to a realm or to amber. `simulator` is the harness's -# own server (bin/simulator/serve.mjs), whose URL the runner exports as +# own loopback server, whose URL the dispatcher exports as # CONFORMANCE_SIMULATOR_URL; unset, there is nothing to reach: no-realm-option. REALMS = { 'simulator': os.environ.get('CONFORMANCE_SIMULATOR_URL') or None, @@ -75,7 +76,7 @@ class Amber(Exception): class Failure(Exception): - """A golden-path step that did not do what the card claims.""" + """A golden-path step that did not do what the capability requires.""" def __init__(self, step: str, detail: str) -> None: self.step = step @@ -89,8 +90,10 @@ def say(target: str, verdict: str) -> None: def step(name: str, action): """Run one golden-path step, converting the environment's own errors. - A credential NEVER reaches the detail: only the exception class name and, - for a classified network/auth error, the class that classified it. + A credential NEVER reaches the detail: only the exception class name. + Every error here is a FAIL: the runner supplies both the simulator and the + credential, so an auth error, access denied, connection error or SDK error + is a defect, never an amber (COULD-NOT-RUN) result. """ try: return action() @@ -98,10 +101,6 @@ def step(name: str, action): raise except Exception as error: # noqa: BLE001 -- classified below, never echoed name_of = type(error).__name__ - if name_of in ('Unauthorized', 'InvalidAuthToken', 'AccessDenied'): - raise Amber('unauthorized', f"{name_of} at step '{name}'") from error - if name_of in ('gaierror', 'ConnectionError', 'ServiceError', 'B2ConnectionError'): - raise Amber('unreachable', f"{name_of} at step '{name}'") from error raise Failure(name, name_of) from error @@ -120,6 +119,9 @@ def run(target: str) -> None: try: from b2sdk.v3 import B2Api, InMemoryAccountInfo except ImportError as error: + if not missing_runtime(error): + # b2sdk is installed but broken: an SDK regression, not a missing runtime + raise Failure('import', type(error).__name__) from error raise Amber('missing-runtime', 'b2sdk is not installed') from error api = B2Api(InMemoryAccountInfo()) diff --git a/.sdkharness/tests/conformance/keys.crud b/.sdkharness/tests/conformance/keys.crud index 69a510d9b..3ca012fc0 100755 --- a/.sdkharness/tests/conformance/keys.crud +++ b/.sdkharness/tests/conformance/keys.crud @@ -20,10 +20,9 @@ https://www.backblaze.com/apidocs/b2-create-key https://www.backblaze.com/apidocs/b2-list-keys https://www.backblaze.com/apidocs/b2-delete-key -Written from bin/conformance/b2-sdk-python/files.upload, the reference check, -and bin/conformance/README.md, the contract. It exercises b2sdk from this exact repository -checkout; the API was taken from -docs/sdks/b2-sdk-python/card.md and the published b2sdk docs; the assertion now lives with the SDK code it exercises. +Written from files.upload in this directory, the reference check. It exercises +b2sdk from this exact repository checkout; the API usage is taken from the +published b2sdk documentation. """ import os @@ -31,14 +30,16 @@ import sys import uuid sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'lib')) -from loopback_guard import refusal # noqa: E402 +from loopback_guard import missing_runtime, refusal # noqa: E402 SLUG = 'b2-sdk-python' CAPABILITY = 'keys.crud' CAPABILITIES = ['listBuckets', 'listFiles', 'readFiles'] -# The closed reason set, mirrored from bin/conformance/README.md. The runner -# enforces it; naming one outside this tuple is a FAIL it manufactures. +# The closed reason set. `lib/contract.py` only turns `no-realm-option`, +# `missing-runtime` and `not-claimed` into a SKIP. `unreachable` and +# `unauthorized` are never reported at the simulator: the runner supplies both +# the server and the credential, so those are FAIL, not amber. REASONS = ( 'no-realm-option', 'unreachable', @@ -49,7 +50,7 @@ REASONS = ( ) # A requested target maps to a realm or to amber. `simulator` is the harness's -# own server (bin/simulator/serve.mjs), whose URL the runner exports as +# own loopback server, whose URL the dispatcher exports as # CONFORMANCE_SIMULATOR_URL; unset, there is nothing to reach: no-realm-option. REALMS = { 'simulator': os.environ.get('CONFORMANCE_SIMULATOR_URL') or None, @@ -78,7 +79,7 @@ class Amber(Exception): class Failure(Exception): - """A golden-path step that did not do what the card claims.""" + """A golden-path step that did not do what the capability requires.""" def __init__(self, step: str, detail: str) -> None: self.step = step @@ -102,8 +103,10 @@ def note(text: str) -> None: def step(name, action): """Run one golden-path step, converting the environment's own errors. - A credential NEVER reaches the detail: only the exception class name and, - for a classified network/auth error, the class that classified it. + A credential NEVER reaches the detail: only the exception class name. + Every error here is a FAIL: the runner supplies both the simulator and the + credential, so an auth error, access denied, connection error or SDK error + is a defect, never an amber (COULD-NOT-RUN) result. """ try: return action() @@ -111,10 +114,6 @@ def step(name, action): raise except Exception as error: # noqa: BLE001 -- classified below, never echoed name_of = type(error).__name__ - if name_of in ('Unauthorized', 'InvalidAuthToken', 'AccessDenied'): - raise Amber('unauthorized', f"{name_of} at step '{name}'") from error - if name_of in ('gaierror', 'ConnectionError', 'ServiceError', 'B2ConnectionError'): - raise Amber('unreachable', f"{name_of} at step '{name}'") from error raise Failure(name, name_of) from error @@ -159,6 +158,9 @@ def prepare(target): try: import b2sdk.v3 as b2 except ImportError as error: + if not missing_runtime(error): + # b2sdk is installed but broken: an SDK regression, not a missing runtime + raise Failure('import', type(error).__name__) from error raise Amber('missing-runtime', 'b2sdk is not installed') from error return b2, realm diff --git a/.sdkharness/tests/conformance/keys.multi_bucket b/.sdkharness/tests/conformance/keys.multi_bucket index fe34963c4..773c6e01e 100755 --- a/.sdkharness/tests/conformance/keys.multi_bucket +++ b/.sdkharness/tests/conformance/keys.multi_bucket @@ -19,10 +19,9 @@ https://www.backblaze.com/apidocs/b2-create-key https://www.backblaze.com/apidocs/b2-authorize-account https://www.backblaze.com/apidocs/b2-list-buckets -Written from bin/conformance/b2-sdk-python/files.upload, the reference check, -and bin/conformance/README.md, the contract. It exercises b2sdk from this exact repository -checkout; the API was taken from -docs/sdks/b2-sdk-python/card.md and the published b2sdk docs; the assertion now lives with the SDK code it exercises. +Written from files.upload in this directory, the reference check. It exercises +b2sdk from this exact repository checkout; the API usage is taken from the +published b2sdk documentation. """ import os @@ -30,14 +29,16 @@ import sys import uuid sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'lib')) -from loopback_guard import refusal # noqa: E402 +from loopback_guard import missing_runtime, refusal # noqa: E402 SLUG = 'b2-sdk-python' CAPABILITY = 'keys.multi_bucket' CAPABILITIES = ['listBuckets', 'listFiles', 'readFiles'] -# The closed reason set, mirrored from bin/conformance/README.md. The runner -# enforces it; naming one outside this tuple is a FAIL it manufactures. +# The closed reason set. `lib/contract.py` only turns `no-realm-option`, +# `missing-runtime` and `not-claimed` into a SKIP. `unreachable` and +# `unauthorized` are never reported at the simulator: the runner supplies both +# the server and the credential, so those are FAIL, not amber. REASONS = ( 'no-realm-option', 'unreachable', @@ -48,7 +49,7 @@ REASONS = ( ) # A requested target maps to a realm or to amber. `simulator` is the harness's -# own server (bin/simulator/serve.mjs), whose URL the runner exports as +# own loopback server, whose URL the dispatcher exports as # CONFORMANCE_SIMULATOR_URL; unset, there is nothing to reach: no-realm-option. REALMS = { 'simulator': os.environ.get('CONFORMANCE_SIMULATOR_URL') or None, @@ -77,7 +78,7 @@ class Amber(Exception): class Failure(Exception): - """A golden-path step that did not do what the card claims.""" + """A golden-path step that did not do what the capability requires.""" def __init__(self, step: str, detail: str) -> None: self.step = step @@ -101,8 +102,10 @@ def note(text: str) -> None: def step(name, action): """Run one golden-path step, converting the environment's own errors. - A credential NEVER reaches the detail: only the exception class name and, - for a classified network/auth error, the class that classified it. + A credential NEVER reaches the detail: only the exception class name. + Every error here is a FAIL: the runner supplies both the simulator and the + credential, so an auth error, access denied, connection error or SDK error + is a defect, never an amber (COULD-NOT-RUN) result. """ try: return action() @@ -110,10 +113,6 @@ def step(name, action): raise except Exception as error: # noqa: BLE001 -- classified below, never echoed name_of = type(error).__name__ - if name_of in ('Unauthorized', 'InvalidAuthToken', 'AccessDenied'): - raise Amber('unauthorized', f"{name_of} at step '{name}'") from error - if name_of in ('gaierror', 'ConnectionError', 'ServiceError', 'B2ConnectionError'): - raise Amber('unreachable', f"{name_of} at step '{name}'") from error raise Failure(name, name_of) from error @@ -158,6 +157,9 @@ def prepare(target): try: import b2sdk.v3 as b2 except ImportError as error: + if not missing_runtime(error): + # b2sdk is installed but broken: an SDK regression, not a missing runtime + raise Failure('import', type(error).__name__) from error raise Amber('missing-runtime', 'b2sdk is not installed') from error return b2, realm diff --git a/.sdkharness/tests/conformance/large.compose_mixed b/.sdkharness/tests/conformance/large.compose_mixed index e09fb88da..8315ca640 100755 --- a/.sdkharness/tests/conformance/large.compose_mixed +++ b/.sdkharness/tests/conformance/large.compose_mixed @@ -22,10 +22,9 @@ will be copied." https://www.backblaze.com/apidocs/b2-copy-part Part sizes: "the minimum part size is 5 MB except for the last part in a file which has a minimum size of 1 byte." https://www.backblaze.com/docs/cloud-storage-create-large-files-with-the-native-api -Written from bin/conformance/b2-sdk-python/files.upload, the reference check, -and bin/conformance/README.md, the contract. It exercises b2sdk from this exact repository -checkout; the API was taken from -docs/sdks/b2-sdk-python/card.md and the published b2sdk docs; the assertion now lives with the SDK code it exercises. +Written from files.upload in this directory, the reference check. It exercises +b2sdk from this exact repository checkout; the API usage is taken from the +published b2sdk documentation. """ import hashlib @@ -36,7 +35,7 @@ import tempfile import uuid sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'lib')) -from loopback_guard import refusal # noqa: E402 +from loopback_guard import missing_runtime, refusal # noqa: E402 SLUG = 'b2-sdk-python' CAPABILITY = 'large.compose_mixed' @@ -45,8 +44,10 @@ STORED_A = 'st/compose-a.bin' STORED_B = 'st/compose-b.bin' COMPOSED = 'st/composed.bin' -# The closed reason set, mirrored from bin/conformance/README.md. The runner -# enforces it; naming one outside this tuple is a FAIL it manufactures. +# The closed reason set. `lib/contract.py` only turns `no-realm-option`, +# `missing-runtime` and `not-claimed` into a SKIP. `unreachable` and +# `unauthorized` are never reported at the simulator: the runner supplies both +# the server and the credential, so those are FAIL, not amber. REASONS = ( 'no-realm-option', 'unreachable', @@ -57,7 +58,7 @@ REASONS = ( ) # A requested target maps to a realm or to amber. `simulator` is the harness's -# own server (bin/simulator/serve.mjs), whose URL the runner exports as +# own loopback server, whose URL the dispatcher exports as # CONFORMANCE_SIMULATOR_URL; unset, there is nothing to reach: no-realm-option. REALMS = { 'simulator': os.environ.get('CONFORMANCE_SIMULATOR_URL') or None, @@ -86,7 +87,7 @@ class Amber(Exception): class Failure(Exception): - """A golden-path step that did not do what the card claims.""" + """A golden-path step that did not do what the capability requires.""" def __init__(self, step: str, detail: str) -> None: self.step = step @@ -110,8 +111,10 @@ def note(text: str) -> None: def step(name, action): """Run one golden-path step, converting the environment's own errors. - A credential NEVER reaches the detail: only the exception class name and, - for a classified network/auth error, the class that classified it. + A credential NEVER reaches the detail: only the exception class name. + Every error here is a FAIL: the runner supplies both the simulator and the + credential, so an auth error, access denied, connection error or SDK error + is a defect, never an amber (COULD-NOT-RUN) result. """ try: return action() @@ -119,10 +122,6 @@ def step(name, action): raise except Exception as error: # noqa: BLE001 -- classified below, never echoed name_of = type(error).__name__ - if name_of in ('Unauthorized', 'InvalidAuthToken', 'AccessDenied'): - raise Amber('unauthorized', f"{name_of} at step '{name}'") from error - if name_of in ('gaierror', 'ConnectionError', 'ServiceError', 'B2ConnectionError'): - raise Amber('unreachable', f"{name_of} at step '{name}'") from error raise Failure(name, name_of) from error @@ -167,6 +166,9 @@ def prepare(target): try: import b2sdk.v3 as b2 except ImportError as error: + if not missing_runtime(error): + # b2sdk is installed but broken: an SDK regression, not a missing runtime + raise Failure('import', type(error).__name__) from error raise Amber('missing-runtime', 'b2sdk is not installed') from error return b2, realm diff --git a/.sdkharness/tests/conformance/large.concurrent_parts b/.sdkharness/tests/conformance/large.concurrent_parts index b0bce90df..8062a4c01 100755 --- a/.sdkharness/tests/conformance/large.concurrent_parts +++ b/.sdkharness/tests/conformance/large.concurrent_parts @@ -26,10 +26,9 @@ PERMISSION ONLY: no B2 document requires a client to upload parts concurrently, so the ">1 in flight at 4" expected value traces to the tool's own concurrency setting, not to B2. -Written from bin/conformance/b2-sdk-python/files.upload, the reference check, -and bin/conformance/README.md, the contract. It exercises b2sdk from this exact repository -checkout; the API was taken from -docs/sdks/b2-sdk-python/card.md and the published b2sdk docs; the assertion now lives with the SDK code it exercises. +Written from files.upload in this directory, the reference check. It exercises +b2sdk from this exact repository checkout; the API usage is taken from the +published b2sdk documentation. """ import os @@ -39,7 +38,7 @@ import time import uuid sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'lib')) -from loopback_guard import refusal # noqa: E402 +from loopback_guard import missing_runtime, refusal # noqa: E402 SLUG = 'b2-sdk-python' CAPABILITY = 'large.concurrent_parts' @@ -49,8 +48,10 @@ PARTS_WANTED = 4 WORKERS = 4 OBSERVATION_DWELL_SECONDS = 0.1 -# The closed reason set, mirrored from bin/conformance/README.md. The runner -# enforces it; naming one outside this tuple is a FAIL it manufactures. +# The closed reason set. `lib/contract.py` only turns `no-realm-option`, +# `missing-runtime` and `not-claimed` into a SKIP. `unreachable` and +# `unauthorized` are never reported at the simulator: the runner supplies both +# the server and the credential, so those are FAIL, not amber. REASONS = ( 'no-realm-option', 'unreachable', @@ -61,7 +62,7 @@ REASONS = ( ) # A requested target maps to a realm or to amber. `simulator` is the harness's -# own server (bin/simulator/serve.mjs), whose URL the runner exports as +# own loopback server, whose URL the dispatcher exports as # CONFORMANCE_SIMULATOR_URL; unset, there is nothing to reach: no-realm-option. REALMS = { 'simulator': os.environ.get('CONFORMANCE_SIMULATOR_URL') or None, @@ -90,7 +91,7 @@ class Amber(Exception): class Failure(Exception): - """A golden-path step that did not do what the card claims.""" + """A golden-path step that did not do what the capability requires.""" def __init__(self, step: str, detail: str) -> None: self.step = step @@ -114,8 +115,10 @@ def note(text: str) -> None: def step(name, action): """Run one golden-path step, converting the environment's own errors. - A credential NEVER reaches the detail: only the exception class name and, - for a classified network/auth error, the class that classified it. + A credential NEVER reaches the detail: only the exception class name. + Every error here is a FAIL: the runner supplies both the simulator and the + credential, so an auth error, access denied, connection error or SDK error + is a defect, never an amber (COULD-NOT-RUN) result. """ try: return action() @@ -123,10 +126,6 @@ def step(name, action): raise except Exception as error: # noqa: BLE001 -- classified below, never echoed name_of = type(error).__name__ - if name_of in ('Unauthorized', 'InvalidAuthToken', 'AccessDenied'): - raise Amber('unauthorized', f"{name_of} at step '{name}'") from error - if name_of in ('gaierror', 'ConnectionError', 'ServiceError', 'B2ConnectionError'): - raise Amber('unreachable', f"{name_of} at step '{name}'") from error raise Failure(name, name_of) from error @@ -171,6 +170,9 @@ def prepare(target): try: import b2sdk.v3 as b2 except ImportError as error: + if not missing_runtime(error): + # b2sdk is installed but broken: an SDK regression, not a missing runtime + raise Failure('import', type(error).__name__) from error raise Amber('missing-runtime', 'b2sdk is not installed') from error return b2, realm diff --git a/.sdkharness/tests/conformance/large.multipart b/.sdkharness/tests/conformance/large.multipart index 2ee9bf3ef..6034da97e 100755 --- a/.sdkharness/tests/conformance/large.multipart +++ b/.sdkharness/tests/conformance/large.multipart @@ -23,10 +23,9 @@ DOCS -- the acceptance criteria; what the tool does is the result: NEEDS REVIEW: docs say large_file_sha1 is RECOMMENDED, not required; the assertion FAILs a large file that lacks it. -Written from bin/conformance/b2-sdk-python/files.upload, the reference check, -and bin/conformance/README.md, the contract. It exercises b2sdk from this exact repository -checkout; the API was taken from -docs/sdks/b2-sdk-python/card.md and the published b2sdk docs; the assertion now lives with the SDK code it exercises. +Written from files.upload in this directory, the reference check. It exercises +b2sdk from this exact repository checkout; the API usage is taken from the +published b2sdk documentation. """ import collections @@ -37,15 +36,17 @@ import sys import uuid sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'lib')) -from loopback_guard import refusal # noqa: E402 +from loopback_guard import missing_runtime, refusal # noqa: E402 SLUG = 'b2-sdk-python' CAPABILITY = 'large.multipart' OBJECT_NAME = 'st/multipart.bin' PARTS_WANTED = 3 -# The closed reason set, mirrored from bin/conformance/README.md. The runner -# enforces it; naming one outside this tuple is a FAIL it manufactures. +# The closed reason set. `lib/contract.py` only turns `no-realm-option`, +# `missing-runtime` and `not-claimed` into a SKIP. `unreachable` and +# `unauthorized` are never reported at the simulator: the runner supplies both +# the server and the credential, so those are FAIL, not amber. REASONS = ( 'no-realm-option', 'unreachable', @@ -56,7 +57,7 @@ REASONS = ( ) # A requested target maps to a realm or to amber. `simulator` is the harness's -# own server (bin/simulator/serve.mjs), whose URL the runner exports as +# own loopback server, whose URL the dispatcher exports as # CONFORMANCE_SIMULATOR_URL; unset, there is nothing to reach: no-realm-option. REALMS = { 'simulator': os.environ.get('CONFORMANCE_SIMULATOR_URL') or None, @@ -85,7 +86,7 @@ class Amber(Exception): class Failure(Exception): - """A golden-path step that did not do what the card claims.""" + """A golden-path step that did not do what the capability requires.""" def __init__(self, step: str, detail: str) -> None: self.step = step @@ -109,8 +110,10 @@ def note(text: str) -> None: def step(name, action): """Run one golden-path step, converting the environment's own errors. - A credential NEVER reaches the detail: only the exception class name and, - for a classified network/auth error, the class that classified it. + A credential NEVER reaches the detail: only the exception class name. + Every error here is a FAIL: the runner supplies both the simulator and the + credential, so an auth error, access denied, connection error or SDK error + is a defect, never an amber (COULD-NOT-RUN) result. """ try: return action() @@ -118,10 +121,6 @@ def step(name, action): raise except Exception as error: # noqa: BLE001 -- classified below, never echoed name_of = type(error).__name__ - if name_of in ('Unauthorized', 'InvalidAuthToken', 'AccessDenied'): - raise Amber('unauthorized', f"{name_of} at step '{name}'") from error - if name_of in ('gaierror', 'ConnectionError', 'ServiceError', 'B2ConnectionError'): - raise Amber('unreachable', f"{name_of} at step '{name}'") from error raise Failure(name, name_of) from error @@ -166,6 +165,9 @@ def prepare(target): try: import b2sdk.v3 as b2 except ImportError as error: + if not missing_runtime(error): + # b2sdk is installed but broken: an SDK regression, not a missing runtime + raise Failure('import', type(error).__name__) from error raise Amber('missing-runtime', 'b2sdk is not installed') from error return b2, realm diff --git a/.sdkharness/tests/conformance/large.parallel_download b/.sdkharness/tests/conformance/large.parallel_download index 1df48e882..5c0a8a8ec 100755 --- a/.sdkharness/tests/conformance/large.parallel_download +++ b/.sdkharness/tests/conformance/large.parallel_download @@ -30,10 +30,9 @@ PERMISSION ONLY: no B2 document requires a client to download in parallel, so the ">1 concurrent ranged GET" expected value traces to the tool's stream setting, not to B2. -Written from bin/conformance/b2-sdk-python/files.upload, the reference check, -and bin/conformance/README.md, the contract. It exercises b2sdk from this exact repository -checkout; the API was taken from -docs/sdks/b2-sdk-python/card.md and the published b2sdk docs; the assertion now lives with the SDK code it exercises. +Written from files.upload in this directory, the reference check. It exercises +b2sdk from this exact repository checkout; the API usage is taken from the +published b2sdk documentation. """ import io @@ -44,7 +43,7 @@ import time import uuid sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'lib')) -from loopback_guard import refusal # noqa: E402 +from loopback_guard import missing_runtime, refusal # noqa: E402 SLUG = 'b2-sdk-python' CAPABILITY = 'large.parallel_download' @@ -53,8 +52,10 @@ PARTS_WANTED = 4 STREAMS = 4 OBSERVATION_DWELL_SECONDS = 0.1 -# The closed reason set, mirrored from bin/conformance/README.md. The runner -# enforces it; naming one outside this tuple is a FAIL it manufactures. +# The closed reason set. `lib/contract.py` only turns `no-realm-option`, +# `missing-runtime` and `not-claimed` into a SKIP. `unreachable` and +# `unauthorized` are never reported at the simulator: the runner supplies both +# the server and the credential, so those are FAIL, not amber. REASONS = ( 'no-realm-option', 'unreachable', @@ -65,7 +66,7 @@ REASONS = ( ) # A requested target maps to a realm or to amber. `simulator` is the harness's -# own server (bin/simulator/serve.mjs), whose URL the runner exports as +# own loopback server, whose URL the dispatcher exports as # CONFORMANCE_SIMULATOR_URL; unset, there is nothing to reach: no-realm-option. REALMS = { 'simulator': os.environ.get('CONFORMANCE_SIMULATOR_URL') or None, @@ -94,7 +95,7 @@ class Amber(Exception): class Failure(Exception): - """A golden-path step that did not do what the card claims.""" + """A golden-path step that did not do what the capability requires.""" def __init__(self, step: str, detail: str) -> None: self.step = step @@ -118,8 +119,10 @@ def note(text: str) -> None: def step(name, action): """Run one golden-path step, converting the environment's own errors. - A credential NEVER reaches the detail: only the exception class name and, - for a classified network/auth error, the class that classified it. + A credential NEVER reaches the detail: only the exception class name. + Every error here is a FAIL: the runner supplies both the simulator and the + credential, so an auth error, access denied, connection error or SDK error + is a defect, never an amber (COULD-NOT-RUN) result. """ try: return action() @@ -127,10 +130,6 @@ def step(name, action): raise except Exception as error: # noqa: BLE001 -- classified below, never echoed name_of = type(error).__name__ - if name_of in ('Unauthorized', 'InvalidAuthToken', 'AccessDenied'): - raise Amber('unauthorized', f"{name_of} at step '{name}'") from error - if name_of in ('gaierror', 'ConnectionError', 'ServiceError', 'B2ConnectionError'): - raise Amber('unreachable', f"{name_of} at step '{name}'") from error raise Failure(name, name_of) from error @@ -175,6 +174,9 @@ def prepare(target): try: import b2sdk.v3 as b2 except ImportError as error: + if not missing_runtime(error): + # b2sdk is installed but broken: an SDK regression, not a missing runtime + raise Failure('import', type(error).__name__) from error raise Amber('missing-runtime', 'b2sdk is not installed') from error return b2, realm diff --git a/.sdkharness/tests/conformance/large.resume b/.sdkharness/tests/conformance/large.resume index 3ea0559e9..7c80d05e1 100755 --- a/.sdkharness/tests/conformance/large.resume +++ b/.sdkharness/tests/conformance/large.resume @@ -25,10 +25,9 @@ B2 makes reusing the unfinished fileId POSSIBLE; that a rerun reuses it instead of calling b2_start_large_file is the capability under test, not a B2 promise. -Written from bin/conformance/b2-sdk-python/files.upload, the reference check, -and bin/conformance/README.md, the contract. It exercises b2sdk from this exact repository -checkout; the API was taken from -docs/sdks/b2-sdk-python/card.md and the published b2sdk docs; the assertion now lives with the SDK code it exercises. +Written from files.upload in this directory, the reference check. It exercises +b2sdk from this exact repository checkout; the API usage is taken from the +published b2sdk documentation. """ import collections @@ -40,7 +39,7 @@ import tempfile import uuid sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'lib')) -from loopback_guard import refusal # noqa: E402 +from loopback_guard import missing_runtime, refusal # noqa: E402 SLUG = 'b2-sdk-python' CAPABILITY = 'large.resume' @@ -48,8 +47,10 @@ OBJECT_NAME = 'st/resume.bin' PARTS_WANTED = 4 PARTS_BEFORE_INTERRUPT = 1 -# The closed reason set, mirrored from bin/conformance/README.md. The runner -# enforces it; naming one outside this tuple is a FAIL it manufactures. +# The closed reason set. `lib/contract.py` only turns `no-realm-option`, +# `missing-runtime` and `not-claimed` into a SKIP. `unreachable` and +# `unauthorized` are never reported at the simulator: the runner supplies both +# the server and the credential, so those are FAIL, not amber. REASONS = ( 'no-realm-option', 'unreachable', @@ -60,7 +61,7 @@ REASONS = ( ) # A requested target maps to a realm or to amber. `simulator` is the harness's -# own server (bin/simulator/serve.mjs), whose URL the runner exports as +# own loopback server, whose URL the dispatcher exports as # CONFORMANCE_SIMULATOR_URL; unset, there is nothing to reach: no-realm-option. REALMS = { 'simulator': os.environ.get('CONFORMANCE_SIMULATOR_URL') or None, @@ -89,7 +90,7 @@ class Amber(Exception): class Failure(Exception): - """A golden-path step that did not do what the card claims.""" + """A golden-path step that did not do what the capability requires.""" def __init__(self, step: str, detail: str) -> None: self.step = step @@ -113,8 +114,10 @@ def note(text: str) -> None: def step(name, action): """Run one golden-path step, converting the environment's own errors. - A credential NEVER reaches the detail: only the exception class name and, - for a classified network/auth error, the class that classified it. + A credential NEVER reaches the detail: only the exception class name. + Every error here is a FAIL: the runner supplies both the simulator and the + credential, so an auth error, access denied, connection error or SDK error + is a defect, never an amber (COULD-NOT-RUN) result. """ try: return action() @@ -122,10 +125,6 @@ def step(name, action): raise except Exception as error: # noqa: BLE001 -- classified below, never echoed name_of = type(error).__name__ - if name_of in ('Unauthorized', 'InvalidAuthToken', 'AccessDenied'): - raise Amber('unauthorized', f"{name_of} at step '{name}'") from error - if name_of in ('gaierror', 'ConnectionError', 'ServiceError', 'B2ConnectionError'): - raise Amber('unreachable', f"{name_of} at step '{name}'") from error raise Failure(name, name_of) from error @@ -170,6 +169,9 @@ def prepare(target): try: import b2sdk.v3 as b2 except ImportError as error: + if not missing_runtime(error): + # b2sdk is installed but broken: an SDK regression, not a missing runtime + raise Failure('import', type(error).__name__) from error raise Amber('missing-runtime', 'b2sdk is not installed') from error return b2, realm diff --git a/.sdkharness/tests/conformance/large.unbound_incremental b/.sdkharness/tests/conformance/large.unbound_incremental index 32fcaa5a8..f57c331c5 100755 --- a/.sdkharness/tests/conformance/large.unbound_incremental +++ b/.sdkharness/tests/conformance/large.unbound_incremental @@ -32,10 +32,9 @@ which b2_start_large_file recommends only "If the caller knows the SHA1 of the entire large file being uploaded" (https://www.backblaze.com/apidocs/b2-start-large-file) -- an unbound stream's uploader cannot know it when the file is started. -Written from bin/conformance/b2-sdk-python/files.upload, the reference check, -and bin/conformance/README.md, the contract. It exercises b2sdk from this exact repository -checkout; the API was taken from -docs/sdks/b2-sdk-python/card.md and the published b2sdk docs; the assertion now lives with the SDK code it exercises. +Written from files.upload in this directory, the reference check. It exercises +b2sdk from this exact repository checkout; the API usage is taken from the +published b2sdk documentation. """ import collections @@ -47,7 +46,7 @@ import tempfile import uuid sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'lib')) -from loopback_guard import refusal # noqa: E402 +from loopback_guard import missing_runtime, refusal # noqa: E402 SLUG = 'b2-sdk-python' CAPABILITY = 'large.unbound_incremental' @@ -56,8 +55,10 @@ INCREMENTAL_NAME = 'st/incremental.bin' UNBOUND_SIZE = 4096 APPENDED_SIZE = 1024 -# The closed reason set, mirrored from bin/conformance/README.md. The runner -# enforces it; naming one outside this tuple is a FAIL it manufactures. +# The closed reason set. `lib/contract.py` only turns `no-realm-option`, +# `missing-runtime` and `not-claimed` into a SKIP. `unreachable` and +# `unauthorized` are never reported at the simulator: the runner supplies both +# the server and the credential, so those are FAIL, not amber. REASONS = ( 'no-realm-option', 'unreachable', @@ -68,7 +69,7 @@ REASONS = ( ) # A requested target maps to a realm or to amber. `simulator` is the harness's -# own server (bin/simulator/serve.mjs), whose URL the runner exports as +# own loopback server, whose URL the dispatcher exports as # CONFORMANCE_SIMULATOR_URL; unset, there is nothing to reach: no-realm-option. REALMS = { 'simulator': os.environ.get('CONFORMANCE_SIMULATOR_URL') or None, @@ -97,7 +98,7 @@ class Amber(Exception): class Failure(Exception): - """A golden-path step that did not do what the card claims.""" + """A golden-path step that did not do what the capability requires.""" def __init__(self, step: str, detail: str) -> None: self.step = step @@ -121,8 +122,10 @@ def note(text: str) -> None: def step(name, action): """Run one golden-path step, converting the environment's own errors. - A credential NEVER reaches the detail: only the exception class name and, - for a classified network/auth error, the class that classified it. + A credential NEVER reaches the detail: only the exception class name. + Every error here is a FAIL: the runner supplies both the simulator and the + credential, so an auth error, access denied, connection error or SDK error + is a defect, never an amber (COULD-NOT-RUN) result. """ try: return action() @@ -130,10 +133,6 @@ def step(name, action): raise except Exception as error: # noqa: BLE001 -- classified below, never echoed name_of = type(error).__name__ - if name_of in ('Unauthorized', 'InvalidAuthToken', 'AccessDenied'): - raise Amber('unauthorized', f"{name_of} at step '{name}'") from error - if name_of in ('gaierror', 'ConnectionError', 'ServiceError', 'B2ConnectionError'): - raise Amber('unreachable', f"{name_of} at step '{name}'") from error raise Failure(name, name_of) from error @@ -178,6 +177,9 @@ def prepare(target): try: import b2sdk.v3 as b2 except ImportError as error: + if not missing_runtime(error): + # b2sdk is installed but broken: an SDK regression, not a missing runtime + raise Failure('import', type(error).__name__) from error raise Amber('missing-runtime', 'b2sdk is not installed') from error return b2, realm diff --git a/.sdkharness/tests/conformance/lock.bucket_default b/.sdkharness/tests/conformance/lock.bucket_default index facb2590e..976a39f4a 100755 --- a/.sdkharness/tests/conformance/lock.bucket_default +++ b/.sdkharness/tests/conformance/lock.bucket_default @@ -18,10 +18,9 @@ The read-back shape -- defaultRetention {mode, period {duration, unit}} -- is the native API's: https://www.backblaze.com/docs/cloud-storage-enable-object-lock-with-the-native-api -Written from bin/conformance/b2-sdk-python/files.upload, the reference check, -and bin/conformance/README.md, the contract. It exercises b2sdk from this exact repository -checkout; the API was taken from -docs/sdks/b2-sdk-python/card.md and the published b2sdk docs; the assertion now lives with the SDK code it exercises. +Written from files.upload in this directory, the reference check. It exercises +b2sdk from this exact repository checkout; the API usage is taken from the +published b2sdk documentation. """ import os @@ -30,7 +29,7 @@ import time import uuid sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'lib')) -from loopback_guard import refusal # noqa: E402 +from loopback_guard import missing_runtime, refusal # noqa: E402 SLUG = 'b2-sdk-python' CAPABILITY = 'lock.bucket_default' @@ -39,8 +38,10 @@ PAYLOAD_SIZE = 256 DAY_MILLIS = 24 * 60 * 60 * 1000 TOLERANCE_MILLIS = 30 * 60 * 1000 -# The closed reason set, mirrored from bin/conformance/README.md. The runner -# enforces it; naming one outside this tuple is a FAIL it manufactures. +# The closed reason set. `lib/contract.py` only turns `no-realm-option`, +# `missing-runtime` and `not-claimed` into a SKIP. `unreachable` and +# `unauthorized` are never reported at the simulator: the runner supplies both +# the server and the credential, so those are FAIL, not amber. REASONS = ( 'no-realm-option', 'unreachable', @@ -51,7 +52,7 @@ REASONS = ( ) # A requested target maps to a realm or to amber. `simulator` is the harness's -# own server (bin/simulator/serve.mjs), whose URL the runner exports as +# own loopback server, whose URL the dispatcher exports as # CONFORMANCE_SIMULATOR_URL; unset, there is nothing to reach: no-realm-option. REALMS = { 'simulator': os.environ.get('CONFORMANCE_SIMULATOR_URL') or None, @@ -80,7 +81,7 @@ class Amber(Exception): class Failure(Exception): - """A golden-path step that did not do what the card claims.""" + """A golden-path step that did not do what the capability requires.""" def __init__(self, step: str, detail: str) -> None: self.step = step @@ -104,8 +105,10 @@ def note(text: str) -> None: def step(name, action): """Run one golden-path step, converting the environment's own errors. - A credential NEVER reaches the detail: only the exception class name and, - for a classified network/auth error, the class that classified it. + A credential NEVER reaches the detail: only the exception class name. + Every error here is a FAIL: the runner supplies both the simulator and the + credential, so an auth error, access denied, connection error or SDK error + is a defect, never an amber (COULD-NOT-RUN) result. """ try: return action() @@ -113,10 +116,6 @@ def step(name, action): raise except Exception as error: # noqa: BLE001 -- classified below, never echoed name_of = type(error).__name__ - if name_of in ('Unauthorized', 'InvalidAuthToken', 'AccessDenied'): - raise Amber('unauthorized', f"{name_of} at step '{name}'") from error - if name_of in ('gaierror', 'ConnectionError', 'ServiceError', 'B2ConnectionError'): - raise Amber('unreachable', f"{name_of} at step '{name}'") from error raise Failure(name, name_of) from error @@ -161,6 +160,9 @@ def prepare(target): try: import b2sdk.v3 as b2 except ImportError as error: + if not missing_runtime(error): + # b2sdk is installed but broken: an SDK regression, not a missing runtime + raise Failure('import', type(error).__name__) from error raise Amber('missing-runtime', 'b2sdk is not installed') from error return b2, realm diff --git a/.sdkharness/tests/conformance/lock.bypass_governance b/.sdkharness/tests/conformance/lock.bypass_governance index 570f778bb..a914aaaaa 100755 --- a/.sdkharness/tests/conformance/lock.bypass_governance +++ b/.sdkharness/tests/conformance/lock.bypass_governance @@ -28,10 +28,9 @@ InvalidAuthToken (bad or expired token), any other Unauthorized code, a 5xx or a network error does not count. The exact error code and message are not verified against real B2 (UNVERIFIED in the simulator ledger, docs/FIDELITY.md). -Written from bin/conformance/b2-sdk-python/files.upload, the reference check, -and bin/conformance/README.md, the contract. It exercises b2sdk from this exact repository -checkout; the API was taken from -docs/sdks/b2-sdk-python/card.md and the published b2sdk docs; the assertion now lives with the SDK code it exercises. +Written from files.upload in this directory, the reference check. It exercises +b2sdk from this exact repository checkout; the API usage is taken from the +published b2sdk documentation. """ import os @@ -40,7 +39,7 @@ import time import uuid sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'lib')) -from loopback_guard import refusal # noqa: E402 +from loopback_guard import missing_runtime, refusal # noqa: E402 SLUG = 'b2-sdk-python' CAPABILITY = 'lock.bypass_governance' @@ -48,8 +47,10 @@ OBJECT_NAME = 'st/bypass-governance.txt' PAYLOAD_SIZE = 256 DAY_MILLIS = 24 * 60 * 60 * 1000 -# The closed reason set, mirrored from bin/conformance/README.md. The runner -# enforces it; naming one outside this tuple is a FAIL it manufactures. +# The closed reason set. `lib/contract.py` only turns `no-realm-option`, +# `missing-runtime` and `not-claimed` into a SKIP. `unreachable` and +# `unauthorized` are never reported at the simulator: the runner supplies both +# the server and the credential, so those are FAIL, not amber. REASONS = ( 'no-realm-option', 'unreachable', @@ -60,7 +61,7 @@ REASONS = ( ) # A requested target maps to a realm or to amber. `simulator` is the harness's -# own server (bin/simulator/serve.mjs), whose URL the runner exports as +# own loopback server, whose URL the dispatcher exports as # CONFORMANCE_SIMULATOR_URL; unset, there is nothing to reach: no-realm-option. REALMS = { 'simulator': os.environ.get('CONFORMANCE_SIMULATOR_URL') or None, @@ -89,7 +90,7 @@ class Amber(Exception): class Failure(Exception): - """A golden-path step that did not do what the card claims.""" + """A golden-path step that did not do what the capability requires.""" def __init__(self, step: str, detail: str) -> None: self.step = step @@ -113,8 +114,10 @@ def note(text: str) -> None: def step(name, action): """Run one golden-path step, converting the environment's own errors. - A credential NEVER reaches the detail: only the exception class name and, - for a classified network/auth error, the class that classified it. + A credential NEVER reaches the detail: only the exception class name. + Every error here is a FAIL: the runner supplies both the simulator and the + credential, so an auth error, access denied, connection error or SDK error + is a defect, never an amber (COULD-NOT-RUN) result. """ try: return action() @@ -122,10 +125,6 @@ def step(name, action): raise except Exception as error: # noqa: BLE001 -- classified below, never echoed name_of = type(error).__name__ - if name_of in ('Unauthorized', 'InvalidAuthToken', 'AccessDenied'): - raise Amber('unauthorized', f"{name_of} at step '{name}'") from error - if name_of in ('gaierror', 'ConnectionError', 'ServiceError', 'B2ConnectionError'): - raise Amber('unreachable', f"{name_of} at step '{name}'") from error raise Failure(name, name_of) from error @@ -180,6 +179,9 @@ def prepare(target): try: import b2sdk.v3 as b2 except ImportError as error: + if not missing_runtime(error): + # b2sdk is installed but broken: an SDK regression, not a missing runtime + raise Failure('import', type(error).__name__) from error raise Amber('missing-runtime', 'b2sdk is not installed') from error return b2, realm diff --git a/.sdkharness/tests/conformance/lock.legal_hold b/.sdkharness/tests/conformance/lock.legal_hold index af39e7fc0..d2009cff2 100755 --- a/.sdkharness/tests/conformance/lock.legal_hold +++ b/.sdkharness/tests/conformance/lock.legal_hold @@ -18,10 +18,9 @@ https://www.backblaze.com/apidocs/b2-update-file-legal-hold given file, then that file is protected from being deleted." https://www.backblaze.com/docs/cloud-storage-object-lock -Written from bin/conformance/b2-sdk-python/files.upload, the reference check, -and bin/conformance/README.md, the contract. It exercises b2sdk from this exact repository -checkout; the API was taken from -docs/sdks/b2-sdk-python/card.md and the published b2sdk docs; the assertion now lives with the SDK code it exercises. +Written from files.upload in this directory, the reference check. It exercises +b2sdk from this exact repository checkout; the API usage is taken from the +published b2sdk documentation. """ import os @@ -29,15 +28,17 @@ import sys import uuid sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'lib')) -from loopback_guard import refusal # noqa: E402 +from loopback_guard import missing_runtime, refusal # noqa: E402 SLUG = 'b2-sdk-python' CAPABILITY = 'lock.legal_hold' OBJECT_NAME = 'st/legal-hold.txt' PAYLOAD_SIZE = 256 -# The closed reason set, mirrored from bin/conformance/README.md. The runner -# enforces it; naming one outside this tuple is a FAIL it manufactures. +# The closed reason set. `lib/contract.py` only turns `no-realm-option`, +# `missing-runtime` and `not-claimed` into a SKIP. `unreachable` and +# `unauthorized` are never reported at the simulator: the runner supplies both +# the server and the credential, so those are FAIL, not amber. REASONS = ( 'no-realm-option', 'unreachable', @@ -48,7 +49,7 @@ REASONS = ( ) # A requested target maps to a realm or to amber. `simulator` is the harness's -# own server (bin/simulator/serve.mjs), whose URL the runner exports as +# own loopback server, whose URL the dispatcher exports as # CONFORMANCE_SIMULATOR_URL; unset, there is nothing to reach: no-realm-option. REALMS = { 'simulator': os.environ.get('CONFORMANCE_SIMULATOR_URL') or None, @@ -77,7 +78,7 @@ class Amber(Exception): class Failure(Exception): - """A golden-path step that did not do what the card claims.""" + """A golden-path step that did not do what the capability requires.""" def __init__(self, step: str, detail: str) -> None: self.step = step @@ -101,8 +102,10 @@ def note(text: str) -> None: def step(name, action): """Run one golden-path step, converting the environment's own errors. - A credential NEVER reaches the detail: only the exception class name and, - for a classified network/auth error, the class that classified it. + A credential NEVER reaches the detail: only the exception class name. + Every error here is a FAIL: the runner supplies both the simulator and the + credential, so an auth error, access denied, connection error or SDK error + is a defect, never an amber (COULD-NOT-RUN) result. """ try: return action() @@ -110,10 +113,6 @@ def step(name, action): raise except Exception as error: # noqa: BLE001 -- classified below, never echoed name_of = type(error).__name__ - if name_of in ('Unauthorized', 'InvalidAuthToken', 'AccessDenied'): - raise Amber('unauthorized', f"{name_of} at step '{name}'") from error - if name_of in ('gaierror', 'ConnectionError', 'ServiceError', 'B2ConnectionError'): - raise Amber('unreachable', f"{name_of} at step '{name}'") from error raise Failure(name, name_of) from error @@ -158,6 +157,9 @@ def prepare(target): try: import b2sdk.v3 as b2 except ImportError as error: + if not missing_runtime(error): + # b2sdk is installed but broken: an SDK regression, not a missing runtime + raise Failure('import', type(error).__name__) from error raise Amber('missing-runtime', 'b2sdk is not installed') from error return b2, realm diff --git a/.sdkharness/tests/conformance/lock.per_file_retention b/.sdkharness/tests/conformance/lock.per_file_retention index 93f28b829..b4af79d9b 100755 --- a/.sdkharness/tests/conformance/lock.per_file_retention +++ b/.sdkharness/tests/conformance/lock.per_file_retention @@ -30,10 +30,9 @@ InvalidAuthToken (bad or expired token), any other Unauthorized code, a 5xx or a network error does not count. The exact error code and message are not verified against real B2 (UNVERIFIED in the simulator ledger, docs/FIDELITY.md). -Written from bin/conformance/b2-sdk-python/files.upload, the reference check, -and bin/conformance/README.md, the contract. It exercises b2sdk from this exact repository -checkout; the API was taken from -docs/sdks/b2-sdk-python/card.md and the published b2sdk docs; the assertion now lives with the SDK code it exercises. +Written from files.upload in this directory, the reference check. It exercises +b2sdk from this exact repository checkout; the API usage is taken from the +published b2sdk documentation. """ import os @@ -42,7 +41,7 @@ import time import uuid sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'lib')) -from loopback_guard import refusal # noqa: E402 +from loopback_guard import missing_runtime, refusal # noqa: E402 SLUG = 'b2-sdk-python' CAPABILITY = 'lock.per_file_retention' @@ -50,8 +49,10 @@ OBJECT_NAME = 'st/per-file-retention.txt' PAYLOAD_SIZE = 256 TWO_DAYS_MILLIS = 2 * 24 * 60 * 60 * 1000 -# The closed reason set, mirrored from bin/conformance/README.md. The runner -# enforces it; naming one outside this tuple is a FAIL it manufactures. +# The closed reason set. `lib/contract.py` only turns `no-realm-option`, +# `missing-runtime` and `not-claimed` into a SKIP. `unreachable` and +# `unauthorized` are never reported at the simulator: the runner supplies both +# the server and the credential, so those are FAIL, not amber. REASONS = ( 'no-realm-option', 'unreachable', @@ -62,7 +63,7 @@ REASONS = ( ) # A requested target maps to a realm or to amber. `simulator` is the harness's -# own server (bin/simulator/serve.mjs), whose URL the runner exports as +# own loopback server, whose URL the dispatcher exports as # CONFORMANCE_SIMULATOR_URL; unset, there is nothing to reach: no-realm-option. REALMS = { 'simulator': os.environ.get('CONFORMANCE_SIMULATOR_URL') or None, @@ -91,7 +92,7 @@ class Amber(Exception): class Failure(Exception): - """A golden-path step that did not do what the card claims.""" + """A golden-path step that did not do what the capability requires.""" def __init__(self, step: str, detail: str) -> None: self.step = step @@ -115,8 +116,10 @@ def note(text: str) -> None: def step(name, action): """Run one golden-path step, converting the environment's own errors. - A credential NEVER reaches the detail: only the exception class name and, - for a classified network/auth error, the class that classified it. + A credential NEVER reaches the detail: only the exception class name. + Every error here is a FAIL: the runner supplies both the simulator and the + credential, so an auth error, access denied, connection error or SDK error + is a defect, never an amber (COULD-NOT-RUN) result. """ try: return action() @@ -124,10 +127,6 @@ def step(name, action): raise except Exception as error: # noqa: BLE001 -- classified below, never echoed name_of = type(error).__name__ - if name_of in ('Unauthorized', 'InvalidAuthToken', 'AccessDenied'): - raise Amber('unauthorized', f"{name_of} at step '{name}'") from error - if name_of in ('gaierror', 'ConnectionError', 'ServiceError', 'B2ConnectionError'): - raise Amber('unreachable', f"{name_of} at step '{name}'") from error raise Failure(name, name_of) from error @@ -182,6 +181,9 @@ def prepare(target): try: import b2sdk.v3 as b2 except ImportError as error: + if not missing_runtime(error): + # b2sdk is installed but broken: an SDK regression, not a missing runtime + raise Failure('import', type(error).__name__) from error raise Amber('missing-runtime', 'b2sdk is not installed') from error return b2, realm diff --git a/.sdkharness/tests/conformance/urls.native_download b/.sdkharness/tests/conformance/urls.native_download index 282d2a02a..8af211ee0 100755 --- a/.sdkharness/tests/conformance/urls.native_download +++ b/.sdkharness/tests/conformance/urls.native_download @@ -10,7 +10,7 @@ claims it): Assert 200 with the correct bytes, then 401 The share token MUST be the B2-NATIVE shape: b2sdk has no S3 presigning at - all (the card records that), so a SigV4 query string appearing here would + all (the capability record says so), so a SigV4 query string appearing here would mean this check is testing something other than what the cell claims. DOCS. The expected values are B2's published NATIVE contract, not SigV4. @@ -26,10 +26,9 @@ https://www.backblaze.com/apidocs/b2-download-file-by-name The assertion below matches using the header form: a /file/ URL with no query string, the token sent as Authorization, no X-Amz-* material, 401. -Written from bin/conformance/b2-sdk-python/files.upload, the reference check, -and bin/conformance/README.md, the contract. It exercises b2sdk from this exact repository -checkout; the API was taken from -docs/sdks/b2-sdk-python/card.md and the published b2sdk docs; the assertion now lives with the SDK code it exercises. +Written from files.upload in this directory, the reference check. It exercises +b2sdk from this exact repository checkout; the API usage is taken from the +published b2sdk documentation. """ import hashlib @@ -41,7 +40,7 @@ import urllib.request import uuid sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'lib')) -from loopback_guard import refusal # noqa: E402 +from loopback_guard import missing_runtime, refusal # noqa: E402 SLUG = 'b2-sdk-python' CAPABILITY = 'urls.native_download' @@ -51,8 +50,10 @@ PAYLOAD_SIZE = 1024 TTL_SECONDS = 1 EXPIRY_SLACK_SECONDS = 4 -# The closed reason set, mirrored from bin/conformance/README.md. The runner -# enforces it; naming one outside this tuple is a FAIL it manufactures. +# The closed reason set. `lib/contract.py` only turns `no-realm-option`, +# `missing-runtime` and `not-claimed` into a SKIP. `unreachable` and +# `unauthorized` are never reported at the simulator: the runner supplies both +# the server and the credential, so those are FAIL, not amber. REASONS = ( 'no-realm-option', 'unreachable', @@ -63,7 +64,7 @@ REASONS = ( ) # A requested target maps to a realm or to amber. `simulator` is the harness's -# own server (bin/simulator/serve.mjs), whose URL the runner exports as +# own loopback server, whose URL the dispatcher exports as # CONFORMANCE_SIMULATOR_URL; unset, there is nothing to reach: no-realm-option. REALMS = { 'simulator': os.environ.get('CONFORMANCE_SIMULATOR_URL') or None, @@ -92,7 +93,7 @@ class Amber(Exception): class Failure(Exception): - """A golden-path step that did not do what the card claims.""" + """A golden-path step that did not do what the capability requires.""" def __init__(self, step: str, detail: str) -> None: self.step = step @@ -116,8 +117,10 @@ def note(text: str) -> None: def step(name, action): """Run one golden-path step, converting the environment's own errors. - A credential NEVER reaches the detail: only the exception class name and, - for a classified network/auth error, the class that classified it. + A credential NEVER reaches the detail: only the exception class name. + Every error here is a FAIL: the runner supplies both the simulator and the + credential, so an auth error, access denied, connection error or SDK error + is a defect, never an amber (COULD-NOT-RUN) result. """ try: return action() @@ -125,10 +128,6 @@ def step(name, action): raise except Exception as error: # noqa: BLE001 -- classified below, never echoed name_of = type(error).__name__ - if name_of in ('Unauthorized', 'InvalidAuthToken', 'AccessDenied'): - raise Amber('unauthorized', f"{name_of} at step '{name}'") from error - if name_of in ('gaierror', 'ConnectionError', 'ServiceError', 'B2ConnectionError'): - raise Amber('unreachable', f"{name_of} at step '{name}'") from error raise Failure(name, name_of) from error @@ -173,6 +172,9 @@ def prepare(target): try: import b2sdk.v3 as b2 except ImportError as error: + if not missing_runtime(error): + # b2sdk is installed but broken: an SDK regression, not a missing runtime + raise Failure('import', type(error).__name__) from error raise Amber('missing-runtime', 'b2sdk is not installed') from error return b2, realm @@ -295,8 +297,8 @@ def run(target: str) -> None: except urllib.error.HTTPError as error: raise Failure('fetch', f'the authorized fetch returned HTTP {error.code}') from error except urllib.error.URLError as error: - raise Amber( - 'unreachable', f'{type(error.reason).__name__} fetching the download url' + raise Failure( + 'fetch', f'{type(error.reason).__name__} fetching the download url' ) from error if status != 200: @@ -316,8 +318,8 @@ def run(target: str) -> None: 'expiry', f'the expired token returned HTTP {error.code}, expected 401' ) from error except urllib.error.URLError as error: - raise Amber( - 'unreachable', f'{type(error.reason).__name__} re-fetching after expiry' + raise Failure( + 'expiry', f'{type(error.reason).__name__} re-fetching after expiry' ) from error else: raise Failure('expiry', f'the expired token still returned HTTP {expired_status}') diff --git a/.sdkharness/tests/health-golden-path b/.sdkharness/tests/health-golden-path index 9d1505995..a96931f18 100755 --- a/.sdkharness/tests/health-golden-path +++ b/.sdkharness/tests/health-golden-path @@ -16,6 +16,9 @@ SCENARIO = 'golden-path' SIMULATOR_CREDENTIAL = ('test-key-id', 'test-key') REPOSITORY_ROOT = Path(__file__).resolve().parents[2] +sys.path.insert(0, str(Path(__file__).resolve().parent / 'lib')) +from loopback_guard import scrub_proxy_environment # noqa: E402 + class CheckFailure(Exception): """A failed lifecycle step with a credential-safe reason.""" @@ -144,6 +147,7 @@ def run_health( def main() -> int: + scrub_proxy_environment(os.environ) try: run_health(os.environ) except CheckFailure as error: diff --git a/.sdkharness/tests/lib/contract.py b/.sdkharness/tests/lib/contract.py index 86da62dff..8d53f4777 100644 --- a/.sdkharness/tests/lib/contract.py +++ b/.sdkharness/tests/lib/contract.py @@ -10,9 +10,17 @@ from pathlib import Path from urllib.parse import urlsplit +sys.path.insert(0, str(Path(__file__).resolve().parent)) +from loopback_guard import scrub_proxy_environment # noqa: E402 + SLUG = 'b2-sdk-python' REPOSITORY_ROOT = Path(__file__).resolve().parents[3] SCENARIO_ROOT = Path(__file__).resolve().parents[1] +# The only COULD-NOT-RUN reasons that may become SKIP: the question genuinely +# could not be asked. At a simulator the harness supplies the server and the +# credential, so `unreachable`, `unauthorized` and an SDK import error are never +# legitimate ambers: any other reason is a FAIL (the CLI's SKIP policy). +SKIP_REASONS = frozenset({'no-realm-option', 'missing-runtime', 'no-client-option', 'not-claimed'}) SCENARIO_RE = re.compile(r'^[A-Za-z0-9_.-]+$') @@ -61,6 +69,7 @@ def validate_environment(level: str, environment: Mapping[str, str]) -> tuple[st def child_environment(level: str, environment: Mapping[str, str]) -> dict[str, str]: child = {name: value for name, value in environment.items() if not name.startswith('B2_')} + scrub_proxy_environment(child) child['PYTHONPATH'] = str(REPOSITORY_ROOT) child['B2_APPLICATION_KEY_ID'] = 'test-key-id' child['B2_APPLICATION_KEY'] = 'test-key' @@ -96,7 +105,10 @@ def translate(level: str, scenario: str, returncode: int, output: str) -> tuple[ if verdict.startswith('COULD-NOT-RUN (') and verdict.endswith(')'): if returncode != 0: return 'FAIL', f'contract: SKIP exited {returncode}', 1 - return 'SKIP', verdict[15:-1], 0 + reason = verdict[15:-1] + if reason.split(' -- ', 1)[0] not in SKIP_REASONS: + return 'FAIL', f'contract: {reason}', 1 + return 'SKIP', reason, 0 return 'FAIL', 'contract: malformed standing verdict', 1 diff --git a/.sdkharness/tests/lib/loopback_guard.py b/.sdkharness/tests/lib/loopback_guard.py index 2bd38babc..ea32a35d6 100644 --- a/.sdkharness/tests/lib/loopback_guard.py +++ b/.sdkharness/tests/lib/loopback_guard.py @@ -10,8 +10,40 @@ from __future__ import annotations import os +from collections.abc import MutableMapping from urllib.parse import urlsplit +PROXY_VARIABLES = frozenset( + {'http_proxy', 'https_proxy', 'all_proxy', 'ftp_proxy', 'no_proxy', 'request_method'} +) + + +def scrub_proxy_environment(environment: MutableMapping[str, str]) -> None: + """Remove proxy settings so a stray proxy cannot change a loopback result. + + `requests` and `urllib` honor `HTTP_PROXY`, `HTTPS_PROXY` and `ALL_PROXY` + (any case) even for 127.0.0.1, which turns a passing scenario into an + "unreachable" one on a machine that has a proxy configured. The proxy + variables are dropped and `NO_PROXY` is pinned to the loopback address, so + nothing but the simulator is ever reached directly and nothing is proxied. + `REQUEST_METHOD` (a CGI marker that makes `requests` ignore `HTTP_PROXY`) + is dropped too so the behavior does not depend on it. + """ + for name in list(environment): + if name.lower() in PROXY_VARIABLES: + del environment[name] + environment['NO_PROXY'] = '127.0.0.1' + environment['no_proxy'] = '127.0.0.1' + + +def missing_runtime(error: ImportError) -> bool: + """True only when `b2sdk` itself is not installed (no such top-level module). + + Any other ImportError means b2sdk is installed but broken (a failed or + circular import inside the SDK): that is an SDK regression and a FAIL. + """ + return isinstance(error, ModuleNotFoundError) and error.name == 'b2sdk' + def _is_loopback_origin(value: str, scheme: str) -> bool: try: @@ -38,6 +70,7 @@ def refusal(level: str) -> str | None: dispatcher builds: `_TARGET`, `_SIMULATOR_URL`, optionally `_SIMULATOR_HTTPS_URL`, and `RESILIENCE_CONTROL_URL` for resilience. """ + scrub_proxy_environment(os.environ) prefix = level.upper() target = os.environ.get(f'{prefix}_TARGET', 'simulator') if target != 'simulator': diff --git a/.sdkharness/tests/resilience/api.backoff_503 b/.sdkharness/tests/resilience/api.backoff_503 index 680ae01fb..59f915dcf 100755 --- a/.sdkharness/tests/resilience/api.backoff_503 +++ b/.sdkharness/tests/resilience/api.backoff_503 @@ -1,9 +1,8 @@ #!/usr/bin/env python3 """b2-sdk-python x api.backoff_503. -Written from the reference check, bin/resilience/b2-sdk-python/upload.retry_503. -The contract is bin/resilience/README.md; the question is the api.backoff_503 row of -bin/resilience/scenarios.tsv. +Written from the reference check, upload.retry_503 in this directory. +The question is the api.backoff_503 scenario of the central sdkharness registry. Fault fault b2_list_file_names 503 service_unavailable, NO Retry-After (count 1), armed after setup Assert the end state: the listing names exactly the fixture; the recovery path, @@ -18,7 +17,7 @@ not present, the developer should retry using an exponential backoff starting wi https://www.backblaze.com/docs/cloud-storage-integration-checklist It exercises b2sdk from this exact repository checkout; -the API is taken from docs/sdks/b2-sdk-python/card.md. +the API is taken from the published b2sdk documentation. """ import json @@ -29,7 +28,7 @@ import urllib.request import uuid sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'lib')) -from loopback_guard import refusal # noqa: E402 +from loopback_guard import missing_runtime, refusal # noqa: E402 SLUG = 'b2-sdk-python' SCENARIO = 'api.backoff_503' @@ -44,7 +43,7 @@ def is_faulted(e): FLOOR_S = 1.0 -# The closed reason set, mirrored from bin/resilience/README.md. This +# The closed reason set, fixed by the sdkharness resilience contract. This # scenario's `needs` is `-`, so no-client-option is not available to it. REASONS = ('missing-runtime',) @@ -118,6 +117,9 @@ def authorized_bucket(**api_kwargs): try: from b2sdk.v3 import B2Api, InMemoryAccountInfo except ImportError as error: + if not missing_runtime(error): + # b2sdk is installed but broken: an SDK regression, not a missing runtime + raise Failure('import', type(error).__name__) from error raise Amber('missing-runtime', 'b2sdk is not installed') from error api = B2Api(InMemoryAccountInfo(), **api_kwargs) step('authenticate', lambda: api.authorize_account('test-key-id', 'test-key', realm=realm)) diff --git a/.sdkharness/tests/resilience/api.retry_after_429 b/.sdkharness/tests/resilience/api.retry_after_429 index 2bad7d679..6468e8c9f 100755 --- a/.sdkharness/tests/resilience/api.retry_after_429 +++ b/.sdkharness/tests/resilience/api.retry_after_429 @@ -1,9 +1,8 @@ #!/usr/bin/env python3 """b2-sdk-python x api.retry_after_429. -Written from the reference check, bin/resilience/b2-sdk-python/upload.retry_503. -The contract is bin/resilience/README.md; the question is the api.retry_after_429 row of -bin/resilience/scenarios.tsv. +Written from the reference check, upload.retry_503 in this directory. +The question is the api.retry_after_429 scenario of the central sdkharness registry. Fault fault b2_list_file_names 429 too_many_requests retryAfter=2 (count 1), armed after setup Assert the end state: the listing names exactly the fixture; the recovery path, @@ -17,7 +16,7 @@ The Integration Checklist, Error Handling, 429: "the response may also include a https://www.backblaze.com/docs/cloud-storage-integration-checklist It exercises b2sdk from this exact repository checkout; -the API is taken from docs/sdks/b2-sdk-python/card.md. +the API is taken from the published b2sdk documentation. """ import json @@ -28,7 +27,7 @@ import urllib.request import uuid sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'lib')) -from loopback_guard import refusal # noqa: E402 +from loopback_guard import missing_runtime, refusal # noqa: E402 SLUG = 'b2-sdk-python' SCENARIO = 'api.retry_after_429' @@ -49,7 +48,7 @@ def is_faulted(e): FLOOR_S = 2.0 -# The closed reason set, mirrored from bin/resilience/README.md. This +# The closed reason set, fixed by the sdkharness resilience contract. This # scenario's `needs` is `-`, so no-client-option is not available to it. REASONS = ('missing-runtime',) @@ -123,6 +122,9 @@ def authorized_bucket(**api_kwargs): try: from b2sdk.v3 import B2Api, InMemoryAccountInfo except ImportError as error: + if not missing_runtime(error): + # b2sdk is installed but broken: an SDK regression, not a missing runtime + raise Failure('import', type(error).__name__) from error raise Amber('missing-runtime', 'b2sdk is not installed') from error api = B2Api(InMemoryAccountInfo(), **api_kwargs) step('authenticate', lambda: api.authorize_account('test-key-id', 'test-key', realm=realm)) diff --git a/.sdkharness/tests/resilience/api.retry_after_503 b/.sdkharness/tests/resilience/api.retry_after_503 index 79e5037b0..527b41e3e 100755 --- a/.sdkharness/tests/resilience/api.retry_after_503 +++ b/.sdkharness/tests/resilience/api.retry_after_503 @@ -1,9 +1,8 @@ #!/usr/bin/env python3 """b2-sdk-python x api.retry_after_503. -Written from the reference check, bin/resilience/b2-sdk-python/upload.retry_503. -The contract is bin/resilience/README.md; the question is the api.retry_after_503 row of -bin/resilience/scenarios.tsv. +Written from the reference check, upload.retry_503 in this directory. +The question is the api.retry_after_503 scenario of the central sdkharness registry. Fault fault b2_list_file_names 503 service_unavailable retryAfter=2 (count 1), armed after setup Assert the end state: the listing names exactly the fixture; the recovery path, @@ -18,7 +17,7 @@ before re-issuing the command." https://www.backblaze.com/docs/cloud-storage-integration-checklist It exercises b2sdk from this exact repository checkout; -the API is taken from docs/sdks/b2-sdk-python/card.md. +the API is taken from the published b2sdk documentation. """ import json @@ -29,7 +28,7 @@ import urllib.request import uuid sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'lib')) -from loopback_guard import refusal # noqa: E402 +from loopback_guard import missing_runtime, refusal # noqa: E402 SLUG = 'b2-sdk-python' SCENARIO = 'api.retry_after_503' @@ -50,7 +49,7 @@ def is_faulted(e): FLOOR_S = 2.0 -# The closed reason set, mirrored from bin/resilience/README.md. This +# The closed reason set, fixed by the sdkharness resilience contract. This # scenario's `needs` is `-`, so no-client-option is not available to it. REASONS = ('missing-runtime',) @@ -124,6 +123,9 @@ def authorized_bucket(**api_kwargs): try: from b2sdk.v3 import B2Api, InMemoryAccountInfo except ImportError as error: + if not missing_runtime(error): + # b2sdk is installed but broken: an SDK regression, not a missing runtime + raise Failure('import', type(error).__name__) from error raise Amber('missing-runtime', 'b2sdk is not installed') from error api = B2Api(InMemoryAccountInfo(), **api_kwargs) step('authenticate', lambda: api.authorize_account('test-key-id', 'test-key', realm=realm)) diff --git a/.sdkharness/tests/resilience/auth.clock_expiry b/.sdkharness/tests/resilience/auth.clock_expiry index 542035af9..8e935c209 100755 --- a/.sdkharness/tests/resilience/auth.clock_expiry +++ b/.sdkharness/tests/resilience/auth.clock_expiry @@ -1,9 +1,8 @@ #!/usr/bin/env python3 """b2-sdk-python x auth.clock_expiry. -Written from the reference check, bin/resilience/b2-sdk-python/upload.retry_503. -The contract is bin/resilience/README.md; the question is the auth.clock_expiry row of -bin/resilience/scenarios.tsv. +Written from the reference check, upload.retry_503 in this directory. +The question is the auth.clock_expiry scenario of the central sdkharness registry. Fault clock 86400001 -- POST /clock {advanceMs: 86400001}, after setup, so the account token the one live B2Api session holds is past its 24 h life. @@ -20,12 +19,12 @@ or expired_auth_token you should call b2_authorize_account again to get a new au https://www.backblaze.com/docs/cloud-storage-integration-checklist `needs: long-lived-session` is met: one B2Api over an InMemoryAccountInfo is -one session that outlives the virtual advance, and the card records the token -as "cached in an AccountInfo and auto-refreshed on expiry" (card.md, Auth model: -b2sdk/_internal/api.py:206, session.py:107, session.py:92). +one session that outlives the virtual advance, and the token is cached in the +AccountInfo and auto-refreshed on expiry (b2sdk/_internal/api.py, +b2sdk/_internal/session.py). It exercises b2sdk from this exact repository checkout; -the API is taken from docs/sdks/b2-sdk-python/card.md. +the API is taken from the published b2sdk documentation. """ import json @@ -35,7 +34,7 @@ import urllib.request import uuid sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'lib')) -from loopback_guard import refusal # noqa: E402 +from loopback_guard import missing_runtime, refusal # noqa: E402 SLUG = 'b2-sdk-python' SCENARIO = 'auth.clock_expiry' @@ -48,8 +47,8 @@ def is_faulted(e): return e['status'] == 401 and e['fault'] is None -# The closed reason set, mirrored from bin/resilience/README.md. This -# scenario's `needs` is `long-lived-session`; the card shows b2sdk meets it, +# The closed reason set, fixed by the sdkharness resilience contract. This +# scenario's `needs` is `long-lived-session`; b2sdk meets it, # so this check never emits no-client-option. REASONS = ('missing-runtime', 'no-client-option') @@ -123,6 +122,9 @@ def authorized_bucket(**api_kwargs): try: from b2sdk.v3 import B2Api, InMemoryAccountInfo except ImportError as error: + if not missing_runtime(error): + # b2sdk is installed but broken: an SDK regression, not a missing runtime + raise Failure('import', type(error).__name__) from error raise Amber('missing-runtime', 'b2sdk is not installed') from error api = B2Api(InMemoryAccountInfo(), **api_kwargs) step('authenticate', lambda: api.authorize_account('test-key-id', 'test-key', realm=realm)) diff --git a/.sdkharness/tests/resilience/auth.expired_401 b/.sdkharness/tests/resilience/auth.expired_401 index a3af2919e..dafee56c5 100755 --- a/.sdkharness/tests/resilience/auth.expired_401 +++ b/.sdkharness/tests/resilience/auth.expired_401 @@ -1,9 +1,8 @@ #!/usr/bin/env python3 """b2-sdk-python x auth.expired_401. -Written from the reference check, bin/resilience/b2-sdk-python/upload.retry_503. -The contract is bin/resilience/README.md; the question is the auth.expired_401 row of -bin/resilience/scenarios.tsv. +Written from the reference check, upload.retry_503 in this directory. +The question is the auth.expired_401 scenario of the central sdkharness registry. Fault fault b2_list_file_names 401 expired_auth_token (count 1), armed after setup Assert the recovery path, from GET /journal: exactly one injected 401 on @@ -20,7 +19,7 @@ or expired_auth_token you should call b2_authorize_account again to get a new au https://www.backblaze.com/docs/cloud-storage-integration-checklist It exercises b2sdk from this exact repository checkout; -the API is taken from docs/sdks/b2-sdk-python/card.md. +the API is taken from the published b2sdk documentation. """ import json @@ -30,7 +29,7 @@ import urllib.request import uuid sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'lib')) -from loopback_guard import refusal # noqa: E402 +from loopback_guard import missing_runtime, refusal # noqa: E402 SLUG = 'b2-sdk-python' SCENARIO = 'auth.expired_401' @@ -43,7 +42,7 @@ def is_faulted(e): return e['endpoint'] == 'b2_list_file_names' and e['fault'] == 'injected' and e['status'] == 401 -# The closed reason set, mirrored from bin/resilience/README.md. This +# The closed reason set, fixed by the sdkharness resilience contract. This # scenario's `needs` is `-`, so no-client-option is not available to it. REASONS = ('missing-runtime',) @@ -117,6 +116,9 @@ def authorized_bucket(**api_kwargs): try: from b2sdk.v3 import B2Api, InMemoryAccountInfo except ImportError as error: + if not missing_runtime(error): + # b2sdk is installed but broken: an SDK regression, not a missing runtime + raise Failure('import', type(error).__name__) from error raise Amber('missing-runtime', 'b2sdk is not installed') from error api = B2Api(InMemoryAccountInfo(), **api_kwargs) step('authenticate', lambda: api.authorize_account('test-key-id', 'test-key', realm=realm)) diff --git a/.sdkharness/tests/resilience/download.retry_503 b/.sdkharness/tests/resilience/download.retry_503 index eac3982a8..b8b24866f 100755 --- a/.sdkharness/tests/resilience/download.retry_503 +++ b/.sdkharness/tests/resilience/download.retry_503 @@ -1,9 +1,8 @@ #!/usr/bin/env python3 """b2-sdk-python x download.retry_503. -Written from the reference check, bin/resilience/b2-sdk-python/upload.retry_503. -The contract is bin/resilience/README.md; the question is the download.retry_503 row of -bin/resilience/scenarios.tsv. +Written from the reference check, upload.retry_503 in this directory. +The question is the download.retry_503 scenario of the central sdkharness registry. Fault fault b2_download_file_by_id 503 service_unavailable (count 1), armed after the fixture is uploaded @@ -18,7 +17,7 @@ using an exponential backoff starting with 1 second." https://www.backblaze.com/docs/cloud-storage-integration-checklist It exercises b2sdk from this exact repository checkout; -the API is taken from docs/sdks/b2-sdk-python/card.md. +the API is taken from the published b2sdk documentation. """ import io @@ -29,7 +28,7 @@ import urllib.request import uuid sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'lib')) -from loopback_guard import refusal # noqa: E402 +from loopback_guard import missing_runtime, refusal # noqa: E402 SLUG = 'b2-sdk-python' SCENARIO = 'download.retry_503' @@ -46,7 +45,7 @@ def is_faulted(e): ) -# The closed reason set, mirrored from bin/resilience/README.md. This +# The closed reason set, fixed by the sdkharness resilience contract. This # scenario's `needs` is `-`, so no-client-option is not available to it. REASONS = ('missing-runtime',) @@ -120,6 +119,9 @@ def authorized_bucket(**api_kwargs): try: from b2sdk.v3 import B2Api, InMemoryAccountInfo except ImportError as error: + if not missing_runtime(error): + # b2sdk is installed but broken: an SDK regression, not a missing runtime + raise Failure('import', type(error).__name__) from error raise Amber('missing-runtime', 'b2sdk is not installed') from error api = B2Api(InMemoryAccountInfo(), **api_kwargs) step('authenticate', lambda: api.authorize_account('test-key-id', 'test-key', realm=realm)) diff --git a/.sdkharness/tests/resilience/part.retry_503 b/.sdkharness/tests/resilience/part.retry_503 index d8cdbe477..b534a21d0 100755 --- a/.sdkharness/tests/resilience/part.retry_503 +++ b/.sdkharness/tests/resilience/part.retry_503 @@ -1,9 +1,8 @@ #!/usr/bin/env python3 """b2-sdk-python x part.retry_503. -Written from the reference check, bin/resilience/b2-sdk-python/upload.retry_503. -The contract is bin/resilience/README.md; the question is the part.retry_503 row of -bin/resilience/scenarios.tsv. +Written from the reference check, upload.retry_503 in this directory. +The question is the part.retry_503 scenario of the central sdkharness registry. Fault fault b2_upload_part 503 service_unavailable (count 1), armed after setup, so the first part of a three-part large file gets it (one upload worker) @@ -23,7 +22,7 @@ upload using the new URL and auth key pair"; among them: https://www.backblaze.com/docs/cloud-storage-integration-checklist It exercises b2sdk from this exact repository checkout; -the API is taken from docs/sdks/b2-sdk-python/card.md. +the API is taken from the published b2sdk documentation. """ import io @@ -34,7 +33,7 @@ import urllib.request import uuid sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'lib')) -from loopback_guard import refusal # noqa: E402 +from loopback_guard import missing_runtime, refusal # noqa: E402 SLUG = 'b2-sdk-python' SCENARIO = 'part.retry_503' @@ -49,7 +48,7 @@ def is_faulted(e): PARTS = 3 -# The closed reason set, mirrored from bin/resilience/README.md. This +# The closed reason set, fixed by the sdkharness resilience contract. This # scenario's `needs` is `-`, so no-client-option is not available to it. REASONS = ('missing-runtime',) @@ -123,6 +122,9 @@ def authorized_bucket(**api_kwargs): try: from b2sdk.v3 import B2Api, InMemoryAccountInfo except ImportError as error: + if not missing_runtime(error): + # b2sdk is installed but broken: an SDK regression, not a missing runtime + raise Failure('import', type(error).__name__) from error raise Amber('missing-runtime', 'b2sdk is not installed') from error api = B2Api(InMemoryAccountInfo(), **api_kwargs) step('authenticate', lambda: api.authorize_account('test-key-id', 'test-key', realm=realm)) diff --git a/.sdkharness/tests/resilience/upload.cap_exceeded_403 b/.sdkharness/tests/resilience/upload.cap_exceeded_403 index 2f0dd3533..161f4f394 100755 --- a/.sdkharness/tests/resilience/upload.cap_exceeded_403 +++ b/.sdkharness/tests/resilience/upload.cap_exceeded_403 @@ -1,9 +1,8 @@ #!/usr/bin/env python3 """b2-sdk-python x upload.cap_exceeded_403. -Written from the reference check, bin/resilience/b2-sdk-python/upload.retry_503. -The contract is bin/resilience/README.md; the question is the upload.cap_exceeded_403 row of -bin/resilience/scenarios.tsv. +Written from the reference check, upload.retry_503 in this directory. +The question is the upload.cap_exceeded_403 scenario of the central sdkharness registry. Fault fault b2_upload_file 403 cap_exceeded (count 1), armed after setup Assert the end state: the upload RAISES a b2sdk error to the caller; and the @@ -18,7 +17,7 @@ inform the user they need to log in and review their B2 Caps." https://www.backblaze.com/docs/cloud-storage-integration-checklist It exercises b2sdk from this exact repository checkout; -the API is taken from docs/sdks/b2-sdk-python/card.md. +the API is taken from the published b2sdk documentation. """ import json @@ -28,7 +27,7 @@ import urllib.request import uuid sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'lib')) -from loopback_guard import refusal # noqa: E402 +from loopback_guard import missing_runtime, refusal # noqa: E402 SLUG = 'b2-sdk-python' SCENARIO = 'upload.cap_exceeded_403' @@ -41,7 +40,7 @@ def is_faulted(e): return e['endpoint'] == 'b2_upload_file' and e['fault'] == 'injected' and e['status'] == 403 -# The closed reason set, mirrored from bin/resilience/README.md. This +# The closed reason set, fixed by the sdkharness resilience contract. This # scenario's `needs` is `-`, so no-client-option is not available to it. REASONS = ('missing-runtime',) @@ -115,6 +114,9 @@ def authorized_bucket(**api_kwargs): try: from b2sdk.v3 import B2Api, InMemoryAccountInfo except ImportError as error: + if not missing_runtime(error): + # b2sdk is installed but broken: an SDK regression, not a missing runtime + raise Failure('import', type(error).__name__) from error raise Amber('missing-runtime', 'b2sdk is not installed') from error api = B2Api(InMemoryAccountInfo(), **api_kwargs) step('authenticate', lambda: api.authorize_account('test-key-id', 'test-key', realm=realm)) diff --git a/.sdkharness/tests/resilience/upload.expired_token_401 b/.sdkharness/tests/resilience/upload.expired_token_401 index a5dc9bb72..32c58f0ca 100755 --- a/.sdkharness/tests/resilience/upload.expired_token_401 +++ b/.sdkharness/tests/resilience/upload.expired_token_401 @@ -1,9 +1,8 @@ #!/usr/bin/env python3 """b2-sdk-python x upload.expired_token_401. -Written from the reference check, bin/resilience/b2-sdk-python/upload.retry_503. -The contract is bin/resilience/README.md; the question is the upload.expired_token_401 row of -bin/resilience/scenarios.tsv. +Written from the reference check, upload.retry_503 in this directory. +The question is the upload.expired_token_401 scenario of the central sdkharness registry. Fault fault b2_upload_file 401 expired_auth_token (count 1), armed after setup Assert the recovery path, from GET /journal: exactly one faulted b2_upload_file, @@ -20,7 +19,7 @@ and auth key pair". https://www.backblaze.com/docs/cloud-storage-integration-checklist It exercises b2sdk from this exact repository checkout; -the API is taken from docs/sdks/b2-sdk-python/card.md. +the API is taken from the published b2sdk documentation. """ import hashlib @@ -32,7 +31,7 @@ import urllib.request import uuid sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'lib')) -from loopback_guard import refusal # noqa: E402 +from loopback_guard import missing_runtime, refusal # noqa: E402 SLUG = 'b2-sdk-python' SCENARIO = 'upload.expired_token_401' @@ -45,7 +44,7 @@ def is_faulted(e): return e['endpoint'] == 'b2_upload_file' and e['fault'] == 'injected' and e['status'] == 401 -# The closed reason set, mirrored from bin/resilience/README.md. This +# The closed reason set, fixed by the sdkharness resilience contract. This # scenario's `needs` is `-`, so no-client-option is not available to it. REASONS = ('missing-runtime',) @@ -119,6 +118,9 @@ def authorized_bucket(**api_kwargs): try: from b2sdk.v3 import B2Api, InMemoryAccountInfo except ImportError as error: + if not missing_runtime(error): + # b2sdk is installed but broken: an SDK regression, not a missing runtime + raise Failure('import', type(error).__name__) from error raise Amber('missing-runtime', 'b2sdk is not installed') from error api = B2Api(InMemoryAccountInfo(), **api_kwargs) step('authenticate', lambda: api.authorize_account('test-key-id', 'test-key', realm=realm)) diff --git a/.sdkharness/tests/resilience/upload.get_url_503 b/.sdkharness/tests/resilience/upload.get_url_503 index abebbb3b8..89ba80e73 100755 --- a/.sdkharness/tests/resilience/upload.get_url_503 +++ b/.sdkharness/tests/resilience/upload.get_url_503 @@ -1,9 +1,8 @@ #!/usr/bin/env python3 """b2-sdk-python x upload.get_url_503. -Written from the reference check, bin/resilience/b2-sdk-python/upload.retry_503. -The contract is bin/resilience/README.md; the question is the upload.get_url_503 row of -bin/resilience/scenarios.tsv. +Written from the reference check, upload.retry_503 in this directory. +The question is the upload.get_url_503 scenario of the central sdkharness registry. Fault fault b2_get_upload_url 503 service_unavailable (count 1), armed after setup, so the first attempt to obtain an upload URL gets it @@ -19,7 +18,7 @@ using an exponential backoff starting with 1 second." https://www.backblaze.com/docs/cloud-storage-integration-checklist It exercises b2sdk from this exact repository checkout; -the API is taken from docs/sdks/b2-sdk-python/card.md. +the API is taken from the published b2sdk documentation. """ import hashlib @@ -31,7 +30,7 @@ import urllib.request import uuid sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'lib')) -from loopback_guard import refusal # noqa: E402 +from loopback_guard import missing_runtime, refusal # noqa: E402 SLUG = 'b2-sdk-python' SCENARIO = 'upload.get_url_503' @@ -44,7 +43,7 @@ def is_faulted(e): return e['endpoint'] == 'b2_get_upload_url' and e['fault'] == 'injected' and e['status'] == 503 -# The closed reason set, mirrored from bin/resilience/README.md. This +# The closed reason set, fixed by the sdkharness resilience contract. This # scenario's `needs` is `-`, so no-client-option is not available to it. REASONS = ('missing-runtime',) @@ -118,6 +117,9 @@ def authorized_bucket(**api_kwargs): try: from b2sdk.v3 import B2Api, InMemoryAccountInfo except ImportError as error: + if not missing_runtime(error): + # b2sdk is installed but broken: an SDK regression, not a missing runtime + raise Failure('import', type(error).__name__) from error raise Amber('missing-runtime', 'b2sdk is not installed') from error api = B2Api(InMemoryAccountInfo(), **api_kwargs) step('authenticate', lambda: api.authorize_account('test-key-id', 'test-key', realm=realm)) diff --git a/.sdkharness/tests/resilience/upload.reset_before_response b/.sdkharness/tests/resilience/upload.reset_before_response index 1903e153d..77d3267e4 100755 --- a/.sdkharness/tests/resilience/upload.reset_before_response +++ b/.sdkharness/tests/resilience/upload.reset_before_response @@ -1,9 +1,8 @@ #!/usr/bin/env python3 """b2-sdk-python x upload.reset_before_response. -Written from the reference check, bin/resilience/b2-sdk-python/upload.retry_503. -The contract is bin/resilience/README.md; the question is the upload.reset_before_response row of -bin/resilience/scenarios.tsv. +Written from the reference check, upload.retry_503 in this directory. +The question is the upload.reset_before_response scenario of the central sdkharness registry. Fault wire b2_upload_file reset-before-response (count 1), armed after setup: the upload IS dispatched (state changed), then the connection drops with no @@ -20,7 +19,7 @@ upload using the new URL and auth key pair"; among them: https://www.backblaze.com/docs/cloud-storage-integration-checklist It exercises b2sdk from this exact repository checkout; -the API is taken from docs/sdks/b2-sdk-python/card.md. +the API is taken from the published b2sdk documentation. """ import hashlib @@ -32,7 +31,7 @@ import urllib.request import uuid sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'lib')) -from loopback_guard import refusal # noqa: E402 +from loopback_guard import missing_runtime, refusal # noqa: E402 SLUG = 'b2-sdk-python' SCENARIO = 'upload.reset_before_response' @@ -45,7 +44,7 @@ def is_faulted(e): return e['endpoint'] == 'b2_upload_file' and e['fault'] == 'reset-before-response' -# The closed reason set, mirrored from bin/resilience/README.md. This +# The closed reason set, fixed by the sdkharness resilience contract. This # scenario's `needs` is `-`, so no-client-option is not available to it. REASONS = ('missing-runtime',) @@ -119,6 +118,9 @@ def authorized_bucket(**api_kwargs): try: from b2sdk.v3 import B2Api, InMemoryAccountInfo except ImportError as error: + if not missing_runtime(error): + # b2sdk is installed but broken: an SDK regression, not a missing runtime + raise Failure('import', type(error).__name__) from error raise Amber('missing-runtime', 'b2sdk is not installed') from error api = B2Api(InMemoryAccountInfo(), **api_kwargs) step('authenticate', lambda: api.authorize_account('test-key-id', 'test-key', realm=realm)) diff --git a/.sdkharness/tests/resilience/upload.reset_mid_request b/.sdkharness/tests/resilience/upload.reset_mid_request index a4e116427..a78d35ede 100755 --- a/.sdkharness/tests/resilience/upload.reset_mid_request +++ b/.sdkharness/tests/resilience/upload.reset_mid_request @@ -1,9 +1,8 @@ #!/usr/bin/env python3 """b2-sdk-python x upload.reset_mid_request. -Written from the reference check, bin/resilience/b2-sdk-python/upload.retry_503. -The contract is bin/resilience/README.md; the question is the upload.reset_mid_request row of -bin/resilience/scenarios.tsv. +Written from the reference check, upload.retry_503 in this directory. +The question is the upload.reset_mid_request scenario of the central sdkharness registry. Fault wire b2_upload_file reset-mid-request (count 1), armed after setup: the connection drops after the first request-body chunk, never dispatched @@ -19,7 +18,7 @@ upload using the new URL and auth key pair"; among them: https://www.backblaze.com/docs/cloud-storage-integration-checklist It exercises b2sdk from this exact repository checkout; -the API is taken from docs/sdks/b2-sdk-python/card.md. +the API is taken from the published b2sdk documentation. """ import hashlib @@ -31,7 +30,7 @@ import urllib.request import uuid sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'lib')) -from loopback_guard import refusal # noqa: E402 +from loopback_guard import missing_runtime, refusal # noqa: E402 SLUG = 'b2-sdk-python' SCENARIO = 'upload.reset_mid_request' @@ -44,7 +43,7 @@ def is_faulted(e): return e['endpoint'] == 'b2_upload_file' and e['fault'] == 'reset-mid-request' -# The closed reason set, mirrored from bin/resilience/README.md. This +# The closed reason set, fixed by the sdkharness resilience contract. This # scenario's `needs` is `-`, so no-client-option is not available to it. REASONS = ('missing-runtime',) @@ -118,6 +117,9 @@ def authorized_bucket(**api_kwargs): try: from b2sdk.v3 import B2Api, InMemoryAccountInfo except ImportError as error: + if not missing_runtime(error): + # b2sdk is installed but broken: an SDK regression, not a missing runtime + raise Failure('import', type(error).__name__) from error raise Amber('missing-runtime', 'b2sdk is not installed') from error api = B2Api(InMemoryAccountInfo(), **api_kwargs) step('authenticate', lambda: api.authorize_account('test-key-id', 'test-key', realm=realm)) diff --git a/.sdkharness/tests/resilience/upload.retry_408 b/.sdkharness/tests/resilience/upload.retry_408 index 2399a255d..999835f82 100755 --- a/.sdkharness/tests/resilience/upload.retry_408 +++ b/.sdkharness/tests/resilience/upload.retry_408 @@ -1,9 +1,8 @@ #!/usr/bin/env python3 """b2-sdk-python x upload.retry_408. -Written from the reference check, bin/resilience/b2-sdk-python/upload.retry_503. -The contract is bin/resilience/README.md; the question is the upload.retry_408 row of -bin/resilience/scenarios.tsv. +Written from the reference check, upload.retry_503 in this directory. +The question is the upload.retry_408 scenario of the central sdkharness registry. Fault fault b2_upload_file 408 request_timeout (count 1), armed after setup Assert the recovery path, from GET /journal: exactly one faulted b2_upload_file, @@ -20,7 +19,7 @@ upload using the new URL and auth key pair"; among them: https://www.backblaze.com/docs/cloud-storage-integration-checklist It exercises b2sdk from this exact repository checkout; -the API is taken from docs/sdks/b2-sdk-python/card.md. +the API is taken from the published b2sdk documentation. """ import hashlib @@ -32,7 +31,7 @@ import urllib.request import uuid sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'lib')) -from loopback_guard import refusal # noqa: E402 +from loopback_guard import missing_runtime, refusal # noqa: E402 SLUG = 'b2-sdk-python' SCENARIO = 'upload.retry_408' @@ -45,7 +44,7 @@ def is_faulted(e): return e['endpoint'] == 'b2_upload_file' and e['fault'] == 'injected' and e['status'] == 408 -# The closed reason set, mirrored from bin/resilience/README.md. This +# The closed reason set, fixed by the sdkharness resilience contract. This # scenario's `needs` is `-`, so no-client-option is not available to it. REASONS = ('missing-runtime',) @@ -119,6 +118,9 @@ def authorized_bucket(**api_kwargs): try: from b2sdk.v3 import B2Api, InMemoryAccountInfo except ImportError as error: + if not missing_runtime(error): + # b2sdk is installed but broken: an SDK regression, not a missing runtime + raise Failure('import', type(error).__name__) from error raise Amber('missing-runtime', 'b2sdk is not installed') from error api = B2Api(InMemoryAccountInfo(), **api_kwargs) step('authenticate', lambda: api.authorize_account('test-key-id', 'test-key', realm=realm)) diff --git a/.sdkharness/tests/resilience/upload.retry_500 b/.sdkharness/tests/resilience/upload.retry_500 index 84a476a7c..189d00689 100755 --- a/.sdkharness/tests/resilience/upload.retry_500 +++ b/.sdkharness/tests/resilience/upload.retry_500 @@ -1,9 +1,8 @@ #!/usr/bin/env python3 """b2-sdk-python x upload.retry_500. -Written from the reference check, bin/resilience/b2-sdk-python/upload.retry_503. -The contract is bin/resilience/README.md; the question is the upload.retry_500 row of -bin/resilience/scenarios.tsv. +Written from the reference check, upload.retry_503 in this directory. +The question is the upload.retry_500 scenario of the central sdkharness registry. Fault fault b2_upload_file 500 internal_error (count 1), armed after setup; asserted on the 500 STATUS only -- the code string is not doc-sourced (PROVENANCE.md) @@ -19,7 +18,7 @@ upload using the new URL and auth key pair"; among them: https://www.backblaze.com/docs/cloud-storage-integration-checklist It exercises b2sdk from this exact repository checkout; -the API is taken from docs/sdks/b2-sdk-python/card.md. +the API is taken from the published b2sdk documentation. """ import hashlib @@ -31,7 +30,7 @@ import urllib.request import uuid sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'lib')) -from loopback_guard import refusal # noqa: E402 +from loopback_guard import missing_runtime, refusal # noqa: E402 SLUG = 'b2-sdk-python' SCENARIO = 'upload.retry_500' @@ -44,7 +43,7 @@ def is_faulted(e): return e['endpoint'] == 'b2_upload_file' and e['fault'] == 'injected' and e['status'] == 500 -# The closed reason set, mirrored from bin/resilience/README.md. This +# The closed reason set, fixed by the sdkharness resilience contract. This # scenario's `needs` is `-`, so no-client-option is not available to it. REASONS = ('missing-runtime',) @@ -118,6 +117,9 @@ def authorized_bucket(**api_kwargs): try: from b2sdk.v3 import B2Api, InMemoryAccountInfo except ImportError as error: + if not missing_runtime(error): + # b2sdk is installed but broken: an SDK regression, not a missing runtime + raise Failure('import', type(error).__name__) from error raise Amber('missing-runtime', 'b2sdk is not installed') from error api = B2Api(InMemoryAccountInfo(), **api_kwargs) step('authenticate', lambda: api.authorize_account('test-key-id', 'test-key', realm=realm)) diff --git a/.sdkharness/tests/resilience/upload.retry_503 b/.sdkharness/tests/resilience/upload.retry_503 index 65708c511..7d04a5cd2 100755 --- a/.sdkharness/tests/resilience/upload.retry_503 +++ b/.sdkharness/tests/resilience/upload.retry_503 @@ -2,9 +2,8 @@ """THE REFERENCE CHECK -- b2-sdk-python x upload.retry_503. Every other resilience check is written from this one, the way -bin/conformance/b2-sdk-python/files.upload is for conformance. The contract is -bin/resilience/README.md; the question is the upload.retry_503 row of -bin/resilience/scenarios.tsv. +conformance/files.upload is for conformance. The question is the upload.retry_503 +scenario of the central sdkharness registry. Fault fault b2_upload_file 503 service_unavailable (count 1), armed after setup, so the first upload attempt is the one that gets it @@ -23,7 +22,7 @@ new URL and auth key pair". https://www.backblaze.com/docs/cloud-storage-integration-checklist It exercises b2sdk from this exact repository checkout; -the API is taken from docs/sdks/b2-sdk-python/card.md. +the API is taken from the published b2sdk documentation. """ import hashlib @@ -35,14 +34,14 @@ import urllib.request import uuid sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'lib')) -from loopback_guard import refusal # noqa: E402 +from loopback_guard import missing_runtime, refusal # noqa: E402 SLUG = 'b2-sdk-python' SCENARIO = 'upload.retry_503' OBJECT_NAME = 'res/retry_503.txt' FAULT = {'on': 'b2_upload_file', 'status': 503, 'code': 'service_unavailable', 'count': 1} -# The closed reason set, mirrored from bin/resilience/README.md. This +# The closed reason set, fixed by the sdkharness resilience contract. This # scenario's `needs` is `-`, so no-client-option is not available to it. REASONS = ('missing-runtime',) @@ -97,6 +96,9 @@ def run() -> None: try: from b2sdk.v3 import B2Api, InMemoryAccountInfo except ImportError as error: + if not missing_runtime(error): + # b2sdk is installed but broken: an SDK regression, not a missing runtime + raise Failure('import', type(error).__name__) from error raise Amber('missing-runtime', 'b2sdk is not installed') from error api = B2Api(InMemoryAccountInfo()) diff --git a/.sdkharness/tests/resilience/upload.stall b/.sdkharness/tests/resilience/upload.stall index 7c1949a5f..28eeceed2 100755 --- a/.sdkharness/tests/resilience/upload.stall +++ b/.sdkharness/tests/resilience/upload.stall @@ -1,13 +1,12 @@ #!/usr/bin/env python3 """b2-sdk-python x upload.stall. -Written from the reference check, bin/resilience/b2-sdk-python/upload.retry_503. -The contract is bin/resilience/README.md; the question is the upload.stall row of -bin/resilience/scenarios.tsv. +Written from the reference check, upload.retry_503 in this directory. +The question is the upload.stall scenario of the central sdkharness registry. Fault wire b2_upload_file stall ms=60000 -- NOT ARMED. The scenario needs a client request timeout short enough to beat a 60 s stall (`needs: request-timeout`) -Assert nothing: docs/sdks/b2-sdk-python/card.md cites no request-timeout option, so +Assert nothing: b2sdk documents no request-timeout option, so the check reports no-client-option instead of guessing at one The expected behaviour is B2's, not the tool's. @@ -18,7 +17,7 @@ upload using the new URL and auth key pair"; among them: https://www.backblaze.com/docs/cloud-storage-integration-checklist It exercises b2sdk from this exact repository checkout; -the API is taken from docs/sdks/b2-sdk-python/card.md. +the API is taken from the published b2sdk documentation. """ import json @@ -28,7 +27,7 @@ import urllib.request import uuid sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'lib')) -from loopback_guard import refusal # noqa: E402 +from loopback_guard import missing_runtime, refusal # noqa: E402 SLUG = 'b2-sdk-python' SCENARIO = 'upload.stall' @@ -41,7 +40,7 @@ def is_faulted(e): return e['endpoint'] == 'b2_upload_file' and e['fault'] == 'stall' -# The closed reason set, mirrored from bin/resilience/README.md. This +# The closed reason set, fixed by the sdkharness resilience contract. This # scenario's `needs` is `request-timeout`, so no-client-option is available to it. REASONS = ('missing-runtime', 'no-client-option') @@ -115,6 +114,9 @@ def authorized_bucket(**api_kwargs): try: from b2sdk.v3 import B2Api, InMemoryAccountInfo except ImportError as error: + if not missing_runtime(error): + # b2sdk is installed but broken: an SDK regression, not a missing runtime + raise Failure('import', type(error).__name__) from error raise Amber('missing-runtime', 'b2sdk is not installed') from error api = B2Api(InMemoryAccountInfo(), **api_kwargs) step('authenticate', lambda: api.authorize_account('test-key-id', 'test-key', realm=realm)) @@ -125,11 +127,11 @@ def authorized_bucket(**api_kwargs): return api, bucket -# What the card was searched for, and why it does not settle the precondition. -# Only sdk-inspector reads the clone, so this check never looks past the card. +# Why this scenario cannot be asked. The published b2sdk documentation names no +# request-timeout option, so the precondition cannot be settled from outside. UNSETTLED = ( - "docs/sdks/b2-sdk-python/card.md cites no request-timeout option: B2HttpApiConfig's " - 'cited parameters are http_session_factory and _raw_api_class, and no citation names ' + "b2sdk documents no request-timeout option: B2HttpApiConfig's " + 'documented parameters are http_session_factory and _raw_api_class, and nothing names ' 'the timeout B2Http passes to requests or a way to shorten it' ) @@ -138,11 +140,14 @@ def run() -> None: try: import b2sdk.v3 # noqa: F401 -- only presence is asked except ImportError as error: + if not missing_runtime(error): + # b2sdk is installed but broken: an SDK regression, not a missing runtime + raise Failure('import', type(error).__name__) from error raise Amber('missing-runtime', 'b2sdk is not installed') from error note( 'unconfirmed, not absent: an http_session_factory returning a Session that forces a ' - 'short timeout MIGHT meet the need, but the card marks session-level behaviour as ' - 'inferred; an sdk-inspector re-inspection asking what timeout b2http.py passes to ' + 'short timeout MIGHT meet the need, but session-level behaviour is not documented; ' + 'reading what timeout b2http.py passes to ' 'Session.request, and whether it is configurable, would settle it' ) raise Amber('no-client-option', UNSETTLED) diff --git a/changelog.d/+sdkharness-fail-not-skip.infrastructure.md b/changelog.d/+sdkharness-fail-not-skip.infrastructure.md new file mode 100644 index 000000000..9d77740af --- /dev/null +++ b/changelog.d/+sdkharness-fail-not-skip.infrastructure.md @@ -0,0 +1 @@ +Repository-owned sdkharness conformance and resilience checks now report an authorization error, access denied, a connection error against the simulator, or an SDK `ImportError` as `FAIL` instead of `COULD-NOT-RUN`/`SKIP`, strip proxy environment variables so a stray proxy cannot change a result, and no longer refer to files that exist only in the central harness. diff --git a/test/unit/test_sdkharness_fail_not_skip.py b/test/unit/test_sdkharness_fail_not_skip.py new file mode 100644 index 000000000..79b1fc9fb --- /dev/null +++ b/test/unit/test_sdkharness_fail_not_skip.py @@ -0,0 +1,176 @@ +###################################################################### +# +# File: test/unit/test_sdkharness_fail_not_skip.py +# +# Copyright 2026 Backblaze Inc. All Rights Reserved. +# +# License https://www.backblaze.com/using_b2_code.html +# +###################################################################### +from __future__ import annotations + +import os +import socket +import subprocess +import sys +from importlib.util import module_from_spec, spec_from_file_location +from pathlib import Path + +import pytest + +ROOT = Path(__file__).parents[2] +LIB = ROOT / '.sdkharness' / 'tests' / 'lib' +CONFORMANCE = ROOT / '.sdkharness' / 'tests' / 'conformance' +LEAVES = ('files.upload', 'files.hide', 'keys.multi_bucket') + + +def load(name): + spec = spec_from_file_location(f'sdkharness_{name}', LIB / f'{name}.py') + module = module_from_spec(spec) + sys.path.insert(0, str(LIB)) + try: + spec.loader.exec_module(module) + finally: + sys.path.remove(str(LIB)) + return module + + +def dead_loopback_url(): + with socket.socket() as sock: + sock.bind(('127.0.0.1', 0)) + port = sock.getsockname()[1] + return f'http://127.0.0.1:{port}' # the socket is closed again: nothing listens there + + +def run_leaf(leaf, simulator_url, extra_path=None): + env = { + name: value + for name, value in os.environ.items() + if not name.startswith(('B2_', 'CONFORMANCE_', 'RESILIENCE_', 'SDKHARNESS_')) + } + python_path = [str(ROOT)] + if extra_path: + python_path.insert(0, str(extra_path)) + env.update( + PYTHONPATH=os.pathsep.join(python_path), + CONFORMANCE_TARGET='simulator', + CONFORMANCE_SIMULATOR_URL=simulator_url, + ) + return subprocess.run( + [sys.executable, str(CONFORMANCE / leaf)], + env=env, + stdin=subprocess.DEVNULL, + capture_output=True, + text=True, + timeout=120, + check=False, + ) + + +def dispatcher_verdict(contract, leaf, completed): + return contract.translate('conformance', leaf, completed.returncode, completed.stdout) + + +@pytest.mark.parametrize('leaf', LEAVES) +def test_dead_simulator_port_is_a_fail_not_a_skip(leaf): + contract = load('contract') + completed = run_leaf(leaf, dead_loopback_url()) + assert completed.returncode == 1, completed.stdout + assert 'COULD-NOT-RUN' not in completed.stdout + outcome, _reason, code = dispatcher_verdict(contract, leaf, completed) + assert (outcome, code) == ('FAIL', 1) + + +@pytest.mark.parametrize('leaf', LEAVES) +def test_sdk_import_error_is_a_fail_not_a_skip(leaf, tmp_path): + broken = tmp_path / 'b2sdk' + broken.mkdir() + (broken / '__init__.py').write_text('raise ImportError("circular import inside the SDK")\n') + contract = load('contract') + completed = run_leaf(leaf, dead_loopback_url(), extra_path=tmp_path) + assert completed.returncode == 1, completed.stdout + assert 'COULD-NOT-RUN' not in completed.stdout + assert 'ImportError' in completed.stdout + outcome, _reason, code = dispatcher_verdict(contract, leaf, completed) + assert (outcome, code) == ('FAIL', 1) + + +@pytest.mark.parametrize('leaf', LEAVES) +def test_a_missing_b2sdk_module_is_still_could_not_run(leaf, tmp_path): + # `import b2sdk` raising ModuleNotFoundError(name='b2sdk') is a genuinely missing runtime. + missing = tmp_path / 'b2sdk' + missing.mkdir() + (missing / '__init__.py').write_text( + "raise ModuleNotFoundError(\"No module named 'b2sdk'\", name='b2sdk')\n" + ) + contract = load('contract') + completed = run_leaf(leaf, dead_loopback_url(), extra_path=tmp_path) + assert completed.returncode == 0, completed.stdout + outcome, reason, code = dispatcher_verdict(contract, leaf, completed) + assert (outcome, code) == ('SKIP', 0) + assert reason.startswith('missing-runtime') + + +def test_missing_runtime_is_only_b2sdk_itself_not_found(): + guard = load('loopback_guard') + assert guard.missing_runtime(ModuleNotFoundError('x', name='b2sdk')) + assert not guard.missing_runtime(ModuleNotFoundError('x', name='b2sdk.v3.exception')) + assert not guard.missing_runtime(ModuleNotFoundError('x', name='requests')) + assert not guard.missing_runtime(ImportError('cannot import name')) + + +@pytest.mark.parametrize( + 'reason', + [ + 'unreachable -- B2ConnectionError at step authenticate', + 'unauthorized -- Unauthorized at step authenticate', + 'unauthorized -- AccessDenied at step create bucket', + 'unreachable -- ServiceError at step upload', + 'missing-runtime-ish -- unknown reason', + ], +) +def test_dispatcher_turns_non_genuine_could_not_run_reasons_into_fail(reason): + contract = load('contract') + line = f'CONFORMANCE b2-sdk-python files.upload @simulator: COULD-NOT-RUN ({reason})\n' + outcome, _reason, code = contract.translate('conformance', 'files.upload', 0, line) + assert (outcome, code) == ('FAIL', 1) + + +@pytest.mark.parametrize('reason', ['no-realm-option', 'missing-runtime', 'no-client-option']) +def test_dispatcher_keeps_genuine_could_not_run_reasons_as_skip(reason): + contract = load('contract') + line = f'CONFORMANCE b2-sdk-python files.upload @simulator: COULD-NOT-RUN ({reason} -- why)\n' + assert contract.translate('conformance', 'files.upload', 0, line) == ( + 'SKIP', + f'{reason} -- why', + 0, + ) + + +def test_child_environment_drops_proxies_and_pins_no_proxy(): + contract = load('contract') + parent = { + 'SDKHARNESS_SIMULATOR_URL': 'http://127.0.0.1:8180', + 'HTTP_PROXY': 'http://127.0.0.1:9', + 'https_proxy': 'http://127.0.0.1:9', + 'ALL_PROXY': 'socks5://127.0.0.1:9', + 'NO_PROXY': 'example.invalid', + } + child = contract.child_environment('conformance', parent) + assert not { + name for name in child if name.lower().endswith('_proxy') and 'no' not in name.lower() + } + assert child['NO_PROXY'] == child['no_proxy'] == '127.0.0.1' + assert parent['HTTP_PROXY'] == 'http://127.0.0.1:9' # the caller's mapping is untouched + + +def test_leaf_refusal_scrubs_the_proxy_environment(monkeypatch): + guard = load('loopback_guard') + monkeypatch.setenv('HTTP_PROXY', 'http://127.0.0.1:9') + monkeypatch.setenv('https_proxy', 'http://127.0.0.1:9') + monkeypatch.setenv('NO_PROXY', 'example.invalid') + monkeypatch.delenv('CONFORMANCE_TARGET', raising=False) + monkeypatch.setenv('CONFORMANCE_SIMULATOR_URL', 'http://127.0.0.1:8180') + assert guard.refusal('conformance') is None + assert 'HTTP_PROXY' not in os.environ and 'https_proxy' not in os.environ + assert os.environ['NO_PROXY'] == '127.0.0.1' From fbda229c972ee6c0b014b99755b6c71da30b6d9e Mon Sep 17 00:00:00 2001 From: Sophie <49928680+sophiecarreras@users.noreply.github.com> Date: Sat, 3 Oct 2026 22:59:36 -0300 Subject: [PATCH 004/113] test(sdkharness): refuse a resilience run on a simulator that already served requests (#624) The resilience leaves count the simulator's whole request journal, which has no reset. On a simulator shared by several scenarios, upload.cap_exceeded_403 read earlier scenarios' b2_upload_file entries as its own and failed with N calls, and api.retry_after_503 counted earlier injected 503s. The dispatcher now FAILs with a configuration reason when the journal is not empty. Co-authored-by: Claude Sonnet 5.5 --- .sdkharness/README.md | 5 +- .sdkharness/tests/lib/contract.py | 29 ++++++++++ ...silience-fresh-simulator.infrastructure.md | 1 + ...harness_conformance_resilience_contract.py | 53 +++++++++++++++++++ 4 files changed, 87 insertions(+), 1 deletion(-) create mode 100644 changelog.d/+sdkharness-resilience-fresh-simulator.infrastructure.md diff --git a/.sdkharness/README.md b/.sdkharness/README.md index 00e0405a3..b6ea67014 100644 --- a/.sdkharness/README.md +++ b/.sdkharness/README.md @@ -66,7 +66,10 @@ helper); the checks read the `SDKHARNESS_SIMULATOR_*` names above. # conformance (one capability) SDKHARNESS_TEST_LEVEL=conformance SDKHARNESS_SCENARIO=files.upload .sdkharness/tests/run-conformance -# resilience (one injected fault; needs the control URL, i.e. serve.mjs --control) +# resilience (one injected fault; needs the control URL, i.e. serve.mjs --control). +# Start a FRESH simulator for every scenario: the simulator keeps one request journal +# with no reset, the leaves count it, and the dispatcher FAILs a simulator that already +# served requests. SDKHARNESS_TEST_LEVEL=resilience SDKHARNESS_SCENARIO=api.backoff_503 .sdkharness/tests/run-resilience # customer health (needs a bucket in the simulator first) diff --git a/.sdkharness/tests/lib/contract.py b/.sdkharness/tests/lib/contract.py index 8d53f4777..ff977308c 100644 --- a/.sdkharness/tests/lib/contract.py +++ b/.sdkharness/tests/lib/contract.py @@ -2,10 +2,12 @@ from __future__ import annotations +import json import os import re import subprocess import sys +import urllib.request from collections.abc import Mapping from pathlib import Path from urllib.parse import urlsplit @@ -112,6 +114,31 @@ def translate(level: str, scenario: str, returncode: int, output: str) -> tuple[ return 'FAIL', 'contract: malformed standing verdict', 1 +def require_fresh_simulator(control_url: str) -> None: + """Refuse a simulator that already served requests. + + The resilience leaves read the simulator's whole request journal and count + its entries (for example every b2_upload_file), and the simulator has no + journal reset. Run on a simulator an earlier scenario used, a leaf reads + that scenario's requests as its own and reports a bogus SDK verdict + (`upload.cap_exceeded_403`: "N b2_upload_file calls"). Start one control + simulator per scenario, as the harness runner does. + """ + opener = urllib.request.build_opener(urllib.request.ProxyHandler({})) + try: + with opener.open(f'{control_url.rstrip("/")}/journal', timeout=10) as response: + entries = json.load(response)['entries'] + except Exception as error: + raise ContractFailure( + f'configuration: cannot read the simulator journal ({type(error).__name__})' + ) from error + if entries: + raise ContractFailure( + f'configuration: the simulator already served {len(entries)} request(s); ' + 'resilience scenarios need one fresh --control simulator per scenario' + ) + + def run(level: str, environment: Mapping[str, str] = os.environ) -> int: scenario = environment.get('SDKHARNESS_SCENARIO', 'unknown') try: @@ -119,6 +146,8 @@ def run(level: str, environment: Mapping[str, str] = os.environ) -> int: executable = SCENARIO_ROOT / level / scenario if not executable.is_file() or not os.access(executable, os.X_OK): raise ContractFailure('configuration: scenario executable is unavailable') + if level == 'resilience': + require_fresh_simulator(environment['SDKHARNESS_SIMULATOR_CONTROL_URL']) completed = subprocess.run( [str(executable)], cwd=REPOSITORY_ROOT, diff --git a/changelog.d/+sdkharness-resilience-fresh-simulator.infrastructure.md b/changelog.d/+sdkharness-resilience-fresh-simulator.infrastructure.md new file mode 100644 index 000000000..5fd122d2d --- /dev/null +++ b/changelog.d/+sdkharness-resilience-fresh-simulator.infrastructure.md @@ -0,0 +1 @@ +The repository-owned resilience dispatcher refuses a simulator that has already served requests, instead of letting a leaf count an earlier scenario's journal entries (for example `upload.cap_exceeded_403` reporting extra `b2_upload_file` calls) and report a false SDK failure. diff --git a/test/unit/test_sdkharness_conformance_resilience_contract.py b/test/unit/test_sdkharness_conformance_resilience_contract.py index 15d59f77e..d1845ddc0 100644 --- a/test/unit/test_sdkharness_conformance_resilience_contract.py +++ b/test/unit/test_sdkharness_conformance_resilience_contract.py @@ -180,3 +180,56 @@ def test_leaf_checks_name_no_external_realm_or_ambient_credentials(): assert "os.environ.get('B2_APPLICATION_KEY" not in text, leaf.name assert "os.environ['B2_APPLICATION_KEY" not in text, leaf.name assert 'refusal(' in text, leaf.name + + +class _JournalServer: + """A loopback server answering GET /journal with a fixed entry list.""" + + def __init__(self, entries): + import json + import threading + from http.server import BaseHTTPRequestHandler, HTTPServer + + body = json.dumps({'entries': entries}).encode() + + class Handler(BaseHTTPRequestHandler): + def do_GET(self): + self.send_response(200) + self.send_header('content-length', str(len(body))) + self.end_headers() + self.wfile.write(body) + + def log_message(self, *args): + pass + + self.server = HTTPServer(('127.0.0.1', 0), Handler) + self.url = f'http://127.0.0.1:{self.server.server_address[1]}' + threading.Thread(target=self.server.serve_forever, daemon=True).start() + + def close(self): + self.server.shutdown() + self.server.server_close() + + +def test_resilience_refuses_a_simulator_that_already_served_requests(capsys): + contract = load_contract() + server = _JournalServer([{'seq': 1, 'endpoint': 'b2_upload_file', 'status': 200}]) + try: + env = environment('resilience', 'upload.cap_exceeded_403') + env['SDKHARNESS_SIMULATOR_CONTROL_URL'] = server.url + assert contract.run('resilience', env) == 1 + finally: + server.close() + out = capsys.readouterr().out + assert 'FAIL' in out and 'already served 1 request(s)' in out + + +def test_fresh_simulator_is_accepted_and_unreadable_journal_is_a_failure(): + contract = load_contract() + server = _JournalServer([]) + try: + contract.require_fresh_simulator(server.url) + finally: + server.close() + with pytest.raises(contract.ContractFailure, match='cannot read the simulator journal'): + contract.require_fresh_simulator('http://127.0.0.1:1') From c83daa583d0374647c74021e2f435ab28af99de2 Mon Sep 17 00:00:00 2001 From: Sophie <49928680+sophiecarreras@users.noreply.github.com> Date: Sun, 4 Oct 2026 01:14:47 -0300 Subject: [PATCH 005/113] docs(sdkharness): run one check against the standalone simulator (#625) * docs(sdkharness): run one check against the standalone simulator Rewrite the README's local-run steps to use backblaze-labs/b2-simulator (via B2SIM_DIR) instead of central-harness-only paths, list every proxy variable the leaf checks scrub, and move the _JournalServer test helper's imports to module level. Co-Authored-By: Claude Sonnet 5.5 * docs(sdkharness): neutralize private repo names in the README Drop links to private repositories, say the standalone simulator is available to the team, show the full loopback_guard.py path, note the Python 3.10+ requirement, and stop each example's simulator before the next so copy-paste runs get a fresh one. Co-Authored-By: Claude Sonnet 5.5 --------- Co-authored-by: Claude Sonnet 5.5 --- .sdkharness/README.md | 49 ++++++++++++------- ...dme-standalone-simulator.infrastructure.md | 1 + ...harness_conformance_resilience_contract.py | 7 ++- 3 files changed, 35 insertions(+), 22 deletions(-) create mode 100644 changelog.d/+sdkharness-readme-standalone-simulator.infrastructure.md diff --git a/.sdkharness/README.md b/.sdkharness/README.md index b6ea67014..43c37dd9d 100644 --- a/.sdkharness/README.md +++ b/.sdkharness/README.md @@ -1,8 +1,7 @@ # sdkharness contract This directory exposes version-matched quality checks to the centralized -[`sdkharness`](https://github.com/backblaze-labs/demand-side-ai/tree/main/sdkharness). -The repository owns the executable assertions; sdkharness owns the canonical +`sdkharness`. The repository owns the executable assertions; sdkharness owns the canonical scenario, simulator, invocation, evidence, fleet report, and notification. `tests.tsv` is the machine-readable entry point. Schema 1 has four @@ -22,8 +21,10 @@ check refuses any other `B2_TEST_APPLICATION_KEY*` pair before it reaches the SDK. The individual conformance and resilience check files refuse to run at all unless they are given a loopback simulator URL, so run them through the dispatchers below, never with real `B2_*` values in the environment. The -dispatchers also drop `HTTP_PROXY`, `HTTPS_PROXY`, `ALL_PROXY` (any case) and pin -`NO_PROXY` to `127.0.0.1`, so a proxy configured on the machine cannot change a result. +dispatchers also drop `HTTP_PROXY`, `HTTPS_PROXY`, `ALL_PROXY`, `FTP_PROXY`, +`NO_PROXY` and `REQUEST_METHOD` (any case; `.sdkharness/tests/lib/loopback_guard.py`) and then pin +`NO_PROXY`/`no_proxy` to `127.0.0.1`, so a proxy configured on the machine cannot +change a result. Conformance owns 33 capability checks and resilience owns 16 injected-fault checks. Their small dispatchers validate the invocation, run the selected @@ -34,34 +35,41 @@ reporting, and notification. ## Run one check locally -Nothing here touches B2. You need Python 3.10+ and Node 22+ (for the simulator). +Nothing here touches B2. You need this repository, **Python 3.10 or newer** +(older versions cannot install `b2sdk`), Node 20+ (for the simulator), and a +checkout of the standalone B2 simulator (available to the team; ask the SDK +harness owners for access). Set `B2SIM_DIR` to that checkout. ```bash # 1. This checkout, in a virtualenv (the checks import b2sdk from here) python -m venv .venv && . .venv/bin/activate && pip install -e . -# 2. A local simulator (any one of these; it needs access to backblaze-labs/b2-simulator) -git clone https://github.com/backblaze-labs/b2-simulator /tmp/b2-simulator -node /tmp/b2-simulator/bin/simulator/serve.mjs --control > /tmp/sim.out 2>&1 & # prints the URLs +# 2. A local simulator with the fault-control listener (--control) +export B2SIM_DIR=/path/to/your/simulator/checkout # contains bin/simulator/serve.mjs +SIM_OUT=$(mktemp) +node "$B2SIM_DIR/bin/simulator/serve.mjs" --control > "$SIM_OUT" 2>&1 & # prints the URLs SIM_PID=$! -# ...or use the simulator embedded in the harness: sdkharness/bin/simulator/serve.mjs # 3. Wait until it has printed all three listener lines (http, https, control), then read them for _ in $(seq 100); do - [ "$(grep -c '^SIMULATOR-' /tmp/sim.out)" -ge 3 ] && break - kill -0 "$SIM_PID" 2>/dev/null || { echo 'simulator exited:'; cat /tmp/sim.out; break; } + [ "$(grep -c '^SIMULATOR-' "$SIM_OUT")" -ge 3 ] && break + kill -0 "$SIM_PID" 2>/dev/null || { echo 'simulator exited:'; cat "$SIM_OUT"; break; } sleep 0.1 done -export SDKHARNESS_SIMULATOR_URL=$(sed -n 's/^SIMULATOR-LISTENING \(http:.*\)/\1/p' /tmp/sim.out) -export SDKHARNESS_SIMULATOR_HTTPS_URL=$(sed -n 's/^SIMULATOR-LISTENING \(https:.*\)/\1/p' /tmp/sim.out) -export SDKHARNESS_SIMULATOR_CONTROL_URL=$(sed -n 's/^SIMULATOR-CONTROL \(.*\)/\1/p' /tmp/sim.out) -export SDKHARNESS_SIMULATOR_CA=/tmp/b2-simulator/bin/simulator/loopback-cert.pem +export SDKHARNESS_SIMULATOR_URL=$(sed -n 's/^SIMULATOR-LISTENING \(http:.*\)/\1/p' "$SIM_OUT") +export SDKHARNESS_SIMULATOR_HTTPS_URL=$(sed -n 's/^SIMULATOR-LISTENING \(https:.*\)/\1/p' "$SIM_OUT") +export SDKHARNESS_SIMULATOR_CONTROL_URL=$(sed -n 's/^SIMULATOR-CONTROL \(.*\)/\1/p' "$SIM_OUT") +export SDKHARNESS_SIMULATOR_CA=$B2SIM_DIR/bin/simulator/loopback-cert.pem ``` The standalone simulator also exports the same values as `B2SIM_URL`, `B2SIM_HTTPS_URL`, `B2SIM_CONTROL_URL` and `B2SIM_CA` (its `bin/lib/simulator.sh` helper); the checks read the `SDKHARNESS_SIMULATOR_*` names above. +Then run one scenario through its dispatcher. Each prints one +`SDKHARNESS_RESULT` line, for example +`SDKHARNESS_RESULT conformance files.upload PASS -`. + ```bash # conformance (one capability) SDKHARNESS_TEST_LEVEL=conformance SDKHARNESS_SCENARIO=files.upload .sdkharness/tests/run-conformance @@ -70,9 +78,13 @@ SDKHARNESS_TEST_LEVEL=conformance SDKHARNESS_SCENARIO=files.upload .sdkharness/t # Start a FRESH simulator for every scenario: the simulator keeps one request journal # with no reset, the leaves count it, and the dispatcher FAILs a simulator that already # served requests. +kill "$SIM_PID"; rm -f "$SIM_OUT" +# ...now repeat steps 2 and 3 to start a fresh simulator, then: SDKHARNESS_TEST_LEVEL=resilience SDKHARNESS_SCENARIO=api.backoff_503 .sdkharness/tests/run-resilience -# customer health (needs a bucket in the simulator first) +# customer health (needs a bucket in the simulator first, so use a fresh simulator again) +kill "$SIM_PID"; rm -f "$SIM_OUT" +# ...repeat steps 2 and 3 again, then: python - <<'PY' import os from b2sdk.v3 import B2Api, InMemoryAccountInfo @@ -85,9 +97,10 @@ HEALTHCHECK_REALM_URL=$SDKHARNESS_SIMULATOR_URL B2_TEST_APPLICATION_KEY_ID=test- .sdkharness/tests/health-golden-path ``` -When you are done, stop the simulator with `kill "$SIM_PID"`. +When you are done, stop the simulator you started with `kill "$SIM_PID"` (never +kill by process name) and remove `"$SIM_OUT"`. -Each prints one `SDKHARNESS_RESULT` line. Scenario ids are in `tests.tsv`. +Scenario ids are in `tests.tsv`. `api.retry_after_503` and `upload.retry_408` used to FAIL as known SDK findings; both pass now, so there are no standing known findings listed here. `upload.stall` reports `SKIP` because b2sdk documents no request-timeout option. A `FAIL` is a diff --git a/changelog.d/+sdkharness-readme-standalone-simulator.infrastructure.md b/changelog.d/+sdkharness-readme-standalone-simulator.infrastructure.md new file mode 100644 index 000000000..f0f4f27aa --- /dev/null +++ b/changelog.d/+sdkharness-readme-standalone-simulator.infrastructure.md @@ -0,0 +1 @@ +Document in the sdkharness README how to run one check against the standalone simulator, and list every proxy variable the leaf checks scrub. diff --git a/test/unit/test_sdkharness_conformance_resilience_contract.py b/test/unit/test_sdkharness_conformance_resilience_contract.py index d1845ddc0..41d47c5a1 100644 --- a/test/unit/test_sdkharness_conformance_resilience_contract.py +++ b/test/unit/test_sdkharness_conformance_resilience_contract.py @@ -9,6 +9,9 @@ ###################################################################### from __future__ import annotations +import json +import threading +from http.server import BaseHTTPRequestHandler, HTTPServer from importlib.util import module_from_spec, spec_from_file_location from pathlib import Path @@ -186,10 +189,6 @@ class _JournalServer: """A loopback server answering GET /journal with a fixed entry list.""" def __init__(self, entries): - import json - import threading - from http.server import BaseHTTPRequestHandler, HTTPServer - body = json.dumps({'entries': entries}).encode() class Handler(BaseHTTPRequestHandler): From d32620d9ec035b014f0a6f366cd6392bb0867e39 Mon Sep 17 00:00:00 2001 From: Felipe Fumero Date: Sun, 4 Oct 2026 10:18:32 -0600 Subject: [PATCH 006/113] release 2.13.1 --- CHANGELOG.md | 19 +++++++++++++++++++ ...sdkharness-fail-not-skip.infrastructure.md | 1 - ...ness-leaves-skip-pycache.infrastructure.md | 1 - ...+sdkharness-lock-refusal.infrastructure.md | 1 - ...dkharness-loopback-guard.infrastructure.md | 1 - ...dme-standalone-simulator.infrastructure.md | 1 - ...silience-fresh-simulator.infrastructure.md | 1 - changelog.d/605.fixed.md | 1 - changelog.d/606.fixed.md | 1 - changelog.d/610.infrastructure.md | 1 - changelog.d/612.infrastructure.md | 1 - 11 files changed, 19 insertions(+), 10 deletions(-) delete mode 100644 changelog.d/+sdkharness-fail-not-skip.infrastructure.md delete mode 100644 changelog.d/+sdkharness-leaves-skip-pycache.infrastructure.md delete mode 100644 changelog.d/+sdkharness-lock-refusal.infrastructure.md delete mode 100644 changelog.d/+sdkharness-loopback-guard.infrastructure.md delete mode 100644 changelog.d/+sdkharness-readme-standalone-simulator.infrastructure.md delete mode 100644 changelog.d/+sdkharness-resilience-fresh-simulator.infrastructure.md delete mode 100644 changelog.d/605.fixed.md delete mode 100644 changelog.d/606.fixed.md delete mode 100644 changelog.d/610.infrastructure.md delete mode 100644 changelog.d/612.infrastructure.md diff --git a/CHANGELOG.md b/CHANGELOG.md index 4a14b8e60..0a9c315d3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,25 @@ upcoming release can be found in [changelog.d](changelog.d). +## [2.13.1](https://github.com/Backblaze/b2-sdk-python/releases/tag/v2.13.1) - 2026-10-04 + +### Fixed + +- Retry uploads after a B2 request-timeout response (HTTP 408). ([#605](https://github.com/Backblaze/b2-sdk-python/issues/605)) +- Fixed honoring the Retry-After header on 5xx service errors. ([#606](https://github.com/Backblaze/b2-sdk-python/issues/606)) + +### Infrastructure + +- Added a repository-owned sdkharness customer-health contract for version-matched simulator testing. ([#610](https://github.com/Backblaze/b2-sdk-python/issues/610)) +- Moved sdkharness conformance and resilience assertions into this repository so they execute against the exact b2sdk checkout. ([#612](https://github.com/Backblaze/b2-sdk-python/issues/612)) +- Document in the sdkharness README how to run one check against the standalone simulator, and list every proxy variable the leaf checks scrub. +- Make the sdkharness leaf-check unit tests ignore `__pycache__` and other non-leaf entries. +- Repository-owned conformance checks `lock.bypass_governance` and `lock.per_file_retention` accept the 401 `access_denied` that B2 answers for a delete of a governance-locked version without bypass, and still fail if the delete is allowed or refused for an unrelated reason. +- Repository-owned sdkharness conformance and resilience checks now report an authorization error, access denied, a connection error against the simulator, or an SDK `ImportError` as `FAIL` instead of `COULD-NOT-RUN`/`SKIP`, strip proxy environment variables so a stray proxy cannot change a result, and no longer refer to files that exist only in the central harness. +- Repository-owned sdkharness conformance and resilience leaf checks now refuse to run unless they are given a loopback simulator URL, and always use the fixed simulator credential, so running one directly can no longer reach staging or production with ambient `B2_*` credentials. +- The repository-owned resilience dispatcher refuses a simulator that has already served requests, instead of letting a leaf count an earlier scenario's journal entries (for example `upload.cap_exceeded_403` reporting extra `b2_upload_file` calls) and report a false SDK failure. + + ## [2.13.0](https://github.com/Backblaze/b2-sdk-python/releases/tag/v2.13.0) - 2026-09-14 diff --git a/changelog.d/+sdkharness-fail-not-skip.infrastructure.md b/changelog.d/+sdkharness-fail-not-skip.infrastructure.md deleted file mode 100644 index 9d77740af..000000000 --- a/changelog.d/+sdkharness-fail-not-skip.infrastructure.md +++ /dev/null @@ -1 +0,0 @@ -Repository-owned sdkharness conformance and resilience checks now report an authorization error, access denied, a connection error against the simulator, or an SDK `ImportError` as `FAIL` instead of `COULD-NOT-RUN`/`SKIP`, strip proxy environment variables so a stray proxy cannot change a result, and no longer refer to files that exist only in the central harness. diff --git a/changelog.d/+sdkharness-leaves-skip-pycache.infrastructure.md b/changelog.d/+sdkharness-leaves-skip-pycache.infrastructure.md deleted file mode 100644 index 4d74b4253..000000000 --- a/changelog.d/+sdkharness-leaves-skip-pycache.infrastructure.md +++ /dev/null @@ -1 +0,0 @@ -Make the sdkharness leaf-check unit tests ignore `__pycache__` and other non-leaf entries. diff --git a/changelog.d/+sdkharness-lock-refusal.infrastructure.md b/changelog.d/+sdkharness-lock-refusal.infrastructure.md deleted file mode 100644 index b30c9f913..000000000 --- a/changelog.d/+sdkharness-lock-refusal.infrastructure.md +++ /dev/null @@ -1 +0,0 @@ -Repository-owned conformance checks `lock.bypass_governance` and `lock.per_file_retention` accept the 401 `access_denied` that B2 answers for a delete of a governance-locked version without bypass, and still fail if the delete is allowed or refused for an unrelated reason. diff --git a/changelog.d/+sdkharness-loopback-guard.infrastructure.md b/changelog.d/+sdkharness-loopback-guard.infrastructure.md deleted file mode 100644 index 074913dfd..000000000 --- a/changelog.d/+sdkharness-loopback-guard.infrastructure.md +++ /dev/null @@ -1 +0,0 @@ -Repository-owned sdkharness conformance and resilience leaf checks now refuse to run unless they are given a loopback simulator URL, and always use the fixed simulator credential, so running one directly can no longer reach staging or production with ambient `B2_*` credentials. diff --git a/changelog.d/+sdkharness-readme-standalone-simulator.infrastructure.md b/changelog.d/+sdkharness-readme-standalone-simulator.infrastructure.md deleted file mode 100644 index f0f4f27aa..000000000 --- a/changelog.d/+sdkharness-readme-standalone-simulator.infrastructure.md +++ /dev/null @@ -1 +0,0 @@ -Document in the sdkharness README how to run one check against the standalone simulator, and list every proxy variable the leaf checks scrub. diff --git a/changelog.d/+sdkharness-resilience-fresh-simulator.infrastructure.md b/changelog.d/+sdkharness-resilience-fresh-simulator.infrastructure.md deleted file mode 100644 index 5fd122d2d..000000000 --- a/changelog.d/+sdkharness-resilience-fresh-simulator.infrastructure.md +++ /dev/null @@ -1 +0,0 @@ -The repository-owned resilience dispatcher refuses a simulator that has already served requests, instead of letting a leaf count an earlier scenario's journal entries (for example `upload.cap_exceeded_403` reporting extra `b2_upload_file` calls) and report a false SDK failure. diff --git a/changelog.d/605.fixed.md b/changelog.d/605.fixed.md deleted file mode 100644 index 47d11f87e..000000000 --- a/changelog.d/605.fixed.md +++ /dev/null @@ -1 +0,0 @@ -Retry uploads after a B2 request-timeout response (HTTP 408). diff --git a/changelog.d/606.fixed.md b/changelog.d/606.fixed.md deleted file mode 100644 index bd710ff39..000000000 --- a/changelog.d/606.fixed.md +++ /dev/null @@ -1 +0,0 @@ -Fixed honoring the Retry-After header on 5xx service errors. diff --git a/changelog.d/610.infrastructure.md b/changelog.d/610.infrastructure.md deleted file mode 100644 index 1596362ea..000000000 --- a/changelog.d/610.infrastructure.md +++ /dev/null @@ -1 +0,0 @@ -Added a repository-owned sdkharness customer-health contract for version-matched simulator testing. diff --git a/changelog.d/612.infrastructure.md b/changelog.d/612.infrastructure.md deleted file mode 100644 index 69746558f..000000000 --- a/changelog.d/612.infrastructure.md +++ /dev/null @@ -1 +0,0 @@ -Moved sdkharness conformance and resilience assertions into this repository so they execute against the exact b2sdk checkout. From ffa02b3264bc0e7069ef2c8b25facd9a467e65a6 Mon Sep 17 00:00:00 2001 From: Sophie <49928680+sophiecarreras@users.noreply.github.com> Date: Thu, 15 Oct 2026 17:30:48 -0300 Subject: [PATCH 007/113] test(sdkharness): upload.stall meets its request-timeout need through http_session_factory (#628) b2sdk has no timeout option, but B2Http passes its timeout to Session.request on every call (b2sdk/_internal/b2http.py), and B2HttpApiConfig documents http_session_factory. A Session subclass that clamps the read timeout to 5 s makes the 60 s stall give up, after which the upload retries on a new upload URL. The check used to report no-client-option. Co-authored-by: Claude Sonnet 5.5 --- .sdkharness/README.md | 5 +- .sdkharness/tests/resilience/upload.stall | 72 ++++++++++++++----- ...ss-upload-stall-runnable.infrastructure.md | 1 + 3 files changed, 60 insertions(+), 18 deletions(-) create mode 100644 changelog.d/+sdkharness-upload-stall-runnable.infrastructure.md diff --git a/.sdkharness/README.md b/.sdkharness/README.md index 43c37dd9d..3d3f741c0 100644 --- a/.sdkharness/README.md +++ b/.sdkharness/README.md @@ -103,7 +103,10 @@ kill by process name) and remove `"$SIM_OUT"`. Scenario ids are in `tests.tsv`. `api.retry_after_503` and `upload.retry_408` used to FAIL as known SDK findings; both pass now, so there are no standing known findings listed here. `upload.stall` -reports `SKIP` because b2sdk documents no request-timeout option. A `FAIL` is a +meets its request-timeout need through `B2HttpApiConfig(http_session_factory=...)`: b2sdk has no +timeout option, but `B2Http` hands its timeout to the session on every request, so a `Session` +subclass that clamps the read timeout makes the stalled upload give up and retry on a new upload +URL. A `FAIL` is a real SDK or harness defect (or a simulator older than the checks expect), not a setup problem. `SKIP` is reserved for a question that genuinely cannot be asked (`no-realm-option`, `missing-runtime` when `b2sdk` is not installed at all, diff --git a/.sdkharness/tests/resilience/upload.stall b/.sdkharness/tests/resilience/upload.stall index 28eeceed2..4a8c91f41 100755 --- a/.sdkharness/tests/resilience/upload.stall +++ b/.sdkharness/tests/resilience/upload.stall @@ -4,10 +4,14 @@ Written from the reference check, upload.retry_503 in this directory. The question is the upload.stall scenario of the central sdkharness registry. -Fault wire b2_upload_file stall ms=60000 -- NOT ARMED. The scenario needs a client - request timeout short enough to beat a 60 s stall (`needs: request-timeout`) -Assert nothing: b2sdk documents no request-timeout option, so - the check reports no-client-option instead of guessing at one +Fault wire b2_upload_file stall ms=60000, armed after setup, so the first upload + attempt is the one that stalls. The scenario needs a client request timeout + short enough to beat a 60 s stall (`needs: request-timeout`); b2sdk has no + timeout option, so the check meets it through B2HttpApiConfig's documented + `http_session_factory` (a Session that clamps the read timeout to 5 s) +Assert the recovery path, from GET /journal: exactly one stall on b2_upload_file, + then a successful b2_upload_file on a DIFFERENT uploadUrlId; and the end + state, through the normal API: the file downloads with the bytes that went up The expected behaviour is B2's, not the tool's. The Integration Checklist, Upload Retry Guidelines, lists the failures after which "the @@ -20,6 +24,8 @@ It exercises b2sdk from this exact repository checkout; the API is taken from the published b2sdk documentation. """ +import hashlib +import io import json import os import sys @@ -127,30 +133,62 @@ def authorized_bucket(**api_kwargs): return api, bucket -# Why this scenario cannot be asked. The published b2sdk documentation names no -# request-timeout option, so the precondition cannot be settled from outside. -UNSETTLED = ( - "b2sdk documents no request-timeout option: B2HttpApiConfig's " - 'documented parameters are http_session_factory and _raw_api_class, and nothing names ' - 'the timeout B2Http passes to requests or a way to shorten it' -) +# The request-timeout precondition (`needs: request-timeout`). b2sdk has no timeout option, but +# B2HttpApiConfig documents `http_session_factory` (a callable returning a requests.Session), and +# B2Http (b2sdk/_internal/b2http.py) hands its timeout to that session on every call: +# `self.session.request(..., timeout=(CONNECTION_TIMEOUT, _timeout or TIMEOUT_FOR_UPLOAD))`. A Session +# subclass that clamps the read timeout therefore makes a stalled response give up early. +REQUEST_TIMEOUT_S = 5 + + +def short_timeout_session_class(): + import requests + + class ShortTimeoutSession(requests.Session): + def request(self, method, url, **kwargs): + timeout = kwargs.get('timeout') + connect = timeout[0] if isinstance(timeout, tuple) else timeout + kwargs['timeout'] = (connect or REQUEST_TIMEOUT_S, REQUEST_TIMEOUT_S) + return super().request(method, url, **kwargs) + + return ShortTimeoutSession def run() -> None: try: - import b2sdk.v3 # noqa: F401 -- only presence is asked + from b2sdk.v3 import B2HttpApiConfig except ImportError as error: if not missing_runtime(error): # b2sdk is installed but broken: an SDK regression, not a missing runtime raise Failure('import', type(error).__name__) from error raise Amber('missing-runtime', 'b2sdk is not installed') from error note( - 'unconfirmed, not absent: an http_session_factory returning a Session that forces a ' - 'short timeout MIGHT meet the need, but session-level behaviour is not documented; ' - 'reading what timeout b2http.py passes to ' - 'Session.request, and whether it is configurable, would settle it' + 'request-timeout met through B2HttpApiConfig(http_session_factory=...), a documented ' + f'parameter: a Session subclass clamps the read timeout to {REQUEST_TIMEOUT_S} s' ) - raise Amber('no-client-option', UNSETTLED) + config = B2HttpApiConfig(http_session_factory=short_timeout_session_class()) + api, bucket = authorized_bucket(api_config=config) + + payload = (b'sdkharness resilience ' * 64)[:1024] + step('arm fault', lambda: control('POST', ARM_PATH, FAULT)) + uploaded = step('upload', lambda: bucket.upload_bytes(payload, OBJECT_NAME)) + if hashlib.sha1(payload).hexdigest() != getattr(uploaded, 'content_sha1', None): + raise Failure('upload', 'the returned contentSha1 does not match the bytes sent') + + sink = io.BytesIO() + step('download', lambda: bucket.download_file_by_name(OBJECT_NAME).save(sink)) + if sink.getvalue() != payload: + raise Failure('round trip', 'downloaded bytes differ from what was uploaded') + + entries = journal() + stalled = [e for e in entries if is_faulted(e)] + if len(stalled) != 1: + raise Failure('journal', f'{len(stalled)} stalls on b2_upload_file, expected 1') + retries = after(entries, stalled[0]['seq'], 'b2_upload_file', 200) + if not retries: + raise Failure('journal', 'no successful b2_upload_file after the stall') + if retries[0]['uploadUrlId'] in (None, stalled[0]['uploadUrlId']): + raise Failure('recovery path', 'the retry reused the upload URL that stalled') def main() -> int: diff --git a/changelog.d/+sdkharness-upload-stall-runnable.infrastructure.md b/changelog.d/+sdkharness-upload-stall-runnable.infrastructure.md new file mode 100644 index 000000000..dd98b84ee --- /dev/null +++ b/changelog.d/+sdkharness-upload-stall-runnable.infrastructure.md @@ -0,0 +1 @@ +Make the sdkharness `upload.stall` check runnable: it meets its request-timeout need through the documented `B2HttpApiConfig(http_session_factory=...)` instead of reporting `no-client-option`. From 9f87e04860b32284e6630ae42debc7ed12b87276 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Nowacki?= Date: Wed, 21 Oct 2026 16:55:56 +0200 Subject: [PATCH 008/113] pin certifi to 2026.10.19 --- changelog.d/+certifi-minimum.changed.md | 1 + pyproject.toml | 1 + uv.lock | 8 +++++--- 3 files changed, 7 insertions(+), 3 deletions(-) create mode 100644 changelog.d/+certifi-minimum.changed.md diff --git a/changelog.d/+certifi-minimum.changed.md b/changelog.d/+certifi-minimum.changed.md new file mode 100644 index 000000000..b9c470e0c --- /dev/null +++ b/changelog.d/+certifi-minimum.changed.md @@ -0,0 +1 @@ +Require certifi 2026.10.19 or newer. diff --git a/pyproject.toml b/pyproject.toml index 1cd4ffb2c..23c35527f 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -23,6 +23,7 @@ classifiers = [ ] dependencies = [ "annotated_types>=0.5.0", + "certifi>=2026.10.19", "logfury<2.0.0,>=1.0.1", "requests<3.0.0,>=2.33.0", "typing-extensions>=4.7.1; python_version < '3.12'", diff --git a/uv.lock b/uv.lock index b8bb3e640..b8a7c69b3 100644 --- a/uv.lock +++ b/uv.lock @@ -62,6 +62,7 @@ name = "b2sdk" source = { editable = "." } dependencies = [ { name = "annotated-types" }, + { name = "certifi" }, { name = "logfury" }, { name = "requests" }, { name = "typing-extensions", marker = "python_full_version < '3.12'" }, @@ -122,6 +123,7 @@ test = [ [package.metadata] requires-dist = [ { name = "annotated-types", specifier = ">=0.5.0" }, + { name = "certifi", specifier = ">=2026.10.19" }, { name = "logfury", specifier = ">=1.0.1,<2.0.0" }, { name = "pydantic", marker = "python_full_version < '3.11' and platform_python_implementation == 'PyPy' and extra == 'full'", specifier = ">=2.0.1,<2.13" }, { name = "pydantic", marker = "(python_full_version >= '3.11' and extra == 'full') or (platform_python_implementation != 'PyPy' and extra == 'full')", specifier = ">=2.0.1" }, @@ -180,11 +182,11 @@ wheels = [ [[package]] name = "certifi" -version = "2026.1.4" +version = "2026.10.19" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/e0/2d/a891ca51311197f6ad14a7ef42e2399f36cf2f9bd44752b3dc4eab60fdc5/certifi-2026.1.4.tar.gz", hash = "sha256:ac726dd470482006e014ad384921ed6438c457018f4b3d204aea4281258b2120", size = 154268, upload-time = "2026-01-04T02:42:41.825Z" } +sdist = { url = "https://files.pythonhosted.org/packages/a6/bd/1436c50cc46699de0230fbaacc1d1de7bfec413176099949e9d5112e88f2/certifi-2026.10.19.tar.gz", hash = "sha256:035c1e85572b141bf1c3a3eff0e33a8eb74917522f2559075ff8d2fea780a1ae", size = 137598, upload-time = "2026-10-20T02:24:16.604Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/e6/ad/3cc14f097111b4de0040c83a525973216457bbeeb63739ef1ed275c1c021/certifi-2026.1.4-py3-none-any.whl", hash = "sha256:9943707519e4add1115f44c2bc244f782c0249876bf51b6599fee1ffbedd685c", size = 152900, upload-time = "2026-01-04T02:42:40.15Z" }, + { url = "https://files.pythonhosted.org/packages/c4/51/29046e48f693c54e5b7412216d447a1d8362c9653148d98c02cdf65fa733/certifi-2026.10.19-py3-none-any.whl", hash = "sha256:42d35340cc5b9ba78e818ddbff0c5b1c2b779de448a340fd1b989f5fa8670e1b", size = 136464, upload-time = "2026-10-20T02:24:15.072Z" }, ] [[package]] From a037176d57129bd104e253f57bcbf8298ba162fd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Nowacki?= Date: Wed, 21 Oct 2026 17:06:55 +0200 Subject: [PATCH 009/113] pin pip >=26.2.2 --- .github/workflows/cd.yml | 2 +- .github/workflows/ci.yml | 2 +- changelog.d/+ci-pip-minimum.infrastructure.md | 1 + noxfile.py | 2 +- pyproject.toml | 4 +++- uv.lock | 16 +++++++++++----- 6 files changed, 18 insertions(+), 9 deletions(-) create mode 100644 changelog.d/+ci-pip-minimum.infrastructure.md diff --git a/.github/workflows/cd.yml b/.github/workflows/cd.yml index d01218fd6..8c0c898f2 100644 --- a/.github/workflows/cd.yml +++ b/.github/workflows/cd.yml @@ -6,7 +6,7 @@ on: env: PYTHON_DEFAULT_VERSION: "3.14" - UV_VERSION: "0.8.24" + UV_VERSION: "0.13.4" jobs: deploy: diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index e8e7ce08f..8b58b6acf 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -8,7 +8,7 @@ on: env: PYTHON_DEFAULT_VERSION: "3.14" - UV_VERSION: "0.8.24" + UV_VERSION: "0.13.4" jobs: lint: diff --git a/changelog.d/+ci-pip-minimum.infrastructure.md b/changelog.d/+ci-pip-minimum.infrastructure.md new file mode 100644 index 000000000..578d7c4da --- /dev/null +++ b/changelog.d/+ci-pip-minimum.infrastructure.md @@ -0,0 +1 @@ +Require pip 26.2.2 or newer in the Nox runner, lint, build, and test environments and update GitHub Actions to uv 0.13.4 to address the emSign CA certificate security incident. diff --git a/noxfile.py b/noxfile.py index fedc60dda..418ef765f 100644 --- a/noxfile.py +++ b/noxfile.py @@ -195,7 +195,7 @@ def build(session): if len(sdists) != 1: session.error(f'Expected exactly one source distribution, found {len(sdists)}: {sdists!r}') - session.install(str(sdists[0])) + session.install('pip>=26.2.2', str(sdists[0])) session.cd('dist') # avoid importing from the checkout instead of the built package session.run( 'python', diff --git a/pyproject.toml b/pyproject.toml index 23c35527f..c2391380b 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -39,12 +39,13 @@ full = [ [dependency-groups] nox = [ "nox>=2025.11.12", + "pip>=26.2.2", ] format = [ "ruff~=0.8.4", ] lint = [ - "pip>=26.1", + "pip>=26.2.2", "ruff~=0.8.4", "pytest>=9.0.3,<10", "tenacity>=9.1.4,<10", @@ -52,6 +53,7 @@ lint = [ "setuptools", ] test = [ + "pip>=26.2.2", "coverage>=7.13.5,<8", "pytest>=9.0.3,<10", "pytest-cov>=7.1.0,<8", diff --git a/uv.lock b/uv.lock index b8a7c69b3..5bc9480d6 100644 --- a/uv.lock +++ b/uv.lock @@ -99,12 +99,14 @@ lint = [ ] nox = [ { name = "nox" }, + { name = "pip" }, ] release = [ { name = "towncrier" }, ] test = [ { name = "coverage" }, + { name = "pip" }, { name = "pydantic", version = "2.12.5", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11' and platform_python_implementation == 'PyPy'" }, { name = "pydantic", version = "2.13.3", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11' or platform_python_implementation != 'PyPy'" }, { name = "pytest" }, @@ -146,16 +148,20 @@ doc = [ format = [{ name = "ruff", specifier = "~=0.8.4" }] lint = [ { name = "liccheck", specifier = "==0.9.2" }, - { name = "pip", specifier = ">=26.1" }, + { name = "pip", specifier = ">=26.2.2" }, { name = "pytest", specifier = ">=9.0.3,<10" }, { name = "ruff", specifier = "~=0.8.4" }, { name = "setuptools" }, { name = "tenacity", specifier = ">=9.1.4,<10" }, ] -nox = [{ name = "nox", specifier = ">=2025.11.12" }] +nox = [ + { name = "nox", specifier = ">=2025.11.12" }, + { name = "pip", specifier = ">=26.2.2" }, +] release = [{ name = "towncrier", specifier = "==23.11.0" }] test = [ { name = "coverage", specifier = ">=7.13.5,<8" }, + { name = "pip", specifier = ">=26.2.2" }, { name = "pydantic", marker = "python_full_version >= '3.11' or platform_python_implementation != 'PyPy'", specifier = ">=2.13.3,<3" }, { name = "pydantic", marker = "python_full_version < '3.11' and platform_python_implementation == 'PyPy'", specifier = ">=2.0.1,<2.13" }, { name = "pytest", specifier = ">=9.0.3,<10" }, @@ -746,11 +752,11 @@ wheels = [ [[package]] name = "pip" -version = "26.1" +version = "26.2.2" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/73/7e/d2b04004e1068ad4fdfa2f227b839b5d03e602e47cdbbf49de71137c9546/pip-26.1.tar.gz", hash = "sha256:81e13ebcca3ffa8cc85e4deff5c27e1ee26dea0aa7fc2f294a073ac208806ff3", size = 1840316, upload-time = "2026-04-26T21:00:05.406Z" } +sdist = { url = "https://files.pythonhosted.org/packages/fa/e8/0842d757e483e895e670f655084cfe8b8c72580c6769a76b30b2789a0608/pip-26.2.2.tar.gz", hash = "sha256:3a8e5c800492787f33a4114ef54444546c340df428974ebba17e0fd47e11af2f", size = 1863336, upload-time = "2026-10-20T16:36:29.008Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/70/7a/be4bd8bcbb24ea475856dd68159d78b03b2bb53dae369f69c9606b8888f5/pip-26.1-py3-none-any.whl", hash = "sha256:4e8486d821d814b77319acb7b9e8bf5a4ee7590a643e7cb21029f209be8573c1", size = 1812804, upload-time = "2026-04-26T21:00:03.194Z" }, + { url = "https://files.pythonhosted.org/packages/3f/06/3e4420302363fbb71be3c7f35ce042f54bfca330e3e66b3a2e3c4cca579f/pip-26.2.2-py3-none-any.whl", hash = "sha256:fd7f4dfa8190e014013b9f08f3e973f4e4c26ffd179a204895533a7254813a70", size = 1819850, upload-time = "2026-10-20T16:36:27.046Z" }, ] [[package]] From 17a6be766237899f8d807feab4102533085d0683 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Nowacki?= Date: Wed, 21 Oct 2026 17:27:01 +0200 Subject: [PATCH 010/113] release 2.13.2 --- CHANGELOG.md | 13 +++++++++++++ changelog.d/+certifi-minimum.changed.md | 1 - changelog.d/+ci-pip-minimum.infrastructure.md | 1 - ...kharness-upload-stall-runnable.infrastructure.md | 1 - 4 files changed, 13 insertions(+), 3 deletions(-) delete mode 100644 changelog.d/+certifi-minimum.changed.md delete mode 100644 changelog.d/+ci-pip-minimum.infrastructure.md delete mode 100644 changelog.d/+sdkharness-upload-stall-runnable.infrastructure.md diff --git a/CHANGELOG.md b/CHANGELOG.md index 0a9c315d3..76b7eecf6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,19 @@ upcoming release can be found in [changelog.d](changelog.d). +## [2.13.2](https://github.com/Backblaze/b2-sdk-python/releases/tag/v2.13.2) - 2026-10-21 + + +### Changed + +- Require certifi 2026.10.19 or newer. + +### Infrastructure + +- Make the sdkharness `upload.stall` check runnable: it meets its request-timeout need through the documented `B2HttpApiConfig(http_session_factory=...)` instead of reporting `no-client-option`. +- Require pip 26.2.2 or newer in the Nox runner, lint, build, and test environments and update GitHub Actions to uv 0.13.4 to address the emSign CA certificate security incident. + + ## [2.13.1](https://github.com/Backblaze/b2-sdk-python/releases/tag/v2.13.1) - 2026-10-04 ### Fixed diff --git a/changelog.d/+certifi-minimum.changed.md b/changelog.d/+certifi-minimum.changed.md deleted file mode 100644 index b9c470e0c..000000000 --- a/changelog.d/+certifi-minimum.changed.md +++ /dev/null @@ -1 +0,0 @@ -Require certifi 2026.10.19 or newer. diff --git a/changelog.d/+ci-pip-minimum.infrastructure.md b/changelog.d/+ci-pip-minimum.infrastructure.md deleted file mode 100644 index 578d7c4da..000000000 --- a/changelog.d/+ci-pip-minimum.infrastructure.md +++ /dev/null @@ -1 +0,0 @@ -Require pip 26.2.2 or newer in the Nox runner, lint, build, and test environments and update GitHub Actions to uv 0.13.4 to address the emSign CA certificate security incident. diff --git a/changelog.d/+sdkharness-upload-stall-runnable.infrastructure.md b/changelog.d/+sdkharness-upload-stall-runnable.infrastructure.md deleted file mode 100644 index dd98b84ee..000000000 --- a/changelog.d/+sdkharness-upload-stall-runnable.infrastructure.md +++ /dev/null @@ -1 +0,0 @@ -Make the sdkharness `upload.stall` check runnable: it meets its request-timeout need through the documented `B2HttpApiConfig(http_session_factory=...)` instead of reporting `no-client-option`. From a965446a14372d8b418cb3e07c66e18d9822cdc8 Mon Sep 17 00:00:00 2001 From: Sophie <49928680+sophiecarreras@users.noreply.github.com> Date: Mon, 2 Nov 2026 11:50:29 -0300 Subject: [PATCH 011/113] fix: seven confirmed bugs from a whole-branch review, each with a test that fails without the fix (#637) Fixes found by reviewing the default branch, with covering unit tests (fail before, pass after) and strengthened weak tests: - SQLite account info: bound parameter for allowed capabilities; reset upload pools after schema update - Bucket.copy: pass expires and content headers through - start_large_file: send customUploadTimestamp under its wire name - Replication monitor: no hang when the consumer fails - Local folder scan: keep scanning after an unreadable file when no reporter is given - Synchronizer: accept reporter=None - Parallel downloader: hash written data; surface writer errors One known bug whose behavior needs an owner decision (executor not shut down when scheduling fails) is recorded as an xfail with its reason. Also adds a sdkharness sync leg for reporter=None. Co-authored-by: Claude Sonnet 5.5 --- .sdkharness/tests/conformance/client.sync | 71 ++++++++++++++- .../account_info/sqlite_account_info.py | 11 ++- b2sdk/_internal/bucket.py | 4 + b2sdk/_internal/raw_api.py | 3 +- b2sdk/_internal/replication/monitoring.py | 43 ++++++--- b2sdk/_internal/scan/folder.py | 4 +- b2sdk/_internal/sync/sync.py | 7 +- .../transfer/inbound/downloader/parallel.py | 36 ++++++-- changelog.d/+copy-file-headers.fixed.md | 1 + changelog.d/+custom-upload-timestamp.fixed.md | 1 + changelog.d/+local-scan-errors.fixed.md | 1 + .../+parallel-download-writer.fixed.md | 1 + .../+replication-monitor-hang.fixed.md | 1 + changelog.d/+sqlite-allowed-param.fixed.md | 1 + changelog.d/+sync-silent-reporter.fixed.md | 1 + test/unit/account_info/test_account_info.py | 12 +++ .../account_info/test_sqlite_account_info.py | 39 ++++++++ test/unit/b2http/test_b2http.py | 18 +++- test/unit/bucket/test_bucket.py | 45 +++++++++- .../transfer/downloader/test_parallel.py | 63 +++++++++++++ test/unit/replication/test_monitoring.py | 90 +++++++++++++++++++ test/unit/scan/test_folder_traversal.py | 37 ++++++++ test/unit/sync/test_sync.py | 65 ++++++++++++-- test/unit/sync/test_sync_report.py | 29 ++++++ test/unit/test_raw_api.py | 35 ++++++++ ...harness_conformance_resilience_contract.py | 21 +++++ test/unit/v0/test_bucket.py | 12 ++- test/unit/v0/test_sync.py | 8 +- test/unit/v1/test_bounded_queue_executor.py | 28 ++++++ test/unit/v1/test_raw_api.py | 26 ++++-- test/unit/v1/test_sync.py | 8 +- 31 files changed, 671 insertions(+), 51 deletions(-) create mode 100644 changelog.d/+copy-file-headers.fixed.md create mode 100644 changelog.d/+custom-upload-timestamp.fixed.md create mode 100644 changelog.d/+local-scan-errors.fixed.md create mode 100644 changelog.d/+parallel-download-writer.fixed.md create mode 100644 changelog.d/+replication-monitor-hang.fixed.md create mode 100644 changelog.d/+sqlite-allowed-param.fixed.md create mode 100644 changelog.d/+sync-silent-reporter.fixed.md diff --git a/.sdkharness/tests/conformance/client.sync b/.sdkharness/tests/conformance/client.sync index 8032ff5ea..2ff8438c5 100755 --- a/.sdkharness/tests/conformance/client.sync +++ b/.sdkharness/tests/conformance/client.sync @@ -9,6 +9,10 @@ claims it): policy; sync down into a fresh directory Assert all 3 land; the remote matches the local side after the second pass; the round-tripped bytes are identical + Leg reporter=None (sync_folders documents `SyncReport | None`): sync + down from the bucket, and sync up from a directory holding a + dangling symlink; neither may crash, and the unreadable entry is + skipped, not uploaded NO DOCUMENTED CONTRACT FOUND -- this is SDK-side/ecosystem tooling, not a B2 API contract. B2 documents only sync's building blocks. "Remote matches local" is read @@ -257,7 +261,16 @@ def write(path, data): handle.write(data) -def sync(b2, syncer, source, destination): +def sync(b2, syncer, source, destination, silent=False): + """Run one sync pass. `silent` passes reporter=None, which sync_folders documents as valid.""" + if silent: + syncer.sync_folders( + source_folder=source, + dest_folder=destination, + now_millis=int(time.time() * 1000), + reporter=None, + ) + return reporter = b2.SyncReport(io.StringIO(), True) try: syncer.sync_folders( @@ -353,6 +366,62 @@ def run(target: str) -> None: extra = sorted(set(os.listdir(down_dir)) - set(contents)) if extra: raise Failure('sync down', f'{len(extra)} unexpected file(s) came down') + + # Leg: reporter=None. sync_folders documents `SyncReport | None`, so a caller + # that wants no progress output must get a normal sync, never an AttributeError + # (b2-source path) and never a crash on an inaccessible local file. + silent_down = tempfile.mkdtemp(prefix='sdkharness-conf-silent-down-') + silent_up = tempfile.mkdtemp(prefix='sdkharness-conf-silent-up-') + try: + step( + 'sync down with reporter=None', + lambda: sync( + b2, + syncer, + b2.parse_folder(remote_url, api), + b2.parse_folder(silent_down, api), + silent=True, + ), + ) + if sorted(os.listdir(silent_down)) != sorted(contents): + raise Failure('sync down with reporter=None', 'the files did not all come down') + for name, expected in contents.items(): + with open(os.path.join(silent_down, name), 'rb') as handle: + if handle.read() != expected: + raise Failure('sync down with reporter=None', "a file's bytes differ") + + # A local source holding a file that cannot be read. A dangling symlink is + # inaccessible whoever runs the check (chmod 000 is not for root). + write(os.path.join(silent_up, 'good.txt'), payload_of(300)) + os.symlink( + os.path.join(silent_up, 'does-not-exist'), os.path.join(silent_up, 'a-dangling') + ) + silent_url = f'b2://{bucket.name}/{REMOTE_PREFIX}-silent' + step( + 'sync up with reporter=None past an inaccessible file', + lambda: sync( + b2, + syncer, + b2.parse_folder(silent_up, api), + b2.parse_folder(silent_url, api), + silent=True, + ), + ) + silent_landed = step( + 'list the reporter=None upload', + lambda: sorted( + v.file_name.rsplit('/', 1)[-1] + for v, _folder in bucket.ls(REMOTE_PREFIX + '-silent/', recursive=True) + ), + ) + if silent_landed != ['good.txt']: + raise Failure( + 'sync up with reporter=None past an inaccessible file', + f'the remote holds {len(silent_landed)} file(s), expected only the readable one', + ) + finally: + shutil.rmtree(silent_down, ignore_errors=True) + shutil.rmtree(silent_up, ignore_errors=True) finally: teardown(api, bucket) shutil.rmtree(up_dir, ignore_errors=True) diff --git a/b2sdk/_internal/account_info/sqlite_account_info.py b/b2sdk/_internal/account_info/sqlite_account_info.py index 76e865b2a..1ee7e5a6f 100644 --- a/b2sdk/_internal/account_info/sqlite_account_info.py +++ b/b2sdk/_internal/account_info/sqlite_account_info.py @@ -441,9 +441,8 @@ def _migrate_allowed_to_multi_bucket(self, *, version: int): allowed['buckets'] = None allowed_text = json.dumps(allowed) - stmt = f"UPDATE account SET allowed = ('{allowed_text}');" - self._perform_update(version, [stmt]) + self._perform_update(version, [('UPDATE account SET allowed = ?;', (allowed_text,))]) def _ensure_update(self, update_number, update_commands: list[str]): """ @@ -466,17 +465,21 @@ def _get_update_count(self, update_number: int): ) return cursor.fetchone()[0] - def _perform_update(self, update_number, update_commands: list[str]): + def _perform_update(self, update_number, update_commands: list[str | tuple[str, tuple]]): with self._get_connection() as conn: conn.execute('BEGIN') for command in update_commands: - conn.execute(command) + if isinstance(command, str): + conn.execute(command) + else: + conn.execute(*command) conn.execute('INSERT INTO update_done (update_number) VALUES (?);', (update_number,)) def clear(self): """ Remove all info about accounts and buckets. """ + self._reset_upload_pools() with self._get_connection() as conn: conn.execute('DELETE FROM account;') conn.execute('DELETE FROM bucket;') diff --git a/b2sdk/_internal/bucket.py b/b2sdk/_internal/bucket.py index e6df3495c..e9bb5c4bd 100644 --- a/b2sdk/_internal/bucket.py +++ b/b2sdk/_internal/bucket.py @@ -1485,6 +1485,10 @@ def copy( file_retention=file_retention, legal_hold=legal_hold, cache_control=cache_control, + expires=expires, + content_disposition=content_disposition, + content_encoding=content_encoding, + content_language=content_language, min_part_size=min_part_size, max_part_size=max_part_size, ) diff --git a/b2sdk/_internal/raw_api.py b/b2sdk/_internal/raw_api.py index b24e5ba31..0a392bf1e 100644 --- a/b2sdk/_internal/raw_api.py +++ b/b2sdk/_internal/raw_api.py @@ -392,6 +392,7 @@ def start_large_file( server_side_encryption: EncryptionSetting | None = None, file_retention: FileRetentionSetting | None = None, legal_hold: LegalHold | None = None, + custom_upload_timestamp: int | None = None, ): pass @@ -880,7 +881,7 @@ def start_large_file( kwargs['fileRetention'] = file_retention.serialize_to_json_for_request() if custom_upload_timestamp is not None: - kwargs['custom_upload_timestamp'] = custom_upload_timestamp + kwargs['customUploadTimestamp'] = custom_upload_timestamp return self._post_json( api_url, diff --git a/b2sdk/_internal/replication/monitoring.py b/b2sdk/_internal/replication/monitoring.py index bae3a2a83..2c3cc983d 100644 --- a/b2sdk/_internal/replication/monitoring.py +++ b/b2sdk/_internal/replication/monitoring.py @@ -12,7 +12,8 @@ import sys from concurrent.futures import ThreadPoolExecutor from dataclasses import dataclass, field -from queue import Queue +from queue import Full, Queue +from threading import Event from typing import ClassVar, Iterator from ..api import B2Api @@ -195,29 +196,49 @@ def scan(self, scan_destination: bool = True) -> AbstractScanReport: """ report = self.REPORT_CLASS() queue = Queue(maxsize=self.QUEUE_SIZE) + stop = Event() # set when the consumer dies, so the producer never blocks on a full queue + + def put(item) -> bool: + while not stop.is_set(): + try: + queue.put(item, timeout=0.1) + return True + except Full: + pass + return False if not scan_destination: def fill_queue(): - for path in self.source_folder.all_files( - policies_manager=self.scan_policies_manager, - reporter=self.report, - ): - queue.put((path,), block=True) - queue.put(None, block=True) + try: + for path in self.source_folder.all_files( + policies_manager=self.scan_policies_manager, + reporter=self.report, + ): + if not put((path,)): + return + finally: + put(None) else: def fill_queue(): - for pair in self.iter_pairs(): - queue.put(pair, block=True) - queue.put(None, block=True) + try: + for pair in self.iter_pairs(): + if not put(pair): + return + finally: + put(None) def consume_queue(): while True: items = queue.get(block=True) if items is None: # using None as "end of queue" marker break - report.add(*items) + try: + report.add(*items) + except BaseException: + stop.set() + raise with ThreadPoolExecutor(max_workers=2) as thread_pool: futures = [ diff --git a/b2sdk/_internal/scan/folder.py b/b2sdk/_internal/scan/folder.py index 254a5f55b..66553ea2a 100644 --- a/b2sdk/_internal/scan/folder.py +++ b/b2sdk/_internal/scan/folder.py @@ -289,7 +289,7 @@ def _walk_relative_paths( except OSError: if reporter is not None: reporter.local_access_error(str(local_path)) - continue + continue local_scan_path = LocalPath( absolute_path=self.make_full_path(str(relative_file_path)), @@ -303,7 +303,7 @@ def _walk_relative_paths( if not _file_read_access(local_path): if reporter is not None: reporter.local_permission_error(str(local_path)) - continue + continue yield local_scan_path diff --git a/b2sdk/_internal/sync/sync.py b/b2sdk/_internal/sync/sync.py index 2ce4f72d5..252f40dd7 100644 --- a/b2sdk/_internal/sync/sync.py +++ b/b2sdk/_internal/sync/sync.py @@ -10,6 +10,7 @@ from __future__ import annotations import concurrent.futures as futures +import io import logging from enum import Enum, unique from typing import cast @@ -202,7 +203,11 @@ def sync_folders( queue_limit = self.max_workers + 1000 sync_executor = BoundedQueueExecutor(unbounded_executor, queue_limit=queue_limit) - if source_type == 'local' and reporter is not None: + if reporter is None: + # silent reporter so that downstream code can call it unconditionally + reporter = SyncReport(io.StringIO(), True) + + if source_type == 'local': # Start the thread that counts the local files. That's the operation # that should be fastest, and it provides scale for the progress reporting. sync_executor.submit(count_files, source_folder, reporter, self.policies_manager) diff --git a/b2sdk/_internal/transfer/inbound/downloader/parallel.py b/b2sdk/_internal/transfer/inbound/downloader/parallel.py index a3ae8c0f5..ab185130f 100644 --- a/b2sdk/_internal/transfer/inbound/downloader/parallel.py +++ b/b2sdk/_internal/transfer/inbound/downloader/parallel.py @@ -156,7 +156,7 @@ def _finish_hashing(self, first_part, file, hasher, content_length): stop = True else: to_hash = data - hasher.update(data) + hasher.update(to_hash) current_offset += len(to_hash) if stop: break @@ -248,6 +248,8 @@ def __init__(self, file, max_queue_depth): self.file = file self.queue = queue.Queue(max_queue_depth) self.total = 0 + self.error: BaseException | None = None + self._stopped = threading.Event() self.stats_collector = StatsCollector(str(self.file), 'writer', 'seek') super().__init__() @@ -266,11 +268,18 @@ def run(self): if shutdown: break - with stats_collector_other: - file.seek(offset) + if self.error is not None: + continue # keep draining so that producers never block - with stats_collector_write: - file.write(data) + try: + with stats_collector_other: + file.seek(offset) + + with stats_collector_write: + file.write(data) + except Exception as e: + self.error = e + continue self.total += len(data) @@ -279,12 +288,25 @@ def __enter__(self): return self def queue_write(self, offset: int, data: bytes) -> None: - self.queue.put((False, offset, data)) + item = (False, offset, data) + while True: + if self.error is not None: + raise self.error + if self._stopped.is_set(): + raise RuntimeError('writer has been stopped') + try: + self.queue.put(item, timeout=0.1) + return + except queue.Full: + pass def __exit__(self, exc_type, exc_val, exc_tb): - self.queue.put((True, None, None)) + self._stopped.set() # make straggling producers fail instead of blocking forever + self.queue.put((True, None, None)) # writer keeps draining, so this cannot block for long self.join() self.stats_collector.report() + if exc_type is None and self.error is not None: + raise self.error def download_first_part( diff --git a/changelog.d/+copy-file-headers.fixed.md b/changelog.d/+copy-file-headers.fixed.md new file mode 100644 index 000000000..e281ca1b4 --- /dev/null +++ b/changelog.d/+copy-file-headers.fixed.md @@ -0,0 +1 @@ +Pass `expires`, `content_disposition`, `content_encoding` and `content_language` through `Bucket.copy` to the created file instead of dropping them. diff --git a/changelog.d/+custom-upload-timestamp.fixed.md b/changelog.d/+custom-upload-timestamp.fixed.md new file mode 100644 index 000000000..23a2d9ecc --- /dev/null +++ b/changelog.d/+custom-upload-timestamp.fixed.md @@ -0,0 +1 @@ +Send `customUploadTimestamp` under its B2 wire name when starting a large file, so custom upload timestamps are no longer ignored. diff --git a/changelog.d/+local-scan-errors.fixed.md b/changelog.d/+local-scan-errors.fixed.md new file mode 100644 index 000000000..000363130 --- /dev/null +++ b/changelog.d/+local-scan-errors.fixed.md @@ -0,0 +1 @@ +Keep scanning a local folder after a file cannot be read or accessed when no reporter is given, instead of failing on that file. diff --git a/changelog.d/+parallel-download-writer.fixed.md b/changelog.d/+parallel-download-writer.fixed.md new file mode 100644 index 000000000..60d86aa3d --- /dev/null +++ b/changelog.d/+parallel-download-writer.fixed.md @@ -0,0 +1 @@ +Parallel download: hash the data that was actually written, and surface a failing writer to producers instead of blocking them or losing the error. diff --git a/changelog.d/+replication-monitor-hang.fixed.md b/changelog.d/+replication-monitor-hang.fixed.md new file mode 100644 index 000000000..c70a5291f --- /dev/null +++ b/changelog.d/+replication-monitor-hang.fixed.md @@ -0,0 +1 @@ +Stop the replication monitor from hanging when its consumer fails: the producer no longer blocks on a full queue and always signals the end of input. diff --git a/changelog.d/+sqlite-allowed-param.fixed.md b/changelog.d/+sqlite-allowed-param.fixed.md new file mode 100644 index 000000000..d9771ce30 --- /dev/null +++ b/changelog.d/+sqlite-allowed-param.fixed.md @@ -0,0 +1 @@ +Store the account's allowed capabilities in SQLite with a bound parameter instead of string formatting, and reset upload pools after an account-info schema update. diff --git a/changelog.d/+sync-silent-reporter.fixed.md b/changelog.d/+sync-silent-reporter.fixed.md new file mode 100644 index 000000000..0df357bd2 --- /dev/null +++ b/changelog.d/+sync-silent-reporter.fixed.md @@ -0,0 +1 @@ +Accept `reporter=None` in `Synchronizer.sync_folders` by using a silent reporter instead of failing. diff --git a/test/unit/account_info/test_account_info.py b/test/unit/account_info/test_account_info.py index 8c40ec27e..e1969569b 100644 --- a/test/unit/account_info/test_account_info.py +++ b/test/unit/account_info/test_account_info.py @@ -217,6 +217,18 @@ def test_set_auth_data_compatibility(self, account_info_default_data, allowed): ) assert account_info.get_allowed() == allowed + def test_clear_drops_cached_upload_urls(self, account_info_default_data): + """After ``clear()`` (log out) no upload URL or token of the cleared account may be handed out.""" + account_info = self._make_info() + account_info.set_auth_data(**account_info_default_data) + account_info.put_bucket_upload_url('bucket-0', 'http://bucket-0', 'bucket-0_auth') + account_info.put_large_file_upload_url('file_0', 'http://file_0', 'auth_0') + + account_info.clear() + + assert (None, None) == account_info.take_bucket_upload_url('bucket-0') + assert (None, None) == account_info.take_large_file_upload_url('file_0') + def test_clear_bucket_upload_data(self): account_info = self._make_info() account_info.put_bucket_upload_url('bucket-0', 'http://bucket-0', 'bucket-0_auth') diff --git a/test/unit/account_info/test_sqlite_account_info.py b/test/unit/account_info/test_sqlite_account_info.py index a025a3d5d..afb2231f6 100644 --- a/test/unit/account_info/test_sqlite_account_info.py +++ b/test/unit/account_info/test_sqlite_account_info.py @@ -194,6 +194,45 @@ def test_migrate_to_5_v3( assert new_account_info.get_allowed() == exp_allowed assert new_account_info._get_update_count(end_version) == 1 + @pytest.mark.parametrize( + ('start_version', 'end_version'), + [ + (4, 5), + (5, 6), + ], + ) + @pytest.mark.apiver(from_ver=3) + def test_migrate_to_5_v3_name_prefix_with_apostrophe( + self, + sqlite_account_info_factory, + account_info_default_data: dict, + start_version: int, + end_version: int, + ): + """A single quote in the stored ``allowed`` JSON must not break the migration SQL.""" + old_allowed = dict( + bucketId='123', + bucketName='bucket1', + capabilities=['listBuckets', 'readBuckets'], + namePrefix="it's/", + ) + old_account_info = sqlite_account_info_factory(last_upgrade_to_run=start_version) + old_account_info.set_auth_data(**account_info_default_data) + + with old_account_info._get_connection() as conn: + conn.execute('UPDATE account SET allowed = ?;', (json.dumps(old_allowed),)) + + new_account_info = self.sqlite_account_info_factory( + file_name=old_account_info.filename, last_upgrade_to_run=end_version + ) + + assert new_account_info.get_allowed() == dict( + buckets=[{'id': '123', 'name': 'bucket1'}], + capabilities=['listBuckets', 'readBuckets'], + namePrefix="it's/", + ) + assert new_account_info._get_update_count(end_version) == 1 + @pytest.mark.apiver(2) def test_multi_bucket_key_error_apiver_v2( self, diff --git a/test/unit/b2http/test_b2http.py b/test/unit/b2http/test_b2http.py index 6ae18269e..138464793 100644 --- a/test/unit/b2http/test_b2http.py +++ b/test/unit/b2http/test_b2http.py @@ -530,10 +530,20 @@ def test_set_locale_context_manager(self): if saved == test_locale: test_locale, other_locale = other_locale, test_locale - locale.setlocale(locale.LC_ALL, other_locale) - with setlocale(test_locale): - assert locale.setlocale(category=locale.LC_ALL) == test_locale - locale.setlocale(locale.LC_ALL, saved) + try: + locale.setlocale(locale.LC_ALL, other_locale) + with setlocale(test_locale): + assert locale.setlocale(category=locale.LC_ALL) == test_locale + # leaving the context manager must put the previous locale back... + assert locale.setlocale(category=locale.LC_ALL) == other_locale + + # ...also when the body raises + with pytest.raises(RuntimeError): + with setlocale(test_locale): + raise RuntimeError('boom') + assert locale.setlocale(category=locale.LC_ALL) == other_locale + finally: + locale.setlocale(locale.LC_ALL, saved) class TestClockSkewHook(TestBase): diff --git a/test/unit/bucket/test_bucket.py b/test/unit/bucket/test_bucket.py index f140a6612..86ff96fc1 100644 --- a/test/unit/bucket/test_bucket.py +++ b/test/unit/bucket/test_bucket.py @@ -32,6 +32,7 @@ B2Error, B2RequestTimeoutDuringUpload, BucketIdNotFound, + Conflict, DestinationDirectoryDoesntAllowOperation, DestinationDirectoryDoesntExist, DestinationIsADirectory, @@ -1450,6 +1451,7 @@ def test_copy_retention(self): resulting_file_version = self.bucket.copy( file_id, 'copied_file', + length=length, file_retention=FileRetentionSetting(RetentionMode.COMPLIANCE, 100), legal_hold=LegalHold.ON, max_part_size=400, @@ -1460,6 +1462,32 @@ def test_copy_retention(self): ) self.assertEqual(LegalHold.ON, resulting_file_version.legal_hold) + @pytest.mark.apiver(from_ver=2) + def test_copy_keeps_http_header_params_with_and_without_length(self): + """ + ``expires``, ``content_disposition``, ``content_encoding`` and ``content_language`` + must end up in the new file's file_info whether the copy is a plain ``b2_copy_file`` + (no ``length``) or goes through the large file interface (``length`` given). + """ + for length in [None, 5]: + with self.subTest(length=length): + file_id = self._make_file() + copied = self.bucket.copy( + file_id, + f'copied_{length}.txt', + offset=0, + length=length, + content_type='text/plain', + content_disposition='attachment', + expires='Thu, 01 Dec 2050 16:00:00 GMT', + content_language='en', + content_encoding='identity', + ) + self.assertEqual('attachment', copied.file_info['b2-content-disposition']) + self.assertEqual('Thu, 01 Dec 2050 16:00:00 GMT', copied.file_info['b2-expires']) + self.assertEqual('en', copied.file_info['b2-content-language']) + self.assertEqual('identity', copied.file_info['b2-content-encoding']) + def test_copy_encryption(self): data = b'hello_world' a = self.bucket.upload_bytes(data, 'a') @@ -1829,13 +1857,12 @@ def test_update_if_revision_is(self): updated_bucket = self.api.get_bucket_by_name(self.bucket.name) self.assertEqual([{'fileNamePrefix': 'is_life'}], updated_bucket.lifecycle_rules) - try: + # a stale revision must be rejected, and the rejected update must not be applied + with self.assertRaises(Conflict): self.bucket.update( - lifecycle_rules=[{'fileNamePrefix': 'is_life'}], + lifecycle_rules=[{'fileNamePrefix': 'stale_update'}], if_revision_is=current_revision, # this is now the old revision ) - except Exception: - pass not_updated_bucket = self.api.get_bucket_by_name(self.bucket.name) self.assertEqual([{'fileNamePrefix': 'is_life'}], not_updated_bucket.lifecycle_rules) @@ -3018,6 +3045,16 @@ def setUp(self): def test_download_by_id_progress_monotonic(self): self.download_file_by_id(self.file_version.id_, progress_listener=self.progress_listener) self._verify(self.DATA) + # _verify does not require incremental reports; a single end-of-download report + # would pass it, so require several, non-decreasing ones here + valid, reason = self.progress_listener.is_valid_reason( + check_progress=True, + check_monotonic_progress=True, + ) + assert valid, reason + reports = [int(v) for v in self.progress_listener.history[1:] if v != 'closed'] + assert len(reports) > 1 + assert reports == sorted(reports) # Truncated downloads diff --git a/test/unit/internal/transfer/downloader/test_parallel.py b/test/unit/internal/transfer/downloader/test_parallel.py index cac4ebf28..eda3d4be6 100644 --- a/test/unit/internal/transfer/downloader/test_parallel.py +++ b/test/unit/internal/transfer/downloader/test_parallel.py @@ -8,6 +8,7 @@ # ###################################################################### import hashlib +import threading from concurrent.futures import ThreadPoolExecutor from io import BytesIO from unittest.mock import Mock @@ -86,6 +87,27 @@ def test_download_file(apiver_module, b2api, bucket, downloader, output_file): mock_response.close.assert_called_once() +def test_download_file__does_not_hash_bytes_after_the_downloaded_range( + apiver_module, b2api, bucket, downloader +): + """ + The returned hash is the hash of the downloaded content, even when the output file already + holds more data after the end of the downloaded range. + """ + file_size = 100 + mock_response, download_version = mock_download_response_factory( + apiver_module, bucket, file_size=file_size + ) + output_file = BytesIO(b'trailing data that is not part of the download' * 10) + + bytes_written, hash_hex = downloader.download( + output_file, mock_response, download_version, b2api.session + ) + + assert bytes_written == file_size + assert hash_hex == '7804df8c623573ccfc1993e04981006e5bc30383' # sha1 of b'dummy' * 20 + + def test_download_file__data_stream_error__in_first_response( apiver_module, b2api, bucket, downloader, output_file ): @@ -169,3 +191,44 @@ def iter_content(chunk_size=1, decode_unicode=False): assert bytes_written == file_size assert output_file.getvalue() == b'dUMMY' + b'DUMMY' * 19 + + +class FileFailingOnSecondWrite(BytesIO): + """A file-like object that behaves like a full disk after the first write.""" + + def __init__(self): + super().__init__() + self.write_calls = 0 + + def write(self, data): + self.write_calls += 1 + if self.write_calls > 1: + raise OSError('disk full') + return super().write(data) + + +def test_writer_thread__write_error__does_not_block_producers(apiver_module): + """ + If the file cannot be written, the error must reach the caller and the producers must not + block forever on a queue that nobody drains any more. + """ + from b2sdk._internal.transfer.inbound.downloader.parallel import WriterThread + + outcome = {} + + def produce(): + try: + with WriterThread(FileFailingOnSecondWrite(), max_queue_depth=4) as writer: + for offset in range(50): + writer.queue_write(offset, b'x') + except OSError as e: + outcome['error'] = e + + # daemon thread: if the bug is present, this thread blocks forever and must not keep the + # test process alive + producer = threading.Thread(target=produce, daemon=True) + producer.start() + producer.join(timeout=10) + + assert not producer.is_alive(), 'producer is blocked on a queue that is no longer drained' + assert 'disk full' in str(outcome.get('error')) diff --git a/test/unit/replication/test_monitoring.py b/test/unit/replication/test_monitoring.py index f4955dae2..798068fec 100644 --- a/test/unit/replication/test_monitoring.py +++ b/test/unit/replication/test_monitoring.py @@ -9,6 +9,10 @@ ###################################################################### from __future__ import annotations +import queue +import threading + +import pytest from apiver_deps import ( SSE_B2_AES, EncryptionAlgorithm, @@ -20,6 +24,8 @@ RetentionMode, ) +from b2sdk._internal.replication import monitoring as monitoring_module + SSE_C_AES = EncryptionSetting( mode=EncryptionMode.SSE_C, algorithm=EncryptionAlgorithm.AES256, @@ -280,3 +286,87 @@ def test_scan_source_and_destination( ] == 1 ) + + +class _SpyQueue(queue.Queue): + """A queue that remembers its instances, so the test can release threads stuck on it.""" + + instances: list = [] + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self.instances.append(self) + + +def _release_blocked_threads(spy_queue: queue.Queue, worker: threading.Thread) -> None: + """Unblock whichever side of the queue is stuck, so that a failing test does not leak threads.""" + for _ in range(50): + if not worker.is_alive(): + return + while True: + try: + spy_queue.get_nowait() # frees a producer blocked on put() + except queue.Empty: + break + worker.join(timeout=0.1) + if not worker.is_alive(): + return + try: + spy_queue.put_nowait(None) # frees a consumer blocked on get() + except queue.Full: + pass + worker.join(timeout=0.1) + + +@pytest.mark.parametrize('failing_side', ['producer', 'consumer']) +def test_scan__failure_in_one_thread__is_raised_instead_of_hanging( + source_bucket, test_file, monitor, monkeypatch, failing_side +): + """ + When listing files (producer) or building the report (consumer) raises, ``scan`` must + propagate the error. The two threads talk through a bounded queue, so the surviving + thread must not wait forever for a partner that is gone. + """ + for i in range(6): + source_bucket.upload_local_file(test_file, f'folder/test-{i}.txt') + + _SpyQueue.instances = [] + monkeypatch.setattr(monitoring_module, 'Queue', _SpyQueue) + monkeypatch.setattr(type(monitor), 'QUEUE_SIZE', 2) + + if failing_side == 'producer': + base_folder_class = type(monitor).B2_FOLDER_CLASS + + class FailingFolder(base_folder_class): + def all_files(self, *args, **kwargs): + for i, path in enumerate(super().all_files(*args, **kwargs)): + if i == 2: + raise RuntimeError('listing failed') + yield path + + monkeypatch.setattr(type(monitor), 'B2_FOLDER_CLASS', FailingFolder) + else: + + class FailingReport(type(monitor).REPORT_CLASS): + def add(self, *args, **kwargs): + raise RuntimeError('report failed') + + monkeypatch.setattr(type(monitor), 'REPORT_CLASS', FailingReport) + + outcome = {} + + def run_scan(): + try: + monitor.scan(scan_destination=False) + except RuntimeError as e: + outcome['error'] = e + + # daemon thread: with the bug present, scan() never returns + worker = threading.Thread(target=run_scan, daemon=True) + worker.start() + worker.join(timeout=10) + hung = worker.is_alive() + _release_blocked_threads(_SpyQueue.instances[-1], worker) + + assert not hung, 'scan() is blocked waiting for the other thread' + assert str(outcome.get('error')) in ('listing failed', 'report failed') diff --git a/test/unit/scan/test_folder_traversal.py b/test/unit/scan/test_folder_traversal.py index 4971b08f7..5c601b71f 100644 --- a/test/unit/scan/test_folder_traversal.py +++ b/test/unit/scan/test_folder_traversal.py @@ -793,3 +793,40 @@ def test_excluded_without_permissions(self, tmp_path, fs_perm_tool): assert not reporter.warnings reporter.close() + + @pytest.mark.skipif( + platform.system() == 'Windows', reason='Broken symlinks are only tested on Unix' + ) + @pytest.mark.parametrize('broken_link_name', ['a_broken_link', 'z_broken_link']) + @pytest.mark.parametrize('with_reporter', [True, False]) + def test_broken_symlink_is_skipped(self, tmp_path, broken_link_name, with_reporter): + """ + A symlink to a missing target must be skipped, whether or not a reporter is given + (``reporter`` is optional) and whatever its position among the other entries. + """ + (tmp_path / 'file.txt').write_text('content') + (tmp_path / broken_link_name).symlink_to(tmp_path / 'missing_target') + + reporter = ProgressReport(sys.stdout, False) if with_reporter else None + folder = LocalFolder(str(tmp_path)) + local_paths = list( + folder.all_files(reporter=reporter, policies_manager=ScanPoliciesManager()) + ) + + assert [path.relative_path for path in local_paths] == ['file.txt'] + if reporter is not None: + assert len(reporter.warnings) == 1 + reporter.close() + + @pytest.mark.skipif( + platform.system() == 'Windows', reason='Unix-only filesystem permissions are tested' + ) + def test_unreadable_file_is_skipped_without_reporter(self, tmp_path, fs_perm_tool): + (tmp_path / 'readable.txt').write_text('content') + (tmp_path / 'no_perm_file.txt').write_text('content') + fs_perm_tool.deny_access(tmp_path / 'no_perm_file.txt') + + folder = LocalFolder(str(tmp_path)) + local_paths = list(folder.all_files(reporter=None, policies_manager=ScanPoliciesManager())) + + assert [path.relative_path for path in local_paths] == ['readable.txt'] diff --git a/test/unit/sync/test_sync.py b/test/unit/sync/test_sync.py index a9b51d7ec..ccb4692df 100644 --- a/test/unit/sync/test_sync.py +++ b/test/unit/sync/test_sync.py @@ -32,6 +32,8 @@ ) from apiver_deps_exception import DestFileNewer, InvalidArgument +import b2sdk._internal.sync.sync as sync_module + from ..fixtures.folder import * from .fixtures import * @@ -975,13 +977,11 @@ def check_path_and_get_size(self): large_file_sha1=local_sha1 if should_be_incremental else None, ) ] - # In Python 3.7 unittest.mock.call doesn't have `args` properly defined. Instead we have to take 1st index. - # TODO: use .args[0] instead of [1] when we drop Python 3.7 - num_calls = len(bucket.mock_calls[0][1]) - assert num_calls == 2 if should_be_incremental else 1, bucket.mock_calls[0] + # first positional argument of concatenate() is the list of sources + sources = bucket.mock_calls[0][1][0] + assert len(sources) == (2 if should_be_incremental else 1), bucket.mock_calls[0] if should_be_incremental: - # Order of indices: call index, pick arguments, pick first argument, first element of the first argument. - assert isinstance(bucket.mock_calls[0][1][0][0], CopySource) + assert isinstance(sources[0], CopySource) def test_sync_lexicographical_order(self, synchronizer_factory): """ @@ -1008,6 +1008,59 @@ def test_sync_lexicographical_order(self, synchronizer_factory): dst_with_files = self.folder_factory('b2', *files) self.assert_folder_sync_actions(synchronizer, src, dst_with_files, []) + @pytest.mark.apiver(from_ver=2) + @pytest.mark.parametrize( + 'src_type, dst_type', + [ + ('b2', 'local'), + ('local', 'b2'), + ], + ) + def test_sync_folders_without_reporter(self, synchronizer_factory, src_type, dst_type): + """ + ``sync_folders`` documents ``reporter`` as optional (``SyncReport | None``), so a + sync run without a reporter must complete instead of failing on ``None``. + """ + synchronizer = synchronizer_factory(dry_run=True, allow_empty_source=True) + src = self.folder_factory(src_type, ('a.txt', [200], 10)) + dst = self.folder_factory(dst_type) + + synchronizer.sync_folders(src, dst, TODAY, None) + + @pytest.mark.xfail( + strict=True, + reason=( + 'known bug (review b2-sdk-python prod:7, sync.py:201, owner decides): the executor ' + 'is not shut down when scheduling raises, so queued actions keep running in ' + 'the background; whether to wait for or cancel them is not decided' + ), + ) + def test_sync_folders_shuts_executor_down_when_scheduling_fails(self, synchronizer_factory): + synchronizer = synchronizer_factory(dry_run=True, allow_empty_source=True) + src = self.folder_factory('b2', ('a.txt', [200], 10)) + dst = self.folder_factory('local') + + def failing_actions(*args, **kwargs): + yield mock.MagicMock() + raise RuntimeError('scheduling failed') + + executors = [] + real_executor_class = sync_module.BoundedQueueExecutor + + def spy(*args, **kwargs): + executor = real_executor_class(*args, **kwargs) + executor.shutdown = mock.MagicMock(wraps=executor.shutdown) + executors.append(executor) + return executor + + with mock.patch.object(synchronizer, '_make_folder_sync_actions', failing_actions): + with mock.patch.object(sync_module, 'BoundedQueueExecutor', spy): + with pytest.raises(RuntimeError, match='scheduling failed'): + synchronizer.sync_folders(src, dst, TODAY, None) + + assert len(executors) == 1 + executors[0].shutdown.assert_called_once() + class TstEncryptionSettingsProvider(AbstractSyncEncryptionSettingsProvider): def __init__(self, source_encryption_setting, destination_encryption_setting): diff --git a/test/unit/sync/test_sync_report.py b/test/unit/sync/test_sync_report.py index 496224f79..7d908ad47 100644 --- a/test/unit/sync/test_sync_report.py +++ b/test/unit/sync/test_sync_report.py @@ -27,6 +27,35 @@ def test_bad_terminal(self): sync_report = SyncReport(stdout, False) sync_report.print_completion('transferred: 123.txt') + def test_bad_terminal_falls_back_to_escaped_output_and_warns_once(self): + written = [] + + class BadTerminal: + encoding = 'ascii' + + def __init__(self): + self.fail_next = True + + def write(self, text): + if self.fail_next: + self.fail_next = False + raise UnicodeEncodeError('codec', 'foo', 100, 105, 'artificial') + written.append(text) + + def flush(self): + pass + + sync_report = SyncReport(BadTerminal(), True) + sync_report.print_completion('transferred: caf\u00e9.txt') + sync_report.print_completion('transferred: other.txt') + + output = ''.join(written) + assert ( + output.count('!WARNING! this terminal cannot properly handle progress reporting') == 1 + ) + assert 'transferred: caf\\xe9.txt' in output + assert 'transferred: other.txt' in output + @pytest.mark.apiver(to_ver=1) def test_legacy_methods(self): stdout = MagicMock() diff --git a/test/unit/test_raw_api.py b/test/unit/test_raw_api.py index 4745f02ed..b181f44d5 100644 --- a/test/unit/test_raw_api.py +++ b/test/unit/test_raw_api.py @@ -169,3 +169,38 @@ def test_raw_api_omits_encryption_from_request_when_not_given(raw_api, call, tra sent = {**headers, **(payload if isinstance(payload, dict) else {})} assert not [key for key in sent if 'encryption' in key.lower()], sent + + +def test_start_large_file_sends_custom_upload_timestamp_under_its_wire_name(raw_api): + """ + The b2_start_large_file request body uses camelCase for every field, so the custom + upload timestamp must be sent as ``customUploadTimestamp``. The simulator never looks at + the wire key, so only a request-level assertion can catch a misspelling. + """ + raw_api.start_large_file( + 'api-url', + 'account-token', + 'bucket-id', + 'file-name', + 'text/plain', + {}, + custom_upload_timestamp=123, + ) + + _, _, payload = raw_api.b2_http.post_json_return_json.call_args.args[:3] + + assert payload.get('customUploadTimestamp') == 123, payload + assert 'custom_upload_timestamp' not in payload, payload + + +def test_update_bucket_sends_if_revision_is_under_its_wire_name(raw_api): + """ + ``ifRevisionIs`` is the optimistic-locking guard of b2_update_bucket. If it is not on the + wire, concurrent bucket updates silently overwrite each other, and the simulator, which + takes the Python argument directly, cannot tell. + """ + raw_api.update_bucket('api-url', 'account-token', 'account-id', 'bucket-id', if_revision_is=7) + + _, _, payload = raw_api.b2_http.post_json_return_json.call_args.args[:3] + + assert payload.get('ifRevisionIs') == 7, payload diff --git a/test/unit/test_sdkharness_conformance_resilience_contract.py b/test/unit/test_sdkharness_conformance_resilience_contract.py index 41d47c5a1..a61f945de 100644 --- a/test/unit/test_sdkharness_conformance_resilience_contract.py +++ b/test/unit/test_sdkharness_conformance_resilience_contract.py @@ -162,6 +162,27 @@ def test_leaf_checks_refuse_ambient_staging_runs(leaf): assert 'real-looking' not in refused.stdout + refused.stderr +@pytest.mark.parametrize('leaf', LEAVES, ids=lambda path: f'{path.parent.name}/{path.name}') +def test_leaf_checks_refuse_staging_target_even_with_a_valid_loopback_simulator(leaf): + """ + The staging refusal must be what stops the run. Everything else about this environment is + valid (loopback simulator, test credential), so if the target check were deleted the leaf + would go on to try the simulator instead of refusing. + """ + prefix = leaf.parent.name.upper() + ambient = { + f'{prefix}_TARGET': 'staging', + f'{prefix}_SIMULATOR_URL': 'http://127.0.0.1:8180', + } + if prefix == 'RESILIENCE': + ambient['RESILIENCE_CONTROL_URL'] = 'http://127.0.0.1:8181' + + refused = run_leaf(leaf, ambient) + + assert refused.returncode == 1 + assert 'FAIL (configuration -- only the simulator target is supported' in refused.stdout + + @pytest.mark.parametrize('leaf', LEAVES[:2] + LEAVES[-2:], ids=lambda path: path.name) def test_leaf_checks_refuse_missing_or_non_loopback_simulator(leaf): prefix = leaf.parent.name.upper() diff --git a/test/unit/v0/test_bucket.py b/test/unit/v0/test_bucket.py index 6c1aa2c6d..9dbfe1c6e 100644 --- a/test/unit/v0/test_bucket.py +++ b/test/unit/v0/test_bucket.py @@ -220,7 +220,16 @@ def __call__(self, *args, **kwargs): raise InvalidAuthToken('message', 401) self.simulator.create_bucket = InvalidAuthTokenWrapper(self.simulator.create_bucket) - self.bucket = self.api.create_bucket('your-bucket', 'allPublic') + with mock.patch.object( + self.api.session, 'authorize_account', wraps=self.api.session.authorize_account + ) as authorize_account: + self.bucket = self.api.create_bucket('your-bucket', 'allPublic') + + # the invalid token must have triggered exactly one re-authorization, and the retried + # call must have created the bucket + authorize_account.assert_called_once() + self.assertEqual('your-bucket', self.bucket.name) + self.assertEqual(self.bucket.id_, self.api.get_bucket_by_name('your-bucket').id_) class TestListParts(TestCaseWithBucket): @@ -598,6 +607,7 @@ def test_copy_retention(self): resulting_file_version = self.bucket.copy( file_id, 'copied_file', + length=length, file_retention=FileRetentionSetting(RetentionMode.COMPLIANCE, 100), legal_hold=LegalHold.ON, max_part_size=400, diff --git a/test/unit/v0/test_sync.py b/test/unit/v0/test_sync.py index 4ec679284..a4713053c 100644 --- a/test/unit/v0/test_sync.py +++ b/test/unit/v0/test_sync.py @@ -973,7 +973,6 @@ def test_wait_for_running_jobs(self): """ raw_executor = futures.ThreadPoolExecutor(2) bounded_executor = BoundedQueueExecutor(raw_executor, 1) - assert_equal = self.assertEqual class CountAtOnce: """ @@ -984,12 +983,14 @@ class CountAtOnce: def __init__(self): self.running_at_once = 0 + self.max_seen = 0 + self.counter = 0 self.lock = threading.Lock() def run(self): with self.lock: self.running_at_once += 1 - assert_equal(1, self.running_at_once) + self.max_seen = max(self.max_seen, self.running_at_once) # While we are sleeping here, no other actions should start # running. If they do, they will increment the counter and # fail the above assertion. @@ -1004,6 +1005,9 @@ def run(self): for _ in range(5): bounded_executor.submit(count_at_once.run) bounded_executor.shutdown() + self.assertEqual(1, count_at_once.max_seen) + self.assertEqual(5, count_at_once.counter) + self.assertEqual(2, bounded_executor.get_num_exceptions()) if __name__ == '__main__': diff --git a/test/unit/v1/test_bounded_queue_executor.py b/test/unit/v1/test_bounded_queue_executor.py index 8f94a857f..293027314 100644 --- a/test/unit/v1/test_bounded_queue_executor.py +++ b/test/unit/v1/test_bounded_queue_executor.py @@ -10,6 +10,7 @@ from __future__ import annotations import concurrent.futures as futures +import threading import time from ..test_base import TestBase @@ -46,6 +47,33 @@ def fcn(): answers = list(map(lambda f: f.result(), futures)) self.assertEqual(list(range(10)), answers) + def test_submit_blocks_until_a_slot_is_free(self): + """With a queue limit of 1, a second submit() must wait for the first job to finish.""" + release_first_job = threading.Event() + first_job_started = threading.Event() + + def first_job(): + first_job_started.set() + release_first_job.wait(timeout=10) + + self.executor.submit(first_job) + assert first_job_started.wait(timeout=10) + + second_submit_returned = threading.Event() + + def submit_second_job(): + self.executor.submit(lambda: None) + second_submit_returned.set() + + # daemon thread: it must not keep the test process alive if submit() blocks for good + submitter = threading.Thread(target=submit_second_job, daemon=True) + submitter.start() + try: + self.assertFalse(second_submit_returned.wait(timeout=0.3), 'submit() did not block') + finally: + release_first_job.set() + self.assertTrue(second_submit_returned.wait(timeout=10), 'submit() never returned') + def test_no_exceptions(self): f = self.executor.submit(lambda: 1) self.executor.shutdown() diff --git a/test/unit/v1/test_raw_api.py b/test/unit/v1/test_raw_api.py index 4202fa653..0f9aad68a 100644 --- a/test/unit/v1/test_raw_api.py +++ b/test/unit/v1/test_raw_api.py @@ -116,17 +116,26 @@ def test_assertion_raises(self): self.raw_api.update_bucket('test', 'account_auth_token', 'account_id', 'bucket_id') @pytest.mark.parametrize( - 'bucket_type,bucket_info,default_retention', + 'bucket_type,bucket_info,default_retention,expected_payload', ( - (None, {}, None), + (None, {}, None, {'bucketInfo': {}}), ( 'allPublic', None, BucketRetentionSetting(RetentionMode.COMPLIANCE, RetentionPeriod(years=1)), + { + 'bucketType': 'allPublic', + 'defaultRetention': { + 'mode': 'compliance', + 'period': {'duration': 1, 'unit': 'years'}, + }, + }, ), ), ) - def test_assertion_not_raises(self, bucket_type, bucket_info, default_retention): + def test_assertion_not_raises( + self, bucket_type, bucket_info, default_retention, expected_payload + ): self.raw_api.update_bucket( 'test', 'account_auth_token', @@ -137,8 +146,15 @@ def test_assertion_not_raises(self, bucket_type, bucket_info, default_retention) default_retention=default_retention, ) + _, _, payload = self.raw_api.b2_http.post_json_return_json.call_args.args[:3] + assert payload == { + 'accountId': 'account_id', + 'bucketId': 'bucket_id', + **expected_payload, + } + @pytest.mark.parametrize( - 'encryption_setting,', + 'encryption_setting', ( EncryptionSetting( mode=EncryptionMode.SSE_C, @@ -169,7 +185,7 @@ class TestCreateBucket(BucketTestBase): """Test creating bucket.""" @pytest.mark.parametrize( - 'encryption_setting,', + 'encryption_setting', ( EncryptionSetting( mode=EncryptionMode.SSE_C, diff --git a/test/unit/v1/test_sync.py b/test/unit/v1/test_sync.py index 03e0cf189..cf51bd433 100644 --- a/test/unit/v1/test_sync.py +++ b/test/unit/v1/test_sync.py @@ -999,7 +999,6 @@ def test_wait_for_running_jobs(self): """ raw_executor = futures.ThreadPoolExecutor(2) bounded_executor = BoundedQueueExecutor(raw_executor, 1) - assert_equal = self.assertEqual class CountAtOnce: """ @@ -1010,12 +1009,14 @@ class CountAtOnce: def __init__(self): self.running_at_once = 0 + self.max_seen = 0 + self.counter = 0 self.lock = threading.Lock() def run(self): with self.lock: self.running_at_once += 1 - assert_equal(1, self.running_at_once) + self.max_seen = max(self.max_seen, self.running_at_once) # While we are sleeping here, no other actions should start # running. If they do, they will increment the counter and # fail the above assertion. @@ -1030,6 +1031,9 @@ def run(self): for _ in range(5): bounded_executor.submit(count_at_once.run) bounded_executor.shutdown() + self.assertEqual(1, count_at_once.max_seen) + self.assertEqual(5, count_at_once.counter) + self.assertEqual(2, bounded_executor.get_num_exceptions()) if __name__ == '__main__': From bfb3086cd429abec1b4a28795781674cc85a3559 Mon Sep 17 00:00:00 2001 From: Felipe Fumero Date: Wed, 4 Nov 2026 14:32:33 -0600 Subject: [PATCH 012/113] fix(deps): bump urllib3 to 2.8.0 --- changelog.d/638.infrastructure.md | 1 + uv.lock | 6 +++--- 2 files changed, 4 insertions(+), 3 deletions(-) create mode 100644 changelog.d/638.infrastructure.md diff --git a/changelog.d/638.infrastructure.md b/changelog.d/638.infrastructure.md new file mode 100644 index 000000000..f9fa7867a --- /dev/null +++ b/changelog.d/638.infrastructure.md @@ -0,0 +1 @@ +Updated the locked urllib3 dependency to version 2.8.0. diff --git a/uv.lock b/uv.lock index 5bc9480d6..bd089e0c4 100644 --- a/uv.lock +++ b/uv.lock @@ -1708,11 +1708,11 @@ wheels = [ [[package]] name = "urllib3" -version = "2.7.0" +version = "2.8.0" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/53/0c/06f8b233b8fd13b9e5ee11424ef85419ba0d8ba0b3138bf360be2ff56953/urllib3-2.7.0.tar.gz", hash = "sha256:231e0ec3b63ceb14667c67be60f2f2c40a518cb38b03af60abc813da26505f4c", size = 433602, upload-time = "2026-05-07T16:13:18.596Z" } +sdist = { url = "https://files.pythonhosted.org/packages/e3/05/b17359e1cefb4f909b5e40b1b90a496d987258916dbbf88e842c729f510e/urllib3-2.8.0.tar.gz", hash = "sha256:63bf2ead4c879426ebf22ef2a781eeb4aa3b4ae798a0435506f8687fd5bb9b63", size = 458972, upload-time = "2026-09-15T19:29:36.253Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/7f/3e/5db95bcf282c52709639744ca2a8b149baccf648e39c8cc87553df9eae0c/urllib3-2.7.0-py3-none-any.whl", hash = "sha256:9fb4c81ebbb1ce9531cce37674bbc6f1360472bc18ca9a553ede278ef7276897", size = 131087, upload-time = "2026-05-07T16:13:17.151Z" }, + { url = "https://files.pythonhosted.org/packages/92/9d/c4e665119135114480843e7ab388fa94d8480650450e6f8e26b70d323a4c/urllib3-2.8.0-py3-none-any.whl", hash = "sha256:0cf3cae568d36aa9576b28dfb35f11328f1cb974ca7647d9475ebb86c75ac6e3", size = 135717, upload-time = "2026-09-15T19:29:34.577Z" }, ] [[package]] From a7681961594e53cee9605175e997bc30c08cd78d Mon Sep 17 00:00:00 2001 From: Felipe Fumero Date: Wed, 4 Nov 2026 16:25:37 -0600 Subject: [PATCH 013/113] fix(deps): update development tooling --- changelog.d/640.infrastructure.md | 1 + pyproject.toml | 2 +- uv.lock | 226 ++++++++++++++++++++++-------- 3 files changed, 170 insertions(+), 59 deletions(-) create mode 100644 changelog.d/640.infrastructure.md diff --git a/changelog.d/640.infrastructure.md b/changelog.d/640.infrastructure.md new file mode 100644 index 000000000..2af706e84 --- /dev/null +++ b/changelog.d/640.infrastructure.md @@ -0,0 +1 @@ +Updated Starlette, AnyIO, and virtualenv in the development tooling. Setuptools remains below 81 for liccheck compatibility and requires a dev-only dismissal; filelock and tornado retain Python 3.10-compatible dev-only locks. diff --git a/pyproject.toml b/pyproject.toml index c2391380b..9e80c3e3e 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -50,7 +50,7 @@ lint = [ "pytest>=9.0.3,<10", "tenacity>=9.1.4,<10", "liccheck==0.9.2", - "setuptools", + "setuptools<81", # liccheck 0.9.2 imports pkg_resources, removed in setuptools 81 ] test = [ "pip>=26.2.2", diff --git a/uv.lock b/uv.lock index bd089e0c4..46673c7fb 100644 --- a/uv.lock +++ b/uv.lock @@ -27,16 +27,16 @@ wheels = [ [[package]] name = "anyio" -version = "4.12.1" +version = "4.14.2" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "exceptiongroup", marker = "python_full_version < '3.11'" }, { name = "idna" }, { name = "typing-extensions", marker = "python_full_version < '3.13'" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/96/f0/5eb65b2bb0d09ac6776f2eb54adee6abe8228ea05b20a5ad0e4945de8aac/anyio-4.12.1.tar.gz", hash = "sha256:41cfcc3a4c85d3f05c932da7c26d0201ac36f72abd4435ba90d0464a3ffed703", size = 228685, upload-time = "2026-01-06T11:45:21.246Z" } +sdist = { url = "https://files.pythonhosted.org/packages/61/cc/a381afa6efea9f496eff839d4a6a1aed3bfafc7b3ab4b0d1b243a12573dd/anyio-4.14.2.tar.gz", hash = "sha256:cfa139f3ed1a23ee8f88a145ddb5ac7605b8bbfd8592baacd7ce3d8bb4313c7f", size = 260176, upload-time = "2026-07-12T20:29:07.082Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/38/0e/27be9fdef66e72d64c0cdc3cc2823101b80585f8119b5c112c2e8f5f7dab/anyio-4.12.1-py3-none-any.whl", hash = "sha256:d405828884fc140aa80a3c667b8beed277f1dfedec42ba031bd6ac3db606ab6c", size = 113592, upload-time = "2026-01-06T11:45:19.497Z" }, + { url = "https://files.pythonhosted.org/packages/da/35/f2287558c17e29fafc8ef3daf819bb9834061cfa43bff8014f7df7f63bdc/anyio-4.14.2-py3-none-any.whl", hash = "sha256:9f505dda5ac9f0c8309b5e8bd445a8c2bf7246f3ce950121e45ea15bc41d1494", size = 125813, upload-time = "2026-07-12T20:29:05.763Z" }, ] [[package]] @@ -84,7 +84,8 @@ doc = [ { name = "sphinx-autodoc-typehints" }, { name = "sphinx-rtd-theme" }, { name = "sphinxcontrib-plantuml" }, - { name = "tornado" }, + { name = "tornado", version = "6.5.10", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, + { name = "tornado", version = "6.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" }, ] format = [ { name = "ruff" }, @@ -151,7 +152,7 @@ lint = [ { name = "pip", specifier = ">=26.2.2" }, { name = "pytest", specifier = ">=9.0.3,<10" }, { name = "ruff", specifier = "~=0.8.4" }, - { name = "setuptools" }, + { name = "setuptools", specifier = "<81" }, { name = "tenacity", specifier = ">=9.1.4,<10" }, ] nox = [ @@ -450,11 +451,11 @@ wheels = [ [[package]] name = "distlib" -version = "0.4.0" +version = "0.4.4" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/96/8e/709914eb2b5749865801041647dc7f4e6d00b549cfe88b65ca192995f07c/distlib-0.4.0.tar.gz", hash = "sha256:feec40075be03a04501a973d81f633735b4b69f98b05450592310c0f401a4e0d", size = 614605, upload-time = "2025-07-17T16:52:00.465Z" } +sdist = { url = "https://files.pythonhosted.org/packages/68/bc/d36966de7304047a1001a7559fbf266c464bb5d8cc85464536ef8c9bcc32/distlib-0.4.4.tar.gz", hash = "sha256:ca4175b4ac7f71223cc30ed7248c45d2b38c2439d8ee6e498ab67ed63cf3508d", size = 621304, upload-time = "2026-10-16T13:56:34.203Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/33/6b/e0547afaf41bf2c42e52430072fa5658766e3d65bd4b03a563d1b6336f57/distlib-0.4.0-py2.py3-none-any.whl", hash = "sha256:9659f7d87e46584a30b5780e43ac7a2143098441670ff0a49d5f9034c54a6c16", size = 469047, upload-time = "2025-07-17T16:51:58.613Z" }, + { url = "https://files.pythonhosted.org/packages/c1/2b/238f02a4927fa2e27aa995371d240a468b52e42eae44a678434aff736b38/distlib-0.4.4-py2.py3-none-any.whl", hash = "sha256:cf09d55b1e85a89576b036aeb71550bfd68320f3f21761ca329eadadad918638", size = 472099, upload-time = "2026-10-16T13:56:32.053Z" }, ] [[package]] @@ -471,7 +472,7 @@ name = "exceptiongroup" version = "1.3.1" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "typing-extensions", marker = "python_full_version < '3.11'" }, + { name = "typing-extensions" }, ] sdist = { url = "https://files.pythonhosted.org/packages/50/79/66800aadf48771f6b62f7eb014e352e5d06856655206165d775e675a02c9/exceptiongroup-1.3.1.tar.gz", hash = "sha256:8b412432c6055b0b7d14c310000ae93352ed6754f70fa8f7c34141f91c4e3219", size = 30371, upload-time = "2025-11-21T23:01:54.787Z" } wheels = [ @@ -489,11 +490,27 @@ wheels = [ [[package]] name = "filelock" -version = "3.29.0" +version = "4.1.0" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version < '3.11' and platform_python_implementation == 'PyPy'", + "python_full_version < '3.11' and platform_python_implementation != 'PyPy'", +] +sdist = { url = "https://files.pythonhosted.org/packages/4c/58/6fd434bec86eff7c38a3168454cb132b762b2bea9b3ac094101a2f7bc32a/filelock-4.1.0.tar.gz", hash = "sha256:ad7f724afef953e731b1cc39bcd3a09166d72ed7fcdf29e6e88b1c3235c6715d", size = 561277, upload-time = "2026-10-09T19:57:20.34Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/ee/86/032133892a5de43b5a98200b01aadcad68cc255e274a762f08b8a76d2912/filelock-4.1.0-py3-none-any.whl", hash = "sha256:2ce9818e3e2d8f284c1a964414447ef148d42a5fd5e2a477a7118e574b293ec1", size = 133003, upload-time = "2026-10-09T19:57:18.716Z" }, +] + +[[package]] +name = "filelock" +version = "4.2.9" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/b5/fe/997687a931ab51049acce6fa1f23e8f01216374ea81374ddee763c493db5/filelock-3.29.0.tar.gz", hash = "sha256:69974355e960702e789734cb4871f884ea6fe50bd8404051a3530bc07809cf90", size = 57571, upload-time = "2026-04-19T15:39:10.068Z" } +resolution-markers = [ + "python_full_version >= '3.11'", +] +sdist = { url = "https://files.pythonhosted.org/packages/a3/1d/d730c664fcb4f1d264a722722a3134cf0881854f73c1fd58abf87572f232/filelock-4.2.9.tar.gz", hash = "sha256:96530b7c538d4ea08493ab067247aab7948c54d8cd622cce711c97cccc5d9896", size = 663116, upload-time = "2026-11-04T18:37:10.014Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/81/47/dd9a212ef6e343a6857485ffe25bba537304f1913bdbed446a23f7f592e1/filelock-3.29.0-py3-none-any.whl", hash = "sha256:96f5f6344709aa1572bbf631c640e4ebeeb519e08da902c39a001882f30ac258", size = 39812, upload-time = "2026-04-19T15:39:08.752Z" }, + { url = "https://files.pythonhosted.org/packages/00/05/76184fe08339723d643ab47887a8e4de8f2921ca4e008617ab7490af7857/filelock-4.2.9-py3-none-any.whl", hash = "sha256:a379c50a729e5b68c8519a4d26489f755d9769960a236ecd838190e2a78db2e9", size = 164734, upload-time = "2026-11-04T18:37:08.273Z" }, ] [[package]] @@ -743,11 +760,11 @@ wheels = [ [[package]] name = "packaging" -version = "25.0" +version = "26.3" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/a1/d4/1fc4078c65507b51b96ca8f8c3ba19e6a61c8253c72794544580a7b6c24d/packaging-25.0.tar.gz", hash = "sha256:d443872c98d677bf60f6a1f2f8c1cb748e8fe762d2bf9d3148b5599295b0fc4f", size = 165727, upload-time = "2025-04-19T11:48:59.673Z" } +sdist = { url = "https://files.pythonhosted.org/packages/7d/fa/3944b40b07da9ce895c0e6303a5ab7d53da063554f534556b134a54d6093/packaging-26.3.tar.gz", hash = "sha256:94edc256424af38762eb31306eed28beb9f0efc50a8837492c9d6fd6004aed79", size = 313412, upload-time = "2026-08-04T18:15:28.737Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/20/12/38679034af332785aac8774540895e234f4d07f7545804097de4b666afd8/packaging-25.0-py3-none-any.whl", hash = "sha256:29572ef2b1f17581046b3a2227d5c611fb25ec70ca1ba8554b24b0e69331a484", size = 66469, upload-time = "2025-04-19T11:48:57.875Z" }, + { url = "https://files.pythonhosted.org/packages/63/34/ba1c580383c9eada3711951fef0795c80b829a078d72188184bcab9dd527/packaging-26.3-py3-none-any.whl", hash = "sha256:d7193f7c8e4e93f444fde0262bf90af30e16fa0ad0ad44cb553c87339b23cd1c", size = 129956, upload-time = "2026-08-04T18:15:27.159Z" }, ] [[package]] @@ -785,10 +802,10 @@ resolution-markers = [ "python_full_version < '3.11' and platform_python_implementation == 'PyPy'", ] dependencies = [ - { name = "annotated-types", marker = "python_full_version < '3.11' and platform_python_implementation == 'PyPy'" }, - { name = "pydantic-core", version = "2.41.5", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11' and platform_python_implementation == 'PyPy'" }, - { name = "typing-extensions", marker = "python_full_version < '3.11' and platform_python_implementation == 'PyPy'" }, - { name = "typing-inspection", marker = "python_full_version < '3.11' and platform_python_implementation == 'PyPy'" }, + { name = "annotated-types" }, + { name = "pydantic-core", version = "2.41.5", source = { registry = "https://pypi.org/simple" } }, + { name = "typing-extensions" }, + { name = "typing-inspection" }, ] sdist = { url = "https://files.pythonhosted.org/packages/69/44/36f1a6e523abc58ae5f928898e4aca2e0ea509b5aa6f6f392a5d882be928/pydantic-2.12.5.tar.gz", hash = "sha256:4d351024c75c0f085a9febbb665ce8c0c6ec5d30e903bdb6394b7ede26aebb49", size = 821591, upload-time = "2025-11-26T15:11:46.471Z" } wheels = [ @@ -804,10 +821,10 @@ resolution-markers = [ "python_full_version < '3.11' and platform_python_implementation != 'PyPy'", ] dependencies = [ - { name = "annotated-types", marker = "python_full_version >= '3.11' or platform_python_implementation != 'PyPy'" }, - { name = "pydantic-core", version = "2.46.3", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11' or platform_python_implementation != 'PyPy'" }, - { name = "typing-extensions", marker = "python_full_version >= '3.11' or platform_python_implementation != 'PyPy'" }, - { name = "typing-inspection", marker = "python_full_version >= '3.11' or platform_python_implementation != 'PyPy'" }, + { name = "annotated-types" }, + { name = "pydantic-core", version = "2.46.3", source = { registry = "https://pypi.org/simple" } }, + { name = "typing-extensions" }, + { name = "typing-inspection" }, ] sdist = { url = "https://files.pythonhosted.org/packages/d9/e4/40d09941a2cebcb20609b86a559817d5b9291c49dd6f8c87e5feffbe703a/pydantic-2.13.3.tar.gz", hash = "sha256:af09e9d1d09f4e7fe37145c1f577e1d61ceb9a41924bf0094a36506285d0a84d", size = 844068, upload-time = "2026-04-20T14:46:43.632Z" } wheels = [ @@ -822,7 +839,7 @@ resolution-markers = [ "python_full_version < '3.11' and platform_python_implementation == 'PyPy'", ] dependencies = [ - { name = "typing-extensions", marker = "python_full_version < '3.11' and platform_python_implementation == 'PyPy'" }, + { name = "typing-extensions" }, ] sdist = { url = "https://files.pythonhosted.org/packages/71/70/23b021c950c2addd24ec408e9ab05d59b035b39d97cdc1130e1bce647bb6/pydantic_core-2.41.5.tar.gz", hash = "sha256:08daa51ea16ad373ffd5e7606252cc32f07bc72b28284b6bc9c6df804816476e", size = 460952, upload-time = "2025-11-04T13:43:49.098Z" } wheels = [ @@ -944,7 +961,7 @@ resolution-markers = [ "python_full_version < '3.11' and platform_python_implementation != 'PyPy'", ] dependencies = [ - { name = "typing-extensions", marker = "python_full_version >= '3.11' or platform_python_implementation != 'PyPy'" }, + { name = "typing-extensions" }, ] sdist = { url = "https://files.pythonhosted.org/packages/2a/ef/f7abb56c49382a246fd2ce9c799691e3c3e7175ec74b14d99e798bcddb1a/pydantic_core-2.46.3.tar.gz", hash = "sha256:41c178f65b8c29807239d47e6050262eb6bf84eb695e41101e62e38df4a5bc2c", size = 471412, upload-time = "2026-04-20T14:40:56.672Z" } wheels = [ @@ -1158,6 +1175,19 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/ca/31/d4e37e9e550c2b92a9cbc2e4d0b7420a27224968580b5a447f420847c975/pytest_xdist-3.8.0-py3-none-any.whl", hash = "sha256:202ca578cfeb7370784a8c33d6d05bc6e13b4f25b5053c30a152269fd10f0b88", size = 46396, upload-time = "2025-07-01T13:30:56.632Z" }, ] +[[package]] +name = "python-discovery" +version = "1.9.4" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "filelock", version = "4.1.0", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, + { name = "filelock", version = "4.2.9", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/0f/d7/1e94df7d1636bf00b9f261bf88a4adc0414f14931ff60511eb0f34c250d1/python_discovery-1.9.4.tar.gz", hash = "sha256:c01b45fe515c1d268b57c57d554bb0e1d320b8e9eb5490bb2f4f577be26e4380", size = 140385, upload-time = "2026-11-04T05:25:52.097Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/c5/44/b248f3b1a23f44d8de172e2767748082c41cbd9353009af72f4b11b00afa/python_discovery-1.9.4-py3-none-any.whl", hash = "sha256:b468f365040b40f4cb39918b0766d3e5a2f340968e07df752fbc96f1bb4641ab", size = 44220, upload-time = "2026-11-04T05:25:50.514Z" }, +] + [[package]] name = "pywin32" version = "311" @@ -1374,12 +1404,12 @@ resolution-markers = [ "python_full_version < '3.11' and platform_python_implementation != 'PyPy'", ] dependencies = [ - { name = "colorama", marker = "python_full_version < '3.11'" }, - { name = "sphinx", marker = "python_full_version < '3.11'" }, - { name = "starlette", marker = "python_full_version < '3.11'" }, - { name = "uvicorn", marker = "python_full_version < '3.11'" }, - { name = "watchfiles", marker = "python_full_version < '3.11'" }, - { name = "websockets", marker = "python_full_version < '3.11'" }, + { name = "colorama" }, + { name = "sphinx" }, + { name = "starlette", version = "1.7.0", source = { registry = "https://pypi.org/simple" } }, + { name = "uvicorn" }, + { name = "watchfiles" }, + { name = "websockets" }, ] sdist = { url = "https://files.pythonhosted.org/packages/a5/2c/155e1de2c1ba96a72e5dba152c509a8b41e047ee5c2def9e9f0d812f8be7/sphinx_autobuild-2024.10.3.tar.gz", hash = "sha256:248150f8f333e825107b6d4b86113ab28fa51750e5f9ae63b59dc339be951fb1", size = 14023, upload-time = "2024-10-02T23:15:30.172Z" } wheels = [ @@ -1394,12 +1424,12 @@ resolution-markers = [ "python_full_version >= '3.11'", ] dependencies = [ - { name = "colorama", marker = "python_full_version >= '3.11'" }, - { name = "sphinx", marker = "python_full_version >= '3.11'" }, - { name = "starlette", marker = "python_full_version >= '3.11'" }, - { name = "uvicorn", marker = "python_full_version >= '3.11'" }, - { name = "watchfiles", marker = "python_full_version >= '3.11'" }, - { name = "websockets", marker = "python_full_version >= '3.11'" }, + { name = "colorama" }, + { name = "sphinx" }, + { name = "starlette", version = "1.10.0", source = { registry = "https://pypi.org/simple" } }, + { name = "uvicorn" }, + { name = "watchfiles" }, + { name = "websockets" }, ] sdist = { url = "https://files.pythonhosted.org/packages/e0/3c/a59a3a453d4133777f7ed2e83c80b7dc817d43c74b74298ca0af869662ad/sphinx_autobuild-2025.8.25.tar.gz", hash = "sha256:9cf5aab32853c8c31af572e4fecdc09c997e2b8be5a07daf2a389e270e85b213", size = 15200, upload-time = "2025-08-25T18:44:55.436Z" } wheels = [ @@ -1558,15 +1588,35 @@ wheels = [ [[package]] name = "starlette" -version = "0.51.0" +version = "1.7.0" source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version < '3.11' and platform_python_implementation == 'PyPy'", + "python_full_version < '3.11' and platform_python_implementation != 'PyPy'", +] +dependencies = [ + { name = "anyio" }, + { name = "typing-extensions" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/7b/2b/3850dc6bf7ef71b088962eba31dafc6cffd2f96e577ebb0bb316df96da3e/starlette-1.7.0.tar.gz", hash = "sha256:c79f74ea63cff761804fbbfb182f1e0b440c2d07b164d24700c5a1bab5d6ff5d", size = 2736246, upload-time = "2026-09-23T07:30:26.35Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/4e/d6/1ec1b290f9e0fb067899b61e1d37a30c923068bad260b216dbe37a7d2967/starlette-1.7.0-py3-none-any.whl", hash = "sha256:67f8e99895493dd2911a03f11314af6ceebeae4e704bb9f43dfc6a9db151c93e", size = 78980, upload-time = "2026-09-23T07:30:24.567Z" }, +] + +[[package]] +name = "starlette" +version = "1.10.0" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version >= '3.11'", +] dependencies = [ { name = "anyio" }, { name = "typing-extensions", marker = "python_full_version < '3.13'" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/e7/65/5a1fadcc40c5fdc7df421a7506b79633af8f5d5e3a95c3e72acacec644b9/starlette-0.51.0.tar.gz", hash = "sha256:4c4fda9b1bc67f84037d3d14a5112e523509c369d9d47b111b2f984b0cc5ba6c", size = 2647658, upload-time = "2026-01-10T20:23:15.043Z" } +sdist = { url = "https://files.pythonhosted.org/packages/48/bb/3d8757f21e9a53d9035c9eb039a777047139a16bfdbedfc7a58241c3d914/starlette-1.10.0.tar.gz", hash = "sha256:b8399098d4c1e3522734f7235dc79b1fc967f96cf139c81e0fa30479e0685f9b", size = 2734356, upload-time = "2026-10-24T15:04:12.342Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/18/c4/09985a03dba389d4fe16a9014147a7b02fa76ef3519bf5846462a485876d/starlette-0.51.0-py3-none-any.whl", hash = "sha256:fb460a3d6fd3c958d729fdd96aee297f89a51b0181f16401fe8fd4cb6129165d", size = 74133, upload-time = "2026-01-10T20:23:13.445Z" }, + { url = "https://files.pythonhosted.org/packages/88/2e/947cfe02def9371c07cd5bf5b6b61c829e9aecb9904db02a66cfafbc1eec/starlette-1.10.0-py3-none-any.whl", hash = "sha256:478c0ab3b4ced6e82719849c118fa406f0278a3499c1a898cd15cd31bdc38ce4", size = 80571, upload-time = "2026-10-24T15:04:10.371Z" }, ] [[package]] @@ -1643,19 +1693,76 @@ wheels = [ [[package]] name = "tornado" -version = "6.5.5" +version = "6.5.10" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/f8/f1/3173dfa4a18db4a9b03e5d55325559dab51ee653763bb8745a75af491286/tornado-6.5.5.tar.gz", hash = "sha256:192b8f3ea91bd7f1f50c06955416ed76c6b72f96779b962f07f911b91e8d30e9", size = 516006, upload-time = "2026-03-10T21:31:02.067Z" } +resolution-markers = [ + "python_full_version < '3.11' and platform_python_implementation == 'PyPy'", + "python_full_version < '3.11' and platform_python_implementation != 'PyPy'", +] +sdist = { url = "https://files.pythonhosted.org/packages/06/61/53d562a57b28c08eda40b258c0f975e360541943ad7c7bef897a40caafda/tornado-6.5.10.tar.gz", hash = "sha256:a6b1ccd08c04b4a06fb5aeb381be99de5ad1e5375c1785e31d78c880feb57687", size = 537910, upload-time = "2026-09-15T13:47:48.73Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/59/8c/77f5097695f4dd8255ecbd08b2a1ed8ba8b953d337804dd7080f199e12bf/tornado-6.5.5-cp39-abi3-macosx_10_9_universal2.whl", hash = "sha256:487dc9cc380e29f58c7ab88f9e27cdeef04b2140862e5076a66fb6bb68bb1bfa", size = 445983, upload-time = "2026-03-10T21:30:44.28Z" }, - { url = "https://files.pythonhosted.org/packages/ab/5e/7625b76cd10f98f1516c36ce0346de62061156352353ef2da44e5c21523c/tornado-6.5.5-cp39-abi3-macosx_10_9_x86_64.whl", hash = "sha256:65a7f1d46d4bb41df1ac99f5fcb685fb25c7e61613742d5108b010975a9a6521", size = 444246, upload-time = "2026-03-10T21:30:46.571Z" }, - { url = "https://files.pythonhosted.org/packages/b2/04/7b5705d5b3c0fab088f434f9c83edac1573830ca49ccf29fb83bf7178eec/tornado-6.5.5-cp39-abi3-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:e74c92e8e65086b338fd56333fb9a68b9f6f2fe7ad532645a290a464bcf46be5", size = 447229, upload-time = "2026-03-10T21:30:48.273Z" }, - { url = "https://files.pythonhosted.org/packages/34/01/74e034a30ef59afb4097ef8659515e96a39d910b712a89af76f5e4e1f93c/tornado-6.5.5-cp39-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:435319e9e340276428bbdb4e7fa732c2d399386d1de5686cb331ec8eee754f07", size = 448192, upload-time = "2026-03-10T21:30:51.22Z" }, - { url = "https://files.pythonhosted.org/packages/be/00/fe9e02c5a96429fce1a1d15a517f5d8444f9c412e0bb9eadfbe3b0fc55bf/tornado-6.5.5-cp39-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:3f54aa540bdbfee7b9eb268ead60e7d199de5021facd276819c193c0fb28ea4e", size = 448039, upload-time = "2026-03-10T21:30:53.52Z" }, - { url = "https://files.pythonhosted.org/packages/82/9e/656ee4cec0398b1d18d0f1eb6372c41c6b889722641d84948351ae19556d/tornado-6.5.5-cp39-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:36abed1754faeb80fbd6e64db2758091e1320f6bba74a4cf8c09cd18ccce8aca", size = 447445, upload-time = "2026-03-10T21:30:55.541Z" }, - { url = "https://files.pythonhosted.org/packages/5a/76/4921c00511f88af86a33de770d64141170f1cfd9c00311aea689949e274e/tornado-6.5.5-cp39-abi3-win32.whl", hash = "sha256:dd3eafaaeec1c7f2f8fdcd5f964e8907ad788fe8a5a32c4426fbbdda621223b7", size = 448582, upload-time = "2026-03-10T21:30:57.142Z" }, - { url = "https://files.pythonhosted.org/packages/2c/23/f6c6112a04d28eed765e374435fb1a9198f73e1ec4b4024184f21faeb1ad/tornado-6.5.5-cp39-abi3-win_amd64.whl", hash = "sha256:6443a794ba961a9f619b1ae926a2e900ac20c34483eea67be4ed8f1e58d3ef7b", size = 448990, upload-time = "2026-03-10T21:30:58.857Z" }, - { url = "https://files.pythonhosted.org/packages/b7/c8/876602cbc96469911f0939f703453c1157b0c826ecb05bdd32e023397d4e/tornado-6.5.5-cp39-abi3-win_arm64.whl", hash = "sha256:2c9a876e094109333f888539ddb2de4361743e5d21eece20688e3e351e4990a6", size = 448016, upload-time = "2026-03-10T21:31:00.43Z" }, + { url = "https://files.pythonhosted.org/packages/cd/5b/ff5fc58fa2427c30dea74c90053f4fc5eda1e7f3833ed3ecc7147fe2b311/tornado-6.5.10-cp39-abi3-macosx_10_9_universal2.whl", hash = "sha256:9261783640e23258694a9ff0795df430a5a7b0a651d3dd53dd0969ad6be16da7", size = 465883, upload-time = "2026-09-15T13:47:35.463Z" }, + { url = "https://files.pythonhosted.org/packages/ad/f5/cd7be26c34a3315532f3aef5f092465da8f59c334dd439d3c14aaef16461/tornado-6.5.10-cp39-abi3-macosx_10_9_x86_64.whl", hash = "sha256:83e6cf438b106c6b3852d70960967bb1b70c87438050dca0981e4b9aa751a4c1", size = 464046, upload-time = "2026-09-15T13:47:37.178Z" }, + { url = "https://files.pythonhosted.org/packages/60/33/df6d7d04854a58619f8349a51e3edb138324130a7562b0bb21f115bb940f/tornado-6.5.10-cp39-abi3-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:bdf942448169e5336451d0494d7e3d81cfa726d5aa312affdc4682dd62a62f6d", size = 467096, upload-time = "2026-09-15T13:47:38.559Z" }, + { url = "https://files.pythonhosted.org/packages/29/17/cc35dff68272d685cffd8600ffafbd8067e7d05e7348d9f80caddffbbd5f/tornado-6.5.10-cp39-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:69acca6501eed74582b76dbbceee2a91613f54728e3e418346000d7103101676", size = 468067, upload-time = "2026-09-15T13:47:40.085Z" }, + { url = "https://files.pythonhosted.org/packages/c3/01/6e5349b4e1a53a4b4972a6716785e1fe7407f312063c3972690af8ff301b/tornado-6.5.10-cp39-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:66aaa3f57d30c6e6becee83ff28055d5930ac724214bde99393eefda83d5e015", size = 467901, upload-time = "2026-09-15T13:47:41.576Z" }, + { url = "https://files.pythonhosted.org/packages/28/5e/b4facf94370dba006819c8d304376f8b9fbec6b935b5e51bf45823a9790b/tornado-6.5.10-cp39-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:4bd192b959f9128fb99b8898148070ba4574c9589b78bce42d1851131fe85828", size = 467308, upload-time = "2026-09-15T13:47:43.145Z" }, + { url = "https://files.pythonhosted.org/packages/56/ae/047938e828cafc8eca4c908fafb6588fee944e3af39a0af9d7b602499ae5/tornado-6.5.10-cp39-abi3-win32.whl", hash = "sha256:302eb1e0e3e159314eb591920529fdea80acca92df5510a2cec5bbd4f099ec72", size = 468387, upload-time = "2026-09-15T13:47:44.556Z" }, + { url = "https://files.pythonhosted.org/packages/d8/d4/5901517f05affd752490f6a654ba31b7474664e8dd80bd045a00c220bd88/tornado-6.5.10-cp39-abi3-win_amd64.whl", hash = "sha256:37ae8f150cecfdbf747fc4e12f5e9a97ecd8cf1d4cdb3f119e2de84b11196918", size = 468828, upload-time = "2026-09-15T13:47:45.961Z" }, + { url = "https://files.pythonhosted.org/packages/f3/1a/fd497f3a7f7b74bb04f4b94536b5c9f80742b5d50501fd27977652ddec16/tornado-6.5.10-cp39-abi3-win_arm64.whl", hash = "sha256:ce045d3c298fddd30e89a2777f97039d1b641eb9518ac7b26a4721903539c694", size = 467847, upload-time = "2026-09-15T13:47:47.283Z" }, +] + +[[package]] +name = "tornado" +version = "6.6" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version >= '3.11'", +] +sdist = { url = "https://files.pythonhosted.org/packages/d0/02/5f549b1ad5da6267ed1e1fac2eef69257b1979cc812497002499b7895ff9/tornado-6.6.tar.gz", hash = "sha256:34c4aa916d7f2b2d5cadee2c6850f5a4a7f3d688cbf58399ea9bd3057af4abd5", size = 617998, upload-time = "2026-10-21T15:31:04.733Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/df/f5/d3e6f76b945f9812842db742d0708a3b6287e850e81be3ca10e290c103c6/tornado-6.6-cp311-abi3-macosx_10_9_universal2.whl", hash = "sha256:01abf15429d64f04ccfafc238b191cc2c177108b7a331f4461707ad77198c8c2", size = 528326, upload-time = "2026-10-21T15:30:05.528Z" }, + { url = "https://files.pythonhosted.org/packages/30/69/b20cf3a8bf641ec792a5a6050aa153e8f120604f9c23471142de535113e5/tornado-6.6-cp311-abi3-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:11bb97c00981eb8254e55bd6a5ad960c983ae343fef8ae3ae5584cd1fb70236a", size = 529544, upload-time = "2026-10-21T15:30:07.126Z" }, + { url = "https://files.pythonhosted.org/packages/0f/f4/d9d8d3ac345aa9df3a132ad03bd443160c2ab24ad4003b4e8d6d5af06371/tornado-6.6-cp311-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:4e152a3b2d3eae113b836d979823f7bb2320f7e334a84449729964921f374a4c", size = 530523, upload-time = "2026-10-21T15:30:08.478Z" }, + { url = "https://files.pythonhosted.org/packages/ad/82/1296ade1c14dee5a4906e5ca092997622ece7c4dc768c68ed9caaf895d1b/tornado-6.6-cp311-abi3-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:e912d4c4babd04db6f34b25b748174a4a176debe86c8610beedf1815f9af7fdd", size = 530739, upload-time = "2026-10-21T15:30:09.98Z" }, + { url = "https://files.pythonhosted.org/packages/66/30/6ac1eab66c81af46dafd93c9b24bd311f82e199d9d7b8ce2a64a91b6a200/tornado-6.6-cp311-abi3-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:33aabe8a03d426cef4e0fe5669f0643cadd983b54957f1a7ac2789ec326e9644", size = 529738, upload-time = "2026-10-21T15:30:11.498Z" }, + { url = "https://files.pythonhosted.org/packages/24/b4/6c1f6aa1fd148e4d0f500a10cd0c9949e7bf385e161ff497c81de5b3ae4f/tornado-6.6-cp311-abi3-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:9aaf0e1c2fb9f046f30e2036b8d2060666399e8464d0a72769e43c754089567b", size = 527908, upload-time = "2026-10-21T15:30:13.298Z" }, + { url = "https://files.pythonhosted.org/packages/54/5b/67d3d452b1179bc9e265cebd381a56ab4cf2d7b2a54607aedd8d6e1ebc2e/tornado-6.6-cp311-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:61fc5513cea97720ab9bf54b04827ac0f4500c63f0b072b963d6145c798b4661", size = 530367, upload-time = "2026-10-21T15:30:15.183Z" }, + { url = "https://files.pythonhosted.org/packages/74/14/4e8e9a14f77bcafb2408634b2d4c8c676ad7a43bf8dac4ee2d48370698f9/tornado-6.6-cp311-abi3-musllinux_1_2_ppc64le.whl", hash = "sha256:31e1a0d5cd704d2fe8a008c1cc27a0e2b67269ca263630a27985dddc160b5537", size = 530456, upload-time = "2026-10-21T15:30:16.741Z" }, + { url = "https://files.pythonhosted.org/packages/56/12/e3ddef99a2089ccfc86f32bd3f39caaad87bee4868be1bacbf213a0b07a2/tornado-6.6-cp311-abi3-musllinux_1_2_riscv64.whl", hash = "sha256:74416e41e9bdf70fbc2fb242f6fbbc7a58ec11e59d39f15fc5a421ecb6845118", size = 529610, upload-time = "2026-10-21T15:30:18.031Z" }, + { url = "https://files.pythonhosted.org/packages/35/3d/62a692343d46b37e852e5078e0f6513534d925f70a04580072e3c127b129/tornado-6.6-cp311-abi3-musllinux_1_2_s390x.whl", hash = "sha256:8cdd69104ae9d705b3f04d2563aa96e357043e267a455802daae9a1e633a37c8", size = 529803, upload-time = "2026-10-21T15:30:19.326Z" }, + { url = "https://files.pythonhosted.org/packages/49/04/6c59a9413adfe4810f648a4dd9fdf476f13b0495f9cc25ef856b71f9ce1e/tornado-6.6-cp311-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:fc7c8a3263501fbe97518cd699101bc3c5f499a7dd4f75fc6cbb3bd9ee1db1f1", size = 529751, upload-time = "2026-10-21T15:30:20.826Z" }, + { url = "https://files.pythonhosted.org/packages/31/36/a1b3b84cd347ae43f982d3bf95628de6c6365668dba2543af47c6a1c888e/tornado-6.6-cp311-abi3-win32.whl", hash = "sha256:b54ca69ff93d0374efb083a12a1e9ec2dd2036e8496d197e0e8ef77b8d9135c3", size = 530643, upload-time = "2026-10-21T15:30:22.428Z" }, + { url = "https://files.pythonhosted.org/packages/b7/50/dc813fe35a672e14ee8bed8b5c634eeb343a05c98eb455318a169de24567/tornado-6.6-cp311-abi3-win_amd64.whl", hash = "sha256:48f26ed9d7beb64e5f06adc864524e581ab6d62ba8ff46eaaa1ac2d0e6d753fd", size = 530886, upload-time = "2026-10-21T15:30:23.975Z" }, + { url = "https://files.pythonhosted.org/packages/0d/71/62a9b9e980026d38874740d0a7c162f53eb0563f6a441e3aff84c48db7e8/tornado-6.6-cp311-abi3-win_arm64.whl", hash = "sha256:29114ffd4e4de869d390393df9e9a0f191065aae1a96f38a58d35e464c04a867", size = 530899, upload-time = "2026-10-21T15:30:25.264Z" }, + { url = "https://files.pythonhosted.org/packages/ac/4c/633e3568eb574df555d6ddd2dac44b7793a5c26cd63b444e653fcfb1d6ec/tornado-6.6-cp314-cp314t-macosx_10_15_universal2.whl", hash = "sha256:63fc8d243b52fd8dd9ed4ad02d0df08f2024f9aea632a433a8a6c91075076d44", size = 528432, upload-time = "2026-10-21T15:30:26.578Z" }, + { url = "https://files.pythonhosted.org/packages/37/eb/b525d1870ad28a56f47b664dd8fd3fab4f7ddd237c87c14e97248bf4762f/tornado-6.6-cp314-cp314t-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:8d4b85cac795bfc6a7f20ba81871abb8c2ae8fba019061b8a9ae1c2f97e29637", size = 532586, upload-time = "2026-10-21T15:30:28.027Z" }, + { url = "https://files.pythonhosted.org/packages/b7/35/909a33c253352346ca081a27ca66b45c1398468adf784b767597ca773c28/tornado-6.6-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:e035c065edadfa696529d05eebcbeb25154c129b5aee6dbfb697a6abf5d4f697", size = 533641, upload-time = "2026-10-21T15:30:29.318Z" }, + { url = "https://files.pythonhosted.org/packages/6f/64/100202666d6e3d96288ab184827762415456c139798a15c962547f9fabf9/tornado-6.6-cp314-cp314t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:5b94e589ab855090c448b5c0937b3a75f1c1a604b7b36207e8236d209f720b9c", size = 533869, upload-time = "2026-10-21T15:30:30.882Z" }, + { url = "https://files.pythonhosted.org/packages/b1/e0/af3ed62bc15830d60328d5b4a1a9076b35ea0ba142cb17b1c1772cb15c59/tornado-6.6-cp314-cp314t-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:1a394c8c9db9137f2a2b42869d9f7b91398fcf19da120d0dde4c4546172710f7", size = 532767, upload-time = "2026-10-21T15:30:32.273Z" }, + { url = "https://files.pythonhosted.org/packages/24/d7/1e2e1a6932eb62d63324b64dba2f62e6eaf79ad883dd209352c297b7848c/tornado-6.6-cp314-cp314t-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:0215d1df6e4b5e736ddad5adf0af4138cf7437fdd39c77c5e69768e37850a632", size = 530956, upload-time = "2026-10-21T15:30:33.746Z" }, + { url = "https://files.pythonhosted.org/packages/70/65/3b9a0e53d7a4c39f2ebe95486540fa8eeb67bfb6e8c437d603c00d35b128/tornado-6.6-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:4d711790e0a9576ad924d942c4607e4e401d697588ea6f30f6662824008a7add", size = 533372, upload-time = "2026-10-21T15:30:35.085Z" }, + { url = "https://files.pythonhosted.org/packages/44/48/90979cbfaa3ff941324a2605eb794af0f087c670cd99f18a69ab40498073/tornado-6.6-cp314-cp314t-musllinux_1_2_ppc64le.whl", hash = "sha256:034a66bae0f55421d007803e2385d2a59707d8829b2f026373d42f08256e9922", size = 533425, upload-time = "2026-10-21T15:30:36.425Z" }, + { url = "https://files.pythonhosted.org/packages/bb/c4/ce743a86d91f85c255b77a4282eb5b2716b61e74430eb9d1df8578a539d2/tornado-6.6-cp314-cp314t-musllinux_1_2_riscv64.whl", hash = "sha256:5cb38483b077129056a94dd415a71d29ab4e42b46da894fee8b4657003f10b21", size = 532545, upload-time = "2026-10-21T15:30:37.789Z" }, + { url = "https://files.pythonhosted.org/packages/02/5e/a82131e35778540fc19139229d02aa8cf2453a8022e202be50c88f0f8ac3/tornado-6.6-cp314-cp314t-musllinux_1_2_s390x.whl", hash = "sha256:46bbbd107efa37777ac4b83601866d19b4dbd5b770a7a9123582633d95959ad3", size = 532700, upload-time = "2026-10-21T15:30:39.336Z" }, + { url = "https://files.pythonhosted.org/packages/3a/09/6dac8c2c677c65d60b3d7dae94176dbfe392f314e7c8e2d709623edd6a26/tornado-6.6-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:b85e9d0263cdbc027b95947c8b873a7bc7fd6a08d16bfb4f5047350b0808e464", size = 532712, upload-time = "2026-10-21T15:30:40.698Z" }, + { url = "https://files.pythonhosted.org/packages/b2/ac/71e5776cbcdc3264e81aa6db28c69717ba50607a9eb8d5b766f11a4b020e/tornado-6.6-cp314-cp314t-win32.whl", hash = "sha256:4276eef0880e5fe4488e6799c2842f59af3b06637e9313ab4fb506f9c9c2d6cb", size = 530491, upload-time = "2026-10-21T15:30:42.115Z" }, + { url = "https://files.pythonhosted.org/packages/d8/0f/0b6a6908a5b5aa8320009dfdb84434b1cf160b577a00456e59ab9e6ea598/tornado-6.6-cp314-cp314t-win_amd64.whl", hash = "sha256:10d4af98c6df09f8429b1340ccaea3a72887b86f695dfb8056bda517c8115a00", size = 530780, upload-time = "2026-10-21T15:30:43.414Z" }, + { url = "https://files.pythonhosted.org/packages/3c/39/c152e1cc5371f75f5f9f0a4f44bf2dc9396be9407d384de7428446fb4651/tornado-6.6-cp314-cp314t-win_arm64.whl", hash = "sha256:b1f0ef20a5278854f5fdac31637bafadb055405df28b7fc945e54add12b172e3", size = 530781, upload-time = "2026-10-21T15:30:44.741Z" }, + { url = "https://files.pythonhosted.org/packages/0c/c5/f96c7d7a8895745bb37dfb6e6107e1ee40ad02a4b162d7d6c143644455ab/tornado-6.6-cp315-cp315t-macosx_10_15_universal2.whl", hash = "sha256:8f8e382da30fe042f27f27a871e21aefc2613870e5a41648de18446c72d6ea59", size = 528446, upload-time = "2026-10-21T15:30:46.112Z" }, + { url = "https://files.pythonhosted.org/packages/c0/dd/ab8f6500d274b9c55b025798eb54e92591bcff27515799bec443bd54e35a/tornado-6.6-cp315-cp315t-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:8c7a8a328396c2195454a2ecd9499512441bbce99505544a717e6a87d16ff6f9", size = 532774, upload-time = "2026-10-21T15:30:47.393Z" }, + { url = "https://files.pythonhosted.org/packages/87/23/b78e7d1bf329160b8157284005395421ea941864c16c7f04c3e48c98bcf9/tornado-6.6-cp315-cp315t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:ca025bb0da81c294aef26f27427316df1525220820315f4bf32dc1e84a4d2232", size = 533872, upload-time = "2026-10-21T15:30:48.884Z" }, + { url = "https://files.pythonhosted.org/packages/e0/4f/ab66b614ad0bc9a219484be6bc2c002c8de9916a7b6c7b27fe6273838e5c/tornado-6.6-cp315-cp315t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:59c22ebc905ac2a267f8d9d8a878f86afbcbbde329d75c485f1422fc45a81b83", size = 534027, upload-time = "2026-10-21T15:30:50.157Z" }, + { url = "https://files.pythonhosted.org/packages/da/63/501fa15a36bace2f4b9158228cf922d606403261bf71c960c433ec3ca0a4/tornado-6.6-cp315-cp315t-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:f89802bc0bcd15f988d9325b4e6d2171bb04ea68d188732556335e10d3fd00bd", size = 532936, upload-time = "2026-10-21T15:30:51.45Z" }, + { url = "https://files.pythonhosted.org/packages/7f/b7/82d643f635f0300bda98613ca2660b4f3134b6fb594c6fddfa4de706806c/tornado-6.6-cp315-cp315t-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:70043256d5958f9c655066153d23d60ea3e29bf9854f7fb75850e223c477758a", size = 531254, upload-time = "2026-10-21T15:30:52.865Z" }, + { url = "https://files.pythonhosted.org/packages/d4/53/92c40891a94750bc09257310af964bf25c59e3531d6199736c318baa864f/tornado-6.6-cp315-cp315t-musllinux_1_2_aarch64.whl", hash = "sha256:82b49495e3849d644b841ef33b35491160055997deaa93720ff647ef019421db", size = 533566, upload-time = "2026-10-21T15:30:54.15Z" }, + { url = "https://files.pythonhosted.org/packages/7e/88/b82f5c5efde731b88d839ad99cb6ace2a521f03bb6d7346d2de089c76da8/tornado-6.6-cp315-cp315t-musllinux_1_2_ppc64le.whl", hash = "sha256:07b2bcaa4bf447bdbfb664e4c28344226540db3f0ebccd74886528338a240765", size = 533567, upload-time = "2026-10-21T15:30:55.451Z" }, + { url = "https://files.pythonhosted.org/packages/02/2c/e9a7f5d0fca0bdbcd48b2d9c7884dd0b32669c9945d98bc6d303a80ecfea/tornado-6.6-cp315-cp315t-musllinux_1_2_riscv64.whl", hash = "sha256:c36b921374c302e54909bae17d9f354061d80e7ae7d8c94f73abbcc217866460", size = 532849, upload-time = "2026-10-21T15:30:56.729Z" }, + { url = "https://files.pythonhosted.org/packages/d0/f5/4ade737340ca6ce9c677ea0c2843591c8ad065d07f0913c28d922c7e078e/tornado-6.6-cp315-cp315t-musllinux_1_2_s390x.whl", hash = "sha256:7412d9e37aa9f7048e4b591f520a95f7a097278ffab15f1ddf3f5c2320cf6648", size = 532873, upload-time = "2026-10-21T15:30:58.067Z" }, + { url = "https://files.pythonhosted.org/packages/8e/04/6acdc937d0bb6189ddb34ceded517d7bd1c7b3bded5d4e1b3442160e6b6f/tornado-6.6-cp315-cp315t-musllinux_1_2_x86_64.whl", hash = "sha256:15bc95112b2d24b0bfaee9a004e3f974da929e33b4244a7f695a22f45b08a5e5", size = 532883, upload-time = "2026-10-21T15:30:59.395Z" }, + { url = "https://files.pythonhosted.org/packages/ab/27/0a766fac6b1cc629d96346329a0485287fd2857c51a887a3a154f2a69938/tornado-6.6-cp315-cp315t-win32.whl", hash = "sha256:f661c21117b875d612371f3eb243d0c69f56d9bdd6aee38b7c24453419dfe554", size = 530488, upload-time = "2026-10-21T15:31:00.77Z" }, + { url = "https://files.pythonhosted.org/packages/5c/80/3e4142570883da27b3f60ae82c638ac96e60997eac684740613557519c96/tornado-6.6-cp315-cp315t-win_amd64.whl", hash = "sha256:ee8853ab35da510dc952879ebd9995c82bc10ffb7925fd87930dc0d6916f4b39", size = 530777, upload-time = "2026-10-21T15:31:02.087Z" }, + { url = "https://files.pythonhosted.org/packages/17/57/4a85c617b6349962320b4afbe1386d5b05fd57218ee8ad6e82e0110ec9ee/tornado-6.6-cp315-cp315t-win_arm64.whl", hash = "sha256:7de62e2dfdf559fd7154d2b9aa58ff3d9cff8304ae0519341feb082618bc2a33", size = 530780, upload-time = "2026-10-21T15:31:03.425Z" }, ] [[package]] @@ -1687,11 +1794,11 @@ wheels = [ [[package]] name = "typing-extensions" -version = "4.15.0" +version = "4.16.0" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/72/94/1a15dd82efb362ac84269196e94cf00f187f7ed21c242792a923cdb1c61f/typing_extensions-4.15.0.tar.gz", hash = "sha256:0cea48d173cc12fa28ecabc3b837ea3cf6f38c6d1136f85cbaaf598984861466", size = 109391, upload-time = "2025-08-25T13:49:26.313Z" } +sdist = { url = "https://files.pythonhosted.org/packages/f6/cc/6253133b5bb138fc3306cebfbda2c520f545d36b5be2c7255cc528bb45d6/typing_extensions-4.16.0.tar.gz", hash = "sha256:dc983d19a509c94dba722ee6abd33940f7c05a89e243c47e907eb4db6f1a43e5", size = 113555, upload-time = "2026-07-02T08:40:05.92Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/18/67/36e9267722cc04a6b9f15c7f3441c2363321a3ea07da7ae0c0707beb2a9c/typing_extensions-4.15.0-py3-none-any.whl", hash = "sha256:f0fa19c6845758ab08074a0cfa8b7aecb71c999ca73d62883bc25cc018c4e548", size = 44614, upload-time = "2025-08-25T13:49:24.86Z" }, + { url = "https://files.pythonhosted.org/packages/49/d3/b8441a820a491ddfc024b0b0cf0393375b75ea13866d9c66727e54c2fc80/typing_extensions-4.16.0-py3-none-any.whl", hash = "sha256:481caa481374e813c1b176ada14e97f1f67a4539ce9cfeb3f350d78d6370c2e8", size = 45571, upload-time = "2026-07-02T08:40:04.659Z" }, ] [[package]] @@ -1731,17 +1838,20 @@ wheels = [ [[package]] name = "virtualenv" -version = "20.36.1" +version = "21.15.5" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "distlib" }, - { name = "filelock" }, + { name = "filelock", version = "4.1.0", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, + { name = "filelock", version = "4.2.9", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" }, + { name = "packaging" }, { name = "platformdirs" }, + { name = "python-discovery" }, { name = "typing-extensions", marker = "python_full_version < '3.11'" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/aa/a3/4d310fa5f00863544e1d0f4de93bddec248499ccf97d4791bc3122c9d4f3/virtualenv-20.36.1.tar.gz", hash = "sha256:8befb5c81842c641f8ee658481e42641c68b5eab3521d8e092d18320902466ba", size = 6032239, upload-time = "2026-01-09T18:21:01.296Z" } +sdist = { url = "https://files.pythonhosted.org/packages/69/74/745e612b69ad14a534b7bc233c4574b968eb2c21a276ea172e8f0fc13f51/virtualenv-21.15.5.tar.gz", hash = "sha256:fb869ea32930530ccc87549877b53268c2a4d4a7d7f2c384042eca05170350e6", size = 5639868, upload-time = "2026-11-04T05:13:20.929Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/6a/2a/dc2228b2888f51192c7dc766106cd475f1b768c10caaf9727659726f7391/virtualenv-20.36.1-py3-none-any.whl", hash = "sha256:575a8d6b124ef88f6f51d56d656132389f961062a9177016a50e4f507bbcc19f", size = 6008258, upload-time = "2026-01-09T18:20:59.425Z" }, + { url = "https://files.pythonhosted.org/packages/9d/d6/f9ac78f115e32e0d76adda9db72b74425b86495ae274cd7b58c660f5d1c1/virtualenv-21.15.5-py3-none-any.whl", hash = "sha256:bcf98c32139cf3df7f0cc2c8c48ca150645c20e66f8c4fe6c1e5e40bcae73947", size = 5680750, upload-time = "2026-11-04T05:13:19.057Z" }, ] [[package]] From 437bcd9b33a87458dfdbd665586eef98474b707c Mon Sep 17 00:00:00 2001 From: Felipe Fumero Date: Fri, 6 Nov 2026 13:33:58 -0600 Subject: [PATCH 014/113] chore(release): 2.13.3 (#644) --- CHANGELOG.md | 19 +++++++++++++++++++ changelog.d/+copy-file-headers.fixed.md | 1 - changelog.d/+custom-upload-timestamp.fixed.md | 1 - changelog.d/+local-scan-errors.fixed.md | 1 - .../+parallel-download-writer.fixed.md | 1 - .../+replication-monitor-hang.fixed.md | 1 - changelog.d/+sqlite-allowed-param.fixed.md | 1 - changelog.d/+sync-silent-reporter.fixed.md | 1 - changelog.d/638.infrastructure.md | 1 - changelog.d/640.infrastructure.md | 1 - 10 files changed, 19 insertions(+), 9 deletions(-) delete mode 100644 changelog.d/+copy-file-headers.fixed.md delete mode 100644 changelog.d/+custom-upload-timestamp.fixed.md delete mode 100644 changelog.d/+local-scan-errors.fixed.md delete mode 100644 changelog.d/+parallel-download-writer.fixed.md delete mode 100644 changelog.d/+replication-monitor-hang.fixed.md delete mode 100644 changelog.d/+sqlite-allowed-param.fixed.md delete mode 100644 changelog.d/+sync-silent-reporter.fixed.md delete mode 100644 changelog.d/638.infrastructure.md delete mode 100644 changelog.d/640.infrastructure.md diff --git a/CHANGELOG.md b/CHANGELOG.md index 76b7eecf6..45f5cf39f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,25 @@ upcoming release can be found in [changelog.d](changelog.d). +## [2.13.3](https://github.com/Backblaze/b2-sdk-python/releases/tag/v2.13.3) - 2026-11-06 + + +### Fixed + +- Accept `reporter=None` in `Synchronizer.sync_folders` by using a silent reporter instead of failing. +- Keep scanning a local folder after a file cannot be read or accessed when no reporter is given, instead of failing on that file. +- Parallel download: hash the data that was actually written, and surface a failing writer to producers instead of blocking them or losing the error. +- Pass `expires`, `content_disposition`, `content_encoding` and `content_language` through `Bucket.copy` to the created file instead of dropping them. +- Send `customUploadTimestamp` under its B2 wire name when starting a large file, so custom upload timestamps are no longer ignored. +- Stop the replication monitor from hanging when its consumer fails: the producer no longer blocks on a full queue and always signals the end of input. +- Store the account's allowed capabilities in SQLite with a bound parameter instead of string formatting, and reset cached upload pools when `SqliteAccountInfo.clear()` is called. + +### Infrastructure + +- Updated the locked urllib3 dependency to version 2.8.0. ([#638](https://github.com/Backblaze/b2-sdk-python/issues/638)) +- Updated Starlette, AnyIO, and virtualenv in the development tooling. Setuptools remains below 81 for liccheck compatibility and requires a dev-only dismissal; filelock and tornado retain Python 3.10-compatible dev-only locks. ([#640](https://github.com/Backblaze/b2-sdk-python/issues/640)) + + ## [2.13.2](https://github.com/Backblaze/b2-sdk-python/releases/tag/v2.13.2) - 2026-10-21 diff --git a/changelog.d/+copy-file-headers.fixed.md b/changelog.d/+copy-file-headers.fixed.md deleted file mode 100644 index e281ca1b4..000000000 --- a/changelog.d/+copy-file-headers.fixed.md +++ /dev/null @@ -1 +0,0 @@ -Pass `expires`, `content_disposition`, `content_encoding` and `content_language` through `Bucket.copy` to the created file instead of dropping them. diff --git a/changelog.d/+custom-upload-timestamp.fixed.md b/changelog.d/+custom-upload-timestamp.fixed.md deleted file mode 100644 index 23a2d9ecc..000000000 --- a/changelog.d/+custom-upload-timestamp.fixed.md +++ /dev/null @@ -1 +0,0 @@ -Send `customUploadTimestamp` under its B2 wire name when starting a large file, so custom upload timestamps are no longer ignored. diff --git a/changelog.d/+local-scan-errors.fixed.md b/changelog.d/+local-scan-errors.fixed.md deleted file mode 100644 index 000363130..000000000 --- a/changelog.d/+local-scan-errors.fixed.md +++ /dev/null @@ -1 +0,0 @@ -Keep scanning a local folder after a file cannot be read or accessed when no reporter is given, instead of failing on that file. diff --git a/changelog.d/+parallel-download-writer.fixed.md b/changelog.d/+parallel-download-writer.fixed.md deleted file mode 100644 index 60d86aa3d..000000000 --- a/changelog.d/+parallel-download-writer.fixed.md +++ /dev/null @@ -1 +0,0 @@ -Parallel download: hash the data that was actually written, and surface a failing writer to producers instead of blocking them or losing the error. diff --git a/changelog.d/+replication-monitor-hang.fixed.md b/changelog.d/+replication-monitor-hang.fixed.md deleted file mode 100644 index c70a5291f..000000000 --- a/changelog.d/+replication-monitor-hang.fixed.md +++ /dev/null @@ -1 +0,0 @@ -Stop the replication monitor from hanging when its consumer fails: the producer no longer blocks on a full queue and always signals the end of input. diff --git a/changelog.d/+sqlite-allowed-param.fixed.md b/changelog.d/+sqlite-allowed-param.fixed.md deleted file mode 100644 index d9771ce30..000000000 --- a/changelog.d/+sqlite-allowed-param.fixed.md +++ /dev/null @@ -1 +0,0 @@ -Store the account's allowed capabilities in SQLite with a bound parameter instead of string formatting, and reset upload pools after an account-info schema update. diff --git a/changelog.d/+sync-silent-reporter.fixed.md b/changelog.d/+sync-silent-reporter.fixed.md deleted file mode 100644 index 0df357bd2..000000000 --- a/changelog.d/+sync-silent-reporter.fixed.md +++ /dev/null @@ -1 +0,0 @@ -Accept `reporter=None` in `Synchronizer.sync_folders` by using a silent reporter instead of failing. diff --git a/changelog.d/638.infrastructure.md b/changelog.d/638.infrastructure.md deleted file mode 100644 index f9fa7867a..000000000 --- a/changelog.d/638.infrastructure.md +++ /dev/null @@ -1 +0,0 @@ -Updated the locked urllib3 dependency to version 2.8.0. diff --git a/changelog.d/640.infrastructure.md b/changelog.d/640.infrastructure.md deleted file mode 100644 index 2af706e84..000000000 --- a/changelog.d/640.infrastructure.md +++ /dev/null @@ -1 +0,0 @@ -Updated Starlette, AnyIO, and virtualenv in the development tooling. Setuptools remains below 81 for liccheck compatibility and requires a dev-only dismissal; filelock and tornado retain Python 3.10-compatible dev-only locks. From a97fcab00c80644b9b05e31971184ffc5cb0952d Mon Sep 17 00:00:00 2001 From: scarreras Date: Wed, 11 Nov 2026 06:09:36 -0300 Subject: [PATCH 015/113] test(sdkharness): lock.legal_hold accepts real B2's 401 access_denied --- .sdkharness/tests/conformance/lock.legal_hold | 17 ++++++++++++++++- test/unit/test_sdkharness_lock_refusal.py | 2 +- 2 files changed, 17 insertions(+), 2 deletions(-) diff --git a/.sdkharness/tests/conformance/lock.legal_hold b/.sdkharness/tests/conformance/lock.legal_hold index d2009cff2..9cdda6e26 100755 --- a/.sdkharness/tests/conformance/lock.legal_hold +++ b/.sdkharness/tests/conformance/lock.legal_hold @@ -116,11 +116,15 @@ def step(name, action): raise Failure(name, name_of) from error -def refused(name, action, expected): +def refused(name, action, expected, *, access_denied_401=False): """Assert something is REFUSED, and record what refused it. `expected` is a tuple of exception class names. A different class -- or no exception at all -- is a Failure, because the refusal IS the claim here. + With `access_denied_401`, b2sdk's Unauthorized is also accepted, but only + when its code is `access_denied` (what real B2 answers for a delete of a + version under a legal hold); InvalidAuthToken and every other Unauthorized + code stay failures. """ try: action() @@ -130,6 +134,12 @@ def refused(name, action, expected): name_of = type(error).__name__ if name_of in expected: return name_of + if ( + access_denied_401 + and name_of == 'Unauthorized' + and getattr(error, 'code', None) == 'access_denied' + ): + return 'Unauthorized(access_denied)' raise Failure(name, f"refused with {name_of}, expected {'/'.join(expected)}") from error raise Failure(name, 'the call was permitted; the claim under test is that it is refused') @@ -269,6 +279,11 @@ def run(target: str) -> None: 'delete while held', lambda: bucket.delete_file_version(uploaded.id_, OBJECT_NAME), ('AccessDenied', 'RetentionWriteError', 'Conflict', 'BadRequest'), + # Real B2 answers a delete under a legal hold with 401 access_denied + # ("Access Denied"), measured 2026-11-10 (b2-simulator ledger F-139); + # b2sdk raises Unauthorized for it. The classes above are the + # simulator's older shapes and stay accepted. + access_denied_401=True, ) step( diff --git a/test/unit/test_sdkharness_lock_refusal.py b/test/unit/test_sdkharness_lock_refusal.py index 5c6ebf45f..5cd4a3d19 100644 --- a/test/unit/test_sdkharness_lock_refusal.py +++ b/test/unit/test_sdkharness_lock_refusal.py @@ -16,7 +16,7 @@ import pytest CONFORMANCE = Path(__file__).parents[2] / '.sdkharness' / 'tests' / 'conformance' -LEAVES = ('lock.bypass_governance', 'lock.per_file_retention') +LEAVES = ('lock.bypass_governance', 'lock.per_file_retention', 'lock.legal_hold') EXPECTED = ('AccessDenied', 'RetentionWriteError', 'Conflict', 'BadRequest') From 601015bd2bebe1f4995a6b2e2dcdf139cb5297fb Mon Sep 17 00:00:00 2001 From: Felipe Fumero Date: Fri, 13 Nov 2026 13:47:46 -0600 Subject: [PATCH 016/113] release 2.13.4 (#646) * fix: stop tracing notification-rule method calls * test: note the getter tracing case is a precaution * release 2.13.4 * docs(changelog): clarify notification rule tracing entry * fix: limit error interpretation trace arguments --- CHANGELOG.md | 7 + b2sdk/_internal/bucket.py | 2 + b2sdk/_internal/exception.py | 2 +- .../bucket/test_notification_rule_tracing.py | 48 ++++++ test/unit/test_exception.py | 143 +++++++++++++++++- 5 files changed, 200 insertions(+), 2 deletions(-) create mode 100644 test/unit/bucket/test_notification_rule_tracing.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 45f5cf39f..ce94c2e17 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,13 @@ upcoming release can be found in [changelog.d](changelog.d). +## [2.13.4](https://github.com/Backblaze/b2-sdk-python/releases/tag/v2.13.4) - 2026-11-12 + +### Fixed + +- Notification-rule methods and B2 error interpretation no longer record request arguments (including signing secrets, custom headers, and SSE-C keys) in SDK debug tracing. + + ## [2.13.3](https://github.com/Backblaze/b2-sdk-python/releases/tag/v2.13.3) - 2026-11-06 diff --git a/b2sdk/_internal/bucket.py b/b2sdk/_internal/bucket.py index e9bb5c4bd..3cc7ad214 100644 --- a/b2sdk/_internal/bucket.py +++ b/b2sdk/_internal/bucket.py @@ -1535,12 +1535,14 @@ def as_dict(self): def __repr__(self): return f'Bucket<{self.id_},{self.name},{self.type_}>' + @disable_trace def get_notification_rules(self) -> list[NotificationRuleResponse]: """ Get all notification rules for this bucket. """ return self.api.session.get_bucket_notification_rules(self.id_) + @disable_trace def set_notification_rules( self, rules: Iterable[NotificationRule] ) -> list[NotificationRuleResponse]: diff --git a/b2sdk/_internal/exception.py b/b2sdk/_internal/exception.py index 86ffa3fce..9684f8ab0 100644 --- a/b2sdk/_internal/exception.py +++ b/b2sdk/_internal/exception.py @@ -661,7 +661,7 @@ def _event_type_invalid_error(code: str, message: str, **_) -> B2Error: } -@trace_call(logger) +@trace_call(logger, only=('status', 'code')) def interpret_b2_error( status: int, code: str | None, diff --git a/test/unit/bucket/test_notification_rule_tracing.py b/test/unit/bucket/test_notification_rule_tracing.py new file mode 100644 index 000000000..7f755f697 --- /dev/null +++ b/test/unit/bucket/test_notification_rule_tracing.py @@ -0,0 +1,48 @@ +###################################################################### +# +# File: test/unit/bucket/test_notification_rule_tracing.py +# +# Copyright 2026 Backblaze Inc. All Rights Reserved. +# +# License https://www.backblaze.com/using_b2_code.html +# +###################################################################### +import logging + +import pytest + + +@pytest.mark.parametrize('method_name', ['set_notification_rules', 'get_notification_rules']) +def test_notification_rule_values_are_not_traced(bucket, caplog, method_name): + signing_value = '0123456789abcdefghijklmnopqrstuv' + rules = [ + { + 'eventTypes': ['b2:ObjectCreated:*'], + 'isEnabled': True, + 'name': 'test-rule', + 'objectNamePrefix': '', + 'targetConfiguration': { + 'customHeaders': [], + 'targetType': 'webhook', + 'url': 'https://example.com/webhook', + 'hmacSha256SigningSecret': signing_value, + }, + } + ] + # Precaution: B2TraceMeta skips get_* and logfury does not log return values. + # Keep this case in case either behavior changes. + if method_name == 'get_notification_rules': + bucket.set_notification_rules(rules) + + logger = logging.getLogger('b2sdk._internal.bucket') + caplog.clear() + with caplog.at_level(logging.DEBUG, logger=logger.name): + logger.debug('notification rule logging capture') + if method_name == 'set_notification_rules': + result = bucket.set_notification_rules(rules) + else: + result = bucket.get_notification_rules() + + assert (logger.name, logging.DEBUG, 'notification rule logging capture') in caplog.record_tuples + assert result[0]['targetConfiguration']['hmacSha256SigningSecret'] == signing_value + assert all(signing_value not in record.getMessage() for record in caplog.records) diff --git a/test/unit/test_exception.py b/test/unit/test_exception.py index 5b460b51b..e7e0e41b8 100644 --- a/test/unit/test_exception.py +++ b/test/unit/test_exception.py @@ -9,7 +9,23 @@ ###################################################################### from __future__ import annotations +import base64 +import json +import logging +import re +import secrets +from contextlib import closing +from logging.handlers import BufferingHandler + import pytest +import responses +from apiver_deps import ( + B2RawHTTPApi, + EncryptionAlgorithm, + EncryptionKey, + EncryptionMode, + EncryptionSetting, +) from apiver_deps_exception import ( AlreadyFailed, B2Error, @@ -35,7 +51,9 @@ interpret_b2_error, ) -from b2sdk._internal.exception import RequestTimeout, ResourceNotFound +from b2sdk._internal.api_config import B2HttpApiConfig +from b2sdk._internal.b2http import B2Http +from b2sdk._internal.exception import BadRequest, RequestTimeout, ResourceNotFound, SSECKeyError class TestB2Error: @@ -156,6 +174,43 @@ def test_service_error_without_retry_after_header(self): error = self._check_one(ServiceError, 503, '', '', {}) assert error.retry_after_seconds is None + @pytest.mark.parametrize('use_keywords', [False, True], ids=['positional', 'keyword']) + def test_trace_uses_only_safe_arguments(self, caplog, monkeypatch, use_keywords): + key_value = base64.b64encode(secrets.token_bytes(32)).decode('ascii') + header_value = secrets.token_urlsafe(24) + message_value = secrets.token_urlsafe(24) + arguments = dict( + status=503, + code='server_busy', + message=message_value, + response_headers={'retry-after': '7', 'X-Trace-Test': header_value}, + post_params={'serverSideEncryption': {'mode': 'SSE-C', 'customerKey': key_value}}, + ) + logger = logging.getLogger('b2sdk._internal.exception') + with closing(BufferingHandler(capacity=100)) as handler, monkeypatch.context() as patch: + # Keep test values in memory, including on a failed assertion. + patch.setattr(logger, 'handlers', [handler]) + patch.setattr(logger, 'propagate', False) + with caplog.at_level(logging.DEBUG, logger=logger.name): + if use_keywords: + error = interpret_b2_error(**arguments) + else: + error = interpret_b2_error(*arguments.values()) + + messages = [record.getMessage() for record in handler.buffer] + has_private_values = any( + value in message + for value in (key_value, header_value, message_value) + for message in messages + ) + assert not has_private_values, 'trace included a disallowed argument value' + assert any( + 'status=503' in message and "code='server_busy'" in message for message in messages + ) + + assert isinstance(error, ServiceError) + assert error.retry_after_seconds == 7 + @pytest.mark.apiver( from_ver=3 ) # previous apivers throw this as well, but BucketIdNotFound is a different class in them @@ -206,3 +261,89 @@ def test_simple_error_handlers(self, status, code, expected_exception_cls): error = interpret_b2_error(status, code, '', {}) assert isinstance(error, expected_exception_cls) assert error.code == code + + +@pytest.mark.parametrize('operation', ['notification_rules', 'sse_c_copy']) +def test_http_error_trace_keeps_request_values_private(bucket, caplog, monkeypatch, operation): + signing_value = secrets.token_hex(16) + header_value = secrets.token_urlsafe(24) + response_value = secrets.token_urlsafe(24) + message_value = secrets.token_urlsafe(24) + key = EncryptionKey(secret=secrets.token_bytes(32), key_id=None) + key_value = key.key_b64() + encryption = EncryptionSetting(EncryptionMode.SSE_C, EncryptionAlgorithm.AES256, key) + rules = [ + { + 'eventTypes': ['b2:ObjectCreated:*'], + 'isEnabled': True, + 'name': 'test-rule', + 'objectNamePrefix': '', + 'targetConfiguration': { + 'targetType': 'webhook', + 'url': 'https://example.com/webhook', + 'hmacSha256SigningSecret': signing_value, + 'customHeaders': [{'name': 'X-Test-Header', 'value': header_value}], + }, + } + ] + if operation == 'notification_rules': + endpoint, status, code, error_class = ( + 'b2_set_bucket_notification_rules', + 400, + 'bad_request', + BadRequest, + ) + else: + endpoint, status, code, error_class = 'b2_copy_file', 403, 'access_denied', SSECKeyError + + http = B2Http(B2HttpApiConfig(install_clock_skew_hook=False)) + bucket.api.session.raw_api = B2RawHTTPApi(http) + logger = logging.getLogger('b2sdk') + with ( + closing(BufferingHandler(capacity=100)) as handler, + monkeypatch.context() as patch, + responses.RequestsMock() as transport, + ): + # Capture the entire SDK namespace without letting values reach pytest's log output. + patch.setattr(logger, 'handlers', [handler]) + patch.setattr(logger, 'propagate', False) + transport.add( + responses.POST, + re.compile(r'.*/' + endpoint + '$'), + status=status, + json={'status': status, 'code': code, 'message': message_value}, + headers={'X-Test-Response': response_value}, + ) + with caplog.at_level(logging.DEBUG, logger=logger.name), pytest.raises(error_class): + if operation == 'notification_rules': + bucket.set_notification_rules(rules) + else: + bucket.api.session.copy_file( + 'source-file', 'target-file', source_server_side_encryption=encryption + ) + + assert len(transport.calls) == 1 + request = json.loads(transport.calls[0].request.body) + if operation == 'notification_rules': + target = request['eventNotificationRules'][0]['targetConfiguration'] + request_has_values = ( + target['hmacSha256SigningSecret'] == signing_value + and target['customHeaders'][0]['value'] == header_value + ) + else: + request_has_values = request['sourceServerSideEncryption']['customerKey'] == key_value + assert request_has_values, 'The HTTP request must exercise the sensitive request fields' + + messages = [record.getMessage() for record in handler.buffer] + has_private_values = any( + value in message + for value in (signing_value, header_value, key_value, response_value, message_value) + for message in messages + ) + assert not has_private_values, 'Private values must not appear in SDK tracing' + assert any( + 'calling interpret_b2_error(' in message + and f'status={status}' in message + and f'code={code!r}' in message + for message in messages + ) From 028bb542cc2539fe6fd12c82820e2a5c153607cb Mon Sep 17 00:00:00 2001 From: Felipe Fumero Date: Fri, 13 Nov 2026 13:52:04 -0600 Subject: [PATCH 017/113] test: accept legal-hold refusals across simulator versions (#647) * test(sdkharness): expect Unauthorized for legal-hold delete * test(sdkharness): retain legacy legal-hold refusals --- .sdkharness/tests/conformance/lock.legal_hold | 13 +++++++++++- ...egal-hold-delete-refusal.infrastructure.md | 1 + test/unit/test_sdkharness_lock_refusal.py | 21 +++++++++++++------ 3 files changed, 28 insertions(+), 7 deletions(-) create mode 100644 changelog.d/+sdkharness-legal-hold-delete-refusal.infrastructure.md diff --git a/.sdkharness/tests/conformance/lock.legal_hold b/.sdkharness/tests/conformance/lock.legal_hold index d2009cff2..2a0a97b03 100755 --- a/.sdkharness/tests/conformance/lock.legal_hold +++ b/.sdkharness/tests/conformance/lock.legal_hold @@ -116,11 +116,13 @@ def step(name, action): raise Failure(name, name_of) from error -def refused(name, action, expected): +def refused(name, action, expected, *, access_denied_401=False): """Assert something is REFUSED, and record what refused it. `expected` is a tuple of exception class names. A different class -- or no exception at all -- is a Failure, because the refusal IS the claim here. + With `access_denied_401`, Unauthorized is also accepted, but only when its + code is `access_denied`; other authorization failures remain failures. """ try: action() @@ -130,6 +132,12 @@ def refused(name, action, expected): name_of = type(error).__name__ if name_of in expected: return name_of + if ( + access_denied_401 + and name_of == 'Unauthorized' + and getattr(error, 'code', None) == 'access_denied' + ): + return 'Unauthorized(access_denied)' raise Failure(name, f"refused with {name_of}, expected {'/'.join(expected)}") from error raise Failure(name, 'the call was permitted; the claim under test is that it is refused') @@ -268,7 +276,10 @@ def run(target: str) -> None: refused( 'delete while held', lambda: bucket.delete_file_version(uploaded.id_, OBJECT_NAME), + # b2_delete_file_version error table and b2-simulator FIDELITY.md F-139: + # real B2 uses 401 access_denied; retain older simulator refusal shapes. ('AccessDenied', 'RetentionWriteError', 'Conflict', 'BadRequest'), + access_denied_401=True, ) step( diff --git a/changelog.d/+sdkharness-legal-hold-delete-refusal.infrastructure.md b/changelog.d/+sdkharness-legal-hold-delete-refusal.infrastructure.md new file mode 100644 index 000000000..a4b4a01b6 --- /dev/null +++ b/changelog.d/+sdkharness-legal-hold-delete-refusal.infrastructure.md @@ -0,0 +1 @@ +Make the sdkharness legal-hold delete check accept B2's `401 access_denied` response while retaining older simulator refusal shapes. diff --git a/test/unit/test_sdkharness_lock_refusal.py b/test/unit/test_sdkharness_lock_refusal.py index 5c6ebf45f..b78858205 100644 --- a/test/unit/test_sdkharness_lock_refusal.py +++ b/test/unit/test_sdkharness_lock_refusal.py @@ -16,7 +16,7 @@ import pytest CONFORMANCE = Path(__file__).parents[2] / '.sdkharness' / 'tests' / 'conformance' -LEAVES = ('lock.bypass_governance', 'lock.per_file_retention') +LEAVES = ('lock.bypass_governance', 'lock.per_file_retention', 'lock.legal_hold') EXPECTED = ('AccessDenied', 'RetentionWriteError', 'Conflict', 'BadRequest') @@ -64,14 +64,15 @@ def test_401_access_denied_counts_as_the_refusal(leaf): @pytest.mark.parametrize('leaf', LEAVES) -def test_the_old_refusal_classes_are_still_accepted(leaf): +@pytest.mark.parametrize('error_name', EXPECTED) +def test_the_old_refusal_classes_are_still_accepted(leaf, error_name): module = load_leaf(leaf) - AccessDenied = type('AccessDenied', (Exception,), {}) + refusal_class = type(error_name, (Exception,), {}) assert ( module.refused( - 'delete without bypass', raising(AccessDenied()), EXPECTED, access_denied_401=True + 'delete without bypass', raising(refusal_class()), EXPECTED, access_denied_401=True ) - == 'AccessDenied' + == error_name ) @@ -89,10 +90,18 @@ def test_an_allowed_operation_still_fails(leaf): InvalidAuthToken('expired_auth_token'), Unauthorized('bad_auth_token'), Unauthorized('email_not_verified'), + Unauthorized('unauthorized'), ServiceError('503'), KeyError('404'), ], - ids=['bad-token', 'other-401-code', 'unverified-email', '5xx', 'not-found'], + ids=[ + 'bad-token', + 'other-401-code', + 'unverified-email', + 'missing-capability', + '5xx', + 'not-found', + ], ) def test_an_unrelated_refusal_still_fails(leaf, error): module = load_leaf(leaf) From 862ab89f90f016cc865c0953bd10ffb5d97d2edd Mon Sep 17 00:00:00 2001 From: Felipe Fumero Date: Tue, 17 Nov 2026 15:49:58 -0600 Subject: [PATCH 018/113] chore(release): 2.13.5 (#671) --- CHANGELOG.md | 8 ++++++++ ...sdkharness-legal-hold-delete-refusal.infrastructure.md | 1 - 2 files changed, 8 insertions(+), 1 deletion(-) delete mode 100644 changelog.d/+sdkharness-legal-hold-delete-refusal.infrastructure.md diff --git a/CHANGELOG.md b/CHANGELOG.md index ce94c2e17..9518f6bd5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,14 @@ upcoming release can be found in [changelog.d](changelog.d). +## [2.13.5](https://github.com/Backblaze/b2-sdk-python/releases/tag/v2.13.5) - 2026-11-17 + + +### Infrastructure + +- Make the sdkharness legal-hold delete check accept B2's `401 access_denied` response while retaining older simulator refusal shapes. + + ## [2.13.4](https://github.com/Backblaze/b2-sdk-python/releases/tag/v2.13.4) - 2026-11-12 ### Fixed diff --git a/changelog.d/+sdkharness-legal-hold-delete-refusal.infrastructure.md b/changelog.d/+sdkharness-legal-hold-delete-refusal.infrastructure.md deleted file mode 100644 index a4b4a01b6..000000000 --- a/changelog.d/+sdkharness-legal-hold-delete-refusal.infrastructure.md +++ /dev/null @@ -1 +0,0 @@ -Make the sdkharness legal-hold delete check accept B2's `401 access_denied` response while retaining older simulator refusal shapes. From afb0a7db771cac49c58ba96853e13cb489df9f06 Mon Sep 17 00:00:00 2001 From: Felipe Fumero Date: Thu, 19 Nov 2026 10:55:40 -0600 Subject: [PATCH 019/113] ci: replace unverified third-party GitHub Actions with first-party steps (#675) * ci: replace community actions with local workflow commands * ci: preserve the original codespell invocation --- .github/workflows/cd.yml | 89 ++++++++++++++++--- .github/workflows/ci.yml | 10 ++- ...ndor-third-party-actions.infrastructure.md | 1 + 3 files changed, 83 insertions(+), 17 deletions(-) create mode 100644 changelog.d/+ci-vendor-third-party-actions.infrastructure.md diff --git a/.github/workflows/cd.yml b/.github/workflows/cd.yml index 8c0c898f2..f79a0c0f5 100644 --- a/.github/workflows/cd.yml +++ b/.github/workflows/cd.yml @@ -10,6 +10,8 @@ env: jobs: deploy: + permissions: + contents: write env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} B2_PYPI_PASSWORD: ${{ secrets.B2_PYPI_PASSWORD }} @@ -18,8 +20,9 @@ jobs: - name: Determine if pre-release id: prerelease_check run: | - export IS_PRERELEASE=$([[ ${{ github.ref }} =~ [^0-9]$ ]] && echo true || echo false) - echo "prerelease=$IS_PRERELEASE" >> $GITHUB_OUTPUT + IS_PRERELEASE=$([[ ${{ github.ref }} =~ [^0-9]$ ]] && echo true || echo false) + export IS_PRERELEASE + echo "prerelease=$IS_PRERELEASE" >> "$GITHUB_OUTPUT" - uses: actions/checkout@v4 with: fetch-depth: 0 @@ -38,20 +41,78 @@ jobs: - name: Build the distribution id: build run: uv run nox -vs build - - name: Read the Changelog + # actions-governance: replaced by Read the Changelog with awk; remove after a real run verifies the replacement + # - name: Read the Changelog + # id: read-changelog + # uses: mindsers/changelog-reader-action@v2 + # with: + # version: ${{ steps.build.outputs.version }} + - name: Read the Changelog with awk id: read-changelog - uses: mindsers/changelog-reader-action@v2 - with: - version: ${{ steps.build.outputs.version }} - - name: Create GitHub release and upload the distribution + env: + VERSION: ${{ steps.build.outputs.version }} + run: | + notes_file="$RUNNER_TEMP/release-notes.md" + awk -v version="$VERSION" ' + /^## \[/ { + if (found) exit + heading = $0 + sub(/^## \[/, "", heading) + sub(/\].*$/, "", heading) + found = (heading == version) + next + } + found { lines[++count] = $0 } + END { + if (!found) exit 1 + while (count && lines[count] ~ /^[[:space:]]*$/) count-- + for (i = 1; i <= count; i++) + printf "%s%s", lines[i], (i < count ? "\n" : "") + } + ' CHANGELOG.md > "$notes_file" + delimiter="changelog_$(python -c 'import uuid; print(uuid.uuid4().hex)')" + { + echo "changes<<$delimiter" + cat "$notes_file" + echo + echo "$delimiter" + } >> "$GITHUB_OUTPUT" + # actions-governance: replaced by Create GitHub release with gh and upload the distribution; remove after a real run verifies the replacement + # - name: Create GitHub release and upload the distribution + # id: create-release + # uses: softprops/action-gh-release@v2 + # with: + # name: ${{ steps.build.outputs.version }} + # body: ${{ steps.read-changelog.outputs.changes }} + # draft: ${{ env.ACTIONS_STEP_DEBUG == 'true' }} + # prerelease: ${{ steps.prerelease_check.outputs.prerelease }} + # files: ${{ steps.build.outputs.asset_path }} + - name: Create GitHub release with gh and upload the distribution id: create-release - uses: softprops/action-gh-release@v2 - with: - name: ${{ steps.build.outputs.version }} - body: ${{ steps.read-changelog.outputs.changes }} - draft: ${{ env.ACTIONS_STEP_DEBUG == 'true' }} - prerelease: ${{ steps.prerelease_check.outputs.prerelease }} - files: ${{ steps.build.outputs.asset_path }} + env: + TAG: ${{ github.ref_name }} + VERSION: ${{ steps.build.outputs.version }} + RELEASE_NOTES: ${{ steps.read-changelog.outputs.changes }} + IS_DRAFT: ${{ env.ACTIONS_STEP_DEBUG == 'true' }} + IS_PRERELEASE: ${{ steps.prerelease_check.outputs.prerelease }} + ASSET_PATH: ${{ steps.build.outputs.asset_path }} + run: | + notes_file="$RUNNER_TEMP/github-release-notes.md" + printf '%s' "$RELEASE_NOTES" > "$notes_file" + if ! gh release view "$TAG" > /dev/null 2>&1; then + # Upload assets before publishing the requested final release state. + gh release create "$TAG" --verify-tag --title "$VERSION" \ + --notes-file "$notes_file" --draft --prerelease="$IS_PRERELEASE" + fi + assets=() + while IFS= read -r asset; do + assets+=("$asset") + done < <(compgen -G "$ASSET_PATH" || true) + if ((${#assets[@]})); then + gh release upload "$TAG" "${assets[@]}" --clobber + fi + gh release edit "$TAG" --title "$VERSION" --notes-file "$notes_file" \ + --draft="$IS_DRAFT" --prerelease="$IS_PRERELEASE" - name: Upload the distribution to PyPI if: ${{ env.B2_PYPI_PASSWORD != '' && steps.prerelease_check.outputs.prerelease == 'false' }} uses: pypa/gh-action-pypi-publish@release/v1 diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 8b58b6acf..4acc6e4b0 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -18,9 +18,13 @@ jobs: - uses: actions/checkout@v4 with: fetch-depth: 0 - - uses: codespell-project/actions-codespell@2391250ab05295bddd51e36a8c6295edb6343b0e - with: - ignore_words_list: datas re-use + # actions-governance: replaced by Check spelling; remove after a real run verifies the replacement + # - uses: codespell-project/actions-codespell@2391250ab05295bddd51e36a8c6295edb6343b0e + # with: + # ignore_words_list: datas re-use + - name: Check spelling + # Preserve the original action's effective CLI arguments, including its positional path. + run: pipx run codespell --count --skip ./.git --ignore-words-list datas re-use - name: Set up Python ${{ env.PYTHON_DEFAULT_VERSION }} uses: actions/setup-python@v6 with: diff --git a/changelog.d/+ci-vendor-third-party-actions.infrastructure.md b/changelog.d/+ci-vendor-third-party-actions.infrastructure.md new file mode 100644 index 000000000..650c41017 --- /dev/null +++ b/changelog.d/+ci-vendor-third-party-actions.infrastructure.md @@ -0,0 +1 @@ +Replace community spelling, changelog-reading, and GitHub release actions with local commands, retaining commented fallbacks until a real workflow run verifies the replacements. From 564785aae815ae6741d58f9023f38fd27f5f7a9a Mon Sep 17 00:00:00 2001 From: Felipe Fumero Date: Thu, 19 Nov 2026 13:27:44 -0600 Subject: [PATCH 020/113] Keep negative-size range-stream reads within the selected range (#677) * fix: bound negative range stream reads * docs: clarify bounded stream reads * docs: add range stream changelog entry --- b2sdk/_internal/stream/range.py | 4 +-- .../+range-read-negative-size.fixed.md | 1 + test/unit/stream/test_finding_c46_range.py | 34 +++++++++++++++++++ 3 files changed, 37 insertions(+), 2 deletions(-) create mode 100644 changelog.d/+range-read-negative-size.fixed.md create mode 100644 test/unit/stream/test_finding_c46_range.py diff --git a/b2sdk/_internal/stream/range.py b/b2sdk/_internal/stream/range.py index cdc891ed8..cb96f5a0d 100644 --- a/b2sdk/_internal/stream/range.py +++ b/b2sdk/_internal/stream/range.py @@ -58,12 +58,12 @@ def read(self, size=None): """ Read data from the stream. - :param int size: number of bytes to read + :param int size: number of bytes to read; None or a negative value reads the remaining range :return: data read from the stream :rtype: bytes """ remaining = max(0, self.length - self.relative_pos) - if size is None: + if size is None or size < 0: to_read = remaining else: to_read = min(size, remaining) diff --git a/changelog.d/+range-read-negative-size.fixed.md b/changelog.d/+range-read-negative-size.fixed.md new file mode 100644 index 000000000..daf785358 --- /dev/null +++ b/changelog.d/+range-read-negative-size.fixed.md @@ -0,0 +1 @@ +Reading a range stream with a negative size no longer returns bytes past the end of the configured range. diff --git a/test/unit/stream/test_finding_c46_range.py b/test/unit/stream/test_finding_c46_range.py new file mode 100644 index 000000000..a93880023 --- /dev/null +++ b/test/unit/stream/test_finding_c46_range.py @@ -0,0 +1,34 @@ +###################################################################### +# +# File: test/unit/stream/test_finding_c46_range.py +# +# Copyright 2026 Backblaze Inc. All Rights Reserved. +# +# License https://www.backblaze.com/using_b2_code.html +# +###################################################################### +import io + +import pytest + +from b2sdk._internal.stream.range import RangeOfInputStream + + +def test_c46_read_minus_one_does_not_go_past_range_end(): + with RangeOfInputStream(io.BytesIO(b'0123456789'), offset=2, length=3) as stream: + assert stream.read(-1) == b'234' + + +@pytest.mark.parametrize('size', [-1, -7]) +def test_negative_read_is_bounded_after_partial_read(size): + with RangeOfInputStream(io.BytesIO(b'0123456789'), offset=2, length=3) as stream: + assert stream.read(1) == b'2' + assert stream.read(size) == b'34' + assert stream.tell() == 3 + assert stream.read(size) == b'' + + +def test_negative_read_from_empty_range_is_empty(): + with RangeOfInputStream(io.BytesIO(b'0123456789'), offset=2, length=0) as stream: + assert stream.read(-1) == b'' + assert stream.tell() == 0 From e3652cae2549e77e370ed4bee444a27f7d79a845 Mon Sep 17 00:00:00 2001 From: Felipe Fumero Date: Thu, 19 Nov 2026 13:28:18 -0600 Subject: [PATCH 021/113] fix: simplify concurrent upload error messages (#676) Simplify and harden the error messages raised for concurrent-upload responses, and add regression tests covering casing and formatting variants. --- b2sdk/_internal/exception.py | 5 +- changelog.d/+concurrent-upload-error.fixed.md | 1 + test/unit/test_exception.py | 54 ++++++++++++++++++- 3 files changed, 57 insertions(+), 3 deletions(-) create mode 100644 changelog.d/+concurrent-upload-error.fixed.md diff --git a/b2sdk/_internal/exception.py b/b2sdk/_internal/exception.py index 9684f8ab0..797fe9552 100644 --- a/b2sdk/_internal/exception.py +++ b/b2sdk/_internal/exception.py @@ -522,7 +522,7 @@ def __init__(self, token): self.token = token def __str__(self): - return f'More than one concurrent upload using auth token {self.token}' + return 'More than one concurrent upload using the same auth token' class AccessDenied(B2Error): @@ -713,7 +713,8 @@ def interpret_b2_error( return BucketIdNotFound(post_params.get('bucketId')) elif status == 400 and code == 'auth_token_limit': matcher = UPLOAD_TOKEN_USED_CONCURRENTLY_ERROR_MESSAGE_RE.match(message) - assert matcher is not None, f'unexpected error message: {message}' + if matcher is None: + raise AssertionError('unexpected auth_token_limit error message') token = matcher.group('token') return UploadTokenUsedConcurrently(token) elif status == 400 and code == 'source_too_large': diff --git a/changelog.d/+concurrent-upload-error.fixed.md b/changelog.d/+concurrent-upload-error.fixed.md new file mode 100644 index 000000000..797ce988a --- /dev/null +++ b/changelog.d/+concurrent-upload-error.fixed.md @@ -0,0 +1 @@ +Simplify and clarify the error messages raised for concurrent-upload responses. diff --git a/test/unit/test_exception.py b/test/unit/test_exception.py index e7e0e41b8..4f64a5c3b 100644 --- a/test/unit/test_exception.py +++ b/test/unit/test_exception.py @@ -53,7 +53,14 @@ from b2sdk._internal.api_config import B2HttpApiConfig from b2sdk._internal.b2http import B2Http -from b2sdk._internal.exception import BadRequest, RequestTimeout, ResourceNotFound, SSECKeyError +from b2sdk._internal.exception import ( + BadRequest, + MaxRetriesExceeded, + RequestTimeout, + ResourceNotFound, + SSECKeyError, + UploadTokenUsedConcurrently, +) class TestB2Error: @@ -65,6 +72,19 @@ def test_unicode(self): class TestExceptions: + @pytest.mark.parametrize('retry_summary', [False, True], ids=['direct', 'retry-summary']) + def test_concurrent_upload_error_text_omits_token(self, retry_summary): + tokens = ('test-only-upload-token-a', 'test-only-upload-token-b') + errors = [UploadTokenUsedConcurrently(token) for token in tokens] + error = MaxRetriesExceeded(2, errors) if retry_summary else errors[0] + + message = str(error) + contains_token = any(token in message for token in tokens) + assert not contains_token, 'upload authorization token was included in exception text' + assert message.count('More than one concurrent upload') == (2 if retry_summary else 1) + if retry_summary: + assert 'FAILED to upload after 2 tries.' in message + def test_bad_upload_url_exception(self): try: raise BadUploadUrl('foo') @@ -90,6 +110,38 @@ def test_command_error(self): class TestInterpretError: + @pytest.mark.parametrize('http_path', [False, True], ids=['direct', 'http']) + @pytest.mark.parametrize('variant', ['casing', 'parenthesis']) + def test_unexpected_auth_token_limit_text_omits_token(self, variant, http_path, caplog): + token = 'test-only-upload-token-secret' + message = f'More than one upload using auth token {token}' + if variant == 'parenthesis': + token += ')suffix' + message = f'more than one upload using auth token {token}' + + if http_path: + http = B2Http(B2HttpApiConfig(install_clock_skew_hook=False)) + url = 'https://example.com/b2api/v3/b2_upload_file' + with responses.RequestsMock() as transport: + transport.add( + responses.POST, + url, + status=400, + json={'status': 400, 'code': 'auth_token_limit', 'message': message}, + ) + with caplog.at_level(logging.ERROR, logger='b2sdk'), pytest.raises( + UnknownError + ) as raised: + http.post_json_return_json(url, {}, {}, try_count=1) + assert len(transport.calls) == 1 + assert any(record.exc_info for record in caplog.records) + else: + with pytest.raises(AssertionError) as raised: + interpret_b2_error(400, 'auth_token_limit', message, {}) + + assert token not in str(raised.value) + assert token not in caplog.text + def test_file_already_hidden(self): self._check_one(FileAlreadyHidden, 400, 'already_hidden', '', {}) assert 'File already hidden: file.txt' == str( From fc258be76453467bacd9e30a45f075cbca58f68e Mon Sep 17 00:00:00 2001 From: Felipe Fumero Date: Thu, 19 Nov 2026 13:37:54 -0600 Subject: [PATCH 022/113] Continue hashing through short stream reads (#679) * fix: continue hashing through short stream reads Read nonempty short chunks until the requested length or end of stream. Append the digest only after end of stream and preserve zero-length reads. Fixes #654 * Add changelog fragment for short-read hashing fix (#654) --- b2sdk/_internal/stream/hashing.py | 27 +++-- b2sdk/_internal/utils/__init__.py | 2 +- changelog.d/654.fixed.md | 1 + .../stream/test_finding_c16_short_reads.py | 101 ++++++++++++++++++ 4 files changed, 121 insertions(+), 10 deletions(-) create mode 100644 changelog.d/654.fixed.md create mode 100644 test/unit/stream/test_finding_c16_short_reads.py diff --git a/b2sdk/_internal/stream/hashing.py b/b2sdk/_internal/stream/hashing.py index 858774d7e..cc5551ad2 100644 --- a/b2sdk/_internal/stream/hashing.py +++ b/b2sdk/_internal/stream/hashing.py @@ -55,17 +55,26 @@ def read(self, size=None): :return: read data :rtype: bytes|None """ + if size == 0: + return super().read(size) + if size is not None and size < 0: + size = None + data = b'' if self.hash is None: - data = super().read(size) - # Update hash - self.digest.update(data) - - # Check for end of stream - if size is None or len(data) < size: - self.hash = self.digest.hexdigest() - if size is not None: - size -= len(data) + chunks = [] + data_len = 0 + while size is None or data_len < size: + chunk = super().read(None if size is None else size - data_len) + if chunk == b'': + self.hash = self.digest.hexdigest() + break + self.digest.update(chunk) + chunks.append(chunk) + data_len += len(chunk) + data = b''.join(chunks) + if self.hash is not None and size is not None: + size -= data_len if self.hash is not None: # The end of stream was reached, return hash now diff --git a/b2sdk/_internal/utils/__init__.py b/b2sdk/_internal/utils/__init__.py index ed409a188..d6819864a 100644 --- a/b2sdk/_internal/utils/__init__.py +++ b/b2sdk/_internal/utils/__init__.py @@ -180,7 +180,7 @@ def update_from_stream( self.digest.update(data) self.read_bytes += data_len offset += data_len - if data_len < to_read or to_read == 0: + if data_len == 0 or to_read == 0: break return self.hex_digest diff --git a/changelog.d/654.fixed.md b/changelog.d/654.fixed.md new file mode 100644 index 000000000..db1520ef8 --- /dev/null +++ b/changelog.d/654.fixed.md @@ -0,0 +1 @@ +Stream hashing now continues reading until the requested length or the true end of data. Previously a source that returned a short read before EOF could produce a checksum and length covering only a prefix, allowing a truncated body to be uploaded with a matching hash. diff --git a/test/unit/stream/test_finding_c16_short_reads.py b/test/unit/stream/test_finding_c16_short_reads.py new file mode 100644 index 000000000..baabf0a78 --- /dev/null +++ b/test/unit/stream/test_finding_c16_short_reads.py @@ -0,0 +1,101 @@ +###################################################################### +# +# File: test/unit/stream/test_finding_c16_short_reads.py +# +# Copyright 2026 Backblaze Inc. All Rights Reserved. +# +# License https://www.backblaze.com/using_b2_code.html +# +###################################################################### +from __future__ import annotations + +import io + +import pytest + +from b2sdk._internal.stream.hashing import StreamWithHash +from b2sdk._internal.transfer.outbound.upload_source import UploadSourceStream +from b2sdk._internal.utils import IncrementalHexDigester, hex_sha1_of_unlimited_stream + +DATA = b'0123456789' +SHA1 = '87acec17cd9dcd20a716cc2cf67417b71c8a7016' +PREFIX_SHA1 = 'c4b5c86bd577da3d93fea7c89cba61c78b48e589' +EMPTY_SHA1 = 'da39a3ee5e6b4b0d3255bfef95601890afd80709' + + +class ShortReadStream(io.BytesIO): + """A blocking source that may return less than requested before EOF.""" + + def __init__(self, data, chunk_size=3): + super().__init__(data) + self.chunk_size = chunk_size + + def read(self, size=-1): + if size is None or size < 0: + return super().read() + return super().read(min(size, self.chunk_size)) + + +@pytest.mark.parametrize('chunk_size', [1, 3]) +def test_unlimited_digest_and_length_cover_the_whole_stream(chunk_size): + assert hex_sha1_of_unlimited_stream(ShortReadStream(DATA, chunk_size)) == (SHA1, len(DATA)) + + +def test_limited_digest_reads_to_the_limit_then_resumes(): + stream = ShortReadStream(DATA) + digester = IncrementalHexDigester(stream, block_size=5) + + assert digester.update_from_stream(0) == EMPTY_SHA1 + assert stream.tell() == digester.read_bytes == 0 + assert digester.update_from_stream(4) == PREFIX_SHA1 + assert stream.tell() == digester.read_bytes == 4 + assert digester.update_from_stream() == SHA1 + assert stream.tell() == digester.read_bytes == len(DATA) + + +def test_upload_source_reports_the_whole_length_and_digest(): + source = UploadSourceStream(lambda: ShortReadStream(DATA)) + assert source.get_content_length() == len(DATA) + assert source.get_content_sha1() == SHA1 + + +@pytest.mark.parametrize('data, digest', [(DATA, SHA1), (b'', EMPTY_SHA1)]) +@pytest.mark.parametrize('read_size', [4, 10, 11, 64, None, -1]) +def test_hashing_stream_preserves_all_data_before_appending_digest(data, digest, read_size): + stream = StreamWithHash(ShortReadStream(data), stream_length=len(data)) + expected = data + digest.encode('ascii') + assert len(stream) == len(expected) + + if read_size is None: + assert stream.read() == expected + elif read_size < 0: + assert stream.read(read_size) == expected + else: + for offset in range(0, len(expected), read_size): + assert stream.read(read_size) == expected[offset : offset + read_size] + assert stream.read(read_size) == b'' + + +def test_zero_reads_do_not_consume_data_or_digest(): + stream = StreamWithHash(io.BytesIO(DATA)) + expected = DATA + SHA1.encode('ascii') + assert stream.read(0) == b'' + assert stream.read(len(DATA) + 2) == expected[: len(DATA) + 2] + assert stream.read(0) == b'' + assert stream.read() == expected[len(DATA) + 2 :] + assert stream.read(0) == b'' + + +def test_zero_read_preserves_the_closed_source_error(): + source = io.BytesIO(DATA) + stream = StreamWithHash(source) + source.close() + with pytest.raises(ValueError, match='closed'): + stream.read(0) + + +def test_seek_to_start_resets_the_digest_after_short_reads(): + stream = StreamWithHash(ShortReadStream(DATA)) + stream.read(4) + stream.seek(0) + assert stream.read() == DATA + SHA1.encode('ascii') From 846909bbb4b688715859081a63626fa8eea611ac Mon Sep 17 00:00:00 2001 From: Sophie <49928680+sophiecarreras@users.noreply.github.com> Date: Fri, 20 Nov 2026 03:17:07 -0300 Subject: [PATCH 023/113] Add regression tests for known defects (#673) * test: add regression tests for known defects (tests only) Add regression tests for known defects. Tests of defects that are still present are strict expected failures (`xfail(strict=True)`, reason "Known defect C: ..."), tagged with a new `known_defect` marker, so the default run stays green and fails as soon as a defect is fixed, which prompts removing the decorator. `pytest --runxfail -m known_defect --api=v3 test/unit test/static` runs them as real failures. Tests that pass today run in the normal suite. No production code changes. Test wiring: `test/known_defect.py` (decorator) and marker registration in `test/conftest.py`. Co-Authored-By: Claude Sonnet 5.5 * test: constrain known_defect to each defect's specific failure path Address review of the regression tests (tests only, no production changes): - known_defect now requires `raises=`, passed to xfail(strict=True, raises=...), so an unrelated exception or a failed prerequisite is a real failure instead of an XFAIL. New helpers `expect`/`defect_raises`/`DefectStillPresent` pin the defect to one assertion or to one exception type and message; prerequisites stay ordinary assertions. - C13 guard: inject CanRetry(True) in the upload_part wrapper for one designated part and assert the retry used a different URL/token pair. - C8: event-based, sleep-free check that no part starts after the failing part, waiting for the real part-upload futures and requiring AccessDenied. - C51: require B2ConnectionError, keep the IndexError as the known defect. - C17: inject the fault into both os.rename and os.replace and check it was reached. - C33: replace the FIXME-text check with an upload test that records real part lengths. - C56: drop the "or fail clearly" alternative; the contract stays "saves twice". - C57: measure peak traced memory during construction. - C4: split the quick-start checks; fix the EncryptionKey and `pip install` patterns. - C10, C35, C1, C11, C15, C44, C48, C36, C37: pin the specific failure. Co-Authored-By: Claude Sonnet 5.5 * test: restore the original C57 memory check The tracemalloc.reset_peak version is not available on PyPy. Co-Authored-By: Claude Sonnet 5.5 * test: keep defect checks precise across interpreters * test: distinguish recommended and minimum upload part sizes * test: drop known_defect from C16 and C46, fixed on master Co-Authored-By: Claude Sonnet 5.5 --------- Co-authored-by: scarreras Co-authored-by: Claude Sonnet 5.5 Co-authored-by: Felipe Fumero --- ...sion-tests-known-defects.infrastructure.md | 1 + test/conftest.py | 8 + test/known_defect.py | 89 ++++ test/static/test_regression_repo_checks.py | 118 +++++ .../account_info/test_regression_sqlite.py | 89 ++++ test/unit/bucket/test_regression_bucket.py | 479 ++++++++++++++++++ test/unit/stream/test_regression_streams.py | 215 ++++++++ .../unit/sync/test_regression_sync_actions.py | 183 +++++++ test/unit/test_regression_misc.py | 134 +++++ test/unit/v_all/test_regression_legacy_api.py | 75 +++ 10 files changed, 1391 insertions(+) create mode 100644 changelog.d/+regression-tests-known-defects.infrastructure.md create mode 100644 test/known_defect.py create mode 100644 test/static/test_regression_repo_checks.py create mode 100644 test/unit/account_info/test_regression_sqlite.py create mode 100644 test/unit/bucket/test_regression_bucket.py create mode 100644 test/unit/stream/test_regression_streams.py create mode 100644 test/unit/sync/test_regression_sync_actions.py create mode 100644 test/unit/test_regression_misc.py create mode 100644 test/unit/v_all/test_regression_legacy_api.py diff --git a/changelog.d/+regression-tests-known-defects.infrastructure.md b/changelog.d/+regression-tests-known-defects.infrastructure.md new file mode 100644 index 000000000..4cffb7e48 --- /dev/null +++ b/changelog.d/+regression-tests-known-defects.infrastructure.md @@ -0,0 +1 @@ +Add regression tests for known defects; tests of defects that are still present are strict expected failures marked `known_defect` (run them with `pytest --runxfail -m known_defect`). diff --git a/test/conftest.py b/test/conftest.py index 489730dd6..cd17e2a42 100644 --- a/test/conftest.py +++ b/test/conftest.py @@ -14,6 +14,14 @@ pytest_plugins = ['b2sdk.v3.testing'] +def pytest_configure(config): + config.addinivalue_line( + 'markers', + 'known_defect: test of a defect that is still present, marked as a strict expected failure ' + '(see test/known_defect.py)', + ) + + @pytest.fixture def bg_executor(): with concurrent.futures.ThreadPoolExecutor() as executor: diff --git a/test/known_defect.py b/test/known_defect.py new file mode 100644 index 000000000..681ae9631 --- /dev/null +++ b/test/known_defect.py @@ -0,0 +1,89 @@ +###################################################################### +# +# File: test/known_defect.py +# +# Copyright 2026 Backblaze Inc. All Rights Reserved. +# +# License https://www.backblaze.com/using_b2_code.html +# +###################################################################### +from __future__ import annotations + +import contextlib +import re + +import pytest + + +class DefectStillPresent(AssertionError): + """ + Raised by :func:`expect` when the behaviour that a ``@known_defect`` test describes is wrong. + + A test that has ordinary prerequisite assertions (setup that must hold whether or not the defect + is fixed) marks itself ``raises=DefectStillPresent`` and checks the defect with :func:`expect`. + A failed prerequisite is then a plain ``AssertionError`` and shows up as a real failure instead + of being swallowed as the expected one. + """ + + +def expect(condition: object, message: str = '') -> None: + """Assert the correct behaviour of a known defect; fails with :class:`DefectStillPresent`.""" + if not condition: + raise DefectStillPresent(message) + + +@contextlib.contextmanager +def defect_raises(exc_type: type[BaseException], match: str | None = None): + """ + Turn the one specific exception that a known defect produces into :class:`DefectStillPresent`. + + An exception of another type, or whose message does not match ``match`` (a regular expression + searched in ``str(exception)``), propagates unchanged and is a real failure of the test. + """ + try: + yield + except exc_type as exc: + if match is not None and not re.search(match, str(exc)): + raise + raise DefectStillPresent(f'{type(exc).__name__}: {exc}') from exc + + +def known_defect( + defect_id: str, + summary: str, + *, + raises: type[BaseException] | tuple[type[BaseException], ...], + condition: bool = True, +): + """ + Mark a test that asserts the correct behaviour of a defect that is still present. + + The test is a strict expected failure (``xfail(strict=True)``), so the default test run stays + green, and the run fails as soon as the defect is fixed ("XPASS(strict)"). When that happens, + delete the ``@known_defect(...)`` line: the test then becomes a normal regression test. + + The tests carry the ``known_defect`` marker, so they can be run (and are reported as real + failures) on demand with one command, for example:: + + pytest --runxfail -m known_defect --api=v3 test/unit test/static + + :param defect_id: identifier of the defect, for example ``'C16'`` + :param summary: one-line description of the defect + :param raises: the exception (or tuple of exceptions) the test raises while the defect is present. + Any other failure, in the test or in its setup, is reported as a real failure. + Use ``AssertionError`` for a test whose only assertion is the defect check, + :class:`DefectStillPresent` when the test also has prerequisite assertions, or + ``pytest.fail.Exception`` when the defect is "DID NOT RAISE" from ``pytest.raises`` + :param condition: when false the defect does not apply (for example to another apiver) and the + test is a normal test + """ + + def decorator(func): + if not condition: + return func + func = pytest.mark.known_defect(func) + return pytest.mark.xfail( + strict=True, raises=raises, reason=f'Known defect {defect_id}: {summary}' + )(func) + + return decorator diff --git a/test/static/test_regression_repo_checks.py b/test/static/test_regression_repo_checks.py new file mode 100644 index 000000000..ff028501b --- /dev/null +++ b/test/static/test_regression_repo_checks.py @@ -0,0 +1,118 @@ +###################################################################### +# +# File: test/static/test_regression_repo_checks.py +# +# Copyright 2026 Backblaze Inc. All Rights Reserved. +# +# License https://www.backblaze.com/using_b2_code.html +# +###################################################################### +"""Static regression checks of repository files (docs, changelog, packaging, sources). + +They read repository files only and are skipped when the repository files are not available. + +Tests marked with ``@known_defect`` describe a defect that is still present: they assert the correct +behaviour and are strict expected failures, so the default run stays green and fails with +"XPASS(strict)" once the defect is fixed (then remove the decorator). To see them fail, run +``pytest --runxfail -m known_defect`` (see ``test/known_defect.py``). The ``C`` identifiers are +short labels that also appear in the test names and decorators. +""" + +from __future__ import annotations + +import re +import subprocess +import sys +import textwrap +from pathlib import Path + +import pytest + +from test.known_defect import DefectStillPresent, expect, known_defect + +ROOT = Path(__file__).resolve().parents[2] + + +def _read(rel: str) -> str: + path = ROOT / rel + if not path.is_file(): + pytest.skip(f'{rel} is not available (not a full repository checkout)') + return path.read_text(encoding='utf-8') + + +@known_defect('C30', 'typo in .github/SUPPORT.md', raises=AssertionError) +def test_c30_support_file_has_no_known_typo(): + """C30: typo 'Issuew' in .github/SUPPORT.md (codespell did not catch it).""" + assert 'Issuew' not in _read('.github/SUPPORT.md'), 'typo is still present' + + +@known_defect('C59', 'the README does not mention the "full" install extra', raises=AssertionError) +def test_c59_readme_mentions_full_extra(): + """C59: README must mention the `full` install extra (tqdm/pydantic support).""" + assert re.search(r'b2sdk\[full\]', _read('README.md')), 'README does not mention b2sdk[full]' + + +# an EncryptionKey(...) call whose arguments contain `id=`; quoted strings are skipped as a whole, +# so a ")" inside the secret does not end the argument list early +ENCRYPTION_KEY_WITH_ID = re.compile(r"""EncryptionKey\((?:[^()'"]|'[^']*'|"[^"]*")*?\bid=""") +# installs the local checkout (`pip install .` or `pip install -e .`), not a package index or a URL +PIP_INSTALL_CHECKOUT = re.compile(r'pip install (?:-e\s+)?\.(?:\[[^\]]*\])?(?=\s|$)') + + +@known_defect('C4', 'the Quick Start uses a class that does not exist', raises=AssertionError) +def test_c4_quick_start_does_not_use_encryption_settings_class(): + """C4: Quick Start must not use the non-existent class EncryptionSettings.""" + assert 'EncryptionSettings(' not in _read( + 'doc/source/quick_start.rst' + ), 'EncryptionSettings does not exist' + + +@known_defect( + 'C4', + 'the Quick Start uses an EncryptionKey argument that does not exist', + raises=AssertionError, +) +def test_c4_quick_start_uses_key_id_argument_of_encryption_key(): + """C4: Quick Start must call EncryptionKey with `key_id=`, which is the argument it has.""" + assert not ENCRYPTION_KEY_WITH_ID.search( + _read('doc/source/quick_start.rst') + ), 'EncryptionKey has no id= argument' + + +@known_defect( + 'C4', + 'the development-version install instructions install from PyPI, not the checkout', + raises=AssertionError, +) +def test_c4_install_doc_development_version_installs_from_checkout(): + """C4: 'Installing a development version' must install the checkout, not PyPI.""" + section = _read('doc/source/install.rst').split('Installing a development version', 1)[1] + assert PIP_INSTALL_CHECKOUT.search(section), 'development-version section installs from PyPI' + + +@known_defect( + 'C36', + 'importing b2sdk fails when the package metadata is not installed', + raises=DefectStillPresent, +) +def test_c36_version_import_works_when_package_metadata_is_missing(tmp_path): + """C36: importing a vendored/uninstalled copy of b2sdk must not fail for missing dist metadata.""" + script = textwrap.dedent( + f""" + import importlib.metadata as m, sys + orig = m.version + def fake(name): + if name == 'b2sdk': + raise m.PackageNotFoundError(name) + return orig(name) + m.version = fake + sys.path.insert(0, {str(ROOT)!r}) + import b2sdk.version + """ + ) + result = subprocess.run( + [sys.executable, '-c', script], capture_output=True, text=True, cwd=tmp_path + ) + # only the missing-metadata error is the defect; any other failure is a real failure + expect('PackageNotFoundError' not in result.stderr, result.stderr[-300:]) + assert result.returncode == 0, result.stderr[-300:] diff --git a/test/unit/account_info/test_regression_sqlite.py b/test/unit/account_info/test_regression_sqlite.py new file mode 100644 index 000000000..eb48454a0 --- /dev/null +++ b/test/unit/account_info/test_regression_sqlite.py @@ -0,0 +1,89 @@ +###################################################################### +# +# File: test/unit/account_info/test_regression_sqlite.py +# +# Copyright 2026 Backblaze Inc. All Rights Reserved. +# +# License https://www.backblaze.com/using_b2_code.html +# +###################################################################### +"""Regression tests for SqliteAccountInfo. + +Tests marked with ``@known_defect`` describe a defect that is still present: they assert the correct +behaviour and are strict expected failures, so the default run stays green and fails with +"XPASS(strict)" once the defect is fixed (then remove the decorator). To see them fail, run +``pytest --runxfail -m known_defect`` (see ``test/known_defect.py``). The ``C`` identifiers are +short labels that also appear in the test names and decorators. +""" + +from __future__ import annotations + +import os +import sqlite3 +import threading + +import pytest +from apiver_deps import ( + B2_ACCOUNT_INFO_ENV_VAR, + XDG_CONFIG_HOME_ENV_VAR, + SqliteAccountInfo, +) + +from test.known_defect import DefectStillPresent, expect, known_defect + +pytestmark = [pytest.mark.apiver(from_ver=2)] + + +@pytest.fixture +def home(monkeypatch, tmp_path): + monkeypatch.setenv('HOME', str(tmp_path)) + monkeypatch.setenv('USERPROFILE', str(tmp_path)) + monkeypatch.delenv(B2_ACCOUNT_INFO_ENV_VAR, raising=False) + monkeypatch.delenv(XDG_CONFIG_HOME_ENV_VAR, raising=False) + return tmp_path + + +class TestProfilePaths: + @known_defect( + 'C47', + 'an existing ~/.b2db-.sqlite is ignored because "~" is not expanded before the existence check', + raises=AssertionError, + ) + def test_c47_existing_legacy_profile_database_is_used_with_xdg(self, home, monkeypatch): + """C47: an existing ~/.b2db-.sqlite must be found even when XDG_CONFIG_HOME is set.""" + monkeypatch.setenv(XDG_CONFIG_HOME_ENV_VAR, str(home / 'xdg')) + legacy = home / '.b2db-foo.sqlite' + legacy.write_bytes(b'') + path = SqliteAccountInfo.get_user_account_info_path(profile='foo') + assert os.path.realpath(path) == os.path.realpath(str(legacy)), f'got {path}' + + +class TestThreadConnections: + @known_defect( + 'C37', + "close() closes only the calling thread's database connection", + raises=DefectStillPresent, + ) + def test_c37_close_closes_connections_of_other_threads(self, tmp_path): + """C37: close() must close the database connections opened by other threads, too.""" + info = SqliteAccountInfo(file_name=str(tmp_path / 'acct.sqlite')) + opened, closed_by_main, result = threading.Event(), threading.Event(), {} + + def worker(): + conn = info._get_connection() # connection of this worker thread + opened.set() + assert closed_by_main.wait(timeout=10), 'main thread did not call close()' + try: + conn.execute('select 1') + result['closed'] = False + except sqlite3.ProgrammingError: # Cannot operate on a closed database + result['closed'] = True + + thread = threading.Thread(target=worker) + thread.start() + assert opened.wait(timeout=10), 'worker thread did not open a connection' + info.close() + closed_by_main.set() + thread.join(timeout=10) + assert 'closed' in result, 'the worker thread did not finish its check' + expect(result['closed'], 'connection of another thread is still open after close()') diff --git a/test/unit/bucket/test_regression_bucket.py b/test/unit/bucket/test_regression_bucket.py new file mode 100644 index 000000000..93400dd97 --- /dev/null +++ b/test/unit/bucket/test_regression_bucket.py @@ -0,0 +1,479 @@ +###################################################################### +# +# File: test/unit/bucket/test_regression_bucket.py +# +# Copyright 2026 Backblaze Inc. All Rights Reserved. +# +# License https://www.backblaze.com/using_b2_code.html +# +###################################################################### +"""Regression tests for Bucket and B2Api behaviour on the RawSimulator. + +Tests marked with ``@known_defect`` describe a defect that is still present: they assert the correct +behaviour and are strict expected failures, so the default run stays green and fails with +"XPASS(strict)" once the defect is fixed (then remove the decorator). To see them fail, run +``pytest --runxfail -m known_defect`` (see ``test/known_defect.py``). The ``C`` identifiers are +short labels that also appear in the test names and decorators. +""" + +from __future__ import annotations + +import concurrent.futures +import datetime +import json +import locale +import threading + +import apiver_deps +import pytest +import requests +import responses +from apiver_deps import ( + B2Api, + B2Http, + B2HttpApiConfig, + B2RawHTTPApi, + Filter, + InMemoryAccountInfo, + InMemoryCache, + RawSimulator, + UploadSourceBytes, +) +from apiver_deps_exception import CopyArgumentsMismatch, NonExistentBucket + +from test.known_defect import DefectStillPresent, defect_raises, expect, known_defect + +from .test_bucket import TestCaseWithBucket + +pytestmark = [pytest.mark.apiver(from_ver=2)] + + +class TestRegressionCopyAndLs(TestCaseWithBucket): + @known_defect( + 'C1', + 'copy() with expires/content_disposition/cache_control but no content_type is refused', + raises=DefectStillPresent, + ) + def test_c1_copy_with_expiry_but_no_content_type(self): + """C1: copy() with expires/headers but no content_type must work (2.13.3 notes).""" + file_id = self.bucket.upload_bytes(b'hello world', 'src.txt').id_ + with defect_raises(CopyArgumentsMismatch, match='content type'): + copied = self.bucket.copy( + file_id, + 'copied.txt', + expires='Thu, 01 Dec 2050 16:00:00 GMT', + content_disposition='attachment', + cache_control='max-age=5', + ) + assert copied.file_info['b2-expires'] == 'Thu, 01 Dec 2050 16:00:00 GMT', copied.file_info + assert copied.file_info['b2-content-disposition'] == 'attachment', copied.file_info + + @known_defect( + 'C5', + 'ls("x") stops at an object named "x" and never lists "x/..."', + condition=apiver_deps.V >= 3, + raises=AssertionError, + ) + def test_c5_ls_path_without_slash_lists_folder_next_to_same_named_file(self): + """C5: ls('x') with an object 'x' and objects 'x/...' must also list 'x/...'.""" + self.bucket.upload_bytes(b'data', 'x') + self.bucket.upload_bytes(b'data', 'x/1.txt') + names = [fv.file_name for fv, _ in self.bucket.ls('x', recursive=True)] + assert 'x/1.txt' in names, names + + @known_defect( + 'C5', + 'B2Folder for a prefix naming a single object hits an AssertionError', + condition=apiver_deps.V >= 3, + raises=AssertionError, + ) + def test_c5_folder_sync_source_with_prefix_naming_a_single_object(self): + """C5: B2Folder for 'b2://bucket/x' must not hit an AssertionError when only 'x' exists.""" + from apiver_deps import B2Folder + + self.bucket.upload_bytes(b'data', 'x') + folder = B2Folder(self.bucket_name, 'x', self.api) + # must not raise AssertionError (it may list nothing or the object, but not crash) + list(folder.all_files(None)) + + @known_defect( + 'C6', + 'ls() of an exact file name ignores the filters', + condition=apiver_deps.V >= 3, + raises=AssertionError, + ) + def test_c6_exact_filename_respects_exclude_filter(self): + """C6: an exclude filter naming the exact file must hide it from ls().""" + self.bucket.upload_bytes(b'hello world', 'b/a.txt') + result = [ + fv.file_name + for fv, _ in self.bucket.ls( + 'b/a.txt', recursive=True, filters=[Filter.exclude('b/a.txt')] + ) + ] + assert result == [], 'the filter was ignored' + + @known_defect( + 'C6', + 'ls() of an exact file name ignores the filters', + condition=apiver_deps.V >= 3, + raises=AssertionError, + ) + def test_c6_exact_filename_respects_include_filter_for_other_name(self): + """C6: an include filter not matching the exact file must hide it from ls().""" + self.bucket.upload_bytes(b'hello world', 'b/a.txt') + result = [ + fv.file_name + for fv, _ in self.bucket.ls( + 'b/a.txt', recursive=True, filters=[Filter.include('b/z.txt')] + ) + ] + assert result == [], 'the filter was ignored' + + +class TestRegressionUploadOptions(TestCaseWithBucket): + @known_defect('C45', 'multipart uploads ignore custom_upload_timestamp', raises=AssertionError) + def test_c45_custom_timestamp_is_kept_on_large_upload(self): + """C45: a custom upload timestamp must be applied to multi-part uploads too.""" + data = self._make_data(self.simulator.MIN_PART_SIZE * 3) + file_version = self.bucket.upload_bytes(data, 'large', custom_upload_timestamp=12345) + assert file_version.upload_timestamp == 12345, file_version.upload_timestamp + + @known_defect('C45', 'multipart uploads ignore custom_upload_timestamp', raises=AssertionError) + def test_c45_custom_timestamp_is_kept_on_large_unfinished_file(self): + """C45: the started large file carries the custom timestamp (visible after the upload).""" + data = self._make_data(self.simulator.MIN_PART_SIZE * 3) + self.bucket.upload_bytes(data, 'large2', custom_upload_timestamp=777) + stored = self.bucket.get_file_info_by_name('large2') + assert stored.upload_timestamp == 777, stored.upload_timestamp + + @known_defect( + 'C33', + 'Bucket.upload passes min_part_size as the recommended part size instead of a lower limit', + raises=DefectStillPresent, + ) + def test_c33_upload_min_part_size_is_only_a_lower_limit(self): + """C33: min_part_size is a lower limit; parts must still follow the recommended part size. + + A min_part_size below what the server accepts must not shrink the parts below it: the + planner has to keep using the account's recommended part size (not the user's minimum), + otherwise the real service refuses the parts. Bucket.upload documents the first and does + the second. + """ + from unittest import mock + + absolute_minimum = self.account_info.get_absolute_minimum_part_size() + recommended_part_size = absolute_minimum * 3 + user_minimum = absolute_minimum // 2 + part_lengths = [] + original = self.simulator.upload_part + + def recording(upload_url, token, part_number, content_length, *args, **kwargs): + part_lengths.append((part_number, content_length)) + return original(upload_url, token, part_number, content_length, *args, **kwargs) + + data = self._make_data(recommended_part_size * 4 + 1) + with mock.patch.object( + self.account_info, 'get_recommended_part_size', return_value=recommended_part_size + ), mock.patch.object(self.simulator, 'upload_part', recording): + self.bucket.upload(UploadSourceBytes(data), 'min-part.bin', min_part_size=user_minimum) + self._check_file_contents('min-part.bin', data) + assert len(part_lengths) > 2, f'the upload was not split into several parts: {part_lengths}' + non_final = [length for _, length in sorted(part_lengths)[:-1]] + assert all(length >= user_minimum for length in non_final), non_final + expect( + all(length >= recommended_part_size for length in non_final), + f'parts below the recommended part size {recommended_part_size}: {non_final}', + ) + + @pytest.mark.skipif( + not hasattr(locale, 'setlocale'), reason='locale support is required for this test' + ) + @known_defect( + 'C32', + 'the "expires" header uses day and month names of the process locale', + raises=AssertionError, + ) + def test_c32_expires_header_uses_english_names_under_foreign_locale(self): + """C32: the 'expires' date must not use process-locale day/month names.""" + old = locale.setlocale(locale.LC_TIME) + for name in ('de_DE.UTF-8', 'de_DE.utf8', 'fr_FR.UTF-8', 'es_ES.UTF-8'): + try: + locale.setlocale(locale.LC_TIME, name) + break + except locale.Error: + continue + else: + pytest.skip('no non-English locale available on this host') + try: + expires = datetime.datetime(2050, 12, 1, 16, 0, tzinfo=datetime.timezone.utc) + file_version = self.bucket.upload_bytes(b'x', 'f.txt', expires=expires) + finally: + locale.setlocale(locale.LC_TIME, old) + assert ( + file_version.file_info['b2-expires'] == 'Thu, 01 Dec 2050 16:00:00 GMT' + ), file_version.file_info + + +class TestRegressionApi: + def _api(self, account_info=None, cache=None): + api = B2Api( + account_info or InMemoryAccountInfo(), + cache=cache if cache is not None else InMemoryCache(), + api_config=B2HttpApiConfig(_raw_api_class=RawSimulator), + ) + account_id, master_key = api.session.raw_api.create_account() + api.authorize_account( + application_key_id=account_id, application_key=master_key, realm='production' + ) + return api, master_key + + @known_defect( + 'C2', + 'delete_bucket does not remove the bucket name from the name cache', + raises=pytest.fail.Exception, + ) + def test_c2_deleted_bucket_not_returned_from_name_cache(self): + """C2: after delete_bucket, a lookup by name must fail, not return the stale ID.""" + api, _ = self._api() + bucket = api.create_bucket('to-delete', 'allPrivate') + assert api.get_bucket_by_name('to-delete').id_ == bucket.id_, 'cache was not warm' + api.delete_bucket(bucket) + with pytest.raises(NonExistentBucket): + api.get_bucket_by_name('to-delete') + + @known_defect( + 'C28', + 'the create_bucket mismatch message prints the same name twice', + raises=AssertionError, + ) + def test_c28_create_bucket_mismatch_message_names_both_buckets(self): + """C28: the assertion message must show requested and returned names, not name twice.""" + from unittest import mock + + api, _ = self._api() + wrong = mock.Mock() + wrong.name = 'returned-other-name' + wrong.type_ = 'allPrivate' + with mock.patch.object( + api.BUCKET_FACTORY_CLASS, 'from_api_bucket_dict', return_value=wrong + ): + with pytest.raises(AssertionError) as exc_info: + api.create_bucket('requested-name', 'allPrivate') + message = str(exc_info.value) + assert 'requested-name' in message, message + assert 'returned-other-name' in message, message + + +class TestRegressionRawApiContract: + @responses.activate + @known_defect( + 'C35', + 'set_notification_rules fails for a generator although it is typed as Iterable', + raises=DefectStillPresent, + ) + def test_c35_set_notification_rules_accepts_a_generator(self): + """C35: set_notification_rules is typed Iterable; a generator must serialize to JSON.""" + raw_api = B2RawHTTPApi( + B2Http(B2HttpApiConfig(requests.Session, install_clock_skew_hook=False)) + ) + responses.add( + responses.POST, + f'https://api.example.com/b2api/{B2RawHTTPApi.API_VERSION}/b2_set_bucket_notification_rules', + json={'eventNotificationRules': []}, + ) + rule = { + 'eventTypes': ['b2:ObjectCreated:*'], + 'isEnabled': True, + 'name': 'r', + 'objectNamePrefix': '', + 'targetConfiguration': { + 'targetType': 'webhook', + 'url': 'https://example.com/hook', + 'customHeaders': [], + }, + } + with defect_raises(TypeError, match='not JSON serializable'): + sent = raw_api.set_bucket_notification_rules( + 'https://api.example.com', 'token', 'bucket-id', (r for r in [rule]) + ) + assert sent == [], sent + body = json.loads(responses.calls[0].request.body) + assert body['eventNotificationRules'] == [rule], body + + +class TestRegressionLargeUploadFailure: + @known_defect( + 'C8', + 'part uploads keep running after one part of a large upload failed', + raises=DefectStillPresent, + ) + def test_c8_failed_part_stops_remaining_part_uploads(self): + """C8: once one part fails the whole upload fails; queued parts must not keep uploading.""" + from unittest import mock + + from apiver_deps_exception import AccessDenied + + api = B2Api( + InMemoryAccountInfo(), + cache=InMemoryCache(), + api_config=B2HttpApiConfig(_raw_api_class=RawSimulator), + max_upload_workers=1, # parts start one at a time, in order + ) + simulator = api.session.raw_api + account_id, master_key = simulator.create_account() + api.authorize_account( + application_key_id=account_id, application_key=master_key, realm='production' + ) + bucket = api.create_bucket('big', 'allPrivate') + original = simulator.upload_part + part_failed = threading.Event() + started_after_failure = [] + + def flaky_upload_part(upload_url, token, part_number, *args, **kwargs): + if part_failed.is_set(): + started_after_failure.append(part_number) + elif part_number == 1: + part_failed.set() # before raising, so that no later start can be missed + raise AccessDenied() + return original(upload_url, token, part_number, *args, **kwargs) + + # collect the futures of the real part uploads, to wait for all of them to finish + pool = api.services.upload_manager._thread_pool + real_submit = pool.submit + futures = [] + + def recording_submit(*args, **kwargs): + future = real_submit(*args, **kwargs) + futures.append(future) + return future + + data = b'x' * (simulator.MIN_PART_SIZE * 6) + with mock.patch.object(simulator, 'upload_part', flaky_upload_part): + with mock.patch.object(pool, 'submit', recording_submit): + with pytest.raises(AccessDenied): + bucket.upload_bytes(data, 'big.bin') + _, pending = concurrent.futures.wait(futures, timeout=30) + + assert part_failed.is_set(), 'part 1 was never uploaded, so no part failed' + assert len(futures) > 1, 'the upload was not split into several parts' + assert not pending, 'part uploads did not finish within the timeout' + expect( + not started_after_failure, + f'parts kept uploading after the failure: {started_after_failure}', + ) + + +class TestRegressionDownloadedFileContract: + @responses.activate + @known_defect( + 'C56', + 'DownloadedFile.save() called twice re-reads a used response', + raises=DefectStillPresent, + ) + def test_c56_downloaded_file_can_be_saved_twice_from_a_real_response(self): + """C56: save() called twice on a real streamed HTTP response must give the full data again; + the simulator's in-memory response hides this. Today the second call raises requests' + StreamConsumedError.""" + import hashlib + import io + from unittest import mock + + from apiver_deps import DownloadedFile, Range, SimpleDownloader + + data = b'0123456789' * 100 + url = 'https://download.example.com/file/bucket/name' + responses.add(responses.GET, url, body=data, content_type='application/octet-stream') + response = requests.get(url, stream=True) + + download_version = mock.MagicMock() + download_version.content_length = len(data) + download_version.content_sha1 = hashlib.sha1(data).hexdigest() + download_version.content_encoding = None + download_version.range_ = Range(0, len(data) - 1) + download_version.api.api_config.decode_content = False + download_manager = mock.MagicMock() + download_manager.strategies = [SimpleDownloader(force_chunk_size=64)] + + downloaded = DownloadedFile(download_version, download_manager, None, response, None, None) + first, second = io.BytesIO(), io.BytesIO() + downloaded.save(first) + assert first.getvalue() == data, 'first save() returned wrong data' + with defect_raises(requests.exceptions.StreamConsumedError): + downloaded.save(second) + assert second.getvalue() == data, 'second save() returned wrong data' + + +class TestRegressionGuards(TestCaseWithBucket): + def test_c43_guard_sse_c_key_is_not_printed_or_logged(self): + """C43: SSE-C key material must not show in repr/str or DEBUG logs of public calls.""" + import logging + + from apiver_deps import ( + EncryptionAlgorithm, + EncryptionKey, + EncryptionMode, + EncryptionSetting, + ) + + secret = b'sse-c-key-material-MUST-NOT-LEAK' + setting = EncryptionSetting( + mode=EncryptionMode.SSE_C, + algorithm=EncryptionAlgorithm.AES256, + key=EncryptionKey(secret=secret, key_id='key-id'), + ) + for text in (repr(setting), str(setting), repr(setting.key), str(setting.key)): + assert secret.decode() not in text, 'key material in printed form' + assert repr(secret) not in text, 'key material in printed form' + + records = [] + + class Collector(logging.Handler): + def emit(self, record): + records.append(record.getMessage()) + + handler = Collector(level=logging.DEBUG) + root = logging.getLogger() + old_level = root.level + root.addHandler(handler) + root.setLevel(logging.DEBUG) + try: + fv = self.bucket.upload_bytes(b'data', 'enc.txt', encryption=setting) + self.bucket.copy( + fv.id_, 'enc-copy.txt', source_encryption=setting, destination_encryption=setting + ) + finally: + root.removeHandler(handler) + root.setLevel(old_level) + joined = '\n'.join(records) + assert records, 'expected DEBUG records to be captured' + assert secret.decode() not in joined, 'key material in DEBUG logs' + assert repr(secret) not in joined, 'key material in DEBUG logs' + + def test_c13_guard_failed_part_upload_retries_with_a_fresh_upload_url(self): + """C13: after a retryable part failure the retry must not reuse the failed URL/token.""" + from unittest import mock + + from .test_bucket import CanRetry + + failing_part = 2 + attempts = [] + original = self.simulator.upload_part + + def recording(upload_url, token, part_number, *args, **kwargs): + attempts.append((part_number, upload_url, token)) + first_attempt = [a for a in attempts if a[0] == failing_part] == [attempts[-1]] + if part_number == failing_part and first_attempt: + raise CanRetry(True) # RawSimulator only consumes set_upload_errors() for files + return original(upload_url, token, part_number, *args, **kwargs) + + data = self._make_data(self.simulator.MIN_PART_SIZE * 3) + with mock.patch.object(self.simulator, 'upload_part', recording): + self.bucket.upload_bytes(data, 'large.bin') + self._check_file_contents('large.bin', data) + + tried = [ + (url, token) for part_number, url, token in attempts if part_number == failing_part + ] + assert len(tried) >= 2, f'part {failing_part} was not retried: {tried}' + assert tried[1] != tried[0], f'part {failing_part} retried with the failed URL/token' diff --git a/test/unit/stream/test_regression_streams.py b/test/unit/stream/test_regression_streams.py new file mode 100644 index 000000000..51979a312 --- /dev/null +++ b/test/unit/stream/test_regression_streams.py @@ -0,0 +1,215 @@ +###################################################################### +# +# File: test/unit/stream/test_regression_streams.py +# +# Copyright 2026 Backblaze Inc. All Rights Reserved. +# +# License https://www.backblaze.com/using_b2_code.html +# +###################################################################### +"""Regression tests for stream and upload-source classes. + +Tests marked with ``@known_defect`` describe a defect that is still present: they assert the correct +behaviour and are strict expected failures, so the default run stays green and fails with +"XPASS(strict)" once the defect is fixed (then remove the decorator). To see them fail, run +``pytest --runxfail -m known_defect`` (see ``test/known_defect.py``). The ``C`` identifiers are +short labels that also appear in the test names and decorators. +""" + +from __future__ import annotations + +import hashlib +import io + +import pytest + +from b2sdk._internal.stream.chained import ChainedStream +from b2sdk._internal.stream.range import RangeOfInputStream +from b2sdk._internal.transfer.outbound.upload_source import ( + UploadSourceLocalFileRange, + UploadSourceStream, + UploadSourceStreamRange, +) +from b2sdk._internal.utils import hex_sha1_of_unlimited_stream +from test.known_defect import DefectStillPresent, defect_raises, expect, known_defect + + +class ShortReadStream(io.RawIOBase): + """A pipe-like stream that never returns more than `chunk` bytes per read, before the real end.""" + + def __init__(self, data: bytes, chunk: int): + self._buf = io.BytesIO(data) + self._chunk = chunk + + def readable(self): + return True + + def read(self, size=-1): + if size is None or size < 0 or size > self._chunk: + size = self._chunk + return self._buf.read(size) + + +class ClosableTracker(io.BytesIO): + def close(self): + self.was_closed = True + super().close() + + +class TestHashingShortReads: + @pytest.mark.parametrize('chunk', [1, 7, 100]) + def test_c16_hash_and_length_cover_whole_stream_with_short_reads(self, chunk): + """C16: a source returning fewer bytes than asked must not truncate hash/length.""" + data = bytes(range(256)) * 20 + sha1, length = hex_sha1_of_unlimited_stream(ShortReadStream(data, chunk)) + assert length == len(data), f'length {length} != {len(data)}' + assert sha1 == hashlib.sha1(data).hexdigest(), 'SHA1 does not cover the whole stream' + + def test_c16_upload_source_stream_reports_full_length_with_short_reads(self): + """C16: UploadSourceStream computing length/sha1 from a pipe-like stream.""" + data = b'x' * 5000 + source = UploadSourceStream(lambda: ShortReadStream(data, 13)) + assert source.get_content_length() == len(data), 'length does not cover the whole stream' + assert ( + source.get_content_sha1() == hashlib.sha1(data).hexdigest() + ), 'SHA1 does not cover the whole stream' + + +class TestRangeOfInputStream: + def test_c46_read_minus_one_does_not_go_past_range_end(self): + """C46: read(-1) must be limited to the range, like read() is.""" + stream = RangeOfInputStream(io.BytesIO(b'0123456789'), offset=2, length=3) + assert stream.read(-1) == b'234', 'read(-1) went past the end of the range' + + def test_c46_read_none_stays_within_range(self): + """Control for C46: read(None) is limited to the range (passes today).""" + stream = RangeOfInputStream(io.BytesIO(b'0123456789'), offset=2, length=3) + assert stream.read() == b'234', 'read() went past the end of the range' + + +class TestChainedStream: + @known_defect( + 'C11', + 'ChainedStream.read() with the default size raises TypeError instead of reading everything', + raises=DefectStillPresent, + ) + def test_c11_default_read_returns_everything(self): + """C11: read() with default size reads everything (docs), not a TypeError.""" + stream = ChainedStream([lambda: io.BytesIO(b'abc'), lambda: io.BytesIO(b'def')]) + with defect_raises(TypeError, match="'<' not supported between instances of 'NoneType'"): + data = stream.read() + assert data == b'abcdef', 'read() did not return all data' + + @known_defect( + 'C11', + 'ChainedStream.read(None) raises TypeError instead of reading everything', + raises=DefectStillPresent, + ) + def test_c11_explicit_none_returns_everything(self): + """C11: read(None) is documented as 'read everything'.""" + stream = ChainedStream([lambda: io.BytesIO(b'abc'), lambda: io.BytesIO(b'def')]) + with defect_raises(TypeError, match="'<' not supported between instances of 'NoneType'"): + data = stream.read(None) + assert data == b'abcdef', 'read(None) did not return all data' + + def test_c12_guard_sized_reads_cross_stream_boundaries(self): + """C12: guard that sized reads span the chained streams and end at EOF.""" + stream = ChainedStream([lambda: io.BytesIO(b'abc'), lambda: io.BytesIO(b'def')]) + assert stream.read(4) == b'abcd', 'sized read did not cross the stream boundary' + assert stream.read(10) == b'ef', 'second sized read returned wrong data' + assert stream.read(10) == b'', 'read at EOF did not return empty bytes' + + +class TestUploadSourceStreamRange: + @known_defect( + 'C15', + 'UploadSourceStreamRange built without a length fails on the first read', + raises=DefectStillPresent, + ) + def test_c15_stream_range_without_length_can_be_read(self): + """C15: docs allow omitting the stream length; open() then read must work.""" + data = b'0123456789' + source = UploadSourceStreamRange(lambda: io.BytesIO(data), offset=4) + with defect_raises(TypeError, match="unsupported operand type.*'NoneType'"): + with source.open() as fp: + content = fp.read() + assert content == data[4:], 'wrong data read from the stream range' + + @known_defect( + 'C15', + 'UploadSourceStreamRange built without a length cannot report its length', + raises=DefectStillPresent, + ) + def test_c15_stream_range_without_length_computes_length(self): + """C15: length is computed lazily when not given.""" + source = UploadSourceStreamRange(lambda: io.BytesIO(b'0123456789'), offset=0) + with defect_raises(TypeError, match="unsupported operand type.*'NoneType'"): + length = source.get_content_length() + assert length == 10, 'wrong computed length' + + @known_defect( + 'C14', + 'UploadSourceStream does not close the stream it opened to compute the checksum', + raises=DefectStillPresent, + ) + def test_c14_stream_is_closed_after_checksum_computation(self): + """C14: computing the checksum must close the stream it opened.""" + opened = [] + + def opener(): + s = ClosableTracker(b'hello world') + s.was_closed = False + opened.append(s) + return s + + UploadSourceStream(opener).get_content_sha1() + assert opened, 'the source never opened a stream' + expect(all(s.was_closed for s in opened), 'a stream opened for the checksum was left open') + + +class TestUploadSourceLocalFileRange: + @pytest.mark.parametrize('offset', [-3, 15]) + @known_defect( + 'C52', + 'UploadSourceLocalFileRange accepts a negative offset or an offset past the end of the file', + raises=pytest.fail.Exception, + ) + def test_c52_invalid_offset_is_rejected(self, tmp_path, offset): + """C52: negative offset or offset past end (file is 10 bytes) must be refused.""" + path = tmp_path / 'f.bin' + path.write_bytes(b'0123456789') + with pytest.raises(ValueError): + UploadSourceLocalFileRange(str(path), offset=offset) + + +class TestUnboundWriteIntentMemory: + @known_defect( + 'C57', + 'UnboundSourceBytes copies the chunk, using about twice the documented memory', + raises=DefectStillPresent, + ) + def test_c57_unbound_buffer_wrapping_does_not_copy_the_chunk(self): + """C57: wrapping a bytearray chunk for upload must not allocate a second full copy.""" + tracemalloc = pytest.importorskip( + 'tracemalloc', + reason='allocation measurements require tracemalloc (unavailable on PyPy)', + exc_type=ModuleNotFoundError, + ) + + from b2sdk._internal.transfer.emerge.unbound_write_intent import UnboundSourceBytes + + size = 8 * 1024 * 1024 + chunk = bytearray(size) + already_tracing = tracemalloc.is_tracing() + if not already_tracing: + tracemalloc.start() + try: + before = tracemalloc.get_traced_memory()[0] + tracemalloc.reset_peak() + source = UnboundSourceBytes(chunk, lambda: None) + extra = tracemalloc.get_traced_memory()[1] - before + finally: + if not already_tracing: + tracemalloc.stop() + assert source.get_content_length() == size, 'wrong content length' + expect(extra < size // 2, f'wrapping allocated {extra} extra bytes for a {size} byte chunk') diff --git a/test/unit/sync/test_regression_sync_actions.py b/test/unit/sync/test_regression_sync_actions.py new file mode 100644 index 000000000..e506ff0c2 --- /dev/null +++ b/test/unit/sync/test_regression_sync_actions.py @@ -0,0 +1,183 @@ +###################################################################### +# +# File: test/unit/sync/test_regression_sync_actions.py +# +# Copyright 2026 Backblaze Inc. All Rights Reserved. +# +# License https://www.backblaze.com/using_b2_code.html +# +###################################################################### +"""Regression tests for sync actions and downloads to local files. + +Tests marked with ``@known_defect`` describe a defect that is still present: they assert the correct +behaviour and are strict expected failures, so the default run stays green and fails with +"XPASS(strict)" once the defect is fixed (then remove the decorator). To see them fail, run +``pytest --runxfail -m known_defect`` (see ``test/known_defect.py``). The ``C`` identifiers are +short labels that also appear in the test names and decorators. +""" + +from __future__ import annotations + +import os +from unittest import mock + +import pytest +from apiver_deps import ( + B2Api, + B2HttpApiConfig, + InMemoryAccountInfo, + InMemoryCache, + RawSimulator, + ServerDefaultSyncEncryptionSettingsProvider, +) +from apiver_deps_exception import ChecksumMismatch, TruncatedOutput + +from b2sdk._internal.scan.path import B2Path +from b2sdk._internal.sync.action import B2CopyAction, B2DownloadAction +from test.known_defect import DefectStillPresent, expect, known_defect + +pytestmark = [pytest.mark.apiver(from_ver=2)] + +REMOTE_MTIME_MILLIS = 1_000_000_000_000 # 2001-09-09 + + +@pytest.fixture +def api_and_bucket(): + api = B2Api( + InMemoryAccountInfo(), + cache=InMemoryCache(), + api_config=B2HttpApiConfig(_raw_api_class=RawSimulator), + ) + account_id, key = api.session.raw_api.create_account() + api.authorize_account(application_key_id=account_id, application_key=key, realm='production') + return api, api.create_bucket('sync-bucket', 'allPublic') + + +def _download_action(bucket, file_version, local_path): + path = B2Path(file_version.file_name, file_version, [file_version]) + return B2DownloadAction( + path, + file_version.file_name, + str(local_path), + ServerDefaultSyncEncryptionSettingsProvider(), + ) + + +def _corrupt_stored_sha1(api, bucket, file_version): + sim_bucket = api.session.raw_api.bucket_id_to_bucket[bucket.id_] + sim_bucket.file_id_to_file[file_version.id_].content_sha1 = 'f' * 40 + + +class TestDownloadedFileModTime: + @known_defect( + 'C3', + 'a download that fails its checksum check still gets the remote modification time', + raises=AssertionError, + ) + def test_c3_failed_checksum_does_not_stamp_remote_mtime(self, api_and_bucket, tmp_path): + """C3: a download that fails validation must not leave a file that looks current.""" + api, bucket = api_and_bucket + fv = bucket.upload_bytes( + b'hello world', + 'f.txt', + file_info={'src_last_modified_millis': str(REMOTE_MTIME_MILLIS)}, + ) + _corrupt_stored_sha1(api, bucket, fv) + target = tmp_path / 'out.txt' + with pytest.raises((ChecksumMismatch, TruncatedOutput)): + bucket.download_file_by_id(fv.id_).save_to(target) + # either the file is gone, or it does not carry the remote mod time + if target.exists(): + assert ( + int(target.stat().st_mtime * 1000) != REMOTE_MTIME_MILLIS + ), 'the remote modification time was set on a file that failed validation' + + +class TestSyncDownloadAction: + @known_defect( + 'C3', 'a failed sync download leaves the temporary file behind', raises=DefectStillPresent + ) + def test_c3_failed_download_leaves_no_temp_file(self, api_and_bucket, tmp_path): + """C3: after a failed sync download the .b2.sync.tmp file must not be left behind.""" + api, bucket = api_and_bucket + fv = bucket.upload_bytes(b'hello world', 'f.txt') + _corrupt_stored_sha1(api, bucket, fv) + action = _download_action(bucket, fv, tmp_path / 'f.txt') + with pytest.raises((ChecksumMismatch, TruncatedOutput)): + action.do_action(bucket, None) + assert not (tmp_path / 'f.txt').exists(), 'final file was created' + expect(not (tmp_path / 'f.txt.b2.sync.tmp').exists(), 'temporary file left behind') + + @known_defect( + 'C17', + 'sync download deletes the old local file before renaming the new one into place', + raises=DefectStillPresent, + ) + def test_c17_failed_replacement_keeps_previous_local_copy(self, api_and_bucket, tmp_path): + """C17: if moving the new file into place fails, the old local file must still exist. + + The fault is injected into both os.rename and os.replace, so the test does not depend on + which of them the implementation uses to move the file into place. + """ + api, bucket = api_and_bucket + fv = bucket.upload_bytes(b'new content', 'f.txt') + local = tmp_path / 'f.txt' + local.write_bytes(b'old content') + action = _download_action(bucket, fv, local) + injected = [] + + def fail(*args, **kwargs): + injected.append(args) + raise OSError('simulated replacement failure') + + with mock.patch('os.rename', side_effect=fail), mock.patch('os.replace', side_effect=fail): + with pytest.raises(OSError, match='simulated replacement failure'): + action.do_action(bucket, None) + assert injected, 'the download never tried to move the new file into place' + expect(local.exists(), 'the previous local copy was removed') + expect(local.read_bytes() == b'old content', 'the previous local copy was changed') + + def test_c17_guard_successful_download_replaces_file(self, api_and_bucket, tmp_path): + """Guard for C17: a normal sync download replaces the local file and leaves no temp file.""" + api, bucket = api_and_bucket + fv = bucket.upload_bytes(b'new content', 'f.txt') + local = tmp_path / 'f.txt' + local.write_bytes(b'old content') + _download_action(bucket, fv, local).do_action(bucket, None) + assert local.read_bytes() == b'new content', 'the download did not replace the file' + assert not os.path.exists(str(local) + '.b2.sync.tmp'), 'temporary file left behind' + + +class TestSyncMessages: + NAME = 'dir/evil\x1b[31mname' + + def _path(self): + return B2Path(self.NAME, mock.Mock(), []) + + @known_defect( + 'C24', + 'the sync download message prints remote names without escaping control characters', + raises=AssertionError, + ) + def test_c24_download_message_escapes_control_characters(self): + """C24: remote names with control chars must be escaped in output.""" + action = B2DownloadAction(self._path(), self.NAME, 'out/x', mock.Mock()) + reporter = mock.Mock() + action.do_report(mock.Mock(), reporter) + printed = reporter.print_completion.call_args[0][0] + assert '\x1b' not in printed, repr(printed) + + @known_defect( + 'C24', + 'the sync copy message prints remote names without escaping control characters', + raises=AssertionError, + ) + def test_c24_copy_message_escapes_control_characters(self): + """C24: same for copy actions.""" + action = B2CopyAction( + self.NAME, self._path(), 'dest', mock.Mock(), mock.Mock(), mock.Mock() + ) + reporter = mock.Mock() + action.do_report(mock.Mock(), reporter) + printed = reporter.print_completion.call_args[0][0] + assert '\x1b' not in printed, repr(printed) diff --git a/test/unit/test_regression_misc.py b/test/unit/test_regression_misc.py new file mode 100644 index 000000000..eb38bf25e --- /dev/null +++ b/test/unit/test_regression_misc.py @@ -0,0 +1,134 @@ +###################################################################### +# +# File: test/unit/test_regression_misc.py +# +# Copyright 2026 Backblaze Inc. All Rights Reserved. +# +# License https://www.backblaze.com/using_b2_code.html +# +###################################################################### +"""Regression tests for validation helpers, folder scanning, the HTTP layer and types. + +Tests marked with ``@known_defect`` describe a defect that is still present: they assert the correct +behaviour and are strict expected failures, so the default run stays green and fails with +"XPASS(strict)" once the defect is fixed (then remove the decorator). To see them fail, run +``pytest --runxfail -m known_defect`` (see ``test/known_defect.py``). The ``C`` identifiers are +short labels that also appear in the test names and decorators. +""" + +from __future__ import annotations + +import importlib +import os +import sys +from unittest import mock + +import pytest +import requests +import responses +from apiver_deps import B2Http, B2HttpApiConfig +from apiver_deps_exception import B2ConnectionError, B2RequestTimeout + +from b2sdk._internal.scan.folder import LocalFolder +from b2sdk._internal.scan.policies import DEFAULT_SCAN_MANAGER +from test.known_defect import DefectStillPresent, defect_raises, expect, known_defect + +pytestmark = [pytest.mark.apiver(from_ver=2)] + +URL = 'https://example.com/b2api/v4/test' + + +def _b2_http(): + return B2Http(B2HttpApiConfig(requests.Session, install_clock_skew_hook=False)) + + +@pytest.mark.skipif(sys.platform == 'win32', reason='needs symlinks') +class TestLocalFolderSymlinks: + @known_defect( + 'C53', + 'the symlink loop check compares only inode numbers, not devices', + raises=AssertionError, + ) + def test_c53_symlinks_to_different_devices_with_same_inode_are_not_loops(self, tmp_path): + """C53: links to directories on another device that share an inode number are not loops.""" + t1, t2 = tmp_path / 't1', tmp_path / 't2' + t1.mkdir() + t2.mkdir() + (t1 / 'f1.txt').write_text('1') + (t2 / 'f2.txt').write_text('2') + root = tmp_path / 'root' + root.mkdir() + os.symlink(t1, root / 'l1') + os.symlink( + t2, t1 / 'l2' + ) # nested link: the loop check only tracks links on the current path + + real_stat = type(t1).stat + + def fake_stat(self, *args, **kwargs): + st = real_stat(self, *args, **kwargs) + if self.name == 't2': # pretend t2 lives on another device but has t1's inode number + t1_st = real_stat(t1) + values = list(st) + values[1] = t1_st.st_ino + values[2] = t1_st.st_dev + 1 + return os.stat_result(values) + return st + + with mock.patch.object(type(t1), 'stat', fake_stat): + names = sorted( + p.relative_path + for p in LocalFolder(str(root)).all_files(None, DEFAULT_SCAN_MANAGER) + ) + assert names == ['l1/f1.txt', 'l1/l2/f2.txt'] + + +class TestTypes: + @known_defect( + 'C31', + 'the pydantic version is compared as text, so "10.0" counts as older than "2"', + raises=AssertionError, + ) + def test_c31_pydantic_version_ten_counts_as_v2_or_newer(self, monkeypatch): + """C31: pydantic version comparison must be numeric ('10.0' is newer than '2').""" + pydantic = pytest.importorskip('pydantic') + types_module = importlib.import_module('b2sdk._internal.types') + monkeypatch.setattr(pydantic, '__version__', '10.0.0') + try: + importlib.reload(types_module) + detected = types_module.pydantic + finally: + monkeypatch.undo() + importlib.reload(types_module) + assert detected is not None, 'pydantic was not detected' + + +class TestHttpLayer: + @responses.activate + @known_defect( + 'C10', 'calls that create things are re-sent after a timeout', raises=DefectStillPresent + ) + def test_c10_create_style_post_is_not_blindly_resent_after_timeout(self): + """C10: a POST that creates something (b2_create_bucket) must not be re-sent after a timeout.""" + url = 'https://example.com/b2api/v4/b2_create_bucket' + responses.add(responses.POST, url, body=requests.exceptions.ReadTimeout('timed out')) + http = _b2_http() + with mock.patch('time.sleep'): + with pytest.raises(B2RequestTimeout): + http.post_json_return_json(url, {}, {'bucketName': 'b'}) + expect(len(responses.calls) == 1, f'request was sent {len(responses.calls)} times') + + @pytest.mark.parametrize('args', [()]) + @known_defect( + 'C51', + 'error mapping raises IndexError for a ConnectionError with no arguments', + raises=DefectStillPresent, + ) + def test_c51_connection_error_with_missing_args_is_mapped_without_indexerror(self, args): + """C51: ConnectionError carrying fewer than 2 args must map to a B2 error, not IndexError.""" + from b2sdk._internal.b2http import B2Http as InternalB2Http + + error = requests.ConnectionError(*args) + with defect_raises(IndexError, match='tuple index out of range'): + with pytest.raises(B2ConnectionError): + InternalB2Http._translate_errors(lambda: (_ for _ in ()).throw(error)) diff --git a/test/unit/v_all/test_regression_legacy_api.py b/test/unit/v_all/test_regression_legacy_api.py new file mode 100644 index 000000000..7330df40d --- /dev/null +++ b/test/unit/v_all/test_regression_legacy_api.py @@ -0,0 +1,75 @@ +###################################################################### +# +# File: test/unit/v_all/test_regression_legacy_api.py +# +# Copyright 2026 Backblaze Inc. All Rights Reserved. +# +# License https://www.backblaze.com/using_b2_code.html +# +###################################################################### +"""Regression tests for the legacy v0/v1 interfaces. + +Tests marked with ``@known_defect`` describe a defect that is still present: they assert the correct +behaviour and are strict expected failures, so the default run stays green and fails with +"XPASS(strict)" once the defect is fixed (then remove the decorator). To see them fail, run +``pytest --runxfail -m known_defect`` (see ``test/known_defect.py``). The ``C`` identifiers are +short labels that also appear in the test names and decorators. +""" + +from __future__ import annotations + +import apiver_deps +import pytest +from apiver_deps import B2Api, RawSimulator, StubAccountInfo + +from test.known_defect import DefectStillPresent, defect_raises, known_defect + +if apiver_deps.V <= 1: + from apiver_deps import DownloadDestBytes +else: + DownloadDestBytes = None # not present in v2+; tests are skipped there + +pytestmark = [pytest.mark.apiver(to_ver=1)] + + +@pytest.fixture +def bucket(): + simulator = RawSimulator() + api = B2Api(StubAccountInfo(), raw_api=simulator) + account_id, master_key = simulator.create_account() + api.authorize_account('production', account_id, master_key) + return api.create_bucket('my-bucket', 'allPublic') + + +@pytest.mark.apiver(0) +@known_defect('C48', 'v0 unhide_file() raises TypeError', raises=DefectStillPresent) +def test_c48_v0_unhide_file_removes_hide_marker(bucket): + """C48: on the v0 interface unhide_file() must not fail with a TypeError.""" + bucket.upload_bytes(b'hello', 'hello.txt') + bucket.hide_file('hello.txt') + # CPython names the first invalid keyword; PyPy reports both invalid keywords. + with defect_raises( + TypeError, + match=( + r"^Bucket\.list_file_versions\(\) got (?:an unexpected keyword argument 'file_name'" + r'|2 unexpected keyword arguments)$' + ), + ): + bucket.unhide_file('hello.txt') + names = [info.file_name for info, _ in bucket.ls(show_versions=False)] + assert 'hello.txt' in names, names + + +@known_defect( + 'C44', + 'v0/v1 clients cannot download a file stored with a Content-Encoding', + raises=DefectStillPresent, +) +def test_c44_legacy_api_can_download_file_stored_with_content_encoding(bucket): + """C44: v0/v1 clients must be able to download a file that has a Content-Encoding.""" + data = b'compressed-looking payload' + bucket.upload_bytes(data, 'enc.bin', file_infos={'b2-content-encoding': 'gzip'}) + dest = DownloadDestBytes() + with defect_raises(AttributeError, match="no attribute 'api_config'"): + bucket.download_file_by_name('enc.bin', dest) + assert dest.get_bytes_written() == data, 'wrong downloaded data' From dba278f86efdf30ed4944e542f65d7d213cc45cc Mon Sep 17 00:00:00 2001 From: Felipe Fumero Date: Fri, 20 Nov 2026 12:53:48 -0600 Subject: [PATCH 024/113] fix: refresh pooled upload URLs when the authorization key changes (#680) Pooled upload URLs (and their upload tokens) are now invalidated when the account authorization key changes, including while uploads or upload-URL requests are in progress, across both the in-memory and SQLite backends. Each pool carries a generation that advances on every authorization change. Acquisition and return are checked against the current generation, so a URL obtained under a previous key is dropped rather than reused or returned into a freshly refreshed pool. Account cleanup is serialized with the pools so a late return cannot repopulate a reset pool. Network calls remain outside the lock. --- b2sdk/_internal/account_info/abstract.py | 27 + b2sdk/_internal/account_info/in_memory.py | 23 +- .../account_info/sqlite_account_info.py | 13 +- .../_internal/account_info/upload_url_pool.py | 40 +- b2sdk/_internal/session.py | 83 ++- .../+reauthorization-upload-pools.fixed.md | 1 + .../test_reauth_drops_pooled_urls.py | 547 ++++++++++++++++++ 7 files changed, 681 insertions(+), 53 deletions(-) create mode 100644 changelog.d/+reauthorization-upload-pools.fixed.md create mode 100644 test/unit/account_info/test_reauth_drops_pooled_urls.py diff --git a/b2sdk/_internal/account_info/abstract.py b/b2sdk/_internal/account_info/abstract.py index 7b1f3a7ad..d113536f2 100644 --- a/b2sdk/_internal/account_info/abstract.py +++ b/b2sdk/_internal/account_info/abstract.py @@ -10,6 +10,7 @@ from __future__ import annotations from abc import abstractmethod +from contextlib import contextmanager from b2sdk._internal.account_info import exception from b2sdk._internal.raw_api import ALL_CAPABILITIES @@ -379,6 +380,32 @@ def take_bucket_upload_url(self, bucket_id): :rtype: tuple """ + @contextmanager + def _upload_pool_context(self): + """Custom backends without generations retain their existing pool behavior.""" + yield None + + def _get_upload_pool_generation(self): + with self._upload_pool_context() as generation: + return generation + + def _take_upload_url_tagged(self, resource_id, generation=None, *, large_file=False): + with self._upload_pool_context() as current_generation: + # Reauthorization can occur after the caller's initial snapshot. + if generation != current_generation: + generation = current_generation + take = self.take_large_file_upload_url if large_file else self.take_bucket_upload_url + upload_url, upload_auth_token = take(resource_id) + return upload_url, upload_auth_token, generation + + def _put_upload_url_tagged( + self, resource_id, upload_url, upload_auth_token, generation, *, large_file=False + ): + with self._upload_pool_context() as current_generation: + if generation == current_generation: + put = self.put_large_file_upload_url if large_file else self.put_bucket_upload_url + put(resource_id, upload_url, upload_auth_token) + @abstractmethod @limit_trace_arguments(only=['self', 'bucket_id']) def put_bucket_upload_url(self, bucket_id, upload_url, upload_auth_token): diff --git a/b2sdk/_internal/account_info/in_memory.py b/b2sdk/_internal/account_info/in_memory.py index 737a56fac..d42e481d2 100644 --- a/b2sdk/_internal/account_info/in_memory.py +++ b/b2sdk/_internal/account_info/in_memory.py @@ -73,17 +73,18 @@ def _set_auth_data( allowed, application_key_id, ): - self._account_id = account_id - self._application_key_id = application_key_id - self._auth_token = auth_token - self._api_url = api_url - self._download_url = download_url - self._absolute_minimum_part_size = absolute_minimum_part_size - self._recommended_part_size = recommended_part_size - self._application_key = application_key - self._realm = realm - self._s3_api_url = s3_api_url - self._allowed = allowed + with self._auth_data_change(application_key_id, realm): + self._account_id = account_id + self._application_key_id = application_key_id + self._auth_token = auth_token + self._api_url = api_url + self._download_url = download_url + self._absolute_minimum_part_size = absolute_minimum_part_size + self._recommended_part_size = recommended_part_size + self._application_key = application_key + self._realm = realm + self._s3_api_url = s3_api_url + self._allowed = allowed def refresh_entire_bucket_name_cache(self, name_id_iterable): self._buckets = dict(name_id_iterable) diff --git a/b2sdk/_internal/account_info/sqlite_account_info.py b/b2sdk/_internal/account_info/sqlite_account_info.py index 1ee7e5a6f..c618dcd9f 100644 --- a/b2sdk/_internal/account_info/sqlite_account_info.py +++ b/b2sdk/_internal/account_info/sqlite_account_info.py @@ -479,11 +479,12 @@ def clear(self): """ Remove all info about accounts and buckets. """ - self._reset_upload_pools() - with self._get_connection() as conn: - conn.execute('DELETE FROM account;') - conn.execute('DELETE FROM bucket;') - conn.execute('DELETE FROM bucket_upload_url;') + with self._auth_data_lock: + self._reset_upload_pools() + with self._get_connection() as conn: + conn.execute('DELETE FROM account;') + conn.execute('DELETE FROM bucket;') + conn.execute('DELETE FROM bucket_upload_url;') def _set_auth_data( self, @@ -499,7 +500,7 @@ def _set_auth_data( allowed, application_key_id, ): - with self._get_connection() as conn: + with self._auth_data_change(application_key_id, realm), self._get_connection() as conn: conn.execute('DELETE FROM account;') conn.execute('DELETE FROM bucket;') conn.execute('DELETE FROM bucket_upload_url;') diff --git a/b2sdk/_internal/account_info/upload_url_pool.py b/b2sdk/_internal/account_info/upload_url_pool.py index e96b38bbe..d75225c50 100644 --- a/b2sdk/_internal/account_info/upload_url_pool.py +++ b/b2sdk/_internal/account_info/upload_url_pool.py @@ -12,6 +12,7 @@ import collections import threading from abc import abstractmethod +from contextlib import contextmanager from .abstract import AbstractAccountInfo @@ -82,6 +83,8 @@ class UrlPoolAccountInfo(AbstractAccountInfo): def __init__(self): super().__init__() + self._auth_data_lock = threading.RLock() + self._upload_pool_generation = 0 self._reset_upload_pools() @abstractmethod @@ -90,25 +93,46 @@ def clear(self): return super().clear() def _reset_upload_pools(self): - self._bucket_uploads = self.BUCKET_UPLOAD_POOL_CLASS() - self._large_file_uploads = self.LARGE_FILE_UPLOAD_POOL_CLASS() + with self._auth_data_lock: + self._upload_pool_generation += 1 + self._bucket_uploads = self.BUCKET_UPLOAD_POOL_CLASS() + self._large_file_uploads = self.LARGE_FILE_UPLOAD_POOL_CLASS() + + @contextmanager + def _auth_data_change(self, application_key_id, realm): + with self._auth_data_lock: + changed = not self.is_same_key(application_key_id, realm) + yield + if changed: + self._reset_upload_pools() + + @contextmanager + def _upload_pool_context(self): + with self._auth_data_lock: + yield self._upload_pool_generation # bucket upload url def put_bucket_upload_url(self, bucket_id, upload_url, upload_auth_token): - self._bucket_uploads.put(bucket_id, upload_url, upload_auth_token) + with self._auth_data_lock: + self._bucket_uploads.put(bucket_id, upload_url, upload_auth_token) def clear_bucket_upload_data(self, bucket_id): - self._bucket_uploads.clear_for_key(bucket_id) + with self._auth_data_lock: + self._bucket_uploads.clear_for_key(bucket_id) def take_bucket_upload_url(self, bucket_id): - return self._bucket_uploads.take(bucket_id) + with self._auth_data_lock: + return self._bucket_uploads.take(bucket_id) # large file upload url def put_large_file_upload_url(self, file_id, upload_url, upload_auth_token): - self._large_file_uploads.put(file_id, upload_url, upload_auth_token) + with self._auth_data_lock: + self._large_file_uploads.put(file_id, upload_url, upload_auth_token) def take_large_file_upload_url(self, file_id): - return self._large_file_uploads.take(file_id) + with self._auth_data_lock: + return self._large_file_uploads.take(file_id) def clear_large_file_upload_urls(self, file_id): - self._large_file_uploads.clear_for_key(file_id) + with self._auth_data_lock: + self._large_file_uploads.clear_for_key(file_id) diff --git a/b2sdk/_internal/session.py b/b2sdk/_internal/session.py index 589c0cffb..31f5461b0 100644 --- a/b2sdk/_internal/session.py +++ b/b2sdk/_internal/session.py @@ -10,6 +10,7 @@ from __future__ import annotations import logging +from contextvars import ContextVar from enum import Enum, unique from functools import partial from typing import Any @@ -28,6 +29,8 @@ logger = logging.getLogger(__name__) +_upload_url_request = ContextVar('upload_url_request', default=None) + @unique class TokenType(Enum): @@ -473,8 +476,16 @@ def _wrap_token(self, raw_api_method, token_type, *args, **kwargs): return self._execute_with_auth_retry(partial_callback) def _api_token_callback(self, raw_api_method, *args, **kwargs): - api_url = self.account_info.get_api_url() - account_auth_token = self.account_info.get_account_auth_token() + request = _upload_url_request.get() + if request is not None and request['method'] == raw_api_method: + # Snapshot the generation with the credentials, never across network I/O. + with self.account_info._upload_pool_context() as generation: + api_url = self.account_info.get_api_url() + account_auth_token = self.account_info.get_account_auth_token() + request['generation'] = generation + else: + api_url = self.account_info.get_api_url() + account_auth_token = self.account_info.get_account_auth_token() return raw_api_method(api_url, account_auth_token, *args, **kwargs) def _api_token_only_callback(self, raw_api_method, *args, **kwargs): @@ -536,42 +547,58 @@ def _get_allowed_buckets_message(self, allowed) -> str | None: return f'restricted to buckets {bucket_names}' - def _get_upload_data(self, bucket_id): - """ - Take ownership of an upload URL / auth token for the bucket and - return it. - """ - account_info = self.account_info - upload_url, upload_auth_token = account_info.take_bucket_upload_url(bucket_id) + def _get_new_upload_data(self, get_upload_url, raw_api_method, resource_id): + # Keep public getter overrides active. A ContextVar isolates concurrent and + # nested requests; auth retries replace the snapshot with the attempt used. + request = { + 'method': raw_api_method, + 'generation': self.account_info._get_upload_pool_generation(), + } + context_token = _upload_url_request.set(request) + try: + response = get_upload_url(resource_id) + finally: + _upload_url_request.reset(context_token) + return response['uploadUrl'], response['authorizationToken'], request['generation'] + + def _get_upload_data(self, bucket_id, generation=None): + """Take an upload URL and its acquisition generation for the bucket.""" + upload_url, upload_auth_token, generation = self.account_info._take_upload_url_tagged( + bucket_id, generation + ) if None not in (upload_url, upload_auth_token): - return upload_url, upload_auth_token - - response = self.get_upload_url(bucket_id) - return response['uploadUrl'], response['authorizationToken'] + return upload_url, upload_auth_token, generation + return self._get_new_upload_data( + self.get_upload_url, self.raw_api.get_upload_url, bucket_id + ) - def _get_upload_part_data(self, file_id): - """ - Make sure that we have an upload URL and auth token for the given bucket and - return it. - """ - account_info = self.account_info - upload_url, upload_auth_token = account_info.take_large_file_upload_url(file_id) + def _get_upload_part_data(self, file_id, generation=None): + """Take an upload URL and its acquisition generation for a large file.""" + upload_url, upload_auth_token, generation = self.account_info._take_upload_url_tagged( + file_id, generation, large_file=True + ) if None not in (upload_url, upload_auth_token): - return upload_url, upload_auth_token - - response = self.get_upload_part_url(file_id) - return response['uploadUrl'], response['authorizationToken'] + return upload_url, upload_auth_token, generation + return self._get_new_upload_data( + self.get_upload_part_url, self.raw_api.get_upload_part_url, file_id + ) def _upload_small(self, f, bucket_id, *args, **kwargs): - upload_url, upload_auth_token = self._get_upload_data(bucket_id) + generation = self.account_info._get_upload_pool_generation() + upload_url, upload_auth_token, generation = self._get_upload_data(bucket_id, generation) response = f(upload_url, upload_auth_token, *args, **kwargs) - self.account_info.put_bucket_upload_url(bucket_id, upload_url, upload_auth_token) + self.account_info._put_upload_url_tagged( + bucket_id, upload_url, upload_auth_token, generation + ) return response def _upload_part(self, f, file_id, *args, **kwargs): - upload_url, upload_auth_token = self._get_upload_part_data(file_id) + generation = self.account_info._get_upload_pool_generation() + upload_url, upload_auth_token, generation = self._get_upload_part_data(file_id, generation) response = f(upload_url, upload_auth_token, *args, **kwargs) - self.account_info.put_large_file_upload_url(file_id, upload_url, upload_auth_token) + self.account_info._put_upload_url_tagged( + file_id, upload_url, upload_auth_token, generation, large_file=True + ) return response def update_file_retention( diff --git a/changelog.d/+reauthorization-upload-pools.fixed.md b/changelog.d/+reauthorization-upload-pools.fixed.md new file mode 100644 index 000000000..76efdd959 --- /dev/null +++ b/changelog.d/+reauthorization-upload-pools.fixed.md @@ -0,0 +1 @@ +Refresh pooled upload URLs when the authorization key changes, including when uploads or upload URL requests are in progress. diff --git a/test/unit/account_info/test_reauth_drops_pooled_urls.py b/test/unit/account_info/test_reauth_drops_pooled_urls.py new file mode 100644 index 000000000..c0211656c --- /dev/null +++ b/test/unit/account_info/test_reauth_drops_pooled_urls.py @@ -0,0 +1,547 @@ +###################################################################### +# +# File: test/unit/account_info/test_reauth_drops_pooled_urls.py +# +# Copyright 2026 Backblaze Inc. All Rights Reserved. +# +# License https://www.backblaze.com/using_b2_code.html +# +###################################################################### +from __future__ import annotations + +import hashlib +import io +import threading +from concurrent.futures import ThreadPoolExecutor + +import pytest +from apiver_deps import ALL_CAPABILITIES, B2HttpApiConfig, B2Session, RawSimulator +from apiver_deps_exception import InvalidAuthToken, MissingAccountData + +from .fixtures import * # noqa: F401, F403 + + +@pytest.fixture +def session_with_keys(account_info): + session = B2Session( + account_info=account_info, + api_config=B2HttpApiConfig(_raw_api_class=RawSimulator), + ) + simulator = session.raw_api + account_id, master_key = simulator.create_account() + session.authorize_account('production', account_id, master_key) + bucket_id = session.create_bucket(account_id, 'reauth-test', 'allPrivate')['bucketId'] + file_id = session.start_large_file(bucket_id, 'large.bin', 'application/octet-stream', {})[ + 'fileId' + ] + keys = [ + simulator.create_key( + account_info.get_api_url(), + account_info.get_account_auth_token(), + account_id, + ALL_CAPABILITIES, + name, + None, + None, + None, + ) + for name in ('key-a', 'key-b') + ] + session.authorize_account('production', keys[0]['applicationKeyId'], keys[0]['applicationKey']) + return session, keys, bucket_id, file_id + + +@pytest.fixture(params=['bucket', 'part']) +def pooled_uploads(session_with_keys, request): + session, _, bucket_id, file_id = session_with_keys + info = session.account_info + if request.param == 'bucket': + resource_id = bucket_id + get_url = session.get_upload_url + put = info.put_bucket_upload_url + take = info.take_bucket_upload_url + else: + resource_id = file_id + get_url = session.get_upload_part_url + put = info.put_large_file_upload_url + take = info.take_large_file_upload_url + + responses = [get_url(resource_id) for _ in range(2)] + pairs = [(response['uploadUrl'], response['authorizationToken']) for response in responses] + for pair in pairs: + put(resource_id, *pair) + assert set(take(resource_id) for _ in pairs) == set(pairs), 'pool was not populated' + for pair in pairs: + put(resource_id, *pair) + return resource_id, take, pairs + + +def test_different_key_drops_pooled_upload_urls(session_with_keys, pooled_uploads): + session, keys, _, _ = session_with_keys + resource_id, take, pairs = pooled_uploads + account_id = session.account_info.get_account_id() + + session.authorize_account('production', keys[1]['applicationKeyId'], keys[1]['applicationKey']) + + assert session.account_info.get_account_id() == account_id + assert session.account_info.get_application_key_id() == keys[1]['applicationKeyId'] + pool_is_empty = all(take(resource_id) == (None, None) for _ in pairs) + assert pool_is_empty, 'upload data from the previous authorization remained pooled' + + +def test_same_key_refresh_preserves_pooled_upload_urls(session_with_keys, pooled_uploads): + session, keys, _, _ = session_with_keys + resource_id, take, pairs = pooled_uploads + + session.authorize_account('production', keys[0]['applicationKeyId'], keys[0]['applicationKey']) + + assert set(take(resource_id) for _ in pairs) == set(pairs) + + +def test_failed_authorization_preserves_pooled_upload_urls(session_with_keys, pooled_uploads): + session, keys, _, _ = session_with_keys + resource_id, take, pairs = pooled_uploads + + with pytest.raises(InvalidAuthToken) as caught: + session.authorize_account('production', keys[1]['applicationKeyId'], 'invalid-test-key') + + assert caught.value.code == 'unauthorized' + assert session.account_info.get_application_key_id() == keys[0]['applicationKeyId'] + assert set(take(resource_id) for _ in pairs) == set(pairs) + + +@pytest.mark.parametrize('use_pooled_url', [False, True], ids=['new-url', 'pooled-url']) +def test_upload_finishing_after_reauthorization_cannot_refill_new_pool( + session_with_keys, pooled_uploads, use_pooled_url, mocker +): + session, keys, bucket_id, file_id = session_with_keys + resource_id, take, pairs = pooled_uploads + if not use_pooled_url: + for _ in pairs: + take(resource_id) + + # Simulator-sized data exercises both upload paths without live B2 requests. + data = b'x' * session.raw_api.MIN_PART_SIZE + digest = hashlib.sha1(data).hexdigest() + started, release = threading.Event(), threading.Event() + sent = [] + if resource_id == bucket_id: + upload_method = 'upload_file' + get_url_method = 'get_upload_url' + + def upload(): + return session.upload_file( + bucket_id, + 'small.bin', + len(data), + 'application/octet-stream', + digest, + {}, + io.BytesIO(data), + ) + + else: + upload_method = 'upload_part' + get_url_method = 'get_upload_part_url' + + def upload(): + return session.upload_part(file_id, 1, len(data), digest, io.BytesIO(data)) + + original = getattr(session.raw_api, upload_method) + + def blocked_upload(*args, **kwargs): + sent.append(args[:2]) + if len(sent) == 1: + started.set() + assert release.wait(10), 'authorization did not release the upload' + return original(*args, **kwargs) + + issued = mocker.spy(session.raw_api, get_url_method) + mocker.patch.object(session.raw_api, upload_method, side_effect=blocked_upload) + with ThreadPoolExecutor(max_workers=1) as executor: + pending = executor.submit(upload) + try: + assert started.wait(10), 'upload did not start' + session.authorize_account( + 'production', keys[1]['applicationKeyId'], keys[1]['applicationKey'] + ) + finally: + release.set() + pending.result(timeout=10) + + pool_is_empty = all(take(resource_id) == (None, None) for _ in pairs) + assert pool_is_empty, 'the completed upload refilled the pool after authorization changed' + + upload() + assert issued.call_args.args[1] == session.account_info.get_account_auth_token() + assert sent[1] == (issued.spy_return['uploadUrl'], issued.spy_return['authorizationToken']) + assert sent[1] != sent[0] + assert take(resource_id) == sent[1] + + +@pytest.mark.parametrize( + 'change_key', [False, True], ids=['current-generation', 'retired-generation'] +) +def test_tagged_upload_url_returns_respect_generation( + session_with_keys, pooled_uploads, change_key +): + session, keys, bucket_id, _ = session_with_keys + resource_id, take, pairs = pooled_uploads + info = session.account_info + large_file = resource_id != bucket_id + upload_url, token, generation = info._take_upload_url_tagged(resource_id, large_file=large_file) + assert (upload_url, token) in pairs + if change_key: + session.authorize_account( + 'production', keys[1]['applicationKeyId'], keys[1]['applicationKey'] + ) + assert info._get_upload_pool_generation() > generation + + info._put_upload_url_tagged(resource_id, upload_url, token, generation, large_file=large_file) + returned = take(resource_id) + expected = (None, None) if change_key else (upload_url, token) + matches_generation = returned == expected + assert matches_generation, 'a tagged return was pooled in the wrong generation' + + +def test_reauthorization_before_acquisition_keeps_the_current_url( + session_with_keys, pooled_uploads, mocker +): + session, keys, bucket_id, file_id = session_with_keys + resource_id, take, _ = pooled_uploads + is_bucket = resource_id == bucket_id + acquire_name = '_get_upload_data' if is_bucket else '_get_upload_part_data' + original = getattr(session, acquire_name) + + def reauthorize_then_acquire(*args, **kwargs): + session.authorize_account( + 'production', keys[1]['applicationKeyId'], keys[1]['applicationKey'] + ) + return original(*args, **kwargs) + + mocker.patch.object(session, acquire_name, side_effect=reauthorize_then_acquire) + issued = mocker.spy(session.raw_api, 'get_upload_url' if is_bucket else 'get_upload_part_url') + # Use the simulator's part size to exercise the request without live B2 I/O. + data = b'x' * session.raw_api.MIN_PART_SIZE + digest = hashlib.sha1(data).hexdigest() + if is_bucket: + session.upload_file( + bucket_id, + 'current.bin', + len(data), + 'application/octet-stream', + digest, + {}, + io.BytesIO(data), + ) + else: + session.upload_part(file_id, 1, len(data), digest, io.BytesIO(data)) + + assert issued.call_args.args[1] == session.account_info.get_account_auth_token() + current_url_was_pooled = take(resource_id) == ( + issued.spy_return['uploadUrl'], + issued.spy_return['authorizationToken'], + ) + assert current_url_was_pooled, 'a URL acquired after reauthorization was discarded' + + +def test_take_is_serialized_with_pool_reset(session_with_keys, pooled_uploads, mocker): + session, keys, bucket_id, _ = session_with_keys + resource_id, take, pairs = pooled_uploads + info = session.account_info + old_pool = info._bucket_uploads if resource_id == bucket_id else info._large_file_uploads + real_lock = info._auth_data_lock + local = threading.local() + authorizer = [] + entered, release, authorization_progress = ( + threading.Event(), + threading.Event(), + threading.Event(), + ) + order = [] + + class ObservedLock: + def __enter__(self): + if not real_lock.acquire(blocking=False): + if authorizer and threading.get_ident() == authorizer[0]: + authorization_progress.set() + real_lock.acquire() + local.depth = getattr(local, 'depth', 0) + 1 + return self + + def __exit__(self, *args): + local.depth -= 1 + real_lock.release() + if authorizer and threading.get_ident() == authorizer[0] and local.depth == 0: + authorization_progress.set() + + original_take = old_pool.take + original_reset = info._reset_upload_pools + + def blocked_take(key): + entered.set() + assert release.wait(10), 'take was not released' + result = original_take(key) + order.append('take') + return result + + def recorded_reset(): + original_reset() + order.append('reset') + + def authorize(): + authorizer.append(threading.get_ident()) + session.authorize_account( + 'production', keys[1]['applicationKeyId'], keys[1]['applicationKey'] + ) + + mocker.patch.object(info, '_auth_data_lock', ObservedLock()) + mocker.patch.object(old_pool, 'take', side_effect=blocked_take) + mocker.patch.object(info, '_reset_upload_pools', side_effect=recorded_reset) + with ThreadPoolExecutor(max_workers=2) as executor: + pending_take = executor.submit(take, resource_id) + try: + assert entered.wait(10), 'take did not reach the pool' + pending_auth = executor.submit(authorize) + assert authorization_progress.wait( + 10 + ), 'authorization did not reach its critical section' + finally: + release.set() + assert pending_take.result(timeout=10) in pairs + pending_auth.result(timeout=10) + + assert order == ['take', 'reset'], 'reauthorization reset a pool while a take was in progress' + assert take(resource_id) == (None, None) + + +def _upload(session, bucket_id, file_id, *, large_file): + data = b'x' * session.raw_api.MIN_PART_SIZE + digest = hashlib.sha1(data).hexdigest() + if large_file: + return session.upload_part(file_id, 1, len(data), digest, io.BytesIO(data)) + return session.upload_file( + bucket_id, + 'generation.bin', + len(data), + 'application/octet-stream', + digest, + {}, + io.BytesIO(data), + ) + + +def test_url_request_in_flight_does_not_block_reauthorization_or_refill_new_pool( + session_with_keys, pooled_uploads, mocker +): + session, keys, bucket_id, file_id = session_with_keys + resource_id, take, pairs = pooled_uploads + large_file = resource_id == file_id + for _ in pairs: + take(resource_id) + method = 'get_upload_part_url' if large_file else 'get_upload_url' + original = getattr(session.raw_api, method) + entered, release = threading.Event(), threading.Event() + + def blocked_get(*args, **kwargs): + entered.set() + assert release.wait(10), 'URL request was not released' + return original(*args, **kwargs) + + mocker.patch.object(session.raw_api, method, side_effect=blocked_get) + with ThreadPoolExecutor(max_workers=2) as executor: + pending_upload = executor.submit( + _upload, session, bucket_id, file_id, large_file=large_file + ) + try: + assert entered.wait(10), 'URL request did not start' + authorization = executor.submit( + session.authorize_account, + 'production', + keys[1]['applicationKeyId'], + keys[1]['applicationKey'], + ) + authorization.result(timeout=10) + finally: + release.set() + pending_upload.result(timeout=10) + pool_is_empty = take(resource_id) == (None, None) + assert pool_is_empty, 'a URL requested using the previous authorization was pooled' + + issued = mocker.spy(session.raw_api, method) + _upload(session, bucket_id, file_id, large_file=large_file) + assert take(resource_id) == ( + issued.spy_return['uploadUrl'], + issued.spy_return['authorizationToken'], + ) + + +def test_url_request_retries_expired_account_token(session_with_keys, pooled_uploads, mocker): + session, _, bucket_id, file_id = session_with_keys + resource_id, take, pairs = pooled_uploads + large_file = resource_id == file_id + for _ in pairs: + take(resource_id) + info = session.account_info + expired_token = info.get_account_auth_token() + session.raw_api.expire_auth_token(expired_token) + issued = mocker.spy(session.raw_api, 'get_upload_part_url' if large_file else 'get_upload_url') + + _upload(session, bucket_id, file_id, large_file=large_file) + + assert issued.call_count == 2 + assert issued.call_args_list[0].args[1] == expired_token + assert issued.call_args_list[1].args[1] == info.get_account_auth_token() + assert info.get_account_auth_token() != expired_token + assert take(resource_id) == ( + issued.spy_return['uploadUrl'], + issued.spy_return['authorizationToken'], + ) + + +@pytest.mark.parametrize('large_file', [False, True], ids=['bucket', 'part']) +def test_tagged_helpers_preserve_public_account_info_overrides( + account_info, sqlite_account_info_factory, large_file +): + calls = [] + + class LegacyAccountInfo(type(account_info)): + def take_bucket_upload_url(self, bucket_id): + calls.append('take-bucket') + return super().take_bucket_upload_url(bucket_id) + + def put_bucket_upload_url(self, bucket_id, upload_url, upload_auth_token): + calls.append('put-bucket') + return super().put_bucket_upload_url(bucket_id, upload_url, upload_auth_token) + + def take_large_file_upload_url(self, file_id): + calls.append('take-part') + return super().take_large_file_upload_url(file_id) + + def put_large_file_upload_url(self, file_id, upload_url, upload_auth_token): + calls.append('put-part') + return super().put_large_file_upload_url(file_id, upload_url, upload_auth_token) + + if isinstance(account_info, SqliteAccountInfo): + info = sqlite_account_info_factory(account_info_class=LegacyAccountInfo) + else: + info = LegacyAccountInfo() + generation = info._get_upload_pool_generation() + info._put_upload_url_tagged( + 'resource', 'url', 'synthetic-token', generation, large_file=large_file + ) + assert info._take_upload_url_tagged('resource', large_file=large_file) == ( + 'url', + 'synthetic-token', + generation, + ) + kind = 'part' if large_file else 'bucket' + assert calls == [f'put-{kind}', f'take-{kind}'] + + +@pytest.mark.parametrize('reauthorize', [False, True], ids=['unchanged', 'reauthorized']) +def test_upload_preserves_public_session_getter_override( + session_with_keys, pooled_uploads, reauthorize +): + session, keys, bucket_id, file_id = session_with_keys + resource_id, take, pairs = pooled_uploads + large_file = resource_id == file_id + for _ in pairs: + take(resource_id) + issued = [] + + class SessionWithOverride(type(session)): + def get_upload_url(self, bucket_id): + if reauthorize: + self.authorize_account( + 'production', keys[1]['applicationKeyId'], keys[1]['applicationKey'] + ) + result = super().get_upload_url(bucket_id) + issued.append(result) + return result + + def get_upload_part_url(self, file_id): + if reauthorize: + self.authorize_account( + 'production', keys[1]['applicationKeyId'], keys[1]['applicationKey'] + ) + result = super().get_upload_part_url(file_id) + issued.append(result) + return result + + overridden = SessionWithOverride( + account_info=session.account_info, + api_config=B2HttpApiConfig(_raw_api_class=RawSimulator), + ) + overridden.raw_api = session.raw_api + _upload(overridden, bucket_id, file_id, large_file=large_file) + assert len(issued) == 1 + current_url_was_pooled = take(resource_id) == ( + issued[0]['uploadUrl'], + issued[0]['authorizationToken'], + ) + assert current_url_was_pooled, 'the public getter acquired a current URL that was discarded' + + +def test_clear_cannot_repool_url_from_removed_authorization( + session_with_keys, pooled_uploads, mocker +): + session, _, bucket_id, file_id = session_with_keys + resource_id, take, pairs = pooled_uploads + info = session.account_info + for _ in pairs: + take(resource_id) + clear_paused, finish_clear, upload_progress = ( + threading.Event(), + threading.Event(), + threading.Event(), + ) + real_lock = info._auth_data_lock + uploader = [] + + class ObservedLock: + def __enter__(self): + if not real_lock.acquire(blocking=False): + if uploader and threading.get_ident() == uploader[0]: + upload_progress.set() + real_lock.acquire() + return self + + def __exit__(self, *args): + real_lock.release() + + original_reset = info._reset_upload_pools + + def pause_after_reset(): + original_reset() + # Pause before clear has completed its account cleanup. + clear_paused.set() + assert finish_clear.wait(10), 'account cleanup was not released' + + def upload(): + uploader.append(threading.get_ident()) + try: + return _upload(session, bucket_id, file_id, large_file=resource_id == file_id) + except MissingAccountData: + return None + finally: + upload_progress.set() + + mocker.patch.object(info, '_auth_data_lock', ObservedLock()) + mocker.patch.object(info, '_reset_upload_pools', side_effect=pause_after_reset) + with ThreadPoolExecutor(max_workers=2) as executor: + clearing = executor.submit(info.clear) + try: + assert clear_paused.wait(10), 'clear did not reset its pools' + pending_upload = executor.submit(upload) + assert upload_progress.wait(10), 'upload neither completed nor reached the lock' + finally: + finish_clear.set() + clearing.result(timeout=10) + upload_result = pending_upload.result(timeout=10) + + with pytest.raises(MissingAccountData): + info.get_account_auth_token() + pool_is_empty = take(resource_id) == (None, None) + assert pool_is_empty, 'an upload refilled the pool after account data was cleared' + assert upload_result is None, 'an upload acquired authorization during account cleanup' From f0254d71e45f8f3e74551ed36d9214815dcff582 Mon Sep 17 00:00:00 2001 From: Felipe Fumero Date: Fri, 20 Nov 2026 12:54:07 -0600 Subject: [PATCH 025/113] fix: honor filters for exact file listings (#682) --- b2sdk/_internal/bucket.py | 7 +- changelog.d/+ls-exact-name-filter.fixed.md | 1 + .../unit/bucket/test_ls_exact_name_filters.py | 96 +++++++++++++++++++ test/unit/bucket/test_regression_bucket.py | 12 --- 4 files changed, 102 insertions(+), 14 deletions(-) create mode 100644 changelog.d/+ls-exact-name-filter.fixed.md create mode 100644 test/unit/bucket/test_ls_exact_name_filters.py diff --git a/b2sdk/_internal/bucket.py b/b2sdk/_internal/bucket.py index 3cc7ad214..0b8986928 100644 --- a/b2sdk/_internal/bucket.py +++ b/b2sdk/_internal/bucket.py @@ -412,6 +412,8 @@ def ls( if with_wildcard and not recursive: raise ValueError('with_wildcard requires recursive to be turned on as well') + filter_matcher = FilterMatcher(filters) + # check if path points to an object instead of a folder if path and not with_wildcard and not path.endswith('/'): file_versions = self.list_file_versions(path, 1 if latest_only else fetch_count) @@ -420,7 +422,9 @@ def ls( path_pointed_to_file = False for file_version in file_versions: path_pointed_to_file = True - if not latest_only or file_version.action == 'upload': + if filter_matcher.match(path) and ( + not latest_only or file_version.action == 'upload' + ): yield file_version, None if path_pointed_to_file: return @@ -471,7 +475,6 @@ def ls( # "folder". If the first search doesn't produce enough results, # then we keep calling list_file_names until we get all of the # names in this "folder". - filter_matcher = FilterMatcher(filters) current_dir = None start_file_name = prefix start_file_id = None diff --git a/changelog.d/+ls-exact-name-filter.fixed.md b/changelog.d/+ls-exact-name-filter.fixed.md new file mode 100644 index 000000000..2a963d91a --- /dev/null +++ b/changelog.d/+ls-exact-name-filter.fixed.md @@ -0,0 +1 @@ +Honor filters when listing an exact file name. diff --git a/test/unit/bucket/test_ls_exact_name_filters.py b/test/unit/bucket/test_ls_exact_name_filters.py new file mode 100644 index 000000000..83981de47 --- /dev/null +++ b/test/unit/bucket/test_ls_exact_name_filters.py @@ -0,0 +1,96 @@ +###################################################################### +# +# File: test/unit/bucket/test_ls_exact_name_filters.py +# +# Copyright 2026 Backblaze Inc. All Rights Reserved. +# +# License https://www.backblaze.com/using_b2_code.html +# +###################################################################### +import pytest +from apiver_deps import Filter + + +@pytest.mark.apiver(3) +def test_exact_file_name_honors_exclude_filter(bucket): + bucket.upload_bytes(b'contents', 'reports/result.txt') + assert [item.file_name for item, _ in bucket.ls('reports/result.txt')] == ['reports/result.txt'] + assert ( + list(bucket.ls('reports/result.txt', filters=[Filter.exclude('reports/result.txt')])) == [] + ) + + +@pytest.fixture +def ls_exact(bucket, apiver_int): + def list_exact(path, *, latest_only=True, **kwargs): + if apiver_int < 3: + kwargs['folder_to_list_can_be_a_file'] = True + if apiver_int < 2: + kwargs['show_versions'] = not latest_only + else: + kwargs['latest_only'] = latest_only + return bucket.ls(path, **kwargs) + + return list_exact + + +@pytest.mark.apiver(from_ver=1) +@pytest.mark.parametrize( + 'filters, included', + [ + ([], True), + ([Filter.exclude('reports/*')], False), + ([Filter.include('other/*')], False), + ([Filter.include('reports/*')], True), + ([Filter.exclude('reports/*'), Filter.include('reports/result.txt')], True), + ([Filter.include('reports/*'), Filter.exclude('reports/result.txt')], False), + ], + ids=['no-filter', 'exclude', 'include-other', 'include', 'last-includes', 'last-excludes'], +) +def test_exact_file_name_uses_filter_order(bucket, ls_exact, filters, included): + bucket.upload_bytes(b'contents', 'reports/result.txt') + names = [item.file_name for item, _ in ls_exact('reports/result.txt', filters=filters)] + assert names == (['reports/result.txt'] if included else []) + + +@pytest.mark.apiver(from_ver=1) +def test_excluded_exact_file_does_not_fall_back_to_a_folder(bucket, ls_exact): + bucket.upload_bytes(b'file', 'item') + bucket.upload_bytes(b'child', 'item/child.txt') + assert list(ls_exact('item', recursive=True, filters=[Filter.exclude('item')])) == [] + + +@pytest.mark.apiver(from_ver=1) +@pytest.mark.parametrize('latest_only', [True, False]) +def test_exact_file_name_filter_applies_to_all_versions(bucket, ls_exact, latest_only): + bucket.upload_bytes(b'first', 'reports/result.txt') + bucket.upload_bytes(b'second', 'reports/result.txt') + all_versions = list(ls_exact('reports/result.txt', latest_only=latest_only)) + assert len(all_versions) == (1 if latest_only else 2) + assert ( + list( + ls_exact( + 'reports/result.txt', + latest_only=latest_only, + filters=[Filter.exclude('reports/result.txt')], + ) + ) + == [] + ) + + +@pytest.mark.apiver(0) +@pytest.mark.parametrize('show_versions', [True, False]) +def test_v0_excluded_exact_name(bucket, show_versions): + bucket.upload_bytes(b'contents', 'reports/result.txt') + assert ( + list( + bucket.ls( + 'reports/result.txt', + show_versions=show_versions, + folder_to_list_can_be_a_file=True, + filters=[Filter.exclude('reports/result.txt')], + ) + ) + == [] + ) diff --git a/test/unit/bucket/test_regression_bucket.py b/test/unit/bucket/test_regression_bucket.py index 93400dd97..97e3ddccf 100644 --- a/test/unit/bucket/test_regression_bucket.py +++ b/test/unit/bucket/test_regression_bucket.py @@ -96,12 +96,6 @@ def test_c5_folder_sync_source_with_prefix_naming_a_single_object(self): # must not raise AssertionError (it may list nothing or the object, but not crash) list(folder.all_files(None)) - @known_defect( - 'C6', - 'ls() of an exact file name ignores the filters', - condition=apiver_deps.V >= 3, - raises=AssertionError, - ) def test_c6_exact_filename_respects_exclude_filter(self): """C6: an exclude filter naming the exact file must hide it from ls().""" self.bucket.upload_bytes(b'hello world', 'b/a.txt') @@ -113,12 +107,6 @@ def test_c6_exact_filename_respects_exclude_filter(self): ] assert result == [], 'the filter was ignored' - @known_defect( - 'C6', - 'ls() of an exact file name ignores the filters', - condition=apiver_deps.V >= 3, - raises=AssertionError, - ) def test_c6_exact_filename_respects_include_filter_for_other_name(self): """C6: an include filter not matching the exact file must hide it from ls().""" self.bucket.upload_bytes(b'hello world', 'b/a.txt') From 177a57ec89ac1bb6ec84e80269285054f17cad1c Mon Sep 17 00:00:00 2001 From: Felipe Fumero Date: Fri, 20 Nov 2026 12:54:27 -0600 Subject: [PATCH 026/113] Avoid replaying non-idempotent create-style calls on ambiguous failures (#684) * fix: avoid replaying non-idempotent creates * fix: isolate JSON request retry policy * test: cover wrapped connect timeout retries * fix: recognize connection establishment errors explicitly --- b2sdk/_internal/b2http.py | 114 ++++- .../+non-idempotent-create-retries.fixed.md | 1 + .../test_non_idempotent_create_retries.py | 440 ++++++++++++++++++ test/unit/test_regression_misc.py | 3 - 4 files changed, 542 insertions(+), 16 deletions(-) create mode 100644 changelog.d/+non-idempotent-create-retries.fixed.md create mode 100644 test/unit/b2http/test_non_idempotent_create_retries.py diff --git a/b2sdk/_internal/b2http.py b/b2sdk/_internal/b2http.py index ddac75217..b9d5efd5f 100644 --- a/b2sdk/_internal/b2http.py +++ b/b2sdk/_internal/b2http.py @@ -18,8 +18,10 @@ import threading import time from contextlib import contextmanager +from contextvars import ContextVar from random import random from typing import Any, Callable +from urllib.parse import urlsplit try: from typing_extensions import Literal @@ -41,6 +43,7 @@ ClockSkew, ConnectionReset, PotentialS3EndpointPassedAsRealm, + TooManyRequests, UnknownError, UnknownHost, interpret_b2_error, @@ -50,6 +53,33 @@ LOCALE_LOCK = threading.Lock() logger = logging.getLogger(__name__) +_JSON_POST_ORIGIN = ContextVar('b2sdk_json_post_origin', default=None) + +# These Native API operations can be replayed without creating another resource. +_REPLAYABLE_JSON_POST_ENDPOINTS = frozenset( + { + 'b2_authorize_account', + 'b2_cancel_large_file', + 'b2_delete_bucket', + 'b2_delete_file_version', + 'b2_delete_key', + 'b2_get_download_authorization', + 'b2_get_file_info', + 'b2_get_upload_url', + 'b2_get_upload_part_url', + 'b2_list_buckets', + 'b2_list_file_names', + 'b2_list_file_versions', + 'b2_list_keys', + 'b2_list_parts', + 'b2_list_unfinished_large_files', + 'b2_update_bucket', + 'b2_update_file_retention', + 'b2_update_file_legal_hold', + 'b2_copy_part', + 'b2_set_bucket_notification_rules', + } +) def _print_exception(e, indent=''): @@ -280,7 +310,30 @@ def do_request(): self._run_post_request_hooks(method, url, request_headers, response) return response - return self._translate_and_retry(do_request, try_count, params) + origin = _JSON_POST_ORIGIN.get() + # Hooks may issue nested requests, each of which needs its own policy. + origin_token = _JSON_POST_ORIGIN.set(None) + try: + return self._translate_and_retry( + do_request, + try_count, + params, + retry_on_ambiguous=(origin is not self or self._is_replayable_request(method, url)), + ) + finally: + _JSON_POST_ORIGIN.reset(origin_token) + + @staticmethod + def _is_replayable_request(method, url): + if method != 'POST': + return True + try: + api_path = urlsplit(url).path.rsplit('/', 3) + except ValueError: + # Let requests validate the URL inside the normal error translator. + return False + native_api = len(api_path) == 4 and api_path[1] == 'b2api' + return native_api and api_path[-1] in _REPLAYABLE_JSON_POST_ENDPOINTS def request_content_return_json( self, @@ -373,6 +426,11 @@ def post_json_return_json(self, url, headers, params, try_count: int = TRY_COUNT :param str url: a URL to call :param dict headers: headers to send. :param dict params: a dict that will be converted to JSON + :param int try_count: maximum attempts; ambiguous failures are only retried + for known replayable Native API operations. Create-style or unclassified + JSON POSTs still retry rate limits and proven connection failures before + sending, but surface response timeouts, connection loss and 5xx (including + 503). The operation may have succeeded; check server state before retrying. :return: the decoded JSON document :rtype: dict """ @@ -384,17 +442,21 @@ def post_json_return_json(self, url, headers, params, try_count: int = TRY_COUNT timeout = self.TIMEOUT_FOR_COPY data = json.dumps(params).encode() - return self.post_content_return_json( - url, - { - **headers, - 'Content-Type': 'application/json', - }, - data, - try_count, - params, - _timeout=timeout, - ) + origin_token = _JSON_POST_ORIGIN.set(self) + try: + return self.post_content_return_json( + url, + { + **headers, + 'Content-Type': 'application/json', + }, + data, + try_count, + params, + _timeout=timeout, + ) + finally: + _JSON_POST_ORIGIN.reset(origin_token) def get_content(self, url, headers, try_count: int = TRY_COUNT_DOWNLOAD): """ @@ -571,9 +633,33 @@ def _translate_errors(cls, fcn, post_params=None): logger.exception('_translate_errors has intercepted an unexpected exception') raise UnknownError(text) + @staticmethod + def _is_unapplied_error(error): + if isinstance(error, TooManyRequests): + return True + if not isinstance(error, B2ConnectionError): + return False + original = error.__context__ + if isinstance(original, requests.ConnectTimeout): + return True + if isinstance(original, requests.ConnectionError) and original.args: + reason = original.args[0] + urllib3_errors = requests.packages.urllib3.exceptions + if isinstance(reason, urllib3_errors.MaxRetryError): + reason = reason.reason + return isinstance( + reason, (urllib3_errors.NewConnectionError, urllib3_errors.ConnectTimeoutError) + ) + return False + @classmethod def _translate_and_retry( - cls, fcn: Callable, try_count: int, post_params: dict[str, Any] | None = None + cls, + fcn: Callable, + try_count: int, + post_params: dict[str, Any] | None = None, + *, + retry_on_ambiguous: bool = True, ): """ Try calling fcn try_count times, retrying only if @@ -596,6 +682,8 @@ def _translate_and_retry( except B2Error as e: if not e.should_retry_http(): raise + if not retry_on_ambiguous and not cls._is_unapplied_error(e): + raise logger.debug(str(e), exc_info=True) if e.retry_after_seconds is not None: sleep_duration = e.retry_after_seconds diff --git a/changelog.d/+non-idempotent-create-retries.fixed.md b/changelog.d/+non-idempotent-create-retries.fixed.md new file mode 100644 index 000000000..84e55bb1f --- /dev/null +++ b/changelog.d/+non-idempotent-create-retries.fixed.md @@ -0,0 +1 @@ +Avoid replaying create-style JSON API calls after response timeouts, connection loss, or 5xx responses, including 503. Unlike the general [503 retry guidance](https://www.backblaze.com/docs/cloud-storage-integration-checklist), an uncertain create outcome is surfaced so callers can check server state before trying again. Replayable operations retain their retry policy; rate limits and proven connection-establishment failures are still retried. diff --git a/test/unit/b2http/test_non_idempotent_create_retries.py b/test/unit/b2http/test_non_idempotent_create_retries.py new file mode 100644 index 000000000..3ba5a1ebc --- /dev/null +++ b/test/unit/b2http/test_non_idempotent_create_retries.py @@ -0,0 +1,440 @@ +###################################################################### +# +# File: test/unit/b2http/test_non_idempotent_create_retries.py +# +# Copyright 2026 Backblaze Inc. All Rights Reserved. +# +# License https://www.backblaze.com/using_b2_code.html +# +###################################################################### +from __future__ import annotations + +import json + +import pytest +import requests +from apiver_deps import B2RawHTTPApi +from apiver_deps_exception import B2ConnectionError, B2RequestTimeout, ServiceError, UnknownError + +from b2sdk._internal.api_config import B2HttpApiConfig +from b2sdk._internal.b2http import B2Http, HttpCallback + +API_URL = 'https://api.example.invalid' +AUTH_TOKEN = 'synthetic-account-token' + +CREATE_CALLS = [ + pytest.param( + 'create_bucket', + ('account-id', 'retry-test-bucket', 'allPrivate'), + id='create-bucket', + ), + pytest.param( + 'create_key', + ('account-id', ['readFiles'], 'retry-test-key', None, None, None), + id='create-key', + ), + pytest.param( + 'start_large_file', + ('bucket-id', 'large.bin', 'application/octet-stream', {}), + id='start-large-file', + ), + pytest.param('copy_file', ('source-file-id', 'copy.bin'), id='copy-file'), + pytest.param('hide_file', ('bucket-id', 'hidden.bin'), id='hide-file'), + pytest.param('finish_large_file', ('large-file-id', ['part-sha1']), id='finish-large-file'), +] + + +class CommittedCreateTransport: + """Model applied creates and failures before or after their server effect.""" + + def __init__(self, failure): + self.failures = [failure] if isinstance(failure, str) else failure + self.requests = [] + self.created = [] + + @staticmethod + def response(url, status, payload): + response = requests.Response() + response.url = url + response.status_code = status + response._content = json.dumps(payload).encode() + return response + + def request(self, method, url, *, data, **kwargs): + assert method == 'POST' + self.requests.append(json.loads(data)) + index = len(self.requests) - 1 + failure = self.failures[index] if index < len(self.failures) else None + if failure == '429': + response = self.response( + url, 429, {'status': 429, 'code': 'too_many_requests', 'message': 'rate limited'} + ) + response.headers['Retry-After'] = '2' + return response + if failure == 'connect-timeout': + raise requests.ConnectTimeout('connection not established') + if failure == 'new-connection': + urllib3_errors = requests.packages.urllib3.exceptions + reason = urllib3_errors.NewConnectionError(None, 'connection refused') + raise requests.ConnectionError(urllib3_errors.MaxRetryError(None, url, reason)) + + endpoint = url.rsplit('/', 1)[-1] + if self.created and endpoint in ('b2_create_bucket', 'b2_finish_large_file'): + # A replay cannot recover the successful first result for these calls. + return self.response( + url, + 400, + {'status': 400, 'code': 'bad_request', 'message': 'resource already exists'}, + ) + self.created.append({'id': len(self.created) + 1}) + if failure == 'timeout': + raise requests.ReadTimeout('response unavailable after commit') + if failure == 'connection-lost': + raise requests.ConnectionError('connection lost after commit') + if failure == 'wrapped-connection-lost': + urllib3_errors = requests.packages.urllib3.exceptions + reason = urllib3_errors.ProtocolError( + 'connection lost after send', ConnectionResetError() + ) + raise requests.ConnectionError(urllib3_errors.MaxRetryError(None, url, reason)) + if failure == '503': + return self.response( + url, + 503, + {'status': 503, 'code': 'service_unavailable', 'message': 'response unavailable'}, + ) + return self.response(url, 200, self.created[-1]) + + +@pytest.mark.parametrize('method, args', CREATE_CALLS) +@pytest.mark.parametrize( + 'failure', ['503', 'timeout', 'connection-lost', 'wrapped-connection-lost'] +) +def test_committed_create_is_not_replayed_after_ambiguous_failure(method, args, failure, mocker): + transport = CommittedCreateTransport(failure) + http = B2Http(B2HttpApiConfig(install_clock_skew_hook=False)) + mocker.patch.object(http.session, 'request', side_effect=transport.request) + # Backoff is not under test; the HTTP retry and translation code remain real. + sleep = mocker.patch('b2sdk._internal.b2http.time.sleep') + raw_api = B2RawHTTPApi(http) + expected_error = { + 'timeout': B2RequestTimeout, + '503': ServiceError, + 'connection-lost': B2ConnectionError, + 'wrapped-connection-lost': B2ConnectionError, + }[failure] + + try: + with pytest.raises(expected_error): + getattr(raw_api, method)(API_URL, AUTH_TOKEN, *args) + finally: + http.session.close() + + assert len(transport.requests) == 1 + assert transport.created == [{'id': 1}] + sleep.assert_not_called() + + +@pytest.mark.parametrize('failure', ['503', 'timeout']) +@pytest.mark.parametrize('operation', ['list-buckets', 'copy-part', 'http-explicit']) +def test_replayable_posts_still_retry(operation, failure, mocker): + http = B2Http(B2HttpApiConfig(install_clock_skew_hook=False)) + raw_api = B2RawHTTPApi(http) + requests_sent = [] + parts = {} + if operation == 'copy-part': + expected_result = {'fileId': 'large-file-id', 'partNumber': 1, 'contentSha1': 'part-sha1'} + else: + expected_result = {'buckets': []} + + def request(method, url, *, data, **kwargs): + assert method == 'POST' + payload = json.loads(data) + requests_sent.append(payload) + if operation == 'copy-part': + parts[(payload['largeFileId'], payload['partNumber'])] = payload['sourceFileId'] + if len(requests_sent) == 1: + if failure == 'timeout': + raise requests.ReadTimeout('response unavailable') + return CommittedCreateTransport.response( + url, + 503, + {'status': 503, 'code': 'service_unavailable', 'message': 'response unavailable'}, + ) + return CommittedCreateTransport.response(url, 200, expected_result) + + mocker.patch.object(http.session, 'request', side_effect=request) + mocker.patch('b2sdk._internal.b2http.time.sleep') + try: + if operation == 'copy-part': + result = raw_api.copy_part(API_URL, AUTH_TOKEN, 'source-file-id', 'large-file-id', 1) + elif operation == 'http-explicit': + result = http.post_json_return_json( + API_URL + '/b2api/v4/b2_list_buckets', {}, {'accountId': 'account-id'}, try_count=5 + ) + else: + result = raw_api.list_buckets(API_URL, AUTH_TOKEN, 'account-id') + finally: + http.session.close() + + assert result == expected_result + assert len(requests_sent) == 2 + assert requests_sent[0] == requests_sent[1] + if operation == 'copy-part': + assert parts == {('large-file-id', 1): 'source-file-id'} + + +def test_read_only_post_retains_five_attempt_limit(mocker): + http = B2Http(B2HttpApiConfig(install_clock_skew_hook=False)) + raw_api = B2RawHTTPApi(http) + request = mocker.patch.object( + http.session, + 'request', + side_effect=lambda method, url, **kwargs: CommittedCreateTransport.response( + url, 503, {'status': 503, 'code': 'service_unavailable', 'message': 'unavailable'} + ), + ) + mocker.patch('b2sdk._internal.b2http.time.sleep') + try: + with pytest.raises(ServiceError): + raw_api.list_buckets(API_URL, AUTH_TOKEN, 'account-id') + finally: + http.session.close() + + assert request.call_count == 5 + + +@pytest.mark.parametrize('failure', ['503', 'timeout', 'connection-lost']) +@pytest.mark.parametrize('entry_point', ['http', 'unclassified-raw-api']) +def test_json_post_without_retry_classification_is_not_replayed(entry_point, failure, mocker): + transport = CommittedCreateTransport(failure) + http = B2Http(B2HttpApiConfig(install_clock_skew_hook=False)) + mocker.patch.object(http.session, 'request', side_effect=transport.request) + sleep = mocker.patch('b2sdk._internal.b2http.time.sleep') + expected_error = { + 'timeout': B2RequestTimeout, + '503': ServiceError, + 'connection-lost': B2ConnectionError, + }[failure] + try: + with pytest.raises(expected_error): + if entry_point == 'http': + http.post_json_return_json(API_URL + '/new-operation', {}, {'name': 'candidate'}) + else: + B2RawHTTPApi(http)._post_json( + API_URL, 'new-operation', AUTH_TOKEN, name='candidate' + ) + finally: + http.session.close() + + assert len(transport.requests) == 1 + assert transport.created == [{'id': 1}] + sleep.assert_not_called() + + +@pytest.mark.parametrize('method, args', CREATE_CALLS) +@pytest.mark.parametrize('failure', ['429', 'connect-timeout', 'new-connection']) +def test_creates_retry_only_failures_before_the_server_effect(method, args, failure, mocker): + transport = CommittedCreateTransport(failure) + http = B2Http(B2HttpApiConfig(install_clock_skew_hook=False)) + mocker.patch.object(http.session, 'request', side_effect=transport.request) + sleep = mocker.patch('b2sdk._internal.b2http.time.sleep') + try: + result = getattr(B2RawHTTPApi(http), method)(API_URL, AUTH_TOKEN, *args) + finally: + http.session.close() + + assert result == {'id': 1} + assert transport.created == [{'id': 1}] + assert len(transport.requests) == 2 + sleep.assert_called_once_with(2 if failure == '429' else 1) + + +@pytest.mark.parametrize('method, args', CREATE_CALLS) +def test_create_retries_new_connection_without_shared_timeout_parent(method, args, mocker): + # Simulate a future hierarchy while retaining real NewConnectionError instances. + urllib3_errors = requests.packages.urllib3.exceptions + + class IndependentConnectTimeoutError(urllib3_errors.HTTPError): + pass + + mocker.patch.object(urllib3_errors, 'ConnectTimeoutError', IndependentConnectTimeoutError) + assert not issubclass(urllib3_errors.NewConnectionError, urllib3_errors.ConnectTimeoutError) + transport = CommittedCreateTransport('new-connection') + http = B2Http(B2HttpApiConfig(install_clock_skew_hook=False)) + mocker.patch.object(http.session, 'request', side_effect=transport.request) + sleep = mocker.patch('b2sdk._internal.b2http.time.sleep') + try: + result = getattr(B2RawHTTPApi(http), method)(API_URL, AUTH_TOKEN, *args) + finally: + http.session.close() + + assert len(transport.requests) == 2 + assert transport.requests[0] == transport.requests[1] + assert transport.created == [{'id': 1}] + assert result == {'id': 1} + sleep.assert_called_once_with(1) + + +@pytest.mark.parametrize('method, args', CREATE_CALLS) +def test_create_retries_wrapped_connect_timeout(method, args, mocker): + http = B2Http(B2HttpApiConfig(install_clock_skew_hook=False)) + requests_sent = [] + created = [] + + def request(http_method, url, *, data, **kwargs): + assert http_method == 'POST' + requests_sent.append(json.loads(data)) + if len(requests_sent) == 1: + urllib3_errors = requests.packages.urllib3.exceptions + reason = urllib3_errors.ConnectTimeoutError(None, 'connection timed out') + raise requests.ConnectionError(urllib3_errors.MaxRetryError(None, url, reason=reason)) + created.append({'id': len(created) + 1}) + return CommittedCreateTransport.response(url, 200, created[-1]) + + mocker.patch.object(http.session, 'request', side_effect=request) + sleep = mocker.patch('b2sdk._internal.b2http.time.sleep') + try: + result = getattr(B2RawHTTPApi(http), method)(API_URL, AUTH_TOKEN, *args) + finally: + http.session.close() + + assert len(requests_sent) == 2 + assert requests_sent[0] == requests_sent[1] + assert created == [{'id': 1}] + assert result == {'id': 1} + sleep.assert_called_once_with(1) + + +@pytest.mark.parametrize('failure', ['503', 'timeout', 'connection-lost']) +def test_ambiguous_create_is_not_replayed_after_a_safe_retry(failure, mocker): + transport = CommittedCreateTransport(['429', failure]) + http = B2Http(B2HttpApiConfig(install_clock_skew_hook=False)) + mocker.patch.object(http.session, 'request', side_effect=transport.request) + sleep = mocker.patch('b2sdk._internal.b2http.time.sleep') + expected_error = { + 'timeout': B2RequestTimeout, + '503': ServiceError, + 'connection-lost': B2ConnectionError, + }[failure] + try: + with pytest.raises(expected_error): + B2RawHTTPApi(http).create_key( + API_URL, AUTH_TOKEN, 'account-id', ['readFiles'], 'retry-test-key', None, None, None + ) + finally: + http.session.close() + + assert len(transport.requests) == 2 + assert transport.created == [{'id': 1}] + sleep.assert_called_once_with(2) + + +def test_binary_part_upload_retains_its_explicit_retry_policy(mocker): + http = B2Http(B2HttpApiConfig(install_clock_skew_hook=False)) + bodies = [] + + def request(method, url, *, data, **kwargs): + assert method == 'POST' + bodies.append(data) + if len(bodies) == 1: + return CommittedCreateTransport.response( + url, 503, {'status': 503, 'code': 'service_unavailable', 'message': 'unavailable'} + ) + return CommittedCreateTransport.response( + url, 200, {'fileId': 'large-file-id', 'partNumber': 1} + ) + + mocker.patch.object(http.session, 'request', side_effect=request) + mocker.patch('b2sdk._internal.b2http.time.sleep') + try: + result = http.post_content_return_json( + API_URL + '/b2api/v4/b2_upload_part', {}, b'part', try_count=2 + ) + finally: + http.session.close() + assert bodies == [b'part', b'part'] + assert result == {'fileId': 'large-file-id', 'partNumber': 1} + + +@pytest.mark.parametrize('after_json_failure', [False, True]) +def test_content_metadata_does_not_enable_the_json_retry_policy(after_json_failure, mocker): + http = B2Http(B2HttpApiConfig(install_clock_skew_hook=False)) + bodies = [] + + def request(method, url, *, data, **kwargs): + if url.endswith('b2_create_bucket'): + return CommittedCreateTransport.response( + url, 503, {'status': 503, 'code': 'service_unavailable', 'message': 'unavailable'} + ) + bodies.append(data) + if len(bodies) == 1: + return CommittedCreateTransport.response( + url, 503, {'status': 503, 'code': 'service_unavailable', 'message': 'unavailable'} + ) + return CommittedCreateTransport.response(url, 200, {'ok': True}) + + mocker.patch.object(http.session, 'request', side_effect=request) + mocker.patch('b2sdk._internal.b2http.time.sleep') + try: + if after_json_failure: + with pytest.raises(ServiceError): + http.post_json_return_json( + API_URL + '/b2api/v4/b2_create_bucket', {}, {'bucketName': 'candidate'} + ) + result = http.post_content_return_json( + API_URL + '/content', {}, b'part', try_count=2, post_params={'fileName': 'part.bin'} + ) + finally: + http.session.close() + assert result == {'ok': True} + assert bodies == [b'part', b'part'] + + +def test_nested_content_request_keeps_its_own_retry_policy(mocker): + http = B2Http(B2HttpApiConfig(install_clock_skew_hook=False)) + create_url = API_URL + '/b2api/v4/b2_create_bucket' + attempts = {'create': 0, 'content': 0} + nested_results = [] + + def request(method, url, **kwargs): + kind = 'create' if url == create_url else 'content' + attempts[kind] += 1 + if kind == 'create' or attempts[kind] == 1: + return CommittedCreateTransport.response( + url, 503, {'status': 503, 'code': 'service_unavailable', 'message': 'unavailable'} + ) + return CommittedCreateTransport.response(url, 200, {'ok': True}) + + class NestedRequest(HttpCallback): + def post_request(self, method, url, headers, response): + if url == create_url: + nested_results.append( + http.post_content_return_json( + API_URL + '/content', + {}, + b'part', + try_count=2, + post_params={'fileName': 'part.bin'}, + ) + ) + + http.add_callback(NestedRequest()) + mocker.patch.object(http.session, 'request', side_effect=request) + mocker.patch('b2sdk._internal.b2http.time.sleep') + try: + with pytest.raises(ServiceError): + http.post_json_return_json(create_url, {}, {'bucketName': 'candidate'}) + finally: + http.session.close() + assert attempts == {'create': 1, 'content': 2} + assert nested_results == [{'ok': True}] + + +def test_retry_classification_preserves_invalid_url_error_translation(): + http = B2Http(B2HttpApiConfig(install_clock_skew_hook=False)) + try: + with pytest.raises(UnknownError): + http.post_json_return_json('http://[invalid', {}, {'name': 'candidate'}) + finally: + http.session.close() diff --git a/test/unit/test_regression_misc.py b/test/unit/test_regression_misc.py index eb38bf25e..c075f51cc 100644 --- a/test/unit/test_regression_misc.py +++ b/test/unit/test_regression_misc.py @@ -105,9 +105,6 @@ def test_c31_pydantic_version_ten_counts_as_v2_or_newer(self, monkeypatch): class TestHttpLayer: @responses.activate - @known_defect( - 'C10', 'calls that create things are re-sent after a timeout', raises=DefectStillPresent - ) def test_c10_create_style_post_is_not_blindly_resent_after_timeout(self): """C10: a POST that creates something (b2_create_bucket) must not be re-sent after a timeout.""" url = 'https://example.com/b2api/v4/b2_create_bucket' From fd0da7398577cefc9db104c8ee1255a17900df7c Mon Sep 17 00:00:00 2001 From: Felipe Fumero Date: Fri, 20 Nov 2026 12:55:12 -0600 Subject: [PATCH 027/113] Support stream upload source without a declared length (#688) * fix: support stream ranges with unknown length * docs: clarify unknown range stream length --- b2sdk/_internal/stream/range.py | 19 ++-- .../+stream-range-unknown-length.fixed.md | 1 + test/unit/stream/test_regression_streams.py | 18 +--- ...est_upload_source_stream_unknown_length.py | 98 +++++++++++++++++++ 4 files changed, 115 insertions(+), 21 deletions(-) create mode 100644 changelog.d/+stream-range-unknown-length.fixed.md create mode 100644 test/unit/stream/test_upload_source_stream_unknown_length.py diff --git a/b2sdk/_internal/stream/range.py b/b2sdk/_internal/stream/range.py index cb96f5a0d..d6f11a2b7 100644 --- a/b2sdk/_internal/stream/range.py +++ b/b2sdk/_internal/stream/range.py @@ -25,7 +25,11 @@ def __init__(self, stream, offset, length): """ :param stream: a seekable stream :param int offset: offset in the stream - :param int length: max number of bytes to read + :param length: max number of bytes to read, or None to read to the end of the stream + + If length is None, ``len()`` on this stream raises ``TypeError``. For an + ``UploadSourceStreamRange``, call ``get_content_length()`` on the source and open a + new stream to obtain a stream with a known length. """ super().__init__(stream, length) self.offset = offset @@ -62,12 +66,15 @@ def read(self, size=None): :return: data read from the stream :rtype: bytes """ - remaining = max(0, self.length - self.relative_pos) - if size is None or size < 0: - to_read = remaining + if self.length is None: + to_read = size else: - to_read = min(size, remaining) - data = self.stream.read(to_read) + remaining = max(0, self.length - self.relative_pos) + if size is None or size < 0: + to_read = remaining + else: + to_read = min(size, remaining) + data = super().read(to_read) self.relative_pos += len(data) return data diff --git a/changelog.d/+stream-range-unknown-length.fixed.md b/changelog.d/+stream-range-unknown-length.fixed.md new file mode 100644 index 000000000..b3bcd83b6 --- /dev/null +++ b/changelog.d/+stream-range-unknown-length.fixed.md @@ -0,0 +1 @@ +Allow stream range uploads with an unspecified length to read and calculate their size. diff --git a/test/unit/stream/test_regression_streams.py b/test/unit/stream/test_regression_streams.py index 51979a312..b176422eb 100644 --- a/test/unit/stream/test_regression_streams.py +++ b/test/unit/stream/test_regression_streams.py @@ -121,30 +121,18 @@ def test_c12_guard_sized_reads_cross_stream_boundaries(self): class TestUploadSourceStreamRange: - @known_defect( - 'C15', - 'UploadSourceStreamRange built without a length fails on the first read', - raises=DefectStillPresent, - ) def test_c15_stream_range_without_length_can_be_read(self): """C15: docs allow omitting the stream length; open() then read must work.""" data = b'0123456789' source = UploadSourceStreamRange(lambda: io.BytesIO(data), offset=4) - with defect_raises(TypeError, match="unsupported operand type.*'NoneType'"): - with source.open() as fp: - content = fp.read() + with source.open() as fp: + content = fp.read() assert content == data[4:], 'wrong data read from the stream range' - @known_defect( - 'C15', - 'UploadSourceStreamRange built without a length cannot report its length', - raises=DefectStillPresent, - ) def test_c15_stream_range_without_length_computes_length(self): """C15: length is computed lazily when not given.""" source = UploadSourceStreamRange(lambda: io.BytesIO(b'0123456789'), offset=0) - with defect_raises(TypeError, match="unsupported operand type.*'NoneType'"): - length = source.get_content_length() + length = source.get_content_length() assert length == 10, 'wrong computed length' @known_defect( diff --git a/test/unit/stream/test_upload_source_stream_unknown_length.py b/test/unit/stream/test_upload_source_stream_unknown_length.py new file mode 100644 index 000000000..bd3e789cd --- /dev/null +++ b/test/unit/stream/test_upload_source_stream_unknown_length.py @@ -0,0 +1,98 @@ +###################################################################### +# +# File: test/unit/stream/test_upload_source_stream_unknown_length.py +# +# Copyright 2026 Backblaze Inc. All Rights Reserved. +# +# License https://www.backblaze.com/using_b2_code.html +# +###################################################################### +import hashlib +import io + +import pytest + +from b2sdk.v3 import UploadSourceStreamRange + + +def test_stream_range_without_length_can_be_read(): + source = UploadSourceStreamRange(lambda: io.BytesIO(b'0123456789'), offset=4) + with source.open() as stream: + assert stream.read() == b'456789' + + +@pytest.mark.parametrize('offset', [0, 4, 10, 15]) +def test_unknown_length_is_calculated_for_the_remainder(offset): + data = b'0123456789' + expected = data[offset:] + source = UploadSourceStreamRange(lambda: io.BytesIO(data), offset=offset) + assert source.get_content_length() == len(expected) + assert source.get_content_sha1() == hashlib.sha1(expected).hexdigest() + with source.open() as stream: + assert stream.read() == expected + + +def test_unknown_length_supports_sized_reads_and_relative_seek(): + source = UploadSourceStreamRange(lambda: io.BytesIO(b'0123456789'), offset=4) + with source.open() as stream: + assert stream.read(0) == b'' + assert stream.read(2) == b'45' + assert stream.tell() == 2 + assert stream.seek(0) == 0 + assert stream.read(-1) == b'456789' + assert stream.tell() == 6 + assert stream.read() == b'' + + +def test_unknown_length_and_hash_include_all_short_reads(): + class ShortReadStream(io.BytesIO): + def read(self, size=-1): + return super().read(2 if size is None or size < 0 else min(size, 2)) + + source = UploadSourceStreamRange(lambda: ShortReadStream(b'0123456789'), offset=4) + assert source.get_content_sha1() == hashlib.sha1(b'456789').hexdigest() + assert source.get_content_length() == 6 + + +def test_explicit_length_still_bounds_the_stream(): + source = UploadSourceStreamRange(lambda: io.BytesIO(b'0123456789'), offset=4, stream_length=3) + with source.open() as stream: + assert stream.read() == b'456' + assert source.get_content_length() == 3 + assert source.get_content_sha1() == hashlib.sha1(b'456').hexdigest() + + +@pytest.mark.apiver(3) +def test_upload_with_unknown_length_uses_only_the_selected_remainder(bucket): + source = UploadSourceStreamRange(lambda: io.BytesIO(b'0123456789'), offset=4) + version = bucket.upload(source, 'suffix.txt') + assert version.size == 6 + destination = io.BytesIO() + bucket.download_file_by_name('suffix.txt').save(destination) + assert destination.getvalue() == b'456789' + + +def test_unknown_length_read_none_uses_default_inner_read(): + class NoExplicitNoneStream(io.BytesIO): + def read(self, size=-1): + if size is None: + raise TypeError('read size cannot be None') + return super().read(size) + + source = UploadSourceStreamRange(lambda: NoExplicitNoneStream(b'0123456789'), offset=4) + with source.open() as stream: + assert stream.read(None) == b'456789' + + +def test_unknown_stream_length_requires_new_open_after_calculation(): + source = UploadSourceStreamRange(lambda: io.BytesIO(b'0123456789'), offset=4) + with source.open() as unknown_length_stream: + with pytest.raises(TypeError): + len(unknown_length_stream) + assert source.get_content_length() == 6 + # Existing stream wrappers retain the length they were opened with. + with pytest.raises(TypeError): + len(unknown_length_stream) + with source.open() as known_length_stream: + assert len(known_length_stream) == 6 + assert known_length_stream.read() == b'456789' From 8756b1019e81f8b076899dff284d007ba739208f Mon Sep 17 00:00:00 2001 From: Felipe Fumero Date: Fri, 20 Nov 2026 12:57:46 -0600 Subject: [PATCH 028/113] docs: fix broken examples, fill gaps, and consolidate contributor guides (#603) * Fix typos and a stale claim in the docs Corrects overalapping, manullay, "Streams that contains" and "If all candidates fails" in the Advanced usage patterns guide, and replaces the time-relative "developed for 3 years" claim on the overview page. Closes #591 Co-Authored-By: Claude Opus 5 * Install the local checkout in the development install guide The Installation Guide told readers to check out the repository and then run "pip install b2sdk", which resolves the published package from PyPI and ignores local changes. Use an editable install of the checkout, and point at the Contributors Guide for the full nox/uv setup. Closes #590 Co-Authored-By: Claude Opus 5 * Correct the nox session list and CI matrix in contributor docs The Sphinx contributor guide advertised a "deploy" nox session that does not exist; releases are published by the Continuous Delivery workflow on a version tag. Both contributor guides also claimed a matrix of 8 Python versions, which no longer matches PYTHON_VERSIONS; describe the matrix by reference so it does not drift again. Closes #588 Closes #589 Co-Authored-By: Claude Opus 5 * Fix invalid API usage in the Quick Start examples The sync example used a nonexistent EncryptionSettings class, passed id= to EncryptionKey instead of key_id=, and gave BasicSyncEncryptionSettingsProvider one mapping where it requires both read and write mappings. Uploads documented file_infos= instead of file_info=. The file-lock examples also handed a FileRetentionSetting to update_file_legal_hold, which takes a LegalHold; those calls now use update_file_retention. Closes #584 Closes #585 Co-Authored-By: Claude Opus 5 * Fix stale names in the Advanced usage patterns guide The prose referred to LocalUploadSource, which is not exported; the surrounding examples already use UploadSourceLocalFile. One example also called planner.create_file, while every other example in the section calls bucket.create_file. Closes #586 Co-Authored-By: Claude Opus 5 * Make the published Contributors Guide the canonical source CONTRIBUTING.md and doc/source/contributing.rst duplicated environment setup, nox sessions, testing and documentation commands, and had already drifted apart. Move the guidance that only existed in the Markdown copy (versioning, changelog fragments, dependency management, keyword-filtered tests) into the Sphinx guide, and reduce CONTRIBUTING.md to a short GitHub-facing entry point that links to it. Closes #599 Co-Authored-By: Claude Opus 5 * Document where a new test belongs The repository keeps four numbered interfaces working at once, and the unit suite is what enforces that, but nothing explained how the apiver machinery selects tests. A test could therefore be placed where it covers only one interface even though the changed _internal behaviour is shared. Add a decision table for the shared, per-version, v_all and integration locations, document the apiver marker, and add a checklist for _internal changes. Closes #592 Co-Authored-By: Claude Opus 5 * Expand the release guide into a maintainer runbook The guide was a single instruction to run make_release_commit and follow its output, leaving the boundaries undocumented: that the session builds the changelog but neither commits nor tags, that CI must be green before tagging because a PyPI version cannot be reused, and that CD creates a GitHub release but publishes to PyPI only when the token is present and the tag is not a prerelease. Document those, plus recovery before and after a tag is pushed. Closes #593 Co-Authored-By: Claude Opus 5 * Make the public/internal namespace boundary explicit The interface policy described which modules are public but said nothing about the versioned namespace itself, which re-exports far more than the public interface - low-level HTTP classes, simulators, constants, and names leaked by star-imports. State that importability is not a promise, and give the rule for telling public, internal and unclassified names apart. The per-name classification that #597 also asks for still needs maintainer review, so this does not close the issue. Refs #597 Co-Authored-By: Claude Opus 5 * Add a replication guide and API reference Replication was fully exposed by the SDK but undocumented, discoverable only by guessing at names. Add a task-oriented guide covering setup via ReplicationSetupHelper and by hand, the application-key capabilities each side needs, per-file replication status, monitoring a rule, and how to read and interpret a scan report. Add reference pages for the public replication classes. Documenting ReplicationMonitor also required indenting the continuation lines of its docstring's parameter list, which docutils otherwise rejects. No executable code is changed. ReplicationReport is described in prose rather than generated, because its inherited annotations cannot be resolved from the subclass's module. Fixing that properly belongs in b2sdk/_internal/scan/scan.py. Closes #595 Co-Authored-By: Claude Opus 5 * Resolve the embedded documentation TODOs Five of the six todo directives are addressed: the "delete doc/source/b2sdk?" note is obsolete since that directory no longer exists, raw_simulator already has an autodoc page, the "Why use b2sdk?" list is now consistently phrased and links to the features it mentions, and the progress reporters and exception hierarchy have real documentation rather than a note saying they need some. The remaining directive, in advanced.rst, asks for `prioritize` to accept an enum instead of a string. That is an API design change rather than documentation, so it is left in place until an issue exists to link it to. Refs #601 Co-Authored-By: Claude Opus 5 * Link the remaining documentation TODO to its tracking issue The last todo directive asked for `prioritize` to accept an enum instead of a string, which is an API design change rather than documentation work. It is now tracked as issue #602 and the directive links to it, retained in place so that anyone editing that section sees it next to the documented string values. It stays out of published builds, since the todo directive only renders when B2_SPHINX_TODO is set. Closes #601 Co-Authored-By: Claude Opus 5 --------- Co-authored-by: Claude Opus 5 --- CONTRIBUTING.md | 157 +++----------- README.release.md | 107 +++++++++- b2sdk/_internal/replication/monitoring.py | 10 +- changelog.d/+interface-boundary.doc.md | 1 + changelog.d/584.doc.md | 1 + changelog.d/585.doc.md | 1 + changelog.d/586.doc.md | 1 + changelog.d/588.doc.md | 1 + changelog.d/589.doc.md | 1 + changelog.d/590.doc.md | 1 + changelog.d/591.doc.md | 1 + changelog.d/592.doc.md | 1 + changelog.d/593.doc.md | 1 + changelog.d/595.doc.md | 1 + changelog.d/599.doc.md | 1 + changelog.d/601.doc.md | 1 + doc/source/advanced.rst | 18 +- doc/source/api/exception.rst | 51 ++++- doc/source/api/progress.rst | 64 +++++- doc/source/api/replication/monitoring.rst | 19 ++ doc/source/api/replication/setting.rst | 17 ++ doc/source/api/replication/setup.rst | 8 + doc/source/api/replication/types.rst | 8 + doc/source/api_reference.rst | 4 + doc/source/api_types.rst | 34 ++++ doc/source/contributing.rst | 127 +++++++++++- doc/source/index.rst | 31 ++- doc/source/install.rst | 13 +- doc/source/quick_start.rst | 26 ++- doc/source/replication.rst | 236 ++++++++++++++++++++++ 30 files changed, 755 insertions(+), 188 deletions(-) create mode 100644 changelog.d/+interface-boundary.doc.md create mode 100644 changelog.d/584.doc.md create mode 100644 changelog.d/585.doc.md create mode 100644 changelog.d/586.doc.md create mode 100644 changelog.d/588.doc.md create mode 100644 changelog.d/589.doc.md create mode 100644 changelog.d/590.doc.md create mode 100644 changelog.d/591.doc.md create mode 100644 changelog.d/592.doc.md create mode 100644 changelog.d/593.doc.md create mode 100644 changelog.d/595.doc.md create mode 100644 changelog.d/599.doc.md create mode 100644 changelog.d/601.doc.md create mode 100644 doc/source/api/replication/monitoring.rst create mode 100644 doc/source/api/replication/setting.rst create mode 100644 doc/source/api/replication/setup.rst create mode 100644 doc/source/api/replication/types.rst create mode 100644 doc/source/replication.rst diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index c561287bc..3c3ee9d32 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,146 +1,39 @@ # Contributing to B2 Python SDK -We encourage outside contributors to perform changes on our codebase. Many such changes have been merged already. -In order to make it easier to contribute, core developers of this project: +We encourage outside contributors to perform changes on our codebase. Many such changes have been merged +already. -* provide guidance (through the issue reporting system) -* provide tool assisted code review (through the Pull Request system) -* maintain a set of unit tests -* maintain a set of integration tests (run with a production cloud) -* maintain development automation tools using [nox](https://github.com/theacodes/nox) that can easily: - * format the code using [ruff](https://github.com/astral-sh/ruff) - * runs linters to find subtle/potential issues with maintainability - * run the test suite on multiple Python versions using [pytest](https://github.com/pytest-dev/pytest) -* maintain Continuous Integration (by using GitHub Actions) that: - * runs all sorts of linters - * checks if the Python distribution can be built - * runs all tests on a matrix of 8 versions of Python (including pypy) and 3 operating systems - (Linux, Mac OS X and Windows) - * checks if the documentation can be built properly -* maintain other Continuous Integration tools (coverage tracker) +**The full contributors guide is published at +[b2-sdk-python.readthedocs.io/en/master/contributing.html](https://b2-sdk-python.readthedocs.io/en/master/contributing.html)** +(source: [`doc/source/contributing.rst`](doc/source/contributing.rst)). It is the canonical reference for +environment setup, the available `nox` sessions, dependency management, testing, and building the +documentation. This file is a short entry point only — please keep detailed guidance in the published +guide rather than duplicating it here. -## Versioning +## Getting started -This package's versions adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html) and the versions are -established by reading git tags, i.e. no code or manifest file changes are required when working on PRs. +You'll need [nox](https://github.com/theacodes/nox) and [uv](https://docs.astral.sh/uv/): -## Changelog + pip install nox uv -Each PR needs to have at least one changelog (aka news) item added. This is done by creating files in `changelog.d`. -`towncrier` is used for compiling these files into [CHANGELOG.md](CHANGELOG.md). There are several types of changes -(news): - -1. fixed -2. changed -3. added -4. deprecated -5. removed -6. infrastructure -7. doc - - -The `changelog.d` file name convention is: - -1. If the PR closes a github issue: `{issue_number}.{type}.md` e.g. `157.fixed.md`. Note that the - change description still has to be complete, linking an issue is just there for convenience, a change like - `fixed #157` will not be accepted. -2. If the PR is not related to a github issue: `+{unique_string}.{type}.md` e.g. `+foobar.fixed.md`. - -These files can either be created manually, or using `towncrier` e.g. - - towncrier create -c 'write your description here' 157.fixed.md - -`towncrier create` also takes care of duplicates automatically (if there is more than 1 news fragment of one type -for a given github issue). - -## Developer Info - -You'll need to have [nox](https://github.com/theacodes/nox) and [uv](https://docs.astral.sh/uv/) installed: - -* `pip install nox uv` - -With `nox`, you can run different sessions (default are `lint` and `test`): - -* `format` -> Format the code. -* `lint` -> Run linters. -* `test` (`test-3.10`, `test-3.11`, `test-3.12`, `test-3.13`, `test-3.14`, `test-pypy3.10`) -> Run test suite. -* `cover` -> Perform coverage analysis. -* `build` -> Build the distribution. -* `doc` -> Build the documentation. -* `doc_cover` -> Perform coverage analysis for the documentation. - -For example: - - $ nox -s format - nox > Running session format - nox > Creating virtual environment (virtualenv) using python3.14 in .nox/format - ... - - $ nox -s format - nox > Running session format - nox > Re-using existing virtual environment at .nox/format. - ... - - $ nox --no-venv -s format - nox > Running session format - ... - -Sessions `test` ,`unit`, and `integration` can run on many Python versions, 3.10-3.14 (+ pypy3.10) by default. - -Sessions other than `test` use the last CPython version from `NOX_PYTHONS`, 3.14 by default. - -You can change it: - - export NOX_PYTHONS=3.12,3.14 - -With the above setting, session `test` will run on Python 3.12 and 3.14, and all other sessions on Python 3.14. - -Given Python interpreters should be installed in the operating system or via [pyenv](https://github.com/pyenv/pyenv). - -## Managing dependencies - -We use [uv](https://docs.astral.sh/uv/) for managing dependencies and developing locally. -If you want to change any of the project requirements (or requirement bounds) in `pyproject.toml`, -make sure that `uv.lock` file reflects those changes by using `uv add`, `uv lock` or other -commands - see [documentation](https://docs.astral.sh/uv/). You can verify that the lock file -is up to date by running `uv lock --check`. - -## Linting - -To run all available linters: +Then, to run the linters and the test suite: nox -s lint - -## Testing - -To run all tests on every available Python version: - nox -s test -To run all tests on a specific version: - - nox -s test-3.10 - -To run just unit tests: - - nox -s unit-3.10 - -To run just integration tests: - - export B2_TEST_APPLICATION_KEY=your_app_key - export B2_TEST_APPLICATION_KEY_ID=your_app_key_id - nox -s integration-3.10 - -To run tests by keyword expressions: - - nox -s unit-3.10 -- -k keyword - -## Documentation - -To build the documentation and watch for changes (including the source code): +Integration tests need real B2 credentials; see the published guide for details. - nox -s doc +## Before you open a pull request -To just build the documentation: +* **Add a changelog entry.** Every PR needs at least one news fragment in `changelog.d`, or CI will + fail. Name it `{issue_number}.{type}.md` (e.g. `157.fixed.md`) when the PR closes an issue, or + `+{unique_string}.{type}.md` (e.g. `+foobar.fixed.md`) otherwise. Valid types are `fixed`, `changed`, + `added`, `deprecated`, `removed`, `infrastructure` and `doc`. The description must stand on its own — + a change like `fixed #157` will not be accepted. [towncrier](https://towncrier.readthedocs.io/) + compiles these into [CHANGELOG.md](CHANGELOG.md). +* **Don't bump the version.** Versions follow [Semantic Versioning](https://semver.org/spec/v2.0.0.html) + and are established by reading git tags, so no code or manifest changes are required in a PR. +* **Update `uv.lock` if you touched dependencies.** Use `uv add` or `uv lock`, and verify with + `uv lock --check`. - nox --non-interactive -s doc +Releases are cut by maintainers; see [README.release.md](README.release.md). diff --git a/README.release.md b/README.release.md index 9ebbd8303..81a344ee2 100644 --- a/README.release.md +++ b/README.release.md @@ -1,3 +1,108 @@ # Release Process -- Run `nox -s make_release_commit -- X.Y.Z` where `X.Y.Z` is the version you're releasing, and follow the instructions +Releasing **b2sdk** is part automated and part manual. A `nox` session prepares the changelog, a +maintainer commits and tags by hand, and the *Continuous Delivery* workflow +([`.github/workflows/cd.yml`](.github/workflows/cd.yml)) does everything from the tag onwards. + +Nothing in the release is triggered by merging to `master`. Publishing begins only when a `v*` tag is +pushed. + +## Prerequisites + +* **A clean worktree.** `make_release_commit` aborts if `git diff --stat` reports anything. Note that + it inspects tracked files only, so untracked files will not stop it. +* **Release from `master`.** The session only *warns* when you are on another branch, it does not stop + you. Releasing from a feature branch is almost never what you want. +* **A version of the form `X.Y.Z`**, with integers and no leading `v` and no suffix. Anything else is + rejected. +* **An `upstream` remote** pointing at the release repository. `noxfile.py` defines the expected URL as + `UPSTREAM_REPO_URL`; the session prints a command to add it if it is missing. +* **Changelog fragments** for everything going out. Every PR should already have added one to + `changelog.d`; review that directory before starting, because whatever is there becomes the release + notes. + +## Steps + +### 1. Build the changelog + +``` +nox -s make_release_commit -- X.Y.Z +``` + +Despite the session's name, **this does not commit and does not tag.** It runs `towncrier build`, which +folds the `changelog.d` fragments into `CHANGELOG.md` and deletes the fragment files, then prints the +commands for the remaining steps. Review the resulting `CHANGELOG.md` diff before going further — this +is the last convenient moment to fix wording. + +### 2. Commit and push + +``` +git commit -m "release X.Y.Z" +git push upstream master +``` + +### 3. Wait for CI + +Let the *Continuous Integration* workflow finish on the pushed commit. Tagging a commit whose CI is red +means publishing a broken release, and a version number cannot be reused on PyPI. + +### 4. Tag and push the tag + +``` +git tag vX.Y.Z +git push upstream vX.Y.Z +``` + +Pushing the tag is the point of no return. + +## What the CD workflow does + +Triggered by any pushed tag matching `v*`: + +1. Decides whether the release is a prerelease, based only on whether the tag's last character is a + digit. `v1.2.3` is a normal release. +2. Builds the distribution with `nox -s build`, which also asserts the built package imports from + `site-packages` rather than the checkout. The version is derived from the tag, not from any file. +3. Reads the notes for that version out of `CHANGELOG.md`. If the tag and the changelog heading do not + match, there will be no release body. +4. Creates a GitHub release and attaches the distribution. +5. Uploads to PyPI — **only** when the `B2_PYPI_PASSWORD` secret is present *and* the release is not a + prerelease. A repository without that secret still gets a GitHub release and silently publishes + nothing to PyPI, so do not treat a green CD run as proof that PyPI was updated. + +## After the release + +* Confirm the GitHub release exists, has release notes, and has the distribution attached. +* If a PyPI publish was expected, confirm the new version is actually on PyPI. +* Confirm `pip install b2sdk==X.Y.Z` resolves. + +## If something goes wrong + +### Before the tag is pushed + +Everything is still local and reversible. Remember that `towncrier build` **deleted** the changelog +fragments, so recovering means restoring them: + +* Fragments deleted but not yet committed: `git checkout -- changelog.d CHANGELOG.md`. +* Already committed: `git reset --hard HEAD~1` (only if the commit has not been pushed), or revert it. + +Then fix the problem and start again from step 1. + +### After the tag is pushed, before PyPI published + +Delete the tag locally and upstream, fix the problem, and re-tag: + +``` +git push upstream :refs/tags/vX.Y.Z +git tag -d vX.Y.Z +``` + +Delete the GitHub release too, if one was created. Re-using the version number is safe only while +nothing has reached PyPI. + +### After PyPI published + +The version is spent. PyPI does not allow re-uploading a version, even after deleting it. Do not try to +reuse the number — fix the problem and release the next patch version instead. If the published release +is actively harmful, yank it on PyPI (which hides it from new resolutions without breaking pins that +already reference it) and follow up with a fixed release. diff --git a/b2sdk/_internal/replication/monitoring.py b/b2sdk/_internal/replication/monitoring.py index 2c3cc983d..1cea8ade5 100644 --- a/b2sdk/_internal/replication/monitoring.py +++ b/b2sdk/_internal/replication/monitoring.py @@ -115,14 +115,14 @@ class ReplicationMonitor: :param b2sdk.v2.Bucket bucket: replication source bucket :param b2sdk.v2.ReplicationRule rule: replication rule to be monitored; - should belong to `bucket`'s replication configuration + should belong to `bucket`'s replication configuration :param b2sdk.v2.B2Api destination_api: B2Api instance for destination - bucket; if destination bucket is on the same account as source bucket, - omit this parameter and then source bucket's B2Api will be used + bucket; if destination bucket is on the same account as source bucket, + omit this parameter and then source bucket's B2Api will be used :param b2sdk.v2.ProgressReport report: instance of ProgressReport which will report - scanning progress, by default to stdout + scanning progress, by default to stdout :param b2sdk.v2.ScanPoliciesManager scan_policies_manager: a strategy to scan - files, so that several files that match some criteria may be omitted + files, so that several files that match some criteria may be omitted :rtype: b2sdk.v2.ReplicationMonitor """ diff --git a/changelog.d/+interface-boundary.doc.md b/changelog.d/+interface-boundary.doc.md new file mode 100644 index 000000000..391df3310 --- /dev/null +++ b/changelog.d/+interface-boundary.doc.md @@ -0,0 +1 @@ +State explicitly that being importable from a versioned namespace such as `b2sdk.v3` is not a compatibility promise, and document how to tell whether a name is public, internal, or unclassified. diff --git a/changelog.d/584.doc.md b/changelog.d/584.doc.md new file mode 100644 index 000000000..756bbea1f --- /dev/null +++ b/changelog.d/584.doc.md @@ -0,0 +1 @@ +Fix the Quick Start examples to match the public `b2sdk.v3` interface: `EncryptionSetting` rather than `EncryptionSettings`, `EncryptionKey(key_id=...)` rather than `id=`, both required mappings for `BasicSyncEncryptionSettingsProvider`, and `file_info=` rather than `file_infos=`. diff --git a/changelog.d/585.doc.md b/changelog.d/585.doc.md new file mode 100644 index 000000000..784e6f02e --- /dev/null +++ b/changelog.d/585.doc.md @@ -0,0 +1 @@ +Use `update_file_retention` instead of `update_file_legal_hold` in the Quick Start file-lock examples that pass a `FileRetentionSetting`. diff --git a/changelog.d/586.doc.md b/changelog.d/586.doc.md new file mode 100644 index 000000000..986ff1691 --- /dev/null +++ b/changelog.d/586.doc.md @@ -0,0 +1 @@ +Fix the Advanced usage patterns guide to reference `UploadSourceLocalFile` rather than the nonexistent `LocalUploadSource`, and to call `bucket.create_file` rather than an undefined `planner` object. diff --git a/changelog.d/588.doc.md b/changelog.d/588.doc.md new file mode 100644 index 000000000..c07000e08 --- /dev/null +++ b/changelog.d/588.doc.md @@ -0,0 +1 @@ +Remove the nonexistent `deploy` Nox session from the Contributors Guide and describe how releases are actually published by the Continuous Delivery workflow. diff --git a/changelog.d/589.doc.md b/changelog.d/589.doc.md new file mode 100644 index 000000000..f4b8015d1 --- /dev/null +++ b/changelog.d/589.doc.md @@ -0,0 +1 @@ +Correct the stale CI test matrix description in the contributor guides, which claimed eight Python versions instead of the currently supported set. diff --git a/changelog.d/590.doc.md b/changelog.d/590.doc.md new file mode 100644 index 000000000..af97b4e72 --- /dev/null +++ b/changelog.d/590.doc.md @@ -0,0 +1 @@ +Correct the Installation Guide's development-install instructions, which told readers to check out the repository and then install the published package from PyPI instead of their local checkout. diff --git a/changelog.d/591.doc.md b/changelog.d/591.doc.md new file mode 100644 index 000000000..3f62ef354 --- /dev/null +++ b/changelog.d/591.doc.md @@ -0,0 +1 @@ +Fix typos in the Advanced usage patterns guide and remove an outdated time-relative claim about the library's age from the overview. diff --git a/changelog.d/592.doc.md b/changelog.d/592.doc.md new file mode 100644 index 000000000..0e2aba5d5 --- /dev/null +++ b/changelog.d/592.doc.md @@ -0,0 +1 @@ +Document how to choose a location for a new test in the Contributors Guide, covering the shared unit directories, the per-interface `v0`-`v3` directories, `v_all`, integration tests, the `apiver` marker, and a checklist for changes to `b2sdk/_internal`. diff --git a/changelog.d/593.doc.md b/changelog.d/593.doc.md new file mode 100644 index 000000000..26594d812 --- /dev/null +++ b/changelog.d/593.doc.md @@ -0,0 +1 @@ +Expand the release guide into a maintainer runbook covering prerequisites, the changelog build, the commit/CI/tag sequence, what the Continuous Delivery workflow does, post-release verification, and recovery before and after a tag is pushed. diff --git a/changelog.d/595.doc.md b/changelog.d/595.doc.md new file mode 100644 index 000000000..f59ac6131 --- /dev/null +++ b/changelog.d/595.doc.md @@ -0,0 +1 @@ +Add a task-oriented replication guide covering setup, required application-key capabilities, per-file replication status, monitoring and how to read a scan report, plus API reference pages for the public replication classes. diff --git a/changelog.d/599.doc.md b/changelog.d/599.doc.md new file mode 100644 index 000000000..deb43320b --- /dev/null +++ b/changelog.d/599.doc.md @@ -0,0 +1 @@ +Consolidate contributor guidance into the published Contributors Guide, and reduce `CONTRIBUTING.md` to a short entry point that links to it, so the two copies can no longer drift apart. diff --git a/changelog.d/601.doc.md b/changelog.d/601.doc.md new file mode 100644 index 000000000..cf88f11b4 --- /dev/null +++ b/changelog.d/601.doc.md @@ -0,0 +1 @@ +Resolve the embedded documentation TODOs: drop the obsolete ones, make the "Why use b2sdk?" list consistent and linked, and document the progress reporters and the exception hierarchy properly. diff --git a/doc/source/advanced.rst b/doc/source/advanced.rst index 5b78c8f9c..6e0d283b5 100644 --- a/doc/source/advanced.rst +++ b/doc/source/advanced.rst @@ -79,7 +79,7 @@ Concatenate files of known size If one of remote source has length smaller than :term:`absoluteMinimumPartSize` then it cannot be copied into large file part. Such remote source would be downloaded and concatenated locally with local source or with other downloaded remote source. -Please note that this method only allows checksum verification for local upload sources. Checksum verification for remote sources is available only when local copy is available. In such case :meth:`b2sdk.v3.Bucket.create_file` can be used with overalapping ranges in input. +Please note that this method only allows checksum verification for local upload sources. Checksum verification for remote sources is available only when local copy is available. In such case :meth:`b2sdk.v3.Bucket.create_file` can be used with overlapping ranges in input. For more information about ``concatenate`` please see :meth:`b2sdk.v3.Bucket.concatenate` and :class:`b2sdk.v3.CopySource`. @@ -150,7 +150,7 @@ The assumption here is that the file has been appended to since it was last uplo >>> bucket.create_file(input_sources, remote_name, file_info) -`LocalUploadSource` has the size determined automatically in this case. This is more efficient than :meth:`b2sdk.v3.Bucket.concatenate`, as it can use the overlapping ranges when a remote part is smaller than :term:`absoluteMinimumPartSize` to prevent downloading a range (when concatenating, local source would have destination offset at the end of remote source) +:class:`b2sdk.v3.UploadSourceLocalFile` has the size determined automatically in this case. This is more efficient than :meth:`b2sdk.v3.Bucket.concatenate`, as it can use the overlapping ranges when a remote part is smaller than :term:`absoluteMinimumPartSize` to prevent downloading a range (when concatenating, local source would have destination offset at the end of remote source) For more information see :meth:`b2sdk.v3.Bucket.create_file`. @@ -179,7 +179,7 @@ Change the middle of the remote file >>> bucket.create_file(input_sources, remote_name, file_info) -`LocalUploadSource` has the size determined automatically in this case. This is more efficient than :meth:`b2sdk.v3.Bucket.concatenate`, as it can use the overlapping ranges when a remote part is smaller than :term:`absoluteMinimumPartSize` to prevent downloading a range. +:class:`b2sdk.v3.UploadSourceLocalFile` has the size determined automatically in this case. This is more efficient than :meth:`b2sdk.v3.Bucket.concatenate`, as it can use the overlapping ranges when a remote part is smaller than :term:`absoluteMinimumPartSize` to prevent downloading a range. For more information see :meth:`b2sdk.v3.Bucket.create_file`. @@ -284,7 +284,7 @@ Here the planner has only used a remote source where remote range was not availa .. code-block:: python - >>> planner.create_file(input_sources, remote_name, file_info, prioritize='remote') + >>> bucket.create_file(input_sources, remote_name, file_info, prioritize='remote') # planner parts: cloud[A, D], local[D, E] Here the planner has only used a local source where remote range was not available, minimizing uploads. @@ -301,8 +301,10 @@ In `local_verification` mode the remote range was artificially split into three .. note:: `prioritize` is just a planner setting - remote parts are always verified if matching local parts exists. -.. TODO:: - prioritization should accept enum, not string +.. todo:: + Prioritization should accept an enum, not a string. Tracked in + `issue #602 `_. Kept here so that anyone + editing this section sees it alongside the documented string values. .. _continuation: @@ -353,7 +355,7 @@ Manual continuation (streamed version) >>> large_file_id = storage.query({'name': remote_name})[0]['large_file_id'] >>> bucket.create_file_stream(input_sources, remote_name, file_info, large_file_id=large_file_id) -Streams that contains remote sources cannot be continued with :meth:`b2sdk.v3.Bucket.create_file` - internally :meth:`b2sdk.v3.Bucket.create_file` stores plan information in file info for such inputs, and verifies it before any copy/upload and :meth:`b2sdk.v3.Bucket.create_file_stream` cannot store this information. Local source only inputs can be safely continued with :meth:`b2sdk.v3.Bucket.create_file` in auto continue mode or manual continue mode (because plan information is not stored in file info in such case). +Streams that contain remote sources cannot be continued with :meth:`b2sdk.v3.Bucket.create_file` - internally :meth:`b2sdk.v3.Bucket.create_file` stores plan information in file info for such inputs, and verifies it before any copy/upload and :meth:`b2sdk.v3.Bucket.create_file_stream` cannot store this information. Local source only inputs can be safely continued with :meth:`b2sdk.v3.Bucket.create_file` in auto continue mode or manual continue mode (because plan information is not stored in file info in such case). Auto continuation ----------------- @@ -364,7 +366,7 @@ Auto continuation For local source only input, :meth:`b2sdk.v3.Bucket.create_file` would try to find matching unfinished large file. It will verify uploaded parts checksums with local sources - the most completed, having all uploaded parts matched candidate would be automatically selected as file to continue. If there is no matching candidate (even if there are unfinished files for the same file name) new large file would be started. -In other cases plan information would be generated and :meth:`b2sdk.v3.Bucket.create_file` would try to find unfinished large file with matching plan info in its file info. If there is one or more such unfinished large files, :meth:`b2sdk.v3.Bucket.create_file` would verify checksums for all locally available parts and choose any matching candidate. If all candidates fails on uploaded parts checksums verification, process is interrupted and error raises. In such case corrupted unfinished large files should be cancelled manullay and :meth:`b2sdk.v3.Bucket.create_file` should be retried, or auto continuation should be turned off with `auto_continue=False` +In other cases plan information would be generated and :meth:`b2sdk.v3.Bucket.create_file` would try to find unfinished large file with matching plan info in its file info. If there is one or more such unfinished large files, :meth:`b2sdk.v3.Bucket.create_file` would verify checksums for all locally available parts and choose any matching candidate. If all candidates fail on uploaded parts checksums verification, process is interrupted and error raises. In such case corrupted unfinished large files should be cancelled manually and :meth:`b2sdk.v3.Bucket.create_file` should be retried, or auto continuation should be turned off with `auto_continue=False` No continuation diff --git a/doc/source/api/exception.rst b/doc/source/api/exception.rst index 4a0396d93..30e1bcca9 100644 --- a/doc/source/api/exception.rst +++ b/doc/source/api/exception.rst @@ -1,8 +1,55 @@ Exceptions ========== -.. todo:: - improve documentation of exceptions, automodule -> autoclass? +Every error raised by **b2sdk** derives from :class:`b2sdk.v3.exception.B2Error`, so catching that one +class is enough to catch anything the library raises deliberately. + +How to catch them +----------------- + +The hierarchy is arranged so you can be as specific as you need. Catch a named class when you intend to +handle that exact condition, and fall back to a broader one otherwise: + +.. code-block:: python + + >>> from b2sdk.v3.exception import B2Error, NonExistentBucket + + >>> try: + bucket = b2_api.get_bucket_by_name('no-such-bucket') + except NonExistentBucket: + ... # handle this specific case + except B2Error as e: + print(e) # anything else the SDK raises + +.. warning:: + The hierarchy may gain intermediate classes in a backwards-compatible release, so an exception's + direct parent is not guaranteed to stay the same. Use ``isinstance`` and ``super()`` rather than + naming a parent class explicitly. See :ref:`interface version compatibility + `. + +Deciding whether to retry +------------------------- + +Errors carry their own retry advice, so you rarely need to inspect status codes yourself: + +* ``should_retry_http()`` is true when the failed HTTP call is worth repeating. +* ``should_retry_upload()`` is true when the upload should be retried after obtaining a fresh upload URL. +* ``retry_after_seconds`` is set when the server asked the client to wait before issuing more requests. + When it is present, honour it rather than retrying immediately. + +**b2sdk** already applies this logic internally for its own transfers, so these are relevant mainly if +you are driving the lower-level API yourself. + +Two conveniences +---------------- + +Every error has a ``prefix`` property giving a readable name derived from the class name, which is what +makes the default messages presentable to end users. And +:func:`b2sdk.v3.exception.interpret_b2_error` turns a raw B2 error response into the appropriate +exception class, which is the function responsible for the hierarchy below being raised at all. + +Reference +--------- .. automodule:: b2sdk.v3.exception :members: diff --git a/doc/source/api/progress.rst b/doc/source/api/progress.rst index 95f3c4434..6a1daf800 100644 --- a/doc/source/api/progress.rst +++ b/doc/source/api/progress.rst @@ -1,13 +1,67 @@ Progress reporters ================== -.. note:: - Concrete classes described in this chapter implement methods defined in ``AbstractProgressListener`` +**b2sdk** reports progress through two separate mechanisms, and which one you want depends on what you +are doing. + +For **a single transfer** - one upload, download or copy - pass a *progress listener* to the method. +Every such method accepts a ``progress_listener`` argument, and the classes on this page are the +available implementations. + +For **a whole sync operation**, which scans folders and then transfers many files, a single listener is +not enough. Sync instead takes a :class:`b2sdk.v3.SyncReport`, which tracks the scan and comparison +phases as well as the transfers. See :ref:`sync` for how to use it. + +Choosing a listener +------------------- + +.. list-table:: + :header-rows: 1 + :widths: 34 66 + + * - Class + - When to use it + * - :class:`b2sdk.v3.TqdmProgressListener` + - Interactive use. Draws a progress bar, and needs the ``tqdm`` package installed. + * - :class:`b2sdk.v3.SimpleProgressListener` + - Interactive use without ``tqdm``. Prints plain percentages. + * - :class:`b2sdk.v3.DoNothingProgressListener` + - Non-interactive use - servers, scripts, tests. Discards everything. + * - :class:`b2sdk.v3.ProgressListenerForTest` + - Test support. Records the calls it receives so they can be asserted on. + +If you do not want to choose, :func:`b2sdk.v3.make_progress_listener` picks for you: it returns +``DoNothingProgressListener`` when ``quiet`` is set, ``TqdmProgressListener`` when ``tqdm`` is +importable, and ``SimpleProgressListener`` otherwise. -.. todo:: - improve documentation of progress reporters +.. code-block:: python - include info about sync progress + >>> from b2sdk.v3 import make_progress_listener + + >>> with make_progress_listener('uploading backup.tar', quiet=False) as listener: + bucket.upload_local_file( + local_file='backup.tar', + file_name='backup.tar', + progress_listener=listener, + ) + +Writing your own +---------------- + +Subclass :class:`b2sdk.v3.AbstractProgressListener` and implement ``set_total_bytes`` and +``bytes_completed``. Two details of the contract are easy to get wrong: + +* ``set_total_bytes`` is always called before the listener is entered, but **may be called again** if a + transfer is retried. +* ``bytes_completed`` receives a **running total, not a delta**, and that total **can go down**, because + a failed transfer restarts from the beginning. Do not accumulate the values you are given. + +Listeners are context managers, and ``close`` must be called exactly once - it asserts if called twice - +so prefer a ``with`` block over calling it yourself. + +.. note:: + The concrete classes on this page all implement the methods defined by + :class:`b2sdk.v3.AbstractProgressListener`. .. autoclass:: b2sdk.v3.AbstractProgressListener :inherited-members: diff --git a/doc/source/api/replication/monitoring.rst b/doc/source/api/replication/monitoring.rst new file mode 100644 index 000000000..a3b74207a --- /dev/null +++ b/doc/source/api/replication/monitoring.rst @@ -0,0 +1,19 @@ +.. _replication_monitoring: + +Replication monitoring +====================== + +.. autoclass:: b2sdk.v3.ReplicationMonitor() + :members: + :exclude-members: source_folder, destination_folder + :special-members: __init__ + +.. autoclass:: b2sdk.v3.ReplicationScanResult() + :inherited-members: + :members: + +``ReplicationReport`` is a :class:`b2sdk.v3.CountAndSampleScanReport` whose results are +:class:`b2sdk.v3.ReplicationScanResult` instances. It groups scanned files by result rather than +listing them: ``counter_by_status`` counts the files sharing each result, while +``samples_by_status_first`` and ``samples_by_status_last`` hold the first and last example seen for +each. See :ref:`replication` for how to read one. diff --git a/doc/source/api/replication/setting.rst b/doc/source/api/replication/setting.rst new file mode 100644 index 000000000..ff6992d03 --- /dev/null +++ b/doc/source/api/replication/setting.rst @@ -0,0 +1,17 @@ +.. _replication_setting: + +Replication settings +==================== + +.. autoclass:: b2sdk.v3.ReplicationConfiguration() + :inherited-members: + :members: + :special-members: __init__ + +.. autoclass:: b2sdk.v3.ReplicationRule() + :inherited-members: + :members: + :special-members: __init__ + +.. autoclass:: b2sdk.v3.ReplicationConfigurationFactory() + :no-members: diff --git a/doc/source/api/replication/setup.rst b/doc/source/api/replication/setup.rst new file mode 100644 index 000000000..786f929c0 --- /dev/null +++ b/doc/source/api/replication/setup.rst @@ -0,0 +1,8 @@ +.. _replication_setup: + +Replication setup helper +======================== + +.. autoclass:: b2sdk.v3.ReplicationSetupHelper() + :members: + :special-members: __init__ diff --git a/doc/source/api/replication/types.rst b/doc/source/api/replication/types.rst new file mode 100644 index 000000000..bb28b4a23 --- /dev/null +++ b/doc/source/api/replication/types.rst @@ -0,0 +1,8 @@ +.. _replication_types: + +Replication types +================= + +.. autoclass:: b2sdk.v3.ReplicationStatus() + :inherited-members: + :members: diff --git a/doc/source/api_reference.rst b/doc/source/api_reference.rst index e449307a4..3825eb33f 100644 --- a/doc/source/api_reference.rst +++ b/doc/source/api_reference.rst @@ -37,6 +37,10 @@ Public API api/transfer/outbound/outbound_source api/encryption/setting api/encryption/types + api/replication/setting + api/replication/setup + api/replication/monitoring + api/replication/types .. _api_internal: diff --git a/doc/source/api_types.rst b/doc/source/api_types.rst index 3995def72..86fc279c6 100644 --- a/doc/source/api_types.rst +++ b/doc/source/api_types.rst @@ -74,6 +74,40 @@ Those modules will generally not change in a backwards-incompatible way between .. note:: ``b2sdk.*._something`` and ``b2sdk.*.*._something``, while having a name beginning with an underscore, are **NOT** considered public interface. +Importable is not the same as public +==================================== + +The versioned namespace re-exports a considerably larger surface than the public interface. Alongside +the classes documented here, ``b2sdk.v3`` carries low-level HTTP machinery, test simulators, +transfer-manager internals, module-level constants, and a few names that are merely an artefact of +star-imports - ``annotations``, leaked from ``from __future__ import annotations``, is one. Most of the +names in the namespace are not mentioned anywhere in this documentation. + +**Being importable from** ``b2sdk.v3`` **is therefore not a compatibility promise.** To find out where a +name stands, look it up in the :doc:`API Reference `: + +.. list-table:: + :header-rows: 1 + :widths: 26 74 + + * - Where the name appears + - What is promised + * - :ref:`Public API ` + - Public interface. Pin the major version. + * - :ref:`Internal API ` + - Documented, but may change in a non-major release. Pin the middle version. + * - Neither + - No compatibility promise. It may be renamed or removed in any release. + +A name in the third group has not necessarily been judged internal - classifying the namespace is still +in progress. Treat the absence of documentation as the absence of a promise, rather than as a statement +about what the name is meant to be. If you depend on such a name, please file an issue so it can be +considered for the public interface instead of being relied on as an incidental re-export. + +The current contents of the namespace can be listed with:: + + python -c "import b2sdk.v3; print(sorted(n for n in vars(b2sdk.v3) if not n.startswith('_')))" + .. _internal_interface: ****************** diff --git a/doc/source/contributing.rst b/doc/source/contributing.rst index 03c33fe9a..746762590 100644 --- a/doc/source/contributing.rst +++ b/doc/source/contributing.rst @@ -20,11 +20,50 @@ We encourage outside contributors to perform changes on our codebase. Many such * runs all sorts of linters * checks if the Python distribution can be built - * runs all tests on a matrix of 8 versions of Python (including pypy) and 3 operating systems (Linux, Mac OS X and Windows) + * runs all tests on a matrix of every supported Python version (CPython and PyPy, see ``PYTHON_VERSIONS`` in ``noxfile.py``) across Linux, macOS and Windows * checks if the documentation can be built properly * maintain other Continuous Integration tools (coverage tracker) +Versioning +############# + +This package's versions adhere to `Semantic Versioning `_, and the +versions are established by reading git tags, i.e. no code or manifest file changes are required when +working on PRs. + +Changelog +############# + +Each PR needs to have at least one changelog (aka news) item added. This is done by creating files in +``changelog.d``. `towncrier `_ is used for compiling these files into +``CHANGELOG.md``. There are several types of changes (news): + +#. ``fixed`` +#. ``changed`` +#. ``added`` +#. ``deprecated`` +#. ``removed`` +#. ``infrastructure`` +#. ``doc`` + +The ``changelog.d`` file name convention is: + +#. If the PR closes a GitHub issue: ``{issue_number}.{type}.md``, e.g. ``157.fixed.md``. Note that the + change description still has to be complete; linking an issue is just there for convenience. A change + like ``fixed #157`` will not be accepted. +#. If the PR is not related to a GitHub issue: ``+{unique_string}.{type}.md``, e.g. ``+foobar.fixed.md``. + +These files can either be created manually, or using ``towncrier``, e.g.:: + + $ towncrier create -c 'write your description here' 157.fixed.md + +``towncrier create`` also takes care of duplicates automatically (if there is more than one news fragment +of one type for a given GitHub issue). + +Developer info +############## + You'll need to have `nox `_ and `uv `_ installed: * ``pip install nox uv`` @@ -36,10 +75,14 @@ With ``nox``, you can run different sessions (default are ``lint`` and ``test``) * ``test`` (``test-3.10``, ``test-3.11``, ``test-3.12``, ``test-3.13``, ``test-3.14``, ``test-pypy3.10``) -> Run test suite. * ``cover`` -> Perform coverage analysis. * ``build`` -> Build the distribution. -* ``deploy`` -> Deploy the distribution to the PyPi. * ``doc`` -> Build the documentation. * ``doc_cover`` -> Perform coverage analysis for the documentation. +Releases are not published from a ``nox`` session. The *Continuous Delivery* GitHub Actions +workflow (``.github/workflows/cd.yml``) builds the distribution when a version tag is pushed, +creates a GitHub release, and uploads it to PyPI for non-prerelease versions. The release +procedure itself is described in ``README.release.md``. + For example:: $ nox -s format @@ -68,6 +111,17 @@ With the above setting, session ``test`` will run on Python 3.12 and 3.14, and a Given Python interpreters should be installed in the operating system or via `pyenv `_. +Managing dependencies +##################### + +We use `uv `_ for managing dependencies and developing locally. If you want +to change any of the project requirements (or requirement bounds) in ``pyproject.toml``, make sure that +the ``uv.lock`` file reflects those changes by using ``uv add``, ``uv lock`` or other commands - see the +`uv documentation `_. You can verify that the lock file is up to date by +running:: + + $ uv lock --check + Linting ############# @@ -97,6 +151,75 @@ To run just integration tests:: $ export B2_TEST_APPLICATION_KEY_ID=your_app_key_id $ nox -s integration-3.10 +To run tests matching a keyword expression:: + + $ nox -s unit-3.10 -- -k keyword + +Where to put a new test +======================= + +**b2sdk** keeps several numbered interfaces (``b2sdk.v0`` through ``b2sdk.v3``) working at the same +time, and the unit suite is what holds that promise. ``nox -s unit`` therefore runs ``pytest`` once per +interface version - ``--api=v3``, then ``v2``, ``v1`` and ``v0`` - so a single shared test is executed +four times, once against each interface. + +Two mechanisms make that work: + +* ``pytest`` gains an ``--api`` option, defaulting to the newest version. It puts + ``test/unit//apiver`` on ``sys.path``, so a shared test can write + ``from apiver_deps import B2Api`` and receive whichever interface is under test. The ``apiver`` and + ``apiver_int`` fixtures expose that version as ``"v2"`` or ``2`` respectively. +* Tests living under a *different* version's directory are not collected. Running with ``--api=v3`` + skips ``test/unit/v0``, ``v1`` and ``v2`` entirely. + +Choose a location accordingly: + +.. list-table:: + :header-rows: 1 + :widths: 28 22 50 + + * - Location + - Collected for + - Use it for + * - ``test/unit//``, e.g. ``bucket``, ``api``, ``sync`` + - every interface version + - The default home. Behaviour shared by all interfaces - in practice, anything implemented in + ``b2sdk/_internal``. Import through ``apiver_deps``. + * - ``test/unit/v0`` … ``test/unit/v3`` + - only its own version + - Behaviour that exists in exactly one interface, such as a legacy constructor argument or an + older return type preserved by a compatibility adapter. + * - ``test/unit/v_all/`` + - every interface version + - Assertions about the interfaces themselves - that a name is still exported, or that two + versions agree. + * - ``test/integration/`` + - not run by ``nox -s unit`` + - End-to-end behaviour against real B2. Requires credentials, so it cannot gate every PR. + +If a shared test applies to only some versions, keep it in the shared directory and mark it rather than +copying it into each version directory:: + + @pytest.mark.apiver(1) # only v1 + @pytest.mark.apiver(1, 3) # only v1 and v3 + @pytest.mark.apiver(from_ver=2) # v2 and newer + @pytest.mark.apiver(to_ver=2) # v2 and older + +``from_ver`` and ``to_ver`` are inclusive, and a single mark may not mix positional and keyword +arguments. Marks also work on individual ``pytest.param`` entries, which is the usual way to assert that +an older interface raises a different exception than a newer one. When a module-level ``pytestmark`` and +a test-level mark disagree, the test is skipped unless *both* conditions allow it. See +``test/unit/conftest.py`` for the full behaviour. + +When you change something in ``b2sdk/_internal``, check that: + +#. the regression test sits in a shared directory, so it runs for every interface, and not in a single + version directory where it would silently cover only one; +#. it imports from ``apiver_deps`` rather than a fixed ``b2sdk.vN``; +#. any interface that deliberately keeps the old behaviour has a test asserting that, placed in that + version's directory or marked with ``apiver``; +#. ``nox -s unit`` passes - a suite that passes only for the newest interface is not enough. + Documentation ############# diff --git a/doc/source/index.rst b/doc/source/index.rst index f1f2f61fa..772ad9ada 100644 --- a/doc/source/index.rst +++ b/doc/source/index.rst @@ -16,26 +16,18 @@ to provide command-line access to the B2 service, but there are many possible ap Why use b2sdk? ######################################### -.. todo:: - delete doc/source/b2sdk? +When building an application which uses B2 cloud, it is possible to implement an independent B2 API client, but using **b2sdk** gives you: -.. todo:: - describe raw_simulator in detail - -.. todo:: - fix list consistency style in "Why use b2sdk?", add links - -When building an application which uses B2 cloud, it is possible to implement an independent B2 API client, but using **b2sdk** allows for: - -- reuse of code that is already written, with hundreds of unit tests -- use of **Synchronizer**, a high-performance, parallel rsync-like utility -- developer-friendly library :ref:`api version policy ` which guards your program against incompatible changes -- `B2 integration checklist `_ is passed automatically -- **raw_simulator** makes it easy to mock the B2 cloud for unit testing purposes -- reporting progress of operations to an object of your choice -- exception hierarchy makes it easy to display informative messages to users -- interrupted transfers are automatically continued -- **b2sdk** has been developed for 3 years before it version 1.0.0 was released. It's stable and mature. +- code that is already written and covered by hundreds of unit tests +- :ref:`Synchronizer `, a high-performance, parallel rsync-like utility +- :ref:`Replication ` support, for keeping a second bucket up to date automatically +- a developer-friendly :ref:`api version policy ` that guards your program against incompatible changes +- automatic compliance with the `B2 integration checklist `_ +- :doc:`raw_simulator `, which mocks the B2 cloud so you can unit test without network access +- :doc:`progress reporting ` to an object of your choice +- an :doc:`exception hierarchy ` that makes it easy to show users informative messages +- automatic continuation of interrupted transfers +- a stable and mature codebase, in development for years before its 1.0.0 release ######################################### @@ -48,6 +40,7 @@ Documentation index tutorial quick_start server_side_encryption + replication advanced glossary api_types diff --git a/doc/source/install.rst b/doc/source/install.rst index 159ea3332..1b2d75ea1 100644 --- a/doc/source/install.rst +++ b/doc/source/install.rst @@ -15,8 +15,15 @@ In order to properly set a dependency, see :ref:`versioning chapter `_ and +`uv `_ to manage test and documentation environments. See +:ref:`contributors_guide` for the full development setup. diff --git a/doc/source/quick_start.rst b/doc/source/quick_start.rst index 4c74ecebc..2950ea88c 100644 --- a/doc/source/quick_start.rst +++ b/doc/source/quick_start.rst @@ -50,14 +50,18 @@ Synchronization ) >>> no_progress = False - >>> encryption_settings_provider = BasicSyncEncryptionSettingsProvider({ - 'bucket1': EncryptionSettings(mode=EncryptionMode.SSE_B2), - 'bucket2': EncryptionSettings( + >>> bucket_settings = { + 'bucket1': EncryptionSetting(mode=EncryptionMode.SSE_B2), + 'bucket2': EncryptionSetting( mode=EncryptionMode.SSE_C, - key=EncryptionKey(secret=b'VkYp3s6v9y$B&E)H@McQfTjWmZq4t7w!', id='user-generated-key-id') + key=EncryptionKey(secret=b'VkYp3s6v9y$B&E)H@McQfTjWmZq4t7w!', key_id='user-generated-key-id') ), 'bucket3': None, - }) + } + >>> encryption_settings_provider = BasicSyncEncryptionSettingsProvider( + read_bucket_settings=bucket_settings, + write_bucket_settings=bucket_settings, + ) >>> with SyncReport(sys.stdout, no_progress) as reporter: synchronizer.sync_folders( source_folder=source, @@ -176,7 +180,7 @@ Upload file >>> bucket.upload_local_file( local_file=local_file_path, file_name=b2_file_name, - file_infos=file_info, + file_info=file_info, ) @@ -194,14 +198,14 @@ Upload file encrypted with SSE-C >>> file_info = {'how': 'good-file'} >>> encryption_setting = EncryptionSetting( mode=EncryptionMode.SSE_C, - key=EncryptionKey(secret=b'VkYp3s6v9y$B&E)H@McQfTjWmZq4t7w!', id='user-generated-key-id'), + key=EncryptionKey(secret=b'VkYp3s6v9y$B&E)H@McQfTjWmZq4t7w!', key_id='user-generated-key-id'), ) >>> bucket = b2_api.get_bucket_by_name(bucket_name) >>> bucket.upload_local_file( local_file=local_file_path, file_name=b2_file_name, - file_infos=file_info, + file_info=file_info, encryption=encryption_setting, ) @@ -337,7 +341,7 @@ Update file lock configuration >>> file_id = '4_z5485a1682662eb3e60980d10_f113f963288e711a6_d20190404_m065910_c002_v0001095_t0044' >>> file_name = 'dummy.pdf' >>> b2_api.update_file_legal_hold(file_id, file_name, LegalHold.ON) - >>> b2_api.update_file_legal_hold( + >>> b2_api.update_file_retention( file_id, file_name, FileRetentionSetting(RetentionMode.GOVERNANCE, int(time.time() + 100)*1000)) @@ -497,10 +501,10 @@ Update file lock >>> # equivalent to >>> b2_api.update_file_legal_hold(file_version.id_, file_version.file_name, LegalHold.ON) >>> b2_api.update_file_legal_hold(download_version.id_, download_version.file_name, LegalHold.ON) - >>> b2_api.update_file_legal_hold( + >>> b2_api.update_file_retention( file_version.id_, file_version.file_name, FileRetentionSetting(RetentionMode.GOVERNANCE, int(time.time() + 100)*1000)) - >>> b2_api.update_file_legal_hold( + >>> b2_api.update_file_retention( download_version.id_, download_version.file_name, FileRetentionSetting(RetentionMode.GOVERNANCE, int(time.time() + 100)*1000)) diff --git a/doc/source/replication.rst b/doc/source/replication.rst new file mode 100644 index 000000000..ebfd1fd16 --- /dev/null +++ b/doc/source/replication.rst @@ -0,0 +1,236 @@ +.. _replication: + +######################## +Replication +######################## + +Replication asks B2 to copy files from one bucket to another automatically, as they are uploaded. The +bucket being copied *from* is the **source**; the bucket being copied *to* is the **destination**. One +bucket may be both at once, and a source bucket may replicate to several destinations under different +rules. + +Replication is configured on the buckets, not on individual files: you attach a +:class:`b2sdk.v3.ReplicationConfiguration` to each side, and B2 does the copying. The SDK's job is to +help you write that configuration, create the application keys it needs, and inspect the outcome. + +.. note:: + Replication only applies to files uploaded *after* a rule starts matching them. To bring across + files that already exist, set ``include_existing_files=True`` on the rule. + +********************** +What replication needs +********************** + +Both sides need an application key, and the two sides need different capabilities: + +.. list-table:: + :header-rows: 1 + :widths: 20 80 + + * - Side + - Capabilities + * - Source + - ``readFiles``, ``readFileLegalHolds``, ``readFileRetentions`` + * - Destination + - ``writeFiles``, ``writeFileLegalHolds``, ``writeFileRetentions``, ``deleteFiles`` + +The source bucket's configuration records the id of the source key. The destination bucket's +configuration maps each incoming source key id to the destination key that should be used for it - that +mapping is how a destination bucket authorises a particular source to write into it. + +If the two buckets live in different accounts, you will need a separate :class:`b2sdk.v3.B2Api` +instance for each. + +********************** +Setting up replication +********************** + +Using the setup helper +====================== + +:class:`b2sdk.v3.ReplicationSetupHelper` is the supported path. It creates both application keys, adds +the rule to the source, and registers the key mapping on the destination: + +.. code-block:: python + + >>> from b2sdk.v3 import ReplicationSetupHelper + + >>> source_bucket = b2_api.get_bucket_by_name('source-bucket') + >>> destination_bucket = b2_api.get_bucket_by_name('destination-bucket') + + >>> rsh = ReplicationSetupHelper() + >>> source_bucket, destination_bucket = rsh.setup_both( + source_bucket=source_bucket, + destination_bucket=destination_bucket, + name='my-rule', + prefix='folder/', + ) + +It returns the two updated buckets, so use the returned objects rather than the ones you passed in. + +The keys it creates are named after the buckets, suffixed ``-replisrc`` and ``-replidst``. If a rule is +already present, the helper places the new one ahead of the existing rules rather than overwriting +them. + +The two halves are also available separately, which is what you need when the buckets are on different +accounts - run :meth:`~b2sdk.v3.ReplicationSetupHelper.setup_destination` against the destination +account first, then :meth:`~b2sdk.v3.ReplicationSetupHelper.setup_source` against the source account +with the resulting key. + +Writing the configuration by hand +================================= + +When you need full control, build the configuration yourself and pass it to +:meth:`b2sdk.v3.Bucket.update` (or to :meth:`b2sdk.v3.B2Api.create_bucket` for a new bucket). You are +then responsible for creating the application keys with the capabilities listed above. + +.. code-block:: python + + >>> from b2sdk.v3 import ReplicationConfiguration, ReplicationRule + + >>> source_bucket.update( + replication=ReplicationConfiguration( + rules=[ + ReplicationRule( + destination_bucket_id=destination_bucket.id_, + name='my-rule', + file_name_prefix='folder/', + ), + ], + source_key_id=source_key.id_, + ), + ) + + >>> destination_bucket.update( + replication=ReplicationConfiguration( + source_to_destination_key_mapping={ + source_key.id_: destination_key.id_, + }, + ), + ) + +A few constraints are enforced when the objects are constructed, so you will hear about mistakes before +a request is sent: + +* a rule ``name`` must match ``[a-zA-Z0-9_-]`` and be at most 64 characters; +* ``destination_bucket_id`` is required; +* ``priority`` must be between 1 and 2\ :sup:`31`\ -1, and defaults to 128 - lower numbers are + evaluated first, and the first matching rule wins; +* a configuration that has ``rules`` must also have a ``source_key_id``. + +Inspecting what is configured +============================= + +``bucket.replication`` is either ``None`` or a :class:`b2sdk.v3.ReplicationConfiguration`. Because one +bucket can be both ends of a replication relationship, ask which role it plays: + +.. code-block:: python + + >>> bucket.replication.is_source + True + >>> bucket.replication.is_destination + False + >>> [rule.name for rule in bucket.replication.rules] + ['my-rule'] + +******************** +Checking on progress +******************** + +Per-file status +=============== + +A file version carries a :class:`b2sdk.v3.ReplicationStatus`, which is one of: + +.. list-table:: + :header-rows: 1 + :widths: 18 82 + + * - Status + - Meaning + * - ``PENDING`` + - On the source, and not yet copied to every destination. + * - ``COMPLETED`` + - On the source, and copied successfully. + * - ``FAILED`` + - On the source, and B2 will not retry. Needs investigation. + * - ``REPLICA`` + - This file *is* a copy - the status you see on the destination side. + +A source file whose status stays ``PENDING`` is usually still in flight. ``FAILED`` is terminal, and the +common causes are a key that no longer has the required capabilities, a destination key mapping that +does not match the source key in use, or a file the destination refuses because of its own lock +settings. + +Monitoring a rule +================= + +:class:`b2sdk.v3.ReplicationMonitor` walks one rule and reports what it finds on both sides: + +.. code-block:: python + + >>> from b2sdk.v3 import ReplicationMonitor + + >>> rule = source_bucket.replication.rules[0] + >>> monitor = ReplicationMonitor(bucket=source_bucket, rule=rule) + >>> report = monitor.scan() + +The monitor scans the source and, by default, the matching files on the destination so it can compare +them. Pass ``scan_destination=False`` to look at the source alone, which is much cheaper. + +Two optional arguments matter in practice. ``destination_api`` takes a second +:class:`b2sdk.v3.B2Api`, and is required when the destination bucket is on another account; omit it and +the source bucket's own API is used. ``scan_policies_manager`` takes a +:class:`b2sdk.v3.ScanPoliciesManager`, letting you skip files you do not care about. + +The monitor validates its arguments on construction: it raises ``ValueError`` if the bucket has no +replication configuration at all, or if the rule you passed does not belong to that bucket's +configuration. + +Reading the report +================== + +:meth:`~b2sdk.v3.ReplicationMonitor.scan` returns a :class:`b2sdk.v3.ReplicationReport`. Rather than a +flat list of files, it groups them: ``counter_by_status`` counts how many files share each distinct +:class:`b2sdk.v3.ReplicationScanResult`, and ``samples_by_status_first`` and ``samples_by_status_last`` +hold the first and last example seen for each, so you have something concrete to go and look at. + +.. code-block:: python + + >>> for result, count in report.counter_by_status.most_common(): + print(count, result.source_replication_status, result.destination_replication_status) + +A scan result describes a source/destination *pair*, and the fields fall into three groups: + +* what the source file looks like - ``source_replication_status``, ``source_has_hide_marker``, + ``source_encryption_mode``, ``source_has_large_metadata``, ``source_has_file_retention``, + ``source_has_legal_hold``; +* what the destination file looks like - ``destination_replication_status``; +* how the two compare - ``metadata_differs``, ``hash_differs``. + +Any of these may be ``None``, which means "not known" rather than "false" - typically because only one +side of the pair exists, or because the destination was not scanned. + +Interpreting partial results +============================ + +A scan is a snapshot of a system that is still moving, so mixed results are normal rather than a sign of +failure: + +* **A destination file is missing entirely.** The destination fields are ``None``. Expected while a file + is still ``PENDING``; worth investigating once the source reads ``COMPLETED``. +* **``hash_differs`` is true.** The two sides hold different content. This is briefly normal if the + source file was replaced while the scan was running, and a real problem otherwise. +* **``metadata_differs`` is true.** The content matches but the file info does not. Large metadata is the + usual cause - see ``source_has_large_metadata``, since B2 will not replicate metadata beyond a size + limit. +* **``source_has_legal_hold`` or ``source_has_file_retention`` is set.** Copying these requires the + ``*FileLegalHolds`` and ``*FileRetentions`` capabilities on *both* keys. Keys created by hand without + them are a common cause of ``FAILED``. + +.. note:: + Only the latest version of each file is inspected. Earlier versions are not represented in a report, + so a clean scan is not a statement about a bucket's whole version history. + +For the full signatures of everything above, see :ref:`replication_setting`, :ref:`replication_setup`, +:ref:`replication_monitoring` and :ref:`replication_types`. From 07674d4834a97d0da6366dbee21a0241d95f2792 Mon Sep 17 00:00:00 2001 From: Felipe Fumero Date: Fri, 20 Nov 2026 13:53:06 -0600 Subject: [PATCH 029/113] Remove stale C4 known-defect demonstrators (#690) * test: remove stale C4 known-defect demonstrators The C4 quick-start and install-doc defects are fixed on master: quick_start.rst no longer uses the non-existent EncryptionSettings class and calls EncryptionKey with key_id=, and install.rst installs the development version from the checkout. The three @known_defect('C4', ...) demonstrators therefore XPASS(strict) and fail 'pytest test/static' in the lint session on every PR. Remove them and their C4-only helper regexes. * chore: add changelog fragment for C4 demonstrator removal --- ...e-stale-c4-demonstrators.infrastructure.md | 1 + test/static/test_regression_repo_checks.py | 38 ------------------- 2 files changed, 1 insertion(+), 38 deletions(-) create mode 100644 changelog.d/+remove-stale-c4-demonstrators.infrastructure.md diff --git a/changelog.d/+remove-stale-c4-demonstrators.infrastructure.md b/changelog.d/+remove-stale-c4-demonstrators.infrastructure.md new file mode 100644 index 000000000..465c2864a --- /dev/null +++ b/changelog.d/+remove-stale-c4-demonstrators.infrastructure.md @@ -0,0 +1 @@ +Remove the stale C4 known-defect test demonstrators, whose quick-start and install-documentation defects are already fixed, so the static test suite no longer fails with XPASS(strict). diff --git a/test/static/test_regression_repo_checks.py b/test/static/test_regression_repo_checks.py index ff028501b..0fe61c387 100644 --- a/test/static/test_regression_repo_checks.py +++ b/test/static/test_regression_repo_checks.py @@ -52,44 +52,6 @@ def test_c59_readme_mentions_full_extra(): assert re.search(r'b2sdk\[full\]', _read('README.md')), 'README does not mention b2sdk[full]' -# an EncryptionKey(...) call whose arguments contain `id=`; quoted strings are skipped as a whole, -# so a ")" inside the secret does not end the argument list early -ENCRYPTION_KEY_WITH_ID = re.compile(r"""EncryptionKey\((?:[^()'"]|'[^']*'|"[^"]*")*?\bid=""") -# installs the local checkout (`pip install .` or `pip install -e .`), not a package index or a URL -PIP_INSTALL_CHECKOUT = re.compile(r'pip install (?:-e\s+)?\.(?:\[[^\]]*\])?(?=\s|$)') - - -@known_defect('C4', 'the Quick Start uses a class that does not exist', raises=AssertionError) -def test_c4_quick_start_does_not_use_encryption_settings_class(): - """C4: Quick Start must not use the non-existent class EncryptionSettings.""" - assert 'EncryptionSettings(' not in _read( - 'doc/source/quick_start.rst' - ), 'EncryptionSettings does not exist' - - -@known_defect( - 'C4', - 'the Quick Start uses an EncryptionKey argument that does not exist', - raises=AssertionError, -) -def test_c4_quick_start_uses_key_id_argument_of_encryption_key(): - """C4: Quick Start must call EncryptionKey with `key_id=`, which is the argument it has.""" - assert not ENCRYPTION_KEY_WITH_ID.search( - _read('doc/source/quick_start.rst') - ), 'EncryptionKey has no id= argument' - - -@known_defect( - 'C4', - 'the development-version install instructions install from PyPI, not the checkout', - raises=AssertionError, -) -def test_c4_install_doc_development_version_installs_from_checkout(): - """C4: 'Installing a development version' must install the checkout, not PyPI.""" - section = _read('doc/source/install.rst').split('Installing a development version', 1)[1] - assert PIP_INSTALL_CHECKOUT.search(section), 'development-version section installs from PyPI' - - @known_defect( 'C36', 'importing b2sdk fails when the package metadata is not installed', From 139899d16c629fc1dbd57e233b9781552e21d175 Mon Sep 17 00:00:00 2001 From: Felipe Fumero Date: Fri, 20 Nov 2026 14:57:44 -0600 Subject: [PATCH 030/113] fix: bound retry-after delays (#694) --- b2sdk/_internal/exception.py | 20 +++- changelog.d/+retry-after-bounds.fixed.md | 1 + test/unit/b2http/test_retry_after_bounds.py | 112 ++++++++++++++++++++ 3 files changed, 131 insertions(+), 2 deletions(-) create mode 100644 changelog.d/+retry-after-bounds.fixed.md create mode 100644 test/unit/b2http/test_retry_after_bounds.py diff --git a/b2sdk/_internal/exception.py b/b2sdk/_internal/exception.py index 797fe9552..090b32915 100644 --- a/b2sdk/_internal/exception.py +++ b/b2sdk/_internal/exception.py @@ -27,12 +27,28 @@ logger = logging.getLogger(__name__) +# Keep server-requested waits bounded while preserving ordinary delays. +_MAX_RETRY_AFTER_SECONDS = 300 + + def _parse_retry_after_seconds(retry_after_seconds): - """Return Retry-After delay-seconds, ignoring HTTP-date and invalid forms.""" + """Return bounded Retry-After delay-seconds, ignoring dates and invalid forms.""" + if isinstance(retry_after_seconds, str): + text = retry_after_seconds.strip() + negative = text.startswith('-') + digits = text[1:] if text[:1] in ('+', '-') else text + if digits.isascii() and digits.isdecimal(): + digits = digits.lstrip('0') + if not digits or negative: + return 0 + if len(digits) > len(str(_MAX_RETRY_AFTER_SECONDS)): + return _MAX_RETRY_AFTER_SECONDS + return min(int(digits), _MAX_RETRY_AFTER_SECONDS) try: - return int(retry_after_seconds) + delay = int(retry_after_seconds) except (TypeError, ValueError): return None + return max(0, min(delay, _MAX_RETRY_AFTER_SECONDS)) class B2Error(Exception, metaclass=ABCMeta): diff --git a/changelog.d/+retry-after-bounds.fixed.md b/changelog.d/+retry-after-bounds.fixed.md new file mode 100644 index 000000000..488259fb7 --- /dev/null +++ b/changelog.d/+retry-after-bounds.fixed.md @@ -0,0 +1 @@ +Bound server-provided retry delays to between zero and five minutes. diff --git a/test/unit/b2http/test_retry_after_bounds.py b/test/unit/b2http/test_retry_after_bounds.py new file mode 100644 index 000000000..e6a967f57 --- /dev/null +++ b/test/unit/b2http/test_retry_after_bounds.py @@ -0,0 +1,112 @@ +###################################################################### +# +# File: test/unit/b2http/test_retry_after_bounds.py +# +# Copyright 2026 Backblaze Inc. All Rights Reserved. +# +# License https://www.backblaze.com/using_b2_code.html +# +###################################################################### +from __future__ import annotations + +import pytest +import responses + +from b2sdk._internal.api_config import B2HttpApiConfig +from b2sdk._internal.b2http import B2Http + + +@pytest.mark.parametrize('status', [429, 503]) +@pytest.mark.parametrize( + 'retry_after, expected_delay', + [ + pytest.param('-5', 0, id='negative'), + pytest.param('-' + '9' * 5000, 0, id='very-long-negative'), + pytest.param('0', 0, id='zero'), + pytest.param('2', 2, id='ordinary'), + pytest.param('200', 200, id='existing-200-second-delay'), + pytest.param('300', 300, id='at-cap'), + pytest.param('301', 300, id='above-cap'), + pytest.param('999999999999999999999999', 300, id='huge'), + pytest.param('9' * 5000, 300, id='very-long-positive'), + pytest.param('0' * 5000 + '2', 2, id='very-long-zero-padding'), + pytest.param('not-a-delay', 1, id='invalid-fallback'), + pytest.param('Wed, 21 Oct 2015 07:28:00 GMT', 1, id='date-fallback'), + ], +) +@responses.activate +def test_retry_after_delay_is_bounded(status, retry_after, expected_delay, mocker): + url = 'https://api.example.invalid/resource' + responses.get( + url, + status=status, + json={'status': status, 'code': 'service_unavailable', 'message': 'retry later'}, + adding_headers={'Retry-After': retry_after}, + ) + responses.get(url, status=200, json={'ok': True}) + delays = [] + + def record_sleep(delay): + if delay < 0: + raise ValueError('sleep length must be non-negative') + delays.append(delay) + + mocker.patch('b2sdk._internal.b2http.time.sleep', side_effect=record_sleep) + http = B2Http(B2HttpApiConfig(install_clock_skew_hook=False)) + try: + response = http.request('GET', url, headers={}, try_count=2) + finally: + http.session.close() + + assert response.json() == {'ok': True} + assert len(responses.calls) == 2 + if expected_delay == 0: + assert delays in ([], [0]) + else: + assert delays == [expected_delay] + + +@pytest.mark.parametrize( + 'retry_after, expected_delay', [('-5', 0), ('999999999999999', 300), ('200', 200)] +) +@responses.activate +def test_create_rate_limit_uses_bounded_retry_after(retry_after, expected_delay, mocker): + import json + + from b2sdk._internal.raw_api import B2RawHTTPApi + + api_url = 'https://api.example.invalid' + url = api_url + '/b2api/v4/b2_create_bucket' + attempts = [] + created = [] + + def handle_create(request): + attempts.append(json.loads(request.body)) + if len(attempts) == 1: + return ( + 429, + {'Content-Type': 'application/json', 'Retry-After': retry_after}, + json.dumps({'status': 429, 'code': 'too_many_requests', 'message': 'retry later'}), + ) + created.append('bucket-id') + return 200, {'Content-Type': 'application/json'}, json.dumps({'bucketId': created[-1]}) + + responses.add_callback(responses.POST, url, callback=handle_create) + delays = [] + mocker.patch('b2sdk._internal.b2http.time.sleep', side_effect=delays.append) + http = B2Http(B2HttpApiConfig(install_clock_skew_hook=False)) + try: + result = B2RawHTTPApi(http).create_bucket( + api_url, 'synthetic-token', 'account-id', 'retry-test-bucket', 'allPrivate' + ) + finally: + http.session.close() + + assert result == {'bucketId': 'bucket-id'} + assert created == ['bucket-id'] + assert len(attempts) == 2 + assert attempts[0] == attempts[1] + if expected_delay == 0: + assert delays in ([], [0]) + else: + assert delays == [expected_delay] From 6ebf1c6ff424a131ac95013defd0c4fbb86fd5bf Mon Sep 17 00:00:00 2001 From: Felipe Fumero Date: Fri, 20 Nov 2026 14:57:57 -0600 Subject: [PATCH 031/113] fix: restore v0 file unhide (#692) --- b2sdk/_internal/bucket.py | 5 +- b2sdk/v0/bucket.py | 4 + changelog.d/+v0-unhide-file.fixed.md | 1 + test/unit/v0/test_unhide_file_legacy.py | 75 +++++++++++++++++++ test/unit/v_all/test_regression_legacy_api.py | 11 +-- 5 files changed, 85 insertions(+), 11 deletions(-) create mode 100644 changelog.d/+v0-unhide-file.fixed.md create mode 100644 test/unit/v0/test_unhide_file_legacy.py diff --git a/b2sdk/_internal/bucket.py b/b2sdk/_internal/bucket.py index 0b8986928..48e2e4a3b 100644 --- a/b2sdk/_internal/bucket.py +++ b/b2sdk/_internal/bucket.py @@ -1355,13 +1355,16 @@ def hide_file(self, file_name): response = self.api.session.hide_file(self.id_, file_name) return self.api.file_version_factory.from_api_response(response) + def _list_file_versions_for_unhide(self, file_name: str): + return self.list_file_versions(file_name=file_name, fetch_count=1) + def unhide_file(self, file_name: str, bypass_governance: bool = False) -> FileIdAndName: """ Unhide a file by deleting the "hide marker". """ # get the latest file version - file_versions = self.list_file_versions(file_name=file_name, fetch_count=1) + file_versions = self._list_file_versions_for_unhide(file_name) latest_file_version = next(file_versions, None) if latest_file_version is None: raise FileNotPresent(bucket_name=self.name, file_id_or_name=file_name) diff --git a/b2sdk/v0/bucket.py b/b2sdk/v0/bucket.py index d482f2b3f..08bb879cd 100644 --- a/b2sdk/v0/bucket.py +++ b/b2sdk/v0/bucket.py @@ -13,6 +13,10 @@ class Bucket(v1.Bucket): + def _list_file_versions_for_unhide(self, file_name: str): + # v0's public list_file_versions returns a raw response, not typed versions. + return super().list_file_versions(file_name=file_name, fetch_count=1) + def list_file_names(self, start_filename=None, max_entries=None, prefix=None): """ Legacy interface which just returns whatever remote API returns. diff --git a/changelog.d/+v0-unhide-file.fixed.md b/changelog.d/+v0-unhide-file.fixed.md new file mode 100644 index 000000000..6fc041b88 --- /dev/null +++ b/changelog.d/+v0-unhide-file.fixed.md @@ -0,0 +1 @@ +Allow the v0 bucket interface to unhide files. diff --git a/test/unit/v0/test_unhide_file_legacy.py b/test/unit/v0/test_unhide_file_legacy.py new file mode 100644 index 000000000..eff4d4f7c --- /dev/null +++ b/test/unit/v0/test_unhide_file_legacy.py @@ -0,0 +1,75 @@ +###################################################################### +# +# File: test/unit/v0/test_unhide_file_legacy.py +# +# Copyright 2026 Backblaze Inc. All Rights Reserved. +# +# License https://www.backblaze.com/using_b2_code.html +# +###################################################################### + + +import pytest + +from b2sdk._internal.exception import FileNotHidden, FileNotPresent + + +def test_v0_unhide_removes_hide_marker_and_returns_its_identity(bucket): + uploaded = bucket.upload_bytes(b'hello', 'example.txt') + marker = bucket.hide_file('example.txt') + + result = bucket.unhide_file('example.txt') + + assert result.file_id == marker.id_ + assert result.file_name == 'example.txt' + assert [(item.id_, item.action) for item, _ in bucket.ls(show_versions=True)] == [ + (uploaded.id_, 'upload') + ] + + +def test_v0_unhide_missing_exact_name_leaves_matching_prefix_untouched(bucket): + bucket.upload_bytes(b'other', 'example.txt-extra') + marker = bucket.hide_file('example.txt-extra') + with pytest.raises(FileNotPresent): + bucket.unhide_file('example.txt') + assert bucket.list_file_versions(prefix='example.txt-extra')['files'][0]['fileId'] == marker.id_ + + +def test_v0_unhide_visible_file_raises_without_deleting_it(bucket): + uploaded = bucket.upload_bytes(b'hello', 'example.txt') + with pytest.raises(FileNotHidden): + bucket.unhide_file('example.txt') + assert bucket.list_file_versions(prefix='example.txt')['files'][0]['fileId'] == uploaded.id_ + + +def test_v0_unhide_removes_only_the_latest_hide_marker(bucket): + uploaded = bucket.upload_bytes(b'hello', 'example.txt') + previous_marker = bucket.hide_file('example.txt') + latest_marker = bucket.hide_file('example.txt') + + result = bucket.unhide_file('example.txt') + + assert result.file_id == latest_marker.id_ + assert [(item.id_, item.action) for item, _ in bucket.ls(show_versions=True)] == [ + (previous_marker.id_, 'hide'), + (uploaded.id_, 'upload'), + ] + + +def test_v0_unhide_forwards_governance_flag_to_real_session(bucket, mocker): + bucket.upload_bytes(b'hello', 'example.txt') + marker = bucket.hide_file('example.txt') + delete = mocker.spy(bucket.api.session, 'delete_file_version') + + result = bucket.unhide_file('example.txt', bypass_governance=True) + + assert result.file_id == marker.id_ + delete.assert_called_once_with(marker.id_, 'example.txt', True) + + +def test_v0_list_file_versions_keeps_legacy_raw_response(bucket): + uploaded = bucket.upload_bytes(b'hello', 'example.txt') + result = bucket.list_file_versions(start_filename='example.txt', max_entries=1) + assert isinstance(result, dict) + assert result['files'][0]['fileId'] == uploaded.id_ + assert 'nextFileName' in result and 'nextFileId' in result diff --git a/test/unit/v_all/test_regression_legacy_api.py b/test/unit/v_all/test_regression_legacy_api.py index 7330df40d..c07fe93bf 100644 --- a/test/unit/v_all/test_regression_legacy_api.py +++ b/test/unit/v_all/test_regression_legacy_api.py @@ -42,20 +42,11 @@ def bucket(): @pytest.mark.apiver(0) -@known_defect('C48', 'v0 unhide_file() raises TypeError', raises=DefectStillPresent) def test_c48_v0_unhide_file_removes_hide_marker(bucket): """C48: on the v0 interface unhide_file() must not fail with a TypeError.""" bucket.upload_bytes(b'hello', 'hello.txt') bucket.hide_file('hello.txt') - # CPython names the first invalid keyword; PyPy reports both invalid keywords. - with defect_raises( - TypeError, - match=( - r"^Bucket\.list_file_versions\(\) got (?:an unexpected keyword argument 'file_name'" - r'|2 unexpected keyword arguments)$' - ), - ): - bucket.unhide_file('hello.txt') + bucket.unhide_file('hello.txt') names = [info.file_name for info, _ in bucket.ls(show_versions=False)] assert 'hello.txt' in names, names From 204b8d1c631b128f04aa212587021e7690d307c7 Mon Sep 17 00:00:00 2001 From: Felipe Fumero Date: Fri, 20 Nov 2026 14:58:10 -0600 Subject: [PATCH 032/113] Identify visited symlink targets by (device, inode), not inode alone (#686) * fix: distinguish symlink targets across devices * test: drop the now-fixed C53 symlink known-defect demonstrator The C53 fix makes the (st_dev, st_ino) loop check correct, so the known_defect demonstrator in test_regression_misc.py now XPASS(strict)es and fails the suite. The behavior is covered by the new test_symlink_device_inode.py regression test. --- b2sdk/_internal/scan/folder.py | 11 ++--- changelog.d/+symlink-device-inode.fixed.md | 1 + test/unit/scan/test_symlink_device_inode.py | 40 ++++++++++++++++++ test/unit/test_regression_misc.py | 45 --------------------- 4 files changed, 47 insertions(+), 50 deletions(-) create mode 100644 changelog.d/+symlink-device-inode.fixed.md create mode 100644 test/unit/scan/test_symlink_device_inode.py diff --git a/b2sdk/_internal/scan/folder.py b/b2sdk/_internal/scan/folder.py index 66553ea2a..3b01db592 100644 --- a/b2sdk/_internal/scan/folder.py +++ b/b2sdk/_internal/scan/folder.py @@ -201,7 +201,7 @@ def _walk_relative_paths( relative_dir_path: Path, reporter: ProgressReport, policies_manager: ScanPoliciesManager, - visited_symlinks: set[int] | None = None, + visited_symlinks: set[tuple[int, int]] | None = None, ): """ Yield a File object for each of the files anywhere under this folder, @@ -211,7 +211,7 @@ def _walk_relative_paths( :param relative_dir_path: the path of this dir relative to the scan point, or Path('') if at scan point :param reporter: a reporter object to report errors and warnings :param policies_manager: a policies manager object - :param visited_symlinks: a set of paths to symlinks that have already been visited. Using inode numbers to reduce memory usage + :param visited_symlinks: device and inode pairs for already visited symlink targets """ # Collect the names. We do this before returning any results, because @@ -230,12 +230,13 @@ def _walk_relative_paths( visited_symlinks = visited_symlinks or set() if local_dir.is_symlink(): - inode_number = local_dir.resolve().stat().st_ino - if inode_number in visited_symlinks: + target_stat = local_dir.resolve().stat() + target_id = (target_stat.st_dev, target_stat.st_ino) + if target_id in visited_symlinks: if reporter: reporter.circular_symlink_skipped(str(local_dir)) return # Skip if symlink already visited - visited_symlinks.add(inode_number) + visited_symlinks.add(target_id) try: dir_children = sorted(local_dir.iterdir()) diff --git a/changelog.d/+symlink-device-inode.fixed.md b/changelog.d/+symlink-device-inode.fixed.md new file mode 100644 index 000000000..61ae8dba2 --- /dev/null +++ b/changelog.d/+symlink-device-inode.fixed.md @@ -0,0 +1 @@ +Fixed incorrect symlink loop detection when directories on different devices have the same inode number. diff --git a/test/unit/scan/test_symlink_device_inode.py b/test/unit/scan/test_symlink_device_inode.py new file mode 100644 index 000000000..4638dfd1a --- /dev/null +++ b/test/unit/scan/test_symlink_device_inode.py @@ -0,0 +1,40 @@ +###################################################################### +# +# File: test/unit/scan/test_symlink_device_inode.py +# +# Copyright 2026 Backblaze Inc. All Rights Reserved. +# +# License https://www.backblaze.com/using_b2_code.html +# +###################################################################### +import os +from pathlib import Path + +from b2sdk._internal.scan.folder import LocalFolder + + +def test_symlink_targets_with_same_inode_on_different_devices_are_scanned(tmp_path, monkeypatch): + first = tmp_path / 'first' + second = tmp_path / 'second' + first.mkdir() + second.mkdir() + (second / 'file.txt').write_text('contents') + (first / 'next').symlink_to(second, target_is_directory=True) + root = tmp_path / 'root' + root.symlink_to(first, target_is_directory=True) + + original_stat = Path.stat + + def stat_with_device_collision(path, *args, **kwargs): + result = original_stat(path, *args, **kwargs) + if path in (first, second): + fields = list(result) + fields[1] = 12345 + fields[2] = 1 if path == first else 2 + return os.stat_result(fields) + return result + + monkeypatch.setattr(Path, 'stat', stat_with_device_collision) + files = list(LocalFolder(root).all_files(None)) + + assert [path.relative_path for path in files] == ['next/file.txt'] diff --git a/test/unit/test_regression_misc.py b/test/unit/test_regression_misc.py index c075f51cc..a05b5c4f6 100644 --- a/test/unit/test_regression_misc.py +++ b/test/unit/test_regression_misc.py @@ -19,8 +19,6 @@ from __future__ import annotations import importlib -import os -import sys from unittest import mock import pytest @@ -29,8 +27,6 @@ from apiver_deps import B2Http, B2HttpApiConfig from apiver_deps_exception import B2ConnectionError, B2RequestTimeout -from b2sdk._internal.scan.folder import LocalFolder -from b2sdk._internal.scan.policies import DEFAULT_SCAN_MANAGER from test.known_defect import DefectStillPresent, defect_raises, expect, known_defect pytestmark = [pytest.mark.apiver(from_ver=2)] @@ -42,47 +38,6 @@ def _b2_http(): return B2Http(B2HttpApiConfig(requests.Session, install_clock_skew_hook=False)) -@pytest.mark.skipif(sys.platform == 'win32', reason='needs symlinks') -class TestLocalFolderSymlinks: - @known_defect( - 'C53', - 'the symlink loop check compares only inode numbers, not devices', - raises=AssertionError, - ) - def test_c53_symlinks_to_different_devices_with_same_inode_are_not_loops(self, tmp_path): - """C53: links to directories on another device that share an inode number are not loops.""" - t1, t2 = tmp_path / 't1', tmp_path / 't2' - t1.mkdir() - t2.mkdir() - (t1 / 'f1.txt').write_text('1') - (t2 / 'f2.txt').write_text('2') - root = tmp_path / 'root' - root.mkdir() - os.symlink(t1, root / 'l1') - os.symlink( - t2, t1 / 'l2' - ) # nested link: the loop check only tracks links on the current path - - real_stat = type(t1).stat - - def fake_stat(self, *args, **kwargs): - st = real_stat(self, *args, **kwargs) - if self.name == 't2': # pretend t2 lives on another device but has t1's inode number - t1_st = real_stat(t1) - values = list(st) - values[1] = t1_st.st_ino - values[2] = t1_st.st_dev + 1 - return os.stat_result(values) - return st - - with mock.patch.object(type(t1), 'stat', fake_stat): - names = sorted( - p.relative_path - for p in LocalFolder(str(root)).all_files(None, DEFAULT_SCAN_MANAGER) - ) - assert names == ['l1/f1.txt', 'l1/l2/f2.txt'] - - class TestTypes: @known_defect( 'C31', From e4434b0176dc73a623220ec0c2fc7950b43d998f Mon Sep 17 00:00:00 2001 From: Felipe Fumero Date: Fri, 20 Nov 2026 16:30:53 -0600 Subject: [PATCH 033/113] fix: retain legacy API download configuration (#695) --- b2sdk/v1/api.py | 1 + ...+legacy-content-encoding-download.fixed.md | 1 + test/unit/v_all/test_regression_legacy_api.py | 101 +++++++++++++++--- 3 files changed, 86 insertions(+), 17 deletions(-) create mode 100644 changelog.d/+legacy-content-encoding-download.fixed.md diff --git a/b2sdk/v1/api.py b/b2sdk/v1/api.py index fafbe7d88..edad257da 100644 --- a/b2sdk/v1/api.py +++ b/b2sdk/v1/api.py @@ -68,6 +68,7 @@ def __init__( raw_api=raw_api, api_config=api_config, ) + self.api_config = api_config if api_config is not None else v2.DEFAULT_HTTP_API_CONFIG self.file_version_factory = self.FILE_VERSION_FACTORY_CLASS(self) self.download_version_factory = self.DOWNLOAD_VERSION_FACTORY_CLASS(self) self.services = Services( diff --git a/changelog.d/+legacy-content-encoding-download.fixed.md b/changelog.d/+legacy-content-encoding-download.fixed.md new file mode 100644 index 000000000..54bec6d57 --- /dev/null +++ b/changelog.d/+legacy-content-encoding-download.fixed.md @@ -0,0 +1 @@ +Allow v0 and v1 clients to download files stored with a Content-Encoding. diff --git a/test/unit/v_all/test_regression_legacy_api.py b/test/unit/v_all/test_regression_legacy_api.py index c07fe93bf..d0cf8e92c 100644 --- a/test/unit/v_all/test_regression_legacy_api.py +++ b/test/unit/v_all/test_regression_legacy_api.py @@ -7,22 +7,26 @@ # License https://www.backblaze.com/using_b2_code.html # ###################################################################### -"""Regression tests for the legacy v0/v1 interfaces. - -Tests marked with ``@known_defect`` describe a defect that is still present: they assert the correct -behaviour and are strict expected failures, so the default run stays green and fails with -"XPASS(strict)" once the defect is fixed (then remove the decorator). To see them fail, run -``pytest --runxfail -m known_defect`` (see ``test/known_defect.py``). The ``C`` identifiers are -short labels that also appear in the test names and decorators. -""" +"""Regression tests for the legacy v0/v1 interfaces.""" from __future__ import annotations +import gzip +import hashlib + import apiver_deps import pytest -from apiver_deps import B2Api, RawSimulator, StubAccountInfo +import responses +from apiver_deps import ( + DEFAULT_HTTP_API_CONFIG, + B2Api, + B2HttpApiConfig, + B2RawHTTPApi, + RawSimulator, + StubAccountInfo, +) -from test.known_defect import DefectStillPresent, defect_raises, known_defect +from b2sdk._internal.b2http import B2Http if apiver_deps.V <= 1: from apiver_deps import DownloadDestBytes @@ -51,16 +55,79 @@ def test_c48_v0_unhide_file_removes_hide_marker(bucket): assert 'hello.txt' in names, names -@known_defect( - 'C44', - 'v0/v1 clients cannot download a file stored with a Content-Encoding', - raises=DefectStillPresent, -) def test_c44_legacy_api_can_download_file_stored_with_content_encoding(bucket): """C44: v0/v1 clients must be able to download a file that has a Content-Encoding.""" data = b'compressed-looking payload' bucket.upload_bytes(data, 'enc.bin', file_infos={'b2-content-encoding': 'gzip'}) dest = DownloadDestBytes() - with defect_raises(AttributeError, match="no attribute 'api_config'"): - bucket.download_file_by_name('enc.bin', dest) + bucket.download_file_by_name('enc.bin', dest) assert dest.get_bytes_written() == data, 'wrong downloaded data' + + +@pytest.mark.parametrize('decode_content', [False, True]) +def test_legacy_api_retains_explicit_configuration(decode_content): + config = B2HttpApiConfig(decode_content=decode_content, _raw_api_class=RawSimulator) + api = B2Api(StubAccountInfo(), api_config=config) + assert api.api_config is config + + +@pytest.mark.parametrize('use_raw_api', [False, True]) +def test_legacy_api_retains_default_configuration(use_raw_api): + raw_api = RawSimulator() + kwargs = {'raw_api': raw_api} if use_raw_api else {} + api = B2Api(StubAccountInfo(), **kwargs) + assert api.api_config is DEFAULT_HTTP_API_CONFIG + if use_raw_api: + assert api.session.raw_api is raw_api + + +@pytest.mark.parametrize('decode_content', [False, True]) +@pytest.mark.parametrize('by_id', [False, True], ids=['by-name', 'by-id']) +def test_legacy_encoded_http_download_preserves_decode_setting(decode_content, by_id): + data = b'actual gzip payload' * 100 + encoded = gzip.compress(data, mtime=0) + config = B2HttpApiConfig( + decode_content=decode_content, + install_clock_skew_hook=False, + _raw_api_class=RawSimulator, + ) + api = B2Api(StubAccountInfo(), api_config=config) + simulator = api.session.raw_api + account_id, master_key = simulator.create_account() + api.authorize_account('production', account_id, master_key) + bucket = api.create_bucket('encoded-downloads', 'allPrivate') + api.session.raw_api = B2RawHTTPApi(B2Http(config)) + if by_id: + url = api.session.get_download_url_by_id('encoded-file') + else: + url = api.session.get_download_url_by_name(bucket.name, 'enc.bin') + headers = { + 'Content-Length': str(len(encoded)), + 'Content-Encoding': 'gzip', + 'X-Bz-File-Id': 'encoded-file', + 'X-Bz-File-Name': 'enc.bin', + 'X-Bz-Content-Sha1': hashlib.sha1(encoded).hexdigest(), + 'X-Bz-Upload-Timestamp': '1000', + } + destination = DownloadDestBytes() + with responses.RequestsMock() as transport: + transport.add( + responses.GET, + url, + body=encoded, + headers=headers, + content_type='application/octet-stream', + ) + if by_id: + result = api.download_file_by_id('encoded-file', destination) + else: + result = bucket.download_file_by_name('enc.bin', destination) + assert destination.get_bytes_written() == (data if decode_content else encoded) + assert result['fileName'] == 'enc.bin' + + +def test_legacy_api_still_rejects_raw_api_with_configuration(): + from apiver_deps_exception import InvalidArgument + + with pytest.raises(InvalidArgument, match='Provide at most one'): + B2Api(StubAccountInfo(), raw_api=RawSimulator(), api_config=B2HttpApiConfig()) From 1ce80d92b800c29c72019fd370ea0555acd2fb74 Mon Sep 17 00:00:00 2001 From: Felipe Fumero Date: Fri, 20 Nov 2026 17:12:03 -0600 Subject: [PATCH 034/113] Invalidate the bucket name cache on delete across v0-v3 (#696) * fix: invalidate bucket cache after deletion * fix: invalidate bucket cache in legacy API --- b2sdk/_internal/api.py | 1 + b2sdk/v0/api.py | 4 ++- changelog.d/+bucket-delete-cache.fixed.md | 1 + test/unit/api/test_api.py | 21 +++++++++++++++ test/unit/bucket/test_regression_bucket.py | 30 +++++++++++++++++----- 5 files changed, 49 insertions(+), 8 deletions(-) create mode 100644 changelog.d/+bucket-delete-cache.fixed.md diff --git a/b2sdk/_internal/api.py b/b2sdk/_internal/api.py index 5ca76053e..0588f4464 100644 --- a/b2sdk/_internal/api.py +++ b/b2sdk/_internal/api.py @@ -383,6 +383,7 @@ def delete_bucket(self, bucket): """ account_id = self.account_info.get_account_id() self.session.delete_bucket(account_id, bucket.id_) + self.cache.clear() def list_buckets( self, bucket_name=None, bucket_id=None, *, use_cache: bool = False diff --git a/b2sdk/v0/api.py b/b2sdk/v0/api.py index 56393a359..a8a8fc148 100644 --- a/b2sdk/v0/api.py +++ b/b2sdk/v0/api.py @@ -28,4 +28,6 @@ def delete_bucket(self, bucket): :param b2sdk.v1.Bucket bucket: a :term:`bucket` to delete """ account_id = self.account_info.get_account_id() - return self.session.delete_bucket(account_id, bucket.id_) + response = self.session.delete_bucket(account_id, bucket.id_) + self.cache.clear() + return response diff --git a/changelog.d/+bucket-delete-cache.fixed.md b/changelog.d/+bucket-delete-cache.fixed.md new file mode 100644 index 000000000..52e737a9d --- /dev/null +++ b/changelog.d/+bucket-delete-cache.fixed.md @@ -0,0 +1 @@ +Clear cached bucket names after deleting a bucket. diff --git a/test/unit/api/test_api.py b/test/unit/api/test_api.py index 99bc75526..bc2894eaf 100644 --- a/test/unit/api/test_api.py +++ b/test/unit/api/test_api.py @@ -38,6 +38,7 @@ AccessDenied, FileNotPresent, InvalidArgument, + NonExistentBucket, RestrictedBucket, WrongEncryptionModeForBucketDefault, ) @@ -259,6 +260,26 @@ def test_list_buckets(self, expected_delete_bucket_output): self.api.create_bucket('bucket3', 'allPrivate') assert [b.name for b in self.api.list_buckets()] == ['bucket1', 'bucket3'] + def test_delete_bucket_invalidates_cached_name(self): + self._authorize_account() + bucket = self.api.create_bucket('bucket1', 'allPrivate') + assert self.cache.get_bucket_id_or_none_from_bucket_name(bucket.name) == bucket.id_ + self.api.delete_bucket(bucket) + with pytest.raises(NonExistentBucket): + self.api.get_bucket_by_name(bucket.name) + + def test_failed_delete_bucket_keeps_cached_name(self, monkeypatch): + self._authorize_account() + bucket = self.api.create_bucket('bucket1', 'allPrivate') + + def fail_delete(*args): + raise RuntimeError('delete failed') + + monkeypatch.setattr(self.api.session, 'delete_bucket', fail_delete) + with pytest.raises(RuntimeError, match='delete failed'): + self.api.delete_bucket(bucket) + assert self.cache.get_bucket_id_or_none_from_bucket_name(bucket.name) == bucket.id_ + def test_list_buckets_with_name(self): self._authorize_account() self.api.create_bucket('bucket1', 'allPrivate') diff --git a/test/unit/bucket/test_regression_bucket.py b/test/unit/bucket/test_regression_bucket.py index 97e3ddccf..bd99617df 100644 --- a/test/unit/bucket/test_regression_bucket.py +++ b/test/unit/bucket/test_regression_bucket.py @@ -29,6 +29,7 @@ import requests import responses from apiver_deps import ( + AuthInfoCache, B2Api, B2Http, B2HttpApiConfig, @@ -37,6 +38,7 @@ InMemoryAccountInfo, InMemoryCache, RawSimulator, + SqliteAccountInfo, UploadSourceBytes, ) from apiver_deps_exception import CopyArgumentsMismatch, NonExistentBucket @@ -216,20 +218,34 @@ def _api(self, account_info=None, cache=None): ) return api, master_key - @known_defect( - 'C2', - 'delete_bucket does not remove the bucket name from the name cache', - raises=pytest.fail.Exception, - ) - def test_c2_deleted_bucket_not_returned_from_name_cache(self): + @pytest.mark.parametrize('cache_kind', ['memory', 'account_info', 'sqlite']) + def test_c2_deleted_bucket_not_returned_from_name_cache(self, cache_kind, tmp_path): """C2: after delete_bucket, a lookup by name must fail, not return the stale ID.""" - api, _ = self._api() + account_info = ( + SqliteAccountInfo(file_name=str(tmp_path / 'account.sqlite')) + if cache_kind == 'sqlite' + else InMemoryAccountInfo() + ) + cache = InMemoryCache() if cache_kind == 'memory' else AuthInfoCache(account_info) + api, _ = self._api(account_info=account_info, cache=cache) bucket = api.create_bucket('to-delete', 'allPrivate') assert api.get_bucket_by_name('to-delete').id_ == bucket.id_, 'cache was not warm' api.delete_bucket(bucket) with pytest.raises(NonExistentBucket): api.get_bucket_by_name('to-delete') + def test_failed_bucket_delete_preserves_cached_name(self, monkeypatch): + api, _ = self._api() + bucket = api.create_bucket('not-deleted', 'allPrivate') + + def fail_delete(*args): + raise RuntimeError('delete failed') + + monkeypatch.setattr(api.session, 'delete_bucket', fail_delete) + with pytest.raises(RuntimeError, match='delete failed'): + api.delete_bucket(bucket) + assert api.cache.get_bucket_id_or_none_from_bucket_name(bucket.name) == bucket.id_ + @known_defect( 'C28', 'the create_bucket mismatch message prints the same name twice', From d043d22fa0db26a7ac7bdf6016e42ab3c82e835a Mon Sep 17 00:00:00 2001 From: Felipe Fumero Date: Fri, 20 Nov 2026 17:12:23 -0600 Subject: [PATCH 035/113] fix: preserve timestamps on multipart uploads (#697) --- b2sdk/_internal/large_file/services.py | 3 + .../large_file/unfinished_large_file.py | 1 + b2sdk/_internal/transfer/emerge/executor.py | 10 ++- .../+large-upload-custom-timestamp.fixed.md | 1 + test/unit/bucket/test_regression_bucket.py | 79 ++++++++++++++++++- 5 files changed, 91 insertions(+), 3 deletions(-) create mode 100644 changelog.d/+large-upload-custom-timestamp.fixed.md diff --git a/b2sdk/_internal/large_file/services.py b/b2sdk/_internal/large_file/services.py index 6dd5dd35d..c03237ffb 100644 --- a/b2sdk/_internal/large_file/services.py +++ b/b2sdk/_internal/large_file/services.py @@ -88,6 +88,7 @@ def start_large_file( encryption: EncryptionSetting | None = None, file_retention: FileRetentionSetting | None = None, legal_hold: LegalHold | None = None, + custom_upload_timestamp: int | None = None, ): """ Start a large file transfer. @@ -98,6 +99,7 @@ def start_large_file( :param b2sdk.v2.EncryptionSetting encryption: encryption settings (``None`` if unknown) :param b2sdk.v2.FileRetentionSetting file_retention: file retention setting :param b2sdk.v2.LegalHold legal_hold: legal hold setting + :param int,None custom_upload_timestamp: override the upload timestamp in milliseconds since epoch """ return self.UNFINISHED_LARGE_FILE_CLASS( self.services.session.start_large_file( @@ -108,6 +110,7 @@ def start_large_file( server_side_encryption=encryption, file_retention=file_retention, legal_hold=legal_hold, + custom_upload_timestamp=custom_upload_timestamp, ) ) diff --git a/b2sdk/_internal/large_file/unfinished_large_file.py b/b2sdk/_internal/large_file/unfinished_large_file.py index 4bfe3e7b2..81299c3d6 100644 --- a/b2sdk/_internal/large_file/unfinished_large_file.py +++ b/b2sdk/_internal/large_file/unfinished_large_file.py @@ -38,6 +38,7 @@ def __init__(self, file_dict): self.bucket_id = file_dict['bucketId'] self.content_type = file_dict['contentType'] self.file_info = file_dict['fileInfo'] + self._upload_timestamp = file_dict.get('uploadTimestamp') self.encryption = EncryptionSettingFactory.from_file_version_dict(file_dict) self.file_retention = FileRetentionSetting.from_file_version_dict(file_dict) self.legal_hold = LegalHold.from_file_version_dict(file_dict) diff --git a/b2sdk/_internal/transfer/emerge/executor.py b/b2sdk/_internal/transfer/emerge/executor.py index 2a7ba07d9..779cd5bd3 100644 --- a/b2sdk/_internal/transfer/emerge/executor.py +++ b/b2sdk/_internal/transfer/emerge/executor.py @@ -205,6 +205,7 @@ def execute_plan(self, emerge_plan: StreamingEmergePlan): encryption=encryption, file_retention=self.file_retention, legal_hold=self.legal_hold, + custom_upload_timestamp=self.custom_upload_timestamp, ) file_id = unfinished_file.file_id @@ -273,6 +274,13 @@ def _get_unfinished_file_and_parts( continue_large_file_id, prefix=file_name, ) + if ( + custom_upload_timestamp is not None + and unfinished_file._upload_timestamp != custom_upload_timestamp + ): + raise ValueError( + 'Cannot manually resume unfinished large file with different custom_upload_timestamp' + ) if unfinished_file.file_info != file_info: raise ValueError( 'Cannot manually resume unfinished large file with different file_info' @@ -387,7 +395,7 @@ def _find_matching_unfinished_file( if ( custom_upload_timestamp is not None - and file_.upload_timestamp != custom_upload_timestamp + and file_._upload_timestamp != custom_upload_timestamp ): logger.debug('Rejecting %s: custom_upload_timestamp mismatch', file_.file_id) continue diff --git a/changelog.d/+large-upload-custom-timestamp.fixed.md b/changelog.d/+large-upload-custom-timestamp.fixed.md new file mode 100644 index 000000000..884c74ede --- /dev/null +++ b/changelog.d/+large-upload-custom-timestamp.fixed.md @@ -0,0 +1 @@ +Fixed custom upload timestamps for multipart uploads and their resumption. diff --git a/test/unit/bucket/test_regression_bucket.py b/test/unit/bucket/test_regression_bucket.py index bd99617df..ab831e4cd 100644 --- a/test/unit/bucket/test_regression_bucket.py +++ b/test/unit/bucket/test_regression_bucket.py @@ -23,6 +23,7 @@ import json import locale import threading +from unittest import mock import apiver_deps import pytest @@ -40,6 +41,7 @@ RawSimulator, SqliteAccountInfo, UploadSourceBytes, + WriteIntent, ) from apiver_deps_exception import CopyArgumentsMismatch, NonExistentBucket @@ -122,14 +124,12 @@ def test_c6_exact_filename_respects_include_filter_for_other_name(self): class TestRegressionUploadOptions(TestCaseWithBucket): - @known_defect('C45', 'multipart uploads ignore custom_upload_timestamp', raises=AssertionError) def test_c45_custom_timestamp_is_kept_on_large_upload(self): """C45: a custom upload timestamp must be applied to multi-part uploads too.""" data = self._make_data(self.simulator.MIN_PART_SIZE * 3) file_version = self.bucket.upload_bytes(data, 'large', custom_upload_timestamp=12345) assert file_version.upload_timestamp == 12345, file_version.upload_timestamp - @known_defect('C45', 'multipart uploads ignore custom_upload_timestamp', raises=AssertionError) def test_c45_custom_timestamp_is_kept_on_large_unfinished_file(self): """C45: the started large file carries the custom timestamp (visible after the upload).""" data = self._make_data(self.simulator.MIN_PART_SIZE * 3) @@ -137,6 +137,81 @@ def test_c45_custom_timestamp_is_kept_on_large_unfinished_file(self): stored = self.bucket.get_file_info_by_name('large2') assert stored.upload_timestamp == 777, stored.upload_timestamp + def test_c45_interrupted_upload_preserves_timestamp_and_resumes(self): + data = self._make_data(self.simulator.MIN_PART_SIZE * 3) + for timestamp in (0, 777): + with self.subTest(timestamp=timestamp): + name = f'resume-{timestamp}' + with mock.patch.object( + self.api.services.upload_manager, + 'upload_part', + side_effect=RuntimeError('interrupted'), + ): + with pytest.raises(RuntimeError, match='interrupted'): + self.bucket.upload_bytes(data, name, custom_upload_timestamp=timestamp) + + unfinished = list(self.bucket.list_unfinished_large_files(prefix=name)) + assert len(unfinished) == 1 + raw = self.simulator.list_unfinished_large_files( + self.api_url, self.account_auth_token, self.bucket_id, prefix=name + ) + assert raw['files'][0]['uploadTimestamp'] == timestamp + completed = self.bucket.upload_bytes(data, name, custom_upload_timestamp=timestamp) + assert completed.id_ == unfinished[0].file_id + assert completed.upload_timestamp == timestamp + + def test_c45_resume_matches_requested_timestamp(self): + data = self._make_data(self.simulator.MIN_PART_SIZE * 3) + for existing_timestamp, requested_timestamp in ((777, 777), (777, 888), (0, 0)): + with self.subTest(existing=existing_timestamp, requested=requested_timestamp): + name = f'match-{existing_timestamp}-{requested_timestamp}' + unfinished = self.simulator.start_large_file( + self.api_url, + self.account_auth_token, + self.bucket_id, + name, + None, + {}, + custom_upload_timestamp=existing_timestamp, + ) + completed = self.bucket.upload_bytes( + data, name, custom_upload_timestamp=requested_timestamp + ) + if existing_timestamp == requested_timestamp: + assert completed.id_ == unfinished['fileId'] + else: + assert completed.id_ != unfinished['fileId'] + assert completed.upload_timestamp == requested_timestamp + + def test_c45_explicit_resume_requires_matching_timestamp(self): + data = self._make_data(self.simulator.MIN_PART_SIZE * 3) + for requested_timestamp in (777, 888): + with self.subTest(requested=requested_timestamp): + name = f'explicit-{requested_timestamp}' + unfinished = self.simulator.start_large_file( + self.api_url, + self.account_auth_token, + self.bucket_id, + name, + None, + {'large_file_sha1': apiver_deps.hex_sha1_of_bytes(data)}, + custom_upload_timestamp=777, + ) + kwargs = dict( + write_intents=[WriteIntent(UploadSourceBytes(data))], + file_name=name, + continue_large_file_id=unfinished['fileId'], + custom_upload_timestamp=requested_timestamp, + ) + if requested_timestamp == 777: + completed = self.bucket.create_file(**kwargs) + assert completed.id_ == unfinished['fileId'] + assert completed.upload_timestamp == 777 + else: + with pytest.raises(ValueError, match='custom_upload_timestamp'): + self.bucket.create_file(**kwargs) + assert list(self.bucket.list_unfinished_large_files(prefix=name)) + @known_defect( 'C33', 'Bucket.upload passes min_part_size as the recommended part size instead of a lower limit', From fe0d560ca1f07efc9cde4a04320257c5806f846f Mon Sep 17 00:00:00 2001 From: scarreras Date: Sat, 21 Nov 2026 00:29:57 -0300 Subject: [PATCH 036/113] test: prove B2Http outbound calls time out against an unresponsive server Co-Authored-By: Claude Sonnet 5.5 --- .../+outbound-timeout-tests.infrastructure.md | 1 + test/unit/b2http/test_outbound_timeouts.py | 140 ++++++++++++++++++ 2 files changed, 141 insertions(+) create mode 100644 changelog.d/+outbound-timeout-tests.infrastructure.md create mode 100644 test/unit/b2http/test_outbound_timeouts.py diff --git a/changelog.d/+outbound-timeout-tests.infrastructure.md b/changelog.d/+outbound-timeout-tests.infrastructure.md new file mode 100644 index 000000000..08f37ad49 --- /dev/null +++ b/changelog.d/+outbound-timeout-tests.infrastructure.md @@ -0,0 +1 @@ +Add unit tests proving that every outbound HTTP entry point of `B2Http` stops waiting on an unresponsive local server within its timeout and raises `B2RequestTimeout`. diff --git a/test/unit/b2http/test_outbound_timeouts.py b/test/unit/b2http/test_outbound_timeouts.py new file mode 100644 index 000000000..4fcf3135b --- /dev/null +++ b/test/unit/b2http/test_outbound_timeouts.py @@ -0,0 +1,140 @@ +###################################################################### +# +# File: test/unit/b2http/test_outbound_timeouts.py +# +# Copyright 2026 Backblaze Inc. All Rights Reserved. +# +# License https://www.backblaze.com/using_b2_code.html +# +###################################################################### +""" +Every outbound HTTP entry point of ``B2Http`` must stop waiting for an unresponsive +server within its configured timeout and surface ``B2RequestTimeout`` (a controlled +failure) instead of hanging the caller. + +The server here is a real local TCP listener that accepts connections and never +answers, so the timeout is exercised by the actual ``requests`` socket deadline. +No external network and no B2 credentials are involved. +""" + +from __future__ import annotations + +import contextlib +import socket +import threading +import time + +import pytest +import requests +from apiver_deps_exception import B2RequestTimeout + +from b2sdk._internal.api_config import B2HttpApiConfig +from b2sdk._internal.b2http import B2Http + +TIMEOUT_SECONDS = 0.3 +# Generous ceiling that still proves the call was bounded by the timeout, not by luck. +MAX_ELAPSED_SECONDS = 10.0 + +# A regression that removes a timeout must fail the test rather than hang the suite. +pytestmark = pytest.mark.timeout(30) + + +class ShortTimeoutB2Http(B2Http): + """B2Http with every class-level timeout shrunk so a hung server is detected quickly.""" + + CONNECTION_TIMEOUT = TIMEOUT_SECONDS + TIMEOUT = TIMEOUT_SECONDS + TIMEOUT_FOR_COPY = TIMEOUT_SECONDS + TIMEOUT_FOR_UPLOAD = TIMEOUT_SECONDS + + +@pytest.fixture +def unresponsive_server_url(monkeypatch): + """URL of a local server that accepts connections but never sends a response.""" + monkeypatch.setenv('NO_PROXY', '127.0.0.1') + monkeypatch.setenv('no_proxy', '127.0.0.1') + listener = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + listener.bind(('127.0.0.1', 0)) + listener.listen(8) + listener.settimeout(0.1) + stop = threading.Event() + held = [] + + def accept_and_hold(): + while not stop.is_set(): + with contextlib.suppress(OSError): + held.append(listener.accept()[0]) + + thread = threading.Thread(target=accept_and_hold, daemon=True) + thread.start() + try: + yield f'http://127.0.0.1:{listener.getsockname()[1]}/b2api/v3/b2_list_buckets' + finally: + stop.set() + thread.join(timeout=5) + for connection in held: + connection.close() + listener.close() + + +@pytest.fixture +def b2_http(): + http = ShortTimeoutB2Http(B2HttpApiConfig(install_clock_skew_hook=False)) + try: + yield http + finally: + http.session.close() + + +def _request(http, url): + return http.request('GET', url, headers={}, try_count=1) + + +def _post_content_return_json(http, url): + return http.post_content_return_json(url, {}, b'{}', try_count=1) + + +def _post_json_return_json(http, url): + return http.post_json_return_json(url, {}, {'accountId': 'a'}, try_count=1) + + +def _get_content(http, url): + return http.get_content(url, {}, try_count=1) + + +def _head_content(http, url): + return http.head_content(url, {}, try_count=1) + + +@pytest.mark.parametrize( + 'call', + [ + pytest.param(_request, id='request'), + pytest.param(_post_content_return_json, id='post_content_return_json'), + pytest.param(_post_json_return_json, id='post_json_return_json'), + pytest.param(_get_content, id='get_content'), + pytest.param(_head_content, id='head_content'), + ], +) +def test_unresponsive_server_raises_request_timeout_within_bound( + call, b2_http, unresponsive_server_url +): + started = time.monotonic() + # The tuple only admits the raw requests timeout so that the stricter isinstance + # check below reports a leaked, untranslated timeout as its own failure. + with pytest.raises((B2RequestTimeout, requests.Timeout)) as raised: + call(b2_http, unresponsive_server_url) + elapsed = time.monotonic() - started + + assert isinstance(raised.value, B2RequestTimeout), 'timeout was not translated to a B2Error' + assert elapsed >= TIMEOUT_SECONDS * 0.5, 'call failed before the timeout could have expired' + assert elapsed < MAX_ELAPSED_SECONDS, f'call was not bounded by its timeout: {elapsed:.1f}s' + + +def test_explicit_request_timeout_overrides_default_bound(b2_http, unresponsive_server_url): + """A caller-supplied ``_timeout`` is what bounds the call, not the larger class default.""" + b2_http.TIMEOUT_FOR_UPLOAD = 3600 + started = time.monotonic() + with pytest.raises(B2RequestTimeout): + b2_http.request('GET', unresponsive_server_url, headers={}, try_count=1, _timeout=0.3) + assert time.monotonic() - started < MAX_ELAPSED_SECONDS From 4cb319de686fe2c961ac55f3504ea9985ef1a553 Mon Sep 17 00:00:00 2001 From: scarreras Date: Sat, 21 Nov 2026 01:09:21 -0300 Subject: [PATCH 037/113] test: cover _filter_out_none and validate documented imports in CI Add direct unit tests for the emerge planner's _filter_out_none predicate helper, and a test plus a doc_examples nox session and CI step that check every import shown in the README and Sphinx examples resolves against the public b2sdk API. Co-Authored-By: Claude Sonnet 5.5 --- .github/workflows/ci.yml | 2 + ...xamples-and-filter-tests.infrastructure.md | 1 + noxfile.py | 7 + .../test_emerge_planner_filter_out_none.py | 60 ++++++ test/unit/test_documentation_examples.py | 171 ++++++++++++++++++ 5 files changed, 241 insertions(+) create mode 100644 changelog.d/+doc-examples-and-filter-tests.infrastructure.md create mode 100644 test/unit/internal/test_emerge_planner_filter_out_none.py create mode 100644 test/unit/test_documentation_examples.py diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 4acc6e4b0..db4ac0f9b 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -73,6 +73,8 @@ jobs: run: uv sync --only-group nox --locked - name: Build the distribution run: uv run nox -vs build + - name: Compile documentation examples + run: uv run nox -vs doc_examples cleanup_buckets: timeout-minutes: 30 needs: lint diff --git a/changelog.d/+doc-examples-and-filter-tests.infrastructure.md b/changelog.d/+doc-examples-and-filter-tests.infrastructure.md new file mode 100644 index 000000000..2225d2ee5 --- /dev/null +++ b/changelog.d/+doc-examples-and-filter-tests.infrastructure.md @@ -0,0 +1 @@ +Check in CI that every import shown in the README and documentation examples resolves against the public `b2sdk` API, and add direct unit tests for the planner's `_filter_out_none` helper. diff --git a/noxfile.py b/noxfile.py index 418ef765f..42a29fcf6 100644 --- a/noxfile.py +++ b/noxfile.py @@ -243,6 +243,13 @@ def doc(session): session.run('sphinx-autobuild', *sphinx_args) +@nox.session(python=PYTHON_DEFAULT_VERSION) +def doc_examples(session): + """Compile the documentation examples: every import in README/docs must resolve against b2sdk.""" + uv_install(session, groups=('test',), extras=('full',)) + session.run('pytest', '--api=v3', 'test/unit/test_documentation_examples.py', *session.posargs) + + @nox.session def doc_cover(session): """Perform coverage analysis for the documentation.""" diff --git a/test/unit/internal/test_emerge_planner_filter_out_none.py b/test/unit/internal/test_emerge_planner_filter_out_none.py new file mode 100644 index 000000000..7be0cbc6b --- /dev/null +++ b/test/unit/internal/test_emerge_planner_filter_out_none.py @@ -0,0 +1,60 @@ +###################################################################### +# +# File: test/unit/internal/test_emerge_planner_filter_out_none.py +# +# Copyright 2026 Backblaze Inc. All Rights Reserved. +# +# License https://www.backblaze.com/using_b2_code.html +# +###################################################################### +from __future__ import annotations + +import pytest + +from b2sdk._internal.http_constants import ( + DEFAULT_MAX_PART_SIZE, + DEFAULT_MIN_PART_SIZE, + DEFAULT_RECOMMENDED_UPLOAD_PART_SIZE, +) +from b2sdk._internal.transfer.emerge.planner.planner import EmergePlanner, _filter_out_none + + +@pytest.mark.parametrize( + 'args, expected', + [ + ((), []), + ((None,), []), + ((None, None), []), + ((1, 2), [1, 2]), + ((None, 5), [5]), + ((5, None), [5]), + ((3, None, 7, None), [3, 7]), + # only `None` is dropped; other falsy values must survive + ((0, None, '', False, []), [0, '', False, []]), + ], +) +def test_filter_out_none_drops_only_none_and_keeps_order(args, expected): + assert list(_filter_out_none(*args)) == expected + + +def test_filter_out_none_is_lazy_and_single_pass(): + result = _filter_out_none(1, None, 2) + assert next(result) == 1 + assert list(result) == [2] + assert list(result) == [] + + +def test_planner_min_part_size_skips_the_unset_limit(): + # `_filter_out_none` feeds `min(...)` in the planner constructor: if it let `None` + # through, `min` would raise a TypeError (or compare None to an int) instead of + # using the one limit that is set. + planner = EmergePlanner(recommended_upload_part_size=None, max_part_size=DEFAULT_MAX_PART_SIZE) + assert planner.min_part_size == DEFAULT_MIN_PART_SIZE + assert planner.recommended_upload_part_size == DEFAULT_RECOMMENDED_UPLOAD_PART_SIZE + assert planner.max_part_size == DEFAULT_MAX_PART_SIZE + + +def test_planner_min_part_size_is_lowered_by_the_configured_limit(): + small = DEFAULT_MIN_PART_SIZE // 2 + planner = EmergePlanner(recommended_upload_part_size=small, max_part_size=None) + assert planner.min_part_size == small diff --git a/test/unit/test_documentation_examples.py b/test/unit/test_documentation_examples.py new file mode 100644 index 000000000..ca062c850 --- /dev/null +++ b/test/unit/test_documentation_examples.py @@ -0,0 +1,171 @@ +###################################################################### +# +# File: test/unit/test_documentation_examples.py +# +# Copyright 2026 Backblaze Inc. All Rights Reserved. +# +# License https://www.backblaze.com/using_b2_code.html +# +###################################################################### +""" +Validate the Python examples published in the README and the Sphinx docs. + +The examples talk to a live B2 account, so they cannot be executed here. What can drift silently +(and what users copy first) are the `import` statements: a renamed or removed public name leaves +the documentation importing something that no longer exists. This module extracts every Python +`code-block` from the docs and checks that each `import` statement in it resolves against the +installed `b2sdk` package. +""" + +from __future__ import annotations + +import ast +import importlib +import pathlib +import re +import textwrap + +import pytest + +REPO_ROOT = pathlib.Path(__file__).resolve().parents[2] +DOC_SOURCE = REPO_ROOT / 'doc' / 'source' + +_CODE_BLOCK_RE = re.compile(r'^(?P[ ]*)\.\. code-block:: python[ ]*$') +_MARKDOWN_FENCE_RE = re.compile(r'^```(?:python|py)[ ]*$') + + +def extract_python_blocks(text: str) -> list[str]: + """Return the body of each Python code block (reST `code-block` or Markdown fence) in `text`.""" + lines = text.splitlines() + blocks: list[str] = [] + i = 0 + while i < len(lines): + rst = _CODE_BLOCK_RE.match(lines[i]) + if rst: + base_indent = len(rst.group('indent')) + i += 1 + body: list[str] = [] + while i < len(lines): + line = lines[i] + if line.strip() and len(line) - len(line.lstrip()) <= base_indent: + break + body.append(line) + i += 1 + blocks.append(textwrap.dedent('\n'.join(body)).strip('\n')) + elif _MARKDOWN_FENCE_RE.match(lines[i]): + i += 1 + body = [] + while i < len(lines) and not lines[i].startswith('```'): + body.append(lines[i]) + i += 1 + blocks.append('\n'.join(body)) + i += 1 + else: + i += 1 + return blocks + + +def import_statements(block: str) -> list[str]: + """ + Return the `import` statements found in a block. + + Blocks are written either as plain Python or as an interactive session (`>>> ` prompts); + for the latter only the prompt lines are code, the rest is sample output. + """ + interactive = any(line.lstrip().startswith('>>> ') for line in block.splitlines()) + statements = [] + for line in block.splitlines(): + stripped = line.strip() + if interactive: + if not stripped.startswith('>>> '): + continue + stripped = stripped[4:].strip() + if stripped.startswith('import ') or ( + stripped.startswith('from ') and ' import ' in stripped + ): + statements.append(stripped) + return statements + + +def assert_import_resolves(statement: str) -> None: + """Execute-free check that an `import` statement names things that really exist.""" + node = ast.parse(statement).body[0] + if isinstance(node, ast.Import): + for alias in node.names: + importlib.import_module(alias.name) + elif isinstance(node, ast.ImportFrom): + assert node.level == 0, f'relative import in documentation: {statement!r}' + module = importlib.import_module(node.module) + for alias in node.names: + if alias.name == '*': + continue + assert hasattr( + module, alias.name + ), f'{statement!r}: module {node.module!r} has no public name {alias.name!r}' + else: # pragma: no cover - guarded by import_statements + raise AssertionError(f'not an import statement: {statement!r}') + + +def documentation_files() -> list[pathlib.Path]: + return [REPO_ROOT / 'README.md', *sorted(DOC_SOURCE.glob('*.rst'))] + + +class TestExtraction: + def test_rst_block_stops_at_dedent(self): + text = ( + 'Title\n=====\n\n.. code-block:: python\n\n >>> import time\n\n' + ' >>> time.sleep(0)\n\nProse after the block.\n' + ) + assert extract_python_blocks(text) == ['>>> import time\n\n>>> time.sleep(0)'] + + def test_markdown_fence(self): + text = 'Intro\n\n```python\nimport os\n```\n\n```sh\nls\n```\n' + assert extract_python_blocks(text) == ['import os'] + + def test_non_python_blocks_are_ignored(self): + assert extract_python_blocks('.. code-block:: sh\n\n import fake\n') == [] + + def test_import_statements_from_interactive_block(self): + block = '>>> from b2sdk.v3 import B2Api\n>>> b2_api = B2Api()\nfrom not_code import x' + assert import_statements(block) == ['from b2sdk.v3 import B2Api'] + + def test_import_statements_from_plain_block(self): + block = 'import os\nfrom os import path\nvalue = 1 # import not_a_statement' + assert import_statements(block) == ['import os', 'from os import path'] + + +class TestImportResolution: + def test_detects_missing_name(self): + with pytest.raises(AssertionError, match='no public name'): + assert_import_resolves('from b2sdk.v3 import ThisNameDoesNotExist') + + def test_detects_missing_module(self): + with pytest.raises(ImportError): + assert_import_resolves('import b2sdk.v3.no_such_module') + + def test_accepts_real_names(self): + assert_import_resolves('from b2sdk.v3 import B2Api, InMemoryAccountInfo') + assert_import_resolves('from b2sdk.v3 import *') + + +def _documented_imports() -> list: + params = [] + for path in documentation_files(): + for block in extract_python_blocks(path.read_text(encoding='utf-8')): + for statement in import_statements(block): + params.append( + pytest.param( + statement, id=f'{path.relative_to(REPO_ROOT).as_posix()}::{statement}' + ) + ) + return params + + +def test_documentation_contains_examples_to_validate(): + # Guard against the extraction silently matching nothing (e.g. after a docs reformat). + assert len(_documented_imports()) >= 10 + + +@pytest.mark.parametrize('statement', _documented_imports()) +def test_documented_import_resolves_against_public_api(statement): + assert_import_resolves(statement) From f7d3f806fec4c5a63413612bfca07e44233b4802 Mon Sep 17 00:00:00 2001 From: scarreras Date: Sat, 21 Nov 2026 01:09:21 -0300 Subject: [PATCH 038/113] test: assert notification rule secrets stay out of SDK debug trace and exceptions Covers Bucket.set_notification_rules for the signing secret and a custom header value on the success, pre-authorization, API error and validation error paths. Co-Authored-By: Claude Sonnet 5.5 --- ...-rules-nonexposure-tests.infrastructure.md | 1 + .../test_notification_rules_nonexposure.py | 224 ++++++++++++++++++ 2 files changed, 225 insertions(+) create mode 100644 changelog.d/+notification-rules-nonexposure-tests.infrastructure.md create mode 100644 test/unit/bucket/test_notification_rules_nonexposure.py diff --git a/changelog.d/+notification-rules-nonexposure-tests.infrastructure.md b/changelog.d/+notification-rules-nonexposure-tests.infrastructure.md new file mode 100644 index 000000000..7c2a330d9 --- /dev/null +++ b/changelog.d/+notification-rules-nonexposure-tests.infrastructure.md @@ -0,0 +1 @@ +Add unit tests asserting that the signing secret and custom header value of a notification rule never appear in the SDK DEBUG trace or in exception text raised by `Bucket.set_notification_rules`, on the success, pre-authorization, API error and validation error paths. diff --git a/test/unit/bucket/test_notification_rules_nonexposure.py b/test/unit/bucket/test_notification_rules_nonexposure.py new file mode 100644 index 000000000..7d664019d --- /dev/null +++ b/test/unit/bucket/test_notification_rules_nonexposure.py @@ -0,0 +1,224 @@ +###################################################################### +# +# File: test/unit/bucket/test_notification_rules_nonexposure.py +# +# Copyright 2026 Backblaze Inc. All Rights Reserved. +# +# License https://www.backblaze.com/using_b2_code.html +# +###################################################################### +""" +Operation-level secret non-exposure for ``Bucket.set_notification_rules``. + +A notification rule can carry an HMAC signing secret and a custom header value. Neither may +reach the SDK's DEBUG trace or the text of an exception raised by the call. + +There is one test per (surface, path); each is run once per sensitive input +(``signing_secret``, ``custom_header``) and asserts exactly that cell: + +* surfaces: SDK DEBUG trace (every ``logging`` record, with tracebacks, at DEBUG level; the SDK + traces little on the success, pre-authorization and validation paths, so those tests also + emit a marker record to prove the capture is live; on the API error path the SDK's own + records, including the HTTP error, are asserted to be present) and + exception text (message, repr and formatted traceback of whatever the call raised); +* paths: success (simulator-backed), failure before authorization, API error (a real + ``B2RawHTTPApi`` over a faked HTTP session answering 400), and a local validation error + (a request that cannot be serialized, raised before anything is sent). + +On the success path nothing is raised, so the success x exception test can only assert that the +call does not raise and that no exception text can carry the secret. It is weaker than the +failure-path exception tests and is documented as such rather than dressed up. +""" + +from __future__ import annotations + +import json +import logging +import traceback + +import pytest +import requests +from apiver_deps import ( + B2Api, + B2HttpApiConfig, + B2RawHTTPApi, + InMemoryAccountInfo, + RawSimulator, +) + +from b2sdk._internal.b2http import B2Http + +SECRET_VALUES = { + 'signing_secret': 'hmac-signing-secret-must-not-leak-4b1e', + 'custom_header': 'custom-header-value-must-not-leak-9d7c', +} + + +def sensitive_rules(): + """One webhook rule carrying both sensitive inputs.""" + return [ + { + 'eventTypes': ['b2:ObjectCreated:*'], + 'isEnabled': True, + 'name': 'sensitive-webhook', + 'objectNamePrefix': '', + 'targetConfiguration': { + 'targetType': 'webhook', + 'url': 'https://example.com/webhook', + 'hmacSha256SigningSecret': SECRET_VALUES['signing_secret'], + 'customHeaders': [ + {'name': 'X-Webhook-Token', 'value': SECRET_VALUES['custom_header']} + ], + }, + } + ] + + +def unserializable_rules(): + """Sensitive rules that cannot be sent: ``eventTypes`` is a ``set``, which JSON rejects.""" + rules = sensitive_rules() + rules[0]['eventTypes'] = {'b2:ObjectCreated:*'} + return rules + + +def exception_text(error: BaseException) -> str: + """Message, repr and formatted traceback (including chained causes) of an exception.""" + formatted = traceback.format_exception(type(error), error, error.__traceback__) + return '\n'.join([str(error), repr(error), *formatted]) + + +@pytest.fixture +def http_rejecting_bucket(b2api, mocker): + """ + A bucket created through the simulator, whose API object then switches to the real HTTP + raw API talking to a faked HTTP session that answers every request with a 400 + ``bad_request``. + """ + bucket = b2api.create_bucket('test-bucket', 'allPrivate') + + def respond(method, url, **kwargs): + response = requests.Response() + response.url = url + response.status_code = 400 + response._content = json.dumps( + {'status': 400, 'code': 'bad_request', 'message': 'rejected by the service'} + ).encode() + return response + + http = B2Http(B2HttpApiConfig(install_clock_skew_hook=False)) + mocker.patch.object(http.session, 'request', side_effect=respond) + b2api.session.raw_api = B2RawHTTPApi(http) + return bucket + + +@pytest.fixture +def unauthorized_bucket(): + """A bucket whose account info was cleared, so the call fails before it is authorized.""" + api = B2Api(InMemoryAccountInfo(), api_config=B2HttpApiConfig(_raw_api_class=RawSimulator)) + account_id, master_key = api.session.raw_api.create_account() + api.authorize_account( + application_key_id=account_id, application_key=master_key, realm='production' + ) + bucket = api.create_bucket('test-bucket', 'allPrivate') + api.account_info.clear() + return bucket + + +CAPTURE_MARKER = 'debug capture is active' + +# ── SDK debug trace ────────────────────────────────────────────────────────── + + +@pytest.mark.parametrize('sensitive_input', ['signing_secret', 'custom_header']) +def test_sensitive_input_stays_out_of_sdk_debug_trace_on_success_path( + bucket, caplog, sensitive_input +): + with caplog.at_level(logging.DEBUG): + logging.getLogger('b2sdk').debug(CAPTURE_MARKER) + bucket.set_notification_rules(sensitive_rules()) + sdk_debug_trace = caplog.text + assert CAPTURE_MARKER in sdk_debug_trace # DEBUG capture works + assert SECRET_VALUES[sensitive_input] not in sdk_debug_trace + + +@pytest.mark.parametrize('sensitive_input', ['signing_secret', 'custom_header']) +def test_sensitive_input_stays_out_of_sdk_debug_trace_on_pre_authorization_path( + unauthorized_bucket, caplog, sensitive_input +): + with caplog.at_level(logging.DEBUG): + logging.getLogger('b2sdk').debug(CAPTURE_MARKER) + with pytest.raises(Exception): + unauthorized_bucket.set_notification_rules(sensitive_rules()) + sdk_debug_trace = caplog.text + assert CAPTURE_MARKER in sdk_debug_trace # DEBUG capture works + assert SECRET_VALUES[sensitive_input] not in sdk_debug_trace + + +@pytest.mark.parametrize('sensitive_input', ['signing_secret', 'custom_header']) +def test_sensitive_input_stays_out_of_sdk_debug_trace_on_api_error_path( + http_rejecting_bucket, caplog, sensitive_input +): + with caplog.at_level(logging.DEBUG), pytest.raises(Exception): + http_rejecting_bucket.set_notification_rules(sensitive_rules()) + sdk_debug_trace = caplog.text + assert 'interpret_b2_error' in sdk_debug_trace # the SDK traced the service error itself + assert SECRET_VALUES[sensitive_input] not in sdk_debug_trace + + +@pytest.mark.parametrize('sensitive_input', ['signing_secret', 'custom_header']) +def test_sensitive_input_stays_out_of_sdk_debug_trace_on_validation_error_path( + http_rejecting_bucket, caplog, sensitive_input +): + with caplog.at_level(logging.DEBUG): + logging.getLogger('b2sdk').debug(CAPTURE_MARKER) + with pytest.raises(TypeError): + http_rejecting_bucket.set_notification_rules(unserializable_rules()) + sdk_debug_trace = caplog.text + assert CAPTURE_MARKER in sdk_debug_trace # DEBUG capture works + assert SECRET_VALUES[sensitive_input] not in sdk_debug_trace + + +# ── exception text ─────────────────────────────────────────────────────────── + + +@pytest.mark.parametrize('sensitive_input', ['signing_secret', 'custom_header']) +def test_sensitive_input_stays_out_of_exception_on_success_path(bucket, sensitive_input): + # Weaker than the failure-path cells: a successful call raises nothing, so there is no + # exception text that could carry the secret. This pins that the call really does succeed + # (nothing raised) and that the exception text is therefore free of the secret. + raised = None + try: + bucket.set_notification_rules(sensitive_rules()) + except Exception as error: + raised = error + exception_text_of_call = '' if raised is None else exception_text(raised) + assert raised is None + assert SECRET_VALUES[sensitive_input] not in exception_text_of_call + + +@pytest.mark.parametrize('sensitive_input', ['signing_secret', 'custom_header']) +def test_sensitive_input_stays_out_of_exception_on_pre_authorization_path( + unauthorized_bucket, sensitive_input +): + with pytest.raises(Exception) as excinfo: + unauthorized_bucket.set_notification_rules(sensitive_rules()) + assert SECRET_VALUES[sensitive_input] not in exception_text(excinfo.value) + + +@pytest.mark.parametrize('sensitive_input', ['signing_secret', 'custom_header']) +def test_sensitive_input_stays_out_of_exception_on_api_error_path( + http_rejecting_bucket, sensitive_input +): + with pytest.raises(Exception) as excinfo: + http_rejecting_bucket.set_notification_rules(sensitive_rules()) + assert SECRET_VALUES[sensitive_input] not in exception_text(excinfo.value) + assert 'rejected by the service' in exception_text(excinfo.value) # the service error is real + + +@pytest.mark.parametrize('sensitive_input', ['signing_secret', 'custom_header']) +def test_sensitive_input_stays_out_of_exception_on_validation_error_path( + http_rejecting_bucket, sensitive_input +): + with pytest.raises(TypeError) as excinfo: + http_rejecting_bucket.set_notification_rules(unserializable_rules()) + assert SECRET_VALUES[sensitive_input] not in exception_text(excinfo.value) From 03b99b3a16004eed1907e979aaf603b8571206fe Mon Sep 17 00:00:00 2001 From: Sophie <49928680+sophiecarreras@users.noreply.github.com> Date: Sat, 21 Nov 2026 14:46:48 -0300 Subject: [PATCH 039/113] Fix JUnit subtest reports and require opt-in for live B2 CI (#702) * fix: emit individual JUnit cases for subtests Related to backblaze-labs/quality-keeper#612. Preserve each subtest outcome without changing execution or relaxing report validation. * ci: keep draft pull requests free of live B2 operations * test: interpret CI gate expressions without executing code * fix: preserve JUnit teardown totals and subtest diagnostics * fix: keep interrupted JUnit reports inconclusive * ci: require explicit opt-in for live B2 operations --- .github/workflows/ci.yml | 25 +- .../+draft-ci-no-live.infrastructure.md | 1 + .../+junit-review-errors.infrastructure.md | 1 + .../+junit-subtest-counts.infrastructure.md | 1 + changelog.d/+live-ci-opt-in.infrastructure.md | 1 + doc/source/contributing.rst | 23 ++ pyproject.toml | 3 + test/conftest.py | 2 +- test/junit_subtests.py | 79 ++++++ test/static/test_ci_draft_safety.py | 179 ++++++++++++++ test/static/test_junit_subtests.py | 232 ++++++++++++++++++ uv.lock | 8 +- 12 files changed, 543 insertions(+), 12 deletions(-) create mode 100644 changelog.d/+draft-ci-no-live.infrastructure.md create mode 100644 changelog.d/+junit-review-errors.infrastructure.md create mode 100644 changelog.d/+junit-subtest-counts.infrastructure.md create mode 100644 changelog.d/+live-ci-opt-in.infrastructure.md create mode 100644 test/junit_subtests.py create mode 100644 test/static/test_ci_draft_safety.py create mode 100644 test/static/test_junit_subtests.py diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 4acc6e4b0..bf27eedaf 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -5,6 +5,7 @@ on: branches: [master] pull_request: branches: [master] + types: [opened, synchronize, reopened, ready_for_review] env: PYTHON_DEFAULT_VERSION: "3.14" @@ -74,11 +75,13 @@ jobs: - name: Build the distribution run: uv run nox -vs build cleanup_buckets: + # Live B2 access requires explicit opt-in and is never allowed for drafts. + if: ${{ vars.B2_LIVE_TESTS_ENABLED == 'true' && (github.event_name != 'pull_request' || !github.event.pull_request.draft) }} timeout-minutes: 30 needs: lint env: - B2_TEST_APPLICATION_KEY: ${{ secrets.B2_TEST_APPLICATION_KEY }} - B2_TEST_APPLICATION_KEY_ID: ${{ secrets.B2_TEST_APPLICATION_KEY_ID }} + B2_TEST_APPLICATION_KEY: ${{ (vars.B2_LIVE_TESTS_ENABLED == 'true' && (github.event_name != 'pull_request' || !github.event.pull_request.draft)) && secrets.B2_TEST_APPLICATION_KEY || '' }} + B2_TEST_APPLICATION_KEY_ID: ${{ (vars.B2_LIVE_TESTS_ENABLED == 'true' && (github.event_name != 'pull_request' || !github.event.pull_request.draft)) && secrets.B2_TEST_APPLICATION_KEY_ID || '' }} runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 @@ -103,10 +106,11 @@ jobs: run: uv run nox -vs cleanup_old_buckets test: timeout-minutes: 90 - needs: cleanup_buckets + needs: [lint, cleanup_buckets] + if: ${{ !cancelled() && needs.lint.result == 'success' && (needs.cleanup_buckets.result == 'success' || needs.cleanup_buckets.result == 'skipped') }} env: - B2_TEST_APPLICATION_KEY: ${{ secrets.B2_TEST_APPLICATION_KEY }} - B2_TEST_APPLICATION_KEY_ID: ${{ secrets.B2_TEST_APPLICATION_KEY_ID }} + B2_TEST_APPLICATION_KEY: ${{ (vars.B2_LIVE_TESTS_ENABLED == 'true' && (github.event_name != 'pull_request' || !github.event.pull_request.draft)) && secrets.B2_TEST_APPLICATION_KEY || '' }} + B2_TEST_APPLICATION_KEY_ID: ${{ (vars.B2_LIVE_TESTS_ENABLED == 'true' && (github.event_name != 'pull_request' || !github.event.pull_request.draft)) && secrets.B2_TEST_APPLICATION_KEY_ID || '' }} NOX_EXTRAS: ${{ matrix.extras }} runs-on: ${{ matrix.os }} strategy: @@ -141,14 +145,15 @@ jobs: - name: Run unit tests run: uv run nox -vs unit -- -v - name: Run integration tests - if: ${{ env.B2_TEST_APPLICATION_KEY != '' && env.B2_TEST_APPLICATION_KEY_ID != '' }} + if: ${{ (vars.B2_LIVE_TESTS_ENABLED == 'true' && (github.event_name != 'pull_request' || !github.event.pull_request.draft)) && env.B2_TEST_APPLICATION_KEY != '' && env.B2_TEST_APPLICATION_KEY_ID != '' }} run: uv run nox -vs integration -- --dont-cleanup-old-buckets -v cli-compat: timeout-minutes: 90 - needs: cleanup_buckets + needs: [lint, cleanup_buckets] + if: ${{ !cancelled() && needs.lint.result == 'success' && (needs.cleanup_buckets.result == 'success' || needs.cleanup_buckets.result == 'skipped') }} env: - B2_TEST_APPLICATION_KEY: ${{ secrets.B2_TEST_APPLICATION_KEY }} - B2_TEST_APPLICATION_KEY_ID: ${{ secrets.B2_TEST_APPLICATION_KEY_ID }} + B2_TEST_APPLICATION_KEY: ${{ (vars.B2_LIVE_TESTS_ENABLED == 'true' && (github.event_name != 'pull_request' || !github.event.pull_request.draft)) && secrets.B2_TEST_APPLICATION_KEY || '' }} + B2_TEST_APPLICATION_KEY_ID: ${{ (vars.B2_LIVE_TESTS_ENABLED == 'true' && (github.event_name != 'pull_request' || !github.event.pull_request.draft)) && secrets.B2_TEST_APPLICATION_KEY_ID || '' }} INSTALL_SDK_FROM: ../b2-sdk-python runs-on: ${{ matrix.os }} strategy: @@ -196,7 +201,7 @@ jobs: - name: Run CLI integration tests (without secrets) run: uv run --directory ./B2_Command_Line_Tool nox -vs integration -p ${{ matrix.python-version }} -- -m "not require_secrets" - name: Run CLI integration tests (with secrets) - if: ${{ env.B2_TEST_APPLICATION_KEY != '' && env.B2_TEST_APPLICATION_KEY_ID != '' && matrix.os == 'ubuntu-latest' && matrix.python-version == '3.14' }} + if: ${{ (vars.B2_LIVE_TESTS_ENABLED == 'true' && (github.event_name != 'pull_request' || !github.event.pull_request.draft)) && env.B2_TEST_APPLICATION_KEY != '' && env.B2_TEST_APPLICATION_KEY_ID != '' && matrix.os == 'ubuntu-latest' && matrix.python-version == '3.14' }} working-directory: B2_Command_Line_Tool run: | export VIRTUAL_ENV="$PWD/.nox/integration-3-14" diff --git a/changelog.d/+draft-ci-no-live.infrastructure.md b/changelog.d/+draft-ci-no-live.infrastructure.md new file mode 100644 index 000000000..55dcc1759 --- /dev/null +++ b/changelog.d/+draft-ci-no-live.infrastructure.md @@ -0,0 +1 @@ +Keep draft pull request CI credential-free: skip bucket cleanup and SDK/CLI live tests while retaining unit and build checks. diff --git a/changelog.d/+junit-review-errors.infrastructure.md b/changelog.d/+junit-review-errors.infrastructure.md new file mode 100644 index 000000000..6f0749929 --- /dev/null +++ b/changelog.d/+junit-review-errors.infrastructure.md @@ -0,0 +1 @@ +Keep JUnit case totals consistent when a failed subtest parent also has a teardown error. Preserve requested captured output on subtest cases while respecting passing-test logging settings. Leave interrupted reports unreconciled rather than manufacturing passing outcomes. diff --git a/changelog.d/+junit-subtest-counts.infrastructure.md b/changelog.d/+junit-subtest-counts.infrastructure.md new file mode 100644 index 000000000..a4963d13f --- /dev/null +++ b/changelog.d/+junit-subtest-counts.infrastructure.md @@ -0,0 +1 @@ +Emit individual JUnit cases for pytest and unittest subtests so report totals match their case entries, including failures and skips. diff --git a/changelog.d/+live-ci-opt-in.infrastructure.md b/changelog.d/+live-ci-opt-in.infrastructure.md new file mode 100644 index 000000000..ac7ec1321 --- /dev/null +++ b/changelog.d/+live-ci-opt-in.infrastructure.md @@ -0,0 +1 @@ +Require the B2_LIVE_TESTS_ENABLED repository variable to opt into live tests and bucket cleanup, including ready pull requests and master pushes. diff --git a/doc/source/contributing.rst b/doc/source/contributing.rst index 746762590..65259a820 100644 --- a/doc/source/contributing.rst +++ b/doc/source/contributing.rst @@ -155,6 +155,29 @@ To run tests matching a keyword expression:: $ nox -s unit-3.10 -- -k keyword +Draft pull requests run credential-free checks. CI skips the bucket-cleanup job, +withholds B2 test credentials, and skips SDK and CLI live integration steps. +Unit and CLI compatibility jobs still run when cleanup is deliberately skipped; +failed lint or cleanup jobs continue to block them. Live tests, B2 credential +access and bucket cleanup also require the repository Actions variable +``B2_LIVE_TESTS_ENABLED`` to be explicitly set to ``true``. The default is off, +including ready pull requests and pushes to master. Enable that variable only +when live validation with an approved test account is intended; marking a pull +request ready or merging it does not itself enable live operations. + +JUnit reports include each subtest as its own case, as well as its parent test. +The repository's ``test.junit_subtests`` compatibility plugin supplies those cases +because pytest 9's reporter counts subtest outcomes without emitting separate +case elements. Totals count emitted cases, including separate parent-call and +teardown-error cases. Incomplete reports stay unreconciled rather than counting +unfinished cases as passes. Requested captured output is retained on subtest cases, +respecting ``junit_logging`` and ``junit_log_passing_tests``. It copies reports +only for JUnit serialization; assertions, test selection, terminal outcomes and +exit codes keep their normal pytest behavior. +The plugin uses pytest's internal reporter API, so dependency updates should run +``pytest test/static/test_junit_subtests.py`` (serial and xdist regression cases). +Remove the compatibility layer only after upstream reporting passes those checks. + Where to put a new test ======================= diff --git a/pyproject.toml b/pyproject.toml index 9e80c3e3e..fd8a09a7d 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -45,6 +45,8 @@ format = [ "ruff~=0.8.4", ] lint = [ + "pytest-xdist>=3.8.0,<4", + "pyyaml>=6,<7", "pip>=26.2.2", "ruff~=0.8.4", "pytest>=9.0.3,<10", @@ -53,6 +55,7 @@ lint = [ "setuptools<81", # liccheck 0.9.2 imports pkg_resources, removed in setuptools 81 ] test = [ + "pyyaml>=6,<7", "pip>=26.2.2", "coverage>=7.13.5,<8", "pytest>=9.0.3,<10", diff --git a/test/conftest.py b/test/conftest.py index cd17e2a42..e5ea5ba4e 100644 --- a/test/conftest.py +++ b/test/conftest.py @@ -11,7 +11,7 @@ import pytest -pytest_plugins = ['b2sdk.v3.testing'] +pytest_plugins = ['b2sdk.v3.testing', 'test.junit_subtests'] def pytest_configure(config): diff --git a/test/junit_subtests.py b/test/junit_subtests.py new file mode 100644 index 000000000..46622c1ed --- /dev/null +++ b/test/junit_subtests.py @@ -0,0 +1,79 @@ +###################################################################### +# +# File: test/junit_subtests.py +# +# Copyright 2026 Backblaze Inc. All Rights Reserved. +# +# License https://www.backblaze.com/using_b2_code.html +# +###################################################################### +"""Keep pytest 9's JUnit subtest counts consistent with its case elements. + +Only the XML reporter sees copied subtest reports with distinct identities. +Other plugins, test execution and pytest's terminal/exit outcomes are unchanged. +This compatibility layer deliberately uses pytest's internal reporter API; +its subprocess regressions must pass when upgrading pytest. +""" + +from __future__ import annotations + +from copy import copy +from itertools import count + +import pytest +from _pytest.junitxml import LogXML, xml_key +from _pytest.subtests import SubtestReport + + +class SubtestLogXML(LogXML): + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self._subtest_ids = count(1) + + @pytest.hookimpl(trylast=True) + def pytest_runtest_logreport(self, report): + if not isinstance(report, SubtestReport): + return super().pytest_runtest_logreport(report) + report = copy(report) + report.nodeid += f'::subtest-{next(self._subtest_ids)}' + super().pytest_runtest_logreport(report) + # The normal reporter writes output at teardown, which subtests lack. + # Failure-only logging and regular skips have already written theirs. + if ( + report.passed + or (report.failed and self.log_passing_tests) + or (report.skipped and hasattr(report, 'wasxfail')) + ): + self.node_reporter(report).write_captured_output(report) + # Subtests have a call report, but no later teardown to close the case. + self.finalize(report) + self.open_reports = [entry for entry in self.open_reports if entry is not report] + + def pytest_sessionfinish(self): + # Upstream subtracts a logical test when call and teardown both fail, + # although it emits two XML cases. Compensate from the actual case list + # so every outcome remains present and the declared count matches it. + # An interrupted call can leave a bare, unfinished XML case. Do not + # reconcile such a report: that would manufacture a passing outcome. + if not self.node_reporters: + self.cnt_double_fail_tests = sum(self.stats.values()) - len(self.node_reporters_ordered) + super().pytest_sessionfinish() + + +@pytest.hookimpl(trylast=True) +def pytest_configure(config): + original = config.stash.get(xml_key, None) + if original is None: + return # No --junitxml, or an xdist worker: leave reporting untouched. + replacement = SubtestLogXML( + original.logfile, + original.prefix, + original.suite_name, + original.logging, + original.report_duration, + original.family, + original.log_passing_tests, + ) + config.pluginmanager.unregister(original) + config.stash[xml_key] = replacement + config.pluginmanager.register(replacement) diff --git a/test/static/test_ci_draft_safety.py b/test/static/test_ci_draft_safety.py new file mode 100644 index 000000000..8a4973940 --- /dev/null +++ b/test/static/test_ci_draft_safety.py @@ -0,0 +1,179 @@ +###################################################################### +# +# File: test/static/test_ci_draft_safety.py +# +# Copyright 2026 Backblaze Inc. All Rights Reserved. +# +# License https://www.backblaze.com/using_b2_code.html +# +###################################################################### +"""Exercise CI's draft, credential and dependency gates without running jobs.""" + +from __future__ import annotations + +import ast +import re +from pathlib import Path + +import pytest +import yaml + +JOBS = yaml.safe_load((Path(__file__).parents[2] / '.github/workflows/ci.yml').read_text())['jobs'] + + +def expression(value, context): + """Evaluate only the boolean/string expression subset used by these gates. + + actionlint validates the complete workflow separately. Unknown contexts or + expression syntax fail this check rather than being assumed safe. + """ + if not isinstance(value, str) or not value.startswith('${{'): + return value + code = value[3:-2].strip().replace('cancelled()', repr(context['cancelled'])) + code = re.sub( + r'[a-zA-Z_][\w-]*(?:\.[a-zA-Z_][\w-]*)+', lambda match: repr(context[match.group()]), code + ) + code = code.replace('&&', ' and ').replace('||', ' or ') + code = re.sub(r'!(?!=)', 'not ', code) + code = re.sub(r'\btrue\b', 'True', code) + code = re.sub(r'\bfalse\b', 'False', code) + tree = ast.parse(code.strip(), mode='eval') + + def resolve(node): + if isinstance(node, ast.Constant) and isinstance(node.value, (str, bool)): + return node.value + if isinstance(node, ast.UnaryOp) and isinstance(node.op, ast.Not): + return not resolve(node.operand) + if isinstance(node, ast.BoolOp): + result = resolve(node.values[0]) + for child in node.values[1:]: + if isinstance(node.op, ast.And) and not result: + return result + if isinstance(node.op, ast.Or) and result: + return result + result = resolve(child) + return result + if isinstance(node, ast.Compare): + left = resolve(node.left) + for operator, child in zip(node.ops, node.comparators): + right = resolve(child) + assert isinstance(operator, (ast.Eq, ast.NotEq)), code + if (left == right) != isinstance(operator, ast.Eq): + return False + left = right + return True + raise AssertionError(f'Unsupported workflow expression: {code}') + + return resolve(tree.body) + + +def context( + draft=True, + credentials=True, + event='pull_request', + lint='success', + cleanup='skipped', + live_enabled='true', +): + return { + 'github.event_name': event, + 'github.event.pull_request.draft': draft, + 'needs.lint.result': lint, + 'needs.cleanup_buckets.result': cleanup, + 'cancelled': False, + 'vars.B2_LIVE_TESTS_ENABLED': live_enabled, + 'secrets.B2_TEST_APPLICATION_KEY': 'test-key' if credentials else '', + 'secrets.B2_TEST_APPLICATION_KEY_ID': 'test-id' if credentials else '', + } + + +@pytest.mark.parametrize('credentials', [True, False]) +def test_draft_never_starts_bucket_cleanup(credentials): + assert not expression( + JOBS['cleanup_buckets'].get('if', '${{ true }}'), context(credentials=credentials) + ) + + +@pytest.mark.parametrize('job_id', ['test', 'cli-compat']) +@pytest.mark.parametrize( + 'draft,event', [(True, 'pull_request'), (False, 'pull_request'), (False, 'push')] +) +def test_b2_credentials_are_empty_only_for_drafts(job_id, draft, event): + values = context(draft=draft, event=event) + for name in ('B2_TEST_APPLICATION_KEY', 'B2_TEST_APPLICATION_KEY_ID'): + actual = expression(JOBS[job_id]['env'][name], values) + assert actual == ('' if draft else values[f'secrets.{name}']) + + +@pytest.mark.parametrize('job_id', ['test', 'cli-compat']) +@pytest.mark.parametrize( + 'draft,credentials,allowed', + [(True, True, False), (True, False, False), (False, True, True), (False, False, False)], +) +def test_live_steps_require_non_draft_and_credentials(job_id, draft, credentials, allowed): + values = context(draft=draft, credentials=credentials) + values.update( + { + f'env.{name}': expression(value, values) + for name, value in JOBS[job_id]['env'].items() + if name.startswith('B2_TEST_') + } + ) + values.update({'matrix.os': 'ubuntu-latest', 'matrix.python-version': '3.14'}) + steps = [ + step + for step in JOBS[job_id]['steps'] + if step.get('name') in ('Run integration tests', 'Run CLI integration tests (with secrets)') + ] + assert len(steps) == 1 + assert bool(expression(steps[0]['if'], values)) == allowed + + +@pytest.mark.parametrize('job_id', ['test', 'cli-compat']) +@pytest.mark.parametrize( + 'lint,cleanup,allowed', + [ + ('success', 'skipped', True), + ('success', 'success', True), + ('failure', 'skipped', False), + ('success', 'failure', False), + ('success', 'cancelled', False), + ], +) +def test_unit_jobs_survive_skipped_cleanup_but_not_failed_dependencies( + job_id, lint, cleanup, allowed +): + assert 'lint' in JOBS[job_id]['needs'] + assert 'cleanup_buckets' in JOBS[job_id]['needs'] + values = context(lint=lint, cleanup=cleanup) + assert bool(expression(JOBS[job_id]['if'], values)) == allowed + values['cancelled'] = True + assert not expression(JOBS[job_id]['if'], values) + + +@pytest.mark.parametrize('event', ['pull_request', 'push']) +def test_non_draft_cleanup_is_retained(event): + assert expression(JOBS['cleanup_buckets']['if'], context(draft=False, event=event)) + + +@pytest.mark.parametrize('event', ['pull_request', 'push']) +@pytest.mark.parametrize('live_enabled', ['', 'false', 'true']) +def test_non_draft_live_operations_require_explicit_repository_opt_in(event, live_enabled): + values = context(draft=False, event=event, live_enabled=live_enabled) + allowed = live_enabled == 'true' + assert bool(expression(JOBS['cleanup_buckets']['if'], values)) == allowed + for job_id in ('test', 'cli-compat'): + job_values = dict(values) + for name in ('B2_TEST_APPLICATION_KEY', 'B2_TEST_APPLICATION_KEY_ID'): + actual = expression(JOBS[job_id]['env'][name], values) + assert actual == (values[f'secrets.{name}'] if allowed else '') + job_values[f'env.{name}'] = actual + job_values.update({'matrix.os': 'ubuntu-latest', 'matrix.python-version': '3.14'}) + steps = [ + step + for step in JOBS[job_id]['steps'] + if step.get('name') + in ('Run integration tests', 'Run CLI integration tests (with secrets)') + ] + assert len(steps) == 1 + assert bool(expression(steps[0]['if'], job_values)) == allowed diff --git a/test/static/test_junit_subtests.py b/test/static/test_junit_subtests.py new file mode 100644 index 000000000..f24c37337 --- /dev/null +++ b/test/static/test_junit_subtests.py @@ -0,0 +1,232 @@ +###################################################################### +# +# File: test/static/test_junit_subtests.py +# +# Copyright 2026 Backblaze Inc. All Rights Reserved. +# +# License https://www.backblaze.com/using_b2_code.html +# +###################################################################### +"""Exercise real pytest reports, including subtest outcomes and xdist delivery.""" + +from __future__ import annotations + +import os +import subprocess +import sys +import textwrap +from pathlib import Path +from xml.etree import ElementTree as ET + +import pytest + +ROOT = Path(__file__).resolve().parents[2] + + +@pytest.mark.parametrize('workers', [0, 2]) +@pytest.mark.parametrize('outcome', ['passed', 'failed', 'skipped']) +def test_junit_subtest_totals_match_individual_cases(tmp_path, workers, outcome): + # Use the repository's plugin declarations, without loading its SDK fixtures + # into the child fixture directory or inheriting external pytest options. + declarations = (ROOT / 'test/conftest.py').read_text() + line = next(line for line in declarations.splitlines() if line.startswith('pytest_plugins =')) + (tmp_path / 'conftest.py').write_text(line + '\n') + (tmp_path / 'pytest.ini').write_text('[pytest]\n') + (tmp_path / 'test_sample.py').write_text( + textwrap.dedent(f""" + import unittest + import pytest + + def check(i): + if i == 1 and {outcome!r} == 'failed': + assert False, 'deliberate subtest failure' + if i == 1 and {outcome!r} == 'skipped': + pytest.skip('deliberate subtest skip') + + class TestUnittest(unittest.TestCase): + def test_subtests(self): + for i in range(2): + with self.subTest(i=i): + check(i) + + def test_pytest(subtests): + for i in range(2): + with subtests.test(i=i): + check(i) + + def test_pass(): + assert True + + @pytest.mark.skip(reason='deliberate regular skip') + def test_skip(): + pass + + @pytest.mark.xfail(strict=True, reason='deliberate expected failure') + def test_xfail(): + assert False + """) + ) + env = { + key: value + for key, value in os.environ.items() + if not key.startswith(('B2_', 'PYTEST_', 'COV_CORE_', 'COVERAGE_')) + } + env['PYTHONPATH'] = str(ROOT) + completed = subprocess.run( + [sys.executable, '-m', 'pytest', '-n', str(workers), '--junitxml=result.xml', '-q'], + cwd=tmp_path, + env=env, + capture_output=True, + text=True, + timeout=90, + ) + assert completed.returncode == (1 if outcome == 'failed' else 0), ( + completed.stdout + completed.stderr + ) + suite = ET.parse(tmp_path / 'result.xml').getroot().find('testsuite') + cases = suite.findall('testcase') + assert int(suite.get('tests')) == len(cases), completed.stdout + # Two parents, four independently reported subtests, and three plain tests. + assert len(cases) == 9 + for tag, attribute in [('failure', 'failures'), ('error', 'errors'), ('skipped', 'skipped')]: + assert int(suite.get(attribute)) == sum(case.find(tag) is not None for case in cases) + assert all( + sum(child.tag in ('failure', 'error', 'skipped') for child in case) <= 1 for case in cases + ) + assert int(suite.get('failures')) == (3 if outcome == 'failed' else 0) + assert int(suite.get('errors')) == 0 + assert int(suite.get('skipped')) == (4 if outcome == 'skipped' else 2) + + +@pytest.mark.parametrize('workers', [0, 2]) +def test_junit_totals_include_a_failed_parent_and_its_teardown_error(tmp_path, workers): + (tmp_path / 'pytest.ini').write_text('[pytest]\n') + (tmp_path / 'conftest.py').write_text("pytest_plugins = ['test.junit_subtests']\n") + (tmp_path / 'test_sample.py').write_text( + textwrap.dedent(""" + import pytest + + @pytest.fixture + def broken_teardown(): + yield + raise RuntimeError('deliberate teardown error') + + def test_subtest(subtests, broken_teardown): + with subtests.test('deliberate failure'): + assert False + """) + ) + env = { + key: value + for key, value in os.environ.items() + if not key.startswith(('B2_', 'PYTEST_', 'COV_CORE_', 'COVERAGE_')) + } + env['PYTHONPATH'] = str(ROOT) + completed = subprocess.run( + [sys.executable, '-m', 'pytest', '-n', str(workers), '--junitxml=result.xml', '-q'], + cwd=tmp_path, + env=env, + capture_output=True, + text=True, + timeout=90, + ) + assert completed.returncode == 1, completed.stdout + completed.stderr + suite = ET.parse(tmp_path / 'result.xml').getroot().find('testsuite') + cases = suite.findall('testcase') + assert int(suite.get('tests')) == len(cases) + assert len(cases) == 3 # failed subtest, failed parent call, errored teardown + assert int(suite.get('failures')) == 2 + assert int(suite.get('errors')) == 1 + assert sum(case.find('failure') is not None for case in cases) == 2 + assert sum(case.find('error') is not None for case in cases) == 1 + + +@pytest.mark.parametrize('workers', [0, 2]) +@pytest.mark.parametrize('outcome', ['passed', 'failed', 'skipped', 'xfail']) +@pytest.mark.parametrize('log_passing', [True, False]) +def test_junit_subtests_retain_requested_captured_output(tmp_path, workers, outcome, log_passing): + (tmp_path / 'pytest.ini').write_text('[pytest]\n') + (tmp_path / 'conftest.py').write_text("pytest_plugins = ['test.junit_subtests']\n") + (tmp_path / 'test_sample.py').write_text( + textwrap.dedent(f""" + import sys + import pytest + + def test_subtest(subtests): + with subtests.test('captured output'): + print('SUBTEST_STDOUT') + print('SUBTEST_STDERR', file=sys.stderr) + if {outcome!r} == 'failed': + assert False + if {outcome!r} == 'skipped': + pytest.skip('deliberate skip') + if {outcome!r} == 'xfail': + pytest.xfail('deliberate expected failure') + """) + ) + env = { + key: value + for key, value in os.environ.items() + if not key.startswith(('B2_', 'PYTEST_', 'COV_CORE_', 'COVERAGE_')) + } + env['PYTHONPATH'] = str(ROOT) + completed = subprocess.run( + [ + sys.executable, + '-m', + 'pytest', + '-n', + str(workers), + '--junitxml=result.xml', + '-q', + '-o', + 'junit_logging=all', + '-o', + f'junit_log_passing_tests={log_passing}', + ], + cwd=tmp_path, + env=env, + capture_output=True, + text=True, + timeout=90, + ) + assert completed.returncode == (1 if outcome == 'failed' else 0), ( + completed.stdout + completed.stderr + ) + cases = ET.parse(tmp_path / 'result.xml').getroot().findall('.//testcase') + subcase = next(case for case in cases if case.get('name').startswith('subtest-')) + for tag, token in [('system-out', 'SUBTEST_STDOUT'), ('system-err', 'SUBTEST_STDERR')]: + captured = subcase.findall(tag) + if log_passing or outcome != 'passed': + assert len(captured) == 1 + assert token in captured[0].text + else: + assert not captured + + +def test_junit_does_not_count_an_interrupted_test_as_passed(tmp_path): + (tmp_path / 'pytest.ini').write_text('[pytest]\n') + (tmp_path / 'conftest.py').write_text("pytest_plugins = ['test.junit_subtests']\n") + (tmp_path / 'test_sample.py').write_text( + 'def test_interrupted():\n raise KeyboardInterrupt\n' + ) + env = { + key: value + for key, value in os.environ.items() + if not key.startswith(('B2_', 'PYTEST_', 'COV_CORE_', 'COVERAGE_')) + } + env['PYTHONPATH'] = str(ROOT) + completed = subprocess.run( + [sys.executable, '-m', 'pytest', '--junitxml=result.xml', '-q'], + cwd=tmp_path, + env=env, + capture_output=True, + text=True, + timeout=30, + ) + assert completed.returncode == 2, completed.stdout + completed.stderr + suite = ET.parse(tmp_path / 'result.xml').getroot().find('testsuite') + declared_passes = int(suite.get('tests')) - sum( + int(suite.get(key)) for key in ('failures', 'errors', 'skipped') + ) + assert declared_passes == 0, 'an interrupted call has no passing test outcome' diff --git a/uv.lock b/uv.lock index 46673c7fb..322bda999 100644 --- a/uv.lock +++ b/uv.lock @@ -1,5 +1,5 @@ version = 1 -revision = 3 +revision = 5 requires-python = ">=3.10" resolution-markers = [ "python_full_version >= '3.11'", @@ -94,6 +94,8 @@ lint = [ { name = "liccheck" }, { name = "pip" }, { name = "pytest" }, + { name = "pytest-xdist" }, + { name = "pyyaml" }, { name = "ruff" }, { name = "setuptools" }, { name = "tenacity" }, @@ -118,6 +120,7 @@ test = [ { name = "pytest-watcher" }, { name = "pytest-xdist" }, { name = "pywin32", marker = "platform_python_implementation != 'PyPy' and sys_platform == 'win32'" }, + { name = "pyyaml" }, { name = "responses" }, { name = "tenacity" }, { name = "tqdm" }, @@ -151,6 +154,8 @@ lint = [ { name = "liccheck", specifier = "==0.9.2" }, { name = "pip", specifier = ">=26.2.2" }, { name = "pytest", specifier = ">=9.0.3,<10" }, + { name = "pytest-xdist", specifier = ">=3.8.0,<4" }, + { name = "pyyaml", specifier = ">=6,<7" }, { name = "ruff", specifier = "~=0.8.4" }, { name = "setuptools", specifier = "<81" }, { name = "tenacity", specifier = ">=9.1.4,<10" }, @@ -173,6 +178,7 @@ test = [ { name = "pytest-watcher", specifier = ">=0.6.3,<1" }, { name = "pytest-xdist", specifier = ">=3.8.0,<4" }, { name = "pywin32", marker = "platform_python_implementation != 'PyPy' and sys_platform == 'win32'", specifier = ">=311,<312" }, + { name = "pyyaml", specifier = ">=6,<7" }, { name = "responses", specifier = ">=0.26.0,<1" }, { name = "tenacity", specifier = ">=9.1.4,<10" }, { name = "tqdm", specifier = ">=4.5.0,<5.0.0" }, From 84ce6f5ab9d8cbf9cdb904ca926cb847a118108a Mon Sep 17 00:00:00 2001 From: Felipe Fumero Date: Sat, 21 Nov 2026 14:31:37 -0600 Subject: [PATCH 040/113] fix: accept iterable notification rules (#704) --- b2sdk/_internal/bucket.py | 2 +- .../+notification-rule-iterables.fixed.md | 1 + test/unit/bucket/test_regression_bucket.py | 29 ++++++++++--------- 3 files changed, 17 insertions(+), 15 deletions(-) create mode 100644 changelog.d/+notification-rule-iterables.fixed.md diff --git a/b2sdk/_internal/bucket.py b/b2sdk/_internal/bucket.py index 48e2e4a3b..4f4c85dc9 100644 --- a/b2sdk/_internal/bucket.py +++ b/b2sdk/_internal/bucket.py @@ -1555,7 +1555,7 @@ def set_notification_rules( """ Set notification rules for this bucket. """ - return self.api.session.set_bucket_notification_rules(self.id_, rules) + return self.api.session.set_bucket_notification_rules(self.id_, list(rules)) class BucketFactory: diff --git a/changelog.d/+notification-rule-iterables.fixed.md b/changelog.d/+notification-rule-iterables.fixed.md new file mode 100644 index 000000000..b8779b949 --- /dev/null +++ b/changelog.d/+notification-rule-iterables.fixed.md @@ -0,0 +1 @@ +Allow notification rules to be supplied as any iterable. diff --git a/test/unit/bucket/test_regression_bucket.py b/test/unit/bucket/test_regression_bucket.py index ab831e4cd..2050f43f1 100644 --- a/test/unit/bucket/test_regression_bucket.py +++ b/test/unit/bucket/test_regression_bucket.py @@ -344,21 +344,23 @@ def test_c28_create_bucket_mismatch_message_names_both_buckets(self): assert 'returned-other-name' in message, message -class TestRegressionRawApiContract: - @responses.activate - @known_defect( - 'C35', - 'set_notification_rules fails for a generator although it is typed as Iterable', - raises=DefectStillPresent, - ) +class TestRegressionRawApiContract(TestCaseWithBucket): def test_c35_set_notification_rules_accepts_a_generator(self): - """C35: set_notification_rules is typed Iterable; a generator must serialize to JSON.""" + self._check_iterable_rules('generator') + + def test_c35_set_notification_rules_accepts_a_set(self): + self._check_iterable_rules('set') + + @responses.activate + def _check_iterable_rules(self, input_kind): + """C35: Bucket accepts iterable rules and sends a JSON array.""" raw_api = B2RawHTTPApi( B2Http(B2HttpApiConfig(requests.Session, install_clock_skew_hook=False)) ) + self.api.session.raw_api = raw_api responses.add( responses.POST, - f'https://api.example.com/b2api/{B2RawHTTPApi.API_VERSION}/b2_set_bucket_notification_rules', + f'{self.api_url}/b2api/{B2RawHTTPApi.API_VERSION}/b2_set_bucket_notification_rules', json={'eventNotificationRules': []}, ) rule = { @@ -372,13 +374,12 @@ def test_c35_set_notification_rules_accepts_a_generator(self): 'customHeaders': [], }, } - with defect_raises(TypeError, match='not JSON serializable'): - sent = raw_api.set_bucket_notification_rules( - 'https://api.example.com', 'token', 'bucket-id', (r for r in [rule]) - ) + expected = [rule] if input_kind == 'generator' else [] + rules = (r for r in expected) if input_kind == 'generator' else set() + sent = self.bucket.set_notification_rules(rules) assert sent == [], sent body = json.loads(responses.calls[0].request.body) - assert body['eventNotificationRules'] == [rule], body + assert body['eventNotificationRules'] == expected, body class TestRegressionLargeUploadFailure: From 08f06b3e94488050184534a80fbad037c6cc2279 Mon Sep 17 00:00:00 2001 From: Felipe Fumero Date: Sat, 21 Nov 2026 14:36:09 -0600 Subject: [PATCH 041/113] Format the expires header locale-independently (#705) * fix: format expiration dates independently of locale * test: harden the C32 regression to run without an OS locale The C32 expires-header regression previously skipped on hosts with no non-English locale installed, so CI could not catch a recurrence of the locale-dependent strftime formatting. Replace the setlocale dance with a monkeypatch that forces the bucket module's datetime.strftime to emit non-English day/month names, so the test runs everywhere and fails if the formatter reverts to locale-dependent output. --- b2sdk/_internal/bucket.py | 3 +- changelog.d/+http-date-locale.fixed.md | 1 + test/unit/bucket/test_regression_bucket.py | 71 +++++++++++++++------- 3 files changed, 51 insertions(+), 24 deletions(-) create mode 100644 changelog.d/+http-date-locale.fixed.md diff --git a/b2sdk/_internal/bucket.py b/b2sdk/_internal/bucket.py index 4f4c85dc9..6c8c8d24d 100644 --- a/b2sdk/_internal/bucket.py +++ b/b2sdk/_internal/bucket.py @@ -15,6 +15,7 @@ import logging import pathlib from contextlib import suppress +from email.utils import format_datetime from typing import Iterable, Sequence from .encryption.setting import EncryptionSetting, EncryptionSettingFactory @@ -142,7 +143,7 @@ def _merge_file_info_and_headers_params( if isinstance(expires, dt.datetime): expires = expires.astimezone(dt.timezone.utc) - expires = dt.datetime.strftime(expires, '%a, %d %b %Y %H:%M:%S GMT') + expires = format_datetime(expires, usegmt=True) self._add_file_info_item(updated_file_info, 'b2-expires', expires) self._add_file_info_item(updated_file_info, 'b2-cache-control', cache_control) diff --git a/changelog.d/+http-date-locale.fixed.md b/changelog.d/+http-date-locale.fixed.md new file mode 100644 index 000000000..0afbee4f4 --- /dev/null +++ b/changelog.d/+http-date-locale.fixed.md @@ -0,0 +1 @@ +Fixed locale-dependent formatting of HTTP expiration dates. diff --git a/test/unit/bucket/test_regression_bucket.py b/test/unit/bucket/test_regression_bucket.py index 2050f43f1..4a676ea53 100644 --- a/test/unit/bucket/test_regression_bucket.py +++ b/test/unit/bucket/test_regression_bucket.py @@ -21,8 +21,8 @@ import concurrent.futures import datetime import json -import locale import threading +import types from unittest import mock import apiver_deps @@ -251,30 +251,55 @@ def recording(upload_url, token, part_number, content_length, *args, **kwargs): f'parts below the recommended part size {recommended_part_size}: {non_final}', ) - @pytest.mark.skipif( - not hasattr(locale, 'setlocale'), reason='locale support is required for this test' - ) - @known_defect( - 'C32', - 'the "expires" header uses day and month names of the process locale', - raises=AssertionError, - ) def test_c32_expires_header_uses_english_names_under_foreign_locale(self): - """C32: the 'expires' date must not use process-locale day/month names.""" - old = locale.setlocale(locale.LC_TIME) - for name in ('de_DE.UTF-8', 'de_DE.utf8', 'fr_FR.UTF-8', 'es_ES.UTF-8'): - try: - locale.setlocale(locale.LC_TIME, name) - break - except locale.Error: - continue - else: - pytest.skip('no non-English locale available on this host') - try: - expires = datetime.datetime(2050, 12, 1, 16, 0, tzinfo=datetime.timezone.utc) + """C32: the 'expires' date must not use process-locale day/month names. + + Runs on every host, never skips: rather than depending on a non-English OS locale + being installed, it forces the bucket module's ``datetime.strftime`` to emit + non-English day/month names (as a reverted, locale-dependent formatter would under a + foreign ``LC_TIME``). The fix formats with ``email.utils.format_datetime``, which is + locale-independent, so the header stays English; a regression to ``strftime('%a…%b…')`` + would pick up the foreign names and fail this assertion. + """ + import b2sdk._internal.bucket as bucket_module + + # Abbreviated day/month names as a German LC_TIME would render them; used to simulate + # the locale leakage a locale-dependent strftime would exhibit on a non-English host. + foreign_names = { + 'Mon': 'Mo', + 'Tue': 'Di', + 'Wed': 'Mi', + 'Thu': 'Do', + 'Fri': 'Fr', + 'Sat': 'Sa', + 'Sun': 'So', + 'Mar': 'Mär', + 'May': 'Mai', + 'Oct': 'Okt', + 'Dec': 'Dez', + } + + class _ForeignLocaleDatetimeMeta(type): + def __instancecheck__(cls, instance): + return isinstance(instance, datetime.datetime) + + class _ForeignLocaleDatetime(metaclass=_ForeignLocaleDatetimeMeta): + @staticmethod + def strftime(value, fmt): + # Localise exactly as the C library would under a foreign LC_TIME: substitute + # the English %a/%b tokens, so only a locale-dependent formatter is caught. + rendered = datetime.datetime.strftime(value, fmt) + for english, foreign in foreign_names.items(): + rendered = rendered.replace(english, foreign) + return rendered + + foreign_dt = types.SimpleNamespace( + datetime=_ForeignLocaleDatetime, timezone=datetime.timezone + ) + + expires = datetime.datetime(2050, 12, 1, 16, 0, tzinfo=datetime.timezone.utc) + with mock.patch.object(bucket_module, 'dt', foreign_dt): file_version = self.bucket.upload_bytes(b'x', 'f.txt', expires=expires) - finally: - locale.setlocale(locale.LC_TIME, old) assert ( file_version.file_info['b2-expires'] == 'Thu, 01 Dec 2050 16:00:00 GMT' ), file_version.file_info From 2ff39debadc2d1814dcbbf7225d1a3d27538f3a9 Mon Sep 17 00:00:00 2001 From: Felipe Fumero Date: Sat, 21 Nov 2026 14:49:48 -0600 Subject: [PATCH 042/113] fix: allow chained stream reads with no size (#706) --- b2sdk/_internal/stream/chained.py | 2 +- changelog.d/+chained-stream-read-none.fixed.md | 1 + test/unit/stream/test_regression_streams.py | 18 +++--------------- 3 files changed, 5 insertions(+), 16 deletions(-) create mode 100644 changelog.d/+chained-stream-read-none.fixed.md diff --git a/b2sdk/_internal/stream/chained.py b/b2sdk/_internal/stream/chained.py index 90fcbb842..5a3962663 100644 --- a/b2sdk/_internal/stream/chained.py +++ b/b2sdk/_internal/stream/chained.py @@ -97,7 +97,7 @@ def read(self, size=None): """ byte_arrays = [] - if size < 0 or size is None: + if size is None or size < 0: while 1: current_stream = self.stream buff = current_stream.read() diff --git a/changelog.d/+chained-stream-read-none.fixed.md b/changelog.d/+chained-stream-read-none.fixed.md new file mode 100644 index 000000000..bdcff774e --- /dev/null +++ b/changelog.d/+chained-stream-read-none.fixed.md @@ -0,0 +1 @@ +Fix reading a chained stream when the size is omitted or None. diff --git a/test/unit/stream/test_regression_streams.py b/test/unit/stream/test_regression_streams.py index b176422eb..bdffe4a01 100644 --- a/test/unit/stream/test_regression_streams.py +++ b/test/unit/stream/test_regression_streams.py @@ -31,7 +31,7 @@ UploadSourceStreamRange, ) from b2sdk._internal.utils import hex_sha1_of_unlimited_stream -from test.known_defect import DefectStillPresent, defect_raises, expect, known_defect +from test.known_defect import DefectStillPresent, expect, known_defect class ShortReadStream(io.RawIOBase): @@ -88,28 +88,16 @@ def test_c46_read_none_stays_within_range(self): class TestChainedStream: - @known_defect( - 'C11', - 'ChainedStream.read() with the default size raises TypeError instead of reading everything', - raises=DefectStillPresent, - ) def test_c11_default_read_returns_everything(self): """C11: read() with default size reads everything (docs), not a TypeError.""" stream = ChainedStream([lambda: io.BytesIO(b'abc'), lambda: io.BytesIO(b'def')]) - with defect_raises(TypeError, match="'<' not supported between instances of 'NoneType'"): - data = stream.read() + data = stream.read() assert data == b'abcdef', 'read() did not return all data' - @known_defect( - 'C11', - 'ChainedStream.read(None) raises TypeError instead of reading everything', - raises=DefectStillPresent, - ) def test_c11_explicit_none_returns_everything(self): """C11: read(None) is documented as 'read everything'.""" stream = ChainedStream([lambda: io.BytesIO(b'abc'), lambda: io.BytesIO(b'def')]) - with defect_raises(TypeError, match="'<' not supported between instances of 'NoneType'"): - data = stream.read(None) + data = stream.read(None) assert data == b'abcdef', 'read(None) did not return all data' def test_c12_guard_sized_reads_cross_stream_boundaries(self): From 579a1365c467012138f9908fb7519881f1d243c5 Mon Sep 17 00:00:00 2001 From: Felipe Fumero Date: Sat, 21 Nov 2026 14:50:05 -0600 Subject: [PATCH 043/113] fix: fall back when package version metadata is unavailable (#707) --- b2sdk/version.py | 6 +++- .../+version-metadata-fallback.fixed.md | 1 + test/static/test_regression_repo_checks.py | 11 ++----- test/unit/test_version.py | 30 +++++++++++++++++++ 4 files changed, 39 insertions(+), 9 deletions(-) create mode 100644 changelog.d/+version-metadata-fallback.fixed.md create mode 100644 test/unit/test_version.py diff --git a/b2sdk/version.py b/b2sdk/version.py index 241bce2ec..26d80f488 100644 --- a/b2sdk/version.py +++ b/b2sdk/version.py @@ -9,6 +9,7 @@ ###################################################################### from __future__ import annotations +from importlib.metadata import PackageNotFoundError from importlib.metadata import version as _version from sys import version_info as _version_info @@ -18,7 +19,10 @@ 'USER_AGENT', ] -VERSION = _version('b2sdk') +try: + VERSION = _version('b2sdk') +except PackageNotFoundError: + VERSION = '0.0.0+unknown' PYTHON_VERSION = '.'.join(map(str, _version_info[:3])) # something like: 3.9.1 diff --git a/changelog.d/+version-metadata-fallback.fixed.md b/changelog.d/+version-metadata-fallback.fixed.md new file mode 100644 index 000000000..d1e20db45 --- /dev/null +++ b/changelog.d/+version-metadata-fallback.fixed.md @@ -0,0 +1 @@ +Fix importing vendored or uninstalled copies of the SDK by using a fallback version when package metadata is unavailable. diff --git a/test/static/test_regression_repo_checks.py b/test/static/test_regression_repo_checks.py index 0fe61c387..0199a8adf 100644 --- a/test/static/test_regression_repo_checks.py +++ b/test/static/test_regression_repo_checks.py @@ -28,7 +28,7 @@ import pytest -from test.known_defect import DefectStillPresent, expect, known_defect +from test.known_defect import known_defect ROOT = Path(__file__).resolve().parents[2] @@ -52,11 +52,6 @@ def test_c59_readme_mentions_full_extra(): assert re.search(r'b2sdk\[full\]', _read('README.md')), 'README does not mention b2sdk[full]' -@known_defect( - 'C36', - 'importing b2sdk fails when the package metadata is not installed', - raises=DefectStillPresent, -) def test_c36_version_import_works_when_package_metadata_is_missing(tmp_path): """C36: importing a vendored/uninstalled copy of b2sdk must not fail for missing dist metadata.""" script = textwrap.dedent( @@ -70,11 +65,11 @@ def fake(name): m.version = fake sys.path.insert(0, {str(ROOT)!r}) import b2sdk.version + assert b2sdk.__version__ == b2sdk.version.VERSION + assert b2sdk.version.VERSION """ ) result = subprocess.run( [sys.executable, '-c', script], capture_output=True, text=True, cwd=tmp_path ) - # only the missing-metadata error is the defect; any other failure is a real failure - expect('PackageNotFoundError' not in result.stderr, result.stderr[-300:]) assert result.returncode == 0, result.stderr[-300:] diff --git a/test/unit/test_version.py b/test/unit/test_version.py new file mode 100644 index 000000000..39921a213 --- /dev/null +++ b/test/unit/test_version.py @@ -0,0 +1,30 @@ +###################################################################### +# +# File: test/unit/test_version.py +# +# Copyright 2026 Backblaze Inc. All Rights Reserved. +# +# License https://www.backblaze.com/using_b2_code.html +# +###################################################################### +from __future__ import annotations + +import importlib.util +from importlib.metadata import PackageNotFoundError +from pathlib import Path +from unittest.mock import patch + +from packaging.version import Version + + +def test_version_import_without_package_metadata(): + spec = importlib.util.spec_from_file_location( + 'version_under_test', Path(__file__).resolve().parents[2] / 'b2sdk' / 'version.py' + ) + module = importlib.util.module_from_spec(spec) + with patch('importlib.metadata.version', side_effect=PackageNotFoundError('b2sdk')): + spec.loader.exec_module(module) + + assert module.VERSION + assert str(Version(module.VERSION)) == module.VERSION + assert module.USER_AGENT == f'backblaze-b2/{module.VERSION} python/{module.PYTHON_VERSION}' From 6a9831458830b902a1aa0258dbc48ef516dafd2b Mon Sep 17 00:00:00 2001 From: Felipe Fumero Date: Sat, 21 Nov 2026 14:50:30 -0600 Subject: [PATCH 044/113] fix: reject saving a consumed download again (#708) --- .../transfer/inbound/downloaded_file.py | 13 ++++++++ .../+downloaded-file-double-save.fixed.md | 1 + test/unit/bucket/test_bucket.py | 31 +++++++++++++++++++ test/unit/bucket/test_regression_bucket.py | 15 +++------ 4 files changed, 49 insertions(+), 11 deletions(-) create mode 100644 changelog.d/+downloaded-file-double-save.fixed.md diff --git a/b2sdk/_internal/transfer/inbound/downloaded_file.py b/b2sdk/_internal/transfer/inbound/downloaded_file.py index 7242b19df..b75923dc7 100644 --- a/b2sdk/_internal/transfer/inbound/downloaded_file.py +++ b/b2sdk/_internal/transfer/inbound/downloaded_file.py @@ -168,6 +168,7 @@ def __init__( self.download_strategy = None self.write_buffer_size = write_buffer_size self.check_hash = check_hash + self._consumed = False def _validate_download(self, bytes_read, actual_sha1): if ( @@ -201,7 +202,10 @@ def save(self, file: BinaryIO, allow_seeking: bool | None = None) -> None: :param file: a file-like object :param allow_seeking: if False, download strategies that rely on seeking to write data (parallel strategies) will be discarded. + :raises RuntimeError: if a download has already been attempted on this object """ + self._check_not_consumed() + if allow_seeking is None: allow_seeking = file.seekable() elif allow_seeking and not file.seekable(): @@ -230,6 +234,7 @@ def save(self, file: BinaryIO, allow_seeking: bool | None = None) -> None: else: raise ValueError('no strategy suitable for download was found!') self.download_strategy = strategy + self._consumed = True bytes_read, actual_sha1 = strategy.download( file, response=self.response, @@ -239,6 +244,12 @@ def save(self, file: BinaryIO, allow_seeking: bool | None = None) -> None: ) self._validate_download(bytes_read, actual_sha1) + def _check_not_consumed(self) -> None: + if self._consumed: + raise RuntimeError( + 'This download response has already been consumed. Request a new download to save again.' + ) + def save_to( self, path_: str | pathlib.Path, @@ -252,7 +263,9 @@ def save_to( :param mode: mode in which the file should be opened :param allow_seeking: if False, download strategies that rely on seeking to write data (parallel strategies) will be discarded. + :raises RuntimeError: if a download has already been attempted on this object """ + self._check_not_consumed() path_ = pathlib.Path(path_) is_stdout = points_to_stdout(path_) if is_stdout or points_to_fifo(path_): diff --git a/changelog.d/+downloaded-file-double-save.fixed.md b/changelog.d/+downloaded-file-double-save.fixed.md new file mode 100644 index 000000000..8a7b9fdce --- /dev/null +++ b/changelog.d/+downloaded-file-double-save.fixed.md @@ -0,0 +1 @@ +Raise a clear error when saving a consumed download again, before modifying the destination. diff --git a/test/unit/bucket/test_bucket.py b/test/unit/bucket/test_bucket.py index 86ff96fc1..80a420d20 100644 --- a/test/unit/bucket/test_bucket.py +++ b/test/unit/bucket/test_bucket.py @@ -51,6 +51,8 @@ UnsatisfiableRange, WrongEncryptionSettingForFileWrite, ) +from requests import Response +from urllib3.response import HTTPResponse from test.helpers import NonSeekableIO, assert_dict_equal_ignore_extra @@ -2956,6 +2958,35 @@ def test_download_by_name_unverified_checksum(self): @pytest.mark.apiver(from_ver=2) class TestChooseStrategy(TestCaseWithBucket): + def test_save_twice(self): + for data in (b'', b'hello world'): + for save_method in ('save', 'save_to'): + with self.subTest(data=data, save_method=save_method): + file_version = self.bucket.upload_bytes(data, 'file1') + downloaded_file = self.bucket.download_file_by_id(file_version.id_) + # Use a streaming response: the simulator response can be replayed. + response = Response() + response.request = downloaded_file.response.request + response.headers.update(downloaded_file.response.headers) + response.raw = HTTPResponse(body=io.BytesIO(data), preload_content=False) + downloaded_file.response = response + first_output = io.BytesIO() + downloaded_file.save(first_output) + assert first_output.getvalue() == data + + second_output = io.BytesIO(b'existing data') + with tempfile.TemporaryDirectory() as directory: + destination = pathlib.Path(directory) / 'destination' + destination.write_bytes(b'existing data') + with pytest.raises(RuntimeError, match='already been consumed'): + if save_method == 'save': + downloaded_file.save(second_output) + else: + downloaded_file.save_to(destination) + + assert second_output.getvalue() == b'existing data' + assert destination.read_bytes() == b'existing data' + def test_choose_strategy(self): file_version = self.bucket.upload_bytes(b'hello world' * 8, 'file1') download_manager = self.bucket.api.services.download_manager diff --git a/test/unit/bucket/test_regression_bucket.py b/test/unit/bucket/test_regression_bucket.py index 4a676ea53..491d40837 100644 --- a/test/unit/bucket/test_regression_bucket.py +++ b/test/unit/bucket/test_regression_bucket.py @@ -471,15 +471,8 @@ def recording_submit(*args, **kwargs): class TestRegressionDownloadedFileContract: @responses.activate - @known_defect( - 'C56', - 'DownloadedFile.save() called twice re-reads a used response', - raises=DefectStillPresent, - ) - def test_c56_downloaded_file_can_be_saved_twice_from_a_real_response(self): - """C56: save() called twice on a real streamed HTTP response must give the full data again; - the simulator's in-memory response hides this. Today the second call raises requests' - StreamConsumedError.""" + def test_c56_downloaded_file_rejects_second_save_from_a_real_response(self): + """A consumed HTTP response must be rejected with a clear error on re-save.""" import hashlib import io from unittest import mock @@ -504,9 +497,9 @@ def test_c56_downloaded_file_can_be_saved_twice_from_a_real_response(self): first, second = io.BytesIO(), io.BytesIO() downloaded.save(first) assert first.getvalue() == data, 'first save() returned wrong data' - with defect_raises(requests.exceptions.StreamConsumedError): + with pytest.raises(RuntimeError, match='already been consumed'): downloaded.save(second) - assert second.getvalue() == data, 'second save() returned wrong data' + assert second.getvalue() == b'', 'rejected save() modified the destination' class TestRegressionGuards(TestCaseWithBucket): From 747cab9254a05ecba2a97558234423f8b822e027 Mon Sep 17 00:00:00 2001 From: Felipe Fumero Date: Sat, 21 Nov 2026 14:58:41 -0600 Subject: [PATCH 045/113] fix: preserve content type when copying with headers (#709) * fix: preserve content type when copying with headers * fix: avoid inheriting checksums for partial copies * docs: clarify checksum handling for copy ranges --- b2sdk/_internal/bucket.py | 40 +++- .../+copy-header-content-type.fixed.md | 1 + .../bucket/test_copy_header_content_type.py | 191 ++++++++++++++++++ test/unit/bucket/test_regression_bucket.py | 22 +- 4 files changed, 238 insertions(+), 16 deletions(-) create mode 100644 changelog.d/+copy-header-content-type.fixed.md create mode 100644 test/unit/bucket/test_copy_header_content_type.py diff --git a/b2sdk/_internal/bucket.py b/b2sdk/_internal/bucket.py index 6c8c8d24d..725911154 100644 --- a/b2sdk/_internal/bucket.py +++ b/b2sdk/_internal/bucket.py @@ -40,7 +40,11 @@ ) from .file_version import DownloadVersion, FileIdAndName, FileVersion from .filter import Filter, FilterMatcher -from .http_constants import LIST_FILE_NAMES_MAX_LIMIT +from .http_constants import ( + LARGE_FILE_SHA1, + LIST_FILE_NAMES_MAX_LIMIT, + SSE_C_KEY_ID_FILE_INFO_KEY_NAME, +) from .progress import AbstractProgressListener, DoNothingProgressListener from .raw_api import LifecycleRule, NotificationRule, NotificationRuleResponse from .replication.setting import ReplicationConfiguration, ReplicationConfigurationFactory @@ -1441,7 +1445,39 @@ def copy( Example string value: 'gzip'. :param str,None content_language: an optional content language setting. Syntax based on the section 14.12 of RFC 2616. Example string value: 'mi, en_US'. - """ + + .. note:: + When header overrides are provided without ``content_type``, source metadata is used + to preserve the content type and, if ``file_info`` is omitted, the source file info. + If the required source metadata is not supplied, fetching it requires the ``readFiles`` + capability. Supplying ``source_content_type`` and either ``source_file_info`` or + destination ``file_info`` avoids that lookup. + For partial copies and other copies with a specified range, the inherited + ``large_file_sha1`` is omitted because it may not describe the copied bytes. + """ + + if content_type is None and any( + value is not None + for value in ( + cache_control, + expires, + content_disposition, + content_encoding, + content_language, + ) + ): + if source_content_type is None or (file_info is None and source_file_info is None): + source_metadata = self.api.session.get_file_info_by_id(file_id) + if source_content_type is None: + source_content_type = source_metadata['contentType'] + if source_file_info is None: + source_file_info = source_metadata['fileInfo'] + content_type = source_content_type + if file_info is None: + file_info = source_file_info.copy() + file_info.pop(SSE_C_KEY_ID_FILE_INFO_KEY_NAME, None) + if offset or length: + file_info.pop(LARGE_FILE_SHA1, None) copy_source = CopySource( file_id, diff --git a/changelog.d/+copy-header-content-type.fixed.md b/changelog.d/+copy-header-content-type.fixed.md new file mode 100644 index 000000000..b4a659396 --- /dev/null +++ b/changelog.d/+copy-header-content-type.fixed.md @@ -0,0 +1 @@ +Preserve the source content type when copying with header overrides and avoid inheriting an incorrect checksum for ranged copies. diff --git a/test/unit/bucket/test_copy_header_content_type.py b/test/unit/bucket/test_copy_header_content_type.py new file mode 100644 index 000000000..252d8f733 --- /dev/null +++ b/test/unit/bucket/test_copy_header_content_type.py @@ -0,0 +1,191 @@ +###################################################################### +# +# File: test/unit/bucket/test_copy_header_content_type.py +# +# Copyright 2026 Backblaze Inc. All Rights Reserved. +# +# License https://www.backblaze.com/using_b2_code.html +# +###################################################################### +from hashlib import sha1 +from unittest import mock + +import pytest + +from b2sdk._internal.exception import AccessDenied +from b2sdk._internal.http_constants import LARGE_FILE_SHA1, SSE_C_KEY_ID_FILE_INFO_KEY_NAME + +from .test_bucket import SSE_C_AES, SSE_C_AES_2 + + +@pytest.mark.apiver(from_ver=2) +@pytest.mark.parametrize('length', [None, 5]) +@pytest.mark.parametrize('provide_source_metadata', [False, True]) +def test_copy_headers_without_content_type_preserves_source_metadata( + bucket, length, provide_source_metadata, monkeypatch +): + source = bucket.upload_bytes( + b'hello', 'source.txt', content_type='application/x-example', file_info={'owner': 'alice'} + ) + source_metadata = ( + {'source_content_type': source.content_type, 'source_file_info': source.file_info} + if provide_source_metadata + else {} + ) + if provide_source_metadata: + + def fail_lookup(*args, **kwargs): + raise AssertionError('source metadata lookup was unnecessary') + + monkeypatch.setattr(bucket.api.session, 'get_file_info_by_id', fail_lookup) + copied = bucket.copy( + source.id_, + 'destination.txt', + length=length, + expires='Thu, 01 Dec 2050 16:00:00 GMT', + content_language='en', + **source_metadata, + ) + assert copied.content_type == 'application/x-example' + assert copied.file_info['owner'] == 'alice' + assert copied.file_info['b2-expires'] == 'Thu, 01 Dec 2050 16:00:00 GMT' + assert copied.file_info['b2-content-language'] == 'en' + + +@pytest.mark.apiver(from_ver=2) +def test_copy_headers_uses_explicit_destination_metadata(bucket, monkeypatch): + source = bucket.upload_bytes( + b'hello', 'source.txt', content_type='application/x-example', file_info={'old': 'value'} + ) + + def fail_lookup(*args, **kwargs): + raise AssertionError('source metadata lookup was unnecessary') + + monkeypatch.setattr(bucket.api.session, 'get_file_info_by_id', fail_lookup) + copied = bucket.copy( + source.id_, + 'destination.txt', + source_content_type='application/x-example', + file_info={'new': 'value'}, + content_disposition='attachment', + ) + assert copied.content_type == 'application/x-example' + assert copied.file_info == {'new': 'value', 'b2-content-disposition': 'attachment'} + + +@pytest.mark.apiver(from_ver=2) +@pytest.mark.parametrize('length', [None, 5]) +@pytest.mark.parametrize('destination_encryption', [None, SSE_C_AES_2]) +def test_copy_headers_replaces_source_encryption_key_id(bucket, length, destination_encryption): + source = bucket.upload_bytes( + b'hello', + 'source.txt', + content_type='application/x-example', + file_info={'owner': 'alice'}, + encryption=SSE_C_AES, + ) + copied = bucket.copy( + source.id_, + 'destination.txt', + length=length, + source_encryption=SSE_C_AES, + destination_encryption=destination_encryption, + source_file_info=source.file_info, + source_content_type=source.content_type, + content_language='en', + ) + assert copied.file_info['owner'] == 'alice' + assert copied.file_info['b2-content-language'] == 'en' + assert copied.file_info.get(SSE_C_KEY_ID_FILE_INFO_KEY_NAME) == ( + destination_encryption.key.key_id if destination_encryption else None + ) + assert source.file_info[SSE_C_KEY_ID_FILE_INFO_KEY_NAME] == SSE_C_AES.key.key_id + + +@pytest.mark.apiver(from_ver=2) +@pytest.mark.parametrize('provide_source_metadata', [False, True]) +def test_partial_multipart_copy_does_not_inherit_source_checksum(bucket, provide_source_metadata): + data = b'a' * 300 + b'b' * 300 + source_checksum = sha1(data).hexdigest() + source = bucket.upload_bytes( + data, + 'source.txt', + content_type='application/x-example', + file_info={'owner': 'alice'}, + large_file_sha1=source_checksum, + ) + source_metadata = ( + {'source_content_type': source.content_type, 'source_file_info': source.file_info} + if provide_source_metadata + else {} + ) + with mock.patch.object( + bucket.api.session, 'copy_part', wraps=bucket.api.session.copy_part + ) as copy_part: + copied = bucket.copy( + source.id_, + 'partial.txt', + offset=100, + length=400, + max_part_size=200, + content_language='en', + **source_metadata, + ) + assert copy_part.call_count == 2 + assert copied.size == 400 + assert LARGE_FILE_SHA1 not in copied.file_info + assert copied.get_content_sha1() is None + assert copied.file_info['owner'] == 'alice' + assert copied.file_info['b2-content-language'] == 'en' + assert source.file_info[LARGE_FILE_SHA1] == source_checksum + + +@pytest.mark.apiver(from_ver=2) +def test_whole_file_copy_keeps_source_checksum(bucket): + data = b'hello' + checksum = sha1(data).hexdigest() + source = bucket.upload_bytes(data, 'source.txt', file_info={LARGE_FILE_SHA1: checksum}) + copied = bucket.copy(source.id_, 'destination.txt', content_language='en') + assert copied.file_info[LARGE_FILE_SHA1] == checksum + + +@pytest.mark.apiver(from_ver=2) +def test_partial_copy_keeps_explicit_destination_checksum(bucket): + data = b'a' * 300 + b'b' * 300 + source = bucket.upload_bytes(data, 'source.txt') + checksum = sha1(data[100:500]).hexdigest() + copied = bucket.copy( + source.id_, + 'partial.txt', + offset=100, + length=400, + max_part_size=200, + source_content_type=source.content_type, + file_info={LARGE_FILE_SHA1: checksum}, + content_language='en', + ) + assert copied.file_info[LARGE_FILE_SHA1] == checksum + assert copied.get_content_sha1() == checksum + + +@pytest.mark.apiver(from_ver=2) +def test_copy_headers_propagates_source_info_access_denied(bucket, monkeypatch): + source = bucket.upload_bytes(b'hello', 'source.txt') + + def deny_lookup(*args, **kwargs): + raise AccessDenied() + + monkeypatch.setattr(bucket.api.session, 'get_file_info_by_id', deny_lookup) + with mock.patch.object( + bucket.api.session, 'copy_file', wraps=bucket.api.session.copy_file + ) as copy_file: + with pytest.raises(AccessDenied): + bucket.copy(source.id_, 'destination.txt', content_language='en') + copy_file.assert_not_called() + + +@pytest.mark.apiver(from_ver=2) +def test_copy_documents_omission_of_source_checksum_for_partial_copies(bucket): + doc = bucket.copy.__doc__ + assert 'partial cop' in doc.lower() + assert 'large_file_sha1' in doc diff --git a/test/unit/bucket/test_regression_bucket.py b/test/unit/bucket/test_regression_bucket.py index 491d40837..1149c7855 100644 --- a/test/unit/bucket/test_regression_bucket.py +++ b/test/unit/bucket/test_regression_bucket.py @@ -43,7 +43,7 @@ UploadSourceBytes, WriteIntent, ) -from apiver_deps_exception import CopyArgumentsMismatch, NonExistentBucket +from apiver_deps_exception import NonExistentBucket from test.known_defect import DefectStillPresent, defect_raises, expect, known_defect @@ -53,22 +53,16 @@ class TestRegressionCopyAndLs(TestCaseWithBucket): - @known_defect( - 'C1', - 'copy() with expires/content_disposition/cache_control but no content_type is refused', - raises=DefectStillPresent, - ) def test_c1_copy_with_expiry_but_no_content_type(self): """C1: copy() with expires/headers but no content_type must work (2.13.3 notes).""" file_id = self.bucket.upload_bytes(b'hello world', 'src.txt').id_ - with defect_raises(CopyArgumentsMismatch, match='content type'): - copied = self.bucket.copy( - file_id, - 'copied.txt', - expires='Thu, 01 Dec 2050 16:00:00 GMT', - content_disposition='attachment', - cache_control='max-age=5', - ) + copied = self.bucket.copy( + file_id, + 'copied.txt', + expires='Thu, 01 Dec 2050 16:00:00 GMT', + content_disposition='attachment', + cache_control='max-age=5', + ) assert copied.file_info['b2-expires'] == 'Thu, 01 Dec 2050 16:00:00 GMT', copied.file_info assert copied.file_info['b2-content-disposition'] == 'attachment', copied.file_info From 0da9bc0a89d287b1815aa46df2592d4d8ec3b7a0 Mon Sep 17 00:00:00 2001 From: Felipe Fumero Date: Sat, 21 Nov 2026 15:03:01 -0600 Subject: [PATCH 046/113] test: remove unused defect_raises import from bucket regression suite (#710) PRs #708 and #709 both edited test/unit/bucket/test_regression_bucket.py; the clean auto-merge left `defect_raises` imported but unused, failing ruff (F401) on master. Drop the unused import. --- changelog.d/+regression-bucket-unused-import.infrastructure.md | 1 + test/unit/bucket/test_regression_bucket.py | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) create mode 100644 changelog.d/+regression-bucket-unused-import.infrastructure.md diff --git a/changelog.d/+regression-bucket-unused-import.infrastructure.md b/changelog.d/+regression-bucket-unused-import.infrastructure.md new file mode 100644 index 000000000..6b54424c2 --- /dev/null +++ b/changelog.d/+regression-bucket-unused-import.infrastructure.md @@ -0,0 +1 @@ +Drop an unused test import left in the bucket regression suite after two fixes merged into the same file, restoring the lint gate on master. diff --git a/test/unit/bucket/test_regression_bucket.py b/test/unit/bucket/test_regression_bucket.py index 1149c7855..4df8b149a 100644 --- a/test/unit/bucket/test_regression_bucket.py +++ b/test/unit/bucket/test_regression_bucket.py @@ -45,7 +45,7 @@ ) from apiver_deps_exception import NonExistentBucket -from test.known_defect import DefectStillPresent, defect_raises, expect, known_defect +from test.known_defect import DefectStillPresent, expect, known_defect from .test_bucket import TestCaseWithBucket From be9745b88d2f3d35e73b08e0ec5368b8d8093c18 Mon Sep 17 00:00:00 2001 From: Felipe Fumero Date: Sat, 21 Nov 2026 16:29:40 -0600 Subject: [PATCH 047/113] docs: correct release date and installation guidance (#712) --- .github/SUPPORT.md | 2 +- CHANGELOG.md | 2 +- README.md | 4 ++++ changelog.d/+installation-support-docs.doc.md | 1 + 4 files changed, 7 insertions(+), 2 deletions(-) create mode 100644 changelog.d/+installation-support-docs.doc.md diff --git a/.github/SUPPORT.md b/.github/SUPPORT.md index 063dde13a..8338bdd58 100644 --- a/.github/SUPPORT.md +++ b/.github/SUPPORT.md @@ -1,5 +1,5 @@ Issues with **B2_Command_line_tool** (problems with the tool itself) should be reported at [B2 CLI issue tracker](https://github.com/Backblaze/B2_Command_Line_Tool/issues). -Issuew with **B2 cloud service** (not caused by B2 CLI or sdk) should be reported directly to [Backblaze support](https://help.backblaze.com/hc/en-us/requests/new). +Issues with **B2 cloud service** (not caused by B2 CLI or sdk) should be reported directly to [Backblaze support](https://help.backblaze.com/hc/en-us/requests/new). Issues with the B2 python sdk should be reported in [b2-sdk-python issue tracker](https://github.com/Backblaze/b2-sdk-python/issues). This should be used by authors of tools that interact with the b2 cloud through **b2-sdk-python**, but also if an issue with some other project (that uses **b2-sdk-python**) is clearly caused by a bug in **b2-sdk-python**. diff --git a/CHANGELOG.md b/CHANGELOG.md index 9518f6bd5..c2695caeb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -17,7 +17,7 @@ upcoming release can be found in [changelog.d](changelog.d). - Make the sdkharness legal-hold delete check accept B2's `401 access_denied` response while retaining older simulator refusal shapes. -## [2.13.4](https://github.com/Backblaze/b2-sdk-python/releases/tag/v2.13.4) - 2026-11-12 +## [2.13.4](https://github.com/Backblaze/b2-sdk-python/releases/tag/v2.13.4) - 2026-11-13 ### Fixed diff --git a/README.md b/README.md index c0396ce85..0f5841276 100644 --- a/README.md +++ b/README.md @@ -17,6 +17,10 @@ The sdk can be installed with: pip install b2sdk +To install with all optional dependencies: + + pip install 'b2sdk[full]' + # Version policy b2sdk follows [Semantic Versioning](https://semver.org/) policy, so in essence the version number is MAJOR.MINOR.PATCH (for example 1.2.3) and: diff --git a/changelog.d/+installation-support-docs.doc.md b/changelog.d/+installation-support-docs.doc.md new file mode 100644 index 000000000..850e749d3 --- /dev/null +++ b/changelog.d/+installation-support-docs.doc.md @@ -0,0 +1 @@ +Correct the release date, support guidance, and installation instructions. From dd366eb3138202af22a9267d1745bb860fa4c5af Mon Sep 17 00:00:00 2001 From: Felipe Fumero Date: Sat, 21 Nov 2026 16:29:54 -0600 Subject: [PATCH 048/113] ci: pin actions and gate releases on tests (#713) --- .github/workflows/cd.yml | 29 +++++++++++-- .github/workflows/ci.yml | 41 ++++++++++-------- .../+release-ci-safety.infrastructure.md | 1 + test/static/test_release_workflow_safety.py | 43 +++++++++++++++++++ 4 files changed, 91 insertions(+), 23 deletions(-) create mode 100644 changelog.d/+release-ci-safety.infrastructure.md create mode 100644 test/static/test_release_workflow_safety.py diff --git a/.github/workflows/cd.yml b/.github/workflows/cd.yml index f79a0c0f5..8eea08a68 100644 --- a/.github/workflows/cd.yml +++ b/.github/workflows/cd.yml @@ -9,7 +9,28 @@ env: UV_VERSION: "0.13.4" jobs: + test: + permissions: + contents: read + timeout-minutes: 90 + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 + with: + fetch-depth: 0 + - uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6 + with: + python-version: ${{ env.PYTHON_DEFAULT_VERSION }} + - uses: astral-sh/setup-uv@37802adc94f370d6bfd71619e3f0bf239e1f3b78 # v7 + with: + version: ${{ env.UV_VERSION }} + enable-cache: true + - name: Install dependencies + run: uv sync --only-group nox --locked + - name: Run unit tests + run: uv run nox -vs unit -p ${{ env.PYTHON_DEFAULT_VERSION }} -- -v deploy: + needs: test permissions: contents: write env: @@ -23,14 +44,14 @@ jobs: IS_PRERELEASE=$([[ ${{ github.ref }} =~ [^0-9]$ ]] && echo true || echo false) export IS_PRERELEASE echo "prerelease=$IS_PRERELEASE" >> "$GITHUB_OUTPUT" - - uses: actions/checkout@v4 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 with: fetch-depth: 0 - name: Set up Python ${{ env.PYTHON_DEFAULT_VERSION }} - uses: actions/setup-python@v6 + uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6 with: python-version: ${{ env.PYTHON_DEFAULT_VERSION }} - - uses: astral-sh/setup-uv@v7 + - uses: astral-sh/setup-uv@37802adc94f370d6bfd71619e3f0bf239e1f3b78 # v7 with: version: ${{ env.UV_VERSION }} enable-cache: true @@ -115,7 +136,7 @@ jobs: --draft="$IS_DRAFT" --prerelease="$IS_PRERELEASE" - name: Upload the distribution to PyPI if: ${{ env.B2_PYPI_PASSWORD != '' && steps.prerelease_check.outputs.prerelease == 'false' }} - uses: pypa/gh-action-pypi-publish@release/v1 + uses: pypa/gh-action-pypi-publish@7245906fb61fa33a13554f9d5fb856fe61758086 # release/v1 with: user: __token__ password: ${{ secrets.B2_PYPI_PASSWORD }} diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index bf27eedaf..146ccdb7f 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -7,6 +7,9 @@ on: branches: [master] types: [opened, synchronize, reopened, ready_for_review] +permissions: + contents: read + env: PYTHON_DEFAULT_VERSION: "3.14" UV_VERSION: "0.13.4" @@ -16,7 +19,7 @@ jobs: timeout-minutes: 30 runs-on: ubuntu-latest steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 with: fetch-depth: 0 # actions-governance: replaced by Check spelling; remove after a real run verifies the replacement @@ -27,10 +30,10 @@ jobs: # Preserve the original action's effective CLI arguments, including its positional path. run: pipx run codespell --count --skip ./.git --ignore-words-list datas re-use - name: Set up Python ${{ env.PYTHON_DEFAULT_VERSION }} - uses: actions/setup-python@v6 + uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6 with: python-version: ${{ env.PYTHON_DEFAULT_VERSION }} - - uses: astral-sh/setup-uv@v7 + - uses: astral-sh/setup-uv@37802adc94f370d6bfd71619e3f0bf239e1f3b78 # v7 with: version: ${{ env.UV_VERSION }} enable-cache: true @@ -59,14 +62,14 @@ jobs: needs: lint runs-on: ubuntu-latest steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 with: fetch-depth: 0 - name: Set up Python ${{ env.PYTHON_DEFAULT_VERSION }} - uses: actions/setup-python@v6 + uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6 with: python-version: ${{ env.PYTHON_DEFAULT_VERSION }} - - uses: astral-sh/setup-uv@v7 + - uses: astral-sh/setup-uv@37802adc94f370d6bfd71619e3f0bf239e1f3b78 # v7 with: version: ${{ env.UV_VERSION }} enable-cache: true @@ -84,16 +87,16 @@ jobs: B2_TEST_APPLICATION_KEY_ID: ${{ (vars.B2_LIVE_TESTS_ENABLED == 'true' && (github.event_name != 'pull_request' || !github.event.pull_request.draft)) && secrets.B2_TEST_APPLICATION_KEY_ID || '' }} runs-on: ubuntu-latest steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 if: ${{ env.B2_TEST_APPLICATION_KEY != '' && env.B2_TEST_APPLICATION_KEY_ID != '' }} # TODO: skip this whole job instead with: fetch-depth: 0 - name: Set up Python ${{ env.PYTHON_DEFAULT_VERSION }} if: ${{ env.B2_TEST_APPLICATION_KEY != '' && env.B2_TEST_APPLICATION_KEY_ID != '' }} # TODO: skip this whole job instead - uses: actions/setup-python@v6 + uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6 with: python-version: ${{ env.PYTHON_DEFAULT_VERSION }} - - uses: astral-sh/setup-uv@v7 + - uses: astral-sh/setup-uv@37802adc94f370d6bfd71619e3f0bf239e1f3b78 # v7 if: ${{ env.B2_TEST_APPLICATION_KEY != '' && env.B2_TEST_APPLICATION_KEY_ID != '' }} # TODO: skip this whole job instead with: version: ${{ env.UV_VERSION }} @@ -129,14 +132,14 @@ jobs: extras: "full" os: "ubuntu-latest" steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 with: fetch-depth: 0 - name: Set up Python ${{ matrix.python-version }} - uses: actions/setup-python@v6 + uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6 with: python-version: ${{ matrix.python-version }} - - uses: astral-sh/setup-uv@v7 + - uses: astral-sh/setup-uv@37802adc94f370d6bfd71619e3f0bf239e1f3b78 # v7 with: version: ${{ env.UV_VERSION }} enable-cache: true @@ -169,19 +172,19 @@ jobs: - os: windows-latest python-version: "3.12" steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 with: fetch-depth: 0 path: b2-sdk-python - - uses: actions/checkout@v4 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 with: repository: Backblaze/B2_Command_Line_Tool path: B2_Command_Line_Tool - name: Set up Python ${{ matrix.python-version }} - uses: actions/setup-python@v6 + uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6 with: python-version: ${{ matrix.python-version }} - - uses: astral-sh/setup-uv@v7 + - uses: astral-sh/setup-uv@37802adc94f370d6bfd71619e3f0bf239e1f3b78 # v7 with: version: ${{ env.UV_VERSION }} enable-cache: true @@ -219,14 +222,14 @@ jobs: needs: build runs-on: ubuntu-latest steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 with: fetch-depth: 0 - name: Set up Python ${{ env.PYTHON_DEFAULT_VERSION }} - uses: actions/setup-python@v6 + uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6 with: python-version: ${{ env.PYTHON_DEFAULT_VERSION }} - - uses: astral-sh/setup-uv@v7 + - uses: astral-sh/setup-uv@37802adc94f370d6bfd71619e3f0bf239e1f3b78 # v7 with: version: ${{ env.UV_VERSION }} enable-cache: true diff --git a/changelog.d/+release-ci-safety.infrastructure.md b/changelog.d/+release-ci-safety.infrastructure.md new file mode 100644 index 000000000..50912e5cf --- /dev/null +++ b/changelog.d/+release-ci-safety.infrastructure.md @@ -0,0 +1 @@ +Pin workflow actions and require unit tests to pass before release. diff --git a/test/static/test_release_workflow_safety.py b/test/static/test_release_workflow_safety.py new file mode 100644 index 000000000..471672034 --- /dev/null +++ b/test/static/test_release_workflow_safety.py @@ -0,0 +1,43 @@ +###################################################################### +# +# File: test/static/test_release_workflow_safety.py +# +# Copyright 2026 Backblaze Inc. All Rights Reserved. +# +# License https://www.backblaze.com/using_b2_code.html +# +###################################################################### +"""Check the CI permissions, action pins, and release test gate.""" + +import re +from pathlib import Path + +import yaml + +WORKFLOWS = Path(__file__).parents[2] / '.github' / 'workflows' + + +def load_workflow(name): + return yaml.safe_load((WORKFLOWS / name).read_text()) + + +def test_ci_token_is_read_only(): + assert load_workflow('ci.yml')['permissions'] == {'contents': 'read'} + + +def test_active_actions_are_pinned_to_full_commit_shas(): + for path in WORKFLOWS.glob('*.yml'): + for job in load_workflow(path)['jobs'].values(): + for step in job.get('steps', []): + action = step.get('uses', '') + if action and not action.startswith(('./', 'docker://')): + assert re.fullmatch(r'[^@]+@[0-9a-f]{40}', action), action + + +def test_release_requires_successful_unit_tests(): + jobs = load_workflow('cd.yml')['jobs'] + assert jobs['deploy']['needs'] == 'test' + assert 'if' not in jobs['deploy'] + steps = jobs['test']['steps'] + assert any('nox -vs unit' in step.get('run', '') for step in steps) + assert jobs['test'].get('permissions') == {'contents': 'read'} From be0814dc05cc5a0baa2f5425b34c101e18439b47 Mon Sep 17 00:00:00 2001 From: Felipe Fumero Date: Sat, 21 Nov 2026 17:27:08 -0600 Subject: [PATCH 049/113] test: unmark the C30 and C59 known-defect checks now that both are fixed (#720) * test: unmark the C30 and C59 known-defect checks now that both are fixed PR #712 fixed the SUPPORT.md typo (C30) and documented the b2sdk[full] extra (C59), so their strict-xfail known-defect tests now XPASS and fail the lint session on master. Remove the @known_defect decorators (and the now-unused import) so both run as ordinary passing regression checks. Refs #711 * test: add changelog fragment for the known-defect test cleanup --- .../+flip-resolved-known-defect-tests.infrastructure.md | 1 + test/static/test_regression_repo_checks.py | 4 ---- 2 files changed, 1 insertion(+), 4 deletions(-) create mode 100644 changelog.d/+flip-resolved-known-defect-tests.infrastructure.md diff --git a/changelog.d/+flip-resolved-known-defect-tests.infrastructure.md b/changelog.d/+flip-resolved-known-defect-tests.infrastructure.md new file mode 100644 index 000000000..885ad8ecf --- /dev/null +++ b/changelog.d/+flip-resolved-known-defect-tests.infrastructure.md @@ -0,0 +1 @@ +Unmark the C30 and C59 known-defect regression tests now that both defects are fixed. diff --git a/test/static/test_regression_repo_checks.py b/test/static/test_regression_repo_checks.py index 0199a8adf..b2b5f6148 100644 --- a/test/static/test_regression_repo_checks.py +++ b/test/static/test_regression_repo_checks.py @@ -28,8 +28,6 @@ import pytest -from test.known_defect import known_defect - ROOT = Path(__file__).resolve().parents[2] @@ -40,13 +38,11 @@ def _read(rel: str) -> str: return path.read_text(encoding='utf-8') -@known_defect('C30', 'typo in .github/SUPPORT.md', raises=AssertionError) def test_c30_support_file_has_no_known_typo(): """C30: typo 'Issuew' in .github/SUPPORT.md (codespell did not catch it).""" assert 'Issuew' not in _read('.github/SUPPORT.md'), 'typo is still present' -@known_defect('C59', 'the README does not mention the "full" install extra', raises=AssertionError) def test_c59_readme_mentions_full_extra(): """C59: README must mention the `full` install extra (tqdm/pydantic support).""" assert re.search(r'b2sdk\[full\]', _read('README.md')), 'README does not mention b2sdk[full]' From f6a2725fab90169106067eff69b4f07abf004dcf Mon Sep 17 00:00:00 2001 From: Felipe Fumero Date: Sat, 21 Nov 2026 17:32:05 -0600 Subject: [PATCH 050/113] fix: harden sqlite account information handling (#714) --- .../account_info/sqlite_account_info.py | 37 +++---- .../+sqlite-account-info-safety.fixed.md | 1 + .../account_info/test_regression_sqlite.py | 9 +- .../account_info/test_sqlite_low_audit.py | 98 +++++++++++++++++++ 4 files changed, 121 insertions(+), 24 deletions(-) create mode 100644 changelog.d/+sqlite-account-info-safety.fixed.md create mode 100644 test/unit/account_info/test_sqlite_low_audit.py diff --git a/b2sdk/_internal/account_info/sqlite_account_info.py b/b2sdk/_internal/account_info/sqlite_account_info.py index c618dcd9f..16c2a57ef 100644 --- a/b2sdk/_internal/account_info/sqlite_account_info.py +++ b/b2sdk/_internal/account_info/sqlite_account_info.py @@ -75,6 +75,8 @@ def __init__(self, file_name=None, last_upgrade_to_run=None, profile: str | None :param int last_upgrade_to_run: For testing only, override the auto-update on the db. """ self.thread_local = threading.local() + self._connections = set() + self._connections_lock = threading.Lock() self.filename = self.get_user_account_info_path(file_name=file_name, profile=profile) logger.debug('%s file path to use: %s', self.__class__.__name__, self.filename) @@ -109,7 +111,7 @@ def _get_xdg_config_path(cls) -> str | None: @classmethod def get_user_account_info_path(cls, file_name: str | None = None, profile: str | None = None): - if profile and not B2_ACCOUNT_INFO_PROFILE_NAME_REGEXP.match(profile): + if profile and not B2_ACCOUNT_INFO_PROFILE_NAME_REGEXP.fullmatch(profile): raise ValueError(f'Invalid profile name: {profile}') profile_file = B2_ACCOUNT_INFO_PROFILE_FILE.format(profile=profile) if profile else None @@ -130,7 +132,7 @@ def get_user_account_info_path(cls, file_name: str | None = None, profile: str | elif profile and os.path.exists(profile_file): user_account_info_path = profile_file elif xdg_config_path: - os.makedirs(os.path.join(xdg_config_path, 'b2'), mode=0o755, exist_ok=True) + os.makedirs(os.path.join(xdg_config_path, 'b2'), mode=0o700, exist_ok=True) file_name = f'db-{profile}.sqlite' if profile else 'account_info' user_account_info_path = os.path.join(xdg_config_path, 'b2', file_name) @@ -203,17 +205,17 @@ def _validate_database(self, last_upgrade_to_run=None): raise CorruptAccountInfo(self.filename) def _get_connection(self): - """ - Connections to sqlite cannot be shared across threads. - """ - try: - return self.thread_local.connection - except AttributeError: - self.thread_local.connection = self._connect() - return self.thread_local.connection + """Return a connection owned by the calling thread, reopening it after close().""" + with self._connections_lock: + connection = getattr(self.thread_local, 'connection', None) + if connection not in self._connections: + connection = self._connect() + self._connections.add(connection) + self.thread_local.connection = connection + return connection def _connect(self): - return sqlite3.connect(self.filename, isolation_level='EXCLUSIVE') + return sqlite3.connect(self.filename, isolation_level='EXCLUSIVE', check_same_thread=False) @contextmanager def _temp_connection(self): @@ -226,12 +228,13 @@ def _temp_connection(self): conn.close() def close(self): - connection = getattr(self.thread_local, 'connection', None) - if connection is None: - return - - connection.close() - del self.thread_local.connection + """Close cached connections after callers have finished using them.""" + with self._connections_lock: + for connection in self._connections: + connection.close() + self._connections.clear() + if hasattr(self.thread_local, 'connection'): + del self.thread_local.connection def _create_database(self, last_upgrade_to_run): """ diff --git a/changelog.d/+sqlite-account-info-safety.fixed.md b/changelog.d/+sqlite-account-info-safety.fixed.md new file mode 100644 index 000000000..b156489ab --- /dev/null +++ b/changelog.d/+sqlite-account-info-safety.fixed.md @@ -0,0 +1 @@ +Protect new account configuration directories, validate profile names, and close cached SQLite connections across threads. diff --git a/test/unit/account_info/test_regression_sqlite.py b/test/unit/account_info/test_regression_sqlite.py index eb48454a0..8185c775a 100644 --- a/test/unit/account_info/test_regression_sqlite.py +++ b/test/unit/account_info/test_regression_sqlite.py @@ -29,7 +29,7 @@ SqliteAccountInfo, ) -from test.known_defect import DefectStillPresent, expect, known_defect +from test.known_defect import known_defect pytestmark = [pytest.mark.apiver(from_ver=2)] @@ -59,11 +59,6 @@ def test_c47_existing_legacy_profile_database_is_used_with_xdg(self, home, monke class TestThreadConnections: - @known_defect( - 'C37', - "close() closes only the calling thread's database connection", - raises=DefectStillPresent, - ) def test_c37_close_closes_connections_of_other_threads(self, tmp_path): """C37: close() must close the database connections opened by other threads, too.""" info = SqliteAccountInfo(file_name=str(tmp_path / 'acct.sqlite')) @@ -86,4 +81,4 @@ def worker(): closed_by_main.set() thread.join(timeout=10) assert 'closed' in result, 'the worker thread did not finish its check' - expect(result['closed'], 'connection of another thread is still open after close()') + assert result['closed'], 'connection of another thread is still open after close()' diff --git a/test/unit/account_info/test_sqlite_low_audit.py b/test/unit/account_info/test_sqlite_low_audit.py new file mode 100644 index 000000000..58a745c41 --- /dev/null +++ b/test/unit/account_info/test_sqlite_low_audit.py @@ -0,0 +1,98 @@ +###################################################################### +# +# File: test/unit/account_info/test_sqlite_low_audit.py +# +# Copyright 2026 Backblaze Inc. All Rights Reserved. +# +# License https://www.backblaze.com/using_b2_code.html +# +###################################################################### +import os +import stat +import threading + +import pytest +from apiver_deps import SqliteAccountInfo + + +@pytest.mark.skipif(os.name == 'nt', reason='POSIX directory permissions') +def test_c58_new_config_directory_is_private(tmp_path, monkeypatch): + monkeypatch.setenv('HOME', str(tmp_path)) + monkeypatch.setenv('XDG_CONFIG_HOME', str(tmp_path / 'config')) + monkeypatch.delenv('B2_ACCOUNT_INFO', raising=False) + SqliteAccountInfo.get_user_account_info_path(profile='test') + mode = stat.S_IMODE((tmp_path / 'config' / 'b2').stat().st_mode) + assert mode == 0o700 + + +def test_c23_profile_rejects_trailing_path(tmp_path, monkeypatch): + monkeypatch.setenv('HOME', str(tmp_path)) + monkeypatch.setenv('XDG_CONFIG_HOME', str(tmp_path / 'config')) + monkeypatch.delenv('B2_ACCOUNT_INFO', raising=False) + with pytest.raises(ValueError, match='Invalid profile name'): + SqliteAccountInfo.get_user_account_info_path(profile='ok/../../x') + assert not (tmp_path / 'config').exists() + + +def test_c37_worker_reopens_after_another_thread_closes(tmp_path): + info = SqliteAccountInfo(file_name=str(tmp_path / 'account.sqlite')) + opened, closed = threading.Event(), threading.Event() + result = [] + + def worker(): + conn = info._get_connection() + opened.set() + if closed.wait(10): + try: + new_conn = info._get_connection() + result.append((new_conn is not conn, new_conn.execute('select 1').fetchone())) + except Exception as exc: + result.append(exc) + + thread = threading.Thread(target=worker) + thread.start() + try: + assert opened.wait(10) + info.close() + finally: + closed.set() + thread.join(10) + assert not thread.is_alive() + assert result == [(True, (1,))] + info.close() + + +def test_c37_closes_all_worker_connections_and_is_idempotent(tmp_path): + info = SqliteAccountInfo(file_name=str(tmp_path / 'account.sqlite')) + connections = [] + ready = threading.Barrier(4) + release = threading.Event() + outcomes = [] + + def worker(): + conn = info._get_connection() + connections.append(conn) + ready.wait(timeout=10) + if release.wait(10): + try: + conn.execute('select 1') + except Exception as exc: + outcomes.append(type(exc).__name__) + else: + outcomes.append('open') + + threads = [threading.Thread(target=worker) for _ in range(3)] + for thread in threads: + thread.start() + try: + ready.wait(timeout=10) + info.close() + info.close() + finally: + release.set() + for thread in threads: + thread.join(10) + assert all(not thread.is_alive() for thread in threads) + assert len({id(conn) for conn in connections}) == 3 + assert outcomes == ['ProgrammingError'] * 3 + info.close() From 6578b80bd9e7302dc1f71499b720f755e3b58b88 Mon Sep 17 00:00:00 2001 From: Felipe Fumero Date: Sat, 21 Nov 2026 17:32:58 -0600 Subject: [PATCH 051/113] fix: harden sync download finalization (#715) --- b2sdk/_internal/sync/action.py | 39 ++++++++++-------- .../transfer/inbound/downloaded_file.py | 3 +- changelog.d/+sync-finalization.fixed.md | 1 + .../unit/sync/test_regression_sync_actions.py | 40 +++++++------------ 4 files changed, 40 insertions(+), 43 deletions(-) create mode 100644 changelog.d/+sync-finalization.fixed.md diff --git a/b2sdk/_internal/sync/action.py b/b2sdk/_internal/sync/action.py index 7a7a01e00..42e5d660d 100644 --- a/b2sdk/_internal/sync/action.py +++ b/b2sdk/_internal/sync/action.py @@ -318,20 +318,27 @@ def do_action(self, bucket: Bucket, reporter: ProgressReport) -> None: bucket=bucket, file_version=self.source_path.selected_version, ) - with contextlib.ExitStack() as exit_stack: - if progress_listener: - exit_stack.enter_context(progress_listener) - downloaded_file = bucket.download_file_by_id( - self.source_path.selected_version.id_, - progress_listener=progress_listener, - encryption=encryption, - ) - downloaded_file.save_to(download_path) - - # Move the file into place - with suppress(OSError): - os.unlink(self.local_full_path) - os.rename(download_path, self.local_full_path) + try: + with contextlib.ExitStack() as exit_stack: + if progress_listener: + exit_stack.enter_context(progress_listener) + downloaded_file = bucket.download_file_by_id( + self.source_path.selected_version.id_, + progress_listener=progress_listener, + encryption=encryption, + ) + downloaded_file.save_to(download_path) + + # Move the file into place + os.replace(download_path, self.local_full_path) + except BaseException: + try: + os.unlink(download_path) + except FileNotFoundError: + pass + except OSError: + logger.warning('Could not remove temporary sync download', exc_info=True) + raise def do_report(self, bucket: Bucket, reporter: ProgressReport) -> None: """ @@ -340,7 +347,7 @@ def do_report(self, bucket: Bucket, reporter: ProgressReport) -> None: :param bucket: a Bucket object :param reporter: a place to report errors """ - reporter.print_completion('dnload ' + self.source_path.relative_path) + reporter.print_completion('dnload ' + escape_control_chars(self.source_path.relative_path)) def __str__(self) -> str: return 'b2_download(%s, %s, %s, %d)' % ( @@ -430,7 +437,7 @@ def do_report(self, bucket: Bucket, reporter: ProgressReport) -> None: :param bucket: a Bucket object :param reporter: a place to report errors """ - reporter.print_completion('copy ' + self.source_path.relative_path) + reporter.print_completion('copy ' + escape_control_chars(self.source_path.relative_path)) def __str__(self) -> str: return 'b2_copy(%s, %s, %s, %d)' % ( diff --git a/b2sdk/_internal/transfer/inbound/downloaded_file.py b/b2sdk/_internal/transfer/inbound/downloaded_file.py index b75923dc7..4f4ed721c 100644 --- a/b2sdk/_internal/transfer/inbound/downloaded_file.py +++ b/b2sdk/_internal/transfer/inbound/downloaded_file.py @@ -136,7 +136,8 @@ def __enter__(self): def __exit__(self, exc_type, exc_val, exc_tb): self.file.close() - set_file_mtime(self.path_, self.mod_time_to_set) + if exc_type is None: + set_file_mtime(self.path_, self.mod_time_to_set) def __str__(self): return str(self.path) diff --git a/changelog.d/+sync-finalization.fixed.md b/changelog.d/+sync-finalization.fixed.md new file mode 100644 index 000000000..da24777f3 --- /dev/null +++ b/changelog.d/+sync-finalization.fixed.md @@ -0,0 +1 @@ +Fixed sync download finalization and escaped control characters in sync completion messages. diff --git a/test/unit/sync/test_regression_sync_actions.py b/test/unit/sync/test_regression_sync_actions.py index e506ff0c2..435cd3e60 100644 --- a/test/unit/sync/test_regression_sync_actions.py +++ b/test/unit/sync/test_regression_sync_actions.py @@ -34,7 +34,7 @@ from b2sdk._internal.scan.path import B2Path from b2sdk._internal.sync.action import B2CopyAction, B2DownloadAction -from test.known_defect import DefectStillPresent, expect, known_defect +from test.known_defect import expect pytestmark = [pytest.mark.apiver(from_ver=2)] @@ -69,11 +69,6 @@ def _corrupt_stored_sha1(api, bucket, file_version): class TestDownloadedFileModTime: - @known_defect( - 'C3', - 'a download that fails its checksum check still gets the remote modification time', - raises=AssertionError, - ) def test_c3_failed_checksum_does_not_stamp_remote_mtime(self, api_and_bucket, tmp_path): """C3: a download that fails validation must not leave a file that looks current.""" api, bucket = api_and_bucket @@ -94,9 +89,6 @@ def test_c3_failed_checksum_does_not_stamp_remote_mtime(self, api_and_bucket, tm class TestSyncDownloadAction: - @known_defect( - 'C3', 'a failed sync download leaves the temporary file behind', raises=DefectStillPresent - ) def test_c3_failed_download_leaves_no_temp_file(self, api_and_bucket, tmp_path): """C3: after a failed sync download the .b2.sync.tmp file must not be left behind.""" api, bucket = api_and_bucket @@ -108,11 +100,16 @@ def test_c3_failed_download_leaves_no_temp_file(self, api_and_bucket, tmp_path): assert not (tmp_path / 'f.txt').exists(), 'final file was created' expect(not (tmp_path / 'f.txt.b2.sync.tmp').exists(), 'temporary file left behind') - @known_defect( - 'C17', - 'sync download deletes the old local file before renaming the new one into place', - raises=DefectStillPresent, - ) + def test_c3_cleanup_failure_preserves_download_error(self, api_and_bucket, tmp_path, caplog): + api, bucket = api_and_bucket + fv = bucket.upload_bytes(b'hello world', 'f.txt') + _corrupt_stored_sha1(api, bucket, fv) + action = _download_action(bucket, fv, tmp_path / 'f.txt') + with mock.patch('os.unlink', side_effect=PermissionError('cleanup failed')): + with pytest.raises((ChecksumMismatch, TruncatedOutput)): + action.do_action(bucket, None) + assert 'Could not remove temporary sync download' in caplog.text + def test_c17_failed_replacement_keeps_previous_local_copy(self, api_and_bucket, tmp_path): """C17: if moving the new file into place fails, the old local file must still exist. @@ -136,6 +133,7 @@ def fail(*args, **kwargs): assert injected, 'the download never tried to move the new file into place' expect(local.exists(), 'the previous local copy was removed') expect(local.read_bytes() == b'old content', 'the previous local copy was changed') + assert not (tmp_path / 'f.txt.b2.sync.tmp').exists() def test_c17_guard_successful_download_replaces_file(self, api_and_bucket, tmp_path): """Guard for C17: a normal sync download replaces the local file and leaves no temp file.""" @@ -154,24 +152,14 @@ class TestSyncMessages: def _path(self): return B2Path(self.NAME, mock.Mock(), []) - @known_defect( - 'C24', - 'the sync download message prints remote names without escaping control characters', - raises=AssertionError, - ) def test_c24_download_message_escapes_control_characters(self): """C24: remote names with control chars must be escaped in output.""" action = B2DownloadAction(self._path(), self.NAME, 'out/x', mock.Mock()) reporter = mock.Mock() action.do_report(mock.Mock(), reporter) printed = reporter.print_completion.call_args[0][0] - assert '\x1b' not in printed, repr(printed) + assert printed == r"dnload 'dir/evil\x1b[31mname'" - @known_defect( - 'C24', - 'the sync copy message prints remote names without escaping control characters', - raises=AssertionError, - ) def test_c24_copy_message_escapes_control_characters(self): """C24: same for copy actions.""" action = B2CopyAction( @@ -180,4 +168,4 @@ def test_c24_copy_message_escapes_control_characters(self): reporter = mock.Mock() action.do_report(mock.Mock(), reporter) printed = reporter.print_completion.call_args[0][0] - assert '\x1b' not in printed, repr(printed) + assert printed == r"copy 'dir/evil\x1b[31mname'" From 973ad3566b6f9b6e45400984db06bad58f2a22c3 Mon Sep 17 00:00:00 2001 From: Felipe Fumero Date: Sat, 21 Nov 2026 17:33:12 -0600 Subject: [PATCH 052/113] fix: harden upload source handling (#716) --- .../transfer/outbound/upload_source.py | 13 ++--- changelog.d/+upload-source-safety.fixed.md | 1 + test/unit/stream/test_regression_streams.py | 15 +---- test/unit/stream/test_upload_source_safety.py | 57 +++++++++++++++++++ 4 files changed, 66 insertions(+), 20 deletions(-) create mode 100644 changelog.d/+upload-source-safety.fixed.md create mode 100644 test/unit/stream/test_upload_source_safety.py diff --git a/b2sdk/_internal/transfer/outbound/upload_source.py b/b2sdk/_internal/transfer/outbound/upload_source.py index 647336a21..502653300 100644 --- a/b2sdk/_internal/transfer/outbound/upload_source.py +++ b/b2sdk/_internal/transfer/outbound/upload_source.py @@ -89,13 +89,7 @@ def __init__( self.content_sha1 = content_sha1 def __repr__(self) -> str: - return '<{classname} data={data} id={id}>'.format( - classname=self.__class__.__name__, - data=str(self.data_bytes[:20]) + '...' - if len(self.data_bytes) > 20 - else self.data_bytes, - id=id(self), - ) + return f'<{self.__class__.__name__} content_length={len(self.data_bytes)} id={id(self)}>' def get_content_length(self) -> int: return len(self.data_bytes) @@ -178,6 +172,8 @@ def __init__( """ super().__init__(local_path, content_sha1) self.file_size = self.content_length + if offset < 0 or offset > self.file_size: + raise ValueError('Range offset outside file size') self.offset = offset if length is None: self.content_length = self.file_size - self.offset @@ -316,7 +312,8 @@ def open(self): return self.stream_opener() def _set_content_length_and_sha1(self) -> None: - sha1, content_length = hex_sha1_of_unlimited_stream(self.open()) + with self.open() as stream: + sha1, content_length = hex_sha1_of_unlimited_stream(stream) self._content_length = content_length self._content_sha1 = sha1 diff --git a/changelog.d/+upload-source-safety.fixed.md b/changelog.d/+upload-source-safety.fixed.md new file mode 100644 index 000000000..7bfbbe7b1 --- /dev/null +++ b/changelog.d/+upload-source-safety.fixed.md @@ -0,0 +1 @@ +Protect upload data in representations, close checksum streams, and validate local file range offsets. diff --git a/test/unit/stream/test_regression_streams.py b/test/unit/stream/test_regression_streams.py index bdffe4a01..626faa8e5 100644 --- a/test/unit/stream/test_regression_streams.py +++ b/test/unit/stream/test_regression_streams.py @@ -123,11 +123,6 @@ def test_c15_stream_range_without_length_computes_length(self): length = source.get_content_length() assert length == 10, 'wrong computed length' - @known_defect( - 'C14', - 'UploadSourceStream does not close the stream it opened to compute the checksum', - raises=DefectStillPresent, - ) def test_c14_stream_is_closed_after_checksum_computation(self): """C14: computing the checksum must close the stream it opened.""" opened = [] @@ -145,17 +140,13 @@ def opener(): class TestUploadSourceLocalFileRange: @pytest.mark.parametrize('offset', [-3, 15]) - @known_defect( - 'C52', - 'UploadSourceLocalFileRange accepts a negative offset or an offset past the end of the file', - raises=pytest.fail.Exception, - ) - def test_c52_invalid_offset_is_rejected(self, tmp_path, offset): + @pytest.mark.parametrize('length', [None, 0, 1]) + def test_c52_invalid_offset_is_rejected(self, tmp_path, offset, length): """C52: negative offset or offset past end (file is 10 bytes) must be refused.""" path = tmp_path / 'f.bin' path.write_bytes(b'0123456789') with pytest.raises(ValueError): - UploadSourceLocalFileRange(str(path), offset=offset) + UploadSourceLocalFileRange(str(path), offset=offset, length=length) class TestUnboundWriteIntentMemory: diff --git a/test/unit/stream/test_upload_source_safety.py b/test/unit/stream/test_upload_source_safety.py new file mode 100644 index 000000000..fb6f25459 --- /dev/null +++ b/test/unit/stream/test_upload_source_safety.py @@ -0,0 +1,57 @@ +###################################################################### +# +# File: test/unit/stream/test_upload_source_safety.py +# +# Copyright 2026 Backblaze Inc. All Rights Reserved. +# +# License https://www.backblaze.com/using_b2_code.html +# +###################################################################### +import io +import logging + +import pytest + +from b2sdk._internal.transfer.outbound.upload_source import ( + UploadSourceBytes, + UploadSourceLocalFileRange, + UploadSourceStream, +) + + +@pytest.mark.parametrize( + 'payload', [b'sample-data', b'sample-data-' * 5, bytearray(b'sample-data')] +) +def test_bytes_source_repr_and_logs_do_not_expose_payload(payload, caplog): + source = UploadSourceBytes(payload) + logger = logging.getLogger('test.upload-source') + with caplog.at_level(logging.DEBUG, logger=logger.name): + logger.debug('upload source: %r', source) + assert 'sample-data' not in repr(source) + assert caplog.records + assert all('sample-data' not in record.getMessage() for record in caplog.records) + assert source.get_content_length() == len(payload) + + +def test_stream_is_closed_if_checksum_read_fails(): + class FailingStream(io.BytesIO): + def read(self, size=-1): + raise OSError('read failed') + + stream = FailingStream(b'content') + source = UploadSourceStream(lambda: stream) + with pytest.raises(OSError, match='read failed'): + source.get_content_sha1() + assert stream.closed + + +@pytest.mark.parametrize( + 'offset,length,expected', [(0, None, b'abc'), (3, None, b''), (3, 0, b''), (1, 2, b'bc')] +) +def test_file_range_accepts_valid_boundaries(tmp_path, offset, length, expected): + path = tmp_path / 'data.bin' + path.write_bytes(b'abc') + source = UploadSourceLocalFileRange(path, offset=offset, length=length) + assert source.get_content_length() == len(expected) + with source.open() as stream: + assert stream.read() == expected From b5919e256e0644793fe2d184000a8603413916bd Mon Sep 17 00:00:00 2001 From: Felipe Fumero Date: Sat, 21 Nov 2026 17:33:26 -0600 Subject: [PATCH 053/113] fix: harden local path and filename validation (#717) --- b2sdk/_internal/scan/folder.py | 12 ++++--- b2sdk/_internal/utils/__init__.py | 2 ++ b2sdk/_internal/utils/filesystem.py | 8 +++++ changelog.d/+path-validation.fixed.md | 1 + test/unit/scan/test_folder.py | 34 +++++++++++++++++++ test/unit/scan/test_folder_traversal.py | 36 ++------------------- test/unit/scan/test_symlink_device_inode.py | 4 +-- test/unit/utils/test_filename_controls.py | 25 ++++++++++++++ test/unit/utils/test_filesystem.py | 30 +++++++++++++++++ 9 files changed, 113 insertions(+), 39 deletions(-) create mode 100644 changelog.d/+path-validation.fixed.md create mode 100644 test/unit/utils/test_filename_controls.py diff --git a/b2sdk/_internal/scan/folder.py b/b2sdk/_internal/scan/folder.py index 3b01db592..c8260ea86 100644 --- a/b2sdk/_internal/scan/folder.py +++ b/b2sdk/_internal/scan/folder.py @@ -165,11 +165,15 @@ def make_full_path(self, file_name): # Generate the full path to the file full_path = os.path.normpath(os.path.join(self.root, file_name)) - # Get the common path between the new full_path and self.root - common_path = os.path.commonpath([full_path, self.root]) + # Resolve symlinks in both paths before checking containment. + resolved_root = os.path.realpath(self.root) + resolved_path = os.path.realpath(full_path) + try: + common_path = os.path.commonpath([resolved_path, resolved_root]) + except ValueError: # Paths on different Windows drives. + raise UnsupportedFilename('illegal file name', full_path) from None - # Ensure the new full_path is inside the self.root directory - if common_path != self.root: + if os.path.normcase(common_path) != os.path.normcase(resolved_root): raise UnsupportedFilename('illegal file name', full_path) return full_path diff --git a/b2sdk/_internal/utils/__init__.py b/b2sdk/_internal/utils/__init__.py index d6819864a..d3fdc8b4e 100644 --- a/b2sdk/_internal/utils/__init__.py +++ b/b2sdk/_internal/utils/__init__.py @@ -253,6 +253,8 @@ def validate_b2_file_name(name): raise ValueError("file names must not contain '\\'") if '//' in name: raise ValueError("file names must not contain '//'") + if any(ord(char) < 32 for char in name): + raise ValueError('file names must not contain ASCII control characters') if chr(127) in name: raise ValueError('file names must not contain DEL') if any(250 < len(segment) for segment in name_utf8.split(b'/')): diff --git a/b2sdk/_internal/utils/filesystem.py b/b2sdk/_internal/utils/filesystem.py index f9a65e261..997639bf5 100644 --- a/b2sdk/_internal/utils/filesystem.py +++ b/b2sdk/_internal/utils/filesystem.py @@ -16,6 +16,7 @@ DRIVE_MATCHER = re.compile(r'^([A-Za-z]):([/\\])') ABSOLUTE_PATH_MATCHER = re.compile(r'^(/)|^(\\)') +WINDOWS_DEVICE_NAMES = re.compile(r'^(?:CON|PRN|AUX|NUL|COM[1-9¹²³]|LPT[1-9¹²³])$', re.I) RELATIVE_PATH_MATCHER = re.compile( # "abc" and "xyz" represent anything, including "nothing" r'^(\.\.[/\\])|' # ../abc or ..\abc @@ -63,3 +64,10 @@ def validate_b2_file_name_as_path(file_name: str) -> None: if _IS_WINDOWS and DRIVE_MATCHER.search(file_name): raise ValueError('File names containing Windows drive letters are not supported') + + if _IS_WINDOWS: + if ':' in file_name: + raise ValueError('File names containing Windows stream separators are not supported') + for part in re.split(r'[/\\]', file_name): + if WINDOWS_DEVICE_NAMES.fullmatch(part.split('.')[0].rstrip(' ')): + raise ValueError('File names containing Windows device names are not supported') diff --git a/changelog.d/+path-validation.fixed.md b/changelog.d/+path-validation.fixed.md new file mode 100644 index 000000000..efc4d871f --- /dev/null +++ b/changelog.d/+path-validation.fixed.md @@ -0,0 +1 @@ +Reject local paths that resolve outside the sync root, Windows device names and streams, and ASCII control characters in file names. diff --git a/test/unit/scan/test_folder.py b/test/unit/scan/test_folder.py index ecfeb9b78..d887eab86 100644 --- a/test/unit/scan/test_folder.py +++ b/test/unit/scan/test_folder.py @@ -44,3 +44,37 @@ def test_make_full_path_invalid_prefix( with pytest.raises(UnsupportedFilename): folder.make_full_path(str(file_path)) + + +@pytest.mark.skipif( + platform.system() == 'Windows' and platform.python_implementation() == 'PyPy', + reason='Symlinks not supported on PyPy/Windows', +) +def test_make_full_path_rejects_symlink_outside_root(tmp_path): + root = tmp_path / 'root' + root.mkdir() + outside = tmp_path / 'outside' + outside.mkdir() + (root / 'link').symlink_to(outside, target_is_directory=True) + + with pytest.raises(UnsupportedFilename): + LocalFolder(root).make_full_path('link/new-file.txt') + + assert not (outside / 'new-file.txt').exists() + + +@pytest.mark.skipif( + platform.system() == 'Windows' and platform.python_implementation() == 'PyPy', + reason='Symlinks not supported on PyPy/Windows', +) +def test_make_full_path_accepts_internal_link_and_symlinked_root(tmp_path): + root = tmp_path / 'root' + root.mkdir() + (root / 'inside').mkdir() + (root / 'link').symlink_to(root / 'inside', target_is_directory=True) + root_link = tmp_path / 'root-link' + root_link.symlink_to(root, target_is_directory=True) + + assert LocalFolder(root_link).make_full_path('link/new-file.txt') == str( + root_link / 'link' / 'new-file.txt' + ) diff --git a/test/unit/scan/test_folder_traversal.py b/test/unit/scan/test_folder_traversal.py index 5c601b71f..26c3efae0 100644 --- a/test/unit/scan/test_folder_traversal.py +++ b/test/unit/scan/test_folder_traversal.py @@ -20,6 +20,7 @@ import pytest +from b2sdk._internal.scan.exception import UnsupportedFilename from b2sdk._internal.scan.folder import LocalFolder from b2sdk._internal.scan.policies import ScanPoliciesManager from b2sdk._internal.scan.report import ProgressReport @@ -287,39 +288,8 @@ def test_folder_with_symlink_to_parent(self, tmp_path): folder = LocalFolder(str(tmp_path / 'parent' / 'child')) - local_paths = folder.all_files(reporter=MagicMock()) - absolute_paths = [path.absolute_path for path in list(local_paths)] - - assert absolute_paths == [ - fix_windows_path_limit(str(tmp_path / 'parent' / 'child' / 'file4.txt')), - fix_windows_path_limit(str(tmp_path / 'parent' / 'child' / 'grandchild' / 'file5.txt')), - fix_windows_path_limit( - str( - tmp_path - / 'parent' - / 'child' - / 'grandchild' - / 'symlink_dir' - / 'child' - / 'file4.txt' - ) - ), - fix_windows_path_limit( - str( - tmp_path - / 'parent' - / 'child' - / 'grandchild' - / 'symlink_dir' - / 'child' - / 'grandchild' - / 'file5.txt' - ) - ), - fix_windows_path_limit( - str(tmp_path / 'parent' / 'child' / 'grandchild' / 'symlink_dir' / 'file3.txt') - ), - ] + with pytest.raises(UnsupportedFilename, match='illegal file name'): + list(folder.all_files(reporter=MagicMock())) @pytest.mark.skipif( platform.system() == 'Windows' and platform.python_implementation() == 'PyPy', diff --git a/test/unit/scan/test_symlink_device_inode.py b/test/unit/scan/test_symlink_device_inode.py index 4638dfd1a..5fc309507 100644 --- a/test/unit/scan/test_symlink_device_inode.py +++ b/test/unit/scan/test_symlink_device_inode.py @@ -15,7 +15,7 @@ def test_symlink_targets_with_same_inode_on_different_devices_are_scanned(tmp_path, monkeypatch): first = tmp_path / 'first' - second = tmp_path / 'second' + second = first / 'second' first.mkdir() second.mkdir() (second / 'file.txt').write_text('contents') @@ -37,4 +37,4 @@ def stat_with_device_collision(path, *args, **kwargs): monkeypatch.setattr(Path, 'stat', stat_with_device_collision) files = list(LocalFolder(root).all_files(None)) - assert [path.relative_path for path in files] == ['next/file.txt'] + assert [path.relative_path for path in files] == ['next/file.txt', 'second/file.txt'] diff --git a/test/unit/utils/test_filename_controls.py b/test/unit/utils/test_filename_controls.py new file mode 100644 index 000000000..503a24a91 --- /dev/null +++ b/test/unit/utils/test_filename_controls.py @@ -0,0 +1,25 @@ +###################################################################### +# +# File: test/unit/utils/test_filename_controls.py +# +# Copyright 2026 Backblaze Inc. All Rights Reserved. +# +# License https://www.backblaze.com/using_b2_code.html +# +###################################################################### +import pytest + +from b2sdk._internal.utils import validate_b2_file_name + + +@pytest.mark.parametrize('codepoint', range(32)) +def test_rejects_ascii_control_characters(codepoint): + with pytest.raises(ValueError): + validate_b2_file_name(f'folder/name{chr(codepoint)}.txt') + + +def test_del_is_rejected_and_printable_boundaries_are_allowed(): + with pytest.raises(ValueError): + validate_b2_file_name('file\x7f.txt') + validate_b2_file_name('folder/space and tilde~.txt') + validate_b2_file_name('folder/café.txt') diff --git a/test/unit/utils/test_filesystem.py b/test/unit/utils/test_filesystem.py index 0b97cf3a1..831d66941 100644 --- a/test/unit/utils/test_filesystem.py +++ b/test/unit/utils/test_filesystem.py @@ -96,3 +96,33 @@ def test_drive_letter_disallowed_on_windows(self): match=r'drive letters', ): validate_b2_file_name_as_path(r'C:\file.txt') + + +@pytest.mark.parametrize( + 'file_name', + ['CON', 'folder/nul.txt', r'folder\PRN.log', 'aux ', 'dir/COM1.txt', 'lpt³', 'file:stream'], +) +def test_windows_device_names_and_streams_are_rejected(monkeypatch, file_name): + from b2sdk._internal.utils import filesystem + + monkeypatch.setattr(filesystem, '_IS_WINDOWS', True) + with pytest.raises(ValueError): + filesystem.validate_b2_file_name_as_path(file_name) + + +@pytest.mark.parametrize( + 'file_name', ['console.txt', 'com0', 'com10', 'lpt40.logfile', 'folder/file.txt'] +) +def test_windows_regular_names_are_allowed(monkeypatch, file_name): + from b2sdk._internal.utils import filesystem + + monkeypatch.setattr(filesystem, '_IS_WINDOWS', True) + filesystem.validate_b2_file_name_as_path(file_name) + + +@pytest.mark.parametrize('file_name', ['CON', 'folder/nul.txt', 'file:stream']) +def test_unix_allows_windows_device_names_and_stream_characters(monkeypatch, file_name): + from b2sdk._internal.utils import filesystem + + monkeypatch.setattr(filesystem, '_IS_WINDOWS', False) + filesystem.validate_b2_file_name_as_path(file_name) From fdb8cebf11d871fc93ac93516adcbfb5cbb03ac3 Mon Sep 17 00:00:00 2001 From: Felipe Fumero Date: Sat, 21 Nov 2026 17:33:43 -0600 Subject: [PATCH 054/113] fix: harden multipart and unbound transfers (#718) --- b2sdk/_internal/transfer/emerge/executor.py | 69 ++++++++++++++----- .../transfer/emerge/unbound_write_intent.py | 47 +++++++++++-- .../transfer/outbound/upload_manager.py | 24 ++++--- changelog.d/+transfer-audit.fixed.md | 1 + test/unit/bucket/test_regression_bucket.py | 9 ++- .../internal/test_emerge_cancel_siblings.py | 48 +++++++++++++ .../internal/test_unbound_write_intent.py | 15 ++++ .../test_upload_checksum_optimized.py | 60 ++++++++++++++++ test/unit/stream/test_regression_streams.py | 5 -- 9 files changed, 232 insertions(+), 46 deletions(-) create mode 100644 changelog.d/+transfer-audit.fixed.md create mode 100644 test/unit/internal/test_emerge_cancel_siblings.py create mode 100644 test/unit/internal/test_upload_checksum_optimized.py diff --git a/b2sdk/_internal/transfer/emerge/executor.py b/b2sdk/_internal/transfer/emerge/executor.py index 779cd5bd3..35369bed3 100644 --- a/b2sdk/_internal/transfer/emerge/executor.py +++ b/b2sdk/_internal/transfer/emerge/executor.py @@ -212,25 +212,56 @@ def execute_plan(self, emerge_plan: StreamingEmergePlan): large_file_upload_state = LargeFileUploadState(self.progress_listener) part_futures = [] - for part_number, emerge_part in emerge_plan.enumerate_emerge_parts(): - execution_step_factory = LargeFileEmergeExecutionStepFactory( - self, - emerge_part, - part_number, - file_id, - large_file_upload_state, - finished_parts=finished_parts, - # it already knows encryption from BaseMergeExecution being passed as self - ) - execution_step = execution_step_factory.get_execution_step() - future = self._execute_step(execution_step) - part_futures.append(future) - - # Collect the sha1 checksums of the parts as the uploads finish. - # If any of them raised an exception, that same exception will - # be raised here by result() - part_sha1_array = [f.result()['contentSha1'] for f in part_futures] - + failure_lock = threading.RLock() + first_failure = [] + + def cancel_on_failure(future): + if future.cancelled(): + return + error = future.exception() + if error is None: + return + with failure_lock: + if not first_failure: + first_failure.append(error) + large_file_upload_state.set_error(str(error)) + for sibling in part_futures: + if sibling is not future: + sibling.cancel() + + try: + for part_number, emerge_part in emerge_plan.enumerate_emerge_parts(): + with failure_lock: + if first_failure: + raise first_failure[0] + execution_step_factory = LargeFileEmergeExecutionStepFactory( + self, + emerge_part, + part_number, + file_id, + large_file_upload_state, + finished_parts=finished_parts, + ) + execution_step = execution_step_factory.get_execution_step() + future = self._execute_step(execution_step) + with failure_lock: + part_futures.append(future) + future.add_done_callback(cancel_on_failure) + if first_failure: + future.cancel() + raise first_failure[0] + + # Keep the part checksums in part-number order. + part_sha1_array = [f.result()['contentSha1'] for f in part_futures] + except BaseException: + with failure_lock: + for future in part_futures: + future.cancel() + if first_failure: + raise first_failure[0] + raise + + # Leave unfinished uploads on the server after failure so they can be resumed. # Finish the large file response = self.services.session.finish_large_file(file_id, part_sha1_array) return self.services.api.file_version_factory.from_api_response(response) diff --git a/b2sdk/_internal/transfer/emerge/unbound_write_intent.py b/b2sdk/_internal/transfer/emerge/unbound_write_intent.py index 68f1e9fd2..d4fa4b5c3 100644 --- a/b2sdk/_internal/transfer/emerge/unbound_write_intent.py +++ b/b2sdk/_internal/transfer/emerge/unbound_write_intent.py @@ -19,9 +19,9 @@ from b2sdk._internal.transfer.outbound.upload_source import AbstractUploadSource -class IOWrapper(io.BytesIO): +class IOWrapper(io.RawIOBase): """ - Wrapper for BytesIO that knows when it has been read in full. + Seekable, read-only view over an upload buffer. Note that this stream should go through ``emerge_unbound``, as it's the only one that skips ``_get_emerge_parts`` and pushes buffers to the cloud @@ -38,7 +38,7 @@ def __init__( release_function: Callable[[], None], ): """ - Prepares a new ``io.BytesIO`` structure that will call + Prepares a stream over the buffer that will call a ``release_function`` when buffer is read in full. ``release_function`` can be called from another thread. @@ -48,13 +48,48 @@ def __init__( :param data: data to be provided as a stream :param release_function: function to be called when resource will be released """ - super().__init__(data) + super().__init__() + self._view = memoryview(data) + self._position = 0 self.release_function = release_function + def readable(self): + return True + + def seekable(self): + return True + + def tell(self): + self._checkClosed() + return self._position + + def seek(self, offset, whence=io.SEEK_SET): + self._checkClosed() + if whence == io.SEEK_CUR: + offset += self._position + elif whence == io.SEEK_END: + offset += len(self._view) + elif whence != io.SEEK_SET: + raise ValueError('invalid whence') + if offset < 0: + raise ValueError('negative seek position') + self._position = offset + return offset + + def readinto(self, buffer): + self._checkClosed() + count = min(len(buffer), max(0, len(self._view) - self._position)) + buffer[:count] = self._view[self._position : self._position + count] + self._position += count + return count + def close(self): if not self.closed: - self.release_function() - return super().close() + self._view.release() + try: + self.release_function() + finally: + super().close() class UnboundSourceBytes(AbstractUploadSource): diff --git a/b2sdk/_internal/transfer/outbound/upload_manager.py b/b2sdk/_internal/transfer/outbound/upload_manager.py index 842d8c3f0..ff6ad932d 100644 --- a/b2sdk/_internal/transfer/outbound/upload_manager.py +++ b/b2sdk/_internal/transfer/outbound/upload_manager.py @@ -17,6 +17,7 @@ from b2sdk._internal.exception import ( AlreadyFailed, B2Error, + ChecksumMismatch, MaxRetriesExceeded, ) from b2sdk._internal.file_lock import FileRetentionSetting, LegalHold @@ -175,15 +176,17 @@ def close_stream_callback(stream): input_stream, server_side_encryption=encryption, # todo: client side encryption ) - if content_sha1 == HEX_DIGITS_AT_END: - content_sha1 = input_stream.hash - assert content_sha1 == response['contentSha1'] - return response except B2Error as e: if not e.should_retry_upload(): raise exception_list.append(e) self.account_info.clear_bucket_upload_data(bucket_id) + else: + if content_sha1 == HEX_DIGITS_AT_END: + content_sha1 = input_stream.hash + if content_sha1 != response['contentSha1']: + raise ChecksumMismatch('sha1', content_sha1, response['contentSha1']) + return response large_file_upload_state.set_error(str(exception_list[-1])) raise MaxRetriesExceeded(self.MAX_UPLOAD_ATTEMPTS, exception_list) @@ -228,17 +231,16 @@ def _upload_small_file( legal_hold=legal_hold, custom_upload_timestamp=custom_upload_timestamp, ) - if content_sha1 == HEX_DIGITS_AT_END: - content_sha1 = input_stream.hash - assert ( - content_sha1 == 'do_not_verify' or content_sha1 == response['contentSha1'] - ), '{} != {}'.format(content_sha1, response['contentSha1']) - return self.services.api.file_version_factory.from_api_response(response) - except B2Error as e: if not e.should_retry_upload(): raise exception_info_list.append(e) self.account_info.clear_bucket_upload_data(bucket_id) + else: + if content_sha1 == HEX_DIGITS_AT_END: + content_sha1 = input_stream.hash + if content_sha1 != 'do_not_verify' and content_sha1 != response['contentSha1']: + raise ChecksumMismatch('sha1', content_sha1, response['contentSha1']) + return self.services.api.file_version_factory.from_api_response(response) raise MaxRetriesExceeded(self.MAX_UPLOAD_ATTEMPTS, exception_info_list) diff --git a/changelog.d/+transfer-audit.fixed.md b/changelog.d/+transfer-audit.fixed.md new file mode 100644 index 000000000..4d68c0079 --- /dev/null +++ b/changelog.d/+transfer-audit.fixed.md @@ -0,0 +1 @@ +Reject incorrect upload checksums under Python optimization, cancel pending multipart work after a part fails, and avoid copying unbound upload buffers. diff --git a/test/unit/bucket/test_regression_bucket.py b/test/unit/bucket/test_regression_bucket.py index 4df8b149a..bebbebb68 100644 --- a/test/unit/bucket/test_regression_bucket.py +++ b/test/unit/bucket/test_regression_bucket.py @@ -402,11 +402,6 @@ def _check_iterable_rules(self, input_kind): class TestRegressionLargeUploadFailure: - @known_defect( - 'C8', - 'part uploads keep running after one part of a large upload failed', - raises=DefectStillPresent, - ) def test_c8_failed_part_stops_remaining_part_uploads(self): """C8: once one part fails the whole upload fails; queued parts must not keep uploading.""" from unittest import mock @@ -427,12 +422,14 @@ def test_c8_failed_part_stops_remaining_part_uploads(self): bucket = api.create_bucket('big', 'allPrivate') original = simulator.upload_part part_failed = threading.Event() + queued_sibling = threading.Event() started_after_failure = [] def flaky_upload_part(upload_url, token, part_number, *args, **kwargs): if part_failed.is_set(): started_after_failure.append(part_number) elif part_number == 1: + assert queued_sibling.wait(5), 'a sibling was not queued' part_failed.set() # before raising, so that no later start can be missed raise AccessDenied() return original(upload_url, token, part_number, *args, **kwargs) @@ -445,6 +442,8 @@ def flaky_upload_part(upload_url, token, part_number, *args, **kwargs): def recording_submit(*args, **kwargs): future = real_submit(*args, **kwargs) futures.append(future) + if len(futures) > 1: + queued_sibling.set() return future data = b'x' * (simulator.MIN_PART_SIZE * 6) diff --git a/test/unit/internal/test_emerge_cancel_siblings.py b/test/unit/internal/test_emerge_cancel_siblings.py new file mode 100644 index 000000000..11c2f040f --- /dev/null +++ b/test/unit/internal/test_emerge_cancel_siblings.py @@ -0,0 +1,48 @@ +###################################################################### +# +# File: test/unit/internal/test_emerge_cancel_siblings.py +# +# Copyright 2026 Backblaze Inc. All Rights Reserved. +# +# License https://www.backblaze.com/using_b2_code.html +# +###################################################################### +from concurrent.futures import Future +from types import SimpleNamespace +from unittest.mock import MagicMock, patch + +import pytest + +from b2sdk._internal.transfer.emerge.executor import LargeFileEmergeExecution + + +def test_failed_part_cancels_pending_siblings_and_keeps_unfinished_upload(): + services = MagicMock() + execution = LargeFileEmergeExecution(services, 'bucket', 'name', None, {}, MagicMock()) + execution._get_unfinished_file_and_parts = MagicMock( + return_value=(SimpleNamespace(file_id='unfinished'), {}) + ) + plan = MagicMock() + plan.get_total_length.return_value = None + plan.get_plan_id.return_value = None + plan.enumerate_emerge_parts.return_value = iter([(1, object()), (2, object()), (3, object())]) + first, failed, pending = Future(), Future(), Future() + first.set_result({'contentSha1': 'one'}) + steps = [MagicMock(), MagicMock(), MagicMock()] + for step, future in zip(steps, (first, failed, pending)): + step.execute.return_value = future + steps[2].execute.side_effect = lambda: ( + failed.set_exception(ValueError('part failed')), + pending, + )[1] + with patch( + 'b2sdk._internal.transfer.emerge.executor.LargeFileEmergeExecutionStepFactory' + ) as factory: + factory.side_effect = [ + SimpleNamespace(get_execution_step=lambda step=step: step) for step in steps + ] + with pytest.raises(ValueError, match='part failed'): + execution.execute_plan(plan) + assert pending.cancelled() + services.session.finish_large_file.assert_not_called() + services.large_file.cancel_large_file.assert_not_called() diff --git a/test/unit/internal/test_unbound_write_intent.py b/test/unit/internal/test_unbound_write_intent.py index 7be6ce977..1f12ef639 100644 --- a/test/unit/internal/test_unbound_write_intent.py +++ b/test/unit/internal/test_unbound_write_intent.py @@ -31,6 +31,21 @@ def setUp(self) -> None: self.mock_fun = MagicMock() self.wrapper = IOWrapper(self.data, release_function=self.mock_fun) + def test_read_seek_retry_and_release_buffer(self): + data = bytearray(b'abcdef') + release = MagicMock() + stream = IOWrapper(data, release) + self.assertEqual(stream.read(2), b'ab') + self.assertEqual(stream.tell(), 2) + self.assertEqual(stream.seek(-2, io.SEEK_END), 4) + self.assertEqual(stream.read(), b'ef') + self.assertEqual(stream.seek(0), 0) + self.assertEqual(stream.read(), b'abcdef') + stream.close() + stream.close() + release.assert_called_once() + data.extend(b'g') # closing releases the memoryview's export + def test_function_called_on_close_manual(self): self.mock_fun.assert_not_called() diff --git a/test/unit/internal/test_upload_checksum_optimized.py b/test/unit/internal/test_upload_checksum_optimized.py new file mode 100644 index 000000000..e49ba6841 --- /dev/null +++ b/test/unit/internal/test_upload_checksum_optimized.py @@ -0,0 +1,60 @@ +###################################################################### +# +# File: test/unit/internal/test_upload_checksum_optimized.py +# +# Copyright 2026 Backblaze Inc. All Rights Reserved. +# +# License https://www.backblaze.com/using_b2_code.html +# +###################################################################### +from __future__ import annotations + +import subprocess +import sys + +import pytest + + +@pytest.mark.parametrize('kind', ['small', 'part']) +@pytest.mark.parametrize('known_sha1', [True, False]) +def test_upload_rejects_bad_server_sha1_under_optimization(kind, known_sha1): + program = """ +from unittest.mock import MagicMock +from b2sdk._internal.exception import ChecksumMismatch +from b2sdk._internal.transfer.outbound.upload_manager import UploadManager +from b2sdk._internal.transfer.outbound.upload_source import UploadSourceBytes +from b2sdk._internal.progress import DoNothingProgressListener +from b2sdk._internal.transfer.outbound.large_file_upload_state import LargeFileUploadState + +services = MagicMock() +def upload_file(*args, **kwargs): + args[6].read() + return {'contentSha1': 'wrong'} +def upload_part(*args, **kwargs): + args[4].read() + return {'contentSha1': 'wrong'} +services.session.upload_file.side_effect = upload_file +services.session.upload_part.side_effect = upload_part +manager = UploadManager(services) +source = UploadSourceBytes(b'hello') +if KNOWN_SHA1: + source.get_content_sha1() +progress = DoNothingProgressListener() +try: + if KIND == 'small': + manager._upload_small_file('bucket', source, 'file', 'text/plain', {}, progress) + else: + manager._upload_part('bucket', 'id', source, 1, LargeFileUploadState(progress), {}, None) +except ChecksumMismatch as error: + if error.expected != source.get_content_sha1() or error.actual != 'wrong': + raise RuntimeError('checksum error has incorrect values') +else: + raise RuntimeError('server checksum mismatch was accepted') +""" + result = subprocess.run( + [sys.executable, '-O', '-c', f'KIND = {kind!r}\nKNOWN_SHA1 = {known_sha1!r}\n' + program], + capture_output=True, + text=True, + check=False, + ) + assert result.returncode == 0, result.stderr diff --git a/test/unit/stream/test_regression_streams.py b/test/unit/stream/test_regression_streams.py index 626faa8e5..d9a52272a 100644 --- a/test/unit/stream/test_regression_streams.py +++ b/test/unit/stream/test_regression_streams.py @@ -150,11 +150,6 @@ def test_c52_invalid_offset_is_rejected(self, tmp_path, offset, length): class TestUnboundWriteIntentMemory: - @known_defect( - 'C57', - 'UnboundSourceBytes copies the chunk, using about twice the documented memory', - raises=DefectStillPresent, - ) def test_c57_unbound_buffer_wrapping_does_not_copy_the_chunk(self): """C57: wrapping a bytearray chunk for upload must not allocate a second full copy.""" tracemalloc = pytest.importorskip( From 2e316e6a60b589d07885de167f15e7eb69fb6a68 Mon Sep 17 00:00:00 2001 From: Felipe Fumero Date: Sat, 21 Nov 2026 17:34:04 -0600 Subject: [PATCH 055/113] fix: preserve auth state and correct API, HTTP, type, and part-size handling (#719) --- b2sdk/_internal/api.py | 2 +- b2sdk/_internal/b2http.py | 6 +- b2sdk/_internal/bucket.py | 6 +- b2sdk/_internal/session.py | 12 +++- b2sdk/_internal/types.py | 2 +- b2sdk/v1/session.py | 2 + changelog.d/+c28-bucket-assert.fixed.md | 1 + changelog.d/+c31-pydantic-version.fixed.md | 1 + changelog.d/+c33-upload-part-size.fixed.md | 1 + changelog.d/+c51-http-error-args.fixed.md | 1 + changelog.d/+c55-auth-session.fixed.md | 1 + test/unit/bucket/test_regression_bucket.py | 68 ++++++++++++++++++---- test/unit/test_regression_misc.py | 41 ++++++++----- test/unit/test_session.py | 16 +++++ 14 files changed, 125 insertions(+), 35 deletions(-) create mode 100644 changelog.d/+c28-bucket-assert.fixed.md create mode 100644 changelog.d/+c31-pydantic-version.fixed.md create mode 100644 changelog.d/+c33-upload-part-size.fixed.md create mode 100644 changelog.d/+c51-http-error-args.fixed.md create mode 100644 changelog.d/+c55-auth-session.fixed.md diff --git a/b2sdk/_internal/api.py b/b2sdk/_internal/api.py index 0588f4464..8fa97547c 100644 --- a/b2sdk/_internal/api.py +++ b/b2sdk/_internal/api.py @@ -265,7 +265,7 @@ def create_bucket( bucket = self.BUCKET_FACTORY_CLASS.from_api_bucket_dict(self, response) assert ( name == bucket.name - ), f'API created a bucket with different name than requested: {name} != {name}' + ), f'API created a bucket with different name than requested: {name} != {bucket.name}' assert ( bucket_type == bucket.type_ ), f'API created a bucket with different type than requested: {bucket_type} != {bucket.type_}' diff --git a/b2sdk/_internal/b2http.py b/b2sdk/_internal/b2http.py index b9d5efd5f..4ea477473 100644 --- a/b2sdk/_internal/b2http.py +++ b/b2sdk/_internal/b2http.py @@ -591,16 +591,16 @@ def _translate_errors(cls, fcn, post_params=None): raise # pass through exceptions from just above except requests.ConnectionError as e0: - e1 = e0.args[0] + e1 = e0.args[0] if e0.args else None if isinstance(e1, requests.packages.urllib3.exceptions.MaxRetryError): - msg = e1.args[0] + msg = e1.args[0] if e1.args else '' if 'nodename nor servname provided, or not known' in msg: # Unknown host, or DNS failing. In the context of calling # B2, this means that something is down between here and # Backblaze, so we treat it like 503 Service Unavailable. raise UnknownHost() elif isinstance(e1, requests.packages.urllib3.exceptions.ProtocolError): - e2 = e1.args[1] + e2 = e1.args[1] if len(e1.args) > 1 else None if isinstance(e2, TimeoutError): raise B2RequestTimeout(str(e0)) diff --git a/b2sdk/_internal/bucket.py b/b2sdk/_internal/bucket.py index 725911154..e3b3d30dc 100644 --- a/b2sdk/_internal/bucket.py +++ b/b2sdk/_internal/bucket.py @@ -910,7 +910,8 @@ def upload( :param str file_name: the file name of the new B2 file :param str,None content_type: the MIME type, or ``None`` to accept the default based on file extension of the B2 file name :param dict,None file_info: a file info to store with the file or ``None`` to not store anything - :param min_part_size: lower limit of part size for the transfer planner, in bytes + :param min_part_size: lower limit of part size for the transfer planner, in bytes; + the account's recommended part size is used when larger :param b2sdk.v2.AbstractProgressListener,None progress_listener: a progress listener object to use, or ``None`` to not report progress :param b2sdk.v2.EncryptionSetting encryption: encryption settings (``None`` if unknown) :param b2sdk.v2.FileRetentionSetting file_retention: file retention setting @@ -937,8 +938,7 @@ def upload( content_type=content_type, file_info=file_info, progress_listener=progress_listener, - # FIXME: Bucket.upload documents wrong logic - recommended_upload_part_size=min_part_size, + min_part_size=min_part_size, encryption=encryption, file_retention=file_retention, legal_hold=legal_hold, diff --git a/b2sdk/_internal/session.py b/b2sdk/_internal/session.py index 31f5461b0..125df0207 100644 --- a/b2sdk/_internal/session.py +++ b/b2sdk/_internal/session.py @@ -22,7 +22,7 @@ from b2sdk._internal.b2http import B2Http from b2sdk._internal.cache import AbstractCache, AuthInfoCache, DummyCache from b2sdk._internal.encryption.setting import EncryptionSetting -from b2sdk._internal.exception import InvalidAuthToken, Unauthorized +from b2sdk._internal.exception import InvalidAuthToken, RestrictedBucketMissing, Unauthorized from b2sdk._internal.file_lock import BucketRetentionSetting, FileRetentionSetting, LegalHold from b2sdk._internal.raw_api import ALL_CAPABILITIES, REALM_URLS, LifecycleRule from b2sdk._internal.replication.setting import ReplicationConfiguration @@ -123,6 +123,8 @@ def authorize_account(self, realm, application_key_id, application_key): allowed = self._construct_allowed_dict(storage_api_info) + self._validate_bucket_restrictions(allowed) + # Clear the cache if new account has been used if not self.account_info.is_same_account(account_id, realm): self.cache.clear() @@ -142,6 +144,14 @@ def authorize_account(self, realm, application_key_id, application_key): application_key_id=application_key_id, ) + @staticmethod + def _validate_bucket_restrictions(allowed): + # Reject deleted-bucket restrictions before changing credentials or caches. + if any(bucket['name'] is None for bucket in allowed.get('buckets') or []): + raise RestrictedBucketMissing + if allowed.get('bucketId') is not None and allowed.get('bucketName') is None: + raise RestrictedBucketMissing + def _construct_allowed_dict(self, storage_api_info): # `allowed` object has been deprecated in the v3 of the API, but we still # construct it artificially to avoid changes in all the reliant parts. diff --git a/b2sdk/_internal/types.py b/b2sdk/_internal/types.py index 5e3dbbd3d..277f21439 100644 --- a/b2sdk/_internal/types.py +++ b/b2sdk/_internal/types.py @@ -32,7 +32,7 @@ try: import pydantic - if getattr(pydantic, '__version__', '') < '2': + if int(getattr(pydantic, '__version__', '0').split('.')[0] or '0') < 2: raise ImportError if sys.version_info < (3, 10): # https://github.com/pydantic/pydantic/issues/7873 diff --git a/b2sdk/v1/session.py b/b2sdk/v1/session.py index 075feab8a..c7ae3fc88 100644 --- a/b2sdk/v1/session.py +++ b/b2sdk/v1/session.py @@ -60,6 +60,8 @@ def authorize_account(self, realm, application_key_id, application_key): 'namePrefix': storage_api_info['namePrefix'], } + self._validate_bucket_restrictions(allowed) + # Clear the cache if new account has been used if not self.account_info.is_same_account(account_id, realm): self.cache.clear() diff --git a/changelog.d/+c28-bucket-assert.fixed.md b/changelog.d/+c28-bucket-assert.fixed.md new file mode 100644 index 000000000..53e5aaa09 --- /dev/null +++ b/changelog.d/+c28-bucket-assert.fixed.md @@ -0,0 +1 @@ +Show the returned bucket name in the assertion message when bucket creation returns a different name. diff --git a/changelog.d/+c31-pydantic-version.fixed.md b/changelog.d/+c31-pydantic-version.fixed.md new file mode 100644 index 000000000..e163c2b3f --- /dev/null +++ b/changelog.d/+c31-pydantic-version.fixed.md @@ -0,0 +1 @@ +Compare the Pydantic major version numerically when detecting optional validation support. diff --git a/changelog.d/+c33-upload-part-size.fixed.md b/changelog.d/+c33-upload-part-size.fixed.md new file mode 100644 index 000000000..4564e3632 --- /dev/null +++ b/changelog.d/+c33-upload-part-size.fixed.md @@ -0,0 +1 @@ +Treat Bucket.upload min_part_size as a lower limit while retaining the account recommended upload part size. diff --git a/changelog.d/+c51-http-error-args.fixed.md b/changelog.d/+c51-http-error-args.fixed.md new file mode 100644 index 000000000..1fc88389c --- /dev/null +++ b/changelog.d/+c51-http-error-args.fixed.md @@ -0,0 +1 @@ +Map connection errors with missing exception arguments to B2 connection errors without raising IndexError. diff --git a/changelog.d/+c55-auth-session.fixed.md b/changelog.d/+c55-auth-session.fixed.md new file mode 100644 index 000000000..d2c6f4007 --- /dev/null +++ b/changelog.d/+c55-auth-session.fixed.md @@ -0,0 +1 @@ +Preserve existing credentials and bucket caches when authorization is rejected because a restricted bucket no longer exists. diff --git a/test/unit/bucket/test_regression_bucket.py b/test/unit/bucket/test_regression_bucket.py index bebbebb68..6fcaf6afe 100644 --- a/test/unit/bucket/test_regression_bucket.py +++ b/test/unit/bucket/test_regression_bucket.py @@ -206,11 +206,6 @@ def test_c45_explicit_resume_requires_matching_timestamp(self): self.bucket.create_file(**kwargs) assert list(self.bucket.list_unfinished_large_files(prefix=name)) - @known_defect( - 'C33', - 'Bucket.upload passes min_part_size as the recommended part size instead of a lower limit', - raises=DefectStillPresent, - ) def test_c33_upload_min_part_size_is_only_a_lower_limit(self): """C33: min_part_size is a lower limit; parts must still follow the recommended part size. @@ -340,11 +335,64 @@ def fail_delete(*args): api.delete_bucket(bucket) assert api.cache.get_bucket_id_or_none_from_bucket_name(bucket.name) == bucket.id_ - @known_defect( - 'C28', - 'the create_bucket mismatch message prints the same name twice', - raises=AssertionError, - ) + @pytest.mark.parametrize('account_kind', ['fresh', 'same', 'different']) + @pytest.mark.parametrize('cache_kind', ['memory', 'account_info', 'sqlite']) + def test_c55_failed_authorization_preserves_session(self, account_kind, cache_kind, tmp_path): + from apiver_deps_exception import MissingAccountData, RestrictedBucketMissing + + from test.unit.test_base import create_key + + info = ( + SqliteAccountInfo(file_name=str(tmp_path / 'auth.sqlite')) + if cache_kind == 'sqlite' + else InMemoryAccountInfo() + ) + cache = InMemoryCache() if cache_kind == 'memory' else AuthInfoCache(info) + api, _ = self._api(account_info=info, cache=cache) + old_bucket = api.create_bucket('old-bucket', 'allPrivate') + old_token = info.get_account_auth_token() + old_key = info.get_application_key_id() + old_allowed = info.get_allowed() + if account_kind == 'different': + other = B2Api( + InMemoryAccountInfo(), api_config=B2HttpApiConfig(_raw_api_class=RawSimulator) + ) + other.session.raw_api = api.session.raw_api + account_id, master_key = other.session.raw_api.create_account() + other.authorize_account( + application_key_id=account_id, application_key=master_key, realm='production' + ) + else: + other = api + key = create_key( + other, + key_name='deleted-bucket', + capabilities=['listBuckets'], + bucket_id='missing-bucket', + ) + if account_kind == 'fresh': + info.clear() + cache.clear() + old_cache = cache.list_bucket_names_ids() + + with pytest.raises(RestrictedBucketMissing): + api.authorize_account( + application_key_id=key.id_, application_key=key.application_key, realm='production' + ) + + if account_kind == 'fresh': + with pytest.raises(MissingAccountData): + info.get_application_key_id() + assert not api.authorize_automatically() + else: + assert info.get_account_auth_token() == old_token + assert info.get_application_key_id() == old_key + assert info.get_allowed() == old_allowed + assert api.get_bucket_by_name(old_bucket.name).id_ == old_bucket.id_ + assert cache.list_bucket_names_ids() == old_cache + if cache_kind == 'sqlite': + info.close() + def test_c28_create_bucket_mismatch_message_names_both_buckets(self): """C28: the assertion message must show requested and returned names, not name twice.""" from unittest import mock diff --git a/test/unit/test_regression_misc.py b/test/unit/test_regression_misc.py index a05b5c4f6..a0971a9af 100644 --- a/test/unit/test_regression_misc.py +++ b/test/unit/test_regression_misc.py @@ -27,7 +27,7 @@ from apiver_deps import B2Http, B2HttpApiConfig from apiver_deps_exception import B2ConnectionError, B2RequestTimeout -from test.known_defect import DefectStillPresent, defect_raises, expect, known_defect +from test.known_defect import expect pytestmark = [pytest.mark.apiver(from_ver=2)] @@ -39,23 +39,28 @@ def _b2_http(): class TestTypes: - @known_defect( - 'C31', - 'the pydantic version is compared as text, so "10.0" counts as older than "2"', - raises=AssertionError, + @pytest.mark.parametrize( + 'version, supported', + [ + ('1.10.20', False), + ('2.0.0', True), + ('2.0.0rc1', True), + ('10.0.0', True), + ('', False), + ], ) - def test_c31_pydantic_version_ten_counts_as_v2_or_newer(self, monkeypatch): + def test_c31_pydantic_version_is_compared_numerically(self, monkeypatch, version, supported): """C31: pydantic version comparison must be numeric ('10.0' is newer than '2').""" pydantic = pytest.importorskip('pydantic') types_module = importlib.import_module('b2sdk._internal.types') - monkeypatch.setattr(pydantic, '__version__', '10.0.0') + monkeypatch.setattr(pydantic, '__version__', version) try: importlib.reload(types_module) detected = types_module.pydantic finally: monkeypatch.undo() importlib.reload(types_module) - assert detected is not None, 'pydantic was not detected' + assert (detected is not None) == supported class TestHttpLayer: @@ -70,17 +75,21 @@ def test_c10_create_style_post_is_not_blindly_resent_after_timeout(self): http.post_json_return_json(url, {}, {'bucketName': 'b'}) expect(len(responses.calls) == 1, f'request was sent {len(responses.calls)} times') - @pytest.mark.parametrize('args', [()]) - @known_defect( - 'C51', - 'error mapping raises IndexError for a ConnectionError with no arguments', - raises=DefectStillPresent, + @pytest.mark.parametrize( + 'args', + [ + (), + (requests.packages.urllib3.exceptions.MaxRetryError(None, URL),), + (requests.packages.urllib3.exceptions.ProtocolError(),), + (requests.packages.urllib3.exceptions.ProtocolError('incomplete'),), + ], ) def test_c51_connection_error_with_missing_args_is_mapped_without_indexerror(self, args): """C51: ConnectionError carrying fewer than 2 args must map to a B2 error, not IndexError.""" from b2sdk._internal.b2http import B2Http as InternalB2Http + if args and isinstance(args[0], requests.packages.urllib3.exceptions.MaxRetryError): + args[0].args = () error = requests.ConnectionError(*args) - with defect_raises(IndexError, match='tuple index out of range'): - with pytest.raises(B2ConnectionError): - InternalB2Http._translate_errors(lambda: (_ for _ in ()).throw(error)) + with pytest.raises(B2ConnectionError): + InternalB2Http._translate_errors(lambda: (_ for _ in ()).throw(error)) diff --git a/test/unit/test_session.py b/test/unit/test_session.py index a19cb522a..1b9d36cba 100644 --- a/test/unit/test_session.py +++ b/test/unit/test_session.py @@ -69,6 +69,22 @@ def test_simple_authorization(self, authorize_call_kwargs): assert self.b2_session.cache.clear.called is False self.b2_session.account_info.set_auth_data.assert_called_once_with(**authorize_call_kwargs) + def test_c55_deleted_bucket_does_not_replace_auth_data(self, apiver_int): + from apiver_deps_exception import RestrictedBucketMissing + + storage = self.b2_session.raw_api.authorize_account.return_value['apiInfo']['storageApi'] + if apiver_int >= 3: + storage['allowed']['buckets'] = [{'id': 'deleted', 'name': None}] + else: + storage.update(bucketId='deleted', bucketName=None) + self.b2_session.account_info.is_same_account.return_value = False + + with pytest.raises(RestrictedBucketMissing): + self.b2_session.authorize_account('dev', '123', '456') + + self.b2_session.account_info.set_auth_data.assert_not_called() + self.b2_session.cache.clear.assert_not_called() + def test_clear_cache(self): self.b2_session.account_info.is_same_account.return_value = False From f9bad63cbfd6da4007d26957c97a0874bbf01e26 Mon Sep 17 00:00:00 2001 From: Felipe Fumero Date: Sat, 21 Nov 2026 17:41:06 -0600 Subject: [PATCH 056/113] test: drop unused known-defect imports after the low-severity fixes (#722) Merging the low-severity fixes (#716, #719) converted known-defect tests to ordinary assertions but left test.known_defect imports unused, failing ruff (F401) on master. Import only the names each module still uses. Refs #711 --- .../+prune-unused-known-defect-imports.infrastructure.md | 1 + test/unit/bucket/test_regression_bucket.py | 2 +- test/unit/stream/test_regression_streams.py | 2 +- 3 files changed, 3 insertions(+), 2 deletions(-) create mode 100644 changelog.d/+prune-unused-known-defect-imports.infrastructure.md diff --git a/changelog.d/+prune-unused-known-defect-imports.infrastructure.md b/changelog.d/+prune-unused-known-defect-imports.infrastructure.md new file mode 100644 index 000000000..a25e99071 --- /dev/null +++ b/changelog.d/+prune-unused-known-defect-imports.infrastructure.md @@ -0,0 +1 @@ +Remove unused known-defect test imports left after resolving several low-severity findings. diff --git a/test/unit/bucket/test_regression_bucket.py b/test/unit/bucket/test_regression_bucket.py index 6fcaf6afe..98a0b55c0 100644 --- a/test/unit/bucket/test_regression_bucket.py +++ b/test/unit/bucket/test_regression_bucket.py @@ -45,7 +45,7 @@ ) from apiver_deps_exception import NonExistentBucket -from test.known_defect import DefectStillPresent, expect, known_defect +from test.known_defect import expect, known_defect from .test_bucket import TestCaseWithBucket diff --git a/test/unit/stream/test_regression_streams.py b/test/unit/stream/test_regression_streams.py index d9a52272a..87a7cc001 100644 --- a/test/unit/stream/test_regression_streams.py +++ b/test/unit/stream/test_regression_streams.py @@ -31,7 +31,7 @@ UploadSourceStreamRange, ) from b2sdk._internal.utils import hex_sha1_of_unlimited_stream -from test.known_defect import DefectStillPresent, expect, known_defect +from test.known_defect import expect class ShortReadStream(io.RawIOBase): From 23f39d6420c069f11fc6048f23e0d50e7247fbe2 Mon Sep 17 00:00:00 2001 From: Sophie <49928680+sophiecarreras@users.noreply.github.com> Date: Sat, 21 Nov 2026 20:43:53 -0300 Subject: [PATCH 057/113] test: retire resolved documentation defect markers (#721) --- changelog.d/+resolved-doc-regressions.infrastructure.md | 1 + test/static/test_regression_repo_checks.py | 8 +++----- 2 files changed, 4 insertions(+), 5 deletions(-) create mode 100644 changelog.d/+resolved-doc-regressions.infrastructure.md diff --git a/changelog.d/+resolved-doc-regressions.infrastructure.md b/changelog.d/+resolved-doc-regressions.infrastructure.md new file mode 100644 index 000000000..29c66f4c6 --- /dev/null +++ b/changelog.d/+resolved-doc-regressions.infrastructure.md @@ -0,0 +1 @@ +Run checks for the support text and optional dependency installation as ordinary regressions now that the documentation defects are fixed. diff --git a/test/static/test_regression_repo_checks.py b/test/static/test_regression_repo_checks.py index b2b5f6148..b8a376843 100644 --- a/test/static/test_regression_repo_checks.py +++ b/test/static/test_regression_repo_checks.py @@ -11,11 +11,9 @@ They read repository files only and are skipped when the repository files are not available. -Tests marked with ``@known_defect`` describe a defect that is still present: they assert the correct -behaviour and are strict expected failures, so the default run stays green and fails with -"XPASS(strict)" once the defect is fixed (then remove the decorator). To see them fail, run -``pytest --runxfail -m known_defect`` (see ``test/known_defect.py``). The ``C`` identifiers are -short labels that also appear in the test names and decorators. +These ordinary regression tests retain coverage for resolved defects. The ``C`` identifiers +are short labels retained in the test names and docstrings. See ``test/known_defect.py`` for the +expected-failure convention used for unresolved defects elsewhere in the suite. """ from __future__ import annotations From 901933f929d3f6cadff74eb9de9d84cacd270671 Mon Sep 17 00:00:00 2001 From: Felipe Fumero Date: Sat, 21 Nov 2026 18:12:21 -0600 Subject: [PATCH 058/113] test: compare resolved paths in the symlinked-root scan test (#724) The C54 containment test asserted an exact path string, but on Windows symlink resolution can return an extended-length (\\?\\) path, so the raw-string comparison failed there while the containment behaviour is correct. Compare os.path.realpath of both sides instead. Refs #711 --- changelog.d/+windows-symlink-path-test.infrastructure.md | 1 + test/unit/scan/test_folder.py | 9 ++++++--- 2 files changed, 7 insertions(+), 3 deletions(-) create mode 100644 changelog.d/+windows-symlink-path-test.infrastructure.md diff --git a/changelog.d/+windows-symlink-path-test.infrastructure.md b/changelog.d/+windows-symlink-path-test.infrastructure.md new file mode 100644 index 000000000..0e68ddace --- /dev/null +++ b/changelog.d/+windows-symlink-path-test.infrastructure.md @@ -0,0 +1 @@ +Make the symlinked-root scan test compare resolved paths so it passes on Windows. diff --git a/test/unit/scan/test_folder.py b/test/unit/scan/test_folder.py index d887eab86..347229afb 100644 --- a/test/unit/scan/test_folder.py +++ b/test/unit/scan/test_folder.py @@ -9,6 +9,7 @@ ###################################################################### from __future__ import annotations +import os import platform from pathlib import Path @@ -75,6 +76,8 @@ def test_make_full_path_accepts_internal_link_and_symlinked_root(tmp_path): root_link = tmp_path / 'root-link' root_link.symlink_to(root, target_is_directory=True) - assert LocalFolder(root_link).make_full_path('link/new-file.txt') == str( - root_link / 'link' / 'new-file.txt' - ) + result = LocalFolder(root_link).make_full_path('link/new-file.txt') + expected = str(root_link / 'link' / 'new-file.txt') + # On Windows, symlink resolution can return an extended-length ("\\?\\") path, + # so compare the resolved real paths rather than the raw strings. + assert os.path.realpath(result) == os.path.realpath(expected) From 7fc243773515da59cbd9220292875210b801c705 Mon Sep 17 00:00:00 2001 From: Felipe Fumero Date: Sat, 21 Nov 2026 18:25:49 -0600 Subject: [PATCH 059/113] test: compare the symlinked-root path by filesystem identity (#725) The previous realpath comparison (#724) did not normalize the Windows extended-length (\\?\\) prefix: realpath keeps it on the returned path but not on the expected one. Compare os.path.samefile of the existing parent directory plus the file name, which is immune to the prefix. Refs #711 --- changelog.d/+windows-symlink-samefile.infrastructure.md | 1 + test/unit/scan/test_folder.py | 8 +++++--- 2 files changed, 6 insertions(+), 3 deletions(-) create mode 100644 changelog.d/+windows-symlink-samefile.infrastructure.md diff --git a/changelog.d/+windows-symlink-samefile.infrastructure.md b/changelog.d/+windows-symlink-samefile.infrastructure.md new file mode 100644 index 000000000..33d182df6 --- /dev/null +++ b/changelog.d/+windows-symlink-samefile.infrastructure.md @@ -0,0 +1 @@ +Compare the symlinked-root scan test path by filesystem identity so it passes on Windows. diff --git a/test/unit/scan/test_folder.py b/test/unit/scan/test_folder.py index 347229afb..41b33bec0 100644 --- a/test/unit/scan/test_folder.py +++ b/test/unit/scan/test_folder.py @@ -78,6 +78,8 @@ def test_make_full_path_accepts_internal_link_and_symlinked_root(tmp_path): result = LocalFolder(root_link).make_full_path('link/new-file.txt') expected = str(root_link / 'link' / 'new-file.txt') - # On Windows, symlink resolution can return an extended-length ("\\?\\") path, - # so compare the resolved real paths rather than the raw strings. - assert os.path.realpath(result) == os.path.realpath(expected) + # Windows symlink resolution can add an extended-length ("\\?\\") prefix that + # realpath does not normalize away, so compare by filesystem identity of the + # (existing) parent directory plus the file name instead of raw strings. + assert os.path.basename(result) == os.path.basename(expected) == 'new-file.txt' + assert os.path.samefile(os.path.dirname(result), os.path.dirname(expected)) From 3811cd54ec46a0ee768ef140a62e4030720d23e2 Mon Sep 17 00:00:00 2001 From: Sophie <49928680+sophiecarreras@users.noreply.github.com> Date: Sat, 21 Nov 2026 22:36:14 -0300 Subject: [PATCH 060/113] test: account for Windows long-path prefix in symlink assertion (#723) --- .../+windows-symlink-path-expectation.infrastructure.md | 1 + test/unit/scan/test_folder.py | 7 ++++--- 2 files changed, 5 insertions(+), 3 deletions(-) create mode 100644 changelog.d/+windows-symlink-path-expectation.infrastructure.md diff --git a/changelog.d/+windows-symlink-path-expectation.infrastructure.md b/changelog.d/+windows-symlink-path-expectation.infrastructure.md new file mode 100644 index 000000000..1d0525161 --- /dev/null +++ b/changelog.d/+windows-symlink-path-expectation.infrastructure.md @@ -0,0 +1 @@ +Account for the Windows long-path prefix when checking paths through internal symlinks and symlinked local roots in the unit tests. diff --git a/test/unit/scan/test_folder.py b/test/unit/scan/test_folder.py index 41b33bec0..03868ba5b 100644 --- a/test/unit/scan/test_folder.py +++ b/test/unit/scan/test_folder.py @@ -17,6 +17,7 @@ from b2sdk._internal.scan.exception import UnsupportedFilename from b2sdk._internal.scan.folder import LocalFolder +from b2sdk._internal.utils import fix_windows_path_limit @pytest.mark.skipif( @@ -78,8 +79,8 @@ def test_make_full_path_accepts_internal_link_and_symlinked_root(tmp_path): result = LocalFolder(root_link).make_full_path('link/new-file.txt') expected = str(root_link / 'link' / 'new-file.txt') - # Windows symlink resolution can add an extended-length ("\\?\\") prefix that - # realpath does not normalize away, so compare by filesystem identity of the - # (existing) parent directory plus the file name instead of raw strings. + assert result == fix_windows_path_limit(expected) + # Also check the existing parent by filesystem identity: realpath alone + # does not normalize away the Windows extended-length prefix. assert os.path.basename(result) == os.path.basename(expected) == 'new-file.txt' assert os.path.samefile(os.path.dirname(result), os.path.dirname(expected)) From 279b46e82e8dbd2f3e927aa47a120adb5aa89df7 Mon Sep 17 00:00:00 2001 From: Felipe Fumero Date: Sun, 22 Nov 2026 13:14:08 -0600 Subject: [PATCH 061/113] docs: add a SECURITY.md disclosure policy (#727) Adds a standalone coordinated-disclosure policy (private GitHub advisory flow, scope, response targets). Independent of the larger AI-native SDLC bundle in #635 so the policy lands without waiting on it. Refs #711 --- SECURITY.md | 75 +++++++++++++++++++ .../+security-policy.infrastructure.md | 1 + 2 files changed, 76 insertions(+) create mode 100644 SECURITY.md create mode 100644 changelog.d/+security-policy.infrastructure.md diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 000000000..d6fe48579 --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,75 @@ +# Security Policy + +Security-response owner: Backblaze Security. Repository maintainers triage reports with them. + +## Supported Versions + +The latest release of b2sdk (currently `2.13.x`) receives security fixes. Every apiver layer +(`b2sdk.v0`..`b2sdk.v3`) inside that release is covered. Earlier releases are not patched in place; +upgrade to the newest release to receive fixes. + +| Version | Supported | +|---|---| +| Latest release (`2.13.x`) | Yes | +| Older releases | No | + +## Reporting a Vulnerability + +**Do not file a public GitHub issue for a security vulnerability.** + +Instead, report it privately via GitHub Security Advisories: + +1. Go to the [Security tab](https://github.com/Backblaze/b2-sdk-python/security/advisories/new) of this repository +2. Click **Report a vulnerability** +3. Provide a clear description, the affected version, reproduction steps, and impact assessment + +You can also email **security@backblaze.com** if you cannot use GitHub Security Advisories. + +## What to expect + +- Acknowledgement within 3 business days +- Initial assessment within 7 business days +- Coordinated disclosure once a fix is available, shipped as a patch release with a changelog entry and a + GitHub security advisory + +## Scope + +In scope: + +- Credential-handling flaws in `b2sdk`: application keys, authorization tokens or SSE-C keys exposed in + logs, exception messages, `repr`, or sent to unintended hosts +- Account-info storage: `SqliteAccountInfo` files created readable by other users, or credentials cached + where the caller did not ask +- Transport flaws: TLS verification bypassed, or requests sent outside the key's bucket or prefix scope +- Sync and download path handling that writes outside the destination folder +- Denial of service reachable through the public API, such as unbounded retries or thread leaks triggered + by server responses + +Out of scope: + +- Vulnerabilities in the Backblaze B2 service itself — report those to Backblaze directly +- Misuse of credentials by the calling application, such as embedding a master key in client code +- Issues requiring root or local access on the machine running the application + +## Security-relevant areas + +- **Credentials**: application keys go to `B2Api.authorize_account` and only to the B2 authorize + endpoint; the token returned is kept in the account-info store and sent in the `Authorization` header. +- **Account info**: `SqliteAccountInfo` creates its database with owner-only permissions before writing + credentials to it. +- **SSE-C keys**: customer-provided keys travel in request headers on uploads and downloads, and as + `customerKey` fields in JSON request bodies on large-file start (`serverSideEncryption`) and server-side + copy (`sourceServerSideEncryption`, `destinationServerSideEncryption`). They are not persisted. If you + log requests, redact encryption keys in both headers and bodies. +- **Transport**: all B2 API traffic uses HTTPS through `requests`, with certificates from `certifi`. +- **Tests and CI**: integration tests read `B2_TEST_APPLICATION_KEY_ID` and `B2_TEST_APPLICATION_KEY` from + repository secrets. The `.sdkharness` checks refuse any non-loopback endpoint and ambient `B2_*` + credentials. + +## Best practices for users + +- Use application keys scoped to specific buckets, prefixes and capabilities. +- Never embed an application key in code shipped to end users; issue download authorizations from a + backend instead. +- Rotate application keys regularly. +- Use SSE-B2 or SSE-C for encryption at rest, and Object Lock for compliance-sensitive data. diff --git a/changelog.d/+security-policy.infrastructure.md b/changelog.d/+security-policy.infrastructure.md new file mode 100644 index 000000000..4a9e6c321 --- /dev/null +++ b/changelog.d/+security-policy.infrastructure.md @@ -0,0 +1 @@ +Add a SECURITY.md describing the coordinated vulnerability-disclosure policy. From 38fc6f56da1d3c98d88fbd9c4c7d28889e806bee Mon Sep 17 00:00:00 2001 From: scarreras Date: Mon, 23 Nov 2026 20:52:13 -0300 Subject: [PATCH 062/113] ci: name the doc-example step for what it checks (imports resolve) Co-Authored-By: Claude Sonnet 5.5 --- .github/workflows/ci.yml | 2 +- changelog.d/+doc-examples-and-filter-tests.infrastructure.md | 2 +- noxfile.py | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 023cb80fb..f2edcfd16 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -77,7 +77,7 @@ jobs: run: uv sync --only-group nox --locked - name: Build the distribution run: uv run nox -vs build - - name: Compile documentation examples + - name: Check documentation example imports run: uv run nox -vs doc_examples cleanup_buckets: # Live B2 access requires explicit opt-in and is never allowed for drafts. diff --git a/changelog.d/+doc-examples-and-filter-tests.infrastructure.md b/changelog.d/+doc-examples-and-filter-tests.infrastructure.md index 2225d2ee5..c5c2b2bf8 100644 --- a/changelog.d/+doc-examples-and-filter-tests.infrastructure.md +++ b/changelog.d/+doc-examples-and-filter-tests.infrastructure.md @@ -1 +1 @@ -Check in CI that every import shown in the README and documentation examples resolves against the public `b2sdk` API, and add direct unit tests for the planner's `_filter_out_none` helper. +Check in CI that every import shown in the documentation examples (`doc/source/*.rst`) resolves against the public `b2sdk` API, and add direct unit tests for the planner's `_filter_out_none` helper. diff --git a/noxfile.py b/noxfile.py index 42a29fcf6..f9570267e 100644 --- a/noxfile.py +++ b/noxfile.py @@ -245,7 +245,7 @@ def doc(session): @nox.session(python=PYTHON_DEFAULT_VERSION) def doc_examples(session): - """Compile the documentation examples: every import in README/docs must resolve against b2sdk.""" + """Check that every import shown in the documented examples (doc/source/*.rst) resolves against b2sdk.""" uv_install(session, groups=('test',), extras=('full',)) session.run('pytest', '--api=v3', 'test/unit/test_documentation_examples.py', *session.posargs) From 842cd5e410460db446dcf21ee12d2f36bc8dd686 Mon Sep 17 00:00:00 2001 From: Sophie <49928680+sophiecarreras@users.noreply.github.com> Date: Mon, 23 Nov 2026 21:25:00 -0300 Subject: [PATCH 063/113] Add shared parsing and retry boundary tests (#728) * test: cover HTTP parsing and bounded retry behavior * test: use malformed range end in rejection case --- .../+parsing_retry_coverage.infrastructure.md | 1 + test/unit/b2http/test_b2http.py | 84 +++++++++++++++++++ test/unit/utils/test_range_.py | 6 ++ 3 files changed, 91 insertions(+) create mode 100644 changelog.d/+parsing_retry_coverage.infrastructure.md diff --git a/changelog.d/+parsing_retry_coverage.infrastructure.md b/changelog.d/+parsing_retry_coverage.infrastructure.md new file mode 100644 index 000000000..8d71247ff --- /dev/null +++ b/changelog.d/+parsing_retry_coverage.infrastructure.md @@ -0,0 +1 @@ +Add shared-interface unit coverage for malformed range headers, HTTP error parsing, retry attempt budgets, and capped retry backoff. diff --git a/test/unit/b2http/test_b2http.py b/test/unit/b2http/test_b2http.py index 138464793..15a32e553 100644 --- a/test/unit/b2http/test_b2http.py +++ b/test/unit/b2http/test_b2http.py @@ -356,6 +356,90 @@ def test_service_error_ignores_http_date_retry_after( mock_time.assert_called_once_with(1.0) + @pytest.mark.parametrize( + 'http_status, body_status, retry_expected', + [(503, 400, True), (503, 'invalid', True), (503, None, True), (400, 503, False)], + ) + @responses.activate + def test_http_status_controls_retries_when_error_metadata_is_invalid( + self, b2_http: B2Http, mock_time: MagicMock, http_status, body_status, retry_expected + ): + responses.get( + self.URL, + status=http_status, + json={ + 'status': body_status, + 'code': 'bad_json', + 'message': 'synthetic upstream error', + 'additional_metadata': {'ignored': True}, + }, + ) + responses.get(self.URL, json={'recovered': True}) + + if retry_expected: + result = b2_http.request(responses.GET, self.URL, {}, try_count=2) + assert result.json() == {'recovered': True} + assert len(responses.calls) == 2 + mock_time.assert_called_once_with(1.0) + else: + with pytest.raises(BadJson, match='synthetic upstream error'): + b2_http.request(responses.GET, self.URL, {}, try_count=2) + assert len(responses.calls) == 1 + mock_time.assert_not_called() + + @responses.activate + def test_invalid_utf8_error_body_still_retries_service_failure( + self, b2_http: B2Http, mock_time: MagicMock + ): + responses.get(self.URL, status=503, body=b'upstream failure: \xff') + responses.get(self.URL, json={'recovered': True}) + + result = b2_http.request(responses.GET, self.URL, {}, try_count=2) + + assert result.json() == {'recovered': True} + assert len(responses.calls) == 2 + mock_time.assert_called_once_with(1.0) + + @pytest.mark.parametrize('try_count', [0, -1]) + @responses.activate + def test_invalid_attempt_budget_never_sends_request( + self, b2_http: B2Http, mock_time: MagicMock, try_count + ): + responses.get(self.URL, json={'unexpected': True}) + + with pytest.raises(ValueError, match='try_count must be >= 1'): + b2_http.request(responses.GET, self.URL, {}, try_count=try_count) + + assert len(responses.calls) == 0 + mock_time.assert_not_called() + + @responses.activate + def test_backoff_is_bounded_and_exhaustion_preserves_last_error( + self, b2_http: B2Http, mock_time: MagicMock, mocker: MockerFixture + ): + attempts = [] + + def fail_request(request): + attempts.append(request.url) + return ( + 503, + {'Content-Type': 'application/json'}, + '{"status": 503, "code": "server_busy", "message": "attempt %d"}' % len(attempts), + ) + + responses.add_callback(responses.GET, self.URL, callback=fail_request) + mocker.patch('b2sdk._internal.b2http.random', return_value=0.25) + + with pytest.raises(ServiceError, match='attempt 14'): + b2_http.request(responses.GET, self.URL, {}, try_count=14) + + delays = [args.args[0] for args in mock_time.call_args_list] + assert len(attempts) == len(responses.calls) == 14 + assert len(delays) == 13 # No sleep after the final failed attempt. + assert delays[:3] == [1.0, 1.5, 2.25] + assert all(0 < delay <= 65 for delay in delays) + assert delays[-2:] == [64.25, 64.25] + @responses.activate def test_never_works(self, b2_http: B2Http, mock_time: MagicMock): _mock_error_response(self.URL, status=503) diff --git a/test/unit/utils/test_range_.py b/test/unit/utils/test_range_.py index 5ff3c2d57..a958040df 100644 --- a/test/unit/utils/test_range_.py +++ b/test/unit/utils/test_range_.py @@ -79,3 +79,9 @@ def test_range_repr(apiver_module): def test_empty_range(apiver_module): r = apiver_module.EMPTY_RANGE assert r.size() == 0 + + +@pytest.mark.parametrize('header', ['garbage', 'items=0-11', 'bytes=5-x', 'bytes=0-11junk']) +def test_malformed_range_header_is_rejected(apiver_module, header): + with pytest.raises(ValueError, match='Invalid range header:'): + apiver_module.Range.from_header_with_size(header) From 22ada338615a3cb52f091b3ac1cc45cbec800e93 Mon Sep 17 00:00:00 2001 From: Sophie <49928680+sophiecarreras@users.noreply.github.com> Date: Tue, 24 Nov 2026 00:11:14 -0300 Subject: [PATCH 064/113] test: cover response streaming and simulator authorization helpers (#729) --- ...eaming_boundary_coverage.infrastructure.md | 1 + test/unit/b2http/test_b2http.py | 71 +++++++++++++++++ test/unit/test_testing_api_helpers.py | 79 +++++++++++++++++++ 3 files changed, 151 insertions(+) create mode 100644 changelog.d/+streaming_boundary_coverage.infrastructure.md create mode 100644 test/unit/test_testing_api_helpers.py diff --git a/changelog.d/+streaming_boundary_coverage.infrastructure.md b/changelog.d/+streaming_boundary_coverage.infrastructure.md new file mode 100644 index 000000000..8a034c7a8 --- /dev/null +++ b/changelog.d/+streaming_boundary_coverage.infrastructure.md @@ -0,0 +1 @@ +Add shared unit tests for streaming response failures, encoded bytes, Unicode decoding, consumed streams, and simulator-only authorization helpers. diff --git a/test/unit/b2http/test_b2http.py b/test/unit/b2http/test_b2http.py index 15a32e553..7d7d432de 100644 --- a/test/unit/b2http/test_b2http.py +++ b/test/unit/b2http/test_b2http.py @@ -9,6 +9,8 @@ from __future__ import annotations import datetime +import gzip +import io import locale import sys from unittest.mock import MagicMock, call @@ -35,8 +37,11 @@ ) from pytest_mock import MockerFixture from responses import matchers +from urllib3.exceptions import DecodeError, ProtocolError, ReadTimeoutError +from urllib3.response import HTTPResponse from b2sdk._internal.b2http import setlocale +from b2sdk._internal.requests import NotDecompressingResponse from ..test_base import TestBase @@ -665,3 +670,69 @@ def test_negative_skew(self): response.headers = {'Date': now_str} with self.assertRaises(ClockSkew): ClockSkewHook().post_request('POST', 'http://example.com', {}, response) + + +class TestStreamingResponse: + @responses.activate + def test_http_download_preserves_gzip_bytes(self, b2_http): + original = b'encoded file bytes must remain intact' * 20 + encoded = gzip.compress(original, mtime=0) + url = 'https://download.example.invalid/encoded-file' + responses.get(url, body=encoded, headers={'Content-Encoding': 'gzip'}) + + with b2_http.get_content(url, {}, try_count=1) as response: + chunks = list(response.iter_content(chunk_size=7)) + + assert b''.join(chunks) == encoded + assert all(0 < len(chunk) <= 7 for chunk in chunks) + assert len(responses.calls) == 1 + + @pytest.mark.parametrize( + 'raw_error, expected_error', + [ + (ProtocolError('interrupted stream'), requests.exceptions.ChunkedEncodingError), + (DecodeError('invalid encoded data'), requests.exceptions.ContentDecodingError), + (ReadTimeoutError(None, '/synthetic', 'read timed out'), requests.ConnectionError), + ], + ) + def test_stream_error_keeps_partial_data_and_requests_exception( + self, raw_error, expected_error + ): + calls = [] + + class FailingRawStream: + def stream(self, chunk_size, decode_content): + calls.append((chunk_size, decode_content)) + yield b'ok' + raise raw_error + + # This internal response component is shared and is not exported by apiver_deps. + response = NotDecompressingResponse() + response.raw = FailingRawStream() + chunks = response.iter_content(chunk_size=2) + + assert next(chunks) == b'ok' + with pytest.raises(expected_error) as caught: + next(chunks) + + assert caught.value.args[0] is raw_error + assert calls == [(2, False)] + + def test_unicode_decoding_handles_split_multibyte_characters(self): + text = 'a snowman: \u2603; coffee: \u2615' + response = NotDecompressingResponse() + response.encoding = 'utf-8' + response.raw = HTTPResponse(body=io.BytesIO(text.encode()), preload_content=False) + + chunks = list(response.iter_content(chunk_size=2, decode_unicode=True)) + + assert ''.join(chunks) == text + assert all(isinstance(chunk, str) for chunk in chunks) + + def test_consumed_stream_cannot_be_read_again(self): + response = NotDecompressingResponse() + response.raw = HTTPResponse(body=io.BytesIO(b'abcd'), preload_content=False) + + assert list(response.iter_content(chunk_size=2)) == [b'ab', b'cd'] + with pytest.raises(requests.exceptions.StreamConsumedError): + list(response.iter_content(chunk_size=2)) diff --git a/test/unit/test_testing_api_helpers.py b/test/unit/test_testing_api_helpers.py new file mode 100644 index 000000000..b4393a3d5 --- /dev/null +++ b/test/unit/test_testing_api_helpers.py @@ -0,0 +1,79 @@ +###################################################################### +# +# File: test/unit/test_testing_api_helpers.py +# +# Copyright 2026 Backblaze Inc. All Rights Reserved. +# +# License https://www.backblaze.com/using_b2_code.html +# +###################################################################### +"""Test live-test setup helpers against the simulator, with HTTP forbidden.""" + +from __future__ import annotations + +import pytest + +from b2sdk._internal.api_config import B2HttpApiConfig +from b2sdk._internal.exception import InvalidAuthToken +from b2sdk._internal.raw_simulator import RawSimulator +from b2sdk._internal.testing.helpers.api import authorize, get_b2_auth_data, get_realm + + +@pytest.fixture +def simulator_config(mocker): + blocked_http = mocker.patch( + 'requests.sessions.Session.request', + side_effect=AssertionError('HTTP is forbidden in this test'), + ) + simulator = RawSimulator() + config = B2HttpApiConfig(install_clock_skew_hook=False, _raw_api_class=lambda http: simulator) + yield simulator, config + blocked_http.assert_not_called() + + +def test_authorize_populates_returned_in_memory_account_info(simulator_config): + simulator, config = simulator_config + key_id, key = simulator.create_account() + + api, info = authorize((key_id, key), 'production', config) + + assert api.account_info is info + assert api.session.raw_api is simulator + assert api.api_config is config + assert info.get_account_id() == key_id + assert info.get_application_key_id() == key_id + assert info.get_account_auth_token() == simulator.current_token + assert info.get_api_url() == simulator.API_URL + + +def test_authorize_propagates_invalid_credentials_without_creating_token(simulator_config): + simulator, config = simulator_config + key_id, _ = simulator.create_account() + + with pytest.raises(InvalidAuthToken, match='secret key is wrong'): + authorize((key_id, 'incorrect-synthetic-key'), 'production', config) + + assert simulator.auth_token_to_key == {} + + +@pytest.mark.parametrize('missing_id', [True, False]) +def test_missing_environment_credentials_fail_explicitly(monkeypatch, simulator_config, missing_id): + monkeypatch.delenv('B2_TEST_APPLICATION_KEY_ID', raising=False) + monkeypatch.delenv('B2_TEST_APPLICATION_KEY', raising=False) + if not missing_id: + monkeypatch.setenv('B2_TEST_APPLICATION_KEY_ID', 'synthetic-id') + missing = 'B2_TEST_APPLICATION_KEY_ID' if missing_id else 'B2_TEST_APPLICATION_KEY' + + with pytest.raises(ValueError, match=f'{missing} is not set'): + get_b2_auth_data() + + +def test_environment_values_and_realm_are_explicit(monkeypatch, simulator_config): + monkeypatch.setenv('B2_TEST_APPLICATION_KEY_ID', 'synthetic-id') + monkeypatch.setenv('B2_TEST_APPLICATION_KEY', 'synthetic-key') + monkeypatch.delenv('B2_TEST_ENVIRONMENT', raising=False) + + assert get_b2_auth_data() == ('synthetic-id', 'synthetic-key') + assert get_realm() == 'production' + monkeypatch.setenv('B2_TEST_ENVIRONMENT', 'synthetic-realm') + assert get_realm() == 'synthetic-realm' From 45be352b80093bdf0d4c1b4666d0ef77b6d3318c Mon Sep 17 00:00:00 2001 From: Sophie <49928680+sophiecarreras@users.noreply.github.com> Date: Tue, 24 Nov 2026 16:33:29 -0300 Subject: [PATCH 065/113] Fix sync folder prefix scans and executor shutdown (#730) --- b2sdk/_internal/scan/folder.py | 2 +- b2sdk/_internal/sync/sync.py | 65 ++++++++++--------- .../+sync-folder-prefix-and-shutdown.fixed.md | 1 + test/unit/bucket/test_regression_bucket.py | 31 +++------ test/unit/scan/test_folder.py | 31 +++++++++ test/unit/sync/test_sync.py | 64 +++++++++++++++--- 6 files changed, 133 insertions(+), 61 deletions(-) create mode 100644 changelog.d/+sync-folder-prefix-and-shutdown.fixed.md diff --git a/b2sdk/_internal/scan/folder.py b/b2sdk/_internal/scan/folder.py index c8260ea86..07fb82178 100644 --- a/b2sdk/_internal/scan/folder.py +++ b/b2sdk/_internal/scan/folder.py @@ -418,7 +418,7 @@ def all_files( def get_file_versions(self): for file_version, _ in self.bucket.ls( - self.folder_name, + self.prefix, latest_only=False, recursive=True, ): diff --git a/b2sdk/_internal/sync/sync.py b/b2sdk/_internal/sync/sync.py index 252f40dd7..f4485c4fa 100644 --- a/b2sdk/_internal/sync/sync.py +++ b/b2sdk/_internal/sync/sync.py @@ -173,6 +173,9 @@ def sync_folders( source is also in the destination. Deletes any file versions in the destination older than history_days. + If scheduling fails, wait for already submitted actions to finish before + propagating the scheduling error. + :param source_folder: source folder object :param dest_folder: destination folder object :param now_millis: current time in milliseconds @@ -203,37 +206,39 @@ def sync_folders( queue_limit = self.max_workers + 1000 sync_executor = BoundedQueueExecutor(unbounded_executor, queue_limit=queue_limit) - if reporter is None: - # silent reporter so that downstream code can call it unconditionally - reporter = SyncReport(io.StringIO(), True) - - if source_type == 'local': - # Start the thread that counts the local files. That's the operation - # that should be fastest, and it provides scale for the progress reporting. - sync_executor.submit(count_files, source_folder, reporter, self.policies_manager) - - # Bucket for scheduling actions. - # For bucket-to-bucket sync, the bucket for the API calls should be the destination. - action_bucket = None - if dest_type == 'b2': - action_bucket = cast(B2Folder, dest_folder).bucket - elif source_type == 'b2': - action_bucket = cast(B2Folder, source_folder).bucket - - # Schedule each of the actions. - for action in self._make_folder_sync_actions( - source_folder, - dest_folder, - now_millis, - reporter, - self.policies_manager, - encryption_settings_provider, - ): - logging.debug('scheduling action %s on bucket %s', action, action_bucket) - sync_executor.submit(action.run, action_bucket, reporter, self.dry_run) + try: + if reporter is None: + # silent reporter so that downstream code can call it unconditionally + reporter = SyncReport(io.StringIO(), True) + + if source_type == 'local': + # Start the thread that counts the local files. That's the operation + # that should be fastest, and it provides scale for the progress reporting. + sync_executor.submit(count_files, source_folder, reporter, self.policies_manager) + + # Bucket for scheduling actions. + # For bucket-to-bucket sync, the bucket for the API calls should be the destination. + action_bucket = None + if dest_type == 'b2': + action_bucket = cast(B2Folder, dest_folder).bucket + elif source_type == 'b2': + action_bucket = cast(B2Folder, source_folder).bucket + + # Schedule each of the actions. + for action in self._make_folder_sync_actions( + source_folder, + dest_folder, + now_millis, + reporter, + self.policies_manager, + encryption_settings_provider, + ): + logging.debug('scheduling action %s on bucket %s', action, action_bucket) + sync_executor.submit(action.run, action_bucket, reporter, self.dry_run) - # Wait for everything to finish - sync_executor.shutdown() + finally: + # Drain queued actions before returning, including when scheduling fails. + sync_executor.shutdown() if sync_executor.get_num_exceptions() != 0: raise IncompleteSync('sync is incomplete') diff --git a/changelog.d/+sync-folder-prefix-and-shutdown.fixed.md b/changelog.d/+sync-folder-prefix-and-shutdown.fixed.md new file mode 100644 index 000000000..6f6d1b2fc --- /dev/null +++ b/changelog.d/+sync-folder-prefix-and-shutdown.fixed.md @@ -0,0 +1 @@ +Fix folder scans when an object has the same name as the source folder, preserving exact-object listing behavior. Ensure sync waits for queued actions to finish before returning a scheduling error. diff --git a/test/unit/bucket/test_regression_bucket.py b/test/unit/bucket/test_regression_bucket.py index 98a0b55c0..72e6c1417 100644 --- a/test/unit/bucket/test_regression_bucket.py +++ b/test/unit/bucket/test_regression_bucket.py @@ -32,6 +32,7 @@ from apiver_deps import ( AuthInfoCache, B2Api, + B2Folder, B2Http, B2HttpApiConfig, B2RawHTTPApi, @@ -45,7 +46,7 @@ ) from apiver_deps_exception import NonExistentBucket -from test.known_defect import expect, known_defect +from test.known_defect import expect from .test_bucket import TestCaseWithBucket @@ -66,33 +67,19 @@ def test_c1_copy_with_expiry_but_no_content_type(self): assert copied.file_info['b2-expires'] == 'Thu, 01 Dec 2050 16:00:00 GMT', copied.file_info assert copied.file_info['b2-content-disposition'] == 'attachment', copied.file_info - @known_defect( - 'C5', - 'ls("x") stops at an object named "x" and never lists "x/..."', - condition=apiver_deps.V >= 3, - raises=AssertionError, - ) - def test_c5_ls_path_without_slash_lists_folder_next_to_same_named_file(self): - """C5: ls('x') with an object 'x' and objects 'x/...' must also list 'x/...'.""" + def test_listing_distinguishes_exact_object_from_explicit_folder(self): self.bucket.upload_bytes(b'data', 'x') self.bucket.upload_bytes(b'data', 'x/1.txt') names = [fv.file_name for fv, _ in self.bucket.ls('x', recursive=True)] - assert 'x/1.txt' in names, names - - @known_defect( - 'C5', - 'B2Folder for a prefix naming a single object hits an AssertionError', - condition=apiver_deps.V >= 3, - raises=AssertionError, - ) - def test_c5_folder_sync_source_with_prefix_naming_a_single_object(self): - """C5: B2Folder for 'b2://bucket/x' must not hit an AssertionError when only 'x' exists.""" - from apiver_deps import B2Folder + # v3 prefers an exact object; older interfaces default to folders. + expected = ['x'] if apiver_deps.V >= 3 else ['x/1.txt'] + assert names == expected + assert [fv.file_name for fv, _ in self.bucket.ls('x/', recursive=True)] == ['x/1.txt'] + def test_folder_prefix_matching_single_object_is_empty(self): self.bucket.upload_bytes(b'data', 'x') folder = B2Folder(self.bucket_name, 'x', self.api) - # must not raise AssertionError (it may list nothing or the object, but not crash) - list(folder.all_files(None)) + assert list(folder.all_files(None)) == [] def test_c6_exact_filename_respects_exclude_filter(self): """C6: an exclude filter naming the exact file must hide it from ls().""" diff --git a/test/unit/scan/test_folder.py b/test/unit/scan/test_folder.py index 03868ba5b..ae1619e6b 100644 --- a/test/unit/scan/test_folder.py +++ b/test/unit/scan/test_folder.py @@ -14,6 +14,7 @@ from pathlib import Path import pytest +from apiver_deps import B2Folder from b2sdk._internal.scan.exception import UnsupportedFilename from b2sdk._internal.scan.folder import LocalFolder @@ -84,3 +85,33 @@ def test_make_full_path_accepts_internal_link_and_symlinked_root(tmp_path): # does not normalize away the Windows extended-length prefix. assert os.path.basename(result) == os.path.basename(expected) == 'new-file.txt' assert os.path.samefile(os.path.dirname(result), os.path.dirname(expected)) + + +@pytest.mark.parametrize('folder_name', ['x', 'x/']) +@pytest.mark.parametrize('children', [(), ('a.txt', 'nested/b.txt')]) +def test_b2_folder_uses_directory_prefix_with_same_named_object( + bucket, b2api, folder_name, children +): + bucket.upload_bytes(b'object', 'x') + bucket.upload_bytes(b'neighbor', 'xx/not-a-child.txt') + for name in children: + bucket.upload_bytes(b'child', 'x/' + name) + + folder = B2Folder(bucket.name, folder_name, b2api) + paths = list(folder.all_files(None)) + + assert [path.relative_path for path in paths] == list(children) + + +@pytest.mark.parametrize('folder_name', ['x', 'x/']) +def test_b2_folder_retains_child_version_history(bucket, b2api, folder_name): + bucket.upload_bytes(b'object', 'x') + first = bucket.upload_bytes(b'first', 'x/a.txt') + second = bucket.upload_bytes(b'second', 'x/a.txt') + bucket.hide_file('x/a.txt') + + paths = list(B2Folder(bucket.name, folder_name, b2api).all_files(None)) + + assert [path.relative_path for path in paths] == ['a.txt'] + assert [version.action for version in paths[0].all_versions] == ['hide', 'upload', 'upload'] + assert [version.id_ for version in paths[0].all_versions[1:]] == [second.id_, first.id_] diff --git a/test/unit/sync/test_sync.py b/test/unit/sync/test_sync.py index ccb4692df..78458731d 100644 --- a/test/unit/sync/test_sync.py +++ b/test/unit/sync/test_sync.py @@ -13,6 +13,7 @@ from contextlib import ExitStack from enum import Enum from functools import partial +from threading import Event, Thread from unittest import mock import pytest @@ -1027,14 +1028,6 @@ def test_sync_folders_without_reporter(self, synchronizer_factory, src_type, dst synchronizer.sync_folders(src, dst, TODAY, None) - @pytest.mark.xfail( - strict=True, - reason=( - 'known bug (review b2-sdk-python prod:7, sync.py:201, owner decides): the executor ' - 'is not shut down when scheduling raises, so queued actions keep running in ' - 'the background; whether to wait for or cancel them is not decided' - ), - ) def test_sync_folders_shuts_executor_down_when_scheduling_fails(self, synchronizer_factory): synchronizer = synchronizer_factory(dry_run=True, allow_empty_source=True) src = self.folder_factory('b2', ('a.txt', [200], 10)) @@ -1061,6 +1054,61 @@ def spy(*args, **kwargs): assert len(executors) == 1 executors[0].shutdown.assert_called_once() + def test_sync_folders_waits_for_queued_actions_before_scheduling_error( + self, synchronizer_factory + ): + synchronizer = synchronizer_factory(dry_run=True, allow_empty_source=True) + src = self.folder_factory('b2', ('a.txt', [200], 10)) + dst = self.folder_factory('local') + first_started, release_first, shutdown_started = Event(), Event(), Event() + completed, observed_errors, completed_when_error_returned = [], [], [] + scheduling_error = RuntimeError('scheduling failed') + + def first_action(*args): + first_started.set() + assert release_first.wait(timeout=5), 'first action was not released' + completed.append('first') + + def second_action(*args): + completed.append('second') + + def failing_actions(*args, **kwargs): + yield mock.Mock(run=first_action) + assert first_started.wait(timeout=5), 'first action did not start' + yield mock.Mock(run=second_action) + raise scheduling_error + + real_shutdown = sync_module.BoundedQueueExecutor.shutdown + + def shutdown(executor): + shutdown_started.set() + real_shutdown(executor) + + def sync(): + try: + synchronizer.sync_folders(src, dst, TODAY, None) + except BaseException as exc: + completed_when_error_returned.extend(completed) + observed_errors.append(exc) + + with mock.patch.object(synchronizer, '_make_folder_sync_actions', failing_actions): + with mock.patch.object(sync_module.BoundedQueueExecutor, 'shutdown', shutdown): + thread = Thread(target=sync, daemon=True) + thread.start() + try: + assert first_started.wait(timeout=5), 'first action did not start' + assert shutdown_started.wait(timeout=5), 'executor was not shut down' + assert thread.is_alive(), 'sync returned while its first action was blocked' + assert completed == [] + finally: + release_first.set() + thread.join(timeout=5) + + assert not thread.is_alive(), 'sync did not finish' + assert completed == ['first', 'second'] + assert completed_when_error_returned == ['first', 'second'] + assert observed_errors == [scheduling_error] + class TstEncryptionSettingsProvider(AbstractSyncEncryptionSettingsProvider): def __init__(self, source_encryption_setting, destination_encryption_setting): From 075ec999b1dec01681e25de0461bfe1021f60488 Mon Sep 17 00:00:00 2001 From: Felipe Fumero Date: Tue, 24 Nov 2026 16:08:48 -0600 Subject: [PATCH 066/113] Reject explicit resume when encryption, retention or legal hold differ (#733) * fix: validate settings before explicit upload continuation * Only reject explicitly requested resume protections that differ Address panel review: omitting file_retention or legal_hold means the caller did not request one, not that it is NONE/UNSET, so -- as with encryption -- it is no longer coerced to a default and compared. This avoids rejecting a resume that relies on, for example, the bucket's default retention. Explicit mismatches are still rejected. --- b2sdk/_internal/transfer/emerge/executor.py | 17 ++ changelog.d/+resume-settings.fixed.md | 1 + .../test_explicit_resume_protections.py | 167 ++++++++++++++++++ 3 files changed, 185 insertions(+) create mode 100644 changelog.d/+resume-settings.fixed.md create mode 100644 test/unit/internal/test_explicit_resume_protections.py diff --git a/b2sdk/_internal/transfer/emerge/executor.py b/b2sdk/_internal/transfer/emerge/executor.py index 35369bed3..5ec12a94d 100644 --- a/b2sdk/_internal/transfer/emerge/executor.py +++ b/b2sdk/_internal/transfer/emerge/executor.py @@ -316,6 +316,23 @@ def _get_unfinished_file_and_parts( raise ValueError( 'Cannot manually resume unfinished large file with different file_info' ) + if encryption is not None and encryption != unfinished_file.encryption: + raise ValueError( + 'Cannot manually resume unfinished large file with different encryption' + ) + # Only an explicitly requested protection can conflict. An omitted + # file_retention or legal_hold means the caller did not request one (not that + # it is NONE/UNSET), so -- as with encryption above -- it is left uncompared + # rather than assuming a default and rejecting a resume that relies on, for + # example, the bucket's default retention. + if file_retention is not None and file_retention != unfinished_file.file_retention: + raise ValueError( + 'Cannot manually resume unfinished large file with different file_retention' + ) + if legal_hold is not None and legal_hold != unfinished_file.legal_hold: + raise ValueError( + 'Cannot manually resume unfinished large file with different legal_hold' + ) finished_parts = { part.part_number: part for part in self.services.large_file.list_parts(continue_large_file_id) diff --git a/changelog.d/+resume-settings.fixed.md b/changelog.d/+resume-settings.fixed.md new file mode 100644 index 000000000..f958cd6cb --- /dev/null +++ b/changelog.d/+resume-settings.fixed.md @@ -0,0 +1 @@ +Reject manually continuing an unfinished large file when an explicitly requested encryption, retention, or legal-hold setting differs from the unfinished file. Omitted settings are not compared. diff --git a/test/unit/internal/test_explicit_resume_protections.py b/test/unit/internal/test_explicit_resume_protections.py new file mode 100644 index 000000000..3e79466b8 --- /dev/null +++ b/test/unit/internal/test_explicit_resume_protections.py @@ -0,0 +1,167 @@ +###################################################################### +# +# File: test/unit/internal/test_explicit_resume_protections.py +# +# Copyright 2026 Backblaze Inc. All Rights Reserved. +# +# License https://www.backblaze.com/using_b2_code.html +# +###################################################################### +import hashlib +import io +from unittest import mock + +import pytest + +from b2sdk.v3 import ( + NO_RETENTION_FILE_SETTING, + SSE_B2_AES, + EncryptionAlgorithm, + EncryptionKey, + EncryptionMode, + EncryptionSetting, + FileRetentionSetting, + LegalHold, + RetentionMode, + UploadSourceBytes, + WriteIntent, +) + +RETENTION = FileRetentionSetting(RetentionMode.COMPLIANCE, 4102444800000) +SSE_C = EncryptionSetting( + EncryptionMode.SSE_C, EncryptionAlgorithm.AES256, EncryptionKey(b'x' * 32, None) +) + + +@pytest.fixture +def prepared_resume(b2api): + bucket = b2api.create_bucket('resume-bucket', 'allPrivate', is_file_lock_enabled=True) + data = b'a' * 600 + + def prepare(encryption=SSE_B2_AES, retention=None, hold=None): + unfinished = b2api.session.start_large_file( + bucket.id_, + 'destination', + 'application/octet-stream', + {'large_file_sha1': hashlib.sha1(data).hexdigest()}, + server_side_encryption=encryption, + file_retention=retention, + legal_hold=hold, + ) + for number in range(1, 4): + part = data[(number - 1) * 200 : number * 200] + b2api.session.upload_part( + unfinished['fileId'], + number, + len(part), + hashlib.sha1(part).hexdigest(), + io.BytesIO(part), + server_side_encryption=encryption, + ) + return bucket, data, unfinished['fileId'] + + return prepare + + +@pytest.mark.parametrize( + 'requested,existing,field', + [ + ({'encryption': SSE_C}, {}, 'encryption'), + ({'file_retention': RETENTION}, {}, 'file_retention'), + ({'legal_hold': LegalHold.ON}, {}, 'legal_hold'), + ( + {'encryption': SSE_C, 'file_retention': RETENTION, 'legal_hold': LegalHold.ON}, + {}, + 'encryption', + ), + ({'legal_hold': LegalHold.OFF}, {}, 'legal_hold'), + ], + ids=[ + 'encryption', + 'retention', + 'hold', + 'combined', + 'off-vs-unset', + ], +) +def test_explicit_resume_rejects_incompatible_protections( + prepared_resume, requested, existing, field +): + bucket, data, file_id = prepared_resume(**existing) + session = bucket.api.session + with mock.patch.object(session, 'finish_large_file', wraps=session.finish_large_file) as finish: + with pytest.raises(ValueError, match=field): + bucket.create_file( + [WriteIntent(UploadSourceBytes(data))], + 'destination', + continue_large_file_id=file_id, + max_part_size=200, + **requested, + ) + finish.assert_not_called() + remaining = list(bucket.list_unfinished_large_files()) + assert [item.file_id for item in remaining] == [file_id] + assert len(list(bucket.api.services.large_file.list_parts(file_id))) == 3 + + +@pytest.mark.parametrize( + 'retention,hold', + [(None, None), (NO_RETENTION_FILE_SETTING, LegalHold.UNSET), (RETENTION, LegalHold.ON)], +) +def test_explicit_resume_accepts_matching_protections(prepared_resume, retention, hold): + bucket, data, file_id = prepared_resume(retention=retention, hold=hold) + result = bucket.create_file( + [WriteIntent(UploadSourceBytes(data))], + 'destination', + continue_large_file_id=file_id, + max_part_size=200, + encryption=SSE_B2_AES, + file_retention=retention, + legal_hold=hold, + ) + assert result.id_ == file_id + assert result.server_side_encryption == SSE_B2_AES + assert result.file_retention == (retention or NO_RETENTION_FILE_SETTING) + assert result.legal_hold == (hold or LegalHold.UNSET) + + +@pytest.mark.parametrize( + 'existing', + [{'retention': RETENTION}, {'hold': LegalHold.ON}], + ids=['omitted-retention', 'omitted-hold'], +) +def test_explicit_resume_allows_omitted_protections(prepared_resume, existing): + # Omitting file_retention / legal_hold is "not requested", not a conflicting NONE/UNSET, + # so the resume is allowed and the unfinished file keeps its existing protection. + bucket, data, file_id = prepared_resume(**existing) + result = bucket.create_file( + [WriteIntent(UploadSourceBytes(data))], + 'destination', + continue_large_file_id=file_id, + max_part_size=200, + ) + assert result.id_ == file_id + + +@pytest.mark.parametrize( + 'field,unknown,requested', + [ + ('file_retention', FileRetentionSetting(RetentionMode.UNKNOWN), RETENTION), + ('legal_hold', LegalHold.UNKNOWN, LegalHold.ON), + ], +) +def test_explicit_resume_rejects_unreadable_protections(prepared_resume, field, unknown, requested): + bucket, data, file_id = prepared_resume() + manager = bucket.api.services.large_file + unfinished = manager.get_unfinished_large_file(bucket.id_, file_id) + setattr(unfinished, field, unknown) + with mock.patch.object(manager, 'get_unfinished_large_file', return_value=unfinished): + with pytest.raises(ValueError, match=field): + bucket.create_file( + [WriteIntent(UploadSourceBytes(data))], + 'destination', + continue_large_file_id=file_id, + max_part_size=200, + **{field: requested}, + ) + assert [item.file_id for item in bucket.list_unfinished_large_files()] == [file_id] From fac61cd665184a0b7351ae6192efe9b73a6664ac Mon Sep 17 00:00:00 2001 From: Sophie <49928680+sophiecarreras@users.noreply.github.com> Date: Tue, 24 Nov 2026 19:14:23 -0300 Subject: [PATCH 067/113] Cover request and Object Lock boundaries; fix encoded SSE-C key IDs (#734) * Test request and Object Lock contracts; fix SSE-C key IDs * Cover remaining optional request and notification branches --- b2sdk/_internal/encryption/setting.py | 7 +- .../+request-encryption-retention.fixed.md | 1 + test/unit/test_encryption_settings.py | 254 ++++++ test/unit/test_file_lock_settings.py | 236 +++++ test/unit/test_raw_api_requests.py | 839 ++++++++++++++++++ 5 files changed, 1336 insertions(+), 1 deletion(-) create mode 100644 changelog.d/+request-encryption-retention.fixed.md create mode 100644 test/unit/test_encryption_settings.py create mode 100644 test/unit/test_file_lock_settings.py create mode 100644 test/unit/test_raw_api_requests.py diff --git a/b2sdk/_internal/encryption/setting.py b/b2sdk/_internal/encryption/setting.py index 31506cbf4..fa861c51d 100644 --- a/b2sdk/_internal/encryption/setting.py +++ b/b2sdk/_internal/encryption/setting.py @@ -186,7 +186,12 @@ def add_to_upload_headers(self, headers): self._add_sse_c_headers(headers) if self.key.key_id is not None: header = SSE_C_KEY_ID_HEADER - if headers.get(header) is not None and headers[header] != self.key.key_id: + # File-info headers are percent-encoded; compare decoded identities. + header_key_id = headers.get(header) + if ( + header_key_id is not None + and urllib.parse.unquote(header_key_id) != self.key.key_id + ): raise ValueError( f'Ambiguous key id set: "{headers[header]}" in headers and "{self.key.key_id}" in {self.__class__.__name__}' ) diff --git a/changelog.d/+request-encryption-retention.fixed.md b/changelog.d/+request-encryption-retention.fixed.md new file mode 100644 index 000000000..67b334d3b --- /dev/null +++ b/changelog.d/+request-encryption-retention.fixed.md @@ -0,0 +1 @@ +Accept matching percent-encoded SSE-C key identifiers in upload metadata without double encoding, while rejecting conflicting identifiers. Add request, encryption and Object Lock unit tests across the supported SDK interfaces. diff --git a/test/unit/test_encryption_settings.py b/test/unit/test_encryption_settings.py new file mode 100644 index 000000000..42a088a08 --- /dev/null +++ b/test/unit/test_encryption_settings.py @@ -0,0 +1,254 @@ +###################################################################### +# +# File: test/unit/test_encryption_settings.py +# +# Copyright 2026 Backblaze Inc. All Rights Reserved. +# +# License https://www.backblaze.com/using_b2_code.html +# +###################################################################### +"""Encryption state and wire-format contracts using public, synthetic key material. + +Reference: https://www.backblaze.com/docs/cloud-storage-server-side-encryption-with-the-native-api +""" + +from __future__ import annotations + +import pytest +from apiver_deps import ( + UNKNOWN_KEY_ID, + EncryptionAlgorithm, + EncryptionKey, + EncryptionMode, + EncryptionSetting, + EncryptionSettingFactory, +) + +KEY = bytes(range(32)) +KEY_B64 = 'AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8=' +KEY_MD5 = 'tP/LI3N87DFaSk0aoqYgzg==' +CUSTOMER_HEADERS = { + 'X-Bz-Server-Side-Encryption-Customer-Algorithm': 'AES256', + 'X-Bz-Server-Side-Encryption-Customer-Key': KEY_B64, + 'X-Bz-Server-Side-Encryption-Customer-Key-Md5': KEY_MD5, +} + + +def customer_setting(key_id='key id+Δ', secret=KEY): + return EncryptionSetting( + EncryptionMode.SSE_C, EncryptionAlgorithm.AES256, EncryptionKey(secret, key_id) + ) + + +@pytest.mark.parametrize( + 'kwargs', + [ + {'mode': EncryptionMode.NONE, 'algorithm': EncryptionAlgorithm.AES256}, + {'mode': EncryptionMode.NONE, 'key': EncryptionKey(KEY, None)}, + {'mode': EncryptionMode.SSE_B2}, + {'mode': EncryptionMode.SSE_C}, + {'mode': EncryptionMode.SSE_C, 'algorithm': EncryptionAlgorithm.AES256}, + ], +) +def test_encryption_constructor_rejects_incomplete_or_conflicting_settings(kwargs): + with pytest.raises(ValueError): + EncryptionSetting(**kwargs) + + +@pytest.mark.parametrize('key_id', [None, UNKNOWN_KEY_ID, 'public-id']) +def test_key_representation_never_discloses_secret(key_id): + key = EncryptionKey(KEY, key_id) + text = repr(key) + assert str(KEY) not in text + assert KEY_B64 not in text + assert KEY_MD5 not in text + assert '******' in text + if key_id is UNKNOWN_KEY_ID: + assert 'unknown' in text + + +def test_server_key_metadata_has_no_usable_secret(): + key = EncryptionKey(None, UNKNOWN_KEY_ID) + assert key.as_dict() == {'customerKey': '******', 'customerKeyMd5': '******'} + assert 'None' in repr(key) + assert 'unknown' in repr(key) + + +@pytest.mark.parametrize('key_id', [None, 'public-id']) +def test_customer_key_serialization_uses_known_base64_vectors(key_id): + setting = customer_setting(key_id) + assert setting.serialize_to_json_for_request() == { + 'mode': 'SSE-C', + 'algorithm': 'AES256', + 'customerKey': KEY_B64, + 'customerKeyMd5': KEY_MD5, + } + assert setting.key.key_b64() == KEY_B64 + assert setting.key.key_md5() == KEY_MD5 + + +@pytest.mark.parametrize('operation', ['serialize_to_json_for_request', 'add_to_download_headers']) +def test_unknown_customer_secret_cannot_be_used_in_a_request(operation): + setting = customer_setting(secret=None) + with pytest.raises(ValueError, match='unknown key'): + if operation == 'serialize_to_json_for_request': + setting.serialize_to_json_for_request() + else: + setting.add_to_download_headers({}) + + +@pytest.mark.parametrize('direction', ['upload', 'download']) +@pytest.mark.parametrize('mode', [EncryptionMode.SSE_B2, EncryptionMode.SSE_C]) +def test_encryption_headers_preserve_existing_headers(direction, mode): + setting = ( + customer_setting() + if mode == EncryptionMode.SSE_C + else EncryptionSetting(mode, EncryptionAlgorithm.AES256) + ) + headers = {'Authorization': 'synthetic-token'} + getattr(setting, f'add_to_{direction}_headers')(headers) + expected = {'Authorization': 'synthetic-token'} + if mode == EncryptionMode.SSE_C: + expected.update(CUSTOMER_HEADERS) + if direction == 'upload': + expected['X-Bz-Info-sse_c_key_id'] = 'key%20id%2B%CE%94' + else: + expected['X-Bz-Server-Side-Encryption'] = 'AES256' + assert headers == expected + + +def test_no_encryption_download_preserves_headers_without_adding_sse(): + headers = {'Authorization': 'synthetic-token'} + EncryptionSetting(EncryptionMode.NONE).add_to_download_headers(headers) + assert headers == {'Authorization': 'synthetic-token'} + + +@pytest.mark.parametrize('direction', ['upload', 'download']) +def test_unknown_encryption_mode_cannot_generate_headers(direction): + with pytest.raises(NotImplementedError, match='unsupported encryption setting'): + getattr(EncryptionSetting(EncryptionMode.UNKNOWN), f'add_to_{direction}_headers')({}) + + +@pytest.mark.parametrize('operation', ['add_to_upload_headers', 'add_key_id_to_file_info']) +def test_unknown_key_identity_is_rejected_for_metadata_writes(operation): + with pytest.raises(ValueError, match='unknown key id'): + getattr(customer_setting(UNKNOWN_KEY_ID), operation)({}) + + +def test_conflicting_key_identity_is_not_silently_overwritten(): + with pytest.raises(ValueError, match='Ambiguous key id'): + customer_setting('new').add_to_upload_headers({'X-Bz-Info-sse_c_key_id': 'old'}) + info = {'sse_c_key_id': 'old', 'other': 'unchanged'} + with pytest.raises(ValueError, match='Ambiguous key id'): + customer_setting('new').add_key_id_to_file_info(info) + assert info == {'sse_c_key_id': 'old', 'other': 'unchanged'} + + +@pytest.mark.parametrize('info', [None, {}, {'sse_c_key_id': 'new', 'other': 'kept'}]) +def test_key_identity_is_added_to_file_metadata(info): + expected = {**(info or {}), 'sse_c_key_id': 'new'} + assert customer_setting('new').add_key_id_to_file_info(info) == expected + + +@pytest.mark.parametrize('mode', [EncryptionMode.NONE, EncryptionMode.SSE_B2]) +def test_settings_without_customer_key_leave_file_metadata_alone(mode): + setting = ( + EncryptionSetting(mode) + if mode == EncryptionMode.NONE + else EncryptionSetting(mode, EncryptionAlgorithm.AES256) + ) + info = {'other': 'kept'} + assert setting.add_key_id_to_file_info(info) is info + assert info == {'other': 'kept'} + + +@pytest.mark.parametrize( + 'metadata,mode,algorithm,key_id', + [ + ({}, EncryptionMode.NONE, None, None), + ({'serverSideEncryption': {'mode': None}}, EncryptionMode.NONE, None, None), + ( + {'serverSideEncryption': {'mode': 'SSE-B2', 'algorithm': 'AES256'}}, + EncryptionMode.SSE_B2, + EncryptionAlgorithm.AES256, + None, + ), + ( + { + 'serverSideEncryption': {'mode': 'SSE-C', 'algorithm': 'AES256'}, + 'fileInfo': {'sse_c_key_id': 'key%20id%2B%CE%94'}, + }, + EncryptionMode.SSE_C, + EncryptionAlgorithm.AES256, + 'key id+Δ', + ), + ], +) +def test_response_metadata_preserves_encryption_state(metadata, mode, algorithm, key_id): + setting = EncryptionSettingFactory.from_file_version_dict(metadata) + assert setting.mode == mode + assert setting.algorithm == algorithm + if mode == EncryptionMode.SSE_C: + assert setting.key.secret is None + assert setting.key.key_id == key_id + else: + assert setting.key is None + + +@pytest.mark.parametrize( + 'metadata,mode', + [ + ({}, EncryptionMode.UNKNOWN), + ( + {'defaultServerSideEncryption': {'isClientAuthorizedToRead': False}}, + EncryptionMode.UNKNOWN, + ), + ( + {'defaultServerSideEncryption': {'isClientAuthorizedToRead': True, 'value': None}}, + EncryptionMode.NONE, + ), + ( + { + 'defaultServerSideEncryption': { + 'isClientAuthorizedToRead': True, + 'value': {'mode': 'SSE-B2', 'algorithm': 'AES256'}, + } + }, + EncryptionMode.SSE_B2, + ), + ], +) +def test_bucket_response_distinguishes_unreadable_from_unencrypted(metadata, mode): + assert EncryptionSettingFactory.from_bucket_dict(metadata).mode == mode + + +@pytest.mark.parametrize( + 'metadata', + [ + {'serverSideEncryption': {'mode': 'unrecognized'}}, + {'serverSideEncryption': {'mode': 'SSE-B2', 'algorithm': 'unrecognized'}}, + ], +) +def test_unrecognized_response_encryption_is_not_treated_as_plaintext(metadata): + with pytest.raises(ValueError): + EncryptionSettingFactory.from_file_version_dict(metadata) + + +@pytest.mark.parametrize( + 'key_id,existing', + [ + ('key id+Δ', 'key%20id%2B%CE%94'), + ('key id+Δ', 'key%20id%2b%ce%94'), + ('literal%20value', 'literal%2520value'), + ], +) +def test_equivalent_encoded_key_id_headers_are_accepted_without_double_encoding(key_id, existing): + headers = {'X-Bz-Info-sse_c_key_id': existing} + setting = customer_setting(key_id) + setting.add_to_upload_headers(headers) + setting.add_to_upload_headers(headers) + assert headers['X-Bz-Info-sse_c_key_id'] == ( + 'literal%2520value' if key_id == 'literal%20value' else 'key%20id%2B%CE%94' + ) + for name, value in CUSTOMER_HEADERS.items(): + assert headers[name] == value diff --git a/test/unit/test_file_lock_settings.py b/test/unit/test_file_lock_settings.py new file mode 100644 index 000000000..855052882 --- /dev/null +++ b/test/unit/test_file_lock_settings.py @@ -0,0 +1,236 @@ +###################################################################### +# +# File: test/unit/test_file_lock_settings.py +# +# Copyright 2026 Backblaze Inc. All Rights Reserved. +# +# License https://www.backblaze.com/using_b2_code.html +# +###################################################################### +"""Object Lock parsing and request contracts; no account or bucket operations. + +References: https://www.backblaze.com/apidocs/b2-upload-file +https://www.backblaze.com/apidocs/b2-update-file-retention +""" + +from __future__ import annotations + +import pytest +from apiver_deps import ( + BucketRetentionSetting, + FileLockConfiguration, + FileRetentionSetting, + LegalHold, + RetentionMode, + RetentionPeriod, +) +from apiver_deps_exception import UnexpectedCloudBehaviour + +UNTIL = 1900000000123 + + +@pytest.mark.parametrize('mode', [RetentionMode.GOVERNANCE, RetentionMode.COMPLIANCE]) +def test_retention_requires_file_timestamp_and_bucket_period(mode): + with pytest.raises(ValueError, match='retain_until'): + FileRetentionSetting(mode) + with pytest.raises(ValueError, match='period'): + BucketRetentionSetting(mode) + + +@pytest.mark.parametrize( + 'mode,wire', + [(RetentionMode.GOVERNANCE, 'governance'), (RetentionMode.COMPLIANCE, 'compliance')], +) +def test_file_retention_serializes_json_numbers_and_header_strings(mode, wire): + setting = FileRetentionSetting(mode, UNTIL) + assert setting.serialize_to_json_for_request() == { + 'mode': wire, + 'retainUntilTimestamp': UNTIL, + } + headers = {'Authorization': 'synthetic-token'} + setting.add_to_to_upload_headers(headers) + assert headers == { + 'Authorization': 'synthetic-token', + 'X-Bz-File-Retention-Mode': wire, + 'X-Bz-File-Retention-Retain-Until-Timestamp': str(UNTIL), + } + assert FileRetentionSetting.from_response_headers(headers) == setting + + +@pytest.mark.parametrize('operation', ['serialize_to_json_for_request', 'add_to_to_upload_headers']) +def test_unknown_retention_cannot_be_written(operation): + setting = FileRetentionSetting(RetentionMode.UNKNOWN) + with pytest.raises(ValueError, match='unknown file retention'): + if operation == 'serialize_to_json_for_request': + setting.serialize_to_json_for_request() + else: + headers = {'preserved': 'value'} + setting.add_to_to_upload_headers(headers) + if operation != 'serialize_to_json_for_request': + assert headers == {'preserved': 'value'} + + +@pytest.mark.parametrize('action', ['hide', 'folder']) +def test_marker_versions_may_omit_lock_metadata(action): + assert ( + FileRetentionSetting.from_file_version_dict({'action': action}).mode == RetentionMode.NONE + ) + assert LegalHold.from_file_version_dict({'action': action}) == LegalHold.UNSET + + +@pytest.mark.parametrize('action', ['upload', 'start']) +@pytest.mark.parametrize( + 'reader', [FileRetentionSetting.from_file_version_dict, LegalHold.from_file_version_dict] +) +def test_data_versions_missing_lock_metadata_are_rejected(action, reader): + with pytest.raises(UnexpectedCloudBehaviour): + reader({'action': action}) + + +@pytest.mark.parametrize('authorized', [False, True]) +def test_retention_and_legal_hold_distinguish_unknown_from_unset(authorized): + response = { + 'action': 'upload', + 'fileRetention': { + 'isClientAuthorizedToRead': authorized, + 'value': {'mode': None, 'retainUntilTimestamp': None} if authorized else None, + }, + 'legalHold': {'isClientAuthorizedToRead': authorized, 'value': None}, + } + assert FileRetentionSetting.from_file_version_dict(response).mode == ( + RetentionMode.NONE if authorized else RetentionMode.UNKNOWN + ) + assert LegalHold.from_file_version_dict(response) == ( + LegalHold.UNSET if authorized else LegalHold.UNKNOWN + ) + + +@pytest.mark.parametrize('mode', [RetentionMode.GOVERNANCE, RetentionMode.COMPLIANCE]) +def test_authorized_file_response_retains_mode_and_timestamp(mode): + value = {'mode': mode.value, 'retainUntilTimestamp': UNTIL} + setting = FileRetentionSetting.from_file_version_dict( + { + 'action': 'upload', + 'fileRetention': {'isClientAuthorizedToRead': True, 'value': value}, + } + ) + assert setting.mode == mode + assert setting.retain_until == UNTIL + assert FileRetentionSetting.from_server_response({'fileRetention': value}) == setting + + +def test_unknown_bucket_retention_cannot_be_sent_in_requests(): + with pytest.raises(ValueError, match='unknown file lock'): + BucketRetentionSetting(RetentionMode.UNKNOWN).serialize_to_json_for_request() + + +@pytest.mark.parametrize('unit', ['days', 'years']) +def test_bucket_period_has_one_explicit_unit(unit): + period = RetentionPeriod(**{unit: 7}) + assert period.as_dict() == {'duration': 7, 'unit': unit} + assert RetentionPeriod.from_period_dict({'duration': 7, 'unit': unit}) == period + setting = BucketRetentionSetting(RetentionMode.GOVERNANCE, period) + assert setting.serialize_to_json_for_request() == { + 'mode': 'governance', + 'period': {'duration': 7, 'unit': unit}, + } + + +@pytest.mark.parametrize('kwargs', [{}, {'days': 1, 'years': 1}]) +def test_retention_period_requires_exactly_one_unit(kwargs): + with pytest.raises(AssertionError): + RetentionPeriod(**kwargs) + + +@pytest.mark.parametrize( + 'hold,wire', [(LegalHold.ON, 'on'), (LegalHold.OFF, 'off'), (LegalHold.UNSET, 'off')] +) +def test_legal_hold_wire_state_and_flags(hold, wire): + assert hold.to_server() == wire + assert hold.is_on() == (wire == 'on') + assert hold.is_off() == (wire == 'off') + headers = {'preserved': 'value'} + hold.add_to_upload_headers(headers) + assert headers == {'preserved': 'value', 'X-Bz-File-Legal-Hold': wire} + + +def test_unknown_legal_hold_is_not_sent_as_off(): + headers = {'preserved': 'value'} + assert LegalHold.UNKNOWN.is_unknown() + with pytest.raises(ValueError, match='unknown legal hold'): + LegalHold.UNKNOWN.add_to_upload_headers(headers) + assert headers == {'preserved': 'value'} + + +@pytest.mark.parametrize( + 'headers,mode,hold', + [ + ({}, RetentionMode.NONE, LegalHold.UNSET), + ( + {'X-Bz-Client-Unauthorized-To-Read': 'X-Bz-File-Retention-Mode,X-Bz-File-Legal-Hold'}, + RetentionMode.UNKNOWN, + LegalHold.UNKNOWN, + ), + ( + { + 'X-Bz-File-Retention-Mode': 'governance', + 'X-Bz-File-Retention-Retain-Until-Timestamp': str(UNTIL), + 'X-Bz-File-Legal-Hold': 'on', + }, + RetentionMode.GOVERNANCE, + LegalHold.ON, + ), + ], +) +def test_response_headers_distinguish_absent_unreadable_and_enabled(headers, mode, hold): + setting = FileRetentionSetting.from_response_headers(headers) + assert setting.mode == mode + assert setting.retain_until == (UNTIL if mode == RetentionMode.GOVERNANCE else None) + assert LegalHold.from_response_headers(headers) == hold + + +@pytest.mark.parametrize( + 'headers', + [ + {'X-Bz-File-Retention-Mode': 'governance'}, + { + 'X-Bz-File-Retention-Mode': 'governance', + 'X-Bz-File-Retention-Retain-Until-Timestamp': 'invalid', + }, + {'X-Bz-File-Retention-Mode': 'unrecognized'}, + ], +) +def test_malformed_retention_headers_are_not_treated_as_no_retention(headers): + with pytest.raises(ValueError): + FileRetentionSetting.from_response_headers(headers) + + +@pytest.mark.parametrize('authorized', [False, True]) +def test_bucket_lock_configuration_preserves_unknown_state(authorized): + response = { + 'fileLockConfiguration': { + 'isClientAuthorizedToRead': authorized, + 'value': { + 'isFileLockEnabled': True, + 'defaultRetention': { + 'mode': 'governance', + 'period': {'duration': 7, 'unit': 'days'}, + }, + } + if authorized + else None, + } + } + setting = FileLockConfiguration.from_bucket_dict(response) + assert setting.is_file_lock_enabled is (True if authorized else None) + assert setting.default_retention.mode == ( + RetentionMode.GOVERNANCE if authorized else RetentionMode.UNKNOWN + ) + expected = { + 'defaultRetention': {'mode': 'governance', 'period': {'duration': 7, 'unit': 'days'}} + if authorized + else {'mode': 'unknown'}, + 'isFileLockEnabled': True if authorized else None, + } + assert setting.as_dict() == expected + assert setting == FileLockConfiguration.from_bucket_dict(response) diff --git a/test/unit/test_raw_api_requests.py b/test/unit/test_raw_api_requests.py new file mode 100644 index 000000000..8119f1869 --- /dev/null +++ b/test/unit/test_raw_api_requests.py @@ -0,0 +1,839 @@ +###################################################################### +# +# File: test/unit/test_raw_api_requests.py +# +# Copyright 2026 Backblaze Inc. All Rights Reserved. +# +# License https://www.backblaze.com/using_b2_code.html +# +###################################################################### +"""Request-level contracts, replacing only transport and forbidding real HTTP. + +Expected payloads are literal Native API examples, not simulator output: +https://www.backblaze.com/apidocs/b2-copy-file +https://www.backblaze.com/apidocs/b2-start-large-file +https://www.backblaze.com/apidocs/b2-upload-file +https://www.backblaze.com/apidocs/b2-update-file-retention +""" + +from __future__ import annotations + +import io +from unittest.mock import Mock + +import pytest +from apiver_deps import ( + UNKNOWN_KEY_ID, + B2Http, + B2RawHTTPApi, + BucketRetentionSetting, + EncryptionAlgorithm, + EncryptionKey, + EncryptionMode, + EncryptionSetting, + FileRetentionSetting, + LegalHold, + MetadataDirectiveMode, + ReplicationConfiguration, + RetentionMode, + RetentionPeriod, +) +from apiver_deps_exception import ( + AccessDenied, + InvalidMetadataDirective, + RetentionWriteError, + SSECKeyError, + UnusableFileName, + WrongEncryptionModeForBucketDefault, + WrongEncryptionSettingForFileWrite, +) + +# These raw-transport exceptions have no public interface export. +from b2sdk._internal.exception import FileOrBucketNotFound, ResourceNotFound +from b2sdk._internal.raw_api import notification_rule_response_to_request + +API = 'https://api.example.invalid' +TOKEN = 'synthetic-account-token' +UNTIL = 1900000000123 +KEY = bytes(range(32)) +KEY_B64 = 'AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8=' +KEY_MD5 = 'tP/LI3N87DFaSk0aoqYgzg==' +SSE_JSON = { + 'mode': 'SSE-C', + 'algorithm': 'AES256', + 'customerKey': KEY_B64, + 'customerKeyMd5': KEY_MD5, +} +SSE_HEADERS = { + 'X-Bz-Server-Side-Encryption-Customer-Algorithm': 'AES256', + 'X-Bz-Server-Side-Encryption-Customer-Key': KEY_B64, + 'X-Bz-Server-Side-Encryption-Customer-Key-Md5': KEY_MD5, +} + + +@pytest.fixture(autouse=True) +def forbid_network(monkeypatch): + def forbidden(*args, **kwargs): + pytest.fail('request unit tests must not perform real HTTP') + + monkeypatch.setattr('requests.sessions.Session.request', forbidden) + + +@pytest.fixture +def raw_api(): + return B2RawHTTPApi(Mock(spec=B2Http)) + + +@pytest.fixture +def api_version(apiver_int): + # Interface v3 uses Native API v4; the compatibility interfaces use v3. + return 'v4' if apiver_int == 3 else 'v3' + + +def customer_setting(key_id='public-key-id', secret=KEY): + return EncryptionSetting( + EncryptionMode.SSE_C, EncryptionAlgorithm.AES256, EncryptionKey(secret, key_id) + ) + + +def assert_json_request(raw_api, api_version, endpoint, payload): + raw_api.b2_http.post_json_return_json.assert_called_once_with( + f'{API}/b2api/{api_version}/{endpoint}', + {'Authorization': TOKEN}, + payload, + ) + + +# Each row pins an externally named endpoint and wire fields, including pagination. +@pytest.mark.parametrize( + 'method,args,kwargs,endpoint,payload', + [ + ('cancel_large_file', ('file-id',), {}, 'b2_cancel_large_file', {'fileId': 'file-id'}), + ( + 'delete_bucket', + ('account-id', 'bucket-id'), + {}, + 'b2_delete_bucket', + {'accountId': 'account-id', 'bucketId': 'bucket-id'}, + ), + ( + 'delete_file_version', + ('file-id', 'dir/a.txt'), + {'bypass_governance': True}, + 'b2_delete_file_version', + {'fileId': 'file-id', 'fileName': 'dir/a.txt', 'bypassGovernance': True}, + ), + ('delete_key', ('key-id',), {}, 'b2_delete_key', {'applicationKeyId': 'key-id'}), + ( + 'finish_large_file', + ('file-id', ['hash1', 'hash2']), + {}, + 'b2_finish_large_file', + {'fileId': 'file-id', 'partSha1Array': ['hash1', 'hash2']}, + ), + ( + 'get_download_authorization', + ('bucket-id', 'dir/', 60), + {}, + 'b2_get_download_authorization', + {'bucketId': 'bucket-id', 'fileNamePrefix': 'dir/', 'validDurationInSeconds': 60}, + ), + ('get_file_info_by_id', ('file-id',), {}, 'b2_get_file_info', {'fileId': 'file-id'}), + ('get_upload_url', ('bucket-id',), {}, 'b2_get_upload_url', {'bucketId': 'bucket-id'}), + ('get_upload_part_url', ('file-id',), {}, 'b2_get_upload_part_url', {'fileId': 'file-id'}), + ( + 'hide_file', + ('bucket-id', 'dir/a.txt'), + {}, + 'b2_hide_file', + {'bucketId': 'bucket-id', 'fileName': 'dir/a.txt'}, + ), + ( + 'list_buckets', + ('account-id',), + {'bucket_id': 'bucket-id'}, + 'b2_list_buckets', + { + 'accountId': 'account-id', + 'bucketId': 'bucket-id', + 'bucketName': None, + 'bucketTypes': ['all'], + }, + ), + ( + 'list_file_names', + ('bucket-id',), + {'start_file_name': 'dir/a.txt', 'max_file_count': 2, 'prefix': 'dir/'}, + 'b2_list_file_names', + { + 'bucketId': 'bucket-id', + 'startFileName': 'dir/a.txt', + 'maxFileCount': 2, + 'prefix': 'dir/', + }, + ), + ( + 'list_file_versions', + ('bucket-id',), + { + 'start_file_name': 'dir/a.txt', + 'start_file_id': 'file-id', + 'max_file_count': 2, + 'prefix': 'dir/', + }, + 'b2_list_file_versions', + { + 'bucketId': 'bucket-id', + 'startFileName': 'dir/a.txt', + 'startFileId': 'file-id', + 'maxFileCount': 2, + 'prefix': 'dir/', + }, + ), + ( + 'list_keys', + ('account-id',), + {'max_key_count': 2, 'start_application_key_id': 'key-id'}, + 'b2_list_keys', + {'accountId': 'account-id', 'maxKeyCount': 2, 'startApplicationKeyId': 'key-id'}, + ), + ( + 'list_parts', + ('file-id', 2, 3), + {}, + 'b2_list_parts', + {'fileId': 'file-id', 'startPartNumber': 2, 'maxPartCount': 3}, + ), + ( + 'list_unfinished_large_files', + ('bucket-id',), + {'start_file_id': 'file-id', 'max_file_count': 2, 'prefix': 'dir/'}, + 'b2_list_unfinished_large_files', + { + 'bucketId': 'bucket-id', + 'startFileId': 'file-id', + 'maxFileCount': 2, + 'namePrefix': 'dir/', + }, + ), + ], +) +def test_json_endpoint_and_payload(raw_api, api_version, method, args, kwargs, endpoint, payload): + getattr(raw_api, method)(API, TOKEN, *args, **kwargs) + assert_json_request(raw_api, api_version, endpoint, payload) + + +def test_authorization_uses_basic_header_not_body_credentials(raw_api, api_version): + raw_api.authorize_account(API, 'id', 'key') + raw_api.b2_http.post_json_return_json.assert_called_once_with( + f'{API}/b2api/{api_version}/b2_authorize_account', + {'Authorization': 'Basic aWQ6a2V5'}, + {}, + ) + + +@pytest.mark.parametrize('operation', ['create', 'update']) +def test_bucket_settings_preserve_explicit_false_and_empty_values(raw_api, api_version, operation): + options = dict( + bucket_info={}, + cors_rules=[], + lifecycle_rules=[], + default_server_side_encryption=EncryptionSetting( + EncryptionMode.SSE_B2, EncryptionAlgorithm.AES256 + ), + is_file_lock_enabled=False, + replication=ReplicationConfiguration( + source_to_destination_key_mapping={'source-key': 'destination-key'} + ), + ) + payload = { + 'accountId': 'account-id', + 'bucketInfo': {}, + 'corsRules': [], + 'lifecycleRules': [], + 'defaultServerSideEncryption': {'mode': 'SSE-B2', 'algorithm': 'AES256'}, + 'fileLockEnabled': False, + 'replicationConfiguration': { + 'asReplicationSource': None, + 'asReplicationDestination': { + 'sourceToDestinationKeyMapping': {'source-key': 'destination-key'} + }, + }, + } + if operation == 'create': + raw_api.create_bucket(API, TOKEN, 'account-id', 'bucket-name', 'allPrivate', **options) + payload.update(bucketName='bucket-name', bucketType='allPrivate') + else: + raw_api.update_bucket( + API, + TOKEN, + 'account-id', + 'bucket-id', + default_retention=BucketRetentionSetting( + RetentionMode.GOVERNANCE, RetentionPeriod(days=7) + ), + if_revision_is=0, + **options, + ) + payload.update( + bucketId='bucket-id', + ifRevisionIs=0, + defaultRetention={'mode': 'governance', 'period': {'duration': 7, 'unit': 'days'}}, + ) + assert_json_request(raw_api, api_version, 'b2_' + operation + '_bucket', payload) + + +@pytest.mark.parametrize('operation', ['create', 'update']) +def test_customer_encryption_cannot_be_a_bucket_default(raw_api, operation): + with pytest.raises(WrongEncryptionModeForBucketDefault): + if operation == 'create': + raw_api.create_bucket( + API, + TOKEN, + 'account-id', + 'bucket-name', + 'allPrivate', + default_server_side_encryption=customer_setting(), + ) + else: + raw_api.update_bucket( + API, + TOKEN, + 'account-id', + 'bucket-id', + default_server_side_encryption=customer_setting(), + ) + assert raw_api.b2_http.mock_calls == [] + + +@pytest.mark.parametrize('mode', [EncryptionMode.SSE_C, EncryptionMode.SSE_B2]) +def test_start_large_file_sends_encryption_retention_and_legal_hold(raw_api, api_version, mode): + setting = ( + customer_setting() + if mode == EncryptionMode.SSE_C + else EncryptionSetting(mode, EncryptionAlgorithm.AES256) + ) + raw_api.start_large_file( + API, + TOKEN, + 'bucket-id', + 'dir/a.txt', + 'text/plain', + {}, + server_side_encryption=setting, + file_retention=FileRetentionSetting(RetentionMode.GOVERNANCE, UNTIL), + legal_hold=LegalHold.ON, + ) + assert_json_request( + raw_api, + api_version, + 'b2_start_large_file', + { + 'bucketId': 'bucket-id', + 'fileName': 'dir/a.txt', + 'contentType': 'text/plain', + 'fileInfo': {'sse_c_key_id': 'public-key-id'} if mode == EncryptionMode.SSE_C else {}, + 'serverSideEncryption': SSE_JSON + if mode == EncryptionMode.SSE_C + else {'mode': 'SSE-B2', 'algorithm': 'AES256'}, + 'fileRetention': {'mode': 'governance', 'retainUntilTimestamp': UNTIL}, + 'legalHold': 'on', + }, + ) + + +@pytest.mark.parametrize('directive', [MetadataDirectiveMode.COPY, MetadataDirectiveMode.REPLACE]) +def test_copy_serializes_encryption_range_and_lock_settings(raw_api, api_version, directive): + kwargs = ( + {} + if directive == MetadataDirectiveMode.COPY + else {'content_type': 'text/plain', 'file_info': {'color': 'blue'}} + ) + raw_api.copy_file( + API, + TOKEN, + 'source-id', + 'dir/copied.txt', + bytes_range=(0, 0), + metadata_directive=directive, + destination_bucket_id='destination-id', + destination_server_side_encryption=customer_setting('destination'), + source_server_side_encryption=customer_setting('source'), + file_retention=FileRetentionSetting(RetentionMode.COMPLIANCE, UNTIL), + legal_hold=LegalHold.OFF, + **kwargs, + ) + payload = { + 'sourceFileId': 'source-id', + 'fileName': 'dir/copied.txt', + 'range': 'bytes=0-0', + 'metadataDirective': directive.name, + 'destinationBucketId': 'destination-id', + 'destinationServerSideEncryption': SSE_JSON, + 'sourceServerSideEncryption': SSE_JSON, + 'fileRetention': {'mode': 'compliance', 'retainUntilTimestamp': UNTIL}, + 'legalHold': 'off', + } + if directive == MetadataDirectiveMode.REPLACE: + payload.update(contentType='text/plain', fileInfo={'color': 'blue'}) + assert_json_request(raw_api, api_version, 'b2_copy_file', payload) + + +@pytest.mark.parametrize( + 'directive,kwargs', + [ + (MetadataDirectiveMode.COPY, {'content_type': 'text/plain'}), + (MetadataDirectiveMode.COPY, {'file_info': {}}), + (MetadataDirectiveMode.REPLACE, {}), + ], +) +def test_copy_metadata_conflicts_are_rejected_before_transport(raw_api, directive, kwargs): + with pytest.raises(InvalidMetadataDirective): + raw_api.copy_file( + API, TOKEN, 'source-id', 'copied.txt', metadata_directive=directive, **kwargs + ) + assert raw_api.b2_http.mock_calls == [] + + +def test_copy_part_preserves_range_and_both_customer_keys(raw_api, api_version): + raw_api.copy_part( + API, + TOKEN, + 'source-id', + 'large-id', + 2, + bytes_range=(4, 9), + destination_server_side_encryption=customer_setting('destination'), + source_server_side_encryption=customer_setting('source'), + ) + assert_json_request( + raw_api, + api_version, + 'b2_copy_part', + { + 'sourceFileId': 'source-id', + 'largeFileId': 'large-id', + 'partNumber': 2, + 'range': 'bytes=4-9', + 'destinationServerSideEncryption': SSE_JSON, + 'sourceServerSideEncryption': SSE_JSON, + }, + ) + + +@pytest.mark.parametrize('operation', ['upload_file', 'upload_part']) +@pytest.mark.parametrize('mode', [EncryptionMode.SSE_B2, EncryptionMode.SSE_C]) +def test_upload_preserves_body_and_exact_headers(raw_api, operation, mode): + data = io.BytesIO(b'body') + encryption = ( + customer_setting() + if mode == EncryptionMode.SSE_C + else EncryptionSetting(mode, EncryptionAlgorithm.AES256) + ) + expected = { + 'Authorization': 'upload-token', + 'Content-Length': '4', + 'X-Bz-Content-Sha1': 'test-sha1', + } + if mode == EncryptionMode.SSE_C: + expected.update(SSE_HEADERS) + expected['X-Bz-Info-sse_c_key_id'] = 'public-key-id' + else: + expected['X-Bz-Server-Side-Encryption'] = 'AES256' + if operation == 'upload_file': + raw_api.upload_file( + 'https://upload.example.invalid', + 'upload-token', + 'dir/Δ +.txt', + 4, + 'text/plain', + 'test-sha1', + {'note': 'Δ +'}, + data, + server_side_encryption=encryption, + file_retention=FileRetentionSetting(RetentionMode.GOVERNANCE, UNTIL), + legal_hold=LegalHold.ON, + custom_upload_timestamp=0, + ) + expected.update( + { + 'X-Bz-File-Name': 'dir/%CE%94%20%2B.txt', + 'Content-Type': 'text/plain', + 'X-Bz-Info-note': '%CE%94%20%2B', + 'X-Bz-File-Legal-Hold': 'on', + 'X-Bz-File-Retention-Mode': 'governance', + 'X-Bz-File-Retention-Retain-Until-Timestamp': str(UNTIL), + 'X-Bz-Custom-Upload-Timestamp': '0', + } + ) + else: + raw_api.upload_part( + 'https://upload.example.invalid', + 'upload-token', + 2, + 4, + 'test-sha1', + data, + server_side_encryption=encryption, + ) + expected['X-Bz-Part-Number'] = '2' + raw_api.b2_http.post_content_return_json.assert_called_once_with( + 'https://upload.example.invalid', + expected, + data, + try_count=1, + ) + assert data.tell() == 0 + + +@pytest.mark.parametrize('token', [None, TOKEN]) +@pytest.mark.parametrize('mode', [EncryptionMode.NONE, EncryptionMode.SSE_B2, EncryptionMode.SSE_C]) +def test_download_authorization_range_and_encryption_headers(raw_api, token, mode): + setting = ( + EncryptionSetting(mode) + if mode == EncryptionMode.NONE + else customer_setting() + if mode == EncryptionMode.SSE_C + else EncryptionSetting(mode, EncryptionAlgorithm.AES256) + ) + raw_api.download_file_from_url( + token, 'https://download.example.invalid/file', range_=(0, 0), encryption=setting + ) + headers = {'Range': 'bytes=0-0'} + if token is not None: + headers['Authorization'] = token + if mode == EncryptionMode.SSE_C: + headers.update(SSE_HEADERS) + elif mode == EncryptionMode.SSE_B2: + headers['X-Bz-Server-Side-Encryption'] = 'AES256' + raw_api.b2_http.get_content.assert_called_once_with( + 'https://download.example.invalid/file', headers + ) + + +@pytest.mark.parametrize('operation', ['download', 'copy', 'copy_part']) +@pytest.mark.parametrize('range_', [(-1, 2), (3, 2), (0,)]) +def test_invalid_range_never_reaches_transport(raw_api, operation, range_): + with pytest.raises(AssertionError): + if operation == 'download': + raw_api.download_file_from_url(TOKEN, API, range_=range_) + elif operation == 'copy': + raw_api.copy_file(API, TOKEN, 'source-id', 'copy.txt', bytes_range=range_) + else: + raw_api.copy_part(API, TOKEN, 'source-id', 'large-id', 1, bytes_range=range_) + assert raw_api.b2_http.mock_calls == [] + + +@pytest.mark.parametrize('bypass', [False, True]) +def test_retention_update_preserves_explicit_governance_bypass(raw_api, api_version, bypass): + raw_api.update_file_retention( + API, + TOKEN, + 'file-id', + 'dir/a.txt', + FileRetentionSetting(RetentionMode.GOVERNANCE, UNTIL), + bypass_governance=bypass, + ) + assert_json_request( + raw_api, + api_version, + 'b2_update_file_retention', + { + 'fileId': 'file-id', + 'fileName': 'dir/a.txt', + 'bypassGovernance': bypass, + 'fileRetention': {'mode': 'governance', 'retainUntilTimestamp': UNTIL}, + }, + ) + + +@pytest.mark.parametrize('hold,wire', [(LegalHold.ON, 'on'), (LegalHold.OFF, 'off')]) +def test_legal_hold_update_uses_wire_value(raw_api, api_version, hold, wire): + raw_api.update_file_legal_hold(API, TOKEN, 'file-id', 'dir/a.txt', hold) + assert_json_request( + raw_api, + api_version, + 'b2_update_file_legal_hold', + { + 'fileId': 'file-id', + 'fileName': 'dir/a.txt', + 'legalHold': wire, + }, + ) + + +@pytest.mark.parametrize( + 'operation', ['start', 'copy', 'upload', 'retention_update', 'hold_update', 'bucket_update'] +) +def test_unknown_lock_setting_is_rejected_before_transport(raw_api, operation): + unknown = FileRetentionSetting(RetentionMode.UNKNOWN) + with pytest.raises(ValueError, match='unknown'): + if operation == 'start': + raw_api.start_large_file( + API, TOKEN, 'bucket-id', 'file.txt', 'text/plain', {}, file_retention=unknown + ) + elif operation == 'copy': + raw_api.copy_file(API, TOKEN, 'source-id', 'copy.txt', legal_hold=LegalHold.UNKNOWN) + elif operation == 'upload': + raw_api.upload_file( + API, + TOKEN, + 'file.txt', + 1, + 'text/plain', + 'sha1', + {}, + io.BytesIO(b'x'), + file_retention=unknown, + ) + elif operation == 'retention_update': + raw_api.update_file_retention(API, TOKEN, 'file-id', 'file.txt', unknown) + elif operation == 'hold_update': + raw_api.update_file_legal_hold(API, TOKEN, 'file-id', 'file.txt', LegalHold.UNKNOWN) + else: + raw_api.update_bucket( + API, + TOKEN, + 'account-id', + 'bucket-id', + default_retention=BucketRetentionSetting(RetentionMode.UNKNOWN), + ) + assert raw_api.b2_http.mock_calls == [] + + +@pytest.mark.parametrize('operation', ['start', 'copy', 'copy_part', 'upload', 'upload_part']) +def test_missing_customer_secret_is_rejected_before_transport(raw_api, operation): + setting = customer_setting(secret=None) + with pytest.raises(WrongEncryptionSettingForFileWrite): + if operation == 'start': + raw_api.start_large_file( + API, + TOKEN, + 'bucket-id', + 'file.txt', + 'text/plain', + {}, + server_side_encryption=setting, + ) + elif operation == 'copy': + raw_api.copy_file( + API, TOKEN, 'source-id', 'copy.txt', destination_server_side_encryption=setting + ) + elif operation == 'copy_part': + raw_api.copy_part( + API, TOKEN, 'source-id', 'large-id', 1, destination_server_side_encryption=setting + ) + elif operation == 'upload': + raw_api.upload_file( + API, + TOKEN, + 'file.txt', + 1, + 'text/plain', + 'sha1', + {}, + io.BytesIO(b'x'), + server_side_encryption=setting, + ) + else: + raw_api.upload_part( + API, TOKEN, 1, 1, 'sha1', io.BytesIO(b'x'), server_side_encryption=setting + ) + assert raw_api.b2_http.mock_calls == [] + + +@pytest.mark.parametrize( + 'operation,transport,expected_error', + [ + ('download', 'get_content', SSECKeyError), + ('copy', 'post_json_return_json', SSECKeyError), + ('copy_part', 'post_json_return_json', SSECKeyError), + ('retention', 'post_json_return_json', RetentionWriteError), + ('legal_hold', 'post_json_return_json', RetentionWriteError), + ], +) +def test_access_denied_is_translated_at_the_boundary(raw_api, operation, transport, expected_error): + getattr(raw_api.b2_http, transport).side_effect = AccessDenied() + with pytest.raises(expected_error): + if operation == 'download': + raw_api.download_file_from_url(TOKEN, API, encryption=customer_setting()) + elif operation == 'copy': + raw_api.copy_file( + API, + TOKEN, + 'source-id', + 'copy.txt', + source_server_side_encryption=customer_setting(), + ) + elif operation == 'copy_part': + raw_api.copy_part( + API, + TOKEN, + 'source-id', + 'large-id', + 1, + source_server_side_encryption=customer_setting(), + ) + elif operation == 'retention': + raw_api.update_file_retention( + API, + TOKEN, + 'file-id', + 'file.txt', + FileRetentionSetting(RetentionMode.GOVERNANCE, UNTIL), + ) + else: + raw_api.update_file_legal_hold(API, TOKEN, 'file-id', 'file.txt', LegalHold.ON) + assert getattr(raw_api.b2_http, transport).call_count == 1 + + +@pytest.mark.parametrize('missing', [False, True]) +def test_file_info_by_name_encodes_path_and_preserves_not_found_identity(raw_api, missing): + expected_url = 'https://download.example.invalid/file/bucket-name/dir/%CE%94%20%2B.txt' + if missing: + raw_api.b2_http.head_content.side_effect = ResourceNotFound() + with pytest.raises(FileOrBucketNotFound) as exc: + raw_api.get_file_info_by_name( + 'https://download.example.invalid', TOKEN, 'bucket-name', 'dir/Δ +.txt' + ) + assert exc.value.bucket_name == 'bucket-name' + assert exc.value.file_id_or_name == 'dir/Δ +.txt' + else: + raw_api.b2_http.head_content.return_value.headers = { + 'Content-Length': '4', + 'X-Bz-File-Id': 'file-id', + } + assert raw_api.get_file_info_by_name( + 'https://download.example.invalid', TOKEN, 'bucket-name', 'dir/Δ +.txt' + ) == { + 'Content-Length': '4', + 'X-Bz-File-Id': 'file-id', + } + raw_api.b2_http.head_content.assert_called_once_with( + expected_url, headers={'Authorization': TOKEN} + ) + + +@pytest.mark.parametrize( + 'key_id,expected', + [ + ('plain-id', 'plain-id'), + ('key id+Δ', 'key%20id%2B%CE%94'), + ('literal%20value', 'literal%2520value'), + ('plus+literal', 'plus%2Bliteral'), + ], +) +def test_upload_accepts_matching_key_id_from_file_metadata(raw_api, key_id, expected): + raw_api.upload_file( + API, + TOKEN, + 'file.txt', + 1, + 'text/plain', + 'sha1', + {'sse_c_key_id': key_id}, + io.BytesIO(b'x'), + server_side_encryption=customer_setting(key_id), + ) + headers = raw_api.b2_http.post_content_return_json.call_args.args[1] + assert headers['X-Bz-Info-sse_c_key_id'] == expected + assert raw_api.b2_http.post_content_return_json.call_count == 1 + + +@pytest.mark.parametrize('metadata_id', ['different', 'key%20id+Δ']) +def test_conflicting_upload_key_id_is_rejected_before_transport(raw_api, metadata_id): + with pytest.raises(ValueError, match='Ambiguous key id'): + raw_api.upload_file( + API, + TOKEN, + 'file.txt', + 1, + 'text/plain', + 'sha1', + {'sse_c_key_id': metadata_id}, + io.BytesIO(b'x'), + server_side_encryption=customer_setting('key id+Δ'), + ) + assert raw_api.b2_http.mock_calls == [] + + +@pytest.mark.parametrize('operation', ['start', 'upload']) +def test_unknown_customer_key_id_is_rejected_before_metadata_write(raw_api, operation): + setting = customer_setting(UNKNOWN_KEY_ID) + with pytest.raises(ValueError, match='unknown key id'): + if operation == 'start': + raw_api.start_large_file( + API, + TOKEN, + 'bucket-id', + 'file.txt', + 'text/plain', + {}, + server_side_encryption=setting, + ) + else: + raw_api.upload_file( + API, + TOKEN, + 'file.txt', + 1, + 'text/plain', + 'sha1', + {}, + io.BytesIO(b'x'), + server_side_encryption=setting, + ) + assert raw_api.b2_http.mock_calls == [] + + +@pytest.mark.parametrize('operation', ['get', 'set']) +def test_notification_requests_preserve_method_parameters_and_response( + raw_api, api_version, operation +): + # The notification GET endpoint is Native API v4, including when called + # through a compatibility facade. POST keeps the facade's native version. + rules = [ + { + 'name': 'example-rule', + 'eventTypes': ['b2:ObjectCreated:Upload'], + 'isEnabled': True, + 'objectNamePrefix': 'dir/', + 'targetConfiguration': {'targetType': 'webhook', 'url': 'https://hook.example.invalid'}, + } + ] + if operation == 'get': + raw_api.b2_http.request_content_return_json.return_value = {'eventNotificationRules': rules} + result = raw_api.get_bucket_notification_rules(API, TOKEN, 'bucket-id') + raw_api.b2_http.request_content_return_json.assert_called_once_with( + 'GET', + f'{API}/b2api/v4/b2_get_bucket_notification_rules', + {'Authorization': TOKEN}, + params={'bucketId': 'bucket-id'}, + ) + raw_api.b2_http.post_json_return_json.assert_not_called() + else: + raw_api.b2_http.post_json_return_json.return_value = {'eventNotificationRules': rules} + result = raw_api.set_bucket_notification_rules(API, TOKEN, 'bucket-id', rules) + assert_json_request( + raw_api, + api_version, + 'b2_set_bucket_notification_rules', + {'bucketId': 'bucket-id', 'eventNotificationRules': rules}, + ) + assert result == rules + + +@pytest.mark.parametrize('status_fields', [{}, {'isSuspended': False, 'suspensionReason': ''}]) +def test_notification_response_status_is_not_sent_back_or_removed_from_input(status_fields): + response = {'name': 'example-rule', 'isEnabled': True, **status_fields} + original = response.copy() + request = notification_rule_response_to_request(response) + assert request == {'name': 'example-rule', 'isEnabled': True} + assert request is not response + assert response == original + + +def test_empty_upload_filename_is_rejected_before_transport(raw_api): + with pytest.raises(UnusableFileName, match='at least 1 character'): + raw_api.upload_file(API, TOKEN, '', 1, 'text/plain', 'sha1', {}, io.BytesIO(b'x')) + assert raw_api.b2_http.mock_calls == [] From 040533f280ae5af4487f0113e0532d75145ac864 Mon Sep 17 00:00:00 2001 From: Felipe Fumero Date: Tue, 24 Nov 2026 16:54:36 -0600 Subject: [PATCH 068/113] Restore the simulator encryption-check flag on exception (#735) * fix: restore simulator encryption check state * docs(changelog): add fragment for the simulator encryption-check fix --- b2sdk/_internal/raw_simulator.py | 7 ++-- ...+simulator-encryption-check-reset.fixed.md | 1 + .../unit/test_simulator_encryption_context.py | 35 +++++++++++++++++++ 3 files changed, 41 insertions(+), 2 deletions(-) create mode 100644 changelog.d/+simulator-encryption-check-reset.fixed.md create mode 100644 test/unit/test_simulator_encryption_context.py diff --git a/b2sdk/_internal/raw_simulator.py b/b2sdk/_internal/raw_simulator.py index 450f7bec3..f02fc21c5 100644 --- a/b2sdk/_internal/raw_simulator.py +++ b/b2sdk/_internal/raw_simulator.py @@ -232,9 +232,12 @@ def __init__( @classmethod @contextmanager def dont_check_encryption(cls): + previous = cls.CHECK_ENCRYPTION cls.CHECK_ENCRYPTION = False - yield - cls.CHECK_ENCRYPTION = True + try: + yield + finally: + cls.CHECK_ENCRYPTION = previous def sort_key(self): """ diff --git a/changelog.d/+simulator-encryption-check-reset.fixed.md b/changelog.d/+simulator-encryption-check-reset.fixed.md new file mode 100644 index 000000000..95a649223 --- /dev/null +++ b/changelog.d/+simulator-encryption-check-reset.fixed.md @@ -0,0 +1 @@ +Restore the raw simulator encryption-check flag after an exception inside `dont_check_encryption`, so later simulator checks are not left disabled (affects the test model only). diff --git a/test/unit/test_simulator_encryption_context.py b/test/unit/test_simulator_encryption_context.py new file mode 100644 index 000000000..109f07ebd --- /dev/null +++ b/test/unit/test_simulator_encryption_context.py @@ -0,0 +1,35 @@ +###################################################################### +# +# File: test/unit/test_simulator_encryption_context.py +# +# Copyright 2026 Backblaze Inc. All Rights Reserved. +# +# License https://www.backblaze.com/using_b2_code.html +# +###################################################################### +import pytest + +from b2sdk._internal.raw_simulator import FileSimulator + + +@pytest.mark.parametrize('initial', [True, False]) +def test_context_restores_previous_flag_after_exception(monkeypatch, initial): + monkeypatch.setattr(FileSimulator, 'CHECK_ENCRYPTION', initial) + with pytest.raises(RuntimeError, match='body failed'): + with FileSimulator.dont_check_encryption(): + assert FileSimulator.CHECK_ENCRYPTION is False + raise RuntimeError('body failed') + assert FileSimulator.CHECK_ENCRYPTION is initial + + +def test_nested_context_restores_outer_flag_after_inner_exception(monkeypatch): + monkeypatch.setattr(FileSimulator, 'CHECK_ENCRYPTION', True) + with FileSimulator.dont_check_encryption(): + with pytest.raises(RuntimeError, match='inner failed'): + with FileSimulator.dont_check_encryption(): + raise RuntimeError('inner failed') + assert FileSimulator.CHECK_ENCRYPTION is False + with FileSimulator.dont_check_encryption(): + assert FileSimulator.CHECK_ENCRYPTION is False + assert FileSimulator.CHECK_ENCRYPTION is False + assert FileSimulator.CHECK_ENCRYPTION is True From ff8dc303f401824e6acd4071aef985d8702e3545 Mon Sep 17 00:00:00 2001 From: Felipe Fumero Date: Wed, 25 Nov 2026 11:28:52 -0600 Subject: [PATCH 069/113] Do not delete old versions when a sync replacement transfer fails (#738) * fix: preserve sync versions when replacement fails Run cleanup only after its corresponding transfer succeeds. Otherwise an upload or copy failure can leave the destination without any version. * fix: avoid blocking sync workers on cleanup Queue dependent cleanup when its transfer completes so unrelated transfers can run while a replacement is in progress. Drain ready cleanup before shutting down the executor. * fix: bound pending sync cleanup actions Drain completed cleanup during scheduling and apply backpressure at the executor queue limit to avoid retaining unbounded dependent actions. * test: verify prompt sync cleanup draining --- b2sdk/_internal/sync/policy.py | 9 +- b2sdk/_internal/sync/sync.py | 42 ++- .../+sync-replacement-cleanup.fixed.md | 1 + .../unit/sync/test_failed_transfer_cleanup.py | 331 ++++++++++++++++++ 4 files changed, 378 insertions(+), 5 deletions(-) create mode 100644 changelog.d/+sync-replacement-cleanup.fixed.md create mode 100644 test/unit/sync/test_failed_transfer_cleanup.py diff --git a/b2sdk/_internal/sync/policy.py b/b2sdk/_internal/sync/policy.py index 724d09c42..6d22cbc95 100644 --- a/b2sdk/_internal/sync/policy.py +++ b/b2sdk/_internal/sync/policy.py @@ -214,13 +214,18 @@ def get_all_actions(self): """ Yield file actions. """ + transfer = None if self._should_transfer(): - yield self._make_transfer_action() + transfer = self._make_transfer_action() + yield transfer self._transferred = True assert self._dest_path is not None or self._source_path is not None - yield from self._get_hide_delete_actions() + for action in self._get_hide_delete_actions(): + if transfer is not None: + action._sync_transfer = transfer + yield action def _get_hide_delete_actions(self): """ diff --git a/b2sdk/_internal/sync/sync.py b/b2sdk/_internal/sync/sync.py index f4485c4fa..39bd8d18c 100644 --- a/b2sdk/_internal/sync/sync.py +++ b/b2sdk/_internal/sync/sync.py @@ -12,6 +12,7 @@ import concurrent.futures as futures import io import logging +import queue from enum import Enum, unique from typing import cast @@ -205,6 +206,20 @@ def sync_folders( unbounded_executor = futures.ThreadPoolExecutor(max_workers=self.max_workers) queue_limit = self.max_workers + 1000 sync_executor = BoundedQueueExecutor(unbounded_executor, queue_limit=queue_limit) + cleanup_ready = queue.SimpleQueue() + pending_cleanup = 0 + action_bucket = None + + def drain_cleanup(block): + nonlocal pending_cleanup + try: + future, action = cleanup_ready.get(block=block) + except queue.Empty: + return False + pending_cleanup -= 1 + if not future.cancelled() and future.exception() is None: + sync_executor.submit(action.run, action_bucket, reporter, self.dry_run) + return True try: if reporter is None: @@ -234,11 +249,32 @@ def sync_folders( encryption_settings_provider, ): logging.debug('scheduling action %s on bucket %s', action, action_bucket) - sync_executor.submit(action.run, action_bucket, reporter, self.dry_run) + transfer = vars(action).get('_sync_transfer') + if transfer is None: + action._sync_future = sync_executor.submit( + action.run, action_bucket, reporter, self.dry_run + ) + else: + # The callback owns the action now; avoid a reference cycle through + # its transfer and future after the cleanup is drained. + del action._sync_transfer + pending_cleanup += 1 + transfer._sync_future.add_done_callback( + lambda future, action=action: cleanup_ready.put((future, action)) + ) + while drain_cleanup(block=False): + pass + if pending_cleanup >= queue_limit: + drain_cleanup(block=True) finally: - # Drain queued actions before returning, including when scheduling fails. - sync_executor.shutdown() + try: + # Callbacks do not occupy executor workers or submit during shutdown. + # Drain them even if action scheduling raises. + while pending_cleanup: + drain_cleanup(block=True) + finally: + sync_executor.shutdown() if sync_executor.get_num_exceptions() != 0: raise IncompleteSync('sync is incomplete') diff --git a/changelog.d/+sync-replacement-cleanup.fixed.md b/changelog.d/+sync-replacement-cleanup.fixed.md new file mode 100644 index 000000000..8d934318f --- /dev/null +++ b/changelog.d/+sync-replacement-cleanup.fixed.md @@ -0,0 +1 @@ +Preserve destination versions when a sync replacement transfer fails. diff --git a/test/unit/sync/test_failed_transfer_cleanup.py b/test/unit/sync/test_failed_transfer_cleanup.py new file mode 100644 index 000000000..f4e2d714b --- /dev/null +++ b/test/unit/sync/test_failed_transfer_cleanup.py @@ -0,0 +1,331 @@ +###################################################################### +# +# File: test/unit/sync/test_failed_transfer_cleanup.py +# +# Copyright 2026 Backblaze Inc. All Rights Reserved. +# +# License https://www.backblaze.com/using_b2_code.html +# +###################################################################### +import time + +import pytest + +from b2sdk._internal.scan.folder import B2Folder, LocalFolder +from b2sdk._internal.sync.action import B2DeleteAction +from b2sdk._internal.sync.exception import IncompleteSync +from b2sdk._internal.sync.policy import CompareVersionMode +from b2sdk._internal.sync.sync import KeepOrDeleteMode, Synchronizer + +pytestmark = pytest.mark.apiver(3) + + +@pytest.mark.parametrize('workers', [1, 4]) +@pytest.mark.parametrize('mode', [KeepOrDeleteMode.DELETE, KeepOrDeleteMode.KEEP_BEFORE_DELETE]) +def test_failed_replacement_preserves_old_versions( + tmp_path, b2api, bucket, monkeypatch, workers, mode +): + old = [bucket.upload_bytes(data, 'file.txt') for data in (b'old', b'older')] + old_versions = [v.id_ for v in old] + (tmp_path / 'file.txt').write_bytes(b'replacement bytes') + dest = B2Folder(bucket.name, '', b2api) + + def fail_upload(*args, **kwargs): + raise RuntimeError('replacement failed') + + monkeypatch.setattr(dest.bucket, 'concatenate', fail_upload) + sync = Synchronizer( + max_workers=workers, + keep_days_or_delete=mode, + keep_days=1 if mode == KeepOrDeleteMode.KEEP_BEFORE_DELETE else None, + compare_version_mode=CompareVersionMode.SIZE, + ) + with pytest.raises(IncompleteSync): + sync.sync_folders( + LocalFolder(tmp_path), dest, max(v.upload_timestamp for v in old) + 3 * 86400000, None + ) + assert {v.id_ for v in bucket.list_file_versions('file.txt')} == set(old_versions) + + +def test_successful_replacement_deletes_old_versions(tmp_path, b2api, bucket): + old_ids = {bucket.upload_bytes(data, 'file.txt').id_ for data in (b'old', b'older')} + (tmp_path / 'file.txt').write_bytes(b'replacement bytes') + sync = Synchronizer( + max_workers=4, + keep_days_or_delete=KeepOrDeleteMode.DELETE, + compare_version_mode=CompareVersionMode.SIZE, + ) + sync.sync_folders( + LocalFolder(tmp_path), B2Folder(bucket.name, '', b2api), int(time.time() * 1000), None + ) + versions = list(bucket.list_file_versions('file.txt')) + assert len(versions) == 1 + assert versions[0].id_ not in old_ids + assert versions[0].size == len(b'replacement bytes') + + +def test_cleanup_waits_for_in_progress_upload(tmp_path, b2api, bucket, monkeypatch): + from threading import Event, Thread + + old_id = bucket.upload_bytes(b'old', 'file.txt').id_ + (tmp_path / 'file.txt').write_bytes(b'replacement bytes') + dest = B2Folder(bucket.name, '', b2api) + started, release, scheduled, delete_started = Event(), Event(), Event(), Event() + errors = [] + real_upload = dest.bucket.concatenate + + def wait_for_upload(*args, **kwargs): + started.set() + assert release.wait(10), 'upload was not released' + return real_upload(*args, **kwargs) + + monkeypatch.setattr(dest.bucket, 'concatenate', wait_for_upload) + sync = Synchronizer( + max_workers=4, + keep_days_or_delete=KeepOrDeleteMode.DELETE, + compare_version_mode=CompareVersionMode.SIZE, + ) + + original_actions = sync._make_folder_sync_actions + original_delete = B2DeleteAction.run + + def tracked_actions(*args, **kwargs): + yield from original_actions(*args, **kwargs) + scheduled.set() + + def tracked_delete(self, *args, **kwargs): + delete_started.set() + return original_delete(self, *args, **kwargs) + + monkeypatch.setattr(sync, '_make_folder_sync_actions', tracked_actions) + monkeypatch.setattr(B2DeleteAction, 'run', tracked_delete) + + def run_sync(): + try: + sync.sync_folders(LocalFolder(tmp_path), dest, int(time.time() * 1000), None) + except Exception as exc: + errors.append(exc) + + thread = Thread(target=run_sync) + thread.start() + try: + assert started.wait(10), 'upload did not start' + assert scheduled.wait(10), 'scheduler did not finish' + assert not delete_started.wait(0.3), 'delete ran while upload was blocked' + assert [v.id_ for v in bucket.list_file_versions('file.txt')] == [old_id] + finally: + release.set() + thread.join(10) + assert not thread.is_alive() + assert not errors + assert old_id not in {v.id_ for v in bucket.list_file_versions('file.txt')} + + +def test_failed_upload_does_not_block_another_file(tmp_path, b2api, bucket, monkeypatch): + failed_id = bucket.upload_bytes(b'old', 'a.txt').id_ + other_id = bucket.upload_bytes(b'old', 'b.txt').id_ + (tmp_path / 'a.txt').write_bytes(b'new contents') + (tmp_path / 'b.txt').write_bytes(b'new contents') + dest = B2Folder(bucket.name, '', b2api) + original = dest.bucket.concatenate + + def fail_one(sources, name, *args, **kwargs): + if name == 'a.txt': + raise RuntimeError('replacement failed') + return original(sources, name, *args, **kwargs) + + monkeypatch.setattr(dest.bucket, 'concatenate', fail_one) + sync = Synchronizer( + max_workers=2, + keep_days_or_delete=KeepOrDeleteMode.DELETE, + compare_version_mode=CompareVersionMode.SIZE, + ) + with pytest.raises(IncompleteSync): + sync.sync_folders(LocalFolder(tmp_path), dest, int(time.time() * 1000), None) + assert {v.id_ for v in bucket.list_file_versions('a.txt')} == {failed_id} + other_versions = list(bucket.list_file_versions('b.txt')) + assert len(other_versions) == 1 + assert other_versions[0].id_ != other_id + assert other_versions[0].size == len(b'new contents') + + +def test_failed_copy_preserves_old_versions(b2api, bucket, monkeypatch): + source_bucket = b2api.create_bucket('source-bucket', 'allPublic') + source_bucket.upload_bytes(b'replacement contents', 'file.txt') + old_ids = {bucket.upload_bytes(data, 'file.txt').id_ for data in (b'old', b'older')} + source = B2Folder(source_bucket.name, '', b2api) + dest = B2Folder(bucket.name, '', b2api) + + def fail_copy(*args, **kwargs): + raise RuntimeError('copy failed') + + monkeypatch.setattr(dest.bucket, 'copy', fail_copy) + sync = Synchronizer( + max_workers=2, + keep_days_or_delete=KeepOrDeleteMode.DELETE, + compare_version_mode=CompareVersionMode.SIZE, + ) + with pytest.raises(IncompleteSync): + sync.sync_folders(source, dest, int(time.time() * 1000), None) + assert {v.id_ for v in bucket.list_file_versions('file.txt')} == old_ids + + +def test_blocked_transfer_does_not_starve_unrelated_file(tmp_path, b2api, bucket, monkeypatch): + from threading import Event, Thread + + for content in (b'old', b'older', b'oldest'): + bucket.upload_bytes(content, 'a.txt') + (tmp_path / 'a.txt').write_bytes(b'replacement contents') + (tmp_path / 'b.txt').write_bytes(b'unrelated contents') + dest = B2Folder(bucket.name, '', b2api) + started, release, other_done = Event(), Event(), Event() + errors = [] + original = dest.bucket.concatenate + + def upload(sources, name, *args, **kwargs): + if name == 'a.txt': + started.set() + assert release.wait(10), 'blocked upload was not released' + result = original(sources, name, *args, **kwargs) + if name == 'b.txt': + other_done.set() + return result + + monkeypatch.setattr(dest.bucket, 'concatenate', upload) + sync = Synchronizer( + max_workers=2, + keep_days_or_delete=KeepOrDeleteMode.DELETE, + compare_version_mode=CompareVersionMode.SIZE, + ) + + def run_sync(): + try: + sync.sync_folders(LocalFolder(tmp_path), dest, int(time.time() * 1000), None) + except Exception as exc: + errors.append(exc) + + thread = Thread(target=run_sync) + thread.start() + try: + assert started.wait(10), 'first upload did not start' + assert other_done.wait(2), 'unrelated upload was starved by cleanup tasks' + finally: + release.set() + thread.join(10) + assert not thread.is_alive() + assert not errors + + +def test_ready_cleanup_is_bounded_during_enumeration(tmp_path, b2api, bucket, monkeypatch): + import itertools + import queue + from types import SimpleNamespace + + import b2sdk._internal.sync.sync as sync_module + + b2api.session.raw_api.bucket_id_to_bucket[bucket.id_].upload_url_counter = itertools.count() + max_ready = [] + + class TrackedQueue(queue.SimpleQueue): + def put(self, item): + super().put(item) + max_ready.append(self.qsize()) + + monkeypatch.setattr( + sync_module, 'queue', SimpleNamespace(SimpleQueue=TrackedQueue, Empty=queue.Empty) + ) + old_ids = set() + for index in range(1010): + name = f'{index:04}.txt' + old_ids.add(bucket.upload_bytes(b'old', name).id_) + (tmp_path / name).write_bytes(b'new content') + + sync = Synchronizer( + max_workers=1, + keep_days_or_delete=KeepOrDeleteMode.DELETE, + compare_version_mode=CompareVersionMode.SIZE, + ) + original_actions = sync._make_folder_sync_actions + + def slow_actions(*args, **kwargs): + for action in original_actions(*args, **kwargs): + is_transfer = vars(action).get('_sync_transfer') is None + yield action + if is_transfer: + action._sync_future.result(timeout=10) + + monkeypatch.setattr(sync, '_make_folder_sync_actions', slow_actions) + sync.sync_folders( + LocalFolder(tmp_path), B2Folder(bucket.name, '', b2api), int(time.time() * 1000), None + ) + assert max_ready + assert max(max_ready) <= 1 + remaining_ids = {version.id_ for version, _ in bucket.ls('', latest_only=False, recursive=True)} + assert len(old_ids) == 1010 + assert not old_ids.intersection(remaining_ids) + + +@pytest.mark.parametrize('fail', [False, True]) +def test_pending_cleanup_backpressure_with_one_worker(tmp_path, b2api, bucket, monkeypatch, fail): + import itertools + from threading import Event, Thread + + b2api.session.raw_api.bucket_id_to_bucket[bucket.id_].upload_url_counter = itertools.count() + old_ids = {bucket.upload_bytes(b'old', 'file.txt').id_ for _ in range(1002)} + (tmp_path / 'file.txt').write_bytes(b'replacement contents') + dest = B2Folder(bucket.name, '', b2api) + started, release, at_limit, beyond_limit = Event(), Event(), Event(), Event() + original_upload = dest.bucket.concatenate + errors = [] + + def blocked_upload(*args, **kwargs): + started.set() + assert release.wait(10), 'upload was not released' + if fail: + raise RuntimeError('replacement failed') + return original_upload(*args, **kwargs) + + monkeypatch.setattr(dest.bucket, 'concatenate', blocked_upload) + sync = Synchronizer( + max_workers=1, + keep_days_or_delete=KeepOrDeleteMode.DELETE, + compare_version_mode=CompareVersionMode.SIZE, + ) + original_actions = sync._make_folder_sync_actions + + def tracked_actions(*args, **kwargs): + count = 0 + for action in original_actions(*args, **kwargs): + if vars(action).get('_sync_transfer') is not None: + count += 1 + if count == 1001: + at_limit.set() + if count == 1002: + beyond_limit.set() + yield action + + monkeypatch.setattr(sync, '_make_folder_sync_actions', tracked_actions) + + def run_sync(): + try: + sync.sync_folders(LocalFolder(tmp_path), dest, int(time.time() * 1000), None) + except Exception as exc: + errors.append(exc) + + thread = Thread(target=run_sync, daemon=True) + thread.start() + try: + assert started.wait(10) + assert at_limit.wait(10), 'scheduler did not reach the bound' + assert not beyond_limit.wait(0.3), 'scheduler exceeded the dependency bound' + finally: + release.set() + thread.join(10) + assert not thread.is_alive(), 'sync deadlocked after transfer completion' + remaining = {v.id_ for v in bucket.list_file_versions('file.txt')} + if fail: + assert len(errors) == 1 and isinstance(errors[0], IncompleteSync) + assert remaining == old_ids + else: + assert not errors + assert len(remaining) == 1 and not remaining.intersection(old_ids) From 8bc0e70d0632438919a90b5cd126447c2cf7461a Mon Sep 17 00:00:00 2001 From: Felipe Fumero Date: Wed, 25 Nov 2026 11:29:06 -0600 Subject: [PATCH 070/113] Do not delete excluded destination files during delete sync (#739) * fix: preserve excluded destination paths during sync Skip destination-only paths excluded by name or directory policy before planning actions. Keep destination scans unfiltered so metadata-based selection does not hide existing versions needed for comparison. * fix: honor destination exclusion policies during sync * fix: preserve excluded destination version histories Skip destination-only B2 paths when any version is excluded so deleting a newer version or hide marker cannot expose an excluded older version. --- b2sdk/_internal/sync/sync.py | 23 +- changelog.d/736.fixed.md | 1 + .../sync/test_excluded_destination_delete.py | 216 ++++++++++++++++++ test/unit/v0/test_sync.py | 1 - test/unit/v1/test_sync.py | 1 - 5 files changed, 239 insertions(+), 3 deletions(-) create mode 100644 changelog.d/736.fixed.md create mode 100644 test/unit/sync/test_excluded_destination_delete.py diff --git a/b2sdk/_internal/sync/sync.py b/b2sdk/_internal/sync/sync.py index 39bd8d18c..7fadcfb6d 100644 --- a/b2sdk/_internal/sync/sync.py +++ b/b2sdk/_internal/sync/sync.py @@ -14,12 +14,13 @@ import logging import queue from enum import Enum, unique +from pathlib import PurePosixPath from typing import cast from ..bounded_queue_executor import BoundedQueueExecutor from ..scan.exception import InvalidArgument from ..scan.folder import AbstractFolder, B2Folder, LocalFolder -from ..scan.path import AbstractPath +from ..scan.path import AbstractPath, B2Path, LocalPath from ..scan.policies import DEFAULT_SCAN_MANAGER, ScanPoliciesManager from ..scan.scan import zip_folders from ..transfer.outbound.upload_source import UploadMode @@ -319,6 +320,26 @@ def _make_folder_sync_actions( policies_manager, ): if source_path is None: + relative_path = dest_path.relative_path + exclude_directory = ( + policies_manager.should_exclude_b2_directory + if dest_type == 'b2' + else policies_manager.should_exclude_local_directory + ) + excluded = ( + any( + policies_manager.should_exclude_b2_file_version(version, relative_path) + for version in cast(B2Path, dest_path).all_versions + ) + if dest_type == 'b2' + else policies_manager.should_exclude_local_path(cast(LocalPath, dest_path)) + ) + if excluded or any( + exclude_directory(str(parent)) + for parent in PurePosixPath(relative_path).parents + if str(parent) != '.' + ): + continue logger.debug('determined that %s is not present on source', dest_path) elif dest_path is None: logger.debug('determined that %s is not present on destination', source_path) diff --git a/changelog.d/736.fixed.md b/changelog.d/736.fixed.md new file mode 100644 index 000000000..4604c1b16 --- /dev/null +++ b/changelog.d/736.fixed.md @@ -0,0 +1 @@ +Preserve destination-only paths during sync deletion when excluded by name or directory, or when any B2 version is excluded by a time policy. diff --git a/test/unit/sync/test_excluded_destination_delete.py b/test/unit/sync/test_excluded_destination_delete.py new file mode 100644 index 000000000..4a6c0c7b5 --- /dev/null +++ b/test/unit/sync/test_excluded_destination_delete.py @@ -0,0 +1,216 @@ +###################################################################### +# +# File: test/unit/sync/test_excluded_destination_delete.py +# +# Copyright 2026 Backblaze Inc. All Rights Reserved. +# +# License https://www.backblaze.com/using_b2_code.html +# +###################################################################### +from unittest import mock + +import pytest +from apiver_deps import KeepOrDeleteMode, ScanPoliciesManager + +from ..fixtures.folder import * # noqa: F403 +from .fixtures import * # noqa: F403 + + +@pytest.mark.apiver(from_ver=3) +@pytest.mark.parametrize('src_type,dst_type', [('local', 'b2'), ('b2', 'local'), ('b2', 'b2')]) +@pytest.mark.parametrize('source_has_excluded', [False, True]) +def test_delete_sync_preserves_excluded_destination_files( + folder_factory, synchronizer_factory, src_type, dst_type, source_has_excluded +): + source = folder_factory(src_type, *([('secret.txt', [100])] if source_has_excluded else [])) + destination = folder_factory(dst_type, ('secret.txt', [100]), ('remove.txt', [100])) + policy = ScanPoliciesManager(exclude_file_regexes=[r'secret\.txt$']) + synchronizer = synchronizer_factory(keep_days_or_delete=KeepOrDeleteMode.DELETE) + actions = list( + synchronizer._make_folder_sync_actions( + source, destination, 1000, mock.MagicMock(), policies_manager=policy + ) + ) + descriptions = [str(action) for action in actions] + assert len(descriptions) == 1 + assert 'remove.txt' in descriptions[0] + assert all('secret.txt' not in item for item in descriptions) + + +@pytest.mark.apiver(from_ver=3) +@pytest.mark.parametrize('dst_type', ['local', 'b2']) +def test_delete_sync_preserves_excluded_directory_and_honors_include( + folder_factory, synchronizer_factory, dst_type +): + source = folder_factory('b2') + destination = folder_factory( + dst_type, ('private/nested/secret.txt', [100]), ('keep.txt', [100]), ('remove.txt', [100]) + ) + policy = ScanPoliciesManager( + exclude_dir_regexes=[r'private$'], + exclude_file_regexes=[r'.*'], + include_file_regexes=[r'remove\.txt$'], + ) + synchronizer = synchronizer_factory(keep_days_or_delete=KeepOrDeleteMode.DELETE) + actions = list( + synchronizer._make_folder_sync_actions( + source, destination, 1000, mock.MagicMock(), policies_manager=policy + ) + ) + descriptions = [str(action) for action in actions] + assert len(descriptions) == 1 + assert 'remove.txt' in descriptions[0] + + +@pytest.mark.apiver(from_ver=3) +def test_destination_time_filter_does_not_hide_existing_file(folder_factory, synchronizer_factory): + source = folder_factory('local', ('a.txt', [200])) + destination = folder_factory('b2', ('a.txt', [100])) + policy = ScanPoliciesManager(exclude_modified_before=150) + synchronizer = synchronizer_factory(keep_days_or_delete=KeepOrDeleteMode.DELETE) + actions = list( + synchronizer._make_folder_sync_actions( + source, destination, 1000, mock.MagicMock(), policies_manager=policy + ) + ) + assert [str(action) for action in actions] == [ + 'b2_upload(/dir/a.txt, folder/a.txt, 200)', + 'b2_delete(folder/a.txt, id_a_100, (old version))', + ] + + +@pytest.mark.apiver(from_ver=3) +def test_local_delete_directory_exclusion_uses_posix_separators( + folder_factory, synchronizer_factory, monkeypatch +): + from pathlib import PureWindowsPath + + from b2sdk._internal.sync import sync as sync_module + + monkeypatch.setattr(sync_module, 'Path', PureWindowsPath, raising=False) + source = folder_factory('b2') + destination = folder_factory( + 'local', ('private/nested/secret.txt', [100]), ('remove.txt', [100]) + ) + policy = ScanPoliciesManager(exclude_dir_regexes=[r'private/nested$']) + synchronizer = synchronizer_factory(keep_days_or_delete=KeepOrDeleteMode.DELETE) + actions = list( + synchronizer._make_folder_sync_actions( + source, destination, 1000, mock.MagicMock(), policies_manager=policy + ) + ) + assert len(actions) == 1 + assert 'remove.txt' in str(actions[0]) + + +@pytest.mark.apiver(from_ver=3) +@pytest.mark.parametrize('dst_type', ['local', 'b2']) +def test_delete_sync_directory_only_exclusion(folder_factory, synchronizer_factory, dst_type): + source = folder_factory('b2') + destination = folder_factory( + dst_type, ('private/nested/secret.txt', [100]), ('remove.txt', [100]) + ) + policy = ScanPoliciesManager(exclude_dir_regexes=[r'private$']) + synchronizer = synchronizer_factory(keep_days_or_delete=KeepOrDeleteMode.DELETE) + actions = list( + synchronizer._make_folder_sync_actions( + source, destination, 1000, mock.MagicMock(), policies_manager=policy + ) + ) + expected = ( + 'local_delete(/dir/remove.txt)' + if dst_type == 'local' + else 'b2_delete(folder/remove.txt, id_r_100, )' + ) + assert [str(action) for action in actions] == [expected] + + +@pytest.mark.apiver(from_ver=3) +@pytest.mark.parametrize( + 'policy_kwargs,excluded_time,included_time', + [({'exclude_modified_before': 150}, 100, 200), ({'exclude_modified_after': 150}, 200, 100)], + ids=['before', 'after'], +) +def test_local_destination_only_respects_modified_time( + folder_factory, synchronizer_factory, policy_kwargs, excluded_time, included_time +): + source = folder_factory('b2') + destination = folder_factory( + 'local', ('excluded.txt', [excluded_time]), ('remove.txt', [included_time]) + ) + synchronizer = synchronizer_factory(keep_days_or_delete=KeepOrDeleteMode.DELETE) + actions = list( + synchronizer._make_folder_sync_actions( + source, + destination, + 1000, + mock.MagicMock(), + policies_manager=ScanPoliciesManager(**policy_kwargs), + ) + ) + assert len(actions) == 1 + assert 'remove.txt' in str(actions[0]) + + +@pytest.mark.apiver(from_ver=3) +@pytest.mark.parametrize( + 'policy_kwargs,excluded_time,included_time', + [ + ({'exclude_modified_before': 150}, 100, 200), + ({'exclude_modified_after': 150}, 200, 100), + ({'exclude_uploaded_before': 150}, 100, 200), + ({'exclude_uploaded_after': 150}, 200, 100), + ], + ids=['modified-before', 'modified-after', 'uploaded-before', 'uploaded-after'], +) +def test_b2_destination_only_respects_time( + folder_factory, synchronizer_factory, policy_kwargs, excluded_time, included_time +): + source = folder_factory('local') + destination = folder_factory( + 'b2', ('excluded.txt', [excluded_time]), ('remove.txt', [included_time]) + ) + synchronizer = synchronizer_factory(keep_days_or_delete=KeepOrDeleteMode.DELETE) + actions = list( + synchronizer._make_folder_sync_actions( + source, + destination, + 1000, + mock.MagicMock(), + policies_manager=ScanPoliciesManager(**policy_kwargs), + ) + ) + assert len(actions) == 1 + assert 'remove.txt' in str(actions[0]) + + +@pytest.mark.apiver(from_ver=3) +def test_b2_destination_only_preserves_time_excluded_older_version( + folder_factory, synchronizer_factory +): + source = folder_factory('local') + destination = folder_factory('b2', ('file.txt', [200, 100])) + policy = ScanPoliciesManager(exclude_modified_before=150) + synchronizer = synchronizer_factory(keep_days_or_delete=KeepOrDeleteMode.DELETE) + actions = list( + synchronizer._make_folder_sync_actions( + source, destination, 1000, mock.MagicMock(), policies_manager=policy + ) + ) + assert [str(action) for action in actions] == [] + + +@pytest.mark.apiver(from_ver=3) +def test_b2_destination_only_does_not_delete_hide_marker_above_excluded_version( + folder_factory, synchronizer_factory +): + source = folder_factory('local') + destination = folder_factory('b2', ('file.txt', [-200, 100])) + policy = ScanPoliciesManager(exclude_modified_before=150) + synchronizer = synchronizer_factory(keep_days_or_delete=KeepOrDeleteMode.DELETE) + actions = list( + synchronizer._make_folder_sync_actions( + source, destination, 1000, mock.MagicMock(), policies_manager=policy + ) + ) + assert [str(action) for action in actions] == [] diff --git a/test/unit/v0/test_sync.py b/test/unit/v0/test_sync.py index a4713053c..05bad9bfc 100644 --- a/test/unit/v0/test_sync.py +++ b/test/unit/v0/test_sync.py @@ -913,7 +913,6 @@ def _check_folder_sync(self, expected_actions, fakeargs): def test_file_exclusions_with_delete(self): expected_actions = [ 'b2_upload(/dir/a.txt, folder/a.txt, 100)', - 'b2_delete(folder/b.txt.incl, id_b_100, )', 'b2_delete(folder/c.txt, id_c_100, )', 'b2_upload(/dir/d/d.txt, folder/d/d.txt, 100)', 'b2_upload(/dir/e/e.incl, folder/e/e.incl, 100)', diff --git a/test/unit/v1/test_sync.py b/test/unit/v1/test_sync.py index cf51bd433..78bfada54 100644 --- a/test/unit/v1/test_sync.py +++ b/test/unit/v1/test_sync.py @@ -929,7 +929,6 @@ def _check_folder_sync(self, expected_actions, fakeargs): def test_file_exclusions_with_delete(self): expected_actions = [ 'b2_upload(/dir/a.txt, folder/a.txt, 100)', - 'b2_delete(folder/b.txt.incl, id_b_100, )', 'b2_delete(folder/c.txt, id_c_100, )', 'b2_upload(/dir/d/d.txt, folder/d/d.txt, 100)', 'b2_upload(/dir/e/e.incl, folder/e/e.incl, 100)', From c36af3536f00ccf9e17e7135880344751e057d30 Mon Sep 17 00:00:00 2001 From: scarreras Date: Wed, 25 Nov 2026 17:44:03 -0300 Subject: [PATCH 071/113] test: tighten notification rule non-exposure tests Drop success-path cases that duplicate test_notification_rule_tracing.py or cannot fail, narrow pytest.raises to MissingAccountData/BadRequest, assert on the stable interpret_b2_error trace record, rename the validation path to the unserializable-request path, build secrets at runtime, and document in the module docstring what each case can and cannot detect. Co-Authored-By: Claude Sonnet 5.5 --- .../test_notification_rules_nonexposure.py | 91 ++++++++----------- 1 file changed, 38 insertions(+), 53 deletions(-) diff --git a/test/unit/bucket/test_notification_rules_nonexposure.py b/test/unit/bucket/test_notification_rules_nonexposure.py index 7d664019d..406f763db 100644 --- a/test/unit/bucket/test_notification_rules_nonexposure.py +++ b/test/unit/bucket/test_notification_rules_nonexposure.py @@ -11,29 +11,33 @@ Operation-level secret non-exposure for ``Bucket.set_notification_rules``. A notification rule can carry an HMAC signing secret and a custom header value. Neither may -reach the SDK's DEBUG trace or the text of an exception raised by the call. - -There is one test per (surface, path); each is run once per sensitive input -(``signing_secret``, ``custom_header``) and asserts exactly that cell: - -* surfaces: SDK DEBUG trace (every ``logging`` record, with tracebacks, at DEBUG level; the SDK - traces little on the success, pre-authorization and validation paths, so those tests also - emit a marker record to prove the capture is live; on the API error path the SDK's own - records, including the HTTP error, are asserted to be present) and - exception text (message, repr and formatted traceback of whatever the call raised); -* paths: success (simulator-backed), failure before authorization, API error (a real - ``B2RawHTTPApi`` over a faked HTTP session answering 400), and a local validation error - (a request that cannot be serialized, raised before anything is sent). - -On the success path nothing is raised, so the success x exception test can only assert that the -call does not raise and that no exception text can carry the secret. It is weaker than the -failure-path exception tests and is documented as such rather than dressed up. +reach the SDK's DEBUG trace or the text of an exception raised by the call. Each test is run +once per sensitive input (``signing_secret``, ``custom_header``). + +What each case can and cannot detect: + +* API error path (``B2RawHTTPApi`` over a real ``B2Http``, only ``session.request`` faked to + answer 400): detects a leak anywhere in the SDK stack, including ``b2http`` and the raw API + (for example logging or raising with the request body). The debug test also requires the + SDK's own ``interpret_b2_error`` call record to be present, so it cannot pass on an empty + trace. It overlaps ``test_exception.py::test_http_error_trace_keeps_request_values_private`` + for log messages, but also covers formatted tracebacks (``caplog.text``); the exception test + is the only one asserting on exception text. +* Pre-authorization path and unserializable-request path: detect leaks in ``Bucket`` and + ``Session`` on a failure path (the pre-authorization case runs on ``RawSimulator``, so it + cannot see anything below ``Session``). The SDK logs almost nothing there, so the debug tests + emit a marker record to prove the capture is live; the marker does not prove the SDK + logging itself. +* Success path: not covered here. ``test_notification_rule_tracing.py`` already asserts that + ``set_notification_rules`` does not trace the secret on success, and a successful call + raises nothing, so an exception-text test there cannot fail. """ from __future__ import annotations import json import logging +import secrets import traceback import pytest @@ -45,12 +49,14 @@ InMemoryAccountInfo, RawSimulator, ) +from apiver_deps_exception import BadRequest, MissingAccountData from b2sdk._internal.b2http import B2Http +# Random per run, so no credential-shaped literal lives in the source. SECRET_VALUES = { - 'signing_secret': 'hmac-signing-secret-must-not-leak-4b1e', - 'custom_header': 'custom-header-value-must-not-leak-9d7c', + 'signing_secret': secrets.token_hex(16), + 'custom_header': secrets.token_urlsafe(24), } @@ -129,25 +135,13 @@ def unauthorized_bucket(): # ── SDK debug trace ────────────────────────────────────────────────────────── -@pytest.mark.parametrize('sensitive_input', ['signing_secret', 'custom_header']) -def test_sensitive_input_stays_out_of_sdk_debug_trace_on_success_path( - bucket, caplog, sensitive_input -): - with caplog.at_level(logging.DEBUG): - logging.getLogger('b2sdk').debug(CAPTURE_MARKER) - bucket.set_notification_rules(sensitive_rules()) - sdk_debug_trace = caplog.text - assert CAPTURE_MARKER in sdk_debug_trace # DEBUG capture works - assert SECRET_VALUES[sensitive_input] not in sdk_debug_trace - - @pytest.mark.parametrize('sensitive_input', ['signing_secret', 'custom_header']) def test_sensitive_input_stays_out_of_sdk_debug_trace_on_pre_authorization_path( unauthorized_bucket, caplog, sensitive_input ): with caplog.at_level(logging.DEBUG): logging.getLogger('b2sdk').debug(CAPTURE_MARKER) - with pytest.raises(Exception): + with pytest.raises(MissingAccountData): unauthorized_bucket.set_notification_rules(sensitive_rules()) sdk_debug_trace = caplog.text assert CAPTURE_MARKER in sdk_debug_trace # DEBUG capture works @@ -158,15 +152,21 @@ def test_sensitive_input_stays_out_of_sdk_debug_trace_on_pre_authorization_path( def test_sensitive_input_stays_out_of_sdk_debug_trace_on_api_error_path( http_rejecting_bucket, caplog, sensitive_input ): - with caplog.at_level(logging.DEBUG), pytest.raises(Exception): + with caplog.at_level(logging.DEBUG), pytest.raises(BadRequest): http_rejecting_bucket.set_notification_rules(sensitive_rules()) sdk_debug_trace = caplog.text - assert 'interpret_b2_error' in sdk_debug_trace # the SDK traced the service error itself + # the SDK's own trace record of the service error is present (stable logfury message) + assert any( + 'calling interpret_b2_error(' in record.getMessage() + and 'status=400' in record.getMessage() + and "code='bad_request'" in record.getMessage() + for record in caplog.records + ) assert SECRET_VALUES[sensitive_input] not in sdk_debug_trace @pytest.mark.parametrize('sensitive_input', ['signing_secret', 'custom_header']) -def test_sensitive_input_stays_out_of_sdk_debug_trace_on_validation_error_path( +def test_sensitive_input_stays_out_of_sdk_debug_trace_on_unserializable_request_path( http_rejecting_bucket, caplog, sensitive_input ): with caplog.at_level(logging.DEBUG): @@ -181,26 +181,11 @@ def test_sensitive_input_stays_out_of_sdk_debug_trace_on_validation_error_path( # ── exception text ─────────────────────────────────────────────────────────── -@pytest.mark.parametrize('sensitive_input', ['signing_secret', 'custom_header']) -def test_sensitive_input_stays_out_of_exception_on_success_path(bucket, sensitive_input): - # Weaker than the failure-path cells: a successful call raises nothing, so there is no - # exception text that could carry the secret. This pins that the call really does succeed - # (nothing raised) and that the exception text is therefore free of the secret. - raised = None - try: - bucket.set_notification_rules(sensitive_rules()) - except Exception as error: - raised = error - exception_text_of_call = '' if raised is None else exception_text(raised) - assert raised is None - assert SECRET_VALUES[sensitive_input] not in exception_text_of_call - - @pytest.mark.parametrize('sensitive_input', ['signing_secret', 'custom_header']) def test_sensitive_input_stays_out_of_exception_on_pre_authorization_path( unauthorized_bucket, sensitive_input ): - with pytest.raises(Exception) as excinfo: + with pytest.raises(MissingAccountData) as excinfo: unauthorized_bucket.set_notification_rules(sensitive_rules()) assert SECRET_VALUES[sensitive_input] not in exception_text(excinfo.value) @@ -209,14 +194,14 @@ def test_sensitive_input_stays_out_of_exception_on_pre_authorization_path( def test_sensitive_input_stays_out_of_exception_on_api_error_path( http_rejecting_bucket, sensitive_input ): - with pytest.raises(Exception) as excinfo: + with pytest.raises(BadRequest) as excinfo: http_rejecting_bucket.set_notification_rules(sensitive_rules()) assert SECRET_VALUES[sensitive_input] not in exception_text(excinfo.value) assert 'rejected by the service' in exception_text(excinfo.value) # the service error is real @pytest.mark.parametrize('sensitive_input', ['signing_secret', 'custom_header']) -def test_sensitive_input_stays_out_of_exception_on_validation_error_path( +def test_sensitive_input_stays_out_of_exception_on_unserializable_request_path( http_rejecting_bucket, sensitive_input ): with pytest.raises(TypeError) as excinfo: From 7dca1a6275b70883554b2e4f37310e8df0abb457 Mon Sep 17 00:00:00 2001 From: Sophie <49928680+sophiecarreras@users.noreply.github.com> Date: Thu, 26 Nov 2026 01:38:59 -0300 Subject: [PATCH 072/113] test: check documented imports in doc/source/api pages too documentation_files() used DOC_SOURCE.glob('*.rst'), which skipped the API reference pages under doc/source/api/, so 9 documented imports (account_info, exception, progress, sync) were never checked. Use rglob, and add a test that every .rst page with a Python example is scanned. Co-Authored-By: Claude Opus 5.5 --- test/unit/test_documentation_examples.py | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/test/unit/test_documentation_examples.py b/test/unit/test_documentation_examples.py index ca062c850..95b889800 100644 --- a/test/unit/test_documentation_examples.py +++ b/test/unit/test_documentation_examples.py @@ -107,7 +107,7 @@ def assert_import_resolves(statement: str) -> None: def documentation_files() -> list[pathlib.Path]: - return [REPO_ROOT / 'README.md', *sorted(DOC_SOURCE.glob('*.rst'))] + return [REPO_ROOT / 'README.md', *sorted(DOC_SOURCE.rglob('*.rst'))] class TestExtraction: @@ -161,6 +161,18 @@ def _documented_imports() -> list: return params +def test_every_doc_page_with_python_examples_is_scanned(): + # The API reference lives in subdirectories (doc/source/api/...); its examples count too. + scanned = {path.relative_to(REPO_ROOT).as_posix() for path in documentation_files()} + with_examples = { + path.relative_to(REPO_ROOT).as_posix() + for path in DOC_SOURCE.rglob('*.rst') + if extract_python_blocks(path.read_text(encoding='utf-8')) + } + assert 'doc/source/api/exception.rst' in with_examples + assert with_examples - scanned == set() + + def test_documentation_contains_examples_to_validate(): # Guard against the extraction silently matching nothing (e.g. after a docs reformat). assert len(_documented_imports()) >= 10 From 3fd75b9ef2195e1c83f10b6530ccb13d84f6f4ad Mon Sep 17 00:00:00 2001 From: Sophie <49928680+sophiecarreras@users.noreply.github.com> Date: Thu, 26 Nov 2026 01:40:01 -0300 Subject: [PATCH 073/113] changelog: notification-rule non-exposure tests do not cover the success path The fragment listed the success path, but the test module deliberately leaves it to test_notification_rule_tracing.py. Make the fragment say so. Co-Authored-By: Claude Opus 5.5 --- .../+notification-rules-nonexposure-tests.infrastructure.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/changelog.d/+notification-rules-nonexposure-tests.infrastructure.md b/changelog.d/+notification-rules-nonexposure-tests.infrastructure.md index 7c2a330d9..bf4a6affe 100644 --- a/changelog.d/+notification-rules-nonexposure-tests.infrastructure.md +++ b/changelog.d/+notification-rules-nonexposure-tests.infrastructure.md @@ -1 +1 @@ -Add unit tests asserting that the signing secret and custom header value of a notification rule never appear in the SDK DEBUG trace or in exception text raised by `Bucket.set_notification_rules`, on the success, pre-authorization, API error and validation error paths. +Add unit tests asserting that the signing secret and custom header value of a notification rule never appear in the SDK DEBUG trace or in exception text raised by `Bucket.set_notification_rules`, on the pre-authorization, API error and validation error paths (the success path is already covered by `test_notification_rule_tracing.py`). From 61318960565e198b4f5788d85f07bef937728cc6 Mon Sep 17 00:00:00 2001 From: Sophie <49928680+sophiecarreras@users.noreply.github.com> Date: Thu, 26 Nov 2026 01:40:01 -0300 Subject: [PATCH 074/113] test: check each B2Http entry point uses its own timeout setting All four class timeouts were the same 0.3 s, so the tests showed each call is bounded but not by which setting. Give CONNECTION_TIMEOUT, TIMEOUT, TIMEOUT_FOR_COPY and TIMEOUT_FOR_UPLOAD distinct values and assert the (connect, read) timeout each call passes to the real session: request, post_content_return_json and head_content use TIMEOUT_FOR_UPLOAD, post_json_return_json uses TIMEOUT_FOR_COPY, get_content uses TIMEOUT, and an explicit _timeout wins. Co-Authored-By: Claude Opus 5.5 --- test/unit/b2http/test_outbound_timeouts.py | 39 ++++++++++++++++------ 1 file changed, 28 insertions(+), 11 deletions(-) diff --git a/test/unit/b2http/test_outbound_timeouts.py b/test/unit/b2http/test_outbound_timeouts.py index 4fcf3135b..27503a56e 100644 --- a/test/unit/b2http/test_outbound_timeouts.py +++ b/test/unit/b2http/test_outbound_timeouts.py @@ -31,7 +31,11 @@ from b2sdk._internal.api_config import B2HttpApiConfig from b2sdk._internal.b2http import B2Http +# Distinct values, so each entry point can be checked against the setting it should use. +CONNECTION_TIMEOUT_SECONDS = 0.2 TIMEOUT_SECONDS = 0.3 +TIMEOUT_FOR_COPY_SECONDS = 0.4 +TIMEOUT_FOR_UPLOAD_SECONDS = 0.5 # Generous ceiling that still proves the call was bounded by the timeout, not by luck. MAX_ELAPSED_SECONDS = 10.0 @@ -42,10 +46,10 @@ class ShortTimeoutB2Http(B2Http): """B2Http with every class-level timeout shrunk so a hung server is detected quickly.""" - CONNECTION_TIMEOUT = TIMEOUT_SECONDS + CONNECTION_TIMEOUT = CONNECTION_TIMEOUT_SECONDS TIMEOUT = TIMEOUT_SECONDS - TIMEOUT_FOR_COPY = TIMEOUT_SECONDS - TIMEOUT_FOR_UPLOAD = TIMEOUT_SECONDS + TIMEOUT_FOR_COPY = TIMEOUT_FOR_COPY_SECONDS + TIMEOUT_FOR_UPLOAD = TIMEOUT_FOR_UPLOAD_SECONDS @pytest.fixture @@ -80,6 +84,15 @@ def accept_and_hold(): @pytest.fixture def b2_http(): http = ShortTimeoutB2Http(B2HttpApiConfig(install_clock_skew_hook=False)) + # Record the ``timeout`` each call hands to the real session; the request still goes out. + http.recorded_timeouts = [] + real_request = http.session.request + + def recording_request(*args, **kwargs): + http.recorded_timeouts.append(kwargs.get('timeout')) + return real_request(*args, **kwargs) + + http.session.request = recording_request try: yield http finally: @@ -107,17 +120,19 @@ def _head_content(http, url): @pytest.mark.parametrize( - 'call', + 'call, read_timeout', [ - pytest.param(_request, id='request'), - pytest.param(_post_content_return_json, id='post_content_return_json'), - pytest.param(_post_json_return_json, id='post_json_return_json'), - pytest.param(_get_content, id='get_content'), - pytest.param(_head_content, id='head_content'), + pytest.param(_request, TIMEOUT_FOR_UPLOAD_SECONDS, id='request'), + pytest.param( + _post_content_return_json, TIMEOUT_FOR_UPLOAD_SECONDS, id='post_content_return_json' + ), + pytest.param(_post_json_return_json, TIMEOUT_FOR_COPY_SECONDS, id='post_json_return_json'), + pytest.param(_get_content, TIMEOUT_SECONDS, id='get_content'), + pytest.param(_head_content, TIMEOUT_FOR_UPLOAD_SECONDS, id='head_content'), ], ) def test_unresponsive_server_raises_request_timeout_within_bound( - call, b2_http, unresponsive_server_url + call, read_timeout, b2_http, unresponsive_server_url ): started = time.monotonic() # The tuple only admits the raw requests timeout so that the stricter isinstance @@ -127,7 +142,8 @@ def test_unresponsive_server_raises_request_timeout_within_bound( elapsed = time.monotonic() - started assert isinstance(raised.value, B2RequestTimeout), 'timeout was not translated to a B2Error' - assert elapsed >= TIMEOUT_SECONDS * 0.5, 'call failed before the timeout could have expired' + assert b2_http.recorded_timeouts == [(CONNECTION_TIMEOUT_SECONDS, read_timeout)] + assert elapsed >= read_timeout * 0.5, 'call failed before the timeout could have expired' assert elapsed < MAX_ELAPSED_SECONDS, f'call was not bounded by its timeout: {elapsed:.1f}s' @@ -137,4 +153,5 @@ def test_explicit_request_timeout_overrides_default_bound(b2_http, unresponsive_ started = time.monotonic() with pytest.raises(B2RequestTimeout): b2_http.request('GET', unresponsive_server_url, headers={}, try_count=1, _timeout=0.3) + assert b2_http.recorded_timeouts == [(CONNECTION_TIMEOUT_SECONDS, 0.3)] assert time.monotonic() - started < MAX_ELAPSED_SECONDS From cb69c689d1c5b1e16b5a5cbe1cf52ec9d60e796c Mon Sep 17 00:00:00 2001 From: Felipe Fumero Date: Thu, 26 Nov 2026 15:04:46 -0600 Subject: [PATCH 075/113] docs: add a writing style guide for contributors (#755) Give contributors consistent wording and terminology guidance while preserving the meaning of SDK documentation and docstrings. --- CONTRIBUTING.md | 1 + changelog.d/741.doc.md | 1 + docs/writing-style.md | 64 ++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 66 insertions(+) create mode 100644 changelog.d/741.doc.md create mode 100644 docs/writing-style.md diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 3c3ee9d32..fc9fd7575 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -25,6 +25,7 @@ Integration tests need real B2 credentials; see the published guide for details. ## Before you open a pull request +* Follow the [writing style guide](docs/writing-style.md) for documentation and docstrings. * **Add a changelog entry.** Every PR needs at least one news fragment in `changelog.d`, or CI will fail. Name it `{issue_number}.{type}.md` (e.g. `157.fixed.md`) when the PR closes an issue, or `+{unique_string}.{type}.md` (e.g. `+foobar.fixed.md`) otherwise. Valid types are `fixed`, `changed`, diff --git a/changelog.d/741.doc.md b/changelog.d/741.doc.md new file mode 100644 index 000000000..ff76bc75b --- /dev/null +++ b/changelog.d/741.doc.md @@ -0,0 +1 @@ +Add a writing style guide for SDK documentation and docstrings. diff --git a/docs/writing-style.md b/docs/writing-style.md new file mode 100644 index 000000000..1539db332 --- /dev/null +++ b/docs/writing-style.md @@ -0,0 +1,64 @@ +Applies to documentation in this repository, including the Sphinx tree in `doc/`, and to Python docstrings. + +# Writing style + +Use this guide for new and edited documentation and docstrings. Do not apply it to +`CHANGELOG.md`, `changelog.d/` fragments, or dated records. These rules are inspired by +ASD-STE100 and are written for this project; they are not the standard. + +## Rules + +1. Put one idea in each sentence. +2. Prefer active voice and name the person or component performing the action. +3. Write procedure steps as commands, with one action per step. +4. Use one term for each meaning. Follow the term table below. +5. Choose simple verbs such as use, send, start, and stop. +6. Keep articles such as “a”, “an”, and “the” where they make a sentence clear. +7. Use plain words and remove intensifiers that add no meaning. +8. Repeat a noun when a pronoun could refer to more than one thing. +9. Use “must” for a requirement, “can” for an ability, and “should” for a recommendation. +10. Put the condition before the action. +11. Give exact numbers and units when they are known. Do not invent them. +12. Keep paragraphs short. Use a list for a sequence of steps. +13. Keep identifiers, flags, error strings, code, and URLs unchanged. +14. Change wording only; preserve the meaning of the original statement. + +## Terms + +Use the names in the public [`b2sdk.v3` exports](../b2sdk/v3/__init__.py) when referring to an API identifier. + +| Concept | Preferred wording | +| --- | --- | +| Storage container | Use “bucket”; the SDK exports `Bucket`. | +| Stored data | Use “file” for a named file and “file version” for a specific version; the SDK exports `FileVersion`. | +| Application credential | Use “application key” for an account credential; the SDK exports `ApplicationKey`. | +| Authorization | Use “authorization token” for a token used to authorize requests; distinguish it from an application key. | +| Customer-managed encryption | Use “SSE-C key” for the customer-managed encryption key; the SDK exports `EncryptionKey`. | +| Transfers | Use “upload” for sending data to B2 and “download” for receiving it from B2; `Bucket` has upload and download methods. | +| Data units | Use “part” for a large-file part, represented by `Part`; use “chunk” for a buffer or a piece of a stream. | +| Repeated requests | Use “attempt” for each try, including the first; use “retry” for an additional try after a failure. | + +## Check meaning before editing + +- Preserve numbers, units, and limits. +- Preserve whether a statement is a requirement, recommendation, or ability: “must”, “should”, and “can” are not interchangeable. +- Preserve security wording and credential requirements. +- Preserve compatibility, deprecation, and removal statements. +- Check claims against the code or the relevant contract. Flag a statement that cannot be verified; do not guess. + +## Examples from this repository + +[README.md](../README.md): + +- Before: “This repository contains a client library and a few handy utilities for easy access to all of the capabilities of B2 Cloud Storage.” +- After: “This repository contains a client library and a few handy utilities. They provide easy access to all capabilities of B2 Cloud Storage.” + +[doc/source/tutorial.rst](../doc/source/tutorial.rst): + +- Before: “With the ``info`` object in hand, we can now proceed to create a ``B2Api`` object.” +- After: “Use the ``info`` object to create a ``B2Api`` object.” + +[CONTRIBUTING.md](../CONTRIBUTING.md): + +- Before: “Integration tests need real B2 credentials; see the published guide for details.” +- After: “Integration tests need real B2 credentials. See the published guide for details.” From 1174f7d0ac97979dc7d131f2a7076e58612b2b1b Mon Sep 17 00:00:00 2001 From: Felipe Fumero Date: Thu, 26 Nov 2026 15:16:21 -0600 Subject: [PATCH 076/113] docs: add SDK documentation index (#756) Provide a concise map of SDK guides and API entry points, and check that repository links remain valid. --- changelog.d/742.doc.md | 1 + llms.txt | 33 +++++++++++++++++++++++++++++++++ test/static/test_llms_txt.py | 31 +++++++++++++++++++++++++++++++ 3 files changed, 65 insertions(+) create mode 100644 changelog.d/742.doc.md create mode 100644 llms.txt create mode 100644 test/static/test_llms_txt.py diff --git a/changelog.d/742.doc.md b/changelog.d/742.doc.md new file mode 100644 index 000000000..338638f4b --- /dev/null +++ b/changelog.d/742.doc.md @@ -0,0 +1 @@ +Add a documentation index for SDK entry points. diff --git a/llms.txt b/llms.txt new file mode 100644 index 000000000..64c2d0169 --- /dev/null +++ b/llms.txt @@ -0,0 +1,33 @@ +# B2 Python SDK + +> The B2 Python SDK provides Python interfaces for the Backblaze B2 Native API. + +## Start here + +- [README](https://github.com/Backblaze/b2-sdk-python/blob/master/README.md): Overview and entry points. +- [Install](https://b2-sdk-python.readthedocs.io/en/master/install.html): Install the SDK. +- [Quick start](https://b2-sdk-python.readthedocs.io/en/master/quick_start.html): Start using the SDK. +- [Tutorial](https://b2-sdk-python.readthedocs.io/en/master/tutorial.html): Follow a walkthrough. + +## Guides + +- [Advanced usage](https://b2-sdk-python.readthedocs.io/en/master/advanced.html): Explore advanced SDK usage. +- [Replication](https://github.com/Backblaze/b2-sdk-python/blob/master/doc/source/replication.rst): Configure replication. +- [Server-side encryption](https://b2-sdk-python.readthedocs.io/en/master/server_side_encryption.html): Use server-side encryption. + +## API reference + +- [B2Api](https://b2-sdk-python.readthedocs.io/en/master/api/api.html): Work with the B2 API. +- [Bucket](https://b2-sdk-python.readthedocs.io/en/master/api/bucket.html): Work with buckets and files. +- [Exceptions](https://b2-sdk-python.readthedocs.io/en/master/api/exception.html): Inspect SDK exceptions. +- [Raw simulator](https://b2-sdk-python.readthedocs.io/en/master/api/internal/raw_simulator.html): Explore the internal B2 simulator. + +## Contributing and testing + +- [Contributing](https://github.com/Backblaze/b2-sdk-python/blob/master/CONTRIBUTING.md): Find contribution and testing guidance. + +## Optional + +- [Changelog](https://github.com/Backblaze/b2-sdk-python/blob/master/CHANGELOG.md): Review release changes. +- [Security](https://github.com/Backblaze/b2-sdk-python/blob/master/SECURITY.md): Report security concerns. +- [Release process](https://github.com/Backblaze/b2-sdk-python/blob/master/README.release.md): Review release procedures. diff --git a/test/static/test_llms_txt.py b/test/static/test_llms_txt.py new file mode 100644 index 000000000..79c3e52e9 --- /dev/null +++ b/test/static/test_llms_txt.py @@ -0,0 +1,31 @@ +###################################################################### +# +# File: test/static/test_llms_txt.py +# +# Copyright 2026 Backblaze Inc. All Rights Reserved. +# +# License https://www.backblaze.com/using_b2_code.html +# +###################################################################### +import re +from pathlib import Path + +import pytest + +ROOT = Path(__file__).resolve().parents[2] +PREFIX = 'https://github.com/Backblaze/b2-sdk-python/blob/master/' + + +def check_repo_links(text, root): + for line_number, line in enumerate(text.splitlines(), 1): + for path in re.findall(re.escape(PREFIX) + r'([^\s)#]+)', line): + assert (root / path).is_file(), f'line {line_number}: missing {path}' + + +def test_llms_txt_repo_links(): + check_repo_links((ROOT / 'llms.txt').read_text(encoding='utf-8'), ROOT) + + +def test_missing_repo_link_is_rejected(tmp_path): + with pytest.raises(AssertionError, match='line 1: missing missing.md'): + check_repo_links(f'[missing]({PREFIX}missing.md)', tmp_path) From 5cf865bb4884aea71c18a94e773ecde73b4a742e Mon Sep 17 00:00:00 2001 From: Felipe Fumero Date: Thu, 26 Nov 2026 15:16:37 -0600 Subject: [PATCH 077/113] docs: correct bucket and large-file docstrings (#757) Clarify return types, CORS rules, pagination, wildcard paths, and inclusive download ranges so the API documentation matches the implementation. --- b2sdk/_internal/api.py | 2 +- b2sdk/_internal/bucket.py | 22 +++++++++++----------- b2sdk/_internal/large_file/services.py | 2 +- changelog.d/745.doc.md | 1 + 4 files changed, 14 insertions(+), 13 deletions(-) create mode 100644 changelog.d/745.doc.md diff --git a/b2sdk/_internal/api.py b/b2sdk/_internal/api.py index 8fa97547c..22f63c9d0 100644 --- a/b2sdk/_internal/api.py +++ b/b2sdk/_internal/api.py @@ -241,7 +241,7 @@ def create_bucket( :param str name: bucket name :param str bucket_type: a bucket type, could be one of the following values: ``"allPublic"``, ``"allPrivate"`` :param dict bucket_info: additional bucket info to store with the bucket - :param dict cors_rules: bucket CORS rules to store with the bucket + :param list[dict] cors_rules: bucket CORS rules to store with the bucket :param lifecycle_rules: bucket lifecycle rules to store with the bucket :param b2sdk.v2.EncryptionSetting default_server_side_encryption: default server side encryption settings (``None`` if unknown) :param bool is_file_lock_enabled: boolean value specifies whether bucket is File Lock-enabled diff --git a/b2sdk/_internal/bucket.py b/b2sdk/_internal/bucket.py index e3b3d30dc..b8fedd2bd 100644 --- a/b2sdk/_internal/bucket.py +++ b/b2sdk/_internal/bucket.py @@ -98,7 +98,7 @@ def __init__( :param str name: a bucket name :param str type_: a bucket type :param dict bucket_info: an info to store with a bucket - :param dict cors_rules: CORS rules to store with a bucket + :param list[dict] cors_rules: CORS rules to store with a bucket :param lifecycle_rules: lifecycle rules of the bucket :param int revision: a bucket revision number :param dict bucket_dict: a dictionary which contains bucket parameters @@ -199,7 +199,7 @@ def update( self, bucket_type: str | None = None, bucket_info: dict | None = None, - cors_rules: dict | None = None, + cors_rules: list[dict] | None = None, lifecycle_rules: list[LifecycleRule] | None = None, if_revision_is: int | None = None, default_server_side_encryption: EncryptionSetting | None = None, @@ -212,7 +212,7 @@ def update( :param bucket_type: a bucket type, e.g. ``allPrivate`` or ``allPublic`` :param bucket_info: an info to store with a bucket - :param cors_rules: CORS rules to store with a bucket + :param cors_rules: list of CORS rule dictionaries to store with a bucket :param lifecycle_rules: lifecycle rules to store with a bucket :param if_revision_is: revision number, update the info **only if** *revision* equals to *if_revision_is* :param default_server_side_encryption: default server side encryption settings (``None`` if unknown) @@ -261,7 +261,7 @@ def download_file_by_id( :param file_id: a file ID :param progress_listener: a progress listener object to use, or ``None`` to not track progress - :param range_: two integer values, start and end offsets + :param range_: two integer values, start and inclusive end offsets :param encryption: encryption settings (``None`` if unknown) """ return self.api.download_file_by_id( @@ -287,7 +287,7 @@ def download_file_by_name( :param file_name: a file name :param progress_listener: a progress listener object to use, or ``None`` to not track progress - :param range_: two integer values, start and end offsets + :param range_: two integer values, start and inclusive end offsets :param encryption: encryption settings (``None`` if unknown) """ url = self.api.session.get_download_url_by_name(self.name, file_name) @@ -302,8 +302,8 @@ def get_file_info_by_id(self, file_id: str) -> FileVersion: """ Gets a file version's by ID. - :param str file_id: the id of the file who's info will be retrieved. - :rtype: generator[b2sdk.v2.FileVersion] + :param str file_id: the id of the file whose info will be retrieved. + :rtype: b2sdk.v2.FileVersion """ return self.api.get_file_info(file_id) @@ -311,7 +311,7 @@ def get_file_info_by_name(self, file_name: str) -> DownloadVersion: """ Gets a file's DownloadVersion by name. - :param str file_name: the name of the file who's info will be retrieved. + :param str file_name: the name of the file whose info will be retrieved. """ try: return self.api.download_version_factory.from_response_headers( @@ -403,9 +403,9 @@ def ls( when ``True``, just returns info about the most recent versions :param recursive: if ``True``, list folders recursively :param fetch_count: how many entries to list per API call or ``None`` to use the default. Acceptable values: 1 - 10000 - :param with_wildcard: Accepts "*", "?", "[]" and "[!]" in folder_to_list, similarly to what shell does. + :param with_wildcard: Accepts "*", "?", "[]" and "[!]" in path, similarly to what shell does. As of 1.19.0 it can only be enabled when recursive is also enabled. - Also, in this mode, folder_to_list is considered to be a filename or a pattern. + Also, in this mode, path is considered to be a filename or a pattern. :param filters: list of filters to apply to the files returned by the server. :rtype: generator[tuple[b2sdk.v2.FileVersion, str]] :returns: generator of (file_version, folder_name) tuples @@ -549,7 +549,7 @@ def list_unfinished_large_files(self, start_file_id=None, batch_size=None, prefi unfinished large file in the bucket, starting at the given file, filtering by prefix. :param str,None start_file_id: a file ID to start from or None to start from the beginning - :param int,None batch_size: max file count + :param int,None batch_size: the number of files to fetch at a time from the server :param str,None prefix: file name prefix filter :rtype: generator[b2sdk.v2.UnfinishedLargeFile] """ diff --git a/b2sdk/_internal/large_file/services.py b/b2sdk/_internal/large_file/services.py index c03237ffb..a999fc8dc 100644 --- a/b2sdk/_internal/large_file/services.py +++ b/b2sdk/_internal/large_file/services.py @@ -49,7 +49,7 @@ def list_unfinished_large_files( :param str bucket_id: bucket id :param str,None start_file_id: a file ID to start from or None to start from the beginning - :param int,None batch_size: max file count + :param int,None batch_size: the number of files to fetch at a time from the server :param str,None prefix: file name prefix filter :rtype: generator[b2sdk.v2.UnfinishedLargeFile] """ diff --git a/changelog.d/745.doc.md b/changelog.d/745.doc.md new file mode 100644 index 000000000..16c309167 --- /dev/null +++ b/changelog.d/745.doc.md @@ -0,0 +1 @@ +Corrected bucket and large-file API docstrings to match their behavior. From 21151d60caff64ee8e42b739e9218be506dd3e46 Mon Sep 17 00:00:00 2001 From: Felipe Fumero Date: Thu, 26 Nov 2026 15:16:53 -0600 Subject: [PATCH 078/113] Correct sync and scan docstrings (#758) Describe the implemented sync defaults and scan policy methods so readers are not misled by outdated documentation. --- b2sdk/_internal/scan/policies.py | 15 ++++++++------- b2sdk/_internal/sync/sync.py | 13 +++++++++---- b2sdk/v0/sync.py | 8 ++++++-- changelog.d/746.doc.md | 1 + 4 files changed, 24 insertions(+), 13 deletions(-) create mode 100644 changelog.d/746.doc.md diff --git a/b2sdk/_internal/scan/policies.py b/b2sdk/_internal/scan/policies.py index 41575346a..0d5723643 100644 --- a/b2sdk/_internal/scan/policies.py +++ b/b2sdk/_internal/scan/policies.py @@ -113,13 +113,14 @@ class ScanPoliciesManager: Policy object used when scanning folders, used to decide which files to include in the list of files. - Code that scans through files should at least use should_exclude_file() - to decide whether each file should be included; it will check include/exclude - patterns for file names, as well as patterns for excluding directories. - - Code that scans may optionally use should_exclude_directory() to test whether - it can skip a directory completely and not bother listing the files and - sub-directories in it. + Use should_exclude_relative_path(), should_exclude_local_path(), or + should_exclude_b2_file_version() to filter files using file-name include + and exclude patterns. These checks assume their directories have already + been checked for exclusion. Use should_exclude_local_directory() or + should_exclude_b2_directory() to skip excluded directories without listing + their files and sub-directories. The v1 policy manager instead provides + should_exclude_file(), which checks both file-name include/exclude patterns + and directory-exclusion patterns, and should_exclude_directory(). """ def __init__( diff --git a/b2sdk/_internal/sync/sync.py b/b2sdk/_internal/sync/sync.py index 7fadcfb6d..f7e9d1474 100644 --- a/b2sdk/_internal/sync/sync.py +++ b/b2sdk/_internal/sync/sync.py @@ -76,7 +76,7 @@ class Synchronizer: - Fails when the specified source directory doesn't exist or is empty. (see ``allow_empty_source`` argument) - - Fails when the source is newer. + - Fails when a destination file is newer than its source file. (see ``newer_file_mode`` argument) - Doesn't delete a file if it's present on the destination but not on the source. (see ``keep_days_or_delete`` and ``keep_days`` arguments) @@ -109,7 +109,7 @@ def __init__( :param b2sdk.v2.NewerFileSyncMode newer_file_mode: setting which determines handling for destination files newer than on the source :param b2sdk.v2.KeepOrDeleteMode keep_days_or_delete: setting which determines if we should delete or not delete or keep for `keep_days` :param b2sdk.v2.CompareVersionMode compare_version_mode: how to compare the source and destination files to find new ones - :param int compare_threshold: should be greater than 0, default is 0 + :param int compare_threshold: must not be negative, default is 0 :param int keep_days: if keep_days_or_delete is `b2sdk.v2.KeepOrDeleteMode.KEEP_BEFORE_DELETE`, then this should be greater than 0 :param SyncPolicyManager sync_policy_manager: object which decides what to do with each file (upload, download, delete, copy, hide etc) :param b2sdk.v2.UploadMode upload_mode: determines how file uploads are handled @@ -172,8 +172,13 @@ def sync_folders( ): """ Syncs two folders. Always ensures that every file in the - source is also in the destination. Deletes any file versions - in the destination older than history_days. + source is also in the destination. By default, no files are deleted. + In DELETE mode, local destination files are removed when the source + file is absent or hidden. For B2 destinations, all existing versions + are removed if the source path is absent or a new version is transferred; + otherwise, only older versions are removed and the latest is kept. + KEEP_BEFORE_DELETE retains versions for the period specified by + keep_days before deletion. If scheduling fails, wait for already submitted actions to finish before propagating the scheduling error. diff --git a/b2sdk/v0/sync.py b/b2sdk/v0/sync.py index f2d3cca1b..60ad5d02f 100644 --- a/b2sdk/v0/sync.py +++ b/b2sdk/v0/sync.py @@ -172,8 +172,12 @@ def sync_folders( """ This is deprecated. Use the new Synchronizer class. - source is also in the destination. Deletes any file versions - in the destination older than history_days. + Ensures source files are also in the destination. By default, no files + are deleted. The delete option removes local destination files when the + source file is absent or hidden. For B2 destinations, it removes all + existing versions if the source path is absent or a new version is + transferred; otherwise, it removes older versions and keeps the latest. + The keepDays option retains versions for the specified period before deletion. :param source_folder: source folder object :type source_folder: b2sdk._internal.scan.folder.AbstractFolder diff --git a/changelog.d/746.doc.md b/changelog.d/746.doc.md new file mode 100644 index 000000000..a41ff7725 --- /dev/null +++ b/changelog.d/746.doc.md @@ -0,0 +1 @@ +Correct the sync and scan docstrings to match their current behavior. From 9a3036ed8e4449e3e80d77cb58b41d50e9396d5f Mon Sep 17 00:00:00 2001 From: Felipe Fumero Date: Thu, 26 Nov 2026 15:46:38 -0600 Subject: [PATCH 079/113] docs: link the B2 MCP server (#759) Help readers discover the Model Context Protocol server from the project entry points. --- README.md | 4 ++++ changelog.d/743.doc.md | 1 + llms.txt | 1 + 3 files changed, 6 insertions(+) create mode 100644 changelog.d/743.doc.md diff --git a/README.md b/README.md index 0f5841276..f891aae5c 100644 --- a/README.md +++ b/README.md @@ -38,6 +38,10 @@ b2sdk>=2,<3 Please refer to the [changelog](CHANGELOG.md). +# Related projects + +- **[b2-mcp](https://github.com/backblaze-labs/b2-mcp)** — a Model Context Protocol server for B2. + # Developer Info Please see our [contributing guidelines](CONTRIBUTING.md). diff --git a/changelog.d/743.doc.md b/changelog.d/743.doc.md new file mode 100644 index 000000000..30f3029e9 --- /dev/null +++ b/changelog.d/743.doc.md @@ -0,0 +1 @@ +Add a link to the B2 Model Context Protocol server in SDK documentation. diff --git a/llms.txt b/llms.txt index 64c2d0169..d465e0f6f 100644 --- a/llms.txt +++ b/llms.txt @@ -28,6 +28,7 @@ ## Optional +- [b2-mcp](https://github.com/backblaze-labs/b2-mcp): a Model Context Protocol server for B2. - [Changelog](https://github.com/Backblaze/b2-sdk-python/blob/master/CHANGELOG.md): Review release changes. - [Security](https://github.com/Backblaze/b2-sdk-python/blob/master/SECURITY.md): Report security concerns. - [Release process](https://github.com/Backblaze/b2-sdk-python/blob/master/README.release.md): Review release procedures. From f40cb527e1a1d3120d327d65d104031a0c23fe5e Mon Sep 17 00:00:00 2001 From: Felipe Fumero Date: Thu, 26 Nov 2026 15:47:00 -0600 Subject: [PATCH 080/113] docs: add SDK testing guide (#760) Explain the existing test levels and their limits so contributors can select checks and report evidence accurately. --- CONTRIBUTING.md | 1 + changelog.d/744.doc.md | 1 + docs/testing.md | 56 ++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 58 insertions(+) create mode 100644 changelog.d/744.doc.md create mode 100644 docs/testing.md diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index fc9fd7575..719daad3c 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -26,6 +26,7 @@ Integration tests need real B2 credentials; see the published guide for details. ## Before you open a pull request * Follow the [writing style guide](docs/writing-style.md) for documentation and docstrings. +* Use the [testing guide](docs/testing.md) to choose and report checks. * **Add a changelog entry.** Every PR needs at least one news fragment in `changelog.d`, or CI will fail. Name it `{issue_number}.{type}.md` (e.g. `157.fixed.md`) when the PR closes an issue, or `+{unique_string}.{type}.md` (e.g. `+foobar.fixed.md`) otherwise. Valid types are `fixed`, `changed`, diff --git a/changelog.d/744.doc.md b/changelog.d/744.doc.md new file mode 100644 index 000000000..9a4d08bb0 --- /dev/null +++ b/changelog.d/744.doc.md @@ -0,0 +1 @@ +Add a guide to the SDK test levels and verification practices. diff --git a/docs/testing.md b/docs/testing.md new file mode 100644 index 000000000..ca9e8a122 --- /dev/null +++ b/docs/testing.md @@ -0,0 +1,56 @@ +# Testing + +Run commands from the repository root. Install the tools described in [CONTRIBUTING.md](../CONTRIBUTING.md). +The examples use Python 3.13. Use `nox -l` to list the sessions for your installed versions. + +## Test levels + +| Where it lives | Command | What it proves | What it does not prove | +| --- | --- | --- | --- | +| [Unit](../test/unit) | `nox -s unit-3.13` | Runs the unit suite for each API version, v0 through v3. Tests that use [`RawSimulator`](../b2sdk/_internal/raw_simulator.py) exercise SDK behavior against an in-memory simulator. | It does not prove live B2 behavior. Not every unit test uses the simulator. | +| [Static](../test/static) | `nox -s lint` | Runs checks for Python license headers, workflow gates, JUnit reporting, documentation links, and other repository regressions. The session also runs Ruff and license checks. | It does not run unit or live B2 tests. | +| [Integration](../test/integration) | `nox -s integration-3.13` | Exercises SDK operations against live B2 when credentials are configured. | It does not cover every service behavior or every SDK path. | +| [sdkharness contract](../.sdkharness/README.md) | `SDKHARNESS_TEST_LEVEL=conformance SDKHARNESS_SCENARIO=files.upload .sdkharness/tests/run-conformance` | Exercises the selected contract against a loopback simulator. Follow the harness README to start the simulator and set its URL first. | It does not test live B2. | +| [Known defects](../test/known_defect.py) | `uv run --group test pytest --runxfail -m known_defect --api=v3 test/unit` | Runs marked defect checks as ordinary tests so their failures are visible. | It does not prove that unmarked behavior is correct. | + +The unit session selects each API version with the `--api` option. + +The integration fixture requires `B2_TEST_APPLICATION_KEY_ID` and `B2_TEST_APPLICATION_KEY`. +If either variable is unset, the credential fixture fails instead of skipping the test. +Run integration tests only with an appropriate test account. +The harness accepts a literal IPv4 loopback simulator URL and uses fixed test credentials. +It does not use real B2 credentials. See the harness README for setup and cleanup. + +The static test suite does not validate changelog fragments. Run `nox -s towncrier_check` for that check. + +## Known-defect tests + +Use `known_defect` to mark a test that asserts correct behavior for a defect that remains open. +Set `raises` to the expected failure type. Keep setup assertions separate from the defect assertion. +Use `expect` for the defect assertion when setup assertions must fail normally. +`expect` raises `DefectStillPresent` when the condition is false. +Use `defect_raises` to convert a specific exception and optional message into `DefectStillPresent`. +An unexpected exception remains a failure. + +The marker uses strict expected failure. If the test unexpectedly passes, pytest reports `XPASS(strict)` as a failure. +Remove the marker when the fix makes the test pass, and keep the test as a regression test. +See [issue #689](https://github.com/Backblaze/b2-sdk-python/issues/689) for an example involving stale demonstrators. + +## Showing a test pins the fix + +1. Write a test that asserts the expected behavior. +2. Run the test and observe the failure. +3. Implement the fix and run the test again. +4. Temporarily revert the fix and confirm that the test fails again. +5. Restore the fix and confirm that the test passes. + +## When a PR needs an integration test + +Use an integration test when a change depends on live B2 behavior that the simulator cannot establish. +Examples include a service response, authorization outcome, or server-side transfer behavior. +A simulator test can check how the SDK handles a modeled response; it cannot prove that B2 sends that response. + +## Reporting what you ran + +Report the commands and their outcomes. Report a check that did not run as **NOT RUN**, never as passed. +State whether integration or harness checks used live B2 or a simulator. From 0e2fc75c1f816153a7a8736ad140db6a0d664aba Mon Sep 17 00:00:00 2001 From: Felipe Fumero Date: Thu, 26 Nov 2026 15:47:25 -0600 Subject: [PATCH 081/113] docs: explain SDK errors and retries (#761) Explain exception handling and the separate HTTP and upload retry limits so callers can respond to failures safely. Record the checked source version and distinguish replay restrictions from retry eligibility. --- changelog.d/+errors-and-retries-guide.doc.md | 1 + doc/source/errors_and_retries.rst | 201 +++++++++++++++++++ doc/source/index.rst | 1 + llms.txt | 1 + 4 files changed, 204 insertions(+) create mode 100644 changelog.d/+errors-and-retries-guide.doc.md create mode 100644 doc/source/errors_and_retries.rst diff --git a/changelog.d/+errors-and-retries-guide.doc.md b/changelog.d/+errors-and-retries-guide.doc.md new file mode 100644 index 000000000..658d12bfb --- /dev/null +++ b/changelog.d/+errors-and-retries-guide.doc.md @@ -0,0 +1 @@ +Add a guide to SDK exception handling, HTTP retries, and upload retries. diff --git a/doc/source/errors_and_retries.rst b/doc/source/errors_and_retries.rst new file mode 100644 index 000000000..55a7dcbb1 --- /dev/null +++ b/doc/source/errors_and_retries.rst @@ -0,0 +1,201 @@ +Errors and retries +################## + +This guide describes SDK behavior checked at ``v2.13.5-70-g21151d60``. +The release baseline is ``v2.13.5``. +The checked revision includes unreleased changes after that release. +An installed release can have different retry behavior. + +Catch SDK errors +================ + +Import exceptions from ``b2sdk.v3.exception``. +``B2Error`` is the base class for the SDK exception hierarchy. +Catch a specific exception before you catch ``B2Error``. +Local file operations and argument validation can also raise standard Python exceptions. + +The exception families cover several kinds of failure: + +* Authorization errors include ``Unauthorized`` and its subclass ``InvalidAuthToken``. + ``NotAllowedByAppKeyError`` is the base class for application key restriction errors. +* Missing resource errors include ``FileNotPresent`` and ``NonExistentBucket``. +* Request and limit errors include ``BadRequest``, ``InvalidRange``, and ``StorageCapExceeded``. +* Temporary service and transport errors include ``ServiceError``, ``TooManyRequests``, + and ``B2RequestTimeout``. +* Transfer errors include ``ChecksumMismatch`` and ``MaxRetriesExceeded``. + +``interpret_b2_error`` maps server responses to exception classes. +The mapping uses the HTTP status, the B2 error code, and sometimes the message. +For example, HTTP 429 maps to ``TooManyRequests``. +HTTP 500 through 599 map to ``ServiceError``. +HTTP 408 maps to ``RequestTimeout``. +``B2RequestTimeout`` represents a client-side timeout instead of an HTTP 408 response. + +The following function accepts an authorized ``Bucket`` object. +See the :doc:`tutorial` for account authorization and bucket selection. +The SDK performs its automatic retries before the function catches the final error. + +.. code-block:: python + + from b2sdk.v3.exception import B2Error, MaxRetriesExceeded, Unauthorized + + + def upload_greeting(bucket): + try: + return bucket.upload_bytes(b"Hello from B2\n", "greeting.txt") + except MaxRetriesExceeded as error: + print(f"Upload stopped after {error.limit} attempts.") + raise + except Unauthorized: + print("Check the application key and its access permissions.") + raise + except B2Error: + print("The SDK could not complete the upload.") + raise + +Retry signals +============= + +``B2Error`` provides three retry signals: + +* ``should_retry_http()`` tells the HTTP retry loop whether an error permits another attempt. + The default is ``False``. +* ``should_retry_upload()`` tells the upload manager whether an error permits another upload attempt. + The default is ``False``. +* ``retry_after_seconds`` supplies a server-requested delay when available. + The default is ``None``. + +``TransientErrorMixin`` makes both retry methods return ``True``. +``ServiceError``, ``RequestTimeout``, and ``B2RequestTimeout`` use this mixin. +``TooManyRequests`` permits HTTP retries but does not permit upload-manager retries. +``BadUploadUrl``, ``BrokenPipe``, and ``ConnectionReset`` permit upload-manager retries +but do not permit HTTP retries. + +These signals do not guarantee another attempt. +The attempt limit, the request replay rules, and the location where the error occurs also matter. +For example, the upload manager checks a successful response's checksum outside its retry handler. +If that check raises ``ChecksumMismatch``, the error leaves the upload manager immediately. + +You can inspect the signals without making a request: + +.. code-block:: python + + from b2sdk.v3.exception import TooManyRequests + + error = TooManyRequests(retry_after_seconds="12") + assert error.should_retry_http() is True + assert error.should_retry_upload() is False + assert error.retry_after_seconds == 12 + +HTTP retries +============ + +Attempt limits +-------------- + +``B2Http._translate_and_retry`` makes at most ``try_count`` attempts. +The count includes the first attempt. +A value below 1 raises ``ValueError``. +The HTTP helpers use these defaults: + +.. list-table:: Default HTTP attempt limits + :header-rows: 1 + :widths: 45 35 20 + + * - Request helper + - Constant + - Attempts + * - Data requests, including upload data + - ``TRY_COUNT_DATA`` + - 20 + * - Download requests + - ``TRY_COUNT_DOWNLOAD`` + - 20 + * - HEAD requests + - ``TRY_COUNT_HEAD`` + - 5 + * - JSON POST requests + - ``TRY_COUNT_OTHER`` + - 5 + +These are HTTP helper defaults, not a limit for a complete SDK operation. +An operation can make several requests. +Upload-manager attempts can also contain HTTP retries. + +Before another attempt, the HTTP loop checks ``should_retry_http()``. +If the result is ``False``, the loop raises the error immediately. +The JSON POST replay rules below can also stop retries. +If the final attempt fails, the loop raises that attempt's translated exception. +HTTP retry exhaustion does not wrap the error in ``MaxRetriesExceeded``. + +Backoff and Retry-After +----------------------- + +Without a server-requested delay, the first retry waits 1 second. +After each wait, the loop multiplies the backoff by 1.5. +When the next backoff exceeds 64 seconds, the loop sets it to 64 seconds plus a random value +from 0 up to, but not including, 1 second. +The loop adds this jitter only when the backoff exceeds 64 seconds. + +For ``TooManyRequests`` and ``ServiceError``, the SDK parses the ``Retry-After`` response header. +The parser accepts integer delay-seconds and clamps the delay to 0 through 300 seconds. +It ignores HTTP-date values and invalid values. +If ``retry_after_seconds`` is not ``None``, that delay replaces the backoff for the current wait. +The loop still updates the backoff for the next retry. +A ``Retry-After`` value does not override the retry checks or the attempt limit. + +JSON POST replay rules +---------------------- + +A request can succeed on the server even when the client does not receive its response. +Repeating such a request can create another resource. +The SDK therefore limits automatic retries for JSON POST requests. + +``_REPLAYABLE_JSON_POST_ENDPOINTS`` identifies Native API operations that the HTTP layer +can repeat after an ambiguous failure. +Examples include ``b2_list_file_names``, ``b2_get_file_info``, and ``b2_delete_file_version``. +For these operations, an error must still permit HTTP retries. + +For create-style or unclassified JSON POST requests, ``_is_unapplied_error`` must also return ``True``. +This check accepts ``TooManyRequests`` and recognized connection-establishment failures +that occur before sending the request. +For example, ``b2_create_bucket``, ``b2_create_key``, ``b2_start_large_file``, +``b2_copy_file``, and ``b2_finish_large_file`` use this restriction. +For these operations, response timeouts, connection loss after sending, and HTTP 5xx responses +leave the HTTP retry loop immediately. +This includes HTTP 503 responses. + +After an ambiguous failure, check server state before you repeat the operation in your application. +A retry flag alone does not prove that repeating a request is safe. + +Upload retries +============== + +The upload manager has a separate retry loop for small files and for individual large-file parts. +``MAX_UPLOAD_ATTEMPTS`` is 5. +Each loop can therefore make 1 initial attempt and up to 4 retries. +This limit is not a limit of 5 HTTP requests for the whole file. + +If an upload attempt raises ``B2Error`` inside the retry handler, the upload manager checks +``should_retry_upload()``. +If the result is ``False``, the manager raises the error immediately. +Otherwise, the manager records the error and clears the bucket's cached upload URLs. +Examples of errors that permit another upload attempt include ``ServiceError``, +``B2RequestTimeout``, ``BadUploadUrl``, and ``Unauthorized``. +Some ``Unauthorized`` subclasses, such as ``EmailNotVerified`` and ``NoPaymentHistory``, +disable upload retries. + +The session returns an upload URL and its authorization token to the pool only after a successful request. +After a failed small-file attempt, the next attempt obtains a fresh upload URL when the bucket pool is empty. +Large-file parts use a separate pool. +A part retry can take another pooled URL or request a new URL if none is available. +An upload retry does not always make a new upload-URL request to the server. + +The upload-manager loop adds no delay of its own. +The HTTP layer can wait and retry within an upload attempt. +If all 5 upload attempts fail with errors that permit upload retries, the manager raises +``MaxRetriesExceeded``. +Its ``limit`` attribute holds the attempt limit. +Its ``exception_info_list`` attribute holds the errors recorded by the upload retry loop. + +See the :doc:`exception reference ` for individual exception classes. diff --git a/doc/source/index.rst b/doc/source/index.rst index 772ad9ada..1dc2dfec2 100644 --- a/doc/source/index.rst +++ b/doc/source/index.rst @@ -42,6 +42,7 @@ Documentation index server_side_encryption replication advanced + errors_and_retries glossary api_types api_reference diff --git a/llms.txt b/llms.txt index d465e0f6f..61baa79cb 100644 --- a/llms.txt +++ b/llms.txt @@ -12,6 +12,7 @@ ## Guides - [Advanced usage](https://b2-sdk-python.readthedocs.io/en/master/advanced.html): Explore advanced SDK usage. +- [Errors and retries](https://b2-sdk-python.readthedocs.io/en/master/errors_and_retries.html): Catch SDK errors and understand automatic retry behavior. - [Replication](https://github.com/Backblaze/b2-sdk-python/blob/master/doc/source/replication.rst): Configure replication. - [Server-side encryption](https://b2-sdk-python.readthedocs.io/en/master/server_side_encryption.html): Use server-side encryption. From b0f204c95a6b81762142db0d7a7795f24c1ccb4f Mon Sep 17 00:00:00 2001 From: Felipe Fumero Date: Thu, 26 Nov 2026 15:47:50 -0600 Subject: [PATCH 082/113] Clarify installation and quick start wording (#762) Use clearer prose and consistent terms so readers can follow the existing guidance more easily. --- ...+style-install-quick-start-tutorial.doc.md | 1 + doc/source/install.rst | 6 +++--- doc/source/quick_start.rst | 19 +++++++++---------- doc/source/tutorial.rst | 2 +- 4 files changed, 14 insertions(+), 14 deletions(-) create mode 100644 changelog.d/+style-install-quick-start-tutorial.doc.md diff --git a/changelog.d/+style-install-quick-start-tutorial.doc.md b/changelog.d/+style-install-quick-start-tutorial.doc.md new file mode 100644 index 000000000..785eb1f2d --- /dev/null +++ b/changelog.d/+style-install-quick-start-tutorial.doc.md @@ -0,0 +1 @@ +Improve the wording of the installation, quick start, and tutorial guides. diff --git a/doc/source/install.rst b/doc/source/install.rst index 1b2d75ea1..caade11f7 100644 --- a/doc/source/install.rst +++ b/doc/source/install.rst @@ -5,7 +5,7 @@ Installation Guide Installing as a dependency ========================== -**b2sdk** can simply be added to ``requirements.txt`` (or equivalent such as ``setup.py``, ``.pipfile`` etc). +You can add **b2sdk** to ``requirements.txt`` (or equivalent such as ``setup.py``, ``.pipfile`` etc). In order to properly set a dependency, see :ref:`versioning chapter ` for details. .. note:: @@ -20,8 +20,8 @@ in your python environment:: pip install -e . -The ``-e`` flag installs the package in editable mode, so changes you make to the source -are picked up without reinstalling. Running ``pip install b2sdk`` instead would download +The ``-e`` flag installs the package in editable mode, so the package reflects your source +changes without reinstalling. Running ``pip install b2sdk`` instead would download the published release from PyPI and ignore your local changes. The project uses `nox `_ and diff --git a/doc/source/quick_start.rst b/doc/source/quick_start.rst index 2950ea88c..215fde223 100644 --- a/doc/source/quick_start.rst +++ b/doc/source/quick_start.rst @@ -79,12 +79,12 @@ Synchronization To learn more about sync, see :ref:`sync`. Sync uses an encryption provider. In principle, it's a mapping between file metadata (bucket_name, file_info, etc) and -`EncryptionSetting`. The reason for employing such a mapping, rather than a single `EncryptionSetting`, is the fact that -users of Sync do not necessarily know up front what files it's going to upload and download. This approach enables using -unique keys, or key identifiers, across files. This is covered in greater detail in :ref:`server_side_encryption`. +`EncryptionSetting`. Users of Sync do not necessarily know in advance which files it will upload and download. +A mapping allows for this uncertainty, unlike a single `EncryptionSetting`. This approach enables using +unique keys, or key identifiers, across files. For more detail, see :ref:`server_side_encryption`. -In the example above, Sync will assume `SSE-B2` for all files in `bucket1`, `SSE-C` with the key provided for `bucket2` -and rely on bucket default for `bucket3`. Should developers need to provide keys per file (and not per bucket), they +In the example above, Sync will assume `SSE-B2` for all files in `bucket1`. +It will use `SSE-C` with the provided key for `bucket2` and rely on the bucket default for `bucket3`. Should developers need to provide keys per file (and not per bucket), they need to implement their own :class:`b2sdk.v3.AbstractSyncEncryptionSettingsProvider`. ************** @@ -370,8 +370,8 @@ Copy file If the ``content length`` is not provided and the file is larger than 5GB, ``copy`` would not succeed and error would be raised. If length is provided, then the file may be copied as a large file. Maximum copy part size can be set by ``max_copy_part_size`` - if not set, it will default to 5GB. If ``max_copy_part_size`` is lower than :term:`absoluteMinimumPartSize`, file would be copied in single request - this may be used to force copy in single request large file that fits in server small file limit. -Copying files allows for providing encryption settings for both source and destination files - `SSE-C` encrypted source files -cannot be used unless the proper key is provided. +When copying files, you can provide encryption settings for both source and destination files. +You cannot use `SSE-C` encrypted source files without the proper key. If you want to copy just the part of the file, then you can specify the offset and content length: @@ -414,11 +414,10 @@ Cancel large file uploads Direct file operations ********************** -Methods for manipulating object (file) state mentioned in sections above are low level and useful when users have access +The file state methods described above are low level. They are useful when users have access to basic information, like file id and name. Many API methods, however, return python objects representing files (:class:`b2sdk.v3.FileVersion` and :class:`b2sdk.v3.DownloadVersion`), that provide high-level access to methods -manipulating their state. As a rule, these methods don't change properties of python objects they are called on, but -return new objects instead. +manipulating their state. As a rule, these methods return new objects instead of changing the properties of the python objects they are called on. Obtain file representing objects ================================ diff --git a/doc/source/tutorial.rst b/doc/source/tutorial.rst index 3e19e21d4..523d9ad9b 100644 --- a/doc/source/tutorial.rst +++ b/doc/source/tutorial.rst @@ -6,7 +6,7 @@ Tutorial AccountInfo *************************** -``AccountInfo`` object holds information about access keys, tokens, upload urls, as well as a bucket id-name map. +``AccountInfo`` object holds information about application keys, tokens, upload urls, as well as a bucket id-name map. It is the first object that you need to create to use **b2sdk**. Using ``AccountInfo``, we'll be able to create a ``B2Api`` object to manage a B2 account. From 2e258fe5a310a0d1297590df7728bd08de7818fe Mon Sep 17 00:00:00 2001 From: Felipe Fumero Date: Thu, 26 Nov 2026 16:13:55 -0600 Subject: [PATCH 083/113] docs: explain account info and authorization (#765) Help SDK users choose an account store and understand authorization and restricted keys. --- changelog.d/+account-info-guide.doc.md | 1 + doc/source/account_info.rst | 73 ++++++++++++++++++++++++++ doc/source/index.rst | 1 + llms.txt | 1 + 4 files changed, 76 insertions(+) create mode 100644 changelog.d/+account-info-guide.doc.md create mode 100644 doc/source/account_info.rst diff --git a/changelog.d/+account-info-guide.doc.md b/changelog.d/+account-info-guide.doc.md new file mode 100644 index 000000000..340721041 --- /dev/null +++ b/changelog.d/+account-info-guide.doc.md @@ -0,0 +1 @@ +Document account info stores and account authorization. diff --git a/doc/source/account_info.rst b/doc/source/account_info.rst new file mode 100644 index 000000000..a070e50bd --- /dev/null +++ b/doc/source/account_info.rst @@ -0,0 +1,73 @@ +Account info and authorization +############################## + +This guide describes SDK behavior checked at ``v2.13.5-74-gb0f204c9``. +An installed release may behave differently. + +Choose a store +============== + +Account info holds authorization data for a :class:`b2sdk.v3.B2Api` session. +It includes the account ID, application key ID and key, authorization token, +API and download URLs, realm, part sizes, and allowed capabilities and restrictions. +When no account info is supplied, ``B2Api`` uses ``SqliteAccountInfo``. + +* :class:`b2sdk.v3.AbstractAccountInfo` defines the account-info interface. Use a + concrete implementation or implement the interface for a custom store. +* :class:`b2sdk.v3.InMemoryAccountInfo` keeps account data and bucket name-to-ID + mappings in memory. Use it when persistence between processes is not needed. +* :class:`b2sdk.v3.SqliteAccountInfo` stores account data and bucket name-to-ID + mappings in a SQLite database. Use it to reuse stored account information across + processes. The database holds credentials; protect the file like a secret. +* :class:`b2sdk.v3.StubAccountInfo` is a test stub. It keeps account data in memory, + but its bucket-name lookup and bucket upload URL methods do not provide a cache. + It has a large-file upload URL pool. +* :class:`b2sdk.v3.UrlPoolAccountInfo` is an abstract base for stores that manage + bucket and large-file upload URL pools. It does not implement a complete store. + +The in-memory and SQLite implementations inherit upload URL pools from +``UrlPoolAccountInfo``. These pools are in memory, including for SQLite. +A separate ``cache`` object controls the bucket name cache used by ``B2Api``; +it need not be the account info store. + +SQLite location +=============== + +For a store without a profile, a truthy ``file_name`` takes precedence over the +``B2_ACCOUNT_INFO`` environment variable. If neither is supplied, an existing +``~/.b2_account_info`` takes precedence. Otherwise, on Linux and BSD, the SDK uses +``$XDG_CONFIG_HOME/b2/account_info``; if ``XDG_CONFIG_HOME`` is empty, it uses +``~/.config/b2/account_info``. If ``XDG_CONFIG_HOME`` is set on another platform, +the SDK also uses that location. Otherwise it uses ``~/.b2_account_info``. +Read ``store.filename`` for the resolved path instead of assuming a location. + +Authorize an account +==================== + +In v3, call ``B2Api.authorize_account(application_key_id, application_key, realm='production')``. +The call contacts the service and saves the response and key in account info. +Later SDK calls can use the saved authorization token and URLs without a separate +explicit authorization call. The session can reauthorize when needed. + +The following example uses the simulator and does not contact B2: + +.. code-block:: python + + from b2sdk.v3 import B2Api, B2HttpApiConfig, InMemoryAccountInfo, RawSimulator + + store = InMemoryAccountInfo() + api = B2Api(account_info=store, api_config=B2HttpApiConfig(_raw_api_class=RawSimulator)) + key_id, key = api.session.raw_api.create_account() + api.authorize_account(key_id, key) + bucket = api.create_bucket('example-bucket', 'allPrivate') + assert api.get_bucket_by_name('example-bucket').id_ == bucket.id_ + +Restricted application keys +=========================== + +An application key can limit capabilities, buckets, or a file name prefix. +The service enforces the key's allowed operations. For a bucket-restricted key, +``list_buckets`` requires a permitted bucket name or ID. Bucket lookups check the +allowed bucket names or IDs and can raise ``RestrictedBucket`` for a mismatch. +If an authorized key refers to a bucket that no longer has a name, authorization +raises ``RestrictedBucketMissing``. diff --git a/doc/source/index.rst b/doc/source/index.rst index 1dc2dfec2..930511dc2 100644 --- a/doc/source/index.rst +++ b/doc/source/index.rst @@ -43,6 +43,7 @@ Documentation index replication advanced errors_and_retries + account_info glossary api_types api_reference diff --git a/llms.txt b/llms.txt index 61baa79cb..d8267c708 100644 --- a/llms.txt +++ b/llms.txt @@ -15,6 +15,7 @@ - [Errors and retries](https://b2-sdk-python.readthedocs.io/en/master/errors_and_retries.html): Catch SDK errors and understand automatic retry behavior. - [Replication](https://github.com/Backblaze/b2-sdk-python/blob/master/doc/source/replication.rst): Configure replication. - [Server-side encryption](https://b2-sdk-python.readthedocs.io/en/master/server_side_encryption.html): Use server-side encryption. +- [Account info and authorization](https://b2-sdk-python.readthedocs.io/en/master/account_info.html): Choose a store and authorize an account. ## API reference From 3d5fbd3eb1a0ab97447a830fcae86c732a21c0ce Mon Sep 17 00:00:00 2001 From: Felipe Fumero Date: Thu, 26 Nov 2026 16:14:12 -0600 Subject: [PATCH 084/113] docs: clarify advanced usage and encryption guidance (#766) Improve selected passages while preserving the documented behavior and security recommendations. --- changelog.d/+style-advanced-sse.doc.md | 1 + doc/source/advanced.rst | 6 +++--- doc/source/server_side_encryption.rst | 8 +++----- 3 files changed, 7 insertions(+), 8 deletions(-) create mode 100644 changelog.d/+style-advanced-sse.doc.md diff --git a/changelog.d/+style-advanced-sse.doc.md b/changelog.d/+style-advanced-sse.doc.md new file mode 100644 index 000000000..469c838c7 --- /dev/null +++ b/changelog.d/+style-advanced-sse.doc.md @@ -0,0 +1 @@ +Improve wording in the advanced usage and server-side encryption guides. diff --git a/doc/source/advanced.rst b/doc/source/advanced.rst index 6e0d283b5..c42bf7857 100644 --- a/doc/source/advanced.rst +++ b/doc/source/advanced.rst @@ -6,7 +6,7 @@ Advanced usage patterns B2 server API allows for creation of an object from existing objects. This allows to avoid transferring data from the source machine if the desired outcome can be (at least partially) constructed from what is already on the server. -The way **b2sdk** exposes this functionality is through a few functions that allow the user to express the desired outcome and then the library takes care of planning and executing the work. Please refer to the table below to compare the support of object creation methods for various usage patterns. +**b2sdk** provides functions that let you specify the desired outcome. The library plans and executes the work. Use the table below to compare object creation methods for different usage patterns. ***************** Available methods @@ -43,7 +43,7 @@ Some methods support overlapping ranges between local and remote files. **b2sdk* Streaming interface =================== -Some object creation methods start writing data before reading the whole input (iterator). This can be used to write objects that do not have fully known contents without writing them first locally, so that they could be copied. Such usage pattern can be relevant to small devices which stream data to B2 from an external NAS, where caching large files such as media files or virtual machine images is not an option. +Some object creation methods start writing data before reading the whole input (iterator). You can use these methods to write objects without fully known contents without first writing them locally for copying. Such usage pattern can be relevant to small devices which stream data to B2 from an external NAS, where caching large files such as media files or virtual machine images is not an option. Please see :ref:`advanced method support table ` to see where streaming interface is supported. @@ -316,7 +316,7 @@ Continuation Continuation of upload ====================== -In order to continue a simple upload session, **b2sdk** checks for any available sessions with of the same ``file name``, ``file_info`` and ``media type``, verifying the size of an object as much as possible. +To continue a simple upload session, **b2sdk** checks available sessions for the same ``file name``, ``file_info`` and ``media type``. It verifies the object size as much as possible. To support automatic continuation, some advanced methods create a plan before starting copy/upload operations, saving the hash of that plan in ``file_info`` for increased reliability. diff --git a/doc/source/server_side_encryption.rst b/doc/source/server_side_encryption.rst index a20d1e687..5aedcbb7f 100644 --- a/doc/source/server_side_encryption.rst +++ b/doc/source/server_side_encryption.rst @@ -35,11 +35,9 @@ under `sse_c_key_id` in `fileInfo`. This allows developers to create key manager securely in a file or a database. Implementing such managers, and linking them to :class:`b2sdk.v3.AbstractSyncEncryptionSettingsProvider` implementations (necessary for using Sync) is outside of the scope of this library. -There is, however, a convention to such managers that authors of this library strongly suggest: if a manager needs to generate -a new key-key_id pair for uploading, it's best to commit this data to the underlying storage before commencing the upload. -The justification of such approach is: should the key-key_id pair be committed to permanent storage after completing an IO -operation, committing could fail after successfully upload the data. This data, however, is now just a random blob, that -can never be read, since the key to decrypting it is lost. +The library authors strongly suggest a convention for these managers. If a manager needs to generate a new key-key_id pair +for uploading, the library authors recommend committing the pair to storage before starting the upload. If the manager commits the pair after the I/O +operation, the commit could fail after the upload succeeds. The uploaded data can never be read if the decryption key is lost. This approach comes an overhead: to download a file, its `fileInfo` has to be known. This means that fetching metadata is required before downloading. From 8261554ef86c730bfc5bc6d4fb6a941f57c85d65 Mon Sep 17 00:00:00 2001 From: Felipe Fumero Date: Thu, 26 Nov 2026 16:14:29 -0600 Subject: [PATCH 085/113] docs: improve guide and support wording (#767) Clarify selected documentation sentences while preserving technical details and guidance. --- .github/SUPPORT.md | 6 +++--- README.md | 8 ++++---- .../+style-replication-api-types-glossary-readme.doc.md | 1 + doc/source/api_types.rst | 6 +++--- doc/source/glossary.rst | 2 +- doc/source/replication.rst | 9 ++++----- 6 files changed, 16 insertions(+), 16 deletions(-) create mode 100644 changelog.d/+style-replication-api-types-glossary-readme.doc.md diff --git a/.github/SUPPORT.md b/.github/SUPPORT.md index 8338bdd58..ec801f0b1 100644 --- a/.github/SUPPORT.md +++ b/.github/SUPPORT.md @@ -1,5 +1,5 @@ -Issues with **B2_Command_line_tool** (problems with the tool itself) should be reported at [B2 CLI issue tracker](https://github.com/Backblaze/B2_Command_Line_Tool/issues). +You should report issues with **B2_Command_line_tool** (problems with the tool itself) at [B2 CLI issue tracker](https://github.com/Backblaze/B2_Command_Line_Tool/issues). -Issues with **B2 cloud service** (not caused by B2 CLI or sdk) should be reported directly to [Backblaze support](https://help.backblaze.com/hc/en-us/requests/new). +You should report issues with **B2 cloud service** (not caused by B2 CLI or sdk) directly to [Backblaze support](https://help.backblaze.com/hc/en-us/requests/new). -Issues with the B2 python sdk should be reported in [b2-sdk-python issue tracker](https://github.com/Backblaze/b2-sdk-python/issues). This should be used by authors of tools that interact with the b2 cloud through **b2-sdk-python**, but also if an issue with some other project (that uses **b2-sdk-python**) is clearly caused by a bug in **b2-sdk-python**. +You should report issues with the B2 python sdk in [b2-sdk-python issue tracker](https://github.com/Backblaze/b2-sdk-python/issues). Authors of tools that interact with the b2 cloud through **b2-sdk-python** should use this tracker. You should also use it if a bug in **b2-sdk-python** clearly causes an issue in another project that uses **b2-sdk-python**. diff --git a/README.md b/README.md index f891aae5c..fa47a8c91 100644 --- a/README.md +++ b/README.md @@ -3,9 +3,9 @@ -This repository contains a client library and a few handy utilities for easy access to all of the capabilities of B2 Cloud Storage. +This repository contains a client library and a few handy utilities. They provide access to all capabilities of B2 Cloud Storage. -[B2 command-line tool](https://github.com/Backblaze/B2_Command_Line_Tool) is an example of how it can be used to provide command-line access to the B2 service, but there are many possible applications (including FUSE filesystems, storage backend drivers for backup applications etc). +[B2 command-line tool](https://github.com/Backblaze/B2_Command_Line_Tool) uses the library to provide command-line access to the B2 service. Other applications can include FUSE filesystems and storage backend drivers for backup applications. # Documentation @@ -13,7 +13,7 @@ The latest documentation is available on [Read the Docs](https://b2-sdk-python.r # Installation -The sdk can be installed with: +You can install the SDK with: pip install b2sdk @@ -28,7 +28,7 @@ b2sdk follows [Semantic Versioning](https://semver.org/) policy, so in essence t - we increase MINOR version when we add functionality in a backwards-compatible manner, and - we increase PATCH version when we make backwards-compatible bug fixes (unless someone relies on the undocumented behavior of a fixed bug) -Therefore when setting up b2sdk as a dependency, please make sure to match the version appropriately, for example you could put this in your `requirements.txt` to make sure your code is compatible with the `b2sdk` version your user will get from pypi: +When you add b2sdk as a dependency, choose a version range that matches your code. For example, you can put this in your `requirements.txt` to select a compatible `b2sdk` version from pypi: ``` b2sdk>=2,<3 diff --git a/changelog.d/+style-replication-api-types-glossary-readme.doc.md b/changelog.d/+style-replication-api-types-glossary-readme.doc.md new file mode 100644 index 000000000..e36d0572f --- /dev/null +++ b/changelog.d/+style-replication-api-types-glossary-readme.doc.md @@ -0,0 +1 @@ +Improve the writing style in the replication guide, API interface guide, glossary, README, and support instructions. diff --git a/doc/source/api_types.rst b/doc/source/api_types.rst index 86fc279c6..208e70d0d 100644 --- a/doc/source/api_types.rst +++ b/doc/source/api_types.rst @@ -36,7 +36,7 @@ It also means that **b2sdk** developers may change the interface in the future a Interface version compatibility ******************************* -A :term:`numbered interface` will not be exactly identical throughout its lifespan, which should not be a problem for anyone, however just in case, the acceptable differences that the developer must tolerate, are listed below. +A :term:`numbered interface` will not remain exactly identical throughout its lifespan. This should not be a problem. Developers must tolerate the acceptable differences listed below. Exceptions ========== @@ -48,7 +48,7 @@ Extensions Even in the same interface version, objects/classes/enums can get additional fields and their representations such as ``as_dict()`` or ``__repr__`` (but not ``__str__``) may start to contain those fields. -Methods and functions can start accepting new **optional** arguments. New methods can be added to existing classes. +Methods and functions can start accepting new **optional** arguments. The library can add new methods to existing classes. Performance =========== @@ -123,7 +123,7 @@ but that's a lot of work and we both know it's not going to happen). In practice permissive, but when considering whether to keep your patches private or public, please take into consideration the long-term cost of keeping up with a dynamic open-source project and/or the cost of missing the updates, especially those related to performance and reliability (as those are being actively developed in parallel to documentation). -Internal interface modules are listed in :ref:`API Internal ` section. +The :ref:`API Internal ` section lists internal interface modules. .. note:: It is OK for you to use our internal interface (better that than copying our source files!), however, if you do, please pin your dependencies to **middle** version, diff --git a/doc/source/glossary.rst b/doc/source/glossary.rst index d895a9329..d8ee79ee6 100644 --- a/doc/source/glossary.rst +++ b/doc/source/glossary.rst @@ -11,7 +11,7 @@ Glossary An identifier of the B2 account (not login). Looks like this: ``4ba5845d7aaf``. application key ID - Since every :term:`account ID` can have multiple access keys associated with it, the keys need to be distinguished from each other. :term:`application key ID` is an identifier of the access key. There are two types of keys: :term:`master application key` and :term:`non-master application key`. + Each :term:`account ID` can have multiple application keys. An :term:`application key ID` distinguishes application keys for the same account. There are two types of keys: :term:`master application key` and :term:`non-master application key`. application key The secret associated with an :term:`application key ID`, used to authenticate with the server. Looks like this: ``N2Zug0evLcHDlh_L0Z0AJhiGGdY`` or ``0a1bce5ea463a7e4b090ef5bd6bd82b851928ab2c6`` or ``K0014pbwo1zxcIVMnqSNTfWHReU/O3s`` diff --git a/doc/source/replication.rst b/doc/source/replication.rst index ebfd1fd16..4657673ef 100644 --- a/doc/source/replication.rst +++ b/doc/source/replication.rst @@ -9,7 +9,7 @@ bucket being copied *from* is the **source**; the bucket being copied *to* is th bucket may be both at once, and a source bucket may replicate to several destinations under different rules. -Replication is configured on the buckets, not on individual files: you attach a +You configure replication on the buckets, not on individual files. Attach a :class:`b2sdk.v3.ReplicationConfiguration` to each side, and B2 does the copying. The SDK's job is to help you write that configuration, create the application keys it needs, and inspect the outcome. @@ -175,8 +175,8 @@ Monitoring a rule >>> monitor = ReplicationMonitor(bucket=source_bucket, rule=rule) >>> report = monitor.scan() -The monitor scans the source and, by default, the matching files on the destination so it can compare -them. Pass ``scan_destination=False`` to look at the source alone, which is much cheaper. +By default, the monitor scans the source and matching files on the destination. It can then compare +them. Pass ``scan_destination=False`` to scan only the source, which is much cheaper. Two optional arguments matter in practice. ``destination_api`` takes a second :class:`b2sdk.v3.B2Api`, and is required when the destination bucket is on another account; omit it and @@ -214,8 +214,7 @@ side of the pair exists, or because the destination was not scanned. Interpreting partial results ============================ -A scan is a snapshot of a system that is still moving, so mixed results are normal rather than a sign of -failure: +A scan is a snapshot of a system that is still moving. Mixed results are normal. They are not a sign of failure: * **A destination file is missing entirely.** The destination fields are ``None``. Expected while a file is still ``PENDING``; worth investigating once the source reads ``COMPLETED``. From 5196c752ce707995f60b8e37e39f12426158b0a2 Mon Sep 17 00:00:00 2001 From: Sophie <49928680+sophiecarreras@users.noreply.github.com> Date: Fri, 27 Nov 2026 01:19:32 -0300 Subject: [PATCH 086/113] ci: run pull-request integration against B2 Simulator; live B2 weekly Pull requests and master pushes no longer receive B2 test credentials. A new Simulator Integration workflow runs the SDK integration suite against a pinned B2 Simulator revision, failing closed when the deploy key is missing or the PR comes from a fork. Real-B2 integration moves to a weekly and manual workflow that fails when live credentials are missing. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/ci.yml | 57 +----- .github/workflows/live-b2.yml | 46 +++++ .github/workflows/simulator-integration.yml | 104 ++++++++++ ...ulator-pr-weekly-live-b2.infrastructure.md | 1 + doc/source/contributing.rst | 16 +- docs/testing.md | 2 +- test/static/test_ci_draft_safety.py | 190 ++++-------------- 7 files changed, 197 insertions(+), 219 deletions(-) create mode 100644 .github/workflows/live-b2.yml create mode 100644 .github/workflows/simulator-integration.yml create mode 100644 changelog.d/+simulator-pr-weekly-live-b2.infrastructure.md diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index f2edcfd16..2f4a111ab 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -79,43 +79,10 @@ jobs: run: uv run nox -vs build - name: Check documentation example imports run: uv run nox -vs doc_examples - cleanup_buckets: - # Live B2 access requires explicit opt-in and is never allowed for drafts. - if: ${{ vars.B2_LIVE_TESTS_ENABLED == 'true' && (github.event_name != 'pull_request' || !github.event.pull_request.draft) }} - timeout-minutes: 30 - needs: lint - env: - B2_TEST_APPLICATION_KEY: ${{ (vars.B2_LIVE_TESTS_ENABLED == 'true' && (github.event_name != 'pull_request' || !github.event.pull_request.draft)) && secrets.B2_TEST_APPLICATION_KEY || '' }} - B2_TEST_APPLICATION_KEY_ID: ${{ (vars.B2_LIVE_TESTS_ENABLED == 'true' && (github.event_name != 'pull_request' || !github.event.pull_request.draft)) && secrets.B2_TEST_APPLICATION_KEY_ID || '' }} - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 - if: ${{ env.B2_TEST_APPLICATION_KEY != '' && env.B2_TEST_APPLICATION_KEY_ID != '' }} # TODO: skip this whole job instead - with: - fetch-depth: 0 - - name: Set up Python ${{ env.PYTHON_DEFAULT_VERSION }} - if: ${{ env.B2_TEST_APPLICATION_KEY != '' && env.B2_TEST_APPLICATION_KEY_ID != '' }} # TODO: skip this whole job instead - uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6 - with: - python-version: ${{ env.PYTHON_DEFAULT_VERSION }} - - uses: astral-sh/setup-uv@37802adc94f370d6bfd71619e3f0bf239e1f3b78 # v7 - if: ${{ env.B2_TEST_APPLICATION_KEY != '' && env.B2_TEST_APPLICATION_KEY_ID != '' }} # TODO: skip this whole job instead - with: - version: ${{ env.UV_VERSION }} - enable-cache: true - - name: Install dependencies - if: ${{ env.B2_TEST_APPLICATION_KEY != '' && env.B2_TEST_APPLICATION_KEY_ID != '' }} # TODO: skip this whole job instead - run: uv sync --only-group nox --locked - - name: Find and remove old buckets - if: ${{ env.B2_TEST_APPLICATION_KEY != '' && env.B2_TEST_APPLICATION_KEY_ID != '' }} # TODO: skip this whole job instead - run: uv run nox -vs cleanup_old_buckets test: timeout-minutes: 90 - needs: [lint, cleanup_buckets] - if: ${{ !cancelled() && needs.lint.result == 'success' && (needs.cleanup_buckets.result == 'success' || needs.cleanup_buckets.result == 'skipped') }} + needs: lint env: - B2_TEST_APPLICATION_KEY: ${{ (vars.B2_LIVE_TESTS_ENABLED == 'true' && (github.event_name != 'pull_request' || !github.event.pull_request.draft)) && secrets.B2_TEST_APPLICATION_KEY || '' }} - B2_TEST_APPLICATION_KEY_ID: ${{ (vars.B2_LIVE_TESTS_ENABLED == 'true' && (github.event_name != 'pull_request' || !github.event.pull_request.draft)) && secrets.B2_TEST_APPLICATION_KEY_ID || '' }} NOX_EXTRAS: ${{ matrix.extras }} runs-on: ${{ matrix.os }} strategy: @@ -149,16 +116,10 @@ jobs: run: uv sync --only-group nox --locked - name: Run unit tests run: uv run nox -vs unit -- -v - - name: Run integration tests - if: ${{ (vars.B2_LIVE_TESTS_ENABLED == 'true' && (github.event_name != 'pull_request' || !github.event.pull_request.draft)) && env.B2_TEST_APPLICATION_KEY != '' && env.B2_TEST_APPLICATION_KEY_ID != '' }} - run: uv run nox -vs integration -- --dont-cleanup-old-buckets -v cli-compat: timeout-minutes: 90 - needs: [lint, cleanup_buckets] - if: ${{ !cancelled() && needs.lint.result == 'success' && (needs.cleanup_buckets.result == 'success' || needs.cleanup_buckets.result == 'skipped') }} + needs: lint env: - B2_TEST_APPLICATION_KEY: ${{ (vars.B2_LIVE_TESTS_ENABLED == 'true' && (github.event_name != 'pull_request' || !github.event.pull_request.draft)) && secrets.B2_TEST_APPLICATION_KEY || '' }} - B2_TEST_APPLICATION_KEY_ID: ${{ (vars.B2_LIVE_TESTS_ENABLED == 'true' && (github.event_name != 'pull_request' || !github.event.pull_request.draft)) && secrets.B2_TEST_APPLICATION_KEY_ID || '' }} INSTALL_SDK_FROM: ../b2-sdk-python runs-on: ${{ matrix.os }} strategy: @@ -205,20 +166,6 @@ jobs: run: uv run --directory ./B2_Command_Line_Tool nox -vs unit -p ${{ matrix.python-version }} - name: Run CLI integration tests (without secrets) run: uv run --directory ./B2_Command_Line_Tool nox -vs integration -p ${{ matrix.python-version }} -- -m "not require_secrets" - - name: Run CLI integration tests (with secrets) - if: ${{ (vars.B2_LIVE_TESTS_ENABLED == 'true' && (github.event_name != 'pull_request' || !github.event.pull_request.draft)) && env.B2_TEST_APPLICATION_KEY != '' && env.B2_TEST_APPLICATION_KEY_ID != '' && matrix.os == 'ubuntu-latest' && matrix.python-version == '3.14' }} - working-directory: B2_Command_Line_Tool - run: | - export VIRTUAL_ENV="$PWD/.nox/integration-3-14" - export PATH="$VIRTUAL_ENV/bin:$PATH" - python -m pytest \ - test/integration \ - -n 1 \ - --log-level INFO \ - -W ignore::DeprecationWarning:rst2ansi.visitor: \ - -m "require_secrets" \ - --cleanup \ - --sut "$VIRTUAL_ENV/bin/b2v4" doc: timeout-minutes: 30 needs: build diff --git a/.github/workflows/live-b2.yml b/.github/workflows/live-b2.yml new file mode 100644 index 000000000..c4a9e26c5 --- /dev/null +++ b/.github/workflows/live-b2.yml @@ -0,0 +1,46 @@ +name: Weekly Live B2 Integration + +on: + schedule: + - cron: "15 7 * * 1" + workflow_dispatch: + +permissions: + contents: read + +env: + PYTHON_DEFAULT_VERSION: "3.14" + UV_VERSION: "0.13.4" + +jobs: + live-b2-integration: + runs-on: ubuntu-latest + timeout-minutes: 90 + env: + B2_TEST_APPLICATION_KEY_ID: ${{ secrets.B2_TEST_APPLICATION_KEY_ID }} + B2_TEST_APPLICATION_KEY: ${{ secrets.B2_TEST_APPLICATION_KEY }} + steps: + - name: Require live B2 credentials + run: | + if [ -z "$B2_TEST_APPLICATION_KEY_ID" ] || [ -z "$B2_TEST_APPLICATION_KEY" ]; then + echo "B2_TEST_APPLICATION_KEY_ID and B2_TEST_APPLICATION_KEY are required." + exit 1 + fi + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 + with: + fetch-depth: 0 + persist-credentials: false + - name: Set up Python ${{ env.PYTHON_DEFAULT_VERSION }} + uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6 + with: + python-version: ${{ env.PYTHON_DEFAULT_VERSION }} + - uses: astral-sh/setup-uv@37802adc94f370d6bfd71619e3f0bf239e1f3b78 # v7 + with: + version: ${{ env.UV_VERSION }} + enable-cache: true + - name: Install dependencies + run: uv sync --only-group nox --locked + - name: Remove stale test buckets + run: uv run nox -vs cleanup_old_buckets + - name: Test against live B2 + run: uv run nox -vs integration -p "$PYTHON_DEFAULT_VERSION" -- --dont-cleanup-old-buckets -v diff --git a/.github/workflows/simulator-integration.yml b/.github/workflows/simulator-integration.yml new file mode 100644 index 000000000..658df3b5d --- /dev/null +++ b/.github/workflows/simulator-integration.yml @@ -0,0 +1,104 @@ +name: Simulator Integration + +on: + push: + branches: [master] + pull_request: + types: [opened, synchronize, reopened, ready_for_review] + +permissions: + contents: read + +env: + PYTHON_DEFAULT_VERSION: "3.14" + UV_VERSION: "0.13.4" + SIMULATOR_REVISION: "529721037901412b7b24fdc18498631d298295c5" + +jobs: + simulator-access-policy: + runs-on: ubuntu-latest + timeout-minutes: 5 + steps: + - name: Require a trusted PR branch + env: + EVENT_NAME: ${{ github.event_name }} + HEAD_REPOSITORY: ${{ github.event.pull_request.head.repo.full_name || github.repository }} + run: | + if [ "$EVENT_NAME" = "pull_request" ] && [ "$HEAD_REPOSITORY" != "$GITHUB_REPOSITORY" ]; then + echo "Simulator testing is mandatory; use a branch in $GITHUB_REPOSITORY." + exit 1 + fi + + simulator-integration: + needs: simulator-access-policy + runs-on: ubuntu-latest + timeout-minutes: 90 + steps: + - name: Require the private Simulator deploy key + env: + SIMULATOR_DEPLOY_KEY: ${{ secrets.SIMULATOR_DEPLOY_KEY }} + run: | + if [ -z "$SIMULATOR_DEPLOY_KEY" ]; then + echo "SIMULATOR_DEPLOY_KEY is required because Simulator testing is mandatory." + exit 1 + fi + - name: Check out the SDK + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + fetch-depth: 0 + persist-credentials: false + path: sdk + - name: Check out the pinned private Simulator + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + repository: backblaze-labs/b2-simulator + ref: 529721037901412b7b24fdc18498631d298295c5 + ssh-key: ${{ secrets.SIMULATOR_DEPLOY_KEY }} + persist-credentials: false + path: simulator + - name: Verify the Simulator revision + run: | + test "$(git -C simulator rev-parse HEAD)" = "$SIMULATOR_REVISION" + test -z "$(git -C simulator status --short)" + - name: Set up Node.js 22 + uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 + with: + node-version: 22 + - name: Set up Python ${{ env.PYTHON_DEFAULT_VERSION }} + uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6 + with: + python-version: ${{ env.PYTHON_DEFAULT_VERSION }} + - uses: astral-sh/setup-uv@37802adc94f370d6bfd71619e3f0bf239e1f3b78 # v7 + with: + version: ${{ env.UV_VERSION }} + enable-cache: true + - name: Install dependencies + working-directory: sdk + run: uv sync --only-group nox --locked + - name: Test against Simulator + working-directory: sdk + env: + B2_TEST_APPLICATION_KEY_ID: sim-test-id + B2_TEST_APPLICATION_KEY: sim-test-secret + run: | + simulator_log="$RUNNER_TEMP/b2-simulator.log" + node ../simulator/bin/simulator/serve.mjs --custom-upload-timestamps >"$simulator_log" 2>&1 & + simulator_pid=$! + trap 'kill "$simulator_pid" 2>/dev/null || true; wait "$simulator_pid" 2>/dev/null || true' EXIT + + B2_TEST_ENVIRONMENT="" + for _ in $(seq 1 150); do + B2_TEST_ENVIRONMENT="$(sed -n 's|^SIMULATOR-LISTENING \(https://127\.0\.0\.1:[0-9][0-9]*\)$|\1|p' "$simulator_log" | head -1)" + if [ -n "$B2_TEST_ENVIRONMENT" ]; then break; fi + if ! kill -0 "$simulator_pid" 2>/dev/null; then cat "$simulator_log"; exit 1; fi + sleep 0.2 + done + if [ -z "$B2_TEST_ENVIRONMENT" ]; then cat "$simulator_log"; exit 1; fi + export B2_TEST_ENVIRONMENT + certifi_bundle="$(uv run python -c 'import certifi; print(certifi.where())')" + simulator_ca_bundle="$RUNNER_TEMP/b2-simulator-ca.pem" + cp "$certifi_bundle" "$simulator_ca_bundle" + cat "$GITHUB_WORKSPACE/simulator/bin/simulator/loopback-cert.pem" >>"$simulator_ca_bundle" + export REQUESTS_CA_BUNDLE="$simulator_ca_bundle" + export SSL_CERT_FILE="$simulator_ca_bundle" + uv run nox -vs integration -p "$PYTHON_DEFAULT_VERSION" -- --dont-cleanup-old-buckets -v diff --git a/changelog.d/+simulator-pr-weekly-live-b2.infrastructure.md b/changelog.d/+simulator-pr-weekly-live-b2.infrastructure.md new file mode 100644 index 000000000..8eb914618 --- /dev/null +++ b/changelog.d/+simulator-pr-weekly-live-b2.infrastructure.md @@ -0,0 +1 @@ +Run integration tests against the pinned B2 Simulator for pull requests, and run fail-closed real-B2 integration weekly or on manual dispatch. diff --git a/doc/source/contributing.rst b/doc/source/contributing.rst index 65259a820..eea5a0317 100644 --- a/doc/source/contributing.rst +++ b/doc/source/contributing.rst @@ -155,15 +155,13 @@ To run tests matching a keyword expression:: $ nox -s unit-3.10 -- -k keyword -Draft pull requests run credential-free checks. CI skips the bucket-cleanup job, -withholds B2 test credentials, and skips SDK and CLI live integration steps. -Unit and CLI compatibility jobs still run when cleanup is deliberately skipped; -failed lint or cleanup jobs continue to block them. Live tests, B2 credential -access and bucket cleanup also require the repository Actions variable -``B2_LIVE_TESTS_ENABLED`` to be explicitly set to ``true``. The default is off, -including ready pull requests and pushes to master. Enable that variable only -when live validation with an approved test account is intended; marking a pull -request ready or merging it does not itself enable live operations. +Pull requests and pushes to master never receive B2 test credentials. The +``Simulator Integration`` workflow runs the SDK integration suite against a pinned +revision of the B2 Simulator (``backblaze-labs/b2-simulator``) with fixed test +credentials. It fails if the Simulator cannot be checked out or started, and it +fails for pull requests from forks: push the branch to this repository instead. +The ``Weekly Live B2 Integration`` workflow runs the same suite against live B2 +every Monday and on manual dispatch. It fails if the live credentials are missing. JUnit reports include each subtest as its own case, as well as its parent test. The repository's ``test.junit_subtests`` compatibility plugin supplies those cases diff --git a/docs/testing.md b/docs/testing.md index ca9e8a122..21613e47a 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -9,7 +9,7 @@ The examples use Python 3.13. Use `nox -l` to list the sessions for your install | --- | --- | --- | --- | | [Unit](../test/unit) | `nox -s unit-3.13` | Runs the unit suite for each API version, v0 through v3. Tests that use [`RawSimulator`](../b2sdk/_internal/raw_simulator.py) exercise SDK behavior against an in-memory simulator. | It does not prove live B2 behavior. Not every unit test uses the simulator. | | [Static](../test/static) | `nox -s lint` | Runs checks for Python license headers, workflow gates, JUnit reporting, documentation links, and other repository regressions. The session also runs Ruff and license checks. | It does not run unit or live B2 tests. | -| [Integration](../test/integration) | `nox -s integration-3.13` | Exercises SDK operations against live B2 when credentials are configured. | It does not cover every service behavior or every SDK path. | +| [Integration](../test/integration) | `nox -s integration-3.13` | Exercises SDK operations against live B2 when credentials are configured. CI runs it against the B2 Simulator for pull requests and against live B2 weekly. | It does not cover every service behavior or every SDK path. | | [sdkharness contract](../.sdkharness/README.md) | `SDKHARNESS_TEST_LEVEL=conformance SDKHARNESS_SCENARIO=files.upload .sdkharness/tests/run-conformance` | Exercises the selected contract against a loopback simulator. Follow the harness README to start the simulator and set its URL first. | It does not test live B2. | | [Known defects](../test/known_defect.py) | `uv run --group test pytest --runxfail -m known_defect --api=v3 test/unit` | Runs marked defect checks as ordinary tests so their failures are visible. | It does not prove that unmarked behavior is correct. | diff --git a/test/static/test_ci_draft_safety.py b/test/static/test_ci_draft_safety.py index 8a4973940..267de484b 100644 --- a/test/static/test_ci_draft_safety.py +++ b/test/static/test_ci_draft_safety.py @@ -7,173 +7,55 @@ # License https://www.backblaze.com/using_b2_code.html # ###################################################################### -"""Exercise CI's draft, credential and dependency gates without running jobs.""" +"""Keep PR integration on Simulator and live B2 on a weekly/manual path.""" from __future__ import annotations -import ast import re from pathlib import Path -import pytest import yaml -JOBS = yaml.safe_load((Path(__file__).parents[2] / '.github/workflows/ci.yml').read_text())['jobs'] +ROOT = Path(__file__).parents[2] +CI_TEXT = (ROOT / '.github/workflows/ci.yml').read_text() +SIMULATOR_PATH = ROOT / '.github/workflows/simulator-integration.yml' +LIVE_PATH = ROOT / '.github/workflows/live-b2.yml' +KEYS = ('B2_TEST_APPLICATION_KEY', 'B2_TEST_APPLICATION_KEY_ID') -def expression(value, context): - """Evaluate only the boolean/string expression subset used by these gates. - - actionlint validates the complete workflow separately. Unknown contexts or - expression syntax fail this check rather than being assumed safe. - """ - if not isinstance(value, str) or not value.startswith('${{'): - return value - code = value[3:-2].strip().replace('cancelled()', repr(context['cancelled'])) - code = re.sub( - r'[a-zA-Z_][\w-]*(?:\.[a-zA-Z_][\w-]*)+', lambda match: repr(context[match.group()]), code - ) - code = code.replace('&&', ' and ').replace('||', ' or ') - code = re.sub(r'!(?!=)', 'not ', code) - code = re.sub(r'\btrue\b', 'True', code) - code = re.sub(r'\bfalse\b', 'False', code) - tree = ast.parse(code.strip(), mode='eval') - - def resolve(node): - if isinstance(node, ast.Constant) and isinstance(node.value, (str, bool)): - return node.value - if isinstance(node, ast.UnaryOp) and isinstance(node.op, ast.Not): - return not resolve(node.operand) - if isinstance(node, ast.BoolOp): - result = resolve(node.values[0]) - for child in node.values[1:]: - if isinstance(node.op, ast.And) and not result: - return result - if isinstance(node.op, ast.Or) and result: - return result - result = resolve(child) - return result - if isinstance(node, ast.Compare): - left = resolve(node.left) - for operator, child in zip(node.ops, node.comparators): - right = resolve(child) - assert isinstance(operator, (ast.Eq, ast.NotEq)), code - if (left == right) != isinstance(operator, ast.Eq): - return False - left = right - return True - raise AssertionError(f'Unsupported workflow expression: {code}') - - return resolve(tree.body) +def triggers(workflow): + return workflow.get('on', workflow.get(True)) -def context( - draft=True, - credentials=True, - event='pull_request', - lint='success', - cleanup='skipped', - live_enabled='true', -): - return { - 'github.event_name': event, - 'github.event.pull_request.draft': draft, - 'needs.lint.result': lint, - 'needs.cleanup_buckets.result': cleanup, - 'cancelled': False, - 'vars.B2_LIVE_TESTS_ENABLED': live_enabled, - 'secrets.B2_TEST_APPLICATION_KEY': 'test-key' if credentials else '', - 'secrets.B2_TEST_APPLICATION_KEY_ID': 'test-id' if credentials else '', - } +def test_regular_ci_cannot_use_real_b2_credentials(): + assert 'B2_LIVE_TESTS_ENABLED' not in CI_TEXT + for key in KEYS: + assert not re.search(rf'secrets\.{key}\b', CI_TEXT) -@pytest.mark.parametrize('credentials', [True, False]) -def test_draft_never_starts_bucket_cleanup(credentials): - assert not expression( - JOBS['cleanup_buckets'].get('if', '${{ true }}'), context(credentials=credentials) +def test_simulator_workflow_runs_on_every_pull_request_and_fails_closed(): + text = SIMULATOR_PATH.read_text() + workflow = yaml.safe_load(text) + events = triggers(workflow) + assert 'pull_request' in events + assert 'schedule' not in events + assert 'SIMULATOR_DEPLOY_KEY' in text + scripts = '\n'.join( + step.get('run', '') for job in workflow['jobs'].values() for step in job.get('steps', []) ) - - -@pytest.mark.parametrize('job_id', ['test', 'cli-compat']) -@pytest.mark.parametrize( - 'draft,event', [(True, 'pull_request'), (False, 'pull_request'), (False, 'push')] -) -def test_b2_credentials_are_empty_only_for_drafts(job_id, draft, event): - values = context(draft=draft, event=event) - for name in ('B2_TEST_APPLICATION_KEY', 'B2_TEST_APPLICATION_KEY_ID'): - actual = expression(JOBS[job_id]['env'][name], values) - assert actual == ('' if draft else values[f'secrets.{name}']) - - -@pytest.mark.parametrize('job_id', ['test', 'cli-compat']) -@pytest.mark.parametrize( - 'draft,credentials,allowed', - [(True, True, False), (True, False, False), (False, True, True), (False, False, False)], -) -def test_live_steps_require_non_draft_and_credentials(job_id, draft, credentials, allowed): - values = context(draft=draft, credentials=credentials) - values.update( - { - f'env.{name}': expression(value, values) - for name, value in JOBS[job_id]['env'].items() - if name.startswith('B2_TEST_') - } + assert 'B2_TEST_ENVIRONMENT' in scripts + assert 'uv run nox -vs integration' in scripts + assert 'exit 1' in scripts + + +def test_live_b2_workflow_is_weekly_manual_and_fails_closed(): + text = LIVE_PATH.read_text() + workflow = yaml.safe_load(text) + assert set(triggers(workflow)) == {'schedule', 'workflow_dispatch'} + assert triggers(workflow)['schedule'] + assert all(f'secrets.{key}' in text for key in KEYS) + scripts = '\n'.join( + step.get('run', '') for job in workflow['jobs'].values() for step in job.get('steps', []) ) - values.update({'matrix.os': 'ubuntu-latest', 'matrix.python-version': '3.14'}) - steps = [ - step - for step in JOBS[job_id]['steps'] - if step.get('name') in ('Run integration tests', 'Run CLI integration tests (with secrets)') - ] - assert len(steps) == 1 - assert bool(expression(steps[0]['if'], values)) == allowed - - -@pytest.mark.parametrize('job_id', ['test', 'cli-compat']) -@pytest.mark.parametrize( - 'lint,cleanup,allowed', - [ - ('success', 'skipped', True), - ('success', 'success', True), - ('failure', 'skipped', False), - ('success', 'failure', False), - ('success', 'cancelled', False), - ], -) -def test_unit_jobs_survive_skipped_cleanup_but_not_failed_dependencies( - job_id, lint, cleanup, allowed -): - assert 'lint' in JOBS[job_id]['needs'] - assert 'cleanup_buckets' in JOBS[job_id]['needs'] - values = context(lint=lint, cleanup=cleanup) - assert bool(expression(JOBS[job_id]['if'], values)) == allowed - values['cancelled'] = True - assert not expression(JOBS[job_id]['if'], values) - - -@pytest.mark.parametrize('event', ['pull_request', 'push']) -def test_non_draft_cleanup_is_retained(event): - assert expression(JOBS['cleanup_buckets']['if'], context(draft=False, event=event)) - - -@pytest.mark.parametrize('event', ['pull_request', 'push']) -@pytest.mark.parametrize('live_enabled', ['', 'false', 'true']) -def test_non_draft_live_operations_require_explicit_repository_opt_in(event, live_enabled): - values = context(draft=False, event=event, live_enabled=live_enabled) - allowed = live_enabled == 'true' - assert bool(expression(JOBS['cleanup_buckets']['if'], values)) == allowed - for job_id in ('test', 'cli-compat'): - job_values = dict(values) - for name in ('B2_TEST_APPLICATION_KEY', 'B2_TEST_APPLICATION_KEY_ID'): - actual = expression(JOBS[job_id]['env'][name], values) - assert actual == (values[f'secrets.{name}'] if allowed else '') - job_values[f'env.{name}'] = actual - job_values.update({'matrix.os': 'ubuntu-latest', 'matrix.python-version': '3.14'}) - steps = [ - step - for step in JOBS[job_id]['steps'] - if step.get('name') - in ('Run integration tests', 'Run CLI integration tests (with secrets)') - ] - assert len(steps) == 1 - assert bool(expression(steps[0]['if'], job_values)) == allowed + assert 'uv run nox -vs integration' in scripts + assert 'exit 1' in scripts From 5d6730466f83d04e908c9dd3d61c2e7f21aee35c Mon Sep 17 00:00:00 2001 From: Sophie <49928680+sophiecarreras@users.noreply.github.com> Date: Fri, 27 Nov 2026 03:44:37 -0300 Subject: [PATCH 087/113] ci: pin Simulator a1e1db3, restore CLI compat, gate releases on live B2 - Pin backblaze-labs/b2-simulator to a1e1db3 (on its main branch), stated once as SIMULATOR_REVISION and referenced by every checkout. - Run the CLI's require_secrets integration tests with this SDK against the Simulator in pull-request CI (cli-compat-simulator), replacing the live cli-compat step removed from ci.yml; also run them weekly against live B2. - Check deploy-key and live-credential presence with `if:` on a boolean derived from the secret, so no secret enters a shell. The missing-key message tells an admin to add SIMULATOR_DEPLOY_KEY as a Dependabot secret; Dependabot PRs are not skipped. - Move the live suite into a reusable live-b2-tests.yml with a shared live-b2-account concurrency group. The weekly workflow opens or updates an issue when a scheduled run fails (issues: write on that job only). - The release workflow runs the live SDK suite on the tagged commit and publishes only if it passes. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/cd.yml | 10 +- .github/workflows/live-b2-tests.yml | 93 ++++++++ .github/workflows/live-b2.yml | 56 +++-- .github/workflows/simulator-integration.yml | 102 ++++++++- README.release.md | 19 +- ...ulator-pr-weekly-live-b2.infrastructure.md | 2 +- doc/source/contributing.rst | 15 +- docs/testing.md | 2 +- test/static/test_ci_draft_safety.py | 198 ++++++++++++++++-- test/static/test_release_workflow_safety.py | 15 +- 10 files changed, 448 insertions(+), 64 deletions(-) create mode 100644 .github/workflows/live-b2-tests.yml diff --git a/.github/workflows/cd.yml b/.github/workflows/cd.yml index 8eea08a68..7fb855017 100644 --- a/.github/workflows/cd.yml +++ b/.github/workflows/cd.yml @@ -29,8 +29,16 @@ jobs: run: uv sync --only-group nox --locked - name: Run unit tests run: uv run nox -vs unit -p ${{ env.PYTHON_DEFAULT_VERSION }} -- -v + # Pull requests test against the Simulator only, so a release must pass live B2 on the tagged commit. + live-b2: + permissions: + contents: read + uses: ./.github/workflows/live-b2-tests.yml + secrets: + B2_TEST_APPLICATION_KEY_ID: ${{ secrets.B2_TEST_APPLICATION_KEY_ID }} + B2_TEST_APPLICATION_KEY: ${{ secrets.B2_TEST_APPLICATION_KEY }} deploy: - needs: test + needs: [test, live-b2] permissions: contents: write env: diff --git a/.github/workflows/live-b2-tests.yml b/.github/workflows/live-b2-tests.yml new file mode 100644 index 000000000..9955450b1 --- /dev/null +++ b/.github/workflows/live-b2-tests.yml @@ -0,0 +1,93 @@ +name: Live B2 Tests + +# Reusable: called by the weekly live workflow and by the release workflow. +on: + workflow_call: + inputs: + cli-compat: + description: Also run the CLI's secret-marked integration tests with this SDK. + type: boolean + required: false + default: false + secrets: + B2_TEST_APPLICATION_KEY_ID: + required: false + B2_TEST_APPLICATION_KEY: + required: false + +permissions: + contents: read + +env: + PYTHON_DEFAULT_VERSION: "3.14" + UV_VERSION: "0.13.4" + +jobs: + live-b2-integration: + runs-on: ubuntu-latest + timeout-minutes: 120 + # Every caller shares one live B2 account: run one live job at a time and never cancel one mid-run. + concurrency: + group: live-b2-account + cancel-in-progress: false + env: + LIVE_B2_CREDENTIALS_SET: ${{ secrets.B2_TEST_APPLICATION_KEY_ID != '' && secrets.B2_TEST_APPLICATION_KEY != '' }} + INSTALL_SDK_FROM: ../sdk + steps: + - name: Require live B2 credentials + if: ${{ env.LIVE_B2_CREDENTIALS_SET != 'true' }} + run: | + echo "::error::B2_TEST_APPLICATION_KEY_ID and B2_TEST_APPLICATION_KEY are required. A repository admin must add them as Actions secrets." + exit 1 + - name: Check out the SDK + uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 + with: + fetch-depth: 0 + persist-credentials: false + path: sdk + - name: Check out the CLI + if: ${{ inputs.cli-compat }} + uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 + with: + repository: Backblaze/B2_Command_Line_Tool + persist-credentials: false + path: cli + - name: Set up Python ${{ env.PYTHON_DEFAULT_VERSION }} + uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6 + with: + python-version: ${{ env.PYTHON_DEFAULT_VERSION }} + - uses: astral-sh/setup-uv@37802adc94f370d6bfd71619e3f0bf239e1f3b78 # v7 + with: + version: ${{ env.UV_VERSION }} + enable-cache: true + - name: Install SDK dependencies + working-directory: sdk + run: uv sync --only-group nox --locked + - name: Install CLI dependencies + if: ${{ inputs.cli-compat }} + working-directory: cli + run: uv sync --locked --group nox + - name: Remove stale test buckets + working-directory: sdk + env: + B2_TEST_APPLICATION_KEY_ID: ${{ secrets.B2_TEST_APPLICATION_KEY_ID }} + B2_TEST_APPLICATION_KEY: ${{ secrets.B2_TEST_APPLICATION_KEY }} + run: uv run nox -vs cleanup_old_buckets + - name: Test against live B2 + id: sdk-live + working-directory: sdk + env: + B2_TEST_APPLICATION_KEY_ID: ${{ secrets.B2_TEST_APPLICATION_KEY_ID }} + B2_TEST_APPLICATION_KEY: ${{ secrets.B2_TEST_APPLICATION_KEY }} + run: uv run nox -vs integration -p "$PYTHON_DEFAULT_VERSION" -- --dont-cleanup-old-buckets -v + # The CLI's secret-marked tests with this SDK, as the old ci.yml cli-compat step ran them. + - name: Run CLI integration tests with secrets against live B2 + if: ${{ inputs.cli-compat && (success() || steps.sdk-live.conclusion == 'failure') }} + working-directory: cli + env: + B2_TEST_APPLICATION_KEY_ID: ${{ secrets.B2_TEST_APPLICATION_KEY_ID }} + B2_TEST_APPLICATION_KEY: ${{ secrets.B2_TEST_APPLICATION_KEY }} + run: | + uv run nox -vs integration -p "$PYTHON_DEFAULT_VERSION" -- \ + -n 1 -m "require_secrets" --cleanup \ + --sut "$PWD/.nox/integration-${PYTHON_DEFAULT_VERSION//./-}/bin/b2v4" diff --git a/.github/workflows/live-b2.yml b/.github/workflows/live-b2.yml index c4a9e26c5..f20e643f8 100644 --- a/.github/workflows/live-b2.yml +++ b/.github/workflows/live-b2.yml @@ -8,39 +8,35 @@ on: permissions: contents: read -env: - PYTHON_DEFAULT_VERSION: "3.14" - UV_VERSION: "0.13.4" - jobs: - live-b2-integration: - runs-on: ubuntu-latest - timeout-minutes: 90 - env: + live-b2: + uses: ./.github/workflows/live-b2-tests.yml + with: + cli-compat: true + secrets: B2_TEST_APPLICATION_KEY_ID: ${{ secrets.B2_TEST_APPLICATION_KEY_ID }} B2_TEST_APPLICATION_KEY: ${{ secrets.B2_TEST_APPLICATION_KEY }} + + report-scheduled-failure: + needs: live-b2 + if: ${{ failure() && github.event_name == 'schedule' }} + runs-on: ubuntu-latest + timeout-minutes: 5 + permissions: + issues: write steps: - - name: Require live B2 credentials + - name: Open or update the live B2 failure issue + env: + GH_TOKEN: ${{ github.token }} + GH_REPO: ${{ github.repository }} + RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }} run: | - if [ -z "$B2_TEST_APPLICATION_KEY_ID" ] || [ -z "$B2_TEST_APPLICATION_KEY" ]; then - echo "B2_TEST_APPLICATION_KEY_ID and B2_TEST_APPLICATION_KEY are required." - exit 1 + title="Weekly live B2 integration failed" + body="The scheduled live B2 run failed: $RUN_URL" + number="$(gh issue list --state open --search "\"$title\" in:title" --json number,title \ + --jq "map(select(.title == \"$title\")) | first | .number // empty")" + if [ -n "$number" ]; then + gh issue comment "$number" --body "$body" + else + gh issue create --title "$title" --body "$body" fi - - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 - with: - fetch-depth: 0 - persist-credentials: false - - name: Set up Python ${{ env.PYTHON_DEFAULT_VERSION }} - uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6 - with: - python-version: ${{ env.PYTHON_DEFAULT_VERSION }} - - uses: astral-sh/setup-uv@37802adc94f370d6bfd71619e3f0bf239e1f3b78 # v7 - with: - version: ${{ env.UV_VERSION }} - enable-cache: true - - name: Install dependencies - run: uv sync --only-group nox --locked - - name: Remove stale test buckets - run: uv run nox -vs cleanup_old_buckets - - name: Test against live B2 - run: uv run nox -vs integration -p "$PYTHON_DEFAULT_VERSION" -- --dont-cleanup-old-buckets -v diff --git a/.github/workflows/simulator-integration.yml b/.github/workflows/simulator-integration.yml index 658df3b5d..280c0917e 100644 --- a/.github/workflows/simulator-integration.yml +++ b/.github/workflows/simulator-integration.yml @@ -12,7 +12,8 @@ permissions: env: PYTHON_DEFAULT_VERSION: "3.14" UV_VERSION: "0.13.4" - SIMULATOR_REVISION: "529721037901412b7b24fdc18498631d298295c5" + # The single Simulator pin for this workflow; every checkout below refers to it. + SIMULATOR_REVISION: "a1e1db373b71f2d5f40082c19bc716cb6b3c3675" jobs: simulator-access-policy: @@ -33,15 +34,15 @@ jobs: needs: simulator-access-policy runs-on: ubuntu-latest timeout-minutes: 90 + env: + # A boolean only; the key itself never enters a shell. + SIMULATOR_DEPLOY_KEY_SET: ${{ secrets.SIMULATOR_DEPLOY_KEY != '' }} steps: - name: Require the private Simulator deploy key - env: - SIMULATOR_DEPLOY_KEY: ${{ secrets.SIMULATOR_DEPLOY_KEY }} + if: ${{ env.SIMULATOR_DEPLOY_KEY_SET != 'true' }} run: | - if [ -z "$SIMULATOR_DEPLOY_KEY" ]; then - echo "SIMULATOR_DEPLOY_KEY is required because Simulator testing is mandatory." - exit 1 - fi + echo "::error::SIMULATOR_DEPLOY_KEY is missing. Simulator testing is mandatory. A repository admin must add SIMULATOR_DEPLOY_KEY as an Actions secret and as a Dependabot secret (Dependabot pull requests only receive Dependabot secrets)." + exit 1 - name: Check out the SDK uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: @@ -52,7 +53,7 @@ jobs: uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: repository: backblaze-labs/b2-simulator - ref: 529721037901412b7b24fdc18498631d298295c5 + ref: ${{ env.SIMULATOR_REVISION }} ssh-key: ${{ secrets.SIMULATOR_DEPLOY_KEY }} persist-credentials: false path: simulator @@ -102,3 +103,88 @@ jobs: export REQUESTS_CA_BUNDLE="$simulator_ca_bundle" export SSL_CERT_FILE="$simulator_ca_bundle" uv run nox -vs integration -p "$PYTHON_DEFAULT_VERSION" -- --dont-cleanup-old-buckets -v + + # The CLI's secret-marked integration tests, run with this SDK against the Simulator. + # This replaces the live `cli-compat` step that ci.yml used to run on pull requests. + cli-compat-simulator: + needs: simulator-access-policy + runs-on: ubuntu-latest + timeout-minutes: 90 + env: + SIMULATOR_DEPLOY_KEY_SET: ${{ secrets.SIMULATOR_DEPLOY_KEY != '' }} + INSTALL_SDK_FROM: ../sdk + steps: + - name: Require the private Simulator deploy key + if: ${{ env.SIMULATOR_DEPLOY_KEY_SET != 'true' }} + run: | + echo "::error::SIMULATOR_DEPLOY_KEY is missing. Simulator testing is mandatory. A repository admin must add SIMULATOR_DEPLOY_KEY as an Actions secret and as a Dependabot secret (Dependabot pull requests only receive Dependabot secrets)." + exit 1 + - name: Check out the SDK + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + fetch-depth: 0 + persist-credentials: false + path: sdk + - name: Check out the CLI + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + repository: Backblaze/B2_Command_Line_Tool + persist-credentials: false + path: cli + - name: Check out the pinned private Simulator + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + repository: backblaze-labs/b2-simulator + ref: ${{ env.SIMULATOR_REVISION }} + ssh-key: ${{ secrets.SIMULATOR_DEPLOY_KEY }} + persist-credentials: false + path: simulator + - name: Verify the Simulator revision + run: | + test "$(git -C simulator rev-parse HEAD)" = "$SIMULATOR_REVISION" + test -z "$(git -C simulator status --short)" + - name: Set up Node.js 22 + uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 + with: + node-version: 22 + - name: Set up Python ${{ env.PYTHON_DEFAULT_VERSION }} + uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6 + with: + python-version: ${{ env.PYTHON_DEFAULT_VERSION }} + - uses: astral-sh/setup-uv@37802adc94f370d6bfd71619e3f0bf239e1f3b78 # v7 + with: + version: ${{ env.UV_VERSION }} + enable-cache: true + - name: Install dependencies + working-directory: cli + run: uv sync --locked --group nox + - name: Run CLI integration tests with secrets against Simulator + working-directory: cli + env: + B2_TEST_APPLICATION_KEY_ID: sim-test-id + B2_TEST_APPLICATION_KEY: sim-test-secret + B2_TEST_SHORT_TIMEOUTS: "1" + WORKFLOW_ID: ${{ github.run_id }}-${{ github.run_attempt }}-${{ github.job }} + run: | + simulator_log="$RUNNER_TEMP/b2-simulator.log" + node ../simulator/bin/simulator/serve.mjs --custom-upload-timestamps >"$simulator_log" 2>&1 & + simulator_pid=$! + trap 'kill "$simulator_pid" 2>/dev/null || true; wait "$simulator_pid" 2>/dev/null || true' EXIT + + B2_TEST_ENVIRONMENT="" + for _ in $(seq 1 150); do + B2_TEST_ENVIRONMENT="$(sed -n 's|^SIMULATOR-LISTENING \(https://127\.0\.0\.1:[0-9][0-9]*\)$|\1|p' "$simulator_log" | head -1)" + if [ -n "$B2_TEST_ENVIRONMENT" ]; then break; fi + if ! kill -0 "$simulator_pid" 2>/dev/null; then cat "$simulator_log"; exit 1; fi + sleep 0.2 + done + if [ -z "$B2_TEST_ENVIRONMENT" ]; then cat "$simulator_log"; exit 1; fi + export B2_TEST_ENVIRONMENT + export B2_ENVIRONMENT="$B2_TEST_ENVIRONMENT" + certifi_bundle="$(uv run python -c 'import certifi; print(certifi.where())')" + simulator_ca_bundle="$RUNNER_TEMP/b2-simulator-ca.pem" + cp "$certifi_bundle" "$simulator_ca_bundle" + cat "$GITHUB_WORKSPACE/simulator/bin/simulator/loopback-cert.pem" >>"$simulator_ca_bundle" + export REQUESTS_CA_BUNDLE="$simulator_ca_bundle" + export SSL_CERT_FILE="$simulator_ca_bundle" + uv run nox -vs integration -p "$PYTHON_DEFAULT_VERSION" -- -n 0 -m "require_secrets" diff --git a/README.release.md b/README.release.md index 81a344ee2..fbc01023e 100644 --- a/README.release.md +++ b/README.release.md @@ -61,12 +61,17 @@ Triggered by any pushed tag matching `v*`: 1. Decides whether the release is a prerelease, based only on whether the tag's last character is a digit. `v1.2.3` is a normal release. -2. Builds the distribution with `nox -s build`, which also asserts the built package imports from +2. Runs the unit tests, and runs the integration suite against live B2 on the tagged commit + (`.github/workflows/live-b2-tests.yml`). Pull requests test against the B2 Simulator only, so + this is the release's real-B2 check. Nothing is built or published unless both pass. The live + run needs the `B2_TEST_APPLICATION_KEY_ID` and `B2_TEST_APPLICATION_KEY` secrets, and it waits + while another live run (for example the weekly one) is using the test account. +3. Builds the distribution with `nox -s build`, which also asserts the built package imports from `site-packages` rather than the checkout. The version is derived from the tag, not from any file. -3. Reads the notes for that version out of `CHANGELOG.md`. If the tag and the changelog heading do not +4. Reads the notes for that version out of `CHANGELOG.md`. If the tag and the changelog heading do not match, there will be no release body. -4. Creates a GitHub release and attaches the distribution. -5. Uploads to PyPI — **only** when the `B2_PYPI_PASSWORD` secret is present *and* the release is not a +5. Creates a GitHub release and attaches the distribution. +6. Uploads to PyPI — **only** when the `B2_PYPI_PASSWORD` secret is present *and* the release is not a prerelease. A repository without that secret still gets a GitHub release and silently publishes nothing to PyPI, so do not treat a green CD run as proof that PyPI was updated. @@ -88,6 +93,12 @@ fragments, so recovering means restoring them: Then fix the problem and start again from step 1. +### The live B2 job failed + +Nothing was built or published. If the cause was outside the SDK (missing or expired credentials, a +B2 outage), fix it and re-run the failed jobs of the same workflow run. If the SDK is at fault, fix it +and follow the next section to re-tag. + ### After the tag is pushed, before PyPI published Delete the tag locally and upstream, fix the problem, and re-tag: diff --git a/changelog.d/+simulator-pr-weekly-live-b2.infrastructure.md b/changelog.d/+simulator-pr-weekly-live-b2.infrastructure.md index 8eb914618..7481cb3aa 100644 --- a/changelog.d/+simulator-pr-weekly-live-b2.infrastructure.md +++ b/changelog.d/+simulator-pr-weekly-live-b2.infrastructure.md @@ -1 +1 @@ -Run integration tests against the pinned B2 Simulator for pull requests, and run fail-closed real-B2 integration weekly or on manual dispatch. +Run SDK and CLI-compatibility integration tests against the pinned B2 Simulator for pull requests; run fail-closed live B2 integration weekly (reporting scheduled failures as an issue), on manual dispatch, and before each release. diff --git a/doc/source/contributing.rst b/doc/source/contributing.rst index eea5a0317..e4f82ab1e 100644 --- a/doc/source/contributing.rst +++ b/doc/source/contributing.rst @@ -158,10 +158,17 @@ To run tests matching a keyword expression:: Pull requests and pushes to master never receive B2 test credentials. The ``Simulator Integration`` workflow runs the SDK integration suite against a pinned revision of the B2 Simulator (``backblaze-labs/b2-simulator``) with fixed test -credentials. It fails if the Simulator cannot be checked out or started, and it -fails for pull requests from forks: push the branch to this repository instead. -The ``Weekly Live B2 Integration`` workflow runs the same suite against live B2 -every Monday and on manual dispatch. It fails if the live credentials are missing. +credentials. A second job runs the B2 Command Line Tool's secret-marked +integration tests with this SDK against the same Simulator. Both jobs fail if the +Simulator cannot be checked out or started, and they fail for pull requests from +forks: push the branch to this repository instead. Dependabot pull requests run +them too, so the deploy key must also be stored as a Dependabot secret. + +The ``Weekly Live B2 Integration`` workflow runs the SDK suite and the CLI's +secret-marked tests against live B2 every Monday and on manual dispatch. It fails +if the live credentials are missing, and a failed scheduled run opens or updates a +"Weekly live B2 integration failed" issue. The release workflow runs the SDK suite +against live B2 on the tagged commit and publishes only if it passes. JUnit reports include each subtest as its own case, as well as its parent test. The repository's ``test.junit_subtests`` compatibility plugin supplies those cases diff --git a/docs/testing.md b/docs/testing.md index 21613e47a..a20bb6e5b 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -9,7 +9,7 @@ The examples use Python 3.13. Use `nox -l` to list the sessions for your install | --- | --- | --- | --- | | [Unit](../test/unit) | `nox -s unit-3.13` | Runs the unit suite for each API version, v0 through v3. Tests that use [`RawSimulator`](../b2sdk/_internal/raw_simulator.py) exercise SDK behavior against an in-memory simulator. | It does not prove live B2 behavior. Not every unit test uses the simulator. | | [Static](../test/static) | `nox -s lint` | Runs checks for Python license headers, workflow gates, JUnit reporting, documentation links, and other repository regressions. The session also runs Ruff and license checks. | It does not run unit or live B2 tests. | -| [Integration](../test/integration) | `nox -s integration-3.13` | Exercises SDK operations against live B2 when credentials are configured. CI runs it against the B2 Simulator for pull requests and against live B2 weekly. | It does not cover every service behavior or every SDK path. | +| [Integration](../test/integration) | `nox -s integration-3.13` | Exercises SDK operations against live B2 when credentials are configured. CI runs it against the B2 Simulator for pull requests, and against live B2 weekly and before each release. | It does not cover every service behavior or every SDK path. | | [sdkharness contract](../.sdkharness/README.md) | `SDKHARNESS_TEST_LEVEL=conformance SDKHARNESS_SCENARIO=files.upload .sdkharness/tests/run-conformance` | Exercises the selected contract against a loopback simulator. Follow the harness README to start the simulator and set its URL first. | It does not test live B2. | | [Known defects](../test/known_defect.py) | `uv run --group test pytest --runxfail -m known_defect --api=v3 test/unit` | Runs marked defect checks as ordinary tests so their failures are visible. | It does not prove that unmarked behavior is correct. | diff --git a/test/static/test_ci_draft_safety.py b/test/static/test_ci_draft_safety.py index 267de484b..e2a301d6b 100644 --- a/test/static/test_ci_draft_safety.py +++ b/test/static/test_ci_draft_safety.py @@ -7,7 +7,7 @@ # License https://www.backblaze.com/using_b2_code.html # ###################################################################### -"""Keep PR integration on Simulator and live B2 on a weekly/manual path.""" +"""Keep PR integration on Simulator and live B2 on a weekly/manual/release path.""" from __future__ import annotations @@ -17,16 +17,54 @@ import yaml ROOT = Path(__file__).parents[2] -CI_TEXT = (ROOT / '.github/workflows/ci.yml').read_text() -SIMULATOR_PATH = ROOT / '.github/workflows/simulator-integration.yml' -LIVE_PATH = ROOT / '.github/workflows/live-b2.yml' +WORKFLOWS = ROOT / '.github/workflows' +CI_TEXT = (WORKFLOWS / 'ci.yml').read_text() +SIMULATOR_PATH = WORKFLOWS / 'simulator-integration.yml' +LIVE_PATH = WORKFLOWS / 'live-b2.yml' +LIVE_TESTS_PATH = WORKFLOWS / 'live-b2-tests.yml' KEYS = ('B2_TEST_APPLICATION_KEY', 'B2_TEST_APPLICATION_KEY_ID') +SIMULATOR_REPOSITORY = 'backblaze-labs/b2-simulator' +SIMULATOR_PIN = 'a1e1db373b71f2d5f40082c19bc716cb6b3c3675' +CLI_REPOSITORY = 'Backblaze/B2_Command_Line_Tool' +KEY_SET_FLAG = "${{ secrets.SIMULATOR_DEPLOY_KEY != '' }}" +SECRET_EXPRESSION = re.compile(r'secrets\.[A-Za-z_]') def triggers(workflow): return workflow.get('on', workflow.get(True)) +def load(path): + return yaml.safe_load(path.read_text()) + + +def steps(workflow): + return [step for job in workflow['jobs'].values() for step in job.get('steps', [])] + + +def called_workflows(workflow): + """Load the local reusable workflows that a workflow's jobs call.""" + return [ + load(ROOT / job['uses']) + for job in workflow['jobs'].values() + if job.get('uses', '').startswith('./') + ] + + +def scripts(workflow, follow_calls=False): + workflows = [workflow, *(called_workflows(workflow) if follow_calls else [])] + return '\n'.join(step.get('run', '') for wf in workflows for step in steps(wf)) + + +def checkouts_of(job, repository): + return [ + step + for step in job.get('steps', []) + if step.get('uses', '').startswith('actions/checkout@') + and step.get('with', {}).get('repository') == repository + ] + + def test_regular_ci_cannot_use_real_b2_credentials(): assert 'B2_LIVE_TESTS_ENABLED' not in CI_TEXT for key in KEYS: @@ -40,12 +78,80 @@ def test_simulator_workflow_runs_on_every_pull_request_and_fails_closed(): assert 'pull_request' in events assert 'schedule' not in events assert 'SIMULATOR_DEPLOY_KEY' in text - scripts = '\n'.join( - step.get('run', '') for job in workflow['jobs'].values() for step in job.get('steps', []) - ) - assert 'B2_TEST_ENVIRONMENT' in scripts - assert 'uv run nox -vs integration' in scripts - assert 'exit 1' in scripts + run = scripts(workflow) + assert 'B2_TEST_ENVIRONMENT' in run + assert 'uv run nox -vs integration' in run + assert 'exit 1' in run + + +def test_simulator_pin_is_stated_once_on_simulator_main_and_referenced(): + text = SIMULATOR_PATH.read_text() + workflow = yaml.safe_load(text) + assert workflow['env']['SIMULATOR_REVISION'] == SIMULATOR_PIN + assert text.count(SIMULATOR_PIN) == 1 + checkouts = [ + step + for job in workflow['jobs'].values() + for step in checkouts_of(job, SIMULATOR_REPOSITORY) + ] + assert checkouts + for step in checkouts: + assert step['with']['ref'] == '${{ env.SIMULATOR_REVISION }}' + assert step['with']['persist-credentials'] is False + + +def test_simulator_key_presence_is_checked_with_if_not_in_a_shell(): + workflow = load(SIMULATOR_PATH) + jobs = [job for job in workflow['jobs'].values() if checkouts_of(job, SIMULATOR_REPOSITORY)] + assert jobs + for job in jobs: + assert job['env']['SIMULATOR_DEPLOY_KEY_SET'] == KEY_SET_FLAG + guard = job['steps'][0] + assert guard['if'] == "${{ env.SIMULATOR_DEPLOY_KEY_SET != 'true' }}" + assert 'exit 1' in guard['run'] + for step in job['steps']: + assert 'SIMULATOR_DEPLOY_KEY' not in str(step.get('env', {})) + assert not SECRET_EXPRESSION.search(step.get('run', '')) + ssh_key = step.get('with', {}).get('ssh-key') + if ssh_key is not None: + assert step in checkouts_of(job, SIMULATOR_REPOSITORY) + + +def test_dependabot_runs_the_simulator_and_is_told_which_secret_is_missing(): + text = SIMULATOR_PATH.read_text() + workflow = yaml.safe_load(text) + for job in workflow['jobs'].values(): + assert 'dependabot' not in str(job.get('if', '')).lower() + for step in job.get('steps', []): + assert 'dependabot' not in str(step.get('if', '')).lower() + guards = [ + step['run'] + for job in workflow['jobs'].values() + for step in job.get('steps', []) + if 'SIMULATOR_DEPLOY_KEY_SET' in str(step.get('if', '')) + ] + assert guards + for run in guards: + assert 'admin' in run + assert 'Dependabot secret' in run + assert 'SIMULATOR_DEPLOY_KEY' in run + + +def test_cli_compatibility_secret_tests_run_against_the_simulator_in_pr_ci(): + workflow = load(SIMULATOR_PATH) + cli_jobs = [ + job + for job in workflow['jobs'].values() + if checkouts_of(job, CLI_REPOSITORY) and checkouts_of(job, SIMULATOR_REPOSITORY) + ] + assert len(cli_jobs) == 1 + [job] = cli_jobs + assert job['needs'] == 'simulator-access-policy' + assert job['env']['INSTALL_SDK_FROM'] + assert checkouts_of(job, CLI_REPOSITORY)[0]['with']['persist-credentials'] is False + run = '\n'.join(step.get('run', '') for step in job['steps']) + assert 'B2_TEST_ENVIRONMENT' in run + assert re.search(r'nox -vs integration .*-m "?require_secrets"?', run) def test_live_b2_workflow_is_weekly_manual_and_fails_closed(): @@ -54,8 +160,72 @@ def test_live_b2_workflow_is_weekly_manual_and_fails_closed(): assert set(triggers(workflow)) == {'schedule', 'workflow_dispatch'} assert triggers(workflow)['schedule'] assert all(f'secrets.{key}' in text for key in KEYS) - scripts = '\n'.join( - step.get('run', '') for job in workflow['jobs'].values() for step in job.get('steps', []) + run = scripts(workflow, follow_calls=True) + assert 'uv run nox -vs integration' in run + assert 'exit 1' in run + + +def test_live_b2_tests_are_reusable_serialized_and_fail_closed(): + workflow = load(LIVE_TESTS_PATH) + events = triggers(workflow) + assert set(events) == {'workflow_call'} + assert set(events['workflow_call']['secrets']) == set(KEYS) + assert workflow['permissions'] == {'contents': 'read'} + [job] = workflow['jobs'].values() + assert job['concurrency'] == {'group': 'live-b2-account', 'cancel-in-progress': False} + assert job['env']['LIVE_B2_CREDENTIALS_SET'] == ( + "${{ secrets.B2_TEST_APPLICATION_KEY_ID != '' && secrets.B2_TEST_APPLICATION_KEY != '' }}" + ) + guard = job['steps'][0] + assert guard['if'] == "${{ env.LIVE_B2_CREDENTIALS_SET != 'true' }}" + assert 'exit 1' in guard['run'] + assert not SECRET_EXPRESSION.search(guard['run']) + + +def test_live_b2_tests_cover_the_sdk_suite_and_cli_compatibility(): + workflow = load(LIVE_TESTS_PATH) + cli_input = triggers(workflow)['workflow_call']['inputs']['cli-compat'] + assert (cli_input['type'], cli_input['required'], cli_input['default']) == ( + 'boolean', + False, + False, ) - assert 'uv run nox -vs integration' in scripts - assert 'exit 1' in scripts + [job] = workflow['jobs'].values() + assert job['env']['INSTALL_SDK_FROM'] + sdk_run = '\n'.join(step.get('run', '') for step in job['steps'] if 'if' not in step) + assert 'nox -vs cleanup_old_buckets' in sdk_run + assert 'uv run nox -vs integration' in sdk_run + cli_steps = [step for step in job['steps'] if 'inputs.cli-compat' in str(step.get('if', ''))] + assert any(step in checkouts_of(job, CLI_REPOSITORY) for step in cli_steps) + cli_run = '\n'.join(step.get('run', '') for step in cli_steps) + assert re.search(r'nox -vs integration .*-m "?require_secrets"? .*--cleanup', cli_run, re.S) + + +def test_weekly_live_b2_runs_cli_compatibility_and_release_does_not(): + weekly = load(LIVE_PATH)['jobs']['live-b2'] + assert weekly['with'] == {'cli-compat': True} + release = load(WORKFLOWS / 'cd.yml')['jobs']['live-b2'] + assert 'cli-compat' not in release.get('with', {}) + + +def test_weekly_live_b2_reports_scheduled_failures_with_a_scoped_token(): + workflow = load(LIVE_PATH) + assert workflow['permissions'] == {'contents': 'read'} + jobs = workflow['jobs'] + live = [ + name + for name, job in jobs.items() + if job.get('uses') == './' + str(LIVE_TESTS_PATH.relative_to(ROOT)) + ] + assert len(live) == 1 + assert jobs[live[0]]['secrets'] == {key: f'${{{{ secrets.{key} }}}}' for key in KEYS} + reporters = [job for job in jobs.values() if job.get('permissions', {}).get('issues')] + assert len(reporters) == 1 + [reporter] = reporters + assert reporter['permissions'] == {'issues': 'write'} + assert reporter['needs'] == live[0] + assert 'failure()' in reporter['if'] + assert "github.event_name == 'schedule'" in reporter['if'] + run = '\n'.join(step.get('run', '') for step in reporter['steps']) + assert 'gh issue create' in run + assert 'gh issue comment' in run diff --git a/test/static/test_release_workflow_safety.py b/test/static/test_release_workflow_safety.py index 471672034..ca05042f5 100644 --- a/test/static/test_release_workflow_safety.py +++ b/test/static/test_release_workflow_safety.py @@ -36,8 +36,21 @@ def test_active_actions_are_pinned_to_full_commit_shas(): def test_release_requires_successful_unit_tests(): jobs = load_workflow('cd.yml')['jobs'] - assert jobs['deploy']['needs'] == 'test' + assert 'test' in jobs['deploy']['needs'] assert 'if' not in jobs['deploy'] steps = jobs['test']['steps'] assert any('nox -vs unit' in step.get('run', '') for step in steps) assert jobs['test'].get('permissions') == {'contents': 'read'} + + +def test_release_requires_a_green_live_b2_run_of_the_tagged_commit(): + jobs = load_workflow('cd.yml')['jobs'] + assert set(jobs['deploy']['needs']) == {'test', 'live-b2'} + live = jobs['live-b2'] + assert live['uses'] == './.github/workflows/live-b2-tests.yml' + assert live['permissions'] == {'contents': 'read'} + # Only the live test credentials reach the called workflow, never the PyPI token. + assert live['secrets'] == { + key: f'${{{{ secrets.{key} }}}}' + for key in ('B2_TEST_APPLICATION_KEY_ID', 'B2_TEST_APPLICATION_KEY') + } From 75384f9ccc3f03863d714463dd00424b7bb75f05 Mon Sep 17 00:00:00 2001 From: Sophie <49928680+sophiecarreras@users.noreply.github.com> Date: Fri, 27 Nov 2026 03:50:23 -0300 Subject: [PATCH 088/113] test: add opt-in --b2-simulator plugin for unit tests With --b2-simulator and B2_SIMULATOR_DIR pointing at a checkout of backblaze-labs/b2-simulator, each pytest process (each xdist worker) starts one simulator, resets it before every test and the shared setups (the b2api fixture, TestCaseWithBucket and the per-class setups) talk to it over HTTP instead of using the in-process RawSimulator. A test's own RawSimulator subclass stays in-process. The simulator exits when its pytest process does, including on SIGKILL. Opting in without a usable checkout or node is a usage error, never a skip. Without the option nothing changes. Co-Authored-By: Claude Opus 5.5 --- docs/testing.md | 22 ++ .../test_reauth_drops_pooled_urls.py | 6 +- test/unit/api/test_api.py | 6 +- test/unit/b2_simulator.py | 265 ++++++++++++++++++ test/unit/bucket/test_bucket.py | 9 +- .../test_notification_rules_nonexposure.py | 6 +- test/unit/bucket/test_regression_bucket.py | 8 +- test/unit/conftest.py | 6 +- test/unit/file_version/test_file_version.py | 6 +- .../unit/sync/test_regression_sync_actions.py | 3 +- test/unit/test_b2_simulator_plugin.py | 235 ++++++++++++++++ test/unit/v0/test_bucket.py | 4 +- test/unit/v_all/test_api.py | 6 +- test/unit/v_all/test_replication.py | 6 +- 14 files changed, 571 insertions(+), 17 deletions(-) create mode 100644 test/unit/b2_simulator.py create mode 100644 test/unit/test_b2_simulator_plugin.py diff --git a/docs/testing.md b/docs/testing.md index ca9e8a122..bb0307355 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -15,6 +15,28 @@ The examples use Python 3.13. Use `nox -l` to list the sessions for your install The unit session selects each API version with the `--api` option. +## Unit tests on the standalone b2-simulator (opt-in) + +The `--b2-simulator` option runs the simulator-backed unit tests against +[b2-simulator](https://github.com/backblaze-labs/b2-simulator) over HTTP instead of the in-process `RawSimulator`. +The default run does not change. The option is in trial: many tests still fail with it. + +1. Clone b2-simulator. It needs Node.js 20 or later. +2. Set `B2_SIMULATOR_DIR` to the clone. +3. Run `uv run --group test pytest --api=v3 -n auto --b2-simulator test/unit`. + +The plugin in [`test/unit/b2_simulator.py`](../test/unit/b2_simulator.py) starts one simulator for each pytest process. +With pytest-xdist, each worker gets its own simulator. The plugin resets the simulator before each test. +The reset sets the part sizes to `RawSimulator.MIN_PART_SIZE` (200 bytes). +Use `@pytest.mark.b2_simulator_config(...)` to send other reset settings for one test. +A simulator stops when the pytest process that started it stops. +If `B2_SIMULATOR_DIR` is missing or wrong, or `node` is not on `PATH`, the run stops with a usage error. It does not skip tests. + +Shared setups get their raw API class from `raw_api_class()`: the `b2api` fixture, `TestCaseWithBucket`, and the other +per-class setups. The option replaces the SDK's `RawSimulator` only. A test's own `RawSimulator` subclass stays in-process. +Tests that construct `RawSimulator()` directly also stay in-process. +Tests marked `needs_b2_simulator` run only with the option. + The integration fixture requires `B2_TEST_APPLICATION_KEY_ID` and `B2_TEST_APPLICATION_KEY`. If either variable is unset, the credential fixture fails instead of skipping the test. Run integration tests only with an appropriate test account. diff --git a/test/unit/account_info/test_reauth_drops_pooled_urls.py b/test/unit/account_info/test_reauth_drops_pooled_urls.py index c0211656c..e784161a6 100644 --- a/test/unit/account_info/test_reauth_drops_pooled_urls.py +++ b/test/unit/account_info/test_reauth_drops_pooled_urls.py @@ -18,6 +18,8 @@ from apiver_deps import ALL_CAPABILITIES, B2HttpApiConfig, B2Session, RawSimulator from apiver_deps_exception import InvalidAuthToken, MissingAccountData +from test.unit.b2_simulator import raw_api_class + from .fixtures import * # noqa: F401, F403 @@ -25,7 +27,7 @@ def session_with_keys(account_info): session = B2Session( account_info=account_info, - api_config=B2HttpApiConfig(_raw_api_class=RawSimulator), + api_config=B2HttpApiConfig(_raw_api_class=raw_api_class(RawSimulator)), ) simulator = session.raw_api account_id, master_key = simulator.create_account() @@ -471,7 +473,7 @@ def get_upload_part_url(self, file_id): overridden = SessionWithOverride( account_info=session.account_info, - api_config=B2HttpApiConfig(_raw_api_class=RawSimulator), + api_config=B2HttpApiConfig(_raw_api_class=raw_api_class(RawSimulator)), ) overridden.raw_api = session.raw_api _upload(overridden, bucket_id, file_id, large_file=large_file) diff --git a/test/unit/api/test_api.py b/test/unit/api/test_api.py index bc2894eaf..292a8e562 100644 --- a/test/unit/api/test_api.py +++ b/test/unit/api/test_api.py @@ -43,6 +43,8 @@ WrongEncryptionModeForBucketDefault, ) +from test.unit.b2_simulator import raw_api_class + from ..test_base import create_key, create_key_multibucket if apiver_deps.V <= 1: @@ -57,7 +59,9 @@ def setUp(self): self.account_info = InMemoryAccountInfo() self.cache = InMemoryCache() self.api = B2Api( - self.account_info, self.cache, api_config=B2HttpApiConfig(_raw_api_class=RawSimulator) + self.account_info, + self.cache, + api_config=B2HttpApiConfig(_raw_api_class=raw_api_class(RawSimulator)), ) self.raw_api = self.api.session.raw_api (self.application_key_id, self.master_key) = self.raw_api.create_account() diff --git a/test/unit/b2_simulator.py b/test/unit/b2_simulator.py new file mode 100644 index 000000000..bef58d14e --- /dev/null +++ b/test/unit/b2_simulator.py @@ -0,0 +1,265 @@ +###################################################################### +# +# File: test/unit/b2_simulator.py +# +# Copyright 2026 Backblaze Inc. All Rights Reserved. +# +# License https://www.backblaze.com/using_b2_code.html +# +###################################################################### +""" +Opt-in pytest plugin: run the unit tests against the standalone b2-simulator. + +``pytest --b2-simulator`` with ``B2_SIMULATOR_DIR`` set to a checkout of +https://github.com/backblaze-labs/b2-simulator starts one simulator per pytest process (so one +per pytest-xdist worker) and resets it before every test. Tests that build their API through +:func:`raw_api_class` (the ``b2api`` fixture, ``TestCaseWithBucket`` and the other shared +setups) then talk to it over HTTP instead of using the in-process ``RawSimulator``. + +Without ``--b2-simulator`` nothing changes: :func:`raw_api_class` returns the class it is given. +With ``--b2-simulator`` and no usable checkout, the run stops with a usage error; it never skips. + +``@pytest.mark.b2_simulator_config(**settings)`` adds settings to the reset before that test +(keys of the simulator's ``POST /reset`` ``config``, for example ``minimumPartSize``). +""" + +from __future__ import annotations + +import json +import os +import shutil +import subprocess +import tempfile +import threading +import typing +import urllib.request +from dataclasses import dataclass +from pathlib import Path + +import pytest + +ENV_VAR = 'B2_SIMULATOR_DIR' +SERVER_SCRIPT = Path('bin', 'simulator', 'serve.mjs') +START_TIMEOUT_SECONDS = 30 +# The simulator's fixed full-access credential (see its docs/CONTRACT.md). +KEY_ID = 'sim-test-id' +KEY = 'sim-test-secret' +# RawSimulator.MIN_PART_SIZE, which most part-size tests are written for. +PART_SIZE = 200 +DEFAULT_CONFIG = {'minimumPartSize': PART_SIZE, 'recommendedPartSize': PART_SIZE} +# Exits node when its stdin closes, which happens when the process that started it dies in any +# way (including SIGKILL), so a simulator never outlives its pytest worker. +_EXIT_WITH_PARENT = ( + 'data:text/javascript,process.stdin.on("end",()=>process.exit(0));process.stdin.resume()' +) + +_server: SimulatorServer | None = None +_enabled = False + + +@dataclass +class SimulatorServer: + process: subprocess.Popen + api_url: str + control_url: str + stderr: typing.IO[bytes] + + @classmethod + def start(cls, simulator_dir) -> SimulatorServer: + script = Path(simulator_dir) / SERVER_SCRIPT + args = ['--control', '--profile', 'b2'] + args += ['--min-part-size', str(PART_SIZE), '--recommended-part-size', str(PART_SIZE)] + stderr = tempfile.TemporaryFile() + process = subprocess.Popen( + [_node(), '--import', _EXIT_WITH_PARENT, str(script), *args], + stdin=subprocess.PIPE, + stdout=subprocess.PIPE, + stderr=stderr, + text=True, + ) + lines = _read_ready_lines(process) + urls = dict(line.split(' ', 1) for line in lines if ' ' in line) + if len(lines) < 3 or 'SIMULATOR-CONTROL' not in urls: + process.kill() + process.wait() + process.stdout.close() + stderr.seek(0) + message = stderr.read().decode(errors='replace') + stderr.close() + raise RuntimeError( + f'b2-simulator at {script} did not start (exit code {process.returncode}): ' + f'stdout {lines!r}, stderr {message!r}' + ) + api_url = next( + line.split()[1] for line in lines if line.startswith('SIMULATOR-LISTENING http:') + ) + return cls(process, api_url, urls['SIMULATOR-CONTROL'], stderr) + + def reset(self, config=None): + body = json.dumps({'config': {**DEFAULT_CONFIG, **(config or {})}}).encode() + request = urllib.request.Request( + self.control_url + '/reset', + data=body, + method='POST', + headers={'Content-Type': 'application/json'}, + ) + with urllib.request.urlopen(request, timeout=10) as response: + response.read() + + def stop(self): + if self.process.poll() is None: + self.process.stdin.close() # the simulator exits on its own; terminate as a fallback + try: + self.process.wait(timeout=5) + except subprocess.TimeoutExpired: + self.process.terminate() + self.process.wait(timeout=5) + self.process.stdout.close() + self.stderr.close() + + +def _node(): + node = shutil.which('node') + if node is None: + raise pytest.UsageError('--b2-simulator needs Node.js 20 or later on PATH (`node`)') + return node + + +def _read_ready_lines(process, count=3): + """Read the simulator's ready lines; give up after START_TIMEOUT_SECONDS or at end of output.""" + lines = [] + + def read(): + for _ in range(count): + line = process.stdout.readline() + if not line: + return + lines.append(line.strip()) + + reader = threading.Thread(target=read, daemon=True) + reader.start() + reader.join(START_TIMEOUT_SECONDS) + return list(lines) + + +def simulator_dir_from_env() -> Path: + value = os.environ.get(ENV_VAR) + if not value: + raise pytest.UsageError( + f'--b2-simulator needs {ENV_VAR}: set it to a checkout of ' + 'https://github.com/backblaze-labs/b2-simulator' + ) + script = Path(value) / SERVER_SCRIPT + if not script.is_file(): + raise pytest.UsageError( + f'--b2-simulator: no b2-simulator server at {script} (check {ENV_VAR})' + ) + return Path(value) + + +def raw_api_class(default): + """ + Return the raw API class a test should build its ``B2Api`` with. + + ``default`` is ``RawSimulator`` or a test's subclass of it. Under ``--b2-simulator`` the SDK's + own ``RawSimulator`` is replaced by an HTTP client of the per-worker b2-simulator; a test's + subclass (which overrides simulator internals) is returned unchanged. + """ + if not _enabled or not default.__module__.startswith('b2sdk.'): + return default + return _http_raw_api_class() + + +_HTTP_CLASS = None + + +def _http_raw_api_class(): + global _HTTP_CLASS + if _HTTP_CLASS is None: + from apiver_deps import B2Http, B2RawHTTPApi + + class B2SimulatorRawApi(B2RawHTTPApi): + """``B2RawHTTPApi`` for this worker's b2-simulator, with RawSimulator's test hooks.""" + + MIN_PART_SIZE = PART_SIZE + + def __init__(self, b2_http=None): + super().__init__(b2_http or B2Http()) + + def create_account(self): + """Return the simulator's fixed credential; its key id is not the account id.""" + return KEY_ID, KEY + + def authorize_account(self, realm_url, application_key_id, application_key): + # Every realm goes to the simulator, so a test can never reach real B2. + if _server is None: + raise RuntimeError('b2-simulator is not running (use it inside a test)') + return super().authorize_account( + _server.api_url, application_key_id, application_key + ) + + _HTTP_CLASS = B2SimulatorRawApi + return _HTTP_CLASS + + +def pytest_addoption(parser): + parser.addoption( + '--b2-simulator', + action='store_true', + default=False, + help=f'run simulator-backed unit tests against b2-simulator (checkout in ${ENV_VAR})', + ) + + +def pytest_configure(config): + global _enabled + config.addinivalue_line( + 'markers', + 'b2_simulator_config(**settings): b2-simulator reset settings for this test ' + '(only used with --b2-simulator)', + ) + config.addinivalue_line( + 'markers', 'needs_b2_simulator: run only with --b2-simulator (deselected otherwise)' + ) + if config.getoption('--b2-simulator'): + simulator_dir_from_env() + _node() + _enabled = True + + +def pytest_report_header(config): + if config.getoption('--b2-simulator'): + return f'b2-simulator: {os.environ[ENV_VAR]}' + + +def pytest_collection_modifyitems(config, items): + if config.getoption('--b2-simulator'): + return + deselected = [item for item in items if item.get_closest_marker('needs_b2_simulator')] + if deselected: + config.hook.pytest_deselected(items=deselected) + items[:] = [item for item in items if not item.get_closest_marker('needs_b2_simulator')] + + +@pytest.fixture(scope='session') +def b2_simulator_server(pytestconfig): + """This process's b2-simulator, started on first use and stopped with the session.""" + global _server + if not pytestconfig.getoption('--b2-simulator'): + raise pytest.UsageError('the b2_simulator_server fixture needs --b2-simulator') + _server = SimulatorServer.start(simulator_dir_from_env()) + yield _server + _server.stop() + _server = None + + +@pytest.fixture(autouse=True) +def _b2_simulator_reset(request, pytestconfig): + """Reset the simulator before each test, with the test's ``b2_simulator_config`` settings.""" + if not pytestconfig.getoption('--b2-simulator'): + return + server = request.getfixturevalue('b2_simulator_server') + config = {} + for marker in reversed(list(request.node.iter_markers('b2_simulator_config'))): + config.update(marker.kwargs) + server.reset(config) diff --git a/test/unit/bucket/test_bucket.py b/test/unit/bucket/test_bucket.py index 80a420d20..6a89439cd 100644 --- a/test/unit/bucket/test_bucket.py +++ b/test/unit/bucket/test_bucket.py @@ -55,6 +55,7 @@ from urllib3.response import HTTPResponse from test.helpers import NonSeekableIO, assert_dict_equal_ignore_extra +from test.unit.b2_simulator import raw_api_class from ..test_base import TestBase, create_key @@ -317,7 +318,7 @@ def get_api(self): return B2Api( self.account_info, cache=self.CACHE_CLASS(), - api_config=B2HttpApiConfig(_raw_api_class=self.RAW_SIMULATOR_CLASS), + api_config=B2HttpApiConfig(_raw_api_class=raw_api_class(self.RAW_SIMULATOR_CLASS)), ) def setUp(self): @@ -2372,7 +2373,7 @@ class B2ApiPatched(B2Api): self.api = B2ApiPatched( self.account_info, cache=self.CACHE_CLASS(), - api_config=B2HttpApiConfig(_raw_api_class=self.RAW_SIMULATOR_CLASS), + api_config=B2HttpApiConfig(_raw_api_class=raw_api_class(self.RAW_SIMULATOR_CLASS)), ) return self.api @@ -3173,7 +3174,7 @@ class TestDownloadTuneWriteBuffer(DownloadTestsBase, TestCaseWithBucket): def get_api(self): return B2Api( self.account_info, - api_config=B2HttpApiConfig(_raw_api_class=self.RAW_SIMULATOR_CLASS), + api_config=B2HttpApiConfig(_raw_api_class=raw_api_class(self.RAW_SIMULATOR_CLASS)), save_to_buffer_size=self.ALIGN_FACTOR, ) @@ -3221,7 +3222,7 @@ class TestDownloadNoHashChecking(DownloadTestsBase, TestCaseWithBucket): def get_api(self): return B2Api( self.account_info, - api_config=B2HttpApiConfig(_raw_api_class=self.RAW_SIMULATOR_CLASS), + api_config=B2HttpApiConfig(_raw_api_class=raw_api_class(self.RAW_SIMULATOR_CLASS)), check_download_hash=False, ) diff --git a/test/unit/bucket/test_notification_rules_nonexposure.py b/test/unit/bucket/test_notification_rules_nonexposure.py index 406f763db..a4c77fa49 100644 --- a/test/unit/bucket/test_notification_rules_nonexposure.py +++ b/test/unit/bucket/test_notification_rules_nonexposure.py @@ -52,6 +52,7 @@ from apiver_deps_exception import BadRequest, MissingAccountData from b2sdk._internal.b2http import B2Http +from test.unit.b2_simulator import raw_api_class # Random per run, so no credential-shaped literal lives in the source. SECRET_VALUES = { @@ -120,7 +121,10 @@ def respond(method, url, **kwargs): @pytest.fixture def unauthorized_bucket(): """A bucket whose account info was cleared, so the call fails before it is authorized.""" - api = B2Api(InMemoryAccountInfo(), api_config=B2HttpApiConfig(_raw_api_class=RawSimulator)) + api = B2Api( + InMemoryAccountInfo(), + api_config=B2HttpApiConfig(_raw_api_class=raw_api_class(RawSimulator)), + ) account_id, master_key = api.session.raw_api.create_account() api.authorize_account( application_key_id=account_id, application_key=master_key, realm='production' diff --git a/test/unit/bucket/test_regression_bucket.py b/test/unit/bucket/test_regression_bucket.py index 72e6c1417..93cdd3940 100644 --- a/test/unit/bucket/test_regression_bucket.py +++ b/test/unit/bucket/test_regression_bucket.py @@ -47,6 +47,7 @@ from apiver_deps_exception import NonExistentBucket from test.known_defect import expect +from test.unit.b2_simulator import raw_api_class from .test_bucket import TestCaseWithBucket @@ -286,7 +287,7 @@ def _api(self, account_info=None, cache=None): api = B2Api( account_info or InMemoryAccountInfo(), cache=cache if cache is not None else InMemoryCache(), - api_config=B2HttpApiConfig(_raw_api_class=RawSimulator), + api_config=B2HttpApiConfig(_raw_api_class=raw_api_class(RawSimulator)), ) account_id, master_key = api.session.raw_api.create_account() api.authorize_account( @@ -342,7 +343,8 @@ def test_c55_failed_authorization_preserves_session(self, account_kind, cache_ki old_allowed = info.get_allowed() if account_kind == 'different': other = B2Api( - InMemoryAccountInfo(), api_config=B2HttpApiConfig(_raw_api_class=RawSimulator) + InMemoryAccountInfo(), + api_config=B2HttpApiConfig(_raw_api_class=raw_api_class(RawSimulator)), ) other.session.raw_api = api.session.raw_api account_id, master_key = other.session.raw_api.create_account() @@ -446,7 +448,7 @@ def test_c8_failed_part_stops_remaining_part_uploads(self): api = B2Api( InMemoryAccountInfo(), cache=InMemoryCache(), - api_config=B2HttpApiConfig(_raw_api_class=RawSimulator), + api_config=B2HttpApiConfig(_raw_api_class=raw_api_class(RawSimulator)), max_upload_workers=1, # parts start one at a time, in order ) simulator = api.session.raw_api diff --git a/test/unit/conftest.py b/test/unit/conftest.py index 8d208fb08..c429a7211 100644 --- a/test/unit/conftest.py +++ b/test/unit/conftest.py @@ -26,6 +26,10 @@ pytest.register_assert_rewrite('test.unit') +from test.unit.b2_simulator import raw_api_class # noqa: E402 + +pytest_plugins = ['test.unit.b2_simulator'] + def get_api_versions(): return [ @@ -178,7 +182,7 @@ def b2api(): account_info = StubAccountInfo() api = B2Api( account_info, - api_config=B2HttpApiConfig(_raw_api_class=RawSimulator), + api_config=B2HttpApiConfig(_raw_api_class=raw_api_class(RawSimulator)), ) simulator = api.session.raw_api diff --git a/test/unit/file_version/test_file_version.py b/test/unit/file_version/test_file_version.py index 3079b1571..5eb1e85d4 100644 --- a/test/unit/file_version/test_file_version.py +++ b/test/unit/file_version/test_file_version.py @@ -31,6 +31,8 @@ ) from apiver_deps_exception import AccessDenied, FileNotPresent +from test.unit.b2_simulator import raw_api_class + if apiver_deps.V <= 1: from apiver_deps import FileVersionInfo as VFileVersion else: @@ -43,7 +45,9 @@ def setUp(self): self.account_info = InMemoryAccountInfo() self.cache = DummyCache() self.api = B2Api( - self.account_info, self.cache, api_config=B2HttpApiConfig(_raw_api_class=RawSimulator) + self.account_info, + self.cache, + api_config=B2HttpApiConfig(_raw_api_class=raw_api_class(RawSimulator)), ) self.raw_api = self.api.session.raw_api (self.application_key_id, self.master_key) = self.raw_api.create_account() diff --git a/test/unit/sync/test_regression_sync_actions.py b/test/unit/sync/test_regression_sync_actions.py index 435cd3e60..d21e364fb 100644 --- a/test/unit/sync/test_regression_sync_actions.py +++ b/test/unit/sync/test_regression_sync_actions.py @@ -35,6 +35,7 @@ from b2sdk._internal.scan.path import B2Path from b2sdk._internal.sync.action import B2CopyAction, B2DownloadAction from test.known_defect import expect +from test.unit.b2_simulator import raw_api_class pytestmark = [pytest.mark.apiver(from_ver=2)] @@ -46,7 +47,7 @@ def api_and_bucket(): api = B2Api( InMemoryAccountInfo(), cache=InMemoryCache(), - api_config=B2HttpApiConfig(_raw_api_class=RawSimulator), + api_config=B2HttpApiConfig(_raw_api_class=raw_api_class(RawSimulator)), ) account_id, key = api.session.raw_api.create_account() api.authorize_account(application_key_id=account_id, application_key=key, realm='production') diff --git a/test/unit/test_b2_simulator_plugin.py b/test/unit/test_b2_simulator_plugin.py new file mode 100644 index 000000000..fc2b4f4db --- /dev/null +++ b/test/unit/test_b2_simulator_plugin.py @@ -0,0 +1,235 @@ +###################################################################### +# +# File: test/unit/test_b2_simulator_plugin.py +# +# Copyright 2026 Backblaze Inc. All Rights Reserved. +# +# License https://www.backblaze.com/using_b2_code.html +# +###################################################################### +"""Tests of the opt-in ``--b2-simulator`` pytest plugin (``test/unit/b2_simulator.py``).""" + +from __future__ import annotations + +import os +import signal +import socket +import subprocess +import sys +import textwrap +import time +from pathlib import Path + +import pytest +from apiver_deps import RawSimulator + +ROOT = Path(__file__).parents[2] + + +def run_pytest(tmp_path, test_source, *args, env_update=None, env_remove=()): + """Run pytest in a subprocess on one generated test file, with the unit-test plugins loaded.""" + test_file = tmp_path / 'test_generated.py' + test_file.write_text(textwrap.dedent(test_source)) + env = {name: value for name, value in os.environ.items() if name not in env_remove} + env.pop('PYTEST_XDIST_WORKER', None) + env['PYTHONPATH'] = os.pathsep.join([str(ROOT), env.get('PYTHONPATH', '')]) + env.update(env_update or {}) + return subprocess.run( + [ + sys.executable, + '-m', + 'pytest', + '-p', + 'test.conftest', + '-p', + 'test.unit.conftest', + '-p', + 'no:cacheprovider', + '-p', + 'no:xdist', + '-q', + f'--rootdir={tmp_path}', + *args, + str(test_file), + ], + cwd=tmp_path, + env=env, + stdin=subprocess.DEVNULL, + capture_output=True, + text=True, + timeout=120, + check=False, + ) + + +PASSING_TEST = """ +def test_nothing(): + pass +""" + + +def test_opt_in_without_a_checkout_fails_and_names_the_variable(tmp_path): + completed = run_pytest( + tmp_path, PASSING_TEST, '--b2-simulator', env_remove=('B2_SIMULATOR_DIR',) + ) + assert completed.returncode == pytest.ExitCode.USAGE_ERROR, completed.stdout + assert '--b2-simulator needs B2_SIMULATOR_DIR' in completed.stderr + assert 'passed' not in completed.stdout + assert 'skipped' not in completed.stdout + + +def test_opt_in_with_a_directory_that_is_not_a_checkout_fails(tmp_path): + not_a_checkout = tmp_path / 'empty' + not_a_checkout.mkdir() + completed = run_pytest( + tmp_path, + PASSING_TEST, + '--b2-simulator', + env_update={'B2_SIMULATOR_DIR': str(not_a_checkout)}, + ) + assert completed.returncode == pytest.ExitCode.USAGE_ERROR, completed.stdout + expected = str(not_a_checkout / 'bin' / 'simulator' / 'serve.mjs') + assert f'no b2-simulator server at {expected}' in completed.stderr + assert 'passed' not in completed.stdout + + +def test_without_the_flag_the_fixtures_use_raw_simulator(tmp_path): + completed = run_pytest( + tmp_path, + """ + from apiver_deps import RawSimulator + + def test_fixture(b2api): + assert type(b2api.session.raw_api) is RawSimulator + """, + # Even with a checkout configured, nothing changes without the flag. + env_update={'B2_SIMULATOR_DIR': str(tmp_path / 'unused')}, + ) + assert completed.returncode == pytest.ExitCode.OK, completed.stdout + completed.stderr + assert '1 passed' in completed.stdout + + +@pytest.mark.needs_b2_simulator +def test_b2api_fixture_talks_to_this_workers_server(b2api, b2_simulator_server): + assert b2api.account_info.get_api_url() == b2_simulator_server.api_url + # The account id comes from the server, not from the key id the test logged in with. + key_id, _ = b2api.session.raw_api.create_account() + assert b2api.account_info.get_account_id() != key_id + bucket = b2api.create_bucket('plugin-start-check', 'allPrivate') + assert [b.name for b in b2api.list_buckets()] == [bucket.name] + + +@pytest.mark.needs_b2_simulator +def test_reset_uses_raw_simulator_part_size_by_default(b2api): + assert b2api.account_info.get_absolute_minimum_part_size() == RawSimulator.MIN_PART_SIZE + assert b2api.account_info.get_recommended_part_size() == RawSimulator.MIN_PART_SIZE + + +@pytest.mark.needs_b2_simulator +@pytest.mark.b2_simulator_config(minimumPartSize=300, recommendedPartSize=400) +def test_marker_config_is_sent_with_the_reset(b2api): + assert b2api.account_info.get_absolute_minimum_part_size() == 300 + assert b2api.account_info.get_recommended_part_size() == 400 + + +@pytest.mark.needs_b2_simulator +def test_each_test_starts_from_an_empty_server(tmp_path): + # Both tests create the same bucket name; the second can only pass if the server was reset. + completed = run_pytest( + tmp_path, + """ + import pytest + + @pytest.mark.parametrize('attempt', [1, 2]) + def test_create(b2api, b2_simulator_server, attempt, tmp_path_factory): + b2api.create_bucket('reset-check', 'allPrivate') + assert [b.name for b in b2api.list_buckets()] == ['reset-check'] + urls = tmp_path_factory.getbasetemp().parent / 'urls.txt' + with open(urls, 'a') as f: + f.write(b2_simulator_server.control_url + '\\n') + """, + '--b2-simulator', + f'--basetemp={tmp_path / "base"}', + ) + assert completed.returncode == pytest.ExitCode.OK, completed.stdout + completed.stderr + assert '2 passed' in completed.stdout + urls = (tmp_path / 'urls.txt').read_text().split() + assert len(urls) == 2 and urls[0] == urls[1], 'one server per pytest process' + + +def _assert_on_simulator(case, server): + from apiver_deps import B2RawHTTPApi + + case.setUp() + assert isinstance(case.simulator, B2RawHTTPApi) + assert case.api.account_info.get_api_url() == server.api_url + assert [b.name for b in case.api.list_buckets()] == [case.bucket_name] + + +@pytest.mark.needs_b2_simulator +@pytest.mark.apiver(from_ver=1) +def test_test_case_with_bucket_uses_the_simulator(b2_simulator_server): + from test.unit.bucket.test_bucket import TestCaseWithBucket + + _assert_on_simulator(TestCaseWithBucket('setUp'), b2_simulator_server) + + +@pytest.mark.needs_b2_simulator +@pytest.mark.apiver(0) +def test_v0_test_case_with_bucket_uses_the_simulator(b2_simulator_server): + from test.unit.v0.test_bucket import TestCaseWithBucket + + _assert_on_simulator(TestCaseWithBucket('setUp'), b2_simulator_server) + + +@pytest.mark.needs_b2_simulator +def test_a_tests_own_simulator_subclass_stays_in_process(): + from test.unit.b2_simulator import raw_api_class + + class PatchedSimulator(RawSimulator): + pass + + assert raw_api_class(PatchedSimulator) is PatchedSimulator + + +def _port_open(url): + host, port = url.rsplit('/', 1)[-1].rsplit(':', 1) + with socket.socket() as sock: + sock.settimeout(1) + return sock.connect_ex((host, int(port))) == 0 + + +@pytest.mark.needs_b2_simulator +def test_server_stops_when_its_pytest_process_is_killed(): + child = subprocess.Popen( + [ + sys.executable, + '-c', + 'import sys, time\n' + 'from test.unit.b2_simulator import SimulatorServer\n' + 'server = SimulatorServer.start(sys.argv[1])\n' + 'print(server.control_url, flush=True)\n' + 'time.sleep(120)\n', + os.environ['B2_SIMULATOR_DIR'], + ], + cwd=ROOT, + stdin=subprocess.DEVNULL, + stdout=subprocess.PIPE, + text=True, + ) + try: + control_url = child.stdout.readline().strip() + assert control_url.startswith('http://127.0.0.1:'), control_url + assert _port_open(control_url) + if hasattr(signal, 'SIGKILL'): + child.send_signal(signal.SIGKILL) # no atexit, no fixture teardown + else: + child.kill() + child.wait(timeout=10) + deadline = time.monotonic() + 10 + while _port_open(control_url) and time.monotonic() < deadline: + time.sleep(0.05) + assert not _port_open(control_url), 'the simulator outlived the process that started it' + finally: + child.kill() + child.stdout.close() diff --git a/test/unit/v0/test_bucket.py b/test/unit/v0/test_bucket.py index 9dbfe1c6e..af010884d 100644 --- a/test/unit/v0/test_bucket.py +++ b/test/unit/v0/test_bucket.py @@ -17,6 +17,8 @@ import pytest +from test.unit.b2_simulator import raw_api_class + from ..test_base import TestBase from .deps import ( NO_RETENTION_FILE_SETTING, @@ -168,7 +170,7 @@ class TestCaseWithBucket(TestBase): def setUp(self): self.bucket_name = 'my-bucket' - self.simulator = self.RAW_SIMULATOR_CLASS() + self.simulator = raw_api_class(self.RAW_SIMULATOR_CLASS)() self.account_info = StubAccountInfo() self.api = B2Api(self.account_info, raw_api=self.simulator) (self.account_id, self.master_key) = self.simulator.create_account() diff --git a/test/unit/v_all/test_api.py b/test/unit/v_all/test_api.py index d40741e31..ea2d31eda 100644 --- a/test/unit/v_all/test_api.py +++ b/test/unit/v_all/test_api.py @@ -24,6 +24,8 @@ ) from apiver_deps_exception import BucketIdNotFound +from test.unit.b2_simulator import raw_api_class + from ..test_base import TestBase @@ -108,7 +110,9 @@ def setUp(self): self.account_info = InMemoryAccountInfo() self.cache = InMemoryCache() self.api = B2Api( - self.account_info, self.cache, api_config=B2HttpApiConfig(_raw_api_class=RawSimulator) + self.account_info, + self.cache, + api_config=B2HttpApiConfig(_raw_api_class=raw_api_class(RawSimulator)), ) self.raw_api = self.api.session.raw_api (self.application_key_id, self.master_key) = self.raw_api.create_account() diff --git a/test/unit/v_all/test_replication.py b/test/unit/v_all/test_replication.py index ee3185333..cc2ea01e1 100644 --- a/test/unit/v_all/test_replication.py +++ b/test/unit/v_all/test_replication.py @@ -23,6 +23,8 @@ ReplicationSetupHelper, ) +from test.unit.b2_simulator import raw_api_class + from ..test_base import TestBase logger = logging.getLogger(__name__) @@ -33,7 +35,9 @@ def setUp(self): self.account_info = InMemoryAccountInfo() self.cache = InMemoryCache() self.api = B2Api( - self.account_info, self.cache, api_config=B2HttpApiConfig(_raw_api_class=RawSimulator) + self.account_info, + self.cache, + api_config=B2HttpApiConfig(_raw_api_class=raw_api_class(RawSimulator)), ) self.raw_api = self.api.session.raw_api self.application_key_id, self.master_key = self.raw_api.create_account() From f991998e1008f0150c0ea818d3a7aa4818d6c37b Mon Sep 17 00:00:00 2001 From: Sophie <49928680+sophiecarreras@users.noreply.github.com> Date: Fri, 27 Nov 2026 03:50:29 -0300 Subject: [PATCH 089/113] test: fix test data that only RawSimulator accepted These fixes are correct on both RawSimulator and b2-simulator: - SSE-C test keys are 256-bit (32-byte) AES keys, as B2 requires. - The reauthorization fixture uses the authorized account id, not the key id, as the account id. - Assertions derive file ids, key ids, a bucket id, the authorization token, the stored content type and download URLs from the server's answers instead of RawSimulator's fixed values. Each stays an exact comparison. Co-Authored-By: Claude Opus 5.5 --- ...2-simulator-unit-harness.infrastructure.md | 1 + .../test_reauth_drops_pooled_urls.py | 5 ++- test/unit/api/test_api.py | 41 ++++++------------- test/unit/bucket/test_bucket.py | 31 +++++++------- test/unit/file_version/test_file_version.py | 13 ++++-- test/unit/replication/test_monitoring.py | 2 +- test/unit/v0/test_bucket.py | 5 ++- test/unit/v_all/test_api.py | 8 ++-- test/unit/v_all/test_replication.py | 7 ++-- 9 files changed, 53 insertions(+), 60 deletions(-) create mode 100644 changelog.d/+b2-simulator-unit-harness.infrastructure.md diff --git a/changelog.d/+b2-simulator-unit-harness.infrastructure.md b/changelog.d/+b2-simulator-unit-harness.infrastructure.md new file mode 100644 index 000000000..bb60064e3 --- /dev/null +++ b/changelog.d/+b2-simulator-unit-harness.infrastructure.md @@ -0,0 +1 @@ +Add an opt-in `--b2-simulator` pytest option that runs the simulator-backed unit tests against the standalone b2-simulator over HTTP, and fix test data that only the in-process `RawSimulator` accepted: SSE-C test keys are now 256-bit, the reauthorization fixture uses the authorized account id instead of the key id, and assertions derive file ids, key ids, bucket ids, authorization tokens and URLs instead of using `RawSimulator`'s fixed values. diff --git a/test/unit/account_info/test_reauth_drops_pooled_urls.py b/test/unit/account_info/test_reauth_drops_pooled_urls.py index e784161a6..53a376360 100644 --- a/test/unit/account_info/test_reauth_drops_pooled_urls.py +++ b/test/unit/account_info/test_reauth_drops_pooled_urls.py @@ -30,8 +30,9 @@ def session_with_keys(account_info): api_config=B2HttpApiConfig(_raw_api_class=raw_api_class(RawSimulator)), ) simulator = session.raw_api - account_id, master_key = simulator.create_account() - session.authorize_account('production', account_id, master_key) + key_id, master_key = simulator.create_account() + session.authorize_account('production', key_id, master_key) + account_id = account_info.get_account_id() # B2 account ids differ from key ids bucket_id = session.create_bucket(account_id, 'reauth-test', 'allPrivate')['bucketId'] file_id = session.start_large_file(bucket_id, 'large.bin', 'application/octet-stream', {})[ 'fileId' diff --git a/test/unit/api/test_api.py b/test/unit/api/test_api.py index 292a8e562..8be23cc5e 100644 --- a/test/unit/api/test_api.py +++ b/test/unit/api/test_api.py @@ -126,22 +126,23 @@ def test_get_file_info(self): def test_get_file_info_by_name(self): self._authorize_account() bucket = self.api.create_bucket('bucket1', 'allPrivate') - bucket.upload_bytes( + uploaded = bucket.upload_bytes( b'hello world', 'file', ) result = self.api.get_file_info_by_name('bucket1', 'file') + # The server assigns the id, the timestamp and the stored content type at upload. expected_result = { - 'fileId': '9999', + 'fileId': uploaded.id_, 'fileName': 'file', 'fileInfo': {}, 'serverSideEncryption': {'algorithm': 'AES256', 'mode': 'SSE-B2'}, 'legalHold': None, 'fileRetention': {'mode': None, 'retainUntilTimestamp': None}, 'size': 11, - 'uploadTimestamp': 5000, - 'contentType': 'b2/x-auto', + 'uploadTimestamp': uploaded.upload_timestamp, + 'contentType': uploaded.content_type, 'contentSha1': '2aae6c35c94fcfb415dbe95f408b9ce91ee846ed', 'replicationStatus': None, } @@ -199,7 +200,9 @@ def test_get_non_existent_file_info_by_name(self): def test_get_file_info_by_name_with_properties(self): encr_setting = EncryptionSetting( - EncryptionMode.SSE_C, EncryptionAlgorithm.AES256, EncryptionKey(b'secret', None) + EncryptionMode.SSE_C, + EncryptionAlgorithm.AES256, + EncryptionKey(b'secret'.ljust(32, b'.'), None), ) lh_setting = LegalHold.ON retention_setting = FileRetentionSetting(RetentionMode.COMPLIANCE, 100) @@ -777,32 +780,12 @@ def test_list_keys_v1(self): @pytest.mark.apiver(from_ver=2) def test_list_keys_v2(self): self._authorize_account() - for i in range(20): - self.api.create_key(['readFiles'], f'testkey{i}') + existing_ids = [key.id_ for key in self.api.list_keys()] + created_ids = [self.api.create_key(['readFiles'], f'testkey{i}').id_ for i in range(20)] with mock.patch.object(self.api, 'DEFAULT_LIST_KEY_COUNT', 10): keys = list(self.api.list_keys()) - assert [key.id_ for key in keys] == [ - 'appKeyId0', - 'appKeyId1', - 'appKeyId10', - 'appKeyId11', - 'appKeyId12', - 'appKeyId13', - 'appKeyId14', - 'appKeyId15', - 'appKeyId16', - 'appKeyId17', - 'appKeyId18', - 'appKeyId19', - 'appKeyId2', - 'appKeyId3', - 'appKeyId4', - 'appKeyId5', - 'appKeyId6', - 'appKeyId7', - 'appKeyId8', - 'appKeyId9', - ] + # Keys are listed in key id order, across pages. + assert [key.id_ for key in keys] == sorted(existing_ids + created_ids) assert isinstance(keys[0], ApplicationKey) def test_get_key(self): diff --git a/test/unit/bucket/test_bucket.py b/test/unit/bucket/test_bucket.py index 6a89439cd..89dd05f36 100644 --- a/test/unit/bucket/test_bucket.py +++ b/test/unit/bucket/test_bucket.py @@ -116,10 +116,11 @@ pytestmark = [pytest.mark.apiver(from_ver=1)] +# SSE-C keys must be 256-bit (32-byte) AES keys, as B2 requires. SSE_C_AES = EncryptionSetting( mode=EncryptionMode.SSE_C, algorithm=EncryptionAlgorithm.AES256, - key=EncryptionKey(secret=b'some_key', key_id='some-id'), + key=EncryptionKey(secret=b'some_key'.ljust(32, b'.'), key_id='some-id'), ) SSE_NONE = EncryptionSetting(mode=EncryptionMode.NONE) SSE_C_AES_NO_SECRET = EncryptionSetting( @@ -130,7 +131,7 @@ SSE_C_AES_2 = EncryptionSetting( mode=EncryptionMode.SSE_C, algorithm=EncryptionAlgorithm.AES256, - key=EncryptionKey(secret=b'some_other_key', key_id='some-id-2'), + key=EncryptionKey(secret=b'some_other_key'.ljust(32, b'.'), key_id='some-id-2'), ) SSE_C_AES_2_NO_SECRET = EncryptionSetting( mode=EncryptionMode.SSE_C, @@ -653,19 +654,15 @@ def test_three_files_in_dir(self): def test_three_files_multiple_versions(self): data = b'hello world' - self.bucket.upload_bytes(data, 'a') - self.bucket.upload_bytes(data, 'bb/1') - self.bucket.upload_bytes(data, 'bb/2') - self.bucket.upload_bytes(data, 'bb/2') - self.bucket.upload_bytes(data, 'bb/2') - self.bucket.upload_bytes(data, 'bb/3') - self.bucket.upload_bytes(data, 'ccc') + names = ['a', 'bb/1', 'bb/2', 'bb/2', 'bb/2', 'bb/3', 'ccc'] + ids = [self.bucket.upload_bytes(data, name).id_ for name in names] + # Versions of one name are listed newest first. expected = [ - ('9998', 'bb/1', 11, 'upload', None), - ('9995', 'bb/2', 11, 'upload', None), - ('9996', 'bb/2', 11, 'upload', None), - ('9997', 'bb/2', 11, 'upload', None), - ('9994', 'bb/3', 11, 'upload', None), + (ids[1], 'bb/1', 11, 'upload', None), + (ids[4], 'bb/2', 11, 'upload', None), + (ids[3], 'bb/2', 11, 'upload', None), + (ids[2], 'bb/2', 11, 'upload', None), + (ids[5], 'bb/3', 11, 'upload', None), ] actual = [ (info.id_, info.file_name, info.size, info.action, folder) @@ -2204,7 +2201,8 @@ def test_create_file_over_10k_parts(self): created_file.size, created_file.server_side_encryption, ) - expected = ('9998', 'created_file', len(data), SSE_B2_AES) + latest_id = self.bucket.get_file_info_by_name('created_file').id_ + expected = (latest_id, 'created_file', len(data), SSE_B2_AES) self.assertEqual(expected, actual) def test_upload_large_resume(self): @@ -2443,7 +2441,8 @@ def test_create_remote(self): created_file.size, created_file.server_side_encryption, ) - expected = ('9997', 'created_file', 33, SSE_B2_AES) + latest_id = self.bucket.get_file_info_by_name('created_file').id_ + expected = (latest_id, 'created_file', 33, SSE_B2_AES) self.assertEqual(expected, actual) def test_create_remote_encryption(self): diff --git a/test/unit/file_version/test_file_version.py b/test/unit/file_version/test_file_version.py index 5eb1e85d4..531f48897 100644 --- a/test/unit/file_version/test_file_version.py +++ b/test/unit/file_version/test_file_version.py @@ -87,7 +87,9 @@ def test_get_fresh_state(self): def test_clone_file_version_and_download_version(self): encryption = EncryptionSetting( - EncryptionMode.SSE_C, EncryptionAlgorithm.AES256, EncryptionKey(b'secret', None) + EncryptionMode.SSE_C, + EncryptionAlgorithm.AES256, + EncryptionKey(b'secret'.ljust(32, b'.'), None), ) initial_file_version = self.bucket.upload_bytes( b'nothing', @@ -187,13 +189,16 @@ def test_file_version_upload_headers(self): ), ) + # The token and the stored content type come from the server. + auth_token = self.account_info.get_account_auth_token() + content_type = file_version.content_type assert ( file_version._get_upload_headers() - == """ - Authorization: auth_token_0 + == f""" + Authorization: {auth_token} Content-Length: 7 X-Bz-File-Name: test_file - Content-Type: b2/x-auto + Content-Type: {content_type} X-Bz-Content-Sha1: 0feca720e2c29dafb2c900713ba560e03b758711 X-Bz-Info-b2-cache-control: private%2C%20max-age%3D3600 X-Bz-Server-Side-Encryption-Customer-Algorithm: AES256 diff --git a/test/unit/replication/test_monitoring.py b/test/unit/replication/test_monitoring.py index 798068fec..e559c261d 100644 --- a/test/unit/replication/test_monitoring.py +++ b/test/unit/replication/test_monitoring.py @@ -29,7 +29,7 @@ SSE_C_AES = EncryptionSetting( mode=EncryptionMode.SSE_C, algorithm=EncryptionAlgorithm.AES256, - key=EncryptionKey(secret=b'some_key', key_id='some-id'), + key=EncryptionKey(secret=b'some_key'.ljust(32, b'.'), key_id='some-id'), ) RETENTION_GOVERNANCE = FileRetentionSetting(RetentionMode.GOVERNANCE, retain_until=1) diff --git a/test/unit/v0/test_bucket.py b/test/unit/v0/test_bucket.py index af010884d..4b0a520bd 100644 --- a/test/unit/v0/test_bucket.py +++ b/test/unit/v0/test_bucket.py @@ -65,10 +65,11 @@ WrongEncryptionSettingForFileWrite, ) +# SSE-C keys must be 256-bit (32-byte) AES keys, as B2 requires. SSE_C_AES = EncryptionSetting( mode=EncryptionMode.SSE_C, algorithm=EncryptionAlgorithm.AES256, - key=EncryptionKey(secret=b'some_key', key_id='some-id'), + key=EncryptionKey(secret=b'some_key'.ljust(32, b'.'), key_id='some-id'), ) SSE_C_AES_NO_SECRET = EncryptionSetting( mode=EncryptionMode.SSE_C, @@ -78,7 +79,7 @@ SSE_C_AES_2 = EncryptionSetting( mode=EncryptionMode.SSE_C, algorithm=EncryptionAlgorithm.AES256, - key=EncryptionKey(secret=b'some_other_key', key_id='some-id-2'), + key=EncryptionKey(secret=b'some_other_key'.ljust(32, b'.'), key_id='some-id-2'), ) SSE_C_AES_2_NO_SECRET = EncryptionSetting( mode=EncryptionMode.SSE_C, diff --git a/test/unit/v_all/test_api.py b/test/unit/v_all/test_api.py index ea2d31eda..3cd031084 100644 --- a/test/unit/v_all/test_api.py +++ b/test/unit/v_all/test_api.py @@ -159,16 +159,18 @@ def test_get_download_url_for_file_name(self): download_url = self.api.get_download_url_for_file_name('bucket1', 'some-file.txt') - assert download_url == 'http://download.example.com/file/bucket1/some-file.txt' + base_url = self.account_info.get_download_url() + assert download_url == f'{base_url}/file/bucket1/some-file.txt' def test_get_download_url_for_fileid(self): self._authorize_account() download_url = self.api.get_download_url_for_fileid('file-id') + base_url = self.account_info.get_download_url() if apiver_deps.V >= 3: - exp_url = 'http://download.example.com/b2api/v4/b2_download_file_by_id?fileId=file-id' + exp_url = f'{base_url}/b2api/v4/b2_download_file_by_id?fileId=file-id' else: - exp_url = 'http://download.example.com/b2api/v3/b2_download_file_by_id?fileId=file-id' + exp_url = f'{base_url}/b2api/v3/b2_download_file_by_id?fileId=file-id' assert download_url == exp_url diff --git a/test/unit/v_all/test_replication.py b/test/unit/v_all/test_replication.py index cc2ea01e1..0cce8835c 100644 --- a/test/unit/v_all/test_replication.py +++ b/test/unit/v_all/test_replication.py @@ -54,6 +54,7 @@ def test_setup_both(self): self._authorize_account() source_bucket = self.api.create_bucket('bucket1', 'allPrivate') destination_bucket = self.api.create_bucket('bucket2', 'allPrivate') + destination_bucket_id = destination_bucket.id_ logger.info('preparations complete, starting the test') rsh = ReplicationSetupHelper() source_bucket, destination_bucket = rsh.setup_both( @@ -87,7 +88,7 @@ def test_setup_both(self): assert source_bucket.replication.rules == [ ReplicationRule( - destination_bucket_id='bucket_1', + destination_bucket_id=destination_bucket_id, name='aa', file_name_prefix='ab', is_enabled=True, @@ -117,14 +118,14 @@ def test_setup_both(self): new_source_application_key = keymap['bucket1-replisrc'] assert source_bucket.replication.rules == [ ReplicationRule( - destination_bucket_id='bucket_1', + destination_bucket_id=destination_bucket_id, name='aa', file_name_prefix='ab', is_enabled=True, priority=128, ), ReplicationRule( - destination_bucket_id='bucket_1', + destination_bucket_id=destination_bucket_id, name='bucket2', file_name_prefix='ad', is_enabled=True, From 4117d19ff679d73bec47cfeb23763146bba94c1e Mon Sep 17 00:00:00 2001 From: Sophie <49928680+sophiecarreras@users.noreply.github.com> Date: Fri, 27 Nov 2026 04:00:20 -0300 Subject: [PATCH 090/113] ci: keep release live runs from being replaced; report cancelled weekly runs - Give each caller workflow and ref its own live-B2 concurrency group. GitHub keeps one pending job per group, so a shared group let a queued weekly or manual run cancel a pending release run, skipping deploy. - Open or update the weekly failure issue for any scheduled run that did not succeed, including cancelled or timed-out runs. - Static tests require deploy.needs to be a list, so a string cannot pass the membership check as a substring. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/live-b2-tests.yml | 7 +++++-- .github/workflows/live-b2.yml | 5 +++-- README.release.md | 4 ++-- test/static/test_ci_draft_safety.py | 13 ++++++++++--- test/static/test_release_workflow_safety.py | 2 ++ 5 files changed, 22 insertions(+), 9 deletions(-) diff --git a/.github/workflows/live-b2-tests.yml b/.github/workflows/live-b2-tests.yml index 9955450b1..3ec1ff224 100644 --- a/.github/workflows/live-b2-tests.yml +++ b/.github/workflows/live-b2-tests.yml @@ -26,9 +26,12 @@ jobs: live-b2-integration: runs-on: ubuntu-latest timeout-minutes: 120 - # Every caller shares one live B2 account: run one live job at a time and never cancel one mid-run. + # One group per caller workflow and ref (in a called workflow these are the caller's), so a + # queued weekly or manual run never replaces a pending release run. Runs from different + # groups may share the live account; test buckets have unique names and cleanup only removes + # test buckets older than three hours. concurrency: - group: live-b2-account + group: live-b2-${{ github.workflow }}-${{ github.ref }} cancel-in-progress: false env: LIVE_B2_CREDENTIALS_SET: ${{ secrets.B2_TEST_APPLICATION_KEY_ID != '' && secrets.B2_TEST_APPLICATION_KEY != '' }} diff --git a/.github/workflows/live-b2.yml b/.github/workflows/live-b2.yml index f20e643f8..cca89c34e 100644 --- a/.github/workflows/live-b2.yml +++ b/.github/workflows/live-b2.yml @@ -19,7 +19,8 @@ jobs: report-scheduled-failure: needs: live-b2 - if: ${{ failure() && github.event_name == 'schedule' }} + # Any scheduled run that did not succeed, including a cancelled or timed-out one. + if: ${{ always() && github.event_name == 'schedule' && needs.live-b2.result != 'success' }} runs-on: ubuntu-latest timeout-minutes: 5 permissions: @@ -32,7 +33,7 @@ jobs: RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }} run: | title="Weekly live B2 integration failed" - body="The scheduled live B2 run failed: $RUN_URL" + body="The scheduled live B2 run did not succeed: $RUN_URL" number="$(gh issue list --state open --search "\"$title\" in:title" --json number,title \ --jq "map(select(.title == \"$title\")) | first | .number // empty")" if [ -n "$number" ]; then diff --git a/README.release.md b/README.release.md index fbc01023e..f853fc676 100644 --- a/README.release.md +++ b/README.release.md @@ -64,8 +64,8 @@ Triggered by any pushed tag matching `v*`: 2. Runs the unit tests, and runs the integration suite against live B2 on the tagged commit (`.github/workflows/live-b2-tests.yml`). Pull requests test against the B2 Simulator only, so this is the release's real-B2 check. Nothing is built or published unless both pass. The live - run needs the `B2_TEST_APPLICATION_KEY_ID` and `B2_TEST_APPLICATION_KEY` secrets, and it waits - while another live run (for example the weekly one) is using the test account. + run needs the `B2_TEST_APPLICATION_KEY_ID` and `B2_TEST_APPLICATION_KEY` secrets. Each tag + gets its own concurrency group, so a weekly or manual live run cannot cancel it. 3. Builds the distribution with `nox -s build`, which also asserts the built package imports from `site-packages` rather than the checkout. The version is derived from the tag, not from any file. 4. Reads the notes for that version out of `CHANGELOG.md`. If the tag and the changelog heading do not diff --git a/test/static/test_ci_draft_safety.py b/test/static/test_ci_draft_safety.py index e2a301d6b..71368dc4e 100644 --- a/test/static/test_ci_draft_safety.py +++ b/test/static/test_ci_draft_safety.py @@ -172,7 +172,11 @@ def test_live_b2_tests_are_reusable_serialized_and_fail_closed(): assert set(events['workflow_call']['secrets']) == set(KEYS) assert workflow['permissions'] == {'contents': 'read'} [job] = workflow['jobs'].values() - assert job['concurrency'] == {'group': 'live-b2-account', 'cancel-in-progress': False} + # One group per caller and ref: a newer queued run must never replace a pending release run. + assert job['concurrency'] == { + 'group': 'live-b2-${{ github.workflow }}-${{ github.ref }}', + 'cancel-in-progress': False, + } assert job['env']['LIVE_B2_CREDENTIALS_SET'] == ( "${{ secrets.B2_TEST_APPLICATION_KEY_ID != '' && secrets.B2_TEST_APPLICATION_KEY != '' }}" ) @@ -224,8 +228,11 @@ def test_weekly_live_b2_reports_scheduled_failures_with_a_scoped_token(): [reporter] = reporters assert reporter['permissions'] == {'issues': 'write'} assert reporter['needs'] == live[0] - assert 'failure()' in reporter['if'] - assert "github.event_name == 'schedule'" in reporter['if'] + # Report any scheduled run that did not succeed, including cancelled or timed-out runs. + assert reporter['if'] == ( + "${{ always() && github.event_name == 'schedule' && needs.%s.result != 'success' }}" + % live[0] + ) run = '\n'.join(step.get('run', '') for step in reporter['steps']) assert 'gh issue create' in run assert 'gh issue comment' in run diff --git a/test/static/test_release_workflow_safety.py b/test/static/test_release_workflow_safety.py index ca05042f5..9d11ba5d3 100644 --- a/test/static/test_release_workflow_safety.py +++ b/test/static/test_release_workflow_safety.py @@ -36,6 +36,7 @@ def test_active_actions_are_pinned_to_full_commit_shas(): def test_release_requires_successful_unit_tests(): jobs = load_workflow('cd.yml')['jobs'] + assert isinstance(jobs['deploy']['needs'], list) assert 'test' in jobs['deploy']['needs'] assert 'if' not in jobs['deploy'] steps = jobs['test']['steps'] @@ -45,6 +46,7 @@ def test_release_requires_successful_unit_tests(): def test_release_requires_a_green_live_b2_run_of_the_tagged_commit(): jobs = load_workflow('cd.yml')['jobs'] + assert isinstance(jobs['deploy']['needs'], list) assert set(jobs['deploy']['needs']) == {'test', 'live-b2'} live = jobs['live-b2'] assert live['uses'] == './.github/workflows/live-b2-tests.yml' From 8e3e7f647096269216c0d664a9127cb1c2ca63f5 Mon Sep 17 00:00:00 2001 From: Sophie <49928680+sophiecarreras@users.noreply.github.com> Date: Fri, 27 Nov 2026 04:03:11 -0300 Subject: [PATCH 091/113] test: harden the --b2-simulator plugin after review - Register the plugin in test/conftest.py: pytest refuses pytest_plugins in test/unit/conftest.py when it collects the whole test directory. - A second create_account() on the simulator's raw API now fails. RawSimulator makes a new account on every call; b2-simulator has one, so the "different account" regression cases failed to test what they say. - Report a missing HTTP ready line as a start failure, and kill the simulator if it ignores both stdin EOF and SIGTERM at teardown. - State Node.js 20.6 (needed for --import), that b2-simulator is not public yet, and that MIN_PART_SIZE stays 200 under a part-size marker. Co-Authored-By: Claude Opus 5.5 --- docs/testing.md | 6 ++-- test/conftest.py | 3 +- test/unit/b2_simulator.py | 50 ++++++++++++++++++--------- test/unit/conftest.py | 2 -- test/unit/test_b2_simulator_plugin.py | 25 ++++++++++++-- 5 files changed, 62 insertions(+), 24 deletions(-) diff --git a/docs/testing.md b/docs/testing.md index bb0307355..f7851f210 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -18,10 +18,11 @@ The unit session selects each API version with the `--api` option. ## Unit tests on the standalone b2-simulator (opt-in) The `--b2-simulator` option runs the simulator-backed unit tests against -[b2-simulator](https://github.com/backblaze-labs/b2-simulator) over HTTP instead of the in-process `RawSimulator`. +b2-simulator (`backblaze-labs/b2-simulator`) over HTTP instead of the in-process `RawSimulator`. The default run does not change. The option is in trial: many tests still fail with it. +The b2-simulator repository is not public yet, so only people with access to it can use the option. -1. Clone b2-simulator. It needs Node.js 20 or later. +1. Clone b2-simulator. It needs Node.js 20.6 or later. 2. Set `B2_SIMULATOR_DIR` to the clone. 3. Run `uv run --group test pytest --api=v3 -n auto --b2-simulator test/unit`. @@ -29,6 +30,7 @@ The plugin in [`test/unit/b2_simulator.py`](../test/unit/b2_simulator.py) starts With pytest-xdist, each worker gets its own simulator. The plugin resets the simulator before each test. The reset sets the part sizes to `RawSimulator.MIN_PART_SIZE` (200 bytes). Use `@pytest.mark.b2_simulator_config(...)` to send other reset settings for one test. +The raw API's `MIN_PART_SIZE` attribute stays 200 bytes; a test that changes the part size must not size its data from it. A simulator stops when the pytest process that started it stops. If `B2_SIMULATOR_DIR` is missing or wrong, or `node` is not on `PATH`, the run stops with a usage error. It does not skip tests. diff --git a/test/conftest.py b/test/conftest.py index e5ea5ba4e..8fcc39253 100644 --- a/test/conftest.py +++ b/test/conftest.py @@ -11,7 +11,8 @@ import pytest -pytest_plugins = ['b2sdk.v3.testing', 'test.junit_subtests'] +# test.unit.b2_simulator: the opt-in --b2-simulator option for the unit tests. +pytest_plugins = ['b2sdk.v3.testing', 'test.junit_subtests', 'test.unit.b2_simulator'] def pytest_configure(config): diff --git a/test/unit/b2_simulator.py b/test/unit/b2_simulator.py index bef58d14e..8ac7f92f3 100644 --- a/test/unit/b2_simulator.py +++ b/test/unit/b2_simulator.py @@ -11,7 +11,7 @@ Opt-in pytest plugin: run the unit tests against the standalone b2-simulator. ``pytest --b2-simulator`` with ``B2_SIMULATOR_DIR`` set to a checkout of -https://github.com/backblaze-labs/b2-simulator starts one simulator per pytest process (so one +backblaze-labs/b2-simulator starts one simulator per pytest process (so one per pytest-xdist worker) and resets it before every test. Tests that build their API through :func:`raw_api_class` (the ``b2api`` fixture, ``TestCaseWithBucket`` and the other shared setups) then talk to it over HTTP instead of using the in-process ``RawSimulator``. @@ -79,7 +79,11 @@ def start(cls, simulator_dir) -> SimulatorServer: ) lines = _read_ready_lines(process) urls = dict(line.split(' ', 1) for line in lines if ' ' in line) - if len(lines) < 3 or 'SIMULATOR-CONTROL' not in urls: + api_url = next( + (line.split()[1] for line in lines if line.startswith('SIMULATOR-LISTENING http:')), + None, + ) + if api_url is None or 'SIMULATOR-CONTROL' not in urls: process.kill() process.wait() process.stdout.close() @@ -90,9 +94,6 @@ def start(cls, simulator_dir) -> SimulatorServer: f'b2-simulator at {script} did not start (exit code {process.returncode}): ' f'stdout {lines!r}, stderr {message!r}' ) - api_url = next( - line.split()[1] for line in lines if line.startswith('SIMULATOR-LISTENING http:') - ) return cls(process, api_url, urls['SIMULATOR-CONTROL'], stderr) def reset(self, config=None): @@ -107,21 +108,25 @@ def reset(self, config=None): response.read() def stop(self): - if self.process.poll() is None: - self.process.stdin.close() # the simulator exits on its own; terminate as a fallback - try: - self.process.wait(timeout=5) - except subprocess.TimeoutExpired: - self.process.terminate() - self.process.wait(timeout=5) - self.process.stdout.close() - self.stderr.close() + try: + # The simulator exits when its stdin closes; terminate and kill are fallbacks. + self.process.stdin.close() + for fallback in (self.process.terminate, self.process.kill): + try: + self.process.wait(timeout=5) + break + except subprocess.TimeoutExpired: + fallback() + self.process.wait(timeout=5) + finally: + self.process.stdout.close() + self.stderr.close() def _node(): node = shutil.which('node') if node is None: - raise pytest.UsageError('--b2-simulator needs Node.js 20 or later on PATH (`node`)') + raise pytest.UsageError('--b2-simulator needs Node.js 20.6 or later on PATH (`node`)') return node @@ -147,7 +152,7 @@ def simulator_dir_from_env() -> Path: if not value: raise pytest.UsageError( f'--b2-simulator needs {ENV_VAR}: set it to a checkout of ' - 'https://github.com/backblaze-labs/b2-simulator' + 'backblaze-labs/b2-simulator' ) script = Path(value) / SERVER_SCRIPT if not script.is_file(): @@ -187,7 +192,18 @@ def __init__(self, b2_http=None): super().__init__(b2_http or B2Http()) def create_account(self): - """Return the simulator's fixed credential; its key id is not the account id.""" + """ + Return the simulator's fixed credential; its key id is not the account id. + + RawSimulator makes a new account on every call. b2-simulator has one account, so a + second call fails instead of silently returning the first account again. + """ + if getattr(self, '_account_created', False): + raise RuntimeError( + 'b2-simulator has one account: this test needs a second account, ' + 'which only RawSimulator provides' + ) + self._account_created = True return KEY_ID, KEY def authorize_account(self, realm_url, application_key_id, application_key): diff --git a/test/unit/conftest.py b/test/unit/conftest.py index c429a7211..54b20559b 100644 --- a/test/unit/conftest.py +++ b/test/unit/conftest.py @@ -28,8 +28,6 @@ from test.unit.b2_simulator import raw_api_class # noqa: E402 -pytest_plugins = ['test.unit.b2_simulator'] - def get_api_versions(): return [ diff --git a/test/unit/test_b2_simulator_plugin.py b/test/unit/test_b2_simulator_plugin.py index fc2b4f4db..11d6b0cd6 100644 --- a/test/unit/test_b2_simulator_plugin.py +++ b/test/unit/test_b2_simulator_plugin.py @@ -109,12 +109,26 @@ def test_fixture(b2api): assert '1 passed' in completed.stdout +def test_the_whole_test_directory_still_collects(): + # pytest refuses `pytest_plugins` in a conftest below the top level when it collects `test`. + completed = subprocess.run( + [sys.executable, '-m', 'pytest', '--co', '-q', '-p', 'no:cacheprovider', 'test'], + cwd=ROOT, + stdin=subprocess.DEVNULL, + capture_output=True, + text=True, + timeout=120, + check=False, + ) + assert completed.returncode == pytest.ExitCode.OK, completed.stdout[-2000:] + + @pytest.mark.needs_b2_simulator def test_b2api_fixture_talks_to_this_workers_server(b2api, b2_simulator_server): assert b2api.account_info.get_api_url() == b2_simulator_server.api_url # The account id comes from the server, not from the key id the test logged in with. - key_id, _ = b2api.session.raw_api.create_account() - assert b2api.account_info.get_account_id() != key_id + assert b2api.account_info.get_application_key_id() == 'sim-test-id' + assert b2api.account_info.get_account_id() != 'sim-test-id' bucket = b2api.create_bucket('plugin-start-check', 'allPrivate') assert [b.name for b in b2api.list_buckets()] == [bucket.name] @@ -182,6 +196,13 @@ def test_v0_test_case_with_bucket_uses_the_simulator(b2_simulator_server): _assert_on_simulator(TestCaseWithBucket('setUp'), b2_simulator_server) +@pytest.mark.needs_b2_simulator +def test_a_second_account_fails_instead_of_reusing_the_first(b2api): + # RawSimulator.create_account() makes a new account on every call; b2-simulator has one. + with pytest.raises(RuntimeError, match='b2-simulator has one account'): + b2api.session.raw_api.create_account() + + @pytest.mark.needs_b2_simulator def test_a_tests_own_simulator_subclass_stays_in_process(): from test.unit.b2_simulator import raw_api_class From 4aef840aedb10b6725623f2d49dfba296b1016fc Mon Sep 17 00:00:00 2001 From: Sophie <49928680+sophiecarreras@users.noreply.github.com> Date: Fri, 27 Nov 2026 07:26:32 -0300 Subject: [PATCH 092/113] ci: pin b2-simulator v0.6.0 Move SIMULATOR_REVISION to 4052c6f8f45350486460d19bc796866cbdcdd3bc (tag v0.6.0). Co-Authored-By: Claude Opus 5.5 --- .github/workflows/simulator-integration.yml | 2 +- test/static/test_ci_draft_safety.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/simulator-integration.yml b/.github/workflows/simulator-integration.yml index 280c0917e..5ba35c667 100644 --- a/.github/workflows/simulator-integration.yml +++ b/.github/workflows/simulator-integration.yml @@ -13,7 +13,7 @@ env: PYTHON_DEFAULT_VERSION: "3.14" UV_VERSION: "0.13.4" # The single Simulator pin for this workflow; every checkout below refers to it. - SIMULATOR_REVISION: "a1e1db373b71f2d5f40082c19bc716cb6b3c3675" + SIMULATOR_REVISION: "4052c6f8f45350486460d19bc796866cbdcdd3bc" jobs: simulator-access-policy: diff --git a/test/static/test_ci_draft_safety.py b/test/static/test_ci_draft_safety.py index 71368dc4e..4b3a47feb 100644 --- a/test/static/test_ci_draft_safety.py +++ b/test/static/test_ci_draft_safety.py @@ -24,7 +24,7 @@ LIVE_TESTS_PATH = WORKFLOWS / 'live-b2-tests.yml' KEYS = ('B2_TEST_APPLICATION_KEY', 'B2_TEST_APPLICATION_KEY_ID') SIMULATOR_REPOSITORY = 'backblaze-labs/b2-simulator' -SIMULATOR_PIN = 'a1e1db373b71f2d5f40082c19bc716cb6b3c3675' +SIMULATOR_PIN = '4052c6f8f45350486460d19bc796866cbdcdd3bc' CLI_REPOSITORY = 'Backblaze/B2_Command_Line_Tool' KEY_SET_FLAG = "${{ secrets.SIMULATOR_DEPLOY_KEY != '' }}" SECRET_EXPRESSION = re.compile(r'secrets\.[A-Za-z_]') From baf6cb127f96960b52b30ef1ff5342822f1f11d4 Mon Sep 17 00:00:00 2001 From: Felipe Fumero Date: Fri, 27 Nov 2026 10:30:49 -0600 Subject: [PATCH 093/113] docs: correct quick start and tutorial examples (#778) Align the examples and copy guidance with the v3 API so readers can follow the documented operations. --- changelog.d/763.doc.md | 1 + doc/source/quick_start.rst | 17 ++++++++--------- doc/source/tutorial.rst | 2 +- 3 files changed, 10 insertions(+), 10 deletions(-) create mode 100644 changelog.d/763.doc.md diff --git a/changelog.d/763.doc.md b/changelog.d/763.doc.md new file mode 100644 index 000000000..5717cbd08 --- /dev/null +++ b/changelog.d/763.doc.md @@ -0,0 +1 @@ +Correct quick start and tutorial examples for the v3 API. diff --git a/doc/source/quick_start.rst b/doc/source/quick_start.rst index 215fde223..c45a6cff6 100644 --- a/doc/source/quick_start.rst +++ b/doc/source/quick_start.rst @@ -15,7 +15,7 @@ Prepare b2sdk >>> b2_api = B2Api(info, cache=AuthInfoCache(info)) >>> application_key_id = '4a5b6c7d8e9f' >>> application_key = '001b8e23c26ff6efb941e237deb182b9599a84bef7' - >>> b2_api.authorize_account("production", application_key_id, application_key) + >>> b2_api.authorize_account(application_key_id, application_key) .. tip:: Get credentials from B2 website @@ -252,7 +252,7 @@ By name >>> b2_file_name = 'dummy_new.pdf' >>> local_file_name = '/home/user1/b2_example/new3.pdf' >>> downloaded_file = bucket.download_file_by_name(b2_file_name) - >>> downloaded_file.save_to(local_file_path) + >>> downloaded_file.save_to(local_file_name) Downloading encrypted files @@ -283,18 +283,17 @@ List files f2.txt 1560927489000 None som2.pdf 1554296578000 None some.pdf 1554296579000 None - test-folder/.bzEmpty 1561005295000 test-folder/ + test-folder/.bzEmpty 1561005295000 None test-folder/folder_file.txt 1561005349000 None -Note: The files are returned recursively and in order so all files in a folder are printed one after another. -The folder_name is returned only for the first file in the folder. +In a recursive listing, ``folder_name`` is always ``None``. .. code-block:: python # Within folder >>> bucket_name = 'example-mybucket-b2' >>> bucket = b2_api.get_bucket_by_name(bucket_name) - >>> for file_version, folder_name in bucket.ls(folder_to_list='test-folder', latest_only=True): + >>> for file_version, folder_name in bucket.ls(path='test-folder', latest_only=True): >>> print(file_version.file_name, file_version.upload_timestamp, folder_name) test-folder/.bzEmpty 1561005295000 None test-folder/folder_file.txt 1561005349000 None @@ -368,7 +367,7 @@ Copy file "serverSideEncryption": {"algorithm": "AES256", "mode": "SSE-B2"}} -If the ``content length`` is not provided and the file is larger than 5GB, ``copy`` would not succeed and error would be raised. If length is provided, then the file may be copied as a large file. Maximum copy part size can be set by ``max_copy_part_size`` - if not set, it will default to 5GB. If ``max_copy_part_size`` is lower than :term:`absoluteMinimumPartSize`, file would be copied in single request - this may be used to force copy in single request large file that fits in server small file limit. +If you omit ``length``, the SDK first attempts a single-request copy. If the source is too large for that request, the SDK logs a warning and uses the large-file interface. If you provide ``length``, the SDK uses the transfer planner, which can copy the file in parts. Use ``min_part_size`` and ``max_part_size`` to set the planner’s part-size bounds in bytes. When copying files, you can provide encryption settings for both source and destination files. You cannot use `SSE-C` encrypted source files without the proper key. @@ -438,7 +437,7 @@ By listing .. code-block:: python - >>> for file_version, folder_name in bucket.ls(latest_only=True, prefix='dir_name'): + >>> for file_version, folder_name in bucket.ls(path='dir_name/', latest_only=True, recursive=True): >>> ... @@ -513,7 +512,7 @@ Usage examples .. code-block:: python - >>> for file_version, folder_name in bucket.ls(latest_only=True, prefix='dir_name'): + >>> for file_version, folder_name in bucket.ls(path='dir_name/', latest_only=True, recursive=True): >>> if file_version.mod_time_millis < 1627979193913 and file_version.file_name.endswith('.csv'): >>> if file_version.legal_hold.is_on(): >>> file_version = file_version.update_legal_hold(LegalHold.OFF) diff --git a/doc/source/tutorial.rst b/doc/source/tutorial.rst index 523d9ad9b..f885bdde6 100644 --- a/doc/source/tutorial.rst +++ b/doc/source/tutorial.rst @@ -33,7 +33,7 @@ Account authorization >>> b2_api = B2Api(info) >>> application_key_id = '4a5b6c7d8e9f' >>> application_key = '001b8e23c26ff6efb941e237deb182b9599a84bef7' - >>> b2_api.authorize_account("production", application_key_id, application_key) + >>> b2_api.authorize_account(application_key_id, application_key) .. tip:: Get credentials from B2 website From 6177e660f1d023e0d12e15aea9d7e469ce7d354f Mon Sep 17 00:00:00 2001 From: Felipe Fumero Date: Fri, 27 Nov 2026 10:31:12 -0600 Subject: [PATCH 094/113] docs: correct SDK API and streaming descriptions (#779) Align parameter and streaming guidance with the implementation so readers can use the documented interfaces correctly. --- b2sdk/_internal/api.py | 2 +- b2sdk/_internal/bucket.py | 3 ++- changelog.d/764.doc.md | 1 + doc/source/advanced.rst | 2 +- 4 files changed, 5 insertions(+), 3 deletions(-) create mode 100644 changelog.d/764.doc.md diff --git a/b2sdk/_internal/api.py b/b2sdk/_internal/api.py index 22f63c9d0..cbf74f5ee 100644 --- a/b2sdk/_internal/api.py +++ b/b2sdk/_internal/api.py @@ -526,7 +526,7 @@ def create_key( :param capabilities: a list of capabilities :param key_name: a name of a key :param valid_duration_seconds: key auto-expire time after it is created, in seconds, or ``None`` to not expire - :param bucket_id: a bucket ID to restrict the key to, or ``None`` to not restrict + :param bucket_ids: a list of bucket IDs to restrict the key to, or ``None`` for no bucket restriction :param name_prefix: a remote filename prefix to restrict the key to or ``None`` to not restrict """ account_id = self.account_info.get_account_id() diff --git a/b2sdk/_internal/bucket.py b/b2sdk/_internal/bucket.py index b8fedd2bd..76c56a97d 100644 --- a/b2sdk/_internal/bucket.py +++ b/b2sdk/_internal/bucket.py @@ -810,7 +810,8 @@ def upload_unbound_stream( value of ``recommended_upload_part_size`` is used. If that also is ``None``, it will be determined automatically as "recommended upload size". :param read_size: size of a single read operation performed on the ``read_only_object`` - :param unused_buffer_timeout_seconds: amount of time that a buffer can be idle before returning error + :param unused_buffer_timeout_seconds: maximum seconds to wait for a free buffer slot. + If no slot becomes free, raise ``UnboundStreamBufferTimeout``. :param int,None custom_upload_timestamp: override object creation date, expressed as a number of milliseconds since epoch :param str,None cache_control: an optional cache control setting. Syntax based on the section 14.9 of RFC 2616. Example string value: 'public, max-age=86400, s-maxage=3600, no-transform'. diff --git a/changelog.d/764.doc.md b/changelog.d/764.doc.md new file mode 100644 index 000000000..915e25a3d --- /dev/null +++ b/changelog.d/764.doc.md @@ -0,0 +1 @@ +Correct documentation for application keys, unbound uploads, and streamed concatenation. diff --git a/doc/source/advanced.rst b/doc/source/advanced.rst index c42bf7857..855e52d2d 100644 --- a/doc/source/advanced.rst +++ b/doc/source/advanced.rst @@ -87,7 +87,7 @@ For more information about ``concatenate`` please see :meth:`b2sdk.v3.Bucket.con Concatenate files of known size (streamed version) ================================================== -:meth:`b2sdk.v3.Bucket.concatenate` accepts an iterable of upload sources (either local or remote). The operation would not be planned ahead so it supports very large output objects, but continuation is only possible for local only sources and provided unfinished large file id. See more about continuation in :meth:`b2sdk.v3.Bucket.create_file` paragraph about continuation. +:meth:`b2sdk.v3.Bucket.concatenate_stream` accepts an iterable of upload sources (either local or remote). The operation would not be planned ahead so it supports very large output objects, but continuation is only possible for local only sources and provided unfinished large file id. See more about continuation in :meth:`b2sdk.v3.Bucket.create_file` paragraph about continuation. .. code-block:: python From 0fd7a1e070cd8575349d7e7fc5be6fb7a0fde649 Mon Sep 17 00:00:00 2001 From: Felipe Fumero Date: Fri, 27 Nov 2026 11:01:21 -0600 Subject: [PATCH 095/113] Fix create_file and concatenate examples in the advanced usage guide (#781) Several examples called parameters that do not exist (prioritize, large_file_callback, large_file_id, auto_continue) and passed file_info in the content_type position. Remove or replace them with what the code supports, and describe the planner's remote-over-local preference including the short-remote exception. --- changelog.d/780.doc.md | 1 + doc/source/advanced.rst | 83 +++++++++++++++-------------------------- 2 files changed, 31 insertions(+), 53 deletions(-) create mode 100644 changelog.d/780.doc.md diff --git a/changelog.d/780.doc.md b/changelog.d/780.doc.md new file mode 100644 index 000000000..70bb2a8de --- /dev/null +++ b/changelog.d/780.doc.md @@ -0,0 +1 @@ +Fix the `create_file`, `create_file_stream`, `concatenate` and `concatenate_stream` examples in the advanced usage guide: remove the `prioritize`, `large_file_callback` and `auto_continue` parameters that do not exist, use `continue_large_file_id`, and pass `file_info` by keyword. diff --git a/doc/source/advanced.rst b/doc/source/advanced.rst index 855e52d2d..2e06c7586 100644 --- a/doc/source/advanced.rst +++ b/doc/source/advanced.rst @@ -74,7 +74,7 @@ Concatenate files of known size ... CopySource('4_z5485a1682662eb3e60980d10_f1022e2320daf707f_d20190620_m122848_c002_v0001123_t0020', length=2123456789), ... ] >>> file_info = {'how': 'good-file'} - >>> bucket.concatenate(input_sources, remote_name, file_info) + >>> bucket.concatenate(input_sources, remote_name, file_info=file_info) If one of remote source has length smaller than :term:`absoluteMinimumPartSize` then it cannot be copied into large file part. Such remote source would be downloaded and concatenated locally with local source or with other downloaded remote source. @@ -98,7 +98,7 @@ Concatenate files of known size (streamed version) ... CopySource('4_z5485a1682662eb3e60980d10_f1022e2320daf707f_d20190620_m122848_c002_v0001123_t0020', length=2123456789), ... ] >>> file_info = {'how': 'good-file'} - >>> bucket.concatenate_stream(input_sources, remote_name, file_info) + >>> bucket.concatenate_stream(input_sources, remote_name, file_info=file_info) @@ -147,7 +147,7 @@ The assumption here is that the file has been appended to since it was last uplo ... ), ... ] >>> file_info = {'how': 'good-file'} - >>> bucket.create_file(input_sources, remote_name, file_info) + >>> bucket.create_file(input_sources, remote_name, file_info=file_info) :class:`b2sdk.v3.UploadSourceLocalFile` has the size determined automatically in this case. This is more efficient than :meth:`b2sdk.v3.Bucket.concatenate`, as it can use the overlapping ranges when a remote part is smaller than :term:`absoluteMinimumPartSize` to prevent downloading a range (when concatenating, local source would have destination offset at the end of remote source) @@ -176,7 +176,7 @@ Change the middle of the remote file ... ), ... ] >>> file_info = {'how': 'good-file'} - >>> bucket.create_file(input_sources, remote_name, file_info) + >>> bucket.create_file(input_sources, remote_name, file_info=file_info) :class:`b2sdk.v3.UploadSourceLocalFile` has the size determined automatically in this case. This is more efficient than :meth:`b2sdk.v3.Bucket.concatenate`, as it can use the overlapping ranges when a remote part is smaller than :term:`absoluteMinimumPartSize` to prevent downloading a range. @@ -235,7 +235,7 @@ Scenarios such as below are then possible: ... ) ... >>> file_info = {'how': 'good-file'} - >>> bucket.create_file(generate_input(), remote_name, file_info) + >>> bucket.create_file(generate_input(), remote_name, file_info=file_info) @@ -251,7 +251,7 @@ Even if files `A-C` and `D-G` are encrypted using `SSE-C` with different keys, t Prioritize remote or local sources ---------------------------------- -:meth:`b2sdk.v3.Bucket.create_file` and :meth:`b2sdk.v3.Bucket.create_file_stream` support source/origin prioritization, so that planner would know which sources should be used for overlapping ranges. Supported values are: `local`, `remote` and `local_verification`. +:meth:`b2sdk.v3.Bucket.create_file` and :meth:`b2sdk.v3.Bucket.create_file_stream` prioritize remote sources over local sources when possible. For overlapping ranges, the planner uses a remote source where one is available. It uses a local source where no remote source covers the range, or where the remote source is shorter than the minimum part size (:term:`absoluteMinimumPartSize` by default). The SDK cannot copy such a source as a part. .. code-block:: @@ -277,34 +277,10 @@ Prioritize remote or local sources .. code-block:: python - >>> bucket.create_file(input_sources, remote_name, file_info, prioritize='local') - # planner parts: cloud[A, B], local[B, C], remote[C, D], local[D, E] - -Here the planner has only used a remote source where remote range was not available, minimizing downloads. - -.. code-block:: python - - >>> bucket.create_file(input_sources, remote_name, file_info, prioritize='remote') + >>> bucket.create_file(input_sources, remote_name, file_info=file_info) # planner parts: cloud[A, D], local[D, E] -Here the planner has only used a local source where remote range was not available, minimizing uploads. - -.. code-block:: python - - >>> bucket.create_file(input_sources, remote_name, file_info) - # or - >>> bucket.create_file(input_sources, remote_name, file_info, prioritize='local_verification') - # planner parts: cloud[A, B], cloud[B, C], cloud[C, D], local[D, E] - -In `local_verification` mode the remote range was artificially split into three parts to allow for checksum verification against matching local ranges. - -.. note:: - `prioritize` is just a planner setting - remote parts are always verified if matching local parts exists. - -.. todo:: - Prioritization should accept an enum, not a string. Tracked in - `issue #602 `_. Kept here so that anyone - editing this section sees it alongside the documented string values. +Here the remote range A-D is long enough to copy, so the planner uses a local source only for D-E, minimizing uploads. .. _continuation: @@ -320,7 +296,7 @@ To continue a simple upload session, **b2sdk** checks available sessions for the To support automatic continuation, some advanced methods create a plan before starting copy/upload operations, saving the hash of that plan in ``file_info`` for increased reliability. -If that is not available, ``large_file_id`` can be extracted via callback during the operation start. It can then be passed into the subsequent call to continue the same task, though the responsibility for passing the exact same input is then on the user of the function. Please see :ref:`advanced method support table ` to see where automatic continuation is supported. ``large_file_id`` can also be passed if automatic continuation is available in order to avoid issues where multiple matching upload sessions are matching the transfer. +If that is not available, get the ``large_file_id`` of the unfinished large file with :meth:`b2sdk.v3.Bucket.list_unfinished_large_files`. Pass it as ``continue_large_file_id`` in the subsequent call to continue the same task. The user of the function is then responsible for passing the exact same input. Please see :ref:`advanced method support table ` to see where automatic continuation is supported. ``continue_large_file_id`` can also be passed if automatic continuation is available in order to avoid issues where multiple matching upload sessions are matching the transfer. Continuation of create/concatenate @@ -333,13 +309,14 @@ Manual continuation .. code-block:: python - >>> def large_file_callback(large_file): - ... # storage is not part of the interface - here only for demonstration purposes - ... storage.store({'name': remote_name, 'large_file_id': large_file.id}) - >>> bucket.create_file(input_sources, remote_name, file_info, large_file_callback=large_file_callback) - # ... - >>> large_file_id = storage.query({'name': remote_name})[0]['large_file_id'] - >>> bucket.create_file(input_sources, remote_name, file_info, large_file_id=large_file_id) + >>> bucket.create_file(input_sources, remote_name, file_info=file_info) + # the call is interrupted + >>> large_file_id = next( + ... f.file_id + ... for f in bucket.list_unfinished_large_files(prefix=remote_name) + ... if f.file_name == remote_name + ... ) + >>> bucket.create_file(input_sources, remote_name, file_info=file_info, continue_large_file_id=large_file_id) Manual continuation (streamed version) @@ -347,13 +324,14 @@ Manual continuation (streamed version) .. code-block:: python - >>> def large_file_callback(large_file): - ... # storage is not part of the interface - here only for demonstration purposes - ... storage.store({'name': remote_name, 'large_file_id': large_file.id}) - >>> bucket.create_file_stream(input_sources, remote_name, file_info, large_file_callback=large_file_callback) - # ... - >>> large_file_id = storage.query({'name': remote_name})[0]['large_file_id'] - >>> bucket.create_file_stream(input_sources, remote_name, file_info, large_file_id=large_file_id) + >>> bucket.create_file_stream(input_sources, remote_name, file_info=file_info) + # the call is interrupted + >>> large_file_id = next( + ... f.file_id + ... for f in bucket.list_unfinished_large_files(prefix=remote_name) + ... if f.file_name == remote_name + ... ) + >>> bucket.create_file_stream(input_sources, remote_name, file_info=file_info, continue_large_file_id=large_file_id) Streams that contain remote sources cannot be continued with :meth:`b2sdk.v3.Bucket.create_file` - internally :meth:`b2sdk.v3.Bucket.create_file` stores plan information in file info for such inputs, and verifies it before any copy/upload and :meth:`b2sdk.v3.Bucket.create_file_stream` cannot store this information. Local source only inputs can be safely continued with :meth:`b2sdk.v3.Bucket.create_file` in auto continue mode or manual continue mode (because plan information is not stored in file info in such case). @@ -362,22 +340,21 @@ Auto continuation .. code-block:: python - >>> bucket.create_file(input_sources, remote_name, file_info) + >>> bucket.create_file(input_sources, remote_name, file_info=file_info) For local source only input, :meth:`b2sdk.v3.Bucket.create_file` would try to find matching unfinished large file. It will verify uploaded parts checksums with local sources - the most completed, having all uploaded parts matched candidate would be automatically selected as file to continue. If there is no matching candidate (even if there are unfinished files for the same file name) new large file would be started. -In other cases plan information would be generated and :meth:`b2sdk.v3.Bucket.create_file` would try to find unfinished large file with matching plan info in its file info. If there is one or more such unfinished large files, :meth:`b2sdk.v3.Bucket.create_file` would verify checksums for all locally available parts and choose any matching candidate. If all candidates fail on uploaded parts checksums verification, process is interrupted and error raises. In such case corrupted unfinished large files should be cancelled manually and :meth:`b2sdk.v3.Bucket.create_file` should be retried, or auto continuation should be turned off with `auto_continue=False` +In other cases plan information would be generated and :meth:`b2sdk.v3.Bucket.create_file` would try to find unfinished large file with matching plan info in its file info. If there is one or more such unfinished large files, :meth:`b2sdk.v3.Bucket.create_file` would verify checksums for all locally available parts and choose any matching candidate. If all candidates fail on uploaded parts checksums verification, process is interrupted and error raises. In such case corrupted unfinished large files should be cancelled manually and :meth:`b2sdk.v3.Bucket.create_file` should be retried. No continuation --------------- -.. code-block:: python - - >>> bucket.create_file(input_sources, remote_name, file_info, auto_continue=False) +If :meth:`b2sdk.v3.Bucket.create_file_stream` does not receive ``continue_large_file_id``, it starts a new large file. +.. code-block:: python -Note, that this only forces start of a new large file - it is still possible to continue the process with either auto or manual modes. + >>> bucket.create_file_stream(input_sources, remote_name, file_info=file_info) **************************** From 5500aec2d91dc5764ffbee6f8b58c6c91c1aa8d7 Mon Sep 17 00:00:00 2001 From: Felipe Fumero Date: Fri, 27 Nov 2026 11:24:26 -0600 Subject: [PATCH 096/113] docs: add AGENTS.md and CLAUDE.md for coding agents (#784) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Take AGENTS.md and CLAUDE.md from the draft in #635 and leave the rest of that draft out. Remove references to files this change does not add, point the release link at README.release.md, link the testing and writing style guides, add the b2-mcp entry, and list the file in llms.txt. Commands, paths and the retry, apiver and test claims were checked against the current code. Co-authored-by: Gonzalo Peña-Castellanos --- AGENTS.md | 120 ++++++++++++++++++++++++++++++++++ CLAUDE.md | 1 + changelog.d/+agents-md.doc.md | 1 + llms.txt | 1 + 4 files changed, 123 insertions(+) create mode 100644 AGENTS.md create mode 100644 CLAUDE.md create mode 100644 changelog.d/+agents-md.doc.md diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 000000000..9408cd3c2 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,120 @@ +# b2sdk + +Python SDK for Backblaze B2 Cloud Storage (`b2sdk` on PyPI, `Backblaze/b2-sdk-python`). The B2 CLI is +its largest user. This file is the map for coding agents and new contributors; `CLAUDE.md` points here. +Keep it under about 150 lines and link out for detail. [`llms.txt`](llms.txt) lists the user documentation. + +## Commands + +Tooling is `nox` + `uv` (`pip install nox uv`). Sessions are defined in `noxfile.py`. + +- Local CI, run before every push and paste the tail in the PR: + `nox -s lint`, `nox -s towncrier_check`, `nox -s unit-3.14`, `nox -s build`, `nox --non-interactive -s doc`. +- Format: `nox -s format` (ruff). Lint: `nox -s lint` (ruff, `test/static`, liccheck). +- Unit tests run once per apiver: `nox -s unit-3.14` runs `pytest --api=v3`, then `v2`, `v1`, `v0`. + By keyword: `nox -s unit-3.14 -- -k keyword`. One apiver: `uv run --group test pytest --api=v2 test/unit`. +- Integration tests hit live B2 and need `B2_TEST_APPLICATION_KEY_ID` and `B2_TEST_APPLICATION_KEY`: + `nox -s integration-3.14`. Leftover test buckets: `nox -s cleanup_old_buckets`. +- Docs: `nox --non-interactive -s doc` (needs `graphviz` and `plantuml`) also runs `doc_cover`, which fails on + undocumented API. Without `--non-interactive` in a terminal it starts a live-reload server instead. +- Lock file: `uv lock --check`. Dependency changes go through `uv add`/`uv lock`, never by hand. +- Changelog fragment: `uv run --group release towncrier create -c 'Text.' +slug.fixed.md`. +- Release: [README.release.md](README.release.md) (`nox -s make_release_commit -- X.Y.Z`). + +External tools: + +- **[b2-mcp](https://github.com/backblaze-labs/b2-mcp)** — a Model Context Protocol server for B2. + +## Architecture + +| Path | Role | +| --- | --- | +| `b2sdk/_internal/` | All implementation. Private: users never import it. | +| `b2sdk/v3/`, `v2/`, `v1/`, `v0/` | Public apiver layers. `v3` re-exports `_internal`; older layers wrap or subclass to keep their old signatures and behavior. | +| `_internal/api.py`, `bucket.py` | High-level `B2Api` and `Bucket`, the surface most callers use. | +| `_internal/session.py`, `b2http.py` | Auth, reauth, retries, `Retry-After`, exception translation. | +| `_internal/raw_api.py` | One method per B2 Native API call (`AbstractRawApi`, `B2RawHTTPApi`). | +| `_internal/raw_simulator.py` | In-memory B2 used by unit tests and by users; must match `raw_api.py`. | +| `_internal/transfer/`, `large_file/` | Upload, download, copy, emerger and large-file managers (thread pools). | +| `_internal/sync/`, `scan/` | Folder scan and sync (used by `b2 sync`). | +| `_internal/account_info/` | Credential and cache stores, including `SqliteAccountInfo`. | +| `test/unit/` | Unit tests; `test/unit/vN/apiver` and `v_all` hold apiver-specific tests, selected by `--api`. | +| `test/integration/` | Live-B2 tests, using `_internal/testing/helpers/bucket_manager.py`. | +| `.sdkharness/` | Contract checks the central SDK harness runs against the B2 simulator on loopback. | +| `doc/source/` | Sphinx user documentation. `docs/` holds the testing and writing style guides. | +| `changelog.d/` | towncrier fragments; `CHANGELOG.md` is built from them at release. | + +## Conventions + +- Python 3.10+ (`requires-python`); CI runs 3.10-3.14 and PyPy 3.10 on Linux, macOS and Windows. +- ruff, 100-column lines, single quotes. Every file keeps the Backblaze license header (`test/static` checks it). +- Semver on each apiver. A breaking change goes into a new apiver (or the newest, unreleased one), never + into an older layer. Deprecate with a warning before removing. +- New B2 calls follow the B2 docs and the + [Integration Checklist](https://www.backblaze.com/docs/cloud-storage-integration-checklist). +- Comments are short and explain non-obvious decisions. Public API gets docstrings that Sphinx renders. +- Write and edit docs and docstrings as described in [docs/writing-style.md](docs/writing-style.md). +- Detail: test levels and how to run them in [docs/testing.md](docs/testing.md), contributor setup in + [CONTRIBUTING.md](CONTRIBUTING.md), the harness in [.sdkharness/README.md](.sdkharness/README.md). + +## Things agents get wrong here + +Each line comes from recurring review feedback on this repository. + +1. **Missing or wrong changelog fragment.** Every PR adds `changelog.d/..md` or + `+slug..md` (types in `pyproject.toml`). Write it for SDK users, about the fix, not the test. +2. **Tests that do not pin the fix.** Revert the change and the new test must fail. Exercise the mechanism + (the real sleep in `_translate_and_retry`, a new upload URL fetched after a 408), not an attribute. + Server-format fixes get a simulator unit test and an integration test. +3. **Reordered or inserted positional parameters.** New optional parameters go last (or keyword-only); + never reorder. Callers pass many positionals (`Bucket.upload_bytes`), and a shift is silent. +4. **apiver layering.** Change only the unreleased layer; a released `b2sdk/vN` keeps its behavior through + a wrapper in `b2sdk/vN/` that forwards `*args, **kwargs`. Export new public names from `b2sdk/v3` + (`__init__.py`, `exception.py`, `testing/__init__.py`). Compat shims kept for the CLI get existence and + signature tests. Run the unit tests on every `--api`. +5. **Raw API drift.** `AbstractRawApi`, `B2RawHTTPApi` and `RawSimulator` change together with matching + signatures and argument names. Check live B2 before changing simulator behavior; keep it deterministic + and bounded in memory. No `requests` types in the raw API interface. +6. **Retries in the wrong place.** Uploads go out with `try_count=1` so `UploadManager` retries with a + fresh upload URL and token; never retry them in `b2http.py`. Treat every retryable 5xx alike and parse + `Retry-After` through `_parse_retry_after_seconds`. +7. **Accidental public interface.** Do not call another class's `_private` members. Tunables are named + constants: module-level, or a class attribute (`DEFAULT_*_CLASS`, `B2Http.TIMEOUT`) when a subclass or + apiver layer may override it. Logic lives in `B2Api` and `Bucket` delegates; use `_by_id`/`_by_name`. +8. **Hidden failures.** No bare `Exception` (subclass in `exception.py`), no catch-all `except`, no + `pytest.fail` that drops the real error, no unawaited async test. A skipped check is NOT RUN, not PASS. +9. **Undocumented public API.** Every new public class gets a docstring and every new parameter a `:param`, + with units and whether ranges are inclusive. `doc_cover` fails on the first, reviewers on the second. +10. **Sync and scan safety.** Reject `..` traversal, decide absolute paths per platform, allow names legal on + the OS, and never silently drop user files. Windows: do not reopen a `NamedTemporaryFile` by name. +11. **Large files and transfers.** A new upload option flows through emerger, executor and the + unfinished-file matcher, and a mismatch must not resume. Cover zero length, the 10,000-part limit and + >5 GB. Thread pools: lazy init and `get` share a lock; one `max_workers` default in one place. +12. **Test and integration hygiene.** `parametrize`, not loops of asserts; no nested functions (use + `_method`); `@pytest.mark.apiver` only where behavior differs. Integration tests use + `bucket_manager.py` and never touch real account info or leave buckets behind. +13. **sdkharness safety.** Checks target only `http://127.0.0.1:` with `test-key-id`/`test-key`; + never read or print ambient `B2_*` credentials. +14. **PR scope.** Search open PRs first; one change per PR, against `master`; no unrelated reformatting; + file an issue for out-of-scope bugs. The live-B2 stage has known failures (#614): reproduce on `master` + before calling a failure unrelated. + +## Workflow + +- Bug fixes: commit the failing regression test first, then the fix, without editing the test. +- Before opening a PR, review your own diff in a fresh context (a second agent, or a person who did not + write it) and fix or answer what it finds. Say in the PR what it reported. +- Every review finding gets fixed or answered with a reason. Agents never approve or merge their own PRs; + a maintainer approves. +- The person directing an agent owns its PR: they count as one of its reviewers and fix what it breaks. + Keep PRs small so they are easy to review and revert. +- When reviewers flag the same thing twice, fix it at the source in the same PR: this file, a lint rule + or a test. +- Stacked PRs: state the base PR and merge order in the description; retarget to `master` after it merges. +- Security reports go through [SECURITY.md](SECURITY.md), never a public issue. + +## Verifying your work + +Run the local CI commands above and paste the tail of their output. If a test fails, fix the code, not +the test. Say which apivers and Python versions you ran, and list any integration or `.sdkharness` checks +you ran and any you could not. diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 000000000..43c994c2d --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1 @@ +@AGENTS.md diff --git a/changelog.d/+agents-md.doc.md b/changelog.d/+agents-md.doc.md new file mode 100644 index 000000000..fc93a8cab --- /dev/null +++ b/changelog.d/+agents-md.doc.md @@ -0,0 +1 @@ +Add `AGENTS.md` and `CLAUDE.md` with commands, architecture, conventions and recurring review findings for coding agents and new contributors. diff --git a/llms.txt b/llms.txt index d8267c708..c1fb917fe 100644 --- a/llms.txt +++ b/llms.txt @@ -27,6 +27,7 @@ ## Contributing and testing - [Contributing](https://github.com/Backblaze/b2-sdk-python/blob/master/CONTRIBUTING.md): Find contribution and testing guidance. +- [Contributor instructions](https://github.com/Backblaze/b2-sdk-python/blob/master/AGENTS.md): Find commands, conventions and recurring review findings. ## Optional From bb3ee6cf6d132b0fd2637bae26fce7e88dde9b99 Mon Sep 17 00:00:00 2001 From: Felipe Fumero Date: Fri, 27 Nov 2026 11:24:43 -0600 Subject: [PATCH 097/113] Apply the writing style to more of the advanced usage guide (#786) Shorten flagged long sentences, replace passive wording that hid the actor, and use "see the table" phrasing in place of "please see ... to see". Sentences about planner source selection and continuation of streamed concatenation are left unchanged until they are verified. Wording only; code blocks and doctest lines are untouched. --- changelog.d/+style-advanced-continued.doc.md | 1 + doc/source/advanced.rst | 32 ++++++++++---------- 2 files changed, 17 insertions(+), 16 deletions(-) create mode 100644 changelog.d/+style-advanced-continued.doc.md diff --git a/changelog.d/+style-advanced-continued.doc.md b/changelog.d/+style-advanced-continued.doc.md new file mode 100644 index 000000000..9f81b9894 --- /dev/null +++ b/changelog.d/+style-advanced-continued.doc.md @@ -0,0 +1 @@ +Rewrite flagged long and passive sentences in the advanced usage guide to follow the writing style. diff --git a/doc/source/advanced.rst b/doc/source/advanced.rst index 2e06c7586..4e5f74fde 100644 --- a/doc/source/advanced.rst +++ b/doc/source/advanced.rst @@ -4,7 +4,7 @@ Advanced usage patterns ######################################### -B2 server API allows for creation of an object from existing objects. This allows to avoid transferring data from the source machine if the desired outcome can be (at least partially) constructed from what is already on the server. +The B2 server API can create an object from existing objects. This can avoid transferring data from the source machine if the desired outcome can be (at least partially) constructed from what is already on the server. **b2sdk** provides functions that let you specify the desired outcome. The library plans and executes the work. Use the table below to compare object creation methods for different usage patterns. @@ -43,9 +43,9 @@ Some methods support overlapping ranges between local and remote files. **b2sdk* Streaming interface =================== -Some object creation methods start writing data before reading the whole input (iterator). You can use these methods to write objects without fully known contents without first writing them locally for copying. Such usage pattern can be relevant to small devices which stream data to B2 from an external NAS, where caching large files such as media files or virtual machine images is not an option. +Some object creation methods start writing data before reading the whole input (iterator). You can use these methods to write objects without fully known contents without first writing them locally for copying. This pattern can be relevant to small devices that stream data to B2 from an external NAS. On such devices, caching large files such as media files or virtual machine images is not an option. -Please see :ref:`advanced method support table ` to see where streaming interface is supported. +See the :ref:`advanced method support table ` for the methods that support the streaming interface. Continuation ============ @@ -57,9 +57,9 @@ Please see :ref:`here ` Concatenate files ***************** -:meth:`b2sdk.v3.Bucket.concatenate` accepts an iterable of upload sources (either local or remote). It can be used to glue remote files together, back-to-back, into a new file. +:meth:`b2sdk.v3.Bucket.concatenate` accepts an iterable of upload sources (either local or remote). You can use it to glue remote files together, back-to-back, into a new file. -:meth:`b2sdk.v3.Bucket.concatenate_stream` does not create and validate a plan before starting the transfer, so it can be used to process a large input iterator, at a cost of limited automated continuation. +:meth:`b2sdk.v3.Bucket.concatenate_stream` does not create and validate a plan before starting the transfer. You can use it to process a large input iterator, at a cost of limited automated continuation. Concatenate files of known size @@ -79,7 +79,7 @@ Concatenate files of known size If one of remote source has length smaller than :term:`absoluteMinimumPartSize` then it cannot be copied into large file part. Such remote source would be downloaded and concatenated locally with local source or with other downloaded remote source. -Please note that this method only allows checksum verification for local upload sources. Checksum verification for remote sources is available only when local copy is available. In such case :meth:`b2sdk.v3.Bucket.create_file` can be used with overlapping ranges in input. +This method allows checksum verification only for local upload sources. Checksum verification for remote sources is available only when a local copy is available. In that case, you can use :meth:`b2sdk.v3.Bucket.create_file` with overlapping ranges in the input. For more information about ``concatenate`` please see :meth:`b2sdk.v3.Bucket.concatenate` and :class:`b2sdk.v3.CopySource`. @@ -106,14 +106,14 @@ Concatenate files of known size (streamed version) Concatenate files of unknown size ================================= -While it is supported by B2 server, this pattern is currently not supported by **b2sdk**. +The B2 server supports this pattern, but **b2sdk** does not currently support it. ********************* Synthethize an object ********************* -Using methods described below an object can be created from both local and remote sources while avoiding downloading small ranges when such range is already present on a local drive. +The methods described below can create an object from both local and remote sources. They avoid downloading a small range when that range is already present on a local drive. Update a file efficiently ==================================== @@ -121,13 +121,13 @@ Update a file efficiently :meth:`b2sdk.v3.Bucket.create_file` accepts an iterable which *can contain overlapping destination ranges*. .. note:: - Following examples *create* new file - data in bucket is immutable, but **b2sdk** can create a new file version with the same name and updated content + The following examples *create* a new file. Data in a bucket is immutable, but **b2sdk** can create a new file version with the same name and updated content. Append to the end of a file --------------------------- -The assumption here is that the file has been appended to since it was last uploaded to. This assumption is verified by **b2sdk** when possible by recalculating checksums of the overlapping remote and local ranges. If copied remote part sha does not match with locally available source, file creation process would be interrupted and an exception would be raised. +The assumption here is that the file has been appended to since it was last uploaded to. **b2sdk** verifies this assumption when possible, by recalculating checksums of the overlapping remote and local ranges. If the sha of a copied remote part does not match the locally available source, **b2sdk** interrupts the file creation and raises an exception. .. code-block:: python @@ -193,7 +193,7 @@ This is useful for expert usage patterns such as: - mostly-server-side cutting and gluing uncompressed media files such as `wav` and `avi` with rewriting of file headers - various deduplicated backup scenarios -Please note that :meth:`b2sdk.v3.Bucket.create_file_stream` accepts **an ordered iterable** which *can contain overlapping ranges*, so the operation does not need to be planned ahead, but can be streamed, which supports very large output objects. +:meth:`b2sdk.v3.Bucket.create_file_stream` accepts **an ordered iterable** which *can contain overlapping ranges*. Because of this, the operation does not need to be planned ahead, but can be streamed, which supports very large output objects. Scenarios such as below are then possible: @@ -246,7 +246,7 @@ For more information see :meth:`b2sdk.v3.Bucket.create_file`. Encryption ---------- -Even if files `A-C` and `D-G` are encrypted using `SSE-C` with different keys, they can still be used in a single :meth:`b2sdk.v3.Bucket.create_file` call, because :class:`b2sdk.v3.CopySource` accepts an optional :class:`b2sdk.v3.EncryptionSetting`. +Files `A-C` and `D-G` can be used in a single :meth:`b2sdk.v3.Bucket.create_file` call even if they are encrypted using `SSE-C` with different keys. This works because :class:`b2sdk.v3.CopySource` accepts an optional :class:`b2sdk.v3.EncryptionSetting`. Prioritize remote or local sources ---------------------------------- @@ -296,7 +296,7 @@ To continue a simple upload session, **b2sdk** checks available sessions for the To support automatic continuation, some advanced methods create a plan before starting copy/upload operations, saving the hash of that plan in ``file_info`` for increased reliability. -If that is not available, get the ``large_file_id`` of the unfinished large file with :meth:`b2sdk.v3.Bucket.list_unfinished_large_files`. Pass it as ``continue_large_file_id`` in the subsequent call to continue the same task. The user of the function is then responsible for passing the exact same input. Please see :ref:`advanced method support table ` to see where automatic continuation is supported. ``continue_large_file_id`` can also be passed if automatic continuation is available in order to avoid issues where multiple matching upload sessions are matching the transfer. +If that is not available, get the ``large_file_id`` of the unfinished large file with :meth:`b2sdk.v3.Bucket.list_unfinished_large_files`. Pass it as ``continue_large_file_id`` in the subsequent call to continue the same task. The user of the function is then responsible for passing the exact same input. See the :ref:`advanced method support table ` for the methods that support automatic continuation. You can also pass ``continue_large_file_id`` when automatic continuation is available, to avoid issues where multiple upload sessions match the transfer. Continuation of create/concatenate @@ -342,7 +342,7 @@ Auto continuation >>> bucket.create_file(input_sources, remote_name, file_info=file_info) -For local source only input, :meth:`b2sdk.v3.Bucket.create_file` would try to find matching unfinished large file. It will verify uploaded parts checksums with local sources - the most completed, having all uploaded parts matched candidate would be automatically selected as file to continue. If there is no matching candidate (even if there are unfinished files for the same file name) new large file would be started. +For local source only input, :meth:`b2sdk.v3.Bucket.create_file` tries to find a matching unfinished large file. It verifies the checksums of the uploaded parts against the local sources. It automatically selects the most complete candidate, in which all uploaded parts match, as the file to continue. If there is no matching candidate (even if there are unfinished files for the same file name), it starts a new large file. In other cases plan information would be generated and :meth:`b2sdk.v3.Bucket.create_file` would try to find unfinished large file with matching plan info in its file info. If there is one or more such unfinished large files, :meth:`b2sdk.v3.Bucket.create_file` would verify checksums for all locally available parts and choose any matching candidate. If all candidates fail on uploaded parts checksums verification, process is interrupted and error raises. In such case corrupted unfinished large files should be cancelled manually and :meth:`b2sdk.v3.Bucket.create_file` should be retried. @@ -361,8 +361,8 @@ If :meth:`b2sdk.v3.Bucket.create_file_stream` does not receive ``continue_large_ SHA-1 hashes for large files **************************** -Depending on the number and size of sources and the size of the result file, the SDK may decide to use the large file API to create a file on the server. In such cases the file's SHA-1 won't be stored on the server in the ``X-Bz-Content-Sha1`` header, but it may optionally be stored with the file in the ``large_file_sha1`` entry in the ``file_info``, as per [B2 integration checklist](https://www.backblaze.com/b2/docs/integration_checklist.html). +Depending on the number and size of sources and the size of the result file, the SDK may decide to use the large file API to create a file on the server. In such cases the file's SHA-1 won't be stored on the server in the ``X-Bz-Content-Sha1`` header. However, it may optionally be stored with the file in the ``large_file_sha1`` entry in the ``file_info``, as per [B2 integration checklist](https://www.backblaze.com/b2/docs/integration_checklist.html). -In basic scenarios, large files uploaded to the server will have a ``large_file_sha1`` element added automatically to their ``file_info``. However, when concatenating multiple sources, it may be impossible for the SDK to figure out the SHA-1 automatically. In such cases, the SHA-1 can be provided using the ``large_file_sha1`` parameter to :meth:`b2sdk.v3.Bucket.create_file`, :meth:`b2sdk.v3.Bucket.concatenate` and their stream equivalents. If the parameter is skipped or ``None``, the result file may not have the ``large_file_sha1`` value set. +In basic scenarios, large files uploaded to the server will have a ``large_file_sha1`` element added automatically to their ``file_info``. However, when concatenating multiple sources, it may be impossible for the SDK to figure out the SHA-1 automatically. In such cases, you can provide the SHA-1 using the ``large_file_sha1`` parameter to :meth:`b2sdk.v3.Bucket.create_file`, :meth:`b2sdk.v3.Bucket.concatenate` and their stream equivalents. If you skip the parameter or pass ``None``, the result file may not have the ``large_file_sha1`` value set. Note that the provided SHA-1 value is not verified. From 5886c7e1914e992b190537d9b3c753d50007114e Mon Sep 17 00:00:00 2001 From: Felipe Fumero Date: Fri, 27 Nov 2026 11:25:03 -0600 Subject: [PATCH 098/113] Correct the HTTP retry statements about uploads in the errors guide (#787) The raw API sends upload data with try_count=1, so the HTTP layer never retries an upload data request. Only the upload manager retries a failed upload. The HTTP layer can retry the request that fetches an upload URL. The guide said uploads get 20 HTTP attempts. --- changelog.d/785.doc.md | 1 + doc/source/errors_and_retries.rst | 11 ++++++++--- 2 files changed, 9 insertions(+), 3 deletions(-) create mode 100644 changelog.d/785.doc.md diff --git a/changelog.d/785.doc.md b/changelog.d/785.doc.md new file mode 100644 index 000000000..0a030e76d --- /dev/null +++ b/changelog.d/785.doc.md @@ -0,0 +1 @@ +Correct the errors and retries guide: upload data requests are sent once by the HTTP layer, and only the upload manager retries a failed upload. diff --git a/doc/source/errors_and_retries.rst b/doc/source/errors_and_retries.rst index 55a7dcbb1..e605fb4b6 100644 --- a/doc/source/errors_and_retries.rst +++ b/doc/source/errors_and_retries.rst @@ -105,9 +105,12 @@ The HTTP helpers use these defaults: * - Request helper - Constant - Attempts - * - Data requests, including upload data + * - Data requests, except upload data - ``TRY_COUNT_DATA`` - 20 + * - Upload data (``b2_upload_file`` and ``b2_upload_part``) + - set to 1 by the raw API + - 1 * - Download requests - ``TRY_COUNT_DOWNLOAD`` - 20 @@ -120,7 +123,8 @@ The HTTP helpers use these defaults: These are HTTP helper defaults, not a limit for a complete SDK operation. An operation can make several requests. -Upload-manager attempts can also contain HTTP retries. +The raw API sends upload data with ``try_count=1``, so the HTTP loop does not retry an upload data request. +The HTTP loop can retry the request that fetches an upload URL. Before another attempt, the HTTP loop checks ``should_retry_http()``. If the result is ``False``, the loop raises the error immediately. @@ -192,7 +196,8 @@ A part retry can take another pooled URL or request a new URL if none is availab An upload retry does not always make a new upload-URL request to the server. The upload-manager loop adds no delay of its own. -The HTTP layer can wait and retry within an upload attempt. +The HTTP layer does not retry the upload data request, so only this loop retries a failed upload. +The HTTP layer can wait and retry the request that fetches an upload URL. If all 5 upload attempts fail with errors that permit upload retries, the manager raises ``MaxRetriesExceeded``. Its ``limit`` attribute holds the attempt limit. From 1b591935e7bec523833e5bf47b57916e497437dc Mon Sep 17 00:00:00 2001 From: Felipe Fumero Date: Fri, 27 Nov 2026 11:42:16 -0600 Subject: [PATCH 099/113] docs: link the guides from llms.txt and the README (#788) --- README.md | 3 +++ changelog.d/782.doc.md | 1 + llms.txt | 4 ++++ 3 files changed, 8 insertions(+) create mode 100644 changelog.d/782.doc.md diff --git a/README.md b/README.md index fa47a8c91..f53c2055e 100644 --- a/README.md +++ b/README.md @@ -45,3 +45,6 @@ Please refer to the [changelog](CHANGELOG.md). # Developer Info Please see our [contributing guidelines](CONTRIBUTING.md). +The [testing guide](docs/testing.md) and the +[writing style guide](docs/writing-style.md) describe how to test changes and write documentation. +[llms.txt](llms.txt) lists the user documentation. diff --git a/changelog.d/782.doc.md b/changelog.d/782.doc.md new file mode 100644 index 000000000..8c4772760 --- /dev/null +++ b/changelog.d/782.doc.md @@ -0,0 +1 @@ +Link the testing guide, the writing style guide, the API compatibility page and the glossary from `llms.txt`, and link the testing guide, the writing style guide and `llms.txt` from the README. diff --git a/llms.txt b/llms.txt index c1fb917fe..6447b7857 100644 --- a/llms.txt +++ b/llms.txt @@ -16,6 +16,8 @@ - [Replication](https://github.com/Backblaze/b2-sdk-python/blob/master/doc/source/replication.rst): Configure replication. - [Server-side encryption](https://b2-sdk-python.readthedocs.io/en/master/server_side_encryption.html): Use server-side encryption. - [Account info and authorization](https://b2-sdk-python.readthedocs.io/en/master/account_info.html): Choose a store and authorize an account. +- [API compatibility](https://b2-sdk-python.readthedocs.io/en/master/api_types.html): Check what can change inside one interface version. +- [Glossary](https://b2-sdk-python.readthedocs.io/en/master/glossary.html): Look up B2 and SDK terms. ## API reference @@ -26,6 +28,8 @@ ## Contributing and testing +- [Testing guide](https://github.com/Backblaze/b2-sdk-python/blob/master/docs/testing.md): Choose a test level and check what it proves. +- [Writing style](https://github.com/Backblaze/b2-sdk-python/blob/master/docs/writing-style.md): Write or edit documentation and docstrings. - [Contributing](https://github.com/Backblaze/b2-sdk-python/blob/master/CONTRIBUTING.md): Find contribution and testing guidance. - [Contributor instructions](https://github.com/Backblaze/b2-sdk-python/blob/master/AGENTS.md): Find commands, conventions and recurring review findings. From c6e15c04860ce07fc3d35bce77c95ccff32812a2 Mon Sep 17 00:00:00 2001 From: Felipe Fumero Date: Fri, 27 Nov 2026 11:42:33 -0600 Subject: [PATCH 100/113] Add a verify skill for the local nox gate (#789) An agent can report work as done without running the local gate, and a failing stage has no list that says what it means. The skill names each stage in the order AGENTS.md lists, says what a failure in it means, and requires stages that were not run to be reported as NOT RUN. AGENTS.md now points to the skill. --- .claude/skills/verify/SKILL.md | 30 +++++++++++++++++++++ AGENTS.md | 1 + changelog.d/+verify-skill.infrastructure.md | 1 + 3 files changed, 32 insertions(+) create mode 100644 .claude/skills/verify/SKILL.md create mode 100644 changelog.d/+verify-skill.infrastructure.md diff --git a/.claude/skills/verify/SKILL.md b/.claude/skills/verify/SKILL.md new file mode 100644 index 000000000..d0aa6fc85 --- /dev/null +++ b/.claude/skills/verify/SKILL.md @@ -0,0 +1,30 @@ +--- +name: verify +description: Run the local verification gate before you push, open a PR, or say work is done. +--- + +# Verify your work + +Run these stages from the repository root, in this order. Read the first failing stage and its output. +Fix the cause and rerun the stage. Paste the tail of each stage into the PR. +If a test fails, fix the code, not the test. + +## Stages + +1. `nox -s lint`: ruff reported an issue, a `test/static` test failed (for example the license header or the + `llms.txt` link test), or liccheck rejected a dependency license. +2. `nox -s towncrier_check`: a `changelog.d/` fragment has a wrong name or an unknown type. +3. `nox -s unit-3.14`: runs every apiver. One failing apiver means a layer broke. To run one apiver: + `uv run --group test pytest --api=v2 test/unit`. +4. `nox -s build`: the distribution did not build. +5. `nox --non-interactive -s doc`: Sphinx runs with `-W`, so a warning is a failure. It also runs `doc_cover`, + which fails on undocumented public API. +6. `uv lock --check`: `uv.lock` does not match `pyproject.toml`. + +Without `--non-interactive`, `nox -s doc` starts a live-reload server in a terminal. Always pass the flag. + +## Separate checks + +Integration tests (`nox -s integration-3.14`) and the `.sdkharness` checks are not part of this gate. +They need live B2 credentials or a simulator. See [docs/testing.md](../../../docs/testing.md). +Report any stage you did not run as NOT RUN, never as passed. diff --git a/AGENTS.md b/AGENTS.md index 9408cd3c2..5b3286794 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -118,3 +118,4 @@ Each line comes from recurring review feedback on this repository. Run the local CI commands above and paste the tail of their output. If a test fails, fix the code, not the test. Say which apivers and Python versions you ran, and list any integration or `.sdkharness` checks you ran and any you could not. +The `verify` skill in [.claude/skills/verify/SKILL.md](.claude/skills/verify/SKILL.md) wraps these commands. diff --git a/changelog.d/+verify-skill.infrastructure.md b/changelog.d/+verify-skill.infrastructure.md new file mode 100644 index 000000000..48a800345 --- /dev/null +++ b/changelog.d/+verify-skill.infrastructure.md @@ -0,0 +1 @@ +Add a `verify` skill that runs the local nox gate and explains what each stage failure means. From 25dc75b94062e0abbd5025103fc01d54320e8c1b Mon Sep 17 00:00:00 2001 From: Felipe Fumero Date: Fri, 27 Nov 2026 11:42:50 -0600 Subject: [PATCH 101/113] Add a migration guide from b2sdk.v2 to b2sdk.v3 (#790) Code and examples written for b2sdk.v2 fail on b2sdk.v3 in ways that do not look like a version problem: the authorize_account argument order, Bucket.ls(folder_to_list=...), create_key(bucket_id=...) and arguments that moved in the upload methods. The new page lists each difference found by comparing the signatures of both layers, with the behavior read from the wrapper code in b2sdk/v2/. It shows a v2 and a v3 example for each difference and a script to repeat the comparison. --- changelog.d/783.doc.md | 1 + doc/source/index.rst | 1 + doc/source/migrating.rst | 311 +++++++++++++++++++++++++++++++++++++++ llms.txt | 1 + 4 files changed, 314 insertions(+) create mode 100644 changelog.d/783.doc.md create mode 100644 doc/source/migrating.rst diff --git a/changelog.d/783.doc.md b/changelog.d/783.doc.md new file mode 100644 index 000000000..9d957a04e --- /dev/null +++ b/changelog.d/783.doc.md @@ -0,0 +1 @@ +Add a guide for migrating from `b2sdk.v2` to `b2sdk.v3`. diff --git a/doc/source/index.rst b/doc/source/index.rst index 930511dc2..38ac6c181 100644 --- a/doc/source/index.rst +++ b/doc/source/index.rst @@ -46,6 +46,7 @@ Documentation index account_info glossary api_types + migrating api_reference contributing diff --git a/doc/source/migrating.rst b/doc/source/migrating.rst new file mode 100644 index 000000000..f91806c8e --- /dev/null +++ b/doc/source/migrating.rst @@ -0,0 +1,311 @@ +Migrating from v2 to v3 +####################### + +This guide lists the differences between ``b2sdk.v2`` and ``b2sdk.v3``. +It covers the signatures of public methods and the behavior of the ``b2sdk.v2`` wrapper code. +The sections below list the differences found by comparing both layers. +See `How to check the differences yourself`_ to repeat the comparison. + +Choose a version +================ + +Import names from one interface version. +To migrate, change the import and then apply the changes in this guide. + +.. code-block:: python + + # before + from b2sdk.v2 import B2Api + + # after + from b2sdk.v3 import B2Api + +The ``b2sdk.v2`` layer wraps ``b2sdk.v3`` and keeps the old signatures. +See :ref:`interface_versions` and :doc:`api_types` for the compatibility policy. + +The examples in this guide run against the in-memory simulator. +The setup is the same for both layers. +Replace ``v3`` with ``v2`` in the import to run the ``b2sdk.v2`` form. + +.. code-block:: python + + >>> from b2sdk.v3 import B2Api, B2HttpApiConfig, InMemoryAccountInfo, RawSimulator + >>> api = B2Api(account_info=InMemoryAccountInfo(), api_config=B2HttpApiConfig(_raw_api_class=RawSimulator)) + >>> key_id, key = api.session.raw_api.create_account() + +Authorize an account +==================== + +``B2Api.authorize_account`` changed the order of its arguments. + +* ``b2sdk.v2`` takes ``(realm, application_key_id, application_key)``. +* ``b2sdk.v3`` takes ``(application_key_id, application_key, realm='production')``. + +The ``b2sdk.v2`` method calls the ``b2sdk.v3`` method with keyword arguments. +The ``b2sdk.v3`` method does not reject the old order. +It treats ``'production'`` as the application key ID, and the authorization fails. + +.. code-block:: python + + >>> # b2sdk.v2 + >>> api.authorize_account('production', key_id, key) + + >>> # b2sdk.v3 + >>> api.authorize_account(key_id, key) + >>> api.authorize_account(key_id, key, 'production') + + >>> # the v2 order on b2sdk.v3 + >>> api.authorize_account('production', key_id, key) + Traceback (most recent call last): + ... + b2sdk._internal.exception.InvalidAuthToken: Invalid authorization token. Server said: application key ID not valid (unauthorized) + +To migrate, remove the ``realm`` argument from the front of the call. +Pass ``realm`` last, or omit it to use ``'production'``. +Use keyword arguments to avoid the problem. + +Restrict an application key to buckets +====================================== + +The ``bucket_id`` argument became ``bucket_ids``. +It takes a list of bucket IDs instead of one bucket ID. +The change applies to these methods and classes: + +* ``B2Api.create_key`` +* ``ApplicationKey`` and ``FullApplicationKey``, including the ``B2Api.APPLICATION_KEY_CLASS`` and ``B2Api.FULL_APPLICATION_KEY_CLASS`` attributes +* ``B2Session.create_key`` +* ``create_key`` in ``AbstractRawApi``, ``B2RawHTTPApi``, and ``RawSimulator`` + +The application key objects follow the same rename. +An ``ApplicationKey`` or ``FullApplicationKey`` object has a ``bucket_id`` attribute on ``b2sdk.v2``. +The same object has a ``bucket_ids`` attribute on ``b2sdk.v3``. +The ``b2sdk.v3`` object has no ``bucket_id`` attribute. + +.. code-block:: python + + >>> bucket = api.create_bucket('my-bucket', 'allPrivate') + + >>> # b2sdk.v2 + >>> application_key = api.create_key(['listFiles'], 'my-key', bucket_id=bucket.id_) + >>> application_key.bucket_id + 'bucket_0' + + >>> # b2sdk.v3 + >>> application_key = api.create_key(['listFiles'], 'my-key', bucket_ids=[bucket.id_]) + >>> application_key.bucket_ids + ['bucket_0'] + +Each layer rejects the argument name of the other layer with a ``TypeError``. +To migrate, wrap the bucket ID in a list and rename the argument and the attribute. +Pass ``None`` for ``bucket_ids`` to create a key that is not restricted to buckets. + +The ``B2Session.create_key`` method and the raw API ``create_key`` methods take the bucket IDs in the same position as before. +Pass a list of bucket IDs instead of one bucket ID. + +List files in a folder +====================== + +The first argument of ``Bucket.ls`` changed its name and its default behavior. + +* ``b2sdk.v2`` names the first argument ``folder_to_list``. + It also takes ``folder_to_list_can_be_a_file`` and ``**kwargs``. +* ``b2sdk.v3`` names the first argument ``path``. + It takes no ``folder_to_list_can_be_a_file`` argument and no ``**kwargs``. + +The ``b2sdk.v2`` method adds ``/`` to ``folder_to_list`` when all of these conditions are true: + +* ``folder_to_list_can_be_a_file`` is ``False``, which is the default. +* ``folder_to_list`` is not empty and does not end with ``/``. +* ``with_wildcard`` is ``False``. + +Then the method lists only the files in that folder. +The ``b2sdk.v3`` method does not add ``/``. +For a path that does not end with ``/``, it first looks for a file with that exact name. +If the file exists, the method returns that file and does not list a folder. +If no file has that name, the method lists the files that have that folder prefix. + +The example below uses a bucket that has a file named ``dir`` and a folder named ``dir/``. + +.. code-block:: python + + >>> uploaded = [bucket.upload_bytes(b'x', name) for name in ['dir', 'dir/b.txt', 'dir/sub/c.txt']] + >>> def names(entries): + ... return [(file_version.file_name, folder) for file_version, folder in entries] + + >>> # b2sdk.v2 + >>> names(bucket.ls(folder_to_list='dir')) + [('dir/b.txt', None), ('dir/sub/c.txt', 'dir/sub/')] + >>> names(bucket.ls(folder_to_list='dir', folder_to_list_can_be_a_file=True)) + [('dir', None)] + + >>> # b2sdk.v3 + >>> names(bucket.ls(path='dir')) + [('dir', None)] + >>> names(bucket.ls(path='dir/')) + [('dir/b.txt', None), ('dir/sub/c.txt', 'dir/sub/')] + +To migrate, follow these steps: + +#. Rename ``folder_to_list`` to ``path``. +#. Remove ``folder_to_list_can_be_a_file``. + The ``b2sdk.v3`` method always has the behavior that ``folder_to_list_can_be_a_file=True`` selects on ``b2sdk.v2``. +#. Add ``/`` to the end of every folder path. + The ``/`` selects the folder, and it saves one API call. + +Upload files +============ + +The ``b2sdk.v2`` upload methods accept ``*args`` and ``**kwargs``. +The ``b2sdk.v3`` upload methods name every parameter. +The ``b2sdk.v3`` methods ``Bucket.upload_bytes`` and ``Bucket.upload_local_file`` add these parameters after ``cache_control``, in this order: + +#. ``expires`` +#. ``content_disposition`` +#. ``content_encoding`` +#. ``content_language`` + +The ``b2sdk.v2`` methods pass ``*args`` and ``**kwargs`` on to the ``b2sdk.v3`` method. +Because of this, a ``b2sdk.v2`` call can already use the new parameters. +A ``b2sdk.v3`` call that has an argument the method does not name raises a ``TypeError``. + +.. code-block:: python + + >>> file_version = bucket.upload_bytes(b'x', 'page.txt', content_disposition='attachment', expires='Wed, 21 Oct 2026 07:28:00 GMT') + >>> file_version.file_info + {'b2-expires': 'Wed, 21 Oct 2026 07:28:00 GMT', 'b2-content-disposition': 'attachment'} + +The same call works on ``b2sdk.v2`` and on ``b2sdk.v3``. + +The ``b2sdk.v2`` upload methods also accept ``file_infos`` as a deprecated name of ``file_info``. +They raise a ``DeprecationWarning`` when you use it. +The ``b2sdk.v3`` methods do not accept ``file_infos``. +To migrate, rename ``file_infos`` to ``file_info``. + +.. code-block:: python + + >>> bucket.upload_bytes(b'x', 'a.txt', file_info={'author': 'me'}).file_info + {'author': 'me'} + >>> bucket.upload_bytes(b'x', 'b.txt', file_infos={'author': 'me'}) + Traceback (most recent call last): + ... + TypeError: Bucket.upload_bytes() got an unexpected keyword argument 'file_infos'. Did you mean 'file_info'? + +The second call fails on ``b2sdk.v3`` only. + +Lower-level upload methods +-------------------------- + +These methods accept ``cache_control``, ``*args``, and ``**kwargs`` on ``b2sdk.v2``: + +* ``B2Session.upload_file`` +* ``upload_file`` and ``get_upload_file_headers`` in ``AbstractRawApi``, ``B2RawHTTPApi``, and ``RawSimulator`` +* ``BucketSimulator.upload_file`` + +The ``b2sdk.v3`` versions of these methods do not accept ``cache_control``, ``*args``, or ``**kwargs``. +The ``b2sdk.v2`` versions store ``cache_control`` in ``file_info`` under the key ``b2-cache-control``. +To migrate, put that key in ``file_info`` yourself. + +.. code-block:: python + + >>> import hashlib, io + >>> data = b'hello' + >>> sha1 = hashlib.sha1(data).hexdigest() + + >>> # b2sdk.v2 + >>> api.session.upload_file(bucket.id_, 's.txt', 5, 'text/plain', sha1, {}, io.BytesIO(data), cache_control='max-age=60')['fileInfo'] + {'b2-cache-control': 'max-age=60'} + + >>> # b2sdk.v3 + >>> api.session.upload_file(bucket.id_, 's.txt', 5, 'text/plain', sha1, {'b2-cache-control': 'max-age=60'}, io.BytesIO(data))['fileInfo'] + {'b2-cache-control': 'max-age=60'} + +Read the cache control of a file version +======================================== + +The ``FILE_VERSION_CLASS`` attribute of ``FileVersionFactory`` changed its constructor. +The ``b2sdk.v2`` class takes a ``cache_control`` argument. +If the argument is ``None``, the class reads the ``b2-cache-control`` key of ``file_info``. +The ``b2sdk.v3`` class does not take the argument. + +The ``cache_control`` attribute of a ``FileVersion`` object works on both layers. +The ``b2sdk.v3`` object reads the attribute from the ``b2-cache-control`` key of ``file_info``. +To migrate code that builds a file version from a constructor call, remove the ``cache_control`` argument. +Put the value in ``file_info`` under ``b2-cache-control`` instead. + +.. code-block:: python + + >>> file_version = bucket.upload_bytes(b'x', 'c.txt', cache_control='max-age=60') + >>> file_version.cache_control + 'max-age=60' + +Replace classes that exist only in v2 +===================================== + +Four classes are exported by ``b2sdk.v2`` and not by ``b2sdk.v3``. + +.. list-table:: + :header-rows: 1 + + * - ``b2sdk.v2`` name + - What to use on ``b2sdk.v3`` + * - ``AbstractSyncPath`` + - ``AbstractPath`` + * - ``LocalSyncPath`` + - ``LocalPath`` + * - ``B2SyncPath`` + - ``B2Path`` + * - ``TempDir`` + - ``tempfile.TemporaryDirectory`` from the Python standard library + +The first three names are aliases on ``b2sdk.v2``. +They refer to the same classes as the ``b2sdk.v3`` names. +Change only the name. + +``TempDir`` is deprecated on ``b2sdk.v2``. +It raises a ``DeprecationWarning`` when you enter it. +Its ``__enter__`` method returns the path of a new temporary directory as a string. +The ``__exit__`` method removes the directory. +``tempfile.TemporaryDirectory`` returns a string path in the same way. + +.. code-block:: python + + >>> import tempfile + >>> with tempfile.TemporaryDirectory() as directory: + ... print(type(directory).__name__) + str + +How to check the differences yourself +===================================== + +The layers change between releases. +Run the following script to list the differences in the installed version. +The script compares the parameter names of every public method of every class that both layers export. +It also lists the classes that only one layer exports. +It does not compare behavior. +Read the code under ``b2sdk/v2/`` to find behavior differences. + +.. code-block:: python + + import inspect + + import b2sdk.v2 as v2 + import b2sdk.v3 as v3 + + names_v2 = {name for name in dir(v2) if not name.startswith('_')} + names_v3 = {name for name in dir(v3) if not name.startswith('_')} + for name in sorted(names_v2 & names_v3): + class_v2, class_v3 = getattr(v2, name), getattr(v3, name) + if not (inspect.isclass(class_v2) and inspect.isclass(class_v3)): + continue + for method in sorted(m for m in dir(class_v2) if not m.startswith('_')): + if not hasattr(class_v3, method): + continue + method_v2, method_v3 = getattr(class_v2, method), getattr(class_v3, method) + if not (callable(method_v2) and callable(method_v3)): + continue + params_v2 = list(inspect.signature(method_v2).parameters) + params_v3 = list(inspect.signature(method_v3).parameters) + if params_v2 != params_v3: + print(f'{name}.{method}\n v2 {params_v2}\n v3 {params_v3}') + print('only v2:', sorted(names_v2 - names_v3)) + print('only v3:', sorted(names_v3 - names_v2)) diff --git a/llms.txt b/llms.txt index 6447b7857..67407c4aa 100644 --- a/llms.txt +++ b/llms.txt @@ -8,6 +8,7 @@ - [Install](https://b2-sdk-python.readthedocs.io/en/master/install.html): Install the SDK. - [Quick start](https://b2-sdk-python.readthedocs.io/en/master/quick_start.html): Start using the SDK. - [Tutorial](https://b2-sdk-python.readthedocs.io/en/master/tutorial.html): Follow a walkthrough. +- [Migrating from v2 to v3](https://b2-sdk-python.readthedocs.io/en/master/migrating.html): Update code from `b2sdk.v2` to `b2sdk.v3`. ## Guides From 907ee535ddac14335ffc4b3c031fe7d4b190cd68 Mon Sep 17 00:00:00 2001 From: Felipe Fumero Date: Fri, 27 Nov 2026 11:43:08 -0600 Subject: [PATCH 102/113] Check that nox sessions and paths named in agent instructions exist (#791) --- .../+instructions-check.infrastructure.md | 1 + test/static/test_agent_instructions.py | 100 ++++++++++++++++++ 2 files changed, 101 insertions(+) create mode 100644 changelog.d/+instructions-check.infrastructure.md create mode 100644 test/static/test_agent_instructions.py diff --git a/changelog.d/+instructions-check.infrastructure.md b/changelog.d/+instructions-check.infrastructure.md new file mode 100644 index 000000000..8fde94518 --- /dev/null +++ b/changelog.d/+instructions-check.infrastructure.md @@ -0,0 +1 @@ +Add a static test that checks the `nox` sessions and relative paths named in `AGENTS.md`, `CONTRIBUTING.md` and the agent skills exist. diff --git a/test/static/test_agent_instructions.py b/test/static/test_agent_instructions.py new file mode 100644 index 000000000..55655ad79 --- /dev/null +++ b/test/static/test_agent_instructions.py @@ -0,0 +1,100 @@ +###################################################################### +# +# File: test/static/test_agent_instructions.py +# +# Copyright 2026 Backblaze Inc. All Rights Reserved. +# +# License https://www.backblaze.com/using_b2_code.html +# +###################################################################### +import ast +import re +from pathlib import Path + +import pytest + +ROOT = Path(__file__).resolve().parents[2] +NOX_SESSION_RE = re.compile(r'\bnox\b(?:\s+-\S+)*\s+-s\s+(\w+)') +LINK_RE = re.compile(r'\]\(([^)\s]+)\)') +TICK_RE = re.compile( + r'`((?:(?:b2sdk|test|doc|docs|changelog\.d|\.sdkharness|\.github|\.claude|_internal)/[^`\s]*)' + r'|(?:noxfile\.py|[A-Za-z][\w.-]*\.(?:md|toml|lock|txt)))`' +) +PLACEHOLDER_RE = re.compile(r'v[Nn]|[<>*{]') + + +def noxfile_sessions(noxfile): + """Read session names statically: noxfile.py must not be imported.""" + names = set() + for node in ast.walk(ast.parse(noxfile.read_text(encoding='utf-8'))): + if not isinstance(node, ast.FunctionDef): + continue + for deco in node.decorator_list: + func = deco.func if isinstance(deco, ast.Call) else deco + if not (isinstance(func, ast.Attribute) and func.attr == 'session'): + continue + name = node.name + for kw in deco.keywords if isinstance(deco, ast.Call) else []: + if kw.arg == 'name' and isinstance(kw.value, ast.Constant): + name = kw.value.value + names.add(name) + return names + + +def instruction_files(root): + # AGENTS.md and CONTRIBUTING.md must exist: a rename must not silently drop the check + files = [root / 'AGENTS.md', root / 'CONTRIBUTING.md'] + optional = [root / '.github' / 'pull_request_template.md'] + optional.extend(sorted(root.glob('.claude/skills/*/SKILL.md'))) + return files + [f for f in optional if f.is_file()] + + +def check_instructions(text, root, sessions, base=None): + """Return one message per unknown nox session or missing relative path.""" + base = base or root + problems = [] + for line_number, line in enumerate(text.splitlines(), 1): + for name in NOX_SESSION_RE.findall(line): + if name not in sessions: + problems.append(f'line {line_number}: missing nox session {name}') + targets = [ + t for t in LINK_RE.findall(line) if not t.startswith(('http://', 'https://', '#')) + ] + targets += TICK_RE.findall(line) + for target in targets: + path = target.split('#')[0].rstrip('.,:;') + if not path or PLACEHOLDER_RE.search(path): + continue + if not any((d / path).exists() for d in (root, base, root / 'b2sdk')): + problems.append(f'line {line_number}: missing path {path}') + return problems + + +@pytest.mark.parametrize('file', instruction_files(ROOT), ids=lambda f: str(f.relative_to(ROOT))) +def test_instructions_name_existing_sessions_and_paths(file): + assert file.is_file(), f'{file.relative_to(ROOT)} is missing' + text = file.read_text(encoding='utf-8') + problems = check_instructions(text, ROOT, noxfile_sessions(ROOT / 'noxfile.py'), file.parent) + assert not problems, f'{file.relative_to(ROOT)}: ' + '; '.join(problems) + + +def test_noxfile_sessions_are_read_statically(): + sessions = noxfile_sessions(ROOT / 'noxfile.py') + assert {'format', 'lint', 'unit', 'towncrier_check'} <= sessions + assert 'format_' not in sessions + + +def test_unknown_session_and_path_are_rejected(tmp_path): + (tmp_path / 'real.md').write_text('x') + text = ( + 'Run `nox --non-interactive -s no_such_session-3.14`.\n' + 'See [a](real.md), [b](gone.md) and `test/nope.py`; `test/vN/*` is skipped.\n' + 'Also `gone.toml` and `real.md`.\n' + ) + problems = check_instructions(text, tmp_path, {'lint'}) + assert problems == [ + 'line 1: missing nox session no_such_session', + 'line 2: missing path gone.md', + 'line 2: missing path test/nope.py', + 'line 3: missing path gone.toml', + ] From 535d5f4cca46c84b3ed52445641a750c5d84948d Mon Sep 17 00:00:00 2001 From: Felipe Fumero Date: Fri, 27 Nov 2026 13:37:06 -0600 Subject: [PATCH 103/113] fix: serialize account database migrations (#793) Co-authored-by: Shubham Padkonde --- .../account_info/sqlite_account_info.py | 8 +++- changelog.d/232.fixed.md | 1 + .../account_info/test_sqlite_account_info.py | 43 +++++++++++++++++++ 3 files changed, 51 insertions(+), 1 deletion(-) create mode 100644 changelog.d/232.fixed.md diff --git a/b2sdk/_internal/account_info/sqlite_account_info.py b/b2sdk/_internal/account_info/sqlite_account_info.py index 16c2a57ef..026eeec1f 100644 --- a/b2sdk/_internal/account_info/sqlite_account_info.py +++ b/b2sdk/_internal/account_info/sqlite_account_info.py @@ -470,7 +470,13 @@ def _get_update_count(self, update_number: int): def _perform_update(self, update_number, update_commands: list[str | tuple[str, tuple]]): with self._get_connection() as conn: - conn.execute('BEGIN') + # Serialize the check and migration across independent connections. + conn.execute('BEGIN IMMEDIATE') + if conn.execute( + 'SELECT COUNT(*) FROM update_done WHERE update_number = ?;', + (update_number,), + ).fetchone()[0]: + return for command in update_commands: if isinstance(command, str): conn.execute(command) diff --git a/changelog.d/232.fixed.md b/changelog.d/232.fixed.md new file mode 100644 index 000000000..144a62e61 --- /dev/null +++ b/changelog.d/232.fixed.md @@ -0,0 +1 @@ +Serialize account database schema migrations so concurrent SDK instances do not apply the same upgrade twice. diff --git a/test/unit/account_info/test_sqlite_account_info.py b/test/unit/account_info/test_sqlite_account_info.py index afb2231f6..68543b477 100644 --- a/test/unit/account_info/test_sqlite_account_info.py +++ b/test/unit/account_info/test_sqlite_account_info.py @@ -11,6 +11,9 @@ import json import os +import sqlite3 +import threading +from concurrent.futures import ThreadPoolExecutor import pytest from apiver_deps import ( @@ -34,6 +37,46 @@ def setup(self, sqlite_account_info_factory, account_info_default_data_schema_0) self.sqlite_account_info_factory = sqlite_account_info_factory self.account_info_default_data = account_info_default_data_schema_0 + @pytest.mark.parametrize('version', range(1, 7)) + def test_concurrent_migrations(self, version): + original = self.sqlite_account_info_factory(last_upgrade_to_run=0) + original.set_auth_data_with_schema_0_for_test(**self.account_info_default_data) + old_account_info = self.sqlite_account_info_factory(last_upgrade_to_run=version - 1) + barrier = threading.Barrier(2, timeout=10) + + class ConcurrentAccountInfo(SqliteAccountInfo): + def _get_update_count(self, update_number): + count = super()._get_update_count(update_number) + if update_number == version and count == 0: + # Both independent connections observe the pending migration. + barrier.wait() + return count + + def upgrade(): + account_info = ConcurrentAccountInfo( + file_name=old_account_info.filename, last_upgrade_to_run=version + ) + try: + assert account_info.get_account_id() == 'account_id' + assert account_info.get_account_auth_token() == 'account_auth' + return account_info._get_update_count(version) + finally: + account_info.close() + + with ThreadPoolExecutor(max_workers=2) as executor: + futures = [executor.submit(upgrade) for _ in range(2)] + assert [future.result(timeout=20) for future in futures] == [1, 1] + assert old_account_info._get_update_count(version) == 1 + + def test_failed_migration_rolls_back_and_can_be_retried(self): + account_info = self.sqlite_account_info_factory() + command = 'ALTER TABLE account ADD COLUMN migration_test TEXT;' + with pytest.raises(sqlite3.OperationalError): + account_info._ensure_update(7, [command, 'INVALID SQL']) + assert account_info._get_update_count(7) == 0 + account_info._ensure_update(7, [command]) + assert account_info._get_update_count(7) == 1 + def test_upgrade_1_default_allowed(self): """The 'allowed' field should be the default for upgraded databases.""" old_account_info = self.sqlite_account_info_factory(last_upgrade_to_run=0) From d3dc05761d9bff4d2ee920861f3c4a12fc674918 Mon Sep 17 00:00:00 2001 From: Felipe Fumero Date: Fri, 27 Nov 2026 13:37:27 -0600 Subject: [PATCH 104/113] Keep Unauthorized subclass when adding app key info (#795) The session rebuilt every Unauthorized as the base class, so EmailNotVerified and NoPaymentHistory could not be caught and their should_retry_upload() = False was lost. Co-authored-by: patrick-immometrica --- b2sdk/_internal/session.py | 2 +- changelog.d/+unauthorized-subclass.fixed.md | 1 + test/unit/test_session.py | 15 ++++++++++++++- 3 files changed, 16 insertions(+), 2 deletions(-) create mode 100644 changelog.d/+unauthorized-subclass.fixed.md diff --git a/b2sdk/_internal/session.py b/b2sdk/_internal/session.py index 125df0207..56e099366 100644 --- a/b2sdk/_internal/session.py +++ b/b2sdk/_internal/session.py @@ -546,7 +546,7 @@ def _add_app_key_info_to_unauthorized(self, unauthorized): new_message = unauthorized.message or 'unauthorized' new_message += ' for application key ' + ', '.join(key_messages) - return Unauthorized(new_message, unauthorized.code) + return type(unauthorized)(new_message, unauthorized.code) def _get_allowed_buckets_message(self, allowed) -> str | None: buckets = allowed['buckets'] diff --git a/changelog.d/+unauthorized-subclass.fixed.md b/changelog.d/+unauthorized-subclass.fixed.md new file mode 100644 index 000000000..4d7087b3d --- /dev/null +++ b/changelog.d/+unauthorized-subclass.fixed.md @@ -0,0 +1 @@ +The session no longer turns `EmailNotVerified` and `NoPaymentHistory` into a plain `Unauthorized`, so uploads fail right away instead of being retried. diff --git a/test/unit/test_session.py b/test/unit/test_session.py index 1b9d36cba..01ec8d911 100644 --- a/test/unit/test_session.py +++ b/test/unit/test_session.py @@ -13,7 +13,7 @@ import pytest from apiver_deps import AuthInfoCache, B2Session, DummyCache, InMemoryAccountInfo -from apiver_deps_exception import Unauthorized +from apiver_deps_exception import EmailNotVerified, NoPaymentHistory, Unauthorized from .account_info.fixtures import * # noqa from .fixtures import * # noqa @@ -136,6 +136,19 @@ def test_app_key_info_all_info(self): ): self.b2_session.get_file_info_by_id(None) + @pytest.mark.apiver(from_ver=3) + @pytest.mark.parametrize('exc_class', [EmailNotVerified, NoPaymentHistory]) + def test_app_key_info_keeps_exception_type(self, exc_class): + self.b2_session.account_info.get_allowed.return_value = dict( + buckets=None, + capabilities=ALL_CAPABILITIES, + namePrefix=None, + ) + self.b2_session.raw_api.get_file_info_by_id.side_effect = exc_class('no_go', 'code') + + with pytest.raises(exc_class, match=r'no_go for application key with no restrictions'): + self.b2_session.get_file_info_by_id(None) + def test_session__with_in_memory_account_info(apiver_int): memory_info = InMemoryAccountInfo() From 7b846efd1f4d24182ef329fe69fe1cdbcdedfc3d Mon Sep 17 00:00:00 2001 From: Felipe Fumero Date: Fri, 27 Nov 2026 13:37:53 -0600 Subject: [PATCH 105/113] Fix repeated words in comments and docstrings (#797) * docs: fix doubled word Signed-off-by: Chareonwit Kunna <21arenabreakout12@gmail.com> * docs: fix doubled word Signed-off-by: Chareonwit Kunna <21arenabreakout12@gmail.com> * docs: fix doubled word Signed-off-by: Chareonwit Kunna <21arenabreakout12@gmail.com> * docs: fix doubled word Signed-off-by: Chareonwit Kunna <21arenabreakout12@gmail.com> * docs: add a changelog fragment for the repeated-word fixes --------- Signed-off-by: Chareonwit Kunna <21arenabreakout12@gmail.com> Co-authored-by: Chareonwit Kunna <21arenabreakout12@gmail.com> --- b2sdk/_internal/exception.py | 2 +- b2sdk/_internal/sync/policy.py | 2 +- b2sdk/v1/bucket.py | 2 +- changelog.d/+fix-doubled-words.doc.md | 1 + test/unit/b2http/test_b2http.py | 2 +- 5 files changed, 5 insertions(+), 4 deletions(-) create mode 100644 changelog.d/+fix-doubled-words.doc.md diff --git a/b2sdk/_internal/exception.py b/b2sdk/_internal/exception.py index 090b32915..2847bc3f4 100644 --- a/b2sdk/_internal/exception.py +++ b/b2sdk/_internal/exception.py @@ -228,7 +228,7 @@ class B2RequestTimeout(TransientErrorMixin, B2SimpleError): class B2RequestTimeoutDuringUpload(B2RequestTimeout): - # if a timeout is hit during upload, it is not guaranteed that the the server has released the upload token lock already, so we'll use a new token + # if a timeout is hit during upload, it is not guaranteed that the server has released the upload token lock already, so we'll use a new token def should_retry_http(self): return False diff --git a/b2sdk/_internal/sync/policy.py b/b2sdk/_internal/sync/policy.py index 6d22cbc95..3d39bbba3 100644 --- a/b2sdk/_internal/sync/policy.py +++ b/b2sdk/_internal/sync/policy.py @@ -137,7 +137,7 @@ def files_are_different( newer_file_mode: NewerFileSyncMode = NewerFileSyncMode.RAISE_ERROR, ): """ - Compare two files and determine if the the destination file + Compare two files and determine if the destination file should be replaced by the source file. :param b2sdk.v2.AbstractPath source_path: source file object diff --git a/b2sdk/v1/bucket.py b/b2sdk/v1/bucket.py index f2922128c..320ad4400 100644 --- a/b2sdk/v1/bucket.py +++ b/b2sdk/v1/bucket.py @@ -29,7 +29,7 @@ # and to retain old style download_file_by_name signature # and to retain old style download_file_by_id signature (allowing for the new one as well) # and to retain old style get_file_info_by_name return type -# and to to adjust to old style B2Api.get_file_info return type +# and to adjust to old style B2Api.get_file_info return type # and to retain old style update return type class Bucket(v2.Bucket): FILE_VERSION_FACTORY = staticmethod(FileVersionInfoFactory) diff --git a/changelog.d/+fix-doubled-words.doc.md b/changelog.d/+fix-doubled-words.doc.md new file mode 100644 index 000000000..b29638a7c --- /dev/null +++ b/changelog.d/+fix-doubled-words.doc.md @@ -0,0 +1 @@ +Fix repeated words in comments and docstrings. diff --git a/test/unit/b2http/test_b2http.py b/test/unit/b2http/test_b2http.py index 7d7d432de..442575149 100644 --- a/test/unit/b2http/test_b2http.py +++ b/test/unit/b2http/test_b2http.py @@ -553,7 +553,7 @@ def test_get_content(self, b2_http: B2Http): close_mock = MagicMock() def response_callback(resp): - # mock the response close method so that we can can check if it has been called later + # mock the response close method so that we can check if it has been called later resp.close = close_mock return resp From 2653745d81f6656c56169838e22bff68e1b3c4fd Mon Sep 17 00:00:00 2001 From: Felipe Fumero Date: Fri, 27 Nov 2026 13:38:13 -0600 Subject: [PATCH 106/113] Escape remote names in the sync failed-action error output (#798) * fix: escape remote names in the sync failed-action error output * test: cover escaping of remote names in sync output --------- Co-authored-by: Paul Valladares <85648028+dreyfus92@users.noreply.github.com> --- b2sdk/_internal/sync/action.py | 4 +- changelog.d/631.fixed.md | 1 + test/unit/sync/test_sync_escaping.py | 62 ++++++++++++++++++++++++++++ 3 files changed, 65 insertions(+), 2 deletions(-) create mode 100644 changelog.d/631.fixed.md create mode 100644 test/unit/sync/test_sync_escaping.py diff --git a/b2sdk/_internal/sync/action.py b/b2sdk/_internal/sync/action.py index 42e5d660d..363656957 100644 --- a/b2sdk/_internal/sync/action.py +++ b/b2sdk/_internal/sync/action.py @@ -23,7 +23,7 @@ from ..sync.report import ProgressReport, SyncReport from ..transfer.outbound.outbound_source import OutboundTransferSource from ..transfer.outbound.upload_source import UploadSourceLocalFile -from ..utils.escape import escape_control_chars +from ..utils.escape import escape_control_chars, unprintable_to_hex from .encryption_provider import AbstractSyncEncryptionSettingsProvider from .report import SyncFileReporter @@ -57,7 +57,7 @@ def run(self, bucket: Bucket, reporter: ProgressReport, dry_run: bool = False): self.do_report(bucket, reporter) except Exception as e: logger.exception('an exception occurred in a sync action') - reporter.error(str(self) + ': ' + repr(e) + ' ' + str(e)) + reporter.error(unprintable_to_hex(f'{self}: {e!r} {e}')) raise # Re-throw so we can identify failed actions @abstractmethod diff --git a/changelog.d/631.fixed.md b/changelog.d/631.fixed.md new file mode 100644 index 000000000..92edd5973 --- /dev/null +++ b/changelog.d/631.fixed.md @@ -0,0 +1 @@ +Escape control characters in the remote file name printed when a sync action fails. diff --git a/test/unit/sync/test_sync_escaping.py b/test/unit/sync/test_sync_escaping.py new file mode 100644 index 000000000..92410f673 --- /dev/null +++ b/test/unit/sync/test_sync_escaping.py @@ -0,0 +1,62 @@ +###################################################################### +# +# File: test/unit/sync/test_sync_escaping.py +# +# Copyright 2026 Backblaze Inc. All Rights Reserved. +# +# License https://www.backblaze.com/using_b2_code.html +# +###################################################################### +from __future__ import annotations + +import io +import time + +import pytest +from apiver_deps import B2Folder, LocalFolder, Synchronizer, SyncReport +from apiver_deps_exception import IncompleteSync + +# U+009B (8-bit CSI) is legal in NTFS names, so the error test can create it on Windows too +HOSTILE_NAME = '\x9b31minvoice.pdf' +ESCAPED_HOSTILE_NAME = "'\\x9b31minvoice.pdf'" + + +@pytest.fixture +def source(b2api): + b2api.create_bucket('source', 'allPrivate').upload_bytes(b'x', HOSTILE_NAME) + return B2Folder('source', '', b2api) + + +def _sync(source, dest, out, dry_run=False): + Synchronizer(max_workers=1, dry_run=dry_run).sync_folders( + source_folder=source, + dest_folder=dest, + now_millis=int(time.time() * 1000), + reporter=SyncReport(out, True), + ) + + +def test_download_completion_escapes_remote_name(source, tmp_path): + out = io.StringIO() + _sync(source, LocalFolder(str(tmp_path)), out, dry_run=True) + + assert out.getvalue().rstrip() == f'dnload {ESCAPED_HOSTILE_NAME}' + + +def test_copy_completion_escapes_remote_name(b2api, source): + b2api.create_bucket('dest', 'allPrivate') + out = io.StringIO() + _sync(source, B2Folder('dest', '', b2api), out, dry_run=True) + + assert out.getvalue().rstrip() == f'copy {ESCAPED_HOSTILE_NAME}' + + +@pytest.mark.apiver(from_ver=1) +def test_failed_action_error_escapes_remote_name(source, tmp_path): + (tmp_path / HOSTILE_NAME).mkdir() + out = io.StringIO() + with pytest.raises(IncompleteSync): + _sync(source, LocalFolder(str(tmp_path)), out) + + assert 'b2_download(\\x9b31minvoice.pdf' in out.getvalue() + assert HOSTILE_NAME not in out.getvalue() From 7b94169c24ef7c2cc8cf94cf179ecc39e547bec2 Mon Sep 17 00:00:00 2001 From: Felipe Fumero Date: Sun, 29 Nov 2026 12:02:04 -0600 Subject: [PATCH 107/113] fix: accept dotted profile names in SqliteAccountInfo (#804) Profile names such as 'work.prod' worked before the validation was anchored with fullmatch, because the unanchored match only checked the prefix. Allow '.' in the pattern and reject names made only of dots ('.', '..'). Path separators remain rejected. --- .../account_info/sqlite_account_info.py | 3 ++- changelog.d/803.fixed.md | 1 + .../account_info/test_sqlite_account_info.py | 22 +++++++++++++++++++ 3 files changed, 25 insertions(+), 1 deletion(-) create mode 100644 changelog.d/803.fixed.md diff --git a/b2sdk/_internal/account_info/sqlite_account_info.py b/b2sdk/_internal/account_info/sqlite_account_info.py index 026eeec1f..35cc962e1 100644 --- a/b2sdk/_internal/account_info/sqlite_account_info.py +++ b/b2sdk/_internal/account_info/sqlite_account_info.py @@ -27,7 +27,8 @@ B2_ACCOUNT_INFO_ENV_VAR = 'B2_ACCOUNT_INFO' B2_ACCOUNT_INFO_DEFAULT_FILE = os.path.join('~', '.b2_account_info') B2_ACCOUNT_INFO_PROFILE_FILE = os.path.join('~', '.b2db-{profile}.sqlite') -B2_ACCOUNT_INFO_PROFILE_NAME_REGEXP = re.compile(r'[a-zA-Z0-9_\-]{1,64}') +# Dots are allowed (e.g. `work.prod`), but a name made only of dots (`.`, `..`) is not. +B2_ACCOUNT_INFO_PROFILE_NAME_REGEXP = re.compile(r'(?!\.+$)[a-zA-Z0-9_.\-]{1,64}') XDG_CONFIG_HOME_ENV_VAR = 'XDG_CONFIG_HOME' DEFAULT_ABSOLUTE_MINIMUM_PART_SIZE = ( diff --git a/changelog.d/803.fixed.md b/changelog.d/803.fixed.md new file mode 100644 index 000000000..29fa5cbea --- /dev/null +++ b/changelog.d/803.fixed.md @@ -0,0 +1 @@ +Accept profile names containing a dot (e.g. `work.prod`) again; they were rejected after profile names started being validated against the whole string. Path separators and names made only of dots remain rejected. diff --git a/test/unit/account_info/test_sqlite_account_info.py b/test/unit/account_info/test_sqlite_account_info.py index 68543b477..f5fb71112 100644 --- a/test/unit/account_info/test_sqlite_account_info.py +++ b/test/unit/account_info/test_sqlite_account_info.py @@ -317,6 +317,28 @@ def test_invalid_profile_name(self): with pytest.raises(ValueError): SqliteAccountInfo.get_user_account_info_path(profile='&@(*$') + @pytest.mark.parametrize('profile', ['work.prod', 'my.profile', 'a.b-c_d', 'v1.2']) + def test_dotted_profile_name_is_accepted(self, profile): + xdg_config_path = SqliteAccountInfo._get_xdg_config_path() + if xdg_config_path: + expected_path = (xdg_config_path, 'b2', f'db-{profile}.sqlite') + else: + expected_path = ('~', f'.b2db-{profile}.sqlite') + + account_info_path = SqliteAccountInfo.get_user_account_info_path(profile=profile) + assert account_info_path == os.path.expanduser(os.path.join(*expected_path)) + + @pytest.mark.parametrize( + 'profile', + ['../x', 'a/b', 'a\\b', '..', '.', '...', 'a/../b', 'ok/../../x', 'x' * 65], + ) + def test_unsafe_profile_name_is_rejected(self, profile): + with pytest.raises(ValueError, match='Invalid profile name'): + SqliteAccountInfo.get_user_account_info_path(profile=profile) + + def test_max_length_profile_name_is_accepted(self): + SqliteAccountInfo.get_user_account_info_path(profile='x' * 64) + def test_profile_and_file_name_conflict(self): with pytest.raises(ValueError): SqliteAccountInfo.get_user_account_info_path(file_name='foo', profile='bar') From 20678d766715583dd00ca3ea3da717a34d57f6b4 Mon Sep 17 00:00:00 2001 From: Sophie <49928680+sophiecarreras@users.noreply.github.com> Date: Fri, 27 Nov 2026 07:04:09 -0300 Subject: [PATCH 108/113] test: fix G1 test data that only RawSimulator accepted Tests that use only the normal B2 API now pass on b2-simulator as well as on RawSimulator, at apiver v3, v2, v1 and v0. Each fix stays an exact check: - Retention dates are one day in the future, and tests that set retention or legal hold use a bucket with Object Lock (B2 refuses both otherwise). - test_update sends B2-valid CORS, lifecycle and replication settings (real keys and destination buckets) and derives account id, bucket id, name, revision and options from the server instead of RawSimulator's values. - Lifecycle rules carry an action, which B2 requires. - The resume helper and v1 test_started_large_file pass a content type: B2 refuses the null that content_type=None sends. - Expected content types for b2/x-auto uploads, part file ids and v1 download file ids come from the server's answers. - A refused governance delete is 401 access_denied on B2 (Unauthorized in the SDK), and a wrong SHA-1 is 400 bad_request "Sha1 did not match data received" (BadRequest); RawSimulator's AccessDenied and FileSha1Mismatch stay accepted until the default flips. The wrong-SHA-1 test now also checks that nothing was stored. - test_custom_timestamp enables custom upload timestamps on the simulator. - TestAuthorizeForBucket stays in-process at apiver v2: b2-simulator v0.6.0 refuses every bucket-restricted key at API v3. Co-Authored-By: Claude Opus 5.5 --- .../+b2-simulator-unit-g1.infrastructure.md | 1 + test/unit/bucket/test_bucket.py | 180 ++++++++++++++---- test/unit/file_version/test_file_version.py | 17 +- 3 files changed, 155 insertions(+), 43 deletions(-) create mode 100644 changelog.d/+b2-simulator-unit-g1.infrastructure.md diff --git a/changelog.d/+b2-simulator-unit-g1.infrastructure.md b/changelog.d/+b2-simulator-unit-g1.infrastructure.md new file mode 100644 index 000000000..24c3400c8 --- /dev/null +++ b/changelog.d/+b2-simulator-unit-g1.infrastructure.md @@ -0,0 +1 @@ +Fix more unit-test data that only the in-process `RawSimulator` accepted, so those tests also pass against b2-simulator: retention dates in the future and on Object Lock buckets, valid CORS, lifecycle and replication settings, an explicit content type on `b2_start_large_file`, the content type B2 stores for `b2/x-auto`, and the errors real B2 returns for a refused governance delete and a wrong SHA-1. diff --git a/test/unit/bucket/test_bucket.py b/test/unit/bucket/test_bucket.py index 89dd05f36..6228d2fa9 100644 --- a/test/unit/bucket/test_bucket.py +++ b/test/unit/bucket/test_bucket.py @@ -31,6 +31,7 @@ B2ConnectionError, B2Error, B2RequestTimeoutDuringUpload, + BadRequest, BucketIdNotFound, Conflict, DestinationDirectoryDoesntAllowOperation, @@ -48,6 +49,7 @@ RestrictedBucketMissing, SourceReplicationConflict, SSECKeyError, + Unauthorized, UnsatisfiableRange, WrongEncryptionSettingForFileWrite, ) @@ -138,11 +140,17 @@ algorithm=EncryptionAlgorithm.AES256, key=EncryptionKey(secret=None, key_id='some-id-2'), ) +# B2 refuses a retention date in the past; one day ahead outlives any test run. +FUTURE_RETAIN_UNTIL = int(time.time() * 1000) + 24 * 60 * 60 * 1000 + SSE_C_AES_FROM_SERVER = EncryptionSetting( mode=EncryptionMode.SSE_C, algorithm=EncryptionAlgorithm.AES256, key=EncryptionKey(key_id=None, secret=None), ) +# B2 needs at least one action in a lifecycle rule. +LIFECYCLE_RULE = {'fileNamePrefix': 'is_life', 'daysFromHidingToDeleting': 1} + REPLICATION = ReplicationConfiguration( rules=[ ReplicationRule( @@ -366,6 +374,13 @@ def recorder(*args, **kwargs): def bucket_ls(self, *args, show_versions=False, **kwargs): return bucket_ls(self.bucket, *args, show_versions=show_versions, **kwargs) + def _use_file_lock_bucket(self): + """Point the test at a new Object Lock bucket: B2 refuses retention and legal hold elsewhere.""" + self.bucket = self.api.create_bucket( + self.bucket_name + '-file-lock', 'allPublic', is_file_lock_enabled=True + ) + self.bucket_id = self.bucket.id_ + def assertBucketContents(self, expected, *args, **kwargs): """ *args and **kwargs are passed to self.bucket_ls() @@ -458,9 +473,9 @@ def testThree(self): self.bucket_id, file1.file_id, UploadSourceBytes(content), 3, large_file_upload_state ).result() expected_parts = [ - Part('9999', 1, 11, content_sha1), - Part('9999', 2, 11, content_sha1), - Part('9999', 3, 11, content_sha1), + Part(file1.file_id, 1, 11, content_sha1), + Part(file1.file_id, 2, 11, content_sha1), + Part(file1.file_id, 3, 11, content_sha1), ] self.assertEqual(expected_parts, list(self.bucket.list_parts(file1.file_id, batch_size=1))) @@ -526,7 +541,8 @@ def _make_file(self, file_id, file_name): class TestGetFileInfo(TestCaseWithBucket): def test_version_by_name(self): data = b'hello world' - a_id = self.bucket.upload_bytes(data, 'a').id_ + uploaded = self.bucket.upload_bytes(data, 'a') + a_id = uploaded.id_ info = self.bucket.get_file_info_by_name('a') @@ -534,11 +550,12 @@ def test_version_by_name(self): self.assertIsInstance(info, VFileVersionInfo) else: self.assertIsInstance(info, DownloadVersion) + # The upload sent b2/x-auto; B2 stores the type it resolved, which the upload answer reports. expected = ( a_id, 'a', 11, - 'b2/x-auto', + uploaded.content_type, 'SSE-B2', NO_RETENTION_FILE_SETTING, LegalHold.UNSET, @@ -560,7 +577,7 @@ def test_version_by_name_file_lock(self): ) data = b'hello world' legal_hold = LegalHold.ON - file_retention = FileRetentionSetting(RetentionMode.COMPLIANCE, 100) + file_retention = FileRetentionSetting(RetentionMode.COMPLIANCE, FUTURE_RETAIN_UNTIL) bucket.upload_bytes(data, 'a', file_retention=file_retention, legal_hold=legal_hold) @@ -598,12 +615,14 @@ def test_version_by_name_file_lock(self): def test_version_by_id(self): data = b'hello world' - b_id = self.bucket.upload_bytes(data, 'b').id_ + uploaded = self.bucket.upload_bytes(data, 'b') + b_id = uploaded.id_ info = self.bucket.get_file_info_by_id(b_id) self.assertIsInstance(info, VFileVersionInfo) - expected = (b_id, 'b', 11, 'upload', 'b2/x-auto', 'SSE-B2') + # The upload sent b2/x-auto; B2 stores the type it resolved, which the upload answer reports. + expected = (b_id, 'b', 11, 'upload', uploaded.content_type, 'SSE-B2') actual = ( info.id_, info.file_name, @@ -672,7 +691,8 @@ def test_three_files_multiple_versions(self): @pytest.mark.apiver(to_ver=1) def test_started_large_file(self): - self.bucket.start_large_file('hello.txt') + # An explicit content type: B2 refuses the null that content_type=None sends. + self.bucket.start_large_file('hello.txt', 'b2/x-auto') expected = [('hello.txt', 0, 'start', None)] self.assertBucketContents(expected, '', show_versions=True) @@ -704,16 +724,21 @@ def test_delete_file_version(self): self.assertBucketContents(expected, '', show_versions=True) def test_delete_file_version_bypass_governance(self): + self._use_file_lock_bucket() data = b'hello world' file_id = self.bucket.upload_bytes( data, 'hello.txt', - file_retention=FileRetentionSetting(RetentionMode.GOVERNANCE, int(time.time()) + 100), + file_retention=FileRetentionSetting(RetentionMode.GOVERNANCE, FUTURE_RETAIN_UNTIL), ).id_ - with pytest.raises(AccessDenied): + # Real B2 refuses this delete with 401 access_denied (the b2_delete_file_version error + # table), which the SDK raises as Unauthorized; RawSimulator raises AccessDenied. + with pytest.raises((AccessDenied, Unauthorized)) as refusal: self.bucket.delete_file_version(file_id, 'hello.txt') + if isinstance(refusal.value, Unauthorized): + assert refusal.value.code == 'access_denied' self.bucket.delete_file_version(file_id, 'hello.txt', bypass_governance=True) self.assertBucketContents([], '', show_versions=True) @@ -1392,8 +1417,10 @@ def test_copy_with_replace_metadata(self): metadata_directive=MetadataDirectiveMode.REPLACE, content_type='text/plain', ) + # The source was uploaded with b2/x-auto; B2 stores the type it resolved. + source_content_type = self.bucket.get_file_info_by_name('hello.txt').content_type expected = [ - ('hello.txt', 11, 'upload', 'b2/x-auto', None), + ('hello.txt', 11, 'upload', source_content_type, None), ('hello_new.txt', 11, 'upload', 'text/plain', None), ] actual = [ @@ -1444,6 +1471,7 @@ def ls(bucket): self.assertBucketContents(expected, '', show_versions=True) def test_copy_retention(self): + self._use_file_lock_bucket() for data in [self._make_data(self.simulator.MIN_PART_SIZE * 3), b'hello']: for length in [None, len(data)]: with self.subTest(real_length=len(data), length=length): @@ -1452,12 +1480,14 @@ def test_copy_retention(self): file_id, 'copied_file', length=length, - file_retention=FileRetentionSetting(RetentionMode.COMPLIANCE, 100), + file_retention=FileRetentionSetting( + RetentionMode.COMPLIANCE, FUTURE_RETAIN_UNTIL + ), legal_hold=LegalHold.ON, max_part_size=400, ) self.assertEqual( - FileRetentionSetting(RetentionMode.COMPLIANCE, 100), + FileRetentionSetting(RetentionMode.COMPLIANCE, FUTURE_RETAIN_UNTIL), resulting_file_version.file_retention, ) self.assertEqual(LegalHold.ON, resulting_file_version.legal_hold) @@ -1771,30 +1801,79 @@ def test_update_bucket_without_encryption_passes_none_to_raw_api(self): class TestUpdate(TestCaseWithBucket): + def _replication_with_real_keys(self): + """REPLICATION's shape, with the buckets and keys B2 checks created for real.""" + destination_ids = [ + self.api.create_bucket(f'{self.bucket_name}-replica-{n}', 'allPrivate').id_ + for n in (1, 2) + ] + source_key_ids = [ + create_key(self.api, ['readFiles'], f'replication-source-{n}').id_ for n in (1, 2, 3) + ] + destination_key_ids = [ + create_key(self.api, ['writeFiles'], f'replication-destination-{n}').id_ for n in (1, 2) + ] + return ReplicationConfiguration( + rules=[ + ReplicationRule( + destination_bucket_id=destination_ids[0], + name='replication-us-west', + ), + ReplicationRule( + destination_bucket_id=destination_ids[1], + name='replication-us-west-2', + file_name_prefix='replica/', + is_enabled=False, + priority=255, + ), + ], + source_key_id=source_key_ids[0], + source_to_destination_key_mapping={ + source_key_ids[1]: destination_key_ids[0], + source_key_ids[2]: destination_key_ids[1], + }, + ) + def test_update(self): + # B2 refuses a default retention on a bucket without Object Lock, CORS rules that are + # not a list of rules, a lifecycle rule without an action, and replication with keys or + # buckets that do not exist. + self._use_file_lock_bucket() + replication = self._replication_with_real_keys() + cors_rules = [ + { + 'corsRuleName': 'downloadFromAnyOrigin', + 'allowedOrigins': ['https'], + 'allowedOperations': ['b2_download_file_by_name'], + 'maxAgeSeconds': 3600, + } + ] + revision_before = self.bucket.revision result = self.bucket.update( bucket_type='allPrivate', bucket_info={'info': 'o'}, - cors_rules={'andrea': 'corr'}, - lifecycle_rules=[{'fileNamePrefix': 'is_life'}], + cors_rules=cors_rules, + lifecycle_rules=[LIFECYCLE_RULE], default_server_side_encryption=SSE_B2_AES, default_retention=BucketRetentionSetting( RetentionMode.COMPLIANCE, RetentionPeriod(years=7) ), - replication=REPLICATION, + replication=replication, ) if apiver_deps.V <= 1: self.maxDiff = None with suppress(KeyError): del result['replicationConfiguration'] + # The bucket keeps the options it was created with (B2 sends a list, RawSimulator a set). + self.assertEqual(self.bucket.options_set, set(result.pop('options'))) self.assertEqual( { - 'accountId': 'account-0', - 'bucketId': 'bucket_0', + 'accountId': self.account_info.get_account_id(), + 'bucketId': self.bucket.id_, 'bucketInfo': {'info': 'o'}, - 'bucketName': 'my-bucket', + 'bucketName': self.bucket.name, 'bucketType': 'allPrivate', - 'corsRules': {'andrea': 'corr'}, + 'corsRules': cors_rules, 'defaultServerSideEncryption': { 'isClientAuthorizedToRead': True, 'value': {'algorithm': 'AES256', 'mode': 'SSE-B2'}, @@ -1806,12 +1885,11 @@ def test_update(self): 'mode': 'compliance', 'period': {'unit': 'years', 'duration': 7}, }, - 'isFileLockEnabled': None, + 'isFileLockEnabled': True, }, }, - 'lifecycleRules': [{'fileNamePrefix': 'is_life'}], - 'options': set(), - 'revision': 2, + 'lifecycleRules': [LIFECYCLE_RULE], + 'revision': revision_before + 1, }, result, ) @@ -1822,14 +1900,15 @@ def test_update(self): 'name': self.bucket.name, 'type_': 'allPrivate', 'bucket_info': {'info': 'o'}, - 'cors_rules': {'andrea': 'corr'}, - 'lifecycle_rules': [{'fileNamePrefix': 'is_life'}], - 'options_set': set(), + 'cors_rules': cors_rules, + 'lifecycle_rules': [LIFECYCLE_RULE], + # the options the bucket was created with + 'options_set': self.bucket.options_set, 'default_server_side_encryption': SSE_B2_AES, 'default_retention': BucketRetentionSetting( RetentionMode.COMPLIANCE, RetentionPeriod(years=7) ), - 'replication': REPLICATION, + 'replication': replication, } for attr_name, attr_value in assertions_mapping.items(): self.maxDiff = None @@ -1851,21 +1930,21 @@ def test_empty_replication(self): def test_update_if_revision_is(self): current_revision = self.bucket.revision self.bucket.update( - lifecycle_rules=[{'fileNamePrefix': 'is_life'}], + lifecycle_rules=[LIFECYCLE_RULE], if_revision_is=current_revision, ) updated_bucket = self.api.get_bucket_by_name(self.bucket.name) - self.assertEqual([{'fileNamePrefix': 'is_life'}], updated_bucket.lifecycle_rules) + self.assertEqual([LIFECYCLE_RULE], updated_bucket.lifecycle_rules) # a stale revision must be rejected, and the rejected update must not be applied with self.assertRaises(Conflict): self.bucket.update( - lifecycle_rules=[{'fileNamePrefix': 'stale_update'}], + lifecycle_rules=[{'fileNamePrefix': 'stale_update', 'daysFromHidingToDeleting': 1}], if_revision_is=current_revision, # this is now the old revision ) not_updated_bucket = self.api.get_bucket_by_name(self.bucket.name) - self.assertEqual([{'fileNamePrefix': 'is_life'}], not_updated_bucket.lifecycle_rules) + self.assertEqual([LIFECYCLE_RULE], not_updated_bucket.lifecycle_rules) def test_is_file_lock_enabled(self): assert not self.bucket.is_file_lock_enabled @@ -1925,8 +2004,9 @@ def test_upload_bytes(self): self._check_large_file_sha1('file1', None) def test_upload_bytes_file_retention(self): + self._use_file_lock_bucket() data = b'hello world' - retention = FileRetentionSetting(RetentionMode.COMPLIANCE, 150) + retention = FileRetentionSetting(RetentionMode.COMPLIANCE, FUTURE_RETAIN_UNTIL) file_info = self.bucket.upload_bytes( data, 'file1', file_retention=retention, legal_hold=LegalHold.ON ) @@ -2108,12 +2188,21 @@ def test_upload_local_wrong_sha(self): path = os.path.join(d, 'file123') data = b'hello world' write_file(path, data) - with self.assertRaises(FileSha1Mismatch): + # B2 refuses the upload with 400 bad_request "Sha1 did not match data received" + # (b2_upload_file), which the SDK raises as BadRequest; RawSimulator raises + # FileSha1Mismatch. + with pytest.raises((FileSha1Mismatch, BadRequest)) as refusal: self.bucket.upload_local_file( path, 'file123', sha1_sum='abcd' * 10, ) + if isinstance(refusal.value, BadRequest): + assert (refusal.value.code, refusal.value.message) == ( + 'bad_request', + 'Sha1 did not match data received', + ) + self.assertBucketContents([], '', show_versions=True) def test_upload_one_retryable_error(self): self.simulator.set_upload_errors([CanRetry(True)]) @@ -2316,8 +2405,9 @@ def test_upload_stream_from_file(self): def _start_large_file(self, file_name, file_info=None): if file_info is None: file_info = {} + # B2 refuses a null contentType on b2_start_large_file; use the SDK's default upload type. large_file_info = self.simulator.start_large_file( - self.api_url, self.account_auth_token, self.bucket_id, file_name, None, file_info + self.api_url, self.account_auth_token, self.bucket_id, file_name, 'b2/x-auto', file_info ) return large_file_info['fileId'] @@ -2502,6 +2592,8 @@ def _create_remote(self, sources, file_name, encryption=None): class TestCustomTimestamp(TestCaseWithBucket): + # Custom upload timestamps are a restricted B2 feature; the account must have it enabled. + @pytest.mark.b2_simulator_config(customUploadTimestampsEnabled=True) def test_custom_timestamp(self): data = b'hello world' @@ -2662,8 +2754,9 @@ def test_v1_return_types(self): expected = { 'contentLength': 19, 'contentSha1': '893e69ff0109f3459c4243013b3de8b12b41a30e', - 'contentType': 'b2/x-auto', - 'fileId': '9999', + # The upload sent b2/x-auto; B2 stores the type it resolved. + 'contentType': self.file_version.content_type, + 'fileId': self.file_version.id_, 'fileInfo': {}, 'fileName': 'file1', } @@ -3317,8 +3410,19 @@ def test_file_info_4(self): assert download_version.file_name == 'test.txt%253Ffoo%253Dbar' +class _InProcessRawSimulator(RawSimulator): + """ + Keeps a test on the in-process RawSimulator under --b2-simulator. + + At apiver v2 the SDK authorizes at B2 API v3 with a key that b2_create_key (v3) restricted to + one bucket. b2-simulator v0.6.0 refuses every bucket-restricted key at v3, including one made + at v3; serving keys made at v3 is a later b2-simulator change. + """ + + class TestAuthorizeForBucket(TestCaseWithBucket): CACHE_CLASS = InMemoryCache + RAW_SIMULATOR_CLASS = _InProcessRawSimulator if apiver_deps.V == 2 else RawSimulator @pytest.mark.apiver(from_ver=2) def test_authorize_for_bucket_ensures_cache(self): diff --git a/test/unit/file_version/test_file_version.py b/test/unit/file_version/test_file_version.py index 531f48897..203e79d0c 100644 --- a/test/unit/file_version/test_file_version.py +++ b/test/unit/file_version/test_file_version.py @@ -29,7 +29,7 @@ RawSimulator, RetentionMode, ) -from apiver_deps_exception import AccessDenied, FileNotPresent +from apiver_deps_exception import AccessDenied, FileNotPresent, Unauthorized from test.unit.b2_simulator import raw_api_class @@ -38,6 +38,9 @@ else: from apiver_deps import FileVersion as VFileVersion +# B2 refuses a retention date in the past; one day ahead outlives any test run. +FUTURE_RETAIN_UNTIL = int(time.time() * 1000) + 24 * 60 * 60 * 1000 + class TestFileVersion: @pytest.fixture(autouse=True) @@ -103,7 +106,7 @@ def test_clone_file_version_and_download_version(self): 'b2-content-encoding': 'text', }, encryption=encryption, - file_retention=FileRetentionSetting(RetentionMode.GOVERNANCE, 100), + file_retention=FileRetentionSetting(RetentionMode.GOVERNANCE, FUTURE_RETAIN_UNTIL), legal_hold=LegalHold.ON, cache_control='public, max-age=86400', ) @@ -142,7 +145,7 @@ def test_update_legal_hold(self): assert new_download_version.legal_hold == LegalHold.ON def test_update_retention(self): - new_retention = FileRetentionSetting(RetentionMode.COMPLIANCE, 100) + new_retention = FileRetentionSetting(RetentionMode.COMPLIANCE, FUTURE_RETAIN_UNTIL) new_file_version = self.file_version.update_retention(new_retention) assert isinstance(new_file_version, VFileVersion) @@ -163,11 +166,15 @@ def test_delete_bypass_governance(self): locked_file_version = self.bucket.upload_bytes( b'nothing', 'test_file_with_governance', - file_retention=FileRetentionSetting(RetentionMode.GOVERNANCE, int(time.time()) + 100), + file_retention=FileRetentionSetting(RetentionMode.GOVERNANCE, FUTURE_RETAIN_UNTIL), ) - with pytest.raises(AccessDenied): + # Real B2 refuses this delete with 401 access_denied (the b2_delete_file_version error + # table), which the SDK raises as Unauthorized; RawSimulator raises AccessDenied. + with pytest.raises((AccessDenied, Unauthorized)) as refusal: locked_file_version.delete() + if isinstance(refusal.value, Unauthorized): + assert refusal.value.code == 'access_denied' locked_file_version.delete(bypass_governance=True) with pytest.raises(FileNotPresent): From c4a49360882b7933cfda324db254fc9fb4f84621 Mon Sep 17 00:00:00 2001 From: Sophie <49928680+sophiecarreras@users.noreply.github.com> Date: Fri, 27 Nov 2026 07:14:33 -0300 Subject: [PATCH 109/113] test: fix progress and replication-scan test data for real B2 - test_upload_bytes_progress uploads three parts, so the listener gets an update per part on any transport. It still requires several updates ending at the total; an 11-byte body is read once over HTTP, and only RawSimulator's forced chunked reads gave it several updates. - test_scan_source: the source bucket has Object Lock (for the retention file) and the large-metadata files use 1,900 bytes of file info. That fits b2_upload_file's documented limits (7,000 bytes for name plus info, 2,048 for SSE or Object Lock buckets); the old 7,000-byte value broke both. The upload headers stay over the 2,048 bytes has_large_header measures, so every category is still checked. - Mark the two dual-acceptance error checks (governance delete, wrong SHA-1) with a TODO naming the real-B2 error to assert once --b2-simulator is the default. Co-Authored-By: Claude Opus 5.5 --- test/unit/bucket/test_bucket.py | 9 ++++++++- test/unit/file_version/test_file_version.py | 2 ++ test/unit/replication/conftest.py | 3 ++- test/unit/replication/test_monitoring.py | 16 +++++++++++++--- 4 files changed, 25 insertions(+), 5 deletions(-) diff --git a/test/unit/bucket/test_bucket.py b/test/unit/bucket/test_bucket.py index 6228d2fa9..bc75c3841 100644 --- a/test/unit/bucket/test_bucket.py +++ b/test/unit/bucket/test_bucket.py @@ -735,6 +735,8 @@ def test_delete_file_version_bypass_governance(self): # Real B2 refuses this delete with 401 access_denied (the b2_delete_file_version error # table), which the SDK raises as Unauthorized; RawSimulator raises AccessDenied. + # TODO: once --b2-simulator is the default, assert only the real-B2 error: + # Unauthorized with code 'access_denied' (401), and drop AccessDenied. with pytest.raises((AccessDenied, Unauthorized)) as refusal: self.bucket.delete_file_version(file_id, 'hello.txt') if isinstance(refusal.value, Unauthorized): @@ -2084,7 +2086,9 @@ def test_upload_bytes_cache_control(self): self.assertEqual(file_info.cache_control, 'max-age=3600') def test_upload_bytes_progress(self): - data = b'hello world' + # Three parts, so the listener gets an update per part. Over HTTP a body is read in one go, + # so a single small file reports only its total; RawSimulator's chunked reads hid that. + data = self._make_data(self.simulator.MIN_PART_SIZE * 3) progress_listener = StubProgressListener() self.bucket.upload_bytes(data, 'file1', progress_listener=progress_listener) self.assertTrue(progress_listener.is_valid()) @@ -2191,6 +2195,9 @@ def test_upload_local_wrong_sha(self): # B2 refuses the upload with 400 bad_request "Sha1 did not match data received" # (b2_upload_file), which the SDK raises as BadRequest; RawSimulator raises # FileSha1Mismatch. + # TODO: once --b2-simulator is the default, assert only the real-B2 error: BadRequest + # with code 'bad_request' and message 'Sha1 did not match data received' (400), and + # drop FileSha1Mismatch. with pytest.raises((FileSha1Mismatch, BadRequest)) as refusal: self.bucket.upload_local_file( path, diff --git a/test/unit/file_version/test_file_version.py b/test/unit/file_version/test_file_version.py index 203e79d0c..b824e7c22 100644 --- a/test/unit/file_version/test_file_version.py +++ b/test/unit/file_version/test_file_version.py @@ -171,6 +171,8 @@ def test_delete_bypass_governance(self): # Real B2 refuses this delete with 401 access_denied (the b2_delete_file_version error # table), which the SDK raises as Unauthorized; RawSimulator raises AccessDenied. + # TODO: once --b2-simulator is the default, assert only the real-B2 error: + # Unauthorized with code 'access_denied' (401), and drop AccessDenied. with pytest.raises((AccessDenied, Unauthorized)) as refusal: locked_file_version.delete() if isinstance(refusal.value, Unauthorized): diff --git a/test/unit/replication/conftest.py b/test/unit/replication/conftest.py index 6aa680bb2..f225a2552 100644 --- a/test/unit/replication/conftest.py +++ b/test/unit/replication/conftest.py @@ -25,7 +25,8 @@ def destination_bucket(b2api) -> Bucket: @pytest.fixture def source_bucket(b2api, destination_bucket) -> Bucket: - bucket = b2api.create_bucket('source-bucket', 'allPublic') + # Object Lock, so a scan test can store a file with retention (B2 refuses it elsewhere). + bucket = b2api.create_bucket('source-bucket', 'allPublic', is_file_lock_enabled=True) bucket.replication = ReplicationConfiguration( rules=[ diff --git a/test/unit/replication/test_monitoring.py b/test/unit/replication/test_monitoring.py index e559c261d..d08cdfca3 100644 --- a/test/unit/replication/test_monitoring.py +++ b/test/unit/replication/test_monitoring.py @@ -11,6 +11,7 @@ import queue import threading +import time import pytest from apiver_deps import ( @@ -32,7 +33,16 @@ key=EncryptionKey(secret=b'some_key'.ljust(32, b'.'), key_id='some-id'), ) -RETENTION_GOVERNANCE = FileRetentionSetting(RetentionMode.GOVERNANCE, retain_until=1) +# B2 refuses a retention date in the past; one day ahead outlives any test run. +RETENTION_GOVERNANCE = FileRetentionSetting( + RetentionMode.GOVERNANCE, retain_until=int(time.time() * 1000) + 24 * 60 * 60 * 1000 +) +# b2_upload_file: "The file name and file info must fit within a 7,000 byte limit", reduced to +# 2,048 bytes "for files that are uploaded with Server-Side Encryption and/or to Object +# Lock-enabled buckets" (the source bucket has Object Lock). This value keeps name + info under +# 2,048 bytes, while the whole upload header set, which ReplicationScanResult measures +# (has_large_header), is over 2,048. +LARGE_INFO_VALUE = 'a' * 1900 DEFAULT_REPLICATION_RESULT = dict( source_replication_status=None, @@ -94,14 +104,14 @@ def test_scan_source(source_bucket, test_file, monitor): test_file, 'folder/test-large-meta.txt', file_info={ - 'dummy-key': 'a' * 7000, + 'dummy-key': LARGE_INFO_VALUE, }, ), source_bucket.upload_local_file( test_file, 'folder/test-large-meta-encrypted.txt', file_info={ - 'dummy-key': 'a' * 2048, + 'dummy-key': LARGE_INFO_VALUE, }, encryption=SSE_C_AES, ), From abcf08ccf8016e3999e56d17e239981983f27d15 Mon Sep 17 00:00:00 2001 From: Felipe Fumero Date: Tue, 1 Dec 2026 12:09:37 -0600 Subject: [PATCH 110/113] fix: protect sync destinations and release worker connections (#807) * fix: protect sync destinations and release worker connections Validate temporary download paths as well as final write and deletion paths. Create temporary files exclusively so a pre-existing path cannot redirect the download, while preserving replacement, timestamps, and cleanup. Track worker SQLite connections weakly without changing profile-name validation. * test: cover sync worker checks and connection cleanup * fix: revalidate sync worker paths and finalize thread connections Repeat destination checks immediately before worker filesystem operations so queued actions reject replaced parent directories. Close thread-local SQLite connections explicitly when their holders are released, and cover timestamp preservation and final-path refusal. * test: cover renamed download cleanup and explicit connection closure * fix: retain the sync temporary directory for cleanup Create and remove temporary downloads relative to the same directory descriptor where supported so a parent rename does not strand the action file. Document that pathname-based creation and replacement still have a containment check-to-use window. * test: skip symlink regressions on Windows * fix: keep downloads working in write-only directories and pin sync guards Fall back to pathname-based creation and cleanup when the destination directory cannot be opened for reading, as for a mode 0300 directory the scanner tolerates. Add tests that pin the policy final-destination guard and the validation before replacement, and guard the descriptor-only cleanup assertion. --- .../account_info/sqlite_account_info.py | 26 ++- b2sdk/_internal/scan/folder.py | 45 +++- b2sdk/_internal/sync/action.py | 62 ++++- b2sdk/_internal/sync/policy.py | 6 +- changelog.d/806.fixed.md | 1 + .../account_info/test_sqlite_low_audit.py | 29 +++ test/unit/scan/test_folder.py | 22 +- test/unit/scan/test_folder_traversal.py | 12 +- .../unit/sync/test_regression_sync_actions.py | 214 ++++++++++++++++++ 9 files changed, 395 insertions(+), 22 deletions(-) create mode 100644 changelog.d/806.fixed.md diff --git a/b2sdk/_internal/account_info/sqlite_account_info.py b/b2sdk/_internal/account_info/sqlite_account_info.py index 35cc962e1..215596256 100644 --- a/b2sdk/_internal/account_info/sqlite_account_info.py +++ b/b2sdk/_internal/account_info/sqlite_account_info.py @@ -17,6 +17,7 @@ import stat import sys import threading +import weakref from contextlib import contextmanager from .exception import CorruptAccountInfo, MissingAccountData @@ -37,6 +38,17 @@ # meant to be a default for other applications +class _WeakrefableConnection(sqlite3.Connection): + """``sqlite3.Connection`` itself cannot be weakly referenced; a subclass can.""" + + +class _ConnectionHolder: + """Close a thread's connection when its local storage is released.""" + + def __init__(self, connection): + weakref.finalize(self, connection.close) + + class SqliteAccountInfo(UrlPoolAccountInfo): """ Store account information in an `sqlite3 `_ database which is @@ -76,7 +88,8 @@ def __init__(self, file_name=None, last_upgrade_to_run=None, profile: str | None :param int last_upgrade_to_run: For testing only, override the auto-update on the db. """ self.thread_local = threading.local() - self._connections = set() + # Thread-local holders close connections; weak tracking does not extend their lifetime. + self._connections = weakref.WeakSet() self._connections_lock = threading.Lock() self.filename = self.get_user_account_info_path(file_name=file_name, profile=profile) @@ -213,10 +226,16 @@ def _get_connection(self): connection = self._connect() self._connections.add(connection) self.thread_local.connection = connection + self.thread_local.connection_holder = _ConnectionHolder(connection) return connection def _connect(self): - return sqlite3.connect(self.filename, isolation_level='EXCLUSIVE', check_same_thread=False) + return sqlite3.connect( + self.filename, + isolation_level='EXCLUSIVE', + check_same_thread=False, + factory=_WeakrefableConnection, + ) @contextmanager def _temp_connection(self): @@ -231,11 +250,12 @@ def _temp_connection(self): def close(self): """Close cached connections after callers have finished using them.""" with self._connections_lock: - for connection in self._connections: + for connection in list(self._connections): connection.close() self._connections.clear() if hasattr(self.thread_local, 'connection'): del self.thread_local.connection + del self.thread_local.connection_holder def _create_database(self, last_upgrade_to_run): """ diff --git a/b2sdk/_internal/scan/folder.py b/b2sdk/_internal/scan/folder.py index 07fb82178..67f4c32d9 100644 --- a/b2sdk/_internal/scan/folder.py +++ b/b2sdk/_internal/scan/folder.py @@ -82,6 +82,13 @@ def make_full_path(self, file_name): :rtype: str """ + def make_write_path(self, file_name): + """ + Return the full path to a file that is about to be created, modified or deleted. + Folders where that can differ from :meth:`make_full_path` override it. + """ + return self.make_full_path(file_name) + def join_b2_path(relative_dir_path: str | Path, file_name: str): """ @@ -165,19 +172,39 @@ def make_full_path(self, file_name): # Generate the full path to the file full_path = os.path.normpath(os.path.join(self.root, file_name)) - # Resolve symlinks in both paths before checking containment. - resolved_root = os.path.realpath(self.root) - resolved_path = os.path.realpath(full_path) - try: - common_path = os.path.commonpath([resolved_path, resolved_root]) - except ValueError: # Paths on different Windows drives. - raise UnsupportedFilename('illegal file name', full_path) from None + # Lexical containment only: symlinks to targets outside the root are legitimate to scan. + self._check_contained(os.path.abspath(full_path), os.path.abspath(self.root), full_path) + + return full_path - if os.path.normcase(common_path) != os.path.normcase(resolved_root): - raise UnsupportedFilename('illegal file name', full_path) + def make_write_path(self, file_name): + """ + Like :meth:`make_full_path`, but also resolves symlinks, so a path that would be + written through a symlink pointing outside self.root is rejected. + Raise ``UnsupportedFilename`` if the path resolves outside the folder. + :param file_name: a file name + :type file_name: str + """ + full_path = self.make_full_path(file_name) + lexical_path = os.path.normpath( + os.path.join(self.root, file_name.replace('/', os.path.sep)) + ) + self._check_contained( + os.path.realpath(lexical_path), os.path.realpath(self.root), report=full_path + ) return full_path + @staticmethod + def _check_contained(path, root, report=None): + try: + common_path = os.path.commonpath([path, root]) + except ValueError: # Paths on different Windows drives. + raise UnsupportedFilename('illegal file name', report or path) from None + + if os.path.normcase(common_path) != os.path.normcase(root): + raise UnsupportedFilename('illegal file name', report or path) + def ensure_present(self): """ Make sure that the directory exists. diff --git a/b2sdk/_internal/sync/action.py b/b2sdk/_internal/sync/action.py index 363656957..adaaf257a 100644 --- a/b2sdk/_internal/sync/action.py +++ b/b2sdk/_internal/sync/action.py @@ -19,10 +19,13 @@ from ..bucket import Bucket from ..file_version import FileVersion from ..http_constants import SRC_LAST_MODIFIED_MILLIS +from ..scan.exception import UnsupportedFilename +from ..scan.folder import AbstractFolder from ..scan.path import B2Path from ..sync.report import ProgressReport, SyncReport from ..transfer.outbound.outbound_source import OutboundTransferSource from ..transfer.outbound.upload_source import UploadSourceLocalFile +from ..utils import set_file_mtime from ..utils.escape import escape_control_chars, unprintable_to_hex from .encryption_provider import AbstractSyncEncryptionSettingsProvider from .report import SyncFileReporter @@ -269,17 +272,25 @@ def __init__( b2_file_name: str, local_full_path: str, encryption_settings_provider: AbstractSyncEncryptionSettingsProvider, + destination_folder: AbstractFolder | None = None, ): """ :param source_path: the file to be downloaded :param b2_file_name: b2_file_name :param local_full_path: a local file path :param encryption_settings_provider: encryption setting provider + :param destination_folder: destination folder used to revalidate worker write paths """ self.source_path = source_path self.b2_file_name = b2_file_name self.local_full_path = local_full_path self.encryption_settings_provider = encryption_settings_provider + self.destination_folder = destination_folder + + def _validate_destination(self): + if self.destination_folder is not None: + self.destination_folder.make_write_path(self.source_path.relative_path) + self.destination_folder.make_write_path(self.source_path.relative_path + '.b2.sync.tmp') def get_bytes(self) -> int: """ @@ -297,13 +308,34 @@ def _ensure_directory_existence(self) -> None: if not os.path.isdir(parent_dir): raise Exception(f'could not create directory {parent_dir}') + @staticmethod + def _open_destination_directory(download_path: str) -> int | None: + """ + Open the download directory so creation and cleanup stay pinned to it even if it is renamed. + + Returns None where descriptors are unsupported, or where the directory cannot be opened for + reading (e.g. mode 0300, which the scanner tolerates); those use pathname-based operations. + """ + if os.open not in os.supports_dir_fd or os.unlink not in os.supports_dir_fd: + return None + try: + return os.open(os.path.dirname(download_path), os.O_RDONLY | os.O_DIRECTORY) + except PermissionError: + return None + def do_action(self, bucket: Bucket, reporter: ProgressReport) -> None: """ Perform the downloading action, returning only after the action is completed. :param bucket: a Bucket object :param reporter: a place to report errors + + Destination revalidation is not atomic with pathname-based filesystem operations. + A concurrent directory swap between a check and an operation can still redirect a write + or replacement outside the destination. Descriptor-relative, no-follow traversal from + the destination root is required to close that remaining race. """ + self._validate_destination() self._ensure_directory_existence() if reporter: @@ -318,6 +350,8 @@ def do_action(self, bucket: Bucket, reporter: ProgressReport) -> None: bucket=bucket, file_version=self.source_path.selected_version, ) + temporary_created = False + directory_fd = None try: with contextlib.ExitStack() as exit_stack: if progress_listener: @@ -327,18 +361,40 @@ def do_action(self, bucket: Bucket, reporter: ProgressReport) -> None: progress_listener=progress_listener, encryption=encryption, ) - downloaded_file.save_to(download_path) + # Exclusive creation refuses a temporary path planted after destination validation. + self._validate_destination() + directory_fd = self._open_destination_directory(download_path) + if directory_fd is not None: + opener = functools.partial(os.open, dir_fd=directory_fd) + file_context = open(os.path.basename(download_path), 'xb+', opener=opener) + else: + file_context = open(download_path, 'xb+') + with file_context as file: + temporary_created = True + downloaded_file.save(file) + self._validate_destination() + set_file_mtime(download_path, downloaded_file.download_version.mod_time_millis) # Move the file into place + self._validate_destination() os.replace(download_path, self.local_full_path) except BaseException: + if not temporary_created: + raise try: - os.unlink(download_path) + if directory_fd is not None: + os.unlink(os.path.basename(download_path), dir_fd=directory_fd) + else: + self._validate_destination() + os.unlink(download_path) except FileNotFoundError: pass - except OSError: + except (OSError, UnsupportedFilename): logger.warning('Could not remove temporary sync download', exc_info=True) raise + finally: + if directory_fd is not None: + os.close(directory_fd) def do_report(self, bucket: Bucket, reporter: ProgressReport) -> None: """ diff --git a/b2sdk/_internal/sync/policy.py b/b2sdk/_internal/sync/policy.py index 3d39bbba3..df2362f40 100644 --- a/b2sdk/_internal/sync/policy.py +++ b/b2sdk/_internal/sync/policy.py @@ -254,11 +254,13 @@ class DownPolicy(AbstractFileSyncPolicy): SOURCE_PREFIX = 'b2://' def _make_transfer_action(self): + self._dest_folder.make_write_path(self._source_path.relative_path + '.b2.sync.tmp') return B2DownloadAction( cast(B2Path, self._source_path), self._source_folder.make_full_path(self._source_path.relative_path), - self._dest_folder.make_full_path(self._source_path.relative_path), + self._dest_folder.make_write_path(self._source_path.relative_path), self._encryption_settings_provider, + destination_folder=self._dest_folder, ) @@ -340,7 +342,7 @@ def _get_hide_delete_actions(self): ): yield LocalDeleteAction( self._dest_path.relative_path, - self._dest_folder.make_full_path(self._dest_path.relative_path), + self._dest_folder.make_write_path(self._dest_path.relative_path), ) diff --git a/changelog.d/806.fixed.md b/changelog.d/806.fixed.md new file mode 100644 index 000000000..31f7129d6 --- /dev/null +++ b/changelog.d/806.fixed.md @@ -0,0 +1 @@ +Validate sync download and deletion destinations with make_write_path, refuse existing temporary download paths, and stop retaining SQLite connections from completed worker threads; an unsafe destination aborts down-sync. diff --git a/test/unit/account_info/test_sqlite_low_audit.py b/test/unit/account_info/test_sqlite_low_audit.py index 58a745c41..03b8c7b4e 100644 --- a/test/unit/account_info/test_sqlite_low_audit.py +++ b/test/unit/account_info/test_sqlite_low_audit.py @@ -7,9 +7,12 @@ # License https://www.backblaze.com/using_b2_code.html # ###################################################################### +import gc import os +import sqlite3 import stat import threading +import warnings import pytest from apiver_deps import SqliteAccountInfo @@ -96,3 +99,29 @@ def worker(): assert len({id(conn) for conn in connections}) == 3 assert outcomes == ['ProgrammingError'] * 3 info.close() + + +def _open_thread_connection(info, connections): + connections.append(info._get_connection()) + + +def test_dead_thread_connections_are_not_retained(tmp_path): + gc.collect() + info = SqliteAccountInfo(file_name=str(tmp_path / 'account.sqlite')) + connections = [] + try: + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter('always', ResourceWarning) + for _ in range(20): + thread = threading.Thread(target=_open_thread_connection, args=(info, connections)) + thread.start() + thread.join(10) + assert not thread.is_alive() + gc.collect() + assert not [warning for warning in caught if issubclass(warning.category, ResourceWarning)] + assert len(connections) == 20 + for connection in connections: + with pytest.raises(sqlite3.ProgrammingError, match='closed'): + connection.execute('select 1') + finally: + info.close() diff --git a/test/unit/scan/test_folder.py b/test/unit/scan/test_folder.py index ae1619e6b..76c522860 100644 --- a/test/unit/scan/test_folder.py +++ b/test/unit/scan/test_folder.py @@ -53,7 +53,7 @@ def test_make_full_path_invalid_prefix( platform.system() == 'Windows' and platform.python_implementation() == 'PyPy', reason='Symlinks not supported on PyPy/Windows', ) -def test_make_full_path_rejects_symlink_outside_root(tmp_path): +def test_make_write_path_rejects_symlink_outside_root(tmp_path): root = tmp_path / 'root' root.mkdir() outside = tmp_path / 'outside' @@ -61,11 +61,29 @@ def test_make_full_path_rejects_symlink_outside_root(tmp_path): (root / 'link').symlink_to(outside, target_is_directory=True) with pytest.raises(UnsupportedFilename): - LocalFolder(root).make_full_path('link/new-file.txt') + LocalFolder(root).make_write_path('link/new-file.txt') assert not (outside / 'new-file.txt').exists() +@pytest.mark.skipif( + platform.system() == 'Windows' and platform.python_implementation() == 'PyPy', + reason='Symlinks not supported on PyPy/Windows', +) +def test_scan_does_not_abort_on_symlink_outside_root(tmp_path): + root = tmp_path / 'root' + root.mkdir() + outside = tmp_path / 'outside' + outside.mkdir() + (outside / 'a.txt').write_text('a') + (root / 'link').symlink_to(outside, target_is_directory=True) + (root / 'file-link.txt').symlink_to(outside / 'a.txt') + + files = list(LocalFolder(root).all_files(None)) + + assert [f.relative_path for f in files] == ['file-link.txt', 'link/a.txt'] + + @pytest.mark.skipif( platform.system() == 'Windows' and platform.python_implementation() == 'PyPy', reason='Symlinks not supported on PyPy/Windows', diff --git a/test/unit/scan/test_folder_traversal.py b/test/unit/scan/test_folder_traversal.py index 26c3efae0..c00c02988 100644 --- a/test/unit/scan/test_folder_traversal.py +++ b/test/unit/scan/test_folder_traversal.py @@ -20,7 +20,6 @@ import pytest -from b2sdk._internal.scan.exception import UnsupportedFilename from b2sdk._internal.scan.folder import LocalFolder from b2sdk._internal.scan.policies import ScanPoliciesManager from b2sdk._internal.scan.report import ProgressReport @@ -288,8 +287,15 @@ def test_folder_with_symlink_to_parent(self, tmp_path): folder = LocalFolder(str(tmp_path / 'parent' / 'child')) - with pytest.raises(UnsupportedFilename, match='illegal file name'): - list(folder.all_files(reporter=MagicMock())) + # The link leaves the root but is scanned; the visited-symlink check stops the loop. + files = [f.relative_path for f in folder.all_files(reporter=MagicMock())] + assert files == [ + 'file4.txt', + 'grandchild/file5.txt', + 'grandchild/symlink_dir/child/file4.txt', + 'grandchild/symlink_dir/child/grandchild/file5.txt', + 'grandchild/symlink_dir/file3.txt', + ] @pytest.mark.skipif( platform.system() == 'Windows' and platform.python_implementation() == 'PyPy', diff --git a/test/unit/sync/test_regression_sync_actions.py b/test/unit/sync/test_regression_sync_actions.py index d21e364fb..d40106b59 100644 --- a/test/unit/sync/test_regression_sync_actions.py +++ b/test/unit/sync/test_regression_sync_actions.py @@ -19,6 +19,8 @@ from __future__ import annotations import os +import platform +from functools import partial from unittest import mock import pytest @@ -170,3 +172,215 @@ def test_c24_copy_message_escapes_control_characters(self): action.do_report(mock.Mock(), reporter) printed = reporter.print_completion.call_args[0][0] assert printed == r"copy 'dir/evil\x1b[31mname'" + + +class TestSyncDestinationContainment: + def test_download_preserves_source_mtime(self, api_and_bucket, tmp_path): + _, bucket = api_and_bucket + version = bucket.upload_bytes( + b'content', 'a', file_info={'src_last_modified_millis': str(REMOTE_MTIME_MILLIS)} + ) + target = tmp_path / 'a' + _download_action(bucket, version, target).do_action(bucket, None) + assert target.read_bytes() == b'content' + assert round(target.stat().st_mtime * 1000) == REMOTE_MTIME_MILLIS + + @staticmethod + def _swap_parent(subdir, outside): + subdir.rename(subdir.with_name('original-subdir')) + subdir.symlink_to(outside, target_is_directory=True) + + def _save_and_swap(self, save, subdir, outside, file): + save(file) + self._swap_parent(subdir, outside) + + @pytest.mark.skipif(platform.system() == 'Windows', reason='requires symlink support') + @pytest.mark.parametrize('swap_at', ['before_worker', 'before_open', 'after_save']) + @pytest.mark.parametrize('remote_name', ['subdir/a', 'subdir/new/a']) + def test_worker_rechecks_swapped_parent(self, api_and_bucket, tmp_path, swap_at, remote_name): + from b2sdk.v3 import B2Folder, LocalFolder, Synchronizer + from b2sdk.v3.exception import UnsupportedFilename + + _, bucket = api_and_bucket + bucket.upload_bytes(b'replacement', remote_name) + root = tmp_path / 'root' + subdir = root / 'subdir' + subdir.mkdir(parents=True) + outside = tmp_path / 'outside' + outside.mkdir() + protected = outside / 'a' + protected.write_bytes(b'original outside content') + actions = list( + Synchronizer(max_workers=1)._make_folder_sync_actions( + B2Folder(bucket.name, '', bucket.api), + LocalFolder(str(root)), + now_millis=2_000_000_000_000, + reporter=mock.MagicMock(), + ) + ) + assert len(actions) == 1 + action = actions[0] + with mock.patch.object( + action, '_ensure_directory_existence', wraps=action._ensure_directory_existence + ) as ensure: + if swap_at == 'before_worker': + self._swap_parent(subdir, outside) + elif swap_at == 'before_open': + ensure.side_effect = partial(self._swap_parent, subdir, outside) + if swap_at == 'after_save': + downloaded = bucket.download_file_by_id(action.source_path.selected_version.id_) + with mock.patch.object( + bucket, 'download_file_by_id', return_value=downloaded + ), mock.patch.object( + downloaded, + 'save', + side_effect=partial(self._save_and_swap, downloaded.save, subdir, outside), + ): + with pytest.raises(UnsupportedFilename): + action.do_action(bucket, None) + else: + with pytest.raises(UnsupportedFilename): + action.do_action(bucket, None) + assert protected.read_bytes() == b'original outside content' + assert not (outside / 'a.b2.sync.tmp').exists() + assert {path.name for path in outside.iterdir()} == {'a'} + # Only descriptor-pinned cleanup can reach the renamed directory; pathname cleanup refuses. + if ( + swap_at == 'after_save' + and os.open in os.supports_dir_fd + and os.unlink in os.supports_dir_fd + ): + assert not list((root / 'original-subdir').rglob('*.b2.sync.tmp')) + + @pytest.mark.skipif(platform.system() == 'Windows', reason='requires POSIX permissions') + @pytest.mark.skipif( + hasattr(os, 'geteuid') and os.geteuid() == 0, reason='root ignores directory permissions' + ) + def test_download_into_unreadable_directory_succeeds(self, api_and_bucket, tmp_path): + # The scanner tolerates a write-only directory (chmod 0300), so the download must too. + _, bucket = api_and_bucket + version = bucket.upload_bytes(b'content', 'drop/a') + drop = tmp_path / 'root' / 'drop' + drop.mkdir(parents=True) + drop.chmod(0o300) + try: + _download_action(bucket, version, drop / 'a').do_action(bucket, None) + finally: + drop.chmod(0o700) + assert (drop / 'a').read_bytes() == b'content' + assert not (drop / 'a.b2.sync.tmp').exists() + + @pytest.mark.skipif(platform.system() == 'Windows', reason='requires symlink support') + def test_parent_swapped_after_mtime_is_refused_before_replace(self, api_and_bucket, tmp_path): + from b2sdk._internal.sync import action as action_module + from b2sdk.v3 import LocalFolder + from b2sdk.v3.exception import UnsupportedFilename + + _, bucket = api_and_bucket + version = bucket.upload_bytes(b'replacement', 'subdir/a') + root = tmp_path / 'root' + subdir = root / 'subdir' + subdir.mkdir(parents=True) + outside = tmp_path / 'outside' + outside.mkdir() + real_set_file_mtime = action_module.set_file_mtime + + def set_mtime_then_swap(path, millis): + real_set_file_mtime(path, millis) + self._swap_parent(subdir, outside) + + action = B2DownloadAction( + B2Path(version.file_name, version, [version]), + version.file_name, + str(subdir / 'a'), + ServerDefaultSyncEncryptionSettingsProvider(), + destination_folder=LocalFolder(str(root)), + ) + with mock.patch.object(action_module, 'set_file_mtime', set_mtime_then_swap): + with pytest.raises(UnsupportedFilename): + action.do_action(bucket, None) + assert list(outside.iterdir()) == [] + + @pytest.mark.skipif(platform.system() == 'Windows', reason='requires symlink support') + def test_policy_rejects_final_path_escaping_through_symlink(self, tmp_path): + # Isolates the policy guard: the temporary path stays inside the root, the final one escapes. + from b2sdk._internal.sync.policy import DownPolicy + from b2sdk.v3 import LocalFolder + from b2sdk.v3.exception import UnsupportedFilename + + root = tmp_path / 'root' + root.mkdir() + outside_file = tmp_path / 'outside' + outside_file.write_bytes(b'original outside content') + (root / 'a').symlink_to(outside_file) + policy = DownPolicy.__new__(DownPolicy) + policy._dest_folder = LocalFolder(str(root)) + policy._source_folder = mock.MagicMock() + policy._source_path = mock.MagicMock(relative_path='a') + policy._encryption_settings_provider = ServerDefaultSyncEncryptionSettingsProvider() + with pytest.raises(UnsupportedFilename): + policy._make_transfer_action() + assert outside_file.read_bytes() == b'original outside content' + + @pytest.mark.skipif(platform.system() == 'Windows', reason='requires symlink support') + def test_download_action_refuses_existing_temporary_symlink(self, api_and_bucket, tmp_path): + _, bucket = api_and_bucket + version = bucket.upload_bytes(b'replacement', 'a') + protected = tmp_path / 'outside' + protected.write_bytes(b'original outside content') + root = tmp_path / 'root' + root.mkdir() + temporary = root / 'a.b2.sync.tmp' + temporary.symlink_to(protected) + with pytest.raises(FileExistsError): + _download_action(bucket, version, root / 'a').do_action(bucket, None) + assert protected.read_bytes() == b'original outside content' + assert temporary.is_symlink() + assert not (root / 'a').exists() + + @pytest.mark.skipif(platform.system() == 'Windows', reason='requires symlink support') + @pytest.mark.parametrize('operation', ['write', 'delete', 'temporary_write', 'final_write']) + def test_outside_destination_is_refused(self, api_and_bucket, tmp_path, operation): + from b2sdk.v3 import ( + B2Folder, + KeepOrDeleteMode, + LocalFolder, + NewerFileSyncMode, + Synchronizer, + ) + from b2sdk.v3.exception import UnsupportedFilename + + _, bucket = api_and_bucket + root = tmp_path / 'root' + root.mkdir() + outside = tmp_path / 'outside' + outside.mkdir() + protected = outside / 'a' + protected.write_bytes(b'original outside content') + if operation == 'final_write': + (root / 'a').symlink_to(protected) + remote_name = 'a' + elif operation == 'temporary_write': + (root / 'a.b2.sync.tmp').symlink_to(protected) + remote_name = 'a' + else: + (root / 'link').symlink_to(outside, target_is_directory=True) + remote_name = 'link/a' + if operation != 'delete': + bucket.upload_bytes(b'replacement', remote_name) + synchronizer = Synchronizer( + max_workers=1, + allow_empty_source=True, + newer_file_mode=NewerFileSyncMode.REPLACE, + keep_days_or_delete=( + KeepOrDeleteMode.DELETE if operation == 'delete' else KeepOrDeleteMode.NO_DELETE + ), + ) + with pytest.raises(UnsupportedFilename): + synchronizer.sync_folders( + B2Folder(bucket.name, '', bucket.api), + LocalFolder(str(root)), + now_millis=2_000_000_000_000, + reporter=mock.MagicMock(), + ) + assert protected.read_bytes() == b'original outside content' From de4bb934e3b2244e42638bd1801ed1f8f9266234 Mon Sep 17 00:00:00 2001 From: Felipe Fumero Date: Tue, 1 Dec 2026 12:50:30 -0600 Subject: [PATCH 111/113] fix: create sync downloads with the usual file permissions (#810) An opener passed to open() is called without a mode, so os.open defaulted to 0o777 and downloaded files became executable. Pass 0o666 so the umask yields the same mode as before. --- b2sdk/_internal/sync/action.py | 3 ++- changelog.d/809.fixed.md | 1 + .../unit/sync/test_regression_sync_actions.py | 24 +++++++++++++++++++ 3 files changed, 27 insertions(+), 1 deletion(-) create mode 100644 changelog.d/809.fixed.md diff --git a/b2sdk/_internal/sync/action.py b/b2sdk/_internal/sync/action.py index adaaf257a..4f6f11d1f 100644 --- a/b2sdk/_internal/sync/action.py +++ b/b2sdk/_internal/sync/action.py @@ -365,7 +365,8 @@ def do_action(self, bucket: Bucket, reporter: ProgressReport) -> None: self._validate_destination() directory_fd = self._open_destination_directory(download_path) if directory_fd is not None: - opener = functools.partial(os.open, dir_fd=directory_fd) + # open() calls an opener without a mode, and os.open then defaults to 0o777. + opener = functools.partial(os.open, mode=0o666, dir_fd=directory_fd) file_context = open(os.path.basename(download_path), 'xb+', opener=opener) else: file_context = open(download_path, 'xb+') diff --git a/changelog.d/809.fixed.md b/changelog.d/809.fixed.md new file mode 100644 index 000000000..2e3c088e7 --- /dev/null +++ b/changelog.d/809.fixed.md @@ -0,0 +1 @@ +Create files downloaded by sync with the usual permissions (0o666 filtered by the umask) instead of making them executable on POSIX platforms. diff --git a/test/unit/sync/test_regression_sync_actions.py b/test/unit/sync/test_regression_sync_actions.py index d40106b59..fa62a4ab9 100644 --- a/test/unit/sync/test_regression_sync_actions.py +++ b/test/unit/sync/test_regression_sync_actions.py @@ -20,6 +20,7 @@ import os import platform +import stat from functools import partial from unittest import mock @@ -252,6 +253,29 @@ def test_worker_rechecks_swapped_parent(self, api_and_bucket, tmp_path, swap_at, ): assert not list((root / 'original-subdir').rglob('*.b2.sync.tmp')) + @pytest.mark.skipif(platform.system() == 'Windows', reason='requires POSIX permissions') + @pytest.mark.parametrize('pinned_directory', [True, False]) + def test_download_file_mode_follows_umask(self, api_and_bucket, tmp_path, pinned_directory): + # A custom opener passed to open() defaults to mode 0o777, which would make every + # downloaded file executable; the file must get 0o666 filtered by the umask instead. + _, bucket = api_and_bucket + version = bucket.upload_bytes(b'content', 'a') + target = tmp_path / 'a' + action = _download_action(bucket, version, target) + previous_umask = os.umask(0o022) + try: + if pinned_directory: + action.do_action(bucket, None) + else: + with mock.patch.object( + B2DownloadAction, '_open_destination_directory', return_value=None + ): + action.do_action(bucket, None) + finally: + os.umask(previous_umask) + assert target.read_bytes() == b'content' + assert stat.S_IMODE(target.stat().st_mode) == 0o644 + @pytest.mark.skipif(platform.system() == 'Windows', reason='requires POSIX permissions') @pytest.mark.skipif( hasattr(os, 'geteuid') and os.geteuid() == 0, reason='root ignores directory permissions' From 35a59562d5fde79cacccd58e2877de8dd23c327d Mon Sep 17 00:00:00 2001 From: Felipe Fumero Date: Tue, 1 Dec 2026 13:27:56 -0600 Subject: [PATCH 112/113] docs: state that LocalFolder.make_full_path checks containment lexically (#812) The docstring promised that the path is not outside the root, but symlinks are not resolved. Point to make_write_path for paths that are written or deleted. --- b2sdk/_internal/scan/folder.py | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/b2sdk/_internal/scan/folder.py b/b2sdk/_internal/scan/folder.py index 67f4c32d9..93480869e 100644 --- a/b2sdk/_internal/scan/folder.py +++ b/b2sdk/_internal/scan/folder.py @@ -161,7 +161,11 @@ def all_files( def make_full_path(self, file_name): """ - Convert a file name into an absolute path, ensure it is not outside self.root + Convert a file name into an absolute path and check, lexically, that it is inside self.root. + + Symlinks are not resolved, so a symlink inside self.root may point to a location outside + it; use :meth:`make_write_path` for a path that will be written or deleted. + Raise ``UnsupportedFilename`` if the normalized path is outside self.root. :param file_name: a file name :type file_name: str From a9673282e01ff47d9d853b71577d3bd5e2ebe065 Mon Sep 17 00:00:00 2001 From: Felipe Fumero Date: Wed, 2 Dec 2026 09:14:57 -0600 Subject: [PATCH 113/113] release 2.13.6 (#800) --- CHANGELOG.md | 114 ++++++++++++++++++ changelog.d/+account-info-guide.doc.md | 1 - changelog.d/+agents-md.doc.md | 1 - .../+b2-simulator-unit-g1.infrastructure.md | 1 - ...2-simulator-unit-harness.infrastructure.md | 1 - changelog.d/+bucket-delete-cache.fixed.md | 1 - changelog.d/+c28-bucket-assert.fixed.md | 1 - changelog.d/+c31-pydantic-version.fixed.md | 1 - changelog.d/+c33-upload-part-size.fixed.md | 1 - changelog.d/+c51-http-error-args.fixed.md | 1 - changelog.d/+c55-auth-session.fixed.md | 1 - .../+chained-stream-read-none.fixed.md | 1 - ...ndor-third-party-actions.infrastructure.md | 1 - changelog.d/+concurrent-upload-error.fixed.md | 1 - .../+copy-header-content-type.fixed.md | 1 - ...xamples-and-filter-tests.infrastructure.md | 1 - .../+downloaded-file-double-save.fixed.md | 1 - .../+draft-ci-no-live.infrastructure.md | 1 - changelog.d/+errors-and-retries-guide.doc.md | 1 - changelog.d/+fix-doubled-words.doc.md | 1 - ...olved-known-defect-tests.infrastructure.md | 1 - changelog.d/+http-date-locale.fixed.md | 1 - changelog.d/+installation-support-docs.doc.md | 1 - .../+instructions-check.infrastructure.md | 1 - changelog.d/+interface-boundary.doc.md | 1 - .../+junit-review-errors.infrastructure.md | 1 - .../+junit-subtest-counts.infrastructure.md | 1 - .../+large-upload-custom-timestamp.fixed.md | 1 - ...+legacy-content-encoding-download.fixed.md | 1 - changelog.d/+live-ci-opt-in.infrastructure.md | 1 - changelog.d/+ls-exact-name-filter.fixed.md | 1 - .../+non-idempotent-create-retries.fixed.md | 1 - .../+notification-rule-iterables.fixed.md | 1 - ...-rules-nonexposure-tests.infrastructure.md | 1 - .../+outbound-timeout-tests.infrastructure.md | 1 - .../+parsing_retry_coverage.infrastructure.md | 1 - changelog.d/+path-validation.fixed.md | 1 - ...sed-known-defect-imports.infrastructure.md | 1 - .../+range-read-negative-size.fixed.md | 1 - .../+reauthorization-upload-pools.fixed.md | 1 - ...ion-bucket-unused-import.infrastructure.md | 1 - ...sion-tests-known-defects.infrastructure.md | 1 - .../+release-ci-safety.infrastructure.md | 1 - ...e-stale-c4-demonstrators.infrastructure.md | 1 - .../+request-encryption-retention.fixed.md | 1 - ...resolved-doc-regressions.infrastructure.md | 1 - changelog.d/+resume-settings.fixed.md | 1 - changelog.d/+retry-after-bounds.fixed.md | 1 - .../+security-policy.infrastructure.md | 1 - ...+simulator-encryption-check-reset.fixed.md | 1 - ...ulator-pr-weekly-live-b2.infrastructure.md | 1 - .../+sqlite-account-info-safety.fixed.md | 1 - .../+stream-range-unknown-length.fixed.md | 1 - ...eaming_boundary_coverage.infrastructure.md | 1 - changelog.d/+style-advanced-continued.doc.md | 1 - changelog.d/+style-advanced-sse.doc.md | 1 - ...+style-install-quick-start-tutorial.doc.md | 1 - ...plication-api-types-glossary-readme.doc.md | 1 - changelog.d/+symlink-device-inode.fixed.md | 1 - changelog.d/+sync-finalization.fixed.md | 1 - .../+sync-folder-prefix-and-shutdown.fixed.md | 1 - .../+sync-replacement-cleanup.fixed.md | 1 - changelog.d/+transfer-audit.fixed.md | 1 - changelog.d/+unauthorized-subclass.fixed.md | 1 - changelog.d/+upload-source-safety.fixed.md | 1 - changelog.d/+v0-unhide-file.fixed.md | 1 - changelog.d/+verify-skill.infrastructure.md | 1 - .../+version-metadata-fallback.fixed.md | 1 - ...symlink-path-expectation.infrastructure.md | 1 - ...indows-symlink-path-test.infrastructure.md | 1 - ...windows-symlink-samefile.infrastructure.md | 1 - changelog.d/232.fixed.md | 1 - changelog.d/584.doc.md | 1 - changelog.d/585.doc.md | 1 - changelog.d/586.doc.md | 1 - changelog.d/588.doc.md | 1 - changelog.d/589.doc.md | 1 - changelog.d/590.doc.md | 1 - changelog.d/591.doc.md | 1 - changelog.d/592.doc.md | 1 - changelog.d/593.doc.md | 1 - changelog.d/595.doc.md | 1 - changelog.d/599.doc.md | 1 - changelog.d/601.doc.md | 1 - changelog.d/631.fixed.md | 1 - changelog.d/654.fixed.md | 1 - changelog.d/736.fixed.md | 1 - changelog.d/741.doc.md | 1 - changelog.d/742.doc.md | 1 - changelog.d/743.doc.md | 1 - changelog.d/744.doc.md | 1 - changelog.d/745.doc.md | 1 - changelog.d/746.doc.md | 1 - changelog.d/763.doc.md | 1 - changelog.d/764.doc.md | 1 - changelog.d/780.doc.md | 1 - changelog.d/782.doc.md | 1 - changelog.d/783.doc.md | 1 - changelog.d/785.doc.md | 1 - changelog.d/803.fixed.md | 1 - changelog.d/806.fixed.md | 1 - changelog.d/809.fixed.md | 1 - 102 files changed, 114 insertions(+), 101 deletions(-) delete mode 100644 changelog.d/+account-info-guide.doc.md delete mode 100644 changelog.d/+agents-md.doc.md delete mode 100644 changelog.d/+b2-simulator-unit-g1.infrastructure.md delete mode 100644 changelog.d/+b2-simulator-unit-harness.infrastructure.md delete mode 100644 changelog.d/+bucket-delete-cache.fixed.md delete mode 100644 changelog.d/+c28-bucket-assert.fixed.md delete mode 100644 changelog.d/+c31-pydantic-version.fixed.md delete mode 100644 changelog.d/+c33-upload-part-size.fixed.md delete mode 100644 changelog.d/+c51-http-error-args.fixed.md delete mode 100644 changelog.d/+c55-auth-session.fixed.md delete mode 100644 changelog.d/+chained-stream-read-none.fixed.md delete mode 100644 changelog.d/+ci-vendor-third-party-actions.infrastructure.md delete mode 100644 changelog.d/+concurrent-upload-error.fixed.md delete mode 100644 changelog.d/+copy-header-content-type.fixed.md delete mode 100644 changelog.d/+doc-examples-and-filter-tests.infrastructure.md delete mode 100644 changelog.d/+downloaded-file-double-save.fixed.md delete mode 100644 changelog.d/+draft-ci-no-live.infrastructure.md delete mode 100644 changelog.d/+errors-and-retries-guide.doc.md delete mode 100644 changelog.d/+fix-doubled-words.doc.md delete mode 100644 changelog.d/+flip-resolved-known-defect-tests.infrastructure.md delete mode 100644 changelog.d/+http-date-locale.fixed.md delete mode 100644 changelog.d/+installation-support-docs.doc.md delete mode 100644 changelog.d/+instructions-check.infrastructure.md delete mode 100644 changelog.d/+interface-boundary.doc.md delete mode 100644 changelog.d/+junit-review-errors.infrastructure.md delete mode 100644 changelog.d/+junit-subtest-counts.infrastructure.md delete mode 100644 changelog.d/+large-upload-custom-timestamp.fixed.md delete mode 100644 changelog.d/+legacy-content-encoding-download.fixed.md delete mode 100644 changelog.d/+live-ci-opt-in.infrastructure.md delete mode 100644 changelog.d/+ls-exact-name-filter.fixed.md delete mode 100644 changelog.d/+non-idempotent-create-retries.fixed.md delete mode 100644 changelog.d/+notification-rule-iterables.fixed.md delete mode 100644 changelog.d/+notification-rules-nonexposure-tests.infrastructure.md delete mode 100644 changelog.d/+outbound-timeout-tests.infrastructure.md delete mode 100644 changelog.d/+parsing_retry_coverage.infrastructure.md delete mode 100644 changelog.d/+path-validation.fixed.md delete mode 100644 changelog.d/+prune-unused-known-defect-imports.infrastructure.md delete mode 100644 changelog.d/+range-read-negative-size.fixed.md delete mode 100644 changelog.d/+reauthorization-upload-pools.fixed.md delete mode 100644 changelog.d/+regression-bucket-unused-import.infrastructure.md delete mode 100644 changelog.d/+regression-tests-known-defects.infrastructure.md delete mode 100644 changelog.d/+release-ci-safety.infrastructure.md delete mode 100644 changelog.d/+remove-stale-c4-demonstrators.infrastructure.md delete mode 100644 changelog.d/+request-encryption-retention.fixed.md delete mode 100644 changelog.d/+resolved-doc-regressions.infrastructure.md delete mode 100644 changelog.d/+resume-settings.fixed.md delete mode 100644 changelog.d/+retry-after-bounds.fixed.md delete mode 100644 changelog.d/+security-policy.infrastructure.md delete mode 100644 changelog.d/+simulator-encryption-check-reset.fixed.md delete mode 100644 changelog.d/+simulator-pr-weekly-live-b2.infrastructure.md delete mode 100644 changelog.d/+sqlite-account-info-safety.fixed.md delete mode 100644 changelog.d/+stream-range-unknown-length.fixed.md delete mode 100644 changelog.d/+streaming_boundary_coverage.infrastructure.md delete mode 100644 changelog.d/+style-advanced-continued.doc.md delete mode 100644 changelog.d/+style-advanced-sse.doc.md delete mode 100644 changelog.d/+style-install-quick-start-tutorial.doc.md delete mode 100644 changelog.d/+style-replication-api-types-glossary-readme.doc.md delete mode 100644 changelog.d/+symlink-device-inode.fixed.md delete mode 100644 changelog.d/+sync-finalization.fixed.md delete mode 100644 changelog.d/+sync-folder-prefix-and-shutdown.fixed.md delete mode 100644 changelog.d/+sync-replacement-cleanup.fixed.md delete mode 100644 changelog.d/+transfer-audit.fixed.md delete mode 100644 changelog.d/+unauthorized-subclass.fixed.md delete mode 100644 changelog.d/+upload-source-safety.fixed.md delete mode 100644 changelog.d/+v0-unhide-file.fixed.md delete mode 100644 changelog.d/+verify-skill.infrastructure.md delete mode 100644 changelog.d/+version-metadata-fallback.fixed.md delete mode 100644 changelog.d/+windows-symlink-path-expectation.infrastructure.md delete mode 100644 changelog.d/+windows-symlink-path-test.infrastructure.md delete mode 100644 changelog.d/+windows-symlink-samefile.infrastructure.md delete mode 100644 changelog.d/232.fixed.md delete mode 100644 changelog.d/584.doc.md delete mode 100644 changelog.d/585.doc.md delete mode 100644 changelog.d/586.doc.md delete mode 100644 changelog.d/588.doc.md delete mode 100644 changelog.d/589.doc.md delete mode 100644 changelog.d/590.doc.md delete mode 100644 changelog.d/591.doc.md delete mode 100644 changelog.d/592.doc.md delete mode 100644 changelog.d/593.doc.md delete mode 100644 changelog.d/595.doc.md delete mode 100644 changelog.d/599.doc.md delete mode 100644 changelog.d/601.doc.md delete mode 100644 changelog.d/631.fixed.md delete mode 100644 changelog.d/654.fixed.md delete mode 100644 changelog.d/736.fixed.md delete mode 100644 changelog.d/741.doc.md delete mode 100644 changelog.d/742.doc.md delete mode 100644 changelog.d/743.doc.md delete mode 100644 changelog.d/744.doc.md delete mode 100644 changelog.d/745.doc.md delete mode 100644 changelog.d/746.doc.md delete mode 100644 changelog.d/763.doc.md delete mode 100644 changelog.d/764.doc.md delete mode 100644 changelog.d/780.doc.md delete mode 100644 changelog.d/782.doc.md delete mode 100644 changelog.d/783.doc.md delete mode 100644 changelog.d/785.doc.md delete mode 100644 changelog.d/803.fixed.md delete mode 100644 changelog.d/806.fixed.md delete mode 100644 changelog.d/809.fixed.md diff --git a/CHANGELOG.md b/CHANGELOG.md index c2695caeb..e33a97102 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,120 @@ upcoming release can be found in [changelog.d](changelog.d). +## [2.13.6](https://github.com/Backblaze/b2-sdk-python/releases/tag/v2.13.6) - 2026-12-01 + + +### Fixed + +- Serialize account database schema migrations so concurrent SDK instances do not apply the same upgrade twice. ([#232](https://github.com/Backblaze/b2-sdk-python/issues/232)) +- Escape control characters in the remote file name printed when a sync action fails. ([#631](https://github.com/Backblaze/b2-sdk-python/issues/631)) +- Stream hashing now continues reading until the requested length or the true end of data. Previously a source that returned a short read before EOF could produce a checksum and length covering only a prefix, allowing a truncated body to be uploaded with a matching hash. ([#654](https://github.com/Backblaze/b2-sdk-python/issues/654)) +- Preserve destination-only paths during sync deletion when excluded by name or directory, or when any B2 version is excluded by a time policy. ([#736](https://github.com/Backblaze/b2-sdk-python/issues/736)) +- Accept profile names containing a dot (e.g. `work.prod`) again; they were rejected after profile names started being validated against the whole string. Path separators and names made only of dots remain rejected. ([#803](https://github.com/Backblaze/b2-sdk-python/issues/803)) +- Validate sync download and deletion destinations with make_write_path, refuse existing temporary download paths, and stop retaining SQLite connections from completed worker threads; an unsafe destination aborts down-sync. ([#806](https://github.com/Backblaze/b2-sdk-python/issues/806)) +- Create files downloaded by sync with the usual permissions (0o666 filtered by the umask) instead of making them executable on POSIX platforms. ([#809](https://github.com/Backblaze/b2-sdk-python/issues/809)) +- Accept matching percent-encoded SSE-C key identifiers in upload metadata without double encoding, while rejecting conflicting identifiers. Add request, encryption and Object Lock unit tests across the supported SDK interfaces. +- Allow notification rules to be supplied as any iterable. +- Allow stream range uploads with an unspecified length to read and calculate their size. +- Allow the v0 bucket interface to unhide files. +- Allow v0 and v1 clients to download files stored with a Content-Encoding. +- Avoid replaying create-style JSON API calls after response timeouts, connection loss, or 5xx responses, including 503. Unlike the general [503 retry guidance](https://www.backblaze.com/docs/cloud-storage-integration-checklist), an uncertain create outcome is surfaced so callers can check server state before trying again. Replayable operations retain their retry policy; rate limits and proven connection-establishment failures are still retried. +- Bound server-provided retry delays to between zero and five minutes. +- Clear cached bucket names after deleting a bucket. +- Compare the Pydantic major version numerically when detecting optional validation support. +- Fix folder scans when an object has the same name as the source folder, preserving exact-object listing behavior. Ensure sync waits for queued actions to finish before returning a scheduling error. +- Fix importing vendored or uninstalled copies of the SDK by using a fallback version when package metadata is unavailable. +- Fix reading a chained stream when the size is omitted or None. +- Fixed custom upload timestamps for multipart uploads and their resumption. +- Fixed incorrect symlink loop detection when directories on different devices have the same inode number. +- Fixed locale-dependent formatting of HTTP expiration dates. +- Fixed sync download finalization and escaped control characters in sync completion messages. +- Honor filters when listing an exact file name. +- Map connection errors with missing exception arguments to B2 connection errors without raising IndexError. +- Preserve destination versions when a sync replacement transfer fails. +- Preserve existing credentials and bucket caches when authorization is rejected because a restricted bucket no longer exists. +- Preserve the source content type when copying with header overrides and avoid inheriting an incorrect checksum for ranged copies. +- Protect new account configuration directories, validate profile names, and close cached SQLite connections across threads. +- Protect upload data in representations, close checksum streams, and validate local file range offsets. +- Raise a clear error when saving a consumed download again, before modifying the destination. +- Reading a range stream with a negative size no longer returns bytes past the end of the configured range. +- Refresh pooled upload URLs when the authorization key changes, including when uploads or upload URL requests are in progress. +- Reject incorrect upload checksums under Python optimization, cancel pending multipart work after a part fails, and avoid copying unbound upload buffers. +- Reject local paths that fall outside the sync root, Windows device names and streams, and ASCII control characters in file names. Paths that a sync writes or deletes are also refused when they resolve through a symlink to a location outside the sync root; scanning still follows symlinks. +- Reject manually continuing an unfinished large file when an explicitly requested encryption, retention, or legal-hold setting differs from the unfinished file. Omitted settings are not compared. +- Restore the raw simulator encryption-check flag after an exception inside `dont_check_encryption`, so later simulator checks are not left disabled (affects the test model only). +- Show the returned bucket name in the assertion message when bucket creation returns a different name. +- Simplify and clarify the error messages raised for concurrent-upload responses. +- The session no longer turns `EmailNotVerified` and `NoPaymentHistory` into a plain `Unauthorized`, so uploads fail right away instead of being retried. +- Treat Bucket.upload min_part_size as a lower limit while retaining the account recommended upload part size. + +### Doc + +- Fix the Quick Start examples to match the public `b2sdk.v3` interface: `EncryptionSetting` rather than `EncryptionSettings`, `EncryptionKey(key_id=...)` rather than `id=`, both required mappings for `BasicSyncEncryptionSettingsProvider`, and `file_info=` rather than `file_infos=`. ([#584](https://github.com/Backblaze/b2-sdk-python/issues/584)) +- Use `update_file_retention` instead of `update_file_legal_hold` in the Quick Start file-lock examples that pass a `FileRetentionSetting`. ([#585](https://github.com/Backblaze/b2-sdk-python/issues/585)) +- Fix the Advanced usage patterns guide to reference `UploadSourceLocalFile` rather than the nonexistent `LocalUploadSource`, and to call `bucket.create_file` rather than an undefined `planner` object. ([#586](https://github.com/Backblaze/b2-sdk-python/issues/586)) +- Remove the nonexistent `deploy` Nox session from the Contributors Guide and describe how releases are actually published by the Continuous Delivery workflow. ([#588](https://github.com/Backblaze/b2-sdk-python/issues/588)) +- Correct the stale CI test matrix description in the contributor guides, which claimed eight Python versions instead of the currently supported set. ([#589](https://github.com/Backblaze/b2-sdk-python/issues/589)) +- Correct the Installation Guide's development-install instructions, which told readers to check out the repository and then install the published package from PyPI instead of their local checkout. ([#590](https://github.com/Backblaze/b2-sdk-python/issues/590)) +- Fix typos in the Advanced usage patterns guide and remove an outdated time-relative claim about the library's age from the overview. ([#591](https://github.com/Backblaze/b2-sdk-python/issues/591)) +- Document how to choose a location for a new test in the Contributors Guide, covering the shared unit directories, the per-interface `v0`-`v3` directories, `v_all`, integration tests, the `apiver` marker, and a checklist for changes to `b2sdk/_internal`. ([#592](https://github.com/Backblaze/b2-sdk-python/issues/592)) +- Expand the release guide into a maintainer runbook covering prerequisites, the changelog build, the commit/CI/tag sequence, what the Continuous Delivery workflow does, post-release verification, and recovery before and after a tag is pushed. ([#593](https://github.com/Backblaze/b2-sdk-python/issues/593)) +- Add a task-oriented replication guide covering setup, required application-key capabilities, per-file replication status, monitoring and how to read a scan report, plus API reference pages for the public replication classes. ([#595](https://github.com/Backblaze/b2-sdk-python/issues/595)) +- Consolidate contributor guidance into the published Contributors Guide, and reduce `CONTRIBUTING.md` to a short entry point that links to it, so the two copies can no longer drift apart. ([#599](https://github.com/Backblaze/b2-sdk-python/issues/599)) +- Resolve the embedded documentation TODOs: drop the obsolete ones, make the "Why use b2sdk?" list consistent and linked, and document the progress reporters and the exception hierarchy properly. ([#601](https://github.com/Backblaze/b2-sdk-python/issues/601)) +- Add a writing style guide for SDK documentation and docstrings. ([#741](https://github.com/Backblaze/b2-sdk-python/issues/741)) +- Add a documentation index for SDK entry points. ([#742](https://github.com/Backblaze/b2-sdk-python/issues/742)) +- Add a link to the B2 Model Context Protocol server in SDK documentation. ([#743](https://github.com/Backblaze/b2-sdk-python/issues/743)) +- Add a guide to the SDK test levels and verification practices. ([#744](https://github.com/Backblaze/b2-sdk-python/issues/744)) +- Corrected bucket and large-file API docstrings to match their behavior. ([#745](https://github.com/Backblaze/b2-sdk-python/issues/745)) +- Correct the sync and scan docstrings to match their current behavior. ([#746](https://github.com/Backblaze/b2-sdk-python/issues/746)) +- Correct quick start and tutorial examples for the v3 API. ([#763](https://github.com/Backblaze/b2-sdk-python/issues/763)) +- Correct documentation for application keys, unbound uploads, and streamed concatenation. ([#764](https://github.com/Backblaze/b2-sdk-python/issues/764)) +- Fix the `create_file`, `create_file_stream`, `concatenate` and `concatenate_stream` examples in the advanced usage guide: remove the `prioritize`, `large_file_callback` and `auto_continue` parameters that do not exist, use `continue_large_file_id`, and pass `file_info` by keyword. ([#780](https://github.com/Backblaze/b2-sdk-python/issues/780)) +- Link the testing guide, the writing style guide, the API compatibility page and the glossary from `llms.txt`, and link the testing guide, the writing style guide and `llms.txt` from the README. ([#782](https://github.com/Backblaze/b2-sdk-python/issues/782)) +- Add a guide for migrating from `b2sdk.v2` to `b2sdk.v3`. ([#783](https://github.com/Backblaze/b2-sdk-python/issues/783)) +- Correct the errors and retries guide: upload data requests are sent once by the HTTP layer, and only the upload manager retries a failed upload. ([#785](https://github.com/Backblaze/b2-sdk-python/issues/785)) +- Add `AGENTS.md` and `CLAUDE.md` with commands, architecture, conventions and recurring review findings for coding agents and new contributors. +- Add a guide to SDK exception handling, HTTP retries, and upload retries. +- Correct the release date, support guidance, and installation instructions. +- Document account info stores and account authorization. +- Fix repeated words in comments and docstrings. +- Improve the wording of the installation, quick start, and tutorial guides. +- Improve the writing style in the replication guide, API interface guide, glossary, README, and support instructions. +- Improve wording in the advanced usage and server-side encryption guides. +- Rewrite flagged long and passive sentences in the advanced usage guide to follow the writing style. +- State explicitly that being importable from a versioned namespace such as `b2sdk.v3` is not a compatibility promise, and document how to tell whether a name is public, internal, or unclassified. + +### Infrastructure + +- Account for the Windows long-path prefix when checking paths through internal symlinks and symlinked local roots in the unit tests. +- Add a SECURITY.md describing the coordinated vulnerability-disclosure policy. +- Add a `verify` skill that runs the local nox gate and explains what each stage failure means. +- Add a static test that checks the `nox` sessions and relative paths named in `AGENTS.md`, `CONTRIBUTING.md` and the agent skills exist. +- Add an opt-in `--b2-simulator` pytest option that runs the simulator-backed unit tests against the standalone b2-simulator over HTTP, and fix test data that only the in-process `RawSimulator` accepted: SSE-C test keys are now 256-bit, the reauthorization fixture uses the authorized account id instead of the key id, and assertions derive file ids, key ids, bucket ids, authorization tokens and URLs instead of using `RawSimulator`'s fixed values. +- Add regression tests for known defects; tests of defects that are still present are strict expected failures marked `known_defect` (run them with `pytest --runxfail -m known_defect`). +- Add shared unit tests for streaming response failures, encoded bytes, Unicode decoding, consumed streams, and simulator-only authorization helpers. +- Add shared-interface unit coverage for malformed range headers, HTTP error parsing, retry attempt budgets, and capped retry backoff. +- Add unit tests asserting that the signing secret and custom header value of a notification rule never appear in the SDK DEBUG trace or in exception text raised by `Bucket.set_notification_rules`, on the pre-authorization, API error and validation error paths (the success path is already covered by `test_notification_rule_tracing.py`). +- Add unit tests proving that every outbound HTTP entry point of `B2Http` stops waiting on an unresponsive local server within its timeout and raises `B2RequestTimeout`. +- Check in CI that every import shown in the documentation examples (`doc/source/*.rst`) resolves against the public `b2sdk` API, and add direct unit tests for the planner's `_filter_out_none` helper. +- Compare the symlinked-root scan test path by filesystem identity so it passes on Windows. +- Drop an unused test import left in the bucket regression suite after two fixes merged into the same file, restoring the lint gate on master. +- Emit individual JUnit cases for pytest and unittest subtests so report totals match their case entries, including failures and skips. +- Fix more unit-test data that only the in-process `RawSimulator` accepted, so those tests also pass against b2-simulator: retention dates in the future and on Object Lock buckets, valid CORS, lifecycle and replication settings, an explicit content type on `b2_start_large_file`, the content type B2 stores for `b2/x-auto`, and the errors real B2 returns for a refused governance delete and a wrong SHA-1. +- Keep JUnit case totals consistent when a failed subtest parent also has a teardown error. Preserve requested captured output on subtest cases while respecting passing-test logging settings. Leave interrupted reports unreconciled rather than manufacturing passing outcomes. +- Keep draft pull request CI credential-free: skip bucket cleanup and SDK/CLI live tests while retaining unit and build checks. +- Make the symlinked-root scan test compare resolved paths so it passes on Windows. +- Pin workflow actions and require unit tests to pass before release. +- Remove the stale C4 known-defect test demonstrators, whose quick-start and install-documentation defects are already fixed, so the static test suite no longer fails with XPASS(strict). +- Remove unused known-defect test imports left after resolving several low-severity findings. +- Replace community spelling, changelog-reading, and GitHub release actions with local commands, retaining commented fallbacks until a real workflow run verifies the replacements. +- Require the B2_LIVE_TESTS_ENABLED repository variable to opt into live tests and bucket cleanup, including ready pull requests and master pushes. +- Run SDK and CLI-compatibility integration tests against the pinned B2 Simulator for pull requests; run fail-closed live B2 integration weekly (reporting scheduled failures as an issue), on manual dispatch, and before each release. +- Run checks for the support text and optional dependency installation as ordinary regressions now that the documentation defects are fixed. +- Unmark the C30 and C59 known-defect regression tests now that both defects are fixed. + + ## [2.13.5](https://github.com/Backblaze/b2-sdk-python/releases/tag/v2.13.5) - 2026-11-17 diff --git a/changelog.d/+account-info-guide.doc.md b/changelog.d/+account-info-guide.doc.md deleted file mode 100644 index 340721041..000000000 --- a/changelog.d/+account-info-guide.doc.md +++ /dev/null @@ -1 +0,0 @@ -Document account info stores and account authorization. diff --git a/changelog.d/+agents-md.doc.md b/changelog.d/+agents-md.doc.md deleted file mode 100644 index fc93a8cab..000000000 --- a/changelog.d/+agents-md.doc.md +++ /dev/null @@ -1 +0,0 @@ -Add `AGENTS.md` and `CLAUDE.md` with commands, architecture, conventions and recurring review findings for coding agents and new contributors. diff --git a/changelog.d/+b2-simulator-unit-g1.infrastructure.md b/changelog.d/+b2-simulator-unit-g1.infrastructure.md deleted file mode 100644 index 24c3400c8..000000000 --- a/changelog.d/+b2-simulator-unit-g1.infrastructure.md +++ /dev/null @@ -1 +0,0 @@ -Fix more unit-test data that only the in-process `RawSimulator` accepted, so those tests also pass against b2-simulator: retention dates in the future and on Object Lock buckets, valid CORS, lifecycle and replication settings, an explicit content type on `b2_start_large_file`, the content type B2 stores for `b2/x-auto`, and the errors real B2 returns for a refused governance delete and a wrong SHA-1. diff --git a/changelog.d/+b2-simulator-unit-harness.infrastructure.md b/changelog.d/+b2-simulator-unit-harness.infrastructure.md deleted file mode 100644 index bb60064e3..000000000 --- a/changelog.d/+b2-simulator-unit-harness.infrastructure.md +++ /dev/null @@ -1 +0,0 @@ -Add an opt-in `--b2-simulator` pytest option that runs the simulator-backed unit tests against the standalone b2-simulator over HTTP, and fix test data that only the in-process `RawSimulator` accepted: SSE-C test keys are now 256-bit, the reauthorization fixture uses the authorized account id instead of the key id, and assertions derive file ids, key ids, bucket ids, authorization tokens and URLs instead of using `RawSimulator`'s fixed values. diff --git a/changelog.d/+bucket-delete-cache.fixed.md b/changelog.d/+bucket-delete-cache.fixed.md deleted file mode 100644 index 52e737a9d..000000000 --- a/changelog.d/+bucket-delete-cache.fixed.md +++ /dev/null @@ -1 +0,0 @@ -Clear cached bucket names after deleting a bucket. diff --git a/changelog.d/+c28-bucket-assert.fixed.md b/changelog.d/+c28-bucket-assert.fixed.md deleted file mode 100644 index 53e5aaa09..000000000 --- a/changelog.d/+c28-bucket-assert.fixed.md +++ /dev/null @@ -1 +0,0 @@ -Show the returned bucket name in the assertion message when bucket creation returns a different name. diff --git a/changelog.d/+c31-pydantic-version.fixed.md b/changelog.d/+c31-pydantic-version.fixed.md deleted file mode 100644 index e163c2b3f..000000000 --- a/changelog.d/+c31-pydantic-version.fixed.md +++ /dev/null @@ -1 +0,0 @@ -Compare the Pydantic major version numerically when detecting optional validation support. diff --git a/changelog.d/+c33-upload-part-size.fixed.md b/changelog.d/+c33-upload-part-size.fixed.md deleted file mode 100644 index 4564e3632..000000000 --- a/changelog.d/+c33-upload-part-size.fixed.md +++ /dev/null @@ -1 +0,0 @@ -Treat Bucket.upload min_part_size as a lower limit while retaining the account recommended upload part size. diff --git a/changelog.d/+c51-http-error-args.fixed.md b/changelog.d/+c51-http-error-args.fixed.md deleted file mode 100644 index 1fc88389c..000000000 --- a/changelog.d/+c51-http-error-args.fixed.md +++ /dev/null @@ -1 +0,0 @@ -Map connection errors with missing exception arguments to B2 connection errors without raising IndexError. diff --git a/changelog.d/+c55-auth-session.fixed.md b/changelog.d/+c55-auth-session.fixed.md deleted file mode 100644 index d2c6f4007..000000000 --- a/changelog.d/+c55-auth-session.fixed.md +++ /dev/null @@ -1 +0,0 @@ -Preserve existing credentials and bucket caches when authorization is rejected because a restricted bucket no longer exists. diff --git a/changelog.d/+chained-stream-read-none.fixed.md b/changelog.d/+chained-stream-read-none.fixed.md deleted file mode 100644 index bdcff774e..000000000 --- a/changelog.d/+chained-stream-read-none.fixed.md +++ /dev/null @@ -1 +0,0 @@ -Fix reading a chained stream when the size is omitted or None. diff --git a/changelog.d/+ci-vendor-third-party-actions.infrastructure.md b/changelog.d/+ci-vendor-third-party-actions.infrastructure.md deleted file mode 100644 index 650c41017..000000000 --- a/changelog.d/+ci-vendor-third-party-actions.infrastructure.md +++ /dev/null @@ -1 +0,0 @@ -Replace community spelling, changelog-reading, and GitHub release actions with local commands, retaining commented fallbacks until a real workflow run verifies the replacements. diff --git a/changelog.d/+concurrent-upload-error.fixed.md b/changelog.d/+concurrent-upload-error.fixed.md deleted file mode 100644 index 797ce988a..000000000 --- a/changelog.d/+concurrent-upload-error.fixed.md +++ /dev/null @@ -1 +0,0 @@ -Simplify and clarify the error messages raised for concurrent-upload responses. diff --git a/changelog.d/+copy-header-content-type.fixed.md b/changelog.d/+copy-header-content-type.fixed.md deleted file mode 100644 index b4a659396..000000000 --- a/changelog.d/+copy-header-content-type.fixed.md +++ /dev/null @@ -1 +0,0 @@ -Preserve the source content type when copying with header overrides and avoid inheriting an incorrect checksum for ranged copies. diff --git a/changelog.d/+doc-examples-and-filter-tests.infrastructure.md b/changelog.d/+doc-examples-and-filter-tests.infrastructure.md deleted file mode 100644 index c5c2b2bf8..000000000 --- a/changelog.d/+doc-examples-and-filter-tests.infrastructure.md +++ /dev/null @@ -1 +0,0 @@ -Check in CI that every import shown in the documentation examples (`doc/source/*.rst`) resolves against the public `b2sdk` API, and add direct unit tests for the planner's `_filter_out_none` helper. diff --git a/changelog.d/+downloaded-file-double-save.fixed.md b/changelog.d/+downloaded-file-double-save.fixed.md deleted file mode 100644 index 8a7b9fdce..000000000 --- a/changelog.d/+downloaded-file-double-save.fixed.md +++ /dev/null @@ -1 +0,0 @@ -Raise a clear error when saving a consumed download again, before modifying the destination. diff --git a/changelog.d/+draft-ci-no-live.infrastructure.md b/changelog.d/+draft-ci-no-live.infrastructure.md deleted file mode 100644 index 55dcc1759..000000000 --- a/changelog.d/+draft-ci-no-live.infrastructure.md +++ /dev/null @@ -1 +0,0 @@ -Keep draft pull request CI credential-free: skip bucket cleanup and SDK/CLI live tests while retaining unit and build checks. diff --git a/changelog.d/+errors-and-retries-guide.doc.md b/changelog.d/+errors-and-retries-guide.doc.md deleted file mode 100644 index 658d12bfb..000000000 --- a/changelog.d/+errors-and-retries-guide.doc.md +++ /dev/null @@ -1 +0,0 @@ -Add a guide to SDK exception handling, HTTP retries, and upload retries. diff --git a/changelog.d/+fix-doubled-words.doc.md b/changelog.d/+fix-doubled-words.doc.md deleted file mode 100644 index b29638a7c..000000000 --- a/changelog.d/+fix-doubled-words.doc.md +++ /dev/null @@ -1 +0,0 @@ -Fix repeated words in comments and docstrings. diff --git a/changelog.d/+flip-resolved-known-defect-tests.infrastructure.md b/changelog.d/+flip-resolved-known-defect-tests.infrastructure.md deleted file mode 100644 index 885ad8ecf..000000000 --- a/changelog.d/+flip-resolved-known-defect-tests.infrastructure.md +++ /dev/null @@ -1 +0,0 @@ -Unmark the C30 and C59 known-defect regression tests now that both defects are fixed. diff --git a/changelog.d/+http-date-locale.fixed.md b/changelog.d/+http-date-locale.fixed.md deleted file mode 100644 index 0afbee4f4..000000000 --- a/changelog.d/+http-date-locale.fixed.md +++ /dev/null @@ -1 +0,0 @@ -Fixed locale-dependent formatting of HTTP expiration dates. diff --git a/changelog.d/+installation-support-docs.doc.md b/changelog.d/+installation-support-docs.doc.md deleted file mode 100644 index 850e749d3..000000000 --- a/changelog.d/+installation-support-docs.doc.md +++ /dev/null @@ -1 +0,0 @@ -Correct the release date, support guidance, and installation instructions. diff --git a/changelog.d/+instructions-check.infrastructure.md b/changelog.d/+instructions-check.infrastructure.md deleted file mode 100644 index 8fde94518..000000000 --- a/changelog.d/+instructions-check.infrastructure.md +++ /dev/null @@ -1 +0,0 @@ -Add a static test that checks the `nox` sessions and relative paths named in `AGENTS.md`, `CONTRIBUTING.md` and the agent skills exist. diff --git a/changelog.d/+interface-boundary.doc.md b/changelog.d/+interface-boundary.doc.md deleted file mode 100644 index 391df3310..000000000 --- a/changelog.d/+interface-boundary.doc.md +++ /dev/null @@ -1 +0,0 @@ -State explicitly that being importable from a versioned namespace such as `b2sdk.v3` is not a compatibility promise, and document how to tell whether a name is public, internal, or unclassified. diff --git a/changelog.d/+junit-review-errors.infrastructure.md b/changelog.d/+junit-review-errors.infrastructure.md deleted file mode 100644 index 6f0749929..000000000 --- a/changelog.d/+junit-review-errors.infrastructure.md +++ /dev/null @@ -1 +0,0 @@ -Keep JUnit case totals consistent when a failed subtest parent also has a teardown error. Preserve requested captured output on subtest cases while respecting passing-test logging settings. Leave interrupted reports unreconciled rather than manufacturing passing outcomes. diff --git a/changelog.d/+junit-subtest-counts.infrastructure.md b/changelog.d/+junit-subtest-counts.infrastructure.md deleted file mode 100644 index a4963d13f..000000000 --- a/changelog.d/+junit-subtest-counts.infrastructure.md +++ /dev/null @@ -1 +0,0 @@ -Emit individual JUnit cases for pytest and unittest subtests so report totals match their case entries, including failures and skips. diff --git a/changelog.d/+large-upload-custom-timestamp.fixed.md b/changelog.d/+large-upload-custom-timestamp.fixed.md deleted file mode 100644 index 884c74ede..000000000 --- a/changelog.d/+large-upload-custom-timestamp.fixed.md +++ /dev/null @@ -1 +0,0 @@ -Fixed custom upload timestamps for multipart uploads and their resumption. diff --git a/changelog.d/+legacy-content-encoding-download.fixed.md b/changelog.d/+legacy-content-encoding-download.fixed.md deleted file mode 100644 index 54bec6d57..000000000 --- a/changelog.d/+legacy-content-encoding-download.fixed.md +++ /dev/null @@ -1 +0,0 @@ -Allow v0 and v1 clients to download files stored with a Content-Encoding. diff --git a/changelog.d/+live-ci-opt-in.infrastructure.md b/changelog.d/+live-ci-opt-in.infrastructure.md deleted file mode 100644 index ac7ec1321..000000000 --- a/changelog.d/+live-ci-opt-in.infrastructure.md +++ /dev/null @@ -1 +0,0 @@ -Require the B2_LIVE_TESTS_ENABLED repository variable to opt into live tests and bucket cleanup, including ready pull requests and master pushes. diff --git a/changelog.d/+ls-exact-name-filter.fixed.md b/changelog.d/+ls-exact-name-filter.fixed.md deleted file mode 100644 index 2a963d91a..000000000 --- a/changelog.d/+ls-exact-name-filter.fixed.md +++ /dev/null @@ -1 +0,0 @@ -Honor filters when listing an exact file name. diff --git a/changelog.d/+non-idempotent-create-retries.fixed.md b/changelog.d/+non-idempotent-create-retries.fixed.md deleted file mode 100644 index 84e55bb1f..000000000 --- a/changelog.d/+non-idempotent-create-retries.fixed.md +++ /dev/null @@ -1 +0,0 @@ -Avoid replaying create-style JSON API calls after response timeouts, connection loss, or 5xx responses, including 503. Unlike the general [503 retry guidance](https://www.backblaze.com/docs/cloud-storage-integration-checklist), an uncertain create outcome is surfaced so callers can check server state before trying again. Replayable operations retain their retry policy; rate limits and proven connection-establishment failures are still retried. diff --git a/changelog.d/+notification-rule-iterables.fixed.md b/changelog.d/+notification-rule-iterables.fixed.md deleted file mode 100644 index b8779b949..000000000 --- a/changelog.d/+notification-rule-iterables.fixed.md +++ /dev/null @@ -1 +0,0 @@ -Allow notification rules to be supplied as any iterable. diff --git a/changelog.d/+notification-rules-nonexposure-tests.infrastructure.md b/changelog.d/+notification-rules-nonexposure-tests.infrastructure.md deleted file mode 100644 index bf4a6affe..000000000 --- a/changelog.d/+notification-rules-nonexposure-tests.infrastructure.md +++ /dev/null @@ -1 +0,0 @@ -Add unit tests asserting that the signing secret and custom header value of a notification rule never appear in the SDK DEBUG trace or in exception text raised by `Bucket.set_notification_rules`, on the pre-authorization, API error and validation error paths (the success path is already covered by `test_notification_rule_tracing.py`). diff --git a/changelog.d/+outbound-timeout-tests.infrastructure.md b/changelog.d/+outbound-timeout-tests.infrastructure.md deleted file mode 100644 index 08f37ad49..000000000 --- a/changelog.d/+outbound-timeout-tests.infrastructure.md +++ /dev/null @@ -1 +0,0 @@ -Add unit tests proving that every outbound HTTP entry point of `B2Http` stops waiting on an unresponsive local server within its timeout and raises `B2RequestTimeout`. diff --git a/changelog.d/+parsing_retry_coverage.infrastructure.md b/changelog.d/+parsing_retry_coverage.infrastructure.md deleted file mode 100644 index 8d71247ff..000000000 --- a/changelog.d/+parsing_retry_coverage.infrastructure.md +++ /dev/null @@ -1 +0,0 @@ -Add shared-interface unit coverage for malformed range headers, HTTP error parsing, retry attempt budgets, and capped retry backoff. diff --git a/changelog.d/+path-validation.fixed.md b/changelog.d/+path-validation.fixed.md deleted file mode 100644 index efc4d871f..000000000 --- a/changelog.d/+path-validation.fixed.md +++ /dev/null @@ -1 +0,0 @@ -Reject local paths that resolve outside the sync root, Windows device names and streams, and ASCII control characters in file names. diff --git a/changelog.d/+prune-unused-known-defect-imports.infrastructure.md b/changelog.d/+prune-unused-known-defect-imports.infrastructure.md deleted file mode 100644 index a25e99071..000000000 --- a/changelog.d/+prune-unused-known-defect-imports.infrastructure.md +++ /dev/null @@ -1 +0,0 @@ -Remove unused known-defect test imports left after resolving several low-severity findings. diff --git a/changelog.d/+range-read-negative-size.fixed.md b/changelog.d/+range-read-negative-size.fixed.md deleted file mode 100644 index daf785358..000000000 --- a/changelog.d/+range-read-negative-size.fixed.md +++ /dev/null @@ -1 +0,0 @@ -Reading a range stream with a negative size no longer returns bytes past the end of the configured range. diff --git a/changelog.d/+reauthorization-upload-pools.fixed.md b/changelog.d/+reauthorization-upload-pools.fixed.md deleted file mode 100644 index 76efdd959..000000000 --- a/changelog.d/+reauthorization-upload-pools.fixed.md +++ /dev/null @@ -1 +0,0 @@ -Refresh pooled upload URLs when the authorization key changes, including when uploads or upload URL requests are in progress. diff --git a/changelog.d/+regression-bucket-unused-import.infrastructure.md b/changelog.d/+regression-bucket-unused-import.infrastructure.md deleted file mode 100644 index 6b54424c2..000000000 --- a/changelog.d/+regression-bucket-unused-import.infrastructure.md +++ /dev/null @@ -1 +0,0 @@ -Drop an unused test import left in the bucket regression suite after two fixes merged into the same file, restoring the lint gate on master. diff --git a/changelog.d/+regression-tests-known-defects.infrastructure.md b/changelog.d/+regression-tests-known-defects.infrastructure.md deleted file mode 100644 index 4cffb7e48..000000000 --- a/changelog.d/+regression-tests-known-defects.infrastructure.md +++ /dev/null @@ -1 +0,0 @@ -Add regression tests for known defects; tests of defects that are still present are strict expected failures marked `known_defect` (run them with `pytest --runxfail -m known_defect`). diff --git a/changelog.d/+release-ci-safety.infrastructure.md b/changelog.d/+release-ci-safety.infrastructure.md deleted file mode 100644 index 50912e5cf..000000000 --- a/changelog.d/+release-ci-safety.infrastructure.md +++ /dev/null @@ -1 +0,0 @@ -Pin workflow actions and require unit tests to pass before release. diff --git a/changelog.d/+remove-stale-c4-demonstrators.infrastructure.md b/changelog.d/+remove-stale-c4-demonstrators.infrastructure.md deleted file mode 100644 index 465c2864a..000000000 --- a/changelog.d/+remove-stale-c4-demonstrators.infrastructure.md +++ /dev/null @@ -1 +0,0 @@ -Remove the stale C4 known-defect test demonstrators, whose quick-start and install-documentation defects are already fixed, so the static test suite no longer fails with XPASS(strict). diff --git a/changelog.d/+request-encryption-retention.fixed.md b/changelog.d/+request-encryption-retention.fixed.md deleted file mode 100644 index 67b334d3b..000000000 --- a/changelog.d/+request-encryption-retention.fixed.md +++ /dev/null @@ -1 +0,0 @@ -Accept matching percent-encoded SSE-C key identifiers in upload metadata without double encoding, while rejecting conflicting identifiers. Add request, encryption and Object Lock unit tests across the supported SDK interfaces. diff --git a/changelog.d/+resolved-doc-regressions.infrastructure.md b/changelog.d/+resolved-doc-regressions.infrastructure.md deleted file mode 100644 index 29c66f4c6..000000000 --- a/changelog.d/+resolved-doc-regressions.infrastructure.md +++ /dev/null @@ -1 +0,0 @@ -Run checks for the support text and optional dependency installation as ordinary regressions now that the documentation defects are fixed. diff --git a/changelog.d/+resume-settings.fixed.md b/changelog.d/+resume-settings.fixed.md deleted file mode 100644 index f958cd6cb..000000000 --- a/changelog.d/+resume-settings.fixed.md +++ /dev/null @@ -1 +0,0 @@ -Reject manually continuing an unfinished large file when an explicitly requested encryption, retention, or legal-hold setting differs from the unfinished file. Omitted settings are not compared. diff --git a/changelog.d/+retry-after-bounds.fixed.md b/changelog.d/+retry-after-bounds.fixed.md deleted file mode 100644 index 488259fb7..000000000 --- a/changelog.d/+retry-after-bounds.fixed.md +++ /dev/null @@ -1 +0,0 @@ -Bound server-provided retry delays to between zero and five minutes. diff --git a/changelog.d/+security-policy.infrastructure.md b/changelog.d/+security-policy.infrastructure.md deleted file mode 100644 index 4a9e6c321..000000000 --- a/changelog.d/+security-policy.infrastructure.md +++ /dev/null @@ -1 +0,0 @@ -Add a SECURITY.md describing the coordinated vulnerability-disclosure policy. diff --git a/changelog.d/+simulator-encryption-check-reset.fixed.md b/changelog.d/+simulator-encryption-check-reset.fixed.md deleted file mode 100644 index 95a649223..000000000 --- a/changelog.d/+simulator-encryption-check-reset.fixed.md +++ /dev/null @@ -1 +0,0 @@ -Restore the raw simulator encryption-check flag after an exception inside `dont_check_encryption`, so later simulator checks are not left disabled (affects the test model only). diff --git a/changelog.d/+simulator-pr-weekly-live-b2.infrastructure.md b/changelog.d/+simulator-pr-weekly-live-b2.infrastructure.md deleted file mode 100644 index 7481cb3aa..000000000 --- a/changelog.d/+simulator-pr-weekly-live-b2.infrastructure.md +++ /dev/null @@ -1 +0,0 @@ -Run SDK and CLI-compatibility integration tests against the pinned B2 Simulator for pull requests; run fail-closed live B2 integration weekly (reporting scheduled failures as an issue), on manual dispatch, and before each release. diff --git a/changelog.d/+sqlite-account-info-safety.fixed.md b/changelog.d/+sqlite-account-info-safety.fixed.md deleted file mode 100644 index b156489ab..000000000 --- a/changelog.d/+sqlite-account-info-safety.fixed.md +++ /dev/null @@ -1 +0,0 @@ -Protect new account configuration directories, validate profile names, and close cached SQLite connections across threads. diff --git a/changelog.d/+stream-range-unknown-length.fixed.md b/changelog.d/+stream-range-unknown-length.fixed.md deleted file mode 100644 index b3bcd83b6..000000000 --- a/changelog.d/+stream-range-unknown-length.fixed.md +++ /dev/null @@ -1 +0,0 @@ -Allow stream range uploads with an unspecified length to read and calculate their size. diff --git a/changelog.d/+streaming_boundary_coverage.infrastructure.md b/changelog.d/+streaming_boundary_coverage.infrastructure.md deleted file mode 100644 index 8a034c7a8..000000000 --- a/changelog.d/+streaming_boundary_coverage.infrastructure.md +++ /dev/null @@ -1 +0,0 @@ -Add shared unit tests for streaming response failures, encoded bytes, Unicode decoding, consumed streams, and simulator-only authorization helpers. diff --git a/changelog.d/+style-advanced-continued.doc.md b/changelog.d/+style-advanced-continued.doc.md deleted file mode 100644 index 9f81b9894..000000000 --- a/changelog.d/+style-advanced-continued.doc.md +++ /dev/null @@ -1 +0,0 @@ -Rewrite flagged long and passive sentences in the advanced usage guide to follow the writing style. diff --git a/changelog.d/+style-advanced-sse.doc.md b/changelog.d/+style-advanced-sse.doc.md deleted file mode 100644 index 469c838c7..000000000 --- a/changelog.d/+style-advanced-sse.doc.md +++ /dev/null @@ -1 +0,0 @@ -Improve wording in the advanced usage and server-side encryption guides. diff --git a/changelog.d/+style-install-quick-start-tutorial.doc.md b/changelog.d/+style-install-quick-start-tutorial.doc.md deleted file mode 100644 index 785eb1f2d..000000000 --- a/changelog.d/+style-install-quick-start-tutorial.doc.md +++ /dev/null @@ -1 +0,0 @@ -Improve the wording of the installation, quick start, and tutorial guides. diff --git a/changelog.d/+style-replication-api-types-glossary-readme.doc.md b/changelog.d/+style-replication-api-types-glossary-readme.doc.md deleted file mode 100644 index e36d0572f..000000000 --- a/changelog.d/+style-replication-api-types-glossary-readme.doc.md +++ /dev/null @@ -1 +0,0 @@ -Improve the writing style in the replication guide, API interface guide, glossary, README, and support instructions. diff --git a/changelog.d/+symlink-device-inode.fixed.md b/changelog.d/+symlink-device-inode.fixed.md deleted file mode 100644 index 61ae8dba2..000000000 --- a/changelog.d/+symlink-device-inode.fixed.md +++ /dev/null @@ -1 +0,0 @@ -Fixed incorrect symlink loop detection when directories on different devices have the same inode number. diff --git a/changelog.d/+sync-finalization.fixed.md b/changelog.d/+sync-finalization.fixed.md deleted file mode 100644 index da24777f3..000000000 --- a/changelog.d/+sync-finalization.fixed.md +++ /dev/null @@ -1 +0,0 @@ -Fixed sync download finalization and escaped control characters in sync completion messages. diff --git a/changelog.d/+sync-folder-prefix-and-shutdown.fixed.md b/changelog.d/+sync-folder-prefix-and-shutdown.fixed.md deleted file mode 100644 index 6f6d1b2fc..000000000 --- a/changelog.d/+sync-folder-prefix-and-shutdown.fixed.md +++ /dev/null @@ -1 +0,0 @@ -Fix folder scans when an object has the same name as the source folder, preserving exact-object listing behavior. Ensure sync waits for queued actions to finish before returning a scheduling error. diff --git a/changelog.d/+sync-replacement-cleanup.fixed.md b/changelog.d/+sync-replacement-cleanup.fixed.md deleted file mode 100644 index 8d934318f..000000000 --- a/changelog.d/+sync-replacement-cleanup.fixed.md +++ /dev/null @@ -1 +0,0 @@ -Preserve destination versions when a sync replacement transfer fails. diff --git a/changelog.d/+transfer-audit.fixed.md b/changelog.d/+transfer-audit.fixed.md deleted file mode 100644 index 4d68c0079..000000000 --- a/changelog.d/+transfer-audit.fixed.md +++ /dev/null @@ -1 +0,0 @@ -Reject incorrect upload checksums under Python optimization, cancel pending multipart work after a part fails, and avoid copying unbound upload buffers. diff --git a/changelog.d/+unauthorized-subclass.fixed.md b/changelog.d/+unauthorized-subclass.fixed.md deleted file mode 100644 index 4d7087b3d..000000000 --- a/changelog.d/+unauthorized-subclass.fixed.md +++ /dev/null @@ -1 +0,0 @@ -The session no longer turns `EmailNotVerified` and `NoPaymentHistory` into a plain `Unauthorized`, so uploads fail right away instead of being retried. diff --git a/changelog.d/+upload-source-safety.fixed.md b/changelog.d/+upload-source-safety.fixed.md deleted file mode 100644 index 7bfbbe7b1..000000000 --- a/changelog.d/+upload-source-safety.fixed.md +++ /dev/null @@ -1 +0,0 @@ -Protect upload data in representations, close checksum streams, and validate local file range offsets. diff --git a/changelog.d/+v0-unhide-file.fixed.md b/changelog.d/+v0-unhide-file.fixed.md deleted file mode 100644 index 6fc041b88..000000000 --- a/changelog.d/+v0-unhide-file.fixed.md +++ /dev/null @@ -1 +0,0 @@ -Allow the v0 bucket interface to unhide files. diff --git a/changelog.d/+verify-skill.infrastructure.md b/changelog.d/+verify-skill.infrastructure.md deleted file mode 100644 index 48a800345..000000000 --- a/changelog.d/+verify-skill.infrastructure.md +++ /dev/null @@ -1 +0,0 @@ -Add a `verify` skill that runs the local nox gate and explains what each stage failure means. diff --git a/changelog.d/+version-metadata-fallback.fixed.md b/changelog.d/+version-metadata-fallback.fixed.md deleted file mode 100644 index d1e20db45..000000000 --- a/changelog.d/+version-metadata-fallback.fixed.md +++ /dev/null @@ -1 +0,0 @@ -Fix importing vendored or uninstalled copies of the SDK by using a fallback version when package metadata is unavailable. diff --git a/changelog.d/+windows-symlink-path-expectation.infrastructure.md b/changelog.d/+windows-symlink-path-expectation.infrastructure.md deleted file mode 100644 index 1d0525161..000000000 --- a/changelog.d/+windows-symlink-path-expectation.infrastructure.md +++ /dev/null @@ -1 +0,0 @@ -Account for the Windows long-path prefix when checking paths through internal symlinks and symlinked local roots in the unit tests. diff --git a/changelog.d/+windows-symlink-path-test.infrastructure.md b/changelog.d/+windows-symlink-path-test.infrastructure.md deleted file mode 100644 index 0e68ddace..000000000 --- a/changelog.d/+windows-symlink-path-test.infrastructure.md +++ /dev/null @@ -1 +0,0 @@ -Make the symlinked-root scan test compare resolved paths so it passes on Windows. diff --git a/changelog.d/+windows-symlink-samefile.infrastructure.md b/changelog.d/+windows-symlink-samefile.infrastructure.md deleted file mode 100644 index 33d182df6..000000000 --- a/changelog.d/+windows-symlink-samefile.infrastructure.md +++ /dev/null @@ -1 +0,0 @@ -Compare the symlinked-root scan test path by filesystem identity so it passes on Windows. diff --git a/changelog.d/232.fixed.md b/changelog.d/232.fixed.md deleted file mode 100644 index 144a62e61..000000000 --- a/changelog.d/232.fixed.md +++ /dev/null @@ -1 +0,0 @@ -Serialize account database schema migrations so concurrent SDK instances do not apply the same upgrade twice. diff --git a/changelog.d/584.doc.md b/changelog.d/584.doc.md deleted file mode 100644 index 756bbea1f..000000000 --- a/changelog.d/584.doc.md +++ /dev/null @@ -1 +0,0 @@ -Fix the Quick Start examples to match the public `b2sdk.v3` interface: `EncryptionSetting` rather than `EncryptionSettings`, `EncryptionKey(key_id=...)` rather than `id=`, both required mappings for `BasicSyncEncryptionSettingsProvider`, and `file_info=` rather than `file_infos=`. diff --git a/changelog.d/585.doc.md b/changelog.d/585.doc.md deleted file mode 100644 index 784e6f02e..000000000 --- a/changelog.d/585.doc.md +++ /dev/null @@ -1 +0,0 @@ -Use `update_file_retention` instead of `update_file_legal_hold` in the Quick Start file-lock examples that pass a `FileRetentionSetting`. diff --git a/changelog.d/586.doc.md b/changelog.d/586.doc.md deleted file mode 100644 index 986ff1691..000000000 --- a/changelog.d/586.doc.md +++ /dev/null @@ -1 +0,0 @@ -Fix the Advanced usage patterns guide to reference `UploadSourceLocalFile` rather than the nonexistent `LocalUploadSource`, and to call `bucket.create_file` rather than an undefined `planner` object. diff --git a/changelog.d/588.doc.md b/changelog.d/588.doc.md deleted file mode 100644 index c07000e08..000000000 --- a/changelog.d/588.doc.md +++ /dev/null @@ -1 +0,0 @@ -Remove the nonexistent `deploy` Nox session from the Contributors Guide and describe how releases are actually published by the Continuous Delivery workflow. diff --git a/changelog.d/589.doc.md b/changelog.d/589.doc.md deleted file mode 100644 index f4b8015d1..000000000 --- a/changelog.d/589.doc.md +++ /dev/null @@ -1 +0,0 @@ -Correct the stale CI test matrix description in the contributor guides, which claimed eight Python versions instead of the currently supported set. diff --git a/changelog.d/590.doc.md b/changelog.d/590.doc.md deleted file mode 100644 index af97b4e72..000000000 --- a/changelog.d/590.doc.md +++ /dev/null @@ -1 +0,0 @@ -Correct the Installation Guide's development-install instructions, which told readers to check out the repository and then install the published package from PyPI instead of their local checkout. diff --git a/changelog.d/591.doc.md b/changelog.d/591.doc.md deleted file mode 100644 index 3f62ef354..000000000 --- a/changelog.d/591.doc.md +++ /dev/null @@ -1 +0,0 @@ -Fix typos in the Advanced usage patterns guide and remove an outdated time-relative claim about the library's age from the overview. diff --git a/changelog.d/592.doc.md b/changelog.d/592.doc.md deleted file mode 100644 index 0e2aba5d5..000000000 --- a/changelog.d/592.doc.md +++ /dev/null @@ -1 +0,0 @@ -Document how to choose a location for a new test in the Contributors Guide, covering the shared unit directories, the per-interface `v0`-`v3` directories, `v_all`, integration tests, the `apiver` marker, and a checklist for changes to `b2sdk/_internal`. diff --git a/changelog.d/593.doc.md b/changelog.d/593.doc.md deleted file mode 100644 index 26594d812..000000000 --- a/changelog.d/593.doc.md +++ /dev/null @@ -1 +0,0 @@ -Expand the release guide into a maintainer runbook covering prerequisites, the changelog build, the commit/CI/tag sequence, what the Continuous Delivery workflow does, post-release verification, and recovery before and after a tag is pushed. diff --git a/changelog.d/595.doc.md b/changelog.d/595.doc.md deleted file mode 100644 index f59ac6131..000000000 --- a/changelog.d/595.doc.md +++ /dev/null @@ -1 +0,0 @@ -Add a task-oriented replication guide covering setup, required application-key capabilities, per-file replication status, monitoring and how to read a scan report, plus API reference pages for the public replication classes. diff --git a/changelog.d/599.doc.md b/changelog.d/599.doc.md deleted file mode 100644 index deb43320b..000000000 --- a/changelog.d/599.doc.md +++ /dev/null @@ -1 +0,0 @@ -Consolidate contributor guidance into the published Contributors Guide, and reduce `CONTRIBUTING.md` to a short entry point that links to it, so the two copies can no longer drift apart. diff --git a/changelog.d/601.doc.md b/changelog.d/601.doc.md deleted file mode 100644 index cf88f11b4..000000000 --- a/changelog.d/601.doc.md +++ /dev/null @@ -1 +0,0 @@ -Resolve the embedded documentation TODOs: drop the obsolete ones, make the "Why use b2sdk?" list consistent and linked, and document the progress reporters and the exception hierarchy properly. diff --git a/changelog.d/631.fixed.md b/changelog.d/631.fixed.md deleted file mode 100644 index 92edd5973..000000000 --- a/changelog.d/631.fixed.md +++ /dev/null @@ -1 +0,0 @@ -Escape control characters in the remote file name printed when a sync action fails. diff --git a/changelog.d/654.fixed.md b/changelog.d/654.fixed.md deleted file mode 100644 index db1520ef8..000000000 --- a/changelog.d/654.fixed.md +++ /dev/null @@ -1 +0,0 @@ -Stream hashing now continues reading until the requested length or the true end of data. Previously a source that returned a short read before EOF could produce a checksum and length covering only a prefix, allowing a truncated body to be uploaded with a matching hash. diff --git a/changelog.d/736.fixed.md b/changelog.d/736.fixed.md deleted file mode 100644 index 4604c1b16..000000000 --- a/changelog.d/736.fixed.md +++ /dev/null @@ -1 +0,0 @@ -Preserve destination-only paths during sync deletion when excluded by name or directory, or when any B2 version is excluded by a time policy. diff --git a/changelog.d/741.doc.md b/changelog.d/741.doc.md deleted file mode 100644 index ff76bc75b..000000000 --- a/changelog.d/741.doc.md +++ /dev/null @@ -1 +0,0 @@ -Add a writing style guide for SDK documentation and docstrings. diff --git a/changelog.d/742.doc.md b/changelog.d/742.doc.md deleted file mode 100644 index 338638f4b..000000000 --- a/changelog.d/742.doc.md +++ /dev/null @@ -1 +0,0 @@ -Add a documentation index for SDK entry points. diff --git a/changelog.d/743.doc.md b/changelog.d/743.doc.md deleted file mode 100644 index 30f3029e9..000000000 --- a/changelog.d/743.doc.md +++ /dev/null @@ -1 +0,0 @@ -Add a link to the B2 Model Context Protocol server in SDK documentation. diff --git a/changelog.d/744.doc.md b/changelog.d/744.doc.md deleted file mode 100644 index 9a4d08bb0..000000000 --- a/changelog.d/744.doc.md +++ /dev/null @@ -1 +0,0 @@ -Add a guide to the SDK test levels and verification practices. diff --git a/changelog.d/745.doc.md b/changelog.d/745.doc.md deleted file mode 100644 index 16c309167..000000000 --- a/changelog.d/745.doc.md +++ /dev/null @@ -1 +0,0 @@ -Corrected bucket and large-file API docstrings to match their behavior. diff --git a/changelog.d/746.doc.md b/changelog.d/746.doc.md deleted file mode 100644 index a41ff7725..000000000 --- a/changelog.d/746.doc.md +++ /dev/null @@ -1 +0,0 @@ -Correct the sync and scan docstrings to match their current behavior. diff --git a/changelog.d/763.doc.md b/changelog.d/763.doc.md deleted file mode 100644 index 5717cbd08..000000000 --- a/changelog.d/763.doc.md +++ /dev/null @@ -1 +0,0 @@ -Correct quick start and tutorial examples for the v3 API. diff --git a/changelog.d/764.doc.md b/changelog.d/764.doc.md deleted file mode 100644 index 915e25a3d..000000000 --- a/changelog.d/764.doc.md +++ /dev/null @@ -1 +0,0 @@ -Correct documentation for application keys, unbound uploads, and streamed concatenation. diff --git a/changelog.d/780.doc.md b/changelog.d/780.doc.md deleted file mode 100644 index 70bb2a8de..000000000 --- a/changelog.d/780.doc.md +++ /dev/null @@ -1 +0,0 @@ -Fix the `create_file`, `create_file_stream`, `concatenate` and `concatenate_stream` examples in the advanced usage guide: remove the `prioritize`, `large_file_callback` and `auto_continue` parameters that do not exist, use `continue_large_file_id`, and pass `file_info` by keyword. diff --git a/changelog.d/782.doc.md b/changelog.d/782.doc.md deleted file mode 100644 index 8c4772760..000000000 --- a/changelog.d/782.doc.md +++ /dev/null @@ -1 +0,0 @@ -Link the testing guide, the writing style guide, the API compatibility page and the glossary from `llms.txt`, and link the testing guide, the writing style guide and `llms.txt` from the README. diff --git a/changelog.d/783.doc.md b/changelog.d/783.doc.md deleted file mode 100644 index 9d957a04e..000000000 --- a/changelog.d/783.doc.md +++ /dev/null @@ -1 +0,0 @@ -Add a guide for migrating from `b2sdk.v2` to `b2sdk.v3`. diff --git a/changelog.d/785.doc.md b/changelog.d/785.doc.md deleted file mode 100644 index 0a030e76d..000000000 --- a/changelog.d/785.doc.md +++ /dev/null @@ -1 +0,0 @@ -Correct the errors and retries guide: upload data requests are sent once by the HTTP layer, and only the upload manager retries a failed upload. diff --git a/changelog.d/803.fixed.md b/changelog.d/803.fixed.md deleted file mode 100644 index 29fa5cbea..000000000 --- a/changelog.d/803.fixed.md +++ /dev/null @@ -1 +0,0 @@ -Accept profile names containing a dot (e.g. `work.prod`) again; they were rejected after profile names started being validated against the whole string. Path separators and names made only of dots remain rejected. diff --git a/changelog.d/806.fixed.md b/changelog.d/806.fixed.md deleted file mode 100644 index 31f7129d6..000000000 --- a/changelog.d/806.fixed.md +++ /dev/null @@ -1 +0,0 @@ -Validate sync download and deletion destinations with make_write_path, refuse existing temporary download paths, and stop retaining SQLite connections from completed worker threads; an unsafe destination aborts down-sync. diff --git a/changelog.d/809.fixed.md b/changelog.d/809.fixed.md deleted file mode 100644 index 2e3c088e7..000000000 --- a/changelog.d/809.fixed.md +++ /dev/null @@ -1 +0,0 @@ -Create files downloaded by sync with the usual permissions (0o666 filtered by the umask) instead of making them executable on POSIX platforms.