sail-rs 0.4.0

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
//! SDK configuration loaded from environment variables.
//!
//! Endpoints default to the Sail service and can be overridden individually
//! via `SAIL_API_URL`, `SAILBOX_API_URL`, `SAIL_IMAGEBUILDER_URL`, and
//! `SAILBOX_INGRESS_URL`.

use crate::error::SailError;

/// Resolved SDK configuration: credentials plus the three service endpoints.
///
/// Usually produced from the environment and `~/.sail` via
/// [`ClientBuilder`](crate::ClientBuilder) or [`Client::from_env`](crate::Client::from_env),
/// which also fill the derived fields consistently.
///
/// `Debug` redacts the API key, so a logged `Config` never leaks the
/// credential.
#[derive(Clone)]
pub struct Config {
    /// The environment mode these endpoints were resolved from, or `None` for
    /// the default. Retained so a caller that rebuilds a config from an explicit
    /// key can reselect the same environment (including its ingress scheme)
    /// rather than fall back to the default.
    pub mode: Option<String>,
    /// Bearer API key sent on every request (trimmed of surrounding whitespace).
    pub api_key: String,
    /// Base URL of the public Sail REST API (no trailing path).
    pub api_url: String,
    /// Base URL of the Sailbox lifecycle/exec API.
    pub sailbox_api_url: String,
    /// `host:port` endpoint that image builds are submitted to.
    pub imagebuilder_url: String,
    /// Base URL that listener URLs are built from when the server does not
    /// return one, e.g. `https://api.sailresearch.com`.
    pub ingress_base: String,
    /// How a listener's URL is addressed under [`ingress_base`](Config::ingress_base).
    pub ingress_scheme: IngressScheme,
}

impl std::fmt::Debug for Config {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Config")
            .field("mode", &self.mode)
            .field("api_key", &redact_key(&self.api_key))
            .field("api_url", &self.api_url)
            .field("sailbox_api_url", &self.sailbox_api_url)
            .field("imagebuilder_url", &self.imagebuilder_url)
            .field("ingress_base", &self.ingress_base)
            .field("ingress_scheme", &self.ingress_scheme)
            .finish()
    }
}

/// The redacted `Debug` form of an API key: present-or-absent, never the value.
pub(crate) fn redact_key(api_key: &str) -> &'static str {
    if api_key.is_empty() {
        "<unset>"
    } else {
        "<redacted>"
    }
}

/// How the SDK addresses a listener's URL under the ingress base, the Sailbox
/// id, and the port, when the server does not return one.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum IngressScheme {
    /// One host, path-addressed: `<base>/_sailbox/{sailbox_id}/{guest_port}`
    /// (self-hosted stacks, or an explicit ingress URL).
    Path,
    /// Per-listener subdomain of the base: `<sailbox>-<port>.<base host>`
    /// (the Sail service, served by wildcard DNS).
    Subdomain,
}

#[derive(Debug)]
struct EnvDefaults {
    api_url: &'static str,
    sailbox_api_url: &'static str,
    imagebuilder_url: &'static str,
    ingress_base: &'static str,
    /// True when listeners are subdomain-addressed (deployed wildcard DNS);
    /// false for path-addressed (local). Built into [`IngressScheme`].
    ingress_subdomain: bool,
}

const PROD: EnvDefaults = EnvDefaults {
    api_url: "https://api.sailresearch.com",
    sailbox_api_url: "https://sailbox-api.sailresearch.com",
    imagebuilder_url: "sailbox-imagebuilder-dispatcher.sailresearch.com:443",
    ingress_base: "https://api.sailresearch.com",
    ingress_subdomain: true,
};

const DEV: EnvDefaults = EnvDefaults {
    api_url: "https://dev.sailresearch.com",
    sailbox_api_url: "https://sailbox-api.dev.sailresearch.com",
    imagebuilder_url: "sailbox-imagebuilder-dispatcher.dev.sailresearch.com:443",
    ingress_base: "https://dev.sailresearch.com",
    ingress_subdomain: true,
};

const STAGING: EnvDefaults = EnvDefaults {
    api_url: "https://staging.sailresearch.com",
    sailbox_api_url: "https://sailbox-api.staging.sailresearch.com",
    imagebuilder_url: "sailbox-imagebuilder-dispatcher.staging.sailresearch.com:443",
    ingress_base: "https://beta.sailresearch.com",
    ingress_subdomain: true,
};

// Local backend nginx serves the public HTTP API on :8080 (see
// backend/docker-compose.yml NGINX_PORT). All sailbox lifecycle
// operations go through this endpoint; the imagebuilder dispatcher listens on
// :50061; listener ingress is served by path on :18080.
const LOCAL: EnvDefaults = EnvDefaults {
    api_url: "http://localhost:8080",
    sailbox_api_url: "http://localhost:8080",
    imagebuilder_url: "localhost:50061",
    ingress_base: "http://localhost:18080",
    ingress_subdomain: false,
};

fn env_or_empty(name: &str) -> String {
    std::env::var(name).unwrap_or_default()
}

fn env_trimmed(name: &str) -> String {
    env_or_empty(name).trim().to_string()
}

/// Resolve the env defaults for a SAIL_MODE value. Empty means "no mode
/// declared" and is treated as prod; any other unrecognized value raises.
fn mode_defaults(mode: &str) -> Result<&'static EnvDefaults, SailError> {
    match mode.trim().to_lowercase().as_str() {
        "" | "prod" => Ok(&PROD),
        "dev" => Ok(&DEV),
        "staging" => Ok(&STAGING),
        "local" => Ok(&LOCAL),
        other => Err(SailError::Config {
            message: format!(
                "SAIL_MODE={other} is not recognized; use SAIL_MODE=prod|dev|staging|local"
            ),
        }),
    }
}

/// The central public-API URL for a named mode (`prod`/`dev`/`staging`/`local`,
/// empty means prod), or `None` for an unrecognized mode. Lets bindings resolve
/// a mode's endpoint from this single source of truth instead of restating it.
#[doc(hidden)]
pub fn api_url_for_mode(mode: &str) -> Option<&'static str> {
    mode_defaults(mode).ok().map(|defaults| defaults.api_url)
}

impl Config {
    /// Resolve a config from a `mode` plus explicit overrides. `mode` selects
    /// the endpoint defaults (empty/None means prod); any non-empty override
    /// wins over its default. The API key is required and trimmed.
    pub(crate) fn resolve(
        mode: Option<&str>,
        api_key: String,
        api_url: Option<String>,
        sailbox_api_url: Option<String>,
        imagebuilder_url: Option<String>,
        sailbox_ingress_url: Option<String>,
    ) -> Result<Config, SailError> {
        let api_key = api_key.trim().to_string();
        if api_key.is_empty() {
            return Err(SailError::Config {
                message: "Set SAIL_API_KEY or run `sail auth login`.".to_string(),
            });
        }
        Config::build(
            mode,
            api_key,
            api_url,
            sailbox_api_url,
            imagebuilder_url,
            sailbox_ingress_url,
        )
    }

    /// Build a config, resolving each unset endpoint from the mode defaults. Does
    /// not require an API key; the caller decides whether an empty key is valid.
    fn build(
        mode: Option<&str>,
        api_key: String,
        api_url: Option<String>,
        sailbox_api_url: Option<String>,
        imagebuilder_url: Option<String>,
        sailbox_ingress_url: Option<String>,
    ) -> Result<Config, SailError> {
        let defaults = mode_defaults(mode.unwrap_or(""))?;
        fn or_default(override_value: Option<String>, default: &str) -> String {
            match override_value {
                Some(value) if !value.trim().is_empty() => value.trim().to_string(),
                _ => default.to_string(),
            }
        }
        // An explicit ingress URL is always addressed by path; the subdomain
        // scheme only applies to the deployed defaults.
        let has_override = sailbox_ingress_url
            .as_deref()
            .map(str::trim)
            .is_some_and(|value| !value.is_empty());
        let ingress_scheme = if !has_override && defaults.ingress_subdomain {
            IngressScheme::Subdomain
        } else {
            IngressScheme::Path
        };
        Ok(Config {
            mode: mode
                .map(str::trim)
                .filter(|value| !value.is_empty())
                .map(str::to_string),
            api_key,
            api_url: or_default(api_url, defaults.api_url),
            sailbox_api_url: or_default(sailbox_api_url, defaults.sailbox_api_url),
            imagebuilder_url: or_default(imagebuilder_url, defaults.imagebuilder_url),
            ingress_base: or_default(sailbox_ingress_url, defaults.ingress_base),
            ingress_scheme,
        })
    }

    /// Resolve a config from the environment, falling back to the stored
    /// `~/.sail` credential and settings for any value the environment does not
    /// set. Environment variables always win. The stored API key is applied only
    /// when its tagged target matches the resolved one, so a key minted for one
    /// environment is never sent to another. The key is trimmed so one sourced
    /// with a trailing newline can't produce a malformed bearer token.
    pub fn from_env() -> Result<Config, SailError> {
        Config::from_env_inner(/* require_api_key */ true)
    }

    /// Like [`from_env`](Self::from_env) but does not require an API key, for
    /// telemetry that degrades to a no-op when unauthenticated. Endpoints still
    /// resolve from the environment and `~/.sail`.
    #[doc(hidden)]
    pub fn from_env_optional_api_key() -> Result<Config, SailError> {
        Config::from_env_inner(/* require_api_key */ false)
    }

    fn from_env_inner(require_api_key: bool) -> Result<Config, SailError> {
        // Strict: a malformed config.toml or one with an unrecognized key is an
        // error here, so a typo'd setting fails loudly instead of being silently
        // dropped. Telemetry callers (voyage) catch this and degrade rather than
        // crash; see `_core_client.resolved_api_key`.
        let settings = crate::credentials::load_settings()?;
        let pick = |env_name: &str, stored_key: &str| -> String {
            pick_setting(std::env::var(env_name).ok(), settings.get(stored_key))
        };
        let mode = pick("SAIL_MODE", "mode");
        let api_url = pick("SAIL_API_URL", "api_url");
        let sailbox_api_url = pick("SAILBOX_API_URL", "sailbox_api_url");
        let imagebuilder_url = pick("SAIL_IMAGEBUILDER_URL", "imagebuilder_url");
        // Ingress is an env-only override; otherwise it follows the mode default.
        let sailbox_ingress_url = env_trimmed("SAILBOX_INGRESS_URL");

        let mut api_key = env_trimmed("SAIL_API_KEY");
        if api_key.is_empty() {
            let target = crate::credentials::resolve_target_api_url(&api_url, &mode);
            if crate::credentials::stored_key_matches_target(&settings, &target) {
                if let Some(stored) = crate::credentials::auth_key_best_effort() {
                    api_key = stored;
                }
            }
        }
        if require_api_key && api_key.is_empty() {
            return Err(SailError::Config {
                message: "Set SAIL_API_KEY or run `sail auth login`.".to_string(),
            });
        }

        Config::build(
            Some(&mode),
            api_key,
            opt(api_url),
            opt(sailbox_api_url),
            opt(imagebuilder_url),
            opt(sailbox_ingress_url),
        )
    }
}

fn opt(value: String) -> Option<String> {
    if value.is_empty() {
        None
    } else {
        Some(value)
    }
}

/// Resolve one endpoint/mode setting, trimmed. The environment wins whenever the
/// variable is present, including when it is empty: an explicit empty value masks
/// any stored override, which is how `sail --mode <env>` forces that mode's
/// endpoint defaults instead of inheriting a stored `~/.sail` endpoint. Only a
/// fully unset variable falls back to the stored value.
fn pick_setting(env_value: Option<String>, stored: Option<&String>) -> String {
    match env_value {
        Some(value) => value.trim().to_string(),
        None => stored
            .map(|value| value.trim().to_string())
            .unwrap_or_default(),
    }
}

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

    #[test]
    fn known_modes_resolve() {
        assert_eq!(mode_defaults("").unwrap().api_url, PROD.api_url);
        assert_eq!(mode_defaults(" PROD ").unwrap().api_url, PROD.api_url);
        assert_eq!(mode_defaults("dev").unwrap().api_url, DEV.api_url);
        assert_eq!(mode_defaults("local").unwrap().api_url, LOCAL.api_url);
    }

    #[test]
    fn unknown_mode_is_config_error() {
        match mode_defaults("production") {
            Err(SailError::Config { message }) => {
                assert!(message.contains("not recognized"), "message={message}");
            }
            other => panic!("expected Config error, got {other:?}"),
        }
    }

    #[test]
    fn pick_setting_present_env_masks_stored() {
        let stored = "https://stored.example".to_string();
        // A present env var wins, even empty: an empty value masks the stored
        // override (how `--mode` forces mode defaults), rather than falling back.
        assert_eq!(
            pick_setting(Some("https://env.example".to_string()), Some(&stored)),
            "https://env.example"
        );
        assert_eq!(pick_setting(Some(String::new()), Some(&stored)), "");
        assert_eq!(pick_setting(Some("  ".to_string()), Some(&stored)), "");
        // Only a fully unset var falls back to the stored value.
        assert_eq!(
            pick_setting(/* env_value */ None, Some(&stored)),
            "https://stored.example"
        );
        assert_eq!(pick_setting(/* env_value */ None, /* stored */ None), "");
    }

    #[test]
    fn override_wins_blank_falls_back_to_mode_default() {
        let config = Config::resolve(
            Some("dev"),
            "k".to_string(),
            Some("https://override.example".to_string()),
            /* sailbox_api_url */ None, // unset → mode default
            /* imagebuilder_url */ Some("   ".to_string()), // blank → mode default
            /* sailbox_ingress_url */ None,
        )
        .unwrap();
        assert_eq!(config.api_url, "https://override.example");
        assert_eq!(config.sailbox_api_url, DEV.sailbox_api_url);
        assert_eq!(config.imagebuilder_url, DEV.imagebuilder_url);
    }

    #[test]
    fn api_key_is_required_and_trimmed() {
        assert!(matches!(
            Config::resolve(
                /* mode */ None,
                "   ".to_string(),
                /* api_url */ None,
                /* sailbox_api_url */ None,
                /* imagebuilder_url */ None,
                /* sailbox_ingress_url */ None,
            ),
            Err(SailError::Config { .. })
        ));
        let config = Config::resolve(
            /* mode */ None,
            "  sk_k  ".to_string(),
            /* api_url */ None,
            /* sailbox_api_url */ None,
            /* imagebuilder_url */ None,
            /* sailbox_ingress_url */ None,
        )
        .unwrap();
        assert_eq!(config.api_key, "sk_k");
        // No mode declared resolves to the prod defaults.
        assert_eq!(config.api_url, PROD.api_url);
    }

    #[test]
    fn ingress_defaults_per_mode_and_override_forces_path() {
        // Deployed modes default to a subdomain-addressed ingress.
        let prod = Config::resolve(
            /* mode */ None,
            "k".to_string(),
            /* api_url */ None,
            /* sailbox_api_url */ None,
            /* imagebuilder_url */ None,
            /* sailbox_ingress_url */ None,
        )
        .unwrap();
        assert_eq!(prod.ingress_scheme, IngressScheme::Subdomain);
        assert_eq!(prod.ingress_base, PROD.ingress_base);
        // Local defaults to path-addressed ingress.
        let local = Config::resolve(
            Some("local"),
            "k".to_string(),
            /* api_url */ None,
            /* sailbox_api_url */ None,
            /* imagebuilder_url */ None,
            /* sailbox_ingress_url */ None,
        )
        .unwrap();
        assert_eq!(local.ingress_scheme, IngressScheme::Path);
        // An explicit ingress URL is always path-addressed.
        let overridden = Config::resolve(
            /* mode */ None,
            "k".to_string(),
            /* api_url */ None,
            /* sailbox_api_url */ None,
            /* imagebuilder_url */ None,
            Some("https://ingress.example".to_string()),
        )
        .unwrap();
        assert_eq!(overridden.ingress_scheme, IngressScheme::Path);
        assert_eq!(overridden.ingress_base, "https://ingress.example");
    }
}