feat: implement read-only mode enforcement in API handlers and add corresponding tests

This commit is contained in:
Sergey Krashevich
2026-02-01 05:46:20 +03:00
parent 51b79e614f
commit bc7f9c0f79
4 changed files with 76 additions and 0 deletions
+8
View File
@@ -111,6 +111,14 @@ func handleTCP(rawURL string) (core.Producer, error) {
}
func apiStream(w http.ResponseWriter, r *http.Request) {
if api.IsReadOnly() {
switch r.Method {
case "PUT", "PATCH", "POST", "DELETE":
api.ReadOnlyError(w)
return
}
}
dst := r.URL.Query().Get("dst")
stream := streams.Get(dst)
if stream == nil {
+30
View File
@@ -0,0 +1,30 @@
package http
import (
stdhttp "net/http"
"net/http/httptest"
"testing"
"github.com/AlexxIT/go2rtc/internal/api"
"github.com/stretchr/testify/require"
)
func TestApiStreamReadOnly(t *testing.T) {
prevReadOnly := api.ReadOnly
t.Cleanup(func() {
api.ReadOnly = prevReadOnly
})
api.ReadOnly = true
for _, method := range []string{"PUT", "PATCH", "POST", "DELETE"} {
t.Run(method, func(t *testing.T) {
req := httptest.NewRequest(method, "/api/stream?dst=test", nil)
w := httptest.NewRecorder()
apiStream(w, req)
require.Equal(t, stdhttp.StatusForbidden, w.Code)
})
}
}
+8
View File
@@ -21,6 +21,14 @@ const MimeSDP = "application/sdp"
var sessions = map[string]*webrtc.Conn{}
func syncHandler(w http.ResponseWriter, r *http.Request) {
if api.IsReadOnly() {
switch r.Method {
case "POST", "PATCH", "DELETE":
api.ReadOnlyError(w)
return
}
}
switch r.Method {
case "POST":
query := r.URL.Query()
+30
View File
@@ -0,0 +1,30 @@
package webrtc
import (
"net/http"
"net/http/httptest"
"testing"
"github.com/AlexxIT/go2rtc/internal/api"
"github.com/stretchr/testify/require"
)
func TestSyncHandlerReadOnly(t *testing.T) {
prevReadOnly := api.ReadOnly
t.Cleanup(func() {
api.ReadOnly = prevReadOnly
})
api.ReadOnly = true
for _, method := range []string{"POST", "PATCH", "DELETE"} {
t.Run(method, func(t *testing.T) {
req := httptest.NewRequest(method, "/api/webrtc?dst=test", nil)
w := httptest.NewRecorder()
syncHandler(w, req)
require.Equal(t, http.StatusForbidden, w.Code)
})
}
}