schwab 0.4.0

Unofficial Rust client library for the Schwab API, unaffiliated with Schwab brokerage or thinkorswim
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
//! Order preview digest system.
//!
//! Provides a tamper-evident preview/confirm/execute workflow for orders.
//! When previewing, the order payload and account are hashed into a SHA-256
//! digest and stored on disk. When placing from a saved preview, the stored
//! payload is loaded, re-hashed for integrity verification, and submitted
//! exactly as previewed.
//!
//! Works with both option orders and equity orders: the `order` field stores
//! a [`serde_json::Value`] so any serializable order type can round-trip
//! through the preview system.
//!
//! Digests expire after 15 minutes.

use std::fs::{self, File, OpenOptions};
use std::io::Write;
use std::path::{Path, PathBuf};

use serde::{Deserialize, Serialize};
use serde_json::Value;
use sha2::{Digest, Sha256};

use crate::error::AppError;

/// Time-to-live for saved previews (seconds).
const PREVIEW_TTL_SECS: i64 = 900; // 15 minutes

/// Expected length of a hex-encoded SHA-256 digest.
const DIGEST_HEX_LEN: usize = 64;

/// Saved preview payload stored on disk.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SavedPreview {
    /// Schema version for forward compatibility.
    pub version: u32,
    /// Account hash the order targets.
    pub account_hash: String,
    /// The order payload exactly as previewed, stored as a JSON value.
    pub order: Value,
    /// Command name (e.g., `"order.option.buy-to-open"`, `"order.equity.buy"`).
    pub command: String,
    /// Unix timestamp (seconds) when the preview was saved.
    pub saved_at: i64,
}

/// Returns the directory where preview digests are stored.
///
/// Creates the directory if it does not exist.
fn preview_dir() -> Result<PathBuf, AppError> {
    let base = preview_state_base()?;
    let dir = base.join("schwab-agent").join("previews");
    fs::create_dir_all(&dir)
        .map_err(|e| AppError::Preview(format!("failed to create preview directory: {e}")))?;
    set_private_dir_permissions(&dir)?;
    Ok(dir.to_path_buf())
}

fn preview_state_base() -> Result<PathBuf, AppError> {
    std::env::var_os("XDG_STATE_HOME")
        .filter(|value| !value.is_empty())
        .map(PathBuf::from)
        .or_else(dirs::state_dir)
        .or_else(dirs::data_local_dir)
        .ok_or(AppError::Preview(
            "cannot determine state directory".to_string(),
        ))
}

fn set_private_dir_permissions(path: &Path) -> Result<(), AppError> {
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;

        fs::set_permissions(path, fs::Permissions::from_mode(0o700)).map_err(|e| {
            AppError::Preview(format!("failed to set preview directory permissions: {e}"))
        })?;
    }
    Ok(())
}

fn private_preview_file(path: &Path) -> Result<File, AppError> {
    let mut options = OpenOptions::new();
    options.create(true).write(true).truncate(true);

    #[cfg(unix)]
    {
        use std::os::unix::fs::OpenOptionsExt;

        options.mode(0o600);
    }

    let file = options
        .open(path)
        .map_err(|e| AppError::Preview(format!("failed to write preview file: {e}")))?;

    set_private_file_permissions(path)?;

    Ok(file)
}

fn set_private_file_permissions(path: &Path) -> Result<(), AppError> {
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;

        fs::set_permissions(path, fs::Permissions::from_mode(0o600)).map_err(|e| {
            AppError::Preview(format!("failed to set preview file permissions: {e}"))
        })?;
    }
    Ok(())
}

/// Computes the SHA-256 digest of a preview payload.
///
/// The digest covers the canonical JSON serialization of the payload,
/// binding account, order structure, and metadata together.
fn compute_digest(payload: &SavedPreview) -> Result<String, AppError> {
    let json = serde_json::to_string(payload)
        .map_err(|e| AppError::Preview(format!("failed to serialize preview payload: {e}")))?;
    let mut hasher = Sha256::new();
    hasher.update(json.as_bytes());
    let hash = hasher.finalize();
    Ok(hash.iter().fold(String::with_capacity(64), |mut s, b| {
        use std::fmt::Write;
        let _ = write!(s, "{b:02x}");
        s
    }))
}

/// Saves an order preview to disk and returns its digest.
///
/// The digest is the hex-encoded SHA-256 of the canonical JSON payload.
/// The payload file is named `{digest}.json` in the preview directory.
///
/// Accepts any `Serialize` order type (option orders, equity orders, or raw
/// JSON values). The order is serialized to a [`serde_json::Value`] before
/// storage so that loading does not depend on the original Rust type.
pub fn save_preview<T: Serialize>(
    account_hash: &str,
    order: &T,
    command: &str,
) -> Result<String, AppError> {
    let order_value = serde_json::to_value(order)
        .map_err(|e| AppError::Preview(format!("failed to serialize order for preview: {e}")))?;
    let now = time::OffsetDateTime::now_utc().unix_timestamp();
    let payload = SavedPreview {
        version: 1,
        account_hash: account_hash.to_string(),
        order: order_value,
        command: command.to_string(),
        saved_at: now,
    };

    let digest = compute_digest(&payload)?;
    let path = preview_dir()?.join(format!("{digest}.json"));

    let json = serde_json::to_string_pretty(&payload)
        .map_err(|e| AppError::Preview(format!("failed to serialize preview: {e}")))?;
    private_preview_file(&path)?
        .write_all(json.as_bytes())
        .map_err(|e| AppError::Preview(format!("failed to write preview file: {e}")))?;

    Ok(digest)
}

/// Loads a previously saved order preview by its digest.
///
/// Validates:
/// - Digest format (64-character hex string)
/// - File exists
/// - Re-derived digest matches (tamper detection)
/// - TTL has not expired (15 minutes)
/// - Account hash matches the provided account
pub fn load_preview(digest: &str, account_hash: &str) -> Result<SavedPreview, AppError> {
    // Validate digest format.
    if digest.len() != DIGEST_HEX_LEN || !digest.chars().all(|c| c.is_ascii_hexdigit()) {
        return Err(AppError::Preview(format!(
            "invalid digest format: expected {DIGEST_HEX_LEN}-character hex string, \
             got {}-character '{digest}'",
            digest.len()
        )));
    }

    // Load file.
    let path = preview_dir()?.join(format!("{digest}.json"));
    let json = fs::read_to_string(&path)
        .map_err(|e| AppError::Preview(format!("preview {digest} not found or unreadable: {e}")))?;

    let payload: SavedPreview = serde_json::from_str(&json)
        .map_err(|e| AppError::Preview(format!("preview {digest} has corrupt data: {e}")))?;

    // Verify integrity (re-derive digest).
    let verified = compute_digest(&payload)?;
    if verified != digest {
        return Err(AppError::Preview(format!(
            "preview integrity check failed: expected {digest}, derived {verified}"
        )));
    }

    // Verify account match.
    if payload.account_hash != account_hash {
        return Err(AppError::Preview(
            "preview account mismatch; regenerate preview for this account".to_string(),
        ));
    }

    // Check TTL.
    let now = time::OffsetDateTime::now_utc().unix_timestamp();
    let age = now - payload.saved_at;
    if age > PREVIEW_TTL_SECS {
        // Clean up expired file.
        let _ = fs::remove_file(&path);
        return Err(AppError::Preview(format!(
            "preview {digest} expired ({age}s old, TTL is {PREVIEW_TTL_SECS}s)"
        )));
    }

    Ok(payload)
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use std::{ffi::OsString, path::Path};

    use schwab::{Duration, Instruction, PutCall, Session};

    use super::*;
    use crate::order::builder::{self, OptionLegSpec, OrderTiming};

    struct EnvVarGuard {
        key: &'static str,
        previous: Option<OsString>,
    }

    impl EnvVarGuard {
        fn set_path(key: &'static str, value: &Path) -> Self {
            let previous = std::env::var_os(key);

            unsafe {
                std::env::set_var(key, value);
            }

            Self { key, previous }
        }
    }

    impl Drop for EnvVarGuard {
        fn drop(&mut self) {
            match self.previous.as_ref() {
                Some(value) => unsafe { std::env::set_var(self.key, value) },
                None => unsafe { std::env::remove_var(self.key) },
            }
        }
    }

    /// Builds a simple test order value for preview tests.
    fn test_order_value() -> Value {
        let order = builder::build_single_leg(
            OptionLegSpec {
                underlying: "AAPL",
                expiration: "2025-01-17",
                strike: 200.0,
                quantity: 1,
                price: Some(5.0),
                put_call: PutCall::Call,
            },
            OrderTiming {
                session: Session::Normal,
                duration: Duration::Day,
            },
            Instruction::BuyToOpen,
        )
        .unwrap();
        serde_json::to_value(order).unwrap()
    }

    #[test]
    fn round_trip_save_load() {
        let dir = tempfile::tempdir().unwrap();
        // Override preview_dir by using env var or direct file manipulation.
        // Since preview_dir() uses dirs::state_dir(), we test compute_digest
        // and the serialization format instead.
        let order = test_order_value();
        let now = time::OffsetDateTime::now_utc().unix_timestamp();
        let payload = SavedPreview {
            version: 1,
            account_hash: "test-account-hash".to_string(),
            order,
            command: "order.option.buy-to-open".to_string(),
            saved_at: now,
        };

        // Compute digest.
        let digest = compute_digest(&payload).unwrap();
        assert_eq!(digest.len(), DIGEST_HEX_LEN);
        assert!(digest.chars().all(|c| c.is_ascii_hexdigit()));

        // Save to temp dir.
        let path = dir.path().join(format!("{digest}.json"));
        let json = serde_json::to_string_pretty(&payload).unwrap();
        fs::write(&path, &json).unwrap();

        // Load and verify.
        let loaded: SavedPreview =
            serde_json::from_str(&fs::read_to_string(&path).unwrap()).unwrap();
        let re_digest = compute_digest(&loaded).unwrap();
        assert_eq!(digest, re_digest);
        assert_eq!(loaded.account_hash, "test-account-hash");
    }

    #[test]
    fn digest_changes_with_account() {
        let order = test_order_value();
        let now = time::OffsetDateTime::now_utc().unix_timestamp();

        let p1 = SavedPreview {
            version: 1,
            account_hash: "account-a".to_string(),
            order: order.clone(),
            command: "order.option.buy-to-open".to_string(),
            saved_at: now,
        };
        let p2 = SavedPreview {
            version: 1,
            account_hash: "account-b".to_string(),
            order,
            command: "order.option.buy-to-open".to_string(),
            saved_at: now,
        };

        let d1 = compute_digest(&p1).unwrap();
        let d2 = compute_digest(&p2).unwrap();
        assert_ne!(d1, d2);
    }

    #[test]
    fn load_rejects_bad_digest_format() {
        let result = load_preview("not-a-valid-hex", "account");
        assert!(result.is_err());
        let err = result.unwrap_err().to_string();
        assert!(err.contains("invalid digest format"));
    }

    #[test]
    fn load_rejects_account_mismatch() {
        let _guard = crate::config::TEST_ENV_LOCK.lock().unwrap();
        let temp_dir = tempfile::tempdir().unwrap();
        let _state_home = EnvVarGuard::set_path("XDG_STATE_HOME", temp_dir.path());

        let result = (|| {
            let digest = save_preview("HASH_A", &test_order_value(), "order.option.buy-to-open")?;
            load_preview(&digest, "HASH_B")
        })();

        let err = result.unwrap_err();
        assert_eq!(err.exit_code(), 11);
        match err {
            AppError::Preview(message) => {
                assert_eq!(
                    message,
                    "preview account mismatch; regenerate preview for this account"
                );
                assert!(!message.contains("HASH_A"));
                assert!(!message.contains("HASH_B"));
            }
            other => panic!("expected AppError::Preview, got {other:?}"),
        }
    }

    #[cfg(unix)]
    #[test]
    fn preview_directory_and_file_are_owner_only() {
        use std::os::unix::fs::PermissionsExt;

        let _guard = crate::config::TEST_ENV_LOCK.lock().unwrap();
        let temp_dir = tempfile::tempdir().unwrap();
        let _state_home = EnvVarGuard::set_path("XDG_STATE_HOME", temp_dir.path());

        let digest = save_preview("HASH_A", &test_order_value(), "order.option.buy-to-open")
            .expect("preview should save");
        let preview_path = temp_dir
            .path()
            .join("schwab-agent")
            .join("previews")
            .join(format!("{digest}.json"));
        let preview_dir = preview_path.parent().expect("preview file has parent");

        assert_eq!(
            fs::metadata(preview_dir).unwrap().permissions().mode() & 0o777,
            0o700
        );
        assert_eq!(
            fs::metadata(preview_path).unwrap().permissions().mode() & 0o777,
            0o600
        );
    }

    #[test]
    fn preview_state_base_prefers_non_empty_xdg_state_home() {
        let _guard = crate::config::TEST_ENV_LOCK.lock().unwrap();
        let temp_dir = tempfile::tempdir().unwrap();
        let _state_home = EnvVarGuard::set_path("XDG_STATE_HOME", temp_dir.path());

        assert_eq!(preview_state_base().unwrap(), temp_dir.path());
    }
}