mirror of
https://github.com/blakeblackshear/frigate.git
synced 2026-10-30 10:20:30 +03:00
d3bc434e2dc2b14e3acde3236d3c55d94483533c
2634
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
d3bc434e2d | adapt analytics to free-form model scenes, split notice counts, and peewee 4 | ||
|
|
c527ca2b58 | fixes | ||
|
|
f3ab6cbda7 | Add the analytics preview API | ||
|
|
2a9a9edff4 | Send the daily analytics report from the main process | ||
|
|
2fd9c11dde | Add the analytics report transport | ||
|
|
89745dc903 | Build analytics reports from the section collectors | ||
|
|
e474db5008 | Add the health analytics collector | ||
|
|
df40ffd932 | Add the features analytics collector | ||
|
|
e0d9ef762b | Add the cameras analytics collector | ||
|
|
a155e0d79c | Add the detection analytics collector | ||
|
|
e0764dae58 | Add the install and hardware analytics collectors | ||
|
|
6cbae92f18 | Add the analytics state file | ||
|
|
355dc6fe93 | Add the analytics report schema | ||
|
|
47d7d6348e | Add analytics opt-in setting, prompt notice kind, and notice watermarks | ||
|
|
3dd59d9a44 |
Optimize Python Tests (#24823)
* Optimize tests * Address comments * Fix test |
||
|
|
bbf23ccce7 |
Refactor TFL so code is shared among all detectors (#24822)
CI / AMD64 Build (push) Canceled after 0s
CI / AMD64 Smoke Test (push) Canceled after 0s
CI / ARM Build (push) Canceled after 0s
CI / Jetson Jetpack 6 (push) Canceled after 0s
CI / AMD64 Extra Build (push) Canceled after 0s
CI / ARM Extra Build (push) Canceled after 0s
CI / Synaptics Build (push) Canceled after 0s
CI / Assemble and push default build (push) Canceled after 0s
|
||
|
|
4953c19a71 |
Miscellaneous fixes (#24820)
* keep base path in logout redirect * store manual event sub labels as verified objects Manual events created with a sub label were stored in the review item as "label: sub_label", so review previews and collapsed History cards showed a generic icon, the review label filter missed them, and the sub label never reached sub_labels for chips, notifications, or GenAI prompts. The object processor now publishes the label and sub label separately, and the review maintainer stores them as label-verified plus a sub_labels entry, the same as tracked objects. * only expire snapshots for events that still have one Snapshot expiry selected every event older than snapshot retention, including events whose snapshot was already deleted, so with snapshot retention shorter than alert/detection retention the same missing files were unlinked again every cleanup cycle until the event row expired. That was nearly free on local disk but caused constant metadata load on network shares. The expiry queries now filter on has_snapshot so each snapshot is deleted once. |
||
|
|
4f03480afd |
Fix audio worker startup after enabling a disabled camera (#24806)
CI / AMD64 Build (push) Canceled after 0s
CI / ARM Build (push) Canceled after 0s
CI / Jetson Jetpack 6 (push) Canceled after 0s
CI / AMD64 Smoke Test (push) Canceled after 0s
CI / AMD64 Extra Build (push) Canceled after 0s
CI / ARM Extra Build (push) Canceled after 0s
CI / Synaptics Build (push) Canceled after 0s
CI / Assemble and push default build (push) Canceled after 0s
* Fix audio worker startup after enabling a disabled camera * Document audio lifecycle test helpers * Focus audio startup coverage on the enabled update regression |
||
|
|
9769741713 |
Set modified time on case zip entries (#24803)
CI / AMD64 Build (push) Canceled after 0s
CI / AMD64 Smoke Test (push) Canceled after 0s
CI / ARM Build (push) Canceled after 0s
CI / Jetson Jetpack 6 (push) Canceled after 0s
CI / AMD64 Extra Build (push) Canceled after 0s
CI / ARM Extra Build (push) Canceled after 0s
CI / Synaptics Build (push) Canceled after 0s
CI / Assemble and push default build (push) Canceled after 0s
* set modified time on case download zip entries Case download zip entries were written with the zip format's 1980 placeholder date, so extracted files showed a blank or 1980 modified date. Each entry now uses the export's recording start time, converted with the UI timezone since zip times have no zone and extractors read them as local time. * clamp case zip entry dates to 1980 |
||
|
|
0dc05305ae |
Improve History playback after camera audio dropouts (#24793)
CI / AMD64 Build (push) Canceled after 0s
CI / AMD64 Smoke Test (push) Canceled after 0s
CI / ARM Build (push) Canceled after 0s
CI / Jetson Jetpack 6 (push) Canceled after 0s
CI / AMD64 Extra Build (push) Canceled after 0s
CI / ARM Extra Build (push) Canceled after 0s
CI / Synaptics Build (push) Canceled after 0s
CI / Assemble and push default build (push) Canceled after 0s
* skip vod clips that start after their audio ends When a camera's audio dropped out, a recording segment could end its audio early. If a playback range started past that point in the segment, nginx-vod saw no audio track in the first clip, failed the whole range with a track count mismatch, and left the player spinning for up to an hour of footage. Recording now stores each segment's audio length alongside its keyframe index, from the same ffprobe pass, and plan_clip skips a clip whose window starts at or after its audio ends when the range has other clips. A range made of only that clip still plays video-only, and legacy rows without the new column are unchanged. * keep audio skip consistent with playback Clips were skipped even when the range would be served video-only, and seeking into a skipped span landed on later footage. The skip now only applies when every row in the range carries audio, and seeks inside a zero-duration span land on the next clip. |
||
|
|
7d4b87946e |
Miscellaneous fixes (#24790)
* stagger the daily region grid rebuild across cameras Every camera requested its region grid at exactly 02:00, so the requests queued up in the dispatcher and held up recording segment inserts behind them. Each camera now picks a random offset of up to an hour. * only log ffmpeg crashes when restarting * round preview skeleton corners to match the player |
||
|
|
113d499a61 |
Update fastapi requirement from ==0.153.* to ==0.159.* in /docker/main (#24783)
* Update fastapi requirement from ==0.153.* to ==0.159.* in /docker/main Updates the requirements on [fastapi](https://github.com/fastapi/fastapi) to permit the latest version. - [Release notes](https://github.com/fastapi/fastapi/releases) - [Commits](https://github.com/fastapi/fastapi/compare/0.153.0...0.159.1) --- updated-dependencies: - dependency-name: fastapi dependency-version: 0.159.1 dependency-type: direct:production ... Signed-off-by: dependabot[bot] <support@github.com> * Move enum param hints to json_schema_extra for fastapi 0.159 FastAPI 0.159 no longer accepts extra keyword arguments on Path() and Query(), so passing enum= raised a TypeError on import. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: Josh Hawkins <32435876+hawkeye217@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
61fd753aed |
Add accelerated input transform support to zmq detector protocol (#24731)
* Let the zmq detector skip the input transform when the detector applies it _transform_input converts the frame to the model's layout and dtype before the detector sees it. For a remote detector that can apply the transform itself, often on a GPU, that work is done twice over and the tensor is sent in its most expensive form. The detector now reports input_transform_offload in the model handshake. When it does, Frigate sends the frame as captured (uint8 NHWC) and adds the model's expected input_tensor and input_dtype to the request header, so the detector can apply them. The model config is unchanged either way: the expected format is relayed, not overridden. The choice is read per frame rather than cached, because the detector redoes its handshake on a timeout or socket error, so restarting or upgrading it while Frigate runs already works and keeps working here. Negotiated rather than configured, for two reasons. The detector is what knows whether it can apply the transform, and a user who merely believed it could would send unconverted frames to a model that cannot take them. It also needs no config surface, which the device string format has no room for. On a 640x640 region, measured on a Ryzen 9 5900XT, the host-side cost of handing the detector a frame drops from about 4 ms to under 0.1 ms per detection, and the payload from 4.9 MB to 1.2 MB. Nearly all of it is tobytes(): np.transpose returns a view and astype keeps its strides by default, so the transpose is deferred to serialization, where it becomes a strided gather over the whole float32 tensor. The YUV to RGB conversion is unaffected and stays on the host. * Test that the handshake decides whether the input transform is applied Parameterized over the three handshake values against the header the detector ends up sending: reported, the frame goes over as captured uint8 NHWC with the model's input_tensor and input_dtype declared; not reported or absent, the existing transform runs and those fields are omitted. A second case drives a real reconnect -- a timed out request, then a handshake from an upgraded detector -- and checks the next frame follows the new answer rather than the one from startup. --------- Co-authored-by: Eric <eric@localhost> |
||
|
|
6e185ed36e |
Keep post capture after review items end (#24726)
* keep post capture segments after a review item ends The recording maintainer only loaded review items whose end_time was after the oldest cached segment, so once an item closed in the database the segments in its post_capture window no longer matched it. With continuous recording off and no motion after the item, everything past roughly the review cutoff_time was deleted from the cache instead of being kept for the full post_capture. The query bound now subtracts the camera's largest post_capture, and the per-item check still decides the exact cutoff. * fix mypy and add docstring |
||
|
|
a85526187e |
check every overlapping review item before dropping a recording (#24728)
Recording retention around review items applied only the first review item, in start order, whose pre and post capture window covered a segment. When an alert and a detection were close together, a quiet segment covered by both was dropped by the detection's motion mode without checking the alert's all mode. The loop also stopped at a review item that started too late to reach the segment, even when a later alert with a longer pre_capture did reach it. Both the recording maintainer and cleanup now check every review item whose window covers the segment and keep it if any of their retain modes would. |
||
|
|
f385065981 |
Miscellaneous fixes (#24753)
* materialize event counts in metrics endpoint The metrics endpoint stored a lazy peewee query on the shared Prometheus collector, and collect() ran it later. Overlapping scrapes run in separate threadpool threads, so two requests could execute and step the same query's sqlite cursor at once. The rows are now read with list() before they reach the collector. * fix fps overflow restarting ffmpeg after 3 seconds instead of 3 retry intervals This is a regression from 0.18. The watchdog has restarted ffmpeg after 3 consecutive fps overflow checks since #13651, which was 3 retry intervals (30s by default) when the loop ran every retry_interval. #21297 moved the loop to 1s ticks without converting the count, so the window shrank to 3s. camera_fps is a 10s average, so one burst of buffered frames after a stream hiccup could keep it over the limit long enough to restart a healthy camera, and the next reconnect burst could repeat it. The threshold is now 3 * retry_interval ticks. When the count filled while restarts were still rate limited, the watchdog logged "Exiting ffmpeg...", marked the camera offline and reset the count without restarting. The check now waits for can_restart, so the log, status and restart always happen together. * keep recording cleanup running after a failed pass An exception anywhere in a cleanup pass, such as an OSError from a read-only or unmounted storage path, ended the recording cleanup thread with nothing logged. Retention stopped until restart, and recordings, previews and database rows kept growing. Each pass now logs the exception and the loop continues. * expose frigate_camera_events as a gauge The metric reports the current count of events in the database, which drops when retention prunes old events. As a counter, each prune read as a counter reset, so increase() and rate() inflated event counts. The series name changes from frigate_camera_events_total to frigate_camera_events. The test's porch/inside assertion was missing its `in event.text` and always passed. * keep uvicorn idle connections open longer than nginx's upstream keepalive uvicorn closed idle connections after its 5s default while nginx kept them pooled for 60s, so a request nginx sent on a connection uvicorn was closing got a 502. nginx retries that on a fresh connection for most methods, but not for POST or PATCH. * snapshot websocket clients under the manager lock in the output loop The output loop iterated ws4py's live websocket dict without its lock, so a client connecting or disconnecting mid-iteration raised "dictionary changed size during iteration" and killed the output loop. It now copies the clients under manager.lock once per frame and skips terminated ones, matching the jsmpeg and birdseye broadcasters. * only cache preview frames when recording is enabled The segment-end check tested the record config object instead of record.enabled, and the first frame after startup was written unconditionally. With recording disabled, the first segment still cached frames and encoded a preview. * fix untranslated unknown resolution text in camera info dialog * detect all AMD GPUs from vainfo The vainfo check only matched "AMD Radeon Graphics", so drivers reporting names like "AMD Radeon Vega 8 Graphics", "AMD Radeon RX 6600", "AMD Custom GPU 0405", or older codename strings fell through and their GPU stats were collected as Intel. It now matches Mesa's "for AMD" driver string. * return a 500 instead of raising when go2rtc is unreachable The two go2rtc stream GETs had no exception handling or timeout, so a go2rtc outage raised a connection error with a traceback, and a hung go2rtc held the request open indefinitely. Both now catch request errors, log the cause, and use a timeout. The per-stream probe gets a 35s read timeout because go2rtc probes each source in turn, and one unresponsive source takes about 10s. * retry camera snapshots after a failed load AutoUpdatingCameraImage only scheduled the next frame from onLoad, so a single failed latest.webp request froze the image until the component remounted. It now retries on error, dropping the periodic cache key so the retry requests a fresh URL. * reuse pooled upstream connections for nginx auth subrequests The /auth subrequest proxied to a variable address, which nginx can't pool, and its location-level headers dropped the inherited Connection header so nginx sent Connection: close. Every authenticated request opened and closed its own loopback connection to the API. It now proxies to the frigate_api upstream with an empty Connection header so the keepalive pool is reused. |
||
|
|
91e91c68ef |
Add Axelera Metis NPU detector plugin v.0.19 (#24270)
CI / AMD64 Build (push) Canceled after 0s
CI / ARM Build (push) Canceled after 0s
CI / Jetson Jetpack 6 (push) Canceled after 0s
CI / AMD64 Smoke Test (push) Canceled after 0s
CI / AMD64 Extra Build (push) Canceled after 0s
CI / ARM Extra Build (push) Canceled after 0s
CI / Synaptics Build (push) Canceled after 0s
CI / Assemble and push default build (push) Canceled after 0s
* Add Axelera Metis NPU object detector plugin Runs Frigate inference on the Axelera Metis NPU through the vendor's low-level axelera.runtime API with pip-installed, sha256-pinned wheels from Axelera's public artifactory (self-contained: auditwheel-repaired libs + bundled firmware). - async send_input/receive_output contract (FIFO pairing, overload emits zero rows instead of raising, frames are copied out of camera shm) - generic YOLO-family decoder driven by the compiled model's manifest.json (padded input geometry, dequant params, baked postprocess graph via onnx) - labels come from the compiled model's model_info.json; empty labelmaps fail loudly at init * object_detection: async runner path for the axelera detector * detectors: detect_axelera probe (/dev/metis*) + device node init * stats: Axelera Metis board temperature poller The card exposes no utilization counter usable next to a live detector, so the poller reports the board-controller temperature read via axcmd (cached 5s; the read must not race detector init). * docs: Axelera Metis detector (install, config, model catalog, downloads) * axelera: expose Metis colon-name device node and image deps for runtime enumeration The Axelera runtime enumerates Metis cards via the colon-separated node name created by the vendor udev rule on the host (e.g. /dev/metis-0:1:0) and probes kernel state with lsmod/lspci. Containers only receive the raw /dev/metis-0-1-0 node, so the detector never found the card. - init-devices: create /dev/metis-BB:DD:F aliases for each Metis node - install_deps: add kmod and pciutils so the runtime's driver check works * axelera: review round 2 (downloader, stop release, pixel format, docs size, per-class NMS) - download model zips through ModelDownloader (atomic .part rename; a truncated download no longer poisons the cache) - stop(): release the Context (releases connection/model/instance); the previous instance.free() call never existed in the runtime API and was silently swallowed - honor input_pixel_format: flip to RGB planes only when Frigate delivers BGR (input_pixel_format: bgr); with rgb the frame passes through as-is - docs/catalog: width/height = compiled 640x640 input (square regions no longer get squashed twice), document input_pixel_format: bgr - NMS via xyxy_to_xywh_for_nms + per-class cv2.dnn.NMSBoxes, matching the other detector plugins instead of a hand-rolled class-agnostic pass * axelera: report Metis temperature only on the NPU card The same board readout was surfaced twice on the System page: once as the detector temperature (get_hardware_temperatures) and once on the NPU card (npu_usages). Keep the NPU card, where the value belongs. * axelera: report AIPU utilization as the detector run duty cycle The runtime exposes no device-side usage counter (mvm_utilisation is a configuration limit, not a readout), so the NPU card rendered empty. ModelInstance.run blocks until the AIPU completes: the detector process now times each run and publishes busy/wall over a 2s window through a small file under the tmp cache dir; the stats poller reads it and sets the npu key. A stale file (detector idle/restarting) reports nothing rather than a stale number. * axelera: cut hot-path allocations in preprocess and dequantise Preprocess reused three fresh arrays per frame (resize output, quantised copy, strided channel flip at write time) and refilled the whole padded input buffer. Now resize writes into a scratch with cv2 dst=, the BGR->RGB swap is a cvtColor into scratch (no strided copy), the int8 quantise runs with out=, and only the border strips the content rect does not cover get memset. Measured 39% faster on the 704x576 -> 640x640 path. Dequantise allocated two fp32 temporaries per head (astype then the dequant expression) before the transpose copy. copyto now casts int8->fp32 while transposing straight into a reused fp32 feed buffer, and the zp/scale math runs in place. Measured 78% faster for the YOLOX-S head set, outputs bit-identical (int8->fp32 cast is lossless). Argmax+gather replaces max+argmax (one class-axis reduction instead of two), and the postprocess session pins intra_op_num_threads=1: one frame is in flight through the decoder, extra ORT threads only add context switches. * axelera: publish the run duty cycle through a shared Value Replace the tmp-file duty-cycle handoff (and the FRIGATE_TMP env var nothing else reads) with a third multiprocessing.Value alongside avg_inference_speed and detection_start: ObjectDetectProcess creates it, AsyncDetectorRunner passes it to the detector, and the plugin publishes busy/wall of the blocking ModelInstance.run over a 2s window, mirroring how memryx receives its shared state. No filesystem path, no staleness window, no atomic rename, and stats/hardware.py no longer imports the plugin module to find the file. The producer also ticks the window while the queue is empty, so the duty cycle falls to 0 when the card idles instead of sticking at its last value. Name it what it is: host-side occupancy of the run call, including DMA and driver time, not an AIPU core counter (the runtime exposes no device-side one). The NPU entry now reads temperature from the board controller plus the detector-reported run duty cycle folded in where the detector processes are in reach. * axelera: enumerate devices explicitly and fail with an actionable error Context.list_devices() keys off the lspci BDF and needs the colon-form node to be present, so surface an empty enumeration at init with the fix-it hint instead of a bare device_connect(None) ConnectionError several frames deeper. Uses the DeviceInfo the runtime enumerated rather than relying on the pick-first implicit path. * axelera: deliver every accepted result under backpressure, reset duty cycle on restart Greptile P1: _push_result dropped a completion when the result queue was full, stranding the runner's send_times entry and the input SHM mapping (1 submission : 1 result contract). Replace the drop with a stop-aware blocking put so an accepted submission always produces exactly one delivered completion. Greptile P2: start_or_restart did not clear run_duty_cycle when starting a replacement process, so stats could show the previous process's duty cycle while the new detector was still initializing. Reset it to the -1.0 sentinel alongside detection_start, inside the async branch. Greptile P2 (offline docs): list axelera among the detector types whose pre-seeded runtime files live under /config/model_cache/runtimes/<type>. * axelera: reviewer round 3 (plugin-owned enumeration tools, generic DEVICE_ALIASES, generic duty-cycle fold) install_deps.sh: drop kmod/pciutils from the base image. The runtime's list_devices() only greps popen'd lspci/lsmod output over /sys and /proc, so the plugin now installs shell stand-ins in its own /config/model_cache/axelera/bin and prepends it to PATH when the real tools are missing (hardware-verified: the stand-in lspci prints the Device 1f9d:<id> line the runtime matches, the lsmod shape matches /proc/modules). init-devices: replace the Metis-keyed alias block with a generic DEVICE_ALIASES env var (comma separated alias=target pairs, next to DEVICE_ACL_PATHS). Docker rejects colon-named nodes in --device AND in bind mounts (probed: 'too many colons' on both the long volume form and the mount form), so the in-container symlink stays necessary; docs carry the pair users must set. stats/util.py: fold any detector's published run_duty_cycle into the matching npu_usages entry generically; _axelera_run_duty_cycle and the per-vendor branch are gone. plugin: the no-device RuntimeError now names the raw dash-form node (--device rejects colons, users can only pass the raw node) and points at DEVICE_ALIASES for the colon alias. * axelera: reviewer round 4 (aggregate shared-type duty cycles, american spellings) stats/util.py: several detector processes can share one hardware type (e.g. two axelera cards on one host). Iterating and assigning made the displayed NPU usage depend on dict order, last writer wins. Collect the published windows per type and write the busiest one, matching what the removed per-vendor helper did with max(). plugin: the remaining British spellings (dequantise family) corrected to the American forms the repo requires. plugin: model path resolution follows hailo8l's single-string pattern (URL or local path or preset name in one value), the download uses urllib directly like memryx, and _find_model_json now raises on an ambiguous multi-model directory instead of returning whichever sorts first. plugin: AxeleraDetector exposes shutdown() (the async contract hook base.py calls) instead of close(); __del__ guards a partially initialised instance. * axelera: download URL models through the atomic ModelDownloader * axelera: bring the detector unit tests in tree * init-devices: create DEVICE_ALIASES before the ACL-mode exits An alias is not an ACL grant: users running with FRIGATE_RUN_AS_ROOT or FRIGATE_DEVICE_ACLS=false still need the colon-form node the runtime enumerates, so create the aliases right after the euid check. Document DEVICE_ALIASES next to DEVICE_ACL_PATHS and note it cannot work under docker's user: mode (the container cannot write to /dev). * detectors: cover the Axelera Metis probe in test_detector_hardware * Update docs/docs/configuration/non_root.md Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com> * axelera: address the 2026-10-12 review round - hash directory models deterministically in compute_model_hash instead of raising IsADirectoryError at startup - keep canonical model labels addressable after user renames in the labelmap lookup (two classes can share one renamed name) - key the URL model cache by source and archive content, extract replaced archives into fresh directories, prune superseded variants conservatively - keep publishing the run duty cycle when the hardware poll has no entry (duty-only npu_usages entry instead of a hidden detector) - document the user: mode device reach instead of host-only alias creation * axelera: prune only generated cache entries A fresh download matched user-provided layouts (the docs-recommended <name>/ directory, <name>.zip archives) and look-alike model names (yolox.zip vs yolox-s-*) by prefix. Pruning is now gated on the exact generated identity pattern <name>-<source>-<32 hex digits>, so downloads never touch user-provided directories, other models, or other sources. * axelera: narrow the model path design to memryx-style zips - path is always a .zip of the compiled output (local or http(s) URL), extracted fresh on every start under a lock, like the memryx custom-model flow - _decode returns the raw class index and Frigate's labelmap names it; _build_label_lookup and _read_model_labels are gone, and the YOLOX objectness check keys off model_type - scheme-less URL support and the quantized/manifest.json fallback are dropped - width/height must equal the compiled input size; init raises otherwise instead of letterboxing - compute_model_hash is back to the unchanged file-only hashing; the .extracted marker, source/content cache-name hashes and _prune_model_cache are removed * Update frigate/test/test_axelera_detector.py Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com> * axelera: drop the run duty cycle, match the hailo temperature flow - no other accelerator reports NPU usage and the published value was time blocked in run(), not device utilization from the vendor API; removing it leaves the runner selection as the only core change - the board temperature moves to a get_hardware_temperatures branch like hailo, so it renders on the detector card; _poll_axelera, its POLLERS entry and the _scan_detectors line are gone - axelera_runtime2 is not installed: axelera.runtime imports it only inside a try for its separate new-runtime API, and the low-level API the plugin uses (Context, load_model, device_connect, load_model_instance) lives in axelera.runtime.objects * axelera: follow-ups from the 2026-10-13 review round - the offline-setup table no longer lists the axelera_runtime2 wheels, which are not installed - a failed board temperature read starts a 60s cooldown so an unresponsive axcmd does not delay every stats update * axelera: drop the model-hash test, fix the model.json error messages * axelera: drop DEVICE_ALIASES, document the CDI device spec * axelera: use ln -sf in the CDI hook example --------- Co-authored-by: Patryk Watkowski <patrykorwat@users.noreply.github.com> Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com> |
||
|
|
5bb2cde8b3 |
Reject cross-origin websocket connections (#24714)
CI / AMD64 Build (push) Canceled after 0s
CI / AMD64 Smoke Test (push) Canceled after 0s
CI / ARM Build (push) Canceled after 0s
CI / Jetson Jetpack 6 (push) Canceled after 0s
CI / AMD64 Extra Build (push) Canceled after 0s
CI / ARM Extra Build (push) Canceled after 0s
CI / Synaptics Build (push) Canceled after 0s
CI / Assemble and push default build (push) Canceled after 0s
* reject cross-origin websocket handshakes Neither /ws nor the jsmpeg websockets checked Origin, and the internal port grants admin to everyone, so any page a LAN user visited could open ws://frigate:5000/ws and send commands or read streams. Both servers now reject a browser handshake whose Origin host matches neither Host nor X-Forwarded-Host, and allow handshakes without an Origin for non-browser clients. nginx now forwards an outer proxy's X-Forwarded-Host instead of overwriting it, so proxies that rewrite Host and the Home Assistant integration's proxy still match. * apply runtime role changes to jsmpeg streams The output process never subscribed to config/auth, so role edits from the Roles UI (requires_restart 0) did not reach it and jsmpeg kept streaming cameras that had been removed from a role until restart. The output process now replaces its auth config on config/auth updates, which the camera and birdseye broadcast threads read through the shared config. * tidy origin check docstring and auth update comment * reject cross-origin go2rtc stream requests in /auth The go2rtc websockets and the webrtc offer POST still accepted any Origin, since go2rtc runs with origin "*" and /auth grants admin on the internal port, so a page on another site could pull live video through a LAN user's browser. nginx now passes Origin, Host, X-Forwarded-Host and Upgrade to /auth, which rejects a websocket upgrade or go2rtc stream request with a foreign Origin before the internal-port early return. The hostname rule moves to frigate/util/origin.py so /auth and the ws4py servers share it. * set Host in the nginx proxy doc examples * drain all queued auth updates in the output process * note that cards must stream through the integration proxy * strip the query before matching go2rtc paths in the origin check |
||
|
|
9a0672a64d |
Harden container startup (#24718)
CI / AMD64 Build (push) Canceled after 0s
CI / AMD64 Smoke Test (push) Canceled after 0s
CI / ARM Build (push) Canceled after 0s
CI / Jetson Jetpack 6 (push) Canceled after 0s
CI / AMD64 Extra Build (push) Canceled after 0s
CI / ARM Extra Build (push) Canceled after 0s
CI / Synaptics Build (push) Canceled after 0s
CI / Assemble and push default build (push) Canceled after 0s
* keep /config out of the root environment in the frigate run script
The script exported HOME=/config and prepended /config/.local/lib to LD_LIBRARY_PATH while still root, then ran python3, ffmpeg, grep, and opt_in_out as root. The runtime user owns /config, so it could plant a .pth file in the user site-packages or a library on the loader path and get code run as root on the next start. Root helpers now run with root's environment (and python3 -I), and HOME, LD_LIBRARY_PATH, and PATH reach only the dropped process through env on the s6-setuidgid line. opt_in_out runs as the runtime user, so the openvino marker no longer gets written into /config by root.
* don't follow a planted symlink when writing /dev/shm/go2rtc.yaml
After the first start the go2rtc user owned /dev/shm/go2rtc.yaml and could swap it for a dangling symlink. The run script's -f test was false for a dangling link, so the link survived, and root's create_config.py then created the link target and the chown handed it to go2rtc. The run script now removes any existing entry, create_config.py creates the file with O_EXCL and O_NOFOLLOW at mode 0640, and the chown uses -h.
* run root python helpers in isolated mode and keep HOME=/config for non-root containers
The previous commit only set HOME=/config when dropping from root, so a container started with --user lost it. The other root-run helpers in the go2rtc, nginx, and certsync scripts now use python3 -I too, so they never load user site-packages or PYTHON* variables.
* validate networking.listen values before rendering them into nginx config
ListenConfig and get_nginx_settings.py only checked that the text after the last colon parsed as an int, and tempio rendered the raw string into the listen directive, so a value like "5000; location /x/ { alias /; } #:5000" injected nginx directives. Both now go through parse_listen_address, which accepts only a port, IPv4:port, or [IPv6]:port with a 1 to 65535 port and rebuilds the value from the parsed parts. get_nginx_settings.py falls back to the default port on an invalid value so nginx still serves the safe-mode UI.
* tighten comments
* accept hostnames, wildcards, and padded values in networking.listen
The stricter parser broke localhost:5000, *:5000, and values with surrounding whitespace that the old int() parsing accepted. parse_listen_address now strips the value and accepts RFC 1123 hostnames and *, still rebuilding the rendered value from the parsed parts. The ListenConfig validator runs in before mode, because pydantic coerced true to port 1 while get_nginx_settings.py rejected it and fell back to 5000, so the auth internal port and nginx disagreed.
* always create go2rtc.yaml after removing it and don't let opt_in_out stop frigate
The go2rtc else-branch was only reachable when a regular file was planted between rm and the test, and then loaded that file as go2rtc's config. create_config.py now runs unconditionally and its exclusive create fails closed. opt_in_out runs after s6-svc -O, so a failure there was terminal under errexit.
* fall back to default listen ports when either is invalid or they collide
* keep valid listen values and refuse to start nginx when the ports collide
|
||
|
|
3d3f6a0678 |
Harden web push notifications (#24715)
* reject push endpoints that crash the vapid audience parse The validator accepted hostnames like "." so https://./x passed, and check_registrations then raised ValueError slicing the endpoint, killing the dispatcher's IPC thread. The validator now rejects empty hostname labels and lives in webpush.py, the audience comes from urlparse, and _build_web_pushers skips stored rows whose endpoint fails validation. * keep the ipc thread alive when a handler raises An exception from any dispatcher handler escaped InterProcessCommunicator.read, which only caught ZMQError. The REP thread died owing a reply, so every InterProcessRequestor blocked forever. read now logs the error and replies with an empty response, and Dispatcher.publish and publish_local catch per communicator so one failing communicator can't take down the rest. * stop push sends from reaching internal addresses pywebpush posts through requests with redirects enabled, so an endpoint could answer 307 to http://127.0.0.1:5000/api/restart and the sender would follow it into the internal admin port on every alert. Pushers now use a session that never follows redirects, and each send first resolves the endpoint host and skips it unless every address is global. * keep the previous region grid when the refresh request fails The IPC reader now replies [] when a handler raises, and process_frames assigned that reply to region_grid unconditionally. The next region lookup then indexed into an empty list and killed the camera's detect process. An empty reply now keeps the current grid until the next daily refresh. * drop the send-time public address check Refusing non-global resolved addresses broke Tailscale (100.64.0.0/10), split-horizon DNS and HTTPS_PROXY-only setups, and added little once redirects are no longer followed and TLS verification stays on. * only skip stored push rows that break the vapid audience Running the full registration validator over stored rows dropped self-hosted endpoints registered before 0.18 with a non-443 port or a bare / path. _build_web_pushers now skips only non-dict rows, rows with no endpoint, unparsable endpoints and hosts with empty labels, and the warning names the host so the row can be found. Registration still uses the full validator. |
||
|
|
53ca9c929b |
Mask all camera credentials in config (#24719)
* mask every credential form in camera and go2rtc urls
The credential mask only matched a userinfo with a [A-Za-z0-9_-] username or the exact user=..&password=.. query order, so dotted or email usernames, password-only userinfo (tapo://pw@host), empty usernames, reversed or renamed query credentials, and token query strings (ring refresh_token, nest client_secret, homekit client_private) reached every authenticated user through /config, /go2rtc/streams, /stats and /metrics. clean_camera_user_pass now masks any userinfo and any credential-named query parameter, and the config save restore and the settings UI detect masked paths with the same patterns so a save never writes the mask back over the real credential.
* redact go2rtc rtsp, api and webrtc credentials in /config
/config cleaned only go2rtc.streams, so go2rtc.rtsp and go2rtc.api usernames and passwords and the WebRTC ICE server credentials went back verbatim to any authenticated user. They now use the redaction sentinel like the MQTT and ONVIF passwords. Config save already dropped a field equal to the sentinel, but lists are leaf values after flattening, so an ice_servers list echoed back from /config would have written the sentinel to disk. Save now drops any value that contains it.
* bound the credential mask to the url authority
The userinfo pattern ran from any host:port to the last "@" in the token, so rtsp://host:554/live?x=a@b lost its host and a comma between two URLs was swallowed, which merged the paths /ffprobe splits on. It also backtracked quadratically on long lines with many "://", and every subprocess log line goes through it. A "user:" userinfo now runs to the last "@" before the next URL unless a port follows the colon, and any other userinfo stops at the end of the authority. Query masking now covers only real secret names, so auth, private and autoken are left alone.
* restore masked credentials by value on config save
Masked camera paths were restored by index, so deleting the first input wrote its credentials onto the next input. Each masked path now matches the saved input that masks to the same value, with roles breaking a tie, and an unmatched or ambiguous path is rejected instead of written. A redacted ICE server is filled from the saved server with the same urls, or rejected when its urls changed, instead of dropping the whole list. /config also redacts the go2rtc mqtt credentials, the ngrok command, homekit pins and pairings, and publish destinations.
* restore masked camera paths from the saved yaml
Masked paths were restored from the in-memory config, where {FRIGATE_*} placeholders are already resolved, so saving an untouched camera replaced the placeholder in config.yml with the real secret. Masked paths now restore from the YAML on disk, matched against each saved path with its placeholders resolved, so the path is written back as it was. In-memory saves still restore from the live config.
* mask passwords that start with digits
The port check in the userinfo pattern also matched passwords, so rtsp://admin:2024/pw@host and rtsp://admin:12#abc@host went out unmasked where the old regex masked them. The check is gone. Stopping at the next "://" already keeps the comma between two ffprobe paths, and a host:port/path@x is over-masked for display only, since saves restore it by value.
* reject config saves that still hold masked credentials
Index-keyed input maps, query-string saves and go2rtc stream lists echoed from /config bypassed the credential restore and could write a masked path or the redaction sentinel over the real value. Every save, body or query string, now rejects any value that still holds one after the restores run, naming the field.
* fix partial password masking and ambiguous ice server restore
- Mask userinfo before query params so a credential key inside a password can't leave the rest of it visible
- Reject restoring redacted ice servers when saved servers share urls but hold different accounts
* mask the whole url when userinfo and a query credential overlap
Masking userinfo first leaked the tail of a query password holding "@" on URLs with a port, like rtsp://10.0.0.2:554/live?password=pre@suf. When the userinfo span contains a credential query key, the mask now covers the rest of the URL in both clean_camera_user_pass and maskCredentials.
* resolve placeholders with dev's env module
* reveal camera paths by masked value instead of position
After deleting or reordering inputs in the camera ffmpeg form, the path widget looked up raw_paths by index and revealed another input's real path, which a save then wrote with the wrong roles. The widget now matches the saved path whose mask equals the field's value, the same rule the backend uses on save, and doesn't reveal when there is no single match.
* stop redacting ice servers and break camera path ties by role
The WebRTC player passes /config's ice_servers to RTCPeerConnection, so redacting them sent the placeholder as the TURN account. ICE servers are no longer redacted and the restore code for them is removed. The camera path widget now uses the input's roles to pick between saved paths that mask to the same value, as the backend does on save.
|
||
|
|
796aec7a4a |
Limit concurrent motion searches (#24717)
* limit concurrent motion search jobs and search range Any viewer could start unlimited motion search jobs over an unbounded time range, and finished jobs were never dropped from memory. Each user now gets one active job (409), at most 3 run at once (429), the range is capped at 48 hours, and finished jobs are evicted 10 minutes after they end. Jobs are no longer filed in the shared job manager, which kept every finished job forever. * show translated errors for motion search limits * release the motion search slot if the runner fails to start * keep wedged or shared-identity motion searches from locking out users A stalled VOD read blocked the runner forever, so a wedged job held its user and global slot until restart, and on installs without per-user identity (internal port, or auth disabled without a proxy user header) everyone shared one per-user slot. VOD ffmpeg and ffprobe inputs now use a 30 s rw_timeout, a cancel also drops queued parallel runs, a cancelled job stops counting after 60 s, and the per-user limit only applies when the request carries a real username. A failed runner start also stops its requestor. * treat timed-out VOD segments as motion search errors With rw_timeout, the HLS demuxer skipped a timed-out segment and exited cleanly, so a run reported success with a hole in it, and when the keyframe probe and the decode lost different segments the equal frame counts paired frames with the wrong timestamps. The keyframe path now requires the probe to cover the whole run without a gap over 5 s, a decode whose stderr shows a skipped segment fails the run, and a cadence decode more than 5 s short of the run's duration fails it too, so these runs land in segments_with_errors. The keyframe probe polls should_stop and is killed on cancel, probe_video_dimensions gets the read timeout, and a user's own cancelled job no longer blocks their next search while it still counts toward the global cap. * drop motion search stall detection and range cap * remove motion search range check from the UI |
||
|
|
6ba3198232 |
Revoke stale sessions in /auth (#24713)
* take the jwt role from the user and revoke stale sessions /auth trusted the role claim in the token, and only checked password_changed_at when refreshing a cookie. Demoting or deleting a user, changing a password, or resetting the admin password left existing cookies and bearer tokens working with their old role. The API now keeps each user's role and password change time in memory, loads it at startup, and updates it from the user endpoints. /auth rejects unknown users and tokens issued before the last password change, and authorizes with the stored role without touching the database. Resetting the admin password now sets password_changed_at. * set the secure cookie flag when the request arrived over tls The session cookie only got the Secure flag from auth.cookie_secure, which defaults to false even though TLS is on by default, so browsers would send it over plain HTTP. The cookie is now Secure whenever nginx reports an https scheme, and nginx passes that scheme to the /auth subrequest so refreshed cookies match. cookie_secure still forces the flag for a reverse proxy that terminates TLS in front of plain-HTTP Frigate. * regenerate config schema mock data * revoke tokens issued in the same second as a password change /auth compared the token's whole-second iat against the truncated change time, so a token issued earlier in the same second as a password change stayed valid. The change time is now rounded up, and the cookie reissued to a user who changes their own password carries that rounded-up iat so it still passes. * note that a proxy on the tls port must serve https to browsers * reject users whose role was removed from the config A user whose role was removed from the config fell back to viewer, which has no camera restrictions, so a restricted role removed from yaml gained access to every camera. /auth now rejects that user's tokens, and login refuses them until an admin assigns a valid role. * floor password change time to match iat The password change time was rounded up while the token iat was rounded down, so a login in the same second as a password change got a token that /auth rejected as revoked. Both are floored now, which leaves a sub-second window where a token issued just before the change stays valid. * set password_changed_at on user creation A recreated username had no password change cutoff, so an unexpired token from the deleted account passed /auth with the new account's role. Creating a user now sets the cutoff to the creation time. |
||
|
|
d7bb780ff8 |
Upgrade to ROCm 10.1 (#24708)
* Update to ROCm 10.1 * Update docs for new setup |
||
|
|
275e18403e |
Miscellaneous fixes (#24704)
* remove unreachable FileNotFoundError catches around frame_manager.get * clear the end time cache entry when a segment is moved The successful move returned before the end_time_cache pop at the bottom of move_segment, so every kept segment left its entry, keyframes list included, in the cache for the life of the process. Removing the cache file through drop_segment clears the entry with it. * drop the cache file when the recording destination already exists When the destination mp4 already existed, move_segment returned without removing the cache file, so the next pass probed and resolved the same segment again, forever. The leftover file is now dropped along with its end time cache entry, the same as the exception path. * pace restarts of exited record and audio ffmpeg processes The watchdog loop runs every second, and an exited record or audio ffmpeg was restarted on every pass with no backoff. A camera that refuses connections, such as one rebooting or rejecting credentials, got a reconnect attempt and a dump of ffmpeg's logs every second until it came back. The restart is now gated on can_restart like the stale segment and detect paths. * don't send a stray newline in the certsync tls probe The probe piped echo into openssl s_client, which sent the newline to nginx as a request after the handshake, so nginx logged an empty "" 400 line every 60 seconds on any install with TLS enabled. Reading stdin from /dev/null closes the connection right after the handshake. The fingerprint and the failure logging are unchanged. * require a record expire_interval of at least 1 An expire_interval of 0 or less made the cleanup loop iterate over an empty range, so the cleanup thread exited on startup and expired recordings, temp clips and previews were never removed. * remove the transcription temp wav when whisper raises The temp wav was only removed after a successful transcribe call, so every failed transcription left a file in the cache directory. * don't kill the ipc responder when a described event is gone handle_update_event_description used Event.get, so a GenAI description that finished after its event was deleted raised DoesNotExist on the inter-process REP thread. That thread died with a reply still owed, and every process waiting on the requestor hung until restart. A missing event is now skipped. * size the birdseye frame from the snapped canvas shape The birdseye writer sizes its shared memory with get_canvas_shape, which snaps an unsupported aspect ratio such as 1920x1200 to a supported one, but the tracked object processor read it with the raw config width and height. The sizes never matched, so get returned None on every call and /api/birdseye/latest.jpg returned a 500, which broke the Home Assistant birdseye entity's still image. The reader now uses the same canvas shape, and a missing frame during startup returns an error response instead of raising in cvtColor. * remove dead disconnect timer from the mse player The effect that scheduled a delayed disconnect when playback was disabled never ran its body. The connect effect's cleanup already calls onDisconnect, which clears wsRef before the later effect checks it. * remove partial output when a recording move fails A remux that failed partway, such as on a full disk, left a partial mp4 at the destination. The next pass saw the destination already existed and dropped the cache file instead of retrying, so the segment was never saved. The failed output is now removed so the next pass retries the move. Tests cover the success, existing destination and failed move paths of move_segment. |
||
|
|
c177849f57 |
Tweaks (#24684)
* bound recording snapshot lookups by segment length Ordering the recording snapshot and Frigate+ lookups by stream_type ahead of start_time broke index order, so SQLite fetched and sorted every older recording for the camera on each request (about 100 ms on a 30 day camera, run on the event loop). A start_time lower bound of the frame time minus MAX_SEGMENT_DURATION keeps the lookup to a few rows. * bound recording overlap queries by segment length Clip, export, review and recording deletion, debug replay, motion search, and audio transcription found overlapping recordings with an OR clause that gave SQLite no start_time range, so every call read the camera's whole recording history (30 to 300 ms on a 30 day database). The classification and review description point lookups did the same whenever the timestamp had no recording. A shared recording_overlap helper now adds a start_time lower bound of MAX_SEGMENT_DURATION before the range, which drops no rows because segments are always shorter than that. * probe webrtc before reporting it as not configured The WebRTC gate read only the Frigate config, so an install with no go2rtc candidates showed WebRTC as not configured, even though go2rtc fills in default candidates at startup (including the internal one under the HA app) and WebRTC often worked. Unset candidates now run the connectivity probe first, and only a failed probe reports not configured. The not-configured reason shows as a neutral note that names the setting and says WebRTC is optional, rather than as a red error. * validate trusted_proxies at config load Malformed trusted_proxies entries were only parsed per request in get_remote_addr, so a typo logged a warning on every proxied request and the entry was skipped, collapsing all clients behind that proxy into one rate-limit bucket. The config now rejects unparseable entries at startup and get_remote_addr no longer needs the fallback. Host bits are accepted (192.168.1.1/24 reads as 192.168.1.0/24) so a common typo doesn't take down safe mode, which copies the auth section verbatim. * remove path data from thumbnail payloads The thumbnail data carried a full copy of the object's path, which went out as snapshot.path_data in every events message alongside the top level path_data. Nothing reads the snapshot copy, and the path has no length limit, so it only made events payloads larger. * hide incompatible frigate+ models behind a toggle * keep the probe failure detail in the not-configured console message * use a unique id for each show incompatible models toggle * pad the bottom of the desktop timeline so zoom buttons don't cover segments * create the admin row when auth is disabled so notification registrations persist Installs that never enabled auth had no admin row, so registering for notifications returned 200 but saved nothing. Frigate now creates an admin row with an empty password hash when auth is disabled, and treats that empty hash as first-time setup when auth is enabled later so a password is still generated and printed. Registration returns 404 when no user row was updated, and the success toast only shows after the request succeeds. The Users settings page hides Add User and Reset Password when auth is disabled and notes that accounts only apply once built-in auth is enabled. |
||
|
|
c9f7cc8165 |
Compare mask coordinates numerically (#24666)
CI / AMD64 Build (push) Canceled after 0s
CI / AMD64 Smoke Test (push) Canceled after 0s
CI / ARM Build (push) Canceled after 0s
CI / Jetson Jetpack 6 (push) Canceled after 0s
CI / AMD64 Extra Build (push) Canceled after 0s
CI / ARM Extra Build (push) Canceled after 0s
CI / Synaptics Build (push) Canceled after 0s
CI / Assemble and push default build (push) Canceled after 0s
* Compare mask coordinates numerically * Fix zone coordinate comparisons and normalize mask examples * Fix validation errors for malformed zone coordinates |
||
|
|
62ca5b25ea |
Merge remote-tracking branch 'origin/master' into dev
CI / AMD64 Build (push) Canceled after 0s
CI / AMD64 Smoke Test (push) Canceled after 0s
CI / ARM Build (push) Canceled after 0s
CI / Jetson Jetpack 6 (push) Canceled after 0s
CI / AMD64 Extra Build (push) Canceled after 0s
CI / ARM Extra Build (push) Canceled after 0s
CI / Synaptics Build (push) Canceled after 0s
CI / Assemble and push default build (push) Canceled after 0s
|
||
|
|
15da89e56c |
Avoid buffering raw frames during watchdog resets (#24663)
* Don't buffer detect ffmpeg stdout when resetting the capture thread reset_capture_thread waited for the terminated detect process with communicate() on the no-frames and stale sub stream paths. communicate() reads the process's raw frames into memory until it exits, and a stalled detect process can write hundreds of duplicate frames per second before it does. Use wait() on every path, as the fps-exceeded path has since #19110; the timeout and kill still bound the wait. * Update frigate/video/ffmpeg.py accurately explain why wait() is safe Co-authored-by: Josh Hawkins <32435876+hawkeye217@users.noreply.github.com> * test(watchdog): remove non-regression child process test The Python child exits on SIGTERM, so this test also passes with the original communicate() reset. Keep the two mock tests that distinguish the fix and remove the unused imports. --------- Co-authored-by: Josh Hawkins <32435876+hawkeye217@users.noreply.github.com> |
||
|
|
64b07889af |
Tweaks and fixes (#24659)
* add last time to active notices * Stop retrying the review lookup in the explore detail menu when it 404s * don't let a slow websocket client block publishers A websocket client that stopped reading its socket (for example a suspended workstation with a Frigate tab open) blocked ws4py's sendall on whatever thread was publishing, including the single inter-process responder thread, so the recording maintainer and stats hung until nginx dropped the client after 5 minutes. Each client now gets its own bounded send queue and writer thread, and a client that overflows the queue is shut down. ws4py writes close and pong frames directly on its shared manager thread, bypassing the queue, so a 10s socket send timeout keeps a stalled client from pinning that thread. The jsmpeg and birdseye outputs share the class, so their unreachable send error handling is removed. * don't let a lost object enter a zone When the detector lost an object, the tracker kept it at its last box and every held frame still counted toward the zone's inertia. A car detected in a zone once or twice as it drove out of view could reach an inertia of 8 and be marked as entering, which sent it to GenAI and any other required zones check even though Review never showed the zone. Inertia and loitering still count on frames without a detection, but an object can only newly enter a zone on a frame where it was actually detected. * add test * limit retry stop to 404 only * add docstrings |
||
|
|
cfa08c56b2 |
Normalize request paths in media auth (#24662)
CI / AMD64 Build (push) Canceled after 0s
CI / ARM Build (push) Canceled after 0s
CI / Jetson Jetpack 6 (push) Canceled after 0s
CI / AMD64 Extra Build (push) Canceled after 0s
CI / ARM Extra Build (push) Canceled after 0s
CI / Synaptics Build (push) Canceled after 0s
CI / Assemble and push default build (push) Canceled after 0s
* merge repeated slashes in the media auth path check X-Original-URL carries only the raw request path since #24602, and extract_path parsed it with urlparse, which reads a path starting with // as a host. A restricted role could request another camera's clips or recordings with a leading // and the media check saw a non-media path and allowed it, while nginx merged the slashes and served the file. extract_path now splits the raw URI the same way the go2rtc stream check does and merges repeated slashes as nginx does before matching locations. The split helper moves from auth.py into media_auth.py so both checks share it. * check the nginx-normalized path in the media auth dot-segment fallback The dot-segment fallback only checked the raw first segment, so a role restricted to one camera could request `/x/../clips/back_door-1.jpg` and nginx served back_door's clip. The fallback now resolves the path the way nginx does before checking for a media root, and the URI split ends at a literal `#` since nginx ignores everything after it. |
||
|
|
2b0a69c028 |
Merge remote-tracking branch 'origin/master' into dev
CI / AMD64 Build (push) Canceled after 0s
CI / AMD64 Smoke Test (push) Canceled after 0s
CI / ARM Build (push) Canceled after 0s
CI / Jetson Jetpack 6 (push) Canceled after 0s
CI / AMD64 Extra Build (push) Canceled after 0s
CI / ARM Extra Build (push) Canceled after 0s
CI / Synaptics Build (push) Canceled after 0s
CI / Assemble and push default build (push) Canceled after 0s
Brings the go2rtc security fixes from #24658 to dev. Dev-specific changes in the merge: - frigate/config/env.py stays deleted; the environment_vars protection for GO2RTC_ALLOW_ARBITRARY_EXEC moves to apply_config_env_vars in frigate/util/env.py, so the value never reaches os.environ - services.py imports substitute_frigate_vars from frigate.util.env and maps UnknownVariableError to the unknown variable message - go2rtc stream tests patch dev's import-time exec override snapshot and its FRIGATE_* variable sources - test_http_media.py keeps dev's _insert_recording helper; the one added on master replaced it and broke the dev tests Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
a3ca8742b0 |
Security patches (#24658)
CI / AMD64 Build (push) Canceled after 0s
CI / ARM Build (push) Canceled after 0s
CI / Jetson Jetpack 6 (push) Canceled after 0s
CI / AMD64 Extra Build (push) Canceled after 0s
CI / ARM Extra Build (push) Canceled after 0s
CI / Synaptics Build (push) Canceled after 0s
CI / Assemble and push default build (push) Canceled after 0s
* update version * Restrict ffmpeg: go2rtc sources added through the API go2rtc expands ffmpeg: sources into an exec: command line built from the source's #key=value parameters, so the echo/expr/exec prefix check on PUT /go2rtc/streams could be bypassed to run arbitrary ffmpeg arguments. Sources submitted through the API now only accept the ffmpeg: parameters the UI and docs use (video, audio, hardware with preset names, plus numeric width/height/rotate/bitrate/timeout and async). Quotes, whitespace, #raw, #input, #drawtext and unknown parameters are rejected unless GO2RTC_ALLOW_ARBITRARY_EXEC is set. Sources defined in the config file are unchanged. Fixes GHSA-qjjw-3v66-279f Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Only allow existing streams on proxied go2rtc live paths nginx proxies /live/mse/api/ws, /live/webrtc/api/ws and /api/go2rtc/webrtc straight to go2rtc, which creates a new ad hoc stream from any src that is not an existing stream name and starts the producer it describes. Any authenticated user, including the built-in viewer role, could use this to launch arbitrary go2rtc sources without going through the restricted-source checks on PUT /go2rtc/streams. The /auth subrequest now denies these paths unless every src names an existing stream: a camera or its live stream, a go2rtc stream from the config, or a stream go2rtc reports at runtime. This applies to every role, and the runtime lookup fails closed when go2rtc cannot be reached. Fixes GHSA-93xj-hg88-ffg7 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Ignore GO2RTC_ALLOW_ARBITRARY_EXEC in environment_vars environment_vars installs every key into the Frigate process environment at startup, so an admin could enable GO2RTC_ALLOW_ARBITRARY_EXEC from the config and turn off the restricted go2rtc source checks on the API. The override is meant to be set by the operator in the container environment (or the Home Assistant add-on options), so it is now skipped with a warning when it appears in environment_vars. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Apply go2rtc source restrictions to config/save and config/set go2rtc.streams written through config/save or config/set were only filtered at startup, which blocks echo/expr/exec and the map form but not the ffmpeg: parameters that PUT /go2rtc/streams now rejects. Saving a stream this way and restarting bypassed the API restriction. Both endpoints now reject a change that adds a go2rtc stream source that fails is_restricted_go2rtc_api_source, or a map-form source, unless GO2RTC_ALLOW_ARBITRARY_EXEC is set. Sources already in the saved config for the same stream are left alone, so streams configured on disk keep working and resubmitting the whole file from the config editor succeeds. config/set restores the previous file when it rejects a change. Follow-up to GHSA-qjjw-3v66-279f Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Match go2rtc stream-proxy paths the way nginx does /auth compared the raw $request_uri path against the three go2rtc stream-proxy paths exactly, while nginx matches its prefix locations against the normalized URI. Encoded characters, repeated slashes, dot segments or a suffix on the path skipped the stream check even though nginx still proxied the request to go2rtc. The go2rtc stream locations now set a variable that the auth subrequest forwards as X-Go2rtc-Stream-Proxy (client headers are not forwarded, so it cannot be spoofed). As a fallback, /auth also normalizes the path like nginx (percent-decoding, merging slashes, resolving dot segments) and prefix matches it, and splits the raw URI by hand since urlparse reads a leading // as a host. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Parse config stream changes with Frigate's YAML loader The go2rtc stream check on config/save and config/set parsed the config with the safe loader and treated a parse error as an empty config, while Frigate and the go2rtc startup script use the round-trip loader. Input that only the round-trip loader accepts, such as a tagged root map, hid new stream sources from the check. The check now uses the same round-trip loader and rejects the request when the new config cannot be parsed. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Resolve go2rtc stream placeholders the same way everywhere The go2rtc startup script expanded stream sources with str.format(), which also supports attribute and index access, while the config API check used substitute_frigate_vars and fell back to the raw string when a placeholder could not be resolved. A placeholder the API check could not resolve could therefore expand into a restricted source at startup. The startup script now uses substitute_frigate_vars, like the rest of the config, and the API check rejects a stream source whose placeholders cannot be resolved. The startup script's own copy of the FRIGATE_* env var map is removed; the shared one also honors CREDENTIALS_DIRECTORY. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Accept codec sample rates in ffmpeg: go2rtc sources The ffmpeg: parameter allowlist only accepted plain names for video, audio and hardware, so the documented HomeKit source with #audio=opus/16000 was rejected by PUT /go2rtc/streams, config/save and config/set. Names may now carry a numeric /rate suffix. A rate without a name is still rejected. All ffmpeg: sources in the docs pass the check. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Restore the environment after go2rtc exec override tests Tests that removed or set GO2RTC_ALLOW_ARBITRARY_EXEC did not restore a value that was already present, so later tests could run with a changed security setting. They now use patch.dict on os.environ. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Revert the go2rtc startup script to str.format substitution Restores create_config.py to its state on master. The config API check rejects any stream source whose {FRIGATE_*} placeholders it cannot resolve with substitute_frigate_vars, and for every source it accepts, str.format() at startup either produces the same string or fails and stops go2rtc startup. Changing the startup script is therefore not needed for the fix, and leaving it alone avoids a conflict with dev, which already moved this script to the new env helpers. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Explain why a go2rtc stream change was rejected A stream source with an undefined or malformed {FRIGATE_*} placeholder was reported as a restricted source, which reads like a security block when the user made a typo. The config API now reports unknown variables and invalid placeholders separately from restricted sources. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |
||
|
|
b79e043976 |
Reduce idle CPU from thread pools (#24652)
CI / AMD64 Build (push) Canceled after 0s
CI / ARM Build (push) Canceled after 0s
CI / Jetson Jetpack 6 (push) Canceled after 0s
CI / AMD64 Smoke Test (push) Canceled after 0s
CI / AMD64 Extra Build (push) Canceled after 0s
CI / ARM Extra Build (push) Canceled after 0s
CI / Synaptics Build (push) Canceled after 0s
CI / Assemble and push default build (push) Canceled after 0s
* reduce idle cpu from onnxruntime and opencv thread pools ONNX Runtime's intra-op threads kept spinning for about 1 s after every run, so a CPU enrichment called once a second or more kept most cores busy. On a 16 thread machine, arcface at one call per second used 9.4 s of CPU per call with ~360 ms latency. Enrichment sessions on the CPU execution provider now set `session.intra_op.allow_spinning` to 0, which drops that to 1.9 s with no latency change. Detector sessions and GPU providers are unchanged, since disabling spinning doubled yolov9-t latency on CPU (12 to 23 ms). The output and embeddings processes now run OpenCV single threaded, like the camera tracking process. A 4 camera birdseye redraw at 1080p drops from 13.7 to 4.0 ms of CPU, and the full frame conversion in the enrichment processors from 23 to 2.7 ms, each adding about 1 ms of wall time. * test that only cpu enrichment sessions disable ort spinning * patch out the neural engine in the spinning test |
||
|
|
e61ad52b67 |
move env helpers out of the config package (#24648)
CI / AMD64 Build (push) Canceled after 0s
CI / AMD64 Smoke Test (push) Canceled after 0s
CI / ARM Build (push) Canceled after 0s
CI / Jetson Jetpack 6 (push) Canceled after 0s
CI / AMD64 Extra Build (push) Canceled after 0s
CI / ARM Extra Build (push) Canceled after 0s
CI / Synaptics Build (push) Canceled after 0s
CI / Assemble and push default build (push) Canceled after 0s
go2rtc's create_config.py imported frigate.config.env, which ran the frigate.config package init and loaded every detector plugin. Since the onnxruntime 1.30 bump, importing onnxruntime takes about 5s on some hosts, so go2rtc started after Frigate's cameras and every ffmpeg process failed to connect to the restream until it came up. The env helpers now live in frigate.util.env, so go2rtc's config script no longer imports onnxruntime. |
||
|
|
ff9eb8f184 |
Keep frame shared memory mapped (#24644)
* keep frame shm open and skip overwritten frames
Every reader closed and reopened a frame's shared memory segment on each frame, so each process paid a page fault on every page of a fresh mapping (about 760 for a 1080p frame) per frame. Readers now keep segments mapped. Capture stamps each slot's frame time in a per-camera `{camera}_frame_times` segment, and `get()` returns None when the slot no longer holds the requested frame, reopening once by name so a mapping left over from a same-size camera recreate heals itself. Capture also reuses a slot when the frame queue is full, since no reader was told about it.
* verify the frame for embeddings object updates
Tracked object events only carried the object's own frame_time, which stays at its last detection when the object isn't detected in a frame, so embeddings couldn't check the slot it read and could crop face or plate data from a frame that had already been overwritten. Events now carry the time of the frame they name, and embeddings passes it to `get()`.
* log when a frame slot was overwritten before it was read
A lapped read and a missing segment ended up as the same debug line at every caller, so there was no way to tell a slow reader from a missing frame.
* bring the FrameManager interface in line with its implementation
The abstract get() still had a timeout_ms signature from an older implementation and frame_times() wasn't declared, though capture and detect are typed against the interface. get() also didn't say how long the array it returns stays valid.
* drop a camera's cached frame mappings when it is removed or recreated
A reader that kept its mappings open stayed on a removed camera's segments, which pinned their shared memory until restart, and after a same-size recreate the ledger reopen only refreshed the slot being read while the other cached slots still returned the old camera's pixels. Readers now drop every cached slot for a camera on its remove update, and get() does the same when a ledger mismatch turns out to be a replaced ledger rather than a lapped slot.
* match a camera's frame names exactly in close_camera
The prefix match on `{camera}_frame` also caught another camera whose name starts with it, so removing `cam` dropped the cached ring of a camera named `cam_frame`.
|
||
|
|
bc06b8c753 |
run opencv single threaded in camera tracking processes (#24640)
CI / AMD64 Build (push) Canceled after 0s
CI / AMD64 Smoke Test (push) Canceled after 0s
CI / ARM Build (push) Canceled after 0s
CI / Jetson Jetpack 6 (push) Canceled after 0s
CI / AMD64 Extra Build (push) Canceled after 0s
CI / ARM Extra Build (push) Canceled after 0s
CI / Synaptics Build (push) Canceled after 0s
CI / Assemble and push default build (push) Canceled after 0s
OpenCV's default thread pool is sized to every core, and its idle threads spin while it works on the small motion frames and detection regions in each camera tracking process. On a 16 thread machine replaying 720p clips at 5 fps, tracking CPU dropped from 27-50 ms to 5-8 ms per frame with identical output and no change in wall time. Frames from ffmpeg are now also read directly into shared memory with readinto(), which skips one copy per frame. |
||
|
|
135a95d8f2 |
Fix various warnings and deprecations (#23641)
* Migrate to fastapi lifespan for startup events The `on_event` style decorator is deprecated https://fastapi.tiangolo.com/advanced/events/ * Migrate to pydantic TypeAdapter https://pydantic.dev/docs/validation/2.12/get-started/migration/#introduction-of-typeadapter * Replace pytz with native tz-aware objects and zoneinfo library Supported from Python 3.9, see https://peps.python.org/pep-0615/. Also https://blog.ganssle.io/articles/2019/11/utcnow.html. Also provide tzdata as new dependency to supplement systems without local tzdata information. * Provide lookup for normalized timezone names This provides a helper to look up the correct timezone name independent of the casing of the given timezone name. * Test timezone naming normalization and error handling |
||
|
|
7e402d70df |
Fix environment_vars not reaching ffmpeg processes (#24635)
CI / AMD64 Build (push) Canceled after 0s
CI / ARM Build (push) Canceled after 0s
CI / Jetson Jetpack 6 (push) Canceled after 0s
CI / AMD64 Extra Build (push) Canceled after 0s
CI / ARM Extra Build (push) Canceled after 0s
CI / Synaptics Build (push) Canceled after 0s
CI / Assemble and push default build (push) Canceled after 0s
* start the forkserver after the config applies environment_vars The forkserver started as a side effect of creating the multiprocessing Manager at the top of main(), before the config loaded, so every worker process and the ffmpeg it launched inherited the environment from before environment_vars were applied. Variables like LIBVA_DRIVER_NAME set in config.yml never reached ffmpeg. The Manager now uses the fork context, so the forkserver does not start until the first worker process. * fix test |
||
|
|
186a730790 |
use CLIPImageProcessorPil to silence transformers torchvision warning (#24636)
CI / AMD64 Build (push) Canceled after 0s
CI / AMD64 Smoke Test (push) Canceled after 0s
CI / ARM Build (push) Canceled after 0s
CI / Jetson Jetpack 6 (push) Canceled after 0s
CI / AMD64 Extra Build (push) Canceled after 0s
CI / ARM Extra Build (push) Canceled after 0s
CI / Synaptics Build (push) Canceled after 0s
CI / Assemble and push default build (push) Canceled after 0s
|