Open platform to collect and prioritize feedback
Fix cross-tenant auth takeover via tenant-unbound user lookup
Matt Roberts0c2d11b8670c
diff --git a/app/actions/user.go b/app/actions/user.goindex 65ad0a0bc..6bac9f0b4 100644--- a/app/actions/user.go+++ b/app/actions/user.go@@ -78,7 +78,7 @@ func (action *ChangeUserRole) Validate(ctx context.Context, user *entity.User) *result.AddFieldFailure("userID", "It is not allowed to change your own Role.")}- userByID := &query.GetUserByID{UserID: action.UserID}+ userByID := &query.GetUserByID{UserID: action.UserID, TenantID: user.Tenant.ID}err := bus.Dispatch(ctx, userByID)if err != nil {if errors.Cause(err) == app.ErrNotFound {diff --git a/app/handlers/images.go b/app/handlers/images.goindex 6cdbd2cc0..77e910e33 100644--- a/app/handlers/images.go+++ b/app/handlers/images.go@@ -71,7 +71,7 @@ func Gravatar() web.HandlerFunc {size = between(size, 50, 200)if err == nil && id > 0 {- userByID := &query.GetUserByID{UserID: id}+ userByID := &query.GetUserByID{UserID: id, TenantID: c.Tenant().ID}err := bus.Dispatch(c, userByID)if err == nil && userByID.Result.Tenant.ID == c.Tenant().ID {if userByID.Result.Email != "" {diff --git a/app/middlewares/user.go b/app/middlewares/user.goindex 320856871..1c2db3375 100644--- a/app/middlewares/user.go+++ b/app/middlewares/user.go@@ -25,18 +25,21 @@ func User() web.MiddlewareFunc {return func(next web.HandlerFunc) web.HandlerFunc {return func(c *web.Context) error {var (- token string- user *entity.User+ token string+ user *entity.User+ fromSignUpCookie bool)cookie, err := c.Request.Cookie(web.CookieAuthName)if err == nil {token = cookie.Value} else {+ // The signup-transfer cookie is domain-wide, so it reaches every tenant+ // subdomain. We do NOT promote it to a durable host-only auth cookie here:+ // that only happens later, and only once we have confirmed the token's user+ // actually belongs to the tenant selected by the current host.token = webutil.GetSignUpAuthCookie(c)- if token != "" {- webutil.AddAuthTokenCookie(c, token)- }+ fromSignUpCookie = token != ""}if token != "" {@@ -46,7 +49,14 @@ func User() web.MiddlewareFunc {return next(c)}- userByClaimsID := &query.GetUserByID{UserID: claims.UserID}+ // Scope the lookup to the tenant selected by the request host. A globally+ // valid user ID that belongs to a different tenant must resolve to "not+ // found" so a token cannot be replayed across tenant boundaries.+ tenantID := 0+ if c.Tenant() != nil {+ tenantID = c.Tenant().ID+ }+ userByClaimsID := &query.GetUserByID{UserID: claims.UserID, TenantID: tenantID}err = bus.Dispatch(c, userByClaimsID)user = userByClaimsID.Resultif err != nil {@@ -103,7 +113,7 @@ func User() web.MiddlewareFunc {if err != nil {return c.HandleValidation(validate.Failed(fmt.Sprintf("User not found for given impersonate UserID '%s'", impersonateUserIDStr)))}- userByImpersonateID := &query.GetUserByID{UserID: impersonateUserID}+ userByImpersonateID := &query.GetUserByID{UserID: impersonateUserID, TenantID: user.Tenant.ID}err = bus.Dispatch(c, userByImpersonateID)user = userByImpersonateID.Resultif err != nil {@@ -123,6 +133,14 @@ func User() web.MiddlewareFunc {return c.Unauthorized()}+ // Only now that the user is confirmed to belong to the current tenant do we+ // promote a signup-transfer cookie into a durable host-only auth cookie.+ // This is deliberately skipped on any other tenant, so the domain-wide+ // signup token cannot become a normal session on an unrelated subdomain.+ if fromSignUpCookie {+ webutil.AddAuthTokenCookie(c, token)+ }+c.SetUser(user)}diff --git a/app/middlewares/user_test.go b/app/middlewares/user_test.goindex b1e09495a..af6805f87 100644--- a/app/middlewares/user_test.go+++ b/app/middlewares/user_test.go@@ -232,6 +232,98 @@ func TestUser_WithSignUpCookie(t *testing.T) {Expect(cookie.Expires).TemporarilySimilar(time.Now().Add(365*24*time.Hour), 5*time.Second)}+// TestUser_SignUpCookie_CrossTenant_Denied is the core regression test for the cross-tenant+// signup-cookie takeover. Jon Snow is an Administrator of the demo tenant. His domain-wide+// __signup_auth cookie is presented while the avengers tenant is in context. Because the+// user lookup is now tenant-scoped, no user is installed, the signup token is NOT promoted+// into a host-only auth cookie, and an authenticated route returns 401.+func TestUser_SignUpCookie_CrossTenant_Denied(t *testing.T) {+ RegisterT(t)++ server := mock.NewServer()+ token, _ := jwt.Encode(jwt.FiderClaims{+ UserID: mock.JonSnow.ID, // belongs to the demo tenant+ UserName: mock.JonSnow.Name,+ })++ // Tenant-aware handler: only resolves the user when the requested tenant matches.+ bus.AddHandler(func(ctx context.Context, q *query.GetUserByID) error {+ if q.UserID == mock.JonSnow.ID && q.TenantID == mock.JonSnow.Tenant.ID {+ q.Result = mock.JonSnow+ return nil+ }+ return app.ErrNotFound+ })++ server.Use(middlewares.User())+ server.Use(middlewares.IsAuthenticated())+ status, response := server.+ OnTenant(mock.AvengersTenant). // victim tenant, different from Jon Snow's+ AddHeader("Accept", "application/json").+ AddCookie(web.CookieSignUpAuthName, token).+ Execute(func(c *web.Context) error {+ return c.String(http.StatusOK, c.User().Name)+ })++ // An authenticated (administrator) route must reject the request.+ Expect(status).Equals(http.StatusUnauthorized)++ // The domain-wide signup token must never become a durable host-only auth cookie on+ // the victim tenant. Any auth cookie emitted here must be a deletion (empty value).+ for _, raw := range response.Header()["Set-Cookie"] {+ c := web.ParseCookie(raw)+ if c.Name == web.CookieAuthName {+ Expect(c.Value).Equals("")+ }+ }+}++// TestUser_SignUpCookie_SameTenant_Promotes verifies the positive path: the signup cookie+// succeeds on the tenant the user actually belongs to and is promoted to a host-only auth+// cookie for that host.+func TestUser_SignUpCookie_SameTenant_Promotes(t *testing.T) {+ RegisterT(t)++ server := mock.NewServer()+ token, _ := jwt.Encode(jwt.FiderClaims{+ UserID: mock.JonSnow.ID,+ UserName: mock.JonSnow.Name,+ })++ bus.AddHandler(func(ctx context.Context, q *query.GetUserByID) error {+ if q.UserID == mock.JonSnow.ID && q.TenantID == mock.JonSnow.Tenant.ID {+ q.Result = mock.JonSnow+ return nil+ }+ return app.ErrNotFound+ })++ server.Use(middlewares.User())+ status, response := server.+ OnTenant(mock.DemoTenant). // Jon Snow's own tenant+ AddCookie(web.CookieSignUpAuthName, token).+ Execute(func(c *web.Context) error {+ return c.String(http.StatusOK, c.User().Name)+ })++ Expect(status).Equals(http.StatusOK)+ Expect(response.Body.String()).Equals("Jon Snow")++ cookies := response.Header()["Set-Cookie"]+ Expect(cookies).HasLen(2)++ // The signup cookie is consumed (deleted)...+ signup := web.ParseCookie(cookies[0])+ Expect(signup.Name).Equals(web.CookieSignUpAuthName)+ Expect(signup.Value).Equals("")++ // ...and promoted to a host-only auth cookie (no Domain) carrying the same token.+ auth := web.ParseCookie(cookies[1])+ Expect(auth.Name).Equals(web.CookieAuthName)+ Expect(auth.Value).Equals(token)+ Expect(auth.Domain).Equals("")+}+func TestUser_ValidAPIKey(t *testing.T) {RegisterT(t)diff --git a/app/models/query/user.go b/app/models/query/user.goindex ddcd3dce2..118a3d854 100644--- a/app/models/query/user.go+++ b/app/models/query/user.go@@ -26,7 +26,8 @@ type GetCurrentUserSettings struct {}type GetUserByID struct {- UserID int+ UserID int+ TenantID intResult *entity.User}diff --git a/app/services/sqlstore/dbEntities/user.go b/app/services/sqlstore/dbEntities/user.goindex 15d056cf6..27feee37c 100644--- a/app/services/sqlstore/dbEntities/user.go+++ b/app/services/sqlstore/dbEntities/user.go@@ -41,11 +41,25 @@ func (u *User) ToModel(ctx context.Context) *entity.User {return nil}- tenant, ok := ctx.Value(app.TenantCtxKey).(*entity.Tenant)- if !ok || tenant == nil {- if u.Tenant != nil {- tenant = u.Tenant.ToModel()+ // Bind the user to the tenant persisted on its own database row. The persisted+ // association is loaded into u.Tenant from the tenant_id column and is the user's+ // authorization identity — it MUST take precedence over the request-context tenant.+ // Deriving the tenant from context would let an authentication token minted on one+ // tenant be replayed on another subdomain and pass the downstream tenant-equality+ // check tautologically (cross-tenant privilege escalation).+ var tenant *entity.Tenant+ if u.Tenant != nil {+ tenant = u.Tenant.ToModel()+ // When the request is scoped to this same tenant, prefer the fully-populated+ // request tenant so presentation data (name, plan, settings) is preserved. The+ // authorization identity is unchanged because the IDs are equal.+ if ctxTenant, ok := ctx.Value(app.TenantCtxKey).(*entity.Tenant); ok && ctxTenant != nil && ctxTenant.ID == tenant.ID {+ tenant = ctxTenant}+ } else if ctxTenant, ok := ctx.Value(app.TenantCtxKey).(*entity.Tenant); ok {+ // No persisted association was loaded (e.g. a user struct not read through the+ // standard queries); fall back to the request tenant.+ tenant = ctxTenant}avatarType := enum.AvatarType(u.AvatarType.Int64)diff --git a/app/services/sqlstore/dbEntities/user_test.go b/app/services/sqlstore/dbEntities/user_test.goindex 5f6a8ea7b..9ff08d8c3 100644--- a/app/services/sqlstore/dbEntities/user_test.go+++ b/app/services/sqlstore/dbEntities/user_test.go@@ -7,6 +7,7 @@ import ("testing""github.com/getfider/fider/app"+ "github.com/getfider/fider/app/models/entity""github.com/getfider/fider/app/models/enum""github.com/getfider/fider/app/pkg/web""github.com/getfider/fider/app/services/sqlstore/dbEntities"@@ -81,6 +82,62 @@ func TestUserToModel(t *testing.T) {}}+// TestUserToModel_PreservesPersistedTenant verifies that a user loaded from the database+// keeps the tenant persisted on its own row even when a *different* tenant is present in+// the request context. Adopting the context tenant here would make the downstream+// tenant-equality authorization check tautological (cross-tenant token replay).+func TestUserToModel_PreservesPersistedTenant(t *testing.T) {+ u, _ := url.Parse("http://victim.fider.io")+ req := web.Request{URL: u}+ ctx := context.WithValue(context.Background(), app.RequestCtxKey, req)+ // Request is scoped to the victim tenant (id 2)...+ ctx = context.WithValue(ctx, app.TenantCtxKey, &entity.Tenant{ID: 2, Name: "Victim"})++ // ...but the user row is persisted under the attacker tenant (id 1).+ dbUser := &dbEntities.User{+ ID: sql.NullInt64{Int64: 1, Valid: true},+ Name: sql.NullString{String: "Attacker", Valid: true},+ Role: sql.NullInt64{Int64: int64(enum.RoleAdministrator), Valid: true},+ Status: sql.NullInt64{Int64: int64(enum.UserActive), Valid: true},+ Tenant: &dbEntities.Tenant{ID: 1},+ }++ entityUser := dbUser.ToModel(ctx)++ if entityUser.Tenant == nil {+ t.Fatal("expected Tenant to be populated from the persisted association")+ }+ if entityUser.Tenant.ID != 1 {+ t.Errorf("expected persisted Tenant ID 1, got %d", entityUser.Tenant.ID)+ }+}++// TestUserToModel_SameTenantUsesRequestTenant verifies that when the request tenant matches+// the persisted tenant, the fully-populated request tenant is used for presentation data.+func TestUserToModel_SameTenantUsesRequestTenant(t *testing.T) {+ u, _ := url.Parse("http://demo.fider.io")+ req := web.Request{URL: u}+ ctx := context.WithValue(context.Background(), app.RequestCtxKey, req)+ ctx = context.WithValue(ctx, app.TenantCtxKey, &entity.Tenant{ID: 1, Name: "Demo"})++ dbUser := &dbEntities.User{+ ID: sql.NullInt64{Int64: 1, Valid: true},+ Name: sql.NullString{String: "Jon Snow", Valid: true},+ Role: sql.NullInt64{Int64: int64(enum.RoleAdministrator), Valid: true},+ Status: sql.NullInt64{Int64: int64(enum.UserActive), Valid: true},+ Tenant: &dbEntities.Tenant{ID: 1},+ }++ entityUser := dbUser.ToModel(ctx)++ if entityUser.Tenant == nil || entityUser.Tenant.ID != 1 {+ t.Fatalf("expected Tenant ID 1, got %v", entityUser.Tenant)+ }+ if entityUser.Tenant.Name != "Demo" {+ t.Errorf("expected fully-populated request tenant (Name 'Demo'), got '%s'", entityUser.Tenant.Name)+ }+}+func TestUserToModel_Nil(t *testing.T) {var dbUser *dbEntities.UserentityUser := dbUser.ToModel(context.Background())diff --git a/app/services/sqlstore/postgres/user.go b/app/services/sqlstore/postgres/user.goindex 8d430f022..b1057be9b 100644--- a/app/services/sqlstore/postgres/user.go+++ b/app/services/sqlstore/postgres/user.go@@ -290,7 +290,7 @@ func updateCurrentUser(ctx context.Context, c *cmd.UpdateCurrentUser) error {func getUserByID(ctx context.Context, q *query.GetUserByID) error {return using(ctx, func(trx *dbx.Trx, tenant *entity.Tenant, user *entity.User) error {- u, err := queryUser(ctx, trx, "id = $1", q.UserID)+ u, err := queryUser(ctx, trx, "id = $1 AND tenant_id = $2", q.UserID, q.TenantID)if err != nil {return errors.Wrap(err, "failed to get user with id '%d'", q.UserID)}@@ -326,7 +326,7 @@ func getUserByProvider(ctx context.Context, q *query.GetUserByProvider) error {return errors.Wrap(err, "failed to get user by provider '%s' and uid '%s'", q.Provider, q.UID)}- byID := &query.GetUserByID{UserID: userID}+ byID := &query.GetUserByID{UserID: userID, TenantID: tenant.ID}err := getUserByID(ctx, byID)q.Result = byID.Resultreturn errdiff --git a/app/services/sqlstore/postgres/user_test.go b/app/services/sqlstore/postgres/user_test.goindex bc42a4bb1..c048ba52a 100644--- a/app/services/sqlstore/postgres/user_test.go+++ b/app/services/sqlstore/postgres/user_test.go@@ -22,7 +22,7 @@ func TestUserStorage_GetByID(t *testing.T) {ctx := SetupDatabaseTest(t)defer TeardownDatabaseTest()- userByID := &query.GetUserByID{UserID: 1}+ userByID := &query.GetUserByID{UserID: 1, TenantID: demoTenant.ID}err := bus.Dispatch(ctx, userByID)Expect(err).IsNil()Expect(userByID.Result.ID).Equals(int(1))@@ -35,6 +35,27 @@ func TestUserStorage_GetByID(t *testing.T) {Expect(userByID.Result.Providers[0].Name).Equals("facebook")}+// TestUserStorage_GetByID_WrongTenant proves that a globally valid user ID paired with a+// different tenant ID resolves to "not found". This is the database-predicate guard that+// independently prevents cross-tenant user resolution.+func TestUserStorage_GetByID_WrongTenant(t *testing.T) {+ ctx := SetupDatabaseTest(t)+ defer TeardownDatabaseTest()++ // Jon Snow (id 1) belongs to the demo tenant. Ask for him under the avengers tenant.+ userByID := &query.GetUserByID{UserID: jonSnow.ID, TenantID: avengersTenant.ID}+ err := bus.Dispatch(ctx, userByID)+ Expect(errors.Cause(err)).Equals(app.ErrNotFound)+ Expect(userByID.Result).IsNil()++ // Sanity check: the same user resolves correctly under his own tenant.+ userByID = &query.GetUserByID{UserID: jonSnow.ID, TenantID: demoTenant.ID}+ err = bus.Dispatch(ctx, userByID)+ Expect(err).IsNil()+ Expect(userByID.Result.ID).Equals(jonSnow.ID)+ Expect(userByID.Result.Tenant.ID).Equals(demoTenant.ID)+}+func TestUserStorage_GetByEmail_Error(t *testing.T) {SetupDatabaseTest(t)defer TeardownDatabaseTest()@@ -142,7 +163,7 @@ func TestUserStorage_Register_WhiteSpaceEmail(t *testing.T) {err := bus.Dispatch(demoTenantCtx, &cmd.RegisterUser{User: user})Expect(err).IsNil()- getUser := &query.GetUserByID{UserID: user.ID}+ getUser := &query.GetUserByID{UserID: user.ID, TenantID: demoTenant.ID}err = bus.Dispatch(demoTenantCtx, getUser)Expect(err).IsNil()@@ -201,7 +222,7 @@ func TestUserStorage_RegisterProvider(t *testing.T) {})Expect(err).IsNil()- getUser := &query.GetUserByID{UserID: 1}+ getUser := &query.GetUserByID{UserID: 1, TenantID: demoTenant.ID}err = bus.Dispatch(demoTenantCtx, getUser)Expect(err).IsNil()@@ -357,7 +378,7 @@ func TestUserStorage_Delete(t *testing.T) {Expect(errors.Cause(err)).Equals(app.ErrNotFound)Expect(getByEmail.Result).IsNil()- getByID := &query.GetUserByID{UserID: jonSnow.ID}+ getByID := &query.GetUserByID{UserID: jonSnow.ID, TenantID: jonSnow.Tenant.ID}err = bus.Dispatch(jonSnowCtx, getByID)Expect(errors.Cause(err)).Equals(app.ErrNotFound)Expect(getByID.Result).IsNil()@@ -406,7 +427,7 @@ func TestUserStorage_BlockUser(t *testing.T) {defer TeardownDatabaseTest()userID := 1- getUser := &query.GetUserByID{UserID: userID}+ getUser := &query.GetUserByID{UserID: userID, TenantID: demoTenant.ID}err := bus.Dispatch(demoTenantCtx, getUser)Expect(err).IsNil()diff --git a/app/services/userlist/userlist.go b/app/services/userlist/userlist.goindex ae737f3cd..e14066833 100644--- a/app/services/userlist/userlist.go+++ b/app/services/userlist/userlist.go@@ -9,7 +9,9 @@ import ("net/http""strconv"+ "github.com/getfider/fider/app""github.com/getfider/fider/app/models/cmd"+ "github.com/getfider/fider/app/models/entity""github.com/getfider/fider/app/models/enum""github.com/getfider/fider/app/models/query""github.com/getfider/fider/app/pkg/bus"@@ -76,9 +78,16 @@ func (s Service) Init() {func addOrRemoveUserListUser(ctx context.Context, u *cmd.UserListHandleRoleChange) error {if u.Role == enum.RoleAdministrator {- // Get the user so we can add it to userlist.+ // Get the user so we can add it to userlist. Scope the lookup to the tenant in+ // context so a user ID is never resolved across tenant boundaries.+ tenant, _ := ctx.Value(app.TenantCtxKey).(*entity.Tenant)+ tenantID := 0+ if tenant != nil {+ tenantID = tenant.ID+ }user := &query.GetUserByID{- UserID: u.Id,+ UserID: u.Id,+ TenantID: tenantID,}err := bus.Dispatch(ctx, user)if err != nil {@@ -113,7 +122,8 @@ func addOrRemoveUserListUser(ctx context.Context, u *cmd.UserListHandleRoleChangfunc updateUserListUser(ctx context.Context, u *cmd.UserListUpdateUser) error {dbUser := &query.GetUserByID{- UserID: u.Id,+ UserID: u.Id,+ TenantID: u.TenantId,}err := bus.Dispatch(ctx, dbUser)if err != nil {