From e47df0b301510a49b49fc43266f436b7d58a02b1 Mon Sep 17 00:00:00 2001 From: B-OnTheGo <42626718+beeonthego@users.noreply.github.com> Date: Tue, 11 Sep 2018 02:15:52 +1000 Subject: [PATCH] Enforce token on api routes [fixed critical security issue #4357] (#4840) --- integrations/api_admin_test.go | 20 +++++--- integrations/api_branch_test.go | 3 +- integrations/api_comment_test.go | 15 +++--- integrations/api_gpg_keys_test.go | 72 ++++++++++++++-------------- integrations/api_issue_label_test.go | 14 +++--- integrations/api_issue_test.go | 9 ++-- integrations/api_keys_test.go | 8 ++-- integrations/api_pull_test.go | 6 ++- integrations/api_releases_test.go | 10 ++-- integrations/api_repo_raw_test.go | 5 +- integrations/api_repo_test.go | 25 +++++----- integrations/api_team_test.go | 3 +- integrations/git_test.go | 6 ++- integrations/integration_test.go | 16 +++++++ integrations/repo_commits_test.go | 3 +- modules/auth/auth.go | 3 +- routers/api/v1/api.go | 2 +- 17 files changed, 131 insertions(+), 89 deletions(-) diff --git a/integrations/api_admin_test.go b/integrations/api_admin_test.go index ab878dd6a5..f801b08d39 100644 --- a/integrations/api_admin_test.go +++ b/integrations/api_admin_test.go @@ -21,7 +21,8 @@ func TestAPIAdminCreateAndDeleteSSHKey(t *testing.T) { session := loginUser(t, "user1") keyOwner := models.AssertExistsAndLoadBean(t, &models.User{Name: "user2"}).(*models.User) - urlStr := fmt.Sprintf("/api/v1/admin/users/%s/keys", keyOwner.Name) + token := getTokenForLoggedInUser(t, session) + urlStr := fmt.Sprintf("/api/v1/admin/users/%s/keys?token=%s", keyOwner.Name, token) req := NewRequestWithValues(t, "POST", urlStr, map[string]string{ "key": "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAAAgQDAu7tvIvX6ZHrRXuZNfkR3XLHSsuCK9Zn3X58lxBcQzuo5xZgB6vRwwm/QtJuF+zZPtY5hsQILBLmF+BZ5WpKZp1jBeSjH2G7lxet9kbcH+kIVj0tPFEoyKI9wvWqIwC4prx/WVk2wLTJjzBAhyNxfEq7C9CeiX9pQEbEqJfkKCQ== nocomment\n", "title": "test-key", @@ -38,7 +39,7 @@ func TestAPIAdminCreateAndDeleteSSHKey(t *testing.T) { OwnerID: keyOwner.ID, }) - req = NewRequestf(t, "DELETE", "/api/v1/admin/users/%s/keys/%d", + req = NewRequestf(t, "DELETE", "/api/v1/admin/users/%s/keys/%d?token="+token, keyOwner.Name, newPublicKey.ID) session.MakeRequest(t, req, http.StatusNoContent) models.AssertNotExistsBean(t, &models.PublicKey{ID: newPublicKey.ID}) @@ -49,7 +50,8 @@ func TestAPIAdminDeleteMissingSSHKey(t *testing.T) { // user1 is an admin user session := loginUser(t, "user1") - req := NewRequestf(t, "DELETE", "/api/v1/admin/users/user1/keys/%d", models.NonexistentID) + token := getTokenForLoggedInUser(t, session) + req := NewRequestf(t, "DELETE", "/api/v1/admin/users/user1/keys/%d?token="+token, models.NonexistentID) session.MakeRequest(t, req, http.StatusNotFound) } @@ -59,7 +61,8 @@ func TestAPIAdminDeleteUnauthorizedKey(t *testing.T) { normalUsername := "user2" session := loginUser(t, adminUsername) - urlStr := fmt.Sprintf("/api/v1/admin/users/%s/keys", adminUsername) + token := getTokenForLoggedInUser(t, session) + urlStr := fmt.Sprintf("/api/v1/admin/users/%s/keys?token=%s", adminUsername, token) req := NewRequestWithValues(t, "POST", urlStr, map[string]string{ "key": "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAAAgQDAu7tvIvX6ZHrRXuZNfkR3XLHSsuCK9Zn3X58lxBcQzuo5xZgB6vRwwm/QtJuF+zZPtY5hsQILBLmF+BZ5WpKZp1jBeSjH2G7lxet9kbcH+kIVj0tPFEoyKI9wvWqIwC4prx/WVk2wLTJjzBAhyNxfEq7C9CeiX9pQEbEqJfkKCQ== nocomment\n", "title": "test-key", @@ -69,7 +72,8 @@ func TestAPIAdminDeleteUnauthorizedKey(t *testing.T) { DecodeJSON(t, resp, &newPublicKey) session = loginUser(t, normalUsername) - req = NewRequestf(t, "DELETE", "/api/v1/admin/users/%s/keys/%d", + token = getTokenForLoggedInUser(t, session) + req = NewRequestf(t, "DELETE", "/api/v1/admin/users/%s/keys/%d?token="+token, adminUsername, newPublicKey.ID) session.MakeRequest(t, req, http.StatusForbidden) } @@ -79,8 +83,9 @@ func TestAPISudoUser(t *testing.T) { adminUsername := "user1" normalUsername := "user2" session := loginUser(t, adminUsername) + token := getTokenForLoggedInUser(t, session) - urlStr := fmt.Sprintf("/api/v1/user?sudo=%s", normalUsername) + urlStr := fmt.Sprintf("/api/v1/user?sudo=%s&token=%s", normalUsername, token) req := NewRequest(t, "GET", urlStr) resp := session.MakeRequest(t, req, http.StatusOK) var user api.User @@ -95,8 +100,9 @@ func TestAPISudoUserForbidden(t *testing.T) { normalUsername := "user2" session := loginUser(t, normalUsername) + token := getTokenForLoggedInUser(t, session) - urlStr := fmt.Sprintf("/api/v1/user?sudo=%s", adminUsername) + urlStr := fmt.Sprintf("/api/v1/user?sudo=%s&token=%s", adminUsername, token) req := NewRequest(t, "GET", urlStr) session.MakeRequest(t, req, http.StatusForbidden) } diff --git a/integrations/api_branch_test.go b/integrations/api_branch_test.go index 5a28c1f494..aff3f223c0 100644 --- a/integrations/api_branch_test.go +++ b/integrations/api_branch_test.go @@ -17,7 +17,8 @@ func testAPIGetBranch(t *testing.T, branchName string, exists bool) { prepareTestEnv(t) session := loginUser(t, "user2") - req := NewRequestf(t, "GET", "/api/v1/repos/user2/repo1/branches/%s", branchName) + token := getTokenForLoggedInUser(t, session) + req := NewRequestf(t, "GET", "/api/v1/repos/user2/repo1/branches/%s?token=%s", branchName, token) resp := session.MakeRequest(t, req, NoExpectedStatus) if !exists { assert.EqualValues(t, http.StatusNotFound, resp.Code) diff --git a/integrations/api_comment_test.go b/integrations/api_comment_test.go index 423d0f7989..60bb2cfb7b 100644 --- a/integrations/api_comment_test.go +++ b/integrations/api_comment_test.go @@ -69,8 +69,9 @@ func TestAPICreateComment(t *testing.T) { repoOwner := models.AssertExistsAndLoadBean(t, &models.User{ID: repo.OwnerID}).(*models.User) session := loginUser(t, repoOwner.Name) - urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/issues/%d/comments", - repoOwner.Name, repo.Name, issue.Index) + token := getTokenForLoggedInUser(t, session) + urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/issues/%d/comments?token=%s", + repoOwner.Name, repo.Name, issue.Index, token) req := NewRequestWithValues(t, "POST", urlStr, map[string]string{ "body": commentBody, }) @@ -93,8 +94,9 @@ func TestAPIEditComment(t *testing.T) { repoOwner := models.AssertExistsAndLoadBean(t, &models.User{ID: repo.OwnerID}).(*models.User) session := loginUser(t, repoOwner.Name) - urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/issues/comments/%d", - repoOwner.Name, repo.Name, comment.ID) + token := getTokenForLoggedInUser(t, session) + urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/issues/comments/%d?token=%s", + repoOwner.Name, repo.Name, comment.ID, token) req := NewRequestWithValues(t, "PATCH", urlStr, map[string]string{ "body": newCommentBody, }) @@ -117,8 +119,9 @@ func TestAPIDeleteComment(t *testing.T) { repoOwner := models.AssertExistsAndLoadBean(t, &models.User{ID: repo.OwnerID}).(*models.User) session := loginUser(t, repoOwner.Name) - req := NewRequestf(t, "DELETE", "/api/v1/repos/%s/%s/issues/comments/%d", - repoOwner.Name, repo.Name, comment.ID) + token := getTokenForLoggedInUser(t, session) + req := NewRequestf(t, "DELETE", "/api/v1/repos/%s/%s/issues/comments/%d?token=%s", + repoOwner.Name, repo.Name, comment.ID, token) session.MakeRequest(t, req, http.StatusNoContent) models.AssertNotExistsBean(t, &models.Comment{ID: comment.ID}) diff --git a/integrations/api_gpg_keys_test.go b/integrations/api_gpg_keys_test.go index 4d3745d942..0973fd33a3 100644 --- a/integrations/api_gpg_keys_test.go +++ b/integrations/api_gpg_keys_test.go @@ -20,16 +20,18 @@ type makeRequestFunc func(testing.TB, *http.Request, int) *httptest.ResponseReco func TestGPGKeys(t *testing.T) { prepareTestEnv(t) session := loginUser(t, "user2") + token := getTokenForLoggedInUser(t, session) tt := []struct { name string makeRequest makeRequestFunc + token string results []int }{ - {name: "NoLogin", makeRequest: MakeRequest, + {name: "NoLogin", makeRequest: MakeRequest, token: "", results: []int{http.StatusUnauthorized, http.StatusUnauthorized, http.StatusUnauthorized, http.StatusUnauthorized, http.StatusUnauthorized, http.StatusUnauthorized, http.StatusUnauthorized, http.StatusUnauthorized}, }, - {name: "LoggedAsUser2", makeRequest: session.MakeRequest, + {name: "LoggedAsUser2", makeRequest: session.MakeRequest, token: token, results: []int{http.StatusOK, http.StatusOK, http.StatusNotFound, http.StatusNoContent, http.StatusInternalServerError, http.StatusInternalServerError, http.StatusCreated, http.StatusCreated}}, } @@ -38,29 +40,29 @@ func TestGPGKeys(t *testing.T) { //Basic test on result code t.Run(tc.name, func(t *testing.T) { t.Run("ViewOwnGPGKeys", func(t *testing.T) { - testViewOwnGPGKeys(t, tc.makeRequest, tc.results[0]) + testViewOwnGPGKeys(t, tc.makeRequest, tc.token, tc.results[0]) }) t.Run("ViewGPGKeys", func(t *testing.T) { - testViewGPGKeys(t, tc.makeRequest, tc.results[1]) + testViewGPGKeys(t, tc.makeRequest, tc.token, tc.results[1]) }) t.Run("GetGPGKey", func(t *testing.T) { - testGetGPGKey(t, tc.makeRequest, tc.results[2]) + testGetGPGKey(t, tc.makeRequest, tc.token, tc.results[2]) }) t.Run("DeleteGPGKey", func(t *testing.T) { - testDeleteGPGKey(t, tc.makeRequest, tc.results[3]) + testDeleteGPGKey(t, tc.makeRequest, tc.token, tc.results[3]) }) t.Run("CreateInvalidGPGKey", func(t *testing.T) { - testCreateInvalidGPGKey(t, tc.makeRequest, tc.results[4]) + testCreateInvalidGPGKey(t, tc.makeRequest, tc.token, tc.results[4]) }) t.Run("CreateNoneRegistredEmailGPGKey", func(t *testing.T) { - testCreateNoneRegistredEmailGPGKey(t, tc.makeRequest, tc.results[5]) + testCreateNoneRegistredEmailGPGKey(t, tc.makeRequest, tc.token, tc.results[5]) }) t.Run("CreateValidGPGKey", func(t *testing.T) { - testCreateValidGPGKey(t, tc.makeRequest, tc.results[6]) + testCreateValidGPGKey(t, tc.makeRequest, tc.token, tc.results[6]) }) t.Run("CreateValidSecondaryEmailGPGKey", func(t *testing.T) { - testCreateValidSecondaryEmailGPGKey(t, tc.makeRequest, tc.results[7]) + testCreateValidSecondaryEmailGPGKey(t, tc.makeRequest, tc.token, tc.results[7]) }) }) } @@ -70,7 +72,7 @@ func TestGPGKeys(t *testing.T) { var keys []*api.GPGKey - req := NewRequest(t, "GET", "/api/v1/user/gpg_keys") //GET all keys + req := NewRequest(t, "GET", "/api/v1/user/gpg_keys?token="+token) //GET all keys resp := session.MakeRequest(t, req, http.StatusOK) DecodeJSON(t, resp, &keys) @@ -91,7 +93,7 @@ func TestGPGKeys(t *testing.T) { assert.EqualValues(t, false, primaryKey2.Emails[0].Verified) var key api.GPGKey - req = NewRequest(t, "GET", "/api/v1/user/gpg_keys/"+strconv.FormatInt(primaryKey1.ID, 10)) //Primary key 1 + req = NewRequest(t, "GET", "/api/v1/user/gpg_keys/"+strconv.FormatInt(primaryKey1.ID, 10)+"?token="+token) //Primary key 1 resp = session.MakeRequest(t, req, http.StatusOK) DecodeJSON(t, resp, &key) assert.EqualValues(t, "38EA3BCED732982C", key.KeyID) @@ -99,13 +101,13 @@ func TestGPGKeys(t *testing.T) { assert.EqualValues(t, "user2@example.com", key.Emails[0].Email) assert.EqualValues(t, true, key.Emails[0].Verified) - req = NewRequest(t, "GET", "/api/v1/user/gpg_keys/"+strconv.FormatInt(subKey.ID, 10)) //Subkey of 38EA3BCED732982C + req = NewRequest(t, "GET", "/api/v1/user/gpg_keys/"+strconv.FormatInt(subKey.ID, 10)+"?token="+token) //Subkey of 38EA3BCED732982C resp = session.MakeRequest(t, req, http.StatusOK) DecodeJSON(t, resp, &key) assert.EqualValues(t, "70D7C694D17D03AD", key.KeyID) assert.EqualValues(t, 0, len(key.Emails)) - req = NewRequest(t, "GET", "/api/v1/user/gpg_keys/"+strconv.FormatInt(primaryKey2.ID, 10)) //Primary key 2 + req = NewRequest(t, "GET", "/api/v1/user/gpg_keys/"+strconv.FormatInt(primaryKey2.ID, 10)+"?token="+token) //Primary key 2 resp = session.MakeRequest(t, req, http.StatusOK) DecodeJSON(t, resp, &key) assert.EqualValues(t, "FABF39739FE1E927", key.KeyID) @@ -119,7 +121,7 @@ func TestGPGKeys(t *testing.T) { t.Run("CheckCommits", func(t *testing.T) { t.Run("NotSigned", func(t *testing.T) { var branch api.Branch - req := NewRequest(t, "GET", "/api/v1/repos/user2/repo16/branches/not-signed") + req := NewRequest(t, "GET", "/api/v1/repos/user2/repo16/branches/not-signed?token="+token) resp := session.MakeRequest(t, req, http.StatusOK) DecodeJSON(t, resp, &branch) assert.EqualValues(t, false, branch.Commit.Verification.Verified) @@ -127,7 +129,7 @@ func TestGPGKeys(t *testing.T) { t.Run("SignedWithNotValidatedEmail", func(t *testing.T) { var branch api.Branch - req := NewRequest(t, "GET", "/api/v1/repos/user2/repo16/branches/good-sign-not-yet-validated") + req := NewRequest(t, "GET", "/api/v1/repos/user2/repo16/branches/good-sign-not-yet-validated?token="+token) resp := session.MakeRequest(t, req, http.StatusOK) DecodeJSON(t, resp, &branch) assert.EqualValues(t, false, branch.Commit.Verification.Verified) @@ -135,7 +137,7 @@ func TestGPGKeys(t *testing.T) { t.Run("SignedWithValidEmail", func(t *testing.T) { var branch api.Branch - req := NewRequest(t, "GET", "/api/v1/repos/user2/repo16/branches/good-sign") + req := NewRequest(t, "GET", "/api/v1/repos/user2/repo16/branches/good-sign?token="+token) resp := session.MakeRequest(t, req, http.StatusOK) DecodeJSON(t, resp, &branch) assert.EqualValues(t, true, branch.Commit.Verification.Verified) @@ -143,39 +145,39 @@ func TestGPGKeys(t *testing.T) { }) } -func testViewOwnGPGKeys(t *testing.T, makeRequest makeRequestFunc, expected int) { - req := NewRequest(t, "GET", "/api/v1/user/gpg_keys") +func testViewOwnGPGKeys(t *testing.T, makeRequest makeRequestFunc, token string, expected int) { + req := NewRequest(t, "GET", "/api/v1/user/gpg_keys?token="+token) makeRequest(t, req, expected) } -func testViewGPGKeys(t *testing.T, makeRequest makeRequestFunc, expected int) { - req := NewRequest(t, "GET", "/api/v1/users/user2/gpg_keys") +func testViewGPGKeys(t *testing.T, makeRequest makeRequestFunc, token string, expected int) { + req := NewRequest(t, "GET", "/api/v1/users/user2/gpg_keys?token="+token) makeRequest(t, req, expected) } -func testGetGPGKey(t *testing.T, makeRequest makeRequestFunc, expected int) { - req := NewRequest(t, "GET", "/api/v1/user/gpg_keys/1") +func testGetGPGKey(t *testing.T, makeRequest makeRequestFunc, token string, expected int) { + req := NewRequest(t, "GET", "/api/v1/user/gpg_keys/1?token="+token) makeRequest(t, req, expected) } -func testDeleteGPGKey(t *testing.T, makeRequest makeRequestFunc, expected int) { - req := NewRequest(t, "DELETE", "/api/v1/user/gpg_keys/1") +func testDeleteGPGKey(t *testing.T, makeRequest makeRequestFunc, token string, expected int) { + req := NewRequest(t, "DELETE", "/api/v1/user/gpg_keys/1?token="+token) makeRequest(t, req, expected) } -func testCreateGPGKey(t *testing.T, makeRequest makeRequestFunc, expected int, publicKey string) { - req := NewRequestWithJSON(t, "POST", "/api/v1/user/gpg_keys", api.CreateGPGKeyOption{ +func testCreateGPGKey(t *testing.T, makeRequest makeRequestFunc, token string, expected int, publicKey string) { + req := NewRequestWithJSON(t, "POST", "/api/v1/user/gpg_keys?token="+token, api.CreateGPGKeyOption{ ArmoredKey: publicKey, }) makeRequest(t, req, expected) } -func testCreateInvalidGPGKey(t *testing.T, makeRequest makeRequestFunc, expected int) { - testCreateGPGKey(t, makeRequest, expected, "invalid_key") +func testCreateInvalidGPGKey(t *testing.T, makeRequest makeRequestFunc, token string, expected int) { + testCreateGPGKey(t, makeRequest, token, expected, "invalid_key") } -func testCreateNoneRegistredEmailGPGKey(t *testing.T, makeRequest makeRequestFunc, expected int) { - testCreateGPGKey(t, makeRequest, expected, `-----BEGIN PGP PUBLIC KEY BLOCK----- +func testCreateNoneRegistredEmailGPGKey(t *testing.T, makeRequest makeRequestFunc, token string, expected int) { + testCreateGPGKey(t, makeRequest, token, expected, `-----BEGIN PGP PUBLIC KEY BLOCK----- mQENBFmGUygBCACjCNbKvMGgp0fd5vyFW9olE1CLCSyyF9gQN2hSuzmZLuAZF2Kh dCMCG2T1UwzUB/yWUFWJ2BtCwSjuaRv+cGohqEy6bhEBV90peGA33lHfjx7wP25O @@ -194,9 +196,9 @@ INx/MmBfmtCq05FqNclvU+sj2R3N1JJOtBOjZrJHQbJhzoILou8AkxeX1A+q9OAz -----END PGP PUBLIC KEY BLOCK-----`) } -func testCreateValidGPGKey(t *testing.T, makeRequest makeRequestFunc, expected int) { +func testCreateValidGPGKey(t *testing.T, makeRequest makeRequestFunc, token string, expected int) { //User2 //primary & activated - testCreateGPGKey(t, makeRequest, expected, `-----BEGIN PGP PUBLIC KEY BLOCK----- + testCreateGPGKey(t, makeRequest, token, expected, `-----BEGIN PGP PUBLIC KEY BLOCK----- mQENBFmGVsMBCACuxgZ7W7rI9xN08Y4M7B8yx/6/I4Slm94+wXf8YNRvAyqj30dW VJhyBcnfNRDLKSQp5o/hhfDkCgdqBjLa1PnHlGS3PXJc0hP/FyYPD2BFvNMPpCYS @@ -228,9 +230,9 @@ uy6MA3VSB99SK9ducGmE1Jv8mcziREroz2TEGr0zPs6h -----END PGP PUBLIC KEY BLOCK-----`) } -func testCreateValidSecondaryEmailGPGKey(t *testing.T, makeRequest makeRequestFunc, expected int) { +func testCreateValidSecondaryEmailGPGKey(t *testing.T, makeRequest makeRequestFunc, token string, expected int) { //User2 //secondary and not activated - testCreateGPGKey(t, makeRequest, expected, `-----BEGIN PGP PUBLIC KEY BLOCK----- + testCreateGPGKey(t, makeRequest, token, expected, `-----BEGIN PGP PUBLIC KEY BLOCK----- mQENBFmGWN4BCAC18V4tVGO65VLCV7p14FuXJlUtZ5CuYMvgEkcOqrvRaBSW9ao4 PGESOhJpfWpnW3QgJniYndLzPpsmdHEclEER6aZjiNgReWPOjHD5tykWocZAJqXD diff --git a/integrations/api_issue_label_test.go b/integrations/api_issue_label_test.go index 1bfaa4303e..57ca07337d 100644 --- a/integrations/api_issue_label_test.go +++ b/integrations/api_issue_label_test.go @@ -23,12 +23,13 @@ func TestAPIAddIssueLabels(t *testing.T) { label := models.AssertExistsAndLoadBean(t, &models.Label{RepoID: repo.ID}).(*models.Label) owner := models.AssertExistsAndLoadBean(t, &models.User{ID: repo.OwnerID}).(*models.User) - urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/issues/%d/labels", - owner.Name, repo.Name, issue.Index) + session := loginUser(t, owner.Name) + token := getTokenForLoggedInUser(t, session) + urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/issues/%d/labels?token=%s", + owner.Name, repo.Name, issue.Index, token) req := NewRequestWithJSON(t, "POST", urlStr, &api.IssueLabelsOption{ Labels: []int64{label.ID}, }) - session := loginUser(t, owner.Name) resp := session.MakeRequest(t, req, http.StatusOK) var apiLabels []*api.Label DecodeJSON(t, resp, &apiLabels) @@ -45,12 +46,13 @@ func TestAPIReplaceIssueLabels(t *testing.T) { label := models.AssertExistsAndLoadBean(t, &models.Label{RepoID: repo.ID}).(*models.Label) owner := models.AssertExistsAndLoadBean(t, &models.User{ID: repo.OwnerID}).(*models.User) - urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/issues/%d/labels", - owner.Name, repo.Name, issue.Index) + session := loginUser(t, owner.Name) + token := getTokenForLoggedInUser(t, session) + urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/issues/%d/labels?token=%s", + owner.Name, repo.Name, issue.Index, token) req := NewRequestWithJSON(t, "PUT", urlStr, &api.IssueLabelsOption{ Labels: []int64{label.ID}, }) - session := loginUser(t, owner.Name) resp := session.MakeRequest(t, req, http.StatusOK) var apiLabels []*api.Label DecodeJSON(t, resp, &apiLabels) diff --git a/integrations/api_issue_test.go b/integrations/api_issue_test.go index 74436ffe9e..97207f3368 100644 --- a/integrations/api_issue_test.go +++ b/integrations/api_issue_test.go @@ -22,8 +22,9 @@ func TestAPIListIssues(t *testing.T) { owner := models.AssertExistsAndLoadBean(t, &models.User{ID: repo.OwnerID}).(*models.User) session := loginUser(t, owner.Name) - req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/issues?state=all", - owner.Name, repo.Name) + token := getTokenForLoggedInUser(t, session) + req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/issues?state=all&token=%s", + owner.Name, repo.Name, token) resp := session.MakeRequest(t, req, http.StatusOK) var apiIssues []*api.Issue DecodeJSON(t, resp, &apiIssues) @@ -41,8 +42,8 @@ func TestAPICreateIssue(t *testing.T) { owner := models.AssertExistsAndLoadBean(t, &models.User{ID: repo.OwnerID}).(*models.User) session := loginUser(t, owner.Name) - - urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/issues?state=all", owner.Name, repo.Name) + token := getTokenForLoggedInUser(t, session) + urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/issues?state=all&token=%s", owner.Name, repo.Name, token) req := NewRequestWithJSON(t, "POST", urlStr, &api.CreateIssueOption{ Body: body, Title: title, diff --git a/integrations/api_keys_test.go b/integrations/api_keys_test.go index b2ae1035ce..8c83ae42c5 100644 --- a/integrations/api_keys_test.go +++ b/integrations/api_keys_test.go @@ -46,8 +46,8 @@ func TestCreateReadOnlyDeployKey(t *testing.T) { repoOwner := models.AssertExistsAndLoadBean(t, &models.User{ID: repo.OwnerID}).(*models.User) session := loginUser(t, repoOwner.Name) - - keysURL := fmt.Sprintf("/api/v1/repos/%s/%s/keys", repoOwner.Name, repo.Name) + token := getTokenForLoggedInUser(t, session) + keysURL := fmt.Sprintf("/api/v1/repos/%s/%s/keys?token=%s", repoOwner.Name, repo.Name, token) rawKeyBody := api.CreateKeyOption{ Title: "read-only", Key: "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAAAgQDAu7tvIvX6ZHrRXuZNfkR3XLHSsuCK9Zn3X58lxBcQzuo5xZgB6vRwwm/QtJuF+zZPtY5hsQILBLmF+BZ5WpKZp1jBeSjH2G7lxet9kbcH+kIVj0tPFEoyKI9wvWqIwC4prx/WVk2wLTJjzBAhyNxfEq7C9CeiX9pQEbEqJfkKCQ== nocomment\n", @@ -72,8 +72,8 @@ func TestCreateReadWriteDeployKey(t *testing.T) { repoOwner := models.AssertExistsAndLoadBean(t, &models.User{ID: repo.OwnerID}).(*models.User) session := loginUser(t, repoOwner.Name) - - keysURL := fmt.Sprintf("/api/v1/repos/%s/%s/keys", repoOwner.Name, repo.Name) + token := getTokenForLoggedInUser(t, session) + keysURL := fmt.Sprintf("/api/v1/repos/%s/%s/keys?token=%s", repoOwner.Name, repo.Name, token) rawKeyBody := api.CreateKeyOption{ Title: "read-write", Key: "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDsufOCrDDlT8DLkodnnJtbq7uGflcPae7euTfM+Laq4So+v4WeSV362Rg0O/+Sje1UthrhN6lQkfRkdWIlCRQEXg+LMqr6RhvDfZquE2Xwqv/itlz7LjbdAUdYoO1iH7rMSmYvQh4WEnC/DAacKGbhdGIM/ZBz0z6tHm7bPgbI9ykEKekTmPwQFP1Qebvf5NYOFMWqQ2sCEAI9dBMVLoojsIpV+KADf+BotiIi8yNfTG2rzmzpxBpW9fYjd1Sy1yd4NSUpoPbEJJYJ1TrjiSWlYOVq9Ar8xW1O87i6gBjL/3zN7ANeoYhaAXupdOS6YL22YOK/yC0tJtXwwdh/eSrh", diff --git a/integrations/api_pull_test.go b/integrations/api_pull_test.go index e56b91d8b9..c416fee8ba 100644 --- a/integrations/api_pull_test.go +++ b/integrations/api_pull_test.go @@ -23,7 +23,8 @@ func TestAPIViewPulls(t *testing.T) { owner := models.AssertExistsAndLoadBean(t, &models.User{ID: repo.OwnerID}).(*models.User) session := loginUser(t, "user2") - req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/pulls?state=all", owner.Name, repo.Name) + token := getTokenForLoggedInUser(t, session) + req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/pulls?state=all&token="+token, owner.Name, repo.Name) resp := session.MakeRequest(t, req, http.StatusOK) var pulls []*api.PullRequest @@ -47,7 +48,8 @@ func TestAPIMergePullWIP(t *testing.T) { assert.Contains(t, pr.Issue.Title, setting.Repository.PullRequest.WorkInProgressPrefixes[0]) session := loginUser(t, owner.Name) - req := NewRequestWithJSON(t, http.MethodPost, fmt.Sprintf("/api/v1/repos/%s/%s/pulls/%d/merge", owner.Name, repo.Name, pr.Index), &auth.MergePullRequestForm{ + token := getTokenForLoggedInUser(t, session) + req := NewRequestWithJSON(t, http.MethodPost, fmt.Sprintf("/api/v1/repos/%s/%s/pulls/%d/merge?token=%s", owner.Name, repo.Name, pr.Index, token), &auth.MergePullRequestForm{ MergeMessageField: pr.Issue.Title, Do: string(models.MergeStyleMerge), }) diff --git a/integrations/api_releases_test.go b/integrations/api_releases_test.go index 678075935c..c8bad51c09 100644 --- a/integrations/api_releases_test.go +++ b/integrations/api_releases_test.go @@ -22,7 +22,7 @@ func TestAPICreateRelease(t *testing.T) { repo := models.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository) owner := models.AssertExistsAndLoadBean(t, &models.User{ID: repo.OwnerID}).(*models.User) session := loginUser(t, owner.LowerName) - + token := getTokenForLoggedInUser(t, session) gitRepo, err := git.OpenRepository(repo.RepoPath()) assert.NoError(t, err) @@ -32,8 +32,8 @@ func TestAPICreateRelease(t *testing.T) { commitID, err := gitRepo.GetTagCommitID("v0.0.1") assert.NoError(t, err) - urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/releases", - owner.Name, repo.Name) + urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/releases?token=%s", + owner.Name, repo.Name, token) req := NewRequestWithJSON(t, "POST", urlStr, &api.CreateReleaseOption{ TagName: "v0.0.1", Title: "v0.0.1", @@ -53,8 +53,8 @@ func TestAPICreateRelease(t *testing.T) { Note: newRelease.Note, }) - urlStr = fmt.Sprintf("/api/v1/repos/%s/%s/releases/%d", - owner.Name, repo.Name, newRelease.ID) + urlStr = fmt.Sprintf("/api/v1/repos/%s/%s/releases/%d?token=%s", + owner.Name, repo.Name, newRelease.ID, token) req = NewRequest(t, "GET", urlStr) resp = session.MakeRequest(t, req, http.StatusOK) diff --git a/integrations/api_repo_raw_test.go b/integrations/api_repo_raw_test.go index 7ef930ff3f..d8da9c831d 100644 --- a/integrations/api_repo_raw_test.go +++ b/integrations/api_repo_raw_test.go @@ -16,16 +16,17 @@ func TestAPIReposRaw(t *testing.T) { user := models.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User) // Login as User2. session := loginUser(t, user.Name) + token := getTokenForLoggedInUser(t, session) for _, ref := range [...]string{ "master", // Branch "v1.1", // Tag "65f1bf27bc3bf70f64657658635e66094edbcb4d", // Commit } { - req := NewRequestf(t, "GET", "/api/v1/repos/%s/repo1/raw/%s/README.md", user.Name, ref) + req := NewRequestf(t, "GET", "/api/v1/repos/%s/repo1/raw/%s/README.md?token="+token, user.Name, ref) session.MakeRequest(t, req, http.StatusOK) } // Test default branch - req := NewRequestf(t, "GET", "/api/v1/repos/%s/repo1/raw/README.md", user.Name) + req := NewRequestf(t, "GET", "/api/v1/repos/%s/repo1/raw/README.md?token="+token, user.Name) session.MakeRequest(t, req, http.StatusOK) } diff --git a/integrations/api_repo_test.go b/integrations/api_repo_test.go index 5dc2f88cb9..3fa2ae21dc 100644 --- a/integrations/api_repo_test.go +++ b/integrations/api_repo_test.go @@ -76,7 +76,7 @@ func TestAPISearchRepo(t *testing.T) { user: {count: 10}, user2: {count: 10}}, }, - {name: "RepositoriesDefaultMax10", requestURL: "/api/v1/repos/search", expectedResults: expectedResults{ + {name: "RepositoriesDefaultMax10", requestURL: "/api/v1/repos/search?default", expectedResults: expectedResults{ nil: {count: 10}, user: {count: 10}, user2: {count: 10}}, @@ -143,9 +143,11 @@ func TestAPISearchRepo(t *testing.T) { var session *TestSession var testName string var userID int64 + var token string if userToLogin != nil && userToLogin.ID > 0 { testName = fmt.Sprintf("LoggedUser%d", userToLogin.ID) session = loginUser(t, userToLogin.Name) + token = getTokenForLoggedInUser(t, session) userID = userToLogin.ID } else { testName = "AnonymousUser" @@ -153,7 +155,7 @@ func TestAPISearchRepo(t *testing.T) { } t.Run(testName, func(t *testing.T) { - request := NewRequest(t, "GET", testCase.requestURL) + request := NewRequest(t, "GET", testCase.requestURL+"&token="+token) response := session.MakeRequest(t, request, http.StatusOK) var body api.SearchResults @@ -214,8 +216,8 @@ func TestAPIOrgRepos(t *testing.T) { sourceOrg := models.AssertExistsAndLoadBean(t, &models.User{ID: 3}).(*models.User) // Login as User2. session := loginUser(t, user.Name) - - req := NewRequestf(t, "GET", "/api/v1/orgs/%s/repos", sourceOrg.Name) + token := getTokenForLoggedInUser(t, session) + req := NewRequestf(t, "GET", "/api/v1/orgs/%s/repos?token="+token, sourceOrg.Name) resp := session.MakeRequest(t, req, http.StatusOK) var apiRepos []*api.Repository @@ -231,9 +233,10 @@ func TestAPIOrgRepos(t *testing.T) { func TestAPIGetRepoByIDUnauthorized(t *testing.T) { prepareTestEnv(t) user := models.AssertExistsAndLoadBean(t, &models.User{ID: 4}).(*models.User) - sess := loginUser(t, user.Name) - req := NewRequestf(t, "GET", "/api/v1/repositories/2") - sess.MakeRequest(t, req, http.StatusNotFound) + session := loginUser(t, user.Name) + token := getTokenForLoggedInUser(t, session) + req := NewRequestf(t, "GET", "/api/v1/repositories/2?token="+token) + session.MakeRequest(t, req, http.StatusNotFound) } func TestAPIRepoMigrate(t *testing.T) { @@ -253,8 +256,8 @@ func TestAPIRepoMigrate(t *testing.T) { for _, testCase := range testCases { user := models.AssertExistsAndLoadBean(t, &models.User{ID: testCase.ctxUserID}).(*models.User) session := loginUser(t, user.Name) - - req := NewRequestWithJSON(t, "POST", "/api/v1/repos/migrate", &api.MigrateRepoOption{ + token := getTokenForLoggedInUser(t, session) + req := NewRequestWithJSON(t, "POST", "/api/v1/repos/migrate?token="+token, &api.MigrateRepoOption{ CloneAddr: testCase.cloneURL, UID: int(testCase.userID), RepoName: testCase.repoName, @@ -278,8 +281,8 @@ func TestAPIOrgRepoCreate(t *testing.T) { for _, testCase := range testCases { user := models.AssertExistsAndLoadBean(t, &models.User{ID: testCase.ctxUserID}).(*models.User) session := loginUser(t, user.Name) - - req := NewRequestWithJSON(t, "POST", fmt.Sprintf("/api/v1/org/%s/repos", testCase.orgName), &api.CreateRepoOption{ + token := getTokenForLoggedInUser(t, session) + req := NewRequestWithJSON(t, "POST", fmt.Sprintf("/api/v1/org/%s/repos?token="+token, testCase.orgName), &api.CreateRepoOption{ Name: testCase.repoName, }) session.MakeRequest(t, req, testCase.expectedStatus) diff --git a/integrations/api_team_test.go b/integrations/api_team_test.go index b8d21be539..f59d95c712 100644 --- a/integrations/api_team_test.go +++ b/integrations/api_team_test.go @@ -21,7 +21,8 @@ func TestAPITeam(t *testing.T) { user := models.AssertExistsAndLoadBean(t, &models.User{ID: teamUser.UID}).(*models.User) session := loginUser(t, user.Name) - req := NewRequestf(t, "GET", "/api/v1/teams/%d", teamUser.TeamID) + token := getTokenForLoggedInUser(t, session) + req := NewRequestf(t, "GET", "/api/v1/teams/%d?token="+token, teamUser.TeamID) resp := session.MakeRequest(t, req, http.StatusOK) var apiTeam api.Team diff --git a/integrations/git_test.go b/integrations/git_test.go index 49f75c4a4a..7ac375dd02 100644 --- a/integrations/git_test.go +++ b/integrations/git_test.go @@ -75,7 +75,8 @@ func TestGit(t *testing.T) { t.Run("CreateRepo", func(t *testing.T) { session := loginUser(t, "user2") - req := NewRequestWithJSON(t, "POST", "/api/v1/user/repos", &api.CreateRepoOption{ + token := getTokenForLoggedInUser(t, session) + req := NewRequestWithJSON(t, "POST", "/api/v1/user/repos?token="+token, &api.CreateRepoOption{ AutoInit: true, Description: "Temporary repo", Name: "repo-tmp-17", @@ -166,7 +167,8 @@ func TestGit(t *testing.T) { t.Run("Standard", func(t *testing.T) { t.Run("CreateRepo", func(t *testing.T) { session := loginUser(t, "user2") - req := NewRequestWithJSON(t, "POST", "/api/v1/user/repos", &api.CreateRepoOption{ + token := getTokenForLoggedInUser(t, session) + req := NewRequestWithJSON(t, "POST", "/api/v1/user/repos?token="+token, &api.CreateRepoOption{ AutoInit: true, Description: "Temporary repo", Name: "repo-tmp-18", diff --git a/integrations/integration_test.go b/integrations/integration_test.go index a1e66ffdfd..ed165f6534 100644 --- a/integrations/integration_test.go +++ b/integrations/integration_test.go @@ -223,6 +223,22 @@ func loginUserWithPassword(t testing.TB, userName, password string) *TestSession return session } +func getTokenForLoggedInUser(t testing.TB, session *TestSession) string { + req := NewRequest(t, "GET", "/user/settings/applications") + resp := session.MakeRequest(t, req, http.StatusOK) + doc := NewHTMLParser(t, resp.Body) + req = NewRequestWithValues(t, "POST", "/user/settings/applications", map[string]string{ + "_csrf": doc.GetCSRF(), + "name": "api-testing-token", + }) + resp = session.MakeRequest(t, req, http.StatusFound) + req = NewRequest(t, "GET", "/user/settings/applications") + resp = session.MakeRequest(t, req, http.StatusOK) + htmlDoc := NewHTMLParser(t, resp.Body) + token := htmlDoc.doc.Find(".ui.info p").Text() + return token +} + func NewRequest(t testing.TB, method, urlStr string) *http.Request { return NewRequestWithBody(t, method, urlStr, nil) } diff --git a/integrations/repo_commits_test.go b/integrations/repo_commits_test.go index 94d513370d..48aac1802b 100644 --- a/integrations/repo_commits_test.go +++ b/integrations/repo_commits_test.go @@ -33,6 +33,7 @@ func doTestRepoCommitWithStatus(t *testing.T, state string, classes ...string) { prepareTestEnv(t) session := loginUser(t, "user2") + token := getTokenForLoggedInUser(t, session) // Request repository commits page req := NewRequest(t, "GET", "/user2/repo1/commits/branch/master") @@ -45,7 +46,7 @@ func doTestRepoCommitWithStatus(t *testing.T, state string, classes ...string) { assert.NotEmpty(t, commitURL) // Call API to add status for commit - req = NewRequestWithJSON(t, "POST", "/api/v1/repos/user2/repo1/statuses/"+path.Base(commitURL), + req = NewRequestWithJSON(t, "POST", "/api/v1/repos/user2/repo1/statuses/"+path.Base(commitURL)+"?token="+token, api.CreateStatusOption{ State: api.StatusState(state), TargetURL: "http://test.ci/", diff --git a/modules/auth/auth.go b/modules/auth/auth.go index f3aac51899..8391e7de8f 100644 --- a/modules/auth/auth.go +++ b/modules/auth/auth.go @@ -63,6 +63,7 @@ func SignedInID(ctx *macaron.Context, sess session.Store) int64 { if err = models.UpdateAccessToken(t); err != nil { log.Error(4, "UpdateAccessToken: %v", err) } + ctx.Data["IsApiToken"] = true return t.UID } } @@ -136,7 +137,7 @@ func SignedInUser(ctx *macaron.Context, sess session.Store) (*models.User, bool) } return nil, false } - + ctx.Data["IsApiToken"] = true return u, true } } diff --git a/routers/api/v1/api.go b/routers/api/v1/api.go index 967db3b01c..23a85759c2 100644 --- a/routers/api/v1/api.go +++ b/routers/api/v1/api.go @@ -175,7 +175,7 @@ func repoAssignment() macaron.Handler { // Contexter middleware already checks token for user sign in process. func reqToken() macaron.Handler { return func(ctx *context.Context) { - if !ctx.IsSigned { + if true != ctx.Data["IsApiToken"] { ctx.Error(401) return }