~ knotless Search/
↑↓ move↵ open⇧↵ all results

socialweb.computer/socialweb-computer-kcp

socialweb.computer: a compute market on atproto (kcp)

1 collaborator
0
0

prod gate fixes: 0013 own-user rule, 0013:c mirror delete race and index check, submitAccept over iroh

Merged johnandersen777.bsky.social asked to merge into main from socialweb.computer/socialweb-computer-kcp:phase-2
docs/acceptance/0013-mixed-prod.md+7−4
@@ -31,7 +31,7 @@ sections 2, 5 and 7).
44 s after start, cluster c1 + kubeconfig 17 s, pod Ready 50 s after the apply (node `*-c1-node1` on hat-8),
`quickstart-k8s-ok`; delete Deployment: nodes 0 in 156 s, node records 6/6, `self` and `nodes-<hex>` mirrors gone, 0
ERROR
- C also reads the index: after nodes 0 `computer.socialweb.infra/self`'s `live` list must not name this run's Infra (the ended records themselves are kept); not yet run with that check; the controller reconciles the index (`infra_index_reconciled`: entries whose record ended or is missing are dropped from `live` at start and on each index write) (a 2-bidder dev net 2026-11-14 never got a Ready quickstart-k8s pod in 15 min: the k8s node did not join there)
- C also reads the index: after nodes 0 `computer.socialweb.infra/self` is the account's, not the run's (it holds every deployment of the DID, live or in `recentEnded`, and is deleted only when nothing is left in it), so C checks it apart from the run's records: it is gone, or neither its `live` nor its `recentEnded` names this run's `nodes-<hex>` and it is not empty; the run's own records, the `nodes-<hex>` mirror among them, must be RecordNotFound (2026-11-18, alice: `self` held 32 `recentEnded` entries of other deployments, so the old "self gone" read failed, as on 2026-11-14); not yet run with that check; the controller reconciles the index (`infra_index_reconciled`: entries whose record ended or is missing are dropped from `live` at start and on each index write) (a 2-bidder dev net 2026-11-14 never got a Ready quickstart-k8s pod in 15 min: the k8s node did not join there)
- Previous pass C: 2026-11-12 21:12-21:19Z, kcp e190a3b1 (rollout 19, rc165 candidate): 0 ERROR, the infra `self` and
`nodes-<hex>` mirror gone 20 s after nodes 0 (8e849b42). Before: 2026-11-12 20:02-20:10Z, kcp ac51b91e (rollout 18): node Ready, `quickstart-k8s-ok`, the requester logs 0
ERROR (no ComponentLink errors: fixed in 363dd814); nodes 0 in 156 s; but the emptied
@@ -81,7 +81,7 @@ sequenceDiagram
| Bidder DID | `MarketBidder app` `status.did` in the bidder kcp (the operator reads it); it replaces `REPLACE-BIDDER-DID` in every contract of `mixed-prod.yaml` |
| Bidder association | the bidder DID is its operator's agent: `agent-of/<operator DID>` in its DID doc (written by the bidder) and, in the operator repo, `market.association/<bidder DID>` then `link.ident.endorsement/<bidder DID>` (written by the bidder with `--bidder-operator-signin`, needs the optional scope `repo:link.ident.endorsement?action=create&action=delete`, or by `deno run -A --no-lock scripts/associate-bidder.ts --creds <file> --account <ACCOUNT> --agent-did <bidder DID>`); check: `socialweb-computer internal association <bidder DID>` roots [operator DID] |
| Requester account | a real atproto account (handle resolves to its DID, PDS public) signed in by OAuth QR; the creds file owner-only (mode 0600), read only by `scripts/oauth-signin.ts` |
| Vouches | both directions: requester -> bidder by [../../examples/infra/vouch.yaml](../../examples/infra/vouch.yaml) in the requester kcp (needs the optional scope `repo:sh.tangled.graph.vouch`) or `goat`; bidder operator -> requester by [../../examples/infra/vouch-bidder-operator.yaml](../../examples/infra/vouch-bidder-operator.yaml) in the bidder kcp (operator sign-in) or `goat` from the operator account |
| Vouches | both directions: requester -> bidder by [../../examples/infra/vouch.yaml](../../examples/infra/vouch.yaml) in the requester kcp (needs the optional scope `repo:sh.tangled.graph.vouch`) or `goat`; bidder operator -> requester by [../../examples/infra/vouch-bidder-operator.yaml](../../examples/infra/vouch-bidder-operator.yaml) in the bidder kcp (operator sign-in) or `goat` from the operator account, unless the requester account is that bidder's own user or one of the user's verified agents. Owner, 2026-11-18: "the vouch policy mode must also trust the own user and their associated DIDs/agents to N levels down". `bidder-tangled-vouch` (and `requester-tangled-vouch`) build the trust snapshot from the identlink walk of each party (`trust.BuildSnapshot`): each link verified both ways (the agent's DID doc `agent-of/<principal>`, the principal's `link.ident.endorsement/<agent>` and `com.publicdomainrelay.temp.market.association/<agent>`), N = 100 levels (`identlink.DefaultMaxDepth`), 256 lookups; a requester that shares a root with the bidder, or whose operator is on the bidder's side, is trusted (policytest cases `operated-by-counterparty`, `same-verified-operator`, `two-levels-below-counterparty`, `counterparty-two-levels-below-self(-operator)` and their forged and half-verified twins). The test runs, per bidder, the same walks of the account and of the bidder (`com.fedfork.exec.identlink.walk`) and reads the operator's vouch of the account; a bidder admits the account when that vouch exists or the walks say so |
| atirc | a token of your own (`atirc token <nick>`) to `atirc sub` the owner channel; never print it |
| Host | Linux, `kubectl`, `jq`, `ssh`, `dumbpipe` on PATH (the requester tries iroh first; a bidder without https, such as hat-9, is reached only over iroh or webrtc), the release or dev binary of the commit under test as `$SWC`; B: root on the requester host |
| Rules | [README.md](README.md) shared rules: announce on atirc first, one driver per account, release what you rent |
@@ -111,7 +111,8 @@ minutes before the first apply when a contract was denied before (verdicts are c
record with `goat record create` from the requester account instead.
4. Bidder operator -> requester vouch: in the bidder kcp, `vouch-bidder-operator.yaml` with `REPLACE-REQUESTER-DID` (the
operator sign-in of [../bidder.md](../bidder.md)), or `goat` from the operator account; check with `goat get
"at://<operator did>/sh.tangled.graph.vouch/<requester did>" | jq -r .kind` -> `vouch`. When the write needs the
"at://<operator did>/sh.tangled.graph.vouch/<requester did>" | jq -r .kind` -> `vouch`. Skip it for a bidder whose
user is the requester account or one of the account's operators (Preconditions, Vouches). When the write needs the
owner's account, it is owner-only: ask the owner to write it; an agent does not.
4b. agent1's harness (optional; without it the agent joins the mesh but nothing answers): write agent1's bundle into the
requester's own OpenBao before the apply, with the placeholder `/etc/atirc/atirc.env` and an atirc agent config (as
@@ -187,7 +188,9 @@ user (`check-host` reports it).
bidder: `kubectl patch marketbidders.socialweb.computer app --type merge -p '{"spec":{"suspend":true}}'` in its kcp,
resumed after).
5. `kubectl --kubeconfig "$TK" delete deployment quickstart-k8s`: the node is reaped, its contract released, `kubectl
get nodes` is empty (scale to zero); the bidder host is empty.
get nodes` is empty (scale to zero); the bidder host is empty; `computer.socialweb.infra/nodes-<hex>` answers
RecordNotFound; `computer.socialweb.infra/self` is gone, or names no `nodes-<hex>` of this run in `live` or
`recentEnded` and is not empty.
6. Ctrl-C the `run requester`.
## Expected Observations
docs/plans/0040-findings.md+87−0
@@ -1512,3 +1512,90 @@ Each: what was seen (with the log), the cause, the fix, its proof.
- CI test-4 at 7a0406d9, the cause found: 0005:b leaks. Its guest requester rents its own default-size VM; the entry
deletes the outer VM out of band; the guest requester dies without releasing; the bidder keeps the VM until the
association expires (accept + 24 h + 10 min); the entry passed on records alone. Owner decision 37.
- 0013:run FAIL on prod as bob (by-hand gate, 2026-11-18 18:24Z, build 7a0406d9, run
`0013-composition-1795026291310`): `no bidder operator vouches the account` 25 s after the start (628 s = that plus the
600 s freeze; no wait for a vouch). Cause: the module's precondition (`tests/modules/acc-0013/src/lib.rs`, the `mr`
step) read only `at://<bidder operator>/sh.tangled.graph.vouch/<account>`. Since 2026-11-17 every prod bidder (seven,
`deploy/release/rc-operators.json`) is bob's, and the entry runs as bob (`identity_mode` pdsAccount, renter = bob's DID;
the Rust port binds 0013 to `secondRequester`, bob on prod; every earlier prod pass was bob), so the only voucher read was
bob of bob: absent. Before 11-17 hat-7 was john's and john vouches bob, which hid it. The records (public, read
2026-11-18): bob vouches alice, socialweb.computer, john and one bidder, not himself; john vouches bob and alice; the seven
bidders vouch nobody; bob's repo endorses all seven (`link.ident.endorsement`), each DID doc `agent-of` bob. The product
admits bob anyway: `trust.BuildSnapshot` / `operatorsOf` (`internal/policyengine/trust/trust.go`) gives the requester the
root it shares with the bidder (bob's walk roots = [bob], the bidder's = [bob]), and `bidder-tangled-vouch` allows a
counterparty operated by a trusted operator (`operatedByTrusted`); in this same gate 0001, 0004, 0005, 0007, 0009 and
0012 rented as bob from these bidders. The owner's rule (2026-11-18): "the vouch policy mode must also trust the own
user and their associated DIDs/agents to N levels down". The product already does: the walk (`identlink.Walk`,
`internal/identlink/walk.go`) follows `agent-of` upward from each party, an edge only when the agent's DID doc says
`agent-of/<principal>` AND the principal's repo holds `link.ident.endorsement/<agent>` AND
`com.publicdomainrelay.temp.market.association/<agent>` (live, contract-scoped ones only while the contract is held);
N = `DefaultMaxDepth` 100 (walk.go:18, `trust.MaxChainDepth`, association.go:13, the cap for a run's
`spec.association.maxDepth`), budget 256 lookups (walk.go:19). `operatorsOf` (trust.go) gives both parties a shared
root, else the counterparty its first other root; `operatedByTrusted` trusts it when that is on the self side (self and
its ancestors). Bob's real walks today (`socialweb-computer internal association`): bob roots [bob]; each of the seven
bidders ancestors [bob], roots [bob]; alice roots [alice] (admitted by bob's vouch, not by the walk). Spec cases
added (`internal/policyengine/policytest/cases.go`; each runs both sides, both lanes, the matrix of tangled-vouch,
only-me, mutuals and open plus the bidder and requester decision sites, 52 runs a case), all PASS, so no product gap:
`operated-by-counterparty`, `two-levels-below-counterparty`, `counterparty-two-levels-below-self`,
`counterparty-two-levels-below-self-operator` (allowed), and the twins `forged-operated-by-counterparty`,
`operated-by-counterparty-without-grant`, `operated-by-counterparty-undeclared`, `forged-two-levels-below-counterparty`,
`forged-lower-link-`, `lower-link-without-grant-`, `forged-upper-link-`, `upper-link-without-endorsement-two-levels-below-self-operator`
(denied); "another agent of the same user" is the existing `same-verified-operator`. Fix (branch `rc-0013`): the
module and the Rust port walk the account and each bidder (`com.fedfork.exec.identlink.walk`, atlibs-identlink: the
same records, depth and budget, the vectors gate the parity) and admit the account when the bidder's operator vouches it
(a self-vouch is never read: `trust.vouchPairs`) or the walks give what `operatorsOf` + `operatedByTrusted` do; runbook
0013 Preconditions (Vouches) quotes the owner. No other entry has this precondition.
- 0014:abandon on prod: `sub: the offering names no https endpoint` (branch `submit-iroh`, off main 1b30bf9a). SEEN:
the hand prod gate on hat-8 (prod on main 7a0406d9, alice), 2026-11-18 ~19:20Z: `RESULT 0014:abandon FAIL 601 sub:
the offering names no https endpoint (alice)`. CAUSE: the same assumption as the ops routes (Finding "Step 11, the
prod target has no https market endpoint"): the host call `bidder.submitAccept` (`tests/host/src/more.rs`) took the
bidder's market endpoint as the `kind == "https"` address of its offering; prod bidders offer iroh and webrtc only.
FIX: one shared helper, `tests/testkit/src/irohfetch.rs` (`ticket`, `market_base`: an offering's https address
where it has one, else `iroh://<ticket>`; `request`: HTTP/1.1 over atlibs-iroh's raw fetch, one client per
process), used by `tests/host/src/ops.rs` (its own copy gone) and by `testkit::Atproto::service_call`, which now
takes an `iroh://<ticket>` base and sends the same method, path, query, service-auth bearer and JSON body over it.
`bidder.submitAccept` takes `market_base` of the offering. The other `"https"` picks under `tests/host/src`,
`tests/testkit/src` and `tests/modules/*/src`: `more.rs` `signin` and `page-round` filter the target's PLC, PDS and
relay URLs for an xrpc front's names, not a bidder endpoint, and run only off prod (`name != "prod"`); acc-0001
`s2.rs` asserts a staging bidder's offering is exactly {https, iroh, webrtc} (0001:s2, staging only): all left.
PROOF (hat-8, read-only): `submitAccept` POSTed over each of the 4 prod bidders' iroh market endpoints through
`irohfetch::request`: body `{}` -> 400 `InvalidRequest` "missing acceptUri or acceptCid"; a well-formed body for a
made-up accept with no bearer -> 401 `Unauthorized` "invalid service-auth token" (the bidder's admit, before any
record read); no accept created. The refactored `ops.rs` (through the probe that compiles it as is) on the same 4 bidders,
now on main 7a0406d9 with the routes: a dummy bearer 401 `AuthenticationRequired`, the real ops read secret (by path)
200 `getHealth` on all 4. `cargo check -p swc-test-host`, `cargo wasm` pass. To prove: 0014:abandon on prod as
alice from this tree (not run here: the hand gate held alice's slot; 0014 runs alone).
- BY-HAND PROD GATE ENDED 19:07Z (hat-8, gate dir ~/.tmp/prod-hand/gate-1, 5471 s, two at once, prod on rc180 = main
7a0406d9, the seven bidders, as bob and alice): `gate: prod: 25 of 30 PASS`. FAIL: 0002:run, 0011:token, 0013:run,
0013:c, 0014:abandon: each root-caused above. This is the lead's debug run, not a goal number. The ops routes over
iroh answered 200 with the real secret on the four hats' bidders (agent, read-only, 19:00Z).
- 0013:c as alice on prod (by-hand gate `~/.tmp/prod-hand/gate-1`, 7a0406d9, run
`~/.tmp/swc-system-tests/runs/0013-composition-1795026550298`): "records left after nodes 0: infra/self,
infra/nodes-e76e5ac7dd369a1b20c7" (1094 is the seconds). NOT CI's staging shares: the check is scoped to this run's
own URIs (the 5 `requester.records` read from the mk requester's logs), and alice's repo (PDS
jellybaby.us-east.host.bsky.network, read-only listRecords after the run) holds no infra or ephemeralInfra record from
today but this run's; the index's `live` is empty. Two causes:
- `self` is the account's index, not the run's: it is deleted only when nothing is left in it
(`infra.ApplyIndex`, Forget with live and recentEnded empty), and alice's holds 32 `recentEnded` entries of other
deployments (CI's prod-market staging EphemeralInfra `stg-*` of 11-13 to 11-15, page sessions, older nodes
mirrors). The entry asserted it RecordNotFound, true only on an account with no other history (bob, 11-12). The
2026-11-14 prod FAIL of 0013:c ("not root-caused" above; gate `~/.tmp/swc-system-tests/gate/20261114T134403Z`, alice)
was this alone: `left: [infra/self]`, its mirror was deleted. Fix (`rc-0013c`, module c entry and runbook): the run's
records exclude the index URI; the index check reads it after the records are gone: gone, or neither `live` nor
`recentEnded` names the run's `nodes-<hex>` and it is not empty (an empty one should have been deleted). Stricter
than before (recentEnded and the empty case were not read), not a loosening.
- `nodes-e76e5ac7dd369a1b20c7` is a real leak, a race in the infra controller's `dropMirror`
(`internal/controllers/infra/record.go`), the class of 8e849b42. requesters/mk/logs/core.log: 18:33:59.907Z
`infra_record_deleted` (swap cid ...bykulcgm), 18:33:59.919Z the child AtprotoRecord "wrote its declared record"
reason Repaired, cid bafyreidcnkg5...vkpumi, then `atprotorecord_retained` (infra is a kept collection). The PDS
holds exactly that cid (phase `released`, no endedAt). The child's reconcile had read the record before the delete
(Repaired = present and different) with its pre-hold spec, and its PutRecord landed after the swap delete,
recreating it; the hold (Retain, swapCid, the held value) pins only reconciles that start after it. Fix
(`rc-0013c`): dropMirror holds and deletes the child, then waits (not done, woken by the child's delete event,
which the Infra controller watches) until the AtprotoRecord is gone, and only then swap-deletes the record with a
fresh read: the runtime serializes reconciles per object, so no write of the child can follow. Unproven by a run.
- Left on alice's repo: `computer.socialweb.infra/nodes-e76e5ac7dd369a1b20c7` (the next 0013:c as alice reuses that
rkey and deletes it at its end; the lead may delete it now).
- Every other `both` entry scopes its "records left" check to its own run (recordsGone over its requester's URIs, or
noneSince with `since`: 0002, 0006); only 0013:c's requester writes `computer.socialweb.infra` (0012:run's and
0013:run's logs name no infra or ephemeralInfra URI), so no other entry reads the shared index.
docs/spec/integration-catalog.yaml+4−1
@@ -1519,7 +1519,10 @@ entries:
unvouched, vouched by self, vouched by a verified or a self-claimed self operator, verified or
forged counterparty operator, a claim for the other role, a direct vouch of an operated
counterparty, a reverse vouch only, mutual operator vouches, denounced, stranger vouches, same
verified operator, counterparty operated by self, forged same operator, different operators, and a
verified operator, counterparty operated by self, self operated by the counterparty (verified, forged, without
grant, undeclared), two levels below the counterparty (verified, forged), the counterparty two levels below self
or below self's operator (verified; forged or half-verified at the lower or the upper link), forged same
operator, different operators, and a
contract-scoped association held, expired, released or terminated.
asserts: the fixtures are deterministic; no case reads the network.
cleanup: each case has its own harness; nothing outlives the test.
internal/controllers/infra/record.go+18−13
@@ -603,7 +603,7 @@ func (r *reconciler[T]) finalWrite(ctx context.Context, req ctlruntime.Request,
return true, nil
}
if mirror(v) {
return true, r.dropMirror(ctx, req, v, ar, repo, rkey, got, attrs)
return r.dropMirror(ctx, req, v, ar, repo, rkey, got, attrs)
}
own := []string{strings.TrimSpace(stored.CID)}
if ar != nil && arInSync(ar) {
@@ -895,28 +895,33 @@ func mirror(v view) bool {
}
func (r *reconciler[T]) dropMirror(ctx context.Context, req ctlruntime.Request, v view, ar *v1alpha1.AtprotoRecord, repo commonv1.ObjectRef,
rkey string, got atprotorepo.Record, attrs []any) error {
rkey string, got atprotorepo.Record, attrs []any) (bool, error) {
cid := got.CID
dyn, err := r.c.dynamic(req.Workspace)
if err != nil {
return err
}
records := dyn.Resource(v1alpha1.AtprotoRecordGVR)
if ar != nil && ar.DeletionTimestamp.IsZero() {
if ar != nil {
if !ar.DeletionTimestamp.IsZero() {
return false, nil
}
dyn, err := r.c.dynamic(req.Workspace)
if err != nil {
return false, err
}
records := dyn.Resource(v1alpha1.AtprotoRecordGVR)
held := &v1alpha1.AtprotoRecord{TypeMeta: metav1.TypeMeta{APIVersion: v1alpha1.GroupVersion.String(), Kind: "AtprotoRecord"},
ObjectMeta: metav1.ObjectMeta{Name: ar.Name, Labels: ar.Labels, OwnerReferences: ar.OwnerReferences}, Spec: ar.Spec}
held.Spec.DeletionPolicy, held.Spec.SwapCid, held.Spec.Record = v1alpha1.RecordDeletionRetain, cid, got.Value
if _, err := kube.Apply[v1alpha1.AtprotoRecord](ctx, records, held, kube.ApplyOptions{FieldManager: r.manager, Force: true}); err != nil {
return fmt.Errorf("infra: holding the AtprotoRecord %s at cid %s: %w", ar.Name, cid, err)
return false, fmt.Errorf("infra: holding the AtprotoRecord %s at cid %s: %w", ar.Name, cid, err)
}
if err := records.Delete(ctx, ar.Name, metav1.DeleteOptions{}); err != nil && !apierrors.IsNotFound(err) {
return err
return false, err
}
r.c.log.Info("infra_record_mirror_unbinding", append(attrs, "atprotoRecord", ar.Name)...)
return false, nil
}
writer, err := bus.Resolve[atprotorepo.RecordWriter](ctx, r.c.bus, r.self(req), repo,
bus.Capability{Name: atprotorepo.CapabilityWrite, Scope: []string{v.kind.NSID()}})
if err != nil {
return err
return false, err
}
if d, ok := writer.(atprotorepo.SwapDeleter); ok {
err = d.DeleteRecordSwap(ctx, v.kind.NSID(), rkey, cid)
@@ -924,8 +929,8 @@ func (r *reconciler[T]) dropMirror(ctx context.Context, req ctlruntime.Request,
err = writer.DeleteRecord(ctx, v.kind.NSID(), rkey)
}
if err != nil && !errors.Is(err, atprotorepo.ErrNotFound) {
return fmt.Errorf("infra: deleting the cluster mirror record %s: %w", v.status.Record.URI, err)
return false, fmt.Errorf("infra: deleting the cluster mirror record %s: %w", v.status.Record.URI, err)
}
r.c.log.Info("infra_record_deleted", append(attrs, "reason", "the record mirrors the nodes of a cluster")...)
return nil
return true, nil
}
internal/policyengine/policytest/cases.go+53−0
@@ -82,6 +82,59 @@ var TrustCases = []TrustCase{
{Name: "counterparty-operated-by-self", OnlyMe: true, Vouch: true, Mutuals: true, Build: func(w *World, p Parties) {
w.Associate(p.CP, p.Self)
}},
{Name: "operated-by-counterparty", OnlyMe: true, Vouch: true, Mutuals: true, Build: func(w *World, p Parties) {
w.Associate(p.Self, p.CP)
}},
{Name: "forged-operated-by-counterparty", Build: func(w *World, p Parties) {
w.DeclareAgentOf(p.Self, p.CP)
}},
{Name: "operated-by-counterparty-without-grant", Build: func(w *World, p Parties) {
w.DeclareAgentOf(p.Self, p.CP)
w.Endorse(p.CP, p.Self)
}},
{Name: "operated-by-counterparty-undeclared", Build: func(w *World, p Parties) {
w.Endorse(p.CP, p.Self)
w.Grant(p.CP, p.Self)
}},
{Name: "two-levels-below-counterparty", OnlyMe: true, Vouch: true, Mutuals: true, Build: func(w *World, p Parties) {
w.Associate(p.Self, p.SelfOp)
w.Associate(p.SelfOp, p.CP)
}},
{Name: "forged-two-levels-below-counterparty", Build: func(w *World, p Parties) {
w.Associate(p.Self, p.SelfOp)
w.DeclareAgentOf(p.SelfOp, p.CP)
}},
{Name: "counterparty-two-levels-below-self", OnlyMe: true, Vouch: true, Mutuals: true, Build: func(w *World, p Parties) {
w.Associate(p.CP, p.CPOp)
w.Associate(p.CPOp, p.Self)
}},
{Name: "counterparty-two-levels-below-self-operator", OnlyMe: true, Vouch: true, Mutuals: true, Build: func(w *World, p Parties) {
w.Associate(p.Self, p.SelfOp)
w.Associate(p.CPOp, p.SelfOp)
w.Associate(p.CP, p.CPOp)
}},
{Name: "forged-lower-link-two-levels-below-self-operator", Build: func(w *World, p Parties) {
w.Associate(p.Self, p.SelfOp)
w.Associate(p.CPOp, p.SelfOp)
w.DeclareAgentOf(p.CP, p.CPOp)
}},
{Name: "lower-link-without-grant-two-levels-below-self-operator", Build: func(w *World, p Parties) {
w.Associate(p.Self, p.SelfOp)
w.Associate(p.CPOp, p.SelfOp)
w.DeclareAgentOf(p.CP, p.CPOp)
w.Endorse(p.CPOp, p.CP)
}},
{Name: "forged-upper-link-two-levels-below-self-operator", Build: func(w *World, p Parties) {
w.Associate(p.Self, p.SelfOp)
w.DeclareAgentOf(p.CPOp, p.SelfOp)
w.Associate(p.CP, p.CPOp)
}},
{Name: "upper-link-without-endorsement-two-levels-below-self-operator", Build: func(w *World, p Parties) {
w.Associate(p.Self, p.SelfOp)
w.DeclareAgentOf(p.CPOp, p.SelfOp)
w.Grant(p.SelfOp, p.CPOp)
w.Associate(p.CP, p.CPOp)
}},
{Name: "forged-same-operator", Build: func(w *World, p Parties) {
w.Associate(p.Self, p.SelfOp)
w.DeclareAgentOf(p.CP, p.SelfOp)
tests/host/src/more.rs+3−9
@@ -1018,7 +1018,7 @@ printf '{{"unit":"%s","current":%s,"high":"%s","max":"%s","swapMax":"%s","events
// the embedded build record in a copy of the binary and runs it
"assets.tamper" => self.assets_tamper(input).await,
// submitAccept of an accept record that does not exist (a requester that deleted its accept before the bidder read it): the
// account's service auth to the bidder's https endpoint (its offering), for at://<account>/market.accept/<rkey>
// account's service auth to the bidder's market endpoint (its offering: https, else iroh), for at://<account>/market.accept/<rkey>
"bidder.submitAccept" => {
let (Ok(name), Ok(rkey), Ok(cid)) = (
str_of(input, "name"),
@@ -1041,14 +1041,8 @@ printf '{{"unit":"%s","current":%s,"high":"%s","max":"%s","swapMax":"%s","events
.await
.map_err(|e| e.to_string())?
.ok_or("the bidder has no offering record")?;
let endpoint = offering["endpoints"]
.as_array()
.into_iter()
.flatten()
.find(|e| e["kind"] == "https")
.and_then(|e| e["address"].as_str())
.ok_or("the offering names no https endpoint")?
.to_string();
let endpoint = testkit::irohfetch::market_base(&offering)
.ok_or("the offering names no https or iroh market endpoint")?;
let uri = format!(
"at://{}/com.publicdomainrelay.temp.market.accept/{rkey}",
sess.did()
tests/host/src/ops.rs+7−21
@@ -4,8 +4,8 @@
//! (the fields the modules read), every write refused. One shared secret for every bidder and the gateway (owner): it is the target's `opsSecretFile` (0600), sent as the bearer and never logged.
//! A bidder's routes are on its market mux, reached over its market endpoint: https (`ops.url`) where its offering has
//! one, else iroh (`ops.iroh`, the `endpoint...` ticket of its market.offering record): the same GETs and bearer as
//! HTTP/1.1 over atlibs-iroh's raw fetch (`dumbpipe connect <ticket>`, the stream a requester's market calls take),
//! end-to-end encrypted to the iroh node the ticket names. The gateway's route is its https web origin.
//! HTTP/1.1 over atlibs-iroh's raw fetch (`testkit::irohfetch`: `dumbpipe connect <ticket>`, the stream a requester's
//! market calls take), end-to-end encrypted to the iroh node the ticket names. The gateway's route is its https web origin.
use std::collections::HashMap;
use std::sync::Arc;
@@ -50,11 +50,7 @@ impl Base {
(Some(u), None) if u.starts_with("https://") => Ok(Self::Https(u.trim_end_matches('/').to_string())),
(Some(u), None) => Err(format!("the ops route {u} is not https: the ops read secret is sent to https origins only")),
(None, Some(t)) => {
let t = t.strip_prefix("iroh://").unwrap_or(t);
match atlibs_iroh::raw_url(&format!("iroh://{t}/")) {
Some(Ok(_)) => Ok(Self::Iroh(t.to_string())),
_ => Err(format!("the ops iroh endpoint {t} is not an iroh endpoint ticket")),
}
testkit::irohfetch::ticket(t).map(Self::Iroh).ok_or(format!("the ops iroh endpoint {t} is not an iroh endpoint ticket"))
}
_ => Err("an ops endpoint is exactly one of url (https) and iroh".into()),
}
@@ -63,7 +59,6 @@ impl Base {
pub struct Ops {
http: reqwest::Client,
iroh: atlibs_iroh::Iroh,
secret: String,
bidders: HashMap<String, Base>,
gateway: Option<Base>,
@@ -92,9 +87,7 @@ impl Ops {
return Err(format!("{} is empty", path.display()));
}
let http = reqwest::Client::builder().timeout(Duration::from_secs(120)).build().map_err(|e| e.to_string())?;
// raw iroh fetches use no ssh key; the path is the host's iroh transport's
let iroh = atlibs_iroh::Iroh::new(testkit::home_tmp("iroh_ed25519"));
Ok(Some(Arc::new(Self { http, iroh, secret, bidders, gateway })))
Ok(Some(Arc::new(Self { http, secret, bidders, gateway })))
}
/// The bidder `name` is read through its ops routes.
@@ -115,19 +108,12 @@ impl Ops {
(status, res.json::<Value>().await.unwrap_or(Value::Null))
}
Base::Iroh(ticket) => {
let mut query = String::new();
if !params.is_empty() {
let mut u = reqwest::Url::parse("http://q/").map_err(|e| e.to_string())?;
u.query_pairs_mut().extend_pairs(params);
query = format!("?{}", u.query().unwrap_or_default());
}
let url = format!("iroh://{ticket}/xrpc/{NS}{method}{query}");
let target = format!("/xrpc/{NS}{method}{}", testkit::irohfetch::query(params));
let headers = vec![("authorization".to_string(), format!("Bearer {}", self.secret))];
let res = tokio::time::timeout(Duration::from_secs(120), self.iroh.http("GET", &url, headers, vec![]))
let (status, body) = testkit::irohfetch::request(ticket, "GET", &target, headers, vec![], Duration::from_secs(120))
.await
.map_err(|_| format!("{NS}{method}: no response over iroh in 120 s"))?
.map_err(|e| format!("{NS}{method}: {e}"))?;
(res.status, serde_json::from_slice(&res.body).unwrap_or(Value::Null))
(status, serde_json::from_slice(&body).unwrap_or(Value::Null))
}
};
if !(200..300).contains(&status) {
tests/modules/acc-0013/src/lib.rs+73−21
@@ -4,12 +4,31 @@
// DIDs tombstoned, hosts empty. c: `run requester --with-gateway`, cluster c1, k8s-cluster.yaml on a market node, scale
// to zero, the infra mirror records gone. b (root on a staging VM): `install requester`, Ready, a unit restart keeps
// the DID, uninstall.
use abi::{Event, Handle, Run, entries};
use abi::{Call, Event, Handle, Run, entries};
use serde_json::{Value, json};
use steps::{ASSOC, ENDORSE, MIN, S, host, kube, out, ready_pods, sw};
const CC: [&str; 3] = ["vm1", "sbx1", "agent1"];
fn walk(id: &str, agent: &str) -> Call {
Call::new(id, "com.fedfork.exec.identlink.walk").input(json!({ "agent": agent }))
}
fn dids(v: &Value) -> Vec<&str> {
v.as_array().map(|a| a.iter().filter_map(|x| x.as_str().or(x["did"].as_str())).collect()).unwrap_or_default()
}
// trust.BuildSnapshot's operatorsOf and the policies' operatedByTrusted, over the same identlink walks: the account is the
// bidder, or shares a root with it, or its operator (its first root that is not itself) is on the bidder's side
fn operated_by_trusted(account: &str, aw: &Value, bidder: &str, bw: &Value) -> bool {
let (ours, theirs) = (dids(&bw["roots"]), dids(&aw["roots"]));
let mut side = vec![bidder];
side.extend(dids(&bw["ancestors"]));
account == bidder
|| ours.iter().any(|r| theirs.contains(r))
|| theirs.iter().find(|r| **r != account).is_some_and(|op| side.contains(op))
}
fn mixed_prod(text: &str, key: &str) -> String {
text.lines().filter(|l| !l.contains("bidderDids:") && !l.contains("REPLACE-BIDDER-DID")).collect::<Vec<_>>().join("\n").replace("ssh-ed25519 AAAAREPLACE-WITH-YOUR-PUBLIC-KEY you@laptop", key.trim())
}
@@ -115,7 +134,7 @@ fn a_handler(run: Run<Value>) -> Result<Handle, String> {
Event::Result { id, result, .. } => {
let o = match out(&s, &id, result.output()) {
Ok(o) => o,
// a missing vouch is a value (the fan below counts the ones found): an operator need not vouch itself
// a missing record is a value (the fan below counts the ones found): an operator need not vouch itself
Err(f) if id == "eigone" || id.starts_with("vouch-") => {
let _ = f;
Value::Null
@@ -133,16 +152,28 @@ fn a_handler(run: Run<Value>) -> Result<Handle, String> {
if o["status"]["phase"] != "Ready" || o["status"]["did"] != s.st["renter"] {
return Ok(s.fail(format!("MarketRequester {}", o["status"])));
}
// a bidder operator vouches the account (else no bids): one getRecord per operator
s.st["fan"] = json!(bidders.len());
// some bidder's bidder-tangled-vouch admits the account (else no bids): its operator vouches the
// account, or the account is the bidder's own user or one of that user's verified agents, to
// identlink's depth (the walk of the account and of each bidder, as the policy's trust snapshot)
s.st["vouched"] = json!([]);
s.st["walks"] = json!({});
h = h.call(walk("walk-account", &did));
let mut fan = 1;
for (j, b) in bidders.iter().enumerate() {
// a bidder with no operator (a staging joined bidder) is its own voucher, as bidder-tangled-vouch reads it
h = h.call(walk(&format!("walk-{j}"), b["did"].as_str().unwrap_or_default()));
fan += 1;
// a bidder with no operator (a staging joined bidder) is its own voucher, as bidder-tangled-vouch reads it;
// a self-vouch is never read (trust.vouchPairs)
let voucher = b["operator"].as_str().filter(|o| !o.is_empty()).or(b["did"].as_str()).unwrap_or_default();
h = h.call(steps::get_record(&format!("vouch-{j}"), &format!("at://{voucher}/sh.tangled.graph.vouch/{did}")));
if voucher != did {
h = h.call(steps::get_record(&format!("vouch-{j}"), &format!("at://{voucher}/sh.tangled.graph.vouch/{did}")));
fan += 1;
}
}
s.st["fan"] = json!(fan);
}
v if v.starts_with("vouch-") => {}
v if v.starts_with("walk-") => s.st["walks"][v] = o.clone(),
"bundle" => h = h.call(host("ex", "example", json!({ "name": "mixed-prod.yaml" }))),
"ex" => {
let key = s.st["key"].as_str().unwrap_or_default().to_string();
@@ -270,8 +301,8 @@ fn a_handler(run: Run<Value>) -> Result<Handle, String> {
}
_ => {}
}
// fans: vouches, then the bundle; winners, then vm1 ssh; Held checks after the restart, then ssh again
if id.starts_with("vouch-") || id.starts_with("cc-") {
// fans: admissions, then the bundle; winners, then vm1 ssh; Held checks after the restart, then ssh again
if id.starts_with("vouch-") || id.starts_with("walk-") || id.starts_with("cc-") {
if id.starts_with("vouch-") && result.output().is_ok() {
s.st["vouched"].as_array_mut().unwrap().push(json!(id));
}
@@ -279,8 +310,23 @@ fn a_handler(run: Run<Value>) -> Result<Handle, String> {
s.st["fan"] = json!(left);
if left == 0 {
h = match s.phase().as_str() {
"requester" if s.st["vouched"].as_array().is_none_or(|v| v.is_empty()) => return Ok(s.fail("no bidder operator vouches the account")),
"requester" => {
let aw = s.st["walks"]["walk-account"].clone();
let mut admitted = vec![];
for (j, b) in bidders.iter().enumerate() {
let vouched = s.st["vouched"].as_array().is_some_and(|v| v.contains(&json!(format!("vouch-{j}"))));
let bd = b["did"].as_str().unwrap_or_default();
if vouched || operated_by_trusted(&did, &aw, bd, &s.st["walks"][format!("walk-{j}")]) {
admitted.push(b["name"].clone());
}
}
if admitted.is_empty() {
return Ok(s.fail(format!(
"no bidder admits the account: no bidder operator vouches it, and it is no bidder's own user or verified agent (account roots {})",
aw["roots"]
)));
}
s.reading("admitted_by", admitted);
s.set("bundle");
h.call(host("bundle", "requester.bundle", json!({ "name": "mp", "contract": cc("agent1") })))
}
@@ -382,15 +428,17 @@ fn c_handler(run: Run<Value>) -> Result<Handle, String> {
}
}
"records" => {
let infra: Vec<Value> = o["uris"].as_array().into_iter().flatten().filter(|u| u.as_str().is_some_and(|u| u.contains("/computer.socialweb.infra/"))).cloned().collect();
s.reading("records_checked", o["uris"].as_array().map_or(0, Vec::len));
h = h.call(host("gone", "assert.recordsGone", json!({ "uris": o["uris"] })));
let index = format!("at://{}/computer.socialweb.infra/self", s.st["renter"].as_str().unwrap_or_default());
let uris: Vec<Value> = o["uris"].as_array().into_iter().flatten().filter(|u| u.as_str() != Some(index.as_str())).cloned().collect();
let infra: Vec<Value> = uris.iter().filter(|u| u.as_str().is_some_and(|u| u.contains("/computer.socialweb.infra/"))).cloned().collect();
s.reading("records_checked", uris.len());
h = h.call(host("gone", "assert.recordsGone", json!({ "uris": uris })));
s.st["infra"] = json!(infra);
}
"gone" => {
if o["left"].as_array().is_some_and(Vec::is_empty) {
// the index of live deployments (computer.socialweb.infra/self) must not list this cluster's Infra any more; the
// ended records themselves are kept, only the index says what is live
// the index (computer.socialweb.infra/self) is the account's, not this run's: it is deleted only when nothing is
// left in it, so it must be gone or name this run's Infra neither in live nor in recentEnded
s.set("index");
s.mark("index");
h = h.call(steps::get_record("idx", &format!("at://{}/computer.socialweb.infra/self", s.st["renter"].as_str().unwrap_or_default())));
@@ -403,21 +451,25 @@ fn c_handler(run: Run<Value>) -> Result<Handle, String> {
}
"idx" => {
let live: Vec<Value> = o["value"]["index"]["live"].as_array().cloned().unwrap_or_default();
let ended: Vec<Value> = o["value"]["index"]["recentEnded"].as_array().cloned().unwrap_or_default();
s.reading("index_live", live.len());
s.reading("index_ended", ended.len());
let mine: Vec<String> = s.st["infra"].as_array().into_iter().flatten().filter_map(Value::as_str).map(|u| u.rsplit('/').next().unwrap_or_default().to_string()).collect();
s.reading("infra_rkeys", json!(mine));
if mine.is_empty() {
return Ok(s.fail("no Infra rkey of this run was found in the requester's logs: the index check would pass for nothing"));
}
let listed: Vec<&Value> = live.iter().filter(|e| e["rkey"].as_str().is_some_and(|r| mine.iter().any(|m| m == r))).collect();
if !listed.is_empty() {
if s.since("index") > 120.0 {
return Ok(s.fail(format!("the index at computer.socialweb.infra/self still lists this run's Infra as live after nodes 0: {}", json!(listed))));
}
h = h.timer("idxpoll", 10_000);
} else {
let named: Vec<&Value> = live.iter().chain(ended.iter()).filter(|e| e["rkey"].as_str().is_some_and(|r| mine.iter().any(|m| m == r))).collect();
if named.is_empty() && !(live.is_empty() && ended.is_empty()) {
return Ok(s.pass());
}
if s.since("index") > 120.0 {
if named.is_empty() {
return Ok(s.fail("the index at computer.socialweb.infra/self is left with nothing in it after nodes 0: an empty index is deleted"));
}
return Ok(s.fail(format!("the index at computer.socialweb.infra/self still names this run's Infra after nodes 0: {}", json!(named))));
}
h = h.timer("idxpoll", 10_000);
}
_ => {}
}
tests/modules/acc-0013/module.json+9−0
@@ -33,6 +33,7 @@
"computer.socialweb.test.root.exec",
"computer.socialweb.test.root.putBinary",
"com.atproto.repo.getRecord",
"com.fedfork.exec.identlink.walk",
"com.fedfork.exec.kube.get",
"com.fedfork.exec.kube.list",
"com.fedfork.exec.kube.apply",
@@ -43,6 +44,14 @@
"computer.socialweb.test.atirc.meshRun"
],
"hooks": [
{
"nsid": "com.fedfork.exec.identlink.walk",
"required": true,
"entries": [
"run"
],
"reason": "the walk of the account and of each bidder, as the bidder's trust snapshot"
},
{
"nsid": "computer.socialweb.test.assert.recordsGone",
"reason": "records RecordNotFound after the delete"
tests/system/tests/acc_0013_mixed_prod.rs+17−3
@@ -112,14 +112,28 @@ async fn a_run_requester_mixed_prod() {
let mr = kcp.get("MarketRequester", "app").await?.context("MarketRequester app")?;
ensure!(mr["status"]["phase"] == "Ready" && mr["status"]["did"] == did.as_str(), "MarketRequester {}", mr["status"]);
// vouches are preconditions: some bidder operator vouches the account (else no bids)
// a precondition: some bidder's bidder-tangled-vouch admits the account (else no bids): its operator vouches
// the account, or the account is the bidder's own user or one of that user's verified agents (the identlink
// walks of the policy's trust snapshot: a shared root, or the account's operator on the bidder's side)
let account = ctx.walk(&did).await;
let mut vouched = vec![];
for b in &ctx.target.bidders {
if ctx.at.record_of(&b.operator, "sh.tangled.graph.vouch", &did).await?.is_some() {
let bidder = ctx.walk(&b.did).await;
let voucher = if b.operator.is_empty() { &b.did } else { &b.operator };
let by_vouch = *voucher != did && ctx.at.record_of(voucher, "sh.tangled.graph.vouch", &did).await?.is_some();
let side: Vec<&str> = std::iter::once(b.did.as_str()).chain(bidder.ancestors.iter().map(|a| a.did.as_str())).collect();
let operated = b.did == did
|| bidder.roots.iter().any(|r| account.roots.contains(r))
|| account.roots.iter().find(|r| **r != did).is_some_and(|op| side.contains(&op.as_str()));
if by_vouch || operated {
vouched.push(b.name.clone());
}
}
ensure!(!vouched.is_empty(), "no bidder operator vouches {did}");
ensure!(
!vouched.is_empty(),
"no bidder admits {did}: no bidder operator vouches it, and it is no bidder's own user or verified agent (roots {:?})",
account.roots
);
ctx.reading("vouched_by_operators_of", &vouched);
agent1_bundle(&ctx, &r).await?;
tests/testkit/src/atproto.rs+26−8
tests/testkit/src/irohfetch.rsnew+56−0
tests/testkit/src/lib.rs+1−0