assay-cli 6.6.3

Policy-as-code gate for MCP agent tool calls, with verifiable evidence and Linux kernel enforcement.
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
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
//! `assay policy activate` — activate a validated policy into a policy root.

use std::path::{Path, PathBuf};

use chrono::SecondsFormat;
use serde::{Deserialize, Serialize};

use crate::cli::args::PolicyActivateArgs;
use crate::exit_codes;

pub const SCHEMA_ACTIVATION_V0: &str = "assay.policy.activation.v0";
pub const MAX_RECORD_RETRIES: usize = 10;

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
pub struct ActivationRecord {
    pub schema: String,
    pub name: String,
    pub input_sha256: String,
    pub policy_digest: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub previous_input_sha256: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub previous_policy_digest: Option<String>,
    pub assay_version: String,
    pub activated_at: String,
    pub source: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub rollback_of: Option<String>,
}

#[derive(Debug, Clone)]
pub struct PolicyRootDirs {
    pub root: PathBuf,
    #[allow(dead_code)]
    pub assay_dir: PathBuf,
    pub store_dir: PathBuf,
    pub activations_dir: PathBuf,
}

pub fn now_rfc3339_utc() -> String {
    chrono::Utc::now().to_rfc3339_opts(SecondsFormat::Secs, true)
}

pub fn validate_target_name(name: &str) -> anyhow::Result<()> {
    if name.is_empty() || name.contains('/') || name.contains('\\') || name == "." || name == ".." {
        anyhow::bail!(
            "invalid policy target name '{name}': name must be a single filename component without path separators"
        );
    }
    Ok(())
}

pub fn ensure_policy_root_dirs(
    root: &Path,
    create_if_missing: bool,
) -> anyhow::Result<PolicyRootDirs> {
    let _root_meta = match std::fs::symlink_metadata(root) {
        Ok(m) => m,
        Err(err) if err.kind() == std::io::ErrorKind::NotFound => {
            anyhow::bail!("policy root directory does not exist: {}", root.display());
        }
        Err(err) => {
            return Err(anyhow::anyhow!(
                "failed to access policy root {}: {err}",
                root.display()
            ));
        }
    };

    if !root.is_dir() {
        anyhow::bail!("policy root is not a directory: {}", root.display());
    }

    let canonical_root = root.canonicalize().map_err(|err| {
        anyhow::anyhow!(
            "failed to canonicalize policy root {}: {err}",
            root.display()
        )
    })?;

    let assay_dir = root.join(".assay");
    let store_dir = assay_dir.join("policy-store");
    let activations_dir = assay_dir.join("activations");

    // 1. Check / create .assay
    match std::fs::symlink_metadata(&assay_dir) {
        Ok(meta) => {
            if meta.file_type().is_symlink() {
                anyhow::bail!(
                    "refusing to operate on symlinked assay directory: {}",
                    assay_dir.display()
                );
            }
            if !meta.is_dir() {
                anyhow::bail!(
                    "assay directory is not a directory: {}",
                    assay_dir.display()
                );
            }
        }
        Err(err) if err.kind() == std::io::ErrorKind::NotFound => {
            if create_if_missing {
                std::fs::create_dir(&assay_dir).map_err(|err| {
                    anyhow::anyhow!(
                        "failed to create assay directory {}: {err}",
                        assay_dir.display()
                    )
                })?;
            }
        }
        Err(err) => {
            return Err(anyhow::anyhow!(
                "failed to access assay directory {}: {err}",
                assay_dir.display()
            ));
        }
    }

    // 2. Check / create policy-store
    match std::fs::symlink_metadata(&store_dir) {
        Ok(meta) => {
            if meta.file_type().is_symlink() {
                anyhow::bail!(
                    "refusing to operate on symlinked policy-store directory: {}",
                    store_dir.display()
                );
            }
            if !meta.is_dir() {
                anyhow::bail!(
                    "policy-store directory is not a directory: {}",
                    store_dir.display()
                );
            }
        }
        Err(err) if err.kind() == std::io::ErrorKind::NotFound => {
            if create_if_missing {
                std::fs::create_dir(&store_dir).map_err(|err| {
                    anyhow::anyhow!(
                        "failed to create policy-store directory {}: {err}",
                        store_dir.display()
                    )
                })?;
            }
        }
        Err(err) => {
            return Err(anyhow::anyhow!(
                "failed to access policy-store directory {}: {err}",
                store_dir.display()
            ));
        }
    }

    // 3. Check / create activations
    match std::fs::symlink_metadata(&activations_dir) {
        Ok(meta) => {
            if meta.file_type().is_symlink() {
                anyhow::bail!(
                    "refusing to operate on symlinked activations directory: {}",
                    activations_dir.display()
                );
            }
            if !meta.is_dir() {
                anyhow::bail!(
                    "activations directory is not a directory: {}",
                    activations_dir.display()
                );
            }
        }
        Err(err) if err.kind() == std::io::ErrorKind::NotFound => {
            if create_if_missing {
                std::fs::create_dir(&activations_dir).map_err(|err| {
                    anyhow::anyhow!(
                        "failed to create activations directory {}: {err}",
                        activations_dir.display()
                    )
                })?;
            }
        }
        Err(err) => {
            return Err(anyhow::anyhow!(
                "failed to access activations directory {}: {err}",
                activations_dir.display()
            ));
        }
    }

    // 4. Verify canonical containment
    if assay_dir.exists() {
        let canonical_assay = assay_dir.canonicalize().map_err(|err| {
            anyhow::anyhow!(
                "failed to canonicalize assay dir {}: {err}",
                assay_dir.display()
            )
        })?;
        if !canonical_assay.starts_with(&canonical_root) {
            anyhow::bail!(
                "assay directory {} escapes root {}",
                assay_dir.display(),
                root.display()
            );
        }
    }

    if store_dir.exists() {
        let canonical_store = store_dir.canonicalize().map_err(|err| {
            anyhow::anyhow!(
                "failed to canonicalize policy-store dir {}: {err}",
                store_dir.display()
            )
        })?;
        if !canonical_store.starts_with(&canonical_root) {
            anyhow::bail!(
                "policy-store directory {} escapes root {}",
                store_dir.display(),
                root.display()
            );
        }
    }

    if activations_dir.exists() {
        let canonical_activations = activations_dir.canonicalize().map_err(|err| {
            anyhow::anyhow!(
                "failed to canonicalize activations dir {}: {err}",
                activations_dir.display()
            )
        })?;
        if !canonical_activations.starts_with(&canonical_root) {
            anyhow::bail!(
                "activations directory {} escapes root {}",
                activations_dir.display(),
                root.display()
            );
        }
    }

    Ok(PolicyRootDirs {
        root: root.to_path_buf(),
        assay_dir,
        store_dir,
        activations_dir,
    })
}

pub fn store_policy_content(
    store_dir: &Path,
    input_sha256: &str,
    bytes: &[u8],
) -> anyhow::Result<PathBuf> {
    match assay_common::atomic_write::write_new(store_dir, input_sha256, bytes) {
        Ok(path) => Ok(path),
        Err(assay_common::atomic_write::WriteNewError::AlreadyExists { .. }) => {
            Ok(store_dir.join(input_sha256))
        }
        Err(err) => Err(anyhow::anyhow!(
            "failed to store policy content in policy-store: {err}"
        )),
    }
}

fn parse_activation_record_seq(record_name: &str, target_name: &str) -> Option<u64> {
    let suffix = format!("-{target_name}.json");
    let prefix = record_name.strip_suffix(&suffix)?;
    if prefix.is_empty() || !prefix.bytes().all(|b| b.is_ascii_digit()) {
        return None;
    }
    prefix.parse::<u64>().ok()
}

fn is_lower_hex_64(value: &str) -> bool {
    value.len() == 64 && value.bytes().all(|b| b.is_ascii_hexdigit())
}

pub fn validate_store_object_name(name: &str) -> anyhow::Result<()> {
    let Some(hex) = name.strip_prefix("sha256:") else {
        anyhow::bail!(
            "invalid policy-store object name '{name}': expected sha256:<64 lowercase hex chars>"
        );
    };
    if !is_lower_hex_64(hex) || hex.bytes().any(|b| b.is_ascii_uppercase()) {
        anyhow::bail!(
            "invalid policy-store object name '{name}': expected sha256:<64 lowercase hex chars>"
        );
    }
    Ok(())
}

pub fn read_store_object(store_dir: &Path, object_name: &str) -> anyhow::Result<Vec<u8>> {
    validate_store_object_name(object_name)?;
    let store_dir_handle = std::fs::File::open(store_dir).map_err(|err| {
        anyhow::anyhow!(
            "failed to open policy-store directory {}: {err}",
            store_dir.display()
        )
    })?;
    #[cfg(unix)]
    {
        assay_common::atomic_write::read_at(&store_dir_handle, object_name).map_err(|err| {
            anyhow::anyhow!(
                "failed to read policy-store object '{object_name}' from {}: {err}",
                store_dir.display()
            )
        })
    }
    #[cfg(not(unix))]
    {
        std::fs::read(store_dir.join(object_name)).map_err(|err| {
            anyhow::anyhow!(
                "failed to read policy-store object '{object_name}' from {}: {err}",
                store_dir.display()
            )
        })
    }
}

pub fn replace_pointer_atomic(root: &Path, name: &str, bytes: &[u8]) -> anyhow::Result<PathBuf> {
    validate_target_name(name)?;
    let target = root.join(name);

    if let Ok(meta) = std::fs::symlink_metadata(&target) {
        if meta.file_type().is_symlink() {
            anyhow::bail!(
                "refusing to operate on symlinked policy target: {}",
                target.display()
            );
        }
        if meta.is_dir() {
            anyhow::bail!(
                "policy target {} is a directory; expected a regular file",
                target.display()
            );
        }
    }

    let temp_name = format!(
        ".{name}.tmp.{}.{:x}",
        std::process::id(),
        std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map(|d| d.as_nanos())
            .unwrap_or(0)
    );
    let temp_path = root.join(&temp_name);

    {
        let mut file = std::fs::OpenOptions::new()
            .write(true)
            .create_new(true)
            .open(&temp_path)
            .map_err(|err| {
                anyhow::anyhow!(
                    "failed to create temporary file {}: {err}",
                    temp_path.display()
                )
            })?;
        use std::io::Write;
        file.write_all(bytes)?;
        file.sync_all()?;
    }

    if let Err(err) = std::fs::rename(&temp_path, &target) {
        let _ = std::fs::remove_file(&temp_path);
        return Err(anyhow::anyhow!(
            "failed to replace {} via atomic rename: {err}",
            target.display()
        ));
    }

    #[cfg(unix)]
    {
        if let Ok(dir_file) = std::fs::File::open(root) {
            use std::os::fd::AsRawFd;
            let _ = nix::unistd::fsync(dir_file.as_raw_fd());
        }
    }

    Ok(target)
}

pub fn find_latest_activation_record(
    activations_dir: &Path,
    name: &str,
) -> anyhow::Result<Option<(u64, String, ActivationRecord)>> {
    if !activations_dir.exists() {
        return Ok(None);
    }
    let activations_dir_handle = std::fs::File::open(activations_dir).map_err(|err| {
        anyhow::anyhow!(
            "failed to open activations directory {}: {err}",
            activations_dir.display()
        )
    })?;
    let mut highest: Option<(u64, String, ActivationRecord)> = None;

    for entry in std::fs::read_dir(activations_dir)? {
        let entry = entry?;
        if !entry.file_type()?.is_file() {
            continue;
        }
        let Some(file_name) = entry.file_name().to_str().map(str::to_owned) else {
            continue;
        };
        let Some(seq) = parse_activation_record_seq(&file_name, name) else {
            continue;
        };

        #[cfg(unix)]
        let content = assay_common::atomic_write::read_at(&activations_dir_handle, &file_name)
            .map_err(|err| {
                anyhow::anyhow!(
                    "failed to read activation record '{}' from {}: {err}",
                    file_name,
                    activations_dir.display()
                )
            })?;
        #[cfg(not(unix))]
        let content = std::fs::read(activations_dir.join(&file_name)).map_err(|err| {
            anyhow::anyhow!(
                "failed to read activation record '{}' from {}: {err}",
                file_name,
                activations_dir.display()
            )
        })?;

        if let Ok(rec) = serde_json::from_slice::<ActivationRecord>(&content) {
            if highest
                .as_ref()
                .is_none_or(|(max_seq, _, _)| seq > *max_seq)
            {
                highest = Some((seq, file_name, rec));
            }
        }
    }

    Ok(highest)
}

#[allow(clippy::too_many_arguments)]
pub fn write_activation_record(
    activations_dir: &Path,
    name: &str,
    input_sha256: &str,
    policy_digest: &str,
    previous_input_sha256: Option<String>,
    previous_policy_digest: Option<String>,
    source: &str,
    rollback_of: Option<String>,
) -> anyhow::Result<(ActivationRecord, PathBuf)> {
    for _attempt in 0..MAX_RECORD_RETRIES {
        let latest = find_latest_activation_record(activations_dir, name)?;
        let next_seq = latest.as_ref().map_or(1, |(seq, _, _)| *seq + 1);
        let record_name = format!("{:06}-{name}.json", next_seq);

        let record = ActivationRecord {
            schema: SCHEMA_ACTIVATION_V0.to_string(),
            name: name.to_string(),
            input_sha256: input_sha256.to_string(),
            policy_digest: policy_digest.to_string(),
            previous_input_sha256: previous_input_sha256.clone(),
            previous_policy_digest: previous_policy_digest.clone(),
            assay_version: env!("CARGO_PKG_VERSION").to_string(),
            activated_at: now_rfc3339_utc(),
            source: source.to_string(),
            rollback_of: rollback_of.clone(),
        };

        let record_bytes = serde_json::to_vec_pretty(&record)?;

        match assay_common::atomic_write::write_new(activations_dir, &record_name, &record_bytes) {
            Ok(path) => return Ok((record, path)),
            Err(assay_common::atomic_write::WriteNewError::AlreadyExists { .. }) => {
                // Sequence number race with another concurrent activation; retry
                continue;
            }
            Err(err) => {
                return Err(anyhow::anyhow!(
                    "failed to write activation record {record_name}: {err}"
                ));
            }
        }
    }

    Err(anyhow::anyhow!(
        "failed to write activation record for '{name}' after {MAX_RECORD_RETRIES} attempts due to concurrent activations"
    ))
}

pub async fn run(args: PolicyActivateArgs) -> anyhow::Result<i32> {
    let name = args.target_name()?;
    validate_target_name(&name)?;

    // 1. Read and validate source policy before touching active state
    let bytes = super::resolved::read_bounded(&args.src)
        .map_err(|error| super::classify_load_error(&args.src, error))?;
    let resolved = super::resolved::load_resolved(&bytes)
        .map_err(|error| super::classify_load_error(&args.src, error))?;

    // 2. Ensure .assay directories exist inside root (fail if root missing or symlinked)
    let dirs = ensure_policy_root_dirs(&args.root, true)?;

    // 3. Store content in content store
    store_policy_content(&dirs.store_dir, &resolved.input_sha256, &bytes)?;

    // 4. Find previous state
    let latest = find_latest_activation_record(&dirs.activations_dir, &name)?;
    let (prev_sha, prev_digest) = match latest {
        Some((_, _, ref prev_rec)) => (
            Some(prev_rec.input_sha256.clone()),
            Some(prev_rec.policy_digest.clone()),
        ),
        None => (None, None),
    };

    // 5. Replace active pointer atomically
    replace_pointer_atomic(&dirs.root, &name, &bytes)?;

    // 6. Record activation
    let source_str = args.src.display().to_string();
    let (record, record_path) = write_activation_record(
        &dirs.activations_dir,
        &name,
        &resolved.input_sha256,
        &resolved.policy_digest,
        prev_sha,
        prev_digest,
        &source_str,
        None,
    )?;

    eprintln!(
        "✔ Policy activated: {} (input: {}, digest: {}, record: {})",
        name,
        record.input_sha256,
        record.policy_digest,
        record_path
            .file_name()
            .unwrap_or_default()
            .to_string_lossy()
    );

    Ok(exit_codes::OK)
}