Skip to content

Take control over your live stream video by running it yourself. Streaming + chat out of the box.

fix(plugins): confine grantSession to a plugin's own registered users

Gabe Kangas34056dc4ff2d
diff --git a/db/query.sql b/db/query.sql
index 21b3221b6f..1240327332 100644
--- a/db/query.sql
+++ b/db/query.sql
@@ -129,6 +129,9 @@ INSERT INTO auth(user_id, token, type) values(?, ?, ?);
-- name: GetUserByAuth :one
SELECT users.id, display_name, display_color, users.created_at, disabled_at, previous_names, namechanged_at, authenticated_at, scopes FROM auth, users WHERE token = ? AND auth.type = ? AND users.id = auth.user_id;
+-- name: CountUserAuthByTypeAndTokenPrefix :one
+SELECT count(*) FROM auth WHERE user_id = ? AND type = ? AND token LIKE ?;
+
-- name: AddAccessTokenForUser :exec
INSERT INTO user_access_tokens(token, user_id) values(?, ?);
diff --git a/db/query.sql.go b/db/query.sql.go
index 7c736736b2..4322a52fcd 100644
--- a/db/query.sql.go
+++ b/db/query.sql.go
@@ -219,6 +219,23 @@ func (q *Queries) ChangeDisplayName(ctx context.Context, arg ChangeDisplayNamePa
return err
}
+const countUserAuthByTypeAndTokenPrefix = `-- name: CountUserAuthByTypeAndTokenPrefix :one
+SELECT count(*) FROM auth WHERE user_id = ? AND type = ? AND token LIKE ?
+`
+
+type CountUserAuthByTypeAndTokenPrefixParams struct {
+ UserID string
+ Type string
+ Token string
+}
+
+func (q *Queries) CountUserAuthByTypeAndTokenPrefix(ctx context.Context, arg CountUserAuthByTypeAndTokenPrefixParams) (int64, error) {
+ row := q.db.QueryRowContext(ctx, countUserAuthByTypeAndTokenPrefix, arg.UserID, arg.Type, arg.Token)
+ var count int64
+ err := row.Scan(&count)
+ return count, err
+}
+
const doesInboundActivityExist = `-- name: DoesInboundActivityExist :one
SELECT count(*) FROM ap_accepted_activities WHERE iri = ? AND actor = ? AND TYPE = ?
`
diff --git a/persistence/userrepository/userrepository.go b/persistence/userrepository/userrepository.go
index 067b3187bd..af66be83b9 100644
--- a/persistence/userrepository/userrepository.go
+++ b/persistence/userrepository/userrepository.go
@@ -42,6 +42,7 @@ type UserRepository interface {
HasValidScopes(scopes []string) bool
GetUserByAuth(authToken string, authType models.AuthType) *models.User
AddAuth(userID, authToken string, authType models.AuthType) error
+ UserRegisteredByPlugin(pluginName, userID string) bool
AddAccessTokenForUser(accessToken, userID string) error
SetUserScopes(userID string, scopes []string) error
SetExternalAPIUserAccessTokenAsUsed(token string) error
@@ -292,6 +293,29 @@ func (r *SqlUserRepository) AddAuth(userID, authToken string, authType models.Au
})
}
+// UserRegisteredByPlugin reports whether userID belongs to a user the named
+// plugin registered via owncast.users.register — i.e. the user has a
+// plugin.auth identity namespaced to that plugin's slug (RegisterUser stores
+// it as "<slug>:<authId>"). The viewer-auth gate uses this to confine
+// owncast.auth.grantSession to a plugin's own users, so a gate plugin can't
+// mint a session impersonating an arbitrary existing user (e.g. a moderator).
+//
+// Matching on the "<slug>:" prefix is safe: plugin slugs are validated to
+// lowercase letters/digits/hyphens, so they can't carry SQL LIKE wildcards.
+// Fails closed (returns false) on any query error.
+func (r *SqlUserRepository) UserRegisteredByPlugin(pluginName, userID string) bool {
+ count, err := r.datastore.GetQueries().CountUserAuthByTypeAndTokenPrefix(context.Background(), db.CountUserAuthByTypeAndTokenPrefixParams{
+ UserID: userID,
+ Type: string(models.PluginAuth),
+ Token: pluginName + ":%",
+ })
+ if err != nil {
+ log.Errorln("checking plugin user ownership:", err)
+ return false
+ }
+ return count > 0
+}
+
// GetUserByAuth will return an existing user given auth details if a user
// has previously authenticated with that method.
func (r *SqlUserRepository) GetUserByAuth(authToken string, authType models.AuthType) *models.User {
@@ -583,6 +607,12 @@ func (r *SqlUserRepository) DeleteExternalAPIUser(token string) error {
}
// GetExternalAPIUserForAccessTokenAndScope will determine if a specific token has access to perform a scoped action.
+//
+// Only true third-party API integrations (users.type = 'API', created via the
+// admin Access Tokens UI) may authenticate to the scoped external API. Without
+// the type filter, any user that happened to carry an admin scope on a regular
+// access token — e.g. a user created and granted a session by a viewer-auth
+// plugin — would also pass, which is not the intent of this Bearer-token API.
func (r *SqlUserRepository) GetExternalAPIUserForAccessTokenAndScope(token string, scope string) (*models.ExternalAPIUser, error) {
// This will split the scopes from comma separated to individual rows
// so we can efficiently find if a token supports a single scope.
@@ -621,6 +651,8 @@ FROM
scopes || ','
FROM
users AS u
+ WHERE
+ u.type = 'API'
UNION ALL
SELECT
id,
diff --git a/persistence/userrepository/userrepository_test.go b/persistence/userrepository/userrepository_test.go
new file mode 100644
index 0000000000..ea5e7d15f2
--- /dev/null
+++ b/persistence/userrepository/userrepository_test.go
@@ -0,0 +1,89 @@
+package userrepository
+
+import (
+ "os"
+ "testing"
+
+ "github.com/owncast/owncast/models"
+ "github.com/owncast/owncast/services/datastore"
+)
+
+func newTestRepo(t *testing.T) *SqlUserRepository {
+ t.Helper()
+ ds, err := datastore.SetupPersistence(":memory:", os.TempDir())
+ if err != nil {
+ t.Fatalf("setup persistence: %v", err)
+ }
+ return New(ds).(*SqlUserRepository)
+}
+
+// The scoped external API is for true third-party integrations
+// (users.type = 'API'). A regular user that happens to carry an admin scope on
+// an access token — e.g. one a viewer-auth plugin created and granted a session
+// for — must NOT be able to authenticate to it.
+func TestGetExternalAPIUserForAccessTokenAndScope_OnlyAPIUsers(t *testing.T) {
+ r := newTestRepo(t)
+
+ // A real API integration with the admin scope: authorized.
+ const apiToken = "api-token-aaa"
+ if err := r.InsertExternalAPIUser(apiToken, "integration", 0, []string{models.ScopeHasAdminAccess}); err != nil {
+ t.Fatalf("insert API user: %v", err)
+ }
+ if u, err := r.GetExternalAPIUserForAccessTokenAndScope(apiToken, models.ScopeHasAdminAccess); err != nil || u == nil {
+ t.Fatalf("API user with the scope should be authorized: user=%v err=%v", u, err)
+ }
+
+ // A STANDARD user carrying the same scope on a plain access token: rejected.
+ user, _, err := r.CreateAnonymousUser("viewer")
+ if err != nil {
+ t.Fatalf("create user: %v", err)
+ }
+ if err := r.SetUserScopes(user.ID, []string{models.ScopeHasAdminAccess}); err != nil {
+ t.Fatalf("set scopes: %v", err)
+ }
+ const stdToken = "std-token-bbb"
+ if err := r.AddAccessTokenForUser(stdToken, user.ID); err != nil {
+ t.Fatalf("add token: %v", err)
+ }
+ // No match returns a nil user (and sql.ErrNoRows); the security property is
+ // that no authorized user comes back for a non-API token.
+ if u, _ := r.GetExternalAPIUserForAccessTokenAndScope(stdToken, models.ScopeHasAdminAccess); u != nil {
+ t.Fatalf("non-API user must NOT be authorized to the scoped external API: got %v", u)
+ }
+}
+
+// grantSession is confined to users a plugin registered. UserRegisteredByPlugin
+// is the durable ownership check behind that, matching the "<slug>:<authId>"
+// plugin.auth identity RegisterUser stores.
+func TestUserRegisteredByPlugin(t *testing.T) {
+ r := newTestRepo(t)
+
+ user, _, err := r.CreateAnonymousUser("gated viewer")
+ if err != nil {
+ t.Fatalf("create user: %v", err)
+ }
+ // Mirror what RegisterUser stores: "<slug>:<authId>" under PluginAuth.
+ if err := r.AddAuth(user.ID, "basic-auth:shared", models.PluginAuth); err != nil {
+ t.Fatalf("add auth: %v", err)
+ }
+
+ cases := []struct {
+ name string
+ plugin string
+ userID string
+ want bool
+ }{
+ {"owning plugin", "basic-auth", user.ID, true},
+ {"different plugin", "github-auth", user.ID, false},
+ {"unknown user", "basic-auth", "no-such-user", false},
+ // Slug prefix must respect the ":" separator, not match a partial slug.
+ {"partial slug is not a match", "basic", user.ID, false},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ if got := r.UserRegisteredByPlugin(tc.plugin, tc.userID); got != tc.want {
+ t.Fatalf("UserRegisteredByPlugin(%q, %q) = %v, want %v", tc.plugin, tc.userID, got, tc.want)
+ }
+ })
+ }
+}
diff --git a/pluginhost/pluginhost.go b/pluginhost/pluginhost.go
index 2881cca55b..48895cccc7 100644
--- a/pluginhost/pluginhost.go
+++ b/pluginhost/pluginhost.go
@@ -1600,6 +1600,13 @@ func wireAuthHostFns(env *plugins.HostEnv, deps Deps) {
}
env.GrantSession = func(pluginName, userID string, ttlSeconds int64) (string, error) {
+ // Only mint a session for a user THIS plugin registered. RegisterUser
+ // namespaces every plugin identity by slug; mirror that here so a gate
+ // plugin can't grant a session impersonating an arbitrary existing user
+ // (e.g. a moderator) just by naming their id.
+ if !users.UserRegisteredByPlugin(pluginName, userID) {
+ return "", fmt.Errorf("user %q was not registered by plugin %q", userID, pluginName)
+ }
// Mint an access token for this session and carry it (signed) in the
// cookie, so the chat /ws path can resolve the viewer via the existing
// GetUserByToken lookup. Login is infrequent, so a token per session is