Compare commits

..
Author SHA1 Message Date
Josh Hawkins 69b6bd3544 remove client image filter from chat messages 2026-11-23 09:21:28 -06:00
Josh Hawkins 0ff8718057 use server-generated tool call ids and drop remote images from chat messages
Chat write-tool approvals were keyed by the provider's tool call id, but Gemini uses the function name as the id and Ollama falls back to call_0, call_1, so a later or repeated write call in the same request reused an earlier approval and ran without a prompt. Each tool call the model returns now gets a unique server-generated id, and the Gemini plugin resolves a tool result's function name from the assistant's tool calls instead of from the id. Client message content now keeps only text parts and data:image/ image parts, so OpenAI-compatible servers and llama-server are never handed a remote URL to fetch.
2026-11-23 08:59:30 -06:00
12 changed files with 112 additions and 92 deletions
@@ -102,7 +102,7 @@ proxy:
# Optional: Auth secret that is checked against the X-Proxy-Secret header sent from
# the proxy. If not set, all requests are trusted regardless of origin.
auth_secret: None
# Optional: The default role to use for proxy auth. Must be "admin", "viewer", a custom role, or "none" to deny
# Optional: The default role to use for proxy auth. Must be "admin" or "viewer"
default_role: viewer
# Optional: The character used to separate multiple values in the proxy headers. (default: shown below)
separator: ","
+1 -4
View File
@@ -234,8 +234,6 @@ proxy:
Setting `default_role` to `none` denies access instead of falling back to a role. Any proxy-authenticated user whose headers do not match an explicit `role_map` entry receives a 403 response. This is useful when the upstream proxy authenticates a broader set of users than should reach Frigate, so that only mapped groups are allowed in.
A `default_role` that does not name a configured role is treated as `none`.
```yaml
proxy:
...
@@ -268,8 +266,7 @@ In this example:
- If the proxy passes a role header containing `camera-viewer`, the user is assigned the `viewer` role.
- If the proxy passes a role header containing `operators`, the user is assigned the `operator` custom role.
- If no mapping matches, Frigate falls back to `default_role` if configured, or denies access if `default_role` is `none`.
- If a group matches but its mapped role no longer exists (for example, a deleted custom role), access is denied.
- If `role_map` is not defined, Frigate assumes the role header directly contains `admin`, `viewer`, or a custom role name, matched without regard to case.
- If `role_map` is not defined, Frigate assumes the role header directly contains `admin`, `viewer`, or a custom role name.
**Note on matching semantics:**
+16 -13
View File
@@ -580,9 +580,8 @@ def resolve_role(
(split by proxy_config.separator) and map to roles.
Admin matches short-circuit to admin.
- If no role_map is configured, treat the header as role names directly.
2. If no valid role is found, return proxy_config.default_role if it's valid in config_roles, else 'none'.
The literal value 'none' means access should be denied.
A role_map match whose mapped roles no longer exist in config_roles also resolves to 'none'.
2. If no valid role is found, return proxy_config.default_role if it's valid in config_roles, else 'viewer'.
The literal value 'none' is a valid default and means access should be denied.
Args:
headers (dict): Incoming request headers (case-insensitive).
@@ -595,11 +594,17 @@ def resolve_role(
default_role = proxy_config.default_role
role_header = proxy_config.header_map.role
# Role names match case-insensitively, as header values are lowercased.
# "none" is the deny sentinel; an unknown or missing default also denies,
# since falling back to viewer would grant every camera.
roles_by_name = {r.lower(): r for r in config_roles}
validated_default = roles_by_name.get((default_role or "").lower(), "none")
# Validate default_role against config; fallback to 'viewer' if invalid.
# "none" is a sentinel meaning "deny access when no mapping matches"; it is
# reserved in AuthConfig.validate_roles so it is never a configured role.
validated_default = (
default_role
if default_role in config_roles or default_role == "none"
else "viewer"
)
if not config_roles:
# Edge case: no roles defined
validated_default = "none" if default_role == "none" else "viewer"
if not role_header:
logger.debug(
@@ -626,7 +631,7 @@ def resolve_role(
logger.debug("Parsed groups from role header: %s", groups)
matched_roles = {
role_name.lower()
role_name
for role_name, required_groups in proxy_config.header_map.role_map.items()
if any(group in groups for group in required_groups)
}
@@ -638,11 +643,9 @@ def resolve_role(
logger.debug("Resolved role (with role_map) to 'admin'.")
return "admin"
# A mapped role that was deleted or renamed denies rather than
# widening to the default role
if matched_roles:
resolved = next(
(r for r in config_roles if r.lower() in matched_roles), "none"
(r for r in config_roles if r in matched_roles), validated_default
)
logger.debug("Resolved role (with role_map) to '%s'.", resolved)
return resolved
@@ -661,7 +664,7 @@ def resolve_role(
logger.debug("Parsed roles directly from header: %s", roles_from_header)
resolved = next(
(r for r in config_roles if r.lower() in roles_from_header),
(r for r in config_roles if r in roles_from_header),
validated_default,
)
if resolved == validated_default and roles_from_header:
+14 -2
View File
@@ -6,6 +6,7 @@ import json
import logging
import operator
import time
import uuid
from datetime import datetime
from functools import reduce
from typing import Any, Literal
@@ -1274,6 +1275,14 @@ def _pending_tool_calls_from_tail(
return parse_tool_calls_from_message(tail)
def _with_server_ids(tool_calls: list[dict[str, Any]]) -> list[dict[str, Any]]:
"""Give each model tool call a unique id.
Approvals are keyed by id, and some providers reuse ids across calls.
"""
return [{**tc, "id": uuid.uuid4().hex[:9]} for tc in tool_calls]
def _tool_calls_awaiting_approval(
pending_tool_calls: list[dict[str, Any]],
body: ChatCompletionRequest,
@@ -1599,6 +1608,7 @@ async def chat_completion(
return
requested = msg.get("tool_calls")
if requested:
requested = _with_server_ids(requested)
stream_iterations += 1
conversation.append(
build_assistant_message_for_conversation(
@@ -1684,13 +1694,15 @@ async def chat_completion(
status_code=500,
)
pending_tool_calls = response.get("tool_calls")
if pending_tool_calls:
pending_tool_calls = _with_server_ids(pending_tool_calls)
conversation.append(
build_assistant_message_for_conversation(
response.get("content"), response.get("tool_calls")
response.get("content"), pending_tool_calls
)
)
pending_tool_calls = response.get("tool_calls")
if not pending_tool_calls:
logger.debug(
f"Chat completion finished with final answer (iterations: {tool_iterations})"
+5 -6
View File
@@ -88,17 +88,16 @@ class AuthConfig(FrigateBaseModel):
f"Invalid role name '{role}'. Must be alphanumeric with underscores."
)
# Proxy role headers match role names case-insensitively, so reserved
# names are reserved in every casing and names must differ beyond case
used_reserved = sorted(r for r in v if r.lower() in ("admin", "viewer", "none"))
# 'none' is the deny sentinel for proxy.default_role, where it is matched
# case-insensitively, so every casing of it has to be reserved here
used_reserved = sorted(
r for r in v if r in ("admin", "viewer") or r.lower() == "none"
)
if used_reserved:
raise ValueError(
f"Reserved role name(s) {', '.join(used_reserved)} cannot be used as custom roles."
)
if len({r.lower() for r in v}) != len(v):
raise ValueError("Role names must be unique regardless of letter case.")
# Ensure no role has an empty camera list
for role, allowed_cameras in v.items():
if not allowed_cameras:
-9
View File
@@ -1041,15 +1041,6 @@ class FrigateConfig(FrigateBaseModel):
# set notifications state
self.notifications.enabled_in_config = self.notifications.enabled
default_role = (self.proxy.default_role or "").lower()
if default_role != "none" and default_role not in {
r.lower() for r in self.auth.roles
}:
logger.warning(
"proxy.default_role '%s' is not a configured role, so proxy users without a matching role are denied",
self.proxy.default_role,
)
# validate genai: each role (chat, descriptions, embeddings, transcribe) at most once
role_to_name: dict[GenAIRoleEnum, str] = {}
for name, genai_cfg in self.genai.items():
+4 -3
View File
@@ -55,9 +55,10 @@ class ProxyConfig(FrigateBaseModel):
@field_validator("default_role", mode="before")
@classmethod
def normalize_deny_sentinel(cls, v):
# Fail closed: "none" in any casing and a null default both deny.
# Normalizing null keeps the value through /config, which drops nulls
if v is None or (isinstance(v, str) and v.strip().lower() == "none"):
# Fail closed on capitalization: an unnormalized "None" would miss the
# sentinel and fall back to viewer, granting the access it was meant to
# deny. Other role names stay case-sensitive.
if isinstance(v, str) and v.strip().lower() == "none":
return "none"
return v
+15
View File
@@ -67,6 +67,17 @@ def _decode_data_uri(url: str) -> tuple[str, bytes] | None:
return None
def _tool_names_by_id(messages: list[dict[str, Any]]) -> dict[str, str]:
"""Map each assistant tool call id to its function name."""
return {
tc["id"]: (tc.get("function") or {}).get("name") or ""
for msg in messages
if msg.get("role") == "assistant"
for tc in msg.get("tool_calls") or []
if tc.get("id")
}
def _parts_from_content(content: Any) -> list[types.Part]:
"""Convert OpenAI-style message content (str or multimodal list) to Gemini parts."""
if isinstance(content, list):
@@ -458,6 +469,7 @@ class GeminiClient(GenAIClient):
try:
# Convert messages to Gemini format
gemini_messages: list[types.Content] = []
tool_names = _tool_names_by_id(messages)
for msg in messages:
role = msg.get("role", "user")
content = msg.get("content", "")
@@ -520,6 +532,7 @@ class GeminiClient(GenAIClient):
parts=[
types.Part.from_function_response(
name=msg.get("name")
or tool_names.get(msg.get("tool_call_id") or "")
or msg.get("tool_call_id")
or "",
response=response_payload,
@@ -714,6 +727,7 @@ class GeminiClient(GenAIClient):
try:
# Convert messages to Gemini format
gemini_messages: list[types.Content] = []
tool_names = _tool_names_by_id(messages)
for msg in messages:
role = msg.get("role", "user")
content = msg.get("content", "")
@@ -776,6 +790,7 @@ class GeminiClient(GenAIClient):
parts=[
types.Part.from_function_response(
name=msg.get("name")
or tool_names.get(msg.get("tool_call_id") or "")
or msg.get("tool_call_id")
or "",
response=response_payload,
+17
View File
@@ -22,6 +22,7 @@ from frigate.api.chat import (
_execute_pending_tools,
_pending_tool_calls_from_tail,
_tool_calls_awaiting_approval,
_with_server_ids,
)
from frigate.api.defs.request.chat_body import ChatCompletionRequest
from frigate.genai.prompts import (
@@ -152,6 +153,22 @@ class TestApprovalHelpers(unittest.TestCase):
body = _body(tool_decisions={"c2": "approve", "c3": "reject"})
self.assertEqual(_tool_calls_awaiting_approval(pending, body, WRITE_TOOLS), [])
def test_repeated_provider_ids_get_unique_server_ids(self):
calls = [
{"id": "set_camera_state", "name": "set_camera_state", "arguments": {}},
{"id": "set_camera_state", "name": "set_camera_state", "arguments": {}},
]
renamed = _with_server_ids(calls)
self.assertEqual(len({tc["id"] for tc in renamed}), 2)
self.assertNotIn("set_camera_state", {tc["id"] for tc in renamed})
# A later call to the same tool is not covered by an earlier decision.
body = _body(tool_decisions={renamed[0]["id"]: "approve"})
later = _with_server_ids(calls[:1])
self.assertEqual(
len(_tool_calls_awaiting_approval(later, body, WRITE_TOOLS)), 1
)
class TestExecutePendingTools(unittest.TestCase):
def test_rejected_call_is_not_executed(self):
+36
View File
@@ -500,6 +500,42 @@ class TestGeminiProvider(unittest.TestCase):
final = _final_message(_collect(client, MULTIMODAL_MESSAGES))
self.assertEqual(final["content"], "ok")
def test_tool_response_name_resolves_from_call_id(self):
from google.genai.types import FinishReason
client = self._client()
self._patch_stream(
client,
[
_gemini_chunk(
parts=[_gemini_part(text="ok")], finish_reason=FinishReason.STOP
)
],
)
messages = [
{"role": "user", "content": "turn off recordings"},
{
"role": "assistant",
"content": None,
"tool_calls": [
{
"id": "call_abc",
"type": "function",
"function": {"name": "set_camera_state", "arguments": "{}"},
}
],
},
{"role": "tool", "tool_call_id": "call_abc", "content": "{}"},
]
_collect(client, messages)
contents = client.provider.aio.models.generate_content_stream.call_args.kwargs[
"contents"
]
self.assertEqual(
contents[-1].parts[0].function_response.name, "set_camera_state"
)
class TestGeminiImageTokens(unittest.TestCase):
def _client(self, count_tokens):
+1 -50
View File
@@ -95,42 +95,6 @@ class TestProxyRoleResolution(unittest.TestCase):
role = resolve_role(headers, self.proxy_config, self.config_roles)
self.assertEqual(role, self.proxy_config.default_role)
def test_custom_role_direct_header_ignores_case(self):
config = self.proxy_config
config.header_map.role_map = None
headers = {"x-remote-role": "garage"}
role = resolve_role(headers, config, ["admin", "viewer", "Garage"])
self.assertEqual(role, "Garage")
def test_role_map_to_missing_role_denies(self):
"""A group mapped to a deleted role must not widen to default_role."""
self.proxy_config.header_map.role_map = {"garage": ["group_garage"]}
headers = {"x-remote-role": "group_garage"}
role = resolve_role(headers, self.proxy_config, self.config_roles)
self.assertEqual(role, "none")
def test_unknown_default_role_denies(self):
for default in ("operatr", None):
with self.subTest(default_role=default):
config = ProxyConfig(
default_role=default,
header_map=HeaderMappingConfig(role="x-remote-role"),
)
role = resolve_role({}, config, self.config_roles)
self.assertEqual(role, "none")
def test_default_role_and_role_map_ignore_case(self):
roles = ["admin", "viewer", "Garage"]
config = ProxyConfig(
default_role="garage",
header_map=HeaderMappingConfig(
role="x-remote-role", role_map={"GARAGE": ["group_garage"]}
),
)
self.assertEqual(resolve_role({}, config, roles), "Garage")
headers = {"x-remote-role": "group_garage"}
self.assertEqual(resolve_role(headers, config, roles), "Garage")
class TestDefaultRoleNone(unittest.TestCase):
def setUp(self):
@@ -226,9 +190,6 @@ class TestDefaultRoleNone(unittest.TestCase):
)
self.assertEqual(role, "none")
def test_null_default_role_normalizes_to_none(self):
self.assertEqual(ProxyConfig(default_role=None).default_role, "none")
def test_other_role_names_stay_case_sensitive(self):
"""Only the deny sentinel is normalized; role names are untouched."""
config = ProxyConfig(default_role="Operator")
@@ -260,18 +221,8 @@ class TestReservedRoleNames(unittest.TestCase):
with self.assertRaises(ValidationError):
AuthConfig(roles={name: ["front_door"]})
def test_admin_and_viewer_reserved_in_every_casing(self):
for name in ("Admin", "VIEWER"):
with self.subTest(role=name):
with self.assertRaises(ValidationError):
AuthConfig(roles={name: ["front_door"]})
def test_role_names_differing_only_by_case_rejected(self):
with self.assertRaises(ValidationError):
AuthConfig(roles={"garage": ["front_door"], "Garage": ["back"]})
def test_case_variant_of_a_normal_role_still_allowed(self):
"""A mixed-case custom name is fine when it is not reserved."""
"""Only 'none' folds case; other role names are untouched."""
config = AuthConfig(roles={"Operator": ["front_door"]})
self.assertEqual(config.roles["Operator"], ["front_door"])
@@ -61,9 +61,7 @@ export default function CreateRoleDialog({
(config.cameras[b]?.ui?.order ?? 0),
);
const existingRoles = Object.keys(config.auth?.roles || {}).map((role) =>
role.toLowerCase(),
);
const existingRoles = Object.keys(config.auth?.roles || {});
const formSchema = z.object({
role: z
@@ -72,7 +70,7 @@ export default function CreateRoleDialog({
.regex(/^[A-Za-z0-9._]+$/, {
message: t("roles.dialog.form.role.roleOnlyInclude"),
})
.refine((role) => !existingRoles.includes(role.toLowerCase()), {
.refine((role) => !existingRoles.includes(role), {
message: t("roles.dialog.form.role.roleExists"),
}),
cameras: z