sail-rs 0.5.9

Official Rust SDK for Sail: create and drive sailboxes (sandboxed cloud VMs) with lifecycle, streaming exec, file transfer, and ingress.
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
//! Wire types for org secrets and credential injection policies, plus the
//! client-side validation shared with the language bindings.

use serde::{Deserialize, Serialize};
use time::OffsetDateTime;

use crate::error::SailError;

/// Longest accepted secret name; matches the service's rule.
const MAX_SECRET_NAME_LEN: usize = 128;
/// Largest accepted secret value in bytes; matches the service's rule.
const MAX_SECRET_VALUE_BYTES: usize = 64 * 1024;
/// Most rules one policy may carry; matches the service's rule.
const MAX_POLICY_RULES: usize = 100;
/// Longest accepted policy name in characters; matches the service's rule.
const MAX_POLICY_NAME_CHARS: usize = 128;
/// Longest accepted rule value template in bytes; matches the service's rule.
const MAX_RULE_VALUE_BYTES: usize = 512;

/// A secret's name and timestamps.
///
/// Secret values are write-only. They are accepted by
/// [`Credentials::set_secret`](crate::Credentials::set_secret) and can never
/// be read back, so no value field exists here.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[non_exhaustive]
pub struct SecretInfo {
    /// The secret's name, unique within the organization.
    pub name: String,
    /// When the secret was first set.
    #[serde(with = "crate::rfc3339_micros")]
    pub created_at: OffsetDateTime,
    /// When the secret's value last changed.
    #[serde(with = "crate::rfc3339_micros")]
    pub updated_at: OffsetDateTime,
}

/// Where an injection rule writes its value: an HTTP header or a URL query
/// parameter. An unrecognized kind a newer service introduces is preserved in
/// `Other` so decoding an existing policy never fails.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum InjectionTargetKind {
    /// Replace an HTTP request header.
    Header,
    /// Replace a URL query parameter.
    QueryParam,
    /// A target kind this SDK version does not recognize, kept verbatim.
    Other(String),
}

impl InjectionTargetKind {
    /// The wire string for this target kind.
    pub fn as_str(&self) -> &str {
        match self {
            InjectionTargetKind::Header => "header",
            InjectionTargetKind::QueryParam => "query_param",
            InjectionTargetKind::Other(s) => s,
        }
    }
}

impl From<&str> for InjectionTargetKind {
    fn from(s: &str) -> InjectionTargetKind {
        match s {
            "header" => InjectionTargetKind::Header,
            "query_param" => InjectionTargetKind::QueryParam,
            other => InjectionTargetKind::Other(other.to_string()),
        }
    }
}

impl std::fmt::Display for InjectionTargetKind {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(self.as_str())
    }
}

impl Serialize for InjectionTargetKind {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        serializer.serialize_str(self.as_str())
    }
}

impl<'de> Deserialize<'de> for InjectionTargetKind {
    fn deserialize<D: serde::Deserializer<'de>>(
        deserializer: D,
    ) -> Result<InjectionTargetKind, D::Error> {
        Ok(InjectionTargetKind::from(
            String::deserialize(deserializer)?.as_str(),
        ))
    }
}

/// The request component an injection rule replaces. `kind` picks a header
/// or query parameter; `name` names it.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct InjectionTarget {
    /// Which request component to replace.
    #[serde(rename = "type")]
    pub kind: InjectionTargetKind,
    /// The header or query-parameter name to replace.
    pub name: String,
}

/// A rule that sets its `target` header or query parameter on requests to an
/// exact `host`, using the rendered `value` template.
///
/// The value template mixes literal text with `${secrets.NAME}` references
/// (write `$$` for a literal `$`). Build rules with [`InjectionRule::header`]
/// or [`InjectionRule::query_param`]:
///
/// ```
/// use sail::InjectionRule;
///
/// let rule = InjectionRule::header(
///     "api.github.com",
///     "Authorization",
///     "Bearer ${secrets.GITHUB_TOKEN}",
/// );
/// # let _ = rule;
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct InjectionRule {
    /// Exact hostname the rule applies to (no scheme, port, or wildcard).
    pub host: String,
    /// The request component to replace.
    pub target: InjectionTarget,
    /// The value template rendered into the target on every match.
    pub value: String,
}

impl InjectionRule {
    /// A rule that sets the header `name` on requests to `host`.
    pub fn header(
        host: impl Into<String>,
        name: impl Into<String>,
        value: impl Into<String>,
    ) -> InjectionRule {
        InjectionRule {
            host: host.into(),
            target: InjectionTarget {
                kind: InjectionTargetKind::Header,
                name: name.into(),
            },
            value: value.into(),
        }
    }

    /// A rule that sets the query parameter `name` on requests to `host`.
    pub fn query_param(
        host: impl Into<String>,
        name: impl Into<String>,
        value: impl Into<String>,
    ) -> InjectionRule {
        InjectionRule {
            host: host.into(),
            target: InjectionTarget {
                kind: InjectionTargetKind::QueryParam,
                name: name.into(),
            },
            value: value.into(),
        }
    }
}

/// A credential injection policy's id, name, and immutable rules.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[non_exhaustive]
pub struct CredentialInjectionPolicyInfo {
    /// Stable server-assigned policy identifier.
    pub id: String,
    /// Human-readable policy name (the only mutable field).
    pub name: String,
    /// The policy's rules, immutable after creation.
    pub rules: Vec<InjectionRule>,
    /// Policy creation time.
    #[serde(with = "crate::rfc3339_micros")]
    pub created_at: OffsetDateTime,
    /// Last time the policy's name changed.
    #[serde(with = "crate::rfc3339_micros")]
    pub updated_at: OffsetDateTime,
}

/// A policy as returned by
/// [`Credentials::list_policies`](crate::Credentials::list_policies), with
/// usage counts but without the rules. Fetch the full policy by id for its
/// rules.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[non_exhaustive]
pub struct CredentialInjectionPolicySummary {
    /// Stable server-assigned policy identifier.
    pub id: String,
    /// Human-readable policy name.
    pub name: String,
    /// How many rules the policy carries.
    pub rule_count: i64,
    /// The secret names the policy's rules reference.
    pub referenced_secret_names: Vec<String>,
    /// How many Sailboxes the policy is currently attached to.
    pub attachment_count: i64,
    /// Policy creation time.
    #[serde(with = "crate::rfc3339_micros")]
    pub created_at: OffsetDateTime,
    /// Last time the policy's name changed.
    #[serde(with = "crate::rfc3339_micros")]
    pub updated_at: OffsetDateTime,
}

/// One page of policy listings plus the pagination envelope.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[non_exhaustive]
pub struct CredentialInjectionPolicyPage {
    /// The policies in this page.
    #[serde(rename = "data")]
    pub items: Vec<CredentialInjectionPolicySummary>,
    /// Maximum number of items requested for this page.
    pub limit: i64,
    /// Zero-based offset of the first item in this page.
    pub offset: i64,
    /// Total number of policies matching the query across all pages.
    pub total: i64,
    /// True when further pages exist beyond this one.
    pub has_more: bool,
}

/// Query parameters for
/// [`Credentials::list_policies`](crate::Credentials::list_policies).
#[derive(Debug, Clone)]
pub struct ListCredentialInjectionPoliciesQuery {
    /// Case-insensitive name filter; `None` lists every policy.
    pub search: Option<String>,
    /// Page size (1-100).
    pub limit: i64,
    /// Zero-based offset of the first item.
    pub offset: i64,
}

impl Default for ListCredentialInjectionPoliciesQuery {
    fn default() -> Self {
        ListCredentialInjectionPoliciesQuery {
            search: None,
            limit: crate::sailbox::types::DEFAULT_LIST_LIMIT,
            offset: 0,
        }
    }
}

/// Validate a secret name against the service's rule: 1-128 characters, first
/// a letter or digit, the rest letters, digits, underscores, or dashes.
/// Shared client-side source of truth so a wrapper fails fast.
#[doc(hidden)]
pub fn validate_secret_name(name: &str) -> Result<(), SailError> {
    let mut chars = name.chars();
    let valid_first = chars.next().is_some_and(|c| c.is_ascii_alphanumeric());
    let valid_rest = chars.all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-');
    if !valid_first || !valid_rest || name.len() > MAX_SECRET_NAME_LEN {
        return Err(SailError::InvalidArgument {
            message: "secret name must start with a letter or number and use only letters, \
                      numbers, underscores, and dashes (at most 128 characters)"
                .to_string(),
        });
    }
    Ok(())
}

/// Validate a secret value against the service's rule: non-empty, at most
/// 64 KiB, and free of ASCII control characters.
pub(crate) fn validate_secret_value(value: &str) -> Result<(), SailError> {
    if value.is_empty() {
        return Err(SailError::InvalidArgument {
            message: "secret value must not be empty".to_string(),
        });
    }
    if value.len() > MAX_SECRET_VALUE_BYTES {
        return Err(SailError::InvalidArgument {
            message: "secret value must be at most 64 KiB".to_string(),
        });
    }
    if value.bytes().any(|b| b < 0x20 || b == 0x7f) {
        return Err(SailError::InvalidArgument {
            message: "secret value must not contain ASCII control characters".to_string(),
        });
    }
    Ok(())
}

/// Validate a policy name against the service's rule: non-blank, at most 128
/// characters, no control characters.
pub(crate) fn validate_policy_name(name: &str) -> Result<(), SailError> {
    let trimmed = name.trim();
    if trimmed.is_empty() {
        return Err(SailError::InvalidArgument {
            message: "policy name must not be empty".to_string(),
        });
    }
    if trimmed.chars().count() > MAX_POLICY_NAME_CHARS {
        return Err(SailError::InvalidArgument {
            message: format!("policy name must be at most {MAX_POLICY_NAME_CHARS} characters"),
        });
    }
    if trimmed.chars().any(char::is_control) {
        return Err(SailError::InvalidArgument {
            message: "policy name must not contain control characters".to_string(),
        });
    }
    Ok(())
}

/// Validate injection rules before a create call: at least one rule, the
/// count and value-length caps, non-empty host and target name, and a target
/// kind this SDK can construct (the caller-set vocabulary is closed; `Other`
/// exists only to decode policies newer services return). The service
/// re-validates with the full host/name grammar.
pub(crate) fn validate_rules(rules: &[InjectionRule]) -> Result<(), SailError> {
    let invalid = |message: String| Err(SailError::InvalidArgument { message });
    if rules.is_empty() {
        return invalid("rules must contain at least one rule".to_string());
    }
    if rules.len() > MAX_POLICY_RULES {
        return invalid(format!(
            "rules must contain at most {MAX_POLICY_RULES} items"
        ));
    }
    for (i, rule) in rules.iter().enumerate() {
        if rule.host.trim().is_empty() {
            return invalid(format!("rules[{i}]: host is required"));
        }
        if matches!(rule.target.kind, InjectionTargetKind::Other(_)) {
            return invalid(format!(
                "rules[{i}]: target kind must be header or query_param"
            ));
        }
        if rule.target.name.trim().is_empty() {
            return invalid(format!("rules[{i}]: target name is required"));
        }
        if rule.value.len() > MAX_RULE_VALUE_BYTES {
            return invalid(format!(
                "rules[{i}]: value must be at most {MAX_RULE_VALUE_BYTES} bytes"
            ));
        }
    }
    Ok(())
}

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

    #[test]
    fn rule_serializes_to_the_wire_shape() {
        let rule = InjectionRule::header("api.github.com", "Authorization", "Bearer ${secrets.T}");
        assert_eq!(
            serde_json::to_value(&rule).unwrap(),
            json!({
                "host": "api.github.com",
                "target": {"type": "header", "name": "Authorization"},
                "value": "Bearer ${secrets.T}",
            })
        );
        let query = InjectionRule::query_param("maps.example.com", "key", "${secrets.K}");
        assert_eq!(
            serde_json::to_value(&query).unwrap()["target"]["type"],
            json!("query_param")
        );
    }

    #[test]
    fn unknown_target_kind_round_trips() {
        // A policy created by a newer service must decode, keep the unknown
        // kind verbatim, and re-encode identically.
        let wire = json!({
            "host": "api.example.com",
            "target": {"type": "path_segment", "name": "token"},
            "value": "v",
        });
        let rule: InjectionRule = serde_json::from_value(wire.clone()).unwrap();
        assert_eq!(
            rule.target.kind,
            InjectionTargetKind::Other("path_segment".to_string())
        );
        assert_eq!(serde_json::to_value(&rule).unwrap(), wire);
    }

    #[test]
    fn secret_name_rule_matches_the_service() {
        for valid in ["A", "GITHUB_TOKEN", "0token-x_y", &"a".repeat(128)] {
            assert!(validate_secret_name(valid).is_ok(), "{valid:?}");
        }
        for invalid in [
            "",
            "_leading",
            "-leading",
            "has space",
            "has.dot",
            &"a".repeat(129),
        ] {
            assert!(validate_secret_name(invalid).is_err(), "{invalid:?}");
        }
    }

    #[test]
    fn secret_value_rule_matches_the_service() {
        assert!(validate_secret_value("ok value").is_ok());
        assert!(validate_secret_value("").is_err());
        assert!(validate_secret_value("has\nnewline").is_err());
        assert!(validate_secret_value(&"v".repeat(64 * 1024 + 1)).is_err());
    }

    #[test]
    fn rules_validation_rejects_the_obvious_failures() {
        let good = InjectionRule::header("h.example.com", "X-Key", "v");
        assert!(validate_rules(std::slice::from_ref(&good)).is_ok());
        assert!(validate_rules(&[]).is_err());
        assert!(validate_rules(&vec![good.clone(); 101]).is_err());
        assert!(validate_rules(&[InjectionRule::header("", "X-Key", "v")]).is_err());
        assert!(validate_rules(&[InjectionRule::header("h.example.com", "", "v")]).is_err());
        assert!(validate_rules(&[InjectionRule::header(
            "h.example.com",
            "X-Key",
            "v".repeat(513)
        )])
        .is_err());
        let unknown = InjectionRule {
            host: "h.example.com".to_string(),
            target: InjectionTarget {
                kind: InjectionTargetKind::Other("path_segment".to_string()),
                name: "token".to_string(),
            },
            value: "v".to_string(),
        };
        assert!(validate_rules(&[unknown]).is_err());
    }

    #[test]
    fn policy_page_decodes_the_wire_envelope() {
        let page: CredentialInjectionPolicyPage = serde_json::from_value(json!({
            "data": [{
                "id": "cip_1",
                "name": "github",
                "rule_count": 2,
                "referenced_secret_names": ["GITHUB_TOKEN"],
                "attachment_count": 1,
                "created_at": "2026-07-01T00:00:00.123456789Z",
                "updated_at": "2026-07-02T00:00:00Z",
            }],
            "limit": 50,
            "offset": 0,
            "total": 1,
            "has_more": false,
        }))
        .unwrap();
        assert_eq!(page.items.len(), 1);
        assert_eq!(page.items[0].referenced_secret_names, ["GITHUB_TOKEN"]);
        assert!(!page.has_more);
    }
}