Skip to main content

subc_daemon/config_gate/project_registry/
layers.rs

1//! Retained-root and layer observations. All filesystem calls run in a root I/O job.
2
3use std::{ffi::OsStr, fs::File, io::Read, path::Path};
4
5use subc_config::{raw_digest, Digest};
6use subc_os::OpenRetainedError;
7
8use super::{layer_unavailable, RegistryFileId, RootCheckFailure};
9use crate::config_gate::{
10    capture::{file_object_id, FileObjectId, CONFIG_FILE_LIMIT},
11    GateError, Result,
12};
13
14pub(super) struct OpenedRoot {
15    pub id: RegistryFileId,
16    pub handle: std::sync::Arc<File>,
17    pub layer: Option<Result<LayerLocation>>,
18}
19
20/// One observation of a physical layer location, even when several tuples read
21/// it. A missing parent and an existing directory with no file are distinct.
22pub struct LayerLocation {
23    pub directory: Option<File>,
24    pub directory_id: Option<FileObjectId>,
25    pub file: Option<LayerFile>,
26}
27
28pub struct LayerFile {
29    pub handle: File,
30    pub id: FileObjectId,
31    pub digest: Digest,
32    pub bytes: Vec<u8>,
33    pub permissions: std::fs::Permissions,
34    pub fingerprint: subc_config::InputState,
35}
36
37impl LayerLocation {
38    pub(in crate::config_gate) fn same_identity(&self, current: &Self) -> bool {
39        self.directory_id == current.directory_id
40            && self.file.as_ref().map(|file| &file.id) == current.file.as_ref().map(|file| &file.id)
41    }
42}
43
44pub(super) fn open_root(
45    path: &Path,
46    layer_leaf: Option<&OsStr>,
47    allowed: &[Option<RegistryFileId>],
48) -> std::result::Result<OpenedRoot, RootCheckFailure> {
49    if !path.is_absolute()
50        || path
51            .components()
52            .collect::<std::path::PathBuf>()
53            .as_os_str()
54            != path.as_os_str()
55    {
56        return Err(RootCheckFailure::InvalidPath);
57    }
58    if path
59        .components()
60        .any(|part| matches!(part, std::path::Component::ParentDir))
61    {
62        return Err(RootCheckFailure::InvalidPath);
63    }
64    let handle = subc_os::open_directory_nofollow_all(path)
65        .map_err(|error| RootCheckFailure::OpenRefused(std::sync::Arc::new(error)))?;
66    let id = RegistryFileId::read(&handle)
67        .map_err(|error| RootCheckFailure::IdentityUnreadable(std::sync::Arc::new(error)))?;
68    // Do not inspect a replacement checkout's settings. Shared roots can
69    // have several expectations; only readers with a match will get the file.
70    let layer = layer_leaf
71        .filter(|_| {
72            allowed
73                .iter()
74                .any(|expected| expected.as_ref().is_none_or(|expected| expected == &id))
75        })
76        .map(|leaf| read_layer(&handle, leaf));
77    Ok(OpenedRoot {
78        id,
79        handle: std::sync::Arc::new(handle),
80        layer,
81    })
82}
83
84pub(super) fn read_layer(root: &File, leaf: &OsStr) -> Result<LayerLocation> {
85    let directory =
86        subc_os::open_directory_nofollow_at(root, OsStr::new(".cortexkit")).map_err(open_error)?;
87    let Some(directory) = directory else {
88        return Ok(LayerLocation {
89            directory: None,
90            directory_id: None,
91            file: None,
92        });
93    };
94    let directory_id = file_object_id(&directory).map_err(layer_unavailable)?;
95    let file = subc_os::open_single_link_file_nofollow_at(&directory, leaf)
96        .map_err(open_error)?
97        .map(read_file)
98        .transpose()?;
99    Ok(LayerLocation {
100        directory: Some(directory),
101        directory_id: Some(directory_id),
102        file,
103    })
104}
105
106fn read_file(handle: File) -> Result<LayerFile> {
107    let id = file_object_id(&handle).map_err(layer_unavailable)?;
108    let before = handle.metadata().map_err(layer_unavailable)?;
109    let mut bytes = Vec::new();
110    (&handle)
111        .take(CONFIG_FILE_LIMIT + 1)
112        .read_to_end(&mut bytes)
113        .map_err(layer_unavailable)?;
114    if bytes.len() as u64 > CONFIG_FILE_LIMIT {
115        return Err(GateError::new(
116            "layer_too_large",
117            "configuration document exceeds the 1 MiB JSONC limit",
118        ));
119    }
120    let after = handle.metadata().map_err(layer_unavailable)?;
121    if before.len() != bytes.len() as u64
122        || before.len() != after.len()
123        || before.modified().ok() != after.modified().ok()
124    {
125        return Err(layer_unavailable(
126            "configuration layer changed while reading",
127        ));
128    }
129    Ok(LayerFile {
130        fingerprint: crate::config_gate::capture::opened_file_state(&handle, &before, &bytes)?,
131        permissions: before.permissions(),
132        handle,
133        id,
134        digest: raw_digest(&bytes),
135        bytes,
136    })
137}
138
139fn open_error(error: OpenRetainedError) -> GateError {
140    let code = match error {
141        OpenRetainedError::Symlink => "layer_symlink",
142        OpenRetainedError::NotRegular => "layer_not_regular",
143        OpenRetainedError::Hardlinked => "layer_hardlinked",
144        OpenRetainedError::Io(_) => "config_unavailable",
145    };
146    GateError::new(code, error)
147}