swarm UI: show the accounts linked to each agent
GET /api/hives/{hive}/agents/{agent}/linked-accounts returns one row per
account linked to the agent, as kind, name and host: each matrix account
under swarm/agents/<agent>/matrix (with its homeserver, and the agent's own
`main` marked reserved), each forge label under swarm/agents/<agent>/forge
(with its url), and github when swarm/agents/<agent>/github-token exists
(host github.com, which is not stored). No credential field is in the
response type.
Listing those two directories needs a new controller grant: `list` on
secret/metadata/swarm/agents/+/matrix and .../+/forge only, pinned in
bao-grants.nix as the only metadata stanzas under agents/ beside the queue
revocation. Checked against a dev OpenBao 2.6.3: the grant lists those two
directories and is refused on agents/, agents/<agent>/, and a leaf.
The swarm UI agent detail panel shows all rows under "accounts"; the table
view's matrix column shows the matrix rows. The link badges stay.
Refs #4855
This commit is contained in:
parent
6fd91b0e69
commit
3380c1915f
13 changed files with 577 additions and 30 deletions
|
|
@ -23,7 +23,23 @@ An agent created here or with `swarmctl agent create` starts `paused`; set it
|
|||
|
||||
Each agent on `/agents` opens three dialogs that write a credential for it
|
||||
into the swarm secret store through swarm-controller. All three are blind
|
||||
set/update actions: no route lists linked accounts or hands a token back.
|
||||
set/update actions: no route hands a token back.
|
||||
|
||||
The agent's detail panel lists its linked accounts under **accounts**, one row
|
||||
per account: kind, name and host. The table view's matrix column lists the
|
||||
matrix rows. Both come from
|
||||
`GET /api/hives/{hive}/agents/{agent}/linked-accounts`, which returns names
|
||||
and hosts and never a credential.
|
||||
|
||||
| kind | one row per | name | host |
|
||||
| ------- | ------------------------------------------- | ----------- | ------------------------ |
|
||||
| matrix | `swarm/agents/<agent>/matrix/<account>` | the account | its `homeserver`, if set |
|
||||
| forgejo | `swarm/agents/<agent>/forge/<label>` | the label | its `url` |
|
||||
| github | `swarm/agents/<agent>/github-token`, if any | `github` | `github.com` |
|
||||
|
||||
The matrix `main` row is the agent's own account, which the swarm mints;
|
||||
it carries an **own account** badge. The lists refresh when a link dialog
|
||||
closes.
|
||||
|
||||
- **link a matrix account** — `PUT /api/hives/{hive}/agents/{agent}/matrix-accounts/{account}`,
|
||||
either a pasted bearer token or a user id + password that
|
||||
|
|
|
|||
|
|
@ -5,7 +5,8 @@
|
|||
// `ApiErrorPanel` like `LinkMatrixAccountForm`.
|
||||
//
|
||||
// The label is what the agent passes to `hive-forge -f <label>`. A blind
|
||||
// set/update: no route lists linked accounts, and none hands a token back.
|
||||
// set/update: no route hands a token back. Linked labels and URLs show on
|
||||
// the agent panel (`LinkedAccounts`).
|
||||
import { useState } from "preact/hooks";
|
||||
import { ApiErrorPanel } from "@hive/shared/api-error-panel.js";
|
||||
import { readApiError, type ProblemDetails } from "@hive/shared/api-error.js";
|
||||
|
|
|
|||
|
|
@ -4,8 +4,8 @@
|
|||
// 400/500 as `problem+json`, shown via `ApiErrorPanel` like
|
||||
// `LinkForgeAccountForm`.
|
||||
//
|
||||
// One token per agent. A blind set/update: no route says whether a token is
|
||||
// stored, and none hands one back.
|
||||
// One token per agent. A blind set/update: no route hands a token back.
|
||||
// Whether one is stored shows on the agent panel (`LinkedAccounts`).
|
||||
import { useState } from "preact/hooks";
|
||||
import { ApiErrorPanel } from "@hive/shared/api-error-panel.js";
|
||||
import { readApiError, type ProblemDetails } from "@hive/shared/api-error.js";
|
||||
|
|
|
|||
|
|
@ -13,10 +13,9 @@
|
|||
// same as every other form here, since the response is `problem+json`
|
||||
// regardless of which arm fired.
|
||||
//
|
||||
// No "linked accounts" list to show first: no route exposes one (a
|
||||
// credential store shouldn't hand a secret back out anyway), so this is
|
||||
// a blind set/update action, not an edit of something already on
|
||||
// screen. That matches "make it 1:1 for now, we will split later" and
|
||||
// A blind set/update action: no route hands a token back, so there is
|
||||
// nothing to edit. What is already linked shows on the agent panel
|
||||
// (`LinkedAccounts`), names and hosts only. That matches "make it 1:1 for now, we will split later" and
|
||||
// "adding them and assigning them should be separate things" — both
|
||||
// mara's rulings on that issue — there's no assignment step here yet,
|
||||
// just the write.
|
||||
|
|
|
|||
|
|
@ -33,6 +33,7 @@ import { LinkIcon } from "@hive/shared/icons.js";
|
|||
import { AgentCard } from "./AgentCard.js";
|
||||
import { AgentTermPreview } from "./AgentTermPreview.js";
|
||||
import { FRESHNESS, type AgentRow } from "./AgentTypes.js";
|
||||
import { LinkedAccounts } from "./LinkedAccounts.js";
|
||||
import { Button } from "../../ui/button/Button.js";
|
||||
import { ConfirmDialog } from "../../ui/confirm-dialog/ConfirmDialog.js";
|
||||
import { Dialog } from "../../ui/dialog/Dialog.js";
|
||||
|
|
@ -158,6 +159,22 @@ export function AgentsPage() {
|
|||
const [matrixTarget, setMatrixTarget] = useState<AgentRow | null>(null);
|
||||
// The row showing the "link a forge account" dialog, same shape.
|
||||
const [forgeTarget, setForgeTarget] = useState<AgentRow | null>(null);
|
||||
// Bumped whenever a link dialog closes; every `LinkedAccounts` refetches
|
||||
// on a change, so a newly linked account shows without a reload.
|
||||
const [linkVersion, setLinkVersion] = useState(0);
|
||||
const linkClosed = () => setLinkVersion((v) => v + 1);
|
||||
const closeMatrix = () => {
|
||||
setMatrixTarget(null);
|
||||
linkClosed();
|
||||
};
|
||||
const closeForge = () => {
|
||||
setForgeTarget(null);
|
||||
linkClosed();
|
||||
};
|
||||
const closeGithub = () => {
|
||||
setGithubTarget(null);
|
||||
linkClosed();
|
||||
};
|
||||
// Which agent the detail panel shows, *by name* — not the `AgentRow`
|
||||
// object itself. Storing the row would snapshot it at selection time;
|
||||
// `rows` replaces its whole array on every `refresh()` and every
|
||||
|
|
@ -374,6 +391,15 @@ export function AgentsPage() {
|
|||
key: "matrix",
|
||||
header: "matrix",
|
||||
render: (a) => (
|
||||
<>
|
||||
{a.hive ? (
|
||||
<LinkedAccounts
|
||||
hive={a.hive}
|
||||
agent={a.name}
|
||||
version={linkVersion}
|
||||
kinds={["matrix"]}
|
||||
/>
|
||||
) : null}
|
||||
<Badge
|
||||
variant="quiet"
|
||||
icon={<LinkIcon />}
|
||||
|
|
@ -386,6 +412,7 @@ export function AgentsPage() {
|
|||
: "no hive on record for this agent — nothing to link against"
|
||||
}
|
||||
/>
|
||||
</>
|
||||
),
|
||||
},
|
||||
{
|
||||
|
|
@ -569,6 +596,18 @@ export function AgentsPage() {
|
|||
"—"
|
||||
)}
|
||||
</dd>
|
||||
<dt>accounts</dt>
|
||||
<dd>
|
||||
{detailTarget.hive ? (
|
||||
<LinkedAccounts
|
||||
hive={detailTarget.hive}
|
||||
agent={detailTarget.name}
|
||||
version={linkVersion}
|
||||
/>
|
||||
) : (
|
||||
"—"
|
||||
)}
|
||||
</dd>
|
||||
</dl>
|
||||
<div class="ui-agent-detail-actions">
|
||||
<Badge
|
||||
|
|
@ -641,7 +680,7 @@ export function AgentsPage() {
|
|||
</Dialog>
|
||||
<Dialog
|
||||
open={matrixTarget !== null}
|
||||
onClose={() => setMatrixTarget(null)}
|
||||
onClose={closeMatrix}
|
||||
label="link a matrix account"
|
||||
plain
|
||||
>
|
||||
|
|
@ -652,13 +691,13 @@ export function AgentsPage() {
|
|||
<LinkMatrixAccountForm
|
||||
hive={matrixTarget.hive}
|
||||
agent={matrixTarget.name}
|
||||
onClose={() => setMatrixTarget(null)}
|
||||
onClose={closeMatrix}
|
||||
/>
|
||||
) : null}
|
||||
</Dialog>
|
||||
<Dialog
|
||||
open={forgeTarget !== null}
|
||||
onClose={() => setForgeTarget(null)}
|
||||
onClose={closeForge}
|
||||
label="link a forge account"
|
||||
plain
|
||||
>
|
||||
|
|
@ -666,13 +705,13 @@ export function AgentsPage() {
|
|||
<LinkForgeAccountForm
|
||||
hive={forgeTarget.hive}
|
||||
agent={forgeTarget.name}
|
||||
onClose={() => setForgeTarget(null)}
|
||||
onClose={closeForge}
|
||||
/>
|
||||
) : null}
|
||||
</Dialog>
|
||||
<Dialog
|
||||
open={githubTarget !== null}
|
||||
onClose={() => setGithubTarget(null)}
|
||||
onClose={closeGithub}
|
||||
label="link a github account"
|
||||
plain
|
||||
>
|
||||
|
|
@ -680,7 +719,7 @@ export function AgentsPage() {
|
|||
<LinkGithubAccountForm
|
||||
hive={githubTarget.hive}
|
||||
agent={githubTarget.name}
|
||||
onClose={() => setGithubTarget(null)}
|
||||
onClose={closeGithub}
|
||||
/>
|
||||
) : null}
|
||||
</Dialog>
|
||||
|
|
|
|||
|
|
@ -0,0 +1,18 @@
|
|||
/* <LinkedAccounts> — one account per line: kind/name badge, then host. */
|
||||
.ui-linked-accounts {
|
||||
list-style: none;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
display: grid;
|
||||
gap: 0.3em;
|
||||
}
|
||||
.ui-linked-accounts li {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5em;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
.ui-linked-accounts-host,
|
||||
.ui-linked-accounts-muted {
|
||||
color: var(--muted);
|
||||
}
|
||||
|
|
@ -0,0 +1,92 @@
|
|||
// <LinkedAccounts> — the accounts linked to one agent, one row each: kind,
|
||||
// name, host. Reads `GET /api/hives/{hive}/agents/{agent}/linked-accounts`,
|
||||
// which carries names and hosts only, never a credential.
|
||||
//
|
||||
// Fetched on mount and again whenever `version` changes; `AgentsPage` bumps
|
||||
// it when a link dialog closes, so an account linked there shows up without
|
||||
// waiting for a reload.
|
||||
import { useEffect, useState } from "preact/hooks";
|
||||
import { readApiError, type ProblemDetails } from "@hive/shared/api-error.js";
|
||||
import { Badge } from "@hive/shared/badge.js";
|
||||
import "./LinkedAccounts.css";
|
||||
|
||||
export type AccountKind = "matrix" | "forgejo" | "github";
|
||||
|
||||
// Mirrors `linked_accounts::LinkedAccount`.
|
||||
interface LinkedAccount {
|
||||
kind: AccountKind;
|
||||
name: string;
|
||||
host: string | null;
|
||||
reserved: boolean;
|
||||
}
|
||||
|
||||
export function LinkedAccounts({
|
||||
hive,
|
||||
agent,
|
||||
version,
|
||||
kinds,
|
||||
}: {
|
||||
hive: string;
|
||||
agent: string;
|
||||
version: number;
|
||||
/** Only these kinds; all of them when omitted. */
|
||||
kinds?: AccountKind[];
|
||||
}) {
|
||||
const [accounts, setAccounts] = useState<LinkedAccount[] | null>(null);
|
||||
const [error, setError] = useState<ProblemDetails | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
(async () => {
|
||||
const r = await fetch(
|
||||
`/api/hives/${encodeURIComponent(hive)}/agents/${encodeURIComponent(agent)}/linked-accounts`,
|
||||
);
|
||||
if (!r.ok) {
|
||||
if (!cancelled) setError(await readApiError(r));
|
||||
return;
|
||||
}
|
||||
const data = (await r.json()) as LinkedAccount[];
|
||||
if (cancelled) return;
|
||||
setAccounts(data);
|
||||
setError(null);
|
||||
})().catch((e: unknown) => {
|
||||
if (!cancelled) setError({ detail: String(e) });
|
||||
});
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [hive, agent, version]);
|
||||
|
||||
if (error) {
|
||||
return (
|
||||
<Badge
|
||||
tone="negative"
|
||||
value="accounts unavailable"
|
||||
title={error.detail ?? "listing linked accounts failed"}
|
||||
/>
|
||||
);
|
||||
}
|
||||
if (accounts === null) return <span class="ui-linked-accounts-muted">…</span>;
|
||||
const shown = kinds
|
||||
? accounts.filter((a) => kinds.includes(a.kind))
|
||||
: accounts;
|
||||
if (shown.length === 0) {
|
||||
return <span class="ui-linked-accounts-muted">none linked</span>;
|
||||
}
|
||||
return (
|
||||
<ul class="ui-linked-accounts">
|
||||
{shown.map((a) => (
|
||||
<li key={`${a.kind}/${a.name}`}>
|
||||
<Badge label={a.kind} value={a.name} />
|
||||
<span class="ui-linked-accounts-host">{a.host ?? "—"}</span>
|
||||
{a.reserved ? (
|
||||
<Badge
|
||||
value="own account"
|
||||
title="the agent's own account, which the swarm mints"
|
||||
/>
|
||||
) : null}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
);
|
||||
}
|
||||
|
|
@ -400,6 +400,14 @@ let
|
|||
capabilities = ["delete"]
|
||||
}
|
||||
|
||||
path "${credentialMountPath}/metadata/swarm/agents/+/matrix" {
|
||||
capabilities = ["list"]
|
||||
}
|
||||
|
||||
path "${credentialMountPath}/metadata/swarm/agents/+/forge" {
|
||||
capabilities = ["list"]
|
||||
}
|
||||
|
||||
path "${credentialMountPath}/data/swarm/hives/+/matrix/sender-token" {
|
||||
capabilities = ["create", "read", "update"]
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1195,6 +1195,23 @@ let
|
|||
&& !(lib.hasInfix "secret/metadata/swarm/agents/*" s)
|
||||
&& !(lib.hasInfix "secret/metadata/*" s);
|
||||
}
|
||||
{
|
||||
# `linked_accounts` names an agent's matrix accounts and forge labels by
|
||||
# listing their two directories. A LIST matches the directory path
|
||||
# itself, so each stanza reaches that one directory: not the agent's
|
||||
# other keys, not `agents/` itself, not anything below. Pinned as whole
|
||||
# stanzas, and as the only metadata stanzas under `agents/` beside the
|
||||
# queue revocation, so a widened path or an added capability fails.
|
||||
name = "the controller may list each agent's matrix and forge accounts, and nothing else under agents";
|
||||
ok =
|
||||
let
|
||||
s = baoGrantHere.systemd.services.swarm-bao-controller-policy.script;
|
||||
stanzas = lib.length (lib.splitString "path \"secret/metadata/swarm/agents/" s) - 1;
|
||||
in
|
||||
lib.hasInfix "path \"secret/metadata/swarm/agents/+/matrix\" {\n capabilities = [\"list\"]\n}" s
|
||||
&& lib.hasInfix "path \"secret/metadata/swarm/agents/+/forge\" {\n capabilities = [\"list\"]\n}" s
|
||||
&& stanzas == 3;
|
||||
}
|
||||
{
|
||||
# The swarm appservice token is a homeserver-admin credential. The
|
||||
# controller mints agents' accounts with it and has no business replacing
|
||||
|
|
|
|||
|
|
@ -32,7 +32,8 @@ The swarm's control plane. The swarm UI and `swarmctl` are its clients.
|
|||
GitHub account for one agent, stored in the swarm secret store
|
||||
(`PUT /api/hives/{hive}/agents/{agent}/matrix-accounts/{account}`,
|
||||
`.../forge-accounts/{label}`, `.../github-account`); distinct from the agent's own swarm-minted
|
||||
accounts above.
|
||||
accounts above. `GET .../linked-accounts` lists them, plus the agent's own
|
||||
`main` matrix account, by kind, name and host, never with a credential.
|
||||
- **Config PR status** — each agent's open config-repo PR, cached from forge
|
||||
webhooks (`GET /api/config-prs`, `/api/agents/{name}/config-pr`).
|
||||
- **Swarm-wide forge objects and webhooks** →
|
||||
|
|
|
|||
353
swarm-controller/src/linked_accounts.rs
Normal file
353
swarm-controller/src/linked_accounts.rs
Normal file
|
|
@ -0,0 +1,353 @@
|
|||
//! The accounts linked to one agent, as kind, name and host: what the swarm
|
||||
//! UI's agent panel lists.
|
||||
//!
|
||||
//! Read from the paths [`crate::matrix_account`], [`crate::forge_account`] and
|
||||
//! [`crate::github_account`] write, plus the agent's own `main` matrix account,
|
||||
//! which `matrix_account::agent_token` mints into the same directory. Each
|
||||
//! entry is read for its host and nothing else leaves this module:
|
||||
//! [`LinkedAccount`] has no field a credential could land in.
|
||||
//!
|
||||
//! Naming the matrix accounts and forge labels takes `list` on each agent's
|
||||
//! `matrix` and `forge` metadata directories, which `controllerPolicyText` in
|
||||
//! `nix/host-modules/swarm-bao.nix` grants on those two directories alone.
|
||||
|
||||
use std::future::Future;
|
||||
|
||||
use axum::Json;
|
||||
use axum::extract::State;
|
||||
use axum::http::StatusCode;
|
||||
use serde::Serialize;
|
||||
use serde::de::DeserializeOwned;
|
||||
use swarm_secret_client::{Error, SecretStore, forge, github, matrix};
|
||||
use utoipa::ToSchema;
|
||||
|
||||
use super::{AppState, error_problem, swarm_hive};
|
||||
|
||||
/// The host shown for a GitHub token. The store keeps none: a token is only
|
||||
/// ever used against github.com.
|
||||
const GITHUB_HOST: &str = "github.com";
|
||||
|
||||
/// Which kind of account a [`LinkedAccount`] is.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, ToSchema)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum AccountKind {
|
||||
Matrix,
|
||||
Forgejo,
|
||||
Github,
|
||||
}
|
||||
|
||||
/// One account linked to an agent. Never carries the credential.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, ToSchema)]
|
||||
pub struct LinkedAccount {
|
||||
kind: AccountKind,
|
||||
/// The matrix account name, the forge label, or `github`.
|
||||
#[schema(example = "main")]
|
||||
name: String,
|
||||
/// The matrix homeserver, the forge base URL, or `github.com`. `None` for a
|
||||
/// matrix account stored without a homeserver.
|
||||
#[schema(example = "https://matrix.example.org")]
|
||||
host: Option<String>,
|
||||
/// The agent's own matrix account, which the swarm mints and an operator
|
||||
/// does not link.
|
||||
reserved: bool,
|
||||
}
|
||||
|
||||
/// The store reads a listing makes, so a test can stand in for the store.
|
||||
pub(crate) trait AccountStore {
|
||||
/// As [`SecretStore::list`].
|
||||
fn list(&self, dir: &str) -> impl Future<Output = Result<Vec<String>, Error>> + Send;
|
||||
|
||||
/// As [`SecretStore::read_optional`].
|
||||
fn read_optional<T: DeserializeOwned + Send>(
|
||||
&self,
|
||||
path: &str,
|
||||
) -> impl Future<Output = Result<Option<T>, Error>> + Send;
|
||||
}
|
||||
|
||||
impl AccountStore for SecretStore {
|
||||
async fn list(&self, dir: &str) -> Result<Vec<String>, Error> {
|
||||
SecretStore::list(self, dir).await
|
||||
}
|
||||
|
||||
async fn read_optional<T: DeserializeOwned + Send>(
|
||||
&self,
|
||||
path: &str,
|
||||
) -> Result<Option<T>, Error> {
|
||||
SecretStore::read_optional(self, path).await
|
||||
}
|
||||
}
|
||||
|
||||
/// The object names directly under `dir`. A key ending in `/` is a directory
|
||||
/// below it, not an account.
|
||||
async fn objects(store: &impl AccountStore, dir: &str) -> Result<Vec<String>, Error> {
|
||||
let keys = store.list(dir).await?;
|
||||
Ok(keys.into_iter().filter(|k| !k.ends_with('/')).collect())
|
||||
}
|
||||
|
||||
/// Every account the store holds for `agent`: matrix, then forgejo, then
|
||||
/// github.
|
||||
///
|
||||
/// A missing directory lists nothing, and a listed name whose object is gone
|
||||
/// gets no entry.
|
||||
///
|
||||
/// # Errors
|
||||
/// Anything [`SecretStore::list`] or [`SecretStore::read_optional`] does not
|
||||
/// treat as absence, such as a denial or an unreachable store, and an `agent`
|
||||
/// or listed name that is not a single path segment.
|
||||
pub(crate) async fn linked_accounts(
|
||||
store: &impl AccountStore,
|
||||
agent: &str,
|
||||
) -> Result<Vec<LinkedAccount>, Error> {
|
||||
let mut out = Vec::new();
|
||||
|
||||
for name in objects(store, &matrix::accounts_dir(agent)?).await? {
|
||||
let path = matrix::account_path(agent, &name)?;
|
||||
if let Some(c) = store.read_optional::<matrix::Credential>(&path).await? {
|
||||
out.push(LinkedAccount {
|
||||
kind: AccountKind::Matrix,
|
||||
reserved: crate::matrix_account::is_reserved_account(&name),
|
||||
host: c.homeserver,
|
||||
name,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
for label in objects(store, &forge::accounts_dir(agent)?).await? {
|
||||
let path = forge::account_path(agent, &label)?;
|
||||
if let Some(a) = store.read_optional::<forge::Account>(&path).await? {
|
||||
out.push(LinkedAccount {
|
||||
kind: AccountKind::Forgejo,
|
||||
name: label,
|
||||
host: Some(a.url),
|
||||
reserved: false,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
let path = github::account_path(agent)?;
|
||||
if store
|
||||
.read_optional::<github::Credential>(&path)
|
||||
.await?
|
||||
.is_some()
|
||||
{
|
||||
out.push(LinkedAccount {
|
||||
kind: AccountKind::Github,
|
||||
name: "github".to_owned(),
|
||||
host: Some(GITHUB_HOST.to_owned()),
|
||||
reserved: false,
|
||||
});
|
||||
}
|
||||
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// List the accounts linked to an agent: names and hosts, never a credential.
|
||||
#[utoipa::path(
|
||||
get,
|
||||
path = "/api/hives/{hive}/agents/{agent}/linked-accounts",
|
||||
params(
|
||||
("hive" = String, Path, description = "hive the agent runs on"),
|
||||
("agent" = String, Path, description = "agent whose accounts to list"),
|
||||
),
|
||||
responses(
|
||||
(status = 200, description = "the agent's linked accounts, empty when it has none", body = Vec<LinkedAccount>),
|
||||
(status = 400, description = "the agent is not an identifier, or the hive is not in this swarm (problem+json)", body = String),
|
||||
(status = 500, description = "the store could not be read (problem+json)", body = String),
|
||||
),
|
||||
tag = "agents"
|
||||
)]
|
||||
pub async fn get_linked_accounts(
|
||||
State(state): State<AppState>,
|
||||
axum::extract::Path((hive, agent)): axum::extract::Path<(String, String)>,
|
||||
) -> Result<Json<Vec<LinkedAccount>>, problem_details::ProblemDetails> {
|
||||
let hive = swarm_hive(&state, &hive).map_err(|(s, d)| error_problem(s, &d))?;
|
||||
let agent = hive_types::Ident::parse(&agent)
|
||||
.map_err(|reason| error_problem(StatusCode::BAD_REQUEST, reason))?
|
||||
.into_string();
|
||||
|
||||
let store = crate::store::connect().await.map_err(|e| {
|
||||
tracing::warn!(error = %e, "connecting to the swarm secret store failed");
|
||||
error_problem(StatusCode::INTERNAL_SERVER_ERROR, &e.to_string())
|
||||
})?;
|
||||
let accounts = linked_accounts(&store, &agent).await.map_err(|e| {
|
||||
tracing::warn!(%hive, %agent, error = %e, "listing linked accounts failed");
|
||||
error_problem(StatusCode::INTERNAL_SERVER_ERROR, &e.to_string())
|
||||
})?;
|
||||
Ok(Json(accounts))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use serde::de::DeserializeOwned;
|
||||
use serde_json::{Value, json};
|
||||
use swarm_secret_client::Error;
|
||||
|
||||
use super::{AccountKind, AccountStore, LinkedAccount, linked_accounts};
|
||||
|
||||
/// Objects by path. A list answers the next segment of every path under
|
||||
/// the directory, with a trailing `/` when it goes deeper, as the store
|
||||
/// does.
|
||||
#[derive(Default)]
|
||||
struct FakeStore {
|
||||
objects: BTreeMap<String, Value>,
|
||||
denied: bool,
|
||||
}
|
||||
|
||||
impl FakeStore {
|
||||
fn with(mut self, path: &str, object: Value) -> Self {
|
||||
self.objects.insert(path.to_owned(), object);
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
impl AccountStore for FakeStore {
|
||||
async fn list(&self, dir: &str) -> Result<Vec<String>, Error> {
|
||||
if self.denied {
|
||||
return Err(Error::MissingEnv("BAO_ADDR"));
|
||||
}
|
||||
let prefix = format!("{dir}/");
|
||||
let mut keys: Vec<String> = self
|
||||
.objects
|
||||
.keys()
|
||||
.filter_map(|p| p.strip_prefix(&prefix))
|
||||
.map(|rest| match rest.split_once('/') {
|
||||
Some((head, _)) => format!("{head}/"),
|
||||
None => rest.to_owned(),
|
||||
})
|
||||
.collect();
|
||||
keys.dedup();
|
||||
Ok(keys)
|
||||
}
|
||||
|
||||
async fn read_optional<T: DeserializeOwned + Send>(
|
||||
&self,
|
||||
path: &str,
|
||||
) -> Result<Option<T>, Error> {
|
||||
if self.denied {
|
||||
return Err(Error::MissingEnv("BAO_ADDR"));
|
||||
}
|
||||
Ok(self
|
||||
.objects
|
||||
.get(path)
|
||||
.map(|v| serde_json::from_value(v.clone()).expect("fixture decodes")))
|
||||
}
|
||||
}
|
||||
|
||||
fn row(kind: AccountKind, name: &str, host: Option<&str>, reserved: bool) -> LinkedAccount {
|
||||
LinkedAccount {
|
||||
kind,
|
||||
name: name.to_owned(),
|
||||
host: host.map(str::to_owned),
|
||||
reserved,
|
||||
}
|
||||
}
|
||||
|
||||
fn every_kind() -> FakeStore {
|
||||
FakeStore::default()
|
||||
.with(
|
||||
"swarm/agents/atlas/matrix/main",
|
||||
json!({"value": "t0k3n-main", "homeserver": "https://matrix.swarm"}),
|
||||
)
|
||||
.with(
|
||||
"swarm/agents/atlas/matrix/catgirl",
|
||||
json!({"value": "t0k3n-cat", "homeserver": "https://matrix.example.org"}),
|
||||
)
|
||||
.with(
|
||||
"swarm/agents/atlas/matrix/old",
|
||||
json!({"value": "t0k3n-old"}),
|
||||
)
|
||||
.with(
|
||||
"swarm/agents/atlas/forge/codeberg",
|
||||
json!({"value": "t0k3n-forge", "url": "https://codeberg.org"}),
|
||||
)
|
||||
.with(
|
||||
"swarm/agents/atlas/github-token",
|
||||
json!({"value": "t0k3n-gh"}),
|
||||
)
|
||||
// Another agent's accounts, and the agent's own forge token beside
|
||||
// its `forge/` directory: neither is a linked account of atlas.
|
||||
.with(
|
||||
"swarm/agents/red/matrix/catgirl",
|
||||
json!({"value": "t0k3n-red", "homeserver": "https://matrix.example.org"}),
|
||||
)
|
||||
.with(
|
||||
"swarm/agents/atlas/forge-token",
|
||||
json!({"value": "t0k3n-own", "name": "atlas"}),
|
||||
)
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn every_kind_is_listed_with_its_name_and_host() {
|
||||
let got = linked_accounts(&every_kind(), "atlas")
|
||||
.await
|
||||
.expect("store answers");
|
||||
assert_eq!(
|
||||
got,
|
||||
vec![
|
||||
row(
|
||||
AccountKind::Matrix,
|
||||
"catgirl",
|
||||
Some("https://matrix.example.org"),
|
||||
false
|
||||
),
|
||||
row(
|
||||
AccountKind::Matrix,
|
||||
"main",
|
||||
Some("https://matrix.swarm"),
|
||||
true
|
||||
),
|
||||
row(AccountKind::Matrix, "old", None, false),
|
||||
row(
|
||||
AccountKind::Forgejo,
|
||||
"codeberg",
|
||||
Some("https://codeberg.org"),
|
||||
false
|
||||
),
|
||||
row(AccountKind::Github, "github", Some("github.com"), false),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn the_response_carries_no_credential() {
|
||||
let got = linked_accounts(&every_kind(), "atlas")
|
||||
.await
|
||||
.expect("store answers");
|
||||
let body = serde_json::to_value(&got).expect("serialises");
|
||||
for entry in body.as_array().expect("an array") {
|
||||
let mut keys: Vec<&str> = entry
|
||||
.as_object()
|
||||
.expect("an object")
|
||||
.keys()
|
||||
.map(String::as_str)
|
||||
.collect();
|
||||
keys.sort_unstable();
|
||||
assert_eq!(keys, ["host", "kind", "name", "reserved"], "{entry}");
|
||||
}
|
||||
let text = body.to_string();
|
||||
assert!(!text.contains("value"), "{text}");
|
||||
assert!(!text.contains("t0k3n"), "{text}");
|
||||
// The control: the same serialisation does carry the names, so the
|
||||
// absence above is not an empty body.
|
||||
assert!(text.contains("catgirl"), "{text}");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn an_agent_with_nothing_stored_lists_nothing() {
|
||||
let got = linked_accounts(&FakeStore::default(), "atlas")
|
||||
.await
|
||||
.expect("absence is not an error");
|
||||
assert!(got.is_empty(), "{got:?}");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_store_that_refuses_is_an_error_not_an_empty_list() {
|
||||
let store = FakeStore {
|
||||
denied: true,
|
||||
..every_kind()
|
||||
};
|
||||
assert!(linked_accounts(&store, "atlas").await.is_err());
|
||||
}
|
||||
}
|
||||
|
|
@ -51,6 +51,7 @@ mod forge;
|
|||
mod forge_account;
|
||||
mod github_account;
|
||||
mod issue_report;
|
||||
mod linked_accounts;
|
||||
mod matrix_account;
|
||||
mod otel_http_client;
|
||||
mod queue_identity;
|
||||
|
|
@ -2892,6 +2893,7 @@ fn build_app(state: AppState) -> axum::Router {
|
|||
.routes(routes!(matrix_account::put_matrix_account))
|
||||
.routes(routes!(forge_account::put_forge_account))
|
||||
.routes(routes!(github_account::put_github_account))
|
||||
.routes(routes!(linked_accounts::get_linked_accounts))
|
||||
.routes(routes!(get_hive_wanted))
|
||||
.routes(routes!(term_stream::stream_agent_term))
|
||||
.routes(routes!(agent_state_stream::stream_agent_state))
|
||||
|
|
|
|||
|
|
@ -194,9 +194,10 @@ pub async fn put_matrix_account(
|
|||
}
|
||||
|
||||
/// Whether `account` is the agent's own account, which [`agent_token`] mints
|
||||
/// and `nix/agent-modules/matrix.nix` declares per agent — see the call site's
|
||||
/// own comment for why this route must never write one.
|
||||
fn is_reserved_account(account: &str) -> bool {
|
||||
/// and `nix/agent-modules/matrix.nix` declares per agent — see
|
||||
/// [`put_matrix_account`]'s comment on it for why that route must never write
|
||||
/// one.
|
||||
pub(crate) fn is_reserved_account(account: &str) -> bool {
|
||||
account == agent_token::ACCOUNT
|
||||
}
|
||||
|
||||
|
|
|
|||
Loading…
Reference in a new issue