Skip to content

Review proposed lock maintenance, local retention, Restic parsing and B2 lifecycle-read fixes #30

Closed

Description

@DangItShipIt

Purpose and ownership boundary

Submit the backup-utility changes discovered during a GS deployment for upstream review. These are proposals, not an approved release or deployment instruction. The installation agent incorrectly modified and deployed private candidates while configuring the utility; the user has explicitly prohibited further modifications to deployed software. Installation work is paused. No branch, tag, release, package publication, or PR is being pushed by this report.

Stable comparison base: v2.0.5 source 80fafa4 (merge of #29). All implementation changes from the private checkout are attached below, including tests and generated schemas. The private commit identifiers are provenance only and are not published GitHub refs: 90a3c4b9ed9259071dbc05afdabb349d09814694 and b0013bedf981af042419fa0c352093c9cc24e92b. Please review/reimplement upstream rather than consuming the private builds.

Related: #23 (restricted B2 credentials/recovery), #25 (retention). Those issues were closed as not planned; this report does not reopen their broader canceled qualification scope.

1. Native reviewed stale-lock inspection and removal

Problem: interruption can leave Restic locks, but there is no native production command for bounded inspection and explicitly reviewed stale unlock. Shell/backend deletion would bypass the utility's operation and reconciliation owners.

Proposed commands: production repositories locks --name <repository> and production repositories unlock-stale with an exact review token, explicit approval, and quiescent-window confirmation.

Proposed behavior:

  • Inspect encrypted lock IDs/payloads using stock Restic and the normal enrolled production dispatcher and native lease/ledger.
  • Bind the review token to repository identity, hostname, UID, complete IDs and payloads, and process-liveness observations.
  • Permit removal only when every observed lock belongs to the current host/UID and its PID is demonstrably absent; reject live, foreign, malformed, truncated, excessive, changed, or uncertain lock sets.
  • Reinspect under the mutation lease, use ordinary restic unlock, never --remove-all or backend object deletion, and verify no locks remain.
  • Bound listings, output size, per-query time and overall inspection; retain uncertainty on incomplete mutation outcomes.
  • External repository users must remain quiescent: stock unlock is repository-wide. This proposal is not automatic lock cleanup.

Tests include actual killed-stdin-backup stale locks in a disposable local Restic repository, refusal of live/foreign/other-UID locks, changed-token/set rejection, truncated/malformed outputs, strict CLI schema/dispatch, native uncertainty barriers, and failed post-unlock verification.

2. Optional local last/weekly retention counts

Problem: the deployment needs combined last/daily/weekly local retention, while portable local policy only exposes daily selection.

Propose optional local_last and local_weekly, default zero/disabled. Require nonnegative integers and reject booleans, negative, noninteger, and null values. Pass enabled values as stock Restic --keep-last and --keep-weekly alongside existing daily rules, using normal union semantics and existing host/job grouping.

Include all counts in the reviewed plan/token and replan before applying exact snapshot IDs. Preserve captured required-replica obligations even if the current job no longer declares the destination. Changing either count must invalidate prior approval.

An example policy is 12 last, 14 daily, and 8 weekly; counts must remain configuration, not hard-coded defaults. This adds no physical prune, cloud retention engine, database migration, or scheduler.

3. Strict parsing of valid Restic keep-all output

Problem/reproduction: Restic 0.19.1 can emit [{"keep":[{"id":"<full snapshot ID>"}],"remove":null}] when all snapshots are retained. Existing parsing rejects the null removal slice despite a valid keep-all result, so even a zero-removal local retention plan fails.

Propose accepting explicit remove: null only when the keep group is nonempty and contains valid full snapshot IDs. Missing/malformed removal groups, invalid kept IDs, empty/null keep arrays and non-list removal values must still fail closed. Include a real one-snapshot Restic reproduction and negative parser tests.

4. B2 lifecycle-read capability compatibility

Problem: a checkpoint can finish the full data read and then fail with HTTP 403 when inspecting lifecycle rules because its otherwise valid bucket/prefix-scoped key lacks the distinct readBucketLifecycleRules permission. Adding that permission then causes bbackup's safe-capability allowlist/native lock-reader qualification to reject the key as unknown.

Propose adding the read-only readBucketLifecycleRules capability to _SAFE_CAPABILITIES in bbackup/b2.py. Preserve all bucket/prefix checks and rejection of administrative/unknown write permissions. The allowlist does not grant permissions and must not claim recovery/protection qualification.

Observed scoped checkpoint profile: listBuckets, readBuckets, listFiles, readFiles, writeFiles, deleteFiles, readBucketLifecycleRules. This is a checkpoint role, not the no-permanent-delete restricted source writer.

Observed separate metadata/maintenance SDK profile: listBuckets, readBuckets, listFiles, readFiles, readBucketRetentions, readFileRetentions, readFileLegalHolds, deleteFiles, readBucketLifecycleRules. Its delete authority likewise does not qualify it as a restricted source writer.

Tests cover safe scoped lifecycle-read assessment, native B2 version-lock reader acceptance, and continued rejection of writeBucketLifecycleRules, writeBuckets, and unknown future write capabilities.

Provider reference: https://www.backblaze.com/docs/cloud-storage-s3-compatible-app-keys

5. Additional discovered defect: nested lock queries lose cache-free fallback

No fix for this is included in the attached proposal. When HOME and XDG_CACHE_HOME are absent, the initial native operation can receive --no-cache, but nested _lock_query commands rebuild engine arguments without inheriting it. The nested Restic invocation then fails because no cache home exists; a finalizer failure can leave the operation requiring reconciliation.

Reproduction: run proposed lock inspection with a valid repository/key/password environment, no HOME/XDG_CACHE_HOME and no explicit cache option; compare initial and nested Restic argument lists. A protected explicit HOME was used as a deployment workaround. Upstream should propagate the resolved cache policy consistently and add a minimal-environment regression test.

Validation evidence and limits

  • Private rc2 proposal: 1,296 available tests passed; rc3 lifecycle-read addition: 1,301 available tests passed, including 42 focused B2 tests.
  • In both runs, 13 live Docker integration tests were excluded because the host has no Docker daemon. Do not interpret the available-test result as Docker qualification.
  • Lint, compilation, generated catalog/schema checks, version alignment, Markdown, publishing-readiness and whitespace checks passed in the private checkout. Dependencies were unchanged.
  • Disposable local root candidate drill passed capture, live-lock refusal, own-host dead-PID stale unlock, a zero-removal 12/14/8 retention plan, and byte-verified small-file restore.
  • Point-in-time live scoped B2 metadata checks passed lifecycle inspection (versioning enabled, zero lifecycle rules), bucket access and version listing after adding the lifecycle-read capability. These checks do not establish recovery-window, Object Lock, central deletion or provider protection guarantees.
  • The original lifecycle-403 checkpoint produced no recovery kit or signed acceptance. It was explicitly reconciled as failed after observing zero Restic processes, zero B2 locks and unchanged snapshot inventory. No successful signed daily checkpoint is claimed.

The private candidate versions, release-number changes, changelog wording, generated version headers and packaging metadata are not release requests. Upstream owns release selection and acceptance. No credentials, encrypted payloads, provider object identities, private host paths or service logs are included here.

Proposed acceptance

  • Review each change independently against the existing native operation, lease, receipt and reconciliation boundaries.
  • Run the full supported test matrix, including Docker and relevant Restic versions, upstream.
  • Preserve fail-closed parsing, replica protection and no-replay behavior; prove changed lock sets/tokens and uncertain outcomes cannot trigger unlock.
  • Establish the supported least-privilege capability split without conflating lifecycle visibility with source protection.
  • Resolve or explicitly document the nested cache-policy defect.
  • Publish supported behavior through the normal upstream release process before deployment integration.

Complete proposed runtime/schema/test diff

The diff excludes documentation, release/version-number edits and packaging-only churn; all behavioral code and test changes are included. Generated production schemas/catalog changes are included where they define the new commands.

Proposed patch against v2.0.5 (code and tests)
diff --git a/bbackup/__init__.py b/bbackup/__init__.py
index 31f32e6..3f28f3f 100644
--- a/bbackup/__init__.py
+++ b/bbackup/__init__.py
@@ -3,5 +3,5 @@ bbackup - Local-first Linux backup and restore
 Encrypted restic-based workflows; legacy Docker commands remain available.
 """
 
-__version__ = "2.0.5"
+__version__ = "2.0.6-rc.3"
 __author__ = "Slavic Kozyuk / Crux Experts LLC"
diff --git a/bbackup/b2.py b/bbackup/b2.py
index e04a280..e4bde39 100644
--- a/bbackup/b2.py
+++ b/bbackup/b2.py
@@ -37,7 +37,7 @@ _SAFE_CAPABILITIES = {
     "listBuckets", "listAllBucketNames", "listFiles", "readFiles", "writeFiles",
     "readBuckets", "readBucketEncryption", "readBucketRetentions",
     "readFileRetentions", "readFileLegalHolds", "readBucketReplications",
-    "readBucketNotifications",
+    "readBucketNotifications", "readBucketLifecycleRules",
 }
 _INSPECTION_CAPABILITIES = {"listBuckets", "listFiles", "readFiles"}
 _PROFILE_CAPABILITIES = _INSPECTION_CAPABILITIES | {"writeFiles"}
diff --git a/bbackup/cli_metadata.py b/bbackup/cli_metadata.py
index 1f5fa21..852abaa 100644
--- a/bbackup/cli_metadata.py
+++ b/bbackup/cli_metadata.py
@@ -1956,6 +1956,8 @@ PRODUCTION_COMMANDS: dict[str, ProductionCommand] = {
     "jobs run": {"summary": "Capture locally and copy explicit successful snapshots.", "fields": {"name": "string", "quiet_administrative_window_confirmed": "boolean"}},
     "repositories list": {"summary": "List declared repositories without host credentials.", "fields": {}},
     "repositories init": {"summary": "Initialize an encrypted repository.", "fields": {"name": "string", "source": "optional-string"}},
+    "repositories locks": {"summary": "Inspect a bounded encrypted lock set and create an exact review token; does not remove locks.", "fields": {"name": "string"}},
+    "repositories unlock-stale": {"summary": "Remove only reviewed own-host dead-process locks during an explicitly confirmed quiescent window; never remove-all.", "fields": {"name": "string", "review_token": "string", "approved": "boolean", "quiescent_window_confirmed": "boolean"}},
     "repositories check": {"summary": "Read and verify repository data.", "fields": {"name": "string"}},
     "snapshots list": {"summary": "List successful local snapshot receipts.", "fields": {"limit": "limit", "offset": "offset"}},
     "snapshots copy": {"summary": "Copy a successful snapshot into an independent repository.", "fields": {"source": "string", "destination": "string", "snapshot": "string"}},
diff --git a/bbackup/data/cli-skills.md b/bbackup/data/cli-skills.md
index c13d983..d4b73aa 100644
--- a/bbackup/data/cli-skills.md
+++ b/bbackup/data/cli-skills.md
@@ -1,6 +1,6 @@
 # CLI skills catalog
 
-> Generated from the bbackup/bbman CLI metadata. Version: 2.0.5. This catalog is authoritative for this version.
+> Generated from the bbackup/bbman CLI metadata. Version: 2.0.6-rc.3. This catalog is authoritative for this version.
 > Source: `bbackup/cli_metadata.py` rendered by `scripts/generate_cli_skills.py`; run the generator's `--check` mode before publishing.
 
 ## bbackup
diff --git a/bbackup/data/production-schemas.json b/bbackup/data/production-schemas.json
index da63daf..4c5d590 100644
--- a/bbackup/data/production-schemas.json
+++ b/bbackup/data/production-schemas.json
@@ -931,6 +931,47 @@
     "required": [],
     "type": "object"
   },
+  "repositories locks": {
+    "$schema": "https://json-schema.org/draft/2020-12/schema",
+    "additionalProperties": false,
+    "properties": {
+      "name": {
+        "minLength": 1,
+        "type": "string"
+      }
+    },
+    "required": [
+      "name"
+    ],
+    "type": "object"
+  },
+  "repositories unlock-stale": {
+    "$schema": "https://json-schema.org/draft/2020-12/schema",
+    "additionalProperties": false,
+    "properties": {
+      "approved": {
+        "default": false,
+        "type": "boolean"
+      },
+      "name": {
+        "minLength": 1,
+        "type": "string"
+      },
+      "quiescent_window_confirmed": {
+        "default": false,
+        "type": "boolean"
+      },
+      "review_token": {
+        "minLength": 1,
+        "type": "string"
+      }
+    },
+    "required": [
+      "name",
+      "review_token"
+    ],
+    "type": "object"
+  },
   "restore": {
     "$schema": "https://json-schema.org/draft/2020-12/schema",
     "additionalProperties": false,
diff --git a/bbackup/models.py b/bbackup/models.py
index 3fb345c..7972c5f 100644
--- a/bbackup/models.py
+++ b/bbackup/models.py
@@ -192,12 +192,21 @@ class Retention:
     cloud_weekly: int = 8
     cloud_monthly: int = 12
     protection_days: int = 30
+    local_last: int = 0
+    local_weekly: int = 0
 
     @classmethod
     def parse(cls, raw):
         fields = set(cls.__dataclass_fields__)
         raw = _object(raw, fields, set())
-        values = {key: _positive(value) for key, value in raw.items()}
+        values = {}
+        for key, value in raw.items():
+            if key in {"local_last", "local_weekly"}:
+                if type(value) is not int or value < 0:
+                    raise ConfigurationError("Optional local retention counts must be nonnegative integers")
+                values[key] = value
+            else:
+                values[key] = _positive(value)
         if values.get("protection_days", 30) < 30:
             raise ConfigurationError(
                 "Cloud recovery protection must be at least thirty days"
diff --git a/bbackup/production_operations.py b/bbackup/production_operations.py
index 7af26ed..7a3fc07 100644
--- a/bbackup/production_operations.py
+++ b/bbackup/production_operations.py
@@ -169,6 +169,11 @@ def _service_operation(service, command, values, config_path, bindings_path, can
         return [asdict(repo) for repo in service.config.repositories]
     if command == "repositories init":
         return service.initialize(values["name"], source=values.get("source"), cancel=cancel)
+    if command == "repositories locks":
+        return service.repository_locks(values["name"], cancel=cancel)
+    if command == "repositories unlock-stale":
+        return service.unlock_stale(values["name"], values["review_token"], values["approved"],
+            quiescent_window_confirmed=values["quiescent_window_confirmed"], cancel=cancel)
     if command == "repositories check":
         return service.check(values["name"], cancel=cancel)
     if command == "snapshots list":
diff --git a/bbackup/service.py b/bbackup/service.py
index f6f6fb3..eaf4cf9 100644
--- a/bbackup/service.py
+++ b/bbackup/service.py
@@ -12,6 +12,8 @@ from pathlib import Path
 import re
 import shutil
 import sqlite3
+import socket
+import time
 import stat
 import sys
 import tempfile
@@ -1418,6 +1420,114 @@ class BackupService:
         return {"operation_id": plan.operation_id, "source_snapshot_id": snapshot,
                 "destination_snapshot_id": copied, "destination_repository": destination}
 
+    def _lock_query(self, plan, argv, cancel):
+        query = OperationPlan(operation_id=plan.operation_id, repository_id=plan.repository_id,
+                              label=plan.label, argv=tuple(argv), env=plan.env, timeout_seconds=30)
+        result = self.runner.run(query, cancel_event=cancel)
+        if (result.status is not OperationStatus.SUCCEEDED or result.exit_code != 0 or
+                result.stdout_bytes != len(result.stdout_tail) or result.stdout_bytes > 65536):
+            raise ServiceError("Repository lock inspection was incomplete")
+        return result
+
+    def _lock_inventory(self, repository, plan, listing, cancel):
+        # Restic list emits one complete object ID per line, even with --json.
+        if (listing.status is not OperationStatus.SUCCEEDED or listing.exit_code != 0 or
+                listing.stdout_bytes != len(listing.stdout_tail) or listing.stdout_bytes > 65536):
+            raise ServiceError("Repository lock listing was incomplete")
+        try:
+            ids = listing.stdout_tail.decode("ascii").splitlines()
+        except UnicodeError:
+            raise ServiceError("Repository lock listing was invalid") from None
+        if (len(ids) > 64 or len(set(ids)) != len(ids) or
+                any(not re.fullmatch(r"[0-9a-f]{64}", item) for item in ids)):
+            raise ServiceError("Repository lock listing was invalid or exceeds the inspection bound")
+        engine, records = self._engine(repository), []
+        hostname, uid = socket.gethostname(), os.getuid()
+        deadline = time.monotonic() + 60
+        for lock_id in sorted(ids):
+            if time.monotonic() > deadline:
+                raise ServiceError("Repository lock inspection exceeded its time bound")
+            result = self._lock_query(plan, [*engine.base_args(), "--no-lock", "cat", "lock", lock_id], cancel)
+            try:
+                payload = strict_json(result.stdout_tail.decode("utf-8"))
+                if (not isinstance(payload, dict) or
+                        set(payload) - {"time", "exclusive", "hostname", "username", "pid", "uid", "gid"} or
+                        not {"time", "exclusive", "hostname", "pid"}.issubset(payload) or
+                        type(payload["exclusive"]) is not bool or
+                        type(payload["pid"]) is not int or not 0 < payload["pid"] < 2**31 or
+                        any(type(payload.get(key, 0)) is not int or not 0 <= payload.get(key, 0) < 2**32
+                            for key in ("uid", "gid")) or
+                        any(not isinstance(payload.get(key, ""), str) or len(payload.get(key, "")) > 255 or
+                            any(ord(char) < 32 for char in payload.get(key, ""))
+                            for key in ("hostname", "username")) or not payload["hostname"] or
+                        not isinstance(payload["time"], str) or len(payload["time"]) > 64):
+                    raise ValueError()
+                stamp = datetime.fromisoformat(payload["time"].replace("Z", "+00:00"))
+                if stamp.tzinfo is None:
+                    raise ValueError()
+            except (ValueError, UnicodeError):
+                raise ServiceError("Repository lock payload was invalid") from None
+            own = payload["hostname"] == hostname and payload.get("uid", 0) == uid
+            dead = False
+            if own:
+                try:
+                    os.kill(payload["pid"], 0)
+                except ProcessLookupError:
+                    dead = True
+                except (PermissionError, OSError):
+                    pass
+            records.append({"id": lock_id, "payload": payload, "same_host_and_uid": own,
+                            "pid_dead": dead})
+        proof = {"repository_identity": repository_key(self._identity(repository)),
+                 "hostname": hostname, "uid": uid, "locks": records}
+        token = hashlib.sha256(json.dumps(proof, sort_keys=True, separators=(",", ":")).encode()).hexdigest()
+        return {"repository": repository, "locks": records, "review_token": token,
+                "unlock_eligible": bool(records) and all(row["same_host_and_uid"] and row["pid_dead"]
+                                                         for row in records),
+                "quiescence_required": True}
+
+    def repository_locks(self, repository, *, cancel=None):
+        """Inspect encrypted lock objects without taking or removing a Restic lock."""
+        engine, report = self._engine(repository), {}
+
+        def inspect(plan, result):
+            report.update(self._lock_inventory(repository, plan, result, cancel))
+
+        plan, _ = self._execute(repository, [*engine.base_args(), "--no-lock", "list", "locks"],
+                                label="inspect-locks", cancel=cancel, finalize=inspect,
+                                timeout_seconds=30)
+        return {"operation_id": plan.operation_id, **report}
+
+    def unlock_stale(self, repository, review_token, approved, *,
+                     quiescent_window_confirmed=False, cancel=None):
+        """Remove only reviewed own-host dead-PID locks through stock stale unlock."""
+        if (approved is not True or quiescent_window_confirmed is not True or
+                not isinstance(review_token, str) or not re.fullmatch(r"[0-9a-f]{64}", review_token)):
+            raise ServiceError("Lock removal requires an exact review token, approval, and quiescent window")
+        # Reject ordinary approval mistakes before entering a mutating operation.
+        reviewed = self.repository_locks(repository, cancel=cancel)
+        if reviewed["review_token"] != review_token or not reviewed["unlock_eligible"]:
+            raise ServiceError("Reviewed locks changed or include a live, foreign, or unknown process")
+        engine, removed = self._engine(repository), []
+
+        def unlock(plan, listing):
+            current = self._lock_inventory(repository, plan, listing, cancel)
+            if current["review_token"] != review_token or not current["unlock_eligible"]:
+                raise ServiceError("Lock set changed before removal; review repository state")
+            # No remove-all, no backend deletes. External actors must remain
+            # quiescent: Restic's ordinary unlock is repository-wide by design.
+            self._lock_query(plan, [*engine.base_args(), "unlock"], cancel)
+            after = self._lock_query(plan, [*engine.base_args(), "--no-lock", "list", "locks"], cancel)
+            if after.stdout_tail.strip():
+                raise ServiceError("Repository lock removal could not be verified")
+            removed.extend(row["id"] for row in current["locks"])
+
+        plan, _ = self._execute(repository, [*engine.base_args(), "--no-lock", "list", "locks"],
+                                label="unlock-stale", cancel=cancel, mutating=True,
+                                finalize=unlock, timeout_seconds=30)
+        return {"operation_id": plan.operation_id, "repository": repository,
+                "removed_lock_ids": removed, "verified_no_locks": True}
+
     def check(self, repository, *, cancel=None):
         engine = self._engine(repository)
         plan, _ = self._execute(repository, [*engine.check_args(), "--read-data"], label="check", cancel=cancel)
@@ -1607,7 +1717,7 @@ class BackupService:
         }
 
     def _retention_snapshot_plan(self, job, operation_plan, cancel):
-        """Inspect snapshots and restic's daily forget selection under one lease."""
+        """Inspect snapshots and Restic's combined keep selection under one lease."""
         engine = self._engine(job.repository)
         tag = f"bbackup-job={job.name}"
         forget_args = [
@@ -1616,6 +1726,11 @@ class BackupService:
             "--group-by", "host", "--tag", tag,
         ]
 
+        for option, count in (("--keep-last", job.retention.local_last),
+                              ("--keep-weekly", job.retention.local_weekly)):
+            if count > 0:
+                forget_args.extend([option, str(count)])
+
         def run_read(argv, message):
             plan = OperationPlan(
                 operation_id=operation_plan.operation_id,
@@ -1729,6 +1844,15 @@ class BackupService:
                         continue
                     raise ServiceError("Restic retention selection is incomplete")
                 snapshots = group["remove"]
+                if snapshots is None:
+                    # Restic serializes an empty removal slice as null. Accept
+                    # only a genuine keep-all group with complete kept IDs.
+                    keep = group.get("keep")
+                    if not isinstance(keep, list) or not keep or any(not isinstance(item, dict) for item in keep):
+                        raise ServiceError("Restic retention keep-all group is invalid")
+                    for item in keep:
+                        _snapshot_id(item.get("id"))
+                    snapshots = []
                 if not isinstance(snapshots, list):
                     raise ServiceError("Restic retention selection is invalid")
                 for item in snapshots:
@@ -1830,6 +1954,8 @@ class BackupService:
 
         policy = {
             "local_daily": job.retention.local_daily,
+            "local_last": job.retention.local_last,
+            "local_weekly": job.retention.local_weekly,
             "group_by": "host",
             "job_tag": job_tag,
         }
diff --git a/tests/test_b2.py b/tests/test_b2.py
index 563aefe..4b718fe 100644
--- a/tests/test_b2.py
+++ b/tests/test_b2.py
@@ -329,3 +329,39 @@ def test_vendor_http_retry_uses_polite_backoff(monkeypatch, status):
     ) == {"ok": True}
     assert len(attempts) == 2
     assert delays == ([3] if status == 429 else [1.0])
+
+
+def test_lifecycle_rule_read_capability_is_safe_for_scoped_restricted_source():
+    capabilities = ["listBuckets", "listFiles", "readFiles", "writeFiles", "readBucketLifecycleRules"]
+    result = inspect_sdk("backup-bucket", prefix="restic/", api=api(capabilities))
+    profile = result["restricted_source_profile"]
+    assert profile["status"] == "eligible_from_observed_metadata"
+    assert "readBucketLifecycleRules" in profile["observed_capabilities"]
+    assert profile["scope"]["key_bucket_matches_selected_bucket"]
+    assert profile["scope"]["requested_prefix_within_machine_prefix"]
+    assert result["credential_administration_denied"] is True
+    assert result["unsafe_capabilities"] == []
+    assert result["protection_qualified"] is False
+
+
+def test_native_lock_reader_accepts_scoped_lifecycle_read_capability():
+    value = _native_lock_api()
+    capabilities = list(value.account_info.get_allowed()["capabilities"]) + ["readBucketLifecycleRules"]
+    reader = B2VersionLockReader(
+        "backup-bucket", "bucket-id-1", "restic/", "https://s3.us-west-004.backblazeb2.com",
+        api=_native_lock_api(allowed={"capabilities": capabilities}),
+        access_key_id="key", secret_access_key="secret")
+    from datetime import datetime, timezone
+    evidence, held = reader.read("restic/data", "file-v1", now=datetime.now(timezone.utc))
+    assert evidence["provider"] == "b2-native" and held is False
+
+
+@pytest.mark.parametrize("unsafe", ["writeBucketLifecycleRules", "writeBuckets", "futureWritePermission"])
+def test_lifecycle_read_does_not_allow_write_admin_or_unknown_capabilities(unsafe):
+    capabilities = ["listBuckets", "listFiles", "readFiles", "writeFiles", "readBucketLifecycleRules", unsafe]
+    result = inspect_sdk("backup-bucket", prefix="restic/", api=api(capabilities))
+    profile = result["restricted_source_profile"]
+    assert profile["status"] == "unqualified"
+    assert {"administrative_capability_present", "unrecognized_capability_present"} & set(profile["reasons"])
+    assert result["credential_administration_denied"] is False
+    assert result["unsafe_capabilities"]
diff --git a/tests/test_local_retention.py b/tests/test_local_retention.py
new file mode 100644
index 0000000..6f16b04
--- /dev/null
+++ b/tests/test_local_retention.py
@@ -0,0 +1,125 @@
+# ruff: noqa: F811
+"""Optional local keep rules use native planning, evidence, and approval."""
+from dataclasses import replace
+import json
+import shutil
+
+import pytest
+
+from bbackup.models import ConfigurationError, Retention
+from bbackup.service import BackupService, ServiceError
+from tests.test_service import service  # noqa: F401
+from tests.test_service import _mock_retention_restic, _record_retention_source, _retention_snapshot
+
+
+def test_optional_keep_counts_default_disabled_and_accept_zero():
+    policy = Retention.parse({})
+    assert policy.local_last == policy.local_weekly == 0
+    policy = Retention.parse({"local_last": 12, "local_daily": 14, "local_weekly": 8})
+    assert (policy.local_last, policy.local_daily, policy.local_weekly) == (12, 14, 8)
+    assert Retention.parse({"local_last": 0, "local_weekly": 0}).local_last == 0
+
+
+@pytest.mark.parametrize("field", ["local_last", "local_weekly"])
+@pytest.mark.parametrize("value", [-1, True, False, 1.0, "12", None])
+def test_optional_keep_counts_reject_non_integer_or_negative(field, value):
+    with pytest.raises(ConfigurationError):
+        Retention.parse({field: value})
+
+
+@pytest.mark.parametrize("field", ["local_last", "local_weekly"])
+def test_optional_policy_change_invalidates_reviewed_native_token(service, monkeypatch, field):
+    snapshot = "a" * 64
+    _record_retention_source(service, snapshot, required=())
+    state = _mock_retention_restic(service, monkeypatch, [_retention_snapshot(snapshot)], [snapshot])
+    plan = service.retention_plan("daily")
+    job = service.config.jobs[0]
+    service.config = replace(service.config, jobs=(replace(job, retention=replace(job.retention, **{field: 1})),))
+    with pytest.raises(ServiceError, match="approval is stale"):
+        service.retention_apply("daily", plan["plan_token"], True)
+    assert state["apply_args"] == []
+    assert plan["policy"][field] == 0
+
+
+def test_disabled_optional_rules_leave_original_forget_arguments(service, monkeypatch):
+    calls = []
+    _mock_retention_restic(service, monkeypatch, [], [])
+    mocked = service.runner.run
+
+    def observe(plan, **kwargs):
+        calls.append(plan.argv)
+        return mocked(plan, **kwargs)
+
+    monkeypatch.setattr(service.runner, "run", observe)
+    service.retention_plan("daily")
+    forget = next(argv for argv in calls if "forget" in argv)
+    assert "--keep-last" not in forget and "--keep-weekly" not in forget
+    assert "--keep-daily" in forget
+
+
+@pytest.mark.integration
+@pytest.mark.skipif(shutil.which("restic") is None, reason="restic unavailable")
+def test_real_restic_keep_rules_are_union_and_old_pending_copy_stays_protected(service, monkeypatch):
+    service.initialize("local")
+    job = service.config.jobs[0]
+    service.config = replace(service.config, jobs=(replace(
+        job, retention=replace(job.retention, local_daily=1, local_last=2, local_weekly=3)),))
+    original = service.runner.run
+    clock = {"time": None}
+
+    def dated_capture(plan, **kwargs):
+        if "backup" in plan.argv:
+            split = plan.argv.index("backup") + 1
+            plan = replace(plan, argv=(*plan.argv[:split], "--time", clock["time"], *plan.argv[split:]))
+        return original(plan, **kwargs)
+
+    monkeypatch.setattr(service.runner, "run", dated_capture)
+    snapshots = []
+    for index, stamp in enumerate(["2026-01-01 00:00:00", "2026-01-08 00:00:00",
+                                   "2026-01-15 00:00:00", "2026-01-22 00:00:00",
+                                   "2026-01-29 00:00:00", "2026-01-29 01:00:00"]):
+        clock["time"] = stamp
+        snapshots.append(service.capture("daily")["snapshot_id"])
+        if index == 0:
+            # Retain the first capture's genuine required-copy receipt even
+            # though later captures have no off-host requirement.
+            service.config = replace(service.config, jobs=(replace(service.config.jobs[0], replicas=()),))
+    report = service.retention_plan("daily")
+    assert report["policy"]["local_last"] == 2
+    assert report["policy"]["local_weekly"] == 3
+    assert report["retained_by_policy_count"] == 4
+    assert report["target_snapshot_ids"] == [snapshots[1]]
+    assert report["protected_snapshots"] == [{"snapshot_id": snapshots[0], "reason": "required_copy_pending"}]
+    assert len(service.snapshots()) == 6  # Planning never forgets snapshots.
+
+
+def test_explicit_null_removal_requires_valid_nonempty_keep_group():
+    raw = json.dumps([{"keep": [{"id": "a" * 64}], "remove": None}]).encode()
+    assert BackupService._forget_snapshot_ids(raw) == set()
+
+
+@pytest.mark.parametrize("group", [{"keep": [{"id": "a" * 64}]}, {"remove": None},
+                                    {"keep": None, "remove": None}, {"keep": [], "remove": None},
+                                    {"keep": ["invalid"], "remove": None},
+                                    {"keep": [{"id": "short"}], "remove": None},
+                                    {"keep": [{"id": "a" * 64}], "remove": "invalid"}])
+def test_missing_or_malformed_removal_group_still_holds(group):
+    with pytest.raises(ServiceError):
+        BackupService._forget_snapshot_ids(json.dumps([group]).encode())
+
+
+@pytest.mark.integration
+@pytest.mark.skipif(shutil.which("restic") is None, reason="restic unavailable")
+def test_real_one_snapshot_keep_all_accepts_restic_null_removals(service):
+    job = service.config.jobs[0]
+    service.config = replace(service.config, jobs=(replace(job, replicas=(), retention=replace(
+        job.retention, local_last=12, local_daily=14, local_weekly=8)),))
+    service.initialize("local")
+    captured = service.capture("daily")
+    report = service.retention_plan("daily")
+    assert report["target_snapshot_ids"] == [] and report["target_count"] == 0
+    assert report["retained_by_policy_count"] == report["total_snapshots"] == 1
+    assert report["policy"]["local_last"] == 12
+    assert report["policy"]["local_daily"] == 14
+    assert report["policy"]["local_weekly"] == 8
+    assert service.snapshots()[0]["snapshot_id"] == captured["snapshot_id"]
diff --git a/tests/test_repository_locks.py b/tests/test_repository_locks.py
new file mode 100644
index 0000000..ad5740a
--- /dev/null
+++ b/tests/test_repository_locks.py
@@ -0,0 +1,287 @@
+# ruff: noqa: F811
+"""Reviewed native lock maintenance; only disposable repositories are exercised."""
+import json
+import os
+import shutil
+import socket
+import subprocess
+import time
+
+import pytest
+
+from bbackup.operations import OperationPlan, OperationStatus, UncertainOperationError
+from bbackup.production_operations import _service_operation, validate_operation_input
+from bbackup.service import ServiceError
+from tests.test_service import service, _run  # noqa: F401
+
+
+LOCK = "a" * 64
+
+
+def payload(**changes):
+    return {"time": "2026-10-23T12:00:00Z", "exclusive": False,
+            "hostname": socket.gethostname(), "pid": 2147483000, "uid": os.getuid(), **changes}
+
+
+@pytest.fixture
+def backend(service, monkeypatch):
+    locks, calls = {LOCK: payload()}, []
+
+    def run(plan, **kwargs):
+        calls.append(plan.argv)
+        if "list" in plan.argv:
+            return _run(plan, stdout="".join(key + "\n" for key in locks).encode())
+        if "cat" in plan.argv:
+            return _run(plan, stdout=json.dumps(locks[plan.argv[-1]]).encode())
+        assert plan.argv[-1] == "unlock"
+        locks.clear()
+        return _run(plan)
+
+    monkeypatch.setattr(service.runner, "run", run)
+    return locks, calls
+
+
+def test_inspection_is_readonly_and_exact_token_binds_payload(service, backend):
+    locks, calls = backend
+    first = service.repository_locks("local")
+    assert first["unlock_eligible"] is True
+    assert first["locks"][0]["pid_dead"] is True
+    assert all("--no-lock" in call for call in calls)
+    assert not any("unlock" in call for call in calls)
+    locks[LOCK]["exclusive"] = True
+    assert service.repository_locks("local")["review_token"] != first["review_token"]
+
+
+@pytest.mark.parametrize("changes", [{"hostname": "foreign"}, {"pid": os.getpid()},
+                                     {"uid": os.getuid() + 1}])
+def test_live_foreign_or_other_uid_is_never_eligible(service, backend, changes):
+    locks, calls = backend
+    locks[LOCK] = payload(**changes)
+    report = service.repository_locks("local")
+    assert report["unlock_eligible"] is False
+    with pytest.raises(ServiceError):
+        service.unlock_stale("local", report["review_token"], True, quiescent_window_confirmed=True)
+    assert not any("unlock" in call for call in calls)
+
+
+@pytest.mark.parametrize("field,value", [("pid", True), ("pid", 0), ("uid", -1),
+                                        ("time", "invalid"), ("hostname", "bad\nname"),
+                                        ("exclusive", 1)])
+def test_malformed_payload_fails_closed(service, backend, field, value):
+    locks, calls = backend
+    locks[LOCK][field] = value
+    with pytest.raises(ServiceError):
+        service.repository_locks("local")
+    assert not any("unlock" in call for call in calls)
+
+
+@pytest.mark.parametrize("approved,quiet,token", [(False, True, "a" * 64),
+                                                  (True, False, "a" * 64),
+                                                  (True, True, "wrong")])
+def test_explicit_approval_and_quiescence_required_before_any_dispatch(service, backend, approved, quiet, token):
+    _, calls = backend
+    with pytest.raises(ServiceError):
+        service.unlock_stale("local", token, approved, quiescent_window_confirmed=quiet)
+    assert not calls
+
+
+def test_wrong_or_changed_review_token_never_dispatches_unlock(service, backend):
+    locks, calls = backend
+    token = service.repository_locks("local")["review_token"]
+    locks[LOCK]["time"] = "2026-10-23T12:01:00Z"
+    with pytest.raises(ServiceError):
+        service.unlock_stale("local", token, True, quiescent_window_confirmed=True)
+    assert not any("unlock" in call for call in calls)
+
+
+def test_approved_unlock_uses_native_backend_and_verifies_absence(service, backend):
+    _, calls = backend
+    report = service.repository_locks("local")
+    result = service.unlock_stale("local", report["review_token"], True, quiescent_window_confirmed=True)
+    assert result["removed_lock_ids"] == [LOCK]
+    assert result["verified_no_locks"] is True
+    assert sum(call[-1] == "unlock" for call in calls) == 1
+    assert not any("--remove-all" in call for call in calls)
+    assert calls[-1][-2:] == ("list", "locks")
+
+
+def test_lock_set_changes_under_mutation_lease_hold_without_unlock(service, backend, monkeypatch):
+    locks, calls = backend
+    report = service.repository_locks("local")
+    original = service.runner.run
+    listings = 0
+
+    def run(plan, **kwargs):
+        nonlocal listings
+        if "list" in plan.argv:
+            listings += 1
+            if listings == 2:  # Re-read after the mutating native lease begins.
+                locks["b" * 64] = payload(hostname="foreign")
+        return original(plan, **kwargs)
+
+    monkeypatch.setattr(service.runner, "run", run)
+    with pytest.raises(ServiceError):
+        service.unlock_stale("local", report["review_token"], True, quiescent_window_confirmed=True)
+    assert not any("unlock" in call for call in calls)
+    with pytest.raises(UncertainOperationError):
+        service.repository_locks("local")
+
+
+@pytest.mark.parametrize("listing", [b"short\n", (LOCK + "\n" + LOCK + "\n").encode(),
+                                     "".join(f"{number:064x}\n" for number in range(65)).encode()])
+def test_invalid_duplicate_or_excessive_ids_are_not_decrypted(service, monkeypatch, listing):
+    calls = []
+
+    def run(plan, **kwargs):
+        calls.append(plan.argv)
+        return _run(plan, stdout=listing)
+
+    monkeypatch.setattr(service.runner, "run", run)
+    with pytest.raises(ServiceError):
+        service.repository_locks("local")
+    assert len(calls) == 1
+
+
+def test_no_locks_is_not_an_unlock_plan(service, backend):
+    backend[0].clear()
+    report = service.repository_locks("local")
+    assert report["locks"] == [] and report["unlock_eligible"] is False
+    with pytest.raises(ServiceError):
+        service.unlock_stale("local", report["review_token"], True, quiescent_window_confirmed=True)
+    assert not any("unlock" in call for call in backend[1])
+
+
+@pytest.mark.parametrize("phase", ["listing", "payload"])
+def test_truncated_listing_or_payload_fails_closed(service, backend, monkeypatch, phase):
+    original = service.runner.run
+
+    def run(plan, **kwargs):
+        result = original(plan, **kwargs)
+        if (phase == "listing" and "list" in plan.argv) or (phase == "payload" and "cat" in plan.argv):
+            from dataclasses import replace
+            return replace(result, stdout_bytes=result.stdout_bytes + 1)
+        return result
+
+    monkeypatch.setattr(service.runner, "run", run)
+    with pytest.raises(ServiceError):
+        service.repository_locks("local")
+    assert not any("unlock" in call for call in backend[1])
+
+
+@pytest.mark.parametrize("failure", ["remaining", "query_failed"])
+def test_post_unlock_verification_failure_retains_uncertainty(service, backend, monkeypatch, failure):
+    report = service.repository_locks("local")
+    original = service.runner.run
+    unlocked = False
+
+    def run(plan, **kwargs):
+        nonlocal unlocked
+        if plan.argv[-1] == "unlock":
+            unlocked = True
+        elif unlocked and "list" in plan.argv:
+            if failure == "remaining":
+                return _run(plan, stdout=(LOCK + "\n").encode())
+            return _run(plan, status=OperationStatus.FAILED, exit_code=1)
+        return original(plan, **kwargs)
+
+    monkeypatch.setattr(service.runner, "run", run)
+    with pytest.raises(ServiceError):
+        service.unlock_stale("local", report["review_token"], True, quiescent_window_confirmed=True)
+    assert unlocked
+    with pytest.raises(UncertainOperationError):
+        service.repository_locks("local")
+
+
+def test_native_uncertain_barrier_is_not_bypassed(service, backend):
+    plan = OperationPlan.create(service._identity("local"), "copy", ["restic", "copy"])
+    with service.ledger.begin(plan):
+        pass  # Unfinished native lease deliberately records uncertainty.
+    with pytest.raises(UncertainOperationError):
+        service.repository_locks("local")
+    assert not backend[1]
+
+
+def test_mutation_failure_stays_uncertain(service, backend, monkeypatch):
+    report = service.repository_locks("local")
+    original = service.runner.run
+
+    def run(plan, **kwargs):
+        if plan.argv[-1] == "unlock":
+            return _run(plan, status=OperationStatus.FAILED, exit_code=1)
+        return original(plan, **kwargs)
+
+    monkeypatch.setattr(service.runner, "run", run)
+    with pytest.raises(ServiceError):
+        service.unlock_stale("local", report["review_token"], True, quiescent_window_confirmed=True)
+    with pytest.raises(UncertainOperationError):
+        service.repository_locks("local")
+
+
+def test_public_dispatch_and_boolean_schema(service, backend):
+    report = _service_operation(service, "repositories locks", {"name": "local"}, None, None, None)
+    values = validate_operation_input("repositories unlock-stale", {
+        "name": "local", "review_token": report["review_token"], "approved": True,
+        "quiescent_window_confirmed": True})
+    result = _service_operation(service, "repositories unlock-stale", values, None, None, None)
+    assert result["removed_lock_ids"] == [LOCK]
+
+
+def test_cli_commands_use_fresh_enrolled_dispatch_and_strict_inputs(service, monkeypatch):
+    from tests.test_production_cli import invoke
+    calls = []
+
+    def inspect(self, name, *, cancel=None):
+        calls.append((name, cancel))
+        return {"locks": [], "review_token": "a" * 64}
+
+    monkeypatch.setattr(type(service), "repository_locks", inspect)
+    result = invoke(service, ["repositories", "locks", "--name", "local"])
+    assert result.exit_code == 0, result.output
+    assert json.loads(result.output)["data"]["locks"] == []
+    assert calls[0][0] == "local"
+    schema = invoke(service, ["repositories", "unlock-stale", "--schema"])
+    fields = json.loads(schema.output)["data"]["properties"]
+    assert fields["approved"]["type"] == "boolean"
+    assert "review_token" in fields and "remove_all" not in fields
+    invalid = invoke(service, ["repositories", "unlock-stale", "--input-json",
+                              '{"name":"local","review_token":"a","approved":"yes"}'])
+    assert invalid.exit_code == 2
+
+
+@pytest.mark.integration
+@pytest.mark.skipif(shutil.which("restic") is None, reason="restic unavailable")
+def test_real_killed_stdin_backup_own_lock_inspection_and_native_removal(service):
+    # Native service initializes the disposable local repository. Holding stdin
+    # open blocks backup after lock creation; SIGKILL intentionally skips cleanup.
+    service.initialize("local")
+    service.capture("daily")
+    engine = service._engine("local")
+    before = subprocess.run([*engine.base_args(), "snapshots"], capture_output=True, check=True).stdout
+    process = subprocess.Popen([*engine.base_args(), "backup", "--stdin", "--stdin-filename", "blocked"],
+                               stdin=subprocess.PIPE, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
+    try:
+        for _ in range(100):
+            report = service.repository_locks("local")
+            if report["locks"]:
+                break
+            time.sleep(.05)
+        else:
+            pytest.fail("Disposable backup did not acquire a lock")
+        assert report["unlock_eligible"] is False
+        with pytest.raises(ServiceError):
+            service.unlock_stale("local", report["review_token"], True, quiescent_window_confirmed=True)
+        process.kill()
+        process.wait(timeout=5)
+        report = service.repository_locks("local")
+        assert report["unlock_eligible"] is True
+        result = service.unlock_stale("local", report["review_token"], True, quiescent_window_confirmed=True)
+        assert result["verified_no_locks"]
+        assert service.repository_locks("local")["locks"] == []
+        after = subprocess.run([*engine.base_args(), "snapshots"], capture_output=True, check=True).stdout
+        assert json.loads(before) == json.loads(after)
+    finally:
+        if process.poll() is None:
+            process.kill()
+            process.wait(timeout=5)
+        if process.stdin:
+            process.stdin.close()

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions