Skip to content

armgit / fider

Public Imported from GitHub
0

Open platform to collect and prioritize feedback

feature: allow impersonation on API (#508)

Guilherme Oenning9ae801f7ff08
diff --git a/app/middlewares/domain.go b/app/middlewares/tenant.go
similarity index 63%
rename from app/middlewares/domain.go
rename to app/middlewares/tenant.go
index c336e3798..a609d5471 100644
--- a/app/middlewares/domain.go
+++ b/app/middlewares/tenant.go
@@ -2,18 +2,13 @@ package middlewares
import (
"fmt"
- "strings"
-
- "github.com/getfider/fider/app/pkg/validate"
"github.com/getfider/fider/app/models"
"github.com/getfider/fider/app"
"github.com/getfider/fider/app/pkg/env"
"github.com/getfider/fider/app/pkg/errors"
- "github.com/getfider/fider/app/pkg/jwt"
"github.com/getfider/fider/app/pkg/web"
- "github.com/getfider/fider/app/pkg/web/util"
)
// Tenant adds either SingleTenant or MultiTenant to the pipeline
@@ -94,69 +89,6 @@ func RequireTenant() web.MiddlewareFunc {
}
}
-// User gets JWT Auth token from cookie and insert into context
-func User() web.MiddlewareFunc {
- return func(next web.HandlerFunc) web.HandlerFunc {
- return func(c web.Context) error {
- var (
- token string
- user *models.User
- )
-
- cookie, err := c.Request.Cookie(web.CookieAuthName)
- if err == nil {
- token = cookie.Value
- } else {
- token = webutil.GetSignUpAuthCookie(c)
- if token != "" {
- webutil.AddAuthTokenCookie(c, token)
- }
- }
-
- if token != "" {
- claims, err := jwt.DecodeFiderClaims(token)
- if err != nil {
- c.RemoveCookie(web.CookieAuthName)
- c.SetClaims(claims)
- return next(c)
- }
-
- user, err = c.Services().Users.GetByID(claims.UserID)
- if err != nil {
- if errors.Cause(err) == app.ErrNotFound {
- c.RemoveCookie(web.CookieAuthName)
- return next(c)
- }
- return err
- }
- } else {
- authHeader := c.Request.GetHeader("Authorization")
- parts := strings.Split(authHeader, "Bearer")
- if len(parts) == 2 {
- apiKey := strings.TrimSpace(parts[1])
- user, err = c.Services().Users.GetByAPIKey(apiKey)
- if err != nil {
- if errors.Cause(err) == app.ErrNotFound {
- return c.HandleValidation(validate.Failed("API Key is invalid"))
- }
- return err
- }
-
- if !user.IsCollaborator() {
- return c.HandleValidation(validate.Failed("API Key is invalid"))
- }
- }
- }
-
- if user != nil && c.Tenant() != nil && user.Tenant.ID == c.Tenant().ID {
- c.SetUser(user)
- }
-
- return next(c)
- }
- }
-}
-
// OnlyActiveTenants blocks requests for inactive tenants
func OnlyActiveTenants() web.MiddlewareFunc {
return func(next web.HandlerFunc) web.HandlerFunc {
diff --git a/app/middlewares/domain_test.go b/app/middlewares/tenant_test.go
similarity index 60%
rename from app/middlewares/domain_test.go
rename to app/middlewares/tenant_test.go
index ca069cf0e..b2fb8694f 100644
--- a/app/middlewares/domain_test.go
+++ b/app/middlewares/tenant_test.go
@@ -2,15 +2,12 @@ package middlewares_test
import (
"errors"
- "fmt"
"net/http"
"testing"
- "time"
"github.com/getfider/fider/app/middlewares"
"github.com/getfider/fider/app/models"
. "github.com/getfider/fider/app/pkg/assert"
- "github.com/getfider/fider/app/pkg/jwt"
"github.com/getfider/fider/app/pkg/mock"
"github.com/getfider/fider/app/pkg/web"
)
@@ -305,183 +302,3 @@ func TestRequireTenant_SingleHostMode_ValidTenant(t *testing.T) {
Expect(status).Equals(http.StatusOK)
Expect(response.Body.String()).Equals("Demonstration")
}
-
-func TestUser_NoCookie(t *testing.T) {
- RegisterT(t)
-
- server, _ := mock.NewServer()
- server.Use(middlewares.User())
- status, _ := server.Execute(func(c web.Context) error {
- if c.IsAuthenticated() {
- return c.NoContent(http.StatusOK)
- } else {
- return c.NoContent(http.StatusNoContent)
- }
- })
-
- Expect(status).Equals(http.StatusNoContent)
-}
-
-func TestUser_WithCookie(t *testing.T) {
- RegisterT(t)
-
- server, _ := mock.NewServer()
- token, _ := jwt.Encode(jwt.FiderClaims{
- UserID: mock.JonSnow.ID,
- UserName: mock.JonSnow.Name,
- })
-
- server.Use(middlewares.User())
- status, response := server.
- OnTenant(mock.DemoTenant).
- AddHeader("Accept", "application/json").
- AddCookie(web.CookieAuthName, 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")
- Expect(response.HeaderMap["Set-Cookie"]).HasLen(0)
-}
-
-func TestUser_WithCookie_InvalidUser(t *testing.T) {
- RegisterT(t)
-
- server, _ := mock.NewServer()
- token, _ := jwt.Encode(jwt.FiderClaims{
- UserID: 999,
- UserName: "Unknown",
- })
-
- server.Use(middlewares.User())
- status, response := server.
- OnTenant(mock.AvengersTenant).
- AddCookie(web.CookieAuthName, token).
- Execute(func(c web.Context) error {
- if c.User() == nil {
- return c.NoContent(http.StatusNoContent)
- }
- return c.NoContent(http.StatusOK)
- })
-
- Expect(status).Equals(http.StatusNoContent)
- Expect(response.Header().Get("Set-Cookie")).ContainsSubstring(web.CookieAuthName + "=;")
-}
-
-func TestUser_WithCookie_DifferentTenant(t *testing.T) {
- RegisterT(t)
-
- server, _ := mock.NewServer()
- token, _ := jwt.Encode(jwt.FiderClaims{
- UserID: mock.JonSnow.ID,
- UserName: mock.JonSnow.Name,
- })
-
- server.Use(middlewares.User())
- status, _ := server.
- OnTenant(mock.AvengersTenant).
- AddCookie(web.CookieAuthName, token).
- Execute(func(c web.Context) error {
- if c.User() == nil {
- return c.NoContent(http.StatusNoContent)
- }
- return c.NoContent(http.StatusOK)
- })
-
- Expect(status).Equals(http.StatusNoContent)
-}
-
-func TestUser_WithSignUpCookie(t *testing.T) {
- RegisterT(t)
-
- server, _ := mock.NewServer()
- token, _ := jwt.Encode(jwt.FiderClaims{
- UserID: mock.JonSnow.ID,
- UserName: mock.JonSnow.Name,
- })
-
- server.Use(middlewares.User())
- status, response := server.
- OnTenant(mock.DemoTenant).
- 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.HeaderMap["Set-Cookie"]
- Expect(cookies).HasLen(2)
-
- cookie := web.ParseCookie(cookies[0])
- Expect(cookie.Name).Equals(web.CookieSignUpAuthName)
- Expect(cookie.Value).Equals("")
- Expect(cookie.Domain).Equals("test.fider.io")
- Expect(cookie.HttpOnly).IsTrue()
- Expect(cookie.Path).Equals("/")
- Expect(cookie.Expires).TemporarilySimilar(time.Now().Add(-100*time.Hour), 5*time.Second)
-
- cookie = web.ParseCookie(cookies[1])
- Expect(cookie.Name).Equals(web.CookieAuthName)
- Expect(cookie.Value).Equals(token)
- Expect(cookie.Domain).Equals("")
- Expect(cookie.HttpOnly).IsTrue()
- Expect(cookie.Path).Equals("/")
- Expect(cookie.Expires).TemporarilySimilar(time.Now().Add(365*24*time.Hour), 5*time.Second)
-}
-
-func TestUser_ValidAPIKey(t *testing.T) {
- RegisterT(t)
-
- server, services := mock.NewServer()
- services.Users.SetCurrentUser(mock.JonSnow)
- apiKey, _ := services.Users.RegenerateAPIKey()
-
- server.Use(middlewares.User())
- status, response := server.
- OnTenant(mock.DemoTenant).
- AddHeader("Authorization", fmt.Sprintf("Bearer %s", apiKey)).
- 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")
-}
-
-func TestUser_InvalidAPIKey(t *testing.T) {
- RegisterT(t)
-
- server, _ := mock.NewServer()
-
- server.Use(middlewares.User())
- status, query := server.
- OnTenant(mock.DemoTenant).
- AddHeader("Authorization", "Bearer MY-KEY").
- ExecuteAsJSON(func(c web.Context) error {
- return c.NoContent(http.StatusOK)
- })
-
- Expect(status).Equals(http.StatusBadRequest)
- Expect(query.String("errors[0].message")).Equals("API Key is invalid")
-}
-
-func TestUser_ValidAPIKey_Visitor(t *testing.T) {
- RegisterT(t)
-
- server, services := mock.NewServer()
- services.Users.SetCurrentUser(mock.AryaStark)
- apiKey, _ := services.Users.RegenerateAPIKey()
-
- server.Use(middlewares.User())
- status, query := server.
- OnTenant(mock.DemoTenant).
- AddHeader("Authorization", fmt.Sprintf("Bearer %s", apiKey)).
- ExecuteAsJSON(func(c web.Context) error {
- return c.NoContent(http.StatusOK)
- })
-
- Expect(status).Equals(http.StatusBadRequest)
- Expect(query.String("errors[0].message")).Equals("API Key is invalid")
-}
diff --git a/app/middlewares/user.go b/app/middlewares/user.go
new file mode 100644
index 000000000..e34339506
--- /dev/null
+++ b/app/middlewares/user.go
@@ -0,0 +1,97 @@
+package middlewares
+
+import (
+ "fmt"
+ "strconv"
+ "strings"
+
+ "github.com/getfider/fider/app/pkg/validate"
+
+ "github.com/getfider/fider/app/models"
+
+ "github.com/getfider/fider/app"
+ "github.com/getfider/fider/app/pkg/errors"
+ "github.com/getfider/fider/app/pkg/jwt"
+ "github.com/getfider/fider/app/pkg/web"
+ "github.com/getfider/fider/app/pkg/web/util"
+)
+
+// User gets JWT Auth token from cookie and insert into context
+func User() web.MiddlewareFunc {
+ return func(next web.HandlerFunc) web.HandlerFunc {
+ return func(c web.Context) error {
+ var (
+ token string
+ user *models.User
+ )
+
+ cookie, err := c.Request.Cookie(web.CookieAuthName)
+ if err == nil {
+ token = cookie.Value
+ } else {
+ token = webutil.GetSignUpAuthCookie(c)
+ if token != "" {
+ webutil.AddAuthTokenCookie(c, token)
+ }
+ }
+
+ if token != "" {
+ claims, err := jwt.DecodeFiderClaims(token)
+ if err != nil {
+ c.RemoveCookie(web.CookieAuthName)
+ c.SetClaims(claims)
+ return next(c)
+ }
+
+ user, err = c.Services().Users.GetByID(claims.UserID)
+ if err != nil {
+ if errors.Cause(err) == app.ErrNotFound {
+ c.RemoveCookie(web.CookieAuthName)
+ return next(c)
+ }
+ return err
+ }
+ } else if c.Request.IsAPI() {
+ authHeader := c.Request.GetHeader("Authorization")
+ parts := strings.Split(authHeader, "Bearer")
+ if len(parts) == 2 {
+ apiKey := strings.TrimSpace(parts[1])
+ user, err = c.Services().Users.GetByAPIKey(apiKey)
+ if err != nil {
+ if errors.Cause(err) == app.ErrNotFound {
+ return c.HandleValidation(validate.Failed("API Key is invalid"))
+ }
+ return err
+ }
+
+ if !user.IsCollaborator() {
+ return c.HandleValidation(validate.Failed("API Key is invalid"))
+ }
+
+ if impersonateUserIDStr := c.Request.GetHeader("X-Fider-UserID"); impersonateUserIDStr != "" {
+ if !user.IsAdministrator() {
+ return c.HandleValidation(validate.Failed("Only Administrators are allowed to impersonate another user"))
+ }
+ impersonateUserID, err := strconv.Atoi(impersonateUserIDStr)
+ if err != nil {
+ return c.HandleValidation(validate.Failed(fmt.Sprintf("User not found for given impersonate UserID '%s'", impersonateUserIDStr)))
+ }
+ user, err = c.Services().Users.GetByID(impersonateUserID)
+ if err != nil {
+ if errors.Cause(err) == app.ErrNotFound {
+ return c.HandleValidation(validate.Failed(fmt.Sprintf("User not found for given impersonate UserID '%s'", impersonateUserIDStr)))
+ }
+ return err
+ }
+ }
+ }
+ }
+
+ if user != nil && c.Tenant() != nil && user.Tenant.ID == c.Tenant().ID {
+ c.SetUser(user)
+ }
+
+ return next(c)
+ }
+ }
+}
diff --git a/app/middlewares/user_test.go b/app/middlewares/user_test.go
new file mode 100644
index 000000000..16142d370
--- /dev/null
+++ b/app/middlewares/user_test.go
@@ -0,0 +1,291 @@
+package middlewares_test
+
+import (
+ "fmt"
+ "net/http"
+ "strconv"
+ "testing"
+ "time"
+
+ "github.com/getfider/fider/app/middlewares"
+ "github.com/getfider/fider/app/models"
+ . "github.com/getfider/fider/app/pkg/assert"
+ "github.com/getfider/fider/app/pkg/jwt"
+ "github.com/getfider/fider/app/pkg/mock"
+ "github.com/getfider/fider/app/pkg/web"
+)
+
+func TestUser_NoCookie(t *testing.T) {
+ RegisterT(t)
+
+ server, _ := mock.NewServer()
+ server.Use(middlewares.User())
+ status, _ := server.Execute(func(c web.Context) error {
+ if c.IsAuthenticated() {
+ return c.NoContent(http.StatusOK)
+ } else {
+ return c.NoContent(http.StatusNoContent)
+ }
+ })
+
+ Expect(status).Equals(http.StatusNoContent)
+}
+
+func TestUser_WithCookie(t *testing.T) {
+ RegisterT(t)
+
+ server, _ := mock.NewServer()
+ token, _ := jwt.Encode(jwt.FiderClaims{
+ UserID: mock.JonSnow.ID,
+ UserName: mock.JonSnow.Name,
+ })
+
+ server.Use(middlewares.User())
+ status, response := server.
+ OnTenant(mock.DemoTenant).
+ AddHeader("Accept", "application/json").
+ AddCookie(web.CookieAuthName, 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")
+ Expect(response.HeaderMap["Set-Cookie"]).HasLen(0)
+}
+
+func TestUser_WithCookie_InvalidUser(t *testing.T) {
+ RegisterT(t)
+
+ server, _ := mock.NewServer()
+ token, _ := jwt.Encode(jwt.FiderClaims{
+ UserID: 999,
+ UserName: "Unknown",
+ })
+
+ server.Use(middlewares.User())
+ status, response := server.
+ OnTenant(mock.AvengersTenant).
+ AddCookie(web.CookieAuthName, token).
+ Execute(func(c web.Context) error {
+ if c.User() == nil {
+ return c.NoContent(http.StatusNoContent)
+ }
+ return c.NoContent(http.StatusOK)
+ })
+
+ Expect(status).Equals(http.StatusNoContent)
+ Expect(response.Header().Get("Set-Cookie")).ContainsSubstring(web.CookieAuthName + "=;")
+}
+
+func TestUser_WithCookie_DifferentTenant(t *testing.T) {
+ RegisterT(t)
+
+ server, _ := mock.NewServer()
+ token, _ := jwt.Encode(jwt.FiderClaims{
+ UserID: mock.JonSnow.ID,
+ UserName: mock.JonSnow.Name,
+ })
+
+ server.Use(middlewares.User())
+ status, _ := server.
+ OnTenant(mock.AvengersTenant).
+ AddCookie(web.CookieAuthName, token).
+ Execute(func(c web.Context) error {
+ if c.User() == nil {
+ return c.NoContent(http.StatusNoContent)
+ }
+ return c.NoContent(http.StatusOK)
+ })
+
+ Expect(status).Equals(http.StatusNoContent)
+}
+
+func TestUser_WithSignUpCookie(t *testing.T) {
+ RegisterT(t)
+
+ server, _ := mock.NewServer()
+ token, _ := jwt.Encode(jwt.FiderClaims{
+ UserID: mock.JonSnow.ID,
+ UserName: mock.JonSnow.Name,
+ })
+
+ server.Use(middlewares.User())
+ status, response := server.
+ OnTenant(mock.DemoTenant).
+ 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.HeaderMap["Set-Cookie"]
+ Expect(cookies).HasLen(2)
+
+ cookie := web.ParseCookie(cookies[0])
+ Expect(cookie.Name).Equals(web.CookieSignUpAuthName)
+ Expect(cookie.Value).Equals("")
+ Expect(cookie.Domain).Equals("test.fider.io")
+ Expect(cookie.HttpOnly).IsTrue()
+ Expect(cookie.Path).Equals("/")
+ Expect(cookie.Expires).TemporarilySimilar(time.Now().Add(-100*time.Hour), 5*time.Second)
+
+ cookie = web.ParseCookie(cookies[1])
+ Expect(cookie.Name).Equals(web.CookieAuthName)
+ Expect(cookie.Value).Equals(token)
+ Expect(cookie.Domain).Equals("")
+ Expect(cookie.HttpOnly).IsTrue()
+ Expect(cookie.Path).Equals("/")
+ Expect(cookie.Expires).TemporarilySimilar(time.Now().Add(365*24*time.Hour), 5*time.Second)
+}
+
+func TestUser_ValidAPIKey(t *testing.T) {
+ RegisterT(t)
+
+ server, services := mock.NewServer()
+ services.Users.SetCurrentUser(mock.JonSnow)
+ apiKey, _ := services.Users.RegenerateAPIKey()
+
+ server.Use(middlewares.User())
+ status, response := server.
+ OnTenant(mock.DemoTenant).
+ WithURL("http://example.com/api/v1").
+ AddHeader("Authorization", fmt.Sprintf("Bearer %s", apiKey)).
+ 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")
+}
+
+func TestUser_InvalidAPIKey(t *testing.T) {
+ RegisterT(t)
+
+ server, _ := mock.NewServer()
+
+ server.Use(middlewares.User())
+ status, query := server.
+ OnTenant(mock.DemoTenant).
+ WithURL("http://example.com/api/v1").
+ AddHeader("Authorization", "Bearer MY-KEY").
+ ExecuteAsJSON(func(c web.Context) error {
+ return c.NoContent(http.StatusOK)
+ })
+
+ Expect(status).Equals(http.StatusBadRequest)
+ Expect(query.String("errors[0].message")).Equals("API Key is invalid")
+}
+
+func TestUser_ValidAPIKey_Visitor(t *testing.T) {
+ RegisterT(t)
+
+ server, services := mock.NewServer()
+ services.Users.SetCurrentUser(mock.AryaStark)
+ apiKey, _ := services.Users.RegenerateAPIKey()
+
+ server.Use(middlewares.User())
+ status, query := server.
+ OnTenant(mock.DemoTenant).
+ WithURL("http://example.com/api/v1").
+ AddHeader("Authorization", fmt.Sprintf("Bearer %s", apiKey)).
+ ExecuteAsJSON(func(c web.Context) error {
+ return c.NoContent(http.StatusOK)
+ })
+
+ Expect(status).Equals(http.StatusBadRequest)
+ Expect(query.String("errors[0].message")).Equals("API Key is invalid")
+}
+
+func TestUser_Impersonation_Collaborator(t *testing.T) {
+ RegisterT(t)
+
+ server, services := mock.NewServer()
+ user := &models.User{
+ Name: "The Collaborator",
+ Role: models.RoleCollaborator,
+ Status: models.UserActive,
+ Tenant: mock.DemoTenant,
+ }
+ services.Users.SetCurrentTenant(mock.DemoTenant)
+ services.Users.Register(user)
+ services.Users.SetCurrentUser(user)
+ apiKey, _ := services.Users.RegenerateAPIKey()
+
+ server.Use(middlewares.User())
+ status, query := server.
+ OnTenant(mock.DemoTenant).
+ WithURL("http://example.com/api/v1").
+ AddHeader("Authorization", fmt.Sprintf("Bearer %s", apiKey)).
+ AddHeader("X-Fider-UserID", strconv.Itoa(mock.JonSnow.ID)).
+ ExecuteAsJSON(func(c web.Context) error {
+ return c.NoContent(http.StatusOK)
+ })
+
+ Expect(status).Equals(http.StatusBadRequest)
+ Expect(query.String("errors[0].message")).Equals("Only Administrators are allowed to impersonate another user")
+}
+
+func TestUser_Impersonation_InvalidUser(t *testing.T) {
+ RegisterT(t)
+
+ server, services := mock.NewServer()
+ services.Users.SetCurrentUser(mock.JonSnow)
+ apiKey, _ := services.Users.RegenerateAPIKey()
+
+ server.Use(middlewares.User())
+ status, query := server.
+ OnTenant(mock.DemoTenant).
+ WithURL("http://example.com/api/v1").
+ AddHeader("Authorization", fmt.Sprintf("Bearer %s", apiKey)).
+ AddHeader("X-Fider-UserID", "ABC").
+ ExecuteAsJSON(func(c web.Context) error {
+ return c.NoContent(http.StatusOK)
+ })
+
+ Expect(status).Equals(http.StatusBadRequest)
+ Expect(query.String("errors[0].message")).Equals("User not found for given impersonate UserID 'ABC'")
+}
+
+func TestUser_Impersonation_UserNotFound(t *testing.T) {
+ RegisterT(t)
+
+ server, services := mock.NewServer()
+ services.Users.SetCurrentUser(mock.JonSnow)
+ apiKey, _ := services.Users.RegenerateAPIKey()
+
+ server.Use(middlewares.User())
+ status, query := server.
+ OnTenant(mock.DemoTenant).
+ WithURL("http://example.com/api/v1").
+ AddHeader("Authorization", fmt.Sprintf("Bearer %s", apiKey)).
+ AddHeader("X-Fider-UserID", "999").
+ ExecuteAsJSON(func(c web.Context) error {
+ return c.NoContent(http.StatusOK)
+ })
+
+ Expect(status).Equals(http.StatusBadRequest)
+ Expect(query.String("errors[0].message")).Equals("User not found for given impersonate UserID '999'")
+}
+
+func TestUser_Impersonation_ValidUser(t *testing.T) {
+ RegisterT(t)
+
+ server, services := mock.NewServer()
+ services.Users.SetCurrentUser(mock.JonSnow)
+ apiKey, _ := services.Users.RegenerateAPIKey()
+
+ server.Use(middlewares.User())
+ status, response := server.
+ OnTenant(mock.DemoTenant).
+ WithURL("http://example.com/api/v1").
+ AddHeader("Authorization", fmt.Sprintf("Bearer %s", apiKey)).
+ AddHeader("X-Fider-UserID", strconv.Itoa(mock.AryaStark.ID)).
+ Execute(func(c web.Context) error {
+ return c.String(http.StatusOK, c.User().Name)
+ })
+
+ Expect(status).Equals(http.StatusOK)
+ Expect(response.Body.String()).Equals("Arya Stark")
+}