From dafc3b5b92865b97be48456e02ad235f4c79cf4e Mon Sep 17 00:00:00 2001 From: tsmethurst Date: Tue, 20 Apr 2021 18:14:23 +0200 Subject: linting + organizing --- internal/apimodule/account/account.go | 47 +- internal/apimodule/account/accountcreate.go | 6 +- internal/apimodule/account/accountcreate_test.go | 550 -------------------- internal/apimodule/account/accountget.go | 6 +- internal/apimodule/account/accountupdate.go | 8 +- internal/apimodule/account/accountupdate_test.go | 302 ----------- internal/apimodule/account/accountverify.go | 4 +- internal/apimodule/account/accountverify_test.go | 19 - .../apimodule/account/test/accountcreate_test.go | 551 +++++++++++++++++++++ .../apimodule/account/test/accountupdate_test.go | 303 +++++++++++ .../apimodule/account/test/accountverify_test.go | 19 + internal/apimodule/admin/admin.go | 24 +- internal/apimodule/admin/emojicreate.go | 2 +- internal/apimodule/app/app.go | 15 +- internal/apimodule/app/app_test.go | 21 - internal/apimodule/app/appcreate.go | 4 +- internal/apimodule/app/test/app_test.go | 21 + internal/apimodule/auth/README.md | 5 - internal/apimodule/auth/auth.go | 37 +- internal/apimodule/auth/auth_test.go | 166 ------- internal/apimodule/auth/authorize.go | 10 +- internal/apimodule/auth/middleware.go | 4 +- internal/apimodule/auth/signin.go | 17 +- internal/apimodule/auth/test/auth_test.go | 166 +++++++ internal/apimodule/auth/token.go | 4 +- internal/apimodule/fileserver/fileserver.go | 7 +- .../apimodule/fileserver/test/servefile_test.go | 2 +- internal/apimodule/media/media.go | 15 +- internal/apimodule/media/mediacreate.go | 3 +- internal/apimodule/media/test/mediacreate_test.go | 8 +- internal/apimodule/security/flocblock.go | 5 +- internal/apimodule/security/security.go | 14 +- internal/apimodule/status/status.go | 34 +- internal/apimodule/status/statuscreate.go | 19 +- internal/apimodule/status/statusdelete.go | 3 +- internal/apimodule/status/statusfave.go | 3 +- internal/apimodule/status/statusfavedby.go | 3 +- internal/apimodule/status/statusget.go | 3 +- internal/apimodule/status/statusunfave.go | 3 +- .../apimodule/status/test/statuscreate_test.go | 16 +- internal/apimodule/status/test/statusfave_test.go | 10 +- .../apimodule/status/test/statusfavedby_test.go | 8 +- internal/apimodule/status/test/statusget_test.go | 6 +- .../apimodule/status/test/statusunfave_test.go | 10 +- 44 files changed, 1264 insertions(+), 1219 deletions(-) delete mode 100644 internal/apimodule/account/accountcreate_test.go delete mode 100644 internal/apimodule/account/accountupdate_test.go delete mode 100644 internal/apimodule/account/accountverify_test.go create mode 100644 internal/apimodule/account/test/accountcreate_test.go create mode 100644 internal/apimodule/account/test/accountupdate_test.go create mode 100644 internal/apimodule/account/test/accountverify_test.go delete mode 100644 internal/apimodule/app/app_test.go create mode 100644 internal/apimodule/app/test/app_test.go delete mode 100644 internal/apimodule/auth/README.md delete mode 100644 internal/apimodule/auth/auth_test.go create mode 100644 internal/apimodule/auth/test/auth_test.go (limited to 'internal/apimodule') diff --git a/internal/apimodule/account/account.go b/internal/apimodule/account/account.go index f4a47f6a2..a836afcdb 100644 --- a/internal/apimodule/account/account.go +++ b/internal/apimodule/account/account.go @@ -37,25 +37,31 @@ import ( ) const ( - idKey = "id" - basePath = "/api/v1/accounts" - basePathWithID = basePath + "/:" + idKey - verifyPath = basePath + "/verify_credentials" - updateCredentialsPath = basePath + "/update_credentials" + // IDKey is the key to use for retrieving account ID in requests + IDKey = "id" + // BasePath is the base API path for this module + BasePath = "/api/v1/accounts" + // BasePathWithID is the base path for this module with the ID key + BasePathWithID = BasePath + "/:" + IDKey + // VerifyPath is for verifying account credentials + VerifyPath = BasePath + "/verify_credentials" + // UpdateCredentialsPath is for updating account credentials + UpdateCredentialsPath = BasePath + "/update_credentials" ) -type accountModule struct { +// Module implements the ClientAPIModule interface for account-related actions +type Module struct { config *config.Config db db.DB oauthServer oauth.Server - mediaHandler media.MediaHandler + mediaHandler media.Handler mastoConverter mastotypes.Converter log *logrus.Logger } // New returns a new account module -func New(config *config.Config, db db.DB, oauthServer oauth.Server, mediaHandler media.MediaHandler, mastoConverter mastotypes.Converter, log *logrus.Logger) apimodule.ClientAPIModule { - return &accountModule{ +func New(config *config.Config, db db.DB, oauthServer oauth.Server, mediaHandler media.Handler, mastoConverter mastotypes.Converter, log *logrus.Logger) apimodule.ClientAPIModule { + return &Module{ config: config, db: db, oauthServer: oauthServer, @@ -66,14 +72,15 @@ func New(config *config.Config, db db.DB, oauthServer oauth.Server, mediaHandler } // Route attaches all routes from this module to the given router -func (m *accountModule) Route(r router.Router) error { - r.AttachHandler(http.MethodPost, basePath, m.accountCreatePOSTHandler) - r.AttachHandler(http.MethodGet, basePathWithID, m.muxHandler) - r.AttachHandler(http.MethodPatch, basePathWithID, m.muxHandler) +func (m *Module) Route(r router.Router) error { + r.AttachHandler(http.MethodPost, BasePath, m.AccountCreatePOSTHandler) + r.AttachHandler(http.MethodGet, BasePathWithID, m.muxHandler) + r.AttachHandler(http.MethodPatch, BasePathWithID, m.muxHandler) return nil } -func (m *accountModule) CreateTables(db db.DB) error { +// CreateTables creates the required tables for this module in the given database +func (m *Module) CreateTables(db db.DB) error { models := []interface{}{ >smodel.User{}, >smodel.Account{}, @@ -93,18 +100,18 @@ func (m *accountModule) CreateTables(db db.DB) error { return nil } -func (m *accountModule) muxHandler(c *gin.Context) { +func (m *Module) muxHandler(c *gin.Context) { ru := c.Request.RequestURI switch c.Request.Method { case http.MethodGet: - if strings.HasPrefix(ru, verifyPath) { - m.accountVerifyGETHandler(c) + if strings.HasPrefix(ru, VerifyPath) { + m.AccountVerifyGETHandler(c) } else { - m.accountGETHandler(c) + m.AccountGETHandler(c) } case http.MethodPatch: - if strings.HasPrefix(ru, updateCredentialsPath) { - m.accountUpdateCredentialsPATCHHandler(c) + if strings.HasPrefix(ru, UpdateCredentialsPath) { + m.AccountUpdateCredentialsPATCHHandler(c) } } } diff --git a/internal/apimodule/account/accountcreate.go b/internal/apimodule/account/accountcreate.go index 266d820af..fb21925b8 100644 --- a/internal/apimodule/account/accountcreate.go +++ b/internal/apimodule/account/accountcreate.go @@ -34,10 +34,10 @@ import ( "github.com/superseriousbusiness/oauth2/v4" ) -// accountCreatePOSTHandler handles create account requests, validates them, +// AccountCreatePOSTHandler handles create account requests, validates them, // and puts them in the database if they're valid. // It should be served as a POST at /api/v1/accounts -func (m *accountModule) accountCreatePOSTHandler(c *gin.Context) { +func (m *Module) AccountCreatePOSTHandler(c *gin.Context) { l := m.log.WithField("func", "accountCreatePOSTHandler") authed, err := oauth.MustAuth(c, true, true, false, false) if err != nil { @@ -83,7 +83,7 @@ func (m *accountModule) accountCreatePOSTHandler(c *gin.Context) { // accountCreate does the dirty work of making an account and user in the database. // It then returns a token to the caller, for use with the new account, as per the // spec here: https://docs.joinmastodon.org/methods/accounts/ -func (m *accountModule) accountCreate(form *mastotypes.AccountCreateRequest, signUpIP net.IP, token oauth2.TokenInfo, app *gtsmodel.Application) (*mastotypes.Token, error) { +func (m *Module) accountCreate(form *mastotypes.AccountCreateRequest, signUpIP net.IP, token oauth2.TokenInfo, app *gtsmodel.Application) (*mastotypes.Token, error) { l := m.log.WithField("func", "accountCreate") // don't store a reason if we don't require one diff --git a/internal/apimodule/account/accountcreate_test.go b/internal/apimodule/account/accountcreate_test.go deleted file mode 100644 index 8677e3573..000000000 --- a/internal/apimodule/account/accountcreate_test.go +++ /dev/null @@ -1,550 +0,0 @@ -/* - GoToSocial - Copyright (C) 2021 GoToSocial Authors admin@gotosocial.org - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Affero General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Affero General Public License for more details. - - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . -*/ - -package account - -import ( - "bytes" - "context" - "encoding/json" - "fmt" - "io" - "io/ioutil" - "mime/multipart" - "net/http" - "net/http/httptest" - "net/url" - "os" - "testing" - "time" - - "github.com/gin-gonic/gin" - "github.com/google/uuid" - "github.com/sirupsen/logrus" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/mock" - "github.com/stretchr/testify/suite" - "github.com/superseriousbusiness/gotosocial/internal/config" - "github.com/superseriousbusiness/gotosocial/internal/db" - "github.com/superseriousbusiness/gotosocial/internal/db/gtsmodel" - "github.com/superseriousbusiness/gotosocial/internal/mastotypes" - mastomodel "github.com/superseriousbusiness/gotosocial/internal/mastotypes/mastomodel" - - "github.com/superseriousbusiness/gotosocial/internal/media" - "github.com/superseriousbusiness/gotosocial/internal/oauth" - "github.com/superseriousbusiness/gotosocial/internal/storage" - "github.com/superseriousbusiness/oauth2/v4" - "github.com/superseriousbusiness/oauth2/v4/models" - oauthmodels "github.com/superseriousbusiness/oauth2/v4/models" - "golang.org/x/crypto/bcrypt" -) - -type AccountCreateTestSuite struct { - suite.Suite - config *config.Config - log *logrus.Logger - testAccountLocal *gtsmodel.Account - testApplication *gtsmodel.Application - testToken oauth2.TokenInfo - mockOauthServer *oauth.MockServer - mockStorage *storage.MockStorage - mediaHandler media.MediaHandler - mastoConverter mastotypes.Converter - db db.DB - accountModule *accountModule - newUserFormHappyPath url.Values -} - -/* - TEST INFRASTRUCTURE -*/ - -// SetupSuite sets some variables on the suite that we can use as consts (more or less) throughout -func (suite *AccountCreateTestSuite) SetupSuite() { - // some of our subsequent entities need a log so create this here - log := logrus.New() - log.SetLevel(logrus.TraceLevel) - suite.log = log - - suite.testAccountLocal = >smodel.Account{ - ID: uuid.NewString(), - Username: "test_user", - } - - // can use this test application throughout - suite.testApplication = >smodel.Application{ - ID: "weeweeeeeeeeeeeeee", - Name: "a test application", - Website: "https://some-application-website.com", - RedirectURI: "http://localhost:8080", - ClientID: "a-known-client-id", - ClientSecret: "some-secret", - Scopes: "read", - VapidKey: "aaaaaa-aaaaaaaa-aaaaaaaaaaa", - } - - // can use this test token throughout - suite.testToken = &oauthmodels.Token{ - ClientID: "a-known-client-id", - RedirectURI: "http://localhost:8080", - Scope: "read", - Code: "123456789", - CodeCreateAt: time.Now(), - CodeExpiresIn: time.Duration(10 * time.Minute), - } - - // Direct config to local postgres instance - c := config.Empty() - c.Protocol = "http" - c.Host = "localhost" - c.DBConfig = &config.DBConfig{ - Type: "postgres", - Address: "localhost", - Port: 5432, - User: "postgres", - Password: "postgres", - Database: "postgres", - ApplicationName: "gotosocial", - } - c.MediaConfig = &config.MediaConfig{ - MaxImageSize: 2 << 20, - } - c.StorageConfig = &config.StorageConfig{ - Backend: "local", - BasePath: "/tmp", - ServeProtocol: "http", - ServeHost: "localhost", - ServeBasePath: "/fileserver/media", - } - suite.config = c - - // use an actual database for this, because it's just easier than mocking one out - database, err := db.New(context.Background(), c, log) - if err != nil { - suite.FailNow(err.Error()) - } - suite.db = database - - // we need to mock the oauth server because account creation needs it to create a new token - suite.mockOauthServer = &oauth.MockServer{} - suite.mockOauthServer.On("GenerateUserAccessToken", suite.testToken, suite.testApplication.ClientSecret, mock.AnythingOfType("string")).Run(func(args mock.Arguments) { - l := suite.log.WithField("func", "GenerateUserAccessToken") - token := args.Get(0).(oauth2.TokenInfo) - l.Infof("received token %+v", token) - clientSecret := args.Get(1).(string) - l.Infof("received clientSecret %+v", clientSecret) - userID := args.Get(2).(string) - l.Infof("received userID %+v", userID) - }).Return(&models.Token{ - Access: "we're authorized now!", - }, nil) - - suite.mockStorage = &storage.MockStorage{} - // We don't need storage to do anything for these tests, so just simulate a success and do nothing -- we won't need to return anything from storage - suite.mockStorage.On("StoreFileAt", mock.AnythingOfType("string"), mock.AnythingOfType("[]uint8")).Return(nil) - - // set a media handler because some handlers (eg update credentials) need to upload media (new header/avatar) - suite.mediaHandler = media.New(suite.config, suite.db, suite.mockStorage, log) - - suite.mastoConverter = mastotypes.New(suite.config, suite.db) - - // and finally here's the thing we're actually testing! - suite.accountModule = New(suite.config, suite.db, suite.mockOauthServer, suite.mediaHandler, suite.mastoConverter, suite.log).(*accountModule) -} - -func (suite *AccountCreateTestSuite) TearDownSuite() { - if err := suite.db.Stop(context.Background()); err != nil { - logrus.Panicf("error closing db connection: %s", err) - } -} - -// SetupTest creates a db connection and creates necessary tables before each test -func (suite *AccountCreateTestSuite) SetupTest() { - // create all the tables we might need in thie suite - models := []interface{}{ - >smodel.User{}, - >smodel.Account{}, - >smodel.Follow{}, - >smodel.FollowRequest{}, - >smodel.Status{}, - >smodel.Application{}, - >smodel.EmailDomainBlock{}, - >smodel.MediaAttachment{}, - } - for _, m := range models { - if err := suite.db.CreateTable(m); err != nil { - logrus.Panicf("db connection error: %s", err) - } - } - - // form to submit for happy path account create requests -- this will be changed inside tests so it's better to set it before each test - suite.newUserFormHappyPath = url.Values{ - "reason": []string{"a very good reason that's at least 40 characters i swear"}, - "username": []string{"test_user"}, - "email": []string{"user@example.org"}, - "password": []string{"very-strong-password"}, - "agreement": []string{"true"}, - "locale": []string{"en"}, - } - - // same with accounts config - suite.config.AccountsConfig = &config.AccountsConfig{ - OpenRegistration: true, - RequireApproval: true, - ReasonRequired: true, - } -} - -// TearDownTest drops tables to make sure there's no data in the db -func (suite *AccountCreateTestSuite) TearDownTest() { - - // remove all the tables we might have used so it's clear for the next test - models := []interface{}{ - >smodel.User{}, - >smodel.Account{}, - >smodel.Follow{}, - >smodel.FollowRequest{}, - >smodel.Status{}, - >smodel.Application{}, - >smodel.EmailDomainBlock{}, - >smodel.MediaAttachment{}, - } - for _, m := range models { - if err := suite.db.DropTable(m); err != nil { - logrus.Panicf("error dropping table: %s", err) - } - } -} - -/* - ACTUAL TESTS -*/ - -/* - TESTING: AccountCreatePOSTHandler -*/ - -// TestAccountCreatePOSTHandlerSuccessful checks the happy path for an account creation request: all the fields provided are valid, -// and at the end of it a new user and account should be added into the database. -// -// This is the handler served at /api/v1/accounts as POST -func (suite *AccountCreateTestSuite) TestAccountCreatePOSTHandlerSuccessful() { - - // setup - recorder := httptest.NewRecorder() - ctx, _ := gin.CreateTestContext(recorder) - ctx.Set(oauth.SessionAuthorizedApplication, suite.testApplication) - ctx.Set(oauth.SessionAuthorizedToken, suite.testToken) - ctx.Request = httptest.NewRequest(http.MethodPost, fmt.Sprintf("http://localhost:8080/%s", basePath), nil) // the endpoint we're hitting - ctx.Request.Form = suite.newUserFormHappyPath - suite.accountModule.accountCreatePOSTHandler(ctx) - - // check response - - // 1. we should have OK from our call to the function - suite.EqualValues(http.StatusOK, recorder.Code) - - // 2. we should have a token in the result body - result := recorder.Result() - defer result.Body.Close() - b, err := ioutil.ReadAll(result.Body) - assert.NoError(suite.T(), err) - t := &mastomodel.Token{} - err = json.Unmarshal(b, t) - assert.NoError(suite.T(), err) - assert.Equal(suite.T(), "we're authorized now!", t.AccessToken) - - // check new account - - // 1. we should be able to get the new account from the db - acct := >smodel.Account{} - err = suite.db.GetWhere("username", "test_user", acct) - assert.NoError(suite.T(), err) - assert.NotNil(suite.T(), acct) - // 2. reason should be set - assert.Equal(suite.T(), suite.newUserFormHappyPath.Get("reason"), acct.Reason) - // 3. display name should be equal to username by default - assert.Equal(suite.T(), suite.newUserFormHappyPath.Get("username"), acct.DisplayName) - // 4. domain should be nil because this is a local account - assert.Nil(suite.T(), nil, acct.Domain) - // 5. id should be set and parseable as a uuid - assert.NotNil(suite.T(), acct.ID) - _, err = uuid.Parse(acct.ID) - assert.Nil(suite.T(), err) - // 6. private and public key should be set - assert.NotNil(suite.T(), acct.PrivateKey) - assert.NotNil(suite.T(), acct.PublicKey) - - // check new user - - // 1. we should be able to get the new user from the db - usr := >smodel.User{} - err = suite.db.GetWhere("unconfirmed_email", suite.newUserFormHappyPath.Get("email"), usr) - assert.Nil(suite.T(), err) - assert.NotNil(suite.T(), usr) - - // 2. user should have account id set to account we got above - assert.Equal(suite.T(), acct.ID, usr.AccountID) - - // 3. id should be set and parseable as a uuid - assert.NotNil(suite.T(), usr.ID) - _, err = uuid.Parse(usr.ID) - assert.Nil(suite.T(), err) - - // 4. locale should be equal to what we requested - assert.Equal(suite.T(), suite.newUserFormHappyPath.Get("locale"), usr.Locale) - - // 5. created by application id should be equal to the app id - assert.Equal(suite.T(), suite.testApplication.ID, usr.CreatedByApplicationID) - - // 6. password should be matcheable to what we set above - err = bcrypt.CompareHashAndPassword([]byte(usr.EncryptedPassword), []byte(suite.newUserFormHappyPath.Get("password"))) - assert.Nil(suite.T(), err) -} - -// TestAccountCreatePOSTHandlerNoAuth makes sure that the handler fails when no authorization is provided: -// only registered applications can create accounts, and we don't provide one here. -func (suite *AccountCreateTestSuite) TestAccountCreatePOSTHandlerNoAuth() { - - // setup - recorder := httptest.NewRecorder() - ctx, _ := gin.CreateTestContext(recorder) - ctx.Request = httptest.NewRequest(http.MethodPost, fmt.Sprintf("http://localhost:8080/%s", basePath), nil) // the endpoint we're hitting - ctx.Request.Form = suite.newUserFormHappyPath - suite.accountModule.accountCreatePOSTHandler(ctx) - - // check response - - // 1. we should have forbidden from our call to the function because we didn't auth - suite.EqualValues(http.StatusForbidden, recorder.Code) - - // 2. we should have an error message in the result body - result := recorder.Result() - defer result.Body.Close() - b, err := ioutil.ReadAll(result.Body) - assert.NoError(suite.T(), err) - assert.Equal(suite.T(), `{"error":"not authorized"}`, string(b)) -} - -// TestAccountCreatePOSTHandlerNoAuth makes sure that the handler fails when no form is provided at all. -func (suite *AccountCreateTestSuite) TestAccountCreatePOSTHandlerNoForm() { - - // setup - recorder := httptest.NewRecorder() - ctx, _ := gin.CreateTestContext(recorder) - ctx.Set(oauth.SessionAuthorizedApplication, suite.testApplication) - ctx.Set(oauth.SessionAuthorizedToken, suite.testToken) - ctx.Request = httptest.NewRequest(http.MethodPost, fmt.Sprintf("http://localhost:8080/%s", basePath), nil) // the endpoint we're hitting - suite.accountModule.accountCreatePOSTHandler(ctx) - - // check response - suite.EqualValues(http.StatusBadRequest, recorder.Code) - - // 2. we should have an error message in the result body - result := recorder.Result() - defer result.Body.Close() - b, err := ioutil.ReadAll(result.Body) - assert.NoError(suite.T(), err) - assert.Equal(suite.T(), `{"error":"missing one or more required form values"}`, string(b)) -} - -// TestAccountCreatePOSTHandlerWeakPassword makes sure that the handler fails when a weak password is provided -func (suite *AccountCreateTestSuite) TestAccountCreatePOSTHandlerWeakPassword() { - - // setup - recorder := httptest.NewRecorder() - ctx, _ := gin.CreateTestContext(recorder) - ctx.Set(oauth.SessionAuthorizedApplication, suite.testApplication) - ctx.Set(oauth.SessionAuthorizedToken, suite.testToken) - ctx.Request = httptest.NewRequest(http.MethodPost, fmt.Sprintf("http://localhost:8080/%s", basePath), nil) // the endpoint we're hitting - ctx.Request.Form = suite.newUserFormHappyPath - // set a weak password - ctx.Request.Form.Set("password", "weak") - suite.accountModule.accountCreatePOSTHandler(ctx) - - // check response - suite.EqualValues(http.StatusBadRequest, recorder.Code) - - // 2. we should have an error message in the result body - result := recorder.Result() - defer result.Body.Close() - b, err := ioutil.ReadAll(result.Body) - assert.NoError(suite.T(), err) - assert.Equal(suite.T(), `{"error":"insecure password, try including more special characters, using uppercase letters, using numbers or using a longer password"}`, string(b)) -} - -// TestAccountCreatePOSTHandlerWeirdLocale makes sure that the handler fails when a weird locale is provided -func (suite *AccountCreateTestSuite) TestAccountCreatePOSTHandlerWeirdLocale() { - - // setup - recorder := httptest.NewRecorder() - ctx, _ := gin.CreateTestContext(recorder) - ctx.Set(oauth.SessionAuthorizedApplication, suite.testApplication) - ctx.Set(oauth.SessionAuthorizedToken, suite.testToken) - ctx.Request = httptest.NewRequest(http.MethodPost, fmt.Sprintf("http://localhost:8080/%s", basePath), nil) // the endpoint we're hitting - ctx.Request.Form = suite.newUserFormHappyPath - // set an invalid locale - ctx.Request.Form.Set("locale", "neverneverland") - suite.accountModule.accountCreatePOSTHandler(ctx) - - // check response - suite.EqualValues(http.StatusBadRequest, recorder.Code) - - // 2. we should have an error message in the result body - result := recorder.Result() - defer result.Body.Close() - b, err := ioutil.ReadAll(result.Body) - assert.NoError(suite.T(), err) - assert.Equal(suite.T(), `{"error":"language: tag is not well-formed"}`, string(b)) -} - -// TestAccountCreatePOSTHandlerRegistrationsClosed makes sure that the handler fails when registrations are closed -func (suite *AccountCreateTestSuite) TestAccountCreatePOSTHandlerRegistrationsClosed() { - - // setup - recorder := httptest.NewRecorder() - ctx, _ := gin.CreateTestContext(recorder) - ctx.Set(oauth.SessionAuthorizedApplication, suite.testApplication) - ctx.Set(oauth.SessionAuthorizedToken, suite.testToken) - ctx.Request = httptest.NewRequest(http.MethodPost, fmt.Sprintf("http://localhost:8080/%s", basePath), nil) // the endpoint we're hitting - ctx.Request.Form = suite.newUserFormHappyPath - - // close registrations - suite.config.AccountsConfig.OpenRegistration = false - suite.accountModule.accountCreatePOSTHandler(ctx) - - // check response - suite.EqualValues(http.StatusBadRequest, recorder.Code) - - // 2. we should have an error message in the result body - result := recorder.Result() - defer result.Body.Close() - b, err := ioutil.ReadAll(result.Body) - assert.NoError(suite.T(), err) - assert.Equal(suite.T(), `{"error":"registration is not open for this server"}`, string(b)) -} - -// TestAccountCreatePOSTHandlerReasonNotProvided makes sure that the handler fails when no reason is provided but one is required -func (suite *AccountCreateTestSuite) TestAccountCreatePOSTHandlerReasonNotProvided() { - - // setup - recorder := httptest.NewRecorder() - ctx, _ := gin.CreateTestContext(recorder) - ctx.Set(oauth.SessionAuthorizedApplication, suite.testApplication) - ctx.Set(oauth.SessionAuthorizedToken, suite.testToken) - ctx.Request = httptest.NewRequest(http.MethodPost, fmt.Sprintf("http://localhost:8080/%s", basePath), nil) // the endpoint we're hitting - ctx.Request.Form = suite.newUserFormHappyPath - - // remove reason - ctx.Request.Form.Set("reason", "") - - suite.accountModule.accountCreatePOSTHandler(ctx) - - // check response - suite.EqualValues(http.StatusBadRequest, recorder.Code) - - // 2. we should have an error message in the result body - result := recorder.Result() - defer result.Body.Close() - b, err := ioutil.ReadAll(result.Body) - assert.NoError(suite.T(), err) - assert.Equal(suite.T(), `{"error":"no reason provided"}`, string(b)) -} - -// TestAccountCreatePOSTHandlerReasonNotProvided makes sure that the handler fails when a crappy reason is presented but a good one is required -func (suite *AccountCreateTestSuite) TestAccountCreatePOSTHandlerInsufficientReason() { - - // setup - recorder := httptest.NewRecorder() - ctx, _ := gin.CreateTestContext(recorder) - ctx.Set(oauth.SessionAuthorizedApplication, suite.testApplication) - ctx.Set(oauth.SessionAuthorizedToken, suite.testToken) - ctx.Request = httptest.NewRequest(http.MethodPost, fmt.Sprintf("http://localhost:8080/%s", basePath), nil) // the endpoint we're hitting - ctx.Request.Form = suite.newUserFormHappyPath - - // remove reason - ctx.Request.Form.Set("reason", "just cuz") - - suite.accountModule.accountCreatePOSTHandler(ctx) - - // check response - suite.EqualValues(http.StatusBadRequest, recorder.Code) - - // 2. we should have an error message in the result body - result := recorder.Result() - defer result.Body.Close() - b, err := ioutil.ReadAll(result.Body) - assert.NoError(suite.T(), err) - assert.Equal(suite.T(), `{"error":"reason should be at least 40 chars but 'just cuz' was 8"}`, string(b)) -} - -/* - TESTING: AccountUpdateCredentialsPATCHHandler -*/ - -func (suite *AccountCreateTestSuite) TestAccountUpdateCredentialsPATCHHandler() { - - // put test local account in db - err := suite.db.Put(suite.testAccountLocal) - assert.NoError(suite.T(), err) - - // attach avatar to request - aviFile, err := os.Open("../../media/test/test-jpeg.jpg") - assert.NoError(suite.T(), err) - body := &bytes.Buffer{} - writer := multipart.NewWriter(body) - - part, err := writer.CreateFormFile("avatar", "test-jpeg.jpg") - assert.NoError(suite.T(), err) - - _, err = io.Copy(part, aviFile) - assert.NoError(suite.T(), err) - - err = aviFile.Close() - assert.NoError(suite.T(), err) - - err = writer.Close() - assert.NoError(suite.T(), err) - - // setup - recorder := httptest.NewRecorder() - ctx, _ := gin.CreateTestContext(recorder) - ctx.Set(oauth.SessionAuthorizedAccount, suite.testAccountLocal) - ctx.Set(oauth.SessionAuthorizedToken, suite.testToken) - ctx.Request = httptest.NewRequest(http.MethodPatch, fmt.Sprintf("http://localhost:8080/%s", updateCredentialsPath), body) // the endpoint we're hitting - ctx.Request.Header.Set("Content-Type", writer.FormDataContentType()) - suite.accountModule.accountUpdateCredentialsPATCHHandler(ctx) - - // check response - - // 1. we should have OK because our request was valid - suite.EqualValues(http.StatusOK, recorder.Code) - - // 2. we should have an error message in the result body - result := recorder.Result() - defer result.Body.Close() - // TODO: implement proper checks here - // - // b, err := ioutil.ReadAll(result.Body) - // assert.NoError(suite.T(), err) - // assert.Equal(suite.T(), `{"error":"not authorized"}`, string(b)) -} - -func TestAccountCreateTestSuite(t *testing.T) { - suite.Run(t, new(AccountCreateTestSuite)) -} diff --git a/internal/apimodule/account/accountget.go b/internal/apimodule/account/accountget.go index cd4aed22e..5003be139 100644 --- a/internal/apimodule/account/accountget.go +++ b/internal/apimodule/account/accountget.go @@ -26,12 +26,12 @@ import ( "github.com/superseriousbusiness/gotosocial/internal/db/gtsmodel" ) -// accountGetHandler serves the account information held by the server in response to a GET +// AccountGETHandler serves the account information held by the server in response to a GET // request. It should be served as a GET at /api/v1/accounts/:id. // // See: https://docs.joinmastodon.org/methods/accounts/ -func (m *accountModule) accountGETHandler(c *gin.Context) { - targetAcctID := c.Param(idKey) +func (m *Module) AccountGETHandler(c *gin.Context) { + targetAcctID := c.Param(IDKey) if targetAcctID == "" { c.JSON(http.StatusBadRequest, gin.H{"error": "no account id specified"}) return diff --git a/internal/apimodule/account/accountupdate.go b/internal/apimodule/account/accountupdate.go index 15e9cf0d1..7709697bf 100644 --- a/internal/apimodule/account/accountupdate.go +++ b/internal/apimodule/account/accountupdate.go @@ -34,7 +34,7 @@ import ( "github.com/superseriousbusiness/gotosocial/internal/util" ) -// accountUpdateCredentialsPATCHHandler allows a user to modify their account/profile settings. +// AccountUpdateCredentialsPATCHHandler allows a user to modify their account/profile settings. // It should be served as a PATCH at /api/v1/accounts/update_credentials // // TODO: this can be optimized massively by building up a picture of what we want the new account @@ -42,7 +42,7 @@ import ( // which is not gonna make the database very happy when lots of requests are going through. // This way it would also be safer because the update won't happen until *all* the fields are validated. // Otherwise we risk doing a partial update and that's gonna cause probllleeemmmsss. -func (m *accountModule) accountUpdateCredentialsPATCHHandler(c *gin.Context) { +func (m *Module) AccountUpdateCredentialsPATCHHandler(c *gin.Context) { l := m.log.WithField("func", "accountUpdateCredentialsPATCHHandler") authed, err := oauth.MustAuth(c, true, false, false, true) if err != nil { @@ -196,7 +196,7 @@ func (m *accountModule) accountUpdateCredentialsPATCHHandler(c *gin.Context) { // UpdateAccountAvatar does the dirty work of checking the avatar part of an account update form, // parsing and checking the image, and doing the necessary updates in the database for this to become // the account's new avatar image. -func (m *accountModule) UpdateAccountAvatar(avatar *multipart.FileHeader, accountID string) (*gtsmodel.MediaAttachment, error) { +func (m *Module) UpdateAccountAvatar(avatar *multipart.FileHeader, accountID string) (*gtsmodel.MediaAttachment, error) { var err error if int(avatar.Size) > m.config.MediaConfig.MaxImageSize { err = fmt.Errorf("avatar with size %d exceeded max image size of %d bytes", avatar.Size, m.config.MediaConfig.MaxImageSize) @@ -229,7 +229,7 @@ func (m *accountModule) UpdateAccountAvatar(avatar *multipart.FileHeader, accoun // UpdateAccountHeader does the dirty work of checking the header part of an account update form, // parsing and checking the image, and doing the necessary updates in the database for this to become // the account's new header image. -func (m *accountModule) UpdateAccountHeader(header *multipart.FileHeader, accountID string) (*gtsmodel.MediaAttachment, error) { +func (m *Module) UpdateAccountHeader(header *multipart.FileHeader, accountID string) (*gtsmodel.MediaAttachment, error) { var err error if int(header.Size) > m.config.MediaConfig.MaxImageSize { err = fmt.Errorf("header with size %d exceeded max image size of %d bytes", header.Size, m.config.MediaConfig.MaxImageSize) diff --git a/internal/apimodule/account/accountupdate_test.go b/internal/apimodule/account/accountupdate_test.go deleted file mode 100644 index 7ca2190d8..000000000 --- a/internal/apimodule/account/accountupdate_test.go +++ /dev/null @@ -1,302 +0,0 @@ -/* - GoToSocial - Copyright (C) 2021 GoToSocial Authors admin@gotosocial.org - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Affero General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Affero General Public License for more details. - - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . -*/ - -package account - -import ( - "bytes" - "context" - "fmt" - "io" - "mime/multipart" - "net/http" - "net/http/httptest" - "net/url" - "os" - "testing" - "time" - - "github.com/gin-gonic/gin" - "github.com/google/uuid" - "github.com/sirupsen/logrus" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/mock" - "github.com/stretchr/testify/suite" - "github.com/superseriousbusiness/gotosocial/internal/config" - "github.com/superseriousbusiness/gotosocial/internal/db" - "github.com/superseriousbusiness/gotosocial/internal/db/gtsmodel" - "github.com/superseriousbusiness/gotosocial/internal/mastotypes" - "github.com/superseriousbusiness/gotosocial/internal/media" - "github.com/superseriousbusiness/gotosocial/internal/oauth" - "github.com/superseriousbusiness/gotosocial/internal/storage" - "github.com/superseriousbusiness/oauth2/v4" - "github.com/superseriousbusiness/oauth2/v4/models" - oauthmodels "github.com/superseriousbusiness/oauth2/v4/models" -) - -type AccountUpdateTestSuite struct { - suite.Suite - config *config.Config - log *logrus.Logger - testAccountLocal *gtsmodel.Account - testApplication *gtsmodel.Application - testToken oauth2.TokenInfo - mockOauthServer *oauth.MockServer - mockStorage *storage.MockStorage - mediaHandler media.MediaHandler - mastoConverter mastotypes.Converter - db db.DB - accountModule *accountModule - newUserFormHappyPath url.Values -} - -/* - TEST INFRASTRUCTURE -*/ - -// SetupSuite sets some variables on the suite that we can use as consts (more or less) throughout -func (suite *AccountUpdateTestSuite) SetupSuite() { - // some of our subsequent entities need a log so create this here - log := logrus.New() - log.SetLevel(logrus.TraceLevel) - suite.log = log - - suite.testAccountLocal = >smodel.Account{ - ID: uuid.NewString(), - Username: "test_user", - } - - // can use this test application throughout - suite.testApplication = >smodel.Application{ - ID: "weeweeeeeeeeeeeeee", - Name: "a test application", - Website: "https://some-application-website.com", - RedirectURI: "http://localhost:8080", - ClientID: "a-known-client-id", - ClientSecret: "some-secret", - Scopes: "read", - VapidKey: "aaaaaa-aaaaaaaa-aaaaaaaaaaa", - } - - // can use this test token throughout - suite.testToken = &oauthmodels.Token{ - ClientID: "a-known-client-id", - RedirectURI: "http://localhost:8080", - Scope: "read", - Code: "123456789", - CodeCreateAt: time.Now(), - CodeExpiresIn: time.Duration(10 * time.Minute), - } - - // Direct config to local postgres instance - c := config.Empty() - c.Protocol = "http" - c.Host = "localhost" - c.DBConfig = &config.DBConfig{ - Type: "postgres", - Address: "localhost", - Port: 5432, - User: "postgres", - Password: "postgres", - Database: "postgres", - ApplicationName: "gotosocial", - } - c.MediaConfig = &config.MediaConfig{ - MaxImageSize: 2 << 20, - } - c.StorageConfig = &config.StorageConfig{ - Backend: "local", - BasePath: "/tmp", - ServeProtocol: "http", - ServeHost: "localhost", - ServeBasePath: "/fileserver/media", - } - suite.config = c - - // use an actual database for this, because it's just easier than mocking one out - database, err := db.New(context.Background(), c, log) - if err != nil { - suite.FailNow(err.Error()) - } - suite.db = database - - // we need to mock the oauth server because account creation needs it to create a new token - suite.mockOauthServer = &oauth.MockServer{} - suite.mockOauthServer.On("GenerateUserAccessToken", suite.testToken, suite.testApplication.ClientSecret, mock.AnythingOfType("string")).Run(func(args mock.Arguments) { - l := suite.log.WithField("func", "GenerateUserAccessToken") - token := args.Get(0).(oauth2.TokenInfo) - l.Infof("received token %+v", token) - clientSecret := args.Get(1).(string) - l.Infof("received clientSecret %+v", clientSecret) - userID := args.Get(2).(string) - l.Infof("received userID %+v", userID) - }).Return(&models.Token{ - Code: "we're authorized now!", - }, nil) - - suite.mockStorage = &storage.MockStorage{} - // We don't need storage to do anything for these tests, so just simulate a success and do nothing -- we won't need to return anything from storage - suite.mockStorage.On("StoreFileAt", mock.AnythingOfType("string"), mock.AnythingOfType("[]uint8")).Return(nil) - - // set a media handler because some handlers (eg update credentials) need to upload media (new header/avatar) - suite.mediaHandler = media.New(suite.config, suite.db, suite.mockStorage, log) - - suite.mastoConverter = mastotypes.New(suite.config, suite.db) - - // and finally here's the thing we're actually testing! - suite.accountModule = New(suite.config, suite.db, suite.mockOauthServer, suite.mediaHandler, suite.mastoConverter, suite.log).(*accountModule) -} - -func (suite *AccountUpdateTestSuite) TearDownSuite() { - if err := suite.db.Stop(context.Background()); err != nil { - logrus.Panicf("error closing db connection: %s", err) - } -} - -// SetupTest creates a db connection and creates necessary tables before each test -func (suite *AccountUpdateTestSuite) SetupTest() { - // create all the tables we might need in thie suite - models := []interface{}{ - >smodel.User{}, - >smodel.Account{}, - >smodel.Follow{}, - >smodel.FollowRequest{}, - >smodel.Status{}, - >smodel.Application{}, - >smodel.EmailDomainBlock{}, - >smodel.MediaAttachment{}, - } - for _, m := range models { - if err := suite.db.CreateTable(m); err != nil { - logrus.Panicf("db connection error: %s", err) - } - } - - // form to submit for happy path account create requests -- this will be changed inside tests so it's better to set it before each test - suite.newUserFormHappyPath = url.Values{ - "reason": []string{"a very good reason that's at least 40 characters i swear"}, - "username": []string{"test_user"}, - "email": []string{"user@example.org"}, - "password": []string{"very-strong-password"}, - "agreement": []string{"true"}, - "locale": []string{"en"}, - } - - // same with accounts config - suite.config.AccountsConfig = &config.AccountsConfig{ - OpenRegistration: true, - RequireApproval: true, - ReasonRequired: true, - } -} - -// TearDownTest drops tables to make sure there's no data in the db -func (suite *AccountUpdateTestSuite) TearDownTest() { - - // remove all the tables we might have used so it's clear for the next test - models := []interface{}{ - >smodel.User{}, - >smodel.Account{}, - >smodel.Follow{}, - >smodel.FollowRequest{}, - >smodel.Status{}, - >smodel.Application{}, - >smodel.EmailDomainBlock{}, - >smodel.MediaAttachment{}, - } - for _, m := range models { - if err := suite.db.DropTable(m); err != nil { - logrus.Panicf("error dropping table: %s", err) - } - } -} - -/* - ACTUAL TESTS -*/ - -/* - TESTING: AccountUpdateCredentialsPATCHHandler -*/ - -func (suite *AccountUpdateTestSuite) TestAccountUpdateCredentialsPATCHHandler() { - - // put test local account in db - err := suite.db.Put(suite.testAccountLocal) - assert.NoError(suite.T(), err) - - // attach avatar to request form - avatarFile, err := os.Open("../../media/test/test-jpeg.jpg") - assert.NoError(suite.T(), err) - body := &bytes.Buffer{} - writer := multipart.NewWriter(body) - - avatarPart, err := writer.CreateFormFile("avatar", "test-jpeg.jpg") - assert.NoError(suite.T(), err) - - _, err = io.Copy(avatarPart, avatarFile) - assert.NoError(suite.T(), err) - - err = avatarFile.Close() - assert.NoError(suite.T(), err) - - // set display name to a new value - displayNamePart, err := writer.CreateFormField("display_name") - assert.NoError(suite.T(), err) - - _, err = io.Copy(displayNamePart, bytes.NewBufferString("test_user_wohoah")) - assert.NoError(suite.T(), err) - - // set locked to true - lockedPart, err := writer.CreateFormField("locked") - assert.NoError(suite.T(), err) - - _, err = io.Copy(lockedPart, bytes.NewBufferString("true")) - assert.NoError(suite.T(), err) - - // close the request writer, the form is now prepared - err = writer.Close() - assert.NoError(suite.T(), err) - - // setup - recorder := httptest.NewRecorder() - ctx, _ := gin.CreateTestContext(recorder) - ctx.Set(oauth.SessionAuthorizedAccount, suite.testAccountLocal) - ctx.Set(oauth.SessionAuthorizedToken, suite.testToken) - ctx.Request = httptest.NewRequest(http.MethodPatch, fmt.Sprintf("http://localhost:8080/%s", updateCredentialsPath), body) // the endpoint we're hitting - ctx.Request.Header.Set("Content-Type", writer.FormDataContentType()) - suite.accountModule.accountUpdateCredentialsPATCHHandler(ctx) - - // check response - - // 1. we should have OK because our request was valid - suite.EqualValues(http.StatusOK, recorder.Code) - - // 2. we should have an error message in the result body - result := recorder.Result() - defer result.Body.Close() - // TODO: implement proper checks here - // - // b, err := ioutil.ReadAll(result.Body) - // assert.NoError(suite.T(), err) - // assert.Equal(suite.T(), `{"error":"not authorized"}`, string(b)) -} - -func TestAccountUpdateTestSuite(t *testing.T) { - suite.Run(t, new(AccountUpdateTestSuite)) -} diff --git a/internal/apimodule/account/accountverify.go b/internal/apimodule/account/accountverify.go index 584ab6122..9edf1e73a 100644 --- a/internal/apimodule/account/accountverify.go +++ b/internal/apimodule/account/accountverify.go @@ -25,10 +25,10 @@ import ( "github.com/superseriousbusiness/gotosocial/internal/oauth" ) -// accountVerifyGETHandler serves a user's account details to them IF they reached this +// AccountVerifyGETHandler serves a user's account details to them IF they reached this // handler while in possession of a valid token, according to the oauth middleware. // It should be served as a GET at /api/v1/accounts/verify_credentials -func (m *accountModule) accountVerifyGETHandler(c *gin.Context) { +func (m *Module) AccountVerifyGETHandler(c *gin.Context) { l := m.log.WithField("func", "accountVerifyGETHandler") authed, err := oauth.MustAuth(c, true, false, false, true) if err != nil { diff --git a/internal/apimodule/account/accountverify_test.go b/internal/apimodule/account/accountverify_test.go deleted file mode 100644 index 223a0c145..000000000 --- a/internal/apimodule/account/accountverify_test.go +++ /dev/null @@ -1,19 +0,0 @@ -/* - GoToSocial - Copyright (C) 2021 GoToSocial Authors admin@gotosocial.org - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Affero General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Affero General Public License for more details. - - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . -*/ - -package account diff --git a/internal/apimodule/account/test/accountcreate_test.go b/internal/apimodule/account/test/accountcreate_test.go new file mode 100644 index 000000000..81eab467a --- /dev/null +++ b/internal/apimodule/account/test/accountcreate_test.go @@ -0,0 +1,551 @@ +/* + GoToSocial + Copyright (C) 2021 GoToSocial Authors admin@gotosocial.org + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . +*/ + +package account + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "io" + "io/ioutil" + "mime/multipart" + "net/http" + "net/http/httptest" + "net/url" + "os" + "testing" + "time" + + "github.com/gin-gonic/gin" + "github.com/google/uuid" + "github.com/sirupsen/logrus" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/mock" + "github.com/stretchr/testify/suite" + "github.com/superseriousbusiness/gotosocial/internal/apimodule/account" + "github.com/superseriousbusiness/gotosocial/internal/config" + "github.com/superseriousbusiness/gotosocial/internal/db" + "github.com/superseriousbusiness/gotosocial/internal/db/gtsmodel" + "github.com/superseriousbusiness/gotosocial/internal/mastotypes" + mastomodel "github.com/superseriousbusiness/gotosocial/internal/mastotypes/mastomodel" + + "github.com/superseriousbusiness/gotosocial/internal/media" + "github.com/superseriousbusiness/gotosocial/internal/oauth" + "github.com/superseriousbusiness/gotosocial/internal/storage" + "github.com/superseriousbusiness/oauth2/v4" + "github.com/superseriousbusiness/oauth2/v4/models" + oauthmodels "github.com/superseriousbusiness/oauth2/v4/models" + "golang.org/x/crypto/bcrypt" +) + +type AccountCreateTestSuite struct { + suite.Suite + config *config.Config + log *logrus.Logger + testAccountLocal *gtsmodel.Account + testApplication *gtsmodel.Application + testToken oauth2.TokenInfo + mockOauthServer *oauth.MockServer + mockStorage *storage.MockStorage + mediaHandler media.Handler + mastoConverter mastotypes.Converter + db db.DB + accountModule *account.Module + newUserFormHappyPath url.Values +} + +/* + TEST INFRASTRUCTURE +*/ + +// SetupSuite sets some variables on the suite that we can use as consts (more or less) throughout +func (suite *AccountCreateTestSuite) SetupSuite() { + // some of our subsequent entities need a log so create this here + log := logrus.New() + log.SetLevel(logrus.TraceLevel) + suite.log = log + + suite.testAccountLocal = >smodel.Account{ + ID: uuid.NewString(), + Username: "test_user", + } + + // can use this test application throughout + suite.testApplication = >smodel.Application{ + ID: "weeweeeeeeeeeeeeee", + Name: "a test application", + Website: "https://some-application-website.com", + RedirectURI: "http://localhost:8080", + ClientID: "a-known-client-id", + ClientSecret: "some-secret", + Scopes: "read", + VapidKey: "aaaaaa-aaaaaaaa-aaaaaaaaaaa", + } + + // can use this test token throughout + suite.testToken = &oauthmodels.Token{ + ClientID: "a-known-client-id", + RedirectURI: "http://localhost:8080", + Scope: "read", + Code: "123456789", + CodeCreateAt: time.Now(), + CodeExpiresIn: time.Duration(10 * time.Minute), + } + + // Direct config to local postgres instance + c := config.Empty() + c.Protocol = "http" + c.Host = "localhost" + c.DBConfig = &config.DBConfig{ + Type: "postgres", + Address: "localhost", + Port: 5432, + User: "postgres", + Password: "postgres", + Database: "postgres", + ApplicationName: "gotosocial", + } + c.MediaConfig = &config.MediaConfig{ + MaxImageSize: 2 << 20, + } + c.StorageConfig = &config.StorageConfig{ + Backend: "local", + BasePath: "/tmp", + ServeProtocol: "http", + ServeHost: "localhost", + ServeBasePath: "/fileserver/media", + } + suite.config = c + + // use an actual database for this, because it's just easier than mocking one out + database, err := db.New(context.Background(), c, log) + if err != nil { + suite.FailNow(err.Error()) + } + suite.db = database + + // we need to mock the oauth server because account creation needs it to create a new token + suite.mockOauthServer = &oauth.MockServer{} + suite.mockOauthServer.On("GenerateUserAccessToken", suite.testToken, suite.testApplication.ClientSecret, mock.AnythingOfType("string")).Run(func(args mock.Arguments) { + l := suite.log.WithField("func", "GenerateUserAccessToken") + token := args.Get(0).(oauth2.TokenInfo) + l.Infof("received token %+v", token) + clientSecret := args.Get(1).(string) + l.Infof("received clientSecret %+v", clientSecret) + userID := args.Get(2).(string) + l.Infof("received userID %+v", userID) + }).Return(&models.Token{ + Access: "we're authorized now!", + }, nil) + + suite.mockStorage = &storage.MockStorage{} + // We don't need storage to do anything for these tests, so just simulate a success and do nothing -- we won't need to return anything from storage + suite.mockStorage.On("StoreFileAt", mock.AnythingOfType("string"), mock.AnythingOfType("[]uint8")).Return(nil) + + // set a media handler because some handlers (eg update credentials) need to upload media (new header/avatar) + suite.mediaHandler = media.New(suite.config, suite.db, suite.mockStorage, log) + + suite.mastoConverter = mastotypes.New(suite.config, suite.db) + + // and finally here's the thing we're actually testing! + suite.accountModule = account.New(suite.config, suite.db, suite.mockOauthServer, suite.mediaHandler, suite.mastoConverter, suite.log).(*account.Module) +} + +func (suite *AccountCreateTestSuite) TearDownSuite() { + if err := suite.db.Stop(context.Background()); err != nil { + logrus.Panicf("error closing db connection: %s", err) + } +} + +// SetupTest creates a db connection and creates necessary tables before each test +func (suite *AccountCreateTestSuite) SetupTest() { + // create all the tables we might need in thie suite + models := []interface{}{ + >smodel.User{}, + >smodel.Account{}, + >smodel.Follow{}, + >smodel.FollowRequest{}, + >smodel.Status{}, + >smodel.Application{}, + >smodel.EmailDomainBlock{}, + >smodel.MediaAttachment{}, + } + for _, m := range models { + if err := suite.db.CreateTable(m); err != nil { + logrus.Panicf("db connection error: %s", err) + } + } + + // form to submit for happy path account create requests -- this will be changed inside tests so it's better to set it before each test + suite.newUserFormHappyPath = url.Values{ + "reason": []string{"a very good reason that's at least 40 characters i swear"}, + "username": []string{"test_user"}, + "email": []string{"user@example.org"}, + "password": []string{"very-strong-password"}, + "agreement": []string{"true"}, + "locale": []string{"en"}, + } + + // same with accounts config + suite.config.AccountsConfig = &config.AccountsConfig{ + OpenRegistration: true, + RequireApproval: true, + ReasonRequired: true, + } +} + +// TearDownTest drops tables to make sure there's no data in the db +func (suite *AccountCreateTestSuite) TearDownTest() { + + // remove all the tables we might have used so it's clear for the next test + models := []interface{}{ + >smodel.User{}, + >smodel.Account{}, + >smodel.Follow{}, + >smodel.FollowRequest{}, + >smodel.Status{}, + >smodel.Application{}, + >smodel.EmailDomainBlock{}, + >smodel.MediaAttachment{}, + } + for _, m := range models { + if err := suite.db.DropTable(m); err != nil { + logrus.Panicf("error dropping table: %s", err) + } + } +} + +/* + ACTUAL TESTS +*/ + +/* + TESTING: AccountCreatePOSTHandler +*/ + +// TestAccountCreatePOSTHandlerSuccessful checks the happy path for an account creation request: all the fields provided are valid, +// and at the end of it a new user and account should be added into the database. +// +// This is the handler served at /api/v1/accounts as POST +func (suite *AccountCreateTestSuite) TestAccountCreatePOSTHandlerSuccessful() { + + // setup + recorder := httptest.NewRecorder() + ctx, _ := gin.CreateTestContext(recorder) + ctx.Set(oauth.SessionAuthorizedApplication, suite.testApplication) + ctx.Set(oauth.SessionAuthorizedToken, suite.testToken) + ctx.Request = httptest.NewRequest(http.MethodPost, fmt.Sprintf("http://localhost:8080/%s", account.BasePath), nil) // the endpoint we're hitting + ctx.Request.Form = suite.newUserFormHappyPath + suite.accountModule.AccountCreatePOSTHandler(ctx) + + // check response + + // 1. we should have OK from our call to the function + suite.EqualValues(http.StatusOK, recorder.Code) + + // 2. we should have a token in the result body + result := recorder.Result() + defer result.Body.Close() + b, err := ioutil.ReadAll(result.Body) + assert.NoError(suite.T(), err) + t := &mastomodel.Token{} + err = json.Unmarshal(b, t) + assert.NoError(suite.T(), err) + assert.Equal(suite.T(), "we're authorized now!", t.AccessToken) + + // check new account + + // 1. we should be able to get the new account from the db + acct := >smodel.Account{} + err = suite.db.GetWhere("username", "test_user", acct) + assert.NoError(suite.T(), err) + assert.NotNil(suite.T(), acct) + // 2. reason should be set + assert.Equal(suite.T(), suite.newUserFormHappyPath.Get("reason"), acct.Reason) + // 3. display name should be equal to username by default + assert.Equal(suite.T(), suite.newUserFormHappyPath.Get("username"), acct.DisplayName) + // 4. domain should be nil because this is a local account + assert.Nil(suite.T(), nil, acct.Domain) + // 5. id should be set and parseable as a uuid + assert.NotNil(suite.T(), acct.ID) + _, err = uuid.Parse(acct.ID) + assert.Nil(suite.T(), err) + // 6. private and public key should be set + assert.NotNil(suite.T(), acct.PrivateKey) + assert.NotNil(suite.T(), acct.PublicKey) + + // check new user + + // 1. we should be able to get the new user from the db + usr := >smodel.User{} + err = suite.db.GetWhere("unconfirmed_email", suite.newUserFormHappyPath.Get("email"), usr) + assert.Nil(suite.T(), err) + assert.NotNil(suite.T(), usr) + + // 2. user should have account id set to account we got above + assert.Equal(suite.T(), acct.ID, usr.AccountID) + + // 3. id should be set and parseable as a uuid + assert.NotNil(suite.T(), usr.ID) + _, err = uuid.Parse(usr.ID) + assert.Nil(suite.T(), err) + + // 4. locale should be equal to what we requested + assert.Equal(suite.T(), suite.newUserFormHappyPath.Get("locale"), usr.Locale) + + // 5. created by application id should be equal to the app id + assert.Equal(suite.T(), suite.testApplication.ID, usr.CreatedByApplicationID) + + // 6. password should be matcheable to what we set above + err = bcrypt.CompareHashAndPassword([]byte(usr.EncryptedPassword), []byte(suite.newUserFormHappyPath.Get("password"))) + assert.Nil(suite.T(), err) +} + +// TestAccountCreatePOSTHandlerNoAuth makes sure that the handler fails when no authorization is provided: +// only registered applications can create accounts, and we don't provide one here. +func (suite *AccountCreateTestSuite) TestAccountCreatePOSTHandlerNoAuth() { + + // setup + recorder := httptest.NewRecorder() + ctx, _ := gin.CreateTestContext(recorder) + ctx.Request = httptest.NewRequest(http.MethodPost, fmt.Sprintf("http://localhost:8080/%s", account.BasePath), nil) // the endpoint we're hitting + ctx.Request.Form = suite.newUserFormHappyPath + suite.accountModule.AccountCreatePOSTHandler(ctx) + + // check response + + // 1. we should have forbidden from our call to the function because we didn't auth + suite.EqualValues(http.StatusForbidden, recorder.Code) + + // 2. we should have an error message in the result body + result := recorder.Result() + defer result.Body.Close() + b, err := ioutil.ReadAll(result.Body) + assert.NoError(suite.T(), err) + assert.Equal(suite.T(), `{"error":"not authorized"}`, string(b)) +} + +// TestAccountCreatePOSTHandlerNoAuth makes sure that the handler fails when no form is provided at all. +func (suite *AccountCreateTestSuite) TestAccountCreatePOSTHandlerNoForm() { + + // setup + recorder := httptest.NewRecorder() + ctx, _ := gin.CreateTestContext(recorder) + ctx.Set(oauth.SessionAuthorizedApplication, suite.testApplication) + ctx.Set(oauth.SessionAuthorizedToken, suite.testToken) + ctx.Request = httptest.NewRequest(http.MethodPost, fmt.Sprintf("http://localhost:8080/%s", account.BasePath), nil) // the endpoint we're hitting + suite.accountModule.AccountCreatePOSTHandler(ctx) + + // check response + suite.EqualValues(http.StatusBadRequest, recorder.Code) + + // 2. we should have an error message in the result body + result := recorder.Result() + defer result.Body.Close() + b, err := ioutil.ReadAll(result.Body) + assert.NoError(suite.T(), err) + assert.Equal(suite.T(), `{"error":"missing one or more required form values"}`, string(b)) +} + +// TestAccountCreatePOSTHandlerWeakPassword makes sure that the handler fails when a weak password is provided +func (suite *AccountCreateTestSuite) TestAccountCreatePOSTHandlerWeakPassword() { + + // setup + recorder := httptest.NewRecorder() + ctx, _ := gin.CreateTestContext(recorder) + ctx.Set(oauth.SessionAuthorizedApplication, suite.testApplication) + ctx.Set(oauth.SessionAuthorizedToken, suite.testToken) + ctx.Request = httptest.NewRequest(http.MethodPost, fmt.Sprintf("http://localhost:8080/%s", account.BasePath), nil) // the endpoint we're hitting + ctx.Request.Form = suite.newUserFormHappyPath + // set a weak password + ctx.Request.Form.Set("password", "weak") + suite.accountModule.AccountCreatePOSTHandler(ctx) + + // check response + suite.EqualValues(http.StatusBadRequest, recorder.Code) + + // 2. we should have an error message in the result body + result := recorder.Result() + defer result.Body.Close() + b, err := ioutil.ReadAll(result.Body) + assert.NoError(suite.T(), err) + assert.Equal(suite.T(), `{"error":"insecure password, try including more special characters, using uppercase letters, using numbers or using a longer password"}`, string(b)) +} + +// TestAccountCreatePOSTHandlerWeirdLocale makes sure that the handler fails when a weird locale is provided +func (suite *AccountCreateTestSuite) TestAccountCreatePOSTHandlerWeirdLocale() { + + // setup + recorder := httptest.NewRecorder() + ctx, _ := gin.CreateTestContext(recorder) + ctx.Set(oauth.SessionAuthorizedApplication, suite.testApplication) + ctx.Set(oauth.SessionAuthorizedToken, suite.testToken) + ctx.Request = httptest.NewRequest(http.MethodPost, fmt.Sprintf("http://localhost:8080/%s", account.BasePath), nil) // the endpoint we're hitting + ctx.Request.Form = suite.newUserFormHappyPath + // set an invalid locale + ctx.Request.Form.Set("locale", "neverneverland") + suite.accountModule.AccountCreatePOSTHandler(ctx) + + // check response + suite.EqualValues(http.StatusBadRequest, recorder.Code) + + // 2. we should have an error message in the result body + result := recorder.Result() + defer result.Body.Close() + b, err := ioutil.ReadAll(result.Body) + assert.NoError(suite.T(), err) + assert.Equal(suite.T(), `{"error":"language: tag is not well-formed"}`, string(b)) +} + +// TestAccountCreatePOSTHandlerRegistrationsClosed makes sure that the handler fails when registrations are closed +func (suite *AccountCreateTestSuite) TestAccountCreatePOSTHandlerRegistrationsClosed() { + + // setup + recorder := httptest.NewRecorder() + ctx, _ := gin.CreateTestContext(recorder) + ctx.Set(oauth.SessionAuthorizedApplication, suite.testApplication) + ctx.Set(oauth.SessionAuthorizedToken, suite.testToken) + ctx.Request = httptest.NewRequest(http.MethodPost, fmt.Sprintf("http://localhost:8080/%s", account.BasePath), nil) // the endpoint we're hitting + ctx.Request.Form = suite.newUserFormHappyPath + + // close registrations + suite.config.AccountsConfig.OpenRegistration = false + suite.accountModule.AccountCreatePOSTHandler(ctx) + + // check response + suite.EqualValues(http.StatusBadRequest, recorder.Code) + + // 2. we should have an error message in the result body + result := recorder.Result() + defer result.Body.Close() + b, err := ioutil.ReadAll(result.Body) + assert.NoError(suite.T(), err) + assert.Equal(suite.T(), `{"error":"registration is not open for this server"}`, string(b)) +} + +// TestAccountCreatePOSTHandlerReasonNotProvided makes sure that the handler fails when no reason is provided but one is required +func (suite *AccountCreateTestSuite) TestAccountCreatePOSTHandlerReasonNotProvided() { + + // setup + recorder := httptest.NewRecorder() + ctx, _ := gin.CreateTestContext(recorder) + ctx.Set(oauth.SessionAuthorizedApplication, suite.testApplication) + ctx.Set(oauth.SessionAuthorizedToken, suite.testToken) + ctx.Request = httptest.NewRequest(http.MethodPost, fmt.Sprintf("http://localhost:8080/%s", account.BasePath), nil) // the endpoint we're hitting + ctx.Request.Form = suite.newUserFormHappyPath + + // remove reason + ctx.Request.Form.Set("reason", "") + + suite.accountModule.AccountCreatePOSTHandler(ctx) + + // check response + suite.EqualValues(http.StatusBadRequest, recorder.Code) + + // 2. we should have an error message in the result body + result := recorder.Result() + defer result.Body.Close() + b, err := ioutil.ReadAll(result.Body) + assert.NoError(suite.T(), err) + assert.Equal(suite.T(), `{"error":"no reason provided"}`, string(b)) +} + +// TestAccountCreatePOSTHandlerReasonNotProvided makes sure that the handler fails when a crappy reason is presented but a good one is required +func (suite *AccountCreateTestSuite) TestAccountCreatePOSTHandlerInsufficientReason() { + + // setup + recorder := httptest.NewRecorder() + ctx, _ := gin.CreateTestContext(recorder) + ctx.Set(oauth.SessionAuthorizedApplication, suite.testApplication) + ctx.Set(oauth.SessionAuthorizedToken, suite.testToken) + ctx.Request = httptest.NewRequest(http.MethodPost, fmt.Sprintf("http://localhost:8080/%s", account.BasePath), nil) // the endpoint we're hitting + ctx.Request.Form = suite.newUserFormHappyPath + + // remove reason + ctx.Request.Form.Set("reason", "just cuz") + + suite.accountModule.AccountCreatePOSTHandler(ctx) + + // check response + suite.EqualValues(http.StatusBadRequest, recorder.Code) + + // 2. we should have an error message in the result body + result := recorder.Result() + defer result.Body.Close() + b, err := ioutil.ReadAll(result.Body) + assert.NoError(suite.T(), err) + assert.Equal(suite.T(), `{"error":"reason should be at least 40 chars but 'just cuz' was 8"}`, string(b)) +} + +/* + TESTING: AccountUpdateCredentialsPATCHHandler +*/ + +func (suite *AccountCreateTestSuite) TestAccountUpdateCredentialsPATCHHandler() { + + // put test local account in db + err := suite.db.Put(suite.testAccountLocal) + assert.NoError(suite.T(), err) + + // attach avatar to request + aviFile, err := os.Open("../../media/test/test-jpeg.jpg") + assert.NoError(suite.T(), err) + body := &bytes.Buffer{} + writer := multipart.NewWriter(body) + + part, err := writer.CreateFormFile("avatar", "test-jpeg.jpg") + assert.NoError(suite.T(), err) + + _, err = io.Copy(part, aviFile) + assert.NoError(suite.T(), err) + + err = aviFile.Close() + assert.NoError(suite.T(), err) + + err = writer.Close() + assert.NoError(suite.T(), err) + + // setup + recorder := httptest.NewRecorder() + ctx, _ := gin.CreateTestContext(recorder) + ctx.Set(oauth.SessionAuthorizedAccount, suite.testAccountLocal) + ctx.Set(oauth.SessionAuthorizedToken, suite.testToken) + ctx.Request = httptest.NewRequest(http.MethodPatch, fmt.Sprintf("http://localhost:8080/%s", account.UpdateCredentialsPath), body) // the endpoint we're hitting + ctx.Request.Header.Set("Content-Type", writer.FormDataContentType()) + suite.accountModule.AccountUpdateCredentialsPATCHHandler(ctx) + + // check response + + // 1. we should have OK because our request was valid + suite.EqualValues(http.StatusOK, recorder.Code) + + // 2. we should have an error message in the result body + result := recorder.Result() + defer result.Body.Close() + // TODO: implement proper checks here + // + // b, err := ioutil.ReadAll(result.Body) + // assert.NoError(suite.T(), err) + // assert.Equal(suite.T(), `{"error":"not authorized"}`, string(b)) +} + +func TestAccountCreateTestSuite(t *testing.T) { + suite.Run(t, new(AccountCreateTestSuite)) +} diff --git a/internal/apimodule/account/test/accountupdate_test.go b/internal/apimodule/account/test/accountupdate_test.go new file mode 100644 index 000000000..1c6f528a1 --- /dev/null +++ b/internal/apimodule/account/test/accountupdate_test.go @@ -0,0 +1,303 @@ +/* + GoToSocial + Copyright (C) 2021 GoToSocial Authors admin@gotosocial.org + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . +*/ + +package account + +import ( + "bytes" + "context" + "fmt" + "io" + "mime/multipart" + "net/http" + "net/http/httptest" + "net/url" + "os" + "testing" + "time" + + "github.com/gin-gonic/gin" + "github.com/google/uuid" + "github.com/sirupsen/logrus" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/mock" + "github.com/stretchr/testify/suite" + "github.com/superseriousbusiness/gotosocial/internal/apimodule/account" + "github.com/superseriousbusiness/gotosocial/internal/config" + "github.com/superseriousbusiness/gotosocial/internal/db" + "github.com/superseriousbusiness/gotosocial/internal/db/gtsmodel" + "github.com/superseriousbusiness/gotosocial/internal/mastotypes" + "github.com/superseriousbusiness/gotosocial/internal/media" + "github.com/superseriousbusiness/gotosocial/internal/oauth" + "github.com/superseriousbusiness/gotosocial/internal/storage" + "github.com/superseriousbusiness/oauth2/v4" + "github.com/superseriousbusiness/oauth2/v4/models" + oauthmodels "github.com/superseriousbusiness/oauth2/v4/models" +) + +type AccountUpdateTestSuite struct { + suite.Suite + config *config.Config + log *logrus.Logger + testAccountLocal *gtsmodel.Account + testApplication *gtsmodel.Application + testToken oauth2.TokenInfo + mockOauthServer *oauth.MockServer + mockStorage *storage.MockStorage + mediaHandler media.Handler + mastoConverter mastotypes.Converter + db db.DB + accountModule *account.Module + newUserFormHappyPath url.Values +} + +/* + TEST INFRASTRUCTURE +*/ + +// SetupSuite sets some variables on the suite that we can use as consts (more or less) throughout +func (suite *AccountUpdateTestSuite) SetupSuite() { + // some of our subsequent entities need a log so create this here + log := logrus.New() + log.SetLevel(logrus.TraceLevel) + suite.log = log + + suite.testAccountLocal = >smodel.Account{ + ID: uuid.NewString(), + Username: "test_user", + } + + // can use this test application throughout + suite.testApplication = >smodel.Application{ + ID: "weeweeeeeeeeeeeeee", + Name: "a test application", + Website: "https://some-application-website.com", + RedirectURI: "http://localhost:8080", + ClientID: "a-known-client-id", + ClientSecret: "some-secret", + Scopes: "read", + VapidKey: "aaaaaa-aaaaaaaa-aaaaaaaaaaa", + } + + // can use this test token throughout + suite.testToken = &oauthmodels.Token{ + ClientID: "a-known-client-id", + RedirectURI: "http://localhost:8080", + Scope: "read", + Code: "123456789", + CodeCreateAt: time.Now(), + CodeExpiresIn: time.Duration(10 * time.Minute), + } + + // Direct config to local postgres instance + c := config.Empty() + c.Protocol = "http" + c.Host = "localhost" + c.DBConfig = &config.DBConfig{ + Type: "postgres", + Address: "localhost", + Port: 5432, + User: "postgres", + Password: "postgres", + Database: "postgres", + ApplicationName: "gotosocial", + } + c.MediaConfig = &config.MediaConfig{ + MaxImageSize: 2 << 20, + } + c.StorageConfig = &config.StorageConfig{ + Backend: "local", + BasePath: "/tmp", + ServeProtocol: "http", + ServeHost: "localhost", + ServeBasePath: "/fileserver/media", + } + suite.config = c + + // use an actual database for this, because it's just easier than mocking one out + database, err := db.New(context.Background(), c, log) + if err != nil { + suite.FailNow(err.Error()) + } + suite.db = database + + // we need to mock the oauth server because account creation needs it to create a new token + suite.mockOauthServer = &oauth.MockServer{} + suite.mockOauthServer.On("GenerateUserAccessToken", suite.testToken, suite.testApplication.ClientSecret, mock.AnythingOfType("string")).Run(func(args mock.Arguments) { + l := suite.log.WithField("func", "GenerateUserAccessToken") + token := args.Get(0).(oauth2.TokenInfo) + l.Infof("received token %+v", token) + clientSecret := args.Get(1).(string) + l.Infof("received clientSecret %+v", clientSecret) + userID := args.Get(2).(string) + l.Infof("received userID %+v", userID) + }).Return(&models.Token{ + Code: "we're authorized now!", + }, nil) + + suite.mockStorage = &storage.MockStorage{} + // We don't need storage to do anything for these tests, so just simulate a success and do nothing -- we won't need to return anything from storage + suite.mockStorage.On("StoreFileAt", mock.AnythingOfType("string"), mock.AnythingOfType("[]uint8")).Return(nil) + + // set a media handler because some handlers (eg update credentials) need to upload media (new header/avatar) + suite.mediaHandler = media.New(suite.config, suite.db, suite.mockStorage, log) + + suite.mastoConverter = mastotypes.New(suite.config, suite.db) + + // and finally here's the thing we're actually testing! + suite.accountModule = account.New(suite.config, suite.db, suite.mockOauthServer, suite.mediaHandler, suite.mastoConverter, suite.log).(*account.Module) +} + +func (suite *AccountUpdateTestSuite) TearDownSuite() { + if err := suite.db.Stop(context.Background()); err != nil { + logrus.Panicf("error closing db connection: %s", err) + } +} + +// SetupTest creates a db connection and creates necessary tables before each test +func (suite *AccountUpdateTestSuite) SetupTest() { + // create all the tables we might need in thie suite + models := []interface{}{ + >smodel.User{}, + >smodel.Account{}, + >smodel.Follow{}, + >smodel.FollowRequest{}, + >smodel.Status{}, + >smodel.Application{}, + >smodel.EmailDomainBlock{}, + >smodel.MediaAttachment{}, + } + for _, m := range models { + if err := suite.db.CreateTable(m); err != nil { + logrus.Panicf("db connection error: %s", err) + } + } + + // form to submit for happy path account create requests -- this will be changed inside tests so it's better to set it before each test + suite.newUserFormHappyPath = url.Values{ + "reason": []string{"a very good reason that's at least 40 characters i swear"}, + "username": []string{"test_user"}, + "email": []string{"user@example.org"}, + "password": []string{"very-strong-password"}, + "agreement": []string{"true"}, + "locale": []string{"en"}, + } + + // same with accounts config + suite.config.AccountsConfig = &config.AccountsConfig{ + OpenRegistration: true, + RequireApproval: true, + ReasonRequired: true, + } +} + +// TearDownTest drops tables to make sure there's no data in the db +func (suite *AccountUpdateTestSuite) TearDownTest() { + + // remove all the tables we might have used so it's clear for the next test + models := []interface{}{ + >smodel.User{}, + >smodel.Account{}, + >smodel.Follow{}, + >smodel.FollowRequest{}, + >smodel.Status{}, + >smodel.Application{}, + >smodel.EmailDomainBlock{}, + >smodel.MediaAttachment{}, + } + for _, m := range models { + if err := suite.db.DropTable(m); err != nil { + logrus.Panicf("error dropping table: %s", err) + } + } +} + +/* + ACTUAL TESTS +*/ + +/* + TESTING: AccountUpdateCredentialsPATCHHandler +*/ + +func (suite *AccountUpdateTestSuite) TestAccountUpdateCredentialsPATCHHandler() { + + // put test local account in db + err := suite.db.Put(suite.testAccountLocal) + assert.NoError(suite.T(), err) + + // attach avatar to request form + avatarFile, err := os.Open("../../media/test/test-jpeg.jpg") + assert.NoError(suite.T(), err) + body := &bytes.Buffer{} + writer := multipart.NewWriter(body) + + avatarPart, err := writer.CreateFormFile("avatar", "test-jpeg.jpg") + assert.NoError(suite.T(), err) + + _, err = io.Copy(avatarPart, avatarFile) + assert.NoError(suite.T(), err) + + err = avatarFile.Close() + assert.NoError(suite.T(), err) + + // set display name to a new value + displayNamePart, err := writer.CreateFormField("display_name") + assert.NoError(suite.T(), err) + + _, err = io.Copy(displayNamePart, bytes.NewBufferString("test_user_wohoah")) + assert.NoError(suite.T(), err) + + // set locked to true + lockedPart, err := writer.CreateFormField("locked") + assert.NoError(suite.T(), err) + + _, err = io.Copy(lockedPart, bytes.NewBufferString("true")) + assert.NoError(suite.T(), err) + + // close the request writer, the form is now prepared + err = writer.Close() + assert.NoError(suite.T(), err) + + // setup + recorder := httptest.NewRecorder() + ctx, _ := gin.CreateTestContext(recorder) + ctx.Set(oauth.SessionAuthorizedAccount, suite.testAccountLocal) + ctx.Set(oauth.SessionAuthorizedToken, suite.testToken) + ctx.Request = httptest.NewRequest(http.MethodPatch, fmt.Sprintf("http://localhost:8080/%s", account.UpdateCredentialsPath), body) // the endpoint we're hitting + ctx.Request.Header.Set("Content-Type", writer.FormDataContentType()) + suite.accountModule.AccountUpdateCredentialsPATCHHandler(ctx) + + // check response + + // 1. we should have OK because our request was valid + suite.EqualValues(http.StatusOK, recorder.Code) + + // 2. we should have an error message in the result body + result := recorder.Result() + defer result.Body.Close() + // TODO: implement proper checks here + // + // b, err := ioutil.ReadAll(result.Body) + // assert.NoError(suite.T(), err) + // assert.Equal(suite.T(), `{"error":"not authorized"}`, string(b)) +} + +func TestAccountUpdateTestSuite(t *testing.T) { + suite.Run(t, new(AccountUpdateTestSuite)) +} diff --git a/internal/apimodule/account/test/accountverify_test.go b/internal/apimodule/account/test/accountverify_test.go new file mode 100644 index 000000000..223a0c145 --- /dev/null +++ b/internal/apimodule/account/test/accountverify_test.go @@ -0,0 +1,19 @@ +/* + GoToSocial + Copyright (C) 2021 GoToSocial Authors admin@gotosocial.org + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . +*/ + +package account diff --git a/internal/apimodule/admin/admin.go b/internal/apimodule/admin/admin.go index 34a0aa2c8..2ebe9c7a7 100644 --- a/internal/apimodule/admin/admin.go +++ b/internal/apimodule/admin/admin.go @@ -33,21 +33,24 @@ import ( ) const ( - basePath = "/api/v1/admin" - emojiPath = basePath + "/custom_emojis" + // BasePath is the base API path for this module + BasePath = "/api/v1/admin" + // EmojiPath is used for posting/deleting custom emojis + EmojiPath = BasePath + "/custom_emojis" ) -type adminModule struct { +// Module implements the ClientAPIModule interface for admin-related actions (reports, emojis, etc) +type Module struct { config *config.Config db db.DB - mediaHandler media.MediaHandler + mediaHandler media.Handler mastoConverter mastotypes.Converter log *logrus.Logger } -// New returns a new account module -func New(config *config.Config, db db.DB, mediaHandler media.MediaHandler, mastoConverter mastotypes.Converter, log *logrus.Logger) apimodule.ClientAPIModule { - return &adminModule{ +// New returns a new admin module +func New(config *config.Config, db db.DB, mediaHandler media.Handler, mastoConverter mastotypes.Converter, log *logrus.Logger) apimodule.ClientAPIModule { + return &Module{ config: config, db: db, mediaHandler: mediaHandler, @@ -57,12 +60,13 @@ func New(config *config.Config, db db.DB, mediaHandler media.MediaHandler, masto } // Route attaches all routes from this module to the given router -func (m *adminModule) Route(r router.Router) error { - r.AttachHandler(http.MethodPost, emojiPath, m.emojiCreatePOSTHandler) +func (m *Module) Route(r router.Router) error { + r.AttachHandler(http.MethodPost, EmojiPath, m.emojiCreatePOSTHandler) return nil } -func (m *adminModule) CreateTables(db db.DB) error { +// CreateTables creates the necessary tables for this module in the given database +func (m *Module) CreateTables(db db.DB) error { models := []interface{}{ >smodel.User{}, >smodel.Account{}, diff --git a/internal/apimodule/admin/emojicreate.go b/internal/apimodule/admin/emojicreate.go index 91457c07c..49e5492dd 100644 --- a/internal/apimodule/admin/emojicreate.go +++ b/internal/apimodule/admin/emojicreate.go @@ -33,7 +33,7 @@ import ( "github.com/superseriousbusiness/gotosocial/internal/util" ) -func (m *adminModule) emojiCreatePOSTHandler(c *gin.Context) { +func (m *Module) emojiCreatePOSTHandler(c *gin.Context) { l := m.log.WithFields(logrus.Fields{ "func": "emojiCreatePOSTHandler", "request_uri": c.Request.RequestURI, diff --git a/internal/apimodule/app/app.go b/internal/apimodule/app/app.go index 08292acd1..518192758 100644 --- a/internal/apimodule/app/app.go +++ b/internal/apimodule/app/app.go @@ -31,9 +31,11 @@ import ( "github.com/superseriousbusiness/gotosocial/internal/router" ) -const appsPath = "/api/v1/apps" +// BasePath is the base path for this api module +const BasePath = "/api/v1/apps" -type appModule struct { +// Module implements the ClientAPIModule interface for requests relating to registering/removing applications +type Module struct { server oauth.Server db db.DB mastoConverter mastotypes.Converter @@ -42,7 +44,7 @@ type appModule struct { // New returns a new auth module func New(srv oauth.Server, db db.DB, mastoConverter mastotypes.Converter, log *logrus.Logger) apimodule.ClientAPIModule { - return &appModule{ + return &Module{ server: srv, db: db, mastoConverter: mastoConverter, @@ -51,12 +53,13 @@ func New(srv oauth.Server, db db.DB, mastoConverter mastotypes.Converter, log *l } // Route satisfies the RESTAPIModule interface -func (m *appModule) Route(s router.Router) error { - s.AttachHandler(http.MethodPost, appsPath, m.appsPOSTHandler) +func (m *Module) Route(s router.Router) error { + s.AttachHandler(http.MethodPost, BasePath, m.AppsPOSTHandler) return nil } -func (m *appModule) CreateTables(db db.DB) error { +// CreateTables creates the necessary tables for this module in the given database +func (m *Module) CreateTables(db db.DB) error { models := []interface{}{ &oauth.Client{}, &oauth.Token{}, diff --git a/internal/apimodule/app/app_test.go b/internal/apimodule/app/app_test.go deleted file mode 100644 index d45b04e74..000000000 --- a/internal/apimodule/app/app_test.go +++ /dev/null @@ -1,21 +0,0 @@ -/* - GoToSocial - Copyright (C) 2021 GoToSocial Authors admin@gotosocial.org - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Affero General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Affero General Public License for more details. - - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . -*/ - -package app - -// TODO: write tests diff --git a/internal/apimodule/app/appcreate.go b/internal/apimodule/app/appcreate.go index ec52a9d37..99b79d470 100644 --- a/internal/apimodule/app/appcreate.go +++ b/internal/apimodule/app/appcreate.go @@ -29,9 +29,9 @@ import ( "github.com/superseriousbusiness/gotosocial/internal/oauth" ) -// appsPOSTHandler should be served at https://example.org/api/v1/apps +// AppsPOSTHandler should be served at https://example.org/api/v1/apps // It is equivalent to: https://docs.joinmastodon.org/methods/apps/ -func (m *appModule) appsPOSTHandler(c *gin.Context) { +func (m *Module) AppsPOSTHandler(c *gin.Context) { l := m.log.WithField("func", "AppsPOSTHandler") l.Trace("entering AppsPOSTHandler") diff --git a/internal/apimodule/app/test/app_test.go b/internal/apimodule/app/test/app_test.go new file mode 100644 index 000000000..d45b04e74 --- /dev/null +++ b/internal/apimodule/app/test/app_test.go @@ -0,0 +1,21 @@ +/* + GoToSocial + Copyright (C) 2021 GoToSocial Authors admin@gotosocial.org + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . +*/ + +package app + +// TODO: write tests diff --git a/internal/apimodule/auth/README.md b/internal/apimodule/auth/README.md deleted file mode 100644 index 96b2443c1..000000000 --- a/internal/apimodule/auth/README.md +++ /dev/null @@ -1,5 +0,0 @@ -# auth - -This package provides uses the [GoToSocial oauth2](https://github.com/gotosocial/oauth2) module (forked from [go-oauth2](https://github.com/go-oauth2/oauth2)) to provide [oauth2](https://www.oauth.com/) functionality to the GoToSocial client API. - -It also provides a handler/middleware for attaching to the Gin engine for validating authenticated users. diff --git a/internal/apimodule/auth/auth.go b/internal/apimodule/auth/auth.go index b70adeb43..341805b40 100644 --- a/internal/apimodule/auth/auth.go +++ b/internal/apimodule/auth/auth.go @@ -16,12 +16,6 @@ along with this program. If not, see . */ -// Package auth is a module that provides oauth functionality to a router. -// It adds the following paths: -// /auth/sign_in -// /oauth/token -// /oauth/authorize -// It also includes the oauthTokenMiddleware, which can be attached to a router to authenticate every request by Bearer token. package auth import ( @@ -37,12 +31,16 @@ import ( ) const ( - authSignInPath = "/auth/sign_in" - oauthTokenPath = "/oauth/token" - oauthAuthorizePath = "/oauth/authorize" + // AuthSignInPath is the API path for users to sign in through + AuthSignInPath = "/auth/sign_in" + // OauthTokenPath is the API path to use for granting token requests to users with valid credentials + OauthTokenPath = "/oauth/token" + // OauthAuthorizePath is the API path for authorization requests (eg., authorize this app to act on my behalf as a user) + OauthAuthorizePath = "/oauth/authorize" ) -type authModule struct { +// Module implements the ClientAPIModule interface for +type Module struct { server oauth.Server db db.DB log *logrus.Logger @@ -50,7 +48,7 @@ type authModule struct { // New returns a new auth module func New(srv oauth.Server, db db.DB, log *logrus.Logger) apimodule.ClientAPIModule { - return &authModule{ + return &Module{ server: srv, db: db, log: log, @@ -58,20 +56,21 @@ func New(srv oauth.Server, db db.DB, log *logrus.Logger) apimodule.ClientAPIModu } // Route satisfies the RESTAPIModule interface -func (m *authModule) Route(s router.Router) error { - s.AttachHandler(http.MethodGet, authSignInPath, m.signInGETHandler) - s.AttachHandler(http.MethodPost, authSignInPath, m.signInPOSTHandler) +func (m *Module) Route(s router.Router) error { + s.AttachHandler(http.MethodGet, AuthSignInPath, m.SignInGETHandler) + s.AttachHandler(http.MethodPost, AuthSignInPath, m.SignInPOSTHandler) - s.AttachHandler(http.MethodPost, oauthTokenPath, m.tokenPOSTHandler) + s.AttachHandler(http.MethodPost, OauthTokenPath, m.TokenPOSTHandler) - s.AttachHandler(http.MethodGet, oauthAuthorizePath, m.authorizeGETHandler) - s.AttachHandler(http.MethodPost, oauthAuthorizePath, m.authorizePOSTHandler) + s.AttachHandler(http.MethodGet, OauthAuthorizePath, m.AuthorizeGETHandler) + s.AttachHandler(http.MethodPost, OauthAuthorizePath, m.AuthorizePOSTHandler) - s.AttachMiddleware(m.oauthTokenMiddleware) + s.AttachMiddleware(m.OauthTokenMiddleware) return nil } -func (m *authModule) CreateTables(db db.DB) error { +// CreateTables creates the necessary tables for this module in the given database +func (m *Module) CreateTables(db db.DB) error { models := []interface{}{ &oauth.Client{}, &oauth.Token{}, diff --git a/internal/apimodule/auth/auth_test.go b/internal/apimodule/auth/auth_test.go deleted file mode 100644 index 2c272e985..000000000 --- a/internal/apimodule/auth/auth_test.go +++ /dev/null @@ -1,166 +0,0 @@ -/* - GoToSocial - Copyright (C) 2021 GoToSocial Authors admin@gotosocial.org - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Affero General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Affero General Public License for more details. - - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . -*/ - -package auth - -import ( - "context" - "fmt" - "testing" - - "github.com/google/uuid" - "github.com/sirupsen/logrus" - "github.com/stretchr/testify/suite" - "github.com/superseriousbusiness/gotosocial/internal/config" - "github.com/superseriousbusiness/gotosocial/internal/db" - "github.com/superseriousbusiness/gotosocial/internal/db/gtsmodel" - "github.com/superseriousbusiness/gotosocial/internal/oauth" - "golang.org/x/crypto/bcrypt" -) - -type AuthTestSuite struct { - suite.Suite - oauthServer oauth.Server - db db.DB - testAccount *gtsmodel.Account - testApplication *gtsmodel.Application - testUser *gtsmodel.User - testClient *oauth.Client - config *config.Config -} - -// SetupSuite sets some variables on the suite that we can use as consts (more or less) throughout -func (suite *AuthTestSuite) SetupSuite() { - c := config.Empty() - // we're running on localhost without https so set the protocol to http - c.Protocol = "http" - // just for testing - c.Host = "localhost:8080" - // because go tests are run within the test package directory, we need to fiddle with the templateconfig - // basedir in a way that we wouldn't normally have to do when running the binary, in order to make - // the templates actually load - c.TemplateConfig.BaseDir = "../../../web/template/" - c.DBConfig = &config.DBConfig{ - Type: "postgres", - Address: "localhost", - Port: 5432, - User: "postgres", - Password: "postgres", - Database: "postgres", - ApplicationName: "gotosocial", - } - suite.config = c - - encryptedPassword, err := bcrypt.GenerateFromPassword([]byte("password"), bcrypt.DefaultCost) - if err != nil { - logrus.Panicf("error encrypting user pass: %s", err) - } - - acctID := uuid.NewString() - - suite.testAccount = >smodel.Account{ - ID: acctID, - Username: "test_user", - } - suite.testUser = >smodel.User{ - EncryptedPassword: string(encryptedPassword), - Email: "user@example.org", - AccountID: acctID, - } - suite.testClient = &oauth.Client{ - ID: "a-known-client-id", - Secret: "some-secret", - Domain: fmt.Sprintf("%s://%s", c.Protocol, c.Host), - } - suite.testApplication = >smodel.Application{ - Name: "a test application", - Website: "https://some-application-website.com", - RedirectURI: "http://localhost:8080", - ClientID: "a-known-client-id", - ClientSecret: "some-secret", - Scopes: "read", - VapidKey: uuid.NewString(), - } -} - -// SetupTest creates a postgres connection and creates the oauth_clients table before each test -func (suite *AuthTestSuite) SetupTest() { - - log := logrus.New() - log.SetLevel(logrus.TraceLevel) - db, err := db.New(context.Background(), suite.config, log) - if err != nil { - logrus.Panicf("error creating database connection: %s", err) - } - - suite.db = db - - models := []interface{}{ - &oauth.Client{}, - &oauth.Token{}, - >smodel.User{}, - >smodel.Account{}, - >smodel.Application{}, - } - - for _, m := range models { - if err := suite.db.CreateTable(m); err != nil { - logrus.Panicf("db connection error: %s", err) - } - } - - suite.oauthServer = oauth.New(suite.db, log) - - if err := suite.db.Put(suite.testAccount); err != nil { - logrus.Panicf("could not insert test account into db: %s", err) - } - if err := suite.db.Put(suite.testUser); err != nil { - logrus.Panicf("could not insert test user into db: %s", err) - } - if err := suite.db.Put(suite.testClient); err != nil { - logrus.Panicf("could not insert test client into db: %s", err) - } - if err := suite.db.Put(suite.testApplication); err != nil { - logrus.Panicf("could not insert test application into db: %s", err) - } - -} - -// TearDownTest drops the oauth_clients table and closes the pg connection after each test -func (suite *AuthTestSuite) TearDownTest() { - models := []interface{}{ - &oauth.Client{}, - &oauth.Token{}, - >smodel.User{}, - >smodel.Account{}, - >smodel.Application{}, - } - for _, m := range models { - if err := suite.db.DropTable(m); err != nil { - logrus.Panicf("error dropping table: %s", err) - } - } - if err := suite.db.Stop(context.Background()); err != nil { - logrus.Panicf("error closing db connection: %s", err) - } - suite.db = nil -} - -func TestAuthTestSuite(t *testing.T) { - suite.Run(t, new(AuthTestSuite)) -} diff --git a/internal/apimodule/auth/authorize.go b/internal/apimodule/auth/authorize.go index bf525e09e..4bc1991ac 100644 --- a/internal/apimodule/auth/authorize.go +++ b/internal/apimodule/auth/authorize.go @@ -31,10 +31,10 @@ import ( "github.com/superseriousbusiness/gotosocial/internal/mastotypes/mastomodel" ) -// authorizeGETHandler should be served as GET at https://example.org/oauth/authorize +// 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. See here: https://docs.joinmastodon.org/methods/apps/oauth/#authorize-a-user -func (m *authModule) authorizeGETHandler(c *gin.Context) { +func (m *Module) AuthorizeGETHandler(c *gin.Context) { l := m.log.WithField("func", "AuthorizeGETHandler") s := sessions.Default(c) @@ -46,7 +46,7 @@ func (m *authModule) authorizeGETHandler(c *gin.Context) { if err := parseAuthForm(c, l); err != nil { c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) } else { - c.Redirect(http.StatusFound, authSignInPath) + c.Redirect(http.StatusFound, AuthSignInPath) } return } @@ -108,11 +108,11 @@ func (m *authModule) authorizeGETHandler(c *gin.Context) { }) } -// authorizePOSTHandler should be served as POST at https://example.org/oauth/authorize +// AuthorizePOSTHandler should be served as POST at https://example.org/oauth/authorize // 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. // See here: https://docs.joinmastodon.org/methods/apps/oauth/#authorize-a-user -func (m *authModule) authorizePOSTHandler(c *gin.Context) { +func (m *Module) AuthorizePOSTHandler(c *gin.Context) { l := m.log.WithField("func", "AuthorizePOSTHandler") s := sessions.Default(c) diff --git a/internal/apimodule/auth/middleware.go b/internal/apimodule/auth/middleware.go index 4ca1f47a2..1d9a85993 100644 --- a/internal/apimodule/auth/middleware.go +++ b/internal/apimodule/auth/middleware.go @@ -24,12 +24,12 @@ import ( "github.com/superseriousbusiness/gotosocial/internal/oauth" ) -// oauthTokenMiddleware checks if the client has presented a valid oauth Bearer token. +// OauthTokenMiddleware checks if the client has presented a valid oauth Bearer token. // If so, it will check the User that the token belongs to, and set that in the context of // the request. Then, it will look up the account for that user, and set that in the request too. // If user or account can't be found, then the handler won't *fail*, in case the server wants to allow // public requests that don't have a Bearer token set (eg., for public instance information and so on). -func (m *authModule) oauthTokenMiddleware(c *gin.Context) { +func (m *Module) OauthTokenMiddleware(c *gin.Context) { l := m.log.WithField("func", "ValidatePassword") l.Trace("entering OauthTokenMiddleware") diff --git a/internal/apimodule/auth/signin.go b/internal/apimodule/auth/signin.go index a6994c90e..44de0891c 100644 --- a/internal/apimodule/auth/signin.go +++ b/internal/apimodule/auth/signin.go @@ -28,23 +28,24 @@ import ( "golang.org/x/crypto/bcrypt" ) +// login just wraps a form-submitted username (we want an email) and password type login struct { Email string `form:"username"` Password string `form:"password"` } -// signInGETHandler should be served at https://example.org/auth/sign_in. +// 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 -func (m *authModule) signInGETHandler(c *gin.Context) { +func (m *Module) SignInGETHandler(c *gin.Context) { m.log.WithField("func", "SignInGETHandler").Trace("serving sign in html") c.HTML(http.StatusOK, "sign-in.tmpl", gin.H{}) } -// signInPOSTHandler should be served at https://example.org/auth/sign_in. +// 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 *authModule) signInPOSTHandler(c *gin.Context) { +func (m *Module) SignInPOSTHandler(c *gin.Context) { l := m.log.WithField("func", "SignInPOSTHandler") s := sessions.Default(c) form := &login{} @@ -54,7 +55,7 @@ func (m *authModule) signInPOSTHandler(c *gin.Context) { } l.Tracef("parsed form: %+v", form) - userid, err := m.validatePassword(form.Email, form.Password) + userid, err := m.ValidatePassword(form.Email, form.Password) if err != nil { c.String(http.StatusForbidden, err.Error()) return @@ -67,14 +68,14 @@ func (m *authModule) signInPOSTHandler(c *gin.Context) { } l.Trace("redirecting to auth page") - c.Redirect(http.StatusFound, oauthAuthorizePath) + c.Redirect(http.StatusFound, OauthAuthorizePath) } -// validatePassword takes an email address and a password. +// ValidatePassword takes an email address and a password. // 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 uuid) 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 *authModule) validatePassword(email string, password string) (userid string, err error) { +func (m *Module) ValidatePassword(email string, password string) (userid string, err error) { l := m.log.WithField("func", "ValidatePassword") // make sure an email/password was provided and bail if not diff --git a/internal/apimodule/auth/test/auth_test.go b/internal/apimodule/auth/test/auth_test.go new file mode 100644 index 000000000..2c272e985 --- /dev/null +++ b/internal/apimodule/auth/test/auth_test.go @@ -0,0 +1,166 @@ +/* + GoToSocial + Copyright (C) 2021 GoToSocial Authors admin@gotosocial.org + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . +*/ + +package auth + +import ( + "context" + "fmt" + "testing" + + "github.com/google/uuid" + "github.com/sirupsen/logrus" + "github.com/stretchr/testify/suite" + "github.com/superseriousbusiness/gotosocial/internal/config" + "github.com/superseriousbusiness/gotosocial/internal/db" + "github.com/superseriousbusiness/gotosocial/internal/db/gtsmodel" + "github.com/superseriousbusiness/gotosocial/internal/oauth" + "golang.org/x/crypto/bcrypt" +) + +type AuthTestSuite struct { + suite.Suite + oauthServer oauth.Server + db db.DB + testAccount *gtsmodel.Account + testApplication *gtsmodel.Application + testUser *gtsmodel.User + testClient *oauth.Client + config *config.Config +} + +// SetupSuite sets some variables on the suite that we can use as consts (more or less) throughout +func (suite *AuthTestSuite) SetupSuite() { + c := config.Empty() + // we're running on localhost without https so set the protocol to http + c.Protocol = "http" + // just for testing + c.Host = "localhost:8080" + // because go tests are run within the test package directory, we need to fiddle with the templateconfig + // basedir in a way that we wouldn't normally have to do when running the binary, in order to make + // the templates actually load + c.TemplateConfig.BaseDir = "../../../web/template/" + c.DBConfig = &config.DBConfig{ + Type: "postgres", + Address: "localhost", + Port: 5432, + User: "postgres", + Password: "postgres", + Database: "postgres", + ApplicationName: "gotosocial", + } + suite.config = c + + encryptedPassword, err := bcrypt.GenerateFromPassword([]byte("password"), bcrypt.DefaultCost) + if err != nil { + logrus.Panicf("error encrypting user pass: %s", err) + } + + acctID := uuid.NewString() + + suite.testAccount = >smodel.Account{ + ID: acctID, + Username: "test_user", + } + suite.testUser = >smodel.User{ + EncryptedPassword: string(encryptedPassword), + Email: "user@example.org", + AccountID: acctID, + } + suite.testClient = &oauth.Client{ + ID: "a-known-client-id", + Secret: "some-secret", + Domain: fmt.Sprintf("%s://%s", c.Protocol, c.Host), + } + suite.testApplication = >smodel.Application{ + Name: "a test application", + Website: "https://some-application-website.com", + RedirectURI: "http://localhost:8080", + ClientID: "a-known-client-id", + ClientSecret: "some-secret", + Scopes: "read", + VapidKey: uuid.NewString(), + } +} + +// SetupTest creates a postgres connection and creates the oauth_clients table before each test +func (suite *AuthTestSuite) SetupTest() { + + log := logrus.New() + log.SetLevel(logrus.TraceLevel) + db, err := db.New(context.Background(), suite.config, log) + if err != nil { + logrus.Panicf("error creating database connection: %s", err) + } + + suite.db = db + + models := []interface{}{ + &oauth.Client{}, + &oauth.Token{}, + >smodel.User{}, + >smodel.Account{}, + >smodel.Application{}, + } + + for _, m := range models { + if err := suite.db.CreateTable(m); err != nil { + logrus.Panicf("db connection error: %s", err) + } + } + + suite.oauthServer = oauth.New(suite.db, log) + + if err := suite.db.Put(suite.testAccount); err != nil { + logrus.Panicf("could not insert test account into db: %s", err) + } + if err := suite.db.Put(suite.testUser); err != nil { + logrus.Panicf("could not insert test user into db: %s", err) + } + if err := suite.db.Put(suite.testClient); err != nil { + logrus.Panicf("could not insert test client into db: %s", err) + } + if err := suite.db.Put(suite.testApplication); err != nil { + logrus.Panicf("could not insert test application into db: %s", err) + } + +} + +// TearDownTest drops the oauth_clients table and closes the pg connection after each test +func (suite *AuthTestSuite) TearDownTest() { + models := []interface{}{ + &oauth.Client{}, + &oauth.Token{}, + >smodel.User{}, + >smodel.Account{}, + >smodel.Application{}, + } + for _, m := range models { + if err := suite.db.DropTable(m); err != nil { + logrus.Panicf("error dropping table: %s", err) + } + } + if err := suite.db.Stop(context.Background()); err != nil { + logrus.Panicf("error closing db connection: %s", err) + } + suite.db = nil +} + +func TestAuthTestSuite(t *testing.T) { + suite.Run(t, new(AuthTestSuite)) +} diff --git a/internal/apimodule/auth/token.go b/internal/apimodule/auth/token.go index 1e54b6ab3..c531a3009 100644 --- a/internal/apimodule/auth/token.go +++ b/internal/apimodule/auth/token.go @@ -24,10 +24,10 @@ import ( "github.com/gin-gonic/gin" ) -// tokenPOSTHandler should be served as a POST at https://example.org/oauth/token +// 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. // See https://docs.joinmastodon.org/methods/apps/oauth/#obtain-a-token -func (m *authModule) tokenPOSTHandler(c *gin.Context) { +func (m *Module) TokenPOSTHandler(c *gin.Context) { l := m.log.WithField("func", "TokenPOSTHandler") l.Trace("entered TokenPOSTHandler") if err := m.server.HandleTokenRequest(c.Writer, c.Request); err != nil { diff --git a/internal/apimodule/fileserver/fileserver.go b/internal/apimodule/fileserver/fileserver.go index 25f3be864..7651c8cc1 100644 --- a/internal/apimodule/fileserver/fileserver.go +++ b/internal/apimodule/fileserver/fileserver.go @@ -32,12 +32,14 @@ import ( ) const ( + // AccountIDKey is the url key for account id (an account uuid) AccountIDKey = "account_id" + // MediaTypeKey is the url key for media type (usually something like attachment or header etc) MediaTypeKey = "media_type" + // MediaSizeKey is the url key for the desired media size--original/small/static MediaSizeKey = "media_size" + // FileNameKey is the actual filename being sought. Will usually be a UUID then something like .jpeg FileNameKey = "file_name" - - FilesPath = "files" ) // FileServer implements the RESTAPIModule interface. @@ -67,6 +69,7 @@ func (m *FileServer) Route(s router.Router) error { return nil } +// CreateTables populates necessary tables in the given DB func (m *FileServer) CreateTables(db db.DB) error { models := []interface{}{ >smodel.MediaAttachment{}, diff --git a/internal/apimodule/fileserver/test/servefile_test.go b/internal/apimodule/fileserver/test/servefile_test.go index 8af2b40b3..516e3528c 100644 --- a/internal/apimodule/fileserver/test/servefile_test.go +++ b/internal/apimodule/fileserver/test/servefile_test.go @@ -49,7 +49,7 @@ type ServeFileTestSuite struct { log *logrus.Logger storage storage.Storage mastoConverter mastotypes.Converter - mediaHandler media.MediaHandler + mediaHandler media.Handler oauthServer oauth.Server // standard suite models diff --git a/internal/apimodule/media/media.go b/internal/apimodule/media/media.go index c8d3d7425..8fb9f16ec 100644 --- a/internal/apimodule/media/media.go +++ b/internal/apimodule/media/media.go @@ -32,10 +32,12 @@ import ( "github.com/superseriousbusiness/gotosocial/internal/router" ) +// BasePath is the base API path for making media requests const BasePath = "/api/v1/media" -type MediaModule struct { - mediaHandler media.MediaHandler +// Module implements the ClientAPIModule interface for media +type Module struct { + mediaHandler media.Handler config *config.Config db db.DB mastoConverter mastotypes.Converter @@ -43,8 +45,8 @@ type MediaModule struct { } // New returns a new auth module -func New(db db.DB, mediaHandler media.MediaHandler, mastoConverter mastotypes.Converter, config *config.Config, log *logrus.Logger) apimodule.ClientAPIModule { - return &MediaModule{ +func New(db db.DB, mediaHandler media.Handler, mastoConverter mastotypes.Converter, config *config.Config, log *logrus.Logger) apimodule.ClientAPIModule { + return &Module{ mediaHandler: mediaHandler, config: config, db: db, @@ -54,12 +56,13 @@ func New(db db.DB, mediaHandler media.MediaHandler, mastoConverter mastotypes.Co } // Route satisfies the RESTAPIModule interface -func (m *MediaModule) Route(s router.Router) error { +func (m *Module) Route(s router.Router) error { s.AttachHandler(http.MethodPost, BasePath, m.MediaCreatePOSTHandler) return nil } -func (m *MediaModule) CreateTables(db db.DB) error { +// CreateTables populates necessary tables in the given DB +func (m *Module) CreateTables(db db.DB) error { models := []interface{}{ >smodel.MediaAttachment{}, } diff --git a/internal/apimodule/media/mediacreate.go b/internal/apimodule/media/mediacreate.go index 06b6d5be6..ee713a471 100644 --- a/internal/apimodule/media/mediacreate.go +++ b/internal/apimodule/media/mediacreate.go @@ -33,7 +33,8 @@ import ( "github.com/superseriousbusiness/gotosocial/internal/oauth" ) -func (m *MediaModule) MediaCreatePOSTHandler(c *gin.Context) { +// MediaCreatePOSTHandler handles requests to create/upload media attachments +func (m *Module) MediaCreatePOSTHandler(c *gin.Context) { l := m.log.WithField("func", "statusCreatePOSTHandler") authed, err := oauth.MustAuth(c, true, true, true, true) // posting new media is serious business so we want *everything* if err != nil { diff --git a/internal/apimodule/media/test/mediacreate_test.go b/internal/apimodule/media/test/mediacreate_test.go index 01a0a6a31..30bbb117a 100644 --- a/internal/apimodule/media/test/mediacreate_test.go +++ b/internal/apimodule/media/test/mediacreate_test.go @@ -52,7 +52,7 @@ type MediaCreateTestSuite struct { log *logrus.Logger storage storage.Storage mastoConverter mastotypes.Converter - mediaHandler media.MediaHandler + mediaHandler media.Handler oauthServer oauth.Server // standard suite models @@ -64,7 +64,7 @@ type MediaCreateTestSuite struct { testAttachments map[string]*gtsmodel.MediaAttachment // item being tested - mediaModule *mediamodule.MediaModule + mediaModule *mediamodule.Module } /* @@ -82,7 +82,7 @@ func (suite *MediaCreateTestSuite) SetupSuite() { suite.oauthServer = testrig.NewTestOauthServer(suite.db) // setup module being tested - suite.mediaModule = mediamodule.New(suite.db, suite.mediaHandler, suite.mastoConverter, suite.config, suite.log).(*mediamodule.MediaModule) + suite.mediaModule = mediamodule.New(suite.db, suite.mediaHandler, suite.mastoConverter, suite.config, suite.log).(*mediamodule.Module) } func (suite *MediaCreateTestSuite) TearDownSuite() { @@ -115,7 +115,7 @@ func (suite *MediaCreateTestSuite) TestStatusCreatePOSTImageHandlerSuccessful() // set up the context for the request t := suite.testTokens["local_account_1"] - oauthToken := oauth.PGTokenToOauthToken(t) + oauthToken := oauth.TokenToOauthToken(t) recorder := httptest.NewRecorder() ctx, _ := gin.CreateTestContext(recorder) ctx.Set(oauth.SessionAuthorizedApplication, suite.testApplications["application_1"]) diff --git a/internal/apimodule/security/flocblock.go b/internal/apimodule/security/flocblock.go index 4bb011d4d..7cedcde6b 100644 --- a/internal/apimodule/security/flocblock.go +++ b/internal/apimodule/security/flocblock.go @@ -20,8 +20,9 @@ package security import "github.com/gin-gonic/gin" -// flocBlock prevents google chrome cohort tracking by writing the Permissions-Policy header after all other parts of the request have been completed. +// FlocBlock is a middleware that prevents google chrome cohort tracking by +// writing the Permissions-Policy header after all other parts of the request have been completed. // See: https://plausible.io/blog/google-floc -func (m *module) flocBlock(c *gin.Context) { +func (m *Module) FlocBlock(c *gin.Context) { c.Header("Permissions-Policy", "interest-cohort=()") } diff --git a/internal/apimodule/security/security.go b/internal/apimodule/security/security.go index cfac2ce1e..8f805bc93 100644 --- a/internal/apimodule/security/security.go +++ b/internal/apimodule/security/security.go @@ -26,25 +26,27 @@ import ( "github.com/superseriousbusiness/gotosocial/internal/router" ) -// module implements the apiclient interface -type module struct { +// Module implements the ClientAPIModule interface for security middleware +type Module struct { config *config.Config log *logrus.Logger } // New returns a new security module func New(config *config.Config, log *logrus.Logger) apimodule.ClientAPIModule { - return &module{ + return &Module{ config: config, log: log, } } -func (m *module) Route(s router.Router) error { - s.AttachMiddleware(m.flocBlock) +// Route attaches security middleware to the given router +func (m *Module) Route(s router.Router) error { + s.AttachMiddleware(m.FlocBlock) return nil } -func (m *module) CreateTables(db db.DB) error { +// CreateTables doesn't do diddly squat at the moment, it's just for fulfilling the interface +func (m *Module) CreateTables(db db.DB) error { return nil } diff --git a/internal/apimodule/status/status.go b/internal/apimodule/status/status.go index e65293b62..73a1b5847 100644 --- a/internal/apimodule/status/status.go +++ b/internal/apimodule/status/status.go @@ -36,42 +36,60 @@ import ( ) const ( + // IDKey is for status UUIDs IDKey = "id" + // BasePath is the base path for serving the status API BasePath = "/api/v1/statuses" + // BasePathWithID is just the base path with the ID key in it. + // Use this anywhere you need to know the ID of the status being queried. BasePathWithID = BasePath + "/:" + IDKey + // ContextPath is used for fetching context of posts ContextPath = BasePathWithID + "/context" + // FavouritedPath is for seeing who's faved a given status FavouritedPath = BasePathWithID + "/favourited_by" + // FavouritePath is for posting a fave on a status FavouritePath = BasePathWithID + "/favourite" + // UnfavouritePath is for removing a fave from a status UnfavouritePath = BasePathWithID + "/unfavourite" + // RebloggedPath is for seeing who's boosted a given status RebloggedPath = BasePathWithID + "/reblogged_by" + // ReblogPath is for boosting/reblogging a given status ReblogPath = BasePathWithID + "/reblog" + // UnreblogPath is for undoing a boost/reblog of a given status UnreblogPath = BasePathWithID + "/unreblog" + // BookmarkPath is for creating a bookmark on a given status BookmarkPath = BasePathWithID + "/bookmark" + // UnbookmarkPath is for removing a bookmark from a given status UnbookmarkPath = BasePathWithID + "/unbookmark" + // MutePath is for muting a given status so that notifications will no longer be received about it. MutePath = BasePathWithID + "/mute" + // UnmutePath is for undoing an existing mute UnmutePath = BasePathWithID + "/unmute" + // PinPath is for pinning a status to an account profile so that it's the first thing people see PinPath = BasePathWithID + "/pin" + // UnpinPath is for undoing a pin and returning a status to the ever-swirling drain of time and entropy UnpinPath = BasePathWithID + "/unpin" ) -type StatusModule struct { +// Module implements the ClientAPIModule interface for every related to posting/deleting/interacting with statuses +type Module struct { config *config.Config db db.DB - mediaHandler media.MediaHandler + mediaHandler media.Handler mastoConverter mastotypes.Converter distributor distributor.Distributor log *logrus.Logger } // New returns a new account module -func New(config *config.Config, db db.DB, mediaHandler media.MediaHandler, mastoConverter mastotypes.Converter, distributor distributor.Distributor, log *logrus.Logger) apimodule.ClientAPIModule { - return &StatusModule{ +func New(config *config.Config, db db.DB, mediaHandler media.Handler, mastoConverter mastotypes.Converter, distributor distributor.Distributor, log *logrus.Logger) apimodule.ClientAPIModule { + return &Module{ config: config, db: db, mediaHandler: mediaHandler, @@ -82,7 +100,7 @@ func New(config *config.Config, db db.DB, mediaHandler media.MediaHandler, masto } // Route attaches all routes from this module to the given router -func (m *StatusModule) Route(r router.Router) error { +func (m *Module) Route(r router.Router) error { r.AttachHandler(http.MethodPost, BasePath, m.StatusCreatePOSTHandler) r.AttachHandler(http.MethodDelete, BasePathWithID, m.StatusDELETEHandler) @@ -93,7 +111,8 @@ func (m *StatusModule) Route(r router.Router) error { return nil } -func (m *StatusModule) CreateTables(db db.DB) error { +// CreateTables populates necessary tables in the given DB +func (m *Module) CreateTables(db db.DB) error { models := []interface{}{ >smodel.User{}, >smodel.Account{}, @@ -121,7 +140,8 @@ func (m *StatusModule) CreateTables(db db.DB) error { return nil } -func (m *StatusModule) muxHandler(c *gin.Context) { +// muxHandler is a little workaround to overcome the limitations of Gin +func (m *Module) muxHandler(c *gin.Context) { m.log.Debug("entering mux handler") ru := c.Request.RequestURI diff --git a/internal/apimodule/status/statuscreate.go b/internal/apimodule/status/statuscreate.go index ce1cc6da7..97354e767 100644 --- a/internal/apimodule/status/statuscreate.go +++ b/internal/apimodule/status/statuscreate.go @@ -53,7 +53,8 @@ type advancedVisibilityFlagsForm struct { Likeable *bool `form:"likeable"` } -func (m *StatusModule) StatusCreatePOSTHandler(c *gin.Context) { +// StatusCreatePOSTHandler deals with the creation of new statuses +func (m *Module) StatusCreatePOSTHandler(c *gin.Context) { l := m.log.WithField("func", "statusCreatePOSTHandler") authed, err := oauth.MustAuth(c, true, true, true, true) // posting a status is serious business so we want *everything* if err != nil { @@ -318,7 +319,7 @@ func parseVisibility(form *advancedStatusCreateForm, accountDefaultVis gtsmodel. return nil } -func (m *StatusModule) parseReplyToID(form *advancedStatusCreateForm, thisAccountID string, status *gtsmodel.Status) error { +func (m *Module) parseReplyToID(form *advancedStatusCreateForm, thisAccountID string, status *gtsmodel.Status) error { if form.InReplyToID == "" { return nil } @@ -336,9 +337,8 @@ func (m *StatusModule) parseReplyToID(form *advancedStatusCreateForm, thisAccoun if err := m.db.GetByID(form.InReplyToID, repliedStatus); err != nil { if _, ok := err.(db.ErrNoEntries); ok { return fmt.Errorf("status with id %s not replyable because it doesn't exist", form.InReplyToID) - } else { - return fmt.Errorf("status with id %s not replyable: %s", form.InReplyToID, err) } + return fmt.Errorf("status with id %s not replyable: %s", form.InReplyToID, err) } if !repliedStatus.VisibilityAdvanced.Replyable { @@ -349,9 +349,8 @@ func (m *StatusModule) parseReplyToID(form *advancedStatusCreateForm, thisAccoun if err := m.db.GetByID(repliedStatus.AccountID, repliedAccount); err != nil { if _, ok := err.(db.ErrNoEntries); ok { return fmt.Errorf("status with id %s not replyable because account id %s is not known", form.InReplyToID, repliedStatus.AccountID) - } else { - return fmt.Errorf("status with id %s not replyable: %s", form.InReplyToID, err) } + return fmt.Errorf("status with id %s not replyable: %s", form.InReplyToID, err) } // check if a block exists if blocked, err := m.db.Blocked(thisAccountID, repliedAccount.ID); err != nil { @@ -367,7 +366,7 @@ func (m *StatusModule) parseReplyToID(form *advancedStatusCreateForm, thisAccoun return nil } -func (m *StatusModule) parseMediaIDs(form *advancedStatusCreateForm, thisAccountID string, status *gtsmodel.Status) error { +func (m *Module) parseMediaIDs(form *advancedStatusCreateForm, thisAccountID string, status *gtsmodel.Status) error { if form.MediaIDs == nil { return nil } @@ -408,7 +407,7 @@ func parseLanguage(form *advancedStatusCreateForm, accountDefaultLanguage string return nil } -func (m *StatusModule) parseMentions(form *advancedStatusCreateForm, accountID string, status *gtsmodel.Status) error { +func (m *Module) parseMentions(form *advancedStatusCreateForm, accountID string, status *gtsmodel.Status) error { menchies := []string{} gtsMenchies, err := m.db.MentionStringsToMentions(util.DeriveMentions(form.Status), accountID, status.ID) if err != nil { @@ -427,7 +426,7 @@ func (m *StatusModule) parseMentions(form *advancedStatusCreateForm, accountID s return nil } -func (m *StatusModule) parseTags(form *advancedStatusCreateForm, accountID string, status *gtsmodel.Status) error { +func (m *Module) parseTags(form *advancedStatusCreateForm, accountID string, status *gtsmodel.Status) error { tags := []string{} gtsTags, err := m.db.TagStringsToTags(util.DeriveHashtags(form.Status), accountID, status.ID) if err != nil { @@ -446,7 +445,7 @@ func (m *StatusModule) parseTags(form *advancedStatusCreateForm, accountID strin return nil } -func (m *StatusModule) parseEmojis(form *advancedStatusCreateForm, accountID string, status *gtsmodel.Status) error { +func (m *Module) parseEmojis(form *advancedStatusCreateForm, accountID string, status *gtsmodel.Status) error { emojis := []string{} gtsEmojis, err := m.db.EmojiStringsToEmojis(util.DeriveEmojis(form.Status), accountID, status.ID) if err != nil { diff --git a/internal/apimodule/status/statusdelete.go b/internal/apimodule/status/statusdelete.go index f67d035d8..01dfe81df 100644 --- a/internal/apimodule/status/statusdelete.go +++ b/internal/apimodule/status/statusdelete.go @@ -29,7 +29,8 @@ import ( "github.com/superseriousbusiness/gotosocial/internal/oauth" ) -func (m *StatusModule) StatusDELETEHandler(c *gin.Context) { +// StatusDELETEHandler verifies and handles deletion of a status +func (m *Module) StatusDELETEHandler(c *gin.Context) { l := m.log.WithFields(logrus.Fields{ "func": "StatusDELETEHandler", "request_uri": c.Request.RequestURI, diff --git a/internal/apimodule/status/statusfave.go b/internal/apimodule/status/statusfave.go index de475b905..9ce68af09 100644 --- a/internal/apimodule/status/statusfave.go +++ b/internal/apimodule/status/statusfave.go @@ -29,7 +29,8 @@ import ( "github.com/superseriousbusiness/gotosocial/internal/oauth" ) -func (m *StatusModule) StatusFavePOSTHandler(c *gin.Context) { +// StatusFavePOSTHandler handles fave requests against a given status ID +func (m *Module) StatusFavePOSTHandler(c *gin.Context) { l := m.log.WithFields(logrus.Fields{ "func": "StatusFavePOSTHandler", "request_uri": c.Request.RequestURI, diff --git a/internal/apimodule/status/statusfavedby.go b/internal/apimodule/status/statusfavedby.go index 76a50b2ca..58236edc2 100644 --- a/internal/apimodule/status/statusfavedby.go +++ b/internal/apimodule/status/statusfavedby.go @@ -29,7 +29,8 @@ import ( "github.com/superseriousbusiness/gotosocial/internal/oauth" ) -func (m *StatusModule) StatusFavedByGETHandler(c *gin.Context) { +// StatusFavedByGETHandler is for serving a list of accounts that have faved a given status +func (m *Module) StatusFavedByGETHandler(c *gin.Context) { l := m.log.WithFields(logrus.Fields{ "func": "statusGETHandler", "request_uri": c.Request.RequestURI, diff --git a/internal/apimodule/status/statusget.go b/internal/apimodule/status/statusget.go index ed2e89159..76918c782 100644 --- a/internal/apimodule/status/statusget.go +++ b/internal/apimodule/status/statusget.go @@ -28,7 +28,8 @@ import ( "github.com/superseriousbusiness/gotosocial/internal/oauth" ) -func (m *StatusModule) StatusGETHandler(c *gin.Context) { +// StatusGETHandler is for handling requests to just get one status based on its ID +func (m *Module) StatusGETHandler(c *gin.Context) { l := m.log.WithFields(logrus.Fields{ "func": "statusGETHandler", "request_uri": c.Request.RequestURI, diff --git a/internal/apimodule/status/statusunfave.go b/internal/apimodule/status/statusunfave.go index 61ffd8e4c..9c06eaf92 100644 --- a/internal/apimodule/status/statusunfave.go +++ b/internal/apimodule/status/statusunfave.go @@ -29,7 +29,8 @@ import ( "github.com/superseriousbusiness/gotosocial/internal/oauth" ) -func (m *StatusModule) StatusUnfavePOSTHandler(c *gin.Context) { +// StatusUnfavePOSTHandler is for undoing a fave on a status with a given ID +func (m *Module) StatusUnfavePOSTHandler(c *gin.Context) { l := m.log.WithFields(logrus.Fields{ "func": "StatusUnfavePOSTHandler", "request_uri": c.Request.RequestURI, diff --git a/internal/apimodule/status/test/statuscreate_test.go b/internal/apimodule/status/test/statuscreate_test.go index 6c5aa6b7d..d143ac9a7 100644 --- a/internal/apimodule/status/test/statuscreate_test.go +++ b/internal/apimodule/status/test/statuscreate_test.go @@ -52,7 +52,7 @@ type StatusCreateTestSuite struct { log *logrus.Logger storage storage.Storage mastoConverter mastotypes.Converter - mediaHandler media.MediaHandler + mediaHandler media.Handler oauthServer oauth.Server distributor distributor.Distributor @@ -65,7 +65,7 @@ type StatusCreateTestSuite struct { testAttachments map[string]*gtsmodel.MediaAttachment // module being tested - statusModule *status.StatusModule + statusModule *status.Module } /* @@ -85,7 +85,7 @@ func (suite *StatusCreateTestSuite) SetupSuite() { suite.distributor = testrig.NewTestDistributor() // setup module being tested - suite.statusModule = status.New(suite.config, suite.db, suite.mediaHandler, suite.mastoConverter, suite.distributor, suite.log).(*status.StatusModule) + suite.statusModule = status.New(suite.config, suite.db, suite.mediaHandler, suite.mastoConverter, suite.distributor, suite.log).(*status.Module) } func (suite *StatusCreateTestSuite) TearDownSuite() { @@ -121,7 +121,7 @@ func (suite *StatusCreateTestSuite) TearDownTest() { func (suite *StatusCreateTestSuite) TestPostNewStatus() { t := suite.testTokens["local_account_1"] - oauthToken := oauth.PGTokenToOauthToken(t) + oauthToken := oauth.TokenToOauthToken(t) // setup recorder := httptest.NewRecorder() @@ -175,7 +175,7 @@ func (suite *StatusCreateTestSuite) TestPostNewStatus() { func (suite *StatusCreateTestSuite) TestPostNewStatusWithEmoji() { t := suite.testTokens["local_account_1"] - oauthToken := oauth.PGTokenToOauthToken(t) + oauthToken := oauth.TokenToOauthToken(t) // setup recorder := httptest.NewRecorder() @@ -216,7 +216,7 @@ func (suite *StatusCreateTestSuite) TestPostNewStatusWithEmoji() { // Try to reply to a status that doesn't exist func (suite *StatusCreateTestSuite) TestReplyToNonexistentStatus() { t := suite.testTokens["local_account_1"] - oauthToken := oauth.PGTokenToOauthToken(t) + oauthToken := oauth.TokenToOauthToken(t) // setup recorder := httptest.NewRecorder() @@ -247,7 +247,7 @@ func (suite *StatusCreateTestSuite) TestReplyToNonexistentStatus() { // Post a reply to the status of a local user that allows replies. func (suite *StatusCreateTestSuite) TestReplyToLocalStatus() { t := suite.testTokens["local_account_1"] - oauthToken := oauth.PGTokenToOauthToken(t) + oauthToken := oauth.TokenToOauthToken(t) // setup recorder := httptest.NewRecorder() @@ -287,7 +287,7 @@ func (suite *StatusCreateTestSuite) TestReplyToLocalStatus() { // Take a media file which is currently not associated with a status, and attach it to a new status. func (suite *StatusCreateTestSuite) TestAttachNewMediaSuccess() { t := suite.testTokens["local_account_1"] - oauthToken := oauth.PGTokenToOauthToken(t) + oauthToken := oauth.TokenToOauthToken(t) // setup recorder := httptest.NewRecorder() diff --git a/internal/apimodule/status/test/statusfave_test.go b/internal/apimodule/status/test/statusfave_test.go index b15e57e77..9ccf58948 100644 --- a/internal/apimodule/status/test/statusfave_test.go +++ b/internal/apimodule/status/test/statusfave_test.go @@ -52,7 +52,7 @@ type StatusFaveTestSuite struct { log *logrus.Logger storage storage.Storage mastoConverter mastotypes.Converter - mediaHandler media.MediaHandler + mediaHandler media.Handler oauthServer oauth.Server distributor distributor.Distributor @@ -66,7 +66,7 @@ type StatusFaveTestSuite struct { testStatuses map[string]*gtsmodel.Status // module being tested - statusModule *status.StatusModule + statusModule *status.Module } /* @@ -86,7 +86,7 @@ func (suite *StatusFaveTestSuite) SetupSuite() { suite.distributor = testrig.NewTestDistributor() // setup module being tested - suite.statusModule = status.New(suite.config, suite.db, suite.mediaHandler, suite.mastoConverter, suite.distributor, suite.log).(*status.StatusModule) + suite.statusModule = status.New(suite.config, suite.db, suite.mediaHandler, suite.mastoConverter, suite.distributor, suite.log).(*status.Module) } func (suite *StatusFaveTestSuite) TearDownSuite() { @@ -120,7 +120,7 @@ func (suite *StatusFaveTestSuite) TearDownTest() { func (suite *StatusFaveTestSuite) TestPostFave() { t := suite.testTokens["local_account_1"] - oauthToken := oauth.PGTokenToOauthToken(t) + oauthToken := oauth.TokenToOauthToken(t) targetStatus := suite.testStatuses["admin_account_status_2"] @@ -168,7 +168,7 @@ func (suite *StatusFaveTestSuite) TestPostFave() { func (suite *StatusFaveTestSuite) TestPostUnfaveable() { t := suite.testTokens["local_account_1"] - oauthToken := oauth.PGTokenToOauthToken(t) + oauthToken := oauth.TokenToOauthToken(t) targetStatus := suite.testStatuses["local_account_2_status_3"] // this one is unlikeable and unreplyable diff --git a/internal/apimodule/status/test/statusfavedby_test.go b/internal/apimodule/status/test/statusfavedby_test.go index 83f66562b..169543a81 100644 --- a/internal/apimodule/status/test/statusfavedby_test.go +++ b/internal/apimodule/status/test/statusfavedby_test.go @@ -52,7 +52,7 @@ type StatusFavedByTestSuite struct { log *logrus.Logger storage storage.Storage mastoConverter mastotypes.Converter - mediaHandler media.MediaHandler + mediaHandler media.Handler oauthServer oauth.Server distributor distributor.Distributor @@ -66,7 +66,7 @@ type StatusFavedByTestSuite struct { testStatuses map[string]*gtsmodel.Status // module being tested - statusModule *status.StatusModule + statusModule *status.Module } // SetupSuite sets some variables on the suite that we can use as consts (more or less) throughout @@ -82,7 +82,7 @@ func (suite *StatusFavedByTestSuite) SetupSuite() { suite.distributor = testrig.NewTestDistributor() // setup module being tested - suite.statusModule = status.New(suite.config, suite.db, suite.mediaHandler, suite.mastoConverter, suite.distributor, suite.log).(*status.StatusModule) + suite.statusModule = status.New(suite.config, suite.db, suite.mediaHandler, suite.mastoConverter, suite.distributor, suite.log).(*status.Module) } func (suite *StatusFavedByTestSuite) TearDownSuite() { @@ -114,7 +114,7 @@ func (suite *StatusFavedByTestSuite) TearDownTest() { func (suite *StatusFavedByTestSuite) TestGetFavedBy() { t := suite.testTokens["local_account_2"] - oauthToken := oauth.PGTokenToOauthToken(t) + oauthToken := oauth.TokenToOauthToken(t) targetStatus := suite.testStatuses["admin_account_status_1"] // this status is faved by local_account_1 diff --git a/internal/apimodule/status/test/statusget_test.go b/internal/apimodule/status/test/statusget_test.go index 2c2e98acd..ce817d247 100644 --- a/internal/apimodule/status/test/statusget_test.go +++ b/internal/apimodule/status/test/statusget_test.go @@ -43,7 +43,7 @@ type StatusGetTestSuite struct { log *logrus.Logger storage storage.Storage mastoConverter mastotypes.Converter - mediaHandler media.MediaHandler + mediaHandler media.Handler oauthServer oauth.Server distributor distributor.Distributor @@ -56,7 +56,7 @@ type StatusGetTestSuite struct { testAttachments map[string]*gtsmodel.MediaAttachment // module being tested - statusModule *status.StatusModule + statusModule *status.Module } /* @@ -76,7 +76,7 @@ func (suite *StatusGetTestSuite) SetupSuite() { suite.distributor = testrig.NewTestDistributor() // setup module being tested - suite.statusModule = status.New(suite.config, suite.db, suite.mediaHandler, suite.mastoConverter, suite.distributor, suite.log).(*status.StatusModule) + suite.statusModule = status.New(suite.config, suite.db, suite.mediaHandler, suite.mastoConverter, suite.distributor, suite.log).(*status.Module) } func (suite *StatusGetTestSuite) TearDownSuite() { diff --git a/internal/apimodule/status/test/statusunfave_test.go b/internal/apimodule/status/test/statusunfave_test.go index 81276a1ed..5f5277921 100644 --- a/internal/apimodule/status/test/statusunfave_test.go +++ b/internal/apimodule/status/test/statusunfave_test.go @@ -52,7 +52,7 @@ type StatusUnfaveTestSuite struct { log *logrus.Logger storage storage.Storage mastoConverter mastotypes.Converter - mediaHandler media.MediaHandler + mediaHandler media.Handler oauthServer oauth.Server distributor distributor.Distributor @@ -66,7 +66,7 @@ type StatusUnfaveTestSuite struct { testStatuses map[string]*gtsmodel.Status // module being tested - statusModule *status.StatusModule + statusModule *status.Module } /* @@ -86,7 +86,7 @@ func (suite *StatusUnfaveTestSuite) SetupSuite() { suite.distributor = testrig.NewTestDistributor() // setup module being tested - suite.statusModule = status.New(suite.config, suite.db, suite.mediaHandler, suite.mastoConverter, suite.distributor, suite.log).(*status.StatusModule) + suite.statusModule = status.New(suite.config, suite.db, suite.mediaHandler, suite.mastoConverter, suite.distributor, suite.log).(*status.Module) } func (suite *StatusUnfaveTestSuite) TearDownSuite() { @@ -120,7 +120,7 @@ func (suite *StatusUnfaveTestSuite) TearDownTest() { func (suite *StatusUnfaveTestSuite) TestPostUnfave() { t := suite.testTokens["local_account_1"] - oauthToken := oauth.PGTokenToOauthToken(t) + oauthToken := oauth.TokenToOauthToken(t) // this is the status we wanna unfave: in the testrig it's already faved by this account targetStatus := suite.testStatuses["admin_account_status_1"] @@ -169,7 +169,7 @@ func (suite *StatusUnfaveTestSuite) TestPostUnfave() { func (suite *StatusUnfaveTestSuite) TestPostAlreadyNotFaved() { t := suite.testTokens["local_account_1"] - oauthToken := oauth.PGTokenToOauthToken(t) + oauthToken := oauth.TokenToOauthToken(t) // this is the status we wanna unfave: in the testrig it's not faved by this account targetStatus := suite.testStatuses["admin_account_status_2"] -- cgit v1.2.3