tenuo 0.3.2

Task-scoped authorization for AI agents: signed warrants that constrain tools and arguments, narrow on delegation, and verify offline. Rust core of Tenuo.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
//! Connect token support for streamlined onboarding.
//!
//! A connect token (`tenuo_ct_<base64url-json>`) bundles the credentials
//! needed to register an authorizer with a control plane into a single
//! string. It can be shared across multiple authorizer instances.
//!
//! # Token format (v1)
//!
//! ```text
//! tenuo_ct_<base64url({"v":1,"e":"<endpoint>","k":"<api_key>","a":"<agent_id>","t":"<reg_token>"})>
//! ```
//!
//! The `e` field may or may not include a `/v1` suffix; [`ConnectToken::parse`]
//! normalizes it to the bare origin so callers can uniformly build
//! `{endpoint}/v1/…` paths.
//!
//! Fields `a` (agent ID) and `t` (registration token) are optional — when absent
//! the token acts as a pure authorizer credential without agent binding.

use base64::Engine;
use serde::{Deserialize, Serialize};

const TOKEN_PREFIX: &str = "tenuo_ct_";

/// Strip trailing slashes and a trailing `/v1` so callers append `/v1/…` once.
pub fn normalize_control_plane_url(url: &str) -> String {
    let mut endpoint = url.trim().trim_end_matches('/').to_string();
    if endpoint.ends_with("/v1") {
        endpoint.truncate(endpoint.len() - 3);
        endpoint = endpoint.trim_end_matches('/').to_string();
    }
    endpoint
}

/// Parsed connect token payload.
///
/// `Debug` and `Serialize` redact `api_key` and `registration_token`.
#[derive(Clone, Deserialize)]
pub struct ConnectToken {
    /// Token format version. [`ConnectToken::parse`] accepts only version 1.
    #[serde(rename = "v")]
    pub version: u8,
    /// Control plane API base endpoint.
    ///
    /// Callers append `/v1/…` paths to this value. If the token's `e` field
    /// contains a trailing `/v1` it is stripped during [`ConnectToken::parse`]
    /// so all URL construction is consistent.
    #[serde(rename = "e")]
    pub endpoint: String,
    /// API key with `authorizer` scope.
    #[serde(rename = "k")]
    pub api_key: String,
    /// Pre-created agent ID (omitted for authorizer-only tokens).
    #[serde(rename = "a", default, skip_serializing_if = "Option::is_none")]
    pub agent_id: Option<String>,
    /// One-time registration token for claiming the agent.
    #[serde(
        rename = "t",
        alias = "r",
        alias = "registration_token",
        default,
        skip_serializing_if = "Option::is_none"
    )]
    pub registration_token: Option<String>,
}

impl std::fmt::Debug for ConnectToken {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ConnectToken")
            .field("version", &self.version)
            .field("endpoint", &self.endpoint)
            .field("api_key", &"[REDACTED]")
            .field("agent_id", &self.agent_id)
            .field(
                "registration_token",
                &self.registration_token.as_ref().map(|_| "[REDACTED]"),
            )
            .finish()
    }
}

impl Serialize for ConnectToken {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        use serde::ser::SerializeStruct;
        let mut state = serializer.serialize_struct("ConnectToken", 5)?;
        state.serialize_field("v", &self.version)?;
        state.serialize_field("e", &self.endpoint)?;
        state.serialize_field("k", "[REDACTED]")?;
        state.serialize_field("a", &self.agent_id)?;
        state.serialize_field("t", &self.registration_token.as_ref().map(|_| "[REDACTED]"))?;
        state.end()
    }
}

/// Errors specific to connect token operations.
#[derive(Debug)]
#[non_exhaustive]
pub enum ConnectTokenError {
    /// Token string does not start with the expected prefix.
    MissingPrefix,
    /// Base64 decoding failed.
    Base64(String),
    /// JSON parsing failed.
    Json(String),
    /// A required field is empty.
    MissingField(&'static str),
    /// Agent claim HTTP request failed.
    ClaimFailed(String),
    /// Token version is not supported by this SDK.
    UnsupportedVersion(u64),
}

impl std::fmt::Display for ConnectTokenError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::MissingPrefix => write!(f, "token must start with '{}'", TOKEN_PREFIX),
            Self::Base64(e) => write!(f, "base64 decode error: {}", e),
            Self::Json(e) => write!(f, "JSON parse error: {}", e),
            Self::MissingField(name) => write!(f, "required field '{}' is empty", name),
            Self::ClaimFailed(e) => write!(f, "agent claim failed: {}", e),
            Self::UnsupportedVersion(v) => write!(
                f,
                "connect token version {} is not supported by this SDK (max: 1). \
                 Upgrade tenuo to use this token.",
                v
            ),
        }
    }
}

impl std::error::Error for ConnectTokenError {}

impl ConnectToken {
    /// Parse a raw `tenuo_ct_…` string into a [`ConnectToken`].
    pub fn parse(raw: &str) -> Result<Self, ConnectTokenError> {
        let encoded = raw
            .trim()
            .strip_prefix(TOKEN_PREFIX)
            .ok_or(ConnectTokenError::MissingPrefix)?;

        let json_bytes = base64::engine::general_purpose::URL_SAFE_NO_PAD
            .decode(encoded)
            .or_else(|_| base64::engine::general_purpose::URL_SAFE.decode(encoded))
            .or_else(|_| base64::engine::general_purpose::STANDARD_NO_PAD.decode(encoded))
            .or_else(|_| base64::engine::general_purpose::STANDARD.decode(encoded))
            .map_err(|e| ConnectTokenError::Base64(e.to_string()))?;

        let value: serde_json::Value = serde_json::from_slice(&json_bytes)
            .map_err(|e| ConnectTokenError::Json(e.to_string()))?;
        if !value.is_object() {
            return Err(ConnectTokenError::Json(
                "connect token payload must be a JSON object".into(),
            ));
        }
        match value.get("v") {
            None | Some(serde_json::Value::Null) => {
                return Err(ConnectTokenError::MissingField("version"));
            }
            Some(v) => {
                let parsed = v.as_u64().ok_or_else(|| {
                    ConnectTokenError::Json(
                        "version must be a non-negative integer. This SDK supports version 1."
                            .into(),
                    )
                })?;
                if parsed != 1 {
                    return Err(ConnectTokenError::UnsupportedVersion(parsed));
                }
            }
        }

        let token: ConnectToken =
            serde_json::from_value(value).map_err(|e| ConnectTokenError::Json(e.to_string()))?;

        if token.endpoint.is_empty() {
            return Err(ConnectTokenError::MissingField("endpoint"));
        }
        if token.api_key.is_empty() {
            return Err(ConnectTokenError::MissingField("api_key"));
        }

        Ok(ConnectToken {
            endpoint: normalize_control_plane_url(&token.endpoint),
            ..token
        })
    }

    /// True when `e` was a relative path such as `/v1` and parse stripped it
    /// to an empty or path-only origin. The caller must supply a base URL.
    pub fn needs_endpoint_base(&self) -> bool {
        self.endpoint.is_empty() || self.endpoint.starts_with('/')
    }

    /// Resolve a relative connect-token endpoint against a caller-provided base.
    ///
    /// `base` is an origin such as `https://control.example.com` or the same
    /// origin with a `/v1` suffix. This method never invents an origin.
    /// Absolute endpoints are left unchanged.
    pub fn resolve_endpoint(&mut self, base: &str) -> Result<(), ConnectTokenError> {
        if !self.needs_endpoint_base() {
            return Ok(());
        }
        let origin = normalize_control_plane_url(base);
        if origin.is_empty() || origin.starts_with('/') {
            return Err(ConnectTokenError::MissingField("endpoint"));
        }
        let remainder = self.endpoint.clone();
        self.endpoint = if remainder.is_empty() || remainder == "/" {
            origin
        } else {
            format!("{}{}", origin.trim_end_matches('/'), remainder)
        };
        Ok(())
    }

    /// Claim the pre-created agent using the embedded registration token.
    ///
    /// This is a no-op when `agent_id` or `registration_token` is absent.
    /// HTTP 409 (already claimed) is treated as success so the same token can
    /// be safely reused by multiple authorizer instances.
    #[cfg(feature = "server")]
    pub async fn claim_agent(
        &self,
        signing_key: &crate::crypto::SigningKey,
    ) -> Result<(), ConnectTokenError> {
        let (agent_id, reg_token) = match (&self.agent_id, &self.registration_token) {
            (Some(a), Some(t)) if !a.is_empty() && !t.is_empty() => (a, t),
            _ => return Ok(()),
        };

        let public_key_hex = hex::encode(signing_key.public_key().to_bytes());
        let claim_url = format!("{}/v1/agents/claim", self.endpoint.trim_end_matches('/'));

        let body = serde_json::json!({
            "agent_id": agent_id,
            "public_key": public_key_hex,
            "registration_token": reg_token,
        });

        let client = reqwest::Client::builder()
            .timeout(std::time::Duration::from_secs(10))
            .build()
            .map_err(|e| ConnectTokenError::ClaimFailed(e.to_string()))?;

        tracing::debug!(agent_id = %agent_id, "claiming agent via connect token");

        let resp = client
            .post(&claim_url)
            .header("Authorization", format!("Bearer {}", self.api_key))
            .header("Content-Type", "application/json")
            .json(&body)
            .send()
            .await
            .map_err(|e| ConnectTokenError::ClaimFailed(e.to_string()))?;

        let status = resp.status().as_u16();
        match status {
            200..=299 => {
                tracing::info!(agent_id = %agent_id, "agent claimed successfully");
                Ok(())
            }
            409 => {
                tracing::debug!(agent_id = %agent_id, "agent already claimed (idempotent)");
                Ok(())
            }
            _ => {
                let msg = resp.text().await.unwrap_or_default();
                tracing::warn!(agent_id = %agent_id, status, body = %msg, "agent claim returned non-success");
                Err(ConnectTokenError::ClaimFailed(format!(
                    "HTTP {}: {}",
                    status, msg
                )))
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn make_token_str(payload: &str) -> String {
        let encoded = base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(payload);
        format!("{}{}", TOKEN_PREFIX, encoded)
    }

    #[test]
    fn parse_full_token() {
        let raw = make_token_str(
            r#"{"v":1,"e":"https://control.example.com/v1","k":"tc_abc","a":"my-agent","t":"tok123"}"#,
        );
        let ct = ConnectToken::parse(&raw).unwrap();
        assert_eq!(ct.version, 1);
        assert_eq!(ct.endpoint, "https://control.example.com");
        assert_eq!(ct.api_key, "tc_abc");
        assert_eq!(ct.agent_id.as_deref(), Some("my-agent"));
        assert_eq!(ct.registration_token.as_deref(), Some("tok123"));
    }

    #[test]
    fn parse_token_without_v1_suffix() {
        let raw = make_token_str(
            r#"{"v":1,"e":"https://control.example.com","k":"tc_abc","a":"my-agent","t":"tok123"}"#,
        );
        let ct = ConnectToken::parse(&raw).unwrap();
        assert_eq!(ct.endpoint, "https://control.example.com");
    }

    #[test]
    fn parse_token_with_trailing_slash() {
        let raw = make_token_str(r#"{"v":1,"e":"https://control.example.com/v1/","k":"tc_abc"}"#);
        let ct = ConnectToken::parse(&raw).unwrap();
        assert_eq!(ct.endpoint, "https://control.example.com");
    }

    #[test]
    fn parse_authorizer_only_token() {
        let raw = make_token_str(r#"{"v":1,"e":"https://control.example.com/v1","k":"tc_xyz"}"#);
        let ct = ConnectToken::parse(&raw).unwrap();
        assert_eq!(ct.version, 1);
        assert_eq!(ct.endpoint, "https://control.example.com");
        assert!(ct.agent_id.is_none());
        assert!(ct.registration_token.is_none());
    }

    #[test]
    fn parse_padded_base64url_and_registration_alias() {
        let payload =
            r#"{"v":1,"e":"https://control.example.com/v1","k":"tc_abc","r":"tok-alias"}"#;
        let padded = base64::engine::general_purpose::URL_SAFE.encode(payload);
        let raw = format!("{TOKEN_PREFIX}{padded}");
        let ct = ConnectToken::parse(&raw).unwrap();
        assert_eq!(ct.registration_token.as_deref(), Some("tok-alias"));
    }

    #[test]
    fn parse_trims_whitespace_and_accepts_standard_base64() {
        let payload = br#"{"v":1,"e":"https://control.example.com/v1","k":"tc_abc"}"#;
        let encoded = base64::engine::general_purpose::STANDARD.encode(payload);
        let raw = format!("  {TOKEN_PREFIX}{encoded}\n");
        let ct = ConnectToken::parse(&raw).unwrap();
        assert_eq!(ct.api_key, "tc_abc");
        assert_eq!(ct.endpoint, "https://control.example.com");
    }

    #[test]
    fn parse_v0_token_without_version() {
        let raw = make_token_str(
            r#"{"e":"https://control.example.com/v1","k":"tc_old","a":"ag","t":"rt"}"#,
        );
        assert!(matches!(
            ConnectToken::parse(&raw),
            Err(ConnectTokenError::MissingField("version"))
        ));
    }

    #[test]
    fn reject_missing_prefix() {
        assert!(ConnectToken::parse("not_a_token").is_err());
    }

    #[test]
    fn reject_empty_endpoint() {
        let raw = make_token_str(r#"{"v":1,"e":"","k":"tc_abc"}"#);
        assert!(matches!(
            ConnectToken::parse(&raw),
            Err(ConnectTokenError::MissingField("endpoint"))
        ));
    }

    #[test]
    fn reject_empty_api_key() {
        let raw = make_token_str(r#"{"v":1,"e":"https://control.example.com","k":""}"#);
        assert!(matches!(
            ConnectToken::parse(&raw),
            Err(ConnectTokenError::MissingField("api_key"))
        ));
    }

    #[test]
    fn reject_future_version() {
        let raw = make_token_str(r#"{"v":2,"e":"https://control.example.com","k":"tc_abc"}"#);
        assert!(matches!(
            ConnectToken::parse(&raw),
            Err(ConnectTokenError::UnsupportedVersion(2))
        ));
    }

    #[test]
    fn relative_v1_endpoint_needs_caller_base() {
        let raw = make_token_str(r#"{"v":1,"e":"/v1","k":"tc_abc"}"#);
        let mut ct = ConnectToken::parse(&raw).unwrap();
        assert!(ct.needs_endpoint_base());
        ct.resolve_endpoint("https://control.example.com/v1")
            .unwrap();
        assert_eq!(ct.endpoint, "https://control.example.com");
        assert!(!ct.needs_endpoint_base());
    }

    #[test]
    fn resolve_endpoint_does_not_replace_absolute_origin() {
        let raw = make_token_str(r#"{"v":1,"e":"https://control.example.com/v1","k":"tc_abc"}"#);
        let mut ct = ConnectToken::parse(&raw).unwrap();
        ct.resolve_endpoint("https://other.example").unwrap();
        assert_eq!(ct.endpoint, "https://control.example.com");
    }

    #[test]
    fn resolve_endpoint_joins_remaining_relative_path() {
        let raw = make_token_str(r#"{"v":1,"e":"/api/v1","k":"tc_abc"}"#);
        let mut ct = ConnectToken::parse(&raw).unwrap();
        assert_eq!(ct.endpoint, "/api");
        ct.resolve_endpoint("https://control.example.com").unwrap();
        assert_eq!(ct.endpoint, "https://control.example.com/api");
    }

    #[test]
    fn reject_version_out_of_u8_range() {
        let raw = make_token_str(r#"{"v":257,"e":"https://control.example.com","k":"tc_abc"}"#);
        assert!(matches!(
            ConnectToken::parse(&raw),
            Err(ConnectTokenError::UnsupportedVersion(257))
        ));
        assert!(ConnectToken::parse(&raw)
            .unwrap_err()
            .to_string()
            .contains("257"));
    }

    #[test]
    fn resolve_endpoint_rejects_empty_or_relative_base() {
        let raw = make_token_str(r#"{"v":1,"e":"/v1","k":"tc_abc"}"#);
        let mut ct = ConnectToken::parse(&raw).unwrap();
        assert!(matches!(
            ct.resolve_endpoint("/v1"),
            Err(ConnectTokenError::MissingField("endpoint"))
        ));
        assert!(matches!(
            ct.resolve_endpoint(""),
            Err(ConnectTokenError::MissingField("endpoint"))
        ));
    }

    #[test]
    fn debug_and_serialize_redact_secrets() {
        let raw = make_token_str(
            r#"{"v":1,"e":"https://control.example.com","k":"tc_secret","t":"reg_secret"}"#,
        );
        let ct = ConnectToken::parse(&raw).unwrap();
        let debug = format!("{ct:?}");
        assert!(!debug.contains("tc_secret"), "{debug}");
        assert!(!debug.contains("reg_secret"), "{debug}");
        assert!(debug.contains("[REDACTED]"), "{debug}");
        let json = serde_json::to_string(&ct).unwrap();
        assert!(!json.contains("tc_secret"), "{json}");
        assert!(!json.contains("reg_secret"), "{json}");
        assert!(json.contains("[REDACTED]"), "{json}");
    }
}