Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement mediaMTX RTMP auth #3240

Merged
merged 7 commits into from
Nov 13, 2024
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
7 changes: 5 additions & 2 deletions media/rtmp2segment.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,6 @@
}

func (ms *MediaSegmenter) RunSegmentation(in string, segmentHandler SegmentHandler) {

outFilePattern := filepath.Join(ms.Workdir, randomString()+"-%d.ts")
completionSignal := make(chan bool, 1)
wg := &sync.WaitGroup{}
Expand All @@ -36,15 +35,19 @@
defer wg.Done()
processSegments(segmentHandler, outFilePattern, completionSignal)
}()

ffmpeg.FfmpegSetLogLevel(ffmpeg.FFLogWarning)
ffmpeg.Transcode3(&ffmpeg.TranscodeOptionsIn{
_, err := ffmpeg.Transcode3(&ffmpeg.TranscodeOptionsIn{

Check warning on line 40 in media/rtmp2segment.go

View check run for this annotation

Codecov / codecov/patch

media/rtmp2segment.go#L40

Added line #L40 was not covered by tests
Fname: in,
}, []ffmpeg.TranscodeOptions{{
Oname: outFilePattern,
AudioEncoder: ffmpeg.ComponentOptions{Name: "copy"},
VideoEncoder: ffmpeg.ComponentOptions{Name: "copy"},
Muxer: ffmpeg.ComponentOptions{Name: "segment"},
}})
if err != nil {
slog.Error("Failed to run segmentation", "in", in, "err", err)
}

Check warning on line 50 in media/rtmp2segment.go

View check run for this annotation

Codecov / codecov/patch

media/rtmp2segment.go#L48-L50

Added lines #L48 - L50 were not covered by tests
completionSignal <- true
slog.Info("sent completion signal, now waiting")
wg.Wait()
Expand Down
55 changes: 54 additions & 1 deletion server/ai_mediaserver.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"time"

Expand Down Expand Up @@ -360,12 +361,40 @@
http.Error(w, "Missing stream name", http.StatusBadRequest)
return
}
sourceID := r.FormValue("source_id")
if sourceID == "" {
http.Error(w, "Missing source_id", http.StatusBadRequest)
return
}
sourceType := r.FormValue("source_type")
if sourceType == "" {
http.Error(w, "Missing source_type", http.StatusBadRequest)
return
}

Check warning on line 373 in server/ai_mediaserver.go

View check run for this annotation

Codecov / codecov/patch

server/ai_mediaserver.go#L364-L373

Added lines #L364 - L373 were not covered by tests

if streamName == "out-stream" {
// skip for now; we don't want to re-publish our own outputs
return
}
ctx := clog.AddVal(r.Context(), "stream", streamName)
ctx = clog.AddVal(ctx, "source_id", sourceID)
ctx = clog.AddVal(ctx, "source_type", sourceType)

err := authenticateAIStream(AuthWebhookURL, AIAuthRequest{
Stream: streamName,
})
if err != nil {
kickErr := kickInputConnection(sourceID, sourceType)
if kickErr != nil {
clog.Errorf(ctx, "failed to kick input connection: %s", kickErr.Error())
}
clog.Errorf(ctx, "Live AI auth failed: %s", err.Error())
http.Error(w, "Forbidden", http.StatusForbidden)
return

Check warning on line 393 in server/ai_mediaserver.go

View check run for this annotation

Codecov / codecov/patch

server/ai_mediaserver.go#L379-L393

Added lines #L379 - L393 were not covered by tests
}

requestID := string(core.RandomManifestID())
ctx := clog.AddVal(r.Context(), "request_id", requestID)
ctx = clog.AddVal(ctx, "request_id", requestID)

Check warning on line 397 in server/ai_mediaserver.go

View check run for this annotation

Codecov / codecov/patch

server/ai_mediaserver.go#L397

Added line #L397 was not covered by tests
clog.Infof(ctx, "Received live video AI request for %s", streamName)

// Kick off the RTMP pull and segmentation as soon as possible
Expand All @@ -389,3 +418,27 @@
processAIRequest(ctx, params, req)
})
}

const mediaMTXControlPort = "9997"

func kickInputConnection(sourceID string, sourceType string) error {
var apiPath string
switch sourceType {
case "webrtcSession":
apiPath = "webrtcsessions"
case "rtmpConn":
apiPath = "rtmpconns"
default:
return fmt.Errorf("invalid sourceType: %s", sourceType)

Check warning on line 432 in server/ai_mediaserver.go

View check run for this annotation

Codecov / codecov/patch

server/ai_mediaserver.go#L424-L432

Added lines #L424 - L432 were not covered by tests
}

resp, err := http.Post(fmt.Sprintf("http://localhost:%s/v3/%s/kick/%s", mediaMTXControlPort, apiPath, sourceID), "", nil)
if err != nil {
return err
}
if resp.StatusCode < http.StatusOK || resp.StatusCode >= http.StatusBadRequest {
body, _ := io.ReadAll(resp.Body)
return fmt.Errorf("kick connection failed with status code: %d body: %s", resp.StatusCode, body)
}
return nil

Check warning on line 443 in server/ai_mediaserver.go

View check run for this annotation

Codecov / codecov/patch

server/ai_mediaserver.go#L435-L443

Added lines #L435 - L443 were not covered by tests
}
40 changes: 38 additions & 2 deletions server/auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"io"
"net/http"
"net/url"
"time"
Expand Down Expand Up @@ -34,7 +34,7 @@
return nil, err
}

rbody, err := ioutil.ReadAll(resp.Body)
rbody, err := io.ReadAll(resp.Body)
resp.Body.Close()
if resp.StatusCode != 200 {
return nil, fmt.Errorf("status=%d error=%s", resp.StatusCode, string(rbody))
Expand Down Expand Up @@ -95,3 +95,39 @@

return string(profilesA) == string(profilesB)
}

type AIAuthRequest struct {
Stream string `json:"stream"`
// TODO not sure what params we need yet
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

later on, query params

}

func authenticateAIStream(authURL *url.URL, req AIAuthRequest) error {
if authURL == nil {
return nil
}

Check warning on line 107 in server/auth.go

View check run for this annotation

Codecov / codecov/patch

server/auth.go#L106-L107

Added lines #L106 - L107 were not covered by tests
started := time.Now()

jsonValue, err := json.Marshal(req)
if err != nil {
return err
}

Check warning on line 113 in server/auth.go

View check run for this annotation

Codecov / codecov/patch

server/auth.go#L112-L113

Added lines #L112 - L113 were not covered by tests

resp, err := http.Post(authURL.String(), "application/json", bytes.NewBuffer(jsonValue))
if err != nil {
return err
}

Check warning on line 118 in server/auth.go

View check run for this annotation

Codecov / codecov/patch

server/auth.go#L117-L118

Added lines #L117 - L118 were not covered by tests

rbody, err := io.ReadAll(resp.Body)
resp.Body.Close()
if resp.StatusCode != 200 {
return fmt.Errorf("status=%d error=%s", resp.StatusCode, string(rbody))
}

Check warning on line 124 in server/auth.go

View check run for this annotation

Codecov / codecov/patch

server/auth.go#L123-L124

Added lines #L123 - L124 were not covered by tests

took := time.Since(started)
glog.Infof("AI Stream authentication for authURL=%s stream=%s dur=%s", authURL, req.Stream, took)
if monitor.Enabled {
monitor.AuthWebhookFinished(took)
}

Check warning on line 130 in server/auth.go

View check run for this annotation

Codecov / codecov/patch

server/auth.go#L129-L130

Added lines #L129 - L130 were not covered by tests

return nil
}
10 changes: 10 additions & 0 deletions server/auth_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,16 @@ func TestAuthSucceeds(t *testing.T) {
require.Equal(t, "456", resp.StreamID)
}

func TestAILiveAuthSucceeds(t *testing.T) {
s, serverURL := stubAuthServer(t, http.StatusOK, `{}`)
defer s.Close()

err := authenticateAIStream(serverURL, AIAuthRequest{
Stream: "stream",
})
require.NoError(t, err)
}

func TestNoErrorWhenTranscodeAuthHeaderNotPassed(t *testing.T) {
r, err := http.NewRequest(http.MethodPost, "some.com/url", nil)
require.NoError(t, err)
Expand Down
Loading