carlos / platform Public

store: fix Astra round 1 (no off, exact-version restore, older consoles)

- P1: there is no off. A suspended bucket lets an app's own PutObject or
  DeleteObject replace a null version, so the setter refuses
  enabled:false, the walks refuse an off block, EnsureVersioning only
  ever sets Enabled, and restore refuses a bucket that is not Enabled.
  The fake now writes null versions as S3 does.
- P1: the version listing pages (after/next, --after) and restore finds
  a version by id (StatVersion: HEAD naming the version), however many
  newer versions a writer piled on.
- P1: the CLI refuses an older console's answer that drops requested
  versioning, before provisioning or reporting success.
- P2: --keep-days is checked before any request; create never lowers
  retention (shared nextKeepDays); create with versioning is
  person-only.
- Copy review applied (Astra, as Luna is refused on this account).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by paul@keymail.dev 7cdd220e62ef6cf9e967775c57787c65dda21994 parent c805eaa
28 files changed, +1,184 −364
  • docs/parity.md +2 −2
  • docs/site/cli.md +19 −19
  • docs/site/media-conversion.md +1 −1
  • docs/superpowers/notes/copy-luna-brief-store-versioning.md +128 −0
  • docs/superpowers/notes/copy-luna-store-versioning.md +102 −0
  • docs/superpowers/notes/store-versioning-copy-deck.md +34 −34
  • docs/superpowers/reviews/CODEX-FINDINGS-store-versioning.md +109 −0
  • docs/superpowers/specs/2026-11-22-store-versioning-design.md +71 −32
  • infra/modules/region-host/README.md +1 −1
  • infra/modules/region-host/variables.tf +1 −1
  • instances_cli.go +4 −1
  • internal/console/apistore.go +14 −4
  • internal/console/apistoreversioning.go +81 −53
  • internal/console/apistoreversioning_test.go +79 −14
  • internal/console/routedecls.go +4 −4
  • internal/console/store_versioning_copy.go +16 −14
  • internal/objstore/aws_versioning.go +81 −36
  • internal/objstore/aws_versioning_test.go +106 −41
  • internal/objstore/memversioning.go +80 −21
  • internal/objstore/objstore.go +7 −5
  • internal/objstore/versioning.go +30 −16
  • internal/objstore/versioning_test.go +69 −8
  • internal/provision/store_versioning_census_test.go +4 −2
  • parity/cli.tsv +0 −1
  • parity/parity.tsv +1 −1
  • store.go +17 −10
  • store_versioning.go +50 −28
  • store_versioning_test.go +73 −15
diff --git a/docs/parity.md b/docs/parity.md
index 2efb38270..cb1fbcd8a 100644
--- a/docs/parity.md
+++ b/docs/parity.md
@@ -243,7 +243,7 @@ CLI rows are checked against the command registry (`parity/cli.tsv`).
| store-rotate | gap | `store rotate` | | [wp-email-storage](#wp-email-storage) | |
| store-scan | gap | `store scan request`<br>`store scan status`<br>`store scan grant`<br>`store scan revoke`<br>`store scan sweep`<br>`store scan enforce`<br>`store scan rotate-webhook-key` | | [wp-email-storage](#wp-email-storage) | |
| store-uploads | gap | `store uploads enable`<br>`store uploads status`<br>`store uploads disable` | | [wp-email-storage](#wp-email-storage) | |
-| store-versioning | gap | `store versioning on`<br>`store versioning off`<br>`store versioning status`<br>`store versions`<br>`store restore` | | [wp-email-storage](#wp-email-storage) | The console has no versioning page yet; store status shows whether it is on. |
+| store-versioning | gap | `store versioning on`<br>`store versioning status`<br>`store versions`<br>`store restore` | | [wp-email-storage](#wp-email-storage) | The console has no versioning page yet; store status shows whether it is on. |
| store-destroy | console-only | | `POST /a/{sqid}/apps/{app}/store/destroy` | | Needs a passkey. |
## team
@@ -332,7 +332,7 @@ Discussion #737.
- `store-rotate` (storage), CLI has `store rotate`
- `store-scan` (storage), CLI has `store scan request`, `store scan status`, `store scan grant`, `store scan revoke`, `store scan sweep`, `store scan enforce`, `store scan rotate-webhook-key`
- `store-uploads` (storage), CLI has `store uploads enable`, `store uploads status`, `store uploads disable`
-- `store-versioning` (storage), CLI has `store versioning on`, `store versioning off`, `store versioning status`, `store versions`, `store restore`
+- `store-versioning` (storage), CLI has `store versioning on`, `store versioning status`, `store versions`, `store restore`
- `email-enable` (email), CLI has `email enable`
- `email-domains` (email), CLI has `email domains add`, `email domains rm`
- `email-test` (email), CLI has `email test`
diff --git a/docs/site/cli.md b/docs/site/cli.md
index fba629856..87a51ff6f 100644
--- a/docs/site/cli.md
+++ b/docs/site/cli.md
@@ -1522,11 +1522,12 @@ would reach that quota between them.
`--private-storage=false` turns the policy off. Instances created before it
keep the bindings and buckets they already have.
-`--store-versioning` versions every private store made from then on, keeping
-old versions for 30 days (see [carlos store versioning](#carlos-store-versioning)).
-Its bucket is versioned before the new instance gets a credential. Stores
-made before it keep their setting. `--store-versioning=false` turns the
-policy off for stores made later; it changes no existing store.
+Use `--store-versioning` to turn versioning on for every private store made
+from then on. Old versions are kept for 30 days (see
+[carlos store versioning](#carlos-store-versioning)). Each bucket has
+versioning on before the new instance gets a credential. Existing stores keep
+their setting. Use `--store-versioning=false` to turn this policy off for
+stores made later. It changes no existing store.
#### Bringing back a deleted instance
@@ -2253,16 +2254,17 @@ Lets browsers on the origins you name upload large files in parts straight to th
```sh
carlos store versioning on --app hello
carlos store versioning status --app hello
-carlos store versioning off --app hello
```
-Keeps old versions of the store's objects, so a delete or an overwrite can be undone. Old versions are kept 30 days unless `--keep-days` says longer.
+Keep old versions so you can undo deletes and overwrites. Keep them for 30 days unless `--keep-days` sets a longer period. Once on, it stays on.
-With versioning on, a delete leaves the object's old versions behind and an overwrite keeps the bytes it replaced. Each old version is kept for 30 days after it stopped being current, then the platform's own lifecycle rule removes it. `--keep-days` sets from 30 to 365 days. You can raise it later, but never lower it.
+With versioning on, a delete leaves the object's old versions behind. An overwrite keeps the bytes it replaced. Old versions are kept for 30 days by default, counted from when they stopped being current. The platform's lifecycle rule then removes them. Use `--keep-days` to set this period from 30 to 365 days. You can raise it later, but never lower it.
-The store's own credential, the one your app holds, can't delete an old version, change the lifecycle rule, suspend versioning or write a bucket policy. So a bug in your app or a stolen credential can delete or overwrite objects, but you can still get them back for the next 30 days.
+Your app's store credential can't delete an old version, change the lifecycle rule, turn versioning off or write a bucket policy. A bug in your app or a stolen credential can still delete or overwrite objects. You can get them back for as long as their old versions are kept.
-`status` reads the bucket and says whether it matches what you asked for:
+There is no `off`. Once versioning is on, the store keeps it until the store is destroyed. You must be signed in as a person to turn versioning on. A service credential can't do it.
+
+Use `status` to read the bucket and check whether its settings match what you asked for:
```text
versioning on
@@ -2270,15 +2272,13 @@ keep old versions for 30 days
bucket in place
```
-`off` suspends versioning. Versions that already exist are still kept until they expire. Only objects written after `off` lose their protection. Turning versioning on or off needs a person signed in: a service credential can't do it.
-
-To version a store from the start, pass `--versioning` (and optionally `--keep-days`) to `carlos store create`. Its bucket is versioned before the first credential is delivered. For [private storage](#carlos-instances), `carlos instances enable --store-versioning` versions every private store made after it. Stores that already exist keep their setting; turn each one on with `--environment`.
+To turn versioning on when you create a store, pass `--versioning` and optionally `--keep-days` to `carlos store create`. The bucket has versioning on before the first credential is delivered. For [private storage](#carlos-instances), use `carlos instances enable --store-versioning` to turn versioning on for every private store made after that command. Existing stores keep their setting. To turn it on for an existing private store, run `carlos store versioning on --app <app> --environment <environment>`.
-`carlos store status` shows a versioning line when a store has ever had it on.
+`carlos store status` shows a versioning line for any store that has versioning on.
-Old versions take up space, so they count towards the store's size, its usage and its plan's storage limit, the same as current objects.
+Old versions count towards the store's size, its usage and its plan's storage limit, just like current objects.
-Versioning works only where the deployment has turned it on: the operator applies `store_versioning = true` in the `region-host` module and sets `CARLOS_STORE_VERSIONING=1` on the console. It needs AWS S3: the console refuses to start with it set alongside `CARLOS_STORE_ENDPOINT`. A versioned store can't use [media conversion](/docs/media-conversion) or browser uploads.
+Versioning is available only when the deployment has turned it on. The operator must apply `store_versioning = true` in the `region-host` module and set `CARLOS_STORE_VERSIONING=1` on the console. Versioning requires AWS S3. The console refuses to start if both `CARLOS_STORE_VERSIONING=1` and `CARLOS_STORE_ENDPOINT` are set. A store that has versioning on can't use [media conversion](/docs/media-conversion) or browser uploads.
#### carlos store versions
@@ -2286,7 +2286,7 @@ Versioning works only where the deployment has turned it on: the operator applie
carlos store versions --app hello --key uploads/a1b2.bin
```
-Lists one object's versions, newest first, at most 100:
+Lists one object's versions, newest first, 100 at a time:
```text
VERSION MODIFIED SIZE STATE
@@ -2294,7 +2294,7 @@ Wq3sVh1Hq2v7m4H0eS0pR8yIEwq0vM8A 2026-11-22 10:04 UTC - deleted
3HL4kqtJlcpXroDTDmJ.rmSpXd3dIbrH 2026-11-21 18:30 UTC 4.0 MiB old
```
-`deleted` is the marker a delete leaves. It holds no bytes.
+`deleted` marks a delete. It holds no bytes. When there are more, the last line names the command for the next page, with `--after`.
#### carlos store restore
@@ -2302,7 +2302,7 @@ Wq3sVh1Hq2v7m4H0eS0pR8yIEwq0vM8A 2026-11-22 10:04 UTC - deleted
carlos store restore --app hello --key uploads/a1b2.bin --version 3HL4kqtJlcpXroDTDmJ.rmSpXd3dIbrH
```
-Makes an old version current again by copying it, so the version it replaces is kept like any other. Nothing is deleted. A deleted object comes back the same way: restore the version before the delete. Restore refuses a delete marker, the version that is already current, a version over 5 GiB, and a store that refuses uploads because its plan's storage is full.
+Restore makes an old version current by copying it. The version it replaces is kept like any other. Nothing is deleted. To recover a deleted object, restore the version before the delete. Any kept version can be restored by its id, however many newer versions there are. Restore refuses a delete marker, the version that is already current, or a version larger than 5 GiB (gibibytes). It also refuses a store whose bucket isn't versioned yet, and a store that blocks uploads because its plan's storage is full.
#### carlos store scan
diff --git a/docs/site/media-conversion.md b/docs/site/media-conversion.md
index 8ea31ba99..cd904e8aa 100644
--- a/docs/site/media-conversion.md
+++ b/docs/site/media-conversion.md
@@ -89,7 +89,7 @@ If the same object was already sent with the same preset and class, `POST` answe
Poll with `GET`. A repeated `POST` also returns the job, but each one makes the console read your store's settings and check the object in your bucket again.
-The first time your app uses its store for conversion or browser uploads, the console checks the bucket. It must be named and owned the way this deployment names and owns buckets, be in the store's region, use SSE-S3 encryption, have versioning off, and carry no bucket policy, lifecycle rule or CORS rule the platform didn't write. A store made with `carlos store create` and left alone passes. A store with [versioning](/docs/cli#carlos-store-versioning) on, or ever turned on, never passes: S3 can't turn versioning off again, only suspend it. So turning versioning on is final for conversion and browser uploads on that store, and `carlos store versioning on` refuses a store that already uses either. A store that fails is refused with `store_unverified` and the check it failed, and is checked again on your next request.
+The first time your app uses its store for conversion or browser uploads, the console checks the bucket. It must be named and owned the way this deployment names and owns buckets, be in the store's region, use SSE-S3 encryption, have versioning off, and carry no bucket policy, lifecycle rule or CORS rule the platform didn't write. A store made with `carlos store create` and left alone passes. A store that has ever had [versioning](/docs/cli#carlos-store-versioning) turned on can't use media conversion or browser uploads, and versioning can't be turned off. `carlos store versioning on` refuses a store that already uses either feature. A store that fails is refused with `store_unverified` and the check it failed, and is checked again on your next request.
A console running in host-claim mode doesn't offer conversion or browser uploads. It refuses both with `claims_console`.
diff --git a/docs/superpowers/notes/copy-luna-brief-store-versioning.md b/docs/superpowers/notes/copy-luna-brief-store-versioning.md
new file mode 100644
index 000000000..428eddf3c
--- /dev/null
+++ b/docs/superpowers/notes/copy-luna-brief-store-versioning.md
@@ -0,0 +1,128 @@
+You are the copy-review gate itself for this set. Paul delegated copy review to you on 2026-10-25; your verdicts ARE the review. Do NOT run any skill or start any server, and do not modify files. You are writing a review report.
+
+House rules (Paul's): plain, direct, short sentences; no jargon left undefined; no em dashes or en dashes; no throat-clearing; second person ("you") is fine; tell the reader what to do rather than explaining the design; facts must stay exactly as given (do not add or drop technical claims). Code identifiers, flags, env vars and the `%s`/`%d` placeholders stay as written. CLI status lines are label and value pairs aligned in two columns (`versioning on`); keep that shape. Refusal messages are lowercase-first sentences without a final period, as the console's other refusals are.
+
+Context: CARLOS platform, object storage. A store is a bucket an app owns. This change lets an owner turn on versioning: deletes and overwrites keep the old bytes as old versions for 30 days (30 to 365, can be raised, never lowered) on a platform lifecycle rule, the app's own credential cannot delete old versions or change the setting, `off` suspends versioning but keeps existing old versions until they expire, `carlos store versions` lists one object's versions, `carlos store restore` copies an old version back as the current one and deletes nothing. A versioned store can't use media conversion or browser uploads. The deployment switches it on with `store_versioning = true` in the region-host module and `CARLOS_STORE_VERSIONING=1` on the console; AWS S3 only.
+
+Strings (key: text). Multi-line values show line breaks as <br>.
+
+cli.versioning.usage: usage: carlos store versioning <on\|off\|status> --app <a> [--environment <e>] [--keep-days <n>]
+cli.versioning.store_usage: versioning <on\|off\|status> --app <a> [--environment <e>] [--keep-days <n>]<br> keep old versions of the store's objects, so a<br> delete or an overwrite can be undone. Old versions<br> are kept 30 days unless --keep-days says longer.<br> versions --app <a> --key <key> [--environment <e>]<br> list one object's versions, newest first.<br> restore --app <a> --key <key> --version <id> [--environment <e>]<br> make an old version current again. Nothing is deleted.
+docs.cli.store_versioning: Keeps old versions of the store's objects, so a delete or an overwrite can be undone. Old versions are kept 30 days unless --keep-days says longer.
+cli.versioning.flag_app: app whose store to version
+cli.versioning.flag_env: the config environment whose store to act on (default: the app's own)
+cli.versioning.flag_keep: days to keep old versions, from 30 to 365 (default 30, or the store's current setting); can't be lowered
+cli.versioning.flag_key: the object's key
+cli.versioning.flag_version: the version to make current again (from carlos store versions)
+cli.versioning.flag_create: keep old versions of this store's objects from the start (see carlos store versioning)
+cli.versioning.flag_create_kd: days to keep old versions, from 30 to 365 (default 30); implies --versioning
+cli.versioning.on: versioning on
+cli.versioning.off: versioning off
+cli.versioning.never: versioning never turned on
+cli.versioning.keep: keep old versions for %d days
+cli.versioning.off_note: note versions from before still expire after %d days
+cli.versioning.bucket_ok: bucket in place
+cli.versioning.bucket_pending: bucket set when the store is provisioned
+cli.versioning.bucket_stale: bucket not set yet. Run the same command again
+cli.versioning.bucket_foreign: bucket changed: it has a lifecycle rule this platform didn't write
+cli.versioning.status_line_on: versioning: on, old versions kept %d days
+cli.versioning.status_line_of: versioning: off; versions from before expire after %d days
+cli.versions.none: no versions of %s
+cli.versions.header: VERSION\tMODIFIED\tSIZE\tSTATE
+cli.versions.current: current
+cli.versions.old: old
+cli.versions.deleted: deleted
+cli.restore.done: restored %s<br>from %s<br>new %s
+cli.versioning.unreadable: store versioning: unreadable response: %w
+cli.versioning.need_key: --key is required
+cli.versioning.need_version: --version is required
+versioning.not_configured: store versioning isn't switched on for this deployment (CARLOS_STORE_VERSIONING)
+versioning.claims_console: store versioning isn't available while host claims are on
+versioning.unsupported: this deployment's storage backend can't version buckets
+versioning.no_store: %s has no store here. Run carlos store create --app %s --versioning
+versioning.no_bucket: this store has no bucket yet
+versioning.bad_keep_days: keep days must be from 30 to 365
+versioning.keep_days_lowered: this store keeps old versions for %d days, and that can't be lowered
+versioning.in_use_by_media: this store is set up for media conversion or browser uploads, and both need versioning off
+versioning.lifecycle_in_use: the bucket has a lifecycle rule this platform didn't write. Remove it, then run this again
+versioning.bucket_failed: versioning is recorded, but the bucket wasn't changed. Run the same command again
+versioning.create_existing: this store already exists. Turn versioning on with carlos store versioning on
+versions.no_key: name the object with --key
+versions.bad_key: %q isn't an object key
+versions.not_versioned: this store has never had versioning on, so it keeps no old versions
+restore.no_version: %s has no version %s among its newest 100
+restore.delete_marker: version %s marks a delete, so it holds nothing to restore
+restore.already_current: version %s is already the current one
+restore.too_large: version %s is over 5 GiB, which restore can't copy
+restore.writes_denied: this store refuses uploads while its plan's storage is full, so nothing can be restored into it
+restore.failed: %s wasn't restored, and nothing changed. Try again
+audit.versioning_on: turned versioning on%s, keeping old versions %d days (cli)
+audit.versioning_off: turned versioning off%s (cli)
+audit.restore: restored %s from version %s%s (cli)
+
+instances.flag_store_versioning (flag help, `carlos instances enable`): version every private store made from now on, keeping old versions 30 days (see carlos store versioning); --store-versioning=false turns the policy off
+instances.enable_line (printed after enable when the policy is on): every new private store keeps old versions for 30 days
+infra.variable_store_versioning (Terraform variable description): Let this host's role version the buckets under store_bucket_prefix, keep their old versions on a platform lifecycle rule, list and copy old versions back for a restore, and delete every version when a versioned store is destroyed. Off by default: the role gets no new grant, and the store user boundary never changes either way. Set it only on the box that runs the console, together with CARLOS_STORE_VERSIONING=1 on the console. Requires a dedicated store_bucket_prefix ending in -store-, such as carlos-store-, that none of the deployment, data or sibling staging buckets start with and that does not overlap managed_fleet_bucket_prefix.
+infra.readme_store_versioning (region-host README paragraph): `store_versioning = true` lets this host’s role version the buckets under `store_bucket_prefix`: turn versioning on or off, write the platform’s one lifecycle rule that removes old versions after the store’s retention, list old versions, copy one back for a restore, and delete every version when a versioned store is destroyed. Store users get none of this, and their own policy denies every action that deletes a version or changes a bucket’s versioning, lifecycle or policy. It is off by default, so a deployment that has not switched it on plans no change. Set it on the console’s box only, along with `CARLOS_STORE_VERSIONING=1` on the console. Like `store_conversion`, it needs a dedicated `store_bucket_prefix` ending in `-store-`.
+docs.media_conversion_versioning (sentence in docs/site/media-conversion.md): A store with [versioning](/docs/cli#carlos-store-versioning) on, or ever turned on, never passes: S3 can't turn versioning off again, only suspend it. So turning versioning on is final for conversion and browser uploads on that store, and `carlos store versioning on` refuses a store that already uses either.
+docs.cli_instances_store_versioning (paragraph in docs/site/cli.md under carlos instances): `--store-versioning` versions every private store made from then on, keeping old versions for 30 days (see [carlos store versioning](#carlos-store-versioning)). Its bucket is versioned before the new instance gets a credential. Stores made before it keep their setting. `--store-versioning=false` turns the policy off for stores made later; it changes no existing store.
+
+docs.cli_store_versioning_sections (docs/site/cli.md, three sections; review each paragraph, key them D1, D2, ... in order):
+
+#### carlos store versioning
+
+```sh
+carlos store versioning on --app hello
+carlos store versioning status --app hello
+carlos store versioning off --app hello
+```
+
+Keeps old versions of the store's objects, so a delete or an overwrite can be undone. Old versions are kept 30 days unless `--keep-days` says longer.
+
+With versioning on, a delete leaves the object's old versions behind and an overwrite keeps the bytes it replaced. Each old version is kept for 30 days after it stopped being current, then the platform's own lifecycle rule removes it. `--keep-days` sets from 30 to 365 days. You can raise it later, but never lower it.
+
+The store's own credential, the one your app holds, can't delete an old version, change the lifecycle rule, suspend versioning or write a bucket policy. So a bug in your app or a stolen credential can delete or overwrite objects, but you can still get them back for the next 30 days.
+
+`status` reads the bucket and says whether it matches what you asked for:
+
+```text
+versioning on
+keep old versions for 30 days
+bucket in place
+```
+
+`off` suspends versioning. Versions that already exist are still kept until they expire. Only objects written after `off` lose their protection. Turning versioning on or off needs a person signed in: a service credential can't do it.
+
+To version a store from the start, pass `--versioning` (and optionally `--keep-days`) to `carlos store create`. Its bucket is versioned before the first credential is delivered. For [private storage](#carlos-instances), `carlos instances enable --store-versioning` versions every private store made after it. Stores that already exist keep their setting; turn each one on with `--environment`.
+
+`carlos store status` shows a versioning line when a store has ever had it on.
+
+Old versions take up space, so they count towards the store's size, its usage and its plan's storage limit, the same as current objects.
+
+Versioning works only where the deployment has turned it on: the operator applies `store_versioning = true` in the `region-host` module and sets `CARLOS_STORE_VERSIONING=1` on the console. It needs AWS S3: the console refuses to start with it set alongside `CARLOS_STORE_ENDPOINT`. A versioned store can't use [media conversion](/docs/media-conversion) or browser uploads.
+
+#### carlos store versions
+
+```sh
+carlos store versions --app hello --key uploads/a1b2.bin
+```
+
+Lists one object's versions, newest first, at most 100:
+
+```text
+VERSION MODIFIED SIZE STATE
+Wq3sVh1Hq2v7m4H0eS0pR8yIEwq0vM8A 2026-11-22 10:04 UTC - deleted
+3HL4kqtJlcpXroDTDmJ.rmSpXd3dIbrH 2026-11-21 18:30 UTC 4.0 MiB old
+```
+
+`deleted` is the marker a delete leaves. It holds no bytes.
+
+#### carlos store restore
+
+```sh
+carlos store restore --app hello --key uploads/a1b2.bin --version 3HL4kqtJlcpXroDTDmJ.rmSpXd3dIbrH
+```
+
+Makes an old version current again by copying it, so the version it replaces is kept like any other. Nothing is deleted. A deleted object comes back the same way: restore the version before the delete. Restore refuses a delete marker, the version that is already current, a version over 5 GiB, and a store that refuses uploads because its plan's storage is full.
+
+Answer ONLY with a Markdown table: key | verdict (keep/change) | new text (full, if changed) | why. Then a "Flags" list for any fact conflict or unclear term (or "none").
diff --git a/docs/superpowers/notes/copy-luna-store-versioning.md b/docs/superpowers/notes/copy-luna-store-versioning.md
new file mode 100644
index 000000000..6efd641a5
--- /dev/null
+++ b/docs/superpowers/notes/copy-luna-store-versioning.md
@@ -0,0 +1,102 @@
+# Copy pass, store versioning (delegated review, Paul 2026-10-25)
+
+The repo's copy reviews use Luna (`gpt-6-luna`). This Codex account refuses it (`The 'gpt-6-luna' model is not supported when using Codex with a ChatGPT account`), so this pass ran on Astra (`gpt-6-astra`, effort high, `codex exec -s read-only`) with the Luna brief, `docs/superpowers/notes/copy-luna-brief-store-versioning.md`, as Rastrillo did (rastrillo/rastrillo #375).
+
+## What was applied
+
+Applied as suggested, except:
+- **Every `off` string and paragraph is gone**, not reworded. Code review round 1 cut `off` (decision 3), which also answers the copy flags "Suspension and protection" and "Recovery guarantee". D3 now promises recovery "for as long as their old versions are kept", not "for the next 30 days".
+- **`cli.versioning.status_line_on` keeps the `label: value` form.** It is a line inside `carlos store status`, whose neighbours (`size:`, `environment:`) use that form. The two-column shape is for `carlos store versioning status`.
+- **`restore.failed`** was not "nothing changed": a lost response after a successful copy would make that untrue (flag "Failure guarantee"). It now reads "%s may not have been restored; run carlos store versions to check, then try again".
+- **`restore.no_version`** dropped "among its newest 100": restore now finds any version by id (code round 1 P1).
+- **`versioning.lifecycle_in_use`** now says who acts: "ask your deployment operator to remove it, then run this again" (flag "Lifecycle recovery").
+- **D6** names the full command for an existing private store (flag "Incomplete command").
+- **D9 and the media sentence** say "a store that has ever had versioning on" (flag "Permanent incompatibility").
+- **`versioning.claims_console`** reads "isn't available on this console while host claims are on". "Store user boundary" and "sibling staging buckets" stay in the operator-facing module text, where those are the module's own variable names.
+- **New strings** written in the review's style, for the round 1 fixes: `versioning.permanent`, `versioning.person_only`, `restore.not_enabled`, `cli.versioning.bad_keep_days`, `cli.versioning.old_console`, `cli.instances.old_console`, `cli.versioning.flag_after`, `cli.versions.more`. They go through the round 2 copy check.
+
+## Reply, whole
+
+| key | verdict (keep/change) | new text (full, if changed) | why |
+|---|---|---|---|
+| cli.versioning.usage | keep | | Clear syntax. |
+| cli.versioning.store_usage | change | ` versioning <on\|off\|status> --app <a> [--environment <e>] [--keep-days <n>]<br> keep old versions so you can undo deletes and<br> overwrites. Keep them for 30 days unless<br> --keep-days sets a longer period.<br> versions --app <a> --key <key> [--environment <e>]<br> list one object's versions, newest first.<br> restore --app <a> --key <key> --version <id> [--environment <e>]<br> make an old version current again. Nothing is deleted.` | Shorter, direct instructions. |
+| docs.cli.store_versioning | change | Keep old versions so you can undo deletes and overwrites. Keep them for 30 days unless `--keep-days` sets a longer period. | Direct wording. |
+| cli.versioning.flag_app | change | app whose store to use | Avoids using “version” as a verb for an option that also checks status or turns versioning off. |
+| cli.versioning.flag_env | change | config environment whose store to use (default: the app's own) | Removes “act on.” |
+| cli.versioning.flag_keep | change | days to keep old versions, from 30 to 365 (default: the store's current setting, or 30 if unset); can't be lowered | Makes the default's precedence clear. |
+| cli.versioning.flag_key | change | the object's key (name) | Defines “key.” |
+| cli.versioning.flag_version | keep | | Gives the source of the required value. |
+| cli.versioning.flag_create | keep | | Clear effect and command reference. |
+| cli.versioning.flag_create_kd | keep | | States the range, default and implied flag. |
+| cli.versioning.on | keep | | Clear label and value. |
+| cli.versioning.off | keep | | Clear label and value. |
+| cli.versioning.never | keep | | Distinguishes suspension from never being enabled. |
+| cli.versioning.keep | keep | | Clear label and value. |
+| cli.versioning.off_note | change | `note existing old versions still expire after %d days` | Replaces vague “versions from before.” |
+| cli.versioning.bucket_ok | keep | | Short status value. |
+| cli.versioning.bucket_pending | keep | | Explains when the setting takes effect. |
+| cli.versioning.bucket_stale | keep | | Gives the next action. |
+| cli.versioning.bucket_foreign | keep | | Identifies the conflict; see terminology flag. |
+| cli.versioning.status_line_on | change | ` versioning on, old versions kept %d days` | Uses the required two-column shape. |
+| cli.versioning.status_line_of | change | ` versioning off; existing old versions expire after %d days` | Uses two columns and replaces vague wording. |
+| cli.versions.none | keep | | Clear empty state. |
+| cli.versions.header | keep | | Clear table headings. |
+| cli.versions.current | keep | | Clear state. |
+| cli.versions.old | keep | | Clear state. |
+| cli.versions.deleted | keep | | Explained in the command documentation. |
+| cli.restore.done | keep | | Preserves aligned labels and all three values. |
+| cli.versioning.unreadable | change | `store versioning: can't read the response: %w` | Uses a direct sentence and preserves error wrapping. |
+| cli.versioning.need_key | keep | | Clear required flag. |
+| cli.versioning.need_version | keep | | Clear required flag. |
+| versioning.not_configured | keep | | Identifies the deployment setting. |
+| versioning.claims_console | keep | | Clear refusal structure; “host claims” needs a definition. |
+| versioning.unsupported | change | this deployment's storage service doesn't support bucket versioning | Replaces “backend” and “version” as a verb. |
+| versioning.no_store | change | `%s has no store here; run carlos store create --app %s --versioning` | Keeps the refusal lowercase and gives the next action. |
+| versioning.no_bucket | keep | | Clear refusal. |
+| versioning.bad_keep_days | change | old versions must be kept for 30 to 365 days | Replaces the unclear noun phrase “keep days.” |
+| versioning.keep_days_lowered | change | `this store keeps old versions for %d days; you can't lower that setting` | Names what cannot be lowered. |
+| versioning.in_use_by_media | keep | | Names both incompatible features. |
+| versioning.lifecycle_in_use | change | the bucket has a lifecycle rule this platform didn't write; remove it, then run this again | Preserves the action and refusal format; see flags. |
+| versioning.bucket_failed | change | versioning is recorded, but the bucket wasn't changed; run the same command again | Preserves partial success and the recovery action. |
+| versioning.create_existing | change | `this store already exists; turn versioning on with carlos store versioning on` | Preserves the next action and refusal format. |
+| versions.no_key | keep | | Direct instruction. |
+| versions.bad_key | keep | | Clear refusal with the rejected value. |
+| versions.not_versioned | keep | | Explains why no old versions exist. |
+| restore.no_version | change | `%s has no version %s among its newest 100 versions` | Makes the search limit explicit. |
+| restore.delete_marker | keep | | Explains the marker without relying on jargon. |
+| restore.already_current | keep | | Clear refusal. |
+| restore.too_large | change | `version %s is larger than 5 GiB (gibibytes), so restore can't copy it` | Defines the unit and preserves the exact limit. |
+| restore.writes_denied | change | this store refuses uploads because its plan's storage is full; you can't restore into it until space is available | Makes the condition and required remedy direct. |
+| restore.failed | change | `%s wasn't restored, and nothing changed; try again` | Preserves the guarantee and refusal format; see flags. |
+| audit.versioning_on | change | `turned versioning on%s, keeping old versions for %d days (cli)` | Adds the missing preposition. |
+| audit.versioning_off | keep | | Clear audit action. |
+| audit.restore | keep | | Clear audit action with placeholders preserved. |
+| instances.flag_store_versioning | change | turn versioning on for every private store made from now on, keeping old versions for 30 days (see carlos store versioning); --store-versioning=false turns this policy off | Avoids “version” as a verb and preserves future-store scope. |
+| instances.enable_line | keep | | Clear scope and duration. |
+| infra.variable_store_versioning | change | Allow this host's role to turn bucket versioning on or off under store_bucket_prefix. Allow it to keep old versions using a platform lifecycle rule, list old versions, copy one back for a restore, and delete every version when a versioned store is destroyed. Off by default: the role gets no new permissions. The store user boundary does not change whether this is on or off. Set it only on the box that runs the console. Also set CARLOS_STORE_VERSIONING=1 on the console. Use a dedicated store_bucket_prefix ending in -store-, such as carlos-store-. No deployment, data or sibling staging bucket may start with that prefix. It must not overlap managed_fleet_bucket_prefix. | Splits long sentences and makes setup requirements direct; boundary terminology remains flagged. |
+| infra.readme_store_versioning | change | Set `store_versioning = true` to let this host's role turn versioning on or off for buckets under `store_bucket_prefix`. The role can write the platform's one lifecycle rule, which removes old versions after the store's retention period. It can list old versions, copy one back for a restore, and delete every version when a versioned store is destroyed. Store users get none of these permissions. Their own policy denies every action that deletes a version or changes a bucket's versioning, lifecycle or policy. This setting is off by default. A deployment that has not switched it on plans no change. Set it only on the box that runs the console. Also set `CARLOS_STORE_VERSIONING=1` on the console. Like `store_conversion`, it requires a dedicated `store_bucket_prefix` ending in `-store-`. | Preserves the permissions and restrictions in shorter sentences. |
+| docs.media_conversion_versioning | change | A store that has ever had [versioning](/docs/cli#carlos-store-versioning) turned on cannot use media conversion or browser uploads. S3 can only suspend versioning once it has been turned on. Turning versioning on permanently rules out both features for that store. `carlos store versioning on` refuses a store that already uses either feature. | Replaces “never passes” with the actual consequence. |
+| docs.cli_instances_store_versioning | change | Use `--store-versioning` to turn versioning on for every private store made from then on. Old versions are kept for 30 days (see [carlos store versioning](#carlos-store-versioning)). Each bucket has versioning on before the new instance gets a credential. Existing stores keep their setting. Use `--store-versioning=false` to turn this policy off for stores made later. It changes no existing store. | Direct instructions with the timing and scope preserved. |
+| D1 | change | Keep old versions so you can undo deletes and overwrites. Keep them for 30 days unless `--keep-days` sets a longer period. | Shorter, direct wording. |
+| D2 | change | With versioning on, a delete leaves the object's old versions behind. An overwrite keeps the bytes it replaced. Old versions are kept for 30 days by default, counted from when they stopped being current. The platform's lifecycle rule then removes them. Use `--keep-days` to set this period from 30 to 365 days. You can raise it later, but never lower it. | Makes 30 days the default rather than an unconditional duration. |
+| D3 | change | Your app's store credential can't delete an old version, change the lifecycle rule, suspend versioning or write a bucket policy. A bug in your app or a stolen credential can still delete or overwrite objects. You can get them back for the next 30 days. | Shortens the sentences while preserving the stated recovery claim; see flags. |
+| D4 | change | Use `status` to read the bucket and check whether its settings match what you asked for: | Direct instruction. |
+| D5 | change | Use `off` to suspend versioning. Existing versions are kept until they expire. Only objects written after `off` lose their protection. You must be signed in as a person to turn versioning on or off. A service credential can't do it. | Shorter sentences; the protection claim needs factual confirmation. |
+| D6 | change | To turn versioning on when you create a store, pass `--versioning` and optionally `--keep-days` to `carlos store create`. The bucket has versioning on before the first credential is delivered. For [private storage](#carlos-instances), use `carlos instances enable --store-versioning` to turn versioning on for every private store made after that command. Existing stores keep their setting. Turn versioning on for each existing store with `--environment`. | Removes “version” as a verb and clarifies timing; the final instruction remains incomplete. |
+| D7 | change | `carlos store status` shows a versioning line for any store that has ever had versioning on. | Replaces the ambiguous “it.” |
+| D8 | change | Old versions count towards the store's size, its usage and its plan's storage limit, just like current objects. | Removes redundant explanation without dropping any accounting claim. |
+| D9 | change | Versioning is available only when the deployment has turned it on. The operator must apply `store_versioning = true` in the `region-host` module and set `CARLOS_STORE_VERSIONING=1` on the console. Versioning requires AWS S3. The console refuses to start if both `CARLOS_STORE_VERSIONING=1` and `CARLOS_STORE_ENDPOINT` are set. A versioned store can't use [media conversion](/docs/media-conversion) or browser uploads. | Separates prerequisites and restrictions into short sentences. |
+| D10 | keep | | Clear ordering and limit. |
+| D11 | change | `deleted` marks a delete. It holds no bytes. | Explains the state without introducing another term. |
+| D12 | change | Restore makes an old version current by copying it. The version it replaces is kept like any other. Nothing is deleted. To recover a deleted object, restore the version before the delete. Restore refuses a delete marker, the version that is already current, or a version larger than 5 GiB (gibibytes). It also refuses a store that blocks uploads because its plan's storage is full. | Splits the explanation and refusal conditions while preserving each claim. |
+
+Flags
+
+- **Suspension and protection:** D5 says only objects written after `off` lose protection. Confirm this covers objects already present when versioning is suspended, including any versions with a `null` version ID.
+- **Recovery guarantee:** D3 promises recovery for the next 30 days. Confirm its scope when versioning is suspended or the store is destroyed.
+- **Failure guarantee:** `restore.failed` says nothing changed. Confirm this is guaranteed for every failure that produces this message, including a lost response after a successful copy.
+- **Permanent incompatibility:** D9's “versioned store” could mean only a store with versioning currently on. The media conversion paragraph says any store that has ever enabled versioning is permanently excluded.
+- **Incomplete command:** D6's instruction to use `--environment` does not show the command or environment value needed to select an existing private store.
+- **Undefined terms:** “host claims,” “store user boundary,” and “sibling staging buckets” need definitions. Standalone messages using “lifecycle rule” also need accessible wording or a linked explanation.
+- **Lifecycle recovery:** `versioning.lifecycle_in_use` tells the reader to remove the rule without identifying how or who can do that. The supplied facts say the app's credential cannot change it.
\ No newline at end of file
diff --git a/docs/superpowers/notes/store-versioning-copy-deck.md b/docs/superpowers/notes/store-versioning-copy-deck.md
index 6b3c6d1e8..62b9002a5 100644
--- a/docs/superpowers/notes/store-versioning-copy-deck.md
+++ b/docs/superpowers/notes/store-versioning-copy-deck.md
@@ -1,14 +1,9 @@
# Store versioning copy deck
-**Status: DRAFT, not yet copy-reviewed.** Spec: `docs/superpowers/specs/2026-11-22-store-versioning-design.md`.
-The text lives in two maps, `storeVersioningCopy` (`store_versioning.go`, the CLI) and `versioningCopy`
-(`internal/console/store_versioning_copy.go`, the console's refusals and audit rows). This deck was generated
-from them; apply review edits to the map and the deck together. The docs pages (`docs/site/cli.md`
-`#### carlos store versioning`, `versions`, `restore`, the `--store-versioning` paragraph under
-`carlos instances`, and the versioning sentence in `docs/site/media-conversion.md`) are in scope for the same review.
-Also in scope: the `--store-versioning` flag help and the `every new private store keeps old versions for 30 days` line
-in `instances_cli.go`, and the module's
-`store_versioning` variable description and README paragraph.
+**Status: copy-reviewed, round 1** (Astra, as Luna is refused on this account: `docs/superpowers/notes/copy-luna-store-versioning.md`). Strings added by code review round 1's fixes are checked in round 2.
+Spec: `docs/superpowers/specs/2026-11-22-store-versioning-design.md`.
+
+The text lives in two maps: `storeVersioningCopy` (`store_versioning.go`, the CLI) and `versioningCopy` (`internal/console/store_versioning_copy.go`, the console's refusals and audit rows). This deck is generated from them, so apply edits to the map and regenerate. The docs pages (`docs/site/cli.md` `#### carlos store versioning`, `versions`, `restore`, the `--store-versioning` paragraph under `carlos instances`, the versioning sentence in `docs/site/media-conversion.md`), the `--store-versioning` flag help and enable line in `instances_cli.go`, and the module's `store_versioning` variable description and README paragraph are in scope for the same review.
`%s` and `%d` are filled in by the code.
@@ -16,34 +11,37 @@ in `instances_cli.go`, and the module's
| key | text |
|---|---|
-| `cli.versioning.usage` | usage: carlos store versioning <on\|off\|status> --app <a> [--environment <e>] [--keep-days <n>] |
-| `cli.versioning.store_usage` | versioning <on\|off\|status> --app <a> [--environment <e>] [--keep-days <n>]<br> keep old versions of the store's objects, so a<br> delete or an overwrite can be undone. Old versions<br> are kept 30 days unless --keep-days says longer.<br> versions --app <a> --key <key> [--environment <e>]<br> list one object's versions, newest first.<br> restore --app <a> --key <key> --version <id> [--environment <e>]<br> make an old version current again. Nothing is deleted. |
-| `docs.cli.store_versioning` | Keeps old versions of the store's objects, so a delete or an overwrite can be undone. Old versions are kept 30 days unless --keep-days says longer. |
-| `cli.versioning.flag_app` | app whose store to version |
-| `cli.versioning.flag_env` | the config environment whose store to act on (default: the app's own) |
-| `cli.versioning.flag_keep` | days to keep old versions, from 30 to 365 (default 30, or the store's current setting); can't be lowered |
-| `cli.versioning.flag_key` | the object's key |
+| `cli.versioning.usage` | usage: carlos store versioning <on\|status> --app <a> [--environment <e>] [--keep-days <n>] |
+| `cli.versioning.store_usage` | versioning <on\|status> --app <a> [--environment <e>] [--keep-days <n>]<br> keep old versions so you can undo deletes and<br> overwrites. Keep them for 30 days unless<br> --keep-days sets a longer period. Once on, it<br> stays on.<br> versions --app <a> --key <key> [--after <id>] [--environment <e>]<br> list one object's versions, newest first.<br> restore --app <a> --key <key> --version <id> [--environment <e>]<br> make an old version current again. Nothing is deleted. |
+| `docs.cli.store_versioning` | Keep old versions so you can undo deletes and overwrites. Keep them for 30 days unless --keep-days sets a longer period. Once on, it stays on. |
+| `cli.versioning.flag_app` | app whose store to use |
+| `cli.versioning.flag_env` | config environment whose store to use (default: the app's own) |
+| `cli.versioning.flag_keep` | days to keep old versions, from 30 to 365 (default: the store's current setting, or 30 if unset); can't be lowered |
+| `cli.versioning.flag_key` | the object's key (name) |
| `cli.versioning.flag_version` | the version to make current again (from carlos store versions) |
+| `cli.versioning.flag_after` | list the versions older than this one (from the more line of the last page) |
| `cli.versioning.flag_create` | keep old versions of this store's objects from the start (see carlos store versioning) |
| `cli.versioning.flag_create_kd` | days to keep old versions, from 30 to 365 (default 30); implies --versioning |
+| `cli.versioning.bad_keep_days` | --keep-days must be from 30 to 365 |
+| `cli.versioning.old_console` | this console is older than store versioning, so the store was declared without it and nothing was provisioned. Ask your operator to upgrade the console, then run carlos store versioning on |
+| `cli.instances.old_console` | this console is older than store versioning, so it did not turn on --store-versioning. Ask your operator to upgrade the console, then run this again |
| `cli.versioning.on` | versioning on |
| `cli.versioning.off` | versioning off |
| `cli.versioning.never` | versioning never turned on |
| `cli.versioning.keep` | keep old versions for %d days |
-| `cli.versioning.off_note` | note versions from before still expire after %d days |
| `cli.versioning.bucket_ok` | bucket in place |
| `cli.versioning.bucket_pending` | bucket set when the store is provisioned |
| `cli.versioning.bucket_stale` | bucket not set yet. Run the same command again |
| `cli.versioning.bucket_foreign` | bucket changed: it has a lifecycle rule this platform didn't write |
| `cli.versioning.status_line_on` | versioning: on, old versions kept %d days |
-| `cli.versioning.status_line_of` | versioning: off; versions from before expire after %d days |
| `cli.versions.none` | no versions of %s |
-| `cli.versions.header` | VERSION\tMODIFIED\tSIZE\tSTATE |
+| `cli.versions.header` | VERSION⇥MODIFIED⇥SIZE⇥STATE |
| `cli.versions.current` | current |
| `cli.versions.old` | old |
| `cli.versions.deleted` | deleted |
+| `cli.versions.more` | more: carlos store versions --key %s --after %s |
| `cli.restore.done` | restored %s<br>from %s<br>new %s |
-| `cli.versioning.unreadable` | store versioning: unreadable response: %w |
+| `cli.versioning.unreadable` | store versioning: can't read the response: %w |
| `cli.versioning.need_key` | --key is required |
| `cli.versioning.need_version` | --version is required |
@@ -52,25 +50,27 @@ in `instances_cli.go`, and the module's
| key | text |
|---|---|
| `versioning.not_configured` | store versioning isn't switched on for this deployment (CARLOS_STORE_VERSIONING) |
-| `versioning.claims_console` | store versioning isn't available while host claims are on |
-| `versioning.unsupported` | this deployment's storage backend can't version buckets |
-| `versioning.no_store` | %s has no store here. Run carlos store create --app %s --versioning |
+| `versioning.claims_console` | store versioning isn't available on this console while host claims are on |
+| `versioning.unsupported` | this deployment's storage service doesn't support bucket versioning |
+| `versioning.no_store` | %s has no store here; run carlos store create --app %s --versioning |
| `versioning.no_bucket` | this store has no bucket yet |
-| `versioning.bad_keep_days` | keep days must be from 30 to 365 |
-| `versioning.keep_days_lowered` | this store keeps old versions for %d days, and that can't be lowered |
+| `versioning.bad_keep_days` | old versions must be kept for 30 to 365 days |
+| `versioning.keep_days_lowered` | this store keeps old versions for %d days; you can't lower that setting |
+| `versioning.permanent` | versioning can't be turned off once it is on; the store keeps old versions until the store is destroyed |
+| `versioning.person_only` | only a person signed in can turn versioning on; a service credential can't |
| `versioning.in_use_by_media` | this store is set up for media conversion or browser uploads, and both need versioning off |
-| `versioning.lifecycle_in_use` | the bucket has a lifecycle rule this platform didn't write. Remove it, then run this again |
-| `versioning.bucket_failed` | versioning is recorded, but the bucket wasn't changed. Run the same command again |
-| `versioning.create_existing` | this store already exists. Turn versioning on with carlos store versioning on |
+| `versioning.lifecycle_in_use` | the bucket has a lifecycle rule this platform didn't write; ask your deployment operator to remove it, then run this again |
+| `versioning.bucket_failed` | versioning is recorded, but the bucket wasn't changed; run the same command again |
+| `versioning.create_existing` | this store already exists; turn versioning on with carlos store versioning on |
| `versions.no_key` | name the object with --key |
| `versions.bad_key` | %q isn't an object key |
| `versions.not_versioned` | this store has never had versioning on, so it keeps no old versions |
-| `restore.no_version` | %s has no version %s among its newest 100 |
+| `restore.not_enabled` | this store's bucket isn't versioned yet; run carlos store versioning on, then try again |
+| `restore.no_version` | %s has no version %s |
| `restore.delete_marker` | version %s marks a delete, so it holds nothing to restore |
| `restore.already_current` | version %s is already the current one |
-| `restore.too_large` | version %s is over 5 GiB, which restore can't copy |
-| `restore.writes_denied` | this store refuses uploads while its plan's storage is full, so nothing can be restored into it |
-| `restore.failed` | %s wasn't restored, and nothing changed. Try again |
-| `audit.versioning_on` | turned versioning on%s, keeping old versions %d days (cli) |
-| `audit.versioning_off` | turned versioning off%s (cli) |
+| `restore.too_large` | version %s is larger than 5 GiB (gibibytes), so restore can't copy it |
+| `restore.writes_denied` | this store refuses uploads because its plan's storage is full; you can't restore into it until space is available |
+| `restore.failed` | %s may not have been restored; run carlos store versions to check, then try again |
+| `audit.versioning_on` | turned versioning on%s, keeping old versions for %d days (cli) |
| `audit.restore` | restored %s from version %s%s (cli) |
diff --git a/docs/superpowers/reviews/CODEX-FINDINGS-store-versioning.md b/docs/superpowers/reviews/CODEX-FINDINGS-store-versioning.md
new file mode 100644
index 000000000..671bb2344
--- /dev/null
+++ b/docs/superpowers/reviews/CODEX-FINDINGS-store-versioning.md
@@ -0,0 +1,109 @@
+# Astra review, store versioning, round 1
+
+Reviewer: Astra (`gpt-6-astra`, reasoning effort high, `codex exec -s read-only`), from outside the author's model family (Claude Opus 5.5). Reviewed `74aeb271c..c953103e4` with `docs/superpowers/reviews/CODEX-REVIEW-BRIEF-store-versioning.md`.
+
+**Verdict: NOT READY.** It found 3 P1s and 3 P2s and approved every census unit and envelope.
+
+## What was done about each finding
+
+1. **P1, suspension and restore can destroy history** (family: existing history survives suspension and restore). Fixed by cutting the feature that produced it, stopping rule 2's second option, rather than guarding suspension.
+ - There is no `off`. The setter refuses `enabled: false` (`versioning_permanent`).
+ - The walks refuse a block that says false (`objstore.ErrVersioningPermanent`).
+ - `EnsureVersioning` only ever sets Enabled.
+ - Restore refuses unless the bucket reads Enabled (`not_enabled`).
+ - The in-memory fake now writes `null` versions as S3 does, replacing them in an unversioned or Suspended bucket. `TestMemSuspendedWriteReplacesTheNullVersion` pins the behaviour that made the cut necessary.
+ - Tests: `TestVersioningOnProvisionedStoreAndNoOff`, `TestVersioningOffNeverOnWritesNothing`, the `not_enabled` case in `TestVersionsAndRestore`, and `TestConvergeVersioningInTouchesOnlyTheBucket`'s refusal of an off block.
+2. **P1, a writer can push old versions past the only recovery interface** (family: retained versions stay recoverable).
+ - `ListVersions` pages (`after`/`next`, `--after`).
+ - Restore looks the version up by its id with `StatVersion` (a HEAD naming the version, plus a one-entry listing for "current"), however deep it is. No new IAM is needed: `s3:GetObjectVersion` and `s3:ListBucketVersions` were already in the grant.
+ - Tests: `TestRestoreReachesAVersionPastThePage`, `TestMemStatVersionAndPaging`, `TestStatVersion`, and the paging in `TestListVersionsOneKeyNewestFirst`.
+3. **P1, an older console silently ignores requested versioning** (family: requested protection is acknowledged before provisioning).
+ - `store create --versioning` refuses, before provisioning, an answer without an enabled versioning block.
+ - `instances enable --store-versioning` refuses an answer whose `store_versioning` is not true.
+ - Tests: `TestStoreCreateVersionedRefusesAnOlderConsole` and `TestInstancesEnableRefusesAnOlderConsole`.
+4. **P2, a negative `--keep-days` selects an unversioned create.** Fixed. Versioning is now a separate bool, and `--keep-days` is checked (30 to 365) before any request, for both create and `versioning on`. Test: `TestStoreCreateRefusesBadKeepDaysLocally`.
+5. **P2, re-create could lower retention.** Fixed. The create door uses the setter's rule (`nextKeepDays`): omitted keeps the record's retention, lower is refused. Test: `TestStoreCreateNeverLowersRetention`.
+6. **P2, the create door bypassed the person-only rule.** Fixed. Create with a versioning block refuses a non-person principal (`person_only`, 403); an ordinary create is unchanged. Test: `TestStoreCreateVersioningIsPersonOnly`.
+
+## Census verdicts (round 1)
+
+All approved:
+- `infra/modules/region-host/main.tf:external`
+- `infra/modules/region-host/variables.tf:external`
+- the new `infra/modules/region-host/tests/store_versioning.tftest.hcl:external`
+- envelopes `.`, `infra/modules/region-host`, `infra/modules/region-host/tests`, `internal/objstore` and `internal/provision`
+
+The fixes re-pin the same envelopes. `variables.tf` changes only its description text (copy review). The census check of the fix diff is round 2's.
+
+## Reply, whole
+
+Reviewed `74aeb271c..c953103e4`, the named specs, and the census card. Found **3 P1s and 3 P2s**. No files were modified and no test suites were run. `git diff --check` passed.
+
+1. **P1 — Suspension can destroy retained history; restore can also overwrite a version.**
+ **Spec:** decisions 3/6, §§4.1 and 6.4. **Fault family:** existing history survives suspension and restore.
+
+ [aws_versioning.go:170](/Users/paulcampbell/amadan.net/carlos/platform/.claude/worktrees/store-versioning/internal/objstore/aws_versioning.go:170) suspends the bucket without checking for `null` versions. A concrete failure is: write object A before enabling versioning; enable; overwrite with B, making A’s `null` version noncurrent; suspend; overwrite again. S3 permanently replaces A before its retention expires. The unconditional `DeleteObjectVersion` deny cannot prevent this `PutObject` route. [AWS documents this behavior](https://docs.aws.amazon.com/AmazonS3/latest/userguide/AddingObjectstoVersionSuspendedBuckets.html).
+
+ Separately, `versionedStore` accepts a suspended record (`internal/console/apistoreversioning.go:367`), and restore calls `CopyObject` without checking the bucket is Enabled (`internal/objstore/aws_versioning.go:269`). Restoring an older numbered version over a current `null` version destroys the latter.
+
+ **Fix:** gate suspension on preserving existing `null` history, and refuse restore unless actual bucket versioning is Enabled. Add both transition cases to the server contract tests. The fake currently conceals this: `memversioning.go:64` and `:182` allocate fresh version IDs even while suspended.
+
+2. **P1 — A credential can push recoverable history beyond the only recovery interface.**
+ **Spec:** §§4.1 and 6.4. **Fault family:** retained versions remain recoverable through the CLI/API.
+
+ [apistoreversioning.go:483](/Users/paulcampbell/amadan.net/carlos/platform/.claude/worktrees/store-versioning/internal/console/apistoreversioning.go:483) searches only `MaxListedVersions`—100—and returns `no_version` when the requested ID is outside that result. `internal/objstore/aws_versioning.go:236` and `:243` enforce that cap; the listing response offers no continuation.
+
+ A stolen credential can overwrite or delete a key 100 times. The original bytes remain in S3, but the owner cannot list or restore them through CARLOS—even with the original version ID already known.
+
+ **Fix:** make listing paginated and resolve a requested restore version independently of the display limit, either through exact-version inspection or a bounded, resumable search.
+
+3. **P1 — An older console silently ignores requested versioning, and the new CLI proceeds successfully.**
+ **Spec:** §§6.1, 6.3 and 10.2; review check 9. **Fault family:** requested storage protection must be acknowledged before provisioning.
+
+ [store.go:248](/Users/paulcampbell/amadan.net/carlos/platform/.claude/worktrees/store-versioning/store.go:248) sends the new body, but checks only the environment before issuing provision at line 265. It never requires an enabled versioning block in the response.
+
+ At the reviewed base, `internal/console/apistore.go:389` accepts only `env_prefix`; its permissive JSON decoder ignores `versioning`. Thus a new CLI against that console creates and provisions an **unversioned** store successfully. The instance-policy path has the same problem: `apimode.go:3582` accepts a response lacking `store_versioning`, and `instances_cli.go:132` reports success.
+
+ **Fix:** require affirmative response fields matching the requested protection before provisioning or reporting enable success. Refuse with an upgrade instruction when the server lacks support. Cover both paths with older-console response fixtures.
+
+4. **P2 — Negative `--keep-days` silently selects an unversioned create.**
+ **Spec:** §§5.2 and 10.1. **Fault family:** invalid retention must not remove requested protection.
+
+ [store.go:194](/Users/paulcampbell/amadan.net/carlos/platform/.claude/worktrees/store-versioning/store.go:194) passes the supplied integer into a helper where every negative value means unversioned (`store.go:248–251`). Consequently, `store create --versioning --keep-days=-1` sends the ordinary create request instead of reaching the server’s retention validation.
+
+ **Fix:** validate supplied retention before any request and represent “versioning not requested” separately from the numeric value.
+
+5. **P2 — Re-create can lower retention after a declared store is switched off.**
+ **Spec:** §5.2; review check 5. **Fault family:** `keep_days` never decreases.
+
+ [apistore.go:505](/Users/paulcampbell/amadan.net/carlos/platform/.claude/worktrees/store-versioning/internal/console/apistore.go:505) replaces the entire block whenever `!v.Enabled`, regardless of its existing retention.
+
+ Before provisioning: create with 90 days; turn versioning off; POST create with `"versioning": {}`. The stored retention becomes 30 days. No existing bucket history is lost in this sequence, but the promised monotonic setting is violated.
+
+ **Fix:** share the setter’s retention validation with create; omission preserves existing retention, and explicit decreases are refused.
+
+6. **P2 — The create door bypasses the person-only versioning rule.**
+ **Spec:** decision 5. **Fault family:** only a person may choose versioning policy.
+
+ The create route admits Admin service credentials at `internal/console/routedecls.go:1071`. [apistore.go:407](/Users/paulcampbell/amadan.net/carlos/platform/.claude/worktrees/store-versioning/internal/console/apistore.go:407) checks deployment support but adds no person check before recording versioning at line 506.
+
+ An Admin service credential can therefore enable versioning on a new or declared-only store, including reversing a person’s disabled declaration.
+
+ **Fix:** require a person when create requests a versioning block, preserving ordinary create authorization. Add a service-credential test for this second entry point.
+
+The remaining checks found no additional blocking issue: IAM grants use the dedicated-prefix exclusions; grants converge before minting; teardown preserves the record on backend failure; media checks reject the versioning block before trusting verification; and sizing follows both pagination markers and marks API failures unswept. CopySource encoding and scan-tag replacement match the stated design. The MinIO fixture exercises the specified denial requests and requires a PASS line, but does not cover the transition failure in finding 1.
+
+NOT READY
+
+Census verdicts below are limited to the recorded root-read dispositions. The findings above remain branch merge blockers.
+
+| Census unit or envelope | Verdict | Basis and inspected source |
+|---|---|---|
+| `infra/modules/region-host/main.tf:external` | **approve** | Switched grant, dedicated resource prefixes and deployment/data/staging/fleet exclusions; store boundary unchanged. [main.tf:1149](/Users/paulcampbell/amadan.net/carlos/platform/.claude/worktrees/store-versioning/infra/modules/region-host/main.tf:1149), `:1182`, `:829`. |
+| `infra/modules/region-host/variables.tf:external` | **approve** | Operator input, default false; no box runtime read. [variables.tf:309](/Users/paulcampbell/amadan.net/carlos/platform/.claude/worktrees/store-versioning/infra/modules/region-host/variables.tf:309). |
+| `infra/modules/region-host/tests/store_versioning.tftest.hcl:external` — new disposition | **approve** | `legacy / accepted-legacy` fits a mock-provider, plan-time test; no runtime authority. [store_versioning.tftest.hcl:7](/Users/paulcampbell/amadan.net/carlos/platform/.claude/worktrees/store-versioning/infra/modules/region-host/tests/store_versioning.tftest.hcl:7), `:44`, `:56`, `:141`. |
+| `.` envelope | **approve** | CLI/API changes add no root filesystem input or execution path. [store_versioning.go:119](/Users/paulcampbell/amadan.net/carlos/platform/.claude/worktrees/store-versioning/store_versioning.go:119), `:221`; `apimode.go:3573`. Findings 3–4 require functional fixes. |
+| `infra/modules/region-host` envelope | **approve** | Same operator-only IAM changes and exclusions as the two approved units. [main.tf:1182](/Users/paulcampbell/amadan.net/carlos/platform/.claude/worktrees/store-versioning/infra/modules/region-host/main.tf:1182). |
+| `infra/modules/region-host/tests` envelope | **approve** | New file contains mock planning assertions only. [store_versioning.tftest.hcl:29](/Users/paulcampbell/amadan.net/carlos/platform/.claude/worktrees/store-versioning/infra/modules/region-host/tests/store_versioning.tftest.hcl:29). |
+| `internal/objstore` envelope | **approve** | Existing name/ownership checks remain; bounded AWS client reused; policy adds denies; no new root filesystem input. [aws.go:94](/Users/paulcampbell/amadan.net/carlos/platform/.claude/worktrees/store-versioning/internal/objstore/aws.go:94), `walk.go:269`, `:292`, `:727`. Finding 1 requires storage-behavior fixes. |
+| `internal/provision` envelope | **approve** | Additive manifest field; census updates retain existing classifications. [provision.go:403](/Users/paulcampbell/amadan.net/carlos/platform/.claude/worktrees/store-versioning/internal/provision/provision.go:403), [store_versioning_census_test.go:17](/Users/paulcampbell/amadan.net/carlos/platform/.claude/worktrees/store-versioning/internal/provision/store_versioning_census_test.go:17). |
\ No newline at end of file
diff --git a/docs/superpowers/specs/2026-11-22-store-versioning-design.md b/docs/superpowers/specs/2026-11-22-store-versioning-design.md
index 5ec4fcd90..35da47643 100644
--- a/docs/superpowers/specs/2026-11-22-store-versioning-design.md
+++ b/docs/superpowers/specs/2026-11-22-store-versioning-design.md
@@ -4,9 +4,14 @@
**Branch:** `store-versioning` from `origin/main` `74aeb271c` ·
**Author:** Claude Opus 5.5, for Paul · **Discussion:** carlos/platform #1372.
-**Review history (stopping rules apply).** None yet. Round 1 is an
-independent review from the other model family (Astra for a Claude
-author), briefed from `docs/superpowers/reviews/REVIEW-BRIEF-TEMPLATE.md`.
+**Review history (stopping rules apply).** Round 1: Astra
+(`gpt-6-astra`, effort high, `codex exec -s read-only`) on `c953103e4`
+returned NOT READY: 3 P1s and 3 P2s, and approved every census unit and
+envelope. Findings and what was done about each:
+`docs/superpowers/reviews/CODEX-FINDINGS-store-versioning.md`. The P1 in
+the "history survives suspension and restore" family is answered by
+cutting the feature that produced it (stopping rule 2's second option):
+there is no `off` (decision 3).
The census card for this branch is
`docs/superpowers/notes/census-proposal-store-versioning.md`; it needs the
same reviewer's verdict (AGENTS.md, "The census").
@@ -69,7 +74,8 @@ gains an unconditional Deny on every action that can destroy a version or
change the bucket's versioning, lifecycle or policy, and the permissions
boundary already allows none of them. The console role gets a new, switched,
customer-managed grant (`store_versioning`) with exactly the calls the walk,
-the sweep, teardown and restore make. A person turns versioning on or off
+the sweep, teardown and restore make. A person turns versioning on, for
+good,
with `carlos store versioning`; anyone with the store verbs lists an object's
versions with `carlos store versions` and restores one with
`carlos store restore`, which copies the old version back as a new current
@@ -90,20 +96,26 @@ refuse any bucket that has ever been versioned.
may be set from 30 to 365, and can never be lowered on an existing store
(§5.2). The rule never sets `NewerNoncurrentVersions`, so overwriting an
object many times cannot push its oldest version out early.
-3. **Off is a suspend, not an erase.** S3 cannot un-version a bucket.
- `carlos store versioning off` sets Suspended and keeps the lifecycle
- rule, so every version that already exists is still kept for `keep_days`
- after it became noncurrent. Only objects written after "off" lose
- protection. The block is never removed once written, because teardown and
- the sizing sweep need to know a bucket may hold versions.
+3. **There is no off** (Astra round 1 P1). S3 cannot un-version a bucket,
+ only suspend it, and a suspended bucket is not safe: an ordinary
+ `PutObject` or `DeleteObject` there replaces the key's `null` version,
+ which is how every object written before versioning was first turned on
+ is held. So the app's own credential could destroy history before
+ `keep_days`. Once on, a store stays versioned until it is destroyed; the
+ setter refuses `enabled: false` (`versioning_permanent`) and the walks
+ refuse a block that says false (`ErrVersioningPermanent`). The block is
+ never removed once written, because teardown and the sizing sweep need
+ to know a bucket may hold versions.
4. **The store credential cannot destroy history, by any route** (§4). The
property is stated as "this credential cannot destroy a version", not as
"this action is absent from the Allow", and the MinIO contract test
checks it against a real server (§9.3). Explicit Denies, unconditional,
on every store, versioned or not.
-5. **Turning versioning on or off is a person's act.** The setter door takes
- no service credential (`svcrole.Set{}`), so an app holding an Admin
- service token cannot weaken its own store. Status, the version listing
+5. **Turning versioning on is a person's act.** The setter door takes no
+ service credential (`svcrole.Set{}`), and the create door refuses a
+ service credential that asks for versioning (`person_only`, Astra round
+ 1 P2), so an app holding an Admin service token cannot choose its own
+ store's history policy. Status, the version listing
and restore take Admin, like every other store verb: none of them can
remove anything.
6. **Restore copies, never deletes.** A restore is a server-side
@@ -140,7 +152,7 @@ unrecoverable before `keep_days`, and what closes it.
| `DeleteObject` with `versionId` | `s3:DeleteObjectVersion` | not in the boundary; explicit Deny |
| `DeleteObjects` naming `VersionId` | `s3:DeleteObjectVersion`, per key | the same |
| Replace the lifecycle with a short expiry | `s3:PutLifecycleConfiguration` | not in the boundary; explicit Deny |
-| Suspend versioning, then overwrite | `s3:PutBucketVersioning` | not in the boundary; explicit Deny. (Even then, only versions written after the suspend are exposed.) |
+| Suspend versioning, then overwrite or delete (replaces the key's `null` version) | `s3:PutBucketVersioning` | not in the boundary; explicit Deny; and no door ever suspends (decision 3) |
| A bucket policy granting the user itself more | `s3:PutBucketPolicy` | not in the boundary; explicit Deny. A same-account resource policy naming the user is not limited by its permissions boundary, so this one matters. |
| Delete the bucket policy the platform might write | `s3:DeleteBucketPolicy` | explicit Deny |
| Object Lock settings that block the platform's own expiry or teardown | `s3:PutBucketObjectLockConfiguration`, `s3:PutObjectRetention`, `s3:PutObjectLegalHold`, `s3:BypassGovernanceRetention` | not in the boundary; explicit Deny |
@@ -150,7 +162,9 @@ unrecoverable before `keep_days`, and what closes it.
| `DeleteObject` without a version | `s3:DeleteObject` | not destructive: it writes a delete marker |
| Flood a key with versions so the oldest expires | no action | the rule has no `NewerNoncurrentVersions` |
| Shorten `keep_days` | the setter door | person-only, and `keep_days` can never be lowered (§5.2) |
-| Turn versioning off | the setter door | person-only; and off keeps history (decision 3) |
+| Turn versioning off | the setter door | there is no off (decision 3) |
+| Restore into a bucket that is not Enabled (the copy writes a `null` version over the current one) | the restore door | refused unless the bucket reads Enabled (§6.4) |
+| Pile more versions on a key than one listing page holds | `s3:PutObject` | the listing pages (`after`/`next`), and restore looks a version up by its id (§6.4) |
The Denies go into `storePolicyJSON` unconditionally, for every store,
versioned or not, as the anti-forgery pair already does: an explicit Deny
@@ -203,8 +217,10 @@ compares, as `carlos store uploads status` does.
refused (`keep_days_lowered`). Raising it is allowed. This is what stops a
stolen session from shortening history to the floor and waiting; it can
only lengthen it, which costs money and destroys nothing.
-- `enabled: false` on a store with no block writes nothing and answers
- "never on". There is nothing to suspend.
+- `enabled: false` is refused (`versioning_permanent`), whatever the
+ store's state (decision 3).
+- The create door applies the same rule: omitted keeps the record's
+ retention, lower is refused (Astra round 1 P2).
- The block is never deleted, by any door. Teardown deletes the record last,
as ever.
@@ -231,7 +247,7 @@ platform never replaces a lifecycle rule it did not write.
1. read the lifecycle configuration; refuse a foreign one (§5.3);
2. if it is not exactly the rule for `want.KeepDays`, write it;
-3. `PutBucketVersioning` Enabled, or Suspended when `want.Enabled` is false.
+3. `PutBucketVersioning` Enabled. Never Suspended.
The rule goes first. Versioning Enabled with no rule would keep every
version forever; the rule with versioning still off costs nothing. Every
@@ -295,17 +311,29 @@ one door, at create time.
### 6.4 Restore and the version listing
-`Versioner.ListVersions(ctx, bucket, key, max)` lists one key's versions,
-newest first: version id, whether it is current, whether it is a delete
-marker, size, and last-modified time. `ListObjectVersions` with `Prefix:
-key`, keeping only entries whose key is exactly `key`, at most 100.
+`Versioner.ListVersions(ctx, bucket, key, after, max)` lists one page of a
+key's versions, newest first: version id, whether it is current, whether it
+is a delete marker, size, and last-modified time. `ListObjectVersions` with
+`Prefix: key`, `MaxKeys: max` (100), and `KeyMarker: key`,
+`VersionIdMarker: after` to resume, keeping only entries whose key is
+exactly `key`. It answers `next`, the `after` of the following page, while
+the listing is still on the key. A writer piling versions on a key cannot
+push the old ones out of reach (Astra round 1 P1).
+
+`Versioner.StatVersion(ctx, bucket, key, versionID)` finds one version by its
+id however deep it is: `HeadObject` naming the version (`s3:GetObjectVersion`;
+405 is a delete marker, 404 or 400 not one of the key's), and whether it is
+current from a one-entry version listing of the key (`HeadObject` without a
+version would need `s3:GetObject`, which the role does not hold).
`Versioner.RestoreVersion(ctx, bucket, key, versionID)` is `CopyObject` with
`CopySource: bucket/key?versionId=versionID`, `MetadataDirective: COPY` and
`TaggingDirective: REPLACE` with no tags. The new current version carries no
scan verdict, so the scanner judges it again; the console role needs no
-tagging permission for it. The door refuses, before copying: a version id
-that is not one of the key's versions (`no_version`), a delete marker
+tagging permission for it. The door refuses, before copying: a bucket that
+does not read Enabled (`not_enabled`; a copy there writes a `null` version
+over the current one, Astra round 1 P1), a version id that `StatVersion`
+does not find (`no_version`), a delete marker
(`delete_marker`), the version that is already current (`already_current`),
a version over 5 GiB, `CopyObject`'s limit (`too_large`), and a store whose
uploads are denied for its plan (`writes_denied`).
@@ -411,7 +439,8 @@ applies anything.
rule like the AWS adapter.
- AWS adapter against a stub S3: rule-first ordering; a foreign lifecycle
configuration refused with nothing written; our own rule left alone when
- unchanged and rewritten when `keep_days` moved; Suspended keeps the rule;
+ unchanged and rewritten when `keep_days` moved; the bucket is only ever set
+ Enabled; `StatVersion`'s 405/404/400 and current lookup; paged listing;
`EmptyVersions` paginates, batches at 1,000, deletes markers too, and
surfaces per-key errors; `ListVersions` keeps only the exact key, newest
first, capped; `RestoreVersion` sends the version in `CopySource` and
@@ -427,8 +456,10 @@ applies anything.
### 9.2 Console
- The setter: person-only (an Admin service credential is refused), 503
- without `StoreVersioning`, `keep_days` bounds, lowering refused, off with
- no block writes nothing, on over a conversion block refused, a declared
+ without `StoreVersioning`, `keep_days` bounds, lowering refused (by the
+ setter and by create), off refused, create with versioning refused to a
+ service credential, restore refused into a bucket that is not Enabled,
+ restore of a version past the first page, on over a conversion block refused, a declared
but ungranted store records the block and the walk applies it later, a
provisioned store is converged at once, audit rows written.
- Status, listing and restore: each refusal in §6.4, restore copies from the
@@ -473,9 +504,8 @@ allows a §4.1 action, with any combination of switches.
```text
carlos store create --app <a> [--environment <e>] --versioning [--keep-days <n>]
carlos store versioning on --app <a> [--environment <e>] [--keep-days <n>]
-carlos store versioning off --app <a> [--environment <e>]
carlos store versioning status --app <a> [--environment <e>]
-carlos store versions --app <a> [--environment <e>] --key <key>
+carlos store versions --app <a> [--environment <e>] --key <key> [--after <id>]
carlos store restore --app <a> [--environment <e>] --key <key> --version <id>
carlos instances enable --app <a> --private-storage --store-versioning
```
@@ -558,8 +588,17 @@ files (tofu run by an operator) and its new test file; the Go envelopes are
re-pinned for the objstore walks, the manifest field (nothing on a box reads
it) and the CLI.
+### 10.5 Older consoles (Astra round 1 P1)
+
+A console from before this change ignores the create body's `versioning`
+and the enable body's `store_versioning` and answers success. The CLI
+therefore requires the answer to carry them: `store create --versioning`
+refuses, before provisioning, an answer with no enabled versioning block,
+and `instances enable --store-versioning` refuses an answer whose
+`store_versioning` is not true, both naming the upgrade. `--keep-days` is
+checked (30 to 365) before any request, so a bad value never falls back
+to an unversioned create (round 1 P2).
+
## 12. Open questions for the reviewer
-1. Is person-only right for "off", given that off keeps history (decision
- 3), or should it also need a passkey, like store destroy?
-2. Is a 365-day ceiling the right bound on `keep_days`?
+1. Is a 365-day ceiling the right bound on `keep_days`?
diff --git a/infra/modules/region-host/README.md b/infra/modules/region-host/README.md
index 221553f5e..215f7ec2c 100644
--- a/infra/modules/region-host/README.md
+++ b/infra/modules/region-host/README.md
@@ -110,7 +110,7 @@ looks exactly like a deploy that did nothing.
`store_conversion = true` lets this host’s role check the buckets under `store_bucket_prefix` before media conversion uses them, and set them up for browser uploads. The role can read each bucket’s policy, encryption and versioning, and read and change its CORS rules, lifecycle rules and tags. Store users can also list the parts of their multipart uploads and abort those uploads. It is off by default, so a deployment that has not switched it on plans no change. Set it on the console’s box only, along with `CARLOS_STORE_CONVERSION=1` on the console.
-`store_versioning = true` lets this host’s role version the buckets under `store_bucket_prefix`: turn versioning on or off, write the platform’s one lifecycle rule that removes old versions after the store’s retention, list old versions, copy one back for a restore, and delete every version when a versioned store is destroyed. Store users get none of this, and their own policy denies every action that deletes a version or changes a bucket’s versioning, lifecycle or policy. It is off by default, so a deployment that has not switched it on plans no change. Set it on the console’s box only, along with `CARLOS_STORE_VERSIONING=1` on the console. Like `store_conversion`, it needs a dedicated `store_bucket_prefix` ending in `-store-`.
+Set `store_versioning = true` to let this host’s role turn versioning on for buckets under `store_bucket_prefix`. The role can write the platform’s one lifecycle rule, which removes old versions after the store’s retention period. It can list old versions, copy one back for a restore, and delete every version when a versioned store is destroyed. It never turns versioning off. Store users get none of these permissions. Their own policy denies every action that deletes a version or changes a bucket’s versioning, lifecycle or policy. This setting is off by default. A deployment that has not switched it on plans no change. Set it only on the box that runs the console. Also set `CARLOS_STORE_VERSIONING=1` on the console. Like `store_conversion`, it requires a dedicated `store_bucket_prefix` ending in `-store-`.
The switch needs a `store_bucket_prefix` used only for stores: lower-case letters, digits and hyphens, ending in `-store-`, such as `carlos-store-`. The plan fails on a broader prefix such as `carlos-`, because this grant can replace the settings of every bucket the prefix matches. It also fails if the name of the deployment bucket, the data bucket or a sibling staging bucket starts with the prefix, or if the prefix and `managed_fleet_bucket_prefix` overlap. That last check applies even with managed fleets off, because fleet buckets stay after the switch is turned off. With managed fleets on, the switch also needs `managed_fleets_inline_retired = true` (see below).
diff --git a/infra/modules/region-host/variables.tf b/infra/modules/region-host/variables.tf
index 4905e91a1..750f91806 100644
--- a/infra/modules/region-host/variables.tf
+++ b/infra/modules/region-host/variables.tf
@@ -307,7 +307,7 @@ variable "store_conversion" {
}
variable "store_versioning" {
- description = "Let this host's role version the buckets under store_bucket_prefix, keep their old versions on a platform lifecycle rule, list and copy old versions back for a restore, and delete every version when a versioned store is destroyed. Off by default: the role gets no new grant, and the store user boundary never changes either way. Set it only on the box that runs the console, together with CARLOS_STORE_VERSIONING=1 on the console. Requires a dedicated store_bucket_prefix ending in -store-, such as carlos-store-, that none of the deployment, data or sibling staging buckets start with and that does not overlap managed_fleet_bucket_prefix."
+ description = "Allow this host's role to turn bucket versioning on under store_bucket_prefix, keep old versions with a platform lifecycle rule, list old versions, copy one back for a restore, and delete every version when a versioned store is destroyed. Off by default: the role gets no new permissions. The store user boundary does not change whether this is on or off. Set it only on the box that runs the console, and also set CARLOS_STORE_VERSIONING=1 on the console. Use a dedicated store_bucket_prefix ending in -store-, such as carlos-store-. No deployment, data or sibling staging bucket may start with that prefix, and it must not overlap managed_fleet_bucket_prefix."
type = bool
default = false
}
diff --git a/instances_cli.go b/instances_cli.go
index d4fcba742..d8445c7b2 100644
--- a/instances_cli.go
+++ b/instances_cli.go
@@ -79,7 +79,7 @@ func runInstancesEnable(args []string) {
// preserves whatever policy the manifest already carries, and
// --private-storage=false turns the policy off.
privateStorage := fs.Bool("private-storage", false, "give every instance of this app a config environment and an object store of its own (issue #412); --private-storage=false turns the policy off")
- storeVersioning := fs.Bool("store-versioning", false, "version every private store made from now on, keeping old versions 30 days (see carlos store versioning); --store-versioning=false turns the policy off")
+ storeVersioning := fs.Bool("store-versioning", false, "turn versioning on for every private store made from now on, keeping old versions for 30 days (see carlos store versioning); --store-versioning=false turns this policy off")
consoleFlag := consoleOption(fs, "console to enable through (signed-in mode only; default: the only logged-in one)")
acctRaw, acctIDRaw, acctOf := accountFlags(fs)
fs.Usage = flagUsage(fs, instancesEnableUsage)
@@ -126,6 +126,9 @@ func runInstancesEnable(args []string) {
acct := resolvedAccount(sess, acctRaw, acctIDRaw)
app2 := resolvedApp(sess, acct, *app, instancesEnableUsage)
m, err := sess.instancesEnable(context.Background(), acct, app2, channelReq, seedReq, privateStorageReq, storeVersioningReq)
+ if err == nil {
+ err = storeVersioningEchoed(storeVersioningReq, m)
+ }
if err != nil {
log.Fatalf("instances enable: %v", err)
}
diff --git a/internal/console/apistore.go b/internal/console/apistore.go
index 2ae7ab5a5..d8e4c03a4 100644
--- a/internal/console/apistore.go
+++ b/internal/console/apistore.go
@@ -408,6 +408,13 @@ func (s *Server) handleAPIStoreCreate(w http.ResponseWriter, r *http.Request) {
if !s.versioningConfiguredOr(w) {
return
}
+ // Choosing versioning is a person's act at this door too (spec
+ // decision 5, Astra round 1 P2): the route admits an Admin service
+ // credential for an ordinary create, but not for this.
+ if p.Kind != PrincipalUser {
+ jsonErrorCode(w, http.StatusForbidden, versioningCodePersonOnly, versioningText("versioning.person_only"))
+ return
+ }
if req.Versioning.KeepDays != 0 && !objstore.ValidKeepDays(req.Versioning.KeepDays) {
jsonErrorCode(w, http.StatusBadRequest, versioningCodeBadKeepDays, versioningText("versioning.bad_keep_days"))
return
@@ -498,11 +505,14 @@ func (s *Server) handleAPIStoreCreate(w http.ResponseWriter, r *http.Request) {
jsonErrorCode(w, http.StatusConflict, versioningCodeInUseByMedia, versioningText("versioning.in_use_by_media"))
return
}
- days := req.Versioning.KeepDays
- if days == 0 {
- days = objstore.DefaultKeepDays
+ // The setter's retention rule: omitted keeps what the record has,
+ // and a lower value is refused, never applied.
+ days, code, msg := nextKeepDays(rec.Versioning, req.Versioning.KeepDays)
+ if code != "" {
+ jsonErrorCode(w, http.StatusConflict, code, msg)
+ return
}
- if v := rec.Versioning; v == nil || !v.Enabled || v.KeepDays < days {
+ if v := rec.Versioning; v == nil || !v.Enabled || v.KeepDays != days {
rec.Versioning = &objstore.Versioning{Enabled: true, KeepDays: days, At: time.Now().UTC(), By: addr}
wantVersioning = true
}
diff --git a/internal/console/apistoreversioning.go b/internal/console/apistoreversioning.go
index c45c415d9..71cb4c05b 100644
--- a/internal/console/apistoreversioning.go
+++ b/internal/console/apistoreversioning.go
@@ -13,7 +13,7 @@ import (
)
// Store versioning (spec docs/superpowers/specs/2026-11-22-store-versioning-design.md
-// §10.2): `carlos store versioning on|off|status`, `carlos store versions`
+// §10.2): `carlos store versioning on|status`, `carlos store versions`
// and `carlos store restore`, on any store of an app (?environment= as
// every store door).
//
@@ -48,6 +48,9 @@ const (
versioningCodeInUseByMedia = "store_in_use_by_media"
versioningCodeLifecycleInUse = "lifecycle_in_use"
versioningCodeExisting = "store_exists"
+ versioningCodePermanent = "versioning_permanent"
+ versioningCodePersonOnly = "person_only"
+ restoreCodeNotEnabled = "not_enabled"
versionsCodeNoKey = "no_key"
versionsCodeBadKey = "bad_key"
versionsCodeNotVersioned = "not_versioned"
@@ -71,9 +74,9 @@ const (
)
// versioningAnswer is the setter's and the status door's answer. Versioning
-// is "on", "off" (suspended: old versions still expire on the platform's
-// rule) or "never". Bucket is one of the versioningBucket states, "" for a
-// store that was never versioned.
+// is "on", "off" (a hand-edited block only: no door writes one, and the
+// walks refuse it) or "never". Bucket is one of the versioningBucket states,
+// "" for a store that was never versioned.
type versioningAnswer struct {
Environment string `json:"environment"`
Versioning string `json:"versioning"`
@@ -82,7 +85,8 @@ type versioningAnswer struct {
}
// versioningBody is the setter's body. KeepDays 0 keeps the store's current
-// retention, or takes the default for a store that has none.
+// retention, or takes the default for a store that has none. Enabled must be
+// true: versioning cannot be turned off (objstore.ErrVersioningPermanent).
type versioningBody struct {
Enabled bool `json:"enabled"`
KeepDays int `json:"keep_days"`
@@ -131,6 +135,27 @@ func versioningInternal(w http.ResponseWriter, what string, err error, msg strin
jsonError(w, http.StatusBadGateway, msg)
}
+// nextKeepDays is the retention a request for keepDays (0: keep the
+// store's, or the default) gives a store whose block is cur, or the refusal
+// (spec §5.2): keep_days is 30 to 365 and never lowered. The setter and the
+// create door both use it, so neither can lower what the other set.
+func nextKeepDays(cur *objstore.Versioning, keepDays int) (days int, code, msg string) {
+ if keepDays != 0 && !objstore.ValidKeepDays(keepDays) {
+ return 0, versioningCodeBadKeepDays, versioningText("versioning.bad_keep_days")
+ }
+ days = keepDays
+ if days == 0 {
+ days = objstore.DefaultKeepDays
+ if cur != nil {
+ days = cur.KeepDays
+ }
+ }
+ if cur != nil && days < cur.KeepDays {
+ return 0, versioningCodeKeepDaysLower, versioningText("versioning.keep_days_lowered", cur.KeepDays)
+ }
+ return days, "", ""
+}
+
// versioningState is a record's block as the answer names it.
func versioningState(v *objstore.Versioning) (state string, keepDays int) {
switch {
@@ -213,21 +238,23 @@ func (s *Server) handleAPIStoreVersioningGet(w http.ResponseWriter, r *http.Requ
}
// handleAPIStoreVersioningSet is POST .../store/versioning: `carlos store
-// versioning on` ({"enabled": true}) and `off` ({"enabled": false}). A person
-// only (the route admits no service credential). After apiAccountApp, in
-// order, stopping at the first failure:
+// versioning on` ({"enabled": true}). There is no off: {"enabled": false} is
+// refused, because a suspended bucket lets the app's own writes replace
+// null versions (spec decision 3, Astra round 1 P1). A person only (the route
+// admits no service credential). After apiAccountApp, in order, stopping at
+// the first failure:
//
// 1. host-claim console: 409 (claimUnsupported)
// 2. not switched on, or no Versioner: 503
// 3. the store walk gates (write budget, deployment bucket, backend)
// 4. ?environment= and the body (strict JSON, at most 4 KiB)
-// 5. keep_days, when given, from 30 to 365: 400 bad_keep_days
+// 5. enabled false: 400 versioning_permanent
+// 6. keep_days, when given, from 30 to 365: 400 bad_keep_days
//
// Then, under the account lock and the store's walk lock:
//
-// 6. no declared store: 404 no_store
-// 7. off on a store never versioned: 200 "never", nothing written
-// 8. on over a conversion block (verified for media, or browser uploads):
+// 7. no declared store: 404 no_store
+// 8. a conversion block (verified for media, or browser uploads):
// 409 store_in_use_by_media (spec §7)
// 9. keep_days lower than the store's: 409 keep_days_lowered (§5.2)
// 10. a provisioned store whose bucket holds a lifecycle rule the
@@ -262,6 +289,10 @@ func (s *Server) handleAPIStoreVersioningSet(w http.ResponseWriter, r *http.Requ
if !readJSONStrictLimit(w, r, &body, versioningBodyLimit) {
return
}
+ if !body.Enabled {
+ jsonErrorCode(w, http.StatusBadRequest, versioningCodePermanent, versioningText("versioning.permanent"))
+ return
+ }
if body.KeepDays != 0 && !objstore.ValidKeepDays(body.KeepDays) {
jsonErrorCode(w, http.StatusBadRequest, versioningCodeBadKeepDays, versioningText("versioning.bad_keep_days"))
return
@@ -281,24 +312,13 @@ func (s *Server) handleAPIStoreVersioningSet(w http.ResponseWriter, r *http.Requ
versioningNoStore(w, app)
return
}
- if !body.Enabled && rec.Versioning == nil {
- writeJSON(w, http.StatusOK, versioningAnswer{Environment: env, Versioning: "never"})
- return
- }
- if body.Enabled && rec.Conversion != nil {
+ if rec.Conversion != nil {
jsonErrorCode(w, http.StatusConflict, versioningCodeInUseByMedia, versioningText("versioning.in_use_by_media"))
return
}
- days := body.KeepDays
- if days == 0 {
- days = objstore.DefaultKeepDays
- if rec.Versioning != nil {
- days = rec.Versioning.KeepDays
- }
- }
- if rec.Versioning != nil && days < rec.Versioning.KeepDays {
- jsonErrorCode(w, http.StatusConflict, versioningCodeKeepDaysLower,
- versioningText("versioning.keep_days_lowered", rec.Versioning.KeepDays))
+ days, code, msg := nextKeepDays(rec.Versioning, body.KeepDays)
+ if code != "" {
+ jsonErrorCode(w, http.StatusConflict, code, msg)
return
}
if rec.Provisioned != nil {
@@ -312,8 +332,8 @@ func (s *Server) handleAPIStoreVersioningSet(w http.ResponseWriter, r *http.Requ
return
}
}
- if v := rec.Versioning; v == nil || v.Enabled != body.Enabled || v.KeepDays != days {
- rec.Versioning = &objstore.Versioning{Enabled: body.Enabled, KeepDays: days, At: s.now().UTC(), By: addr}
+ if v := rec.Versioning; v == nil || !v.Enabled || v.KeepDays != days {
+ rec.Versioning = &objstore.Versioning{Enabled: true, KeepDays: days, At: s.now().UTC(), By: addr}
if _, err := claimAppCall(s, ctx, acct, app, "store-versioning", func(ctx context.Context) (string, error) {
return objstore.PutIn(ctx, s.cfg.Releases, acct.Sqid, app, env, rec, etag)
}); err != nil {
@@ -324,11 +344,7 @@ func (s *Server) handleAPIStoreVersioningSet(w http.ResponseWriter, r *http.Requ
versioningInternal(w, "set write "+acct.Sqid+"/"+app, err, "could not record the setting. nothing was changed; try again")
return
}
- if body.Enabled {
- s.audit(acct, app, addr, "store-versioning-on", versioningText("audit.versioning_on", storeEnvSuffix(env), days))
- } else {
- s.audit(acct, app, addr, "store-versioning-off", versioningText("audit.versioning_off", storeEnvSuffix(env)))
- }
+ s.audit(acct, app, addr, "store-versioning-on", versioningText("audit.versioning_on", storeEnvSuffix(env), days))
}
if rec.Provisioned != nil {
if _, err := claimAppCall(s, ctx, acct, app, "store-versioning", func(ctx context.Context) (*objstore.Record, error) {
@@ -377,9 +393,11 @@ func validObjectKey(k string) bool {
return k != "" && len(k) <= 1024 && utf8.ValidString(k) && !strings.ContainsRune(k, 0)
}
-// handleAPIStoreVersions is GET .../store/versions?key=: `carlos store
-// versions`. One key's versions, newest first, at most 100. It writes
-// nothing and takes no lock.
+// handleAPIStoreVersions is GET .../store/versions?key=[&after=]: `carlos
+// store versions`. One page of a key's versions, newest first, at most 100,
+// and "next", the after for the following page ("" when there is none), so
+// every retained version can be listed however many a writer piled on top
+// (Astra round 1 P1). It writes nothing and takes no lock.
func (s *Server) handleAPIStoreVersions(w http.ResponseWriter, r *http.Request) {
_, acct, app, ok := s.apiAccountApp(w, r)
if !ok {
@@ -415,7 +433,8 @@ func (s *Server) handleAPIStoreVersions(w http.ResponseWriter, r *http.Request)
if !ok {
return
}
- versions, err := s.storeVersioner().ListVersions(ctx, rec.Provisioned.Bucket, key, objstore.MaxListedVersions)
+ versions, next, err := s.storeVersioner().ListVersions(ctx, rec.Provisioned.Bucket, key,
+ r.URL.Query().Get("after"), objstore.MaxListedVersions)
if err != nil {
versioningInternal(w, "list "+acct.Sqid+"/"+app, err, "could not list this object's versions — try again")
return
@@ -423,17 +442,18 @@ func (s *Server) handleAPIStoreVersions(w http.ResponseWriter, r *http.Request)
if versions == nil {
versions = []objstore.ObjectVersion{}
}
- writeJSON(w, http.StatusOK, map[string]any{"environment": env, "key": key, "versions": versions})
+ writeJSON(w, http.StatusOK, map[string]any{"environment": env, "key": key, "versions": versions, "next": next})
}
// handleAPIStoreRestore is POST .../store/restore: `carlos store restore`.
// After apiAccountApp, in order: a host-claim console (409), not switched
// on (503), the walk gates, ?environment=, the body, the key. Then under the
-// store's walk lock, so a teardown cannot run between the listing and the
+// store's walk lock, so a teardown cannot run between the lookup and the
// copy: the store must be provisioned and versioned, must not be refusing
-// uploads for its plan (409 writes_denied), and the version must be among
-// the key's newest 100 (409 no_version), hold bytes (409 delete_marker),
-// not already be current (409 already_current), and be at most 5 GiB (409
+// uploads for its plan (409 writes_denied), its bucket must really be
+// Enabled (409 not_enabled), and the version, looked up by its id, must be
+// one of the key's (409 no_version), hold bytes (409 delete_marker), not
+// already be current (409 already_current), and be at most 5 GiB (409
// too_large). Then the copy (spec §6.4), which makes a new current version
// and removes nothing.
func (s *Server) handleAPIStoreRestore(w http.ResponseWriter, r *http.Request) {
@@ -480,22 +500,30 @@ func (s *Server) handleAPIStoreRestore(w http.ResponseWriter, r *http.Request) {
return
}
bucket := rec.Provisioned.Bucket
- versions, err := s.storeVersioner().ListVersions(ctx, bucket, body.Key, objstore.MaxListedVersions)
+ // The bucket must really be Enabled: a copy into a bucket that is not
+ // (versioning not applied yet, or suspended by hand) writes a null
+ // version, which replaces the key's current null version for good.
+ state, err := s.storeVersioner().ReadVersioning(ctx, bucket)
if err != nil {
- versioningInternal(w, "restore list "+acct.Sqid+"/"+app, err, versioningText("restore.failed", body.Key))
+ versioningInternal(w, "restore read bucket "+acct.Sqid+"/"+app, err, versioningText("restore.failed", body.Key))
return
}
- var found *objstore.ObjectVersion
- for i := range versions {
- if versions[i].VersionID == body.VersionID {
- found = &versions[i]
- break
- }
+ if state.Status != "Enabled" {
+ jsonErrorCode(w, http.StatusConflict, restoreCodeNotEnabled, versioningText("restore.not_enabled"))
+ return
}
- switch {
- case found == nil:
+ // Found by its id, however many newer versions there are.
+ v, err := s.storeVersioner().StatVersion(ctx, bucket, body.Key, body.VersionID)
+ if errors.Is(err, objstore.ErrNoSuchVersion) || body.VersionID == "" {
jsonErrorCode(w, http.StatusConflict, restoreCodeNoVersion, versioningText("restore.no_version", body.Key, body.VersionID))
return
+ }
+ if err != nil {
+ versioningInternal(w, "restore stat "+acct.Sqid+"/"+app, err, versioningText("restore.failed", body.Key))
+ return
+ }
+ found := &v
+ switch {
case found.DeleteMarker:
jsonErrorCode(w, http.StatusConflict, restoreCodeDeleteMarker, versioningText("restore.delete_marker", body.VersionID))
return
diff --git a/internal/console/apistoreversioning_test.go b/internal/console/apistoreversioning_test.go
index 164f32c6e..5ee4a48bb 100644
--- a/internal/console/apistoreversioning_test.go
+++ b/internal/console/apistoreversioning_test.go
@@ -101,7 +101,7 @@ func TestVersioningDoorsRefuseWhenNotSwitchedOn(t *testing.T) {
// On, the bucket is versioned with the platform's rule at once, and status
// reads it back as in place. Off suspends it and keeps the rule.
-func TestVersioningOnAndOffProvisionedStore(t *testing.T) {
+func TestVersioningOnProvisionedStoreAndNoOff(t *testing.T) {
v := newVersioningFixture(t, "code-ver-on", true)
got := v.wantOK(v.set(`{"enabled":true}`))
if got.Versioning != "on" || got.KeepDays != 30 || got.Bucket != versioningBucketInPlace {
@@ -123,25 +123,22 @@ func TestVersioningOnAndOffProvisionedStore(t *testing.T) {
t.Fatalf("store status lacks the block: %s", raw)
}
- off := v.wantOK(v.set(`{"enabled":false}`))
- if off.Versioning != "off" || off.KeepDays != 30 || off.Bucket != versioningBucketInPlace {
- t.Fatalf("off = %+v", off)
- }
- if b := v.prov.VersioningOf(v.bucket); b.Status != "Suspended" || b.KeepDays != 30 {
- t.Fatalf("off: bucket = %+v, want Suspended with the rule kept", b)
+ // There is no off (Astra round 1 P1): a suspended bucket lets the app's
+ // own writes replace null versions. The bucket stays Enabled.
+ v.wantRefused(v.set(`{"enabled":false}`), http.StatusBadRequest, versioningCodePermanent)
+ if b := v.prov.VersioningOf(v.bucket); b.Status != "Enabled" || b.KeepDays != 30 {
+ t.Fatalf("after a refused off: bucket = %+v", b)
}
- if v.record().Versioning == nil {
- t.Fatal("off removed the block")
+ if rec := v.record(); rec.Versioning == nil || !rec.Versioning.Enabled {
+ t.Fatalf("after a refused off: record = %+v", rec.Versioning)
}
}
-// Off on a store that was never versioned writes nothing.
+// Off is refused on any store, and writes nothing.
func TestVersioningOffNeverOnWritesNothing(t *testing.T) {
v := newVersioningFixture(t, "code-ver-never", true)
before, beforeTag := rawStoreRecord(t, v.consoleFixture)
- if got := v.wantOK(v.set(`{"enabled":false}`)); got.Versioning != "never" {
- t.Fatalf("off = %+v", got)
- }
+ v.wantRefused(v.set(`{"enabled":false}`), http.StatusBadRequest, versioningCodePermanent)
after, afterTag := rawStoreRecord(t, v.consoleFixture)
if string(before) != string(after) || beforeTag != afterTag {
t.Fatal("off on a never-versioned store wrote the record")
@@ -163,7 +160,7 @@ func TestVersioningKeepDays(t *testing.T) {
t.Fatalf("raised = %+v", got)
}
v.wantRefused(v.set(`{"enabled":true,"keep_days":60}`), http.StatusConflict, versioningCodeKeepDaysLower)
- v.wantRefused(v.set(`{"enabled":false,"keep_days":30}`), http.StatusConflict, versioningCodeKeepDaysLower)
+ v.wantRefused(v.set(`{"enabled":false,"keep_days":30}`), http.StatusBadRequest, versioningCodePermanent)
// Omitted keeps the store's own.
if got := v.wantOK(v.set(`{"enabled":true}`)); got.KeepDays != 90 {
t.Fatalf("omitted = %+v", got)
@@ -251,6 +248,35 @@ func TestStoreCreateWithVersioning(t *testing.T) {
v.wantRefused(v.call(http.MethodPost, "", v.token, `{"versioning":{}}`), http.StatusConflict, versioningCodeExisting)
}
+// Create follows the setter's retention rule on a declared store: omitted
+// keeps the record's retention, lower is refused (Astra round 1 P2).
+func TestStoreCreateNeverLowersRetention(t *testing.T) {
+ v := newVersioningFixture(t, "code-ver-create-lower", false)
+ declareStore(t, v.consoleFixture, v.token)
+ v.wantOK(v.set(`{"enabled":true,"keep_days":90}`))
+ v.wantRefused(v.call(http.MethodPost, "", v.token, `{"versioning":{"keep_days":60}}`), http.StatusConflict, versioningCodeKeepDaysLower)
+ if status, _, raw := rawReq(t, http.MethodPost, storeURL(v.consoleFixture, "titogo"), v.token, `{"versioning":{}}`); status != http.StatusOK {
+ t.Fatalf("create with retention omitted = %d %s", status, raw)
+ }
+ if rec := v.record(); rec.Versioning == nil || rec.Versioning.KeepDays != 90 {
+ t.Fatalf("record = %+v, want 90 days kept", rec.Versioning)
+ }
+}
+
+// Create with versioning takes a person, even though an ordinary create
+// admits an Admin service credential (Astra round 1 P2).
+func TestStoreCreateVersioningIsPersonOnly(t *testing.T) {
+ v := newVersioningFixture(t, "code-ver-create-svc", false)
+ admin := serviceToken(t, v.st, OpsAccountID, "ops-bot", "titogo", svcrole.Admin)
+ v.wantRefused(v.call(http.MethodPost, "", admin, `{"versioning":{}}`), http.StatusForbidden, versioningCodePersonOnly)
+ if rec := v.record(); rec != nil {
+ t.Fatalf("the refused create wrote %+v", rec)
+ }
+ if status, _, raw := rawReq(t, http.MethodPost, storeURL(v.consoleFixture, "titogo"), admin, `{}`); status != http.StatusOK {
+ t.Fatalf("an ordinary create by the same credential = %d %s", status, raw)
+ }
+}
+
type versionsReply struct {
Key string `json:"key"`
Versions []objstore.ObjectVersion `json:"versions"`
@@ -304,6 +330,12 @@ func TestVersionsAndRestore(t *testing.T) {
t.Fatalf("current after undelete = %q", got)
}
+ // A bucket that is not Enabled (suspended by hand) is refused: a copy
+ // there would replace the current null version (Astra round 1 P1).
+ v.prov.SetStatus(v.bucket, "Suspended")
+ v.wantRefused(restore("blobs/a", old), http.StatusConflict, restoreCodeNotEnabled)
+ v.prov.SetStatus(v.bucket, "Enabled")
+
// A store refusing uploads for its plan refuses a restore too.
rec := v.record()
rec.WritesDenied = &objstore.WritesDenied{Reason: "plan storage", At: time.Now().UTC()}
@@ -314,6 +346,39 @@ func TestVersionsAndRestore(t *testing.T) {
v.wantRefused(restore("blobs/a", old), http.StatusConflict, restoreCodeWritesDenied)
}
+// A writer piling more than a page of versions on a key cannot hide the old
+// ones: the listing pages with after/next, and restore finds a version by
+// its id however deep it is (Astra round 1 P1).
+func TestRestoreReachesAVersionPastThePage(t *testing.T) {
+ v := newVersioningFixture(t, "code-ver-deep", true)
+ v.wantOK(v.set(`{"enabled":true}`))
+ v.prov.PutObject(v.bucket, "k", []byte("good"))
+ for i := 0; i < objstore.MaxListedVersions+3; i++ {
+ v.prov.PutObject(v.bucket, "k", []byte("garbage"))
+ }
+ good := v.prov.VersioningOf(v.bucket).History["k"][0].ID
+ var page struct {
+ Versions []objstore.ObjectVersion `json:"versions"`
+ Next string `json:"next"`
+ }
+ r := v.call(http.MethodGet, "/versions?key=k", v.token, "")
+ if err := json.Unmarshal([]byte(r.raw), &page); err != nil || len(page.Versions) != objstore.MaxListedVersions || page.Next == "" {
+ t.Fatalf("first page = %d versions, next %q (%d)", len(page.Versions), page.Next, r.status)
+ }
+ r = v.call(http.MethodGet, "/versions?key=k&after="+url.QueryEscape(page.Next), v.token, "")
+ page.Versions, page.Next = nil, ""
+ if err := json.Unmarshal([]byte(r.raw), &page); err != nil || len(page.Versions) != 4 || page.Next != "" || page.Versions[3].VersionID != good {
+ t.Fatalf("second page = %s", r.raw)
+ }
+ b, _ := json.Marshal(map[string]string{"key": "k", "version_id": good})
+ if r := v.call(http.MethodPost, "/restore", v.token, string(b)); r.status != http.StatusOK {
+ t.Fatalf("restore of the oldest = %d %s", r.status, r.raw)
+ }
+ if got := string(v.prov.Buckets[v.bucket]["k"]); got != "good" {
+ t.Fatalf("current after restore = %q", got)
+ }
+}
+
// Media conversion and browser uploads never trust a versioned store, even
// one with a verification on record.
func TestMediaStoreCheckRefusesAVersionedStore(t *testing.T) {
diff --git a/internal/console/routedecls.go b/internal/console/routedecls.go
index 1e2cbfc5f..260ca8a10 100644
--- a/internal/console/routedecls.go
+++ b/internal/console/routedecls.go
@@ -1081,10 +1081,10 @@ var routeDecls = []routeDecl{
{Pattern: "POST /api/cli/apps/{account}/{app}/store/uploads", Kind: kindCLI, Allow: svcrole.Allow(svcrole.Admin), Handler: (*Server).handleAPIStoreUploadsSet},
{Pattern: "GET /api/cli/apps/{account}/{app}/store/uploads", Kind: kindCLI, Allow: svcrole.Allow(svcrole.Admin), Handler: (*Server).handleAPIStoreUploadsGet},
// Store versioning (apistoreversioning.go, store versioning spec §10.2).
- // Turning it on or off is a person's act: the zero Set, so an app's own
- // Admin service credential cannot weaken its store's history. Status, the
- // version listing and restore take Admin like every store verb; none of
- // them removes anything.
+ // Turning it on is a person's act: the zero Set, so an app's own Admin
+ // service credential cannot choose its store's history policy. There is
+ // no off. Status, the version listing and restore take Admin like every
+ // store verb; none of them removes anything.
{Pattern: "POST /api/cli/apps/{account}/{app}/store/versioning", Kind: kindCLI, Allow: svcrole.Set{}, Handler: (*Server).handleAPIStoreVersioningSet},
{Pattern: "GET /api/cli/apps/{account}/{app}/store/versioning", Kind: kindCLI, Allow: svcrole.Allow(svcrole.Admin), Handler: (*Server).handleAPIStoreVersioningGet},
{Pattern: "GET /api/cli/apps/{account}/{app}/store/versions", Kind: kindCLI, Allow: svcrole.Allow(svcrole.Admin), Handler: (*Server).handleAPIStoreVersions},
diff --git a/internal/console/store_versioning_copy.go b/internal/console/store_versioning_copy.go
index d34473634..f3c92e267 100644
--- a/internal/console/store_versioning_copy.go
+++ b/internal/console/store_versioning_copy.go
@@ -8,27 +8,29 @@ import "fmt"
// deck together, not by hand in one of them.
var versioningCopy = map[string]string{
"versioning.not_configured": "store versioning isn't switched on for this deployment (CARLOS_STORE_VERSIONING)",
- "versioning.claims_console": "store versioning isn't available while host claims are on",
- "versioning.unsupported": "this deployment's storage backend can't version buckets",
- "versioning.no_store": "%s has no store here. Run carlos store create --app %s --versioning",
+ "versioning.claims_console": "store versioning isn't available on this console while host claims are on",
+ "versioning.unsupported": "this deployment's storage service doesn't support bucket versioning",
+ "versioning.no_store": "%s has no store here; run carlos store create --app %s --versioning",
"versioning.no_bucket": "this store has no bucket yet",
- "versioning.bad_keep_days": "keep days must be from 30 to 365",
- "versioning.keep_days_lowered": "this store keeps old versions for %d days, and that can't be lowered",
+ "versioning.bad_keep_days": "old versions must be kept for 30 to 365 days",
+ "versioning.keep_days_lowered": "this store keeps old versions for %d days; you can't lower that setting",
+ "versioning.permanent": "versioning can't be turned off once it is on; the store keeps old versions until the store is destroyed",
+ "versioning.person_only": "only a person signed in can turn versioning on; a service credential can't",
"versioning.in_use_by_media": "this store is set up for media conversion or browser uploads, and both need versioning off",
- "versioning.lifecycle_in_use": "the bucket has a lifecycle rule this platform didn't write. Remove it, then run this again",
- "versioning.bucket_failed": "versioning is recorded, but the bucket wasn't changed. Run the same command again",
- "versioning.create_existing": "this store already exists. Turn versioning on with carlos store versioning on",
+ "versioning.lifecycle_in_use": "the bucket has a lifecycle rule this platform didn't write; ask your deployment operator to remove it, then run this again",
+ "versioning.bucket_failed": "versioning is recorded, but the bucket wasn't changed; run the same command again",
+ "versioning.create_existing": "this store already exists; turn versioning on with carlos store versioning on",
"versions.no_key": "name the object with --key",
"versions.bad_key": "%q isn't an object key",
"versions.not_versioned": "this store has never had versioning on, so it keeps no old versions",
- "restore.no_version": "%s has no version %s among its newest 100",
+ "restore.not_enabled": "this store's bucket isn't versioned yet; run carlos store versioning on, then try again",
+ "restore.no_version": "%s has no version %s",
"restore.delete_marker": "version %s marks a delete, so it holds nothing to restore",
"restore.already_current": "version %s is already the current one",
- "restore.too_large": "version %s is over 5 GiB, which restore can't copy",
- "restore.writes_denied": "this store refuses uploads while its plan's storage is full, so nothing can be restored into it",
- "restore.failed": "%s wasn't restored, and nothing changed. Try again",
- "audit.versioning_on": "turned versioning on%s, keeping old versions %d days (cli)",
- "audit.versioning_off": "turned versioning off%s (cli)",
+ "restore.too_large": "version %s is larger than 5 GiB (gibibytes), so restore can't copy it",
+ "restore.writes_denied": "this store refuses uploads because its plan's storage is full; you can't restore into it until space is available",
+ "restore.failed": "%s may not have been restored; run carlos store versions to check, then try again",
+ "audit.versioning_on": "turned versioning on%s, keeping old versions for %d days (cli)",
"audit.restore": "restored %s from version %s%s (cli)",
}
diff --git a/internal/objstore/aws_versioning.go b/internal/objstore/aws_versioning.go
index 48a26258a..89ad13686 100644
--- a/internal/objstore/aws_versioning.go
+++ b/internal/objstore/aws_versioning.go
@@ -10,6 +10,7 @@ import (
"strings"
"github.com/aws/aws-sdk-go-v2/aws"
+ awshttp "github.com/aws/aws-sdk-go-v2/aws/transport/http"
awss3 "github.com/aws/aws-sdk-go-v2/service/s3"
s3types "github.com/aws/aws-sdk-go-v2/service/s3/types"
"github.com/aws/smithy-go"
@@ -26,6 +27,7 @@ import (
// PutBucketLifecycleConfiguration s3:PutLifecycleConfiguration
// ListObjectVersions s3:ListBucketVersions
// DeleteObjects with VersionId s3:DeleteObjectVersion (teardown only)
+// HeadObject naming a VersionId s3:GetObjectVersion (restore's lookup)
// CopyObject from a version s3:GetObjectVersion + s3:PutObject
//
// Add a call here and that table, and the module's, must move with it.
@@ -40,6 +42,7 @@ type s3VersionAPI interface {
ListObjectVersions(ctx context.Context, in *awss3.ListObjectVersionsInput, optFns ...func(*awss3.Options)) (*awss3.ListObjectVersionsOutput, error)
DeleteObjects(ctx context.Context, in *awss3.DeleteObjectsInput, optFns ...func(*awss3.Options)) (*awss3.DeleteObjectsOutput, error)
CopyObject(ctx context.Context, in *awss3.CopyObjectInput, optFns ...func(*awss3.Options)) (*awss3.CopyObjectOutput, error)
+ HeadObject(ctx context.Context, in *awss3.HeadObjectInput, optFns ...func(*awss3.Options)) (*awss3.HeadObjectOutput, error)
}
var _ Versioner = (*awsProvisioner)(nil)
@@ -167,13 +170,9 @@ func (p *awsProvisioner) EnsureVersioning(ctx context.Context, bucket string, wa
return fmt.Errorf("objstore: write lifecycle of %q: %w", bucket, err)
}
}
- status := s3types.BucketVersioningStatusSuspended
- if want.Enabled {
- status = s3types.BucketVersioningStatusEnabled
- }
if _, err := api.PutBucketVersioning(ctx, &awss3.PutBucketVersioningInput{
Bucket: aws.String(bucket),
- VersioningConfiguration: &s3types.VersioningConfiguration{Status: status},
+ VersioningConfiguration: &s3types.VersioningConfiguration{Status: s3types.BucketVersioningStatusEnabled},
}); err != nil {
return fmt.Errorf("objstore: set versioning of %q: %w", bucket, err)
}
@@ -197,54 +196,100 @@ func (p *awsProvisioner) ReadVersioning(ctx context.Context, bucket string) (Buc
return BucketVersioning{Status: string(out.Status), Rule: rule, KeepDays: days}, nil
}
-// ListVersions lists key's versions and delete markers, newest first. S3
-// lists by key and, within a key, newest first, but in two arrays, so the
-// two are merged by time; a page that has moved past key ends the walk.
-func (p *awsProvisioner) ListVersions(ctx context.Context, bucket, key string, max int) ([]ObjectVersion, error) {
+// ListVersions lists one page of key's versions and delete markers, newest
+// first. S3 lists by key and, within a key, newest first, with versions and
+// delete markers in two arrays of one ordered page, so the page is merged by
+// time. after resumes after that version of key (KeyMarker key,
+// VersionIdMarker after); next is set only while the listing is still on
+// key.
+func (p *awsProvisioner) ListVersions(ctx context.Context, bucket, key, after string, max int) ([]ObjectVersion, string, error) {
api, err := p.versionAPI()
if err != nil {
- return nil, err
+ return nil, "", err
}
if max <= 0 || max > MaxListedVersions {
max = MaxListedVersions
}
+ in := &awss3.ListObjectVersionsInput{Bucket: aws.String(bucket), Prefix: aws.String(key), MaxKeys: aws.Int32(int32(max))}
+ if after != "" {
+ in.KeyMarker, in.VersionIdMarker = aws.String(key), aws.String(after)
+ }
+ page, err := api.ListObjectVersions(ctx, in)
+ if err != nil {
+ return nil, "", fmt.Errorf("objstore: list versions of %q in %q: %w", key, bucket, err)
+ }
var out []ObjectVersion
- var keyMarker, versionMarker *string
- for {
- page, err := api.ListObjectVersions(ctx, &awss3.ListObjectVersionsInput{
- Bucket: aws.String(bucket),
- Prefix: aws.String(key),
- KeyMarker: keyMarker,
- VersionIdMarker: versionMarker,
- })
- if err != nil {
- return nil, fmt.Errorf("objstore: list versions of %q in %q: %w", key, bucket, err)
- }
- for _, v := range page.Versions {
- if aws.ToString(v.Key) == key {
- out = append(out, ObjectVersion{VersionID: aws.ToString(v.VersionId), Current: aws.ToBool(v.IsLatest),
- Size: aws.ToInt64(v.Size), Modified: aws.ToTime(v.LastModified)})
- }
- }
- for _, m := range page.DeleteMarkers {
- if aws.ToString(m.Key) == key {
- out = append(out, ObjectVersion{VersionID: aws.ToString(m.VersionId), Current: aws.ToBool(m.IsLatest),
- DeleteMarker: true, Modified: aws.ToTime(m.LastModified)})
- }
+ for _, v := range page.Versions {
+ if aws.ToString(v.Key) == key {
+ out = append(out, ObjectVersion{VersionID: aws.ToString(v.VersionId), Current: aws.ToBool(v.IsLatest),
+ Size: aws.ToInt64(v.Size), Modified: aws.ToTime(v.LastModified)})
}
- next := aws.ToString(page.NextKeyMarker)
- if !aws.ToBool(page.IsTruncated) || len(out) >= max || (next != "" && next != key) || page.NextKeyMarker == nil {
- break
+ }
+ for _, m := range page.DeleteMarkers {
+ if aws.ToString(m.Key) == key {
+ out = append(out, ObjectVersion{VersionID: aws.ToString(m.VersionId), Current: aws.ToBool(m.IsLatest),
+ DeleteMarker: true, Modified: aws.ToTime(m.LastModified)})
}
- keyMarker, versionMarker = page.NextKeyMarker, page.NextVersionIdMarker
}
sortVersions(out)
if len(out) > max {
out = out[:max]
}
+ next := ""
+ if aws.ToBool(page.IsTruncated) && aws.ToString(page.NextKeyMarker) == key && aws.ToString(page.NextVersionIdMarker) != "" {
+ next = aws.ToString(page.NextVersionIdMarker)
+ }
+ return out, next, nil
+}
+
+// StatVersion reports one version of key by its id (spec §6.4, Astra round
+// 1 P1): a HEAD naming the version, so a version is found however many newer
+// ones a writer has piled on top of it. A HEAD of a delete marker answers
+// 405; an id that is not one of key's answers 404 (or 400 for one S3 cannot
+// parse). Whether it is current comes from the first entry of a one-entry
+// version listing of key: S3 lists key itself before any longer key it
+// prefixes, newest first, and HeadObject without a version would need
+// s3:GetObject, which the console role does not hold.
+func (p *awsProvisioner) StatVersion(ctx context.Context, bucket, key, versionID string) (ObjectVersion, error) {
+ api, err := p.versionAPI()
+ if err != nil {
+ return ObjectVersion{}, err
+ }
+ out := ObjectVersion{VersionID: versionID}
+ head, err := api.HeadObject(ctx, &awss3.HeadObjectInput{Bucket: aws.String(bucket), Key: aws.String(key), VersionId: aws.String(versionID)})
+ switch status := httpStatus(err); {
+ case err == nil:
+ out.Size, out.Modified = aws.ToInt64(head.ContentLength), aws.ToTime(head.LastModified)
+ case status == 405:
+ out.DeleteMarker = true
+ case status == 400 || status == 404:
+ return ObjectVersion{}, ErrNoSuchVersion
+ default:
+ return ObjectVersion{}, fmt.Errorf("objstore: head %q version %q in %q: %w", key, versionID, bucket, err)
+ }
+ latest, err := api.ListObjectVersions(ctx, &awss3.ListObjectVersionsInput{Bucket: aws.String(bucket), Prefix: aws.String(key), MaxKeys: aws.Int32(1)})
+ if err != nil {
+ return ObjectVersion{}, fmt.Errorf("objstore: find the current version of %q in %q: %w", key, bucket, err)
+ }
+ for _, v := range latest.Versions {
+ out.Current = out.Current || aws.ToString(v.Key) == key && aws.ToBool(v.IsLatest) && aws.ToString(v.VersionId) == versionID
+ }
+ for _, m := range latest.DeleteMarkers {
+ out.Current = out.Current || aws.ToString(m.Key) == key && aws.ToBool(m.IsLatest) && aws.ToString(m.VersionId) == versionID
+ }
return out, nil
}
+// httpStatus is the HTTP status of an AWS response error, 0 for anything
+// else.
+func httpStatus(err error) int {
+ var re *awshttp.ResponseError
+ if errors.As(err, &re) {
+ return re.HTTPStatusCode()
+ }
+ return 0
+}
+
// sortVersions orders one key's versions newest first, the current one
// ahead of any other with the same time.
func sortVersions(vs []ObjectVersion) {
diff --git a/internal/objstore/aws_versioning_test.go b/internal/objstore/aws_versioning_test.go
index d439e1b7e..b95ba25ef 100644
--- a/internal/objstore/aws_versioning_test.go
+++ b/internal/objstore/aws_versioning_test.go
@@ -4,13 +4,16 @@ import (
"context"
"errors"
"fmt"
+ "net/http"
"strings"
"testing"
"time"
"github.com/aws/aws-sdk-go-v2/aws"
+ awshttp "github.com/aws/aws-sdk-go-v2/aws/transport/http"
awss3 "github.com/aws/aws-sdk-go-v2/service/s3"
s3types "github.com/aws/aws-sdk-go-v2/service/s3/types"
+ smithyhttp "github.com/aws/smithy-go/transport/http"
)
// stubS3V is the s3VersionAPI seam with per-method hooks; an unset hook fails
@@ -26,6 +29,7 @@ type stubS3V struct {
listVersions func(*awss3.ListObjectVersionsInput) (*awss3.ListObjectVersionsOutput, error)
deleteObjects func(*awss3.DeleteObjectsInput) (*awss3.DeleteObjectsOutput, error)
copyObject func(*awss3.CopyObjectInput) (*awss3.CopyObjectOutput, error)
+ headObject func(*awss3.HeadObjectInput) (*awss3.HeadObjectOutput, error)
}
func stubCall[I, O any](s *stubS3V, name string, hook func(I) (O, error), in I) (O, error) {
@@ -54,6 +58,9 @@ func (s *stubS3V) ListObjectVersions(_ context.Context, in *awss3.ListObjectVers
func (s *stubS3V) DeleteObjects(_ context.Context, in *awss3.DeleteObjectsInput, _ ...func(*awss3.Options)) (*awss3.DeleteObjectsOutput, error) {
return stubCall(s, "DeleteObjects", s.deleteObjects, in)
}
+func (s *stubS3V) HeadObject(_ context.Context, in *awss3.HeadObjectInput, _ ...func(*awss3.Options)) (*awss3.HeadObjectOutput, error) {
+ return stubCall(s, "HeadObject", s.headObject, in)
+}
func (s *stubS3V) CopyObject(_ context.Context, in *awss3.CopyObjectInput, _ ...func(*awss3.Options)) (*awss3.CopyObjectOutput, error) {
return stubCall(s, "CopyObject", s.copyObject, in)
}
@@ -88,7 +95,7 @@ func TestEnsureVersioningWritesTheRuleFirst(t *testing.T) {
},
}
p := &awsProvisioner{s3v: api}
- if err := p.EnsureVersioning(context.Background(), "b", VersioningWant{Enabled: true, KeepDays: 30}); err != nil {
+ if err := p.EnsureVersioning(context.Background(), "b", VersioningWant{KeepDays: 30}); err != nil {
t.Fatal(err)
}
if got := strings.Join(api.calls, ","); got != "GetBucketLifecycleConfiguration,PutBucketLifecycleConfiguration,PutBucketVersioning" {
@@ -133,7 +140,7 @@ func TestEnsureVersioningRefusesAForeignRule(t *testing.T) {
t.Run(name, func(t *testing.T) {
api := &stubS3V{t: t, getLifecycle: lifecycleOf(rules...)}
p := &awsProvisioner{s3v: api}
- if err := p.EnsureVersioning(context.Background(), "b", VersioningWant{Enabled: true, KeepDays: 30}); !errors.Is(err, ErrLifecycleInUse) {
+ if err := p.EnsureVersioning(context.Background(), "b", VersioningWant{KeepDays: 30}); !errors.Is(err, ErrLifecycleInUse) {
t.Fatalf("EnsureVersioning = %v, want ErrLifecycleInUse", err)
}
if len(api.calls) != 1 {
@@ -143,19 +150,17 @@ func TestEnsureVersioningRefusesAForeignRule(t *testing.T) {
}
}
-// The platform's own rule is left alone when right, rewritten when
-// keep_days moved; off suspends and keeps the rule.
+// The platform's own rule is left alone when right and rewritten when
+// keep_days moved; the bucket is always set Enabled, never Suspended.
func TestEnsureVersioningOwnRule(t *testing.T) {
for _, tc := range []struct {
- name string
- held int
- want VersioningWant
- calls string
- suspends bool
+ name string
+ held int
+ want VersioningWant
+ calls string
}{
- {"unchanged", 30, VersioningWant{Enabled: true, KeepDays: 30}, "GetBucketLifecycleConfiguration,PutBucketVersioning", false},
- {"raised", 30, VersioningWant{Enabled: true, KeepDays: 90}, "GetBucketLifecycleConfiguration,PutBucketLifecycleConfiguration,PutBucketVersioning", false},
- {"off", 30, VersioningWant{Enabled: false, KeepDays: 30}, "GetBucketLifecycleConfiguration,PutBucketVersioning", true},
+ {"unchanged", 30, VersioningWant{KeepDays: 30}, "GetBucketLifecycleConfiguration,PutBucketVersioning"},
+ {"raised", 30, VersioningWant{KeepDays: 90}, "GetBucketLifecycleConfiguration,PutBucketLifecycleConfiguration,PutBucketVersioning"},
} {
t.Run(tc.name, func(t *testing.T) {
var status s3types.BucketVersioningStatus
@@ -178,8 +183,8 @@ func TestEnsureVersioningOwnRule(t *testing.T) {
if got := strings.Join(api.calls, ","); got != tc.calls {
t.Fatalf("calls = %s, want %s", got, tc.calls)
}
- if want := map[bool]s3types.BucketVersioningStatus{true: "Suspended", false: "Enabled"}[tc.suspends]; status != want {
- t.Fatalf("status = %s, want %s", status, want)
+ if status != s3types.BucketVersioningStatusEnabled {
+ t.Fatalf("status = %s, want Enabled", status)
}
})
}
@@ -187,10 +192,10 @@ func TestEnsureVersioningOwnRule(t *testing.T) {
func TestEnsureVersioningRefusesBadKeepDaysAndNoClient(t *testing.T) {
p := &awsProvisioner{s3v: &stubS3V{t: t}}
- if err := p.EnsureVersioning(context.Background(), "b", VersioningWant{Enabled: true, KeepDays: 7}); err == nil {
+ if err := p.EnsureVersioning(context.Background(), "b", VersioningWant{KeepDays: 7}); err == nil {
t.Fatal("wrote a 7-day rule")
}
- if err := (&awsProvisioner{}).EnsureVersioning(context.Background(), "b", VersioningWant{Enabled: true, KeepDays: 30}); !errors.Is(err, ErrVersioningUnsupported) {
+ if err := (&awsProvisioner{}).EnsureVersioning(context.Background(), "b", VersioningWant{KeepDays: 30}); !errors.Is(err, ErrVersioningUnsupported) {
t.Fatalf("no client: %v", err)
}
}
@@ -206,34 +211,21 @@ func TestReadVersioning(t *testing.T) {
}
}
-// One key's versions only, newest first, delete markers included.
+// One page of one key's versions, newest first, delete markers included,
+// with the marker to resume from while the listing is still on the key.
func TestListVersionsOneKeyNewestFirst(t *testing.T) {
at := func(m int) *time.Time { v := time.Date(2026, 11, 22, 10, m, 0, 0, time.UTC); return &v }
- pages := []*awss3.ListObjectVersionsOutput{
- {IsTruncated: aws.Bool(true), NextKeyMarker: aws.String("k"), NextVersionIdMarker: aws.String("v2"),
+ var in *awss3.ListObjectVersionsInput
+ api := &stubS3V{t: t, listVersions: func(got *awss3.ListObjectVersionsInput) (*awss3.ListObjectVersionsOutput, error) {
+ in = got
+ return &awss3.ListObjectVersionsOutput{IsTruncated: aws.Bool(true), NextKeyMarker: aws.String("k"), NextVersionIdMarker: aws.String("v2"),
Versions: []s3types.ObjectVersion{
{Key: aws.String("k"), VersionId: aws.String("v3"), IsLatest: aws.Bool(false), Size: aws.Int64(3), LastModified: at(3)},
{Key: aws.String("k"), VersionId: aws.String("v2"), Size: aws.Int64(2), LastModified: at(2)},
},
- DeleteMarkers: []s3types.DeleteMarkerEntry{{Key: aws.String("k"), VersionId: aws.String("m4"), IsLatest: aws.Bool(true), LastModified: at(4)}}},
- {IsTruncated: aws.Bool(true), NextKeyMarker: aws.String("k2"), NextVersionIdMarker: aws.String("x"),
- Versions: []s3types.ObjectVersion{
- {Key: aws.String("k"), VersionId: aws.String("v1"), Size: aws.Int64(1), LastModified: at(1)},
- {Key: aws.String("k2"), VersionId: aws.String("x"), Size: aws.Int64(9), LastModified: at(9)},
- }},
- }
- var seen []string
- api := &stubS3V{t: t, listVersions: func(in *awss3.ListObjectVersionsInput) (*awss3.ListObjectVersionsOutput, error) {
- if aws.ToString(in.Prefix) != "k" {
- t.Fatalf("prefix = %q", aws.ToString(in.Prefix))
- }
- seen = append(seen, aws.ToString(in.KeyMarker)+"@"+aws.ToString(in.VersionIdMarker))
- if len(seen) > len(pages) {
- t.Fatal("listed past the key")
- }
- return pages[len(seen)-1], nil
+ DeleteMarkers: []s3types.DeleteMarkerEntry{{Key: aws.String("k"), VersionId: aws.String("m4"), IsLatest: aws.Bool(true), LastModified: at(4)}}}, nil
}}
- got, err := (&awsProvisioner{s3v: api}).ListVersions(context.Background(), "b", "k", 0)
+ got, next, err := (&awsProvisioner{s3v: api}).ListVersions(context.Background(), "b", "k", "", 3)
if err != nil {
t.Fatal(err)
}
@@ -241,11 +233,84 @@ func TestListVersionsOneKeyNewestFirst(t *testing.T) {
for _, v := range got {
ids = append(ids, fmt.Sprintf("%s:%v:%v", v.VersionID, v.Current, v.DeleteMarker))
}
- if strings.Join(ids, " ") != "m4:true:true v3:false:false v2:false:false v1:false:false" {
- t.Fatalf("versions = %v", ids)
+ if strings.Join(ids, " ") != "m4:true:true v3:false:false v2:false:false" || next != "v2" {
+ t.Fatalf("versions = %v, next %q", ids, next)
+ }
+ if aws.ToString(in.Prefix) != "k" || aws.ToInt32(in.MaxKeys) != 3 || in.KeyMarker != nil {
+ t.Fatalf("first page asked for %+v", in)
+ }
+
+ // Resuming names the key and the version to start after, and a page that
+ // has moved on to another key has no next.
+ api.listVersions = func(got *awss3.ListObjectVersionsInput) (*awss3.ListObjectVersionsOutput, error) {
+ in = got
+ return &awss3.ListObjectVersionsOutput{IsTruncated: aws.Bool(true), NextKeyMarker: aws.String("k2"), NextVersionIdMarker: aws.String("x"),
+ Versions: []s3types.ObjectVersion{
+ {Key: aws.String("k"), VersionId: aws.String("v1"), Size: aws.Int64(1), LastModified: at(1)},
+ {Key: aws.String("k2"), VersionId: aws.String("x"), Size: aws.Int64(9), LastModified: at(9)},
+ }}, nil
+ }
+ got, next, err = (&awsProvisioner{s3v: api}).ListVersions(context.Background(), "b", "k", "v2", 3)
+ if err != nil || len(got) != 1 || got[0].VersionID != "v1" || next != "" {
+ t.Fatalf("second page = %+v, next %q, %v", got, next, err)
+ }
+ if aws.ToString(in.KeyMarker) != "k" || aws.ToString(in.VersionIdMarker) != "v2" {
+ t.Fatalf("resume asked for %+v", in)
+ }
+}
+
+// StatVersion finds a version by id however deep it is: a HEAD naming it,
+// a delete marker's 405, an unknown id's 404 or 400, and current from the
+// newest entry of the key.
+func TestStatVersion(t *testing.T) {
+ at := time.Date(2026, 11, 22, 10, 0, 0, 0, time.UTC)
+ newest := func(id string, marker bool) func(*awss3.ListObjectVersionsInput) (*awss3.ListObjectVersionsOutput, error) {
+ return func(in *awss3.ListObjectVersionsInput) (*awss3.ListObjectVersionsOutput, error) {
+ if aws.ToInt32(in.MaxKeys) != 1 || aws.ToString(in.Prefix) != "k" {
+ t.Fatalf("current lookup asked for %+v", in)
+ }
+ if marker {
+ return &awss3.ListObjectVersionsOutput{DeleteMarkers: []s3types.DeleteMarkerEntry{{Key: aws.String("k"), VersionId: aws.String(id), IsLatest: aws.Bool(true)}}}, nil
+ }
+ return &awss3.ListObjectVersionsOutput{Versions: []s3types.ObjectVersion{{Key: aws.String("k"), VersionId: aws.String(id), IsLatest: aws.Bool(true)}}}, nil
+ }
+ }
+ respErr := func(status int) error {
+ return &awshttp.ResponseError{ResponseError: &smithyhttp.ResponseError{Response: &smithyhttp.Response{Response: &http.Response{StatusCode: status}}, Err: errors.New("x")}}
+ }
+ for _, tc := range []struct {
+ name string
+ head func(*awss3.HeadObjectInput) (*awss3.HeadObjectOutput, error)
+ current string
+ marker bool
+ want ObjectVersion
+ err error
+ }{
+ {"old version", func(in *awss3.HeadObjectInput) (*awss3.HeadObjectOutput, error) {
+ if aws.ToString(in.VersionId) != "v1" {
+ t.Fatalf("head asked for %q", aws.ToString(in.VersionId))
+ }
+ return &awss3.HeadObjectOutput{ContentLength: aws.Int64(7), LastModified: &at}, nil
+ }, "v9", false, ObjectVersion{VersionID: "v1", Size: 7, Modified: at}, nil},
+ {"current", func(*awss3.HeadObjectInput) (*awss3.HeadObjectOutput, error) {
+ return &awss3.HeadObjectOutput{ContentLength: aws.Int64(7), LastModified: &at}, nil
+ }, "v1", false, ObjectVersion{VersionID: "v1", Size: 7, Modified: at, Current: true}, nil},
+ {"delete marker", func(*awss3.HeadObjectInput) (*awss3.HeadObjectOutput, error) { return nil, respErr(405) },
+ "v1", true, ObjectVersion{VersionID: "v1", DeleteMarker: true, Current: true}, nil},
+ {"unknown", func(*awss3.HeadObjectInput) (*awss3.HeadObjectOutput, error) { return nil, respErr(404) }, "", false, ObjectVersion{}, ErrNoSuchVersion},
+ {"unparseable", func(*awss3.HeadObjectInput) (*awss3.HeadObjectOutput, error) { return nil, respErr(400) }, "", false, ObjectVersion{}, ErrNoSuchVersion},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ api := &stubS3V{t: t, headObject: tc.head, listVersions: newest(tc.current, tc.marker)}
+ got, err := (&awsProvisioner{s3v: api}).StatVersion(context.Background(), "b", "k", "v1")
+ if !errors.Is(err, tc.err) || got != tc.want {
+ t.Fatalf("StatVersion = %+v, %v; want %+v, %v", got, err, tc.want, tc.err)
+ }
+ })
}
- if strings.Join(seen, " ") != "@ k@v2" {
- t.Fatalf("pages asked for = %v", seen)
+ api := &stubS3V{t: t, headObject: func(*awss3.HeadObjectInput) (*awss3.HeadObjectOutput, error) { return nil, respErr(500) }}
+ if _, err := (&awsProvisioner{s3v: api}).StatVersion(context.Background(), "b", "k", "v1"); err == nil || errors.Is(err, ErrNoSuchVersion) {
+ t.Fatalf("a 500 = %v, want a plain error", err)
}
}
diff --git a/internal/objstore/memversioning.go b/internal/objstore/memversioning.go
index db817c78d..f7de41fa7 100644
--- a/internal/objstore/memversioning.go
+++ b/internal/objstore/memversioning.go
@@ -61,10 +61,42 @@ func (p *MemProvisioner) PutObject(bucket, key string, body []byte) {
}
p.Buckets[bucket][key] = append([]byte(nil), body...)
v := p.versioningLocked(bucket)
- if v.Status != "" {
- id, at := p.nextVersionLocked()
- v.History[key] = append(v.History[key], MemVersion{ID: id, Body: append([]byte(nil), body...), Modified: at})
+ p.writeVersionLocked(v, key, MemVersion{Body: append([]byte(nil), body...)})
+}
+
+// writeVersionLocked adds ver as key's newest version, as S3 does: with
+// versioning Enabled it gets a fresh id and every older version stays; in a
+// bucket never versioned, or Suspended, it is the "null" version and
+// REPLACES any null version the key already had (the S3 behaviour that
+// makes suspension unsafe, store versioning spec decision 3).
+func (p *MemProvisioner) writeVersionLocked(v *MemBucketVersioning, key string, ver MemVersion) {
+ id, at := p.nextVersionLocked()
+ ver.Modified = at
+ if v.Status == "Enabled" {
+ ver.ID = id
+ v.History[key] = append(v.History[key], ver)
+ return
+ }
+ ver.ID = "null"
+ h := v.History[key][:0]
+ for _, old := range v.History[key] {
+ if old.ID != "null" {
+ h = append(h, old)
+ }
}
+ if v.Status == "" && ver.DeleteMarker {
+ v.History[key] = h // an unversioned delete leaves nothing behind
+ return
+ }
+ v.History[key] = append(h, ver)
+}
+
+// SetStatus sets bucket's versioning status by hand ("", "Enabled",
+// "Suspended"), as an operator's console edit would.
+func (p *MemProvisioner) SetStatus(bucket, status string) {
+ p.mu.Lock()
+ defer p.mu.Unlock()
+ p.versioningLocked(bucket).Status = status
}
// DeleteObject is an app's DeleteObject with no version id: the object is
@@ -77,11 +109,7 @@ func (p *MemProvisioner) DeleteObject(bucket, key string) {
func (p *MemProvisioner) deleteObjectLocked(bucket, key string) {
delete(p.Buckets[bucket], key)
- v := p.versioningLocked(bucket)
- if v.Status != "" {
- id, at := p.nextVersionLocked()
- v.History[key] = append(v.History[key], MemVersion{ID: id, DeleteMarker: true, Modified: at})
- }
+ p.writeVersionLocked(p.versioningLocked(bucket), key, MemVersion{DeleteMarker: true})
}
// VersioningOf is a copy of bucket's versioning state.
@@ -122,11 +150,7 @@ func (p *MemProvisioner) EnsureVersioning(ctx context.Context, bucket string, wa
return ErrLifecycleInUse
}
v.KeepDays = want.KeepDays
- if want.Enabled {
- v.Status = "Enabled"
- } else {
- v.Status = "Suspended"
- }
+ v.Status = "Enabled"
return nil
}
@@ -147,22 +171,56 @@ func (p *MemProvisioner) ReadVersioning(ctx context.Context, bucket string) (Buc
return out, nil
}
-func (p *MemProvisioner) ListVersions(ctx context.Context, bucket, key string, max int) ([]ObjectVersion, error) {
+func (p *MemProvisioner) ListVersions(ctx context.Context, bucket, key, after string, max int) ([]ObjectVersion, string, error) {
p.mu.Lock()
defer p.mu.Unlock()
if err := p.takeFailure("ListVersions"); err != nil {
- return nil, err
+ return nil, "", err
}
if max <= 0 || max > MaxListedVersions {
max = MaxListedVersions
}
h := p.versioningLocked(bucket).History[key]
+ start := len(h) - 1
+ if after != "" {
+ start = -1
+ for i := range h {
+ if h[i].ID == after {
+ start = i - 1
+ }
+ }
+ }
var out []ObjectVersion
- for i := len(h) - 1; i >= 0 && len(out) < max; i-- {
- out = append(out, ObjectVersion{VersionID: h[i].ID, Current: i == len(h)-1,
- DeleteMarker: h[i].DeleteMarker, Size: int64(len(h[i].Body)), Modified: h[i].Modified})
+ i := start
+ for ; i >= 0 && len(out) < max; i-- {
+ out = append(out, memObjectVersion(h, i))
}
- return out, nil
+ next := ""
+ if i >= 0 && len(out) > 0 {
+ next = out[len(out)-1].VersionID
+ }
+ return out, next, nil
+}
+
+// memObjectVersion is h[i] as ObjectVersion; the last entry is current.
+func memObjectVersion(h []MemVersion, i int) ObjectVersion {
+ return ObjectVersion{VersionID: h[i].ID, Current: i == len(h)-1,
+ DeleteMarker: h[i].DeleteMarker, Size: int64(len(h[i].Body)), Modified: h[i].Modified}
+}
+
+func (p *MemProvisioner) StatVersion(ctx context.Context, bucket, key, versionID string) (ObjectVersion, error) {
+ p.mu.Lock()
+ defer p.mu.Unlock()
+ if err := p.takeFailure("StatVersion"); err != nil {
+ return ObjectVersion{}, err
+ }
+ h := p.versioningLocked(bucket).History[key]
+ for i := range h {
+ if h[i].ID == versionID {
+ return memObjectVersion(h, i), nil
+ }
+ }
+ return ObjectVersion{}, ErrNoSuchVersion
}
func (p *MemProvisioner) RestoreVersion(ctx context.Context, bucket, key, versionID string) (string, error) {
@@ -179,8 +237,9 @@ func (p *MemProvisioner) RestoreVersion(ctx context.Context, bucket, key, versio
if ver.DeleteMarker {
return "", fmt.Errorf("objstore: mem: %s is a delete marker", versionID)
}
- id, at := p.nextVersionLocked()
- v.History[key] = append(v.History[key], MemVersion{ID: id, Body: append([]byte(nil), ver.Body...), Modified: at})
+ body := append([]byte(nil), ver.Body...)
+ p.writeVersionLocked(v, key, MemVersion{Body: body})
+ id := v.History[key][len(v.History[key])-1].ID
if p.Buckets[bucket] == nil {
p.Buckets[bucket] = map[string][]byte{}
}
diff --git a/internal/objstore/objstore.go b/internal/objstore/objstore.go
index 5186ad376..723f11247 100644
--- a/internal/objstore/objstore.go
+++ b/internal/objstore/objstore.go
@@ -177,17 +177,19 @@ type Record struct {
// Versioning is what the store's bucket should be: versioned, with
// noncurrent versions kept for KeepDays (store versioning spec,
// 2026-11-22, §5). Absent means nobody ever asked for it. Once written
- // it is never removed: "off" is Enabled false, because the bucket may
- // still hold versions that teardown and the sizing sweep must see.
+ // it is never removed, and Enabled is always true: versioning cannot be
+ // turned off (ErrVersioningPermanent), because a suspended bucket lets
+ // the app's own writes replace null versions.
// Additive, like Scanning and Conversion: release.PurgeApp's local
// struct ignores it (TestPurgeGuardIgnoresVersioningBlock).
Versioning *Versioning `json:"versioning,omitempty"`
}
// Versioning is the record's versioning block (store versioning spec §5.1).
-// Enabled false is a suspended bucket whose old versions still expire on the
-// platform's rule. KeepDays is how long a version is kept after it stops
-// being current, from MinKeepDays to MaxKeepDays.
+// Enabled is always true in a record any door writes; the walks refuse a
+// block that says false rather than suspend the bucket. KeepDays is how long
+// a version is kept after it stops being current, from MinKeepDays to
+// MaxKeepDays.
type Versioning struct {
Enabled bool `json:"enabled"`
KeepDays int `json:"keep_days"`
diff --git a/internal/objstore/versioning.go b/internal/objstore/versioning.go
index 408eef895..2bbe9dbd2 100644
--- a/internal/objstore/versioning.go
+++ b/internal/objstore/versioning.go
@@ -48,12 +48,24 @@ var ErrLifecycleInUse = errors.New("objstore: the bucket has a lifecycle rule th
// ValidKeepDays is a retention the walk will write.
func ValidKeepDays(n int) bool { return n >= MinKeepDays && n <= MaxKeepDays }
-// VersioningWant is what EnsureVersioning converges a bucket to.
+// VersioningWant is what EnsureVersioning converges a bucket to: versioning
+// Enabled, with the platform's rule for KeepDays. There is no suspended
+// state to ask for (store versioning spec decision 3, Astra round 1 P1): in
+// a suspended bucket an ordinary PutObject or DeleteObject replaces the
+// key's null version, so the app's own credential could destroy history
+// written before versioning was first turned on. Once on, a store stays
+// versioned until it is destroyed.
type VersioningWant struct {
- Enabled bool
KeepDays int
}
+// ErrVersioningPermanent is a request, or a hand-edited record, asking for
+// versioning to be switched off. Nothing is written.
+var ErrVersioningPermanent = errors.New("objstore: store versioning cannot be turned off once it is on")
+
+// ErrNoSuchVersion is a version id that is not one of the key's versions.
+var ErrNoSuchVersion = errors.New("objstore: no such version")
+
// The lifecycle states ReadVersioning reports (BucketVersioning.Rule).
const (
// RuleNone: the bucket has no lifecycle configuration.
@@ -75,14 +87,7 @@ type BucketVersioning struct {
// Matches reports whether the bucket is exactly what v asks for.
func (b BucketVersioning) Matches(v *Versioning) bool {
- if v == nil {
- return false
- }
- status := "Suspended"
- if v.Enabled {
- status = "Enabled"
- }
- return b.Status == status && b.Rule == RuleOurs && b.KeepDays == v.KeepDays
+ return v != nil && v.Enabled && b.Status == "Enabled" && b.Rule == RuleOurs && b.KeepDays == v.KeepDays
}
// ObjectVersion is one version of one key, as ListVersions answers it.
@@ -105,14 +110,20 @@ type Versioner interface {
// EnsureVersioning writes the platform's lifecycle rule for
// want.KeepDays (refusing, with ErrLifecycleInUse and nothing written,
// a configuration holding anything else) and THEN sets versioning
- // Enabled, or Suspended when want.Enabled is false. Rule first: a
- // versioned bucket with no rule keeps every version forever.
+ // Enabled. Rule first: a versioned bucket with no rule keeps every
+ // version forever.
EnsureVersioning(ctx context.Context, bucket string, want VersioningWant) error
// ReadVersioning reports the bucket's versioning status and rule.
ReadVersioning(ctx context.Context, bucket string) (BucketVersioning, error)
- // ListVersions lists key's versions and delete markers, newest first,
- // at most max of them. Only entries whose key is exactly key.
- ListVersions(ctx context.Context, bucket, key string, max int) ([]ObjectVersion, error)
+ // ListVersions lists one page of key's versions and delete markers,
+ // newest first, at most max of them, starting after version id after
+ // ("" from the newest). next is the after for the following page, ""
+ // when there is none. Only entries whose key is exactly key.
+ ListVersions(ctx context.Context, bucket, key, after string, max int) (versions []ObjectVersion, next string, err error)
+ // StatVersion reports one version of key, found by its id however many
+ // newer versions there are: its size, whether it is a delete marker and
+ // whether it is current. ErrNoSuchVersion when it is not one of key's.
+ StatVersion(ctx context.Context, bucket, key, versionID string) (ObjectVersion, error)
// RestoreVersion copies versionID of key onto key, making a new
// current version, and answers its version id. It never deletes.
RestoreVersion(ctx context.Context, bucket, key, versionID string) (string, error)
@@ -137,10 +148,13 @@ func convergeVersioning(ctx context.Context, p Provisioner, bucket string, v *Ve
if err != nil {
return err
}
+ if !v.Enabled {
+ return ErrVersioningPermanent
+ }
if !ValidKeepDays(v.KeepDays) {
return fmt.Errorf("objstore: versioning keep_days %d is outside %d-%d", v.KeepDays, MinKeepDays, MaxKeepDays)
}
- if err := vr.EnsureVersioning(ctx, bucket, VersioningWant{Enabled: v.Enabled, KeepDays: v.KeepDays}); err != nil {
+ if err := vr.EnsureVersioning(ctx, bucket, VersioningWant{KeepDays: v.KeepDays}); err != nil {
return fmt.Errorf("objstore: version bucket %s: %w", bucket, err)
}
return nil
diff --git a/internal/objstore/versioning_test.go b/internal/objstore/versioning_test.go
index b98a62972..57e304932 100644
--- a/internal/objstore/versioning_test.go
+++ b/internal/objstore/versioning_test.go
@@ -213,7 +213,7 @@ func TestGrantRefusesForeignLifecycleRule(t *testing.T) {
}
// ConvergeVersioningIn changes the bucket and nothing else: no key, no
-// delivered config, no record write. Off suspends and keeps the rule.
+// delivered config, no record write. It never suspends a bucket.
func TestConvergeVersioningInTouchesOnlyTheBucket(t *testing.T) {
ctx := context.Background()
s := release.NewDirStore(t.TempDir())
@@ -239,12 +239,73 @@ func TestConvergeVersioningInTouchesOnlyTheBucket(t *testing.T) {
t.Fatalf("keys = %v, want the one the grant minted", keys)
}
+ // A block that says off (hand-edited: no door writes one) is refused,
+ // and the bucket stays versioned.
setVersioning(t, s, testVersioning(false, 30))
- if _, err := ConvergeVersioningIn(ctx, s, p, "bab", "titogo", ""); err != nil {
+ if _, err := ConvergeVersioningIn(ctx, s, p, "bab", "titogo", ""); !errors.Is(err, ErrVersioningPermanent) {
+ t.Fatalf("converging an off block = %v, want ErrVersioningPermanent", err)
+ }
+ if v := p.VersioningOf(bucket); v.Status != "Enabled" {
+ t.Fatalf("off: bucket %+v, want it still Enabled", v)
+ }
+}
+
+// Why versioning cannot be turned off (Astra round 1 P1): an object written
+// before versioning is its null version; with versioning Enabled an
+// overwrite keeps it, but in a Suspended bucket the app's own next write
+// replaces it for good. The fake behaves as S3 does, so the cut is pinned.
+func TestMemSuspendedWriteReplacesTheNullVersion(t *testing.T) {
+ ctx := context.Background()
+ p := NewMemProvisioner("eu-west-1")
+ if _, err := p.EnsureBucket(ctx, "b"); err != nil {
+ t.Fatal(err)
+ }
+ p.PutObject("b", "k", []byte("written before versioning"))
+ if err := p.EnsureVersioning(ctx, "b", VersioningWant{KeepDays: 30}); err != nil {
t.Fatal(err)
}
- if v := p.VersioningOf(bucket); v.Status != "Suspended" || v.KeepDays != 30 {
- t.Fatalf("off: bucket %+v, want Suspended with the rule kept", v)
+ p.PutObject("b", "k", []byte("overwrite"))
+ if h := p.VersioningOf("b").History["k"]; len(h) != 2 || h[0].ID != "null" {
+ t.Fatalf("enabled overwrite: history %+v, want the null version kept", h)
+ }
+ p.SetStatus("b", "Suspended")
+ p.PutObject("b", "k", []byte("garbage"))
+ for _, v := range p.VersioningOf("b").History["k"] {
+ if string(v.Body) == "written before versioning" {
+ t.Fatal("the fake kept a null version S3 would have replaced")
+ }
+ }
+}
+
+// StatVersion finds any version by id, past the listing's page size, and the
+// listing pages with after/next.
+func TestMemStatVersionAndPaging(t *testing.T) {
+ ctx := context.Background()
+ p := NewMemProvisioner("eu-west-1")
+ if _, err := p.EnsureBucket(ctx, "b"); err != nil {
+ t.Fatal(err)
+ }
+ if err := p.EnsureVersioning(ctx, "b", VersioningWant{KeepDays: 30}); err != nil {
+ t.Fatal(err)
+ }
+ for i := 0; i < MaxListedVersions+5; i++ {
+ p.PutObject("b", "k", []byte{byte(i)})
+ }
+ first := p.VersioningOf("b").History["k"][0]
+ got, err := p.StatVersion(ctx, "b", "k", first.ID)
+ if err != nil || got.Current || got.VersionID != first.ID {
+ t.Fatalf("StatVersion of the oldest = %+v, %v", got, err)
+ }
+ if _, err := p.StatVersion(ctx, "b", "k", "nope"); !errors.Is(err, ErrNoSuchVersion) {
+ t.Fatalf("unknown = %v", err)
+ }
+ page, next, _ := p.ListVersions(ctx, "b", "k", "", 0)
+ if len(page) != MaxListedVersions || next == "" {
+ t.Fatalf("first page: %d versions, next %q", len(page), next)
+ }
+ rest, next, _ := p.ListVersions(ctx, "b", "k", next, 0)
+ if len(rest) != 5 || next != "" || rest[4].VersionID != first.ID {
+ t.Fatalf("second page: %+v, next %q", rest, next)
}
}
@@ -311,7 +372,7 @@ func TestMemDeleteBucketRefusesVersions(t *testing.T) {
if _, err := p.EnsureBucket(ctx, "b"); err != nil {
t.Fatal(err)
}
- if err := p.EnsureVersioning(ctx, "b", VersioningWant{Enabled: true, KeepDays: 30}); err != nil {
+ if err := p.EnsureVersioning(ctx, "b", VersioningWant{KeepDays: 30}); err != nil {
t.Fatal(err)
}
p.PutObject("b", "k", []byte("x"))
@@ -352,12 +413,12 @@ func TestMemRestoreKeepsEveryVersion(t *testing.T) {
if _, err := p.EnsureBucket(ctx, "b"); err != nil {
t.Fatal(err)
}
- if err := p.EnsureVersioning(ctx, "b", VersioningWant{Enabled: true, KeepDays: 30}); err != nil {
+ if err := p.EnsureVersioning(ctx, "b", VersioningWant{KeepDays: 30}); err != nil {
t.Fatal(err)
}
p.PutObject("b", "k", []byte("good"))
p.PutObject("b", "k", []byte("garbage"))
- vs, err := p.ListVersions(ctx, "b", "k", 0)
+ vs, _, err := p.ListVersions(ctx, "b", "k", "", 0)
if err != nil || len(vs) != 2 || !vs[0].Current || vs[1].Current {
t.Fatalf("versions: %+v, %v", vs, err)
}
@@ -367,7 +428,7 @@ func TestMemRestoreKeepsEveryVersion(t *testing.T) {
if got := string(p.Buckets["b"]["k"]); got != "good" {
t.Fatalf("current after restore = %q", got)
}
- if after, _ := p.ListVersions(ctx, "b", "k", 0); len(after) != 3 {
+ if after, _, _ := p.ListVersions(ctx, "b", "k", "", 0); len(after) != 3 {
t.Fatalf("restore changed the history: %+v", after)
}
got, _ := p.ReadVersioning(ctx, "b")
diff --git a/internal/provision/store_versioning_census_test.go b/internal/provision/store_versioning_census_test.go
index bff3974ba..f3aa4ad49 100644
--- a/internal/provision/store_versioning_census_test.go
+++ b/internal/provision/store_versioning_census_test.go
@@ -9,7 +9,9 @@ package provision
//
// - var routeDecls (internal/console/routedecls.go): four declarations
// added, POST and GET .../store/versioning, GET .../store/versions and
-// POST .../store/restore, beside the store uploads doors. Their handlers
+// POST .../store/restore, beside the store uploads doors (re-pinned
+// after Astra round 1 for the comment above them: there is no off).
+// Their handlers
// write the store record (objstore.PutIn) and the store's bucket; none
// writes an instance or sidecar record.
// - var linkedPolicies (internal/console/linkedpolicy.go): the same four
@@ -17,7 +19,7 @@ package provision
func storeVersioningWriteCensusInventory() []censusEntry {
entries := append([]censusEntry(nil), fleetRestartWakeWriteCensusInventory()...)
for _, r := range []censusEntry{
- {"internal/console/routedecls.go", "var routeDecls", "key-site", "lit:instances,lit:sidecars", "2d56c48c60a4841b642680ea0abb9db1f3c3a417901d051d960328978b9997e1"},
+ {"internal/console/routedecls.go", "var routeDecls", "key-site", "lit:instances,lit:sidecars", "7cddf4239f5ab4fffc0ba5602973501b3c9e830a20ab94f675b9a194d8f244bd"},
{"internal/console/linkedpolicy.go", "var linkedPolicies", "key-site", "lit:instances,lit:sidecars", "864a5e5962ec7b3555338b5ebd4eeeafcc53e702357d7f6bac3a432c2e904daa"},
} {
replaced := false
diff --git a/parity/cli.tsv b/parity/cli.tsv
index 284a78797..407d7cd2d 100644
--- a/parity/cli.tsv
+++ b/parity/cli.tsv
@@ -268,7 +268,6 @@ store status customer - - - - -
store uploads disable customer - - - - -
store uploads enable customer - - - - -
store uploads status customer - - - - -
-store versioning off customer - - - - -
store versioning on customer - - - - -
store versioning status customer - - - - -
store versions customer - - - - -
diff --git a/parity/parity.tsv b/parity/parity.tsv
index 86e339e60..5db5713cf 100644
--- a/parity/parity.tsv
+++ b/parity/parity.tsv
@@ -132,7 +132,7 @@ store-apply storage both store apply GET /a/{sqid}/settings ; POST /a/{sqid}/sto
store-rotate storage gap store rotate wp-email-storage
store-scan storage gap store scan request ; store scan status ; store scan grant ; store scan revoke ; store scan sweep ; store scan enforce ; store scan rotate-webhook-key wp-email-storage
store-uploads storage gap store uploads enable ; store uploads status ; store uploads disable wp-email-storage
-store-versioning storage gap store versioning on ; store versioning off ; store versioning status ; store versions ; store restore wp-email-storage The console has no versioning page yet; store status shows whether it is on.
+store-versioning storage gap store versioning on ; store versioning status ; store versions ; store restore wp-email-storage The console has no versioning page yet; store status shows whether it is on.
media-convert apps cli-only media convert ; media status Apps call the conversion door; the CLI is how a person tries it.
store-destroy storage console-only POST /a/{sqid}/apps/{app}/store/destroy Needs a passkey.
diff --git a/store.go b/store.go
index 99fdde9d1..ac4bd9391 100644
--- a/store.go
+++ b/store.go
@@ -191,12 +191,9 @@ func runStoreCreate(args []string) {
printUsing(stdout, sess)
acct := resolvedAccount(sess, acctRaw, acctIDRaw)
name = resolvedApp(sess, acct, name, usage)
- versionKeep := -1 // not versioned
- if *versioning || *keepDays != 0 {
- versionKeep = *keepDays // --keep-days alone implies --versioning
- }
if err := storeCreateAndProvisionVersioned(context.Background(), sess, acct, name,
- strings.TrimSpace(*environment), strings.TrimSpace(*envPrefix), versionKeep, stdout); err != nil {
+ strings.TrimSpace(*environment), strings.TrimSpace(*envPrefix),
+ *versioning || flagWasSet(fs, "keep-days"), *keepDays, stdout); err != nil {
log.Fatalf("store create: %v", err)
}
}
@@ -236,16 +233,23 @@ func storeEnvMismatch(res apiStoreReply, env string) error {
}
func storeCreateAndProvision(ctx context.Context, sess *apiSession, acct apiAcct, app, env, envPrefix string, out io.Writer) error {
- return storeCreateAndProvisionVersioned(ctx, sess, acct, app, env, envPrefix, -1, out)
+ return storeCreateAndProvisionVersioned(ctx, sess, acct, app, env, envPrefix, false, 0, out)
}
// storeCreateAndProvisionVersioned is storeCreateAndProvision for a store
-// that may be born versioned: keepDays -1 is not versioned, 0 the default
-// retention, anything else that many days (store versioning spec §6.1).
-func storeCreateAndProvisionVersioned(ctx context.Context, sess *apiSession, acct apiAcct, app, env, envPrefix string, keepDays int, out io.Writer) error {
+// that may be born versioned (store versioning spec §6.1). With versioned,
+// keepDays 0 is the default retention and anything else must be 30 to 365,
+// checked here before any request (Astra round 1 P2: a bad value must never
+// fall back to an unversioned create). The console's answer must then carry
+// an enabled versioning block, or nothing is provisioned (round 1 P1): an
+// older console ignores the field and would make an unversioned store.
+func storeCreateAndProvisionVersioned(ctx context.Context, sess *apiSession, acct apiAcct, app, env, envPrefix string, versioned bool, keepDays int, out io.Writer) error {
+ if versioned && keepDays != 0 && !objstore.ValidKeepDays(keepDays) {
+ return errors.New(storeVersioningText("cli.versioning.bad_keep_days"))
+ }
var res apiStoreReply
var err error
- if keepDays >= 0 {
+ if versioned {
res, err = sess.storeCreateVersioned(ctx, acct, app, env, envPrefix, keepDays)
} else {
res, err = sess.storeCreate(ctx, acct, app, env, envPrefix)
@@ -258,6 +262,9 @@ func storeCreateAndProvisionVersioned(ctx context.Context, sess *apiSession, acc
if err := storeEnvMismatch(res, env); err != nil {
return err
}
+ if versioned && (res.Versioning == nil || !res.Versioning.Enabled) {
+ return errors.New(storeVersioningText("cli.versioning.old_console"))
+ }
printStoreCreate(out, res)
if res.Backend == "" || !res.mayProvision() {
return nil
diff --git a/store_versioning.go b/store_versioning.go
index 2bcb4cbd5..78e786163 100644
--- a/store_versioning.go
+++ b/store_versioning.go
@@ -24,46 +24,51 @@ import (
"time"
"github.com/carlosframework/platform/internal/clireg"
+ "github.com/carlosframework/platform/internal/objstore"
)
// storeVersioningCopy is this file's text by copy deck key. DRAFT, awaiting
// copy review: apply the review's edits here and in the deck together.
var storeVersioningCopy = map[string]string{
- "cli.versioning.usage": "usage: carlos store versioning <on|off|status> --app <a> [--environment <e>] [--keep-days <n>]",
- "cli.versioning.store_usage": " versioning <on|off|status> --app <a> [--environment <e>] [--keep-days <n>]\n" +
- " keep old versions of the store's objects, so a\n" +
- " delete or an overwrite can be undone. Old versions\n" +
- " are kept 30 days unless --keep-days says longer.\n" +
- " versions --app <a> --key <key> [--environment <e>]\n" +
+ "cli.versioning.usage": "usage: carlos store versioning <on|status> --app <a> [--environment <e>] [--keep-days <n>]",
+ "cli.versioning.store_usage": " versioning <on|status> --app <a> [--environment <e>] [--keep-days <n>]\n" +
+ " keep old versions so you can undo deletes and\n" +
+ " overwrites. Keep them for 30 days unless\n" +
+ " --keep-days sets a longer period. Once on, it\n" +
+ " stays on.\n" +
+ " versions --app <a> --key <key> [--after <id>] [--environment <e>]\n" +
" list one object's versions, newest first.\n" +
" restore --app <a> --key <key> --version <id> [--environment <e>]\n" +
" make an old version current again. Nothing is deleted.",
- "docs.cli.store_versioning": "Keeps old versions of the store's objects, so a delete or an overwrite can be undone. Old versions are kept 30 days unless --keep-days says longer.",
- "cli.versioning.flag_app": "app whose store to version",
- "cli.versioning.flag_env": "the config environment whose store to act on (default: the app's own)",
- "cli.versioning.flag_keep": "days to keep old versions, from 30 to 365 (default 30, or the store's current setting); can't be lowered",
- "cli.versioning.flag_key": "the object's key",
+ "docs.cli.store_versioning": "Keep old versions so you can undo deletes and overwrites. Keep them for 30 days unless --keep-days sets a longer period. Once on, it stays on.",
+ "cli.versioning.flag_app": "app whose store to use",
+ "cli.versioning.flag_env": "config environment whose store to use (default: the app's own)",
+ "cli.versioning.flag_keep": "days to keep old versions, from 30 to 365 (default: the store's current setting, or 30 if unset); can't be lowered",
+ "cli.versioning.flag_key": "the object's key (name)",
"cli.versioning.flag_version": "the version to make current again (from carlos store versions)",
+ "cli.versioning.flag_after": "list the versions older than this one (from the more line of the last page)",
"cli.versioning.flag_create": "keep old versions of this store's objects from the start (see carlos store versioning)",
"cli.versioning.flag_create_kd": "days to keep old versions, from 30 to 365 (default 30); implies --versioning",
+ "cli.versioning.bad_keep_days": "--keep-days must be from 30 to 365",
+ "cli.versioning.old_console": "this console is older than store versioning, so the store was declared without it and nothing was provisioned. Ask your operator to upgrade the console, then run carlos store versioning on",
+ "cli.instances.old_console": "this console is older than store versioning, so it did not turn on --store-versioning. Ask your operator to upgrade the console, then run this again",
"cli.versioning.on": "versioning on",
"cli.versioning.off": "versioning off",
"cli.versioning.never": "versioning never turned on",
"cli.versioning.keep": "keep old versions for %d days",
- "cli.versioning.off_note": "note versions from before still expire after %d days",
"cli.versioning.bucket_ok": "bucket in place",
"cli.versioning.bucket_pending": "bucket set when the store is provisioned",
"cli.versioning.bucket_stale": "bucket not set yet. Run the same command again",
"cli.versioning.bucket_foreign": "bucket changed: it has a lifecycle rule this platform didn't write",
"cli.versioning.status_line_on": " versioning: on, old versions kept %d days",
- "cli.versioning.status_line_of": " versioning: off; versions from before expire after %d days",
"cli.versions.none": "no versions of %s",
"cli.versions.header": "VERSION\tMODIFIED\tSIZE\tSTATE",
"cli.versions.current": "current",
"cli.versions.old": "old",
"cli.versions.deleted": "deleted",
+ "cli.versions.more": "more: carlos store versions --key %s --after %s",
"cli.restore.done": "restored %s\nfrom %s\nnew %s",
- "cli.versioning.unreadable": "store versioning: unreadable response: %w",
+ "cli.versioning.unreadable": "store versioning: can't read the response: %w",
"cli.versioning.need_key": "--key is required",
"cli.versioning.need_version": "--version is required",
}
@@ -91,6 +96,7 @@ type apiVersionsReply struct {
Environment string `json:"environment"`
Key string `json:"key"`
Versions []apiObjectVersion `json:"versions"`
+ Next string `json:"next"`
}
type apiRestoreReply struct {
@@ -153,8 +159,11 @@ func (s *apiSession) storeVersioningStatus(ctx context.Context, a apiAcct, app,
return out, err
}
-func (s *apiSession) storeVersions(ctx context.Context, a apiAcct, app, env, key string) (apiVersionsReply, error) {
+func (s *apiSession) storeVersions(ctx context.Context, a apiAcct, app, env, key, after string) (apiVersionsReply, error) {
q := url.Values{"key": {key}}
+ if after != "" {
+ q.Set("after", after)
+ }
if env != "" {
q.Set("environment", env)
}
@@ -187,8 +196,10 @@ func (s *apiSession) storeCreateVersioned(ctx context.Context, a apiAcct, app, e
return out, err
}
-// storeVersioningCommand is `carlos store versioning`: three raw leaves
-// sharing runStoreVersioning. Bare or any other word is its usage, exit 1.
+// storeVersioningCommand is `carlos store versioning`: two raw leaves
+// sharing runStoreVersioning. There is no off (store versioning spec
+// decision 3): once on, a store stays versioned. Bare or any other word is
+// its usage, exit 1.
func storeVersioningCommand() *clireg.Node {
const cust = clireg.Customer
leaf := func(verb string) *clireg.Node {
@@ -197,7 +208,7 @@ func storeVersioningCommand() *clireg.Node {
return &clireg.Node{
Name: "versioning",
Audience: cust,
- Children: []*clireg.Node{leaf("on"), leaf("off"), leaf("status")},
+ Children: []*clireg.Node{leaf("on"), leaf("status")},
OnError: failedAsIs,
FallbackErr: func(args, consumed []string) error {
fmt.Fprintln(os.Stderr, storeVersioningText("cli.versioning.usage"))
@@ -268,9 +279,10 @@ func runStoreVersioningWith(ctx context.Context, t storeVersionTarget, verb stri
var err error
switch verb {
case "on":
+ if keepDays != 0 && !objstore.ValidKeepDays(keepDays) {
+ return errors.New(storeVersioningText("cli.versioning.bad_keep_days"))
+ }
res, err = t.sess.storeVersioningSet(ctx, t.acct, t.app, t.env, true, keepDays)
- case "off":
- res, err = t.sess.storeVersioningSet(ctx, t.acct, t.app, t.env, false, 0)
case "status":
res, err = t.sess.storeVersioningStatus(ctx, t.acct, t.app, t.env)
default:
@@ -293,8 +305,8 @@ func printStoreVersioning(w io.Writer, res apiVersioningReply) {
fmt.Fprintln(w, storeVersioningText("cli.versioning.on"))
fmt.Fprintf(w, storeVersioningText("cli.versioning.keep")+"\n", res.KeepDays)
case "off":
+ // Only a hand-edited record says off; no door writes one.
fmt.Fprintln(w, storeVersioningText("cli.versioning.off"))
- fmt.Fprintf(w, storeVersioningText("cli.versioning.off_note")+"\n", res.KeepDays)
default:
fmt.Fprintln(w, storeVersioningText("cli.versioning.never"))
return
@@ -314,19 +326,16 @@ func printStoreVersioning(w io.Writer, res apiVersioningReply) {
// printStoreVersioningLine is `carlos store status`'s one line, from the
// record alone. A store never versioned prints nothing.
func printStoreVersioningLine(w io.Writer, v *apiStoreVersioningBlock) {
- switch {
- case v == nil:
- case v.Enabled:
+ if v != nil && v.Enabled {
fmt.Fprintf(w, storeVersioningText("cli.versioning.status_line_on")+"\n", v.KeepDays)
- default:
- fmt.Fprintf(w, storeVersioningText("cli.versioning.status_line_of")+"\n", v.KeepDays)
}
}
func runStoreVersions(args []string) error {
- var key *string
+ var key, after *string
t, err := parseStoreVersionFlags("versions", args, func(fs *flag.FlagSet) {
key = fs.String("key", "", storeVersioningText("cli.versioning.flag_key"))
+ after = fs.String("after", "", storeVersioningText("cli.versioning.flag_after"))
})
if err != nil {
return fmt.Errorf("store versions: %w", err)
@@ -334,7 +343,7 @@ func runStoreVersions(args []string) error {
if *key == "" {
return errors.New("store versions: " + storeVersioningText("cli.versioning.need_key"))
}
- res, err := t.sess.storeVersions(context.Background(), t.acct, t.app, t.env, *key)
+ res, err := t.sess.storeVersions(context.Background(), t.acct, t.app, t.env, *key, strings.TrimSpace(*after))
if err != nil {
return fmt.Errorf("store versions: %w", err)
}
@@ -363,6 +372,19 @@ func printStoreVersions(w io.Writer, res apiVersionsReply) {
fmt.Fprintf(tw, "%s\t%s\t%s\t%s\n", v.VersionID, v.Modified.UTC().Format("2006-01-02 15:04 UTC"), size, state)
}
tw.Flush()
+ if res.Next != "" {
+ fmt.Fprintf(w, storeVersioningText("cli.versions.more")+"\n", res.Key, res.Next)
+ }
+}
+
+// storeVersioningEchoed checks that an instances enable asking for
+// --store-versioning was answered by a console that set it (Astra round 1
+// P1): an older console ignores the field and answers success.
+func storeVersioningEchoed(asked *bool, m apiInstanceManifest) error {
+ if asked != nil && *asked && !m.StoreVersioning {
+ return errors.New(storeVersioningText("cli.instances.old_console"))
+ }
+ return nil
}
func runStoreRestore(args []string) error {
diff --git a/store_versioning_test.go b/store_versioning_test.go
index c77f32d25..125b9d33d 100644
--- a/store_versioning_test.go
+++ b/store_versioning_test.go
@@ -44,21 +44,21 @@ func TestStoreVersioningWireShapes(t *testing.T) {
if c.method != http.MethodPost || c.uri != "/api/cli/apps/bab/jam/store/versioning?environment=acme" || c.body != `{"enabled":true,"keep_days":45}` {
t.Fatalf("set sent %s %s %s", c.method, c.uri, c.body)
}
- if _, err := sess.storeVersioningSet(ctx, acct, "jam", "", false, 0); err != nil {
- t.Fatal(err)
- }
- if c.uri != "/api/cli/apps/bab/jam/store/versioning" || c.body != `{"enabled":false}` {
- t.Fatalf("off sent %s %s", c.uri, c.body)
- }
if _, err := sess.storeVersioningStatus(ctx, acct, "jam", ""); err != nil || c.method != http.MethodGet {
t.Fatalf("status: %s, %v", c.method, err)
}
- if _, err := sess.storeVersions(ctx, acct, "jam", "acme", "dir/a b+c"); err != nil {
+ if _, err := sess.storeVersions(ctx, acct, "jam", "acme", "dir/a b+c", ""); err != nil {
t.Fatal(err)
}
if c.method != http.MethodGet || c.uri != "/api/cli/apps/bab/jam/store/versions?environment=acme&key=dir%2Fa+b%2Bc" {
t.Fatalf("versions sent %s %s", c.method, c.uri)
}
+ if _, err := sess.storeVersions(ctx, acct, "jam", "", "k", "v+2"); err != nil {
+ t.Fatal(err)
+ }
+ if c.uri != "/api/cli/apps/bab/jam/store/versions?after=v%2B2&key=k" {
+ t.Fatalf("versions after sent %s", c.uri)
+ }
if _, err := sess.storeRestore(ctx, acct, "jam", "", "k", "v1"); err != nil {
t.Fatal(err)
}
@@ -71,17 +71,71 @@ func TestStoreVersioningWireShapes(t *testing.T) {
// one was chosen; a plain create still sends the bare body it always did.
func TestStoreCreateVersionedWireShape(t *testing.T) {
var c recordingConsole
- ts := c.server(t, map[string]any{"app": "jam", "backend": "", "env_names": []string{}, "missing_vars": []string{}})
+ ts := c.server(t, map[string]any{"app": "jam", "backend": "", "env_names": []string{}, "missing_vars": []string{},
+ "versioning": map[string]any{"enabled": true, "keep_days": 30}})
sess := newTestSession(ts.URL)
for _, tc := range []struct {
- keep int
- want string
- }{{-1, `{}`}, {0, `{"versioning":{}}`}, {90, `{"versioning":{"keep_days":90}}`}} {
- if err := storeCreateAndProvisionVersioned(context.Background(), sess, apiAcct{Seg: "bab"}, "jam", "", "", tc.keep, new(bytes.Buffer)); err != nil {
+ versioned bool
+ keep int
+ want string
+ }{{false, 0, `{}`}, {true, 0, `{"versioning":{}}`}, {true, 90, `{"versioning":{"keep_days":90}}`}} {
+ if err := storeCreateAndProvisionVersioned(context.Background(), sess, apiAcct{Seg: "bab"}, "jam", "", "", tc.versioned, tc.keep, new(bytes.Buffer)); err != nil {
t.Fatal(err)
}
if c.body != tc.want {
- t.Fatalf("keep %d sent %s, want %s", tc.keep, c.body, tc.want)
+ t.Fatalf("%+v sent %s, want %s", tc, c.body, tc.want)
+ }
+ }
+}
+
+// A retention out of range is refused before any request, never turned
+// into an unversioned create (Astra round 1 P2).
+func TestStoreCreateRefusesBadKeepDaysLocally(t *testing.T) {
+ var c recordingConsole
+ ts := c.server(t, map[string]any{"app": "jam"})
+ for _, days := range []int{-1, 7, 366} {
+ err := storeCreateAndProvisionVersioned(context.Background(), newTestSession(ts.URL), apiAcct{Seg: "bab"}, "jam", "", "", true, days, new(bytes.Buffer))
+ if err == nil || !strings.Contains(err.Error(), "--keep-days must be from 30 to 365") || c.method != "" {
+ t.Fatalf("keep %d: err %v, sent %q", days, err, c.method)
+ }
+ }
+}
+
+// A console older than store versioning ignores the field and answers a
+// plain store: the CLI refuses and provisions nothing (Astra round 1 P1).
+func TestStoreCreateVersionedRefusesAnOlderConsole(t *testing.T) {
+ var paths []string
+ ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ paths = append(paths, r.URL.Path)
+ json.NewEncoder(w).Encode(map[string]any{"app": "jam", "backend": "aws", "self_serve": true,
+ "declared": map[string]any{"env_prefix": "CARLOS_STORE", "at": "2026-11-22T10:00:00Z", "by": "a@b"},
+ "entitlement": map[string]any{"decision": map[string]any{"approved": true, "at": "2026-11-22T10:00:00Z"}},
+ "env_names": []string{}, "missing_vars": []string{}})
+ }))
+ t.Cleanup(ts.Close)
+ err := storeCreateAndProvisionVersioned(context.Background(), newTestSession(ts.URL), apiAcct{Seg: "bab"}, "jam", "", "", true, 0, new(bytes.Buffer))
+ if err == nil || !strings.Contains(err.Error(), "older than store versioning") {
+ t.Fatalf("err = %v", err)
+ }
+ for _, p := range paths {
+ if strings.HasSuffix(p, "/provision") {
+ t.Fatal("provisioned an unversioned store behind an older console")
+ }
+ }
+}
+
+// The same for instances enable: asked for and not echoed is a refusal.
+func TestInstancesEnableRefusesAnOlderConsole(t *testing.T) {
+ yes, no := true, false
+ if err := storeVersioningEchoed(&yes, apiInstanceManifest{}); err == nil || !strings.Contains(err.Error(), "older than store versioning") {
+ t.Fatalf("not echoed = %v", err)
+ }
+ for _, tc := range []struct {
+ asked *bool
+ m apiInstanceManifest
+ }{{nil, apiInstanceManifest{}}, {&no, apiInstanceManifest{}}, {&yes, apiInstanceManifest{StoreVersioning: true}}} {
+ if err := storeVersioningEchoed(tc.asked, tc.m); err != nil {
+ t.Fatalf("%+v = %v", tc, err)
}
}
}
@@ -114,7 +168,6 @@ func TestPrintStoreVersioning(t *testing.T) {
{apiVersioningReply{Versioning: "on", KeepDays: 30, Bucket: "pending"}, []string{"bucket set when the store is provisioned"}},
{apiVersioningReply{Versioning: "on", KeepDays: 30, Bucket: "not_applied"}, []string{"not set yet. Run the same command again"}},
{apiVersioningReply{Versioning: "on", KeepDays: 30, Bucket: "rule_changed"}, []string{"a lifecycle rule this platform didn't write"}},
- {apiVersioningReply{Versioning: "off", KeepDays: 60, Bucket: "in_place"}, []string{"versioning off", "versions from before still expire after 60 days"}},
{apiVersioningReply{Versioning: "never"}, []string{"versioning never turned on"}},
} {
var b bytes.Buffer
@@ -140,7 +193,7 @@ func TestPrintStoreVersioningLine(t *testing.T) {
}
printStoreVersioningLine(&b, &apiStoreVersioningBlock{Enabled: true, KeepDays: 30})
printStoreVersioningLine(&b, &apiStoreVersioningBlock{Enabled: false, KeepDays: 30})
- if want := " versioning: on, old versions kept 30 days\n versioning: off; versions from before expire after 30 days\n"; b.String() != want {
+ if want := " versioning: on, old versions kept 30 days\n"; b.String() != want {
t.Fatalf("printed %q, want %q", b.String(), want)
}
}
@@ -163,6 +216,11 @@ func TestPrintStoreVersions(t *testing.T) {
t.Fatalf("version row = %q", lines[2])
}
b.Reset()
+ printStoreVersions(&b, apiVersionsReply{Key: "k", Versions: []apiObjectVersion{{VersionID: "v1", Modified: at}}, Next: "v1"})
+ if !strings.HasSuffix(b.String(), "more: carlos store versions --key k --after v1\n") {
+ t.Fatalf("a page with more = %q", b.String())
+ }
+ b.Reset()
printStoreVersions(&b, apiVersionsReply{Key: "k"})
if b.String() != "no versions of k\n" {
t.Fatalf("empty = %q", b.String())