Take control over your live stream video by running it yourself. Streaming + chat out of the box.
HTML activitypubbroadcastingchatdecentralizedfederationfediversegolanghacktoberfesthlslivelivestreamowncastrtmpself-hostedstreaming-videovideo
Support binary plugin HTTP responses (#5189)
Gabe Kangas4c5249df7eb0
diff --git a/services/plugins/engines/javascript/engine.wasm b/services/plugins/engines/javascript/engine.wasmindex df45e0494c..96af71c136 100644Binary files a/services/plugins/engines/javascript/engine.wasm and b/services/plugins/engines/javascript/engine.wasm differdiff --git a/services/plugins/engines/python/engine.wasm b/services/plugins/engines/python/engine.wasmindex e64adb5552..18cdc7bedb 100644Binary files a/services/plugins/engines/python/engine.wasm and b/services/plugins/engines/python/engine.wasm differdiff --git a/services/plugins/manager.go b/services/plugins/manager.goindex 1a93586cc7..3ce139b708 100644--- a/services/plugins/manager.go+++ b/services/plugins/manager.go@@ -124,10 +124,10 @@ const (MaxKVValueBytes = 256 << 10 // 256 KiB// MaxHTTPHandlerOutputBytes caps the JSON envelope a plugin returns- // from on_http_request (status + headers + body). Sized to leave- // headroom over MaxHTTPResponseBodyBytes (server.go); the inner body- // is then checked again post-unmarshal.- MaxHTTPHandlerOutputBytes = 12 << 20 // 12 MiB+ // from on_http_request (status + headers + body). A 10 MiB binary response+ // expands to about 13.3 MiB as base64; the decoded body is checked again+ // post-unmarshal.+ MaxHTTPHandlerOutputBytes = 16 << 20 // 16 MiB// NotifyTimeout caps a single on_event call. Notification handlers// can do real work (kv writes, owncast.* host calls), but theydiff --git a/services/plugins/server.go b/services/plugins/server.goindex cbae884485..988d2bbff4 100644--- a/services/plugins/server.go+++ b/services/plugins/server.go@@ -3,6 +3,7 @@ package pluginsimport ("bytes""context"+ "encoding/base64""encoding/json""errors""fmt"@@ -604,31 +605,33 @@ func (s *Server) buildRequestEnvelope(r *http.Request, requestPath string, authe// writePluginHTTPResponse parses a plugin's on_http_request output envelope// and writes it to the client, filtering disallowed headers.//-// injectStyles=true rewrites an HTML response (Content-Type starting with+// injectStyles=true rewrites an unencoded HTML response (Content-Type starting with// text/html) to include the host's admin stylesheet links — same behavior// as static HTML assets, so a plugin returning admin HTML from// on_http_request gets the iframe theme automatically.func writePluginHTTPResponse(w http.ResponseWriter, out []byte, injectStyles bool, sessionCookies []*http.Cookie) {- var resp struct {- Status int `json:"status"`- Headers map[string]string `json:"headers"`- Body string `json:"body"`+ var resp *struct {+ Status int `json:"status"`+ Headers map[string]string `json:"headers"`+ Body *string `json:"body"`+ BodyBase64 *string `json:"bodyBase64"`}- if err := json.Unmarshal(out, &resp); err != nil {+ if err := json.Unmarshal(out, &resp); err != nil || resp == nil || (resp.Body != nil && resp.BodyBase64 != nil) {http.Error(w, "plugin returned invalid response", http.StatusInternalServerError)return}if resp.Status == 0 {resp.Status = http.StatusOK}- if len(resp.Body) > MaxHTTPResponseBodyBytes {- http.Error(w, "plugin response too large", http.StatusInternalServerError)++ body, err := resolvePluginBody(resp.Body, resp.BodyBase64)+ if err != nil {+ http.Error(w, err.Error(), http.StatusInternalServerError)return}- body := resp.Body- if injectStyles && responseIsHTML(resp.Headers) {- body = string(injectAdminStyles([]byte(body)))+ if injectStyles && responseIsHTML(resp.Headers) && !responseHasContentEncoding(resp.Headers) {+ body = injectAdminStyles(body)}for k, v := range resp.Headers {@@ -648,7 +651,30 @@ func writePluginHTTPResponse(w http.ResponseWriter, out []byte, injectStyles boohttp.SetCookie(w, c)}w.WriteHeader(resp.Status)- _, _ = io.WriteString(w, body)+ _, _ = w.Write(body)+}++// resolvePluginBody decodes the response body from either the text or base64+// field, enforces MaxHTTPResponseBodyBytes, and returns raw bytes. Returns an+// error on malformed base64 or an oversized decoded body.+func resolvePluginBody(body, bodyBase64 *string) ([]byte, error) {+ if bodyBase64 != nil {+ b, err := base64.StdEncoding.DecodeString(*bodyBase64)+ if err != nil {+ return nil, errors.New("plugin returned invalid response")+ }+ if len(b) > MaxHTTPResponseBodyBytes {+ return nil, errors.New("plugin response too large")+ }+ return b, nil+ }+ if body != nil {+ if len(*body) > MaxHTTPResponseBodyBytes {+ return nil, errors.New("plugin response too large")+ }+ return []byte(*body), nil+ }+ return nil, nil}// stripSetCookie removes any existing Set-Cookie header values for the named@@ -684,6 +710,16 @@ func responseIsHTML(headers map[string]string) bool {return false}+// responseHasContentEncoding reports whether a body must be decoded before rewriting it.+func responseHasContentEncoding(headers map[string]string) bool {+ for k, v := range headers {+ if strings.EqualFold(k, "content-encoding") && strings.TrimSpace(v) != "" {+ return true+ }+ }+ return false+}+func flattenValues(v map[string][]string) map[string]string {out := make(map[string]string, len(v))for k, vs := range v {diff --git a/services/plugins/server_test.go b/services/plugins/server_test.goindex 0b44d3dbed..b55f10f8c0 100644--- a/services/plugins/server_test.go+++ b/services/plugins/server_test.go@@ -1,6 +1,10 @@package pluginsimport (+ "bytes"+ "compress/gzip"+ "encoding/base64"+ "encoding/json""io/fs""net/http""net/http/httptest"@@ -318,6 +322,127 @@ func TestWritePluginHTTPResponse_StripsCoreSessionCookie(t *testing.T) {}}+func TestWritePluginHTTPResponse_BinaryBody(t *testing.T) {+ out := []byte(`{"status":200,"headers":{"Content-Type":"application/octet-stream"},"bodyBase64":"/wCA"}`)+ rec := httptest.NewRecorder()++ writePluginHTTPResponse(rec, out, false, nil)++ want := []byte{0xff, 0x00, 0x80}+ if !bytes.Equal(rec.Body.Bytes(), want) {+ t.Fatalf("binary body: got %v want %v", rec.Body.Bytes(), want)+ }+}++func TestWritePluginHTTPResponse_RejectsInvalidBinaryBody(t *testing.T) {+ for _, out := range [][]byte{+ []byte(`null`),+ []byte(`{"bodyBase64":"not base64"}`),+ []byte(`{"body":"text","bodyBase64":"dGV4dA=="}`),+ } {+ rec := httptest.NewRecorder()+ writePluginHTTPResponse(rec, out, false, nil)+ if rec.Code != http.StatusInternalServerError {+ t.Errorf("status: got %d want %d", rec.Code, http.StatusInternalServerError)+ }+ }+}++func TestWritePluginHTTPResponse_RejectsOversizedDecodedBody(t *testing.T) {+ bodyBase64 := base64.StdEncoding.EncodeToString(make([]byte, MaxHTTPResponseBodyBytes+1))+ out := []byte(`{"bodyBase64":"` + bodyBase64 + `"}`)+ rec := httptest.NewRecorder()++ writePluginHTTPResponse(rec, out, false, nil)++ if rec.Code != http.StatusInternalServerError {+ t.Errorf("status: got %d want %d", rec.Code, http.StatusInternalServerError)+ }+}++func TestWritePluginHTTPResponse_LineWrappedBase64AtBodyLimit(t *testing.T) {+ body := bytes.Repeat([]byte{0xff}, MaxHTTPResponseBodyBytes)+ encoded := base64.StdEncoding.EncodeToString(body)+ var wrapped strings.Builder+ for len(encoded) > 76 {+ wrapped.WriteString(encoded[:76])+ wrapped.WriteString("\r\n")+ encoded = encoded[76:]+ }+ wrapped.WriteString(encoded)+ out, err := json.Marshal(map[string]string{"bodyBase64": wrapped.String()})+ if err != nil {+ t.Fatal(err)+ }+ rec := httptest.NewRecorder()++ writePluginHTTPResponse(rec, out, false, nil)++ if rec.Code != http.StatusOK {+ t.Fatalf("status: got %d want %d", rec.Code, http.StatusOK)+ }+ if !bytes.Equal(rec.Body.Bytes(), body) {+ t.Fatal("line-wrapped base64 body did not round-trip")+ }+}++func TestWritePluginHTTPResponse_AdminStyles(t *testing.T) {+ html := []byte("<html><head></head><body>admin</body></html>")+ var compressed bytes.Buffer+ writer := gzip.NewWriter(&compressed)+ if _, err := writer.Write(html); err != nil {+ t.Fatal(err)+ }+ if err := writer.Close(); err != nil {+ t.Fatal(err)+ }+ styledHTML := []byte("<html><head>" + string(adminStyleSnippet) + "</head><body>admin</body></html>")+ for _, tc := range []struct {+ name string+ bodyField string+ body []byte+ encodingHeader string+ encoding string+ want []byte+ }{+ {name: "text HTML", bodyField: "body", body: html, want: styledHTML},+ {name: "base64 HTML", bodyField: "bodyBase64", body: html, want: styledHTML},+ {name: "empty encoding", bodyField: "body", body: html, encodingHeader: "Content-Encoding", want: styledHTML},+ {name: "gzip", bodyField: "bodyBase64", body: compressed.Bytes(), encodingHeader: "Content-Encoding", encoding: "gzip", want: compressed.Bytes()},+ {name: "gzip mixed case header", bodyField: "bodyBase64", body: compressed.Bytes(), encodingHeader: "cOnTeNt-EnCoDiNg", encoding: "gzip", want: compressed.Bytes()},+ {name: "unsupported text encoding", bodyField: "body", body: html, encodingHeader: "Content-Encoding", encoding: "custom", want: html},+ {name: "unsupported base64 encoding", bodyField: "bodyBase64", body: html, encodingHeader: "Content-Encoding", encoding: "custom", want: html},+ } {+ t.Run(tc.name, func(t *testing.T) {+ headers := map[string]string{"Content-Type": "text/html; charset=utf-8"}+ if tc.encodingHeader != "" {+ headers[tc.encodingHeader] = tc.encoding+ }+ body := string(tc.body)+ if tc.bodyField == "bodyBase64" {+ body = base64.StdEncoding.EncodeToString(tc.body)+ }+ out, err := json.Marshal(map[string]any{"headers": headers, tc.bodyField: body})+ if err != nil {+ t.Fatal(err)+ }+ rec := httptest.NewRecorder()++ writePluginHTTPResponse(rec, out, true, nil)++ if rec.Code != http.StatusOK {+ t.Fatalf("status: got %d want %d", rec.Code, http.StatusOK)+ }+ if !bytes.Equal(rec.Body.Bytes(), tc.want) {+ t.Fatalf("body: got %q want %q", rec.Body.Bytes(), tc.want)+ }+ if got := rec.Header().Get("Content-Encoding"); got != tc.encoding {+ t.Errorf("Content-Encoding: got %q want %q", got, tc.encoding)+ }+ })+ }+}+// TestIsAdminPath_CaseInsensitive is the A5 regression: the admin gate must// fire regardless of the request path's case, so a case-insensitively-routing// plugin can't be tricked into serving admin content via "/Admin/...".