diff --git a/.env.prod.example b/.env.prod.example new file mode 100644 index 0000000..aad2cd6 --- /dev/null +++ b/.env.prod.example @@ -0,0 +1,4 @@ +# Copy to .env and fill in. Keep .env out of git. +DOMAIN=demo.example.com +LED_ADMIN_USER=owner +LED_ADMIN_PASSWORD=change-me-to-a-long-password diff --git a/.gitignore b/.gitignore index 794c54b..6a6d20e 100644 --- a/.gitignore +++ b/.gitignore @@ -45,3 +45,4 @@ desktop-data/ desktop-data-test/ bridge/build-*/ sim-driver/build/ +.env diff --git a/Dockerfile.prod b/Dockerfile.prod new file mode 100644 index 0000000..9ba3244 --- /dev/null +++ b/Dockerfile.prod @@ -0,0 +1,28 @@ +# Production image of the controller demo: ESP-IDF's linux target running the simulated rig. No hardware. +# The web UI is embedded in the binary (main/CMakeLists.txt packs www_dist/www.pack), so no Node is needed. +# Build from the repo root: docker build -f Dockerfile.prod -t led-controller:prod . +# Run with the compose file: docker compose -f docker-compose.prod.yml up -d (see .env.prod.example) + +FROM espressif/idf:v6.1 AS build +WORKDIR /project +COPY . . +RUN bash -c ". /opt/esp/idf/export.sh && cd sim-controller && idf.py build" + +FROM debian:trixie-slim +# The two shared libraries the binary needs, taken from the build image +COPY --from=build /usr/lib/x86_64-linux-gnu/libbsd.so.0.12.1 /usr/lib/x86_64-linux-gnu/libbsd.so.0 +COPY --from=build /usr/lib/x86_64-linux-gnu/libmd.so.0.1.0 /usr/lib/x86_64-linux-gnu/libmd.so.0 +COPY --from=build /project/sim-controller/build/led_controller_sim.elf /usr/local/bin/led_controller_sim +RUN useradd --system --uid 10001 --no-create-home --shell /usr/sbin/nologin led \ + && mkdir /data && chown led:led /data +ENV LED_SIM_DB=/data \ + LED_SIM_HTTP_PORT=8080 \ + LED_SIM_BRIDGE=127.0.0.1:8766 +USER led +VOLUME ["/data"] +EXPOSE 8080 +# Bash's /dev/tcp needs no extra packages: healthy when /status answers 200 +HEALTHCHECK --interval=30s --timeout=5s --start-period=20s --retries=3 \ + CMD bash -c 'exec 3<>/dev/tcp/127.0.0.1/8080 && printf "GET /status HTTP/1.0\r\n\r\n" >&3 && head -n1 <&3 | grep -q " 200"' +STOPSIGNAL SIGTERM +ENTRYPOINT ["/usr/local/bin/led_controller_sim"] diff --git a/Dockerfile.sim b/Dockerfile.sim index 0def4d2..69a39ea 100644 --- a/Dockerfile.sim +++ b/Dockerfile.sim @@ -2,6 +2,9 @@ # The web UI is embedded in the binary (main/CMakeLists.txt packs www_dist/www.pack), so no Node is needed. # Build from the repo root: docker build -f Dockerfile.sim -t led-controller-sim . # Run: docker run --rm -p 8080:8080 -v led-sim-data:/data led-controller-sim +# Editing needs a sign-in. Set the first admin with LED_ADMIN_USER and LED_ADMIN_PASSWORD (8+ characters); +# until a user exists the controller is open to everyone, so set them on the first run. +# docker run ... -e LED_ADMIN_USER=owner -e LED_ADMIN_PASSWORD='change-me-now' led-controller-sim FROM espressif/idf:v6.1 AS build WORKDIR /project @@ -13,9 +16,11 @@ FROM debian:trixie COPY --from=build /usr/lib/x86_64-linux-gnu/libbsd.so.0.12.1 /usr/lib/x86_64-linux-gnu/libbsd.so.0 COPY --from=build /usr/lib/x86_64-linux-gnu/libmd.so.0.1.0 /usr/lib/x86_64-linux-gnu/libmd.so.0 COPY --from=build /project/sim-controller/build/led_controller_sim.elf /usr/local/bin/led_controller_sim +RUN useradd --system --uid 10001 --no-create-home led && mkdir /data && chown led /data ENV LED_SIM_DB=/data \ LED_SIM_HTTP_PORT=8080 \ LED_SIM_BRIDGE=127.0.0.1:8766 +USER led VOLUME ["/data"] EXPOSE 8080 ENTRYPOINT ["/usr/local/bin/led_controller_sim"] diff --git a/deploy/Caddyfile b/deploy/Caddyfile new file mode 100644 index 0000000..e961825 --- /dev/null +++ b/deploy/Caddyfile @@ -0,0 +1,12 @@ +{$DOMAIN} { + encode zstd gzip + reverse_proxy controller:8080 + request_body { + max_size 20MB + } + header { + Strict-Transport-Security "max-age=31536000" + X-Content-Type-Options "nosniff" + Referrer-Policy "same-origin" + } +} diff --git a/desktop/CMakeLists.txt b/desktop/CMakeLists.txt index 45d0379..005b0b8 100644 --- a/desktop/CMakeLists.txt +++ b/desktop/CMakeLists.txt @@ -31,7 +31,7 @@ endif() set(MAIN_SRC beat.c beat_dsp.c espnow_tx.c bridge.c store.c api.c web.c envelope.c engine.c rel.c bench.c audio.c res_profile.c res_misc.c res_device.c res_group.c seqplay.c res_bundle.c audio_api.c patterns.c outputs.c - ws.c ws_client.c wifi_drv.c bridge_serial.c) + ws.c ws_client.c wifi_drv.c bridge_serial.c auth.c) list(TRANSFORM MAIN_SRC PREPEND ${ROOT}/main/) # The host stand-ins for the board's hardware (mic, OTA, littlefs, timers) and the app_main that starts it diff --git a/docker-compose.prod.yml b/docker-compose.prod.yml new file mode 100644 index 0000000..a591279 --- /dev/null +++ b/docker-compose.prod.yml @@ -0,0 +1,59 @@ +# Demo deployment: the controller (no internet access) behind a Caddy proxy that serves HTTPS. +# cp .env.prod.example .env and fill it in +# docker compose -f docker-compose.prod.yml up -d --build +name: led-demo + +services: + controller: + build: + context: . + dockerfile: Dockerfile.prod + image: led-controller:prod + restart: unless-stopped + environment: + LED_ADMIN_USER: ${LED_ADMIN_USER:?required} + LED_ADMIN_PASSWORD: ${LED_ADMIN_PASSWORD:?required} + volumes: + - controller-data:/data + expose: + - "8080" + networks: + - backend # internal only: the controller cannot reach the internet or the host's network + read_only: true + tmpfs: + - /tmp + cap_drop: + - ALL + security_opt: + - no-new-privileges:true + pids_limit: 256 + mem_limit: 512m + + proxy: + image: caddy:2-alpine + restart: unless-stopped + depends_on: + controller: + condition: service_healthy + environment: + DOMAIN: ${DOMAIN:?required} + ports: + - "${HTTP_PORT:-80}:80" + - "${HTTPS_PORT:-443}:443" + volumes: + - ./deploy/Caddyfile:/etc/caddy/Caddyfile:ro + - caddy-data:/data + - caddy-config:/config + networks: + - backend + - public # Caddy needs the internet for public HTTPS certificates + +networks: + backend: + internal: true + public: {} + +volumes: + controller-data: + caddy-data: + caddy-config: diff --git a/main/CMakeLists.txt b/main/CMakeLists.txt index 1968039..7148aca 100644 --- a/main/CMakeLists.txt +++ b/main/CMakeLists.txt @@ -2,14 +2,14 @@ if(IDF_TARGET STREQUAL "linux") # Host build for led-simulator (sim-controller/): no Ethernet, Wi-Fi, mic or OTA. The sim # component has app_main and stands in for main.c, mic.c and ota.c. idf_component_register(SRCS "beat.c" "beat_dsp.c" "espnow_tx.c" "bridge.c" "store.c" "api.c" "web.c" "envelope.c" "engine.c" "rel.c" "bench.c" "audio.c" - "res_profile.c" "res_misc.c" "res_device.c" "res_group.c" "seqplay.c" "res_bundle.c" "audio_api.c" "patterns.c" "outputs.c" "ws.c" "ws_client.c" "wifi_drv.c" "bridge_serial.c" + "res_profile.c" "res_misc.c" "res_device.c" "res_group.c" "seqplay.c" "res_bundle.c" "audio_api.c" "patterns.c" "outputs.c" "ws.c" "ws_client.c" "wifi_drv.c" "bridge_serial.c" "auth.c" INCLUDE_DIRS "." "../sim-controller/components/sim/include" "../bridge/main" REQUIRES esp_http_server esp_timer esp_event cjson PRIV_REQUIRES mbedtls lwip esp_app_format) else() idf_component_register(SRCS "main.c" "mic.c" "beat.c" "beat_dsp.c" "espnow_tx.c" "bridge.c" "store.c" "api.c" "web.c" "envelope.c" "engine.c" "rel.c" "bench.c" "audio.c" "ota.c" - "res_profile.c" "res_misc.c" "res_device.c" "res_group.c" "seqplay.c" "res_bundle.c" "audio_api.c" "patterns.c" "outputs.c" "ws.c" "ws_client.c" "wifi_drv.c" - INCLUDE_DIRS "." + "res_profile.c" "res_misc.c" "res_device.c" "res_group.c" "seqplay.c" "res_bundle.c" "audio_api.c" "patterns.c" "outputs.c" "ws.c" "ws_client.c" "wifi_drv.c" "auth.c" + INCLUDE_DIRS "." "../bridge/main" REQUIRES esp_eth esp_netif esp_event esp_driver_spi esp_driver_gpio nvs_flash app_update esp_app_format esp_http_server esp_timer esp_driver_i2s esp_wifi esp_rom cjson esp_driver_gpio PRIV_REQUIRES littlefs mdns mbedtls lwip w5500) diff --git a/main/api.c b/main/api.c index cc505d1..375da19 100644 --- a/main/api.c +++ b/main/api.c @@ -1,3 +1,4 @@ +#include "auth.h" #include "api.h" #include @@ -556,7 +557,11 @@ static esp_err_t settings_handler_inner(httpd_req_t *req) return web_send_page(req, "settings_editor.html"); } if (n == 1 && req->method == HTTP_GET) { - return api_json(req, "200 OK", store_settings(), false); + cJSON *shown = cJSON_Duplicate(store_settings(), 1); + if (!auth_can(req, "settings", AUTH_EDIT)) { + cJSON_DeleteItemFromObject(shown, "ap_password"); // the Wi-Fi AP password is for editors only + } + return api_json(req, "200 OK", shown, true); } if (n == 2 && strcmp(seg[1], "bridge") == 0 && req->method == HTTP_GET) { return bridge_get(req); @@ -581,6 +586,9 @@ static esp_err_t db_handler_inner(httpd_req_t *req) return api_error(req, "404 Not Found", "unknown collection"); } if (req->method == HTTP_GET) { + if (!strcmp(seg[1], "user")) { + return api_json(req, "200 OK", auth_export_users(), true); // no password hashes + } return api_json(req, "200 OK", store_coll(seg[1]), false); } if (req->method == HTTP_PUT) { @@ -673,6 +681,8 @@ LOCKED(test_handler) esp_err_t api_register(httpd_handle_t server) { + ESP_ERROR_CHECK(auth_init()); + ESP_ERROR_CHECK_WITHOUT_ABORT(auth_register(server)); store_lock(); api_settings_defaults(); api_seed_defaults(); @@ -688,18 +698,18 @@ esp_err_t api_register(httpd_handle_t server) for (size_t r = 0; r < sizeof(ROUTES) / sizeof(ROUTES[0]); r++) { for (size_t m = 0; m < 4; m++) { httpd_uri_t u = { .uri = ROUTES[r], .method = METHODS[m], .handler = collection_handler }; - ESP_ERROR_CHECK_WITHOUT_ABORT(httpd_register_uri_handler(server, &u)); + ESP_ERROR_CHECK_WITHOUT_ABORT(auth_register_uri(server, &u)); } } for (size_t m = 0; m < 4; m++) { httpd_uri_t t = { .uri = "/test/*", .method = METHODS[m], .handler = test_handler }; - ESP_ERROR_CHECK_WITHOUT_ABORT(httpd_register_uri_handler(server, &t)); + ESP_ERROR_CHECK_WITHOUT_ABORT(auth_register_uri(server, &t)); } for (size_t m = 0; m < 4; m++) { httpd_uri_t s = { .uri = "/settings*", .method = METHODS[m], .handler = settings_handler }; httpd_uri_t d = { .uri = "/db/*", .method = METHODS[m], .handler = db_handler }; - ESP_ERROR_CHECK_WITHOUT_ABORT(httpd_register_uri_handler(server, &s)); - ESP_ERROR_CHECK_WITHOUT_ABORT(httpd_register_uri_handler(server, &d)); + ESP_ERROR_CHECK_WITHOUT_ABORT(auth_register_uri(server, &s)); + ESP_ERROR_CHECK_WITHOUT_ABORT(auth_register_uri(server, &d)); } ESP_LOGI(TAG, "API registered"); return ESP_OK; diff --git a/main/audio.c b/main/audio.c index 7849602..8b0ddb8 100644 --- a/main/audio.c +++ b/main/audio.c @@ -2,6 +2,7 @@ * Live audio and beat endpoints: /audio.wav (16 kHz mono PCM stream), /beats (server-sent events from the * beat detector), POST /tap (correct the bar position), /time (board clock). Ported from esp32-eth. */ +#include "auth.h" #include "audio.h" #include @@ -217,7 +218,7 @@ esp_err_t audio_register(httpd_handle_t server) { .uri = "/time", .method = HTTP_GET, .handler = time_get_handler }, }; for (size_t i = 0; i < sizeof(uris) / sizeof(uris[0]); i++) { - esp_err_t err = httpd_register_uri_handler(server, &uris[i]); + esp_err_t err = auth_register_uri(server, &uris[i]); if (err != ESP_OK) { ESP_LOGE(TAG, "register %s: %s", uris[i].uri, esp_err_to_name(err)); return err; diff --git a/main/audio_api.c b/main/audio_api.c index 8601980..21db0b3 100644 --- a/main/audio_api.c +++ b/main/audio_api.c @@ -2,6 +2,7 @@ // start/stop (whether mic beats time sequences), tracking reset and bar anchoring. There is one input, // the I2S microphone, so device selection is stored but changes nothing. +#include "auth.h" #include "audio_api.h" #include @@ -367,7 +368,7 @@ esp_err_t audio_api_register(httpd_handle_t server) static const httpd_method_t METHODS[] = { HTTP_GET, HTTP_POST, HTTP_PUT }; for (size_t m = 0; m < 3; m++) { httpd_uri_t u = { .uri = "/api/audio/*", .method = METHODS[m], .handler = audio_handler }; - esp_err_t err = httpd_register_uri_handler(server, &u); + esp_err_t err = auth_register_uri(server, &u); if (err != ESP_OK) { return err; } diff --git a/main/auth.c b/main/auth.c new file mode 100644 index 0000000..cc69631 --- /dev/null +++ b/main/auth.c @@ -0,0 +1,1301 @@ +#include "auth.h" + +#include +#include +#include +#include +#include +#include "esp_log.h" +#include "esp_random.h" +#include "esp_timer.h" +#include "store.h" + +static const char *TAG = "auth"; + +#define AREA_N 10 +static const char *const AREAS[AREA_N] = { + "presets", "sequences", "zones", "groups", "devices", "outputs", "patterns", "sim", "settings", "users", +}; +// Control actions (POST) on these areas need control, not edit +static const char *const CONTROL_WORDS[] = { + "play", "stop", "fire", "overlay", "sync-phase", "set-current", "current", "apply", "send", "push", + "brightness", "identify", "ping", "resolve-brightness", "test", +}; + +#define COOKIE "led_session" +#define TOKEN_LEN 64 +#define PBKDF2_ITER 10000 +#define SESS_MAX 32 +#define SESS_TTL_US (30LL * 24 * 3600 * 1000000) +#define WS_MAX 16 + +/* ------------------------------------------------------------------ sha-256, hmac, pbkdf2 + * Pure C, so the same hashes come out on every build (the linux host builds have no mbedtls). */ + +typedef struct { + uint32_t h[8]; + uint8_t buf[64]; + size_t bl; + uint64_t total; +} sha_t; + +static const uint32_t K256[64] = { + 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, + 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, + 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, + 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, + 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, + 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, + 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, + 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2, +}; + +static uint32_t rotr(uint32_t x, int n) +{ + return (x >> n) | (x << (32 - n)); +} + +static void sha_init(sha_t *c) +{ + static const uint32_t H0[8] = { + 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19, + }; + memcpy(c->h, H0, sizeof(H0)); + c->bl = 0; + c->total = 0; +} + +static void sha_block(uint32_t h[8], const uint8_t b[64]) +{ + uint32_t w[64]; + for (int i = 0; i < 16; i++) { + w[i] = ((uint32_t)b[4 * i] << 24) | ((uint32_t)b[4 * i + 1] << 16) | ((uint32_t)b[4 * i + 2] << 8) | b[4 * i + 3]; + } + for (int i = 16; i < 64; i++) { + uint32_t s0 = rotr(w[i - 15], 7) ^ rotr(w[i - 15], 18) ^ (w[i - 15] >> 3); + uint32_t s1 = rotr(w[i - 2], 17) ^ rotr(w[i - 2], 19) ^ (w[i - 2] >> 10); + w[i] = w[i - 16] + s0 + w[i - 7] + s1; + } + uint32_t a = h[0], bb = h[1], c = h[2], d = h[3], e = h[4], f = h[5], g = h[6], hh = h[7]; + for (int i = 0; i < 64; i++) { + uint32_t S1 = rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25); + uint32_t ch = (e & f) ^ (~e & g); + uint32_t t1 = hh + S1 + ch + K256[i] + w[i]; + uint32_t S0 = rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22); + uint32_t maj = (a & bb) ^ (a & c) ^ (bb & c); + uint32_t t2 = S0 + maj; + hh = g; + g = f; + f = e; + e = d + t1; + d = c; + c = bb; + bb = a; + a = t1 + t2; + } + h[0] += a; + h[1] += bb; + h[2] += c; + h[3] += d; + h[4] += e; + h[5] += f; + h[6] += g; + h[7] += hh; +} + +static void sha_update(sha_t *c, const void *p, size_t n) +{ + const uint8_t *d = p; + c->total += n; + while (n) { + size_t take = 64 - c->bl; + if (take > n) { + take = n; + } + memcpy(c->buf + c->bl, d, take); + c->bl += take; + d += take; + n -= take; + if (c->bl == 64) { + sha_block(c->h, c->buf); + c->bl = 0; + } + } +} + +static void sha_final(sha_t *c, uint8_t out[32]) +{ + uint64_t bits = c->total * 8; + uint8_t one = 0x80, zero = 0; + sha_update(c, &one, 1); + while (c->bl != 56) { + sha_update(c, &zero, 1); + } + uint8_t len[8]; + for (int i = 0; i < 8; i++) { + len[i] = (uint8_t)(bits >> (56 - 8 * i)); + } + sha_update(c, len, 8); + for (int i = 0; i < 8; i++) { + out[4 * i] = (uint8_t)(c->h[i] >> 24); + out[4 * i + 1] = (uint8_t)(c->h[i] >> 16); + out[4 * i + 2] = (uint8_t)(c->h[i] >> 8); + out[4 * i + 3] = (uint8_t)c->h[i]; + } +} + +// HMAC-SHA256 of m1 || m2 (m2 may be empty) +static void hmac256(const uint8_t *key, size_t kl, const uint8_t *m1, size_t l1, const uint8_t *m2, size_t l2, uint8_t out[32]) +{ + uint8_t k[64] = { 0 }; + if (kl > 64) { + sha_t c; + sha_init(&c); + sha_update(&c, key, kl); + sha_final(&c, k); + } else { + memcpy(k, key, kl); + } + uint8_t ipad[64], opad[64], inner[32]; + for (int i = 0; i < 64; i++) { + ipad[i] = k[i] ^ 0x36; + opad[i] = k[i] ^ 0x5c; + } + sha_t c; + sha_init(&c); + sha_update(&c, ipad, 64); + sha_update(&c, m1, l1); + if (l2) { + sha_update(&c, m2, l2); + } + sha_final(&c, inner); + sha_init(&c); + sha_update(&c, opad, 64); + sha_update(&c, inner, 32); + sha_final(&c, out); +} + +// PBKDF2-HMAC-SHA256, one 32-byte block +static void pbkdf2(const char *pw, const uint8_t *salt, size_t sl, uint32_t iter, uint8_t out[32]) +{ + static const uint8_t one[4] = { 0, 0, 0, 1 }; + uint8_t u[32], t[32]; + hmac256((const uint8_t *)pw, strlen(pw), salt, sl, one, 4, u); + memcpy(t, u, 32); + for (uint32_t i = 1; i < iter; i++) { + hmac256((const uint8_t *)pw, strlen(pw), u, 32, NULL, 0, u); + for (int j = 0; j < 32; j++) { + t[j] ^= u[j]; + } + } + memcpy(out, t, 32); +} + +static void to_hex(const uint8_t *b, size_t n, char *out) +{ + static const char D[] = "0123456789abcdef"; + for (size_t i = 0; i < n; i++) { + out[2 * i] = D[b[i] >> 4]; + out[2 * i + 1] = D[b[i] & 15]; + } + out[2 * n] = 0; +} + +static int hexval(char c) +{ + if (c >= '0' && c <= '9') { + return c - '0'; + } + if (c >= 'a' && c <= 'f') { + return c - 'a' + 10; + } + if (c >= 'A' && c <= 'F') { + return c - 'A' + 10; + } + return -1; +} + +static bool from_hex(const char *s, uint8_t *out, size_t n) +{ + if (!s || strlen(s) != 2 * n) { + return false; + } + for (size_t i = 0; i < n; i++) { + int hi = hexval(s[2 * i]), lo = hexval(s[2 * i + 1]); + if (hi < 0 || lo < 0) { + return false; + } + out[i] = (uint8_t)(hi << 4 | lo); + } + return true; +} + +static bool const_eq(const uint8_t *a, const uint8_t *b, size_t n) +{ + uint8_t d = 0; + for (size_t i = 0; i < n; i++) { + d |= a[i] ^ b[i]; + } + return d == 0; +} + +/* ------------------------------------------------------------------ records */ + +static const char *str_of(const cJSON *o, const char *key) +{ + const cJSON *v = cJSON_GetObjectItem(o, key); + return cJSON_IsString(v) ? v->valuestring : NULL; +} + +// Sets a key whether or not it exists yet (cJSON_ReplaceItemInObject does nothing for a new key) +static void obj_set(cJSON *o, const char *k, cJSON *v) +{ + if (cJSON_GetObjectItem(o, k)) { + cJSON_ReplaceItemInObject(o, k, v); + } else { + cJSON_AddItemToObject(o, k, v); + } +} + +static bool valid_name(const char *s) +{ + size_t n = s ? strlen(s) : 0; + if (n == 0 || n > 32) { + return false; + } + for (size_t i = 0; i < n; i++) { + if (!isalnum((unsigned char)s[i]) && !strchr("_.-", s[i])) { + return false; + } + } + return true; +} + +static int area_index(const char *a) +{ + for (int i = 0; i < AREA_N; i++) { + if (strcmp(AREAS[i], a) == 0) { + return i; + } + } + return -1; +} + +static int perm_in(const cJSON *role, const char *area) +{ + const cJSON *v = cJSON_GetObjectItem(cJSON_GetObjectItem(role, "perms"), area); + if (!cJSON_IsNumber(v)) { + return AUTH_NONE; + } + return v->valueint < 0 ? AUTH_NONE : v->valueint > 3 ? AUTH_EDIT : v->valueint; +} + +static int role_perm(const char *role, const char *area) +{ + if (!role || !role[0]) { + return AUTH_NONE; + } + const cJSON *r = cJSON_GetObjectItem(store_coll("role"), role); + return r ? perm_in(r, area) : AUTH_NONE; +} + +static bool all_edit(const cJSON *perms) +{ + for (int i = 0; i < AREA_N; i++) { + const cJSON *v = cJSON_GetObjectItem(perms, AREAS[i]); + if (!cJSON_IsNumber(v) || v->valueint != AUTH_EDIT) { + return false; + } + } + return true; +} + +// A perms object from JSON: every area present, unknown areas and bad levels refused +static cJSON *perms_from_json(const cJSON *p, const char **err) +{ + if (!cJSON_IsObject(p)) { + *err = "perms must be an object of area: level"; + return NULL; + } + cJSON *out = cJSON_CreateObject(); + for (int i = 0; i < AREA_N; i++) { + cJSON_AddNumberToObject(out, AREAS[i], AUTH_NONE); + } + const cJSON *it = NULL; + cJSON_ArrayForEach(it, p) + { + if (area_index(it->string) < 0) { + *err = "unknown area in perms"; + cJSON_Delete(out); + return NULL; + } + if (!cJSON_IsNumber(it) || it->valueint < 0 || it->valueint > 3) { + *err = "each level must be 0 (none), 1 (view), 2 (control) or 3 (edit)"; + cJSON_Delete(out); + return NULL; + } + obj_set(out, it->string, cJSON_CreateNumber(it->valueint)); + } + return out; +} + +// Users who can change users and roles, counting one user as the role named set_role at set_level +static int managers_after(const char *skip_user, const char *set_role, int set_level) +{ + int n = 0; + const cJSON *u = NULL; + cJSON_ArrayForEach(u, store_coll("user")) + { + if (skip_user && strcmp(u->string, skip_user) == 0) { + continue; + } + const char *r = str_of(u, "role"); + int level = (set_role && r && strcmp(r, set_role) == 0) ? set_level : role_perm(r, "users"); + if (level >= AUTH_EDIT) { + n++; + } + } + return n; +} + +static bool auth_enabled_locked(void) +{ + return cJSON_GetArraySize(store_coll("user")) > 0; +} + +/* ------------------------------------------------------------------ sessions */ + +typedef struct { + bool used; + char tok[TOKEN_LEN + 1]; + char user[33]; + int64_t exp; +} sess_t; + +static sess_t s_sess[SESS_MAX]; + +// Failed logins per username: after 5 in a row that name waits 30 s, doubling to 5 min. Other names are unaffected. +#define LOCK_SLOTS 16 +typedef struct { + bool used; + char user[33]; + int fails; + int64_t until; +} lock_t; +static lock_t s_lock[LOCK_SLOTS]; + +static lock_t *lock_slot(const char *user, bool create) +{ + lock_t *free_slot = NULL, *oldest = &s_lock[0]; + for (int i = 0; i < LOCK_SLOTS; i++) { + lock_t *l = &s_lock[i]; + if (l->used && strcmp(l->user, user) == 0) { + return l; + } + if (!l->used && !free_slot) { + free_slot = l; + } + if (l->until < oldest->until) { + oldest = l; + } + } + if (!create) { + return NULL; + } + lock_t *slot = free_slot ? free_slot : oldest; // a full table gives up the entry that expires first + memset(slot, 0, sizeof(*slot)); + slot->used = true; + snprintf(slot->user, sizeof(slot->user), "%s", user); + return slot; +} + +static sess_t *sess_find(const char *tok) +{ + int64_t now = esp_timer_get_time(); + for (int i = 0; i < SESS_MAX; i++) { + sess_t *s = &s_sess[i]; + if (!s->used) { + continue; + } + if (s->exp < now) { + s->used = false; + continue; + } + if (strcmp(s->tok, tok) == 0) { + s->exp = now + SESS_TTL_US; + return s; + } + } + return NULL; +} + +static void sess_drop_user(const char *user) +{ + for (int i = 0; i < SESS_MAX; i++) { + if (s_sess[i].used && strcmp(s_sess[i].user, user) == 0) { + s_sess[i].used = false; + } + } +} + +static void sess_drop_tok(const char *tok) +{ + for (int i = 0; i < SESS_MAX; i++) { + if (s_sess[i].used && strcmp(s_sess[i].tok, tok) == 0) { + s_sess[i].used = false; + } + } +} + +// A new session for user; the token is written to tok +static void sess_new(const char *user, char tok[TOKEN_LEN + 1]) +{ + uint8_t r[TOKEN_LEN / 2]; + esp_fill_random(r, sizeof(r)); + to_hex(r, sizeof(r), tok); + int64_t now = esp_timer_get_time(); + int slot = -1, oldest = 0; + for (int i = 0; i < SESS_MAX; i++) { + if (!s_sess[i].used || s_sess[i].exp < now) { + slot = i; + break; + } + if (s_sess[i].exp < s_sess[oldest].exp) { + oldest = i; + } + } + if (slot < 0) { + slot = oldest; // full: the session nearest its expiry gives way + } + sess_t *s = &s_sess[slot]; + s->used = true; + snprintf(s->tok, sizeof(s->tok), "%s", tok); + snprintf(s->user, sizeof(s->user), "%s", user); + s->exp = now + SESS_TTL_US; +} + +static bool cookie_tok(httpd_req_t *req, char tok[TOKEN_LEN + 1]) +{ + size_t n = TOKEN_LEN + 1; + tok[0] = 0; + return httpd_req_get_cookie_val(req, COOKIE, tok, &n) == ESP_OK && strlen(tok) == TOKEN_LEN; +} + +// The signed-in user and role for this request; false when signed out +static bool session_of(httpd_req_t *req, char *user, size_t un, char *role, size_t rn) +{ + char tok[TOKEN_LEN + 1]; + if (!cookie_tok(req, tok)) { + return false; + } + store_lock(); + bool ok = false; + sess_t *s = sess_find(tok); + if (s) { + const cJSON *u = cJSON_GetObjectItem(store_coll("user"), s->user); + if (u) { + snprintf(user, un, "%s", s->user); + snprintf(role, rn, "%s", str_of(u, "role") ? str_of(u, "role") : ""); + ok = true; + } + } + store_unlock(); + return ok; +} + +/* ------------------------------------------------------------------ classification */ + +// The request's role: its session's role, or guest when signed out (signed_in says which) +static bool who(httpd_req_t *req, char *user, size_t un, char *role, size_t rn) +{ + bool signed_in = session_of(req, user, un, role, rn); + if (!signed_in) { + user[0] = 0; + snprintf(role, rn, "%s", "guest"); + } + return signed_in; +} + +static auth_need_t need(const char *area, auth_level_t level, bool pub) +{ + auth_need_t n = { area, level, pub }; + return n; +} + +auth_need_t auth_classify(const char *uri, int method) +{ + char buf[160]; + const char *s[6] = { 0 }; + size_t len = strcspn(uri, "?"); + if (len >= sizeof(buf)) { + return need("settings", AUTH_EDIT, false); // too long to read: refuse + } + memcpy(buf, uri, len); + buf[len] = 0; + int n = 0; + if (buf[0] == '/') { + char *p = buf + 1; + while (*p && n < 6) { + s[n++] = p; + char *slash = strchr(p, '/'); + if (!slash) { + break; + } + *slash = 0; + p = slash + 1; + } + } + const bool get = method == HTTP_GET, post = method == HTTP_POST, put = method == HTTP_PUT; + const char *s0 = n > 0 ? s[0] : ""; + const char *s1 = n > 1 ? s[1] : ""; + const char *s2 = n > 2 ? s[2] : ""; + + if (n == 0) { + return get ? need("", AUTH_NONE, true) : need("settings", AUTH_EDIT, false); + } + if (get && (!strcmp(s0, "audio") || !strcmp(s0, "favicon.ico") || !strcmp(s0, "status") || !strcmp(s0, "static"))) { + return need("", AUTH_NONE, true); + } + // The rig page's files are public (its data is not); its websocket checks its own handshake + if (!strcmp(s0, "ws") || (!strcmp(s0, "sim") && n > 1 && !strcmp(s1, "ws"))) { + return need("", AUTH_NONE, true); + } + if (!strcmp(s0, "sim") && get && (n < 2 || (strcmp(s1, "api") && strcmp(s1, "ws")))) { + return need("", AUTH_NONE, true); + } + if (!strcmp(s0, "auth")) { + if (n == 1 && get) { + return need("", AUTH_NONE, true); + } + if (n == 2 && post && (!strcmp(s1, "login") || !strcmp(s1, "logout"))) { + return need("", AUTH_NONE, true); + } + if (n == 2 && put && !strcmp(s1, "password")) { + return need("@user", AUTH_NONE, false); + } + return need("users", AUTH_EDIT, false); + } + + const char *area = NULL; + bool ctrl_ok = false; + if (!strcmp(s0, "presets")) { + area = "presets"; + ctrl_ok = true; + } else if (!strcmp(s0, "sequences")) { + area = "sequences"; + ctrl_ok = true; + } else if (!strcmp(s0, "zones") || !strcmp(s0, "profiles") || !strcmp(s0, "scenes")) { + area = "zones"; + ctrl_ok = true; + } else if (!strcmp(s0, "groups")) { + area = "groups"; + ctrl_ok = true; + } else if (!strcmp(s0, "devices")) { + area = "devices"; + ctrl_ok = true; + } else if (!strcmp(s0, "outputs")) { + area = "outputs"; + ctrl_ok = true; + } else if (!strcmp(s0, "patterns") || !strcmp(s0, "palettes")) { + area = "patterns"; + } else if (!strcmp(s0, "sim")) { + area = "sim"; + } else if (!strcmp(s0, "settings") || !strcmp(s0, "ota") || !strcmp(s0, "reboot") || !strcmp(s0, "test")) { + area = "settings"; + } else if (!strcmp(s0, "api") && n > 1 && !strcmp(s1, "audio")) { + area = "settings"; + } else if (!strcmp(s0, "db")) { + return need("settings", AUTH_EDIT, false); // exports hold everything, so even reads need edit + } else { + return need("settings", AUTH_EDIT, false); // unknown routes fail closed + } + + if (!strcmp(s0, "sim") && post && n == 3 && !strcmp(s1, "api") && !strcmp(s2, "room")) { + return need("sim", AUTH_CONTROL, false); // switching the rig's room + } + if (get) { + return need(area, AUTH_VIEW, false); + } + if (post && ctrl_ok) { + for (int i = 1; i < n; i++) { + for (size_t k = 0; k < sizeof(CONTROL_WORDS) / sizeof(CONTROL_WORDS[0]); k++) { + if (!strcmp(s[i], CONTROL_WORDS[k])) { + return need(area, AUTH_CONTROL, false); + } + } + } + } + return need(area, AUTH_EDIT, false); +} + +/* ------------------------------------------------------------------ responses */ + +static esp_err_t send_json(httpd_req_t *req, const char *status, cJSON *o) +{ + char *s = cJSON_PrintUnformatted(o); + cJSON_Delete(o); + httpd_resp_set_status(req, status); + httpd_resp_set_type(req, "application/json"); + esp_err_t err = httpd_resp_sendstr(req, s ? s : "{}"); + free(s); + return err; +} + +static esp_err_t send_err(httpd_req_t *req, const char *status, const char *msg) +{ + cJSON *o = cJSON_CreateObject(); + cJSON_AddStringToObject(o, "error", msg); + return send_json(req, status, o); +} + +static cJSON *read_body(httpd_req_t *req) +{ + size_t len = req->content_len; + if (len == 0 || len > 4096) { + return NULL; + } + char *buf = malloc(len + 1); + if (!buf) { + return NULL; + } + size_t got = 0; + while (got < len) { + int r = httpd_req_recv(req, buf + got, len - got); + if (r <= 0) { + free(buf); + return NULL; + } + got += (size_t)r; + } + buf[len] = 0; + cJSON *o = cJSON_Parse(buf); + free(buf); + if (!cJSON_IsObject(o)) { + cJSON_Delete(o); + return NULL; + } + return o; +} + +static esp_err_t deny(httpd_req_t *req, const char *status, const char *msg) +{ + httpd_resp_set_hdr(req, "Connection", "close"); // the body is not read, so the connection cannot be reused + return send_err(req, status, msg); +} + +/* ------------------------------------------------------------------ gate */ + +typedef esp_err_t (*auth_handler_t)(httpd_req_t *req); + +static esp_err_t auth_gate(httpd_req_t *req) +{ + auth_handler_t fn = (auth_handler_t)(uintptr_t)req->user_ctx; + auth_need_t n = auth_classify(req->uri, req->method); + if (!n.pub) { + char user[33], role[33]; + store_lock(); + bool enabled = auth_enabled_locked(); + bool signed_in = enabled && who(req, user, sizeof user, role, sizeof role); + bool allowed = !enabled || (n.area[0] == '@' ? signed_in : role_perm(role, n.area) >= n.level); + store_unlock(); + if (!allowed) { + return signed_in ? deny(req, "403 Forbidden", "not allowed") : deny(req, "401 Unauthorized", "login required"); + } + } + return fn(req); +} + +esp_err_t auth_register_uri(httpd_handle_t server, const httpd_uri_t *u) +{ + httpd_uri_t g = *u; + g.user_ctx = (void *)(uintptr_t)u->handler; + g.handler = auth_gate; + return httpd_register_uri_handler(server, &g); +} + +bool auth_can(httpd_req_t *req, const char *area, auth_level_t level) +{ + store_lock(); + bool enabled = auth_enabled_locked(); + store_unlock(); + if (!enabled) { + return true; + } + char user[33], role[33]; + bool signed_in = who(req, user, sizeof user, role, sizeof role); + if (area[0] == 0 || area[0] == '@') { + return signed_in; + } + return role_perm(role, area) >= level; +} + +/* ------------------------------------------------------------------ websockets + * The socket's user is recorded at the handshake; each frame checks the user's current role. */ + +typedef struct { + int fd; + bool used; + char user[33]; // "" when auth was off at the handshake +} ws_t; + +static ws_t s_ws[WS_MAX]; + +static ws_t *ws_slot(int fd, bool create) +{ + ws_t *free_slot = NULL; + for (int i = 0; i < WS_MAX; i++) { + if (s_ws[i].used && s_ws[i].fd == fd) { + return &s_ws[i]; + } + if (!s_ws[i].used && !free_slot) { + free_slot = &s_ws[i]; + } + } + if (create && free_slot) { + free_slot->used = true; + free_slot->fd = fd; + free_slot->user[0] = 0; + return free_slot; + } + return NULL; +} + +esp_err_t auth_ws_admit(httpd_req_t *req, const char *area, auth_level_t level) +{ + int fd = httpd_req_to_sockfd(req); + char user[33] = "", role[33] = ""; + store_lock(); + bool enabled = auth_enabled_locked(); + bool ok = !enabled || (who(req, user, sizeof user, role, sizeof role), role_perm(role, area) >= level); + store_unlock(); + ws_t *w = ws_slot(fd, ok); + if (!ok || !w) { + if (w) { + w->used = false; + } + ESP_LOGW(TAG, "websocket on fd %d refused", fd); + return ESP_FAIL; + } + snprintf(w->user, sizeof(w->user), "%s", enabled ? user : ""); + return ESP_OK; +} + +bool auth_ws_allowed(int fd, const char *area, auth_level_t level) +{ + store_lock(); + bool ok = false; + ws_t *w = ws_slot(fd, false); + if (!auth_enabled_locked()) { + ok = true; + } else if (w && w->user[0]) { + const cJSON *u = cJSON_GetObjectItem(store_coll("user"), w->user); + ok = u && role_perm(str_of(u, "role"), area) >= level; + } else if (w) { + ok = role_perm("guest", area) >= level; + } + store_unlock(); + return ok; +} + +/* ------------------------------------------------------------------ users and roles */ + +cJSON *auth_export_users(void) +{ + cJSON *out = cJSON_CreateObject(); + const cJSON *u = NULL; + store_lock(); + cJSON_ArrayForEach(u, store_coll("user")) + { + cJSON *o = cJSON_CreateObject(); + cJSON_AddStringToObject(o, "role", str_of(u, "role") ? str_of(u, "role") : ""); + cJSON_AddItemToObject(out, u->string, o); + } + store_unlock(); + return out; +} + +static cJSON *role_record(bool builtin, cJSON *perms) +{ + cJSON *r = cJSON_CreateObject(); + cJSON_AddItemToObject(r, "perms", perms); + cJSON_AddBoolToObject(r, "builtin", builtin); + return r; +} + +// Built-in roles, and an admin from LED_ADMIN_USER / LED_ADMIN_PASSWORD (created, or its password reset) +esp_err_t auth_init(void) +{ + store_lock(); + cJSON *roles = store_coll("role"); + cJSON *all3 = cJSON_CreateObject(); + cJSON *guest = cJSON_CreateObject(); + for (int i = 0; i < AREA_N; i++) { + cJSON_AddNumberToObject(all3, AREAS[i], AUTH_EDIT); + bool hidden = !strcmp(AREAS[i], "settings") || !strcmp(AREAS[i], "users"); + cJSON_AddNumberToObject(guest, AREAS[i], hidden ? AUTH_NONE : AUTH_VIEW); + } + // admin is fixed to edit everywhere; guest is seeded once and can then be edited + obj_set(roles, "admin", role_record(true, all3)); + if (!cJSON_GetObjectItem(roles, "guest")) { + cJSON_AddItemToObject(roles, "guest", role_record(true, guest)); + } else { + cJSON_Delete(guest); + } + store_save("role"); + + const char *au = getenv("LED_ADMIN_USER"), *ap = getenv("LED_ADMIN_PASSWORD"); + if (au && au[0] && ap && ap[0]) { + if (!valid_name(au) || strlen(ap) < 8 || strlen(ap) > 128) { + ESP_LOGE(TAG, "LED_ADMIN_USER needs 1-32 letters, digits, _ . - ; LED_ADMIN_PASSWORD 8-128 characters"); + } else { + cJSON *users = store_coll("user"); + uint8_t salt[16], hash[32]; + esp_fill_random(salt, sizeof(salt)); + pbkdf2(ap, salt, sizeof(salt), PBKDF2_ITER, hash); + cJSON *rec = cJSON_CreateObject(); + char hx[65]; + cJSON_AddStringToObject(rec, "role", "admin"); + to_hex(salt, sizeof(salt), hx); + cJSON_AddStringToObject(rec, "salt", hx); + to_hex(hash, sizeof(hash), hx); + cJSON_AddStringToObject(rec, "hash", hx); + obj_set(users, au, rec); + sess_drop_user(au); + store_save("user"); + ESP_LOGI(TAG, "admin user '%s' set from the environment", au); + } + } + store_unlock(); + return ESP_OK; +} + +static esp_err_t users_list(httpd_req_t *req) +{ + cJSON *out = cJSON_CreateArray(); + const cJSON *u = NULL; + cJSON_ArrayForEach(u, store_coll("user")) + { + cJSON *o = cJSON_CreateObject(); + cJSON_AddStringToObject(o, "username", u->string); + cJSON_AddStringToObject(o, "role", str_of(u, "role") ? str_of(u, "role") : ""); + cJSON_AddItemToArray(out, o); + } + return send_json(req, "200 OK", out); +} + +static esp_err_t roles_list(httpd_req_t *req) +{ + cJSON *out = cJSON_CreateArray(); + const cJSON *r = NULL; + cJSON_ArrayForEach(r, store_coll("role")) + { + cJSON *o = cJSON_CreateObject(); + cJSON_AddStringToObject(o, "name", r->string); + cJSON_AddBoolToObject(o, "builtin", cJSON_IsTrue(cJSON_GetObjectItem(r, "builtin"))); + cJSON_AddItemToObject(o, "perms", cJSON_Duplicate(cJSON_GetObjectItem(r, "perms"), 1)); + cJSON_AddItemToArray(out, o); + } + return send_json(req, "200 OK", out); +} + +static esp_err_t login(httpd_req_t *req) +{ + cJSON *body = read_body(req); + const char *name = body ? str_of(body, "username") : NULL, *pw = body ? str_of(body, "password") : NULL; + if (!name || !pw) { + cJSON_Delete(body); + return send_err(req, "400 Bad Request", "send username and password"); + } + int64_t now = esp_timer_get_time(); + store_lock(); + lock_t *lk = lock_slot(name, false); + if (lk && now < lk->until) { + store_unlock(); + cJSON_Delete(body); + return send_err(req, "429 Too Many Requests", "too many attempts for this user, wait and try again"); + } + const cJSON *u = cJSON_GetObjectItem(store_coll("user"), name); + uint8_t salt[16], want[32], got[32]; + bool ok = false; + if (u && from_hex(str_of(u, "salt"), salt, sizeof salt) && from_hex(str_of(u, "hash"), want, sizeof want)) { + pbkdf2(pw, salt, sizeof salt, PBKDF2_ITER, got); + ok = const_eq(got, want, sizeof got); + } else { + pbkdf2(pw, (const uint8_t *)"0000000000000000", 16, PBKDF2_ITER, got); // same work for unknown users + } + if (!ok) { + lk = lock_slot(name, true); + lk->fails++; + if (lk->fails >= 5) { + int shift = lk->fails - 5 > 4 ? 4 : lk->fails - 5; + int64_t wait = (30LL << shift) > 300 ? 300 : (30LL << shift); + lk->until = now + wait * 1000000; + } + store_unlock(); + cJSON_Delete(body); + return send_err(req, "401 Unauthorized", "wrong username or password"); + } + if (lk) { + lk->used = false; // a good sign-in clears this name's failures + } + char tok[TOKEN_LEN + 1]; + sess_new(name, tok); + cJSON *out = cJSON_CreateObject(); + cJSON_AddStringToObject(out, "user", name); + cJSON_AddStringToObject(out, "role", str_of(u, "role") ? str_of(u, "role") : ""); + store_unlock(); + cJSON_Delete(body); + + char ck[220]; + char proto[16] = ""; + bool secure = httpd_req_get_hdr_value_str(req, "X-Forwarded-Proto", proto, sizeof proto) == ESP_OK && !strcmp(proto, "https"); + snprintf(ck, sizeof ck, "%s=%s; Path=/; HttpOnly; SameSite=Strict; Max-Age=2592000%s", COOKIE, tok, secure ? "; Secure" : ""); + httpd_resp_set_hdr(req, "Set-Cookie", ck); + return send_json(req, "200 OK", out); +} + +static esp_err_t logout(httpd_req_t *req) +{ + char tok[TOKEN_LEN + 1]; + if (cookie_tok(req, tok)) { + store_lock(); + sess_drop_tok(tok); + store_unlock(); + } + httpd_resp_set_hdr(req, "Set-Cookie", COOKIE "=; Path=/; HttpOnly; SameSite=Strict; Max-Age=0"); + cJSON *o = cJSON_CreateObject(); + cJSON_AddBoolToObject(o, "ok", true); + return send_json(req, "200 OK", o); +} + +// Sets a password on a user record: a new salt and hash +static void set_password(cJSON *rec, const char *pw) +{ + uint8_t salt[16], hash[32]; + char hx[65]; + esp_fill_random(salt, sizeof salt); + pbkdf2(pw, salt, sizeof salt, PBKDF2_ITER, hash); + to_hex(salt, sizeof salt, hx); + obj_set(rec, "salt", cJSON_CreateString(hx)); + to_hex(hash, sizeof hash, hx); + obj_set(rec, "hash", cJSON_CreateString(hx)); +} + +static bool password_ok(const char *pw) +{ + return pw && strlen(pw) >= 8 && strlen(pw) <= 128; +} + +static esp_err_t password_put(httpd_req_t *req) +{ + cJSON *body = read_body(req); + const char *old = body ? str_of(body, "old") : NULL, *nw = body ? str_of(body, "new") : NULL; + char user[33], role[33]; + store_lock(); + esp_err_t r; + if (!session_of(req, user, sizeof user, role, sizeof role)) { + r = send_err(req, "401 Unauthorized", "login required"); + } else if (!old || !password_ok(nw)) { + r = send_err(req, "400 Bad Request", "send old and new (8 to 128 characters)"); + } else { + cJSON *rec = cJSON_GetObjectItem(store_coll("user"), user); + uint8_t salt[16], want[32], got[32]; + if (!from_hex(str_of(rec, "salt"), salt, sizeof salt) || !from_hex(str_of(rec, "hash"), want, sizeof want)) { + r = send_err(req, "500 Internal Server Error", "stored password is unreadable"); + } else { + pbkdf2(old, salt, sizeof salt, PBKDF2_ITER, got); + if (!const_eq(got, want, sizeof got)) { + r = send_err(req, "403 Forbidden", "current password is wrong"); + } else { + set_password(rec, nw); + store_save("user"); + cJSON *o = cJSON_CreateObject(); + cJSON_AddBoolToObject(o, "ok", true); + r = send_json(req, "200 OK", o); + } + } + } + store_unlock(); + cJSON_Delete(body); + return r; +} + +static esp_err_t user_create(httpd_req_t *req) +{ + cJSON *body = read_body(req); + const char *name = body ? str_of(body, "username") : NULL; + const char *pw = body ? str_of(body, "password") : NULL; + const char *role = body ? str_of(body, "role") : NULL; + esp_err_t r; + store_lock(); + if (!body || !valid_name(name)) { + r = send_err(req, "400 Bad Request", "username: 1 to 32 letters, digits, _ . -"); + } else if (!password_ok(pw)) { + r = send_err(req, "400 Bad Request", "password: 8 to 128 characters"); + } else if (!role || !cJSON_GetObjectItem(store_coll("role"), role)) { + r = send_err(req, "400 Bad Request", "unknown role"); + } else if (cJSON_GetObjectItem(store_coll("user"), name)) { + r = send_err(req, "409 Conflict", "that user exists"); + } else { + cJSON *rec = cJSON_CreateObject(); + cJSON_AddStringToObject(rec, "role", role); + set_password(rec, pw); + cJSON_AddItemToObject(store_coll("user"), name, rec); + store_save("user"); + cJSON *o = cJSON_CreateObject(); + cJSON_AddStringToObject(o, "username", name); + cJSON_AddStringToObject(o, "role", role); + r = send_json(req, "200 OK", o); + } + store_unlock(); + cJSON_Delete(body); + return r; +} + +static esp_err_t user_update(httpd_req_t *req, const char *name) +{ + cJSON *body = read_body(req); + const char *role = body ? str_of(body, "role") : NULL; + const char *pw = body ? str_of(body, "password") : NULL; + esp_err_t r; + store_lock(); + cJSON *rec = cJSON_GetObjectItem(store_coll("user"), name); + if (!body || !rec) { + r = send_err(req, body ? "404 Not Found" : "400 Bad Request", body ? "no such user" : "send role and/or password"); + } else if (!role && !pw) { + r = send_err(req, "400 Bad Request", "send role and/or password"); + } else if (role && !cJSON_GetObjectItem(store_coll("role"), role)) { + r = send_err(req, "400 Bad Request", "unknown role"); + } else if (pw && !password_ok(pw)) { + r = send_err(req, "400 Bad Request", "password: 8 to 128 characters"); + } else if (role && managers_after(name, role, 0) + (role_perm(role, "users") >= AUTH_EDIT ? 1 : 0) < 1) { + r = send_err(req, "400 Bad Request", "keep at least one user who can manage users"); + } else { + if (role) { + obj_set(rec, "role", cJSON_CreateString(role)); + } + if (pw) { + set_password(rec, pw); + sess_drop_user(name); + } + store_save("user"); + cJSON *o = cJSON_CreateObject(); + cJSON_AddStringToObject(o, "username", name); + cJSON_AddStringToObject(o, "role", str_of(rec, "role") ? str_of(rec, "role") : ""); + r = send_json(req, "200 OK", o); + } + store_unlock(); + cJSON_Delete(body); + return r; +} + +static esp_err_t user_delete(httpd_req_t *req, const char *name) +{ + esp_err_t r; + store_lock(); + if (!cJSON_GetObjectItem(store_coll("user"), name)) { + r = send_err(req, "404 Not Found", "no such user"); + } else if (managers_after(name, NULL, 0) < 1) { + r = send_err(req, "400 Bad Request", "keep at least one user who can manage users"); + } else { + cJSON_DeleteItemFromObject(store_coll("user"), name); + sess_drop_user(name); + store_save("user"); + cJSON *o = cJSON_CreateObject(); + cJSON_AddBoolToObject(o, "ok", true); + r = send_json(req, "200 OK", o); + } + store_unlock(); + return r; +} + +static esp_err_t role_create(httpd_req_t *req) +{ + cJSON *body = read_body(req); + const char *name = body ? str_of(body, "name") : NULL; + const char *err = NULL; + cJSON *perms = body ? perms_from_json(cJSON_GetObjectItem(body, "perms"), &err) : NULL; + esp_err_t r; + store_lock(); + if (!body || !valid_name(name)) { + r = send_err(req, "400 Bad Request", "name: 1 to 32 letters, digits, _ . -"); + } else if (!perms) { + r = send_err(req, "400 Bad Request", err ? err : "perms missing"); + } else if (cJSON_GetObjectItem(store_coll("role"), name)) { + r = send_err(req, "409 Conflict", "that role exists"); + } else { + cJSON_AddItemToObject(store_coll("role"), name, role_record(false, perms)); + perms = NULL; + store_save("role"); + cJSON *o = cJSON_CreateObject(); + cJSON_AddStringToObject(o, "name", name); + r = send_json(req, "200 OK", o); + } + cJSON_Delete(perms); + store_unlock(); + cJSON_Delete(body); + return r; +} + +static esp_err_t role_update(httpd_req_t *req, const char *name) +{ + cJSON *body = read_body(req); + const char *err = NULL; + cJSON *perms = body ? perms_from_json(cJSON_GetObjectItem(body, "perms"), &err) : NULL; + esp_err_t r; + store_lock(); + cJSON *old = cJSON_GetObjectItem(store_coll("role"), name); + if (!old) { + r = send_err(req, "404 Not Found", "no such role"); + } else if (!perms) { + r = send_err(req, "400 Bad Request", err ? err : "send perms"); + } else if (!strcmp(name, "admin") && !all_edit(perms)) { + r = send_err(req, "400 Bad Request", "the admin role keeps edit everywhere"); + } else if (managers_after(NULL, name, cJSON_GetObjectItem(perms, "users")->valueint) < 1) { + r = send_err(req, "400 Bad Request", "keep at least one user who can manage users"); + } else { + obj_set(old, "perms", perms); + perms = NULL; + store_save("role"); + cJSON *o = cJSON_CreateObject(); + cJSON_AddStringToObject(o, "name", name); + r = send_json(req, "200 OK", o); + } + cJSON_Delete(perms); + store_unlock(); + cJSON_Delete(body); + return r; +} + +static esp_err_t role_delete(httpd_req_t *req, const char *name) +{ + esp_err_t r; + store_lock(); + const cJSON *role = cJSON_GetObjectItem(store_coll("role"), name); + bool in_use = false; + const cJSON *u = NULL; + cJSON_ArrayForEach(u, store_coll("user")) + { + if (str_of(u, "role") && !strcmp(str_of(u, "role"), name)) { + in_use = true; + } + } + if (!role) { + r = send_err(req, "404 Not Found", "no such role"); + } else if (!strcmp(name, "admin") || !strcmp(name, "guest")) { + r = send_err(req, "400 Bad Request", "the built-in roles cannot be deleted"); + } else if (in_use) { + r = send_err(req, "400 Bad Request", "a user has this role: move them first"); + } else { + cJSON_DeleteItemFromObject(store_coll("role"), name); + store_save("role"); + cJSON *o = cJSON_CreateObject(); + cJSON_AddBoolToObject(o, "ok", true); + r = send_json(req, "200 OK", o); + } + store_unlock(); + return r; +} + +// GET /auth: who is signed in and what they may do (guest's permissions when signed out) +static esp_err_t status_get(httpd_req_t *req) +{ + char user[33] = "", role[33] = ""; + store_lock(); + bool enabled = auth_enabled_locked(); + bool signed_in = enabled && session_of(req, user, sizeof user, role, sizeof role); + if (enabled && !signed_in) { + snprintf(role, sizeof role, "%s", "guest"); + } + cJSON *o = cJSON_CreateObject(); + cJSON_AddBoolToObject(o, "enabled", enabled); + cJSON_AddStringToObject(o, "user", signed_in ? user : ""); + cJSON_AddStringToObject(o, "role", enabled ? role : "admin"); + cJSON *perms = cJSON_CreateObject(); + for (int i = 0; i < AREA_N; i++) { + cJSON_AddNumberToObject(perms, AREAS[i], enabled ? role_perm(role, AREAS[i]) : AUTH_EDIT); + } + cJSON_AddItemToObject(o, "perms", perms); + store_unlock(); + return send_json(req, "200 OK", o); +} + +static esp_err_t auth_route(httpd_req_t *req) +{ + char path[128]; + size_t len = strcspn(req->uri, "?"); + if (len >= sizeof(path)) { + return send_err(req, "414 URI Too Long", "uri too long"); + } + memcpy(path, req->uri, len); + path[len] = 0; + // path is /auth[/[/]]: the first segment is always "auth" + char *s1 = NULL, *s2 = NULL; + char *slash = strchr(path + 1, '/'); + if (slash) { + *slash = 0; + s1 = slash + 1; + char *q = strchr(s1, '/'); + if (q) { + *q = 0; + s2 = q + 1; + } + } + const char *what = s1 ? s1 : ""; + const int m = req->method; + + if (!*what && m == HTTP_GET) { + return status_get(req); + } + if (!strcmp(what, "login") && m == HTTP_POST) { + return login(req); + } + if (!strcmp(what, "logout") && m == HTTP_POST) { + return logout(req); + } + if (!strcmp(what, "password") && m == HTTP_PUT) { + return password_put(req); + } + if (!strcmp(what, "users")) { + if (!s2 && m == HTTP_GET) { + return users_list(req); + } + if (!s2 && m == HTTP_POST) { + return user_create(req); + } + if (s2 && m == HTTP_PUT) { + return user_update(req, s2); + } + if (s2 && m == HTTP_DELETE) { + return user_delete(req, s2); + } + } + if (!strcmp(what, "roles")) { + if (!s2 && m == HTTP_GET) { + return roles_list(req); + } + if (!s2 && m == HTTP_POST) { + return role_create(req); + } + if (s2 && m == HTTP_PUT) { + return role_update(req, s2); + } + if (s2 && m == HTTP_DELETE) { + return role_delete(req, s2); + } + } + return send_err(req, "404 Not Found", "unknown auth route"); +} + +esp_err_t auth_register(httpd_handle_t server) +{ + static const httpd_method_t METHODS[] = { HTTP_GET, HTTP_POST, HTTP_PUT, HTTP_DELETE }; + for (size_t m = 0; m < 4; m++) { + httpd_uri_t u = { .uri = "/auth*", .method = METHODS[m], .handler = auth_route }; + esp_err_t err = auth_register_uri(server, &u); + if (err != ESP_OK) { + return err; + } + } + return ESP_OK; +} diff --git a/main/auth.h b/main/auth.h new file mode 100644 index 0000000..528b75c --- /dev/null +++ b/main/auth.h @@ -0,0 +1,46 @@ +#pragma once + +#include +#include "cJSON.h" +#include "esp_err.h" +#include "esp_http_server.h" + +// Users, roles and per-area permissions. Auth is off until the first user exists: then every +// request is allowed, so a LAN controller or a fresh device behaves as before. Once a user +// exists, each request needs a session cookie and a role with enough permission for its area. + +typedef enum { + AUTH_NONE = 0, + AUTH_VIEW = 1, // read + AUTH_CONTROL = 2, // play, stop, brightness, identify and the like + AUTH_EDIT = 3, // create, change, delete, import, settings +} auth_level_t; + +// What a request needs. pub: no check. An area starting with '@' only needs a signed-in user. +typedef struct { + const char *area; + auth_level_t level; + bool pub; +} auth_need_t; + +// Creates the built-in roles (admin, guest) and the admin named by LED_ADMIN_USER / LED_ADMIN_PASSWORD +esp_err_t auth_init(void); + +// Routes under /auth (login, logout, password, users, roles) +esp_err_t auth_register(httpd_handle_t server); + +// The permission a request needs, from its URI and method +auth_need_t auth_classify(const char *uri, int method); + +// Registers a route behind the permission check (wraps its handler) +esp_err_t auth_register_uri(httpd_handle_t server, const httpd_uri_t *u); + +// True when the request may do this (auth off, or a session whose role has the level) +bool auth_can(httpd_req_t *req, const char *area, auth_level_t level); + +// WebSocket routes are not wrapped: the handshake records who opened the socket, and each frame checks it +esp_err_t auth_ws_admit(httpd_req_t *req, const char *area, auth_level_t level); +bool auth_ws_allowed(int fd, const char *area, auth_level_t level); + +// The users without their password hashes, for the /db export +cJSON *auth_export_users(void); diff --git a/main/bridge.c b/main/bridge.c index a97d077..8901fd4 100644 --- a/main/bridge.c +++ b/main/bridge.c @@ -14,6 +14,8 @@ #include "bridge_proto.h" #if CONFIG_IDF_TARGET_LINUX #include "bridge_serial.h" +#else +typedef struct bridge_serial bridge_serial_t; // serial boards are linux-only; the device never opens one #endif static const char *TAG = "bridge"; diff --git a/main/main.c b/main/main.c index e1d9ffd..765f1cd 100644 --- a/main/main.c +++ b/main/main.c @@ -1,6 +1,7 @@ /* * v2 controller: W5500 Ethernet, INMP441 beat detection, ESP-NOW master. */ +#include "auth.h" #include #include #include "freertos/FreeRTOS.h" @@ -308,7 +309,7 @@ static void start_webserver(void) return; } const httpd_uri_t status_uri = { .uri = "/status", .method = HTTP_GET, .handler = status_get_handler }; - httpd_register_uri_handler(s_server, &status_uri); + auth_register_uri(s_server, &status_uri); web_register(s_server); audio_register(s_server); audio_api_register(s_server); diff --git a/main/ota.c b/main/ota.c index caa350b..ad9f13e 100644 --- a/main/ota.c +++ b/main/ota.c @@ -1,3 +1,4 @@ +#include "auth.h" #include "ota.h" #include @@ -174,13 +175,13 @@ esp_err_t ota_register(httpd_handle_t server) { const httpd_uri_t post = { .uri = "/ota", .method = HTTP_POST, .handler = ota_post_handler }; const httpd_uri_t get = { .uri = "/ota", .method = HTTP_GET, .handler = ota_get_handler }; - esp_err_t err = httpd_register_uri_handler(server, &post); + esp_err_t err = auth_register_uri(server, &post); if (err == ESP_OK) { - err = httpd_register_uri_handler(server, &get); + err = auth_register_uri(server, &get); } const httpd_uri_t reboot = { .uri = "/reboot", .method = HTTP_POST, .handler = reboot_post_handler }; if (err == ESP_OK) { - err = httpd_register_uri_handler(server, &reboot); + err = auth_register_uri(server, &reboot); } return err; } diff --git a/main/store.c b/main/store.c index 6df4010..8cf6445 100644 --- a/main/store.c +++ b/main/store.c @@ -28,7 +28,7 @@ static const char *db_root(void) static const char *const NAMES[] = { "device", "zone", "preset", "profile", "palette", "pattern", - "sequence", "scene", "group", "output", "settings", + "sequence", "scene", "group", "output", "settings", "user", "role", }; #define N_COLL (sizeof(NAMES) / sizeof(NAMES[0])) diff --git a/main/web.c b/main/web.c index 66f6b7e..f0f5b82 100644 --- a/main/web.c +++ b/main/web.c @@ -1,3 +1,4 @@ +#include "auth.h" #include "web.h" #include @@ -182,7 +183,7 @@ esp_err_t web_register(httpd_handle_t server) { .uri = "/favicon.ico", .method = HTTP_GET, .handler = favicon_handler }, }; for (size_t i = 0; i < sizeof(uris) / sizeof(uris[0]); i++) { - esp_err_t err = httpd_register_uri_handler(server, &uris[i]); + esp_err_t err = auth_register_uri(server, &uris[i]); if (err != ESP_OK) { ESP_LOGE(TAG, "register %s: %s", uris[i].uri, esp_err_to_name(err)); return err; diff --git a/main/ws.c b/main/ws.c index 9b4e7d5..706c984 100644 --- a/main/ws.c +++ b/main/ws.c @@ -1,3 +1,4 @@ +#include "auth.h" #include "ws.h" #include @@ -49,6 +50,9 @@ static void forward(httpd_req_t *req, const char *text) // snapshot is always empty. static esp_err_t on_open(httpd_req_t *req) { + if (auth_ws_admit(req, "devices", AUTH_CONTROL) != ESP_OK) { + return ESP_FAIL; // closes the socket: driving drivers needs devices control + } send_text(req, "{\"type\":\"device_tcp_snapshot\",\"connected_ips\":[]}"); return ESP_OK; } @@ -80,7 +84,11 @@ static esp_err_t ws_handler(httpd_req_t *req) err = httpd_ws_recv_frame(req, &f, f.len); if (err == ESP_OK) { buf[f.len] = 0; - forward(req, buf); + if (auth_ws_allowed(httpd_req_to_sockfd(req), "devices", AUTH_CONTROL)) { + forward(req, buf); + } else { + send_text(req, "{\"error\":\"not allowed\"}"); + } } free(buf); return err; diff --git a/sim-controller/components/sim/sim_main.c b/sim-controller/components/sim/sim_main.c index 20fa154..fcfe54e 100644 --- a/sim-controller/components/sim/sim_main.c +++ b/sim-controller/components/sim/sim_main.c @@ -10,6 +10,7 @@ * LED_SIM_HTTP_PORT web UI / API port, default 8080 * The store is the /db directory (mount a volume there to keep it). */ +#include "auth.h" #include #include #include @@ -98,7 +99,7 @@ static void start_webserver(void) abort(); } const httpd_uri_t status_uri = { .uri = "/status", .method = HTTP_GET, .handler = status_get_handler }; - httpd_register_uri_handler(server, &status_uri); + auth_register_uri(server, &status_uri); sim_rig_register(server); web_register(server); audio_register(server); diff --git a/sim-controller/components/sim/sim_rig.c b/sim-controller/components/sim/sim_rig.c index 60f99da..4980a2d 100644 --- a/sim-controller/components/sim/sim_rig.c +++ b/sim-controller/components/sim/sim_rig.c @@ -22,6 +22,7 @@ * "direction" the way it runs (degrees clockwise from +y), "mac" the driver. Each bar's flash is * /sim/flash/.json, so a bar keeps its presets in every room it appears in. */ +#include "auth.h" #include "sim_rig.h" #include @@ -630,6 +631,9 @@ bool sim_rig_tx(const uint8_t *frame, size_t len) static esp_err_t ws_open(httpd_req_t *req) { + if (auth_ws_admit(req, "sim", AUTH_VIEW) != ESP_OK) { + return ESP_FAIL; + } int fd = httpd_req_to_sockfd(req); xSemaphoreTake(s_tx_mu, portMAX_DELAY); int old = page_open_locked() ? s_page_fd : -1; @@ -686,6 +690,9 @@ static esp_err_t ws_handler(httpd_req_t *req) } f.payload = buf; err = httpd_ws_recv_frame(req, &f, f.len); + if (err == ESP_OK && !auth_ws_allowed(httpd_req_to_sockfd(req), "sim", AUTH_VIEW)) { + err = ESP_FAIL; // closes the socket: the socket was not admitted at its handshake + } if (err == ESP_OK) { buf[f.len] = 0; if (f.type == HTTPD_WS_TYPE_BINARY) { @@ -981,15 +988,15 @@ esp_err_t sim_rig_register(httpd_handle_t server) static const httpd_method_t METHODS[] = { HTTP_GET, HTTP_POST, HTTP_PUT, HTTP_DELETE }; for (size_t i = 0; i < 4 && err == ESP_OK; i++) { const httpd_uri_t u = { .uri = "/sim/api/*", .method = METHODS[i], .handler = api_handler }; - err = httpd_register_uri_handler(server, &u); + err = auth_register_uri(server, &u); } const httpd_uri_t root = { .uri = "/sim", .method = HTTP_GET, .handler = page_handler }; const httpd_uri_t files = { .uri = "/sim/*", .method = HTTP_GET, .handler = page_handler }; if (err == ESP_OK) { - err = httpd_register_uri_handler(server, &root); + err = auth_register_uri(server, &root); } if (err == ESP_OK) { - err = httpd_register_uri_handler(server, &files); + err = auth_register_uri(server, &files); } if (err != ESP_OK) { ESP_LOGE(TAG, "register: %s", esp_err_to_name(err)); diff --git a/sim-controller/components/sim/sim_stubs.c b/sim-controller/components/sim/sim_stubs.c index 11bc671..b902ef5 100644 --- a/sim-controller/components/sim/sim_stubs.c +++ b/sim-controller/components/sim/sim_stubs.c @@ -1,4 +1,5 @@ // Host build: what the board's hardware files (mic.c, ota.c, littlefs) provide, without hardware +#include "auth.h" #include #include #include "esp_littlefs.h" @@ -60,5 +61,5 @@ static esp_err_t ota_unsupported(httpd_req_t *req) esp_err_t ota_register(httpd_handle_t server) { const httpd_uri_t u = { .uri = "/ota", .method = HTTP_POST, .handler = ota_unsupported }; - return httpd_register_uri_handler(server, &u); + return auth_register_uri(server, &u); } diff --git a/test/api/conftest.py b/test/api/conftest.py index 5bbeec5..3aa8325 100644 --- a/test/api/conftest.py +++ b/test/api/conftest.py @@ -75,12 +75,18 @@ def restore_db(request): yield return client = request.getfixturevalue("c") + if client.get("/auth").json().get("enabled"): + # test_auth.py turned sign-in on: the snapshot needs editor rights, so the data is left as it is + yield + return snapshot = {} for name in COLLECTIONS: resp = client.get(f"/db/{name}") resp.raise_for_status() snapshot[name] = resp.json() yield snapshot + if client.get("/auth").json().get("enabled"): + return # test_auth.py switched sign-in on during the run: it cannot be restored without an admin failed = [] for name, data in snapshot.items(): resp = client.put(f"/db/{name}", json=data) diff --git a/test/api/test_auth.py b/test/api/test_auth.py new file mode 100644 index 0000000..09e9c34 --- /dev/null +++ b/test/api/test_auth.py @@ -0,0 +1,172 @@ +"""Users, roles and permissions. + +These turn auth on for the controller they run against, and the API cannot turn it off again (the last +admin cannot be removed). Run them only against a throwaway controller, and set LED_AUTH_TEST=1 to confirm: + + LED_AUTH_TEST=1 python -m pytest test_auth.py --host 127.0.0.1:8091 +""" + +import os +import time +import uuid + +import pytest +import requests + +TIMEOUT = 10 +ADMIN_PW = "admin-pass-1234" +OP_PW = "operator-pass-1234" + + +def _base(host): + return host if host.startswith("http") else f"http://{host}" + + +@pytest.fixture(scope="module") +def host(request): + h = request.config.getoption("--host") or os.environ.get("LED_HOST") + if not h: + pytest.skip("no controller: pass --host or set LED_HOST") + if os.environ.get("LED_AUTH_TEST") != "1": + pytest.skip("auth tests switch auth on for good: set LED_AUTH_TEST=1 on a throwaway controller") + return _base(h) + + +def anon(host): + s = requests.Session() + s.headers.update({"User-Agent": "pytest/requests", "Accept": "application/json"}) + s.base = host + return s + + +def call(s, method, path, **kw): + kw.setdefault("timeout", TIMEOUT) + return s.request(method, s.base + path, **kw) + + +def login(host, user, pw): + s = anon(host) + r = call(s, "POST", "/auth/login", json={"username": user, "password": pw}) + assert r.status_code == 200, r.text + return s + + +@pytest.fixture(scope="module") +def admin(host): + """Creates the first admin (open while no user exists), then signs in as them.""" + st = call(anon(host), "GET", "/auth").json() + if st.get("enabled"): + pytest.skip("this controller already has users: run against a fresh one") + name = "admin" + uuid.uuid4().hex[:6] + r = call(anon(host), "POST", "/auth/users", json={"username": name, "password": ADMIN_PW, "role": "admin"}) + assert r.status_code == 200, r.text + return login(host, name, ADMIN_PW) + + +def test_open_until_first_user(host): + s = anon(host) + st = call(s, "GET", "/auth").json() + if st["enabled"]: + pytest.skip("auth already on") + assert call(s, "GET", "/presets").status_code == 200 + created = call(s, "POST", "/presets", json={"name": "auth-open-" + uuid.uuid4().hex[:6]}) + assert created.status_code in (200, 201), created.text + + +def test_signed_out_reads_and_edits(host, admin): + s = anon(host) + assert call(s, "GET", "/presets").status_code == 200 # guest role: view + assert call(s, "GET", "/zones").status_code == 200 + assert call(s, "POST", "/presets", json={"name": "nope"}).status_code == 401 # signed out: login required + assert call(s, "GET", "/auth/users").status_code == 401 # users area is not in the guest role + + +def test_signed_out_has_no_settings_or_users(host, admin): + s = anon(host) + assert call(s, "GET", "/settings").status_code == 401 # guest role: no settings view + assert call(s, "GET", "/db/user").status_code == 401 + + +def test_viewer_does_not_see_wifi_password(host, admin): + role = "view" + uuid.uuid4().hex[:6] + perms = {"presets": 1, "sequences": 1, "zones": 1, "groups": 1, "devices": 1, "outputs": 1, + "patterns": 1, "sim": 1, "settings": 1, "users": 0} + assert call(admin, "POST", "/auth/roles", json={"name": role, "perms": perms}).status_code == 200 + user = "v" + uuid.uuid4().hex[:6] + assert call(admin, "POST", "/auth/users", json={"username": user, "password": OP_PW, "role": role}).status_code == 200 + viewer = login(host, user, OP_PW) + r = call(viewer, "GET", "/settings") + assert r.status_code == 200 + assert "ap_password" not in r.json() + assert call(viewer, "PUT", "/settings", json={"global_brightness": 10}).status_code == 403 + + +def test_password_hashes_never_returned(host, admin): + for path in ("/auth/users", "/db/user", "/auth"): + text = call(admin, "GET", path).text + assert "hash" not in text and "salt" not in text, path + + +def test_wrong_password_refused(host, admin): + r = call(anon(host), "POST", "/auth/login", json={"username": "nobody-here", "password": "x" * 9}) + assert r.status_code == 401 + + +def test_admin_can_edit(host, admin): + r = call(admin, "POST", "/presets", json={"name": "auth-admin-" + uuid.uuid4().hex[:6]}) + assert r.status_code in (200, 201), r.text + + +def test_custom_role_and_its_limits(host, admin): + role = "op" + uuid.uuid4().hex[:6] + perms = {"presets": 1, "sequences": 2, "zones": 1, "groups": 1, "devices": 1, "outputs": 1, + "patterns": 1, "sim": 1, "settings": 0, "users": 0} + assert call(admin, "POST", "/auth/roles", json={"name": role, "perms": perms}).status_code == 200 + user = "u" + uuid.uuid4().hex[:6] + assert call(admin, "POST", "/auth/users", json={"username": user, "password": OP_PW, "role": role}).status_code == 200 + op = login(host, user, OP_PW) + assert call(op, "POST", "/presets", json={"name": "x"}).status_code == 403 # view only on presets + assert call(op, "GET", "/auth/users").status_code == 403 # no users area + assert call(op, "POST", "/sequences/1/play", json={"zone_id": "1"}).status_code not in (401, 403) # control + assert call(op, "POST", "/sequences", json={}).status_code == 403 # editing sequences needs edit + + # raising the role takes effect at once, for a session that already exists + perms["sequences"] = 3 + assert call(admin, "PUT", f"/auth/roles/{role}", json={"perms": perms}).status_code == 200 + assert call(op, "POST", "/sequences", json={}).status_code != 403 + + # logging out drops the session + assert call(op, "POST", "/auth/logout").status_code == 200 + assert call(op, "GET", "/auth/users").status_code == 401 + + +def test_admin_role_is_fixed(host, admin): + perms = {a: 3 for a in ["presets", "sequences", "zones", "groups", "devices", "outputs", "patterns", "sim", + "settings", "users"]} + perms["users"] = 2 + assert call(admin, "PUT", "/auth/roles/admin", json={"perms": perms}).status_code == 400 + assert call(admin, "DELETE", "/auth/roles/admin").status_code == 400 + + +def test_last_manager_cannot_be_removed(host, admin): + me = call(admin, "GET", "/auth").json()["user"] + assert me + r = call(admin, "DELETE", f"/auth/users/{me}") + assert r.status_code == 400, r.text + + +def test_unknown_area_in_perms_refused(host, admin): + r = call(admin, "POST", "/auth/roles", json={"name": "bad" + uuid.uuid4().hex[:4], "perms": {"nope": 3}}) + assert r.status_code == 400 + + +def test_login_lockout(host, admin): + s = anon(host) + codes = [call(s, "POST", "/auth/login", json={"username": "nobody-x", "password": "wrong-wrong"}).status_code + for _ in range(6)] + assert 429 in codes and codes[-1] == 429, codes + # the lock is per username: the admin can still sign in while the other name is locked + me = call(admin, "GET", "/auth").json()["user"] + assert call(anon(host), "POST", "/auth/login", json={"username": me, "password": ADMIN_PW}).status_code == 200 + time.sleep(31) # the first lock is 30 seconds + assert call(anon(host), "POST", "/auth/login", json={"username": "nobody-x", "password": "wrong-wrong"}).status_code == 401 diff --git a/web/static/auth.js b/web/static/auth.js new file mode 100644 index 0000000..c08b65c --- /dev/null +++ b/web/static/auth.js @@ -0,0 +1,424 @@ +// Sign-in, users and roles. Loaded before the other scripts, so every request the page makes goes +// through the permission handling below: a 401 asks for a sign-in and then retries, a 403 shows a notice. +(function () { + 'use strict'; + + var AREAS = ['presets', 'sequences', 'zones', 'groups', 'devices', 'outputs', 'patterns', 'sim', 'settings', 'users']; + var AREA_LABELS = { + presets: 'Presets', sequences: 'Sequences', zones: 'Zones & profiles', groups: 'Groups', devices: 'Devices', + outputs: 'Outputs', patterns: 'Patterns & palettes', sim: 'Simulator', settings: 'Settings & updates', users: 'Users & roles', + }; + var LEVELS = ['none', 'view', 'control', 'edit']; + var state = { enabled: false, user: '', role: '', perms: {} }; + var origFetch = window.fetch.bind(window); + var pendingLogin = null; + + function esc(s) { + return String(s == null ? '' : s).replace(/[&<>"']/g, function (c) { + return { '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]; + }); + } + + function isAuthUrl(url) { + return String(url).indexOf('/auth') === 0; + } + + function can(area, level) { + return !state.enabled || (state.perms[area] || 0) >= level; + } + + function errorText(res) { + return res.json().then(function (j) { return j.error || ('Error ' + res.status); }, function () { return 'Error ' + res.status; }); + } + + /* ------------------------------------------------------------ styles and small UI */ + + function injectStyle() { + var st = document.createElement('style'); + st.textContent = [ + '[data-need][hidden]{display:none !important}', + '.auth-toast{position:fixed;left:50%;bottom:24px;transform:translateX(-50%);background:#3a1d1d;color:#fff;padding:10px 16px;border-radius:8px;z-index:10000;box-shadow:0 4px 16px rgba(0,0,0,.35);max-width:90vw;font-size:14px}', + '.auth-backdrop{position:fixed;inset:0;background:rgba(0,0,0,.55);display:flex;align-items:center;justify-content:center;z-index:9000;padding:16px}', + '.auth-dialog{background:var(--panel,#1e1e24);color:var(--text,#eee);border-radius:10px;padding:18px;min-width:280px;max-width:900px;width:100%;max-height:90vh;overflow:auto;box-shadow:0 8px 32px rgba(0,0,0,.5)}', + '.auth-dialog h3{margin:0 0 12px}', + '.auth-dialog label{display:block;margin:8px 0 4px;font-size:13px;opacity:.85}', + '.auth-dialog input,.auth-dialog select{width:100%;box-sizing:border-box;padding:6px 8px;border-radius:6px;border:1px solid #555;background:#111;color:#eee}', + '.auth-dialog table{border-collapse:collapse;width:100%;margin:8px 0}', + '.auth-dialog th,.auth-dialog td{padding:6px 8px;border-bottom:1px solid #333;text-align:left;font-size:13px}', + '.auth-dialog .auth-row{display:flex;gap:8px;align-items:center;flex-wrap:wrap}', + '.auth-dialog .auth-actions{display:flex;gap:8px;justify-content:flex-end;margin-top:14px;flex-wrap:wrap}', + '.auth-dialog button{padding:6px 12px;border-radius:6px;border:1px solid #555;background:#2a2a33;color:#eee;cursor:pointer}', + '.auth-dialog button.primary{background:#2d6cdf;border-color:#2d6cdf}', + '.auth-dialog button.danger{background:#7a2323;border-color:#7a2323}', + '.auth-err{color:#ff8a8a;font-size:13px;min-height:1em;margin-top:6px}', + '.auth-button{margin-left:8px;padding:4px 10px;border-radius:6px;border:1px solid #555;background:#2a2a33;color:#eee;cursor:pointer;font-size:13px;white-space:nowrap}', + ].join('\n'); + document.head.appendChild(st); + } + + function toast(msg) { + var t = document.createElement('div'); + t.className = 'auth-toast'; + t.textContent = msg; + document.body.appendChild(t); + setTimeout(function () { t.remove(); }, 3500); + } + + // A modal dialog. build(body) fills it; it returns a close function. + function dialog(title, build) { + var back = document.createElement('div'); + back.className = 'auth-backdrop'; + back.innerHTML = ''; + document.body.appendChild(back); + var body = back.querySelector('.auth-body'); + function close() { + back.remove(); + document.removeEventListener('keydown', onKey); + } + function onKey(e) { + if (e.key === 'Escape') { + close(); + } + } + back.addEventListener('mousedown', function (e) { + if (e.target === back) { + close(); + } + }); + document.addEventListener('keydown', onKey); + build(body, close); + return close; + } + + /* ------------------------------------------------------------ state */ + + function refresh() { + return origFetch('/auth', { credentials: 'same-origin' }) + .then(function (r) { return r.json(); }) + .then(function (s) { + state = s; + applyPerms(); + return s; + }) + .catch(function () { return state; }); + } + + function applyPerms() { + document.body.dataset.authRole = state.role || ''; + document.body.dataset.authUser = state.user || ''; + document.querySelectorAll('[data-need]').forEach(function (el) { + var need = el.getAttribute('data-need').split(':'); + el.hidden = !can(need[0], LEVELS.indexOf(need[1])); + }); + var btn = document.getElementById('auth-button'); + if (btn) { + btn.textContent = !state.enabled ? 'Set up users' : state.user ? state.user + ' (' + state.role + ')' : 'Sign in'; + } + } + + /* ------------------------------------------------------------ sign in */ + + function askLogin() { + if (pendingLogin) { + return pendingLogin; + } + pendingLogin = new Promise(function (resolve) { + dialog('Sign in', function (body, close) { + body.innerHTML = [ + '
', + '', + '', + '
', + '
', + '
', + ].join(''); + var form = body.querySelector('form'); + body.querySelector('#auth-user').focus(); + body.querySelector('#auth-cancel').onclick = function () { close(); resolve(false); }; + form.onsubmit = function (e) { + e.preventDefault(); + var user = body.querySelector('#auth-user').value.trim(), pw = body.querySelector('#auth-pass').value; + origFetch('/auth/login', { + method: 'POST', credentials: 'same-origin', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ username: user, password: pw }), + }).then(function (res) { + if (!res.ok) { + return errorText(res).then(function (m) { body.querySelector('#auth-err').textContent = m; }); + } + close(); + return refresh().then(function () { resolve(true); }); + }); + }; + }); + }).then(function (ok) { + pendingLogin = null; + return ok; + }); + return pendingLogin; + } + + function changePassword() { + dialog('Change password', function (body, close) { + body.innerHTML = [ + '
', + '', + '', + '
', + '
', + '
', + ].join(''); + body.querySelector('#auth-cancel').onclick = close; + body.querySelector('form').onsubmit = function (e) { + e.preventDefault(); + origFetch('/auth/password', { + method: 'PUT', credentials: 'same-origin', headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ old: body.querySelector('#auth-old').value, new: body.querySelector('#auth-new').value }), + }).then(function (res) { + if (!res.ok) { + return errorText(res).then(function (m) { body.querySelector('#auth-err').textContent = m; }); + } + close(); + toast('Password changed'); + }); + }; + }); + } + + function signOut() { + origFetch('/auth/logout', { method: 'POST', credentials: 'same-origin' }).then(refresh).then(function () { + toast('Signed out'); + }); + } + + /* ------------------------------------------------------------ users and roles */ + + function usersAndRoles() { + dialog('Users & roles', function (body) { + body.innerHTML = '
Loading…
'; + var err = body.querySelector('#auth-err'); + var content = body.querySelector('#auth-content'); + var roles = []; + + function req(method, url, data) { + err.textContent = ''; + return origFetch(url, { + method: method, credentials: 'same-origin', + headers: data ? { 'Content-Type': 'application/json' } : undefined, + body: data ? JSON.stringify(data) : undefined, + }).then(function (res) { + if (!res.ok) { + return errorText(res).then(function (m) { err.textContent = m; throw new Error(m); }); + } + return res.json().catch(function () { return {}; }); + }); + } + + function roleOptions(selected) { + return roles.map(function (r) { + return ''; + }).join(''); + } + + function render(users) { + var userRows = users.map(function (u) { + return '' + esc(u.username) + '' + + '' + + '' + + ''; + }).join(''); + var head = 'Area' + roles.map(function (r) { return '' + esc(r.name) + ''; }).join('') + ''; + var matrix = AREAS.map(function (a) { + return '' + esc(AREA_LABELS[a]) + '' + roles.map(function (r) { + var lvl = (r.perms && r.perms[a]) || 0; + var locked = r.name === 'admin'; + return ''; + }).join('') + ''; + }).join(''); + content.innerHTML = [ + '

Users

', + '' + (userRows || '') + '
UsernameRole
No users yet
', + '
', + '', + '', + '
', + '

Permissions

', + '

none: hidden · view: read · control: play, stop, brightness, identify · edit: change anything.

', + '
' + head + matrix + '
', + '
', + '', + '
', + '
' + roles.filter(function (r) { return !r.builtin; }).map(function (r) { + return ''; + }).join(' ') + '
', + ].join(''); + wire(); + } + + function wire() { + content.querySelectorAll('[data-user-role]').forEach(function (sel) { + sel.onchange = function () { + req('PUT', '/auth/users/' + encodeURIComponent(sel.dataset.userRole), { role: sel.value }) + .then(load, function () { load(); }); + }; + }); + content.querySelectorAll('[data-reset]').forEach(function (b) { + b.onclick = function () { + var pw = window.prompt('New password for ' + b.dataset.reset + ' (8 to 128 characters)'); + if (pw) { + req('PUT', '/auth/users/' + encodeURIComponent(b.dataset.reset), { password: pw }).then(load, function () {}); + } + }; + }); + content.querySelectorAll('[data-delete-user]').forEach(function (b) { + b.onclick = function () { + if (window.confirm('Delete user ' + b.dataset.deleteUser + '?')) { + req('DELETE', '/auth/users/' + encodeURIComponent(b.dataset.deleteUser)).then(load, function () {}); + } + }; + }); + content.querySelector('#add-user').onclick = function () { + req('POST', '/auth/users', { + username: content.querySelector('#new-user').value.trim(), + password: content.querySelector('#new-pass').value, + role: content.querySelector('#new-role').value, + }).then(load, function () {}); + }; + content.querySelector('#add-role').onclick = function () { + var name = content.querySelector('#new-role-name').value.trim(); + var perms = {}; + AREAS.forEach(function (a) { perms[a] = 0; }); + req('POST', '/auth/roles', { name: name, perms: perms }).then(load, function () {}); + }; + content.querySelector('#save-roles').onclick = function () { + var jobs = roles.filter(function (r) { return r.name !== 'admin'; }).map(function (r) { + var perms = {}; + AREAS.forEach(function (a) { + var sel = content.querySelector('[data-perm-role="' + r.name + '"][data-area="' + a + '"]'); + perms[a] = sel ? parseInt(sel.value, 10) : 0; + }); + return req('PUT', '/auth/roles/' + encodeURIComponent(r.name), { perms: perms }); + }); + Promise.all(jobs).then(function () { toast('Permissions saved'); load(); }, function () { load(); }); + }; + content.querySelectorAll('[data-delete-role]').forEach(function (b) { + b.onclick = function () { + if (window.confirm('Delete role ' + b.dataset.deleteRole + '?')) { + req('DELETE', '/auth/roles/' + encodeURIComponent(b.dataset.deleteRole)).then(load, function () {}); + } + }; + }); + } + + function load() { + Promise.all([req('GET', '/auth/roles'), req('GET', '/auth/users')]).then(function (res) { + try { + roles = res[0]; + render(res[1]); + } catch (e) { + err.textContent = 'Could not show users and roles: ' + e.message; + } + }, function () { + if (!err.textContent) { + err.textContent = 'Could not load users and roles'; + } + }); + } + + load(); + }); + } + + /* ------------------------------------------------------------ header button */ + + function accountMenu() { + dialog(state.user ? 'Signed in as ' + state.user : 'Users', function (body, close) { + var rows = []; + if (!state.enabled) { + rows.push('

No users yet, so anyone can edit. Create the first admin to turn sign-in on.

'); + } + rows.push('
'); + if (!state.user && state.enabled) { + rows.push(''); + } + if (state.user) { + rows.push(''); + rows.push(''); + } + if (can('users', AREA_EDIT_LEVEL)) { + rows.push(''); + } + rows.push('
'); + body.innerHTML = rows.join(''); + var bind = function (id, fn) { var el = body.querySelector('#' + id); if (el) { el.onclick = function () { close(); fn(); }; } }; + bind('auth-do-login', askLogin); + bind('auth-do-pass', changePassword); + bind('auth-do-out', signOut); + bind('auth-do-users', usersAndRoles); + body.querySelector('#auth-do-close').onclick = close; + }); + } + + var AREA_EDIT_LEVEL = 3; + + function addHeaderButton() { + // Beside the Menu button, which stays visible; the header actions inside the menu are hidden until it opens + var menu = document.getElementById('main-menu-btn'); + var host = menu ? menu.parentElement : document.querySelector('header'); + if (!host || document.getElementById('auth-button')) { + return; + } + var btn = document.createElement('button'); + btn.id = 'auth-button'; + btn.type = 'button'; + btn.className = 'auth-button'; + btn.title = 'Sign in, change password, users and roles'; + btn.onclick = accountMenu; + host.insertBefore(btn, menu || host.firstChild); + applyPerms(); + } + + /* ------------------------------------------------------------ fetch wrapper */ + + window.fetch = function (input, init) { + var url = typeof input === 'string' ? input : (input && input.url) || ''; + var auth = isAuthUrl(url); + var method = String((init && init.method) || (input && input.method) || 'GET').toUpperCase(); + return origFetch(input, init).then(function (res) { + if (auth) { + return res; + } + // Only a change asks for a sign-in; a read the page cannot do just fails quietly + if (res.status === 401 && method !== 'GET') { + return askLogin().then(function (ok) { + return ok ? origFetch(input, init) : res; + }); + } + if (res.status === 403 && method !== 'GET') { + errorText(res.clone()).then(toast); + } + return res; + }); + }; + + /* ------------------------------------------------------------ start */ + + function start() { + injectStyle(); + addHeaderButton(); + refresh(); + window.authPerms = { + can: can, + refresh: refresh, + usersAndRoles: usersAndRoles, + }; + } + + if (document.readyState === 'loading') { + document.addEventListener('DOMContentLoaded', start); + } else { + start(); + } +})(); diff --git a/web/templates/index.html b/web/templates/index.html index 4dd541b..1367895 100644 --- a/web/templates/index.html +++ b/web/templates/index.html @@ -1379,6 +1379,7 @@ +