mass_queue icon indicating copy to clipboard operation
mass_queue copied to clipboard

Non-admin users aren’t allowed to subscribe to arbitrary events like mass_queue

Open MankiniChykan opened this issue 1 year ago • 5 comments

Confirmed when switching one of my kiosks to an admin account errors go away.

Logger: homeassistant.components.websocket_api.http.connection
Source: components/websocket_api/connection.py:315
integration: Home Assistant WebSocket API (documentation, issues)
First occurred: October 2, 2025 at 22:14:37 (30 occurrences)
Last logged: October 2, 2025 at 22:59:09

[281471493106848] Error handling message: Unauthorized (unauthorized) Chykan@pi400 from 127.0.0.1 (Mozilla/5.0 (X11; CrOS x86_64 14092.77.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.107 Safari/537.36)
Logger: homeassistant.components.websocket_api.commands
Source: components/websocket_api/commands.py:171
integration: Home Assistant WebSocket API (documentation, issues)
First occurred: October 2, 2025 at 22:14:37 (30 occurrences)
Last logged: October 2, 2025 at 22:59:09

Refusing to allow Chykan@pi400 to subscribe to event mass_queue

You need a server-side WS hook that relays mass_queue to non-admin clients. Here’s the exact patch to your __init__.py — add the imports, register the command in async_setup, and append the handler.

Unified diff (apply as-is)

@@
 from dataclasses import dataclass
 from typing import TYPE_CHECKING
 
+import voluptuous as vol
+from homeassistant.components import websocket_api
+from homeassistant.core import callback
 from homeassistant.config_entries import ConfigEntry, ConfigEntryState
 from homeassistant.const import CONF_URL, EVENT_HOMEASSISTANT_STOP
 from homeassistant.exceptions import ConfigEntryNotReady
 from homeassistant.helpers import config_validation as cv
@@
 async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:  # noqa: ARG001
     """Set up the Music Assistant component."""
-    return True
+    # Expose a safe WS stream for non-admin clients to receive mass_queue updates.
+    websocket_api.async_register_command(hass, ws_subscribe_mass_queue)
+    return True
@@
     return unload_ok
+
+
+# ------------------------------
+# WebSocket: mass_queue/subscribe
+# ------------------------------
+@websocket_api.websocket_command({
+    vol.Required("type"): "mass_queue/subscribe",
+    vol.Optional("event_type", default="mass_queue"): str,
+})
+@websocket_api.async_response
+async def ws_subscribe_mass_queue(
+    hass: HomeAssistant,
+    connection: websocket_api.ActiveConnection,
+    msg: dict,
+) -> None:
+    """Allow non-admin clients to receive mass_queue events (payload-only)."""
+    event_type = msg["event_type"]
+
+    @callback
+    def _forward(event):
+        # Forward only event.data (what the card expects at evt.data.*)
+        connection.send_event(msg["id"], event.data)
+
+    unsub = hass.bus.async_listen(event_type, _forward)
+    connection.subscriptions[msg["id"]] = unsub
+    connection.send_result(msg["id"])

Card tweak (so non-admins use the proxy)

Replace your subscribeUpdates() in the card with this. Admins keep the direct event; everyone else uses the new WS command.

 subscribeUpdates() {
-  this._unsubscribe = this.hass.connection.subscribeEvents(this.eventListener, "mass_queue");
-  this._listening = true;
+  this._unsubscribe?.(); this._unsubscribe = undefined;
+  if (this.hass?.user?.is_admin) {
+    this._unsubscribe = this.hass.connection.subscribeEvents(this.eventListener, "mass_queue");
+    this._listening = true;
+    return;
+  }
+  // Non-admin: stream via our integration command; it forwards event.data
+  this._unsubscribe = this.hass.connection.subscribeMessage(
+    (payload) => this.eventListener({ data: payload }),
+    { type: "mass_queue/subscribe", event_type: "mass_queue" }
+  );
+  this._listening = true;
 }

MankiniChykan avatar Oct 02 '25 17:10 MankiniChykan

Home Assistant doesn't allow arbitrary event access for due to security concerns. I think it's better for the cards to only subscribe if someone is an admin.

This does have the downside that the queue section might not stay updated for non-admins of the card but I don't like the idea of working around security measures.

droans avatar Oct 02 '25 20:10 droans

So I have to set every device (including kiosk displays in my house and the family phones to admin)? Which then exposes all the side bar settings to the kids and family, which causes confusion and possible accidental fiddling.

Usually my devices are the only admin account in the household.

The error occurs and the play list disappears and I have to restart home assistant to get them back up again. A proxy is not safe enough, which still requires a login into the system?

Non-admin users are blocked from subscribing to certain WebSocket events or commands, for security reasons.

Here’s a breakdown and how you can handle it:


What’s happening (and why)

  • Home Assistant’s WebSocket API has built-in security checks. Some message types/commands require elevated (admin) permissions. Non-admin (or restricted) users invoking those commands will trigger an “Unauthorized” error. ([developers.home-assistant.io][1])

  • For example, the error you saw:

    Refusing to allow Chykan@pi400 to subscribe to event mass_queue
    

    indicates that the subscribe_events-style command (or equivalent) is being blocked because the user doesn’t have permission to subscribe to that event.

  • There is precedent in Home Assistant’s issue tracker: non-admin users get “Unauthorized” when attempting to subscribe to custom or “sensitive” events. ([GitHub][2])

  • In particular, subscribe_trigger is documented (in issue tracker) to require admin privileges, because triggers can give broad access to events/automation. ([GitHub][3])

So you’re bumping into those built-in limitations.


The patch you proposed — is it viable?

Your patch (to init.py) essentially:

  1. Defines a new WS command mass_queue/subscribe that non-admin clients can use.
  2. Registers it via websocket_api.async_register_command(...).
  3. In that handler, listens to the underlying event (mass_queue) and forwards only the payload (event.data) to the non-admin connection.

That’s a valid workaround. In effect, you’re creating a “proxy” event subscription for non-admin users. Non-admins call your custom command (which you register), and your integration (which already runs in admin context) listens on their behalf and forwards allowed data.

Pros:

  • You maintain control over which events/data you forward.
  • You avoid exposing full event bus to non-admins.
  • You avoid the built-in “Unauthorized” error, because you’re using a custom command under your component’s authority.

Caveats / things to watch out for:

  • Make sure your forwarding logic is safe (don’t forward sensitive/unintended events).
  • Clean up subscriptions when the client disconnects (memory leaks).
  • Ensure version compatibility: Home Assistant internals (websocket registration, API hooks) may change across versions.
  • Your clients (front end / kiosk) must use your custom command instead of the default subscription for mass_queue.

Overall, your approach is solid and aligns with how custom integrations can circumnavigate WS security (in a controlled way).


What you need to do (next steps / implementation checklist)

  1. Integrate your patch cleanly

    • Add the imports (voluptuous, websocket_api, etc.)
    • In your integration’s async_setup, call websocket_api.async_register_command(hass, ws_subscribe_mass_queue)
    • Define ws_subscribe_mass_queue decorated with @websocket_api.websocket_command(...) and @websocket_api.async_response
    • In the handler, call hass.bus.async_listen(event_type, forwarder)
    • Store the unsub in connection.subscriptions[msg["id"]]
    • Send the subscription result back to the client
  2. Update the frontend / card logic Replace any direct subscribeEvents("mass_queue") in the client side with logic that:

    if (this.hass.user.is_admin) {
        this._unsubscribe = this.hass.connection.subscribeEvents(
            this.eventListener, "mass_queue"
        );
    } else {
        this._unsubscribe = this.hass.connection.subscribeMessage(
            payload => this.eventListener({ data: payload }),
            { type: "mass_queue/subscribe", event_type: "mass_queue" }
        );
    }
    
  3. Security & filtering

    • Only forward event.data, not the full event object (so no sensitive metadata)
    • Possibly enforce checks on event_type names or enforce a whitelist
    • Ensure clients can’t trick you into subscribing to other events via that command
  4. Test thoroughly across user types

    • As an admin user → confirm subscription works via default method
    • As non-admin → confirm your custom command works, and no “Unauthorized” errors
    • Kill/close connections and ensure cleanup (unsubscribing)
  5. Watch for HA updates Because Home Assistant’s internal WebSocket API and registration systems can change, you’ll need to maintain this patch through version upgrades.


Alternate options / things to consider

  • Instead of a custom command, you might consider using existing restricted APIs or pushing data via other channels (REST API polling, MQTT, etc.)—but those often incur additional complexity or delay.
  • If your “mass_queue” event is part of a custom integration anyway, you could emit state updates via standard Home Assistant entities rather than using raw events; then clients can subscribe to state changes (which non-admins can receive). That approach uses HA’s built-in permissions more naturally.

MankiniChykan avatar Oct 04 '25 13:10 MankiniChykan

I understand but I still don't think it's a good idea.

I have an alternative method I'm going to use for the next beta version of the player card, though.

If the user is an admin, it will listen like normal. If the user isn't, though, it'll poll HA in regular intervals to see if the queue has updated.

droans avatar Oct 14 '25 11:10 droans

I can't see the issue. It is HA querying Music Assistant which is all part of the same system.

The error needs to disappear so I can switch my other devices back to Non-Admin Accounts.

The simplicity I had for the family is now eroded.

I am sure I am not the only user that would use Admin and Non-Admin Accounts like this.

Also affects my kiosk mode that activates only on Non-Admin Accounts

MankiniChykan avatar Oct 17 '25 00:10 MankiniChykan

Sorry to ask, but is this still an issue, or does the latest version is working perfectly for non-admin user dashboards?

h3llrais3r avatar Nov 16 '26 13:11 h3llrais3r