Compare commits

...
Author SHA1 Message Date
jochen e539cf6e99 networkmanager: the watcher names no node; the bundle fills in its own
The node-engine gives the watcher's process no MESH_NODE, so the watcher refused to
start and crash-looped on g14. It needs none: a kept change holds its event, its
sequence and its body, and the bundle fills its own node into the subject, the message
id <node>.<event>.<sequence> and the body when it publishes, the same at every publish.

Builds: design 08 sign-in-page §11, §12, §20; lead answer L-3 (hq 09c9a3e3)
2026-11-25 14:32:03 +01:00
mesh-tools 17e1bfb6d3 Merge pull request 'networkmanager: TestUplinkNamesIsCalledAtEachMoment waits for each call, no race with the bundle's start' (#756) from fix/uplink-names-moment-test into main 2026-11-25 00:38:38 +00:00
jochen cd17899328 networkmanager: the uplink-names moments test waits on each call, not on the scheduler
The test changed check-address while the bundle, running beside it, had not yet read it
for its start's call. On a temporary directory in memory with one CPU, as a build step
runs, nothing yields before the test's write, so the start's call read the empty address
every time (pipeline main.517, asks mwvdrpjpbb0cf9 and mwvdrpjpb6c9b9); on a disk the
fsync yielded and it passed. The stood-in resolver now says each uplink-names call, and
the test changes the address only after the call before it.

Builds: design 08 sign-in-page §13, §25
2026-11-25 01:37:04 +01:00
mesh-tools 5153e5fdc2 Merge pull request 'networkmanager opens a network's sign-in page on its own machine (design 08 sign-in-page)' (#755) from feat/sign-in-page-uplink into main 2026-11-25 00:20:12 +00:00
mesh-tools 1712612729 Merge pull request 'i3 serves node-display-session.open (design 08 sign-in-page, issue 935)' (#754) from feat/sign-in-page-i3 into main 2026-11-25 00:20:10 +00:00
mesh-tools dd9b4a10f5 Merge pull request 'systemd-resolved: uplink-names, the guard keeps them on the uplink, routes answers them (design 08 sign-in-page)' (#753) from feat/sign-in-page-resolver into main 2026-11-25 00:20:08 +00:00
jochen ac50980ba1 systemd-resolved: the names file write refuses naming its bound on the deadline (review r2 (3))
Past WriteUplinkNamesBound (15 s) the refusal read the bare signal the
deadline killed the process with ("install failed: signal: killed"); it
now names the bound and says the file was left as it was, for either
step (install or mv).

Builds: design 08 sign-in-page §6, C-8
2026-11-25 01:18:09 +01:00
jochen d859380669 systemd-resolved: the machine's socket answers routes with outside_writes too (review r2 (5))
It answered an empty outside_writes while the bus answered the kept
history; the socket now reads the guard's own history (its own history
file, the same the bus's tools() reads in production), so both answer
the same (§5, DQ-5).

Builds: design 08 sign-in-page §5, §9, DQ-5
2026-11-25 01:17:55 +01:00
jochen 8f86aedeae systemd-resolved: checkUnknownPaths knows exactly its own files (review r2 (4))
It treated the verb's own uplink-names.new as unknown and accepted any
bare *.tmp; it now knows exactly uplink-names, uplink-names.new,
uplink-names.applied and uplink-names.applied.tmp, as §6 and §8 name
them, and nothing else.

Builds: design 08 sign-in-page §6, §8, C-7
2026-11-25 01:17:26 +01:00
jochen 9a3149df88 i3: test the opener's no-kill run with pipes, never a real sleep
Code review round 2 (C-5 follow-up). openerRun's core is now runWithoutKilling(ctx,
*exec.Cmd), callable directly by a test with a command of its own. The test's child
blocks reading its stdin (a pipe held open past the bound); after confirming
TimedOut, the test closes the pipe to unblock it, then waits on the child's own
end (a byte written to an extra file just before it exits, read with a plain
blocking read) instead of sleeping and polling for a marker file. A kill at the
bound now leaves that read empty, which the test checked by reintroducing the old
signal and watching it fail.

Builds: design 08 sign-in-page §3, §29
2026-11-25 01:13:18 +01:00
jochen 8ca052a0c7 networkmanager: the whole test's runtime publishes only what the membership lists
The stand-in tool runner refuses a subject the module's membership does not list, as
the runtime's mayPublish does: the module's held seat's own-node events, read from its
manifest and the nodeuplink contract (MembershipFor's rule at mesh-delivery ef8dd120).
Another node's subject is refused and stays kept.

Builds: design 08 sign-in-page §4a, §25; lead answer C-1
2026-11-25 01:13:13 +01:00
jochen 349ef43a36 networkmanager: a watcher refused at its start by a bus that is there exits
When the first subscribe fails while the system bus's socket is already there, no file
event will make it again: the watcher writes the reason to its journal and exits
non-zero, so its unit shows failing instead of staying active and deaf.

Builds: design 08 sign-in-page §14; lead answer C2-1 (hq f15bc2fd)
2026-11-25 01:12:23 +01:00
jochen a74afe71f3 systemd-resolved: an unknown path in its directory is left and journalled once (review r1 C-7)
The checks/owned check refuses a directory without unknown (ADR 0422 §8).
/var/lib/node-resolver stays, its value "module" (lead answer L-1), not
"program": no other program writes there. The guard looks for a path it
does not know every round and, finding one, leaves it exactly as it is
and says so to the journal once, never every round.

Builds: design 08 sign-in-page §6, C-7
2026-11-24 22:01:21 +01:00
jochen bd6dcdcd0c systemd-resolved: judge "in place" from what resolved holds now (review r1 C-4, note c)
C-4: the guard reads the link's domains fresh with rawDomainsOf before
skipping a round, never trusting its own applied record alone, so a
network manager that rewrites the link's domains, or a restarted
resolved, is found and the names are set again.

note (c): fallback.json's since is the time of the guard's first round,
never the zero time; it moved only on a real turn before, so the first
round's write carried a zero since.

Builds: design 08 sign-in-page §7, §8, C-4
2026-11-24 22:01:01 +01:00
jochen 717f8ec2e5 systemd-resolved: answer with the generated contract's own types (review r1 C-6, C-8)
C-6: import noderesolver (mesh-networking's seat definition) at the zero
version; routes, route, unroute and uplink-names answer with its
RoutesAnswer, RouteAnswer, UnrouteAnswer and UplinkNamesAnswer, never a
map or a parallel struct, and uplink-names' input names is a JSON array
(arrayArg), never a comma- or space-split string.

C-8: the names file write's 15 s is the stated constant
WriteUplinkNamesBound, not an inline literal.

Builds: design 08 sign-in-page §2, §5, §6, §9, DQ-12, C-6, C-8
2026-11-24 22:00:15 +01:00
jochen a94f9f14aa i3: open's own non-killing opener run, the generated answer type, a hand-act on every call
Code review round 1 (C-5, C-6, note (b)):
- open's opener now runs through its own openerRun, which stops waiting at its bound
  without sending any signal, instead of internal/desktop's Exec, which kills the
  command's process group at its deadline; a browser started under the account's
  service manager is never torn down by open's own 10 s bound (DMC-8).
- open imports mesh-contracts' generated nodedisplaysession package at the zero
  version and answers with its OpenAnswer type and Started constants; main.go names
  the tool from its Seat and VerbOpen constants.
- Every call to open, refused or not, writes one act to the log of acts done by hand
  (DQ-7 says "each call"), not only one that reaches the opener.

Builds: design 08 sign-in-page §3, §29
2026-11-24 21:53:45 +01:00
jochen 397e627b02 networkmanager: the watcher's health is its unit's state
The sign-in process is judged by its unit being active, on the machine without the bus,
and NetworkManager's service keeps no state and no health again. The watcher exits
non-zero when it cannot subscribe once the system bus came back, so its unit shows
failing; uplink_health stays a tool that reads and no longer gives the names again.

Builds: design 08 sign-in-page §11, §13, §14, §23, §24, §25, §27; lead answer C-2c (hq 6752a5cf)
2026-11-24 21:53:29 +01:00
jochen 55a90d963e networkmanager: the watcher redials the system bus only at its socket's event
A refused or dropped system bus is dialled again only at the file event that makes its
socket and at rating-again, never because the socket is merely there, so a bus that
refuses the watcher is not dialled in a loop.

Builds: design 08 sign-in-page §14; lead answer note (d) (hq df22a138)
2026-11-24 21:50:49 +01:00
jochen 42b5a7aef3 networkmanager: the watcher socket's bound is a stated constant
Builds: design 08 sign-in-page §12; lead answer C-8 (hq df22a138)
2026-11-24 21:50:00 +01:00
jochen 77602d8586 networkmanager: NetworkManager's unit is checked beside the watcher's tool
NetworkManager's service carries a check of kind unit, still with no state, so the
watcher's tool check stands beside a check of another kind, as zfs's units stand beside
its watch process's tool check.

Builds: design 08 sign-in-page §27; lead answer C-2 (hq df22a138)
2026-11-24 21:49:42 +01:00
jochen ae7d0f874b systemd-resolved: declare the private-interface fact, the literal mesh0 (lead answer L-2)
The fact itself was missing from the manifest (R2's own gap): the guard
and the uplink-names verb's DefaultRouteLink already read
/etc/node-resolver/private-interface, but nothing rendered it. Its
template is the literal "mesh0" per L-2, quick not thorough: the live
interface, named the same way already by netcheck's TunnelInterface and
networkmanager's unmanaged-devices. One value every module reads instead
is L-2's finding, carried outside this milestone.

Builds: design 08 sign-in-page §7, DQ-1
2026-11-24 21:36:32 +01:00
jochen 691ad760d3 systemd-resolved: test that a changed list replaces the old one on the link (issue 960)
R2's acceptance criteria name this case directly: the file's list changes
while the default-route link stays the same, and the guard gives the new
names to that same link without moving them first.

Builds: design 08 sign-in-page §7, §9
2026-11-24 21:34:42 +01:00
jochen 0c2a95aacd systemd-resolved: README names uplink-names, its files and the guard's new duty (issue 960)
Says the verb and its answer, the two new files (uplink-names, its
applied record) and fallback.json, the guard's round over the default-
route link, the sudo -n install / mv -f commands, and that uplink-names
only sets how resolved answers those names over a link, never the link
itself.

Builds: design 08 sign-in-page §10
2026-11-24 21:33:25 +01:00
jochen e20d3c7548 M8 networkmanager: the folder's unknown is the module's
The folder the two parts share says unknown module, so the node-engine does nothing
inside it and the watcher reacts: a path it does not know is left as it is and written
to its journal once per path, at its start and at the file event that makes it; the
README says so.

Builds: design 08 sign-in-page §12, §24, §25, §27; lead answer L-1 (hq 3a3a18a9)
2026-11-24 21:31:51 +01:00
jochen dd35217275 M10 networkmanager: the whole-module test
The watcher, its system bus and desktop stood in, opens the page with no bus; then the
built bundle, played as the tool runner plays it over a real bus with node-uplink's
events and a stand-in holder of node-resolver, publishes the kept events in order
with the times of their changes, each matching the seat's definition, and calls
uplink-names.

Builds: design 08 sign-in-page §1, §25, §26, §33
2026-11-24 21:29:28 +01:00
jochen 20c53a14db M9 networkmanager, systemd-networkd: their READMEs
networkmanager's README says its two parts and their folder, how the watcher opens the
page and finds the session without the bus, the events it keeps and the bundle
publishes, and the uplink-names call; systemd-networkd's says it announces neither
event and opens nothing.

Builds: design 08 sign-in-page §24, §28
2026-11-24 21:26:45 +01:00
jochen 9f5614b35e systemd-resolved: routes answers the uplink's names and the mesh's fallback (issue 960)
routes (bus and the machine socket) gains uplink_names {names, link,
refused}, the applied list's names resolved holds on that link now, never
the file's, and mesh_resolvers {silent, since} from the guard's fallback
state. The guard writes that state at each of ADR 0688's two turns, and
once more at its own first round, since it goes at every boot.

Builds: design 08 sign-in-page §2, §8, §9
2026-11-24 21:26:30 +01:00
jochen dc27af2227 M8 networkmanager: the manifest declares the sign-in parts
The manifest declares the watcher as a process run as the account with uplink_health
as its health, the folder the two parts share (the account's, 0700), the running event
the bundle consumes, the three verbs it invokes and its five tools.

Builds: design 08 sign-in-page §11, §12, §13, §27
2026-11-24 21:26:14 +01:00
jochen 1dec6eb02c M7 networkmanager: its tools and health
The bundle serves uplink_sign_in, uplink_names_again, uplink_rating_again,
uplink_publish_again and uplink_health: the read of the reaction, the three acts the
parts do by themselves, and the watcher process's health, which also gives the names
again where the resolver no longer holds them.

Builds: design 08 sign-in-page §13, §23
2026-11-24 21:25:17 +01:00
jochen 786a23638b M6 networkmanager: the bundle gives the resolver the check's name
The bundle calls this node's node-resolver uplink-names with the check address's host
at its start, at a changed check-address, at its bus connection's return and when this
node's holder of node-resolver runs, reading the holder from the assignments; no holder
is recorded and no failure, a failed call stands failed in names.json until the next
moment.

Builds: design 08 sign-in-page §12, §13, §22
2026-11-24 21:23:56 +01:00
jochen b694c5e2a5 systemd-resolved: the guard applies the uplink's names every round (issue 960)
Each round it finds the link carrying the default route (the lowest-metric
kernel default route that is neither one route routed nor the private
network's interface), gives it the names from uplink-names's file plus
its own search and routing domains, and takes them off the link they were
on before when that differs. What it applied is kept in
uplink-names.applied, read at its own start so a restart never infers
which link to take them off, and a resolved refusal is journalled once
per change, not every round. The guard's own names are left out of
whether a link is judged `route` routed, so the fallback still gives a
link holding only them its default route back while the mesh's resolvers
are silent (ADR 0688 stands).

Builds: design 08 sign-in-page §7, §8
2026-11-24 21:23:06 +01:00
jochen f6646c7254 M5 networkmanager: the bundle publishes the kept events
The bundle publishes what the watcher kept, in order and under each event's own
message id, deleting each once the stream acknowledged it and keeping a refused one
for the next moment: its start, a file event on pending/ and its bus connection's
return. The watcher now names the events by the seat's generated contract.

Builds: design 08 sign-in-page §1, §20, §22
2026-11-24 21:22:01 +01:00
jochen a4169a2325 M4 networkmanager: open the page and tell the person
At a join, at the watcher's start and at a session's start while PORTAL, once per ask,
the watcher opens the check address with systemd-run --user and xdg-open in the
person's session and then shows the notification its outcome calls for, critical when
the open failed; it says when the network is open, and handles what it hears during
an open after it.

Builds: design 08 sign-in-page §15, §18, §19, §22
2026-11-24 21:20:20 +01:00
jochen a40d7fb1c4 systemd-resolved: serve uplink-names, writing the host names file (issue 960)
The verb checks each host name (root, wildcard, trailing dot, a label over
63 bytes, the mesh's own domain or under it, more than 8), writes
/var/lib/node-resolver/uplink-names whole through sudo -n install then
sudo -n mv -f, and answers the names with the link carrying the default
route (the lowest-metric kernel default route that is neither routed nor
the private network's interface) and when they were set.

Builds: design 08 sign-in-page §2, §5, §6
2026-11-24 21:19:35 +01:00
jochen fee3f8ab8b M3 networkmanager: the person's session
The watcher finds the person's graphical session from logind and the user manager's
environment, and acts on a session's start once that environment names a display; the
user manager sends no PropertiesChanged for Environment, so it is read again at the
file events on the X server's socket folder and the session's runtime directory, for
at most 60 s.

Builds: design 08 sign-in-page §15, §16, §17
2026-11-24 21:18:36 +01:00
jochen c12d0027e8 retired-words: add captive portal (the glossary's sign-in page, issue 935)
Builds: design 08 sign-in-page §32
2026-11-24 21:17:51 +01:00
jochen 2b0b234db2 i3: README for open (issue 935)
Documents the verb, its refusals, the percent-encoding and that each call that is
acted on is written to the log of acts done by hand; names the package xdg-utils and
that i3 hears nothing of the uplink.

Builds: design 08 sign-in-page §31
2026-11-24 21:16:57 +01:00
jochen f7b918faea i3: serve node-display-session.open, percent-encoded and recorded as an act (issue 935)
node-display-session gains the verb open: an http or https address opened in the
session's default browser through xdg-mime and systemd-run --user, never i3's IPC
(which hands a shell a command line). The address is percent-encoded per RFC 3986's
unreserved set plus the separators a URL needs, as one argument; a refusal names the
reason (scheme, host, length, session, default program, the opener's own failure).
Each call that is acted on is written to the log of acts done by hand
(seat:mesh-hand-acts.hand-act), with its caller and why.

Builds: design 08 sign-in-page §3, §29
2026-11-24 21:16:22 +01:00
jochen dc59860541 M2 networkmanager: the watcher hears the rating
uplink-tools watch hears the network manager's PropertiesChanged on the system bus,
keeps sign-in-asked and sign-in-ended as the rules say, at most 256 of them, and
subscribes again when the system bus's socket comes back or on rating-again; nothing
reads the rating on a timer.

Builds: design 08 sign-in-page §12, §14, §20, §21, §22
2026-11-24 21:12:25 +01:00
jochen 98b73461e5 M1 networkmanager: the shared folder its two parts keep
The watcher and the bundle share only the module's own folder: the watcher's socket,
the check address, the kept events with ids made once from a sequence that is never
reset, and the bundle's last uplink-names call, every file written whole.

Builds: design 08 sign-in-page §12, §20
2026-11-24 21:08:01 +01:00
jochen a8dfe343a2 M0 uplink-tools: the holder's own part beside the copies
main.go, still the copy both holders of node-uplink carry, now takes each holder's own
subcommands, tools and start work from its manager.go, so networkmanager can add its
watcher and tools while systemd-networkd serves the two seat verbs as before.

Builds: design 08 sign-in-page §11
2026-11-24 21:06:34 +01:00
mesh-tools 03bf70a22b Merge pull request 'systemd-resolved: pack files/ as its templates archive, so the indexer reads the 0.2 manifest (issue 1981)' (#752) from fix/1981-files-archive into main 2026-11-24 13:15:27 +00:00
jochen 324ff5215c systemd-resolved: pack files/ as the archive its templates are read from, so the indexer can read the 0.2 manifest (issue 1981)
The indexer refused the manifest merged in #704 (systemd-resolved names templates and its build packs no archive from files/, novox/hq ADR 0349 §2): the take-in of source 159 then moved no module and started no pipeline.
2026-11-24 14:11:41 +01:00
mesh-tools 8edc9233c0 Merge pull request 'systemd-resolved: a network's own servers answer while the mesh's resolvers are silent (issue 1981)' (#704) from fix/1981-sign-in-page-names into main 2026-11-24 13:00:42 +00:00
jochen 8f21a7a5de Merge main into fix/1981-sign-in-page-names: systemd-resolved keeps main's class core and raises its version to 0.2 (issue 1981) 2026-11-24 13:56:04 +01:00
mesh-tools 527676ccb4 Merge pull request 'nats: a ledger's state and index buckets take the ledger's cap (design 47 H2 H-A-636)' (#751) from fix/ledger-state-cap into main 2026-11-24 00:59:22 +00:00
jschoubben 0f648e26dd nats: a ledger's state and index buckets take the ledger's own max-mib
The keeper planned a ledger's state bucket and each index bucket with no
option, so each was the state default of 64 MiB whatever the ledger asked,
while its history and snapshot took max-mib. The delivery gate's ledger asks
1024 and its state bucket filled at 64. The state and index buckets now take
the ledger's max-mib and no other of its options; a ledger with none keeps
the state default. A raised cap reaches a held bucket through the keeper's
existing path for larger settings (check at the first view after a start).

The keeper's plan test: the existing ledger row now expects its state and
index buckets at the ledger's 16 MiB; a row with max-mib 1024 (and a past-values
option that must not reach them) expects 1 GiB; a row with none expects 64 MiB.

Design 47 H2's corrections, item 12 (lead answer H-A-636).

Builds: design 47 H2 H-A-636 (corrections, item 12)
2026-11-24 01:39:00 +01:00
mesh-tools 008ac6332f Merge pull request 'mesh-build-go: list a Go package artifact's import set in the environment its build uses (issue 1984)' (#750) from fix/1984-imports-env into main 2026-11-23 23:26:16 +00:00
jschoubben 5526873138 mesh-build-go: the imports step lists each package path in the environment its build uses (issue 1984, H-A-633)
The imports step ran every `go list -deps` with the environment of the module's directory, while the build of a
package path runs with the environment of the path's own directory: its temporary modfile of the fetch's pins and the
replace to a module of the module's own repository. A path whose Go module requires such a module at the zero version
(mesh-delivery-contracts' clients require mesh-delivery-sdk) built and published, then failed its listing with "module
lookup disabled by GOPROXY=off" (main.510). ModuleImports now takes the environment as a function of the directory a
listing runs in, and the step passes buildEnv, so each listing reads the import set as the build resolved it.

The row is a subtest of TestImportsStepReadsTheWorkspace: a path's go.mod requires a same-repository module at the zero
version, resolved only through the path's temporary modfile; it fails with the environment of the module directory.

Builds: design 47 H2 H-A-633 (amends H-A-518, H-A-541, H-A-532 DQ-5); issue 1984
2026-11-24 00:19:56 +01:00
mesh-tools 51a6ac3461 Merge pull request 'mesh-delivery-gate: apply each event and call whole, one at a time, so no record loses its delivery time (issue 721)' (#749) from fix/gate-records-race into main 2026-11-23 14:54:30 +00:00
jschoubben fe2bed92e6 mesh-delivery-gate: name the acceptance the race test holds (issue 721, 721/AC1)
The review of cc1140ba found the new test cited no acceptance; issue 721's note 15 gives it 721/AC1.
The test's comment now names it. No code changes.

Fixes: issue 721 note 11
Acceptance: 721/AC1
Builds: design 47 H2 §810
2026-11-23 15:53:07 +01:00
jschoubben cc1140ba36 mesh-delivery-gate: apply each event and call whole, one at a time, so no record loses its delivery time
The runtime hands each event and each tool call to a goroutine of its own (mesh-sdk stdio), and the gate
applied them to the same in-memory records with no lock: Records.Outcome writes the ledger and only then
memory, so a pipeline-wanted heard once a running's outcome was in the ledger ended the record before
memory held that running, and timesAtEnd found no running: the record ended with no delivery time and
no class (main.493's failure of TestAGateWhole...). The race detector names it: 9 reports in 30 runs on
main, the running's Records.Outcome (record.go:759) against pipeline-wanted's timesAtEnd (movers.go:67).

The fix, the thorough one for the kind (events and calls applied concurrently to one in-memory state):
- take applies every event under Holder.applying; the ledger write and the memory write of an entry
  happen under it, so whatever is heard after the write lands waits until memory holds it too.
- Holder.applied runs every tool call under the same lock and takes its answer (marshalled) under it,
  so a view of a kept record is never written out while the next event writes the record.
- The bus test's bundle log fails the test on a data race the bundle reports under -race, a guard for
  every bus test of the gate.
The quick fix, a lock around Records.End and Records.Outcome alone, was not taken: it leaves an event's
several writes (pipeline-ended, take-in) interleaved with another's and the calls reading half-written
records.

Test: TestWhatIsHeardWhileAnEventIsWrittenWaitsUntilItIsApplied hears pipeline-wanted, and calls show,
as the running's write lands; each of the three parts removed fails a row.

Fixes: issue 721 note 11
Builds: design 47 H2 §810
2026-11-23 15:28:11 +01:00
mesh-tools d5161c93ef Merge pull request 'Import fingerprint: the build modules report each build's import set (issue 721, design 47 H2)' (#748) from fix/fp-imports into main 2026-11-23 12:22:47 +00:00
jschoubben 4c290476f8 Merge remote-tracking branch 'origin/main' into fix/fp-imports 2026-11-23 13:18:59 +01:00
jschoubben e5be3c464e N1: Node's own modules are read from the probed toolchain at the imports step
Review r1 finding 4: the imports step held a fixed list of Node 22's
builtin modules (principle 11). It now reads module.builtinModules from the
installed Node at each step, and fails loud when it cannot.

Builds: design 47 H2 H-A-523, H-A-532 (DQ-6)
2026-11-23 13:18:52 +01:00
mesh-tools 841afa5853 Merge pull request 'gitea's Go bundles read the token gitea keeps when the vault refuses their account (design 47 H2, H-A-564)' (#747) from fix/gitea-token-fallback into main 2026-11-23 12:16:02 +00:00
jschoubben 263b5d9aba gitea: the Go bundles fall back to the token files in gitea's state directory by default
The binary is placed by hand on novox first, under gitea 0.1.316's composition, which hands the Go bundles
neither MESH_GITEA_TOKEN_FILE nor MESH_GITEA_PACKAGES_TOKEN_FILE, nor any variable naming gitea's state
directory. Without them the fallback reads token and packages-token in /var/lib/mesh/gitea/state (the
manifest's runtime-state directory) and says at start that the path is the default; the manifest's
variables still win when handed.

Builds: design 47 H2 H-A-564 (hq 1b286366)
2026-11-23 13:11:56 +01:00
jschoubben 1ced7fce14 gitea: the Go bundles read the token gitea keeps when the vault refuses their account
Every package publish fails since about 11:45 CET: the package-registry and forge bundles ask the vault for
module/gitea/* from inside the tool runner, whose account the vault refuses (no module's account), and the
manifest since C4 hands them no token file. Until gitea runs as its own account, a bundle the vault refuses
reads the token gitea's TypeScript bundle keeps under its state directory (token, packages-token, each with
its scopes line naming the account), says once at start which source each token came from, and reads the
file again at each call. The manifest hands the two bundles MESH_GITEA_TOKEN_FILE and
MESH_GITEA_PACKAGES_TOKEN_FILE again. The fallback ends with gitea's own account.

Builds: design 47 H2 H-A-564 (hq 1b286366), H-A-543
2026-11-23 13:08:18 +01:00
jschoubben 7b325126da H-A-553 (2): floor-silent leaves the conditions' homes
The builder's version floor went (B1a, issue 721), and with it the finding
floor-silent it raised; no home names that kind any more.

Builds: design 47 H2 H-A-553 (2), H §756
2026-11-23 12:36:37 +01:00
jschoubben 2b8e2526f2 N3: a Go import set names each package of the import closure, not its module (issue 721)
A module path digested a whole module and brought back the cascade the import
set exists to end; ModuleImports reports the import path of every package the
build resolved, still with no prefix filter, the standard library and the
module's own packages left out.

Builds: design 47 H2 H-A-541, H-A-517, H-A-539
2026-11-23 11:31:38 +01:00
jschoubben 09f66c5f5c N2: a build reports every module or package it resolved, with no prefix or scope (issue 721)
Mesh Go modules come from the seat go-package-registry, not the forge, so no
prefix or scope tells a mesh package apart. ModuleImports reports the module
path of every package the build resolved but the standard library's and the
module's own, and build_node_imports every npm package the bundles reach but
Node's own modules. The settings import-prefix and import-scope leave both
manifests and the ask.

Builds: design 47 H2 H-A-539 (withdraws H-A-534's form check and H-A-535)
2026-11-23 11:28:27 +01:00
jschoubben b117e4ab55 N1: the Node build module reads and says its import set; each build module judges by its own setting (issue 721)
The step tool build_node_imports reads, after a build, esbuild's metafile of each
TypeScript bundle's staged entrypoints and launchers and answers the mesh npm
packages among its inputs and external imports, each by its package name once
(@novox/mesh-sdk, never a sub-path); the ask's steps run it as Imports and say
the set as imports-reported on node-build-node's subject of the node. The Node
build module declares the setting import-scope (default @novox) and the Go build
module import-prefix (default the forge's Go module prefix), each filled into the
step runner's ask as ImportScope and ImportPrefix.

Builds: design 47 H2 H-A-523, H-A-517, H-A-532 DQ-6, DMC-2, DMC-3, H-A-534, H-A-535
2026-11-23 11:21:35 +01:00
jschoubben 0e35d32669 G2: a Go package artifact reports its import set (issue 721)
ModuleImports lists, beside each Go bundle's program, every package each Go
package artifact's paths hold, in the Go module that path is, tests and the
module's own directory left out, as one sorted union; so a contracts module
reports an import set and leaves the version line.

Builds: design 47 H2 H-A-532 DQ-5, H-A-518, H-A-517
2026-11-23 11:07:50 +01:00
jschoubben d625008c57 G1: the Go build module says a done build's import set as imports-reported (issue 721)
The ask's steps gain SayImports, the shared step runner's say of the seat event
imports-reported on this node's subject of node-build-go, published with the
module's SayEvent as its other events are, so the indexer hears each module's
import set from the build that read it.

Builds: design 47 H2 H-A-517, H-A-518, H-A-532 DQ-2, DMC-2
2026-11-23 11:05:59 +01:00
mesh-tools 8b8b0f6669 Merge pull request 'The TypeScript build seat's steps answers lint only where there is TypeScript (design 47 H2, H-A-515 second addendum)' (#746) from fix/nothing-to-run into main 2026-11-23 09:47:13 +00:00
jschoubben f1f09151c0 mesh-build-node: steps answers lint only where there is TypeScript to check
A TypeScript artifact with no .ts file (a contracts module's generated
JavaScript package) had steps answer lint, so its lint was asked of a build
node and waited minutes there to end nothing to run in a second. steps now
answers lint only when one of the artifact's packages holds a TypeScript
file, by the same test the lint step uses, so the pipeline runner can end
it at placement without an ask.

Builds: design 47 H2 H-A-515 second addendum
2026-11-23 10:28:25 +01:00
mesh-tools 1a16a42f18 Merge pull request 'distribution serves name-of: the reference it keeps an upstream copy under (design 47 H2, H-A-513)' (#745) from fix/registry-name-of into main 2026-11-23 08:47:51 +00:00
jschoubben 69d2b0d278 distribution serves name-of: the reference it keeps an upstream copy under
The node-engine composes an upstream artifact's image from the holder's own
name for the copy; distribution owns that naming (ParseSource, Source.Name), so
it answers it on the image seat rather than another module repeating the rule.

Builds: design 47 H2 H-A-513 second addendum
2026-11-23 02:02:10 +01:00
jochen 7fd6d89567 systemd-resolved: find the links to give back from resolved, never a routed one; answer-within is a config value (issue 1981 review)
The guard kept the links it had turned off in memory, so a VPN link turned
off before it was routed got its default route back, and a guard restarted
behind a sign-in page gave nothing back. It now reads them from resolved
each round and skips a link whose domains are all routing domains. How long
a mesh resolver is given to answer is the config value answer-within.
2026-11-19 09:50:08 +01:00
jochen cddfeba266 systemd-resolved: let a network's own servers answer while the mesh's resolvers are silent (issue 1981)
Behind a guest network's sign-in page the private network is out of reach,
and the guard sent every name to the mesh's resolvers, so the sign-in page
itself could not be found. The guard now asks the mesh's resolvers each
round and gives the links it turned off their default route back while none
answers; once one answers they lose it again.
2026-11-19 09:31:54 +01:00
90 changed files with 7782 additions and 147 deletions
@@ -34,7 +34,7 @@ func jsonFields(v any) map[string]bool {
func TestTheVerbsSpeakTheSeatsContract(t *testing.T) {
inputs := map[string]any{reg.VerbPublish: reg.PublishInput{}, reg.VerbPublishPart: reg.PublishPartInput{},
reg.VerbVersions: reg.VersionsInput{}, reg.VerbRemove: reg.RemoveInput{}, reg.VerbHold: reg.HoldInput{},
reg.VerbRelease: reg.ReleaseInput{}, reg.VerbMirror: reg.MirrorInput{}, reg.VerbTags: reg.TagsInput{}}
reg.VerbRelease: reg.ReleaseInput{}, reg.VerbMirror: reg.MirrorInput{}, reg.VerbNameOf: reg.NameOfInput{}, reg.VerbTags: reg.TagsInput{}}
seen := 0
for _, tool := range tools(&holder.Verbs{}, kept[holder.Window]{}, nil) {
seat, verb, ok := strings.Cut(tool.Name, ".")
@@ -51,8 +51,8 @@ func TestTheVerbsSpeakTheSeatsContract(t *testing.T) {
}
}
}
if seen != 14 {
t.Errorf("%d seat verbs served, want 14 (8 on the image seat, 6 on the artifact seat)", seen)
if seen != 15 {
t.Errorf("%d seat verbs served, want 15 (9 on the image seat, 6 on the artifact seat)", seen)
}
for event, want := range map[string]any{holder.EventPublished: &reg.Outcome{}, holder.EventKept: &reg.KeptEvent{}, holder.EventHeld: &reg.Hold{}, holder.EventReleased: &reg.Hold{}} {
b, _ := json.Marshal(eventBody(event, holder.Event{Name: "m/a", Kind: holder.KindArchive, Digest: "sha256:aa", Holder: holder.Self, By: "x.artifact-store-tools"}))
@@ -364,6 +364,19 @@ func tools(v *holder.Verbs, windows kept[holder.Window], taken *asks) []stdio.To
}
return reg.MirrorAnswer{Digest: in.Digest, Reference: ref}, nil
}},
stdio.Tool{Name: holder.ImageSeat + "." + holder.VerbNameOf, Description: "The reference an outside image, as a manifest's from names it pinned by its digest, is kept under in the store (upstream/<host>/<path>@<digest> in the seat's form), the one mirror answers; reads only, asks no copy, refuses a from with no digest.",
Input: obj(map[string]any{"from": s("<name>[:<tag>]@sha256:…")}, "from"),
Run: func(args map[string]any) (any, error) {
in, err := arg[reg.NameOfInput](args)
if err != nil {
return nil, err
}
ref, err := v.NameOf(holder.ImageSeat, in.From)
if err != nil {
return nil, err
}
return reg.NameOfAnswer{Reference: ref}, nil
}},
stdio.Tool{Name: "registry_health", Description: "distribution's health check, run by the runtime each minute: versions of each seat asked through the store's read side (the program's port 5100); fails naming the program when it does not answer.",
Input: obj(map[string]any{}),
Run: func(map[string]any) (any, error) {
@@ -823,6 +823,18 @@ func TestTheHolderOfTheTwoImageSeats(t *testing.T) {
if strings.ContainsAny(key, ":@") {
t.Errorf("the ask's key %q holds characters a key may not", key)
}
// name-of answers the same reference for a manifest's pinned from, asking no copy (H-A-513); a from with no digest,
// and the artifact seat, are refused.
for _, from := range []string{"nats:2.11.17-alpine@" + d, "docker.io/library/nats@" + d} {
if named, err := b.v.NameOf(ImageSeat, from); err != nil || named != want || len(asked) != 1 {
t.Errorf("name-of %s = %q, %v, asks %d: want %s and no copy asked", from, named, err, len(asked), want)
}
}
for seat, from := range map[string]string{ImageSeat: "nats:2.11.17-alpine", ArtifactSeat: "nats@" + d} {
if named, err := b.v.NameOf(seat, from); err == nil {
t.Errorf("name-of %s on %s = %q: want a refusal", from, seat, named)
}
}
if err := b.v.Mirrored(asked[key]); err != nil || len(b.said) != 1 || b.said[0].event != EventPublished ||
b.said[0].body.Reference != want || b.said[0].body.Kind != KindUpstream || len(asked) != 0 {
t.Fatalf("the copy's end = %v, said %+v, asks %v: want published with the reference and the ask gone", err, b.said, asked)
@@ -26,6 +26,7 @@ const (
VerbVersions = "versions"
VerbRemove = "remove"
VerbMirror = "mirror"
VerbNameOf = "name-of"
VerbTags = "tags"
VerbHold = "hold"
VerbRelease = "release"
@@ -34,11 +35,11 @@ const (
// Seats are the seats distribution answers verbs on.
var Seats = []string{ImageSeat, ArtifactSeat}
// VerbsOf are a seat's verbs: mirror and tags on the image seat alone; hold, release and list on both of distribution's.
// VerbsOf are a seat's verbs: mirror, name-of and tags on the image seat alone; hold, release and list on both of distribution's.
func VerbsOf(seat string) []string {
v := []string{VerbPublish, VerbPublishPart, VerbVersions, VerbRemove, VerbHold, VerbRelease, VerbList}
if seat == ImageSeat {
v = append(v, VerbMirror, VerbTags)
v = append(v, VerbMirror, VerbNameOf, VerbTags)
}
sort.Strings(v)
return v
@@ -333,6 +333,25 @@ func (v *Verbs) Mirror(seat, caller string, r MirrorRequest) (string, error) {
return SeatReference(seat, v.Catalog.Reference(src.Name(), r.Digest)), nil
}
// NameOf is `name-of` on the image seat (design 47 H2 H-A-513): the reference mirror answers, and keeps the copy under, for an
// outside image as a manifest's from names it, pinned (<name>[:<tag>]@sha256:<digest>): the holder's own name for the copy,
// upstream/<host>/<path>, with that digest, in the seat's form. It reads only and asks no copy; a from that pins no digest is
// refused, as mirror refuses it.
func (v *Verbs) NameOf(seat, from string) (string, error) {
if seat != ImageSeat {
return "", fmt.Errorf("name-of: %s serves no name-of", seat)
}
_, digest, pinned := strings.Cut(strings.TrimSpace(from), "@")
if !pinned || !strings.HasPrefix(digest, "sha256:") || len(digest) != len("sha256:")+64 {
return "", fmt.Errorf("name-of: refused: %q pins no digest, and an upstream image is named only by its pinned digest", from)
}
src, err := ParseSource(from)
if err != nil {
return "", err
}
return SeatReference(seat, v.Catalog.Reference(src.Name(), digest)), nil
}
// Mirrored runs one asked copy and says its outcome on the image seat's events: published with the reference, or
// refused with the reason; the ask leaves the state either way. An outcome that cannot be said keeps the ask, so the
// next watch takes it on again.
+1
View File
@@ -24,6 +24,7 @@
"hold",
"list",
"mirror",
"name-of",
"publish",
"publish-part",
"release",
+9 -3
View File
@@ -694,6 +694,13 @@ func TestToolsAreTheOnesTheReadmeNamesAndTheManifestBuilds(t *testing.T) {
"cmd/forge": {"MESH_GITEA_URL", "MESH_GITEA_TOOLS_USER"},
"cmd/package-registry": {"MESH_GITEA_URL", "MESH_GITEA_TOOLS_USER", "MESH_GITEA_PACKAGES_USER"},
}
// H-A-564: until gitea runs as its own account, each Go bundle is handed the token files gitea's TypeScript bundle
// keeps under its state directory, read when the vault refuses the caller's account.
files := map[string]map[string]string{
"cmd/forge": {"MESH_GITEA_TOKEN_FILE": "${dir:runtime-state}/token"},
"cmd/package-registry": {"MESH_GITEA_TOKEN_FILE": "${dir:runtime-state}/token",
"MESH_GITEA_PACKAGES_TOKEN_FILE": "${dir:runtime-state}/packages-token"},
}
for _, a := range m.Build.Artifacts {
want, ok := wants[a.From]
if !ok {
@@ -713,10 +720,9 @@ func TestToolsAreTheOnesTheReadmeNamesAndTheManifestBuilds(t *testing.T) {
t.Errorf("%s is given %s: it acts as an account of its own, not the administrator", a.From, k)
}
}
// Design 47 H2 §808, H-A-422 (1): the token is read through the vault seat's get, never from a file.
for _, k := range []string{"MESH_GITEA_TOKEN_FILE", "MESH_GITEA_PACKAGES_TOKEN_FILE"} {
if a.Env[k] != "" {
t.Errorf("%s is given %s: its token is read from the vault", a.From, k)
if a.Env[k] != files[a.From][k] {
t.Errorf("%s is given %s %q, want %q (H-A-564)", a.From, k, a.Env[k], files[a.From][k])
}
}
}
+135 -15
View File
@@ -3,12 +3,20 @@ package forgehttp
// The forge module's tokens as its Go bundles read them (design 47 H2 §808; H-A-422 (1), H-A-426): kept in the vault as
// the module's own, `module/gitea/<account>`, written by the TypeScript bundle's minter through own-put, and read here
// through the seat `mesh-vault`'s `get`, sealed to this process's own key (the Go SDK's seal opens it), at start and at
// each `secret-changed` that names it. Never a file: the bundle holds the token in memory only, and says nothing of it.
// each `secret-changed` that names it. The bundle holds the token in memory only, and says nothing of it.
//
// Until gitea runs as its own account (H-A-543), the vault refuses the tool runner's account these bundles are called
// under, so (H-A-564) when the vault refuses the caller's account, the token is read from the file gitea's TypeScript
// bundle keeps it in under its state directory (MESH_GITEA_TOKEN_FILE for the tools' account,
// MESH_GITEA_PACKAGES_TOKEN_FILE for the packages account, each with its scopes line beside it), and Follow says once
// at start which source each token came from. The fallback ends with H-A-543's delivery.
import (
"encoding/json"
"errors"
"fmt"
"os"
"path/filepath"
"strings"
"sync"
@@ -28,15 +36,41 @@ func VaultName(account string) string { return "module/gitea/" + account }
// Ask asks one seat verb and answers its reply (stdio.Ask).
type Ask func(address string, args any) (json.RawMessage, error)
// VaultToken is one account's token as this process holds it, read from the vault.
// Refusals are what the vault answers when it refuses the caller's account a module's own secret (mesh-vault's
// callerModule and its own-secret judgement): the only answers the token file is read after (H-A-564).
var Refusals = []string{"is no module's account", "handed only to an account of"}
// refused is whether err is the vault refusing the caller's account.
func refused(err error) bool {
for _, r := range Refusals {
if strings.Contains(err.Error(), r) {
return true
}
}
return false
}
// Sources of a token: the vault, or the file gitea's TypeScript bundle keeps (H-A-564).
const (
SourceVault = "the vault"
SourceFile = "the file gitea keeps"
)
// VaultToken is one account's token as this process holds it, read from the vault, or from File when the vault
// refuses the caller's account (H-A-564).
type VaultToken struct {
Account string
ask Ask
keys seal.KeyPair
// File is the token file gitea's TypeScript bundle keeps for Account, "" when the manifest names none.
File string
// FileByDefault says File is DefaultStateDir's, the manifest naming none.
FileByDefault bool
ask Ask
keys seal.KeyPair
mu sync.Mutex
token string
generation int
source string
}
// NewVaultToken is an account's token read through ask, sealed to a key made for this process.
@@ -48,10 +82,20 @@ func NewVaultToken(account string, ask Ask) (*VaultToken, error) {
return &VaultToken{Account: account, ask: ask, keys: keys}, nil
}
// Load reads the account's token from the vault again.
// Load reads the account's token from the vault again; from File when the vault refuses the caller's account.
func (t *VaultToken) Load() error {
raw, err := t.ask(VaultGet, map[string]any{"name": VaultName(t.Account), "public_key": t.keys.PublicKey})
if err != nil {
if t.File != "" && refused(err) {
token, ferr := t.fromFile()
if ferr != nil {
return fmt.Errorf("the vault did not hand %s (%v), and %w", VaultName(t.Account), err, ferr)
}
t.mu.Lock()
t.token, t.generation, t.source = token, 0, SourceFile
t.mu.Unlock()
return nil
}
return fmt.Errorf("the vault did not hand %s: %w", VaultName(t.Account), err)
}
var got struct {
@@ -77,16 +121,45 @@ func (t *VaultToken) Load() error {
return fmt.Errorf("the vault's %s is empty", VaultName(t.Account))
}
t.mu.Lock()
t.token, t.generation = token, got.Generation
t.token, t.generation, t.source = token, got.Generation, SourceVault
t.mu.Unlock()
return nil
}
// fromFile is the token gitea's TypeScript bundle keeps in File, refused unless its scopes line names Account (as the
// bundle writes it: "<scopes> for <account>").
func (t *VaultToken) fromFile() (string, error) {
raw, err := os.ReadFile(t.File)
if err != nil {
return "", fmt.Errorf("the token file gitea keeps for %s cannot be read: %w", t.Account, err)
}
line, err := os.ReadFile(t.File + ".scopes")
if err != nil || !strings.HasSuffix(strings.TrimSpace(string(line)), " for "+t.Account) {
return "", fmt.Errorf("the token kept at %s is not %s's (its scopes line does not name it); nothing is sent", t.File, t.Account)
}
token := strings.TrimSpace(string(raw))
if token == "" {
return "", fmt.Errorf("the token kept at %s is empty; nothing is sent", t.File)
}
return token, nil
}
// Source is where the token held came from, SourceVault or SourceFile; "" when none is held.
func (t *VaultToken) Source() string {
t.mu.Lock()
defer t.mu.Unlock()
return t.source
}
// Token is the token held; read from the vault when none is yet (the module mints it first).
func (t *VaultToken) Token() (string, error) {
t.mu.Lock()
token := t.token
token, source := t.token, t.source
t.mu.Unlock()
if source == SourceFile {
// gitea's TypeScript bundle mints into its file again on a refusal: the file is read at each call, as before C4.
return t.fromFile()
}
if token != "" {
return token, nil
}
@@ -135,12 +208,46 @@ func TokenOf(account string) (*VaultToken, error) {
if err != nil {
return nil, err
}
t.File, t.FileByDefault = TokenFile(account)
processTokens[account] = t
return t, nil
}
// DefaultStateDir is gitea's runtime-state directory (the manifest's `${dir:mesh-state}/state`), where its TypeScript
// bundle keeps the token files, for a composition that hands the Go bundles no token file (gitea 0.1.316 hands them
// no variable naming that directory either; H-A-564).
const DefaultStateDir = "/var/lib/mesh/gitea/state"
// TokenFile is the file the manifest names for account's token as gitea's TypeScript bundle keeps it (H-A-564):
// MESH_GITEA_PACKAGES_TOKEN_FILE for the packages account, MESH_GITEA_TOKEN_FILE for the tools' account; when the
// variable is not handed, the file in DefaultStateDir, and byDefault says so. "" for any other account.
func TokenFile(account string) (file string, byDefault bool) {
packages := os.Getenv("MESH_GITEA_PACKAGES_USER")
if packages == "" {
packages = PackagesAccount
}
tools := os.Getenv("MESH_GITEA_TOOLS_USER")
if tools == "" {
tools = ToolsAccount
}
variable, name := "", ""
switch account {
case packages:
variable, name = "MESH_GITEA_PACKAGES_TOKEN_FILE", "packages-token"
case tools:
variable, name = "MESH_GITEA_TOKEN_FILE", "token"
default:
return "", false
}
if f := os.Getenv(variable); f != "" {
return f, false
}
return filepath.Join(DefaultStateDir, name), true
}
// Follow reads each account's token once the runtime serves, and again at each `secret-changed` naming it, saying
// through logf what it read (never the token). It returns when the subscription ends.
// through logf what it read and, once at start, from which source (never the token). It returns when the
// subscription ends.
func Follow(logf func(format string, args ...any), accounts ...string) error {
var held []*VaultToken
for _, a := range accounts {
@@ -151,13 +258,7 @@ func Follow(logf func(format string, args ...any), accounts ...string) error {
held = append(held, t)
}
<-stdio.Served()
for _, t := range held {
if err := t.Load(); err != nil {
logf("%s is not read at the start (the module mints it): %v", VaultName(t.Account), err)
} else {
logf("read %s at generation %d", VaultName(t.Account), t.Generation())
}
}
Start(logf, held...)
return stdio.Subscribe(SecretChanged, func(e stdio.Envelope) error {
var errs []error
for _, t := range held {
@@ -171,3 +272,22 @@ func Follow(logf func(format string, args ...any), accounts ...string) error {
return errors.Join(errs...)
})
}
// Start reads each token once and says, through logf, from which source it came (H-A-564), never the token.
func Start(logf func(format string, args ...any), held ...*VaultToken) {
for _, t := range held {
switch err := t.Load(); {
case err != nil:
logf("%s is not read at the start (the module mints it): %v", VaultName(t.Account), err)
case t.Source() == SourceFile:
how := "named by the manifest"
if t.FileByDefault {
how = "the default path, the manifest naming none"
}
logf("the vault refuses %s to this process's account, so %s's token is read from %s, %s (%s; H-A-564)",
VaultName(t.Account), t.Account, SourceFile, t.File, how)
default:
logf("read %s at generation %d from %s", VaultName(t.Account), t.Generation(), SourceVault)
}
}
}
@@ -0,0 +1,138 @@
package forgehttp
import (
"encoding/json"
"errors"
"fmt"
"os"
"path/filepath"
"strings"
"testing"
"git.novox.be/novox/mesh-sdk/go/seal"
)
// H-A-564: until gitea runs as its own account, a Go bundle the vault refuses reads the token gitea's TypeScript
// bundle keeps in its state directory, and says once at start which source it used; any other refusal reads no file.
func TestATokenComesFromTheVaultOrWhenTheVaultRefusesTheCallersAccountFromTheFileGiteaKeeps(t *testing.T) {
dir := t.TempDir()
keep := func(name, token, scopes string) string {
p := filepath.Join(dir, name)
if err := os.WriteFile(p, []byte(token+"\n"), 0o600); err != nil {
t.Fatal(err)
}
if scopes != "" {
if err := os.WriteFile(p+".scopes", []byte(scopes+"\n"), 0o600); err != nil {
t.Fatal(err)
}
}
return p
}
tools := keep("token", "file-tools", "read:package,read:user,write:issue,write:repository for mesh-tools")
packages := keep("packages-token", "file-packages", "write:package for mesh-packages")
admins := keep("admins-token", "file-admin", "write:admin")
vaultHolds := func(token string) Ask {
return func(address string, args any) (json.RawMessage, error) {
a := args.(map[string]any)
value, _ := json.Marshal(map[string]any{"token": token})
box, err := seal.Seal(string(value), a["public_key"].(string))
if err != nil {
return nil, err
}
return json.Marshal(map[string]any{"generation": 3, "sealed": box})
}
}
vaultSays := func(said string) Ask {
return func(string, any) (json.RawMessage, error) { return nil, errors.New(said) }
}
notModule := vaultSays("novox.node-tools is no module's account (<machine>.<module>), so it has no own secret here")
for _, c := range []struct {
name, account, file string
ask Ask
token, source, err string
}{
{"the vault hands it", "mesh-tools", tools, vaultHolds("vault-tools"), "vault-tools", SourceVault, ""},
{"the vault refuses the tool runner: the tools' file", "mesh-tools", tools, notModule, "file-tools", SourceFile, ""},
{"the vault refuses the tool runner: the packages file", "mesh-packages", packages, notModule, "file-packages", SourceFile, ""},
{"another module's account: the file", "mesh-tools", tools,
vaultSays("module/gitea/mesh-tools is gitea's own secret, handed only to an account of gitea"), "file-tools", SourceFile, ""},
{"the vault holds none: no file is read", "mesh-tools", tools, vaultSays("the vault holds no secret named module/gitea/mesh-tools"), "", "", "holds no secret"},
{"no file named: the refusal stands", "mesh-tools", "", notModule, "", "", "no module's account"},
{"a file whose scopes line names another account is not sent", "mesh-tools", admins, notModule, "", "", "is not mesh-tools's"},
} {
t.Run(c.name, func(t *testing.T) {
v, err := NewVaultToken(c.account, c.ask)
if err != nil {
t.Fatal(err)
}
v.File = c.file
var said []string
Start(func(f string, a ...any) { said = append(said, fmt.Sprintf(f, a...)) }, v)
got, err := v.Token()
if c.err != "" {
if err == nil || !strings.Contains(err.Error(), c.err) {
t.Fatalf("token %q, error %v; want an error saying %q", got, err, c.err)
}
return
}
if err != nil || got != c.token || v.Source() != c.source {
t.Fatalf("token %q from %q (%v); want %q from %q", got, v.Source(), err, c.token, c.source)
}
if len(said) != 1 || !strings.Contains(said[0], c.source) || strings.Contains(said[0], c.token) {
t.Fatalf("said %q: one line naming %q, never the token", said, c.source)
}
})
}
// A token gitea mints into its file again is the one sent next.
v, _ := NewVaultToken("mesh-tools", notModule)
v.File = tools
Start(func(string, ...any) {}, v)
keep("token", "file-tools-2", "read:package for mesh-tools")
if got, _ := v.Token(); got != "file-tools-2" {
t.Fatalf("after gitea minted again, %q is sent", got)
}
}
// H-A-564: the manifest's file for each account wins; without it, the file in gitea's runtime-state directory, said
// as the default.
func TestTheTokenFileOfAnAccountIsTheOneTheManifestNamesForItElseTheDefault(t *testing.T) {
type file struct {
path string
byDefault bool
}
for _, c := range []struct {
name string
tools, packs string
want map[string]file
}{
{"named by the manifest", "/s/token", "/s/packages-token", map[string]file{
"mesh-tools": {"/s/token", false}, "mesh-packages": {"/s/packages-token", false}, "other": {"", false}}},
{"named by none: the default", "", "", map[string]file{
"mesh-tools": {"/var/lib/mesh/gitea/state/token", true},
"mesh-packages": {"/var/lib/mesh/gitea/state/packages-token", true}, "other": {"", false}}},
} {
t.Run(c.name, func(t *testing.T) {
t.Setenv("MESH_GITEA_TOKEN_FILE", c.tools)
t.Setenv("MESH_GITEA_PACKAGES_TOKEN_FILE", c.packs)
for account, want := range c.want {
if p, d := TokenFile(account); (file{p, d}) != want {
t.Errorf("TokenFile(%s) = %q, %v; want %q, %v", account, p, d, want.path, want.byDefault)
}
}
})
}
// The start line says the default as such.
dir := t.TempDir()
p := filepath.Join(dir, "token")
_ = os.WriteFile(p, []byte("t\n"), 0o600)
_ = os.WriteFile(p+".scopes", []byte("read:user for mesh-tools\n"), 0o600)
v, _ := NewVaultToken("mesh-tools", func(string, any) (json.RawMessage, error) {
return nil, errors.New("novox.node-tools is no module's account")
})
v.File, v.FileByDefault = p, true
var said string
Start(func(f string, a ...any) { said = fmt.Sprintf(f, a...) }, v)
if !strings.Contains(said, "the default path") {
t.Fatalf("said %q, not that the file is the default", said)
}
}
+3
View File
@@ -544,7 +544,9 @@
"env": {
"MESH_GITEA_URL": "http://127.0.0.1:${port:3000}",
"MESH_GITEA_TOOLS_USER": "mesh-tools",
"MESH_GITEA_TOKEN_FILE": "${dir:runtime-state}/token",
"MESH_GITEA_PACKAGES_USER": "mesh-packages",
"MESH_GITEA_PACKAGES_TOKEN_FILE": "${dir:runtime-state}/packages-token",
"MESH_NPM_OWNER": "novox"
}
},
@@ -561,6 +563,7 @@
"env": {
"MESH_GITEA_URL": "http://127.0.0.1:${port:3000}",
"MESH_GITEA_TOOLS_USER": "mesh-tools",
"MESH_GITEA_TOKEN_FILE": "${dir:runtime-state}/token",
"MESH_GITEA_PATCH_DIR": "${dir:forge-patches}"
}
},
+8 -1
View File
@@ -374,8 +374,15 @@ test("the manifest hands the tools their account, and the Go forge bundle holds
const packages = manifest.build.artifacts.find((a: any) => a.name === "package-registry");
assert.equal(packages.env.MESH_GITEA_PACKAGES_USER, PACKAGES_ACCOUNT);
assert.equal(packages.env.MESH_GITEA_ADMIN_PASSWORD_FILE, undefined);
// H-A-564: until gitea runs as its own account, the Go bundles are handed the token files the TypeScript bundle keeps
// under its state directory, read when the vault refuses the caller's account; no other artifact is.
const files: Record<string, [string | undefined, string | undefined]> = {
forge: ["${dir:runtime-state}/token", undefined],
"package-registry": ["${dir:runtime-state}/token", "${dir:runtime-state}/packages-token"],
};
for (const a of manifest.build.artifacts) {
assert.equal(a.env?.MESH_GITEA_TOKEN_FILE ?? a.env?.MESH_GITEA_PACKAGES_TOKEN_FILE, undefined, `${a.name} is handed a token file`);
assert.deepEqual([a.env?.MESH_GITEA_TOKEN_FILE, a.env?.MESH_GITEA_PACKAGES_TOKEN_FILE], files[a.name] ?? [undefined, undefined],
`${a.name}'s token files`);
}
assert.ok(manifest.invokes.includes("seat:mesh-vault.own-put") && manifest.invokes.includes("seat:mesh-vault.get"), manifest.invokes.join(","));
assert.ok(manifest.consumes.includes("mesh-vault.secret-changed"), "the Go bundles hear the vault's changes");
+30 -1
View File
@@ -5,7 +5,8 @@ The window manager as a module (novox/hq ADR 0208, research 026, to-be 42 phase
- **Claims `node-display-session`** and serves its verbs `reload`, `workspaces` and `windows`.
- **Requires `x11-display`**, which only `xorg` on the same machine provides.
- **Packages:** `i3-wm`, and `dex`, which the configuration has always run for XDG autostart. `dex`
was missing on the desktop, so its autostart entries never started there.
was missing on the desktop, so its autostart entries never started there. `xdg-utils` (ADR 0303 §2),
for `open`'s `xdg-mime` and `xdg-open`.
- **Environment** (ADR 0203): `XDG_CURRENT_DESKTOP=i3` and `XDG_SESSION_DESKTOP=i3`. They reach
shells, the session (through `xorg`'s block) and the user manager (`environment.d`). The portal
keys off the first.
@@ -49,6 +50,7 @@ own business.
| `node-display-session.reload` | a | checks, then reloads, keeping windows. Refused with the errors when the check fails; `force` reloads anyway |
| `node-display-session.workspaces` | r | number, name, output, visible, focused, urgent |
| `node-display-session.windows` | r | container id, X id, class, instance, role, title, workspace, output, focused, urgent, floating, fullscreen, scratchpad, marks; narrowed to one workspace |
| `node-display-session.open` | a | opens an http or https address in the session's default browser, for any caller over the bus |
| `i3_focus` | d | a window by criteria, or a workspace |
| `i3_move` | d | windows to a workspace or output; a workspace to an output |
| `i3_layout_save` | d | a workspace's arrangement as a named layout of placeholders (class, instance, role), in `~/.local/state/mesh/i3/layouts/` |
@@ -65,6 +67,33 @@ value a caller gives is quoted before it reaches an i3 command. With no i3 runni
`{"error": "no-graphical-session", …}`. The bundle's binary is `i3-tools`, so nothing that looks for
`i3` by name finds it.
## `open` (novox/hq design 08 sign-in-page §3, §29, §30, §31; issue 935)
Opens an address in the session's default browser, for any caller over the bus — the sign-in
reaction (`networkmanager`'s watcher) never calls it, so this is for every other caller. It does not
go through i3's IPC `exec`, which hands a shell a command line; instead it asks the account's own
program chooser (`xdg-mime query default x-scheme-handler/<scheme>`) and starts the program through
the account's service manager (`systemd-run --user --collect --quiet --wait -- xdg-open <address>`),
the address as one argument, never a shell. The run is bound to 10 s: within it, success answers
`opened` and a failure is refused naming the opener's status; still running at the bound, the page
may still be opening, so the run is left to go on and the answer says `opening`. `program` and
`command` (the desktop entry and the first word of its `Exec` line) are given only once the opener
started.
**Refused**, naming the reason: a scheme other than `http` or `https` (named), no scheme (a file
path), no host, an address over 2048 bytes once encoded, no graphical session running, no default
program for the scheme, the opener ending with a failure (its status named).
**The encoding** (RFC 3986): letters, digits, `-` `.` `_` `~` and the separators `:` `/` `?` `#` `[`
`]` `@` `&` `=` `+` `%` are kept as they are; every other character — a space, a quote, `;`, `$(`,
a comma among them — is percent-encoded, as the bytes of its UTF-8 form. Nothing is refused for a
character, and no shell ever reads the address.
**Every call that is acted on is written to the log of acts done by hand**
(`seat:mesh-hand-acts.hand-act`), with its caller and why; a call refused before the opener ran
writes no act. It hears nothing of the uplink and reads no kept event at its own start: `i3` consumes
no `node-uplink` event (ADR 0689 §3).
## What it improves over today's configuration
Both workstations ran the same configuration. These changes are against it:
+13 -1
View File
@@ -14,6 +14,7 @@ import (
"path/filepath"
"time"
nodedisplaysession "git.novox.be/novox/mesh-contracts/go/seats/nodedisplaysession"
stdio "git.novox.be/novox/mesh-sdk/go"
"i3/internal/desktop"
@@ -53,7 +54,8 @@ func machine() *i3 {
if state == "" {
state = filepath.Join(home, ".local", "state")
}
t := &i3{d: desktop.Machine("i3"), configDir: filepath.Join(cfg, "i3"), layouts: filepath.Join(state, "mesh", "i3", "layouts")}
t := &i3{d: desktop.Machine("i3"), configDir: filepath.Join(cfg, "i3"), layouts: filepath.Join(state, "mesh", "i3", "layouts"),
handAct: liveHandAct, opener: openerRun}
t.socket = func() (string, error) {
runtime := filepath.Join("/run/user", fmt.Sprint(os.Getuid()))
i3sock := ""
@@ -83,6 +85,16 @@ func tools(t *i3) []stdio.Tool {
Input: desktop.Schema(map[string]any{"force": desktop.Flag("reload even when the check finds errors")}),
Run: call(t.reload),
},
{
Name: nodedisplaysession.Seat + "." + nodedisplaysession.VerbOpen,
Description: "Open an http or https address in the person's default browser, for any caller over the bus " +
"(not the sign-in reaction, which never calls it). Refused for any other scheme, no host, an address " +
"too long once encoded, no graphical session or no default program for the scheme; the opener's " +
"failure is refused naming its status. Answers once the opener has started: opened within its bound, " +
"or opening when it still runs. Every call is an act, recorded in the log of acts done by hand.",
Input: desktop.Schema(map[string]any{"address": desktop.Str("the http or https address to open")}, "address"),
Run: call(t.open),
},
{
Name: "node-display-session.workspaces",
Description: "The session's workspaces: number, name, output, and whether each is visible, focused or urgent.",
+21 -3
View File
@@ -17,6 +17,7 @@ import (
type manifest struct {
Capabilities []string `json:"capabilities"`
Requires []string `json:"requires"`
Invokes []string `json:"invokes"`
Claims []struct {
Name string `json:"name"`
Scope string `json:"scope"`
@@ -82,7 +83,7 @@ func resource(t *testing.T, m manifest, id string) map[string]any {
func TestItHoldsTheSessionSeatOnAMachineWithAnXDisplay(t *testing.T) {
m := readManifest(t)
if m.Seats != nil || len(m.Claims) != 1 || m.Claims[0].Name != "node-display-session" || strings.Join(m.Claims[0].Serves, ",") != "reload,workspaces,windows" {
if m.Seats != nil || len(m.Claims) != 1 || m.Claims[0].Name != "node-display-session" || strings.Join(m.Claims[0].Serves, ",") != "reload,workspaces,windows,open" {
t.Fatalf("%+v", m.Claims)
}
if strings.Join(m.Requires, ",") != "x11-display" {
@@ -97,7 +98,7 @@ func TestItHoldsTheSessionSeatOnAMachineWithAnXDisplay(t *testing.T) {
t.Errorf("the seat's %s is not served", v)
}
}
if len(served) != len(m.Tools)+3 {
if len(served) != len(m.Tools)+4 {
t.Fatalf("served %d, listed %d", len(served), len(m.Tools))
}
for _, n := range m.Tools {
@@ -175,6 +176,23 @@ func TestTheConfigurationIsTheModulesFileImprovedAndEndsWithTheDropIns(t *testin
}
}
// open is an act (design 08 sign-in-page §29, DQ-7): the manifest invokes the hand-act log, the
// package the opener needs is present (ADR 0303 §2), and open is among node-display-session's
// served verbs.
func TestOpenIsAnActWithItsPackageAndInvoke(t *testing.T) {
m := readManifest(t)
if strings.Join(m.Invokes, ",") != "seat:mesh-hand-acts.hand-act" {
t.Fatalf("invokes: %v", m.Invokes)
}
served := map[string]bool{}
for _, v := range m.Claims[0].Serves {
served[v] = true
}
if !served["open"] {
t.Fatal("node-display-session does not serve open")
}
}
func TestTheLoginManagersEntryRunsTheSessionsStart(t *testing.T) {
m := readManifest(t)
r := resource(t, m, "session")
@@ -194,7 +212,7 @@ func TestTheLoginManagersEntryRunsTheSessionsStart(t *testing.T) {
pkgs[x["package"].(string)] = true
}
}
if !pkgs["i3-wm"] || !pkgs["dex"] || len(pkgs) != 2 {
if !pkgs["i3-wm"] || !pkgs["dex"] || !pkgs["xdg-utils"] || len(pkgs) != 3 {
t.Fatalf("%v", pkgs)
}
a := m.Build.Artifacts[0]
+300
View File
@@ -0,0 +1,300 @@
// node-display-session.open (design 08 sign-in-page §3, §29, §30, §31): opens an http or https
// address in the person's default browser, outside i3's own IPC (which hands a shell a command
// line); this verb takes the address as one argument, through the account's own program chooser
// (xdg-mime) and the account's service manager (systemd-run --user), never a shell. It is an act
// (ADR 0565 §10): every call, refused or not, is written to the log of acts done by hand (lead
// answer note (b), DQ-7: "each call").
package main
import (
"bytes"
"context"
"errors"
"fmt"
"os"
"os/exec"
"path/filepath"
"regexp"
"strings"
"syscall"
"time"
nodedisplaysession "git.novox.be/novox/mesh-contracts/go/seats/nodedisplaysession"
stdio "git.novox.be/novox/mesh-sdk/go"
"i3/internal/desktop"
)
// defaultOpenTimeout is open's own bound on the opener command (design 08 sign-in-page §18, §29; a
// stated constant, lead answer R2-7): run beyond it, the page may still be opening, so the opener
// is left to go on and the answer says opening. A test shortens it with the i3's openBound field.
const defaultOpenTimeout = 10 * time.Second
// openMaxAddress is the limit on an address once encoded (design 08 sign-in-page §3).
const openMaxAddress = 2048
// schemePattern is a URI's scheme (RFC 3986): letters, digits, +, . and - after the first letter,
// ended by a colon.
var schemePattern = regexp.MustCompile(`^([a-zA-Z][a-zA-Z0-9+.-]*):`)
// openKept are the characters open's encoding never touches, beside the unreserved ones (letters,
// digits, -, ., _, ~): the separators a URL needs, and % itself, so an address already encoded is
// not doubled (design 08 sign-in-page §3, lead answer U-M2/R2-9).
const openKept = "-._~:/?#[]@&=+%"
// checkAddressShape is the refusals of §3 that do not need the session or the opener: a scheme
// other than http or https, no scheme (a file path), no host.
func checkAddressShape(address string) (scheme string, err error) {
m := schemePattern.FindStringSubmatch(address)
if m == nil {
return "", fmt.Errorf("no scheme: %q is a file path, not an http or https address", address)
}
scheme = strings.ToLower(m[1])
if scheme != "http" && scheme != "https" {
return "", fmt.Errorf("a scheme other than http or https: %s", scheme)
}
afterScheme := address[len(m[0]):]
if !strings.HasPrefix(afterScheme, "//") {
return "", fmt.Errorf("no host: %s has no // after its scheme", scheme)
}
rest := afterScheme[2:]
end := strings.IndexAny(rest, "/?#")
authority := rest
if end >= 0 {
authority = rest[:end]
}
if at := strings.LastIndex(authority, "@"); at >= 0 {
authority = authority[at+1:]
}
if authority == "" {
return "", fmt.Errorf("no host")
}
return scheme, nil
}
// encodeAddress is §3's encoding: RFC 3986's unreserved characters and the separators a URL needs
// (openKept) are kept; every other character is percent-encoded, as the bytes of its UTF-8 form.
// Nothing is refused for a character, and the result is never read by a shell.
func encodeAddress(address string) string {
var b strings.Builder
for i := 0; i < len(address); i++ {
c := address[i]
switch {
case c >= 'A' && c <= 'Z', c >= 'a' && c <= 'z', c >= '0' && c <= '9':
b.WriteByte(c)
case strings.IndexByte(openKept, c) >= 0:
b.WriteByte(c)
default:
fmt.Fprintf(&b, "%%%02X", c)
}
}
return b.String()
}
// defaultProgram asks xdg-mime for the scheme's default handler, as §18 does for the same reason:
// the desktop entry's name (such as "firefox.desktop"), or an error naming the scheme when there is
// none.
func defaultProgram(ctx context.Context, d desktop.Desk, env []string, scheme string) (string, error) {
res := d.Run(ctx, env, nil, "xdg-mime", "query", "default", "x-scheme-handler/"+scheme)
name := strings.TrimSpace(res.Stdout)
if !res.OK() || name == "" {
return "", fmt.Errorf("no default program for x-scheme-handler/%s", scheme)
}
return name, nil
}
// entryCommand is the first word of a desktop entry's Exec line, read from the XDG data
// directories (design 08 sign-in-page §29): the program the entry runs, without its field codes
// and arguments.
func entryCommand(entry string) string {
for _, dir := range xdgDataDirs() {
b, err := os.ReadFile(filepath.Join(dir, "applications", entry))
if err != nil {
continue
}
inEntry := false
for _, line := range strings.Split(string(b), "\n") {
line = strings.TrimSpace(line)
switch {
case strings.HasPrefix(line, "["):
inEntry = line == "[Desktop Entry]"
case inEntry:
if exec, ok := strings.CutPrefix(line, "Exec="); ok {
if fields := strings.Fields(exec); len(fields) > 0 {
return fields[0]
}
return ""
}
}
}
}
return ""
}
// xdgDataDirs is where desktop entries are found, most specific first: the account's own, then the
// system's (XDG_DATA_DIRS, or its default).
func xdgDataDirs() []string {
dirs := []string{os.Getenv("XDG_DATA_HOME")}
if dirs[0] == "" {
dirs[0] = filepath.Join(desktop.Home(), ".local", "share")
}
extra := os.Getenv("XDG_DATA_DIRS")
if extra == "" {
extra = "/usr/local/share:/usr/share"
}
for _, d := range strings.Split(extra, ":") {
if d != "" {
dirs = append(dirs, d)
}
}
return dirs
}
// openerRun runs the opener (systemd-run --wait -- xdg-open ...) through runWithoutKilling: it
// stops waiting at its bound without killing what it started (design 08 sign-in-page §18, §29;
// DMC-8, lead answer C-5), unlike internal/desktop's Exec (run.go), which kills the command's
// process group at its deadline. A page still opening at the bound is left to open: the browser
// outlives this call either way, since it runs under the account's own service manager
// (systemd-run --user), not as this process's child.
func openerRun(ctx context.Context, env []string, stdin []byte, name string, args ...string) desktop.Result {
cmd := exec.Command(name, args...)
cmd.Env = env
cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
if stdin != nil {
cmd.Stdin = bytes.NewReader(stdin)
}
return runWithoutKilling(ctx, cmd)
}
// runWithoutKilling starts cmd and waits for it, but stops waiting at ctx's deadline without
// sending cmd any signal (design 08 sign-in-page §18, §29; DMC-8, lead answer C-5): left to go on,
// never torn down by the bound that only governs how long this call waits. A test calls this
// directly, with a command of its own whose Stdin and ExtraFiles it controls, to prove the started
// process is never killed, without a real sleep on either side.
func runWithoutKilling(ctx context.Context, cmd *exec.Cmd) desktop.Result {
res := desktop.Result{Command: append([]string{cmd.Path}, cmd.Args[1:]...)}
var out, errb bytes.Buffer
cmd.Stdout, cmd.Stderr = &out, &errb
if err := cmd.Start(); err != nil {
res.Code = 127
res.Stderr = err.Error()
return res
}
done := make(chan error, 1)
go func() { done <- cmd.Wait() }()
select {
case err := <-done:
res.Stdout, res.Stderr = out.String(), errb.String()
var exit *exec.ExitError
switch {
case err == nil:
case errors.As(err, &exit):
res.Code = exit.ExitCode()
if res.Code < 0 {
res.Code = 128
}
default:
res.Code = 1
if res.Stderr == "" {
res.Stderr = err.Error()
}
}
case <-ctx.Done():
// Left to go on (DMC-8, C-5): no signal is sent, so the process it started keeps running;
// the goroutine above still reads its exit, harmlessly, once it does.
res.TimedOut = true
}
return res
}
// open is node-display-session.open (design 08 sign-in-page §29): opens address in the session's
// default browser for the scheme, and answers once the opener has started.
func (t *i3) open(ctx context.Context, a desktop.Args) (ret any, err error) {
caller := stdio.CallerOf(map[string]any(a))
why := fmt.Sprintf("asked by %s", caller)
var address, encoded, program, started string
defer func() {
switch {
case err != nil:
t.journalOpen(address, "refused", err.Error())
t.recordHandAct(fmt.Sprintf("refused %s: %s", address, err), why)
default:
t.journalOpen(address, started, program)
t.recordHandAct(fmt.Sprintf("%s %s in %s", started, encoded, program), why)
}
}()
address, err = a.Text("address")
if err != nil {
return nil, err
}
scheme, err := checkAddressShape(address)
if err != nil {
return nil, err
}
encoded = encodeAddress(address)
if len(encoded) > openMaxAddress {
err = fmt.Errorf("the address is %d bytes once encoded, over %d", len(encoded), openMaxAddress)
return nil, err
}
s, err := t.d.Find()
if err != nil {
return nil, err
}
env := s.Env(t.d.Base)
program, err = defaultProgram(ctx, t.d, env, scheme)
if err != nil {
return nil, err
}
bound := t.openBound
if bound == 0 {
bound = defaultOpenTimeout
}
runCtx, cancel := context.WithTimeout(ctx, bound)
defer cancel()
runner := t.opener
if runner == nil {
runner = openerRun
}
res := runner(runCtx, env, nil, "systemd-run", "--user", "--collect", "--quiet", "--wait", "--", "xdg-open", encoded)
if !res.OK() && !res.TimedOut {
err = fmt.Errorf("the opener failed: %s", res.Err().Error())
return nil, err
}
started = nodedisplaysession.OpenAnswerStartedOpened
if res.TimedOut {
started = nodedisplaysession.OpenAnswerStartedOpening
}
command := entryCommand(program)
return nodedisplaysession.OpenAnswer{Address: encoded, Program: program, Command: command, Started: started}, nil
}
// journalOpen is open's one journal line per call (design 08 sign-in-page §29; lead answer R2-14):
// the address, opened or refused, and the program or the reason.
func (t *i3) journalOpen(address, outcome, programOrReason string) {
fmt.Fprintf(os.Stderr, "i3: open %s: %s (%s)\n", address, outcome, programOrReason)
}
// recordHandAct writes one call of open to the log of acts done by hand (design 08 sign-in-page
// §29; ADR 0565 §10; lead answer note (b)): every call, refused or not, with its caller and why.
func (t *i3) recordHandAct(what, why string) {
if t.handAct == nil {
return
}
if err := t.handAct(what, why); err != nil {
fmt.Fprintf(os.Stderr, "i3: open: the hand-act log did not take %q: %v\n", what, err)
}
}
// liveHandAct is the real hand-act writer: seat:mesh-hand-acts.hand-act, asked as this module
// (design 08 sign-in-page §29).
func liveHandAct(what, why string) error {
_, err := stdio.Ask("seat:mesh-hand-acts.hand-act", map[string]any{"what": what, "why": why, "verb": "open"})
return err
}
+271
View File
@@ -0,0 +1,271 @@
package main
import (
"context"
"os"
"os/exec"
"path/filepath"
"strings"
"syscall"
"testing"
"time"
nodedisplaysession "git.novox.be/novox/mesh-contracts/go/seats/nodedisplaysession"
"i3/internal/desktop"
)
// runCall records one call the stood-in opener saw, so a test can check the exact argv it was
// handed (design 08 sign-in-page §29, R2-9: one argument, no shell).
type runCall struct {
name string
args []string
}
// stubOpener builds an i3 whose session is found (unless find answers an error), whose xdg-mime
// query answers xdgMime, and whose opener answers the systemd-run call with opener (nil runs it is
// never reached). Every call, to either, is recorded in calls.
func stubOpener(t *testing.T, find func() (*desktop.Session, error), xdgMime desktop.Result, opener desktop.Runner) (*i3, *[]runCall) {
t.Helper()
calls := &[]runCall{}
run := func(ctx context.Context, env []string, stdin []byte, name string, args ...string) desktop.Result {
*calls = append(*calls, runCall{name, args})
if name != "xdg-mime" {
t.Fatalf("unexpected command on the session's own run: %s %v", name, args)
}
return xdgMime
}
var wrapped desktop.Runner
if opener != nil {
wrapped = func(ctx context.Context, env []string, stdin []byte, name string, args ...string) desktop.Result {
*calls = append(*calls, runCall{name, args})
return opener(ctx, env, stdin, name, args...)
}
} else {
wrapped = func(ctx context.Context, env []string, stdin []byte, name string, args ...string) desktop.Result {
t.Fatalf("the opener never runs: %s %v", name, args)
return desktop.Result{}
}
}
return &i3{d: desktop.Desk{Find: find, Run: run}, opener: wrapped, openBound: 50 * time.Millisecond}, calls
}
// resultOpener is an opener stub that answers res, blocking on ctx when res.TimedOut (as a real
// still-running opener would appear to this call).
func resultOpener(res desktop.Result) desktop.Runner {
return func(ctx context.Context, env []string, stdin []byte, name string, args ...string) desktop.Result {
if res.TimedOut {
<-ctx.Done()
return desktop.Result{TimedOut: true}
}
return res
}
}
func foundSession() (*desktop.Session, error) {
return &desktop.Session{}, nil
}
func writeDesktopEntry(t *testing.T, entry, execLine string) {
t.Helper()
dir := t.TempDir()
t.Setenv("XDG_DATA_HOME", dir)
apps := filepath.Join(dir, "applications")
if err := os.MkdirAll(apps, 0o755); err != nil {
t.Fatal(err)
}
text := "[Desktop Entry]\nType=Application\nName=Browser\nExec=" + execLine + "\n"
if err := os.WriteFile(filepath.Join(apps, entry), []byte(text), 0o644); err != nil {
t.Fatal(err)
}
}
// 935/I-1: every scheme but http and https, and a file path, is refused.
func TestOpenRefusesEveryOtherScheme(t *testing.T) {
x, calls := stubOpener(t, foundSession, desktop.Result{}, nil)
for _, address := range []string{
"/etc/passwd", // no scheme: a file path
"file:///etc/passwd", // a scheme other than http or https
"ftp://example.net/f", // a scheme other than http or https
"mailto:a@example.net", // a scheme other than http or https, no //
"http://", // no host
"https:///path", // no host
} {
if _, err := run(t, x, "node-display-session.open", map[string]any{"address": address}); err == nil {
t.Errorf("%s: not refused", address)
}
}
if len(*calls) != 0 {
t.Fatalf("a refused address never reaches xdg-mime or the opener: %v", *calls)
}
}
// 935/I-1: an address over 2048 bytes once encoded is refused.
func TestOpenRefusesAnAddressTooLongOnceEncoded(t *testing.T) {
x, _ := stubOpener(t, foundSession, desktop.Result{}, nil)
address := "https://example.net/" + strings.Repeat("a", 2048)
if _, err := run(t, x, "node-display-session.open", map[string]any{"address": address}); err == nil {
t.Fatal("not refused")
}
}
// 935/I-1: with no graphical session it refuses, as its other tools answer.
func TestOpenRefusesWithNoGraphicalSession(t *testing.T) {
x, _ := stubOpener(t, func() (*desktop.Session, error) {
return nil, &desktop.NoSession{Reason: "none"}
}, desktop.Result{}, nil)
_, err := run(t, x, "node-display-session.open", map[string]any{"address": "https://example.net"})
if !desktop.IsNoSession(err) {
t.Fatalf("%v", err)
}
}
// 935/I-1: no default program for the scheme is refused.
func TestOpenRefusesWithNoDefaultProgram(t *testing.T) {
x, _ := stubOpener(t, foundSession, desktop.Result{Code: 0, Stdout: ""}, nil)
if _, err := run(t, x, "node-display-session.open", map[string]any{"address": "https://example.net"}); err == nil {
t.Fatal("not refused")
}
}
// 935/I-2 (R2-9): every character outside the kept set is percent-encoded, as the bytes of its
// UTF-8 form, and the address reaches the opener as one argument, never a shell command line.
func TestOpenEncodesEveryOtherCharacterAsOneArgument(t *testing.T) {
writeDesktopEntry(t, "browser.desktop", "firefox %u")
x, calls := stubOpener(t, foundSession, desktop.Result{Code: 0, Stdout: "browser.desktop\n"}, resultOpener(desktop.Result{Code: 0}))
address := `https://example.net/a'b;c d$(e),f"g`
got, err := run(t, x, "node-display-session.open", map[string]any{"address": address})
if err != nil {
t.Fatal(err)
}
want := `https://example.net/a%27b%3Bc%20d%24%28e%29%2Cf%22g`
answer := got.(nodedisplaysession.OpenAnswer)
if answer.Address != want {
t.Fatalf("got %q, want %q", answer.Address, want)
}
var last runCall
for _, c := range *calls {
if c.name == "systemd-run" {
last = c
}
}
if len(last.args) == 0 || last.args[len(last.args)-1] != want {
t.Fatalf("the address is not the opener's last, whole argument: %v", last.args)
}
for _, a := range last.args {
if strings.Contains(a, "'") || strings.Contains(a, ";") || strings.Contains(a, " ") {
t.Fatalf("an argument still carries a shell character: %q", a)
}
}
}
// 935/I-3: an opener that fails is refused with its status and names no program.
func TestOpenRefusesWhenTheOpenerFails(t *testing.T) {
writeDesktopEntry(t, "browser.desktop", "firefox %u")
x, _ := stubOpener(t, foundSession, desktop.Result{Code: 0, Stdout: "browser.desktop\n"},
resultOpener(desktop.Result{Code: 1, Stderr: "no such unit"}))
_, err := run(t, x, "node-display-session.open", map[string]any{"address": "https://example.net"})
if err == nil || !strings.Contains(err.Error(), "no such unit") {
t.Fatalf("%v", err)
}
}
// 935/I-3: an opener that ends well answers opened with the program.
func TestOpenAnswersOpenedWithTheProgram(t *testing.T) {
writeDesktopEntry(t, "browser.desktop", "firefox %u")
x, _ := stubOpener(t, foundSession, desktop.Result{Code: 0, Stdout: "browser.desktop\n"}, resultOpener(desktop.Result{Code: 0}))
got, err := run(t, x, "node-display-session.open", map[string]any{"address": "https://example.net"})
if err != nil {
t.Fatal(err)
}
answer := got.(nodedisplaysession.OpenAnswer)
if answer.Started != nodedisplaysession.OpenAnswerStartedOpened || answer.Program != "browser.desktop" || answer.Command != "firefox" {
t.Fatalf("%+v", answer)
}
}
// 935/I-3: one still running at its bound answers opening, with the program (H-M2: the answer
// names the program only once the opener started).
func TestOpenAnswersOpeningWhenStillRunningAtItsBound(t *testing.T) {
writeDesktopEntry(t, "browser.desktop", "firefox %u")
x, _ := stubOpener(t, foundSession, desktop.Result{Code: 0, Stdout: "browser.desktop\n"}, resultOpener(desktop.Result{TimedOut: true}))
got, err := run(t, x, "node-display-session.open", map[string]any{"address": "https://example.net"})
if err != nil {
t.Fatal(err)
}
answer := got.(nodedisplaysession.OpenAnswer)
if answer.Started != nodedisplaysession.OpenAnswerStartedOpening || answer.Program != "browser.desktop" {
t.Fatalf("%+v", answer)
}
}
// C-5: cmd/i3-tools runs the opener with its own run (runWithoutKilling, not internal/desktop's
// Exec, which kills a command's process group at its deadline, run.go:82-86): it stops waiting at
// its bound without killing what it started. The child blocks reading its stdin, a pipe this test
// holds open past the bound and only then closes; once unblocked, the child writes one byte on an
// extra file before it exits, its own end, which this test waits on instead of sleeping — a byte
// the child could reach only by surviving the bound, never by being killed at it.
func TestOpenerRunStopsWaitingWithoutKillingTheProcess(t *testing.T) {
stdinR, stdinW, err := os.Pipe()
if err != nil {
t.Fatal(err)
}
defer stdinW.Close()
doneR, doneW, err := os.Pipe()
if err != nil {
t.Fatal(err)
}
defer doneR.Close()
cmd := exec.Command("sh", "-c", "cat >/dev/null; printf x >&3")
cmd.Stdin = stdinR
cmd.ExtraFiles = []*os.File{doneW}
cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true} // as openerRun starts it
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Millisecond)
defer cancel()
res := runWithoutKilling(ctx, cmd)
stdinR.Close()
doneW.Close() // this process's own copy: only the child's, closed when it exits, is left
if !res.TimedOut {
t.Fatalf("expected TimedOut, got %+v", res)
}
// Unblock the child: were it killed at the bound, this would reach nobody.
if err := stdinW.Close(); err != nil {
t.Fatal(err)
}
// Wait on the child's own end: blocks until the child writes its byte and exits, closing its
// copy of doneW: never a timer, never a kill.
b := make([]byte, 1)
n, _ := doneR.Read(b)
if n != 1 || b[0] != 'x' {
t.Fatalf("the opener process was killed instead of left to finish: read %d byte(s)", n)
}
}
// DQ-7 (lead answer note (b)): every call writes one act to the log of acts done by hand, with its
// caller and why — a successful one and a refused one alike.
func TestOpenWritesOneActDoneByHandForEveryCall(t *testing.T) {
writeDesktopEntry(t, "browser.desktop", "firefox %u")
x, _ := stubOpener(t, foundSession, desktop.Result{Code: 0, Stdout: "browser.desktop\n"}, resultOpener(desktop.Result{Code: 0}))
var recorded []string
x.handAct = func(what, why string) error {
recorded = append(recorded, what+"|"+why)
return nil
}
if _, err := run(t, x, "node-display-session.open", map[string]any{"address": "https://example.net"}); err != nil {
t.Fatal(err)
}
if len(recorded) != 1 || !strings.Contains(recorded[0], "https://example.net") {
t.Fatalf("%v", recorded)
}
recorded = nil
if _, err := run(t, x, "node-display-session.open", map[string]any{"address": "ftp://example.net"}); err == nil {
t.Fatal("expected a refusal")
}
if len(recorded) != 1 || !strings.Contains(recorded[0], "refused") || !strings.Contains(recorded[0], "ftp://example.net") {
t.Fatalf("a refusal writes an act too (note (b)): %v", recorded)
}
}
+9
View File
@@ -19,6 +19,15 @@ type i3 struct {
configDir string
layouts string
watcher *Watcher
// handAct writes one call of open to the log of acts done by hand (design 08 sign-in-page §29);
// nil in a test that does not check it.
handAct func(what, why string) error
// openBound is open's own bound on the opener command, defaultOpenTimeout unless a test shortens
// it so a still-running opener is seen without waiting out the real bound.
openBound time.Duration
// opener runs the opener command: openerRun (design 08 sign-in-page §29; DMC-8, lead answer C-5)
// unless a test replaces it to control the opener's outcome directly.
opener desktop.Runner
}
func (t *i3) ask(kind uint32, payload string, out any) error {
+4 -1
View File
@@ -2,7 +2,10 @@ module i3
go 1.26.0
require git.novox.be/novox/mesh-sdk/go v0.0.0-00010101000000-000000000000
require (
git.novox.be/novox/mesh-contracts/go/seats/nodedisplaysession v0.0.0-00010101000000-000000000000
git.novox.be/novox/mesh-sdk/go v0.0.0-00010101000000-000000000000
)
require (
github.com/klauspost/compress v1.20.1 // indirect
+10 -1
View File
@@ -16,10 +16,14 @@
"serves": [
"reload",
"workspaces",
"windows"
"windows",
"open"
]
}
],
"invokes": [
"seat:mesh-hand-acts.hand-act"
],
"tools": [
"i3_focus",
"i3_move",
@@ -68,6 +72,11 @@
"type": "package",
"package": "dex"
},
{
"id": "package-xdg-utils",
"type": "package",
"package": "xdg-utils"
},
{
"id": "config-dir",
"type": "directory",
@@ -51,10 +51,22 @@ func (m *Module) askSteps(steps []StepTool) steprun.AskSteps {
Lint: m.lintStep,
Node: m.Node,
SayStep: m.sayStep(),
Outputs: m.outputs(),
// A build that read its imports says them as the seat's imports-reported on this node (design 47 H2 H-A-517,
// H-A-532 DQ-2, DMC-2), published as the puller's other events are (SayEvent; nil says none, a test's).
SayImports: m.sayImports(),
Outputs: m.outputs(),
}
}
// sayImports says a build's import set on this node's subject of the seat (design 47 H2 H-A-517, H-A-532 DQ-2), with
// SayEvent; nil when the module says no event.
func (m *Module) sayImports() func(seat.ImportsReported) error {
if m.SayEvent == nil {
return nil
}
return steprun.SayImportsOn(sdkstep.AskGo, m.Node, m.SayEvent)
}
// outputs are the outputs objects a test step keeps its run's output in and the verb output reads (design 47 H2 §791,
// §820): Outputs when a test sets it, else the module's own objects store on the bus.
func (m *Module) outputs() steprun.OutputObjects {
@@ -4,6 +4,7 @@ package main
import (
"context"
"encoding/json"
"sync"
"testing"
"time"
@@ -11,6 +12,7 @@ import (
"github.com/nats-io/nats.go"
"github.com/nats-io/nats.go/jetstream"
seat "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/nodebuildgo"
sdkstep "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/buildstep"
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/steprun"
"git.novox.be/novox/mesh-sdk/go/testbus"
@@ -30,6 +32,9 @@ const checkCommit = "89abcdef0123456789abcdef0123456789abcdef"
// **The order is read from the record.** At capacity 1 the puller starts the check the instant the delivery ask's step
// ends, well before any poll, so "the check key holds a state" is true on correct behaviour (issue 1887). The test
// waits for both asks to end and compares the step records' own Started and Ended times, and the fetch order by commit.
//
// G1/AC2 (design 47 H2 H-A-517, H-A-532 DQ-2): each build that read its imports says imports-reported, and the
// delivery ask's is on the bus, on the seat's subject of the node.
func TestTheModuleTakesADeliveryAskBeforeAnEarlierCheck(t *testing.T) {
nc, err := nats.Connect(testbus.URL(t))
if err != nil {
@@ -64,9 +69,24 @@ func TestTheModuleTakesADeliveryAskBeforeAnEarlierCheck(t *testing.T) {
states := newStates()
m := moduleWith(states, "go1.26.0")
m.Capacity = func() int { return 1 }
reported := make(chan *nats.Msg, 4)
sub, err := nc.ChanSubscribe(seat.SubjectImportsReportedAll, reported)
if err != nil {
t.Fatal(err)
}
defer func() { _ = sub.Unsubscribe() }()
m.SayEvent = func(subject string, body any, _ string) error {
raw, err := json.Marshal(body)
if err != nil {
return err
}
return nc.Publish(subject, raw)
}
var mu sync.Mutex
var order []string
steps := fakeSteps(new([]string))
steps := append(fakeSteps(new([]string)), StepTool{Name: ImportsTool, Run: func(context.Context, map[string]any) (any, error) {
return ImportsResult{Imports: []string{"git.novox.be/novox/mesh-sdk/go"}}, nil
}})
for i := range steps {
if steps[i].Name == "build_go_fetch" {
run := steps[i].Run
@@ -113,8 +133,26 @@ func TestTheModuleTakesADeliveryAskBeforeAnEarlierCheck(t *testing.T) {
t.Fatalf("the check ask started at %v, before the delivery ask ended at %v at capacity 1", checkStarted, deliveryEnded)
}
mu.Lock()
defer mu.Unlock()
if len(order) != 2 || order[0] != askCommit || order[1] != checkCommit {
t.Fatalf("fetched %v, want the delivery ask's commit %s first, then the check's %s", order, askCommit, checkCommit)
}
mu.Unlock()
for timeout := time.After(10 * time.Second); ; {
select {
case msg := <-reported:
var r seat.ImportsReported
if err := json.Unmarshal(msg.Data, &r); err != nil {
t.Fatal(err)
}
if r.Commit != askCommit {
continue
}
if msg.Subject != seat.SubjectImportsReported("ace") || r.Module != "mesh-delivery-view" || len(r.Imports) != 1 {
t.Fatalf("imports-reported on %s: %+v", msg.Subject, r)
}
return
case <-timeout:
t.Fatal("the delivery ask's imports-reported never reached the bus")
}
}
}
@@ -1,8 +1,11 @@
package main
import (
"context"
"encoding/json"
"testing"
seat "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/nodebuildgo"
sdkstep "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/buildstep"
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/steprun"
)
@@ -28,3 +31,47 @@ func TestPullerSaysTheSeatsEventsOnItsNodesSubject(t *testing.T) {
}
}
}
// G1/AC1 (design 47 H2 H-A-517, H-A-532 DQ-2): a build ask of a module with Go bundles that ends done says one
// imports-reported on the seat's subject of the node, naming the module, the fingerprint, the commit and the imports
// the imports step read.
func TestADoneBuildSaysItsImportSetOnTheNodesSubject(t *testing.T) {
type said struct {
subject, id string
body seat.ImportsReported
}
var events []said
m := moduleWith(newStates(), "go1.26.0")
m.SayEvent = func(subject string, body any, id string) error {
r, ok := body.(seat.ImportsReported)
if !ok {
raw, _ := json.Marshal(body)
t.Fatalf("said %s with %T: %s", subject, body, raw)
}
events = append(events, said{subject, id, r})
return nil
}
imports := []string{"git.novox.be/novox/mesh-sdk/go", "git.novox.be/novox/mesh-sdk/go/busstate"}
steps := append(fakeSteps(new([]string)), StepTool{Name: ImportsTool, Run: func(context.Context, map[string]any) (any, error) {
return ImportsResult{Imports: imports}, nil
}})
a := deliveryAsk()
a.Build.Fp = "src2:0123"
if _, err := steprun.RunAsk(context.Background(), m.askSteps(steps), a); err != nil {
t.Fatal(err)
}
if len(events) != 1 {
t.Fatalf("said %d imports-reported, want 1: %+v", len(events), events)
}
e := events[0]
if e.subject != seat.SubjectImportsReported("ace") {
t.Errorf("said on %s, want %s", e.subject, seat.SubjectImportsReported("ace"))
}
if e.id != "imports-reported.mesh-delivery-view.src2:0123" {
t.Errorf("id %s", e.id)
}
if e.body.Node != "ace" || e.body.Module != "mesh-delivery-view" || e.body.Fingerprint != "src2:0123" || e.body.Commit != askCommit ||
len(e.body.Imports) != 2 || e.body.Imports[0] != imports[0] || e.body.Imports[1] != imports[1] {
t.Errorf("said %+v", e.body)
}
}
@@ -195,6 +195,10 @@ func TestManifestClaimsTheGoBuildSeatAndReadsItsCapacity(t *testing.T) {
if strings.Contains(doc.Config[steprun.BuildHoursSetting].Description, "=") {
t.Errorf("the build-hours description names a node pair")
}
// Design 47 H2 H-A-539: no prefix tells a mesh package apart, so the module declares no setting import-prefix.
if _, ok := doc.Config["import-prefix"]; ok {
t.Errorf("the manifest declares import-prefix, which H-A-539 withdrew")
}
var capacity float64
_ = json.Unmarshal(doc.Config[sdkstep.CapacitySetting].Default, &capacity)
if capacity != 0 {
@@ -1,10 +1,12 @@
package main
// The imports step (novox/hq ADR 0593 §2): at a build's end the module says which mesh packages the module's Go programs
// import, so the indexer can take the fingerprint over those packages' content and no other. It is `go list -deps` of
// each Go bundle artifact's program, the tests left out, kept to the packages of the mesh's forge that lie outside the
// module's own directory (a sibling package of the module's own repository counts, a package under the module itself
// comes with its tree).
// The imports step (novox/hq ADR 0593 §2): at a build's end the module says which packages the module's Go programs
// import, so the indexer can take the fingerprint over the ones a module of the module graph publishes and no other. It
// is `go list -deps` of each Go bundle artifact's program and of the packages each Go package artifact's paths hold
// (design 47 H2 H-A-532 DQ-5), the tests left out: the import path of every package of the import closure (H-A-517,
// H-A-541) but the standard library's, with no prefix telling a mesh package apart (H-A-539: mesh modules come from the
// seat go-package-registry), and none of the module's own (its main module, or a module that lies under its own
// directory, which comes with its tree).
import (
"context"
@@ -14,7 +16,6 @@ import (
"slices"
"strings"
trunk "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/trunk"
"git.novox.be/novox/mesh-sdk/go/catalogue"
"git.novox.be/novox/mesh-sdk/go/forgekey"
)
@@ -27,8 +28,9 @@ type ImportsResult struct {
func (m *Module) importsTool() StepTool {
return StepTool{
Name: ImportsTool,
Description: "Read the mesh packages the Go programs of a module of a fetched workspace import: `go list -deps` of each Go " +
"bundle artifact, without tests, kept to the forge's packages outside the module's own directory, sorted and each once. " +
Description: "Read the packages the Go programs of a module of a fetched workspace import: `go list -deps` of each Go " +
"bundle artifact and of the packages each Go package artifact's paths hold, without tests, the import path of every " +
"package but the standard library's and the module's own, sorted and each once. " +
"It is what a build says at its end for the fingerprint (ADR 0593 §2). Read-only.",
Input: map[string]any{
"type": "object",
@@ -65,27 +67,49 @@ func (m *Module) imports(ctx context.Context, args map[string]any) (any, error)
if err != nil {
return nil, err
}
return ModuleImports(ctx, run, m.buildEnv(dir), dir, manifest)
return ModuleImports(ctx, run, m.buildEnv, dir, manifest)
}
// ModuleImports are the mesh packages the Go bundle artifacts of manifest, in the module directory dir, import.
func ModuleImports(ctx context.Context, run forgekey.Runner, env []string, dir string, manifest catalogue.Manifest) (ImportsResult, error) {
// ModuleImports are the packages the Go bundle and package artifacts of manifest, in the module directory dir, import:
// one sorted union of import paths (design 47 H2 H-A-518, H-A-541), the standard library, the tests and the module's
// own left out. Each listing runs with env of the directory it runs in, the environment the build gives that directory
// (its own module file of the fetch's pins, and the tree a module of the module's own repository is built from; design
// 47 H2 H-A-633), never one environment for them all.
func ModuleImports(ctx context.Context, run forgekey.Runner, env func(dir string) []string, dir string, manifest catalogue.Manifest) (ImportsResult, error) {
seen := map[string]bool{}
if manifest.Build != nil {
for _, a := range manifest.Build.Artifacts {
if a.Kind != "bundle" || a.Language != "go" || strings.TrimSpace(a.From) == "" {
if a.Language != "go" {
continue
}
r := run(ctx, env, "go", "-C", dir, "list", "-deps", "-f", "{{.ImportPath}} {{.Dir}}", "./"+strings.Trim(a.From, "./"))
if r.Status != 0 || r.Err != "" {
return ImportsResult{}, fmt.Errorf("go list of %s: %s", a.Name, causeLine(r.Err+"\n"+r.Stderr+"\n"+r.Stdout))
// A bundle lists its program; a package (design 47 H2 H-A-532 DQ-5) lists every package each of its paths
// holds, in the Go module that path is, so a contracts module reports its import set too.
var lists [][2]string
switch a.Kind {
case "bundle":
if strings.TrimSpace(a.From) != "" {
lists = append(lists, [2]string{dir, "./" + strings.Trim(a.From, "./")})
}
case "package":
for _, p := range a.Paths {
if strings.TrimSpace(p) != "" {
lists = append(lists, [2]string{filepath.Join(dir, filepath.FromSlash(strings.Trim(p, "./"))), "./..."})
}
}
}
for _, l := range strings.Split(r.Stdout, "\n") {
pkg, where, ok := strings.Cut(strings.TrimSpace(l), " ")
if !ok || !meshPackage(pkg) || ownedBy(dir, where) {
continue
for _, l := range lists {
r := run(ctx, env(l[0]), "go", "-C", l[0], "list", "-deps", "-f", listFormat, l[1])
if r.Status != 0 || r.Err != "" {
return ImportsResult{}, fmt.Errorf("go list of %s: %s", a.Name, causeLine(r.Err+"\n"+r.Stderr+"\n"+r.Stdout))
}
for _, line := range strings.Split(r.Stdout, "\n") {
// <import path> <dir> <module path> <main>; a package of the standard library has no module.
f := strings.Fields(line)
if len(f) != 4 || f[3] == "true" || ownedBy(dir, f[1]) {
continue
}
seen[f[0]] = true
}
seen[pkg] = true
}
}
}
@@ -94,16 +118,12 @@ func ModuleImports(ctx context.Context, run forgekey.Runner, env []string, dir s
out = append(out, p)
}
slices.Sort(out)
if err := trunk.CheckImports(out); err != nil {
return ImportsResult{}, err
}
return ImportsResult{Imports: out}, nil
}
func meshPackage(pkg string) bool {
_, _, ok := trunk.PackageRepository(pkg)
return ok
}
// listFormat is what go list says of each package a program reaches: its import path, its directory and, outside the
// standard library, its module's path and whether that is the main module.
const listFormat = "{{.ImportPath}} {{.Dir}}{{with .Module}} {{.Path}} {{.Main}}{{end}}"
// ownedBy says the package directory where lies under the module directory dir and is not a vendored copy.
func ownedBy(dir, where string) bool {
@@ -12,33 +12,39 @@ import (
"git.novox.be/novox/mesh-sdk/go/forgekey"
)
// ADR 0593 §2 (C3): a fixture whose program imports announce, a sibling package of its own repository and a package of its
// own directory reports the first two; a test's import never appears (go list is run without -test), and the standard
// library, a package of another host and the module's own packages are left out.
func TestModuleImportsAreTheMeshPackagesOutsideTheModule(t *testing.T) {
// noEnv is the environment of a listing a test's fake compiler reads nothing from.
func noEnv(string) []string { return nil }
// ADR 0593 §2 (C3), design 47 H2 H-A-517, H-A-539, H-A-541: a fixture whose program imports packages of other Go
// modules reports the import path of each package, whatever its host (a mesh module comes from the seat
// go-package-registry, never told apart by a forge prefix): a sibling module's package and an outside package count,
// each once; the standard library (no module), the module's own packages (its main module, or a module under its own
// directory) and a test's import (go list runs without -test) are left out.
func TestModuleImportsAreTheModulesItsBuildResolved(t *testing.T) {
dir := "/w/ws1/tree/modules/demo"
var line string
run := func(ctx context.Context, env []string, name string, args ...string) forgekey.Ran {
line = name + " " + strings.Join(args, " ")
return forgekey.Ran{Stdout: strings.Join([]string{
"fmt /usr/lib/go/src/fmt",
"git.novox.be/novox/mesh-sdk/go/announce /cache/mesh-sdk@v1/go/announce",
"git.novox.be/novox/mesh-sdk/go/announce /cache/mesh-sdk@v1/go/announce",
"git.novox.be/novox/mesh-catalog/modules/sibling/lib /w/ws1/tree/modules/sibling/lib",
"git.novox.be/novox/mesh-catalog/modules/demo/internal/own " + dir + "/internal/own",
"git.novox.be/novox/mesh-sdk/go/vendored " + dir + "/vendor/git.novox.be/novox/mesh-sdk/go/vendored",
"github.com/nats-io/nats.go /cache/nats.go",
"git.novox.be/novox/mesh-sdk/go/announce /cache/mesh-sdk@v1/go/announce git.novox.be/novox/mesh-sdk/go false",
"git.novox.be/novox/mesh-sdk/go/busstate /cache/mesh-sdk@v1/go/busstate git.novox.be/novox/mesh-sdk/go false",
"git.novox.be/novox/mesh-catalog/modules/sibling/lib /w/ws1/tree/modules/sibling/lib git.novox.be/novox/mesh-catalog/modules/sibling/lib false",
"demo/internal/own " + dir + "/internal/own demo true",
"git.novox.be/novox/mesh-catalog/modules/demo/inner " + dir + "/inner git.novox.be/novox/mesh-catalog/modules/demo/inner false",
"github.com/nats-io/nats.go /cache/nats.go github.com/nats-io/nats.go false",
}, "\n")}
}
m, err := catalogue.Decode([]byte(`{"module":"demo","version":"1","build":{"artifacts":[` + goBundle + `,{"name":"files","kind":"archive","from":"files"}]}}`))
if err != nil {
t.Fatal(err)
}
got, err := ModuleImports(context.Background(), run, nil, dir, m)
got, err := ModuleImports(context.Background(), run, noEnv, dir, m)
if err != nil {
t.Fatal(err)
}
want := []string{"git.novox.be/novox/mesh-catalog/modules/sibling/lib", "git.novox.be/novox/mesh-sdk/go/announce", "git.novox.be/novox/mesh-sdk/go/vendored"}
want := []string{"git.novox.be/novox/mesh-catalog/modules/sibling/lib", "git.novox.be/novox/mesh-sdk/go/announce",
"git.novox.be/novox/mesh-sdk/go/busstate", "github.com/nats-io/nats.go"}
if !slices.Equal(got.Imports, want) {
t.Errorf("imports %v, want %v", got.Imports, want)
}
@@ -60,4 +66,116 @@ func TestImportsStepReadsTheWorkspace(t *testing.T) {
if got := out.(ImportsResult).Imports; len(got) != 0 {
t.Errorf("a fake compiler's go list names no package, and the answer was %v", got)
}
// Issue 1984 (design 47 H2 H-A-633): each listing runs with the environment the build gives its directory. A
// package path's Go module requires a module of its own repository at the zero version, which only the path's own
// temporary modfile of the fetch (its replace to the tree) resolves; the module directory's environment names no
// such modfile, and Go's lookup is shut off (GOPROXY=off), as main.510 met on mesh-delivery-contracts' paths.
t.Run("a path resolved only through its own module file", func(t *testing.T) {
const sdk = "git.novox.be/novox/mesh-delivery/modules/demo-sdk"
pkg := `{"name":"clients","kind":"package","language":"go","paths":["go/clients/registry"],"series":"0.1"}`
m, _, _ := buildModule(t, manifestWith(pkg), "x")
tree := filepath.Join(m.Work, "ws1", "tree", "modules")
path, own := filepath.Join(tree, "demo", "go", "clients", "registry"), filepath.Join(tree, "demo-sdk")
for dir, body := range map[string]string{
path: "module git.novox.be/novox/mesh-delivery/modules/demo/go/clients/registry\n\nrequire " + sdk + " " + zeroVersion + "\n",
own: "module " + sdk + "\n",
} {
if err := os.MkdirAll(dir, 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(dir, "go.mod"), []byte(body), 0o644); err != nil {
t.Fatal(err)
}
}
// What the fetch does for a same-repository requirement: a modfile of the path's directory replacing the module.
if err := m.replaceInModfile(path, sdk, own); err != nil {
t.Fatal(err)
}
// Go, as far as the listing needs it: the module file it reads is the one -modfile names, else the directory's
// own go.mod, and a required module no replace of that file points at is looked up, which GOPROXY=off refuses.
m.Run = throughBubblewrap(t, func(ctx context.Context, env []string, name string, args ...string) forgekey.Ran {
modfile := filepath.Join(args[1], "go.mod")
for _, e := range env {
if flags, ok := strings.CutPrefix(e, "GOFLAGS="); ok {
for _, f := range strings.Fields(flags) {
if file, ok := strings.CutPrefix(f, "-modfile="); ok {
modfile = file
}
}
}
}
body, err := os.ReadFile(modfile)
if err != nil {
return forgekey.Ran{Status: 1, Stderr: err.Error()}
}
if !strings.Contains(string(body), "replace "+sdk+" => "+own) {
return forgekey.Ran{Status: 1, Stderr: "go: " + sdk + "@" + zeroVersion + ": module lookup disabled by GOPROXY=off"}
}
return forgekey.Ran{Stdout: strings.Join([]string{
"git.novox.be/novox/mesh-delivery/modules/demo/go/clients/registry " + path + " git.novox.be/novox/mesh-delivery/modules/demo/go/clients/registry true",
sdk + "/buildstep " + own + "/buildstep " + sdk + " false",
"git.novox.be/novox/mesh-sdk/go/stdio /cache/mesh-sdk@v1/go/stdio git.novox.be/novox/mesh-sdk/go false",
}, "\n")}
}, &[]shutOff{})
out, err := m.imports(context.Background(), map[string]any{"workspace": "ws1", "module": "modules/demo"})
if err != nil {
t.Fatal(err)
}
want := []string{sdk + "/buildstep", "git.novox.be/novox/mesh-sdk/go/stdio"}
if got := out.(ImportsResult).Imports; !slices.Equal(got, want) {
t.Errorf("imports %v, want %v: the sibling module's imports as the path's own module file resolves them", got, want)
}
})
}
// G2 (design 47 H2 H-A-532 DQ-5, H-A-518, H-A-541): a Go package artifact reports the packages the packages its paths
// hold import, listed in the Go module each path is, without tests and without the module's own directory; a module
// with both kinds reports one sorted union.
func TestAPackageArtifactReportsItsImportSet(t *testing.T) {
dir := "/w/ws1/tree/modules/contracts"
pkg := `{"name":"seat","kind":"package","language":"go","paths":["go/seats/demo"],"series":"0.1"}`
listed := map[string]string{
dir + "/go/seats/demo ./...": strings.Join([]string{
"encoding/json /usr/lib/go/src/encoding/json",
"git.novox.be/novox/mesh-catalog/modules/contracts/go/seats/demo " + dir + "/go/seats/demo git.novox.be/novox/mesh-catalog/modules/contracts/go/seats/demo true",
"git.novox.be/novox/mesh-sdk/go/stdio /cache/mesh-sdk@v1/go/stdio git.novox.be/novox/mesh-sdk/go false",
}, "\n"),
dir + " ./cmd/demo-tools": "github.com/nats-io/nats.go /cache/nats.go github.com/nats-io/nats.go false",
}
for _, c := range []struct {
name string
artifacts string
want []string
}{
// G2/AC1: a contracts module whose artifact is of kind package.
{"package", pkg, []string{"git.novox.be/novox/mesh-sdk/go/stdio"}},
// G2/AC2: a module with a bundle and a package reports one sorted union.
{"both", goBundle + "," + pkg, []string{"git.novox.be/novox/mesh-sdk/go/stdio", "github.com/nats-io/nats.go"}},
} {
t.Run(c.name, func(t *testing.T) {
run := func(ctx context.Context, env []string, name string, args ...string) forgekey.Ran {
line := args[1] + " " + args[len(args)-1]
if slices.Contains(args, "-test") || args[2] != "list" {
t.Errorf("go ran as %v: it lists dependencies without tests", args)
}
out, ok := listed[line]
if !ok {
t.Errorf("go list in %q, not asked", line)
}
return forgekey.Ran{Stdout: out}
}
m, err := catalogue.Decode([]byte(`{"module":"contracts","version":"1","build":{"artifacts":[` + c.artifacts + `]}}`))
if err != nil {
t.Fatal(err)
}
got, err := ModuleImports(context.Background(), run, noEnv, dir, m)
if err != nil {
t.Fatal(err)
}
if !slices.Equal(got.Imports, c.want) {
t.Errorf("imports %v, want %v", got.Imports, c.want)
}
})
}
}
@@ -5,6 +5,7 @@ import (
"path/filepath"
"time"
nodebuildgo "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/nodebuildgo"
seat "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/nodebuildnode"
buildrun "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/buildrun"
sdkstep "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/buildstep"
@@ -32,6 +33,9 @@ func (m *Module) askSteps(steps []StepTool) steprun.AskSteps {
}
return steprun.AskSteps{
Fetch: byName["build_node_fetch"], Build: byName["build_node_build"], Test: byName["build_node_test"],
// The npm packages its bundles import, read after the build and said as imports-reported (design 47 H2 H-A-523,
// H-A-532 DQ-6, H-A-539).
Imports: byName[ImportsTool],
Compare: steprun.CompareStep(steprun.GeneratedRootTS, func(ws string) string { return filepath.Join(m.Work, ws, "tree") }),
Toolchain: func(ctx context.Context) (sdkstep.ToolchainUsed, error) {
installed, err := m.Probe(ctx)
@@ -47,10 +51,22 @@ func (m *Module) askSteps(steps []StepTool) steprun.AskSteps {
Lint: m.lintStep,
Node: m.Node,
SayStep: m.sayStep(),
Outputs: m.outputs(),
// A build that read its imports says them as the seat's imports-reported on this node (design 47 H2 H-A-517,
// H-A-532 DQ-2, DMC-2), published as the puller's other events are (SayEvent; nil says none, a test's).
SayImports: m.sayImports(),
Outputs: m.outputs(),
}
}
// sayImports says a build's import set on this node's subject of the seat (design 47 H2 H-A-517, H-A-532 DQ-2), with
// SayEvent; nil when the module says no event.
func (m *Module) sayImports() func(nodebuildgo.ImportsReported) error {
if m.SayEvent == nil {
return nil
}
return steprun.SayImportsOn(sdkstep.AskNode, m.Node, m.SayEvent)
}
// outputs are the outputs objects a test step keeps its run's output in and the verb output reads (design 47 H2 §791,
// §820): Outputs when a test sets it, else the module's own objects store on the bus.
func (m *Module) outputs() steprun.OutputObjects {
@@ -1,8 +1,12 @@
package main
import (
"context"
"errors"
"slices"
"testing"
nodebuildgo "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/nodebuildgo"
sdkstep "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/buildstep"
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/steprun"
)
@@ -28,3 +32,43 @@ func TestPullerSaysTheSeatsEventsOnItsNodesSubject(t *testing.T) {
}
}
}
// N1/AC1, N1/AC3 (design 47 H2 H-A-517, H-A-523, H-A-534): a done build of a TypeScript module says one imports-reported
// on the Node build seat's subject of the node, naming the mesh npm packages the imports step read; a failed build says
// none.
func TestADoneNodeBuildSaysItsImportSetAndAFailedOneNone(t *testing.T) {
var said []nodebuildgo.ImportsReported
var subjects []string
m := moduleWith(newStates(), "v26.10.0")
m.Outputs = kitObjects{} // a failed build keeps its error text as an output object, never on a bus here
m.SayEvent = func(subject string, body any, _ string) error {
subjects = append(subjects, subject)
said = append(said, body.(nodebuildgo.ImportsReported))
return nil
}
steps := append(fakeSteps(new([]string)), StepTool{Name: ImportsTool, Run: func(context.Context, map[string]any) (any, error) {
return ImportsResult{Imports: []string{"@novox/mesh-sdk"}}, nil
}})
a := nodeAsk(sdkstep.AskDelivery)
a.Build.Fp = "src2:0456"
if _, err := steprun.RunAsk(context.Background(), m.askSteps(steps), a); err != nil {
t.Fatal(err)
}
want := "mesh.seat.node-build-node.event.imports-reported.ace"
if len(said) != 1 || subjects[0] != want || said[0].Module != "gitea" || said[0].Fingerprint != "src2:0456" ||
said[0].Commit != askCommit || !slices.Equal(said[0].Imports, []string{"@novox/mesh-sdk"}) {
t.Fatalf("said %v on %v, want one imports-reported of gitea naming @novox/mesh-sdk on %s", said, subjects, want)
}
said = nil
for i := range steps {
if steps[i].Name == "build_node_build" {
steps[i].Run = func(context.Context, map[string]any) (any, error) { return nil, errors.New("tsc failed") }
}
}
if _, err := steprun.RunAsk(context.Background(), m.askSteps(steps), a); err == nil {
t.Fatal("the failed build passed")
}
if len(said) != 0 {
t.Errorf("a failed build said %v", said)
}
}
@@ -115,6 +115,10 @@ func TestManifestTakesTheBuildCapacity(t *testing.T) {
if strings.Contains(doc.Config[steprun.BuildHoursSetting].Description, "=") {
t.Errorf("the build-hours description names a node pair")
}
// Design 47 H2 H-A-539: no scope tells a mesh package apart, so the module declares no setting import-scope.
if _, ok := doc.Config["import-scope"]; ok {
t.Errorf("the manifest declares import-scope, which H-A-539 withdrew")
}
var capacity float64
_ = json.Unmarshal(doc.Config[sdkstep.CapacitySetting].Default, &capacity)
if capacity != 0 {
@@ -89,7 +89,8 @@ var fetchedSDK = map[string]string{
// fixture pass the unit level; a package whose test imports its own build output (as mesh-sdk's do) passes the unit level,
// the test step emitting it with the real tsc, shut off, before the test script runs; and the fixture TypeScript bundle
// importing @novox/mesh-sdk, built twice by the real tsc and esbuild, has equal digests, its archive holding the bundled
// .js, the .serve.mjs launcher and package.json. The unit levels run in w3, so the two builds' workspaces stay alike.
// .js, the .serve.mjs launcher and package.json, and its imports step names the SDK. The unit levels run in w3, so the
// two builds' workspaces stay alike.
func TestTheFixturePassesTheUnitLevelAndBuildsTwiceToOneDigest(t *testing.T) {
m, work := realMachine(t)
out, err := m.test(context.Background(), map[string]any{"workspace": "w3", "module": "modules/m", "level": "unit"})
@@ -130,6 +131,15 @@ func TestTheFixturePassesTheUnitLevelAndBuildsTwiceToOneDigest(t *testing.T) {
if digests[0] != digests[1] {
t.Errorf("digests differ: %v", digests)
}
// N1/AC1 (design 47 H2 H-A-523, H-A-532 DQ-6): the real esbuild's metafile of the built bundle names the SDK it
// imports, by its package name.
out, err = m.imports(context.Background(), map[string]any{"workspace": "w1", "module": "modules/m"})
if err != nil {
t.Fatal(err)
}
if got := out.(ImportsResult).Imports; !slices.Equal(got, []string{"@novox/mesh-sdk"}) {
t.Errorf("the bundle's imports = %v, want [@novox/mesh-sdk]", got)
}
if links := symlinksUnder(t, work); len(links) != 0 {
t.Errorf("symlinks in the workspaces: %v", links)
}
@@ -5,6 +5,7 @@ import (
"bytes"
"compress/gzip"
"context"
"errors"
"io"
"maps"
"os"
@@ -361,3 +362,73 @@ func TestTheBundleCarriesTheAsksVersionInItsPackageJSON(t *testing.T) {
}
}
}
// N1/AC1, N1/AC2 (design 47 H2 H-A-523, H-A-532 DQ-6, H-A-539): after a bundle's build, the imports step runs esbuild
// over the staged entrypoint and launcher with a metafile and answers every npm package among its inputs and external
// imports, each by its package name once (the SDK's stdio sub-path is the SDK), with no scope filter: a mesh package is
// told apart by the indexer, never by its scope. Node's own modules (node:module, fs) are no package; a bundle reaching
// only those answers none. Node's own modules are the probed toolchain's module.builtinModules, read at the step
// (principle 11), here holding sqlite, which no fixed list of Node 22 holds.
func TestTheImportsStepNamesTheNpmPackagesABundleReaches(t *testing.T) {
for _, c := range []struct {
name string
metafile string
want []string
}{
{"packages", `{"inputs":{
".mesh-build/tools/tools/index.js":{"imports":[{"path":"../../node_modules/@novox/mesh-sdk/dist/stdio.js"},{"path":"@novox/mesh-other/x","external":true},{"path":"pg","external":true},{"path":"node:module","external":true},{"path":"fs","external":true},{"path":"sqlite","external":true}]},
"../../node_modules/@novox/mesh-sdk/dist/stdio.js":{"imports":[]},
"../../node_modules/@novox/mesh-sdk/dist/index.js":{"imports":[]},
"../../node_modules/nats/lib/index.js":{"imports":[]}}}`, []string{"@novox/mesh-other", "@novox/mesh-sdk", "nats", "pg"}},
{"none", `{"inputs":{".mesh-build/tools/tools/index.js":{"imports":[{"path":"node:module","external":true},{"path":"path","external":true}]}}}`, []string{}},
} {
t.Run(c.name, func(t *testing.T) {
m, f, work := builtMachine(t, `,"external":["pg"]`)
m.Builtins = func(context.Context) ([]string, error) { return []string{"fs", "module", "path", "sqlite"}, nil }
bundled := f.effect
var metaRun []string
f.effect = func(cl call) {
bundled(cl)
for _, a := range cl.args {
if p, ok := strings.CutPrefix(a, "--metafile="); ok {
metaRun = cl.args
write(t, filepath.Join(cl.dir, p), c.metafile, 0o644)
}
}
}
if _, err := m.build(context.Background(), buildArgs()); err != nil {
t.Fatal(err)
}
if metaRun != nil {
t.Fatalf("the build itself ran esbuild with a metafile: %v", metaRun)
}
out, err := m.imports(context.Background(), map[string]any{"workspace": "w1", "module": "modules/m"})
if err != nil {
t.Fatal(err)
}
if got := out.(ImportsResult).Imports; !slices.Equal(got, c.want) {
t.Errorf("imports %v, want %v", got, c.want)
}
last := f.calls[len(f.calls)-1]
if dir := filepath.Join(work, "w1", "stage-tools", "modules", "module"); last.dir != dir ||
!slices.Contains(last.args, ".mesh-build/tools/tools/index.js") || !slices.Contains(last.args, ".mesh-build/tools/tools/index.serve.mjs") ||
!slices.Contains(last.args, "--external:pg") || !slices.Contains(last.args, "--metafile=.mesh-build/tools.imports.json") {
t.Errorf("esbuild ran in %s as %v", last.dir, last.args)
}
})
}
}
// N1 (H-A-517): a workspace whose bundle was not built has no import set to read, and the step says so; a toolchain whose
// own modules cannot be read fails the step loud, never answering them as packages.
func TestTheImportsStepRefusesABundleNotBuilt(t *testing.T) {
m, _, _ := builtMachine(t, ``)
m.Builtins = func(context.Context) ([]string, error) { return nil, errors.New("no node") }
if _, err := m.imports(context.Background(), map[string]any{"workspace": "w1", "module": "modules/m"}); err == nil || !strings.Contains(err.Error(), "Node's own modules") {
t.Errorf("imports with no builtins read: %v", err)
}
m.Builtins = func(context.Context) ([]string, error) { return []string{"fs"}, nil }
if _, err := m.imports(context.Background(), map[string]any{"workspace": "w1", "module": "modules/m"}); err == nil || !strings.Contains(err.Error(), "was not built") {
t.Errorf("imports of an unbuilt bundle: %v", err)
}
}
@@ -0,0 +1,185 @@
package main
// The imports step (design 47 H2 H-A-523, H-A-532 DQ-6, H-A-539): at a build's end the module says which npm packages
// its TypeScript bundles import, so the indexer can take the fingerprint over the ones a module of the module graph
// publishes and no other. It is what esbuild's metafile names as each bundle's inputs, read from the bundle's compiled
// entrypoints and launchers as the build step staged them: every npm package among them, each by its package name once
// (@novox/mesh-sdk, never a sub-path of it), with no scope telling a mesh package apart, and none of Node's own modules.
// A bundle's inputs are what its entrypoints reach, so no test file is among them.
import (
"context"
"encoding/json"
"fmt"
"os"
"path/filepath"
"slices"
"strings"
sdkstep "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/buildstep"
)
// ImportsTool reads the npm packages a module's bundles import (design 47 H2 H-A-532 DQ-6).
const ImportsTool = "build_node_imports"
// ImportsResult is what the imports step answers; a BuildAnswer carries Imports as it is.
type ImportsResult struct {
Imports []string `json:"imports"`
}
func (m *Module) importsTool() StepTool {
return StepTool{
Name: ImportsTool,
Description: "Read the npm packages the TypeScript bundles of a module of a workspace import, after its build: " +
"esbuild's inputs of each bundle's compiled entrypoints and launchers, every npm package among them but Node's own " +
"modules, each by its package name, sorted and each once. It is what a build says at its end " +
"for the fingerprint (design 47 H2 H-A-523). Writes only esbuild's scratch output in the workspace.",
Input: map[string]any{
"type": "object",
"properties": map[string]any{
"workspace": map[string]any{"type": "string", "description": "the workspace id build_node_fetch answered, its bundles built"},
"module": map[string]any{"type": "string", "description": "the module's directory in the workspace, '.' when it is the root"},
},
"required": []string{"workspace", "module"},
},
Run: m.imports,
}
}
func (m *Module) imports(ctx context.Context, args map[string]any) (any, error) {
workspace, _ := args["workspace"].(string)
module, _ := args["module"].(string)
root, dir, err := m.moduleDirOf(workspace, module)
if err != nil {
return nil, err
}
raw, err := os.ReadFile(filepath.Join(dir, "module.json"))
if err != nil {
return nil, fmt.Errorf("the module has no module.json: %w", err)
}
var manifest struct {
Build struct {
Artifacts []artifact `json:"artifacts"`
} `json:"build"`
}
if err := json.Unmarshal(raw, &manifest); err != nil {
return nil, fmt.Errorf("module.json is not JSON: %w", err)
}
probe := m.Builtins
if probe == nil {
probe = ProbeBuiltins
}
builtins, err := probe(ctx)
if err != nil {
return nil, fmt.Errorf("the imports cannot be told from Node's own modules: %w", err)
}
seen := map[string]bool{}
for _, a := range manifest.Build.Artifacts {
if a.Kind != "bundle" || a.Language != "typescript" {
continue
}
names, err := m.bundleImports(ctx, root, a, builtins)
if err != nil {
return nil, err
}
for _, n := range names {
seen[n] = true
}
}
out := []string{}
for n := range seen {
out = append(out, n)
}
slices.Sort(out)
return ImportsResult{Imports: out}, nil
}
// bundleImports are the npm packages esbuild names as inputs of bundle a, read in the stage its build left
// (build.go: <root>/stage-<artifact>/modules/module), from the same entries and externals the build bundled.
func (m *Module) bundleImports(ctx context.Context, root string, a artifact, builtins []string) ([]string, error) {
dir := filepath.Join(root, "stage-"+a.Name, "modules", "module")
out := Out(a.Name)
if _, err := os.Stat(filepath.Join(dir, out)); err != nil {
return nil, fmt.Errorf("the bundle %s was not built in this workspace, so its imports cannot be read: %w", a.Name, err)
}
var entries []string
for _, e := range a.Entrypoints {
if strings.HasSuffix(e, ".js") {
entries = append(entries, out+"/"+e)
}
}
for _, l := range sortedValues(sdkstep.Launchers(a.Language, a.Entrypoints)) {
entries = append(entries, out+"/"+l)
}
if len(entries) == 0 {
return nil, nil
}
meta := out + ".imports.json"
args := append(append([]string{}, entries...), "--bundle", "--platform=node", "--format=esm", "--target=node22",
"--outbase="+out, "--outdir="+out+".imports", "--log-level=warning", "--metafile="+meta)
for _, x := range a.External {
args = append(args, "--external:"+x)
}
if why := ranFailed(m.runIn(ctx, root, false, dir, nil, m.esbuild(), args...)); why != "" {
return nil, fmt.Errorf("esbuild's inputs of %s: %s", a.Name, why)
}
raw, err := os.ReadFile(filepath.Join(dir, meta))
if err != nil {
return nil, fmt.Errorf("esbuild wrote no metafile for %s: %w", a.Name, err)
}
return packagesOf(raw, builtins)
}
// packagesOf are the npm packages an esbuild metafile names: each input under a node_modules directory and each external
// import, by its package name, but Node's own modules.
func packagesOf(metafile []byte, builtins []string) ([]string, error) {
var meta struct {
Inputs map[string]struct {
Imports []struct {
Path string `json:"path"`
External bool `json:"external"`
} `json:"imports"`
} `json:"inputs"`
}
if err := json.Unmarshal(metafile, &meta); err != nil {
return nil, fmt.Errorf("esbuild's metafile is not JSON: %w", err)
}
var out []string
keep := func(name string) {
if name != "" && !nodeBuiltin(name, builtins) && !slices.Contains(out, name) {
out = append(out, name)
}
}
for input, in := range meta.Inputs {
filePath := filepath.ToSlash(input)
if i := strings.LastIndex(filePath, "node_modules/"); i >= 0 {
keep(packageName(filePath[i+len("node_modules/"):]))
}
for _, imp := range in.Imports {
if imp.External {
keep(packageName(imp.Path))
}
}
}
slices.Sort(out)
return out, nil
}
// packageName is the npm package a module specifier or a path under node_modules names: its first segment, or its
// first two for a scoped package (@novox/mesh-sdk/stdio is @novox/mesh-sdk).
func packageName(spec string) string {
parts := strings.SplitN(spec, "/", 3)
if strings.HasPrefix(spec, "@") {
if len(parts) < 2 {
return ""
}
return parts[0] + "/" + parts[1]
}
return parts[0]
}
// nodeBuiltin says whether name is one of Node's own modules (node:<name>, or a name of the probed toolchain's
// module.builtinModules), which is the runtime's standard library and no npm package.
func nodeBuiltin(name string, builtins []string) bool {
return strings.HasPrefix(name, "node:") || slices.Contains(builtins, name)
}
@@ -45,6 +45,9 @@ type Module struct {
Reload func() (Recipe, error)
// Probe reads the installed Node version (ProbeNode).
Probe func(ctx context.Context) (string, error)
// Builtins reads the installed Node's own module names, its module.builtinModules (ProbeBuiltins), at each imports
// step; nil reads them with ProbeBuiltins.
Builtins func(ctx context.Context) ([]string, error)
// Toolchain installs the toolchain directory; nil in a module that only guards.
Toolchain *Toolchain
// Work is the work directory, outside the home: a workspace is <Work>/<step id>/tree. Run runs the commands of a
@@ -2,6 +2,7 @@ package main
import (
"context"
"encoding/json"
"fmt"
"os/exec"
"strings"
@@ -22,6 +23,22 @@ func ProbeNode(ctx context.Context) (string, error) {
return parseNodeVersion(string(out))
}
// ProbeBuiltins reads the installed Node's own modules, its module.builtinModules, so the imports step leaves out exactly
// what the probed toolchain holds (principle 11: read, never a fixed list).
func ProbeBuiltins(ctx context.Context) ([]string, error) {
ctx, cancel := context.WithTimeout(ctx, ProbeTimeout)
defer cancel()
out, err := exec.CommandContext(ctx, "node", "-p", "JSON.stringify(require('module').builtinModules)").Output()
if err != nil {
return nil, fmt.Errorf("node's builtinModules cannot be read: %w", err)
}
var names []string
if err := json.Unmarshal(out, &names); err != nil || len(names) == 0 {
return nil, fmt.Errorf("node's builtinModules answered %q", strings.TrimSpace(string(out)))
}
return names, nil
}
func parseNodeVersion(out string) (string, error) {
v := strings.TrimSpace(out)
if len(v) < 2 || v[0] != 'v' || v[1] < '0' || v[1] > '9' || strings.ContainsAny(v, " \n\t") {
@@ -1,7 +1,9 @@
package main
// **The verb `steps`** (design 47 G §22, §307, §326, §328): which pipeline steps a TypeScript artifact can run, by the
// convention check.go tests by. The type-check is the lint step (§328) and is always one; the unit step is the packages
// convention check.go tests by. The type-check is the lint step (§328), answered only when one of the artifact's packages
// holds a TypeScript file, by the test the lint step itself uses (lint.go; design 47 H2 H-A-515 second addendum), so the
// pipeline runner ends a lint with nothing to type-check at placement, never asking it (H-A-515 addendum); the unit step is the packages
// holding a package.json script `test`, the integration step those holding `test:integration`. A level with none is not
// answered. The answer is kept in the state detected-steps by the artifact's fingerprint, replaced by a newer one and by
// again, as the Go build module keeps it.
@@ -51,7 +53,15 @@ func detectSteps(dir string, narrowedTree bool) ([]DetectedStep, error) {
return nil, err
}
unit, integration := []string{}, []string{}
lint := false
for _, tg := range targets {
if !lint {
sources, err := typeScriptFiles(tg.dir)
if err != nil {
return nil, err
}
lint = len(sources) > 0
}
scripts, err := packageScripts(tg.dir)
if err != nil {
return nil, err
@@ -63,7 +73,10 @@ func detectSteps(dir string, narrowedTree bool) ([]DetectedStep, error) {
integration = append(integration, tg.where)
}
}
steps := []DetectedStep{{Step: StepLint}}
steps := []DetectedStep{}
if lint {
steps = append(steps, DetectedStep{Step: StepLint})
}
for _, l := range []struct {
step string
pkgs []string
@@ -79,7 +92,7 @@ func detectSteps(dir string, narrowedTree bool) ([]DetectedStep, error) {
// stepsTool is the seat's verb `steps`.
func (m *Module) stepsTool() stdio.Tool {
return stdio.Tool{Name: Seat + "." + seat.VerbSteps,
Description: "Which pipeline steps a TypeScript artifact can run: the type-check as lint, always; unit tests where a package has a test script; " +
Description: "Which pipeline steps a TypeScript artifact can run: the type-check as lint, where one of its packages holds a TypeScript file; unit tests where a package has a test script; " +
"integration tests where one has a test:integration script. A level with no test is not answered.",
Input: map[string]any{"type": "object", "required": []string{"module", "artifact"}, "properties": map[string]any{
"module": map[string]any{"type": "string"},
@@ -10,8 +10,9 @@ import (
"testing"
)
// Design 47 G §22, §307, §328 (BLD7): steps answers the type-check as lint always, the packages with a test script as
// unit, those with test:integration as integration, and leaves out a level with none.
// Design 47 G §22, §307, §328 (BLD7): steps answers the type-check as lint where a package holds a TypeScript file (design 47
// H2 H-A-515 second addendum: none for a tree with none, whose lint would end nothing to run), the packages with a test
// script as unit, those with test:integration as integration, and leaves out a level with none.
func TestTheStepsOfATypeScriptArtifactAreFoundByItsScripts(t *testing.T) {
put := func(dir, name, body string) {
if err := os.MkdirAll(filepath.Join(dir), 0o755); err != nil {
@@ -23,15 +24,18 @@ func TestTheStepsOfATypeScriptArtifactAreFoundByItsScripts(t *testing.T) {
}
for name, c := range map[string]struct {
pkg string
noTS bool
narrowed bool
want []DetectedStep
}{
"both levels": {`{"scripts":{"test":"node t.js","test:integration":"node i.js"}}`, false,
"both levels": {`{"scripts":{"test":"node t.js","test:integration":"node i.js"}}`, false, false,
[]DetectedStep{{Step: "lint"}, {Step: "unit", Packages: []string{"."}}, {Step: "integration", Packages: []string{"."}}}},
"unit only": {`{"scripts":{"test":"node t.js"}}`, false, []DetectedStep{{Step: "lint"}, {Step: "unit", Packages: []string{"."}}}},
"no script": {`{"scripts":{}}`, false, []DetectedStep{{Step: "lint"}}},
"unit only": {`{"scripts":{"test":"node t.js"}}`, false, false, []DetectedStep{{Step: "lint"}, {Step: "unit", Packages: []string{"."}}}},
"no script": {`{"scripts":{}}`, false, false, []DetectedStep{{Step: "lint"}}},
// No TypeScript file (only a declaration, as a generated package of JavaScript has): nothing to type-check, no lint.
"no TypeScript file": {`{"scripts":{}}`, true, false, []DetectedStep{}},
// A folder module's tree narrowed to ts/seats/a (H-A-136): the steps are those the narrowed levels run there.
"narrowed folder": {"", true, []DetectedStep{{Step: "lint"}, {Step: "unit", Packages: []string{"ts/seats/a"}}}},
"narrowed folder": {"", false, true, []DetectedStep{{Step: "lint"}, {Step: "unit", Packages: []string{"ts/seats/a"}}}},
} {
dir := t.TempDir()
if c.narrowed {
@@ -42,6 +46,12 @@ func TestTheStepsOfATypeScriptArtifactAreFoundByItsScripts(t *testing.T) {
}
} else {
put(dir, "package.json", c.pkg)
if c.noTS {
put(dir, "index.d.ts", "export declare const v: number;\n")
put(dir, "index.js", "export const v = 1;\n")
} else {
put(dir, "index.ts", "export const v = 1;\n")
}
}
got, err := detectSteps(dir, c.narrowed)
if err != nil || !reflect.DeepEqual(got, c.want) {
@@ -25,7 +25,7 @@ type StepTool struct {
// StepTools are the module's step tools. Each step's issue adds its own.
func (m *Module) StepTools() []StepTool {
return []StepTool{m.fetchTool(), m.testTool(), m.buildTool()}
return []StepTool{m.fetchTool(), m.testTool(), m.buildTool(), m.importsTool()}
}
// Tools is every tool the module serves: its step tools behind the guard, its status and its health.
+1 -1
View File
@@ -5,6 +5,7 @@ go 1.26.0
require (
git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/clients/containerimageregistryclient v0.0.0-00010101000000-000000000000
git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/containerimageregistry v0.0.0-00010101000000-000000000000
git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/nodebuildgo v0.0.0-00010101000000-000000000000
git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/nodebuildnode v0.0.0-00010101000000-000000000000
git.novox.be/novox/mesh-contracts/health-and-repair/go/clients/meshhandactsclient v0.0.0-00010101000000-000000000000
git.novox.be/novox/mesh-contracts/health-and-repair/go/seats/meshhandacts v0.0.0-00010101000000-000000000000
@@ -101,7 +102,6 @@ require (
git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/clients/ociartifactregistryclient v0.0.0-00010101000000-000000000000 // indirect
git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/gopackageregistry v0.0.0-00010101000000-000000000000 // indirect
git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshcatalog v0.0.0-00010101000000-000000000000 // indirect
git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/nodebuildgo v0.0.0-00010101000000-000000000000 // indirect
git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/npmpackageregistry v0.0.0-00010101000000-000000000000 // indirect
git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/ociartifactregistry v0.0.0-00010101000000-000000000000 // indirect
)
+1
View File
@@ -78,6 +78,7 @@
"build_node_fetch",
"build_node_test",
"build_node_build",
"build_node_imports",
"build_node_release",
"build_node_step",
"build_node_steps",
@@ -108,10 +108,9 @@ var Homes = map[string]Home{
// An owner's change not said on its views family past its bound (mesh-sdk views.UnsaidFinding, id <owner>.<state>):
// written by each owner of a views family in its own findings (the indexer, the assigner), so no one observer.
"view-unsaid": {Source: "views", Why: "every owner of a views family writes its own"},
// The builder's own (design 51): a build that ended failed, a floor whose holder said nothing past its bound, an old
// form held seven days by a counted node-engine, a tag's removal asked and not done.
// The builder's own (design 51): a build that ended failed, an old form held seven days by a counted node-engine, a tag's
// removal asked and not done. Its floor-silent went with its version floor (design 47 H2 H-A-553 (2)).
"build-failed": {Source: "builder", Observer: builder},
"floor-silent": {Source: "builder", Observer: builder},
"old-form-held": {Source: "builder", Observer: builder},
"tag-removal-not-done": {Source: "builder", Observer: builder},
// The builder's publishing (design 51): a holder refused the publish, or said nothing past its bound (about the name);
@@ -366,7 +366,7 @@ func TestEveryControllerKindHasItsHome(t *testing.T) {
}
for kind, observer := range map[string]string{"needs-operator": watchman, "machine-network": watchman, "lease-split": selfCheck,
"data-shrank": selfCheck, "retire-waiting": provisioner, "asks-undelivered": messenger,
"image-missing": artifactStore, "build-failed": builder, "floor-silent": builder, "old-form-held": builder,
"image-missing": artifactStore, "build-failed": builder, "old-form-held": builder,
"tag-removal-not-done": builder, "seat-definition-unparsed": indexer, "generated-types-out-of-step": indexer,
"seat-defined-twice": indexer, "accepted-unsaid": indexer, "manifest-held": indexer, "packages-token-refused": gitea,
"publish-refused": builder, "publish-unanswered": builder, "seat-outcome-unread": builder} {
@@ -374,6 +374,10 @@ func TestEveryControllerKindHasItsHome(t *testing.T) {
t.Errorf("%s's home is %+v", kind, h)
}
}
// Design 47 H2 H-A-553 (2): the builder's floor-silent went with its version floor, so no home names it.
if h, ok := Homes["floor-silent"]; ok {
t.Errorf("floor-silent still has a home: %+v", h)
}
for _, kind := range []string{"resolver-wrong", "holder-silent", "archives-missing", "archives-unheld", "binding-kept",
"binding-moved", "binding-moving", "grant-composes-nothing", "root-not-free", "cleanup-waiting", "data-held-twice"} {
if h := Homes[kind]; !h.Carried || h.Observer != "" || h.Why != Dropped {
@@ -397,9 +401,10 @@ func TestEveryControllerKindHasItsHome(t *testing.T) {
// first view, the owners' view too large, the builder's four, the indexer's four and the package seats' token refused.
// And the builder's three publishing kinds and the delivery parts' family not heard: 103.
// And the owners' changes not said, view-unsaid: 104. And the indexer's mesh-wide hold past its bound, manifest-held
// (ADR 0632 §2): 105. (The bus module's own conditions, nats.status-unwritten among them, are said to the keeper
// directly, never through findings, so they have no home here.)
if len(Homes) != 105 || carried != 37 {
// (ADR 0632 §2): 105. Less the builder's floor-silent, gone with its floor (design 47 H2 H-A-553 (2)): 104. (The bus
// module's own conditions, nats.status-unwritten among them, are said to the keeper directly, never through findings, so
// they have no home here.)
if len(Homes) != 104 || carried != 37 {
t.Errorf("the table holds %d kinds, %d carried", len(Homes), carried)
}
}
@@ -169,6 +169,11 @@ type testLog struct{ t *testing.T }
func (w testLog) Write(p []byte) (int, error) {
defer func() { _ = recover() }() // the bundle may speak after the test ended
w.t.Logf("bundle: %s", strings.TrimRight(string(p), "\n"))
// Built with -race, the bundle is too: a race it reports fails the test (issue 721 note 11: two events applied at once
// to one record lost its delivery time).
if strings.Contains(string(p), "WARNING: DATA RACE") {
w.t.Error("the bundle reports a data race, above")
}
return len(p), nil
}
@@ -42,6 +42,12 @@ type Holder struct {
refusals []string
// tried counts the owed effects tried since this owner started, by how each ended (novox/hq issue 407).
tried owedTries
// applying keeps one event or tool call at a time on the delivery records the gate holds in memory (issue 721 note 11):
// the runtime hands each event and each call to a goroutine of its own, and each is applied whole under this lock (take,
// applied), so none reads a record another is halfway through writing. A record's entry is written to the ledger and then
// to memory under it, so an event heard once that write lands (a pipeline-wanted after the running it ends on) is applied
// only after memory holds it too. Taken before h.mu, never under it.
applying sync.Mutex
// reactMu keeps one React at a time; poke asks for a look (react.go); wanted is when the next is wanted, and its timer.
reactMu sync.Mutex
poke chan struct{}
@@ -7,6 +7,7 @@ package main
import (
"context"
"encoding/json"
"errors"
"fmt"
"os"
@@ -125,7 +126,33 @@ func handle(h *Holder, e stdio.Envelope) error {
return taken
}
// applied is a call applied whole, one at a time with the events (Holder.applying), its answer taken under the same lock: a
// view of a record the gate keeps is written out before the next event writes that record. A verb that changes a delivery
// asks for a look at what it makes possible (react.go).
func (h *Holder) applied(run func(map[string]any) (any, error)) func(map[string]any) (any, error) {
return func(a map[string]any) (any, error) {
out, err := func() (any, error) {
h.applying.Lock()
defer h.applying.Unlock()
out, err := run(a)
if err != nil || out == nil {
return out, err
}
raw, err := json.Marshal(out)
if err != nil {
return nil, err
}
return json.RawMessage(raw), nil
}()
h.Poke()
return out, err
}
}
// take applies one event whole, one at a time (Holder.applying).
func take(h *Holder, e stdio.Envelope) error {
h.applying.Lock()
defer h.applying.Unlock()
if h.Consumer != nil && h.Consumer.Takes(e.Key) {
return h.Consumer.Hear(e)
}
@@ -265,14 +292,9 @@ func tools(h *Holder, l *listening) []stdio.Tool {
list = append(list, headTools(h, meshhandactsclient.Recorder{Ask: stdio.Ask})...)
// The prune of heads by hand, now or kept from it (design 47 H2 §812, H-A-380 (3)).
list = append(list, headsPruneTools(meshhandactsclient.Recorder{Ask: stdio.Ask})...)
// A verb that changes a delivery asks for a look at what it makes possible (react.go).
// Each call is applied whole, one at a time with the events, and asks for a look after (applied).
for i := range list {
run := list[i].Run
list[i].Run = func(a map[string]any) (any, error) {
out, err := run(a)
h.Poke()
return out, err
}
list[i].Run = h.applied(list[i].Run)
}
return list
}
@@ -2,11 +2,14 @@ package main
import (
"encoding/json"
"errors"
"fmt"
"strings"
"testing"
"time"
stdio "git.novox.be/novox/mesh-sdk/go"
"git.novox.be/novox/mesh-sdk/go/catalogue"
)
// pipelineBed is a gate with one record open, of main at source revision 1, and its consumer.
@@ -105,6 +108,121 @@ func TestARecordFollowsItsPipelineToTheMachines(t *testing.T) {
}
}
// hookedLedger is the ledger fake, told after each operation it took.
type hookedLedger struct {
*ledgerFake
after func(instance, operation string, body any)
}
func (l *hookedLedger) Apply(instance, operation string, body any) (uint64, error) {
seq, err := l.ledgerFake.Apply(instance, operation, body)
if err == nil && l.after != nil {
l.after(instance, operation, body)
}
return seq, err
}
// 721/AC1 (issue 721 note 11; design 47 H2 §810): the runtime hands each event and each call to a goroutine of its own, so
// one can be heard once a running's outcome is in the ledger and before the gate's memory holds it. Heard then, it waits
// until the running is applied whole: a pipeline-wanted ends the record with its delivery time and class (applied at once it
// ended the record with neither, the delivery time lost), and the call show answers the record with the running, its answer
// taken before the next event writes the record.
func TestWhatIsHeardWhileAnEventIsWrittenWaitsUntilItIsApplied(t *testing.T) {
running := func(node string) stdio.Envelope {
return stdio.Envelope{Key: "node-engine.running." + node + ".app", Node: node, Body: json.RawMessage(
`{"v":1,"at":"2026-11-20T03:05:00Z","module":"app","node":"` + node + `","fingerprint":"f","healthy":true}`)}
}
for _, tc := range []struct {
name string
heard func(h *Holder) (any, error)
check func(t *testing.T, h *Holder, answer any)
}{
{"pipeline-wanted", func(h *Holder) (any, error) {
return nil, take(h, stdio.Envelope{Key: "mesh-wants.pipeline-wanted.main.1", Body: json.RawMessage(
`{"v":1,"pipeline":"main.1","branch":"main","source":1,"outcome":"running"}`)})
}, func(t *testing.T, h *Holder, _ any) {
r, err := h.Records.ByKey("main", 1)
if err != nil || r == nil || r.Ended == nil || r.DeliveryTime != "5m0s" || r.Class != catalogue.ClassCore {
t.Fatalf("the record ended %+v keeping the delivery time %q and the class %q (%v); want 5m0s and core", r.Ended,
r.DeliveryTime, r.Class, err)
}
}},
{"the call show", func(h *Holder) (any, error) {
for _, tool := range tools(h, &listening{}) {
if tool.Name == Seat+".show" {
return tool.Run(map[string]any{"id": "main.1"})
}
}
return nil, fmt.Errorf("the gate serves no %s.show", Seat)
}, func(t *testing.T, h *Holder, answer any) {
if err := take(h, running("g14")); err != nil {
t.Fatal(err)
}
raw, _ := json.Marshal(answer)
if !strings.Contains(string(raw), OutcomeKey("app", "f", "ace", StepRunning)) || strings.Contains(string(raw), "g14") {
t.Fatalf("show answered %.600s: want the running on ace, and nothing the next event wrote", raw)
}
// Every call runs under the lock the events take.
if _, err := h.applied(func(map[string]any) (any, error) {
if h.applying.TryLock() {
h.applying.Unlock()
return nil, errors.New("a call runs while an event can write the records")
}
return nil, nil
})(nil); err != nil {
t.Fatal(err)
}
}},
} {
t.Run(tc.name, func(t *testing.T) {
now := time.Date(2026, 11, 20, 3, 0, 0, 0, time.UTC)
h := &Holder{Now: func() time.Time { return now }}
ledger := &hookedLedger{ledgerFake: newLedgerFake(t)}
h.Records = &Records{Ledger: ledger, Now: h.Now, Class: func(string) (string, error) { return catalogue.ClassCore, nil }}
h.Consumer = &StepConsumer{Records: h.Records, Families: stepFamilies, Now: h.Now, Taken: h.TakenIn, Follow: h.Follow}
if _, _, err := h.Records.Open(opening("main", 1, map[string]string{"novox/app@5": strings.Repeat("a", 40)})); err != nil {
t.Fatal(err)
}
if _, err := h.Records.Kept(); err != nil {
t.Fatal(err)
}
if err := take(h, stdio.Envelope{Key: "mesh-pipeline-runner.pipeline-started.main.1", Body: json.RawMessage(
`{"v":1,"branch":"main","source":1,"pipeline":"main.1","call":"0000000000000001","movers":[{"module":"app","commit":"c","fingerprint":"f","repository":"novox/app","tier":1}]}`)}); err != nil {
t.Fatal(err)
}
now = now.Add(5 * time.Minute)
type heardOut struct {
answer any
err error
}
heard := make(chan heardOut, 1)
ledger.after = func(_, operation string, body any) {
if o, ok := body.(RecordOutcome); !ok || operation != OpOutcome || o.Step != StepRunning {
return
}
ledger.after = nil
// Heard as the running's write lands: taken there and then when nothing holds the records, as the runtime's
// goroutines allow, else on a goroutine of its own, as the runtime hands it.
hear := func() { answer, err := tc.heard(h); heard <- heardOut{answer, err} }
if h.applying.TryLock() {
h.applying.Unlock()
hear()
return
}
go hear()
}
if err := take(h, running("ace")); err != nil {
t.Fatal(err)
}
out := <-heard
if out.err != nil {
t.Fatal(out.err)
}
tc.check(t, h, out.answer)
})
}
}
// GATE-5/AC (design 47 H §738, §751; H-A-75, H-A-89 (3), (4)): a pipeline-ended not passed ends the record failed naming
// the pipeline's why, and pipeline-wanted tier-late ends it failed naming the movers and machines not running.
func TestARecordEndsFailedOnAPipelineNotPassedOrATierLate(t *testing.T) {
+18 -1
View File
@@ -327,6 +327,11 @@ func entry(name, storage, template string, options map[string]string) catalogue.
func TestEachTemplateIsPlannedUnderTheModulesNames(t *testing.T) {
ledger := entry("records", catalogue.StorageLedger, catalogue.TemplateLedger, map[string]string{"max-mib": "16"})
ledger.Types = []catalogue.LedgerType{{Name: "decision", Indexes: []catalogue.LedgerIndex{{Name: "by-topic", On: []string{"topic"}}}}}
// A ledger's state and index buckets take its max-mib and no other option of it (design 47 H2's corrections, item 12, H-A-636).
bigLedger := entry("records", catalogue.StorageLedger, catalogue.TemplateLedger, map[string]string{"max-mib": "1024", "history": "5"})
bigLedger.Types = ledger.Types
plainLedger := entry("records", catalogue.StorageLedger, catalogue.TemplateLedger, nil)
plainLedger.Types = ledger.Types
bare := entry("raw", catalogue.StorageStream, "", nil)
bare.Configuration = map[string]json.RawMessage{"when-full": json.RawMessage(`"drop-oldest"`), "max-mib": json.RawMessage("8"), "max-age-days": json.RawMessage("3")}
forGood := entry("reviews", catalogue.StorageStream, "", nil)
@@ -368,9 +373,21 @@ func TestEachTemplateIsPlannedUnderTheModulesNames(t *testing.T) {
binding: "objects mesh-knowledge_outputs"},
{name: "ledger", entry: ledger,
objects: "stream mesh-knowledge_records [mesh.ledger.mesh-knowledge.records.history.>] {16 MiB, age 0, history 0, new, size 262144}; " +
"key-value mesh-knowledge_records_state {16 MiB, age 0, history 1, new, size 262144}; " +
"key-value mesh-knowledge_records_index-by-topic {16 MiB, age 0, history 1, new, size 262144}; " +
"stream mesh-knowledge_records_snapshot [mesh.ledger.mesh-knowledge.records.snapshot.>] {16 MiB, age 0, history 1, old, size 0}",
binding: "history mesh-knowledge_records on mesh.ledger.mesh-knowledge.records.history, state mesh-knowledge_records_state, indexes map[by-topic:mesh-knowledge_records_index-by-topic], snapshot mesh.ledger.mesh-knowledge.records.snapshot"},
{name: "ledger naming max-mib 1024 and past values: its state and index buckets at 1 GiB, no other option reaching them (H-A-636)", entry: bigLedger,
objects: "stream mesh-knowledge_records [mesh.ledger.mesh-knowledge.records.history.>] {1024 MiB, age 0, history 0, new, size 262144}; " +
"key-value mesh-knowledge_records_state {1024 MiB, age 0, history 1, new, size 262144}; " +
"key-value mesh-knowledge_records_index-by-topic {1024 MiB, age 0, history 1, new, size 262144}; " +
"stream mesh-knowledge_records_snapshot [mesh.ledger.mesh-knowledge.records.snapshot.>] {1024 MiB, age 0, history 1, old, size 0}",
binding: "history mesh-knowledge_records on mesh.ledger.mesh-knowledge.records.history, state mesh-knowledge_records_state, indexes map[by-topic:mesh-knowledge_records_index-by-topic], snapshot mesh.ledger.mesh-knowledge.records.snapshot"},
{name: "ledger naming no max-mib: its state and index buckets at the state default (H-A-636)", entry: plainLedger,
objects: "stream mesh-knowledge_records [mesh.ledger.mesh-knowledge.records.history.>] {1024 MiB, age 0, history 0, new, size 262144}; " +
"key-value mesh-knowledge_records_state {64 MiB, age 0, history 1, new, size 262144}; " +
"key-value mesh-knowledge_records_index-by-topic {64 MiB, age 0, history 1, new, size 262144}; " +
"stream mesh-knowledge_records_snapshot [mesh.ledger.mesh-knowledge.records.snapshot.>] {16 MiB, age 0, history 1, old, size 0}",
"stream mesh-knowledge_records_snapshot [mesh.ledger.mesh-knowledge.records.snapshot.>] {1024 MiB, age 0, history 1, old, size 0}",
binding: "history mesh-knowledge_records on mesh.ledger.mesh-knowledge.records.history, state mesh-knowledge_records_state, indexes map[by-topic:mesh-knowledge_records_index-by-topic], snapshot mesh.ledger.mesh-knowledge.records.snapshot"},
{name: "bare stream", entry: bare,
objects: "stream mesh-knowledge_raw [mesh.bus.mesh-knowledge.raw.>] {8 MiB, age 259200, history 0, old, size 0}",
+7 -1
View File
@@ -229,7 +229,13 @@ func PlanOf(module string, e catalogue.BusStateEntry) (Plan, error) {
return Plan{}, err
}
history.MaxAgeSeconds = days(age)
state, err := stateSettings(options{})
// The state bucket and each index bucket take the ledger's own max-mib, as its history and snapshot do, and no
// other option of it; with none they keep the state default (design 47 H2's corrections, item 12, H-A-636).
stateOpts := options{}
if raw, ok := opts.raw[catalogue.OptionCapMiB]; ok {
stateOpts.raw = map[string]json.RawMessage{catalogue.OptionCapMiB: raw}
}
state, err := stateSettings(stateOpts)
if err != nil {
return Plan{}, err
}
+92
View File
@@ -0,0 +1,92 @@
# networkmanager
The machine's network, managed by NetworkManager: this module holds the node seat `node-uplink` (novox/hq ADR 0241),
answering its verbs `resolvers` and `links`, writes the machine's resolver file from the mesh's resolvers (ADR 0117,
ADR 0223), and reacts when the network asks the person to sign in on its **sign-in page** (ADR 0687, ADR 0689; design
08 sign-in-page §11 to §27).
## Two parts and the folder they share
Behind a sign-in page the private network's tunnel, and with it the bus, is out of reach, and the tool runner starts
no bundle before it has reached the bus. So the reaction runs in two parts:
- **the watcher**, the process `networkmanager-sign-in` (`uplink-tools watch`), started by the machine's service
manager at boot as the machine's account and kept running, needing no bus. It hears NetworkManager's rating of the
network, opens the sign-in page, tells the person, and keeps the events.
- **the bundle** `uplink-tools`, in the tool runner once it has reached the bus: it answers `resolvers` and `links`,
serves the tools below, publishes the kept events and calls `uplink-names`.
They share only the module's own folder, `~/.local/state/mesh/networkmanager` (the account's, mode 0700), every file
written whole (beside, then renamed over):
| file | what |
|---|---|
| `watch.sock` | the watcher's socket: one JSON line asked, one answered; `state` answers its state, `rating-again` makes it subscribe again and act on the rating read now |
| `check-address` | NetworkManager's check address, written by the watcher at its start and at each change |
| `pending/` | the kept changes, one `<sequence>.json` each holding the event, its sequence and its body with no node, written by the watcher and deleted by the bundle once the bus acknowledged it |
| `names.json` | the bundle's last `uplink-names` call: the names, its result (`ok`, `no holder` or the failure) and when |
| `sequence` | the next sequence of the watcher's kept changes, never reset while the folder lives |
The folder's `unknown` is `module`: the node-engine does nothing inside it, and the watcher leaves any other path it
finds there as it is and writes it to its journal once per path. When the module leaves, the node-engine keeps the
folder while it holds files, and nothing reads it then.
## The watcher opens the page on its own machine, without the bus
It hears NetworkManager's `PropertiesChanged` on the system bus for the rating (`Connectivity`), the active connection
and the check (`ConnectivityCheckEnabled`, `ConnectivityCheckAvailable`, `ConnectivityCheckUri`); nothing runs on a
timer, and the check itself stays NetworkManager's. When its system bus connection drops it subscribes again as the
bus's socket comes back.
With the check on, it opens the check address in the person's default browser and shows a notification saying why at
three moments: when the rating becomes PORTAL on the active connection, at its own start while the rating is PORTAL,
and when the person's graphical session starts while it is. It acts once per ask: again only after the rating left
PORTAL, a session's start and its own restart excepted. When the rating leaves PORTAL for FULL it says the network is
open. An open that failed gives a critical notification naming the reason and the address.
It opens with `systemd-run --user --collect --quiet --wait -- xdg-open <address>`, the address one argument and never
through a shell, after asking `xdg-mime query default x-scheme-handler/<scheme>` for the program: the browser runs
under the person's user manager and outlives the watcher. An open still running after 10 s is said as opening.
**How it finds the person's session.** Over the system bus it asks logind for its account's sessions: the one of type
`x11` or `wayland`, not remote, active or online. Its session bus is `<RuntimePath>/bus`, and its display is in the user
manager's environment (`DISPLAY` and `XAUTHORITY`, which the X11 start block imports; `WAYLAND_DISPLAY` for a Wayland
start block). No such session, or no display named there, is no session: then it opens and shows nothing, and still
keeps the events. **How it hears a session start:** logind's `SessionNew`; for a graphical session of its account it
reads the user manager's environment again at each file event in `/tmp/.X11-unix` (an X server's socket) and in the
session's runtime directory (a Wayland socket), for at most 60 s, since the user manager says no change of its
`Environment`; past that it writes that the start was not acted on.
## The events: kept by the watcher, published by the bundle
From NetworkManager's own rating the watcher keeps `node-uplink`'s two events, `sign-in-asked` (node, link, network,
the address opened, when) and `sign-in-ended` (node, link, network, when, and why: `signed-in`, `left` or
`no-longer-asked`), at most 256 of them, the oldest dropped past that with a journal line. With the check switched
off (not enabled, or not available) it neither opens nor keeps anything. The bundle publishes them in order on the
seat's subject `mesh.seat.node-uplink.event.<event>.<node>`, each under the message id `<node>.<event>.<sequence>`,
the bundle's own node filled into the subject, the id and the body (the watcher names no node), awaiting the stream's
acknowledgement, at its start, at each new kept event and when its bus connection comes back; a refused one waits for
the next moment. Nothing in the mesh consumes them: they are its record, read with `nats.nats_stream_messages`
filtered to `mesh.seat.node-uplink.event.*.<node>`, their time in `at`.
## The bundle gives the resolver the check's host name
Where a module holds `node-resolver` on this node (the assignments say which), the bundle calls its `uplink-names`
with the check address's host name, so NetworkManager's own check resolves through the network it tests: at its start,
when `check-address` changes, when its bus connection comes back and when the node-engine says that holder runs. With no holder it calls nothing, and that is no failure.
## Tools
| tool | what |
|---|---|
| `uplink_sign_in` | the reaction as it stands: the watcher's state, the events waiting and the publishes refused, the last `uplink-names` call, the resolver's refusal of the names |
| `uplink_names_again` | call `uplink-names` now |
| `uplink_rating_again` | make the watcher subscribe again and act on the rating now |
| `uplink_publish_again` | publish the kept events now |
| `uplink_health` | whether the reaction works: unhealthy while the watcher's socket does not answer, while it is not subscribed, or while the last `uplink-names` call stands failed; a tool to read, not a health check |
**The watcher's health is its unit's state** (`networkmanager-sign-in` active), judged on the machine without the bus,
so it holds behind a sign-in page. When the system bus comes back and the watcher cannot subscribe on it again, it
writes the reason to its journal and exits non-zero, so its unit shows failing and the service manager restarts it.
`uplink_health` is a tool, not a health check; the watcher not subscribed and a failed `uplink-names` call are also
shown by `uplink_sign_in` and written to the journal.
@@ -0,0 +1,108 @@
package main
// The bundle's own work beside the seat's verbs (design 08 sign-in-page §11, §13, §20): started by the tool runner
// once it reached the bus. It acts at its start, at file events of the kernel in the module's folder, and when its bus
// connection comes back: the first heartbeat of its consumer answered after a missed one (DMC-4).
import (
"encoding/json"
"os"
"path/filepath"
"sync"
"time"
stdio "git.novox.be/novox/mesh-sdk/go"
)
type bundle struct {
folder Folder
pub *publisher
names *namer
mu sync.Mutex
missed bool
lastAt time.Time
}
// bundleRuns is what the bundle hears through: file events of the kernel, its consumer's heartbeat and its
// subscription.
type bundleRuns struct {
files func(dirs []string, stop <-chan struct{}) <-chan struct{}
fileMade func(dir, name string, stop <-chan struct{}) <-chan struct{}
onHeartbeat func(func(stdio.Heartbeat)) error
subscribe func(pattern string, handle func(stdio.Envelope) error) error
}
func newBundle(f Folder) *bundle {
return &bundle{folder: f, pub: &publisher{folder: f, publish: seatPublish},
names: &namer{folder: f, ask: stdio.Ask, now: time.Now}}
}
// seatPublish says a kept event through the runtime, which awaits the stream's acknowledgement.
func seatPublish(subject string, body json.RawMessage, id string) error {
return stdio.SeatPublish(subject, body, id)
}
// start publishes what is kept and gives the resolver the check's host name, then does each again at its moments: a
// file event on pending/ publishes, a changed check-address gives the names, node-resolver's holder running gives the
// names, and the bus connection's return does both (§13, §20).
func (b *bundle) start(runs bundleRuns) {
pending := filepath.Join(b.folder.Dir, pendingName)
if err := os.MkdirAll(pending, 0o700); err != nil {
journal("making %s failed: %v", pending, err)
}
kept := runs.files([]string{pending}, nil)
check := runs.fileMade(b.folder.Dir, checkName, nil)
b.pub.publishKept("the bundle's start")
b.names.give("the bundle's start")
if err := runs.subscribe(runningPattern, b.names.running); err != nil {
journal("subscribing to %s failed: %v", runningPattern, err)
}
if err := runs.onHeartbeat(b.heartbeat); err != nil {
journal("hearing the bus connection's heartbeat failed: %v", err)
}
for kept != nil || check != nil {
select {
case _, ok := <-kept:
if !ok {
kept = nil
continue
}
b.pub.publishKept("a kept event")
case _, ok := <-check:
if !ok {
check = nil
continue
}
b.names.give("a changed check address")
}
}
}
// heartbeat hears the consumer's heartbeat: the first one answered after a missed one is the connection come back.
func (b *bundle) heartbeat(hb stdio.Heartbeat) {
b.mu.Lock()
if !hb.At.IsZero() && hb.At.Before(b.lastAt) {
b.mu.Unlock()
return
}
if !hb.At.IsZero() {
b.lastAt = hb.At
}
back := !hb.Missed && b.missed
b.missed = hb.Missed
b.mu.Unlock()
if hb.Missed {
journal("the bus connection's heartbeat was missed: %s", hb.Why)
}
if back {
journal("the bus connection came back")
b.reconnected()
}
}
// reconnected is the work at the bus connection's return.
func (b *bundle) reconnected() {
b.pub.publishKept("the bus connection's return")
b.names.give("the bus connection's return")
}
@@ -0,0 +1,354 @@
package main
// The watcher's system bus, through godbus: the network manager's properties and its PropertiesChanged, logind's
// SessionNew, and the system bus's socket coming back, heard as a file event of the kernel on its folder.
import (
"bytes"
"errors"
"fmt"
"os"
"path/filepath"
"unsafe"
"github.com/godbus/dbus/v5"
"golang.org/x/sys/unix"
)
const (
nmName = "org.freedesktop.NetworkManager"
nmPath = dbus.ObjectPath("/org/freedesktop/NetworkManager")
nmActive = "org.freedesktop.NetworkManager.Connection.Active"
nmDevice = "org.freedesktop.NetworkManager.Device"
propsIface = "org.freedesktop.DBus.Properties"
login1Name = "org.freedesktop.login1"
login1Path = dbus.ObjectPath("/org/freedesktop/login1")
login1Iface = "org.freedesktop.login1.Manager"
)
// systemSocket is the system bus's socket, whose folder the watcher watches when its connection dropped.
var systemSocket = "/run/dbus/system_bus_socket"
// ratingProperties are the network manager's properties whose change the watcher acts on (§14).
var ratingProperties = map[string]bool{"Connectivity": true, "PrimaryConnection": true,
"ConnectivityCheckEnabled": true, "ConnectivityCheckAvailable": true, "ConnectivityCheckUri": true}
type dbusSystem struct {
conn *dbus.Conn
}
func dialSystemBus() (systemBus, error) {
conn, err := dbus.ConnectSystemBus()
if err != nil {
return nil, err
}
return &dbusSystem{conn: conn}, nil
}
func (d *dbusSystem) close() { d.conn.Close() }
func (d *dbusSystem) listen() (<-chan signal, error) {
if err := d.conn.AddMatchSignal(dbus.WithMatchObjectPath(nmPath), dbus.WithMatchInterface(propsIface),
dbus.WithMatchMember("PropertiesChanged")); err != nil {
return nil, fmt.Errorf("hearing the network manager: %w", err)
}
if err := d.conn.AddMatchSignal(dbus.WithMatchObjectPath(login1Path), dbus.WithMatchInterface(login1Iface),
dbus.WithMatchMember("SessionNew")); err != nil {
return nil, fmt.Errorf("hearing logind: %w", err)
}
in := make(chan *dbus.Signal, 64)
d.conn.Signal(in)
out := make(chan signal)
go func() {
// godbus closes in when the connection drops.
for s := range in {
if heard, ok := readSignal(s); ok {
out <- heard
}
}
close(out)
}()
return out, nil
}
// readSignal is what the watcher hears in a signal of the system bus: the network manager's PropertiesChanged naming
// a property of the rating, or logind's SessionNew with the new session's object.
func readSignal(s *dbus.Signal) (signal, bool) {
switch {
case s.Path == nmPath && s.Name == propsIface+".PropertiesChanged" && len(s.Body) >= 3:
if iface, _ := s.Body[0].(string); iface != nmName {
return signal{}, false
}
changed, _ := s.Body[1].(map[string]dbus.Variant)
for name := range changed {
if ratingProperties[name] {
return signal{Rating: true}, true
}
}
invalidated, _ := s.Body[2].([]string)
for _, name := range invalidated {
if ratingProperties[name] {
return signal{Rating: true}, true
}
}
case s.Path == login1Path && s.Name == login1Iface+".SessionNew" && len(s.Body) >= 2:
if path, ok := s.Body[1].(dbus.ObjectPath); ok {
return signal{Session: string(path)}, true
}
}
return signal{}, false
}
func (d *dbusSystem) rating() (Rating, error) {
nm := d.conn.Object(nmName, nmPath)
var r Rating
for name, into := range map[string]any{"Connectivity": &r.Connectivity, "ConnectivityCheckEnabled": &r.CheckEnabled,
"ConnectivityCheckAvailable": &r.CheckAvailable, "ConnectivityCheckUri": &r.CheckURI} {
v, err := nm.GetProperty(nmName + "." + name)
if err != nil {
return Rating{}, fmt.Errorf("the network manager's %s: %w", name, err)
}
if err := v.Store(into); err != nil {
return Rating{}, fmt.Errorf("the network manager's %s: %w", name, err)
}
}
v, err := nm.GetProperty(nmName + ".PrimaryConnection")
if err != nil {
return Rating{}, fmt.Errorf("the network manager's PrimaryConnection: %w", err)
}
path, _ := v.Value().(dbus.ObjectPath)
r.Connection = string(path)
if !r.active() {
return r, nil
}
// A connection that went between the two reads is read as it is said: its name and link empty.
active := d.conn.Object(nmName, path)
if v, err := active.GetProperty(nmActive + ".Id"); err == nil {
r.Network, _ = v.Value().(string)
}
if v, err := active.GetProperty(nmActive + ".Devices"); err == nil {
if devices, _ := v.Value().([]dbus.ObjectPath); len(devices) > 0 {
if v, err := d.conn.Object(nmName, devices[0]).GetProperty(nmDevice + ".Interface"); err == nil {
r.Link, _ = v.Value().(string)
}
}
}
return r, nil
}
// systemSocketExists says whether the system bus's socket is there now.
func systemSocketExists() bool {
_, err := os.Stat(systemSocket)
return err == nil
}
// systemSocketThere fires at each file event of the kernel that makes the system bus's socket in its folder, until stop
// closes: the one moment, beside rating-again, the watcher dials the system bus again (§14; note d). It never fires
// for a socket that is merely there, so a bus that refuses the watcher is not dialled again in a loop.
func systemSocketThere(stop <-chan struct{}) <-chan struct{} {
return fileMade(filepath.Dir(systemSocket), filepath.Base(systemSocket), stop)
}
// readInotify reads the names of one read's file events; an error once the descriptor is closed.
func readInotify(f *os.File) ([]string, error) {
buf := make([]byte, 64*(unix.SizeofInotifyEvent+unix.NAME_MAX+1))
n, err := f.Read(buf)
if err != nil {
if !errors.Is(err, os.ErrClosed) {
journal("a watch of file events failed: %v", err)
}
return nil, err
}
var names []string
for off := 0; off+unix.SizeofInotifyEvent <= n; {
ev := (*unix.InotifyEvent)(unsafe.Pointer(&buf[off]))
nameAt := off + unix.SizeofInotifyEvent
end := nameAt + int(ev.Len)
if end > n {
break
}
name := buf[nameAt:end]
for i, b := range name {
if b == 0 {
name = name[:i]
break
}
}
names = append(names, string(name))
off = end
}
return names, nil
}
func (d *dbusSystem) sessions(uid uint32) ([]loginSession, error) {
var listed []struct {
ID string
UID uint32
User string
Seat string
Path dbus.ObjectPath
}
if err := d.conn.Object(login1Name, login1Path).Call(login1Iface+".ListSessions", 0).Store(&listed); err != nil {
return nil, fmt.Errorf("logind's sessions: %w", err)
}
var out []loginSession
for _, l := range listed {
if l.UID != uid {
continue
}
s, err := d.session(string(l.Path))
if err != nil {
journal("reading session %s failed: %v", l.ID, err)
continue
}
out = append(out, s)
}
return out, nil
}
func (d *dbusSystem) session(path string) (loginSession, error) {
o := d.conn.Object(login1Name, dbus.ObjectPath(path))
s := loginSession{Path: path}
var user struct {
UID uint32
Path dbus.ObjectPath
}
for name, into := range map[string]any{"Id": &s.ID, "Type": &s.Type, "Remote": &s.Remote, "State": &s.State,
"User": &user} {
v, err := o.GetProperty("org.freedesktop.login1.Session." + name)
if err != nil {
return s, fmt.Errorf("session %s's %s: %w", path, name, err)
}
if err := dbus.Store([]any{v.Value()}, into); err != nil {
return s, fmt.Errorf("session %s's %s: %w", path, name, err)
}
}
s.UID = user.UID
v, err := d.conn.Object(login1Name, user.Path).GetProperty("org.freedesktop.login1.User.RuntimePath")
if err != nil {
return s, fmt.Errorf("the user %d's RuntimePath: %w", user.UID, err)
}
s.RuntimePath, _ = v.Value().(string)
return s, nil
}
// userEnvironment is the user manager's Environment, read over the session bus at bus.
func userEnvironment(bus string) ([]string, error) {
conn, err := dbus.Connect(bus)
if err != nil {
return nil, err
}
defer conn.Close()
v, err := conn.Object("org.freedesktop.systemd1", "/org/freedesktop/systemd1").
GetProperty("org.freedesktop.systemd1.Manager.Environment")
if err != nil {
return nil, err
}
env, _ := v.Value().([]string)
return env, nil
}
// fileEvents fires at each file event of the kernel that makes a file in one of dirs (a burst is one), until stop
// closes. A folder that is not there is not watched, and said.
func fileEvents(dirs []string, stop <-chan struct{}) <-chan struct{} {
return watchFiles(dirs, nil, stop)
}
// fileMade fires at each file event of the kernel that makes name in dir, until stop closes.
func fileMade(dir, name string, stop <-chan struct{}) <-chan struct{} {
return watchFiles([]string{dir}, func(made string) bool { return made == name }, stop)
}
// watchFiles fires at each file event that makes a file in dirs whose name match takes (any, when nil).
func watchFiles(dirs []string, match func(string) bool, stop <-chan struct{}) <-chan struct{} {
out := make(chan struct{}, 1)
fd, err := unix.InotifyInit1(unix.IN_CLOEXEC | unix.IN_NONBLOCK)
if err != nil {
journal("watching %v failed: %v", dirs, err)
return out
}
for _, dir := range dirs {
if _, err := unix.InotifyAddWatch(fd, dir, unix.IN_CREATE|unix.IN_MOVED_TO); err != nil {
journal("watching %s failed: %v", dir, err)
}
}
f := os.NewFile(uintptr(fd), "inotify")
go func() {
<-stop
f.Close()
}()
go func() {
defer f.Close()
for {
names, err := readInotify(f)
if err != nil {
return
}
matched := match == nil
for _, name := range names {
matched = matched || match(name)
}
if !matched {
continue
}
select {
case out <- struct{}{}:
default:
}
}
}()
return out
}
// pathsMade hands each path a file event of the kernel makes in one of dirs, until stop closes; a folder that is not
// there is not watched, and said.
func pathsMade(dirs []string, stop <-chan struct{}) <-chan string {
out := make(chan string, 16)
fd, err := unix.InotifyInit1(unix.IN_CLOEXEC | unix.IN_NONBLOCK)
if err != nil {
journal("watching %v failed: %v", dirs, err)
return out
}
wds := map[int32]string{}
for _, dir := range dirs {
wd, err := unix.InotifyAddWatch(fd, dir, unix.IN_CREATE|unix.IN_MOVED_TO)
if err != nil {
journal("watching %s failed: %v", dir, err)
continue
}
wds[int32(wd)] = dir
}
f := os.NewFile(uintptr(fd), "inotify")
go func() {
<-stop
f.Close()
}()
go func() {
defer f.Close()
buf := make([]byte, 64*(unix.SizeofInotifyEvent+unix.NAME_MAX+1))
for {
n, err := f.Read(buf)
if err != nil {
return
}
for off := 0; off+unix.SizeofInotifyEvent <= n; {
ev := (*unix.InotifyEvent)(unsafe.Pointer(&buf[off]))
nameAt := off + unix.SizeofInotifyEvent
end := nameAt + int(ev.Len)
if end > n {
break
}
name := string(bytes.TrimRight(buf[nameAt:end], "\x00"))
off = end
if dir, ok := wds[ev.Wd]; ok && name != "" {
select {
case out <- filepath.Join(dir, name):
case <-stop:
return
}
}
}
}
}()
return out
}
@@ -1,5 +1,6 @@
// The uplink holder's tools bundle: the node-uplink seat's verbs (novox/hq ADR 0241), served by the node's
// runtime as the operator account. uplink.go is every holder's; manager.go is this holder's own. stdout is
// runtime as the operator account. uplink.go is every holder's; manager.go is this holder's own, and gives the
// holder's own subcommands, tools and the work its bundle starts beside them (design 08 sign-in-page §11). stdout is
// the MCP channel; this says nothing else.
package main
@@ -11,8 +12,16 @@ import (
stdio "git.novox.be/novox/mesh-sdk/go"
)
func tools(m Machine) []stdio.Tool {
return []stdio.Tool{
// holderOwn is what a holder adds to the seat's verbs, from its manager.go: its subcommands (a process of the module
// runs one, as `uplink-tools <name>`), its own tools and the work its bundle starts once it serves.
type holderOwn struct {
Commands map[string]func(args []string) error
Tools []stdio.Tool
Start func()
}
func tools(m Machine, own holderOwn) []stdio.Tool {
return append([]stdio.Tool{
{Name: seat + ".resolvers",
Description: "The machine's resolver file as it is now: the resolvers, search domains and options it lists, " +
"whether it is the file the mesh declares, and when it is not, who wrote it as far as the machine shows " +
@@ -23,12 +32,40 @@ func tools(m Machine) []stdio.Tool {
"leaves through it, and the resolvers and search domains the network manager knows for it — a VPN's " +
"tunnel included. (r)",
Run: func(map[string]any) (any, error) { return m.Links(context.Background()) }},
}, own.Tools...)
}
// command is the holder's subcommand args name, or an error naming it when the holder has none such; nil with no args,
// which is the bundle.
func command(own holderOwn, args []string) (func(args []string) error, error) {
if len(args) == 0 {
return nil, nil
}
if run, ok := own.Commands[args[0]]; ok {
return run, nil
}
return nil, fmt.Errorf("uplink-tools has no subcommand %q", args[0])
}
func main() {
m := Machine{ResolvPath: ResolvConf, Run: execRunner, Running: running, LinkDNS: managerDNS}
if err := stdio.Serve("", tools(m)); err != nil {
own := holder(m)
run, err := command(own, os.Args[1:])
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(2)
}
if run != nil {
if err := run(os.Args[2:]); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
return
}
if own.Start != nil {
go own.Start()
}
if err := stdio.Serve("", tools(m, own)); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
@@ -7,6 +7,8 @@ package main
import (
"context"
"strings"
stdio "git.novox.be/novox/mesh-sdk/go"
)
func managerDNS(ctx context.Context) (map[string]LinkDNS, error) {
@@ -50,3 +52,20 @@ func parseNmcli(out string) map[string]LinkDNS {
flush()
return links
}
// holder is what networkmanager adds to the seat's verbs (design 08 sign-in-page §11): the watcher, `uplink-tools
// watch`.
func holder(m Machine) holderOwn {
own := holderOwn{Commands: map[string]func([]string) error{"watch": watch}}
f, err := theFolder()
if err != nil {
journal("the module's folder: %v", err)
return own
}
b := newBundle(f)
own.Tools = b.tools()
own.Start = func() {
b.start(bundleRuns{files: fileEvents, fileMade: fileMade, onHeartbeat: stdio.OnHeartbeat, subscribe: stdio.Subscribe})
}
return own
}
@@ -16,3 +16,10 @@ func TestNmcliIsReadPerDevice(t *testing.T) {
t.Fatal("a link with no names was said")
}
}
// networkmanager's own part: the watcher's subcommand (design 08 sign-in-page §11).
func TestNetworkManagerRunsItsWatcherAsASubcommand(t *testing.T) {
if run, err := command(holder(Machine{}), []string{"watch"}); err != nil || run == nil {
t.Fatalf("uplink-tools watch is not the watcher: %v", err)
}
}
@@ -0,0 +1,150 @@
package main
// The bundle gives the resolver the check's host name (design 08 sign-in-page §13): it calls
// `<node>/node-resolver.uplink-names` with the check address's host name, or an empty list when there is no address,
// and writes the call to names.json. Which module holds node-resolver on its node it reads from the seat
// mesh-module-assigner's assignments; none is `no holder`, which is no failure (DQ-8). A failed call is written to the
// journal, stands failed in names.json and is asked again at the next moment, never on a timer.
import (
"encoding/json"
"fmt"
"net/url"
"strings"
"sync"
"time"
"git.novox.be/novox/mesh-networking/modules/mesh-connectivity-contracts/go/seats/noderesolver"
stdio "git.novox.be/novox/mesh-sdk/go"
)
const (
// runningPattern is node-engine's running event, as the manifest consumes it: node-engine.running.<node>.<module>.
runningPattern = "node-engine.running.*.*"
assignmentsKey = "seat:mesh-module-assigner.assignments"
)
// namer calls uplink-names, one call at a time.
type namer struct {
folder Folder
// ask calls a verb on the mesh as the module, through the runtime.
ask func(key string, body any) (json.RawMessage, error)
now func() time.Time
mu sync.Mutex
}
// hostOf is the check address's host name, lower-cased, as uplink-names takes it: none for an empty address.
func hostOf(address string) ([]string, error) {
if address == "" {
return []string{}, nil
}
u, err := url.Parse(address)
if err != nil || u.Hostname() == "" {
return nil, fmt.Errorf("the check address %q names no host", address)
}
return []string{strings.ToLower(u.Hostname())}, nil
}
// resolverHolder is the module that holds node-resolver on this node, "" when none does (DQ-8).
func (n *namer) resolverHolder() (string, error) {
raw, err := n.ask(assignmentsKey, map[string]string{"node": n.folder.Node, "seats": "true"})
if err != nil {
return "", fmt.Errorf("reading the assignments: %w", err)
}
var answer struct {
Seats []struct {
Seat string `json:"seat"`
Holders []struct {
Module string `json:"module"`
Node string `json:"node"`
} `json:"holders"`
} `json:"seats"`
}
if err := json.Unmarshal(raw, &answer); err != nil {
return "", fmt.Errorf("the assignments answered in no form this reads: %w", err)
}
for _, s := range answer.Seats {
if s.Seat != noderesolver.Seat {
continue
}
for _, h := range s.Holders {
if h.Node == n.folder.Node {
return h.Module, nil
}
}
}
return "", nil
}
// give calls uplink-names now with the check address's host name and writes the call to names.json.
func (n *namer) give(moment string) NamesCall {
n.mu.Lock()
defer n.mu.Unlock()
call := NamesCall{Names: []string{}, At: n.now()}
address, err := n.folder.checkAddress()
if err == nil {
call.Names, err = hostOf(address)
}
if err == nil {
call.Result, err = n.call(call.Names)
}
if err != nil {
call.Result = err.Error()
}
if call.Names == nil {
call.Names = []string{}
}
if err := n.folder.writeNames(call); err != nil {
journal("writing names.json failed: %v", err)
}
journal("uplink-names %v at %s: %s", call.Names, moment, call.Result)
return call
}
func (n *namer) call(names []string) (string, error) {
holder, err := n.resolverHolder()
if err != nil {
return "", err
}
if holder == "" {
return resultNoHolder, nil
}
raw, err := n.ask(uplinkNamesKey(n.folder.Node), noderesolver.UplinkNamesInput{Names: names})
if err != nil {
return "", fmt.Errorf("%s/%s.%s: %w", n.folder.Node, noderesolver.Seat, noderesolver.VerbUplinkNames, err)
}
if _, _, err := noderesolver.DecodeUplinkNamesAnswer(raw); err != nil {
return "", fmt.Errorf("uplink-names answered in no form this reads: %w", err)
}
return resultOK, nil
}
func uplinkNamesKey(node string) string {
return "seat:" + noderesolver.Seat + "." + noderesolver.VerbUplinkNames + "@" + node
}
// running hears node-engine's running: one for this node's holder of node-resolver, running, is a moment to call
// uplink-names; every other is dropped, another node's first (§13).
func (n *namer) running(e stdio.Envelope) error {
parts := strings.Split(e.Key, ".")
if len(parts) != 4 || parts[2] != n.folder.Node {
return nil
}
var body struct {
Module string `json:"module"`
Stopped bool `json:"stopped"`
}
if err := json.Unmarshal(e.Body, &body); err != nil || body.Stopped {
return nil
}
holder, err := n.resolverHolder()
if err != nil {
journal("hearing %s: %v", e.Key, err)
return nil
}
if holder != "" && holder == parts[3] {
n.give(holder + " running")
}
return nil
}
@@ -0,0 +1,149 @@
package main
import (
"encoding/json"
"errors"
"strings"
"sync"
"testing"
"time"
stdio "git.novox.be/novox/mesh-sdk/go"
)
// The mesh stood in for the bundle's asks: the assignments naming this node's holder of node-resolver (none when
// holder is empty), and node-resolver's uplink-names, failing while fail is set.
type fakeMesh struct {
mu sync.Mutex
holder string
fail error
calls []string
routes string
// given, when set, hears each uplink-names call once made, so a test acts after it and never on a guess of when.
given chan string
}
func (m *fakeMesh) ask(key string, body any) (json.RawMessage, error) {
m.mu.Lock()
defer m.mu.Unlock()
switch key {
case assignmentsKey:
in := body.(map[string]string)
if in["node"] != "laptop" || in["seats"] != "true" {
return nil, errors.New("asked the assignments of another node")
}
seats := `{"seats":[{"seat":"node-uplink","holders":[{"module":"networkmanager","node":"laptop"}]}`
if m.holder != "" {
seats += `,{"seat":"node-resolver","holders":[{"module":"` + m.holder + `","node":"laptop"}]}`
}
return json.RawMessage(seats + `]}`), nil
case "seat:node-resolver.uplink-names@laptop":
raw, _ := json.Marshal(body)
m.calls = append(m.calls, string(raw))
if m.given != nil {
m.given <- string(raw)
}
if m.fail != nil {
return nil, m.fail
}
return json.RawMessage(`{"names":["check.example.net"],"link":"wlan0","set_at":"2026-11-24T19:00:00Z"}`), nil
case "seat:node-resolver.routes@laptop":
if m.routes == "" {
return nil, errors.New("no routes")
}
return json.RawMessage(m.routes), nil
}
return nil, errors.New("no such verb " + key)
}
func (m *fakeMesh) called() []string {
m.mu.Lock()
defer m.mu.Unlock()
return append([]string(nil), m.calls...)
}
// uplink-names is called at the bundle's start, on a changed check-address, when the bus connection comes back and on
// a running holder of node-resolver on its own node; every other running is dropped; no holder is recorded and is
// healthy, a failed call stands failed (design 08 sign-in-page §13, §25).
func TestUplinkNamesIsCalledAtEachMoment(t *testing.T) {
lines := journalLines(t)
f := aFolder(t)
if err := f.writeCheckAddress("http://Check.Example.net/connecttest"); err != nil {
t.Fatal(err)
}
mesh := &fakeMesh{holder: "systemd-resolved", given: make(chan string, 16)}
b := &bundle{folder: f, pub: &publisher{folder: f, publish: (&fakeStream{}).publish},
names: &namer{folder: f, ask: mesh.ask, now: time.Now}}
check := make(chan struct{})
// The bundle runs beside the test: each check address is changed only once the call made from the one before was
// heard, so the test never races the bundle's read of check-address (a call never made ends the run at its bound).
heard := func() { <-mesh.given }
var running func(stdio.Envelope) error
var hook func(stdio.Heartbeat)
done := make(chan struct{})
go func() {
b.start(bundleRuns{files: func([]string, <-chan struct{}) <-chan struct{} { return nil },
fileMade: func(dir, name string, _ <-chan struct{}) <-chan struct{} {
if dir != f.Dir || name != "check-address" {
t.Errorf("watched %s in %s", name, dir)
}
return check
},
onHeartbeat: func(h func(stdio.Heartbeat)) error { hook = h; return nil },
subscribe: func(pattern string, h func(stdio.Envelope) error) error {
if pattern != "node-engine.running.*.*" {
t.Errorf("subscribed to %s", pattern)
}
running = h
return nil
}})
close(done)
}()
heard()
if err := f.writeCheckAddress(""); err != nil {
t.Fatal(err)
}
check <- struct{}{}
heard()
f.writeCheckAddress("https://other.example.net/")
close(check)
<-done
want := []string{`{"names":["check.example.net"]}`, `{"names":[]}`}
if got := mesh.called(); strings.Join(got, " ") != strings.Join(want, " ") {
t.Fatalf("at the start and a changed check address: called %q", got)
}
hook(stdio.Heartbeat{Missed: true})
hook(stdio.Heartbeat{})
for _, e := range []stdio.Envelope{
{Key: "node-engine.running.other.systemd-resolved", Body: json.RawMessage(`{"module":"systemd-resolved"}`)},
{Key: "node-engine.running.laptop.i3", Body: json.RawMessage(`{"module":"i3"}`)},
{Key: "node-engine.running.laptop.systemd-resolved", Body: json.RawMessage(`{"module":"systemd-resolved","stopped":true}`)},
{Key: "node-engine.running.laptop.systemd-resolved", Body: json.RawMessage(`{"module":"systemd-resolved","healthy":true}`)},
} {
if err := running(e); err != nil {
t.Fatal(err)
}
}
want = append(want, `{"names":["other.example.net"]}`, `{"names":["other.example.net"]}`)
if got := mesh.called(); strings.Join(got, " ") != strings.Join(want, " ") {
t.Fatalf("at the connection's return and a running holder: called %q", got)
}
if c, _ := f.names(); c == nil || c.Result != resultOK || strings.Join(c.Names, " ") != "other.example.net" {
t.Fatalf("names.json holds %+v", c)
}
mesh.holder = ""
if c := b.names.give("a test"); c.Result != resultNoHolder || c.Failed() || len(mesh.called()) != 4 {
t.Fatalf("no holder gave %+v after %d calls", c, len(mesh.called()))
}
mesh.holder, mesh.fail = "systemd-resolved", errors.New("no answer within its bound")
if c := b.names.give("a test"); !c.Failed() || !strings.Contains(c.Result, "no answer within its bound") {
t.Fatalf("a failed call gave %+v", c)
}
if c, _ := f.names(); c == nil || !c.Failed() {
t.Fatalf("names.json holds %+v", c)
}
if !strings.Contains(strings.Join(lines(), "\n"), "uplink-names [other.example.net] at a test: laptop/node-resolver.uplink-names: no answer") {
t.Fatalf("the failed call is not in the journal: %q", lines())
}
}
@@ -0,0 +1,21 @@
package main
// Telling the person (design 08 sign-in-page §19): org.freedesktop.Notifications.Notify on the session's bus, the
// desktop notification service, app_name mesh.
import "github.com/godbus/dbus/v5"
func notifyOn(bus string, n note) error {
conn, err := dbus.Connect(bus)
if err != nil {
return err
}
defer conn.Close()
hints := map[string]dbus.Variant{}
if n.Critical {
hints["urgency"] = dbus.MakeVariant(byte(2))
}
return conn.Object("org.freedesktop.Notifications", "/org/freedesktop/Notifications").
Call("org.freedesktop.Notifications.Notify", 0, "mesh", uint32(0), "", n.Summary, n.Body, []string{}, hints,
int32(-1)).Err
}
@@ -0,0 +1,243 @@
package main
// Opening the page and telling the person (design 08 sign-in-page §15, §18, §19): at the three moments, once per ask,
// in the person's session. The open runs beside the watch; rating changes heard meanwhile are handled after it, in the
// order they came.
import (
"context"
"errors"
"fmt"
"net/url"
"os/exec"
"strings"
"time"
)
// openBound is how long the watcher waits for the opener: ended within it, its status decides; still running at it,
// the page is opening and the run is left to go on (§18).
const openBound = 10 * time.Second
// desk is the person's desktop as the watcher reaches it: an address opened in their session, a notification shown.
type desk interface {
open(s Session, address string) openOutcome
notify(s Session, n note) error
}
// openOutcome is how an open ended: opened, opening (still running at its bound) or failed, with the program and the
// reason of a failure.
type openOutcome struct {
Address string `json:"address"`
Program string `json:"program,omitempty"`
Outcome string `json:"outcome"`
Reason string `json:"reason,omitempty"`
At time.Time `json:"at"`
}
// The outcomes of an open.
const (
outcomeOpened = "opened"
outcomeOpening = "opening"
outcomeFailed = "failed"
)
// note is one notification: its summary and body, critical or not, and, once shown, when and whether it failed.
type note struct {
Summary string `json:"summary"`
Body string `json:"body"`
Critical bool `json:"critical,omitempty"`
At time.Time `json:"at"`
Error string `json:"error,omitempty"`
}
const askedSummary = "This network asks you to sign in"
// signInNote is what the person is told after an open, by its outcome (§19).
func signInNote(network, address string, o openOutcome) note {
switch o.Outcome {
case outcomeOpened:
return note{Summary: askedSummary, Body: fmt.Sprintf("%s: its sign-in page is open in %s.", network, o.Program)}
case outcomeOpening:
return note{Summary: askedSummary, Body: fmt.Sprintf("%s: its sign-in page is opening in %s.", network, o.Program)}
}
return note{Summary: askedSummary, Critical: true,
Body: fmt.Sprintf("%s: the page did not open (%s); open %s in a browser.", network, o.Reason, address)}
}
// signedInNote is what the person is told when the rating leaves PORTAL for FULL (§19).
func signedInNote(network string) note {
return note{Summary: "The network is open", Body: network + ": signed in."}
}
// present opens the address in the person's session, s or the one found now, and then tells them (§15, §18, §19),
// beside the watch; with no session found it opens and shows nothing, and the events are kept all the same (§15,
// §16).
func (w *Watcher) present(s *Session, network, address string) {
if w.opening {
w.later = append(w.later, func() { w.present(s, network, address) })
return
}
if s = w.sessionNow(s, "the sign-in page of "+network+" is not opened"); s == nil {
return
}
session := *s
w.opening = true
w.Beside(func() func() {
o := w.Desk.open(session, address)
n := signInNote(network, address, o)
err := w.Desk.notify(session, n)
return func() {
o.At = w.Now()
w.state.LastOpen = &o
if o.Outcome == outcomeFailed {
journal("opening %s in session %s failed: %s", address, session.ID, o.Reason)
} else {
journal("the sign-in page %s is %s in %s", address, o.Outcome, o.Program)
}
w.shown(n, err)
w.opening = false
w.drain()
}
})
}
// tellSignedIn tells the person the network is open, in their session; with none, nothing (§19).
func (w *Watcher) tellSignedIn(network string) {
s := w.sessionNow(nil, "the network being open is not shown")
if s == nil {
return
}
session, n := *s, signedInNote(network)
w.Beside(func() func() {
err := w.Desk.notify(session, n)
return func() { w.shown(n, err) }
})
}
// sessionNow is s, or the person's session found now; nil with a journal line saying what is not done.
func (w *Watcher) sessionNow(s *Session, notDone string) *Session {
if s != nil {
return s
}
found, err := w.findSession()
if err != nil {
journal("finding the person's session failed: %v; %s", err, notDone)
return nil
}
if found == nil {
journal("no graphical session: %s", notDone)
}
return found
}
func (w *Watcher) shown(n note, err error) {
n.At = w.Now()
if err != nil {
n.Error = err.Error()
journal("showing the notification %q failed: %v", n.Summary, err)
} else {
journal("showed the notification %q: %s", n.Summary, n.Body)
}
w.state.LastNotification = &n
}
// drain handles, in the order they came, what was heard during an open, until one starts another open.
func (w *Watcher) drain() {
for len(w.later) > 0 && !w.opening {
next := w.later[0]
w.later = w.later[1:]
next()
}
}
// besideLoop runs work beside the loop and hands its end back to the loop, which runs it.
func (w *Watcher) besideLoop(work func() func()) {
go func() { w.ends <- work() }()
}
// sessionDesk opens and tells in the person's session: the programs run with the session's bus and runtime directory
// in their environment.
type sessionDesk struct {
// query runs a program to its end, within openBound, and answers its output.
query func(env []string, name string, args ...string) (string, error)
// start starts a program; its end, with its status, comes on the channel.
start func(env []string, name string, args ...string) (<-chan error, error)
after func(time.Duration) <-chan time.Time
show func(bus string, n note) error
}
func newSessionDesk() sessionDesk {
return sessionDesk{query: queryProgram, start: startProgram, after: time.After, show: notifyOn}
}
// open asks xdg-mime for the scheme's program, then runs `systemd-run --user --collect --quiet --wait -- xdg-open
// <address>`, the address one argument and no shell, so the browser runs under the person's user manager and outlives
// the watcher (§18).
func (d sessionDesk) open(s Session, address string) openOutcome {
o := openOutcome{Address: address, Outcome: outcomeFailed}
u, err := url.Parse(address)
if err != nil {
o.Reason = err.Error()
return o
}
program, err := d.query(s.Env(), "xdg-mime", "query", "default", "x-scheme-handler/"+u.Scheme)
if err != nil {
o.Reason = "xdg-mime: " + err.Error()
return o
}
if program = strings.TrimSpace(program); program == "" {
o.Reason = "no default program for " + u.Scheme
return o
}
done, err := d.start(s.Env(), "systemd-run", "--user", "--collect", "--quiet", "--wait", "--", "xdg-open", address)
if err != nil {
o.Reason = "systemd-run: " + err.Error()
return o
}
o.Program = program
select {
case err := <-done:
if err != nil {
o.Program, o.Reason = "", "xdg-open "+status(err)
return o
}
o.Outcome = outcomeOpened
case <-d.after(openBound):
o.Outcome = outcomeOpening
}
return o
}
func (d sessionDesk) notify(s Session, n note) error { return d.show(s.Bus(), n) }
// status names how a program ended: its exit status, or why it did not end with one.
func status(err error) string {
var exit *exec.ExitError
if errors.As(err, &exit) {
return fmt.Sprintf("ended with status %d", exit.ExitCode())
}
return "failed: " + err.Error()
}
func queryProgram(env []string, name string, args ...string) (string, error) {
ctx, cancel := context.WithTimeout(context.Background(), openBound)
defer cancel()
cmd := exec.CommandContext(ctx, name, args...)
cmd.Env = env
out, err := cmd.Output()
if err != nil {
return "", errors.New(status(err))
}
return string(out), nil
}
func startProgram(env []string, name string, args ...string) (<-chan error, error) {
cmd := exec.Command(name, args...)
cmd.Env = env
if err := cmd.Start(); err != nil {
return nil, err
}
done := make(chan error, 1)
go func() { done <- cmd.Wait() }()
return done, nil
}
@@ -0,0 +1,199 @@
package main
import (
"errors"
"os/exec"
"strings"
"testing"
"time"
)
// aDeskWatcher is a watcher with the person's session found and the desktop stood in; it starts subscribed, the rating
// at its start being start.
func aDeskWatcher(t *testing.T, start Rating) (*Watcher, *fakeSystem, *fakeDesk) {
t.Helper()
sys := &fakeSystem{sessions: []loginSession{personsSession()}}
sys.set(start)
w := aWatcher(t, sys)
w.Environment = func(string) ([]string, error) { return []string{"DISPLAY=:1", "XAUTHORITY=/x"}, nil }
w.subscribe()
return w, sys, w.Desk.(*fakeDesk)
}
const openedNote = "This network asks you to sign in: guest-example: its sign-in page is open in browser.desktop."
// PORTAL at a join and PORTAL at the watcher's start each open the page and show one notification; a second PORTAL
// without a leave does nothing; PORTAL to FULL shows that the network is open, PORTAL to any other rating shows nothing
// (design 08 sign-in-page §15, §19, §25).
func TestTheRatingOpensThePageAndTellsThePersonOncePerAsk(t *testing.T) {
for _, c := range []struct {
name string
start Rating
then []Rating
opens int
notes []string
journal string
}{
{"PORTAL at a join", guest(ratingFull), []Rating{guest(ratingPortal)}, 1, []string{openedNote},
"showed the notification"},
{"PORTAL at the start", guest(ratingPortal), nil, 1, []string{openedNote}, "the sign-in page http://check.example.net/ is opened in browser.desktop"},
{"a second PORTAL", guest(ratingPortal), []Rating{guest(ratingPortal), guest(ratingPortal)}, 1,
[]string{openedNote}, ""},
{"PORTAL to FULL", guest(ratingPortal), []Rating{guest(ratingFull)}, 1,
[]string{openedNote, "The network is open: guest-example: signed in."}, ""},
{"PORTAL to LIMITED", guest(ratingPortal), []Rating{guest(ratingLimited)}, 1, []string{openedNote}, ""},
{"PORTAL, left, PORTAL on another", guest(ratingPortal), []Rating{other(ratingPortal)}, 2,
[]string{openedNote, "This network asks you to sign in: home-example: its sign-in page is open in browser.desktop."}, ""},
} {
t.Run(c.name, func(t *testing.T) {
lines := journalLines(t)
w, sys, desk := aDeskWatcher(t, c.start)
for _, r := range c.then {
sys.set(r)
w.heardSignal(signal{Rating: true})
}
if got := desk.opened(); len(got) != c.opens {
t.Fatalf("opened %q", got)
}
if got := desk.shown(); strings.Join(got, "|") != strings.Join(c.notes, "|") {
t.Fatalf("showed %q, want %q", got, c.notes)
}
if !strings.Contains(strings.Join(lines(), "\n"), c.journal) {
t.Fatalf("the journal does not say %q: %q", c.journal, lines())
}
})
}
}
// An opener that fails gives the critical notification naming the reason and the address (§19, §25).
func TestAFailingOpenerGivesTheCriticalNotification(t *testing.T) {
journalLines(t)
sys := &fakeSystem{sessions: []loginSession{personsSession()}}
sys.set(guest(ratingFull))
w := aWatcher(t, sys)
w.Environment = func(string) ([]string, error) { return []string{"DISPLAY=:1"}, nil }
desk := w.Desk.(*fakeDesk)
desk.outcome = openOutcome{Address: "http://check.example.net/", Outcome: outcomeFailed, Reason: "xdg-open ended with status 4"}
w.subscribe()
sys.set(guest(ratingPortal))
w.heardSignal(signal{Rating: true})
want := "critical This network asks you to sign in: guest-example: the page did not open (xdg-open ended with status 4); " +
"open http://check.example.net/ in a browser."
if got := desk.shown(); len(got) != 1 || got[0] != want {
t.Fatalf("showed %q", got)
}
if w.state.LastOpen == nil || w.state.LastOpen.Outcome != outcomeFailed || w.state.LastNotification == nil {
t.Fatalf("the state says %+v", w.state)
}
}
// A rating change heard while the page opens is handled after the open, in the order heard (§18, §25).
func TestARatingChangeHeardDuringAnOpenIsHandledAfterIt(t *testing.T) {
journalLines(t)
sys := &fakeSystem{sessions: []loginSession{personsSession()}}
sys.set(guest(ratingFull))
w := aWatcher(t, sys)
w.Environment = func(string) ([]string, error) { return []string{"DISPLAY=:1"}, nil }
var beside []func() func()
w.Beside = func(work func() func()) { beside = append(beside, work) }
w.subscribe()
sys.set(guest(ratingPortal))
w.heardSignal(signal{Rating: true})
sys.set(guest(ratingLimited))
w.heardSignal(signal{Rating: true})
sys.set(guest(ratingFull))
w.heardSignal(signal{Rating: true})
if got := keptSaid(t, w.Folder); len(got) != 2 || len(beside) != 1 {
t.Fatalf("during the open: kept %q, %d run beside", got, len(beside))
}
beside[0]()()
got := keptSaid(t, w.Folder)
if len(got) != 3 || got[2] != "sign-in-ended no-longer-asked guest-example wlan0" {
t.Fatalf("after the open: kept %q", got)
}
if w.opening || len(w.later) != 0 {
t.Fatal("what was heard is still waiting")
}
}
// The opener in the person's session: xdg-mime asked for the scheme's program, then systemd-run --user with the address
// as one argument, both with the session's bus and runtime directory; its status, or its bound, decides (§18).
func TestTheOpenerRunsInThePersonsSession(t *testing.T) {
s := Session{ID: "2", Type: "x11", RuntimePath: "/run/user/1000"}
address := "http://check.example.net/a'b;c"
for _, c := range []struct {
name string
program string
ends error
running bool
want openOutcome
}{
{"opened", "browser.desktop\n", nil, false, openOutcome{Address: address, Program: "browser.desktop", Outcome: outcomeOpened}},
{"opening", "browser.desktop\n", nil, true, openOutcome{Address: address, Program: "browser.desktop", Outcome: outcomeOpening}},
{"failed", "browser.desktop\n", exitStatus(t, 3), false,
openOutcome{Address: address, Outcome: outcomeFailed, Reason: "xdg-open ended with status 3"}},
{"no program", "\n", nil, false, openOutcome{Address: address, Outcome: outcomeFailed, Reason: "no default program for http"}},
} {
t.Run(c.name, func(t *testing.T) {
var ran []string
envOf := func(env []string) string {
var out []string
for _, kv := range env {
if strings.HasPrefix(kv, "DBUS_SESSION_BUS_ADDRESS=") || strings.HasPrefix(kv, "XDG_RUNTIME_DIR=") {
out = append(out, kv)
}
}
return strings.Join(out, " ")
}
bound := make(chan time.Time, 1)
d := sessionDesk{
query: func(env []string, name string, args ...string) (string, error) {
ran = append(ran, envOf(env)+" | "+name+" "+strings.Join(args, " "))
return c.program, nil
},
start: func(env []string, name string, args ...string) (<-chan error, error) {
ran = append(ran, envOf(env)+" | "+name+" "+strings.Join(args, " "))
if args[len(args)-1] != address {
t.Errorf("the address is not one argument: %q", args)
}
done := make(chan error, 1)
if c.running {
bound <- time.Now()
} else {
done <- c.ends
}
return done, nil
},
after: func(d time.Duration) <-chan time.Time {
if d != 10*time.Second {
t.Errorf("the open's bound is %s", d)
}
return bound
},
}
got := d.open(s, address)
if got != c.want {
t.Fatalf("answered %+v, want %+v", got, c.want)
}
env := "DBUS_SESSION_BUS_ADDRESS=unix:path=/run/user/1000/bus XDG_RUNTIME_DIR=/run/user/1000 | "
want := []string{env + "xdg-mime query default x-scheme-handler/http"}
if c.program != "\n" {
want = append(want, env+"systemd-run --user --collect --quiet --wait -- xdg-open "+address)
}
if strings.Join(ran, "\n") != strings.Join(want, "\n") {
t.Fatalf("ran\n%s\nwant\n%s", strings.Join(ran, "\n"), strings.Join(want, "\n"))
}
})
}
}
// exitStatus is the error of a program that ended with status n.
func exitStatus(t *testing.T, n int) error {
t.Helper()
err := exec.Command("sh", "-c", "exit "+string(rune('0'+n))).Run()
var exit *exec.ExitError
if !errors.As(err, &exit) {
t.Fatalf("no exit status: %v", err)
}
return err
}
@@ -0,0 +1,93 @@
package main
// The bundle publishes the kept events (design 08 sign-in-page §20): in sequence order, on the seat's subject, each
// with its message id as the bus's message id (the runtime prefixes it with the module), awaiting the stream's
// acknowledgement, and deletes each file once acknowledged. A publish refused or unacknowledged stays in pending/, is
// written to the journal and counted, and is published again at the next moment: the bundle's start, a file event of
// the kernel on pending/, its bus connection coming back, or uplink_publish_again.
import (
"encoding/json"
"errors"
"fmt"
"sync"
)
// publisher publishes the kept events, one round at a time.
type publisher struct {
folder Folder
// publish says one event on the seat, de-duplicated by id, and answers once the stream acknowledged it.
publish func(subject string, body json.RawMessage, id string) error
mu sync.Mutex
refused int
}
// publishResult is one round: how many were published and how many still wait.
type publishResult struct {
Published int `json:"published"`
Waiting int `json:"waiting"`
Refused string `json:"refused,omitempty"`
}
// publishKept publishes every kept event in order; the first refused stops the round, so none is published before an
// older one.
func (p *publisher) publishKept(moment string) publishResult {
p.mu.Lock()
defer p.mu.Unlock()
var out publishResult
kept, err := p.folder.pending()
if err != nil {
journal("reading the kept events at %s failed: %v", moment, err)
out.Refused = err.Error()
return out
}
for i, k := range kept {
subject, id, body, err := p.outgoing(k)
if err == nil {
err = p.publish(subject, body, id)
}
if err != nil {
p.refused++
out.Waiting, out.Refused = len(kept)-i, err.Error()
journal("publishing %s at %s was refused or not acknowledged: %v; %d left waiting", k.Name(), moment, err,
out.Waiting)
return out
}
journal("published %s on %s", id, subject)
out.Published++
if err := p.folder.drop(k); err != nil {
journal("deleting the published %s failed: %v", id, err)
}
}
return out
}
// outgoing is a kept change as the bundle publishes it on its own node: the seat's subject, the message id
// `<node>.<event>.<sequence>` and the body with its node (§20; lead answer L-3).
func (p *publisher) outgoing(k Kept) (string, string, json.RawMessage, error) {
node := p.folder.Node
if node == "" {
return "", "", nil, errors.New("no node named: the tool runner names the bundle's in MESH_NODE")
}
if k.Event != eventAsked && k.Event != eventEnded {
return "", "", nil, fmt.Errorf("the kept change %s is of no event of the seat", k.Name())
}
var body map[string]json.RawMessage
if err := json.Unmarshal(k.Body, &body); err != nil {
return "", "", nil, fmt.Errorf("the kept change %s holds no body: %w", k.Name(), err)
}
body["node"], _ = json.Marshal(node)
raw, err := json.Marshal(body)
if err != nil {
return "", "", nil, err
}
return eventSubject(k.Event, node), fmt.Sprintf("%s.%s.%d", node, k.Event, k.Sequence), raw, nil
}
// refusedSince is the publishes refused since the bundle's start.
func (p *publisher) refusedSince() int {
p.mu.Lock()
defer p.mu.Unlock()
return p.refused
}
@@ -0,0 +1,161 @@
package main
import (
"encoding/json"
"errors"
"strings"
"sync"
"testing"
"time"
"git.novox.be/novox/mesh-networking/modules/mesh-connectivity-contracts/go/seats/nodeuplink"
stdio "git.novox.be/novox/mesh-sdk/go"
)
// The bus stood in: every publish asked, the ids it refuses once, as the runtime answers a publish the stream did not
// acknowledge.
type fakeStream struct {
mu sync.Mutex
asked []string
refuse map[string]bool
}
func (s *fakeStream) publish(subject string, body json.RawMessage, id string) error {
s.mu.Lock()
defer s.mu.Unlock()
s.asked = append(s.asked, id)
if s.refuse[id] {
delete(s.refuse, id)
return errors.New("no acknowledgement")
}
if !json.Valid(body) || !strings.HasPrefix(subject, "mesh.seat.node-uplink.event.") {
return errors.New("not an event of the seat")
}
return nil
}
func (s *fakeStream) publishes() string {
s.mu.Lock()
defer s.mu.Unlock()
return strings.Join(s.asked, " ")
}
func keepThree(t *testing.T, f Folder) {
t.Helper()
for _, event := range []string{eventEnded, eventAsked, eventEnded} {
if _, err := f.keep(event, map[string]string{"link": "wlan0"}); err != nil {
t.Fatal(err)
}
}
}
// The bundle publishes the kept events in order with their message ids and deletes each once acknowledged; a refused
// one stays, with the ones after it, and is published at the next moment under the same id (design 08 sign-in-page
// §20, §25).
func TestTheBundlePublishesTheKeptEventsInOrder(t *testing.T) {
lines := journalLines(t)
f := aFolder(t)
keepThree(t, f)
stream := &fakeStream{refuse: map[string]bool{"laptop.sign-in-asked.2": true}}
p := &publisher{folder: f, publish: stream.publish}
if r := p.publishKept("the bundle's start"); r.Published != 1 || r.Waiting != 2 || p.refusedSince() != 1 {
t.Fatalf("first round %+v, refused %d", r, p.refusedSince())
}
if kept, _ := f.pending(); len(kept) != 2 || kept[0].Name() != "sign-in-asked.2" {
t.Fatalf("waiting %+v", kept)
}
if !strings.Contains(strings.Join(lines(), "\n"), "publishing sign-in-asked.2 at the bundle's start was refused") {
t.Fatalf("the refusal was not written to the journal: %q", lines())
}
if r := p.publishKept("a kept event"); r.Published != 2 || r.Waiting != 0 {
t.Fatalf("second round %+v", r)
}
if got := stream.publishes(); got != "laptop.sign-in-ended.1 laptop.sign-in-asked.2 laptop.sign-in-asked.2 laptop.sign-in-ended.3" {
t.Fatalf("published %s", got)
}
if kept, _ := f.pending(); len(kept) != 0 {
t.Fatalf("left %+v", kept)
}
}
// The bundle publishes at its start, at each file event on pending/ and when its bus connection comes back: the first
// heartbeat answered after a missed one; an older heartbeat arriving late changes nothing (§20, DMC-4).
func TestTheBundlePublishesAtEachMoment(t *testing.T) {
journalLines(t)
f := aFolder(t)
keepThree(t, f)
stream := &fakeStream{refuse: map[string]bool{"laptop.sign-in-ended.1": true}}
b := &bundle{folder: f, pub: &publisher{folder: f, publish: stream.publish}, names: &namer{folder: f, now: time.Now,
ask: func(string, any) (json.RawMessage, error) { return json.RawMessage(`{"seats":[]}`), nil }}}
files := make(chan struct{})
var hook func(stdio.Heartbeat)
done := make(chan struct{})
go func() {
b.start(bundleRuns{files: func(dirs []string, _ <-chan struct{}) <-chan struct{} {
if len(dirs) != 1 || !strings.HasSuffix(dirs[0], "/pending") {
t.Errorf("watched %v", dirs)
}
return files
}, fileMade: func(string, string, <-chan struct{}) <-chan struct{} { return nil },
onHeartbeat: func(h func(stdio.Heartbeat)) error { hook = h; return nil },
subscribe: func(string, func(stdio.Envelope) error) error { return nil }})
close(done)
}()
files <- struct{}{} // the start's round ran and was refused; this one publishes what waits
if _, err := f.keep(eventAsked, map[string]string{}); err != nil {
t.Fatal(err)
}
files <- struct{}{}
close(files)
<-done
if kept, _ := f.pending(); len(kept) != 0 {
t.Fatalf("a file event published nothing: %+v", kept)
}
keepThree(t, f)
at := time.Date(2026, 11, 24, 20, 0, 0, 0, time.UTC)
hook(stdio.Heartbeat{At: at})
if kept, _ := f.pending(); len(kept) != 3 {
t.Fatal("a heartbeat with none missed published")
}
hook(stdio.Heartbeat{At: at.Add(time.Second), Missed: true, Why: "no heartbeat"})
hook(stdio.Heartbeat{At: at.Add(-time.Second)})
if kept, _ := f.pending(); len(kept) != 3 {
t.Fatal("an older heartbeat arriving late was taken for the connection's return")
}
hook(stdio.Heartbeat{At: at.Add(2 * time.Second)})
if kept, _ := f.pending(); len(kept) != 0 {
t.Fatalf("the connection's return published nothing: %+v", kept)
}
if got := stream.publishes(); !strings.HasPrefix(got, "laptop.sign-in-ended.1 laptop.sign-in-ended.1 laptop.sign-in-asked.2") {
t.Fatalf("published %s", got)
}
}
// The bundle publishes a change the watcher kept with no node under its own: the subject `<event>.<node>`, the message
// id `<node>.<event>.<sequence>` and the body's node, the same at every publish of one file; a bundle that names no node
// publishes nothing and keeps the change (design 08 sign-in-page §20; lead answer L-3).
func TestTheBundleFillsItsNodeIntoAKeptChange(t *testing.T) {
journalLines(t)
watcher := Folder{Dir: t.TempDir()}
if _, err := watcher.keep(eventAsked, nodeuplink.SignInAsked{Link: "wlan0", Network: "guest-example",
Address: "http://check.example.net/", At: "2026-11-24T10:00:00Z"}); err != nil {
t.Fatal(err)
}
var said []string
publish := func(subject string, body json.RawMessage, id string) error {
said = append(said, subject+" "+id+" "+string(body))
return errors.New("no acknowledgement")
}
unnamed := &publisher{folder: watcher, publish: publish}
if r := unnamed.publishKept("a test"); r.Waiting != 1 || !strings.Contains(r.Refused, "no node named") || len(said) != 0 {
t.Fatalf("a bundle with no node: %+v, said %q", r, said)
}
p := &publisher{folder: Folder{Dir: watcher.Dir, Node: "laptop"}, publish: publish}
p.publishKept("a test")
p.publishKept("a test")
want := `mesh.seat.node-uplink.event.sign-in-asked.laptop laptop.sign-in-asked.1 ` +
`{"address":"http://check.example.net/","at":"2026-11-24T10:00:00Z","link":"wlan0","network":"guest-example","node":"laptop"}`
if len(said) != 2 || said[0] != want || said[1] != want {
t.Fatalf("published %q, want twice %s", said, want)
}
}
@@ -0,0 +1,209 @@
package main
// The person's graphical session (design 08 sign-in-page §16, §17): found over the system bus from logind, its
// session bus at the user's RuntimePath and its display in the user manager's environment; its start heard as
// logind's SessionNew, then waited for until the user manager's environment names a display. The user manager sends
// no PropertiesChanged for its Environment (EmitsChangedSignal false), so the environment is read again at each file
// event of the kernel on the X server's socket folder and on the session's RuntimePath, for at most 60 s (§17).
import (
"fmt"
"os"
"strings"
"time"
)
// sessionWait is the most the watcher waits, after a session started, for the user manager's environment to name a
// display (§17).
const sessionWait = 60 * time.Second
// x11Sockets is the folder an X server makes its socket in.
var x11Sockets = "/tmp/.X11-unix"
// loginSession is what logind says of one session: its id and object, its account, type, whether it is remote, its
// state, and its user's runtime directory.
type loginSession struct {
ID string
Path string
UID uint32
Type string
Remote bool
State string
RuntimePath string
}
// graphical says whether the session is one the person sits at: x11 or wayland, not remote, active or online.
func (s loginSession) graphical() bool {
return (s.Type == "x11" || s.Type == "wayland") && !s.Remote && (s.State == "active" || s.State == "online")
}
// Session is the person's graphical session as the watcher reaches it: its session bus, its runtime directory and the
// display its user manager's environment names.
type Session struct {
ID string
Type string
RuntimePath string
Display []string
}
// Bus is the session's bus address.
func (s Session) Bus() string { return "unix:path=" + s.RuntimePath + "/bus" }
// Env is the environment a program run in the session gets: the watcher's own, with the session's bus and runtime
// directory.
func (s Session) Env() []string {
var env []string
for _, kv := range os.Environ() {
if !strings.HasPrefix(kv, "DBUS_SESSION_BUS_ADDRESS=") && !strings.HasPrefix(kv, "XDG_RUNTIME_DIR=") {
env = append(env, kv)
}
}
return append(env, "DBUS_SESSION_BUS_ADDRESS="+s.Bus(), "XDG_RUNTIME_DIR="+s.RuntimePath)
}
// displayIn is the display an environment names for a session of its type: DISPLAY and XAUTHORITY for x11,
// WAYLAND_DISPLAY for wayland; none when it names none.
func displayIn(env []string, sessionType string) []string {
want := map[string]bool{"DISPLAY": sessionType == "x11", "XAUTHORITY": sessionType == "x11",
"WAYLAND_DISPLAY": sessionType == "wayland"}
var out []string
named := false
for _, kv := range env {
name, value, _ := strings.Cut(kv, "=")
if want[name] && value != "" {
out = append(out, kv)
named = named || name == "DISPLAY" || name == "WAYLAND_DISPLAY"
}
}
if !named {
return nil
}
return out
}
// findSession is the person's graphical session now, or nil: a session of the watcher's account that is graphical,
// whose user manager's environment names a display (§16).
func (w *Watcher) findSession() (*Session, error) {
if w.bus == nil {
return nil, fmt.Errorf("not subscribed on the system bus")
}
sessions, err := w.bus.sessions(w.UID)
if err != nil {
return nil, err
}
for _, s := range sessions {
if !s.graphical() {
continue
}
if found := w.sessionWithDisplay(s); found != nil {
return found, nil
}
}
return nil, nil
}
// sessionWithDisplay is s reached, when its user manager's environment names a display; else nil.
func (w *Watcher) sessionWithDisplay(s loginSession) *Session {
found := Session{ID: s.ID, Type: s.Type, RuntimePath: s.RuntimePath}
env, err := w.Environment(found.Bus())
if err != nil {
journal("reading the user manager's environment of session %s failed: %v", s.ID, err)
return nil
}
if found.Display = displayIn(env, s.Type); found.Display == nil {
return nil
}
return &found
}
// sessionStart is the session start being waited for: the session, until when, and the wait's file events.
type sessionStart struct {
session loginSession
files <-chan struct{}
bound <-chan time.Time
stop chan struct{}
}
// sessionNew acts on logind's SessionNew: for a graphical session of the watcher's account, it waits for the user
// manager's environment to name a display, reading it again at each file event (§17).
func (w *Watcher) sessionNew(path string) {
s, err := w.bus.session(path)
if err != nil {
journal("reading the new session %s failed: %v", path, err)
return
}
if s.UID != w.UID || (s.Type != "x11" && s.Type != "wayland") || s.Remote {
return
}
w.endSessionWait()
stop := make(chan struct{})
w.starting = &sessionStart{session: s, stop: stop, bound: w.After(sessionWait),
files: w.FileEvents([]string{x11Sockets, s.RuntimePath}, stop)}
journal("session %s (%s) started; waiting for its display", s.ID, s.Type)
}
// sessionFiles acts on a file event during the wait: the environment is read again, and once it names a display the
// session's start is acted on (§15's third moment).
func (w *Watcher) sessionFiles() {
if w.starting == nil {
return
}
found := w.sessionWithDisplay(w.starting.session)
if found == nil {
return
}
w.endSessionWait()
w.sessionStarted(*found)
}
// sessionBound ends a wait that found no display within its bound.
func (w *Watcher) sessionBound() {
if w.starting == nil {
return
}
journal("session %s's start was not acted on: its user manager's environment named no display within %s",
w.starting.session.ID, sessionWait)
w.noteSession("not acted on: no display named within " + sessionWait.String())
w.endSessionWait()
}
func (w *Watcher) endSessionWait() {
if w.starting != nil {
close(w.starting.stop)
w.starting = nil
}
}
// sessionStarted is §15's third moment: with the present rating PORTAL, the check on and a connection active, the page
// is opened and the person told; else nothing. It reads the present rating, never a kept event.
func (w *Watcher) sessionStarted(s Session) {
if w.bus == nil {
journal("session %s started while not subscribed on the system bus: nothing opened", s.ID)
w.noteSession("nothing: not subscribed on the system bus")
return
}
r, err := w.bus.rating()
if err != nil {
journal("session %s started; reading the rating failed: %v", s.ID, err)
w.noteSession("nothing: the rating did not read")
return
}
if !r.checkOn() || !webAddress(r.CheckURI) || r.Connectivity != ratingPortal || !r.active() {
journal("session %s started with the rating %s: nothing opened", s.ID, ratingName(r.Connectivity))
w.noteSession("nothing: the rating is " + ratingName(r.Connectivity))
return
}
journal("session %s started with the rating PORTAL: opening the sign-in page", s.ID)
w.noteSession("opened the sign-in page")
w.present(&s, r.Network, r.CheckURI)
}
func (w *Watcher) noteSession(did string) {
w.state.LastSession = &sessionNote{At: w.Now(), Did: did}
}
// sessionNote is the last session start and what the watcher did.
type sessionNote struct {
At time.Time `json:"at"`
Did string `json:"did"`
}
@@ -0,0 +1,124 @@
package main
import (
"strings"
"testing"
"time"
)
// The person's session as logind says it: x11, local, active, of the watcher's account.
func personsSession() loginSession {
return loginSession{ID: "2", Path: "/org/freedesktop/login1/session/_32", UID: 1000, Type: "x11", State: "active",
RuntimePath: "/run/user/1000"}
}
// aSessionWatcher is a subscribed watcher whose stood-in user manager names a display once named is set; the test acts
// as its loop, calling what a file event and the bound's end call.
func aSessionWatcher(t *testing.T, sys *fakeSystem, named *bool) *Watcher {
t.Helper()
w := aWatcher(t, sys)
files, bound := make(chan struct{}, 1), make(chan time.Time, 1)
w.FileEvents = func(dirs []string, stop <-chan struct{}) <-chan struct{} {
if strings.Join(dirs, " ") != "/tmp/.X11-unix /run/user/1000" {
t.Errorf("the session's start is waited for on %v", dirs)
}
return files
}
w.After = func(d time.Duration) <-chan time.Time {
if d != 60*time.Second {
t.Errorf("the session's start is waited for %s", d)
}
return bound
}
w.Environment = func(bus string) ([]string, error) {
if bus != "unix:path=/run/user/1000/bus" {
t.Errorf("the environment is read over %s", bus)
}
if *named {
return []string{"HOME=/home/person", "DISPLAY=:1", "XAUTHORITY=/home/person/.Xauthority"}, nil
}
return []string{"HOME=/home/person"}, nil
}
w.subscribe()
return w
}
// A session that starts while the rating is PORTAL opens the page once, when the user manager's environment names its
// display; one that starts while it is not opens nothing; one whose display is not named within the bound is not acted
// on, and says so (design 08 sign-in-page §15, §16, §17, §25).
func TestASessionStartingWhilePortalOpensThePageOnce(t *testing.T) {
for _, c := range []struct {
name string
rating Rating
named bool
opens int
did string
}{
{"PORTAL", guest(ratingPortal), true, 1, "opened the sign-in page"},
{"FULL", guest(ratingFull), true, 0, "nothing: the rating is FULL"},
{"no display named", guest(ratingPortal), false, 0, "not acted on: no display named within 1m0s"},
} {
t.Run(c.name, func(t *testing.T) {
lines := journalLines(t)
sys := &fakeSystem{}
sys.set(guest(ratingFull))
named := false
w := aSessionWatcher(t, sys, &named)
desk := w.Desk.(*fakeDesk)
sys.sessions = []loginSession{personsSession(), {ID: "9", Path: "/org/freedesktop/login1/session/_39", UID: 1001,
Type: "x11", State: "active", RuntimePath: "/run/user/1001"}}
w.heardSignal(signal{Session: "/org/freedesktop/login1/session/_39"})
if w.starting != nil {
t.Fatal("another account's session is waited for")
}
sys.set(c.rating)
w.heardSignal(signal{Session: personsSession().Path})
w.sessionFiles()
if len(desk.opened()) != 0 || w.starting == nil {
t.Fatal("acted on a session whose display is not named yet")
}
named = c.named
w.sessionFiles()
if w.starting != nil {
w.sessionBound()
}
if got := desk.opened(); len(got) != c.opens || (c.opens == 1 && got[0] != "2 http://check.example.net/") {
t.Fatalf("opened %q", got)
}
if w.state.LastSession == nil || w.state.LastSession.Did != c.did {
t.Fatalf("the session's start is said as %+v", w.state.LastSession)
}
if c.named == false && !strings.Contains(strings.Join(lines(), "\n"), "start was not acted on") {
t.Fatal("a start not acted on was not written to the journal")
}
})
}
}
// With no graphical session found the watcher opens nothing and still keeps the events: a remote session, one in no
// graphical type and one whose environment names no display are no session (§15, §16, §25).
func TestNoSessionOpensNothingAndStillKeeps(t *testing.T) {
journalLines(t)
sys := &fakeSystem{}
named := false
w := aSessionWatcher(t, sys, &named)
remote, tty := personsSession(), personsSession()
remote.Remote, tty.Type = true, "tty"
sys.sessions = []loginSession{remote, tty, personsSession()}
w.heard(guest(ratingFull), false)
w.heard(guest(ratingPortal), false)
w.present(nil, "guest-example", "http://check.example.net/")
if got := w.Desk.(*fakeDesk).opened(); len(got) != 0 {
t.Fatalf("opened %q with no session", got)
}
if kept := keptSaid(t, w.Folder); len(kept) == 0 || kept[len(kept)-1] != "sign-in-asked guest-example wlan0" {
t.Fatalf("kept %q", kept)
}
named = true
if s, err := w.findSession(); err != nil || s == nil || s.ID != "2" || strings.Join(s.Display, " ") != "DISPLAY=:1 XAUTHORITY=/home/person/.Xauthority" {
t.Fatalf("found %+v %v", s, err)
}
if got := displayIn([]string{"WAYLAND_DISPLAY=wayland-0", "DISPLAY=:0"}, "wayland"); strings.Join(got, " ") != "WAYLAND_DISPLAY=wayland-0" {
t.Fatalf("a wayland session's display is %v", got)
}
}
@@ -0,0 +1,340 @@
package main
// The module's own local state, the one folder its two parts share (design 08 sign-in-page §12): the watcher's socket,
// the network manager's check address, the kept events in pending/, the bundle's last uplink-names call and the next
// sequence of the watcher's message ids. Every file is written whole: beside, then renamed over. Nothing else reads or
// writes the folder.
import (
"bufio"
"encoding/json"
"errors"
"fmt"
"io"
"net"
"os"
"path/filepath"
"sort"
"strconv"
"strings"
"time"
)
// stateHome is the folder under the account's home, as the manifest declares it: owner the account, mode 0700.
const stateHome = ".local/state/mesh/networkmanager"
// The folder's names.
const (
socketName = "watch.sock"
checkName = "check-address"
pendingName = "pending"
namesName = "names.json"
sequenceName = "sequence"
)
// The watcher's socket's asks.
const (
askState = "state"
askRatingAgain = "rating-again"
)
// socketBound is how long one ask on the watcher's socket may take, a stated constant (design 08 sign-in-page §12;
// lead answer C-8): a bundle's ask past it counts as no answer, and the watcher drops a line not asked within it.
const socketBound = 5 * time.Second
// journal writes one line to the part's journal: its standard error, which the service manager keeps.
var journal = func(format string, args ...any) {
fmt.Fprintf(os.Stderr, "[networkmanager] "+format+"\n", args...)
}
// Folder is the module's own local state, at Dir, on the node named Node.
type Folder struct {
Dir string
Node string
}
// theFolder is the account's folder, on the node the tool runner names the bundle (MESH_NODE).
func theFolder() (Folder, error) {
f, err := accountFolder()
f.Node = os.Getenv("MESH_NODE")
return f, err
}
// accountFolder is the account's folder with no node: the watcher's, which names none (L-3).
func accountFolder() (Folder, error) {
home, err := os.UserHomeDir()
if err != nil {
return Folder{}, err
}
return Folder{Dir: filepath.Join(home, stateHome)}, nil
}
func (f Folder) path(name string) string { return filepath.Join(f.Dir, name) }
// writeWhole writes data to path whole: into a file beside it, synced, then renamed over it, so a reader sees the old
// text or the new, never a part.
func writeWhole(path string, data []byte, mode os.FileMode) error {
beside := path + ".new"
out, err := os.OpenFile(beside, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, mode)
if err != nil {
return err
}
_, err = out.Write(data)
if err == nil {
err = out.Sync()
}
if cerr := out.Close(); err == nil {
err = cerr
}
if err == nil {
err = os.Rename(beside, path)
}
if err != nil {
os.Remove(beside)
return fmt.Errorf("writing %s: %w", path, err)
}
return nil
}
// nextSequence is the next sequence of the watcher's message ids and kept files, written whole as one more before it is
// used, so no id is used twice while the folder lives, a restart included (R3-1).
func (f Folder) nextSequence() (uint64, error) {
n := uint64(1)
raw, err := os.ReadFile(f.path(sequenceName))
switch {
case err == nil:
if n, err = strconv.ParseUint(strings.TrimSpace(string(raw)), 10, 64); err != nil || n == 0 {
return 0, fmt.Errorf("%s holds no sequence: %q", f.path(sequenceName), raw)
}
case !errors.Is(err, os.ErrNotExist):
return 0, err
}
if err := writeWhole(f.path(sequenceName), []byte(strconv.FormatUint(n+1, 10)+"\n"), 0o600); err != nil {
return 0, err
}
return n, nil
}
// Kept is one change the watcher kept for the bundle to publish: the event's name, its sequence and its body, all
// without the node. The watcher names no node; the bundle fills its own into the subject, the message id and the body's
// node when it publishes (lead answer L-3).
type Kept struct {
Sequence uint64 `json:"sequence"`
Event string `json:"event"`
Body json.RawMessage `json:"body"`
}
// Name is the kept change as the journal names it: `<event>.<sequence>`.
func (k Kept) Name() string { return fmt.Sprintf("%s.%d", k.Event, k.Sequence) }
func pendingFile(seq uint64) string { return fmt.Sprintf("%010d.json", seq) }
// keep writes one change into pending/ under the next sequence, made once (§20; L-3).
func (f Folder) keep(event string, body any) (Kept, error) {
raw, err := json.Marshal(body)
if err != nil {
return Kept{}, err
}
if err := os.MkdirAll(f.path(pendingName), 0o700); err != nil {
return Kept{}, err
}
seq, err := f.nextSequence()
if err != nil {
return Kept{}, err
}
k := Kept{Sequence: seq, Event: event, Body: raw}
data, err := json.Marshal(k)
if err != nil {
return Kept{}, err
}
return k, writeWhole(filepath.Join(f.path(pendingName), pendingFile(seq)), append(data, '\n'), 0o600)
}
// pending is every kept event, in sequence order. A file that is not a kept event (a write beside one) is skipped; one
// that does not read is an error naming it.
func (f Folder) pending() ([]Kept, error) {
entries, err := os.ReadDir(f.path(pendingName))
if errors.Is(err, os.ErrNotExist) {
return nil, nil
}
if err != nil {
return nil, err
}
var out []Kept
for _, e := range entries {
name, ok := strings.CutSuffix(e.Name(), ".json")
if !ok || e.IsDir() {
continue
}
seq, err := strconv.ParseUint(name, 10, 64)
if err != nil {
continue
}
raw, err := os.ReadFile(filepath.Join(f.path(pendingName), e.Name()))
if errors.Is(err, os.ErrNotExist) {
continue
}
if err != nil {
return nil, err
}
var k Kept
if err := json.Unmarshal(raw, &k); err != nil {
return nil, fmt.Errorf("the kept event %s does not read: %w", e.Name(), err)
}
k.Sequence = seq
out = append(out, k)
}
sort.Slice(out, func(i, j int) bool { return out[i].Sequence < out[j].Sequence })
return out, nil
}
// drop deletes one kept event; one already gone is no error.
func (f Folder) drop(k Kept) error {
err := os.Remove(filepath.Join(f.path(pendingName), pendingFile(k.Sequence)))
if errors.Is(err, os.ErrNotExist) {
return nil
}
return err
}
// writeCheckAddress writes the network manager's check address on one line, empty when there is none.
func (f Folder) writeCheckAddress(address string) error {
return writeWhole(f.path(checkName), []byte(address+"\n"), 0o600)
}
// checkAddress is the check address the watcher wrote; empty when it wrote none or none is set.
func (f Folder) checkAddress() (string, error) {
raw, err := os.ReadFile(f.path(checkName))
if errors.Is(err, os.ErrNotExist) {
return "", nil
}
return strings.TrimSpace(string(raw)), err
}
// The results of an uplink-names call besides a failure's text.
const (
resultOK = "ok"
resultNoHolder = "no holder"
)
// NamesCall is the bundle's last uplink-names call: the names given, its result (ok, no holder or the failure) and
// when.
type NamesCall struct {
Names []string `json:"names"`
Result string `json:"result"`
At time.Time `json:"at"`
}
// Failed says whether the call stands failed: no holder is not a failure.
func (c NamesCall) Failed() bool {
return c.Result != "" && c.Result != resultOK && c.Result != resultNoHolder
}
func (f Folder) writeNames(c NamesCall) error {
if c.Names == nil {
c.Names = []string{}
}
data, err := json.Marshal(c)
if err != nil {
return err
}
return writeWhole(f.path(namesName), append(data, '\n'), 0o600)
}
// names is the last uplink-names call, nil when none was written.
func (f Folder) names() (*NamesCall, error) {
raw, err := os.ReadFile(f.path(namesName))
if errors.Is(err, os.ErrNotExist) {
return nil, nil
}
if err != nil {
return nil, err
}
var c NamesCall
return &c, json.Unmarshal(raw, &c)
}
// socketAsk is the one line asked on the watcher's socket, socketAnswer the one answered.
type socketAsk struct {
Ask string `json:"ask"`
}
type socketAnswer struct {
Answer json.RawMessage `json:"answer,omitempty"`
Error string `json:"error,omitempty"`
}
// listen makes the watcher's socket, mode 0600, in place of one a stopped watcher left.
func (f Folder) listen() (net.Listener, error) {
path := f.path(socketName)
if err := os.Remove(path); err != nil && !errors.Is(err, os.ErrNotExist) {
return nil, err
}
l, err := net.Listen("unix", path)
if err != nil {
return nil, err
}
if err := os.Chmod(path, 0o600); err != nil {
l.Close()
return nil, err
}
return l, nil
}
// serveSocket answers each connection's one asked line with handle's answer, until l is closed.
func serveSocket(l net.Listener, handle func(ask string) (any, error)) {
for {
conn, err := l.Accept()
if err != nil {
return
}
go func() {
defer conn.Close()
conn.SetDeadline(time.Now().Add(socketBound))
line, err := bufio.NewReader(io.LimitReader(conn, 4096)).ReadBytes('\n')
if err != nil && len(line) == 0 {
return
}
var ask socketAsk
var out socketAnswer
if err := json.Unmarshal(line, &ask); err != nil {
out.Error = "the line asked is no JSON: " + err.Error()
} else if answer, err := handle(ask.Ask); err != nil {
out.Error = err.Error()
} else if out.Answer, err = json.Marshal(answer); err != nil {
out.Error = err.Error()
}
data, _ := json.Marshal(out)
conn.Write(append(data, '\n'))
}()
}
}
// askWatcher asks the watcher one ask on its socket and reads its answer into into (nil to drop it).
func (f Folder) askWatcher(ask string, into any) error {
conn, err := net.DialTimeout("unix", f.path(socketName), socketBound)
if err != nil {
return fmt.Errorf("the watcher's socket does not answer: %w", err)
}
defer conn.Close()
conn.SetDeadline(time.Now().Add(socketBound))
data, _ := json.Marshal(socketAsk{Ask: ask})
if _, err := conn.Write(append(data, '\n')); err != nil {
return fmt.Errorf("the watcher's socket does not answer: %w", err)
}
line, err := bufio.NewReader(conn).ReadBytes('\n')
if err != nil {
return fmt.Errorf("the watcher's socket does not answer: %w", err)
}
var out socketAnswer
if err := json.Unmarshal(line, &out); err != nil {
return fmt.Errorf("the watcher answered no JSON: %w", err)
}
if out.Error != "" {
return fmt.Errorf("the watcher refused %s: %s", ask, out.Error)
}
if into == nil || len(out.Answer) == 0 {
return nil
}
return json.Unmarshal(out.Answer, into)
}
@@ -0,0 +1,191 @@
package main
import (
"errors"
"os"
"path/filepath"
"strings"
"testing"
"time"
)
func aFolder(t *testing.T) Folder {
t.Helper()
return Folder{Dir: t.TempDir(), Node: "laptop"}
}
// A watcher restarted after its events were published and pending/ emptied makes message ids it never used, so the
// bus keeps them rather than dropping them as duplicates (design 08 sign-in-page §12, §25; R3-1). The watcher's folder
// names no node, and a kept change holds its event, its sequence and its body (L-3).
func TestARestartedWatcherMakesIdsItNeverUsed(t *testing.T) {
f := Folder{Dir: t.TempDir()}
used := map[uint64]bool{}
for range 3 {
k, err := f.keep("sign-in-asked", map[string]string{"link": "wlan0"})
if err != nil {
t.Fatal(err)
}
used[k.Sequence] = true
}
kept, err := f.pending()
if err != nil || len(kept) != 3 || kept[0].Name() != "sign-in-asked.1" || kept[2].Sequence != 3 {
t.Fatalf("kept %+v %v", kept, err)
}
for _, k := range kept {
if err := f.drop(k); err != nil {
t.Fatal(err)
}
}
restarted := Folder{Dir: f.Dir}
k, err := restarted.keep("sign-in-ended", map[string]string{})
if err != nil || used[k.Sequence] || k.Name() != "sign-in-ended.4" {
t.Fatalf("the restarted watcher made %q (%v), having used %v", k.Name(), err, used)
}
raw, _ := os.ReadFile(filepath.Join(f.Dir, pendingName, "0000000004.json"))
if string(raw) != `{"sequence":4,"event":"sign-in-ended","body":{}}`+"\n" {
t.Fatalf("the kept file holds %s", raw)
}
if _, err := os.Stat(filepath.Join(f.Dir, pendingName, "0000000004.json")); err != nil {
t.Fatalf("the kept file is not named by its ten-digit sequence: %v", err)
}
}
// Every file of the folder is written whole, beside and renamed over: a write that fails leaves the old text and no
// part of the new, and a file being written beside a kept event is not read as one (§12).
func TestTheFoldersFilesAreWrittenWhole(t *testing.T) {
f := aFolder(t)
if err := f.writeCheckAddress("http://check.example.net/"); err != nil {
t.Fatal(err)
}
if err := os.Mkdir(f.path(checkName)+".new", 0o700); err != nil {
t.Fatal(err)
}
if err := f.writeCheckAddress("http://other.example.net/"); err == nil {
t.Fatal("a write that could not be made beside was taken")
}
if got, _ := f.checkAddress(); got != "http://check.example.net/" {
t.Fatalf("a failed write left %q", got)
}
os.Remove(f.path(checkName) + ".new")
if err := f.writeNames(NamesCall{Result: resultNoHolder}); err != nil {
t.Fatal(err)
}
if c, err := f.names(); err != nil || c.Result != resultNoHolder || c.Names == nil || c.Failed() {
t.Fatalf("names read %+v %v", c, err)
}
if _, err := f.keep("sign-in-asked", map[string]string{}); err != nil {
t.Fatal(err)
}
os.WriteFile(filepath.Join(f.Dir, pendingName, "0000000009.json.new"), []byte("{"), 0o600)
entries, _ := os.ReadDir(f.Dir)
for _, e := range entries {
if strings.HasSuffix(e.Name(), ".new") {
t.Errorf("%s was left beside", e.Name())
}
}
if kept, err := f.pending(); err != nil || len(kept) != 1 {
t.Fatalf("pending read %+v %v", kept, err)
}
if raw, _ := os.ReadFile(f.path(sequenceName)); string(raw) != "2\n" {
t.Fatalf("the sequence file holds %q", raw)
}
}
// The watcher's socket answers one JSON line asked with one line, its refusal named (§12).
func TestTheWatchersSocketAnswersOneLine(t *testing.T) {
f := aFolder(t)
l, err := f.listen()
if err != nil {
t.Fatal(err)
}
defer l.Close()
go serveSocket(l, func(ask string) (any, error) {
if ask == askState {
return map[string]bool{"subscribed": true}, nil
}
return nil, errors.New("no such ask")
})
if fi, err := os.Stat(f.path(socketName)); err != nil || fi.Mode().Perm() != 0o600 {
t.Fatalf("the socket is %v %v", fi, err)
}
var state struct{ Subscribed bool }
if err := f.askWatcher(askState, &state); err != nil || !state.Subscribed {
t.Fatalf("state answered %+v %v", state, err)
}
if err := f.askWatcher("other", nil); err == nil || !strings.Contains(err.Error(), "no such ask") {
t.Fatalf("a refusal answered %v", err)
}
l.Close()
if err := f.askWatcher(askState, nil); err == nil {
t.Fatal("a closed socket answered")
}
}
// A path in the folder the watcher does not know is left as it is and written to its journal once per path: what is
// there at its start, and what a file event makes after (§12; lead answer L-1).
func TestAPathTheWatcherDoesNotKnowIsLeftAndSaidOnce(t *testing.T) {
lines := journalLines(t)
sys := &fakeSystem{}
sys.set(guest(ratingFull))
w := aWatcher(t, sys)
f := w.Folder
if _, err := f.keep(eventEnded, map[string]string{}); err != nil {
t.Fatal(err)
}
f.writeCheckAddress("http://check.example.net/")
for _, p := range []string{filepath.Join(f.Dir, "notes.txt"), filepath.Join(f.Dir, pendingName, "stray")} {
if err := os.WriteFile(p, []byte("x"), 0o600); err != nil {
t.Fatal(err)
}
}
made := make(chan string)
w.Made = func(dirs []string, stop <-chan struct{}) <-chan string {
if len(dirs) != 2 || dirs[0] != f.Dir || dirs[1] != filepath.Join(f.Dir, pendingName) {
t.Errorf("watched %v", dirs)
}
return made
}
stop, done := make(chan struct{}), make(chan struct{})
go func() { _ = w.run(stop); close(done) }()
for _, p := range []string{filepath.Join(f.Dir, "other"), filepath.Join(f.Dir, "other"), filepath.Join(f.Dir, "sequence.new"),
filepath.Join(f.Dir, pendingName, "0000000002.json")} {
made <- p
}
w.askLoop(askState)
close(stop)
<-done
var said []string
for _, l := range lines() {
if strings.Contains(l, "is not the module's") {
said = append(said, strings.TrimPrefix(l, f.Dir+"/"))
}
}
want := []string{"notes.txt is not the module's: left as it is", "pending/stray is not the module's: left as it is",
"other is not the module's: left as it is"}
if strings.Join(said, "|") != strings.Join(want, "|") {
t.Fatalf("said %q", said)
}
if _, err := os.Stat(filepath.Join(f.Dir, "notes.txt")); err != nil {
t.Fatal("a path the watcher does not know was not left")
}
}
// The bounds the design states, each a constant and none a setting: the socket's 5 s, the open's 10 s, the session
// start's 60 s and the 256 kept events (design 08 sign-in-page §12, §17, §18, §20; R2-7, C-8).
func TestTheStatedBounds(t *testing.T) {
if socketBound != 5*time.Second || openBound != 10*time.Second || sessionWait != 60*time.Second || keptBound != 256 {
t.Fatalf("the bounds are %s, %s, %s and %d", socketBound, openBound, sessionWait, keptBound)
}
}
// The watcher reads no MESH_NODE: its folder names no node, whatever the environment says (L-3).
func TestTheWatchersFolderNamesNoNode(t *testing.T) {
t.Setenv("MESH_NODE", "laptop")
t.Setenv("HOME", t.TempDir())
if f, err := accountFolder(); err != nil || f.Node != "" {
t.Fatalf("the watcher's folder is %+v (%v)", f, err)
}
if f, err := theFolder(); err != nil || f.Node != "laptop" {
t.Fatalf("the bundle's folder is %+v (%v)", f, err)
}
}
@@ -4,6 +4,7 @@ import (
"encoding/json"
"os"
"path/filepath"
"strings"
"testing"
)
@@ -62,3 +63,67 @@ func TestEveryFileTakesItsTextFromATemplate(t *testing.T) {
t.Errorf("the build packs files/ into %d archives, not one", packs)
}
}
// The manifest declares the watcher's process as the account, its health its unit's state; the folder the two parts
// share, the account's alone; the event the bundle consumes and the verbs it invokes; and the five tools. NetworkManager's
// unit keeps no state and no health (design 08 sign-in-page §11, §12, §13, §27; lead answer C-2c).
func TestTheManifestDeclaresTheSignInParts(t *testing.T) {
raw, err := os.ReadFile(filepath.Join(moduleDir, "module.json"))
if err != nil {
t.Fatal(err)
}
var m struct {
Consumes []string `json:"consumes"`
Invokes []string `json:"invokes"`
Tools []string `json:"tools"`
Claims []map[string]any `json:"claims"`
Resources []map[string]any `json:"resources"`
}
if err := json.Unmarshal(raw, &m); err != nil {
t.Fatal(err)
}
same := func(got []string, want ...string) bool {
return strings.Join(got, " ") == strings.Join(want, " ")
}
if !same(m.Consumes, "node-engine.running") {
t.Errorf("consumes %v", m.Consumes)
}
if !same(m.Invokes, "seat:mesh-module-assigner.assignments", "seat:node-resolver.uplink-names", "seat:node-resolver.routes") {
t.Errorf("invokes %v", m.Invokes)
}
var served []string
for _, tool := range (&bundle{}).tools() {
served = append(served, tool.Name)
}
if !same(m.Tools, served...) {
t.Errorf("lists the tools %v, serves %v", m.Tools, served)
}
if len(m.Claims) != 1 || m.Claims[0]["name"] != "node-uplink" {
t.Errorf("claims %v", m.Claims)
}
byID := map[string]map[string]any{}
for _, r := range m.Resources {
byID[r["id"].(string)] = r
}
dir := byID["sign-in-state"]
if dir["type"] != "directory" || dir["path"] != "${machine:account-home}/"+stateHome ||
dir["owner"] != "${machine:account}" || dir["mode"] != "0700" || dir["unknown"] != "module" {
t.Errorf("the folder is %v", dir)
}
p := byID["sign-in"]
run, _ := json.Marshal(p["run"])
h, _ := json.Marshal(p["health"])
if p["type"] != "process" || p["name"] != "networkmanager-sign-in" || p["artifact"] != "tools" ||
string(run) != `["./uplink-tools","watch"]` || p["user"] != "${machine:account}" ||
string(h) != `{"kind":"unit"}` {
t.Errorf("the watcher is %v", p)
}
if byID["service"]["health"] != nil || byID["service"]["state"] != nil {
t.Errorf("NetworkManager's unit carries a state or a health: %v", byID["service"])
}
for _, id := range []string{"package", "config", "service"} {
if byID[id] == nil {
t.Errorf("the resource %s is gone", id)
}
}
}
@@ -0,0 +1,126 @@
package main
// networkmanager's own tools, served by the bundle (design 08 sign-in-page §23): the read of the sign-in reaction, the
// three acts that start by hand what the two parts do by themselves, and the health tool of the watcher's process.
import (
"fmt"
"strings"
"git.novox.be/novox/mesh-networking/modules/mesh-connectivity-contracts/go/seats/noderesolver"
stdio "git.novox.be/novox/mesh-sdk/go"
"git.novox.be/novox/mesh-sdk/go/health"
)
// signInRead is uplink_sign_in's answer.
type signInRead struct {
Watcher *watcherState `json:"watcher,omitempty"`
WatcherError string `json:"watcher_error,omitempty"`
Waiting int `json:"waiting"`
RefusedSince int `json:"publishes_refused_since_start"`
Names *NamesCall `json:"names,omitempty"`
ResolverRefused *string `json:"resolver_refused,omitempty"`
ResolverError string `json:"resolver_error,omitempty"`
}
func (b *bundle) tools() []stdio.Tool {
return []stdio.Tool{
{Name: "uplink_sign_in",
Description: "The network's sign-in page as this machine reacts to it: whether the watcher hears the network " +
"manager, the last rating it heard and when, the sign-in asked now (network, link, since), the asks opened " +
"and ended since its start, the last page opened with its outcome, the last notification, the last session " +
"start and what it did, the kept events dropped past the bound of 256, the events waiting to be published " +
"and the publishes refused since the bundle's start, the last uplink-names call with its result, and the " +
"resolver's refusal of the names where a holder of node-resolver runs here. (r)",
Run: func(map[string]any) (any, error) { return b.signIn(), nil }},
{Name: "uplink_names_again",
Description: "Give this machine's resolver the network manager's check host now, as the bundle does at its " +
"moments: calls node-resolver's uplink-names on this node and answers the call as names.json keeps it. (a)",
Run: func(map[string]any) (any, error) { return b.names.give("uplink_names_again"), nil }},
{Name: "uplink_rating_again",
Description: "Make the watcher subscribe on the system bus again, read the network manager's rating now and " +
"act on it as on a change; answers the watcher's state after it. (a)",
Run: func(map[string]any) (any, error) {
var s watcherState
if err := b.folder.askWatcher(askRatingAgain, &s); err != nil {
return nil, err
}
return s, nil
}},
{Name: "uplink_publish_again",
Description: "Publish the kept sign-in events now, in order under their own message ids, as the bundle does at " +
"its moments: answers how many were published and how many still wait. (a)",
Run: func(map[string]any) (any, error) { return b.pub.publishKept("uplink_publish_again"), nil }},
{Name: "uplink_health",
Description: "Whether the sign-in reaction works: unhealthy while the watcher's socket does not answer, while " +
"the watcher is not subscribed on the system bus, or while the last uplink-names call stands failed, naming " +
"which; no holder of node-resolver is healthy. A tool to read, not the watcher's health check, which is its " +
"unit's state. (r)",
Run: func(map[string]any) (any, error) { return b.health(), nil }},
}
}
// signIn reads the watcher's state, the folder and, where a holder of node-resolver runs here, the resolver's refusal.
func (b *bundle) signIn() signInRead {
var out signInRead
var s watcherState
if err := b.folder.askWatcher(askState, &s); err != nil {
out.WatcherError = err.Error()
} else {
out.Watcher = &s
}
if kept, err := b.folder.pending(); err == nil {
out.Waiting = len(kept)
}
out.RefusedSince = b.pub.refusedSince()
out.Names, _ = b.folder.names()
routes, held, err := b.resolverRoutes()
switch {
case err != nil:
out.ResolverError = err.Error()
case held:
out.ResolverRefused = &routes.UplinkNames.Refused
}
return out
}
// resolverRoutes is node-resolver's routes on this node, held false when no module holds the seat here.
func (b *bundle) resolverRoutes() (noderesolver.RoutesAnswer, bool, error) {
holder, err := b.names.resolverHolder()
if err != nil || holder == "" {
return noderesolver.RoutesAnswer{}, false, err
}
raw, err := b.names.ask("seat:"+noderesolver.Seat+"."+noderesolver.VerbRoutes+"@"+b.folder.Node, struct{}{})
if err != nil {
return noderesolver.RoutesAnswer{}, true, fmt.Errorf("%s/%s.%s: %w", b.folder.Node, noderesolver.Seat,
noderesolver.VerbRoutes, err)
}
routes, _, err := noderesolver.DecodeRoutesAnswer(raw)
return routes, true, err
}
// health is uplink_health's answer, a tool of the bundle and not a node-engine check (§23; lead answer C-2c).
func (b *bundle) health() health.Answer {
var faults []string
var s watcherState
if err := b.folder.askWatcher(askState, &s); err != nil {
faults = append(faults, err.Error())
} else if !s.Subscribed {
faults = append(faults, "the watcher is not subscribed on the system bus")
}
call, err := b.folder.names()
if err != nil {
faults = append(faults, "names.json does not read: "+err.Error())
}
if call != nil && call.Failed() {
faults = append(faults, "the last uplink-names call failed: "+call.Result)
}
if len(faults) > 0 {
return health.Unhealthy(strings.Join(faults, "; ") + ".")
}
why := "the watcher hears the network manager"
if call != nil {
why += "; the last uplink-names call: " + call.Result
}
return health.Healthy(why + ".")
}
@@ -0,0 +1,141 @@
package main
import (
"encoding/json"
"errors"
"strings"
"testing"
"time"
"git.novox.be/novox/mesh-sdk/go/health"
)
// aToolBundle is a bundle over the stood-in mesh and stream, with a watcher's socket answering state as subscribed
// says, and recording the asks it was given.
func aToolBundle(t *testing.T, mesh *fakeMesh, subscribed *bool, asked *[]string) (*bundle, *fakeStream) {
t.Helper()
f := aFolder(t)
stream := &fakeStream{refuse: map[string]bool{}}
b := &bundle{folder: f, pub: &publisher{folder: f, publish: stream.publish},
names: &namer{folder: f, ask: mesh.ask, now: time.Now}}
if subscribed == nil {
return b, stream
}
l, err := f.listen()
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { l.Close() })
go serveSocket(l, func(ask string) (any, error) {
*asked = append(*asked, ask)
return watcherState{Subscribed: *subscribed, Rating: "PORTAL", AsksOpened: 1, DroppedPastBound: 2}, nil
})
return b, stream
}
func runTool(t *testing.T, b *bundle, name string) any {
t.Helper()
for _, tool := range b.tools() {
if tool.Name == name {
out, err := tool.Run(map[string]any{})
if err != nil {
t.Fatalf("%s: %v", name, err)
}
return out
}
}
t.Fatalf("no tool %s", name)
return nil
}
// The health tool is unhealthy while the watcher's socket does not answer, while the watcher is not subscribed and
// while the last uplink-names call stands failed, naming which; no holder is healthy. It is a tool that reads and calls
// nothing on the bus: the names are not given again at a look (design 08 sign-in-page §13, §23, §25; C-2c).
func TestTheHealthToolSaysWhatIsWrong(t *testing.T) {
journalLines(t)
for _, c := range []struct {
name string
socket bool
subscribed bool
holder string
fail bool
healthy bool
why string
}{
{"no socket", false, false, "", false, false, "the watcher's socket does not answer"},
{"not subscribed", true, false, "", false, false, "the watcher is not subscribed on the system bus"},
{"a failed call", true, true, "systemd-resolved", true, false, "the last uplink-names call failed"},
{"no holder", true, true, "", false, true, "no holder"},
{"given", true, true, "systemd-resolved", false, true, "ok"},
} {
t.Run(c.name, func(t *testing.T) {
mesh := &fakeMesh{holder: c.holder,
routes: `{"links":[],"mesh":{"domains":[],"servers":[]},"mesh_resolvers":{"silent":false},"uplink_names":{"names":["check.example.net"],"link":"wlan0","refused":""}}`}
var asked []string
subscribed := c.subscribed
var b *bundle
if c.socket {
b, _ = aToolBundle(t, mesh, &subscribed, &asked)
} else {
b, _ = aToolBundle(t, mesh, nil, nil)
}
b.folder.writeCheckAddress("http://check.example.net/")
if c.fail {
mesh.fail = errors.New("no answer within its bound")
}
b.names.give("the bundle's start")
mesh.fail = nil
got := runTool(t, b, "uplink_health").(health.Answer)
if got.Healthy != c.healthy || !strings.Contains(got.Why, c.why) {
t.Fatalf("answered %+v", got)
}
})
}
mesh := &fakeMesh{holder: "systemd-resolved",
routes: `{"uplink_names":{"names":[],"link":"","refused":"resolved refused the domains"}}`}
subscribed, asked := true, []string{}
b, _ := aToolBundle(t, mesh, &subscribed, &asked)
b.folder.writeCheckAddress("http://check.example.net/")
b.names.give("the bundle's start")
if got := runTool(t, b, "uplink_health").(health.Answer); !got.Healthy || len(mesh.called()) != 1 {
t.Fatalf("the health tool answered %+v and called uplink-names %d times", got, len(mesh.called()))
}
}
// Each tool answers: the read of the sign-in reaction, the names given again, the watcher asked rating-again, and the
// kept events published again (§23, §25; R3-5).
func TestEachToolAnswers(t *testing.T) {
journalLines(t)
mesh := &fakeMesh{holder: "systemd-resolved",
routes: `{"uplink_names":{"names":["check.example.net"],"link":"wlan0","refused":"resolved refused the domains"}}`}
subscribed, asked := true, []string{}
b, stream := aToolBundle(t, mesh, &subscribed, &asked)
b.folder.writeCheckAddress("http://check.example.net/")
keepThree(t, b.folder)
stream.refuse["laptop.sign-in-ended.1"] = true
b.pub.publishKept("the bundle's start")
read := runTool(t, b, "uplink_sign_in").(signInRead)
raw, _ := json.Marshal(read)
if read.Watcher == nil || read.Watcher.Rating != "PORTAL" || read.Watcher.DroppedPastBound != 2 || read.Waiting != 3 ||
read.RefusedSince != 1 || read.Names != nil || read.ResolverRefused == nil ||
*read.ResolverRefused != "resolved refused the domains" {
t.Fatalf("uplink_sign_in answered %s", raw)
}
if c := runTool(t, b, "uplink_names_again").(NamesCall); c.Result != resultOK || len(mesh.called()) != 1 {
t.Fatalf("uplink_names_again answered %+v", c)
}
if s := runTool(t, b, "uplink_rating_again").(watcherState); !s.Subscribed || asked[len(asked)-1] != askRatingAgain {
t.Fatalf("uplink_rating_again answered %+v, asked %v", s, asked)
}
if r := runTool(t, b, "uplink_publish_again").(publishResult); r.Published != 3 || r.Waiting != 0 {
t.Fatalf("uplink_publish_again answered %+v", r)
}
var names []string
for _, tool := range b.tools() {
names = append(names, tool.Name)
}
if strings.Join(names, " ") != "uplink_sign_in uplink_names_again uplink_rating_again uplink_publish_again uplink_health" {
t.Fatalf("serves %v", names)
}
}
@@ -0,0 +1,60 @@
package main
// A path in the module's folder the watcher does not know (design 08 sign-in-page §12; lead answer L-1): the folder's
// `unknown` is `module`, so the node-engine does nothing inside it and the watcher reacts. It leaves such a path as it
// is and writes it to its journal once per path: at its start for what is there, and at each file event of the kernel
// that makes one.
import (
"os"
"path/filepath"
"regexp"
"strings"
)
// keptFile is a kept event's name in pending/, or one being written beside it.
var keptFile = regexp.MustCompile(`^[0-9]{10}\.json(\.new)?$`)
// knownPath says whether path is one of the folder's own: watch.sock, check-address, pending/ and its files,
// names.json, sequence, or a file being written beside one of them.
func (f Folder) knownPath(path string) bool {
rel, err := filepath.Rel(f.Dir, path)
if err != nil || strings.HasPrefix(rel, "..") {
return false
}
dir, name := filepath.Split(rel)
switch dir {
case "":
name = strings.TrimSuffix(name, ".new")
return name == socketName || name == checkName || name == pendingName || name == namesName || name == sequenceName
case pendingName + "/":
return keptFile.MatchString(name)
}
return false
}
// unknownAtStart is every path in the folder and in pending/ the watcher does not know.
func (f Folder) unknownAtStart() []string {
var out []string
for _, dir := range []string{f.Dir, filepath.Join(f.Dir, pendingName)} {
entries, _ := os.ReadDir(dir)
for _, e := range entries {
if p := filepath.Join(dir, e.Name()); !f.knownPath(p) {
out = append(out, p)
}
}
}
return out
}
// strange writes a path the watcher does not know to its journal, once per path, and leaves it as it is.
func (w *Watcher) strange(path string) {
if w.Folder.knownPath(path) || w.told[path] {
return
}
if w.told == nil {
w.told = map[string]bool{}
}
w.told[path] = true
journal("%s is not the module's: left as it is", path)
}
@@ -7,6 +7,8 @@ import (
"path/filepath"
"strings"
"testing"
stdio "git.novox.be/novox/mesh-sdk/go"
)
// The node-uplink seat's verbs (novox/hq ADR 0241), every holder's: the resolver file as it is, the mesh's
@@ -148,3 +150,30 @@ func TestTheLinksCarryTheirDefaultRouteAndTheirNames(t *testing.T) {
t.Fatalf("a manager that does not answer is not said: %+v", answer)
}
}
// main.go serves the seat's two verbs first and the holder's own tools after them, and runs a subcommand only when
// the holder's manager.go gives it (design 08 sign-in-page §11).
func TestTheHoldersOwnPartComesBesideTheSeatsVerbs(t *testing.T) {
ran := ""
own := holderOwn{
Commands: map[string]func([]string) error{"watch": func(args []string) error { ran = strings.Join(args, " "); return nil }},
Tools: []stdio.Tool{{Name: "own_tool"}},
}
var names []string
for _, tool := range tools(Machine{}, own) {
names = append(names, tool.Name)
}
if strings.Join(names, " ") != "node-uplink.resolvers node-uplink.links own_tool" {
t.Fatalf("served %v", names)
}
if run, err := command(own, nil); run != nil || err != nil {
t.Fatalf("no arguments is the bundle, got a subcommand or %v", err)
}
if _, err := command(own, []string{"nothing"}); err == nil || !strings.Contains(err.Error(), `"nothing"`) {
t.Fatalf("a subcommand the holder has not was taken: %v", err)
}
run, err := command(own, []string{"watch", "a"})
if err != nil || run([]string{"a"}) != nil || ran != "a" {
t.Fatalf("the holder's subcommand did not run: %v %q", err, ran)
}
}
@@ -0,0 +1,470 @@
package main
// The watcher (design 08 sign-in-page §11, §14, §20 to §22): `uplink-tools watch`, a process the machine's service
// manager starts at boot as the account and keeps running, needing no bus. It hears the network manager's
// PropertiesChanged on the system bus for the rating, the active connection and the check, keeps the events of §21 in
// the module's folder for the bundle to publish, and answers its socket. Nothing runs on a timer: it acts on a signal,
// on the system bus's socket coming back (a file event of the kernel) and on an ask on its socket.
import (
"errors"
"fmt"
"net/url"
"os"
"path/filepath"
"time"
"git.novox.be/novox/mesh-networking/modules/mesh-connectivity-contracts/go/seats/nodeuplink"
)
// keptBound is the most kept events pending/ holds; past it the oldest goes, with a journal line (§20).
const keptBound = 256
// The network manager's ratings of the network (NMConnectivityState).
const (
ratingUnknown uint32 = 0
ratingNone uint32 = 1
ratingPortal uint32 = 2
ratingLimited uint32 = 3
ratingFull uint32 = 4
)
func ratingName(r uint32) string {
switch r {
case ratingNone:
return "NONE"
case ratingPortal:
return "PORTAL"
case ratingLimited:
return "LIMITED"
case ratingFull:
return "FULL"
}
return "UNKNOWN"
}
// Rating is what the watcher reads of the network manager: its rating, whether its check is on and where it goes, and
// the active connection (its object, its name and its first device's interface; "" or "/" when none is active).
type Rating struct {
Connectivity uint32
CheckEnabled bool
CheckAvailable bool
CheckURI string
Connection string
Network string
Link string
}
func (r Rating) checkOn() bool { return r.CheckEnabled && r.CheckAvailable }
func (r Rating) active() bool { return r.Connection != "" && r.Connection != "/" }
// The events of node-uplink the watcher keeps, and why an ask ended, are the seat's (design 08 sign-in-page §1).
const (
eventAsked = nodeuplink.EventSignInAsked
eventEnded = nodeuplink.EventSignInEnded
whySignedIn = nodeuplink.SignInEndedWhySignedIn
whyLeft = nodeuplink.SignInEndedWhyLeft
whyNoLongerAsked = nodeuplink.SignInEndedWhyNoLongerAsked
)
// eventSubject is where a node-uplink event of node is published (§1).
func eventSubject(event, node string) string {
if event == eventAsked {
return nodeuplink.SubjectSignInAsked(node)
}
return nodeuplink.SubjectSignInEnded(node)
}
// signal is one thing the system bus said that the watcher hears: the network manager's rating changed, or logind
// has a new session (its object path).
type signal struct {
Rating bool
Session string
}
// systemBus is the watcher's connection to the machine's system bus: subscribed, it hands every signal it hears on the
// channel, which closes when the connection drops.
type systemBus interface {
listen() (<-chan signal, error)
rating() (Rating, error)
// sessions is every session of the account uid; session is one, by its object.
sessions(uid uint32) ([]loginSession, error)
session(path string) (loginSession, error)
close()
}
// openAsk is the sign-in asked now: the connection, its network and link, and since when.
type openAsk struct {
Network string `json:"network"`
Link string `json:"link"`
Since time.Time `json:"since"`
connection string
address string
}
// watcherState is the watcher's answer to `state` (§23's read).
type watcherState struct {
Subscribed bool `json:"subscribed"`
Rating string `json:"rating,omitempty"`
RatingAt *time.Time `json:"rating_at,omitempty"`
Ask *openAsk `json:"ask,omitempty"`
AsksOpened int `json:"asks_opened"`
AsksEnded int `json:"asks_ended"`
DroppedPastBound int `json:"dropped_past_bound"`
LastOpen *openOutcome `json:"last_open,omitempty"`
LastNotification *note `json:"last_notification,omitempty"`
LastSession *sessionNote `json:"last_session,omitempty"`
}
// asked is an ask on the watcher's socket, handed to its loop, and the answer it sends back.
type asked struct {
ask string
reply chan askReply
}
type askReply struct {
answer any
err error
}
// Watcher is the watch: what it reads through, and the state its loop alone holds.
type Watcher struct {
Folder Folder
// Dial connects to the system bus.
Dial func() (systemBus, error)
// SocketThere fires at the file event of the kernel that makes the system bus's socket in its folder; closing stop
// ends the wait.
SocketThere func(stop <-chan struct{}) <-chan struct{}
// SocketExists says whether the system bus's socket is there now.
SocketExists func() bool
Now func() time.Time
// UID is the watcher's account, whose sessions are the person's.
UID uint32
// Environment reads the user manager's environment over a session's bus.
Environment func(bus string) ([]string, error)
// FileEvents fires at each file event of the kernel that makes a file in one of dirs, until stop closes.
FileEvents func(dirs []string, stop <-chan struct{}) <-chan struct{}
// After is a stated bound's end.
After func(time.Duration) <-chan time.Time
Desk desk
// Beside runs an open beside the loop; the func it returns is run by the loop at its end.
Beside func(work func() func())
// Made fires with each path a file event of the kernel makes in one of dirs, until stop closes.
Made func(dirs []string, stop <-chan struct{}) <-chan string
told map[string]bool
starting *sessionStart
opening bool
later []func()
ends chan func()
asks chan asked
bus systemBus
signals <-chan signal
socketAt <-chan struct{}
stopWait chan struct{}
started bool
state watcherState
rating *Rating
ask *openAsk
}
func newWatcher(f Folder) *Watcher {
w := &Watcher{Folder: f, Dial: dialSystemBus, SocketThere: systemSocketThere, Now: time.Now, asks: make(chan asked),
UID: uint32(os.Getuid()), SocketExists: systemSocketExists, Environment: userEnvironment, FileEvents: fileEvents, After: time.After,
Desk: newSessionDesk(), ends: make(chan func()), Made: pathsMade}
w.Beside = w.besideLoop
return w
}
// watch is `uplink-tools watch`: the watcher, until its process is stopped.
func watch([]string) error {
f, err := accountFolder()
if err != nil {
return err
}
if err := os.MkdirAll(f.Dir, 0o700); err != nil {
return err
}
l, err := f.listen()
if err != nil {
return fmt.Errorf("the watcher's socket: %w", err)
}
w := newWatcher(f)
go serveSocket(l, w.askLoop)
return w.run(nil)
}
// askLoop hands one ask of the socket to the loop and waits for its answer.
func (w *Watcher) askLoop(ask string) (any, error) {
reply := make(chan askReply, 1)
w.asks <- asked{ask: ask, reply: reply}
r := <-reply
return r.answer, r.err
}
// run is the watcher's loop, until stop closes: it subscribes, then acts on what it hears, one thing at a time. It ends
// with an error when it cannot subscribe again once the system bus's socket came back, so the process exits non-zero
// and its unit shows failing, the watcher's health (design 08 sign-in-page §11; lead answer C-2c).
func (w *Watcher) run(stop <-chan struct{}) error {
if w.asks == nil {
w.asks = make(chan asked)
}
var made <-chan string
if w.Made != nil {
made = w.Made([]string{w.Folder.Dir, filepath.Join(w.Folder.Dir, pendingName)}, stop)
}
for _, p := range w.Folder.unknownAtStart() {
w.strange(p)
}
w.subscribe()
if !w.state.Subscribed && w.SocketExists != nil && w.SocketExists() {
// The socket is there and refused the watcher: no file event will make it again, so waiting would leave the
// unit active and the watcher deaf (design 08 sign-in-page §14; lead answer C2-1).
w.unsubscribe()
journal("the system bus's socket is there and the watcher could not subscribe on it at its start")
return errors.New("the system bus's socket is there and the watcher could not subscribe on it at its start")
}
for {
select {
case <-stop:
w.unsubscribe()
return nil
case s, ok := <-w.signals:
if !ok {
journal("the system bus connection dropped; subscribing again when its socket is there")
w.unsubscribe()
w.waitSocket()
continue
}
w.heardSignal(s)
case <-w.startingFiles():
w.sessionFiles()
case <-w.startingBound():
w.sessionBound()
case <-w.socketAt:
w.socketAt = nil
w.subscribe()
if !w.state.Subscribed {
w.unsubscribe()
return errors.New("the system bus came back and the watcher could not subscribe on it")
}
case p := <-made:
w.strange(p)
case end := <-w.ends:
end()
case a := <-w.asks:
answer, err := w.answer(a.ask)
a.reply <- askReply{answer, err}
}
}
}
// subscribe connects to the system bus, listens, reads the rating and acts on it: at the watcher's start as its start,
// after that as on a change (§14). One that fails waits for the system bus's socket.
func (w *Watcher) subscribe() {
w.unsubscribe()
bus, err := w.Dial()
if err == nil {
var signals <-chan signal
if signals, err = bus.listen(); err == nil {
w.bus, w.signals, w.state.Subscribed = bus, signals, true
} else {
bus.close()
}
}
if err != nil {
journal("subscribing on the system bus failed: %v; subscribing again when its socket is there", err)
w.waitSocket()
return
}
journal("subscribed on the system bus")
w.readRating()
}
func (w *Watcher) unsubscribe() {
if w.stopWait != nil {
close(w.stopWait)
w.stopWait, w.socketAt = nil, nil
}
if w.bus != nil {
w.bus.close()
}
w.bus, w.signals, w.state.Subscribed = nil, nil, false
}
func (w *Watcher) waitSocket() {
w.stopWait = make(chan struct{})
w.socketAt = w.SocketThere(w.stopWait)
}
func (w *Watcher) heardSignal(s signal) {
if s.Rating {
w.readRating()
}
if s.Session != "" {
w.sessionNew(s.Session)
}
}
func (w *Watcher) startingFiles() <-chan struct{} {
if w.starting == nil {
return nil
}
return w.starting.files
}
func (w *Watcher) startingBound() <-chan time.Time {
if w.starting == nil {
return nil
}
return w.starting.bound
}
// readRating reads the rating now and acts on it: as the watcher's start the first time, as a change after.
func (w *Watcher) readRating() {
if w.bus == nil {
return
}
r, err := w.bus.rating()
if err != nil {
journal("reading the network manager's rating failed: %v", err)
return
}
if !w.started {
w.started = true
w.heard(r, true)
return
}
if w.opening {
w.later = append(w.later, func() { w.heard(r, false) })
return
}
w.heard(r, false)
}
// heard acts on a rating read: the check address, a journal line for a change, and the events of §21.
func (w *Watcher) heard(r Rating, atStart bool) {
old := w.rating
now := w.Now()
w.rating, w.state.RatingAt = &r, &now
w.state.Rating = ratingName(r.Connectivity)
if atStart || old == nil || old.Connectivity != r.Connectivity || old.Connection != r.Connection {
from := "none"
if old != nil {
from = ratingName(old.Connectivity)
}
journal("rating %s -> %s on %q", from, ratingName(r.Connectivity), r.Network)
}
if atStart || old == nil || old.CheckURI != r.CheckURI {
if err := w.Folder.writeCheckAddress(r.CheckURI); err != nil {
journal("writing the check address failed: %v", err)
}
}
if r.checkOn() && !webAddress(r.CheckURI) {
journal("the check address %q is not http or https: nothing kept, nothing opened", r.CheckURI)
return
}
if atStart {
if !r.checkOn() {
return
}
if r.Connectivity == ratingPortal && r.active() {
w.asked(r)
return
}
w.ended(r.Link, r.Network, whyNoLongerAsked)
return
}
if w.ask != nil {
switch {
case r.Connection != w.ask.connection:
w.ended(w.ask.Link, w.ask.Network, whyLeft)
case !r.checkOn() || (r.Connectivity != ratingPortal && r.Connectivity != ratingFull):
w.ended(w.ask.Link, w.ask.Network, whyNoLongerAsked)
case r.Connectivity == ratingFull:
network := w.ask.Network
w.ended(w.ask.Link, network, whySignedIn)
w.tellSignedIn(network)
default:
return
}
}
if r.checkOn() && r.Connectivity == ratingPortal && r.active() {
w.asked(r)
}
}
// webAddress says whether an address is one the watcher keeps and opens: http or https, with a host.
func webAddress(address string) bool {
u, err := url.Parse(address)
return err == nil && (u.Scheme == "http" || u.Scheme == "https") && u.Host != ""
}
// asked keeps sign-in-asked for the active connection and holds the ask.
func (w *Watcher) asked(r Rating) {
now := w.Now()
w.ask = &openAsk{Network: r.Network, Link: r.Link, Since: now, connection: r.Connection, address: r.CheckURI}
w.state.AsksOpened++
w.keep(eventAsked, nodeuplink.SignInAsked{Link: r.Link, Network: r.Network, Address: r.CheckURI,
At: stamp(now)})
w.present(nil, r.Network, r.CheckURI)
}
// ended keeps sign-in-ended and drops the ask.
func (w *Watcher) ended(link, network, why string) {
if w.ask != nil {
w.state.AsksEnded++
}
w.ask = nil
w.keep(eventEnded, nodeuplink.SignInEnded{Link: link, Network: network, At: stamp(w.Now()), Why: why})
}
// stamp is a time as the events say it: RFC 3339 in UTC, to the second.
func stamp(t time.Time) string { return t.UTC().Truncate(time.Second).Format(time.RFC3339) }
// keep writes one event into pending/ and holds the folder to its bound, the oldest dropped with a journal line.
func (w *Watcher) keep(event string, body any) {
k, err := w.Folder.keep(event, body)
if err != nil {
journal("keeping %s failed: %v", event, err)
return
}
journal("kept %s", k.Name())
kept, err := w.Folder.pending()
if err != nil {
journal("reading the kept events failed: %v", err)
return
}
for i := 0; len(kept)-i > keptBound; i++ {
if err := w.Folder.drop(kept[i]); err != nil {
journal("dropping the kept event %s past the bound of %d failed: %v", kept[i].Name(), keptBound, err)
continue
}
w.state.DroppedPastBound++
journal("dropped the kept event %s past the bound of %d", kept[i].Name(), keptBound)
}
}
// answer answers an ask of the watcher's socket: its state, or rating-again, which subscribes again and acts on the
// rating read now as on a change (§12).
func (w *Watcher) answer(ask string) (any, error) {
switch ask {
case askState:
s := w.state
if w.ask != nil {
a := *w.ask
s.Ask = &a
}
return s, nil
case askRatingAgain:
journal("asked rating-again: subscribing again")
w.subscribe()
if !w.state.Subscribed {
return nil, errors.New("subscribing on the system bus failed; waiting for its socket")
}
return w.state, nil
}
return nil, fmt.Errorf("the watcher has no ask %q", ask)
}
@@ -0,0 +1,495 @@
package main
import (
"encoding/json"
"errors"
"fmt"
"os"
"path/filepath"
"strings"
"sync"
"testing"
"time"
"github.com/godbus/dbus/v5"
)
// The system bus stood in: the rating the test sets, each connection's signals on an unbuffered channel (a send
// returns once the watcher's loop took it), and the system bus's socket fired by the test.
type fakeSystem struct {
mu sync.Mutex
now Rating
sessions []loginSession
// refuse is how many dials, from the next, are refused.
refuse int
reads int
dials int
buses []*fakeBus
socket chan struct{}
}
type fakeBus struct {
sys *fakeSystem
signals chan signal
closed bool
}
func (s *fakeSystem) dial() (systemBus, error) {
s.mu.Lock()
defer s.mu.Unlock()
s.dials++
if s.refuse > 0 {
s.refuse--
return nil, errors.New("connection refused")
}
b := &fakeBus{sys: s, signals: make(chan signal)}
s.buses = append(s.buses, b)
return b, nil
}
func (s *fakeSystem) set(r Rating) {
s.mu.Lock()
s.now = r
s.mu.Unlock()
}
func (s *fakeSystem) last() *fakeBus {
s.mu.Lock()
defer s.mu.Unlock()
return s.buses[len(s.buses)-1]
}
func (s *fakeSystem) counts() (int, int) {
s.mu.Lock()
defer s.mu.Unlock()
return s.reads, s.dials
}
func (b *fakeBus) listen() (<-chan signal, error) { return b.signals, nil }
func (b *fakeBus) sessions(uid uint32) ([]loginSession, error) {
b.sys.mu.Lock()
defer b.sys.mu.Unlock()
var out []loginSession
for _, s := range b.sys.sessions {
if s.UID == uid {
out = append(out, s)
}
}
return out, nil
}
func (b *fakeBus) session(path string) (loginSession, error) {
b.sys.mu.Lock()
defer b.sys.mu.Unlock()
for _, s := range b.sys.sessions {
if s.Path == path {
return s, nil
}
}
return loginSession{}, fmt.Errorf("no session %s", path)
}
func (b *fakeBus) close() { b.closed = true }
func (b *fakeBus) rating() (Rating, error) {
b.sys.mu.Lock()
defer b.sys.mu.Unlock()
b.sys.reads++
return b.sys.now, nil
}
// journalLines collects the journal for one test.
func journalLines(t *testing.T) func() []string {
t.Helper()
var mu sync.Mutex
var lines []string
was := journal
journal = func(format string, args ...any) {
mu.Lock()
lines = append(lines, fmt.Sprintf(format, args...))
mu.Unlock()
}
t.Cleanup(func() { journal = was })
return func() []string {
mu.Lock()
defer mu.Unlock()
return append([]string(nil), lines...)
}
}
var clockStart = time.Date(2026, 11, 24, 19, 0, 0, 0, time.UTC)
// aWatcher is a watcher over the stood-in system bus, its clock one second on at each reading.
func aWatcher(t *testing.T, sys *fakeSystem) *Watcher {
t.Helper()
tick := clockStart
var mu sync.Mutex
return &Watcher{Folder: Folder{Dir: t.TempDir()}, Dial: sys.dial, Now: func() time.Time {
mu.Lock()
defer mu.Unlock()
tick = tick.Add(time.Second)
return tick
}, SocketThere: func(stop <-chan struct{}) <-chan struct{} { return sys.socket }, asks: make(chan asked),
UID: 1000, Desk: &fakeDesk{}, Environment: func(string) ([]string, error) { return nil, nil },
FileEvents: func([]string, <-chan struct{}) <-chan struct{} { return nil },
After: func(time.Duration) <-chan time.Time { return nil },
Beside: func(work func() func()) { work()() }}
}
// The desktop stood in: each open it was asked, answered with outcome.
type fakeDesk struct {
mu sync.Mutex
opens []string
notes []note
outcome openOutcome
}
func (d *fakeDesk) notify(s Session, n note) error {
d.mu.Lock()
defer d.mu.Unlock()
d.notes = append(d.notes, n)
return nil
}
// shown is every notification shown, as `[critical] summary: body`.
func (d *fakeDesk) shown() []string {
d.mu.Lock()
defer d.mu.Unlock()
var out []string
for _, n := range d.notes {
critical := ""
if n.Critical {
critical = "critical "
}
out = append(out, critical+n.Summary+": "+n.Body)
}
return out
}
func (d *fakeDesk) open(s Session, address string) openOutcome {
d.mu.Lock()
defer d.mu.Unlock()
d.opens = append(d.opens, s.ID+" "+address)
o := d.outcome
if o.Outcome == "" {
o = openOutcome{Address: address, Program: "browser.desktop", Outcome: outcomeOpened}
}
return o
}
func (d *fakeDesk) opened() []string {
d.mu.Lock()
defer d.mu.Unlock()
return append([]string(nil), d.opens...)
}
// keptSaid is every kept event as `<event> <why> <network> <link>`, in order.
func keptSaid(t *testing.T, f Folder) []string {
t.Helper()
kept, err := f.pending()
if err != nil {
t.Fatal(err)
}
var out []string
for _, k := range kept {
var b struct{ Node, Link, Network, Address, At, Why string }
if err := json.Unmarshal(k.Body, &b); err != nil {
t.Fatal(err)
}
event := k.Event
if b.Node != "" || b.At == "" {
t.Errorf("kept %+v %+v", k, b)
}
if event == eventAsked && b.Address != "http://check.example.net/" {
t.Errorf("asked with the address %q", b.Address)
}
out = append(out, strings.Join(strings.Fields(fmt.Sprintf("%s %s %s %s", event, b.Why, b.Network, b.Link)), " "))
}
return out
}
func guest(connectivity uint32) Rating {
return Rating{Connectivity: connectivity, CheckEnabled: true, CheckAvailable: true,
CheckURI: "http://check.example.net/", Connection: "/org/freedesktop/NetworkManager/ActiveConnection/1",
Network: "guest-example", Link: "wlan0"}
}
func other(connectivity uint32) Rating {
r := guest(connectivity)
r.Connection, r.Network, r.Link = "/org/freedesktop/NetworkManager/ActiveConnection/2", "home-example", "eth0"
return r
}
func with(r Rating, change func(*Rating)) Rating {
change(&r)
return r
}
// Each line of §21 keeps its event, and with the check off, or a check address that is not http or https, nothing is
// kept (design 08 sign-in-page §21, §25).
func TestEachLineOfTheRulesKeepsItsEvent(t *testing.T) {
off := func(r *Rating) { r.CheckEnabled = false }
unavailable := func(r *Rating) { r.CheckAvailable = false }
none := func(r *Rating) { r.Connection, r.Network, r.Link = "/", "", "" }
for _, c := range []struct {
name string
ratings []Rating
kept []string
}{
{"PORTAL at the start", []Rating{guest(ratingPortal)}, []string{"sign-in-asked guest-example wlan0"}},
{"FULL at the start", []Rating{guest(ratingFull)},
[]string{"sign-in-ended no-longer-asked guest-example wlan0"}},
{"no connection at the start", []Rating{with(guest(ratingNone), none)},
[]string{"sign-in-ended no-longer-asked"}},
{"PORTAL at a join", []Rating{guest(ratingFull), guest(ratingPortal)},
[]string{"sign-in-ended no-longer-asked guest-example wlan0", "sign-in-asked guest-example wlan0"}},
{"staying PORTAL says it once", []Rating{guest(ratingPortal), guest(ratingPortal), guest(ratingPortal)},
[]string{"sign-in-asked guest-example wlan0"}},
{"signed in", []Rating{guest(ratingPortal), guest(ratingFull), guest(ratingFull)},
[]string{"sign-in-asked guest-example wlan0", "sign-in-ended signed-in guest-example wlan0"}},
{"the connection replaced, PORTAL again", []Rating{guest(ratingPortal), other(ratingPortal)},
[]string{"sign-in-asked guest-example wlan0", "sign-in-ended left guest-example wlan0",
"sign-in-asked home-example eth0"}},
{"the connection gone", []Rating{guest(ratingPortal), with(guest(ratingNone), none)},
[]string{"sign-in-asked guest-example wlan0", "sign-in-ended left guest-example wlan0"}},
{"LIMITED", []Rating{guest(ratingPortal), guest(ratingLimited)},
[]string{"sign-in-asked guest-example wlan0", "sign-in-ended no-longer-asked guest-example wlan0"}},
{"UNKNOWN", []Rating{guest(ratingPortal), guest(ratingUnknown)},
[]string{"sign-in-asked guest-example wlan0", "sign-in-ended no-longer-asked guest-example wlan0"}},
{"the check switched off while asked", []Rating{guest(ratingPortal), with(guest(ratingPortal), off)},
[]string{"sign-in-asked guest-example wlan0", "sign-in-ended no-longer-asked guest-example wlan0"}},
{"the check off", []Rating{with(guest(ratingPortal), off), with(guest(ratingFull), off),
with(guest(ratingPortal), off)}, nil},
{"the check not available", []Rating{with(guest(ratingPortal), unavailable), with(guest(ratingPortal), unavailable)},
nil},
{"a check address not http", []Rating{with(guest(ratingPortal), func(r *Rating) { r.CheckURI = "ftp://check.example.net/" })},
nil},
} {
t.Run(c.name, func(t *testing.T) {
journalLines(t)
w := aWatcher(t, &fakeSystem{})
for i, r := range c.ratings {
w.heard(r, i == 0)
}
if got := keptSaid(t, w.Folder); strings.Join(got, "|") != strings.Join(c.kept, "|") {
t.Fatalf("kept %q, want %q", got, c.kept)
}
})
}
}
// Past 256 kept events the oldest goes, with a journal line naming it, and the state counts it (§20, §25).
func TestPastTheBoundTheOldestKeptEventGoes(t *testing.T) {
lines := journalLines(t)
w := aWatcher(t, &fakeSystem{})
for range keptBound {
if _, err := w.Folder.keep(eventEnded, map[string]string{}); err != nil {
t.Fatal(err)
}
}
w.heard(guest(ratingPortal), true)
kept, _ := w.Folder.pending()
if len(kept) != keptBound || kept[0].Sequence != 2 || kept[len(kept)-1].Name() != "sign-in-asked.257" {
t.Fatalf("kept %d, from %d", len(kept), kept[0].Sequence)
}
said := strings.Join(lines(), "\n")
if !strings.Contains(said, "dropped the kept event sign-in-ended.1 past the bound of 256") ||
w.state.DroppedPastBound != 1 {
t.Fatalf("the drop was not said: %s", said)
}
}
// The system bus dropping and its socket coming back make the watcher subscribe again and act on the rating read then
// as on a change; rating-again does the same at once; between them, nothing reads the rating but a signal (§14, §25).
func TestTheWatcherSubscribesAgainAndRunsOnNoTimer(t *testing.T) {
lines := journalLines(t)
sys := &fakeSystem{socket: make(chan struct{})}
sys.set(guest(ratingFull))
w := aWatcher(t, sys)
stop := make(chan struct{})
done := make(chan struct{})
go func() { _ = w.run(stop); close(done) }()
defer func() { close(stop); <-done }()
state := func() watcherState {
s, err := w.askLoop(askState)
if err != nil {
t.Fatal(err)
}
return s.(watcherState)
}
if s := state(); !s.Subscribed || s.Rating != "FULL" {
t.Fatalf("at its start %+v", s)
}
for range 3 {
state()
}
if reads, _ := sys.counts(); reads != 1 {
t.Fatalf("the rating was read %d times with no signal: something reads it on a timer", reads)
}
sys.set(guest(ratingPortal))
sys.last().signals <- signal{Rating: true}
if s := state(); s.Ask == nil || s.Ask.Network != "guest-example" {
t.Fatalf("PORTAL heard as %+v", s)
}
close(sys.last().signals)
if s := state(); s.Subscribed {
t.Fatal("subscribed after the system bus dropped")
}
if !strings.Contains(strings.Join(lines(), "\n"), "the system bus connection dropped") {
t.Fatal("the drop was not written to the journal")
}
sys.set(guest(ratingFull))
sys.socket <- struct{}{}
if s := state(); !s.Subscribed || s.Ask != nil || s.Rating != "FULL" {
t.Fatalf("after the socket came back %+v", s)
}
if got := keptSaid(t, w.Folder); got[len(got)-1] != "sign-in-ended signed-in guest-example wlan0" {
t.Fatalf("the rating read on subscribing again was not acted on as a change: %q", got)
}
sys.set(guest(ratingPortal))
if _, err := w.askLoop(askRatingAgain); err != nil {
t.Fatal(err)
}
if reads, dials := sys.counts(); dials != 3 || reads != 4 || !sys.buses[1].closed {
t.Fatalf("rating-again: %d dials, %d reads", dials, reads)
}
if s := state(); !s.Subscribed || s.Ask == nil || s.AsksOpened != 2 || s.AsksEnded != 1 {
t.Fatalf("after rating-again %+v", s)
}
}
// The signals the watcher hears, as the system bus sends them (recorded with dbus-monitor): the network manager's
// PropertiesChanged for a property of the rating, not for another, and logind's SessionNew (§14, §17).
func TestTheWatcherHearsTheSystemBusSignals(t *testing.T) {
changed := func(props map[string]dbus.Variant, invalidated []string) *dbus.Signal {
return &dbus.Signal{Sender: ":1.5", Path: nmPath, Name: "org.freedesktop.DBus.Properties.PropertiesChanged",
Body: []any{"org.freedesktop.NetworkManager", props, invalidated}}
}
for _, c := range []struct {
name string
s *dbus.Signal
want signal
ok bool
}{
{"Connectivity", changed(map[string]dbus.Variant{"Connectivity": dbus.MakeVariant(uint32(2))}, []string{}),
signal{Rating: true}, true},
{"PrimaryConnection", changed(map[string]dbus.Variant{"PrimaryConnection": dbus.MakeVariant(dbus.ObjectPath("/"))},
[]string{}), signal{Rating: true}, true},
{"ConnectivityCheckUri invalidated", changed(map[string]dbus.Variant{}, []string{"ConnectivityCheckUri"}),
signal{Rating: true}, true},
{"another property", changed(map[string]dbus.Variant{"Metered": dbus.MakeVariant(uint32(4))}, []string{}),
signal{}, false},
{"another interface", &dbus.Signal{Path: nmPath, Name: "org.freedesktop.DBus.Properties.PropertiesChanged",
Body: []any{"org.freedesktop.NetworkManager.Device", map[string]dbus.Variant{"Connectivity": dbus.MakeVariant(uint32(2))},
[]string{}}}, signal{}, false},
{"SessionNew", &dbus.Signal{Sender: ":1.3", Path: login1Path, Name: "org.freedesktop.login1.Manager.SessionNew",
Body: []any{"4", dbus.ObjectPath("/org/freedesktop/login1/session/_34")}},
signal{Session: "/org/freedesktop/login1/session/_34"}, true},
} {
got, ok := readSignal(c.s)
if ok != c.ok || got != c.want {
t.Errorf("%s: heard %+v %v", c.name, got, ok)
}
}
}
// The watcher dials the system bus again only at the file event that makes its socket and at rating-again, never in a
// loop (§14; note d); and when the bus came back and it cannot subscribe on it, it ends with an error, so its process
// exits non-zero and its unit shows failing (§11; lead answer C-2c).
func TestTheWatcherRedialsOnlyAtTheSocketsEventAndRatingAgain(t *testing.T) {
journalLines(t)
sys := &fakeSystem{socket: make(chan struct{}), refuse: 1}
sys.set(guest(ratingFull))
w := aWatcher(t, sys)
stop, done := make(chan struct{}), make(chan error, 1)
go func() { done <- w.run(stop) }()
state := func() watcherState {
s, _ := w.askLoop(askState)
return s.(watcherState)
}
dials := func() int { _, d := sys.counts(); return d }
for range 3 {
if s := state(); s.Subscribed {
t.Fatal("subscribed through a refused dial")
}
}
if d := dials(); d != 1 {
t.Fatalf("a bus that refused the watcher at its start was dialled %d times with no event", d)
}
sys.socket <- struct{}{}
if s := state(); !s.Subscribed || dials() != 2 {
t.Fatalf("at the socket's event: %+v, %d dials", s, dials())
}
close(sys.last().signals)
state()
state()
if d := dials(); d != 2 {
t.Fatalf("a dropped connection was dialled again before the socket's event: %d dials", d)
}
if _, err := w.askLoop(askRatingAgain); err != nil || dials() != 3 || !state().Subscribed {
t.Fatalf("rating-again: %v, %d dials", err, dials())
}
close(sys.last().signals)
sys.mu.Lock()
sys.refuse = 1
sys.mu.Unlock()
sys.socket <- struct{}{}
if err := <-done; err == nil || !strings.Contains(err.Error(), "could not subscribe") || dials() != 4 {
t.Fatalf("the bus came back refusing: the watcher ended with %v after %d dials", err, dials())
}
close(stop)
}
// When its first subscribe at its start fails while the system bus's socket is there, no file event will come: the
// watcher writes the reason to its journal and ends with an error, so its process exits non-zero (§14; lead answer
// C2-1). With no socket there it waits for the one that makes it, as above.
func TestARefusedStartWithTheSocketThereEndsTheWatcher(t *testing.T) {
lines := journalLines(t)
sys := &fakeSystem{socket: make(chan struct{}), refuse: 1}
w := aWatcher(t, sys)
w.SocketExists = func() bool { return true }
ended := make(chan error, 1)
go func() { ended <- w.run(make(chan struct{})) }()
answered := make(chan struct{})
go func() { w.askLoop(askState); close(answered) }()
var err error
select {
case err = <-ended:
case <-answered:
t.Fatal("the watcher waits for a file event that will not come, its unit left active")
}
if _, dials := sys.counts(); err == nil || !strings.Contains(err.Error(), "at its start") || dials != 1 {
t.Fatalf("the watcher ended with %v after %d dials", err, dials)
}
if !strings.Contains(strings.Join(lines(), "\n"), "could not subscribe on it at its start") {
t.Fatalf("the reason is not in the journal: %q", lines())
}
}
// The real wait fires at the file event that makes the system bus's socket, not for one that is merely there (note d).
func TestTheSocketsWaitFiresWhenTheSocketIsMade(t *testing.T) {
journalLines(t)
dir := t.TempDir()
was := systemSocket
systemSocket = filepath.Join(dir, "system_bus_socket")
t.Cleanup(func() { systemSocket = was })
if err := os.WriteFile(systemSocket, nil, 0o600); err != nil {
t.Fatal(err)
}
stop := make(chan struct{})
defer close(stop)
there := systemSocketThere(stop)
select {
case <-there:
t.Fatal("fired for a socket that was already there")
default:
}
os.WriteFile(filepath.Join(dir, "other"), nil, 0o600)
os.Remove(systemSocket)
if err := os.WriteFile(systemSocket+".made", nil, 0o600); err != nil {
t.Fatal(err)
}
if err := os.Rename(systemSocket+".made", systemSocket); err != nil {
t.Fatal(err)
}
<-there
}
@@ -0,0 +1,405 @@
//go:build integration
package main
// networkmanager whole (design 08 sign-in-page §25, R-M4, R2-1): its watcher, with the system bus, logind, the user
// manager and the desktop stood in, runs with no bus and opens the page; then the bundle, the built binary played over
// its real stdin and stdout as the node's tool runner plays it, meets a real bus holding node-uplink's events family and
// a stand-in holder of node-resolver: the kept events are published in order with the times of their changes, each
// matching the seat's definition, and uplink-names is called.
import (
"bufio"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"os"
"os/exec"
"path/filepath"
"strings"
"sync"
"testing"
"time"
"github.com/nats-io/nats.go"
"github.com/nats-io/nats.go/jetstream"
"git.novox.be/novox/mesh-networking/modules/mesh-connectivity-contracts/go/seats/nodeuplink"
"git.novox.be/novox/mesh-sdk/go/testbus"
)
// clock is the watcher's clock, set by the test before each change.
type clock struct {
mu sync.Mutex
now time.Time
}
func (c *clock) set(t time.Time) { c.mu.Lock(); c.now = t; c.mu.Unlock() }
func (c *clock) read() time.Time { c.mu.Lock(); defer c.mu.Unlock(); return c.now }
// tellingDesk is the stood-in desktop, saying each notification on a channel.
type tellingDesk struct {
fakeDesk
told chan note
}
func (d *tellingDesk) notify(s Session, n note) error {
d.fakeDesk.notify(s, n)
d.told <- n
return nil
}
// runtime plays the node's tool runner for the bundle over a real bus: a kept event said on the seat is published on
// the stream with the module's prefix on its id, awaiting the acknowledgement; a seat verb is asked of its holder.
type runtime struct {
t *testing.T
ctx context.Context
nc *nats.Conn
js jetstream.JetStream
mu sync.Mutex
in io.Writer
next int
pending map[string]chan json.RawMessage
// mayPublish is every subject the module's membership lets it say, as the runtime's mayPublish reads it; guarded
// by mu.
mayPublish map[string]bool
}
// membershipPublish is what the module's membership lists it may publish on node: a held seat's own-node machine
// events, the rule mesh-grants' MembershipFor holds (mesh-delivery ef8dd120), read here from the shared contract and the
// module's own manifest, never from mesh-grants' code.
func membershipPublish(t *testing.T, node string) map[string]bool {
t.Helper()
raw, err := os.ReadFile(filepath.Join(moduleDir, "module.json"))
if err != nil {
t.Fatal(err)
}
var m struct {
Claims []struct {
Name string `json:"name"`
} `json:"claims"`
}
if err := json.Unmarshal(raw, &m); err != nil {
t.Fatal(err)
}
out := map[string]bool{}
for _, c := range m.Claims {
if c.Name == nodeuplink.Seat {
out[nodeuplink.SubjectSignInAsked(node)] = true
out[nodeuplink.SubjectSignInEnded(node)] = true
}
}
return out
}
func (r *runtime) send(m map[string]any) {
m["jsonrpc"] = "2.0"
raw, _ := json.Marshal(m)
r.mu.Lock()
defer r.mu.Unlock()
r.in.Write(append(raw, '\n'))
}
func (r *runtime) answer(id json.RawMessage, result any, err error) {
if err != nil {
r.send(map[string]any{"id": id, "error": map[string]any{"code": -32000, "message": err.Error()}})
return
}
r.send(map[string]any{"id": id, "result": result})
}
func (r *runtime) serve(out io.Reader) {
scanner := bufio.NewScanner(out)
scanner.Buffer(make([]byte, 1<<20), 1<<24)
for scanner.Scan() {
var m struct {
ID json.RawMessage `json:"id"`
Method string `json:"method"`
Params json.RawMessage `json:"params"`
Result json.RawMessage `json:"result"`
}
if json.Unmarshal(scanner.Bytes(), &m) != nil {
continue
}
if m.Method == "" {
var id string
json.Unmarshal(m.ID, &id)
r.mu.Lock()
ch := r.pending[id]
r.mu.Unlock()
if ch != nil {
ch <- m.Result
}
continue
}
go r.handle(m.ID, m.Method, m.Params)
}
}
func (r *runtime) handle(id json.RawMessage, method string, params json.RawMessage) {
switch method {
case "mesh/seat.publish":
var p struct {
Subject string `json:"subject"`
Body json.RawMessage `json:"body"`
ID string `json:"id"`
}
json.Unmarshal(params, &p)
r.mu.Lock()
may := r.mayPublish[p.Subject]
r.mu.Unlock()
if !may {
r.answer(id, nil, fmt.Errorf("%s may not publish %s: its membership does not list it", Module, p.Subject))
return
}
_, err := r.js.Publish(r.ctx, p.Subject, p.Body, jetstream.WithMsgID(Module+"."+p.ID))
r.answer(id, map[string]any{}, err)
case "mesh/ask":
var p struct {
Key string `json:"key"`
Body json.RawMessage `json:"body"`
}
json.Unmarshal(params, &p)
switch p.Key {
case "seat:mesh-module-assigner.assignments":
r.answer(id, json.RawMessage(`{"seats":[{"seat":"node-resolver","node":"home-server",`+
`"holders":[{"module":"systemd-resolved","node":"home-server"}]}]}`), nil)
case "seat:node-resolver.uplink-names@home-server":
msg, err := r.nc.Request("stand-in.node-resolver.uplink-names", p.Body, testbus.SetupBound(r.t))
if err != nil {
r.answer(id, nil, err)
return
}
r.answer(id, json.RawMessage(msg.Data), nil)
default:
r.answer(id, nil, errors.New("nats: no responders available for request"))
}
case "mesh/subscribe":
r.answer(id, map[string]any{}, nil)
default:
r.answer(id, nil, fmt.Errorf("%s is not played here", method))
}
}
// call calls one of the bundle's tools and answers its result's text.
func (r *runtime) call(name string) string {
r.t.Helper()
r.mu.Lock()
r.next++
id := fmt.Sprintf("c-%d", r.next)
ch := make(chan json.RawMessage, 1)
r.pending[id] = ch
r.mu.Unlock()
r.send(map[string]any{"id": id, "method": "tools/call", "params": map[string]any{"name": name, "arguments": map[string]any{}}})
select {
case raw := <-ch:
var res struct {
Content []struct {
Text string `json:"text"`
} `json:"content"`
IsError bool `json:"isError"`
}
json.Unmarshal(raw, &res)
if res.IsError || len(res.Content) == 0 {
r.t.Fatalf("%s answered %s", name, raw)
}
return res.Content[0].Text
case <-time.After(testbus.SetupBound(r.t)):
testbus.Starved(r.t, name+" was not answered")
}
return ""
}
// Module is the module the runtime serves the bundle as.
const Module = "networkmanager"
func TestNetworkManagerWhole(t *testing.T) {
home, err := os.MkdirTemp("", "nm")
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { os.RemoveAll(home) })
// The watcher's folder names no node, as the watcher reads no MESH_NODE (L-3); the bundle has its own.
f := Folder{Dir: filepath.Join(home, stateHome)}
if err := os.MkdirAll(f.Dir, 0o700); err != nil {
t.Fatal(err)
}
// The watcher, with no bus: the rating FULL at its start, then PORTAL at 10:00, FULL at 10:05.
portal := Rating{Connectivity: ratingFull, CheckEnabled: true, CheckAvailable: true,
CheckURI: "http://example.net/portal", Connection: "/org/freedesktop/NetworkManager/ActiveConnection/1",
Network: "guest-example", Link: "wlan0"}
sys := &fakeSystem{socket: make(chan struct{}), sessions: []loginSession{personsSession()}}
sys.set(portal)
at := &clock{}
desk := &tellingDesk{told: make(chan note, 4)}
w := &Watcher{Folder: f, Dial: sys.dial, SocketThere: func(<-chan struct{}) <-chan struct{} { return sys.socket },
Now: at.read, asks: make(chan asked), UID: 1000, Desk: desk, ends: make(chan func()),
Environment: func(string) ([]string, error) { return []string{"DISPLAY=:1", "XAUTHORITY=/x"}, nil },
FileEvents: func([]string, <-chan struct{}) <-chan struct{} { return nil },
After: func(time.Duration) <-chan time.Time { return nil }}
w.Beside = w.besideLoop
l, err := f.listen()
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { l.Close() })
go serveSocket(l, w.askLoop)
stop, stopped := make(chan struct{}), make(chan struct{})
at.set(time.Date(2026, 11, 24, 9, 59, 0, 0, time.UTC))
go func() { _ = w.run(stop); close(stopped) }()
t.Cleanup(func() { close(stop); <-stopped })
told := func(summary string) {
t.Helper()
select {
case n := <-desk.told:
if n.Summary != summary {
t.Fatalf("told %q, want %q", n.Summary, summary)
}
case <-time.After(testbus.SetupBound(t)):
testbus.Starved(t, "no notification "+summary)
}
}
w.askLoop(askState)
at.set(time.Date(2026, 11, 24, 10, 0, 0, 0, time.UTC))
portal.Connectivity = ratingPortal
sys.set(portal)
sys.last().signals <- signal{Rating: true}
told("This network asks you to sign in")
if got := desk.opened(); len(got) != 1 || got[0] != "2 http://example.net/portal" {
t.Fatalf("with no bus the watcher opened %q", got)
}
at.set(time.Date(2026, 11, 24, 10, 5, 0, 0, time.UTC))
portal.Connectivity = ratingFull
sys.set(portal)
sys.last().signals <- signal{Rating: true}
told("The network is open")
w.askLoop(askState)
kept, err := f.pending()
if err != nil || len(kept) != 3 {
t.Fatalf("kept %+v %v", kept, err)
}
// The bus comes: node-uplink's family on the events stream, and a stand-in holder of node-resolver.
ctx, cancel := context.WithCancel(context.Background())
t.Cleanup(cancel)
nc, err := nats.Connect(testbus.URL(t))
if err != nil {
t.Fatal(err)
}
t.Cleanup(nc.Close)
js, err := jetstream.New(nc)
if err != nil {
t.Fatal(err)
}
stream, err := js.CreateStream(ctx, jetstream.StreamConfig{Name: "EVENTS",
Subjects: []string{nodeuplink.SubjectSignInAskedAll, nodeuplink.SubjectSignInEndedAll},
MaxAge: nodeuplink.FamilyMaxAgeDays * 24 * time.Hour, Duplicates: time.Hour})
if err != nil {
t.Fatal(err)
}
given := make(chan string, 8)
if _, err := nc.Subscribe("stand-in.node-resolver.uplink-names", func(m *nats.Msg) {
given <- string(m.Data)
m.Respond([]byte(`{"names":["example.net"],"link":"wlan0","set_at":"2026-11-24T10:06:00Z"}`))
}); err != nil {
t.Fatal(err)
}
bin := filepath.Join(home, "uplink-tools")
if out, err := exec.Command("go", "build", "-o", bin, ".").CombinedOutput(); err != nil {
t.Fatalf("building uplink-tools: %v\n%s", err, out)
}
cmd := exec.CommandContext(ctx, bin)
cmd.Env = append(os.Environ(), "HOME="+home, "MESH_NODE=home-server", "MESH_MODULE="+Module, "MESH_SERVED_MODULE="+Module)
in, _ := cmd.StdinPipe()
out, _ := cmd.StdoutPipe()
cmd.Stderr = os.Stderr
if err := cmd.Start(); err != nil {
t.Fatal(err)
}
t.Cleanup(func() { in.Close(); cmd.Wait() })
r := &runtime{t: t, ctx: ctx, nc: nc, js: js, in: in, pending: map[string]chan json.RawMessage{},
mayPublish: membershipPublish(t, "home-server")}
go r.serve(out)
select {
case body := <-given:
if body != `{"names":["example.net"]}` {
t.Fatalf("uplink-names was given %s", body)
}
case <-time.After(testbus.SetupBound(t)):
testbus.Starved(t, "uplink-names was not called")
}
consumer, err := stream.OrderedConsumer(ctx, jetstream.OrderedConsumerConfig{})
if err != nil {
t.Fatal(err)
}
type published struct {
subject, id string
body []byte
}
var got []published
for len(got) < 3 {
msg, err := consumer.Next(jetstream.FetchMaxWait(testbus.SetupBound(t)))
if err != nil {
testbus.Starved(t, fmt.Sprintf("%d of the 3 kept events were published: %v", len(got), err))
}
got = append(got, published{msg.Subject(), msg.Headers().Get(jetstream.MsgIDHeader), msg.Data()})
}
for i, k := range kept {
id := fmt.Sprintf("%s.home-server.%s.%d", Module, k.Event, k.Sequence)
if got[i].id != id || got[i].subject != eventSubject(k.Event, "home-server") {
t.Errorf("published %d: %s %s, kept %s", i, got[i].subject, got[i].id, k.Name())
}
}
strict := func(raw []byte, into any) {
t.Helper()
dec := json.NewDecoder(strings.NewReader(string(raw)))
dec.DisallowUnknownFields()
if err := dec.Decode(into); err != nil {
t.Fatalf("%s does not match the seat's definition: %v", raw, err)
}
}
var asked nodeuplink.SignInAsked
strict(got[1].body, &asked)
if got[1].subject != nodeuplink.SubjectSignInAsked("home-server") || asked != (nodeuplink.SignInAsked{
Node: "home-server", Link: "wlan0", Network: "guest-example", Address: "http://example.net/portal",
At: "2026-11-24T10:00:00Z"}) {
t.Errorf("sign-in-asked is %s on %s", got[1].body, got[1].subject)
}
var ended nodeuplink.SignInEnded
strict(got[2].body, &ended)
if got[2].subject != nodeuplink.SubjectSignInEnded("home-server") || ended != (nodeuplink.SignInEnded{
Node: "home-server", Link: "wlan0", Network: "guest-example", At: "2026-11-24T10:05:00Z",
Why: nodeuplink.SignInEndedWhySignedIn}) {
t.Errorf("sign-in-ended is %s on %s", got[2].body, got[2].subject)
}
if text := r.call("uplink_publish_again"); text != `{"published":0,"waiting":0}` {
t.Fatalf("after the publishes uplink_publish_again answered %s", text)
}
if left, _ := f.pending(); len(left) != 0 {
t.Fatalf("left in pending/: %+v", left)
}
// A subject the membership does not list is refused by the runtime, and the change stays kept.
r.mu.Lock()
delete(r.mayPublish, nodeuplink.SubjectSignInAsked("home-server"))
r.mu.Unlock()
if _, err := f.keep(eventAsked, nodeuplink.SignInAsked{Link: "wlan0", Network: "guest-example",
Address: "http://example.net/portal", At: "2026-11-24T10:10:00Z"}); err != nil {
t.Fatal(err)
}
if text := r.call("uplink_publish_again"); !strings.Contains(text, `"waiting":1`) ||
!strings.Contains(text, "its membership does not list it") {
t.Fatalf("a subject the membership does not list: uplink_publish_again answered %s", text)
}
if left, _ := f.pending(); len(left) != 1 {
t.Fatalf("the refused event is not kept: %+v", left)
}
if info, err := stream.Info(ctx); err != nil || info.State.Msgs != 3 {
t.Fatalf("the stream holds %v messages (%v), not the 3 published", info.State.Msgs, err)
}
}
+14 -3
View File
@@ -2,13 +2,24 @@ module networkmanager
go 1.26.0
require git.novox.be/novox/mesh-sdk/go v0.0.0-00010101000000-000000000000
require (
git.novox.be/novox/mesh-networking/modules/mesh-connectivity-contracts/go/seats/noderesolver v0.0.0-00010101000000-000000000000
git.novox.be/novox/mesh-networking/modules/mesh-connectivity-contracts/go/seats/nodeuplink v0.0.0-00010101000000-000000000000
git.novox.be/novox/mesh-sdk/go v0.0.0-00010101000000-000000000000
github.com/godbus/dbus/v5 v5.1.0
github.com/nats-io/nats.go v1.54.0
golang.org/x/sys v0.48.0
)
require (
github.com/antithesishq/antithesis-sdk-go v0.7.0-default-no-op // indirect
github.com/google/go-tpm v0.9.8 // indirect
github.com/klauspost/compress v1.20.1 // indirect
github.com/nats-io/nats.go v1.54.0 // indirect
github.com/minio/highwayhash v1.0.4 // indirect
github.com/nats-io/jwt/v2 v2.8.1 // indirect
github.com/nats-io/nats-server/v2 v2.11.17 // indirect
github.com/nats-io/nkeys v0.4.16 // indirect
github.com/nats-io/nuid v1.0.1 // indirect
golang.org/x/crypto v0.57.0 // indirect
golang.org/x/sys v0.48.0 // indirect
golang.org/x/time v0.15.0 // indirect
)
+20 -6
View File
@@ -1,12 +1,26 @@
github.com/klauspost/compress v1.20.1 h1:T7kKElXUMXrUJ2E9QhQhxFtcK5rPyLdsGZvdbLMPdiQ=
github.com/antithesishq/antithesis-sdk-go v0.7.0-default-no-op/go.mod h1:FQyySiasQQM8735Ddel3MRojmy4dA1IqCeyJ5jmPMbI=
github.com/antithesishq/antithesis-sdk-go v0.7.0-default-no-op h1:Z/MZK75wC/NSrkgqeNIa7jexam9uWzhLmFTSCPI/kn0=
github.com/godbus/dbus/v5 v5.1.0/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA=
github.com/godbus/dbus/v5 v5.1.0 h1:4KLkAxT3aOY8Li4FRJe/KvhoNFFxo0m6fNuFUO8QJUk=
github.com/google/go-tpm v0.9.8/go.mod h1:h9jEsEECg7gtLis0upRBQU+GhYVH6jMjrFxI8u6bVUY=
github.com/google/go-tpm v0.9.8 h1:slArAR9Ft+1ybZu0lBwpSmpwhRXaa85hWtMinMyRAWo=
github.com/klauspost/compress v1.20.1/go.mod h1:LUdAzn7YLVvxLpc7y3V1m40wESHTgc1422pwwBSKYuI=
github.com/nats-io/nats.go v1.54.0 h1:vsXoOxjHp/GmPUN+EcI7uOf/uB+iAP+kEsAFNQN0yzA=
github.com/klauspost/compress v1.20.1 h1:T7kKElXUMXrUJ2E9QhQhxFtcK5rPyLdsGZvdbLMPdiQ=
github.com/minio/highwayhash v1.0.4/go.mod h1:GGYsuwP/fPD6Y9hMiXuapVvlIUEhFhMTh0rxU3ik1LQ=
github.com/minio/highwayhash v1.0.4 h1:asJizugGgchQod2ja9NJlGOWq4s7KsAWr5XUc9Clgl4=
github.com/nats-io/jwt/v2 v2.8.1/go.mod h1:nWnOEEiVMiKHQpnAy4eXlizVEtSfzacZ1Q43LIRavZg=
github.com/nats-io/jwt/v2 v2.8.1 h1:V0xpGuD/N8Mi+fQNDynXohVvp7ZztevW5io8CUWlPmU=
github.com/nats-io/nats.go v1.54.0/go.mod h1:y+DZoD1oBOYfZTU681eTUiUjI0vbqYGixNVFHcjHJ0k=
github.com/nats-io/nkeys v0.4.16 h1:rd5oAuLOb8mnAycB0xleuEBNS1pVVnN0fv/FF34Eypg=
github.com/nats-io/nats.go v1.54.0 h1:vsXoOxjHp/GmPUN+EcI7uOf/uB+iAP+kEsAFNQN0yzA=
github.com/nats-io/nats-server/v2 v2.11.17/go.mod h1:B1sFVz4StNosQ903ak4N1G01Fl/9f8e06mXpFIE2K24=
github.com/nats-io/nats-server/v2 v2.11.17 h1:GKEghcFK6A+aFx11Yf1LjgLC3txAwvyhnYzhBIQZA8I=
github.com/nats-io/nkeys v0.4.16/go.mod h1:llLgWoI0o4z/Q57q2R1kHfmocyhGV6VG/U18Glg1Afs=
github.com/nats-io/nuid v1.0.1 h1:5iA8DT8V7q8WK2EScv2padNa/rTESc1KdnPw4TC2paw=
github.com/nats-io/nkeys v0.4.16 h1:rd5oAuLOb8mnAycB0xleuEBNS1pVVnN0fv/FF34Eypg=
github.com/nats-io/nuid v1.0.1/go.mod h1:19wcPz3Ph3q0Jbyiqsd0kePYG7A95tJPxeL+1OSON2c=
golang.org/x/crypto v0.57.0 h1:3ZVCjf8Ggz7zneR/EHRVx68Ctf+2pmIMP2UFhh9cC6M=
github.com/nats-io/nuid v1.0.1 h1:5iA8DT8V7q8WK2EScv2padNa/rTESc1KdnPw4TC2paw=
golang.org/x/crypto v0.57.0/go.mod h1:Fdz0i5U6CoizGwLda9DttjSk6qlZo25zYNtR+ycvuZA=
golang.org/x/sys v0.48.0 h1:bbX/i/6MgT9BVLM9RT1thmxL04yeTAhbEz4SyadbXoo=
golang.org/x/crypto v0.57.0 h1:3ZVCjf8Ggz7zneR/EHRVx68Ctf+2pmIMP2UFhh9cC6M=
golang.org/x/sys v0.48.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og=
golang.org/x/sys v0.48.0 h1:bbX/i/6MgT9BVLM9RT1thmxL04yeTAhbEz4SyadbXoo=
golang.org/x/time v0.15.0/go.mod h1:Y4YMaQmXwGQZoFaVFk4YpCt4FLQMYKZe9oeV/f4MSno=
golang.org/x/time v0.15.0 h1:bbrp8t3bGUeFOx08pvsMYRTCVSMk89u4tKbNOZbp88U=
+37
View File
@@ -21,6 +21,21 @@
"scope": "node"
}
],
"consumes": [
"node-engine.running"
],
"invokes": [
"seat:mesh-module-assigner.assignments",
"seat:node-resolver.uplink-names",
"seat:node-resolver.routes"
],
"tools": [
"uplink_sign_in",
"uplink_names_again",
"uplink_rating_again",
"uplink_publish_again",
"uplink_health"
],
"build": {
"artifacts": [
{
@@ -67,6 +82,28 @@
"reload-on": [
"config"
]
},
{
"id": "sign-in-state",
"type": "directory",
"path": "${machine:account-home}/.local/state/mesh/networkmanager",
"owner": "${machine:account}",
"mode": "0700",
"unknown": "module"
},
{
"id": "sign-in",
"type": "process",
"name": "networkmanager-sign-in",
"artifact": "tools",
"run": [
"./uplink-tools",
"watch"
],
"user": "${machine:account}",
"health": {
"kind": "unit"
}
}
]
}
+9
View File
@@ -0,0 +1,9 @@
# systemd-networkd
The machine's network, managed by systemd-networkd: this module holds the node seat `node-uplink` (novox/hq ADR
0241), answering its verbs `resolvers` and `links` from the same code as every holder of the seat, and writes the
machine's resolver file from the mesh's resolvers (ADR 0117, ADR 0223).
**It announces neither of the seat's events and opens nothing** (ADR 0687 §1; design 08 sign-in-page §28).
systemd-networkd cannot tell a network that asks the person to sign in on its sign-in page, so this holder says no
`sign-in-asked` or `sign-in-ended`, which the seat's definition asks of no holder, and opens no page.
@@ -1,5 +1,6 @@
// The uplink holder's tools bundle: the node-uplink seat's verbs (novox/hq ADR 0241), served by the node's
// runtime as the operator account. uplink.go is every holder's; manager.go is this holder's own. stdout is
// runtime as the operator account. uplink.go is every holder's; manager.go is this holder's own, and gives the
// holder's own subcommands, tools and the work its bundle starts beside them (design 08 sign-in-page §11). stdout is
// the MCP channel; this says nothing else.
package main
@@ -11,8 +12,16 @@ import (
stdio "git.novox.be/novox/mesh-sdk/go"
)
func tools(m Machine) []stdio.Tool {
return []stdio.Tool{
// holderOwn is what a holder adds to the seat's verbs, from its manager.go: its subcommands (a process of the module
// runs one, as `uplink-tools <name>`), its own tools and the work its bundle starts once it serves.
type holderOwn struct {
Commands map[string]func(args []string) error
Tools []stdio.Tool
Start func()
}
func tools(m Machine, own holderOwn) []stdio.Tool {
return append([]stdio.Tool{
{Name: seat + ".resolvers",
Description: "The machine's resolver file as it is now: the resolvers, search domains and options it lists, " +
"whether it is the file the mesh declares, and when it is not, who wrote it as far as the machine shows " +
@@ -23,12 +32,40 @@ func tools(m Machine) []stdio.Tool {
"leaves through it, and the resolvers and search domains the network manager knows for it — a VPN's " +
"tunnel included. (r)",
Run: func(map[string]any) (any, error) { return m.Links(context.Background()) }},
}, own.Tools...)
}
// command is the holder's subcommand args name, or an error naming it when the holder has none such; nil with no args,
// which is the bundle.
func command(own holderOwn, args []string) (func(args []string) error, error) {
if len(args) == 0 {
return nil, nil
}
if run, ok := own.Commands[args[0]]; ok {
return run, nil
}
return nil, fmt.Errorf("uplink-tools has no subcommand %q", args[0])
}
func main() {
m := Machine{ResolvPath: ResolvConf, Run: execRunner, Running: running, LinkDNS: managerDNS}
if err := stdio.Serve("", tools(m)); err != nil {
own := holder(m)
run, err := command(own, os.Args[1:])
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(2)
}
if run != nil {
if err := run(os.Args[2:]); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
return
}
if own.Start != nil {
go own.Start()
}
if err := stdio.Serve("", tools(m, own)); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
@@ -65,3 +65,7 @@ func parseNetworkctl(out string) map[string]LinkDNS {
flush()
return links
}
// holder is what systemd-networkd adds to the seat's verbs: nothing, for it cannot tell a sign-in page (design 08
// sign-in-page §11, §28).
func holder(Machine) holderOwn { return holderOwn{} }
@@ -27,3 +27,16 @@ func TestNetworkctlIsReadPerLink(t *testing.T) {
t.Fatalf("read %+v", links)
}
}
// systemd-networkd serves the seat's two verbs and nothing of its own: no subcommand, no tool, no work at its start
// (design 08 sign-in-page §11, §28).
func TestNetworkdServesTheSeatsVerbsAlone(t *testing.T) {
own := holder(Machine{})
if len(own.Commands) != 0 || len(own.Tools) != 0 || own.Start != nil {
t.Fatalf("systemd-networkd adds %+v", own)
}
served := tools(Machine{}, own)
if len(served) != 2 || served[0].Name != "node-uplink.resolvers" || served[1].Name != "node-uplink.links" {
t.Fatalf("served %v", served)
}
}
@@ -7,6 +7,8 @@ import (
"path/filepath"
"strings"
"testing"
stdio "git.novox.be/novox/mesh-sdk/go"
)
// The node-uplink seat's verbs (novox/hq ADR 0241), every holder's: the resolver file as it is, the mesh's
@@ -148,3 +150,30 @@ func TestTheLinksCarryTheirDefaultRouteAndTheirNames(t *testing.T) {
t.Fatalf("a manager that does not answer is not said: %+v", answer)
}
}
// main.go serves the seat's two verbs first and the holder's own tools after them, and runs a subcommand only when
// the holder's manager.go gives it (design 08 sign-in-page §11).
func TestTheHoldersOwnPartComesBesideTheSeatsVerbs(t *testing.T) {
ran := ""
own := holderOwn{
Commands: map[string]func([]string) error{"watch": func(args []string) error { ran = strings.Join(args, " "); return nil }},
Tools: []stdio.Tool{{Name: "own_tool"}},
}
var names []string
for _, tool := range tools(Machine{}, own) {
names = append(names, tool.Name)
}
if strings.Join(names, " ") != "node-uplink.resolvers node-uplink.links own_tool" {
t.Fatalf("served %v", names)
}
if run, err := command(own, nil); run != nil || err != nil {
t.Fatalf("no arguments is the bundle, got a subcommand or %v", err)
}
if _, err := command(own, []string{"nothing"}); err == nil || !strings.Contains(err.Error(), `"nothing"`) {
t.Fatalf("a subcommand the holder has not was taken: %v", err)
}
run, err := command(own, []string{"watch", "a"})
if err != nil || run([]string{"a"}) != nil || ran != "a" {
t.Fatalf("the holder's subcommand did not run: %v %q", err, ran)
}
}
+35 -3
View File
@@ -19,6 +19,11 @@ itself (NetworkManager's VPNs, WireGuard set up by networkd, Tailscale) needs no
| `/etc/node-resolver/resolv.conf` | the same file, kept beside it for the guard to compare with and put back |
| `/etc/node-resolver/suffix` | the mesh's own domain, which a route may never take |
| `/etc/systemd/resolved.conf.d/50-mesh.conf` | every mesh resolver as the default route for names (`DNS=`, `Domains=~.`), no public fallback, the stub on loopback and on the private address, no cache, no LLMNR or mDNS |
| `/etc/node-resolver/answer-within` | the config value `answer-within`: how long the guard gives each of the mesh's resolvers to answer before it takes them for silent (issue 1981) |
| `/etc/node-resolver/private-interface` | the private network's own interface name, so the guard never gives the uplink's names to it (design 08 sign-in-page §7, DQ-1); the literal `mesh0` (lead answer L-2), as netcheck and networkmanager already name it |
| `/var/lib/node-resolver/uplink-names` | the host names `uplink-names` gave, one a line, root's, written through `sudo -n install` then `sudo -n mv -f` (§6); stays until an empty list or a person's cleanup, even once the module leaves |
| `/var/lib/node-resolver/uplink-names.applied` | the guard's own record of what it last gave the link carrying the default route: the names, the link, when, and resolved's refusal or empty (§8); read at the guard's start, so a restart takes the names off the link it names, never inferring which |
| `/run/node-resolver/fallback.json` | whether the mesh's resolvers are silent now, by ADR 0688's guard, and since when; `routes`' `mesh_resolvers` field reads it; gone at the next boot, and the guard's first round writes it again |
**On the private address, so containers reach it.** A container copies its machine's resolver file and
cannot reach the machine's loopback, so the file names the address the machine has on the private
@@ -49,8 +54,33 @@ One long-running process, as root: `resolver-tools guard`.
still raised, naming the writer, for a write nothing on the machine declared to handle.
- **Only the mesh's resolvers answer every name.** Every five seconds, a link that a network manager gave
servers of its own is told it is not a default route for names. Its own domains stay its own.
- **While the mesh's resolvers are silent, a network's own servers answer.** Behind a network's sign-in
page (a guest or hotel network) the private network is out of reach until the person signs in, so no
name, the page's included, would resolve. Every five seconds the guard first asks each of the mesh's
resolvers a name under the mesh's domain, straight over the network, each within the config value
`answer-within` (seconds, default 1); while none answers, every link a network manager gave servers is a
default route again, read from resolved each round (so it holds after the guard restarts), and a network
joined meanwhile keeps its default route. A link `route` routed (a VPN's) never is. Once one answers,
they lose it within five seconds. The guard says both turns on
its journal, and the node's network check still says the mesh's names do not resolve.
- **What it says elsewhere** — the `routes` verb's `outside_writes`, from `/run/node-resolver/history.json`
— is when, the writer's name and what became of each write. It never includes a server or a domain.
- **It gives the uplink's holder's check names to the link carrying the default route.** Every round it
reads `/var/lib/node-resolver/uplink-names` and finds the link that carries the default route: among the
kernel's IPv4 default routes, or the IPv6 ones when there is none, the one with the lowest metric whose
link is neither one `route` routed (a VPN's) nor the private network's own interface (its own fact,
`/etc/node-resolver/private-interface`); none when there is no such link. It gives that link its own
domains plus one routing-only domain `~<name>` per name, keeping every search domain and routing domain it
already has, and takes the names off the link they were on before, when that differs: never a link's
servers, its default route for names (that stays the fallback's alone), its addresses or its routes. It
never counts its own names when it judges whether a link is `route` routed, so a link holding only them
still has its default route given back by the fallback while the mesh's resolvers are silent. What it
gave is kept in `/var/lib/node-resolver/uplink-names.applied`, read at the guard's own start, so a
restart never infers which link to take them off; a refusal by resolved is journalled once per change,
never every round. `uplink-names` only sets how resolved answers those names over a link — never the
link itself, which the network manager chooses.
- **A path in its directory this module does not know** — `/var/lib/node-resolver` declares `unknown:
module` — is left exactly as it is, and said to the journal once, never every round (ADR 0422 §8).
## Its verbs
@@ -58,14 +88,16 @@ On the mesh, through the node's runtime as the operator account (writes escalate
| verb | does |
|---|---|
| `<node>/node-resolver.routes` (r) | the mesh's resolvers, each link given servers of its own with its routed domains and whether it is a default route, and the resolver file's outside writes |
| `<node>/node-resolver.routes` (r) | the generated contract's `RoutesAnswer`: the mesh's resolvers, each link given servers of its own with its routed domains and whether it is a default route, and the resolver file's outside writes. Also `uplink_names {names, link, refused}` (the applied list's names resolved holds on that link now, never the file's) and `mesh_resolvers {silent, since}` (ADR 0688's fallback). The machine's own socket answers the same, without `outside_writes` (its own `displaced` verb gives the write standing now) |
| `<node>/node-resolver.route` (a) | `{link, domains, servers}`: these domains, and every name under them, to these servers over this link, and only them. The mesh's own domain and the root are refused |
| `<node>/node-resolver.unroute` (a) | `{link}`: that link's domains go to the mesh's resolvers again |
| `<node>/node-resolver.uplink-names` (a) | `{names}`, an array of at most 8 host names (letters, digits, hyphens and dots, lower-cased), as the generated contract's `UplinkNamesInput` says; an empty array takes them away. Writes `/var/lib/node-resolver/uplink-names` whole, through `sudo -n install -m 0644 -o root -g root /dev/stdin uplink-names.new` then `sudo -n mv -f uplink-names.new uplink-names`, within 15 s. Answers the contract's `UplinkNamesAnswer` `{names, link, set_at}`: the names now given, the link they are answered over now (empty when no link carries a default route), and when. Refused, naming the name and why: not a host name (a wildcard, a trailing dot, a label over 63 bytes), the root, the mesh's own domain or under it, or more than 8 names |
**On the machine, to its own root processes**, over `/run/node-resolver/verbs.sock` (mode 0600). The path
is the seat's, so a caller does not need to know which holder answers. The protocol is one JSON line
`{"verb": …, "args": {…}}` and one JSON line back, `{"result": …}` or `{"error": "…"}`. The verbs are the
same three, plus:
`{"verb": …, "args": {…}}` and one JSON line back, `{"result": …}` or `{"error": "…"}`. The verbs are
`routes`, `route` and `unroute` (`uplink-names` is the bus's alone, never the machine's: its caller is
always on the bus), plus:
- `displaced`: the write standing now, with what it held, or null;
- `route` with `takes` (the write's `id`) and `by` (the module's name): route, then take that write, so
@@ -46,6 +46,9 @@ const (
Socket = RunDir + "/verbs.sock"
History = RunDir + "/history.json"
Displaced = RunDir + "/displaced"
// Fallback is `routes`'s state for ADR 0688's fallback (design 08 sign-in-page §8, S-N5, R2-2):
// whether the mesh's resolvers are silent, and since when.
Fallback = RunDir + "/fallback.json"
)
// Timing.
@@ -90,6 +93,24 @@ type Guard struct {
pending *Displacement
history []Displacement
wake chan struct{}
// silent is whether none of the mesh's resolvers answered at the last look, so each turn is said once.
// Only the routes' loop reads and writes it.
silent bool
// silentSince is when silent last changed, for Fallback's `since` (design 08 sign-in-page §8, S-N5).
silentSince time.Time
// fallbackWritten is whether Fallback has been written since this guard started; its first round
// writes it once more regardless of a turn, since it goes at every boot (§8).
fallbackWritten bool
// applied is what the guard last gave the link carrying the default route (design 08 sign-in-page §8):
// read at start from UplinkNamesAppliedFile, so a restart takes the names off the link it names,
// never inferring which. Only the uplink names' round reads and writes it.
applied UplinkApplied
// unknownSaid is every path in the uplink-names directory this module does not know, already said to
// the journal (design 08 sign-in-page C-7): said once, never every round.
unknownSaid map[string]bool
}
// NewGuard is the machine's.
@@ -330,10 +351,245 @@ func (g *Guard) Run(ctx context.Context) {
case <-g.wake:
g.Tick()
case <-routes.C:
if changed, err := g.Resolver.OnlyTheMeshIsADefaultRoute(ctx); err == nil && len(changed) > 0 {
g.Log("%s had servers answering every name; now only their own domains", strings.Join(changed, ", "))
g.KeepRoutes(ctx)
g.KeepUplinkNames(ctx)
g.checkUnknownPaths()
}
}
}
// KeepRoutes keeps every link's own servers from being a default route while one of the mesh's resolvers
// answers. While none does, as behind a network's sign-in page, the links it kept from it answer every name
// again, so the page can be found; once one answers, they are kept from it once more. Which links is read
// from resolved each round; the guard keeps no list of its own.
func (g *Guard) KeepRoutes(ctx context.Context) {
routes, err := g.Resolver.Routes(ctx)
if err != nil {
return
}
if !g.Resolver.TheMeshAnswers(ctx, routes.Mesh.Servers) {
if turn := !g.silent; turn || !g.fallbackWritten {
// since is this round's time whether it is a real turn or the guard's first round
// establishing where things stand (design 08 sign-in-page §8, note (c)): never the zero time.
g.silentSince = g.Now()
g.silent = true
g.writeFallback()
if turn {
g.Log("none of the mesh's resolvers answers; a network's own servers answer every name until one does")
}
}
if changed, err := g.Resolver.ADefaultRouteAgain(ctx, routes); err == nil && len(changed) > 0 {
g.Log("%s answers every name again, while the mesh's resolvers are silent", strings.Join(changed, ", "))
}
return
}
if turn := g.silent; turn || !g.fallbackWritten {
g.silentSince = g.Now()
g.silent = false
g.writeFallback()
if turn {
g.Log("one of the mesh's resolvers answers again")
}
}
if changed, err := g.Resolver.OnlyTheMeshIsADefaultRoute(ctx); err == nil && len(changed) > 0 {
g.Log("%s had servers answering every name; now only their own domains", strings.Join(changed, ", "))
}
}
// Fallback is `routes`'s state for ADR 0688's fallback (design 08 sign-in-page §8).
type FallbackState struct {
Silent bool `json:"silent"`
Since time.Time `json:"since"`
}
// writeFallback writes Resolver.FallbackFile whole, at each of the fallback's two turns, and once more at
// the guard's first round, since it goes at every boot (design 08 sign-in-page §8).
func (g *Guard) writeFallback() {
g.fallbackWritten = true
raw, err := json.MarshalIndent(FallbackState{Silent: g.silent, Since: g.silentSince}, "", " ")
if err != nil {
return
}
tmp := g.Resolver.FallbackFile + ".tmp"
if os.WriteFile(tmp, raw, 0o644) == nil {
_ = os.Rename(tmp, g.Resolver.FallbackFile)
}
}
// ReadFallback reads what the guard last said of ADR 0688's fallback; the zero value before it has run.
func ReadFallback(path string) FallbackState {
raw, err := os.ReadFile(path)
if err != nil {
return FallbackState{}
}
var s FallbackState
if json.Unmarshal(raw, &s) != nil {
return FallbackState{}
}
return s
}
// sameNames is whether two name lists are the same, in the same order (the file holds them one a line, in
// the order given).
func sameNames(a, b []string) bool {
if len(a) != len(b) {
return false
}
for i := range a {
if a[i] != b[i] {
return false
}
}
return true
}
// rawDomainsOf is one link's domains as resolved holds them now, `~` kept, so its routing domains and its
// plain search domains are told apart.
func (g *Guard) rawDomainsOf(ctx context.Context, link string) ([]string, error) {
out, err := g.Resolver.Read(ctx, "resolvectl", "domain")
if err != nil {
return nil, err
}
_, links := perScope(out)
return links[link], nil
}
// setLinkUplinkNames sets one link's domains to its own, apart from the names the guard applied there
// last, plus `~<name>` per name now given (design 08 sign-in-page §7): every search domain and routing
// domain the link already has, apart from the guard's own, stays. An empty names takes them off.
func (g *Guard) setLinkUplinkNames(ctx context.Context, link string, names []string) error {
raw, err := g.rawDomainsOf(ctx, link)
if err != nil {
return err
}
marked := map[string]bool{}
for _, n := range g.applied.Names {
marked["~"+n] = true
}
base := withoutMarked(raw, marked)
full := append([]string{}, base...)
for _, n := range names {
full = append(full, "~"+n)
}
_, err = g.Resolver.Change(ctx, "resolvectl", append([]string{"domain", link}, full...)...)
return err
}
// uplinkNamesHeld is whether resolved holds every name on the link now, read fresh with rawDomainsOf
// (design 08 sign-in-page §7, C-4): never the guard's own applied record alone, so a network manager that
// rewrites the link's domains, or a restarted resolved, is found and the names are set again.
func (g *Guard) uplinkNamesHeld(ctx context.Context, link string, names []string) bool {
if len(names) == 0 {
return true
}
if link == "" {
return false
}
raw, err := g.rawDomainsOf(ctx, link)
if err != nil {
return false
}
has := map[string]bool{}
for _, d := range raw {
has[d] = true
}
for _, n := range names {
if !has["~"+n] {
return false
}
}
return true
}
// KeepUplinkNames gives the names in the file to the link carrying the default route, every round (design
// 08 sign-in-page §7, §8): it never sets a link's servers, its default route for names, its addresses or
// its routes. A round in which they are already in place changes nothing.
func (g *Guard) KeepUplinkNames(ctx context.Context) {
given := ReadUplinkNames(g.Resolver.UplinkNamesFile)
routes, err := g.Resolver.Routes(ctx)
if err != nil {
return
}
link, err := g.Resolver.DefaultRouteLink(ctx, routes)
if err != nil {
g.Log("the kernel's default routes: %v", err)
return
}
held := g.uplinkNamesHeld(ctx, link, given)
if link == g.applied.Link && g.applied.Refused == "" && held {
return
}
missing := link == g.applied.Link && sameNames(given, g.applied.Names) && !held
if g.applied.Link != "" && g.applied.Link != link {
if err := g.setLinkUplinkNames(ctx, g.applied.Link, nil); err != nil {
g.Log("taking the uplink's names off %s failed: %v", g.applied.Link, err)
}
}
refused := ""
if link != "" {
if err := g.setLinkUplinkNames(ctx, link, given); err != nil {
refused = err.Error()
}
}
switch {
case link != g.applied.Link:
g.Log("the uplink's names are now answered over %q, were %q", link, g.applied.Link)
case missing:
g.Log("the uplink's names were missing from %s, as resolved holds it now; set again", link)
case !sameNames(given, g.applied.Names):
g.Log("the uplink's names change on %s", link)
}
if refused != g.applied.Refused {
if refused != "" {
g.Log("resolved refuses the uplink's names: %s", refused)
} else {
g.Log("resolved accepts the uplink's names again")
}
}
g.applied = UplinkApplied{Names: given, Link: link, At: g.Now(), Refused: refused}
g.writeApplied()
}
// writeApplied writes what the guard applied last, whole (beside, renamed over), design 08 sign-in-page §8.
func (g *Guard) writeApplied() {
raw, err := json.MarshalIndent(g.applied, "", " ")
if err != nil {
return
}
tmp := g.Resolver.UplinkNamesAppliedFile + ".tmp"
if os.WriteFile(tmp, raw, 0o644) == nil {
_ = os.Rename(tmp, g.Resolver.UplinkNamesAppliedFile)
}
}
// checkUnknownPaths looks at the uplink-names directory for a path this module does not know (design 08
// sign-in-page C-7; ADR 0422 §8, lead answer L-1): it leaves it exactly as it is, and says so to the
// journal once, never every round.
func (g *Guard) checkUnknownPaths() {
dir := filepath.Dir(g.Resolver.UplinkNamesFile)
entries, err := os.ReadDir(dir)
if err != nil {
return
}
// Exactly what this module writes there (review r2 (4)): the names file and the one §6 writes it
// beside (uplink-names, uplink-names.new), the applied record and the one it is written beside (§8:
// uplink-names.applied, uplink-names.applied.tmp). Nothing else, a bare *.tmp included.
known := map[string]bool{
filepath.Base(g.Resolver.UplinkNamesFile): true,
filepath.Base(g.Resolver.UplinkNamesFile) + ".new": true,
filepath.Base(g.Resolver.UplinkNamesAppliedFile): true,
filepath.Base(g.Resolver.UplinkNamesAppliedFile) + ".tmp": true,
}
for _, e := range entries {
name := e.Name()
if known[name] || g.unknownSaid[name] {
continue
}
if g.unknownSaid == nil {
g.unknownSaid = map[string]bool{}
}
g.unknownSaid[name] = true
g.Log("%s in %s is not this module's; left as it is", name, dir)
}
}
@@ -361,7 +617,11 @@ func (g *Guard) Answer(ctx context.Context, req Request) Reply {
case "routes":
var routes *Routes
if routes, err = g.Resolver.Routes(ctx); err == nil {
result = map[string]any{"mesh": routes.Mesh, "links": routes.Links}
// The machine's socket answers routes the same as the bus's (§5, DQ-5, review r2 (5)):
// outside_writes is the guard's own history too, from the same file the bus's tools() reads
// (History, RunDir/history.json); g.Dir is that directory (RunDir in production, a test's own
// in a test), so both read one history.
result = g.Resolver.RoutesAnswer(routes, ReadHistory(filepath.Join(g.Dir, "history.json")))
}
case "route":
var routed *Routed
@@ -4,12 +4,16 @@ import (
"bufio"
"context"
"encoding/json"
"errors"
"fmt"
"net"
"os"
"path/filepath"
"strings"
"testing"
"time"
noderesolver "git.novox.be/novox/mesh-networking/modules/mesh-connectivity-contracts/go/seats/noderesolver"
)
const meshFile = "# Managed by the mesh\nnameserver 10.42.0.2\noptions timeout:3 attempts:2 edns0\n"
@@ -20,6 +24,13 @@ const vpnFile = "# Dynamic resolv.conf(5) file for glibc resolver(3) generated b
// aGuardedMachine is a guard over a temporary /etc and /run, with a clock the test moves.
func aGuardedMachine(t *testing.T) (*Guard, *time.Time, *fakeResolved) {
t.Helper()
g, now, f, _ := aGuardedMachineWithLinks(t, "tun0")
return g, now, f
}
// aGuardedMachineWithLinks is the same, over the links named, and answers the resolver too.
func aGuardedMachineWithLinks(t *testing.T, links ...string) (*Guard, *time.Time, *fakeResolved, *Resolver) {
t.Helper()
dir := t.TempDir()
for _, d := range []string{"etc/node-resolver", "run"} {
@@ -31,10 +42,12 @@ func aGuardedMachine(t *testing.T) (*Guard, *time.Time, *fakeResolved) {
write(t, filepath.Join(dir, "etc/resolv.conf"), meshFile)
now := time.Date(2026, 10, 7, 12, 0, 0, 0, time.UTC)
f := &fakeResolved{}
r := aMachine(t, f, links...)
r.FallbackFile = filepath.Join(dir, "run", "fallback.json")
g := &Guard{Path: filepath.Join(dir, "etc/resolv.conf"), KeptPath: filepath.Join(dir, "etc/node-resolver/resolv.conf"),
Dir: filepath.Join(dir, "run"), Hold: Hold, Now: func() time.Time { return now },
Resolver: aMachine(t, f, "tun0"), Log: t.Logf, wake: make(chan struct{}, 1)}
return g, &now, f
Resolver: r, Log: t.Logf, wake: make(chan struct{}, 1)}
return g, &now, f, r
}
func write(t *testing.T, path, content string) {
@@ -177,6 +190,25 @@ func TestNothingIsGuardedBeforeTheFileIsRendered(t *testing.T) {
}
}
// The machine's socket answers routes with outside_writes too, the guard's own history, the same the bus
// reads (design 08 sign-in-page §5; DQ-5, review r2 (5)).
func TestTheSocketsRoutesAnswersOutsideWritesFromTheGuardsOwnHistory(t *testing.T) {
g, _, _ := aGuardedMachine(t)
write(t, g.Path, vpnFile)
g.Tick()
reply := g.Answer(context.Background(), Request{Verb: "routes"})
if reply.Error != "" {
t.Fatal(reply.Error)
}
answer, ok := reply.Result.(noderesolver.RoutesAnswer)
if !ok {
t.Fatalf("the result is %T, not a RoutesAnswer", reply.Result)
}
if len(answer.OutsideWrites) != 1 || answer.OutsideWrites[0].Writer != "FortiClient" {
t.Errorf("outside_writes is %+v, want the one the guard just kept", answer.OutsideWrites)
}
}
// The socket: a module routes and takes the write standing now in one call, and the module's file is
// back; a bad request and an unknown verb are answered, not dropped; the socket is root's alone.
func TestTheVerbsOnTheMachine(t *testing.T) {
@@ -249,3 +281,364 @@ func TestTheVerbsOnTheMachine(t *testing.T) {
t.Errorf("the mesh's domain over the socket: %+v", r)
}
}
// Behind a network's sign-in page the mesh's resolvers are out of reach, so a link a network manager gave
// servers answers every name again until one of the mesh's resolvers answers; then it is kept from it once
// more. A link `route` routed keeps its default route off, even one the guard turned off before it was
// routed, and a guard started afresh behind the page finds the link from resolved alone. (1981/AC1)
func TestTheNetworksServersAnswerWhileTheMeshsResolversAreSilent(t *testing.T) {
g, _, f := aGuardedMachine(t)
meshAnswers := true
g.Resolver.Answers = func(_ context.Context, server string) bool { return meshAnswers && server == "10.42.0.1" }
f.dns = "Global: 10.42.0.1 10.42.0.2\nLink 2 (wlan0): 192.168.1.1\nLink 7 (tun0): 10.9.0.1\n"
ctx := context.Background()
step := func(g *Guard, domains, defaults string, want ...string) {
t.Helper()
f.domain, f.defaults, f.changed = domains, defaults, nil
g.KeepRoutes(ctx)
var got []string
for _, c := range f.changed {
got = append(got, strings.Join(c, " "))
}
if strings.Join(got, "; ") != strings.Join(want, "; ") {
t.Errorf("changed %q, want %q", got, want)
}
}
// tun0 comes up with servers and a default route, is turned off, and is then routed.
step(g, "Global: ~.\nLink 2 (wlan0): lan\nLink 7 (tun0):\n", "Link 2 (wlan0): yes\nLink 7 (tun0): yes\n",
"resolvectl default-route tun0 false", "resolvectl default-route wlan0 false")
routed := "Global: ~.\nLink 2 (wlan0): lan\nLink 7 (tun0): ~corp.example\n"
meshAnswers = false
step(g, routed, "Link 2 (wlan0): no\nLink 7 (tun0): no\n", "resolvectl default-route wlan0 true")
step(g, routed, "Link 2 (wlan0): yes\nLink 7 (tun0): no\n")
afresh, _, _ := aGuardedMachine(t)
afresh.Resolver = g.Resolver
step(afresh, routed, "Link 2 (wlan0): no\nLink 7 (tun0): no\n", "resolvectl default-route wlan0 true")
meshAnswers = true
step(g, routed, "Link 2 (wlan0): yes\nLink 7 (tun0): no\n", "resolvectl default-route wlan0 false")
}
// The uplink's names are answered over the link carrying the default route, and move with the route: the
// old link loses them and keeps its own search domain (design 08 sign-in-page §7, §9; R-4, R-5).
func TestUplinkNamesMoveWithTheDefaultRoute(t *testing.T) {
g, _, f, r := aGuardedMachineWithLinks(t, "wlan0", "wlan1")
f.dns = "Link 2 (wlan0): 192.168.1.1\n"
f.domain = "Link 2 (wlan0): lan\n"
f.ip = "default via 10.0.0.1 dev wlan0 metric 100\n"
if err := os.WriteFile(r.UplinkNamesFile, []byte("check.example\n"), 0o644); err != nil {
t.Fatal(err)
}
g.KeepUplinkNames(context.Background())
if len(f.changed) != 1 || strings.Join(f.changed[0], " ") != "resolvectl domain wlan0 lan ~check.example" {
t.Fatalf("wlan0 was given %v", f.changed)
}
if g.applied.Link != "wlan0" || strings.Join(g.applied.Names, ",") != "check.example" {
t.Fatalf("applied is %+v", g.applied)
}
applied := contentOf(t, r.UplinkNamesAppliedFile)
if !strings.Contains(applied, "wlan0") || !strings.Contains(applied, "check.example") {
t.Errorf("uplink-names.applied does not say so: %s", applied)
}
// The route moves to wlan1: wlan0, as resolved now holds it, keeps "lan" and the uplink's name.
f.domain = "Link 2 (wlan0): lan ~check.example\nLink 3 (wlan1):\n"
f.ip = "default via 10.1.0.1 dev wlan1 metric 50\n"
f.changed = nil
g.KeepUplinkNames(context.Background())
if len(f.changed) != 2 {
t.Fatalf("moving the route changed %v", f.changed)
}
if strings.Join(f.changed[0], " ") != "resolvectl domain wlan0 lan" {
t.Errorf("wlan0 lost the uplink's name but not its own: %v", f.changed[0])
}
if strings.Join(f.changed[1], " ") != "resolvectl domain wlan1 ~check.example" {
t.Errorf("wlan1 was not given the uplink's name: %v", f.changed[1])
}
if g.applied.Link != "wlan1" {
t.Errorf("applied is now %+v", g.applied)
}
}
// A path in the uplink-names directory this module does not know is left exactly as it is, and said to
// the journal once, never every round (design 08 sign-in-page C-7; ADR 0422 §8, lead answer L-1).
func TestAnUnknownPathIsLeftAndJournalledOnce(t *testing.T) {
g, _, _, r := aGuardedMachineWithLinks(t, "wlan0")
dir := filepath.Dir(r.UplinkNamesFile)
stray := filepath.Join(dir, "a-program-left-this")
if err := os.WriteFile(stray, []byte("not this module's"), 0o644); err != nil {
t.Fatal(err)
}
var said []string
g.Log = func(format string, a ...any) { said = append(said, fmt.Sprintf(format, a...)) }
g.checkUnknownPaths()
g.checkUnknownPaths()
count := 0
for _, s := range said {
if strings.Contains(s, "a-program-left-this") {
count++
}
}
if count != 1 {
t.Errorf("said %d times, want once: %v", count, said)
}
if got := contentOf(t, stray); got != "not this module's" {
t.Errorf("the unknown path was changed: %q", got)
}
}
// The verb's own uplink-names.new and the guard's own uplink-names.applied.tmp are this module's, never
// said as unknown (design 08 sign-in-page §6, §8; review r2 (4)).
func TestItsOwnTemporaryFilesAreNeverSaidUnknown(t *testing.T) {
g, _, _, r := aGuardedMachineWithLinks(t, "wlan0")
// A directory of its own: /var/lib/node-resolver holds nothing but this module's files, unlike the
// fixture's shared one, which also keeps net/ and suffix for the Resolver's other paths.
dir := t.TempDir()
r.UplinkNamesFile = filepath.Join(dir, "uplink-names")
r.UplinkNamesAppliedFile = filepath.Join(dir, "uplink-names.applied")
for _, name := range []string{r.UplinkNamesFile + ".new", r.UplinkNamesAppliedFile + ".tmp"} {
if err := os.WriteFile(name, []byte(""), 0o644); err != nil {
t.Fatal(err)
}
}
var said []string
g.Log = func(format string, a ...any) { said = append(said, fmt.Sprintf(format, a...)) }
g.checkUnknownPaths()
if len(said) != 0 {
t.Errorf("said %v, want nothing for this module's own files", said)
}
}
// A changed list replaces the old one on the link, the route itself staying put (design 08 sign-in-page §9).
func TestAChangedListReplacesTheOldOneOnTheLink(t *testing.T) {
g, _, f, r := aGuardedMachineWithLinks(t, "wlan0")
f.dns = "Link 2 (wlan0): 192.168.1.1\n"
f.domain = "Link 2 (wlan0): lan\n"
f.ip = "default via 10.0.0.1 dev wlan0 metric 100\n"
if err := os.WriteFile(r.UplinkNamesFile, []byte("check.example\n"), 0o644); err != nil {
t.Fatal(err)
}
g.KeepUplinkNames(context.Background())
if len(f.changed) != 1 || strings.Join(f.changed[0], " ") != "resolvectl domain wlan0 lan ~check.example" {
t.Fatalf("the first list was given as %v", f.changed)
}
// resolved now holds it; the file's list changes, the link stays the same.
f.domain = "Link 2 (wlan0): lan ~check.example\n"
f.changed = nil
if err := os.WriteFile(r.UplinkNamesFile, []byte("other.example\n"), 0o644); err != nil {
t.Fatal(err)
}
g.KeepUplinkNames(context.Background())
if len(f.changed) != 1 || strings.Join(f.changed[0], " ") != "resolvectl domain wlan0 lan ~other.example" {
t.Errorf("the changed list was given as %v, want the old name replaced on the same link", f.changed)
}
if g.applied.Link != "wlan0" || strings.Join(g.applied.Names, ",") != "other.example" {
t.Errorf("applied is %+v", g.applied)
}
}
// A network manager that rewrites the link's domains (a DHCP renewal, say) loses the uplink's names; the
// guard judges "in place" from what resolved holds now, never its own record alone, and sets them again
// (design 08 sign-in-page §7; C-4).
func TestANetworkManagerRewriteOfTheLinksDomainsIsSetAgain(t *testing.T) {
g, _, f, r := aGuardedMachineWithLinks(t, "wlan0")
f.dns = "Link 2 (wlan0): 192.168.1.1\n"
f.domain = "Link 2 (wlan0): lan\n"
f.ip = "default via 10.0.0.1 dev wlan0 metric 100\n"
if err := os.WriteFile(r.UplinkNamesFile, []byte("check.example\n"), 0o644); err != nil {
t.Fatal(err)
}
g.KeepUplinkNames(context.Background())
if len(f.changed) != 1 || strings.Join(f.changed[0], " ") != "resolvectl domain wlan0 lan ~check.example" {
t.Fatalf("the first round gave %v", f.changed)
}
// The network manager rewrites the link's domains: the uplink's name is gone, the applied record is not.
f.domain = "Link 2 (wlan0): lan\n"
f.changed = nil
g.KeepUplinkNames(context.Background())
if len(f.changed) != 1 || strings.Join(f.changed[0], " ") != "resolvectl domain wlan0 lan ~check.example" {
t.Errorf("a rewrite that lost the uplink's name was not set again: %v", f.changed)
}
}
// resolved itself restarts, forgetting every link's domains; the guard's next round, judging from what
// resolved holds now, sets the uplink's names again (design 08 sign-in-page §7; C-4).
func TestAResolvedRestartLosingTheLinksDomainsIsSetAgain(t *testing.T) {
g, _, f, r := aGuardedMachineWithLinks(t, "wlan0")
f.dns = "Link 2 (wlan0): 192.168.1.1\n"
f.domain = "Link 2 (wlan0): lan\n"
f.ip = "default via 10.0.0.1 dev wlan0 metric 100\n"
if err := os.WriteFile(r.UplinkNamesFile, []byte("check.example\n"), 0o644); err != nil {
t.Fatal(err)
}
g.KeepUplinkNames(context.Background())
if len(f.changed) != 1 {
t.Fatalf("the first round gave %v", f.changed)
}
// resolved restarts: every link's domains are gone, the guard's applied record is not.
f.domain = "Link 2 (wlan0):\n"
f.changed = nil
g.KeepUplinkNames(context.Background())
if len(f.changed) != 1 || strings.Join(f.changed[0], " ") != "resolvectl domain wlan0 ~check.example" {
t.Errorf("a restarted resolved was not given the uplink's names again: %v", f.changed)
}
}
// A guard restarted with an applied file takes the uplink's names off the link it names, never inferring
// which (design 08 sign-in-page §8, §9; R-6).
func TestARestartedGuardTakesTheUplinkNamesOffTheLinkItNames(t *testing.T) {
g, _, f, r := aGuardedMachineWithLinks(t, "wlan0", "wlan1")
f.dns = "Link 2 (wlan0): 192.168.1.1\n"
f.domain = "Link 2 (wlan0): lan ~check.example\nLink 3 (wlan1):\n"
f.ip = "default via 10.1.0.1 dev wlan1 metric 50\n" // the route has already moved to wlan1
applied := UplinkApplied{Names: []string{"check.example"}, Link: "wlan0", At: time.Now()}
raw, _ := json.Marshal(applied)
if err := os.WriteFile(r.UplinkNamesAppliedFile, raw, 0o644); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(r.UplinkNamesFile, []byte("check.example\n"), 0o644); err != nil {
t.Fatal(err)
}
g.applied = ReadUplinkApplied(r.UplinkNamesAppliedFile) // what the guard does at its start
g.KeepUplinkNames(context.Background())
if len(f.changed) != 2 || strings.Join(f.changed[0], " ") != "resolvectl domain wlan0 lan" ||
strings.Join(f.changed[1], " ") != "resolvectl domain wlan1 ~check.example" {
t.Errorf("the restarted guard did %v", f.changed)
}
}
// A link holding only the uplink's names is still given its default route back while the mesh's resolvers
// are silent: the guard's own names are left out of whether it is judged `route` routed (design 08
// sign-in-page §7, §9; DMC-2; issue 1981's AC1; R-7).
func TestALinkOfOnlyUplinkNamesStillGetsItsDefaultRouteBack(t *testing.T) {
g, _, f, r := aGuardedMachineWithLinks(t, "tun0")
g.Resolver.Answers = func(context.Context, string) bool { return false } // the mesh is silent
f.dns = "Global: 10.42.0.1\nLink 7 (tun0): 10.9.0.1\n"
f.domain = "Global: ~.\nLink 7 (tun0): ~check.example\n" // only the uplink's name, no search domain
f.defaults = "Link 7 (tun0): no\n"
applied := UplinkApplied{Names: []string{"check.example"}, Link: "tun0", At: time.Now()}
raw, _ := json.Marshal(applied)
if err := os.WriteFile(r.UplinkNamesAppliedFile, raw, 0o644); err != nil {
t.Fatal(err)
}
g.KeepRoutes(context.Background())
if len(f.changed) != 1 || strings.Join(f.changed[0], " ") != "resolvectl default-route tun0 true" {
t.Errorf("the fallback did %v, want tun0 given its default route back", f.changed)
}
}
// A refusal by resolved is journalled once per change, never every round (design 08 sign-in-page §8; R-8).
func TestARefusalByResolvedIsJournalledOncePerChange(t *testing.T) {
g, _, f, r := aGuardedMachineWithLinks(t, "wlan0")
f.dns = "Link 2 (wlan0): 192.168.1.1\n"
f.ip = "default via 10.0.0.1 dev wlan0 metric 100\n"
if err := os.WriteFile(r.UplinkNamesFile, []byte("check.example\n"), 0o644); err != nil {
t.Fatal(err)
}
refuse := true
g.Resolver.Change = func(ctx context.Context, name string, args ...string) (string, error) {
if refuse && len(args) > 0 && args[0] == "domain" {
return "", errors.New("refused: not a domain mesh owns")
}
return f.change(ctx, name, args...)
}
var said []string
g.Log = func(format string, a ...any) { said = append(said, fmt.Sprintf(format, a...)) }
g.KeepUplinkNames(context.Background())
g.KeepUplinkNames(context.Background()) // the file and the link are unchanged: no new refusal to say
count := 0
for _, s := range said {
if strings.Contains(s, "refuses") {
count++
}
}
if count != 1 {
t.Errorf("the refusal was journalled %d times, want once: %v", count, said)
}
}
// The guard writes Resolver.FallbackFile at each of ADR 0688's two turns, and once more at its own first
// round, since it goes at every boot (design 08 sign-in-page §8; S-N5, R2-2; R-9).
func TestTheGuardWritesTheFallbackFileAtEachTurnAndItsFirstRound(t *testing.T) {
g, now, f := aGuardedMachine(t)
meshAnswers := true
g.Resolver.Answers = func(context.Context, string) bool { return meshAnswers }
f.dns = "Global: 10.42.0.1\n"
f.domain = "Global: ~.\n"
// The first round, the mesh answering, writes the file although nothing changed: since is the first
// round's time, never the zero time (design 08 sign-in-page note (c)).
g.KeepRoutes(context.Background())
first := ReadFallback(g.Resolver.FallbackFile)
if first.Silent || !first.Since.Equal(*now) {
t.Fatalf("the first round says %+v, want not silent since %v", first, *now)
}
// A second round with nothing changed does not move `since`.
*now = now.Add(time.Second)
g.KeepRoutes(context.Background())
if again := ReadFallback(g.Resolver.FallbackFile); !again.Since.Equal(first.Since) {
t.Errorf("an unchanged round moved since: %v, was %v", again.Since, first.Since)
}
// The mesh goes silent: the turn is written with the new since.
*now = now.Add(time.Second)
meshAnswers = false
g.KeepRoutes(context.Background())
silentState := ReadFallback(g.Resolver.FallbackFile)
if !silentState.Silent || !silentState.Since.Equal(*now) {
t.Errorf("the silent turn is %+v, want silent since %v", silentState, *now)
}
// It answers again: the other turn.
*now = now.Add(time.Second)
meshAnswers = true
g.KeepRoutes(context.Background())
answering := ReadFallback(g.Resolver.FallbackFile)
if answering.Silent || !answering.Since.Equal(*now) {
t.Errorf("the answering turn is %+v, want not silent since %v", answering, *now)
}
}
// routes answers uplink_names with the applied list's names resolved holds on that link now, resolved's
// refusal, and mesh_resolvers from the fallback file (design 08 sign-in-page §2, §9; R-9).
func TestRoutesAnswersUplinkNamesAndMeshResolvers(t *testing.T) {
f := &fakeResolved{dns: "Link 2 (wlan0): 192.168.1.1\n", domain: "Link 2 (wlan0): lan ~check.example\n"}
r := aMachine(t, f, "wlan0")
applied := UplinkApplied{Names: []string{"check.example", "not-held.example"}, Link: "wlan0", Refused: "refused once"}
raw, _ := json.Marshal(applied)
if err := os.WriteFile(r.UplinkNamesAppliedFile, raw, 0o644); err != nil {
t.Fatal(err)
}
since := time.Date(2026, 11, 24, 10, 0, 0, 0, time.UTC)
fb, _ := json.Marshal(FallbackState{Silent: true, Since: since})
if err := os.WriteFile(r.FallbackFile, fb, 0o644); err != nil {
t.Fatal(err)
}
routes, err := r.Routes(context.Background())
if err != nil {
t.Fatal(err)
}
un := r.UplinkNamesField(routes)
if strings.Join(un.Names, ",") != "check.example" || un.Link != "wlan0" || un.Refused != "refused once" {
t.Errorf("uplink_names is %+v", un)
}
mr := r.MeshResolversField()
if !mr.Silent || mr.Since != since.UTC().Format(time.RFC3339) {
t.Errorf("mesh_resolvers is %+v", mr)
}
}
// A network joined while the mesh's resolvers are silent keeps its default route, and loses it once one answers.
// (1981/AC2)
func TestANetworkJoinedWhileTheMeshIsSilentKeepsItsDefaultRoute(t *testing.T) {
g, _, f := aGuardedMachine(t)
meshAnswers := false
g.Resolver.Answers = func(context.Context, string) bool { return meshAnswers }
f.dns = "Global: 10.42.0.1\nLink 2 (wlan0): 192.168.1.1\n"
f.domain = "Global: ~.\n"
f.defaults = "Link 2 (wlan0): yes\n"
g.KeepRoutes(context.Background())
if len(f.changed) != 0 {
t.Errorf("changed %v while the mesh was silent", f.changed)
}
meshAnswers = true
g.KeepRoutes(context.Background())
if len(f.changed) != 1 || strings.Join(f.changed[0], " ") != "resolvectl default-route wlan0 false" {
t.Errorf("changed %v once the mesh answered", f.changed)
}
}
@@ -47,6 +47,9 @@ func guard() error {
return err
}
g.writeHistory()
// Read what it applied last, so a restart takes the uplink's names off the link it names, never
// inferring which (design 08 sign-in-page §8).
g.applied = ReadUplinkApplied(g.Resolver.UplinkNamesAppliedFile)
go g.Run(ctx)
return g.Serve(ctx, Socket)
}
@@ -60,6 +63,25 @@ func arg(a map[string]any, k string) string {
return v
}
// stringArray declares an input as an array of strings, as the seat's definition says `names` is (design 08
// sign-in-page C-6, DQ-12): never a string a caller must separate by hand.
func stringArray(description string) map[string]any {
return map[string]any{"type": "array", "items": map[string]any{"type": "string"}, "description": description}
}
// arrayArg reads an argument declared with stringArray: a JSON array of strings, empty for anything else
// (never comma- or space-split, unlike Split).
func arrayArg(a map[string]any, k string) []string {
list, _ := a[k].([]any)
out := make([]string, 0, len(list))
for _, v := range list {
if s, ok := v.(string); ok {
out = append(out, s)
}
}
return out
}
// verb is one of the seat's verbs: listed as `<seat>.<verb>`, so the runtime serves it on the seat's
// subject, as <node>/node-resolver.<verb>.
func verb(name, description string, input map[string]any, run func(a map[string]any) (any, error)) stdio.Tool {
@@ -78,7 +100,8 @@ func tools(r *Resolver, history string) []stdio.Tool {
if err != nil {
return nil, err
}
return map[string]any{"mesh": routes.Mesh, "links": routes.Links, "outside_writes": ReadHistory(history)}, nil
answer := r.RoutesAnswer(routes, ReadHistory(history))
return &answer, nil
}),
verb("route", "Send these domains, and every name under them, to these servers over this link, and only "+
"them: the link never answers other names, and the mesh's own domain is refused. Replaces whatever the "+
@@ -93,5 +116,11 @@ func tools(r *Resolver, history string) []stdio.Tool {
"when the link has none. (a)",
map[string]any{"link": str("the network link, by name")},
func(a map[string]any) (any, error) { return r.Unroute(ctx, arg(a, "link")) }),
verb("uplink-names", "Give this machine's own resolver the network manager's own check's host names, so a "+
"working network it tests resolves through the network it tests: at most 8, each a host name of "+
"letters, digits, hyphens and dots; an empty list takes them away. Refused, naming the name and why: "+
"not a host name, the root, the mesh's own domain or under it, or more than 8. (a)",
map[string]any{"names": stringArray("the host names, at most 8; an empty array clears them")},
func(a map[string]any) (any, error) { return r.SetUplinkNames(ctx, arrayArg(a, "names")) }),
}
}
@@ -53,6 +53,22 @@ func TestTheManifestSaysWhatTheGuardKeeps(t *testing.T) {
if m.Facts["resolvers"].Path != ResolvConf || m.Facts["kept"].Path != KeptPath || m.Facts["suffix"].Path != SuffixPath {
t.Errorf("the rendered paths are not the ones the guard reads: %+v", m.Facts)
}
// design 08 sign-in-page §7, DQ-1; lead answer L-2: the literal interface name, as netcheck and
// networkmanager already name it.
if m.Facts["private-interface"].Path != PrivateInterfacePath || m.Facts["private-interface"].Template != "mesh0\n" {
t.Errorf("the private interface fact is %+v", m.Facts["private-interface"])
}
// design 08 sign-in-page C-7; ADR 0422 §8, lead answer L-1: a directory needs `unknown`, and this
// one's is "module" (the guard leaves a path it does not know as it is), never "program".
uplinkDir := false
for _, r := range m.Resources {
if r["type"] == "directory" && r["path"] == "/var/lib/node-resolver" {
uplinkDir = r["unknown"] == "module"
}
}
if !uplinkDir {
t.Error("/var/lib/node-resolver's directory resource does not say unknown: module")
}
if m.Facts["resolvers"].Template != m.Facts["kept"].Template {
t.Error("the resolver file and the copy the guard puts back are not one template")
}
@@ -100,7 +116,7 @@ func TestTheManifestSaysWhatTheGuardKeeps(t *testing.T) {
if !guard || !service {
t.Errorf("the guard (root, long-running, its health said) %v; resolved (running, restarted on its drop-in) %v", guard, service)
}
if len(m.Claims) != 1 || m.Claims[0].Name != Seat || strings.Join(m.Claims[0].Serves, " ") != "routes route unroute" {
if len(m.Claims) != 1 || m.Claims[0].Name != Seat || strings.Join(m.Claims[0].Serves, " ") != "routes route unroute uplink-names" {
t.Errorf("the claim is %+v", m.Claims)
}
if len(m.Provides) != 1 || m.Provides[0].Name != "split-dns" || m.Provides[0].Reach != "machine" {
@@ -14,18 +14,40 @@ package main
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"net"
"net/netip"
"os"
"os/exec"
"path/filepath"
"regexp"
"sort"
"strconv"
"strings"
"time"
noderesolver "git.novox.be/novox/mesh-networking/modules/mesh-connectivity-contracts/go/seats/noderesolver"
)
// rfc3339 is a time as the generated contract's answers hold one, RFC 3339, empty for the zero time
// (design 08 sign-in-page C-6, DQ-12).
func rfc3339(t time.Time) string {
if t.IsZero() {
return ""
}
return t.UTC().Format(time.RFC3339)
}
// rfc3339Ptr is the same for a time that may not have happened yet.
func rfc3339Ptr(t *time.Time) string {
if t == nil {
return ""
}
return rfc3339(*t)
}
// Runner runs one command — as root when it changes something — and answers what it printed.
type Runner func(ctx context.Context, name string, args ...string) (string, error)
@@ -85,16 +107,102 @@ type Resolver struct {
NetDir string
// SuffixFile holds the mesh's own domain, which is never routed elsewhere.
SuffixFile string
// Answers says whether one of the mesh's resolvers answers a name now.
Answers func(ctx context.Context, server string) bool
// AnswerWithinFile holds how long one of them is given to answer (the config value answer-within).
AnswerWithinFile string
// PrivateInterfaceFile holds the private network's own interface name, rendered beside SuffixFile
// (design 08 sign-in-page §7, DQ-1): never the private network's interface is the uplink's link.
PrivateInterfaceFile string
// UplinkNamesFile is where the uplink's holder's names are kept, one a line (design 08 sign-in-page §6).
UplinkNamesFile string
// UplinkNamesAppliedFile is what the guard last gave the link carrying the default route (§8).
UplinkNamesAppliedFile string
// FallbackFile is `routes`'s state for ADR 0688's fallback (§8): whether the mesh's resolvers are
// silent, and since when.
FallbackFile string
// WriteUplinkNames writes UplinkNamesFile whole, as root (§6); stood in for in tests.
WriteUplinkNames func(ctx context.Context, content []byte) error
// Now is the clock the uplink-names verb stamps its answer with; stood in for in tests.
Now func() time.Time
}
// ThisResolver is the machine's.
func ThisResolver() *Resolver {
return &Resolver{Change: execRunner, Read: readRunner, NetDir: "/sys/class/net", SuffixFile: SuffixPath}
r := &Resolver{Change: execRunner, Read: readRunner, NetDir: "/sys/class/net", SuffixFile: SuffixPath,
AnswerWithinFile: AnswerWithinPath, PrivateInterfaceFile: PrivateInterfacePath,
UplinkNamesFile: UplinkNamesPath, UplinkNamesAppliedFile: UplinkNamesAppliedPath, FallbackFile: Fallback,
Now: time.Now}
r.Answers = r.asks
r.WriteUplinkNames = r.writeUplinkNamesFile
return r
}
// AnswerWithinPath is the file the mesh renders the config value answer-within into, as `seconds=<n>`.
const AnswerWithinPath = "/etc/node-resolver/answer-within"
// DefaultAnswerWithin is the config value's default, used until the mesh has rendered the file.
const DefaultAnswerWithin = time.Second
// answerWithin is how long one of the mesh's resolvers is given to answer the guard's question, read each
// round, so a changed config value holds from the next round on.
func (r *Resolver) answerWithin() time.Duration {
raw, err := os.ReadFile(r.AnswerWithinFile)
if err != nil {
return DefaultAnswerWithin
}
for _, line := range strings.Split(string(raw), "\n") {
if v, ok := strings.CutPrefix(strings.TrimSpace(line), "seconds="); ok {
if n, err := strconv.ParseFloat(v, 64); err == nil && n > 0 {
return time.Duration(n * float64(time.Second))
}
}
}
return DefaultAnswerWithin
}
// asks one of the mesh's resolvers a name under the mesh's own domain, straight over the network and not
// through resolved: any answer, a name not found included, is an answer; only silence is not.
func (r *Resolver) asks(ctx context.Context, server string) bool {
ctx, cancel := context.WithTimeout(ctx, r.answerWithin())
defer cancel()
ask := &net.Resolver{PreferGo: true, Dial: func(ctx context.Context, network, _ string) (net.Conn, error) {
var d net.Dialer
if _, _, err := net.SplitHostPort(server); err == nil {
return d.DialContext(ctx, network, server)
}
return d.DialContext(ctx, network, net.JoinHostPort(server, "53"))
}}
_, err := ask.LookupHost(ctx, "node-resolver-asks."+r.suffix())
var dnsErr *net.DNSError
return err == nil || (errors.As(err, &dnsErr) && dnsErr.IsNotFound)
}
// SuffixPath is the file the mesh renders the mesh's own domain into (the manifest's fact `suffix`).
const SuffixPath = "/etc/node-resolver/suffix"
// PrivateInterfacePath is the file the mesh renders the private network's own interface name into,
// beside SuffixPath (the manifest's fact `private-interface`; design 08 sign-in-page §7, DQ-1). The fact's
// template is the literal `mesh0` (lead answer L-2): the live interface, named the same way already by
// netcheck's `TunnelInterface` and networkmanager's `unmanaged-devices`; one value every module reads
// instead is the thorough fix, carried as a finding outside this milestone.
const PrivateInterfacePath = "/etc/node-resolver/private-interface"
// UplinkNamesPath is where `uplink-names` keeps the host names, one a line, whole (design 08 sign-in-page
// §6): root's, mode 0644, written through `sudo -n install` then `sudo -n mv -f`.
const UplinkNamesPath = "/var/lib/node-resolver/uplink-names"
// UplinkNamesAppliedPath is what the guard last gave the link carrying the default route (§8): the list,
// the link, when, and resolved's refusal or empty.
const UplinkNamesAppliedPath = "/var/lib/node-resolver/uplink-names.applied"
// privateInterface is the private network's own interface name, as the mesh rendered it; empty before it
// has (DQ-1).
func (r *Resolver) privateInterface() string {
raw, _ := os.ReadFile(r.PrivateInterfaceFile)
return strings.TrimSpace(string(raw))
}
// Scope is one place resolved sends names: the machine's global servers (the mesh's resolvers), or a link.
type Scope struct {
Link string `json:"link,omitempty"`
@@ -103,6 +211,9 @@ type Scope struct {
Domains []string `json:"domains"`
// DefaultRoute is whether names no domain routes may also go here. Only the mesh's resolvers are.
DefaultRoute *bool `json:"default_route,omitempty"`
// routed is a link given its domains by `route`: every one a routing domain, as Route writes them.
routed bool
}
// Routes is what resolved sends where.
@@ -132,6 +243,17 @@ func perScope(out string) (global []string, links map[string][]string) {
return global, links
}
// onlyRouting is whether a link's domains are all routing domains, as `route` gives them; a network manager
// gives a network's search domains, without the `~`.
func onlyRouting(domains []string) bool {
for _, d := range domains {
if !strings.HasPrefix(d, "~") {
return false
}
}
return len(domains) > 0
}
func unrouted(domains []string) []string {
out := make([]string, 0, len(domains))
for _, d := range domains {
@@ -162,8 +284,20 @@ func (r *Resolver) Routes(ctx context.Context) (*Routes, error) {
}
}
sort.Strings(names)
// The guard's own uplink names (design 08 sign-in-page §7, DMC-2) are left out of whether a link is
// judged `route` routed: a link holding only those names is still the fallback's to give a default
// route back while the mesh's resolvers are silent, never one the fallback takes for a VPN's.
applied := ReadUplinkApplied(r.UplinkNamesAppliedFile)
marked := map[string]bool{}
for _, n := range applied.Names {
marked["~"+n] = true
}
for _, name := range names {
s := Scope{Link: name, Servers: lServers[name], Domains: orEmpty(unrouted(lDomains[name]))}
judge := lDomains[name]
if name == applied.Link && len(marked) > 0 {
judge = withoutMarked(judge, marked)
}
s := Scope{Link: name, Servers: lServers[name], Domains: orEmpty(unrouted(lDomains[name])), routed: onlyRouting(judge)}
if d, ok := lDefault[name]; ok && len(d) > 0 {
yes := d[0] == "yes"
s.DefaultRoute = &yes
@@ -173,6 +307,91 @@ func (r *Resolver) Routes(ctx context.Context) (*Routes, error) {
return out, nil
}
// UplinkNamesField is `routes`'s `uplink_names` field, the generated contract's own type (design 08
// sign-in-page §2, §9, C-6; DQ-3, DQ-12): the applied list's names that resolved holds on that link now,
// never the file's, the link, and resolved's refusal or empty.
func (r *Resolver) UplinkNamesField(routes *Routes) noderesolver.UplinkNames {
applied := ReadUplinkApplied(r.UplinkNamesAppliedFile)
held := []string{}
for _, l := range routes.Links {
if l.Link != applied.Link {
continue
}
has := map[string]bool{}
for _, d := range l.Domains {
has[d] = true
}
for _, n := range applied.Names {
if has[n] {
held = append(held, n)
}
}
}
return noderesolver.UplinkNames{Names: held, Link: applied.Link, Refused: applied.Refused}
}
// MeshResolversField is `routes`'s `mesh_resolvers` field, the generated contract's own type (design 08
// sign-in-page §9, C-6; S-N5, DQ-12): whether the mesh's resolvers are silent now, by ADR 0688's guard, and
// since when.
func (r *Resolver) MeshResolversField() noderesolver.MeshResolvers {
s := ReadFallback(r.FallbackFile)
return noderesolver.MeshResolvers{Silent: s.Silent, Since: rfc3339(s.Since)}
}
// ScopeField is one scope as the generated contract answers it (design 08 sign-in-page C-6, DQ-12).
func ScopeField(s Scope) noderesolver.Scope {
return noderesolver.Scope{Link: s.Link, Servers: orEmpty(s.Servers), Domains: orEmpty(s.Domains),
DefaultRoute: s.DefaultRoute != nil && *s.DefaultRoute}
}
// ScopeFields is every scope as the generated contract answers them.
func ScopeFields(ss []Scope) []noderesolver.Scope {
out := make([]noderesolver.Scope, len(ss))
for i, s := range ss {
out[i] = ScopeField(s)
}
return out
}
// OutsideWriteField is one outside write as the generated contract answers it.
func OutsideWriteField(d Displacement) noderesolver.OutsideWrite {
return noderesolver.OutsideWrite{ID: d.ID, At: rfc3339(d.At), Writer: d.Writer, TakenBy: d.TakenBy,
TakenAt: rfc3339Ptr(d.TakenAt), Ended: rfc3339Ptr(d.Ended), How: d.How}
}
// OutsideWriteFields is every outside write as the generated contract answers them.
func OutsideWriteFields(ds []Displacement) []noderesolver.OutsideWrite {
out := make([]noderesolver.OutsideWrite, len(ds))
for i, d := range ds {
out[i] = OutsideWriteField(d)
}
return out
}
// RoutesAnswer is `routes`'s whole answer, the generated contract's own type (design 08 sign-in-page §2,
// §5, §9, C-6; DQ-12): what this machine's own resolver sends where, the resolver file's outside writes,
// and the uplink's names and the mesh's fallback.
func (r *Resolver) RoutesAnswer(routes *Routes, outside []Displacement) noderesolver.RoutesAnswer {
return noderesolver.RoutesAnswer{
Mesh: ScopeField(routes.Mesh),
Links: ScopeFields(routes.Links),
OutsideWrites: OutsideWriteFields(outside),
UplinkNames: r.UplinkNamesField(routes),
MeshResolvers: r.MeshResolversField(),
}
}
// withoutMarked is domains without those marked (design 08 sign-in-page DMC-2).
func withoutMarked(domains []string, marked map[string]bool) []string {
out := make([]string, 0, len(domains))
for _, d := range domains {
if !marked[d] {
out = append(out, d)
}
}
return out
}
func orEmpty(s []string) []string {
if s == nil {
return []string{}
@@ -181,12 +400,8 @@ func orEmpty(s []string) []string {
}
// Routed is what a route did.
type Routed struct {
Link string `json:"link"`
Servers []string `json:"servers"`
Domains []string `json:"domains"`
Said string `json:"said"`
}
// Routed is `route`'s answer, the generated contract's own type (design 08 sign-in-page C-6, DQ-12).
type Routed = noderesolver.RouteAnswer
var (
linkName = regexp.MustCompile(`^[A-Za-z0-9_.:@-]{1,15}$`)
@@ -301,6 +516,216 @@ func Servers(given []string) ([]string, error) {
return out, nil
}
// hostNameLabel matches one label of a host name: letters, digits and hyphens.
var hostNameLabel = regexp.MustCompile(`^[a-z0-9-]+$`)
// HostNames checks the names given to `uplink-names` (design 08 sign-in-page §2): 0 to 8 host names, each
// 1 to 253 bytes of letters, digits, hyphens and dots, lower-cased. Refused, naming the name and the
// reason: a name that is not a host name (a wildcard, a trailing dot, a label over 63 bytes), the root,
// the mesh's own domain or a name under it (ADR 0247 §12's rule for `route`, for the same reason), or more
// than 8 names.
func (r *Resolver) HostNames(given []string) ([]string, error) {
suffix := r.suffix()
out := make([]string, 0, len(given))
for _, n := range given {
n = strings.ToLower(strings.TrimSpace(n))
if n == "" || n == "." {
return nil, errors.New("the root is not a host name: only the mesh's resolvers answer every name")
}
if strings.Contains(n, "*") {
return nil, fmt.Errorf("%q is not a host name: a wildcard", n)
}
if strings.HasSuffix(n, ".") {
return nil, fmt.Errorf("%q is not a host name: a trailing dot", n)
}
if len(n) > 253 {
return nil, fmt.Errorf("%q is not a host name: over 253 bytes", n)
}
for _, label := range strings.Split(n, ".") {
if len(label) > 63 {
return nil, fmt.Errorf("%q is not a host name: a label over 63 bytes", n)
}
if !hostNameLabel.MatchString(label) {
return nil, fmt.Errorf("%q is not a host name", n)
}
}
if n == suffix || strings.HasSuffix(n, "."+suffix) {
return nil, fmt.Errorf("%q is the mesh's own domain: the mesh's names are answered by the mesh's resolvers alone", n)
}
out = append(out, n)
}
if len(out) > 8 {
return nil, fmt.Errorf("%d names; at most 8", len(out))
}
return out, nil
}
// WriteUplinkNamesBound is how long the names file's write (install, then mv) is given before it is
// abandoned (design 08 sign-in-page §6, C-8): a stated constant, since nothing here says it is a setting
// the machine differs on.
const WriteUplinkNamesBound = 15 * time.Second
// writeUplinkNamesFile writes UplinkNamesFile whole (design 08 sign-in-page §6): `sudo -n install -m 0644
// -o root -g root /dev/stdin <file>.new` with the lines on its input, then `sudo -n mv -f <file>.new
// <file>`, so a reader never sees it half-written. As root (the guard never calls this; only the verb,
// over the bus, does), both run unescalated.
func (r *Resolver) writeUplinkNamesFile(ctx context.Context, content []byte) error {
ctx, cancel := context.WithTimeout(ctx, WriteUplinkNamesBound)
defer cancel()
newPath := r.UplinkNamesFile + ".new"
program, args := escalated(os.Getuid(), "install", []string{"-m", "0644", "-o", "root", "-g", "root", "/dev/stdin", newPath})
cmd := exec.CommandContext(ctx, program, args...)
cmd.Stdin = bytes.NewReader(content)
var stderr bytes.Buffer
cmd.Stderr = &stderr
if err := cmd.Run(); err != nil {
// Past the bound, name it and say the file was left as it was (review r2 (3)), never the bare
// signal the deadline killed the process with.
if ctx.Err() == context.DeadlineExceeded {
return fmt.Errorf("the names file's write did not finish within %s; it was left as it was", WriteUplinkNamesBound)
}
if said := strings.TrimSpace(stderr.String()); said != "" {
return fmt.Errorf("install: %s", said)
}
return fmt.Errorf("install failed: %w", err)
}
if _, err := r.Change(ctx, "mv", "-f", newPath, r.UplinkNamesFile); err != nil {
if ctx.Err() == context.DeadlineExceeded {
return fmt.Errorf("the names file's write did not finish within %s; it was left as it was", WriteUplinkNamesBound)
}
return err
}
return nil
}
// SetUplinkNames writes the host names the uplink's holder gives for its network's own check, through
// UplinkNamesFile (§6), and answers them with the generated contract's own type (C-6, DQ-12): the link
// carrying the default route now (§2, DQ-2), empty when there is no such link, and when the list was set.
func (r *Resolver) SetUplinkNames(ctx context.Context, given []string) (*noderesolver.UplinkNamesAnswer, error) {
names, err := r.HostNames(given)
if err != nil {
return nil, err
}
content := []byte(strings.Join(names, "\n"))
if len(names) > 0 {
content = append(content, '\n')
}
if err := r.WriteUplinkNames(ctx, content); err != nil {
return nil, err
}
link := ""
if routes, rerr := r.Routes(ctx); rerr == nil {
link, _ = r.DefaultRouteLink(ctx, routes)
}
return &noderesolver.UplinkNamesAnswer{Names: names, Link: link, SetAt: rfc3339(r.Now())}, nil
}
// ReadUplinkNames reads the host names `uplink-names` last wrote, one a line; empty before it has.
func ReadUplinkNames(path string) []string {
raw, err := os.ReadFile(path)
if err != nil {
return []string{}
}
out := []string{}
for _, line := range strings.Split(string(raw), "\n") {
if line = strings.TrimSpace(line); line != "" {
out = append(out, line)
}
}
return out
}
// UplinkApplied is what the guard last gave the link carrying the default route (design 08 sign-in-page
// §8): the list, the link, when, and resolved's refusal or empty.
type UplinkApplied struct {
Names []string `json:"names"`
Link string `json:"link"`
At time.Time `json:"at"`
Refused string `json:"refused,omitempty"`
}
// ReadUplinkApplied reads what the guard applied last; the zero value before its first round, or after a
// restart with nothing written yet.
func ReadUplinkApplied(path string) UplinkApplied {
raw, err := os.ReadFile(path)
if err != nil {
return UplinkApplied{}
}
var a UplinkApplied
if json.Unmarshal(raw, &a) != nil {
return UplinkApplied{}
}
return a
}
// kernelDefaultRoute is one of the kernel's default routes: its link and metric (the lowest wins).
type kernelDefaultRoute struct {
link string
metric int
}
// kernelDefaultRoutes reads the kernel's default routes for one family ("-4" or "-6"); a route the kernel
// names no metric for gets 0, its own highest priority.
func (r *Resolver) kernelDefaultRoutes(ctx context.Context, family string) ([]kernelDefaultRoute, error) {
out, err := r.Read(ctx, "ip", family, "route", "show", "default")
if err != nil {
return nil, fmt.Errorf("the kernel's default routes: %w", err)
}
var routes []kernelDefaultRoute
for _, line := range strings.Split(out, "\n") {
fields := strings.Fields(line)
if len(fields) == 0 || fields[0] != "default" {
continue
}
var kr kernelDefaultRoute
for i := 0; i+1 < len(fields); i++ {
switch fields[i] {
case "dev":
kr.link = fields[i+1]
case "metric":
if n, err := strconv.Atoi(fields[i+1]); err == nil {
kr.metric = n
}
}
}
if kr.link != "" {
routes = append(routes, kr)
}
}
return routes, nil
}
// DefaultRouteLink is the link that carries the default route now (design 08 sign-in-page §7, §9; DQ-1,
// DQ-2): among the kernel's IPv4 default routes, or the IPv6 ones when there is no IPv4 one, the one with
// the lowest metric whose link is neither one `route` routed (a VPN's, read from resolved) nor the private
// network's own interface; empty when there is no such link.
func (r *Resolver) DefaultRouteLink(ctx context.Context, routes *Routes) (string, error) {
private := r.privateInterface()
routed := map[string]bool{}
for _, l := range routes.Links {
routed[l.Link] = l.routed
}
candidates, err := r.kernelDefaultRoutes(ctx, "-4")
if err != nil {
return "", err
}
if len(candidates) == 0 {
if candidates, err = r.kernelDefaultRoutes(ctx, "-6"); err != nil {
return "", err
}
}
best, bestMetric := "", 0
for _, c := range candidates {
if c.link == private || routed[c.link] {
continue
}
if best == "" || c.metric < bestMetric {
best, bestMetric = c.link, c.metric
}
}
return best, nil
}
// Route sends these domains, and every name under them, to these servers over this link — and only them.
// Whatever the link was given before is replaced. resolved forgets it when the link goes.
func (r *Resolver) Route(ctx context.Context, link string, domains, servers []string) (*Routed, error) {
@@ -335,11 +760,8 @@ func (r *Resolver) Route(ctx context.Context, link string, domains, servers []st
Said: fmt.Sprintf("%d domains go to %d servers over %s; every other name to the mesh's resolvers", len(ds), len(ss), link)}, nil
}
// Unrouted is what taking a route away did.
type Unrouted struct {
Link string `json:"link"`
Said string `json:"said"`
}
// Unrouted is `unroute`'s answer, the generated contract's own type (design 08 sign-in-page C-6, DQ-12).
type Unrouted = noderesolver.UnrouteAnswer
// Unroute takes one link's route away. A link that has gone has nothing to take away.
func (r *Resolver) Unroute(ctx context.Context, link string) (*Unrouted, error) {
@@ -376,3 +798,37 @@ func (r *Resolver) OnlyTheMeshIsADefaultRoute(ctx context.Context) ([]string, er
}
return changed, nil
}
// TheMeshAnswers says whether one of the mesh's resolvers answers now, asking them all at once. Behind a
// network's sign-in page none does: the private network is out of reach until the person signs in.
func (r *Resolver) TheMeshAnswers(ctx context.Context, servers []string) bool {
answered := make(chan bool, len(servers))
for _, s := range servers {
go func() { answered <- r.Answers(ctx, s) }()
}
for range servers {
if <-answered {
return true
}
}
return false
}
// ADefaultRouteAgain lets every link a network manager gave servers answer every name again, while the
// mesh's resolvers are silent: a network's own servers are then the only ones that can find its sign-in
// page. Read from what resolved holds, not from what the guard did, so it holds after the guard restarts.
// A link `route` routed (a VPN's) is never one, and one that already answers every name is left alone.
// Answers the links it changed.
func (r *Resolver) ADefaultRouteAgain(ctx context.Context, routes *Routes) ([]string, error) {
var changed []string
for _, l := range routes.Links {
if l.routed || l.DefaultRoute == nil || *l.DefaultRoute {
continue
}
if _, err := r.Change(ctx, "resolvectl", "default-route", l.Link, "true"); err != nil {
return changed, err
}
changed = append(changed, l.Link)
}
return changed, nil
}
@@ -2,19 +2,30 @@ package main
import (
"context"
"fmt"
"net"
"os"
"path/filepath"
"strings"
"testing"
"time"
)
// fakeResolved answers resolvectl as systemd-resolved would, and records what was asked of it.
// fakeResolved answers resolvectl, and `ip route show default`, as the machine would, and records what was
// asked of it.
type fakeResolved struct {
dns, domain, defaults string
ip string
changed [][]string
}
func (f *fakeResolved) read(_ context.Context, name string, args ...string) (string, error) {
if name == "ip" {
if len(args) > 0 && args[0] == "-6" {
return "", nil
}
return f.ip, nil
}
switch args[0] {
case "dns":
return f.dns, nil
@@ -44,7 +55,15 @@ func aMachine(t *testing.T, f *fakeResolved, links ...string) *Resolver {
if err := os.WriteFile(suffix, []byte("internal\n"), 0o644); err != nil {
t.Fatal(err)
}
return &Resolver{Change: f.change, Read: f.read, NetDir: filepath.Join(dir, "net"), SuffixFile: suffix}
return &Resolver{Change: f.change, Read: f.read, NetDir: filepath.Join(dir, "net"), SuffixFile: suffix,
PrivateInterfaceFile: filepath.Join(dir, "private-interface"),
UplinkNamesFile: filepath.Join(dir, "uplink-names"),
UplinkNamesAppliedFile: filepath.Join(dir, "uplink-names.applied"),
FallbackFile: filepath.Join(dir, "fallback.json"),
Now: func() time.Time { return time.Date(2026, 11, 24, 12, 0, 0, 0, time.UTC) },
WriteUplinkNames: func(_ context.Context, content []byte) error {
return os.WriteFile(filepath.Join(dir, "uplink-names"), content, 0o644)
}}
}
// A route sends the domains to the servers over the link, and only them: the link is first told it is
@@ -170,3 +189,187 @@ func TestChangesAreEscalatedOnlyWhenNotRoot(t *testing.T) {
t.Errorf("as the account: %s %v", p, a)
}
}
// Given names, uplink-names writes the file one a line and answers them (design 08 sign-in-page §2, §6;
// R-1).
// Past the names file write's bound, the refusal names it and says the file was left as it was, never the
// bare signal the deadline killed the process with (design 08 sign-in-page §6; C-8, review r2 (3)).
func TestTheWriteRefusesNamingTheBoundOnTheDeadline(t *testing.T) {
r := aMachine(t, &fakeResolved{}, "tun0")
ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(-time.Minute))
defer cancel()
err := r.writeUplinkNamesFile(ctx, []byte("check.example\n"))
if err == nil || !strings.Contains(err.Error(), WriteUplinkNamesBound.String()) || !strings.Contains(err.Error(), "left as it was") {
t.Errorf("the refusal is %v, want it to name %s and say the file was left as it was", err, WriteUplinkNamesBound)
}
}
func TestUplinkNamesWritesTheFileAndAnswersThem(t *testing.T) {
f := &fakeResolved{}
r := aMachine(t, f, "tun0")
got, err := r.SetUplinkNames(context.Background(), []string{"Check.Example", "check2.example"})
if err != nil {
t.Fatal(err)
}
if strings.Join(got.Names, " ") != "check.example check2.example" {
t.Errorf("the answer names %v", got.Names)
}
if got.SetAt == "" {
t.Error("set_at was not stamped")
}
raw, err := os.ReadFile(r.UplinkNamesFile)
if err != nil {
t.Fatal(err)
}
if string(raw) != "check.example\ncheck2.example\n" {
t.Errorf("the file holds %q", raw)
}
}
// An empty list empties the file (design 08 sign-in-page §2; R-2).
func TestAnEmptyListEmptiesTheUplinkNamesFile(t *testing.T) {
f := &fakeResolved{}
r := aMachine(t, f, "tun0")
if _, err := r.SetUplinkNames(context.Background(), []string{"check.example"}); err != nil {
t.Fatal(err)
}
got, err := r.SetUplinkNames(context.Background(), nil)
if err != nil {
t.Fatal(err)
}
if len(got.Names) != 0 {
t.Errorf("the answer names %v, not empty", got.Names)
}
raw, err := os.ReadFile(r.UplinkNamesFile)
if err != nil {
t.Fatal(err)
}
if string(raw) != "" {
t.Errorf("the file holds %q, not emptied", raw)
}
}
// Each refusal of §2 is answered naming the name and the reason, and writes nothing (design 08
// sign-in-page §2; acceptance test 4; R-3).
func TestEachRefusalOfUplinkNamesIsNamedAndWritesNothing(t *testing.T) {
for name, c := range map[string]struct{ given, says string }{
"the root": {".", "root"},
"empty string": {"", "root"},
"a wildcard": {"*.example", "wildcard"},
"a trailing dot": {"check.example.", "trailing dot"},
"a label over 63": {strings.Repeat("a", 64) + ".example", "label over 63 bytes"},
"the mesh's domain": {"internal", "mesh's own domain"},
"under it": {"check.internal", "mesh's own domain"},
"not a host name": {"a b/c", "not a host name"},
} {
f := &fakeResolved{}
r := aMachine(t, f, "tun0")
_, err := r.SetUplinkNames(context.Background(), []string{c.given})
if err == nil || !strings.Contains(err.Error(), c.says) {
t.Errorf("%s: %v", name, err)
}
if _, statErr := os.Stat(r.UplinkNamesFile); statErr == nil {
t.Errorf("%s: the file was written: %s", name, contentOf(t, r.UplinkNamesFile))
}
}
f := &fakeResolved{}
r := aMachine(t, f, "tun0")
nine := make([]string, 9)
for i := range nine {
nine[i] = fmt.Sprintf("check%d.example", i)
}
_, err := r.SetUplinkNames(context.Background(), nine)
if err == nil || !strings.Contains(err.Error(), "at most 8") {
t.Errorf("more than 8 names: %v", err)
}
if _, statErr := os.Stat(r.UplinkNamesFile); statErr == nil {
t.Error("more than 8 names: the file was written")
}
}
// The link carrying the default route is the lowest-metric one that is neither routed (a VPN's) nor the
// private network's; none when there is none (design 08 sign-in-page §7, §9; DQ-1, DQ-2).
func TestDefaultRouteLinkIsTheLowestMetricOneThatIsNeitherRoutedNorPrivate(t *testing.T) {
f := &fakeResolved{}
r := aMachine(t, f, "tun0", "wlan0", "mesh0")
if err := os.WriteFile(r.PrivateInterfaceFile, []byte("mesh0\n"), 0o644); err != nil {
t.Fatal(err)
}
f.ip = "default via 10.0.0.1 dev wlan0 metric 600\ndefault via 10.1.0.1 dev mesh0 metric 50\n"
f.dns = "Link 7 (tun0): 10.9.0.1\n"
f.domain = "Link 7 (tun0): ~corp.example\n"
routes, err := r.Routes(context.Background())
if err != nil {
t.Fatal(err)
}
link, err := r.DefaultRouteLink(context.Background(), routes)
if err != nil {
t.Fatal(err)
}
if link != "wlan0" {
t.Errorf("the link is %q, not wlan0 (mesh0 is the private interface)", link)
}
// A link `route` routed is also never chosen.
f.ip = "default via 10.0.0.1 dev tun0 metric 10\ndefault via 10.2.0.1 dev wlan0 metric 600\n"
link, err = r.DefaultRouteLink(context.Background(), routes)
if err != nil {
t.Fatal(err)
}
if link != "wlan0" {
t.Errorf("the link is %q, not wlan0 (tun0 is routed)", link)
}
// None when there is none.
f.ip = "default via 10.0.0.1 dev tun0 metric 10\ndefault via 10.1.0.1 dev mesh0 metric 50\n"
if link, err = r.DefaultRouteLink(context.Background(), routes); err != nil || link != "" {
t.Errorf("the link is %q, want none", link)
}
}
// One of the mesh's resolvers answers when it says anything, a name not found included; one that is silent
// does not, and the guard does not wait on it past the config value answer-within, read from the file the
// mesh renders, or a second before it has. (1981/AC3)
func TestAResolverAnswersUnlessItIsSilent(t *testing.T) {
conn, err := net.ListenPacket("udp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
defer conn.Close()
go func() {
buf := make([]byte, 512)
for {
n, from, err := conn.ReadFrom(buf)
if err != nil {
return
}
reply := append([]byte{}, buf[:n]...)
reply[2], reply[3] = 0x81, 0x83 // a reply, recursion available, the name not found
conn.WriteTo(reply, from)
}
}()
silent, err := net.ListenPacket("udp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
defer silent.Close()
r := aMachine(t, &fakeResolved{})
r.AnswerWithinFile = filepath.Join(t.TempDir(), "answer-within")
if got := r.answerWithin(); got != DefaultAnswerWithin {
t.Errorf("before the file is rendered, a resolver is given %v", got)
}
if err := os.WriteFile(r.AnswerWithinFile, []byte("# written by the mesh\nseconds=0.1\n"), 0o644); err != nil {
t.Fatal(err)
}
if got := r.answerWithin(); got != 100*time.Millisecond {
t.Errorf("with answer-within 0.1, a resolver is given %v", got)
}
if !r.asks(context.Background(), conn.LocalAddr().String()) {
t.Error("a resolver that said the name is not found did not answer")
}
start := time.Now()
if r.asks(context.Background(), silent.LocalAddr().String()) {
t.Error("a silent resolver answered")
}
if took := time.Since(start); took > 300*time.Millisecond {
t.Errorf("a silent resolver was waited on %v", took)
}
}
@@ -0,0 +1,4 @@
# How long, in seconds, the guard gives one of the mesh's resolvers to answer, from the config value
# answer-within, written by the mesh (module systemd-resolved, novox/hq issue 1981). Replaced on every
# push; change the config value, never this file.
seconds=${config:answer-within}
+4 -1
View File
@@ -2,7 +2,10 @@ module systemd-resolved
go 1.26.0
require git.novox.be/novox/mesh-sdk/go v0.0.0-00010101000000-000000000000
require (
git.novox.be/novox/mesh-networking/modules/mesh-connectivity-contracts/go/seats/noderesolver v0.0.0-00010101000000-000000000000
git.novox.be/novox/mesh-sdk/go v0.0.0-00010101000000-000000000000
)
require (
github.com/klauspost/compress v1.20.1 // indirect
+36 -2
View File
@@ -1,6 +1,6 @@
{
"module": "systemd-resolved",
"version": "0.1",
"version": "0.2",
"class": "core",
"upgrade": {
"policy": "record",
@@ -28,7 +28,8 @@
"serves": [
"routes",
"route",
"unroute"
"unroute",
"uplink-names"
]
}
],
@@ -66,6 +67,10 @@
"suffix": {
"path": "/etc/node-resolver/suffix",
"template": "{{.Suffix}}\n"
},
"private-interface": {
"path": "/etc/node-resolver/private-interface",
"template": "mesh0\n"
}
},
"resources": [
@@ -82,6 +87,14 @@
"kind": "unit"
}
},
{
"id": "answer-within",
"type": "file",
"path": "/etc/node-resolver/answer-within",
"mode": "0644",
"trusted": false,
"template": "files/answer-within"
},
{
"id": "guard",
"type": "process",
@@ -94,6 +107,13 @@
"health": {
"kind": "unit"
}
},
{
"id": "uplink-names",
"type": "directory",
"path": "/var/lib/node-resolver",
"mode": "0755",
"unknown": "module"
}
],
"build": {
@@ -108,7 +128,21 @@
"loads": [
"resolver-tools"
]
},
{
"name": "files",
"kind": "archive",
"from": "files"
}
]
},
"config": {
"answer-within": {
"type": "number",
"description": "How long, in seconds, the guard gives one of the mesh's resolvers to answer its question each round (novox/hq issue 1981): while none answers within it, a network's own servers answer every name, so a sign-in page can be found. 1 suits a tunnel's usual round trip; a slower link (tethered, abroad) needs more, or the guard takes a slow mesh for a silent one.",
"minimum": 0.2,
"maximum": 5,
"default": 1
}
}
}
+1
View File
@@ -2,6 +2,7 @@
# *Not:* words with no scope or with (tools). A copy, so a catalogue merge needs nothing else; novox/hq's
# words.py compares it with the glossary. Regenerate with: python3 00-META/checks/words.py --list tools
build machine
captive portal
catalogue
change plan
control plane