diff --git a/pkg/service/rtcservice.go b/pkg/service/rtcservice.go index e4280942..a7de1b78 100644 --- a/pkg/service/rtcservice.go +++ b/pkg/service/rtcservice.go @@ -72,11 +72,23 @@ func (s *RTCService) validate(r *http.Request) (string, routing.ParticipantInit, roomName := r.FormValue("room") reconnectParam := r.FormValue("reconnect") autoSubParam := r.FormValue("auto_subscribe") + publishParam := r.FormValue("publish") if onlyName != "" { roomName = onlyName } + // this is new connection for existing participant - with publish only permissions + if publishParam != "" { + // Make sure grant has CanPublish set, + if claims.Video.CanPublish != nil && *claims.Video.CanPublish == false { + return "", routing.ParticipantInit{}, http.StatusUnauthorized, rtc.ErrPermissionDenied + } + // Make sure by default subscribe is off + claims.Video.SetCanSubscribe(false) + claims.Identity += "#" + publishParam + } + if router, ok := s.router.(routing.Router); ok { if foundNode, err := router.GetNodeForRoom(r.Context(), roomName); err == nil { if selector.LimitsReached(s.limits, foundNode.Stats) { diff --git a/test/client/client.go b/test/client/client.go index b04f1555..82b1a690 100644 --- a/test/client/client.go +++ b/test/client/client.go @@ -48,11 +48,12 @@ type RTCClient struct { localParticipant *livekit.ParticipantInfo remoteParticipants map[string]*livekit.ParticipantInfo - reliableDC *webrtc.DataChannel - reliableDCSub *webrtc.DataChannel - lossyDC *webrtc.DataChannel - lossyDCSub *webrtc.DataChannel - publisherConnected utils.AtomicFlag + reliableDC *webrtc.DataChannel + reliableDCSub *webrtc.DataChannel + lossyDC *webrtc.DataChannel + lossyDCSub *webrtc.DataChannel + publisherConnected utils.AtomicFlag + publisherNegotiated utils.AtomicFlag // tracks waiting to be acked, cid => trackInfo pendingPublishedTracks map[string]*livekit.TrackInfo @@ -84,6 +85,7 @@ var ( type Options struct { AutoSubscribe bool + Publish string } func NewWebSocketConn(host, token string, opts *Options) (*websocket.Conn, error) { @@ -96,7 +98,8 @@ func NewWebSocketConn(host, token string, opts *Options) (*websocket.Conn, error connectUrl := u.String() if opts != nil { - connectUrl = fmt.Sprintf("%s&auto_subscribe=%t", connectUrl, opts.AutoSubscribe) + connectUrl = fmt.Sprintf("%s&auto_subscribe=%t&publish=%s", + connectUrl, opts.AutoSubscribe, opts.Publish) } conn, _, err := websocket.DefaultDialer.Dial(connectUrl, requestHeader) return conn, err @@ -224,8 +227,13 @@ func NewRTCClient(conn *websocket.Conn) (*RTCClient, error) { c.publisher.PeerConnection().OnICEConnectionStateChange(func(state webrtc.ICEConnectionState) { logger.Infow("publisher ICE state changed", "state", state.String(), "participant", c.localParticipant.Identity) + if state == webrtc.ICEConnectionStateConnected { c.publisherConnected.TrySet(true) + // check if publisher triggered negotiate (!subscriberPrimary) + if c.publisherNegotiated.Get() { + c.iceConnected.TrySet(true) + } } else { c.publisherConnected.TrySet(false) } @@ -265,6 +273,11 @@ func (c *RTCClient) Run() error { c.remoteParticipants[p.Sid] = p } c.lock.Unlock() + // if publish only, negotiate + if !msg.Join.SubscriberPrimary { + c.publisherNegotiated.TrySet(true) + c.publisher.Negotiate() + } logger.Infow("join accepted, awaiting offer", "participant", msg.Join.Participant.Identity) case *livekit.SignalResponse_Answer: diff --git a/test/integration_helpers.go b/test/integration_helpers.go index 9c2f9232..ca7ef96c 100644 --- a/test/integration_helpers.go +++ b/test/integration_helpers.go @@ -203,6 +203,22 @@ func createRTCClient(name string, port int, opts *testclient.Options) *testclien return c } +// creates a client and runs against server +func createRTCClientWithToken(token string, port int, opts *testclient.Options) *testclient.RTCClient { + ws, err := testclient.NewWebSocketConn(fmt.Sprintf("ws://localhost:%d", port), token, opts) + if err != nil { + panic(err) + } + + c, err := testclient.NewRTCClient(ws) + if err != nil { + panic(err) + } + + go c.Run() + + return c +} func redisClient() *redis.Client { return redis.NewClient(&redis.Options{ Addr: "localhost:6379", @@ -220,6 +236,17 @@ func joinToken(room, name string) string { return t } +func joinTokenWithGrant(name string, grant *auth.VideoGrant) string { + at := auth.NewAccessToken(testApiKey, testApiSecret). + AddGrant(grant). + SetIdentity(name) + t, err := at.ToJWT() + if err != nil { + panic(err) + } + return t +} + func createRoomToken() string { at := auth.NewAccessToken(testApiKey, testApiSecret). AddGrant(&auth.VideoGrant{RoomCreate: true}). diff --git a/test/singlenode_test.go b/test/singlenode_test.go index 3121b49c..b4b2bf45 100644 --- a/test/singlenode_test.go +++ b/test/singlenode_test.go @@ -6,6 +6,8 @@ import ( "testing" "time" + "github.com/livekit/protocol/auth" + "github.com/livekit/livekit-server/pkg/rtc" "github.com/pion/webrtc/v3" "github.com/stretchr/testify/require" @@ -33,6 +35,82 @@ func TestClientCouldConnect(t *testing.T) { }) } +func TestClientConnectDuplicate(t *testing.T) { + if testing.Short() { + t.SkipNow() + return + } + + _, finish := setupSingleNodeTest("TestClientCouldConnect", testRoom) + defer finish() + + grant := &auth.VideoGrant{RoomJoin: true, Room: testRoom} + grant.SetCanPublish(true) + grant.SetCanSubscribe(true) + token := joinTokenWithGrant("c1", grant) + + c1 := createRTCClientWithToken(token, defaultServerPort, nil) + + // publish 2 tracks + t1, err := c1.AddStaticTrack("audio/opus", "audio", "webcam") + require.NoError(t, err) + defer t1.Stop() + t2, err := c1.AddStaticTrack("video/vp8", "video", "webcam") + require.NoError(t, err) + defer t2.Stop() + + c2 := createRTCClient("c2", defaultServerPort, nil) + waitUntilConnected(t, c1, c2) + + opts := &testclient.Options{ + Publish: "duplicate_connection", + } + success := testutils.WithTimeout(t, "c2 should receive two tracks", func() bool { + if len(c2.SubscribedTracks()) == 0 { + return false + } + // should have received three tracks + if len(c2.SubscribedTracks()[c1.ID()]) != 2 { + return false + } + + //participant ID can be appended with '#..' . but should contain orig id as prefix + tr1 := c2.SubscribedTracks()[c1.ID()][0] + participantId1, _ := rtc.UnpackStreamID(tr1.StreamID()) + require.Equal(t, c1.ID(), participantId1) + tr2 := c2.SubscribedTracks()[c1.ID()][1] + participantId2, _ := rtc.UnpackStreamID(tr2.StreamID()) + require.Equal(t, c1.ID(), participantId2) + return true + }) + if !success { + t.FailNow() + } + + c1Dup := createRTCClientWithToken(token, defaultServerPort, opts) + + waitUntilConnected(t, c1Dup) + + t3, err := c1Dup.AddStaticTrack("video/vp8", "video", "webcam") + require.NoError(t, err) + defer t3.Stop() + + success = testutils.WithTimeout(t, "c2 should receive third tracks", func() bool { + if len(c2.SubscribedTracks()[c1Dup.ID()]) != 1 { + return false + } + + tr3 := c2.SubscribedTracks()[c1Dup.ID()][0] + participantId3, _ := rtc.UnpackStreamID(tr3.StreamID()) + require.Contains(t, c1Dup.ID(), participantId3) + + return true + }) + if !success { + t.FailNow() + } +} + func TestSinglePublisher(t *testing.T) { if testing.Short() { t.SkipNow()