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
3 changed files with 183 additions and 67 deletions

View file

@ -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://<swarm domain>` 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://<swarm domain>` 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

View file

@ -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> {
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() {

View file

@ -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<String>,
/// 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 <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.
///
/// 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<File> {
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([