diff --git a/include/app.h b/include/app.h index cafb1a3..4e23885 100644 --- a/include/app.h +++ b/include/app.h @@ -30,6 +30,8 @@ extern Settings settings; extern Sensors::Settings sensorsSettings[SENSORS_AMOUNT]; void initConfig(); void saveSettingsNow(); +const char* getApiToken(); +bool regenerateApiToken(); void requestSaveNetworkSettings(); void requestSaveSettings(); // Call after releasing lifecycle, MQTT queue and Sensors data locks. diff --git a/include/strings_shared.h b/include/strings_shared.h index 0bf6c2c..311c17c 100644 --- a/include/strings_shared.h +++ b/include/strings_shared.h @@ -37,6 +37,7 @@ inline const char S_ADDRESS[] = "address"; inline const char S_ANTI_STUCK_INTERVAL[] = "antistuck_interval"; inline const char S_ANTI_STUCK_TIME[] = "antistuck_time"; inline const char S_AP[] = "ap"; +inline const char S_API_TOKEN[] = "api_token"; inline const char S_APP_VERSION[] = "app_version"; inline const char S_AUTH[] = "auth"; inline const char S_AUTO_DIAG_RESET[] = "auto_diag_reset"; diff --git a/src/config.cpp b/src/config.cpp index 42c1284..98ced40 100644 --- a/src/config.cpp +++ b/src/config.cpp @@ -6,6 +6,8 @@ #include #endif #include +#include +#include #include #include #include @@ -166,6 +168,76 @@ void saveSettingsNow() { } } +// API token +// Kept in NVS rather than in Settings, so the settings file layout does not change. + +static constexpr char API_TOKEN_NAMESPACE[] = "otgw"; +static constexpr char API_TOKEN_KEY[] = "api_token"; +static constexpr size_t API_TOKEN_LENGTH = 32; +static char apiToken[API_TOKEN_LENGTH + 1] = ""; + +static bool isApiTokenValid(const char* token) { + if (strlen(token) != API_TOKEN_LENGTH) { + return false; + } + + for (size_t i = 0; i < API_TOKEN_LENGTH; i++) { + if (!isxdigit(static_cast(token[i]))) { + return false; + } + } + + return true; +} + +static bool storeApiToken(const char* token) { + nvs_handle_t handle; + if (nvs_open(API_TOKEN_NAMESPACE, NVS_READWRITE, &handle) != ESP_OK) { + return false; + } + + const bool stored = nvs_set_str(handle, API_TOKEN_KEY, token) == ESP_OK && nvs_commit(handle) == ESP_OK; + nvs_close(handle); + + if (stored) { + strcpy(apiToken, token); + } + + return stored; +} + +const char* getApiToken() { + return apiToken; +} + +bool regenerateApiToken() { + uint8_t bytes[API_TOKEN_LENGTH / 2]; + esp_fill_random(bytes, sizeof(bytes)); + + char token[API_TOKEN_LENGTH + 1]; + for (size_t i = 0; i < sizeof(bytes); i++) { + snprintf(token + i * 2, 3, "%02x", bytes[i]); + } + + return storeApiToken(token); +} + +static void loadApiToken() { + nvs_handle_t handle; + if (nvs_open(API_TOKEN_NAMESPACE, NVS_READONLY, &handle) == ESP_OK) { + size_t size = sizeof(apiToken); + if (nvs_get_str(handle, API_TOKEN_KEY, apiToken, &size) != ESP_OK) { + apiToken[0] = '\0'; + } + nvs_close(handle); + } + + if (!isApiTokenValid(apiToken) && !regenerateApiToken()) { + apiToken[0] = '\0'; + ESP_LOGW(L_SETTINGS, "Failed to create the API token"); + } +} + // Initialization static bool loadNetworkSettings() { bool loaded = false; @@ -282,6 +354,7 @@ void initConfig() { loadNetworkSettings(); loadSettings(); loadSensorsSettings(); + loadApiToken(); configureLoggingTask.forceRun(); appTaskManager.addTask(settingsSaveTask.setInterval(100)); @@ -832,6 +905,7 @@ JsonVariant toJson(const PortalSettings& src, JsonVariant dst) { portal[S_AUTH] = src.auth; portal[S_LOGIN] = src.login; portal[S_PASSWORD] = src.password; + portal[S_API_TOKEN] = apiToken; portal[S_MDNS] = src.mdns; return dst; @@ -878,6 +952,22 @@ SettingResult fromJson(JsonVariantConst src, PortalSettings& dst) { } } + // Accepted for restoring a backup; the portal shows the token read-only. + if (src[S_API_TOKEN].is()) { + const JsonString value = src[S_API_TOKEN].as(); + + if (strlen(value.c_str()) == value.size() && isApiTokenValid(value.c_str())) { + char token[API_TOKEN_LENGTH + 1]; + for (size_t i = 0; i < sizeof(token); i++) { + token[i] = static_cast(tolower(static_cast(value.c_str()[i]))); + } + + if (strcmp(token, apiToken) == 0 || storeApiToken(token)) { + result.accepted = true; + } + } + } + if (dst.auth && (!strlen(dst.login) || !strlen(dst.password))) { dst.auth = false; result.changed = true; diff --git a/src/portal.cpp b/src/portal.cpp index e69e34d..4927510 100644 --- a/src/portal.cpp +++ b/src/portal.cpp @@ -142,6 +142,44 @@ static AsyncMiddlewareFunction authMiddleware([](AsyncWebServerRequest *request, return request->requestAuthentication(AsyncAuthType::AUTH_BASIC, PROJECT_NAME, "Authentication failed"); }); +static constexpr char BEARER_PREFIX[] = "Bearer "; + +// Checks "Authorization: Bearer ". +static bool isApiTokenRequest(AsyncWebServerRequest* request) { + if (!request->hasHeader("Authorization")) { + return false; + } + + const String& header = request->getHeader("Authorization")->value(); + const size_t prefixLength = sizeof(BEARER_PREFIX) - 1; + const char* token = getApiToken(); + const size_t tokenLength = strlen(token); + if (!tokenLength || header.length() != prefixLength + tokenLength || !header.startsWith(BEARER_PREFIX)) { + return false; + } + + // Compare without an early exit. + uint8_t diff = 0; + for (size_t i = 0; i < tokenLength; i++) { + diff |= tolower(static_cast(header[prefixLength + i])) ^ token[i]; + } + + return diff == 0; +} + +// Setting a sensor value also accepts the API token, so a device needs no portal password. +static AsyncMiddlewareFunction sensorValueAuthMiddleware([](AsyncWebServerRequest *request, ArMiddlewareNext next) { + if (!isAuthenticationRequired(request) || isApiTokenRequest(request)) { + return next(); + } + + if (request->authenticate(settings.portal.login, settings.portal.password, PROJECT_NAME)) { + return next(); + } + + return request->requestAuthentication(AsyncAuthType::AUTH_BASIC, PROJECT_NAME, "Authentication failed"); +}); + static void initWebSerial() { // Register before System starts. Unbuffered WebSerial preserves newlines inside each record. webSerial = new WebSerial(); @@ -917,7 +955,7 @@ static void restApi() { request->send(response); }); sensorValueHandler.setMaxContentLength(64); - sensorValueHandler.addMiddleware(&authMiddleware); + sensorValueHandler.addMiddleware(&sensorValueAuthMiddleware); // Set sensor value (form) @@ -990,6 +1028,24 @@ static void restApi() { response->setLength(); response->setCode(201); request->send(response); + }).addMiddleware(&sensorValueAuthMiddleware); + + + // Regenerate the API token, revoking the old one + webServer->on(AsyncURIMatcher::exact("/api/portal/token/regenerate"), HTTP_POST, [](AsyncWebServerRequest *request) { + if (upgrading || restartTask.scheduled() || restartTask.active()) { + return request->send(503); + } + + if (!regenerateApiToken()) { + return request->send(500); + } + + auto *response = new AsyncJsonResponse(); + response->getRoot()[S_API_TOKEN] = getApiToken(); + response->setLength(); + response->setCode(201); + request->send(response); }).addMiddleware(&authMiddleware); diff --git a/src_data/locales/cn.json b/src_data/locales/cn.json index 4bed36d..d2284aa 100644 --- a/src_data/locales/cn.json +++ b/src_data/locales/cn.json @@ -366,7 +366,13 @@ "login": "登录", "password": "密码", "auth": "需身份验证", - "mdns": "使用 mDNS" + "mdns": "使用 mDNS", + "apiToken": { + "title": "API token", + "note": "Lets a device push sensor values without the portal password: Authorization: Bearer <token> for POST /api/sensor/value?id=N. Works only for this endpoint.", + "regenerate": "Regenerate token", + "regenerateConfirm": "The current token will stop working. Continue?" + } }, "system": { "unit": "单位", diff --git a/src_data/locales/en.json b/src_data/locales/en.json index 7a6ed44..aefbfb6 100644 --- a/src_data/locales/en.json +++ b/src_data/locales/en.json @@ -366,7 +366,13 @@ "login": "Login", "password": "Password", "auth": "Require authentication", - "mdns": "Use mDNS" + "mdns": "Use mDNS", + "apiToken": { + "title": "API token", + "note": "Lets a device push sensor values without the portal password: Authorization: Bearer <token> for POST /api/sensor/value?id=N. Works only for this endpoint.", + "regenerate": "Regenerate token", + "regenerateConfirm": "The current token will stop working. Continue?" + } }, "system": { "unit": "Unit system", diff --git a/src_data/locales/it.json b/src_data/locales/it.json index 1dd9ee1..fe6bc33 100644 --- a/src_data/locales/it.json +++ b/src_data/locales/it.json @@ -366,7 +366,13 @@ "login": "Login", "password": "Password", "auth": "Richiede autenticazione", - "mdns": "Usa mDNS" + "mdns": "Usa mDNS", + "apiToken": { + "title": "API token", + "note": "Lets a device push sensor values without the portal password: Authorization: Bearer <token> for POST /api/sensor/value?id=N. Works only for this endpoint.", + "regenerate": "Regenerate token", + "regenerateConfirm": "The current token will stop working. Continue?" + } }, "system": { "unit": "Unità di misura", diff --git a/src_data/locales/nl.json b/src_data/locales/nl.json index 2fb348b..16d42f9 100644 --- a/src_data/locales/nl.json +++ b/src_data/locales/nl.json @@ -366,7 +366,13 @@ "login": "Gebruikersnaam", "password": "Wachtwoord", "auth": "Authenticatie vereisen", - "mdns": "Gebruik mDNS" + "mdns": "Gebruik mDNS", + "apiToken": { + "title": "API token", + "note": "Lets a device push sensor values without the portal password: Authorization: Bearer <token> for POST /api/sensor/value?id=N. Works only for this endpoint.", + "regenerate": "Regenerate token", + "regenerateConfirm": "The current token will stop working. Continue?" + } }, "system": { "unit": "Eenheidssysteem", diff --git a/src_data/locales/ru.json b/src_data/locales/ru.json index 5dbede2..7b64da6 100644 --- a/src_data/locales/ru.json +++ b/src_data/locales/ru.json @@ -366,7 +366,13 @@ "login": "Логин", "password": "Пароль", "auth": "Требовать аутентификацию", - "mdns": "Использовать mDNS" + "mdns": "Использовать mDNS", + "apiToken": { + "title": "API-токен", + "note": "Позволяет устройству передавать значения датчиков без пароля портала: Authorization: Bearer <токен> для POST /api/sensor/value?id=N. Действует только для этого адреса.", + "regenerate": "Сгенерировать новый токен", + "regenerateConfirm": "Текущий токен перестанет работать. Продолжить?" + } }, "system": { "unit": "Система единиц", diff --git a/src_data/pages/settings.html b/src_data/pages/settings.html index ac77a70..525db7f 100644 --- a/src_data/pages/settings.html +++ b/src_data/pages/settings.html @@ -64,6 +64,13 @@ settings.portal.mdns + + +
@@ -1185,6 +1192,7 @@ setInputValue("[name='login']", data.portal.login, {}, form); setInputValue("[name='password']", data.portal.password, {}, form); setCheckboxValue("[name='mdns']", data.portal.mdns, form); + form.querySelector("#portal-api-token").value = data.portal.api_token ?? ''; } else if (section === 'opentherm') { setInputValue("[name='in_gpio']", data.opentherm.in_gpio < 255 ? data.opentherm.in_gpio : '', {}, form); @@ -1507,6 +1515,32 @@ }; setupSettingsForm('#portal-settings', ['login', 'password']); + + document.querySelector('#portal-api-token-regenerate').addEventListener('click', async (event) => { + if (!confirm(i18n("settings.portal.apiToken.regenerateConfirm"))) { + return; + } + + const button = event.currentTarget; + button.setAttribute('aria-busy', true); + try { + const response = await fetch("/api/portal/token/regenerate", { + method: "POST", + cache: "no-cache", + credentials: "include" + }); + + if (response.ok) { + document.querySelector('#portal-api-token').value = (await response.json()).api_token; + } + + } catch (error) { + console.log(error); + + } finally { + button.removeAttribute('aria-busy'); + } + }); setupSettingsForm('#system-settings', ['ntp.server', 'ntp.timezone']); setupSettingsForm('#heating-settings'); setupSettingsForm('#dhw-settings');