diff options
Diffstat (limited to 'internal/api/client/auth')
-rw-r--r-- | internal/api/client/auth/auth.go | 17 | ||||
-rw-r--r-- | internal/api/client/auth/auth_test.go | 35 | ||||
-rw-r--r-- | internal/api/client/auth/authorize.go | 201 | ||||
-rw-r--r-- | internal/api/client/auth/callback.go | 95 | ||||
-rw-r--r-- | internal/api/client/auth/signin.go | 106 | ||||
-rw-r--r-- | internal/api/client/auth/token.go | 55 |
6 files changed, 301 insertions, 208 deletions
diff --git a/internal/api/client/auth/auth.go b/internal/api/client/auth/auth.go index 717d997a3..10d374838 100644 --- a/internal/api/client/auth/auth.go +++ b/internal/api/client/auth/auth.go @@ -25,6 +25,7 @@ import ( "github.com/superseriousbusiness/gotosocial/internal/db" "github.com/superseriousbusiness/gotosocial/internal/oauth" "github.com/superseriousbusiness/gotosocial/internal/oidc" + "github.com/superseriousbusiness/gotosocial/internal/processing" "github.com/superseriousbusiness/gotosocial/internal/router" ) @@ -66,17 +67,19 @@ const ( // Module implements the ClientAPIModule interface for type Module struct { - db db.DB - server oauth.Server - idp oidc.IDP + db db.DB + server oauth.Server + idp oidc.IDP + processor processing.Processor } // New returns a new auth module -func New(db db.DB, server oauth.Server, idp oidc.IDP) api.ClientModule { +func New(db db.DB, server oauth.Server, idp oidc.IDP, processor processing.Processor) api.ClientModule { return &Module{ - db: db, - server: server, - idp: idp, + db: db, + server: server, + idp: idp, + processor: processor, } } diff --git a/internal/api/client/auth/auth_test.go b/internal/api/client/auth/auth_test.go index bd1a1948e..f222f714f 100644 --- a/internal/api/client/auth/auth_test.go +++ b/internal/api/client/auth/auth_test.go @@ -23,25 +23,37 @@ import ( "fmt" "net/http/httptest" + "codeberg.org/gruf/go-store/kv" "github.com/gin-contrib/sessions" "github.com/gin-contrib/sessions/memstore" "github.com/gin-gonic/gin" "github.com/stretchr/testify/suite" "github.com/superseriousbusiness/gotosocial/internal/api/client/auth" + "github.com/superseriousbusiness/gotosocial/internal/concurrency" "github.com/superseriousbusiness/gotosocial/internal/config" "github.com/superseriousbusiness/gotosocial/internal/db" + "github.com/superseriousbusiness/gotosocial/internal/email" + "github.com/superseriousbusiness/gotosocial/internal/federation" "github.com/superseriousbusiness/gotosocial/internal/gtsmodel" + "github.com/superseriousbusiness/gotosocial/internal/media" + "github.com/superseriousbusiness/gotosocial/internal/messages" "github.com/superseriousbusiness/gotosocial/internal/oauth" "github.com/superseriousbusiness/gotosocial/internal/oidc" + "github.com/superseriousbusiness/gotosocial/internal/processing" "github.com/superseriousbusiness/gotosocial/internal/router" "github.com/superseriousbusiness/gotosocial/testrig" ) type AuthStandardTestSuite struct { suite.Suite - db db.DB - idp oidc.IDP - oauthServer oauth.Server + db db.DB + storage *kv.KVStore + mediaManager media.Manager + federator federation.Federator + processor processing.Processor + emailSender email.Sender + idp oidc.IDP + oauthServer oauth.Server // standard suite models testTokens map[string]*gtsmodel.Token @@ -69,17 +81,26 @@ func (suite *AuthStandardTestSuite) SetupSuite() { func (suite *AuthStandardTestSuite) SetupTest() { testrig.InitTestConfig() - suite.db = testrig.NewTestDB() testrig.InitTestLog() + fedWorker := concurrency.NewWorkerPool[messages.FromFederator](-1, -1) + clientWorker := concurrency.NewWorkerPool[messages.FromClientAPI](-1, -1) + + suite.db = testrig.NewTestDB() + suite.storage = testrig.NewTestStorage() + suite.mediaManager = testrig.NewTestMediaManager(suite.db, suite.storage) + suite.federator = testrig.NewTestFederator(suite.db, testrig.NewTestTransportController(testrig.NewMockHTTPClient(nil), suite.db, fedWorker), suite.storage, suite.mediaManager, fedWorker) + suite.emailSender = testrig.NewEmailSender("../../../../web/template/", nil) + suite.processor = testrig.NewTestProcessor(suite.db, suite.storage, suite.federator, suite.emailSender, suite.mediaManager, clientWorker, fedWorker) + suite.oauthServer = testrig.NewTestOauthServer(suite.db) var err error suite.idp, err = oidc.NewIDP(context.Background()) if err != nil { panic(err) } - suite.authModule = auth.New(suite.db, suite.oauthServer, suite.idp).(*auth.Module) - testrig.StandardDBSetup(suite.db, nil) + suite.authModule = auth.New(suite.db, suite.oauthServer, suite.idp, suite.processor).(*auth.Module) + testrig.StandardDBSetup(suite.db, suite.testAccounts) } func (suite *AuthStandardTestSuite) TearDownTest() { @@ -92,7 +113,7 @@ func (suite *AuthStandardTestSuite) newContext(requestMethod string, requestPath ctx, engine := gin.CreateTestContext(recorder) // load templates into the engine - testrig.ConfigureTemplatesWithGin(engine) + testrig.ConfigureTemplatesWithGin(engine, "../../../../web/template") // create the request protocol := config.GetProtocol() diff --git a/internal/api/client/auth/authorize.go b/internal/api/client/auth/authorize.go index 387b83c1e..6f96484a8 100644 --- a/internal/api/client/auth/authorize.go +++ b/internal/api/client/auth/authorize.go @@ -23,9 +23,6 @@ import ( "fmt" "net/http" "net/url" - "strings" - - "github.com/sirupsen/logrus" "github.com/gin-contrib/sessions" "github.com/gin-gonic/gin" @@ -33,18 +30,22 @@ import ( "github.com/superseriousbusiness/gotosocial/internal/api" "github.com/superseriousbusiness/gotosocial/internal/api/model" "github.com/superseriousbusiness/gotosocial/internal/db" + "github.com/superseriousbusiness/gotosocial/internal/gtserror" "github.com/superseriousbusiness/gotosocial/internal/gtsmodel" ) +// helpfulAdvice is a handy hint to users; +// particularly important during the login flow +var helpfulAdvice = "If you arrived at this error during a login/oauth flow, please try clearing your session cookies and logging in again; if problems persist, make sure you're using the correct credentials" + // AuthorizeGETHandler should be served as GET at https://example.org/oauth/authorize // The idea here is to present an oauth authorize page to the user, with a button // that they have to click to accept. func (m *Module) AuthorizeGETHandler(c *gin.Context) { - l := logrus.WithField("func", "AuthorizeGETHandler") s := sessions.Default(c) if _, err := api.NegotiateAccept(c, api.HTMLAcceptHeaders...); err != nil { - c.HTML(http.StatusNotAcceptable, "error.tmpl", gin.H{"error": err.Error()}) + api.ErrorHandler(c, gtserror.NewErrorNotAcceptable(err, err.Error()), m.processor.InstanceGet) return } @@ -52,56 +53,75 @@ func (m *Module) AuthorizeGETHandler(c *gin.Context) { // If it's not set, then we don't know yet who the user is, so we need to redirect them to the sign in page. userID, ok := s.Get(sessionUserID).(string) if !ok || userID == "" { - l.Trace("userid was empty, parsing form then redirecting to sign in page") form := &model.OAuthAuthorize{} - if err := c.Bind(form); err != nil { - l.Debugf("invalid auth form: %s", err) + if err := c.ShouldBind(form); err != nil { m.clearSession(s) - c.HTML(http.StatusBadRequest, "error.tmpl", gin.H{"error": err.Error()}) + api.ErrorHandler(c, gtserror.NewErrorBadRequest(err, helpfulAdvice), m.processor.InstanceGet) return } - l.Debugf("parsed auth form: %+v", form) - if err := extractAuthForm(s, form); err != nil { - l.Debugf(fmt.Sprintf("error parsing form at /oauth/authorize: %s", err)) + if errWithCode := saveAuthFormToSession(s, form); errWithCode != nil { m.clearSession(s) - c.HTML(http.StatusBadRequest, "error.tmpl", gin.H{"error": err.Error()}) + api.ErrorHandler(c, errWithCode, m.processor.InstanceGet) return } + c.Redirect(http.StatusSeeOther, AuthSignInPath) return } - // We can use the client_id on the session to retrieve info about the app associated with the client_id + // use session information to validate app, user, and account for this request clientID, ok := s.Get(sessionClientID).(string) if !ok || clientID == "" { - c.HTML(http.StatusInternalServerError, "error.tmpl", gin.H{"error": "no client_id found in session"}) + m.clearSession(s) + err := fmt.Errorf("key %s was not found in session", sessionClientID) + api.ErrorHandler(c, gtserror.NewErrorBadRequest(err, helpfulAdvice), m.processor.InstanceGet) return } + app := >smodel.Application{} if err := m.db.GetWhere(c.Request.Context(), []db.Where{{Key: sessionClientID, Value: clientID}}, app); err != nil { m.clearSession(s) - c.HTML(http.StatusInternalServerError, "error.tmpl", gin.H{ - "error": fmt.Sprintf("no application found for client id %s", clientID), - }) + safe := fmt.Sprintf("application for %s %s could not be retrieved", sessionClientID, clientID) + var errWithCode gtserror.WithCode + if err == db.ErrNoEntries { + errWithCode = gtserror.NewErrorBadRequest(err, safe, helpfulAdvice) + } else { + errWithCode = gtserror.NewErrorInternalError(err, safe, helpfulAdvice) + } + api.ErrorHandler(c, errWithCode, m.processor.InstanceGet) return } - // redirect the user if they have not confirmed their email yet, thier account has not been approved yet, - // or thier account has been disabled. user := >smodel.User{} if err := m.db.GetByID(c.Request.Context(), userID, user); err != nil { m.clearSession(s) - c.HTML(http.StatusInternalServerError, "error.tmpl", gin.H{"error": err.Error()}) + safe := fmt.Sprintf("user with id %s could not be retrieved", userID) + var errWithCode gtserror.WithCode + if err == db.ErrNoEntries { + errWithCode = gtserror.NewErrorBadRequest(err, safe, helpfulAdvice) + } else { + errWithCode = gtserror.NewErrorInternalError(err, safe, helpfulAdvice) + } + api.ErrorHandler(c, errWithCode, m.processor.InstanceGet) return } + acct, err := m.db.GetAccountByID(c.Request.Context(), user.AccountID) if err != nil { m.clearSession(s) - c.HTML(http.StatusInternalServerError, "error.tmpl", gin.H{"error": err.Error()}) + safe := fmt.Sprintf("account with id %s could not be retrieved", user.AccountID) + var errWithCode gtserror.WithCode + if err == db.ErrNoEntries { + errWithCode = gtserror.NewErrorBadRequest(err, safe, helpfulAdvice) + } else { + errWithCode = gtserror.NewErrorInternalError(err, safe, helpfulAdvice) + } + api.ErrorHandler(c, errWithCode, m.processor.InstanceGet) return } - if !ensureUserIsAuthorizedOrRedirect(c, user, acct) { + + if ensureUserIsAuthorizedOrRedirect(c, user, acct) { return } @@ -109,25 +129,27 @@ func (m *Module) AuthorizeGETHandler(c *gin.Context) { redirect, ok := s.Get(sessionRedirectURI).(string) if !ok || redirect == "" { m.clearSession(s) - c.HTML(http.StatusInternalServerError, "error.tmpl", gin.H{"error": "no redirect_uri found in session"}) + err := fmt.Errorf("key %s was not found in session", sessionRedirectURI) + api.ErrorHandler(c, gtserror.NewErrorBadRequest(err, helpfulAdvice), m.processor.InstanceGet) return } + scope, ok := s.Get(sessionScope).(string) if !ok || scope == "" { m.clearSession(s) - c.HTML(http.StatusInternalServerError, "error.tmpl", gin.H{"error": "no scope found in session"}) + err := fmt.Errorf("key %s was not found in session", sessionScope) + api.ErrorHandler(c, gtserror.NewErrorBadRequest(err, helpfulAdvice), m.processor.InstanceGet) return } // the authorize template will display a form to the user where they can get some information // about the app that's trying to authorize, and the scope of the request. // They can then approve it if it looks OK to them, which will POST to the AuthorizePOSTHandler - l.Trace("serving authorize html") c.HTML(http.StatusOK, "authorize.tmpl", gin.H{ "appname": app.Name, "appwebsite": app.Website, "redirect": redirect, - sessionScope: scope, + "scope": scope, "user": acct.Username, }) } @@ -136,13 +158,10 @@ func (m *Module) AuthorizeGETHandler(c *gin.Context) { // At this point we assume that the user has A) logged in and B) accepted that the app should act for them, // so we should proceed with the authentication flow and generate an oauth token for them if we can. func (m *Module) AuthorizePOSTHandler(c *gin.Context) { - l := logrus.WithField("func", "AuthorizePOSTHandler") s := sessions.Default(c) // We need to retrieve the original form submitted to the authorizeGEThandler, and // recreate it on the request so that it can be used further by the oauth2 library. - // So first fetch all the values from the session. - errs := []string{} forceLogin, ok := s.Get(sessionForceLogin).(string) @@ -152,77 +171,107 @@ func (m *Module) AuthorizePOSTHandler(c *gin.Context) { responseType, ok := s.Get(sessionResponseType).(string) if !ok || responseType == "" { - errs = append(errs, "session missing response_type") + errs = append(errs, fmt.Sprintf("key %s was not found in session", sessionResponseType)) } clientID, ok := s.Get(sessionClientID).(string) if !ok || clientID == "" { - errs = append(errs, "session missing client_id") + errs = append(errs, fmt.Sprintf("key %s was not found in session", sessionClientID)) } redirectURI, ok := s.Get(sessionRedirectURI).(string) if !ok || redirectURI == "" { - errs = append(errs, "session missing redirect_uri") + errs = append(errs, fmt.Sprintf("key %s was not found in session", sessionRedirectURI)) } scope, ok := s.Get(sessionScope).(string) if !ok { - errs = append(errs, "session missing scope") + errs = append(errs, fmt.Sprintf("key %s was not found in session", sessionScope)) } userID, ok := s.Get(sessionUserID).(string) if !ok { - errs = append(errs, "session missing userid") + errs = append(errs, fmt.Sprintf("key %s was not found in session", sessionUserID)) + } + + if len(errs) != 0 { + errs = append(errs, helpfulAdvice) + api.ErrorHandler(c, gtserror.NewErrorBadRequest(errors.New("one or more missing keys on session during AuthorizePOSTHandler"), errs...), m.processor.InstanceGet) + return } - // redirect the user if they have not confirmed their email yet, thier account has not been approved yet, - // or thier account has been disabled. user := >smodel.User{} if err := m.db.GetByID(c.Request.Context(), userID, user); err != nil { m.clearSession(s) - c.HTML(http.StatusInternalServerError, "error.tmpl", gin.H{"error": err.Error()}) + safe := fmt.Sprintf("user with id %s could not be retrieved", userID) + var errWithCode gtserror.WithCode + if err == db.ErrNoEntries { + errWithCode = gtserror.NewErrorBadRequest(err, safe, helpfulAdvice) + } else { + errWithCode = gtserror.NewErrorInternalError(err, safe, helpfulAdvice) + } + api.ErrorHandler(c, errWithCode, m.processor.InstanceGet) return } + acct, err := m.db.GetAccountByID(c.Request.Context(), user.AccountID) if err != nil { m.clearSession(s) - c.HTML(http.StatusInternalServerError, "error.tmpl", gin.H{"error": err.Error()}) + safe := fmt.Sprintf("account with id %s could not be retrieved", user.AccountID) + var errWithCode gtserror.WithCode + if err == db.ErrNoEntries { + errWithCode = gtserror.NewErrorBadRequest(err, safe, helpfulAdvice) + } else { + errWithCode = gtserror.NewErrorInternalError(err, safe, helpfulAdvice) + } + api.ErrorHandler(c, errWithCode, m.processor.InstanceGet) return } - if !ensureUserIsAuthorizedOrRedirect(c, user, acct) { + + if ensureUserIsAuthorizedOrRedirect(c, user, acct) { return } + // we're done with the session now, so just clear it out m.clearSession(s) - if len(errs) != 0 { - c.HTML(http.StatusBadRequest, "error.tmpl", gin.H{"error": strings.Join(errs, ": ")}) - return + // we have to set the values on the request form + // so that they're picked up by the oauth server + c.Request.Form = url.Values{ + sessionForceLogin: {forceLogin}, + sessionResponseType: {responseType}, + sessionClientID: {clientID}, + sessionRedirectURI: {redirectURI}, + sessionScope: {scope}, + sessionUserID: {userID}, } - // now set the values on the request - values := url.Values{} - values.Set(sessionForceLogin, forceLogin) - values.Set(sessionResponseType, responseType) - values.Set(sessionClientID, clientID) - values.Set(sessionRedirectURI, redirectURI) - values.Set(sessionScope, scope) - values.Set(sessionUserID, userID) - c.Request.Form = values - l.Tracef("values on request set to %+v", c.Request.Form) - - // and proceed with authorization using the oauth2 library if err := m.server.HandleAuthorizeRequest(c.Writer, c.Request); err != nil { - c.HTML(http.StatusBadRequest, "error.tmpl", gin.H{"error": err.Error()}) + api.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error(), helpfulAdvice), m.processor.InstanceGet) } } -// extractAuthForm checks the given OAuthAuthorize form, and stores -// the values in the form into the session. -func extractAuthForm(s sessions.Session, form *model.OAuthAuthorize) error { - // these fields are *required* so check 'em - if form.ResponseType == "" || form.ClientID == "" || form.RedirectURI == "" { - return errors.New("missing one of: response_type, client_id or redirect_uri") +// saveAuthFormToSession checks the given OAuthAuthorize form, +// and stores the values in the form into the session. +func saveAuthFormToSession(s sessions.Session, form *model.OAuthAuthorize) gtserror.WithCode { + if form == nil { + err := errors.New("OAuthAuthorize form was nil") + return gtserror.NewErrorBadRequest(err, err.Error(), helpfulAdvice) + } + + if form.ResponseType == "" { + err := errors.New("field response_type was not set on OAuthAuthorize form") + return gtserror.NewErrorBadRequest(err, err.Error(), helpfulAdvice) + } + + if form.ClientID == "" { + err := errors.New("field client_id was not set on OAuthAuthorize form") + return gtserror.NewErrorBadRequest(err, err.Error(), helpfulAdvice) + } + + if form.RedirectURI == "" { + err := errors.New("field redirect_uri was not set on OAuthAuthorize form") + return gtserror.NewErrorBadRequest(err, err.Error(), helpfulAdvice) } // set default scope to read @@ -237,29 +286,33 @@ func extractAuthForm(s sessions.Session, form *model.OAuthAuthorize) error { s.Set(sessionRedirectURI, form.RedirectURI) s.Set(sessionScope, form.Scope) s.Set(sessionState, uuid.NewString()) - return s.Save() + + if err := s.Save(); err != nil { + err := fmt.Errorf("error saving form values onto session: %s", err) + return gtserror.NewErrorInternalError(err, helpfulAdvice) + } + + return nil } -func ensureUserIsAuthorizedOrRedirect(ctx *gin.Context, user *gtsmodel.User, account *gtsmodel.Account) bool { +func ensureUserIsAuthorizedOrRedirect(ctx *gin.Context, user *gtsmodel.User, account *gtsmodel.Account) (redirected bool) { if user.ConfirmedAt.IsZero() { ctx.Redirect(http.StatusSeeOther, CheckYourEmailPath) - return false + redirected = true + return } if !user.Approved { ctx.Redirect(http.StatusSeeOther, WaitForApprovalPath) - return false - } - - if user.Disabled { - ctx.Redirect(http.StatusSeeOther, AccountDisabledPath) - return false + redirected = true + return } - if !account.SuspendedAt.IsZero() { + if user.Disabled || !account.SuspendedAt.IsZero() { ctx.Redirect(http.StatusSeeOther, AccountDisabledPath) - return false + redirected = true + return } - return true + return } diff --git a/internal/api/client/auth/callback.go b/internal/api/client/auth/callback.go index a5c58647c..34a4995c8 100644 --- a/internal/api/client/auth/callback.go +++ b/internal/api/client/auth/callback.go @@ -30,7 +30,9 @@ import ( "github.com/gin-contrib/sessions" "github.com/gin-gonic/gin" "github.com/google/uuid" + "github.com/superseriousbusiness/gotosocial/internal/api" "github.com/superseriousbusiness/gotosocial/internal/db" + "github.com/superseriousbusiness/gotosocial/internal/gtserror" "github.com/superseriousbusiness/gotosocial/internal/gtsmodel" "github.com/superseriousbusiness/gotosocial/internal/oidc" "github.com/superseriousbusiness/gotosocial/internal/validate" @@ -40,11 +42,14 @@ import ( func (m *Module) CallbackGETHandler(c *gin.Context) { s := sessions.Default(c) - // first make sure the state set in the cookie is the same as the state returned from the external provider + // check the query vs session state parameter to mitigate csrf + // https://auth0.com/docs/secure/attack-protection/state-parameters + state := c.Query(callbackStateParam) if state == "" { m.clearSession(s) - c.JSON(http.StatusForbidden, gin.H{"error": "state query not found on callback"}) + err := fmt.Errorf("%s parameter not found on callback query", callbackStateParam) + api.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) return } @@ -52,84 +57,104 @@ func (m *Module) CallbackGETHandler(c *gin.Context) { savedState, ok := savedStateI.(string) if !ok { m.clearSession(s) - c.JSON(http.StatusForbidden, gin.H{"error": "state not found in session"}) + err := fmt.Errorf("key %s was not found in session", sessionState) + api.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) return } if state != savedState { m.clearSession(s) - c.JSON(http.StatusForbidden, gin.H{"error": "state mismatch"}) + err := errors.New("mismatch between query state and session state") + api.ErrorHandler(c, gtserror.NewErrorUnauthorized(err, err.Error()), m.processor.InstanceGet) return } + // retrieve stored claims using code code := c.Query(callbackCodeParam) + if code == "" { + m.clearSession(s) + err := fmt.Errorf("%s parameter not found on callback query", callbackCodeParam) + api.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) + return + } - claims, err := m.idp.HandleCallback(c.Request.Context(), code) - if err != nil { + claims, errWithCode := m.idp.HandleCallback(c.Request.Context(), code) + if errWithCode != nil { m.clearSession(s) - c.JSON(http.StatusForbidden, gin.H{"error": err.Error()}) + api.ErrorHandler(c, errWithCode, m.processor.InstanceGet) return } - // We can use the client_id on the session to retrieve info about the app associated with the client_id + // We can use the client_id on the session to retrieve + // info about the app associated with the client_id clientID, ok := s.Get(sessionClientID).(string) if !ok || clientID == "" { m.clearSession(s) - c.JSON(http.StatusInternalServerError, gin.H{"error": "no client_id found in session during callback"}) + err := fmt.Errorf("key %s was not found in session", sessionClientID) + api.ErrorHandler(c, gtserror.NewErrorBadRequest(err, helpfulAdvice), m.processor.InstanceGet) return } + app := >smodel.Application{} if err := m.db.GetWhere(c.Request.Context(), []db.Where{{Key: sessionClientID, Value: clientID}}, app); err != nil { m.clearSession(s) - c.JSON(http.StatusInternalServerError, gin.H{"error": fmt.Sprintf("no application found for client id %s", clientID)}) + safe := fmt.Sprintf("application for %s %s could not be retrieved", sessionClientID, clientID) + var errWithCode gtserror.WithCode + if err == db.ErrNoEntries { + errWithCode = gtserror.NewErrorBadRequest(err, safe, helpfulAdvice) + } else { + errWithCode = gtserror.NewErrorInternalError(err, safe, helpfulAdvice) + } + api.ErrorHandler(c, errWithCode, m.processor.InstanceGet) return } - user, err := m.parseUserFromClaims(c.Request.Context(), claims, net.IP(c.ClientIP()), app.ID) - if err != nil { + user, errWithCode := m.parseUserFromClaims(c.Request.Context(), claims, net.IP(c.ClientIP()), app.ID) + if errWithCode != nil { m.clearSession(s) - c.JSON(http.StatusForbidden, gin.H{"error": err.Error()}) + api.ErrorHandler(c, errWithCode, m.processor.InstanceGet) return } s.Set(sessionUserID, user.ID) if err := s.Save(); err != nil { m.clearSession(s) - c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + api.ErrorHandler(c, gtserror.NewErrorInternalError(err), m.processor.InstanceGet) return } c.Redirect(http.StatusFound, OauthAuthorizePath) } -func (m *Module) parseUserFromClaims(ctx context.Context, claims *oidc.Claims, ip net.IP, appID string) (*gtsmodel.User, error) { +func (m *Module) parseUserFromClaims(ctx context.Context, claims *oidc.Claims, ip net.IP, appID string) (*gtsmodel.User, gtserror.WithCode) { if claims.Email == "" { - return nil, errors.New("no email returned in claims") + err := errors.New("no email returned in claims") + return nil, gtserror.NewErrorBadRequest(err, err.Error()) } // see if we already have a user for this email address + // if so, we don't need to continue + create one user := >smodel.User{} err := m.db.GetWhere(ctx, []db.Where{{Key: "email", Value: claims.Email}}, user) if err == nil { - // we do! so we can just return it return user, nil } if err != db.ErrNoEntries { - // we have an actual error in the database - return nil, fmt.Errorf("error checking database for email %s: %s", claims.Email, err) + err := fmt.Errorf("error checking database for email %s: %s", claims.Email, err) + return nil, gtserror.NewErrorInternalError(err) } // maybe we have an unconfirmed user err = m.db.GetWhere(ctx, []db.Where{{Key: "unconfirmed_email", Value: claims.Email}}, user) if err == nil { - // user is unconfirmed so return an error - return nil, fmt.Errorf("user with email address %s is unconfirmed", claims.Email) + err := fmt.Errorf("user with email address %s is unconfirmed", claims.Email) + return nil, gtserror.NewErrorForbidden(err, err.Error()) } if err != db.ErrNoEntries { - // we have an actual error in the database - return nil, fmt.Errorf("error checking database for email %s: %s", claims.Email, err) + err := fmt.Errorf("error checking database for email %s: %s", claims.Email, err) + return nil, gtserror.NewErrorInternalError(err) } // we don't have a confirmed or unconfirmed user with the claimed email address @@ -138,10 +163,10 @@ func (m *Module) parseUserFromClaims(ctx context.Context, claims *oidc.Claims, i // check if the email address is available for use; if it's not there's nothing we can so emailAvailable, err := m.db.IsEmailAvailable(ctx, claims.Email) if err != nil { - return nil, fmt.Errorf("email %s not available: %s", claims.Email, err) + return nil, gtserror.NewErrorBadRequest(err) } if !emailAvailable { - return nil, fmt.Errorf("email %s in use", claims.Email) + return nil, gtserror.NewErrorConflict(fmt.Errorf("email address %s is not available", claims.Email)) } // now we need a username @@ -149,12 +174,12 @@ func (m *Module) parseUserFromClaims(ctx context.Context, claims *oidc.Claims, i // make sure claims.Name is defined since we'll be using that for the username if claims.Name == "" { - return nil, errors.New("no name returned in claims") + err := errors.New("no name returned in claims") + return nil, gtserror.NewErrorBadRequest(err, err.Error()) } // check if we can just use claims.Name as-is - err = validate.Username(claims.Name) - if err == nil { + if err = validate.Username(claims.Name); err == nil { // the name we have on the claims is already a valid username username = claims.Name } else { @@ -166,12 +191,12 @@ func (m *Module) parseUserFromClaims(ctx context.Context, claims *oidc.Claims, i // lowercase the whole thing lower := strings.ToLower(underscored) // see if this is valid.... - if err := validate.Username(lower); err == nil { - // we managed to get a valid username - username = lower - } else { - return nil, fmt.Errorf("couldn't parse a valid username from claims.Name value of %s", claims.Name) + if err := validate.Username(lower); err != nil { + err := fmt.Errorf("couldn't parse a valid username from claims.Name value of %s: %s", claims.Name, err) + return nil, gtserror.NewErrorBadRequest(err, err.Error()) } + // we managed to get a valid username + username = lower } var iString string @@ -185,7 +210,7 @@ func (m *Module) parseUserFromClaims(ctx context.Context, claims *oidc.Claims, i for i := 1; !found; i++ { usernameAvailable, err := m.db.IsUsernameAvailable(ctx, username+iString) if err != nil { - return nil, err + return nil, gtserror.NewErrorInternalError(err) } if usernameAvailable { // no error so we've found a username that works @@ -223,7 +248,7 @@ func (m *Module) parseUserFromClaims(ctx context.Context, claims *oidc.Claims, i // create the user! this will also create an account and store it in the database so we don't need to do that here user, err = m.db.NewSignup(ctx, username, "", requireApproval, claims.Email, password, ip, "", appID, emailVerified, admin) if err != nil { - return nil, fmt.Errorf("error creating user: %s", err) + return nil, gtserror.NewErrorInternalError(err) } return user, nil diff --git a/internal/api/client/auth/signin.go b/internal/api/client/auth/signin.go index bdf00c663..b8f267f54 100644 --- a/internal/api/client/auth/signin.go +++ b/internal/api/client/auth/signin.go @@ -21,14 +21,14 @@ package auth import ( "context" "errors" + "fmt" "net/http" - "github.com/sirupsen/logrus" - "github.com/gin-contrib/sessions" "github.com/gin-gonic/gin" "github.com/superseriousbusiness/gotosocial/internal/api" "github.com/superseriousbusiness/gotosocial/internal/db" + "github.com/superseriousbusiness/gotosocial/internal/gtserror" "github.com/superseriousbusiness/gotosocial/internal/gtsmodel" "golang.org/x/crypto/bcrypt" ) @@ -41,64 +41,62 @@ type login struct { // SignInGETHandler should be served at https://example.org/auth/sign_in. // The idea is to present a sign in page to the user, where they can enter their username and password. -// The form will then POST to the sign in page, which will be handled by SignInPOSTHandler +// The form will then POST to the sign in page, which will be handled by SignInPOSTHandler. +// If an idp provider is set, then the user will be redirected to that to do their sign in. func (m *Module) SignInGETHandler(c *gin.Context) { - l := logrus.WithField("func", "SignInGETHandler") - l.Trace("entering sign in handler") - if _, err := api.NegotiateAccept(c, api.HTMLAcceptHeaders...); err != nil { - c.JSON(http.StatusNotAcceptable, gin.H{"error": err.Error()}) + api.ErrorHandler(c, gtserror.NewErrorNotAcceptable(err, err.Error()), m.processor.InstanceGet) return } - if m.idp != nil { - s := sessions.Default(c) + if m.idp == nil { + // no idp provider, use our own funky little sign in page + c.HTML(http.StatusOK, "sign-in.tmpl", gin.H{}) + return + } - stateI := s.Get(sessionState) - state, ok := stateI.(string) - if !ok { - m.clearSession(s) - c.JSON(http.StatusForbidden, gin.H{"error": "state not found in session"}) - return - } + // idp provider is in use, so redirect to it + s := sessions.Default(c) - redirect := m.idp.AuthCodeURL(state) - l.Debugf("redirecting to external idp at %s", redirect) - c.Redirect(http.StatusSeeOther, redirect) + stateI := s.Get(sessionState) + state, ok := stateI.(string) + if !ok { + m.clearSession(s) + err := fmt.Errorf("key %s was not found in session", sessionState) + api.ErrorHandler(c, gtserror.NewErrorBadRequest(err, err.Error()), m.processor.InstanceGet) return } - c.HTML(http.StatusOK, "sign-in.tmpl", gin.H{}) + + c.Redirect(http.StatusSeeOther, m.idp.AuthCodeURL(state)) } // SignInPOSTHandler should be served at https://example.org/auth/sign_in. // The idea is to present a sign in page to the user, where they can enter their username and password. // The handler will then redirect to the auth handler served at /auth func (m *Module) SignInPOSTHandler(c *gin.Context) { - l := logrus.WithField("func", "SignInPOSTHandler") s := sessions.Default(c) + form := &login{} if err := c.ShouldBind(form); err != nil { - c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) m.clearSession(s) + api.ErrorHandler(c, gtserror.NewErrorBadRequest(err, helpfulAdvice), m.processor.InstanceGet) return } - l.Tracef("parsed form: %+v", form) - userid, err := m.ValidatePassword(c.Request.Context(), form.Email, form.Password) - if err != nil { - c.String(http.StatusForbidden, err.Error()) - m.clearSession(s) + userid, errWithCode := m.ValidatePassword(c.Request.Context(), form.Email, form.Password) + if errWithCode != nil { + // don't clear session here, so the user can just press back and try again + // if they accidentally gave the wrong password or something + api.ErrorHandler(c, errWithCode, m.processor.InstanceGet) return } s.Set(sessionUserID, userid) if err := s.Save(); err != nil { - c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) - m.clearSession(s) - return + err := fmt.Errorf("error saving user id onto session: %s", err) + api.ErrorHandler(c, gtserror.NewErrorInternalError(err, helpfulAdvice), m.processor.InstanceGet) } - l.Trace("redirecting to auth page") c.Redirect(http.StatusFound, OauthAuthorizePath) } @@ -106,42 +104,34 @@ func (m *Module) SignInPOSTHandler(c *gin.Context) { // The goal is to authenticate the password against the one for that email // address stored in the database. If OK, we return the userid (a ulid) for that user, // so that it can be used in further Oauth flows to generate a token/retreieve an oauth client from the db. -func (m *Module) ValidatePassword(ctx context.Context, email string, password string) (userid string, err error) { - l := logrus.WithField("func", "ValidatePassword") - - // make sure an email/password was provided and bail if not +func (m *Module) ValidatePassword(ctx context.Context, email string, password string) (string, gtserror.WithCode) { if email == "" || password == "" { - l.Debug("email or password was not provided") - return incorrectPassword() + err := errors.New("email or password was not provided") + return incorrectPassword(err) } - // first we select the user from the database based on email address, bail if no user found for that email - gtsUser := >smodel.User{} - - if err := m.db.GetWhere(ctx, []db.Where{{Key: "email", Value: email}}, gtsUser); err != nil { - l.Debugf("user %s was not retrievable from db during oauth authorization attempt: %s", email, err) - return incorrectPassword() + user := >smodel.User{} + if err := m.db.GetWhere(ctx, []db.Where{{Key: "email", Value: email}}, user); err != nil { + err := fmt.Errorf("user %s was not retrievable from db during oauth authorization attempt: %s", email, err) + return incorrectPassword(err) } - // make sure a password is actually set and bail if not - if gtsUser.EncryptedPassword == "" { - l.Warnf("encrypted password for user %s was empty for some reason", gtsUser.Email) - return incorrectPassword() + if user.EncryptedPassword == "" { + err := fmt.Errorf("encrypted password for user %s was empty for some reason", user.Email) + return incorrectPassword(err) } - // compare the provided password with the encrypted one from the db, bail if they don't match - if err := bcrypt.CompareHashAndPassword([]byte(gtsUser.EncryptedPassword), []byte(password)); err != nil { - l.Debugf("password hash didn't match for user %s during login attempt: %s", gtsUser.Email, err) - return incorrectPassword() + if err := bcrypt.CompareHashAndPassword([]byte(user.EncryptedPassword), []byte(password)); err != nil { + err := fmt.Errorf("password hash didn't match for user %s during login attempt: %s", user.Email, err) + return incorrectPassword(err) } - // If we've made it this far the email/password is correct, so we can just return the id of the user. - userid = gtsUser.ID - l.Tracef("returning (%s, %s)", userid, err) - return + return user.ID, nil } -// incorrectPassword is just a little helper function to use in the ValidatePassword function -func incorrectPassword() (string, error) { - return "", errors.New("password/email combination was incorrect") +// incorrectPassword wraps the given error in a gtserror.WithCode, and returns +// only a generic 'safe' error message to the user, to not give any info away. +func incorrectPassword(err error) (string, gtserror.WithCode) { + safeErr := fmt.Errorf("password/email combination was incorrect") + return "", gtserror.NewErrorUnauthorized(err, safeErr.Error(), helpfulAdvice) } diff --git a/internal/api/client/auth/token.go b/internal/api/client/auth/token.go index a0bc7ae93..34fb62940 100644 --- a/internal/api/client/auth/token.go +++ b/internal/api/client/auth/token.go @@ -19,11 +19,10 @@ package auth import ( - "net/http" "net/url" - "github.com/sirupsen/logrus" "github.com/superseriousbusiness/gotosocial/internal/api" + "github.com/superseriousbusiness/gotosocial/internal/gtserror" "github.com/gin-gonic/gin" ) @@ -40,38 +39,40 @@ type tokenBody struct { // TokenPOSTHandler should be served as a POST at https://example.org/oauth/token // The idea here is to serve an oauth access token to a user, which can be used for authorizing against non-public APIs. func (m *Module) TokenPOSTHandler(c *gin.Context) { - l := logrus.WithField("func", "TokenPOSTHandler") - l.Trace("entered TokenPOSTHandler") - if _, err := api.NegotiateAccept(c, api.JSONAcceptHeaders...); err != nil { - c.JSON(http.StatusNotAcceptable, gin.H{"error": err.Error()}) + api.ErrorHandler(c, gtserror.NewErrorNotAcceptable(err, err.Error()), m.processor.InstanceGet) return } form := &tokenBody{} - if err := c.ShouldBind(form); err == nil { - c.Request.Form = url.Values{} - if form.ClientID != nil { - c.Request.Form.Set("client_id", *form.ClientID) - } - if form.ClientSecret != nil { - c.Request.Form.Set("client_secret", *form.ClientSecret) - } - if form.Code != nil { - c.Request.Form.Set("code", *form.Code) - } - if form.GrantType != nil { - c.Request.Form.Set("grant_type", *form.GrantType) - } - if form.RedirectURI != nil { - c.Request.Form.Set("redirect_uri", *form.RedirectURI) - } - if form.Scope != nil { - c.Request.Form.Set("scope", *form.Scope) - } + if err := c.ShouldBind(form); err != nil { + api.ErrorHandler(c, gtserror.NewErrorBadRequest(err, helpfulAdvice), m.processor.InstanceGet) + return + } + + c.Request.Form = url.Values{} + if form.ClientID != nil { + c.Request.Form.Set("client_id", *form.ClientID) + } + if form.ClientSecret != nil { + c.Request.Form.Set("client_secret", *form.ClientSecret) + } + if form.Code != nil { + c.Request.Form.Set("code", *form.Code) + } + if form.GrantType != nil { + c.Request.Form.Set("grant_type", *form.GrantType) + } + if form.RedirectURI != nil { + c.Request.Form.Set("redirect_uri", *form.RedirectURI) + } + if form.Scope != nil { + c.Request.Form.Set("scope", *form.Scope) } + // pass the writer and request into the oauth server handler, which will + // take care of writing the oauth token into the response etc if err := m.server.HandleTokenRequest(c.Writer, c.Request); err != nil { - c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + api.ErrorHandler(c, gtserror.NewErrorInternalError(err, helpfulAdvice), m.processor.InstanceGet) } } |