Skip to content

armgit / fider

Public Imported from GitHub
0

Open platform to collect and prioritize feedback

Bind OAuth sign-in to the tenant's canonical origin

Matt Roberts883d15dd9462
diff --git a/app/handlers/oauth.go b/app/handlers/oauth.go
index 24a97dcf2..5aeceacae 100644
--- a/app/handlers/oauth.go
+++ b/app/handlers/oauth.go
@@ -2,9 +2,13 @@ package handlers
import (
"context"
+ "crypto/sha256"
+ "crypto/subtle"
+ "encoding/hex"
"fmt"
"net/http"
"net/url"
+ "slices"
"strings"
"time"
@@ -17,6 +21,7 @@ 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"
@@ -24,6 +29,130 @@ import (
webutil "github.com/getfider/fider/app/pkg/web/util"
)
+// handoffLifetime is how long the token that carries an OAuth sign in from the callback
+// address over to the tenant address stays valid. It only has to survive one redirect.
+const handoffLifetime = 2 * time.Minute
+
+// tenantOrigins returns every origin a given tenant is served on.
+// A tenant with a custom domain is still reachable on its subdomain, so both are valid.
+func tenantOrigins(ctx context.Context, tenant *entity.Tenant) []string {
+ origins := []string{web.TenantBaseURL(ctx, tenant)}
+
+ if tenant.CNAME != "" && !env.IsSingleHostMode() {
+ origins = append(origins, web.TenantBaseURL(ctx, &entity.Tenant{Subdomain: tenant.Subdomain}))
+ }
+
+ return origins
+}
+
+// oauthAllowedOrigins returns the origins an OAuth flow is allowed to continue on for the
+// current request. These come from the resolved tenant record and from configuration, never
+// from the request's Host/X-Forwarded-Host header, which any caller can set to anything.
+func oauthAllowedOrigins(c *web.Context) []string {
+ if c.Tenant() == nil {
+ // Sign up runs on the host-wide OAuth address, before a tenant exists.
+ return []string{web.OAuthBaseURL(c)}
+ }
+
+ return tenantOrigins(c, c.Tenant())
+}
+
+// isAllowedOAuthRedirect reports whether redirect points at one of the given origins.
+func isAllowedOAuthRedirect(origins []string, redirect string) bool {
+ for _, origin := range origins {
+ if redirect == origin || strings.HasPrefix(redirect, origin+"/") {
+ return true
+ }
+ }
+ return false
+}
+
+// isKnownOAuthOrigin reports whether a URL points at an origin Fider actually serves.
+// OAuth state is signed with a process-wide secret, so a valid signature on its own says
+// nothing about whether the redirect it carries was ever legitimate — it has to be checked
+// against the tenant records again.
+func isKnownOAuthOrigin(c *web.Context, u *url.URL) bool {
+ origin := u.Scheme + "://" + u.Host
+
+ if origin == web.OAuthBaseURL(c) {
+ return true
+ }
+
+ byDomain := &query.GetTenantByDomain{Domain: u.Hostname()}
+ if err := bus.Dispatch(c, byDomain); err != nil || byDomain.Result == nil || byDomain.Result.IsDisabled() {
+ return false
+ }
+
+ return slices.Contains(tenantOrigins(c, byDomain.Result), origin)
+}
+
+// newOAuthHandoff mints the token that carries an OAuth sign in from the callback address
+// over to the tenant address, bound to that origin, provider and browser session.
+func newOAuthHandoff(provider, origin, sessionID string) (string, error) {
+ return jwt.Encode(jwt.OAuthHandoffClaims{
+ Provider: provider,
+ Origin: origin,
+ SessionIDHash: hashSessionID(sessionID),
+ Metadata: jwt.Metadata{
+ ExpiresAt: jwt.Time(time.Now().Add(handoffLifetime)),
+ },
+ })
+}
+
+// isValidOAuthHandoff checks that a handoff token belongs to this exact request: same
+// provider, same origin, same browser session, and not yet expired.
+func isValidOAuthHandoff(c *web.Context, provider, handoff string) bool {
+ if handoff == "" || c.SessionID() == "" {
+ return false
+ }
+
+ claims, err := jwt.DecodeOAuthHandoffClaims(handoff)
+ if err != nil {
+ return false
+ }
+
+ if claims.Provider != provider || !isAllowedOAuthRedirect(oauthAllowedOrigins(c), claims.Origin) {
+ return false
+ }
+
+ expected := hashSessionID(c.SessionID())
+ return subtle.ConstantTimeCompare([]byte(claims.SessionIDHash), []byte(expected)) == 1
+}
+
+// hashSessionID hashes a session ID so the handoff token can be bound to a browser session
+// without the session ID itself travelling through URLs, logs and referrers.
+func hashSessionID(sessionID string) string {
+ sum := sha256.Sum256([]byte(sessionID))
+ return hex.EncodeToString(sum[:])
+}
+
+// sanitiseOAuthRedirect reduces a caller supplied redirect to a path on the current tenant.
+// Anything pointing elsewhere falls back to the root, so this endpoint can never be used
+// as an open redirect.
+func sanitiseOAuthRedirect(c *web.Context, redirect string) string {
+ u, err := url.Parse(redirect)
+ if err != nil || redirect == "" {
+ return "/"
+ }
+
+ // Protocol relative URLs ("//evil.com") parse with an empty scheme, so check the host
+ // rather than relying on IsAbs.
+ if u.Host != "" && !isAllowedOAuthRedirect(oauthAllowedOrigins(c), u.Scheme+"://"+u.Host) {
+ return "/"
+ }
+
+ path := u.EscapedPath()
+ if !strings.HasPrefix(path, "/") {
+ return "/"
+ }
+
+ if u.RawQuery != "" {
+ path += "?" + u.RawQuery
+ }
+
+ return path
+}
+
// OAuthEcho exchanges OAuth Code for a user profile and return directly to the UI, without storing it
func OAuthEcho() web.HandlerFunc {
return func(c *web.Context) error {
@@ -34,9 +163,8 @@ func OAuthEcho() web.HandlerFunc {
return c.Redirect("/")
}
- identifier := c.QueryParam("identifier")
- if identifier == "" || identifier != c.SessionID() {
- log.Warn(c, "OAuth identifier doesn't match with user session ID. Aborting sign in process.")
+ if !isValidOAuthHandoff(c, provider, c.QueryParam("handoff")) {
+ log.Warn(c, "OAuth handoff token is not valid for this request. Aborting sign in process.")
return c.Redirect("/")
}
@@ -82,18 +210,16 @@ func OAuthEcho() web.HandlerFunc {
func OAuthToken() web.HandlerFunc {
return func(c *web.Context) error {
provider := c.Param("provider")
- redirectURL, _ := url.ParseRequestURI(c.QueryParam("redirect"))
- redirectURL.ResolveReference(c.Request.URL)
+ redirect := sanitiseOAuthRedirect(c, c.QueryParam("redirect"))
code := c.QueryParam("code")
if code == "" {
- return c.Redirect(redirectURL.String())
+ return c.Redirect(redirect)
}
- identifier := c.QueryParam("identifier")
- if identifier == "" || identifier != c.SessionID() {
- log.Warn(c, "OAuth identifier doesn't match with user session ID. Aborting sign in process.")
- return c.Redirect(redirectURL.String())
+ if !isValidOAuthHandoff(c, provider, c.QueryParam("handoff")) {
+ log.Warn(c, "OAuth handoff token is not valid for this request. Aborting sign in process.")
+ return c.Redirect(redirect)
}
oauthUser := &query.GetOAuthProfile{Provider: provider, Code: code}
@@ -182,7 +308,7 @@ func OAuthToken() web.HandlerFunc {
webutil.AddAuthUserCookie(c, user)
- return c.Redirect(redirectURL.String())
+ return c.Redirect(redirect)
}
}
@@ -228,6 +354,13 @@ func OAuthCallback() web.HandlerFunc {
return c.Failure(err)
}
+ if !isKnownOAuthOrigin(c, redirectURL) {
+ log.Warnf(c, "OAuth callback state for provider @{Provider} points at an unknown origin. Aborting sign in process.", dto.Props{"Provider": provider})
+ return c.Forbidden()
+ }
+
+ origin := redirectURL.Scheme + "://" + redirectURL.Host
+
code := c.QueryParam("code")
if code == "" {
return c.Redirect(redirectURL.String())
@@ -235,9 +368,14 @@ func OAuthCallback() web.HandlerFunc {
//Test OAuth
if redirectURL.Path == fmt.Sprintf("/oauth/%s/echo", provider) {
+ handoff, err := newOAuthHandoff(provider, origin, claims.Identifier)
+ if err != nil {
+ return c.Failure(err)
+ }
+
var query = redirectURL.Query()
query.Set("code", code)
- query.Set("identifier", claims.Identifier)
+ query.Set("handoff", handoff)
redirectURL.RawQuery = query.Encode()
return c.Redirect(redirectURL.String())
}
@@ -271,10 +409,15 @@ func OAuthCallback() web.HandlerFunc {
}
//Sign in process
+ handoff, err := newOAuthHandoff(provider, origin, claims.Identifier)
+ if err != nil {
+ return c.Failure(err)
+ }
+
var query = redirectURL.Query()
query.Set("code", code)
query.Set("redirect", redirectURL.RequestURI())
- query.Set("identifier", claims.Identifier)
+ query.Set("handoff", handoff)
redirectURL.RawQuery = query.Encode()
redirectURL.Path = fmt.Sprintf("/oauth/%s/token", provider)
return c.Redirect(redirectURL.String())
@@ -288,16 +431,30 @@ func SignInByOAuth() web.HandlerFunc {
c.Response.Header().Add("X-Robots-Tag", "noindex")
provider := c.Param("provider")
- redirect := c.QueryParam("redirect")
+ // The origin the user is sent back to has to come from the resolved tenant, not from
+ // the request host: Host and X-Forwarded-Host are caller controlled, so deriving it
+ // from them lets anyone have the provider's authorization code delivered to an origin
+ // they own and then replay it against a tenant of their choosing.
+ origins := oauthAllowedOrigins(c)
+
+ redirect := c.QueryParam("redirect")
if redirect == "" {
- redirect = c.BaseURL()
- } else if redirect != c.BaseURL() && !strings.HasPrefix(redirect, c.BaseURL()+"/") {
+ redirect = origins[0]
+ } else if !isAllowedOAuthRedirect(origins, redirect) {
return c.Forbidden()
}
- redirectURL, _ := url.ParseRequestURI(redirect)
- redirectURL.ResolveReference(c.Request.URL)
+ redirectURL, err := url.ParseRequestURI(redirect)
+ if err != nil {
+ return c.Forbidden()
+ }
+
+ // Without a tenant the only flow that can complete is sign up, which runs on the
+ // host-wide OAuth address. Everything else needs a tenant to sign in to.
+ if c.Tenant() == nil && redirectURL.Path != "/signup" {
+ return c.Forbidden()
+ }
if c.IsAuthenticated() && redirectURL.Path != fmt.Sprintf("/oauth/%s/echo", provider) {
return c.Redirect(redirect)
diff --git a/app/handlers/oauth_test.go b/app/handlers/oauth_test.go
index 969abc25d..72c09eec3 100644
--- a/app/handlers/oauth_test.go
+++ b/app/handlers/oauth_test.go
@@ -2,7 +2,10 @@ package handlers_test
import (
"context"
+ "crypto/sha256"
+ "encoding/hex"
"testing"
+ "time"
"github.com/getfider/fider/app/models/dto"
"github.com/getfider/fider/app/models/entity"
@@ -13,6 +16,7 @@ import (
"github.com/getfider/fider/app"
"net/http"
+ "net/http/httptest"
"net/url"
"github.com/getfider/fider/app/handlers"
@@ -36,6 +40,38 @@ func initOAuthWithMocks() {
}
return nil
})
+ mockTenantByDomain()
+}
+
+// mockTenantByDomain resolves the hostnames the mocked tenants are served on, so that the
+// OAuth handlers can check a redirect origin against a real tenant record.
+func mockTenantByDomain() {
+ bus.AddHandler(func(ctx context.Context, q *query.GetTenantByDomain) error {
+ switch q.Domain {
+ case "demo.test.fider.io":
+ q.Result = mock.DemoTenant
+ return nil
+ case "avengers.test.fider.io", "feedback.theavengers.com":
+ q.Result = mock.AvengersTenant
+ return nil
+ }
+ return app.ErrNotFound
+ })
+}
+
+// newHandoff mints the token OAuthCallback would hand over to the tenant address.
+func newHandoff(provider, origin, sessionID string) string {
+ sum := sha256.Sum256([]byte(sessionID))
+ token, err := jwt.Encode(jwt.OAuthHandoffClaims{
+ Provider: provider,
+ Origin: origin,
+ SessionIDHash: hex.EncodeToString(sum[:]),
+ Metadata: jwt.Metadata{
+ ExpiresAt: jwt.Time(time.Now().Add(2 * time.Minute)),
+ },
+ })
+ Expect(err).IsNil()
+ return token
}
func TestSignOutHandler(t *testing.T) {
@@ -62,6 +98,7 @@ func TestSignInByOAuthHandler_RootRedirect(t *testing.T) {
AddParam("provider", app.FacebookProvider).
AddCookie(web.CookieSessionName, "MY_SESSION_ID").
WithURL("http://avengers.test.fider.io/oauth/facebook?redirect=http://avengers.test.fider.io").
+ OnTenant(mock.AvengersTenant).
Use(middlewares.Session()).
Execute(handlers.SignInByOAuth())
@@ -77,6 +114,24 @@ func TestSignInByOAuthHandler_PathRedirect(t *testing.T) {
AddParam("provider", app.FacebookProvider).
AddCookie(web.CookieSessionName, "MY_SESSION_ID").
WithURL("http://avengers.test.fider.io/oauth/facebook?redirect=http://avengers.test.fider.io/something").
+ OnTenant(mock.AvengersTenant).
+ Use(middlewares.Session()).
+ Execute(handlers.SignInByOAuth())
+
+ Expect(code).Equals(http.StatusTemporaryRedirect)
+}
+
+// A tenant with a custom domain is still served on its subdomain, so both are valid targets.
+func TestSignInByOAuthHandler_CustomDomainRedirect(t *testing.T) {
+ RegisterT(t)
+ initOAuthWithMocks()
+
+ server := mock.NewServer()
+ code, _ := server.
+ AddParam("provider", app.FacebookProvider).
+ AddCookie(web.CookieSessionName, "MY_SESSION_ID").
+ WithURL("http://feedback.theavengers.com/oauth/facebook?redirect=http://feedback.theavengers.com/something").
+ OnTenant(mock.AvengersTenant).
Use(middlewares.Session()).
Execute(handlers.SignInByOAuth())
@@ -92,6 +147,7 @@ func TestSignInByOAuthHandler_EvilRedirect(t *testing.T) {
AddParam("provider", app.FacebookProvider).
AddCookie(web.CookieSessionName, "MY_SESSION_ID").
WithURL("http://avengers.test.fider.io/oauth/facebook?redirect=http://evil.com").
+ OnTenant(mock.AvengersTenant).
Use(middlewares.Session()).
Execute(handlers.SignInByOAuth())
@@ -107,31 +163,118 @@ func TestSignInByOAuthHandler_EvilRedirect2(t *testing.T) {
AddParam("provider", app.FacebookProvider).
AddCookie(web.CookieSessionName, "MY_SESSION_ID").
WithURL("http://avengers.test.fider.io/oauth/facebook?redirect=http://avengers.test.fider.io.evil.com").
+ OnTenant(mock.AvengersTenant).
Use(middlewares.Session()).
Execute(handlers.SignInByOAuth())
Expect(code).Equals(http.StatusForbidden)
}
-func TestSignInByOAuthHandler_InvalidURL(t *testing.T) {
+// The redirect has to be built from the tenant record, never from the request host, which
+// any caller can set with Host or X-Forwarded-Host. A poisoned host falls back to the
+// tenant's canonical origin rather than signing the attacker's origin into the state.
+func TestSignInByOAuthHandler_PoisonedHost(t *testing.T) {
RegisterT(t)
initOAuthWithMocks()
- state, _ := jwt.Encode(jwt.OAuthStateClaims{
- Redirect: "http://avengers.test.fider.io",
- Identifier: "MY_SESSION_ID",
- })
+ server := mock.NewServer()
+ code, response := server.
+ AddParam("provider", app.FacebookProvider).
+ AddCookie(web.CookieSessionName, "MY_SESSION_ID").
+ WithURL("http://evil.com/oauth/facebook").
+ AddHeader("X-Forwarded-Host", "evil.com").
+ OnTenant(mock.AvengersTenant).
+ Use(middlewares.Session()).
+ Execute(handlers.SignInByOAuth())
+
+ Expect(code).Equals(http.StatusTemporaryRedirect)
+ ExpectOAuthState(response, "http://feedback.theavengers.com", "MY_SESSION_ID")
+}
+
+// The poisoned host can't be laundered through the redirect parameter either.
+func TestSignInByOAuthHandler_PoisonedHost_AsRedirect(t *testing.T) {
+ RegisterT(t)
+ initOAuthWithMocks()
+
+ server := mock.NewServer()
+ code, _ := server.
+ AddParam("provider", app.FacebookProvider).
+ AddCookie(web.CookieSessionName, "MY_SESSION_ID").
+ WithURL("http://evil.com/oauth/facebook?redirect=http://evil.com").
+ AddHeader("X-Forwarded-Host", "evil.com").
+ OnTenant(mock.AvengersTenant).
+ Use(middlewares.Session()).
+ Execute(handlers.SignInByOAuth())
+
+ Expect(code).Equals(http.StatusForbidden)
+}
+
+// Same attack, but on a host that resolves to no tenant at all — which is reachable
+// because this route sits in front of the RequireTenant middleware.
+func TestSignInByOAuthHandler_PoisonedHost_WithoutTenant(t *testing.T) {
+ RegisterT(t)
+ initOAuthWithMocks()
+
+ server := mock.NewServer()
+ code, _ := server.
+ AddParam("provider", app.FacebookProvider).
+ AddCookie(web.CookieSessionName, "MY_SESSION_ID").
+ WithURL("http://evil.com/oauth/facebook").
+ AddHeader("X-Forwarded-Host", "evil.com").
+ Use(middlewares.Session()).
+ Execute(handlers.SignInByOAuth())
+
+ Expect(code).Equals(http.StatusForbidden)
+}
+
+// Without a tenant, sign up on the host-wide OAuth address is the only flow that can complete.
+func TestSignInByOAuthHandler_WithoutTenant_SignUp(t *testing.T) {
+ RegisterT(t)
+ initOAuthWithMocks()
+
+ server := mock.NewServer()
+ code, response := server.
+ AddParam("provider", app.FacebookProvider).
+ AddCookie(web.CookieSessionName, "MY_SESSION_ID").
+ WithURL("http://login.test.fider.io/oauth/facebook?redirect=http://login.test.fider.io/signup").
+ Use(middlewares.Session()).
+ Execute(handlers.SignInByOAuth())
+
+ Expect(code).Equals(http.StatusTemporaryRedirect)
+ ExpectOAuthState(response, "http://login.test.fider.io/signup", "MY_SESSION_ID")
+}
+
+func TestSignInByOAuthHandler_WithoutTenant_NotSignUp(t *testing.T) {
+ RegisterT(t)
+ initOAuthWithMocks()
+
+ server := mock.NewServer()
+ code, _ := server.
+ AddParam("provider", app.FacebookProvider).
+ AddCookie(web.CookieSessionName, "MY_SESSION_ID").
+ WithURL("http://login.test.fider.io/oauth/facebook?redirect=http://login.test.fider.io/something").
+ Use(middlewares.Session()).
+ Execute(handlers.SignInByOAuth())
+
+ Expect(code).Equals(http.StatusForbidden)
+}
+
+func TestSignInByOAuthHandler_InvalidURL(t *testing.T) {
+ RegisterT(t)
+ initOAuthWithMocks()
server := mock.NewServer()
code, response := server.
AddParam("provider", app.FacebookProvider).
AddCookie(web.CookieSessionName, "MY_SESSION_ID").
WithURL("http://avengers.test.fider.io/oauth/facebook").
+ OnTenant(mock.AvengersTenant).
Use(middlewares.Session()).
Execute(handlers.SignInByOAuth())
Expect(code).Equals(http.StatusTemporaryRedirect)
- Expect(response.Header().Get("Location")).Equals("https://www.facebook.com/v3.2/dialog/oauth?client_id=FB_CL_ID&redirect_uri=http%3A%2F%2Flogin.test.fider.io%2Foauth%2Ffacebook%2Fcallback&response_type=code&scope=public_profile+email&state=" + state)
+ // No redirect given, so it defaults to the tenant's canonical origin — its custom domain.
+ ExpectOAuthState(response, "http://feedback.theavengers.com", "MY_SESSION_ID")
}
func TestSignInByOAuthHandler_AuthenticatedUser(t *testing.T) {
@@ -144,6 +287,7 @@ func TestSignInByOAuthHandler_AuthenticatedUser(t *testing.T) {
AddParam("provider", app.FacebookProvider).
AddCookie(web.CookieSessionName, "MY_SESSION_ID").
WithURL("http://avengers.test.fider.io/oauth/facebook?redirect=http://avengers.test.fider.io").
+ OnTenant(mock.AvengersTenant).
Use(middlewares.Session()).
Execute(handlers.SignInByOAuth())
@@ -161,20 +305,17 @@ func TestSignInByOAuthHandler_AuthenticatedUser_UsingEcho(t *testing.T) {
AddParam("provider", app.FacebookProvider).
AddCookie(web.CookieSessionName, "MY_SESSION_ID").
WithURL("http://avengers.test.fider.io/oauth/facebook?redirect=http://avengers.test.fider.io/oauth/facebook/echo").
+ OnTenant(mock.AvengersTenant).
Use(middlewares.Session()).
Execute(handlers.SignInByOAuth())
- state, _ := jwt.Encode(jwt.OAuthStateClaims{
- Redirect: "http://avengers.test.fider.io/oauth/facebook/echo",
- Identifier: "MY_SESSION_ID",
- })
-
Expect(code).Equals(http.StatusTemporaryRedirect)
- Expect(response.Header().Get("Location")).Equals("https://www.facebook.com/v3.2/dialog/oauth?client_id=FB_CL_ID&redirect_uri=http%3A%2F%2Flogin.test.fider.io%2Foauth%2Ffacebook%2Fcallback&response_type=code&scope=public_profile+email&state=" + state)
+ ExpectOAuthState(response, "http://avengers.test.fider.io/oauth/facebook/echo", "MY_SESSION_ID")
}
func TestCallbackHandler_InvalidState(t *testing.T) {
RegisterT(t)
+ mockTenantByDomain()
server := mock.NewServer()
code, _ := server.
@@ -187,6 +328,7 @@ func TestCallbackHandler_InvalidState(t *testing.T) {
func TestCallbackHandler_InvalidCode(t *testing.T) {
RegisterT(t)
+ mockTenantByDomain()
server := mock.NewServer()
state, _ := jwt.Encode(jwt.OAuthStateClaims{
@@ -203,8 +345,29 @@ func TestCallbackHandler_InvalidCode(t *testing.T) {
Expect(response.Header().Get("Location")).Equals("http://avengers.test.fider.io")
}
+// State is signed with a process-wide secret, so a valid signature alone doesn't make the
+// origin it carries legitimate — it has to resolve to a tenant Fider actually serves.
+func TestCallbackHandler_UnknownOrigin(t *testing.T) {
+ RegisterT(t)
+ mockTenantByDomain()
+
+ state, _ := jwt.Encode(jwt.OAuthStateClaims{
+ Redirect: "http://evil.com",
+ Identifier: "888",
+ })
+
+ server := mock.NewServer()
+ code, _ := server.
+ WithURL("http://login.test.fider.io/oauth/callback?state="+state+"&code=123").
+ AddParam("provider", app.FacebookProvider).
+ Execute(handlers.OAuthCallback())
+
+ Expect(code).Equals(http.StatusForbidden)
+}
+
func TestCallbackHandler_SignIn(t *testing.T) {
RegisterT(t)
+ mockTenantByDomain()
state, _ := jwt.Encode(jwt.OAuthStateClaims{
Redirect: "http://avengers.test.fider.io",
@@ -218,11 +381,20 @@ func TestCallbackHandler_SignIn(t *testing.T) {
Execute(handlers.OAuthCallback())
Expect(code).Equals(http.StatusTemporaryRedirect)
- Expect(response.Header().Get("Location")).Equals("http://avengers.test.fider.io/oauth/facebook/token?code=123&identifier=888&redirect=%2F")
+
+ location, _ := url.Parse(response.Header().Get("Location"))
+ Expect(location.Host).Equals("avengers.test.fider.io")
+ Expect(location.Path).Equals("/oauth/facebook/token")
+ Expect(location.Query().Get("code")).Equals("123")
+ Expect(location.Query().Get("redirect")).Equals("/")
+ // The session ID itself must not travel through the URL any more.
+ Expect(location.Query().Get("identifier")).IsEmpty()
+ ExpectOAuthHandoff(location.Query().Get("handoff"), "facebook", "http://avengers.test.fider.io", "888")
}
func TestCallbackHandler_SignIn_WithPath(t *testing.T) {
RegisterT(t)
+ mockTenantByDomain()
server := mock.NewServer()
state, _ := jwt.Encode(jwt.OAuthStateClaims{
@@ -236,11 +408,18 @@ func TestCallbackHandler_SignIn_WithPath(t *testing.T) {
Execute(handlers.OAuthCallback())
Expect(code).Equals(http.StatusTemporaryRedirect)
- Expect(response.Header().Get("Location")).Equals("http://avengers.test.fider.io/oauth/facebook/token?code=123&identifier=888&redirect=%2Fsome-page")
+
+ location, _ := url.Parse(response.Header().Get("Location"))
+ Expect(location.Host).Equals("avengers.test.fider.io")
+ Expect(location.Path).Equals("/oauth/facebook/token")
+ Expect(location.Query().Get("code")).Equals("123")
+ Expect(location.Query().Get("redirect")).Equals("/some-page")
+ ExpectOAuthHandoff(location.Query().Get("handoff"), "facebook", "http://avengers.test.fider.io", "888")
}
func TestCallbackHandler_SignUp(t *testing.T) {
RegisterT(t)
+ mockTenantByDomain()
oauthUser := &dto.OAuthUserProfile{
ID: "FB123",
@@ -307,7 +486,7 @@ func TestOAuthTokenHandler_ExistingUserAndProvider(t *testing.T) {
server := mock.NewServer()
code, response := server.
- WithURL("http://demo.test.fider.io/oauth/facebook/token?code=123&identifier=MY_SESSION_ID&redirect=/hello").
+ WithURL("http://demo.test.fider.io/oauth/facebook/token?code=123&redirect=/hello&handoff=" + newHandoff(app.FacebookProvider, "http://demo.test.fider.io", "MY_SESSION_ID")).
OnTenant(mock.DemoTenant).
AddCookie(web.CookieSessionName, "MY_SESSION_ID").
AddParam("provider", app.FacebookProvider).
@@ -358,7 +537,7 @@ func TestOAuthTokenHandler_NewUser(t *testing.T) {
server := mock.NewServer()
code, response := server.
- WithURL("http://demo.test.fider.io/oauth/facebook/token?code=456&identifier=MY_SESSION_ID&redirect=/hello").
+ WithURL("http://demo.test.fider.io/oauth/facebook/token?code=456&redirect=/hello&handoff=" + newHandoff(app.FacebookProvider, "http://demo.test.fider.io", "MY_SESSION_ID")).
OnTenant(mock.DemoTenant).
AddCookie(web.CookieSessionName, "MY_SESSION_ID").
AddParam("provider", app.FacebookProvider).
@@ -405,7 +584,7 @@ func TestOAuthTokenHandler_NewUserWithoutEmail(t *testing.T) {
})
code, response := server.
- WithURL("http://demo.test.fider.io/oauth/facebook/token?code=798&identifier=MY_SESSION_ID&redirect=/").
+ WithURL("http://demo.test.fider.io/oauth/facebook/token?code=798&redirect=/&handoff=" + newHandoff(app.FacebookProvider, "http://demo.test.fider.io", "MY_SESSION_ID")).
OnTenant(mock.DemoTenant).
AddParam("provider", app.FacebookProvider).
AddCookie(web.CookieSessionName, "MY_SESSION_ID").
@@ -461,7 +640,7 @@ func TestOAuthTokenHandler_ExistingUser_WithoutEmail(t *testing.T) {
})
code, response := server.
- WithURL("http://demo.test.fider.io/oauth/facebook/token?code=456&identifier=MY_SESSION_ID&redirect=/").
+ WithURL("http://demo.test.fider.io/oauth/facebook/token?code=456&redirect=/&handoff=" + newHandoff(app.FacebookProvider, "http://demo.test.fider.io", "MY_SESSION_ID")).
OnTenant(mock.DemoTenant).
AddParam("provider", app.FacebookProvider).
AddCookie(web.CookieSessionName, "MY_SESSION_ID").
@@ -512,7 +691,7 @@ func TestOAuthTokenHandler_ExistingUser_NewProvider(t *testing.T) {
server := mock.NewServer()
code, response := server.
- WithURL("http://demo.test.fider.io/oauth/google/token?code=123&identifier=MY_SESSION_ID&redirect=/").
+ WithURL("http://demo.test.fider.io/oauth/google/token?code=123&redirect=/&handoff=" + newHandoff(app.GoogleProvider, "http://demo.test.fider.io", "MY_SESSION_ID")).
OnTenant(mock.DemoTenant).
AddParam("provider", app.GoogleProvider).
AddCookie(web.CookieSessionName, "MY_SESSION_ID").
@@ -559,7 +738,7 @@ func TestOAuthTokenHandler_NewUser_PrivateSite(t *testing.T) {
})
code, response := server.
- WithURL("http://feedback.theavengers.com/oauth/facebook/token?code=456&identifier=MY_SESSION_ID&redirect=/").
+ WithURL("http://feedback.theavengers.com/oauth/facebook/token?code=456&redirect=/&handoff="+newHandoff(app.FacebookProvider, "http://feedback.theavengers.com", "MY_SESSION_ID")).
OnTenant(mock.AvengersTenant).
AddParam("provider", app.FacebookProvider).
AddCookie(web.CookieSessionName, "MY_SESSION_ID").
@@ -621,7 +800,7 @@ func TestOAuthTokenHandler_NewUser_PrivateSite_UsingTrustedProvider(t *testing.T
})
code, response := server.
- WithURL("http://feedback.theavengers.com/oauth/"+providerCode+"/token?code=000111&identifier=MY_SESSION_ID&redirect=/").
+ WithURL("http://feedback.theavengers.com/oauth/"+providerCode+"/token?code=000111&redirect=/&handoff="+newHandoff(providerCode, "http://feedback.theavengers.com", "MY_SESSION_ID")).
OnTenant(mock.AvengersTenant).
AddParam("provider", providerCode).
AddCookie(web.CookieSessionName, "MY_SESSION_ID").
@@ -638,13 +817,108 @@ func TestOAuthTokenHandler_NewUser_PrivateSite_UsingTrustedProvider(t *testing.T
})
}
-func TestOAuthTokenHandler_InvalidIdentifier(t *testing.T) {
+// executeOAuthTokenWithHandoff runs OAuthToken on the Avengers tenant with the given
+// handoff token and returns the response, so the rejection cases can share a setup.
+func executeOAuthTokenWithHandoff(handoff string) (int, *httptest.ResponseRecorder) {
+ return mock.NewServer().
+ WithURL("http://feedback.theavengers.com/oauth/facebook/token?code=456&redirect=/&handoff="+handoff).
+ OnTenant(mock.AvengersTenant).
+ AddParam("provider", app.FacebookProvider).
+ AddCookie(web.CookieSessionName, "MY_SESSION_ID").
+ Use(middlewares.Session()).
+ Execute(handlers.OAuthToken())
+}
+
+func TestOAuthTokenHandler_MissingHandoff(t *testing.T) {
RegisterT(t)
- server := mock.NewServer()
- mock.AvengersTenant.IsPrivate = true
- code, response := server.
- WithURL("http://feedback.theavengers.com/oauth/facebook/token?code=456&identifier=SOME_OTHER_ID&redirect=/").
+ code, response := executeOAuthTokenWithHandoff("")
+
+ Expect(code).Equals(http.StatusTemporaryRedirect)
+ Expect(response.Header().Get("Location")).Equals("/")
+ ExpectFiderAuthCookie(response, nil)
+}
+
+// The browser that started the flow is the only one allowed to finish it. A handoff must
+// not be usable by a caller who simply sets their own user_session_id cookie.
+func TestOAuthTokenHandler_HandoffForAnotherSession(t *testing.T) {
+ RegisterT(t)
+
+ handoff := newHandoff(app.FacebookProvider, "http://feedback.theavengers.com", "SOME_OTHER_ID")
+ code, response := executeOAuthTokenWithHandoff(handoff)
+
+ Expect(code).Equals(http.StatusTemporaryRedirect)
+ Expect(response.Header().Get("Location")).Equals("/")
+ ExpectFiderAuthCookie(response, nil)
+}
+
+// A handoff issued for one tenant must not be redeemable on another.
+func TestOAuthTokenHandler_HandoffForAnotherTenant(t *testing.T) {
+ RegisterT(t)
+
+ handoff := newHandoff(app.FacebookProvider, "http://demo.test.fider.io", "MY_SESSION_ID")
+ code, response := executeOAuthTokenWithHandoff(handoff)
+
+ Expect(code).Equals(http.StatusTemporaryRedirect)
+ Expect(response.Header().Get("Location")).Equals("/")
+ ExpectFiderAuthCookie(response, nil)
+}
+
+func TestOAuthTokenHandler_HandoffForAnotherProvider(t *testing.T) {
+ RegisterT(t)
+
+ handoff := newHandoff(app.GoogleProvider, "http://feedback.theavengers.com", "MY_SESSION_ID")
+ code, response := executeOAuthTokenWithHandoff(handoff)
+
+ Expect(code).Equals(http.StatusTemporaryRedirect)
+ Expect(response.Header().Get("Location")).Equals("/")
+ ExpectFiderAuthCookie(response, nil)
+}
+
+func TestOAuthTokenHandler_ExpiredHandoff(t *testing.T) {
+ RegisterT(t)
+
+ sum := sha256.Sum256([]byte("MY_SESSION_ID"))
+ handoff, _ := jwt.Encode(jwt.OAuthHandoffClaims{
+ Provider: app.FacebookProvider,
+ Origin: "http://feedback.theavengers.com",
+ SessionIDHash: hex.EncodeToString(sum[:]),
+ Metadata: jwt.Metadata{
+ ExpiresAt: jwt.Time(time.Now().Add(-1 * time.Minute)),
+ },
+ })
+
+ code, response := executeOAuthTokenWithHandoff(handoff)
+
+ Expect(code).Equals(http.StatusTemporaryRedirect)
+ Expect(response.Header().Get("Location")).Equals("/")
+ ExpectFiderAuthCookie(response, nil)
+}
+
+// This endpoint must never send the browser to another origin, even before sign in.
+func TestOAuthTokenHandler_OpenRedirect(t *testing.T) {
+ RegisterT(t)
+
+ for _, redirect := range []string{"http://evil.com/x", "//evil.com/x", "https://feedback.theavengers.com.evil.com/x"} {
+ code, response := mock.NewServer().
+ WithURL("http://feedback.theavengers.com/oauth/facebook/token?redirect="+url.QueryEscape(redirect)).
+ OnTenant(mock.AvengersTenant).
+ AddParam("provider", app.FacebookProvider).
+ AddCookie(web.CookieSessionName, "MY_SESSION_ID").
+ Use(middlewares.Session()).
+ Execute(handlers.OAuthToken())
+
+ Expect(code).Equals(http.StatusTemporaryRedirect)
+ Expect(response.Header().Get("Location")).Equals("/")
+ }
+}
+
+// A missing redirect used to be parsed into a nil URL and then dereferenced.
+func TestOAuthTokenHandler_MissingRedirect(t *testing.T) {
+ RegisterT(t)
+
+ code, response := mock.NewServer().
+ WithURL("http://feedback.theavengers.com/oauth/facebook/token").
OnTenant(mock.AvengersTenant).
AddParam("provider", app.FacebookProvider).
AddCookie(web.CookieSessionName, "MY_SESSION_ID").
@@ -653,7 +927,6 @@ func TestOAuthTokenHandler_InvalidIdentifier(t *testing.T) {
Expect(code).Equals(http.StatusTemporaryRedirect)
Expect(response.Header().Get("Location")).Equals("/")
- ExpectFiderAuthCookie(response, nil)
}
func ExpectOAuthToken(token string, expected *jwt.OAuthClaims) {
@@ -664,3 +937,29 @@ func ExpectOAuthToken(token string, expected *jwt.OAuthClaims) {
Expect(user.OAuthEmail).Equals(expected.OAuthEmail)
Expect(user.OAuthProvider).Equals(expected.OAuthProvider)
}
+
+// ExpectOAuthState checks the provider authorization URL and the claims signed into its state.
+func ExpectOAuthState(response *httptest.ResponseRecorder, expectedRedirect, expectedIdentifier string) {
+ location, err := url.Parse(response.Header().Get("Location"))
+ Expect(err).IsNil()
+ Expect(location.Host).Equals("www.facebook.com")
+ Expect(location.Query().Get("redirect_uri")).Equals("http://login.test.fider.io/oauth/facebook/callback")
+
+ claims, err := jwt.DecodeOAuthStateClaims(location.Query().Get("state"))
+ Expect(err).IsNil()
+ Expect(claims.Redirect).Equals(expectedRedirect)
+ Expect(claims.Identifier).Equals(expectedIdentifier)
+ Expect(claims.ExpiresAt).IsNotNil()
+}
+
+// ExpectOAuthHandoff checks a handoff token is bound to the expected provider, origin and session.
+func ExpectOAuthHandoff(handoff, expectedProvider, expectedOrigin, expectedSessionID string) {
+ claims, err := jwt.DecodeOAuthHandoffClaims(handoff)
+ Expect(err).IsNil()
+ Expect(claims.Provider).Equals(expectedProvider)
+ Expect(claims.Origin).Equals(expectedOrigin)
+ Expect(claims.ExpiresAt).IsNotNil()
+
+ sum := sha256.Sum256([]byte(expectedSessionID))
+ Expect(claims.SessionIDHash).Equals(hex.EncodeToString(sum[:]))
+}
diff --git a/app/pkg/jwt/jwt.go b/app/pkg/jwt/jwt.go
index b934a990d..8e28d1f7c 100644
--- a/app/pkg/jwt/jwt.go
+++ b/app/pkg/jwt/jwt.go
@@ -52,6 +52,16 @@ type OAuthStateClaims struct {
Metadata
}
+// OAuthHandoffClaims represents the short lived token that hands an OAuth sign in over
+// from the host-wide callback address to the tenant address. It binds the handoff to a
+// single provider, origin and browser session so it cannot be replayed elsewhere.
+type OAuthHandoffClaims struct {
+ Provider string `json:"oauthhandoff/provider"`
+ Origin string `json:"oauthhandoff/origin"`
+ SessionIDHash string `json:"oauthhandoff/session_id_hash"`
+ Metadata
+}
+
// Encode creates new JWT token with given claims
func Encode(claims jwtgo.Claims) (string, error) {
jwtToken := jwtgo.NewWithClaims(jwtgo.GetSigningMethod("HS256"), claims)
@@ -92,6 +102,16 @@ func DecodeOAuthStateClaims(token string) (*OAuthStateClaims, error) {
return claims, nil
}
+// DecodeOAuthHandoffClaims extract OAuthHandoffClaims from given JWT token
+func DecodeOAuthHandoffClaims(token string) (*OAuthHandoffClaims, error) {
+ claims := &OAuthHandoffClaims{}
+ err := decode(token, claims)
+ if err != nil {
+ return nil, errors.Wrap(err, "failed to decode OAuthHandoff claims")
+ }
+ return claims, nil
+}
+
func decode(token string, claims jwtgo.Claims) error {
jwtToken, err := jwtgo.ParseWithClaims(token, claims, func(t *jwtgo.Token) (any, error) {
if _, ok := t.Method.(*jwtgo.SigningMethodHMAC); !ok {
diff --git a/app/services/oauth/oauth.go b/app/services/oauth/oauth.go
index 2e8bab0c4..95550b930 100644
--- a/app/services/oauth/oauth.go
+++ b/app/services/oauth/oauth.go
@@ -7,6 +7,7 @@ import (
"fmt"
"net/url"
"strings"
+ "time"
"github.com/getfider/fider/app"
"github.com/getfider/fider/app/models/cmd"
@@ -270,6 +271,9 @@ func getOAuthAuthorizationURL(ctx context.Context, q *query.GetOAuthAuthorizatio
Redirect: q.Redirect,
Identifier: q.Identifier,
Code: q.Code,
+ Metadata: jwt.Metadata{
+ ExpiresAt: jwt.Time(time.Now().Add(10 * time.Minute)),
+ },
})
if err != nil {
diff --git a/app/services/oauth/oauth_test.go b/app/services/oauth/oauth_test.go
index a794c79cb..2699b2bee 100644
--- a/app/services/oauth/oauth_test.go
+++ b/app/services/oauth/oauth_test.go
@@ -5,6 +5,7 @@ import (
"crypto/tls"
"net/http/httptest"
"net/url"
+ "strings"
"testing"
"github.com/getfider/fider/app"
@@ -36,6 +37,18 @@ func newGetContext(rawurl string) *web.Context {
return web.NewContext(e, req, res, nil)
}
+
+// ExpectAuthURL checks an authorization URL and the claims signed into its state parameter.
+// The state can't be compared as a string because it carries a freshly generated expiry.
+func ExpectAuthURL(actual, expectedPrefix, expectedRedirect, expectedIdentifier string) {
+ Expect(strings.HasPrefix(actual, expectedPrefix)).IsTrue()
+
+ claims, err := jwt.DecodeOAuthStateClaims(strings.TrimPrefix(actual, expectedPrefix))
+ Expect(err).IsNil()
+ Expect(claims.Redirect).Equals(expectedRedirect)
+ Expect(claims.Identifier).Equals(expectedIdentifier)
+ Expect(claims.ExpiresAt).IsNotNil()
+}
func TestGetAuthURL_Facebook(t *testing.T) {
RegisterT(t)
bus.Init(&oauth.Service{})
@@ -56,14 +69,9 @@ func TestGetAuthURL_Facebook(t *testing.T) {
Identifier: "456",
}
- expectedState, _ := jwt.Encode(jwt.OAuthStateClaims{
- Redirect: "http://example.org",
- Identifier: "456",
- })
-
err := bus.Dispatch(ctx, authURL)
Expect(err).IsNil()
- Expect(authURL.Result).Equals("https://www.facebook.com/v3.2/dialog/oauth?client_id=FB_CL_ID&redirect_uri=http%3A%2F%2Flogin.test.fider.io%3A3000%2Foauth%2Ffacebook%2Fcallback&response_type=code&scope=public_profile+email&state=" + expectedState)
+ ExpectAuthURL(authURL.Result, "https://www.facebook.com/v3.2/dialog/oauth?client_id=FB_CL_ID&redirect_uri=http%3A%2F%2Flogin.test.fider.io%3A3000%2Foauth%2Ffacebook%2Fcallback&response_type=code&scope=public_profile+email&state=", "http://example.org", "456")
}
func TestGetAuthURL_Google(t *testing.T) {
@@ -87,14 +95,9 @@ func TestGetAuthURL_Google(t *testing.T) {
Identifier: "123",
}
- expectedState, _ := jwt.Encode(jwt.OAuthStateClaims{
- Redirect: "http://example.org",
- Identifier: "123",
- })
-
err := bus.Dispatch(ctx, authURL)
Expect(err).IsNil()
- Expect(authURL.Result).Equals("https://accounts.google.com/o/oauth2/v2/auth?client_id=GO_CL_ID&redirect_uri=http%3A%2F%2Flogin.test.fider.io%3A3000%2Foauth%2Fgoogle%2Fcallback&response_type=code&scope=profile+email&state=" + expectedState)
+ ExpectAuthURL(authURL.Result, "https://accounts.google.com/o/oauth2/v2/auth?client_id=GO_CL_ID&redirect_uri=http%3A%2F%2Flogin.test.fider.io%3A3000%2Foauth%2Fgoogle%2Fcallback&response_type=code&scope=profile+email&state=", "http://example.org", "123")
}
func TestGetAuthURL_GitHub(t *testing.T) {
@@ -118,14 +121,9 @@ func TestGetAuthURL_GitHub(t *testing.T) {
Identifier: "456",
}
- expectedState, _ := jwt.Encode(jwt.OAuthStateClaims{
- Redirect: "http://example.org",
- Identifier: "456",
- })
-
err := bus.Dispatch(ctx, authURL)
Expect(err).IsNil()
- Expect(authURL.Result).Equals("https://github.com/login/oauth/authorize?client_id=GH_CL_ID&redirect_uri=http%3A%2F%2Flogin.test.fider.io%3A3000%2Foauth%2Fgithub%2Fcallback&response_type=code&scope=user%3Aemail&state=" + expectedState)
+ ExpectAuthURL(authURL.Result, "https://github.com/login/oauth/authorize?client_id=GH_CL_ID&redirect_uri=http%3A%2F%2Flogin.test.fider.io%3A3000%2Foauth%2Fgithub%2Fcallback&response_type=code&scope=user%3Aemail&state=", "http://example.org", "456")
}
func TestGetAuthURL_Custom(t *testing.T) {
@@ -151,14 +149,9 @@ func TestGetAuthURL_Custom(t *testing.T) {
Identifier: "456",
}
- expectedState, _ := jwt.Encode(jwt.OAuthStateClaims{
- Redirect: "http://example.org",
- Identifier: "456",
- })
-
err := bus.Dispatch(ctx, authURL)
Expect(err).IsNil()
- Expect(authURL.Result).Equals("https://example.org/oauth/authorize?client_id=CU_CL_ID&redirect_uri=http%3A%2F%2Flogin.test.fider.io%3A3000%2Foauth%2F_custom%2Fcallback&response_type=code&scope=profile+email&state=" + expectedState)
+ ExpectAuthURL(authURL.Result, "https://example.org/oauth/authorize?client_id=CU_CL_ID&redirect_uri=http%3A%2F%2Flogin.test.fider.io%3A3000%2Foauth%2F_custom%2Fcallback&response_type=code&scope=profile+email&state=", "http://example.org", "456")
}
func TestGetAuthURL_Twitch(t *testing.T) {
@@ -184,14 +177,9 @@ func TestGetAuthURL_Twitch(t *testing.T) {
Identifier: "456",
}
- expectedState, _ := jwt.Encode(jwt.OAuthStateClaims{
- Redirect: "http://example.org",
- Identifier: "456",
- })
-
err := bus.Dispatch(ctx, authURL)
Expect(err).IsNil()
- Expect(authURL.Result).Equals("https://id.twitch.tv/oauth/authorize?claims=%7B%22userinfo%22%3A%7B%22preferred_username%22%3Anull%2C%22email%22%3Anull%2C%22email_verified%22%3Anull%7D%7D&client_id=CU_CL_ID&redirect_uri=http%3A%2F%2Flogin.test.fider.io%3A3000%2Foauth%2F_custom%2Fcallback&response_type=code&scope=openid&state=" + expectedState)
+ ExpectAuthURL(authURL.Result, "https://id.twitch.tv/oauth/authorize?claims=%7B%22userinfo%22%3A%7B%22preferred_username%22%3Anull%2C%22email%22%3Anull%2C%22email_verified%22%3Anull%7D%7D&client_id=CU_CL_ID&redirect_uri=http%3A%2F%2Flogin.test.fider.io%3A3000%2Foauth%2F_custom%2Fcallback&response_type=code&scope=openid&state=", "http://example.org", "456")
}
func TestParseProfileResponse_AllFields(t *testing.T) {