summaryrefslogtreecommitdiff
path: root/include/persistent_data.hpp
blob: d210800adbd5224c95a16dcb6ed36781c7db4b7b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright OpenBMC Authors
#pragma once

#include "event_service_store.hpp"
#include "logging.hpp"
#include "ossl_random.hpp"
#include "sessions.hpp"
// NOLINTNEXTLINE(misc-include-cleaner)
#include "utility.hpp"

#include <boost/beast/core/file_base.hpp>
#include <boost/beast/core/file_posix.hpp>
#include <boost/beast/http/fields.hpp>
#include <nlohmann/json.hpp>

#include <chrono>
#include <cstdint>
#include <filesystem>
#include <fstream>
#include <memory>
#include <optional>
#include <string>
#include <system_error>
#include <utility>

namespace persistent_data
{

class ConfigFile
{
    uint64_t jsonRevision = 1;

  public:
    // todo(ed) should read this from a fixed location somewhere, not CWD
    static constexpr const char* filename = "bmcweb_persistent_data.json";

    ConfigFile()
    {
        readData();
    }

    ~ConfigFile()
    {
        // Make sure we aren't writing stale sessions
        persistent_data::SessionStore::getInstance().applySessionTimeouts();
        if (persistent_data::SessionStore::getInstance().needsWrite())
        {
            writeData();
        }
    }

    ConfigFile(const ConfigFile&) = delete;
    ConfigFile(ConfigFile&&) = delete;
    ConfigFile& operator=(const ConfigFile&) = delete;
    ConfigFile& operator=(ConfigFile&&) = delete;

    // TODO(ed) this should really use protobuf, or some other serialization
    // library, but adding another dependency is somewhat outside the scope of
    // this application for the moment
    void readData()
    {
        std::ifstream persistentFile(filename);
        uint64_t fileRevision = 0;
        if (persistentFile.is_open())
        {
            // call with exceptions disabled
            auto data = nlohmann::json::parse(persistentFile, nullptr, false);
            if (data.is_discarded())
            {
                BMCWEB_LOG_ERROR("Error parsing persistent data in json file.");
            }
            else
            {
                const nlohmann::json::object_t* obj =
                    data.get_ptr<nlohmann::json::object_t*>();
                if (obj == nullptr)
                {
                    return;
                }
                for (const auto& item : *obj)
                {
                    if (item.first == "revision")
                    {
                        fileRevision = 0;

                        const uint64_t* uintPtr =
                            item.second.get_ptr<const uint64_t*>();
                        if (uintPtr == nullptr)
                        {
                            BMCWEB_LOG_ERROR("Failed to read revision flag");
                        }
                        else
                        {
                            fileRevision = *uintPtr;
                        }
                    }
                    else if (item.first == "system_uuid")
                    {
                        const std::string* jSystemUuid =
                            item.second.get_ptr<const std::string*>();
                        if (jSystemUuid != nullptr)
                        {
                            systemUuid = *jSystemUuid;
                        }
                    }
                    else if (item.first == "service_identification")
                    {
                        const std::string* jServiceIdentification =
                            item.second.get_ptr<const std::string*>();
                        if (jServiceIdentification != nullptr)
                        {
                            serviceIdentification = *jServiceIdentification;
                        }
                    }
                    else if (item.first == "auth_config")
                    {
                        const nlohmann::json::object_t* jObj =
                            item.second
                                .get_ptr<const nlohmann::json::object_t*>();
                        if (jObj == nullptr)
                        {
                            continue;
                        }
                        SessionStore::getInstance()
                            .getAuthMethodsConfig()
                            .fromJson(*jObj);
                    }
                    else if (item.first == "sessions")
                    {
                        for (const auto& elem : item.second)
                        {
                            const nlohmann::json::object_t* jObj =
                                elem.get_ptr<const nlohmann::json::object_t*>();
                            if (jObj == nullptr)
                            {
                                continue;
                            }
                            std::shared_ptr<UserSession> newSession =
                                UserSession::fromJson(*jObj);

                            if (newSession == nullptr)
                            {
                                BMCWEB_LOG_ERROR("Problem reading session "
                                                 "from persistent store");
                                continue;
                            }

                            BMCWEB_LOG_DEBUG("Restored session: {} {} {}",
                                             newSession->csrfToken,
                                             newSession->uniqueId,
                                             newSession->sessionToken);
                            SessionStore::getInstance().authTokens.emplace(
                                newSession->sessionToken, newSession);
                        }
                    }
                    else if (item.first == "timeout")
                    {
                        const int64_t* jTimeout =
                            item.second.get_ptr<const int64_t*>();
                        if (jTimeout == nullptr)
                        {
                            BMCWEB_LOG_DEBUG(
                                "Problem reading session timeout value");
                            continue;
                        }
                        std::chrono::seconds sessionTimeoutInseconds(*jTimeout);
                        BMCWEB_LOG_DEBUG("Restored Session Timeout: {}",
                                         sessionTimeoutInseconds.count());
                        SessionStore::getInstance().updateSessionTimeout(
                            sessionTimeoutInseconds);
                    }
                    else if (item.first == "eventservice_config")
                    {
                        const nlohmann::json::object_t* esobj =
                            item.second
                                .get_ptr<const nlohmann::json::object_t*>();
                        if (esobj == nullptr)
                        {
                            BMCWEB_LOG_DEBUG(
                                "Problem reading EventService value");
                            continue;
                        }

                        EventServiceStore::getInstance()
                            .getEventServiceConfig()
                            .fromJson(*esobj);
                    }
                    else if (item.first == "subscriptions")
                    {
                        for (const auto& elem : item.second)
                        {
                            const nlohmann::json::object_t* subobj =
                                elem.get_ptr<const nlohmann::json::object_t*>();
                            if (subobj == nullptr)
                            {
                                continue;
                            }

                            std::optional<UserSubscription> newSub =
                                UserSubscription::fromJson(*subobj);

                            if (!newSub)
                            {
                                BMCWEB_LOG_ERROR(
                                    "Problem reading subscription from persistent store");
                                continue;
                            }

                            std::string id = newSub->id;
                            BMCWEB_LOG_DEBUG("Restored subscription: {} {}", id,
                                             newSub->customText);

                            EventServiceStore::getInstance()
                                .subscriptionsConfigMap.emplace(
                                    id, std::make_shared<UserSubscription>(
                                            std::move(*newSub)));
                        }
                    }
                    else
                    {
                        // Do nothing in the case of extra fields.  We may have
                        // cases where fields are added in the future, and we
                        // want to at least attempt to gracefully support
                        // downgrades in that case, even if we don't officially
                        // support it
                    }
                }
            }
        }
        bool needWrite = false;

        if (systemUuid.empty())
        {
            systemUuid = bmcweb::getRandomUUID();
            needWrite = true;
        }
        if (fileRevision < jsonRevision)
        {
            needWrite = true;
        }
        // write revision changes or system uuid changes immediately
        if (needWrite)
        {
            writeData();
        }
    }

    void writeData()
    {
        std::filesystem::path path(filename);
        path = path.parent_path();
        if (!path.empty())
        {
            std::error_code ecDir;
            std::filesystem::create_directories(path, ecDir);
            if (ecDir)
            {
                BMCWEB_LOG_CRITICAL("Can't create persistent folders {}",
                                    ecDir.message());
                return;
            }
        }
        boost::beast::file_posix persistentFile;
        boost::system::error_code ec;
        persistentFile.open(filename, boost::beast::file_mode::write, ec);
        if (ec)
        {
            BMCWEB_LOG_CRITICAL("Unable to store persistent data to file {}",
                                ec.message());
            return;
        }

        // set the permission of the file to 640
        std::filesystem::perms permission =
            std::filesystem::perms::owner_read |
            std::filesystem::perms::owner_write |
            std::filesystem::perms::group_read;
        std::filesystem::permissions(filename, permission, ec);
        if (ec)
        {
            BMCWEB_LOG_CRITICAL("Failed to set filesystem permissions {}",
                                ec.message());
            return;
        }
        const AuthConfigMethods& c =
            SessionStore::getInstance().getAuthMethodsConfig();
        const auto& eventServiceConfig =
            EventServiceStore::getInstance().getEventServiceConfig();
        nlohmann::json::object_t data;
        nlohmann::json& authConfig = data["auth_config"];

        authConfig["XToken"] = c.xtoken;
        authConfig["Cookie"] = c.cookie;
        authConfig["SessionToken"] = c.sessionToken;
        authConfig["BasicAuth"] = c.basic;
        authConfig["TLS"] = c.tls;
        authConfig["TLSStrict"] = c.tlsStrict;
        authConfig["MTLSCommonNameParseMode"] =
            static_cast<int>(c.mTLSCommonNameParsingMode);

        nlohmann::json& eventserviceConfig = data["eventservice_config"];
        eventserviceConfig["ServiceEnabled"] = eventServiceConfig.enabled;
        eventserviceConfig["DeliveryRetryAttempts"] =
            eventServiceConfig.retryAttempts;
        eventserviceConfig["DeliveryRetryIntervalSeconds"] =
            eventServiceConfig.retryTimeoutInterval;

        data["system_uuid"] = systemUuid;
        data["service_identification"] = serviceIdentification;
        data["revision"] = jsonRevision;
        data["timeout"] = SessionStore::getInstance().getTimeoutInSeconds();

        nlohmann::json& sessions = data["sessions"];
        sessions = nlohmann::json::array();
        for (const auto& p : SessionStore::getInstance().authTokens)
        {
            if (p.second->sessionType != persistent_data::SessionType::Basic &&
                p.second->sessionType !=
                    persistent_data::SessionType::MutualTLS)
            {
                nlohmann::json::object_t session;
                session["unique_id"] = p.second->uniqueId;
                session["session_token"] = p.second->sessionToken;
                session["username"] = p.second->username;
                session["csrf_token"] = p.second->csrfToken;
                session["client_ip"] = p.second->clientIp;
                const std::optional<std::string>& clientId = p.second->clientId;
                if (clientId)
                {
                    session["client_id"] = *clientId;
                }
                sessions.emplace_back(std::move(session));
            }
        }
        nlohmann::json& subscriptions = data["subscriptions"];
        subscriptions = nlohmann::json::array();
        for (const auto& it :
             EventServiceStore::getInstance().subscriptionsConfigMap)
        {
            if (it.second == nullptr)
            {
                continue;
            }
            const UserSubscription& subValue = *it.second;
            if (subValue.subscriptionType == "SSE")
            {
                BMCWEB_LOG_DEBUG("The subscription type is SSE, so skipping.");
                continue;
            }
            nlohmann::json::object_t headers;
            for (const boost::beast::http::fields::value_type& header :
                 subValue.httpHeaders)
            {
                // Note, these are technically copies because nlohmann doesn't
                // support key lookup by std::string_view.  At least the
                // following code can use move
                // https://github.com/nlohmann/json/issues/1529
                std::string name(header.name_string());
                headers[std::move(name)] = header.value();
            }

            nlohmann::json::object_t subscription;

            subscription["Id"] = subValue.id;
            subscription["Context"] = subValue.customText;
            subscription["DeliveryRetryPolicy"] = subValue.retryPolicy;
            subscription["SendHeartbeat"] = subValue.sendHeartbeat;
            subscription["HeartbeatIntervalMinutes"] =
                subValue.hbIntervalMinutes;
            subscription["Destination"] = subValue.destinationUrl;
            subscription["EventFormatType"] = subValue.eventFormatType;
            subscription["HttpHeaders"] = std::move(headers);
            subscription["MessageIds"] = subValue.registryMsgIds;
            subscription["Protocol"] = subValue.protocol;
            subscription["RegistryPrefixes"] = subValue.registryPrefixes;
            subscription["OriginResources"] = subValue.originResources;
            subscription["ResourceTypes"] = subValue.resourceTypes;
            subscription["SubscriptionType"] = subValue.subscriptionType;
            subscription["MetricReportDefinitions"] =
                subValue.metricReportDefinitions;
            subscription["VerifyCertificate"] = subValue.verifyCertificate;

            subscriptions.emplace_back(std::move(subscription));
        }
        std::string out = nlohmann::json(data).dump(
            -1, ' ', true, nlohmann::json::error_handler_t::replace);
        persistentFile.write(out.data(), out.size(), ec);
        if (ec)
        {
            BMCWEB_LOG_ERROR("Failed to write file {}", ec.message());
        }
    }

    std::string systemUuid;
    std::string serviceIdentification;
};

inline ConfigFile& getConfig()
{
    static ConfigFile f;
    return f;
}

} // namespace persistent_data