feat(claw): carry the ssh private key in the sandbox choice

The ssh sandbox took its credential from a key file the local
disk had to hold, so a daemon whose secrets live in a store could
not reach a far box without staging a file first. The choice
gains private_key, the key text itself, threaded to the ssh
backend's with_private_key; unset, the built-in hunt tries the
agent and the default key files as before.

The route keeps the token's write-only contract: GET /v1/sandbox
answers private_key_set and never the key, PUT takes private_key
and clear_private_key, an absent field keeps the stored one, a
present-but-blank one clears it, and config.yaml's sandbox
section accepts the field for boot seeding. The settings page
grows the key textarea with its forget row, the token UI's
shape.

The three sandbox deps move to 0.4.2 for the seam, so the crate
builds once the rhema 0.4.2 release lands on crates.io; until
then the Rust gates cannot run and were checked by hand (cargo
fmt parses the tree, vue-tsc passes).
This commit is contained in:
vhaudiquet committed 2026-11-22 20:02:06 +01:00
1 parent 49c2fa42df
commit cbd52b3b3f
7 files changed
+221 -38

No files matched your search

+7 -3
View File
@@ -45,9 +45,13 @@ rhema-identity = "0.4.1"
rhema-rsd = "0.4.1" rhema-rsd = "0.4.1"
# The sandbox seam: where `bash` runs, this host's processes, a daemon # The sandbox seam: where `bash` runs, this host's processes, a daemon
# speaking the wire protocol over HTTP, or an ssh login on a far box # speaking the wire protocol over HTTP, or an ssh login on a far box
rhema-sandbox = "0.4.1" # The private-key seam: the ssh sandbox carries the key text, not a
rhema-sandbox-http = "0.4.1" # path, so a store-held credential has no file to stage. This rides
rhema-sandbox-ssh = "0.4.1" # the rhema 0.4.2 release; everything else stays on the 0.4.1 line
# until the lockstep bump.
rhema-sandbox = "0.4.2"
rhema-sandbox-http = "0.4.2"
rhema-sandbox-ssh = "0.4.2"
# The tool contract: the agent-token allowlist and version the auth # The tool contract: the agent-token allowlist and version the auth
# middleware enforces (rhema-tools spec). The arrow runs claw -> # middleware enforces (rhema-tools spec). The arrow runs claw ->
# contract only — never the reverse. # contract only — never the reverse.
+5 -2
View File
@@ -178,8 +178,11 @@ pub struct ClawConfig {
/// Unset closes the door to credentials; the human token can still /// Unset closes the door to credentials; the human token can still
/// ingest. /// ingest.
pub ingest_token: Option<String>, pub ingest_token: Option<String>,
/// Where the agent's `bash` runs: this host when unset, or a /// Where the agent's `bash` runs: this host when unset, a
/// `rhema-sandboxd` over HTTP. The settings store owns the live /// `rhema-sandboxd` over HTTP, or an ssh login on a far box (`kind:
/// ssh`, a `host` destination, and optionally the `private_key`
/// text itself, not a path, the credential stays in this file or
/// the store that holds it). The settings store owns the live
/// choice; this seeds it at boot, before the first settings write. /// choice; this seeds it at boot, before the first settings write.
pub sandbox: Option<crate::sandbox::SandboxChoice>, pub sandbox: Option<crate::sandbox::SandboxChoice>,
/// The git identity the daemon writes into its user's global git /// The git identity the daemon writes into its user's global git
+17 -2
View File
@@ -2016,6 +2016,10 @@ fn sandbox_json(state: &ClawState) -> Value {
"kind": choice.kind.as_str(), "kind": choice.kind.as_str(),
"url": choice.url, "url": choice.url,
"token_set": choice.token.as_deref().is_some_and(|token| !token.is_empty()), "token_set": choice.token.as_deref().is_some_and(|token| !token.is_empty()),
"private_key_set": choice
.private_key
.as_deref()
.is_some_and(|key| !key.is_empty()),
"host": choice.host, "host": choice.host,
"ssh_workspace": choice.workspace, "ssh_workspace": choice.workspace,
"workspace": state.sandbox().workspace().display().to_string(), "workspace": state.sandbox().workspace().display().to_string(),
@@ -2025,8 +2029,9 @@ fn sandbox_json(state: &ClawState) -> Value {
} }
/// `PUT /v1/sandbox`: switch where the next turn's commands run, and /// `PUT /v1/sandbox`: switch where the next turn's commands run, and
/// persist the choice. `token` is write-only; `clear_token` drops the /// persist the choice. `token` and `private_key` are write-only;
/// stored one. The choice applies on the next turn, no restart. /// `clear_token` and `clear_private_key` drop the stored ones. The
/// choice applies on the next turn, no restart.
async fn sandbox_put( async fn sandbox_put(
State(state): State<ClawState>, State(state): State<ClawState>,
Json(body): Json<Value>, Json(body): Json<Value>,
@@ -2046,6 +2051,15 @@ async fn sandbox_put(
.map(str::to_owned) .map(str::to_owned)
.or_else(|| current.token.clone()) .or_else(|| current.token.clone())
}; };
let clear_private_key = body["clear_private_key"].as_bool().unwrap_or(false);
let private_key = if clear_private_key {
None
} else {
body["private_key"]
.as_str()
.map(str::to_owned)
.or_else(|| current.private_key.clone())
};
let choice = crate::sandbox::SandboxChoice { let choice = crate::sandbox::SandboxChoice {
kind, kind,
url: body["url"] url: body["url"]
@@ -2061,6 +2075,7 @@ async fn sandbox_put(
.as_str() .as_str()
.map(str::to_owned) .map(str::to_owned)
.or_else(|| current.workspace.clone()), .or_else(|| current.workspace.clone()),
private_key,
}; };
state.sandbox().set(choice).map_err(|err| match err { state.sandbox().set(choice).map_err(|err| match err {
crate::sandbox::SandboxError::Invalid(_) => bad_request(err), crate::sandbox::SandboxError::Invalid(_) => bad_request(err),
+73 -30
View File
@@ -6,9 +6,11 @@
//! changeable over `/v1/sandbox`. `local` keeps the shell the claw //! changeable over `/v1/sandbox`. `local` keeps the shell the claw
//! always had. `http` builds an `HttpSandbox` for a `rhema-sandboxd`. //! always had. `http` builds an `HttpSandbox` for a `rhema-sandboxd`.
//! `ssh` builds an `SshSandbox` on a destination the local ssh config //! `ssh` builds an `SshSandbox` on a destination the local ssh config
//! resolves, no daemon on the far end. The tool spec, approval gate, //! resolves, no daemon on the far end; its private key rides the
//! output caps, and error shaping stay in `ShellTools`; only the //! choice as key text, the settings table is the store, so a
//! machine changes. //! credential held in config or a store has no file to stage. The
//! tool spec, approval gate, output caps, and error shaping stay in
//! `ShellTools`; only the machine changes.
//! //!
//! A remote sandbox starts empty. On the first command for a //! A remote sandbox starts empty. On the first command for a
//! workspace, the executor probes the workspace root and, when it is //! workspace, the executor probes the workspace root and, when it is
@@ -98,14 +100,22 @@ pub struct SandboxChoice {
/// The shared secret the daemon checks, when it guards its routes. /// The shared secret the daemon checks, when it guards its routes.
#[serde(skip_serializing_if = "Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub token: Option<String>, pub token: Option<String>,
/// The `ssh` sandbox's destination, passed to `ssh` as-is: any /// The `ssh` sandbox's destination: any alias or `user@host` the
/// alias or `user@host` the local config resolves. /// local ssh config resolves, the built-in client's resolution.
#[serde(skip_serializing_if = "Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub host: Option<String>, pub host: Option<String>,
/// The `ssh` sandbox's workspace base, where the per-workspace /// The `ssh` sandbox's workspace base, where the per-workspace
/// directories land. Defaults to [`SSH_WORKSPACE_ROOT`]. /// directories land. Defaults to [`SSH_WORKSPACE_ROOT`].
#[serde(skip_serializing_if = "Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub workspace: Option<String>, pub workspace: Option<String>,
/// The `ssh` sandbox's private key, the key text itself (OpenSSH
/// or PEM format), not a path: the choice lives in a config file
/// or a store that has no file to stage. Unset, the sandbox
/// hunts like the `ssh` binary would, the agent first, then the
/// default key files. `GET /v1/sandbox` never returns the key,
/// only that one is set.
#[serde(skip_serializing_if = "Option::is_none")]
pub private_key: Option<String>,
} }
impl SandboxChoice { impl SandboxChoice {
@@ -129,6 +139,10 @@ impl SandboxChoice {
.workspace .workspace
.map(|workspace| workspace.trim().trim_end_matches('/').to_owned()) .map(|workspace| workspace.trim().trim_end_matches('/').to_owned())
.filter(|workspace| !workspace.is_empty()); .filter(|workspace| !workspace.is_empty());
self.private_key = self
.private_key
.map(|key| key.trim().to_owned())
.filter(|key| !key.is_empty());
if self.kind == SandboxKind::Ssh { if self.kind == SandboxKind::Ssh {
let host = self let host = self
.host .host
@@ -311,31 +325,33 @@ impl SandboxState {
return Ok(sandbox.clone()); return Ok(sandbox.clone());
} }
} }
let sandbox: Arc<dyn Sandbox> = match choice.kind { let sandbox: Arc<dyn Sandbox> =
SandboxKind::Http => { match choice.kind {
let url = choice SandboxKind::Http => {
.url let url = choice.url.as_deref().ok_or_else(|| {
.as_deref() ShellError::Failed("the http sandbox has no url".to_owned())
.ok_or_else(|| ShellError::Failed("the http sandbox has no url".to_owned()))?; })?;
let token = choice.token.as_deref().unwrap_or(""); let token = choice.token.as_deref().unwrap_or("");
Arc::new(HttpSandbox::new(url.to_owned(), &session, token)) Arc::new(HttpSandbox::new(url.to_owned(), &session, token))
} }
SandboxKind::Ssh => { SandboxKind::Ssh => {
let dest = choice let dest = choice.host.as_deref().ok_or_else(|| {
.host ShellError::Failed("the ssh sandbox has no host".to_owned())
.as_deref() })?;
.ok_or_else(|| ShellError::Failed("the ssh sandbox has no host".to_owned()))?; let base = choice.workspace.as_deref().unwrap_or(SSH_WORKSPACE_ROOT);
let base = choice.workspace.as_deref().unwrap_or(SSH_WORKSPACE_ROOT); let mut sandbox = SshSandbox::new(dest.to_owned())
Arc::new( .with_workspace(format!("{base}/{session}"));
SshSandbox::new(dest.to_owned()).with_workspace(format!("{base}/{session}")), if let Some(key) = choice.private_key.as_deref() {
) sandbox = sandbox.with_private_key(key);
} }
SandboxKind::Local => { Arc::new(sandbox)
return Err(ShellError::Failed( }
"the local sandbox needs no remote client".to_owned(), SandboxKind::Local => {
)); return Err(ShellError::Failed(
} "the local sandbox needs no remote client".to_owned(),
}; ));
}
};
self.remote self.remote
.lock() .lock()
.unwrap_or_else(PoisonError::into_inner) .unwrap_or_else(PoisonError::into_inner)
@@ -606,6 +622,33 @@ mod tests {
); );
} }
#[test]
fn the_private_key_trims_and_a_blank_stays_unset() {
let keyed = SandboxChoice {
kind: SandboxKind::Ssh,
host: Some("me@box".to_owned()),
private_key: Some(" -----BEGIN OPENSSH PRIVATE KEY----- ".to_owned()),
..SandboxChoice::default()
}
.normalized()
.expect("the choice normalizes");
assert_eq!(
keyed.private_key.as_deref(),
Some("-----BEGIN OPENSSH PRIVATE KEY-----"),
"the key text is trimmed, not mangled"
);
let blank = SandboxChoice {
kind: SandboxKind::Ssh,
host: Some("me@box".to_owned()),
private_key: Some(" ".to_owned()),
..SandboxChoice::default()
}
.normalized()
.expect("a blank key is no key, not a rejection");
assert_eq!(blank.private_key, None, "blank keeps the hunt on");
}
#[test] #[test]
fn the_remote_workspace_is_the_sandbox_root() { fn the_remote_workspace_is_the_sandbox_root() {
let state = state(SandboxChoice { let state = state(SandboxChoice {
+67 -1
View File
@@ -2435,7 +2435,9 @@ async fn the_sandbox_choice_is_listed_and_switchable() {
/// The ssh sandbox over the surface: a choice without a host is a 400, /// The ssh sandbox over the surface: a choice without a host is a 400,
/// a complete one lists its host and reports the workspace under the /// a complete one lists its host and reports the workspace under the
/// configured base, and switching back to this host keeps the ssh /// configured base, and switching back to this host keeps the ssh
/// fields staged for the next switch. /// fields staged for the next switch. The private key rides the same
/// write-only contract the token has: it goes in, a bit comes back,
/// and `clear_private_key` drops it without moving the host.
#[tokio::test] #[tokio::test]
async fn the_ssh_sandbox_is_switchable_over_the_surface() { async fn the_ssh_sandbox_is_switchable_over_the_surface() {
let dir = tempfile::tempdir().expect("tempdir"); let dir = tempfile::tempdir().expect("tempdir");
@@ -2473,6 +2475,70 @@ async fn the_ssh_sandbox_is_switchable_over_the_surface() {
"the workspace sits under the configured base: {workspace}" "the workspace sits under the configured base: {workspace}"
); );
// The private key rides the same route: it goes in as the key
// text (the store-held credential, no file to stage), only the
// `private_key_set` bit comes back, and an absent field leaves
// the stored key alone the way the token's partial save does.
let keyed: Value = client
.put(format!("{base}/v1/sandbox"))
.json(&json!({
"kind": "ssh",
"host": "me@box.example",
"private_key": "-----BEGIN OPENSSH PRIVATE KEY-----\n...\n-----END OPENSSH PRIVATE KEY-----\n"
}))
.send()
.await
.expect("the switch posts")
.json()
.await
.expect("the switch parses");
assert_eq!(keyed["private_key_set"], true);
assert!(
keyed.get("private_key").is_none(),
"the key stays write-only"
);
// A present-but-blank key clears the stored one, the token's
// exact contract: absent keeps, present replaces, even blank.
let blank: Value = client
.put(format!("{base}/v1/sandbox"))
.json(&json!({"kind": "ssh", "host": "me@box.example", "private_key": " "}))
.send()
.await
.expect("the switch posts")
.json()
.await
.expect("the switch parses");
assert_eq!(blank["private_key_set"], false);
// The key is gone now, so set it again before the clear step:
// `clear_private_key` drops the stored key without moving the
// host.
let _again: Value = client
.put(format!("{base}/v1/sandbox"))
.json(&json!({
"kind": "ssh",
"host": "me@box.example",
"private_key": "-----BEGIN OPENSSH PRIVATE KEY-----\n...\n-----END OPENSSH PRIVATE KEY-----\n"
}))
.send()
.await
.expect("the re-set posts")
.json()
.await
.expect("the re-set parses");
let cleared: Value = client
.put(format!("{base}/v1/sandbox"))
.json(&json!({"kind": "ssh", "host": "me@box.example", "clear_private_key": true}))
.send()
.await
.expect("the clear posts")
.json()
.await
.expect("the clear parses");
assert_eq!(cleared["private_key_set"], false);
assert_eq!(cleared["host"], "me@box.example");
// Back to this host: the workspace flips, the ssh fields stay // Back to this host: the workspace flips, the ssh fields stay
// staged for the next switch. // staged for the next switch.
let local: Value = client let local: Value = client
@@ -20,6 +20,8 @@ const token = ref('')
const clearToken = ref(false) const clearToken = ref(false)
const host = ref('') const host = ref('')
const workspace = ref('') const workspace = ref('')
const privateKey = ref('')
const clearPrivateKey = ref(false)
const dirty = computed(() => { const dirty = computed(() => {
const state = props.state const state = props.state
@@ -33,6 +35,7 @@ const dirty = computed(() => {
if (kind.value === 'ssh') { if (kind.value === 'ssh') {
if (host.value.trim() !== (state.host ?? '')) return true if (host.value.trim() !== (state.host ?? '')) return true
if (workspace.value.trim() !== (state.ssh_workspace ?? '')) return true if (workspace.value.trim() !== (state.ssh_workspace ?? '')) return true
return privateKey.value.trim() !== '' || clearPrivateKey.value
} }
return false return false
}) })
@@ -70,6 +73,8 @@ function sync(): void {
clearToken.value = false clearToken.value = false
host.value = state.host ?? '' host.value = state.host ?? ''
workspace.value = state.ssh_workspace ?? '' workspace.value = state.ssh_workspace ?? ''
privateKey.value = ''
clearPrivateKey.value = false
} }
watch( watch(
@@ -98,6 +103,11 @@ function save(): void {
if (kind.value === 'ssh') { if (kind.value === 'ssh') {
choice.host = host.value.trim() choice.host = host.value.trim()
choice.workspace = workspace.value.trim() choice.workspace = workspace.value.trim()
if (privateKey.value.trim() !== '') {
choice.private_key = privateKey.value
} else if (clearPrivateKey.value) {
choice.clear_private_key = true
}
} }
emit('save', choice) emit('save', choice)
} }
@@ -194,6 +204,33 @@ const workspacePath = computed(() => {
:disabled="saving" :disabled="saving"
/> />
</SettingRow> </SettingRow>
<SettingRow
title="Private key"
:description="state.private_key_set
? 'A key is stored. Leave this blank to keep it, or paste a replacement.'
: 'The key text itself (OpenSSH or PEM), not a path: the claw stores it, it stages no file. Leave blank to authenticate through an agent or the default key files.'"
>
<textarea
v-model="privateKey"
class="mono key-input"
rows="3"
:placeholder="state.private_key_set ? 'stored' : '-----BEGIN OPENSSH PRIVATE KEY-----'"
autocomplete="off"
spellcheck="false"
:disabled="saving || clearPrivateKey"
/>
</SettingRow>
<SettingRow
v-if="state.private_key_set"
title="Stored key"
:description="clearPrivateKey
? 'The stored key is removed when you save.'
: 'The key stays in the settings table until you replace or forget it.'"
>
<button class="ghost" :disabled="saving" @click="clearPrivateKey = !clearPrivateKey">
{{ clearPrivateKey ? 'Keep key' : 'Forget key' }}
</button>
</SettingRow>
</SettingCard> </SettingCard>
<SettingCard v-if="kind === 'http'" title="Remote sandbox"> <SettingCard v-if="kind === 'http'" title="Remote sandbox">
@@ -327,4 +364,12 @@ const workspacePath = computed(() => {
font-size: 12px; font-size: 12px;
font-weight: 500; font-weight: 500;
} }
.key-input {
width: 100%;
min-width: 0;
resize: vertical;
font-size: 12px;
word-break: break-all;
}
</style> </style>
+7
View File
@@ -243,6 +243,9 @@ export interface SandboxState {
kind: SandboxKind kind: SandboxKind
url: string | null url: string | null
token_set: boolean token_set: boolean
/** Whether an ssh private key is stored; the key itself never
* rides the wire. */
private_key_set: boolean
/** The ssh destination, an alias or `user@host` the local ssh /** The ssh destination, an alias or `user@host` the local ssh
* config resolves. */ * config resolves. */
host: string | null host: string | null
@@ -266,6 +269,10 @@ export interface SandboxSelection {
token?: string token?: string
clear_token?: boolean clear_token?: boolean
host?: string host?: string
/** The ssh private key text (no file): the store-held credential.
* Write-only, like the token. */
private_key?: string
clear_private_key?: boolean
/** The ssh workspace base; the per-workspace directories land under /** The ssh workspace base; the per-workspace directories land under
* it. An omitted value keeps the current one. */ * it. An omitted value keeps the current one. */
workspace?: string workspace?: string