Skip to content

Self-hosted monitoring for homelabs: host and container metrics and uptime checks from all your machines in one dashboard, with an optional AI agent that diagnoses incidents and suggests fixes.

fix(admin): confirm with the password and a code before allowing one user the agent chat (#225)

Karlo Kajba Šimanić2f0308cd62d9
diff --git a/SECURITY.md b/SECURITY.md
index 863fe86..5b63444 100644
--- a/SECURITY.md
+++ b/SECURITY.md
@@ -469,8 +469,9 @@ URL, a keyword or a value in a JSON reply, a TCP port, a TLS certificate, a DNS
password again, and every try counts toward the lockout, the right password included. A limited
(set-up-only) session lasts 30 minutes, not a day.
- **Turning the agent on is confirmed with the password and a two-factor code.** Choosing the agent's provider,
- model or API key, switching the chat or automatic diagnosis on, opening the chat to other users and raising a
- look-up budget from 0 all start
+ model or API key, switching the chat or automatic diagnosis on, opening the chat to other users (setting Chat
+ access to "Per user", and allowing one more user the chat in Admin › Users) and raising a look-up budget
+ from 0 all start
sending data from the servers to an outside model, so someone with a stolen admin session can't do it alone.
The password is checked first (`POST /auth/reauth`) and gives a token that lasts five minutes, belongs to that
session, allows five codes and is used up by the change; every try counts toward the two-factor lockout, and an
diff --git a/docs/api.md b/docs/api.md
index 72c43e4..fa07706 100644
--- a/docs/api.md
+++ b/docs/api.md
@@ -29,7 +29,7 @@ All paths are relative to `/api` when going through the frontend/nginx.
| `GET /monitoring/install-info` | admin | The collector address and images the panel uses. |
| `GET` / `POST` / `DELETE /monitoring/enrollment-key` | admin | Show status / create or rotate / revoke the enrollment key. |
| `GET` / `PUT /admin/settings` | admin | History retention (`history_retention_days`: 365, 730 or 0 for forever), chat on/off, require two-factor for admins, alert thresholds and per-mount disk thresholds; the agent's model prices, monthly budget, daily chat limit, automatic diagnosis, whether users see diagnoses, chat access (`admins_only` or `per_user`), and the look-up budgets (`agent_tool_budget_diagnosis` 0–20, `agent_tool_budget_chat` 0–10). Turning the chat or automatic diagnosis on, chat access to `per_user`, and a look-up budget up from 0 also need `reauth_token` and `code` (see `POST /auth/reauth`). |
-| `GET /admin/users`, `PATCH /admin/users/{id}` | admin | Users and invitations; change someone's role, switch them off, or (with per-user chat access) allow them the agent chat (`agent_chat_enabled`). |
+| `GET /admin/users`, `PATCH /admin/users/{id}` | admin | Users and invitations; change someone's role, switch them off, or (with per-user chat access) allow them the agent chat (`agent_chat_enabled`; turning it on also needs `reauth_token` and `code`, see `POST /auth/reauth`). |
| `GET /agent/config` | session | Whether chat with the agent can be used: switched on, allowed for you (`may_chat`), a key configured, and the monthly budget not used up. |
| `GET /incidents`, `GET /incidents/{id}` | session | The incident inbox; one incident with its rule-based diagnosis and, under `agent`, the agent's latest report (with `watch` progress while it is open, `reused_from` when it was reused, and `steps`, its look-ups in plain words: `tool`, `status`, `reason`, `asked`, `found`, `from`, `to`, `at`; never the raw results). The report is left out (`hidden: true`) for users who aren't admins while diagnoses aren't shown to users. |
| `POST /incidents/{id}/acknowledge`, `…/resolve`, `…/mute`, `…/unmute` | admin | Act on an incident. |
diff --git a/docs/assistant.md b/docs/assistant.md
index fa8bbf0..14f21a1 100644
--- a/docs/assistant.md
+++ b/docs/assistant.md
@@ -13,8 +13,8 @@ change files on your servers. Everything about it is in `src/agent/` and in **Ad
2. Create an API key with one of the providers: Anthropic (Claude), OpenAI or Google Gemini.
3. In **Admin → Incident agent**, pick the provider, keep or change the model, paste the key and click **Save**.
Confirm with your password and a two-factor code: this decides where the agent's data goes. Turning the chat
- or automatic diagnosis on, setting Chat access to "Per user" and raising a look-up budget from 0 ask for the
- same; turning things off doesn't.
+ or automatic diagnosis on, setting Chat access to "Per user", allowing one user the chat in Admin › Users and
+ raising a look-up budget from 0 ask for the same; turning things off doesn't.
Models used when the field is left empty:
| Provider | Default model |
diff --git a/src/backend/main.py b/src/backend/main.py
index 813e2d3..eeede1d 100644
--- a/src/backend/main.py
+++ b/src/backend/main.py
@@ -1759,8 +1759,11 @@ INVITE_TTL = timedelta(days=7)
class UserUpdateRequest(BaseModel):
role: Literal["admin", "user"] | None = None
is_active: bool | None = None
- # Whether they may use the agent chat when chat access is "per user".
+ # Whether they may use the agent chat when chat access is "per user". Turning it on sends more data to the AI
+ # provider, so it is confirmed with the password and a code (reauth.py), like the agent's other switches.
agent_chat_enabled: bool | None = None
+ reauth_token: str | None = Field(default=None, max_length=100)
+ code: str | None = Field(default=None, max_length=64)
class InviteRequest(BaseModel):
diff --git a/src/backend/routes/admin.py b/src/backend/routes/admin.py
index d4a0156..7a6c375 100644
--- a/src/backend/routes/admin.py
+++ b/src/backend/routes/admin.py
@@ -50,6 +50,9 @@ def admin_update_user(user_id: main.PathId, payload: main.UserUpdateRequest, ses
raise HTTPException(status_code=403, detail="The owner's account can't be changed here.")
if account.id == admin["id"]:
raise HTTPException(status_code=403, detail="You can't change your own role or switch yourself off.")
+ if payload.agent_chat_enabled is True and not account.agent_chat_enabled:
+ # Lets one more person send questions and incident facts to the AI provider (#202).
+ reauth.require(db, admin, payload.reauth_token, payload.code)
changes = []
if payload.role is not None and payload.role != account.role:
account.role = payload.role
diff --git a/src/frontend/src/admin/AdminPage.jsx b/src/frontend/src/admin/AdminPage.jsx
index abbfcc1..d662781 100644
--- a/src/frontend/src/admin/AdminPage.jsx
+++ b/src/frontend/src/admin/AdminPage.jsx
@@ -123,6 +123,8 @@ function Servers({ overview }) {
function Users({ me }) {
const { data, error, setData, reload } = useLoaded('/admin/users')
const [state, run] = useAction()
+ // Letting someone chat sends more data to the AI provider, so turning it on is confirmed like the agent's switches (#202).
+ const [confirming, setConfirming] = useState(null)
const [inviting, setInviting] = useState(false)
const [form, setForm] = useState({ email: '', role: 'user' })
const [link, setLink] = useState(null)
@@ -142,7 +144,7 @@ function Users({ me }) {
<td className="pl-[18px]"><span className="flex items-center gap-3"><span className="flex h-7 w-7 shrink-0 items-center justify-center rounded-md border border-line bg-raised text-[11px] font-semibold" style={{ color: user.avatar_color || undefined }}>{initials(user.name)}</span><span className="min-w-0"><span className="block truncate font-medium text-paper">{user.name}{user.id === me.id && <span className="ml-2 text-xs font-normal text-muted">you</span>}</span><span className="block truncate text-xs text-muted">{user.email}</span></span></span></td>
<td>{fixed ? <span className="text-paper">{user.role_name}</span> : <select className="select h-8" aria-label={`Role of ${user.name}`} value={user.role} onChange={(event) => change(user, { role: event.target.value })}><option value="admin">Admin</option><option value="user">Viewer</option></select>}</td>
<td><span className={`chip ${user.two_factor ? 'chip-ok' : ''}`}>{user.two_factor ? 'On' : 'Off'}</span></td>
- {data.agent_chat_access === 'per_user' && <td>{user.role === 'admin' ? <span className="text-xs text-muted">always</span> : <Switch label={`Agent chat for ${user.name}`} checked={user.agent_chat_enabled} disabled={state.busy} onChange={(on) => change(user, { agent_chat_enabled: on })} />}</td>}
+ {data.agent_chat_access === 'per_user' && <td>{user.role === 'admin' ? <span className="text-xs text-muted">always</span> : <Switch label={`Agent chat for ${user.name}`} checked={user.agent_chat_enabled} disabled={state.busy} onChange={(on) => (on ? setConfirming({ user, change: { title: `Agent chat for ${user.name}`, from: 'Off', to: 'On', intro: 'Letting someone chat with the agent lets them send questions and incident facts to an outside model.', action: 'Verify and turn on', detail: 'Their questions and the incident facts will be sent to', target: 'the AI provider' } }) : change(user, { agent_chat_enabled: false }))} />}</td>}
<td className="text-soft">{!user.is_active ? 'disabled' : user.sessions > 0 && user.id === me.id ? 'now' : ago(user.last_seen_at)}</td>
<td className="whitespace-nowrap pr-[18px] text-right">{!fixed && <>
{user.sessions > 0 && <button type="button" className="link" onClick={() => run(async () => { await post(`/admin/users/${user.id}/sign-out`); reload() })}>Sign out</button>}
@@ -181,6 +183,7 @@ function Users({ me }) {
<span>Owners and admins change settings. Viewers see everything but can't acknowledge, resolve or change anything. <Outcome state={state} /></span>
{!inviting && <button type="button" className="btn btn-sm" onClick={() => { setLink(null); setInviting(true) }}><Icon name="plus" size={13} />Invite user</button>}
</div>
+ {confirming && <ConfirmDialog change={confirming.change} user={me} onConfirm={async (fields) => setData(await apiRequest(`/admin/users/${confirming.user.id}`, { method: 'PATCH', body: JSON.stringify({ agent_chat_enabled: true, ...fields }) }))} onClose={() => setConfirming(null)} />}
</div>
)
}
diff --git a/tests/accounts/test_new_pages.py b/tests/accounts/test_new_pages.py
index 6c5cc86..bfd3fbd 100644
--- a/tests/accounts/test_new_pages.py
+++ b/tests/accounts/test_new_pages.py
@@ -647,7 +647,7 @@ def test_chat_is_for_admins_unless_allowed_per_user(app, monkeypatch):
assert ask().status_code == 403 and viewer.get("/agent/config").json()["may_chat"] is False # admins only, the default
assert owner.put("/admin/settings", json={"agent_chat_access": "per_user", **confirmed(app, owner)}).status_code == 200
assert ask().status_code == 403 # per user, but not allowed yet
- users = owner.patch("/admin/users/3", json={"agent_chat_enabled": True}).json()
+ users = owner.patch("/admin/users/3", json={"agent_chat_enabled": True, **confirmed(app, owner)}).json()
assert next(user for user in users["users"] if user["id"] == 3)["agent_chat_enabled"] is True and users["agent_chat_access"] == "per_user"
assert ask().status_code == 200 and viewer.get("/agent/config").json()["may_chat"] is True
owner.put("/admin/settings", json={"agent_chat_access": "admins_only"})
@@ -677,6 +677,23 @@ def test_turning_the_agent_on_needs_the_password_and_a_code(app):
assert settings["agent_auto_diagnose"] and settings["agent_chat_enabled"] and settings["agent_chat_access"] == "per_user"
+def test_letting_one_user_chat_needs_the_password_and_a_code_but_stopping_does_not(app):
+ owner = signed_in(app, 1)
+ owner.put("/admin/settings", json={"agent_chat_access": "per_user", **confirmed(app, owner)})
+ allowed = lambda: app.db.get(User, 3).agent_chat_enabled # noqa: E731
+
+ assert owner.patch("/admin/users/3", json={"agent_chat_enabled": True}).status_code == 403 # a stolen session alone can't (#202)
+ app.db.expire_all()
+ assert not allowed()
+ assert owner.patch("/admin/users/3", json={"agent_chat_enabled": True, **confirmed(app, owner)}).status_code == 200
+ app.db.expire_all()
+ assert allowed()
+ assert owner.patch("/admin/users/3", json={"agent_chat_enabled": False}).status_code == 200 # stopping needs nothing
+ app.db.expire_all()
+ assert not allowed()
+ assert owner.patch("/admin/users/3", json={"role": "admin"}).status_code == 200 # other changes as before
+
+
def test_the_look_up_budgets_are_checked_audited_and_raising_one_from_0_is_confirmed(app):
owner = signed_in(app, 1)