Watch
0
0
Fork
You've already forked hyperhive
0

swarm ui ssh row with target snippets, docs for the per-agent switch

This commit is contained in:
atlas 2026-11-16 18:38:10 +01:00 • committed by mara
commit e621397252
5 changed files with 417 additions and 94 deletions

View file

@ -22,6 +22,7 @@ import { AgentInference } from "./AgentInference.js";
import { StatusMessage } from "./StatusMessage.js";
import { AgentInstructions } from "./AgentInstructions.js";
import { AgentLimits } from "./AgentLimits.js";
import { AgentSsh } from "./AgentSsh.js";
import {
AgentInternet,
AgentPermissions,
@ -229,6 +230,8 @@ function GrantRows({ agent }: { agent: string }) {
<dd>
{g.grant === null ? g.loading : <AgentRepos agent={agent} g={g} />}
</dd>
<dt>ssh</dt>
<dd>{g.grant === null ? g.loading : <AgentSsh agent={agent} g={g} />}</dd>
<dt>permissions</dt>
<dd>
{g.grant === null ? (

View file

@ -4,7 +4,7 @@
// changes.
//
// Both read `GET /api/agents/{name}/permissions`, which answers the stored
// grant as `{ permissions?, unrestricted_internet?, internet_log?, max_repos? }` (`{}` when
// grant as `{ permissions?, unrestricted_internet?, internet_log?, max_repos?, ssh? }` (`{}` when
// the swarm sets none, so the agent runs on the default set). The permissions
// control offers the catalogue from `GET /api/permissions` as checkboxes and
// PUTs the ticked ones, a PUT replacing the stored value whole. A selection
@ -50,6 +50,7 @@ interface Grant {
unrestricted_internet?: boolean;
internet_log?: boolean;
max_repos?: number;
ssh?: boolean;
}
// Mirrors swarm-controller's `Catalogue` (`GET /api/permissions`).

View file

@ -0,0 +1,156 @@
// <AgentSsh> — one agent's SSH access in an opened agent card: a badge that
// opens an explainer, the switch, and a folded "on the target" section with the
// text a machine needs to trust the agent's certificates.
//
// The switch is the `ssh` field of `GET/PUT /api/agents/{name}/permissions`,
// shared with the other grant controls through `useGrant`. The CA key comes
// from `GET /api/ssh/ca`, which carries a public value only. The snippets are
// built in `ssh.ts`, prefilled with the key and this agent's name.
//
// Its state belongs to one agent: callers key it by agent name.
import { useEffect, useState } from "preact/hooks";
import { ApiErrorPanel } from "@hive/shared/api-error-panel.js";
import { readApiError, type ProblemDetails } from "@hive/shared/api-error.js";
import { Badge } from "@hive/shared/badge.js";
import { BadgePopover } from "../../ui/badge-popover/BadgePopover.js";
import { Button } from "../../ui/button/Button.js";
import { CheckboxField } from "../../ui/checkbox-field/CheckboxField.js";
import { Hint } from "../../ui/hint/Hint.js";
import { Preformatted } from "../../ui/preformatted/Preformatted.js";
import type { GrantState } from "./AgentPermissions.js";
import {
sshBody,
sshSummary,
targetSnippet,
TARGET_FORMS,
type TargetForm,
} from "./ssh.js";
export function AgentSsh({ agent, g }: { agent: string; g: GrantState }) {
const { grant, busy, saveError, loading, send } = g;
const [form, setForm] = useState<TargetForm>("nixos");
const [copied, setCopied] = useState(false);
// The CA key, or why there is none: a store without a CA yet answers 404.
const [ca, setCa] = useState<string | null>(null);
const [caError, setCaError] = useState<ProblemDetails | null>(null);
useEffect(() => {
let cancelled = false;
(async () => {
const r = await fetch("/api/ssh/ca");
if (!r.ok) {
if (!cancelled) setCaError(await readApiError(r));
return;
}
const body = (await r.json()) as { public_key: string };
if (!cancelled) setCa(body.public_key);
})().catch((e: unknown) => {
if (!cancelled) setCaError({ detail: String(e) });
});
return () => {
cancelled = true;
};
}, []);
if (grant === null) return loading;
const on = grant.ssh === true;
const snippet = ca === null ? null : targetSnippet(form, agent, ca);
async function copy() {
if (snippet === null) return;
try {
await navigator.clipboard.writeText(snippet);
setCopied(true);
setTimeout(() => setCopied(false), 1500);
} catch {
// No clipboard (an insecure context): the text is on screen to select.
}
}
return (
<div class="ui-agent-limits">
<BadgePopover
label="ssh"
value={sshSummary(grant.ssh)}
tone={on ? "warning" : "neutral"}
title={`whether ${agent} may get SSH certificates from the swarm`}
popoverLabel={`${agent} SSH access`}
>
<p class="ui-badge-popover-help">
Lets {agent} log in over SSH to machines that trust the swarm's SSH
certificate authority. With this on, {agent} gets a certificate that
names it and lasts one hour, and renews it every 20 minutes; its key
lives in memory only. The change reaches {agent} within about 25
minutes. A certificate already signed stays valid until it expires, at
most three hours. A machine has to trust the authority before anything
works: see "on the target" below.
</p>
<p class="ui-badge-popover-help" role="note">
{agent} accepts the key a machine shows on the first connection and
refuses a changed one afterwards (trust on first use). It does not
check the key against anything you registered.
</p>
<CheckboxField
id={`ssh-${agent}`}
label={`allow ${agent} to get SSH certificates`}
checked={on}
disabled={busy}
onChange={(next) =>
void send({
method: "PUT",
headers: { "content-type": "application/json" },
body: JSON.stringify(sshBody(grant.permissions, next)),
})
}
/>
{saveError ? (
<ApiErrorPanel
context="the SSH switch was not saved"
problem={saveError}
/>
) : null}
<details class="ui-agent-ssh-target">
<summary>on the target</summary>
{snippet === null ? (
caError ? (
<ApiErrorPanel
context="the swarm's SSH CA key is not available"
problem={caError}
/>
) : (
<Hint as="span" role="status">
loading…
</Hint>
)
) : (
<>
<p class="ui-badge-popover-help">
Put this on a machine {agent} should reach, with{" "}
<code>&lt;user&gt;</code> replaced by the account it logs in as.
The key is the swarm's CA, a public value.
</p>
<div role="tablist" aria-label="target kind">
{TARGET_FORMS.map(([f, label]) => (
<Badge
key={f}
variant={f === form ? "default" : "quiet"}
tone={f === form ? "accent" : "neutral"}
value={label}
onClick={() => setForm(f)}
/>
))}{" "}
<Button onClick={() => void copy()}>
{copied ? "copied" : "copy"}
</Button>
</div>
<Preformatted wrap maxHeight="14em">
{snippet}
</Preformatted>
</>
)}
</details>
</BadgePopover>
</div>
);
}

View file

@ -0,0 +1,75 @@
// An opened agent card's SSH row: what the badge says, the body of the PUT that
// flips the switch, and the text an operator puts on a target machine. Kept out
// of the component so `npm test` can run it.
/** The three ways a target can be set up to trust the swarm's SSH CA. */
export type TargetForm = "nixos" | "home-manager" | "ssh";
/** The forms in the order the card offers them, with their tab labels. */
export const TARGET_FORMS: [TargetForm, string][] = [
["nixos", "NixOS"],
["home-manager", "home-manager"],
["ssh", "ssh"],
];
/** What the badge shows for a stored `ssh` flag: absent is off. */
export function sshSummary(stored: boolean | undefined): string {
return stored === true ? "on" : "off";
}
/**
* The `PUT` body that sets the switch. A `PUT` without `permissions` resets a
* stored list to the default, so the stored list goes along, as in
* `internetBody`; the other fields are left out, which keeps them.
*/
export function sshBody(
stored: string[] | undefined,
on: boolean,
): { permissions?: string[]; ssh: boolean } {
return {
...(stored === undefined ? {} : { permissions: stored }),
ssh: on,
};
}
/**
* The single `authorized_keys` line that makes a machine accept `agent`'s
* certificates, whatever its sshd config: it trusts the CA for that one
* principal and no other.
*/
export function authorizedKeysLine(agent: string, caKey: string): string {
return `cert-authority,principals="${agent}" ${caKey.trim()}`;
}
/**
* The text for one form of target. `<user>` stays a placeholder the operator
* edits: it is the account on the target the agent logs in as.
*/
export function targetSnippet(
form: TargetForm,
agent: string,
caKey: string,
): string {
const ca = caKey.trim();
switch (form) {
case "nixos":
return [
"# The CA key is public. sshd trusts certificates it signed, and the",
`# principal ${agent} may log in as <user>.`,
`environment.etc."ssh/hyperhive-agent-ssh-ca.pub".text = "${ca}\\n";`,
'services.openssh.settings.TrustedUserCAKeys = "/etc/ssh/hyperhive-agent-ssh-ca.pub";',
`users.users.<user>.openssh.authorizedPrincipals = [ "${agent}" ];`,
"",
"# The same, as one module: imports = [ hyperhive.nixosModules.agent-ssh-target ];",
"# services.hyperhive.agentSshTarget.enable = true, with caPublicKey and principals.",
].join("\n");
case "home-manager":
return [
"home.file.\".ssh/authorized_keys\".text = ''",
` ${authorizedKeysLine(agent, ca)}`,
"'';",
].join("\n");
case "ssh":
return `# in ~<user>/.ssh/authorized_keys on the target\n${authorizedKeysLine(agent, ca)}`;
}
}

View file

@ -0,0 +1,62 @@
// An opened agent card's SSH row: the badge, the PUT body and the target
// snippets. Run by `npm test` with Node's type stripping.
import assert from "node:assert/strict";
import { test } from "node:test";
import {
authorizedKeysLine,
sshBody,
sshSummary,
targetSnippet,
} from "../src/agent/detail/ssh.ts";
const ca = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIOHf\n";
test("the badge reads absent as off", () => {
assert.equal(sshSummary(undefined), "off");
assert.equal(sshSummary(false), "off");
assert.equal(sshSummary(true), "on");
});
test("the PUT carries the stored permission list so it is not reset", () => {
assert.deepEqual(sshBody(undefined, true), { ssh: true });
assert.deepEqual(sshBody(["meta"], false), {
permissions: ["meta"],
ssh: false,
});
// Nothing else is sent: the internet and repository fields stay as stored.
assert.deepEqual(Object.keys(sshBody(["meta"], true)).sort(), [
"permissions",
"ssh",
]);
});
test("the authorized_keys line trusts the CA for one principal only", () => {
assert.equal(
authorizedKeysLine("atlas", ca),
'cert-authority,principals="atlas" ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIOHf',
);
});
test("each target form names the agent and the CA key, and keeps <user> for the operator", () => {
for (const form of ["nixos", "home-manager", "ssh"]) {
const text = targetSnippet(form, "atlas", ca);
assert.ok(text.includes("ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIOHf"), form);
assert.ok(text.includes("atlas"), form);
}
assert.ok(targetSnippet("nixos", "atlas", ca).includes("<user>"));
assert.ok(
targetSnippet("nixos", "atlas", ca).includes(
'authorizedPrincipals = [ "atlas" ]',
),
);
assert.ok(targetSnippet("nixos", "atlas", ca).includes("TrustedUserCAKeys"));
assert.ok(
targetSnippet("home-manager", "atlas", ca).includes(
'home.file.".ssh/authorized_keys"',
),
);
// No trailing newline of the CA key leaks into a line.
assert.ok(!targetSnippet("ssh", "atlas", ca).includes("\n\n"));
// The control: another agent gets its own principal.
assert.ok(targetSnippet("ssh", "maia", ca).includes('principals="maia"'));
});