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

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([