From 2dd49a22de26baaf8b1e309da856c540687874c1 Mon Sep 17 00:00:00 2001 From: YifanXu1999 Date: Tue, 24 Nov 2026 15:29:43 +0800 Subject: [PATCH 1/4] store: one saved PostgreSQL login on this computer; machines attach Owner direction 2026-11-24: this computer is the one place a PostgreSQL Store's URL and login are saved; machines attach to the Store and dial with both; no machine has an address or a login of its own. Calls: - store.connect(store, url, { user, password, synchronous_commit }); shell `--user U --password-stdin`. A first connect needs both and checks them before saving; the record keeps url, user, synchronous_commit and binding, the password goes to the home secret `secret/login/.json` (never answered, logged or recorded) and into the URL only when dialled. On a connected Store it changes the address, user, password or setting (omitted ones keep the saved ones) after reaching the same binding; outcome `connected` or `updated`. A sqlite Store of the name is `Exists`. - store.disconnect(store): no --machine; also forgets the saved password and every attachment. - New store.attach(store, { machine }) and store.detach(store, { machine }): attach checks from the machine (it must exist and run PostgreSQL Sandboxes) before recording it in the record's `attached` list and its reach (`attached`, or `checked` again); detach is InUse while a Sandbox of the Store's projects is on the machine, NotFound when not attached. sqlite and `native` are InvalidInput. - sandbox.create on a machine not attached is refused InvalidInput with `layerfs store attach --machine ` as its fix. - store.doctor checks this computer, then every attached machine (or --machine alone, which must be attached); a host failure checks no machine. - store.get/list: url, user, password_saved, password_changed_at, binding, reach, machines ({machine, reached, reach}; names in list and the home tree); auth and connections removed. - Removed with no alias: store.save_auth, store.auths, store.remove_auth, store.update, --auth, --machine on connect and disconnect, OwnConnection. No migration or backward compatibility (owner override): the old-format handling is deleted, not replaced. Removed: record.rs outdated fields, refused URLs, without_old_fields, legacy() and OwnConnection; login.rs's save-auth fix machinery (no_auth_fix, missing_fix, login_fix, fix_of, update_fix); state.rs's PostgreSQL `outdated` and `missing` derivation; store_target.rs own_state; connect.rs readdress, refuse_settings and legacy checks; postgresql/update.rs. A record without the new fields fails through the normal dial path. Docs: api/sdk/store.md, control sqlite-and-postgresql.md, versioned 2.0.0 calls.md, machines-and-stores.md and migration.md, the doctor, home, platform, worker, sdk and front-end guides, the JS SDK skill, the call spec (calls.json, families/store.json, families/home.json, 81 calls); regenerated index.d.ts, the Python stubs, coverage.md and mcp.md's profile table. Deleted tests (they drove removed calls or the retired saved-login and own-address model): - api/crates/layerfs-api/tests/postgres_connections.rs (whole file): an_old_record_reads_outdated_until_its_fix_connects_it_again, an_update_racing_a_login_removal_never_names_a_removed_login, every_side_that_connects_is_listed_with_what_was_seen - api/crates/layerfs-api/tests/postgres_update.rs (whole file): addresses_and_logins_are_proven_before_they_are_saved - control/crates/layerfs-store/tests/postgresql_no_auth.rs (whole file): a_key_value_address_is_refused_before_anything_dials_it, a_record_with_no_saved_login_is_refused_with_the_save_auth_fix, a_saved_login_goes_into_the_dialled_url, its_state_is_broken_outdated_with_the_same_fix, the_login_replaces_the_user_part_its_client_reads - postgres_refusals.rs: a_login_is_saved_privately_listed_without_its_password_and_removed_when_unused (rewritten: connect_refuses_a_login_in_the_url_and_a_missing_login, disconnect_refuses_a_held_store_then_forgets_it_and_its_password, attach_and_detach_refuse_what_is_not_theirs, an_old_url_login_is_never_shown) - observed_reach.rs: a_login_file_that_cannot_be_read_is_a_broken_row, a_missing_login_reads_missing_and_wins_over_old_fields, old_fields_read_outdated_and_an_update_drops_them_but_never_a_url, connections_list_every_side_that_connects (replaced by machines_list_the_attached_machines_with_their_reach, a_missing_password_is_refused_and_a_saved_one_is_dialled) - postgresql_url_corpus.rs: a_machine_address_is_connected_again_and_an_update_names_its_login, an_update_fix_dials_only_with_the_login_it_names, an_update_never_rewrites_a_url_to_another_host (replaced by a_connect_never_rewrites_an_older_url_to_another_host) New: api/crates/layerfs-api/tests/postgres_login.rs. Production LOC: 211762 -> 211291 (delta -471) core 42163 -> 42163 (0), engine 97424 -> 97424 (0), control 61844 -> 61437 (-407), api 10331 -> 10267 (-64); reference absent (retired R9c; last counted 65,417 at tree 498dd1917812). Method: python3 tools/production_loc.py --root on `git archive` of the parent fe9b4d1a3c and `git checkout-index -a` of the staged tree; nonblank, non-comment product source, tests, docs, tools and generated stubs excluded. Co-Authored-By: Claude Opus 5.5 --- .agents/skills/layerfs-js-sdk/SKILL.md | 2 +- .../references/methods/store.md | 36 +- api/README.md | 2 +- api/crates/layerfs-api/src/calls/guide.rs | 37 +- api/crates/layerfs-api/src/home/get.rs | 7 +- api/crates/layerfs-api/src/store/attach.rs | 42 ++ api/crates/layerfs-api/src/store/auths.rs | 42 -- api/crates/layerfs-api/src/store/connect.rs | 51 +- api/crates/layerfs-api/src/store/detach.rs | 29 + .../layerfs-api/src/store/disconnect.rs | 20 +- api/crates/layerfs-api/src/store/doctor.rs | 30 +- api/crates/layerfs-api/src/store/get.rs | 54 +- api/crates/layerfs-api/src/store/list.rs | 20 +- api/crates/layerfs-api/src/store/mod.rs | 18 +- .../layerfs-api/src/store/remove_auth.rs | 25 - api/crates/layerfs-api/src/store/save_auth.rs | 42 -- api/crates/layerfs-api/src/store/update.rs | 38 - api/crates/layerfs-api/tests/calls_table.rs | 24 +- api/crates/layerfs-api/tests/contract.rs | 6 +- .../layerfs-api/tests/doctor_targets.rs | 129 +--- api/crates/layerfs-api/tests/gc_calls.rs | 12 +- api/crates/layerfs-api/tests/logs.rs | 29 +- .../layerfs-api/tests/postgres_connect.rs | 105 +-- .../layerfs-api/tests/postgres_connections.rs | 358 --------- .../layerfs-api/tests/postgres_login.rs | 393 ++++++++++ .../layerfs-api/tests/postgres_refusals.rs | 706 ++++++++---------- .../tests/postgres_sandbox_reach.rs | 15 +- .../layerfs-api/tests/postgres_update.rs | 190 ----- .../layerfs-api/tests/project_doctor_full.rs | 12 +- api/crates/layerfs-api/tests/project_stats.rs | 12 +- .../layerfs-api/tests/sandbox_machines.rs | 190 +++-- api/crates/layerfs-api/tests/store_routes.rs | 8 +- api/crates/layerfs-api/tests/store_stats.rs | 12 +- api/crates/layerfs-cli/src/words.rs | 1 - api/crates/layerfs-cli/tests/rendering.rs | 11 +- .../layerfs-cli/tests/saved_continuation.rs | 24 +- api/mcp/src/profiles.js | 2 +- api/node/src/index.d.ts | 41 +- api/node/test/calls.mjs | 4 +- api/python/src/layerfs/_client.pyi | 42 +- api/python/src/layerfs/aio.pyi | 42 +- api/python/test/test_calls.py | 2 +- .../src/doctor/store_target.rs | 88 +-- .../crates/layerfs-control/src/home_tree.rs | 48 +- .../crates/layerfs-control/src/inventory.rs | 31 + control/crates/layerfs-control/src/machine.rs | 8 +- control/crates/layerfs-control/src/store.rs | 226 +++--- .../layerfs-control/src/worker_server/ops.rs | 2 +- .../layerfs-control/tests/in_use_detail.rs | 2 +- control/crates/layerfs-platform/src/reach.rs | 17 +- .../layerfs-platform/src/setup/calls.rs | 5 +- .../layerfs-platform/tests/conformance.rs | 4 +- .../layerfs-platform/tests/machine_reach.rs | 9 +- control/crates/layerfs-sandbox/src/create.rs | 29 +- control/crates/layerfs-sandbox/src/route.rs | 10 +- control/crates/layerfs-store/src/get.rs | 64 +- control/crates/layerfs-store/src/list.rs | 11 +- control/crates/layerfs-store/src/observed.rs | 10 +- .../layerfs-store/src/postgresql/address.rs | 8 +- .../layerfs-store/src/postgresql/check.rs | 95 ++- .../layerfs-store/src/postgresql/connect.rs | 344 ++++----- .../layerfs-store/src/postgresql/login.rs | 430 ++--------- .../layerfs-store/src/postgresql/mod.rs | 7 +- .../layerfs-store/src/postgresql/update.rs | 134 ---- control/crates/layerfs-store/src/record.rs | 202 ++--- control/crates/layerfs-store/src/state.rs | 40 +- .../tests/compact_report_status.rs | 18 +- .../layerfs-store/tests/observed_reach.rs | 335 +++------ .../layerfs-store/tests/postgresql_no_auth.rs | 222 ------ .../layerfs-store/tests/postgresql_status.rs | 17 +- .../tests/postgresql_url_corpus.rs | 499 +++---------- core/docs/issues/call-surface-2-0/calls.json | 364 +++------ .../call-surface-2-0/families/home.json | 59 +- .../call-surface-2-0/families/store.json | 313 +++----- docs/architecture/api/README.md | 2 +- docs/architecture/api/calls/coverage.md | 12 +- docs/architecture/api/front-ends/README.md | 2 +- docs/architecture/api/front-ends/mcp.md | 26 +- docs/architecture/api/sdk/README.md | 6 +- docs/architecture/api/sdk/home.md | 8 +- docs/architecture/api/sdk/sandbox.md | 5 +- docs/architecture/api/sdk/store.md | 356 ++++----- docs/architecture/control/README.md | 4 +- docs/architecture/control/doctor/README.md | 9 +- docs/architecture/control/doctor/findings.md | 6 +- docs/architecture/control/home/README.md | 12 +- .../control/machines/platforms.md | 2 +- .../control/machines/workers-and-reach.md | 10 +- .../control/stores-and-projects/README.md | 4 +- .../sqlite-and-postgresql.md | 160 ++-- docs/versioned/2.0.0/calls.md | 307 ++++---- docs/versioned/2.0.0/machines-and-stores.md | 245 +++--- docs/versioned/2.0.0/migration.md | 20 +- 93 files changed, 2779 insertions(+), 4933 deletions(-) create mode 100644 api/crates/layerfs-api/src/store/attach.rs delete mode 100644 api/crates/layerfs-api/src/store/auths.rs create mode 100644 api/crates/layerfs-api/src/store/detach.rs delete mode 100644 api/crates/layerfs-api/src/store/remove_auth.rs delete mode 100644 api/crates/layerfs-api/src/store/save_auth.rs delete mode 100644 api/crates/layerfs-api/src/store/update.rs delete mode 100644 api/crates/layerfs-api/tests/postgres_connections.rs create mode 100644 api/crates/layerfs-api/tests/postgres_login.rs delete mode 100644 api/crates/layerfs-api/tests/postgres_update.rs delete mode 100644 control/crates/layerfs-store/src/postgresql/update.rs delete mode 100644 control/crates/layerfs-store/tests/postgresql_no_auth.rs diff --git a/.agents/skills/layerfs-js-sdk/SKILL.md b/.agents/skills/layerfs-js-sdk/SKILL.md index ce94e7d2e6..00114a0d24 100644 --- a/.agents/skills/layerfs-js-sdk/SKILL.md +++ b/.agents/skills/layerfs-js-sdk/SKILL.md @@ -364,7 +364,7 @@ refusals and examples. Every option object may also carry `detail`, `with` | [sandbox](references/methods/sandbox.md) | `create(project, name, { machine, image, mount, on_progress })`, `list({ project, machine, limit, cursor })`, `get(sandbox, { with: ["stats"] })`, `remove(sandbox, { force, on_progress })`, `files(sandbox, path?, { depth, limit, cursor, byte_offset, byte_length })`, `log(sandbox, { limit, cursor })`, `doctor(sandbox, { on_progress })` | | [workspace](references/methods/workspace.md) | `list({ sandbox, limit, cursor })`, `mount(sandbox, branch, { name })`, `exec(workspace, command, { cwd, env, stdin, stream, stdout, stderr, on_progress })`, `cancel(workspace, { exec })`, `commit(workspace, { message, expected, force })`, `unmount(workspace, { discard, force })`, `status(workspace, { path })` | | [machine](references/methods/machine.md) | `list({ with: ["live"] })`, `get(machine, { with: ["live"] })`, `images(machine, { with: ["docker"] })`, `load_image(machine, image, { on_progress })`, `prune(machine, image?, { unused })`, `stats(machine, { with: ["space"] })`, `files(machine, path?, { depth, limit, cursor, byte_offset, byte_length })`, `log(machine, { limit, cursor })`, `start(machine, { on_progress })`, `stop(machine, { force, on_progress })`, `create(name, platform, { cpus, memory, disk, image, os_image, on_progress })`, `remove(machine, { on_progress })`, `update(machine, { cpus, memory, image, docker, wsl, daemon })`, `doctor(machine, { on_progress })` | -| [store](references/methods/store.md) | `list({ machine, with: ["stats"] })`, `get(store, { with: ["live", "stats"] })`, `create(name, { machine })`, `connect(store, url, { auth, machine, synchronous_commit })`, `disconnect(store, { machine })`, `save_auth(auth, { user, password })`, `auths()`, `remove_auth(auth)`, `update(store, { auth, synchronous_commit })`, `move(store, machine, { on_progress })`, `remove(store)`, `compact(store, { on_progress })`, `doctor(store, { machine, on_progress })` | +| [store](references/methods/store.md) | `list({ machine, with: ["stats"] })`, `get(store, { with: ["live", "stats"] })`, `create(name, { machine })`, `connect(store, url, { user, password, synchronous_commit })`, `disconnect(store)`, `attach(store, { machine })`, `detach(store, { machine })`, `move(store, machine, { on_progress })`, `remove(store)`, `compact(store, { on_progress })`, `doctor(store, { machine, on_progress })` | | [backup](references/methods/backup.md) | `connect(name, url, { access_key, secret_key })`, `disconnect(bucket)`, `list({ bucket })`, `create(store, bucket, { file, on_progress })`, `restore(bucket, file, store, { on_progress })`, `doctor(bucket, { full })` | `home`, `machine`, `store` and `backup` set up where things live; an agent diff --git a/.agents/skills/layerfs-js-sdk/references/methods/store.md b/.agents/skills/layerfs-js-sdk/references/methods/store.md index 9be3ed894a..de5e999902 100644 --- a/.agents/skills/layerfs-js-sdk/references/methods/store.md +++ b/.agents/skills/layerfs-js-sdk/references/methods/store.md @@ -13,12 +13,10 @@ store.list({ machine, with: ["stats"] }) store.get(store, { with: ["live", "stats"] }) store.create(name, { machine }) -store.connect(store, url, { auth, machine, synchronous_commit }) -store.disconnect(store, { machine }) -store.save_auth(auth, { user, password }) -store.auths() -store.remove_auth(auth) -store.update(store, { auth, synchronous_commit }) +store.connect(store, url, { user, password, synchronous_commit }) +store.disconnect(store) +store.attach(store, { machine }) +store.detach(store, { machine }) store.move(store, machine, { on_progress }) store.remove(store) store.compact(store, { on_progress }) @@ -28,7 +26,8 @@ store.doctor(store, { machine, on_progress }) A Store holds projects and all their history. The verb says the kind: `create` makes a sqlite Store (one file, on one machine at a time; on `native` unless `machine` names another); `connect` connects a PostgreSQL -database with a saved login. +database with its login, saved on this computer only, and `attach` lets a +machine other than `native` run its Sandboxes. ## `store.list` and `store.get` @@ -36,12 +35,15 @@ From the home's records, with no probe. A Store's `state` is `ready`, `busy` (`op`: a move, remove, create, compaction, backup or restore), `blocked` (its machine is not ready) or `broken` (`reason`, with a `fix` naming the call that clears it). `get` short: `{ engine, state }` with `machine`, -`auth`, `projects`, `projects_count`, `backups`, `connections` and the -companion when they say something; long adds `binding` (16-hex prefix of the -Store's database id), `op`, `blocked_by`, `reason`, `fix`, `observed_at`, +`url`, `user`, `machines`, `projects`, `projects_count`, `backups` and the +companion when they say something; long adds `password_saved`, +`password_changed_at`, `binding` (16-hex prefix of the Store's database id), +`reach` (this computer's last reach of a PostgreSQL Store), `op`, `blocked_by`, `reason`, `fix`, `observed_at`, `store`, `profile`, `synchronous_commit`, `sqlite_version`, `created_at`, -`last_transfer`. `list` rows are the same with `store` first; `machine` keeps -the sqlite Stores on one machine. +`last_transfer`. A PostgreSQL Store's `machines` are its attached machines, +each `{ machine, reached, reach }`. `list` rows are the same with `store` +first and `machines` as names; `machine` keeps the sqlite Stores on one +machine. ```bash $ layerfs store list # seen @@ -76,12 +78,10 @@ $ layerfs store get shop --with live,stats # | Call | What it does | Notes | | --- | --- | --- | | `create(name)` | An empty sqlite Store | `{"ok":true}` (seen). A taken name is `Exists` (seen: `a Store named shop exists`). `machine` makes it on that running machine through its worker | -| `save_auth(auth, { user, password })` | Saves or replaces a PostgreSQL login in the home's secret folder (also overwrites a broken/unreadable login file) | Shell: `--user U --password-stdin`; the password is never answered, logged or traced. `{"ok":true}` | -| `auths()` | The saved logins and the Stores that use each | `{ items: [{ auth, user, stores?, stores_count?, state?, reason?, fix? }] }`; long adds `created_at`, `updated_at`; unreadable login files appear as `state: "broken"`, `reason: "failed"` rows with a `save-auth` `fix`; never a password. Seen on a fresh home: `{"items":[]}` | -| `remove_auth(auth)` | Deletes a saved login no Store uses | `InUse` (flat `stores`) while one uses it | -| `connect(store, url, …)` | Connects a PostgreSQL database as a Store (`auth` required the first time; `synchronous_commit` defaults to `local`); on a connected Store, sets its address, or with `machine` proves and records that machine's own reach | The URL holds host, port, database and TLS settings only (`sslkey`/`sslcert` allowed): one naming a user, password or `passfile` is `InvalidInput` (with a `fix` chaining `store save-auth` and `store connect`/`store update` stripped of credentials). Short `{ projects, projects_count? }`, or `{"ok":true}` | -| `update(store, …)` | A PostgreSQL Store's login (`auth`) or `synchronous_commit` | `{"ok":true}` | -| `disconnect(store)` | Forgets a PostgreSQL Store, its data staying; with `machine`, only that machine's own address | `InUse` while a Sandbox or Workspace uses it | +| `connect(store, url, …)` | Connects a PostgreSQL database as a Store (`user` and `password` required the first time, checked before anything is saved; `synchronous_commit` defaults to `local`); on a connected Store, changes its address, user, password or `synchronous_commit` (an omitted user or password keeps the saved one; the same Store must be reached) | The URL holds host, port, database and TLS settings only: one naming a user, password or `passfile` is `InvalidInput` with the `fix` `layerfs store connect --user --password-stdin`. Shell: `--user U --password-stdin`; the password is never answered, logged or traced. Short `{ projects, projects_count? }`, or `{"ok":true}`; long `outcome` `connected` or `updated` | +| `disconnect(store)` | Forgets a PostgreSQL Store with its saved password and attachments, its data staying | `InUse` while a Sandbox or Workspace uses it | +| `attach(store, { machine })` | Lets a machine run Sandboxes of a PostgreSQL Store, checked from that machine with the saved URL and login first | Short `{ ok, outcome, latency_ms? }`; `outcome` `attached`, or `checked` when already attached. A sqlite Store or `native` is `InvalidInput`. `sandbox.create` on a machine not attached is refused with `layerfs store attach --machine ` as its `fix` | +| `detach(store, { machine })` | Stops a machine running Sandboxes of a PostgreSQL Store | `InUse` while a Sandbox of the Store's projects is on it; `NotFound` when not attached | | `move(store, machine)` | Moves a sqlite Store between this computer and a machine | To or from `native` only (seen when already there: `store move, check: Store shop is already on native`, `InvalidInput`; moving off a machine whose record lacks `vm_name` is `Unavailable` with `blocked_by`). Progress `check`, `snapshot`, `send`, `verify`, `install`, `record`, `retire`. Short `{ moved_bytes }`. A sqlite Store's Sandboxes run only on its machine | | `remove(store)` | Deletes a sqlite Store with every project in it | `{"ok":true}`. `NotFound` for an unknown name (seen). A PostgreSQL Store is disconnected instead. A record this build does not read, or a Store on a machine whose record has no 2.0 name, goes by its records alone, with `left` saying what may remain | | `compact(store)` | Reclaims the dead bytes of one Store | The only byte-reclaiming call. Short `{ freed_bytes }` (seen: `{"freed_bytes":0}`); long `outcome` (`compacted` or `unchanged`), `dead_bytes`, `kept_waste`, `peak_temp_bytes`, `zero_reasons`, …. Progress `mark`, `build`, `verify`, `install` (sqlite; an `unchanged` run sends `mark` only). A sqlite Store on another machine is compacted by its worker. `InUse` while Workspaces are mounted; `Busy` (with `op`); `Unavailable`, `Unknown` and `Unresolved` (each with a `fix`) | diff --git a/api/README.md b/api/README.md index 75b361edb2..b7d3df2f72 100644 --- a/api/README.md +++ b/api/README.md @@ -22,7 +22,7 @@ library's call table as ten families of functions, 83 calls in all: | [`sandbox`](../docs/architecture/api/sdk/sandbox.md) | `create`, `list`, `get`, `remove`, `files`, `log`, `doctor` | | [`workspace`](../docs/architecture/api/sdk/workspace.md) | `list`, `mount`, `exec`, `cancel`, `commit`, `unmount`, `status` | | [`machine`](../docs/architecture/api/sdk/machine.md) | `list`, `get`, `images`, `load_image`, `prune`, `stats`, `files`, `log`, `start`, `stop`, `create`, `remove`, `update`, `doctor` | -| [`store`](../docs/architecture/api/sdk/store.md) | `list`, `get`, `create`, `connect`, `disconnect`, `save_auth`, `auths`, `remove_auth`, `update`, `move`, `remove`, `compact`, `doctor` | +| [`store`](../docs/architecture/api/sdk/store.md) | `list`, `get`, `create`, `connect`, `disconnect`, `attach`, `detach`, `move`, `remove`, `compact`, `doctor` | | [`backup`](../docs/architecture/api/sdk/backup.md) | `connect`, `disconnect`, `list`, `create`, `restore`, `doctor` | `layerfs.table` lists every call with its arguments and options; it is the diff --git a/api/crates/layerfs-api/src/calls/guide.rs b/api/crates/layerfs-api/src/calls/guide.rs index acd3e544b5..00d10b7200 100644 --- a/api/crates/layerfs-api/src/calls/guide.rs +++ b/api/crates/layerfs-api/src/calls/guide.rs @@ -67,7 +67,6 @@ const ARGS: &[(&str, &str, &str)] = &[ "a Workspace, written : as `workspace mount` answers", ), ("*", "bucket", "a connected bucket, by name"), - ("*", "auth", "a saved PostgreSQL login, by name"), ( "*", "image", @@ -480,26 +479,24 @@ const ARGS: &[(&str, &str, &str)] = &[ ), ( "store.connect", - "auth", - "the saved login; needed on a Store's first connect", + "user", + "the PostgreSQL role; needed on a Store's first connect", ), ( "store.connect", - "machine", - "the address is this machine's own", + "password", + "the role's password, read from stdin; needed on a Store's first connect", ), ( - "store.disconnect", + "store.attach", "machine", - "remove only this machine's own address", + "the machine that may run the Store's Sandboxes", ), - ("store.save_auth", "user", "the PostgreSQL role"), ( - "store.save_auth", - "password", - "the password, read from stdin", + "store.detach", + "machine", + "the machine that no longer runs the Store's Sandboxes", ), - ("store.update", "auth", "another saved login"), ( "store.move", "machine", @@ -508,7 +505,7 @@ const ARGS: &[(&str, &str, &str)] = &[ ( "store.doctor", "machine", - "also check a PostgreSQL Store's connection from this machine", + "check a PostgreSQL Store from this attached machine only", ), ("backup.connect", "name", "the bucket's name in this home"), ( @@ -678,19 +675,11 @@ const EXAMPLES: &[(&str, &str)] = &[ ("store.create", "layerfs store create shop"), ( "store.connect", - "layerfs store connect team postgresql://db.local:5432/team --auth admin", + "layerfs store connect team postgresql://db.local:5432/team --user layerfs --password-stdin", ), ("store.disconnect", "layerfs store disconnect team"), - ( - "store.save_auth", - "layerfs store save-auth admin --user layerfs --password-stdin", - ), - ("store.auths", "layerfs store auths"), - ("store.remove_auth", "layerfs store remove-auth admin"), - ( - "store.update", - "layerfs store update team --synchronous-commit on", - ), + ("store.attach", "layerfs store attach team --machine dev"), + ("store.detach", "layerfs store detach team --machine dev"), ("store.move", "layerfs store move shop docker --progress"), ("store.remove", "layerfs store remove shop"), ("store.compact", "layerfs store compact shop --progress"), diff --git a/api/crates/layerfs-api/src/home/get.rs b/api/crates/layerfs-api/src/home/get.rs index 31c4107e97..db4d216f51 100644 --- a/api/crates/layerfs-api/src/home/get.rs +++ b/api/crates/layerfs-api/src/home/get.rs @@ -3,7 +3,6 @@ //! in the home. use crate::calls::table::{call, Call}; use crate::calls::{Context, Form, Part, Section}; -use crate::store::get::CONNECTION; use layerfs_bridge::control::SdkValue; use layerfs_control::home::{Build, With}; use layerfs_home::outcome::Outcome; @@ -55,7 +54,7 @@ const STORE: Form = Form::of( &["store", "engine"], &[ "projects", - "connections", + "machines", "state", "op", "blocked_by", @@ -66,7 +65,7 @@ const STORE: Form = Form::of( "store", "engine", "projects", - "connections", + "machines", "state", "op", "blocked_by", @@ -76,7 +75,7 @@ const STORE: Form = Form::of( ) .parts(&[ ("projects", Part::Scalars("project")), - ("connections", Part::Rows(&CONNECTION)), + ("machines", Part::Scalars("machine")), ]); const WORKSPACE: Form = Form::of(&["workspace", "branch"], &[], &["workspace", "branch"]); const SANDBOX: Form = Form::of( diff --git a/api/crates/layerfs-api/src/store/attach.rs b/api/crates/layerfs-api/src/store/attach.rs new file mode 100644 index 0000000000..5a8c657005 --- /dev/null +++ b/api/crates/layerfs-api/src/store/attach.rs @@ -0,0 +1,42 @@ +//! `store.attach`: let a machine run Sandboxes of a PostgreSQL Store, +//! dialling the URL and login this computer saved; checked from it first. +use crate::calls::table::Kind::Name; +use crate::calls::table::{a, call, opt, Call}; +use crate::calls::{Context, Form}; +use layerfs_bridge::control::SdkValue; +use layerfs_home::names::{MachineName, StoreName}; +use layerfs_home::outcome::Outcome; + +/// Its answer: `ok` and the outcome (`attached`, or `checked` for an +/// attached machine checked again), with what the check measured. +const FORM: Form = Form::of( + &["ok", "outcome"], + &["latency_ms"], + &[ + "ok", + "outcome", + "store", + "machine", + "latency_ms", + "server_version", + ], +); + +/// Its table entry. +pub(crate) const CALL: Call = call( + "store", + "attach", + &[a("store", Name)], + &[opt("machine", Name).required()], + "let a machine run Sandboxes of a PostgreSQL Store, checked from that machine first", + run, +) +.form(&FORM); + +/// Runs `store.attach`. +fn run(context: &mut Context<'_>, args: &SdkValue) -> Outcome { + let store = StoreName::parse(args.get_text("store").unwrap_or(""))?; + let machine = MachineName::parse(args.get_text("machine").unwrap_or(""))?; + let (home, events) = context.parts(); + layerfs_control::store::attach(home, events, &store, &machine) +} diff --git a/api/crates/layerfs-api/src/store/auths.rs b/api/crates/layerfs-api/src/store/auths.rs deleted file mode 100644 index c275461ef6..0000000000 --- a/api/crates/layerfs-api/src/store/auths.rs +++ /dev/null @@ -1,42 +0,0 @@ -//! `store.auths`: the saved PostgreSQL logins and the Stores that use each. -use crate::calls::table::{call, Call}; -use crate::calls::{Context, Form, Part}; -use layerfs_bridge::control::SdkValue; -use layerfs_home::outcome::Outcome; - -/// One login: never its password. A login file that cannot be read is -/// `broken` with its fix (spec v23). -const ITEM: Form = Form::of( - &["auth", "user"], - &["state", "reason", "fix", "stores", "stores_count"], - &[ - "auth", - "user", - "state", - "reason", - "fix", - "stores", - "stores_count", - "created_at", - "updated_at", - ], -); - -/// Its answer: every login; unpaged, a home holds a handful. -const FORM: Form = Form::of(&["items"], &[], &["items"]).parts(&[("items", Part::Rows(&ITEM))]); - -/// Its table entry. -pub(crate) const CALL: Call = call( - "store", - "auths", - &[], - &[], - "the saved PostgreSQL logins and the Stores that use each", - run, -) -.form(&FORM); - -/// Runs `store.auths`. -fn run(context: &mut Context<'_>, _args: &SdkValue) -> Outcome { - layerfs_store::postgresql::login::list(&context.home) -} diff --git a/api/crates/layerfs-api/src/store/connect.rs b/api/crates/layerfs-api/src/store/connect.rs index 527ffd0772..c0eb1892b7 100644 --- a/api/crates/layerfs-api/src/store/connect.rs +++ b/api/crates/layerfs-api/src/store/connect.rs @@ -1,14 +1,17 @@ -//! `store.connect`: connect a PostgreSQL database as a Store, or set an -//! address of a connected one (every machine's, or one machine's own). -use crate::calls::table::Kind::{Name, Text}; +//! `store.connect`: connect a PostgreSQL database as a Store, or change a +//! connected one's address, login or `synchronous_commit`. This computer +//! is the one place a Store's URL and login are saved; machines attach to +//! the Store (`store.attach`) and dial both. +use crate::calls::table::Kind::{Content, Name, Text}; use crate::calls::table::{a, call, opt, Call}; -use crate::calls::{Context, Form, Part}; +use crate::calls::{Context, Form}; use layerfs_bridge::control::SdkValue; -use layerfs_home::names::{MachineName, StoreName}; -use layerfs_home::outcome::Outcome; +use layerfs_home::names::StoreName; +use layerfs_home::outcome::{refused, Outcome}; use layerfs_store::postgresql::connect::StoreConnect; -/// Its answer: the projects a first connect found, else `ok`. +/// Its answer: the projects a first connect found, else `ok`; never the +/// password. const FORM: Form = Form::of( &[], &["ok", "projects", "projects_count"], @@ -19,41 +22,45 @@ const FORM: Form = Form::of( "outcome", "store", "engine", - "auth", - "connections", + "url", + "user", "synchronous_commit", + "machines", ], ) -.parts(&[("connections", Part::Rows(&super::get::CONNECTION))]); +.parts(&[("machines", crate::calls::Part::Scalars("machine"))]); -/// Its table entry. +/// Its table entry: the password is a secret the shell reads from stdin. pub(crate) const CALL: Call = call( "store", "connect", &[a("store", Name), a("url", Text).redact()], &[ - opt("auth", Name), - opt("machine", Name), + opt("user", Text), + opt("password", Content).from_stdin("--password-stdin"), opt("synchronous_commit", Text), ], - "connect a PostgreSQL database as a Store, or set an address of a connected one", + "connect a PostgreSQL database as a Store, or change a connected one's address, login or setting", run, ) .form(&FORM); -/// Runs `store.connect`. +/// Runs `store.connect`; a new Store needs `user` and `password`. fn run(context: &mut Context<'_>, args: &SdkValue) -> Outcome { let text = |name: &str| args.get_text(name).map(str::to_owned); + let password = match args.get("password") { + Some(SdkValue::Bytes(bytes)) => Some( + String::from_utf8(bytes.clone()) + .map_err(|_| refused("InvalidInput", "the password is not UTF-8 text"))?, + ), + _ => text("password"), + }; let request = StoreConnect { store: StoreName::parse(args.get_text("store").unwrap_or(""))?, url: text("url").unwrap_or_default(), - auth: text("auth"), + user: text("user"), + password, synchronous_commit: text("synchronous_commit"), }; - let machine = args - .get_text("machine") - .map(MachineName::parse) - .transpose()?; - let (home, events) = context.parts(); - layerfs_control::store::connect(home, events, &request, machine.as_ref()) + layerfs_control::store::connect(&context.home, &request) } diff --git a/api/crates/layerfs-api/src/store/detach.rs b/api/crates/layerfs-api/src/store/detach.rs new file mode 100644 index 0000000000..ac979c1d37 --- /dev/null +++ b/api/crates/layerfs-api/src/store/detach.rs @@ -0,0 +1,29 @@ +//! `store.detach`: a machine no longer runs Sandboxes of a PostgreSQL +//! Store; its reach is forgotten. +use crate::calls::table::Kind::Name; +use crate::calls::table::{a, call, opt, Call}; +use crate::calls::{Context, Form}; +use layerfs_bridge::control::SdkValue; +use layerfs_home::names::{MachineName, StoreName}; +use layerfs_home::outcome::Outcome; + +/// Its answer: `ok`. +const FORM: Form = Form::of(&["ok"], &[], &["ok", "outcome", "store", "machine"]); + +/// Its table entry. +pub(crate) const CALL: Call = call( + "store", + "detach", + &[a("store", Name)], + &[opt("machine", Name).required()], + "stop a machine running Sandboxes of a PostgreSQL Store; refused while one runs there", + run, +) +.form(&FORM); + +/// Runs `store.detach`. +fn run(context: &mut Context<'_>, args: &SdkValue) -> Outcome { + let store = StoreName::parse(args.get_text("store").unwrap_or(""))?; + let machine = MachineName::parse(args.get_text("machine").unwrap_or(""))?; + layerfs_control::store::detach(&context.home, &store, &machine) +} diff --git a/api/crates/layerfs-api/src/store/disconnect.rs b/api/crates/layerfs-api/src/store/disconnect.rs index 9f97352cb5..f12267fc11 100644 --- a/api/crates/layerfs-api/src/store/disconnect.rs +++ b/api/crates/layerfs-api/src/store/disconnect.rs @@ -1,22 +1,22 @@ -//! `store.disconnect`: forget a PostgreSQL Store, or one machine's own -//! address; its data stays. +//! `store.disconnect`: forget a PostgreSQL Store, its saved login and its +//! attachments; its data stays. use crate::calls::table::Kind::Name; -use crate::calls::table::{a, call, opt, Call}; +use crate::calls::table::{a, call, Call}; use crate::calls::{Context, Form}; use layerfs_bridge::control::SdkValue; -use layerfs_home::names::{MachineName, StoreName}; +use layerfs_home::names::StoreName; use layerfs_home::outcome::Outcome; /// Its answer: `ok`. -const FORM: Form = Form::of(&["ok"], &[], &["ok", "outcome", "store", "machine"]); +const FORM: Form = Form::of(&["ok"], &[], &["ok", "outcome", "store"]); /// Its table entry. pub(crate) const CALL: Call = call( "store", "disconnect", &[a("store", Name)], - &[opt("machine", Name)], - "forget a PostgreSQL Store, or one machine's own address and reach; its data stays", + &[], + "forget a PostgreSQL Store, its saved login and its attachments; its data stays", run, ) .form(&FORM); @@ -24,9 +24,5 @@ pub(crate) const CALL: Call = call( /// Runs `store.disconnect`. fn run(context: &mut Context<'_>, args: &SdkValue) -> Outcome { let store = StoreName::parse(args.get_text("store").unwrap_or(""))?; - let machine = args - .get_text("machine") - .map(MachineName::parse) - .transpose()?; - layerfs_control::store::disconnect(&context.home, &store, machine.as_ref()) + layerfs_control::store::disconnect(&context.home, &store) } diff --git a/api/crates/layerfs-api/src/store/doctor.rs b/api/crates/layerfs-api/src/store/doctor.rs index 18193ed98d..79bf3d24e4 100644 --- a/api/crates/layerfs-api/src/store/doctor.rs +++ b/api/crates/layerfs-api/src/store/doctor.rs @@ -1,6 +1,7 @@ //! `store.doctor`: one Store's checks without the whole-Store data scan, -//! then a shallow check of each of its projects. A PostgreSQL Store is also -//! probed from each machine that has a Sandbox of it, and from `--machine`. +//! then a shallow check of each of its projects. A PostgreSQL Store is +//! checked from this computer, then from each machine attached to it, or +//! from `--machine` alone (which must be attached). use crate::calls::table::Kind::Name; use crate::calls::table::{a, call, opt, Call, PROGRESS}; use crate::calls::Context; @@ -28,13 +29,24 @@ fn run(context: &mut Context<'_>, args: &SdkValue) -> Outcome { if let Some(machine) = &machine { // a sqlite Store lives on one machine: no other dials it let record = StoreRecord::read(&context.home, store)?; - if record.and_then(|record| record.kind().ok()) == Some(StoreKind::Sqlite) { - return Err(refused( - "InvalidInput", - format!( - "--machine {machine} probes a PostgreSQL Store's connection; {store} is a sqlite Store, which only its own machine reaches" - ), - )); + match record.as_ref().and_then(|record| record.kind().ok()) { + Some(StoreKind::Sqlite) => { + return Err(refused( + "InvalidInput", + format!( + "--machine {machine} probes a PostgreSQL Store's connection; {store} is a sqlite Store, which only its own machine reaches" + ), + )) + } + // `native` is this computer, which every PostgreSQL Store is + // attached to + Some(StoreKind::Postgresql) + if machine != "native" + && !record.as_ref().is_some_and(|r| r.is_attached(machine)) => + { + return Err(layerfs_control::store::not_attached(store, machine)); + } + _ => {} } } let options = Options { diff --git a/api/crates/layerfs-api/src/store/get.rs b/api/crates/layerfs-api/src/store/get.rs index 30aa205993..d4ce4c654e 100644 --- a/api/crates/layerfs-api/src/store/get.rs +++ b/api/crates/layerfs-api/src/store/get.rs @@ -23,38 +23,33 @@ const BACKUP: Form = Form::of( ], ); -/// A row's `server`: what its URL names. -const SERVER: Form = Form::of( - &["host", "port", "database"], - &[], - &["host", "port", "database"], -); - -/// A row's `reach`: the last one seen. +/// A reach: the last one seen, from this computer (`reach`) or from an +/// attached machine (a `machines` row's). const REACH: Form = Form::of( &["at", "ok"], &["latency_ms", "server_version", "error"], &["at", "ok", "latency_ms", "server_version", "error"], ); -/// One `connections` row of a PostgreSQL Store (spec v23): a side that -/// connects (`machine` null for this computer), the URL it dials, and the -/// word of its last reach; the long form adds whether the address is its -/// own, the server it names and the reach itself. -pub(crate) const CONNECTION: Form = Form::of( - &["url"], - &["machine", "reached"], - &["machine", "url", "own", "server", "reached", "reach"], -) -.parts(&[ - ("server", Part::Rows(&SERVER)), +/// One `machines` row of a PostgreSQL Store: a machine attached to it, the +/// word of its last reach (`ok`, `failed`, null) and, in the long form, the +/// reach itself. +const MACHINE: Form = Form::of(&["machine"], &["reached"], &["machine", "reached", "reach"]) + .parts(&[("reach", Part::Rows(&REACH))]); + +/// The rows inside a Store's answer. +const PARTS: &[(&str, Part)] = &[ + ("projects", Part::Scalars("project")), ("reach", Part::Rows(&REACH)), -]); + ("machines", Part::Rows(&MACHINE)), + ("backups", Part::Rows(&BACKUP)), +]; -/// The rows inside a Store's answer; `store.list` items share them. -pub(super) const PARTS: &[(&str, Part)] = &[ +/// The rows inside a `store.list` item: its `machines` are names. +pub(super) const ITEM_PARTS: &[(&str, Part)] = &[ ("projects", Part::Scalars("project")), - ("connections", Part::Rows(&CONNECTION)), + ("reach", Part::Rows(&REACH)), + ("machines", Part::Scalars("machine")), ("backups", Part::Rows(&BACKUP)), ]; @@ -63,8 +58,9 @@ const FORM: Form = Form::of( &["engine", "state"], &[ "machine", - "auth", - "connections", + "url", + "user", + "machines", "projects", "projects_count", "backups", @@ -78,9 +74,13 @@ const FORM: Form = Form::of( "engine", "state", "machine", - "auth", + "url", + "user", + "password_saved", + "password_changed_at", "binding", - "connections", + "reach", + "machines", "projects", "projects_count", "backups", diff --git a/api/crates/layerfs-api/src/store/list.rs b/api/crates/layerfs-api/src/store/list.rs index 5c67d119c4..5e9011c4ed 100644 --- a/api/crates/layerfs-api/src/store/list.rs +++ b/api/crates/layerfs-api/src/store/list.rs @@ -1,5 +1,5 @@ //! `store.list`: every Store, from the home's records. -use super::get::PARTS; +use super::get::ITEM_PARTS; use crate::calls::table::Kind::Name; use crate::calls::table::{call, opt, Call}; use crate::calls::{Context, Form, Part, Section}; @@ -13,8 +13,8 @@ const ITEM: Form = Form::of( &[ "state", "machine", - "auth", - "connections", + "user", + "machines", "projects", "projects_count", "backups", @@ -29,9 +29,13 @@ const ITEM: Form = Form::of( "engine", "state", "machine", - "auth", + "url", + "user", + "password_saved", + "password_changed_at", "binding", - "connections", + "reach", + "machines", "projects", "projects_count", "backups", @@ -47,7 +51,7 @@ const ITEM: Form = Form::of( "last_transfer", ], ) -.parts(PARTS) +.parts(ITEM_PARTS) .short_when(&[crate::calls::form::OBSERVED]); /// Its answer: the items, unpaged (the list is the home's Store records). @@ -72,6 +76,6 @@ fn run(context: &mut Context<'_>, args: &SdkValue) -> Outcome { .map(MachineName::parse) .transpose()?; let machine = machine.as_ref().map(MachineName::as_str); - let reads = layerfs_control::store::reads(); - layerfs_store::list::list(&context.home, machine, context.with("stats"), reads) + let machines = layerfs_control::store::reads(); + layerfs_store::list::list(&context.home, machine, context.with("stats"), machines) } diff --git a/api/crates/layerfs-api/src/store/mod.rs b/api/crates/layerfs-api/src/store/mod.rs index f885660a92..f5f8165456 100644 --- a/api/crates/layerfs-api/src/store/mod.rs +++ b/api/crates/layerfs-api/src/store/mod.rs @@ -1,23 +1,21 @@ //! The `store` family: one file each (call surface 2.0). A sqlite Store //! is created, moved between this computer and a machine, and removed; a -//! PostgreSQL database is connected and disconnected, with an address of -//! its own per machine (`connect --machine`), and names a saved login -//! (`save_auth`, `auths`, `remove_auth`). `store.get` answers from the +//! PostgreSQL database is connected and disconnected with its URL and +//! login, saved on this computer only, and machines attach to it to run +//! its Sandboxes (`attach`, `detach`). `store.get` answers from the //! home's records (it absorbs `store.status` and `store.stats`), and //! `store.move` replaces `store.push` and `store.pull`. -mod auths; +mod attach; mod compact; mod connect; mod create; +mod detach; mod disconnect; mod doctor; pub(crate) mod get; mod list; mod r#move; mod remove; -mod remove_auth; -mod save_auth; -mod update; use crate::calls::Calls; @@ -29,10 +27,8 @@ pub(crate) fn calls() -> Calls { create::CALL, connect::CALL, disconnect::CALL, - save_auth::CALL, - auths::CALL, - remove_auth::CALL, - update::CALL, + attach::CALL, + detach::CALL, r#move::CALL, remove::CALL, compact::CALL, diff --git a/api/crates/layerfs-api/src/store/remove_auth.rs b/api/crates/layerfs-api/src/store/remove_auth.rs deleted file mode 100644 index 6afc4a6955..0000000000 --- a/api/crates/layerfs-api/src/store/remove_auth.rs +++ /dev/null @@ -1,25 +0,0 @@ -//! `store.remove_auth`: remove a saved PostgreSQL login no Store uses. -use crate::calls::table::Kind::Name; -use crate::calls::table::{a, call, Call}; -use crate::calls::{Context, Form}; -use layerfs_bridge::control::SdkValue; -use layerfs_home::outcome::Outcome; - -/// Its answer: `ok`. -const FORM: Form = Form::of(&["ok"], &[], &["ok", "outcome", "auth"]); - -/// Its table entry. -pub(crate) const CALL: Call = call( - "store", - "remove_auth", - &[a("auth", Name)], - &[], - "remove a saved PostgreSQL login no Store uses", - run, -) -.form(&FORM); - -/// Runs `store.remove_auth`. -fn run(context: &mut Context<'_>, args: &SdkValue) -> Outcome { - layerfs_store::postgresql::login::remove(&context.home, args.get_text("auth").unwrap_or("")) -} diff --git a/api/crates/layerfs-api/src/store/save_auth.rs b/api/crates/layerfs-api/src/store/save_auth.rs deleted file mode 100644 index 1737a0515f..0000000000 --- a/api/crates/layerfs-api/src/store/save_auth.rs +++ /dev/null @@ -1,42 +0,0 @@ -//! `store.save_auth`: save a PostgreSQL login in the home's secret folder; -//! saving again rotates it. -use crate::calls::table::Kind::{Content, Name, Text}; -use crate::calls::table::{a, call, opt, Call}; -use crate::calls::{Context, Form}; -use layerfs_bridge::control::SdkValue; -use layerfs_home::outcome::{refused, Outcome}; - -/// Its answer: `ok`; never the password. -const FORM: Form = Form::of( - &["ok"], - &[], - &["ok", "outcome", "auth", "user", "stores", "stores_count"], -); - -/// Its table entry: the password is a secret the shell reads from stdin. -pub(crate) const CALL: Call = call( - "store", - "save_auth", - &[a("auth", Name)], - &[ - opt("user", Text).required(), - opt("password", Content) - .from_stdin("--password-stdin") - .required(), - ], - "save a PostgreSQL login in the home; saving again rotates it", - run, -) -.form(&FORM); - -/// Runs `store.save_auth`; the table requires `user` and `password`. -fn run(context: &mut Context<'_>, args: &SdkValue) -> Outcome { - let auth = args.get_text("auth").unwrap_or(""); - let user = args.get_text("user").unwrap_or_default(); - let password = match args.get("password") { - Some(SdkValue::Bytes(bytes)) => String::from_utf8(bytes.clone()) - .map_err(|_| refused("InvalidInput", "the password is not UTF-8 text"))?, - _ => args.get_text("password").unwrap_or_default().to_owned(), - }; - layerfs_store::postgresql::login::save(&context.home, auth, user, &password) -} diff --git a/api/crates/layerfs-api/src/store/update.rs b/api/crates/layerfs-api/src/store/update.rs deleted file mode 100644 index 31ad32a3b0..0000000000 --- a/api/crates/layerfs-api/src/store/update.rs +++ /dev/null @@ -1,38 +0,0 @@ -//! `store.update`: change a PostgreSQL Store's saved login or its -//! `synchronous_commit`. -use crate::calls::table::Kind::{Name, Text}; -use crate::calls::table::{a, call, opt, Call}; -use crate::calls::{Context, Form}; -use layerfs_bridge::control::SdkValue; -use layerfs_home::names::StoreName; -use layerfs_home::outcome::Outcome; -use layerfs_store::postgresql::update::{update, StoreUpdate}; - -/// Its answer: `ok`. -const FORM: Form = Form::of( - &["ok"], - &[], - &["ok", "outcome", "store", "auth", "synchronous_commit"], -); - -/// Its table entry. -pub(crate) const CALL: Call = call( - "store", - "update", - &[a("store", Name)], - &[opt("auth", Name), opt("synchronous_commit", Text)], - "change a PostgreSQL Store's saved login or its synchronous_commit", - run, -) -.form(&FORM); - -/// Runs `store.update`. -fn run(context: &mut Context<'_>, args: &SdkValue) -> Outcome { - let text = |name: &str| args.get_text(name).map(str::to_owned); - let request = StoreUpdate { - store: StoreName::parse(args.get_text("store").unwrap_or(""))?, - auth: text("auth"), - synchronous_commit: text("synchronous_commit"), - }; - update(&context.home, &request) -} diff --git a/api/crates/layerfs-api/tests/calls_table.rs b/api/crates/layerfs-api/tests/calls_table.rs index 5c4ac388bf..2ef07beaec 100644 --- a/api/crates/layerfs-api/tests/calls_table.rs +++ b/api/crates/layerfs-api/tests/calls_table.rs @@ -412,10 +412,20 @@ fn machine_family() { fn store_family() { assert!(code("store.move", map(&[("store", t("shop"))])).contains("`machine` is required")); // a required option is refused before the call runs - let auth = map(&[("auth", t("pg")), ("password", t("pw"))]); - assert!(code("store.save_auth", auth).contains("`user` is required")); + for call in ["store.attach", "store.detach"] { + assert!(code(call, map(&[("store", t("pg"))])).contains("`machine` is required")); + } // the old names are gone, with no alias - for gone in ["store.status", "store.stats", "store.push", "store.pull"] { + for gone in [ + "store.status", + "store.stats", + "store.push", + "store.pull", + "store.save_auth", + "store.auths", + "store.remove_auth", + "store.update", + ] { assert!(layerfs_api::find(gone).is_none(), "{gone}"); } let reached = code("store.list", SdkValue::Null); @@ -454,7 +464,7 @@ fn backup_family() { }; for (name, required) in [ ("backup.connect", ["access_key", "secret_key"]), - ("store.save_auth", ["user", "password"]), + ("store.attach", ["machine", "machine"]), ("file.edit", ["old_string", "new_string"]), ] { let Some(SdkValue::List(options)) = entry(name).get("options").cloned() else { @@ -782,10 +792,8 @@ fn a_migrated_entry_declares_its_forms_and_the_others_declare_none() { "store.create", "store.connect", "store.disconnect", - "store.save_auth", - "store.auths", - "store.remove_auth", - "store.update", + "store.attach", + "store.detach", "store.move", "store.remove", "store.compact", diff --git a/api/crates/layerfs-api/tests/contract.rs b/api/crates/layerfs-api/tests/contract.rs index 81b4c185c4..23068edadf 100644 --- a/api/crates/layerfs-api/tests/contract.rs +++ b/api/crates/layerfs-api/tests/contract.rs @@ -174,7 +174,7 @@ fn every_call_is_migrated_or_pending_and_the_table_names_no_other() { let spec = read(SPEC); let pending = read(PENDING); let named: Vec<&str> = rows(&spec).into_iter().map(name).collect(); - assert_eq!(named.len(), 83); + assert_eq!(named.len(), 81); let waiting = texts(at(&pending, "calls")); for call in &named { let migrated = layerfs_api::find(call).is_some_and(|entry| entry.form.is_some()); @@ -578,7 +578,7 @@ fn a_migrated_entry_declares_what_its_row_says() { #[test] fn every_row_s_long_example_shapes_to_its_long_and_short_keys() { - // one rule, no I/O: all 83 rows, migrated or not + // one rule, no I/O: all 81 rows, migrated or not let spec = read(SPEC); let mut seen = 0; for row in rows(&spec) { @@ -640,7 +640,7 @@ fn every_row_s_long_example_shapes_to_its_long_and_short_keys() { } seen += 1; } - assert_eq!(seen, 83); + assert_eq!(seen, 81); } fn paged(row: &SdkValue) -> bool { diff --git a/api/crates/layerfs-api/tests/doctor_targets.rs b/api/crates/layerfs-api/tests/doctor_targets.rs index bdcf4701ca..bc9499e0ad 100644 --- a/api/crates/layerfs-api/tests/doctor_targets.rs +++ b/api/crates/layerfs-api/tests/doctor_targets.rs @@ -339,56 +339,28 @@ fn what_is_not_there_is_refused_and_no_home_is_made() { } /// A Store whose record alone makes it broken (UI pass 2, F6): the doctor's -/// finding carries the fix its state gives in `store.list`. A PostgreSQL -/// Store naming no saved login fails `store.record` and `store.connection` -/// with the save-auth fix, its `--user` the one its URL names, before -/// anything is dialled; one with old fields (V23-6) or naming a login this -/// home does not hold fails `store.record` with `store.list`'s fix (area -/// 15); a record of a kind this build does not read fails `store.record` -/// with `store remove`. +/// finding carries the fix its state gives in `store.list` (a record of a +/// kind this build does not read: `store remove`). A PostgreSQL Store that +/// cannot be dialled fails `store.connection` before anything is dialled, +/// with its refusal's fix: its password not saved in this home, the +/// connect that saves it; its record naming no user, none. #[test] fn a_store_s_broken_record_gives_its_state_s_fix() { let home = tempdir("store-fix"); short(&home, "home.init", &[]); - write_entity( - &paths::store_record(&home, "pg"), - &SdkValue::map([ - ("name", t("pg")), + for (store, user) in [("pg", None), ("gone", Some(("user", t("owner"))))] { + let mut fields = vec![ + ("name", t(store)), ("kind", t("postgresql")), - ("url", t("postgresql://owner@db.invalid:5432/layerfs_db")), + ("url", t("postgresql://127.0.0.1:1/layerfs_db")), ("schema", t("layerfs")), ("synchronous_commit", t("local")), ("binding", SdkValue::Bytes(vec![1; 16])), ("cursor", SdkValue::Bytes(vec![7; 32])), - ]), - ) - .unwrap(); - // a saved login, and a URL naming a user (V23-6), to a port nothing - // listens on: refused at once when the doctor dials it - short( - &home, - "store.save_auth", - &[ - ("auth", t("a")), - ("user", t("owner")), - ("password", t("pw")), - ], - ); - for (store, auth) in [("old", "a"), ("gone", "nosuch")] { - write_entity( - &paths::store_record(&home, store), - &SdkValue::map([ - ("name", t(store)), - ("kind", t("postgresql")), - ("url", t("postgresql://owner@127.0.0.1:1/layerfs_db")), - ("auth", t(auth)), - ("schema", t("layerfs")), - ("synchronous_commit", t("local")), - ("binding", SdkValue::Bytes(vec![1; 16])), - ("cursor", SdkValue::Bytes(vec![7; 32])), - ]), - ) - .unwrap(); + ]; + fields.extend(user); + let fields = fields.into_iter().map(|(k, v)| (k.to_owned(), v)).collect(); + write_entity(&paths::store_record(&home, store), &SdkValue::Map(fields)).unwrap(); } write_entity( &paths::store_record(&home, "odd"), @@ -396,40 +368,16 @@ fn a_store_s_broken_record_gives_its_state_s_fix() { ) .unwrap(); let listed = short(&home, "store.list", &[]); - let item = |name: &str| { - (list(&listed, "items").iter()) - .find(|item| item.get_text("store") == Some(name)) - .cloned() - .unwrap_or_else(|| panic!("{name}: {listed:?}")) - }; - // a URL naming a user is never rewritten: the Store is connected again - // with the address alone, `` and `` to fill in (the fix named - // `--user owner` and updated the Store, cleaning its URL, before the - // e0aa26e149 Decision) - let pg_fix = "layerfs store save-auth --user --password-stdin && layerfs store disconnect pg && layerfs store connect pg --auth --synchronous-commit local"; - assert_eq!(item("pg").get_text("reason"), Some("outdated")); - assert_eq!(item("pg").get_text("fix"), Some(pg_fix)); - assert_eq!( - item("odd").get_text("fix"), - Some("layerfs store remove odd") - ); - - assert_eq!(item("old").get_text("reason"), Some("outdated")); - let old_fix = "layerfs store disconnect old && layerfs store connect old --auth --synchronous-commit local"; - assert_eq!(item("old").get_text("fix"), Some(old_fix)); - assert_eq!(item("gone").get_text("reason"), Some("missing")); - let gone_fix = item("gone").get_text("fix").unwrap().to_owned(); - assert!( - gone_fix.starts_with("layerfs store save-auth nosuch "), - "{gone_fix}" - ); - + let odd = (list(&listed, "items").iter()) + .find(|item| item.get_text("store") == Some("odd")) + .cloned() + .unwrap_or_else(|| panic!("{listed:?}")); + assert_eq!(odd.get_text("fix"), Some("layerfs store remove odd")); + let gone_fix = "layerfs store connect gone --password-stdin"; for (store, check, fix) in [ - ("pg", "store.record", pg_fix), - ("pg", "store.connection", pg_fix), - ("old", "store.record", old_fix), - ("gone", "store.record", gone_fix.as_str()), - ("odd", "store.record", "layerfs store remove odd"), + ("pg", "store.connection", None), + ("gone", "store.connection", Some(gone_fix)), + ("odd", "store.record", Some("layerfs store remove odd")), ] { let short_form = short(&home, "store.doctor", &[("store", t(store))]); let long_form = long(&home, "store.doctor", &[("store", t(store))]); @@ -439,7 +387,8 @@ fn a_store_s_broken_record_gives_its_state_s_fix() { .find(|f| f.get_text("check") == Some(check)) .unwrap_or_else(|| panic!("{store}: {report:?}")); assert_eq!(found.get_text("store"), Some(store), "{found:?}"); - assert_eq!(found.get_text("fix"), Some(fix), "{found:?}"); + assert_eq!(found.get_text("severity"), Some("error"), "{found:?}"); + assert_eq!(found.get_text("fix"), fix, "{found:?}"); } } let _ = std::fs::remove_dir_all(home); @@ -465,15 +414,7 @@ fn a_silent_server_fails_its_connection_within_the_handshake_limit() { }); let home = tempdir("silent"); short(&home, "home.init", &[]); - short( - &home, - "store.save_auth", - &[ - ("auth", t("a")), - ("user", t("owner")), - ("password", t("pw")), - ], - ); + layerfs_store::postgresql::login::save(&home, "silent", "pw").unwrap(); let url = format!("postgresql://127.0.0.1:{port}/layerfs_db?sslmode=disable"); write_entity( &paths::store_record(&home, "silent"), @@ -481,7 +422,7 @@ fn a_silent_server_fails_its_connection_within_the_handshake_limit() { ("name", t("silent")), ("kind", t("postgresql")), ("url", t(&url)), - ("auth", t("a")), + ("user", t("owner")), ("schema", t("layerfs")), ("synchronous_commit", t("local")), ("binding", SdkValue::Bytes(vec![1; 16])), @@ -505,10 +446,8 @@ fn a_silent_server_fails_its_connection_within_the_handshake_limit() { .all(|n| n.get_text("check") != Some("store.connection"))); let got = long(&home, "store.get", &[("store", t("silent"))]); - let here = (list(&got, "connections").iter()) - .find(|row| row.get("machine") == Some(&SdkValue::Null)) - .unwrap_or_else(|| panic!("{got:?}")); - assert_eq!(here.get_text("reached"), Some("failed"), "{here:?}"); + let here = got.get("reach").unwrap_or_else(|| panic!("{got:?}")); + assert_eq!(here.get("ok"), Some(&SdkValue::Bool(false)), "{here:?}"); let started = Instant::now(); let live = long( @@ -567,22 +506,14 @@ fn a_sqlite_project_without_a_manifest_fails_project_doctor() { } // PostgreSQL project records hold no manifest; project.record still passes. - short( - &home, - "store.save_auth", - &[ - ("auth", t("a")), - ("user", t("owner")), - ("password", t("pw")), - ], - ); + layerfs_store::postgresql::login::save(&home, "pg", "pw").unwrap(); write_entity( &paths::store_record(&home, "pg"), &SdkValue::map([ ("name", t("pg")), ("kind", t("postgresql")), ("url", t("postgresql://db.invalid:5432/layerfs_db")), - ("auth", t("a")), + ("user", t("owner")), ("schema", t("layerfs")), ("synchronous_commit", t("local")), ("binding", SdkValue::Bytes(vec![1; 16])), diff --git a/api/crates/layerfs-api/tests/gc_calls.rs b/api/crates/layerfs-api/tests/gc_calls.rs index ff71ffbbce..1a963ccbe9 100644 --- a/api/crates/layerfs-api/tests/gc_calls.rs +++ b/api/crates/layerfs-api/tests/gc_calls.rs @@ -585,21 +585,17 @@ fn a_close_without_a_store_url_has_its_caller_end_the_mount_intents() { std::fs::write(folder.join("base.txt"), "hello\n").unwrap(); // the URL's user becomes a saved login (a trust-auth server takes any // password); the address is connected without it + let clean = format!("postgresql://{address}:{port}/{database}?sslmode=disable"); ok( &home, - "store.save_auth", + "store.connect", &[ - ("auth", t("pg")), + ("store", t("pg")), + ("url", t(&clean)), ("user", t(&user)), ("password", t("unused")), ], ); - let clean = format!("postgresql://{address}:{port}/{database}?sslmode=disable"); - ok( - &home, - "store.connect", - &[("store", t("pg")), ("url", t(&clean)), ("auth", t("pg"))], - ); ok( &home, "project.init", diff --git a/api/crates/layerfs-api/tests/logs.rs b/api/crates/layerfs-api/tests/logs.rs index 0c3e645431..852270dc13 100644 --- a/api/crates/layerfs-api/tests/logs.rs +++ b/api/crates/layerfs-api/tests/logs.rs @@ -320,31 +320,20 @@ fn free_text_credentials_content_and_json_are_byte_counts() { &[ ("store", t("pg")), ("url", t("postgres://db.internal/x")), - ("auth", t("pg-app")), - ], - ); - let words = argv(&last(&home)); - assert_eq!( - words, - [ - "store".to_owned(), - "connect".into(), - "pg".into(), - bytes(24), - "--auth".into(), - "pg-app".into() - ] - ); - let _ = call( - &home, - "store.save_auth", - &[ - ("auth", t("pg-app")), ("user", t("app")), ("password", t("hunter2")), ], ); let line = last(&home); + let words = argv(&line); + assert_eq!( + &words[..4], + ["store".to_owned(), "connect".into(), "pg".into(), bytes(24)] + ); + assert!( + words.windows(2).any(|w| w == ["--user", "app"]), + "{words:?}" + ); let printed = layerfs_api::json::print(&line); assert!(!printed.contains("hunter2"), "{printed}"); assert!(argv(&line).contains(&bytes(7)), "{printed}"); diff --git a/api/crates/layerfs-api/tests/postgres_connect.rs b/api/crates/layerfs-api/tests/postgres_connect.rs index 6c07239e6f..fddbd00984 100644 --- a/api/crates/layerfs-api/tests/postgres_connect.rs +++ b/api/crates/layerfs-api/tests/postgres_connect.rs @@ -1,13 +1,14 @@ -//! PostgreSQL Stores (#533 steps 10a and 10b, call surface 2.0): connect +//! PostgreSQL Stores (#533 steps 10a and 10b; owner, 2026-11-24): connect //! makes the `layerfs` schema in an empty database and records it as a -//! Store naming a saved login, read per call; Init writes a project into it; Store -//! calls then run on it; disconnect forgets it and keeps its data, and a -//! second connect finds the project. The same database under a second name -//! is `Exists`, by the id in its schema. Needs LAYERFS_TEST_PG_URL (a -//! server URL with its user and no password, to a database with no -//! `layerfs` schema; the test leaves one behind) and -//! LAYERFS_TEST_PG_PASSWORD (the user's password, saved as a login); -//! without them the test says so and passes. +//! Store with its user, its password saved in the home's secret folder and +//! put into the URL per call; Init writes a project into it; Store calls +//! then run on it; a connect of the connected Store keeps its login; +//! disconnect forgets it and its password and keeps its data, and a second +//! connect finds the project. The same database under a second name is +//! `Exists`, by the id in its schema. Needs LAYERFS_TEST_PG_URL (a server +//! URL with its user and no password, to a database with no `layerfs` +//! schema; the test leaves one behind) and LAYERFS_TEST_PG_PASSWORD (the +//! user's password); without them the test says so and passes. use layerfs_api::home::{self, paths}; use layerfs_bridge::control::SdkValue; use std::path::{Path, PathBuf}; @@ -38,22 +39,16 @@ fn ok(home: &Path, name: &str, args: &[(&str, SdkValue)]) -> SdkValue { call(home, name, args).unwrap_or_else(|e| panic!("{name}: {e:?}")) } -/// Saves `url`'s user with LAYERFS_TEST_PG_PASSWORD as login `pg`, and -/// answers the address without the user. -fn login(home: &Path, url: &str) -> String { +/// `url`'s address without its user, and the login: its user with +/// LAYERFS_TEST_PG_PASSWORD. +fn login(url: &str) -> (String, [(&'static str, SdkValue); 2]) { let (scheme, rest) = url.split_once("://").unwrap(); let (user, address) = rest.split_once('@').unwrap(); let password = std::env::var("LAYERFS_TEST_PG_PASSWORD").unwrap(); - ok( - home, - "store.save_auth", - &[ - ("auth", t("pg")), - ("user", t(user)), - ("password", t(&password)), - ], - ); - format!("{scheme}://{address}") + ( + format!("{scheme}://{address}"), + [("user", t(user)), ("password", t(&password))], + ) } #[test] @@ -68,29 +63,35 @@ fn connect_read_and_disconnect() { let home = tempdir("home"); home::open(&home).unwrap(); + let (address, login) = login(&url); + let with_login = |args: &[(&'static str, SdkValue)]| { + let mut args = args.to_vec(); + args.extend(login.iter().cloned()); + args + }; // a URL naming its user is refused before any effect let refused = call( &home, "store.connect", - &[("store", t("pg")), ("url", t(&url)), ("auth", t("pg"))], + &with_login(&[("store", t("pg")), ("url", t(&url))]), ); assert_eq!(refused.unwrap_err().0, "InvalidInput"); - let url = login(&home, &url); - let password = || ("auth", t("pg")); + let url = address; // an empty database: connect makes the schema, with no project yet let connected = ok( &home, "store.connect", - &[ + &with_login(&[ ("store", t("pg")), ("url", t(&url)), - password(), ("detail", SdkValue::Bool(true)), - ], + ]), ); assert_eq!(connected.get("projects"), Some(&SdkValue::List(vec![]))); assert_eq!(connected.get_text("outcome"), Some("connected")); - assert_eq!(connected.get_text("auth"), Some("pg")); + assert_eq!(connected.get("user"), Some(&login[0].1)); + assert_eq!(connected.get_text("url"), Some(url.as_str())); + assert!(connected.get("password").is_none(), "{connected:?}"); assert_eq!(connected.get_text("synchronous_commit"), Some("local")); // Init into it, with progress on the call's stream let folder = tempdir("folder"); @@ -126,17 +127,17 @@ fn connect_read_and_disconnect() { !record.contains(&std::env::var("LAYERFS_TEST_PG_PASSWORD").unwrap()), "no password on disk" ); - // a connected Store takes an address only: --auth is refused - assert_eq!( - call( - &home, - "store.connect", - &[("store", t("pg")), ("url", t(&url)), password()] - ) - .unwrap_err() - .0, - "InvalidInput" + // a connect of the connected Store with no login keeps the saved one + let updated = ok( + &home, + "store.connect", + &[ + ("store", t("pg")), + ("url", t(&url)), + ("detail", SdkValue::Bool(true)), + ], ); + assert_eq!(updated.get_text("outcome"), Some("updated"), "{updated:?}"); // the same database under a second name (#533 review P1-15): by the // id in its schema, whatever the address says let alias = if url.contains("127.0.0.1") { @@ -151,7 +152,7 @@ fn connect_read_and_disconnect() { let refused = call( &home, "store.connect", - &[("store", t("pg-again")), ("url", t(&second)), password()], + &with_login(&[("store", t("pg-again")), ("url", t(&second))]), ) .unwrap_err(); assert_eq!(refused.0, "Exists", "{second}: {refused:?}"); @@ -238,10 +239,17 @@ fn connect_read_and_disconnect() { // this process's own open copy does not block a disconnect ok(&home, "store.disconnect", &[("store", t("pg"))]); assert!(!paths::store_dir(&home, "pg").exists()); + // its password goes with it + let saved = layerfs_api::home::secrets::dir(&home).join("login"); + assert!( + !std::fs::read_dir(&saved).is_ok_and(|mut files| files.next().is_some()), + "{}", + saved.display() + ); let again = ok( &home, "store.connect", - &[("store", t("pg2")), ("url", t(&url)), password()], + &with_login(&[("store", t("pg2")), ("url", t(&url))]), ); assert_eq!( again.get("projects"), @@ -275,19 +283,12 @@ fn a_missing_database_is_a_refused_session() { }; let home = tempdir("missing"); home::open(&home).unwrap(); - let url = login(&home, &url); + let (url, login) = login(&url); let (server, _) = url.rsplit_once('/').unwrap(); let missing = format!("{server}/lfs_no_such_database"); - let (code, message) = call( - &home, - "store.connect", - &[ - ("store", t("gone")), - ("url", t(&missing)), - ("auth", t("pg")), - ], - ) - .unwrap_err(); + let mut args = vec![("store", t("gone")), ("url", t(&missing))]; + args.extend(login); + let (code, message) = call(&home, "store.connect", &args).unwrap_err(); assert_eq!(code, "Unavailable", "{message}"); assert!( message.contains("the server refused the session"), diff --git a/api/crates/layerfs-api/tests/postgres_connections.rs b/api/crates/layerfs-api/tests/postgres_connections.rs deleted file mode 100644 index 63557de08a..0000000000 --- a/api/crates/layerfs-api/tests/postgres_connections.rs +++ /dev/null @@ -1,358 +0,0 @@ -//! Who connects to a PostgreSQL Store's database (spec v23), through the -//! call table against a real server: `store.connect --machine` and -//! `store.doctor` record each side's reach, `store.get` lists every side -//! that connects with its word (`reached`) in both forms and the Store's -//! `binding`, `store.disconnect --machine` forgets a machine seen only by a -//! reach, a record with old fields reads `broken` `outdated` until its fix -//! runs (a URL naming a user is never rewritten: the Store is disconnected -//! and connected again with the address alone), a login that is not saved reads -//! `missing`, and `store.update --auth` racing `store.remove_auth` never -//! leaves a Store naming a removed login. Needs LAYERFS_TEST_PG_URL (a -//! server URL with its user and no password, to a database with no -//! `layerfs` schema; the test leaves one behind) and -//! LAYERFS_TEST_PG_PASSWORD; without them it says so and passes. -#![cfg(feature = "machine")] -use layerfs_api::home::{self, paths}; -use layerfs_bridge::control::SdkValue; -use std::os::unix::fs::PermissionsExt; -use std::path::{Path, PathBuf}; - -fn tempdir(tag: &str) -> PathBuf { - let dir = std::env::temp_dir().join(format!("layerfs-pgconn-{tag}-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&dir); - std::fs::create_dir_all(&dir).unwrap(); - std::fs::set_permissions(&dir, std::fs::Permissions::from_mode(0o700)).unwrap(); - dir -} - -fn t(s: &str) -> SdkValue { - SdkValue::text(s) -} - -fn call_as( - home: &Path, - name: &str, - args: &[(&str, SdkValue)], - detail: bool, -) -> Result { - let mut args: Vec<(String, SdkValue)> = args - .iter() - .map(|(n, v)| ((*n).to_owned(), v.clone())) - .collect(); - args.push(("detail".to_owned(), SdkValue::Bool(detail))); - layerfs_api::call(Some(home), name, SdkValue::Map(args), &mut |_| {}) - .map_err(|r| (r.code, r.message)) -} - -fn ok(home: &Path, name: &str, args: &[(&str, SdkValue)]) -> SdkValue { - call_as(home, name, args, true).unwrap_or_else(|e| panic!("{name}: {e:?}")) -} - -fn rows(answer: &SdkValue) -> Vec { - match answer.get("connections") { - Some(SdkValue::List(rows)) => rows.clone(), - _ => panic!("connections: {answer:?}"), - } -} - -fn row<'a>(rows: &'a [SdkValue], machine: Option<&str>) -> &'a SdkValue { - let mut found = rows.iter(); - found - .find(|row| row.get_text("machine") == machine) - .unwrap_or_else(|| panic!("{machine:?}: {rows:?}")) -} - -/// The tests share one database: one at a time. -static ONE: std::sync::Mutex<()> = std::sync::Mutex::new(()); - -struct Server { - user: String, - password: String, - url: String, -} - -fn server() -> Option { - let (Ok(url), Ok(password)) = ( - std::env::var("LAYERFS_TEST_PG_URL"), - std::env::var("LAYERFS_TEST_PG_PASSWORD"), - ) else { - eprintln!("NOT_RUN: LAYERFS_TEST_PG_URL / LAYERFS_TEST_PG_PASSWORD unset"); - return None; - }; - let (scheme, rest) = url.split_once("://").unwrap(); - let (user, address) = rest.split_once('@').unwrap(); - Some(Server { - user: user.to_owned(), - password, - url: format!("{scheme}://{address}"), - }) -} - -fn save(home: &Path, server: &Server, auth: &str) { - ok( - home, - "store.save_auth", - &[ - ("auth", t(auth)), - ("user", t(&server.user)), - ("password", t(&server.password)), - ], - ); -} - -fn edit(home: &Path, store: &str, change: impl FnOnce(SdkValue) -> SdkValue) { - let path = paths::store_record(home, store); - let record = home::read_record(&path).unwrap().unwrap(); - home::write_record(&path, &change(record)).unwrap(); -} - -#[test] -fn every_side_that_connects_is_listed_with_what_was_seen() { - let Some(server) = server() else { return }; - let _one = ONE.lock().unwrap_or_else(|e| e.into_inner()); - let home = tempdir("rows"); - home::open(&home).unwrap(); - save(&home, &server, "pg"); - let url = server.url.clone(); - ok( - &home, - "store.connect", - &[("store", t("pg")), ("url", t(&url)), ("auth", t("pg"))], - ); - // nothing seen yet: this computer's row only, with no word - let got = ok(&home, "store.get", &[("store", t("pg"))]); - let binding = got.get_text("binding").expect("binding"); - assert_eq!(binding.len(), 16, "{binding}"); - assert!(binding.chars().all(|c| c.is_ascii_hexdigit()), "{binding}"); - let listed = rows(&got); - assert_eq!(listed.len(), 1, "{listed:?}"); - assert_eq!(row(&listed, None).get("reached"), Some(&SdkValue::Null)); - - // the doctor records this computer's reach, measured - ok(&home, "store.doctor", &[("store", t("pg"))]); - let listed = rows(&ok(&home, "store.get", &[("store", t("pg"))])); - let here = row(&listed, None); - assert_eq!(here.get_text("reached"), Some("ok"), "{here:?}"); - let reach = here.get("reach").unwrap(); - assert!(reach.get_int("latency_ms").is_some(), "{reach:?}"); - assert!(reach.get_text("server_version").is_some(), "{reach:?}"); - - // a machine's own address records its check - ok( - &home, - "store.connect", - &[ - ("store", t("pg")), - ("url", t(&url)), - ("machine", t("native")), - ], - ); - let listed = rows(&ok(&home, "store.get", &[("store", t("pg"))])); - let native = row(&listed, Some("native")); - assert_eq!(native.get("own"), Some(&SdkValue::Bool(true))); - assert_eq!(native.get_text("reached"), Some("ok"), "{native:?}"); - - // a failed reach seen from a machine shows in the short form too - let file = home::observed::file(&paths::store_record(&home, "pg")); - let mut seen = home::read_record(&file).unwrap().unwrap(); - let failed = SdkValue::map([ - ("at", SdkValue::Int(1)), - ("ok", SdkValue::Bool(false)), - ("error", t("timed out")), - ]); - let mut reaches = seen - .get("reach") - .cloned() - .unwrap_or(SdkValue::Map(Vec::new())); - reaches = home::with_field(reaches, "lab", failed); - seen = home::with_field(seen, "reach", reaches); - home::write_record(&file, &seen).unwrap(); - let short = call_as(&home, "store.get", &[("store", t("pg"))], false).unwrap(); - let lab = row(&rows(&short), Some("lab")).clone(); - assert_eq!(lab.get_text("reached"), Some("failed"), "{lab:?}"); - assert!(lab.get("reach").is_none(), "short form: {lab:?}"); - // the list's rows carry it too - let list = ok(&home, "store.list", &[]); - let Some(SdkValue::List(items)) = list.get("items") else { - panic!("{list:?}"); - }; - assert_eq!( - row(&rows(&items[0]), Some("lab")).get_text("reached"), - Some("failed") - ); - - // a machine seen only by a reach is forgotten by its disconnect - ok( - &home, - "store.disconnect", - &[("store", t("pg")), ("machine", t("lab"))], - ); - let listed = rows(&ok(&home, "store.get", &[("store", t("pg"))])); - assert!(listed.iter().all(|r| r.get_text("machine") != Some("lab"))); - let (code, _) = call_as( - &home, - "store.disconnect", - &[("store", t("pg")), ("machine", t("lab"))], - true, - ) - .unwrap_err(); - assert_eq!(code, "NotFound"); - // the password is in the secret folder only - for path in [paths::store_record(&home, "pg"), file] { - let text = std::fs::read_to_string(&path).unwrap(); - assert!(!text.contains(&server.password), "{}", path.display()); - } - ok(&home, "store.disconnect", &[("store", t("pg"))]); - std::fs::remove_dir_all(home).unwrap(); -} - -#[test] -fn an_old_record_reads_outdated_until_its_fix_connects_it_again() { - let Some(server) = server() else { return }; - let _one = ONE.lock().unwrap_or_else(|e| e.into_inner()); - let home = tempdir("old"); - home::open(&home).unwrap(); - save(&home, &server, "pg"); - ok( - &home, - "store.connect", - &[ - ("store", t("pg")), - ("url", t(&server.url)), - ("auth", t("pg")), - ], - ); - let (scheme, address) = server.url.split_once("://").unwrap(); - let named = format!("{scheme}://{}@{address}", server.user); - edit(&home, "pg", |record| { - let record = home::with_field(record, "password", t("file:/no/such")); - let record = home::with_field(record, "url", t(&named)); - let checked = SdkValue::map([("checked", SdkValue::map([("at", SdkValue::Int(1))]))]); - home::with_field(record, "machines", SdkValue::map([("lab", checked)])) - }); - let got = ok(&home, "store.get", &[("store", t("pg"))]); - assert_eq!(got.get_text("state"), Some("broken"), "{got:?}"); - assert_eq!(got.get_text("reason"), Some("outdated")); - // the URL names a user: it is never rewritten, so the fix connects the - // Store again with the address alone, its `synchronous_commit` kept (it - // was `layerfs store update pg --auth pg`, whose write cleaned the URL, - // before the e0aa26e149 Decision) - let fix = "layerfs store disconnect pg && layerfs store connect pg --auth --synchronous-commit local"; - assert_eq!(got.get_text("fix"), Some(fix)); - // the doctor reports the record outdated, with the same fix (area 15) - let report = ok(&home, "store.doctor", &[("store", t("pg"))]); - assert_eq!(report.get("ok"), Some(&SdkValue::Bool(false)), "{report:?}"); - let found = match report.get("findings") { - Some(SdkValue::List(found)) => found.clone(), - _ => panic!("findings: {report:?}"), - }; - let record = (found.iter()) - .find(|f| f.get_text("check") == Some("store.record")) - .unwrap_or_else(|| panic!("{report:?}")); - assert_eq!(record.get_text("fix"), Some(fix)); - // `store update --auth` refuses it and writes nothing - let before = std::fs::read(paths::store_record(&home, "pg")).unwrap(); - let args = SdkValue::map([("store", t("pg")), ("auth", t("pg"))]); - let refused = layerfs_api::call(Some(&home), "store.update", args, &mut |_| {}).unwrap_err(); - assert_eq!(refused.code, "InvalidInput", "{}", refused.message); - assert_eq!( - refused.detail.get_text("fix"), - Some("layerfs store disconnect pg && layerfs store connect pg --auth pg --synchronous-commit local") - ); - let after = std::fs::read(paths::store_record(&home, "pg")).unwrap(); - assert_eq!(before, after, "a refused update wrote the record"); - // the fix, each step as the call guide takes it - ok(&home, "store.disconnect", &[("store", t("pg"))]); - ok( - &home, - "store.connect", - &[ - ("store", t("pg")), - ("url", t(&server.url)), - ("auth", t("pg")), - ("synchronous_commit", t("local")), - ], - ); - let got = ok(&home, "store.get", &[("store", t("pg"))]); - assert_eq!(got.get_text("state"), Some("ready"), "{got:?}"); - let text = std::fs::read_to_string(paths::store_record(&home, "pg")).unwrap(); - for gone in ["password", "checked", &format!("{}@", server.user)] { - assert!(!text.contains(gone), "{gone}: {text}"); - } - - // a login the home does not hold: `missing`, with the save that names it - edit(&home, "pg", |record| { - home::with_field(record, "auth", t("gone")) - }); - let got = ok(&home, "store.get", &[("store", t("pg"))]); - assert_eq!(got.get_text("reason"), Some("missing"), "{got:?}"); - assert!( - got.get_text("fix") - .unwrap() - .starts_with("layerfs store save-auth gone --user"), - "{got:?}" - ); - edit(&home, "pg", |record| { - home::with_field(record, "auth", t("pg")) - }); - ok(&home, "store.disconnect", &[("store", t("pg"))]); - std::fs::remove_dir_all(home).unwrap(); -} - -#[test] -fn an_update_racing_a_login_removal_never_names_a_removed_login() { - let Some(server) = server() else { return }; - let _one = ONE.lock().unwrap_or_else(|e| e.into_inner()); - let home = tempdir("race"); - home::open(&home).unwrap(); - save(&home, &server, "pg"); - ok( - &home, - "store.connect", - &[ - ("store", t("pg")), - ("url", t(&server.url)), - ("auth", t("pg")), - ], - ); - for round in 0..8 { - let next = format!("next-{round}"); - save(&home, &server, &next); - let (updated, removed) = std::thread::scope(|scope| { - let update = scope.spawn(|| { - call_as( - &home, - "store.update", - &[("store", t("pg")), ("auth", t(&next))], - true, - ) - }); - let remove = - scope.spawn(|| call_as(&home, "store.remove_auth", &[("auth", t(&next))], true)); - (update.join().unwrap(), remove.join().unwrap()) - }); - assert!( - updated.is_ok() != removed.is_ok(), - "round {round}: update {updated:?}, remove {removed:?}" - ); - let got = ok(&home, "store.get", &[("store", t("pg"))]); - assert_eq!( - got.get_text("state"), - Some("ready"), - "round {round}: {got:?}" - ); - if updated.is_err() { - assert_eq!(got.get_text("auth"), Some("pg")); - } else { - // it names `next`, which stays: put the Store back on `pg` - ok( - &home, - "store.update", - &[("store", t("pg")), ("auth", t("pg"))], - ); - ok(&home, "store.remove_auth", &[("auth", t(&next))]); - } - } - ok(&home, "store.disconnect", &[("store", t("pg"))]); - std::fs::remove_dir_all(home).unwrap(); -} diff --git a/api/crates/layerfs-api/tests/postgres_login.rs b/api/crates/layerfs-api/tests/postgres_login.rs new file mode 100644 index 0000000000..2dffac5f45 --- /dev/null +++ b/api/crates/layerfs-api/tests/postgres_login.rs @@ -0,0 +1,393 @@ +//! A PostgreSQL Store's URL and login, saved on this computer only (owner, +//! 2026-11-24), against a real server: a first connect checks the login +//! before anything is saved and keeps the password in the home's secret +//! folder, never in a record or an answer; a connect of the connected Store +//! changes its address, user, password or `synchronous_commit`, keeping +//! what it is not given, and is refused (nothing written) when the new +//! values reach another Store; `store.get` and `store.list` answer the +//! address, user, password times and attached machines; `store.doctor` +//! checks from this computer, then from each attached machine, and not +//! from them when this computer was not let in. Needs +//! LAYERFS_TEST_POSTGRES_URL (an admin URL of a trust-auth server, in +//! postgres:// form); each test makes and drops its own databases. +use layerfs_api::home::{self, paths}; +use layerfs_bridge::control::SdkValue; +use std::path::{Path, PathBuf}; + +fn tempdir(tag: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!("layerfs-pglogin-{tag}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + use std::os::unix::fs::PermissionsExt; + std::fs::set_permissions(&dir, std::fs::Permissions::from_mode(0o700)).unwrap(); + dir +} + +fn t(s: &str) -> SdkValue { + SdkValue::text(s) +} + +fn call(home: &Path, name: &str, args: &[(&str, SdkValue)]) -> Result { + let args = SdkValue::Map( + args.iter() + .map(|(n, v)| ((*n).to_owned(), v.clone())) + .collect(), + ); + layerfs_api::call(Some(home), name, args, &mut |_| {}).map_err(|r| (r.code, r.message)) +} + +fn ok(home: &Path, name: &str, args: &[(&str, SdkValue)]) -> SdkValue { + call(home, name, args).unwrap_or_else(|e| panic!("{name}: {e:?}")) +} + +fn long(home: &Path, name: &str, args: &[(&str, SdkValue)]) -> SdkValue { + let mut args = args.to_vec(); + args.push(("detail", SdkValue::Bool(true))); + ok(home, name, &args) +} + +/// The test server's databases made here, dropped when the test ends. +struct Server { + admin: String, + user: String, + /// `postgresql://host:port`, no user. + base: String, + made: Vec, +} + +impl Server { + fn new() -> Option { + let Ok(admin) = std::env::var("LAYERFS_TEST_POSTGRES_URL") else { + eprintln!("NOT_RUN: LAYERFS_TEST_POSTGRES_URL unset"); + return None; + }; + let config: postgres::Config = admin.parse().unwrap(); + let user = config.get_user().unwrap_or("postgres").to_owned(); + let host = match config.get_hosts().first() { + Some(postgres::config::Host::Tcp(host)) => host.clone(), + other => panic!("a TCP test server: {other:?}"), + }; + let port = config.get_ports().first().copied().unwrap_or(5432); + Some(Self { + admin, + user, + base: format!("postgresql://{host}:{port}"), + made: Vec::new(), + }) + } + + /// A new empty database's address, no user and no password. + fn database(&mut self, tag: &str) -> String { + let name = format!("pglogin_{tag}_{}", std::process::id()); + let mut client = postgres::Client::connect(&self.admin, postgres::NoTls).unwrap(); + for sql in [ + format!("DROP DATABASE IF EXISTS {name} WITH (FORCE)"), + format!("CREATE DATABASE {name}"), + ] { + client.batch_execute(&sql).unwrap(); + } + self.made.push(name.clone()); + format!("{}/{name}?sslmode=disable", self.base) + } +} + +impl Drop for Server { + fn drop(&mut self) { + if let Ok(mut client) = postgres::Client::connect(&self.admin, postgres::NoTls) { + for name in &self.made { + let _ = + client.batch_execute(&format!("DROP DATABASE IF EXISTS {name} WITH (FORCE)")); + } + } + } +} + +/// Every file under `dir`, with its text. +fn texts(dir: &Path, out: &mut Vec<(PathBuf, String)>) { + for entry in std::fs::read_dir(dir).unwrap() { + let path = entry.unwrap().path(); + if path.is_dir() { + texts(&path, out); + } else { + out.push(( + path.clone(), + String::from_utf8_lossy(&std::fs::read(&path).unwrap()).into(), + )); + } + } +} + +/// The saved password's file of Store `store`. +fn password_file(home: &Path, store: &str) -> Option { + let dir = layerfs_api::home::secrets::dir(home).join("login"); + let found = std::fs::read_dir(dir).ok()?; + found + .map(|entry| entry.unwrap().path()) + .find(|path| path.file_stem().is_some_and(|stem| stem == store)) +} + +#[test] +fn connect_checks_and_saves_the_login_and_a_reconnect_keeps_what_it_is_not_given() { + let Some(mut server) = Server::new() else { + return; + }; + let url = server.database("a"); + let other = server.database("b"); + let empty_db = server.database("c"); + let user = server.user.clone(); + let home = tempdir("connect"); + home::open(&home).unwrap(); + // a login the server refuses is never saved: here a user it does not + // know (a trust-auth server takes any password) + let (code, _) = call( + &home, + "store.connect", + &[ + ("store", t("pg")), + ("url", t(&url)), + ("user", t("layerfs_no_such_role")), + ("password", t("first-secret")), + ], + ) + .unwrap_err(); + assert_ne!(code, "InvalidInput"); + assert!(!paths::store_dir(&home, "pg").exists()); + assert!(password_file(&home, "pg").is_none()); + let connected = long( + &home, + "store.connect", + &[ + ("store", t("pg")), + ("url", t(&url)), + ("user", t(&user)), + ("password", t("first-secret")), + ], + ); + assert_eq!( + layerfs_api::json::print(&connected), + format!( + r#"{{"ok":true,"projects":[],"projects_count":null,"outcome":"connected","store":"pg","engine":"postgresql","url":"{url}","user":"{user}","synchronous_commit":"local","machines":[]}}"# + ) + ); + let file = password_file(&home, "pg").expect("the password is saved"); + // its own Store's binding in a second database: the same data cannot be + // connected twice, and another Store's schema is never this one's + ok( + &home, + "store.connect", + &[ + ("store", t("other")), + ("url", t(&other)), + ("user", t(&user)), + ("password", t("x")), + ], + ); + let got = long(&home, "store.get", &[("store", t("pg"))]); + let changed_at = got.get_text("password_changed_at").unwrap().to_owned(); + assert_eq!(got.get_text("url"), Some(url.as_str())); + assert_eq!(got.get_text("user"), Some(user.as_str())); + assert_eq!(got.get("password_saved"), Some(&SdkValue::Bool(true))); + assert_eq!(got.get_text("synchronous_commit"), Some("local")); + assert_eq!(got.get("machines"), Some(&SdkValue::List(vec![]))); + assert!(got.get("auth").is_none() && got.get("connections").is_none()); + // a reconnect with the setting alone keeps the user and password + let updated = long( + &home, + "store.connect", + &[ + ("store", t("pg")), + ("url", t(&url)), + ("synchronous_commit", t("on")), + ], + ); + assert_eq!(updated.get_text("outcome"), Some("updated")); + assert_eq!(updated.get_text("synchronous_commit"), Some("on")); + assert_eq!(updated.get_text("user"), Some(user.as_str())); + let got = long(&home, "store.get", &[("store", t("pg"))]); + assert_eq!( + got.get_text("password_changed_at"), + Some(changed_at.as_str()) + ); + let first = std::fs::read(&file).unwrap(); + // a new password is saved + long( + &home, + "store.connect", + &[ + ("store", t("pg")), + ("url", t(&url)), + ("password", t("second-secret")), + ], + ); + assert_ne!(std::fs::read(&file).unwrap(), first); + // (`password_changed_at` is whole seconds: the file says it changed) + let got = long(&home, "store.get", &[("store", t("pg"))]); + assert!(got.get_text("password_changed_at").is_some(), "{got:?}"); + // new values that reach another Store, or no Store at all, are refused + // and nothing is written + let record = || std::fs::read(paths::store_record(&home, "pg")).unwrap(); + let before = (record(), std::fs::read(&file).unwrap()); + for (address, why) in [(&other, "holds another Store than pg"), (&empty_db, "")] { + let (code, message) = call( + &home, + "store.connect", + &[ + ("store", t("pg")), + ("url", t(address)), + ("password", t("third-secret")), + ], + ) + .unwrap_err(); + assert_ne!(code, "InvalidInput", "{message}"); + assert!(message.contains(why), "{message}"); + assert_eq!((record(), std::fs::read(&file).unwrap()), before); + } + // a URL holding a login is refused on a connected Store too + let (code, _) = call( + &home, + "store.connect", + &[ + ("store", t("pg")), + ("url", t(&url.replacen("://", &format!("://{user}@"), 1))), + ], + ) + .unwrap_err(); + assert_eq!(code, "InvalidInput"); + assert_eq!(record(), before.0); + // no password outside its secret file + let mut files = Vec::new(); + texts(&home, &mut files); + for (path, text) in &files { + if path.starts_with(layerfs_api::home::secrets::dir(&home)) { + continue; + } + for secret in ["first-secret", "second-secret", "third-secret"] { + assert!(!text.contains(secret), "{secret} in {}", path.display()); + } + } + // `store.list`: the user and the machines' names, no saved-login name + let listed = ok(&home, "store.list", &[]); + let Some(SdkValue::List(items)) = listed.get("items") else { + panic!("{listed:?}"); + }; + let pg = (items.iter()) + .find(|item| item.get_text("store") == Some("pg")) + .unwrap(); + assert_eq!(pg.get_text("user"), Some(user.as_str()), "{pg:?}"); + assert!(pg.get("auth").is_none(), "{pg:?}"); + // disconnect forgets the password; the data stays for the next connect + ok(&home, "store.disconnect", &[("store", t("pg"))]); + assert!(!file.exists()); + let again = long( + &home, + "store.connect", + &[ + ("store", t("pg")), + ("url", t(&url)), + ("user", t(&user)), + ("password", t("x")), + ], + ); + assert_eq!(again.get_text("outcome"), Some("connected")); + std::fs::remove_dir_all(&home).unwrap(); +} + +/// The doctor checks from this computer, then from each attached machine +/// (here a stopped lima machine, which waits), or from `--machine` alone; +/// when this computer is not let in, no machine is checked. `store.get` +/// answers each attached machine as a row with its reach. +#[cfg(feature = "machine")] +#[test] +fn the_doctor_checks_attached_machines_only_after_this_computer() { + let Some(mut server) = Server::new() else { + return; + }; + let url = server.database("doctor"); + let user = server.user.clone(); + let home = tempdir("doctor"); + home::open(&home).unwrap(); + ok(&home, "machine.list", &[]); + ok( + &home, + "store.connect", + &[ + ("store", t("pg")), + ("url", t(&url)), + ("user", t(&user)), + ("password", t("pw")), + ], + ); + for name in ["dev", "lab"] { + home::write_record( + &paths::machine_record(&home, name), + &SdkValue::map([ + ("name", t(name)), + ("platform", t("lima")), + ("vm_name", t(&format!("layerfs-test-{name}"))), + ]), + ) + .unwrap(); + } + // attached as `store.attach` records them + let path = paths::store_record(&home, "pg"); + let record = home::read_record(&path).unwrap().unwrap(); + let attached = SdkValue::List(vec![t("dev"), t("lab")]); + home::write_record(&path, &home::with_field(record, "attached", attached)).unwrap(); + // the machines `store.connection` was checked from (the tree's rows) + let froms = |report: &SdkValue| { + let checks = report.get("tree").and_then(|tree| tree.get("checks")); + let Some(SdkValue::List(rows)) = checks else { + panic!("{report:?}"); + }; + let from = rows + .iter() + .filter(|row| row.get_text("check") == Some("store.connection")); + let mut found: Vec = from + .filter_map(|row| row.get_text("from").map(str::to_owned)) + .collect(); + found.sort(); + found + }; + let report = long(&home, "store.doctor", &[("store", t("pg"))]); + assert_eq!(froms(&report), ["dev", "lab"], "{report:?}"); + let report = long( + &home, + "store.doctor", + &[("store", t("pg")), ("machine", t("lab"))], + ); + assert_eq!(froms(&report), ["lab"], "{report:?}"); + // `native` is this computer, checked anyway + let report = long( + &home, + "store.doctor", + &[("store", t("pg")), ("machine", t("native"))], + ); + assert_eq!(froms(&report), Vec::::new(), "{report:?}"); + let got = long(&home, "store.get", &[("store", t("pg"))]); + let reach = got.get("reach").unwrap(); + assert_eq!(reach.get("ok"), Some(&SdkValue::Bool(true)), "{got:?}"); + assert!(reach.get_int("latency_ms").is_some(), "{got:?}"); + let Some(SdkValue::List(rows)) = got.get("machines") else { + panic!("{got:?}"); + }; + let names: Vec<_> = rows.iter().map(|row| row.get_text("machine")).collect(); + assert_eq!(names, [Some("dev"), Some("lab")]); + assert!( + rows.iter().all(|row| row.get("reach").is_some()), + "{rows:?}" + ); + let listed = ok(&home, "store.list", &[("detail", SdkValue::Bool(true))]); + let Some(SdkValue::List(items)) = listed.get("items") else { + panic!("{listed:?}"); + }; + assert_eq!( + items[0].get("machines"), + Some(&SdkValue::List(vec![t("dev"), t("lab")])) + ); + // this computer not let in (its password forgotten): no machine is + // checked, since each would only repeat it + std::fs::remove_file(password_file(&home, "pg").unwrap()).unwrap(); + let report = long(&home, "store.doctor", &[("store", t("pg"))]); + assert_eq!(froms(&report), Vec::::new(), "{report:?}"); + std::fs::remove_dir_all(&home).unwrap(); +} diff --git a/api/crates/layerfs-api/tests/postgres_refusals.rs b/api/crates/layerfs-api/tests/postgres_refusals.rs index 371fb94123..2575db1436 100644 --- a/api/crates/layerfs-api/tests/postgres_refusals.rs +++ b/api/crates/layerfs-api/tests/postgres_refusals.rs @@ -1,13 +1,17 @@ -//! PostgreSQL Store calls that need no PostgreSQL server (call surface 2.0, -//! `pg.html`): saved logins live in the home's secret folder (0600 files in -//! a 0700 folder), are never answered or logged, and are removed only when -//! no Store names them; `store.connect` refuses a URL with a user or a -//! password, a first connect without `--auth` and a connected Store's -//! `--auth`; `store.disconnect` refuses `InUse` while another process holds -//! the Store. The URLs name 127.0.0.1 port 1, where nothing listens, so a +//! PostgreSQL Store calls that need no PostgreSQL server (owner, +//! 2026-11-24): `store.connect` refuses a URL with a user or a password, a +//! new Store without its user or password, and a connected Store with no +//! user or saved password to dial with, before anything is dialled or +//! written; `store.disconnect` +//! refuses `InUse` while another process holds the Store and forgets its +//! saved password; `store.attach` and `store.detach` refuse a sqlite +//! Store, `native`, a missing machine, a loopback URL a machine does not +//! share and a detach while a Sandbox runs there; `store.doctor --machine` +//! refuses a machine that is not attached. The removed calls are gone from +//! the table. The URLs name 127.0.0.1 port 1, where nothing listens, so a //! request would fail with another code. use layerfs_api::home::{self, paths, write_record}; -use layerfs_bridge::control::SdkValue; +use layerfs_bridge::control::{SdkRefusal, SdkValue}; use std::os::unix::fs::PermissionsExt; use std::path::{Path, PathBuf}; @@ -23,6 +27,15 @@ fn t(s: &str) -> SdkValue { SdkValue::text(s) } +fn refusal(home: &Path, name: &str, args: &[(&str, SdkValue)]) -> SdkRefusal { + let args = SdkValue::Map( + args.iter() + .map(|(n, v)| ((*n).to_owned(), v.clone())) + .collect(), + ); + layerfs_api::call(Some(home), name, args, &mut |_| {}).unwrap_err() +} + fn call(home: &Path, name: &str, args: &[(&str, SdkValue)]) -> Result { let args = SdkValue::Map( args.iter() @@ -36,193 +49,75 @@ fn ok(home: &Path, name: &str, args: &[(&str, SdkValue)]) -> SdkValue { call(home, name, args).unwrap_or_else(|e| panic!("{name}: {e:?}")) } -fn code(home: &Path, name: &str, args: &[(&str, SdkValue)]) -> String { - call(home, name, args).unwrap_err().0 -} - fn mode(path: &Path) -> u32 { std::fs::metadata(path).unwrap().permissions().mode() & 0o777 } -/// Every file under `dir`, with its text. -fn texts(dir: &Path, out: &mut Vec<(PathBuf, String)>) { - for entry in std::fs::read_dir(dir).unwrap() { - let path = entry.unwrap().path(); - if path.is_dir() { - texts(&path, out); - } else { - out.push(( - path.clone(), - String::from_utf8_lossy(&std::fs::read(&path).unwrap()).into(), - )); - } - } -} - -/// Records PostgreSQL Store `name` at `url` (port 1: nothing listens), -/// naming login `auth` when given. -fn connected(home: &Path, name: &str, url: &str, auth: Option<&str>) { +/// Records PostgreSQL Store `name` at `url` (port 1: nothing listens) as +/// `store.connect` writes it, user `app`, with `extra` fields; its +/// password is saved when `password`. +fn connected(home: &Path, name: &str, url: &str, extra: &[(&str, SdkValue)], password: bool) { let mut fields = vec![ ("name", t(name)), ("kind", t("postgresql")), ("url", t(url)), + ("user", t("app")), ("schema", t("layerfs")), ("synchronous_commit", t("off")), ("binding", SdkValue::Bytes(vec![7; 32])), ("cursor", SdkValue::Bytes(vec![9; 32])), ]; - if let Some(auth) = auth { - fields.push(("auth", t(auth))); - } + fields.extend(extra.iter().cloned()); let fields = fields.into_iter().map(|(k, v)| (k.to_owned(), v)).collect(); write_record(&paths::store_record(home, name), &SdkValue::Map(fields)).unwrap(); + if password { + layerfs_store::postgresql::login::save(home, name, "hunter2-secret").unwrap(); + } } -#[test] -fn a_login_is_saved_privately_listed_without_its_password_and_removed_when_unused() { - let home = tempdir("logins"); - home::open(&home).unwrap(); - let saved = ok( - &home, - "store.save_auth", - &[ - ("auth", t("pg-app")), - ("user", t("app")), - ("password", t("hunter2-secret")), - ], - ); - assert_eq!(layerfs_api::json::print(&saved), r#"{"ok":true}"#); - let file = home.join("secret").join("auth").join("pg-app.json"); - assert_eq!(mode(&file), 0o600); - assert_eq!(mode(file.parent().unwrap()), 0o700); - assert_eq!(mode(&home.join("secret")), 0o700); - // a Store names it; the list says so, never with the password - connected( - &home, - "shop", - "postgresql://127.0.0.1:1/shop", - Some("pg-app"), - ); - let listed = ok(&home, "store.auths", &[]); - assert_eq!( - layerfs_api::json::print(&listed), - r#"{"items":[{"auth":"pg-app","user":"app","stores":["shop"]}]}"# - ); - let long = ok(&home, "store.auths", &[("detail", SdkValue::Bool(true))]); - let item = &match long.get("items") { - Some(SdkValue::List(items)) => items.clone(), - other => panic!("{other:?}"), - }[0]; - assert!( - item.get_text("created_at") - .is_some_and(|at| at.ends_with('Z')), - "{item:?}" - ); - // saving again rotates it: the answer says so, the creation time stays - let rotated = ok( - &home, - "store.save_auth", - &[ - ("auth", t("pg-app")), - ("user", t("app2")), - ("password", t("second-secret")), - ("detail", SdkValue::Bool(true)), - ], - ); - assert_eq!(rotated.get_text("outcome"), Some("rotated")); - assert_eq!(rotated.get_text("user"), Some("app2")); - assert_eq!( - rotated.get("stores"), - Some(&SdkValue::List(vec![t("shop")])) - ); - // no password outside the secret file: not in a record, not in the log - let mut files = Vec::new(); - texts(&home, &mut files); - for (path, text) in &files { - if *path != file { - assert!( - !text.contains("hunter2-secret") && !text.contains("second-secret"), - "{path:?}" - ); - } - } - // required and checked - assert_eq!( - code( - &home, - "store.save_auth", - &[("auth", t("x")), ("password", t("p"))] - ), - "InvalidInput" - ); - assert_eq!( - code( - &home, - "store.save_auth", - &[("auth", t("x")), ("user", t("u"))] - ), - "InvalidInput" - ); - assert_eq!( - code( - &home, - "store.save_auth", - &[ - ("auth", t("Bad/Name")), - ("user", t("u")), - ("password", t("p")) - ] - ), - "InvalidInput" - ); - // removal: refused while a Store names it, listing the Stores - let refused = layerfs_api::call( - Some(&home), - "store.remove_auth", - SdkValue::map([("auth", t("pg-app"))]), - &mut |_| {}, +/// A machine record of `platform` (nothing runs). +fn machine(home: &Path, name: &str, platform: &str) { + write_record( + &paths::machine_record(home, name), + &SdkValue::map([ + ("name", t(name)), + ("platform", t(platform)), + ("vm_name", t(&format!("layerfs-test-{name}"))), + ]), ) - .unwrap_err(); - assert_eq!(refused.code, "InUse", "{}", refused.message); - assert!(refused.message.contains("shop"), "{}", refused.message); - std::fs::remove_dir_all(paths::store_dir(&home, "shop")).unwrap(); - let removed = ok( - &home, - "store.remove_auth", - &[("auth", t("pg-app")), ("detail", SdkValue::Bool(true))], - ); - assert_eq!(removed.get_text("outcome"), Some("removed")); - assert!(!file.exists()); - assert_eq!( - code(&home, "store.remove_auth", &[("auth", t("pg-app"))]), - "NotFound" - ); - assert_eq!( - layerfs_api::json::print(&ok(&home, "store.auths", &[])), - r#"{"items":[]}"# - ); - let _ = std::fs::remove_dir_all(home); + .unwrap(); +} + +/// Sandbox `sandbox` of project `project`, on machine `machine`, as its +/// record keeps it (nothing runs). +fn sandbox_on(home: &Path, sandbox: &str, project: &str, machine: &str) { + write_record( + &paths::sandbox_record(home, sandbox), + &SdkValue::map([ + ("v", SdkValue::Int(1)), + ("name", t(sandbox)), + ("project", t(project)), + ("machine", t(machine)), + ("created", SdkValue::Int(1)), + ("id", t(sandbox)), + ("platform", t("lima")), + ("runtime", t("namespaces")), + ("backend", t("namespaces")), + ]), + ) + .unwrap(); } #[test] -fn connect_refuses_a_login_in_the_url_a_missing_auth_and_a_settings_change() { +fn connect_refuses_a_login_in_the_url_and_a_missing_login() { let home = tempdir("connect"); home::open(&home).unwrap(); - ok( - &home, - "store.save_auth", - &[ - ("auth", t("pg-app")), - ("user", t("app")), - ("password", t("secret")), - ], - ); let connect = |store: &str, url: &str, more: &[(&str, SdkValue)]| { let mut args = vec![("store", t(store)), ("url", t(url))]; args.extend(more.iter().cloned()); call(&home, "store.connect", &args) }; - let auth = [("auth", t("pg-app"))]; + let login = [("user", t("app")), ("password", t("secret"))]; for url in [ "postgresql://alice:secret@127.0.0.1:1/app", "postgresql://alice@127.0.0.1:1/app", @@ -236,7 +131,7 @@ fn connect_refuses_a_login_in_the_url_a_missing_auth_and_a_settings_change() { "postgresql://127.0.0.1:1/app?passfile=/home/a/.pgpass", "postgresql://127.0.0.1:1/app?sslmode=require&PassFile=%2Ftmp%2Fp", ] { - let refused = connect("pg", url, &auth).unwrap_err(); + let refused = connect("pg", url, &login).unwrap_err(); assert_eq!(refused.0, "InvalidInput", "{url}: {refused:?}"); assert!( refused.1.contains("user or holds a password"), @@ -245,113 +140,98 @@ fn connect_refuses_a_login_in_the_url_a_missing_auth_and_a_settings_change() { assert!(!paths::store_dir(&home, "pg").exists(), "{url}"); } let url = "postgresql://127.0.0.1:1/app"; - // a first connect needs a saved login - let refused = connect("pg", url, &[]).unwrap_err(); - assert_eq!(refused.0, "InvalidInput", "{refused:?}"); - assert!(refused.1.contains("--auth"), "{refused:?}"); - assert_eq!( - connect("pg", url, &[("auth", t("nobody"))]).unwrap_err().0, - "NotFound" - ); - // a Store not connected yet takes no machine's address - let refused = connect("pg", url, &[("auth", t("pg-app")), ("machine", t("lab"))]).unwrap_err(); - assert_eq!(refused.0, "InvalidInput", "{refused:?}"); - assert!(!paths::store_dir(&home, "pg").exists()); - // a connected Store: an address only, never a login or the setting - connected(&home, "pg", url, Some("pg-app")); - let before = std::fs::read(paths::store_record(&home, "pg")).unwrap(); - for (more, said) in [ - (&auth[..], "--auth"), - ( - &[("synchronous_commit", t("on"))][..], - "--synchronous-commit", - ), + // a new Store needs its user and password, neither empty + for more in [ + vec![], + vec![("user", t("app"))], + vec![("password", t("secret"))], + vec![("user", t("")), ("password", t("secret"))], + vec![("user", t("app")), ("password", t(""))], ] { - let refused = connect("pg", url, more).unwrap_err(); - assert_eq!(refused.0, "InvalidInput", "{refused:?}"); - assert!(refused.1.contains(said), "{refused:?}"); + let refused = connect("pg", url, &more).unwrap_err(); + assert_eq!(refused.0, "InvalidInput", "{more:?}: {refused:?}"); + assert!(!paths::store_dir(&home, "pg").exists()); } - let refused = connect("pg", url, &[("auth", t("pg-app")), ("machine", t("lab"))]).unwrap_err(); - assert_eq!( - refused, - ( - "InvalidInput".to_owned(), - "a machine's own connection takes no --auth; pg uses pg-app".to_owned() - ) + let refused = connect("pg", url, &[]).unwrap_err(); + assert!( + refused.1.contains("--user --password-stdin"), + "{refused:?}" ); + let mut sometimes = login.to_vec(); + sometimes.push(("synchronous_commit", t("sometimes"))); assert_eq!( - before, - std::fs::read(paths::store_record(&home, "pg")).unwrap() + connect("pg", url, &sometimes).unwrap_err().0, + "InvalidInput" ); + // the removed options are unknown + for removed in [("auth", t("pg")), ("machine", t("lab"))] { + let mut args = login.to_vec(); + args.push(removed.clone()); + assert_eq!( + connect("pg", url, &args).unwrap_err().0, + "InvalidInput", + "{removed:?}" + ); + } + // a connected Store whose password is not saved needs one given + connected(&home, "pg", url, &[], false); + let refused = connect("pg", url, &[]).unwrap_err(); + assert_eq!(refused.0, "InvalidInput", "{refused:?}"); + assert!(refused.1.contains("--password-stdin"), "{refused:?}"); + // a connected record naming no user needs one given; nothing is written + connected(&home, "nameless", url, &[], true); + let path = paths::store_record(&home, "nameless"); + let record = home::read_record(&path).unwrap().unwrap(); + let SdkValue::Map(fields) = record else { + panic!("a map"); + }; + let fields = fields.into_iter().filter(|(k, _)| k != "user").collect(); + write_record(&path, &SdkValue::Map(fields)).unwrap(); + let before = std::fs::read(&path).unwrap(); + let refused = connect("nameless", url, &[]).unwrap_err(); + assert_eq!(refused.0, "InvalidInput", "{refused:?}"); + assert!(refused.1.contains("--user"), "{refused:?}"); + assert_eq!(before, std::fs::read(&path).unwrap()); + let listed = ok(&home, "store.list", &[("detail", SdkValue::Bool(true))]); + let printed = layerfs_api::json::print(&listed); + assert!(!printed.contains("\"auth\""), "{printed}"); // a sqlite Store of the name exists write_record( &paths::store_record(&home, "lite"), &SdkValue::map([("name", t("lite")), ("kind", t("sqlite"))]), ) .unwrap(); - assert_eq!(connect("lite", url, &auth).unwrap_err().0, "Exists"); - // update: one of the two is required, a login must be saved; disconnect - // of a machine with no own address is NotFound; a sqlite Store refuses - assert_eq!( - code(&home, "store.update", &[("store", t("pg"))]), - "InvalidInput" - ); - assert_eq!( - code( - &home, - "store.update", - &[("store", t("pg")), ("auth", t("nobody"))] - ), - "NotFound" - ); - assert_eq!( - code( - &home, - "store.update", - &[("store", t("pg")), ("synchronous_commit", t("sometimes"))] - ), - "InvalidInput" - ); - assert_eq!( - code( - &home, - "store.update", - &[("store", t("lite")), ("auth", t("pg-app"))] - ), - "InvalidInput" - ); - let updated = ok( - &home, - "store.update", - &[ - ("store", t("pg")), - ("synchronous_commit", t("on")), - ("detail", SdkValue::Bool(true)), - ], - ); - assert_eq!( - layerfs_api::json::print(&updated), - r#"{"ok":true,"outcome":"updated","store":"pg","auth":"pg-app","synchronous_commit":"on"}"# - ); - assert_eq!( - code( - &home, - "store.disconnect", - &[("store", t("pg")), ("machine", t("lab"))] - ), - "NotFound" - ); + assert_eq!(connect("lite", url, &login).unwrap_err().0, "Exists"); let refused = call(&home, "store.disconnect", &[("store", t("lite"))]).unwrap_err(); assert_eq!(refused.0, "InvalidInput"); assert!(refused.1.contains("store remove lite"), "{refused:?}"); + // the saved-login calls and store.update are gone + for removed in [ + "store.save_auth", + "store.auths", + "store.remove_auth", + "store.update", + ] { + let refused = refusal(&home, removed, &[("store", t("pg"))]); + assert_eq!(refused.code, "InvalidInput", "{removed}: {refused:?}"); + } let _ = std::fs::remove_dir_all(home); } #[test] -fn disconnect_refuses_a_postgresql_store_another_process_holds() { +fn disconnect_refuses_a_held_store_then_forgets_it_and_its_password() { let home = tempdir("held"); home::open(&home).unwrap(); - connected(&home, "pg", "postgresql://alice@127.0.0.1:1/app", None); + connected(&home, "pg", "postgresql://127.0.0.1:1/app", &[], true); + let secret = layerfs_api::home::secrets::dir(&home).join("login"); + let file = std::fs::read_dir(&secret) + .unwrap() + .next() + .unwrap() + .unwrap() + .path(); + assert_eq!(mode(&file), 0o600); + assert_eq!(mode(&secret), 0o700); // process 1 is always alive: its lease holds the Store let lease = paths::lease_dir(&home, "pg").join("1"); std::fs::create_dir_all(lease.parent().unwrap()).unwrap(); @@ -360,13 +240,24 @@ fn disconnect_refuses_a_postgresql_store_another_process_holds() { let (code, message) = call(&home, "store.disconnect", &args).unwrap_err(); assert_eq!(code, "InUse", "{message}"); assert!(paths::store_record(&home, "pg").is_file()); + assert!(file.is_file()); std::fs::remove_file(&lease).unwrap(); + // `machine` is no option of it any more + let mut with_machine = args.to_vec(); + with_machine.push(("machine", t("lab"))); + assert_eq!( + call(&home, "store.disconnect", &with_machine) + .unwrap_err() + .0, + "InvalidInput" + ); let done = ok(&home, "store.disconnect", &args); assert_eq!( layerfs_api::json::print(&done), - r#"{"ok":true,"outcome":"disconnected","store":"pg","machine":null}"# + r#"{"ok":true,"outcome":"disconnected","store":"pg"}"# ); assert!(!paths::store_dir(&home, "pg").exists()); + assert!(!file.exists(), "its password is forgotten"); let _ = std::fs::remove_dir_all(home); } @@ -379,21 +270,8 @@ fn a_postgresql_store_call_holds_the_stores_lease() { home::open(&home).unwrap(); let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); let port = listener.local_addr().unwrap().port(); - ok( - &home, - "store.save_auth", - &[ - ("auth", t("pg-app")), - ("user", t("alice")), - ("password", t("secret")), - ], - ); - connected( - &home, - "pg", - &format!("postgresql://127.0.0.1:{port}/app"), - Some("pg-app"), - ); + let url = format!("postgresql://127.0.0.1:{port}/app"); + connected(&home, "pg", &url, &[], true); write_record( &paths::project_record(&home, "pg", "app"), &SdkValue::map([("name", t("app"))]), @@ -424,26 +302,21 @@ fn a_postgresql_store_call_holds_the_stores_lease() { } /// The refusal of a URL carrying a login has a fix that gives the address -/// alone and names the login with `save-auth`/`--auth` (spec v23 V23-13, -/// LF11); a connected Store, which takes no `--auth` on connect, names it -/// with `store update --auth` first. The fix never carries the password. +/// alone and the login apart (spec v23 V23-13, LF11): always for a new +/// Store, which needs one; on a connected Store only when the URL may hold +/// one. The fix never carries the password. #[test] fn a_login_in_the_url_is_refused_with_the_address_alone_as_the_fix() { let home = tempdir("login-fix"); home::open(&home).unwrap(); - let refusal = |args: &[(&str, SdkValue)]| { - let args = SdkValue::Map( - args.iter() - .map(|(n, v)| ((*n).to_owned(), v.clone())) - .collect(), - ); - let refused = - layerfs_api::call(Some(&home), "store.connect", args, &mut |_| {}).unwrap_err(); + let fix = |args: &[(&str, SdkValue)]| { + let refused = refusal(&home, "store.connect", args); assert_eq!(refused.code, "InvalidInput", "{refused:?}"); let fix = refused.detail.get_text("fix").map(str::to_owned); fix.unwrap_or_else(|| panic!("no fix: {refused:?}")) }; - let first = refusal(&[ + let login = "layerfs store connect pg --user --password-stdin"; + let first = fix(&[ ("store", t("pg")), ( "url", @@ -452,147 +325,204 @@ fn a_login_in_the_url_is_refused_with_the_address_alone_as_the_fix() { ]); // the client does not read `passfile`: no form of the URL is shown, and // no user (`` and `` to fill in) - assert_eq!( - first, - "layerfs store save-auth --user --password-stdin && layerfs store connect pg --auth " - ); - let no_user = refusal(&[ + assert_eq!(first, login); + let no_user = fix(&[ ("store", t("pg")), ("url", t("postgresql://127.0.0.1:1/app?password=secret")), ]); - // a login is never cut out of a URL: the address is `` too (it - // was the URL without its `password` before the e0aa26e149 Decision) - assert_eq!( - no_user, - "layerfs store save-auth --user --password-stdin && layerfs store connect pg --auth " - ); - connected(&home, "pg", "postgresql://127.0.0.1:1/app", Some("pg-app")); - let readdress = refusal(&[ + assert_eq!(no_user, login); + connected(&home, "pg", "postgresql://127.0.0.1:1/app", &[], true); + let readdress = fix(&[ ("store", t("pg")), ("url", t("postgresql://127.0.0.1:2/app?sslpassword=secret")), ]); - // nor `sslpassword` - assert_eq!( - readdress, - "layerfs store save-auth --user --password-stdin && layerfs store update pg --auth && layerfs store connect pg " - ); + assert_eq!(readdress, login); // a URL that is not a PostgreSQL one is refused with no fix (a fix would - // repeat its login); a login after a `#` is never cut out (the fix named - // the client's database `app#x` with its `#` written `%23` before the - // e0aa26e149 Decision) - let args = SdkValue::map([ - ("store", t("pg2")), - ("url", t("postgresq://alice:secret@127.0.0.1:1/app")), - ]); - let bad = layerfs_api::call(Some(&home), "store.connect", args, &mut |_| {}).unwrap_err(); + // repeat its login) + let bad = refusal( + &home, + "store.connect", + &[ + ("store", t("pg2")), + ("url", t("postgresq://alice:secret@127.0.0.1:1/app")), + ], + ); assert_eq!(bad.detail.get_text("fix"), None, "{bad:?}"); assert!(!format!("{bad:?}").contains("secret"), "{bad:?}"); - let fragment = refusal(&[ + let fragment = fix(&[ ("store", t("pg")), ("url", t("postgresql://127.0.0.1:2/app#x?password=secret")), ]); - assert!(fragment.ends_with("store connect pg "), "{fragment}"); - // every shape names the login path (V23-13) and never the password + assert_eq!(fragment, login); + // a `#` alone on a connected Store needs no login + let hash = fix(&[ + ("store", t("pg")), + ("url", t("postgresql://127.0.0.1:2/app#x")), + ]); + assert_eq!(hash, "layerfs store connect pg "); for fix in [&first, &no_user, &readdress, &fragment] { - assert!(fix.contains("save-auth") && fix.contains("--auth"), "{fix}"); assert!(!fix.contains("secret"), "{fix}"); } let _ = std::fs::remove_dir_all(home); } -/// An outdated record whose URL still holds a login never shows it in its -/// `connections` rows (spec v23 V23-3; conformance v23 F1), and a login file -/// that cannot be read is saved again by the fix its broken row gives -/// (V23-8; conformance v23 F2). +/// A record whose URL holds a login never shows it (spec v23 V23-3; +/// conformance v23 F1): `store.get` and `store.list` hide it whole. #[test] -fn an_old_url_login_is_never_shown_and_a_broken_login_file_is_saved_again() { +fn an_old_url_login_is_never_shown() { let home = tempdir("old-url"); home::open(&home).unwrap(); - connected( - &home, - "old", + for url in [ + // the client does not read `sslpassword` "postgresql://alice:hunter2@127.0.0.1:1/app?sslmode=disable&sslpassword=sekrit", - Some("pg-app"), - ); - // the client does not read `sslpassword`: the URL is hidden whole - let got = ok( - &home, - "store.get", - &[("store", t("old")), ("detail", SdkValue::Bool(true))], + // one the client reads is hidden whole too: no login is cut out + "postgresql://alice:hunter2@127.0.0.1:1/app?sslmode=disable&password=sekrit", + ] { + connected(&home, "old", url, &[], false); + let got = ok( + &home, + "store.get", + &[("store", t("old")), ("detail", SdkValue::Bool(true))], + ); + let shown = layerfs_api::json::print(&got); + assert!( + shown.contains("postgresql://"), + "{shown}" + ); + let listed = layerfs_api::json::print(&ok( + &home, + "store.list", + &[("detail", SdkValue::Bool(true))], + )); + for secret in ["hunter2", "sekrit", "alice", "127.0.0.1"] { + assert!(!shown.contains(secret), "{secret} in {shown}"); + assert!(!listed.contains(secret), "{secret} in {listed}"); + } + } + let _ = std::fs::remove_dir_all(home); +} + +/// `store.attach` and `store.detach` refuse what is not theirs before any +/// dial; a machine that does not share this host's loopback is refused a +/// loopback URL with the connect that fixes it; a detach is refused while +/// a Sandbox of the Store runs on the machine, and a machine not attached +/// is `NotFound`; `store.doctor --machine` names the attach for a machine +/// not attached. +#[cfg(feature = "machine")] +#[test] +fn attach_and_detach_refuse_what_is_not_theirs() { + let home = tempdir("attach"); + home::open(&home).unwrap(); + ok(&home, "machine.list", &[]); + let url = "postgresql://127.0.0.1:1/app"; + connected(&home, "pg", url, &[], true); + write_record( + &paths::store_record(&home, "lite"), + &SdkValue::map([("name", t("lite")), ("kind", t("sqlite"))]), + ) + .unwrap(); + machine(&home, "dev", "lima"); + let on = |store: &str, machine: &str| [("store", t(store)), ("machine", t(machine))]; + // `machine` is required + assert_eq!( + refusal(&home, "store.attach", &[("store", t("pg"))]).code, + "InvalidInput" ); - let shown = layerfs_api::json::print(&got); + let lite = refusal(&home, "store.attach", &on("lite", "dev")); + assert_eq!(lite.code, "InvalidInput", "{lite:?}"); assert!( - shown.contains("postgresql://"), - "{shown}" + lite.message.contains("layerfs store move lite dev"), + "{lite:?}" ); - for secret in ["hunter2", "sekrit", "127.0.0.1"] { - assert!(!shown.contains(secret), "{secret} in {shown}"); - } - // and `store.list` shows it hidden too - let listed = layerfs_api::json::print(&ok( - &home, - "store.list", - &[("detail", SdkValue::Bool(true))], - )); - assert!( - listed.contains("postgresql://"), - "{listed}" + assert_eq!( + refusal(&home, "store.attach", &on("nope", "dev")).code, + "NotFound" ); - for secret in ["hunter2", "sekrit", "127.0.0.1"] { - assert!(!listed.contains(secret), "{secret} in {listed}"); + let native = refusal(&home, "store.attach", &on("pg", "native")); + assert_eq!(native.code, "InvalidInput", "{native:?}"); + assert!(native.message.contains("this computer"), "{native:?}"); + assert_eq!( + refusal(&home, "store.attach", &on("pg", "ghost")).code, + "NotFound" + ); + // lima does not share this host's loopback on macOS: the Store is + // connected again with an address the machine reaches; nothing is + // recorded + let lima = layerfs_platform::sandbox_allowed( + layerfs_platform::Platform::Lima, + layerfs_platform::HostOs::current(), + layerfs_platform::StoreKind::Postgresql, + ); + let loopback = refusal(&home, "store.attach", &on("pg", "dev")); + match lima { + Ok(()) if cfg!(target_os = "macos") => { + assert_eq!(loopback.code, "Unsupported", "{loopback:?}"); + assert!( + loopback.message.contains("host.lima.internal") + && loopback + .message + .contains("`layerfs store connect pg `"), + "{loopback:?}" + ); + } + Ok(()) => {} + Err(reason) => assert!(loopback.message.ends_with(reason), "{loopback:?}"), } - // one the client reads is hidden whole too: no login is cut out of a - // URL (it showed its address without its login before the e0aa26e149 - // Decision) - connected( - &home, - "old", - "postgresql://alice:hunter2@127.0.0.1:1/app?sslmode=disable&password=sekrit", - Some("pg-app"), + let record = home::read_record(&paths::store_record(&home, "pg")) + .unwrap() + .unwrap(); + assert!(record.get("attached").is_none(), "{record:?}"); + // detach: not attached is NotFound + assert_eq!( + refusal(&home, "store.detach", &on("pg", "dev")).code, + "NotFound" ); - let got = ok( - &home, - "store.get", - &[("store", t("old")), ("detail", SdkValue::Bool(true))], + // doctor --machine of a machine not attached names the attach + let doctor = refusal(&home, "store.doctor", &on("pg", "dev")); + assert_eq!(doctor.code, "InvalidInput", "{doctor:?}"); + assert_eq!( + doctor.detail.get_text("fix"), + Some("layerfs store attach pg --machine dev") ); - let shown = layerfs_api::json::print(&got); + // attached (as `store.attach` records it), with a Sandbox of its + // project on the machine: the detach is refused, naming it + connected( + &home, + "pg", + url, + &[("attached", SdkValue::List(vec![t("dev")]))], + true, + ); + sandbox_on(&home, "s1", "pg/app", "dev"); + sandbox_on(&home, "s2", "lite/app", "dev"); + let held = refusal(&home, "store.detach", &on("pg", "dev")); + assert_eq!(held.code, "InUse", "{held:?}"); assert!( - shown.contains("postgresql://"), - "{shown}" + held.message + .starts_with("1 Sandbox(es) of Store pg's projects run on machine dev: s1"), + "{held:?}" ); - // no user, host or password of it is named - for secret in ["hunter2", "sekrit", "alice", "127.0.0.1"] { - assert!(!shown.contains(secret), "{secret} in {shown}"); - } - let listed = layerfs_api::json::print(&ok( - &home, - "store.list", - &[("detail", SdkValue::Bool(true))], - )); - for secret in ["hunter2", "sekrit", "alice", "127.0.0.1"] { - assert!(!listed.contains(secret), "{secret} in {listed}"); - } - let bad = layerfs_api::home::secrets::dir(&home).join("auth"); - std::fs::create_dir_all(&bad).unwrap(); - std::fs::set_permissions(&bad, std::fs::Permissions::from_mode(0o700)).unwrap(); - std::fs::write(bad.join("bad.json"), "{not json").unwrap(); - std::fs::set_permissions(bad.join("bad.json"), std::fs::Permissions::from_mode(0o600)).unwrap(); - let saved = ok( + assert_eq!( + held.detail.get_text("fix"), + Some("layerfs sandbox remove s1 && layerfs store detach pg --machine dev") + ); + std::fs::remove_dir_all(paths::sandbox_dir(&home, "s1")).unwrap(); + let detached = ok( &home, - "store.save_auth", + "store.detach", &[ - ("auth", t("bad")), - ("user", t("u")), - ("password", t("pw")), + ("store", t("pg")), + ("machine", t("dev")), ("detail", SdkValue::Bool(true)), ], ); - assert!( - layerfs_api::json::print(&saved).contains("bad"), - "{saved:?}" + assert_eq!( + layerfs_api::json::print(&detached), + r#"{"ok":true,"outcome":"detached","store":"pg","machine":"dev"}"# ); - let auths = layerfs_api::json::print(&ok(&home, "store.auths", &[])); - assert!(auths.contains("\"bad\""), "{auths}"); - assert!(!auths.contains("broken"), "{auths}"); + let record = home::read_record(&paths::store_record(&home, "pg")) + .unwrap() + .unwrap(); + assert!(record.get("attached").is_none(), "{record:?}"); let _ = std::fs::remove_dir_all(home); } diff --git a/api/crates/layerfs-api/tests/postgres_sandbox_reach.rs b/api/crates/layerfs-api/tests/postgres_sandbox_reach.rs index f96de1144c..bb24ae9dac 100644 --- a/api/crates/layerfs-api/tests/postgres_sandbox_reach.rs +++ b/api/crates/layerfs-api/tests/postgres_sandbox_reach.rs @@ -4,7 +4,7 @@ //! binding is another Store's is `Unavailable`, both as before. Needs //! LAYERFS_TEST_PG_URL (a server URL with its user and no password, to a //! database with no `layerfs` schema; the test leaves one behind) and -//! LAYERFS_TEST_PG_PASSWORD (saved as the Store's login); without them the +//! LAYERFS_TEST_PG_PASSWORD (the Store's password); without them the //! test says so and passes. #![cfg(feature = "machine")] use layerfs_api::home::{self, paths}; @@ -47,23 +47,14 @@ fn the_reach_check_finds_the_binding_and_the_project_on_one_session() { let (scheme, rest) = url.split_once("://").unwrap(); let (user, address) = rest.split_once('@').unwrap(); let password = std::env::var("LAYERFS_TEST_PG_PASSWORD").unwrap(); - call( - &home, - "store.save_auth", - &[ - ("auth", t("pg")), - ("user", t(user)), - ("password", t(&password)), - ], - ) - .unwrap(); call( &home, "store.connect", &[ ("store", t("pg")), ("url", t(&format!("{scheme}://{address}"))), - ("auth", t("pg")), + ("user", t(user)), + ("password", t(&password)), ], ) .unwrap(); diff --git a/api/crates/layerfs-api/tests/postgres_update.rs b/api/crates/layerfs-api/tests/postgres_update.rs deleted file mode 100644 index b4df970a24..0000000000 --- a/api/crates/layerfs-api/tests/postgres_update.rs +++ /dev/null @@ -1,190 +0,0 @@ -//! A PostgreSQL Store's addresses and login (call surface 2.0, `pg.html`): -//! `store.connect --machine` gives one machine its own address, proven from -//! that machine before it is saved (another database is refused, nothing -//! saved); `store.connect` without a machine replaces the address every -//! machine dials, proven from this computer; `store.update` changes the -//! saved login (checked on the Store's address) and `synchronous_commit`; -//! `store.disconnect --machine` removes a machine's own address. Needs -//! LAYERFS_TEST_PG_URL (a server URL with its user and no password, to a -//! database with no `layerfs` schema; the test leaves one behind) and -//! LAYERFS_TEST_PG_PASSWORD; without them it says so and passes. -#![cfg(feature = "machine")] -use layerfs_api::home::{self, paths}; -use layerfs_bridge::control::SdkValue; -use std::os::unix::fs::PermissionsExt; -use std::path::{Path, PathBuf}; - -fn tempdir(tag: &str) -> PathBuf { - let dir = std::env::temp_dir().join(format!("layerfs-pgupdate-{tag}-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&dir); - std::fs::create_dir_all(&dir).unwrap(); - std::fs::set_permissions(&dir, std::fs::Permissions::from_mode(0o700)).unwrap(); - dir -} - -fn t(s: &str) -> SdkValue { - SdkValue::text(s) -} - -fn call(home: &Path, name: &str, args: &[(&str, SdkValue)]) -> Result { - let mut args: Vec<(String, SdkValue)> = args - .iter() - .map(|(n, v)| ((*n).to_owned(), v.clone())) - .collect(); - args.push(("detail".to_owned(), SdkValue::Bool(true))); - layerfs_api::call(Some(home), name, SdkValue::Map(args), &mut |_| {}) - .map_err(|r| (r.code, r.message)) -} - -fn ok(home: &Path, name: &str, args: &[(&str, SdkValue)]) -> SdkValue { - call(home, name, args).unwrap_or_else(|e| panic!("{name}: {e:?}")) -} - -fn record_text(home: &Path, store: &str) -> String { - std::fs::read_to_string(paths::store_record(home, store)).unwrap() -} - -/// `(machine, url)` of each address an answer shows. -fn addresses(answer: &SdkValue) -> Vec<(Option, String)> { - let Some(SdkValue::List(rows)) = answer.get("connections") else { - panic!("connections: {answer:?}"); - }; - rows.iter() - .map(|row| { - let machine = row.get_text("machine").map(str::to_owned); - (machine, row.get_text("url").unwrap().to_owned()) - }) - .collect() -} - -#[test] -fn addresses_and_logins_are_proven_before_they_are_saved() { - let (Ok(url), Ok(password)) = ( - std::env::var("LAYERFS_TEST_PG_URL"), - std::env::var("LAYERFS_TEST_PG_PASSWORD"), - ) else { - eprintln!("NOT_RUN: LAYERFS_TEST_PG_URL / LAYERFS_TEST_PG_PASSWORD unset"); - return; - }; - let home = tempdir("live"); - home::open(&home).unwrap(); - let (scheme, rest) = url.split_once("://").unwrap(); - let (user, address) = rest.split_once('@').unwrap(); - let url = format!("{scheme}://{address}"); - for auth in ["pg", "pg-2"] { - ok( - &home, - "store.save_auth", - &[ - ("auth", t(auth)), - ("user", t(user)), - ("password", t(&password)), - ], - ); - } - let connected = ok( - &home, - "store.connect", - &[("store", t("pg")), ("url", t(&url)), ("auth", t("pg"))], - ); - assert_eq!(addresses(&connected), [(None, url.clone())]); - // native's own address: the same server, proven from native - let native = ok( - &home, - "store.connect", - &[ - ("store", t("pg")), - ("url", t(&url)), - ("machine", t("native")), - ], - ); - assert_eq!(native.get_text("outcome"), Some("updated")); - assert_eq!( - addresses(&native), - [ - (None, url.clone()), - (Some("native".to_owned()), url.clone()) - ] - ); - assert!(!record_text(&home, "pg").contains(&password)); - // another database is not this Store: refused, nothing saved, for the - // machine's address and for every machine's - let before = record_text(&home, "pg"); - let other = match url.rsplit_once('/') { - Some((server, _)) => format!("{server}/postgres"), - None => url.clone(), - }; - let (code, message) = call( - &home, - "store.connect", - &[ - ("store", t("pg")), - ("url", t(&other)), - ("machine", t("native")), - ], - ) - .unwrap_err(); - assert_eq!(code, "Unavailable", "{message}"); - assert!(message.contains("holds another Store than pg"), "{message}"); - assert!(!message.contains("cannot reach"), "{message}"); - let (code, message) = call( - &home, - "store.connect", - &[("store", t("pg")), ("url", t(&other))], - ) - .unwrap_err(); - assert!( - matches!(code.as_str(), "Unavailable" | "Failed"), - "{code}: {message}" - ); - assert_eq!(record_text(&home, "pg"), before); - // the address every machine dials, to the same database again: saved - let readdressed = ok( - &home, - "store.connect", - &[("store", t("pg")), ("url", t(&url))], - ); - assert_eq!(readdressed.get_text("outcome"), Some("updated")); - // another login with the same role, and the setting - let updated = ok( - &home, - "store.update", - &[ - ("store", t("pg")), - ("auth", t("pg-2")), - ("synchronous_commit", t("off")), - ], - ); - assert_eq!(updated.get_text("auth"), Some("pg-2")); - assert_eq!(updated.get_text("synchronous_commit"), Some("off")); - let got = ok(&home, "store.get", &[("store", t("pg"))]); - assert_eq!(got.get_text("auth"), Some("pg-2"), "{got:?}"); - // the login a Store uses cannot be removed; the other one can - assert_eq!( - call(&home, "store.remove_auth", &[("auth", t("pg-2"))]) - .unwrap_err() - .0, - "InUse" - ); - ok(&home, "store.remove_auth", &[("auth", t("pg"))]); - // native's own address removed: it dials the Store's again - let removed = ok( - &home, - "store.disconnect", - &[("store", t("pg")), ("machine", t("native"))], - ); - assert_eq!(removed.get_text("machine"), Some("native")); - assert!(!record_text(&home, "pg").contains("machines")); - assert_eq!( - call( - &home, - "store.disconnect", - &[("store", t("pg")), ("machine", t("native"))] - ) - .unwrap_err() - .0, - "NotFound" - ); - ok(&home, "store.disconnect", &[("store", t("pg"))]); - let _ = std::fs::remove_dir_all(home); -} diff --git a/api/crates/layerfs-api/tests/project_doctor_full.rs b/api/crates/layerfs-api/tests/project_doctor_full.rs index 60aa626fdc..89de9201e0 100644 --- a/api/crates/layerfs-api/tests/project_doctor_full.rs +++ b/api/crates/layerfs-api/tests/project_doctor_full.rs @@ -209,22 +209,14 @@ fn postgresql_full_reads_main_and_each_branch_and_names_a_damaged_object_in_each let home = folder("pg-home"); // the URL's user becomes a saved login (a trust-auth server takes any // password); the address is connected without it - call( - &home, - "store.save_auth", - &[ - ("auth", t("pg")), - ("user", t(&user)), - ("password", t("unused")), - ], - ); call( &home, "store.connect", &[ ("store", t("shop")), ("url", t(&clean_url)), - ("auth", t("pg")), + ("user", t(&user)), + ("password", t("unused")), ("synchronous_commit", t("off")), ], ); diff --git a/api/crates/layerfs-api/tests/project_stats.rs b/api/crates/layerfs-api/tests/project_stats.rs index c978b6c730..91909df45d 100644 --- a/api/crates/layerfs-api/tests/project_stats.rs +++ b/api/crates/layerfs-api/tests/project_stats.rs @@ -198,22 +198,14 @@ fn postgresql_counts_the_same_saved_tree_definition() { // password); the address is connected without it let (scheme, rest) = url.split_once("://").unwrap(); let (user, address) = rest.split_once('@').unwrap(); - call( - &home, - "store.save_auth", - &[ - ("auth", t("pg")), - ("user", t(user)), - ("password", t("unused")), - ], - ); call( &home, "store.connect", &[ ("store", t("trees")), ("url", t(&format!("{scheme}://{address}"))), - ("auth", t("pg")), + ("user", t(user)), + ("password", t("unused")), ("synchronous_commit", t("off")), ], ); diff --git a/api/crates/layerfs-api/tests/sandbox_machines.rs b/api/crates/layerfs-api/tests/sandbox_machines.rs index 0916542347..a1c3975bb3 100644 --- a/api/crates/layerfs-api/tests/sandbox_machines.rs +++ b/api/crates/layerfs-api/tests/sandbox_machines.rs @@ -10,9 +10,10 @@ //! LAYERFS_TEST_PG_PASSWORD, LAYERFS_TEST_DAEMON (a host daemon built with //! `postgresql`); the docker half also LAYERFS_TEST_IMAGE (a local image //! digest, the worker container's) and LAYERFS_BUNDLE (a sealed Linux -//! bundle whose daemon has `postgresql`). The URL is never rewritten: on -//! Docker Desktop a loopback URL is refused for the docker machine, which -//! is then given its own URL naming `host.docker.internal`, which its +//! bundle whose daemon has `postgresql`). The docker machine is attached +//! to the Store first. The URL is never rewritten: on Docker Desktop a +//! loopback URL is refused for the docker machine, and the Store is then +//! connected again with a URL naming `host.docker.internal`, which its //! Sandboxes resolve with the worker's resolver files; their Workspace //! and Commit never show those files. //! - a sqlite Store pushed to the docker machine and its Sandbox, through the @@ -61,23 +62,24 @@ fn ok(home: &Path, name: &str, args: &[(&str, SdkValue)]) -> SdkValue { call(home, name, args).unwrap_or_else(|e| panic!("{name}: {e:?}")) } -/// PostgreSQL Store `pg` as a 2.0 home records it: its address and the -/// saved login it names (a test login; nothing is dialled with it here). -fn pg_record(home: &Path) { - let login = [ - ("auth", t("pg")), +/// PostgreSQL Store `pg` as a 2.0 home records it: its address, its user +/// and the machines attached to it, its password saved in the home (a +/// test login; nothing is dialled with it here). +fn pg_record(home: &Path, attached: &[&str]) { + layerfs_store::postgresql::login::save(home, "pg", "not-a-real-password").unwrap(); + let mut fields = vec![ + ("name", t("pg")), + ("kind", t("postgresql")), + ("url", t("postgres://127.0.0.1:1/db")), ("user", t("u")), - ("password", t("not-a-real-password")), ]; - ok(home, "store.save_auth", &login); + if !attached.is_empty() { + let names = attached.iter().map(|m| t(m)).collect(); + fields.push(("attached", SdkValue::List(names))); + } home::write_record( &paths::store_record(home, "pg"), - &SdkValue::map([ - ("name", t("pg")), - ("kind", t("postgresql")), - ("url", t("postgres://127.0.0.1:1/db")), - ("auth", t("pg")), - ]), + &SdkValue::Map(fields.into_iter().map(|(k, v)| (k.to_owned(), v)).collect()), ) .unwrap(); } @@ -172,7 +174,7 @@ fn a_sandbox_runs_where_its_store_can_be_reached() { ok(&home, "machine.list", &[]); // a PostgreSQL Store and a sqlite Store on native, written as records: // the refusals come before any connection - pg_record(&home); + pg_record(&home, &[]); home::write_record( &paths::store_record(&home, "shop"), &SdkValue::map([("name", t("shop")), ("kind", t("sqlite"))]), @@ -225,12 +227,32 @@ fn a_sandbox_runs_where_its_store_can_be_reached() { layerfs_platform::StoreKind::Postgresql, ) { Ok(()) => { + // a machine not attached to the Store is refused first, with + // the attach as its fix + assert_eq!(code, "InvalidInput", "{message}"); + assert_eq!( + message, "machine dev is not attached to PostgreSQL Store pg", + "{message}" + ); + let args = SdkValue::map([ + ("project", t("pg/app")), + ("name", t("t")), + ("machine", t("dev")), + ]); + let refusal = + layerfs_api::call(Some(&home), "sandbox.create", args, &mut |_| {}).unwrap_err(); + assert_eq!( + refusal.detail.get_text("fix"), + Some("layerfs store attach pg --machine dev") + ); + pg_record(&home, &["dev"]); + let (code, message) = create("dev"); // a loopback URL is refused before the machine is asked: lima // does not share this host's loopback, and nothing rewrites it assert_eq!(code, "Unsupported", "{message}"); assert!(message.contains("host.lima.internal"), "{message}"); assert!( - message.contains("`layerfs store connect pg --machine dev`"), + message.contains("`layerfs store connect pg `"), "{message}" ); // a Sandbox already on the machine is still read and removed: @@ -257,7 +279,7 @@ fn a_sandbox_runs_where_its_store_can_be_reached() { let (code, message) = create("dev"); assert_eq!(code, "Unavailable", "{message}"); assert!(message.contains("layerfs machine start dev"), "{message}"); - pg_record(&home); + pg_record(&home, &[]); } Err(reason) => { assert_eq!(code, "Unsupported", "{message}"); @@ -295,8 +317,8 @@ fn a_sandbox_runs_where_its_store_can_be_reached() { /// A close runs without a PostgreSQL Store URL its machine cannot dial (a /// loopback lima does not share), so a Sandbox can always be removed; any /// other reason the URL cannot be made refuses the remove, forced or not, -/// with that reason's own words and fix: the saved login the Store names -/// is gone, or it names none. Nothing is removed then. +/// with that reason's own words and fix: the Store's password is not saved +/// in this home, or its record names no user. Nothing is removed then. #[test] fn a_forced_remove_says_why_its_store_s_url_cannot_be_made() { let home = tempdir("lost-login"); @@ -317,47 +339,38 @@ fn a_forced_remove_says_why_its_store_s_url_cannot_be_made() { ) .unwrap(); sandbox_on(&home, "dev"); - let store = |auth: Option<&str>| { - let mut fields = vec![ + let store = |field: (&str, &str)| { + let fields = vec![ ("name".to_owned(), t("pg")), ("kind".to_owned(), t("postgresql")), ("url".to_owned(), t("postgres://127.0.0.1:1/db")), + (field.0.to_owned(), t(field.1)), ]; - fields.extend(auth.map(|auth| ("auth".to_owned(), t(auth)))); home::write_record(&paths::store_record(&home, "pg"), &SdkValue::Map(fields)).unwrap(); }; let remove = || { let args = SdkValue::map([("sandbox", t("s1")), ("force", SdkValue::Bool(true))]); layerfs_api::call(Some(&home), "sandbox.remove", args, &mut |_| {}).unwrap_err() }; - // the saved login the Store names is gone - store(Some("gone")); - let refusal = remove(); - assert_eq!(refusal.code, "NotFound", "{}", refusal.message); - assert!( - refusal.message.contains("no saved login named gone") - && refusal - .message - .contains("`layerfs store save-auth gone --user --password-stdin`"), - "{}", - refusal.message - ); - // the Store names none: the fix saves one and names it - store(None); + // the Store's password is not saved: the fix connects it with one + store(("user", "u")); let refusal = remove(); assert_eq!(refusal.code, "InvalidInput", "{}", refusal.message); assert_eq!( refusal.detail.get_text("fix"), - Some( - "layerfs store save-auth --user --password-stdin && layerfs store update pg --auth " - ), + Some("layerfs store connect pg --password-stdin"), "{}", refusal.message ); + // a record naming no user + store(("schema", "layerfs")); + let refusal = remove(); + assert_eq!(refusal.code, "InvalidInput", "{}", refusal.message); + assert!(refusal.message.contains("user"), "{}", refusal.message); assert!(paths::sandbox_record(&home, "s1").exists()); // with its login saved, the loopback URL lima does not share refuses // nothing: the remove reaches the machine (here stopped) - pg_record(&home); + pg_record(&home, &["dev"]); let refusal = remove(); assert!(!refusal.message.contains("loopback"), "{}", refusal.message); assert!( @@ -377,7 +390,7 @@ fn every_platform_refusal_is_the_support_table_s() { let home = tempdir("support"); home::open(&home).unwrap(); ok(&home, "machine.list", &[]); - pg_record(&home); + pg_record(&home, &[]); home::write_record( &paths::project_record(&home, "pg", "app"), &SdkValue::map([("name", t("app"))]), @@ -467,24 +480,16 @@ fn a_postgresql_store_s_sandboxes_on_native_and_docker() { let (scheme, rest) = url.split_once("://").unwrap(); let (user, address) = rest.split_once('@').unwrap(); let password = std::env::var("LAYERFS_TEST_PG_PASSWORD").unwrap(); - ok( - &home, - "store.save_auth", - &[ - ("auth", t("pg")), - ("user", t(user)), - ("password", t(&password)), - ], - ); - ok( - &home, - "store.connect", - &[ + let login = [("user", t(user)), ("password", t(&password))]; + let connect = |address: &str| { + let mut args = vec![ ("store", t("pg")), ("url", t(&format!("{scheme}://{address}"))), - ("auth", t("pg")), - ], - ); + ]; + args.extend(login.iter().cloned()); + ok(&home, "store.connect", &args) + }; + connect(address); ok( &home, "project.init", @@ -502,18 +507,20 @@ fn a_postgresql_store_s_sandboxes_on_native_and_docker() { ("machine", t("native")), ], ); - // the create proved this computer reaches the Store: `native` with no - // address of its own is this computer's row (spec v23 V23-2) + // the create proved this computer reaches the Store: `native` is this + // computer, whose reach is the Store's own (spec v23 V23-2) let got = ok( &home, "store.get", &[("store", t("pg")), ("detail", SdkValue::Bool(true))], ); - let Some(SdkValue::List(rows)) = got.get("connections") else { - panic!("{got:?}"); - }; - assert_eq!(rows.len(), 1, "{rows:?}"); - assert_eq!(rows[0].get_text("reached"), Some("ok"), "{rows:?}"); + let reach = got.get("reach").unwrap_or_else(|| panic!("{got:?}")); + assert_eq!(reach.get("ok"), Some(&SdkValue::Bool(true)), "{got:?}"); + assert_eq!( + got.get("machines"), + Some(&SdkValue::List(vec![])), + "{got:?}" + ); work(&home, "pg/app", "n", "on-native", "native.txt"); ok(&home, "sandbox.remove", &[("sandbox", t("n"))]); if let (Some(image), Some(_)) = (env("LAYERFS_TEST_IMAGE"), env("LAYERFS_BUNDLE")) { @@ -536,28 +543,35 @@ fn a_postgresql_store_s_sandboxes_on_native_and_docker() { ], ) }; + // not attached yet: refused with the attach as its fix + let (code, message) = create().unwrap_err(); + assert_eq!(code, "InvalidInput", "{message}"); + let attach = || { + call( + &home, + "store.attach", + &[("store", t("pg")), ("machine", t("docker"))], + ) + }; // Docker Desktop's worker does not share this host's loopback: // a loopback URL is refused, naming the host's name there, and - // the machine gets its own URL (nothing is rewritten) + // the Store is connected again with that name (nothing is + // rewritten; this computer dials it too) let loopback = ["127.0.0.1", "localhost", "[::1]"] .iter() .find(|host| address.starts_with(*host)); if let (Some(host), false) = (loopback, cfg!(target_os = "linux")) { - let (code, message) = create().unwrap_err(); + let (code, message) = attach().unwrap_err(); assert_eq!(code, "Unsupported", "{message}"); assert!(message.contains("host.docker.internal"), "{message}"); - assert!(message.contains("--machine docker"), "{message}"); - let own = address.replacen(host, "host.docker.internal", 1); - ok( - &home, - "store.connect", - &[ - ("store", t("pg")), - ("url", t(&format!("{scheme}://{own}"))), - ("machine", t("docker")), - ], + assert!( + message.contains("`layerfs store connect pg `"), + "{message}" ); + connect(&address.replacen(host, "host.docker.internal", 1)); } + let attached = attach().unwrap(); + assert_eq!(attached.get_text("outcome"), Some("attached")); // the create's reach check dials from the worker container create().unwrap(); resolves_as_the_worker(&home, "pg/app", "d"); @@ -848,12 +862,30 @@ fn a_sandbox_with_no_machine_runs_on_its_store_s() { "a refused create leaves no claim" ); - pg_record(&home); + pg_record(&home, &[]); home::write_record( &paths::project_record(&home, "pg", "app"), &SdkValue::map([("name", t("app"))]), ) .unwrap(); + // a machine not attached to the Store is refused before any dial, + // with the attach as its fix + let args = SdkValue::map([ + ("project", t("pg/app")), + ("name", t("t3")), + ("machine", t("box")), + ]); + let refusal = layerfs_api::call(Some(&home), "sandbox.create", args, &mut |_| {}).unwrap_err(); + assert_eq!(refusal.code, "InvalidInput", "{refusal:?}"); + assert_eq!( + refusal.message, + "machine box is not attached to PostgreSQL Store pg" + ); + assert_eq!( + refusal.detail.get_text("fix"), + Some("layerfs store attach pg --machine box") + ); + assert!(!paths::sandbox_dir(&home, "t3").exists()); let refused = call( &home, "sandbox.create", diff --git a/api/crates/layerfs-api/tests/store_routes.rs b/api/crates/layerfs-api/tests/store_routes.rs index e806ac36e0..73ee4190ba 100644 --- a/api/crates/layerfs-api/tests/store_routes.rs +++ b/api/crates/layerfs-api/tests/store_routes.rs @@ -78,21 +78,21 @@ fn a_store_record_whose_machine_is_not_text_is_refused() { } #[test] -fn a_postgresql_store_reads_its_saved_login_per_call() { +fn a_postgresql_store_reads_its_saved_password_per_call() { let home = home_with(SdkValue::map([ ("name", t("shop")), ("kind", t("postgresql")), ("url", t("postgresql://127.0.0.1:1/db")), - ("auth", t("route-login")), + ("user", t("route-login")), ("schema", t("shop")), ("synchronous_commit", t("off")), ("binding", SdkValue::Bytes(vec![7; 16])), ("cursor", SdkValue::Bytes(vec![8; 32])), ])); let (code, message) = read(&home, "shop/api").unwrap_err(); - assert_eq!(code, "NotFound"); + assert_eq!(code, "InvalidInput"); assert!( - message.contains("no saved login named route-login"), + message.contains("shop's password is not saved in this home"), "{message}" ); std::fs::remove_dir_all(home).unwrap(); diff --git a/api/crates/layerfs-api/tests/store_stats.rs b/api/crates/layerfs-api/tests/store_stats.rs index 2163c2b892..9b71bb5bd8 100644 --- a/api/crates/layerfs-api/tests/store_stats.rs +++ b/api/crates/layerfs-api/tests/store_stats.rs @@ -222,22 +222,14 @@ fn postgresql_statistics_have_null_free_and_count_publications() { // the URL's user becomes a saved login (a trust-auth server takes any // password); the address is connected without it let (user, clean_url) = split_pg_test_url(&url); - call( - &home, - "store.save_auth", - &[ - ("auth", t("pg")), - ("user", t(&user)), - ("password", t("unused")), - ], - ); call( &home, "store.connect", &[ ("store", t("stats")), ("url", t(&clean_url)), - ("auth", t("pg")), + ("user", t(&user)), + ("password", t("unused")), ("synchronous_commit", t("off")), ], ); diff --git a/api/crates/layerfs-cli/src/words.rs b/api/crates/layerfs-cli/src/words.rs index c788bbb01a..7edaa3fdfd 100644 --- a/api/crates/layerfs-cli/src/words.rs +++ b/api/crates/layerfs-cli/src/words.rs @@ -43,7 +43,6 @@ const DEFAULTS: &[(&str, &str, &str)] = &[ const WORDS: &[(&str, &str)] = &[ ("access_key", "K"), ("at", "C"), - ("auth", "A"), ("branch", "B"), ("bucket", "B"), ("call", "C"), diff --git a/api/crates/layerfs-cli/tests/rendering.rs b/api/crates/layerfs-cli/tests/rendering.rs index ea0c272062..cc0dacdf04 100644 --- a/api/crates/layerfs-cli/tests/rendering.rs +++ b/api/crates/layerfs-cli/tests/rendering.rs @@ -219,7 +219,7 @@ fn a_row_s_reason_reads_in_state_and_its_fix_under_the_table() { ("store", t("pg")), ("state", t("broken")), ("reason", t("outdated")), - ("fix", t("layerfs store update pg --auth x")), + ("fix", t("layerfs store connect pg --password-stdin")), ]), SdkValue::map([ ("store", t("s")), @@ -238,7 +238,7 @@ fn a_row_s_reason_reads_in_state_and_its_fix_under_the_table() { pg broken: outdated\n\ s blocked by machine docker (outdated)\n\ \n\ - fix pg: layerfs store update pg --auth x\n" + fix pg: layerfs store connect pg --password-stdin\n" ); } @@ -255,7 +255,7 @@ fn doctor_text_aligns_columns_and_renders_detail_tree_and_evidence() { ("check", t("store.connection")), ("severity", t("error")), ("message", t("cannot reach server")), - ("fix", t("layerfs store update pg --auth a")), + ("fix", t("layerfs store connect pg --password-stdin")), ("evidence", SdkValue::map([("step", t("handshake"))])), ])]), ), @@ -295,6 +295,9 @@ fn doctor_text_aligns_columns_and_renders_detail_tree_and_evidence() { "{shown}" ); assert!(shown.contains("evidence: step=handshake"), "{shown}"); - assert!(shown.contains("observed at: 2026-11-20T05:00:00Z"), "{shown}"); + assert!( + shown.contains("observed at: 2026-11-20T05:00:00Z"), + "{shown}" + ); assert!(shown.contains("store.record: pass"), "{shown}"); } diff --git a/api/crates/layerfs-cli/tests/saved_continuation.rs b/api/crates/layerfs-cli/tests/saved_continuation.rs index 3dd1de5f58..df5be959f7 100644 --- a/api/crates/layerfs-cli/tests/saved_continuation.rs +++ b/api/crates/layerfs-cli/tests/saved_continuation.rs @@ -190,39 +190,29 @@ fn postgresql_saved_queries_resume_in_new_processes() { }; let home = tempdir("pg-continuation-home"); let source = tempdir("pg-continuation-source"); - // the URL's user becomes a saved login, its password on stdin (a + // the URL's user is the Store's login, its password on stdin (a // trust-auth server takes any); the address is connected without it let (scheme, rest) = url.split_once("://").unwrap(); let (user, address) = rest.split_once('@').unwrap(); + let address = format!("{scheme}://{address}"); let out = common::run_with_stdin( &mut layerfs( &home, &[ "store", - "save-auth", - "pg", + "connect", + "q", + &address, "--user", user, "--password-stdin", + "--synchronous-commit", + "off", ], ), b"unused\n", ); assert!(out.status.success(), "{}", text(&out.stderr)); - let address = format!("{scheme}://{address}"); - call( - &home, - &[ - "store", - "connect", - "q", - &address, - "--auth", - "pg", - "--synchronous-commit", - "off", - ], - ); check(&home, &source); std::fs::remove_dir_all(home).unwrap(); std::fs::remove_dir_all(source).unwrap(); diff --git a/api/mcp/src/profiles.js b/api/mcp/src/profiles.js index 7e0ed254b1..14715fc2dc 100644 --- a/api/mcp/src/profiles.js +++ b/api/mcp/src/profiles.js @@ -22,7 +22,7 @@ const WHY = { sandbox: "start, read, remove, inspect and check a Sandbox", workspace: "mount, run in, cancel, commit and unmount a Workspace explicitly; nothing is implicit", machine: "machines hold Stores and workers: read, start, stop, create, change, inspect and check them", - store: "create, connect, move, compact, check and remove Stores, and keep PostgreSQL logins", + store: "create, connect, attach, move, compact, check and remove Stores", backup: "connect buckets, back up and restore a Store, and check a bucket", }; diff --git a/api/node/src/index.d.ts b/api/node/src/index.d.ts index ea72fea9e6..424089932e 100644 --- a/api/node/src/index.d.ts +++ b/api/node/src/index.d.ts @@ -502,26 +502,19 @@ export interface StoreCreateOptions extends CallOptions { /** Options of `store.connect`; an unknown option is refused. */ export interface StoreConnectOptions extends CallOptions { - auth?: string; - machine?: string; + user?: string; + password?: Content; synchronous_commit?: string; } -/** Options of `store.disconnect`; an unknown option is refused. */ -export interface StoreDisconnectOptions extends CallOptions { - machine?: string; +/** Options of `store.attach`; an unknown option is refused. */ +export interface StoreAttachOptions extends CallOptions { + machine: string; } -/** Options of `store.save_auth`; an unknown option is refused. */ -export interface StoreSaveAuthOptions extends CallOptions { - user: string; - password: Content; -} - -/** Options of `store.update`; an unknown option is refused. */ -export interface StoreUpdateOptions extends CallOptions { - auth?: string; - synchronous_commit?: string; +/** Options of `store.detach`; an unknown option is refused. */ +export interface StoreDetachOptions extends CallOptions { + machine: string; } /** Options of `store.move`; an unknown option is refused. */ @@ -732,18 +725,14 @@ export interface StoreFamily { get(store: string, options?: StoreGetOptions): Promise; /** an empty sqlite Store */ create(name: string, options?: StoreCreateOptions): Promise; - /** connect a PostgreSQL database as a Store, or set an address of a connected one */ + /** connect a PostgreSQL database as a Store, or change a connected one's address, login or setting */ connect(store: string, url: string, options?: StoreConnectOptions): Promise; - /** forget a PostgreSQL Store, or one machine's own address and reach; its data stays */ - disconnect(store: string, options?: StoreDisconnectOptions): Promise; - /** save a PostgreSQL login in the home; saving again rotates it */ - save_auth(auth: string, options: StoreSaveAuthOptions): Promise; - /** the saved PostgreSQL logins and the Stores that use each */ - auths(options?: CallOptions): Promise; - /** remove a saved PostgreSQL login no Store uses */ - remove_auth(auth: string, options?: CallOptions): Promise; - /** change a PostgreSQL Store's saved login or its synchronous_commit */ - update(store: string, options?: StoreUpdateOptions): Promise; + /** forget a PostgreSQL Store, its saved login and its attachments; its data stays */ + disconnect(store: string, options?: CallOptions): Promise; + /** let a machine run Sandboxes of a PostgreSQL Store, checked from that machine first */ + attach(store: string, options: StoreAttachOptions): Promise; + /** stop a machine running Sandboxes of a PostgreSQL Store; refused while one runs there */ + detach(store: string, options: StoreDetachOptions): Promise; /** move a sqlite Store between this computer and a machine */ move(store: string, machine: string, options?: StoreMoveOptions): Promise; /** delete a sqlite Store with every project in it */ diff --git a/api/node/test/calls.mjs b/api/node/test/calls.mjs index 12e57c9bb8..4149d4b0c2 100644 --- a/api/node/test/calls.mjs +++ b/api/node/test/calls.mjs @@ -14,9 +14,9 @@ const temp = (tag) => { return dir; }; -test("the table: ten families, 83 calls, each a function", () => { +test("the table: ten families, 81 calls, each a function", () => { assert.deepEqual(families, ["home", "project", "branch", "commit", "file", "sandbox", "workspace", "machine", "store", "backup"]); - assert.equal(table.length, 83); + assert.equal(table.length, 81); for (const spec of table) assert.equal(typeof layerfs[spec.family][spec.call], "function", `${spec.family}.${spec.call}`); }); diff --git a/api/python/src/layerfs/_client.pyi b/api/python/src/layerfs/_client.pyi index ef5f82661a..332786c066 100644 --- a/api/python/src/layerfs/_client.pyi +++ b/api/python/src/layerfs/_client.pyi @@ -827,63 +827,43 @@ class StoreFamily: store: str, url: str, *, - auth: str | None = None, - machine: str | None = None, + user: str | None = None, + password: Content | None = None, synchronous_commit: str | None = None, detail: bool | None = None, with_: Sequence[str] | None = None, log_tag: str | None = None, ) -> Result: - """connect a PostgreSQL database as a Store, or set an address of a connected one""" + """connect a PostgreSQL database as a Store, or change a connected one's address, login or setting""" def disconnect( self, store: str, *, - machine: str | None = None, - detail: bool | None = None, - with_: Sequence[str] | None = None, - log_tag: str | None = None, - ) -> Result: - """forget a PostgreSQL Store, or one machine's own address and reach; its data stays""" - def save_auth( - self, - auth: str, - *, - user: str, - password: Content, detail: bool | None = None, with_: Sequence[str] | None = None, log_tag: str | None = None, ) -> Result: - """save a PostgreSQL login in the home; saving again rotates it""" - def auths( + """forget a PostgreSQL Store, its saved login and its attachments; its data stays""" + def attach( self, + store: str, *, + machine: str, detail: bool | None = None, with_: Sequence[str] | None = None, log_tag: str | None = None, ) -> Result: - """the saved PostgreSQL logins and the Stores that use each""" - def remove_auth( - self, - auth: str, - *, - detail: bool | None = None, - with_: Sequence[str] | None = None, - log_tag: str | None = None, - ) -> Result: - """remove a saved PostgreSQL login no Store uses""" - def update( + """let a machine run Sandboxes of a PostgreSQL Store, checked from that machine first""" + def detach( self, store: str, *, - auth: str | None = None, - synchronous_commit: str | None = None, + machine: str, detail: bool | None = None, with_: Sequence[str] | None = None, log_tag: str | None = None, ) -> Result: - """change a PostgreSQL Store's saved login or its synchronous_commit""" + """stop a machine running Sandboxes of a PostgreSQL Store; refused while one runs there""" def move( self, store: str, diff --git a/api/python/src/layerfs/aio.pyi b/api/python/src/layerfs/aio.pyi index 75b893296b..b42ae7725e 100644 --- a/api/python/src/layerfs/aio.pyi +++ b/api/python/src/layerfs/aio.pyi @@ -825,63 +825,43 @@ class AsyncStoreFamily: store: str, url: str, *, - auth: str | None = None, - machine: str | None = None, + user: str | None = None, + password: Content | None = None, synchronous_commit: str | None = None, detail: bool | None = None, with_: Sequence[str] | None = None, log_tag: str | None = None, ) -> Result: - """connect a PostgreSQL database as a Store, or set an address of a connected one""" + """connect a PostgreSQL database as a Store, or change a connected one's address, login or setting""" async def disconnect( self, store: str, *, - machine: str | None = None, - detail: bool | None = None, - with_: Sequence[str] | None = None, - log_tag: str | None = None, - ) -> Result: - """forget a PostgreSQL Store, or one machine's own address and reach; its data stays""" - async def save_auth( - self, - auth: str, - *, - user: str, - password: Content, detail: bool | None = None, with_: Sequence[str] | None = None, log_tag: str | None = None, ) -> Result: - """save a PostgreSQL login in the home; saving again rotates it""" - async def auths( + """forget a PostgreSQL Store, its saved login and its attachments; its data stays""" + async def attach( self, + store: str, *, + machine: str, detail: bool | None = None, with_: Sequence[str] | None = None, log_tag: str | None = None, ) -> Result: - """the saved PostgreSQL logins and the Stores that use each""" - async def remove_auth( - self, - auth: str, - *, - detail: bool | None = None, - with_: Sequence[str] | None = None, - log_tag: str | None = None, - ) -> Result: - """remove a saved PostgreSQL login no Store uses""" - async def update( + """let a machine run Sandboxes of a PostgreSQL Store, checked from that machine first""" + async def detach( self, store: str, *, - auth: str | None = None, - synchronous_commit: str | None = None, + machine: str, detail: bool | None = None, with_: Sequence[str] | None = None, log_tag: str | None = None, ) -> Result: - """change a PostgreSQL Store's saved login or its synchronous_commit""" + """stop a machine running Sandboxes of a PostgreSQL Store; refused while one runs there""" async def move( self, store: str, diff --git a/api/python/test/test_calls.py b/api/python/test/test_calls.py index c0ec45e291..20624e15b9 100644 --- a/api/python/test/test_calls.py +++ b/api/python/test/test_calls.py @@ -409,7 +409,7 @@ def test_the_table(self): layerfs.FAMILIES, ["home", "project", "branch", "commit", "file", "sandbox", "workspace", "machine", "store", "backup"], ) - self.assertEqual(len(layerfs.TABLE), 83) + self.assertEqual(len(layerfs.TABLE), 81) for spec in layerfs.TABLE: self.assertTrue(callable(getattr(getattr(layerfs, spec["family"]), spec["call"]))) # the options of `branch publish` (2.0 row: at, expected, force) are in diff --git a/control/crates/layerfs-control/src/doctor/store_target.rs b/control/crates/layerfs-control/src/doctor/store_target.rs index 1325080df6..7b51da6b7f 100644 --- a/control/crates/layerfs-control/src/doctor/store_target.rs +++ b/control/crates/layerfs-control/src/doctor/store_target.rs @@ -4,9 +4,9 @@ //! Store is reached through its machine (this process for `native`, the //! worker's `store.diagnose` with `cut: schema` elsewhere), which also //! reads its heads when it has a bucket link; a PostgreSQL Store from this -//! computer, then once more from each machine with an address of its own -//! or a Sandbox of it and from `--machine` (R9, spec v23 V23-9), one -//! `store.connection` each with `from`; every reach is recorded +//! computer, then, when this computer reached it, once more from each +//! machine attached to it, or from `--machine` alone (owner, 2026-11-24), +//! one `store.connection` each with `from`; every reach is recorded //! (`layerfs_store::observed`). //! `store.operation` reads the home's record and, for a sqlite Store, the //! compaction record beside its file through its machine (the shallow cut @@ -126,7 +126,7 @@ fn resolve(home: &Path, name: &str, checks: &mut Checks) -> Option<(StoreRecord, } match identity::identity_in(&record) { Ok(identity) => { - own_state(&record, checks); + checks.pass(RECORD, "its record names it, its engine and its id"); Some((record, identity)) } Err(error) => { @@ -139,33 +139,6 @@ fn resolve(home: &Path, name: &str, checks: &mut Checks) -> Option<(StoreRecord, } } -/// `store.record` passes unless the record itself breaks a PostgreSQL -/// Store (spec v23): naming no saved login, one this home does not hold, -/// or holding what 2.0 no longer writes (V23-6). It then fails with the -/// state's fix, the one `store list` and `store get` give. -fn own_state(record: &StoreRecord, checks: &mut Checks) { - let own = match record.store_ref() { - Ok(StoreRef::Postgres { .. }) => layerfs_store::state::postgresql(record), - _ => None, - }; - let Some(State::Broken { reason, fix }) = own else { - checks.pass(RECORD, "its record names it, its engine and its id"); - return; - }; - let why = match (reason, record.text("auth")) { - (Reason::Missing, Some(auth)) => { - format!("it names login {auth}, which this home does not hold") - } - (_, None) => "it names no saved login".to_owned(), - _ => "it holds what 2.0 no longer writes (a password, a login in a URL or an old machine entry)" - .to_owned(), - }; - checks.fail(RECORD, format!("its record is {}: {why}", reason.word())); - if let Some(fix) = fix { - checks.fix(RECORD, fix); - } -} - /// `store.operation`: no operation on it is half-finished or left with its /// outcome not known, and no lease is stale; read from the home's records /// and, for a sqlite Store, from `compaction`, the compaction record beside @@ -466,7 +439,7 @@ fn postgresql(probe: &Probe<'_>, record: &StoreRecord, identity: &Identity, chec }; let mut seen = Vec::new(); let made = diagnostic::postgresql(record, identity, options, true, &mut |o| seen.push(o)); - match made { + let reached = match made { Err(error) if seen.is_empty() => { checks.fail( CONNECTION, @@ -476,11 +449,12 @@ fn postgresql(probe: &Probe<'_>, record: &StoreRecord, identity: &Identity, chec CONNECTION, SdkValue::map([("step", SdkValue::text("login"))]), ); - // a refusal before any dial carries its own fix: a record - // naming no saved login gives its `outdated` state's (V20-7) + // a refusal before any dial carries its own fix: a password + // this home does not hold names `store connect` again fix_of(&error, checks); let failed = layerfs_store::observed::Reach::failed(&error.message); layerfs_store::observed::record(probe.home, record.name(), None, &failed); + false } // a server that said nothing within the handshake limit is not // dialled a second time: its silence is the reach recorded @@ -488,21 +462,28 @@ fn postgresql(probe: &Probe<'_>, record: &StoreRecord, identity: &Identity, chec Some(silent) => { let failed = layerfs_store::observed::Reach::failed(&silent); layerfs_store::observed::record(probe.home, record.name(), None, &failed); + false } None => here(probe.home, record), }, + }; + // the machines dial the same URL with the same login: when this + // computer was not let in, each would only repeat its failure + if reached { + reach(probe, record, checks); } - reach(probe, record, checks); } /// Records this computer's reach of PostgreSQL Store `record` (spec v23 -/// V23-9): the check a machine's own connection is checked by, so the -/// observation carries its latency and the server's version. -fn here(home: &Path, record: &StoreRecord) { +/// V23-9): the check an attached machine is checked by, so the +/// observation carries its latency and the server's version. Whether it +/// was reached. +fn here(home: &Path, record: &StoreRecord) -> bool { use layerfs_store::postgresql::{check, connect}; let checked = connect::selection(record).and_then(|pg| check::check(record, &pg)); let seen = layerfs_store::observed::Reach::of(&checked); layerfs_store::observed::record(home, record.name(), None, &seen); + checked.is_ok() } /// The step id `o` gives, without its `store.connection.` prefix. @@ -599,28 +580,17 @@ fn fold( None } -/// `store.connection` of PostgreSQL Store `record` from each machine that -/// has an address of its own or a Sandbox of it, and from `--machine`, as -/// those machines dial it; each result is what was seen of its reach -/// (spec v23 V23-9). A machine that is not ready is not dialled. +/// `store.connection` of PostgreSQL Store `record` from each machine +/// attached to it, or from `--machine` alone (the call refuses one that is +/// not attached), as those machines dial it; each result is what was seen +/// of its reach (spec v23 V23-9). A machine that is not ready is not +/// dialled; `native` is this computer, checked above. fn reach(probe: &Probe<'_>, record: &StoreRecord, checks: &mut Checks) { - let name = record.name(); - let mut machines: Vec = crate::inventory::sandboxes(probe.home) - .unwrap_or_default() - .into_iter() - .filter(|sandbox| { - let project = sandbox.project().unwrap_or(""); - project.split_once('/').map(|(store, _)| store) == Some(name) - }) - .map(|sandbox| sandbox.machine().to_owned()) - .collect(); - machines.extend(probe.options.machine.clone()); - machines.extend(record.own_connections().into_iter().map(|(m, _)| m)); - // this computer dialled the Store's own address above; `native` is - // probed again only for an address of its own - machines.retain(|machine| machine != "native" || record.own_connection(machine).is_some()); - machines.sort(); - machines.dedup(); + let mut machines = match &probe.options.machine { + Some(machine) => vec![machine.clone()], + None => record.attached(), + }; + machines.retain(|machine| machine != "native"); for machine in &machines { let state = crate::store::machine_state(probe.home, machine) .unwrap_or_else(|_| State::broken(Reason::Missing, None)); diff --git a/control/crates/layerfs-control/src/home_tree.rs b/control/crates/layerfs-control/src/home_tree.rs index a7cdfea4a4..3ae9240738 100644 --- a/control/crates/layerfs-control/src/home_tree.rs +++ b/control/crates/layerfs-control/src/home_tree.rs @@ -22,7 +22,7 @@ use layerfs_home::outcome::{failed, Outcome}; use layerfs_home::state::{Reason, State}; use layerfs_machine::record::MachineRecord; use layerfs_sandbox::record::{SandboxRecord, WorkspaceRecord}; -use layerfs_store::record::{StoreRecord, StoreRef}; +use layerfs_store::record::{StoreKind, StoreRecord, StoreRef}; use std::collections::BTreeSet; use std::path::Path; @@ -42,32 +42,27 @@ fn unreadable() -> State { State::broken(Reason::Failed, None) } -/// One Store: `{ store, engine, projects, connections, state.. }`. `under` +/// One Store: `{ store, engine, projects, machines, state.. }`. `under` /// is its machine's name and state, for a sqlite Store; a PostgreSQL -/// Store's `connections` are every side that connects to it, as `store -/// get` answers them (`layerfs_store::postgresql::connect::connections`, -/// spec v23), with `sandboxes` the machines with a Sandbox of it; a -/// sqlite Store has none (null). No URL holds a login. Its state is the -/// Store's one records-only derivation; `engine` is null for a kind it -/// does not read. -fn store( - home: &Path, - record: &StoreRecord, - under: Option<(&str, &State)>, - sandboxes: &[String], -) -> SdkValue { +/// Store's `machines` are the names of the machines attached to it +/// (`layerfs_store::postgresql::connect::machines`; `store get` answers +/// each with its reach); a sqlite Store has none (null). Its state is the Store's one records-only derivation; +/// `engine` is null for a kind it does not read. +fn store(home: &Path, record: &StoreRecord, under: Option<(&str, &State)>) -> SdkValue { let state = layerfs_store::state::recorded_under(record, under.map(|(_, state)| state)) .unwrap_or_else(|_| unreadable()); - let connections = match under { - Some(_) => SdkValue::Null, - None => layerfs_store::postgresql::connect::connections(record, sandboxes), + let machines = match (under, record.kind()) { + (None, Ok(StoreKind::Postgresql)) => { + layerfs_store::postgresql::connect::machines(record, false) + } + _ => SdkValue::Null, }; let engine = record.kind().ok().map(|kind| kind.as_str().to_owned()); state.write(SdkValue::map([ ("store", SdkValue::text(record.name())), ("engine", SdkValue::opt_text(engine)), ("projects", projects(home, record.name())), - ("connections", connections), + ("machines", machines), ])) } @@ -77,7 +72,7 @@ fn unreadable_store(home: &Path, name: &str) -> SdkValue { ("store", SdkValue::text(name)), ("engine", SdkValue::Null), ("projects", projects(home, name)), - ("connections", SdkValue::Null), + ("machines", SdkValue::Null), ])) } @@ -209,7 +204,7 @@ fn machine( let built_in = matches!(name, "native" | "docker").then_some(name); let held_stores = (stores.iter()) .filter(|record| placed(record).as_deref() == Some(name)) - .map(|record| store(home, record, Some((name, &state)), &[])) + .map(|record| store(home, record, Some((name, &state)))) .collect(); let run = (sandboxes.iter()) .filter(|s| s.machine() == name) @@ -286,18 +281,7 @@ pub fn tree(home: &Path) -> Outcome { // a Store on no machine: PostgreSQL, or one whose placement is not read let mut elsewhere: Vec = (stores.iter()) .filter(|record| !matches!(record.store_ref(), Ok(StoreRef::Sqlite { .. }))) - .map(|record| { - let on = (sandboxes.iter()) - .filter(|s| { - let of = s - .project() - .and_then(|p| p.split_once('/')) - .map(|(st, _)| st); - of == Some(record.name()) - }) - .map(|s| s.machine().to_owned()); - store(home, record, None, &on.collect::>()) - }) + .map(|record| store(home, record, None)) .collect(); elsewhere.extend( (unread_stores.into_iter()).filter_map(|read| Some(unreadable_store(home, &read.err()?))), diff --git a/control/crates/layerfs-control/src/inventory.rs b/control/crates/layerfs-control/src/inventory.rs index 364ba29b61..a8fd113dfe 100644 --- a/control/crates/layerfs-control/src/inventory.rs +++ b/control/crates/layerfs-control/src/inventory.rs @@ -150,6 +150,37 @@ pub fn sandboxes_of_store(home: &Path, store: &str) -> Result> { Ok(of.map(|sandbox| sandbox.name().to_owned()).collect()) } +/// `store.detach`: refused `InUse` while a Sandbox of Store `store`'s +/// projects is on machine `machine`, naming how many and which (next field +/// `sandboxes`), with the fix that removes them and detaches the machine. +pub fn store_idle_on(home: &Path, store: &str, machine: &str) -> Result<()> { + let on: Vec = sandboxes(home)? + .into_iter() + .filter(|sandbox| sandbox.machine() == machine) + .filter(|sandbox| { + let project = sandbox.project().unwrap_or(""); + project.split_once('/').map(|(s, _)| s) == Some(store) + }) + .map(|sandbox| sandbox.name().to_owned()) + .collect(); + if on.is_empty() { + return Ok(()); + } + let message = format!( + "{} Sandbox(es) of Store {store}'s projects run on machine {machine}: {}", + on.len(), + on.join(", ") + ); + let detach = format!( + "layerfs store detach {} --machine {}", + shell_word(store), + shell_word(machine) + ); + let refusal = in_use(message, related("sandbox", &on)); + let refusal = with_next(refusal, "sandboxes", listed(&on)); + Err(with_fix(refusal, then(&on, &detach))) +} + /// The Sandboxes of project `project` (`/`). pub fn sandboxes_of_project(home: &Path, project: &str) -> Result> { let of = sandboxes(home)?.into_iter(); diff --git a/control/crates/layerfs-control/src/machine.rs b/control/crates/layerfs-control/src/machine.rs index 1770b8c4b6..a3faab345a 100644 --- a/control/crates/layerfs-control/src/machine.rs +++ b/control/crates/layerfs-control/src/machine.rs @@ -76,9 +76,9 @@ pub fn create(home: &Path, events: &mut Events<'_>, request: &MachineCreate) -> layerfs_machine::create(home, events, request, RELATED) } -/// `machine.remove`. A removed machine's own connection to each -/// PostgreSQL Store is forgotten with it, so a later machine of its name -/// dials the Store's, and so are the home's image copy locks of it +/// `machine.remove`. A removed machine's attachment to each PostgreSQL +/// Store is forgotten with it, so a later machine of its name is attached +/// to none, and so are the home's image copy locks of it /// (`run/image-lock//`). pub fn remove(home: &Path, events: &mut Events<'_>, name: &MachineName) -> Outcome { let removed = layerfs_machine::remove(home, name, RELATED, events)?; @@ -86,7 +86,7 @@ pub fn remove(home: &Path, events: &mut Events<'_>, name: &MachineName) -> Outco layerfs_home::outcome::refused( &refusal.code, format!( - "machine {name} was removed, but its own PostgreSQL connection was not forgotten: {}", + "machine {name} was removed, but its PostgreSQL Store attachments were not forgotten: {}", refusal.message ), ) diff --git a/control/crates/layerfs-control/src/store.rs b/control/crates/layerfs-control/src/store.rs index 9c407e0238..278488e1d5 100644 --- a/control/crates/layerfs-control/src/store.rs +++ b/control/crates/layerfs-control/src/store.rs @@ -2,9 +2,8 @@ //! each runs `layerfs-store`'s call with the checks from //! [`crate::inventory`]. The Store calls proper (`branch`, `commit`, `file`) //! and the rest (`store.list`, `store.get`, `store.create`) are -//! `layerfs-store`'s own. `store.connect --machine` and -//! `store.disconnect --machine` also read the machine, and the first -//! reaches it as a Sandbox call would. +//! `layerfs-store`'s own. `store.attach` and `store.detach` also read the +//! machine, and the first reaches the Store from it as a Sandbox would. use crate::inventory; use layerfs_bridge::control::{SdkRefusal, SdkValue}; use layerfs_home::events::Events; @@ -15,7 +14,7 @@ use layerfs_machine::worker::Unreached; use layerfs_store::place::{self, Executor}; use layerfs_store::postgresql::check; use layerfs_store::postgresql::connect::{self, StoreConnect}; -use layerfs_store::record::{OwnConnection, StoreKind, StoreRecord}; +use layerfs_store::record::{StoreKind, StoreRecord}; use layerfs_store::Related; use std::path::Path; @@ -85,33 +84,10 @@ pub fn machine_state(home: &Path, name: &str) -> Result Vec<(String, String)> { - let sandboxes = inventory::sandboxes(home).unwrap_or_default().into_iter(); - sandboxes - .filter_map(|sandbox| { - let (store, _) = sandbox.project()?.split_once('/')?; - Some((store.to_owned(), sandbox.machine().to_owned())) - }) - .collect() -} - /// What the Store reads take from the other entities: each machine's -/// state ([`machine_state`]) and the Sandboxes' Stores -/// ([`sandbox_stores`]). -pub fn reads() -> ( - layerfs_store::state::Machines<'static>, - layerfs_store::get::Sandboxes<'static>, -) { - (&machine_state, &sandbox_stores) -} - -/// The machines with a Sandbox of Store `store`. -fn sandboxes_of(home: &Path, store: &str) -> Vec { - layerfs_store::get::sandbox_machines(&sandbox_stores(home), store) +/// state ([`machine_state`]). +pub fn reads() -> layerfs_store::state::Machines<'static> { + &machine_state } /// `store.remove`: a sqlite Store no Sandbox uses, with its file. @@ -125,97 +101,114 @@ pub fn move_to(home: &Path, events: &mut Events<'_>, store: &str, machine: &str) layerfs_store::sqlite::transfer::phases::move_to(home, events, store, machine, RELATED) } -/// `store.disconnect(store, { machine })`: without `machine`, forget a -/// PostgreSQL Store (its data stays), refused `InUse` while a process -/// holds it or a Sandbox of its projects exists; with it, remove that -/// machine's own address, after which it dials the Store's again, and -/// forget what was seen of its reach (spec v23): `NotFound` when it has -/// neither. A sqlite Store is `InvalidInput`, naming `store remove`. -pub fn disconnect(home: &Path, name: &StoreName, machine: Option<&MachineName>) -> Outcome { - let Some(machine) = machine.map(|m| m.as_str()) else { - return connect::disconnect(home, name, RELATED); - }; - let record = check::postgresql_record(home, name)?; - let seen = layerfs_store::observed::read(home, name) - .of(machine) - .is_some(); - if record.own_connection(machine).is_none() && !seen { - return Err(refused( - "NotFound", - format!("machine {machine} has no address of its own for Store {name}, and none was seen connecting"), - )); - } - check::save_own( - home, - name, - machine, - &OwnConnection::default(), - record.binding(), - )?; - Ok(connect::disconnected(name, Some(machine))) +/// `store.disconnect(store)`: forget a PostgreSQL Store, its saved login +/// and its attachments (its data stays), refused `InUse` while a process +/// holds it or a Sandbox of its projects exists. A sqlite Store is +/// `InvalidInput`, naming `store remove`. +pub fn disconnect(home: &Path, name: &StoreName) -> Outcome { + connect::disconnect(home, name, RELATED) } -/// `store.connect(store, url, { auth, machine, synchronous_commit })`. A -/// Store not connected yet is connected from this process (`--auth` -/// required, `--machine` refused). On a connected Store the URL becomes -/// the address every machine dials, proven from this process, or with -/// `machine` that machine's own, proven from that machine; either refuses -/// `--auth` and `--synchronous-commit`. A sqlite Store of the name is -/// `Exists`. -pub fn connect( - home: &Path, - events: &mut Events<'_>, - request: &StoreConnect, - machine: Option<&MachineName>, -) -> Outcome { - let name = request.store.as_str(); - let Some(record) = StoreRecord::read(home, name)? else { - if let Some(machine) = machine { - return Err(refused( - "InvalidInput", - format!( - "Store {name} is not connected: connect it first without --machine, then `layerfs store connect {name} --machine {machine}`" - ), - )); - } - return connect::connect(home, request); - }; - if record.kind()? != StoreKind::Postgresql { +/// `store.connect(store, url, { user, password, synchronous_commit })`: +/// a new PostgreSQL Store, or a connected one's address, login or setting, +/// checked from this process before anything is saved. +pub fn connect(home: &Path, request: &StoreConnect) -> Outcome { + connect::run(home, request) +} + +/// The PostgreSQL Store `name` a machine attaches to or detaches from: a +/// sqlite Store is `InvalidInput` naming `store move` (it lives on one +/// machine), and `native` (this computer, which every PostgreSQL Store is attached to) +/// is `InvalidInput`. +fn attachable(home: &Path, name: &StoreName, machine: &str) -> Result { + let record = StoreRecord::of(home, name)?; + if record.kind()? == StoreKind::Sqlite { + let on = record.machine().unwrap_or_default(); return Err(refused( - "Exists", - format!("a sqlite Store named {name} exists"), + "InvalidInput", + format!( + "Store {name} is a sqlite Store on machine {on}; machines attach to PostgreSQL Stores only, and `layerfs store move {name} {machine}` moves it" + ), )); } - let Some(machine) = machine.map(|m| m.as_str()) else { - return connect::readdress(home, request, &sandboxes_of(home, name)); - }; - if request.auth.is_some() { - let uses = record.text("auth").unwrap_or("no saved login"); + if machine == "native" { return Err(refused( "InvalidInput", - format!("a machine's own connection takes no --auth; {name} uses {uses}"), + format!("machine native is this computer, which every PostgreSQL Store is attached to; `layerfs store doctor {name}` checks it"), )); } - connect::refuse_settings(name, request)?; - connect::refuse_login_with_fix(name, &request.url, Some(&record), Some(machine))?; - connect::target(&request.url)?; + Ok(record) +} + +/// `store.attach(store, { machine })`: lets machine `machine` run Sandboxes +/// of PostgreSQL Store `store`. The machine must exist and its platform +/// run PostgreSQL Sandboxes; the Store is checked from it with the URL and +/// login this computer saved, as its Sandboxes dial them, before it is +/// recorded in the Store's `attached` and its reach observed. Attaching an +/// attached machine checks it again (`outcome: checked`, its reach +/// recorded either way). Answers `{ ok, outcome: attached | checked, +/// store, machine, latency_ms, server_version }`. +pub fn attach( + home: &Path, + events: &mut Events<'_>, + name: &StoreName, + machine: &MachineName, +) -> Outcome { + let machine = machine.as_str(); + let record = attachable(home, name, machine)?; runs_postgresql_sandboxes(home, name, machine)?; - let own = OwnConnection { - url: Some(request.url.clone()), - }; - let trial = record.clone().with_own_connection(machine, &own); - let checked = check_from(home, events, &trial, machine).1?; - check::save_own(home, &request.store, machine, &own, record.binding())?; - // its check is what was seen of the machine's reach (spec v23 V23-2) - let seen = layerfs_store::observed::Reach::of(&Ok(checked)); - layerfs_store::observed::record(home, name, Some(machine), &seen); - let saved = StoreRecord::of(home, name)?; - Ok(connect::answer( - &saved, - "updated", - None, - &sandboxes_of(home, name), - )) + let attached = record.is_attached(machine); + let checked = check_from(home, events, &record, machine).1; + if attached || checked.is_ok() { + let seen = layerfs_store::observed::Reach::of(&checked); + layerfs_store::observed::record(home, name, Some(machine), &seen); + } + let checked = checked?; + let new = check::attach(home, name, machine, record.binding())?; + let outcome = if new { "attached" } else { "checked" }; + let copied = |key: &str| checked.get(key).cloned().unwrap_or_default(); + Ok(SdkValue::map([ + ("ok", SdkValue::Bool(true)), + ("outcome", SdkValue::text(outcome)), + ("store", SdkValue::text(name.as_str())), + ("machine", SdkValue::text(machine)), + ("latency_ms", copied("latency_ms")), + ("server_version", copied("server_version")), + ])) +} + +/// `store.detach(store, { machine })`: machine `machine` no longer runs +/// Sandboxes of PostgreSQL Store `store`, and its reach is forgotten. +/// Refused `InUse` while a Sandbox of the Store's projects is on it, +/// `NotFound` when it is not attached. Answers `{ ok, outcome: detached, +/// store, machine }`. +pub fn detach(home: &Path, name: &StoreName, machine: &MachineName) -> Outcome { + let machine = machine.as_str(); + attachable(home, name, machine)?; + let idle = |home: &Path| inventory::store_idle_on(home, name, machine); + check::detach(home, name, machine, &idle)?; + Ok(SdkValue::map([ + ("ok", SdkValue::Bool(true)), + ("outcome", SdkValue::text("detached")), + ("store", SdkValue::text(name.as_str())), + ("machine", SdkValue::text(machine)), + ])) +} + +/// The refusal of a call naming machine `machine` for PostgreSQL Store +/// `store` it is not attached to, with the attach as its fix. +pub fn not_attached(store: &str, machine: &str) -> SdkRefusal { + with_fix( + refused( + "InvalidInput", + format!("machine {machine} is not attached to PostgreSQL Store {store}"), + ), + format!( + "layerfs store attach {} --machine {}", + shell_word(store), + shell_word(machine) + ), + ) } /// Refused unless machine `machine` exists and its platform runs @@ -284,8 +277,8 @@ fn from_machine( } /// The check of machine `machine`'s connection to PostgreSQL Store -/// `record` (its own connection where the record names one, else the -/// Store's), run from that machine: in this process, or in its worker as +/// `record` (the Store's URL with its login), run from that machine: in +/// this process, or in its worker as /// `store.reach`. The URL is built as the machine's Sandboxes' calls build /// it. Answers the check, `{ at, server_version, latency_ms }`, or its /// refusal; either way with the host it dialled, once known. @@ -308,8 +301,8 @@ pub(crate) fn check_from( }; // the host named is read from the address the machine dials, with no // login: the URL dialled holds the password - let address = layerfs_store::record::address_on(record, machine).unwrap_or_default(); - let host = match connect::target(&address) { + let address = record.text("url").unwrap_or_default(); + let host = match connect::target(address) { Ok((host, _, _)) => host, Err(refusal) => return (None, Err(refusal)), }; @@ -341,8 +334,7 @@ pub(crate) fn check_from( /// `store.reach` in a machine's worker: `{ store, store_record, postgresql }` /// from the caller, which put the saved login into the URL this machine -/// dials. Answers the check `store.connect --machine` and `store.doctor` -/// ask for. +/// dials. Answers the check `store.attach` and `store.doctor` ask for. pub fn reach_in_worker(args: &SdkValue) -> Outcome { let store = args.get_text("store").unwrap_or(""); StoreName::parse(store)?; diff --git a/control/crates/layerfs-control/src/worker_server/ops.rs b/control/crates/layerfs-control/src/worker_server/ops.rs index 23b7a4e870..f30f410bfa 100644 --- a/control/crates/layerfs-control/src/worker_server/ops.rs +++ b/control/crates/layerfs-control/src/worker_server/ops.rs @@ -118,7 +118,7 @@ pub(super) fn run( crate::doctor::NETWORK_OP => crate::doctor::inspect_network_in_worker(root), "store.diagnose" => crate::doctor::diagnose_store_in_worker(root, args, events), // the check of this machine's connection to a PostgreSQL Store - // (`store.update`): the caller sends the record and + // (`store.attach`, `store.doctor`): the caller sends the record and // what it dials "store.reach" => crate::store::reach_in_worker(&args), // one Store call, on the Store file under this worker's root (2.0) diff --git a/control/crates/layerfs-control/tests/in_use_detail.rs b/control/crates/layerfs-control/tests/in_use_detail.rs index 44a2e4a59e..be250e38ae 100644 --- a/control/crates/layerfs-control/tests/in_use_detail.rs +++ b/control/crates/layerfs-control/tests/in_use_detail.rs @@ -51,7 +51,7 @@ fn store_disconnect_names_another_process_s_lease() { ) .unwrap(); let name = layerfs_home::names::StoreName::parse("g").unwrap(); - let refusal = refused(|_| layerfs_control::store::disconnect(&home, &name, None)); + let refusal = refused(|_| layerfs_control::store::disconnect(&home, &name)); let _ = holder.kill(); let _ = holder.wait(); assert_eq!(refusal.code, "InUse", "{refusal:?}"); diff --git a/control/crates/layerfs-platform/src/reach.rs b/control/crates/layerfs-platform/src/reach.rs index d4685a3ac4..be1041db48 100644 --- a/control/crates/layerfs-platform/src/reach.rs +++ b/control/crates/layerfs-platform/src/reach.rs @@ -3,8 +3,8 @@ //! machine: LayerFS rewrites no part of it and inspects no port (owner, //! 2026-11-24). A machine that does not share the caller's loopback //! refuses a URL naming that loopback, or a Unix socket of the caller, -//! naming what the machine calls this host and the per-machine URL -//! instead. Each platform's adapter declares its [`Loopback`]. +//! naming what the machine calls this host, with which the Store is +//! connected again (every machine dials the one URL this computer saved). Each platform's adapter declares its [`Loopback`]. //! //! The URL may hold the Store's password: no message here holds any part //! of it but a loopback host. @@ -41,7 +41,7 @@ pub(crate) fn dial( "its URL is not one postgres://[user@]host[:port][,host[:port]...]/... URL its client reads, so the machine cannot check that it does not name this host's loopback", ) })?; - let advice = advice(spec, store, &this_host); + let advice = advice(store, &this_host); if hosts .iter() .any(|host| layerfs_sandbox_backend::socket(host)) @@ -86,15 +86,16 @@ pub(crate) fn hint(spec: &Spec, (store, url): (&str, &str), loopback: Loopback) "if its host is a loopback address on the {} machine {} (a hosts entry can make a name one), the machine does not share this host's loopback; {}", spec.kind.name(), spec.name, - advice(spec, store, &this_host) + advice(store, &this_host) )) } -/// What to give a machine that does not share the caller's loopback. -fn advice(spec: &Spec, store: &str, this_host: &str) -> String { +/// What to do for a machine that does not share the caller's loopback: +/// every machine dials the URL this computer saved, so the Store is +/// connected again with an address the machine reaches. +fn advice(store: &str, this_host: &str) -> String { format!( - "give the Store a host the machine reaches ({this_host}), or give the machine its own URL with `layerfs store connect {store} --machine {}`", - spec.name + "connect the Store again with an address the machine reaches ({this_host}): `layerfs store connect {store} `" ) } diff --git a/control/crates/layerfs-platform/src/setup/calls.rs b/control/crates/layerfs-platform/src/setup/calls.rs index 07709664f6..c4bf90b852 100644 --- a/control/crates/layerfs-platform/src/setup/calls.rs +++ b/control/crates/layerfs-platform/src/setup/calls.rs @@ -222,8 +222,9 @@ pub fn load_image(spec: &Spec, archive: &Path) -> Result { /// caller's loopback (`docker` on Docker Desktop, `lima`, /// `apple-container`) refuses a loopback host `Unsupported`, naming what it /// calls this host (`host.docker.internal`, `host.lima.internal`, the -/// network's gateway) and `layerfs store connect --machine -/// `; `native` and `docker` on a Linux Engine share it. Starts +/// network's gateway), with which `layerfs store connect ` +/// connects the Store again; `native` and `docker` on a Linux Engine share +/// it. Starts /// nothing; no message holds any part of the URL but a loopback host. pub fn reach(spec: &Spec, store: &str, url: &str) -> Result { spec.validate()?; diff --git a/control/crates/layerfs-platform/tests/conformance.rs b/control/crates/layerfs-platform/tests/conformance.rs index 52186ccca4..61651708b6 100644 --- a/control/crates/layerfs-platform/tests/conformance.rs +++ b/control/crates/layerfs-platform/tests/conformance.rs @@ -14,7 +14,7 @@ //! - `reach` against the §7.3 rules (owner, 2026-11-24): every URL is //! dialled exactly as given, never rewritten, and no provider tool runs; //! a loopback host the machine does not share is refused, naming the -//! machine's name for this host and `store connect --machine`; no error +//! machine's name for this host and `store connect `; no error //! text or `Debug` holds the password; //! - `forward` (#535 G4): a daemon's port is used as it is, carried by a //! detached `ssh -L 127.0.0.1::127.0.0.1:` that @@ -441,7 +441,7 @@ fn each_platform_reaches_a_loopback_server_as_it_declares() { assert!(message.contains("loopback"), "{message}"); assert!(message.contains(name), "{message}"); assert!( - message.contains("layerfs store connect pg --machine dev"), + message.contains("`layerfs store connect pg `"), "{message}" ); } diff --git a/control/crates/layerfs-platform/tests/machine_reach.rs b/control/crates/layerfs-platform/tests/machine_reach.rs index db5b51751f..0d70adaec9 100644 --- a/control/crates/layerfs-platform/tests/machine_reach.rs +++ b/control/crates/layerfs-platform/tests/machine_reach.rs @@ -2,7 +2,7 @@ //! Sandbox daemon on each platform dials, which is the URL as configured, //! never rewritten. A machine that does not share the caller's loopback //! (docker on Docker Desktop, lima, apple-container) refuses a loopback host, -//! naming its own name for this host and `store connect --machine`; +//! naming its own name for this host and `store connect `; //! every other URL is passed on as given, `sslmode=verify-full` included //! (a reach input only: the Store's client reads `sslmode` disable, prefer //! or require, and `store connect` refuses `verify-full`). Hosts @@ -26,8 +26,9 @@ fn reach(spec: &Spec, url: &str) -> Result { machine::reach(spec, STORE, url) } -/// The per-machine URL call every refusal on machine `dev` advises. -const CONNECT: &str = "`layerfs store connect pg --machine dev`"; +/// The connect every refusal on machine `dev` advises: the Store again, +/// with an address the machine reaches. +const CONNECT: &str = "`layerfs store connect pg `"; /// `getent ahostsv4 host.docker.internal` in a Docker Desktop worker /// container (D-8 live receipt), which the former lookup ran per call. @@ -230,7 +231,7 @@ fn a_failed_dial_carries_the_loopback_hint_where_it_is_not_shared() { assert!(hint.contains(CONNECT), "{hint}"); // the same advice as the up-front refusal let (_, message) = refused(reach(&spec, &loopback_urls()[0])); - let advice = &hint[hint.find("give the Store").unwrap()..]; + let advice = &hint[hint.find("connect the Store again").unwrap()..]; assert!(message.ends_with(advice), "{message} / {hint}"); } assert_eq!(scratch.log(), "", "no provider tool runs"); diff --git a/control/crates/layerfs-sandbox/src/create.rs b/control/crates/layerfs-sandbox/src/create.rs index 9f1226ad5c..250e5a437b 100644 --- a/control/crates/layerfs-sandbox/src/create.rs +++ b/control/crates/layerfs-sandbox/src/create.rs @@ -56,8 +56,9 @@ pub struct Created { } /// Starts the Sandbox: with no `machine`, on a sqlite Store's machine, or -/// `native` for a PostgreSQL Store (#536 §10), which runs on any machine -/// whose platform runs PostgreSQL Sandboxes. +/// `native` for a PostgreSQL Store (#536 §10), which also runs on each +/// machine attached to it (`store.attach`) whose platform runs PostgreSQL +/// Sandboxes. pub fn create( home: &Path, events: &mut Events<'_>, @@ -120,9 +121,27 @@ pub fn create( if layerfs_machine::record::MachineRecord::read(&home, machine)?.is_none() { return Err(refused("NotFound", format!("no machine named {machine}"))); } - // a PostgreSQL Store is on no machine: its Sandboxes run on any machine - // the support table allows, each dialling the server with its own - // connection or the Store's, and the create's reach check proves it can + // a PostgreSQL Store is on no machine: its Sandboxes run on this + // computer (`native`) and on each machine attached to it, each dialling + // the URL and login this computer saved; the create's reach check + // proves it can + if let StoreRef::Postgres { .. } = target.store_ref { + if machine != "native" && !target.record.is_attached(machine) { + let refusal = refused( + "InvalidInput", + format!( + "machine {machine} is not attached to PostgreSQL Store {}", + target.store + ), + ); + let attach = format!( + "layerfs store attach {} --machine {}", + shell_word(&target.store), + shell_word(machine) + ); + return Err(with_fix(refusal, attach)); + } + } if let StoreRef::Sqlite { .. } = target.store_ref { let store_machine = target.store_ref.machine()?; if store_machine != machine { diff --git a/control/crates/layerfs-sandbox/src/route.rs b/control/crates/layerfs-sandbox/src/route.rs index 3575660731..864bad3960 100644 --- a/control/crates/layerfs-sandbox/src/route.rs +++ b/control/crates/layerfs-sandbox/src/route.rs @@ -89,8 +89,8 @@ enum RunRoot { } /// A PostgreSQL Store's `postgresql` argument for a Sandbox on `machine` -/// (#535 §7.4): the URL the machine's own connection names, else the record's, -/// with its password, resolved here in the caller and dialled as it is: a +/// (#535 §7.4): the record's URL with its login, resolved here in the +/// caller and dialled as it is: a /// loopback host the machine does not share is refused, nothing is /// rewritten and no machine is asked (`layerfs_machine::platform::reach`). /// It travels only in the one request that runs the call and is never @@ -99,8 +99,8 @@ enum RunRoot { /// when the machine does not share this host's loopback and the URL names /// a host by name (`layerfs_machine::platform::loopback_hint`): a name /// resolving to a loopback address there fails its one dial, never -/// resolved here to be refused up front. `store.update` and `store.status` -/// build their check's argument here too. +/// resolved here to be refused up front. `store.attach` and +/// `store.doctor` build their check's argument here too. pub fn reached( home: &Path, machine: &str, @@ -119,7 +119,7 @@ fn dialled( machine: &str, record: &StoreRecord, ) -> Result)>> { - let url = layerfs_store::record::url_on(record, machine)?; + let url = layerfs_store::record::url(record)?; // a build without machines (the guest's) runs its own Sandboxes on the // machine it is, which shares its loopback #[cfg(feature = "machine")] diff --git a/control/crates/layerfs-store/src/get.rs b/control/crates/layerfs-store/src/get.rs index 74cfcc774b..937878e70f 100644 --- a/control/crates/layerfs-store/src/get.rs +++ b/control/crates/layerfs-store/src/get.rs @@ -5,9 +5,11 @@ //! //! The answer is one full map, the long form's keys: the dispatcher makes //! the short form from it. A sqlite Store answers `machine`, `profile` and -//! `sqlite_version`; a PostgreSQL Store `auth`, `binding`, `connections` -//! (every side that connects, spec v23) and `synchronous_commit`; the -//! other engine's keys are null. +//! `sqlite_version`; a PostgreSQL Store `url`, `user`, `password_saved`, +//! `password_changed_at`, `binding`, `synchronous_commit`, `reach` (this +//! computer's last) and `machines` (the attached machines: rows with +//! their reach in `store.get`, names in a `store.list` item); the other +//! engine's keys are null. The password is never answered. use crate::backup::record::StoreLink; use crate::intent; use crate::record::{StoreRecord, StoreRef}; @@ -31,17 +33,6 @@ pub struct With { pub stats: bool, } -/// Every Sandbox's `(store, machine)`, read by the caller from the -/// Sandbox records (which this crate sits below): who connects to a -/// PostgreSQL Store from a machine with no address or reach of its own. -pub type Sandboxes<'a> = &'a dyn Fn(&Path) -> Vec<(String, String)>; - -/// The machines with a Sandbox of Store `store` among `pairs`. -pub fn sandbox_machines(pairs: &[(String, String)], store: &str) -> Vec { - let on = pairs.iter().filter(|(of, _)| of == store); - on.map(|(_, machine)| machine.clone()).collect() -} - /// `ms` since 1970 as an answer's time, null when unknown. pub(crate) fn at(ms: Option) -> SdkValue { ms.map_or(SdkValue::Null, |ms| SdkValue::Text(time::iso(ms))) @@ -137,15 +128,16 @@ pub fn project_names(home: &Path, store: &str) -> Result> { /// Store `record` as `store.get` and a `store.list` item answer it, in /// `state`: every long-form key. `observed_at` is the state's own when it /// is `unknown`, else when the Store was last read live (`observed`). -/// `sandboxes` are the machines with a Sandbox of it. A PostgreSQL Store's -/// `binding` is the first 8 bytes of its id as 16 hex, the open-Store -/// cache's key (spec v23 V23-5). +/// `rows` answers a PostgreSQL Store's `machines` as rows (`store.get`), +/// else as names (a `store.list` item). A PostgreSQL Store's `binding` is +/// the first 8 bytes of its id as 16 hex, the open-Store cache's key (spec +/// v23 V23-5). pub fn summary( home: &Path, record: &StoreRecord, state: &State, observed: Option, - sandboxes: &[String], + rows: bool, ) -> Result { let store = record.name(); let projects = project_names(home, store)?; @@ -158,6 +150,13 @@ pub fn summary( }; let only = |yes: bool, value: SdkValue| if yes { value } else { SdkValue::Null }; let postgresql = engine == "postgresql"; + let pg_text = |key: &str| only(postgresql, SdkValue::opt_text(record.text(key))); + // a URL that may hold a login is never shown + let url = record.text("url").map(crate::postgresql::connect::shown); + let (saved, changed) = match postgresql { + true => crate::postgresql::connect::password_changed(record), + false => (false, SdkValue::Null), + }; let links = record.links(); let backups = links.iter().map(|(bucket, link)| backup_row(bucket, link)); let mut fields: Vec<(&str, SdkValue)> = vec![ @@ -171,10 +170,10 @@ pub fn summary( fields.extend([ // a sqlite Store's machine; null for a PostgreSQL Store ("machine", SdkValue::opt_text(state::placed(record))), - ( - "auth", - SdkValue::opt_text(crate::postgresql::login::auth_of(record)), - ), + ("url", only(postgresql, SdkValue::opt_text(url))), + ("user", pg_text("user")), + ("password_saved", only(postgresql, SdkValue::Bool(saved))), + ("password_changed_at", changed), ( "binding", only( @@ -185,10 +184,14 @@ pub fn summary( ), ), ( - "connections", + "reach", + only(postgresql, crate::postgresql::connect::reach(record)), + ), + ( + "machines", only( postgresql, - crate::postgresql::connect::connections(record, sandboxes), + crate::postgresql::connect::machines(record, rows), ), ), ("projects", shown), @@ -198,13 +201,7 @@ pub fn summary( "profile", only(sqlite, SdkValue::opt_text(crate::record::profile(record))), ), - ( - "synchronous_commit", - only( - postgresql, - SdkValue::opt_text(record.text("synchronous_commit")), - ), - ), + ("synchronous_commit", pg_text("synchronous_commit")), ( "sqlite_version", only(sqlite, SdkValue::opt_text(record.text("sqlite"))), @@ -224,7 +221,7 @@ pub fn get( events: &mut Events<'_>, store: &str, with: With, - (machines, sandboxes): (state::Machines, Sandboxes), + machines: state::Machines, ) -> Outcome { let record = StoreRecord::of(home, store)?; let (record, state, observed, live) = match with.live { @@ -242,8 +239,7 @@ pub fn get( ) } }; - let on = sandbox_machines(&sandboxes(home), store); - let mut answer = summary(home, &record, &state, observed, &on)?; + let mut answer = summary(home, &record, &state, observed, true)?; if let SdkValue::Map(fields) = &mut answer { if let Some(live) = live { fields.push(("live".to_owned(), live)); diff --git a/control/crates/layerfs-store/src/list.rs b/control/crates/layerfs-store/src/list.rs index 3ade214903..91bcc26a8f 100644 --- a/control/crates/layerfs-store/src/list.rs +++ b/control/crates/layerfs-store/src/list.rs @@ -45,13 +45,7 @@ fn size(home: &Path, record: &StoreRecord, unanswered: &mut Vec) -> SdkV /// `store.list`: every Store, or with `machine` only the sqlite Stores on /// that machine, each with its records-only state; with `stats`, each /// item's `size`. -pub fn list( - home: &Path, - machine: Option<&str>, - stats: bool, - (machines, sandboxes): (state::Machines, crate::get::Sandboxes), -) -> Outcome { - let pairs = sandboxes(home); +pub fn list(home: &Path, machine: Option<&str>, stats: bool, machines: state::Machines) -> Outcome { let mut derived: BTreeMap = BTreeMap::new(); let mut unanswered = Vec::new(); let mut items = Vec::new(); @@ -71,8 +65,7 @@ pub fn list( }; let state = state::recorded_under(&record, under)?; let observed = observed::read(&paths::store_record(home, record.name())); - let on = crate::get::sandbox_machines(&pairs, record.name()); - let mut item = summary(home, &record, &state, observed, &on)?; + let mut item = summary(home, &record, &state, observed, false)?; if let (true, SdkValue::Map(fields)) = (stats, &mut item) { fields.push(("size".to_owned(), size(home, &record, &mut unanswered))); } diff --git a/control/crates/layerfs-store/src/observed.rs b/control/crates/layerfs-store/src/observed.rs index f19568a155..dc402277ff 100644 --- a/control/crates/layerfs-store/src/observed.rs +++ b/control/crates/layerfs-store/src/observed.rs @@ -106,10 +106,10 @@ pub fn seen_at(home: &Path, store: &str, ms: i64) { } } -/// The key `machine`'s reach of `record` is kept under: none for this -/// computer's (`native` without an address of its own). -fn from<'a>(record: &StoreRecord, machine: Option<&'a str>) -> Option<&'a str> { - machine.filter(|m| *m != "native" || record.own_connection(m).is_some()) +/// The key `machine`'s reach is kept under: none for this computer's +/// (`native`'s too). +fn from(machine: Option<&str>) -> Option<&str> { + machine.filter(|m| *m != "native") } /// Records what `machine` (none: this computer) saw dialling PostgreSQL @@ -120,7 +120,7 @@ pub fn record(home: &Path, store: &str, machine: Option<&str>, reach: &Reach) { return Ok(()); } let entry = reach.to_record(now_ms()); - match from(record, machine) { + match from(machine) { None => observed::merge(file, HERE, entry), Some(machine) => { let machines = reaches(&observed::fields(file)); diff --git a/control/crates/layerfs-store/src/postgresql/address.rs b/control/crates/layerfs-store/src/postgresql/address.rs index 776dfc5b1c..8025655a4f 100644 --- a/control/crates/layerfs-store/src/postgresql/address.rs +++ b/control/crates/layerfs-store/src/postgresql/address.rs @@ -5,7 +5,7 @@ //! record keeps it byte for byte until the user connects an address //! holding none. Any other URL is shown and stored exactly as written. A //! URL is dialled only when it is an address alone ([`refuse_login`]), with -//! the saved login put in and read back by the client ([`with_login`]): +//! the Store's login put in and read back by the client ([`with_login`]): //! tokio-postgres 0.7, [`layerfs_persistence::PostgresConfig`], the reading //! every Store session dials with. use layerfs_bridge::control::SdkRefusal; @@ -20,11 +20,11 @@ type Result = std::result::Result; pub const HIDDEN: &str = "postgresql://"; /// The refusal of a URL holding a login (spec v23 V23-13). -const LOGIN: &str = "the URL names a user or holds a password (or a password file); give the address alone and the login with --auth (`layerfs store save-auth` saves one)"; +const LOGIN: &str = "the URL names a user or holds a password (or a password file); give the address alone and the login with --user and --password-stdin"; /// The refusal of a URL the client does not read, when no key or value /// of it can be named ([`unread`]). -const UNREAD: &str = "the URL is not one its PostgreSQL client reads, or names a user or holds a password (or a password file) under a key it does not know: give the address alone, postgresql://host[:port][,host[:port]...]/database?key=value&... with keys the client knows (not `passfile`, `sslpassword`, `sslkey` or `sslcert`), and the login with --auth (`layerfs store save-auth` saves one)"; +const UNREAD: &str = "the URL is not one its PostgreSQL client reads, or names a user or holds a password (or a password file) under a key it does not know: give the address alone, postgresql://host[:port][,host[:port]...]/database?key=value&... with keys the client knows (not `passfile`, `sslpassword`, `sslkey` or `sslcert`), and the login with --user and --password-stdin"; /// What a refusal of a URL holding a `#` ends with. const HASH: &str = "; a `#` that is part of the address is written %23"; @@ -227,7 +227,7 @@ fn unread(scheme: &str, after: &str) -> String { }; if let Some(pair) = pairs.iter().copied().find(as_login) { return match UNREAD_LOGIN_KEYS.iter().find(|login| **login == key(pair)) { - Some(login) => format!("the URL names a user or holds a password (or a password file) in `{login}`, which its PostgreSQL client does not read; give the address alone and the login with --auth (`layerfs store save-auth` saves one)"), + Some(login) => format!("the URL names a user or holds a password (or a password file) in `{login}`, which its PostgreSQL client does not read; give the address alone and the login with --user and --password-stdin"), None => LOGIN.to_owned(), }; } diff --git a/control/crates/layerfs-store/src/postgresql/check.rs b/control/crates/layerfs-store/src/postgresql/check.rs index fedfbfbc0b..2bf6f2c7e4 100644 --- a/control/crates/layerfs-store/src/postgresql/check.rs +++ b/control/crates/layerfs-store/src/postgresql/check.rs @@ -1,15 +1,13 @@ -//! A PostgreSQL Store's connection, checked from the side that dials it. -//! A Store's Sandboxes run on any machine whose platform runs PostgreSQL -//! Sandboxes (supersedes the per-machine attachments of 2026-11-12; #536 -//! C4 again): each dials the Store's address, or its own where -//! `store.connect --machine` gave it one, kept in the Store's record as -//! `machines.`, always with the Store's saved login. This module is the Store's part: the check run on -//! the side that dials, and the record writes. Which side dials, and the -//! URL a machine dials, are the caller's (`layerfs-control`, through the -//! Sandbox route). +//! A PostgreSQL Store's connection, checked from the side that dials it +//! (owner, 2026-11-24): the host saves a Store's URL and login, and a +//! machine attached to the Store (`store.attach`, its record's +//! `attached`) runs its Sandboxes, dialling that URL with that login; no +//! machine has an address of its own. This module is the Store's part: the +//! check run on the side that dials, and the attachment writes. Which side +//! dials is the caller's (`layerfs-control`, through the Sandbox route). use crate::open_args::PgSelection; use crate::postgresql::connect::SCHEMA; -use crate::record::{OwnConnection, StoreKind, StoreRecord}; +use crate::record::{StoreKind, StoreRecord}; use layerfs_bridge::control::{SdkRefusal, SdkValue}; use layerfs_home::home; use layerfs_home::names::StoreName; @@ -103,40 +101,73 @@ pub fn same_store(record: &StoreRecord, postgresql: &PgSelection) -> Result<()> Ok(()) } -/// Saves `machine`'s own address of Store `name` (an empty one removes -/// it, and forgets its reach observations), under the home lock and the -/// Store's: `Conflict` when the Store was disconnected, or connected again -/// to another database (`binding` differs), since it was read. Nothing else -/// of the record changes: no URL is rewritten (a Store address that may -/// hold a login stays byte for byte), and no old field is dropped. -pub fn save_own( +/// The record of Store `name` under the home lock and the Store's, read +/// again: `Conflict` when the Store was disconnected, or connected again to +/// another database (`binding` differs), since it was read. +fn current( + home_dir: &Path, + name: &str, + binding: Option<&[u8]>, + doing: &str, +) -> Result { + let record = StoreRecord::read(home_dir, name)?.filter(|r| r.binding() == binding); + record.ok_or_else(|| { + refused( + "Conflict", + format!("Store {name} changed while {doing}; run the call again"), + ) + }) +} + +/// Attaches `machine` to Store `name`, checked meanwhile, under the home +/// lock and the Store's: whether it was not attached before. Nothing else +/// of the record changes. +pub fn attach( home_dir: &Path, name: &StoreName, machine: &str, - own: &OwnConnection, binding: Option<&[u8]>, +) -> Result { + let _lock = home::lock::take(home_dir)?; + let _store = crate::record::lock(home_dir, name)?; + let doing = format!("machine {machine} was checked"); + let record = current(home_dir, name, binding, &doing)?; + if record.is_attached(machine) { + return Ok(false); + } + record.with_attached(machine, true).write(home_dir)?; + Ok(true) +} + +/// Detaches `machine` from Store `name` and forgets its reach, under the +/// home lock and the Store's, once `idle` (run under both: no Sandbox of +/// the Store is on the machine) allows it. `NotFound` when it is not +/// attached. +pub fn detach( + home_dir: &Path, + name: &StoreName, + machine: &str, + idle: &dyn Fn(&Path) -> Result<()>, ) -> Result<()> { let _lock = home::lock::take(home_dir)?; let _store = crate::record::lock(home_dir, name)?; - let record = StoreRecord::read(home_dir, name)?.filter(|r| r.binding() == binding); - let Some(record) = record else { + let record = StoreRecord::of(home_dir, name)?; + if !record.is_attached(machine) { return Err(refused( - "Conflict", - format!("Store {name} changed while machine {machine} was checked; connect it again"), + "NotFound", + format!("machine {machine} is not attached to Store {name}"), )); - }; - record.with_own_connection(machine, own).write(home_dir)?; - if own.is_empty() { - crate::observed::forget_locked(home_dir, name, machine)?; } + idle(home_dir)?; + record.with_attached(machine, false).write(home_dir)?; + crate::observed::forget_locked(home_dir, name, machine)?; Ok(()) } /// Forgets machine `machine` in every PostgreSQL Store of the home (its -/// `machine.remove`): its own connection and its reach observations, the -/// rest of each record as it was (no URL rewritten); a later machine of the -/// same name dials each Store's connection and was never seen. Under the -/// home lock and each Store's. +/// `machine.remove`): its attachment and its reach observations, the rest +/// of each record as it was; a later machine of the same name is attached +/// to none. Under the home lock and each Store's. pub fn forget_machine(home_dir: &Path, machine: &str) -> Result<()> { let _lock = home::lock::take(home_dir)?; for record in crate::record::stores(home_dir)? { @@ -144,8 +175,8 @@ pub fn forget_machine(home_dir: &Path, machine: &str) -> Result<()> { continue; } let _store = crate::record::lock(home_dir, record.name())?; - if record.own_connection(machine).is_some() { - let record = record.clone().without_own_connection(machine); + if record.is_attached(machine) { + let record = record.clone().with_attached(machine, false); record.write(home_dir)?; } crate::observed::forget_locked(home_dir, record.name(), machine)?; diff --git a/control/crates/layerfs-store/src/postgresql/connect.rs b/control/crates/layerfs-store/src/postgresql/connect.rs index eeb6bb2692..8a09d82fcd 100644 --- a/control/crates/layerfs-store/src/postgresql/connect.rs +++ b/control/crates/layerfs-store/src/postgresql/connect.rs @@ -1,12 +1,13 @@ -//! PostgreSQL Stores (#533 step 10a, call surface 2.0 `pg.html`): `store -//! connect` records a database as a Store in the fixed `layerfs` schema, -//! or sets the address every machine dials; `store disconnect` forgets it -//! (its data stays). The record keeps the URL as given, an address alone -//! with no user and no password, and names its saved login (`auth`, -//! [`super::login`]), put into the URL on each call; the full URL is never -//! written down, and no recorded URL is ever rewritten. A machine's own address -//! is `layerfs-control`'s part of the call, proven from that machine. -use super::address; +//! PostgreSQL Stores (#533 step 10a; owner, 2026-11-24): `store connect` +//! records a database as a Store in the fixed `layerfs` schema, or changes +//! a connected Store's address, user, password or `synchronous_commit`; +//! `store disconnect` forgets it (its data stays). The host is the one +//! place a Store's URL and login are saved: the record keeps the URL as +//! given, an address alone, and the user; the password is a secret of the +//! home ([`super::login`]), put into the URL on each call. The full URL is +//! never written down, and no recorded URL is ever rewritten. Machines +//! attach to a Store (`layerfs-control`'s `store.attach`) and dial both. +use super::address::{self, with_login}; pub use super::address::{holds_login, refuse_login, shown, target, HIDDEN}; use super::login; use crate::open_args::{OpenArgs, PgSelection}; @@ -27,13 +28,12 @@ type Result = std::result::Result; /// The one schema a 2.0 PostgreSQL Store lives in. pub const SCHEMA: &str = "layerfs"; -/// What a call on Store `record` dials: its URL with its saved login. +/// What a call on Store `record` dials: its URL with its login. pub fn selection(record: &StoreRecord) -> Result { Ok(selection_at(record, url(record)?)) } -/// [`selection`] dialling `url`: an address of the record with its login -/// in it, as a machine reaches it (#535 §7.4). +/// [`selection`] dialling `url`, the record's address with a login in it. pub fn selection_at(record: &StoreRecord, url: String) -> PgSelection { PgSelection { url: Some(url), @@ -47,49 +47,37 @@ pub fn selection_at(record: &StoreRecord, url: String) -> PgSelection { } } -/// `store.connect(store, url, { auth, synchronous_commit })` without a -/// machine: a Store's first connect, or a new address every machine dials. -#[derive(Clone, Debug)] +/// `store.connect(store, url, { user, password, synchronous_commit })`. +/// No `Debug`: it holds the password. +#[derive(Clone)] pub struct StoreConnect { /// The Store's name. pub store: StoreName, - /// The database's URL, with no user and no password. + /// The database's URL, an address alone: no user, no password. pub url: String, - /// The saved login; required on the first connect, refused afterwards. - pub auth: Option, - /// `synchronous_commit`, `local` by default; first connect only. + /// The PostgreSQL role; required for a new Store, else the saved one. + pub user: Option, + /// Its password; required for a new Store, else the saved one. + pub password: Option, + /// `synchronous_commit`; `local` for a new Store, else the saved one. pub synchronous_commit: Option, } /// [`refuse_login`]'s refusal for `store connect `, with its -/// fix (spec v23 V23-13), which names the address `` and the user -/// ``, never text of the URL. A URL that may hold a login -/// ([`holds_login`]) is connected as the address alone with a saved login: -/// on a first connect (`connected` none) the login saved and named with -/// `--auth`; on a connected Store, which takes no `--auth` on connect, the -/// steps that leave it naming the saved login ([`login::login_fix`]), then -/// the address alone (for `machine`'s own connection when given). One -/// refused only for a `#` holds no login: its fix is the connect of the -/// address alone, saving none. -pub fn refuse_login_with_fix( - store: &str, - url: &str, - connected: Option<&StoreRecord>, - machine: Option<&str>, -) -> Result<()> { +/// fix, which names the address `` and the user ``, never text +/// of the URL: the address alone, the login given apart (`new`: the +/// Store's first connect, which needs it; on a connected Store only when +/// the URL may hold one). +pub fn refuse_url(store: &str, url: &str, new: bool) -> Result<()> { // a URL that is not a PostgreSQL one is refused without a fix: its login // cannot be told apart, so no line may repeat it address::scheme(url)?; refuse_login(url).map_err(|refusal| { - let name = shell_word(store); - let on = machine.map_or(String::new(), |m| format!(" --machine {}", shell_word(m))); - let connect = format!("layerfs store connect {name} {on}"); - let fix = match (holds_login(url), connected) { - (true, None) => format!("{} && {connect} --auth ", login::SAVE), - (false, None) => format!("{connect} --auth "), - (true, Some(record)) => login::login_fix(record, &connect), - (false, Some(_)) => connect, + let login = match new || holds_login(url) { + true => " --user --password-stdin", + false => "", }; + let fix = format!("layerfs store connect {} {login}", shell_word(store)); with_fix(refusal, fix) }) } @@ -129,84 +117,47 @@ pub fn unclaimed_by_others(home: &Path, name: &str, binding: &[u8]) -> Result<() Ok(()) } -/// Every side that connects to PostgreSQL Store `record` (spec v23 -/// V23-3), as answers show them: this computer first (`machine` null, the -/// Store's address), then by name each machine with an address of its own, -/// a reach seen from it ([`crate::observed`]) or a Sandbox of the Store -/// (`sandboxes`, the machines the caller found). `native` without an -/// address of its own dials as this computer does and is its row. Each row -/// is `{ machine, url, own, server, reached, reach }`: the URL it dials -/// (no login), whether it is its own, the `{ host, port, database }` it -/// names, and the last reach seen with its word (`ok`, `failed`, null). -pub fn connections(record: &StoreRecord, sandboxes: &[String]) -> SdkValue { +/// This computer's last reach of PostgreSQL Store `record`, `{ at, ok, +/// latency_ms, server_version, error }`, or null when none was seen. +pub fn reach(record: &StoreRecord) -> SdkValue { + let seen = (record.home()).map(|home| crate::observed::read(home, record.name())); + seen.and_then(|seen| seen.here).unwrap_or_default() +} + +/// The machines attached to PostgreSQL Store `record`, as answers show +/// them: with `rows`, `{ machine, reached, reach }` each, the last reach +/// seen from it and its word (`ok`, `failed`, null); else their names. +pub fn machines(record: &StoreRecord, rows: bool) -> SdkValue { + let attached = record.attached(); + if !rows { + return SdkValue::List(attached.iter().map(SdkValue::text).collect()); + } let seen = (record.home()) .map(|home| crate::observed::read(home, record.name())) .unwrap_or_default(); - let own = record.own_connections(); - let own_url = |machine: &str| { - let mut found = own.iter(); - found - .find(|(m, _)| m == machine) - .and_then(|(_, own)| own.url.clone()) - }; - let mut machines: Vec = (own.iter().map(|(m, _)| m.clone())) - .chain(seen.machines.iter().map(|(m, _)| m.clone())) - .chain(sandboxes.iter().cloned()) - .filter(|m| m != "native" || own_url(m).is_some()) - .collect(); - machines.sort(); - machines.dedup(); - let store_url = record.text("url").map(str::to_owned); - let mut rows = vec![row(None, store_url.clone(), false, seen.here.clone())]; - for machine in machines { - let mine = own_url(&machine); + let rows = attached.into_iter().map(|machine| { let reach = seen.of(&machine); - let own = mine.is_some(); - rows.push(row(Some(machine), mine.or(store_url.clone()), own, reach)); - } - SdkValue::List(rows) + SdkValue::map([ + ("machine", SdkValue::text(machine)), + ("reached", crate::observed::reached(reach.as_ref())), + ("reach", reach.unwrap_or_default()), + ]) + }); + SdkValue::List(rows.collect()) } -/// One `connections` row. -fn row( - machine: Option, - url: Option, - own: bool, - reach: Option, -) -> SdkValue { - let server = (url.as_deref()).and_then(|url| target(url).ok()).map_or( - SdkValue::Null, - |(host, port, database)| { - let port = port - .parse::() - .map_or(SdkValue::text(&port), SdkValue::Int); - SdkValue::map([ - ("host", SdkValue::text(host)), - ("port", port), - ("database", SdkValue::text(database)), - ]) - }, - ); - SdkValue::map([ - ("machine", SdkValue::opt_text(machine)), - // an outdated record may still hold a login in its URL: a row never shows it (V23-3) - ("url", SdkValue::opt_text(url.as_deref().map(shown))), - ("own", SdkValue::Bool(own)), - ("server", server), - ("reached", crate::observed::reached(reach.as_ref())), - ("reach", reach.unwrap_or_default()), - ]) +/// When Store `record`'s password was last saved, as an answer's time. +pub fn password_changed(record: &StoreRecord) -> (bool, SdkValue) { + let saved = (record.home()).and_then(|home| login::read(home, record.name()).ok().flatten()); + let at = saved.as_ref().and_then(|saved| saved.changed_ms); + (saved.is_some(), crate::get::at(at)) } /// `store.connect`'s answer for `record`: `outcome` (`connected` or /// `updated`), the projects found on a first connect (the first 20 names, -/// and the count only when there were more), the login, the addresses and the setting. -pub fn answer( - record: &StoreRecord, - outcome: &str, - projects: Option<&[String]>, - sandboxes: &[String], -) -> SdkValue { +/// and the count only when there were more), the address, the user, the +/// setting and the attached machines; never the password. +pub fn answer(record: &StoreRecord, outcome: &str, projects: Option<&[String]>) -> SdkValue { let (names, count) = match projects { Some(found) => layerfs_home::helpers::shown_names(found), None => (SdkValue::Null, SdkValue::Null), @@ -219,38 +170,67 @@ pub fn answer( ("outcome", SdkValue::text(outcome)), ("store", SdkValue::text(record.name())), ("engine", SdkValue::text("postgresql")), - ("auth", text("auth")), - ("connections", connections(record, sandboxes)), + ("url", text("url")), + ("user", text("user")), ("synchronous_commit", text("synchronous_commit")), + ("machines", machines(record, false)), ]) } +/// A given user or password that is empty, refused. +fn given<'a>(value: Option<&'a str>, what: &str) -> Result> { + match value { + Some("") => Err(refused("InvalidInput", format!("the {what} is empty"))), + other => Ok(other), + } +} + +/// `store.connect`: a new Store ([`connect`]), or a connected one's +/// address, login or setting ([`update`]). A sqlite Store of the name is +/// `Exists`. +pub fn run(home_dir: &Path, request: &StoreConnect) -> Outcome { + let name = request.store.as_str(); + let Some(record) = StoreRecord::read(home_dir, name)? else { + return connect(home_dir, request); + }; + if record.kind()? != StoreKind::Postgresql { + return Err(refused( + "Exists", + format!("a sqlite Store named {name} exists"), + )); + } + update(home_dir, request) +} + /// `store.connect` of a new Store: records a PostgreSQL database as Store -/// `request.store`, its login `auth` required and saved. Every refusal of -/// its input comes before any effect. The connection is made from this -/// process, which gives an empty database the schema and a new id or reads -/// the id the schema holds, and lists its projects, before the home lock; -/// the lock covers the re-checks and the record writes only. A database -/// whose id another Store of this home holds is `Exists`. +/// `request.store`, its user and password required. Every refusal of its +/// input comes before any effect. The connection is made from this +/// process with the given login, which gives an empty database the schema +/// and a new id or reads the id the schema holds, and lists its projects, +/// before the home lock; the lock covers the re-checks and the writes +/// only: the record, then the password. A database whose id another +/// Store of this home holds is `Exists`. pub fn connect(home_dir: &Path, request: &StoreConnect) -> Outcome { let name = request.store.as_str(); - let given = request.url.as_str(); - refuse_login_with_fix(name, given, None, None)?; - target(given)?; - let auth = request.auth.as_deref().ok_or_else(|| { + let given_url = request.url.as_str(); + refuse_url(name, given_url, true)?; + target(given_url)?; + let needs = |what: &str| { refused( "InvalidInput", - format!("connecting Store {name} needs its login: --auth (`layerfs store save-auth` saves one)"), + format!("connecting Store {name} needs its login: --user --password-stdin (no {what} was given)"), ) - })?; - login::saved(home_dir, auth)?; + }; + let user = given(request.user.as_deref(), "user")?.ok_or_else(|| needs("user"))?; + let password = + given(request.password.as_deref(), "password")?.ok_or_else(|| needs("password"))?; let sync = request.synchronous_commit.as_deref().unwrap_or("local"); synchronous_commit(sync)?; if paths::store_record(home_dir, name).exists() { return Err(refused("Exists", format!("a Store named {name} exists"))); } - let record = StoreRecord::connected(name, given, SCHEMA, sync, Some(auth)).in_home(home_dir); - let probe = selection(&record)?; + let record = StoreRecord::connected(name, given_url, user, SCHEMA, sync).in_home(home_dir); + let probe = selection_at(&record, with_login(given_url, user, password)?); // an empty database gets the schema, with a new binding (#533 step // 10b); an existing LayerFS schema keeps its binding, read once. The // cursor key is this home's own either way. @@ -280,35 +260,69 @@ pub fn connect(home_dir: &Path, request: &StoreConnect) -> Outcome { return Err(refused("Exists", format!("a Store named {name} exists"))); } unclaimed_by_others(home_dir, name, &binding)?; - login::saved(home_dir, auth)?; home::private_dir(&directory)?; record.write(home_dir)?; + login::save(home_dir, name, password)?; let mut projects = Vec::new(); for project in listed { let stack = SdkValue::text(hex(&project.stack.to_bytes())); ProjectRecord::found(name, &project.name, stack).write(home_dir)?; projects.push(project.name); } - Ok(answer(&record, "connected", Some(&projects), &[])) + Ok(answer(&record, "connected", Some(&projects))) } -/// `store.connect` of a connected Store without a machine: `request.url` -/// becomes the address every machine dials, proven from this process (it -/// must read this Store's id: `Unavailable` otherwise). `--auth` and -/// `--synchronous-commit` are refused (`store update` changes both). The -/// record is written under the home lock and the Store's, `Conflict` when -/// it was disconnected or connected to another database meanwhile; this -/// process's open sessions on it are closed. A running Sandbox keeps the -/// connection it started with. -pub fn readdress(home_dir: &Path, request: &StoreConnect, sandboxes: &[String]) -> Outcome { +/// `store.connect` of a connected Store: its address `request.url`, and +/// any of a new user, password and `synchronous_commit` (those not given +/// are kept). The new values are dialled once from this process and must +/// read this Store's id (`Unavailable` otherwise) before anything is +/// saved. The record (and a new password) are written under +/// the home lock and the Store's, `Conflict` when it was disconnected or +/// connected to another database meanwhile; this process's open sessions +/// on it are closed. A running Sandbox keeps the connection it started +/// with. +pub fn update(home_dir: &Path, request: &StoreConnect) -> Outcome { let name = request.store.as_str(); let record = super::check::postgresql_record(home_dir, name)?; - refuse_settings(name, request)?; - refuse_login_with_fix(name, &request.url, Some(&record), None)?; + refuse_url(name, &request.url, false)?; target(&request.url)?; record.unblocked()?; - let trial = record.clone().with("url", SdkValue::text(&request.url)); - super::check::same_store(&trial, &selection(&trial)?).map_err(|refusal| { + let user = given(request.user.as_deref(), "user")?.or(record.text("user")); + let user = user.map(str::to_owned).ok_or_else(|| { + refused( + "InvalidInput", + format!("Store {name}'s record names no user: give it with --user"), + ) + })?; + let new_password = given(request.password.as_deref(), "password")?; + let saved = login::read(home_dir, name)?; + let password = match (new_password, &saved) { + (Some(password), _) => password.to_owned(), + (None, Some(saved)) => saved.password().to_owned(), + (None, None) => { + return Err(refused( + "InvalidInput", + format!( + "Store {name}'s password is not saved in this home: give it with --password-stdin" + ), + )) + } + }; + if let Some(sync) = &request.synchronous_commit { + synchronous_commit(sync)?; + } + let changed = |record: StoreRecord| { + let record = record + .with("url", SdkValue::text(&request.url)) + .with("user", SdkValue::text(&user)); + match &request.synchronous_commit { + Some(sync) => record.with("synchronous_commit", SdkValue::text(sync)), + None => record, + } + }; + let trial = changed(record.clone()); + let probe = selection_at(&trial, with_login(&request.url, &user, &password)?); + super::check::same_store(&trial, &probe).map_err(|refusal| { refused( &refusal.code, format!("PostgreSQL Store {name}: {}", refusal.message), @@ -320,43 +334,30 @@ pub fn readdress(home_dir: &Path, request: &StoreConnect, sandboxes: &[String]) let Some(current) = current else { return Err(refused( "Conflict", - format!("Store {name} changed while its address was checked; connect it again"), + format!("Store {name} changed while its connection was checked; connect it again"), )); }; current.unblocked()?; crate::open::close(¤t.postgresql_key(home_dir, name))?; - // the address as given; nothing else of the record changes - let current = current.with("url", SdkValue::text(&request.url)); + let current = changed(current); current.write(home_dir)?; + if let Some(password) = new_password { + login::save(home_dir, name, password)?; + } drop((store_lock, home_lock)); - Ok(answer(¤t, "updated", None, sandboxes)) -} - -/// Refuses `--auth` and `--synchronous-commit` on a connected Store's -/// connect: a machine never has its own login, and both are the Store's, -/// changed with `store update`. -pub fn refuse_settings(name: &str, request: &StoreConnect) -> Result<()> { - let given = match (&request.auth, &request.synchronous_commit) { - (Some(_), _) => "--auth", - (None, Some(_)) => "--synchronous-commit", - (None, None) => return Ok(()), - }; - Err(refused( - "InvalidInput", - format!( - "Store {name} is connected: a connect sets an address only and takes no {given}; `layerfs store update {name}` changes its login or setting" - ), - )) + Ok(answer(¤t, "updated", None)) } -/// `store.disconnect` of a whole Store: forgets a PostgreSQL Store; its -/// data stays. Refused `InUse` while a process holds it or a Sandbox of its -/// projects exists; a sqlite Store is `InvalidInput`, naming `store remove`. +/// `store.disconnect`: forgets a PostgreSQL Store, its saved password and +/// its attachments; its data stays. Refused `InUse` while a process holds +/// it or a Sandbox of its projects exists; a sqlite Store is +/// `InvalidInput`, naming `store remove`. pub fn disconnect(home_dir: &Path, name: &StoreName, related: Related) -> Outcome { // a record this build does not read: its records alone go if StoreRecord::read(home_dir, name)?.is_some_and(|record| record.store_ref().is_err()) { crate::record::forget_unread(home_dir, name, related)?; - return Ok(disconnected(name, None)); + login::forget(home_dir, name)?; + return Ok(disconnected(name)); } let _lock = home::lock::take(home_dir)?; let _store = crate::record::lock(home_dir, name)?; @@ -373,18 +374,17 @@ pub fn disconnect(home_dir: &Path, name: &StoreName, related: Related) -> Outcom (related.store_idle)(home_dir, name)?; crate::open::close(&record.postgresql_key(home_dir, name))?; std::fs::remove_dir_all(paths::store_dir(home_dir, name)).map_err(failed)?; + login::forget(home_dir, name)?; layerfs_home::home::generation::moved(home_dir); - Ok(disconnected(name, None)) + Ok(disconnected(name)) } -/// `store.disconnect`'s answer: `{ ok, outcome: disconnected, store, -/// machine }`. -pub fn disconnected(store: &str, machine: Option<&str>) -> SdkValue { +/// `store.disconnect`'s answer: `{ ok, outcome: disconnected, store }`. +pub fn disconnected(store: &str) -> SdkValue { SdkValue::map([ ("ok", SdkValue::Bool(true)), ("outcome", SdkValue::text("disconnected")), ("store", SdkValue::text(store)), - ("machine", machine.map_or(SdkValue::Null, SdkValue::text)), ]) } diff --git a/control/crates/layerfs-store/src/postgresql/login.rs b/control/crates/layerfs-store/src/postgresql/login.rs index 6caad122f9..4377d731a4 100644 --- a/control/crates/layerfs-store/src/postgresql/login.rs +++ b/control/crates/layerfs-store/src/postgresql/login.rs @@ -1,392 +1,94 @@ -//! Saved PostgreSQL logins (call surface 2.0, `pg.html`): a user and a -//! password with no address, saved once in the home's secret folder as -//! secret kind `auth` and named by any number of Stores (a Store record's -//! `auth`). `store.save_auth`, `store.auths` and `store.remove_auth` are -//! here, with [`dial`], which puts a Store's login into the address it -//! dials, and [`auth_of`], the login a Store names. A password is never -//! answered, logged or written into a record. -use super::address::{refuse_login, with_login}; -use crate::record::{StoreKind, StoreRecord}; +//! A PostgreSQL Store's login (owner, 2026-11-24): the host is the one +//! place a Store's URL and login are saved, and every attached machine +//! dials with them. The user is the Store record's `user`; the password is +//! kept in the home's secret folder as secret kind `login` under the +//! Store's name (`secret/login/.json`, `{ password, changed }`), +//! never answered, logged or written into a record. [`dial`] puts both +//! into the address a call dials, only when it dials. +use super::address::with_login; +use crate::record::StoreRecord; use layerfs_bridge::control::{SdkRefusal, SdkValue}; -use layerfs_home::helpers::{map_of, shown_names}; -use layerfs_home::home; -use layerfs_home::home::secrets::{read_secret, remove_secret, save_secret, secret_names}; -use layerfs_home::outcome::{refused, shell_word, with_fix, with_next, Outcome}; -use layerfs_home::state::{Reason, State}; -use layerfs_home::time::iso; +use layerfs_home::home::secrets::{read_secret, remove_secret, save_secret}; +use layerfs_home::outcome::{refused, shell_word, with_fix}; use std::path::Path; type Result = std::result::Result; -/// The secret kind a saved login is kept as: `secret/auth/.json`. -pub const KIND: &str = "auth"; +/// The secret kind a Store's password is kept as. +pub const KIND: &str = "login"; -/// One saved login. No `Debug`: it holds a password. -pub struct Login { - /// The PostgreSQL role. - pub user: String, +/// A Store's saved password. No `Debug`: it holds the password. +pub struct Saved { password: String, - created_ms: Option, - updated_ms: Option, + /// When it was last saved, ms since 1970. + pub changed_ms: Option, } -impl Login { +impl Saved { /// The password, for the URL a call dials and nothing else. pub fn password(&self) -> &str { &self.password } } -/// The saved login `auth`, `NotFound` naming the call that saves it. -pub fn read(home: &Path, auth: &str) -> Result { - let saved = read_secret(home, KIND, auth)?.ok_or_else(|| { - refused( - "NotFound", - format!( - "no saved login named {auth}; `layerfs store save-auth {auth} --user --password-stdin` saves one" - ), - ) - })?; - let text = |key: &str| saved.get_text(key).map(str::to_owned); - let (Some(user), Some(password)) = (text("user"), text("password")) else { - return Err(refused( - "Failed", - format!("the saved login {auth} has no user or no password; save it again"), - )); +/// Store `store`'s saved password, or `None` when none is saved; a file +/// holding no password reads as none. +pub fn read(home: &Path, store: &str) -> Result> { + let Some(saved) = read_secret(home, KIND, store)? else { + return Ok(None); }; - Ok(Login { - user, - password, - created_ms: saved.get_int("created"), - updated_ms: saved.get_int("updated"), - }) + let password = saved.get_text("password").filter(|p| !p.is_empty()); + Ok(password.map(|password| Saved { + password: password.to_owned(), + changed_ms: saved.get_int("changed"), + })) } -/// The saved login PostgreSQL Store `record` names (its `auth`), if any: -/// what `store.get` and each `store.list` item answer as `auth`. -pub fn auth_of(record: &StoreRecord) -> Option<&str> { - match record.kind() { - Ok(StoreKind::Postgresql) => record.text("auth"), - _ => None, - } -} - -/// `url`, an address of PostgreSQL Store `record`, with the Store's saved -/// login put in now, read from the home the record was read from. A record -/// naming no login (one connected before saved logins) is refused with the -/// fix that saves one and names it. -pub fn dial(record: &StoreRecord, url: &str) -> Result { - let Some(auth) = record.text("auth") else { - let message = format!("PostgreSQL Store {} names no saved login", record.name()); - return Err(with_fix( - refused("InvalidInput", message), - no_auth_fix(record), - )); - }; - let home = record.home().ok_or_else(|| { - refused( - "Failed", - format!( - "PostgreSQL Store {}'s record was not read from a home; its login {auth} cannot be read", - record.name() - ), - ) - })?; - // a URL that is not an address alone (an older record's) is never - // dialled: its fix writes or connects one - refuse_login(url).map_err(|refusal| { - let message = format!( - "PostgreSQL Store {}'s URL: {}", - record.name(), - refusal.message - ); - with_fix(refused(&refusal.code, message), fix_of(record)) - })?; - let login = read(home, auth)?; - with_login(url, &login.user, login.password()) -} - -/// The first step of a fix that saves a login: its name and user to fill -/// in (no user is ever read from a URL). -pub const SAVE: &str = "layerfs store save-auth --user --password-stdin"; - -/// The fix of PostgreSQL Store `record` whose record alone makes it -/// `broken` ([`crate::state::postgresql`]): [`no_auth_fix`] when it names -/// no saved login, [`missing_fix`] when the home does not hold the one it -/// names, else [`outdated_fix`]. -pub fn fix_of(record: &StoreRecord) -> String { - fix_with(record, None) -} - -/// [`fix_of`] with the `synchronous_commit` a refused `store update` was -/// given, if any. -fn fix_with(record: &StoreRecord, sync: Option<&str>) -> String { - let steps = match record.text("auth") { - None => steps(record, true, "", sync), - Some(auth) if record.home().is_some_and(|home| is_missing(home, auth)) => { - steps(record, true, &shell_word(auth), sync) - } - Some(auth) => steps(record, false, &outdated_auth(record, auth), sync), - }; - steps.join(" && ") -} - -/// The steps that leave PostgreSQL Store `record` naming login `auth` (a -/// name, or ``) with every URL an address alone, the login saved -/// first when `save` (`` to fill in). Every step dials only with -/// `auth`, never with the login the record names, so the steps work when -/// that one no longer authenticates; a URL that is not an address alone -/// (`refuse_login`) is never rewritten, only replaced by a connect of the -/// address alone (``). When the Store's own address is one, the Store -/// is disconnected (refused `InUse` while a Sandbox of it exists; its -/// data stays) and connected again with `--auth`, keeping its -/// `synchronous_commit` (`sync` when given, else the recorded one), then -/// every machine's own address is connected again. Otherwise each such -/// machine's own address is disconnected first (`store disconnect -/// --machine` dials nothing), the login is named with `store update -/// --auth` (with `sync` when given), and the machine's address alone is -/// connected last: `store connect --machine` checks it from that machine, -/// which must be running and run PostgreSQL Sandboxes (review 57d0aea5ad -/// N2). -fn steps(record: &StoreRecord, save: bool, auth: &str, sync: Option<&str>) -> Vec { - let store = shell_word(record.name()); - let refused = |url: &str| refuse_login(url).is_err(); - let flag = |sync: Option<&str>| { - sync.map_or(String::new(), |sync| { - format!(" --synchronous-commit {}", shell_word(sync)) - }) - }; - let connect_on = |machine: &str| { - let on = shell_word(machine); - format!("layerfs store connect {store} --machine {on}") - }; - let mut steps = Vec::new(); - if save { - steps.push(format!( - "layerfs store save-auth {auth} --user --password-stdin" - )); - } - let own = record.own_connections(); - if record.text("url").is_some_and(refused) { - let sync = flag(sync.or(record.text("synchronous_commit"))); - steps.push(format!("layerfs store disconnect {store}")); - steps.push(format!( - "layerfs store connect {store} --auth {auth}{sync}" - )); - steps.extend(own.iter().map(|(machine, _)| connect_on(machine))); - return steps; - } - let held: Vec<&String> = (own.iter()) - .filter(|(_, own)| own.url.as_deref().is_some_and(refused)) - .map(|(machine, _)| machine) - .collect(); - steps.extend(held.iter().map(|machine| { - let on = shell_word(machine); - format!("layerfs store disconnect {store} --machine {on}") - })); - steps.push(format!( - "layerfs store update {store} --auth {auth}{}", - flag(sync) - )); - steps.extend(held.iter().map(|machine| connect_on(machine))); - steps -} - -/// The login an `outdated` fix names: the record's own, `auth`, unless an -/// address is replaced, whose connect then takes `` (the record's -/// own login or another that authenticates; `store get` names the -/// record's). -fn outdated_auth(record: &StoreRecord, auth: &str) -> String { - match record.refused_urls() { - true => "".to_owned(), - false => shell_word(auth), - } -} - -/// The fix of `store update --auth ` (or `--synchronous-commit -/// ` alone) refused because PostgreSQL Store `record` (as it is, -/// not as the update would leave it) keeps a URL that is not an address -/// alone: the [`steps`] that name `auth` (the record's own fix when none -/// is given), each dialling only with `auth`, the given `sync` carried -/// (review 57d0aea5ad S1, e0aa26e149 S3 and N1). -pub fn update_fix(record: &StoreRecord, auth: Option<&str>, sync: Option<&str>) -> String { - match auth { - Some(auth) => steps(record, false, &shell_word(auth), sync).join(" && "), - None => fix_with(record, sync), - } -} - -/// The fix of a refused `store connect` (`connect`, its address ``) -/// of URL holding a login on connected PostgreSQL Store `record`: the -/// login saved, the [`steps`] that name it, then `connect` unless a step -/// already connects that address. -pub fn login_fix(record: &StoreRecord, connect: &str) -> String { - let mut steps = steps(record, true, "", None); - let with_auth = format!("{connect} --auth "); - if !(steps.iter()).any(|step| step == connect || step.starts_with(&with_auth)) { - steps.push(connect.to_owned()); - } - steps.join(" && ") -} - -/// The fix of PostgreSQL Store `record` naming no saved login: save one, -/// then name it ([`steps`]). `--user` is ``. -pub fn no_auth_fix(record: &StoreRecord) -> String { - steps(record, true, "", None).join(" && ") -} - -/// The fix of PostgreSQL Store `record` naming login `auth` whose record -/// holds what 2.0 no longer writes (spec v23 V23-6): name it again, which -/// drops the old fields, after replacing any URL that is not an address -/// alone, whose connect names `` ([`steps`]). -pub fn outdated_fix(record: &StoreRecord, auth: &str) -> String { - steps(record, false, &outdated_auth(record, auth), None).join(" && ") -} - -/// Whether `home` holds no saved login `auth` (its file is absent; one -/// that cannot be read is not missing, and `store auths` shows it broken). -pub fn is_missing(home: &Path, auth: &str) -> bool { - matches!(read_secret(home, KIND, auth), Ok(None)) -} - -/// The fix of PostgreSQL Store `record` naming login `auth` that is not -/// saved (spec v23 V23-7): save it under that name, then name it -/// ([`steps`]). `--user` is ``. -pub fn missing_fix(record: &StoreRecord, auth: &str) -> String { - steps(record, true, &shell_word(auth), None).join(" && ") -} - -/// The PostgreSQL Stores whose record names login `auth`, by name. -pub fn stores_using(home: &Path, auth: &str) -> Result> { - let mut found = Vec::new(); - for record in crate::record::stores(home)? { - if auth_of(&record) == Some(auth) { - found.push(record.name().to_owned()); - } - } - Ok(found) -} - -/// `stores` as an answer shows them: the first 20 names, and the count -/// only when there were more. -fn shown(stores: &[String]) -> [(&'static str, SdkValue); 2] { - let (names, count) = shown_names(stores); - [("stores", names), ("stores_count", count)] -} - -/// `store.save_auth(auth, { user, password })`: saves the login in the -/// home's secret folder; saving again under the same name rotates it, and -/// every Store using it dials with the new one from its next connection. -/// Answers `{ ok, outcome: saved | rotated, auth, user, stores, -/// stores_count }`, never the password. Under the home lock, so a removal -/// never races it. -pub fn save(home_dir: &Path, auth: &str, user: &str, password: &str) -> Outcome { - layerfs_home::names::name(KIND, auth).map_err(|why| refused("InvalidInput", why))?; - if user.is_empty() { - return Err(refused("InvalidInput", "--user is required")); - } - if password.is_empty() { - return Err(refused( - "InvalidInput", - "the password is empty; give it on stdin with --password-stdin", - )); - } - let _lock = home::lock::take(home_dir)?; - let now = home::now_ms(); - // a login file that cannot be read is written again: that is the fix its - // broken `auths` row gives (V23-8), so its old fields are not kept - let before = read_secret(home_dir, KIND, auth).unwrap_or(None); - let created = before - .as_ref() - .and_then(|saved| saved.get_int("created")) - .unwrap_or(now); +/// Saves `password` as Store `store`'s, replacing the one there, the +/// caller holding the home lock. +pub fn save(home: &Path, store: &str, password: &str) -> Result<()> { let value = SdkValue::map([ - ("user", SdkValue::text(user)), ("password", SdkValue::text(password)), - ("created", SdkValue::Int(created)), - ("updated", SdkValue::Int(now)), + ("changed", SdkValue::Int(layerfs_home::home::now_ms())), ]); - save_secret(home_dir, KIND, auth, &value)?; - let stores = stores_using(home_dir, auth)?; - let outcome = if before.is_some() { "rotated" } else { "saved" }; - let mut fields = vec![ - ("ok", SdkValue::Bool(true)), - ("outcome", SdkValue::text(outcome)), - ("auth", SdkValue::text(auth)), - ("user", SdkValue::text(user)), - ]; - fields.extend(shown(&stores)); - Ok(map_of(fields)) + save_secret(home, KIND, store, &value) } -/// `store.auths()`: every saved login, `{ items: [{ auth, user, state, -/// reason, fix, stores, stores_count, created_at, updated_at }] }`, never a -/// password. A login file that cannot be read is `broken` `failed` with the -/// save that rewrites it (spec v23 V23-8), not a failed list. -pub fn list(home_dir: &Path) -> Outcome { - let mut items = Vec::new(); - for auth in secret_names(home_dir, KIND)? { - let stores = stores_using(home_dir, &auth)?; - let at = |ms: Option| ms.map_or(SdkValue::Null, |ms| SdkValue::Text(iso(ms))); - // a login file that cannot be read is its own broken row, with the - // save that writes it again; the others are listed as usual - let (login, state) = match read(home_dir, &auth) { - Ok(login) => (Some(login), State::Ready), - Err(_) => { - let fix = format!( - "layerfs store save-auth {} --user --password-stdin", - shell_word(&auth) - ); - (None, State::broken(Reason::Failed, Some(&fix))) - } - }; - let mut fields = vec![ - ("auth", SdkValue::text(&auth)), - ( - "user", - SdkValue::opt_text(login.as_ref().map(|l| l.user.clone())), - ), - ]; - fields.extend(state.fields()); - fields.extend(shown(&stores)); - fields.push(("created_at", at(login.as_ref().and_then(|l| l.created_ms)))); - fields.push(("updated_at", at(login.as_ref().and_then(|l| l.updated_ms)))); - items.push(map_of(fields)); - } - Ok(SdkValue::map([("items", SdkValue::List(items))])) +/// Forgets Store `store`'s saved password, if any. +pub fn forget(home: &Path, store: &str) -> Result<()> { + remove_secret(home, KIND, store).map(|_| ()) } -/// `store.remove_auth(auth)`: removes a saved login no Store names. -/// Refused `InUse` while a Store names it, listing those Stores (`stores`), -/// and `NotFound` when there is none. Under the home lock, which a first -/// connect also takes to write the record that names it. -pub fn remove(home_dir: &Path, auth: &str) -> Outcome { - layerfs_home::names::name(KIND, auth).map_err(|why| refused("InvalidInput", why))?; - let _lock = home::lock::take(home_dir)?; - let stores = stores_using(home_dir, auth)?; - if !stores.is_empty() { - let refusal = refused( - "InUse", - format!( - "the login {auth} is used by {}: `layerfs store update --auth ` or `layerfs store disconnect ` first", - stores.join(", ") - ), - ); - let names = stores.iter().map(SdkValue::text).collect(); - return Err(with_next(refusal, "stores", SdkValue::List(names))); - } - if !remove_secret(home_dir, KIND, auth)? { - return Err(refused("NotFound", format!("no saved login named {auth}"))); - } - Ok(map_of(vec![ - ("ok", SdkValue::Bool(true)), - ("outcome", SdkValue::text("removed")), - ("auth", SdkValue::text(auth)), - ])) +/// The fix of a PostgreSQL Store whose password this home does not hold: +/// connect it again with the password, its user kept. Like every fix it +/// names the address ``, never text of a URL (`store get` shows it). +pub fn password_fix(record: &StoreRecord) -> String { + format!( + "layerfs store connect {} --password-stdin", + shell_word(record.name()) + ) } -/// Refused `NotFound` unless login `auth` is saved in `home`. -pub fn saved(home_dir: &Path, auth: &str) -> Result<()> { - layerfs_home::names::name(KIND, auth).map_err(|why| refused("InvalidInput", why))?; - read(home_dir, auth).map(|_| ()) +/// `url`, an address of PostgreSQL Store `record`, with the Store's user +/// and saved password put in now, read from the home the record was read +/// from: refused when the record names no user, when the password is not +/// saved ([`password_fix`]), or when `url` is not an address alone +/// (`with_login`). +pub fn dial(record: &StoreRecord, url: &str) -> Result { + let name = record.name(); + let user = crate::record::required(record.text("user").map(str::to_owned), "user")?; + let home = record.home().ok_or_else(|| { + refused( + "Failed", + format!("PostgreSQL Store {name}'s record was not read from a home; its login cannot be read"), + ) + })?; + let Some(saved) = read(home, name)? else { + let message = format!("PostgreSQL Store {name}'s password is not saved in this home"); + return Err(with_fix( + refused("InvalidInput", message), + password_fix(record), + )); + }; + with_login(url, &user, saved.password()) } diff --git a/control/crates/layerfs-store/src/postgresql/mod.rs b/control/crates/layerfs-store/src/postgresql/mod.rs index 92c26f7d0f..9bbcf355b3 100644 --- a/control/crates/layerfs-store/src/postgresql/mod.rs +++ b/control/crates/layerfs-store/src/postgresql/mod.rs @@ -1,6 +1,7 @@ -//! PostgreSQL Stores: connect, update and disconnect, saved logins +//! PostgreSQL Stores: connect and disconnect, the Store's saved login //! (`login`), a Store URL as its client reads it (`address`), the check of a -//! connection from the side that dials it (`check`), opening a database session +//! connection from the side that dials it and the machines attached to it +//! (`check`), opening a database session //! (`open`, the PostgreSQL URL and Store open), and the held host sessions //! Store calls read through (`reader`). Never imports `sqlite/`. #[doc(hidden)] @@ -15,5 +16,3 @@ pub mod login; pub mod open; #[doc(hidden)] pub mod reader; -#[doc(hidden)] -pub mod update; diff --git a/control/crates/layerfs-store/src/postgresql/update.rs b/control/crates/layerfs-store/src/postgresql/update.rs deleted file mode 100644 index ac4f79b606..0000000000 --- a/control/crates/layerfs-store/src/postgresql/update.rs +++ /dev/null @@ -1,134 +0,0 @@ -//! `store.update` of a PostgreSQL Store: another saved login (`auth`), or -//! its `synchronous_commit`; one of the two is required. A new login is -//! checked once from this process, on the Store's address, before it is -//! saved: the server is reached with it and holds this Store. An address -//! change is a `store connect`, a machine's own address is removed with -//! `store disconnect --machine`. -use crate::postgresql::check::{postgresql_record, same_store}; -use crate::postgresql::connect::{selection, synchronous_commit}; -use crate::postgresql::login; -use crate::record::StoreRecord; -use layerfs_bridge::control::{SdkRefusal, SdkValue}; -use layerfs_home::home; -use layerfs_home::names::StoreName; -use layerfs_home::outcome::{refused, with_fix, Outcome}; -use std::path::Path; - -/// What `store.update` changes of a Store. -#[derive(Clone, Debug)] -pub struct StoreUpdate { - /// The PostgreSQL Store. - pub store: StoreName, - /// The name of its new saved login. - pub auth: Option, - /// Its new `synchronous_commit`. - pub synchronous_commit: Option, -} - -/// `record` with the request's fields in place of its own. -fn changed(record: StoreRecord, request: &StoreUpdate) -> StoreRecord { - let fields = [ - ("auth", &request.auth), - ("synchronous_commit", &request.synchronous_commit), - ]; - fields - .into_iter() - .fold(record, |record, (field, value)| match value { - Some(value) => record.with(field, SdkValue::text(value)), - None => record, - }) -} - -/// `store.update`: changes the Store's saved login and `synchronous_commit`. -/// Every refusal of its input comes before any connection; a new login is -/// dialled once from here on the Store's address and must read this -/// Store's id (`Unavailable` otherwise). A record keeping a URL that is not -/// an address alone (`refuse_login`: one that may hold a login, or a `#`) -/// is refused with its fix, nothing written: no update rewrites a URL. The -/// record is written under the home lock and the Store's, `Conflict` when -/// it was disconnected or connected to another database meanwhile; this -/// process's open sessions on it are closed (`InUse` while one of its calls -/// runs). The login is checked again under the lock, and the write leaves -/// no old field (spec v23 V23-6): an update to the Store's own login is its -/// `outdated` fix. A running Sandbox keeps the connection it started with. -/// Answers `{ ok, outcome: updated, store, auth, synchronous_commit }`. -pub fn update(home_dir: &Path, request: &StoreUpdate) -> Outcome { - let name = &request.store; - let record = postgresql_record(home_dir, name)?; - record.unblocked()?; - if request.auth.is_none() && request.synchronous_commit.is_none() { - return Err(refused( - "InvalidInput", - "nothing to update: give --auth or --synchronous-commit (an address is `store connect`)", - )); - } - if let Some(sync) = &request.synchronous_commit { - synchronous_commit(sync)?; - } - if let Some(auth) = &request.auth { - login::saved(home_dir, auth)?; - } - // a URL that is not an address alone is never rewritten (it may hold a - // login): the fix, built from the record as it is, replaces it with - // steps that dial only with the login given here - if record.refused_urls() { - let message = format!( - "Store {name}'s record keeps a URL that is not an address alone (it may hold a login); nothing was written" - ); - let (auth, sync) = ( - request.auth.as_deref(), - request.synchronous_commit.as_deref(), - ); - return Err(with_fix( - refused("InvalidInput", message), - login::update_fix(&record, auth, sync), - )); - } - if request.auth.is_some() { - let trial = changed(record.clone(), request).without_old_fields(); - same_store(&trial, &selection(&trial)?).map_err(|refusal| named(refusal, name))?; - } - let home_lock = home::lock::take(home_dir)?; - let store_lock = crate::record::lock(home_dir, name)?; - let current = StoreRecord::read(home_dir, name)?.filter(|r| r.binding() == record.binding()); - let Some(current) = current else { - return Err(refused( - "Conflict", - format!("Store {name} changed while its login was checked; update it again"), - )); - }; - current.unblocked()?; - // the login again under the home lock, which `store remove-auth` takes: - // one removed while it was checked is not named (spec v23 V23-7) - if let Some(auth) = &request.auth { - login::saved(home_dir, auth)?; - } - // a URL replaced meanwhile by one that is not an address alone is - // never rewritten either - if current.refused_urls() { - return Err(refused( - "Conflict", - format!("Store {name} changed while its login was checked; update it again"), - )); - } - crate::open::close(¤t.postgresql_key(home_dir, name))?; - let current = changed(current, request).without_old_fields(); - current.write(home_dir)?; - drop((store_lock, home_lock)); - let text = |key: &str| current.text(key).map_or(SdkValue::Null, SdkValue::text); - Ok(SdkValue::map([ - ("ok", SdkValue::Bool(true)), - ("outcome", SdkValue::text("updated")), - ("store", SdkValue::text(name.as_str())), - ("auth", text("auth")), - ("synchronous_commit", text("synchronous_commit")), - ])) -} - -/// `refusal` of the check, naming the Store. -fn named(refusal: SdkRefusal, name: &str) -> SdkRefusal { - refused( - &refusal.code, - format!("PostgreSQL Store {name}: {}", refusal.message), - ) -} diff --git a/control/crates/layerfs-store/src/record.rs b/control/crates/layerfs-store/src/record.rs index 0841868acc..59a09390e5 100644 --- a/control/crates/layerfs-store/src/record.rs +++ b/control/crates/layerfs-store/src/record.rs @@ -29,47 +29,15 @@ pub fn kind_of(record: &SdkValue) -> Result { } /// A PostgreSQL Store's server, as its record names it (no password: the -/// record names its saved login, `auth`, put into the URL per call). A -/// field the record lacks is refused only by the step that needs it. +/// record names its user, and the password is a secret of the home, +/// `postgresql::login`, put into the URL per call). A field the record +/// lacks is refused only by the step that needs it. #[derive(Clone, Debug, PartialEq, Eq)] pub struct PgServer { pub schema: Option, pub synchronous_commit: Option, } -/// A machine's own address of a PostgreSQL Store, its record's -/// `machines.`: the URL (no user, no password) that machine dials -/// in place of the Store's (`store.connect --machine`), with the Store's -/// saved login. A machine without one dials the Store's address. -#[derive(Clone, Debug, Default, PartialEq)] -pub struct OwnConnection { - /// The URL the machine dials, when not the Store's. - pub url: Option, -} - -impl OwnConnection { - fn from_record(value: &SdkValue) -> Self { - Self { - url: value.get_text("url").map(str::to_owned), - } - } - - /// Whether it names no URL: the Store's connection, which no record - /// entry is kept for. - pub fn is_empty(&self) -> bool { - self.url.is_none() - } - - /// The connection as its record holds it: only the fields it has. - pub fn to_record(&self) -> SdkValue { - let mut fields = Vec::new(); - if let Some(url) = &self.url { - fields.push(("url".to_owned(), SdkValue::text(url))); - } - SdkValue::Map(fields) - } -} - /// One Store, decided once from `store//record.json`. #[derive(Clone, Debug, PartialEq, Eq)] pub enum StoreRef { @@ -151,8 +119,8 @@ pub struct StoreRecord { name: String, parsed: Result, fields: SdkValue, - /// The home it was read from, where a PostgreSQL Store's saved login - /// is; none for a record a worker was sent. + /// The home it was read from, where a PostgreSQL Store's password is + /// saved; none for a record a worker was sent. home: Option, } @@ -169,6 +137,9 @@ pub fn lock(home: &Path, name: &str) -> Result { entity_lock::take(&dir.join("lock"), entity_lock::WAIT, &held) } +/// The record field listing the machines attached to a PostgreSQL Store. +pub const ATTACHED: &str = "attached"; + /// The profile label a new sqlite Store's record is written with: the WAL /// Store opened with NORMAL synchronization (owner, 2026-11-23). pub const PROFILE: &str = "normal"; @@ -200,7 +171,7 @@ impl StoreRecord { Ok(read.map(|v| Self::from_record(name, v).in_home(home))) } - /// This record, as one of `home`'s: its saved login is read there. + /// This record, as one of `home`'s: its password is read there. pub fn in_home(self, home: &Path) -> Self { Self { home: Some(home.to_path_buf()), @@ -263,7 +234,7 @@ impl StoreRecord { self.fields.get(field) } - /// The text field `field` (a PostgreSQL Store's `url`, `auth`, + /// The text field `field` (a PostgreSQL Store's `url`, `user`, /// `synchronous_commit`). pub fn text(&self, field: &str) -> Option<&str> { self.fields.get_text(field) @@ -345,106 +316,41 @@ impl StoreRecord { }) } - /// The machines with their own address of a PostgreSQL Store, in - /// record order. An entry that names none is none. - pub fn own_connections(&self) -> Vec<(String, OwnConnection)> { - match self.fields.get("machines") { - Some(SdkValue::Map(machines)) => machines - .iter() - .map(|(machine, value)| (machine.clone(), OwnConnection::from_record(value))) - .filter(|(_, own)| !own.is_empty()) + /// The machines attached to a PostgreSQL Store (its record's + /// `attached`), in record order: the machines its Sandboxes may run on + /// besides this computer, each dialling the Store's URL with its login. + pub fn attached(&self) -> Vec { + match self.fields.get(ATTACHED) { + Some(SdkValue::List(machines)) => (machines.iter()) + .filter_map(|machine| match machine { + SdkValue::Text(machine) => Some(machine.clone()), + _ => None, + }) .collect(), _ => Vec::new(), } } - /// `machine`'s own connection, if it has one. - pub fn own_connection(&self, machine: &str) -> Option { - let mut found = self.own_connections().into_iter(); - found.find(|(m, _)| m == machine).map(|(_, own)| own) + /// Whether `machine` is attached to the Store. + pub fn is_attached(&self, machine: &str) -> bool { + self.attached().iter().any(|m| m == machine) } - /// The record with `machine`'s own connection set to `own`; an empty - /// one removes it. Every other machine's entry is kept byte for byte: a - /// URL is never rewritten, and only `store update` drops old fields - /// ([`Self::without_old_fields`]). - pub fn with_own_connection(self, machine: &str, own: &OwnConnection) -> Self { - let mut machines = match self.fields.get("machines") { - Some(SdkValue::Map(machines)) => machines.clone(), - _ => Vec::new(), - }; - let at = machines.iter().position(|(m, _)| m == machine); - match (at, own.is_empty()) { - (None, true) => return self, - (None, false) => machines.push((machine.to_owned(), own.to_record())), - (Some(at), true) => { - machines.remove(at); - } - (Some(at), false) => machines[at].1 = own.to_record(), + /// The record with `machine` attached (`attach`) or not; no + /// `attached` field when none is. + pub fn with_attached(self, machine: &str, attach: bool) -> Self { + let mut machines: Vec = self.attached(); + machines.retain(|m| m != machine); + if attach { + machines.push(machine.to_owned()); } match machines.is_empty() { - true => self.without("machines"), - false => self.with("machines", SdkValue::Map(machines)), - } - } - - /// The record without an own connection for `machine`. - pub fn without_own_connection(self, machine: &str) -> Self { - self.with_own_connection(machine, &OwnConnection::default()) - } - - /// The record with `machines` holding exactly these own connections, - /// and no `machines` field when there are none. - fn with_machines(self, machines: Vec<(String, OwnConnection)>) -> Self { - if machines.is_empty() { - return self.without("machines"); + true => self.without(ATTACHED), + false => { + let machines = machines.into_iter().map(SdkValue::Text).collect(); + self.with(ATTACHED, SdkValue::List(machines)) + } } - let machines = machines.into_iter().map(|(m, own)| (m, own.to_record())); - self.with("machines", SdkValue::Map(machines.collect())) - } - - /// Whether a PostgreSQL Store's record holds what 2.0 no longer writes - /// (spec v23 V23-6): a `password`, a URL that is not an address alone - /// (`refuse_login`), or a `machines.` entry with anything but a `url` - /// (an old `checked`). Such a record reads `broken` `outdated` with the - /// fix the user runs (`postgresql::login`); no write cleans a URL. - pub fn outdated_fields(&self) -> bool { - let machines = match self.fields.get("machines") { - Some(SdkValue::Map(machines)) => machines.as_slice(), - _ => &[], - }; - self.fields.get("password").is_some() - || self.refused_urls() - || machines.iter().any(|(_, entry)| match entry { - SdkValue::Map(fields) => fields.iter().any(|(key, _)| key != "url"), - _ => true, - }) - || !matches!(self.fields.get("machines"), None | Some(SdkValue::Map(_))) - } - - /// Whether the Store's address or a machine's own is not an address - /// alone (`refuse_login`): it may hold a login, or a `#`. Such a URL is - /// never dialled and never rewritten; only a connect of an address - /// alone replaces it. - pub fn refused_urls(&self) -> bool { - let refused = |url: &str| crate::postgresql::connect::refuse_login(url).is_err(); - let machines = match self.fields.get("machines") { - Some(SdkValue::Map(machines)) => machines.as_slice(), - _ => &[], - }; - self.text("url").is_some_and(refused) - || (machines.iter()).any(|(_, entry)| entry.get_text("url").is_some_and(refused)) - } - - /// The record as `store update` writes it (V23-6): no `password`, and - /// each machine entry its `url` alone (none without one). Its URLs are - /// kept as they are: `store update` refuses a record holding a URL that - /// is not an address alone ([`Self::refused_urls`]), and no write - /// rewrites one. - pub fn without_old_fields(self) -> Self { - let record = self.without("password"); - let machines = record.own_connections(); - record.with_machines(machines) } fn raw_links(&self) -> &[(String, SdkValue)] { @@ -519,34 +425,30 @@ impl StoreRecord { } /// A PostgreSQL Store `store.connect` records: its URL without a user - /// or password, the schema, `synchronous_commit` and the name of its - /// saved login (`auth`), if any (its binding and cursor key are added - /// once read). + /// or password, its user, the schema and `synchronous_commit` (its + /// binding and cursor key are added once read). pub fn connected( name: &str, url: &str, + user: &str, schema: &str, synchronous_commit: &str, - auth: Option<&str>, ) -> Self { let fields = SdkValue::map([ ("name", SdkValue::text(name)), ("kind", SdkValue::text("postgresql")), ("url", SdkValue::text(url)), + ("user", SdkValue::text(user)), ("schema", SdkValue::text(schema)), ("synchronous_commit", SdkValue::text(synchronous_commit)), ("created", SdkValue::Int(home::now_ms())), ]); - let record = Self::from_record(name, fields); - match auth { - Some(auth) => record.with("auth", SdkValue::text(auth)), - None => record, - } + Self::from_record(name, fields) } } -/// The full URL of a PostgreSQL Store's record, with its saved login put -/// in now. +/// The full URL of a PostgreSQL Store's record, with its login put in +/// now: what this computer and every attached machine dial. pub fn url(record: &StoreRecord) -> Result { let url = record.text("url").ok_or_else(|| { refused( @@ -557,26 +459,6 @@ pub fn url(record: &StoreRecord) -> Result { crate::postgresql::login::dial(record, url) } -/// The full URL machine `machine` dials for PostgreSQL Store `record`, with -/// the Store's saved login put in now: its own address where it has one, -/// else the Store's. -pub fn url_on(record: &StoreRecord, machine: &str) -> Result { - let url = address_on(record, machine).ok_or_else(|| { - refused( - "Failed", - format!("PostgreSQL Store {}'s record has no url", record.name()), - ) - })?; - crate::postgresql::login::dial(record, &url) -} - -/// The address machine `machine` dials for PostgreSQL Store `record`, with -/// no login: its own where it has one, else the Store's. -pub fn address_on(record: &StoreRecord, machine: &str) -> Option { - let own = record.own_connection(machine).and_then(|own| own.url); - own.or_else(|| record.text("url").map(str::to_owned)) -} - /// Every Store record, by name. pub fn stores(home: &Path) -> Result> { let mut found = Vec::new(); diff --git a/control/crates/layerfs-store/src/state.rs b/control/crates/layerfs-store/src/state.rs index c4f4c0a755..1186e104f2 100644 --- a/control/crates/layerfs-store/src/state.rs +++ b/control/crates/layerfs-store/src/state.rs @@ -97,8 +97,7 @@ pub fn seen(record: &StoreRecord) -> Option { /// machine's state for a sqlite Store on a machine (none for a PostgreSQL /// Store, which is on no machine; a sqlite Store given none is not /// blocked). A record this build cannot place (a kind it does not read) -/// is `broken` `unsupported`; a PostgreSQL Store's login and old fields -/// may break it too ([`postgresql`]). +/// is `broken` `unsupported`. pub fn recorded_under(record: &StoreRecord, under: Option<&State>) -> Result { if let Some(state) = held(record) { return Ok(state); @@ -113,46 +112,11 @@ pub fn recorded_under(record: &StoreRecord, under: Option<&State>) -> Result { - if let Some(state) = postgresql(record) { - return Ok(state); - } - } + Ok(StoreRef::Postgres { .. }) => {} } Ok(seen(record).unwrap_or(State::Ready)) } -/// A PostgreSQL Store's own `broken` state from its record (spec v23): -/// naming no saved login, `outdated` with the fix that saves one and names -/// it; naming one this home does not hold, `missing` with the same fix for -/// that name; holding what 2.0 no longer writes (V23-6), `outdated` with -/// the update that drops it (or, for a URL that is not an address alone, -/// never rewritten, the steps that replace it, `login::outdated_fix`). A -/// missing login wins over the old fields: -/// its fix clears both. The Store doctor's `store.record` reports the same -/// state and fix. Only for a PostgreSQL record: a sqlite one names no login. -pub fn postgresql(record: &StoreRecord) -> Option { - use crate::postgresql::login; - let Some(auth) = record.text("auth") else { - return Some(State::broken( - Reason::Outdated, - Some(&login::no_auth_fix(record)), - )); - }; - if record - .home() - .is_some_and(|home| login::is_missing(home, auth)) - { - return Some(State::broken( - Reason::Missing, - Some(&login::missing_fix(record, auth)), - )); - } - record - .outdated_fields() - .then(|| State::broken(Reason::Outdated, Some(&login::outdated_fix(record, auth)))) -} - /// The machine a sqlite Store's record places it on, if it names one. pub fn placed(record: &StoreRecord) -> Option<&str> { match record.store_ref() { diff --git a/control/crates/layerfs-store/tests/compact_report_status.rs b/control/crates/layerfs-store/tests/compact_report_status.rs index a63511848f..7fc2eee47b 100644 --- a/control/crates/layerfs-store/tests/compact_report_status.rs +++ b/control/crates/layerfs-store/tests/compact_report_status.rs @@ -148,28 +148,14 @@ fn live(home: &Path) -> SdkValue { live: true, stats: false, }; - layerfs_store::get::get( - home, - &mut Events::new(&mut sink), - "s", - with, - (&machines, &|_: &std::path::Path| Vec::new()), - ) - .unwrap() + layerfs_store::get::get(home, &mut Events::new(&mut sink), "s", with, &machines).unwrap() } /// `store get ` from the records alone. fn recorded(home: &Path) -> SdkValue { let mut sink = |_| {}; let with = With::default(); - layerfs_store::get::get( - home, - &mut Events::new(&mut sink), - "s", - with, - (&machines, &|_: &std::path::Path| Vec::new()), - ) - .unwrap() + layerfs_store::get::get(home, &mut Events::new(&mut sink), "s", with, &machines).unwrap() } #[test] diff --git a/control/crates/layerfs-store/tests/observed_reach.rs b/control/crates/layerfs-store/tests/observed_reach.rs index 1dba3121af..2f4c10f598 100644 --- a/control/crates/layerfs-store/tests/observed_reach.rs +++ b/control/crates/layerfs-store/tests/observed_reach.rs @@ -1,18 +1,16 @@ -//! What was seen of a PostgreSQL Store's reach (spec v23 V23-2, V23-3, -//! V23-6, V23-8), with no server: `store//observed.json` keeps each -//! side's last reach beside the `at` a live read writes, two writers lose -//! no entry, a write after the Store is gone leaves no folder, and a -//! machine's entry is forgotten; `connections` lists every side that -//! connects; an old record reads `outdated`, `store update` drops its old -//! fields and no write rewrites a URL; a missing login reads `missing`; `store auths` lists a login -//! file it cannot read as a broken row. A failed check is `not_connected` -//! (the one case a machine's loopback hint is added) only when no server -//! answered. +//! What was seen of a PostgreSQL Store's reach (spec v23 V23-2), and a +//! PostgreSQL Store's record (owner, 2026-11-24), with no server: +//! `store//observed.json` keeps each side's last reach beside the `at` +//! a live read writes, two writers lose no entry, a write after the Store +//! is gone leaves no folder, and a removed machine's attachment and reach +//! are forgotten; `machines` lists the attached machines with their reach; +//! a Store whose password is not saved is not dialled. A failed check is `not_connected` (the one case a machine's +//! loopback hint is added) only when no server answered. use layerfs_bridge::control::SdkValue; use layerfs_home::home::{self, observed, paths, write_entity}; -use layerfs_home::state::{Reason, State}; use layerfs_store::observed::{self as seen, Reach}; -use layerfs_store::postgresql::connect::{connections, shown}; +use layerfs_store::postgresql::connect::{machines, shown}; +use layerfs_store::postgresql::login; use layerfs_store::record::StoreRecord; use std::path::{Path, PathBuf}; @@ -27,16 +25,16 @@ fn t(s: &str) -> SdkValue { SdkValue::text(s) } -/// Writes PostgreSQL Store `name`'s record, naming login `pg`, with -/// `extra` fields. +/// Writes PostgreSQL Store `name`'s record as `store.connect` does, user +/// `alice`, with `extra` fields. fn store(home: &Path, name: &str, extra: &[(&str, SdkValue)]) -> StoreRecord { let fields = vec![ ("name", t(name)), ("kind", t("postgresql")), ("url", t("postgresql://db.example:6543/app")), + ("user", t("alice")), ("schema", t("layerfs")), ("synchronous_commit", t("local")), - ("auth", t("pg")), ("binding", SdkValue::Bytes((0..32).collect())), ]; let fields = fields.into_iter().map(|(k, v)| (k.to_owned(), v)); @@ -47,16 +45,11 @@ fn store(home: &Path, name: &str, extra: &[(&str, SdkValue)]) -> StoreRecord { StoreRecord::of(home, name).unwrap() } -fn rows(record: &StoreRecord, sandboxes: &[&str]) -> Vec { - let sandboxes: Vec = sandboxes.iter().map(|s| (*s).to_owned()).collect(); - match connections(record, &sandboxes) { - SdkValue::List(rows) => rows, - other => panic!("{other:?}"), - } -} - -fn machines(rows: &[SdkValue]) -> Vec> { - rows.iter().map(|row| row.get_text("machine")).collect() +fn attached(names: &[&str]) -> (&'static str, SdkValue) { + ( + "attached", + SdkValue::List(names.iter().map(|n| t(n)).collect()), + ) } #[test] @@ -88,7 +81,7 @@ fn reaches_are_kept_beside_the_live_read_and_merged() { seen::record(&home, "pg", Some("lab"), &Reach::reached()); let lab = seen::read(&home, "pg").of("lab").unwrap(); assert_eq!(lab.get("latency_ms"), Some(&SdkValue::Null)); - // `native` with no address of its own dials as this computer + // `native` dials as this computer seen::record(&home, "pg", Some("native"), &Reach::reached()); let got = seen::read(&home, "pg"); assert!(got.of("native").is_none()); @@ -137,8 +130,7 @@ fn a_write_after_the_store_is_gone_leaves_no_folder() { #[test] fn a_removed_machine_is_forgotten() { let home = tempdir("forget"); - let own = SdkValue::map([("url", t("postgresql://10.0.0.2:6543/app"))]); - store(&home, "pg", &[("machines", SdkValue::map([("lab", own)]))]); + store(&home, "pg", &[attached(&["lab", "other"])]); seen::record(&home, "pg", Some("lab"), &Reach::reached()); seen::record(&home, "pg", Some("other"), &Reach::reached()); layerfs_store::postgresql::check::forget_machine(&home, "lab").unwrap(); @@ -146,152 +138,84 @@ fn a_removed_machine_is_forgotten() { assert!(got.of("lab").is_none()); assert!(got.of("other").is_some()); let record = StoreRecord::of(&home, "pg").unwrap(); - assert!(record.own_connection("lab").is_none()); + assert_eq!(record.attached(), ["other"]); std::fs::remove_dir_all(home).unwrap(); } #[test] -fn connections_list_every_side_that_connects() { +fn machines_list_the_attached_machines_with_their_reach() { let home = tempdir("rows"); - let own = SdkValue::map([("url", t("postgresql://10.0.0.2:7000/app"))]); - let record = store(&home, "pg", &[("machines", SdkValue::map([("zeta", own)]))]); + let record = store(&home, "pg", &[attached(&["zeta", "lab"])]); seen::record(&home, "pg", Some("lab"), &Reach::failed("timed out")); + seen::record(&home, "pg", Some("box"), &Reach::reached()); seen::record(&home, "pg", None, &Reach::reached()); - let rows = rows(&record, &["box", "native", "lab"]); - // this computer first, then by name; native is this computer's row + // names in record order, for a `store.list` item assert_eq!( - machines(&rows), - [None, Some("box"), Some("lab"), Some("zeta")] - ); - let row = |i: usize| &rows[i]; - assert_eq!(row(0).get_text("reached"), Some("ok")); - assert_eq!(row(0).get("own"), Some(&SdkValue::Bool(false))); - assert_eq!( - row(0).get("server"), - Some(&SdkValue::map([ - ("host", t("db.example")), - ("port", SdkValue::Int(6543)), - ("database", t("app")), - ])) - ); - // a Sandbox only: the Store's address, nothing seen - assert_eq!(row(1).get("reached"), Some(&SdkValue::Null)); - assert_eq!(row(1).get("reach"), Some(&SdkValue::Null)); - assert_eq!( - row(1).get_text("url"), - Some("postgresql://db.example:6543/app") + machines(&record, false), + SdkValue::List(vec![t("zeta"), t("lab")]) ); + let SdkValue::List(rows) = machines(&record, true) else { + panic!("rows"); + }; + // only attached machines: `box`'s reach is not a row + assert_eq!(rows.len(), 2, "{rows:?}"); + assert_eq!(rows[0].get_text("machine"), Some("zeta")); + assert_eq!(rows[0].get("reached"), Some(&SdkValue::Null)); + assert_eq!(rows[0].get("reach"), Some(&SdkValue::Null)); // a failed reach is a word, not a missing key - assert_eq!(row(2).get_text("reached"), Some("failed")); + assert_eq!(rows[1].get_text("reached"), Some("failed")); assert_eq!( - row(2).get("reach").and_then(|r| r.get_text("error")), + rows[1].get("reach").and_then(|r| r.get_text("error")), Some("timed out") ); - // its own address - assert_eq!(row(3).get("own"), Some(&SdkValue::Bool(true))); - assert_eq!( - row(3).get("server").and_then(|s| s.get("port")), - Some(&SdkValue::Int(7000)) - ); + // this computer's reach is the Store's own + let here = layerfs_store::postgresql::connect::reach(&record); + assert_eq!(here.get("ok"), Some(&SdkValue::Bool(true))); + // attach and detach keep the order of the others + let record = record + .with_attached("box", true) + .with_attached("zeta", false); + assert_eq!(record.attached(), ["lab", "box"]); + assert!(record.is_attached("box") && !record.is_attached("zeta")); + let none = record + .with_attached("lab", false) + .with_attached("box", false); + assert!(none.field("attached").is_none(), "{:?}", none.to_record()); std::fs::remove_dir_all(home).unwrap(); } +/// A Store whose password this home does not hold is not dialled: the +/// refusal names the connect that saves it; a record naming no user is +/// refused too. Once saved, it dials with its user and password put into +/// its address. #[test] -fn old_fields_read_outdated_and_an_update_drops_them_but_never_a_url() { - let home = tempdir("old"); - layerfs_store::postgresql::login::save(&home, "pg", "postgres", "pw").unwrap(); - let checked = SdkValue::map([("checked", SdkValue::map([("at", SdkValue::Int(1))]))]); - let own = SdkValue::map([ - ("url", t("postgresql://10.0.0.2/app")), - ("checked", SdkValue::Int(1)), - ]); - // old fields beside addresses alone: `store update --auth` is the fix, - // and its write drops them - let old = store( - &home, - "pg", - &[ - ("url", t("postgresql://db.example:6543/app?sslmode=disable")), - ("password", t("file:/no/such")), - ("machines", SdkValue::map([("lab", checked), ("box", own)])), - ], - ); - assert!(old.outdated_fields()); - let fix = "layerfs store update pg --auth pg"; - assert_eq!( - layerfs_store::state::recorded_under(&old, None).unwrap(), - State::broken(Reason::Outdated, Some(fix)) - ); - let clean = old.without_old_fields(); - assert!(!clean.outdated_fields(), "{:?}", clean.to_record()); - assert!(clean.field("password").is_none()); - assert_eq!( - clean.text("url"), - Some("postgresql://db.example:6543/app?sslmode=disable") - ); - assert_eq!( - clean.own_connection("box").unwrap().url.as_deref(), - Some("postgresql://10.0.0.2/app") - ); - assert!(clean.own_connection("lab").is_none()); - assert_eq!( - layerfs_store::state::recorded_under(&clean, None).unwrap(), - State::Ready - ); - // URLs that may hold a login are never rewritten (they were written - // without their login before the e0aa26e149 Decision): the record keeps - // them, still outdated, and its fix connects the Store again with the - // address alone and ``, then the machine's own address - let (url, box_url) = ( - "postgresql://postgres@db.example:6543/app?sslmode=disable", - "postgresql://postgres@10.0.0.2/app", - ); - let own = SdkValue::map([("url", t(box_url)), ("checked", SdkValue::Int(1))]); - let old = store( - &home, - "pg", - &[ - ("url", t(url)), - ("password", t("file:/no/such")), - ("machines", SdkValue::map([("box", own)])), - ], - ); - let fix = "layerfs store disconnect pg && layerfs store connect pg --auth --synchronous-commit local && layerfs store connect pg --machine box"; - assert_eq!( - layerfs_store::state::recorded_under(&old, None).unwrap(), - State::broken(Reason::Outdated, Some(fix)) - ); - let kept = old.without_old_fields(); - assert!(kept.outdated_fields(), "{:?}", kept.to_record()); - assert_eq!(kept.text("url"), Some(url)); +fn a_missing_password_is_refused_and_a_saved_one_is_dialled() { + let home = tempdir("missing"); + let record = store(&home, "pg", &[("url", t("postgres://db.example/app%23x"))]); + let fix = "layerfs store connect pg --password-stdin"; + let refusal = layerfs_store::record::url(&record).unwrap_err(); + assert_eq!(refusal.code, "InvalidInput"); + assert_eq!(refusal.detail.get_text("fix"), Some(fix)); + login::save(&home, "pg", "s3 cret").unwrap(); + let nameless = record.clone().without("user"); assert_eq!( - kept.own_connection("box").unwrap().url.as_deref(), - Some(box_url) + layerfs_store::record::url(&nameless).unwrap_err().code, + "InvalidInput" ); - // each kind of old field alone is outdated - for extra in [ - ("password", t("env:X")), - ("url", t("postgresql://db.example/app?user=bob")), - ("url", t("postgresql://db.example/app?passfile=/p")), - ] { - assert!( - store(&home, "pg", &[extra.clone()]).outdated_fields(), - "{extra:?}" - ); - } - assert!(!store(&home, "pg", &[]).outdated_fields()); - std::fs::remove_dir_all(home).unwrap(); -} - -#[test] -fn a_missing_login_reads_missing_and_wins_over_old_fields() { - let home = tempdir("missing"); - let record = store(&home, "pg", &[("password", t("file:/x"))]); - let fix = "layerfs store save-auth pg --user --password-stdin && layerfs store update pg --auth pg"; + // the URL dialled is the address alone with the login put in, never + // one holding an `@` or `#` of its own assert_eq!( - layerfs_store::state::recorded_under(&record, None).unwrap(), - State::broken(Reason::Missing, Some(fix)) + layerfs_store::record::url(&record).unwrap(), + "postgres://alice:s3%20cret@db.example/app%23x" ); + // the password is in the home's secret folder, not the record + let written = std::fs::read_to_string(paths::store_record(&home, "pg")).unwrap(); + assert!(!written.contains("s3 cret"), "{written}"); + let saved = login::read(&home, "pg").unwrap().unwrap(); + assert_eq!(saved.password(), "s3 cret"); + assert!(saved.changed_ms.is_some()); + login::forget(&home, "pg").unwrap(); + assert!(login::read(&home, "pg").unwrap().is_none()); std::fs::remove_dir_all(home).unwrap(); } @@ -327,39 +251,6 @@ fn urls_are_shown_as_written_or_hidden_whole() { } } -#[test] -fn a_login_file_that_cannot_be_read_is_a_broken_row() { - let home = tempdir("auths"); - layerfs_store::postgresql::login::save(&home, "good", "alice", "pw").unwrap(); - layerfs_store::postgresql::login::save(&home, "bad", "bob", "pw").unwrap(); - let bad = std::fs::read_dir(home.join("secret/auth")) - .unwrap() - .map(|e| e.unwrap().path()) - .find(|p| p.file_name().unwrap().to_string_lossy().starts_with("bad")) - .unwrap(); - std::fs::write(&bad, "{not json").unwrap(); - let listed = layerfs_store::postgresql::login::list(&home).unwrap(); - let Some(SdkValue::List(items)) = listed.get("items") else { - panic!("{listed:?}"); - }; - let row = |auth: &str| { - items - .iter() - .find(|item| item.get_text("auth") == Some(auth)) - .unwrap_or_else(|| panic!("{auth}: {items:?}")) - }; - assert_eq!(row("good").get_text("state"), Some("ready")); - assert_eq!(row("good").get_text("user"), Some("alice")); - assert_eq!(row("bad").get_text("state"), Some("broken")); - assert_eq!(row("bad").get_text("reason"), Some("failed")); - assert_eq!(row("bad").get("user"), Some(&SdkValue::Null)); - assert_eq!( - row("bad").get_text("fix"), - Some("layerfs store save-auth bad --user --password-stdin") - ); - std::fs::remove_dir_all(home).unwrap(); -} - /// The words of a check that failed `url`. fn failed_check(url: &str) -> String { match layerfs_persistence::postgresql_access(url, "layerfs") { @@ -419,21 +310,14 @@ fn only_a_dial_no_server_answered_is_not_connected() { /// client reads a URL's user part up to its first `@` anywhere. A URL /// holding an `@`, or a login key, is hidden whole and never rewritten /// (e0aa26e149 Decision): nothing shown keeps any part of the password (no -/// address or `--user` a fix line names, no `connections` row, no -/// refusal's server, no state's fix), the record stays as it was, -/// `outdated`, and is never dialled. +/// refusal, no fix line, no state's fix), and it is never dialled. #[test] -fn a_password_holding_at_never_shows_and_dialling_keeps_the_client_split() { - use layerfs_store::postgresql::connect::{refuse_login, refuse_login_with_fix, target, HIDDEN}; - use layerfs_store::postgresql::login; +fn a_password_holding_at_never_shows_and_is_never_dialled() { + use layerfs_store::postgresql::connect::{refuse_login, refuse_url, target, HIDDEN}; const PASSWORD: [&str; 2] = ["Zq7", "Xw9"]; let leaks = |text: &str| PASSWORD.iter().any(|part| text.contains(part)); let home = tempdir("at-password"); - login::save(&home, "pg", "alice", "s3 cret").unwrap(); - let connected = store(&home, "pg", &[]); - // every one is hidden whole, names no host and is never dialled (the - // `/` and `#` rows were shown without their login before the e0aa26e149 - // Decision) + login::save(&home, "pg", "s3 cret").unwrap(); for given in [ // the client's user part holds a query (its host is `Xw9`) "postgres://h/db?user=u&password=Zq7@Xw9", @@ -451,62 +335,29 @@ fn a_password_holding_at_never_shows_and_dialling_keeps_the_client_split() { assert!(refuse_login(given).is_err(), "{given}"); assert_eq!(shown(given), HIDDEN, "{given}"); assert!(target(given).is_err(), "{given}"); - let connected = [ - (None, None), - (Some(&connected), None), - (Some(&connected), Some("lab")), - ]; - for (connected, machine) in connected { - let refusal = refuse_login_with_fix("pg", given, connected, machine).unwrap_err(); + for new in [true, false] { + let refusal = refuse_url("pg", given, new).unwrap_err(); let text = format!("{} {:?}", refusal.message, refusal.detail); assert!(!leaks(&text), "{given}: {text}"); let fix = refusal.detail.get_text("fix").unwrap_or_default(); - assert!( - fix.contains(" ") && fix.contains("--user "), - "{given}: {fix}" + assert_eq!( + fix, "layerfs store connect pg --user --password-stdin", + "{given}" ); } - // an older record holding it, as the Store's address and a machine's own - let own = SdkValue::map([("url", t(given))]); - let record = store( - &home, - "pg", - &[ - ("url", t(given)), - ("machines", SdkValue::map([("lab", own)])), - ], - ); - assert!(record.outdated_fields(), "{given}"); - let shown_rows = format!("{:?}", rows(&record, &["lab"])); - assert!(!leaks(&shown_rows), "{given}: {shown_rows}"); - let fixes = format!( - "{:?} {} {}", - layerfs_store::state::recorded_under(&record, None), - login::no_auth_fix(&record), - login::missing_fix(&record, "pg") - ); - assert!(!leaks(&fixes), "{given}: {fixes}"); - // never dialled: its fix replaces it, and names no part of it + // a record holding it is never dialled, and nothing it answers + // names any part of it + let record = store(&home, "pg", &[("url", t(given))]); let refusal = layerfs_store::record::url(&record).unwrap_err(); let text = format!("{} {:?}", refusal.message, refusal.detail); assert_eq!(refusal.code, "InvalidInput", "{given}"); assert!(!leaks(&text), "{given}: {text}"); - // `store update`'s write keeps it as it was, still outdated (it - // was cleaned before the e0aa26e149 Decision); the update itself - // refuses such a record - record.without_old_fields().write(&home).unwrap(); - let kept = StoreRecord::of(&home, "pg").unwrap(); - assert!(kept.outdated_fields(), "{given}"); - assert_eq!(kept.text("url"), Some(given), "{given}"); - let own = kept.own_connection("lab").unwrap().url; - assert_eq!(own.as_deref(), Some(given), "{given}"); } - // the URL dialled is the address alone with the login put in, never - // one holding an `@` or `#` of its own - let record = store(&home, "pg", &[("url", t("postgres://db.example/app%23x"))]); + // a `#` alone holds no login: a connected Store's fix needs none + let refusal = refuse_url("pg", "postgresql://h/d#x", false).unwrap_err(); assert_eq!( - layerfs_store::record::url(&record).unwrap(), - "postgres://alice:s3%20cret@db.example/app%23x" + refusal.detail.get_text("fix"), + Some("layerfs store connect pg ") ); std::fs::remove_dir_all(home).unwrap(); } diff --git a/control/crates/layerfs-store/tests/postgresql_no_auth.rs b/control/crates/layerfs-store/tests/postgresql_no_auth.rs deleted file mode 100644 index 9dddb17414..0000000000 --- a/control/crates/layerfs-store/tests/postgresql_no_auth.rs +++ /dev/null @@ -1,222 +0,0 @@ -//! A PostgreSQL Store recorded before saved logins (a `password` reference -//! and no `auth`) is not dialled with that reference (CUT, owner -//! 2026-11-19): every call is refused `InvalidInput` and its state is -//! `broken` `outdated`, each with the fix that saves a login and names it, -//! its `--user` `` to fill in: no user is read from a URL, and a URL -//! holding one is never rewritten, so the Store is connected again with the -//! address alone (the e0aa26e149 Decision; UI pass 2, F6 named the URL's -//! user before). The record is only read, never converted. -use layerfs_bridge::control::SdkValue; -use layerfs_home::state::{Reason, State}; -use layerfs_store::record::{url, url_on, StoreRecord}; -use std::path::Path; - -/// The fix of the older record, whose URL names a user: `` to fill -/// in, and the Store connected again with the address alone (the user was -/// named and the URL cleaned by the update before the e0aa26e149 Decision). -const FIX: &str = "layerfs store save-auth --user --password-stdin && layerfs store disconnect pg && layerfs store connect pg --auth "; - -fn older(home: &Path) -> StoreRecord { - let fields = [ - ("name", SdkValue::text("pg")), - ("kind", SdkValue::text("postgresql")), - ( - "url", - SdkValue::text("postgresql://owner@db.example:5432/layerfs_db"), - ), - ("schema", SdkValue::text("layerfs")), - ("password", SdkValue::text("env:LAYERFS_TEST_PG_PASSWORD")), - ( - "machines", - SdkValue::map([( - "lab", - SdkValue::map([("password", SdkValue::text("file:/no/such/file"))]), - )]), - ), - ]; - let fields = fields.into_iter().map(|(k, v)| (k.to_owned(), v)); - StoreRecord::from_record("pg", SdkValue::Map(fields.collect())).in_home(home) -} - -#[test] -fn a_record_with_no_saved_login_is_refused_with_the_save_auth_fix() { - let home = std::env::temp_dir().join(format!("layerfs-pg-no-auth-{}", std::process::id())); - let record = older(&home); - for refused in [ - url(&record).unwrap_err(), - url_on(&record, "lab").unwrap_err(), - ] { - assert_eq!(refused.code, "InvalidInput", "{}", refused.message); - assert_eq!(refused.detail.get_text("fix"), Some(FIX)); - } - // a password reference is no address of a machine's own - assert!(record.own_connections().is_empty()); -} - -#[test] -fn its_state_is_broken_outdated_with_the_same_fix() { - let home = std::env::temp_dir().join(format!("layerfs-pg-no-auth-s-{}", std::process::id())); - let state = layerfs_store::state::recorded_under(&older(&home), None).unwrap(); - assert_eq!(state, State::broken(Reason::Outdated, Some(FIX))); - // a URL naming no user is named by `store update`; one naming a user, - // in a parameter or a user part, is replaced (its user was named, - // shell-quoted, before the e0aa26e149 Decision); `` either way - let update = "layerfs store save-auth --user --password-stdin && layerfs store update pg --auth "; - for (url, fix) in [ - ("postgresql://db.example:5432/layerfs_db", update), - ("postgresql://db.example/layerfs_db?user=o%27k", FIX), - ("postgres://a%20b:pw@db.example/layerfs_db", FIX), - ] { - let record = older(&home).with("url", SdkValue::text(url)); - let state = layerfs_store::state::recorded_under(&record, None).unwrap(); - assert_eq!(state, State::broken(Reason::Outdated, Some(fix)), "{url}"); - } - // a record naming a login the home does not hold reads `missing`, its - // fix saving that login and connecting the Store again with it (spec - // v23; it updated the Store to it before the e0aa26e149 Decision) - let named = older(&home).with("auth", SdkValue::text("pg-app")); - let state = layerfs_store::state::recorded_under(&named, None).unwrap(); - let fix = "layerfs store save-auth pg-app --user --password-stdin && layerfs store disconnect pg && layerfs store connect pg --auth pg-app"; - assert_eq!(state, State::broken(Reason::Missing, Some(fix))); -} - -/// A record naming its saved login is dialled with it: the login's user -/// and password go into the record's URL (which keeps neither), for the -/// Store and for a machine's own address; nothing needs a server. -#[test] -fn a_saved_login_goes_into_the_dialled_url() { - let home = std::env::temp_dir().join(format!("layerfs-pg-login-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&home); - layerfs_home::home::ensure(&home).unwrap(); - layerfs_store::postgresql::login::save(&home, "pg-app", "alice", "s3 cret").unwrap(); - let record = StoreRecord::connected( - "pg", - "postgresql://db.example:5432/layerfs_db", - "layerfs", - "local", - Some("pg-app"), - ) - .in_home(&home); - assert_eq!( - url(&record).unwrap(), - "postgresql://alice:s3%20cret@db.example:5432/layerfs_db" - ); - assert_eq!( - url_on(&record, "lab").unwrap(), - "postgresql://alice:s3%20cret@db.example:5432/layerfs_db" - ); - std::fs::remove_dir_all(home).unwrap(); -} - -/// Every URL a machine's Sandbox dials (`url_on`, which the route's reach -/// check reads) is a `postgres://` or `postgresql://` URL: libpq's -/// key=value words, as a Store's address or a machine's own, are refused -/// `InvalidInput` when the login is put in, before anything reads or dials -/// them. -#[test] -fn a_key_value_address_is_refused_before_anything_dials_it() { - let home = std::env::temp_dir().join(format!("layerfs-pg-words-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&home); - layerfs_home::home::ensure(&home).unwrap(); - layerfs_store::postgresql::login::save(&home, "pg-app", "alice", "s3 cret").unwrap(); - for words in [ - "host=localhost dbname=layerfs_db", - "host=db.example port=5432 dbname=layerfs_db", - ] { - let record = - StoreRecord::connected("pg", words, "layerfs", "local", Some("pg-app")).in_home(&home); - for refusal in [ - url(&record).unwrap_err(), - url_on(&record, "lab").unwrap_err(), - ] { - assert_eq!(refusal.code, "InvalidInput", "{}", refusal.message); - assert!( - refusal.message.contains("postgresql:// or postgres://"), - "{}", - refusal.message - ); - } - } - std::fs::remove_dir_all(home).unwrap(); -} - -/// The user part a URL holds is the one the daemon's client -/// (tokio-postgres 0.7, `UrlParser::parse_credentials`) reads: everything -/// before the first `@` anywhere in the URL, not only before its first -/// `/`. A URL holding an `@` names a user that way and is refused at -/// connect, and is never dialled: the login goes only into an address -/// alone, which keeps its host, path and parameters (the client reads them -/// back as given before it is dialled). -#[test] -fn the_login_replaces_the_user_part_its_client_reads() { - // (url, the user the client reads, the hosts it reads after it) - for (given, user, hosts) in [ - // the review's case: both rules read `b` - ( - "postgres://localhost?x=a@b", - Some("localhost?x=a"), - vec!["b"], - ), - // an `@` only after the path: the client's user part runs to it - ( - "postgres://localhost/db?x=a@b", - Some("localhost/db?x=a"), - vec!["b"], - ), - // two `@` before the path: the first ends the user part - ("postgres://a@b@c/db", Some("a"), vec!["b@c"]), - ( - "postgresql://u:p@db.example/db?x=1", - Some("u"), - vec!["db.example"], - ), - ("postgres://db.example:5432/db", None, vec!["db.example"]), - ] { - // the client reads the whole URL only where it knows each key - let known = given.replace("?x=1", "?application_name=1"); - let read: postgres::Config = known.parse().unwrap(); - assert_eq!(read.get_user(), user, "{given}"); - let read_hosts: Vec = (read.get_hosts().iter()) - .map(|host| format!("{host:?}")) - .collect(); - let hosts: Vec = hosts.iter().map(|h| format!("Tcp({h:?})")).collect(); - assert_eq!(read_hosts, hosts, "{given}"); - // a user part the client reads is a user the URL names: refused - let refused = layerfs_store::postgresql::connect::refuse_login(given); - assert_eq!(refused.is_err(), user.is_some(), "{given}"); - } - let home = std::env::temp_dir().join(format!("layerfs-pg-at-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&home); - layerfs_home::home::ensure(&home).unwrap(); - layerfs_store::postgresql::login::save(&home, "pg-app", "alice", "s3 cret").unwrap(); - // (recorded, dialled): a recorded URL holding an `@` is not dialled - for (recorded, dialled) in [ - ("postgres://localhost/db?x=a@b", None), - ("postgres://a@b@c/db", None), - ( - "postgres://db.example/layerfs_db?application_name=x", - Some("postgres://alice:s3%20cret@db.example/layerfs_db?application_name=x"), - ), - ] { - let record = StoreRecord::connected("pg", recorded, "layerfs", "local", Some("pg-app")) - .in_home(&home); - match url(&record) { - Ok(url) => assert_eq!(Some(url.as_str()), dialled, "{recorded}"), - Err(refusal) => { - assert_eq!(dialled, None, "{recorded}: {}", refusal.message); - assert_eq!(refusal.code, "InvalidInput", "{recorded}"); - assert!(!refusal.message.contains("s3"), "{}", refusal.message); - // connected again with the address alone, the Store's - // login or another (``), its `synchronous_commit` kept - // (it was `layerfs store connect pg `, which dials with - // the record's login, before the e0aa26e149 Decision) - assert_eq!( - refusal.detail.get_text("fix"), - Some("layerfs store disconnect pg && layerfs store connect pg --auth --synchronous-commit local"), - "{recorded}" - ); - } - } - } - std::fs::remove_dir_all(home).unwrap(); -} diff --git a/control/crates/layerfs-store/tests/postgresql_status.rs b/control/crates/layerfs-store/tests/postgresql_status.rs index 30d3b8851d..ee6cce03d9 100644 --- a/control/crates/layerfs-store/tests/postgresql_status.rs +++ b/control/crates/layerfs-store/tests/postgresql_status.rs @@ -248,14 +248,7 @@ fn status(home: &Path) -> SdkValue { live: true, stats: false, }; - layerfs_store::get::get( - home, - &mut Events::new(&mut sink), - "pgs", - with, - (&machines, &|_: &std::path::Path| Vec::new()), - ) - .unwrap() + layerfs_store::get::get(home, &mut Events::new(&mut sink), "pgs", with, &machines).unwrap() } /// The `live` section's `phases`. @@ -283,15 +276,15 @@ fn postgresql_store_status_projects_busy_leftover_and_idle() { let home = tempdir("home"); home::ensure(&home).unwrap(); - // `store.connect` records exactly this shape, with its saved login - // (`store.save_auth`); `store.status` reads it. The login is the one + // `store.connect` records exactly this shape, its user in the record + // and its password a secret of the home; `store.status` reads it. The login is the one // the client reads in the URL (a trust-auth server takes any password). let read: postgres::Config = url.parse().expect("LAYERFS_TEST_POSTGRES_URL is a URL"); let user = read.get_user().unwrap_or("postgres"); let password = read.get_password().map_or("unused".to_owned(), |password| { String::from_utf8(password.to_vec()).expect("a UTF-8 password") }); - layerfs_store::postgresql::login::save(&home, "pg", user, &password).unwrap(); + layerfs_store::postgresql::login::save(&home, "pgs", &password).unwrap(); // the record keeps the address alone: the URL as given when it holds no // login, else (the test server's URL names its user) the URL after the // user part the client reads (its first `@`), which must then be an @@ -310,7 +303,7 @@ fn postgresql_store_status_projects_busy_leftover_and_idle() { }; layerfs_store::postgresql::connect::refuse_login(&address) .expect("LAYERFS_TEST_POSTGRES_URL is an address with its login in its user part"); - StoreRecord::connected("pgs", &address, "layerfs", "off", Some("pg")) + StoreRecord::connected("pgs", &address, user, "layerfs", "off") .write(&home) .unwrap(); let mut admin = postgres::Client::connect(&url, postgres::NoTls).unwrap(); diff --git a/control/crates/layerfs-store/tests/postgresql_url_corpus.rs b/control/crates/layerfs-store/tests/postgresql_url_corpus.rs index 0249e0fe14..32506c85ec 100644 --- a/control/crates/layerfs-store/tests/postgresql_url_corpus.rs +++ b/control/crates/layerfs-store/tests/postgresql_url_corpus.rs @@ -15,23 +15,24 @@ //! the record itself; (b) a URL shown equals the original byte for byte and //! holds no login; (c) a URL dialled reads back exactly the saved login and //! the address's endpoints, and holds no `#`; (d) no record changes on a -//! read or a refused update, and a write that is not given a new URL for -//! it (`store connect --machine` of another machine, `store disconnect -//! --machine`, `machine remove`) keeps every URL byte for byte; (e) a -//! refusal names only fixed words, a URL holding a `#` gets the `%23` hint, -//! a fix saves a login exactly when the URL may hold one, and every fix +//! read or a refused connect, and a write that is not given a new URL for +//! it (`store attach` and `store detach` of a machine, `machine remove`) +//! keeps every URL byte for byte; (e) a refusal names only fixed words, a +//! URL holding a `#` gets the `%23` hint, a fix gives the login apart +//! exactly when the URL may hold one (or the Store is new), and every fix //! names the address `` and the user ``, never text of a URL. use layerfs_bridge::control::SdkValue; use layerfs_home::home::{self, paths, write_entity}; use layerfs_home::names::StoreName; -use layerfs_store::postgresql::connect::{ - connections, holds_login, refuse_login, refuse_login_with_fix, shown, target, -}; +use layerfs_store::postgresql::connect::{holds_login, refuse_login, refuse_url, shown, target}; use layerfs_store::postgresql::{check, login}; -use layerfs_store::record::{OwnConnection, StoreRecord}; +use layerfs_store::record::StoreRecord; use std::net::IpAddr; use std::path::{Path, PathBuf}; +/// The fix of a refused URL that gives the login apart. +const LOGIN_FIX: &str = "layerfs store connect pg --user --password-stdin"; + /// What is shown of a URL that may hold a login. const HIDDEN: &str = "postgresql://"; @@ -151,40 +152,29 @@ fn login_values(url: &str) -> Vec> { } /// The words of a fix line that are not fixed: every word but the -/// commands, flags, placeholders, the Store and machine names and the -/// recorded `synchronous_commit`. Empty for every fix: no fix names text of -/// a URL. +/// commands, flags, placeholders and the Store's name. Empty for every +/// fix: no fix names text of a URL. fn derived(fix: &str) -> String { - const FIXED: [&str; 19] = [ + const FIXED: [&str; 9] = [ "layerfs", "store", - "save-auth", "--user", "--password-stdin", "&&", "connect", - "update", "disconnect", - "--auth", - "--machine", - "--synchronous-commit", - "", "", "", - "pg", - "lab", - "local", - "new", ]; - let words = fix.split(' ').filter(|word| !FIXED.contains(word)); + let words = (fix.split(' ')).filter(|word| !FIXED.contains(word) && *word != "pg"); words.collect::>().join(" ") } /// The fixed messages of a refused URL: no part of the URL is in one. const MESSAGES: [&str; 5] = [ - "the URL names a user or holds a password (or a password file); give the address alone and the login with --auth (`layerfs store save-auth` saves one)", - "the URL names a user or holds a password (or a password file); give the address alone and the login with --auth (`layerfs store save-auth` saves one); an `@` or `#` that is part of the address is written %40 or %23", - "the URL is not one its PostgreSQL client reads, or names a user or holds a password (or a password file) under a key it does not know: give the address alone, postgresql://host[:port][,host[:port]...]/database?key=value&... with keys the client knows (not `passfile`, `sslpassword`, `sslkey` or `sslcert`), and the login with --auth (`layerfs store save-auth` saves one)", + "the URL names a user or holds a password (or a password file); give the address alone and the login with --user and --password-stdin", + "the URL names a user or holds a password (or a password file); give the address alone and the login with --user and --password-stdin; an `@` or `#` that is part of the address is written %40 or %23", + "the URL is not one its PostgreSQL client reads, or names a user or holds a password (or a password file) under a key it does not know: give the address alone, postgresql://host[:port][,host[:port]...]/database?key=value&... with keys the client knows (not `passfile`, `sslpassword`, `sslkey` or `sslcert`), and the login with --user and --password-stdin", "the URL holds a `#`; one that is part of the address is written %23", "a PostgreSQL URL starts postgresql:// or postgres://", ]; @@ -253,7 +243,7 @@ fn messages() -> Vec { all.push(tls(&format!("`{key}`"))); } for key in ["passfile", "sslpassword"] { - all.push(format!("the URL names a user or holds a password (or a password file) in `{key}`, which its PostgreSQL client does not read; give the address alone and the login with --auth (`layerfs store save-auth` saves one)")); + all.push(format!("the URL names a user or holds a password (or a password file) in `{key}`, which its PostgreSQL client does not read; give the address alone and the login with --user and --password-stdin")); } for key in KEYS { all.push(format!("the URL's value of `{key}` is not one its PostgreSQL client reads: give the address with values the client reads")); @@ -264,54 +254,36 @@ fn messages() -> Vec { all } -/// Writes PostgreSQL Store `pg` with `url` as its address and machine -/// `lab`'s own, naming login `pg`. +/// Writes PostgreSQL Store `pg` with `url` as its address, user `alice` +/// and machine `lab` attached, as `store.connect` and `store.attach` write +/// it. fn store(home: &Path, url: &str) -> StoreRecord { - store_with(home, url, url, Some("pg")) -} - -/// Writes PostgreSQL Store `pg` with address `url`, machine `lab`'s own -/// address `lab`, naming login `auth` when given, `synchronous_commit` -/// `local`. -fn store_with(home: &Path, url: &str, lab: &str, auth: Option<&str>) -> StoreRecord { - store_sync(home, url, lab, auth, "local") -} - -/// [`store_with`] with `synchronous_commit` `sync`. -fn store_sync(home: &Path, url: &str, lab: &str, auth: Option<&str>, sync: &str) -> StoreRecord { - let own = SdkValue::map([("url", t(lab))]); - let mut fields = vec![ + let fields = vec![ ("name", t("pg")), ("kind", t("postgresql")), ("url", t(url)), + ("user", t("alice")), ("schema", t("layerfs")), - ("synchronous_commit", t(sync)), + ("synchronous_commit", t("local")), ("binding", SdkValue::Bytes((0..32).collect())), - ("machines", SdkValue::map([("lab", own)])), + ("attached", SdkValue::List(vec![t("lab")])), ]; - fields.extend(auth.map(|auth| ("auth", t(auth)))); let fields = fields.into_iter().map(|(k, v)| (k.to_owned(), v)).collect(); write_entity(&paths::store_record(home, "pg"), &SdkValue::Map(fields)).unwrap(); StoreRecord::of(home, "pg").unwrap() } -/// The texts of `connections` rows: each `url` and its `server`'s host -/// and database. +/// The texts `store.get` shows of `record`'s URL. fn row_texts(record: &StoreRecord) -> Vec { - let SdkValue::List(rows) = connections(record, &["lab".to_owned()]) else { - panic!("connections"); - }; - let mut texts = Vec::new(); - for row in rows { - // the hidden form is fixed text, none of the URL's - let url = row.get_text("url").unwrap_or_default(); - texts.extend((url != HIDDEN).then(|| url.to_owned())); - if let Some(server) = row.get("server").filter(|s| **s != SdkValue::Null) { - texts.push(server.get_text("host").unwrap_or_default().to_owned()); - texts.push(server.get_text("database").unwrap_or_default().to_owned()); - } - } - texts + let home = record.home().unwrap(); + let state = layerfs_home::state::State::Ready; + let got = layerfs_store::get::summary(home, record, &state, None, true).unwrap(); + let url = got.get_text("url").unwrap_or_default(); + // the hidden form is fixed text, none of the URL's + (url != HIDDEN) + .then(|| url.to_owned()) + .into_iter() + .collect() } /// The state fix of `record`. @@ -674,27 +646,8 @@ fn check(home: &Path, given: &str, meant: &str) { if scheme && after.contains('#') { assert!(refusal.message.contains("%23"), "(e) {given}"); } - let clean = store_with( - home, - "postgres://db.example/app", - "postgres://lab/app", - Some("pg"), - ); - let older = store_with( - home, - "postgres://u:Zq7@Xw9@db.example/app", - "postgres://lab/app", - None, - ); - let connected = [None, Some(&clean), Some(&older)]; - for (connected, machine) in connected - .iter() - .flat_map(|c| [(*c, None), (*c, Some("lab"))]) - { - if connected.is_none() && machine.is_some() { - continue; - } - let Err(refusal) = refuse_login_with_fix("pg", given, connected, machine) else { + for new in [true, false] { + let Err(refusal) = refuse_url("pg", given, new) else { panic!("{given}"); }; assert!(messages.contains(&refusal.message), "{given}"); @@ -702,29 +655,22 @@ fn check(home: &Path, given: &str, meant: &str) { assert!(!scheme, "{given}: no fix"); continue; }; - assert_eq!(fix.contains("save-auth"), held, "(e) {given}: {fix}"); + assert_eq!( + fix.contains("--password-stdin"), + held || new, + "(e) {given}: {fix}" + ); assert!(fix.contains(" "), "(e) {given}: {fix}"); assert_eq!(derived(fix), "", "(e) {given}: {fix}"); } } } - // an older record holding it, as the Store's address and a machine's own + // a record holding it as the Store's address let record = store(home, given); let bytes = || std::fs::read(paths::store_record(home, "pg")).unwrap(); let before = bytes(); - assert_eq!( - record.outdated_fields(), - refuse_login(given).is_err(), - "{given}" - ); texts.extend(row_texts(&record)); - let fixes = [ - state_fix(&record), - login::no_auth_fix(&record), - login::missing_fix(&record, "pg"), - login::outdated_fix(&record, "pg"), - login::update_fix(&record, Some("new"), None), - ]; + let fixes = [state_fix(&record), login::password_fix(&record)]; // a fix names only fixed words (checked empty here), so no secret for fix in fixes { assert_eq!(derived(&fix), "", "(e) {given}: {fix}"); @@ -753,10 +699,11 @@ fn check(home: &Path, given: &str, meant: &str) { "(c) {given}: {}", refusal.message ); - let message = (refusal.message) - .strip_prefix("PostgreSQL Store pg's URL: ") - .unwrap_or(&refusal.message); - assert!(messages.iter().any(|m| m == message), "{given}: {message}"); + assert!( + messages.contains(&refusal.message), + "{given}: {}", + refusal.message + ); let fix = refusal.detail.get_text("fix").unwrap_or_default(); assert_eq!(derived(fix), "", "(e) {given}: {fix}"); texts.push(derived(fix)); @@ -764,32 +711,15 @@ fn check(home: &Path, given: &str, meant: &str) { } // (d) no read wrote the record assert_eq!(bytes(), before, "(d) {given}: a read wrote"); - // (d) another machine's own address is connected and disconnected, and - // a machine removed: every URL stays byte for byte + // (d) another machine is attached and detached, and a machine + // removed: every URL stays byte for byte let name = StoreName::parse("pg").unwrap(); - let other = OwnConnection { - url: Some("postgres://other.example/app".to_owned()), - }; - check::save_own(home, &name, "other", &other, record.binding()).unwrap(); + assert!(check::attach(home, &name, "other", record.binding()).unwrap()); let kept = StoreRecord::of(home, "pg").unwrap(); assert_eq!(kept.text("url"), Some(given), "(d) {given}"); - let lab = kept.own_connection("lab").and_then(|own| own.url); - assert_eq!(lab.as_deref(), Some(given), "(d) {given}"); - check::save_own( - home, - &name, - "other", - &OwnConnection::default(), - record.binding(), - ) - .unwrap(); + check::detach(home, &name, "other", &|_| Ok(())).unwrap(); check::forget_machine(home, "other").unwrap(); assert_eq!(bytes(), before, "(d) {given}: rewritten"); - // and `store update` keeps it as it is too: it drops old fields only - let updated = record.clone().without_old_fields(); - assert_eq!(updated.text("url"), Some(given), "(d) {given}"); - let lab = updated.own_connection("lab").and_then(|own| own.url); - assert_eq!(lab.as_deref(), Some(given), "(d) {given}"); // (a) for text in &texts { for secret in &secrets { @@ -829,7 +759,7 @@ fn separated() -> Vec<(String, String)> { #[test] fn every_url_is_shown_written_and_dialled_as_the_rule_says() { let home = tempdir("corpus"); - login::save(&home, "pg", "alice", LOGIN_PASSWORD).unwrap(); + login::save(&home, "pg", LOGIN_PASSWORD).unwrap(); for (given, meant) in CORPUS { check(&home, given, meant); } @@ -894,36 +824,37 @@ fn the_reviewers_urls_show_what_their_client_reads() { } } -/// M3 / item 6: an older record whose URL holds an `@` in a value is never -/// rewritten to another host: `store update --auth` refuses it with the -/// steps that connect the Store again with the address alone, and writes -/// nothing. +/// M3 / item 6: a record whose URL holds an `@` in a value is never +/// rewritten to another host: a connect of the Store with an address that +/// does not answer writes nothing. #[test] -fn an_update_never_rewrites_a_url_to_another_host() { +fn a_connect_never_rewrites_an_older_url_to_another_host() { let home = tempdir("update"); - login::save(&home, "pg", "alice", LOGIN_PASSWORD).unwrap(); + login::save(&home, "pg", LOGIN_PASSWORD).unwrap(); let given = "postgres://u:Zq7Xw9q@realhost.invalid/db?application_name=me@laptop.example"; store(&home, given); let before = std::fs::read(paths::store_record(&home, "pg")).unwrap(); - let request = layerfs_store::postgresql::update::StoreUpdate { - store: StoreName::parse("pg").unwrap(), - auth: Some("pg".to_owned()), - synchronous_commit: None, - }; - let refusal = layerfs_store::postgresql::update::update(&home, &request).unwrap_err(); - assert_eq!(refusal.code, "InvalidInput", "{}", refusal.message); - // the machine's own address is connected again, not left on the - // Store's (review d194c7e9df N2), after the Store is (e0aa26e149) - assert_eq!( - refusal.detail.get_text("fix"), - Some("layerfs store disconnect pg && layerfs store connect pg --auth pg --synchronous-commit local && layerfs store connect pg --machine lab") - ); + let refusal = connect_again(&home).unwrap_err(); + assert_eq!(refusal.code, "Unavailable", "{}", refusal.message); assert!(!refusal.message.contains("laptop") && !refusal.message.contains("Zq7")); let after = std::fs::read(paths::store_record(&home, "pg")).unwrap(); assert_eq!(before, after, "the record was written"); std::fs::remove_dir_all(home).unwrap(); } +/// A connect of connected Store `pg` with an address alone where nothing +/// listens, and no new login. +fn connect_again(home: &Path) -> Result { + let request = layerfs_store::postgresql::connect::StoreConnect { + store: StoreName::parse("pg").unwrap(), + url: "postgres://127.0.0.1:1/app?connect_timeout=5".to_owned(), + user: None, + password: None, + synchronous_commit: None, + }; + layerfs_store::postgresql::connect::update(home, &request) +} + /// The rows of the d194c7e9df review: what each shows, names and fixes. #[test] fn the_d194c7e9df_review_rows_show_name_and_fix_as_the_rule_says() { @@ -936,12 +867,9 @@ fn the_d194c7e9df_review_rows_show_name_and_fix_as_the_rule_says() { ] { assert_eq!(shown(given), HIDDEN, "{given}"); assert!(target(given).is_err(), "{given}"); - let fix = refuse_login_with_fix("pg", given, None, None).unwrap_err(); + let fix = refuse_url("pg", given, true).unwrap_err(); let fix = fix.detail.get_text("fix").unwrap().to_owned(); - assert_eq!( - fix, - "layerfs store save-auth --user --password-stdin && layerfs store connect pg --auth " - ); + assert_eq!(fix, LOGIN_FIX); } // N1: a password of one or two bytes, and any user part, is hidden // whole (the short user part was shown without its login before) @@ -952,260 +880,77 @@ fn the_d194c7e9df_review_rows_show_name_and_fix_as_the_rule_says() { ] { assert_eq!(shown(given), HIDDEN, "{given}"); } - let home = tempdir("d194"); - let clean = store_with( - &home, - "postgres://db.example/app", - "postgres://lab/app", - Some("pg"), - ); // S1: the TLS setting the client does not read is named, with what // `require` checks; the URL may hold a login (the client does not read // it), so the fix saves one (it saved none before the e0aa26e149 // Decision) - for (given, connected, machine, message, fix) in [ + for (given, new, message, fix) in [ ( "postgresql://db.example/app?sslmode=verify-full", - None, - None, + true, tls("`sslmode=verify-full`"), - "layerfs store save-auth --user --password-stdin && layerfs store connect pg --auth ", + LOGIN_FIX, ), ( "postgresql://db.example/app?sslrootcert=%2Fca.pem&sslmode=require", - Some(&clean), - None, + false, format!("{}{PRIVATE_CA}", tls("`sslrootcert`")), - "layerfs store save-auth --user --password-stdin && layerfs store update pg --auth && layerfs store connect pg ", + LOGIN_FIX, ), // N5: a `#` is named with any other refusal, and one refused only - // for its `#` is connected again with the address alone (``, - // not a form of LayerFS's own) + // for its `#` on a connected Store is connected again with the + // address alone (``, not a form of LayerFS's own) ( "postgres://h/db?sslmode=require#f", - Some(&clean), - Some("lab"), + false, format!("{}{HASH}", hash_in("sslmode")), - "layerfs store save-auth --user --password-stdin && layerfs store update pg --auth && layerfs store connect pg --machine lab", - ), - ( - "postgres://h/d#x", - None, - None, - MESSAGES[3].to_owned(), - "layerfs store connect pg --auth ", + LOGIN_FIX, ), + ("postgres://h/d#x", true, MESSAGES[3].to_owned(), LOGIN_FIX), ( "postgres://h/d#x", - Some(&clean), - Some("lab"), + false, MESSAGES[3].to_owned(), - "layerfs store connect pg --machine lab", + "layerfs store connect pg ", ), ( "postgres://h/db?password=Zq7Xw9q#f", - None, - None, + true, format!("{}{HASH}", MESSAGES[0]), - "layerfs store save-auth --user --password-stdin && layerfs store connect pg --auth ", + LOGIN_FIX, ), // a login is refused first, and a key no list names may hold one ( "postgres://h/db?sslmode=verify-full&password=Zq7Xw9q", - None, - None, + true, MESSAGES[0].to_owned(), - "layerfs store save-auth --user --password-stdin && layerfs store connect pg --auth ", + LOGIN_FIX, ), ( "postgres://h/db?sslmode=verify-full&foo=Zq7Xw9q", - None, - None, + true, tls("`sslmode=verify-full`"), - "layerfs store save-auth --user --password-stdin && layerfs store connect pg --auth ", + LOGIN_FIX, ), // a `password` with no `=`, and a `user` the client cannot decode, // are a login all the same (found by fuzzing) ( "postgres://h/db?sslmode=verify-full&password", - None, - None, + true, MESSAGES[0].to_owned(), - "layerfs store save-auth --user --password-stdin && layerfs store connect pg --auth ", + LOGIN_FIX, ), ( "postgres://h/db?user=%db&sslmode=verify-full", - None, - None, + true, MESSAGES[0].to_owned(), - "layerfs store save-auth --user --password-stdin && layerfs store connect pg --auth ", + LOGIN_FIX, ), ] { - let refusal = refuse_login_with_fix("pg", given, connected, machine).unwrap_err(); + let refusal = refuse_url("pg", given, new).unwrap_err(); assert_eq!(refusal.message, message, "{given}"); assert_eq!(refusal.detail.get_text("fix"), Some(fix), "{given}"); } - std::fs::remove_dir_all(home).unwrap(); -} - -/// N2, N3 of the d194c7e9df review, S3 and N1 of the e0aa26e149 review: a -/// machine's own address that may hold a login is disconnected first and -/// connected again as the address alone after the login is named; a Store -/// address that may hold one takes the whole Store, disconnected and -/// connected again with its recorded `synchronous_commit`; and no step -/// dials with the login the record names before the one the fix names. -#[test] -fn a_machine_address_is_connected_again_and_an_update_names_its_login() { - let home = tempdir("machine-fix"); - login::save(&home, "new", "alice", LOGIN_PASSWORD).unwrap(); - let (clean, held) = ( - "postgres://db.example/app", - "postgres://u:Zq7@Xw9@db.example/app", - ); - // the record's own login is saved: its outdated fix connects the - // machine's address with `` named first (it connected the - // machine with the record's login first before the e0aa26e149 Decision) - let named = store_with(&home, clean, held, Some("new")); - assert_eq!( - login::outdated_fix(&named, "new"), - "layerfs store disconnect pg --machine lab && layerfs store update pg --auth && layerfs store connect pg --machine lab" - ); - let none = store_with(&home, clean, held, None); - assert_eq!( - login::no_auth_fix(&none), - "layerfs store save-auth --user --password-stdin && layerfs store disconnect pg --machine lab && layerfs store update pg --auth && layerfs store connect pg --machine lab" - ); - // the whole Store goes with an address that may hold a login: every - // machine's own address is connected again after it, and the recorded - // `synchronous_commit` is kept - let both = store_sync(&home, held, clean, None, "off"); - assert_eq!( - login::no_auth_fix(&both), - "layerfs store save-auth --user --password-stdin && layerfs store disconnect pg && layerfs store connect pg --auth --synchronous-commit off && layerfs store connect pg --machine lab" - ); - // N3: the record names `old`, not saved; the update gives `new` - store_with(&home, clean, held, Some("old")); - let before = std::fs::read(paths::store_record(&home, "pg")).unwrap(); - let request = layerfs_store::postgresql::update::StoreUpdate { - store: StoreName::parse("pg").unwrap(), - auth: Some("new".to_owned()), - synchronous_commit: None, - }; - let refusal = layerfs_store::postgresql::update::update(&home, &request).unwrap_err(); - assert_eq!(refusal.code, "InvalidInput", "{}", refusal.message); - assert_eq!( - refusal.detail.get_text("fix"), - Some("layerfs store disconnect pg --machine lab && layerfs store update pg --auth new && layerfs store connect pg --machine lab") - ); - let after = std::fs::read(paths::store_record(&home, "pg")).unwrap(); - assert_eq!(before, after, "the record was written"); - std::fs::remove_dir_all(home).unwrap(); -} - -/// `store update pg --auth new` (and `--synchronous-commit sync` when -/// given) of record `pg` (address `url`, machine `lab`'s own `lab`, login -/// `auth`, `synchronous_commit` `off`): its refusal's fix, the record left -/// as it was. -fn update_fix( - home: &Path, - (url, lab, auth): (&str, &str, Option<&str>), - new: Option<&str>, - sync: Option<&str>, -) -> String { - store_sync(home, url, lab, auth, "off"); - let before = std::fs::read(paths::store_record(home, "pg")).unwrap(); - let request = layerfs_store::postgresql::update::StoreUpdate { - store: StoreName::parse("pg").unwrap(), - auth: new.map(str::to_owned), - synchronous_commit: sync.map(str::to_owned), - }; - let refusal = layerfs_store::postgresql::update::update(home, &request).unwrap_err(); - assert_eq!(refusal.code, "InvalidInput", "{}", refusal.message); - let after = std::fs::read(paths::store_record(home, "pg")).unwrap(); - assert_eq!(before, after, "the record was written"); - refusal.detail.get_text("fix").unwrap().to_owned() -} - -/// S1 of the 57d0aea5ad review and S3 of the e0aa26e149 review: `store -/// update --auth new`'s fix dials only with `new`, never with the login the -/// record names (which may no longer authenticate): a machine's own -/// address that may hold a login is disconnected first (which dials -/// nothing) and connected again last; a Store address that may hold one -/// takes the whole Store, connected again with `--auth new` and its -/// `synchronous_commit` (N1). A `--synchronous-commit` given with the update -/// is carried. Every step is one the call guide accepts. -#[test] -fn an_update_fix_dials_only_with_the_login_it_names() { - let home = tempdir("update-fix"); - login::save(&home, "new", "alice", LOGIN_PASSWORD).unwrap(); - login::save(&home, "old", "bob", LOGIN_PASSWORD).unwrap(); - let (clean, held) = ( - "postgres://db.invalid/app", - "postgres://u:Zq7@Xw9@db.invalid/app", - ); - let machine = "layerfs store disconnect pg --machine lab && layerfs store update pg --auth new && layerfs store connect pg --machine lab"; - let whole = "layerfs store disconnect pg && layerfs store connect pg --auth new --synchronous-commit off && layerfs store connect pg --machine lab"; - for (record, fix) in [ - // the record's login `old` is saved, `gone` is not, or none: the fix - // is the same, as none of them is dialled - ((clean, held, Some("old")), machine), - ((held, clean, Some("old")), whole), - ((held, held, Some("old")), whole), - ((clean, held, Some("new")), machine), - ((held, clean, Some("new")), whole), - ((clean, held, Some("gone")), machine), - ((held, clean, Some("gone")), whole), - ((clean, held, None), machine), - ((held, held, None), whole), - ] { - let got = update_fix(&home, record, Some("new"), None); - assert_eq!(got, fix, "{record:?}"); - assert!(!got.contains("save-auth") && !got.contains("Zq7"), "{got}"); - // no step connects before the one that names `new` - let steps: Vec<&str> = got.split(" && ").collect(); - let named = steps.iter().position(|step| step.contains("--auth new")); - let early = steps[..named.unwrap()] - .iter() - .any(|s| s.contains("store connect")); - assert!(!early, "{got}"); - } - // a `--synchronous-commit` given with the update is carried - assert_eq!( - update_fix(&home, (clean, held, Some("old")), Some("new"), Some("on")), - "layerfs store disconnect pg --machine lab && layerfs store update pg --auth new --synchronous-commit on && layerfs store connect pg --machine lab" - ); - assert_eq!( - update_fix(&home, (held, clean, Some("old")), Some("new"), Some("on")), - "layerfs store disconnect pg && layerfs store connect pg --auth new --synchronous-commit on && layerfs store connect pg --machine lab" - ); - // `--synchronous-commit` alone on such a record is refused too (it - // cleaned the URL before the e0aa26e149 Decision), with the record's - // own fix, `` to fill in - assert_eq!( - update_fix(&home, (held, clean, Some("old")), None, Some("on")), - "layerfs store disconnect pg && layerfs store connect pg --auth --synchronous-commit on && layerfs store connect pg --machine lab" - ); - // the first step of a machine fix dials nothing and leaves the update - // to pass the address check: `store disconnect --machine` is - // `check::save_own` with no connection - let record = store_with(&home, clean, held, Some("old")); - let own = OwnConnection::default(); - let name = StoreName::parse("pg").unwrap(); - check::save_own(&home, &name, "lab", &own, record.binding()).unwrap(); - let request = layerfs_store::postgresql::update::StoreUpdate { - store: name, - auth: Some("new".to_owned()), - synchronous_commit: None, - }; - // its next step dials `new` on the Store's address: `db.invalid` is not - // reached, and the refusal is no longer the URL's - let refusal = layerfs_store::postgresql::update::update(&home, &request).unwrap_err(); - assert!( - !refusal.message.contains("not an address alone"), - "{}", - refusal.message - ); - std::fs::remove_dir_all(home).unwrap(); } /// The rows of the 57d0aea5ad review: S2 (a user part of a host with a @@ -1223,12 +968,8 @@ fn the_57d0aea5ad_review_rows_are_hidden_refused_and_named() { ] { assert_eq!(shown(given), HIDDEN, "{given}"); assert!(target(given).is_err(), "{given}"); - let fix = refuse_login_with_fix("pg", given, None, None).unwrap_err(); - assert_eq!( - fix.detail.get_text("fix"), - Some("layerfs store save-auth --user --password-stdin && layerfs store connect pg --auth "), - "{given}" - ); + let fix = refuse_url("pg", given, true).unwrap_err(); + assert_eq!(fix.detail.get_text("fix"), Some(LOGIN_FIX), "{given}"); } // N1: a raw base64 password in a pre-2.0 user part is hidden whole // (it was cleaned before the e0aa26e149 Decision) @@ -1241,20 +982,16 @@ fn the_57d0aea5ad_review_rows_are_hidden_refused_and_named() { "postgres://h/db&password=Zq7", "postgres://h/db#password=Zq7", ] { - let refusal = refuse_login_with_fix("pg", given, None, None).unwrap_err(); + let refusal = refuse_url("pg", given, true).unwrap_err(); assert!(refusal.message.starts_with(MESSAGES[0]), "{given}"); - assert_eq!( - refusal.detail.get_text("fix"), - Some("layerfs store save-auth --user --password-stdin && layerfs store connect pg --auth "), - "{given}" - ); + assert_eq!(refusal.detail.get_text("fix"), Some(LOGIN_FIX), "{given}"); assert_eq!(shown(given), HIDDEN, "{given}"); assert!(target(given).is_err(), "{given}"); } assert!(refuse_login("postgres://h/db&sslmode=require").is_ok()); // S3: `store connect` refuses it before any dial, and records nothing let home = tempdir("smuggled"); - login::save(&home, "pg", "alice", LOGIN_PASSWORD).unwrap(); + login::save(&home, "pg", LOGIN_PASSWORD).unwrap(); for given in [ "postgres://h/db&password=Zq7", "postgres://h/db#password=Zq7", @@ -1262,7 +999,8 @@ fn the_57d0aea5ad_review_rows_are_hidden_refused_and_named() { let request = layerfs_store::postgresql::connect::StoreConnect { store: StoreName::parse("pg").unwrap(), url: given.to_owned(), - auth: Some("pg".to_owned()), + user: Some("alice".to_owned()), + password: Some(LOGIN_PASSWORD.to_owned()), synchronous_commit: None, }; let refusal = layerfs_store::postgresql::connect::connect(&home, &request).unwrap_err(); @@ -1275,13 +1013,9 @@ fn the_57d0aea5ad_review_rows_are_hidden_refused_and_named() { ); // an older record holding it is hidden and never rewritten let record = store(&home, given); - assert!(record.outdated_fields(), "{given}"); - let kept = record.clone().without_old_fields(); - assert_eq!(kept.text("url"), Some(given), "{given} rewritten"); assert!(!row_texts(&record).iter().any(|text| text.contains("Zq7"))); let dialled = layerfs_store::record::url(&record).unwrap_err(); - let fix = dialled.detail.get_text("fix").unwrap(); - assert!(!fix.contains("Zq7") && fix.contains(" "), "{fix}"); + assert!(!format!("{dialled:?}").contains("Zq7"), "{dialled:?}"); std::fs::remove_file(paths::store_record(&home, "pg")).unwrap(); } std::fs::remove_dir_all(home).unwrap(); @@ -1289,7 +1023,7 @@ fn the_57d0aea5ad_review_rows_are_hidden_refused_and_named() { // `@host` and a TLS setting the client does not read may hold a login // (the client does not read them), so their fix saves one; N4: // `sslrootcert` names where a private CA is trusted - let save = "layerfs store save-auth --user --password-stdin && layerfs store connect pg --auth "; + let save = LOGIN_FIX; for (given, message, fix) in [ ( "postgres://h/db?sslmode=require#f", @@ -1312,7 +1046,7 @@ fn the_57d0aea5ad_review_rows_are_hidden_refused_and_named() { save, ), ] { - let refusal = refuse_login_with_fix("pg", given, None, None).unwrap_err(); + let refusal = refuse_url("pg", given, true).unwrap_err(); assert_eq!(refusal.message, message, "{given}"); assert_eq!(refusal.detail.get_text("fix"), Some(fix), "{given}"); } @@ -1326,7 +1060,7 @@ fn the_57d0aea5ad_review_rows_are_hidden_refused_and_named() { #[test] fn the_e0aa26e149_review_rows_are_hidden_refused_and_kept() { let home = tempdir("e0"); - login::save(&home, "pg", "alice", LOGIN_PASSWORD).unwrap(); + login::save(&home, "pg", LOGIN_PASSWORD).unwrap(); for given in [ "postgres://h:5432/db/password=Zq7@Xw9", "postgres://h:5432/db password=Zq7@Xw9", @@ -1365,17 +1099,8 @@ fn the_e0aa26e149_review_rows_are_hidden_refused_and_kept() { row_texts(&record).iter().all(|text| text == HIDDEN), "{given}" ); - let request = layerfs_store::postgresql::update::StoreUpdate { - store: StoreName::parse("pg").unwrap(), - auth: Some("pg".to_owned()), - synchronous_commit: None, - }; - let refusal = layerfs_store::postgresql::update::update(&home, &request).unwrap_err(); - assert_eq!( - refusal.detail.get_text("fix"), - Some("layerfs store disconnect pg && layerfs store connect pg --auth pg --synchronous-commit local && layerfs store connect pg --machine lab"), - "{given}" - ); + let refusal = connect_again(&home).unwrap_err(); + assert_eq!(refusal.code, "Unavailable", "{given}: {refusal:?}"); let after = std::fs::read(paths::store_record(&home, "pg")).unwrap(); assert_eq!(before, after, "{given}: written"); } diff --git a/core/docs/issues/call-surface-2-0/calls.json b/core/docs/issues/call-surface-2-0/calls.json index 2249b8423b..f887ad9f8f 100644 --- a/core/docs/issues/call-surface-2-0/calls.json +++ b/core/docs/issues/call-surface-2-0/calls.json @@ -5367,7 +5367,7 @@ ], "sometimes": [ "projects", - "connections", + "machines", "state", "op", "blocked_by", @@ -5379,7 +5379,7 @@ "store", "engine", "projects", - "connections", + "machines", "state", "op", "blocked_by", @@ -5446,59 +5446,8 @@ "branch" ] }, - "connections": { - "short": { - "always": [ - "url" - ], - "sometimes": [ - "machine", - "reached" - ] - }, - "long": [ - "machine", - "url", - "own", - "server", - "reached", - "reach" - ] - }, - "server": { - "short": { - "always": [ - "host", - "port", - "database" - ], - "sometimes": [] - }, - "long": [ - "host", - "port", - "database" - ] - }, - "reach": { - "short": { - "always": [ - "at", - "ok" - ], - "sometimes": [ - "latency_ms", - "server_version", - "error" - ] - }, - "long": [ - "at", - "ok", - "latency_ms", - "server_version", - "error" - ] + "machines": { + "scalar": "machine" } }, "example": { @@ -7361,8 +7310,8 @@ "sometimes": [ "state", "machine", - "auth", - "connections", + "user", + "machines", "projects", "projects_count", "backups", @@ -7378,9 +7327,13 @@ "engine", "state", "machine", - "auth", + "url", + "user", + "password_saved", + "password_changed_at", "binding", - "connections", + "reach", + "machines", "projects", "projects_count", "backups", @@ -7398,9 +7351,9 @@ }, "examples": { "short": [ - "{\"items\":[{\"store\":\"shop\",\"engine\":\"sqlite\",\"machine\":\"dev\",\"projects\":[\"api\",\"web\"],\"backups\":[{\"bucket\":\"r2-main\"}]},{\"store\":\"sim-website\",\"engine\":\"sqlite\",\"machine\":\"docker\",\"state\":\"blocked\",\"blocked_by\":{\"machine\":\"docker\",\"reason\":\"stopped\"},\"projects\":[\"website\"]},{\"store\":\"shop-pg\",\"engine\":\"postgresql\",\"auth\":\"pg-app\",\"connections\":[{\"url\":\"postgres://db.internal:5432/shop\",\"reached\":\"ok\"},{\"machine\":\"lab\",\"url\":\"postgres://proxy.lab:6432/shop\",\"reached\":\"failed\"},{\"machine\":\"build\",\"url\":\"postgres://db.internal:5432/shop\"}],\"projects\":[\"abc\"]}]}" + "{\"items\":[{\"store\":\"shop\",\"engine\":\"sqlite\",\"machine\":\"dev\",\"projects\":[\"api\",\"web\"],\"backups\":[{\"bucket\":\"r2-main\"}]},{\"store\":\"sim-website\",\"engine\":\"sqlite\",\"machine\":\"docker\",\"state\":\"blocked\",\"blocked_by\":{\"machine\":\"docker\",\"reason\":\"stopped\"},\"projects\":[\"website\"]},{\"store\":\"shop-pg\",\"engine\":\"postgresql\",\"user\":\"app\",\"machines\":[\"lab\",\"build\"],\"projects\":[\"abc\"]}]}" ], - "long": "{\"items\":[{\"store\":\"shop\",\"engine\":\"sqlite\",\"state\":\"ready\",\"machine\":\"dev\",\"auth\":null,\"binding\":null,\"connections\":null,\"projects\":[\"api\",\"web\"],\"projects_count\":null,\"backups\":[{\"bucket\":\"r2-main\",\"file\":\"shop\",\"sha256\":\"8888888888888888888888888888888888888888888888888888888888888888\",\"heads_sha256\":\"9999999999999999999999999999999999999999999999999999999999999999\",\"last\":{\"call\":\"create\",\"ended_at\":\"2026-11-18T09:15:59Z\",\"size\":213263952},\"attempt\":null}],\"op\":null,\"blocked_by\":null,\"reason\":null,\"fix\":null,\"observed_at\":\"2026-11-18T09:15:59Z\",\"profile\":\"normal\",\"synchronous_commit\":null,\"sqlite_version\":\"3.53.2\",\"created_at\":\"2026-11-17T09:16:59Z\",\"last_transfer\":{\"call\":\"move\",\"from\":\"native\",\"to\":\"dev\",\"ended_at\":\"2026-11-17T09:16:59Z\",\"size\":213263952,\"sha256\":\"8888888888888888888888888888888888888888888888888888888888888888\",\"heads_sha256\":\"9999999999999999999999999999999999999999999999999999999999999999\",\"retired\":true}},{\"store\":\"shop-pg\",\"engine\":\"postgresql\",\"state\":\"ready\",\"machine\":null,\"auth\":\"pg-app\",\"binding\":\"f64587b8a1c2d3e4\",\"connections\":[{\"machine\":null,\"url\":\"postgres://db.internal:5432/shop\",\"own\":false,\"server\":{\"host\":\"db.internal\",\"port\":5432,\"database\":\"shop\"},\"reached\":\"ok\",\"reach\":{\"at\":\"2026-11-18T09:15:59Z\",\"ok\":true,\"latency_ms\":2,\"server_version\":\"17.6\",\"error\":null}},{\"machine\":\"lab\",\"url\":\"postgres://proxy.lab:6432/shop\",\"own\":true,\"server\":{\"host\":\"proxy.lab\",\"port\":6432,\"database\":\"shop\"},\"reached\":\"failed\",\"reach\":{\"at\":\"2026-11-18T09:14:02Z\",\"ok\":false,\"latency_ms\":null,\"server_version\":null,\"error\":\"machine lab cannot reach PostgreSQL Store shop-pg's server at proxy.lab: connection refused\"}},{\"machine\":\"build\",\"url\":\"postgres://db.internal:5432/shop\",\"own\":false,\"server\":{\"host\":\"db.internal\",\"port\":5432,\"database\":\"shop\"},\"reached\":null,\"reach\":null}],\"projects\":[\"api\",\"web\"],\"projects_count\":null,\"backups\":[],\"op\":null,\"blocked_by\":null,\"reason\":null,\"fix\":null,\"observed_at\":\"2026-11-18T09:15:59Z\",\"profile\":null,\"synchronous_commit\":\"local\",\"sqlite_version\":null,\"created_at\":\"2026-11-17T09:16:59Z\",\"last_transfer\":null}]}" + "long": "{\"items\":[{\"store\":\"shop\",\"engine\":\"sqlite\",\"state\":\"ready\",\"machine\":\"dev\",\"url\":null,\"user\":null,\"password_saved\":null,\"password_changed_at\":null,\"binding\":null,\"reach\":null,\"machines\":null,\"projects\":[\"api\",\"web\"],\"projects_count\":null,\"backups\":[{\"bucket\":\"r2-main\",\"file\":\"shop\",\"sha256\":\"8888888888888888888888888888888888888888888888888888888888888888\",\"heads_sha256\":\"9999999999999999999999999999999999999999999999999999999999999999\",\"last\":{\"call\":\"create\",\"ended_at\":\"2026-11-18T09:15:59Z\",\"size\":213263952},\"attempt\":null}],\"op\":null,\"blocked_by\":null,\"reason\":null,\"fix\":null,\"observed_at\":\"2026-11-18T09:15:59Z\",\"profile\":\"normal\",\"synchronous_commit\":null,\"sqlite_version\":\"3.53.2\",\"created_at\":\"2026-11-17T09:16:59Z\",\"last_transfer\":{\"call\":\"move\",\"from\":\"native\",\"to\":\"dev\",\"ended_at\":\"2026-11-17T09:16:59Z\",\"size\":213263952,\"sha256\":\"8888888888888888888888888888888888888888888888888888888888888888\",\"heads_sha256\":\"9999999999999999999999999999999999999999999999999999999999999999\",\"retired\":true}},{\"store\":\"shop-pg\",\"engine\":\"postgresql\",\"state\":\"ready\",\"machine\":null,\"url\":\"postgres://db.internal:5432/shop\",\"user\":\"app\",\"password_saved\":true,\"password_changed_at\":\"2026-11-17T09:16:59Z\",\"binding\":\"f64587b8a1c2d3e4\",\"reach\":{\"at\":\"2026-11-18T09:15:59Z\",\"ok\":true,\"latency_ms\":2,\"server_version\":\"17.6\",\"error\":null},\"machines\":[\"lab\",\"build\"],\"projects\":[\"api\",\"web\"],\"projects_count\":null,\"backups\":[],\"op\":null,\"blocked_by\":null,\"reason\":null,\"fix\":null,\"observed_at\":\"2026-11-18T09:15:59Z\",\"profile\":null,\"synchronous_commit\":\"local\",\"sqlite_version\":null,\"created_at\":\"2026-11-17T09:16:59Z\",\"last_transfer\":null}]}" }, "dropped": [], "new_work": "A records-only state is new: today each item's state comes from the leases and a `stat` on the Store's machine, and is idle, in_use, busy, down or unresolved. `--machine` is a new filter. `blocked` with `blocked_by` replaces `down`.", @@ -7477,8 +7430,9 @@ ], "sometimes": [ "machine", - "auth", - "connections", + "url", + "user", + "machines", "projects", "projects_count", "backups", @@ -7493,9 +7447,13 @@ "engine", "state", "machine", - "auth", + "url", + "user", + "password_saved", + "password_changed_at", "binding", - "connections", + "reach", + "machines", "projects", "projects_count", "backups", @@ -7518,9 +7476,9 @@ "its machine is stopped: {\"engine\":\"sqlite\",\"state\":\"blocked\",\"machine\":\"docker\",\"projects\":[\"website\"],\"blocked_by\":{\"machine\":\"docker\",\"reason\":\"stopped\"}}", "moving: {\"engine\":\"sqlite\",\"state\":\"busy\",\"machine\":\"native\",\"projects\":[\"api\",\"web\"],\"op\":{\"name\":\"move\",\"phase\":\"send\",\"started_at\":\"2026-11-18T09:16:59Z\"}}", "lost reply on a move: {\"engine\":\"sqlite\",\"state\":\"broken\",\"machine\":\"native\",\"projects\":[\"api\",\"web\"],\"reason\":\"unresolved\",\"fix\":\"layerfs store move shop dev\"}", - "PostgreSQL: {\"engine\":\"postgresql\",\"state\":\"ready\",\"auth\":\"pg-app\",\"connections\":[{\"url\":\"postgres://db.internal:5432/shop\",\"reached\":\"ok\"},{\"machine\":\"lab\",\"url\":\"postgres://proxy.lab:6432/shop\",\"reached\":\"failed\"},{\"machine\":\"build\",\"url\":\"postgres://db.internal:5432/shop\"}],\"projects\":[\"api\",\"web\"]}" + "PostgreSQL: {\"engine\":\"postgresql\",\"state\":\"ready\",\"url\":\"postgres://db.internal:5432/shop\",\"user\":\"app\",\"machines\":[{\"machine\":\"lab\",\"reached\":\"failed\"},{\"machine\":\"build\"}],\"projects\":[\"api\",\"web\"]}" ], - "long": "{\"engine\":\"sqlite\",\"state\":\"ready\",\"machine\":\"dev\",\"auth\":null,\"binding\":null,\"connections\":null,\"projects\":[\"api\",\"web\"],\"projects_count\":null,\"backups\":[{\"bucket\":\"r2-main\",\"file\":\"shop\",\"sha256\":\"8888888888888888888888888888888888888888888888888888888888888888\",\"heads_sha256\":\"9999999999999999999999999999999999999999999999999999999999999999\",\"last\":{\"call\":\"create\",\"ended_at\":\"2026-11-18T09:15:59Z\",\"size\":213263952},\"attempt\":null}],\"op\":null,\"blocked_by\":null,\"reason\":null,\"fix\":null,\"observed_at\":\"2026-11-18T09:15:59Z\",\"store\":\"shop\",\"profile\":\"normal\",\"synchronous_commit\":null,\"sqlite_version\":\"3.53.2\",\"created_at\":\"2026-11-17T09:16:59Z\",\"last_transfer\":{\"call\":\"move\",\"from\":\"native\",\"to\":\"dev\",\"ended_at\":\"2026-11-17T09:16:59Z\",\"size\":213263952,\"sha256\":\"8888888888888888888888888888888888888888888888888888888888888888\",\"heads_sha256\":\"9999999999999999999999999999999999999999999999999999999999999999\",\"retired\":true}}" + "long": "{\"engine\":\"sqlite\",\"state\":\"ready\",\"machine\":\"dev\",\"url\":null,\"user\":null,\"password_saved\":null,\"password_changed_at\":null,\"binding\":null,\"reach\":null,\"machines\":null,\"projects\":[\"api\",\"web\"],\"projects_count\":null,\"backups\":[{\"bucket\":\"r2-main\",\"file\":\"shop\",\"sha256\":\"8888888888888888888888888888888888888888888888888888888888888888\",\"heads_sha256\":\"9999999999999999999999999999999999999999999999999999999999999999\",\"last\":{\"call\":\"create\",\"ended_at\":\"2026-11-18T09:15:59Z\",\"size\":213263952},\"attempt\":null}],\"op\":null,\"blocked_by\":null,\"reason\":null,\"fix\":null,\"observed_at\":\"2026-11-18T09:15:59Z\",\"store\":\"shop\",\"profile\":\"normal\",\"synchronous_commit\":null,\"sqlite_version\":\"3.53.2\",\"created_at\":\"2026-11-17T09:16:59Z\",\"last_transfer\":{\"call\":\"move\",\"from\":\"native\",\"to\":\"dev\",\"ended_at\":\"2026-11-17T09:16:59Z\",\"size\":213263952,\"sha256\":\"8888888888888888888888888888888888888888888888888888888888888888\",\"heads_sha256\":\"9999999999999999999999999999999999999999999999999999999999999999\",\"retired\":true}}" }, "dropped": [ { @@ -7611,8 +7569,8 @@ "today": [ "store.connect" ], - "help": "connect a PostgreSQL database as a Store, or set an address of a connected one", - "cli": "layerfs store connect [--auth A] [--machine M] [--synchronous-commit local]", + "help": "connect a PostgreSQL database as a Store, or change a connected one's address, login or setting", + "cli": "layerfs store connect [--user U] [--password-stdin] [--synchronous-commit local]", "positionals": [ { "name": "store", @@ -7626,23 +7584,25 @@ ], "options": [ { - "name": "auth", - "kind": "Name", - "help": "the saved login; required on a Store's first connect, refused afterwards" + "name": "user", + "kind": "Text", + "help": "the PostgreSQL role; needed on a Store's first connect, else the saved one is kept" }, { - "name": "machine", - "kind": "Name", - "help": "on a connected Store: the address is this machine's own" + "name": "password", + "kind": "Content", + "help": "its password; needed on a Store's first connect, else the saved one is kept; the shell reads it from stdin with --password-stdin", + "redact": true, + "shell": "--password-stdin" }, { "name": "synchronous_commit", "kind": "Text", - "help": "off, local, remote_write, on or remote_apply; first connect only", + "help": "off, local, remote_write, on or remote_apply; a new Store takes local", "default": "local" } ], - "stdin": null, + "stdin": "secret", "with": {}, "paging": null, "progress": false, @@ -7663,17 +7623,18 @@ "outcome", "store", "engine", - "auth", - "connections", - "synchronous_commit" + "url", + "user", + "synchronous_commit", + "machines" ], "item": null, "examples": { "short": [ "first connect: {\"projects\":[\"api\",\"web\"]}", - "an empty database, or an address set: {\"ok\":true}" + "an empty database, or a connected Store changed: {\"ok\":true}" ], - "long": "{\"ok\":true,\"projects\":[\"api\",\"web\"],\"projects_count\":null,\"outcome\":\"connected\",\"store\":\"shop-pg\",\"engine\":\"postgresql\",\"auth\":\"pg-app\",\"connections\":[{\"machine\":null,\"url\":\"postgres://db.internal:5432/shop\",\"own\":false,\"server\":{\"host\":\"db.internal\",\"port\":5432,\"database\":\"shop\"},\"reached\":null,\"reach\":null}],\"synchronous_commit\":\"local\"}" + "long": "{\"ok\":true,\"projects\":[\"api\",\"web\"],\"projects_count\":null,\"outcome\":\"connected\",\"store\":\"shop-pg\",\"engine\":\"postgresql\",\"url\":\"postgres://db.internal:5432/shop\",\"user\":\"app\",\"synchronous_commit\":\"local\",\"machines\":[]}" }, "dropped": [ { @@ -7682,12 +7643,17 @@ "why": "an existing thing is named by its own word, never `name`" }, { - "today": "--password", - "now": "--auth", - "why": "a login is saved once in the home and named by any number of Stores" + "today": "--auth", + "now": "--user, --password-stdin", + "why": "this computer is the one place a Store's URL and login are saved; machines attach and inherit both (owner, 2026-11-24)" + }, + { + "today": "--machine", + "now": "store attach", + "why": "no machine has an address of its own" } ], - "new_work": "Saved logins and a URL with no user are new: today the record holds the URL with its user and a password reference (env:NAME or file:/path) per Store. A machine's own address through connect replaces store.update --machine --url, and no longer takes a password; the proof from that machine exists. Replacing the address every machine uses is store.update --url today. The id-only uniqueness check is a change: today a second Store is also refused when its URL names the same host, port and database. `outcome` is connected for a new Store and updated for an address." + "new_work": "Owner, 2026-11-24: the login is given to connect itself, checked from this process before anything is saved; the user is kept in the record and the password in the home's secret folder (kind `login`, by Store). A connect of a connected Store changes its address, user, password or synchronous_commit, keeping what it is not given, and must reach the same Store (binding) first. `outcome` is connected for a new Store and updated otherwise. Saved logins by name, --auth and --machine are gone." }, { "call": "store.disconnect", @@ -7695,21 +7661,15 @@ "today": [ "store.disconnect" ], - "help": "forget a PostgreSQL Store, or one machine's own address and reach; its data stays", - "cli": "layerfs store disconnect [--machine M]", + "help": "forget a PostgreSQL Store, its saved login and its attachments; its data stays", + "cli": "layerfs store disconnect ", "positionals": [ { "name": "store", "kind": "Name" } ], - "options": [ - { - "name": "machine", - "kind": "Name", - "help": "remove only this machine's own address" - } - ], + "options": [], "stdin": null, "with": {}, "paging": null, @@ -7725,15 +7685,14 @@ "long": [ "ok", "outcome", - "store", - "machine" + "store" ], "item": null, "examples": { "short": [ "{\"ok\":true}" ], - "long": "{\"ok\":true,\"outcome\":\"disconnected\",\"store\":\"shop-pg\",\"machine\":null}" + "long": "{\"ok\":true,\"outcome\":\"disconnected\",\"store\":\"shop-pg\"}" }, "dropped": [ { @@ -7742,74 +7701,28 @@ "why": "an existing thing is named by its own word, never `name`" } ], - "new_work": "`--machine` moves here from store.update --machine --clear; the capability exists." + "new_work": "Owner, 2026-11-24: --machine is gone (no machine has an address of its own); the Store's saved password and attachments go with it." }, { - "call": "store.save_auth", + "call": "store.attach", "badge": "new", "today": [], - "help": "save a PostgreSQL login in the home; saving again rotates it", - "cli": "layerfs store save-auth --user U --password-stdin", + "help": "let a machine run Sandboxes of a PostgreSQL Store, checked from that machine first", + "cli": "layerfs store attach --machine M", "positionals": [ { - "name": "auth", + "name": "store", "kind": "Name" } ], "options": [ { - "name": "user", - "kind": "Text", - "help": "the PostgreSQL role; required", + "name": "machine", + "kind": "Name", + "help": "the machine; required", "required": true - }, - { - "name": "password", - "kind": "Content", - "help": "the password; required; the shell reads it from stdin with --password-stdin", - "required": true, - "redact": true, - "shell": "--password-stdin" } ], - "stdin": "secret", - "with": {}, - "paging": null, - "progress": false, - "quiet": false, - "profile": "full", - "short": { - "always": [ - "ok" - ], - "sometimes": [] - }, - "long": [ - "ok", - "outcome", - "auth", - "user", - "stores", - "stores_count" - ], - "item": null, - "examples": { - "short": [ - "{\"ok\":true}" - ], - "long": "{\"ok\":true,\"outcome\":\"saved\",\"auth\":\"pg-app\",\"user\":\"app\",\"stores\":[],\"stores_count\":null}" - }, - "dropped": [], - "new_work": "All of it: saved logins, the home's secret folder and reading a secret from stdin do not exist. Today each Store records its own password reference (env:NAME or file:/path), resolved by the caller on each call." - }, - { - "call": "store.auths", - "badge": "new", - "today": [], - "help": "the saved PostgreSQL logins and the Stores that use each", - "cli": "layerfs store auths", - "positionals": [], - "options": [], "stdin": null, "with": {}, "paging": null, @@ -7818,102 +7731,38 @@ "profile": "full", "short": { "always": [ - "items" + "ok", + "outcome" ], - "sometimes": [] - }, - "long": [ - "items" - ], - "item": { - "short": { - "always": [ - "auth", - "user" - ], - "sometimes": [ - "state", - "reason", - "fix", - "stores", - "stores_count" - ] - }, - "long": [ - "auth", - "user", - "state", - "reason", - "fix", - "stores", - "stores_count", - "created_at", - "updated_at" + "sometimes": [ + "latency_ms" ] }, - "examples": { - "short": [ - "{\"items\":[{\"auth\":\"pg-app\",\"user\":\"app\",\"stores\":[\"shop-pg\",\"analytics\"]},{\"auth\":\"pg-ro\",\"user\":\"reader\"}]}" - ], - "long": "{\"items\":[{\"auth\":\"pg-app\",\"user\":\"app\",\"state\":\"ready\",\"reason\":null,\"fix\":null,\"stores\":[\"shop-pg\",\"analytics\"],\"stores_count\":null,\"created_at\":\"2026-11-17T09:16:59Z\",\"updated_at\":\"2026-11-18T09:16:59Z\"},{\"auth\":\"pg-old\",\"user\":null,\"state\":\"broken\",\"reason\":\"failed\",\"fix\":\"layerfs store save-auth pg-old --user --password-stdin\",\"stores\":[],\"stores_count\":null,\"created_at\":null,\"updated_at\":null}]}" - }, - "dropped": [], - "new_work": "All of it (see store.save_auth).", - "states": { - "reasons": [ - "failed" - ], - "ops": [] - } - }, - { - "call": "store.remove_auth", - "badge": "new", - "today": [], - "help": "remove a saved PostgreSQL login no Store uses", - "cli": "layerfs store remove-auth ", - "positionals": [ - { - "name": "auth", - "kind": "Name" - } - ], - "options": [], - "stdin": null, - "with": {}, - "paging": null, - "progress": false, - "quiet": false, - "profile": "full", - "short": { - "always": [ - "ok" - ], - "sometimes": [] - }, "long": [ "ok", "outcome", - "auth" + "store", + "machine", + "latency_ms", + "server_version" ], "item": null, "examples": { "short": [ - "{\"ok\":true}" + "{\"ok\":true,\"outcome\":\"attached\",\"latency_ms\":3}", + "an attached machine checked again: {\"ok\":true,\"outcome\":\"checked\",\"latency_ms\":2}" ], - "long": "{\"ok\":true,\"outcome\":\"removed\",\"auth\":\"pg-ro\"}" + "long": "{\"ok\":true,\"outcome\":\"attached\",\"store\":\"shop-pg\",\"machine\":\"lab\",\"latency_ms\":3,\"server_version\":\"17.6\"}" }, "dropped": [], - "new_work": "All of it (see store.save_auth)." + "new_work": "New (owner, 2026-11-24): the Store is checked from the machine with the URL and login this computer saved, as its Sandboxes dial them; the machine is then recorded in the Store's `attached` and its reach observed. sandbox.create on a machine not attached is refused with this call as its fix." }, { - "call": "store.update", - "badge": "reshaped", - "today": [ - "store.update" - ], - "help": "change a PostgreSQL Store's saved login or its synchronous_commit", - "cli": "layerfs store update [--auth A] [--synchronous-commit S]", + "call": "store.detach", + "badge": "new", + "today": [], + "help": "stop a machine running Sandboxes of a PostgreSQL Store; refused while one runs there", + "cli": "layerfs store detach --machine M", "positionals": [ { "name": "store", @@ -7922,14 +7771,10 @@ ], "options": [ { - "name": "auth", + "name": "machine", "kind": "Name", - "help": "another saved login" - }, - { - "name": "synchronous_commit", - "kind": "Text", - "help": "off, local, remote_write, on or remote_apply" + "help": "the machine; required", + "required": true } ], "stdin": null, @@ -7948,44 +7793,17 @@ "ok", "outcome", "store", - "auth", - "synchronous_commit" + "machine" ], "item": null, "examples": { "short": [ "{\"ok\":true}" ], - "long": "{\"ok\":true,\"outcome\":\"updated\",\"store\":\"shop-pg\",\"auth\":\"pg-app-2\",\"synchronous_commit\":\"local\"}" + "long": "{\"ok\":true,\"outcome\":\"detached\",\"store\":\"shop-pg\",\"machine\":\"lab\"}" }, - "dropped": [ - { - "today": "", - "now": "", - "why": "an existing thing is named by its own word, never `name`" - }, - { - "today": "--url", - "now": "store connect ", - "why": "an address change is a connect, checked like one" - }, - { - "today": "--machine", - "now": "store connect --machine M", - "why": "a machine's own address is a connect; the login is the Store's" - }, - { - "today": "--password", - "now": "--auth, or store save-auth to rotate", - "why": "the login is saved once and named" - }, - { - "today": "--clear", - "now": "store disconnect --machine M", - "why": "removing an address is a disconnect" - } - ], - "new_work": "`--auth` is new (see store.save_auth). `--synchronous-commit` exists today." + "dropped": [], + "new_work": "New (owner, 2026-11-24): refused InUse while a Sandbox of the Store's projects is on the machine, NotFound when it is not attached; its reach is forgotten." }, { "call": "store.move", @@ -8240,7 +8058,7 @@ { "name": "machine", "kind": "Name", - "help": "also probe a PostgreSQL Store's connection from this machine" + "help": "check a PostgreSQL Store from this computer and this attached machine only" } ], "stdin": null, @@ -8316,7 +8134,7 @@ }, { "check": "store.connection", - "what": "it is reached where it lives: a sqlite Store through its machine; a PostgreSQL Store from this computer, and once more from each machine that has a Sandbox of it, with `from` naming that machine", + "what": "it is reached where it lives: a sqlite Store through its machine; a PostgreSQL Store from this computer, then (when this computer is let in) once more from each machine attached to it, with `from` naming that machine", "full_only": false }, { diff --git a/core/docs/issues/call-surface-2-0/families/home.json b/core/docs/issues/call-surface-2-0/families/home.json index 2de3771ce2..152d344e56 100644 --- a/core/docs/issues/call-surface-2-0/families/home.json +++ b/core/docs/issues/call-surface-2-0/families/home.json @@ -198,7 +198,7 @@ ], "sometimes": [ "projects", - "connections", + "machines", "state", "op", "blocked_by", @@ -210,7 +210,7 @@ "store", "engine", "projects", - "connections", + "machines", "state", "op", "blocked_by", @@ -277,59 +277,8 @@ "branch" ] }, - "connections": { - "short": { - "always": [ - "url" - ], - "sometimes": [ - "machine", - "reached" - ] - }, - "long": [ - "machine", - "url", - "own", - "server", - "reached", - "reach" - ] - }, - "server": { - "short": { - "always": [ - "host", - "port", - "database" - ], - "sometimes": [] - }, - "long": [ - "host", - "port", - "database" - ] - }, - "reach": { - "short": { - "always": [ - "at", - "ok" - ], - "sometimes": [ - "latency_ms", - "server_version", - "error" - ] - }, - "long": [ - "at", - "ok", - "latency_ms", - "server_version", - "error" - ] + "machines": { + "scalar": "machine" } }, "example": { diff --git a/core/docs/issues/call-surface-2-0/families/store.json b/core/docs/issues/call-surface-2-0/families/store.json index 53035ceec4..76bb520c31 100644 --- a/core/docs/issues/call-surface-2-0/families/store.json +++ b/core/docs/issues/call-surface-2-0/families/store.json @@ -2,7 +2,7 @@ "family": "store", "who": null, "old_count": 12, - "blurb": "A sqlite Store is created and removed; a PostgreSQL database is connected and disconnected, with a saved login. Default reads use the home's records.", + "blurb": "A sqlite Store is created and removed; a PostgreSQL database is connected and disconnected with its URL and login, saved on this computer only, and machines attach to it to run its Sandboxes. Default reads use the home's records.", "reasons": [ "Why engine: type means file, dir or symlink everywhere else.", "Why rows list projects: a project count needs a name for the number; the short list of names answers both.", @@ -63,8 +63,8 @@ "sometimes": [ "state", "machine", - "auth", - "connections", + "user", + "machines", "projects", "projects_count", "backups", @@ -80,9 +80,13 @@ "engine", "state", "machine", - "auth", + "url", + "user", + "password_saved", + "password_changed_at", "binding", - "connections", + "reach", + "machines", "projects", "projects_count", "backups", @@ -100,9 +104,9 @@ }, "examples": { "short": [ - "{\"items\":[{\"store\":\"shop\",\"engine\":\"sqlite\",\"machine\":\"dev\",\"projects\":[\"api\",\"web\"],\"backups\":[{\"bucket\":\"r2-main\"}]},{\"store\":\"sim-website\",\"engine\":\"sqlite\",\"machine\":\"docker\",\"state\":\"blocked\",\"blocked_by\":{\"machine\":\"docker\",\"reason\":\"stopped\"},\"projects\":[\"website\"]},{\"store\":\"shop-pg\",\"engine\":\"postgresql\",\"auth\":\"pg-app\",\"connections\":[{\"url\":\"postgres://db.internal:5432/shop\",\"reached\":\"ok\"},{\"machine\":\"lab\",\"url\":\"postgres://proxy.lab:6432/shop\",\"reached\":\"failed\"},{\"machine\":\"build\",\"url\":\"postgres://db.internal:5432/shop\"}],\"projects\":[\"abc\"]}]}" + "{\"items\":[{\"store\":\"shop\",\"engine\":\"sqlite\",\"machine\":\"dev\",\"projects\":[\"api\",\"web\"],\"backups\":[{\"bucket\":\"r2-main\"}]},{\"store\":\"sim-website\",\"engine\":\"sqlite\",\"machine\":\"docker\",\"state\":\"blocked\",\"blocked_by\":{\"machine\":\"docker\",\"reason\":\"stopped\"},\"projects\":[\"website\"]},{\"store\":\"shop-pg\",\"engine\":\"postgresql\",\"user\":\"app\",\"machines\":[\"lab\",\"build\"],\"projects\":[\"abc\"]}]}" ], - "long": "{\"items\":[{\"store\":\"shop\",\"engine\":\"sqlite\",\"state\":\"ready\",\"machine\":\"dev\",\"auth\":null,\"binding\":null,\"connections\":null,\"projects\":[\"api\",\"web\"],\"projects_count\":null,\"backups\":[{\"bucket\":\"r2-main\",\"file\":\"shop\",\"sha256\":\"8888888888888888888888888888888888888888888888888888888888888888\",\"heads_sha256\":\"9999999999999999999999999999999999999999999999999999999999999999\",\"last\":{\"call\":\"create\",\"ended_at\":\"2026-11-18T09:15:59Z\",\"size\":213263952},\"attempt\":null}],\"op\":null,\"blocked_by\":null,\"reason\":null,\"fix\":null,\"observed_at\":\"2026-11-18T09:15:59Z\",\"profile\":\"normal\",\"synchronous_commit\":null,\"sqlite_version\":\"3.53.2\",\"created_at\":\"2026-11-17T09:16:59Z\",\"last_transfer\":{\"call\":\"move\",\"from\":\"native\",\"to\":\"dev\",\"ended_at\":\"2026-11-17T09:16:59Z\",\"size\":213263952,\"sha256\":\"8888888888888888888888888888888888888888888888888888888888888888\",\"heads_sha256\":\"9999999999999999999999999999999999999999999999999999999999999999\",\"retired\":true}},{\"store\":\"shop-pg\",\"engine\":\"postgresql\",\"state\":\"ready\",\"machine\":null,\"auth\":\"pg-app\",\"binding\":\"f64587b8a1c2d3e4\",\"connections\":[{\"machine\":null,\"url\":\"postgres://db.internal:5432/shop\",\"own\":false,\"server\":{\"host\":\"db.internal\",\"port\":5432,\"database\":\"shop\"},\"reached\":\"ok\",\"reach\":{\"at\":\"2026-11-18T09:15:59Z\",\"ok\":true,\"latency_ms\":2,\"server_version\":\"17.6\",\"error\":null}},{\"machine\":\"lab\",\"url\":\"postgres://proxy.lab:6432/shop\",\"own\":true,\"server\":{\"host\":\"proxy.lab\",\"port\":6432,\"database\":\"shop\"},\"reached\":\"failed\",\"reach\":{\"at\":\"2026-11-18T09:14:02Z\",\"ok\":false,\"latency_ms\":null,\"server_version\":null,\"error\":\"machine lab cannot reach PostgreSQL Store shop-pg's server at proxy.lab: connection refused\"}},{\"machine\":\"build\",\"url\":\"postgres://db.internal:5432/shop\",\"own\":false,\"server\":{\"host\":\"db.internal\",\"port\":5432,\"database\":\"shop\"},\"reached\":null,\"reach\":null}],\"projects\":[\"api\",\"web\"],\"projects_count\":null,\"backups\":[],\"op\":null,\"blocked_by\":null,\"reason\":null,\"fix\":null,\"observed_at\":\"2026-11-18T09:15:59Z\",\"profile\":null,\"synchronous_commit\":\"local\",\"sqlite_version\":null,\"created_at\":\"2026-11-17T09:16:59Z\",\"last_transfer\":null}]}" + "long": "{\"items\":[{\"store\":\"shop\",\"engine\":\"sqlite\",\"state\":\"ready\",\"machine\":\"dev\",\"url\":null,\"user\":null,\"password_saved\":null,\"password_changed_at\":null,\"binding\":null,\"reach\":null,\"machines\":null,\"projects\":[\"api\",\"web\"],\"projects_count\":null,\"backups\":[{\"bucket\":\"r2-main\",\"file\":\"shop\",\"sha256\":\"8888888888888888888888888888888888888888888888888888888888888888\",\"heads_sha256\":\"9999999999999999999999999999999999999999999999999999999999999999\",\"last\":{\"call\":\"create\",\"ended_at\":\"2026-11-18T09:15:59Z\",\"size\":213263952},\"attempt\":null}],\"op\":null,\"blocked_by\":null,\"reason\":null,\"fix\":null,\"observed_at\":\"2026-11-18T09:15:59Z\",\"profile\":\"normal\",\"synchronous_commit\":null,\"sqlite_version\":\"3.53.2\",\"created_at\":\"2026-11-17T09:16:59Z\",\"last_transfer\":{\"call\":\"move\",\"from\":\"native\",\"to\":\"dev\",\"ended_at\":\"2026-11-17T09:16:59Z\",\"size\":213263952,\"sha256\":\"8888888888888888888888888888888888888888888888888888888888888888\",\"heads_sha256\":\"9999999999999999999999999999999999999999999999999999999999999999\",\"retired\":true}},{\"store\":\"shop-pg\",\"engine\":\"postgresql\",\"state\":\"ready\",\"machine\":null,\"url\":\"postgres://db.internal:5432/shop\",\"user\":\"app\",\"password_saved\":true,\"password_changed_at\":\"2026-11-17T09:16:59Z\",\"binding\":\"f64587b8a1c2d3e4\",\"reach\":{\"at\":\"2026-11-18T09:15:59Z\",\"ok\":true,\"latency_ms\":2,\"server_version\":\"17.6\",\"error\":null},\"machines\":[\"lab\",\"build\"],\"projects\":[\"api\",\"web\"],\"projects_count\":null,\"backups\":[],\"op\":null,\"blocked_by\":null,\"reason\":null,\"fix\":null,\"observed_at\":\"2026-11-18T09:15:59Z\",\"profile\":null,\"synchronous_commit\":\"local\",\"sqlite_version\":null,\"created_at\":\"2026-11-17T09:16:59Z\",\"last_transfer\":null}]}" }, "dropped": [], "new_work": "A records-only state is new: today each item's state comes from the leases and a `stat` on the Store's machine, and is idle, in_use, busy, down or unresolved. `--machine` is a new filter. `blocked` with `blocked_by` replaces `down`.", @@ -180,8 +184,9 @@ ], "sometimes": [ "machine", - "auth", - "connections", + "url", + "user", + "machines", "projects", "projects_count", "backups", @@ -196,9 +201,13 @@ "engine", "state", "machine", - "auth", + "url", + "user", + "password_saved", + "password_changed_at", "binding", - "connections", + "reach", + "machines", "projects", "projects_count", "backups", @@ -221,9 +230,9 @@ "its machine is stopped: {\"engine\":\"sqlite\",\"state\":\"blocked\",\"machine\":\"docker\",\"projects\":[\"website\"],\"blocked_by\":{\"machine\":\"docker\",\"reason\":\"stopped\"}}", "moving: {\"engine\":\"sqlite\",\"state\":\"busy\",\"machine\":\"native\",\"projects\":[\"api\",\"web\"],\"op\":{\"name\":\"move\",\"phase\":\"send\",\"started_at\":\"2026-11-18T09:16:59Z\"}}", "lost reply on a move: {\"engine\":\"sqlite\",\"state\":\"broken\",\"machine\":\"native\",\"projects\":[\"api\",\"web\"],\"reason\":\"unresolved\",\"fix\":\"layerfs store move shop dev\"}", - "PostgreSQL: {\"engine\":\"postgresql\",\"state\":\"ready\",\"auth\":\"pg-app\",\"connections\":[{\"url\":\"postgres://db.internal:5432/shop\",\"reached\":\"ok\"},{\"machine\":\"lab\",\"url\":\"postgres://proxy.lab:6432/shop\",\"reached\":\"failed\"},{\"machine\":\"build\",\"url\":\"postgres://db.internal:5432/shop\"}],\"projects\":[\"api\",\"web\"]}" + "PostgreSQL: {\"engine\":\"postgresql\",\"state\":\"ready\",\"url\":\"postgres://db.internal:5432/shop\",\"user\":\"app\",\"machines\":[{\"machine\":\"lab\",\"reached\":\"failed\"},{\"machine\":\"build\"}],\"projects\":[\"api\",\"web\"]}" ], - "long": "{\"engine\":\"sqlite\",\"state\":\"ready\",\"machine\":\"dev\",\"auth\":null,\"binding\":null,\"connections\":null,\"projects\":[\"api\",\"web\"],\"projects_count\":null,\"backups\":[{\"bucket\":\"r2-main\",\"file\":\"shop\",\"sha256\":\"8888888888888888888888888888888888888888888888888888888888888888\",\"heads_sha256\":\"9999999999999999999999999999999999999999999999999999999999999999\",\"last\":{\"call\":\"create\",\"ended_at\":\"2026-11-18T09:15:59Z\",\"size\":213263952},\"attempt\":null}],\"op\":null,\"blocked_by\":null,\"reason\":null,\"fix\":null,\"observed_at\":\"2026-11-18T09:15:59Z\",\"store\":\"shop\",\"profile\":\"normal\",\"synchronous_commit\":null,\"sqlite_version\":\"3.53.2\",\"created_at\":\"2026-11-17T09:16:59Z\",\"last_transfer\":{\"call\":\"move\",\"from\":\"native\",\"to\":\"dev\",\"ended_at\":\"2026-11-17T09:16:59Z\",\"size\":213263952,\"sha256\":\"8888888888888888888888888888888888888888888888888888888888888888\",\"heads_sha256\":\"9999999999999999999999999999999999999999999999999999999999999999\",\"retired\":true}}" + "long": "{\"engine\":\"sqlite\",\"state\":\"ready\",\"machine\":\"dev\",\"url\":null,\"user\":null,\"password_saved\":null,\"password_changed_at\":null,\"binding\":null,\"reach\":null,\"machines\":null,\"projects\":[\"api\",\"web\"],\"projects_count\":null,\"backups\":[{\"bucket\":\"r2-main\",\"file\":\"shop\",\"sha256\":\"8888888888888888888888888888888888888888888888888888888888888888\",\"heads_sha256\":\"9999999999999999999999999999999999999999999999999999999999999999\",\"last\":{\"call\":\"create\",\"ended_at\":\"2026-11-18T09:15:59Z\",\"size\":213263952},\"attempt\":null}],\"op\":null,\"blocked_by\":null,\"reason\":null,\"fix\":null,\"observed_at\":\"2026-11-18T09:15:59Z\",\"store\":\"shop\",\"profile\":\"normal\",\"synchronous_commit\":null,\"sqlite_version\":\"3.53.2\",\"created_at\":\"2026-11-17T09:16:59Z\",\"last_transfer\":{\"call\":\"move\",\"from\":\"native\",\"to\":\"dev\",\"ended_at\":\"2026-11-17T09:16:59Z\",\"size\":213263952,\"sha256\":\"8888888888888888888888888888888888888888888888888888888888888888\",\"heads_sha256\":\"9999999999999999999999999999999999999999999999999999999999999999\",\"retired\":true}}" }, "dropped": [ { @@ -316,8 +325,8 @@ "today": [ "store.connect" ], - "help": "connect a PostgreSQL database as a Store, or set an address of a connected one", - "cli": "layerfs store connect [--auth A] [--machine M] [--synchronous-commit local]", + "help": "connect a PostgreSQL database as a Store, or change a connected one's address, login or setting", + "cli": "layerfs store connect [--user U] [--password-stdin] [--synchronous-commit local]", "positionals": [ { "name": "store", @@ -331,23 +340,25 @@ ], "options": [ { - "name": "auth", - "kind": "Name", - "help": "the saved login; required on a Store's first connect, refused afterwards" + "name": "user", + "kind": "Text", + "help": "the PostgreSQL role; needed on a Store's first connect, else the saved one is kept" }, { - "name": "machine", - "kind": "Name", - "help": "on a connected Store: the address is this machine's own" + "name": "password", + "kind": "Content", + "help": "its password; needed on a Store's first connect, else the saved one is kept; the shell reads it from stdin with --password-stdin", + "redact": true, + "shell": "--password-stdin" }, { "name": "synchronous_commit", "kind": "Text", - "help": "off, local, remote_write, on or remote_apply; first connect only", + "help": "off, local, remote_write, on or remote_apply; a new Store takes local", "default": "local" } ], - "stdin": null, + "stdin": "secret", "with": {}, "paging": null, "progress": false, @@ -368,17 +379,18 @@ "outcome", "store", "engine", - "auth", - "connections", - "synchronous_commit" + "url", + "user", + "synchronous_commit", + "machines" ], "item": null, "examples": { "short": [ "first connect: {\"projects\":[\"api\",\"web\"]}", - "an empty database, or an address set: {\"ok\":true}" + "an empty database, or a connected Store changed: {\"ok\":true}" ], - "long": "{\"ok\":true,\"projects\":[\"api\",\"web\"],\"projects_count\":null,\"outcome\":\"connected\",\"store\":\"shop-pg\",\"engine\":\"postgresql\",\"auth\":\"pg-app\",\"connections\":[{\"machine\":null,\"url\":\"postgres://db.internal:5432/shop\",\"own\":false,\"server\":{\"host\":\"db.internal\",\"port\":5432,\"database\":\"shop\"},\"reached\":null,\"reach\":null}],\"synchronous_commit\":\"local\"}" + "long": "{\"ok\":true,\"projects\":[\"api\",\"web\"],\"projects_count\":null,\"outcome\":\"connected\",\"store\":\"shop-pg\",\"engine\":\"postgresql\",\"url\":\"postgres://db.internal:5432/shop\",\"user\":\"app\",\"synchronous_commit\":\"local\",\"machines\":[]}" }, "dropped": [ { @@ -387,12 +399,17 @@ "why": "an existing thing is named by its own word, never `name`" }, { - "today": "--password", - "now": "--auth", - "why": "a login is saved once in the home and named by any number of Stores" + "today": "--auth", + "now": "--user, --password-stdin", + "why": "this computer is the one place a Store's URL and login are saved; machines attach and inherit both (owner, 2026-11-24)" + }, + { + "today": "--machine", + "now": "store attach", + "why": "no machine has an address of its own" } ], - "new_work": "Saved logins and a URL with no user are new: today the record holds the URL with its user and a password reference (env:NAME or file:/path) per Store. A machine's own address through connect replaces store.update --machine --url, and no longer takes a password; the proof from that machine exists. Replacing the address every machine uses is store.update --url today. The id-only uniqueness check is a change: today a second Store is also refused when its URL names the same host, port and database. `outcome` is connected for a new Store and updated for an address." + "new_work": "Owner, 2026-11-24: the login is given to connect itself, checked from this process before anything is saved; the user is kept in the record and the password in the home's secret folder (kind `login`, by Store). A connect of a connected Store changes its address, user, password or synchronous_commit, keeping what it is not given, and must reach the same Store (binding) first. `outcome` is connected for a new Store and updated otherwise. Saved logins by name, --auth and --machine are gone." }, { "call": "store.disconnect", @@ -401,21 +418,15 @@ "today": [ "store.disconnect" ], - "help": "forget a PostgreSQL Store, or one machine's own address and reach; its data stays", - "cli": "layerfs store disconnect [--machine M]", + "help": "forget a PostgreSQL Store, its saved login and its attachments; its data stays", + "cli": "layerfs store disconnect ", "positionals": [ { "name": "store", "kind": "Name" } ], - "options": [ - { - "name": "machine", - "kind": "Name", - "help": "remove only this machine's own address" - } - ], + "options": [], "stdin": null, "with": {}, "paging": null, @@ -431,15 +442,14 @@ "long": [ "ok", "outcome", - "store", - "machine" + "store" ], "item": null, "examples": { "short": [ "{\"ok\":true}" ], - "long": "{\"ok\":true,\"outcome\":\"disconnected\",\"store\":\"shop-pg\",\"machine\":null}" + "long": "{\"ok\":true,\"outcome\":\"disconnected\",\"store\":\"shop-pg\"}" }, "dropped": [ { @@ -448,76 +458,29 @@ "why": "an existing thing is named by its own word, never `name`" } ], - "new_work": "`--machine` moves here from store.update --machine --clear; the capability exists." + "new_work": "Owner, 2026-11-24: --machine is gone (no machine has an address of its own); the Store's saved password and attachments go with it." }, { - "call": "store.save_auth", + "call": "store.attach", "badge": "new", - "note": "a login saved once in the home: a user and a password, no address. The password is the option password: the shell reads it from stdin with --password-stdin and takes it no other way; Node and Python pass it as the option. It is kept in the home's secret folder (0600), never answered, and the call log records its byte count only. Saving again under the same name rotates it: every Store and machine using it picks it up at its next connection, and running Sandboxes keep their session", + "note": "Owner, 2026-11-24.", "today": [], - "help": "save a PostgreSQL login in the home; saving again rotates it", - "cli": "layerfs store save-auth --user U --password-stdin", + "help": "let a machine run Sandboxes of a PostgreSQL Store, checked from that machine first", + "cli": "layerfs store attach --machine M", "positionals": [ { - "name": "auth", + "name": "store", "kind": "Name" } ], "options": [ { - "name": "user", - "kind": "Text", - "help": "the PostgreSQL role; required", + "name": "machine", + "kind": "Name", + "help": "the machine; required", "required": true - }, - { - "name": "password", - "kind": "Content", - "help": "the password; required; the shell reads it from stdin with --password-stdin", - "required": true, - "redact": true, - "shell": "--password-stdin" } ], - "stdin": "secret", - "with": {}, - "paging": null, - "progress": false, - "quiet": false, - "profile": "full", - "short": { - "always": [ - "ok" - ], - "sometimes": [] - }, - "long": [ - "ok", - "outcome", - "auth", - "user", - "stores", - "stores_count" - ], - "item": null, - "examples": { - "short": [ - "{\"ok\":true}" - ], - "long": "{\"ok\":true,\"outcome\":\"saved\",\"auth\":\"pg-app\",\"user\":\"app\",\"stores\":[],\"stores_count\":null}" - }, - "dropped": [], - "new_work": "All of it: saved logins, the home's secret folder and reading a secret from stdin do not exist. Today each Store records its own password reference (env:NAME or file:/path), resolved by the caller on each call." - }, - { - "call": "store.auths", - "badge": "new", - "note": "never the password. stores are the Stores that name the login (first 20). Unpaged: a home holds a handful of logins A login file that cannot be read is its own row, broken failed with the save that writes it again, and the rest are listed as usual (spec v23).", - "today": [], - "help": "the saved PostgreSQL logins and the Stores that use each", - "cli": "layerfs store auths", - "positionals": [], - "options": [], "stdin": null, "with": {}, "paging": null, @@ -526,104 +489,39 @@ "profile": "full", "short": { "always": [ - "items" + "ok", + "outcome" ], - "sometimes": [] - }, - "long": [ - "items" - ], - "item": { - "short": { - "always": [ - "auth", - "user" - ], - "sometimes": [ - "state", - "reason", - "fix", - "stores", - "stores_count" - ] - }, - "long": [ - "auth", - "user", - "state", - "reason", - "fix", - "stores", - "stores_count", - "created_at", - "updated_at" + "sometimes": [ + "latency_ms" ] }, - "examples": { - "short": [ - "{\"items\":[{\"auth\":\"pg-app\",\"user\":\"app\",\"stores\":[\"shop-pg\",\"analytics\"]},{\"auth\":\"pg-ro\",\"user\":\"reader\"}]}" - ], - "long": "{\"items\":[{\"auth\":\"pg-app\",\"user\":\"app\",\"state\":\"ready\",\"reason\":null,\"fix\":null,\"stores\":[\"shop-pg\",\"analytics\"],\"stores_count\":null,\"created_at\":\"2026-11-17T09:16:59Z\",\"updated_at\":\"2026-11-18T09:16:59Z\"},{\"auth\":\"pg-old\",\"user\":null,\"state\":\"broken\",\"reason\":\"failed\",\"fix\":\"layerfs store save-auth pg-old --user --password-stdin\",\"stores\":[],\"stores_count\":null,\"created_at\":null,\"updated_at\":null}]}" - }, - "dropped": [], - "new_work": "All of it (see store.save_auth).", - "states": { - "reasons": [ - "failed" - ], - "ops": [] - } - }, - { - "call": "store.remove_auth", - "badge": "new", - "note": "refused InUse while a Store names it, listing those Stores", - "today": [], - "help": "remove a saved PostgreSQL login no Store uses", - "cli": "layerfs store remove-auth ", - "positionals": [ - { - "name": "auth", - "kind": "Name" - } - ], - "options": [], - "stdin": null, - "with": {}, - "paging": null, - "progress": false, - "quiet": false, - "profile": "full", - "short": { - "always": [ - "ok" - ], - "sometimes": [] - }, "long": [ "ok", "outcome", - "auth" + "store", + "machine", + "latency_ms", + "server_version" ], "item": null, "examples": { "short": [ - "{\"ok\":true}" + "{\"ok\":true,\"outcome\":\"attached\",\"latency_ms\":3}", + "an attached machine checked again: {\"ok\":true,\"outcome\":\"checked\",\"latency_ms\":2}" ], - "long": "{\"ok\":true,\"outcome\":\"removed\",\"auth\":\"pg-ro\"}" + "long": "{\"ok\":true,\"outcome\":\"attached\",\"store\":\"shop-pg\",\"machine\":\"lab\",\"latency_ms\":3,\"server_version\":\"17.6\"}" }, "dropped": [], - "new_work": "All of it (see store.save_auth)." + "new_work": "New (owner, 2026-11-24): the Store is checked from the machine with the URL and login this computer saved, as its Sandboxes dial them; the machine is then recorded in the Store's `attached` and its reach observed. sandbox.create on a machine not attached is refused with this call as its fix." }, { - "call": "store.update", - "badge": "reshaped", - "note": "PostgreSQL: another saved login, or the setting; one of the two is required. A new login is checked once, on the Store's connection, before it is saved, and must read the same id. An address change is a store connect; a machine's own address is removed with store disconnect --machine. A running Sandbox keeps the connection it started with The login is checked again under the home's lock, so one store remove-auth removed meanwhile is refused NotFound, and the write drops what 2.0 no longer writes: store update <store> --auth <its auth> is the outdated fix (spec v23).", - "today": [ - "store.update" - ], - "help": "change a PostgreSQL Store's saved login or its synchronous_commit", - "cli": "layerfs store update [--auth A] [--synchronous-commit S]", + "call": "store.detach", + "badge": "new", + "note": "Owner, 2026-11-24.", + "today": [], + "help": "stop a machine running Sandboxes of a PostgreSQL Store; refused while one runs there", + "cli": "layerfs store detach --machine M", "positionals": [ { "name": "store", @@ -632,14 +530,10 @@ ], "options": [ { - "name": "auth", + "name": "machine", "kind": "Name", - "help": "another saved login" - }, - { - "name": "synchronous_commit", - "kind": "Text", - "help": "off, local, remote_write, on or remote_apply" + "help": "the machine; required", + "required": true } ], "stdin": null, @@ -658,44 +552,17 @@ "ok", "outcome", "store", - "auth", - "synchronous_commit" + "machine" ], "item": null, "examples": { "short": [ "{\"ok\":true}" ], - "long": "{\"ok\":true,\"outcome\":\"updated\",\"store\":\"shop-pg\",\"auth\":\"pg-app-2\",\"synchronous_commit\":\"local\"}" + "long": "{\"ok\":true,\"outcome\":\"detached\",\"store\":\"shop-pg\",\"machine\":\"lab\"}" }, - "dropped": [ - { - "today": "", - "now": "", - "why": "an existing thing is named by its own word, never `name`" - }, - { - "today": "--url", - "now": "store connect ", - "why": "an address change is a connect, checked like one" - }, - { - "today": "--machine", - "now": "store connect --machine M", - "why": "a machine's own address is a connect; the login is the Store's" - }, - { - "today": "--password", - "now": "--auth, or store save-auth to rotate", - "why": "the login is saved once and named" - }, - { - "today": "--clear", - "now": "store disconnect --machine M", - "why": "removing an address is a disconnect" - } - ], - "new_work": "`--auth` is new (see store.save_auth). `--synchronous-commit` exists today." + "dropped": [], + "new_work": "New (owner, 2026-11-24): refused InUse while a Sandbox of the Store's projects is on the machine, NotFound when it is not attached; its reach is forgotten." }, { "call": "store.move", @@ -954,7 +821,7 @@ { "name": "machine", "kind": "Name", - "help": "also probe a PostgreSQL Store's connection from this machine" + "help": "check a PostgreSQL Store from this computer and this attached machine only" } ], "stdin": null, @@ -1030,7 +897,7 @@ }, { "check": "store.connection", - "what": "it is reached where it lives: a sqlite Store through its machine; a PostgreSQL Store from this computer, and once more from each machine that has a Sandbox of it, with `from` naming that machine", + "what": "it is reached where it lives: a sqlite Store through its machine; a PostgreSQL Store from this computer, then (when this computer is let in) once more from each machine attached to it, with `from` naming that machine", "full_only": false }, { diff --git a/docs/architecture/api/README.md b/docs/architecture/api/README.md index 3f07652db0..c496158f5c 100644 --- a/docs/architecture/api/README.md +++ b/docs/architecture/api/README.md @@ -48,7 +48,7 @@ give each call's own arguments, answer and errors. | Convention | Rule | Source | | --- | --- | --- | -| Names | `family.call`, snake_case in every front end (`machine.load_image`, `store.save_auth`); the CLI writes `layerfs machine load-image` and options as `--synchronous-commit`. Python spells the options `with` and `from` as `with_` and `from_` | [`calls/table.rs`](../../../api/crates/layerfs-api/src/calls/table.rs), [`layerfs-cli/src/parse.rs`](../../../api/crates/layerfs-cli/src/parse.rs) | +| Names | `family.call`, snake_case in every front end (`machine.load_image`, `project.hide_path`); the CLI writes `layerfs machine load-image` and options as `--synchronous-commit`. Python spells the options `with` and `from` as `with_` and `from_` | [`calls/table.rs`](../../../api/crates/layerfs-api/src/calls/table.rs), [`layerfs-cli/src/parse.rs`](../../../api/crates/layerfs-cli/src/parse.rs) | | Positionals | required, in table order, from the outside in: owner, Branch, path or new name, other inputs, an optional Commit last | [`calls/table.rs`](../../../api/crates/layerfs-api/src/calls/table.rs) | | Options | named and optional: a trailing object (JS), keywords (Python), `--flags` (CLI); an unknown or misspelled one is `InvalidInput` before any effect | [`calls/check.rs`](../../../api/crates/layerfs-api/src/calls/check.rs) | | Kinds | `Name`, `Project` (`/`), `Text`, `Int`, `Bool`, `Json`, `Content` (text or bytes), `Size` (bytes, or `64K`, `512M`, `8G` in powers of 1024), `Function` (stays in the front end) | [Calls](calls/README.md) | diff --git a/docs/architecture/api/calls/coverage.md b/docs/architecture/api/calls/coverage.md index fc415b18f9..c3e08c8ec8 100644 --- a/docs/architecture/api/calls/coverage.md +++ b/docs/architecture/api/calls/coverage.md @@ -42,7 +42,7 @@ check and proves a missing, renamed or extra call is reported. -83 calls in 10 families, counted from the Node table. Calls present: Node 83, Python 83, Python `aio` 83, CLI 83, MCP 83 (17 in `work`, 66 admin only). +81 calls in 10 families, counted from the Node table. Calls present: Node 81, Python 81, Python `aio` 81, CLI 81, MCP 81 (17 in `work`, 64 admin only). Argument names that are Python keywords: from. @@ -117,12 +117,10 @@ Front-end problems: none. | `store.list` | - | machine | yes | yes | yes | yes | admin | | `store.get` | store | - | yes | yes | yes | yes | admin | | `store.create` | name | machine | yes | yes | yes | yes | admin | -| `store.connect` | store, url | auth, machine, synchronous_commit | yes | yes | yes | yes | admin | -| `store.disconnect` | store | machine | yes | yes | yes | yes | admin | -| `store.save_auth` | auth | user, password | yes | yes | yes | yes | admin | -| `store.auths` | - | - | yes | yes | yes | yes | admin | -| `store.remove_auth` | auth | - | yes | yes | yes | yes | admin | -| `store.update` | store | auth, synchronous_commit | yes | yes | yes | yes | admin | +| `store.connect` | store, url | user, password, synchronous_commit | yes | yes | yes | yes | admin | +| `store.disconnect` | store | - | yes | yes | yes | yes | admin | +| `store.attach` | store | machine | yes | yes | yes | yes | admin | +| `store.detach` | store | machine | yes | yes | yes | yes | admin | | `store.move` | store, machine | on_progress() | yes | yes | yes | yes (--progress) | admin | | `store.remove` | store | - | yes | yes | yes | yes | admin | | `store.compact` | store | on_progress() | yes | yes | yes | yes (--progress) | admin | diff --git a/docs/architecture/api/front-ends/README.md b/docs/architecture/api/front-ends/README.md index 2cd9c28619..45ce7ca501 100644 --- a/docs/architecture/api/front-ends/README.md +++ b/docs/architecture/api/front-ends/README.md @@ -83,7 +83,7 @@ words against its entry: | `-m ` | the `message` option (nine calls); exit 2 when the call has none | | `--detail` | the long form (every call) | | `--with ` | the named sections (the ten calls that list some); a name the call does not list is exit 2 | -| a secret option | read from stdin with its own flag only: `store save-auth --password-stdin`, `backup connect --key-stdin` | +| a secret option | read from stdin with its own flag only: `store connect --password-stdin`, `backup connect --key-stdin` | | content or JSON positional (`file.write`, `file.apply`) | read from stdin, or `--from `; text when UTF-8, else bytes (JSON must be UTF-8); not counted on the line | | any other `--x` | exit 2, listing the call's options | diff --git a/docs/architecture/api/front-ends/mcp.md b/docs/architecture/api/front-ends/mcp.md index 06ef98458b..77f1ddf138 100644 --- a/docs/architecture/api/front-ends/mcp.md +++ b/docs/architecture/api/front-ends/mcp.md @@ -116,7 +116,7 @@ built addon). -83 calls: 17 in `work` (the table's `agent` profile), 66 in `admin` only (`full`); `--profile admin` lists 83. +81 calls: 17 in `work` (the table's `agent` profile), 64 in `admin` only (`full`); `--profile admin` lists 81. | Call | Bucket | Profiles that list it | Why | | --- | --- | --- | --- | @@ -184,19 +184,17 @@ built addon). | `machine.remove` | admin | admin | machines hold Stores and workers: read, start, stop, create, change, inspect and check them; the `full` profile (administration) | | `machine.update` | admin | admin | machines hold Stores and workers: read, start, stop, create, change, inspect and check them; the `full` profile (administration) | | `machine.doctor` | admin | admin | machines hold Stores and workers: read, start, stop, create, change, inspect and check them; the `full` profile (administration) | -| `store.list` | admin | admin | create, connect, move, compact, check and remove Stores, and keep PostgreSQL logins; the `full` profile (administration) | -| `store.get` | admin | admin | create, connect, move, compact, check and remove Stores, and keep PostgreSQL logins; the `full` profile (administration) | -| `store.create` | admin | admin | create, connect, move, compact, check and remove Stores, and keep PostgreSQL logins; the `full` profile (administration) | -| `store.connect` | admin | admin | create, connect, move, compact, check and remove Stores, and keep PostgreSQL logins; the `full` profile (administration) | -| `store.disconnect` | admin | admin | create, connect, move, compact, check and remove Stores, and keep PostgreSQL logins; the `full` profile (administration) | -| `store.save_auth` | admin | admin | create, connect, move, compact, check and remove Stores, and keep PostgreSQL logins; the `full` profile (administration) | -| `store.auths` | admin | admin | create, connect, move, compact, check and remove Stores, and keep PostgreSQL logins; the `full` profile (administration) | -| `store.remove_auth` | admin | admin | create, connect, move, compact, check and remove Stores, and keep PostgreSQL logins; the `full` profile (administration) | -| `store.update` | admin | admin | create, connect, move, compact, check and remove Stores, and keep PostgreSQL logins; the `full` profile (administration) | -| `store.move` | admin | admin | create, connect, move, compact, check and remove Stores, and keep PostgreSQL logins; the `full` profile (administration) | -| `store.remove` | admin | admin | create, connect, move, compact, check and remove Stores, and keep PostgreSQL logins; the `full` profile (administration) | +| `store.list` | admin | admin | create, connect, attach, move, compact, check and remove Stores; the `full` profile (administration) | +| `store.get` | admin | admin | create, connect, attach, move, compact, check and remove Stores; the `full` profile (administration) | +| `store.create` | admin | admin | create, connect, attach, move, compact, check and remove Stores; the `full` profile (administration) | +| `store.connect` | admin | admin | create, connect, attach, move, compact, check and remove Stores; the `full` profile (administration) | +| `store.disconnect` | admin | admin | create, connect, attach, move, compact, check and remove Stores; the `full` profile (administration) | +| `store.attach` | admin | admin | create, connect, attach, move, compact, check and remove Stores; the `full` profile (administration) | +| `store.detach` | admin | admin | create, connect, attach, move, compact, check and remove Stores; the `full` profile (administration) | +| `store.move` | admin | admin | create, connect, attach, move, compact, check and remove Stores; the `full` profile (administration) | +| `store.remove` | admin | admin | create, connect, attach, move, compact, check and remove Stores; the `full` profile (administration) | | `store.compact` | admin | admin | reclaim one Store's dead bytes; a folder scope refuses it; the `full` profile (administration) | -| `store.doctor` | admin | admin | create, connect, move, compact, check and remove Stores, and keep PostgreSQL logins; the `full` profile (administration) | +| `store.doctor` | admin | admin | create, connect, attach, move, compact, check and remove Stores; the `full` profile (administration) | | `backup.connect` | admin | admin | connect buckets, back up and restore a Store, and check a bucket; the `full` profile (administration) | | `backup.disconnect` | admin | admin | connect buckets, back up and restore a Store, and check a bucket; the `full` profile (administration) | | `backup.list` | admin | admin | connect buckets, back up and restore a Store, and check a bucket; the `full` profile (administration) | @@ -248,7 +246,7 @@ the SDK's request schema (`-32603`). The call does not run. | `workspace.exec` | output is buffered (no `stdout`/`stderr` function): each stream's text is in the result up to its last 1 MiB; a longer stream answers its last 1 MiB and `stdout_file` or `stderr_file` names the file on the machine that holds all of it; `stdout_bytes` and `stderr_bytes` (long form) give its full size | [Errors and events](../calls/errors-and-events.md#workspaceexec-output) | | Cancel notification | acknowledged on stderr; the native call cannot be cancelled and runs to its end | [`server.js`](../../../../api/mcp/src/server.js) | | stdin close, `SIGTERM`, `SIGINT` | stop accepting calls, wait up to 2 s (`GRACE_MS`) for in-flight ones, run `layerfs.close()` (idle Stores only), exit 0. A Workspace stays mounted; a call still running is cut off and its outcome is unknown | [`server.js`](../../../../api/mcp/src/server.js) | -| stdout, stderr | stdout carries one JSON-RPC message per line and nothing else while serving; one `layerfs-mcp: …` line per call, startup and shutdown on stderr. Argument values are never logged (a `store.save_auth` password, a `backup.connect` key) | [`server.js`](../../../../api/mcp/src/server.js) | +| stdout, stderr | stdout carries one JSON-RPC message per line and nothing else while serving; one `layerfs-mcp: …` line per call, startup and shutdown on stderr. Argument values are never logged (a `store.connect` password, a `backup.connect` key) | [`server.js`](../../../../api/mcp/src/server.js) | ## Limits diff --git a/docs/architecture/api/sdk/README.md b/docs/architecture/api/sdk/README.md index 10fc46b91b..64dff20630 100644 --- a/docs/architecture/api/sdk/README.md +++ b/docs/architecture/api/sdk/README.md @@ -60,7 +60,7 @@ against the built table. | [`sandbox`](sandbox.md) (7) | [`create`](sandbox.md#sandboxcreate), [`list`](sandbox.md#sandboxlist), [`get`](sandbox.md#sandboxget), [`remove`](sandbox.md#sandboxremove), [`files`](sandbox.md#sandboxfiles), [`log`](sandbox.md#sandboxlog), [`doctor`](sandbox.md#sandboxdoctor) | records here; start and stop on the Sandbox's machine; `files`, `log`: where the Sandbox's run folder is | [`sandbox/`](../../../../api/crates/layerfs-api/src/sandbox) | | [`workspace`](workspace.md) (7) | [`list`](workspace.md#workspacelist), [`mount`](workspace.md#workspacemount), [`exec`](workspace.md#workspaceexec), [`cancel`](workspace.md#workspacecancel), [`commit`](workspace.md#workspacecommit), [`unmount`](workspace.md#workspaceunmount), [`status`](workspace.md#workspacestatus) | the Sandbox's daemon; `exec` and `cancel` in the Sandbox's runtime; `list` from Workspace records | [`workspace/`](../../../../api/crates/layerfs-api/src/workspace) | | [`machine`](machine.md) (14) | [`list`](machine.md#machinelist), [`get`](machine.md#machineget), [`images`](machine.md#machineimages), [`load_image`](machine.md#machineload_image), [`prune`](machine.md#machineprune), [`stats`](machine.md#machinestats), [`files`](machine.md#machinefiles), [`log`](machine.md#machinelog), [`start`](machine.md#machinestart), [`stop`](machine.md#machinestop), [`create`](machine.md#machinecreate), [`remove`](machine.md#machineremove), [`update`](machine.md#machineupdate), [`doctor`](machine.md#machinedoctor) | the caller's process, through the platform adapter; `stats`, `files`, `log`: where the machine's data is | [`machine/`](../../../../api/crates/layerfs-api/src/machine) | -| [`store`](store.md) (13) | [`list`](store.md#storelist), [`get`](store.md#storeget), [`create`](store.md#storecreate), [`connect`](store.md#storeconnect), [`disconnect`](store.md#storedisconnect), [`save_auth`](store.md#storesave_auth), [`auths`](store.md#storeauths), [`remove_auth`](store.md#storeremove_auth), [`update`](store.md#storeupdate), [`move`](store.md#storemove), [`remove`](store.md#storeremove), [`compact`](store.md#storecompact), [`doctor`](store.md#storedoctor) | the caller's process; sqlite file steps in the Store machine's worker | [`store/`](../../../../api/crates/layerfs-api/src/store) | +| [`store`](store.md) (11) | [`list`](store.md#storelist), [`get`](store.md#storeget), [`create`](store.md#storecreate), [`connect`](store.md#storeconnect), [`disconnect`](store.md#storedisconnect), [`attach`](store.md#storeattach), [`detach`](store.md#storedetach), [`move`](store.md#storemove), [`remove`](store.md#storeremove), [`compact`](store.md#storecompact), [`doctor`](store.md#storedoctor) | the caller's process; sqlite file steps in the Store machine's worker | [`store/`](../../../../api/crates/layerfs-api/src/store) | | [`backup`](backup.md) (6) | [`connect`](backup.md#backupconnect), [`disconnect`](backup.md#backupdisconnect), [`list`](backup.md#backuplist), [`create`](backup.md#backupcreate), [`restore`](backup.md#backuprestore), [`doctor`](backup.md#backupdoctor) | the caller's process; `create` stages on the Store's machine | [`backup/`](../../../../api/crates/layerfs-api/src/backup) | "Where the Store's calls run" is the caller's process for a PostgreSQL Store @@ -82,7 +82,7 @@ progress, the refusals the call names with their `fix`, and its MCP profile | To get | You first need | Made by | | --- | --- | --- | | a sqlite Store | nothing (`native` is built in) | [`store.create`](store.md#storecreate) | -| a PostgreSQL Store | a saved login | [`store.save_auth`](store.md#storesave_auth), [`store.connect`](store.md#storeconnect) | +| a PostgreSQL Store | a database and its login | [`store.connect`](store.md#storeconnect); [`store.attach`](store.md#storeattach) for a machine other than `native` | | a project | a Store | [`project.init`](project.md#projectinit) | | a Branch to work on | a project (`main` is its published line) | [`branch.fork`](branch.md#branchfork) | | a Sandbox | a project and a machine | [`sandbox.create`](sandbox.md#sandboxcreate) | @@ -149,5 +149,5 @@ The 1.x names below are gone in 2.0; nothing answers to them. | [sandbox](sandbox.md) | Sandboxes: create, list, get, remove, files, log, doctor | | [workspace](workspace.md) | list, mount, exec, cancel, commit, unmount, status | | [machine](machine.md) | built-in and VM machines, their images, stats, files and logs | -| [store](store.md) | sqlite and PostgreSQL Stores, saved logins, moves, compaction | +| [store](store.md) | sqlite and PostgreSQL Stores, attached machines, moves, compaction | | [backup](backup.md) | buckets, Store backups and restores | diff --git a/docs/architecture/api/sdk/home.md b/docs/architecture/api/sdk/home.md index 28a87fba9d..0e082762e3 100644 --- a/docs/architecture/api/sdk/home.md +++ b/docs/architecture/api/sdk/home.md @@ -144,15 +144,13 @@ it dials nothing, and is null unless the home is ready. | Node | Long form | Short form | | --- | --- | --- | | machine | `machine, platform, cpus, memory_bytes, state, op, reason, fix, stores, sandboxes` | `machine`, `platform`; its state and companion unless ready; `cpus`, `memory_bytes`, `stores` and `sandboxes` when set | -| Store | `store, engine, projects, connections, state, op, blocked_by, reason, fix` | `store`, `engine`; `projects` and `connections` (`store get`'s rows) unless empty; its state unless ready | +| Store | `store, engine, projects, machines, state, op, blocked_by, reason, fix` | `store`, `engine`; `projects` and `machines` (the attached machines' names) unless empty; its state unless ready | | Sandbox | `sandbox, project, image, workspaces, workspaces_not_listed, state, op, blocked_by, reason, fix` | `sandbox`, `project`; `image`, `workspaces` (`[{ workspace, branch }]`) unless empty; `workspaces_not_listed` when true; its state unless ready | | bucket | `bucket, provider` | `bucket`, `provider` | A sqlite Store is under its machine; a PostgreSQL Store lives on no machine -and is in the top-level `stores`, with `connections` naming every side that -connects to it, as `store get` answers them (spec v23): this computer first -(`machine` null, the Store's own URL), then each machine with an address of -its own, a reach seen or a Sandbox of the Store. A Sandbox's `workspaces` are listed +and is in the top-level `stores`, with `machines` naming the machines +attached to it (`store attach`); `store get` answers each one's reach. A Sandbox's `workspaces` are listed only where the home keeps their records (on `native`, or a Sandbox reached directly); otherwise `workspaces_not_listed` is true, and for a blocked Sandbox `workspaces` is null. States come from the records: a recorded diff --git a/docs/architecture/api/sdk/sandbox.md b/docs/architecture/api/sdk/sandbox.md index 630dd45187..0784f719e4 100644 --- a/docs/architecture/api/sdk/sandbox.md +++ b/docs/architecture/api/sdk/sandbox.md @@ -81,7 +81,10 @@ record is written once with the answer, dropping the `op`; a refused start removes the record. With no `--machine` the Sandbox runs on its sqlite Store's machine, else on `native`; another machine than a sqlite Store's is `Unsupported`, and the support table must accept the platform and Store -kind. For a PostgreSQL Store the caller resolves the saved login and sends +kind. A PostgreSQL Store's Sandbox runs on `native` or on a machine attached +to it: any other is refused `InvalidInput` with `layerfs store attach + --machine ` as its fix. The caller puts the Store's user +and saved password into the URL and sends the URL only in this request; the launching side checks that it reaches the server and holds the project first. Nothing starts a stopped machine. diff --git a/docs/architecture/api/sdk/store.md b/docs/architecture/api/sdk/store.md index 32964a14c4..cc5e474991 100644 --- a/docs/architecture/api/sdk/store.md +++ b/docs/architecture/api/sdk/store.md @@ -2,12 +2,12 @@ > **Status:** Current architecture guide for LayerFS 2.0.0; maintained with the source. -The `store` calls: list and read Stores, create a sqlite Store, connect a PostgreSQL database as a Store with a saved login, move, remove, compact and check a Store, within the [SDK](README.md). `store.doctor` is one of [the doctors](../../control/doctor/README.md). +The `store` calls: list and read Stores, create a sqlite Store, connect a PostgreSQL database as a Store with its login, attach machines to it, move, remove, compact and check a Store, within the [SDK](README.md). `store.doctor` is one of [the doctors](../../control/doctor/README.md). | | | | --- | --- | | Source | [`api/crates/layerfs-api/src/store`](../../../../api/crates/layerfs-api/src/store) (one file per call), [`layerfs-store/src`](../../../../control/crates/layerfs-store/src) (`sqlite/`, `postgresql/`, `list.rs`, `get.rs`, `state.rs`, `live.rs`, `stats.rs`, `intent.rs`, `compact.rs`), [`layerfs-control/src/store.rs`](../../../../control/crates/layerfs-control/src/store.rs) | -| Runs by default | the caller's process (records, locks, leases, saved logins, PostgreSQL connections); a sqlite Store's file steps run in its machine's worker when it is not on a locally executing machine | +| Runs by default | the caller's process (records, locks, leases, saved passwords, PostgreSQL connections); a sqlite Store's file steps run in its machine's worker when it is not on a locally executing machine | | Design | [Stores and projects](../../control/stores-and-projects/README.md) (records, placement, leases), [SQLite and PostgreSQL](../../control/stores-and-projects/sqlite-and-postgresql.md), [Engine: Store](../../engine/store/README.md) | ## Calls @@ -17,12 +17,12 @@ The `store` calls: list and read Stores, create a sqlite Store, connect a Postgr | sqlite | PostgreSQL ------ | ---------- - create [--machine] | save-auth --user U --password-stdin - | | auths, remove-auth - v | connect --auth A - move connect ... --machine M (its own address) - move native (back) update [--auth A] [--synchronous-commit S] - | disconnect [--machine M] (data stays) + create [--machine] | connect --user U --password-stdin + | | connect (change address, login, setting) + v | attach --machine M (checked from M) + move detach --machine M + move native (back) disconnect (login and attachments go; data stays) + | | v remove (file + projects) compact (both engines: reclaim dead bytes) @@ -35,10 +35,8 @@ The `store` calls: list and read Stores, create a sqlite Store, connect a Postgr | [`store.create`](#storecreate) | sqlite | `{ ok }` | `admin` | | [`store.connect`](#storeconnect) | PostgreSQL | `{ projects }`, or `{ ok }` | `admin` | | [`store.disconnect`](#storedisconnect) | PostgreSQL | `{ ok }` | `admin` | -| [`store.save_auth`](#storesave_auth) | PostgreSQL | `{ ok }` | `admin` | -| [`store.auths`](#storeauths) | PostgreSQL | `{ items: [{ auth, user, state }] }` | `admin` | -| [`store.remove_auth`](#storeremove_auth) | PostgreSQL | `{ ok }` | `admin` | -| [`store.update`](#storeupdate) | PostgreSQL | `{ ok }` | `admin` | +| [`store.attach`](#storeattach) | PostgreSQL | `{ ok, outcome }` | `admin` | +| [`store.detach`](#storedetach) | PostgreSQL | `{ ok }` | `admin` | | [`store.move`](#storemove) | sqlite | `{ moved_bytes }` | `admin` | | [`store.remove`](#storeremove) | sqlite | `{ ok }`, or `{ left }` | `admin` | | [`store.compact`](#storecompact) | both | `{ freed_bytes }` | `admin` | @@ -89,18 +87,19 @@ Python layerfs.store.list(*, machine=None, with_=None) | --- | --- | | short | `items` | | long | `items` | -| `items[]` short | `store`, `engine`; when set: `state`, `machine`, `auth`, `connections`, `projects`, `projects_count`, `backups`, `op`, `blocked_by`, `reason`, `fix`, `observed_at` | -| `items[]` long | `store, engine, state, machine, auth, binding, connections, projects, projects_count, backups, op, blocked_by, reason, fix, observed_at, profile, synchronous_commit, sqlite_version, created_at, last_transfer` | +| `items[]` short | `store`, `engine`; when set: `state`, `machine`, `user`, `machines`, `projects`, `projects_count`, `backups`, `op`, `blocked_by`, `reason`, `fix`, `observed_at` | +| `items[]` long | `store, engine, state, machine, url, user, password_saved, password_changed_at, binding, reach, machines, projects, projects_count, backups, op, blocked_by, reason, fix, observed_at, profile, synchronous_commit, sqlite_version, created_at, last_transfer` | | `items[].projects[]` short | each a `project` | -| `items[].connections[]` short | `url`; when set: `machine`, `reached` | -| `items[].connections[]` long | `machine, url, own, server, reached, reach` | +| `items[].machines[]` short | each a `machine` (the attached machines' names) | | `items[].backups[]` short | `bucket` | | `items[].backups[]` long | `bucket, file, sha256, heads_sha256, last, attempt` | | `--with stats` | adds `size` | | call | writes one call-log line; MCP `admin` | Reads every `store/*/record.json`; a machine's state is derived once for -all its Stores. Each item is as `get` answers it, with `store` first. +all its Stores. Each item is as `get` answers it, with `store` first, +except that a PostgreSQL Store's `machines` are the attached machines' +names, with no reach. `--machine M` keeps the sqlite Stores on `M`. `--with stats` adds each item's `size` (file plus write-ahead log) from one `stat` on its machine, starting nothing; null for a PostgreSQL Store and for a machine that does @@ -128,11 +127,12 @@ Python layerfs.store.get(store, *, with_=None) | Answer | Keys | | --- | --- | -| short | `engine`, `state`; when set: `machine`, `auth`, `connections`, `projects`, `projects_count`, `backups`, `op`, `blocked_by`, `reason`, `fix`, `observed_at` | -| long | `engine, state, machine, auth, binding, connections, projects, projects_count, backups, op, blocked_by, reason, fix, observed_at, store, profile, synchronous_commit, sqlite_version, created_at, last_transfer` | +| short | `engine`, `state`; when set: `machine`, `url`, `user`, `machines`, `projects`, `projects_count`, `backups`, `op`, `blocked_by`, `reason`, `fix`, `observed_at` | +| long | `engine, state, machine, url, user, password_saved, password_changed_at, binding, reach, machines, projects, projects_count, backups, op, blocked_by, reason, fix, observed_at, store, profile, synchronous_commit, sqlite_version, created_at, last_transfer` | | `projects[]` short | each a `project` | -| `connections[]` short | `url`; when set: `machine`, `reached` | -| `connections[]` long | `machine, url, own, server, reached, reach` | +| `reach` | `at, ok, latency_ms, server_version, error` | +| `machines[]` short | `machine`; when set: `reached` | +| `machines[]` long | `machine, reached, reach` | | `backups[]` short | `bucket` | | `backups[]` long | `bucket, file, sha256, heads_sha256, last, attempt` | | `--with live` | adds `holders`, `phases`, `behind`, `server_version`, `latency_ms` | @@ -142,42 +142,27 @@ Python layerfs.store.get(store, *, with_=None) A Store's record and records-only state ([`get.rs`](../../../../control/crates/layerfs-store/src/get.rs)). A sqlite Store answers `machine`, `profile` and `sqlite_version`; a PostgreSQL Store -`auth` (its saved login, by name), `binding` (long form: the first 8 bytes -of the id in its schema as 16 hex, the open-Store cache's key), -`connections` and `synchronous_commit`; the other engine's keys are null. -`connections` (spec v23, -[`postgresql/connect.rs`](../../../../control/crates/layerfs-store/src/postgresql/connect.rs) -`connections`) lists every side that connects to the database: this computer -first (`machine` null, the Store's address), then by name each machine with -an address of its own, a reach seen from it, or a Sandbox of the Store (the -Sandbox records come from `layerfs-control` through -`layerfs_store::get::Sandboxes`); `native` with no address of its own dials -as this computer and is its row. A row is `{ machine, url, own, server, -reached, reach }`: the URL it dials (never a login), whether it is the -machine's own, the `{ host, port, database }` it names, and the last reach -seen with its word (`ok`, `failed`, null). Reaches live in the Store's -observation file, `store//observed.json` (`here` and -`reach.`, each `{ at, ok, latency_ms, server_version, error }`; +`url` (its address exactly as connected, never a login), `user`, +`password_saved` (whether this home holds its password), `password_changed_at` +(when it was last saved), `binding` (long form: the first 8 bytes of the id +in its schema as 16 hex, the open-Store cache's key), `reach` (this +computer's last reach), `machines` and `synchronous_commit`; the other +engine's keys are null. `machines` lists each attached machine by name as +`{ machine, reached, reach }`: the last reach seen from it and its word +(`ok`, `failed`, null). Reaches live in the Store's observation file, +`store//observed.json` (`here` and `reach.`, each `{ at, ok, +latency_ms, server_version, error }`; [`observed.rs`](../../../../control/crates/layerfs-store/src/observed.rs)): -`store connect --machine` records its check, `store doctor` each reach -(this computer's measured with the same check), and a Sandbox create on a -machine `{ at, ok: true }` after its reply. A writer takes the Store's lock -after its Store I/O and writes nothing once the record is gone; a live -read's `at` merges without a lock, as a read takes none. None of it moves -the home's `generation`. A PostgreSQL Store naming a login the home does not -hold is `broken` `missing`; one whose record holds a `password`, a URL that -is not an address alone or a `machines.` entry with anything but `url` -is `broken` `outdated`, fixed by `store update --auth `. No -URL is ever cleaned or rewritten: a URL that is not an address alone (one -that may hold a login, or a raw `#`) is replaced by the user's fix, which -dials only with the login it names: `store disconnect --machine M -&& store update --auth && store connect ---machine M` for a machine's own, `store disconnect && store -connect --auth --synchronous-commit ` and -each machine's own connected again for the Store's; until then the record -keeps that URL, and any password in it, as it was written -([`state.rs`](../../../../control/crates/layerfs-store/src/state.rs), -[`login.rs`](../../../../control/crates/layerfs-store/src/postgresql/login.rs)). `projects` shows at +`store attach` records its check, `store doctor` each reach (this +computer's measured with the same check), and a Sandbox create on a machine +`{ at, ok: true }` after its reply. A writer takes the Store's lock after its +Store I/O and writes nothing once the record is gone; a live read's `at` +merges without a lock, as a read takes none. None of it moves the home's +`generation`. A record without a `user`, or whose password this home does +not hold, has no state of its own: a call that dials it is refused +`InvalidInput` with `store connect --password-stdin` as its +fix ([`login.rs`](../../../../control/crates/layerfs-store/src/postgresql/login.rs) +`dial`). `projects` shows at most 20 names, `projects_count` only when there are more. A `backups` row's long form is `bucket, file, sha256, heads_sha256, last, attempt`: `last` the last transfer that worked (`{ call, ended_at, size }`), `attempt` the last @@ -272,42 +257,47 @@ $ layerfs store create shop ### store.connect -Connect a PostgreSQL database as a Store, or set an address of a connected one. +Connect a PostgreSQL database as a Store, or change a connected one's address, login or setting. ```text -CLI layerfs store connect [--auth A] [--machine M] [--synchronous-commit local] -Node await layerfs.store.connect(store, url, { auth, machine, synchronous_commit }) -Python layerfs.store.connect(store, url, *, auth=None, machine=None, synchronous_commit=None) +CLI layerfs store connect [--user U] [--password-stdin] [--synchronous-commit local] +Node await layerfs.store.connect(store, url, { user, password, synchronous_commit }) +Python layerfs.store.connect(store, url, *, user=None, password=None, synchronous_commit=None) ``` | Argument | Kind | Rule | | --- | --- | --- | | `store` | name | the Store's name in this home | | `url` | text | a `postgresql://` address: host, port, database and TLS settings, with no user or password | -| `auth` option | name | the saved login; required on a Store's first connect, refused afterwards | -| `machine` option | name | on a connected Store: the address is this machine's own | -| `synchronous_commit` option | text | off, local, remote_write, on or remote_apply; first connect only; default `local` | +| `user` option | text | the PostgreSQL role; required on a Store's first connect, else the saved one is kept | +| `password` option | content | its password; required on a Store's first connect, else the saved one is kept; the shell reads it from stdin with `--password-stdin` | +| `synchronous_commit` option | text | off, local, remote_write, on or remote_apply; a new Store takes `local`, a connected one keeps its own when omitted | | Answer | Keys | | --- | --- | | short | each when set: `ok`, `projects`, `projects_count` | -| long | `ok, projects, projects_count, outcome, store, engine, auth, connections, synchronous_commit` | +| long | `ok, projects, projects_count, outcome, store, engine, url, user, synchronous_commit, machines` | | call | writes one call-log line; MCP `admin` | -Connects a PostgreSQL database as a Store, or sets an address of a -connected one ([`postgresql/connect.rs`](../../../../control/crates/layerfs-store/src/postgresql/connect.rs)). -The record keeps the URL exactly as given, with no user and no password, -and names its saved login (`auth`), put into the URL only when the Store is -dialled; a URL that may hold a login is `InvalidInput`: one holding an `@`, +This computer is the one place a PostgreSQL Store's address and login are +saved (owner, 2026-11-24); every attached machine dials with them +([`postgresql/connect.rs`](../../../../control/crates/layerfs-store/src/postgresql/connect.rs)). +The record keeps the URL exactly as given, the `user` and +`synchronous_commit`, and the Store's `binding`. The password is kept in the +home's secret folder as secret kind `login` under the Store's name +(`secret/login/.json`, mode `0600` in a `0700` folder, `{ password, +changed }`), never answered, logged or written into a record; user and +password are put into the URL only when the Store is dialled +([`login.rs`](../../../../control/crates/layerfs-store/src/postgresql/login.rs) +`dial`). A URL that may hold a login is `InvalidInput`: one holding an `@`, one the PostgreSQL client reads a user or a password in, one it does not read, or one whose percent-decoded text holds a login key (`user`, `password`, `passfile`, `sslkey`, `sslcert`, `sslpassword`, `oauth_client_secret`) and `=` anywhere, in any case (`postgres://h/db&password=p`, `postgres://h/db?application_name=me?password=p`); so is one holding a `#` (written `%40` or `%23` when part of the address). -A URL is read only as that client reads it and shown exactly as written, -or as `postgresql://` when it may hold a -login; none is ever rewritten. The client takes `sslmode` +A URL is read only as that client reads it and shown exactly as written; +none is ever rewritten. The client takes `sslmode` `disable`, `prefer` or `require` and no certificate or key file: `sslmode=require` verifies the server's certificate chain and host name, and `sslmode=verify-full`, `verify-ca`, `sslrootcert`, `sslcert` and `sslkey` are @@ -318,190 +308,145 @@ that reads it: a Sandbox's daemon starts with a cleared environment); on macOS, where it is the Security framework, in the login or system keychain. -On a Store's first connect `--auth` is required and must be saved; -`--synchronous-commit` defaults to `local`. It creates the `layerfs` schema -in an empty database or reads the Store's id from it; an existing -database's projects become this home's project records. Short: `projects` -(the first 20 names, `projects_count` only past those), or `{"ok":true}` -for an empty database or when only an address changed. On a connected Store -`connect` checks the new address against the same Store's id and takes no -`--auth` or `--synchronous-commit` (`InvalidInput`, naming `store update`). -With `--machine M` the address is `M`'s own, checked from `M` with the -Store's login; a machine never has its own login. No default machine is -recorded: `sandbox create --machine M` chooses where a Sandbox of it runs. +On a Store's first connect `--user` and the password are required and are +checked from this process before anything is saved; `--synchronous-commit` +defaults to `local`. It creates the `layerfs` schema in an empty database or +reads the Store's id from it; an existing database's projects become this +home's project records. Short: `projects` (the first 20 names, +`projects_count` only past those), or `{"ok":true}` for an empty database. +The long `outcome` is `connected`. + +On a connected Store `connect` changes its address, user, password or +`synchronous_commit`: an omitted user or password keeps the saved one, and +the server must be reached with the result and hold the same Store (its +`binding`) before anything is saved. The Store's open connections in this +process are closed; a running Sandbox keeps the connection it started with. +Short `{"ok":true}`, long `outcome` `updated`. Attachments are kept: each +attached machine dials the new address and login from its next connection, +and `store doctor` checks them. A sqlite Store of that name is `Exists`. | Refusal | When | | --- | --- | -| `InvalidInput` | a URL that is not PostgreSQL, names a user or holds a password, holds an `@` or `#`, or that the PostgreSQL client does not read; a bad `--synchronous-commit`; `--auth` missing on a first connect; `--auth` or `--synchronous-commit` on a connected Store | -| `NotFound` | the named login is not saved (the message names `store save-auth`) | -| `Exists` | another Store of this home has that name or that database's id | -| `Unavailable` | no session (no database, a refused login, no server); the machine is stopped | -| `Unsupported` | the machine's platform runs no PostgreSQL Sandboxes here | +| `InvalidInput` | a URL that is not PostgreSQL, names a user or holds a password, holds an `@` or `#`, or that the PostgreSQL client does not read; a bad `--synchronous-commit`; `--user` or the password missing on a first connect; a connected Store whose record names no user or whose password this home does not hold, when none is given | +| `Exists` | a sqlite Store of that name, or another Store of this home with that database's id | +| `Unavailable` | no session (no database, a refused login, no server); a connected Store's new address that holds another Store | +| `Conflict` | the Store was disconnected or connected to another database meanwhile | Run on macOS native against a local `postgres:17`, with a debug build: ```console $ layerfs store connect shop-pg 'postgresql://postgres:pw@127.0.0.1:55231/shop' -{"error":"InvalidInput","message":"the URL names a user or holds a password (or a password file); give the address alone and the login with --auth (`layerfs store save-auth` saves one); an `@` or `#` that is part of the address is written %40 or %23"} +{"error":"InvalidInput","message":"the URL names a user or holds a password (or a password file); give the address alone and the login with --user and --password-stdin; an `@` or `#` that is part of the address is written %40 or %23"} +$ printf '%s' "$PGPASSWORD" | layerfs store connect shop-pg postgresql://127.0.0.1:55231/shop --user layerfs --password-stdin +{"ok":true} ``` ### store.disconnect -Forget a PostgreSQL Store, or one machine's own address; its data stays. +Forget a PostgreSQL Store, its saved login and its attachments; its data stays. ```text -CLI layerfs store disconnect [--machine M] -Node await layerfs.store.disconnect(store, { machine }) -Python layerfs.store.disconnect(store, *, machine=None) +CLI layerfs store disconnect +Node await layerfs.store.disconnect(store) +Python layerfs.store.disconnect(store) ``` | Argument | Kind | Rule | | --- | --- | --- | | `store` | name | a Store name | -| `machine` option | name | remove only this machine's own address | | Answer | Keys | | --- | --- | | short | `ok` | -| long | `ok, outcome, store, machine` | +| long | `ok, outcome, store` | | call | writes one call-log line; MCP `admin` | -Forgets a PostgreSQL Store in this home; the database keeps every byte and -`store connect` can record it again. With `--machine M` it removes only -`M`'s own address and forgets what was seen of `M`'s reach (`NotFound` when -it has neither). No server is contacted and no outcome is uncertain. The -long form is `ok, outcome ("disconnected"), store, machine`. +Forgets a PostgreSQL Store in this home with its saved password and its +attachments; the database keeps every byte and `store connect` can record it +again. No server is contacted and no outcome is uncertain. The long form is +`ok, outcome ("disconnected"), store`. Refusals: `InvalidInput` (a sqlite Store: `store remove` deletes one); `InUse` (a Sandbox or Workspace uses the Store, another process holds its lease, or a call in this process is running on it; -[`open.rs`](../../../../control/crates/layerfs-store/src/open.rs)); -`NotFound` (a machine with no address of its own). +[`open.rs`](../../../../control/crates/layerfs-store/src/open.rs)). -### store.save_auth +### store.attach -Save a PostgreSQL login in the home; saving again rotates it. +Let a machine run Sandboxes of a PostgreSQL Store, checked from that machine first. ```text -CLI layerfs store save-auth --user U --password-stdin -Node await layerfs.store.save_auth(auth, { user, password }) -Python layerfs.store.save_auth(auth, *, user, password) +CLI layerfs store attach --machine M +Node await layerfs.store.attach(store, { machine }) +Python layerfs.store.attach(store, *, machine) ``` | Argument | Kind | Rule | | --- | --- | --- | -| `auth` | name | a saved login's name | -| `user` option | text | the PostgreSQL role; required; required | -| `password` option | content | the password; required; the shell reads it from stdin with --password-stdin; required; shell `--password-stdin` | - -| Answer | Keys | -| --- | --- | -| short | `ok` | -| long | `ok, outcome, auth, user, stores, stores_count` | -| call | writes one call-log line; MCP `admin` | - -Saves a PostgreSQL login in the home's secret folder, -`secret/auth/.json` (mode `0600`, in a `0700` folder), and moves the -home's `generation` ([`postgresql/login.rs`](../../../../control/crates/layerfs-store/src/postgresql/login.rs)). -The shell reads the password from stdin with `--password-stdin` and no -other way; Node and Python pass `password`. It is never answered, logged or -traced. Saving again under the same name rotates it: every Store using it -dials with the new one from its next connection. The long form is `ok, -outcome (saved or rotated), auth, user, stores, stores_count`. - -### store.auths - -The saved PostgreSQL logins and the Stores that use each. - -```text -CLI layerfs store auths -Node await layerfs.store.auths() -Python layerfs.store.auths() -``` +| `store` | name | a PostgreSQL Store | +| `machine` option | name | the machine; required | | Answer | Keys | | --- | --- | -| short | `items` | -| long | `items` | -| `items[]` short | `auth`, `user`; when set: `state`, `reason`, `fix`, `stores`, `stores_count` | -| `items[]` long | `auth, user, state, reason, fix, stores, stores_count, created_at, updated_at` | +| short | `ok`, `outcome`; when set: `latency_ms` | +| long | `ok, outcome, store, machine, latency_ms, server_version` | | call | writes one call-log line; MCP `admin` | -The saved logins and the Stores that use each (`stores`, at most 20; -`stores_count` only past 20); never a password. Not paged: a home holds a -handful. The long row adds `created_at` and `updated_at`. A login file that -cannot be read is its own row, `broken` `failed` with the save that writes -it again (`user` null), and the other logins are listed as usual (spec v23). - -### store.remove_auth - -Remove a saved PostgreSQL login no Store uses. +A machine runs Sandboxes of a PostgreSQL Store only once it is attached +([`layerfs-control/src/store.rs`](../../../../control/crates/layerfs-control/src/store.rs) +`attach`). The machine must exist and its platform run PostgreSQL Sandboxes +on this host; the Store is then checked from the machine with the URL and +login this computer saved, as its Sandboxes dial them +([`layerfs-platform/src/reach.rs`](../../../../control/crates/layerfs-platform/src/reach.rs)). +Only after the check succeeds is the machine added to the record's +`attached` list +([`postgresql/check.rs`](../../../../control/crates/layerfs-store/src/postgresql/check.rs) +`attach`) and its reach written to `store//observed.json` +(`reach.`). Attaching an attached machine checks it again: the +outcome is `checked` instead of `attached`, and a failed check is recorded +as its reach while the attachment stays. A machine that reaches the server +only through this computer's loopback is refused with advice to connect the +Store again with an address the machine reaches. `native` is this computer: +it dials as this computer does and is never attached. -```text -CLI layerfs store remove-auth -Node await layerfs.store.remove_auth(auth) -Python layerfs.store.remove_auth(auth) -``` - -| Argument | Kind | Rule | -| --- | --- | --- | -| `auth` | name | a saved login's name | - -| Answer | Keys | +| Refusal | When | | --- | --- | -| short | `ok` | -| long | `ok, outcome, auth` | -| call | writes one call-log line; MCP `admin` | - -Removes a saved login no Store names. Refused `InUse` while a Store names -it (`stores` lists them; the message names `store update --auth` and -`store disconnect`), `NotFound` when there is none. The long form is `ok, -outcome ("removed"), auth`. +| `InvalidInput` | a sqlite Store (`store move` moves one to a machine); `native` | +| `NotFound` | no such Store or machine | +| `Unsupported` | the machine's platform runs no PostgreSQL Sandboxes on this host | +| `Unavailable` | the machine is stopped or does not answer; the server does not answer the machine, or holds another Store | +| `Denied` | the server refuses the login from the machine, or the role lacks a privilege the Store needs | +| `Conflict` | the Store was disconnected or connected again meanwhile | -### store.update +### store.detach -Change a PostgreSQL Store's saved login or its synchronous_commit. +Stop a machine running Sandboxes of a PostgreSQL Store; refused while one runs there. ```text -CLI layerfs store update [--auth A] [--synchronous-commit S] -Node await layerfs.store.update(store, { auth, synchronous_commit }) -Python layerfs.store.update(store, *, auth=None, synchronous_commit=None) +CLI layerfs store detach --machine M +Node await layerfs.store.detach(store, { machine }) +Python layerfs.store.detach(store, *, machine) ``` | Argument | Kind | Rule | | --- | --- | --- | -| `store` | name | a Store name | -| `auth` option | name | another saved login | -| `synchronous_commit` option | text | off, local, remote_write, on or remote_apply | +| `store` | name | a PostgreSQL Store | +| `machine` option | name | the machine; required | | Answer | Keys | | --- | --- | | short | `ok` | -| long | `ok, outcome, store, auth, synchronous_commit` | +| long | `ok, outcome, store, machine` | | call | writes one call-log line; MCP `admin` | -Changes a PostgreSQL Store's saved login or its `synchronous_commit`; at -least one is required ([`postgresql/update.rs`](../../../../control/crates/layerfs-store/src/postgresql/update.rs)). -A new login is checked once from this process on the Store's address, before -it is saved: the server must be reached with it and hold this Store. The -record is written under the home lock and the Store's; this process's open -sessions on it are closed. The login is checked again under the home lock, -which `store remove-auth` takes, and the write drops every field 2.0 no -longer writes (`StoreRecord::without_old_fields`) and never rewrites a URL: -a record keeping a URL that is not an address alone is refused, nothing -written, with the fix that replaces it naming the login given and carrying -a given `--synchronous-commit` (`login::update_fix`). A running Sandbox keeps the -connection it started with. An address change is a `store connect`; a machine's own address is -removed with `store disconnect --machine`. The long form is `ok, outcome -("updated"), store, auth, synchronous_commit`. - -| Refusal | When | -| --- | --- | -| `InvalidInput` | a sqlite Store; nothing to update; a bad `synchronous_commit` | -| `NotFound` | no such Store, or the login is not saved | -| `Unavailable` | the new login does not reach the server, or the database holds another Store | -| `InUse` | a call of this process is running on the Store | -| `Conflict` | the Store was disconnected or connected to another database meanwhile | +Removes the machine from the record's `attached` list and forgets its reach; +no server or machine is contacted. Refused `InUse` while a Sandbox of the +Store's projects is on the machine (the message counts and names them, `next` +lists them, and the `fix` removes them before the detach; +[`inventory.rs`](../../../../control/crates/layerfs-control/src/inventory.rs) +`store_idle_on`), `NotFound` when the machine is not attached, and +`InvalidInput` for a sqlite Store or `native`. The long form is `ok, +outcome ("detached"), store, machine`. ### store.move @@ -678,7 +623,7 @@ Python layerfs.store.doctor(store, *, machine=None, on_progress=None) | Argument | Kind | Rule | | --- | --- | --- | | `store` | name | a Store name | -| `machine` option | name | also probe a PostgreSQL Store's connection from this machine | +| `machine` option | name | check a PostgreSQL Store from this computer and this attached machine only | | `on_progress` option | function | | | Answer | Keys | @@ -692,9 +637,7 @@ Python layerfs.store.doctor(store, *, machine=None, on_progress=None) | call | sends progress; writes one call-log line; MCP `admin` | Checks a Store, then each of its projects shallowly. Its checks, in order: -`store.record` (its record reads and names it; a PostgreSQL record that -alone makes the Store `broken`, `outdated` or `missing`, fails with the `fix` -`store list` gives), `store.operation` (an +`store.record` (its record reads and names it), `store.operation` (an operation whose owner is gone with its outcome unknown is an error whose `fix` is the call that clears it; for a sqlite Store it also reads the compaction record beside the file through its machine), `store.connection` @@ -704,9 +647,12 @@ PostgreSQL Store's server answers this computer with the saved login), schema is this build's) and, for a sqlite Store, `store.backups` (a notice per bucket whose backup heads differ, `fix: layerfs backup create `). No Store data is scanned: `project doctor --full` reads a -project's data. A PostgreSQL Store is then probed from each machine that has -a Sandbox of it and from `--machine`, each as one more `store.connection` -row with `from`; a sqlite Store refuses `--machine`. A Store whose machine +project's data. A PostgreSQL Store reached from this computer is then +checked from every attached machine, or from `--machine` alone, each as one +more `store.connection` row with `from`; when this computer cannot connect, +no machine is checked (each would dial the same URL with the same login). A +`--machine` that is not attached is refused `InvalidInput` with `store attach + --machine ` as its fix; a sqlite Store refuses `--machine`. A Store whose machine is not ready shows `store.connection` as `not_checked` with `blocked_by`, and nothing after it is tried. It changes nothing and exits 0 once its report is made. It replaces the shell's `layerfs doctor store`, removed with no alias. diff --git a/docs/architecture/control/README.md b/docs/architecture/control/README.md index 750473883f..633bffd99b 100644 --- a/docs/architecture/control/README.md +++ b/docs/architecture/control/README.md @@ -74,9 +74,9 @@ machine's worker, or in a Sandbox's daemon. | `store.remove` | records, locks | `store.file` `remove` | — | [`sqlite/remove.rs`](../../../control/crates/layerfs-store/src/sqlite/remove.rs) | | `store.list`, `store.get` | records only; `--with live`: leases and `store.file` `stat`, compaction record and heads, when reached; `--with stats` opens the Store | `store.file` `stat`, when reached | — | [`get.rs`](../../../control/crates/layerfs-store/src/get.rs), [`live.rs`](../../../control/crates/layerfs-store/src/live.rs), [`list.rs`](../../../control/crates/layerfs-store/src/list.rs) | | `store.compact` | the Store's lease; PostgreSQL dials its URL, a sqlite file here rebuilds in this process | `store.compact`: a sqlite file on that machine rebuilds there (spec S6, #42 D5) | — | [`compact.rs`](../../../control/crates/layerfs-store/src/compact.rs) | -| `store.update` | records; a Store's own connection and a `native` check are dialled here | `store.reach`: the machine's own check | — | [`layerfs-control/src/store.rs`](../../../control/crates/layerfs-control/src/store.rs) | +| `store.attach` | records; the Store's address and login are dialled here for a locally executing machine | `store.reach`: the machine's check | — | [`layerfs-control/src/store.rs`](../../../control/crates/layerfs-control/src/store.rs) | | `backup.create` | uploads to the bucket | `store.file` `stage`, `read`, `unstage` | — | [`backup/create.rs`](../../../control/crates/layerfs-store/src/backup/create.rs) | -| `machine.*`, `store.create`, `store.connect`, `store.disconnect`, `backup.connect`, `backup.disconnect`, `backup.list`, `backup.restore` | all of it | — | — | [Machines](machines/README.md), [Backups](backups/README.md) | +| `machine.*`, `store.create`, `store.connect`, `store.disconnect`, `store.detach`, `backup.connect`, `backup.disconnect`, `backup.list`, `backup.restore` | all of it | — | — | [Machines](machines/README.md), [Backups](backups/README.md) | | `sandbox.create`, `sandbox.remove` | records, intent | `sandbox.host` with the internal host ops `sandbox.create` and `sandbox.close` (the worker runs the same host code on its `native`) | started, stopped | [`route.rs`](../../../control/crates/layerfs-sandbox/src/route.rs), [`remove.rs`](../../../control/crates/layerfs-sandbox/src/remove.rs), [`host/call.rs`](../../../control/crates/layerfs-sandbox/src/host/call.rs) | | `workspace.mount`, `commit`, `unmount`, `status` on a forwarded Sandbox | dials the daemon directly | — | serves it | [`direct.rs`](../../../control/crates/layerfs-sandbox/src/direct.rs) | | the same, not forwarded | — (local machine: dials the daemon) | `sandbox.host`; the worker dials the daemon | serves it | `route.rs` | diff --git a/docs/architecture/control/doctor/README.md b/docs/architecture/control/doctor/README.md index fac7b07b31..e785271996 100644 --- a/docs/architecture/control/doctor/README.md +++ b/docs/architecture/control/doctor/README.md @@ -166,16 +166,17 @@ Six checks, in the frozen order (`CHECKS` in `store_target.rs`); no Store data is scanned. A sqlite Store is reached where it lives: in this process for `native`, else through its machine's worker (the internal worker op `store.diagnose` with `cut: schema`, connect 5 s). A PostgreSQL Store is -reached from this computer, then once more from each machine with a Sandbox -of it and from `--machine`, one `store.connection` row each with `from`. +reached from this computer, then, once that reached it, from every machine +attached to it (or `--machine` alone, which must be attached), one +`store.connection` row each with `from`. Under a machine that is not ready only `store.record` is made: the rest are `not_checked`, blocked by the machine. | Check | What is observed | Source | | --- | --- | --- | -| `store.record` | Its record reads and names it, its engine and its id; a PostgreSQL record that alone makes the Store `broken` (no saved login, one the home does not hold, or old fields, V23-6) fails with the `fix` `store list` gives (LF12) | [`store_target.rs`](../../../../control/crates/layerfs-control/src/doctor/store_target.rs) | +| `store.record` | Its record reads and names it, its engine and its id (LF12) | [`store_target.rs`](../../../../control/crates/layerfs-control/src/doctor/store_target.rs) | | `store.operation` | The record's `op`: running passes; one whose owner is gone with its outcome unknown is an error, `fix` the clearing call (`store move `, `store remove `, `store compact `, else `store get --with live`); a stale lease is a notice. For a sqlite Store also the `.compact-op` record beside its file, read through its machine: a live run passes, one left unresolved fails with `fix: layerfs store compact ` | [`store_target.rs`](../../../../control/crates/layerfs-control/src/doctor/store_target.rs), [`intent.rs`](../../../../control/crates/layerfs-store/src/intent.rs) `clearing` | -| `store.connection` | A sqlite Store's file is where its record says, read through its machine; a PostgreSQL Store's server answers with the saved login; connect and login get 5 s, and a server silent past that fails the check, recorded as this computer's reach without a second dial (LF13) | [`store_target.rs`](../../../../control/crates/layerfs-control/src/doctor/store_target.rs) | +| `store.connection` | A sqlite Store's file is where its record says, read through its machine; a PostgreSQL Store's server answers with the Store's user and saved password (a password this home does not hold fails with `layerfs store connect --password-stdin` as its fix); connect and login get 5 s, and a server silent past that fails the check, recorded as this computer's reach without a second dial (LF13) | [`store_target.rs`](../../../../control/crates/layerfs-control/src/doctor/store_target.rs) | | `store.identity` | The id in its file is the one in its record; when it is not, `store.schema` is not made | [`store_target.rs`](../../../../control/crates/layerfs-control/src/doctor/store_target.rs), [`identity.rs`](../../../../control/crates/layerfs-store/src/identity.rs) | | `store.schema` | Its schema is the one this build reads | [`store_target.rs`](../../../../control/crates/layerfs-control/src/doctor/store_target.rs), [`diagnostic.rs`](../../../../control/crates/layerfs-store/src/diagnostic.rs) | | `store.backups` | sqlite only: each bucket link's backup heads against the Store's; one behind is a notice, `fix: layerfs backup create ` | [`store_target.rs`](../../../../control/crates/layerfs-control/src/doctor/store_target.rs) | diff --git a/docs/architecture/control/doctor/findings.md b/docs/architecture/control/doctor/findings.md index 2252f2640f..4351d97677 100644 --- a/docs/architecture/control/doctor/findings.md +++ b/docs/architecture/control/doctor/findings.md @@ -48,9 +48,9 @@ This catalogue lists every check ID emitted by the six LayerFS 2.0 doctors (`hom | Check ID | Failure / Warning Cause | `evidence` Keys (`--detail`) | Remedy (`fix` / Next Step) | Safety | | --- | --- | --- | --- | --- | -| `store.record` | Unreadable record, unsupported engine, or broken PG record (missing/outdated login) | — | `layerfs store save-auth --user --password-stdin && layerfs store update --auth `; for a URL that is not an address alone (never rewritten), the steps that replace it, dialling only the login they name (`layerfs store disconnect && layerfs store connect --auth --synchronous-commit `, or `layerfs store disconnect --machine && layerfs store update --auth && layerfs store connect --machine `); or `layerfs store remove ` | `safe` | +| `store.record` | Unreadable record or unsupported engine | — | `layerfs store remove ` for an unusable sqlite record; `layerfs store disconnect ` then `layerfs store connect --user --password-stdin` for a PostgreSQL one | `safe` | | `store.operation` | Unresolved `op` in home record, stale `.compact-op`, or stale lease | — | `layerfs store compact `, `layerfs store move `, `layerfs store remove `, or `layerfs store get --with live` | `safe` | -| `store.connection` | SQLite file missing/unreadable; or PG auth (`28P01`), transport/TLS, or 5 s silent handshake failure (per-machine probes carry `from`) | `step` (`login`, `transport`, `handshake`, `authentication`) | Rotate login (`layerfs store save-auth`), fix URL (`layerfs store connect `), or restore PostgreSQL server/TLS trust | `safe` | +| `store.connection` | SQLite file missing/unreadable; or PG auth (`28P01`), transport/TLS, or 5 s silent handshake failure (per-machine probes carry `from`) | `step` (`login`, `transport`, `handshake`, `authentication`) | Change the login or URL (`layerfs store connect [--user ] --password-stdin`), attach a machine (`layerfs store attach --machine `), or restore PostgreSQL server/TLS trust | `safe` | | `store.identity` | Database/file binding ID does not match saved record `binding` | — | Reconnect to the intended Store or restore the authoritative Store copy; never delete | `read` | | `store.schema` | Schema version or layout incompatible with this build | — | Use the matching LayerFS build or migrate/restore from backup | `read` | | `store.backups` | SQLite Store heads are ahead of recorded bucket link heads (notice per bucket) | — | `layerfs backup create ` | `safe` | @@ -116,3 +116,5 @@ Executed on disposable homes (`LAYERFS_TEST_TMPDIR` on `ext4`, PostgreSQL `18.6` | 7 | PG `sslmode=require` untrusted cert | `store connect ... --json` | Refusal `Unavailable` (`no connection to the server was made...`, not `Malformed`) | Trust the CA where the Store is dialled: on Linux (OpenSSL) in the system's trusted roots, or name it in `SSL_CERT_FILE` for calls in that process only (a Sandbox's daemon starts with a cleared environment); on macOS (Security framework, which ignores `SSL_CERT_FILE`) trust it in the login or system keychain | Connected `ok: true` | | 8 | Deleted row in `layerfs.object_location` | `project doctor pgs/app --full --detail` | `project.data` (`error`, `coverage: "full"`), names missing 64-hex object ID | Restore from backup / authoritative copy | Verified detection | | 9 | Unreachable/invalid bucket record | `backup doctor b1 --detail` | `bucket.configuration` (`error`) | Reconnect bucket with valid config | Verified detection | + +Rows 4 and 5 are receipts of a run before the 2026-11-24 PostgreSQL redesign and keep the calls it ran (`store save-auth`, `store update --auth`), which are gone: a password is now changed with `layerfs store connect --password-stdin`, and a record without a `user` or a saved password has no state of its own. diff --git a/docs/architecture/control/home/README.md b/docs/architecture/control/home/README.md index baa417444d..8cad85285e 100644 --- a/docs/architecture/control/home/README.md +++ b/docs/architecture/control/home/README.md @@ -39,7 +39,7 @@ says how the first call creates one and why a folder that is not a LayerFS workspace/.json .unmount .unmount-lock workspace//exec/.json one per running command backup//record.json provider, url, prefix, region, access key id - secret//.json 0600: saved logins (auth), bucket keys + secret//.json 0600: PostgreSQL Store passwords (login), bucket keys log/ uncertain.jsonl; leases, exec, repair .jsonl and their .1.jsonl; rotate.lock trace/calls.jsonl the call log; calls.1.jsonl calls.lock @@ -218,7 +218,7 @@ is in the home; a worker's root that holds a sqlite Store's file keeps | Names | Whose | Source | | --- | --- | --- | | `layerfs.json`, `layerfs.lock`, `generation`, `machine/`, `store/`, `sandbox/`, `backup/`, `log/`, `trace/` | LayerFS's: every path it builds in a home starts with one of them | [`home/paths.rs`](../../../../control/crates/layerfs-home/src/home/paths.rs) | -| `secret/` | LayerFS's saved logins and bucket keys, `secret//.json` | [`home/secrets.rs`](../../../../control/crates/layerfs-home/src/home/secrets.rs) | +| `secret/` | LayerFS's PostgreSQL Store passwords (kind `login`) and bucket keys, `secret//.json` | [`home/secrets.rs`](../../../../control/crates/layerfs-home/src/home/secrets.rs) | | `runtime/`, `job/`, `stat/`, `preset/` | an integration's. LayerFS creates none of them; made before the first call they leave the folder a new home ([Opening a home](#opening-a-home)), and neither the home doctor's records scan (four fixed folders) nor a leftover sweep (which never lists the home itself) lists, reads or reports them | [`doctor/scan.rs`](../../../../control/crates/layerfs-control/src/doctor/scan.rs) `scan`, [`sweep.rs`](../../../../control/crates/layerfs-sandbox/src/sweep.rs) | ### The `op` intent @@ -297,7 +297,7 @@ and its prefix | Secret | Where it lives | Source | | --- | --- | --- | -| PostgreSQL password | a saved login (user and password) in `secret/auth/.json` (0600), named by the Store record's `auth`; put into an in-memory URL on each dial. A PostgreSQL record with no `auth` is refused `InvalidInput` with the fix `layerfs store save-auth --user --password-stdin && layerfs store update --auth `; no other password reference is read | [`home/secrets.rs`](../../../../control/crates/layerfs-home/src/home/secrets.rs), [`postgresql/login.rs`](../../../../control/crates/layerfs-store/src/postgresql/login.rs) | +| PostgreSQL password | the Store's password in `secret/login/.json` (0600, `{ password, changed }`), saved by `store connect`; with the record's `user` it is put into an in-memory URL on each dial. A record naming no `user` is refused `InvalidInput`; a password this home does not hold is refused `InvalidInput` with the fix `layerfs store connect --password-stdin`; no other password reference is read | [`home/secrets.rs`](../../../../control/crates/layerfs-home/src/home/secrets.rs), [`postgresql/login.rs`](../../../../control/crates/layerfs-store/src/postgresql/login.rs) | | Bucket key | its id (`access_key`) in `backup//record.json`, its secret in `secret/bucket/.json` (0600); a record with no `access_key` is refused `Failed` with the fix that connects it again | [`backup/record.rs`](../../../../control/crates/layerfs-store/src/backup/record.rs) `credentials`, [`backup/secret.rs`](../../../../control/crates/layerfs-store/src/backup/secret.rs) | | Worker secret | `machine//worker.json` (0600) | [`secrets.rs`](../../../../control/crates/layerfs-home/src/secrets.rs) | | Sandbox daemon keys | `sandbox//control.json` (0600) | same | @@ -305,7 +305,7 @@ and its prefix A copy of a home carries its secrets: every `worker.json` and `control.json`, each started `native` Sandbox's `daemon.setup`, and every -saved login and bucket key in `secret/`. +PostgreSQL Store password and bucket key in `secret/`. ### Moving or copying a home @@ -389,7 +389,7 @@ independent of `LAYERFS_TRACE`. | Lock order is home, start, Store, Sandbox; none is held across a worker call, a VM boot or a byte transfer, except `start.lock` across its start | [`home/lock.rs`](../../../../control/crates/layerfs-home/src/home/lock.rs), [`endpoint.rs`](../../../../control/crates/layerfs-machine/src/endpoint.rs) | | A stale lease (its process gone) is removed under the Store lock by the next lease taker, or by `store.move`, `store.remove` and `store.disconnect`, and logged to `log/leases.jsonl`; reads leave it | [`lease.rs`](../../../../control/crates/layerfs-store/src/lease.rs) | | Only host processes take `layerfs.lock`; a worker's root is never treated as a home | [`home/lock.rs`](../../../../control/crates/layerfs-home/src/home/lock.rs), [`home/guest.rs`](../../../../control/crates/layerfs-home/src/home/guest.rs) | -| A password never reaches a record: `store.connect` refuses a URL that names a user or carries a password; the record names its saved login (`auth`) only | [`postgresql/connect.rs`](../../../../control/crates/layerfs-store/src/postgresql/connect.rs) `refuse_login`, [`postgresql/login.rs`](../../../../control/crates/layerfs-store/src/postgresql/login.rs) | +| A password never reaches a record: `store.connect` refuses a URL that names a user or carries a password; the record keeps the `user` only; the password is a home secret | [`postgresql/connect.rs`](../../../../control/crates/layerfs-store/src/postgresql/connect.rs) `refuse_login`, [`postgresql/login.rs`](../../../../control/crates/layerfs-store/src/postgresql/login.rs) | | A trace or call-log line that cannot be written changes no outcome and is not retried | [`trace.rs`](../../../../control/crates/layerfs-home/src/trace.rs), [`logs.rs`](../../../../control/crates/layerfs-home/src/logs.rs) | | A call-log line is one `write` on a file opened `O_APPEND` and closed, so a long-lived process never writes into a rotated or reset file; nothing is written where `layerfs.json` is absent | [`logs.rs`](../../../../control/crates/layerfs-home/src/logs.rs) | @@ -407,7 +407,7 @@ independent of `LAYERFS_TRACE`. | New `lima` machine name | shorter where Lima's home path is long: Lima refuses an instance whose socket path `//ssh.sock.<16 digits>` is not shorter than 104 characters, so the VM name is at most 76 minus the length of the Lima home (`LIMA_HOME`, else `~/.lima`, links resolved) and the machine name 17 less; else `InvalidInput` stating the longest name that fits on this host | [`lima/limit.rs`](../../../../control/crates/layerfs-platform/src/platforms/lima/limit.rs), [`create.rs`](../../../../control/crates/layerfs-machine/src/create.rs) `provider_room` | | New machine whose VM name another machine has | `Exists`, before any effect: a VM name keeps no punctuation (`a.b` and `a_b` both give `…-a-b`), and the new name is compared with each machine's recorded `vm_name` (a record without one is skipped) | [`create.rs`](../../../../control/crates/layerfs-machine/src/create.rs) `new_name` | | Sandbox name ending in `.root` | `InvalidInput`: `.root` in the run root is another Sandbox's private root | [`create.rs`](../../../../control/crates/layerfs-sandbox/src/create.rs) | -| PostgreSQL Store with no saved login (`auth`) | `InvalidInput`, fix `layerfs store save-auth --user --password-stdin && layerfs store update --auth `; a named login not saved is `NotFound` | [`postgresql/login.rs`](../../../../control/crates/layerfs-store/src/postgresql/login.rs) `dial`, `read` | +| PostgreSQL Store whose password this home does not hold, or whose record names no `user` | `InvalidInput`; the first with the fix `layerfs store connect --password-stdin` | [`postgresql/login.rs`](../../../../control/crates/layerfs-store/src/postgresql/login.rs) `dial`, `read` | | A folder that is not a LayerFS 2.0 home (a `layerfs.json` of another layout, or anything but `layerfs.lock`, the integration folders and `.DS_Store` with no `layerfs.json`) | `Unsupported`, fix `mv .old && layerfs home init`; nothing written ([Opening a home](#opening-a-home)) | [`home/layout.rs`](../../../../control/crates/layerfs-home/src/home/layout.rs) `foreign` | | Call log size | rotates past 16 MiB to the one `calls.1.jsonl` under a non-blocking `flock` on `calls.lock`; `home.clear_log` waits for that lock, truncates in place and removes the rotated file | [`logs.rs`](../../../../control/crates/layerfs-home/src/logs.rs) | | Other log sizes | One rule: past 16 MiB a log moves once to its `.1` name, replacing the one before. `log/*.jsonl` (`leases`, `repair`, and `exec` on the side that keeps the command records): a writer opens, appends one line and closes, and a log then past the size is renamed to `.1.jsonl` under a non-blocking `flock` on `log/rotate.lock`; a writer that does not get the lock skips it. `log/uncertain.jsonl` never rotates: it is the only record of uncertain outcomes. `machine//forward.log` is checked when a forward starts: it is copied to `forward.1.log` and emptied in place, never renamed, since the machine's other forwards hold it open ([forwards](../machines/workers-and-reach.md#forwards)). A machine's `/layerfs/data/log/worker.log` is renamed to `worker.1.log` only when a worker starts, never while one runs ([workers](../machines/workers-and-reach.md#the-workers-log)). A Sandbox's `daemon.log` is new with its run folder and goes with it: it is never rotated and there is no `daemon.1.log` ([Backends](../sandboxes/backends.md#local-one-daemon-process-on-this-kernel)) | [`home/records.rs`](../../../../control/crates/layerfs-home/src/home/records.rs) `log_line`, [`log_file.rs`](../../../../engine/crates/layerfs-bridge/src/log_file.rs), [`setup/forward.rs`](../../../../control/crates/layerfs-platform/src/setup/forward.rs), [`setup/worker.rs`](../../../../control/crates/layerfs-platform/src/setup/worker.rs) `log_start` | diff --git a/docs/architecture/control/machines/platforms.md b/docs/architecture/control/machines/platforms.md index f3ab63a057..cbc452494a 100644 --- a/docs/architecture/control/machines/platforms.md +++ b/docs/architecture/control/machines/platforms.md @@ -205,7 +205,7 @@ One Lima instance (`vmType: vz`, macOS), made from a template written to | docker `start` `Failed` | image not in the Engine (`--pull never`), or no published port (macOS) | same | | `missing: host:macos`, `host:apple-silicon`, `tool:container` | not a Mac, not `aarch64`, no `container` CLI | [`apple_container/adapter.rs`](../../../../control/crates/layerfs-platform/src/platforms/apple_container/adapter.rs) | | apple-container `Failed`: "… inspect answer is not the shape this adapter knows" | another CLI version's JSON | [`apple_container/observe.rs`](../../../../control/crates/layerfs-platform/src/platforms/apple_container/observe.rs) | -| `reach` `Unsupported`: "… its URL names this host's loopback (…), which the machine does not share; give the Store a host the machine reaches (…), or give the machine its own URL with `layerfs store connect --machine `" (or "… names no host (a Unix socket of the caller) …") | a loopback or Unix-socket PostgreSQL URL on docker (Docker Desktop), lima or apple-container | [`reach.rs`](../../../../control/crates/layerfs-platform/src/reach.rs) | +| `reach` `Unsupported`: "… its URL names this host's loopback (…), which the machine does not share; connect the Store again with an address the machine reaches (…): `layerfs store connect `" (or "… names no host (a Unix socket of the caller) …") | a loopback or Unix-socket PostgreSQL URL on docker (Docker Desktop), lima or apple-container | [`reach.rs`](../../../../control/crates/layerfs-platform/src/reach.rs) | | apple-container `Unavailable`: "… a transitional or unrecognized state" | the container is `stopping` (or `unknown`); ask again once it settles, or force the stop | same; [`apple_container/power.rs`](../../../../control/crates/layerfs-platform/src/platforms/apple_container/power.rs) | | `missing: host:macos`, `tool:limactl` | not a Mac, no `limactl` | [`lima/observe.rs`](../../../../control/crates/layerfs-platform/src/platforms/lima/observe.rs) | | lima "… is not an ext4 mount" | the data disk did not attach as ext4 | [`lima/power.rs`](../../../../control/crates/layerfs-platform/src/platforms/lima/power.rs) | diff --git a/docs/architecture/control/machines/workers-and-reach.md b/docs/architecture/control/machines/workers-and-reach.md index 86139340d6..334cc65b6d 100644 --- a/docs/architecture/control/machines/workers-and-reach.md +++ b/docs/architecture/control/machines/workers-and-reach.md @@ -174,7 +174,7 @@ waits at most 10 s; other operations wait as long as they run | `store.call` | one Store method on `store//store.sqlite` under the root, holding the Store's lease there | | `store.compact` | one sqlite Store's compaction on `store//store.sqlite` under the root, holding the Store's lease there; `{ store, store_record }`, each phase sent as a `progress` event; an event that cannot be written does not end the run (spec S6, #42 D5) | | `store.file` | one step of a `store.move` (either direction), `store.remove`, stat or backup, with `progress` events for hashing steps | -| `store.reach` | the check of this machine's connection to a PostgreSQL Store, for `store.update --machine` | +| `store.reach` | the check of this machine's connection to a PostgreSQL Store with the address and login the host saved, for `store.attach` | | `store.diagnose`, `doctor.sandbox` | doctor's read-only observations | | `network.inspect` | doctor's read-only observation of the machine's Sandbox network for `machine.network`: `{ table, forwarding, links: [{ link, addresses, sandbox }] }`, `sandbox` the recorded Sandbox the link is named for, or null | | `sandbox.host` | a Sandbox or Workspace host operation on the machine's own `native`, decoded into its typed request first; a `sandbox.create` sweeps the run root first ([Checks: leftovers](../doctor/checks.md#leftovers)) | @@ -293,9 +293,9 @@ part of the URL but a loopback host. Each adapter declares its `Loopback`. a host empty, or a path (a Unix socket) ----------> Unsupported + advice a host is this host's loopback -------------------> Unsupported + advice else ---------------------------------------------> url as given - advice: "give the Store a host the machine reaches (), or give - the machine its own URL with `layerfs store connect - --machine `", the Store and machine named + advice: "connect the Store again with an address the machine reaches + (): `layerfs store connect `", the + Store named ``` | Platform | `Loopback` | The refusal names | @@ -313,7 +313,7 @@ part of the URL but a loopback host. Each adapter declares its `Loopback`. | TLS | No host is rewritten, so a certificate's name still matches. The client reads `sslmode` `disable`, `prefer` or `require` only, and `require` verifies the server's certificate chain and host name (the engine's `native-tls` connector, with its defaults); `verify-full`, `verify-ca`, `sslrootcert`, `sslcert` and `sslkey` are refused at `store connect` (`refuse_login`, naming the one met) and never dialled | `reach.rs`; [`address.rs`](../../../../control/crates/layerfs-store/src/postgresql/address.rs) `refuse_login` | | A name resolving to loopback | Not resolved to be refused: a hosts entry that maps a name to 127.0.0.1 on the machine fails at its one dial (the create's reach check, `store.reach`, the create's daemon), and that failure carries the refusal's advice (`loopback_hint`, sent to the worker as `reach_hint`). The hint is added only on an `Apart` machine, only when the URL names at least one host by name and gives no `hostaddr` (an address is read, never resolved, every loopback one was refused, and with a `hostaddr` the client dials that address alone, `url_hostaddr`), and only when no connection was made (`not_connected`: the client's `error connecting to server` or `timeout waiting for server`, a silent dial, the session's `no connection to the server was made`; for a create's daemon, its last line saying `cannot reach PostgreSQL Store`, read by `launch/local.rs` `unreached`), never when the server answered (a refused login, a missing database, any error it sent). One attempt: nothing redials | [`setup/calls.rs`](../../../../control/crates/layerfs-platform/src/setup/calls.rs) `loopback_hint`, [`open.rs`](../../../../control/crates/layerfs-store/src/postgresql/open.rs) `not_connected`, [`route.rs`](../../../../control/crates/layerfs-sandbox/src/route.rs) `reach_check`, [`layerfs-control/src/store.rs`](../../../../control/crates/layerfs-control/src/store.rs) `from_machine`, [`launch/local.rs`](../../../../control/crates/layerfs-sandbox/src/launch/local.rs) `unreached` | | Names in the Sandbox | A `namespaces` Sandbox resolves names with its machine's resolver files, bound into its root at start ([Backends](../sandboxes/backends.md)); a remote host is reached through the machine's own NAT and DNS | [`helper mounts.rs`](../../../../control/crates/layerfs-sandbox-backend/src/bin/layerfs-sandbox-helper/mounts.rs) `resolver` | -| Per call | Only the operations that dial the Store's URL on their side build it in the caller (`Op::store_url`): `sandbox.create` (its daemon and reach check), Commit (its Branch's head and `expected`) and a Workspace status (its head). The worker process reads the Store per call, and the password travels only in that one request; building it is a record read and this check, no provider command. A close resolves it only to end the mount intents a forced unmount left. It runs without it only when the machine cannot dial it (`platform::reach` refuses it): its side then hands the intents bound by id back in `ending`, and the caller, where PostgreSQL Store calls run, ends each once with the Store's own URL (`mount_intents::end_handed`); one not ended is a `left` sentence. Any other failure to build it (a saved login that is gone, a Store naming none, an unreadable machine record) refuses the close with its own message and fix, forced or not. The handed intents live only in the close's answer: a lost answer (`Unknown`), a failed removal of the Sandbox's folder after stop and delete (`Failed`) or a caller that ends before `end_handed` leaves them, and a retried remove answers `AlreadyGone` with an empty `left` (S1 of the 3cf2cfc246 review; no record holds them). Every other operation (`sandbox.get`'s reads, mount, exec, cancel, unmount) asks only the Sandbox's daemon, which dials the URL its create gave it, and never reads the URL: a Sandbox whose URL its machine cannot dial can always be read and removed, while a missing or unnamed saved login refuses its close | [`route.rs`](../../../../control/crates/layerfs-sandbox/src/route.rs) `host_op`, `in_worker`; [`host/call.rs`](../../../../control/crates/layerfs-sandbox/src/host/call.rs) `store_url`; [`lifecycle.rs`](../../../../control/crates/layerfs-sandbox/src/lifecycle.rs) `close`; [`mount_intents.rs`](../../../../control/crates/layerfs-sandbox/src/mount_intents.rs) `end_handed` | +| Per call | Only the operations that dial the Store's URL on their side build it in the caller (`Op::store_url`): `sandbox.create` (its daemon and reach check), Commit (its Branch's head and `expected`) and a Workspace status (its head). The worker process reads the Store per call, and the password travels only in that one request; building it is a record read and this check, no provider command. A close resolves it only to end the mount intents a forced unmount left. It runs without it only when the machine cannot dial it (`platform::reach` refuses it): its side then hands the intents bound by id back in `ending`, and the caller, where PostgreSQL Store calls run, ends each once with the Store's own URL (`mount_intents::end_handed`); one not ended is a `left` sentence. Any other failure to build it (a password this home does not hold, a record naming no user, an unreadable machine record) refuses the close with its own message and fix, forced or not. The handed intents live only in the close's answer: a lost answer (`Unknown`), a failed removal of the Sandbox's folder after stop and delete (`Failed`) or a caller that ends before `end_handed` leaves them, and a retried remove answers `AlreadyGone` with an empty `left` (S1 of the 3cf2cfc246 review; no record holds them). Every other operation (`sandbox.get`'s reads, mount, exec, cancel, unmount) asks only the Sandbox's daemon, which dials the URL its create gave it, and never reads the URL: a Sandbox whose URL its machine cannot dial can always be read and removed, while a password this home does not hold refuses its close | [`route.rs`](../../../../control/crates/layerfs-sandbox/src/route.rs) `host_op`, `in_worker`; [`host/call.rs`](../../../../control/crates/layerfs-sandbox/src/host/call.rs) `store_url`; [`lifecycle.rs`](../../../../control/crates/layerfs-sandbox/src/lifecycle.rs) `close`; [`mount_intents.rs`](../../../../control/crates/layerfs-sandbox/src/mount_intents.rs) `end_handed` | `url_hosts` keeps no userinfo and nothing here puts any part of the URL in a message but a host diff --git a/docs/architecture/control/stores-and-projects/README.md b/docs/architecture/control/stores-and-projects/README.md index 12aad32676..a35e0ecb63 100644 --- a/docs/architecture/control/stores-and-projects/README.md +++ b/docs/architecture/control/stores-and-projects/README.md @@ -26,7 +26,7 @@ this process has open, and moves or removes a sqlite Store's file. lease::claim under store//lock | +-- StoreRef::Postgres --> this process: URL from the record, - | its saved login (auth) put in now + | its user and saved password put in now | +-- StoreRef::Sqlite --> place::plan(machine) | | @@ -73,7 +73,7 @@ full per-call table is "Where each call runs" in [Control](../README.md). | `create` | sqlite | empty Store on `native`; `Exists` if named | [`sqlite/create.rs`](../../../../control/crates/layerfs-store/src/sqlite/create.rs) | | `move` | sqlite | moves the file between `native` and a machine (1.x and the 2.0 previews: `push`, `pull`) | [SQLite and PostgreSQL](sqlite-and-postgresql.md#transfer-sqlitetransfer) | | `remove` | sqlite | delete the file wherever it is, with its projects; PostgreSQL `InvalidInput` | [`sqlite/remove.rs`](../../../../control/crates/layerfs-store/src/sqlite/remove.rs) | -| `connect`, `disconnect`, `update`, `save_auth`, `auths`, `remove_auth` | PostgreSQL | record or forget a database (with `machine`, one machine's own address); change its login or `synchronous_commit`; keep named logins in the home's secret folder | [SQLite and PostgreSQL](sqlite-and-postgresql.md#postgresql-postgresql) | +| `connect`, `disconnect`, `attach`, `detach` | PostgreSQL | record a database with its login (the password in the home's secret folder) or change its address, login or `synchronous_commit`; forget it; let a machine run its Sandboxes, checked from that machine, or stop it | [SQLite and PostgreSQL](sqlite-and-postgresql.md#postgresql-postgresql) | ### Multi-step operations diff --git a/docs/architecture/control/stores-and-projects/sqlite-and-postgresql.md b/docs/architecture/control/stores-and-projects/sqlite-and-postgresql.md index 41efbbc7e3..0b0bf5c290 100644 --- a/docs/architecture/control/stores-and-projects/sqlite-and-postgresql.md +++ b/docs/architecture/control/stores-and-projects/sqlite-and-postgresql.md @@ -3,8 +3,8 @@ > **Status:** Current architecture guide for LayerFS 2.0.0; maintained with the source. The two Store kinds' own calls: a sqlite Store's file created, moved and -removed across machines, and a PostgreSQL database connected, updated, -checked from a machine and opened, within [Stores and projects](README.md). +removed across machines, and a PostgreSQL database connected with its +login, attached to machines and opened, within [Stores and projects](README.md). | | | | --- | --- | @@ -78,8 +78,12 @@ another operation holds the Store ## PostgreSQL (`postgresql/`) +This computer is the one place a PostgreSQL Store's address and login are +saved (owner, 2026-11-24). Machines are attached to the Store and dial with +both; no machine has an address or a login of its own. + ```text - store.connect(name, url, {auth, synchronous_commit}) + store.connect(name, url, {user, password, synchronous_commit}) refuse_login(url) not an address alone, as the client reads it: any `@` or `#`, a user or a password, a URL it does not read @@ -87,67 +91,47 @@ another operation holds the Store verify-full, sslrootcert), `&` or `#` before a key in its host, database or a value (db&password=) -> InvalidInput - auth required, and saved (`store save-auth`): - else InvalidInput / NotFound - synchronous_commit off | local (default) | remote_write | on - | remote_apply, else InvalidInput - Exists? same name, or (once read) same schema + no record new: user and password required, else + InvalidInput; synchronous_commit off | + local (default) | remote_write | on | + remote_apply, else InvalidInput + Exists? same name, or (once read) same schema binding, whatever address or login - schema `layerfs` empty database: create it, new binding; + schema `layerfs` empty database: create it, new binding; existing: read its binding - projects in the schema --> project records; record written under - the home lock (re-checked) + projects in the schema --> project records; record written under + the home lock (re-checked), then the + password saved outcome connected + sqlite record Exists + PostgreSQL record update: user/password given or saved; the + server must hold the same binding; record + and password written outcome updated ``` | Call | Does | Refusals | Source | | --- | --- | --- | --- | -| `store.connect` | records the database as a Store in the fixed `layerfs` schema: the URL exactly as given (an address alone: no user or password), schema, `synchronous_commit`, its saved login `auth`, binding, a cursor key of this home's own, no machine. On a connected Store the URL becomes the address every machine dials (`readdress`); with `--machine ` it is that machine's own, `machines.: {url}`, checked from the side that dials (this process, or the worker's `store.reach`): the server answers, its schema holds this Store, and the role has what a Sandbox's reads and writes need (the schema's `USAGE` and `CREATE`, the database's `TEMP`, each table's and sequence's privileges; never what only a compaction needs, which `store compact` checks itself), and the machine's platform must run PostgreSQL Sandboxes. Both refuse `--auth` and `--synchronous-commit` | `InvalidInput`, `Exists`, `NotFound` (no such saved login), `Unavailable`, `Unsupported` (`--machine` on a platform that runs no PostgreSQL Sandbox), `Denied`, `Conflict` | [`connect.rs`](../../../../control/crates/layerfs-store/src/postgresql/connect.rs), [`layerfs-control/src/store.rs`](../../../../control/crates/layerfs-control/src/store.rs) `connect` | -| `store.disconnect` | forgets the Store; its data stays. With `--machine `, removes that machine's own address, which then dials the Store's, and forgets its reach | `InvalidInput` for sqlite (`store remove`); `InUse` while leased or a Sandbox uses it; `NotFound` when the machine has neither an address of its own nor a reach | same | -| `store.update {auth, synchronous_commit}` | another saved login or `synchronous_commit` (one is required); a new login is checked once from this process on the Store's address, which must hold this Store, and saved again under the home lock; the write drops old fields (`StoreRecord::without_old_fields`) and never rewrites a URL: a record keeping a URL that is not an address alone is refused with its fix, nothing written (`login::update_fix`) | `InvalidInput`; `Unavailable` (not reached, or another Store's schema); `Conflict` if the record changed meanwhile | [`update.rs`](../../../../control/crates/layerfs-store/src/postgresql/update.rs) | +| `store.connect` | records the database as a Store in the fixed `layerfs` schema: the URL exactly as given (an address alone: no user or password), `user`, schema, `synchronous_commit`, binding, a cursor key of this home's own, no machine; the password goes to the home's secrets as kind `login` under the Store's name. On a connected Store it changes the address, user, password or `synchronous_commit`, an omitted user or password keeping the saved one; the result is checked from this process against the same binding before the record and password are written, and the Store's open connections in this process are closed | `InvalidInput`, `Exists`, `Unavailable`, `Denied`, `Conflict` | [`connect.rs`](../../../../control/crates/layerfs-store/src/postgresql/connect.rs), [`layerfs-control/src/store.rs`](../../../../control/crates/layerfs-control/src/store.rs) `connect` | +| `store.disconnect` | forgets the Store, its saved password and its attachments; its data stays | `InvalidInput` for sqlite (`store remove`); `InUse` while leased or a Sandbox uses it | same | +| `store.attach --machine ` | checks the Store from the machine with the saved URL and login (in this process on a locally executing machine, else through the worker's `store.reach`): the server answers, its schema holds this Store, and the role has what a Sandbox's reads and writes need (the schema's `USAGE` and `CREATE`, the database's `TEMP`, each table's and sequence's privileges; never what only a compaction needs, which `store compact` checks itself); the machine's platform must run PostgreSQL Sandboxes. Only then is `` added to the record's `attached` list and its reach recorded; an attached machine is checked again (`checked`) | `InvalidInput` (sqlite, `native`), `NotFound`, `Unsupported`, `Unavailable`, `Denied`, `Conflict` | [`check.rs`](../../../../control/crates/layerfs-store/src/postgresql/check.rs) `attach`, [`layerfs-control/src/store.rs`](../../../../control/crates/layerfs-control/src/store.rs) `attach` | +| `store.detach --machine ` | removes `` from `attached` and forgets its reach, under the home lock and the Store's, once no Sandbox of the Store's projects is on it | `InUse` (counted and named, with the removals as `fix`), `NotFound` (not attached), `InvalidInput` | [`check.rs`](../../../../control/crates/layerfs-store/src/postgresql/check.rs) `detach`, [`inventory.rs`](../../../../control/crates/layerfs-control/src/inventory.rs) `store_idle_on` | | Store calls | open the schema in this process with the URL resolved now | — | [`open.rs`](../../../../control/crates/layerfs-store/src/postgresql/open.rs) | | Host read session | one read-only session per process for Sandbox host operations: a create's reach check and a status's head read, on every route; opened with the light check on first read, checked with one empty query before each use (a dead one is replaced, not retried), closed after 60 s unused | — | [`reader.rs`](../../../../control/crates/layerfs-store/src/postgresql/reader.rs) | -A PostgreSQL Store is on no machine. Its Sandboxes run on every machine -whose platform runs PostgreSQL Sandboxes (#536 C4), and `sandbox.create` -checks from the machine that it reaches this Store, so no call comes -between `store.connect` and the first Sandbox. `machines` holds only the -machines with a connection of their own (H9). A record holding what 2.0 no -longer writes (a `password`, a URL that is not an address alone, a -`machines.` entry without `url` or with more, such as an old `checked`) -reads `broken` `outdated` (`StoreRecord::outdated_fields`) with a fix the -user runs; nothing migrates it (owner, 2026-11-19: no backward -compatibility in 2.0). A URL is never cleaned, stripped or rewritten (the -e0aa26e149 review's Decision, owner-confirmed 2026-11-24: five rounds of a grammar -of LayerFS's own each mishandled a new shape). A record keeps a URL that -may hold a login, and any password in it, on disk byte for byte until its -fix runs (the one exception to "no password in a Store record", for -records written before 2.0's rules); only a connect of an address alone -replaces it. The fixes (`login::fix_of`, `login::update_fix`) dial only -with the login they name, never with the one the record names, so they -work when that login no longer authenticates, and name the address -`` and the user ``, never text of a URL: - -| The record | Its fix | -| --- | --- | -| only old fields, every URL an address alone | `store update --auth ` (the record's own login, or `` with `save-auth` first when it names none or one not saved); its write drops them (`StoreRecord::without_old_fields`) | -| a machine's own URL is not an address alone | `store disconnect --machine ` (dials nothing) `&& store update --auth && store connect --machine ` (checked from that machine, which must be running and run PostgreSQL Sandboxes) | -| the Store's URL is not an address alone | `store disconnect && store connect --auth --synchronous-commit `, then `store connect --machine ` for every machine with an address of its own: the Store is forgotten and connected again (its data stays; refused `InUse` while a Sandbox of it exists; its projects are found again, while its backup links and reach observations are not kept) | - -The `outdated` fix names `` when it replaces a URL (the record's own -login, which `store get` names, or another that authenticates). `store -update --auth ` (or `--synchronous-commit` alone) refuses a record -keeping a URL that is not an address alone and writes nothing; its fix is -the one above naming `` and carrying a given `--synchronous-commit` -(review e0aa26e149 S3 and N1). A `store connect` refused for a URL holding -a login names the saved login first: `save-auth --user ---password-stdin`, then on a connected Store the steps above that leave it -naming `` (`store update --auth ` when every URL is an -address alone), then `store connect ` (`--machine `) unless a -step already connects it (`login::login_fix`). No write but `store -update` drops an old field, and none rewrites a URL: `store connect` -writes the address given, `store connect --machine`, `store disconnect ---machine` and `machine remove` change only that machine's entry -(`StoreRecord::with_own_connection`), every other entry byte for byte. +A PostgreSQL Store is on no machine. Its Sandboxes run on `native` and on +every attached machine whose platform runs PostgreSQL Sandboxes (#536 C4); +`sandbox.create` on a machine that is not attached is refused +`InvalidInput` with `layerfs store attach --machine ` as its fix, and +on an attached one still checks from the machine that it reaches this Store. +A record is read as it is: there is no migration and no state for a record +written by an earlier build (owner, 2026-11-19 and 2026-11-24: no backward +compatibility in 2.0). A record without the fields above fails through the +normal path: a call that dials it needs its `user` and the saved password +(`login::dial`), and is refused `InvalidInput` with `layerfs store connect + --password-stdin` as its fix when this home holds none. A URL is +never cleaned, stripped or rewritten (the e0aa26e149 review's Decision, +owner-confirmed 2026-11-24): `store connect` writes the address given, and +`store attach`, `store detach` and `machine remove` change only the +`attached` list. A Store's URL is read only as its client reads it ([`postgresql/address.rs`](../../../../control/crates/layerfs-store/src/postgresql/address.rs), @@ -172,52 +156,48 @@ part of a host, database or value and that names no login key is the client's: `postgres://h/db&sslmode=require` is the database `db&sslmode=require`, accepted, and refused by the server if there is no such database. -`machine.remove` forgets the machine's entry and its reach in every Store. +`machine.remove` detaches the machine from every Store and forgets its reach. -### Who connects (spec v23) +### Who connects What was seen when a side dialled the database is kept beside the record, in `store//observed.json` with the `at` a live read writes: `here` (this computer) and `reach.`, each `{ at, ok, latency_ms, server_version, error }` ([`observed.rs`](../../../../control/crates/layerfs-store/src/observed.rs)). -Writers: `store.connect --machine` (its check), `store.doctor` (this -computer, measured with the same check, then every machine with an address -of its own, a Sandbox, or `--machine`) and a Sandbox create on a machine -(`{ at, ok: true }`, on the host after the reply, -[`route.rs`](../../../../control/crates/layerfs-sandbox/src/route.rs) -`reach`). `native` with no address of its own dials as this computer and is -recorded as `here`. A writer runs after its Store I/O, under the Store's -lock, and writes nothing once the record is gone; a write never fails its -call and moves no `generation`. `connect.rs` `connections` reads it back: -this computer, then every machine with an address of its own, a reach or a -Sandbox (handed in by `layerfs-control`), each `{ machine, url, own, server, -reached, reach }`. Nothing converts a sqlite Store into PostgreSQL: a project -reaches PostgreSQL only by an Init into it. +Writers: `store.attach` (its check), `store.doctor` (this computer, measured +with the same check, then every attached machine, or `--machine` alone) and +a Sandbox create on a machine (`{ at, ok: true }`, on the host after the +reply, [`route.rs`](../../../../control/crates/layerfs-sandbox/src/route.rs) +`reach`). `native` dials as this computer and is recorded as `here`. A +writer runs after its Store I/O, under the Store's lock, and writes nothing +once the record is gone; a write never fails its call and moves no +`generation`. `connect.rs` reads it back: `reach` (this computer's) and +`machines`, one `{ machine, reached, reach }` per attached machine +(`store get`; `store list` and `home get --with tree` give the names). +Nothing converts a sqlite Store into PostgreSQL: a project reaches +PostgreSQL only by an Init into it. ### Credentials -A PostgreSQL Store's record names a saved login (`auth`), which -`postgresql/login.rs` `dial` puts into the address it dials -(`address::with_login`); a machine's own address (`machines..url`) is -dialled with the same login. Only an address alone is dialled -(`refuse_login`, below); a recorded URL that is not one (an older -record's) is refused `InvalidInput` with the record's fix, never dialled. -`with_login` reads the URL it makes back with the client and refuses it, -undialled, unless the client reads exactly the saved user and password and -the address's hosts, host addresses, ports and database. A record that names no `auth` (written before -saved logins) is `broken` `outdated`, and every call that dials it is -refused `InvalidInput` with the fix `layerfs store save-auth --user - --password-stdin && layerfs store update --auth `; its -old `password` reference is not read. A record naming a login the home does -not hold is `broken` `missing` with the save of that login and the same -update as its fix -([`postgresql/login.rs`](../../../../control/crates/layerfs-store/src/postgresql/login.rs) -`dial`, `no_auth_fix`; [`state.rs`](../../../../control/crates/layerfs-store/src/state.rs)). +A PostgreSQL Store's record holds its `user`; its password is a home secret +of kind `login` under the Store's name (`secret/login/.json`, +`{ password, changed }`, mode `0600` in a `0700` folder; +[`login.rs`](../../../../control/crates/layerfs-store/src/postgresql/login.rs)). +`login::dial` puts both into the address it dials (`address::with_login`), +from this computer and for every attached machine alike. Only an address +alone is dialled (`refuse_login`, below). `with_login` reads the URL it +makes back with the client and refuses it, undialled, unless the client +reads exactly the user and password and the address's hosts, host +addresses, ports and database. A record that names no `user` is refused +`InvalidInput` naming the missing field; a password this home does not hold +is refused `InvalidInput` with `layerfs store connect +--password-stdin` as its fix (`login::password_fix`). `store get` answers +`password_saved` and `password_changed_at`, never the password. ```text - Store record: url postgres://h/db auth - secret/auth/.json: user, password (0600) + Store record: url postgres://h/db user attached [m, ...] + secret/login/.json: password, changed (0600) | each call, in the caller only v address::with_login -> :@h/db (memory, @@ -233,7 +213,7 @@ update as its fix | Rule | Source | | --- | --- | -| The login is a saved one, and only an address alone is dialled or recorded: `refuse_login` refuses `InvalidInput` a URL that holds a login (`holds_login`, above: an `@`, a user or password the client reads, a login key and `=`, or one the client does not read, such as an unknown key like `passfile`, `sslpassword`, `sslrootcert`, `sslkey` or `sslcert`, an `sslmode` other than `disable`, `prefer` or `require`, or a bad value) or holding a `#` (the client reads it as text, other readers end the URL there); an `@` or `#` of the address itself is written `%40` or `%23`, which the client decodes. A refusal of a URL the client does not read names what it refuses only by a key or value from fixed lists (`sslmode=verify-full`, `sslrootcert`, the value of `port`), never by other URL text (a value the client would read but for a `#` in it, `sslmode=require#f`, is named by that `#`; `sslrootcert` adds where a private CA is trusted: on Linux, where `native-tls` is OpenSSL, in the system's trusted roots, or in `SSL_CERT_FILE`, which `openssl-probe` reads in the process that dials only: a Sandbox's daemon starts with a cleared environment; on macOS, where it is the Security framework, which reads no such variable, in the login or system keychain); `sslmode=require` verifies the server's certificate chain and host name (the engine's `native-tls` connector, with its defaults), so `verify-ca` and `verify-full` are refused rather than dialled; any refusal of a URL holding a `#` names `%23`. The refusal's fix (`refuse_login_with_fix`) names `` and ``, never URL text: a URL that holds a login gets `save-auth` + `--auth` on a first connect, and on a connected Store `save-auth` and the steps that name the saved login before the address alone (`login::login_fix`); one refused only for a `#` holds no login, so its fix is the connect of the address alone, saving none. A named login not saved is `NotFound`, one with no user or password `Failed` | [`postgresql/address.rs`](../../../../control/crates/layerfs-store/src/postgresql/address.rs), [`postgresql/connect.rs`](../../../../control/crates/layerfs-store/src/postgresql/connect.rs), [`postgresql/login.rs`](../../../../control/crates/layerfs-store/src/postgresql/login.rs) `read` | +| The login is a saved one, and only an address alone is dialled or recorded: `refuse_login` refuses `InvalidInput` a URL that holds a login (`holds_login`, above: an `@`, a user or password the client reads, a login key and `=`, or one the client does not read, such as an unknown key like `passfile`, `sslpassword`, `sslrootcert`, `sslkey` or `sslcert`, an `sslmode` other than `disable`, `prefer` or `require`, or a bad value) or holding a `#` (the client reads it as text, other readers end the URL there); an `@` or `#` of the address itself is written `%40` or `%23`, which the client decodes. A refusal of a URL the client does not read names what it refuses only by a key or value from fixed lists (`sslmode=verify-full`, `sslrootcert`, the value of `port`), never by other URL text (a value the client would read but for a `#` in it, `sslmode=require#f`, is named by that `#`; `sslrootcert` adds where a private CA is trusted: on Linux, where `native-tls` is OpenSSL, in the system's trusted roots, or in `SSL_CERT_FILE`, which `openssl-probe` reads in the process that dials only: a Sandbox's daemon starts with a cleared environment; on macOS, where it is the Security framework, which reads no such variable, in the login or system keychain); `sslmode=require` verifies the server's certificate chain and host name (the engine's `native-tls` connector, with its defaults), so `verify-ca` and `verify-full` are refused rather than dialled; any refusal of a URL holding a `#` names `%23`. The refusal's fix (`connect::refuse_url`) names `` and ``, never URL text: a URL that holds a login gets `layerfs store connect --user --password-stdin` on a first connect or when it holds a login, and one refused only for a `#` on a connected Store gets the connect of the address alone. A password not saved is `InvalidInput` with `login::password_fix` | [`postgresql/address.rs`](../../../../control/crates/layerfs-store/src/postgresql/address.rs), [`postgresql/connect.rs`](../../../../control/crates/layerfs-store/src/postgresql/connect.rs), [`postgresql/login.rs`](../../../../control/crates/layerfs-store/src/postgresql/login.rs) `dial` | | Every byte of the user and password outside `A-Z a-z 0-9 - . _ ~` is percent-encoded | [`postgresql/address.rs`](../../../../control/crates/layerfs-store/src/postgresql/address.rs) `percent` | | Put in again on each call; the full URL is never written to a record, log, trace or `Debug` output | same; [`host/frame.rs`](../../../../control/crates/layerfs-sandbox/src/host/frame.rs) `decode` | | The daemon runs `--config `; the setup is in neither its arguments nor its environment; `DaemonStore` prints `url` as `[redacted]` | [`local/create.rs`](../../../../control/crates/layerfs-sandbox-backend/src/local/create.rs), [`store.rs`](../../../../engine/crates/layerfs-bridge/src/store.rs) | diff --git a/docs/versioned/2.0.0/calls.md b/docs/versioned/2.0.0/calls.md index 5e0335de6d..f10ddbc379 100644 --- a/docs/versioned/2.0.0/calls.md +++ b/docs/versioned/2.0.0/calls.md @@ -9,8 +9,8 @@ one file per call under its family in help, and the Node and Python functions are all built from that table, so the three front ends take the same arguments. -There are 83 calls in ten families: `home` 5, `project` 8, `branch` 6, -`commit` 3, `file` 14, `sandbox` 7, `workspace` 7, `machine` 14, `store` 13 +There are 81 calls in ten families: `home` 5, `project` 8, `branch` 6, +`commit` 3, `file` 14, `sandbox` 7, `workspace` 7, `machine` 14, `store` 11 and `backup` 6. `layerfs help` lists them, `layerfs help []` prints one family or one call, and `layerfs help --json` prints the whole table (each call's arguments and the form of its answer). Outside the table @@ -236,14 +236,14 @@ $ echo $? platform`; Store `store, engine`; Sandbox `sandbox, project`; bucket `bucket, provider`), then what is news: its state only when it is not `ready`, a machine's `cpus` and `memory_bytes`, a Store's `projects` and - `connections`, a Sandbox's `image`, `workspaces` (each `{ workspace, + `machines`, a Sandbox's `image`, `workspaces` (each `{ workspace, branch }`) and `workspaces_not_listed`. The long forms are: machine `machine, platform, cpus, memory_bytes, state, op, reason, fix, stores, - sandboxes`; Store `store, engine, projects, connections, state, op, + sandboxes`; Store `store, engine, projects, machines, state, op, blocked_by, reason, fix`; Sandbox `sandbox, project, image, workspaces, workspaces_not_listed, state, op, blocked_by, reason, fix`; bucket - `bucket, provider`. A PostgreSQL Store's `connections` are `store get`'s - rows (every side that connects, below); a sqlite Store's are null. A Workspace is in the home's + `bucket, provider`. A PostgreSQL Store's `machines` are the names of + the machines attached to it (below); a sqlite Store's are null. A Workspace is in the home's records only on `native` and for a Sandbox reached directly: any other Sandbox answers `workspaces` null and `workspaces_not_listed: true`. A Store or Sandbox whose machine is stopped, busy or broken is `blocked`, and `blocked_by` names that machine. A machine that @@ -886,8 +886,8 @@ alias: `sandbox.close` (now `remove`) and `logs.sandbox` (now `log`); the them: if that answer is lost (`Unknown`), the machine cannot remove the Sandbox's folder after stopping it (`Failed`), or the caller ends before it ends them, they stay, and a retried remove answers `already_gone` - with an empty `left`. A missing or unnamed saved login refuses the - remove, forced or not, with its fix. One it could not end (its Store could not be + with an empty `left`. A PostgreSQL Store whose password this home does + not hold refuses the remove, forced or not, with its fix. One it could not end (its Store could not be opened, say) is a sentence of `left` that says why: `branch remove` of its Branch and `store compact` are refused while it remains, and only the Store's admission ends it later, once it can prove the owner gone (for a @@ -1277,19 +1277,17 @@ See [machines](machines-and-stores.md#machines) for kinds, defaults and refusals, and [removed platforms](machines-and-stores.md#removed-platforms-firecracker-microsandbox-and-ssh). -### `store` (13) +### `store` (11) | Call | Positionals | Options | Does | | --- | --- | --- | --- | | `list` | — | `machine`, `--with stats` | every Store, from the home's records | | `get` | `store` | `--with live,stats` | a Store's record and state; with `--with`, read where it lives or opened for its counters | | `create` | `name` | `machine` | an empty sqlite Store, on this computer or made on `machine` directly | -| `connect` | `store`, `url` | `auth`, `machine`, `synchronous_commit` (`local`) | connects a PostgreSQL database as a Store with a saved login; on a connected Store, sets its address, or with `machine` that machine's own (checked from it first) | -| `disconnect` | `store` | `machine` | forgets a PostgreSQL Store, its data staying; with `machine`, removes only that machine's own address | -| `save_auth` | `auth` | `user`, `password` (both required; `--password-stdin`) | saves or replaces a PostgreSQL login in the home's secret folder | -| `auths` | — | — | the saved logins and the Stores that use each; never a password | -| `remove_auth` | `auth` | — | deletes a saved login no Store uses | -| `update` | `store` | `auth`, `synchronous_commit` | a PostgreSQL Store's login or write setting | +| `connect` | `store`, `url` | `user`, `password` (`--password-stdin`; both required on a first connect), `synchronous_commit` (`local`) | connects a PostgreSQL database as a Store with its login; on a connected Store, changes its address, login or write setting | +| `disconnect` | `store` | — | forgets a PostgreSQL Store with its saved login and attachments, its data staying | +| `attach` | `store` | `machine` (required) | lets a machine run Sandboxes of a PostgreSQL Store, checked from that machine first | +| `detach` | `store` | `machine` (required) | stops a machine running Sandboxes of a PostgreSQL Store; refused while one runs there | | `move` | `store`, `machine` | `on_progress` | moves a sqlite Store between this computer and a machine | | `remove` | `store` | — | deletes a sqlite Store with every project in it | | `compact` | `store` | `on_progress` | reclaims the dead bytes of one Store; a sqlite Store on another machine is compacted by that machine's worker | @@ -1297,103 +1295,83 @@ refusals, and `store.doctor` is one of [the doctors](#the-doctors). `store.status` and `store.stats` are gone into `store get` (`--with live`, `--with stats`), `store.push` and `store.pull` -into `store move`, a password in a Store's record or URL into saved -logins (`save_auth`), and `update`'s `machine`, `url` and `clear` into -`connect` and `disconnect` with `machine`, with no alias. - -- **Saved logins.** `store save-auth --user - --password-stdin` writes `secret/auth/.json` (mode 0600, in a - 0700 folder) and moves the home's `generation`; the password is read from - stdin only and never answered, logged or traced. Short `{"ok":true}`; - long `ok, outcome (saved or rotated), auth, user, stores, stores_count`. - A Store recorded before saved logins (no `auth`) is `broken` `outdated` - with the fix `layerfs store save-auth --user - --password-stdin && layerfs store update --auth ` when its - URLs are addresses alone, else the steps below after the `save-auth` - (`` to fill in: no user is read from a URL); `store doctor`'s - `store.connection` gives the same fix. A Store naming a login the home - does not hold is `broken` `missing`, with the fix `layerfs store - save-auth --user --password-stdin && layerfs store update - --auth ` for that name; it wins over `outdated`. A record - that still holds what 2.0 no longer writes (a `password`, a URL that is - not an address alone, a `machines.` entry with anything but its - `url`, such as an old `checked`) is `broken` `outdated` with the fix - `layerfs store update --auth `, whose write drops those - fields; nothing is migrated for you, and a read never writes. Neither - state refuses a call. A Store records only the login's name (`auth`); - its URL holds host, port, database and TLS settings, read only as the - PostgreSQL client reads it, and is recorded and shown exactly as given: - no URL is ever cleaned or rewritten. A URL that may hold a login is - refused `InvalidInput`: one holding an `@`, one whose client reads a - user or a password, one the client does not read (an unknown key such - as `sslrootcert`, `sslkey` or `sslcert`, or an `sslmode` other than - `disable`, `prefer` or `require`), or one whose percent-decoded text - holds, in any case, `user`, `password`, `passfile`, `sslkey`, `sslcert`, - `sslpassword` or `oauth_client_secret` followed by `=` anywhere - (`postgres://h/db&password=p` and +into `store move`, and a password in a Store's record or URL into the +login `connect` saves, with no alias. The saved logins (`save_auth`, +`auths`, `remove_auth`), `update`, `--auth`, and `--machine` on `connect` +and `disconnect` are gone (owner, 2026-11-24): this computer is the one +place a PostgreSQL Store's address and login are saved, and machines are +attached to the Store and dial with both. + +- **The login.** A PostgreSQL Store's record keeps its URL exactly as + given, its `user`, `synchronous_commit` and binding. Its password is kept + in the home's secret folder as `secret/login/.json` (mode 0600, in + a 0700 folder), read from stdin only (`--password-stdin`) and never + answered, logged, traced or written into a record; user and password go + into the URL only when the Store is dialled, and the URL made is read + back by the client first. `get` answers `password_saved` and + `password_changed_at`, never the password. There is no migration and no + state for a record an earlier build wrote: a record without these fields + fails through the normal path, a call that dials it refused + `InvalidInput` (a record naming no `user`; a password this home does not + hold, with the fix `layerfs store connect + --password-stdin`). The URL holds host, port, database and TLS settings, + read only as the PostgreSQL client reads it, and is recorded and shown + exactly as given: no URL is ever cleaned or rewritten. A URL that may + hold a login is refused `InvalidInput`: one holding an `@`, one whose + client reads a user or a password, one the client does not read (an + unknown key such as `sslrootcert`, `sslkey` or `sslcert`, or an + `sslmode` other than `disable`, `prefer` or `require`), or one whose + percent-decoded text holds, in any case, `user`, `password`, `passfile`, + `sslkey`, `sslcert`, `sslpassword` or `oauth_client_secret` followed by + `=` anywhere (`postgres://h/db&password=p` and `postgres://h/db?application_name=me?password=p` too). One holding a `#` is refused too (one of the address is written `%40` or `%23`). The fix - names the address `` and the user ``: a first connect saves - the login with `save-auth` and names it with `--auth`; one refused only - for a `#` saves no login. Other text the client reads as part of a host, - database or value is the client's (`postgres://h/db&sslmode=require` - names the database `db&sslmode=require`). The refusal names the TLS key - or `sslmode` value it met (`sslmode=verify-full`), or the `#` ending a - value it would otherwise read (`sslmode=require#f`), and - `sslmode=require` verifies the server's certificate chain and host name; - a private CA is trusted where the Store is dialled: on Linux (OpenSSL) - in the system's trusted roots (`SSL_CERT_FILE` reaches only calls in the - process that reads it: a Sandbox's daemon starts with a cleared - environment), on macOS in the login or system keychain. The login goes - into the URL only when the Store is dialled, and the URL made is read - back by the client first. An older record's URL that may hold a login - is shown as `postgresql://`, never dialled - and never rewritten: the record stays `outdated` and keeps that URL, and - any password in it, on disk as it was until its fix runs. The fix dials - only with the login it names, never with the one the record names: for - a machine's own URL, `layerfs store disconnect --machine && - layerfs store update --auth && layerfs store connect - --machine `; for the Store's own, `layerfs store - disconnect && layerfs store connect --auth - --synchronous-commit ` and then each machine's own address - connected again (the Store is forgotten and connected again: refused - while a Sandbox of it exists, its data and projects kept, its backup - links and reaches not). The `outdated` fix names `` when it - replaces a URL. A 2.0 record whose URL holds a raw `#` is refused at - dial and replaced the same way. `auths` answers - `{ items }`, short `{ auth, user }` with `stores` (at most 20) when - used, `stores_count` only past 20, and `state`, `reason`, `fix` when the - login's file cannot be read (`broken` `failed`, fixed by saving it - again; the other logins are listed as usual); long `auth, user, state, - reason, fix, stores, stores_count, created_at, updated_at`. `remove_auth` is refused `InUse` (with - `stores`) while a Store uses the login, `NotFound` when there is none; - long `ok, outcome: "removed", auth`. -- **`connect`**, first time: `--auth` is required and must be saved; + names the address `` and the user ``: `layerfs store connect + --user --password-stdin`. Other text the client + reads as part of a host, database or value is the client's + (`postgres://h/db&sslmode=require` names the database + `db&sslmode=require`). The refusal names the TLS key or `sslmode` value + it met (`sslmode=verify-full`), or the `#` ending a value it would + otherwise read (`sslmode=require#f`), and `sslmode=require` verifies the + server's certificate chain and host name; a private CA is trusted where + the Store is dialled: on Linux (OpenSSL) in the system's trusted roots + (`SSL_CERT_FILE` reaches only calls in the process that reads it: a + Sandbox's daemon starts with a cleared environment), on macOS in the + login or system keychain. +- **`connect`**, first time: `--user` and the password are required and + are checked from this process before anything is saved; `synchronous_commit` defaults to `local`. It creates the LayerFS schema in an empty database or reads the Store's id from it (refused `Exists` - when another Store of this home has that id or name). Short - `{ projects }` (the first 20 names, with `projects_count` only past - those; `{"ok":true}` for an empty database or when only an address - changed); long `ok, - projects, projects_count, outcome (connected or updated), store, engine, - auth, connections, synchronous_commit`. On a connected Store `connect` - checks the new address against the same Store's id and takes no `--auth` - or `--synchronous-commit` (`InvalidInput`, naming `store update`); with - `--machine M` the address is `M`'s own, checked from `M` with the - Store's login, and its check is recorded as `M`'s reach. `projects` is - null when only an address changed. Its `connections` are `get`'s rows. -- **`update`** changes the login (checked against the same Store, and - again under the home lock, so a login removed meanwhile is `NotFound`) - or `synchronous_commit`; at least one. Its write drops the fields 2.0 no - longer writes and never rewrites a URL: a record keeping a URL that is - not an address alone is refused `InvalidInput`, nothing written, with - the steps above naming the login given and carrying a given - `--synchronous-commit`. Long `ok, outcome: "updated", store, - auth, synchronous_commit`. -- **`disconnect`** long `ok, outcome: "disconnected", store, machine`; - refused `InUse` while a Sandbox or Workspace uses the Store. With - `--machine M` it removes `M`'s own address and forgets what was seen of - `M`'s reach; `NotFound` when `M` has neither. + when another Store of this home has that id or name, a sqlite Store + included). Short `{ projects }` (the first 20 names, with + `projects_count` only past those; `{"ok":true}` for an empty database or + a connected Store changed); long `ok, projects, projects_count, outcome + (connected or updated), store, engine, url, user, synchronous_commit, + machines` (`machines` the attached machines' names). On a connected + Store `connect` changes its address, user, password or + `synchronous_commit`: an omitted user or password keeps the saved one, + and the result must reach the same Store (its binding) before anything + is saved; `projects` is null. Attachments are kept. +- **`disconnect`** long `ok, outcome: "disconnected", store`; it forgets + the Store's saved password and attachments too. Refused `InUse` while a + Sandbox or Workspace uses the Store. +- **`attach --machine M`** checks the Store from `M` with the URL and login + this computer saved, as its Sandboxes dial them (`M` must exist and its + platform run PostgreSQL Sandboxes here, else `NotFound` or + `Unsupported`), and only then records `M` in the Store's `attached` list + and its reach. Short `{ ok, outcome }` with `latency_ms`; long `ok, + outcome (attached, or checked for an attached machine checked again), + store, machine, latency_ms, server_version`. A sqlite Store is refused + `InvalidInput` naming `store move`; so is `native`, which is this + computer and needs no attaching. A machine that reaches the server only + through this computer's loopback is refused with advice to connect the + Store again with an address the machine reaches. `sandbox create` on a + machine that is not attached is refused `InvalidInput` with `layerfs + store attach --machine ` as its fix. +- **`detach --machine M`** long `ok, outcome: "detached", store, machine`; + forgets `M`'s reach. Refused `InUse` while a Sandbox of the Store's + projects is on `M` (counted and named, the removals as `fix`), `NotFound` + when `M` is not attached. - **A Store's state** comes from its records only, with no probe: `busy` while an operation it records (`op: { name, phase, started_at }`: a @@ -1408,36 +1386,29 @@ logins (`save_auth`), and `update`'s `machine`, `url` and `clear` into a record kind this build does not read; else `ready`. A move or remove holds the Store exclusively; a compaction, backup or restore does not refuse reads. -- **`get`**, short: `{ engine, state }`, with `machine`, `projects`, - `projects_count`, `backups` (each `{ bucket }`), `connections` and the - state's companion when they say something. Long: `engine, state, - machine, auth, binding, connections, projects, projects_count, backups, - op, blocked_by, reason, fix, observed_at, store, profile, - synchronous_commit, sqlite_version, created_at, last_transfer`. A sqlite - Store answers `machine`, `profile` and `sqlite_version`; a PostgreSQL - Store `binding` (the first 8 bytes of the id in its schema as 16 hex: - one database behind two addresses has one binding), `connections` and - `synchronous_commit`; the other engine's keys are null. `connections` - lists every side that connects to the database: this computer first - (`machine` null, dialling the Store's address), then by name each - machine with an address of its own, a reach seen from it, or a Sandbox - of the Store (`native` with no address of its own is this computer's - row). A row's short form is `{ url }` with `machine` and `reached` - (`ok` or `failed`; absent when nothing was seen); its long form - `machine, url, own, server, reached, reach`: `own` says the URL is the - machine's own, `server` is the `{ host, port, database }` the URL names, - `reach` the last one seen, `{ at, ok, latency_ms, server_version, - error }`, or null. A URL is shown exactly as recorded, and no URL shown - holds a login: an older record's URL that may hold one is - `postgresql://`, with a null `server`. A reach is written beside the +- **`get`**, short: `{ engine, state }`, with `machine`, `url`, `user`, + `machines`, `projects`, `projects_count`, `backups` (each `{ bucket }`) + and the state's companion when they say something. Long: `engine, state, + machine, url, user, password_saved, password_changed_at, binding, reach, + machines, projects, projects_count, backups, op, blocked_by, reason, fix, + observed_at, store, profile, synchronous_commit, sqlite_version, + created_at, last_transfer`. A sqlite Store answers `machine`, `profile` + and `sqlite_version`; a PostgreSQL Store `url` (exactly as connected, no + login), `user`, `password_saved`, `password_changed_at`, `binding` (the + first 8 bytes of the id in its schema as 16 hex: one database behind two + addresses has one binding), `reach` (this computer's last one), + `machines` and `synchronous_commit`; the other engine's keys are null. + `machines` has one row per attached machine: short `{ machine }` with + `reached` (`ok` or `failed`; absent when nothing was seen), long + `machine, reached, reach`; a reach is `{ at, ok, latency_ms, + server_version, error }`, or null. A reach is written beside the Store's record (its observation file, which moves no `generation`) by - `connect --machine`, every `store doctor` reach and each Sandbox made on - a machine. `projects` shows at most 20 names; + `store attach`, every `store doctor` reach and each Sandbox made on a + machine. `projects` shows at most 20 names; `projects_count` counts them all, only when there are more. A `backups` row's long form is `bucket, file, sha256, heads_sha256, last, attempt`: `last` the last transfer that worked (`{ call, ended_at, size }`), `attempt` the last one - that did not (`{ call, ended_at, error }`). `auth` is a PostgreSQL - Store's saved login, by name. + that did not (`{ call, ended_at, error }`). - **`get --with live`** reads the Store where it lives, starting nothing: a sqlite Store's file through its machine (in this process on `native`, else its recorded worker), a PostgreSQL Store's server from this @@ -1468,7 +1439,9 @@ logins (`save_auth`), and `update`'s `machine`, `url` and `clear` into `{ entries, files, size, canonical_bytes, stored_bytes, metadata_bytes, duration_ms }`, or null). - **`list`** answers `{ items }`, each item as `get` answers it with - `store` first: short `{ store, engine }` plus what says something. + `store` first, a PostgreSQL Store's `machines` as names: short + `{ store, engine }` plus what says something (`user` and `machines` for + a PostgreSQL Store). `--machine M` keeps the sqlite Stores on `M`. `--with stats` adds each item's `size` from one stat on its machine, starting nothing; null for a PostgreSQL Store and for a machine that does not answer. @@ -1527,7 +1500,7 @@ $ layerfs store list $ layerfs store get shop {"engine":"sqlite","state":"ready","machine":"native"} $ layerfs store get shop --with live --detail -{"engine":"sqlite","state":"ready","machine":"native","auth":null,"connections":null,"projects":[],"projects_count":null,"backups":[],"op":null,"blocked_by":null,"reason":null,"fix":null,"observed_at":"2026-11-18T15:35:10Z","store":"shop","profile":"normal","synchronous_commit":null,"sqlite_version":"3.53.2","created_at":"2026-11-18T15:35:10Z","last_transfer":null,"live":{"holders":[],"phases":null,"behind":[],"server_version":null,"latency_ms":null}} +{"engine":"sqlite","state":"ready","machine":"native","url":null,"user":null,"password_saved":null,"password_changed_at":null,"binding":null,"reach":null,"machines":null,"projects":[],"projects_count":null,"backups":[],"op":null,"blocked_by":null,"reason":null,"fix":null,"observed_at":"2026-11-18T15:35:10Z","store":"shop","profile":"normal","synchronous_commit":null,"sqlite_version":"3.53.2","created_at":"2026-11-18T15:35:10Z","last_transfer":null,"live":{"holders":[],"phases":null,"behind":[],"server_version":null,"latency_ms":null}} $ layerfs store list --with stats {"items":[{"store":"shop","engine":"sqlite","machine":"native","size":270336}]} $ layerfs store compact shop @@ -1537,37 +1510,36 @@ $ layerfs store move shop native ``` PostgreSQL, against a local `postgres:17` (macOS, native; this build's -outputs): +outputs, run 2026-11-24 on a scratch home): ```console -$ printf '%s' "$PG_PASSWORD" | layerfs store save-auth pg-app --user postgres --password-stdin --detail -{"ok":true,"outcome":"saved","auth":"pg-app","user":"postgres","stores":[],"stores_count":null} -$ layerfs store connect shop-pg 'postgresql://127.0.0.1:55231/shop?sslmode=disable' --auth pg-app --detail -{"ok":true,"projects":[],"projects_count":null,"outcome":"connected","store":"shop-pg","engine":"postgresql","auth":"pg-app","connections":[{"machine":null,"url":"postgresql://127.0.0.1:55231/shop?sslmode=disable","own":false,"server":{"host":"127.0.0.1","port":55231,"database":"shop"},"reached":null,"reach":null}],"synchronous_commit":"local"} -$ layerfs store auths -{"items":[{"auth":"pg-app","user":"postgres","stores":["shop-pg"]}]} +$ layerfs store connect shop-pg 'postgresql://postgres:pw@127.0.0.1:55437/shop' +{"error":"InvalidInput","message":"the URL names a user or holds a password (or a password file); give the address alone and the login with --user and --password-stdin; an `@` or `#` that is part of the address is written %40 or %23","fix":"layerfs store connect shop-pg --user --password-stdin"} +$ printf '%s' "$PG_PASSWORD" | layerfs store connect shop-pg 'postgresql://127.0.0.1:55437/shop?sslmode=disable' --user postgres --password-stdin --detail +{"ok":true,"projects":[],"projects_count":null,"outcome":"connected","store":"shop-pg","engine":"postgresql","url":"postgresql://127.0.0.1:55437/shop?sslmode=disable","user":"postgres","synchronous_commit":"local","machines":[]} +$ layerfs store list +{"items":[{"store":"shop-pg","engine":"postgresql","user":"postgres"}]} $ layerfs store get shop-pg -{"engine":"postgresql","state":"ready","auth":"pg-app","connections":[{"url":"postgresql://127.0.0.1:55231/shop?sslmode=disable"}]} -$ layerfs store connect shop-pg 'postgresql://postgres:pw@127.0.0.1:55231/shop' -{"error":"InvalidInput","message":"the URL names a user or holds a password (or a password file); give the address alone and the login with --auth (`layerfs store save-auth` saves one); an `@` or `#` that is part of the address is written %40 or %23"} -$ layerfs store update shop-pg --synchronous-commit off --detail -{"ok":true,"outcome":"updated","store":"shop-pg","auth":"pg-app","synchronous_commit":"off"} -$ layerfs store remove-auth pg-app -{"error":"InUse","message":"the login pg-app is used by shop-pg: `layerfs store update --auth ` or `layerfs store disconnect ` first","stores":["shop-pg"]} +{"engine":"postgresql","state":"ready","url":"postgresql://127.0.0.1:55437/shop?sslmode=disable","user":"postgres"} +$ layerfs store connect shop-pg 'postgresql://127.0.0.1:55437/shop?sslmode=disable' --synchronous-commit off --detail +{"ok":true,"projects":null,"projects_count":null,"outcome":"updated","store":"shop-pg","engine":"postgresql","url":"postgresql://127.0.0.1:55437/shop?sslmode=disable","user":"postgres","synchronous_commit":"off","machines":[]} +$ layerfs store attach shop-pg --machine native +{"error":"InvalidInput","message":"machine native is this computer, which every PostgreSQL Store is attached to; `layerfs store doctor shop-pg` checks it"} +$ layerfs store doctor shop-pg --machine lab +{"error":"InvalidInput","message":"machine lab is not attached to PostgreSQL Store shop-pg","fix":"layerfs store attach shop-pg --machine lab"} $ layerfs store disconnect shop-pg --detail -{"ok":true,"outcome":"disconnected","store":"shop-pg","machine":null} +{"ok":true,"outcome":"disconnected","store":"shop-pg"} ``` The URL above names `127.0.0.1`, which works only where the Sandbox's machine shares this computer's loopback: `native` and `docker` on a Linux -Engine. On `docker` with Docker Desktop, `lima` or `apple-container` a -`sandbox create --machine` refuses it `Unsupported`, naming what that -machine calls this computer; give the Store a host the machine reaches, or -that machine its own URL with `layerfs store connect shop-pg '' ---machine `. That check, like the first connect, needs no -privilege beyond what a Sandbox's reads and writes need: what only -`store compact` needs (`pg_read_all_stats`, `CREATE` on the database) is -checked when a compaction starts. +Engine. On `docker` with Docker Desktop, `lima` or `apple-container`, +`store attach --machine` refuses it, naming what that machine calls this +computer: connect the Store again with a host every attached machine +reaches (`layerfs store connect shop-pg ''`). That check, like the +first connect, needs no privilege beyond what a Sandbox's reads and writes +need: what only `store compact` needs (`pg_read_all_stats`, `CREATE` on +the database) is checked when a compaction starts. See [Stores](machines-and-stores.md#stores). @@ -1718,8 +1690,9 @@ every check was made and nothing was found; otherwise `findings` and beside it. While it reads it sends `{ phase: "data", done, total }` events counting trees. `store doctor` never runs `project.data`. -- `store doctor --machine` is for a PostgreSQL Store; a sqlite Store - refuses it. +- `store doctor --machine` is for a PostgreSQL Store and a machine + attached to it (else refused `InvalidInput` with `layerfs store attach + --machine ` as its fix); a sqlite Store refuses it. - A Store's checks, in this order: `store.record` (its record reads and names it), `store.operation` (an operation whose owner is gone with its outcome unknown is an error whose `fix` is the call that clears it; for a @@ -1729,17 +1702,17 @@ every check was made and nothing was found; otherwise `findings` and ready it waits with `store.connection`), `store.connection` (a sqlite Store's file is where its record says, read through its machine; a PostgreSQL Store's server answers this - computer with the saved login), `store.identity` (the Store's id is the + computer with the Store's user and saved password), `store.identity` (the Store's id is the recorded one), `store.schema` (its schema is this build's) and, for a sqlite Store, `store.backups` (a notice per bucket whose backup heads differ from the Store's, `fix` `layerfs backup create `). That is the whole cut: no Store data is scanned. A sqlite Store file whose id is not the recorded one fails `store.identity`, and `store.schema` is then not made; a file of the right id whose schema is - not this build's fails `store.schema`. A PostgreSQL Store is then probed from each machine - that has a Sandbox of it and from `--machine` (its own address where it - has one, else the Store's), each as one more `store.connection` row - with `from`. A Store whose machine is not ready shows its + not this build's fails `store.schema`. A PostgreSQL Store that this + computer reached is then checked from every attached machine, or from + `--machine` alone, each as one more `store.connection` row with `from`; + when this computer cannot connect no machine is checked. A Store whose machine is not ready shows its `store.connection` as `not_checked` with `blocked_by`, and nothing after it is tried. - `--text` prints a count line (`N error(s), N warning(s), N notice(s), N @@ -1901,7 +1874,7 @@ the request was sent and no answer settled it, and its message says so `--option=value` works for every option. A bool option alone (`sandbox remove … --force`) is true; `--force=false` is false. An option the table marks required (`backup connect`'s `--access-key` and -`--key-stdin`, `store save-auth`'s `--user` and `--password-stdin`, `file +`--key-stdin`, `store attach`'s and `store detach`'s `--machine`, `file edit`'s `--old-string` and `--new-string`) is shown without brackets in help, and a line without it is exit 2; the table's JSON says `required: true`, and the Node typings, Python stubs and MCP schemas mark it. diff --git a/docs/versioned/2.0.0/machines-and-stores.md b/docs/versioned/2.0.0/machines-and-stores.md index dd3f122d44..2a8fb0c9f8 100644 --- a/docs/versioned/2.0.0/machines-and-stores.md +++ b/docs/versioned/2.0.0/machines-and-stores.md @@ -398,7 +398,7 @@ run as `store push` and `store pull` on 2026-11-08 on `docker`, `lima` and `--with live` reads the Store where it lives (its file through its machine) and settles an uncertain backup or restore whose owner is gone; `--with stats` opens it for its counters. See - [`store`](calls.md#store-13) for every key and the compaction phases. + [`store`](calls.md#store-11) for every key and the compaction phases. - A lease or `op` records its process's start time and boot, so one whose process id was reused by another process is stale. A process that ends with Stores open leaves their leases; taking a lease removes the Store's @@ -422,47 +422,46 @@ run as `store push` and `store pull` on 2026-11-08 on `docker`, `lima` and ### PostgreSQL Stores -The PostgreSQL calls were run for this manual's [`store`](calls.md#store-13) -section against a local `postgres:17` on macOS (`store save-auth`, `connect`, -`auths`, `get`, `update`, `remove-auth`, `disconnect`). In short: +This computer is the one place a PostgreSQL Store's address and login are +saved (owner, 2026-11-24). Machines are attached to the Store and dial with +both; no machine has an address or a login of its own. The calls were run +for this manual's [`store`](calls.md#store-11) section against a local +`postgres:17` on macOS (`connect`, `list`, `get`, `attach`, `doctor`, +`disconnect`). In short: ```console -$ printf '%s' "$PG_PASSWORD" | layerfs store save-auth pg-app --user postgres --password-stdin -{"ok":true} -$ layerfs store connect shop-pg 'postgresql://127.0.0.1:55231/shop?sslmode=disable' --auth pg-app +$ printf '%s' "$PG_PASSWORD" | layerfs store connect shop-pg 'postgresql://127.0.0.1:55437/shop?sslmode=disable' --user postgres --password-stdin {"ok":true} $ layerfs project init shop-pg/load ./load # not run here -$ layerfs store connect shop-pg 'postgresql://10.0.0.5:5432/shop' --machine build-vm # not run -$ layerfs store update shop-pg --synchronous-commit off -$ layerfs store doctor shop-pg # not run here +$ layerfs store attach shop-pg --machine build-vm # not run: needs a reachable address +$ layerfs store connect shop-pg 'postgresql://127.0.0.1:55437/shop?sslmode=disable' --synchronous-commit off +$ layerfs store doctor shop-pg +{"ok":true} ``` -(The two `{"ok":true}` lines are the short forms of the `--detail` answers -shown in [the calls](calls.md#store-13).) - -- **Saved logins.** `store save-auth --user --password-stdin` - saves a login in the home's secret folder (`secret/auth/.json`, mode - 0600, in a 0700 folder); the password comes on stdin only (Node and - Python pass `password`) and is never answered, logged or traced. `store - auths` lists the logins and the Stores using each; `store remove-auth` - deletes one no Store uses. There is no login per machine. -- **`store connect --auth A`.** The URL starts `postgresql://` - or `postgres://` and holds host, port, database and TLS settings, read - only as the PostgreSQL client reads it, and is recorded and shown exactly - as given: LayerFS never cleans or rewrites a URL. One that may hold a - login is refused `InvalidInput`, before any effect: it holds an `@`, the - client reads a user or a password in it, the client does not read it (a - key it does not know, such as `sslpassword`, `sslrootcert`, `sslkey` or - `sslcert`, or an `sslmode` other than `disable`, `prefer` or `require`), - or its percent-decoded text holds a login key and `=` anywhere, in any - case (`user`, `password`, `passfile`, `sslkey`, `sslcert`, - `sslpassword`, `oauth_client_secret`: so - `postgres://h/db?application_name=me?password=p` and +- **`store connect --user U --password-stdin`.** The user and + password are required on a Store's first connect and are checked from + this computer before anything is saved. The record keeps the URL, the + user and `synchronous_commit`; the password is kept in the home's secret + folder (`secret/login/.json`, mode 0600, in a 0700 folder), comes + on stdin only (Node and Python pass `password`) and is never answered, + logged or traced. `store get` says whether it is saved + (`password_saved`) and when it was last changed (`password_changed_at`). + The URL starts `postgresql://` or `postgres://` and holds host, port, + database and TLS settings, read only as the PostgreSQL client reads it, + and is recorded and shown exactly as given: LayerFS never cleans or + rewrites a URL. One that may hold a login is refused `InvalidInput`, + before any effect: it holds an `@`, the client reads a user or a password + in it, the client does not read it (a key it does not know, such as + `sslpassword`, `sslrootcert`, `sslkey` or `sslcert`, or an `sslmode` + other than `disable`, `prefer` or `require`), or its percent-decoded text + holds a login key and `=` anywhere, in any case (`user`, `password`, + `passfile`, `sslkey`, `sslcert`, `sslpassword`, `oauth_client_secret`: + so `postgres://h/db?application_name=me?password=p` and `postgres://h/db&password=p` are refused too). One holding a `#` is refused as well (write a `#` or `@` that is part of the address `%23` or `%40`). The fix names the address `` and the user ``: `store - save-auth`, then the address alone named with `--auth` on a first - connect, with no `save-auth` when only a `#` is refused. Other text the + connect --user --password-stdin`. Other text the client reads as part of a host, database or value is the client's (`postgres://h/db&sslmode=require` names the database `db&sslmode=require`). The refusal names the TLS key or `sslmode` value @@ -472,66 +471,49 @@ shown in [the calls](calls.md#store-13).) the Store is dialled: on Linux (OpenSSL) in the system's trusted roots (`SSL_CERT_FILE` reaches only calls in the process that reads it: a Sandbox's daemon starts with a cleared environment), on macOS in the - login or system keychain. `--auth` is required on a Store's first connect. An empty database - gets the `layerfs` schema with a new identity; a database that already - holds it keeps its identity, and its projects become this home's project - records. A Store name already in the home is `Exists`, and so is the same - database under a second name, whatever address or login reaches it: a - database is known by the binding (the id) in its `layerfs` schema, read on - connect and checked again under the home lock. A replica or a copy of the - database carries the same binding, so it is the same Store; `store get`'s - long form shows the binding's first 16 hex characters. - `synchronous_commit` is `off`, `local` (the default), `remote_write`, `on` - or `remote_apply`. -- **One machine's own address.** `store connect --machine M` - gives machine `M` an address of its own (a proxy, another host name), - checked from `M` with the Store's login before it is saved; it refuses - `--auth`, and its check is recorded as `M`'s reach. `store disconnect - --machine M` removes it and forgets `M`'s reach; `machine remove` - forgets a machine's own addresses and reaches. -- **Who connects.** `store get` and `store list` answer `connections`: this - computer, then every machine with an address of its own, a reach seen - from it or a Sandbox of the Store, each with `reached` (`ok`, `failed`, - or absent when nothing was seen) and, in the long form, the address, the - server it names and the last reach (`at`, `ok`, `latency_ms`, - `server_version`, `error`). Nothing about a database is stored on a - machine; reaches are kept beside the Store's record. -- **Old records.** A PostgreSQL record that still holds a `password`, a URL - that is not an address alone, or an old `machines..checked` reads - `broken` `outdated` with a fix you run; nothing is migrated for you. A URL - that may hold a login is never dialled, shown (it reads - `postgresql://`) or rewritten: the record - keeps it, and any password in it, on disk as it was until a connect of - the address alone replaces it. Every fix dials only with the login it - names, never with the one the record names, so it works when that login - no longer authenticates; it names the address `` and the user - ``. With only old fields, `store update --auth ` - drops them. A machine's own URL that may hold a login is replaced with - `store disconnect --machine && store update --auth - && store connect --machine ` (the machine must be - running for the last step). The Store's own URL is replaced with `store - disconnect && store connect --auth - --synchronous-commit `, then `store connect - --machine ` for each machine's own address: the Store is forgotten - (refused while a Sandbox of it exists; its data stays) and connected - again, its projects found again, its backup links and reach - observations not kept. The `outdated` fix names `` when it replaces - a URL (the Store's own login, which `store get` names, or another). `store - update --auth ` (or `--synchronous-commit` alone) refuses - such a record, writing nothing, with the same steps naming `` and - carrying the `--synchronous-commit` given. A record naming a login the - home does not hold reads `broken` `missing`, fixed by saving that login - first. -- **`store update `** changes the login (`--auth`, checked against the - same Store) or `--synchronous-commit`. A new address is `store connect` - again, checked against the same Store's id. -- **`store disconnect `** forgets the Store; its data stays on the - server. It is `InUse` while a Sandbox or Workspace uses the Store. + login or system keychain. An empty database gets the `layerfs` schema + with a new identity; a database that already holds it keeps its + identity, and its projects become this home's project records. A Store + name already in the home is `Exists` (a sqlite Store's too), and so is + the same database under a second name, whatever address or login reaches + it: a database is known by the binding (the id) in its `layerfs` schema, + read on connect and checked again under the home lock. A replica or a + copy of the database carries the same binding, so it is the same Store; + `store get`'s long form shows the binding's first 16 hex characters. + `synchronous_commit` is `off`, `local` (the default), `remote_write`, + `on` or `remote_apply`. +- **`store connect` again** changes a connected Store's address, user, + password or `synchronous_commit`; an omitted user or password keeps the + saved one. The result must reach the same Store (its binding) before + anything is saved. Attached machines dial the new address and login from + their next connection. +- **`store attach --machine M`** lets machine `M` run Sandboxes of + the Store: `M` must exist and its platform run PostgreSQL Sandboxes, and + the Store is checked from `M` with the URL and login saved here before + `M` is recorded as attached; the check is kept as `M`'s reach. Attaching + again checks again (`outcome: "checked"`). `native` is this computer and + needs no attaching. `store detach --machine M` removes it, + refused while a Sandbox of the Store's projects is on `M`; `machine + remove` detaches a machine from every Store. +- **Who connects.** `store get` answers `reach` (this computer's) and + `machines`, one row per attached machine with `reached` (`ok`, `failed`, + or absent when nothing was seen) and, in the long form, the last reach + (`at`, `ok`, `latency_ms`, `server_version`, `error`); `store list` names + the attached machines. Nothing about a database is stored on a machine; + reaches are kept beside the Store's record. +- **No migration.** A record an earlier build wrote is read as it is, with + no state of its own: a call that dials a record without a `user`, or one + whose password this home does not hold, is refused `InvalidInput` (the + latter with `store connect --password-stdin` as its fix). +- **`store disconnect `** forgets the Store, its saved password and + its attachments; its data stays on the server. It is `InUse` while a + Sandbox or Workspace uses the Store. - `project init` into a PostgreSQL Store runs in the caller's process, under the Store's lease. PostgreSQL is built into every artifact. - A PostgreSQL Store is on no machine and has no default machine. A Sandbox of it runs on `native` unless `sandbox create --machine M` names - another machine whose platform runs PostgreSQL Sandboxes (`native` on + a machine attached to it (refused `InvalidInput`, with `store attach` as + its fix, otherwise) whose platform runs PostgreSQL Sandboxes (`native` on macOS and Linux, `docker`, `lima`, `apple-container`); `sandbox create` checks from the machine that the server answers and holds this Store. The URL is dialled exactly as configured, never rewritten. On a machine @@ -540,36 +522,37 @@ shown in [the calls](calls.md#store-13).) 127.0.0.0/8, `0.0.0.0`, `::1`, in any spelling) or a Unix socket is refused `Unsupported`, naming what the machine calls this computer (`host.docker.internal`; `host.lima.internal`; `apple-container`: its - network's gateway, on which the server must listen) and the per-machine - URL call `layerfs store connect --machine `; - `native` and `docker` on a Linux Engine share the loopback and dial it - as given. A Sandbox resolves names as its machine does. Only the calls - that dial the URL (`sandbox create`, Commit, a Workspace status) are - refused for it: a Sandbox whose URL its machine cannot dial can still be - read and removed. A forced `sandbox remove` there still ends the mount - intent each of its Workspaces held: the machine closes the Sandbox - without the URL and hands those intents back in its answer, and this - computer ends each once with the Store's own address (PostgreSQL Store - calls run in the caller), so `branch remove` and `store compact` are not - refused for them afterwards; one it could not end is a sentence of - `left`. The intents travel only in that answer and nothing records - them, so they stay if the remove ends between the machine stopping the - Sandbox and this computer ending them: the answer is lost (the remove - reports `Unknown`), the machine cannot delete the Sandbox's folder after - stopping and deleting its runtime (the remove is refused `Failed`), or - this computer's process ends first. A retried `sandbox remove` then - answers `already_gone` with an empty `left`, and `branch remove` of the - Branch and `store compact` stay refused (`InUse`, `mounts active`), since - nothing can prove a PostgreSQL mount intent's owner gone. Any other - reason the URL cannot be made (the saved login is gone, or the Store - names none) refuses the remove, forced or not, with that reason and its - fix: save the login and the remove goes through. The login - travels only in the one request. The server always runs off the - machine; nothing installs PostgreSQL in a machine (D12). -- `store doctor ` checks the Store from this computer and from each - machine that has an address of its own or a Sandbox of it (`--machine M` - adds one), each as one `store.connection` row with `from`, and records - each reach. + network's gateway, on which the server must listen) and advising to + connect the Store again with an address the machine reaches (`layerfs + store connect `); `native` and `docker` on a Linux Engine + share the loopback and dial it as given. A Sandbox resolves names as its + machine does. Only the calls that dial the URL (`sandbox create`, + Commit, a Workspace status) are refused for it: a Sandbox whose URL its + machine cannot dial can still be read and removed. A forced `sandbox + remove` there still ends the mount intent each of its Workspaces held: + the machine closes the Sandbox without the URL and hands those intents + back in its answer, and this computer ends each once with the Store's + address (PostgreSQL Store calls run in the caller), so `branch remove` + and `store compact` are not refused for them afterwards; one it could + not end is a sentence of `left`. The intents travel only in that answer + and nothing records them, so they stay if the remove ends between the + machine stopping the Sandbox and this computer ending them: the answer is + lost (the remove reports `Unknown`), the machine cannot delete the + Sandbox's folder after stopping and deleting its runtime (the remove is + refused `Failed`), or this computer's process ends first. A retried + `sandbox remove` then answers `already_gone` with an empty `left`, and + `branch remove` of the Branch and `store compact` stay refused (`InUse`, + `mounts active`), since nothing can prove a PostgreSQL mount intent's + owner gone. Any other reason the URL cannot be made (the password is not + saved, or the record names no user) refuses the remove, forced or not, + with that reason and its fix: connect the Store again with its login and + the remove goes through. The login travels only in the one request. The + server always runs off the machine; nothing installs PostgreSQL in a + machine (D12). +- `store doctor ` checks the Store from this computer and then from + every attached machine (`--machine M`: from `M` alone, which must be + attached), each as one `store.connection` row with `from`, and records + each reach; when this computer cannot connect, no machine is checked. - Not built: backups of PostgreSQL Stores (back it up with PostgreSQL's own tools). @@ -646,15 +629,15 @@ layerfs backup doctor lab --full ## Secrets -A PostgreSQL login (`store save-auth`) and a bucket's secret key (`backup -connect --key-stdin`) are kept in the home's secret folder (`secret/`, 0700; -each file 0600), read from stdin only in the shell, and never answered, -logged or traced; the call log records a secret's byte count. A Store -record names its login by name (`auth`). Anyone who can read the home can -make every call. There is no keychain (O1). A reference an older record -names (`env:NAME` or `file:/absolute/path`) is not read: a PostgreSQL Store -whose record names no saved login reads `broken` `outdated` with the fix -`layerfs store save-auth --user --password-stdin && layerfs -store update --auth `, and a bucket record with no key id is -refused with the fix that connects it again (`layerfs backup connect - --access-key --key-stdin`). +A PostgreSQL Store's password (`store connect --password-stdin`) and a +bucket's secret key (`backup connect --key-stdin`) are kept in the home's +secret folder (`secret/`, 0700; each file 0600), read from stdin only in the +shell, and never answered, logged or traced; the call log records a secret's +byte count. A PostgreSQL Store's record keeps its user; its password is +`secret/login/.json`. Anyone who can read the home can make every +call. There is no keychain (O1). A reference an older record names +(`env:NAME` or `file:/absolute/path`) is not read: a PostgreSQL Store whose +password this home does not hold is refused when it is dialled, with the +fix `layerfs store connect --password-stdin`, and a bucket +record with no key id is refused with the fix that connects it again +(`layerfs backup connect --access-key --key-stdin`). diff --git a/docs/versioned/2.0.0/migration.md b/docs/versioned/2.0.0/migration.md index 128e1ca9c5..a1d528b568 100644 --- a/docs/versioned/2.0.0/migration.md +++ b/docs/versioned/2.0.0/migration.md @@ -233,12 +233,10 @@ Every call of the table, its shell line and what it was: | `store.list` | `layerfs store list [--machine M] [--with stats]` | same name | | `store.get` | `layerfs store get [--with live,stats]` | `store.get`, `store.status`, `store.stats` | | `store.create` | `layerfs store create [--machine M]` | same name | -| `store.connect` | `layerfs store connect [--auth A] [--machine M] [--synchronous-commit local]` | same name | -| `store.disconnect` | `layerfs store disconnect [--machine M]` | same name | -| `store.save_auth` | `layerfs store save-auth --user U --password-stdin` | new | -| `store.auths` | `layerfs store auths` | new | -| `store.remove_auth` | `layerfs store remove-auth ` | new | -| `store.update` | `layerfs store update [--auth A] [--synchronous-commit S]` | same name | +| `store.connect` | `layerfs store connect [--user U] [--password-stdin] [--synchronous-commit local]` | same name, and `store.update` | +| `store.disconnect` | `layerfs store disconnect ` | same name | +| `store.attach` | `layerfs store attach --machine M` | new | +| `store.detach` | `layerfs store detach --machine M` | new | | `store.move` | `layerfs store move ` | `store.push`, `store.pull` | | `store.remove` | `layerfs store remove ` | same name | | `store.compact` | `layerfs store compact ` | same name | @@ -354,13 +352,13 @@ Every argument the table renamed or dropped, from the frozen rows | `store.get` | ` (store.get, store.status, store.stats)` | `` | an existing thing is named by its own word, never `name` | | `store.get` | `--machine (store.status)` | `store doctor --machine M` | whether one machine reaches a Store is a check, and the doctor makes it | | `store.connect` | `` | `` | an existing thing is named by its own word, never `name` | -| `store.connect` | `--password` | `--auth` | a login is saved once in the home and named by any number of Stores | +| `store.connect` | `--password` | `--user · --password-stdin` | secrets come only on stdin; this computer is the one place a Store's login is saved (owner, 2026-11-24) | | `store.disconnect` | `` | `` | an existing thing is named by its own word, never `name` | -| `store.update` | `` | `` | an existing thing is named by its own word, never `name` | +| `store.update` | `` | `store connect ` | a connected Store's address, login or setting changes with a connect, checked like one | | `store.update` | `--url` | `store connect ` | an address change is a connect, checked like one | -| `store.update` | `--machine` | `store connect --machine M` | a machine's own address is a connect; the login is the Store's | -| `store.update` | `--password` | `--auth, or store save-auth to rotate` | the login is saved once and named | -| `store.update` | `--clear` | `store disconnect --machine M` | removing an address is a disconnect | +| `store.update` | `--machine` | `store attach --machine M` | no machine has an address of its own; an attached machine dials the Store's address and login (owner, 2026-11-24) | +| `store.update` | `--password` | `store connect --password-stdin` | the login is saved once, on this computer | +| `store.update` | `--clear` | `store detach --machine M` | a machine stops running Sandboxes of the Store | | `store.move` | ` (store.push, store.pull)` | `` | an existing thing is named by its own word, never `name` | | `store.remove` | `` | `` | an existing thing is named by its own word, never `name` | | `store.compact` | `` | `` | an existing thing is named by its own word, never `name` | From ebf6697a79179366add7b158b6f22ac58fd81f04 Mon Sep 17 00:00:00 2001 From: YifanXu1999 Date: Tue, 24 Nov 2026 15:59:25 +0800 Subject: [PATCH 2/4] store: machine native is an ordinary machine for PostgreSQL Stores Owner correction 2026-11-24: "this computer" (the host) is the control process: the home, records, secrets, the Store's saved connection and the check made from this computer. It is never a machine and never named `native`. Machine native is the built-in machine with Platform::Native; what it allows (shared loopback, local executor) comes from its platform, not its name. - store.attach / store.detach accept native like any machine: the platform support check, the reach check from that machine (its Loopback decides whether a loopback URL is allowed) and the record. The "machine native is this computer, which every PostgreSQL Store is attached to" refusal is gone. - sandbox.create needs the machine attached, native included, with the same refusal and fix. With no --machine, a PostgreSQL Store's Sandbox no longer defaults to native: exactly one attached machine is used; none is refused InvalidInput with `layerfs store attach --machine ` as its fix; several are refused InvalidInput, listed in next.machines, asking for --machine. - store.doctor checks this computer, then every attached machine, native only when attached; --machine native follows the same rule (refused with the attach fix when not attached). - Reaches: this computer's check stays `here`, machine native's is `reach.native`; observed.rs no longer folds native into `here`, and the doctor no longer drops native from the attached machines. - store.connect attaches nothing (unchanged, now documented). Tests updated: observed_reach (native's reach is its own), postgres_refusals (native attach dials and fails Unavailable against a dead address; detach NotFound), postgres_login (doctor --machine native refused until attached; native attached against a real server, checked again, in the doctor's rows and store.get, detached), postgres_sandbox_reach (native attached first), sandbox_machines (no default machine: none and several refused; one attached used; live test attaches native). No test deleted. Docs: api/sdk/store.md, sandbox.md, README.md, control sqlite-and-postgresql.md, versioned calls.md and machines-and-stores.md, the JS SDK skill's store and sandbox pages, the call spec notes and sandbox.create's machine help (also in the guide). Production LOC: 211291 -> 211308 (delta +17) core 42163 -> 42163 (0), engine 97424 -> 97424 (0), control 61437 -> 61455 (+18), api 10267 -> 10266 (-1); reference absent (retired R9c; last counted 65,417 at tree 498dd1917812). Method: python3 tools/production_loc.py --root on `git archive` of the parent 2dd49a22de and `git checkout-index -a` of the staged tree; nonblank, non-comment product source, tests, docs, tools and generated stubs excluded. Co-Authored-By: Claude Opus 5.5 --- .../references/methods/sandbox.md | 5 +- .../references/methods/store.md | 4 +- api/crates/layerfs-api/src/calls/guide.rs | 2 +- api/crates/layerfs-api/src/store/doctor.rs | 5 +- .../layerfs-api/tests/postgres_login.rs | 44 ++++++++++--- .../layerfs-api/tests/postgres_refusals.rs | 11 +++- .../tests/postgres_sandbox_reach.rs | 7 +++ .../layerfs-api/tests/sandbox_machines.rs | 63 +++++++++++++++---- .../src/doctor/store_target.rs | 5 +- control/crates/layerfs-control/src/store.rs | 9 +-- control/crates/layerfs-sandbox/src/create.rs | 52 ++++++++++++--- control/crates/layerfs-store/src/observed.rs | 17 ++--- .../layerfs-store/tests/observed_reach.rs | 7 ++- core/docs/issues/call-surface-2-0/calls.json | 2 +- .../call-surface-2-0/families/home.json | 2 +- .../call-surface-2-0/families/sandbox.json | 2 +- .../call-surface-2-0/families/store.json | 10 +-- docs/architecture/api/sdk/README.md | 2 +- docs/architecture/api/sdk/sandbox.md | 11 ++-- docs/architecture/api/sdk/store.md | 11 ++-- .../sqlite-and-postgresql.md | 20 ++++-- docs/versioned/2.0.0/calls.md | 36 +++++++---- docs/versioned/2.0.0/machines-and-stores.md | 19 ++++-- 23 files changed, 238 insertions(+), 108 deletions(-) diff --git a/.agents/skills/layerfs-js-sdk/references/methods/sandbox.md b/.agents/skills/layerfs-js-sdk/references/methods/sandbox.md index 8923889ce1..496707741e 100644 --- a/.agents/skills/layerfs-js-sdk/references/methods/sandbox.md +++ b/.agents/skills/layerfs-js-sdk/references/methods/sandbox.md @@ -55,8 +55,9 @@ found it so; else `ready`. Every broken Sandbox's `fix` is ## `sandbox.create` Starts a named Sandbox of a project. With no `machine` it runs on its sqlite -Store's machine, else on `native`; another machine than a sqlite Store's is -`Unsupported`. `image` (a `sha256:` digest, a Docker image id or a Docker +Store's machine, or on the one machine attached to its PostgreSQL Store +(none attached, or several: `InvalidInput`; `store.attach` attaches one); +another machine than a sqlite Store's is `Unsupported`. `image` (a `sha256:` digest, a Docker image id or a Docker reference) picks its root on every machine but macOS `native`, which refuses it `Unsupported`; an image the machine does not hold is copied from the host's Docker first, as [`machine.load_image`](machine.md) does, with its diff --git a/.agents/skills/layerfs-js-sdk/references/methods/store.md b/.agents/skills/layerfs-js-sdk/references/methods/store.md index de5e999902..036a08ac92 100644 --- a/.agents/skills/layerfs-js-sdk/references/methods/store.md +++ b/.agents/skills/layerfs-js-sdk/references/methods/store.md @@ -27,7 +27,7 @@ A Store holds projects and all their history. The verb says the kind: `create` makes a sqlite Store (one file, on one machine at a time; on `native` unless `machine` names another); `connect` connects a PostgreSQL database with its login, saved on this computer only, and `attach` lets a -machine other than `native` run its Sandboxes. +machine (machine native too) run its Sandboxes; with no machine named, `sandbox.create` uses the one attached machine. ## `store.list` and `store.get` @@ -80,7 +80,7 @@ $ layerfs store get shop --with live,stats # | `create(name)` | An empty sqlite Store | `{"ok":true}` (seen). A taken name is `Exists` (seen: `a Store named shop exists`). `machine` makes it on that running machine through its worker | | `connect(store, url, …)` | Connects a PostgreSQL database as a Store (`user` and `password` required the first time, checked before anything is saved; `synchronous_commit` defaults to `local`); on a connected Store, changes its address, user, password or `synchronous_commit` (an omitted user or password keeps the saved one; the same Store must be reached) | The URL holds host, port, database and TLS settings only: one naming a user, password or `passfile` is `InvalidInput` with the `fix` `layerfs store connect --user --password-stdin`. Shell: `--user U --password-stdin`; the password is never answered, logged or traced. Short `{ projects, projects_count? }`, or `{"ok":true}`; long `outcome` `connected` or `updated` | | `disconnect(store)` | Forgets a PostgreSQL Store with its saved password and attachments, its data staying | `InUse` while a Sandbox or Workspace uses it | -| `attach(store, { machine })` | Lets a machine run Sandboxes of a PostgreSQL Store, checked from that machine with the saved URL and login first | Short `{ ok, outcome, latency_ms? }`; `outcome` `attached`, or `checked` when already attached. A sqlite Store or `native` is `InvalidInput`. `sandbox.create` on a machine not attached is refused with `layerfs store attach --machine ` as its `fix` | +| `attach(store, { machine })` | Lets a machine run Sandboxes of a PostgreSQL Store, checked from that machine with the saved URL and login first | Short `{ ok, outcome, latency_ms? }`; `outcome` `attached`, or `checked` when already attached. A sqlite Store is `InvalidInput`; machine native is attached like any other. `sandbox.create` on a machine not attached is refused with `layerfs store attach --machine ` as its `fix` | | `detach(store, { machine })` | Stops a machine running Sandboxes of a PostgreSQL Store | `InUse` while a Sandbox of the Store's projects is on it; `NotFound` when not attached | | `move(store, machine)` | Moves a sqlite Store between this computer and a machine | To or from `native` only (seen when already there: `store move, check: Store shop is already on native`, `InvalidInput`; moving off a machine whose record lacks `vm_name` is `Unavailable` with `blocked_by`). Progress `check`, `snapshot`, `send`, `verify`, `install`, `record`, `retire`. Short `{ moved_bytes }`. A sqlite Store's Sandboxes run only on its machine | | `remove(store)` | Deletes a sqlite Store with every project in it | `{"ok":true}`. `NotFound` for an unknown name (seen). A PostgreSQL Store is disconnected instead. A record this build does not read, or a Store on a machine whose record has no 2.0 name, goes by its records alone, with `left` saying what may remain | diff --git a/api/crates/layerfs-api/src/calls/guide.rs b/api/crates/layerfs-api/src/calls/guide.rs index 00d10b7200..056c5cffb1 100644 --- a/api/crates/layerfs-api/src/calls/guide.rs +++ b/api/crates/layerfs-api/src/calls/guide.rs @@ -295,7 +295,7 @@ const ARGS: &[(&str, &str, &str)] = &[ ( "sandbox.create", "machine", - "the machine it runs on; the Store's machine when left out", + "the machine it runs on; when left out, a sqlite Store's machine or the one machine attached to a PostgreSQL Store", ), ( "sandbox.create", diff --git a/api/crates/layerfs-api/src/store/doctor.rs b/api/crates/layerfs-api/src/store/doctor.rs index 79bf3d24e4..4923d90407 100644 --- a/api/crates/layerfs-api/src/store/doctor.rs +++ b/api/crates/layerfs-api/src/store/doctor.rs @@ -38,11 +38,8 @@ fn run(context: &mut Context<'_>, args: &SdkValue) -> Outcome { ), )) } - // `native` is this computer, which every PostgreSQL Store is - // attached to Some(StoreKind::Postgresql) - if machine != "native" - && !record.as_ref().is_some_and(|r| r.is_attached(machine)) => + if !record.as_ref().is_some_and(|r| r.is_attached(machine)) => { return Err(layerfs_control::store::not_attached(store, machine)); } diff --git a/api/crates/layerfs-api/tests/postgres_login.rs b/api/crates/layerfs-api/tests/postgres_login.rs index 2dffac5f45..ab32e81b26 100644 --- a/api/crates/layerfs-api/tests/postgres_login.rs +++ b/api/crates/layerfs-api/tests/postgres_login.rs @@ -293,7 +293,8 @@ fn connect_checks_and_saves_the_login_and_a_reconnect_keeps_what_it_is_not_given } /// The doctor checks from this computer, then from each attached machine -/// (here a stopped lima machine, which waits), or from `--machine` alone; +/// (here stopped lima machines, which wait, and `native`, attached like any +/// other machine and refused until it is), or from `--machine` alone; /// when this computer is not let in, no machine is checked. `store.get` /// answers each attached machine as a row with its reach. #[cfg(feature = "machine")] @@ -356,13 +357,11 @@ fn the_doctor_checks_attached_machines_only_after_this_computer() { &[("store", t("pg")), ("machine", t("lab"))], ); assert_eq!(froms(&report), ["lab"], "{report:?}"); - // `native` is this computer, checked anyway - let report = long( - &home, - "store.doctor", - &[("store", t("pg")), ("machine", t("native"))], - ); - assert_eq!(froms(&report), Vec::::new(), "{report:?}"); + // `native` is an ordinary machine: not attached, it is refused + let on_native = [("store", t("pg")), ("machine", t("native"))]; + let (code, message) = call(&home, "store.doctor", &on_native).unwrap_err(); + assert_eq!(code, "InvalidInput", "{message}"); + assert!(message.contains("not attached"), "{message}"); let got = long(&home, "store.get", &[("store", t("pg"))]); let reach = got.get("reach").unwrap(); assert_eq!(reach.get("ok"), Some(&SdkValue::Bool(true)), "{got:?}"); @@ -384,6 +383,35 @@ fn the_doctor_checks_attached_machines_only_after_this_computer() { items[0].get("machines"), Some(&SdkValue::List(vec![t("dev"), t("lab")])) ); + // attached like any machine, checked from it (it shares this host's + // loopback), then checked by the doctor with the others + let attached = long(&home, "store.attach", &on_native); + assert_eq!( + attached.get_text("outcome"), + Some("attached"), + "{attached:?}" + ); + assert!(attached.get_int("latency_ms").is_some(), "{attached:?}"); + let again = long(&home, "store.attach", &on_native); + assert_eq!(again.get_text("outcome"), Some("checked"), "{again:?}"); + let report = long(&home, "store.doctor", &on_native); + assert_eq!(froms(&report), ["native"], "{report:?}"); + let report = long(&home, "store.doctor", &[("store", t("pg"))]); + assert_eq!(froms(&report), ["dev", "lab", "native"], "{report:?}"); + let got = long(&home, "store.get", &[("store", t("pg"))]); + let Some(SdkValue::List(rows)) = got.get("machines") else { + panic!("{got:?}"); + }; + let native = rows + .iter() + .find(|row| row.get_text("machine") == Some("native")); + assert_eq!( + native.and_then(|row| row.get_text("reached")), + Some("ok"), + "{rows:?}" + ); + let detached = long(&home, "store.detach", &on_native); + assert_eq!(detached.get_text("outcome"), Some("detached")); // this computer not let in (its password forgotten): no machine is // checked, since each would only repeat it std::fs::remove_file(password_file(&home, "pg").unwrap()).unwrap(); diff --git a/api/crates/layerfs-api/tests/postgres_refusals.rs b/api/crates/layerfs-api/tests/postgres_refusals.rs index 2575db1436..407ea427bf 100644 --- a/api/crates/layerfs-api/tests/postgres_refusals.rs +++ b/api/crates/layerfs-api/tests/postgres_refusals.rs @@ -5,7 +5,7 @@ //! written; `store.disconnect` //! refuses `InUse` while another process holds the Store and forgets its //! saved password; `store.attach` and `store.detach` refuse a sqlite -//! Store, `native`, a missing machine, a loopback URL a machine does not +//! Store, a missing machine, `native` when it does not reach the server, a loopback URL a machine does not //! share and a detach while a Sandbox runs there; `store.doctor --machine` //! refuses a machine that is not attached. The removed calls are gone from //! the table. The URLs name 127.0.0.1 port 1, where nothing listens, so a @@ -438,9 +438,14 @@ fn attach_and_detach_refuse_what_is_not_theirs() { refusal(&home, "store.attach", &on("nope", "dev")).code, "NotFound" ); + // `native` is checked like any machine: nothing listens on the + // Store's address, so it is not attached let native = refusal(&home, "store.attach", &on("pg", "native")); - assert_eq!(native.code, "InvalidInput", "{native:?}"); - assert!(native.message.contains("this computer"), "{native:?}"); + assert_eq!(native.code, "Unavailable", "{native:?}"); + assert_eq!( + refusal(&home, "store.detach", &on("pg", "native")).code, + "NotFound" + ); assert_eq!( refusal(&home, "store.attach", &on("pg", "ghost")).code, "NotFound" diff --git a/api/crates/layerfs-api/tests/postgres_sandbox_reach.rs b/api/crates/layerfs-api/tests/postgres_sandbox_reach.rs index bb24ae9dac..1d44c6de1d 100644 --- a/api/crates/layerfs-api/tests/postgres_sandbox_reach.rs +++ b/api/crates/layerfs-api/tests/postgres_sandbox_reach.rs @@ -58,6 +58,13 @@ fn the_reach_check_finds_the_binding_and_the_project_on_one_session() { ], ) .unwrap(); + // its Sandboxes run on `native` once it is attached, like any machine + call( + &home, + "store.attach", + &[("store", t("pg")), ("machine", t("native"))], + ) + .unwrap(); // a project record whose project the schema does not hold home::write_record( &paths::project_record(&home, "pg", "ghost"), diff --git a/api/crates/layerfs-api/tests/sandbox_machines.rs b/api/crates/layerfs-api/tests/sandbox_machines.rs index a1c3975bb3..34fbf6fc90 100644 --- a/api/crates/layerfs-api/tests/sandbox_machines.rs +++ b/api/crates/layerfs-api/tests/sandbox_machines.rs @@ -10,8 +10,8 @@ //! LAYERFS_TEST_PG_PASSWORD, LAYERFS_TEST_DAEMON (a host daemon built with //! `postgresql`); the docker half also LAYERFS_TEST_IMAGE (a local image //! digest, the worker container's) and LAYERFS_BUNDLE (a sealed Linux -//! bundle whose daemon has `postgresql`). The docker machine is attached -//! to the Store first. The URL is never rewritten: on Docker Desktop a +//! bundle whose daemon has `postgresql`). `native` and the docker machine +//! are each attached to the Store first, like any machine. The URL is never rewritten: on Docker Desktop a //! loopback URL is refused for the docker machine, and the Store is then //! connected again with a URL naming `host.docker.internal`, which its //! Sandboxes resolve with the worker's resolver files; their Workspace @@ -490,6 +490,12 @@ fn a_postgresql_store_s_sandboxes_on_native_and_docker() { ok(&home, "store.connect", &args) }; connect(address); + // `native` is attached like any machine, checked from it + ok( + &home, + "store.attach", + &[("store", t("pg")), ("machine", t("native"))], + ); ok( &home, "project.init", @@ -507,20 +513,18 @@ fn a_postgresql_store_s_sandboxes_on_native_and_docker() { ("machine", t("native")), ], ); - // the create proved this computer reaches the Store: `native` is this - // computer, whose reach is the Store's own (spec v23 V23-2) + // the create proved `native` reaches the Store: its own row's reach let got = ok( &home, "store.get", &[("store", t("pg")), ("detail", SdkValue::Bool(true))], ); - let reach = got.get("reach").unwrap_or_else(|| panic!("{got:?}")); - assert_eq!(reach.get("ok"), Some(&SdkValue::Bool(true)), "{got:?}"); - assert_eq!( - got.get("machines"), - Some(&SdkValue::List(vec![])), - "{got:?}" - ); + let Some(SdkValue::List(rows)) = got.get("machines") else { + panic!("{got:?}"); + }; + assert_eq!(rows.len(), 1, "{got:?}"); + assert_eq!(rows[0].get_text("machine"), Some("native"), "{got:?}"); + assert_eq!(rows[0].get_text("reached"), Some("ok"), "{got:?}"); work(&home, "pg/app", "n", "on-native", "native.txt"); ok(&home, "sandbox.remove", &[("sandbox", t("n"))]); if let (Some(image), Some(_)) = (env("LAYERFS_TEST_IMAGE"), env("LAYERFS_BUNDLE")) { @@ -818,8 +822,9 @@ fn a_sqlite_store_s_sandbox_on_each_running_vm_machine() { /// With no machine named, `sandbox.create` runs where the Store's calls /// run (#536 §10): a sqlite Store's machine (here a docker machine with no worker, -/// so the create is refused naming its start), and `native` for a -/// PostgreSQL Store (refused here by the reach check, which runs there). +/// so the create is refused naming its start), and the one machine attached +/// to a PostgreSQL Store (none or several are refused; with machine native +/// attached, the reach check runs there). #[test] fn a_sandbox_with_no_machine_runs_on_its_store_s() { let home = tempdir("default"); @@ -886,6 +891,38 @@ fn a_sandbox_with_no_machine_runs_on_its_store_s() { Some("layerfs store attach pg --machine box") ); assert!(!paths::sandbox_dir(&home, "t3").exists()); + // with no machine named, a Store with no machine attached is refused + // with the attach as its fix: there is no default machine + let args = SdkValue::map([("project", t("pg/app")), ("name", t("t2"))]); + let none = + layerfs_api::call(Some(&home), "sandbox.create", args.clone(), &mut |_| {}).unwrap_err(); + assert_eq!(none.code, "InvalidInput", "{none:?}"); + assert_eq!( + none.message, + "no machine is attached to PostgreSQL Store pg to run a Sandbox on" + ); + assert_eq!( + none.detail.get_text("fix"), + Some("layerfs store attach pg --machine ") + ); + // several attached: the call names one + pg_record(&home, &["box", "native"]); + let several = layerfs_api::call(Some(&home), "sandbox.create", args, &mut |_| {}).unwrap_err(); + assert_eq!(several.code, "InvalidInput", "{several:?}"); + assert!( + several.message.contains("name one with --machine"), + "{several:?}" + ); + assert_eq!( + several + .detail + .get("next") + .and_then(|next| next.get("machines")), + Some(&SdkValue::List(vec![t("box"), t("native")])), + "{several:?}" + ); + // one attached (machine native, here): the Sandbox runs there + pg_record(&home, &["native"]); let refused = call( &home, "sandbox.create", diff --git a/control/crates/layerfs-control/src/doctor/store_target.rs b/control/crates/layerfs-control/src/doctor/store_target.rs index 7b51da6b7f..68ea4d47c1 100644 --- a/control/crates/layerfs-control/src/doctor/store_target.rs +++ b/control/crates/layerfs-control/src/doctor/store_target.rs @@ -584,13 +584,12 @@ fn fold( /// attached to it, or from `--machine` alone (the call refuses one that is /// not attached), as those machines dial it; each result is what was seen /// of its reach (spec v23 V23-9). A machine that is not ready is not -/// dialled; `native` is this computer, checked above. +/// dialled. fn reach(probe: &Probe<'_>, record: &StoreRecord, checks: &mut Checks) { - let mut machines = match &probe.options.machine { + let machines = match &probe.options.machine { Some(machine) => vec![machine.clone()], None => record.attached(), }; - machines.retain(|machine| machine != "native"); for machine in &machines { let state = crate::store::machine_state(probe.home, machine) .unwrap_or_else(|_| State::broken(Reason::Missing, None)); diff --git a/control/crates/layerfs-control/src/store.rs b/control/crates/layerfs-control/src/store.rs index 278488e1d5..6dfe443817 100644 --- a/control/crates/layerfs-control/src/store.rs +++ b/control/crates/layerfs-control/src/store.rs @@ -118,8 +118,7 @@ pub fn connect(home: &Path, request: &StoreConnect) -> Outcome { /// The PostgreSQL Store `name` a machine attaches to or detaches from: a /// sqlite Store is `InvalidInput` naming `store move` (it lives on one -/// machine), and `native` (this computer, which every PostgreSQL Store is attached to) -/// is `InvalidInput`. +/// machine). fn attachable(home: &Path, name: &StoreName, machine: &str) -> Result { let record = StoreRecord::of(home, name)?; if record.kind()? == StoreKind::Sqlite { @@ -131,12 +130,6 @@ fn attachable(home: &Path, name: &StoreName, machine: &str) -> Result, } +/// The machine a Sandbox of PostgreSQL Store `store` runs on when the call +/// names none: the one machine attached to it. None attached is refused +/// with the attach as its fix; several are listed in `next` and the call +/// is asked to name one. +fn only_attached(store: &str, attached: Vec) -> Result { + match attached.as_slice() { + [machine] => Ok(machine.clone()), + [] => Err(with_fix( + refused( + "InvalidInput", + format!("no machine is attached to PostgreSQL Store {store} to run a Sandbox on"), + ), + format!( + "layerfs store attach {} --machine ", + shell_word(store) + ), + )), + several => { + let message = format!( + "PostgreSQL Store {store} is attached to {} machines ({}): name one with --machine", + several.len(), + several.join(", ") + ); + let names = several.iter().map(SdkValue::text).collect(); + Err(with_next( + refused("InvalidInput", message), + "machines", + SdkValue::List(names), + )) + } + } +} + /// Starts the Sandbox: with no `machine`, on a sqlite Store's machine, or -/// `native` for a PostgreSQL Store (#536 §10), which also runs on each -/// machine attached to it (`store.attach`) whose platform runs PostgreSQL -/// Sandboxes. +/// on the one machine attached to a PostgreSQL Store. A PostgreSQL Store's +/// Sandbox runs only on a machine attached to it (`store.attach`) whose +/// platform runs PostgreSQL Sandboxes. pub fn create( home: &Path, events: &mut Events<'_>, @@ -93,7 +126,7 @@ pub fn create( let machine = match (named, &target.store_ref) { (Some(machine), _) => machine.to_owned(), (None, StoreRef::Sqlite { .. }) => target.store_ref.machine()?.to_owned(), - (None, _) => "native".to_owned(), + (None, _) => only_attached(&target.store, target.record.attached())?, }; let machine = machine.as_str(); // refused too while the machine is being removed @@ -121,12 +154,11 @@ pub fn create( if layerfs_machine::record::MachineRecord::read(&home, machine)?.is_none() { return Err(refused("NotFound", format!("no machine named {machine}"))); } - // a PostgreSQL Store is on no machine: its Sandboxes run on this - // computer (`native`) and on each machine attached to it, each dialling - // the URL and login this computer saved; the create's reach check - // proves it can + // a PostgreSQL Store is on no machine: its Sandboxes run on each + // machine attached to it, each dialling the URL and login this + // computer saved; the create's reach check proves it can if let StoreRef::Postgres { .. } = target.store_ref { - if machine != "native" && !target.record.is_attached(machine) { + if !target.record.is_attached(machine) { let refusal = refused( "InvalidInput", format!( diff --git a/control/crates/layerfs-store/src/observed.rs b/control/crates/layerfs-store/src/observed.rs index dc402277ff..484b688bc8 100644 --- a/control/crates/layerfs-store/src/observed.rs +++ b/control/crates/layerfs-store/src/observed.rs @@ -1,10 +1,9 @@ //! What was seen when a PostgreSQL Store's database was dialled (spec v23 //! V23-2): `store//observed.json`, beside the `at` a live read writes -//! there. `here` is this computer's dial of the Store's address; -//! `reach.` a machine's, as its Sandboxes dial it. A Sandbox on -//! `native` with no address of its own dials as this computer does, so -//! its reach is `here`. Each entry is `{ at, ok, latency_ms, -//! server_version, error }`, the last one seen. +//! there. `here` is this computer's dial of the Store's address (the +//! control process that holds the connection), never a machine's; +//! `reach.` a machine's, as its Sandboxes dial it. Each entry is +//! `{ at, ok, latency_ms, server_version, error }`, the last one seen. //! //! It is not a record: a write never moves the home's generation and never //! fails the call that made it. Writers run after their Store I/O, under @@ -106,12 +105,6 @@ pub fn seen_at(home: &Path, store: &str, ms: i64) { } } -/// The key `machine`'s reach is kept under: none for this computer's -/// (`native`'s too). -fn from(machine: Option<&str>) -> Option<&str> { - machine.filter(|m| *m != "native") -} - /// Records what `machine` (none: this computer) saw dialling PostgreSQL /// Store `store`, best effort. pub fn record(home: &Path, store: &str, machine: Option<&str>, reach: &Reach) { @@ -120,7 +113,7 @@ pub fn record(home: &Path, store: &str, machine: Option<&str>, reach: &Reach) { return Ok(()); } let entry = reach.to_record(now_ms()); - match from(machine) { + match machine { None => observed::merge(file, HERE, entry), Some(machine) => { let machines = reaches(&observed::fields(file)); diff --git a/control/crates/layerfs-store/tests/observed_reach.rs b/control/crates/layerfs-store/tests/observed_reach.rs index 2f4c10f598..9655229b14 100644 --- a/control/crates/layerfs-store/tests/observed_reach.rs +++ b/control/crates/layerfs-store/tests/observed_reach.rs @@ -81,11 +81,12 @@ fn reaches_are_kept_beside_the_live_read_and_merged() { seen::record(&home, "pg", Some("lab"), &Reach::reached()); let lab = seen::read(&home, "pg").of("lab").unwrap(); assert_eq!(lab.get("latency_ms"), Some(&SdkValue::Null)); - // `native` dials as this computer + // `native` is a machine like any other, apart from this computer seen::record(&home, "pg", Some("native"), &Reach::reached()); let got = seen::read(&home, "pg"); - assert!(got.of("native").is_none()); - assert_eq!(got.here.unwrap().get("ok"), Some(&SdkValue::Bool(true))); + let native = got.of("native").expect("native's reach"); + assert_eq!(native.get("ok"), Some(&SdkValue::Bool(true))); + assert_eq!(got.here.unwrap().get("ok"), Some(&SdkValue::Bool(false))); std::fs::remove_dir_all(home).unwrap(); } diff --git a/core/docs/issues/call-surface-2-0/calls.json b/core/docs/issues/call-surface-2-0/calls.json index f887ad9f8f..79f7383c37 100644 --- a/core/docs/issues/call-surface-2-0/calls.json +++ b/core/docs/issues/call-surface-2-0/calls.json @@ -2772,7 +2772,7 @@ { "name": "machine", "kind": "Name", - "help": "the machine to run on; default: the machine of the project's sqlite Store; this computer (native) for a project of a PostgreSQL Store" + "help": "the machine to run on; default: the machine of the project's sqlite Store, or the one machine attached to a PostgreSQL Store (none or several attached: refused)" }, { "name": "image", diff --git a/core/docs/issues/call-surface-2-0/families/home.json b/core/docs/issues/call-surface-2-0/families/home.json index 152d344e56..12ed23d8db 100644 --- a/core/docs/issues/call-surface-2-0/families/home.json +++ b/core/docs/issues/call-surface-2-0/families/home.json @@ -55,7 +55,7 @@ { "call": "home.get", "badge": "merged", - "note": "+ machine.platforms (--with platforms). Reads the home and changes nothing; it writes no call-log line. state is ready, or broken with reason: missing (no home yet, fix: layerfs home init) or reason: outdated (a folder that is not a LayerFS 2.0 home, which this build does not convert: fix: mv <home> <home>.old && layerfs home init); a layerfs.json it cannot read is reason: failed. generation is a number that moves when any record in the home is written: a UI polls it and re-reads only when it moves. A live read (--with live, or sandbox get) writes a record only when the state word or its reason changes, and that write moves it; observed_at is kept beside the record in an observation file it does not cover. It does not move when the owner of a recorded op dies (a dead owner's op is ignored on read, with no write), nor for a Workspace the home does not record. --with tree is the whole home from records only, with no machine contacted: every machine with its sqlite Stores and its Sandboxes, then the PostgreSQL Stores and the buckets. A node holds what the records hold: a machine its platform (and cpus, memory_bytes where it has them), a Store its engine and projects (bare names, as store get answers them; a PostgreSQL Store also its connections, store get's rows, spec v23), a Sandbox its project, image and workspaces (each {workspace, branch}), a bucket its provider. A node leaves state out when ready; the state is the last one its record holds, so a blocked_by can name engine_down, not_answering, missing or unreachable after a live read saw it. A project and a Workspace take their Store's or Sandbox's state. Workspaces are listed only where the home keeps their records (a Sandbox on native, or one reached directly); elsewhere the node says workspaces_not_listed:true while that machine is ready. On a stopped machine a Store and a Sandbox answer blocked with blocked_by naming the machine, and no Workspaces are listed. Leftovers are not a section here: LayerFS removes them itself where nothing owns them (v20). The long form's bundle.source says where the Linux bundle this build would deploy was found: env:LAYERFS_BUNDLE, runtime (an installed runtime's own, <runtime>/bundle/linux-<arch>/ beside <runtime>/bin/layerfs, chosen after LAYERFS_BUNDLE and before the cache) or cache", + "note": "+ machine.platforms (--with platforms). Reads the home and changes nothing; it writes no call-log line. state is ready, or broken with reason: missing (no home yet, fix: layerfs home init) or reason: outdated (a folder that is not a LayerFS 2.0 home, which this build does not convert: fix: mv <home> <home>.old && layerfs home init); a layerfs.json it cannot read is reason: failed. generation is a number that moves when any record in the home is written: a UI polls it and re-reads only when it moves. A live read (--with live, or sandbox get) writes a record only when the state word or its reason changes, and that write moves it; observed_at is kept beside the record in an observation file it does not cover. It does not move when the owner of a recorded op dies (a dead owner's op is ignored on read, with no write), nor for a Workspace the home does not record. --with tree is the whole home from records only, with no machine contacted: every machine with its sqlite Stores and its Sandboxes, then the PostgreSQL Stores and the buckets. A node holds what the records hold: a machine its platform (and cpus, memory_bytes where it has them), a Store its engine and projects (bare names, as store get answers them; a PostgreSQL Store also its machines, the names of the machines attached to it), a Sandbox its project, image and workspaces (each {workspace, branch}), a bucket its provider. A node leaves state out when ready; the state is the last one its record holds, so a blocked_by can name engine_down, not_answering, missing or unreachable after a live read saw it. A project and a Workspace take their Store's or Sandbox's state. Workspaces are listed only where the home keeps their records (a Sandbox on native, or one reached directly); elsewhere the node says workspaces_not_listed:true while that machine is ready. On a stopped machine a Store and a Sandbox answer blocked with blocked_by naming the machine, and no Workspaces are listed. Leftovers are not a section here: LayerFS removes them itself where nothing owns them (v20). The long form's bundle.source says where the Linux bundle this build would deploy was found: env:LAYERFS_BUNDLE, runtime (an installed runtime's own, <runtime>/bundle/linux-<arch>/ beside <runtime>/bin/layerfs, chosen after LAYERFS_BUNDLE and before the cache) or cache", "today": [ "home.get", "machine.platforms" diff --git a/core/docs/issues/call-surface-2-0/families/sandbox.json b/core/docs/issues/call-surface-2-0/families/sandbox.json index 80da49e579..c6956de9e0 100644 --- a/core/docs/issues/call-surface-2-0/families/sandbox.json +++ b/core/docs/issues/call-surface-2-0/families/sandbox.json @@ -33,7 +33,7 @@ { "name": "machine", "kind": "Name", - "help": "the machine to run on; default: the machine of the project's sqlite Store; this computer (native) for a project of a PostgreSQL Store" + "help": "the machine to run on; default: the machine of the project's sqlite Store, or the one machine attached to a PostgreSQL Store (none or several attached: refused)" }, { "name": "image", diff --git a/core/docs/issues/call-surface-2-0/families/store.json b/core/docs/issues/call-surface-2-0/families/store.json index 76bb520c31..d4873f33ac 100644 --- a/core/docs/issues/call-surface-2-0/families/store.json +++ b/core/docs/issues/call-surface-2-0/families/store.json @@ -8,8 +8,8 @@ "Why rows list projects: a project count needs a name for the number; the short list of names answers both.", "Why secrets come on stdin: a password in an argument lands in shell history and process listings.", "Why connect is not create: LayerFS makes and deletes a sqlite file; a PostgreSQL database exists outside LayerFS and stays when it is disconnected.", - "Why a saved login without an address: the address is the part that differs per machine and per proxy; the login is the part that is the same everywhere.", - "Why the auth calls live in store: a top-level layerfs auth would read like logging in to LayerFS itself.", + "Why one login per Store, on this computer: the host is the one place a PostgreSQL Store's address and login are saved (owner, 2026-11-24); every attached machine dials with both, so no machine has an address or a login of its own.", + "Why machines attach: a machine runs Sandboxes of a PostgreSQL Store only once it is checked from that machine with the saved address and login; native is an ordinary machine and is attached the same way.", "Why move names the destination: push and pull were one operation with two names. store move shop dev sends it; store move shop native brings it back.", "Why no default machine on a PostgreSQL Store: no machine owns it. Where a Sandbox runs is chosen at sandbox create." ], @@ -130,7 +130,7 @@ { "call": "store.get", "badge": "merged", - "note": "+ store.status, store.stats. state comes from the home's records, with no probe. A sqlite Store is ready, blocked with blocked_by {machine, reason} when its machine is not ready, busy with op {name, phase, started_at} (name is move, remove, compact, backup or restore), or broken with reason and fix. A PostgreSQL Store is ready, busy or broken; it waits on no machine. unresolved is an operation whose outcome is not known and whose owner is gone; its fix is the call that clears it: the same layerfs store move <store> <machine> for a move, layerfs store remove <store> for a remove, layerfs store compact <store> for a compaction (the next run adopts and settles what the earlier one left), and layerfs store get <store> --with live for a backup or a restore. A live read is what first sees missing (no file where the record says; the fix restores a backup or removes the Store) and unreachable (this computer cannot reach the PostgreSQL server; the fix is layerfs store doctor <store>); it writes the record only when the state word or its reason changes, and from then on a records-only read answers them too. unknown with observed_at is answered only by the live read that could not be made, and is never recorded. observed_at is kept beside the record, in an observation file the home's generation does not cover; a write of the record moves generation. An op whose owner is gone and whose outcome is certain is ignored on read, with no write. A sqlite Store answers machine; a PostgreSQL Store answers auth and connections (the one without a machine is the one every machine uses) and has no default machine. The other engine's keys are null in the long form. projects shows the first 20 names. Each backups row is {bucket}, and in the long form {bucket, file, sha256, heads_sha256, last, attempt}: last is the last transfer that worked ({call, ended_at, size}), attempt one that did not ({call, ended_at, error}, else null); last_transfer is {call, from, to, ended_at, size, sha256, heads_sha256, retired}. heads_sha256 was heads. With --with live a sqlite Store on another machine is read through that machine, the compaction record beside its file included: a run live there reads busy (op compact with its phase), even when this home's record holds that run unresolved after a lost reply; while the machine is stopped the Store reads blocked and nothing is asked of it. Whether a machine reaches a PostgreSQL Store is the doctor's to say (store doctor), not this call's. live.phases lists the steps the compaction record can show, in order: on SQLite mark, build, verify, install, cleanup (the record writes cleanup in its final step); store compact's progress events stay mark, build, verify, install (V19-12). connections (spec v23) lists every side that connects to a PostgreSQL Store's database: this computer first (machine null, the Store's address), then by name each machine with an address of its own, a reach seen from it, or a Sandbox of the Store; native without an address of its own is this computer's row. A row is {url} with machine and reached (ok or failed; absent when nothing was seen) in the short form, and {machine, url, own, server, reached, reach} in the long: own is whether the URL is the machine's own, server the {host, port, database} it names, reach the last reach seen {at, ok, latency_ms, server_version, error} or null. A reach is written to the Store's observation file by store connect --machine, every store doctor reach and each Sandbox made on a machine; it moves no generation. binding (long form) is the first 8 bytes of the id in the Store's schema as 16 hex: one database behind two addresses has one binding. A PostgreSQL Store whose record holds what 2.0 no longer writes (a password, a URL with a user or a login parameter, a machines.<m> entry with anything but its url) is broken outdated with fix: layerfs store update <store> --auth <auth>, which writes it clean; one naming a login the home does not hold is broken missing with fix: layerfs store save-auth <auth> --user <user> --password-stdin && layerfs store update <store> --auth <auth>, which wins over outdated. Neither refuses a call.", + "note": "+ store.status, store.stats. state comes from the home's records, with no probe. A sqlite Store is ready, blocked with blocked_by {machine, reason} when its machine is not ready, busy with op {name, phase, started_at} (name is move, remove, compact, backup or restore), or broken with reason and fix. A PostgreSQL Store is ready, busy or broken; it waits on no machine. unresolved is an operation whose outcome is not known and whose owner is gone; its fix is the call that clears it: the same layerfs store move <store> <machine> for a move, layerfs store remove <store> for a remove, layerfs store compact <store> for a compaction (the next run adopts and settles what the earlier one left), and layerfs store get <store> --with live for a backup or a restore. A live read is what first sees missing (no file where the record says; the fix restores a backup or removes the Store) and unreachable (this computer cannot reach the PostgreSQL server; the fix is layerfs store doctor <store>); it writes the record only when the state word or its reason changes, and from then on a records-only read answers them too. unknown with observed_at is answered only by the live read that could not be made, and is never recorded. observed_at is kept beside the record, in an observation file the home's generation does not cover; a write of the record moves generation. An op whose owner is gone and whose outcome is certain is ignored on read, with no write. A sqlite Store answers machine; a PostgreSQL Store answers url, user, password_saved, password_changed_at, reach (this computer's) and machines (one row per attached machine, native included only when attached) and has no default machine. The other engine's keys are null in the long form. projects shows the first 20 names. Each backups row is {bucket}, and in the long form {bucket, file, sha256, heads_sha256, last, attempt}: last is the last transfer that worked ({call, ended_at, size}), attempt one that did not ({call, ended_at, error}, else null); last_transfer is {call, from, to, ended_at, size, sha256, heads_sha256, retired}. heads_sha256 was heads. With --with live a sqlite Store on another machine is read through that machine, the compaction record beside its file included: a run live there reads busy (op compact with its phase), even when this home's record holds that run unresolved after a lost reply; while the machine is stopped the Store reads blocked and nothing is asked of it. Whether a machine reaches a PostgreSQL Store is the doctor's to say (store doctor), not this call's. live.phases lists the steps the compaction record can show, in order: on SQLite mark, build, verify, install, cleanup (the record writes cleanup in its final step); store compact's progress events stay mark, build, verify, install (V19-12). A machines row is {machine} with reached (ok or failed; absent when nothing was seen) in the short form and {machine, reached, reach} in the long, reach the last one seen {at, ok, latency_ms, server_version, error} or null. A reach is written to the Store's observation file by store attach, every store doctor reach and each Sandbox made on a machine; it moves no generation. binding (long form) is the first 8 bytes of the id in the Store's schema as 16 hex: one database behind two addresses has one binding. There is no migration: a record without these fields has no state of its own, and a call that dials it is refused (owner, 2026-11-24).", "today": [ "store.get", "store.status", @@ -321,7 +321,7 @@ { "call": "store.connect", "badge": "reshaped", - "note": "PostgreSQL. The URL holds host, port, database and TLS options; one with a user or a password is refused InvalidInput. First connect: --auth is required, here and only here; it is made from this computer, which gives an empty database the LayerFS schema and its id, or reads them, and answers the projects found. The URL is the address every machine uses. On a connected Store: with --machine the URL becomes that machine's own address, proven from that machine; without it, it replaces the address every machine uses, proven from this computer. Either must read the Store's id (Unavailable otherwise) and refuses --auth and --synchronous-commit (InvalidInput: a machine never has its own login; both change with store update). A Store has at most one address for every machine and one per machine. A database whose id another Store of this home holds is Exists. projects shows the first 20 names. A running Sandbox keeps its route Its connections are store get's rows (spec v23). --machine records the machine's check as its reach. A URL naming a user or carrying a login parameter (user, any password, passfile) is refused InvalidInput with a fix that gives the address alone: on a first connect after store save-auth, naming that login with --auth; on a connected Store (no --auth on connect) after store update --auth, with --machine for a machine's own address (spec v23 V23-13, LF11); sslkey and sslcert name files and pass. Every PostgreSQL record write drops the fields 2.0 no longer writes.", + "note": "PostgreSQL. The URL holds host, port, database and TLS options; one with a user or a password is refused InvalidInput with the fix layerfs store connect <store> <url> --user <user> --password-stdin. First connect: --user and the password are required and are checked from this computer before anything is saved; it gives an empty database the LayerFS schema and its id, or reads them, and answers the projects found. The record keeps the URL, the user and synchronous_commit; the password is kept in the home's secret folder (kind login, by Store), never answered or logged. On a connected Store: it changes the address, user, password or synchronous_commit, keeping what it is not given, and must reach the same Store (its binding) first (Unavailable otherwise). It attaches no machine, native included. A database whose id another Store of this home holds, or a sqlite Store of that name, is Exists. projects shows the first 20 names. A running Sandbox keeps its connection.", "today": [ "store.connect" ], @@ -807,7 +807,7 @@ { "call": "store.doctor", "badge": "new", - "note": "the Store, by the checks of checks.store in order, then a shallow check of each project (project doctor's list: project.record, project.listed; a project on record that the Store does not list is a notice with a fix, not an error). The same Store list runs wherever a Store is checked, by home doctor and machine doctor too. It stops after the schema check and reads no data: project doctor --full reads data. A PostgreSQL Store is also probed from each machine that has a Sandbox of it (R9): one store.connection check per machine, with from naming the machine, on the check entry and on its finding. --machine adds a probe from one more machine, Sandbox or not; it is for the command line and is refused InvalidInput for a sqlite Store. store.backups reports a backup that is behind as a notice on the Store, one finding per bucket, naming the bucket in message and fix (layerfs backup create <store> <bucket>); it is left out for a PostgreSQL Store and for a Store with no bucket link. store.operation reads the home's record and, for a sqlite Store, the compaction record beside its file through its machine (a run live there passes; one left there is an error with fix layerfs store compact <store>). Under a stopped machine store.record is made and the rest, store.operation included, are not_checked with blocked_by. The tree is the Store's node with projects. Today's ids: store.worker and the store.connection.* steps fold into store.connection (the failing step is in the finding's evidence), store.snapshot into store.schema; store.connection.kind is dropped (one doctor serves both engines); store.integrity.*, store.database.*, store.catalog.*, store.history.*, store.namespace, store.packs, store.objects, store.ordinal_blocks, store.acquisition.*, store.merge.* and store.advisory.* are dropped with the whole-Store scan. Exits 0 once the report is made A PostgreSQL Store is dialled from this computer, then from every machine with an address of its own, a Sandbox of it, or --machine; every reach, this computer's included (with its latency and server version), is written to the Store's observation file and read back as store get's connections (spec v23).", + "note": "the Store, by the checks of checks.store in order, then a shallow check of each project (project doctor's list: project.record, project.listed; a project on record that the Store does not list is a notice with a fix, not an error). The same Store list runs wherever a Store is checked, by home doctor and machine doctor too. It stops after the schema check and reads no data: project doctor --full reads data. A PostgreSQL Store is checked from this computer (the process that holds the connection), then, once that reached it, from every machine attached to it (native only when attached): one store.connection check per machine, with from naming the machine, on the check entry and on its finding. --machine checks from that machine alone, which must be attached (else InvalidInput with layerfs store attach as its fix); it is refused InvalidInput for a sqlite Store. store.backups reports a backup that is behind as a notice on the Store, one finding per bucket, naming the bucket in message and fix (layerfs backup create <store> <bucket>); it is left out for a PostgreSQL Store and for a Store with no bucket link. store.operation reads the home's record and, for a sqlite Store, the compaction record beside its file through its machine (a run live there passes; one left there is an error with fix layerfs store compact <store>). Under a stopped machine store.record is made and the rest, store.operation included, are not_checked with blocked_by. The tree is the Store's node with projects. Today's ids: store.worker and the store.connection.* steps fold into store.connection (the failing step is in the finding's evidence), store.snapshot into store.schema; store.connection.kind is dropped (one doctor serves both engines); store.integrity.*, store.database.*, store.catalog.*, store.history.*, store.namespace, store.packs, store.objects, store.ordinal_blocks, store.acquisition.*, store.merge.* and store.advisory.* are dropped with the whole-Store scan. Exits 0 once the report is made Every reach, this computer's included (with its latency and server version), is written to the Store's observation file and read back by store get as reach and machines.", "today": [], "help": "check a Store, then each of its projects", "cli": "layerfs store doctor [--machine M]", diff --git a/docs/architecture/api/sdk/README.md b/docs/architecture/api/sdk/README.md index 64dff20630..e483735b31 100644 --- a/docs/architecture/api/sdk/README.md +++ b/docs/architecture/api/sdk/README.md @@ -82,7 +82,7 @@ progress, the refusals the call names with their `fix`, and its MCP profile | To get | You first need | Made by | | --- | --- | --- | | a sqlite Store | nothing (`native` is built in) | [`store.create`](store.md#storecreate) | -| a PostgreSQL Store | a database and its login | [`store.connect`](store.md#storeconnect); [`store.attach`](store.md#storeattach) for a machine other than `native` | +| a PostgreSQL Store | a database and its login | [`store.connect`](store.md#storeconnect); [`store.attach`](store.md#storeattach) for each machine that runs its Sandboxes, machine native too | | a project | a Store | [`project.init`](project.md#projectinit) | | a Branch to work on | a project (`main` is its published line) | [`branch.fork`](branch.md#branchfork) | | a Sandbox | a project and a machine | [`sandbox.create`](sandbox.md#sandboxcreate) | diff --git a/docs/architecture/api/sdk/sandbox.md b/docs/architecture/api/sdk/sandbox.md index 0784f719e4..d864e5a651 100644 --- a/docs/architecture/api/sdk/sandbox.md +++ b/docs/architecture/api/sdk/sandbox.md @@ -63,7 +63,7 @@ Python layerfs.sandbox.create(project, name, *, machine=None, image=None, mount | --- | --- | --- | | `project` | project | `/` | | `name` | name | the new Sandbox's name | -| `machine` option | name | the machine to run on; default: the machine of the project's sqlite Store; this computer (native) for a project of a PostgreSQL Store | +| `machine` option | name | the machine to run on; default: the machine of the project's sqlite Store, or the one machine attached to a PostgreSQL Store (none or several attached: refused) | | `image` option | image | the image the Sandbox runs; default: the machine's own | | `mount` option | name | also mount this Branch; the Workspace gets the default name, the Branch's name made valid, and the answer is its handle and path | | `on_progress` option | function | | @@ -79,10 +79,13 @@ under one home lock, where it is claimed with the `op` `create`; a name taken anywhere in the home is `Exists`. The machine starts the daemon, and the record is written once with the answer, dropping the `op`; a refused start removes the record. With no `--machine` the Sandbox runs on its sqlite -Store's machine, else on `native`; another machine than a sqlite Store's is +Store's machine, or on the one machine attached to its PostgreSQL Store +(none attached is refused `InvalidInput` with `layerfs store attach +--machine ` as its fix; several are listed in `next.machines` and +the call must name one); another machine than a sqlite Store's is `Unsupported`, and the support table must accept the platform and Store -kind. A PostgreSQL Store's Sandbox runs on `native` or on a machine attached -to it: any other is refused `InvalidInput` with `layerfs store attach +kind. A PostgreSQL Store's Sandbox runs only on a machine attached to it, +machine native as much as any other: any other is refused `InvalidInput` with `layerfs store attach --machine ` as its fix. The caller puts the Store's user and saved password into the URL and sends the URL only in this request; the launching side checks that it reaches the diff --git a/docs/architecture/api/sdk/store.md b/docs/architecture/api/sdk/store.md index cc5e474991..baf30d7c25 100644 --- a/docs/architecture/api/sdk/store.md +++ b/docs/architecture/api/sdk/store.md @@ -406,12 +406,15 @@ Only after the check succeeds is the machine added to the record's outcome is `checked` instead of `attached`, and a failed check is recorded as its reach while the attachment stays. A machine that reaches the server only through this computer's loopback is refused with advice to connect the -Store again with an address the machine reaches. `native` is this computer: -it dials as this computer does and is never attached. +Store again with an address the machine reaches. Machine native is attached, +checked and detached like any other machine, its platform deciding whether +a loopback URL is allowed (it shares this computer's loopback on macOS and +Linux); its reach is its own, apart from this computer's. `store connect` +attaches nothing. | Refusal | When | | --- | --- | -| `InvalidInput` | a sqlite Store (`store move` moves one to a machine); `native` | +| `InvalidInput` | a sqlite Store (`store move` moves one to a machine) | | `NotFound` | no such Store or machine | | `Unsupported` | the machine's platform runs no PostgreSQL Sandboxes on this host | | `Unavailable` | the machine is stopped or does not answer; the server does not answer the machine, or holds another Store | @@ -445,7 +448,7 @@ Store's projects is on the machine (the message counts and names them, `next` lists them, and the `fix` removes them before the detach; [`inventory.rs`](../../../../control/crates/layerfs-control/src/inventory.rs) `store_idle_on`), `NotFound` when the machine is not attached, and -`InvalidInput` for a sqlite Store or `native`. The long form is `ok, +`InvalidInput` for a sqlite Store. The long form is `ok, outcome ("detached"), store, machine`. ### store.move diff --git a/docs/architecture/control/stores-and-projects/sqlite-and-postgresql.md b/docs/architecture/control/stores-and-projects/sqlite-and-postgresql.md index 0b0bf5c290..71475075ae 100644 --- a/docs/architecture/control/stores-and-projects/sqlite-and-postgresql.md +++ b/docs/architecture/control/stores-and-projects/sqlite-and-postgresql.md @@ -112,14 +112,22 @@ both; no machine has an address or a login of its own. | --- | --- | --- | --- | | `store.connect` | records the database as a Store in the fixed `layerfs` schema: the URL exactly as given (an address alone: no user or password), `user`, schema, `synchronous_commit`, binding, a cursor key of this home's own, no machine; the password goes to the home's secrets as kind `login` under the Store's name. On a connected Store it changes the address, user, password or `synchronous_commit`, an omitted user or password keeping the saved one; the result is checked from this process against the same binding before the record and password are written, and the Store's open connections in this process are closed | `InvalidInput`, `Exists`, `Unavailable`, `Denied`, `Conflict` | [`connect.rs`](../../../../control/crates/layerfs-store/src/postgresql/connect.rs), [`layerfs-control/src/store.rs`](../../../../control/crates/layerfs-control/src/store.rs) `connect` | | `store.disconnect` | forgets the Store, its saved password and its attachments; its data stays | `InvalidInput` for sqlite (`store remove`); `InUse` while leased or a Sandbox uses it | same | -| `store.attach --machine ` | checks the Store from the machine with the saved URL and login (in this process on a locally executing machine, else through the worker's `store.reach`): the server answers, its schema holds this Store, and the role has what a Sandbox's reads and writes need (the schema's `USAGE` and `CREATE`, the database's `TEMP`, each table's and sequence's privileges; never what only a compaction needs, which `store compact` checks itself); the machine's platform must run PostgreSQL Sandboxes. Only then is `` added to the record's `attached` list and its reach recorded; an attached machine is checked again (`checked`) | `InvalidInput` (sqlite, `native`), `NotFound`, `Unsupported`, `Unavailable`, `Denied`, `Conflict` | [`check.rs`](../../../../control/crates/layerfs-store/src/postgresql/check.rs) `attach`, [`layerfs-control/src/store.rs`](../../../../control/crates/layerfs-control/src/store.rs) `attach` | +| `store.attach --machine ` | checks the Store from the machine with the saved URL and login (in this process on a locally executing machine, else through the worker's `store.reach`): the server answers, its schema holds this Store, and the role has what a Sandbox's reads and writes need (the schema's `USAGE` and `CREATE`, the database's `TEMP`, each table's and sequence's privileges; never what only a compaction needs, which `store compact` checks itself); the machine's platform must run PostgreSQL Sandboxes. Only then is `` added to the record's `attached` list and its reach recorded; an attached machine is checked again (`checked`) | `InvalidInput` (sqlite), `NotFound`, `Unsupported`, `Unavailable`, `Denied`, `Conflict` | [`check.rs`](../../../../control/crates/layerfs-store/src/postgresql/check.rs) `attach`, [`layerfs-control/src/store.rs`](../../../../control/crates/layerfs-control/src/store.rs) `attach` | | `store.detach --machine ` | removes `` from `attached` and forgets its reach, under the home lock and the Store's, once no Sandbox of the Store's projects is on it | `InUse` (counted and named, with the removals as `fix`), `NotFound` (not attached), `InvalidInput` | [`check.rs`](../../../../control/crates/layerfs-store/src/postgresql/check.rs) `detach`, [`inventory.rs`](../../../../control/crates/layerfs-control/src/inventory.rs) `store_idle_on` | | Store calls | open the schema in this process with the URL resolved now | — | [`open.rs`](../../../../control/crates/layerfs-store/src/postgresql/open.rs) | | Host read session | one read-only session per process for Sandbox host operations: a create's reach check and a status's head read, on every route; opened with the light check on first read, checked with one empty query before each use (a dead one is replaced, not retried), closed after 60 s unused | — | [`reader.rs`](../../../../control/crates/layerfs-store/src/postgresql/reader.rs) | -A PostgreSQL Store is on no machine. Its Sandboxes run on `native` and on -every attached machine whose platform runs PostgreSQL Sandboxes (#536 C4); -`sandbox.create` on a machine that is not attached is refused +A PostgreSQL Store is on no machine. Its Sandboxes run on every attached +machine whose platform runs PostgreSQL Sandboxes (#536 C4). This computer +is the control process (home, records, secrets, the saved connection); it +is never a machine. Machine native is the built-in machine whose platform +runs Sandboxes directly on the host OS; what it allows (a shared loopback, +a local executor) comes from its platform, not its name, and it runs a +Store's Sandboxes only once attached. `store connect` attaches nothing. +With no `--machine`, `sandbox.create` uses the one attached machine (none +attached is refused with the attach as its fix; several are listed in +`next.machines` and one must be named). `sandbox.create` on a machine +that is not attached is refused `InvalidInput` with `layerfs store attach --machine ` as its fix, and on an attached one still checks from the machine that it reaches this Store. A record is read as it is: there is no migration and no state for a record @@ -169,7 +177,9 @@ Writers: `store.attach` (its check), `store.doctor` (this computer, measured with the same check, then every attached machine, or `--machine` alone) and a Sandbox create on a machine (`{ at, ok: true }`, on the host after the reply, [`route.rs`](../../../../control/crates/layerfs-sandbox/src/route.rs) -`reach`). `native` dials as this computer and is recorded as `here`. A +`reach`). `here` is this computer, the process that holds the connection; +machine native's reach is `reach.native`, like any machine's, and neither +is read as the other. A writer runs after its Store I/O, under the Store's lock, and writes nothing once the record is gone; a write never fails its call and moves no `generation`. `connect.rs` reads it back: `reach` (this computer's) and diff --git a/docs/versioned/2.0.0/calls.md b/docs/versioned/2.0.0/calls.md index f10ddbc379..4d560a5068 100644 --- a/docs/versioned/2.0.0/calls.md +++ b/docs/versioned/2.0.0/calls.md @@ -817,8 +817,9 @@ alias: `sandbox.close` (now `remove`) and `logs.sandbox` (now `log`); the with its `op` (`create`, #536 §7.1); its success records the result and drops the `op` in one write, a refused start removes the record. A name taken anywhere in the home is `Exists`. With no `machine` it runs on its - sqlite Store's machine, else on `native`; another machine than a sqlite - Store's is `Unsupported`. Its short answer is `{"ok":true}`, or with + sqlite Store's machine, or on the one machine attached to its PostgreSQL + Store (none or several attached: refused, [below](#store-11)); another + machine than a sqlite Store's is `Unsupported`. Its short answer is `{"ok":true}`, or with `--mount B` the Workspace's `workspace` (its name is the Branch's, lowercased, each other character `-`) and `path`. A refused mount keeps the Sandbox and answers the mount's refusal with `next.sandbox` and @@ -1362,12 +1363,17 @@ attached to the Store and dial with both. and its reach. Short `{ ok, outcome }` with `latency_ms`; long `ok, outcome (attached, or checked for an attached machine checked again), store, machine, latency_ms, server_version`. A sqlite Store is refused - `InvalidInput` naming `store move`; so is `native`, which is this - computer and needs no attaching. A machine that reaches the server only + `InvalidInput` naming `store move`. Machine native is attached like any + other, its platform deciding whether a loopback URL is allowed, and its + reach is its own, apart from this computer's; `connect` attaches + nothing. A machine that reaches the server only through this computer's loopback is refused with advice to connect the Store again with an address the machine reaches. `sandbox create` on a machine that is not attached is refused `InvalidInput` with `layerfs - store attach --machine ` as its fix. + store attach --machine ` as its fix; with no + `--machine` it uses the one attached machine (none: the same refusal + naming ``; several: `InvalidInput` listing them in + `next.machines`). - **`detach --machine M`** long `ok, outcome: "detached", store, machine`; forgets `M`'s reach. Refused `InUse` while a Sandbox of the Store's projects is on `M` (counted and named, the removals as `fix`), `NotFound` @@ -1510,7 +1516,7 @@ $ layerfs store move shop native ``` PostgreSQL, against a local `postgres:17` (macOS, native; this build's -outputs, run 2026-11-24 on a scratch home): +outputs, run 2026-11-24 on a scratch home after the machine native correction): ```console $ layerfs store connect shop-pg 'postgresql://postgres:pw@127.0.0.1:55437/shop' @@ -1523,17 +1529,25 @@ $ layerfs store get shop-pg {"engine":"postgresql","state":"ready","url":"postgresql://127.0.0.1:55437/shop?sslmode=disable","user":"postgres"} $ layerfs store connect shop-pg 'postgresql://127.0.0.1:55437/shop?sslmode=disable' --synchronous-commit off --detail {"ok":true,"projects":null,"projects_count":null,"outcome":"updated","store":"shop-pg","engine":"postgresql","url":"postgresql://127.0.0.1:55437/shop?sslmode=disable","user":"postgres","synchronous_commit":"off","machines":[]} +$ layerfs store doctor shop-pg --machine native +{"error":"InvalidInput","message":"machine native is not attached to PostgreSQL Store shop-pg","fix":"layerfs store attach shop-pg --machine native"} $ layerfs store attach shop-pg --machine native -{"error":"InvalidInput","message":"machine native is this computer, which every PostgreSQL Store is attached to; `layerfs store doctor shop-pg` checks it"} -$ layerfs store doctor shop-pg --machine lab -{"error":"InvalidInput","message":"machine lab is not attached to PostgreSQL Store shop-pg","fix":"layerfs store attach shop-pg --machine lab"} +{"outcome":"attached","latency_ms":1} +$ layerfs store attach shop-pg --machine native --detail +{"ok":true,"outcome":"checked","store":"shop-pg","machine":"native","latency_ms":1,"server_version":"17.11 (Debian 17.11-1.pgdg13+2)"} +$ layerfs store doctor shop-pg +{"ok":true} +$ layerfs store get shop-pg +{"engine":"postgresql","state":"ready","url":"postgresql://127.0.0.1:55437/shop?sslmode=disable","user":"postgres","machines":[{"machine":"native","reached":"ok"}]} +$ layerfs store detach shop-pg --machine native +{"ok":true} $ layerfs store disconnect shop-pg --detail {"ok":true,"outcome":"disconnected","store":"shop-pg"} ``` The URL above names `127.0.0.1`, which works only where the Sandbox's -machine shares this computer's loopback: `native` and `docker` on a Linux -Engine. On `docker` with Docker Desktop, `lima` or `apple-container`, +machine shares this computer's loopback: machine native on macOS and Linux +and `docker` on a Linux Engine. On `docker` with Docker Desktop, `lima` or `apple-container`, `store attach --machine` refuses it, naming what that machine calls this computer: connect the Store again with a host every attached machine reaches (`layerfs store connect shop-pg ''`). That check, like the diff --git a/docs/versioned/2.0.0/machines-and-stores.md b/docs/versioned/2.0.0/machines-and-stores.md index 2a8fb0c9f8..d30e047fa5 100644 --- a/docs/versioned/2.0.0/machines-and-stores.md +++ b/docs/versioned/2.0.0/machines-and-stores.md @@ -427,11 +427,13 @@ saved (owner, 2026-11-24). Machines are attached to the Store and dial with both; no machine has an address or a login of its own. The calls were run for this manual's [`store`](calls.md#store-11) section against a local `postgres:17` on macOS (`connect`, `list`, `get`, `attach`, `doctor`, -`disconnect`). In short: +`detach`, `disconnect`). In short: ```console $ printf '%s' "$PG_PASSWORD" | layerfs store connect shop-pg 'postgresql://127.0.0.1:55437/shop?sslmode=disable' --user postgres --password-stdin {"ok":true} +$ layerfs store attach shop-pg --machine native +{"outcome":"attached","latency_ms":1} $ layerfs project init shop-pg/load ./load # not run here $ layerfs store attach shop-pg --machine build-vm # not run: needs a reachable address $ layerfs store connect shop-pg 'postgresql://127.0.0.1:55437/shop?sslmode=disable' --synchronous-commit off @@ -491,8 +493,10 @@ $ layerfs store doctor shop-pg the Store: `M` must exist and its platform run PostgreSQL Sandboxes, and the Store is checked from `M` with the URL and login saved here before `M` is recorded as attached; the check is kept as `M`'s reach. Attaching - again checks again (`outcome: "checked"`). `native` is this computer and - needs no attaching. `store detach --machine M` removes it, + again checks again (`outcome: "checked"`). Machine native is attached + like any other (`store connect` attaches nothing); its platform decides + whether a loopback URL is allowed, and its reach is its own, apart from + this computer's. `store detach --machine M` removes it, refused while a Sandbox of the Store's projects is on `M`; `machine remove` detaches a machine from every Store. - **Who connects.** `store get` answers `reach` (this computer's) and @@ -511,9 +515,12 @@ $ layerfs store doctor shop-pg - `project init` into a PostgreSQL Store runs in the caller's process, under the Store's lease. PostgreSQL is built into every artifact. - A PostgreSQL Store is on no machine and has no default machine. A - Sandbox of it runs on `native` unless `sandbox create --machine M` names - a machine attached to it (refused `InvalidInput`, with `store attach` as - its fix, otherwise) whose platform runs PostgreSQL Sandboxes (`native` on + Sandbox of it runs on the machine `sandbox create --machine M` names, or, + with none named, on the one machine attached to the Store (none attached + is refused with `store attach` as its fix; several are listed and one + must be named). The machine must be attached to the Store (refused + `InvalidInput`, with `store attach` as its fix, otherwise) and its + platform must run PostgreSQL Sandboxes (`native` on macOS and Linux, `docker`, `lima`, `apple-container`); `sandbox create` checks from the machine that the server answers and holds this Store. The URL is dialled exactly as configured, never rewritten. On a machine From e9f9774f613c02543420c6fe45b02c26cc70a599 Mon Sep 17 00:00:00 2001 From: YifanXu1999 Date: Tue, 24 Nov 2026 16:37:08 +0800 Subject: [PATCH 3/4] store.connect records this computer's reach; machines answer loopback - store.connect (a first connect and an update) records its own check as this computer's reach (`here` in the Store's observation file, the record store.doctor writes): ok, with how long the check took. It is written only after the connect is saved; a refused connect records nothing. store.get's `reach` is no longer "not checked" right after a connect. - machine.list items and machine.get answer a read-only `loopback`: `shared` or `apart`, from the platform adapter's `Loopback` (layerfs_platform::shares_loopback); null for a removed platform or a record that describes no machine. Long form, after `supports`. Clients read it instead of testing platform names. Tests: postgres_login (reach after a first connect and an update; a refused connect leaves observed.json unchanged), machine_calls (native shared; docker apart off Linux), machine_removed_platforms (null). No test deleted. Docs: api/sdk/machine.md, api/sdk/store.md, control sqlite-and-postgresql.md, versioned calls.md; call spec machine.get and machine.list long keys. Production LOC: 211308 -> 211342 (delta +34) core 42163 -> 42163 (0), engine 97424 -> 97424 (0), control 61455 -> 61487 (+32), api 10266 -> 10268 (+2); reference absent (retired R9c; last counted 65,417 at tree 498dd1917812). Method: python3 tools/production_loc.py --root on `git archive` of the parent ebf6697a79 and `git checkout-index -a` of the staged tree; nonblank, non-comment product source, tests, docs, tools and generated stubs excluded. Co-Authored-By: Claude Opus 5.5 --- api/crates/layerfs-api/src/machine/get.rs | 1 + api/crates/layerfs-api/src/machine/list.rs | 1 + api/crates/layerfs-api/tests/machine_calls.rs | 5 ++++ .../tests/machine_removed_platforms.rs | 5 ++++ .../layerfs-api/tests/postgres_login.rs | 16 ++++++++++++ control/crates/layerfs-machine/src/list.rs | 18 ++++++++++++- control/crates/layerfs-platform/src/lib.rs | 4 +-- .../layerfs-platform/src/setup/calls.rs | 10 ++++++++ .../crates/layerfs-platform/src/setup/mod.rs | 4 +-- .../layerfs-store/src/postgresql/connect.rs | 25 ++++++++++++++++--- core/docs/issues/call-surface-2-0/calls.json | 2 ++ .../call-surface-2-0/families/machine.json | 2 ++ docs/architecture/api/sdk/machine.md | 7 +++++- docs/architecture/api/sdk/store.md | 8 ++++-- .../sqlite-and-postgresql.md | 3 ++- docs/versioned/2.0.0/calls.md | 14 +++++++---- 16 files changed, 108 insertions(+), 17 deletions(-) diff --git a/api/crates/layerfs-api/src/machine/get.rs b/api/crates/layerfs-api/src/machine/get.rs index 984b3a4936..e854279c85 100644 --- a/api/crates/layerfs-api/src/machine/get.rs +++ b/api/crates/layerfs-api/src/machine/get.rs @@ -27,6 +27,7 @@ const FORM: Form = Form::of( "machine", "backend", "supports", + "loopback", "cpus", "memory_bytes", "disk_bytes", diff --git a/api/crates/layerfs-api/src/machine/list.rs b/api/crates/layerfs-api/src/machine/list.rs index 0b0eb0aa94..e50b2cc4dc 100644 --- a/api/crates/layerfs-api/src/machine/list.rs +++ b/api/crates/layerfs-api/src/machine/list.rs @@ -30,6 +30,7 @@ const ITEM: Form = Form::of( "observed_at", "backend", "supports", + "loopback", "cpus", "memory_bytes", "disk_bytes", diff --git a/api/crates/layerfs-api/tests/machine_calls.rs b/api/crates/layerfs-api/tests/machine_calls.rs index 44f648910f..2e0b7a5e43 100644 --- a/api/crates/layerfs-api/tests/machine_calls.rs +++ b/api/crates/layerfs-api/tests/machine_calls.rs @@ -70,6 +70,11 @@ fn machines_over_records() { // worker: `docker` here, never `native` (layerfs-project#178) let worker = machine.get_text("machine") == Some("docker"); assert_eq!(supports(machine, "log"), worker, "{machine:?}"); + // whether it shares this computer's loopback is its platform + // adapter's answer: native's always, docker's only on a Linux Engine + let shared = !worker || cfg!(target_os = "linux"); + let loopback = if shared { "shared" } else { "apart" }; + assert_eq!(machine.get_text("loopback"), Some(loopback), "{machine:?}"); } // the support table for this host, each row with its live probe // (`home get --with platforms`, `machine.platforms` before 2.0) diff --git a/api/crates/layerfs-api/tests/machine_removed_platforms.rs b/api/crates/layerfs-api/tests/machine_removed_platforms.rs index fd64e42b1c..9ba9679918 100644 --- a/api/crates/layerfs-api/tests/machine_removed_platforms.rs +++ b/api/crates/layerfs-api/tests/machine_removed_platforms.rs @@ -46,6 +46,11 @@ fn shows_removed(machine: &SdkValue, platform: &str, reason: &str) { assert_eq!(machine.get_text("fix"), Some(fix.as_str())); assert_eq!(machine.get_text("message"), Some(reason), "{machine:?}"); assert_eq!(machine.get("supports"), Some(&SdkValue::List(Vec::new()))); + assert_eq!( + machine.get("loopback"), + Some(&SdkValue::Null), + "{machine:?}" + ); } #[test] diff --git a/api/crates/layerfs-api/tests/postgres_login.rs b/api/crates/layerfs-api/tests/postgres_login.rs index ab32e81b26..e6681df121 100644 --- a/api/crates/layerfs-api/tests/postgres_login.rs +++ b/api/crates/layerfs-api/tests/postgres_login.rs @@ -190,6 +190,12 @@ fn connect_checks_and_saves_the_login_and_a_reconnect_keeps_what_it_is_not_given assert_eq!(got.get_text("synchronous_commit"), Some("local")); assert_eq!(got.get("machines"), Some(&SdkValue::List(vec![]))); assert!(got.get("auth").is_none() && got.get("connections").is_none()); + // the connect's own check is this computer's reach, as the doctor's is + let here = |got: &SdkValue| got.get("reach").cloned().unwrap_or_default(); + let reach = here(&got); + assert_eq!(reach.get("ok"), Some(&SdkValue::Bool(true)), "{got:?}"); + assert!(reach.get_int("latency_ms").is_some(), "{got:?}"); + let first_at = reach.get_text("at").unwrap().to_owned(); // a reconnect with the setting alone keeps the user and password let updated = long( &home, @@ -208,6 +214,12 @@ fn connect_checks_and_saves_the_login_and_a_reconnect_keeps_what_it_is_not_given got.get_text("password_changed_at"), Some(changed_at.as_str()) ); + // an update records its check too + let reach = here(&got); + assert_eq!(reach.get("ok"), Some(&SdkValue::Bool(true)), "{got:?}"); + assert!(reach + .get_text("at") + .is_some_and(|at| at >= first_at.as_str())); let first = std::fs::read(&file).unwrap(); // a new password is saved long( @@ -226,7 +238,10 @@ fn connect_checks_and_saves_the_login_and_a_reconnect_keeps_what_it_is_not_given // new values that reach another Store, or no Store at all, are refused // and nothing is written let record = || std::fs::read(paths::store_record(&home, "pg")).unwrap(); + let seen_file = paths::store_record(&home, "pg").with_file_name("observed.json"); + let seen = || std::fs::read(&seen_file).unwrap(); let before = (record(), std::fs::read(&file).unwrap()); + let seen_before = seen(); for (address, why) in [(&other, "holds another Store than pg"), (&empty_db, "")] { let (code, message) = call( &home, @@ -241,6 +256,7 @@ fn connect_checks_and_saves_the_login_and_a_reconnect_keeps_what_it_is_not_given assert_ne!(code, "InvalidInput", "{message}"); assert!(message.contains(why), "{message}"); assert_eq!((record(), std::fs::read(&file).unwrap()), before); + assert_eq!(seen(), seen_before, "a refused connect records no reach"); } // a URL holding a login is refused on a connected Store too let (code, _) = call( diff --git a/control/crates/layerfs-machine/src/list.rs b/control/crates/layerfs-machine/src/list.rs index 0a3bd23440..2ec44da383 100644 --- a/control/crates/layerfs-machine/src/list.rs +++ b/control/crates/layerfs-machine/src/list.rs @@ -21,9 +21,23 @@ fn names(items: &[String]) -> (SdkValue, SdkValue) { layerfs_home::helpers::shown(names, 0, false) } +/// Whether the machine shares this computer's loopback, as its platform's +/// adapter declares it: `shared` or `apart`; null for a removed platform or +/// a record that describes no machine. +fn loopback(home: &Path, record: &MachineRecord) -> SdkValue { + if record.removed().is_some() { + return SdkValue::Null; + } + match super::spec::provider_spec(home, record) { + Ok(spec) if layerfs_platform::shares_loopback(&spec) => SdkValue::text("shared"), + Ok(_) => SdkValue::text("apart"), + Err(_) => SdkValue::Null, + } +} + /// The machine as `machine.get` and each `machine.list` item show it: /// `platform`, `state` with its companion, `observed_at`, then what its -/// record holds (`machine`, `backend`, `supports`, its size, images and +/// record holds (`machine`, `backend`, `supports`, `loopback`, its size, images and /// settings, `message`, `created_at`) and what is on it (`stores`, /// `sandboxes`, each with its count when cut). /// @@ -55,6 +69,7 @@ pub(super) fn summary( ) } }; + let loopback = loopback(home, record); let file = paths::machine_record(home, record.name()); let (state, message, observed) = match seen { // a VM a live read found gone shows the line that removes what is @@ -110,6 +125,7 @@ pub(super) fn summary( fields.push(("machine", SdkValue::text(record.name()))); fields.push(("backend", backend)); fields.push(("supports", supports)); + fields.push(("loopback", loopback)); for key in SETTINGS { fields.push((key, of(key).unwrap_or_default())); } diff --git a/control/crates/layerfs-platform/src/lib.rs b/control/crates/layerfs-platform/src/lib.rs index df4beeb0fe..9ca091ae5a 100644 --- a/control/crates/layerfs-platform/src/lib.rs +++ b/control/crates/layerfs-platform/src/lib.rs @@ -37,8 +37,8 @@ pub use probe::{native_missing, probe, Probe}; pub use setup::find_tool; pub use setup::{ cached_image, copy_in, copy_out, create, data_volume, forward, forward_close, load_image, - loopback_hint, name_limit, provider_within, reach, remove, start, status, status_within, stop, - stop_force, worker_port, State, Status, + loopback_hint, name_limit, provider_within, reach, remove, shares_loopback, start, status, + status_within, stop, stop_force, worker_port, State, Status, }; pub use spec::{ parse_size, search_path, tool_fallbacks, Bundle, Endpoint, Forward, Lasting, NameLimit, diff --git a/control/crates/layerfs-platform/src/setup/calls.rs b/control/crates/layerfs-platform/src/setup/calls.rs index c4bf90b852..6e7ca8ee8d 100644 --- a/control/crates/layerfs-platform/src/setup/calls.rs +++ b/control/crates/layerfs-platform/src/setup/calls.rs @@ -231,6 +231,16 @@ pub fn reach(spec: &Spec, store: &str, url: &str) -> Result bool { + matches!( + adapter(spec.kind).loopback(spec), + crate::reach::Loopback::Shared + ) +} + /// What a failed connection to Store `store` at `url` from `spec`'s machine /// adds for its user, where it may be a loopback the machine does not /// share: `Some` only on such a machine and only when the URL names a host diff --git a/control/crates/layerfs-platform/src/setup/mod.rs b/control/crates/layerfs-platform/src/setup/mod.rs index fff4d38b94..73d3dc3c6c 100644 --- a/control/crates/layerfs-platform/src/setup/mod.rs +++ b/control/crates/layerfs-platform/src/setup/mod.rs @@ -10,7 +10,7 @@ pub(crate) mod worker; pub(crate) use calls::with_worker; pub use calls::{ cached_image, copy_in, copy_out, create, data_volume, forward, forward_close, load_image, - loopback_hint, name_limit, provider_within, reach, remove, start, status, status_within, stop, - stop_force, worker_port, State, Status, + loopback_hint, name_limit, provider_within, reach, remove, shares_loopback, start, status, + status_within, stop, stop_force, worker_port, State, Status, }; pub use tool::find_tool; diff --git a/control/crates/layerfs-store/src/postgresql/connect.rs b/control/crates/layerfs-store/src/postgresql/connect.rs index 8a09d82fcd..9f2de3b308 100644 --- a/control/crates/layerfs-store/src/postgresql/connect.rs +++ b/control/crates/layerfs-store/src/postgresql/connect.rs @@ -209,7 +209,8 @@ pub fn run(home_dir: &Path, request: &StoreConnect) -> Outcome { /// and a new id or reads the id the schema holds, and lists its projects, /// before the home lock; the lock covers the re-checks and the writes /// only: the record, then the password. A database whose id another -/// Store of this home holds is `Exists`. +/// Store of this home holds is `Exists`. Once saved, the check's reach is +/// this computer's (`here`); a refused connect records nothing. pub fn connect(home_dir: &Path, request: &StoreConnect) -> Outcome { let name = request.store.as_str(); let given_url = request.url.as_str(); @@ -242,11 +243,13 @@ pub fn connect(home_dir: &Path, request: &StoreConnect) -> Outcome { binding: layerfs_home::helpers::random()?.to_vec(), cursor_key: layerfs_home::helpers::random()?, }; + let started = std::time::Instant::now(); let binding = if crate::project::postgres_init::create_schema(&probe, &fresh)? { fresh.binding } else { crate::postgresql::open::read_binding(&probe)? }; + let reach = measured(started); unclaimed_by_others(home_dir, name, &binding)?; let record = record.with("binding", SdkValue::Bytes(binding.clone())); let record = record.with("cursor", SdkValue::Bytes(fresh.cursor_key.to_vec())); @@ -255,7 +258,7 @@ pub fn connect(home_dir: &Path, request: &StoreConnect) -> Outcome { // schema that does not open is not connected let open = OpenArgs::dialled(home_dir, name, &record, probe); let listed = crate::service::with_service(&open, |service| listing::listed(service, false))?; - let _lock = home::lock::take(home_dir)?; + let lock = home::lock::take(home_dir)?; if paths::store_record(home_dir, name).exists() { return Err(refused("Exists", format!("a Store named {name} exists"))); } @@ -269,9 +272,22 @@ pub fn connect(home_dir: &Path, request: &StoreConnect) -> Outcome { ProjectRecord::found(name, &project.name, stack).write(home_dir)?; projects.push(project.name); } + drop(lock); + crate::observed::record(home_dir, name, None, &reach); Ok(answer(&record, "connected", Some(&projects))) } +/// This computer's reach from a connect's own check, begun at `started`: +/// reached, with how long the check took. It is recorded only once the +/// connect is saved, as `store.doctor` records its check (`here`). +fn measured(started: std::time::Instant) -> crate::observed::Reach { + crate::observed::Reach { + ok: true, + latency_ms: Some(i64::try_from(started.elapsed().as_millis()).unwrap_or(i64::MAX)), + ..crate::observed::Reach::default() + } +} + /// `store.connect` of a connected Store: its address `request.url`, and /// any of a new user, password and `synchronous_commit` (those not given /// are kept). The new values are dialled once from this process and must @@ -280,7 +296,7 @@ pub fn connect(home_dir: &Path, request: &StoreConnect) -> Outcome { /// the home lock and the Store's, `Conflict` when it was disconnected or /// connected to another database meanwhile; this process's open sessions /// on it are closed. A running Sandbox keeps the connection it started -/// with. +/// with. Once saved, the check's reach is this computer's (`here`). pub fn update(home_dir: &Path, request: &StoreConnect) -> Outcome { let name = request.store.as_str(); let record = super::check::postgresql_record(home_dir, name)?; @@ -322,12 +338,14 @@ pub fn update(home_dir: &Path, request: &StoreConnect) -> Outcome { }; let trial = changed(record.clone()); let probe = selection_at(&trial, with_login(&request.url, &user, &password)?); + let started = std::time::Instant::now(); super::check::same_store(&trial, &probe).map_err(|refusal| { refused( &refusal.code, format!("PostgreSQL Store {name}: {}", refusal.message), ) })?; + let reach = measured(started); let home_lock = home::lock::take(home_dir)?; let store_lock = crate::record::lock(home_dir, name)?; let current = StoreRecord::read(home_dir, name)?.filter(|r| r.binding() == record.binding()); @@ -345,6 +363,7 @@ pub fn update(home_dir: &Path, request: &StoreConnect) -> Outcome { login::save(home_dir, name, password)?; } drop((store_lock, home_lock)); + crate::observed::record(home_dir, name, None, &reach); Ok(answer(¤t, "updated", None)) } diff --git a/core/docs/issues/call-surface-2-0/calls.json b/core/docs/issues/call-surface-2-0/calls.json index 79f7383c37..72c2c3cccd 100644 --- a/core/docs/issues/call-surface-2-0/calls.json +++ b/core/docs/issues/call-surface-2-0/calls.json @@ -6040,6 +6040,7 @@ "observed_at", "backend", "supports", + "loopback", "cpus", "memory_bytes", "disk_bytes", @@ -6135,6 +6136,7 @@ "machine", "backend", "supports", + "loopback", "cpus", "memory_bytes", "disk_bytes", diff --git a/core/docs/issues/call-surface-2-0/families/machine.json b/core/docs/issues/call-surface-2-0/families/machine.json index f6c76da29a..5ad5404ddc 100644 --- a/core/docs/issues/call-surface-2-0/families/machine.json +++ b/core/docs/issues/call-surface-2-0/families/machine.json @@ -70,6 +70,7 @@ "observed_at", "backend", "supports", + "loopback", "cpus", "memory_bytes", "disk_bytes", @@ -166,6 +167,7 @@ "machine", "backend", "supports", + "loopback", "cpus", "memory_bytes", "disk_bytes", diff --git a/docs/architecture/api/sdk/machine.md b/docs/architecture/api/sdk/machine.md index 68559db9a6..05c1c80587 100644 --- a/docs/architecture/api/sdk/machine.md +++ b/docs/architecture/api/sdk/machine.md @@ -81,7 +81,7 @@ Python layerfs.machine.list(*, with_=None) | short | `items` | | long | `items` | | `items[]` short | `machine`, `platform`; when set: `state`, `op`, `reason`, `fix`, `observed_at` | -| `items[]` long | `machine, platform, state, op, reason, fix, observed_at, backend, supports, cpus, memory_bytes, disk_bytes, image, os_image, docker, wsl, daemon, message, stores, stores_count, sandboxes, sandboxes_count, created_at` | +| `items[]` long | `machine, platform, state, op, reason, fix, observed_at, backend, supports, loopback, cpus, memory_bytes, disk_bytes, image, os_image, docker, wsl, daemon, message, stores, stores_count, sandboxes, sandboxes_count, created_at` | | `items[].supports[]` short | each a `support` | | `items[].stores[]` short | each a `store` | | `items[].sandboxes[]` short | each a `sandbox` | @@ -104,6 +104,11 @@ The long row: `backend` is the Sandbox backend on this host (`native`, is a list of words: `sqlite`, `postgresql_sandbox`, and `log` when the machine has a worker whose log can be read (clients read this and never test platform names; [`support.rs`](../../../../control/crates/layerfs-platform/src/support.rs)); +`loopback` is `shared` when the machine shares this computer's loopback (a +PostgreSQL URL naming it is dialled there as given) and `apart` when it does +not, as the platform's adapter declares it (`Loopback`, +[`reach.rs`](../../../../control/crates/layerfs-platform/src/reach.rs)), null +for a removed platform or a record that describes no machine; `cpus`, `memory_bytes`, `disk_bytes` are the recorded size (null on a built-in machine); `stores` and `sandboxes` list the first 20 names, each count only past those diff --git a/docs/architecture/api/sdk/store.md b/docs/architecture/api/sdk/store.md index baf30d7c25..00869e5c64 100644 --- a/docs/architecture/api/sdk/store.md +++ b/docs/architecture/api/sdk/store.md @@ -153,7 +153,8 @@ engine's keys are null. `machines` lists each attached machine by name as `store//observed.json` (`here` and `reach.`, each `{ at, ok, latency_ms, server_version, error }`; [`observed.rs`](../../../../control/crates/layerfs-store/src/observed.rs)): -`store attach` records its check, `store doctor` each reach (this +`store connect` records its check as this computer's, `store attach` its +check from the machine, `store doctor` each reach (this computer's measured with the same check), and a Sandbox create on a machine `{ at, ok: true }` after its reply. A writer takes the Store's lock after its Store I/O and writes nothing once the record is gone; a live read's `at` @@ -321,7 +322,10 @@ On a connected Store `connect` changes its address, user, password or the server must be reached with the result and hold the same Store (its `binding`) before anything is saved. The Store's open connections in this process are closed; a running Sandbox keeps the connection it started with. -Short `{"ok":true}`, long `outcome` `updated`. Attachments are kept: each +Short `{"ok":true}`, long `outcome` `updated`. A connect that is saved, +first or not, records its check as this computer's reach (`store get`'s +`reach`: `ok` and how long the check took), as `store doctor` does; a +refused connect records nothing. Attachments are kept: each attached machine dials the new address and login from its next connection, and `store doctor` checks them. A sqlite Store of that name is `Exists`. diff --git a/docs/architecture/control/stores-and-projects/sqlite-and-postgresql.md b/docs/architecture/control/stores-and-projects/sqlite-and-postgresql.md index 71475075ae..57438038e2 100644 --- a/docs/architecture/control/stores-and-projects/sqlite-and-postgresql.md +++ b/docs/architecture/control/stores-and-projects/sqlite-and-postgresql.md @@ -173,7 +173,8 @@ in `store//observed.json` with the `at` a live read writes: `here` (this computer) and `reach.`, each `{ at, ok, latency_ms, server_version, error }` ([`observed.rs`](../../../../control/crates/layerfs-store/src/observed.rs)). -Writers: `store.attach` (its check), `store.doctor` (this computer, measured +Writers: `store.connect` (this computer's, from its own check once saved, +first connect or update), `store.attach` (its check), `store.doctor` (this computer, measured with the same check, then every attached machine, or `--machine` alone) and a Sandbox create on a machine (`{ at, ok: true }`, on the host after the reply, [`route.rs`](../../../../control/crates/layerfs-sandbox/src/route.rs) diff --git a/docs/versioned/2.0.0/calls.md b/docs/versioned/2.0.0/calls.md index 4d560a5068..3da49cc12f 100644 --- a/docs/versioned/2.0.0/calls.md +++ b/docs/versioned/2.0.0/calls.md @@ -1145,13 +1145,15 @@ positional `machine`, except `create`, which takes `name` and `platform`. provider tool's first line of `--version`) and `worker` (`{protocol, bundle}` as it answered), each null when not read. - **Item and long keys.** A `list` row and the `get` answer have `machine, - platform, state, op, reason, fix, observed_at, backend, supports, cpus, - memory_bytes, disk_bytes, image, os_image, docker, wsl, daemon, message, + platform, state, op, reason, fix, observed_at, backend, supports, + loopback, cpus, memory_bytes, disk_bytes, image, os_image, docker, wsl, daemon, message, stores, stores_count, sandboxes, sandboxes_count, created_at` (each list the first 20 names, its count only past those; `get` puts `platform` and `state` first). `supports` is a list of words: `sqlite`, `postgresql_sandbox`, and `log` when the machine has a worker whose log - can be read. + can be read. `loopback` is `shared` or `apart`: whether the machine + shares this computer's loopback, as its platform declares it (null for a + removed platform); clients read it and never test platform names. - **`start`, `stop`, `create`, `remove`** record their `op` in the machine's record before their first effect, move its `phase` as they go and report `{"progress":{"phase","done","total"}}` events: `start` `bundle`, @@ -1261,7 +1263,7 @@ $ layerfs machine list $ layerfs machine get docker --with live {"platform":"docker","state":"stopped","observed_at":"2026-11-18T15:34:11Z","live":{"tool_version":"29.5.2"}} $ layerfs machine get native --detail --with live -{"platform":"native","state":"ready","op":null,"reason":null,"fix":null,"observed_at":null,"machine":"native","backend":"native","supports":["sqlite","postgresql_sandbox"],"cpus":null,"memory_bytes":null,"disk_bytes":null,"image":null,"os_image":null,"docker":null,"wsl":null,"daemon":null,"message":null,"stores":["shop"],"stores_count":null,"sandboxes":[],"sandboxes_count":null,"created_at":"2026-11-18T15:34:11Z","live":{"disk_free_bytes":null,"tool_version":null,"worker":null}} +{"platform":"native","state":"ready","op":null,"reason":null,"fix":null,"observed_at":null,"machine":"native","backend":"native","supports":["sqlite","postgresql_sandbox"],"loopback":"shared","cpus":null,"memory_bytes":null,"disk_bytes":null,"image":null,"os_image":null,"docker":null,"wsl":null,"daemon":null,"message":null,"stores":["shop"],"stores_count":null,"sandboxes":[],"sandboxes_count":null,"created_at":"2026-11-18T15:34:11Z","live":{"disk_free_bytes":null,"tool_version":null,"worker":null}} $ layerfs machine start native {"unchanged":true} $ layerfs machine stats native @@ -1352,7 +1354,9 @@ attached to the Store and dial with both. Store `connect` changes its address, user, password or `synchronous_commit`: an omitted user or password keeps the saved one, and the result must reach the same Store (its binding) before anything - is saved; `projects` is null. Attachments are kept. + is saved; `projects` is null. Attachments are kept. A connect that is + saved, first or not, records its check as this computer's reach (`get`'s + `reach`), as `store doctor` does; a refused one records nothing. - **`disconnect`** long `ok, outcome: "disconnected", store`; it forgets the Store's saved password and attachments too. Refused `InUse` while a Sandbox or Workspace uses the Store. From 2f81c3d1f74d1dc8d52511708a5ee5f60411220b Mon Sep 17 00:00:00 2001 From: YifanXu1999 Date: Tue, 24 Nov 2026 18:06:44 +0800 Subject: [PATCH 4/4] home: store_file names the machine whose calls run in this process The doc comment said a sqlite Store's file sits in the home "while it is on native". The file is in the home while the Store is on the machine whose calls run in this process; native is only today's such machine. Comment only. Production LOC: 211342 -> 211342 (delta 0) Scope and method: tools/production_loc.py --root on the worktree before and after the edit (core/engine/control/api; reference absent, retired R9c; last counted 65,417 at tree 498dd1917812). Comment-only change. Co-Authored-By: Claude Opus 5.5 --- control/crates/layerfs-home/src/home/paths.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/control/crates/layerfs-home/src/home/paths.rs b/control/crates/layerfs-home/src/home/paths.rs index ac8c48d7ab..1d27f468f0 100644 --- a/control/crates/layerfs-home/src/home/paths.rs +++ b/control/crates/layerfs-home/src/home/paths.rs @@ -15,7 +15,8 @@ pub fn store_record(home: &Path, store: &str) -> PathBuf { store_dir(home, store).join("record.json") } -/// `store//store.sqlite`: a sqlite Store's file while it is on `native`. +/// `store//store.sqlite`: a sqlite Store's file while it is on the machine whose +/// calls run in this process. pub fn store_file(home: &Path, store: &str) -> PathBuf { store_dir(home, store).join("store.sqlite") }