Open platform to collect and prioritize feedback
Fixed role check being used for all oauth provider
Albert Nimtzc60d23aca8d7
diff --git a/app/handlers/oauth.go b/app/handlers/oauth.goindex 6a46e50e2..eccebf1d0 100644--- a/app/handlers/oauth.go+++ b/app/handlers/oauth.go@@ -92,8 +92,9 @@ func OAuthToken() web.HandlerFunc {return c.Failure(err)}- // Check if user has required roles (if OAUTH_ALLOWED_ROLES is configured)- if !hasAllowedRole(oauthUser.Result.Roles) {+ // Check if user has required roles (if OAUTH_ALLOWED_ROLES is configured AND provider has a roles path)+ providerRolesPath := getProviderJSONUserRolesPath(c, provider)+ if !hasAllowedRole(oauthUser.Result.Roles, providerRolesPath) {log.Warnf(c, "User @{UserID} attempted OAuth login but does not have required role. User roles: @{UserRoles}, Allowed roles: @{AllowedRoles}",dto.Props{"UserID": oauthUser.Result.ID,@@ -165,6 +166,17 @@ func isTrustedOAuthProvider(ctx context.Context, provider string) bool {return customOAuthConfigByProvider.Result.IsTrusted}+// getProviderJSONUserRolesPath returns the JSONUserRolesPath configured for a custom OAuth provider.+// Returns empty string if the provider is a built-in provider or if the config cannot be retrieved.+func getProviderJSONUserRolesPath(ctx context.Context, provider string) string {+ customOAuthConfigByProvider := &query.GetCustomOAuthConfigByProvider{Provider: provider}+ err := bus.Dispatch(ctx, customOAuthConfigByProvider)+ if err != nil {+ return ""+ }+ return customOAuthConfigByProvider.Result.JSONUserRolesPath+}+// OAuthCallback handles the redirect back from the OAuth provider// This callback can run on either Tenant or Login address// If the request is for a sign in, we redirect the user to the tenant address@@ -277,10 +289,13 @@ func SignInByOAuth() web.HandlerFunc {}}-// hasAllowedRole checks if the user has any of the allowed roles configured in OAUTH_ALLOWED_ROLES-// If OAUTH_ALLOWED_ROLES is not set or empty, all users are allowed (returns true)-// If set, user must have at least one of the specified roles-func hasAllowedRole(userRoles []string) bool {+// hasAllowedRole checks if the user has any of the allowed roles configured in OAUTH_ALLOWED_ROLES.+// If OAUTH_ALLOWED_ROLES is not set or empty, all users are allowed (returns true).+// If the provider has no JSONUserRolesPath configured, the role check is skipped (returns true).+// This ensures that providers without a roles path (e.g. built-in Google/GitHub OAuth) are never+// accidentally blocked in a multi-provider setup where OAUTH_ALLOWED_ROLES is configured for a+// different provider that does return roles.+func hasAllowedRole(userRoles []string, jsonUserRolesPath string) bool {allowedRolesConfig := strings.TrimSpace(env.Config.OAuth.AllowedRoles)// If no roles restriction is configured, allow all users@@ -288,8 +303,13 @@ func hasAllowedRole(userRoles []string) bool {return true}- // Parse allowed roles from config (semicolon-separated)- allowedRoles := strings.Split(allowedRolesConfig, ";")+ // If the provider has no roles path configured, skip the role check for this provider+ if strings.TrimSpace(jsonUserRolesPath) == "" {+ return true+ }++ // Parse allowed roles from config (comma-separated)+ allowedRoles := strings.Split(allowedRolesConfig, ",")allowedRolesMap := make(map[string]bool)for _, role := range allowedRoles {role = strings.TrimSpace(role)diff --git a/app/handlers/oauth_roles_test.go b/app/handlers/oauth_roles_test.gonew file mode 100644index 000000000..c522dcbd0--- /dev/null+++ b/app/handlers/oauth_roles_test.go@@ -0,0 +1,147 @@+package handlers++// Internal test file for hasAllowedRole — uses package handlers (not handlers_test)+// so the unexported function is accessible without exporting it.++import (+ "testing"++ "github.com/getfider/fider/app/pkg/env"+)++// setAllowedRoles sets env.Config.OAuth.AllowedRoles for the duration of a test+// and automatically restores the original value when the test finishes.+func setAllowedRoles(t *testing.T, value string) {+ t.Helper()+ original := env.Config.OAuth.AllowedRoles+ env.Config.OAuth.AllowedRoles = value+ t.Cleanup(func() { env.Config.OAuth.AllowedRoles = original })+}++// --- empty / unconfigured OAUTH_ALLOWED_ROLES ---++func TestHasAllowedRole_EmptyConfig_AllowsAll(t *testing.T) {+ setAllowedRoles(t, "")+ if !hasAllowedRole([]string{"ROLE_ADMIN"}, "roles") {+ t.Error("expected true when OAUTH_ALLOWED_ROLES is empty")+ }+}++func TestHasAllowedRole_EmptyConfig_AllowsEmptyRoles(t *testing.T) {+ setAllowedRoles(t, "")+ if !hasAllowedRole([]string{}, "roles") {+ t.Error("expected true when OAUTH_ALLOWED_ROLES is empty and user has no roles")+ }+}++func TestHasAllowedRole_WhitespaceOnlyConfig_AllowsAll(t *testing.T) {+ setAllowedRoles(t, " ")+ if !hasAllowedRole([]string{"ROLE_ADMIN"}, "roles") {+ t.Error("expected true when OAUTH_ALLOWED_ROLES is whitespace only")+ }+}++// --- provider has no JSONUserRolesPath (skip check) ---++func TestHasAllowedRole_NoRolesPath_SkipsCheck(t *testing.T) {+ setAllowedRoles(t, "ROLE_ADMIN")+ // Provider without a roles path must always be allowed through,+ // regardless of whether the user carries matching roles or not.+ if !hasAllowedRole([]string{}, "") {+ t.Error("expected true when provider has no JSONUserRolesPath (check should be skipped)")+ }+}++func TestHasAllowedRole_WhitespaceRolesPath_SkipsCheck(t *testing.T) {+ setAllowedRoles(t, "ROLE_ADMIN")+ if !hasAllowedRole([]string{}, " ") {+ t.Error("expected true when JSONUserRolesPath is whitespace only (check should be skipped)")+ }+}++// --- matching role ---++func TestHasAllowedRole_MatchingSingleRole(t *testing.T) {+ setAllowedRoles(t, "ROLE_ADMIN")+ if !hasAllowedRole([]string{"ROLE_ADMIN"}, "roles") {+ t.Error("expected true when user has the required role")+ }+}++func TestHasAllowedRole_MatchingOneOfMultipleAllowed(t *testing.T) {+ setAllowedRoles(t, "ROLE_ADMIN,ROLE_TEACHER")+ if !hasAllowedRole([]string{"ROLE_TEACHER"}, "roles") {+ t.Error("expected true when user has one of the allowed roles")+ }+}++func TestHasAllowedRole_MatchingMultipleAllowed(t *testing.T) {+ setAllowedRoles(t, "ROLE_ADMIN,ROLE_TEACHER")+ if !hasAllowedRole([]string{"ROLE_ADMIN", "ROLE_TEACHER"}, "roles") {+ t.Error("expected true when user has all of the allowed roles")+ }+}++func TestHasAllowedRole_AllowedRolesWithWhitespace(t *testing.T) {+ setAllowedRoles(t, " ROLE_ADMIN , ROLE_TEACHER ")+ if !hasAllowedRole([]string{"ROLE_TEACHER"}, "roles") {+ t.Error("expected true when allowed roles config has surrounding whitespace")+ }+}++// --- no matching role ---++func TestHasAllowedRole_NoMatchingRole(t *testing.T) {+ setAllowedRoles(t, "ROLE_ADMIN")+ if hasAllowedRole([]string{"ROLE_STUDENT"}, "roles") {+ t.Error("expected false when user does not have any allowed role")+ }+}++func TestHasAllowedRole_EmptyUserRoles_WithConfig(t *testing.T) {+ setAllowedRoles(t, "ROLE_ADMIN")+ if hasAllowedRole([]string{}, "roles") {+ t.Error("expected false when user has no roles and OAUTH_ALLOWED_ROLES is set")+ }+}++func TestHasAllowedRole_NilUserRoles_WithConfig(t *testing.T) {+ setAllowedRoles(t, "ROLE_ADMIN")+ if hasAllowedRole(nil, "roles") {+ t.Error("expected false when user roles slice is nil and OAUTH_ALLOWED_ROLES is set")+ }+}++func TestHasAllowedRole_CaseSensitiveNoMatch(t *testing.T) {+ setAllowedRoles(t, "ROLE_ADMIN")+ // Role names are matched case-sensitively.+ if hasAllowedRole([]string{"role_admin"}, "roles") {+ t.Error("expected false: role matching must be case-sensitive")+ }+}++func TestHasAllowedRole_MultipleDefinedNoMatch(t *testing.T) {+ setAllowedRoles(t, "ROLE_ADMIN,ROLE_TEACHER")+ if hasAllowedRole([]string{"ROLE_GUEST"}, "roles") {+ t.Error("expected false when user has multiple roles but none match the allowed roles")+ }+}++func TestHasAllowedRole_MultipleNoMatch(t *testing.T) {+ setAllowedRoles(t, "ROLE_ADMIN,ROLE_TEACHER")+ if hasAllowedRole([]string{"ROLE_STUDENT", "ROLE_GUEST"}, "roles") {+ t.Error("expected false when user has multiple roles but none match the allowed roles")+ }+}++// --- edge cases ---++func TestHasAllowedRole_ConfigWithOnlyCommas_AllowsAll(t *testing.T) {+ // A config of only separators produces no valid role entries → allow all.+ setAllowedRoles(t, ",,, ,")+ if !hasAllowedRole([]string{}, "roles") {+ t.Error("expected true when config contains only separators (no valid roles)")+ }+}++diff --git a/app/pkg/jsonq/jsonq.go b/app/pkg/jsonq/jsonq.goindex 16812b518..942f04c82 100644--- a/app/pkg/jsonq/jsonq.go+++ b/app/pkg/jsonq/jsonq.go@@ -86,6 +86,16 @@ func (q *Query) Contains(selector string) bool {return q.get(selector) != nil}+//Raw returns the raw JSON bytes at the given dot-notation selector, or nil if not found.+func (q *Query) Raw(selector string) []byte {+ msg := q.get(selector)+ if msg == nil {+ return nil+ }+ b, _ := msg.MarshalJSON()+ return b+}+func (q *Query) get(selector string) *json.RawMessage {if selector == "" {return nildiff --git a/app/services/oauth/oauth.go b/app/services/oauth/oauth.goindex bfffa84ae..ecd16c345 100644--- a/app/services/oauth/oauth.go+++ b/app/services/oauth/oauth.go@@ -211,118 +211,75 @@ func extractRolesFromJSON(jsonBody string, rolesPath string) []string {return nil}- // Parse the JSON body- var data map[string]interface{}- if err := json.Unmarshal([]byte(jsonBody), &data); err != nil {- return nil- }-- // Check if we need to extract a field from array of objects (e.g., "roles[].id")+ // Split "roles[].id" into actualPath="roles" and fieldToExtract="id"var fieldToExtract stringvar actualPath string-if strings.Contains(rolesPath, "[].") {- parts := strings.Split(rolesPath, "[].")- if len(parts) == 2 {- actualPath = parts[0]- fieldToExtract = parts[1]- }+ parts := strings.SplitN(rolesPath, "[].", 2)+ actualPath = parts[0]+ fieldToExtract = parts[1]} else {actualPath = rolesPath}- // Navigate to the value using the path- value := navigateJSONPath(data, actualPath)- if value == nil {+ // Use jsonq to navigate to the value at actualPath+ rawBytes := jsonq.New(jsonBody).Raw(actualPath)+ if rawBytes == nil {return nil}- // If it's an array- if arr, ok := value.([]interface{}); ok {- roles := make([]string, 0)-- // If we need to extract a field from objects+ // Try to unmarshal as an array+ var arr []json.RawMessage+ if err := json.Unmarshal(rawBytes, &arr); err == nil {+ roles := make([]string, 0, len(arr))if fieldToExtract != "" {+ // Array of objects — extract the named field from each elementfor _, item := range arr {- if obj, ok := item.(map[string]interface{}); ok {- if fieldValue, exists := obj[fieldToExtract]; exists {- if roleStr, ok := fieldValue.(string); ok && roleStr != "" {- roles = append(roles, strings.TrimSpace(roleStr))- }- }+ obj := jsonq.New(string(item))+ if s := strings.TrimSpace(obj.String(fieldToExtract)); s != "" {+ roles = append(roles, s)}}} else {- // Array of strings+ // Array of plain stringsfor _, item := range arr {- if roleStr, ok := item.(string); ok && roleStr != "" {- roles = append(roles, strings.TrimSpace(roleStr))+ var s string+ if err := json.Unmarshal(item, &s); err == nil {+ if s = strings.TrimSpace(s); s != "" {+ roles = append(roles, s)+ }}}}-if len(roles) > 0 {return roles}+ return nil}- // If it's a string, try splitting- if str, ok := value.(string); ok {+ // Try to unmarshal as a plain string (comma-separated or single value)+ var str string+ if err := json.Unmarshal(rawBytes, &str); err == nil {str = strings.TrimSpace(str)- if str != "" {- // Try splitting by semicolon first, then comma- var roles []string- if strings.Contains(str, ";") {- roles = strings.Split(str, ";")- } else if strings.Contains(str, ",") {- roles = strings.Split(str, ",")- } else {- roles = []string{str}- }-- // Trim whitespace from each role- cleanRoles := make([]string, 0)- for _, role := range roles {- role = strings.TrimSpace(role)- if role != "" {- cleanRoles = append(cleanRoles, role)- }- }- return cleanRoles+ if str == "" {+ return nil}- }-- return nil-}--// navigateJSONPath navigates through nested JSON structure using dot notation-// e.g., "user.profile.roles" will navigate data["user"]["profile"]["roles"]-func navigateJSONPath(data map[string]interface{}, path string) interface{} {- if path == "" {- return nil- }-- parts := strings.Split(path, ".")- var current interface{} = data-- for _, part := range parts {- part = strings.TrimSpace(part)- if part == "" {- continue+ var parts []string+ if strings.Contains(str, ",") {+ parts = strings.Split(str, ",")+ } else {+ parts = []string{str}}-- if m, ok := current.(map[string]interface{}); ok {- if value, exists := m[part]; exists {- current = value- } else {- return nil+ roles := make([]string, 0, len(parts))+ for _, r := range parts {+ if r = strings.TrimSpace(r); r != "" {+ roles = append(roles, r)}- } else {- return nil}+ return roles}- return current+ return nil}func getOAuthAuthorizationURL(ctx context.Context, q *query.GetOAuthAuthorizationURL) error {diff --git a/docs/OAUTH_ROLE_RESTRICTION.md b/docs/OAUTH_ROLE_RESTRICTION.mdindex cca21c36e..ffb78b55e 100644--- a/docs/OAUTH_ROLE_RESTRICTION.md+++ b/docs/OAUTH_ROLE_RESTRICTION.md@@ -9,12 +9,13 @@ This feature allows you to restrict OAuth login to users who have specific rolesAdd the following environment variable to your `.env` file:```bash-OAUTH_ALLOWED_ROLES=ROLE_ADMIN;ROLE_TEACHER+OAUTH_ALLOWED_ROLES=ROLE_ADMIN,ROLE_TEACHER```-- **Format**: Semicolon-separated list of role names+- **Format**: Comma-separated list of role names- **Case-sensitive**: Role names are matched exactly as they appear in the OAuth response- **Optional**: If not set or empty, all users are allowed to login (default behavior)+- **Per-provider enforcement**: The role check is only applied to OAuth providers that have a **JSON User Roles Path** configured. Providers without a roles path (e.g. built-in Google or GitHub OAuth) are always allowed through, even when `OAUTH_ALLOWED_ROLES` is set. This prevents accidentally blocking users from providers that don't return roles.### Examples@@ -25,7 +26,7 @@ OAUTH_ALLOWED_ROLES=ROLE_ADMIN#### Allow admins and teachers:```bash-OAUTH_ALLOWED_ROLES=ROLE_ADMIN;ROLE_TEACHER+OAUTH_ALLOWED_ROLES=ROLE_ADMIN,ROLE_TEACHER```#### Allow all users (default):@@ -100,7 +101,7 @@ This extracts the `id` field from each object in the `roles` array.```**JSON User Roles Path**: `user.groups[].name`-#### Comma or semicolon-separated string:+#### Comma-separated string:```json{"id": "12345",