//! `zakuro://` deep links (ADR ZC-0020, zc#509): parse a link, verify the
//! hub-signed action token it carries, and describe what it would change.
//!
//! The closed set of links:
//!
//! | Link | Token |
//! |---|---|
//! | `zakuro://open?view=<screen>` | none: opens a screen, changes nothing |
//! | `zakuro://auth/callback?code=&state=` | none: PKCE, the verifier stays with whoever started the sign-in |
//! | `zakuro://squad/join?t=<jwt>` | hub-signed |
//! | `zakuro://env/launch?t=<jwt>` | hub-signed |
//! | `zakuro://env/connect?t=<jwt>` | hub-signed |
//! | `zakuro://share/budget?t=<jwt>` | hub-signed |
//!
//! A token is a compact JWS (`header.payload.signature`, base64url) signed
//! with EdDSA (Ed25519) by the hub's dedicated *action* key, never the
//! voucher key (ZC-0006). The claims are the ones zak-marketplace's
//! `services/action_tokens.py` mints: `act`, `args`, `sub` (the account's
//! `zakuro_user_id`), optional `node` (this node's key fingerprint), `iat`,
//! `exp` (at most 10 minutes), `jti`, `kid`, `iss`.
//!
//! The keys a token may verify against are the active `ZAKURO_ENV`
//! profile's action trust roots ([`profile_roots`]),
//! or, when set, `ZAKURO_ACTION_PUBKEYS` (comma-separated base64 32-byte
//! Ed25519 public keys) in their place, the same way `ZAKURO_API_URL`
//! overrides the profile's hub. No key at all means every signed link is
//! refused: fail closed, never "accept unsigned".
//!
//! Verification is pure ([`verify`], [`check_binding`]); single use is the
//! caller's ([`Seen`]): the agent keeps the used ids until they expire.
use base64::Engine;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::collections::BTreeMap;
use std::path::Path;
pub const SCHEME_PREFIX: &str = "zakuro://";
/// ADR ZC-0020: "exp: at most 10 minutes".
pub const MAX_TTL_SECS: i64 = 600;
/// Clock skew tolerated on `exp` and on the 10-minute ceiling, the same as the
/// signed peer requests (`broker::node_identity`).
pub const LEEWAY_SECS: i64 = 30;
/// Replaces the profile's action trust roots (comma-separated base64 keys).
pub const ENV_ACTION_PUBKEYS: &str = "ZAKURO_ACTION_PUBKEYS";
/// Longest link accepted. The hub caps a token at 8 KiB (`RedeemRequest`).
pub const MAX_LINK_LEN: usize = 8192 + 64;
/// The screens `zakuro://open?view=` may name: the app's sidebar, plus the
/// first-run screens. Anything else is refused rather than guessed at.
pub const VIEWS: &[&str] = &[
"contribution",
"nodes",
"jobs",
"environments",
"squads",
"budget",
"wallet",
"settings",
"setup",
];
/// The six actions of ADR ZC-0020 §2.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Act {
AuthCallback,
SquadJoin,
EnvLaunch,
EnvConnect,
ShareBudget,
Open,
}
impl Act {
pub const ALL: [Act; 6] = [
Act::AuthCallback,
Act::SquadJoin,
Act::EnvLaunch,
Act::EnvConnect,
Act::ShareBudget,
Act::Open,
];
/// The link path, which is also the token's `act` claim.
pub fn path(self) -> &'static str {
match self {
Act::AuthCallback => "auth/callback",
Act::SquadJoin => "squad/join",
Act::EnvLaunch => "env/launch",
Act::EnvConnect => "env/connect",
Act::ShareBudget => "share/budget",
Act::Open => "open",
}
}
pub fn parse(path: &str) -> Option<Act> {
Act::ALL.into_iter().find(|a| a.path() == path)
}
/// Whether the link must carry a hub-signed token (every state change).
pub fn signed(self) -> bool {
!matches!(self, Act::AuthCallback | Act::Open)
}
}
/// A parsed link, before any verification.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Link {
Open { view: String },
AuthCallback { code: String, state: String },
Signed { act: Act, token: String },
}
impl Link {
pub fn act(&self) -> Act {
match self {
Link::Open { .. } => Act::Open,
Link::AuthCallback { .. } => Act::AuthCallback,
Link::Signed { act, .. } => *act,
}
}
}
/// Everything that can refuse a link. Each maps to the agent API's error
/// envelope (`status`, `code`) so the app and the CLI say the same thing.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum LinkError {
/// Not a `zakuro://` link, an action outside the closed set, or a missing
/// or malformed parameter.
Invalid(String),
/// The token is not a three-part JWS, or its signature part is empty, or
/// it names an algorithm other than EdDSA (`none` included).
Unsigned,
/// No trusted key has the token's `kid`.
UnknownKey,
/// The signature does not verify against the key named by `kid`.
BadSignature,
/// This zc has no action key for the active profile.
NoTrustRoot(String),
/// The configured action keys do not parse.
KeyConfig(String),
/// `exp` has passed.
Expired,
/// The token claims to live longer than ten minutes.
TooLong,
/// The claims are malformed, or `act` differs from the link's action.
BadClaims(String),
/// `sub` is another account.
WrongAccount { sub: String },
/// The agent does not know which account it is signed in as yet.
AccountUnknown,
/// `node` (or the args' node) is another node.
WrongNode,
/// The `jti` was already used.
AlreadyUsed,
/// The used-id file could not be read or written, so this zc cannot
/// prove a link is unused: it refuses rather than risk a replay.
Storage(String),
}
impl LinkError {
pub fn status(&self) -> u16 {
match self {
LinkError::Invalid(_) => 400,
LinkError::Unsigned
| LinkError::UnknownKey
| LinkError::BadSignature
| LinkError::TooLong
| LinkError::BadClaims(_)
| LinkError::WrongNode => 403,
LinkError::WrongAccount { .. } | LinkError::AccountUnknown => 409,
LinkError::Expired | LinkError::AlreadyUsed => 410,
LinkError::NoTrustRoot(_) | LinkError::KeyConfig(_) => 503,
LinkError::Storage(_) => 500,
}
}
pub fn code(&self) -> &'static str {
match self {
LinkError::Invalid(_) => "invalid_link",
LinkError::Unsigned => "unsigned",
LinkError::UnknownKey => "unknown_key",
LinkError::BadSignature => "bad_signature",
LinkError::NoTrustRoot(_) | LinkError::KeyConfig(_) => "no_action_key",
LinkError::Expired => "expired",
LinkError::TooLong => "invalid_token",
LinkError::BadClaims(_) => "invalid_token",
LinkError::WrongAccount { .. } => "wrong_account",
LinkError::AccountUnknown => "account_unknown",
LinkError::WrongNode => "wrong_node",
LinkError::AlreadyUsed => "already_used",
LinkError::Storage(_) => "storage",
}
}
pub fn message(&self) -> String {
match self {
LinkError::Invalid(m) => format!("not a valid zakuro:// link: {m}"),
LinkError::Unsigned => "this link is not signed by the hub".into(),
LinkError::UnknownKey => {
"this link was signed with a key this zc does not trust (another environment?)".into()
}
LinkError::BadSignature => "this link's signature does not verify".into(),
LinkError::NoTrustRoot(env) => format!(
"this zc has no hub action key for the {env} profile, so it refuses signed links; set {ENV_ACTION_PUBKEYS} to the hub's key (GET /api/broker/action/pubkey)"
),
LinkError::KeyConfig(e) => format!("the hub action keys are misconfigured: {e}"),
LinkError::Expired => "this link has expired; open it again from the hub".into(),
LinkError::TooLong => "this link claims to stay valid for more than 10 minutes".into(),
LinkError::BadClaims(m) => format!("this link's token is malformed: {m}"),
LinkError::WrongAccount { .. } => {
"this link was made for another account; sign in as that account (zc login --force) and open it again".into()
}
LinkError::AccountUnknown => {
"the agent does not know which account it is signed in as yet; sign in, or wait for the hub to answer, then open the link again".into()
}
LinkError::WrongNode => "this link was made for another node".into(),
LinkError::AlreadyUsed => "this link was already used".into(),
LinkError::Storage(m) => format!("this zc cannot track used links: {m}"),
}
}
}
impl std::fmt::Display for LinkError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(&self.message())
}
}
fn hex_val(b: u8) -> Option<u8> {
match b {
b'0'..=b'9' => Some(b - b'0'),
b'a'..=b'f' => Some(b - b'a' + 10),
b'A'..=b'F' => Some(b - b'A' + 10),
_ => None,
}
}
/// `application/x-www-form-urlencoded` decoding of one query component.
fn percent_decode(s: &str) -> Result<String, LinkError> {
let bytes = s.as_bytes();
let mut out = Vec::with_capacity(bytes.len());
let mut i = 0;
while i < bytes.len() {
match bytes[i] {
b'%' => {
let hi = bytes.get(i + 1).copied().and_then(hex_val);
let lo = bytes.get(i + 2).copied().and_then(hex_val);
match (hi, lo) {
(Some(h), Some(l)) => out.push(h * 16 + l),
_ => return Err(LinkError::Invalid("bad percent-escape".into())),
}
i += 3;
}
b'+' => {
out.push(b' ');
i += 1;
}
b => {
out.push(b);
i += 1;
}
}
}
String::from_utf8(out).map_err(|_| LinkError::Invalid("query is not UTF-8".into()))
}
/// Parse a link. Only the closed set of ADR ZC-0020 §2 is accepted, each with
/// exactly the parameter it needs; a repeated parameter is refused rather
/// than resolved one way or the other.
pub fn parse_link(raw: &str) -> Result<Link, LinkError> {
let raw = raw.trim();
if raw.len() > MAX_LINK_LEN {
return Err(LinkError::Invalid("too long".into()));
}
let rest = raw
.get(..SCHEME_PREFIX.len())
.filter(|p| p.eq_ignore_ascii_case(SCHEME_PREFIX))
.map(|_| &raw[SCHEME_PREFIX.len()..])
.ok_or_else(|| LinkError::Invalid("the scheme must be zakuro://".into()))?;
let rest = rest.split('#').next().unwrap_or("");
let (path, query) = match rest.split_once('?') {
Some((p, q)) => (p, q),
None => (rest, ""),
};
let path = path.trim_end_matches('/');
let act =
Act::parse(path).ok_or_else(|| LinkError::Invalid(format!("unknown action '{path}'")))?;
let mut params: BTreeMap<String, String> = BTreeMap::new();
for pair in query.split('&').filter(|p| !p.is_empty()) {
let (k, v) = pair.split_once('=').unwrap_or((pair, ""));
let k = percent_decode(k)?;
let v = percent_decode(v)?;
if params.insert(k.clone(), v).is_some() {
return Err(LinkError::Invalid(format!("'{k}' is given twice")));
}
}
let take = |params: &mut BTreeMap<String, String>, k: &str| -> Result<String, LinkError> {
params
.remove(k)
.filter(|v| !v.trim().is_empty())
.ok_or_else(|| LinkError::Invalid(format!("'{k}' is missing")))
};
let link = match act {
Act::Open => {
let view = take(&mut params, "view")?;
if !VIEWS.contains(&view.as_str()) {
return Err(LinkError::Invalid(format!("unknown view '{view}'")));
}
Link::Open { view }
}
Act::AuthCallback => Link::AuthCallback {
code: take(&mut params, "code")?,
state: take(&mut params, "state")?,
},
act => Link::Signed {
act,
token: take(&mut params, "t")?,
},
};
if let Some(k) = params.keys().next() {
return Err(LinkError::Invalid(format!("unexpected parameter '{k}'")));
}
Ok(link)
}
/// One action public key, with its `kid`: the first 8 bytes of SHA-256 of
/// the raw key, lowercase hex (what the hub's `key_id` computes).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TrustedKey {
pub kid: String,
pub raw: [u8; 32],
}
pub fn key_id(raw: &[u8]) -> String {
let d = ring::digest::digest(&ring::digest::SHA256, raw);
hex::encode(&d.as_ref()[..8])
}
impl TrustedKey {
/// A base64 (standard or URL-safe, padded or not) 32-byte Ed25519 key.
pub fn from_b64(s: &str) -> Result<TrustedKey, String> {
let s = s.trim();
let raw = base64::engine::general_purpose::STANDARD
.decode(s)
.or_else(|_| base64::engine::general_purpose::STANDARD_NO_PAD.decode(s))
.or_else(|_| base64::engine::general_purpose::URL_SAFE.decode(s))
.or_else(|_| base64::engine::general_purpose::URL_SAFE_NO_PAD.decode(s))
.map_err(|_| format!("'{s}' is not base64"))?;
let raw: [u8; 32] = raw
.try_into()
.map_err(|_| format!("'{s}' is not a 32-byte Ed25519 public key"))?;
Ok(TrustedKey {
kid: key_id(&raw),
raw,
})
}
}
/// The keys signed links verify against: `override_var`
/// (`ZAKURO_ACTION_PUBKEYS`) when set and non-blank, else the profile's
/// roots. A malformed key is an error, not skipped: a typo must not silently
/// turn into "no key".
pub fn trusted_keys(
profile_roots: &[&str],
override_var: Option<String>,
) -> Result<Vec<TrustedKey>, String> {
let from_var = override_var.filter(|v| !v.trim().is_empty());
let items: Vec<String> = match &from_var {
Some(v) => v.split(',').map(str::to_string).collect(),
None => profile_roots.iter().map(|s| s.to_string()).collect(),
};
items
.iter()
.filter(|s| !s.trim().is_empty())
.map(|s| {
TrustedKey::from_b64(s).map_err(|e| match from_var {
Some(_) => format!("{ENV_ACTION_PUBKEYS}: {e}"),
None => format!("profile action trust root: {e}"),
})
})
.collect()
}
/// stg.hub's action key (kid `bde74a18996820b2`).
pub const STAGING_ACTION_PUBKEY: &str = "dOhGMGFe0iJu4g6KvZKsG8MwK/W0i8WX4l3tXbsmL04=";
/// Each `ZAKURO_ENV` profile's action trust roots (ADR ZC-0020 §3): base64
/// 32-byte Ed25519 public keys, current first, then any previous key still
/// inside a token lifetime. Unlike the update and image roots in
/// [`crate::profile`], empty is enforced: every signed link is refused.
///
/// Staging's key (kid `bde74a18996820b2`) was provisioned on 2026-11-04 as
/// the `action-key` Secret behind stg.hub's `ZAKURO_ACTION_PRIVKEY`; its
/// `GET /api/broker/action/pubkey` answers this kid. Prod has not provisioned
/// one yet, so prod still refuses every signed link. The lab's key is derived
/// per lab from its voucher key, so zlab stages it through
/// `ZAKURO_ACTION_PUBKEYS`. Rotating a key: add the new one first, keep the
/// old one for one token lifetime (10 minutes) after the hub switches. Kept here rather than as a `Profile`
/// field so the trust roots of one feature live with its verifier; the
/// profile still selects which set applies.
pub fn profile_roots(env: crate::profile::Env) -> &'static [&'static str] {
use crate::profile::Env;
match env {
Env::Lab => &[],
Env::Staging => &[STAGING_ACTION_PUBKEY],
Env::Prod => &[],
}
}
/// [`trusted_keys`] for the active profile and the process environment.
pub fn active_keys() -> Result<Vec<TrustedKey>, String> {
trusted_keys(
profile_roots(crate::profile::active().env),
std::env::var(ENV_ACTION_PUBKEYS).ok(),
)
}
/// The environment whose trust roots verify links for a node signed in to
/// `api_url`: the hub that minted the token is the one the node talks to.
/// A LaunchAgent started without `ZAKURO_ENV` resolves the profile to prod
/// even when `zc login --staging` pointed the credentials at staging, so the
/// signed-in hub wins when it is staging's or prod's. A lab or custom URL
/// falls back to the profile.
pub fn env_for_api_url(api_url: Option<&str>) -> crate::profile::Env {
use crate::profile::Env;
match api_url.map(|u| u.trim().trim_end_matches('/')) {
Some(u) if u == crate::credentials::STAGING_API_URL => Env::Staging,
Some(u) if u == crate::credentials::PROD_API_URL => Env::Prod,
_ => crate::profile::active().env,
}
}
/// [`trusted_keys`] for `env`, with the process environment's override.
pub fn keys_for(env: crate::profile::Env) -> Result<Vec<TrustedKey>, String> {
trusted_keys(profile_roots(env), std::env::var(ENV_ACTION_PUBKEYS).ok())
}
/// One line for `zc doctor`: the action keys' `kid`s and where they come from.
pub fn doctor_line() -> String {
let var = std::env::var(ENV_ACTION_PUBKEYS)
.ok()
.filter(|v| !v.trim().is_empty());
let keys = match active_keys() {
Err(e) => format!("invalid ({e})"),
Ok(k) if k.is_empty() => "(none: signed zakuro:// links are refused)".to_string(),
Ok(k) => format!(
"{} ({})",
k.iter()
.map(|k| k.kid.as_str())
.collect::<Vec<_>>()
.join(", "),
if var.is_some() {
ENV_ACTION_PUBKEYS
} else {
"profile"
}
),
};
format!(" action key: {keys}")
}
/// The verified claims of an action token.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Claims {
pub act: String,
#[serde(default)]
pub args: Value,
pub sub: String,
#[serde(default)]
pub node: Option<String>,
#[serde(default)]
pub iat: Option<i64>,
pub exp: i64,
pub jti: String,
#[serde(default)]
pub kid: Option<String>,
#[serde(default)]
pub iss: Option<String>,
}
#[derive(Deserialize)]
struct Header {
#[serde(default)]
alg: Option<String>,
#[serde(default)]
kid: Option<String>,
}
fn b64url(part: &str) -> Result<Vec<u8>, LinkError> {
base64::engine::general_purpose::URL_SAFE_NO_PAD
.decode(part.trim_end_matches('='))
.map_err(|_| LinkError::BadClaims("not base64url".into()))
}
/// Check one token's signature, `exp` and shape, for the link's `act`, at
/// `now` (unix seconds). Account, node and single use are checked by
/// [`check_binding`] and [`Seen`]: they depend on the caller's state.
pub fn verify(token: &str, act: Act, keys: &[TrustedKey], now: i64) -> Result<Claims, LinkError> {
let parts: Vec<&str> = token.trim().split('.').collect();
if parts.len() != 3 || parts[2].is_empty() {
return Err(LinkError::Unsigned);
}
let header: Header = serde_json::from_slice(&b64url(parts[0])?)
.map_err(|_| LinkError::BadClaims("unreadable header".into()))?;
if header.alg.as_deref() != Some("EdDSA") {
return Err(LinkError::Unsigned);
}
let kid = header.kid.unwrap_or_default();
let key = keys
.iter()
.find(|k| k.kid == kid)
.ok_or(LinkError::UnknownKey)?;
let sig = b64url(parts[2]).map_err(|_| LinkError::BadSignature)?;
let signed = format!("{}.{}", parts[0], parts[1]);
ring::signature::UnparsedPublicKey::new(&ring::signature::ED25519, key.raw)
.verify(signed.as_bytes(), &sig)
.map_err(|_| LinkError::BadSignature)?;
// Only now, with the signature good, is the payload worth reading.
let claims: Claims = serde_json::from_slice(&b64url(parts[1])?)
.map_err(|e| LinkError::BadClaims(format!("claims: {e}")))?;
if claims.act != act.path() {
return Err(LinkError::BadClaims(format!(
"the token is for '{}', the link is '{}'",
claims.act,
act.path()
)));
}
if claims.kid.as_deref().is_some_and(|k| k != kid) {
return Err(LinkError::BadClaims(
"kid differs between header and claims".into(),
));
}
if claims.jti.trim().is_empty() || claims.sub.trim().is_empty() {
return Err(LinkError::BadClaims("jti and sub are required".into()));
}
if now >= claims.exp + LEEWAY_SECS {
return Err(LinkError::Expired);
}
if claims.exp > now + MAX_TTL_SECS + LEEWAY_SECS
|| claims
.iat
.is_some_and(|iat| claims.exp - iat > MAX_TTL_SECS)
{
return Err(LinkError::TooLong);
}
Ok(claims)
}
/// The token is for this account and, when it names one, this node.
///
/// `account_sub` is the signed-in account's `zakuro_user_id` (`None` when not
/// known yet: refused, never assumed). `node_fp` is this node's key
/// fingerprint and `node_pubkey` its base64 public key: a `share/budget`
/// token also names the node in `args.node_pubkey`, and both must match.
pub fn check_binding(
claims: &Claims,
account_sub: Option<&str>,
node_fp: &str,
node_pubkey: &str,
) -> Result<(), LinkError> {
match account_sub {
None => return Err(LinkError::AccountUnknown),
Some(sub) if sub != claims.sub => {
return Err(LinkError::WrongAccount {
sub: claims.sub.clone(),
})
}
Some(_) => {}
}
if let Some(n) = claims.node.as_deref() {
let n = crate::broker::node_identity::strip_node_arg(n);
if n != node_fp {
return Err(LinkError::WrongNode);
}
}
if let Some(pk) = claims.args.get("node_pubkey").and_then(Value::as_str) {
if pk.trim() != node_pubkey.trim() {
return Err(LinkError::WrongNode);
}
}
Ok(())
}
/// The used action ids, each kept until its token expires (ADR ZC-0020 §4).
/// Persisted so a restart does not reopen a used link.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct Seen {
/// jti -> exp (unix seconds).
#[serde(default)]
used: BTreeMap<String, i64>,
}
impl Seen {
/// Read the used ids. A missing file is an empty set. An unreadable or
/// corrupt one is an error (fail closed: an empty set would re-arm every
/// used link), unless it is older than any token could live, in which
/// case every id it held has expired and an empty set is exact.
pub fn load(path: &Path) -> Result<Seen, LinkError> {
Self::load_at(path, std::time::SystemTime::now())
}
fn load_at(path: &Path, now: std::time::SystemTime) -> Result<Seen, LinkError> {
let bytes = match std::fs::read(path) {
Ok(b) => b,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Seen::default()),
Err(e) => {
return Err(LinkError::Storage(format!(
"could not read {}: {e}",
path.display()
)))
}
};
match serde_json::from_slice(&bytes) {
Ok(s) => Ok(s),
Err(e) => {
let stale = std::fs::metadata(path)
.and_then(|m| m.modified())
.ok()
.and_then(|m| now.duration_since(m).ok())
.is_some_and(|age| age.as_secs() as i64 > MAX_TTL_SECS + 2 * LEEWAY_SECS);
if stale {
Ok(Seen::default())
} else {
Err(LinkError::Storage(format!(
"{} is corrupt ({e}); it resets by itself {} minutes after its last change, or delete it once no link opened in the last 10 minutes matters",
path.display(),
(MAX_TTL_SECS + 2 * LEEWAY_SECS + 59) / 60
)))
}
}
}
}
/// Add the ids `other` holds (another process may have written the
/// file since this one read it).
pub fn merge(&mut self, other: Seen) {
for (jti, exp) in other.used {
let e = self.used.entry(jti).or_insert(exp);
*e = (*e).max(exp);
}
}
pub fn save(&self, path: &Path) -> std::io::Result<()> {
if let Some(dir) = path.parent() {
std::fs::create_dir_all(dir)?;
}
let tmp = path.with_extension("tmp");
std::fs::write(&tmp, serde_json::to_vec(self).unwrap_or_default())?;
std::fs::rename(tmp, path)
}
/// Drop the ids whose tokens can no longer verify anyway.
pub fn prune(&mut self, now: i64) {
self.used.retain(|_, exp| now < *exp + LEEWAY_SECS);
}
pub fn contains(&self, jti: &str) -> bool {
self.used.contains_key(jti)
}
/// Mark `jti` used. `Err(AlreadyUsed)` when it already was.
pub fn mark(&mut self, jti: &str, exp: i64) -> Result<(), LinkError> {
if self.used.contains_key(jti) {
return Err(LinkError::AlreadyUsed);
}
self.used.insert(jti.to_string(), exp);
Ok(())
}
pub fn len(&self) -> usize {
self.used.len()
}
pub fn is_empty(&self) -> bool {
self.used.is_empty()
}
}
/// One line of a confirmation sheet.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Detail {
pub label: String,
pub value: String,
}
/// What a link would do, for the confirmation sheet (`POST /v2/handoff`).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Preview {
pub act: String,
/// `null` for the token-less links (`open`, `auth/callback`): there is
/// nothing for the agent to confirm, the app acts on its own sheet.
pub jti: Option<String>,
pub sub: Option<String>,
pub node: Option<String>,
pub exp: Option<i64>,
pub title: String,
pub summary: String,
pub details: Vec<Detail>,
/// The app screen the action lands on.
pub view: String,
/// Whether confirming runs the action in this zc. When `false`, `until`
/// names the issue it ships in, and confirming answers 501.
pub available: bool,
pub until: Option<String>,
/// `share/budget`: the proposed change, prefilled on Budget & price.
pub prefill: Option<Value>,
pub args: Value,
}
fn view_label(view: &str) -> &'static str {
match view {
"contribution" => "Contribution",
"nodes" => "Nodes",
"jobs" => "Jobs",
"environments" => "Environments",
"squads" => "Squads",
"budget" => "Budget & price",
"wallet" => "Wallet",
"settings" => "Settings",
"setup" => "Setup",
_ => "Zakuro",
}
}
fn arg_str(args: &Value, k: &str) -> Option<String> {
match args.get(k)? {
Value::String(s) if !s.trim().is_empty() => Some(s.chars().take(200).collect()),
Value::Number(n) => Some(n.to_string()),
_ => None,
}
}
/// A proposal value as the sheet shows it: prices in ¥ units (ADR 0027).
fn proposal_line(k: &str, v: &Value) -> Detail {
let label = match k {
"price_per_hour" => "Price".to_string(),
"cpu" | "cpu_pct" => "CPU".to_string(),
"ram" | "ram_gb" | "memory" => "Memory".to_string(),
"gpu" => "GPU".to_string(),
"sharing" => "Sharing".to_string(),
other => other.replace('_', " "),
};
let value = match (k, v) {
("price_per_hour", Value::Number(n)) => format!("¥{n}/h"),
(_, Value::Bool(true)) => "on".into(),
(_, Value::Bool(false)) => "off".into(),
(_, Value::Null) => "unset".into(),
(_, Value::String(s)) => s.chars().take(200).collect(),
(_, other) => other.to_string(),
};
Detail { label, value }
}
/// The confirmation sheet for a link whose token (if any) has verified.
/// `issues` names, per unavailable action, the issue it ships in.
pub fn describe(link: &Link, claims: Option<&Claims>, issues: &Issues) -> Preview {
let args = claims.map(|c| c.args.clone()).unwrap_or(Value::Null);
let mut p = Preview {
act: link.act().path().to_string(),
jti: claims.map(|c| c.jti.clone()),
sub: claims.map(|c| c.sub.clone()),
node: claims.and_then(|c| c.node.clone()),
exp: claims.map(|c| c.exp),
title: String::new(),
summary: String::new(),
details: vec![],
view: "contribution".into(),
available: true,
until: None,
prefill: None,
args: args.clone(),
};
let d = |label: &str, value: String| Detail {
label: label.into(),
value,
};
match link {
Link::Open { view } => {
p.title = format!("Open {}", view_label(view));
p.summary = "Shows a screen of the app. Nothing on this machine changes.".into();
p.view = view.clone();
}
Link::AuthCallback { .. } => {
p.title = "Finish signing in".into();
p.summary = "The browser handed a sign-in back to Zakuro. This zc signs in with a device code instead, which finishes on its own once you approve it in the browser.".into();
p.view = "setup".into();
p.available = false;
p.until = Some(issues.auth_callback.to_string());
}
Link::Signed { act, .. } => {
match act {
Act::SquadJoin => {
let name = arg_str(&args, "name")
.or_else(|| arg_str(&args, "slug"))
.unwrap_or_else(|| "a squad".into());
p.title = format!("Join {name}");
p.summary = "Adds this node to the squad, which can then run jobs on it within the squad's policy.".into();
p.details.push(d("Squad", name));
if let Some(r) = arg_str(&args, "role") {
p.details.push(d("Your role", r));
}
p.view = "squads".into();
p.available = false;
p.until = Some(issues.squads.to_string());
}
Act::EnvLaunch => {
let template =
arg_str(&args, "template").unwrap_or_else(|| "an environment".into());
p.title = format!("Launch {template}");
p.summary =
"Starts the environment through the hub, on the placement the link names."
.into();
p.details.push(d("Template", template));
if let Some(pl) = arg_str(&args, "placement") {
p.details.push(d("Placement", pl));
}
if let Some(s) = arg_str(&args, "size") {
p.details.push(d("Size", s));
}
p.view = "environments".into();
p.available = false;
p.until = Some(issues.envs.to_string());
}
Act::EnvConnect => {
let name = arg_str(&args, "name")
.or_else(|| arg_str(&args, "deployment_id"))
.unwrap_or_else(|| "an environment".into());
p.title = format!("Connect to {name}");
p.summary = "Brings up this machine's scoped mesh peer for the environment, then opens it.".into();
p.details.push(d("Environment", name));
p.view = "environments".into();
p.available = false;
p.until = Some(issues.envs.to_string());
}
Act::ShareBudget => {
p.title = "Review a budget change".into();
p.summary = "Opens Budget & price with the change the hub proposed filled in. Nothing is saved until you save it there.".into();
if let Some(Value::Object(m)) = args.get("proposed") {
for (k, v) in m {
p.details.push(proposal_line(k, v));
}
p.prefill = Some(Value::Object(m.clone()));
}
if p.details.is_empty() {
p.details
.push(d("Proposed", "no change, review only".into()));
}
p.view = "budget".into();
}
Act::Open | Act::AuthCallback => {}
}
}
}
if let Some(c) = claims {
if c.node.is_some() {
p.details.push(d("Node", "this node".into()));
}
}
p
}
/// Where each action that has no backend yet ships.
#[derive(Debug, Clone, Copy)]
pub struct Issues {
pub squads: &'static str,
pub envs: &'static str,
pub auth_callback: &'static str,
}
/// The issues today's zc names.
pub const ISSUES: Issues = Issues {
squads: "zakuro-ai/zc#517",
envs: "zakuro-ai/zc#519",
// The hub has no PKCE authorization-code endpoint yet; `zc login` signs
// in with a device code (M2.1), which needs no callback.
auth_callback: "zakuro-ai/zc#497",
};
/// What verification needs from the caller's state.
pub struct Context<'a> {
pub keys: &'a [TrustedKey],
/// The active profile's name, for the "no action key" message.
pub env: &'a str,
/// The signed-in account's `zakuro_user_id`, when known.
pub account_sub: Option<&'a str>,
pub node_fp: &'a str,
pub node_pubkey: &'a str,
pub now: i64,
}
/// Every check of ADR ZC-0020 §4 for one parsed link: signature, `exp`,
/// account, node and single use. The token-less links pass as they are.
pub fn check_link(link: &Link, ctx: &Context, seen: &Seen) -> Result<Option<Claims>, LinkError> {
let Link::Signed { act, token } = link else {
return Ok(None);
};
if ctx.keys.is_empty() {
return Err(LinkError::NoTrustRoot(ctx.env.to_string()));
}
let claims = verify(token, *act, ctx.keys, ctx.now)?;
check_binding(&claims, ctx.account_sub, ctx.node_fp, ctx.node_pubkey)?;
if seen.contains(&claims.jti) {
return Err(LinkError::AlreadyUsed);
}
Ok(Some(claims))
}
/// Why `confirm` did not run an action.
#[derive(Debug, Clone, PartialEq)]
pub enum ConfirmError {
/// No verified link with that id is waiting: open the link again.
NotFound,
Link(LinkError),
/// Verified, but this zc cannot run it yet (`until` names the issue).
NotAvailable {
until: String,
view: String,
},
}
/// What a confirmed action did (`POST /v2/handoff/{jti}/confirm`).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Confirmed {
/// Always `done`.
pub status: String,
pub act: String,
pub jti: String,
/// The screen to show now.
pub view: String,
/// `share/budget`: the proposal to prefill.
pub prefill: Option<Value>,
}
/// Verified links waiting for their click, and the used ids. One per agent
/// (or per CLI run when no agent is running), behind its own lock.
#[derive(Debug, Default)]
pub struct Handoffs {
pending: BTreeMap<String, (Claims, Preview)>,
seen: Seen,
path: Option<std::path::PathBuf>,
}
impl Handoffs {
/// `path` persists the used ids (`<agent dir>/handoff_seen.json`).
/// The file is read again before every check, so ids that `zc link`
/// (or another agent run) recorded are never missed.
pub fn new(path: Option<std::path::PathBuf>) -> Handoffs {
Handoffs {
pending: BTreeMap::new(),
seen: Seen::default(),
path,
}
}
/// Fold the ids on disk into memory.
fn refresh(&mut self) -> Result<(), LinkError> {
if let Some(p) = &self.path {
let disk = Seen::load(p)?;
self.seen.merge(disk);
}
Ok(())
}
/// Parse and verify `raw`, and describe it. A signed link is kept until
/// it expires or is confirmed; opening it again returns the same sheet.
pub fn open(
&mut self,
raw: &str,
ctx: &Context,
issues: &Issues,
) -> Result<Preview, LinkError> {
self.pending
.retain(|_, (c, _)| ctx.now < c.exp + LEEWAY_SECS);
let link = parse_link(raw)?;
if link.act().signed() {
self.refresh()?;
}
self.seen.prune(ctx.now);
let claims = check_link(&link, ctx, &self.seen)?;
let preview = describe(&link, claims.as_ref(), issues);
if let Some(c) = claims {
self.pending.insert(c.jti.clone(), (c, preview.clone()));
}
Ok(preview)
}
/// Run the verified action `jti` names, once. Only a confirmed,
/// available action marks the id used; one this zc cannot run yet stays
/// usable, so it works once the feature ships, within its 10 minutes.
pub fn confirm(&mut self, jti: &str, now: i64) -> Result<Confirmed, ConfirmError> {
self.refresh().map_err(ConfirmError::Link)?;
self.seen.prune(now);
if self.seen.contains(jti) {
return Err(ConfirmError::Link(LinkError::AlreadyUsed));
}
let Some((claims, preview)) = self.pending.get(jti).cloned() else {
return Err(ConfirmError::NotFound);
};
if now >= claims.exp + LEEWAY_SECS {
self.pending.remove(jti);
return Err(ConfirmError::Link(LinkError::Expired));
}
if !preview.available {
return Err(ConfirmError::NotAvailable {
until: preview.until.clone().unwrap_or_default(),
view: preview.view.clone(),
});
}
self.seen
.mark(&claims.jti, claims.exp)
.map_err(ConfirmError::Link)?;
if let Some(p) = &self.path {
// A used id that is not on disk could be replayed after a
// restart: refuse to run rather than run unrecorded.
if let Err(e) = self.seen.save(p) {
self.seen.used.remove(&claims.jti);
return Err(ConfirmError::Link(LinkError::Storage(format!(
"could not record the used link in {}: {e}",
p.display()
))));
}
}
self.pending.remove(jti);
Ok(Confirmed {
status: "done".into(),
act: claims.act.clone(),
jti: claims.jti.clone(),
view: preview.view.clone(),
prefill: preview.prefill.clone(),
})
}
}
#[cfg(test)]
pub(crate) mod tests {
use super::*;
use ring::signature::{Ed25519KeyPair, KeyPair};
use serde_json::json;
pub(crate) const NOW: i64 = 1_800_000_000;
pub(crate) const NODE_FP: &str = "0123456789abcdef";
pub(crate) const NODE_PK: &str = "q8X2n0Lr4mH6vB9sK3wT7yP1cF5gJ0dZ2aE4uR8iO6s=";
pub(crate) struct Signer {
pair: Ed25519KeyPair,
}
impl Signer {
pub(crate) fn new(seed: u8) -> Signer {
Signer {
pair: Ed25519KeyPair::from_seed_unchecked(&[seed; 32]).unwrap(),
}
}
pub(crate) fn key(&self) -> TrustedKey {
let raw: [u8; 32] = self.pair.public_key().as_ref().try_into().unwrap();
TrustedKey {
kid: key_id(&raw),
raw,
}
}
pub(crate) fn pub_b64(&self) -> String {
base64::engine::general_purpose::STANDARD.encode(self.pair.public_key().as_ref())
}
pub(crate) fn sign_with_header(&self, header: Value, claims: Value) -> String {
let e =
|v: &Value| base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(v.to_string());
let signing = format!("{}.{}", e(&header), e(&claims));
let sig = self.pair.sign(signing.as_bytes());
format!(
"{signing}.{}",
base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(sig.as_ref())
)
}
/// What the hub's `action_tokens.mint` produces.
pub(crate) fn mint(&self, claims: Value) -> String {
let kid = self.key().kid;
self.sign_with_header(json!({"alg": "EdDSA", "typ": "JWT", "kid": kid}), claims)
}
}
pub(crate) fn claims(act: &str, jti: &str) -> Value {
json!({
"act": act,
"args": {"squad_id": "s1", "slug": "kyoto-vision", "name": "Kyoto Vision", "role": "member"},
"sub": "1234567890",
"node": NODE_FP,
"iat": NOW - 10,
"exp": NOW + 590,
"jti": jti,
"iss": "https://stg.hub.zakuro-ai.com",
})
}
fn with(mut v: Value, k: &str, x: Value) -> Value {
v[k] = x;
v
}
#[test]
fn parses_the_closed_set_and_nothing_else() {
assert_eq!(
parse_link("zakuro://open?view=contribution").unwrap(),
Link::Open {
view: "contribution".into()
}
);
assert_eq!(
parse_link("ZAKURO://open/?view=budget").unwrap().act(),
Act::Open
);
assert_eq!(
parse_link("zakuro://auth/callback?code=abc&state=x%2By").unwrap(),
Link::AuthCallback {
code: "abc".into(),
state: "x+y".into()
}
);
for act in ["squad/join", "env/launch", "env/connect", "share/budget"] {
match parse_link(&format!("zakuro://{act}?t=a.b.c")).unwrap() {
Link::Signed { act: a, token } => {
assert_eq!(a.path(), act);
assert_eq!(token, "a.b.c");
}
other => panic!("{other:?}"),
}
}
for bad in [
"https://hub.zakuro-ai.com/open?view=contribution",
"zakuro://open?view=../../etc",
"zakuro://open",
"zakuro://squad/join",
"zakuro://squad/join?t=",
"zakuro://squad/join?t=a&t=b",
"zakuro://squad/leave?t=a.b.c",
"zakuro://share/budget?t=a.b.c&price=1",
"zakuro://open?view=%zz",
] {
let e = parse_link(bad).unwrap_err();
assert_eq!(e.code(), "invalid_link", "{bad}");
}
}
#[test]
fn a_valid_token_verifies() {
let s = Signer::new(7);
let t = s.mint(claims("squad/join", "j1"));
let c = verify(&t, Act::SquadJoin, &[s.key()], NOW).unwrap();
assert_eq!((c.sub.as_str(), c.jti.as_str()), ("1234567890", "j1"));
assert_eq!(c.node.as_deref(), Some(NODE_FP));
check_binding(&c, Some("1234567890"), NODE_FP, NODE_PK).unwrap();
// A node claim in the zc://node-<fp> form is the same node.
let t = s.mint(with(
claims("squad/join", "j2"),
"node",
json!(format!("zc://node-{NODE_FP}")),
));
let c = verify(&t, Act::SquadJoin, &[s.key()], NOW).unwrap();
check_binding(&c, Some("1234567890"), NODE_FP, NODE_PK).unwrap();
// No node claim: any of the account's nodes.
let mut v = claims("squad/join", "j3");
v.as_object_mut().unwrap().remove("node");
let c = verify(&s.mint(v), Act::SquadJoin, &[s.key()], NOW).unwrap();
check_binding(&c, Some("1234567890"), "ffffffffffffffff", NODE_PK).unwrap();
}
#[test]
fn an_expired_token_is_refused() {
let s = Signer::new(7);
let v = with(
with(claims("squad/join", "j"), "iat", json!(NOW - 700)),
"exp",
json!(NOW - 100),
);
assert_eq!(
verify(&s.mint(v), Act::SquadJoin, &[s.key()], NOW),
Err(LinkError::Expired)
);
// Inside the leeway it still verifies; past it, not.
let v = with(claims("squad/join", "j"), "exp", json!(NOW - 5));
assert!(verify(&s.mint(v.clone()), Act::SquadJoin, &[s.key()], NOW).is_ok());
assert_eq!(
verify(&s.mint(v), Act::SquadJoin, &[s.key()], NOW + LEEWAY_SECS).unwrap_err(),
LinkError::Expired
);
assert_eq!(LinkError::Expired.status(), 410);
}
#[test]
fn a_token_living_longer_than_ten_minutes_is_refused() {
let s = Signer::new(7);
let v = with(claims("squad/join", "j"), "exp", json!(NOW + 3600));
assert_eq!(
verify(&s.mint(v), Act::SquadJoin, &[s.key()], NOW),
Err(LinkError::TooLong)
);
let v = with(
with(claims("squad/join", "j"), "iat", json!(NOW - 500)),
"exp",
json!(NOW + 200),
);
assert_eq!(
verify(&s.mint(v), Act::SquadJoin, &[s.key()], NOW),
Err(LinkError::TooLong)
);
}
#[test]
fn a_token_for_another_node_is_refused() {
let s = Signer::new(7);
let v = with(claims("squad/join", "j"), "node", json!("fedcba9876543210"));
let c = verify(&s.mint(v), Act::SquadJoin, &[s.key()], NOW).unwrap();
assert_eq!(
check_binding(&c, Some("1234567890"), NODE_FP, NODE_PK),
Err(LinkError::WrongNode)
);
// share/budget also names the node in args.node_pubkey.
let v = with(
claims("share/budget", "j"),
"args",
json!({"node_pubkey": "Vb3kT9qL2xN7mR4wY8pC1zF6hJ0sD5gA2eU9iO3tK7c=", "proposed": {}}),
);
let c = verify(&s.mint(v), Act::ShareBudget, &[s.key()], NOW).unwrap();
assert_eq!(
check_binding(&c, Some("1234567890"), NODE_FP, NODE_PK),
Err(LinkError::WrongNode)
);
assert_eq!(LinkError::WrongNode.code(), "wrong_node");
}
#[test]
fn a_token_for_another_account_or_an_unknown_account_is_refused() {
let s = Signer::new(7);
let c = verify(
&s.mint(claims("squad/join", "j")),
Act::SquadJoin,
&[s.key()],
NOW,
)
.unwrap();
assert_eq!(
check_binding(&c, Some("999"), NODE_FP, NODE_PK),
Err(LinkError::WrongAccount {
sub: "1234567890".into()
})
);
assert_eq!(
check_binding(&c, None, NODE_FP, NODE_PK),
Err(LinkError::AccountUnknown)
);
}
#[test]
fn a_wrong_signature_is_refused() {
let hub = Signer::new(7);
let forger = Signer::new(8);
// Signed by another key that claims the hub's kid.
let kid = hub.key().kid;
let forged = forger.sign_with_header(
json!({"alg": "EdDSA", "kid": kid}),
claims("squad/join", "j"),
);
assert_eq!(
verify(&forged, Act::SquadJoin, &[hub.key()], NOW),
Err(LinkError::BadSignature)
);
// A good token whose payload was edited after signing.
let good = hub.mint(claims("squad/join", "j"));
let parts: Vec<&str> = good.split('.').collect();
let edited = with(claims("squad/join", "j"), "sub", json!("attacker"));
let payload = base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(edited.to_string());
let tampered = format!("{}.{}.{}", parts[0], payload, parts[2]);
assert_eq!(
verify(&tampered, Act::SquadJoin, &[hub.key()], NOW),
Err(LinkError::BadSignature)
);
// Signed by a key this zc does not trust at all.
assert_eq!(
verify(
&forger.mint(claims("squad/join", "j")),
Act::SquadJoin,
&[hub.key()],
NOW
),
Err(LinkError::UnknownKey)
);
// Nothing to verify against: no profile root and no override.
assert_eq!(
verify(&good, Act::SquadJoin, &[], NOW),
Err(LinkError::UnknownKey)
);
}
#[test]
fn an_unsigned_token_is_refused() {
let hub = Signer::new(7);
let e = |v: Value| base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(v.to_string());
let kid = hub.key().kid;
let body = e(claims("squad/join", "j"));
for t in [
// alg none, empty signature (the classic JWT bypass).
format!("{}.{body}.", e(json!({"alg": "none", "kid": kid}))),
// EdDSA header but no signature part.
format!("{}.{body}.", e(json!({"alg": "EdDSA", "kid": kid}))),
format!("{}.{body}", e(json!({"alg": "EdDSA", "kid": kid}))),
// A plausible signature under another algorithm.
format!("{}.{body}.AAAA", e(json!({"alg": "HS256", "kid": kid}))),
"not-a-jwt".to_string(),
] {
assert_eq!(
verify(&t, Act::SquadJoin, &[hub.key()], NOW),
Err(LinkError::Unsigned),
"{t}"
);
}
}
#[test]
fn the_token_must_be_for_the_links_action() {
let s = Signer::new(7);
let t = s.mint(claims("share/budget", "j"));
assert!(matches!(
verify(&t, Act::SquadJoin, &[s.key()], NOW),
Err(LinkError::BadClaims(_))
));
}
#[test]
fn a_jti_is_single_use_until_it_expires() {
let mut seen = Seen::default();
seen.mark("j1", NOW + 100).unwrap();
assert_eq!(seen.mark("j1", NOW + 100), Err(LinkError::AlreadyUsed));
seen.prune(NOW + 100 + LEEWAY_SECS - 1);
assert!(seen.contains("j1"));
seen.prune(NOW + 100 + LEEWAY_SECS);
assert!(!seen.contains("j1"));
let dir = std::env::temp_dir().join(format!("zc-seen-{}", std::process::id()));
let path = dir.join("handoff_seen.json");
let mut s = Seen::default();
s.mark("j2", NOW).unwrap();
s.save(&path).unwrap();
assert!(Seen::load(&path).unwrap().contains("j2"));
let _ = std::fs::remove_dir_all(dir);
}
#[test]
fn trust_roots_come_from_the_profile_or_the_override() {
let s = Signer::new(7);
let other = Signer::new(9);
let roots = [s.pub_b64()];
let roots: Vec<&str> = roots.iter().map(String::as_str).collect();
assert_eq!(trusted_keys(&roots, None).unwrap(), vec![s.key()]);
assert_eq!(
trusted_keys(&roots, Some(" ".into())).unwrap(),
vec![s.key()]
);
// The override replaces the profile's roots, and takes a list.
let both = format!("{}, {}", other.pub_b64(), s.pub_b64());
assert_eq!(
trusted_keys(&roots, Some(both)).unwrap(),
vec![other.key(), s.key()]
);
// The JWK `x` form (base64url, no padding) is the same key.
let x = base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(s.key().raw);
assert_eq!(trusted_keys(&[], Some(x)).unwrap(), vec![s.key()]);
assert!(trusted_keys(&[], Some("bm90IGEga2V5".into())).is_err());
assert!(trusted_keys(&[], None).unwrap().is_empty());
// Every built-in profile ships without a root today: fail closed.
for env in [
crate::profile::Env::Lab,
crate::profile::Env::Staging,
crate::profile::Env::Prod,
] {
for r in profile_roots(env) {
TrustedKey::from_b64(r).unwrap();
}
}
}
#[test]
fn previews_say_what_will_change() {
let s = Signer::new(7);
let issues = ISSUES;
let link = parse_link("zakuro://open?view=contribution").unwrap();
let p = describe(&link, None, &issues);
assert_eq!(
(p.title.as_str(), p.view.as_str(), p.available),
("Open Contribution", "contribution", true)
);
assert!(p.jti.is_none());
let c = verify(
&s.mint(claims("squad/join", "j")),
Act::SquadJoin,
&[s.key()],
NOW,
)
.unwrap();
let link = Link::Signed {
act: Act::SquadJoin,
token: String::new(),
};
let p = describe(&link, Some(&c), &issues);
assert_eq!(p.title, "Join Kyoto Vision");
assert!(!p.available);
assert_eq!(p.until.as_deref(), Some("zakuro-ai/zc#517"));
assert_eq!(p.view, "squads");
let v = with(
claims("share/budget", "j"),
"args",
json!({"node_pubkey": NODE_PK, "proposed": {"price_per_hour": 120}}),
);
let c = verify(&s.mint(v), Act::ShareBudget, &[s.key()], NOW).unwrap();
let link = Link::Signed {
act: Act::ShareBudget,
token: String::new(),
};
let p = describe(&link, Some(&c), &issues);
assert!(p.available);
assert_eq!(p.view, "budget");
assert_eq!(p.prefill, Some(json!({"price_per_hour": 120})));
assert_eq!(
p.details[0],
Detail {
label: "Price".into(),
value: "¥120/h".into()
}
);
}
fn ctx<'a>(keys: &'a [TrustedKey]) -> Context<'a> {
Context {
keys,
env: "staging",
account_sub: Some("1234567890"),
node_fp: NODE_FP,
node_pubkey: NODE_PK,
now: NOW,
}
}
#[test]
fn handoffs_confirm_once_and_never_run_what_is_not_available() {
let s = Signer::new(7);
let keys = [s.key()];
let dir = std::env::temp_dir().join(format!("zc-handoffs-{}", std::process::id()));
let path = dir.join("handoff_seen.json");
let mut h = Handoffs::new(Some(path.clone()));
let v = with(
claims("share/budget", "b1"),
"args",
json!({"node_pubkey": NODE_PK, "proposed": {"price_per_hour": 120}}),
);
let link = format!("zakuro://share/budget?t={}", s.mint(v));
let p = h.open(&link, &ctx(&keys), &ISSUES).unwrap();
assert_eq!(p.jti.as_deref(), Some("b1"));
// Opening it twice before confirming shows the same sheet.
assert_eq!(h.open(&link, &ctx(&keys), &ISSUES).unwrap(), p);
let done = h.confirm("b1", NOW).unwrap();
assert_eq!(
(done.view.as_str(), done.prefill.clone()),
("budget", Some(json!({"price_per_hour": 120})))
);
assert_eq!(
h.confirm("b1", NOW),
Err(ConfirmError::Link(LinkError::AlreadyUsed))
);
assert_eq!(
h.open(&link, &ctx(&keys), &ISSUES),
Err(LinkError::AlreadyUsed)
);
// The used id survives a restart.
let mut again = Handoffs::new(Some(path));
assert_eq!(
again.open(&link, &ctx(&keys), &ISSUES),
Err(LinkError::AlreadyUsed)
);
// Squads are not in this zc yet: verified, shown, never run or used.
let link = format!(
"zakuro://squad/join?t={}",
s.mint(claims("squad/join", "s1"))
);
h.open(&link, &ctx(&keys), &ISSUES).unwrap();
assert_eq!(
h.confirm("s1", NOW),
Err(ConfirmError::NotAvailable {
until: "zakuro-ai/zc#517".into(),
view: "squads".into()
})
);
assert!(h.open(&link, &ctx(&keys), &ISSUES).is_ok());
assert_eq!(h.confirm("nope", NOW), Err(ConfirmError::NotFound));
// Past exp, a pending link no longer runs.
let link = format!(
"zakuro://share/budget?t={}",
s.mint(with(
claims("share/budget", "b2"),
"args",
json!({"node_pubkey": NODE_PK})
))
);
h.open(&link, &ctx(&keys), &ISSUES).unwrap();
assert_eq!(
h.confirm("b2", NOW + 590 + LEEWAY_SECS),
Err(ConfirmError::Link(LinkError::Expired))
);
// No action key for the profile: every signed link is refused.
assert_eq!(
h.open(&link, &ctx(&[]), &ISSUES),
Err(LinkError::NoTrustRoot("staging".into()))
);
// Token-less links need no key.
assert!(h
.open("zakuro://open?view=contribution", &ctx(&[]), &ISSUES)
.is_ok());
let _ = std::fs::remove_dir_all(dir);
}
/// The agent and a `zc link` run without the agent share one file: an
/// id one of them used is refused by the other, and neither save drops
/// the other's ids (review of zc#541, finding 1).
#[test]
fn two_handoffs_on_one_file_never_lose_a_used_id() {
let s = Signer::new(7);
let keys = [s.key()];
let dir = std::env::temp_dir().join(format!("zc-handoffs-two-{}", std::process::id()));
let path = dir.join("handoff_seen.json");
let budget = |jti: &str| {
format!(
"zakuro://share/budget?t={}",
s.mint(with(
claims("share/budget", jti),
"args",
json!({"node_pubkey": NODE_PK})
))
)
};
// The agent starts first, with an empty file.
let mut agent = Handoffs::new(Some(path.clone()));
agent.open(&budget("x"), &ctx(&keys), &ISSUES).unwrap();
// `zc link` (agent busy) confirms "x" on its own.
let mut cli = Handoffs::new(Some(path.clone()));
cli.open(&budget("x"), &ctx(&keys), &ISSUES).unwrap();
cli.confirm("x", NOW).unwrap();
// The agent sees it on confirm and on open.
assert_eq!(
agent.confirm("x", NOW),
Err(ConfirmError::Link(LinkError::AlreadyUsed))
);
assert_eq!(
agent.open(&budget("x"), &ctx(&keys), &ISSUES),
Err(LinkError::AlreadyUsed)
);
// The agent's next save keeps "x".
agent.open(&budget("y"), &ctx(&keys), &ISSUES).unwrap();
agent.confirm("y", NOW).unwrap();
let disk = Seen::load(&path).unwrap();
assert!(disk.contains("x") && disk.contains("y"));
let _ = std::fs::remove_dir_all(dir);
}
/// A corrupt used-id file refuses signed links instead of reading as
/// empty, until it is older than any token could live (finding 10).
#[test]
fn a_corrupt_seen_file_fails_closed_until_it_is_stale() {
let dir = std::env::temp_dir().join(format!("zc-seen-corrupt-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let path = dir.join("handoff_seen.json");
std::fs::write(&path, b"{\"used\": {\"j\": ").unwrap();
let now = std::time::SystemTime::now();
assert!(matches!(
Seen::load_at(&path, now),
Err(LinkError::Storage(_))
));
let later =
now + std::time::Duration::from_secs((MAX_TTL_SECS + 2 * LEEWAY_SECS + 5) as u64);
assert_eq!(Seen::load_at(&path, later), Ok(Seen::default()));
let s = Signer::new(7);
let keys = [s.key()];
let mut h = Handoffs::new(Some(path.clone()));
let link = format!(
"zakuro://share/budget?t={}",
s.mint(with(
claims("share/budget", "c1"),
"args",
json!({"node_pubkey": NODE_PK})
))
);
let e = h.open(&link, &ctx(&keys), &ISSUES).unwrap_err();
assert_eq!((e.status(), e.code()), (500, "storage"));
// Token-less links do not need the file.
assert!(h
.open("zakuro://open?view=contribution", &ctx(&keys), &ISSUES)
.is_ok());
// A missing file is an empty set.
std::fs::remove_file(&path).unwrap();
assert!(h.open(&link, &ctx(&keys), &ISSUES).is_ok());
let _ = std::fs::remove_dir_all(dir);
}
/// A failed write of the used-id file is a storage error, not a key
/// problem (finding 6).
#[test]
fn a_failed_seen_write_is_a_storage_error() {
let s = Signer::new(7);
let keys = [s.key()];
let dir = std::env::temp_dir().join(format!("zc-seen-ro-{}", std::process::id()));
// A directory where the file should be: reads fail with "is a
// directory" on load; use a parent that is a regular file instead.
std::fs::create_dir_all(&dir).unwrap();
let blocker = dir.join("agent");
std::fs::write(&blocker, b"not a dir").unwrap();
let mut h = Handoffs::new(Some(blocker.join("handoff_seen.json")));
let link = format!(
"zakuro://share/budget?t={}",
s.mint(with(
claims("share/budget", "w1"),
"args",
json!({"node_pubkey": NODE_PK})
))
);
let opened = h.open(&link, &ctx(&keys), &ISSUES);
let err = match opened {
Ok(_) => match h.confirm("w1", NOW) {
Err(ConfirmError::Link(e)) => e,
other => panic!("expected a storage error, got {other:?}"),
},
Err(e) => e,
};
assert_eq!((err.status(), err.code()), (500, "storage"));
let _ = std::fs::remove_dir_all(dir);
}
/// The signed-in hub picks the trust roots, not a profile the
/// LaunchAgent never set (a staging login under a prod default).
#[test]
fn the_signed_in_hub_picks_the_link_environment() {
use crate::profile::Env;
assert_eq!(
env_for_api_url(Some(crate::credentials::STAGING_API_URL)),
Env::Staging
);
assert_eq!(
env_for_api_url(Some(&format!("{}/", crate::credentials::STAGING_API_URL))),
Env::Staging
);
assert_eq!(
env_for_api_url(Some(crate::credentials::PROD_API_URL)),
Env::Prod
);
let fallback = crate::profile::active().env;
assert_eq!(env_for_api_url(Some("http://10.0.0.5:8080")), fallback);
assert_eq!(env_for_api_url(None), fallback);
}
#[test]
fn staging_trusts_its_hub_key_and_prod_trusts_none() {
use crate::profile::Env;
let k = trusted_keys(profile_roots(Env::Staging), None).unwrap();
assert_eq!(k.len(), 1);
assert_eq!(k[0].kid, "bde74a18996820b2");
assert!(trusted_keys(profile_roots(Env::Prod), None)
.unwrap()
.is_empty());
}
/// A token minted by the hub's own code (zak-marketplace
/// `services/action_tokens.mint`, PyJWT 2.13, seed `[42; 32]`): the
/// wire format is the hub's, not a re-implementation of it.
const HUB_PUBKEY: &str = "GX9rI+FshTLGq8g4+s1ep4m+DHaykgM0A5v6iz02jWE=";
const HUB_TOKEN: &str = "eyJhbGciOiJFZERTQSIsImtpZCI6ImI2MDAzMDZjZmE3NjcyM2YiLCJ0eXAiOiJKV1QifQ.eyJhY3QiOiJzaGFyZS9idWRnZXQiLCJhcmdzIjp7Im5vZGVfcHVia2V5IjoicThYMm4wTHI0bUg2dkI5c0szd1Q3eVAxY0Y1Z0owZFoyYUU0dVI4aU82cz0iLCJwcm9wb3NlZCI6eyJwcmljZV9wZXJfaG91ciI6MTIwfX0sInN1YiI6IjEyMzQ1Njc4OTAiLCJpYXQiOjE3OTk5OTk5OTAsImV4cCI6MTgwMDAwMDU5MCwianRpIjoiNWYwYzlkMWFiMmUzNGY2ZjlhN2MxZDJlM2Y0MDUxNjIiLCJraWQiOiJiNjAwMzA2Y2ZhNzY3MjNmIiwiaXNzIjoiaHR0cHM6Ly9zdGcuaHViLnpha3Vyby1haS5jb20iLCJub2RlIjoiMDEyMzQ1Njc4OWFiY2RlZiJ9.E2RFli4y7gzamjzFPHdAtdT50pjd8sDOLFT574QRPLNT7gNtqj65BqteiQ7-BCWGB3HMpOquSZY0L94modUrAQ";
#[test]
fn verifies_a_token_the_hub_minted() {
let keys = trusted_keys(&[HUB_PUBKEY], None).unwrap();
assert_eq!(keys[0].kid, "b600306cfa76723f");
let c = verify(HUB_TOKEN, Act::ShareBudget, &keys, NOW).unwrap();
assert_eq!(c.jti, "5f0c9d1ab2e34f6f9a7c1d2e3f405162");
assert_eq!(c.kid.as_deref(), Some("b600306cfa76723f"));
check_binding(&c, Some("1234567890"), NODE_FP, NODE_PK).unwrap();
let link = parse_link(&format!("zakuro://share/budget?t={HUB_TOKEN}")).unwrap();
let p = describe(&link, Some(&c), &ISSUES);
assert_eq!(p.prefill, Some(json!({"price_per_hour": 120})));
}
}