Skip to main content

dive_stdlib/
inputs.rs

1//! Bounded live environment/text inputs during source binding. A specification
2//! gets no host access unless the run grants the category explicitly, also under
3//! `--compat=tlc`.
4//! Later evaluation can use captured values, but cannot execute more I/O.
5
6use std::collections::BTreeMap;
7use std::io::Read;
8use std::sync::{Mutex, PoisonError};
9
10use dive_eval::HostError;
11use dive_eval::inputs::{
12    HostAccess, InputRecord, InputRequest, InputResponse, InputSource, MAX_ENV_ENTRIES,
13    MAX_INPUT_BYTES, MAX_INPUT_RECORDS, RecordedInputs, input_error,
14};
15
16#[derive(Debug)]
17struct State {
18    records: Vec<InputRecord>,
19    bytes: usize,
20    environment: Option<BTreeMap<String, String>>,
21    closed: bool,
22    failure: Option<HostError>,
23}
24
25/// Live source-binding inputs, empty and unopened until source requests them.
26/// Granting `env` records the entire UTF-8 environment; it may contain secrets.
27/// A seed alone cannot reproduce these external assumptions.
28#[derive(Debug)]
29pub struct LiveInputs {
30    grants: HostAccess,
31    state: Mutex<State>,
32}
33
34impl LiveInputs {
35    /// Creates a bounded recording context. This performs no host access.
36    #[must_use]
37    pub fn new(grants: HostAccess) -> Self {
38        Self {
39            grants,
40            state: Mutex::new(State {
41                records: Vec::new(),
42                bytes: 0,
43                environment: None,
44                closed: false,
45                failure: None,
46            }),
47        }
48    }
49
50    fn read(&self, state: &mut State, request: &InputRequest) -> Result<InputResponse, HostError> {
51        if state.closed {
52            return Err(input_error(
53                "runtime host reads are not implemented; capture inputs in source definitions",
54            ));
55        }
56        if state.records.len() >= MAX_INPUT_RECORDS {
57            return Err(input_error("source input record limit"));
58        }
59        let response = match request {
60            InputRequest::Environment if self.grants.env => {
61                if state.environment.is_none() {
62                    let mut environment = BTreeMap::new();
63                    let mut bytes = 0usize;
64                    for (name, value) in std::env::vars_os() {
65                        if environment.len() >= MAX_ENV_ENTRIES {
66                            return Err(input_error("environment entry limit"));
67                        }
68                        let (name, value) = (
69                            name.into_string()
70                                .map_err(|_| input_error("non-UTF-8 environment name"))?,
71                            value
72                                .into_string()
73                                .map_err(|_| input_error("non-UTF-8 environment value"))?,
74                        );
75                        bytes = bytes.saturating_add(name.len()).saturating_add(value.len());
76                        if bytes > MAX_INPUT_BYTES {
77                            return Err(input_error("environment input byte limit"));
78                        }
79                        environment.insert(name, value);
80                    }
81                    state.environment = Some(environment);
82                }
83                InputResponse::Environment(
84                    state
85                        .environment
86                        .clone()
87                        .ok_or_else(|| input_error("missing owned environment"))?,
88                )
89            }
90            InputRequest::TextFile(path) if self.grants.files => {
91                if state
92                    .records
93                    .iter()
94                    .any(|record| matches!(record.request, InputRequest::TextFile(_)))
95                {
96                    return Err(input_error(
97                        "subsequent TXT Deserialize requests are not implemented (shared native result-name history)",
98                    ));
99                }
100                InputResponse::Text(read_text_file(path)?)
101            }
102            _ => return Err(input_error("source input category was not granted")),
103        };
104        let record = InputRecord {
105            request: request.clone(),
106            response: response.clone(),
107        };
108        let bytes = state.bytes.saturating_add(record.bytes());
109        if bytes > MAX_INPUT_BYTES {
110            return Err(input_error("total external input byte limit"));
111        }
112        state.bytes = bytes;
113        state.records.push(record);
114        Ok(response)
115    }
116}
117
118impl InputSource for LiveInputs {
119    fn request(&self, request: &InputRequest) -> Result<InputResponse, HostError> {
120        let mut state = self.state.lock().unwrap_or_else(PoisonError::into_inner);
121        if let Some(error) = &state.failure {
122            return Err(error.clone());
123        }
124        let result = self.read(&mut state, request);
125        if let Err(error) = &result {
126            state.failure = Some(error.clone());
127        }
128        result
129    }
130    fn finish_binding(&self) -> Result<(), HostError> {
131        let mut state = self.state.lock().unwrap_or_else(PoisonError::into_inner);
132        state.closed = true;
133        state.failure.clone().map_or(Ok(()), Err)
134    }
135    fn recorded(&self) -> RecordedInputs {
136        RecordedInputs {
137            grants: self.grants,
138            records: self
139                .state
140                .lock()
141                .unwrap_or_else(PoisonError::into_inner)
142                .records
143                .clone(),
144        }
145    }
146}
147
148fn read_text_file(path: &str) -> Result<String, HostError> {
149    if path.len() > MAX_INPUT_BYTES {
150        return Err(input_error("input path byte limit"));
151    }
152    if !std::fs::metadata(path)
153        .map_err(|_| {
154            input_error("IOUtils!Deserialize file-open error records are not implemented")
155        })?
156        .is_file()
157    {
158        return Err(input_error("only regular text files are supported"));
159    }
160    let file = std::fs::File::open(path).map_err(|_| {
161        input_error("IOUtils!Deserialize file-open error records are not implemented")
162    })?;
163    if !file
164        .metadata()
165        .map_err(|_| input_error("input file metadata"))?
166        .is_file()
167    {
168        return Err(input_error("only regular text files are supported"));
169    }
170    let mut bytes = Vec::new();
171    file.take(u64::try_from(MAX_INPUT_BYTES + 1).unwrap_or(u64::MAX))
172        .read_to_end(&mut bytes)
173        .map_err(|_| {
174            input_error("IOUtils!Deserialize file-read error records are not implemented")
175        })?;
176    if bytes.len() > MAX_INPUT_BYTES {
177        return Err(input_error("text input byte limit"));
178    }
179    String::from_utf8(bytes)
180        .map_err(|_| input_error("non-UTF-8 file error records are not implemented"))
181}