algotradelib 0.0.0.9000
C++ header-only library for algorithmic trading
Loading...
Searching...
No Matches
file_token_store.hpp
1#pragma once
2
3#include "./token_store.hpp"
4
5#if !defined(_WIN32)
6
7#include <boost/json.hpp>
8
9#include <cerrno>
10#include <chrono>
11#include <cstdint>
12#include <memory>
13#include <optional>
14#include <string>
15#include <string_view>
16#include <thread>
17#include <utility>
18
19#include <fcntl.h>
20#include <sys/file.h>
21#include <sys/stat.h>
22#include <unistd.h>
23
24namespace algotradelib {
25namespace network {
26
43class FileTokenStore : public TokenStore {
44public:
50 explicit FileTokenStore(std::string folder, std::chrono::milliseconds lock_wait = std::chrono::seconds(30))
51 : folder_(std::move(folder)), lock_wait_(lock_wait) {}
52
59 Result<std::unique_ptr<Lock>> lock(const std::string& identity) override {
60 Descriptor folder;
61 if (auto error = open_folder(identity, folder)) {
62 return *error;
63 }
64 const auto name = identity + ".lock";
65 Descriptor file(::openat(folder.get(), name.c_str(), FILE_FLAGS | O_RDWR | O_CREAT, 0600));
66 if (file.get() < 0 && errno == ENOENT) {
67 // A concurrent create that answers no-such-file is retried once.
68 file.reset(::openat(folder.get(), name.c_str(), FILE_FLAGS | O_RDWR | O_CREAT, 0600));
69 }
70 if (auto error = check_file(file)) {
71 return *error;
72 }
73 const auto deadline = std::chrono::steady_clock::now() + lock_wait_;
74 while (::flock(file.get(), LOCK_EX | LOCK_NB) != 0) {
75 if (errno != EWOULDBLOCK && errno != EINTR) {
76 return token_store_error("token store: the lock file could not be locked");
77 }
78 if (std::chrono::steady_clock::now() >= deadline) {
79 return token_store_error("token store: lock not obtained in time");
80 }
81 std::this_thread::sleep_for(std::chrono::milliseconds(10));
82 }
83 std::unique_ptr<Lock> held = std::make_unique<FileLock>(std::move(file));
84 return Result<std::unique_ptr<Lock>>(std::move(held));
85 }
86
92 Result<std::optional<StoredToken>> load(const std::string& identity) override {
93 Descriptor folder;
94 if (auto error = open_folder(identity, folder)) {
95 return *error;
96 }
97 std::optional<std::string> text;
98 if (auto error = read_token(folder, identity, text)) {
99 return *error;
100 }
101 return text ? parse(*text) : std::optional<StoredToken>();
102 }
103
110 std::optional<BrokerError> publish(const std::string& identity, const StoredToken& token) override {
111 Descriptor folder;
112 if (auto error = open_folder(identity, folder)) {
113 return error;
114 }
115 std::optional<std::string> text;
116 if (auto error = read_token(folder, identity, text)) {
117 return error;
118 }
119 if (text) {
120 if (const auto stored = parse(*text); stored && stored->expires_at_ > token.expires_at_) {
121 return std::nullopt;
122 }
123 }
124 return write_token(folder, identity, token);
125 }
126
133 std::optional<BrokerError> discard(const std::string& identity, const std::string& access_token) override {
134 Descriptor folder;
135 if (auto error = open_folder(identity, folder)) {
136 return error;
137 }
138 std::optional<std::string> text;
139 if (auto error = read_token(folder, identity, text)) {
140 return error;
141 }
142 if (!text) {
143 return std::nullopt;
144 }
145 if (const auto stored = parse(*text); !stored || stored->access_token_ != access_token) {
146 return std::nullopt;
147 }
148 return unlink_token(folder, identity);
149 }
150
156 std::optional<BrokerError> remove(const std::string& identity) override {
157 Descriptor folder;
158 if (auto error = open_folder(identity, folder)) {
159 return error;
160 }
161 return unlink_token(folder, identity);
162 }
163
164private:
165 // Opened without following a link, closed on exec, and never blocking on a special file.
166 static constexpr int FILE_FLAGS = O_NOFOLLOW | O_CLOEXEC | O_NONBLOCK;
167 // Larger token files are not well formed.
168 static constexpr std::size_t MAXIMUM_TOKEN_FILE = 64 * 1024;
169
170 // Owns a descriptor; negative for none.
171 class Descriptor {
172 public:
173 explicit Descriptor(int descriptor = -1) noexcept : descriptor_(descriptor) {}
174
175 ~Descriptor() {
176 if (descriptor_ >= 0) {
177 ::close(descriptor_);
178 }
179 }
180
181 Descriptor(Descriptor&& other) noexcept : descriptor_(std::exchange(other.descriptor_, -1)) {}
182 Descriptor& operator=(Descriptor&&) = delete;
183 Descriptor(const Descriptor&) = delete;
184 Descriptor& operator=(const Descriptor&) = delete;
185
186 int get() const noexcept {
187 return descriptor_;
188 }
189
190 void reset(int descriptor) noexcept {
191 if (descriptor_ >= 0) {
192 ::close(descriptor_);
193 }
194 descriptor_ = descriptor;
195 }
196
197 private:
198 int descriptor_;
199 };
200
201 // The lock: closing its own open of the lock file releases it.
202 class FileLock : public Lock {
203 public:
204 explicit FileLock(Descriptor file) noexcept : file_(std::move(file)) {}
205
206 private:
207 Descriptor file_;
208 };
209
210 // Tests whether an identity can name a file: letters, digits, `-` and `_`, at most 200.
211 static bool file_safe(const std::string& identity) noexcept {
212 if (identity.empty() || identity.size() > 200) {
213 return false;
214 }
215 for (const char ch : identity) {
216 const bool allowed =
217 (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || (ch >= '0' && ch <= '9') || ch == '-' || ch == '_';
218 if (!allowed) {
219 return false;
220 }
221 }
222 return true;
223 }
224
225 // Tests what the store requires of everything it opens: the type, the user's own, nothing for group or others.
226 static bool owned_privately(int descriptor, mode_t type) noexcept {
227 struct stat status{};
228 return ::fstat(descriptor, &status) == 0 && (status.st_mode & S_IFMT) == type && status.st_uid == ::geteuid() &&
229 (status.st_mode & 077) == 0;
230 }
231
232 // Creates the folder if it does not exist and opens it, checked.
233 std::optional<BrokerError> open_folder(const std::string& identity, Descriptor& folder) const {
234 if (!file_safe(identity)) {
235 return token_store_error("token store: the identity cannot name a file");
236 }
237 if (::mkdir(folder_.c_str(), 0700) != 0 && errno != EEXIST) {
238 return token_store_error("token store: the folder could not be created");
239 }
240 folder.reset(::open(folder_.c_str(), O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC));
241 if (folder.get() < 0) {
242 struct stat status{};
243 const bool link = ::lstat(folder_.c_str(), &status) == 0 && S_ISLNK(status.st_mode);
244 return token_store_error(
245 link ? "token store: the folder is a symbolic link" : "token store: the folder could not be opened"
246 );
247 }
248 if (!owned_privately(folder.get(), S_IFDIR)) {
249 return token_store_error("token store: the folder is not private (owner or permissions)");
250 }
251 return std::nullopt;
252 }
253
254 // Checks a file just opened.
255 static std::optional<BrokerError> check_file(const Descriptor& file) {
256 if (file.get() < 0) {
257 return token_store_error(
258 errno == ELOOP ? "token store: a file is a symbolic link" : "token store: a file could not be opened"
259 );
260 }
261 if (!owned_privately(file.get(), S_IFREG)) {
262 return token_store_error("token store: a file is not private (owner, permissions or type)");
263 }
264 return std::nullopt;
265 }
266
267 // Reads the token file into `text`; leaves it empty when there is none.
268 static std::optional<BrokerError> read_token(
269 const Descriptor& folder, const std::string& identity, std::optional<std::string>& text
270 ) {
271 Descriptor file(::openat(folder.get(), (identity + ".token").c_str(), FILE_FLAGS | O_RDONLY));
272 if (file.get() < 0 && errno == ENOENT) {
273 return std::nullopt;
274 }
275 if (auto error = check_file(file)) {
276 return error;
277 }
278 std::string contents;
279 char buffer[4096];
280 while (contents.size() <= MAXIMUM_TOKEN_FILE) {
281 const auto count = ::read(file.get(), buffer, sizeof(buffer));
282 if (count == 0) {
283 text = std::move(contents);
284 return std::nullopt;
285 }
286 if (count < 0 && errno != EINTR) {
287 return token_store_error("token store: a file could not be read");
288 }
289 if (count > 0) {
290 contents.append(buffer, static_cast<std::size_t>(count));
291 }
292 }
293 text = std::string();
294 return std::nullopt;
295 }
296
297 // Reads a token file's text; nothing unless it is a JSON object with a nonempty token and an expiry.
298 static std::optional<StoredToken> parse(const std::string& text) {
299 boost::system::error_code ec;
300 const auto document = boost::json::parse(text, ec);
301 if (ec || !document.is_object()) {
302 return std::nullopt;
303 }
304 const auto* token = document.as_object().if_contains("access_token");
305 const auto* expiry = document.as_object().if_contains("expires_at_ns");
306 if (!token || !token->is_string() || token->as_string().empty() || !expiry || !expiry->is_int64()) {
307 return std::nullopt;
308 }
309 const auto since_epoch = std::chrono::nanoseconds(expiry->as_int64());
310 return StoredToken{
311 std::string(token->as_string()),
312 std::chrono::system_clock::time_point(
313 std::chrono::duration_cast<std::chrono::system_clock::duration>(since_epoch)
314 ),
315 };
316 }
317
318 // Writes the token to the temporary file, flushes it and renames it over the token file.
319 static std::optional<BrokerError> write_token(
320 const Descriptor& folder, const std::string& identity, const StoredToken& token
321 ) {
322 boost::json::object document;
323 document["access_token"] = token.access_token_;
324 document["expires_at_ns"] =
325 std::chrono::duration_cast<std::chrono::nanoseconds>(token.expires_at_.time_since_epoch()).count();
326 const auto text = boost::json::serialize(document);
327
328 const auto temporary = identity + ".tmp";
329 // A writer killed before its rename left this file; the lock is held, so nobody else writes it.
330 ::unlinkat(folder.get(), temporary.c_str(), 0);
331 Descriptor file(::openat(folder.get(), temporary.c_str(), FILE_FLAGS | O_WRONLY | O_CREAT | O_EXCL, 0600));
332 bool written = file.get() >= 0;
333 for (std::size_t offset = 0; written && offset < text.size();) {
334 const auto count = ::write(file.get(), text.data() + offset, text.size() - offset);
335 if (count > 0) {
336 offset += static_cast<std::size_t>(count);
337 } else if (count == 0 || errno != EINTR) {
338 written = false;
339 }
340 }
341 written = written && ::fsync(file.get()) == 0 &&
342 ::renameat(folder.get(), temporary.c_str(), folder.get(), (identity + ".token").c_str()) == 0;
343 if (!written) {
344 if (file.get() >= 0) {
345 ::unlinkat(folder.get(), temporary.c_str(), 0);
346 }
347 return token_store_error("token store: the token file could not be written");
348 }
349 return std::nullopt;
350 }
351
352 // Removes the token file; none is not an error.
353 static std::optional<BrokerError> unlink_token(const Descriptor& folder, const std::string& identity) {
354 if (::unlinkat(folder.get(), (identity + ".token").c_str(), 0) != 0 && errno != ENOENT) {
355 return token_store_error("token store: the token file could not be removed");
356 }
357 return std::nullopt;
358 }
359
360 std::string folder_;
361 std::chrono::milliseconds lock_wait_;
362};
363
364} // namespace network
365} // namespace algotradelib
366
367#endif
Either a value or a BrokerError.
Definition types.hpp:1058
Result< std::optional< StoredToken > > load(const std::string &identity) override
Reads the identity's token file.
std::optional< BrokerError > discard(const std::string &identity, const std::string &access_token) override
Removes the identity's token file if it holds the given token.
Result< std::unique_ptr< Lock > > lock(const std::string &identity) override
Takes the identity's lock, opening its lock file anew, so two callers in one process exclude each oth...
std::optional< BrokerError > publish(const std::string &identity, const StoredToken &token) override
Replaces the identity's token file, unless the stored token expires later.
std::optional< BrokerError > remove(const std::string &identity) override
Removes the identity's token file; its lock file stays.
FileTokenStore(std::string folder, std::chrono::milliseconds lock_wait=std::chrono::seconds(30))
Constructs a store; nothing is created or opened until the first call.
Held while one caller works on one identity; destroying it releases the lock.
Where blocking broker clients on one key share its access token, across threads and processes.
HTTP and WebSocket transport, OAuth tokens, and request pacing.
BrokerError token_store_error(std::string_view reason)
Returns a store's error: AUTHENTICATION, not sent to the broker, code token_store.
The library: broker-neutral types (core), and the modules below.
An access token as a TokenStore keeps it.
std::chrono::system_clock::time_point expires_at_
When it expires, as the client that obtained it computed it.