Skip to main content

lean_ctx/core/intelligence_runtime/
mod.rs

1// SPDX-License-Identifier: Apache-2.0
2//! Public installation authority for the optional, separately licensed runtime.
3//! No private implementation, account, entitlement, or implicit network access.
4
5mod bootstrap;
6mod catalog;
7mod channel;
8mod cli;
9pub mod cockpit;
10pub mod code_security;
11pub mod compliance_frameworks;
12mod configuration;
13pub(crate) mod dashboard_pro;
14mod exchange;
15pub(crate) mod org_policy_verifier;
16pub(crate) mod semantic_coverage;
17pub mod semantic_detectors;
18
19// Exercise the same explicit private-directory prerequisite as the CLI.
20#[cfg(any(test, feature = "test-support"))]
21#[cfg_attr(
22    not(any(target_os = "macos", all(target_os = "linux", target_env = "gnu"))),
23    allow(dead_code)
24)]
25pub(crate) fn private_root_for_test() -> tempfile::TempDir {
26    let mut builder = tempfile::Builder::new();
27    builder.prefix("runtime-install-test-");
28    #[cfg(unix)]
29    {
30        use std::os::unix::fs::PermissionsExt;
31        builder.permissions(std::fs::Permissions::from_mode(0o700));
32    }
33    builder.tempdir().expect("private test root")
34}
35
36/// Signs `document` under `domain` as a release manifest would be signed.
37#[cfg(all(
38    any(test, feature = "test-support"),
39    any(target_os = "macos", all(target_os = "linux", target_env = "gnu"))
40))]
41pub(crate) fn sign_document(
42    document: &serde_json::Value,
43    key: &ed25519_dalek::SigningKey,
44    domain: &[u8],
45) -> (Vec<u8>, Vec<u8>, String) {
46    use ed25519_dalek::Signer;
47    let manifest = serde_json::to_vec(document).expect("manifest");
48    let mut payload = domain.to_vec();
49    payload.extend_from_slice(&manifest);
50    let signature = key.sign(&payload).to_bytes().to_vec();
51    let selected = sha256(&manifest);
52    (manifest, signature, selected)
53}
54
55/// The company-journey fixture endpoint for tests outside the Engine (the
56/// proxy's held-floor journey); inside the Engine it is the test module.
57#[cfg(all(
58    feature = "test-support",
59    not(test),
60    any(target_os = "macos", all(target_os = "linux", target_env = "gnu"))
61))]
62#[allow(dead_code, unused_imports, clippy::unwrap_used)]
63#[path = "company_journey_tests.rs"]
64pub mod company_journey_support;
65mod semantic_worker;
66pub use configuration::{
67    COMPANIONS_LATER, DISCLOSURE, SetupRuntime, inspect_setup, load_companions,
68};
69mod health;
70mod install;
71mod license;
72// The Cloud connector's runtime lease registers the source.
73pub mod lease;
74mod manifest;
75mod rotation;
76#[cfg(any(unix, windows))]
77mod session;
78#[cfg(windows)]
79mod session_windows;
80
81#[cfg(test)]
82pub(crate) mod tests;
83
84use std::io::Read;
85use std::path::Path;
86
87pub use cli::{USAGE, error_message, human_note, plain_install, run};
88use manifest::{VerifiedPackage, verify, verify_kind};
89
90// The signed archive member stays platform-neutral; only materialized files vary.
91const EXECUTABLE_NAME: &str = if cfg!(windows) {
92    "leanctx-intelligence.exe"
93} else {
94    "leanctx-intelligence"
95};
96
97/// The signed package kinds the runtime channel delivers. Both share the
98/// archive shape, the signature domains and the trust chain; the signed
99/// `runtime-description.json` names the kind (`engine_id`), and every use
100/// re-authenticates the package as the kind it expects, so one kind never
101/// runs as the other.
102#[derive(Debug, Clone, Copy, PartialEq, Eq)]
103pub(crate) enum RuntimeKind {
104    /// The Pro Intelligence Runtime: licence-bound outside staging.
105    Intelligence,
106    /// The Cockpit web UI: free for everyone, never licence-bound.
107    Cockpit,
108}
109
110impl RuntimeKind {
111    pub(crate) const fn engine_id(self) -> &'static str {
112        match self {
113            Self::Intelligence => "leanctx-intelligence",
114            Self::Cockpit => "leanctx-cockpit",
115        }
116    }
117
118    /// The store directory beside the context data: `<name>` for staging,
119    /// `<name>-production` for production. Kinds never share a store.
120    pub(crate) const fn store_name(self) -> &'static str {
121        match self {
122            Self::Intelligence => "intelligence-runtime",
123            Self::Cockpit => "cockpit-runtime",
124        }
125    }
126}
127
128#[derive(Debug, thiserror::Error)]
129pub enum InstallError {
130    #[error("invalid runtime installer arguments")]
131    Usage,
132    #[error("runtime download URL, transport or response rejected")]
133    Download,
134    #[error("runtime package I/O failed")]
135    Io(#[from] std::io::Error),
136    #[error("runtime metadata or package exceeds its size bound")]
137    Size,
138    #[error("runtime input is not a regular, non-symlink file")]
139    Input,
140    /// The package manifest of one release (not the channel catalog).
141    #[error("runtime package manifest is not independently selected or compatible")]
142    Manifest,
143    /// The signed channel catalog is past its window: nothing new can be
144    /// selected from it until the channel publishes a fresh one.
145    #[error("runtime channel catalog has expired; try again later or update lean-ctx")]
146    ChannelExpired,
147    /// The signed channel catalog is not one this LeanCTX accepts (schema,
148    /// channel name, window or release list).
149    #[error("runtime channel catalog does not match the channel this LeanCTX version accepts")]
150    ChannelMismatch,
151    /// The channel carries no package for this operating system and CPU.
152    #[error("Runtime for this platform is not available yet")]
153    PlatformUnavailable,
154    #[error("runtime signature does not match the independent trust key")]
155    Signature,
156    #[error("runtime archive is invalid or incompatible with this host")]
157    Archive,
158    #[error("runtime installation directory is not private and canonical")]
159    Directory,
160    #[error("another runtime installation is active")]
161    Busy,
162    #[error("runtime selection changed or retained package is inconsistent")]
163    State,
164    #[error("runtime channel is older than the active one; a downgrade must be requested")]
165    Downgrade,
166    #[error("atomic runtime selection write failed")]
167    Commit,
168    #[error("runtime health check failed or exceeded its bound")]
169    Health,
170    #[error("runtime invocation is not supported by the authenticated package and this host")]
171    InvocationAdmission,
172    #[error("runtime invocation failed or exceeded its bound")]
173    Exchange,
174    #[error("runtime request or policy input was rejected")]
175    Policy,
176    #[error("runtime global configuration could not be updated")]
177    Configuration,
178}
179
180pub(crate) type Result<T> = std::result::Result<T, InstallError>;
181
182fn trust_key(encoded: &str) -> Result<[u8; 32]> {
183    if !is_digest(encoded, 64) {
184        return Err(InstallError::Usage);
185    }
186    let mut key = [0; 32];
187    for (index, byte) in key.iter_mut().enumerate() {
188        *byte = u8::from_str_radix(&encoded[index * 2..index * 2 + 2], 16)
189            .map_err(|_| InstallError::Usage)?;
190    }
191    Ok(key)
192}
193
194/// Open once and bound the actual read, including files that grow after stat.
195pub(crate) fn read_regular(path: &Path, limit: usize) -> Result<Vec<u8>> {
196    let metadata = std::fs::symlink_metadata(path)?;
197    if !regular_metadata(&metadata) {
198        return Err(InstallError::Input);
199    }
200    let mut options = std::fs::OpenOptions::new();
201    options.read(true);
202    #[cfg(unix)]
203    {
204        use std::os::unix::fs::OpenOptionsExt;
205        options.custom_flags(libc::O_NOFOLLOW | libc::O_NONBLOCK);
206    }
207    #[cfg(windows)]
208    {
209        use std::os::windows::fs::OpenOptionsExt;
210        use windows_sys::Win32::Storage::FileSystem::FILE_FLAG_OPEN_REPARSE_POINT;
211        // Bind the leaf itself even if it becomes a reparse point after stat.
212        options.custom_flags(FILE_FLAG_OPEN_REPARSE_POINT);
213    }
214    let file = options.open(path)?;
215    let metadata = file.metadata()?;
216    if !regular_metadata(&metadata) {
217        return Err(InstallError::Input);
218    }
219    if metadata.len() > limit as u64 {
220        return Err(InstallError::Size);
221    }
222    let mut bytes = Vec::new();
223    file.take(limit as u64 + 1).read_to_end(&mut bytes)?;
224    if bytes.len() > limit {
225        return Err(InstallError::Size);
226    }
227    Ok(bytes)
228}
229
230fn regular_metadata(metadata: &std::fs::Metadata) -> bool {
231    #[cfg(windows)]
232    {
233        use std::os::windows::fs::MetadataExt;
234        use windows_sys::Win32::Storage::FileSystem::FILE_ATTRIBUTE_REPARSE_POINT;
235        // Symlinks are only one reparse tag; reject every reparse-backed input.
236        if metadata.file_attributes() & FILE_ATTRIBUTE_REPARSE_POINT != 0 {
237            return false;
238        }
239    }
240    metadata.is_file() && !metadata.file_type().is_symlink()
241}
242
243use super::updater::sha256_hex as sha256;
244
245pub(crate) fn is_digest(value: &str, length: usize) -> bool {
246    value.len() == length
247        && value
248            .bytes()
249            .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
250}