feat: users, roles and per-area permissions, production demo image

The controller checks every route against the signed-in user's role, with
levels none, view, control and edit per area. Guests get the permissions
of a built-in guest role. Auth stays off until the first user exists;
LED_ADMIN_USER and LED_ADMIN_PASSWORD create the first admin.

Sessions are cookies, passwords are PBKDF2-SHA256, and logins lock per
username after five failures. The simulator's WebSocket checks the view
permission at handshake and per frame; /ws needs devices control. The web
UI gets a sign-in button, a sign-in prompt on refused changes, and a users
and roles screen.

Also: the device build gets the bridge include path and forward type it
was missing, Dockerfile.sim runs non-root, and Dockerfile.prod with
docker-compose.prod.yml runs the controller on an internal network behind
Caddy for HTTPS.

Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
This commit is contained in:
jimmyandClaude Haiku 5.5 committed 2026-11-17 00:29:04 +13:00
1 parent 02440be55d
commit f0615dc1b7
26 files changed
+2116 -23

No files matched your search

+4
View File
@@ -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
+1
View File
@@ -45,3 +45,4 @@ desktop-data/
desktop-data-test/
bridge/build-*/
sim-driver/build/
.env
+28
View File
@@ -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"]
+5
View File
@@ -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"]
+12
View File
@@ -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"
}
}
+1 -1
View File
@@ -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
+59
View File
@@ -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:
+3 -3
View File
@@ -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)
+15 -5
View File
@@ -1,3 +1,4 @@
#include "auth.h"
#include "api.h"
#include <stdio.h>
@@ -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;
+2 -1
View File
@@ -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 <stdio.h>
@@ -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;
+2 -1
View File
@@ -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 <math.h>
@@ -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;
}
+1301
View File
File diff suppressed because it is too large. Load diff
+46
View File
@@ -0,0 +1,46 @@
#pragma once
#include <stdbool.h>
#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);
+2
View File
@@ -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";
+2 -1
View File
@@ -1,6 +1,7 @@
/*
* v2 controller: W5500 Ethernet, INMP441 beat detection, ESP-NOW master.
*/
#include "auth.h"
#include <stdio.h>
#include <string.h>
#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);
+4 -3
View File
@@ -1,3 +1,4 @@
#include "auth.h"
#include "ota.h"
#include <stdio.h>
@@ -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;
}
+1 -1
View File
@@ -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]))
+2 -1
View File
@@ -1,3 +1,4 @@
#include "auth.h"
#include "web.h"
#include <stddef.h>
@@ -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;
+9 -1
View File
@@ -1,3 +1,4 @@
#include "auth.h"
#include "ws.h"
#include <stdlib.h>
@@ -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;
+2 -1
View File
@@ -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 <signal.h>
#include <stdio.h>
#include <stdlib.h>
@@ -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);
+10 -3
View File
@@ -22,6 +22,7 @@
* "direction" the way it runs (degrees clockwise from +y), "mac" the driver. Each bar's flash is
* <db>/sim/flash/<mac>.json, so a bar keeps its presets in every room it appears in.
*/
#include "auth.h"
#include "sim_rig.h"
#include <ctype.h>
@@ -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));
+2 -1
View File
@@ -1,4 +1,5 @@
// Host build: what the board's hardware files (mic.c, ota.c, littlefs) provide, without hardware
#include "auth.h"
#include <string.h>
#include <sys/stat.h>
#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);
}
+6
View File
@@ -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)
+172
View File
@@ -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
+424
View File
@@ -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 { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[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 = '<div class="auth-dialog" role="dialog" aria-modal="true" aria-label="' + esc(title) + '"><h3>' + esc(title) + '</h3><div class="auth-body"></div></div>';
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 = [
'<form>',
'<label for="auth-user">Username</label><input id="auth-user" autocomplete="username" required>',
'<label for="auth-pass">Password</label><input id="auth-pass" type="password" autocomplete="current-password" required>',
'<div class="auth-err" id="auth-err"></div>',
'<div class="auth-actions"><button type="button" id="auth-cancel">Cancel</button><button type="submit" class="primary">Sign in</button></div>',
'</form>',
].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 = [
'<form>',
'<label for="auth-old">Current password</label><input id="auth-old" type="password" autocomplete="current-password" required>',
'<label for="auth-new">New password (8 to 128 characters)</label><input id="auth-new" type="password" autocomplete="new-password" required>',
'<div class="auth-err" id="auth-err"></div>',
'<div class="auth-actions"><button type="button" id="auth-cancel">Cancel</button><button type="submit" class="primary">Change</button></div>',
'</form>',
].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 = '<div class="auth-err" id="auth-err"></div><div id="auth-content">Loading…</div>';
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 '<option value="' + esc(r.name) + '"' + (r.name === selected ? ' selected' : '') + '>' + esc(r.name) + '</option>';
}).join('');
}
function render(users) {
var userRows = users.map(function (u) {
return '<tr><td>' + esc(u.username) + '</td>' +
'<td><select data-user-role="' + esc(u.username) + '">' + roleOptions(u.role) + '</select></td>' +
'<td class="auth-row"><button data-reset="' + esc(u.username) + '">Set password</button>' +
'<button class="danger" data-delete-user="' + esc(u.username) + '">Delete</button></td></tr>';
}).join('');
var head = '<tr><th>Area</th>' + roles.map(function (r) { return '<th>' + esc(r.name) + '</th>'; }).join('') + '</tr>';
var matrix = AREAS.map(function (a) {
return '<tr><td>' + esc(AREA_LABELS[a]) + '</td>' + roles.map(function (r) {
var lvl = (r.perms && r.perms[a]) || 0;
var locked = r.name === 'admin';
return '<td><select data-perm-role="' + esc(r.name) + '" data-area="' + a + '"' + (locked ? ' disabled' : '') + '>' +
LEVELS.map(function (l, i) { return '<option value="' + i + '"' + (i === lvl ? ' selected' : '') + '>' + l + '</option>'; }).join('') +
'</select></td>';
}).join('') + '</tr>';
}).join('');
content.innerHTML = [
'<h4>Users</h4>',
'<table><tr><th>Username</th><th>Role</th><th></th></tr>' + (userRows || '<tr><td colspan="3">No users yet</td></tr>') + '</table>',
'<div class="auth-row"><input id="new-user" placeholder="username" style="width:140px">',
'<input id="new-pass" type="password" placeholder="password (8+)" style="width:160px">',
'<select id="new-role" style="width:140px">' + roleOptions('guest') + '</select>',
'<button class="primary" id="add-user">Add user</button></div>',
'<h4 style="margin-top:18px">Permissions</h4>',
'<p style="font-size:12px;opacity:.75;margin:4px 0">none: hidden · view: read · control: play, stop, brightness, identify · edit: change anything.</p>',
'<div style="overflow:auto"><table>' + head + matrix + '</table></div>',
'<div class="auth-row"><input id="new-role-name" placeholder="new role name" style="width:180px">',
'<button id="add-role">New role</button><span style="flex:1"></span>',
'<button class="primary" id="save-roles">Save permissions</button></div>',
'<div class="auth-row" style="margin-top:10px">' + roles.filter(function (r) { return !r.builtin; }).map(function (r) {
return '<button class="danger" data-delete-role="' + esc(r.name) + '">Delete role ' + esc(r.name) + '</button>';
}).join(' ') + '</div>',
].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('<p style="font-size:13px;opacity:.85">No users yet, so anyone can edit. Create the first admin to turn sign-in on.</p>');
}
rows.push('<div class="auth-actions" style="justify-content:flex-start;flex-direction:column;align-items:stretch">');
if (!state.user && state.enabled) {
rows.push('<button class="primary" id="auth-do-login">Sign in</button>');
}
if (state.user) {
rows.push('<button id="auth-do-pass">Change password</button>');
rows.push('<button id="auth-do-out">Sign out</button>');
}
if (can('users', AREA_EDIT_LEVEL)) {
rows.push('<button id="auth-do-users">Users &amp; roles</button>');
}
rows.push('<button id="auth-do-close">Close</button></div>');
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();
}
})();
+1
View File
@@ -1379,6 +1379,7 @@
</div>
</div>
<script src="/static/auth.js"></script>
<script src="/static/fetch_cache.js"></script>
<script src="/static/zone-devices-panel.js"></script>
<script src="/static/groups.js"></script>