Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 48 additions & 3 deletions .github/workflows/safety-ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -183,6 +183,49 @@ jobs:
if-no-files-found: warn
retention-days: 14

prune_acceptance:
name: Filesystem pruning — real container acceptance
runs-on: ubuntu-24.04
timeout-minutes: 25
steps:
- uses: actions/checkout@v4
with:
ref: ${{ env.CHECKPOINT_SHA }}
persist-credentials: false
- name: Refresh Ubuntu package indexes
timeout-minutes: 5
run: bash .github/scripts/ci-media-apt.sh update
- name: Install media test tools
timeout-minutes: 8
run: bash .github/scripts/ci-media-apt.sh install ffmpeg python3-venv openssl
- name: Build the exact checkout runtime image
timeout-minutes: 8
run: docker build -t simplenvr-safety-test .
- name: Install pinned browser acceptance tooling
timeout-minutes: 8
shell: bash
run: |
set -euo pipefail
python3 -m venv "$RUNNER_TEMP/simplenvr-browser-venv"
. "$RUNNER_TEMP/simplenvr-browser-venv/bin/activate"
python -m pip install 'playwright==1.56.0'
python -m playwright install --with-deps chrome
- name: Real container ceiling pruning on a loopback ext4 volume, with Chrome
timeout-minutes: 12
shell: bash
run: |
set -euo pipefail
. "$RUNNER_TEMP/simplenvr-browser-venv/bin/activate"
GITHUB_SHA="$CHECKPOINT_SHA" bash tests/acceptance/filesystem-prune-acceptance.sh simplenvr-safety-test "$RUNNER_TEMP/simplenvr-prune-evidence"
- name: Retain pruning acceptance evidence
if: always()
uses: actions/upload-artifact@v4
with:
name: filesystem-prune-acceptance-${{ env.CHECKPOINT_SHA }}-${{ github.run_attempt }}
path: ${{ runner.temp }}/simplenvr-prune-evidence
if-no-files-found: warn
retention-days: 14

correspondence_resources:
name: Ordered content — bounded synthetic resource measurements
runs-on: ubuntu-24.04
Expand Down Expand Up @@ -263,18 +306,20 @@ jobs:
verify:
name: Required checks — all must pass
if: always()
needs: [core, browser, correspondence_resources]
needs: [core, browser, prune_acceptance, correspondence_resources]
runs-on: ubuntu-24.04
timeout-minutes: 2
steps:
- name: Require core, both browser attempts and resource measurements
- name: Require core, both browser attempts, pruning acceptance and resource measurements
env:
CORE_RESULT: ${{ needs.core.result }}
BROWSER_RESULT: ${{ needs.browser.result }}
PRUNE_RESULT: ${{ needs.prune_acceptance.result }}
RESOURCE_RESULT: ${{ needs.correspondence_resources.result }}
run: |
set -euo pipefail
printf 'core=%s browser=%s resources=%s\n' "$CORE_RESULT" "$BROWSER_RESULT" "$RESOURCE_RESULT"
printf 'core=%s browser=%s prune=%s resources=%s\n' "$CORE_RESULT" "$BROWSER_RESULT" "$PRUNE_RESULT" "$RESOURCE_RESULT"
test "$CORE_RESULT" = success
test "$BROWSER_RESULT" = success
test "$PRUNE_RESULT" = success
test "$RESOURCE_RESULT" = success
25 changes: 21 additions & 4 deletions cmd/simplenvr/auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -228,6 +228,25 @@ var mutationPaths = map[string]bool{
"/api/events/clear-all":true, "/api/events/clear-camera":true,
}

// readWriteMutationPaths are mutation paths that also serve GET and HEAD reads. They
// stay in mutationPaths, so the shutdown gate still tracks their POST, and cross-origin
// protection and the session check still apply to every method.
var readWriteMutationPaths = map[string]bool{}

// methodPolicy says which methods a path accepts once the caller is authenticated.
// Paths outside mutationPaths accept only GET and HEAD, mutation paths only POST, and
// read-write mutation paths all three.
func methodPolicy(path, method string) (allow string, ok bool) {
switch {
case readWriteMutationPaths[path]:
return "GET, HEAD, POST", method == http.MethodGet || method == http.MethodHead || method == http.MethodPost
case mutationPaths[path]:
return "POST", method == http.MethodPost
default:
return "GET, HEAD", method == http.MethodGet || method == http.MethodHead
}
}

func (a *authManager) Handler(next http.Handler) http.Handler {
protected := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("X-Content-Type-Options", "nosniff")
Expand All @@ -247,10 +266,8 @@ func (a *authManager) Handler(next http.Handler) http.Handler {
}
if r.URL.Path == "/api/settings/session" { a.sessionSettingsHandler(w,r); return }
if r.URL.Path == "/api/settings/restart" { a.restartHandler(w,r); return }
if mutationPaths[r.URL.Path] {
if r.Method != http.MethodPost { w.Header().Set("Allow","POST"); http.Error(w,"Method not allowed",http.StatusMethodNotAllowed); return }
} else if r.Method != http.MethodGet && r.Method != http.MethodHead {
w.Header().Set("Allow","GET, HEAD"); http.Error(w,"Method not allowed",http.StatusMethodNotAllowed); return
if allow, ok := methodPolicy(r.URL.Path, r.Method); !ok {
w.Header().Set("Allow",allow); http.Error(w,"Method not allowed",http.StatusMethodNotAllowed); return
}
if strings.HasPrefix(r.URL.Path,"/recordings/") { servePrivateRecording(w,r); return }
clean := r.Clone(r.Context())
Expand Down
5 changes: 5 additions & 0 deletions cmd/simplenvr/cleanup.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,13 @@ func cleanupEventsForWithSave(ctx context.Context,n *NVR,persist func() error) {
if ctx.Err()!=nil {n.mu.Unlock();return}
retentionMap:=make(map[string]time.Duration)
invalidRetention:=make(map[string]bool)
ageOff:=make(map[string]bool)
for _,cam:=range n.cameras {
retention,err:=cameraRetentionDuration(cam.RetentionDays)
if err!=nil {invalidRetention[cam.Name]=true;log.Printf("Skipping invalid retention policy for camera %s",cam.ID);continue}
// Retention 0 means no age limit. Events lack camera IDs, so any camera with that
// name and no age limit keeps the name's events from expiring by age.
if cam.RetentionDays==0 {ageOff[cam.Name]=true;continue}
// Events lack camera IDs. Do not choose a shorter policy based on map
// iteration order when several registered cameras share the same name.
if retention>retentionMap[cam.Name] {retentionMap[cam.Name]=retention}
Expand All @@ -34,6 +38,7 @@ func cleanupEventsForWithSave(ctx context.Context,n *NVR,persist func() error) {
// An invalid policy is not equivalent to a missing camera. Preserve its
// events, including ambiguous names shared with another camera.
if invalidRetention[event.CameraName] {validEvents=append(validEvents,event);continue}
if ageOff[event.CameraName] {validEvents=append(validEvents,event);continue}
retention,exists:=retentionMap[event.CameraName]
if !exists || event.StartTime.Before(now.Add(-retention)) {deletedCount++;continue}
validEvents=append(validEvents,event)
Expand Down
149 changes: 149 additions & 0 deletions cmd/simplenvr/filesystem_ceiling.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,149 @@
package main

import (
"bytes"
"encoding/json"
"errors"
"io"
"log"
"math"
"net/http"
"strconv"
"sync"
"time"
)

// The ceiling is the highest filesystem-used percentage the owner accepts. The prune
// job (filesystem_prune.go) reads it; a successful change asks that job for a pass.
const (
defaultMaxFilesystemUsedPercent=80
minMaxFilesystemUsedPercent=10
maxMaxFilesystemUsedPercent=95
filesystemPruneMarginPercent=2
maxFilesystemCeilingRequestBytes=1024
)

var errFilesystemCeiling=errors.New("max_filesystem_used_percent must be a whole number from 10 to 95")

type filesystemCeilingSetting struct {
mu sync.RWMutex
percent int
}

func (s *filesystemCeilingSetting) get() int {s.mu.RLock();defer s.mu.RUnlock();return s.percent}
func (s *filesystemCeilingSetting) set(percent int) {s.mu.Lock();s.percent=percent;s.mu.Unlock()}

var recordingFilesystemCeiling=&filesystemCeilingSetting{percent:defaultMaxFilesystemUsedPercent}

// filesystemCeilingUpdateMu serializes updates so a failed save restores the value
// that was current before that update.
var filesystemCeilingUpdateMu sync.Mutex

func validateFilesystemCeiling(percent int) error {
if percent<minMaxFilesystemUsedPercent || percent>maxMaxFilesystemUsedPercent {return errFilesystemCeiling}
return nil
}

// filesystemPruneTrigger is derived from the ceiling and never stored.
func filesystemPruneTrigger(ceiling int) int {return ceiling-filesystemPruneMarginPercent}

// parseFilesystemCeilingValue accepts only a JSON integer literal in range. A
// string, fraction, exponent, null or boolean is refused.
func parseFilesystemCeilingValue(raw []byte) (int,error) {
percent,err:=strconv.Atoi(string(bytes.TrimSpace(raw)))
if err!=nil {return 0,errFilesystemCeiling}
if err=validateFilesystemCeiling(percent);err!=nil {return 0,err}
return percent,nil
}

// storedFilesystemCeiling reads the top-level key from configuration. A missing key
// is the default; a present but invalid value is an error.
func storedFilesystemCeiling(raw []byte) (int,error) {
var doc struct {Value json.RawMessage `json:"max_filesystem_used_percent"`}
if err:=json.Unmarshal(raw,&doc);err!=nil {return 0,err}
if doc.Value==nil {return defaultMaxFilesystemUsedPercent,nil}
return parseFilesystemCeilingValue(doc.Value)
}

// persistedDocument is what is written to cameras.json. persistedState stays a
// three-field struct so existing positional literals keep compiling; the embedded
// fields are written at the top level beside the ceiling.
type persistedDocument struct {
persistedState
MaxFilesystemUsedPercent int `json:"max_filesystem_used_percent"`
}

type filesystemCeilingResponse struct {
Ceiling int `json:"max_filesystem_used_percent"`
Trigger int `json:"filesystem_prune_trigger_percent"`
Used *float64 `json:"filesystem_used_percent"`
ObservedAt *time.Time `json:"filesystem_observed_at"`
}

type filesystemCeilingDeps struct {
setting *filesystemCeilingSetting
read func(string) (filesystemUsage,error)
save func() error
// onChange, when set, runs after a successful save so a changed ceiling can be
// acted on without waiting for the next scheduled pass.
onChange func()
}

func filesystemCeilingSnapshot(deps filesystemCeilingDeps) filesystemCeilingResponse {
ceiling:=deps.setting.get()
resp:=filesystemCeilingResponse{Ceiling:ceiling,Trigger:filesystemPruneTrigger(ceiling)}
usage,err:=deps.read(recordingsRoot)
if err==nil && !math.IsNaN(usage.UsedPercent) && !math.IsInf(usage.UsedPercent,0) {
used:=math.Round(usage.UsedPercent*10)/10
observed:=usage.ObservedAt
resp.Used=&used;resp.ObservedAt=&observed
}
return resp
}

func writeFilesystemCeiling(w http.ResponseWriter,deps filesystemCeilingDeps) {
w.Header().Set("Content-Type","application/json")
w.Header().Set("X-Content-Type-Options","nosniff")
json.NewEncoder(w).Encode(filesystemCeilingSnapshot(deps))
}

func updateFilesystemCeiling(w http.ResponseWriter,r *http.Request,deps filesystemCeilingDeps) {
r.Body=http.MaxBytesReader(w,r.Body,maxFilesystemCeilingRequestBytes)
dec:=json.NewDecoder(r.Body)
dec.DisallowUnknownFields()
var req struct {Value json.RawMessage `json:"max_filesystem_used_percent"`}
if err:=dec.Decode(&req);err!=nil || req.Value==nil {http.Error(w,errFilesystemCeiling.Error(),400);return}
var extra interface{}
if err:=dec.Decode(&extra);err!=io.EOF {http.Error(w,errFilesystemCeiling.Error(),400);return}
percent,err:=parseFilesystemCeilingValue(req.Value)
if err!=nil {http.Error(w,err.Error(),400);return}
filesystemCeilingUpdateMu.Lock()
defer filesystemCeilingUpdateMu.Unlock()
previous:=deps.setting.get()
deps.setting.set(percent)
if err=deps.save();err!=nil {
deps.setting.set(previous)
log.Printf("Saving filesystem usage ceiling failed: %v",err)
http.Error(w,"Failed to save filesystem usage ceiling",500)
return
}
if deps.onChange!=nil {deps.onChange()}
writeFilesystemCeiling(w,deps)
}

func serveFilesystemCeiling(w http.ResponseWriter,r *http.Request,deps filesystemCeilingDeps) {
w.Header().Set("Cache-Control","no-store")
switch r.Method {
case http.MethodGet:
writeFilesystemCeiling(w,deps)
case http.MethodPost:
updateFilesystemCeiling(w,r,deps)
default:
w.Header().Set("Allow","GET, POST")
http.Error(w,"Method not allowed",405)
}
}

func filesystemCeilingHandler(w http.ResponseWriter,r *http.Request) {
serveFilesystemCeiling(w,r,filesystemCeilingDeps{setting:recordingFilesystemCeiling,read:readFilesystemUsage,save:nvr.save,onChange:recordingFilesystemPruner.requestPass})
}
7 changes: 7 additions & 0 deletions cmd/simplenvr/filesystem_ceiling_frontend_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
package main

import "testing"

func TestFrontendFilesystemCeiling(t *testing.T) {
runFrontendRegression(t, "tests/frontend/filesystem-ceiling.cjs", "UTC")
}
11 changes: 11 additions & 0 deletions cmd/simplenvr/filesystem_ceiling_routes.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package main

const filesystemCeilingPath="/api/storage/ceiling"

// The ceiling route serves GET (read) and POST (change). Registering it as a tracked
// mutation makes the shutdown gate wait for an in-flight save, and registering it as
// read-write lets the auth layer accept its GET as well as its POST.
func init() {
mutationPaths[filesystemCeilingPath]=true
readWriteMutationPaths[filesystemCeilingPath]=true
}
77 changes: 77 additions & 0 deletions cmd/simplenvr/filesystem_ceiling_routes_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
package main

import (
"net/http"
"net/http/httptest"
"net/url"
"strings"
"testing"
)

func httpHandlerRecording(reached *[]string) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter,r *http.Request) {
*reached=append(*reached,r.Method+" "+r.URL.Path)
w.WriteHeader(204)
})
}

func TestMethodPolicy(t *testing.T) {
for _,c:=range []struct{path,method,allow string;ok bool}{
{"/api/storage/ceiling","GET","GET, HEAD, POST",true},
{"/api/storage/ceiling","HEAD","GET, HEAD, POST",true},
{"/api/storage/ceiling","POST","GET, HEAD, POST",true},
{"/api/storage/ceiling","PUT","GET, HEAD, POST",false},
{"/api/storage/ceiling","DELETE","GET, HEAD, POST",false},
{"/api/cameras/delete-all","POST","POST",true},
{"/api/cameras/delete-all","GET","POST",false},
{"/api/cameras/update-retention","GET","POST",false},
{"/api/cameras","GET","GET, HEAD",true},
{"/api/cameras","POST","GET, HEAD",false},
{"/api/storage/status","POST","GET, HEAD",false},
} {
allow,ok:=methodPolicy(c.path,c.method)
if allow!=c.allow || ok!=c.ok {t.Fatalf("%s %s = %q, %v; want %q, %v",c.method,c.path,allow,ok,c.allow,c.ok)}
}
}

func TestFilesystemCeilingPathIsATrackedMutation(t *testing.T) {
if !mutationPaths[filesystemCeilingPath] {t.Fatal("the shutdown gate would not wait for an in-flight ceiling save")}
if !readWriteMutationPaths[filesystemCeilingPath] {t.Fatal("the auth layer would reject the ceiling read")}
for path:=range readWriteMutationPaths {
if !mutationPaths[path] {t.Fatalf("%s is read-write but not a tracked mutation",path)}
}
}

// The CP3 handler tests called the handler directly and never saw the auth layer, which
// rejected every POST with 405. This sends the route through the real auth handler.
func TestFilesystemCeilingRouteThroughRealAuth(t *testing.T) {
a,_:=authFixture(t)
var reached []string
handler:=a.Handler(httpHandlerRecording(&reached))
form:=url.Values{"username":{"admin"},"password":{"correct horse battery staple"}}
login:=httptest.NewRequest("POST","https://nvr.test/auth/login",strings.NewReader(form.Encode()))
login.Header.Set("Content-Type","application/x-www-form-urlencoded")
loginResponse:=httptest.NewRecorder();handler.ServeHTTP(loginResponse,login)
if loginResponse.Code!=303 {t.Fatalf("login: %d",loginResponse.Code)}
cookies:=loginResponse.Result().Cookies()
if len(cookies)==0 {t.Fatal("no session cookie")}
request:=func(method,origin string,withCookie bool) *httptest.ResponseRecorder {
r:=httptest.NewRequest(method,"https://nvr.test"+filesystemCeilingPath,strings.NewReader(`{"max_filesystem_used_percent":90}`))
if withCookie {r.AddCookie(cookies[0])}
if origin!="" {r.Header.Set("Origin",origin)}
w:=httptest.NewRecorder();handler.ServeHTTP(w,r);return w
}
for _,method:=range []string{"GET","HEAD"} {
if w:=request(method,"",true);w.Code!=204 {t.Fatalf("%s with a session: %d",method,w.Code)}
}
if w:=request("POST","https://nvr.test",true);w.Code!=204 {t.Fatalf("POST with a session: %d",w.Code)}
for _,method:=range []string{"PUT","DELETE","PATCH"} {
w:=request(method,"https://nvr.test",true)
if w.Code!=405 || w.Header().Get("Allow")!="GET, HEAD, POST" {t.Fatalf("%s: %d allow %q",method,w.Code,w.Header().Get("Allow"))}
}
if w:=request("POST","https://evil.invalid",true);w.Code!=403 {t.Fatalf("cross-origin POST: %d",w.Code)}
if w:=request("GET","",false);w.Code!=401 {t.Fatalf("unauthenticated GET: %d",w.Code)}
if w:=request("POST","https://nvr.test",false);w.Code!=401 {t.Fatalf("unauthenticated POST: %d",w.Code)}
want:="GET /api/storage/ceiling,HEAD /api/storage/ceiling,POST /api/storage/ceiling"
if got:=strings.Join(reached,",");got!=want {t.Fatalf("requests that reached the handler = %q; want %q",got,want)}
}
Loading
Loading