Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions .example.env
Original file line number Diff line number Diff line change
Expand Up @@ -26,9 +26,9 @@ OAUTH_GOOGLE_SECRET=
OAUTH_GITHUB_CLIENTID=
OAUTH_GITHUB_SECRET=

# Overrides the client secret of the custom OAuth provider whose client ID matches
OAUTH_CUSTOM_CLIENTID=
OAUTH_CUSTOM_SECRET=
# Sign in from guard's identity header instead (fork only, see docs/GUARD_IDENTITY.md)
GUARD_IDENTITY_ENABLED=false
PLATFORM_KIT_EDGEAUTH_AUDIENCES=

[email protected]

Expand Down
12 changes: 12 additions & 0 deletions .golangci.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
version: "2"

# Default linters. node_modules is excluded: npm ci runs before the lint in CI, and
# some packages there ship Go sources (flatted) that are not Fider's.
linters:
exclusions:
paths:
- node_modules
formatters:
exclusions:
paths:
- node_modules
8 changes: 0 additions & 8 deletions app/actions/oauth.go
Original file line number Diff line number Diff line change
Expand Up @@ -116,14 +116,6 @@ func (action *CreateEditOAuthConfig) Validate(ctx context.Context, user *entity.
if action.ClientSecret == "" {
action.ClientSecret = getConfig.Result.ClientSecret
}
// Credentials supplied by OAUTH_CUSTOM_CLIENTID/OAUTH_CUSTOM_SECRET are not editable here:
// the client ID must stay as is and any submitted secret is ignored.
if getConfig.Result.IsClientSecretFromEnv() {
if action.ClientID != getConfig.Result.ClientID {
result.AddFieldFailure("clientID", "Client ID is managed by environment (OAUTH_CUSTOM_CLIENTID).")
}
action.ClientSecret = getConfig.Result.ClientSecret
}
} else {
action.Provider = "_" + strings.ToLower(rand.String(10))
}
Expand Down
61 changes: 0 additions & 61 deletions app/actions/oauth_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@ import (
"github.com/getfider/fider/app/models/query"
. "github.com/getfider/fider/app/pkg/assert"
"github.com/getfider/fider/app/pkg/bus"
"github.com/getfider/fider/app/pkg/env"
"github.com/getfider/fider/app/pkg/rand"
)

Expand Down Expand Up @@ -218,63 +217,3 @@ func TestCreateEditOAuthConfig_EditNonExisting(t *testing.T) {
Expect(result.Err).Equals(app.ErrNotFound)
Expect(result.Ok).IsFalse()
}

func envManagedOAuthSetup(t *testing.T) *actions.CreateEditOAuthConfig {
original := env.Config.OAuth.Custom
env.Config.OAuth.Custom.ClientID = "ENV_CL_ID"
env.Config.OAuth.Custom.Secret = "ENV_SECRET"
t.Cleanup(func() { env.Config.OAuth.Custom = original })

bus.AddHandler(func(ctx context.Context, q *query.GetCustomOAuthConfigByProvider) error {
q.Result = &entity.OAuthConfig{
ID: 6,
Provider: q.Provider,
DisplayName: "Zitadel",
ClientID: "ENV_CL_ID",
ClientSecret: "STORED_SECRET",
}
return nil
})
bus.AddHandler(func(ctx context.Context, q *query.ListActiveOAuthProviders) error {
q.Result = []*dto.OAuthProviderOption{}
return nil
})

action := actions.NewCreateEditOAuthConfig()
action.Provider = "_ENV"
action.DisplayName = "Zitadel renamed"
action.Status = enum.OAuthConfigDisabled
action.ClientID = "ENV_CL_ID"
action.AuthorizeURL = "http://provider/oauth/authorize"
action.TokenURL = "http://provider/oauth/token"
action.Scope = "openid profile email"
action.ProfileURL = "http://provider/profile/me"
action.JSONUserIDPath = "sub"
action.JSONUserNamePath = "name"
action.JSONUserEmailPath = "email"
return action
}

func TestCreateEditOAuthConfig_EnvManaged_KeepsStoredCredentials(t *testing.T) {
for _, submitted := range []string{"", "NEW_SECRET"} {
RegisterT(t)
action := envManagedOAuthSetup(t)
action.ClientSecret = submitted
ctx := context.WithValue(context.Background(), app.TenantCtxKey, &entity.Tenant{IsEmailAuthAllowed: true})

result := action.Validate(ctx, nil)
ExpectSuccess(result)
Expect(action.ClientID).Equals("ENV_CL_ID")
Expect(action.ClientSecret).Equals("STORED_SECRET")
}
}

func TestCreateEditOAuthConfig_EnvManaged_RejectsClientIDChange(t *testing.T) {
RegisterT(t)
action := envManagedOAuthSetup(t)
action.ClientID = "SOMETHING_ELSE"
ctx := context.WithValue(context.Background(), app.TenantCtxKey, &entity.Tenant{IsEmailAuthAllowed: true})

result := action.Validate(ctx, nil)
ExpectFailed(result, "clientID")
}
4 changes: 2 additions & 2 deletions app/handlers/common.go
Original file line number Diff line number Diff line change
Expand Up @@ -68,9 +68,9 @@ func Sitemap() web.HandlerFunc {
text := strings.Builder{}
text.WriteString(`<?xml version="1.0" encoding="UTF-8"?>`)
text.WriteString(`<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">`)
text.WriteString(fmt.Sprintf("<url> <loc>%s</loc> </url>", baseURL))
fmt.Fprintf(&text, "<url> <loc>%s</loc> </url>", baseURL)
for _, post := range allPosts.Result {
text.WriteString(fmt.Sprintf("<url> <loc>%s/posts/%d/%s</loc> </url>", baseURL, post.Number, post.Slug))
fmt.Fprintf(&text, "<url> <loc>%s/posts/%d/%s</loc> </url>", baseURL, post.Number, post.Slug)
}
text.WriteString(`</urlset>`)

Expand Down
138 changes: 138 additions & 0 deletions app/handlers/external_signin.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,138 @@
package handlers

import (
"github.com/getfider/fider/app"
"github.com/getfider/fider/app/models/cmd"
"github.com/getfider/fider/app/models/dto"
"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"
"github.com/getfider/fider/app/pkg/errors"
"github.com/getfider/fider/app/pkg/log"
"github.com/getfider/fider/app/pkg/web"
)

// ExternalSignInOutcome says whether an external identity may sign in.
type ExternalSignInOutcome int

const (
// ExternalSignInOK means the returned user is signed in.
ExternalSignInOK ExternalSignInOutcome = iota
// ExternalSignInDenied means the identity holds none of the roles the provider allows.
ExternalSignInDenied
// ExternalSignInNotInvited means the user is new and the private site does not
// trust the provider to create accounts.
ExternalSignInNotInvited
)

// SignInExternalUser finds the Fider user an external identity belongs to, by its
// provider UID first and then by email, or creates one. It is shared by the OAuth
// callback (OAuthToken) and the guard identity (middlewares.User), so both apply the
// same rules:
//
// - config is the provider's role configuration (nil for built-in providers). When it
// has a roles path, AllowedRoles gates the sign in, and AdminRoles/CollaboratorRoles
// map the identity's roles onto a Fider role authoritatively: the user is promoted or
// demoted to it, except that the last administrator is never demoted.
// - Administrators and collaborators already trusted in Fider, and identities mapped to
// one of those roles, pass the allowed-roles gate.
// - A new user on a private site needs a trusted provider.
//
// The caller decides what a signed-in user gets (a cookie, or the request's user).
func SignInExternalUser(c *web.Context, provider string, profile *dto.OAuthUserProfile, config *entity.OAuthConfig) (*entity.User, ExternalSignInOutcome, error) {
// Look up the existing Fider user first (by provider UID, then by email).
// We need this before the role check so that administrators and collaborators
// can always sign in regardless of role changes at the provider.
var user *entity.User

userByProvider := &query.GetUserByProvider{Provider: provider, UID: profile.ID}
err := bus.Dispatch(c, userByProvider)
user = userByProvider.Result

if errors.Cause(err) == app.ErrNotFound && profile.Email != "" {
userByEmail := &query.GetUserByEmail{Email: profile.Email}
err = bus.Dispatch(c, userByEmail)
user = userByEmail.Result
}

// 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 config != nil {
providerRolesPath = config.JSONUserRolesPath
providerAllowedRoles = config.AllowedRoles
}

// Resolve the Fider role the provider's role mapping assigns to this user.
// A user mapped to collaborator or administrator is implicitly allowed through
// the allowed-roles gate, mirroring the isFiderPrivileged bypass below.
mappedRole, hasMappedRole := enum.RoleVisitor, false
if config != nil && providerRolesPath != "" {
mappedRole, hasMappedRole = resolveMappedRole(profile.Roles, config.AdminRoles, config.CollaboratorRoles)
}

isFiderPrivileged := user != nil && (user.Role == enum.RoleAdministrator || user.Role == enum.RoleCollaborator)
isMappedPrivileged := hasMappedRole && mappedRole >= enum.RoleCollaborator
if !isFiderPrivileged && !isMappedPrivileged && !hasAllowedRole(profile.Roles, providerRolesPath, providerAllowedRoles) {
log.Warnf(c, "User @{UserID} attempted to sign in through @{Provider} but does not have required role. User roles: @{UserRoles}, Allowed roles: @{AllowedRoles}",
dto.Props{
"UserID": profile.ID,
"Provider": provider,
"UserRoles": profile.Roles,
"AllowedRoles": providerAllowedRoles,
})
return nil, ExternalSignInDenied, nil
}
if err != nil {
if errors.Cause(err) != app.ErrNotFound {
return nil, ExternalSignInOK, err
}

isTrusted := config != nil && config.IsTrusted
if c.Tenant().IsPrivate && !isTrusted {
return nil, ExternalSignInNotInvited, nil
}

role := enum.RoleVisitor
if hasMappedRole {
role = mappedRole
}

user = &entity.User{
Name: profile.Name,
Tenant: c.Tenant(),
Email: profile.Email,
Role: role,
Providers: []*entity.UserProvider{
{
UID: profile.ID,
Name: provider,
},
},
}

if err = bus.Dispatch(c, &cmd.RegisterUser{User: user}); err != nil {
return nil, ExternalSignInOK, err
}
} else if !user.HasProvider(provider) {
if err = bus.Dispatch(c, &cmd.RegisterUserProvider{
UserID: user.ID,
ProviderName: provider,
ProviderUID: profile.ID,
}); err != nil {
return nil, ExternalSignInOK, err
}
}

// Sync the Fider role with the provider's role mapping on every sign in.
// The identity provider is the source of truth: users are promoted and
// demoted to whatever their current roles map to.
if hasMappedRole && user.Role != mappedRole {
if err := syncUserRole(c, user, mappedRole); err != nil {
return nil, ExternalSignInOK, err
}
}

return user, ExternalSignInOK, nil
}
60 changes: 60 additions & 0 deletions app/handlers/guard_identity.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
package handlers

import (
"net/url"
"strings"

"github.com/MetsaApp/platform-kit/edgeauth"
"github.com/getfider/fider/app/models/dto"
"github.com/getfider/fider/app/models/entity"
"github.com/getfider/fider/app/pkg/env"
"github.com/getfider/fider/app/pkg/web"
)

// Guard answers these on every host it signs users in for.
const (
guardLoginPath = "/.well-known/bastion/login"
guardLogoutPath = "/.well-known/bastion/logout"
)

// guardRolesPath stands in for a provider's JSON roles path: guard's identity already
// carries the role keys, but the shared role rules only run when a path is set.
const guardRolesPath = "roles"

// SignInGuardIdentity signs in the user behind an identity guard verified, with the same
// rules as a custom OAuth provider (SignInExternalUser). The role mapping and the allowed
// roles come from GUARD_IDENTITY_*; guard is trusted to create users on a private site,
// since its own rule already refused anyone without a role.
func SignInGuardIdentity(c *web.Context, id edgeauth.Identity) (*entity.User, ExternalSignInOutcome, error) {
cfg := env.Config.GuardIdentity

// An unverified address is neither stored nor used to find an existing account,
// or anyone could claim another user's account by setting their email.
email := ""
if id.EmailVerified {
email = strings.ToLower(strings.TrimSpace(id.Email))
}
name := strings.TrimSpace(id.Name)
if name == "" && email != "" {
name = strings.Split(email, "@")[0]
}
if name == "" {
name = "Anonymous"
}

profile := &dto.OAuthUserProfile{ID: id.Subject, Name: name, Email: email, Roles: id.Roles}
config := &entity.OAuthConfig{
Provider: cfg.Provider,
JSONUserRolesPath: guardRolesPath,
AllowedRoles: cfg.AllowedRoles,
AdminRoles: cfg.AdminRoles,
CollaboratorRoles: cfg.CollaboratorRoles,
IsTrusted: true,
}
return SignInExternalUser(c, cfg.Provider, profile, config)
}

// guardLoginURL is guard's login on this host, returning to a path on it.
func guardLoginURL(c *web.Context, redirect string) string {
return guardLoginPath + "?return_to=" + url.QueryEscape(sanitiseOAuthRedirect(c, redirect))
}
Loading
Loading