🔐 Removes auth from backend

This commit is contained in:
Rune Harlyk
2024-10-29 20:47:02 +01:00
parent 9923b66208
commit 1c6b9f79c5
41 changed files with 1389 additions and 2212 deletions
+5 -6
View File
@@ -2,19 +2,18 @@
build_flags =
-D USE_BATTERY=1
-D USE_NTP=1
-D USE_SECURITY=0
-D USE_SLEEP=0
-D USE_UPLOAD_FIRMWARE=0
-D USE_UPLOAD_FIRMWARE=1
-D USE_DOWNLOAD_FIRMWARE=0
-D USE_ANALYTICS=1
-D USE_MOTION=1
; Hardware specific
-D USE_IMU=1
-D USE_MAG=1
-D USE_BMP=1
-D USE_IMU=0
-D USE_MAG=0
-D USE_BMP=0
-D USE_GPS=0
-D USE_WS2812=1
-D USE_USS=0
-D USE_SERVO=1
-D USE_ADS1115=1
-D USE_ADS1115=0
@@ -1,139 +0,0 @@
/**
* ESP32 SvelteKit
*
* A simple, secure and extensible framework for IoT projects for ESP32 platforms
* with responsive Sveltekit front-end built with TailwindCSS and DaisyUI.
* https://github.com/theelims/ESP32-sveltekit
*
* Copyright (C) 2018 - 2023 rjwats
* Copyright (C) 2023 theelims
*
* All Rights Reserved. This software may be modified and distributed under
* the terms of the LGPL v3 license. See the LICENSE file for details.
**/
#include "ArduinoJsonJWT.h"
ArduinoJsonJWT::ArduinoJsonJWT(String secret) : _secret(secret) {}
void ArduinoJsonJWT::setSecret(String secret) { _secret = secret; }
String ArduinoJsonJWT::getSecret() { return _secret; }
/*
* ESP32 uses mbedtls,
*
* Both come with decent HMAC implmentations supporting sha256, as well as others.
*
* No need to pull in additional crypto libraries - lets use what we already have.
*/
String ArduinoJsonJWT::sign(String &payload) {
unsigned char hmacResult[32];
{
mbedtls_md_context_t ctx;
mbedtls_md_type_t md_type = MBEDTLS_MD_SHA256;
mbedtls_md_init(&ctx);
mbedtls_md_setup(&ctx, mbedtls_md_info_from_type(md_type), 1);
mbedtls_md_hmac_starts(&ctx, (unsigned char *)_secret.c_str(), _secret.length());
mbedtls_md_hmac_update(&ctx, (unsigned char *)payload.c_str(), payload.length());
mbedtls_md_hmac_finish(&ctx, hmacResult);
mbedtls_md_free(&ctx);
}
return encode((char *)hmacResult, 32);
}
String ArduinoJsonJWT::buildJWT(JsonObject &payload) {
// serialize, then encode payload
String jwt;
serializeJson(payload, jwt);
jwt = encode(jwt.c_str(), jwt.length());
// add the header to payload
jwt = JWT_HEADER + '.' + jwt;
// add signature
jwt += '.' + sign(jwt);
return jwt;
}
void ArduinoJsonJWT::parseJWT(String jwt, JsonDocument &jsonDocument) {
// clear json document before we begin, jsonDocument wil be null on failure
jsonDocument.clear();
// must have the correct header and delimiter
if (!jwt.startsWith(JWT_HEADER) || jwt.indexOf('.') != JWT_HEADER_SIZE) {
return;
}
// check there is a signature delimieter
int signatureDelimiterIndex = jwt.lastIndexOf('.');
if (signatureDelimiterIndex == JWT_HEADER_SIZE) {
return;
}
// check the signature is valid
String signature = jwt.substring(signatureDelimiterIndex + 1);
jwt = jwt.substring(0, signatureDelimiterIndex);
if (sign(jwt) != signature) {
return;
}
// decode payload
jwt = jwt.substring(JWT_HEADER_SIZE + 1);
jwt = decode(jwt);
// parse payload, clearing json document after failure
DeserializationError error = deserializeJson(jsonDocument, jwt);
if (error != DeserializationError::Ok || !jsonDocument.is<JsonObject>()) {
jsonDocument.clear();
}
}
String ArduinoJsonJWT::encode(const char *cstr, int inputLen) {
// prepare encoder
base64_encodestate _state;
base64_init_encodestate(&_state);
size_t encodedLength = base64_encode_expected_len(inputLen) + 1;
// prepare buffer of correct length, returning an empty string on failure
char *buffer = (char *)malloc(encodedLength * sizeof(char));
if (buffer == nullptr) {
return "";
}
// encode to buffer
int len = base64_encode_block(cstr, inputLen, &buffer[0], &_state);
len += base64_encode_blockend(&buffer[len], &_state);
buffer[len] = 0;
// convert to arduino string, freeing buffer
String value = String(buffer);
free(buffer);
buffer = nullptr;
// remove padding and convert to URL safe form
while (value.length() > 0 && value.charAt(value.length() - 1) == '=') {
value.remove(value.length() - 1);
}
value.replace('+', '-');
value.replace('/', '_');
// return as string
return value;
}
String ArduinoJsonJWT::decode(String value) {
// convert to standard base64
value.replace('-', '+');
value.replace('_', '/');
// prepare buffer of correct length
char buffer[base64_decode_expected_len(value.length()) + 1];
// decode
int len = base64_decode_chars(value.c_str(), value.length(), &buffer[0]);
buffer[len] = 0;
// return as string
return String(buffer);
}
@@ -1,46 +0,0 @@
#ifndef ArduinoJsonJWT_H
#define ArduinoJsonJWT_H
/**
* ESP32 SvelteKit
*
* A simple, secure and extensible framework for IoT projects for ESP32 platforms
* with responsive Sveltekit front-end built with TailwindCSS and DaisyUI.
* https://github.com/theelims/ESP32-sveltekit
*
* Copyright (C) 2018 - 2023 rjwats
* Copyright (C) 2023 theelims
*
* All Rights Reserved. This software may be modified and distributed under
* the terms of the LGPL v3 license. See the LICENSE file for details.
**/
#include <Arduino.h>
#include <ArduinoJson.h>
#include <libb64/cdecode.h>
#include <libb64/cencode.h>
#include <mbedtls/md.h>
class ArduinoJsonJWT {
private:
String _secret;
const String JWT_HEADER = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9";
const int JWT_HEADER_SIZE = JWT_HEADER.length();
String sign(String &value);
static String encode(const char *cstr, int len);
static String decode(String value);
public:
ArduinoJsonJWT(String secret);
void setSecret(String secret);
String getSecret();
String buildJWT(JsonObject &payload);
void parseJWT(String jwt, JsonDocument &jsonDocument);
};
#endif
@@ -1,51 +0,0 @@
/**
* ESP32 SvelteKit
*
* A simple, secure and extensible framework for IoT projects for ESP32 platforms
* with responsive Sveltekit front-end built with TailwindCSS and DaisyUI.
* https://github.com/theelims/ESP32-sveltekit
*
* Copyright (C) 2018 - 2023 rjwats
* Copyright (C) 2023 theelims
*
* All Rights Reserved. This software may be modified and distributed under
* the terms of the LGPL v3 license. See the LICENSE file for details.
**/
#include <AuthenticationService.h>
#if FT_ENABLED(USE_SECURITY)
AuthenticationService::AuthenticationService(PsychicHttpServer *server, SecurityManager *securityManager)
: _server(server), _securityManager(securityManager) {}
void AuthenticationService::begin() {
// Signs in a user if the username and password match. Provides a JWT to be used in the Authorization header in
// subsequent requests
_server->on(SIGN_IN_PATH, HTTP_POST, [this](PsychicRequest *request, JsonVariant &json) {
if (json.is<JsonObject>()) {
String username = json["username"];
String password = json["password"];
Authentication authentication = _securityManager->authenticate(username, password);
if (authentication.authenticated) {
PsychicJsonResponse response = PsychicJsonResponse(request, false);
JsonObject root = response.getRoot();
root["access_token"] = _securityManager->generateJWT(authentication.user);
return response.send();
}
}
return request->reply(401);
});
ESP_LOGV("AuthenticationService", "Registered POST endpoint: %s", SIGN_IN_PATH);
// Verifies that the request supplied a valid JWT
_server->on(VERIFY_AUTHORIZATION_PATH, HTTP_GET, [this](PsychicRequest *request) {
Authentication authentication = _securityManager->authenticateRequest(request);
return request->reply(authentication.authenticated ? 200 : 401);
});
ESP_LOGV("AuthenticationService", "Registered GET endpoint: %s", VERIFY_AUTHORIZATION_PATH);
}
#endif // end FT_ENABLED(USE_SECURITY)
@@ -1,39 +0,0 @@
#ifndef AuthenticationService_H_
#define AuthenticationService_H_
/**
* ESP32 SvelteKit
*
* A simple, secure and extensible framework for IoT projects for ESP32 platforms
* with responsive Sveltekit front-end built with TailwindCSS and DaisyUI.
* https://github.com/theelims/ESP32-sveltekit
*
* Copyright (C) 2018 - 2023 rjwats
* Copyright (C) 2023 theelims
*
* All Rights Reserved. This software may be modified and distributed under
* the terms of the LGPL v3 license. See the LICENSE file for details.
**/
#include <Features.h>
#include <PsychicHttp.h>
#include <SecurityManager.h>
#define VERIFY_AUTHORIZATION_PATH "/api/verifyAuthorization"
#define SIGN_IN_PATH "/api/signIn"
#if FT_ENABLED(USE_SECURITY)
class AuthenticationService {
public:
AuthenticationService(PsychicHttpServer *server, SecurityManager *securityManager);
void begin();
private:
SecurityManager *_securityManager;
PsychicHttpServer *_server;
};
#endif // end FT_ENABLED(USE_SECURITY)
#endif // end SecurityManager_h
+4 -8
View File
@@ -29,16 +29,12 @@ sensor_t *safe_sensor_get() {
void safe_sensor_return() { xSemaphoreGive(cameraMutex); }
CameraService::CameraService(PsychicHttpServer *server, TaskManager *taskManager, SecurityManager *securityManager)
: _server(server), _taskManager(taskManager), _securityManager(securityManager) {}
CameraService::CameraService(PsychicHttpServer *server, TaskManager *taskManager)
: _server(server), _taskManager(taskManager) {}
void CameraService::begin() {
InitializeCamera();
_server->on(STILL_SERVICE_PATH, HTTP_GET,
_securityManager->wrapRequest(std::bind(&CameraService::cameraStill, this, std::placeholders::_1),
AuthenticationPredicates::IS_AUTHENTICATED));
_server->on(STREAM_SERVICE_PATH, HTTP_GET,
_securityManager->wrapRequest(std::bind(&CameraService::cameraStream, this, std::placeholders::_1),
AuthenticationPredicates::IS_AUTHENTICATED));
_server->on(STILL_SERVICE_PATH, HTTP_GET, [this](PsychicRequest *request) { return cameraStill(request); });
_server->on(STREAM_SERVICE_PATH, HTTP_GET, [this](PsychicRequest *request) { return cameraStream(request); });
ESP_LOGV(TAG, "Registered GET endpoint: %s", STILL_SERVICE_PATH);
ESP_LOGV(TAG, "Registered GET endpoint: %s", STREAM_SERVICE_PATH);
+1 -3
View File
@@ -3,7 +3,6 @@
#include <ArduinoJson.h>
#include <PsychicHttp.h>
#include <SecurityManager.h>
#include <TaskManager.h>
#include <WiFi.h>
#include <async_worker.h>
@@ -28,14 +27,13 @@ void safe_sensor_return();
class CameraService {
public:
CameraService(PsychicHttpServer *server, TaskManager *taskManager, SecurityManager *securityManager);
CameraService(PsychicHttpServer *server, TaskManager *taskManager);
void begin();
private:
PsychicHttpServer *_server;
TaskManager *_taskManager;
SecurityManager *_securityManager;
esp_err_t cameraStill(PsychicRequest *request);
esp_err_t cameraStream(PsychicRequest *request);
esp_err_t InitializeCamera();
@@ -9,7 +9,6 @@ namespace Camera {
#include <HttpEndpoint.h>
#include <JsonUtils.h>
#include <PsychicHttp.h>
#include <SecurityManager.h>
#include <SettingValue.h>
#include <StatefulService.h>
#include <esp_camera.h>
@@ -121,11 +120,9 @@ class CameraSettings {
class CameraSettingsService : public StatefulService<CameraSettings> {
public:
CameraSettingsService(PsychicHttpServer *server, FS *fs, SecurityManager *securityManager, EventSocket *socket)
CameraSettingsService(PsychicHttpServer *server, FS *fs, EventSocket *socket)
: _server(server),
_securityManager(securityManager),
_httpEndpoint(CameraSettings::read, CameraSettings::update, this, server, CAMERA_SETTINGS_PATH,
securityManager, AuthenticationPredicates::IS_ADMIN),
_httpEndpoint(CameraSettings::read, CameraSettings::update, this, server, CAMERA_SETTINGS_PATH),
_eventEndpoint(CameraSettings::read, CameraSettings::update, this, socket, EVENT_CAMERA_SETTINGS),
_fsPersistence(CameraSettings::read, CameraSettings::update, this, fs, CAMERA_SETTINGS_FILE) {
addUpdateHandler([&](const String &originId) { updateCamera(); }, false);
@@ -199,7 +196,6 @@ class CameraSettingsService : public StatefulService<CameraSettings> {
private:
PsychicHttpServer *_server;
SecurityManager *_securityManager;
HttpEndpoint<CameraSettings> _httpEndpoint;
EventEndpoint<CameraSettings> _eventEndpoint;
FSPersistence<CameraSettings> _fsPersistence;
@@ -90,15 +90,13 @@ void updateTask(void *param) {
vTaskDelete(NULL);
}
DownloadFirmwareService::DownloadFirmwareService(PsychicHttpServer *server, SecurityManager *securityManager,
EventSocket *socket, TaskManager *taskManager)
: _server(server), _securityManager(securityManager), _socket(socket), _taskManager(taskManager) {}
DownloadFirmwareService::DownloadFirmwareService(PsychicHttpServer *server, EventSocket *socket,
TaskManager *taskManager)
: _server(server), _socket(socket), _taskManager(taskManager) {}
void DownloadFirmwareService::begin() {
_server->on(GITHUB_FIRMWARE_PATH, HTTP_POST,
_securityManager->wrapCallback(std::bind(&DownloadFirmwareService::downloadUpdate, this,
std::placeholders::_1, std::placeholders::_2),
AuthenticationPredicates::IS_ADMIN));
[this](PsychicRequest *request, JsonVariant &json) { return downloadUpdate(request, json); });
ESP_LOGV("DownloadFirmwareService", "Registered POST endpoint: %s", GITHUB_FIRMWARE_PATH);
}
@@ -20,7 +20,6 @@
#include <ArduinoJson.h>
#include <EventSocket.h>
#include <PsychicHttp.h>
#include <SecurityManager.h>
#include <HTTPClient.h>
#include <HTTPUpdate.h>
@@ -33,13 +32,11 @@
class DownloadFirmwareService {
public:
DownloadFirmwareService(PsychicHttpServer *server, SecurityManager *securityManager, EventSocket *socket,
TaskManager *taskManager);
DownloadFirmwareService(PsychicHttpServer *server, EventSocket *socket, TaskManager *taskManager);
void begin();
private:
SecurityManager *_securityManager;
PsychicHttpServer *_server;
EventSocket *_socket;
TaskManager *_taskManager;
+15 -23
View File
@@ -20,23 +20,19 @@ ESP32SvelteKit::ESP32SvelteKit(PsychicHttpServer *server, unsigned int numberEnd
_numberEndpoints(numberEndpoints),
_taskManager(),
_featureService(server),
_securitySettingsService(server, &ESPFS),
_socket(server, &_securitySettingsService, AuthenticationPredicates::IS_AUTHENTICATED),
_socket(server),
#if FT_ENABLED(USE_NTP)
_ntpSettingsService(server, &ESPFS, &_securitySettingsService),
_ntpStatus(server, &_securitySettingsService),
_ntpSettingsService(server, &ESPFS),
_ntpStatus(server),
#endif
#if FT_ENABLED(USE_UPLOAD_FIRMWARE)
_uploadFirmwareService(server, &_securitySettingsService),
_uploadFirmwareService(server),
#endif
#if FT_ENABLED(USE_DOWNLOAD_FIRMWARE)
_downloadFirmwareService(server, &_securitySettingsService, &_socket, &_taskManager),
#endif
#if FT_ENABLED(USE_SECURITY)
_authenticationService(server, &_securitySettingsService),
_downloadFirmwareService(server, &_socket, &_taskManager),
#endif
#if FT_ENABLED(USE_SLEEP)
_sleepService(server, &_securitySettingsService),
_sleepService(server),
#endif
#if FT_ENABLED(USE_BATTERY)
_batteryService(&_peripherals, &_socket),
@@ -45,21 +41,21 @@ ESP32SvelteKit::ESP32SvelteKit(PsychicHttpServer *server, unsigned int numberEnd
_analyticsService(&_socket, &_taskManager),
#endif
#if FT_ENABLED(USE_CAMERA)
_cameraService(server, &_taskManager, &_securitySettingsService),
_cameraSettingsService(server, &ESPFS, &_securitySettingsService, &_socket),
_cameraService(server, &_taskManager),
_cameraSettingsService(server, &ESPFS, &_socket),
#endif
_restartService(server, &_securitySettingsService),
_factoryResetService(server, &ESPFS, &_securitySettingsService),
_systemStatus(server, &_securitySettingsService),
_fileExplorer(server, &_securitySettingsService),
_servoController(server, &ESPFS, &_securitySettingsService, &_peripherals, &_socket),
_restartService(server),
_factoryResetService(server, &ESPFS),
_systemStatus(server),
_fileExplorer(server),
_servoController(server, &ESPFS, &_peripherals, &_socket),
#if FT_ENABLED(USE_MOTION)
_motionService(_server, &_socket, &_securitySettingsService, &_servoController, &_taskManager),
_motionService(_server, &_socket, &_servoController, &_taskManager),
#endif
#if FT_ENABLED(USE_WS2812)
_ledService(&_taskManager),
#endif
_peripherals(server, &ESPFS, &_securitySettingsService, &_socket) {
_peripherals(server, &ESPFS, &_socket) {
}
void ESP32SvelteKit::begin() {
@@ -188,10 +184,6 @@ void ESP32SvelteKit::startServices() {
_ntpSettingsService.begin();
_ntpStatus.begin();
#endif
#if FT_ENABLED(USE_SECURITY)
_authenticationService.begin();
_securitySettingsService.begin();
#endif
#if FT_ENABLED(USE_ANALYTICS)
_analyticsService.begin();
#endif
@@ -19,7 +19,6 @@
#include <Arduino.h>
#include <AnalyticsService.h>
#include <AuthenticationService.h>
#include <BatteryService.h>
#include <FileExplorerService.h>
#include <DownloadFirmwareService.h>
@@ -38,7 +37,6 @@
#include <NTPStatus.h>
#include <PsychicHttp.h>
#include <RestartService.h>
#include <SecuritySettingsService.h>
#include <SleepService.h>
#include <SystemStatus.h>
#include <TaskManager.h>
@@ -78,8 +76,6 @@ class ESP32SvelteKit {
PsychicHttpServer *getServer() { return _server; }
SecurityManager *getSecurityManager() { return &_securitySettingsService; }
EventSocket *getSocket() { return &_socket; }
#if FT_ENABLED(USE_NTP)
@@ -127,7 +123,6 @@ class ESP32SvelteKit {
PsychicHttpServer *_server;
unsigned int _numberEndpoints;
FeaturesService _featureService;
SecuritySettingsService _securitySettingsService;
WiFiService _wifiService;
APService _apService;
EventSocket _socket;
@@ -141,9 +136,6 @@ class ESP32SvelteKit {
#if FT_ENABLED(USE_DOWNLOAD_FIRMWARE)
DownloadFirmwareService _downloadFirmwareService;
#endif
#if FT_ENABLED(USE_SECURITY)
AuthenticationService _authenticationService;
#endif
#if FT_ENABLED(USE_SLEEP)
SleepService _sleepService;
#endif
-1
View File
@@ -9,6 +9,5 @@
#define FS_CONFIG_DIRECTORY "/config"
#define NTP_SETTINGS_FILE "/config/ntpSettings.json"
#define DEVICE_CONFIG_FILE "/config/peripheral.json"
#define SECURITY_SETTINGS_FILE "/config/securitySettings.json"
#define WIFI_SETTINGS_FILE "/config/wifiSettings.json"
#define SERVO_SETTINGS_FILE "/config/servoSettings.json"
@@ -17,7 +17,6 @@
#include <EventSocket.h>
#include <PsychicHttp.h>
#include <SecurityManager.h>
#include <StatefulService.h>
template <class T>
+1 -4
View File
@@ -42,12 +42,9 @@ const char *getEventPayload(const char *msg) {
return payload;
}
EventSocket::EventSocket(PsychicHttpServer *server, SecurityManager *securityManager,
AuthenticationPredicate authenticationPredicate)
: _server(server), _securityManager(securityManager), _authenticationPredicate(authenticationPredicate) {}
EventSocket::EventSocket(PsychicHttpServer *server) : _server(server) {}
void EventSocket::begin() {
_socket.setFilter(_securityManager->filterRequest(_authenticationPredicate));
_socket.onOpen((std::bind(&EventSocket::onWSOpen, this, std::placeholders::_1)));
_socket.onClose(std::bind(&EventSocket::onWSClose, this, std::placeholders::_1));
_socket.onFrame(std::bind(&EventSocket::onFrame, this, std::placeholders::_1, std::placeholders::_2));
+1 -5
View File
@@ -2,7 +2,6 @@
#define Socket_h
#include <PsychicHttp.h>
#include <SecurityManager.h>
#include <StatefulService.h>
#include <list>
#include <map>
@@ -17,8 +16,7 @@ typedef std::function<void(const String &originId, bool sync)> SubscribeCallback
class EventSocket {
public:
EventSocket(PsychicHttpServer *server, SecurityManager *_securityManager,
AuthenticationPredicate authenticationPredicate = AuthenticationPredicates::IS_AUTHENTICATED);
EventSocket(PsychicHttpServer *server);
void begin();
@@ -35,8 +33,6 @@ class EventSocket {
private:
PsychicHttpServer *_server;
PsychicWebSocketHandler _socket;
SecurityManager *_securityManager;
AuthenticationPredicate _authenticationPredicate;
std::map<String, std::list<int>> client_subscriptions;
std::map<String, std::list<EventCallback>> event_callbacks;
@@ -14,14 +14,11 @@
#include <FactoryResetService.h>
FactoryResetService::FactoryResetService(PsychicHttpServer *server, FS *fs, SecurityManager *securityManager)
: _server(server), fs(fs), _securityManager(securityManager) {}
FactoryResetService::FactoryResetService(PsychicHttpServer *server, FS *fs) : _server(server), fs(fs) {}
void FactoryResetService::begin() {
_server->on(
FACTORY_RESET_SERVICE_PATH, HTTP_POST,
_securityManager->wrapRequest(std::bind(&FactoryResetService::handleRequest, this, std::placeholders::_1),
AuthenticationPredicates::IS_ADMIN));
_server->on(FACTORY_RESET_SERVICE_PATH, HTTP_POST,
[this](PsychicRequest *request) { return handleRequest(request); });
ESP_LOGV("FactoryResetService", "Registered POST endpoint: %s", FACTORY_RESET_SERVICE_PATH);
}
@@ -18,7 +18,6 @@
#include <WiFi.h>
#include <PsychicHttp.h>
#include <SecurityManager.h>
#include <RestartService.h>
#include <FS.h>
#include <ESPFS.h>
@@ -29,14 +28,13 @@ class FactoryResetService {
FS *fs;
public:
FactoryResetService(PsychicHttpServer *server, FS *fs, SecurityManager *securityManager);
FactoryResetService(PsychicHttpServer *server, FS *fs);
void begin();
void factoryReset();
private:
PsychicHttpServer *_server;
SecurityManager *_securityManager;
esp_err_t handleRequest(PsychicRequest *request);
};
-5
View File
@@ -17,11 +17,6 @@
#define FT_ENABLED(feature) feature
// security feature on by default
#ifndef USE_SECURITY
#define USE_SECURITY 1
#endif
// ntp feature on by default
#ifndef USE_NTP
#define USE_NTP 1
@@ -22,7 +22,6 @@ void FeaturesService::begin() {
PsychicJsonResponse response = PsychicJsonResponse(request, false);
JsonObject root = response.getRoot();
root["security"] = USE_SECURITY;
root["ntp"] = USE_NTP;
root["upload_firmware"] = USE_UPLOAD_FIRMWARE;
root["download_firmware"] = USE_DOWNLOAD_FIRMWARE;
@@ -3,31 +3,24 @@
#include <ESPFS.h>
#include <PsychicHttp.h>
#include <SecurityManager.h>
#define FILE_EXPLORER_SERVICE_PATH "/api/files"
#define FILE_EXPLORER_DELETE_SERVICE_PATH "/api/files/delete"
class FileExplorer {
public:
FileExplorer(PsychicHttpServer *server, SecurityManager *securityManager)
: _server(server), _securityManager(securityManager) {}
FileExplorer(PsychicHttpServer *server) : _server(server) {}
void begin() {
_server->on(FILE_EXPLORER_SERVICE_PATH, HTTP_GET,
_securityManager->wrapRequest(std::bind(&FileExplorer::explore, this, std::placeholders::_1),
AuthenticationPredicates::IS_AUTHENTICATED));
_server->on(FILE_EXPLORER_SERVICE_PATH, HTTP_GET, [this](PsychicRequest *request) { return explore(request); });
_server->on(FILE_EXPLORER_DELETE_SERVICE_PATH, HTTP_POST,
_securityManager->wrapCallback(
std::bind(&FileExplorer::deleteFile, this, std::placeholders::_1, std::placeholders::_2),
AuthenticationPredicates::IS_AUTHENTICATED));
[this](PsychicRequest *request, JsonVariant &json) { return deleteFile(request, json); });
ESP_LOGV("APStatus", "Registered GET endpoint: %s", FILE_EXPLORER_SERVICE_PATH);
}
private:
PsychicHttpServer *_server;
SecurityManager *_securityManager;
esp_err_t explore(PsychicRequest *request) {
return request->reply(200, "application/json", listFiles("/").c_str());
+26 -41
View File
@@ -2,7 +2,6 @@
#define HttpEndpoint_h
#include <PsychicHttp.h>
#include <SecurityManager.h>
#include <StatefulService.h>
#include <functional>
@@ -17,71 +16,57 @@ class HttpEndpoint {
JsonStateUpdater<T> _stateUpdater;
StatefulService<T> *_statefulService;
size_t _bufferSize;
SecurityManager *_securityManager;
AuthenticationPredicate _authenticationPredicate;
PsychicHttpServer *_server;
const char *_servicePath;
public:
HttpEndpoint(JsonStateReader<T> stateReader, JsonStateUpdater<T> stateUpdater, StatefulService<T> *statefulService,
PsychicHttpServer *server, const char *servicePath, SecurityManager *securityManager,
AuthenticationPredicate authenticationPredicate = AuthenticationPredicates::IS_ADMIN)
PsychicHttpServer *server, const char *servicePath)
: _stateReader(stateReader),
_stateUpdater(stateUpdater),
_statefulService(statefulService),
_server(server),
_servicePath(servicePath),
_securityManager(securityManager),
_authenticationPredicate(authenticationPredicate) {}
_servicePath(servicePath) {}
// register the web server on() endpoints
void begin() {
// OPTIONS (for CORS preflight)
#ifdef ENABLE_CORS
_server->on(_servicePath, HTTP_OPTIONS,
_securityManager->wrapRequest([this](PsychicRequest *request) { return request->reply(200); },
AuthenticationPredicates::IS_AUTHENTICATED));
_server->on(_servicePath, HTTP_OPTIONS, [this](PsychicRequest *request) { return request->reply(200); });
#endif
// GET
_server->on(_servicePath, HTTP_GET,
_securityManager->wrapRequest(
[this](PsychicRequest *request) {
PsychicJsonResponse response = PsychicJsonResponse(request, false);
JsonObject jsonObject = response.getRoot();
_statefulService->read(jsonObject, _stateReader);
return response.send();
},
_authenticationPredicate));
_server->on(_servicePath, HTTP_GET, [this](PsychicRequest *request) {
PsychicJsonResponse response = PsychicJsonResponse(request, false);
JsonObject jsonObject = response.getRoot();
_statefulService->read(jsonObject, _stateReader);
return response.send();
});
ESP_LOGV("HttpEndpoint", "Registered GET endpoint: %s", _servicePath);
// POST
_server->on(_servicePath, HTTP_POST,
_securityManager->wrapCallback(
[this](PsychicRequest *request, JsonVariant &json) {
if (!json.is<JsonObject>()) {
return request->reply(400);
}
_server->on(_servicePath, HTTP_POST, [this](PsychicRequest *request, JsonVariant &json) {
if (!json.is<JsonObject>()) {
return request->reply(400);
}
JsonObject jsonObject = json.as<JsonObject>();
StateUpdateResult outcome =
_statefulService->updateWithoutPropagation(jsonObject, _stateUpdater);
JsonObject jsonObject = json.as<JsonObject>();
StateUpdateResult outcome = _statefulService->updateWithoutPropagation(jsonObject, _stateUpdater);
if (outcome == StateUpdateResult::ERROR) {
return request->reply(400);
} else if ((outcome == StateUpdateResult::CHANGED)) {
// persist the changes to the FS
_statefulService->callUpdateHandlers(HTTP_ENDPOINT_ORIGIN_ID);
}
if (outcome == StateUpdateResult::ERROR) {
return request->reply(400);
} else if ((outcome == StateUpdateResult::CHANGED)) {
// persist the changes to the FS
_statefulService->callUpdateHandlers(HTTP_ENDPOINT_ORIGIN_ID);
}
PsychicJsonResponse response = PsychicJsonResponse(request, false);
jsonObject = response.getRoot();
PsychicJsonResponse response = PsychicJsonResponse(request, false);
jsonObject = response.getRoot();
_statefulService->read(jsonObject, _stateReader);
_statefulService->read(jsonObject, _stateReader);
return response.send();
},
_authenticationPredicate));
return response.send();
});
ESP_LOGV("HttpEndpoint", "Registered POST endpoint: %s", _servicePath);
}
+3 -8
View File
@@ -20,13 +20,9 @@ enum class MOTION_STATE { DEACTIVATED, IDLE, CALIBRATION, REST, STAND, CRAWL, WA
class MotionService {
public:
MotionService(PsychicHttpServer *server, EventSocket *socket, SecurityManager *securityManager,
ServoController *servoController, TaskManager *taskManager)
: _server(server),
_socket(socket),
_securityManager(securityManager),
_servoController(servoController),
_taskManager(taskManager) {}
MotionService(PsychicHttpServer *server, EventSocket *socket, ServoController *servoController,
TaskManager *taskManager)
: _server(server), _socket(socket), _servoController(servoController), _taskManager(taskManager) {}
void begin() {
_socket->onEvent(INPUT_EVENT, [&](JsonObject &root, int originId) { handleInput(root, originId); });
@@ -151,7 +147,6 @@ class MotionService {
private:
PsychicHttpServer *_server;
EventSocket *_socket;
SecurityManager *_securityManager;
TaskManager *_taskManager;
ServoController *_servoController;
Kinematics kinematics;
@@ -14,10 +14,9 @@
#include <NTPSettingsService.h>
NTPSettingsService::NTPSettingsService(PsychicHttpServer *server, FS *fs, SecurityManager *securityManager)
NTPSettingsService::NTPSettingsService(PsychicHttpServer *server, FS *fs)
: _server(server),
_securityManager(securityManager),
_httpEndpoint(NTPSettings::read, NTPSettings::update, this, server, NTP_SETTINGS_SERVICE_PATH, securityManager),
_httpEndpoint(NTPSettings::read, NTPSettings::update, this, server, NTP_SETTINGS_SERVICE_PATH),
_fsPersistence(NTPSettings::read, NTPSettings::update, this, fs, NTP_SETTINGS_FILE) {
addUpdateHandler([&](const String &originId) { configureNTP(); }, false);
}
@@ -31,9 +30,7 @@ void NTPSettingsService::begin() {
_httpEndpoint.begin();
_server->on(TIME_PATH, HTTP_POST,
_securityManager->wrapCallback(
std::bind(&NTPSettingsService::configureTime, this, std::placeholders::_1, std::placeholders::_2),
AuthenticationPredicates::IS_ADMIN));
[this](PsychicRequest *request, JsonVariant &json) { return configureTime(request, json); });
ESP_LOGV("NTPSettingsService", "Registered POST endpoint: %s", TIME_PATH);
@@ -68,13 +68,12 @@ class NTPSettings {
class NTPSettingsService : public StatefulService<NTPSettings> {
public:
NTPSettingsService(PsychicHttpServer *server, FS *fs, SecurityManager *securityManager);
NTPSettingsService(PsychicHttpServer *server, FS *fs);
void begin();
private:
PsychicHttpServer *_server;
SecurityManager *_securityManager;
HttpEndpoint<NTPSettings> _httpEndpoint;
FSPersistence<NTPSettings> _fsPersistence;
+2 -5
View File
@@ -14,13 +14,10 @@
#include <NTPStatus.h>
NTPStatus::NTPStatus(PsychicHttpServer *server, SecurityManager *securityManager)
: _server(server), _securityManager(securityManager) {}
NTPStatus::NTPStatus(PsychicHttpServer *server) : _server(server) {}
void NTPStatus::begin() {
_server->on(NTP_STATUS_SERVICE_PATH, HTTP_GET,
_securityManager->wrapRequest(std::bind(&NTPStatus::ntpStatus, this, std::placeholders::_1),
AuthenticationPredicates::IS_AUTHENTICATED));
_server->on(NTP_STATUS_SERVICE_PATH, HTTP_GET, [this](PsychicRequest *request) { return ntpStatus(request); });
ESP_LOGV("NTPStatus", "Registered GET endpoint: %s", NTP_STATUS_SERVICE_PATH);
}
+1 -3
View File
@@ -21,19 +21,17 @@
#include <ArduinoJson.h>
#include <PsychicHttp.h>
#include <SecurityManager.h>
#define NTP_STATUS_SERVICE_PATH "/api/ntpStatus"
class NTPStatus {
public:
NTPStatus(PsychicHttpServer *server, SecurityManager *securityManager);
NTPStatus(PsychicHttpServer *server);
void begin();
private:
PsychicHttpServer *_server;
SecurityManager *_securityManager;
esp_err_t ntpStatus(PsychicRequest *request);
};
+3 -5
View File
@@ -4,11 +4,11 @@
#include <EventEndpoint.h>
#include <FSPersistence.h>
#include <HttpEndpoint.h>
#include <SecurityManager.h>
#include <StatefulService.h>
#include <MathUtils.h>
#include <Timing.h>
#include <ESPFS.h>
#include <Features.h>
#include <list>
#include <SPI.h>
@@ -101,12 +101,11 @@ class PeripheralsConfiguration {
class Peripherals : public StatefulService<PeripheralsConfiguration> {
public:
Peripherals(PsychicHttpServer *server, FS *fs, SecurityManager *securityManager, EventSocket *socket)
Peripherals(PsychicHttpServer *server, FS *fs, EventSocket *socket)
: _server(server),
_socket(socket),
_securityManager(securityManager),
_httpEndpoint(PeripheralsConfiguration::read, PeripheralsConfiguration::update, this, server,
CONFIGURATION_SETTINGS_PATH, securityManager, AuthenticationPredicates::IS_ADMIN),
CONFIGURATION_SETTINGS_PATH),
_eventEndpoint(PeripheralsConfiguration::read, PeripheralsConfiguration::update, this, socket,
EVENT_CONFIGURATION_SETTINGS),
#if FT_ENABLED(USE_MAG)
@@ -446,7 +445,6 @@ class Peripherals : public StatefulService<PeripheralsConfiguration> {
private:
PsychicHttpServer *_server;
EventSocket *_socket;
SecurityManager *_securityManager;
HttpEndpoint<PeripheralsConfiguration> _httpEndpoint;
EventEndpoint<PeripheralsConfiguration> _eventEndpoint;
FSPersistence<PeripheralsConfiguration> _fsPersistence;
+2 -5
View File
@@ -14,13 +14,10 @@
#include <RestartService.h>
RestartService::RestartService(PsychicHttpServer *server, SecurityManager *securityManager)
: _server(server), _securityManager(securityManager) {}
RestartService::RestartService(PsychicHttpServer *server) : _server(server) {}
void RestartService::begin() {
_server->on(RESTART_SERVICE_PATH, HTTP_POST,
_securityManager->wrapRequest(std::bind(&RestartService::restart, this, std::placeholders::_1),
AuthenticationPredicates::IS_ADMIN));
_server->on(RESTART_SERVICE_PATH, HTTP_POST, [this](PsychicRequest *request) { return restart(request); });
ESP_LOGV("RestartService", "Registered POST endpoint: %s", RESTART_SERVICE_PATH);
}
+1 -3
View File
@@ -18,13 +18,12 @@
#include <WiFi.h>
#include <PsychicHttp.h>
#include <SecurityManager.h>
#define RESTART_SERVICE_PATH "/api/restart"
class RestartService {
public:
RestartService(PsychicHttpServer *server, SecurityManager *securityManager);
RestartService(PsychicHttpServer *server);
void begin();
@@ -36,7 +35,6 @@ class RestartService {
private:
PsychicHttpServer *_server;
SecurityManager *_securityManager;
esp_err_t restart(PsychicRequest *request);
};
-101
View File
@@ -1,101 +0,0 @@
#ifndef SecurityManager_h
#define SecurityManager_h
/**
* ESP32 SvelteKit
*
* A simple, secure and extensible framework for IoT projects for ESP32 platforms
* with responsive Sveltekit front-end built with TailwindCSS and DaisyUI.
* https://github.com/theelims/ESP32-sveltekit
*
* Copyright (C) 2018 - 2023 rjwats
* Copyright (C) 2023 theelims
*
* All Rights Reserved. This software may be modified and distributed under
* the terms of the LGPL v3 license. See the LICENSE file for details.
**/
#include <Features.h>
#include <ArduinoJsonJWT.h>
#include <PsychicHttp.h>
#include <list>
#define ACCESS_TOKEN_PARAMATER "access_token"
#define AUTHORIZATION_HEADER "Authorization"
#define AUTHORIZATION_HEADER_PREFIX "Bearer "
#define AUTHORIZATION_HEADER_PREFIX_LEN 7
#define MAX_JWT_SIZE 128
class User {
public:
String username;
String password;
bool admin;
public:
User(String username, String password, bool admin) : username(username), password(password), admin(admin) {}
};
class Authentication {
public:
User *user;
boolean authenticated;
public:
Authentication(User &user) : user(new User(user)), authenticated(true) {}
Authentication() : user(nullptr), authenticated(false) {}
~Authentication() { delete (user); }
};
typedef std::function<boolean(Authentication &authentication)> AuthenticationPredicate;
class AuthenticationPredicates {
public:
static bool NONE_REQUIRED(Authentication &authentication) { return true; };
static bool IS_AUTHENTICATED(Authentication &authentication) { return authentication.authenticated; };
static bool IS_ADMIN(Authentication &authentication) {
return authentication.authenticated && authentication.user->admin;
};
};
class SecurityManager {
public:
#if FT_ENABLED(USE_SECURITY)
/*
* Authenticate, returning the user if found
*/
virtual Authentication authenticate(const String &username, const String &password) = 0;
/*
* Generate a JWT for the user provided
*/
virtual String generateJWT(User *user) = 0;
#endif
/*
* Check the request header for the Authorization token
*/
virtual Authentication authenticateRequest(PsychicRequest *request) = 0;
/**
* Filter a request with the provided predicate, only returning true if the predicate matches.
*/
virtual PsychicRequestFilterFunction filterRequest(AuthenticationPredicate predicate) = 0;
/**
* Wrap the provided request to provide validation against an AuthenticationPredicate.
*/
virtual PsychicHttpRequestCallback wrapRequest(PsychicHttpRequestCallback onRequest,
AuthenticationPredicate predicate) = 0;
/**
* Wrap the provided json request callback to provide validation against an AuthenticationPredicate.
*/
virtual PsychicJsonRequestCallback wrapCallback(PsychicJsonRequestCallback onRequest,
AuthenticationPredicate predicate) = 0;
};
#endif // end SecurityManager_h
@@ -1,188 +0,0 @@
/**
* ESP32 SvelteKit
*
* A simple, secure and extensible framework for IoT projects for ESP32 platforms
* with responsive Sveltekit front-end built with TailwindCSS and DaisyUI.
* https://github.com/theelims/ESP32-sveltekit
*
* Copyright (C) 2018 - 2023 rjwats
* Copyright (C) 2023 theelims
*
* All Rights Reserved. This software may be modified and distributed under
* the terms of the LGPL v3 license. See the LICENSE file for details.
**/
#include <SecuritySettingsService.h>
#if FT_ENABLED(USE_SECURITY)
SecuritySettingsService::SecuritySettingsService(PsychicHttpServer *server, FS *fs)
: _server(server),
_httpEndpoint(SecuritySettings::read, SecuritySettings::update, this, server, SECURITY_SETTINGS_PATH, this),
_fsPersistence(SecuritySettings::read, SecuritySettings::update, this, fs, SECURITY_SETTINGS_FILE),
_jwtHandler(FACTORY_JWT_SECRET) {
addUpdateHandler([&](const String &originId) { configureJWTHandler(); }, false);
}
void SecuritySettingsService::begin() {
_server->on(GENERATE_TOKEN_PATH, HTTP_GET,
wrapRequest(std::bind(&SecuritySettingsService::generateToken, this, std::placeholders::_1),
AuthenticationPredicates::IS_ADMIN));
ESP_LOGV("SecuritySettingsService", "Registered GET endpoint: %s", GENERATE_TOKEN_PATH);
_httpEndpoint.begin();
_fsPersistence.readFromFS();
configureJWTHandler();
}
Authentication SecuritySettingsService::authenticateRequest(PsychicRequest *request) {
// Load the parameters from the request, as they are only loaded later with the regular handler
if (request->hasHeader(AUTHORIZATION_HEADER)) {
auto value = request->header(AUTHORIZATION_HEADER);
// ESP_LOGV("SecuritySettingsService", "Authorization header: %s", value.c_str());
if (value.startsWith(AUTHORIZATION_HEADER_PREFIX)) {
value = value.substring(AUTHORIZATION_HEADER_PREFIX_LEN);
return authenticateJWT(value);
}
} else if (request->hasParam(ACCESS_TOKEN_PARAMATER)) {
String value = request->getParam(ACCESS_TOKEN_PARAMATER)->value();
// ESP_LOGV("SecuritySettingsService", "Access token parameter: %s", value.c_str());
return authenticateJWT(value);
}
return Authentication();
}
void SecuritySettingsService::configureJWTHandler() { _jwtHandler.setSecret(_state.jwtSecret); }
Authentication SecuritySettingsService::authenticateJWT(String &jwt) {
JsonDocument payloadDocument;
_jwtHandler.parseJWT(jwt, payloadDocument);
if (payloadDocument.is<JsonObject>()) {
JsonObject parsedPayload = payloadDocument.as<JsonObject>();
String username = parsedPayload["username"];
for (User _user : _state.users) {
if (_user.username == username && validatePayload(parsedPayload, &_user)) {
return Authentication(_user);
}
}
}
return Authentication();
}
Authentication SecuritySettingsService::authenticate(const String &username, const String &password) {
for (User _user : _state.users) {
if (_user.username == username && _user.password == password) {
return Authentication(_user);
}
}
return Authentication();
}
inline void populateJWTPayload(JsonObject &payload, User *user) {
payload["username"] = user->username;
payload["admin"] = user->admin;
}
boolean SecuritySettingsService::validatePayload(JsonObject &parsedPayload, User *user) {
JsonDocument jsonDocument;
JsonObject payload = jsonDocument.to<JsonObject>();
populateJWTPayload(payload, user);
return payload == parsedPayload;
}
String SecuritySettingsService::generateJWT(User *user) {
JsonDocument jsonDocument;
JsonObject payload = jsonDocument.to<JsonObject>();
populateJWTPayload(payload, user);
return _jwtHandler.buildJWT(payload);
}
PsychicRequestFilterFunction SecuritySettingsService::filterRequest(AuthenticationPredicate predicate) {
return [this, predicate](PsychicRequest *request) {
// ESP_LOGV("SecuritySettingsService", "Authenticating filter request: %s", request->uri().c_str());
// ESP_LOGV("SecuritySettingsService", "Request Method: %s", request->methodStr().c_str());
// TODO: This is a hack to allow bogus websocket filter requests to pass through
// This is a temporary fix until the PsychicHttp websocket handler is fixed to not send a bogus filter request
// Check if we have a bogus filter request and return true
if (request->uri().isEmpty() && request->method() == HTTP_DELETE) {
// ESP_LOGV("SecuritySettingsService", "Bogus filter request - allowing");
return true;
} else
request->loadParams();
Authentication authentication = authenticateRequest(request);
bool result = predicate(authentication);
// ESP_LOGV("SecuritySettingsService", "Filter Request %s", result ? "allowed" : "denied");
return result;
};
}
PsychicHttpRequestCallback SecuritySettingsService::wrapRequest(PsychicHttpRequestCallback onRequest,
AuthenticationPredicate predicate) {
return [this, onRequest, predicate](PsychicRequest *request) {
Authentication authentication = authenticateRequest(request);
if (!predicate(authentication)) {
return request->reply(401);
}
return onRequest(request);
};
}
PsychicJsonRequestCallback SecuritySettingsService::wrapCallback(PsychicJsonRequestCallback onRequest,
AuthenticationPredicate predicate) {
return [this, onRequest, predicate](PsychicRequest *request, JsonVariant &json) {
Authentication authentication = authenticateRequest(request);
if (!predicate(authentication)) {
return request->reply(401);
}
return onRequest(request, json);
};
}
esp_err_t SecuritySettingsService::generateToken(PsychicRequest *request) {
String usernameParam = request->getParam("username")->value();
for (User _user : _state.users) {
if (_user.username == usernameParam) {
PsychicJsonResponse response = PsychicJsonResponse(request, false);
JsonObject root = response.getRoot();
root["token"] = generateJWT(&_user);
return response.send();
}
}
return request->reply(401);
}
#else
User ADMIN_USER = User(FACTORY_ADMIN_USERNAME, FACTORY_ADMIN_PASSWORD, true);
SecuritySettingsService::SecuritySettingsService(PsychicHttpServer *server, FS *fs) : SecurityManager() {}
SecuritySettingsService::~SecuritySettingsService() {}
PsychicRequestFilterFunction SecuritySettingsService::filterRequest(AuthenticationPredicate predicate) {
return [this, predicate](PsychicRequest *request) {
// ESP_LOGV("SecuritySettingsService", "Security disabled - all requests are allowed");
return true;
};
}
// Return the admin user on all request - disabling security features
Authentication SecuritySettingsService::authenticateRequest(PsychicRequest *request) {
return Authentication(ADMIN_USER);
}
// Return the function unwrapped
PsychicHttpRequestCallback SecuritySettingsService::wrapRequest(PsychicHttpRequestCallback onRequest,
AuthenticationPredicate predicate) {
return onRequest;
}
PsychicJsonRequestCallback SecuritySettingsService::wrapCallback(PsychicJsonRequestCallback onRequest,
AuthenticationPredicate predicate) {
return onRequest;
}
#endif
@@ -1,140 +0,0 @@
#ifndef SecuritySettingsService_h
#define SecuritySettingsService_h
/**
* ESP32 SvelteKit
*
* A simple, secure and extensible framework for IoT projects for ESP32 platforms
* with responsive Sveltekit front-end built with TailwindCSS and DaisyUI.
* https://github.com/theelims/ESP32-sveltekit
*
* Copyright (C) 2018 - 2023 rjwats
* Copyright (C) 2023 theelims
*
* All Rights Reserved. This software may be modified and distributed under
* the terms of the LGPL v3 license. See the LICENSE file for details.
**/
#include <SettingValue.h>
#include <Features.h>
#include <SecurityManager.h>
#include <HttpEndpoint.h>
#include <FSPersistence.h>
#include <ESPFS.h>
#ifndef FACTORY_JWT_SECRET
#define FACTORY_JWT_SECRET "#{random}-#{random}"
#endif
#ifndef FACTORY_ADMIN_USERNAME
#define FACTORY_ADMIN_USERNAME "admin"
#endif
#ifndef FACTORY_ADMIN_PASSWORD
#define FACTORY_ADMIN_PASSWORD "admin"
#endif
#ifndef FACTORY_GUEST_USERNAME
#define FACTORY_GUEST_USERNAME "guest"
#endif
#ifndef FACTORY_GUEST_PASSWORD
#define FACTORY_GUEST_PASSWORD "guest"
#endif
#define SECURITY_SETTINGS_PATH "/api/securitySettings"
#define GENERATE_TOKEN_PATH "/api/generateToken"
#if FT_ENABLED(USE_SECURITY)
class SecuritySettings {
public:
String jwtSecret;
std::list<User> users;
static void read(SecuritySettings &settings, JsonObject &root) {
// secret
root["jwt_secret"] = settings.jwtSecret;
// users
JsonArray users = root.to<JsonArray>();
for (User user : settings.users) {
JsonObject userRoot = users.add<JsonObject>();
userRoot["username"] = user.username;
userRoot["password"] = user.password;
userRoot["admin"] = user.admin;
}
}
static StateUpdateResult update(JsonObject &root, SecuritySettings &settings) {
// secret
settings.jwtSecret = root["jwt_secret"] | SettingValue::format(FACTORY_JWT_SECRET);
// users
settings.users.clear();
if (root["users"].is<JsonArray>()) {
for (JsonVariant user : root["users"].as<JsonArray>()) {
settings.users.push_back(User(user["username"], user["password"], user["admin"]));
}
} else {
settings.users.push_back(User(FACTORY_ADMIN_USERNAME, FACTORY_ADMIN_PASSWORD, true));
settings.users.push_back(User(FACTORY_GUEST_USERNAME, FACTORY_GUEST_PASSWORD, false));
}
return StateUpdateResult::CHANGED;
}
};
class SecuritySettingsService : public StatefulService<SecuritySettings>, public SecurityManager {
public:
SecuritySettingsService(PsychicHttpServer *server, FS *fs);
void begin();
// Functions to implement SecurityManager
Authentication authenticate(const String &username, const String &password);
Authentication authenticateRequest(PsychicRequest *request);
String generateJWT(User *user);
PsychicRequestFilterFunction filterRequest(AuthenticationPredicate predicate);
PsychicHttpRequestCallback wrapRequest(PsychicHttpRequestCallback onRequest, AuthenticationPredicate predicate);
PsychicJsonRequestCallback wrapCallback(PsychicJsonRequestCallback onRequest, AuthenticationPredicate predicate);
private:
PsychicHttpServer *_server;
HttpEndpoint<SecuritySettings> _httpEndpoint;
FSPersistence<SecuritySettings> _fsPersistence;
ArduinoJsonJWT _jwtHandler;
esp_err_t generateToken(PsychicRequest *request);
void configureJWTHandler();
/*
* Lookup the user by JWT
*/
Authentication authenticateJWT(String &jwt);
/*
* Verify the payload is correct
*/
boolean validatePayload(JsonObject &parsedPayload, User *user);
};
#else
class SecuritySettingsService : public SecurityManager {
public:
SecuritySettingsService(PsychicHttpServer *server, FS *fs);
~SecuritySettingsService();
// minimal set of functions to support framework with security settings disabled
Authentication authenticateRequest(PsychicRequest *request);
PsychicRequestFilterFunction filterRequest(AuthenticationPredicate predicate);
PsychicHttpRequestCallback wrapRequest(PsychicHttpRequestCallback onRequest, AuthenticationPredicate predicate);
PsychicJsonRequestCallback wrapCallback(PsychicJsonRequestCallback onRequest, AuthenticationPredicate predicate);
};
#endif // end FT_ENABLED(USE_SECURITY)
#endif // end SecuritySettingsService_h
+1 -5
View File
@@ -5,7 +5,6 @@
#include <EventEndpoint.h>
#include <FSPersistence.h>
#include <HttpEndpoint.h>
#include <SecurityManager.h>
#include <StatefulService.h>
#include <stateful_service_endpoint.h>
#include <MathUtils.h>
@@ -69,10 +68,8 @@ class ServoSettings {
class ServoController : public StatefulService<ServoSettings> {
public:
ServoController(PsychicHttpServer *server, FS *fs, SecurityManager *securityManager, Peripherals *peripherals,
EventSocket *socket)
ServoController(PsychicHttpServer *server, FS *fs, Peripherals *peripherals, EventSocket *socket)
: _server(server),
_securityManager(securityManager),
_peripherals(peripherals),
_socket(socket),
endpoint(ServoSettings::read, ServoSettings::update, this),
@@ -139,7 +136,6 @@ class ServoController : public StatefulService<ServoSettings> {
private:
PsychicHttpServer *_server;
SecurityManager *_securityManager;
Peripherals *_peripherals;
EventSocket *_socket;
FSPersistence<ServoSettings> _fsPersistence;
+2 -5
View File
@@ -16,13 +16,10 @@
// Definition of static member variable
void (*SleepService::_callbackSleep)() = nullptr;
SleepService::SleepService(PsychicHttpServer *server, SecurityManager *securityManager)
: _server(server), _securityManager(securityManager) {}
SleepService::SleepService(PsychicHttpServer *server) : _server(server) {}
void SleepService::begin() {
_server->on(SLEEP_SERVICE_PATH, HTTP_POST,
_securityManager->wrapRequest(std::bind(&SleepService::sleep, this, std::placeholders::_1),
AuthenticationPredicates::IS_AUTHENTICATED));
_server->on(SLEEP_SERVICE_PATH, HTTP_POST, [this](PsychicRequest *request) { return sleep(request); });
ESP_LOGV("SleepService", "Registered POST endpoint: %s", SLEEP_SERVICE_PATH);
}
+1 -3
View File
@@ -17,7 +17,6 @@
#include <ESPmDNS.h>
#include <PsychicHttp.h>
#include <SecurityManager.h>
#define SLEEP_SERVICE_PATH "/api/sleep"
@@ -31,7 +30,7 @@
class SleepService {
public:
SleepService(PsychicHttpServer *server, SecurityManager *securityManager);
SleepService(PsychicHttpServer *server);
void begin();
@@ -41,7 +40,6 @@ class SleepService {
private:
PsychicHttpServer *_server;
SecurityManager *_securityManager;
esp_err_t sleep(PsychicRequest *request);
protected:
+2 -4
View File
@@ -35,13 +35,11 @@ String verbosePrintResetReason(int reason) {
}
}
SystemStatus::SystemStatus(PsychicHttpServer *server, SecurityManager *securityManager)
: _server(server), _securityManager(securityManager) {}
SystemStatus::SystemStatus(PsychicHttpServer *server) : _server(server) {}
void SystemStatus::begin() {
_server->on(SYSTEM_STATUS_SERVICE_PATH, HTTP_GET,
_securityManager->wrapRequest(std::bind(&SystemStatus::systemStatus, this, std::placeholders::_1),
AuthenticationPredicates::IS_AUTHENTICATED));
[this](PsychicRequest *request) { return SystemStatus::systemStatus(request); });
ESP_LOGV("SystemStatus", "Registered GET endpoint: %s", SYSTEM_STATUS_SERVICE_PATH);
}
+1 -3
View File
@@ -19,7 +19,6 @@
#include <ArduinoJson.h>
#include <PsychicHttp.h>
#include <SecurityManager.h>
#include <ESPFS.h>
#include <esp32-hal.h>
@@ -60,13 +59,12 @@
class SystemStatus {
public:
SystemStatus(PsychicHttpServer *server, SecurityManager *securityManager);
SystemStatus(PsychicHttpServer *server);
void begin();
private:
PsychicHttpServer *_server;
SecurityManager *_securityManager;
esp_err_t systemStatus(PsychicRequest *request);
};
@@ -22,8 +22,7 @@ static char md5[33] = "\0";
static FileType fileType = ft_none;
UploadFirmwareService::UploadFirmwareService(PsychicHttpServer *server, SecurityManager *securityManager)
: _server(server), _securityManager(securityManager) {}
UploadFirmwareService::UploadFirmwareService(PsychicHttpServer *server) : _server(server) {}
void UploadFirmwareService::begin() {
_server->maxUploadSize = 2300000; // 2.3 MB
@@ -42,12 +41,6 @@ void UploadFirmwareService::begin() {
esp_err_t UploadFirmwareService::handleUpload(PsychicRequest *request, const String &filename, uint64_t index,
uint8_t *data, size_t len, bool final) {
// quit if not authorized
Authentication authentication = _securityManager->authenticateRequest(request);
if (!AuthenticationPredicates::IS_ADMIN(authentication)) {
return handleError(request, 403); // forbidden
}
// at init
if (!index) {
// check details of the file, to see if its a valid bin or json file
@@ -21,7 +21,6 @@
#include <WiFi.h>
#include <PsychicHttp.h>
#include <SecurityManager.h>
#include <RestartService.h>
#define UPLOAD_FIRMWARE_PATH "/api/uploadFirmware"
@@ -30,13 +29,12 @@ enum FileType { ft_none = 0, ft_firmware = 1, ft_md5 = 2 };
class UploadFirmwareService {
public:
UploadFirmwareService(PsychicHttpServer *server, SecurityManager *securityManager);
UploadFirmwareService(PsychicHttpServer *server);
void begin();
private:
PsychicHttpServer *_server;
SecurityManager *_securityManager;
esp_err_t handleUpload(PsychicRequest *request, const String &filename, uint64_t index, uint8_t *data, size_t len,
bool final);
File diff suppressed because it is too large Load Diff