A11 (C++ runtime)
Native C++ implementation of the A11 streaming action runtime
Loading...
Searching...
No Matches
file_modules.h
Go to the documentation of this file.
1// Copyright 2026 The A11 Authors
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15#ifndef A11_FLOW_FILE_MODULES_H_
16#define A11_FLOW_FILE_MODULES_H_
17
18#include <cerrno>
19#include <cstdint>
20#include <filesystem>
21#include <string>
22#include <vector>
23
24#if defined(__unix__) || defined(__APPLE__)
25#include <fcntl.h>
26#include <sys/stat.h>
27#include <unistd.h>
28#endif
29
30#include "a11/flow/module.h"
31#include "a11/percent.h"
32
33namespace a11::flow {
35inline std::string FileModuleIdentity(std::string_view reference) {
36 std::string name(reference);
37 if (name.empty() || name == "-" || name.front() == '<') {
38 return name;
39 }
40 if (name.starts_with("file://")) {
41 auto decoded =
42 percent::DecodeStrict(std::string_view(name).substr(7), "file URI");
43 if (!decoded.ok()) {
44 return name;
45 }
46 name = *decoded;
47 }
48 std::error_code error;
49 const auto path = std::filesystem::absolute(name, error);
50 return error ? name : path.lexically_normal().generic_string();
51}
52
55 size_t max_bytes = 8 * 1024 * 1024, ModuleSources overrides = {},
56 std::vector<std::string> approved_roots = {}) {
57 std::vector<std::filesystem::path> roots;
58 for (const auto& root : approved_roots) {
59 roots.emplace_back(FileModuleIdentity(root));
60 }
61 return [max_bytes, overrides = std::move(overrides),
62 roots = std::move(roots)](
63 std::string_view reference,
64 std::string_view importer) -> absl::StatusOr<ModuleSource> {
65 if (roots.empty() && overrides.empty()) {
66 return absl::PermissionDeniedError(
67 "Source imports are disallowed in the current runtime: no source "
68 "roots are approved.");
69 }
70 if (reference.find("://") != std::string_view::npos ||
71 reference.find('\0') != std::string_view::npos) {
72 return absl::PermissionDeniedError(
73 "Source imports require a local path.");
74 }
75 std::filesystem::path path(reference);
76 if (path.is_relative()) {
77 if (importer.empty() || importer == "-" || importer.front() == '<') {
78 return absl::PermissionDeniedError(
79 "A relative source import requires a document path.");
80 }
81 path = std::filesystem::path(importer).parent_path() / path;
82 }
83 path = std::filesystem::path(FileModuleIdentity(path.generic_string()));
84 if (const auto found = overrides.find(path.generic_string());
85 found != overrides.end()) {
86 if (found->second.size() > max_bytes) {
87 return absl::ResourceExhaustedError(
88 "Imported source exceeds the byte limit.");
89 }
90 return ModuleSource{found->first, found->second};
91 }
92 if (roots.empty()) {
93 return absl::PermissionDeniedError(
94 "Source imports are disallowed in the current runtime: "
95 "no source roots are approved.");
96 }
97 std::filesystem::path approved;
98 std::filesystem::path relative;
99 for (const auto& root : roots) {
100 const auto candidate = path.lexically_relative(root);
101 if (candidate.empty() || candidate.is_absolute()) {
102 continue;
103 }
104 bool contained = true;
105 for (const auto& component : candidate) {
106 if (component == "..") {
107 contained = false;
108 }
109 }
110 if (contained) {
111 approved = root;
112 relative = candidate;
113 break;
114 }
115 }
116 if (approved.empty()) {
117 return absl::PermissionDeniedError(
118 "Source import is outside the runtime's approved source roots.");
119 }
120#if defined(__unix__) || defined(__APPLE__)
121 class Descriptor {
122 public:
123 explicit Descriptor(int value) : value_(value) {}
124 ~Descriptor() {
125 if (value_ >= 0)
126 ::close(value_);
127 }
128 Descriptor(const Descriptor&) = delete;
129 Descriptor& operator=(const Descriptor&) = delete;
130 int get() const { return value_; }
131 void Reset(int value) {
132 if (value_ >= 0)
133 ::close(value_);
134 value_ = value;
135 }
136
137 private:
138 int value_;
139 };
140 Descriptor directory(::open("/", O_RDONLY | O_DIRECTORY | O_CLOEXEC));
141 for (const auto& component : approved.relative_path()) {
142 if (component == ".")
143 continue;
144 const int next =
145 ::openat(directory.get(), component.c_str(),
146 O_RDONLY | O_DIRECTORY | O_CLOEXEC | O_NOFOLLOW);
147 if (next < 0) {
148 return absl::PermissionDeniedError(
149 "Cannot open an approved source root without traversing symlinks.");
150 }
151 directory.Reset(next);
152 }
153 std::vector<std::filesystem::path> components;
154 for (const auto& component : relative) {
155 if (component != ".")
156 components.push_back(component);
157 }
158 if (components.empty()) {
159 return absl::InvalidArgumentError("An imported source must be a file.");
160 }
161 for (size_t index = 0; index + 1 < components.size(); ++index) {
162 const int next =
163 ::openat(directory.get(), components[index].c_str(),
164 O_RDONLY | O_DIRECTORY | O_CLOEXEC | O_NOFOLLOW);
165 if (next < 0) {
166 return absl::PermissionDeniedError(
167 "Cannot resolve imported source within approved roots; "
168 "symlink traversal is disallowed.");
169 }
170 directory.Reset(next);
171 }
172 Descriptor file(::openat(directory.get(), components.back().c_str(),
173 O_RDONLY | O_CLOEXEC | O_NOFOLLOW | O_NONBLOCK));
174 if (file.get() < 0) {
175 return absl::PermissionDeniedError(
176 "Cannot open imported source within approved roots; "
177 "symlink traversal is disallowed.");
178 }
179 struct stat metadata{};
180 if (::fstat(file.get(), &metadata) != 0 || !S_ISREG(metadata.st_mode)) {
181 return absl::InvalidArgumentError(
182 "An imported source must be a regular file.");
183 }
184 if (metadata.st_size < 0 ||
185 static_cast<uint64_t>(metadata.st_size) > max_bytes) {
186 return absl::ResourceExhaustedError(
187 "Imported source exceeds the byte limit.");
188 }
189 std::string source;
190 char buffer[4096];
191 while (true) {
192 const auto count = ::read(file.get(), buffer, sizeof(buffer));
193 if (count == 0)
194 break;
195 if (count < 0) {
196 if (errno == EINTR)
197 continue;
198 return absl::DataLossError("Cannot read imported source.");
199 }
200 const auto size = static_cast<size_t>(count);
201 if (size > max_bytes - source.size()) {
202 return absl::ResourceExhaustedError(
203 "Imported source exceeds the byte limit.");
204 }
205 source.append(buffer, size);
206 }
207 return ModuleSource{path.generic_string(), std::move(source)};
208#else
209 return absl::UnimplementedError(
210 "This runtime has no confined filesystem source resolver.");
211#endif
212 };
213}
214} // namespace a11::flow
215#endif // A11_FLOW_FILE_MODULES_H_
std::string value
Definition discover.cc:100
std::string name
The declaration name and its colon.
Definition format.cc:50
std::string path
Definition main.cc:135
std::vector< std::string > roots
Definition main.cc:137
Definition catalogue.cc:29
ModuleResolver FileModuleResolver(size_t max_bytes=8 *1024 *1024, ModuleSources overrides={}, std::vector< std::string > approved_roots={})
Filesystem imports confined to explicitly approved roots without symlinks.
Definition file_modules.h:54
std::function< absl::StatusOr< ModuleSource >(std::string_view reference, std::string_view importer)> ModuleResolver
Definition module.h:39
std::string FileModuleIdentity(std::string_view reference)
Lexical source identity; normalizing it performs no target-path inspection.
Definition file_modules.h:35
absl::flat_hash_map< std::string, std::string > ModuleSources
Definition module.h:37
absl::StatusOr< std::string > DecodeStrict(std::string_view value, std::string_view what)
Percent-decodes value, or says why it cannot be decoded.
Definition percent.h:94
Percent-encoding, as inline functions over a string_view.
std::optional< std::string > metadata
Definition sqlite_chunk_store.cc:194
std::string root
Definition main.cc:76