diff --git a/.example.env b/.example.env index 29575b1890..9a4582d418 100644 --- a/.example.env +++ b/.example.env @@ -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_NOREPLY=noreply@yourdomain.com diff --git a/.golangci.yml b/.golangci.yml new file mode 100644 index 0000000000..cbcbe11c97 --- /dev/null +++ b/.golangci.yml @@ -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 diff --git a/app/actions/oauth.go b/app/actions/oauth.go index 77418f5cb1..002ed78713 100644 --- a/app/actions/oauth.go +++ b/app/actions/oauth.go @@ -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)) } diff --git a/app/actions/oauth_test.go b/app/actions/oauth_test.go index 2d3174e05b..5eb05f72a5 100644 --- a/app/actions/oauth_test.go +++ b/app/actions/oauth_test.go @@ -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" ) @@ -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") -} diff --git a/app/handlers/common.go b/app/handlers/common.go index 6b4b5d0ee9..093143ae7a 100644 --- a/app/handlers/common.go +++ b/app/handlers/common.go @@ -68,9 +68,9 @@ func Sitemap() web.HandlerFunc { text := strings.Builder{} text.WriteString(``) text.WriteString(``) - text.WriteString(fmt.Sprintf(" %s ", baseURL)) + fmt.Fprintf(&text, " %s ", baseURL) for _, post := range allPosts.Result { - text.WriteString(fmt.Sprintf(" %s/posts/%d/%s ", baseURL, post.Number, post.Slug)) + fmt.Fprintf(&text, " %s/posts/%d/%s ", baseURL, post.Number, post.Slug) } text.WriteString(``) diff --git a/app/handlers/external_signin.go b/app/handlers/external_signin.go new file mode 100644 index 0000000000..47abbd4134 --- /dev/null +++ b/app/handlers/external_signin.go @@ -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 +} diff --git a/app/handlers/guard_identity.go b/app/handlers/guard_identity.go new file mode 100644 index 0000000000..68b1625660 --- /dev/null +++ b/app/handlers/guard_identity.go @@ -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)) +} diff --git a/app/handlers/oauth.go b/app/handlers/oauth.go index 7c32a324f4..b37d23b9bf 100644 --- a/app/handlers/oauth.go +++ b/app/handlers/oauth.go @@ -20,7 +20,6 @@ import ( "github.com/getfider/fider/app/models/query" "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" @@ -250,98 +249,15 @@ func OAuthToken() web.HandlerFunc { return c.Failure(err) } - // 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 OAuth role changes. - var user *entity.User - - userByProvider := &query.GetUserByProvider{Provider: provider, UID: oauthUser.Result.ID} - err = bus.Dispatch(c, userByProvider) - user = userByProvider.Result - - if errors.Cause(err) == app.ErrNotFound && oauthUser.Result.Email != "" { - userByEmail := &query.GetUserByEmail{Email: oauthUser.Result.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. - // Administrators and collaborators already trusted in Fider are always allowed through, - // regardless of their current OAuth roles. - var providerRolesPath, providerAllowedRoles string - if customConfig != nil { - providerRolesPath = customConfig.JSONUserRolesPath - providerAllowedRoles = customConfig.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 customConfig != nil && providerRolesPath != "" { - mappedRole, hasMappedRole = resolveMappedRole(oauthUser.Result.Roles, customConfig.AdminRoles, customConfig.CollaboratorRoles) - } - - isFiderPrivileged := user != nil && (user.Role == enum.RoleAdministrator || user.Role == enum.RoleCollaborator) - isMappedPrivileged := hasMappedRole && mappedRole >= enum.RoleCollaborator - if !isFiderPrivileged && !isMappedPrivileged && !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": providerAllowedRoles, - }) - return c.Redirect("/access-denied") - } + user, outcome, err := SignInExternalUser(c, provider, oauthUser.Result, customConfig) if err != nil { - if errors.Cause(err) == app.ErrNotFound { - isTrusted := customConfig != nil && customConfig.IsTrusted - if c.Tenant().IsPrivate && !isTrusted { - return c.Redirect("/not-invited") - } - - role := enum.RoleVisitor - if hasMappedRole { - role = mappedRole - } - - user = &entity.User{ - Name: oauthUser.Result.Name, - Tenant: c.Tenant(), - Email: oauthUser.Result.Email, - Role: role, - Providers: []*entity.UserProvider{ - { - UID: oauthUser.Result.ID, - Name: provider, - }, - }, - } - - if err = bus.Dispatch(c, &cmd.RegisterUser{User: user}); err != nil { - return c.Failure(err) - } - } else { - return c.Failure(err) - } - } else if !user.HasProvider(provider) { - if err = bus.Dispatch(c, &cmd.RegisterUserProvider{ - UserID: user.ID, - ProviderName: provider, - ProviderUID: oauthUser.Result.ID, - }); err != nil { - return c.Failure(err) - } + return c.Failure(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 c.Failure(err) - } + switch outcome { + case ExternalSignInDenied: + return c.Redirect("/access-denied") + case ExternalSignInNotInvited: + return c.Redirect("/not-invited") } webutil.AddAuthUserCookie(c, user) diff --git a/app/handlers/signin.go b/app/handlers/signin.go index 470aada7a0..3ad843cf1b 100644 --- a/app/handlers/signin.go +++ b/app/handlers/signin.go @@ -13,6 +13,7 @@ import ( "github.com/getfider/fider/app/actions" "github.com/getfider/fider/app/models/query" "github.com/getfider/fider/app/pkg/bus" + "github.com/getfider/fider/app/pkg/env" "github.com/getfider/fider/app/pkg/errors" "github.com/getfider/fider/app/pkg/web" webutil "github.com/getfider/fider/app/pkg/web/util" @@ -22,6 +23,9 @@ import ( // SignInPage renders the sign in page func SignInPage() web.HandlerFunc { return func(c *web.Context) error { + if env.Config.GuardIdentity.Enabled { + return c.Redirect(guardLoginURL(c, c.QueryParam("redirect"))) + } if c.Tenant().IsPrivate { return c.Page(http.StatusOK, web.Props{ @@ -426,6 +430,9 @@ func CompleteSignInProfile() web.HandlerFunc { func SignOut() web.HandlerFunc { return func(c *web.Context) error { c.RemoveCookie(web.CookieAuthName) + if env.Config.GuardIdentity.Enabled { + return c.Redirect(guardLogoutPath) + } return c.Redirect("/") } } diff --git a/app/handlers/signin_test.go b/app/handlers/signin_test.go index ca027bf9dd..454c5b8d05 100644 --- a/app/handlers/signin_test.go +++ b/app/handlers/signin_test.go @@ -18,6 +18,7 @@ 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/jwt" "github.com/getfider/fider/app/pkg/mock" "github.com/getfider/fider/app/pkg/web" @@ -793,6 +794,51 @@ func TestSignInPageHandler_PrivateTenant_UnauthenticatedUser(t *testing.T) { Expect(code).Equals(http.StatusOK) } +func TestSignInPageHandler_GuardIdentity_RedirectsToGuardLogin(t *testing.T) { + RegisterT(t) + env.Config.GuardIdentity.Enabled = true + + server := mock.NewServer() + mock.DemoTenant.IsPrivate = true + + code, response := server. + OnTenant(mock.DemoTenant). + WithURL("http://demo.test.fider.io/signin?redirect=%2Fposts%2F1%3Fx%3D1"). + Execute(handlers.SignInPage()) + + Expect(code).Equals(http.StatusTemporaryRedirect) + Expect(response.Header().Get("Location")).Equals("/.well-known/bastion/login?return_to=%2Fposts%2F1%3Fx%3D1") +} + +func TestSignInPageHandler_GuardIdentity_ForeignRedirectReturnsHome(t *testing.T) { + RegisterT(t) + env.Config.GuardIdentity.Enabled = true + + server := mock.NewServer() + code, response := server. + OnTenant(mock.DemoTenant). + WithURL("http://demo.test.fider.io/signin?redirect=https%3A%2F%2Fevil.test%2F"). + Execute(handlers.SignInPage()) + + Expect(code).Equals(http.StatusTemporaryRedirect) + Expect(response.Header().Get("Location")).Equals("/.well-known/bastion/login?return_to=%2F") +} + +func TestSignOutHandler_GuardIdentity_RedirectsToGuardLogout(t *testing.T) { + RegisterT(t) + env.Config.GuardIdentity.Enabled = true + + server := mock.NewServer() + code, response := server. + OnTenant(mock.DemoTenant). + AsUser(mock.JonSnow). + WithURL("http://demo.test.fider.io/signout"). + Execute(handlers.SignOut()) + + Expect(code).Equals(http.StatusTemporaryRedirect) + Expect(response.Header().Get("Location")).Equals("/.well-known/bastion/logout") +} + func TestVerifySignInCodeHandler_InvalidCode(t *testing.T) { RegisterT(t) diff --git a/app/middlewares/guard.go b/app/middlewares/guard.go new file mode 100644 index 0000000000..896d036cc8 --- /dev/null +++ b/app/middlewares/guard.go @@ -0,0 +1,82 @@ +package middlewares + +import ( + "errors" + "net/http" + "strings" + "sync" + + "github.com/MetsaApp/platform-kit/edgeauth" + "github.com/getfider/fider/app/handlers" + "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/log" + "github.com/getfider/fider/app/pkg/web" +) + +// guardVerifier is the one edgeauth verifier for the process. It is rebuilt only when +// the configuration changes (tests point it at their own issuer), so its JWKS cache +// survives across requests. +var guardVerifier struct { + sync.Mutex + jwksURL, audiences string + verifier *edgeauth.Verifier +} + +// identityVerifier returns the verifier for env.Config.GuardIdentity. +func identityVerifier() (*edgeauth.Verifier, error) { + cfg := env.Config.GuardIdentity + jwksURL := cfg.JWKSURL + if jwksURL == "" { + jwksURL = edgeauth.DefaultJWKSURL + } + + guardVerifier.Lock() + defer guardVerifier.Unlock() + + if guardVerifier.verifier != nil && guardVerifier.jwksURL == jwksURL && guardVerifier.audiences == cfg.Audiences { + return guardVerifier.verifier, nil + } + + v, err := edgeauth.New(edgeauth.Config{JWKSURL: jwksURL, Audiences: strings.Split(cfg.Audiences, ",")}) + if err != nil { + return nil, err + } + guardVerifier.jwksURL, guardVerifier.audiences, guardVerifier.verifier = jwksURL, cfg.Audiences, v + return v, nil +} + +// guardIdentityUser signs in the user behind the request's guard identity. It returns a +// nil user for a request without one (anonymous), and a non-zero HTTP status when the +// request must be refused: 401 for an identity that does not verify, 503 when guard's +// keys cannot be fetched, 403 for an identity holding none of the allowed roles. +func guardIdentityUser(c *web.Context) (*entity.User, int, error) { + token := c.Request.GetHeader(edgeauth.Header) + if token == "" || c.Tenant() == nil { + return nil, 0, nil + } + + verifier, err := identityVerifier() + if err != nil { + return nil, 0, err + } + + id, err := verifier.Verify(c, token) + if err != nil { + log.Warnf(c, "Guard identity refused: @{Error}", dto.Props{"Error": err.Error()}) + if errors.Is(err, edgeauth.ErrUnavailable) { + return nil, http.StatusServiceUnavailable, nil + } + return nil, http.StatusUnauthorized, nil + } + + user, outcome, err := handlers.SignInGuardIdentity(c, id) + if err != nil { + return nil, 0, err + } + if outcome != handlers.ExternalSignInOK { + return nil, http.StatusForbidden, nil + } + return user, 0, nil +} diff --git a/app/middlewares/user.go b/app/middlewares/user.go index 1c2db33759..e322d9f47d 100644 --- a/app/middlewares/user.go +++ b/app/middlewares/user.go @@ -2,6 +2,7 @@ package middlewares import ( "fmt" + "net/http" "net/url" "strconv" "strings" @@ -14,6 +15,7 @@ import ( "github.com/getfider/fider/app/pkg/validate" "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" @@ -31,7 +33,26 @@ func User() web.MiddlewareFunc { ) cookie, err := c.Request.Cookie(web.CookieAuthName) - if err == nil { + if env.Config.GuardIdentity.Enabled { + // Guard owns sign in and the session: the identity it verified is the only + // way in, and a leftover auth cookie from before is dropped, never honoured. + if err == nil { + c.RemoveCookie(web.CookieAuthName) + } + var status int + user, status, err = guardIdentityUser(c) + if err != nil { + return err + } + switch status { + case http.StatusUnauthorized: + return c.Unauthorized() + case http.StatusForbidden: + return c.Forbidden() + case http.StatusServiceUnavailable: + return c.String(http.StatusServiceUnavailable, "identity keys unavailable") + } + } else if err == nil { token = cookie.Value } else { // The signup-transfer cookie is domain-wide, so it reaches every tenant @@ -86,7 +107,7 @@ func User() web.MiddlewareFunc { } return c.Redirect("/signin") } - } else if c.Request.IsAPI() { + } else if user == nil && c.Request.IsAPI() { authHeader := c.Request.GetHeader("Authorization") parts := strings.Split(authHeader, "Bearer") if len(parts) == 2 { diff --git a/app/middlewares/user_guard_test.go b/app/middlewares/user_guard_test.go new file mode 100644 index 0000000000..835203a33b --- /dev/null +++ b/app/middlewares/user_guard_test.go @@ -0,0 +1,371 @@ +package middlewares_test + +import ( + "context" + "net/http" + "testing" + + "github.com/MetsaApp/platform-kit/edgeauth" + "github.com/MetsaApp/platform-kit/edgeauth/edgeauthtest" + + "github.com/getfider/fider/app" + "github.com/getfider/fider/app/middlewares" + "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/assert" + "github.com/getfider/fider/app/pkg/bus" + "github.com/getfider/fider/app/pkg/env" + "github.com/getfider/fider/app/pkg/jwt" + "github.com/getfider/fider/app/pkg/mock" + "github.com/getfider/fider/app/pkg/web" +) + +const guardHost = "feedback.test" + +// The custom OAuth provider existing users were signed in through before guard. +const legacyProvider = "_c144tcijpa" + +// enableGuard turns the guard identity on against a fresh in-memory issuer. +func enableGuard(t *testing.T) *edgeauthtest.Issuer { + issuer := edgeauthtest.NewIssuer(t) + env.Config.GuardIdentity.Enabled = true + env.Config.GuardIdentity.JWKSURL = issuer.JWKSURL() + env.Config.GuardIdentity.Audiences = guardHost + env.Config.GuardIdentity.Provider = legacyProvider + env.Config.GuardIdentity.AdminRoles = "fider-admin" + env.Config.GuardIdentity.CollaboratorRoles = "" + env.Config.GuardIdentity.AllowedRoles = "fider-user" + return issuer +} + +func guardServer(issuer *edgeauthtest.Issuer, id edgeauth.Identity) *mock.Server { + server := mock.NewServer() + server.Use(middlewares.User()) + return server. + OnTenant(mock.DemoTenant). + AddHeader("Accept", "application/json"). + AddHeader(edgeauth.Header, issuer.Mint(id, guardHost)) +} + +func showUser(c *web.Context) error { + if !c.IsAuthenticated() { + return c.NoContent(http.StatusNoContent) + } + return c.String(http.StatusOK, c.User().Name) +} + +func notFoundByProvider() { + bus.AddHandler(func(ctx context.Context, q *query.GetUserByProvider) error { + return app.ErrNotFound + }) +} + +func TestUser_Guard_ExistingUserByProviderUID(t *testing.T) { + RegisterT(t) + issuer := enableGuard(t) + + server := guardServer(issuer, edgeauth.Identity{ + Subject: "zitadel-jon", Email: "someone.else@got.com", EmailVerified: true, Roles: []string{"fider-admin"}, + }) + mock.JonSnow.Providers = append(mock.JonSnow.Providers, &entity.UserProvider{UID: "zitadel-jon", Name: legacyProvider}) + bus.AddHandler(func(ctx context.Context, q *query.GetUserByProvider) error { + if q.Provider == legacyProvider && q.UID == "zitadel-jon" { + q.Result = mock.JonSnow + return nil + } + return app.ErrNotFound + }) + + status, response := server.Execute(showUser) + + Expect(status).Equals(http.StatusOK) + Expect(response.Body.String()).Equals("Jon Snow") + // No session of Fider's own: nothing is minted. + Expect(response.Header()["Set-Cookie"]).HasLen(0) +} + +func TestUser_Guard_ExistingUserByEmail_LinksProvider(t *testing.T) { + RegisterT(t) + issuer := enableGuard(t) + + notFoundByProvider() + bus.AddHandler(func(ctx context.Context, q *query.GetUserByEmail) error { + if q.Email == "arya.stark@got.com" { + q.Result = mock.AryaStark + return nil + } + return app.ErrNotFound + }) + var linked *cmd.RegisterUserProvider + bus.AddHandler(func(ctx context.Context, c *cmd.RegisterUserProvider) error { + linked = c + return nil + }) + + status, response := guardServer(issuer, edgeauth.Identity{ + Subject: "zitadel-arya", Email: "Arya.Stark@got.com", EmailVerified: true, Roles: []string{"fider-user"}, + }).Execute(showUser) + + Expect(status).Equals(http.StatusOK) + Expect(response.Body.String()).Equals("Arya Stark") + Expect(linked).IsNotNil() + Expect(linked.UserID).Equals(mock.AryaStark.ID) + Expect(linked.ProviderName).Equals(legacyProvider) + Expect(linked.ProviderUID).Equals("zitadel-arya") +} + +func TestUser_Guard_UnverifiedEmail_NeverLinksAccount(t *testing.T) { + RegisterT(t) + issuer := enableGuard(t) + + notFoundByProvider() + bus.AddHandler(func(ctx context.Context, q *query.GetUserByEmail) error { + panic("an unverified email must not be looked up") + }) + var registered *entity.User + bus.AddHandler(func(ctx context.Context, c *cmd.RegisterUser) error { + c.User.ID = 42 + registered = c.User + return nil + }) + + status, _ := guardServer(issuer, edgeauth.Identity{ + Subject: "zitadel-mallory", Email: "arya.stark@got.com", EmailVerified: false, Roles: []string{"fider-user"}, + }).Execute(showUser) + + Expect(status).Equals(http.StatusOK) + Expect(registered).IsNotNil() + Expect(registered.Email).Equals("") + Expect(registered.Name).Equals("Anonymous") +} + +func TestUser_Guard_NewUser_OnPrivateSite(t *testing.T) { + RegisterT(t) + issuer := enableGuard(t) + server := guardServer(issuer, edgeauth.Identity{ + Subject: "zitadel-sansa", Email: "sansa@got.com", EmailVerified: true, Name: "Sansa Stark", Roles: []string{"fider-user"}, + }) + mock.DemoTenant.IsPrivate = true + + notFoundByProvider() + bus.AddHandler(func(ctx context.Context, q *query.GetUserByEmail) error { + return app.ErrNotFound + }) + var registered *entity.User + bus.AddHandler(func(ctx context.Context, c *cmd.RegisterUser) error { + c.User.ID = 42 + registered = c.User + return nil + }) + + status, response := server.Execute(showUser) + + Expect(status).Equals(http.StatusOK) + Expect(response.Body.String()).Equals("Sansa Stark") + Expect(registered.Role).Equals(enum.RoleVisitor) + Expect(registered.Email).Equals("sansa@got.com") + Expect(registered.Tenant).Equals(mock.DemoTenant) + Expect(registered.Providers).HasLen(1) + Expect(registered.Providers[0].Name).Equals(legacyProvider) + Expect(registered.Providers[0].UID).Equals("zitadel-sansa") +} + +func TestUser_Guard_AdminRoleMapsToAdministrator(t *testing.T) { + RegisterT(t) + issuer := enableGuard(t) + + arya := *mock.AryaStark + arya.Providers = []*entity.UserProvider{{UID: "zitadel-arya", Name: legacyProvider}} + bus.AddHandler(func(ctx context.Context, q *query.GetUserByProvider) error { + q.Result = &arya + return nil + }) + var changed *cmd.ChangeUserRole + bus.AddHandler(func(ctx context.Context, c *cmd.ChangeUserRole) error { + changed = c + return nil + }) + bus.AddHandler(func(ctx context.Context, q *query.GetUserByID) error { + promoted := arya + promoted.Role = changed.Role + q.Result = &promoted + return nil + }) + + status, _ := guardServer(issuer, edgeauth.Identity{ + Subject: "zitadel-arya", Roles: []string{"fider-admin", "fider-user"}, + }).Execute(func(c *web.Context) error { + if c.User().IsAdministrator() { + return c.NoContent(http.StatusOK) + } + return c.NoContent(http.StatusTeapot) + }) + + Expect(status).Equals(http.StatusOK) + Expect(changed).IsNotNil() + Expect(changed.UserID).Equals(mock.AryaStark.ID) + Expect(changed.Role).Equals(enum.RoleAdministrator) +} + +func TestUser_Guard_LostAdminRoleIsDemoted_ButNeverTheLastAdmin(t *testing.T) { + for _, tc := range []struct { + admins int + demoted bool + expected enum.Role + }{ + {admins: 2, demoted: true, expected: enum.RoleVisitor}, + {admins: 1, demoted: false, expected: enum.RoleAdministrator}, + } { + RegisterT(t) + issuer := enableGuard(t) + + jon := *mock.JonSnow + jon.Providers = []*entity.UserProvider{{UID: "zitadel-jon", Name: legacyProvider}} + bus.AddHandler(func(ctx context.Context, q *query.GetUserByProvider) error { + q.Result = &jon + return nil + }) + bus.AddHandler(func(ctx context.Context, q *query.CountUsersByRole) error { + q.Result = tc.admins + return nil + }) + var changed *cmd.ChangeUserRole + bus.AddHandler(func(ctx context.Context, c *cmd.ChangeUserRole) error { + changed = c + return nil + }) + bus.AddHandler(func(ctx context.Context, q *query.GetUserByID) error { + demoted := jon + demoted.Role = changed.Role + q.Result = &demoted + return nil + }) + + var role enum.Role + status, _ := guardServer(issuer, edgeauth.Identity{ + Subject: "zitadel-jon", Roles: []string{"fider-user"}, + }).Execute(func(c *web.Context) error { + role = c.User().Role + return c.NoContent(http.StatusOK) + }) + + Expect(status).Equals(http.StatusOK) + Expect(changed != nil).Equals(tc.demoted) + Expect(role).Equals(tc.expected) + } +} + +func TestUser_Guard_MissingRole_Refused(t *testing.T) { + RegisterT(t) + issuer := enableGuard(t) + + notFoundByProvider() + bus.AddHandler(func(ctx context.Context, q *query.GetUserByEmail) error { + return app.ErrNotFound + }) + bus.AddHandler(func(ctx context.Context, c *cmd.RegisterUser) error { + panic("a user without an allowed role must not be created") + }) + + status, _ := guardServer(issuer, edgeauth.Identity{ + Subject: "zitadel-stranger", Email: "stranger@got.com", EmailVerified: true, Roles: []string{"some-other-role"}, + }).Execute(showUser) + + Expect(status).Equals(http.StatusForbidden) +} + +func TestUser_Guard_BlockedUser_Refused(t *testing.T) { + RegisterT(t) + issuer := enableGuard(t) + + arya := *mock.AryaStark + arya.Status = enum.UserBlocked + arya.Providers = []*entity.UserProvider{{UID: "zitadel-arya", Name: legacyProvider}} + bus.AddHandler(func(ctx context.Context, q *query.GetUserByProvider) error { + q.Result = &arya + return nil + }) + + status, _ := guardServer(issuer, edgeauth.Identity{ + Subject: "zitadel-arya", Roles: []string{"fider-user"}, + }).Execute(showUser) + + Expect(status).Equals(http.StatusUnauthorized) +} + +func TestUser_Guard_InvalidIdentity_Unauthorized(t *testing.T) { + RegisterT(t) + issuer := enableGuard(t) + other := edgeauthtest.NewIssuer(t) + + for _, token := range []string{ + "not-a-jwt", + // signed for another host + issuer.Mint(edgeauth.Identity{Subject: "zitadel-jon", Roles: []string{"fider-admin"}}, "evil.test"), + // signed by a key guard never published + other.Mint(edgeauth.Identity{Subject: "zitadel-jon", Roles: []string{"fider-admin"}}, guardHost), + } { + server := mock.NewServer() + server.Use(middlewares.User()) + status, _ := server. + OnTenant(mock.DemoTenant). + AddHeader("Accept", "application/json"). + AddHeader(edgeauth.Header, token). + Execute(showUser) + + Expect(status).Equals(http.StatusUnauthorized) + } +} + +func TestUser_Guard_KeysUnavailable_ServiceUnavailable(t *testing.T) { + RegisterT(t) + issuer := enableGuard(t) + env.Config.GuardIdentity.JWKSURL = "http://127.0.0.1:1/jwks.json" + + status, _ := guardServer(issuer, edgeauth.Identity{ + Subject: "zitadel-jon", Roles: []string{"fider-admin"}, + }).Execute(showUser) + + Expect(status).Equals(http.StatusServiceUnavailable) +} + +func TestUser_Guard_NoIdentity_IsAnonymous_AndAuthCookieIsIgnored(t *testing.T) { + RegisterT(t) + enableGuard(t) + + token, _ := jwt.Encode(jwt.FiderClaims{UserID: mock.JonSnow.ID, UserName: mock.JonSnow.Name}) + bus.AddHandler(func(ctx context.Context, q *query.GetUserByID) error { + q.Result = mock.JonSnow + return nil + }) + + server := mock.NewServer() + server.Use(middlewares.User()) + status, response := server. + OnTenant(mock.DemoTenant). + AddHeader("Accept", "application/json"). + AddCookie(web.CookieAuthName, token). + Execute(showUser) + + Expect(status).Equals(http.StatusNoContent) + // The leftover cookie is cleared. + Expect(response.Header()["Set-Cookie"]).HasLen(1) +} + +func TestUser_GuardDisabled_IdentityHeaderIgnored(t *testing.T) { + RegisterT(t) + issuer := enableGuard(t) + env.Config.GuardIdentity.Enabled = false + + bus.AddHandler(func(ctx context.Context, q *query.GetUserByProvider) error { + panic("the identity header must not be read when guard is off") + }) + + status, _ := guardServer(issuer, edgeauth.Identity{ + Subject: "zitadel-jon", Roles: []string{"fider-admin"}, + }).Execute(showUser) + + Expect(status).Equals(http.StatusNoContent) +} diff --git a/app/models/entity/oauth.go b/app/models/entity/oauth.go index 1baafcb3e4..1af4675656 100644 --- a/app/models/entity/oauth.go +++ b/app/models/entity/oauth.go @@ -1,10 +1,6 @@ package entity -import ( - "encoding/json" - - "github.com/getfider/fider/app/pkg/env" -) +import "encoding/json" // TenantProvider represents tenant-level OAuth provider settings type TenantProvider struct { @@ -45,42 +41,33 @@ func (o OAuthConfig) IsOIDC() bool { return o.IssuerURL != "" } -// IsClientSecretFromEnv returns true when OAUTH_CUSTOM_CLIENTID/OAUTH_CUSTOM_SECRET -// supply this provider's credentials, so they cannot be edited in the admin UI. -func (o OAuthConfig) IsClientSecretFromEnv() bool { - _, ok := env.CustomOAuthSecret(o.ClientID) - return ok -} - -// MarshalJSON returns the JSON encoding of OAuthConfig. -// The masked clientSecret always comes from the stored value, never from the environment. +// MarshalJSON returns the JSON encoding of OAuthConfig func (o OAuthConfig) MarshalJSON() ([]byte, error) { secret := "..." if len(o.ClientSecret) >= 10 { secret = o.ClientSecret[0:3] + "..." + o.ClientSecret[len(o.ClientSecret)-3:] } return json.Marshal(map[string]any{ - "id": o.ID, - "provider": o.Provider, - "displayName": o.DisplayName, - "logoBlobKey": o.LogoBlobKey, - "status": o.Status, - "clientID": o.ClientID, - "clientSecret": secret, - "clientSecretFromEnv": o.IsClientSecretFromEnv(), - "authorizeURL": o.AuthorizeURL, - "tokenURL": o.TokenURL, - "profileURL": o.ProfileURL, - "scope": o.Scope, - "isTrusted": o.IsTrusted, - "jsonUserIDPath": o.JSONUserIDPath, - "jsonUserNamePath": o.JSONUserNamePath, - "jsonUserEmailPath": o.JSONUserEmailPath, - "jsonUserRolesPath": o.JSONUserRolesPath, - "allowedRoles": o.AllowedRoles, - "issuerURL": o.IssuerURL, - "jwksURL": o.JWKSURL, - "adminRoles": o.AdminRoles, - "collaboratorRoles": o.CollaboratorRoles, + "id": o.ID, + "provider": o.Provider, + "displayName": o.DisplayName, + "logoBlobKey": o.LogoBlobKey, + "status": o.Status, + "clientID": o.ClientID, + "clientSecret": secret, + "authorizeURL": o.AuthorizeURL, + "tokenURL": o.TokenURL, + "profileURL": o.ProfileURL, + "scope": o.Scope, + "isTrusted": o.IsTrusted, + "jsonUserIDPath": o.JSONUserIDPath, + "jsonUserNamePath": o.JSONUserNamePath, + "jsonUserEmailPath": o.JSONUserEmailPath, + "jsonUserRolesPath": o.JSONUserRolesPath, + "allowedRoles": o.AllowedRoles, + "issuerURL": o.IssuerURL, + "jwksURL": o.JWKSURL, + "adminRoles": o.AdminRoles, + "collaboratorRoles": o.CollaboratorRoles, }) } diff --git a/app/models/entity/oauth_test.go b/app/models/entity/oauth_test.go deleted file mode 100644 index 67da022bd5..0000000000 --- a/app/models/entity/oauth_test.go +++ /dev/null @@ -1,43 +0,0 @@ -package entity_test - -import ( - "encoding/json" - "testing" - - "github.com/getfider/fider/app/models/entity" - . "github.com/getfider/fider/app/pkg/assert" - "github.com/getfider/fider/app/pkg/env" -) - -func TestOAuthConfig_MarshalJSON_ClientSecretFromEnv(t *testing.T) { - testCases := []struct { - name string - envID string - envSec string - expected bool - }{ - {"matching client id", "CU_CL_ID", "ENV_SECRET_VALUE", true}, - {"other client id", "OTHER_ID", "ENV_SECRET_VALUE", false}, - {"unset", "", "", false}, - } - - for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { - RegisterT(t) - original := env.Config.OAuth.Custom - env.Config.OAuth.Custom.ClientID = tc.envID - env.Config.OAuth.Custom.Secret = tc.envSec - t.Cleanup(func() { env.Config.OAuth.Custom = original }) - - config := entity.OAuthConfig{ClientID: "CU_CL_ID", ClientSecret: "STORED_SECRET_VALUE"} - bytes, err := json.Marshal(config) - Expect(err).IsNil() - - var out map[string]any - Expect(json.Unmarshal(bytes, &out)).IsNil() - Expect(out["clientSecretFromEnv"]).Equals(tc.expected) - // The masked secret always comes from the stored value. - Expect(out["clientSecret"]).Equals("STO...LUE") - }) - } -} diff --git a/app/pkg/bus/bus.go b/app/pkg/bus/bus.go index 3e9bf480e9..874ddbde55 100644 --- a/app/pkg/bus/bus.go +++ b/app/pkg/bus/bus.go @@ -172,7 +172,7 @@ func GetCallCount(msg Msg) int { func getKey(msg Msg) string { typeof := reflect.TypeOf(msg) - if typeof.Kind() != reflect.Ptr { + if typeof.Kind() != reflect.Pointer { panic(fmt.Errorf("'%s' is not a pointer", keyForElement(typeof))) } diff --git a/app/pkg/dbx/mapping.go b/app/pkg/dbx/mapping.go index 1b484b66b5..3c8aae8851 100644 --- a/app/pkg/dbx/mapping.go +++ b/app/pkg/dbx/mapping.go @@ -25,7 +25,7 @@ func NewRowMapper() *RowMapper { //Map values from scanner (usually sql.Rows.Scan) into dest based on columns func (m *RowMapper) Map(dest any, columns []string, scanner func(dest ...any) error) error { t := reflect.TypeOf(dest) - if t.Kind() == reflect.Ptr { + if t.Kind() == reflect.Pointer { t = t.Elem() } @@ -51,7 +51,7 @@ func (m *RowMapper) Map(dest any, columns []string, scanner func(dest ...any) er field := reflect.ValueOf(dest).Elem() for _, f := range mapping.FieldName { - if field.Kind() == reflect.Ptr { + if field.Kind() == reflect.Pointer { if field.IsNil() { field.Set(reflect.New(field.Type().Elem())) } @@ -104,7 +104,7 @@ func NewTypeMapper(t reflect.Type) TypeMapper { fieldType := field.Type fieldKind := fieldType.Kind() - if fieldKind == reflect.Ptr { + if fieldKind == reflect.Pointer { fieldType = field.Type.Elem() mapper := NewTypeMapper(fieldType) for _, f := range mapper.Fields { diff --git a/app/pkg/env/env.go b/app/pkg/env/env.go index 8be644378c..ce8fd1f33c 100644 --- a/app/pkg/env/env.go +++ b/app/pkg/env/env.go @@ -102,12 +102,25 @@ type config struct { ClientID string `env:"OAUTH_GITHUB_CLIENTID"` Secret string `env:"OAUTH_GITHUB_SECRET"` } - // Custom overrides the stored client secret of the custom OAuth provider - // whose client ID matches, so the secret can come from the environment. - Custom struct { - ClientID string `env:"OAUTH_CUSTOM_CLIENTID"` - Secret string `env:"OAUTH_CUSTOM_SECRET"` - } + } + // GuardIdentity signs users in from the identity guard (the edge proxy in front of + // Fider) verifies and hands upstream in the x-bastion-identity header, instead of + // from Fider's own auth cookie. Guard owns the login, the session and the logout. + GuardIdentity struct { + Enabled bool `env:"GUARD_IDENTITY_ENABLED,default=false"` + // JWKSURL is guard's key set; empty means edgeauth.DefaultJWKSURL (in-cluster guard). + JWKSURL string `env:"PLATFORM_KIT_EDGEAUTH_JWKS_URL"` + // Audiences are the hosts Fider is served on, comma separated. + Audiences string `env:"PLATFORM_KIT_EDGEAUTH_AUDIENCES"` + // Provider is the user_providers name the identity's subject is stored under. + // Set it to an existing custom OAuth provider's key to keep the users that + // provider signed in linked to their accounts. + Provider string `env:"GUARD_IDENTITY_PROVIDER,default=_guard"` + // The role mapping, applied on every request like a custom provider's + // (comma separated role keys from the identity's roles claim). + AdminRoles string `env:"GUARD_IDENTITY_ADMIN_ROLES,default=fider-admin"` + CollaboratorRoles string `env:"GUARD_IDENTITY_COLLABORATOR_ROLES"` + AllowedRoles string `env:"GUARD_IDENTITY_ALLOWED_ROLES,default=fider-user"` } Email struct { Type string `env:"EMAIL"` // possible values: smtp, mailgun, awsses @@ -186,6 +199,10 @@ func Reload() { } } + if Config.GuardIdentity.Enabled { + mustBeSet("PLATFORM_KIT_EDGEAUTH_AUDIENCES") + } + // Email Type can be inferred if absense if Config.Email.Type == "" { if Config.Email.Mailgun.APIKey != "" { @@ -226,16 +243,6 @@ func mustBeSet(name string) { } // IsSingleHostMode returns true if host mode is set to single tenant -// CustomOAuthSecret returns OAUTH_CUSTOM_SECRET when both OAUTH_CUSTOM_CLIENTID -// and OAUTH_CUSTOM_SECRET are set and clientID matches OAUTH_CUSTOM_CLIENTID. -func CustomOAuthSecret(clientID string) (string, bool) { - custom := Config.OAuth.Custom - if custom.ClientID == "" || custom.Secret == "" || clientID != custom.ClientID { - return "", false - } - return custom.Secret, true -} - func IsSingleHostMode() bool { return Config.HostMode == "single" } diff --git a/app/pkg/oidc/oidc_test.go b/app/pkg/oidc/oidc_test.go index 229f07d4b7..85c60d60e0 100644 --- a/app/pkg/oidc/oidc_test.go +++ b/app/pkg/oidc/oidc_test.go @@ -33,13 +33,18 @@ func rsaJWK(kid string, key *rsa.PublicKey) map[string]any { func ecJWK(kid string, key *ecdsa.PublicKey) map[string]any { byteLen := (key.Curve.Params().BitSize + 7) / 8 + // Uncompressed point: 0x04 || X || Y. + point, err := key.Bytes() + if err != nil { + panic(err) + } return map[string]any{ "kty": "EC", "kid": kid, "use": "sig", "crv": "P-256", - "x": base64.RawURLEncoding.EncodeToString(key.X.FillBytes(make([]byte, byteLen))), - "y": base64.RawURLEncoding.EncodeToString(key.Y.FillBytes(make([]byte, byteLen))), + "x": base64.RawURLEncoding.EncodeToString(point[1 : 1+byteLen]), + "y": base64.RawURLEncoding.EncodeToString(point[1+byteLen:]), } } diff --git a/app/pkg/web/renderer.go b/app/pkg/web/renderer.go index 57e934a660..2fad61547c 100644 --- a/app/pkg/web/renderer.go +++ b/app/pkg/web/renderer.go @@ -221,6 +221,7 @@ func (r *Renderer) Render(w io.Writer, statusCode int, props Props, ctx *Context "oauth": oauthProviders.Result, "postWithTags": env.Config.PostCreationWithTagsEnabled, "allowAllowedSchemes": env.Config.AllowAllowedSchemes, + "guardIdentity": env.Config.GuardIdentity.Enabled, } if ctx.IsAuthenticated() { diff --git a/app/pkg/web/testdata/basic.html b/app/pkg/web/testdata/basic.html index f556266812..8697d22893 100755 --- a/app/pkg/web/testdata/basic.html +++ b/app/pkg/web/testdata/basic.html @@ -45,7 +45,7 @@

Please enable JavaScript

diff --git a/app/pkg/web/testdata/canonical.html b/app/pkg/web/testdata/canonical.html index ea314bed7a..afae7ab856 100755 --- a/app/pkg/web/testdata/canonical.html +++ b/app/pkg/web/testdata/canonical.html @@ -47,7 +47,7 @@

Please enable JavaScript

diff --git a/app/pkg/web/testdata/chunk.html b/app/pkg/web/testdata/chunk.html index 11bfee86dc..732ab78eaf 100644 --- a/app/pkg/web/testdata/chunk.html +++ b/app/pkg/web/testdata/chunk.html @@ -45,7 +45,7 @@

Please enable JavaScript

diff --git a/app/pkg/web/testdata/home.html b/app/pkg/web/testdata/home.html index b103648be3..ac443a3fca 100755 --- a/app/pkg/web/testdata/home.html +++ b/app/pkg/web/testdata/home.html @@ -45,7 +45,7 @@

Please enable JavaScript

diff --git a/app/pkg/web/testdata/home_ssr.html b/app/pkg/web/testdata/home_ssr.html index a39ae8b69a..efef1d2d62 100755 --- a/app/pkg/web/testdata/home_ssr.html +++ b/app/pkg/web/testdata/home_ssr.html @@ -45,7 +45,7 @@

Please enable JavaScript

diff --git a/app/pkg/web/testdata/oauth.html b/app/pkg/web/testdata/oauth.html index 7a91aff91f..30b86fecc9 100755 --- a/app/pkg/web/testdata/oauth.html +++ b/app/pkg/web/testdata/oauth.html @@ -45,7 +45,7 @@

Please enable JavaScript

diff --git a/app/pkg/web/testdata/tenant.html b/app/pkg/web/testdata/tenant.html index a8aa1b5150..ad04d3410b 100755 --- a/app/pkg/web/testdata/tenant.html +++ b/app/pkg/web/testdata/tenant.html @@ -45,7 +45,7 @@

Please enable JavaScript

diff --git a/app/pkg/web/testdata/user.html b/app/pkg/web/testdata/user.html index 6b49456c36..3b367d87c9 100755 --- a/app/pkg/web/testdata/user.html +++ b/app/pkg/web/testdata/user.html @@ -45,7 +45,7 @@

Please enable JavaScript

diff --git a/app/services/oauth/env_secret_test.go b/app/services/oauth/env_secret_test.go deleted file mode 100644 index a4c76e656f..0000000000 --- a/app/services/oauth/env_secret_test.go +++ /dev/null @@ -1,69 +0,0 @@ -package oauth_test - -import ( - "context" - "net/http" - "net/http/httptest" - "testing" - - "github.com/getfider/fider/app/models/entity" - "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/services/oauth" -) - -// TestGetOAuthRawProfile_CustomSecretFromEnv checks which client secret the -// code exchange sends for a custom provider under OAUTH_CUSTOM_CLIENTID/SECRET. -func TestGetOAuthRawProfile_CustomSecretFromEnv(t *testing.T) { - testCases := []struct { - name string - envID string - envSecret string - wantSecret string - }{ - {"matching client id uses env secret", "CU_CL_ID", "ENV_SECRET", "ENV_SECRET"}, - {"other client id keeps stored secret", "OTHER_ID", "ENV_SECRET", "CU_SECRET"}, - {"unset keeps stored secret", "", "", "CU_SECRET"}, - {"id without secret keeps stored secret", "CU_CL_ID", "", "CU_SECRET"}, - } - - for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { - RegisterT(t) - bus.Init(&oauth.Service{}) - allowPrivateTargets(t) - - original := env.Config.OAuth.Custom - env.Config.OAuth.Custom.ClientID = tc.envID - env.Config.OAuth.Custom.Secret = tc.envSecret - t.Cleanup(func() { env.Config.OAuth.Custom = original }) - - var gotSecret string - tokenServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - _, gotSecret, _ = r.BasicAuth() - w.Header().Set("Content-Type", "application/json") - _, _ = w.Write([]byte(`{"access_token":"a.e30.c","token_type":"Bearer"}`)) - })) - defer tokenServer.Close() - - stored := &entity.OAuthConfig{ - Provider: "_custom", - ClientID: "CU_CL_ID", - ClientSecret: "CU_SECRET", - TokenURL: tokenServer.URL, - } - bus.AddHandler(func(ctx context.Context, q *query.GetCustomOAuthConfigByProvider) error { - q.Result = stored - return nil - }) - - ctx := newGetContext("http://login.test.fider.io:3000") - err := bus.Dispatch(ctx, &query.GetOAuthRawProfile{Provider: "_custom", Code: "the-code"}) - Expect(err).IsNil() - Expect(gotSecret).Equals(tc.wantSecret) - Expect(stored.ClientSecret).Equals("CU_SECRET") - }) - } -} diff --git a/app/services/oauth/oauth.go b/app/services/oauth/oauth.go index 61cdeb6c1b..7abcb9c1c5 100644 --- a/app/services/oauth/oauth.go +++ b/app/services/oauth/oauth.go @@ -490,21 +490,5 @@ func getConfig(ctx context.Context, provider string) (*entity.OAuthConfig, error return nil, err } - return withEnvSecret(getCustomOAuth.Result), nil -} - -// withEnvSecret swaps in OAUTH_CUSTOM_SECRET when the custom provider's client ID -// matches OAUTH_CUSTOM_CLIENTID. Only the sign-in flow reads through here, so the -// env secret is never shown in the admin UI nor saved to the database. -func withEnvSecret(config *entity.OAuthConfig) *entity.OAuthConfig { - if config == nil { - return nil - } - secret, ok := env.CustomOAuthSecret(config.ClientID) - if !ok { - return config - } - overridden := *config - overridden.ClientSecret = secret - return &overridden + return getCustomOAuth.Result, nil } diff --git a/docs/GUARD_IDENTITY.md b/docs/GUARD_IDENTITY.md new file mode 100644 index 0000000000..8beac66e54 --- /dev/null +++ b/docs/GUARD_IDENTITY.md @@ -0,0 +1,42 @@ +# Sign in through guard (fork only) + +This fork can run behind guard, metsa's edge proxy, and take the signed-in user from the +identity guard verifies instead of running a sign in of its own. Guard is the OIDC client +(Zitadel stays the identity provider), owns the session, and hands every request upstream +with a short-lived signed identity JWT in the `x-bastion-identity` header. Fider verifies +that JWT with the shared verifier (`github.com/MetsaApp/platform-kit/edgeauth`) against +guard's JWKS and never trusts a plain header. + +## Turning it on + +| Variable | Default | Meaning | +|---|---|---| +| `GUARD_IDENTITY_ENABLED` | `false` | Sign users in from guard's identity only. | +| `PLATFORM_KIT_EDGEAUTH_AUDIENCES` | (required when enabled) | The hosts Fider is served on, comma separated (`feedback.metsa.app`). | +| `PLATFORM_KIT_EDGEAUTH_JWKS_URL` | guard's in-cluster JWKS | Where guard's public keys are. | +| `GUARD_IDENTITY_PROVIDER` | `_guard` | The `user_providers` name the identity's subject is stored under. Set it to the key of the custom OAuth provider users signed in through before, so they keep their accounts. | +| `GUARD_IDENTITY_ADMIN_ROLES` | `fider-admin` | Roles mapped to Fider administrator. | +| `GUARD_IDENTITY_COLLABORATOR_ROLES` | (none) | Roles mapped to Fider collaborator. | +| `GUARD_IDENTITY_ALLOWED_ROLES` | `fider-user` | Roles that sign in as a visitor. | + +## What happens on a request + +`middlewares.User()` verifies the header and signs the user in with the same rules a +custom OAuth provider's callback applies (`handlers.SignInExternalUser`, shared by both): + +* The user is found by provider and subject, then by email (only a verified email), or + created. Guard is trusted to create users on a private site: its own rule has already + refused anyone without a role. +* The roles map onto Fider's role on every request, promoting and demoting, except that + the last administrator is never demoted. +* An identity holding none of the allowed or mapped roles gets 403, an identity that does + not verify 401, and 503 when guard's keys cannot be fetched. Blocked users get 401. +* No request header means anonymous. Fider's own `auth` cookie is ignored and cleared, and + no cookie is minted: identity is per request, so guard's logout or a revoked session + takes effect on the next request. + +`/signin` redirects to `/.well-known/bastion/login?return_to=…`, `/signout` to +`/.well-known/bastion/logout`, and the sign-in control and the user menu link there +directly (`settings.guardIdentity`). API keys keep working where guard lets the request +through. The OAuth provider code stays compiled; with guard on, a provider sign in can +no longer produce a session, so the provider can be disabled. diff --git a/go.mod b/go.mod index 8734260946..4a2b7509c4 100644 --- a/go.mod +++ b/go.mod @@ -1,10 +1,11 @@ -// +heroku goVersion go1.25 +// +heroku goVersion go1.26 module github.com/getfider/fider -go 1.25.0 +go 1.26.0 require ( + github.com/MetsaApp/platform-kit v0.2.1-0.20261030231032-338c1157e883 github.com/aws/aws-sdk-go v1.41.14 github.com/cosmtrek/air v1.27.3 github.com/goenning/imagic v0.0.1 @@ -25,8 +26,8 @@ require ( github.com/prometheus/client_model v0.6.2 github.com/robfig/cron v1.2.0 github.com/stripe/stripe-go/v83 v83.2.1 - golang.org/x/crypto v0.54.0 - golang.org/x/net v0.57.0 + golang.org/x/crypto v0.57.0 + golang.org/x/net v0.58.0 golang.org/x/oauth2 v0.36.0 rogchap.com/v8go v0.9.0 ) @@ -71,6 +72,7 @@ require ( github.com/breml/errchkjson v0.4.1 // indirect github.com/butuzov/ireturn v0.4.1 // indirect github.com/butuzov/mirror v1.3.0 // indirect + github.com/caarlos0/env/v11 v11.4.1 // indirect github.com/catenacyber/perfsprint v0.10.1 // indirect github.com/ccojocar/zxcvbn-go v1.0.4 // indirect github.com/cespare/xxhash/v2 v2.3.0 // indirect @@ -100,6 +102,7 @@ require ( github.com/fzipp/gocyclo v0.6.0 // indirect github.com/ghostiam/protogetter v0.3.20 // indirect github.com/go-critic/go-critic v0.14.3 // indirect + github.com/go-jose/go-jose/v4 v4.1.7 // indirect github.com/go-toolsmith/astcast v1.1.0 // indirect github.com/go-toolsmith/astcopy v1.1.0 // indirect github.com/go-toolsmith/astequal v1.2.0 // indirect @@ -240,11 +243,11 @@ require ( golang.org/x/exp v0.0.0-20250620022241-b7579e27df2b // indirect golang.org/x/exp/typeparams v0.0.0-20260209203927-2842357ff358 // indirect golang.org/x/image v0.41.0 // indirect - golang.org/x/mod v0.37.0 // indirect - golang.org/x/sync v0.22.0 // indirect - golang.org/x/sys v0.47.0 // indirect - golang.org/x/text v0.40.0 // indirect - golang.org/x/tools v0.47.0 // indirect + golang.org/x/mod v0.41.0 // indirect + golang.org/x/sync v0.23.0 // indirect + golang.org/x/sys v0.48.0 // indirect + golang.org/x/text v0.42.0 // indirect + golang.org/x/tools v0.49.0 // indirect google.golang.org/protobuf v1.36.11 // indirect gopkg.in/ini.v1 v1.67.0 // indirect gopkg.in/yaml.v2 v2.4.0 // indirect diff --git a/go.sum b/go.sum index 57f5491335..cacb7a9c90 100644 --- a/go.sum +++ b/go.sum @@ -34,6 +34,8 @@ github.com/Djarvur/go-err113 v0.1.1 h1:eHfopDqXRwAi+YmCUas75ZE0+hoBHJ2GQNLYRSxao github.com/Djarvur/go-err113 v0.1.1/go.mod h1:IaWJdYFLg76t2ihfflPZnM1LIQszWOsFDh2hhhAVF6k= github.com/Masterminds/semver/v3 v3.5.0 h1:kQceYJfbupGfZOKZQg0kou0DgAKhzDg2NZPAwZ/2OOE= github.com/Masterminds/semver/v3 v3.5.0/go.mod h1:4V+yj/TJE1HU9XfppCwVMZq3I84lprf4nC11bSS5beM= +github.com/MetsaApp/platform-kit v0.2.1-0.20261030231032-338c1157e883 h1:RhyhMdyY4GdC7qN+q0/I+CMuG3SbInj8c2aAis+gNkE= +github.com/MetsaApp/platform-kit v0.2.1-0.20261030231032-338c1157e883/go.mod h1:Twj9dD8xF6CVGLRvVeVBXx/qv3JoGY0pmxsQUub4ctk= github.com/MirrexOne/unqueryvet v1.5.4 h1:38QOxShO7JmMWT+eCdDMbcUgGCOeJphVkzzRgyLJgsQ= github.com/MirrexOne/unqueryvet v1.5.4/go.mod h1:fs9Zq6eh1LRIhsDIsxf9PONVUjYdFHdtkHIgZdJnyPU= github.com/OpenPeeDeeP/depguard/v2 v2.2.1 h1:vckeWVESWp6Qog7UZSARNqfu/cZqvki8zsuj3piCMx4= @@ -82,6 +84,8 @@ github.com/butuzov/ireturn v0.4.1 h1:vWb3NO4t77iku/sjCQ/2pHTQeOmxEhjIriJqRLg1Y+I github.com/butuzov/ireturn v0.4.1/go.mod h1:q+DXKzTDV5guNuXLnIab9fKXizTn2miZHLhxH7V/GB4= github.com/butuzov/mirror v1.3.0 h1:HdWCXzmwlQHdVhwvsfBb2Au0r3HyINry3bDWLYXiKoc= github.com/butuzov/mirror v1.3.0/go.mod h1:AEij0Z8YMALaq4yQj9CPPVYOyJQyiexpQEQgihajRfI= +github.com/caarlos0/env/v11 v11.4.1 h1:fYwH0sWEsBSMPG7t4e/PEfTFzrWrpjyygXyUnWiSwEw= +github.com/caarlos0/env/v11 v11.4.1/go.mod h1:qupehSf/Y0TUTsxKywqRt/vJjN5nz6vauiYEUUr8P4U= github.com/catenacyber/perfsprint v0.10.1 h1:u7Riei30bk46XsG8nknMhKLXG9BcXz3+3tl/WpKm0PQ= github.com/catenacyber/perfsprint v0.10.1/go.mod h1:DJTGsi/Zufpuus6XPGJyKOTMELe347o6akPvWG9Zcsc= github.com/ccojocar/zxcvbn-go v1.0.4 h1:FWnCIRMXPj43ukfX000kvBZvV6raSxakYr1nzyNrUcc= @@ -152,6 +156,8 @@ github.com/ghostiam/protogetter v0.3.20 h1:oW7OPFit2FxZOpmMRPP9FffU4uUpfeE/rEdE1 github.com/ghostiam/protogetter v0.3.20/go.mod h1:FjIu5Yfs6FT391m+Fjp3fbAYJ6rkL/J6ySpZBfnODuI= github.com/go-critic/go-critic v0.14.3 h1:5R1qH2iFeo4I/RJU8vTezdqs08Egi4u5p6vOESA0pog= github.com/go-critic/go-critic v0.14.3/go.mod h1:xwntfW6SYAd7h1OqDzmN6hBX/JxsEKl5up/Y2bsxgVQ= +github.com/go-jose/go-jose/v4 v4.1.7 h1:Nac/98uT5LPkfbiFuYa8ktf62a2VxwQ4xbq1GK8pV5E= +github.com/go-jose/go-jose/v4 v4.1.7/go.mod h1:x4oUasVrzR7071A4TnHLGSPpNOm2a21K9Kf04k1rs08= github.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI= github.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= github.com/go-quicktest/qt v1.101.0 h1:O1K29Txy5P2OK0dGo59b7b0LR6wKfIhttaAhHUyn7eI= @@ -291,8 +297,8 @@ github.com/kisielk/errcheck v1.10.0 h1:Lvs/YAHP24YKg08LA8oDw2z9fJVme090RAXd90S+r github.com/kisielk/errcheck v1.10.0/go.mod h1:kQxWMMVZgIkDq7U8xtG/n2juOjbLgZtedi0D+/VL/i8= github.com/kkHAIKE/contextcheck v1.1.6 h1:7HIyRcnyzxL9Lz06NGhiKvenXq7Zw6Q0UQu/ttjfJCE= github.com/kkHAIKE/contextcheck v1.1.6/go.mod h1:3dDbMRNBFaq8HFXWC1JyvDSPm43CmE6IuHam8Wr0rkg= -github.com/klauspost/compress v1.19.1 h1:VsB4HPswih7mmZ8WleSFQ75c/Ui1M4trX5oAsJnhSlk= -github.com/klauspost/compress v1.19.1/go.mod h1:cwPg85FWrGar70rWktvGQj8/hthj3wpl0PGDogxkrSQ= +github.com/klauspost/compress v1.20.1 h1:T7kKElXUMXrUJ2E9QhQhxFtcK5rPyLdsGZvdbLMPdiQ= +github.com/klauspost/compress v1.20.1/go.mod h1:LUdAzn7YLVvxLpc7y3V1m40wESHTgc1422pwwBSKYuI= github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= @@ -540,8 +546,8 @@ golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACk golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= -golang.org/x/crypto v0.54.0 h1:YLIA59K4fiNzHzjnZt2tUJQjQtUWfWbeHBqKtk3eScw= -golang.org/x/crypto v0.54.0/go.mod h1:KWL8ny2AZdGR2cWmzeHrp2azQPGogOv+HeQaVEXC2dk= +golang.org/x/crypto v0.57.0 h1:3ZVCjf8Ggz7zneR/EHRVx68Ctf+2pmIMP2UFhh9cC6M= +golang.org/x/crypto v0.57.0/go.mod h1:Fdz0i5U6CoizGwLda9DttjSk6qlZo25zYNtR+ycvuZA= golang.org/x/exp v0.0.0-20250620022241-b7579e27df2b h1:M2rDM6z3Fhozi9O7NWsxAkg/yqS/lQJ6PmkyIV3YP+o= golang.org/x/exp v0.0.0-20250620022241-b7579e27df2b/go.mod h1:3//PLf8L/X+8b4vuAfHzxeRUl04Adcb341+IGKfnqS8= golang.org/x/exp/typeparams v0.0.0-20220428152302-39d4317da171/go.mod h1:AbB0pIl9nAr9wVwH+Z2ZpaocVmF5I4GyWCDIsVjR0bk= @@ -559,8 +565,8 @@ golang.org/x/mod v0.4.1/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.6.0-dev.0.20220106191415-9b9b3d81d5e3/go.mod h1:3p9vT2HGsQu2K1YbXdKPJLVgG5VJdoTa1poYQBtP1AY= golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= -golang.org/x/mod v0.37.0 h1:vF1DjpVEshcIqoEaauuHebaLk1O1forxjxBaVn884JQ= -golang.org/x/mod v0.37.0/go.mod h1:m8S8VeM9r4dzDwjrKO0a1sZP3YjeMamRRlD+fmR2Q/0= +golang.org/x/mod v0.41.0 h1:qJmnOUb4YB+FsEuM3HcWucdZASCPGhsX6uljO6pog0c= +golang.org/x/mod v0.41.0/go.mod h1:Ek9pY8RKWXwsWvd3rQiHYtMqkjSUV+s1Rj7j4H5Ur6o= golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20200226121028-0de0cce0169b/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= @@ -571,8 +577,8 @@ golang.org/x/net v0.0.0-20210614182718-04defd469f4e/go.mod h1:9nx3DQGgdP8bBQD5qx golang.org/x/net v0.0.0-20211015210444-4f30a5c0130f/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs= -golang.org/x/net v0.57.0 h1:K5+3DljvIuDG9/Jv9rvyMywYNFCQ9RSUY6OOTTkT+tE= -golang.org/x/net v0.57.0/go.mod h1:KpXc8iv+r3XplLAG/f7Jsf9RPszJzdR0f58q9vGOuEU= +golang.org/x/net v0.58.0 h1:ynWG7rqYi4ccpTEuPZ2QGWHktVEM9DMCj9yzDE0Q7To= +golang.org/x/net v0.58.0/go.mod h1:YwCddHnFlT7eLQqVprV19OnhLGtc5xOKgE0RyqgfWAU= golang.org/x/oauth2 v0.36.0 h1:peZ/1z27fi9hUOFCAZaHyrpWG5lwe0RJEEEeH0ThlIs= golang.org/x/oauth2 v0.36.0/go.mod h1:YDBUJMTkDnJS+A4BP4eZBjCqtokkg1hODuPjwiGPO7Q= golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= @@ -582,8 +588,8 @@ golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJ golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.22.0 h1:SZjpbeLmrCk4xhRSZFNZW5gFUeCeFgjekvI/+gfScek= -golang.org/x/sync v0.22.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0= +golang.org/x/sync v0.23.0 h1:KameEIfc1IkluZyXWLn39Wd4tURc6GbCiISGiZm2bQk= +golang.org/x/sync v0.23.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20191005200804-aed5e4c7ecf9/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= @@ -602,8 +608,8 @@ golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBc golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.47.0 h1:o7XGOvZQCADBQQ4Y7VNq2dRWQR7JmOUW8Kxx4ZsNgWs= -golang.org/x/sys v0.47.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw= +golang.org/x/sys v0.48.0 h1:bbX/i/6MgT9BVLM9RT1thmxL04yeTAhbEz4SyadbXoo= +golang.org/x/sys v0.48.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k= @@ -613,8 +619,8 @@ golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= -golang.org/x/text v0.40.0 h1:Ub2Z6/xjgF1WrYQz2nuITOEegKFtiIy+rieRJ5lHZKs= -golang.org/x/text v0.40.0/go.mod h1:hpnzDAfGV753zIKo+wk3u1bVKCGPbrnF7+7LBF/UHVY= +golang.org/x/text v0.42.0 h1:JbOZXgfeCPU9gacVtYliJqOhD+zhrEqK4LfdpmlUZqI= +golang.org/x/text v0.42.0/go.mod h1:ojzP1Z+2QtioaF8DTtO8K5q7JWVVYwZKenzujK0Zd0E= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.0.0-20200329025819-fd4102a86c65/go.mod h1:Sl4aGygMT6LrqrWclx+PTx3U+LnKx/seiNR+3G19Ar8= @@ -624,8 +630,8 @@ golang.org/x/tools v0.1.1-0.20210302220138-2ac05c832e1a/go.mod h1:9bzcO0MWcOuT0t golang.org/x/tools v0.1.10/go.mod h1:Uh6Zz+xoGYZom868N8YTex3t7RhtHDBrE8Gzo9bV56E= golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU= -golang.org/x/tools v0.47.0 h1:7Kn5x/d1svx/PzryTsqeoZN4TZwqeH5pGWjefhLi/1Q= -golang.org/x/tools v0.47.0/go.mod h1:dFHnyTvFWY212G+h7ZY4Vsp/K3U4/7W9TyVaAul8uCA= +golang.org/x/tools v0.49.0 h1:3NI7VXzL9+1WZD52Dx2ttoPwD5DWrFGpl9mFZDlmisI= +golang.org/x/tools v0.49.0/go.mod h1:SJNXV9DBKT0UbdttsQjbfJlAE/q+y36++zo3uL3N0Oo= golang.org/x/tools/go/expect v0.1.1-deprecated h1:jpBZDwmgPhXsKZC6WhL20P4b/wmnpsEAGHaNy0n/rJM= golang.org/x/tools/go/expect v0.1.1-deprecated/go.mod h1:eihoPOH+FgIqa3FpoTwguz/bVUSGBlGQU67vpBeOrBY= golang.org/x/tools/go/packages/packagestest v0.1.1-deprecated h1:1h2MnaIAIXISqTFKdENegdpAgUXz6NrPEsbIeWaBRvM= diff --git a/public/components/UserMenu.tsx b/public/components/UserMenu.tsx index bd03ac70ed..d7c677f210 100644 --- a/public/components/UserMenu.tsx +++ b/public/components/UserMenu.tsx @@ -29,7 +29,7 @@ export const UserMenu = () => { )} - + Sign out diff --git a/public/components/common/SignInControl.tsx b/public/components/common/SignInControl.tsx index 96fe22026f..0507f6af88 100644 --- a/public/components/common/SignInControl.tsx +++ b/public/components/common/SignInControl.tsx @@ -171,6 +171,18 @@ export const SignInControl: React.FunctionComponent = (props } } + // Behind guard, sign in is guard's: one button to its login, which returns here. + if (fider.settings.guardIdentity) { + const returnTo = props.redirectTo || (typeof location !== "undefined" ? location.pathname + location.search : "/") + return ( +
+ +
+ ) + } + if (!isCookieEnabled()) { return ( diff --git a/public/models/settings.ts b/public/models/settings.ts index e34ee3d077..61bb32a89e 100644 --- a/public/models/settings.ts +++ b/public/models/settings.ts @@ -22,6 +22,7 @@ export interface SystemSettings { oauth: OAuthProviderOption[] postWithTags: boolean allowAllowedSchemes: boolean + guardIdentity: boolean } export interface UserSettings { @@ -39,7 +40,6 @@ export interface OAuthConfig { status: number clientID: string clientSecret: string - clientSecretFromEnv: boolean authorizeURL: string tokenURL: string profileURL: string diff --git a/public/pages/Administration/components/OAuthForm.tsx b/public/pages/Administration/components/OAuthForm.tsx index c2ea9b7d6d..f7c7e371df 100644 --- a/public/pages/Administration/components/OAuthForm.tsx +++ b/public/pages/Administration/components/OAuthForm.tsx @@ -36,7 +36,6 @@ export const OAuthForm: React.FC = (props) => { const [logoURL, setLogoURL] = useState() const [logoBlobKey, setLogoBlobKey] = useState((props.config && props.config.logoBlobKey) || "") const [error, setError] = useState() - const credentialsFromEnv = (props.config && props.config.clientSecretFromEnv) || false const handleSave = async () => { const result = await actions.saveOAuthConfig({ @@ -108,14 +107,7 @@ export const OAuthForm: React.FC = (props) => {

- + = (props) => { disabled={!clientSecretEnabled} onChange={setClientSecret} afterLabel={ - credentialsFromEnv ? undefined : !clientSecretEnabled ? ( + !clientSecretEnabled ? ( <> omitted for security reasons. @@ -134,9 +126,7 @@ export const OAuthForm: React.FC = (props) => { ) : undefined } - > - {credentialsFromEnv &&

Managed by environment (OAUTH_CUSTOM_CLIENTID / OAUTH_CUSTOM_SECRET).

} - + />