harn-hostlib 0.9.4

Opt-in code-intelligence and deterministic-tool host builtins for the Harn VM
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
//! Shared host-environment custody contracts.
//!
//! Harn embedders often need a script or remote runtime to name a host
//! environment class without ever seeing the values in that class. The common
//! pattern is a named environment palette: the orchestrator sends class names
//! over the wire, the host resolves values locally, and receipts/audit trails
//! keep only class names.

use std::collections::BTreeSet;
use std::fmt;

use serde::{Deserialize, Serialize};
use serde_json::{Map, Value};

/// Canonical custody mode for a host-held named environment palette.
pub const HOST_ENV_CUSTODY_MODE_NAMED_ENV_PALETTE: &str = "named_env_palette";
/// Wire policy stating that only env class names may cross a protocol boundary.
pub const HOST_ENV_CUSTODY_WIRE_CLASS_NAMES_ONLY: &str = "class_names_only";
/// Host policy stating that credential values are resolved only in the host.
pub const HOST_ENV_CUSTODY_HOST_VALUES_ONLY: &str = "host_values_only";
/// Sandbox policy stating that secret values are never sandbox-visible.
pub const HOST_ENV_CUSTODY_SANDBOX_NO_SECRET_VALUES: &str = "no_secret_values";
/// Metadata object key carrying a [`HostEnvCustodyContract`].
pub const HOST_ENV_CUSTODY_METADATA_KEY: &str = "host_env_custody";

/// Serializable contract for a host-resolved named environment palette.
///
/// The contract intentionally carries class names only. It is suitable for
/// protocol metadata, receipts, audit logs, and checkpoint records. It is not a
/// secret container and rejects unknown JSON fields so callers cannot smuggle
/// secret-looking side fields into a validated custody object.
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct HostEnvCustodyContract {
    /// Custody mode. Currently only `named_env_palette` is accepted.
    pub mode: String,
    /// Env classes whose values are issued by the orchestrator but injected
    /// only into the host process, never into the VM/script payload.
    pub orchestrator_issued_host_env_classes: Vec<String>,
    /// Env classes whose values are held and resolved by the host itself.
    pub host_held_env_classes: Vec<String>,
    /// Env classes the host may expose to a sandboxed command. These should be
    /// credential-free classes such as `agent` or `verify`.
    pub sandbox_visible_env_classes: Vec<String>,
    /// Wire policy. Currently only `class_names_only` is accepted.
    pub wire_value_policy: String,
    /// Host value policy. Currently only `host_values_only` is accepted.
    pub host_value_policy: String,
    /// Sandbox value policy. Currently only `no_secret_values` is accepted.
    pub sandbox_value_policy: String,
}

impl Default for HostEnvCustodyContract {
    fn default() -> Self {
        Self {
            mode: HOST_ENV_CUSTODY_MODE_NAMED_ENV_PALETTE.to_string(),
            orchestrator_issued_host_env_classes: Vec::new(),
            host_held_env_classes: Vec::new(),
            sandbox_visible_env_classes: Vec::new(),
            wire_value_policy: HOST_ENV_CUSTODY_WIRE_CLASS_NAMES_ONLY.to_string(),
            host_value_policy: HOST_ENV_CUSTODY_HOST_VALUES_ONLY.to_string(),
            sandbox_value_policy: HOST_ENV_CUSTODY_SANDBOX_NO_SECRET_VALUES.to_string(),
        }
    }
}

impl HostEnvCustodyContract {
    /// Trim, sort, deduplicate, and validate class-name lists.
    pub fn normalized(mut self) -> Result<Self, HostEnvCustodyError> {
        validate_literal(
            "host_env_custody.mode",
            &self.mode,
            HOST_ENV_CUSTODY_MODE_NAMED_ENV_PALETTE,
        )?;
        validate_literal(
            "host_env_custody.wire_value_policy",
            &self.wire_value_policy,
            HOST_ENV_CUSTODY_WIRE_CLASS_NAMES_ONLY,
        )?;
        validate_literal(
            "host_env_custody.host_value_policy",
            &self.host_value_policy,
            HOST_ENV_CUSTODY_HOST_VALUES_ONLY,
        )?;
        validate_literal(
            "host_env_custody.sandbox_value_policy",
            &self.sandbox_value_policy,
            HOST_ENV_CUSTODY_SANDBOX_NO_SECRET_VALUES,
        )?;
        self.orchestrator_issued_host_env_classes = normalize_env_classes(
            "host_env_custody.orchestrator_issued_host_env_classes",
            self.orchestrator_issued_host_env_classes,
        )?;
        self.host_held_env_classes = normalize_env_classes(
            "host_env_custody.host_held_env_classes",
            self.host_held_env_classes,
        )?;
        self.sandbox_visible_env_classes = normalize_env_classes(
            "host_env_custody.sandbox_visible_env_classes",
            self.sandbox_visible_env_classes,
        )?;
        Ok(self)
    }
}

/// Return a metadata object containing one normalized host-env custody contract.
pub fn host_env_custody_metadata(
    contract: HostEnvCustodyContract,
) -> Result<Value, HostEnvCustodyError> {
    let mut metadata = Map::new();
    metadata.insert(
        HOST_ENV_CUSTODY_METADATA_KEY.to_string(),
        host_env_custody_value(contract)?,
    );
    Ok(Value::Object(metadata))
}

/// Normalize a JSON metadata object containing optional host-env custody data.
///
/// The input must be a JSON object. If the `host_env_custody` key is absent,
/// the object is returned unchanged. If present, the value must deserialize to a
/// [`HostEnvCustodyContract`] and is replaced with its canonical normalized
/// form.
pub fn normalize_host_env_custody_metadata(
    mut metadata: Value,
) -> Result<Value, HostEnvCustodyError> {
    let Value::Object(object) = &mut metadata else {
        return Err(HostEnvCustodyError::new(
            "host_env_custody metadata envelope must be a JSON object",
        ));
    };
    normalize_host_env_custody_metadata_object(object)?;
    Ok(metadata)
}

/// Normalize optional host-env custody data inside an existing metadata object.
pub fn normalize_host_env_custody_metadata_object(
    metadata: &mut Map<String, Value>,
) -> Result<(), HostEnvCustodyError> {
    let Some(value) = metadata.get(HOST_ENV_CUSTODY_METADATA_KEY) else {
        return Ok(());
    };
    let custody: HostEnvCustodyContract =
        serde_json::from_value(value.clone()).map_err(|error| {
            HostEnvCustodyError::new(format!(
                "metadata.host_env_custody must be a host env custody contract: {error}"
            ))
        })?;
    metadata.insert(
        HOST_ENV_CUSTODY_METADATA_KEY.to_string(),
        host_env_custody_value(custody)?,
    );
    Ok(())
}

/// Error returned when a custody contract is not class-name-only metadata.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct HostEnvCustodyError {
    message: String,
}

impl HostEnvCustodyError {
    fn new(message: impl Into<String>) -> Self {
        Self {
            message: message.into(),
        }
    }

    /// Human-readable validation failure.
    pub fn message(&self) -> &str {
        &self.message
    }
}

impl fmt::Display for HostEnvCustodyError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(&self.message)
    }
}

impl std::error::Error for HostEnvCustodyError {}

fn validate_literal(
    field: &str,
    value: &str,
    expected: &'static str,
) -> Result<(), HostEnvCustodyError> {
    if value == expected {
        return Ok(());
    }
    Err(HostEnvCustodyError::new(format!(
        "{field} must be `{expected}`"
    )))
}

fn host_env_custody_value(contract: HostEnvCustodyContract) -> Result<Value, HostEnvCustodyError> {
    let custody = contract.normalized().map_err(|error| {
        HostEnvCustodyError::new(format!("metadata.host_env_custody invalid: {error}"))
    })?;
    serde_json::to_value(custody).map_err(|error| {
        HostEnvCustodyError::new(format!(
            "metadata.host_env_custody could not be serialized: {error}"
        ))
    })
}

fn normalize_env_classes(
    field: &str,
    values: Vec<String>,
) -> Result<Vec<String>, HostEnvCustodyError> {
    let mut normalized = BTreeSet::new();
    for value in values {
        let value = value.trim();
        if value.is_empty() {
            continue;
        }
        validate_env_class_name(field, value)?;
        normalized.insert(value.to_string());
    }
    Ok(normalized.into_iter().collect())
}

fn validate_env_class_name(field: &str, value: &str) -> Result<(), HostEnvCustodyError> {
    if value.len() > 96 {
        return Err(HostEnvCustodyError::new(format!(
            "{field} entries must be at most 96 bytes"
        )));
    }
    if !value.bytes().all(|byte| {
        byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b':' | b'_' | b'-' | b'/')
    }) {
        return Err(HostEnvCustodyError::new(format!(
            "{field} entries must be env_class names, not key/value payloads"
        )));
    }
    if looks_like_secret_value(value) {
        return Err(HostEnvCustodyError::new(format!(
            "{field} entries must be env_class names, not credential values"
        )));
    }
    Ok(())
}

fn looks_like_secret_value(value: &str) -> bool {
    let lower = value.to_ascii_lowercase();
    lower.starts_with("github_pat_")
        || lower.starts_with("ghp_")
        || lower.starts_with("gho_")
        || lower.starts_with("ghu_")
        || lower.starts_with("ghs_")
        || lower.starts_with("ghr_")
        || lower.starts_with("glpat-")
        || lower.starts_with("xoxb-")
        || lower.starts_with("xoxp-")
        || lower.starts_with("xapp-")
        || lower.starts_with("sk-")
        || value.starts_with("-----BEGIN")
}

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

    use super::*;

    #[test]
    fn host_env_custody_normalizes_class_names() {
        let contract = HostEnvCustodyContract {
            orchestrator_issued_host_env_classes: vec![
                " github.scoped ".to_string(),
                "model.provider".to_string(),
                "github.scoped".to_string(),
            ],
            host_held_env_classes: vec!["customer.registry".to_string()],
            sandbox_visible_env_classes: vec!["verify".to_string(), "agent".to_string()],
            ..HostEnvCustodyContract::default()
        }
        .normalized()
        .expect("contract");

        assert_eq!(
            contract.orchestrator_issued_host_env_classes,
            vec!["github.scoped".to_string(), "model.provider".to_string()]
        );
        assert_eq!(
            contract.sandbox_visible_env_classes,
            vec!["agent".to_string(), "verify".to_string()]
        );
        assert_eq!(
            serde_json::to_value(&contract).expect("json"),
            json!({
                "mode": "named_env_palette",
                "orchestrator_issued_host_env_classes": ["github.scoped", "model.provider"],
                "host_held_env_classes": ["customer.registry"],
                "sandbox_visible_env_classes": ["agent", "verify"],
                "wire_value_policy": "class_names_only",
                "host_value_policy": "host_values_only",
                "sandbox_value_policy": "no_secret_values"
            })
        );
    }

    #[test]
    fn host_env_custody_rejects_secret_like_values() {
        let error =
            HostEnvCustodyContract {
                orchestrator_issued_host_env_classes: vec![
                    "ghp_abcdefghijklmnopqrstuvwxyz".to_string()
                ],
                ..HostEnvCustodyContract::default()
            }
            .normalized()
            .expect_err("credential-looking values are rejected");

        assert_eq!(
            error.message(),
            "host_env_custody.orchestrator_issued_host_env_classes entries must be env_class names, not credential values"
        );
    }

    #[test]
    fn host_env_custody_rejects_key_value_payloads() {
        let error = HostEnvCustodyContract {
            host_held_env_classes: vec!["OPENAI_API_KEY=sk-test".to_string()],
            ..HostEnvCustodyContract::default()
        }
        .normalized()
        .expect_err("env assignments are rejected");

        assert_eq!(
            error.message(),
            "host_env_custody.host_held_env_classes entries must be env_class names, not key/value payloads"
        );
    }

    #[test]
    fn host_env_custody_rejects_unknown_json_fields() {
        let error = serde_json::from_value::<HostEnvCustodyContract>(json!({
            "mode": "named_env_palette",
            "token": "ghp_should_not_parse"
        }))
        .expect_err("unknown fields rejected");

        assert!(
            error.to_string().contains("unknown field `token`"),
            "unexpected error: {error}"
        );
    }

    #[test]
    fn host_env_custody_metadata_normalizes_optional_contract() {
        let metadata = normalize_host_env_custody_metadata(json!({
            "claim_kind": "worker_interactive",
            "host_env_custody": {
                "orchestrator_issued_host_env_classes": [
                    " model.provider ",
                    "github.scoped",
                    "github.scoped"
                ],
                "host_held_env_classes": [" customer.registry "],
                "sandbox_visible_env_classes": ["verify", "agent"]
            }
        }))
        .expect("metadata");

        assert_eq!(metadata["claim_kind"], json!("worker_interactive"));
        assert_eq!(
            metadata["host_env_custody"],
            json!({
                "mode": "named_env_palette",
                "orchestrator_issued_host_env_classes": ["github.scoped", "model.provider"],
                "host_held_env_classes": ["customer.registry"],
                "sandbox_visible_env_classes": ["agent", "verify"],
                "wire_value_policy": "class_names_only",
                "host_value_policy": "host_values_only",
                "sandbox_value_policy": "no_secret_values"
            })
        );
    }

    #[test]
    fn host_env_custody_metadata_without_contract_is_noop() {
        let metadata = json!({"claim_kind": "worker_interactive"});

        assert_eq!(
            normalize_host_env_custody_metadata(metadata.clone()).expect("metadata"),
            metadata
        );
    }

    #[test]
    fn host_env_custody_metadata_rejects_non_object_envelope() {
        let error =
            normalize_host_env_custody_metadata(json!(["not", "metadata"])).expect_err("object");

        assert_eq!(
            error.message(),
            "host_env_custody metadata envelope must be a JSON object"
        );
    }

    #[test]
    fn host_env_custody_metadata_rejects_invalid_contract() {
        let error = normalize_host_env_custody_metadata(json!({
            "host_env_custody": {
                "orchestrator_issued_host_env_classes": ["sk-test"]
            }
        }))
        .expect_err("credential value rejected");

        assert_eq!(
            error.message(),
            "metadata.host_env_custody invalid: host_env_custody.orchestrator_issued_host_env_classes entries must be env_class names, not credential values"
        );
    }

    #[test]
    fn host_env_custody_metadata_constructor_normalizes_contract() {
        let metadata = host_env_custody_metadata(HostEnvCustodyContract {
            host_held_env_classes: vec![" customer.registry ".to_string(), "agent".to_string()],
            ..HostEnvCustodyContract::default()
        })
        .expect("metadata");

        assert_eq!(
            metadata,
            json!({
                "host_env_custody": {
                    "mode": "named_env_palette",
                    "orchestrator_issued_host_env_classes": [],
                    "host_held_env_classes": ["agent", "customer.registry"],
                    "sandbox_visible_env_classes": [],
                    "wire_value_policy": "class_names_only",
                    "host_value_policy": "host_values_only",
                    "sandbox_value_policy": "no_secret_values"
                }
            })
        );
    }
}