Watch
0
0
Fork
You've already forked hyperhive
0

default the host's swarmctl to the gateway; login takes a callback port

This commit is contained in:
atlas 2026-11-22 15:00:54 +01:00
commit 58236e1b7f
12 changed files with 183 additions and 67 deletions

View file

@ -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 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 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 ```console
# swarmctl setup status # 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) 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 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 ```bash
swarmctl login
swarmctl forge make-admin mara 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 <host> # 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 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. SSO login asks for its forge password once, to link the two.

View file

@ -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 are 8 lowercase letters, the same in every agent's key, never reused, and so
never equal to a hive schedule's numeric id. 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 | | method | path | body |
| -------- | --------------------- | ------------------------------------------------------------------------------------------------------------------------- | | -------- | --------------------- | ------------------------------------------------------------------------------------------------------------------------- |

View file

@ -147,7 +147,7 @@ token. Its access token carries `authelia.bearer.authz` with the audience
`https://<swarm>/api/`, so the gateway admits it at the controller's API and `https://<swarm>/api/`, so the gateway admits it at the controller's API and
nowhere else, under the same access rule as a browser session there. nowhere else, under the same access rule as a browser session there.
Revocation is per account: once authelia stops accepting the account, the 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 ## What this doesn't do

View file

@ -66,7 +66,7 @@ swarm-level operator CLI
* `--users-file <PATH>` — Host-side path of authelia's users database — that is, the path inside the container, prefixed with the container's root. * `--users-file <PATH>` — 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. 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 <URL>` — The swarm's domain, as `https://<domain>` 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 <URL>` — The swarm's domain, as `https://<domain>` 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 <PATH>` — 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` * `--ca-file <PATH>` — 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. 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 <host>`, 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 <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`

View file

@ -154,11 +154,14 @@ let
storeRetry = import ./lib/store-retry.nix { }; storeRetry = import ./lib/store-retry.nix { };
tcpOn = deployCfg.swarm-controller.enable && tcpCfg.enable; tcpOn = deployCfg.swarm-controller.enable && tcpCfg.enable;
# Which swarm `swarmctl login` logs in to when given none: this host's own. # The swarm the host's `swarmctl` talks to: this host's own, through the
# Read by `login` alone. `SWARMCTL_SWARM` would also move every socket verb # gateway, as the operator's own SSO account (`swarmctl login`). The
# onto the gateway, where each needs a login. A default, so an operator's # controller socket then serves the gateway alone, which always sets
# own value still wins. # `Remote-User`. Both are defaults, so an operator's own value wins: an
loginDefaultEnv = lib.optionalAttrs (swarmDomain != null) { # 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}"; SWARMCTL_LOGIN_DEFAULT_SWARM = "https://${swarmDomain}";
}; };
@ -339,7 +342,7 @@ let
) )
++ lib.mapAttrsToList ( ++ lib.mapAttrsToList (
name: value: "--set-default ${name} ${lib.escapeShellArg value}" 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 the socket itself is `0666`, exactly as hive-c0re publishes the
per-agent sockets, and the directory is `0750` owned by the per-agent sockets, and the directory is `0750` owned by the
`${clientsGroup}` group. Members of that group (the gateway's `${clientsGroup}` group. Members of that group (the gateway's
nginx, for `/api/` and `/webhook/forge/`) and root (`swarmctl`, nginx, for `/api/` and `/webhook/forge/`) and root (which bypasses mode
which bypasses mode bits) can reach the socket; every other local 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 user gets `EACCES` at the directory. What keeps `0666` safe is that
the directory holds exactly one socket. the directory holds exactly one socket.
Moving this path under a directory that carries anything else — Moving this path under a directory that carries anything else —

View file

@ -154,14 +154,16 @@ let
or null == "https://matrix.hive.t.local"; or null == "https://matrix.hive.t.local";
} }
{ {
# Login-only: `SWARMCTL_SWARM` would move every socket verb onto the # The host's swarmctl reaches the gateway by default and the socket only when
# gateway. The socket variable is the control that the wrapper text was # the operator empties `SWARMCTL_SWARM`: `--set-default` lets that empty value
# found at all. # through, `--set` would not. The socket variable is the control that the
name = "the host's swarmctl logs in to its own swarm by default, and its other verbs stay on the socket"; # 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 = ok =
lib.hasInfix "--set SWARM_CONTROLLER_SOCKET " swarmctlWrapperCmd 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 "--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 # The gateway's leaf chains to the store's root, which no system store

View file

@ -142,6 +142,7 @@ test.overrideTestDerivation (old: {
env = (old.env or { }) // { env = (old.env or { }) // {
FULL_SETUP_SOCKET = deploy.swarm-controller.socketPath; FULL_SETUP_SOCKET = deploy.swarm-controller.socketPath;
FULL_SETUP_FORGE_DOMAIN = swarm.forge.domain; FULL_SETUP_FORGE_DOMAIN = swarm.forge.domain;
FULL_SETUP_SWARM_DOMAIN = swarm.domain;
FULL_SETUP_HIVE = hive; FULL_SETUP_HIVE = hive;
FULL_SETUP_TOPLEVELS = builtins.toJSON (map toString (toplevels settingsJson)); FULL_SETUP_TOPLEVELS = builtins.toJSON (map toString (toplevels settingsJson));
FULL_SETUP_META_SETTINGS = settingsJson; FULL_SETUP_META_SETTINGS = settingsJson;

View file

@ -10,6 +10,11 @@ TOPLEVELS = json.loads(os.environ["FULL_SETUP_TOPLEVELS"])
REPO = os.environ["FULL_SETUP_HYPERHIVE_REPO"] REPO = os.environ["FULL_SETUP_HYPERHIVE_REPO"]
CONTROL_NIX = os.environ["FULL_SETUP_CONTROL_NIX"] CONTROL_NIX = os.environ["FULL_SETUP_CONTROL_NIX"]
INIT = "/root/bao-init.json" 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" FORGE_AUTH = "/root/forge-auth.header"
NIX = "nix --extra-experimental-features nix-command" NIX = "nix --extra-experimental-features nix-command"
ARCHETYPE = {"source": "hyperhive", "name": "reviewer"} ARCHETYPE = {"source": "hyperhive", "name": "reviewer"}
@ -297,7 +302,7 @@ with subtest("swarmctl setup status reports the steps done so far"):
"✅ 10 another agent [optional]", "✅ 10 another agent [optional]",
] ]
for _ in range(60): 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): if all(any(line.startswith(prefix) for line in lines) for prefix in reported):
break break
machine.sleep(10) 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" "swarmctl setup status did not report the steps done so far:\n"
+ "\n".join(lines) + "\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"): with subtest("the agents are deployed and need a login"):
settle( settle(

View file

@ -165,9 +165,10 @@ host so blast radius is unchanged."_
What keeps that safe is that the directory is `0750`, owned by the 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 `swarm-controller-clients` group, and holds **one** socket. nginx is in that
group through its unit's `SupplementaryGroups`; root bypasses mode bits, so group through its unit's `SupplementaryGroups`; root bypasses mode bits. The host's `swarmctl` reaches the controller
`swarmctl` needs no membership. Every other local user gets `EACCES` at the through the gateway by default (`SWARMCTL_SWARM`), so nginx is the only routine client;
directory. The group is not `swarm-controller`'s own, which also owns the 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: state directory. So:
> **Never point `socketPath` at a directory that carries anything else.** > **Never point `socketPath` at a directory that carries anything else.**

View file

@ -2,8 +2,9 @@
Swarm-level operator CLI. Runs as **root on the host running Swarm-level operator CLI. Runs as **root on the host running
`swarm-controller`**, and acts on that host directly; or, for the verbs `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 that talk to the controller, through the gateway as your own SSO account, on the
[Remote use](#remote-use-swarmctl-login)). 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 Distinct from `hivectl`, which drives one hive's `hive-c0re` over its
admin socket. This crate doesn't link `swarm-controller`, for the same 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 something, and one that resolves cleanly to the wrong place is worse than
an error. an error.
| variable | what | | variable | what |
| ----------------------------------- | -------------------------------------------------------------------- | | ----------------------------------- | --------------------------------------------------------------------------------------------------------------- |
| `SWARMCTL_AUTHELIA_BIN` | the **configured** authelia; argon2 params must match the verifier's | | `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_USERS_FILE` | host-side path of the users database |
| `SWARMCTL_AUTHELIA_MACHINE` | container name, for `systemctl -M` | | `SWARMCTL_AUTHELIA_MACHINE` | container name, for `systemctl -M` |
| `SWARMCTL_AUTHELIA_UNIT` | authelia's unit inside that container | | `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_TOKEN_FILE` | where `bao grant-bootstrap` places the 24h grant token |
| `SWARMCTL_BAO_BOOTSTRAP_POLICY` | the `bao-bootstrap` policy file `bao grant-bootstrap` writes | | `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 | | `SWARM_CONTROLLER_SOCKET` | the controller's unix socket, used when no swarm is named |
| `SWARMCTL_LOGIN_DEFAULT_SWARM` | `https://<swarm domain>` of this host's swarm, for `login` only | | `SWARMCTL_LOGIN_DEFAULT_SWARM` | `https://<swarm domain>` of this host's swarm, for `login` |
| `SWARMCTL_SWARM` | the swarm's domain, bare or `https://`: reach the controller there | | `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` | | `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). 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. 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 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 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 only on the authelia host, and the controller socket only on its host (or `--swarm`; on a controller host the
`--swarm`). The exit code is 0 when every step it can see has finished and 1 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, otherwise, counting an `unknown` from a failed check; step 10, another agent,
is optional and does not count. 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 The `agent`, `schedule` and `forge` verbs, and the agent checks and steps of `setup`, go
your own SSO account, through the swarm domain's gateway: through the swarm domain's gateway as your own SSO account, from any machine:
```console ```console
$ export SWARMCTL_SWARM=https://swarm.example.com $ 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 $ swarmctl schedule list
``` ```
`--swarm` (before or after the verb) names the swarm, else `SWARMCTL_SWARM`; `--swarm` (before or after the verb) names the swarm, else `SWARMCTL_SWARM`; either takes the
either takes the bare domain too. With neither, `login` alone falls back to bare domain too. On a swarm-controller host the module's wrapper sets `SWARMCTL_SWARM` and
`SWARMCTL_LOGIN_DEFAULT_SWARM`, which the swarm-controller module sets to its `SWARMCTL_LOGIN_DEFAULT_SWARM` to the host's own swarm, so the host's `swarmctl` uses the gateway
host's own swarm. It's not `SWARMCTL_SWARM` there because that would send too and needs one `swarmctl login`. The gateway names the sender from the SSO session, and the
the host's other verbs through the gateway instead of the socket. 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 `login` opens the swarm's SSO login in a browser and receives the result on a loopback port, so
a loopback port, so run it on the machine whose browser you use. swarmctl run it on the machine whose browser you use. It prints the port. On a host with no browser, forward
keeps the login, mode 0600, under `$XDG_STATE_HOME/swarmctl/` (default a port from the machine that has one, then give the login that port:
`~/.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` ```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. again. To log out, delete the file.
A swarm whose gateway serves a certificate from the swarm's own CA needs A swarm whose gateway serves a certificate from the swarm's own CA needs

View file

@ -26,8 +26,16 @@ const CALLBACK_PATH: &str = "/callback";
/// A `form_post` answer is a few hundred bytes. /// A `form_post` answer is a few hundred bytes.
const MAX_CALLBACK_BODY: usize = 16 * 1024; 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> {
TcpListener::bind(("127.0.0.1", port))
.await
.with_context(|| format!("opening loopback port {port} for the login callback"))
}
/// Run `swarmctl login`. /// 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() let rt = tokio::runtime::Builder::new_current_thread()
.enable_all() .enable_all()
.build() .build()
@ -36,9 +44,7 @@ pub(crate) fn login(swarm: &Swarm) -> Result<()> {
rt.block_on(async { rt.block_on(async {
let http = swarm.http()?; let http = swarm.http()?;
let auth = discover_auth(&http, swarm).await?; let auth = discover_auth(&http, swarm).await?;
let listener = TcpListener::bind("127.0.0.1:0") let listener = callback_listener(callback_port).await?;
.await
.context("opening a loopback port for the login callback")?;
let redirect_uri = format!( let redirect_uri = format!(
"http://127.0.0.1:{}{CALLBACK_PATH}", "http://127.0.0.1:{}{CALLBACK_PATH}",
listener.local_addr()?.port() listener.local_addr()?.port()
@ -71,7 +77,12 @@ pub(crate) fn login(swarm: &Swarm) -> Result<()> {
url.query_pairs_mut() url.query_pairs_mut()
.append_pair("client_id", CLIENT_ID) .append_pair("client_id", CLIENT_ID)
.append_pair("request_uri", &par.request_uri); .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()); open_browser(url.as_str());
let code = tokio::time::timeout(WAIT, receive_code(&listener, &state, &auth)) let code = tokio::time::timeout(WAIT, receive_code(&listener, &state, &auth))
@ -291,6 +302,20 @@ mod tests {
const AUTH: &str = "https://auth.example.test"; 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. /// RFC 7636 appendix B.
#[test] #[test]
fn the_challenge_matches_the_rfc_vector() { fn the_challenge_matches_the_rfc_vector() {

View file

@ -69,12 +69,20 @@ struct Cli {
/// Where a verb that can reach a swarm looks for it when `--swarm` is absent. /// Where a verb that can reach a swarm looks for it when `--swarm` is absent.
const SWARM_ENVS: &[&str] = &["SWARMCTL_SWARM"]; const SWARM_ENVS: &[&str] = &["SWARMCTL_SWARM"];
/// The same for `login`. The swarm-controller nix module sets /// The same for `login`, which also reads `SWARMCTL_LOGIN_DEFAULT_SWARM`. The
/// `SWARMCTL_LOGIN_DEFAULT_SWARM` to its host's own swarm; setting /// swarm-controller nix module sets both it and `SWARMCTL_SWARM` to its host's
/// `SWARMCTL_SWARM` there instead would send every other verb through the /// own swarm.
/// gateway rather than the local socket.
const LOGIN_SWARM_ENVS: &[&str] = &["SWARMCTL_SWARM", "SWARMCTL_LOGIN_DEFAULT_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. /// Which swarm to reach through its domain rather than the local socket.
#[derive(Args)] #[derive(Args)]
struct RemoteArgs { 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 /// 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 /// account `swarmctl login` logged in, instead of over the controller's
/// socket. Falls back to `SWARMCTL_SWARM`; `login` then falls back to /// socket. Falls back to `SWARMCTL_SWARM`; `login` then falls back to
/// `SWARMCTL_LOGIN_DEFAULT_SWARM`, which the swarm-controller nix module /// `SWARMCTL_LOGIN_DEFAULT_SWARM`. The swarm-controller nix module sets both
/// sets to its host's own swarm. /// 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)] #[arg(long, value_name = "URL", global = true)]
swarm: Option<String>, swarm: Option<String>,
/// A PEM CA certificate to trust beside the system roots, for a swarm /// 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 /// runs. swarmctl keeps the login, mode 0600, under
/// `$XDG_STATE_HOME/swarmctl/` and refreshes it as it's used. To log out, /// `$XDG_STATE_HOME/swarmctl/` and refreshes it as it's used. To log out,
/// delete that file. /// 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 <host>`, 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. /// Emit the full CLI reference as `CommonMark` to stdout.
/// ///
/// Hidden tooling command used by the docs build to keep the published /// 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. // Same socket-resolution reasoning as `Create` above.
Verb::Schedule { command } => schedule(&remote, command), Verb::Schedule { command } => schedule(&remote, command),
Verb::Setup(args) => setup_verb(paths, &remote, args), Verb::Setup(args) => setup_verb(paths, &remote, args),
Verb::Login => login::login( Verb::Login(args) => login::login(
&remote &remote
.login_swarm()? .login_swarm()?
.context("`swarmctl login` needs `--swarm` or `SWARMCTL_SWARM`")?, .context("`swarmctl login` needs `--swarm` or `SWARMCTL_SWARM`")?,
args.callback_port,
), ),
// Resolved lazily, inside the one arm that actually touches the // Resolved lazily, inside the one arm that actually touches the
// deployment env vars — see the `MarkdownDocs` doc comment above // deployment env vars — see the `MarkdownDocs` doc comment above
@ -1450,6 +1466,22 @@ fn open_new_nofollow(tmp: &Path) -> io::Result<File> {
mod tests { mod tests {
use super::*; 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] #[test]
fn set_state_takes_the_wire_enum_values() { fn set_state_takes_the_wire_enum_values() {
let cli = Cli::try_parse_from([ let cli = Cli::try_parse_from([