From 58236e1b7f9f7aa81a5ad071ecf3ba209297ac3e Mon Sep 17 00:00:00 2001 From: atlas Date: Sun, 22 Nov 2026 15:00:54 +0100 Subject: [PATCH] default the host's swarmctl to the gateway; login takes a callback port --- docs/1-getting-started/setup.md | 20 +++++++- docs/2-handbook/swarm/schedules.md | 2 +- docs/2-handbook/swarm/sso.md | 2 +- docs/2-handbook/swarm/swarmctl-cli.md | 12 ++++- nix/host-modules/swarm-controller.nix | 21 +++++--- nix/module-eval/bao-controller.nix | 12 +++-- nix/vm-tests/full-setup.nix | 1 + nix/vm-tests/full-setup.py | 18 ++++++- swarm-controller/README.md | 7 +-- swarmctl/README.md | 70 ++++++++++++++++----------- swarmctl/src/login.rs | 35 ++++++++++++-- swarmctl/src/main.rs | 48 +++++++++++++++--- 12 files changed, 182 insertions(+), 66 deletions(-) diff --git a/docs/1-getting-started/setup.md b/docs/1-getting-started/setup.md index 750d95953..1a2055c75 100644 --- a/docs/1-getting-started/setup.md +++ b/docs/1-getting-started/setup.md @@ -53,7 +53,8 @@ the `shamir` seal, the restart after the granter, and the browser login. Run `swarmctl setup status` at any point to see how far you have got. It changes nothing, and it works from a script: it exits 0 when every step it can -see has finished. +see has finished. The agent steps (9 and 10) read the controller, so they show `unknown` until +`swarmctl login` has run. ```console # swarmctl setup status @@ -172,12 +173,27 @@ name resolves on the box itself through `/etc/hosts`; from anywhere else it needs a real DNS record. → [`2-handbook/swarm/ui.md`](../2-handbook/swarm/ui.md) Signing in to the forge once through SSO creates your forge account under the -same username. Then, _on the swarm-controller's host_: +same username. Then, _on the swarm-controller's host_, log `swarmctl` in once. The host's +`swarmctl` reaches the controller through the swarm's gateway as your own SSO account, so every +verb that calls the controller needs this login: ```bash +swarmctl login swarmctl forge make-admin mara ``` +`login` prints a URL and waits for the browser's answer on a loopback port of the machine it runs +on. On a host with no browser, forward a port from the machine that has one, then run the login +with that port: + +```bash +ssh -L 8765:127.0.0.1:8765 # on your workstation +swarmctl login --callback-port 8765 # in that ssh session, on the host +``` + +Open the printed URL in the workstation's browser. The login lasts until the refresh token +expires; `swarmctl` then says to run `login` again. + If the forge already has a local account with your username, the first SSO login asks for its forge password once, to link the two. diff --git a/docs/2-handbook/swarm/schedules.md b/docs/2-handbook/swarm/schedules.md index b8b564574..b42688f53 100644 --- a/docs/2-handbook/swarm/schedules.md +++ b/docs/2-handbook/swarm/schedules.md @@ -129,7 +129,7 @@ minute it rewrites every agent's key, so a rewrite that failed converges. Ids are 8 lowercase letters, the same in every agent's key, never reused, and so never equal to a hive schedule's numeric id. -`swarmctl schedule` calls these routes over the controller's socket: +`swarmctl schedule` calls these routes: | method | path | body | | -------- | --------------------- | ------------------------------------------------------------------------------------------------------------------------- | diff --git a/docs/2-handbook/swarm/sso.md b/docs/2-handbook/swarm/sso.md index 50e8dc871..db19fe658 100644 --- a/docs/2-handbook/swarm/sso.md +++ b/docs/2-handbook/swarm/sso.md @@ -147,7 +147,7 @@ token. Its access token carries `authelia.bearer.authz` with the audience `https:///api/`, so the gateway admits it at the controller's API and nowhere else, under the same access rule as a browser session there. Revocation is per account: once authelia stops accepting the account, the -gateway refuses its token too. See [`swarmctl/README.md`](../../../swarmctl/README.md#remote-use-swarmctl-login). +gateway refuses its token too. See [`swarmctl/README.md`](../../../swarmctl/README.md#reaching-the-controller-swarmctl-login). ## What this doesn't do diff --git a/docs/2-handbook/swarm/swarmctl-cli.md b/docs/2-handbook/swarm/swarmctl-cli.md index 4c1ab4c72..c1b113dfe 100644 --- a/docs/2-handbook/swarm/swarmctl-cli.md +++ b/docs/2-handbook/swarm/swarmctl-cli.md @@ -66,7 +66,7 @@ swarm-level operator CLI * `--users-file ` — Host-side path of authelia's users database — that is, the path inside the container, prefixed with the container's root. This is the only user store: it's read before every change and written in place, and `swarm-authelia-bridge` writes the same file. -* `--swarm ` — The swarm's domain, as `https://` or the bare domain. Given, the `agent`, `schedule` and `forge` verbs, and the agent checks and steps of `setup`, go through its gateway as the account `swarmctl login` logged in, instead of over the controller's socket. Falls back to `SWARMCTL_SWARM`; `login` then falls back to `SWARMCTL_LOGIN_DEFAULT_SWARM`, which the swarm-controller nix module sets to its host's own swarm +* `--swarm ` — The swarm's domain, as `https://` or the bare domain. Given, the `agent`, `schedule` and `forge` verbs, and the agent checks and steps of `setup`, go through its gateway as the account `swarmctl login` logged in, instead of over the controller's socket. Falls back to `SWARMCTL_SWARM`; `login` then falls back to `SWARMCTL_LOGIN_DEFAULT_SWARM`. The swarm-controller nix module sets both to its host's own swarm, so there the verbs use the gateway and need `swarmctl login` once; an empty `SWARMCTL_SWARM` or `--swarm ""` puts them back on the controller's socket * `--ca-file ` — A PEM CA certificate to trust beside the system roots, for a swarm whose gateway serves a certificate from the swarm's own CA. Falls back to `SWARMCTL_CA_FILE` @@ -744,7 +744,15 @@ With no `--swarm` or `SWARMCTL_SWARM`, logs in to `SWARMCTL_LOGIN_DEFAULT_SWARM` Opens the swarm's SSO login in your browser (and prints the URL) and receives the answer on a loopback port, so run it where that browser runs. swarmctl keeps the login, mode 0600, under `$XDG_STATE_HOME/swarmctl/` and refreshes it as it's used. To log out, delete that file. -**Usage:** `swarmctl login` +On a host with no browser, forward the callback port from the machine that has one: `ssh -L 8765:127.0.0.1:8765 `, then run `swarmctl login --callback-port 8765` on the host and open the printed URL in that machine's browser. + +**Usage:** `swarmctl login [OPTIONS]` + +###### **Options:** + +* `--callback-port ` — The loopback port the login listens on for the browser's answer. Defaults to a free one, which the login prints + + Default value: `0` diff --git a/nix/host-modules/swarm-controller.nix b/nix/host-modules/swarm-controller.nix index afeef53aa..b42f66112 100644 --- a/nix/host-modules/swarm-controller.nix +++ b/nix/host-modules/swarm-controller.nix @@ -154,11 +154,14 @@ let storeRetry = import ./lib/store-retry.nix { }; tcpOn = deployCfg.swarm-controller.enable && tcpCfg.enable; - # Which swarm `swarmctl login` logs in to when given none: this host's own. - # Read by `login` alone. `SWARMCTL_SWARM` would also move every socket verb - # onto the gateway, where each needs a login. A default, so an operator's - # own value still wins. - loginDefaultEnv = lib.optionalAttrs (swarmDomain != null) { + # The swarm the host's `swarmctl` talks to: this host's own, through the + # gateway, as the operator's own SSO account (`swarmctl login`). The + # controller socket then serves the gateway alone, which always sets + # `Remote-User`. Both are defaults, so an operator's own value wins: an + # empty `SWARMCTL_SWARM` puts the socket verbs back on the socket for + # root. + swarmDefaultEnv = lib.optionalAttrs (swarmDomain != null) { + SWARMCTL_SWARM = "https://${swarmDomain}"; SWARMCTL_LOGIN_DEFAULT_SWARM = "https://${swarmDomain}"; }; @@ -339,7 +342,7 @@ let ) ++ lib.mapAttrsToList ( name: value: "--set-default ${name} ${lib.escapeShellArg value}" - ) loginDefaultEnv + ) swarmDefaultEnv ) } ''; @@ -633,8 +636,10 @@ in the socket itself is `0666`, exactly as hive-c0re publishes the per-agent sockets, and the directory is `0750` owned by the `${clientsGroup}` group. Members of that group (the gateway's - nginx, for `/api/` and `/webhook/forge/`) and root (`swarmctl`, - which bypasses mode bits) can reach the socket; every other local + nginx, for `/api/` and `/webhook/forge/`) and root (which bypasses mode + bits) can reach the socket. The host's `swarmctl` goes through the + gateway by default, so only a root-run verb with an empty + `SWARMCTL_SWARM` opens it; every other local user gets `EACCES` at the directory. What keeps `0666` safe is that the directory holds exactly one socket. Moving this path under a directory that carries anything else — diff --git a/nix/module-eval/bao-controller.nix b/nix/module-eval/bao-controller.nix index 67c9a5cab..71f4cc60e 100644 --- a/nix/module-eval/bao-controller.nix +++ b/nix/module-eval/bao-controller.nix @@ -154,14 +154,16 @@ let or null == "https://matrix.hive.t.local"; } { - # Login-only: `SWARMCTL_SWARM` would move every socket verb onto the - # gateway. The socket variable is the control that the wrapper text was - # found at all. - name = "the host's swarmctl logs in to its own swarm by default, and its other verbs stay on the socket"; + # The host's swarmctl reaches the gateway by default and the socket only when + # the operator empties `SWARMCTL_SWARM`: `--set-default` lets that empty value + # through, `--set` would not. The socket variable is the control that the + # wrapper text was found at all. + name = "the host's swarmctl defaults to its own swarm's gateway, and an operator's own value wins"; ok = lib.hasInfix "--set SWARM_CONTROLLER_SOCKET " swarmctlWrapperCmd + && lib.hasInfix "--set-default SWARMCTL_SWARM https://t.local" swarmctlWrapperCmd && lib.hasInfix "--set-default SWARMCTL_LOGIN_DEFAULT_SWARM https://t.local" swarmctlWrapperCmd - && !(lib.hasInfix "SWARMCTL_SWARM" swarmctlWrapperCmd); + && !(lib.hasInfix "--set SWARMCTL_SWARM" swarmctlWrapperCmd); } { # The gateway's leaf chains to the store's root, which no system store diff --git a/nix/vm-tests/full-setup.nix b/nix/vm-tests/full-setup.nix index 86466e6cb..6afe14262 100644 --- a/nix/vm-tests/full-setup.nix +++ b/nix/vm-tests/full-setup.nix @@ -142,6 +142,7 @@ test.overrideTestDerivation (old: { env = (old.env or { }) // { FULL_SETUP_SOCKET = deploy.swarm-controller.socketPath; FULL_SETUP_FORGE_DOMAIN = swarm.forge.domain; + FULL_SETUP_SWARM_DOMAIN = swarm.domain; FULL_SETUP_HIVE = hive; FULL_SETUP_TOPLEVELS = builtins.toJSON (map toString (toplevels settingsJson)); FULL_SETUP_META_SETTINGS = settingsJson; diff --git a/nix/vm-tests/full-setup.py b/nix/vm-tests/full-setup.py index cea42e501..158872b3a 100644 --- a/nix/vm-tests/full-setup.py +++ b/nix/vm-tests/full-setup.py @@ -10,6 +10,11 @@ TOPLEVELS = json.loads(os.environ["FULL_SETUP_TOPLEVELS"]) REPO = os.environ["FULL_SETUP_HYPERHIVE_REPO"] CONTROL_NIX = os.environ["FULL_SETUP_CONTROL_NIX"] INIT = "/root/bao-init.json" +# The host's swarmctl defaults to the swarm's gateway, where each controller verb needs a +# `swarmctl login`, which a VM without a browser cannot do. An empty `SWARMCTL_SWARM` puts a +# verb on the controller socket. +VIA_SOCKET = "SWARMCTL_SWARM=" +SWARM_URL = "https://" + os.environ["FULL_SETUP_SWARM_DOMAIN"] FORGE_AUTH = "/root/forge-auth.header" NIX = "nix --extra-experimental-features nix-command" ARCHETYPE = {"source": "hyperhive", "name": "reviewer"} @@ -297,7 +302,7 @@ with subtest("swarmctl setup status reports the steps done so far"): "✅ 10 another agent [optional]", ] for _ in range(60): - lines = machine.execute("swarmctl setup status")[1].splitlines() + lines = machine.execute(f"{VIA_SOCKET} swarmctl setup status")[1].splitlines() if all(any(line.startswith(prefix) for line in lines) for prefix in reported): break machine.sleep(10) @@ -306,7 +311,16 @@ with subtest("swarmctl setup status reports the steps done so far"): "swarmctl setup status did not report the steps done so far:\n" + "\n".join(lines) ) - assert machine.execute("swarmctl setup status >/dev/null")[0] == 1 + assert machine.execute(f"{VIA_SOCKET} swarmctl setup status >/dev/null")[0] == 1 + +with subtest( + "the host's swarmctl reaches the controller through the gateway by default" +): + # No login exists in the VM, so a verb that names the controller stops at the login, and + # says which swarm it went to. Over the socket the same verb needs none. + status, out = machine.execute("swarmctl schedule list 2>&1") + assert status != 0 and f"not logged in to {SWARM_URL}" in out, (status, out) + machine.succeed(f"{VIA_SOCKET} swarmctl schedule list") with subtest("the agents are deployed and need a login"): settle( diff --git a/swarm-controller/README.md b/swarm-controller/README.md index 0c9e348cc..64f968c0e 100644 --- a/swarm-controller/README.md +++ b/swarm-controller/README.md @@ -165,9 +165,10 @@ host so blast radius is unchanged."_ What keeps that safe is that the directory is `0750`, owned by the `swarm-controller-clients` group, and holds **one** socket. nginx is in that -group through its unit's `SupplementaryGroups`; root bypasses mode bits, so -`swarmctl` needs no membership. Every other local user gets `EACCES` at the -directory. The group is not `swarm-controller`'s own, which also owns the +group through its unit's `SupplementaryGroups`; root bypasses mode bits. The host's `swarmctl` reaches the controller +through the gateway by default (`SWARMCTL_SWARM`), so nginx is the only routine client; +root opens the socket only for a verb run with `SWARMCTL_SWARM` empty. Every other local +user gets `EACCES` at the directory. The group is not `swarm-controller`'s own, which also owns the state directory. So: > **Never point `socketPath` at a directory that carries anything else.** diff --git a/swarmctl/README.md b/swarmctl/README.md index 1c9cc129d..0b33d04b8 100644 --- a/swarmctl/README.md +++ b/swarmctl/README.md @@ -2,8 +2,9 @@ Swarm-level operator CLI. Runs as **root on the host running `swarm-controller`**, and acts on that host directly; or, for the verbs -that talk to the controller, from anywhere as your own SSO account (see -[Remote use](#remote-use-swarmctl-login)). +that talk to the controller, through the gateway as your own SSO account, on the +host or anywhere else (see +[Reaching the controller](#reaching-the-controller-swarmctl-login)). Distinct from `hivectl`, which drives one hive's `hive-c0re` over its admin socket. This crate doesn't link `swarm-controller`, for the same @@ -52,18 +53,18 @@ rather than defaulted — a default would be an address we _hope_ points at something, and one that resolves cleanly to the wrong place is worse than an error. -| variable | what | -| ----------------------------------- | -------------------------------------------------------------------- | -| `SWARMCTL_AUTHELIA_BIN` | the **configured** authelia; argon2 params must match the verifier's | -| `SWARMCTL_AUTHELIA_USERS_FILE` | host-side path of the users database | -| `SWARMCTL_AUTHELIA_MACHINE` | container name, for `systemctl -M` | -| `SWARMCTL_AUTHELIA_UNIT` | authelia's unit inside that container | -| `SWARMCTL_BAO_BOOTSTRAP_TOKEN_FILE` | where `bao grant-bootstrap` places the 24h grant token | -| `SWARMCTL_BAO_BOOTSTRAP_POLICY` | the `bao-bootstrap` policy file `bao grant-bootstrap` writes | -| `SWARM_CONTROLLER_SOCKET` | the controller's unix socket, for `agent` and `forge` verbs | -| `SWARMCTL_LOGIN_DEFAULT_SWARM` | `https://` of this host's swarm, for `login` only | -| `SWARMCTL_SWARM` | the swarm's domain, bare or `https://`: reach the controller there | -| `SWARMCTL_CA_FILE` | a PEM CA to trust beside the system roots, for `SWARMCTL_SWARM` | +| variable | what | +| ----------------------------------- | --------------------------------------------------------------------------------------------------------------- | +| `SWARMCTL_AUTHELIA_BIN` | the **configured** authelia; argon2 params must match the verifier's | +| `SWARMCTL_AUTHELIA_USERS_FILE` | host-side path of the users database | +| `SWARMCTL_AUTHELIA_MACHINE` | container name, for `systemctl -M` | +| `SWARMCTL_AUTHELIA_UNIT` | authelia's unit inside that container | +| `SWARMCTL_BAO_BOOTSTRAP_TOKEN_FILE` | where `bao grant-bootstrap` places the 24h grant token | +| `SWARMCTL_BAO_BOOTSTRAP_POLICY` | the `bao-bootstrap` policy file `bao grant-bootstrap` writes | +| `SWARM_CONTROLLER_SOCKET` | the controller's unix socket, used when no swarm is named | +| `SWARMCTL_LOGIN_DEFAULT_SWARM` | `https://` of this host's swarm, for `login` | +| `SWARMCTL_SWARM` | the swarm's domain, bare or `https://`: reach the controller there; the module defaults it to this host's swarm | +| `SWARMCTL_CA_FILE` | a PEM CA to trust beside the system roots, for `SWARMCTL_SWARM` | Every verb and flag: [`docs/2-handbook/swarm/swarmctl-cli.md`](../docs/2-handbook/swarm/swarmctl-cli.md). The sections below cover why each verb behaves as it does. @@ -270,15 +271,15 @@ Read-only, and it needs no token. Where each step is read from: A check that cannot run gives `unknown` with the reason and the rest still print: `bao` is only on `PATH` on the host running swarm-bao, the users file is -only on the authelia host, and the controller socket only on its host (or -`--swarm`). The exit code is 0 when every step it can see has finished and 1 +only on the authelia host, and the controller socket only on its host (or `--swarm`; on a controller host the +default swarm needs `swarmctl login` first). The exit code is 0 when every step it can see has finished and 1 otherwise, counting an `unknown` from a failed check; step 10, another agent, is optional and does not count. -## Remote use: `swarmctl login` +## Reaching the controller: `swarmctl login` -The `agent`, `schedule` and `forge` verbs, and the agent checks and steps of `setup`, also work from any machine, as -your own SSO account, through the swarm domain's gateway: +The `agent`, `schedule` and `forge` verbs, and the agent checks and steps of `setup`, go +through the swarm domain's gateway as your own SSO account, from any machine: ```console $ export SWARMCTL_SWARM=https://swarm.example.com @@ -289,17 +290,28 @@ logged in to https://swarm.example.com/; login kept in ~/.local/state/swarmctl/s $ swarmctl schedule list ``` -`--swarm` (before or after the verb) names the swarm, else `SWARMCTL_SWARM`; -either takes the bare domain too. With neither, `login` alone falls back to -`SWARMCTL_LOGIN_DEFAULT_SWARM`, which the swarm-controller module sets to its -host's own swarm. It's not `SWARMCTL_SWARM` there because that would send -the host's other verbs through the gateway instead of the socket. +`--swarm` (before or after the verb) names the swarm, else `SWARMCTL_SWARM`; either takes the +bare domain too. On a swarm-controller host the module's wrapper sets `SWARMCTL_SWARM` and +`SWARMCTL_LOGIN_DEFAULT_SWARM` to the host's own swarm, so the host's `swarmctl` uses the gateway +too and needs one `swarmctl login`. The gateway names the sender from the SSO session, and the +controller's socket serves nginx alone. Both are defaults, so a value you set wins. An empty +`SWARMCTL_SWARM` (or `--swarm ""`) puts the verbs back on `SWARM_CONTROLLER_SOCKET` as root. That +route sends no `Remote-User`, so the routes that name the sender answer 401. Nothing in setup needs it: +`swarmctl login` needs only authelia and your SSO account, both there by step 2. -`login` opens the swarm's SSO login in a browser and receives the result on -a loopback port, so run it on the machine whose browser you use. swarmctl -keeps the login, mode 0600, under `$XDG_STATE_HOME/swarmctl/` (default -`~/.local/state`) and refreshes it as it's used, and once more if the gateway -refuses it. When it can't be refreshed, any verb says to run `swarmctl login` +`login` opens the swarm's SSO login in a browser and receives the result on a loopback port, so +run it on the machine whose browser you use. It prints the port. On a host with no browser, forward +a port from the machine that has one, then give the login that port: + +```console +workstation$ ssh -L 8765:127.0.0.1:8765 swarm-host +swarm-host$ swarmctl login --callback-port 8765 +``` + +Open the printed URL in the workstation's browser. The registered redirect matches a loopback +address on any port, so any free port works. swarmctl keeps the login, mode 0600, under +`$XDG_STATE_HOME/swarmctl/` (default `~/.local/state`) and refreshes it as it's used, and once +more if the gateway refuses it. When it can't be refreshed, any verb says to run `swarmctl login` again. To log out, delete the file. A swarm whose gateway serves a certificate from the swarm's own CA needs diff --git a/swarmctl/src/login.rs b/swarmctl/src/login.rs index ac05e0310..4065cc216 100644 --- a/swarmctl/src/login.rs +++ b/swarmctl/src/login.rs @@ -26,8 +26,16 @@ const CALLBACK_PATH: &str = "/callback"; /// A `form_post` answer is a few hundred bytes. const MAX_CALLBACK_BODY: usize = 16 * 1024; +/// The loopback listener the browser's answer arrives on: `port`, or a free +/// one when it is 0. +async fn callback_listener(port: u16) -> Result { + TcpListener::bind(("127.0.0.1", port)) + .await + .with_context(|| format!("opening loopback port {port} for the login callback")) +} + /// Run `swarmctl login`. -pub(crate) fn login(swarm: &Swarm) -> Result<()> { +pub(crate) fn login(swarm: &Swarm, callback_port: u16) -> Result<()> { let rt = tokio::runtime::Builder::new_current_thread() .enable_all() .build() @@ -36,9 +44,7 @@ pub(crate) fn login(swarm: &Swarm) -> Result<()> { rt.block_on(async { let http = swarm.http()?; let auth = discover_auth(&http, swarm).await?; - let listener = TcpListener::bind("127.0.0.1:0") - .await - .context("opening a loopback port for the login callback")?; + let listener = callback_listener(callback_port).await?; let redirect_uri = format!( "http://127.0.0.1:{}{CALLBACK_PATH}", listener.local_addr()?.port() @@ -71,7 +77,12 @@ pub(crate) fn login(swarm: &Swarm) -> Result<()> { url.query_pairs_mut() .append_pair("client_id", CLIENT_ID) .append_pair("request_uri", &par.request_uri); - eprintln!("Log in to {} in your browser:\n\n {url}\n", swarm.origin); + eprintln!( + "Log in to {} in your browser:\n\n {url}\n\nThe answer comes back to 127.0.0.1:{}; \ +from another machine, forward that port to this host.\n", + swarm.origin, + listener.local_addr()?.port() + ); open_browser(url.as_str()); let code = tokio::time::timeout(WAIT, receive_code(&listener, &state, &auth)) @@ -291,6 +302,20 @@ mod tests { const AUTH: &str = "https://auth.example.test"; + #[tokio::test] + async fn the_callback_listens_on_the_requested_port_or_a_free_one() { + let free = callback_listener(0).await.expect("binds"); + let port = free.local_addr().expect("address").port(); + assert_ne!(port, 0); + drop(free); + let named = callback_listener(port).await.expect("binds the named port"); + assert_eq!(named.local_addr().expect("address").port(), port); + assert!(named.local_addr().expect("address").ip().is_loopback()); + // A port in use is an error naming it, not a silent other port. + let err = callback_listener(port).await.expect_err("in use"); + assert!(format!("{err:#}").contains(&port.to_string()), "{err:#}"); + } + /// RFC 7636 appendix B. #[test] fn the_challenge_matches_the_rfc_vector() { diff --git a/swarmctl/src/main.rs b/swarmctl/src/main.rs index 19431ab8e..3dc947851 100644 --- a/swarmctl/src/main.rs +++ b/swarmctl/src/main.rs @@ -69,12 +69,20 @@ struct Cli { /// Where a verb that can reach a swarm looks for it when `--swarm` is absent. const SWARM_ENVS: &[&str] = &["SWARMCTL_SWARM"]; -/// The same for `login`. The swarm-controller nix module sets -/// `SWARMCTL_LOGIN_DEFAULT_SWARM` to its host's own swarm; setting -/// `SWARMCTL_SWARM` there instead would send every other verb through the -/// gateway rather than the local socket. +/// The same for `login`, which also reads `SWARMCTL_LOGIN_DEFAULT_SWARM`. The +/// swarm-controller nix module sets both it and `SWARMCTL_SWARM` to its host's +/// own swarm. const LOGIN_SWARM_ENVS: &[&str] = &["SWARMCTL_SWARM", "SWARMCTL_LOGIN_DEFAULT_SWARM"]; +/// What `swarmctl login` takes. +#[derive(Args)] +struct LoginArgs { + /// The loopback port the login listens on for the browser's answer. + /// Defaults to a free one, which the login prints. + #[arg(long, value_name = "PORT", default_value_t = 0)] + callback_port: u16, +} + /// Which swarm to reach through its domain rather than the local socket. #[derive(Args)] struct RemoteArgs { @@ -82,8 +90,10 @@ struct RemoteArgs { /// the `agent`, `schedule` and `forge` verbs, and the agent checks and steps of `setup`, go through its gateway as the /// account `swarmctl login` logged in, instead of over the controller's /// socket. Falls back to `SWARMCTL_SWARM`; `login` then falls back to - /// `SWARMCTL_LOGIN_DEFAULT_SWARM`, which the swarm-controller nix module - /// sets to its host's own swarm. + /// `SWARMCTL_LOGIN_DEFAULT_SWARM`. The swarm-controller nix module sets both + /// to its host's own swarm, so there the verbs use the gateway and need + /// `swarmctl login` once; an empty `SWARMCTL_SWARM` or `--swarm ""` puts + /// them back on the controller's socket. #[arg(long, value_name = "URL", global = true)] swarm: Option, /// A PEM CA certificate to trust beside the system roots, for a swarm @@ -255,7 +265,12 @@ enum Verb { /// runs. swarmctl keeps the login, mode 0600, under /// `$XDG_STATE_HOME/swarmctl/` and refreshes it as it's used. To log out, /// delete that file. - Login, + /// + /// On a host with no browser, forward the callback port from the machine + /// that has one: `ssh -L 8765:127.0.0.1:8765 `, then run + /// `swarmctl login --callback-port 8765` on the host and open the printed + /// URL in that machine's browser. + Login(LoginArgs), /// Emit the full CLI reference as `CommonMark` to stdout. /// /// Hidden tooling command used by the docs build to keep the published @@ -865,10 +880,11 @@ fn main() -> Result<()> { // Same socket-resolution reasoning as `Create` above. Verb::Schedule { command } => schedule(&remote, command), Verb::Setup(args) => setup_verb(paths, &remote, args), - Verb::Login => login::login( + Verb::Login(args) => login::login( &remote .login_swarm()? .context("`swarmctl login` needs `--swarm` or `SWARMCTL_SWARM`")?, + args.callback_port, ), // Resolved lazily, inside the one arm that actually touches the // deployment env vars — see the `MarkdownDocs` doc comment above @@ -1450,6 +1466,22 @@ fn open_new_nofollow(tmp: &Path) -> io::Result { mod tests { use super::*; + #[test] + fn login_takes_a_callback_port_and_defaults_to_a_free_one() { + let port = |args: &[&str]| { + let Verb::Login(login) = Cli::try_parse_from(args).expect("parses").command else { + panic!("parsed as another verb"); + }; + login.callback_port + }; + assert_eq!(port(&["swarmctl", "login"]), 0); + assert_eq!( + port(&["swarmctl", "login", "--callback-port", "8765"]), + 8765 + ); + assert!(Cli::try_parse_from(["swarmctl", "login", "--callback-port", "70000"]).is_err()); + } + #[test] fn set_state_takes_the_wire_enum_values() { let cli = Cli::try_parse_from([