offline-cli 0.3.3

The Offline Protocol developer CLI
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
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
//! Local config storage: `~/.offline/config.json` plus environment overrides.

use std::collections::BTreeMap;
use std::path::PathBuf;

use anyhow::{Context, Result};
use serde::{Deserialize, Serialize};

pub const DEFAULT_API_BASE: &str = "https://api.offlineprotocol.com/api/v1";
pub const DEFAULT_PORTAL_BASE: &str = "https://dev.offlineprotocol.com";
pub const LOCAL_API_BASE: &str = "http://localhost:3010/api/v1";
pub const LOCAL_PORTAL_BASE: &str = "http://localhost:3000";

/// Env vars that override config file values.
pub const ENV_API_KEY: &str = "OFFLINE_API_KEY";
pub const ENV_ACCESS_TOKEN: &str = "OFFLINE_ACCESS_TOKEN";
pub const ENV_APP_ID: &str = "OFFLINE_APP_ID";
pub const ENV_ORG_ID: &str = "OFFLINE_ORG_ID";
pub const ENV_API_BASE: &str = "OFFLINE_API_BASE";
pub const ENV_PORTAL_BASE: &str = "OFFLINE_PORTAL_BASE";
pub const ENV_CONFIG_DIR: &str = "OFFLINE_CONFIG_DIR";
/// `prod` | `dev` | `local`; used when `OFFLINE_API_BASE` is unset.
pub const ENV_ENV: &str = "OFFLINE_ENV";

#[derive(Debug, Default, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "snake_case")]
pub struct CliConfig {
    #[serde(default, skip_serializing_if = "Option::is_none", alias = "apiKey")]
    pub api_key: Option<String>,
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        alias = "accessToken"
    )]
    pub access_token: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none", alias = "devId")]
    pub dev_id: Option<i32>,
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        alias = "appId",
        alias = "applicationId",
        alias = "application_id",
        alias = "projectId",
        alias = "project_id"
    )]
    pub app_id: Option<String>,
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        alias = "orgId",
        alias = "organizationId",
        alias = "organization_id",
        alias = "teamId",
        alias = "team_id"
    )]
    pub org_id: Option<String>,
    /// App API keys this machine created, by application id, so `setup` and
    /// `apply` reuse a key instead of creating another one on every run.
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub app_keys: BTreeMap<String, String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub email: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none", alias = "apiBase")]
    pub api_base: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none", alias = "portalBase")]
    pub portal_base: Option<String>,
}

impl CliConfig {
    pub fn dir() -> Result<PathBuf> {
        if let Some(dir) = std::env::var_os(ENV_CONFIG_DIR) {
            return Ok(PathBuf::from(dir));
        }
        let home = dirs::home_dir().context("could not determine home directory")?;
        Ok(home.join(".offline"))
    }

    pub fn path() -> Result<PathBuf> {
        Ok(Self::dir()?.join("config.json"))
    }

    pub fn load() -> Result<Self> {
        let path = Self::path()?;
        reject_symlink(&path)?;
        if !path.exists() {
            return Ok(Self::default());
        }
        let data = std::fs::read_to_string(&path)
            .with_context(|| format!("reading {}", path.display()))?;
        serde_json::from_str(&data).with_context(|| format!("parsing {}", path.display()))
    }

    /// Write the config atomically with owner-only permissions.
    ///
    /// The JSON goes to a new temporary file in the same directory, created
    /// exclusively and (on Unix) with mode 0600 from the start, so the
    /// credentials are never readable by other users even briefly. It is
    /// flushed to disk and renamed over `config.json`; a crash leaves either
    /// the old file or the new one. A `config.json` that is a symbolic link is
    /// refused, and so is a config directory owned by someone else or
    /// writable by other users (Unix). On Windows the file keeps the
    /// permissions of the directory, normally the user's profile.
    pub fn save(&self) -> Result<()> {
        let dir = Self::dir()?;
        prepare_config_dir(&dir, std::env::var_os(ENV_CONFIG_DIR).is_none())?;
        let path = Self::path()?;
        reject_symlink(&path)?;
        let data = serde_json::to_string_pretty(self)?;

        let tmp = dir.join(format!(
            ".config.json.{}.{:016x}.tmp",
            std::process::id(),
            rand::random::<u64>()
        ));
        let written = write_new_private_file(&tmp, data.as_bytes()).and_then(|()| {
            std::fs::rename(&tmp, &path).with_context(|| format!("replacing {}", path.display()))
        });
        if written.is_err() {
            let _ = std::fs::remove_file(&tmp);
        }
        written
    }

    /// Remove stored credentials and delete the config file.
    pub fn delete_config_file() -> Result<()> {
        let path = Self::path()?;
        if path.exists() {
            std::fs::remove_file(&path).with_context(|| format!("removing {}", path.display()))?;
        }
        Ok(())
    }

    /// Effective API key: env var wins over the config file.
    pub fn effective_api_key(&self) -> Option<String> {
        std::env::var(ENV_API_KEY)
            .ok()
            .filter(|k| !k.is_empty())
            .or_else(|| self.api_key.clone())
    }

    /// Developer JWT for org/app/key management routes.
    pub fn effective_access_token(&self) -> Option<String> {
        std::env::var(ENV_ACCESS_TOKEN)
            .ok()
            .filter(|k| !k.is_empty())
            .or_else(|| self.access_token.clone())
    }

    pub fn effective_app_id(&self) -> Option<String> {
        std::env::var(ENV_APP_ID)
            .ok()
            .filter(|k| !k.is_empty())
            .or_else(|| self.app_id.clone())
    }

    pub fn effective_org_id(&self) -> Option<String> {
        std::env::var(ENV_ORG_ID)
            .ok()
            .filter(|k| !k.is_empty())
            .or_else(|| self.org_id.clone())
    }

    pub fn effective_api_base(&self) -> String {
        if let Ok(base) = std::env::var(ENV_API_BASE) {
            if !base.is_empty() {
                return normalize_api_base(&base);
            }
        }
        if is_local_env() {
            return LOCAL_API_BASE.to_string();
        }
        normalize_api_base(
            &self
                .api_base
                .clone()
                .unwrap_or_else(|| DEFAULT_API_BASE.to_string()),
        )
    }

    pub fn effective_portal_base(&self) -> String {
        if let Ok(base) = std::env::var(ENV_PORTAL_BASE) {
            if !base.is_empty() {
                return base;
            }
        }
        if is_local_env() {
            return LOCAL_PORTAL_BASE.to_string();
        }
        self.portal_base
            .clone()
            .unwrap_or_else(|| DEFAULT_PORTAL_BASE.to_string())
    }

    pub fn has_stored_credentials(&self) -> bool {
        self.api_key.is_some() || self.access_token.is_some()
    }

    pub fn has_api_credentials(&self) -> bool {
        self.effective_api_key().is_some() && self.effective_app_id().is_some()
    }
}

/// Append `/api/v1` when the base URL lacks it.
/// Refuse to read or write credentials through a symbolic link: whoever can
/// plant one could redirect the file somewhere readable.
fn reject_symlink(path: &std::path::Path) -> Result<()> {
    if let Ok(meta) = std::fs::symlink_metadata(path) {
        if meta.file_type().is_symlink() {
            anyhow::bail!(
                "{} is a symbolic link; the CLI will not read or write credentials through it. \
                 Remove it and sign in again.",
                path.display()
            );
        }
    }
    Ok(())
}

/// Create the config directory (owner-only on Unix) or check an existing one.
/// `tighten` is true for the default `~/.offline`, whose permissions the CLI
/// may narrow to 0700; a directory named by `OFFLINE_CONFIG_DIR` is only
/// checked, never changed.
fn prepare_config_dir(dir: &std::path::Path, tighten: bool) -> Result<()> {
    if !dir.exists() {
        #[cfg(unix)]
        {
            use std::os::unix::fs::DirBuilderExt;
            std::fs::DirBuilder::new()
                .recursive(true)
                .mode(0o700)
                .create(dir)
                .with_context(|| format!("creating {}", dir.display()))?;
        }
        #[cfg(not(unix))]
        std::fs::create_dir_all(dir).with_context(|| format!("creating {}", dir.display()))?;
        return Ok(());
    }
    #[cfg(unix)]
    {
        use std::os::unix::fs::{MetadataExt, PermissionsExt};
        let meta = std::fs::metadata(dir).with_context(|| format!("reading {}", dir.display()))?;
        if !meta.is_dir() {
            anyhow::bail!("{} is not a directory", dir.display());
        }
        // SAFETY: geteuid has no preconditions and cannot fail.
        let uid = unsafe { libc::geteuid() };
        if meta.uid() != uid {
            anyhow::bail!(
                "{} belongs to another user; the CLI will not store credentials there",
                dir.display()
            );
        }
        let mode = meta.permissions().mode() & 0o777;
        if tighten && mode & 0o077 != 0 {
            std::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o700))
                .with_context(|| format!("restricting {}", dir.display()))?;
        } else if mode & 0o022 != 0 {
            anyhow::bail!(
                "{} is writable by other users (mode {:o}); run `chmod go-w {}` or choose another OFFLINE_CONFIG_DIR",
                dir.display(),
                mode,
                dir.display()
            );
        }
    }
    #[cfg(not(unix))]
    let _ = tighten;
    Ok(())
}

/// Create `path` exclusively (it must not exist), owner read/write only on
/// Unix from the moment it exists, write `data` and flush it to disk.
fn write_new_private_file(path: &std::path::Path, data: &[u8]) -> Result<()> {
    use std::io::Write;
    let mut options = std::fs::OpenOptions::new();
    options.write(true).create_new(true);
    #[cfg(unix)]
    {
        use std::os::unix::fs::OpenOptionsExt;
        options.mode(0o600);
    }
    let mut file = options
        .open(path)
        .with_context(|| format!("creating {}", path.display()))?;
    file.write_all(data)
        .and_then(|()| file.sync_all())
        .with_context(|| format!("writing {}", path.display()))?;
    Ok(())
}

pub fn normalize_api_base(base: &str) -> String {
    let base = base.trim_end_matches('/');
    if base.ends_with("/api/v1") {
        base.to_string()
    } else {
        format!("{base}/api/v1")
    }
}

pub fn is_local_env() -> bool {
    matches!(
        std::env::var(ENV_ENV)
            .ok()
            .map(|v| v.trim().to_ascii_lowercase())
            .as_deref(),
        Some("dev") | Some("local") | Some("development")
    )
}

#[cfg(test)]
pub(crate) mod test_sync {
    use std::sync::{Mutex, MutexGuard};

    static LOCK: Mutex<()> = Mutex::new(());

    pub fn env_lock() -> MutexGuard<'static, ()> {
        LOCK.lock().unwrap_or_else(|e| e.into_inner())
    }
}

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

    #[test]
    fn config_persists_credentials() {
        let _lock = env_lock();
        let dir = tempfile::tempdir().unwrap();
        std::env::set_var(ENV_CONFIG_DIR, dir.path());

        let config = CliConfig {
            api_key: Some("550e8400-e29b-41d4-a716-446655440000".into()),
            access_token: Some("jwt-token".into()),
            dev_id: Some(123),
            app_id: Some("app_abc".into()),
            org_id: Some("org_xyz".into()),
            email: Some("dev@example.com".into()),
            ..Default::default()
        };
        config.save().unwrap();

        let loaded = CliConfig::load().unwrap();
        assert_eq!(
            loaded.api_key.as_deref(),
            Some("550e8400-e29b-41d4-a716-446655440000")
        );
        assert_eq!(loaded.access_token.as_deref(), Some("jwt-token"));
        assert_eq!(loaded.dev_id, Some(123));
        assert_eq!(loaded.app_id.as_deref(), Some("app_abc"));
        assert_eq!(loaded.org_id.as_deref(), Some("org_xyz"));
        assert_eq!(loaded.email.as_deref(), Some("dev@example.com"));

        let raw = std::fs::read_to_string(CliConfig::path().unwrap()).unwrap();
        assert!(raw.contains("\"api_key\""));
        assert!(raw.contains("\"access_token\""));
        assert!(raw.contains("\"app_id\""));
        assert!(raw.contains("\"org_id\""));

        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            let mode = std::fs::metadata(CliConfig::path().unwrap())
                .unwrap()
                .permissions()
                .mode();
            assert_eq!(mode & 0o777, 0o600);
        }

        std::env::remove_var(ENV_CONFIG_DIR);
    }

    #[cfg(unix)]
    #[test]
    fn save_is_atomic_owner_only_and_refuses_symlinks() {
        use std::os::unix::fs::PermissionsExt;
        let _lock = env_lock();
        let dir = tempfile::tempdir().unwrap();
        let cfg_dir = dir.path().join("cfg");
        std::env::set_var(ENV_CONFIG_DIR, &cfg_dir);

        let config = CliConfig {
            api_key: Some("550e8400-e29b-41d4-a716-446655440000".into()),
            ..Default::default()
        };
        config.save().unwrap();
        let mode = |p: &std::path::Path| std::fs::metadata(p).unwrap().permissions().mode() & 0o777;
        assert_eq!(mode(&cfg_dir), 0o700, "new config directory is owner-only");
        assert_eq!(mode(&CliConfig::path().unwrap()), 0o600);
        // Saving again replaces the file; no temporary files are left behind.
        config.save().unwrap();
        let names: Vec<_> = std::fs::read_dir(&cfg_dir)
            .unwrap()
            .map(|e| e.unwrap().file_name().into_string().unwrap())
            .collect();
        assert_eq!(names, vec!["config.json".to_string()]);

        // A symlinked config.json is refused for both reading and writing,
        // and the link target is never touched.
        let target = dir.path().join("elsewhere.json");
        std::fs::write(&target, "{}").unwrap();
        std::fs::remove_file(CliConfig::path().unwrap()).unwrap();
        std::os::unix::fs::symlink(&target, CliConfig::path().unwrap()).unwrap();
        assert!(config
            .save()
            .unwrap_err()
            .to_string()
            .contains("symbolic link"));
        assert!(CliConfig::load()
            .unwrap_err()
            .to_string()
            .contains("symbolic link"));
        assert_eq!(std::fs::read_to_string(&target).unwrap(), "{}");

        std::env::remove_var(ENV_CONFIG_DIR);
    }

    #[cfg(unix)]
    #[test]
    fn refuses_a_config_dir_writable_by_others() {
        use std::os::unix::fs::PermissionsExt;
        let _lock = env_lock();
        let dir = tempfile::tempdir().unwrap();
        std::fs::set_permissions(dir.path(), std::fs::Permissions::from_mode(0o777)).unwrap();
        std::env::set_var(ENV_CONFIG_DIR, dir.path());

        let err = CliConfig::default().save().unwrap_err().to_string();
        assert!(err.contains("writable by other users"), "{err}");
        assert!(!CliConfig::path().unwrap().exists());
        // OFFLINE_CONFIG_DIR is only checked, never changed.
        assert_eq!(
            std::fs::metadata(dir.path()).unwrap().permissions().mode() & 0o777,
            0o777
        );

        std::env::remove_var(ENV_CONFIG_DIR);
    }

    #[test]
    fn legacy_project_id_deserializes_as_app_id() {
        let raw = r#"{"project_id":"app_legacy","team_id":"org_legacy"}"#;
        let config: CliConfig = serde_json::from_str(raw).unwrap();
        assert_eq!(config.app_id.as_deref(), Some("app_legacy"));
        assert_eq!(config.org_id.as_deref(), Some("org_legacy"));
    }

    #[test]
    fn delete_config_file_removes_credentials() {
        let _lock = env_lock();
        let dir = tempfile::tempdir().unwrap();
        std::env::set_var(ENV_CONFIG_DIR, dir.path());

        let config = CliConfig {
            api_key: Some("off_live_test".into()),
            ..Default::default()
        };
        config.save().unwrap();
        assert!(CliConfig::path().unwrap().exists());

        CliConfig::delete_config_file().unwrap();
        assert!(!CliConfig::path().unwrap().exists());

        std::env::remove_var(ENV_CONFIG_DIR);
    }

    #[test]
    fn offline_env_selects_api_base() {
        let _lock = env_lock();
        std::env::remove_var(ENV_API_BASE);

        std::env::remove_var(ENV_ENV);
        assert_eq!(CliConfig::default().effective_api_base(), DEFAULT_API_BASE);

        std::env::set_var(ENV_ENV, "prod");
        assert_eq!(CliConfig::default().effective_api_base(), DEFAULT_API_BASE);

        std::env::set_var(ENV_ENV, "dev");
        assert_eq!(CliConfig::default().effective_api_base(), LOCAL_API_BASE);

        std::env::set_var(ENV_ENV, "local");

        std::env::set_var(ENV_API_BASE, "http://custom.example");
        let config = CliConfig::default();
        assert_eq!(config.effective_api_base(), "http://custom.example/api/v1");

        assert_eq!(
            normalize_api_base("https://api.offlineprotocol.com/api/v1"),
            "https://api.offlineprotocol.com/api/v1"
        );
        assert_eq!(
            normalize_api_base("http://localhost:3010"),
            "http://localhost:3010/api/v1"
        );

        std::env::remove_var(ENV_ENV);
        std::env::remove_var(ENV_API_BASE);
    }
}