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: std::sync::Arc<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(in crate::config_gate) 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 {
76 id,
77 handle: std::sync::Arc::new(handle),
78 layer,
79 })
80}
81
82pub(super) fn read_layer(root: &File, leaf: &OsStr) -> Result<LayerLocation> {
83 let directory =
84 subc_os::open_directory_nofollow_at(root, OsStr::new(".cortexkit")).map_err(open_error)?;
85 let Some(directory) = directory else {
86 return Ok(LayerLocation {
87 directory: None,
88 directory_id: None,
89 file: None,
90 });
91 };
92 let directory_id = file_object_id(&directory).map_err(layer_unavailable)?;
93 let file = subc_os::open_single_link_file_nofollow_at(&directory, leaf)
94 .map_err(open_error)?
95 .map(read_file)
96 .transpose()?;
97 Ok(LayerLocation {
98 directory: Some(directory),
99 directory_id: Some(directory_id),
100 file,
101 })
102}
103
104fn read_file(handle: File) -> Result<LayerFile> {
105 let id = file_object_id(&handle).map_err(layer_unavailable)?;
106 let before = handle.metadata().map_err(layer_unavailable)?;
107 let mut bytes = Vec::new();
108 (&handle)
109 .take(CONFIG_FILE_LIMIT + 1)
110 .read_to_end(&mut bytes)
111 .map_err(layer_unavailable)?;
112 if bytes.len() as u64 > CONFIG_FILE_LIMIT {
113 return Err(GateError::new(
114 "layer_too_large",
115 "configuration document exceeds the 1 MiB JSONC limit",
116 ));
117 }
118 let after = handle.metadata().map_err(layer_unavailable)?;
119 if before.len() != bytes.len() as u64
120 || before.len() != after.len()
121 || before.modified().ok() != after.modified().ok()
122 {
123 return Err(layer_unavailable(
124 "configuration layer changed while reading",
125 ));
126 }
127 Ok(LayerFile {
128 handle,
129 id,
130 digest: raw_digest(&bytes),
131 bytes,
132 })
133}
134
135fn open_error(error: OpenRetainedError) -> GateError {
136 let code = match error {
137 OpenRetainedError::Symlink => "layer_symlink",
138 OpenRetainedError::NotRegular => "layer_not_regular",
139 OpenRetainedError::Hardlinked => "layer_hardlinked",
140 OpenRetainedError::Io(_) => "config_unavailable",
141 };
142 GateError::new(code, error)
143}