subc_daemon/config_gate/project_registry/
layers.rs1use 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: File,
17 pub layer: Option<Result<LayerLocation>>,
18}
19
20pub 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}
34
35impl LayerLocation {
36 pub(super) fn same_identity(&self, current: &Self) -> bool {
37 self.directory_id == current.directory_id
38 && self.file.as_ref().map(|file| &file.id) == current.file.as_ref().map(|file| &file.id)
39 }
40}
41
42pub(super) fn open_root(
43 path: &Path,
44 layer_leaf: Option<&OsStr>,
45 allowed: &[Option<RegistryFileId>],
46) -> std::result::Result<OpenedRoot, RootCheckFailure> {
47 if !path.is_absolute()
48 || path
49 .components()
50 .collect::<std::path::PathBuf>()
51 .as_os_str()
52 != path.as_os_str()
53 {
54 return Err(RootCheckFailure::InvalidPath);
55 }
56 if path
57 .components()
58 .any(|part| matches!(part, std::path::Component::ParentDir))
59 {
60 return Err(RootCheckFailure::InvalidPath);
61 }
62 let handle = subc_os::open_directory_nofollow_all(path)
63 .map_err(|error| RootCheckFailure::OpenRefused(std::sync::Arc::new(error)))?;
64 let id = RegistryFileId::read(&handle)
65 .map_err(|error| RootCheckFailure::IdentityUnreadable(std::sync::Arc::new(error)))?;
66 let layer = layer_leaf
69 .filter(|_| {
70 allowed
71 .iter()
72 .any(|expected| expected.as_ref().is_none_or(|expected| expected == &id))
73 })
74 .map(|leaf| read_layer(&handle, leaf));
75 Ok(OpenedRoot { id, handle, layer })
76}
77
78fn read_layer(root: &File, leaf: &OsStr) -> Result<LayerLocation> {
79 let directory =
80 subc_os::open_directory_nofollow_at(root, OsStr::new(".cortexkit")).map_err(open_error)?;
81 let Some(directory) = directory else {
82 return Ok(LayerLocation {
83 directory: None,
84 directory_id: None,
85 file: None,
86 });
87 };
88 let directory_id = file_object_id(&directory).map_err(layer_unavailable)?;
89 let file = subc_os::open_single_link_file_nofollow_at(&directory, leaf)
90 .map_err(open_error)?
91 .map(read_file)
92 .transpose()?;
93 Ok(LayerLocation {
94 directory: Some(directory),
95 directory_id: Some(directory_id),
96 file,
97 })
98}
99
100fn read_file(handle: File) -> Result<LayerFile> {
101 let id = file_object_id(&handle).map_err(layer_unavailable)?;
102 let before = handle.metadata().map_err(layer_unavailable)?;
103 let mut bytes = Vec::new();
104 (&handle)
105 .take(CONFIG_FILE_LIMIT + 1)
106 .read_to_end(&mut bytes)
107 .map_err(layer_unavailable)?;
108 if bytes.len() as u64 > CONFIG_FILE_LIMIT {
109 return Err(GateError::new(
110 "layer_too_large",
111 "configuration document exceeds the 1 MiB JSONC limit",
112 ));
113 }
114 let after = handle.metadata().map_err(layer_unavailable)?;
115 if before.len() != bytes.len() as u64
116 || before.len() != after.len()
117 || before.modified().ok() != after.modified().ok()
118 {
119 return Err(layer_unavailable(
120 "configuration layer changed while reading",
121 ));
122 }
123 Ok(LayerFile {
124 handle,
125 id,
126 digest: raw_digest(&bytes),
127 bytes,
128 })
129}
130
131fn open_error(error: OpenRetainedError) -> GateError {
132 let code = match error {
133 OpenRetainedError::Symlink => "layer_symlink",
134 OpenRetainedError::NotRegular => "layer_not_regular",
135 OpenRetainedError::Hardlinked => "layer_hardlinked",
136 OpenRetainedError::Io(_) => "config_unavailable",
137 };
138 GateError::new(code, error)
139}