Open platform to collect and prioritize feedback
Changed allowed roles form env to db level configuration, to allow per provider config
Albert Nimtz1cf53c38884a
diff --git a/.example.env b/.example.envindex 4d0ee1818..a99492ca5 100644--- a/.example.env+++ b/.example.env@@ -23,8 +23,6 @@ OAUTH_GOOGLE_SECRET=OAUTH_GITHUB_CLIENTID=OAUTH_GITHUB_SECRET=-OAUTH_ALLOWED_ROLES=-#EMAIL_MAILGUN_API=diff --git a/app/actions/oauth.go b/app/actions/oauth.goindex 67274a3d3..5ba7f94bc 100644--- a/app/actions/oauth.go+++ b/app/actions/oauth.go@@ -34,6 +34,7 @@ type CreateEditOAuthConfig struct {JSONUserNamePath string `json:"jsonUserNamePath"`JSONUserEmailPath string `json:"jsonUserEmailPath"`JSONUserRolesPath string `json:"jsonUserRolesPath"`+ AllowedRoles string `json:"allowedRoles"`}func NewCreateEditOAuthConfig() *CreateEditOAuthConfig {@@ -189,5 +190,9 @@ func (action *CreateEditOAuthConfig) Validate(ctx context.Context, user *entity.result.AddFieldFailure("jsonUserRolesPath", "JSON User Roles Path must have less than 100 characters.")}+ if len(action.AllowedRoles) > 500 {+ result.AddFieldFailure("allowedRoles", "Allowed Roles must have less than 500 characters.")+ }+return result}diff --git a/app/handlers/admin.go b/app/handlers/admin.goindex 17cea6d2e..6b487f9a7 100644--- a/app/handlers/admin.go+++ b/app/handlers/admin.go@@ -243,6 +243,7 @@ func SaveOAuthConfig() web.HandlerFunc {JSONUserNamePath: action.JSONUserNamePath,JSONUserEmailPath: action.JSONUserEmailPath,JSONUserRolesPath: action.JSONUserRolesPath,+ AllowedRoles: action.AllowedRoles,},); err != nil {return c.Failure(err)diff --git a/app/handlers/oauth.go b/app/handlers/oauth.goindex eccebf1d0..4b2c7d3fa 100644--- a/app/handlers/oauth.go+++ b/app/handlers/oauth.go@@ -17,7 +17,6 @@ import ("github.com/getfider/fider/app/pkg/bus""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/log"@@ -56,12 +55,22 @@ func OAuthEcho() web.HandlerFunc {parseRawProfile := &cmd.ParseOAuthRawProfile{Provider: provider, Body: rawProfile.Result}_ = bus.Dispatch(c, parseRawProfile)+ // Fetch provider config to show configured allowedRoles on the test page.+ // Errors are intentionally ignored here — this is a non-critical diagnostic fetch.+ var configuredAllowedRoles, configuredRolesPath string+ if providerConfig, err := getCustomOAuthConfig(c, provider); err == nil && providerConfig != nil {+ configuredAllowedRoles = providerConfig.AllowedRoles+ configuredRolesPath = providerConfig.JSONUserRolesPath+ }+return c.Page(http.StatusOK, web.Props{Page: "OAuthEcho/OAuthEcho.page",Title: "OAuth Test Page",Data: web.Map{- "body": rawProfile.Result,- "profile": parseRawProfile.Result,+ "body": rawProfile.Result,+ "profile": parseRawProfile.Result,+ "configuredRolesPath": configuredRolesPath,+ "configuredAllowedRoles": configuredAllowedRoles,},})}@@ -92,14 +101,28 @@ func OAuthToken() web.HandlerFunc {return c.Failure(err)}- // 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) {+ // Fetch custom provider config once — used for role checking and trust check below.+ // Returns nil for built-in providers (Google, Facebook, …).+ // Returns an error if the DB is unavailable — we fail hard rather than silently+ // bypassing access controls.+ customConfig, err := getCustomOAuthConfig(c, provider)+ if err != nil {+ return c.Failure(err)+ }++ // Check if user has the required roles for this provider.+ // Both AllowedRoles and JSONUserRolesPath must be set on the provider for the check to run.+ var providerRolesPath, providerAllowedRoles string+ if customConfig != nil {+ providerRolesPath = customConfig.JSONUserRolesPath+ providerAllowedRoles = customConfig.AllowedRoles+ }+ if !hasAllowedRole(oauthUser.Result.Roles, providerRolesPath, providerAllowedRoles) {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,"UserRoles": oauthUser.Result.Roles,- "AllowedRoles": env.Config.OAuth.AllowedRoles,+ "AllowedRoles": providerAllowedRoles,})return c.Redirect("/access-denied")}@@ -107,7 +130,7 @@ func OAuthToken() web.HandlerFunc {var user *entity.UseruserByProvider := &query.GetUserByProvider{Provider: provider, UID: oauthUser.Result.ID}- err := bus.Dispatch(c, userByProvider)+ err = bus.Dispatch(c, userByProvider)user = userByProvider.Resultif errors.Cause(err) == app.ErrNotFound && oauthUser.Result.Email != "" {@@ -117,7 +140,7 @@ func OAuthToken() web.HandlerFunc {}if err != nil {if errors.Cause(err) == app.ErrNotFound {- isTrusted := isTrustedOAuthProvider(c, provider)+ isTrusted := customConfig != nil && customConfig.IsTrustedif c.Tenant().IsPrivate && !isTrusted {return c.Redirect("/not-invited")}@@ -157,24 +180,21 @@ func OAuthToken() web.HandlerFunc {}}-func isTrustedOAuthProvider(ctx context.Context, provider string) bool {- customOAuthConfigByProvider := &query.GetCustomOAuthConfigByProvider{Provider: provider}- err := bus.Dispatch(ctx, customOAuthConfigByProvider)- if err != nil {- return false+// getCustomOAuthConfig fetches the custom OAuth provider config for the given provider.+// Built-in providers (Google, Facebook, GitHub, …) are identified by the absence of a+// leading "_" and never have a custom config row, so the bus dispatch is skipped for them.+// Returns (nil, nil) for built-in providers.+// Returns (nil, err) if the DB lookup fails — callers must treat this as a hard error so+// that a transient DB outage cannot silently bypass access controls.+func getCustomOAuthConfig(ctx context.Context, provider string) (*entity.OAuthConfig, error) {+ if len(provider) == 0 || provider[0] != '_' {+ return nil, nil}- 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 ""+ q := &query.GetCustomOAuthConfigByProvider{Provider: provider}+ if err := bus.Dispatch(ctx, q); err != nil {+ return nil, err}- return customOAuthConfigByProvider.Result.JSONUserRolesPath+ return q.Result, nil}// OAuthCallback handles the redirect back from the OAuth provider@@ -289,16 +309,14 @@ 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 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)+// hasAllowedRole checks if the user has any of the allowed roles configured on the provider.+// If allowedRoles is empty, all users are allowed (returns true).+// If jsonUserRolesPath is empty, the role check is skipped (returns true) — this ensures+// providers without a roles path are never accidentally blocked.+func hasAllowedRole(userRoles []string, jsonUserRolesPath string, allowedRoles string) bool {+ allowedRolesConfig := strings.TrimSpace(allowedRoles)- // If no roles restriction is configured, allow all users+ // If no roles restriction is configured on this provider, allow all usersif allowedRolesConfig == "" {return true}@@ -309,9 +327,9 @@ func hasAllowedRole(userRoles []string, jsonUserRolesPath string) bool {}// Parse allowed roles from config (comma-separated)- allowedRoles := strings.Split(allowedRolesConfig, ",")+ allowedRolesList := strings.Split(allowedRolesConfig, ",")allowedRolesMap := make(map[string]bool)- for _, role := range allowedRoles {+ for _, role := range allowedRolesList {role = strings.TrimSpace(role)if role != "" {allowedRolesMap[role] = truediff --git a/app/handlers/oauth_roles_test.go b/app/handlers/oauth_roles_test.goindex c522dcbd0..55b554d70 100644--- a/app/handlers/oauth_roles_test.go+++ b/app/handlers/oauth_roles_test.go@@ -5,56 +5,40 @@ package handlersimport ("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 ---+// --- empty / unconfigured 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")+ if !hasAllowedRole([]string{"ROLE_ADMIN"}, "roles", "") {+ t.Error("expected true when allowedRoles 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")+ if !hasAllowedRole([]string{}, "roles", "") {+ t.Error("expected true when allowedRoles 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")+ if !hasAllowedRole([]string{"ROLE_ADMIN"}, "roles", " ") {+ t.Error("expected true when allowedRoles 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{}, "") {+ if !hasAllowedRole([]string{}, "", "ROLE_ADMIN") {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{}, " ") {+ if !hasAllowedRole([]string{}, " ", "ROLE_ADMIN") {t.Error("expected true when JSONUserRolesPath is whitespace only (check should be skipped)")}}@@ -62,29 +46,25 @@ func TestHasAllowedRole_WhitespaceRolesPath_SkipsCheck(t *testing.T) {// --- matching role ---func TestHasAllowedRole_MatchingSingleRole(t *testing.T) {- setAllowedRoles(t, "ROLE_ADMIN")- if !hasAllowedRole([]string{"ROLE_ADMIN"}, "roles") {+ if !hasAllowedRole([]string{"ROLE_ADMIN"}, "roles", "ROLE_ADMIN") {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") {+ if !hasAllowedRole([]string{"ROLE_TEACHER"}, "roles", "ROLE_ADMIN,ROLE_TEACHER") {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") {+ if !hasAllowedRole([]string{"ROLE_ADMIN", "ROLE_TEACHER"}, "roles", "ROLE_ADMIN,ROLE_TEACHER") {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") {+ if !hasAllowedRole([]string{"ROLE_TEACHER"}, "roles", " ROLE_ADMIN , ROLE_TEACHER ") {t.Error("expected true when allowed roles config has surrounding whitespace")}}@@ -92,56 +72,48 @@ func TestHasAllowedRole_AllowedRolesWithWhitespace(t *testing.T) {// --- no matching role ---func TestHasAllowedRole_NoMatchingRole(t *testing.T) {- setAllowedRoles(t, "ROLE_ADMIN")- if hasAllowedRole([]string{"ROLE_STUDENT"}, "roles") {+ if hasAllowedRole([]string{"ROLE_STUDENT"}, "roles", "ROLE_ADMIN") {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")+ if hasAllowedRole([]string{}, "roles", "ROLE_ADMIN") {+ t.Error("expected false when user has no roles and allowedRoles 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")+ if hasAllowedRole(nil, "roles", "ROLE_ADMIN") {+ t.Error("expected false when user roles slice is nil and allowedRoles is set")}}func TestHasAllowedRole_CaseSensitiveNoMatch(t *testing.T) {- setAllowedRoles(t, "ROLE_ADMIN")// Role names are matched case-sensitively.- if hasAllowedRole([]string{"role_admin"}, "roles") {+ if hasAllowedRole([]string{"role_admin"}, "roles", "ROLE_ADMIN") {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")- }+ if hasAllowedRole([]string{"ROLE_GUEST"}, "roles", "ROLE_ADMIN,ROLE_TEACHER") {+ t.Error("expected false when user role does not match any allowed role")+ }}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")- }+ if hasAllowedRole([]string{"ROLE_STUDENT", "ROLE_GUEST"}, "roles", "ROLE_ADMIN,ROLE_TEACHER") {+ 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") {+ if !hasAllowedRole([]string{}, "roles", ",,, ,") {t.Error("expected true when config contains only separators (no valid roles)")}}-diff --git a/app/models/cmd/oauth.go b/app/models/cmd/oauth.goindex db1947ab0..8ef37a33e 100644--- a/app/models/cmd/oauth.go+++ b/app/models/cmd/oauth.go@@ -21,6 +21,7 @@ type SaveCustomOAuthConfig struct {JSONUserNamePath stringJSONUserEmailPath stringJSONUserRolesPath string+ AllowedRoles string}type ParseOAuthRawProfile struct {diff --git a/app/models/entity/oauth.go b/app/models/entity/oauth.goindex 08a451712..12d0304c1 100644--- a/app/models/entity/oauth.go+++ b/app/models/entity/oauth.go@@ -28,6 +28,7 @@ type OAuthConfig struct {JSONUserNamePath stringJSONUserEmailPath stringJSONUserRolesPath string+ AllowedRoles string}// MarshalJSON returns the JSON encoding of OAuthConfig@@ -53,5 +54,6 @@ func (o OAuthConfig) MarshalJSON() ([]byte, error) {"jsonUserNamePath": o.JSONUserNamePath,"jsonUserEmailPath": o.JSONUserEmailPath,"jsonUserRolesPath": o.JSONUserRolesPath,+ "allowedRoles": o.AllowedRoles,})}diff --git a/app/pkg/env/env.go b/app/pkg/env/env.goindex 2edd69977..fc1fee739 100644--- a/app/pkg/env/env.go+++ b/app/pkg/env/env.go@@ -99,7 +99,6 @@ type config struct {ClientID string `env:"OAUTH_GITHUB_CLIENTID"`Secret string `env:"OAUTH_GITHUB_SECRET"`}- AllowedRoles string `env:"OAUTH_ALLOWED_ROLES"`}Email struct {Type string `env:"EMAIL"` // possible values: smtp, mailgun, awssesdiff --git a/app/services/sqlstore/dbEntities/oauth.go b/app/services/sqlstore/dbEntities/oauth.goindex 1d41823d4..50d0480f1 100644--- a/app/services/sqlstore/dbEntities/oauth.go+++ b/app/services/sqlstore/dbEntities/oauth.go@@ -23,6 +23,7 @@ type OAuthConfig struct {JSONUserNamePath string `db:"json_user_name_path"`JSONUserEmailPath string `db:"json_user_email_path"`JSONUserRolesPath sql.NullString `db:"json_user_roles_path"`+ AllowedRoles sql.NullString `db:"allowed_roles"`}func (m *OAuthConfig) ToModel() *entity.OAuthConfig {@@ -30,6 +31,10 @@ func (m *OAuthConfig) ToModel() *entity.OAuthConfig {if m.JSONUserRolesPath.Valid {rolesPath = m.JSONUserRolesPath.String}+ allowedRoles := ""+ if m.AllowedRoles.Valid {+ allowedRoles = m.AllowedRoles.String+ }return &entity.OAuthConfig{ID: m.ID,@@ -48,5 +53,6 @@ func (m *OAuthConfig) ToModel() *entity.OAuthConfig {JSONUserNamePath: m.JSONUserNamePath,JSONUserEmailPath: m.JSONUserEmailPath,JSONUserRolesPath: rolesPath,+ AllowedRoles: allowedRoles,}}diff --git a/app/services/sqlstore/postgres/oauth.go b/app/services/sqlstore/postgres/oauth.goindex 916eec43e..409a5e93d 100644--- a/app/services/sqlstore/postgres/oauth.go+++ b/app/services/sqlstore/postgres/oauth.go@@ -24,7 +24,8 @@ func getCustomOAuthConfigByProvider(ctx context.Context, q *query.GetCustomOAuthSELECT id, provider, display_name, status, is_trusted, logo_bkey,client_id, client_secret, authorize_url,profile_url, token_url, scope, json_user_id_path,- json_user_name_path, json_user_email_path, json_user_roles_path+ json_user_name_path, json_user_email_path, json_user_roles_path,+ allowed_rolesFROM oauth_providersWHERE tenant_id = $1 AND provider = $2`, tenant.ID, q.Provider)@@ -49,7 +50,8 @@ func listCustomOAuthConfig(ctx context.Context, q *query.ListCustomOAuthConfig)SELECT id, provider, display_name, status, is_trusted, logo_bkey,client_id, client_secret, authorize_url,profile_url, token_url, scope, json_user_id_path,- json_user_name_path, json_user_email_path, json_user_roles_path+ json_user_name_path, json_user_email_path, json_user_roles_path,+ allowed_rolesFROM oauth_providersWHERE tenant_id = $1ORDER BY id`, tenant.ID)@@ -79,29 +81,29 @@ func saveCustomOAuthConfig(ctx context.Context, c *cmd.SaveCustomOAuthConfig) ertenant_id, provider, display_name, status, is_trusted,client_id, client_secret, authorize_url,profile_url, token_url, scope, json_user_id_path,- json_user_name_path, json_user_email_path, json_user_roles_path, logo_bkey- ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16)+ json_user_name_path, json_user_email_path, json_user_roles_path, allowed_roles, logo_bkey+ ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17)RETURNING id`err = trx.Get(&c.ID, query, tenant.ID, c.Provider,c.DisplayName, c.Status, c.IsTrusted, c.ClientID, c.ClientSecret,c.AuthorizeURL, c.ProfileURL, c.TokenURL,c.Scope, c.JSONUserIDPath, c.JSONUserNamePath,- c.JSONUserEmailPath, c.JSONUserRolesPath, c.Logo.BlobKey)+ c.JSONUserEmailPath, c.JSONUserRolesPath, c.AllowedRoles, c.Logo.BlobKey)} else {query := `UPDATE oauth_providersSET display_name = $3, status = $4, client_id = $5, client_secret = $6,authorize_url = $7, profile_url = $8, token_url = $9, scope = $10,json_user_id_path = $11, json_user_name_path = $12, json_user_email_path = $13,- json_user_roles_path = $14, logo_bkey = $15, is_trusted = $16+ json_user_roles_path = $14, allowed_roles = $15, logo_bkey = $16, is_trusted = $17WHERE tenant_id = $1 AND id = $2`_, err = trx.Execute(query, tenant.ID, c.ID,c.DisplayName, c.Status, c.ClientID, c.ClientSecret,c.AuthorizeURL, c.ProfileURL, c.TokenURL,c.Scope, c.JSONUserIDPath, c.JSONUserNamePath,- c.JSONUserEmailPath, c.JSONUserRolesPath, c.Logo.BlobKey, c.IsTrusted)+ c.JSONUserEmailPath, c.JSONUserRolesPath, c.AllowedRoles, c.Logo.BlobKey, c.IsTrusted)}if err != nil {diff --git a/docs/OAUTH_ROLE_RESTRICTION.md b/docs/OAUTH_ROLE_RESTRICTION.mdindex ffb78b55e..272590a5f 100644--- a/docs/OAUTH_ROLE_RESTRICTION.md+++ b/docs/OAUTH_ROLE_RESTRICTION.md@@ -2,52 +2,65 @@This feature allows you to restrict OAuth login to users who have specific roles provided by your OAuth provider.+Role restrictions are configured **per custom OAuth provider** in the Admin UI.+This means different providers can have completely independent role requirements.+## Configuration-### Environment Variable+### Admin Panel++1. Go to **Site Settings** → **Authentication** → **OAuth Providers**+2. Edit or create a custom OAuth provider+3. Configure two fields together:+ - **JSON User Roles Path** — the path in the provider's profile JSON where roles are found+ - **Allowed Roles** — a comma-separated list of roles that are permitted to sign in-Add the following environment variable to your `.env` file:+Both fields must be set for the role check to run. If either is empty, all users are allowed through for that provider.-```bash-OAUTH_ALLOWED_ROLES=ROLE_ADMIN,ROLE_TEACHER-```+### Allowed Roles field format-- **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.+- Comma-separated list of role names, e.g. `ROLE_ADMIN,ROLE_TEACHER`+- Case-sensitive: role names are matched exactly as they appear in the OAuth response+- Leave empty to allow all users (default)### Examples#### Allow only admins:-```bash-OAUTH_ALLOWED_ROLES=ROLE_ADMIN+```+ROLE_ADMIN```#### Allow admins and teachers:-```bash-OAUTH_ALLOWED_ROLES=ROLE_ADMIN,ROLE_TEACHER```--#### Allow all users (default):-```bash-# Don't set OAUTH_ALLOWED_ROLES or leave it empty-OAUTH_ALLOWED_ROLES=+ROLE_ADMIN,ROLE_TEACHER```-## OAuth Provider Configuration+#### Allow all users (default):+Leave the **Allowed Roles** field empty.-For custom OAuth providers, you need to configure the JSON path to extract roles from the OAuth response.+## JSON User Roles Path-### Admin Panel Configuration+The roles path tells Fider where to find roles in the OAuth profile response.-1. Go to **Site Settings** → **Authentication** → **OAuth Providers**-2. Edit or create a custom OAuth provider-3. Configure the **JSON User Roles Path** field+### Examples-### JSON User Roles Path Examples+#### Single role as string:+```json+{+ "id": "12345",+ "role": "ROLE_ADMIN"+}+```+**JSON User Roles Path**: `role`-The roles path supports various OAuth response formats:+#### Comma-separated string:+```json+{+ "id": "12345",+ "roles": "ROLE_ADMIN,ROLE_TEACHER"+}+```+**JSON User Roles Path**: `roles`#### Array of strings:```json@@ -77,7 +90,6 @@ This extracts the `id` field from each object in the `roles` array.#### Nested array:```json{- "id": "12345","user": {"profile": {"roles": ["ROLE_ADMIN"]@@ -100,21 +112,3 @@ This extracts the `id` field from each object in the `roles` array.}```**JSON User Roles Path**: `user.groups[].name`--#### Comma-separated string:-```json-{- "id": "12345",- "roles": "ROLE_ADMIN,ROLE_TEACHER"-}-```-**JSON User Roles Path**: `roles`--#### Single role as string:-```json-{- "id": "12345",- "role": "ROLE_ADMIN"-}-```-**JSON User Roles Path**: `role`diff --git a/migrations/202602251400_add_oauth_roles_path.sql b/migrations/202603061000_add_oauth_allowed_roles.sqlsimilarity index 52%rename from migrations/202602251400_add_oauth_roles_path.sqlrename to migrations/202603061000_add_oauth_allowed_roles.sqlindex f21ce4ade..84ca0adc2 100644--- a/migrations/202602251400_add_oauth_roles_path.sql+++ b/migrations/202603061000_add_oauth_allowed_roles.sql@@ -1,2 +1,2 @@ALTER TABLE oauth_providers ADD COLUMN json_user_roles_path TEXT;-+ALTER TABLE oauth_providers ADD COLUMN allowed_roles TEXT;diff --git a/public/models/settings.ts b/public/models/settings.tsindex 507cb250e..05085200c 100644--- a/public/models/settings.ts+++ b/public/models/settings.ts@@ -48,6 +48,7 @@ export interface OAuthConfig {jsonUserNamePath: stringjsonUserEmailPath: stringjsonUserRolesPath: string+ allowedRoles: stringisTrusted: boolean}diff --git a/public/pages/Administration/components/OAuthForm.tsx b/public/pages/Administration/components/OAuthForm.tsxindex 128ff3062..2c05ab930 100644--- a/public/pages/Administration/components/OAuthForm.tsx+++ b/public/pages/Administration/components/OAuthForm.tsx@@ -28,6 +28,7 @@ export const OAuthForm: React.FC<OAuthFormProps> = (props) => {const [jsonUserNamePath, setJSONUserNamePath] = useState((props.config && props.config.jsonUserNamePath) || "")const [jsonUserEmailPath, setJSONUserEmailPath] = useState((props.config && props.config.jsonUserEmailPath) || "")const [jsonUserRolesPath, setJSONUserRolesPath] = useState((props.config && props.config.jsonUserRolesPath) || "")+ const [allowedRoles, setAllowedRoles] = useState((props.config && props.config.allowedRoles) || "")const [logo, setLogo] = useState<ImageUpload | undefined>()const [logoURL, setLogoURL] = useState<string | undefined>()const [logoBlobKey, setLogoBlobKey] = useState((props.config && props.config.logoBlobKey) || "")@@ -49,6 +50,7 @@ export const OAuthForm: React.FC<OAuthFormProps> = (props) => {jsonUserNamePath,jsonUserEmailPath,jsonUserRolesPath,+ allowedRoles,logo,})if (result.ok) {@@ -153,7 +155,7 @@ export const OAuthForm: React.FC<OAuthFormProps> = (props) => {<h3 className="text-title mt-8 mb-2">JSON Path</h3><p>Find out more about{" "}- <a rel="noopener" className="text-link" target="_blank" href="https://fider.io/docs/configuring-oauth#configuring-the-json-paths">+ <a rel="noopener" className="text-link" target="_blank" href="https://docs.fider.io/configuring-oauth#configuring-the-json-paths">configuring the JSON Paths</a>.@@ -202,10 +204,24 @@ export const OAuthForm: React.FC<OAuthFormProps> = (props) => {disabled={!fider.session.user.isAdministrator}onChange={setJSONUserRolesPath}>- <p className="text-muted">Optional. Used for role-based access control.</p>+ <p className="text-muted">Optional. JSON path to extract roles from the provider profile.</p></Input></div>+ <Input+ field="allowedRoles"+ label="Allowed Roles"+ maxLength={500}+ value={allowedRoles}+ disabled={!fider.session.user.isAdministrator}+ onChange={setAllowedRoles}+ >+ <p className="text-muted">+ Optional. Comma-separated list of roles allowed to sign in, e.g. <strong>ROLE_ADMIN,ROLE_TEACHER</strong>. Only enforced when a Roles JSON path is+ also configured. Leave empty to allow all roles.+ </p>+ </Input>+<Field label="Trusted Source"><Toggle field="isTrusted" active={isTrusted} onToggle={setTrusted} label={isTrusted ? "Yes" : "No"} /><p className="text-muted mt-1">diff --git a/public/pages/Administration/pages/ManageAuthentication.page.tsx b/public/pages/Administration/pages/ManageAuthentication.page.tsxindex 46ee1a05b..6618a3b87 100644--- a/public/pages/Administration/pages/ManageAuthentication.page.tsx+++ b/public/pages/Administration/pages/ManageAuthentication.page.tsx@@ -138,7 +138,7 @@ export default class ManageAuthenticationPage extends AdminBasePage<ManageAuthen<h2 className="text-display">OAuth Providers</h2><p>You can use these section to add any authentication provider thats supports the OAuth2 protocol. Additional information is available in our{" "}- <a rel="noopener" className="text-link" target="_blank" href="https://fider.io/docs/configuring-oauth/">+ <a rel="noopener" className="text-link" target="_blank" href="https://docs.fider.io/configuring-oauth">OAuth Documentation</a>.diff --git a/public/pages/Administration/pages/ManageWebhooks.page.tsx b/public/pages/Administration/pages/ManageWebhooks.page.tsxindex ff3042763..2b4141272 100644--- a/public/pages/Administration/pages/ManageWebhooks.page.tsx+++ b/public/pages/Administration/pages/ManageWebhooks.page.tsx@@ -129,7 +129,7 @@ const ManageWebhooksPage = (props: ManageWebhooksPageProps) => {<VStack spacing={8}><p>Use webhooks to integrate Fider with other applications like Slack, Discord, Zapier and many others.{" "}- <a className="text-link" href="https://fider.io/docs/using-webhooks" target="_blank" rel="noopener">+ <a className="text-link" href="https://docs.fider.io/using-webhooks" target="_blank" rel="noopener">Learn more in our documentation</a>.diff --git a/public/pages/MySettings/components/APIKeyForm.tsx b/public/pages/MySettings/components/APIKeyForm.tsxindex 5ab54de44..e37bf1903 100644--- a/public/pages/MySettings/components/APIKeyForm.tsx+++ b/public/pages/MySettings/components/APIKeyForm.tsx@@ -49,7 +49,7 @@ export class APIKeyForm extends React.Component<any, APIKeyFormState> {<p className="text-muted"><Trans id="mysettings.apikey.documentation">To learn how to use the API, read the{" "}- <a className="text-link" rel="noopener" href="https://fider.io/docs/api" target="_blank">+ <a className="text-link" rel="noopener" href="https://docs.fider.io/api" target="_blank">official documentation</a>.diff --git a/public/pages/OAuthEcho/OAuthEcho.page.tsx b/public/pages/OAuthEcho/OAuthEcho.page.tsxindex b835f438f..490d41597 100644--- a/public/pages/OAuthEcho/OAuthEcho.page.tsx+++ b/public/pages/OAuthEcho/OAuthEcho.page.tsx@@ -16,6 +16,8 @@ interface OAuthEchoPageProps {email: stringroles: string[]}+ configuredRolesPath: string+ configuredAllowedRoles: string}const ok = <Icon sprite={IconCheckCircle} className="h-4 text-green-500" />@@ -42,6 +44,17 @@ export default class OAuthEchoPage extends React.Component<OAuthEchoPageProps, aconst emailOk = this.props.profile && this.props.profile.email !== ""const hasRoles = this.props.profile && this.props.profile.roles && this.props.profile.roles.length > 0+ const { configuredRolesPath, configuredAllowedRoles } = this.props+ const roleCheckConfigured = configuredRolesPath && configuredAllowedRoles+ let roleCheckPasses = true+ if (roleCheckConfigured && this.props.profile) {+ const allowed = configuredAllowedRoles+ .split(",")+ .map((r) => r.trim())+ .filter((r) => r !== "")+ roleCheckPasses = allowed.length === 0 || (this.props.profile.roles || []).some((r) => allowed.includes(r.trim()))+ }+let responseBody = ""try {responseBody = JSON.stringify(JSON.parse(this.props.body), null, " ")@@ -89,8 +102,26 @@ export default class OAuthEchoPage extends React.Component<OAuthEchoPageProps, a{hasRoles ? ok : warn}<strong>Roles:</strong> {hasRoles ? this.props.profile.roles.join(", ") : "(none)"}</HStack>- <span className="text-muted">Roles are optional and used for role-based access control when OAUTH_ALLOWED_ROLES is configured.</span>+ <span className="text-muted">+ Roles are optional and used for role-based access control when <strong>Allowed Roles</strong> is configured on this provider.+ </span></VStack>+ {roleCheckConfigured && (+ <VStack>+ <HStack>+ {roleCheckPasses ? ok : error}+ <strong>Role check:</strong>{" "}+ {roleCheckPasses ? (+ <span className="text-green-700">Pass</span>+ ) : (+ <span className="text-red-700">Fail — this user would be redirected to /access-denied</span>+ )}+ </HStack>+ <span className="text-muted">+ Configured roles path: <strong>{configuredRolesPath}</strong> · Allowed roles: <strong>{configuredAllowedRoles}</strong>+ </span>+ </VStack>+ )}</VStack></>)diff --git a/public/services/actions/tenant.ts b/public/services/actions/tenant.tsindex fd2ecd135..2ea49da70 100644--- a/public/services/actions/tenant.ts+++ b/public/services/actions/tenant.ts@@ -119,6 +119,7 @@ export interface CreateEditOAuthConfigRequest {jsonUserNamePath: stringjsonUserEmailPath: stringjsonUserRolesPath: string+ allowedRoles: stringlogo?: ImageUploadisTrusted: boolean}