diff --git a/satellite/console/consoleweb/consoleapi/abtesting_test.go b/satellite/console/consoleweb/consoleapi/abtesting_test.go index 91f7f1307..aeb6e6e03 100644 --- a/satellite/console/consoleweb/consoleapi/abtesting_test.go +++ b/satellite/console/consoleweb/consoleapi/abtesting_test.go @@ -6,7 +6,6 @@ package consoleapi_test import ( "net/http" "testing" - "time" "github.com/stretchr/testify/require" "go.uber.org/zap" @@ -42,46 +41,16 @@ func TestABMethodsOnError(t *testing.T) { user, err := sat.AddUser(ctx, newUser, 1) require.NoError(t, err) - tokenInfo, err := sat.API.Console.Service.Token(ctx, console.AuthUser{Email: user.Email, Password: user.FullName}) + _, status, err := doRequestWithAuth(ctx, t, sat, user, http.MethodGet, "ab/values", nil) require.NoError(t, err) - - client := http.Client{} - - req, err := http.NewRequestWithContext(ctx, "GET", "http://"+planet.Satellites[0].API.Console.Listener.Addr().String()+"/api/v0/ab/values", nil) - require.NoError(t, err) - - expire := time.Now().AddDate(0, 0, 1) - cookie := http.Cookie{ - Name: "_tokenKey", - Path: "/", - Value: tokenInfo.Token.String(), - Expires: expire, - } - - req.AddCookie(&cookie) - - resp, err := client.Do(req) - require.NoError(t, err) - require.Equal(t, http.StatusInternalServerError, resp.StatusCode) - defer func() { - err = resp.Body.Close() - require.NoError(t, err) - }() + require.Equal(t, http.StatusInternalServerError, status) values, err := service.GetABValues(ctx, *user) require.Error(t, err) require.Nil(t, values) - req, err = http.NewRequestWithContext(ctx, "POST", "http://"+planet.Satellites[0].API.Console.Listener.Addr().String()+"/api/v0/ab/hit/upgrade-account", nil) + _, status, err = doRequestWithAuth(ctx, t, sat, user, http.MethodPost, "ab/hit/upgrade-account", nil) require.NoError(t, err) - req.AddCookie(&cookie) - - hitResp, err := client.Do(req) - require.NoError(t, err) - require.Equal(t, http.StatusOK, hitResp.StatusCode) - defer func() { - err = hitResp.Body.Close() - require.NoError(t, err) - }() + require.Equal(t, http.StatusOK, status) }) } diff --git a/satellite/console/consoleweb/consoleapi/apikeys_test.go b/satellite/console/consoleweb/consoleapi/apikeys_test.go index 3b8371e90..1bd2dde5b 100644 --- a/satellite/console/consoleweb/consoleapi/apikeys_test.go +++ b/satellite/console/consoleweb/consoleapi/apikeys_test.go @@ -5,10 +5,8 @@ package consoleapi_test import ( "encoding/json" - "io" "net/http" "testing" - "time" "github.com/stretchr/testify/require" "go.uber.org/zap" @@ -56,49 +54,24 @@ func Test_DeleteAPIKeyByNameAndProjectID(t *testing.T) { Secret: secret, } - // we are using full name as a password - tokenInfo, err := sat.API.Console.Service.Token(ctx, console.AuthUser{Email: user.Email, Password: user.FullName}) - require.NoError(t, err) - - client := http.Client{} - - expire := time.Now().AddDate(0, 0, 1) - cookie := http.Cookie{ - Name: "_tokenKey", - Path: "/", - Value: tokenInfo.Token.String(), - Expires: expire, - } - - deleteTestFunc := func(request *http.Request) func(t *testing.T) { + deleteTestFunc := func(endpointSuffix string) func(t *testing.T) { return func(t *testing.T) { created, err := sat.DB.Console().APIKeys().Create(ctx, key.Head(), apikey) require.NoError(t, err) - request.AddCookie(&cookie) - - result, err := client.Do(request) + endpoint := "api-keys/delete-by-name?name=" + apikey.Name + _, status, err := doRequestWithAuth(ctx, t, sat, user, http.MethodDelete, endpoint+endpointSuffix, nil) require.NoError(t, err) - require.Equal(t, http.StatusOK, result.StatusCode) + require.Equal(t, http.StatusOK, status) keyAfterDelete, err := sat.DB.Console().APIKeys().Get(ctx, created.ID) require.Error(t, err) require.Nil(t, keyAfterDelete) - - defer func() { - err = result.Body.Close() - require.NoError(t, err) - }() } } - req, err := http.NewRequestWithContext(ctx, http.MethodDelete, "http://"+planet.Satellites[0].API.Console.Listener.Addr().String()+"/api/v0/api-keys/delete-by-name?name="+apikey.Name+"&projectID="+project.ID.String(), nil) - require.NoError(t, err) - t.Run("delete by name and projectID", deleteTestFunc(req)) - - req, err = http.NewRequestWithContext(ctx, http.MethodDelete, "http://"+planet.Satellites[0].API.Console.Listener.Addr().String()+"/api/v0/api-keys/delete-by-name?name="+apikey.Name+"&publicID="+project.PublicID.String(), nil) - require.NoError(t, err) - t.Run("delete by name and publicID", deleteTestFunc(req)) + t.Run("delete by name and projectID", deleteTestFunc("&projectID="+project.ID.String())) + t.Run("delete by name and publicID", deleteTestFunc("&publicID="+project.PublicID.String())) }) } @@ -126,20 +99,6 @@ func Test_GetAllAPIKeyNamesByProjectID(t *testing.T) { project, err := sat.AddProject(ctx, user.ID, "apikeytest") require.NoError(t, err) - // we are using full name as a password - tokenInfo, err := sat.API.Console.Service.Token(ctx, console.AuthUser{Email: user.Email, Password: user.FullName}) - require.NoError(t, err) - - client := http.Client{} - - expire := time.Now().AddDate(0, 0, 1) - cookie := http.Cookie{ - Name: "_tokenKey", - Path: "/", - Value: tokenInfo.Token.String(), - Expires: expire, - } - secret, err := macaroon.NewSecret() require.NoError(t, err) @@ -170,17 +129,10 @@ func Test_GetAllAPIKeyNamesByProjectID(t *testing.T) { created1, err := sat.DB.Console().APIKeys().Create(ctx, key1.Head(), apikey1) require.NoError(t, err) - request, err := http.NewRequestWithContext(ctx, http.MethodGet, "http://"+planet.Satellites[0].API.Console.Listener.Addr().String()+"/api/v0/api-keys/api-key-names?projectID="+project.ID.String(), nil) - require.NoError(t, err) - - request.AddCookie(&cookie) - - result, err := client.Do(request) - require.NoError(t, err) - require.Equal(t, http.StatusOK, result.StatusCode) - - body, err := io.ReadAll(result.Body) + endpoint := "api-keys/api-key-names?projectID=" + project.ID.String() + body, status, err := doRequestWithAuth(ctx, t, sat, user, http.MethodGet, endpoint, nil) require.NoError(t, err) + require.Equal(t, http.StatusOK, status) var output []string @@ -190,10 +142,5 @@ func Test_GetAllAPIKeyNamesByProjectID(t *testing.T) { require.Equal(t, 2, len(output)) require.Equal(t, created.Name, output[0]) require.Equal(t, created1.Name, output[1]) - - defer func() { - err = result.Body.Close() - require.NoError(t, err) - }() }) } diff --git a/satellite/console/consoleweb/consoleapi/auth_test.go b/satellite/console/consoleweb/consoleapi/auth_test.go index 30ec2852c..0e4e8dc5f 100644 --- a/satellite/console/consoleweb/consoleapi/auth_test.go +++ b/satellite/console/consoleweb/consoleapi/auth_test.go @@ -22,6 +22,7 @@ import ( "time" "github.com/stretchr/testify/require" + "github.com/zeebo/errs/v2" "go.uber.org/zap" "storj.io/common/testcontext" @@ -33,6 +34,50 @@ import ( "storj.io/storj/satellite/console/consoleweb/consoleapi" ) +func doRequestWithAuth( + ctx context.Context, + t *testing.T, + sat *testplanet.Satellite, + user *console.User, + method string, + endpoint string, + body io.Reader, +) (responseBody []byte, statusCode int, err error) { + fullURL := "http://" + sat.API.Console.Listener.Addr().String() + "/api/v0/" + endpoint + + tokenInfo, err := sat.API.Console.Service.GenerateSessionToken(ctx, user.ID, user.Email, "", "") + if err != nil { + return nil, 0, err + } + + req, err := http.NewRequestWithContext(ctx, method, fullURL, body) + if err != nil { + return nil, 0, err + } + + req.AddCookie(&http.Cookie{ + Name: "_tokenKey", + Path: "/", + Value: tokenInfo.Token.String(), + Expires: time.Now().AddDate(0, 0, 1), + }) + + result, err := http.DefaultClient.Do(req) + if err != nil { + return nil, 0, err + } + defer func() { + err = errs.Combine(err, result.Body.Close()) + }() + + responseBody, err = io.ReadAll(result.Body) + if err != nil { + return nil, 0, err + } + + return responseBody, result.StatusCode, nil +} + func TestAuth_Register(t *testing.T) { testplanet.Run(t, testplanet.Config{ SatelliteCount: 1, StorageNodeCount: 0, UplinkCount: 0, @@ -287,10 +332,7 @@ func TestMFAEndpoints(t *testing.T) { RecoveryCode string `json:"recoveryCode"` } - doRequest := func(urlSuffix string, passcode string, recoveryCode string) *http.Response { - urlLink := sat.ConsoleURL() + "/api/v0/auth/mfa" + urlSuffix - var buf io.Reader - + doRequest := func(endpointSuffix string, passcode string, recoveryCode string) (responseBody []byte, status int) { body := &data{ Passcode: passcode, RecoveryCode: recoveryCode, @@ -298,74 +340,54 @@ func TestMFAEndpoints(t *testing.T) { bodyBytes, err := json.Marshal(body) require.NoError(t, err) - buf = bytes.NewBuffer(bodyBytes) + buf := bytes.NewBuffer(bodyBytes) - req, err := http.NewRequestWithContext(ctx, http.MethodPost, urlLink, buf) + responseBody, status, err = doRequestWithAuth(ctx, t, sat, user, http.MethodPost, "auth/mfa"+endpointSuffix, buf) require.NoError(t, err) - req.AddCookie(&http.Cookie{ - Name: "_tokenKey", - Path: "/", - Value: tokenInfo.Token.String(), - Expires: time.Now().AddDate(0, 0, 1), - }) - - req.Header.Set("Content-Type", "application/json") - - result, err := http.DefaultClient.Do(req) - require.NoError(t, err) - - return result + return responseBody, status } // Expect failure because MFA is not enabled. - result := doRequest("/generate-recovery-codes", "", "") - require.Equal(t, http.StatusUnauthorized, result.StatusCode) - require.NoError(t, result.Body.Close()) + _, status := doRequest("/generate-recovery-codes", "", "") + require.Equal(t, http.StatusUnauthorized, status) // Expect failure due to not having generated a secret key. - result = doRequest("/enable", "123456", "") - require.Equal(t, http.StatusBadRequest, result.StatusCode) - require.NoError(t, result.Body.Close()) + _, status = doRequest("/enable", "123456", "") + require.Equal(t, http.StatusBadRequest, status) // Expect success when generating a secret key. - result = doRequest("/generate-secret-key", "", "") - require.Equal(t, http.StatusOK, result.StatusCode) + body, status := doRequest("/generate-secret-key", "", "") + require.Equal(t, http.StatusOK, status) var key string - err = json.NewDecoder(result.Body).Decode(&key) + err = json.Unmarshal(body, &key) require.NoError(t, err) - require.NoError(t, result.Body.Close()) - // Expect failure due to prodiving empty passcode. - result = doRequest("/enable", "", "") - require.Equal(t, http.StatusBadRequest, result.StatusCode) - require.NoError(t, result.Body.Close()) + _, status = doRequest("/enable", "", "") + require.Equal(t, http.StatusBadRequest, status) // Expect failure due to providing invalid passcode. badCode, err := console.NewMFAPasscode(key, time.Now().Add(time.Hour)) require.NoError(t, err) - result = doRequest("/enable", badCode, "") - require.Equal(t, http.StatusBadRequest, result.StatusCode) - require.NoError(t, result.Body.Close()) + _, status = doRequest("/enable", badCode, "") + require.Equal(t, http.StatusBadRequest, status) // Expect success when providing valid passcode. goodCode, err := console.NewMFAPasscode(key, time.Now()) require.NoError(t, err) - result = doRequest("/enable", goodCode, "") - require.Equal(t, http.StatusOK, result.StatusCode) - require.NoError(t, result.Body.Close()) + _, status = doRequest("/enable", goodCode, "") + require.Equal(t, http.StatusOK, status) // Expect 10 recovery codes to be generated. - result = doRequest("/generate-recovery-codes", "", "") - require.Equal(t, http.StatusOK, result.StatusCode) + body, status = doRequest("/generate-recovery-codes", "", "") + require.Equal(t, http.StatusOK, status) var codes []string - err = json.NewDecoder(result.Body).Decode(&codes) + err = json.Unmarshal(body, &codes) require.NoError(t, err) require.Len(t, codes, console.MFARecoveryCodeCount) - require.NoError(t, result.Body.Close()) // Expect no token due to missing passcode. newToken, err := sat.API.Console.Service.Token(ctx, console.AuthUser{Email: user.Email, Password: user.FullName}) @@ -409,49 +431,40 @@ func TestMFAEndpoints(t *testing.T) { } // Expect failure due to disabling MFA with no passcode. - result = doRequest("/disable", "", "") - require.Equal(t, http.StatusBadRequest, result.StatusCode) - require.NoError(t, result.Body.Close()) + _, status = doRequest("/disable", "", "") + require.Equal(t, http.StatusBadRequest, status) // Expect failure due to disabling MFA with invalid passcode. - result = doRequest("/disable", badCode, "") - require.Equal(t, http.StatusBadRequest, result.StatusCode) - require.NoError(t, result.Body.Close()) + _, status = doRequest("/disable", badCode, "") + require.Equal(t, http.StatusBadRequest, status) // Expect failure when disabling due to providing both passcode and recovery code. - result = doRequest("/generate-recovery-codes", "", "") - err = json.NewDecoder(result.Body).Decode(&codes) + body, _ = doRequest("/generate-recovery-codes", "", "") + err = json.Unmarshal(body, &codes) require.NoError(t, err) - require.NoError(t, result.Body.Close()) - result = doRequest("/disable", goodCode, codes[0]) - require.Equal(t, http.StatusConflict, result.StatusCode) - require.NoError(t, result.Body.Close()) + _, status = doRequest("/disable", goodCode, codes[0]) + require.Equal(t, http.StatusConflict, status) // Expect success when disabling MFA with valid passcode. - result = doRequest("/disable", goodCode, "") - require.Equal(t, http.StatusOK, result.StatusCode) - require.NoError(t, result.Body.Close()) + _, status = doRequest("/disable", goodCode, "") + require.Equal(t, http.StatusOK, status) // Expect success when disabling MFA with valid recovery code. - result = doRequest("/generate-secret-key", "", "") - err = json.NewDecoder(result.Body).Decode(&key) + body, _ = doRequest("/generate-secret-key", "", "") + err = json.Unmarshal(body, &key) require.NoError(t, err) - require.NoError(t, result.Body.Close()) goodCode, err = console.NewMFAPasscode(key, time.Now()) require.NoError(t, err) - result = doRequest("/enable", goodCode, "") - require.NoError(t, result.Body.Close()) + doRequest("/enable", goodCode, "") - result = doRequest("/generate-recovery-codes", "", "") - err = json.NewDecoder(result.Body).Decode(&codes) + body, _ = doRequest("/generate-recovery-codes", "", "") + err = json.Unmarshal(body, &codes) require.NoError(t, err) - require.NoError(t, result.Body.Close()) - result = doRequest("/disable", "", codes[0]) - require.Equal(t, http.StatusOK, result.StatusCode) - require.NoError(t, result.Body.Close()) + _, status = doRequest("/disable", "", codes[0]) + require.Equal(t, http.StatusOK, status) }) } diff --git a/satellite/console/consoleweb/consoleapi/buckets_test.go b/satellite/console/consoleweb/consoleapi/buckets_test.go index e6c9d7000..592a559ce 100644 --- a/satellite/console/consoleweb/consoleapi/buckets_test.go +++ b/satellite/console/consoleweb/consoleapi/buckets_test.go @@ -5,10 +5,8 @@ package consoleapi_test import ( "encoding/json" - "io" "net/http" "testing" - "time" "github.com/stretchr/testify/require" "go.uber.org/zap" @@ -63,29 +61,10 @@ func Test_AllBucketNames(t *testing.T) { _, err = sat.API.Buckets.Service.CreateBucket(ctx, bucket2) require.NoError(t, err) - // we are using full name as a password - tokenInfo, err := sat.API.Console.Service.Token(ctx, console.AuthUser{Email: user.Email, Password: user.FullName}) - require.NoError(t, err) - - client := http.Client{} - - testRequest := func(req *http.Request) { - expire := time.Now().AddDate(0, 0, 1) - cookie := http.Cookie{ - Name: "_tokenKey", - Path: "/", - Value: tokenInfo.Token.String(), - Expires: expire, - } - - req.AddCookie(&cookie) - - result, err := client.Do(req) - require.NoError(t, err) - require.Equal(t, http.StatusOK, result.StatusCode) - - body, err := io.ReadAll(result.Body) + testRequest := func(endpointSuffix string) { + body, status, err := doRequestWithAuth(ctx, t, sat, user, http.MethodGet, "buckets/bucket-names"+endpointSuffix, nil) require.NoError(t, err) + require.Equal(t, http.StatusOK, status) var output []string @@ -94,21 +73,12 @@ func Test_AllBucketNames(t *testing.T) { require.Equal(t, bucket1.Name, output[0]) require.Equal(t, bucket2.Name, output[1]) - - defer func() { - err = result.Body.Close() - require.NoError(t, err) - }() } // test using Project.ID - req, err := http.NewRequestWithContext(ctx, "GET", "http://"+planet.Satellites[0].API.Console.Listener.Addr().String()+"/api/v0/buckets/bucket-names?projectID="+project.ID.String(), nil) - require.NoError(t, err) - testRequest(req) + testRequest("?projectID=" + project.ID.String()) // test using Project.PublicID - req, err = http.NewRequestWithContext(ctx, "GET", "http://"+planet.Satellites[0].API.Console.Listener.Addr().String()+"/api/v0/buckets/bucket-names?publicID="+project.PublicID.String(), nil) - require.NoError(t, err) - testRequest(req) + testRequest("?publicID=" + project.PublicID.String()) }) } diff --git a/satellite/console/consoleweb/consoleapi/payments_test.go b/satellite/console/consoleweb/consoleapi/payments_test.go index 8f1818696..e6e18df73 100644 --- a/satellite/console/consoleweb/consoleapi/payments_test.go +++ b/satellite/console/consoleweb/consoleapi/payments_test.go @@ -6,11 +6,9 @@ package consoleapi_test import ( "encoding/json" "fmt" - "io" "net/http" "strings" "testing" - "time" "github.com/stretchr/testify/require" "go.uber.org/zap" @@ -78,30 +76,9 @@ func Test_PurchasePackage(t *testing.T) { }, 1) require.NoError(t, err) - userCtx, err := sat.UserContext(ctx, user.ID) + _, status, err := doRequestWithAuth(ctx, t, sat, user, http.MethodPost, "payments/purchase-package", strings.NewReader(tt.cardToken)) require.NoError(t, err) - - tokenInfo, err := sat.API.Console.Service.Token(ctx, console.AuthUser{Email: user.Email, Password: user.FullName}) - require.NoError(t, err) - - req, err := http.NewRequestWithContext(userCtx, "POST", "http://"+sat.API.Console.Listener.Addr().String()+"/api/v0/payments/purchase-package", strings.NewReader(tt.cardToken)) - require.NoError(t, err) - - expire := time.Now().AddDate(0, 0, 1) - cookie := http.Cookie{ - Name: "_tokenKey", - Path: "/", - Value: tokenInfo.Token.String(), - Expires: expire, - } - - req.AddCookie(&cookie) - - client := http.Client{} - result, err := client.Do(req) - require.NoError(t, err) - require.Equal(t, tt.expectedStatus, result.StatusCode) - require.NoError(t, result.Body.Close()) + require.Equal(t, tt.expectedStatus, status) }) } }) @@ -140,34 +117,13 @@ func Test_PackageAvailable(t *testing.T) { }, 1) require.NoError(t, err) - userCtx, err := sat.UserContext(ctx, user.ID) + body, status, err := doRequestWithAuth(ctx, t, sat, user, http.MethodGet, "payments/package-available", nil) require.NoError(t, err) - tokenInfo, err := sat.API.Console.Service.Token(ctx, console.AuthUser{Email: user.Email, Password: user.FullName}) - require.NoError(t, err) - - req, err := http.NewRequestWithContext(userCtx, http.MethodGet, "http://"+planet.Satellites[0].API.Console.Listener.Addr().String()+"/api/v0/payments/package-available", nil) - require.NoError(t, err) - - cookie := http.Cookie{ - Name: "_tokenKey", - Path: "/", - Value: tokenInfo.Token.String(), - Expires: time.Now().AddDate(0, 0, 1), - } - req.AddCookie(&cookie) - - client := http.Client{} - result, err := client.Do(req) - require.NoError(t, err) - require.Equal(t, http.StatusOK, result.StatusCode) - - responseBody, err := io.ReadAll(result.Body) - require.NoError(t, err) - require.NoError(t, result.Body.Close()) + require.Equal(t, http.StatusOK, status) var hasPackage bool - err = json.Unmarshal(responseBody, &hasPackage) + err = json.Unmarshal(body, &hasPackage) require.NoError(t, err) require.Equal(t, tt.shouldHavePkg, hasPackage) }) diff --git a/satellite/console/consoleweb/consoleapi/projects_test.go b/satellite/console/consoleweb/consoleapi/projects_test.go index b2d5056b7..d994a39c7 100644 --- a/satellite/console/consoleweb/consoleapi/projects_test.go +++ b/satellite/console/consoleweb/consoleapi/projects_test.go @@ -7,7 +7,6 @@ import ( "context" "encoding/json" "fmt" - "io" "net/http" "net/url" "strings" @@ -93,17 +92,6 @@ func TestGetProjectMembersAndInvitationsOrdering(t *testing.T) { members, invitees := createTestMembers(ctx, t, sat.DB.Console(), p, &user.ID) members[user.ID] = *user - tokenInfo, err := sat.API.Console.Service.Token(ctx, console.AuthUser{Email: user.Email, Password: user.FullName}) - require.NoError(t, err) - - expire := time.Now().AddDate(0, 0, 1) - cookie := http.Cookie{ - Name: "_tokenKey", - Path: "/", - Value: tokenInfo.Token.String(), - Expires: expire, - } - tests := []struct { order, orderDir int }{ @@ -134,24 +122,10 @@ func TestGetProjectMembersAndInvitationsOrdering(t *testing.T) { } for _, tt := range tests { - addr := planet.Satellites[0].API.Console.Listener.Addr().String() - - url := fmt.Sprintf("http://%s/api/v0/projects/%s/members", addr, p.String()) - url += fmt.Sprintf("?limit=100&page=1&order=%d&order-direction=%d", tt.order, tt.orderDir) - - req, err := http.NewRequestWithContext(ctx, "GET", url, nil) + endpoint := fmt.Sprintf("projects/%s/members?limit=100&page=1&order=%d&order-direction=%d", p.String(), tt.order, tt.orderDir) + body, status, err := doRequestWithAuth(ctx, t, sat, user, http.MethodGet, endpoint, nil) require.NoError(t, err) - - req.AddCookie(&cookie) - - client := http.Client{} - res, err := client.Do(req) - require.NoError(t, err) - require.NotNil(t, res) - - body, err := io.ReadAll(res.Body) - require.NoError(t, err) - require.NoError(t, res.Body.Close()) + require.Equal(t, http.StatusOK, status) var membersAndInvitations consoleapi.ProjectMembersPage require.NoError(t, json.Unmarshal(body, &membersAndInvitations)) @@ -231,17 +205,6 @@ func TestGetProjectMembersAndInvitationsSearch(t *testing.T) { members, invitees := createTestMembers(ctx, t, sat.DB.Console(), p, &user.ID) members[user.ID] = *user - tokenInfo, err := sat.API.Console.Service.Token(ctx, console.AuthUser{Email: user.Email, Password: user.FullName}) - require.NoError(t, err) - - expire := time.Now().AddDate(0, 0, 1) - cookie := http.Cookie{ - Name: "_tokenKey", - Path: "/", - Value: tokenInfo.Token.String(), - Expires: expire, - } - tests := []struct { search string expectedMembers, expectedInvitees int @@ -279,26 +242,14 @@ func TestGetProjectMembersAndInvitationsSearch(t *testing.T) { } for _, tt := range tests { - addr := planet.Satellites[0].API.Console.Listener.Addr().String() - - endpoint := fmt.Sprintf("http://%s/api/v0/projects/%s/members?limit=100&page=1&order=1&order-direction=1&", addr, p.String()) + endpoint := fmt.Sprintf("projects/%s/members?limit=100&page=1&order=1&order-direction=1&", p.String()) params := url.Values{} params.Add("search", tt.search) endpoint += params.Encode() - req, err := http.NewRequestWithContext(ctx, "GET", endpoint, nil) + body, status, err := doRequestWithAuth(ctx, t, sat, user, http.MethodGet, endpoint, nil) require.NoError(t, err) - - req.AddCookie(&cookie) - - client := http.Client{} - res, err := client.Do(req) - require.NoError(t, err) - require.NotNil(t, res) - - body, err := io.ReadAll(res.Body) - require.NoError(t, err) - require.NoError(t, res.Body.Close()) + require.Equal(t, http.StatusOK, status) var membersAndInvitations consoleapi.ProjectMembersPage require.NoError(t, json.Unmarshal(body, &membersAndInvitations)) @@ -334,42 +285,19 @@ func TestGetProjectMembersAndInvitationsLimitAndPage(t *testing.T) { members, _ := createTestMembers(ctx, t, sat.DB.Console(), p, &user.ID) members[user.ID] = *user - tokenInfo, err := sat.API.Console.Service.Token(ctx, console.AuthUser{Email: user.Email, Password: user.FullName}) - require.NoError(t, err) - - expire := time.Now().AddDate(0, 0, 1) - cookie := http.Cookie{ - Name: "_tokenKey", - Path: "/", - Value: tokenInfo.Token.String(), - Expires: expire, - } - - addr := planet.Satellites[0].API.Console.Listener.Addr().String() - limit := 1 page := 1 var previousResult console.ProjectMembersPage for i := 0; i < 2; i++ { - endpoint := fmt.Sprintf("http://%s/api/v0/projects/%s/members?order=1&order-direction=1&", addr, p.String()) + endpoint := fmt.Sprintf("projects/%s/members?order=1&order-direction=1&", p.String()) params := url.Values{} params.Add("limit", fmt.Sprint(limit)) params.Add("page", fmt.Sprint(page)) endpoint += params.Encode() - req, err := http.NewRequestWithContext(ctx, "GET", endpoint, nil) + body, status, err := doRequestWithAuth(ctx, t, sat, user, http.MethodGet, endpoint, nil) require.NoError(t, err) - - req.AddCookie(&cookie) - - client := http.Client{} - res, err := client.Do(req) - require.NoError(t, err) - require.NotNil(t, res) - - body, err := io.ReadAll(res.Body) - require.NoError(t, err) - require.NoError(t, res.Body.Close()) + require.Equal(t, http.StatusOK, status) var membersAndInvitations console.ProjectMembersPage require.NoError(t, json.Unmarshal(body, &membersAndInvitations)) @@ -401,19 +329,6 @@ func TestDeleteProjectMembers(t *testing.T) { members, invitees := createTestMembers(ctx, t, sat.DB.Console(), p, &user.ID) - tokenInfo, err := sat.API.Console.Service.Token(ctx, console.AuthUser{Email: user.Email, Password: user.FullName}) - require.NoError(t, err) - - expire := time.Now().AddDate(0, 0, 1) - cookie := http.Cookie{ - Name: "_tokenKey", - Path: "/", - Value: tokenInfo.Token.String(), - Expires: expire, - } - - addr := planet.Satellites[0].API.Console.Listener.Addr().String() - var emails string var firstAppendDone bool for _, m := range members { @@ -431,52 +346,30 @@ func TestDeleteProjectMembers(t *testing.T) { emails += e } - endpoint := fmt.Sprintf("http://%s/api/v0/projects/%s/members?", addr, p.String()) + endpoint := fmt.Sprintf("projects/%s/members?", p.String()) params := url.Values{} params.Add("emails", emails) endpoint += params.Encode() - req, err := http.NewRequestWithContext(ctx, "DELETE", endpoint, nil) + body, status, err := doRequestWithAuth(ctx, t, sat, user, http.MethodDelete, endpoint, nil) require.NoError(t, err) - - req.AddCookie(&cookie) - - client := http.Client{} - res, err := client.Do(req) - require.NoError(t, err) - require.NotNil(t, res) - - body, err := io.ReadAll(res.Body) - require.NoError(t, err) - require.NoError(t, res.Body.Close()) + require.Equal(t, http.StatusOK, status) require.NotContains(t, string(body), "error") - require.Equal(t, http.StatusOK, res.StatusCode) - page, err := sat.DB.Console().ProjectMembers().GetPagedWithInvitationsByProjectID(ctx, p, console.ProjectMembersCursor{Limit: 1, Page: 1}) require.NoError(t, err) require.Len(t, page.ProjectMembers, 1) require.Equal(t, user.ID, page.ProjectMembers[0].MemberID) // test error - endpoint = fmt.Sprintf("http://%s/api/v0/projects/%s/members?", addr, p.String()) + endpoint = fmt.Sprintf("projects/%s/members?", p.String()) params = url.Values{} params.Add("emails", "nonmember@storj.test") endpoint += params.Encode() - req, err = http.NewRequestWithContext(ctx, "DELETE", endpoint, nil) + body, status, err = doRequestWithAuth(ctx, t, sat, user, http.MethodDelete, endpoint, nil) require.NoError(t, err) - - req.AddCookie(&cookie) - - client = http.Client{} - res, err = client.Do(req) - require.NoError(t, err) - require.NotNil(t, res) - - body, err = io.ReadAll(res.Body) - require.NoError(t, err) - require.NoError(t, res.Body.Close()) + require.Equal(t, http.StatusInternalServerError, status) require.Contains(t, string(body), "error") }) } diff --git a/satellite/console/consoleweb/consoleapi/usagelimits_test.go b/satellite/console/consoleweb/consoleapi/usagelimits_test.go index 8c0b1bc91..016f32667 100644 --- a/satellite/console/consoleweb/consoleapi/usagelimits_test.go +++ b/satellite/console/consoleweb/consoleapi/usagelimits_test.go @@ -6,7 +6,6 @@ package consoleapi_test import ( "encoding/json" "fmt" - "io" "net/http" "strconv" "testing" @@ -71,36 +70,9 @@ func Test_TotalUsageLimits(t *testing.T) { err = sat.DB.ProjectAccounting().UpdateProjectBandwidthLimit(ctx, project2.ID, expectedLimit) require.NoError(t, err) - // we are using full name as a password - tokenInfo, err := sat.API.Console.Service.Token(ctx, console.AuthUser{Email: user.Email, Password: user.FullName}) - require.NoError(t, err) - - client := http.Client{} - - req, err := http.NewRequestWithContext( - ctx, - "GET", - "http://"+planet.Satellites[0].API.Console.Listener.Addr().String()+"/api/v0/projects/usage-limits", - nil, - ) - require.NoError(t, err) - - expire := time.Now().AddDate(0, 0, 1) - cookie := http.Cookie{ - Name: "_tokenKey", - Path: "/", - Value: tokenInfo.Token.String(), - Expires: expire, - } - - req.AddCookie(&cookie) - - result, err := client.Do(req) - require.NoError(t, err) - require.Equal(t, http.StatusOK, result.StatusCode) - - body, err := io.ReadAll(result.Body) + body, status, err := doRequestWithAuth(ctx, t, sat, user, http.MethodGet, "projects/usage-limits", nil) require.NoError(t, err) + require.Equal(t, http.StatusOK, status) var output console.ProjectUsageLimits @@ -111,11 +83,6 @@ func Test_TotalUsageLimits(t *testing.T) { require.Equal(t, int64(0), output.StorageUsed) require.Equal(t, int64(expectedLimit*3), output.BandwidthLimit) require.Equal(t, int64(expectedLimit*3), output.StorageLimit) - - defer func() { - err = result.Body.Close() - require.NoError(t, err) - }() }) } @@ -185,36 +152,10 @@ func Test_DailyUsage(t *testing.T) { planet.Satellites[0].Orders.Chore.Loop.TriggerWait() satelliteSys.Accounting.Tally.Loop.TriggerWait() - // we are using full name as a password - tokenInfo, err := satelliteSys.API.Console.Service.Token(ctx, console.AuthUser{Email: user.Email, Password: user.FullName}) - require.NoError(t, err) - - client := http.DefaultClient - - req, err := http.NewRequestWithContext( - ctx, - "GET", - fmt.Sprintf("http://%s/api/v0/projects/%s/daily-usage?from=%s&to=%s", planet.Satellites[0].API.Console.Listener.Addr().String(), projectID.String(), since, before), - nil, - ) - require.NoError(t, err) - - expire := time.Now().AddDate(0, 0, 1) - cookie := http.Cookie{ - Name: "_tokenKey", - Path: "/", - Value: tokenInfo.Token.String(), - Expires: expire, - } - - req.AddCookie(&cookie) - - result, err := client.Do(req) - require.NoError(t, err) - require.Equal(t, http.StatusOK, result.StatusCode) - - body, err := io.ReadAll(result.Body) + endpoint := fmt.Sprintf("projects/%s/daily-usage?from=%s&to=%s", projectID.String(), since, before) + body, status, err := doRequestWithAuth(ctx, t, satelliteSys, user, http.MethodGet, endpoint, nil) require.NoError(t, err) + require.Equal(t, http.StatusOK, status) var output accounting.ProjectDailyUsage @@ -224,10 +165,5 @@ func Test_DailyUsage(t *testing.T) { require.GreaterOrEqual(t, output.StorageUsage[0].Value, 15*memory.KiB) require.GreaterOrEqual(t, output.AllocatedBandwidthUsage[0].Value, 5*memory.KiB) require.GreaterOrEqual(t, output.SettledBandwidthUsage[0].Value, 5*memory.KiB) - - defer func() { - err = result.Body.Close() - require.NoError(t, err) - }() }) }