Replace CSRF cookie with CrossOriginProtection (#36183)

Removes the CSRF cookie in favor of
[`CrossOriginProtection`](https://pkg.go.dev/net/http#CrossOriginProtection)
which relies purely on HTTP headers.

Fixes: https://github.com/go-gitea/gitea/issues/11188
Fixes: https://github.com/go-gitea/gitea/issues/30333
Helps: https://github.com/go-gitea/gitea/issues/35107

TODOs:

- [x] Fix tests
- [ ] Ideally add tests to validates the protection

---------

Signed-off-by: wxiaoguang <wxiaoguang@gmail.com>
Co-authored-by: wxiaoguang <wxiaoguang@gmail.com>
This commit is contained in:
silverwind
2025-12-25 11:33:34 +01:00
committed by GitHub
parent eddf875992
commit 42d294941c
207 changed files with 178 additions and 1196 deletions

View File

@@ -127,10 +127,7 @@ jobs:
)
// user2 approves all runs
req = NewRequestWithValues(t, "POST", dataURL,
map[string]string{
"_csrf": GetUserCSRFToken(t, user2Session),
})
req = NewRequest(t, "POST", dataURL)
user2Session.MakeRequest(t, req, http.StatusOK)
// check runs

View File

@@ -51,7 +51,7 @@ func TestWorkflowConcurrency(t *testing.T) {
wf1TreePath := ".gitea/workflows/concurrent-workflow-1.yml"
wf1FileContent := `name: concurrent-workflow-1
on:
on:
push:
paths:
- '.gitea/workflows/concurrent-workflow-1.yml'
@@ -65,7 +65,7 @@ jobs:
`
wf2TreePath := ".gitea/workflows/concurrent-workflow-2.yml"
wf2FileContent := `name: concurrent-workflow-2
on:
on:
push:
paths:
- '.gitea/workflows/concurrent-workflow-2.yml'
@@ -79,7 +79,7 @@ jobs:
`
wf3TreePath := ".gitea/workflows/concurrent-workflow-3.yml"
wf3FileContent := `name: concurrent-workflow-3
on:
on:
push:
paths:
- '.gitea/workflows/concurrent-workflow-3.yml'
@@ -159,7 +159,7 @@ func TestWorkflowConcurrencyShort(t *testing.T) {
wf1TreePath := ".gitea/workflows/concurrent-workflow-1.yml"
wf1FileContent := `name: concurrent-workflow-1
on:
on:
push:
paths:
- '.gitea/workflows/concurrent-workflow-1.yml'
@@ -172,7 +172,7 @@ jobs:
`
wf2TreePath := ".gitea/workflows/concurrent-workflow-2.yml"
wf2FileContent := `name: concurrent-workflow-2
on:
on:
push:
paths:
- '.gitea/workflows/concurrent-workflow-2.yml'
@@ -185,7 +185,7 @@ jobs:
`
wf3TreePath := ".gitea/workflows/concurrent-workflow-3.yml"
wf3FileContent := `name: concurrent-workflow-3
on:
on:
push:
paths:
- '.gitea/workflows/concurrent-workflow-3.yml'
@@ -264,7 +264,7 @@ func TestWorkflowConcurrencyShortJson(t *testing.T) {
wf1TreePath := ".gitea/workflows/concurrent-workflow-1.yml"
wf1FileContent := `name: concurrent-workflow-1
on:
on:
push:
paths:
- '.gitea/workflows/concurrent-workflow-1.yml'
@@ -281,7 +281,7 @@ jobs:
`
wf2TreePath := ".gitea/workflows/concurrent-workflow-2.yml"
wf2FileContent := `name: concurrent-workflow-2
on:
on:
push:
paths:
- '.gitea/workflows/concurrent-workflow-2.yml'
@@ -298,7 +298,7 @@ jobs:
`
wf3TreePath := ".gitea/workflows/concurrent-workflow-3.yml"
wf3FileContent := `name: concurrent-workflow-3
on:
on:
push:
paths:
- '.gitea/workflows/concurrent-workflow-3.yml'
@@ -454,11 +454,7 @@ jobs:
runner.fetchNoTask(t)
// user2 approves the run
pr2Run1 := unittest.AssertExistsAndLoadBean(t, &actions_model.ActionRun{RepoID: baseRepo.ID, TriggerUserID: user4.ID})
req = NewRequestWithValues(t, "POST",
fmt.Sprintf("/%s/%s/actions/runs/%d/approve", baseRepo.OwnerName, baseRepo.Name, pr2Run1.Index),
map[string]string{
"_csrf": GetUserCSRFToken(t, user2Session),
})
req = NewRequest(t, "POST", fmt.Sprintf("/%s/%s/actions/runs/%d/approve", baseRepo.OwnerName, baseRepo.Name, pr2Run1.Index))
user2Session.MakeRequest(t, req, http.StatusOK)
// fetch the task and the previous task has been cancelled
pr2Task1 := runner.fetchTask(t)
@@ -532,7 +528,7 @@ func TestJobConcurrency(t *testing.T) {
wf1TreePath := ".gitea/workflows/concurrent-workflow-1.yml"
wf1FileContent := `name: concurrent-workflow-1
on:
on:
push:
paths:
- '.gitea/workflows/concurrent-workflow-1.yml'
@@ -546,7 +542,7 @@ jobs:
`
wf2TreePath := ".gitea/workflows/concurrent-workflow-2.yml"
wf2FileContent := `name: concurrent-workflow-2
on:
on:
push:
paths:
- '.gitea/workflows/concurrent-workflow-2.yml'
@@ -554,7 +550,7 @@ jobs:
wf2-job1:
runs-on: runner2
outputs:
version: ${{ steps.version_step.outputs.app_version }}
version: ${{ steps.version_step.outputs.app_version }}
steps:
- id: version_step
run: echo "app_version=v1.23.0" >> "$GITHUB_OUTPUT"
@@ -568,7 +564,7 @@ jobs:
`
wf3TreePath := ".gitea/workflows/concurrent-workflow-3.yml"
wf3FileContent := `name: concurrent-workflow-3
on:
on:
push:
paths:
- '.gitea/workflows/concurrent-workflow-3.yml'
@@ -624,9 +620,7 @@ jobs:
assert.Equal(t, actions_model.StatusCancelled, wf2Job2ActionJob.Status)
// rerun wf2
req = NewRequestWithValues(t, "POST", fmt.Sprintf("/%s/%s/actions/runs/%d/rerun", user2.Name, repo.Name, wf2Run.Index), map[string]string{
"_csrf": GetUserCSRFToken(t, session),
})
req = NewRequest(t, "POST", fmt.Sprintf("/%s/%s/actions/runs/%d/rerun", user2.Name, repo.Name, wf2Run.Index))
_ = session.MakeRequest(t, req, http.StatusOK)
// (rerun1) cannot fetch wf2-job2
@@ -650,9 +644,7 @@ jobs:
assert.Equal(t, "job-main-v1.24.0", wf2Job2Rerun1Job.ConcurrencyGroup)
// rerun wf2-job2
req = NewRequestWithValues(t, "POST", fmt.Sprintf("/%s/%s/actions/runs/%d/jobs/%d/rerun", user2.Name, repo.Name, wf2Run.Index, 1), map[string]string{
"_csrf": GetUserCSRFToken(t, session),
})
req = NewRequest(t, "POST", fmt.Sprintf("/%s/%s/actions/runs/%d/jobs/%d/rerun", user2.Name, repo.Name, wf2Run.Index, 1))
_ = session.MakeRequest(t, req, http.StatusOK)
// (rerun2) fetch and exec wf2-job2
wf2Job2Rerun2Task := runner1.fetchTask(t)
@@ -684,7 +676,7 @@ func TestMatrixConcurrency(t *testing.T) {
wf1TreePath := ".gitea/workflows/concurrent-workflow-1.yml"
wf1FileContent := `name: concurrent-workflow-1
on:
on:
push:
paths:
- '.gitea/workflows/concurrent-workflow-1.yml'
@@ -702,7 +694,7 @@ jobs:
wf2TreePath := ".gitea/workflows/concurrent-workflow-2.yml"
wf2FileContent := `name: concurrent-workflow-2
on:
on:
push:
paths:
- '.gitea/workflows/concurrent-workflow-2.yml'
@@ -806,7 +798,6 @@ jobs:
// run the workflow with appVersion=v1.21 and cancel=false
urlStr := fmt.Sprintf("/%s/%s/actions/run?workflow=%s", user2.Name, repo.Name, "workflow-dispatch-concurrency.yml")
req := NewRequestWithValues(t, "POST", urlStr, map[string]string{
"_csrf": GetUserCSRFToken(t, session),
"ref": "refs/heads/main",
"appVersion": "v1.21",
})
@@ -817,7 +808,6 @@ jobs:
// run the workflow with appVersion=v1.22 and cancel=false
req = NewRequestWithValues(t, "POST", urlStr, map[string]string{
"_csrf": GetUserCSRFToken(t, session),
"ref": "refs/heads/main",
"appVersion": "v1.22",
})
@@ -828,7 +818,6 @@ jobs:
// run the workflow with appVersion=v1.22 and cancel=false again
req = NewRequestWithValues(t, "POST", urlStr, map[string]string{
"_csrf": GetUserCSRFToken(t, session),
"ref": "refs/heads/main",
"appVersion": "v1.22",
})
@@ -837,7 +826,6 @@ jobs:
// run the workflow with appVersion=v1.22 and cancel=true
req = NewRequestWithValues(t, "POST", urlStr, map[string]string{
"_csrf": GetUserCSRFToken(t, session),
"ref": "refs/heads/main",
"appVersion": "v1.22",
"cancel": "on",
@@ -900,7 +888,6 @@ jobs:
// run the workflow with appVersion=v1.21 and cancel=false
urlStr := fmt.Sprintf("/%s/%s/actions/run?workflow=%s", user2.Name, repo.Name, "workflow-dispatch-concurrency.yml")
req := NewRequestWithValues(t, "POST", urlStr, map[string]string{
"_csrf": GetUserCSRFToken(t, session),
"ref": "refs/heads/main",
"appVersion": "v1.21",
})
@@ -910,7 +897,6 @@ jobs:
assert.Equal(t, "workflow-dispatch-v1.21", run1.ConcurrencyGroup)
req = NewRequestWithValues(t, "POST", urlStr, map[string]string{
"_csrf": GetUserCSRFToken(t, session),
"ref": "refs/heads/main",
"appVersion": "v1.22",
})
@@ -921,7 +907,6 @@ jobs:
// run the workflow with appVersion=v1.22 and cancel=false again
req = NewRequestWithValues(t, "POST", urlStr, map[string]string{
"_csrf": GetUserCSRFToken(t, session),
"ref": "refs/heads/main",
"appVersion": "v1.22",
})
@@ -931,7 +916,6 @@ jobs:
// run the workflow with appVersion=v1.22 and cancel=true
req = NewRequestWithValues(t, "POST", urlStr, map[string]string{
"_csrf": GetUserCSRFToken(t, session),
"ref": "refs/heads/main",
"appVersion": "v1.22",
"cancel": "on",
@@ -950,14 +934,10 @@ jobs:
// rerun cancel true scenario
req = NewRequestWithValues(t, "POST", fmt.Sprintf("/%s/%s/actions/runs/%d/rerun", user2.Name, apiRepo.Name, run2.Index), map[string]string{
"_csrf": GetUserCSRFToken(t, session),
})
req = NewRequest(t, "POST", fmt.Sprintf("/%s/%s/actions/runs/%d/rerun", user2.Name, apiRepo.Name, run2.Index))
_ = session.MakeRequest(t, req, http.StatusOK)
req = NewRequestWithValues(t, "POST", fmt.Sprintf("/%s/%s/actions/runs/%d/rerun", user2.Name, apiRepo.Name, run4.Index), map[string]string{
"_csrf": GetUserCSRFToken(t, session),
})
req = NewRequest(t, "POST", fmt.Sprintf("/%s/%s/actions/runs/%d/rerun", user2.Name, apiRepo.Name, run4.Index))
_ = session.MakeRequest(t, req, http.StatusOK)
task5 := runner.fetchTask(t)
@@ -973,17 +953,13 @@ jobs:
// rerun cancel false scenario
req = NewRequestWithValues(t, "POST", fmt.Sprintf("/%s/%s/actions/runs/%d/rerun", user2.Name, apiRepo.Name, run2.Index), map[string]string{
"_csrf": GetUserCSRFToken(t, session),
})
req = NewRequest(t, "POST", fmt.Sprintf("/%s/%s/actions/runs/%d/rerun", user2.Name, apiRepo.Name, run2.Index))
_ = session.MakeRequest(t, req, http.StatusOK)
run2_2 := unittest.AssertExistsAndLoadBean(t, &actions_model.ActionRun{ID: run2.ID})
assert.Equal(t, actions_model.StatusWaiting, run2_2.Status)
req = NewRequestWithValues(t, "POST", fmt.Sprintf("/%s/%s/actions/runs/%d/rerun", user2.Name, apiRepo.Name, run2.Index+1), map[string]string{
"_csrf": GetUserCSRFToken(t, session),
})
req = NewRequest(t, "POST", fmt.Sprintf("/%s/%s/actions/runs/%d/rerun", user2.Name, apiRepo.Name, run2.Index+1))
_ = session.MakeRequest(t, req, http.StatusOK)
task6 := runner.fetchTask(t)
@@ -1044,7 +1020,6 @@ jobs:
// run the workflow with appVersion=v1.21 and cancel=false
urlStr := fmt.Sprintf("/%s/%s/actions/run?workflow=%s", user2.Name, repo.Name, "workflow-dispatch-concurrency.yml")
req := NewRequestWithValues(t, "POST", urlStr, map[string]string{
"_csrf": GetUserCSRFToken(t, session),
"ref": "refs/heads/main",
"appVersion": "v1.21",
})
@@ -1054,7 +1029,6 @@ jobs:
assert.Equal(t, "workflow-dispatch-v1.21", run1.ConcurrencyGroup)
req = NewRequestWithValues(t, "POST", urlStr, map[string]string{
"_csrf": GetUserCSRFToken(t, session),
"ref": "refs/heads/main",
"appVersion": "v1.22",
})
@@ -1065,7 +1039,6 @@ jobs:
// run the workflow with appVersion=v1.22 and cancel=false again
req = NewRequestWithValues(t, "POST", urlStr, map[string]string{
"_csrf": GetUserCSRFToken(t, session),
"ref": "refs/heads/main",
"appVersion": "v1.22",
})
@@ -1075,7 +1048,6 @@ jobs:
// run the workflow with appVersion=v1.22 and cancel=true
req = NewRequestWithValues(t, "POST", urlStr, map[string]string{
"_csrf": GetUserCSRFToken(t, session),
"ref": "refs/heads/main",
"appVersion": "v1.22",
"cancel": "on",
@@ -1094,14 +1066,10 @@ jobs:
// rerun cancel true scenario
req = NewRequestWithValues(t, "POST", fmt.Sprintf("/%s/%s/actions/runs/%d/jobs/%d/rerun", user2.Name, apiRepo.Name, run2.Index, 1), map[string]string{
"_csrf": GetUserCSRFToken(t, session),
})
req = NewRequest(t, "POST", fmt.Sprintf("/%s/%s/actions/runs/%d/jobs/%d/rerun", user2.Name, apiRepo.Name, run2.Index, 1))
_ = session.MakeRequest(t, req, http.StatusOK)
req = NewRequestWithValues(t, "POST", fmt.Sprintf("/%s/%s/actions/runs/%d/jobs/%d/rerun", user2.Name, apiRepo.Name, run4.Index, 1), map[string]string{
"_csrf": GetUserCSRFToken(t, session),
})
req = NewRequest(t, "POST", fmt.Sprintf("/%s/%s/actions/runs/%d/jobs/%d/rerun", user2.Name, apiRepo.Name, run4.Index, 1))
_ = session.MakeRequest(t, req, http.StatusOK)
task5 := runner.fetchTask(t)
@@ -1117,17 +1085,13 @@ jobs:
// rerun cancel false scenario
req = NewRequestWithValues(t, "POST", fmt.Sprintf("/%s/%s/actions/runs/%d/jobs/%d/rerun", user2.Name, apiRepo.Name, run2.Index, 1), map[string]string{
"_csrf": GetUserCSRFToken(t, session),
})
req = NewRequest(t, "POST", fmt.Sprintf("/%s/%s/actions/runs/%d/jobs/%d/rerun", user2.Name, apiRepo.Name, run2.Index, 1))
_ = session.MakeRequest(t, req, http.StatusOK)
run2_2 := unittest.AssertExistsAndLoadBean(t, &actions_model.ActionRun{ID: run2.ID})
assert.Equal(t, actions_model.StatusWaiting, run2_2.Status)
req = NewRequestWithValues(t, "POST", fmt.Sprintf("/%s/%s/actions/runs/%d/jobs/%d/rerun", user2.Name, apiRepo.Name, run2.Index+1, 1), map[string]string{
"_csrf": GetUserCSRFToken(t, session),
})
req = NewRequest(t, "POST", fmt.Sprintf("/%s/%s/actions/runs/%d/jobs/%d/rerun", user2.Name, apiRepo.Name, run2.Index+1, 1))
_ = session.MakeRequest(t, req, http.StatusOK)
task6 := runner.fetchTask(t)
@@ -1259,7 +1223,7 @@ func TestWorkflowAndJobConcurrency(t *testing.T) {
wf1TreePath := ".gitea/workflows/concurrent-workflow-1.yml"
wf1FileContent := `name: concurrent-workflow-1
on:
on:
push:
paths:
- '.gitea/workflows/concurrent-workflow-1.yml'
@@ -1281,7 +1245,7 @@ jobs:
`
wf2TreePath := ".gitea/workflows/concurrent-workflow-2.yml"
wf2FileContent := `name: concurrent-workflow-2
on:
on:
push:
paths:
- '.gitea/workflows/concurrent-workflow-2.yml'
@@ -1303,7 +1267,7 @@ jobs:
`
wf3TreePath := ".gitea/workflows/concurrent-workflow-3.yml"
wf3FileContent := `name: concurrent-workflow-3
on:
on:
push:
paths:
- '.gitea/workflows/concurrent-workflow-3.yml'
@@ -1320,7 +1284,7 @@ jobs:
wf4TreePath := ".gitea/workflows/concurrent-workflow-4.yml"
wf4FileContent := `name: concurrent-workflow-4
on:
on:
push:
paths:
- '.gitea/workflows/concurrent-workflow-4.yml'
@@ -1491,9 +1455,7 @@ jobs:
runner.fetchNoTask(t)
// cancel the first run
req := NewRequestWithValues(t, "POST", fmt.Sprintf("/%s/%s/actions/runs/%d/cancel", user2.Name, repo.Name, run1.Index), map[string]string{
"_csrf": GetUserCSRFToken(t, user2Session),
})
req := NewRequest(t, "POST", fmt.Sprintf("/%s/%s/actions/runs/%d/cancel", user2.Name, repo.Name, run1.Index))
user2Session.MakeRequest(t, req, http.StatusOK)
// the first run has been cancelled
@@ -1525,7 +1487,7 @@ func TestAbandonConcurrentRun(t *testing.T) {
wf1TreePath := ".gitea/workflows/workflow-1.yml"
wf1FileContent := `name: Workflow-1
on:
on:
push:
paths:
- '.gitea/workflows/workflow-1.yml'
@@ -1544,7 +1506,7 @@ jobs:
wf2TreePath := ".gitea/workflows/workflow-2.yml"
wf2FileContent := `name: Workflow-2
on:
on:
push:
paths:
- '.gitea/workflows/workflow-2.yml'
@@ -1624,7 +1586,7 @@ func TestRunAndJobWithSameConcurrencyGroup(t *testing.T) {
wf1TreePath := ".gitea/workflows/concurrent-workflow-1.yml"
wf1FileContent := `name: concurrent-workflow-1
on:
on:
push:
paths:
- '.gitea/workflows/concurrent-workflow-1.yml'
@@ -1638,7 +1600,7 @@ jobs:
`
wf2TreePath := ".gitea/workflows/concurrent-workflow-2.yml"
wf2FileContent := `name: concurrent-workflow-2
on:
on:
push:
paths:
- '.gitea/workflows/concurrent-workflow-2.yml'
@@ -1652,7 +1614,7 @@ jobs:
`
wf3TreePath := ".gitea/workflows/concurrent-workflow-3.yml"
wf3FileContent := `name: concurrent-workflow-3
on:
on:
push:
paths:
- '.gitea/workflows/concurrent-workflow-3.yml'

View File

@@ -133,9 +133,7 @@ jobs:
}
for i := 0; i < len(testCase.outcomes); i++ {
req := NewRequestWithValues(t, "POST", fmt.Sprintf("/%s/%s/actions/runs/%s/jobs/%d", user2.Name, apiRepo.Name, runIndex, i), map[string]string{
"_csrf": GetUserCSRFToken(t, session),
})
req := NewRequest(t, "POST", fmt.Sprintf("/%s/%s/actions/runs/%s/jobs/%d", user2.Name, apiRepo.Name, runIndex, i))
resp := session.MakeRequest(t, req, http.StatusOK)
var listResp actions.ViewResponse
err := json.Unmarshal(resp.Body.Bytes(), &listResp)
@@ -147,30 +145,20 @@ jobs:
MakeRequest(t, req, http.StatusOK)
}
req := NewRequestWithValues(t, "GET", fmt.Sprintf("/%s/%s/actions/runs/%s", user2.Name, apiRepo.Name, runIndex), map[string]string{
"_csrf": GetUserCSRFToken(t, session),
})
req := NewRequest(t, "GET", fmt.Sprintf("/%s/%s/actions/runs/%s", user2.Name, apiRepo.Name, runIndex))
session.MakeRequest(t, req, http.StatusOK)
req = NewRequestWithValues(t, "POST", fmt.Sprintf("/%s/%s/actions/runs/%s/delete", user2.Name, apiRepo.Name, runIndex), map[string]string{
"_csrf": GetUserCSRFToken(t, session),
})
req = NewRequest(t, "POST", fmt.Sprintf("/%s/%s/actions/runs/%s/delete", user2.Name, apiRepo.Name, runIndex))
session.MakeRequest(t, req, http.StatusOK)
req = NewRequestWithValues(t, "POST", fmt.Sprintf("/%s/%s/actions/runs/%s/delete", user2.Name, apiRepo.Name, runIndex), map[string]string{
"_csrf": GetUserCSRFToken(t, session),
})
req = NewRequest(t, "POST", fmt.Sprintf("/%s/%s/actions/runs/%s/delete", user2.Name, apiRepo.Name, runIndex))
session.MakeRequest(t, req, http.StatusNotFound)
req = NewRequestWithValues(t, "GET", fmt.Sprintf("/%s/%s/actions/runs/%s", user2.Name, apiRepo.Name, runIndex), map[string]string{
"_csrf": GetUserCSRFToken(t, session),
})
req = NewRequest(t, "GET", fmt.Sprintf("/%s/%s/actions/runs/%s", user2.Name, apiRepo.Name, runIndex))
session.MakeRequest(t, req, http.StatusNotFound)
for i := 0; i < len(testCase.outcomes); i++ {
req := NewRequestWithValues(t, "POST", fmt.Sprintf("/%s/%s/actions/runs/%s/jobs/%d", user2.Name, apiRepo.Name, runIndex, i), map[string]string{
"_csrf": GetUserCSRFToken(t, session),
})
req := NewRequest(t, "POST", fmt.Sprintf("/%s/%s/actions/runs/%s/jobs/%d", user2.Name, apiRepo.Name, runIndex, i))
session.MakeRequest(t, req, http.StatusNotFound)
req = NewRequest(t, "GET", fmt.Sprintf("/%s/%s/actions/runs/%s/jobs/%d/logs", user2.Name, apiRepo.Name, runIndex, i)).

View File

@@ -62,9 +62,8 @@ jobs:
// run the workflow with os=windows
urlStr := fmt.Sprintf("/%s/%s/actions/run?workflow=%s", user2.Name, repo.Name, "test-inputs-context.yml")
req := NewRequestWithValues(t, "POST", urlStr, map[string]string{
"_csrf": GetUserCSRFToken(t, session),
"ref": "refs/heads/main",
"os": "windows",
"ref": "refs/heads/main",
"os": "windows",
})
session.MakeRequest(t, req, http.StatusSeeOther)

View File

@@ -33,7 +33,7 @@ func TestActionsRerun(t *testing.T) {
wfTreePath := ".gitea/workflows/actions-rerun-workflow-1.yml"
wfFileContent := `name: actions-rerun-workflow-1
on:
on:
push:
paths:
- '.gitea/workflows/actions-rerun-workflow-1.yml'
@@ -59,9 +59,7 @@ jobs:
result: runnerv1.Result_RESULT_SUCCESS,
})
// RERUN-FAILURE: the run is not done
req := NewRequestWithValues(t, "POST", fmt.Sprintf("/%s/%s/actions/runs/%d/rerun", user2.Name, repo.Name, run.Index), map[string]string{
"_csrf": GetUserCSRFToken(t, session),
})
req := NewRequest(t, "POST", fmt.Sprintf("/%s/%s/actions/runs/%d/rerun", user2.Name, repo.Name, run.Index))
session.MakeRequest(t, req, http.StatusBadRequest)
// fetch and exec job2
job2Task := runner.fetchTask(t)
@@ -70,9 +68,7 @@ jobs:
})
// RERUN-1: rerun the run
req = NewRequestWithValues(t, "POST", fmt.Sprintf("/%s/%s/actions/runs/%d/rerun", user2.Name, repo.Name, run.Index), map[string]string{
"_csrf": GetUserCSRFToken(t, session),
})
req = NewRequest(t, "POST", fmt.Sprintf("/%s/%s/actions/runs/%d/rerun", user2.Name, repo.Name, run.Index))
session.MakeRequest(t, req, http.StatusOK)
// fetch and exec job1
job1TaskR1 := runner.fetchTask(t)
@@ -86,9 +82,7 @@ jobs:
})
// RERUN-2: rerun job1
req = NewRequestWithValues(t, "POST", fmt.Sprintf("/%s/%s/actions/runs/%d/jobs/%d/rerun", user2.Name, repo.Name, run.Index, 0), map[string]string{
"_csrf": GetUserCSRFToken(t, session),
})
req = NewRequest(t, "POST", fmt.Sprintf("/%s/%s/actions/runs/%d/jobs/%d/rerun", user2.Name, repo.Name, run.Index, 0))
session.MakeRequest(t, req, http.StatusOK)
// job2 needs job1, so rerunning job1 will also rerun job2
// fetch and exec job1
@@ -103,9 +97,7 @@ jobs:
})
// RERUN-3: rerun job2
req = NewRequestWithValues(t, "POST", fmt.Sprintf("/%s/%s/actions/runs/%d/jobs/%d/rerun", user2.Name, repo.Name, run.Index, 1), map[string]string{
"_csrf": GetUserCSRFToken(t, session),
})
req = NewRequest(t, "POST", fmt.Sprintf("/%s/%s/actions/runs/%d/jobs/%d/rerun", user2.Name, repo.Name, run.Index, 1))
session.MakeRequest(t, req, http.StatusOK)
// only job2 will rerun
// fetch and exec job2

View File

@@ -50,16 +50,13 @@ func TestActionsRunnerModify(t *testing.T) {
doUpdate := func(t *testing.T, sess *TestSession, baseURL string, id int64, description string, expectedStatus int) {
req := NewRequestWithValues(t, "POST", fmt.Sprintf("%s/%d", baseURL, id), map[string]string{
"_csrf": GetUserCSRFToken(t, sess),
"description": description,
})
sess.MakeRequest(t, req, expectedStatus)
}
doDelete := func(t *testing.T, sess *TestSession, baseURL string, id int64, expectedStatus int) {
req := NewRequestWithValues(t, "POST", fmt.Sprintf("%s/%d/delete", baseURL, id), map[string]string{
"_csrf": GetUserCSRFToken(t, sess),
})
req := NewRequest(t, "POST", fmt.Sprintf("%s/%d/delete", baseURL, id))
sess.MakeRequest(t, req, expectedStatus)
}

View File

@@ -42,7 +42,6 @@ func TestActionsCollaborativeOwner(t *testing.T) {
// add user10 to the list of collaborative owners
req := NewRequestWithValues(t, "POST", fmt.Sprintf("/%s/%s/settings/actions/general/collaborative_owner/add", repo.Owner.UserName, repo.Name), map[string]string{
"_csrf": GetUserCSRFToken(t, user2Session),
"collaborative_owner": user10.Name,
})
user2Session.MakeRequest(t, req, http.StatusOK)
@@ -51,9 +50,7 @@ func TestActionsCollaborativeOwner(t *testing.T) {
doGitClone(dstPath, u)(t)
// remove user10 from the list of collaborative owners
req = NewRequestWithValues(t, "POST", fmt.Sprintf("/%s/%s/settings/actions/general/collaborative_owner/delete?id=%d", repo.Owner.UserName, repo.Name, user10.ID), map[string]string{
"_csrf": GetUserCSRFToken(t, user2Session),
})
req = NewRequest(t, "POST", fmt.Sprintf("/%s/%s/settings/actions/general/collaborative_owner/delete?id=%d", repo.Owner.UserName, repo.Name, user10.ID))
user2Session.MakeRequest(t, req, http.StatusOK)
// the git clone will fail

View File

@@ -1614,7 +1614,7 @@ func TestPullRequestWithPathsRebase(t *testing.T) {
testCreateFile(t, session, "user2", repoName, repo.DefaultBranch, "", "dir1/dir1.txt", "1")
testCreateFile(t, session, "user2", repoName, repo.DefaultBranch, "", "dir2/dir2.txt", "2")
wfFileContent := `name: ci
on:
on:
pull_request:
paths:
- 'dir1/**'
@@ -1639,12 +1639,10 @@ jobs:
apiPull, err := doAPICreatePullRequest(apiCtx, "user2", repoName, repo.DefaultBranch, "update-dir2")(t)
runner.fetchNoTask(t)
assert.NoError(t, err)
testEditFile(t, session, "user2", repoName, repo.DefaultBranch, "dir1/dir1.txt", "11") // change the file in "dir1"
req := NewRequestWithValues(t, "POST",
fmt.Sprintf("/%s/%s/pulls/%d/update?style=rebase", "user2", repoName, apiPull.Index), // update by rebase
map[string]string{
"_csrf": GetUserCSRFToken(t, session),
})
// change the file in "dir1"
testEditFile(t, session, "user2", repoName, repo.DefaultBranch, "dir1/dir1.txt", "11")
// update by rebase
req := NewRequest(t, "POST", fmt.Sprintf("/%s/%s/pulls/%d/update?style=rebase", "user2", repoName, apiPull.Index))
session.MakeRequest(t, req, http.StatusSeeOther)
runner.fetchNoTask(t)
})

View File

@@ -50,17 +50,14 @@ func TestActionsVariables(t *testing.T) {
doUpdate := func(t *testing.T, sess *TestSession, baseURL string, id int64, data string, expectedStatus int) {
req := NewRequestWithValues(t, "POST", fmt.Sprintf("%s/%d/edit", baseURL, id), map[string]string{
"_csrf": GetUserCSRFToken(t, sess),
"name": "VAR",
"data": data,
"name": "VAR",
"data": data,
})
sess.MakeRequest(t, req, expectedStatus)
}
doDelete := func(t *testing.T, sess *TestSession, baseURL string, id int64, expectedStatus int) {
req := NewRequestWithValues(t, "POST", fmt.Sprintf("%s/%d/delete", baseURL, id), map[string]string{
"_csrf": GetUserCSRFToken(t, sess),
})
req := NewRequest(t, "POST", fmt.Sprintf("%s/%d/delete", baseURL, id))
sess.MakeRequest(t, req, expectedStatus)
}

View File

@@ -52,9 +52,7 @@ func testSuccessfullEdit(t *testing.T, formData user_model.User) {
func makeRequest(t *testing.T, formData user_model.User, headerCode int) {
session := loginUser(t, "user1")
csrf := GetUserCSRFToken(t, session)
req := NewRequestWithValues(t, "POST", "/-/admin/users/"+strconv.Itoa(int(formData.ID))+"/edit", map[string]string{
"_csrf": csrf,
"user_name": formData.Name,
"login_name": formData.LoginName,
"login_type": "0-0",
@@ -96,10 +94,7 @@ func TestAdminDeleteUser(t *testing.T) {
query = "?purge=true"
}
csrf := GetUserCSRFToken(t, session)
req := NewRequestWithValues(t, "POST", fmt.Sprintf("/-/admin/users/%d/delete%s", entry.userID, query), map[string]string{
"_csrf": csrf,
})
req := NewRequest(t, "POST", fmt.Sprintf("/-/admin/users/%d/delete%s", entry.userID, query))
session.MakeRequest(t, req, http.StatusSeeOther)
assertUserDeleted(t, entry.userID)

View File

@@ -95,9 +95,7 @@ func TestHTTPSigCert(t *testing.T) {
defer tests.PrepareTestEnv(t)()
session := loginUser(t, "user1")
csrf := GetUserCSRFToken(t, session)
req := NewRequestWithValues(t, "POST", "/user/settings/keys", map[string]string{
"_csrf": csrf,
"content": "user1",
"title": "principal",
"type": "principal",

View File

@@ -826,7 +826,6 @@ func TestPackageContainer(t *testing.T) {
newOwnerName := "newUsername"
req := NewRequestWithValues(t, "POST", "/user/settings", map[string]string{
"_csrf": GetUserCSRFToken(t, session),
"name": newOwnerName,
"email": "user2@example.com",
"language": "en-US",
@@ -836,7 +835,6 @@ func TestPackageContainer(t *testing.T) {
t.Run(fmt.Sprintf("Catalog[%s]", newOwnerName), checkCatalog(newOwnerName))
req = NewRequestWithValues(t, "POST", "/user/settings", map[string]string{
"_csrf": GetUserCSRFToken(t, session),
"name": user.Name,
"email": "user2@example.com",
"language": "en-US",

View File

@@ -28,7 +28,6 @@ func TestRepoLanguages(t *testing.T) {
// Save new file to master branch
req = NewRequestWithValues(t, "POST", "/user2/repo1/_new/master/", map[string]string{
"_csrf": doc.GetCSRF(),
"last_commit": lastCommit,
"tree_path": "test.go",
"content": "package main",

View File

@@ -43,7 +43,6 @@ func TestAPIRepoLicense(t *testing.T) {
// Save new file to master branch
req = NewRequestWithValues(t, "POST", "/user2/repo1/_new/master/", map[string]string{
"_csrf": doc.GetCSRF(),
"last_commit": lastCommit,
"tree_path": "LICENSE",
"content": testLicenseContent,

View File

@@ -33,7 +33,7 @@ func testGeneratePngBytes() []byte {
return buff.Bytes()
}
func testCreateIssueAttachment(t *testing.T, session *TestSession, csrf, repoURL, filename string, content []byte, expectedStatus int) string {
func testCreateIssueAttachment(t *testing.T, session *TestSession, repoURL, filename string, content []byte, expectedStatus int) string {
body := &bytes.Buffer{}
// Setup multi-part
@@ -46,7 +46,6 @@ func testCreateIssueAttachment(t *testing.T, session *TestSession, csrf, repoURL
assert.NoError(t, err)
req := NewRequestWithBody(t, "POST", repoURL+"/issues/attachments", body)
req.Header.Add("X-Csrf-Token", csrf)
req.Header.Add("Content-Type", writer.FormDataContentType())
resp := session.MakeRequest(t, req, expectedStatus)
@@ -79,20 +78,20 @@ func testUploadAttachmentDeleteTemp(t *testing.T) {
defer web.RouteMock(route_web.RouterMockPointBeforeWebRoutes, func(resp http.ResponseWriter, req *http.Request) {
tmpFileCountDuringUpload = countTmpFile()
})()
_ = testCreateIssueAttachment(t, session, GetUserCSRFToken(t, session), "user2/repo1", "image.png", testGeneratePngBytes(), http.StatusOK)
_ = testCreateIssueAttachment(t, session, "user2/repo1", "image.png", testGeneratePngBytes(), http.StatusOK)
assert.Equal(t, 1, tmpFileCountDuringUpload, "the temp file should exist when uploaded size exceeds the parse form's max memory")
assert.Equal(t, 0, countTmpFile(), "the temp file should be deleted after upload")
}
func testCreateAnonymousAttachment(t *testing.T) {
session := emptyTestSession(t)
testCreateIssueAttachment(t, session, GetAnonymousCSRFToken(t, session), "user2/repo1", "image.png", testGeneratePngBytes(), http.StatusSeeOther)
testCreateIssueAttachment(t, session, "user2/repo1", "image.png", testGeneratePngBytes(), http.StatusSeeOther)
}
func testCreateUser2IssueAttachment(t *testing.T) {
const repoURL = "user2/repo1"
session := loginUser(t, "user2")
uuid := testCreateIssueAttachment(t, session, GetUserCSRFToken(t, session), repoURL, "image.png", testGeneratePngBytes(), http.StatusOK)
uuid := testCreateIssueAttachment(t, session, repoURL, "image.png", testGeneratePngBytes(), http.StatusOK)
req := NewRequest(t, "GET", repoURL+"/issues/new")
resp := session.MakeRequest(t, req, http.StatusOK)
@@ -102,7 +101,6 @@ func testCreateUser2IssueAttachment(t *testing.T) {
assert.True(t, exists, "The template has changed")
postData := map[string]string{
"_csrf": htmlDoc.GetCSRF(),
"title": "New Issue With Attachment",
"content": "some content",
"files": uuid,

View File

@@ -125,7 +125,7 @@ type ldapAuthOptions struct {
groupTeamMapRemoval string
}
func (te *ldapTestEnv) buildAuthSourcePayload(csrf string, opts ...ldapAuthOptions) map[string]string {
func (te *ldapTestEnv) buildAuthSourcePayload(opts ...ldapAuthOptions) map[string]string {
opt := util.OptionalArg(opts)
// Modify user filter to test group filter explicitly
userFilter := "(&(objectClass=inetOrgPerson)(memberOf=cn=git,ou=people,dc=planetexpress,dc=com)(uid=%s))"
@@ -134,7 +134,6 @@ func (te *ldapTestEnv) buildAuthSourcePayload(csrf string, opts ...ldapAuthOptio
}
return map[string]string{
"_csrf": csrf,
"type": "2",
"name": "ldap",
"host": te.serverHost,
@@ -164,8 +163,7 @@ func (te *ldapTestEnv) buildAuthSourcePayload(csrf string, opts ...ldapAuthOptio
func (te *ldapTestEnv) addAuthSource(t *testing.T, opts ...ldapAuthOptions) {
session := loginUser(t, "user1")
csrf := GetUserCSRFToken(t, session)
req := NewRequestWithValues(t, "POST", "/-/admin/auths/new", te.buildAuthSourcePayload(csrf, opts...))
req := NewRequestWithValues(t, "POST", "/-/admin/auths/new", te.buildAuthSourcePayload(opts...))
session.MakeRequest(t, req, http.StatusSeeOther)
}
@@ -212,13 +210,12 @@ func TestLDAPAuthChange(t *testing.T) {
req = NewRequest(t, "GET", href)
resp = session.MakeRequest(t, req, http.StatusOK)
doc = NewHTMLParser(t, resp.Body)
csrf := doc.GetCSRF()
host, _ := doc.Find(`input[name="host"]`).Attr("value")
assert.Equal(t, te.serverHost, host)
binddn, _ := doc.Find(`input[name="bind_dn"]`).Attr("value")
assert.Equal(t, "uid=gitea,ou=service,dc=planetexpress,dc=com", binddn)
req = NewRequestWithValues(t, "POST", href, te.buildAuthSourcePayload(csrf, ldapAuthOptions{groupTeamMapRemoval: "off"}))
req = NewRequestWithValues(t, "POST", href, te.buildAuthSourcePayload(ldapAuthOptions{groupTeamMapRemoval: "off"}))
session.MakeRequest(t, req, http.StatusSeeOther)
req = NewRequest(t, "GET", href)
@@ -267,8 +264,7 @@ func TestLDAPUserSyncWithEmptyUsernameAttribute(t *testing.T) {
defer tests.PrepareTestEnv(t)()
session := loginUser(t, "user1")
csrf := GetUserCSRFToken(t, session)
payload := te.buildAuthSourcePayload(csrf)
payload := te.buildAuthSourcePayload()
payload["attribute_username"] = ""
req := NewRequestWithValues(t, "POST", "/-/admin/auths/new", payload)
session.MakeRequest(t, req, http.StatusSeeOther)
@@ -285,7 +281,6 @@ func TestLDAPUserSyncWithEmptyUsernameAttribute(t *testing.T) {
for _, u := range te.gitLDAPUsers {
req := NewRequestWithValues(t, "POST", "/user/login", map[string]string{
"_csrf": csrf,
"user_name": u.UserName,
"password": u.Password,
})
@@ -512,8 +507,7 @@ func TestLDAPPreventInvalidGroupTeamMap(t *testing.T) {
defer tests.PrepareTestEnv(t)()
session := loginUser(t, "user1")
csrf := GetUserCSRFToken(t, session)
payload := te.buildAuthSourcePayload(csrf, ldapAuthOptions{groupTeamMap: `{"NOT_A_VALID_JSON"["MISSING_DOUBLE_POINT"]}`, groupTeamMapRemoval: "off"})
payload := te.buildAuthSourcePayload(ldapAuthOptions{groupTeamMap: `{"NOT_A_VALID_JSON"["MISSING_DOUBLE_POINT"]}`, groupTeamMapRemoval: "off"})
req := NewRequestWithValues(t, "POST", "/-/admin/auths/new", payload)
session.MakeRequest(t, req, http.StatusOK) // StatusOK = failed, StatusSeeOther = ok
}

View File

@@ -61,9 +61,7 @@ func branchAction(t *testing.T, button string) (*HTMLDoc, string) {
t.Skip()
}
req = NewRequestWithValues(t, "POST", link, map[string]string{
"_csrf": htmlDoc.GetCSRF(),
})
req = NewRequest(t, "POST", link)
session.MakeRequest(t, req, http.StatusOK)
url, err := url.Parse(link)

View File

@@ -26,17 +26,13 @@ func TestChangeDefaultBranch(t *testing.T) {
session := loginUser(t, owner.Name)
branchesURL := fmt.Sprintf("/%s/%s/settings/branches", owner.Name, repo.Name)
csrf := GetUserCSRFToken(t, session)
req := NewRequestWithValues(t, "POST", branchesURL, map[string]string{
"_csrf": csrf,
"action": "default_branch",
"branch": "DefaultBranch",
})
session.MakeRequest(t, req, http.StatusSeeOther)
csrf = GetUserCSRFToken(t, session)
req = NewRequestWithValues(t, "POST", branchesURL, map[string]string{
"_csrf": csrf,
"action": "default_branch",
"branch": "does_not_exist",
})
@@ -110,9 +106,7 @@ func TestChangeDefaultBranchDivergence(t *testing.T) {
// switch default branch
newDefaultBranch := "good-sign-not-yet-validated"
csrf := GetUserCSRFToken(t, session)
req := NewRequestWithValues(t, "POST", settingsBranchesURL, map[string]string{
"_csrf": csrf,
"action": "default_branch",
"branch": newDefaultBranch,
})

View File

@@ -97,9 +97,7 @@ func TestSessionFileCreation(t *testing.T) {
// We're not logged in so there should be no session
assert.False(t, sessionFileExist(t, tmpDir, sessionID))
doc := NewHTMLParser(t, resp.Body)
req = NewRequestWithValues(t, "POST", "/user/login", map[string]string{
"_csrf": doc.GetCSRF(),
"user_name": "user2",
"password": userPassword,
})

View File

@@ -1,34 +0,0 @@
// Copyright 2017 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT
package integration
import (
"net/http"
"testing"
"code.gitea.io/gitea/models/unittest"
user_model "code.gitea.io/gitea/models/user"
"code.gitea.io/gitea/tests"
"github.com/stretchr/testify/assert"
)
func TestCsrfProtection(t *testing.T) {
defer tests.PrepareTestEnv(t)()
// test web form csrf via form
user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2})
session := loginUser(t, user.Name)
req := NewRequestWithValues(t, "POST", "/user/settings", map[string]string{
"_csrf": "fake_csrf",
})
resp := session.MakeRequest(t, req, http.StatusBadRequest)
assert.Contains(t, resp.Body.String(), "Invalid CSRF token")
// test web form csrf via header. TODO: should use an UI api to test
req = NewRequest(t, "POST", "/user/settings")
req.Header.Add("X-Csrf-Token", "fake_csrf")
resp = session.MakeRequest(t, req, http.StatusBadRequest)
assert.Contains(t, resp.Body.String(), "Invalid CSRF token")
}

View File

@@ -32,11 +32,8 @@ func TestUserDeleteAccount(t *testing.T) {
defer tests.PrepareTestEnv(t)()
session := loginUser(t, "user8")
csrf := GetUserCSRFToken(t, session)
urlStr := "/user/settings/account/delete?password=" + userPassword
req := NewRequestWithValues(t, "POST", urlStr, map[string]string{
"_csrf": csrf,
})
req := NewRequest(t, "POST", urlStr)
session.MakeRequest(t, req, http.StatusSeeOther)
assertUserDeleted(t, 8)
@@ -47,11 +44,8 @@ func TestUserDeleteAccountStillOwnRepos(t *testing.T) {
defer tests.PrepareTestEnv(t)()
session := loginUser(t, "user2")
csrf := GetUserCSRFToken(t, session)
urlStr := "/user/settings/account/delete?password=" + userPassword
req := NewRequestWithValues(t, "POST", urlStr, map[string]string{
"_csrf": csrf,
})
req := NewRequest(t, "POST", urlStr)
session.MakeRequest(t, req, http.StatusSeeOther)
// user should not have been deleted, because the user still owns repos

View File

@@ -87,7 +87,6 @@ func testEditorProtectedBranch(t *testing.T) {
session := loginUser(t, "user2")
// Change the "master" branch to "protected"
req := NewRequestWithValues(t, "POST", "/user2/repo1/settings/branches/edit", map[string]string{
"_csrf": GetUserCSRFToken(t, session),
"rule_name": "master",
"enable_push": "true",
})
@@ -106,7 +105,6 @@ func testEditorActionPostRequest(t *testing.T, session *TestSession, requestPath
resp := session.MakeRequest(t, req, http.StatusOK)
htmlDoc := NewHTMLParser(t, resp.Body)
form := map[string]string{
"_csrf": htmlDoc.GetCSRF(),
"last_commit": htmlDoc.GetInputValueByName("last_commit"),
}
maps.Copy(form, params)
@@ -150,7 +148,6 @@ func testEditFileToNewBranch(t *testing.T, session *TestSession, user, repo, bra
func testEditorDiffPreview(t *testing.T) {
session := loginUser(t, "user2")
req := NewRequestWithValues(t, "POST", "/user2/repo1/_preview/master/README.md", map[string]string{
"_csrf": GetUserCSRFToken(t, session),
"content": "Hello, World (Edited)\n",
})
resp := session.MakeRequest(t, req, http.StatusOK)
@@ -200,7 +197,6 @@ func testEditorWebGitCommitEmail(t *testing.T) {
makeReq := func(t *testing.T, link string, params map[string]string, expectedUserName, expectedEmail string) *httptest.ResponseRecorder {
lastCommit := getLastCommit(t)
params["_csrf"] = GetUserCSRFToken(t, session)
params["last_commit"] = lastCommit.ID.String()
params["commit_choice"] = "direct"
req := NewRequestWithValues(t, "POST", link, params)
@@ -225,7 +221,6 @@ func testEditorWebGitCommitEmail(t *testing.T) {
uploadForm := multipart.NewWriter(body)
file, _ := uploadForm.CreateFormFile("file", name)
_, _ = io.Copy(file, strings.NewReader(content))
_ = uploadForm.WriteField("_csrf", GetUserCSRFToken(t, session))
_ = uploadForm.Close()
req := NewRequestWithBody(t, "POST", "/user2/repo1/upload-file", body)
@@ -347,7 +342,7 @@ func testForkToEditFile(t *testing.T, session *TestSession, user, owner, repo, b
assert.Contains(t, resp.Body.String(), "Fork Repository to Propose Changes")
// fork the repository
req = NewRequestWithValues(t, "POST", path.Join(owner, repo, "_fork", branch), map[string]string{"_csrf": GetUserCSRFToken(t, session)})
req = NewRequest(t, "POST", path.Join(owner, repo, "_fork", branch))
resp = session.MakeRequest(t, req, http.StatusOK)
assert.JSONEq(t, `{"redirect":""}`, resp.Body.String())
}
@@ -359,7 +354,6 @@ func testForkToEditFile(t *testing.T, session *TestSession, user, owner, repo, b
// Archive the repository
req := NewRequestWithValues(t, "POST", path.Join(user, repo, "settings"),
map[string]string{
"_csrf": GetUserCSRFToken(t, session),
"repo_name": repo,
"action": "archive",
},
@@ -374,7 +368,6 @@ func testForkToEditFile(t *testing.T, session *TestSession, user, owner, repo, b
// Unfork the repository
req = NewRequestWithValues(t, "POST", path.Join(user, repo, "settings"),
map[string]string{
"_csrf": GetUserCSRFToken(t, session),
"repo_name": repo,
"action": "convert_fork",
},
@@ -410,7 +403,6 @@ func testForkToEditFile(t *testing.T, session *TestSession, user, owner, repo, b
resp := session.MakeRequest(t, req, http.StatusOK)
htmlDoc := NewHTMLParser(t, resp.Body)
editRequestForm := map[string]string{
"_csrf": GetUserCSRFToken(t, session),
"last_commit": htmlDoc.GetInputValueByName("last_commit"),
"tree_path": filePath,
"content": "new content in fork",

View File

@@ -32,7 +32,6 @@ import (
func testAPINewFile(t *testing.T, session *TestSession, user, repo, branch, treePath, content string) {
url := fmt.Sprintf("/%s/%s/_new/%s", user, repo, branch)
req := NewRequestWithValues(t, "POST", url, map[string]string{
"_csrf": GetUserCSRFToken(t, session),
"commit_choice": "direct",
"tree_path": treePath,
"content": content,
@@ -86,7 +85,6 @@ func TestEmptyRepoAddFile(t *testing.T) {
doc := NewHTMLParser(t, resp.Body).Find(`input[name="commit_choice"]`)
assert.Empty(t, doc.AttrOr("checked", "_no_"))
req = NewRequestWithValues(t, "POST", "/user30/empty/_new/"+setting.Repository.DefaultBranch, map[string]string{
"_csrf": GetUserCSRFToken(t, session),
"commit_choice": "direct",
"tree_path": "test-file.md",
"content": "newly-added-test-file",
@@ -142,7 +140,6 @@ func TestEmptyRepoUploadFile(t *testing.T) {
body := &bytes.Buffer{}
mpForm := multipart.NewWriter(body)
_ = mpForm.WriteField("_csrf", GetUserCSRFToken(t, session))
file, _ := mpForm.CreateFormFile("file", "uploaded-file.txt")
_, _ = io.Copy(file, strings.NewReader("newly-uploaded-test-file"))
_ = mpForm.Close()
@@ -154,7 +151,6 @@ func TestEmptyRepoUploadFile(t *testing.T) {
assert.NoError(t, json.Unmarshal(resp.Body.Bytes(), &respMap))
req = NewRequestWithValues(t, "POST", "/user30/empty/_upload/"+setting.Repository.DefaultBranch, map[string]string{
"_csrf": GetUserCSRFToken(t, session),
"commit_choice": "direct",
"files": respMap["uuid"],
"tree_path": "",

View File

@@ -507,10 +507,7 @@ type doProtectBranchOptions struct {
func doProtectBranchExt(ctx APITestContext, ruleName string, opts doProtectBranchOptions) func(t *testing.T) {
// We are going to just use the owner to set the protection.
return func(t *testing.T) {
csrf := GetUserCSRFToken(t, ctx.Session)
formData := map[string]string{
"_csrf": csrf,
"rule_name": ruleName,
"unprotected_file_patterns": opts.UnprotectedFilePatterns,
"protected_file_patterns": opts.ProtectedFilePatterns,
@@ -694,11 +691,7 @@ func doPushCreate(ctx APITestContext, u *url.URL) func(t *testing.T) {
func doBranchDelete(ctx APITestContext, owner, repo, branch string) func(*testing.T) {
return func(t *testing.T) {
csrf := GetUserCSRFToken(t, ctx.Session)
req := NewRequestWithValues(t, "POST", fmt.Sprintf("/%s/%s/branches/delete?name=%s", url.PathEscape(owner), url.PathEscape(repo), url.QueryEscape(branch)), map[string]string{
"_csrf": csrf,
})
req := NewRequest(t, "POST", fmt.Sprintf("/%s/%s/branches/delete?name=%s", url.PathEscape(owner), url.PathEscape(repo), url.QueryEscape(branch)))
ctx.Session.MakeRequest(t, req, http.StatusOK)
}
}

View File

@@ -37,11 +37,6 @@ func (doc *HTMLDoc) Find(selector string) *goquery.Selection {
return doc.doc.Find(selector)
}
// GetCSRF for getting CSRF token value from input
func (doc *HTMLDoc) GetCSRF() string {
return doc.GetInputValueByName("_csrf")
}
// AssertHTMLElement check if the element by selector exists or does not exist depending on checkExists
func AssertHTMLElement[T int | bool](t testing.TB, doc *HTMLDoc, selector string, checkExists T) {
sel := doc.doc.Find(selector)

View File

@@ -225,16 +225,11 @@ func loginUser(t testing.TB, userName string) *TestSession {
func loginUserWithPassword(t testing.TB, userName, password string) *TestSession {
t.Helper()
req := NewRequest(t, "GET", "/user/login")
resp := MakeRequest(t, req, http.StatusOK)
doc := NewHTMLParser(t, resp.Body)
req = NewRequestWithValues(t, "POST", "/user/login", map[string]string{
"_csrf": doc.GetCSRF(),
req := NewRequestWithValues(t, "POST", "/user/login", map[string]string{
"user_name": userName,
"password": password,
})
resp = MakeRequest(t, req, http.StatusSeeOther)
resp := MakeRequest(t, req, http.StatusSeeOther)
ch := http.Header{}
ch.Add("Cookie", strings.Join(resp.Header()["Set-Cookie"], ";"))
@@ -256,7 +251,6 @@ var tokenCounter int64
func getTokenForLoggedInUser(t testing.TB, session *TestSession, scopes ...auth.AccessTokenScope) string {
t.Helper()
urlValues := url.Values{}
urlValues.Add("_csrf", GetUserCSRFToken(t, session))
urlValues.Add("name", fmt.Sprintf("api-testing-token-%d", atomic.AddInt64(&tokenCounter, 1)))
for _, scope := range scopes {
urlValues.Add("scope-dummy", string(scope)) // it only needs to start with "scope-" to be accepted
@@ -436,20 +430,3 @@ func VerifyJSONSchema(t testing.TB, resp *httptest.ResponseRecorder, schemaFile
assert.Empty(t, result.Errors())
assert.True(t, result.Valid())
}
// GetUserCSRFToken returns CSRF token for current user
func GetUserCSRFToken(t testing.TB, session *TestSession) string {
t.Helper()
cookie := session.GetSiteCookie("_csrf")
require.NotEmpty(t, cookie)
return cookie
}
// GetUserCSRFToken returns CSRF token for anonymous user (not logged in)
func GetAnonymousCSRFToken(t testing.TB, session *TestSession) string {
t.Helper()
resp := session.MakeRequest(t, NewRequest(t, "GET", "/user/login"), http.StatusOK)
csrfToken := NewHTMLParser(t, resp.Body).GetCSRF()
require.NotEmpty(t, csrfToken)
return csrfToken
}

View File

@@ -130,7 +130,6 @@ func testNewIssue(t *testing.T, session *TestSession, user, repo, title, content
link, exists := htmlDoc.doc.Find("form.ui.form").Attr("action")
assert.True(t, exists, "The template has changed")
req = NewRequestWithValues(t, "POST", link, map[string]string{
"_csrf": htmlDoc.GetCSRF(),
"title": title,
"content": content,
})
@@ -150,15 +149,12 @@ func testNewIssue(t *testing.T, session *TestSession, user, repo, title, content
}
func testIssueDelete(t *testing.T, session *TestSession, issueURL string) {
req := NewRequestWithValues(t, "POST", path.Join(issueURL, "delete"), map[string]string{
"_csrf": GetUserCSRFToken(t, session),
})
req := NewRequest(t, "POST", path.Join(issueURL, "delete"))
session.MakeRequest(t, req, http.StatusSeeOther)
}
func testIssueAssign(t *testing.T, session *TestSession, repoLink string, issueID, assigneeID int64) {
req := NewRequestWithValues(t, "POST", fmt.Sprintf(repoLink+"/issues/assignee?issue_ids=%d", issueID), map[string]string{
"_csrf": GetUserCSRFToken(t, session),
"id": strconv.FormatInt(assigneeID, 10),
"action": "", // empty action means assign
})
@@ -176,7 +172,6 @@ func testIssueAddComment(t *testing.T, session *TestSession, issueURL, content,
commentCount := htmlDoc.doc.Find(".comment-list .comment .render-content").Length()
req = NewRequestWithValues(t, "POST", link, map[string]string{
"_csrf": htmlDoc.GetCSRF(),
"content": content,
"status": status,
})
@@ -200,8 +195,7 @@ func testIssueAddComment(t *testing.T, session *TestSession, issueURL, content,
func testIssueChangeMilestone(t *testing.T, session *TestSession, repoLink string, issueID, milestoneID int64) {
req := NewRequestWithValues(t, "POST", fmt.Sprintf(repoLink+"/issues/milestone?issue_ids=%d", issueID), map[string]string{
"_csrf": GetUserCSRFToken(t, session),
"id": strconv.FormatInt(milestoneID, 10),
"id": strconv.FormatInt(milestoneID, 10),
})
resp := session.MakeRequest(t, req, http.StatusOK)
assert.Equal(t, `{"ok":true}`, strings.TrimSpace(resp.Body.String()))
@@ -219,21 +213,18 @@ func TestEditIssue(t *testing.T) {
issueURL := testNewIssue(t, session, "user2", "repo1", "Title", "Description")
req := NewRequestWithValues(t, "POST", issueURL+"/content", map[string]string{
"_csrf": GetUserCSRFToken(t, session),
"content": "modified content",
"context": fmt.Sprintf("/%s/%s", "user2", "repo1"),
})
session.MakeRequest(t, req, http.StatusOK)
req = NewRequestWithValues(t, "POST", issueURL+"/content", map[string]string{
"_csrf": GetUserCSRFToken(t, session),
"content": "modified content",
"context": fmt.Sprintf("/%s/%s", "user2", "repo1"),
})
session.MakeRequest(t, req, http.StatusBadRequest)
req = NewRequestWithValues(t, "POST", issueURL+"/content", map[string]string{
"_csrf": GetUserCSRFToken(t, session),
"content": "modified content",
"content_version": "1",
"context": fmt.Sprintf("/%s/%s", "user2", "repo1"),
@@ -267,13 +258,9 @@ func TestIssueCommentDelete(t *testing.T) {
assert.Equal(t, comment1, comment.Content)
// Using the ID of a comment that does not belong to the repository must fail
req := NewRequestWithValues(t, "POST", fmt.Sprintf("/%s/%s/comments/%d/delete", "user5", "repo4", commentID), map[string]string{
"_csrf": GetUserCSRFToken(t, session),
})
req := NewRequest(t, "POST", fmt.Sprintf("/%s/%s/comments/%d/delete", "user5", "repo4", commentID))
session.MakeRequest(t, req, http.StatusNotFound)
req = NewRequestWithValues(t, "POST", fmt.Sprintf("/%s/%s/comments/%d/delete", "user2", "repo1", commentID), map[string]string{
"_csrf": GetUserCSRFToken(t, session),
})
req = NewRequest(t, "POST", fmt.Sprintf("/%s/%s/comments/%d/delete", "user2", "repo1", commentID))
session.MakeRequest(t, req, http.StatusOK)
unittest.AssertNotExistsBean(t, &issues_model.Comment{ID: commentID})
}
@@ -292,13 +279,11 @@ func TestIssueCommentUpdate(t *testing.T) {
// Using the ID of a comment that does not belong to the repository must fail
req := NewRequestWithValues(t, "POST", fmt.Sprintf("/%s/%s/comments/%d", "user5", "repo4", commentID), map[string]string{
"_csrf": GetUserCSRFToken(t, session),
"content": modifiedContent,
})
session.MakeRequest(t, req, http.StatusNotFound)
req = NewRequestWithValues(t, "POST", fmt.Sprintf("/%s/%s/comments/%d", "user2", "repo1", commentID), map[string]string{
"_csrf": GetUserCSRFToken(t, session),
"content": modifiedContent,
})
session.MakeRequest(t, req, http.StatusOK)
@@ -320,7 +305,6 @@ func TestIssueCommentUpdateSimultaneously(t *testing.T) {
modifiedContent := comment.Content + "MODIFIED"
req := NewRequestWithValues(t, "POST", fmt.Sprintf("/%s/%s/comments/%d", "user2", "repo1", commentID), map[string]string{
"_csrf": GetUserCSRFToken(t, session),
"content": modifiedContent,
})
session.MakeRequest(t, req, http.StatusOK)
@@ -328,13 +312,11 @@ func TestIssueCommentUpdateSimultaneously(t *testing.T) {
modifiedContent = comment.Content + "2"
req = NewRequestWithValues(t, "POST", fmt.Sprintf("/%s/%s/comments/%d", "user2", "repo1", commentID), map[string]string{
"_csrf": GetUserCSRFToken(t, session),
"content": modifiedContent,
})
session.MakeRequest(t, req, http.StatusBadRequest)
req = NewRequestWithValues(t, "POST", fmt.Sprintf("/%s/%s/comments/%d", "user2", "repo1", commentID), map[string]string{
"_csrf": GetUserCSRFToken(t, session),
"content": modifiedContent,
"content_version": "1",
})
@@ -350,22 +332,15 @@ func TestIssueReaction(t *testing.T) {
session := loginUser(t, "user2")
issueURL := testNewIssue(t, session, "user2", "repo1", "Title", "Description")
req := NewRequest(t, "GET", issueURL)
resp := session.MakeRequest(t, req, http.StatusOK)
htmlDoc := NewHTMLParser(t, resp.Body)
req = NewRequestWithValues(t, "POST", path.Join(issueURL, "/reactions/react"), map[string]string{
"_csrf": htmlDoc.GetCSRF(),
req := NewRequestWithValues(t, "POST", path.Join(issueURL, "/reactions/react"), map[string]string{
"content": "8ball",
})
session.MakeRequest(t, req, http.StatusInternalServerError)
req = NewRequestWithValues(t, "POST", path.Join(issueURL, "/reactions/react"), map[string]string{
"_csrf": htmlDoc.GetCSRF(),
"content": "eyes",
})
session.MakeRequest(t, req, http.StatusOK)
req = NewRequestWithValues(t, "POST", path.Join(issueURL, "/reactions/unreact"), map[string]string{
"_csrf": htmlDoc.GetCSRF(),
"content": "eyes",
})
session.MakeRequest(t, req, http.StatusOK)
@@ -459,14 +434,8 @@ func testIssueWithBean(t *testing.T, user string, repoID int64, title, content s
func testIssueChangeInfo(t *testing.T, user, issueURL, info, value string) {
session := loginUser(t, user)
req := NewRequest(t, "GET", issueURL)
resp := session.MakeRequest(t, req, http.StatusOK)
htmlDoc := NewHTMLParser(t, resp.Body)
req = NewRequestWithValues(t, "POST", path.Join(issueURL, info), map[string]string{
"_csrf": htmlDoc.GetCSRF(),
info: value,
req := NewRequestWithValues(t, "POST", path.Join(issueURL, info), map[string]string{
info: value,
})
_ = session.MakeRequest(t, req, http.StatusOK)
}
@@ -700,7 +669,7 @@ func TestUpdateIssueDeadline(t *testing.T) {
assert.Equal(t, api.StateOpen, issueBefore.State())
session := loginUser(t, owner.Name)
urlStr := fmt.Sprintf("%s/%s/issues/%d/deadline?_csrf=%s", owner.Name, repoBefore.Name, issueBefore.Index, GetUserCSRFToken(t, session))
urlStr := fmt.Sprintf("%s/%s/issues/%d/deadline", owner.Name, repoBefore.Name, issueBefore.Index)
req := NewRequestWithValues(t, "POST", urlStr, map[string]string{"deadline": "2022-04-06"})
session.MakeRequest(t, req, http.StatusOK)

View File

@@ -95,7 +95,6 @@ func TestMigrateGiteaForm(t *testing.T) {
// Step 4: submit the migration to only migrate issues
migratedRepoName := "otherrepo"
req = NewRequestWithValues(t, "POST", link, map[string]string{
"_csrf": htmlDoc.GetCSRF(),
"service": fmt.Sprintf("%d", structs.GiteaService),
"clone_addr": fmt.Sprintf("%s%s/%s", u, ownerName, repoName),
"auth_token": token,

View File

@@ -79,7 +79,6 @@ func testMirrorPush(t *testing.T, u *url.URL) {
func testCreatePushMirror(t *testing.T, session *TestSession, owner, repo, address, username, password, interval string) {
req := NewRequestWithValues(t, "POST", fmt.Sprintf("/%s/%s/settings", url.PathEscape(owner), url.PathEscape(repo)), map[string]string{
"_csrf": GetUserCSRFToken(t, session),
"action": "push-mirror-add",
"push_mirror_address": address,
"push_mirror_username": username,
@@ -94,7 +93,6 @@ func testCreatePushMirror(t *testing.T, session *TestSession, owner, repo, addre
func doRemovePushMirror(t *testing.T, session *TestSession, owner, repo string, pushMirrorID int64) bool {
req := NewRequestWithValues(t, "POST", fmt.Sprintf("/%s/%s/settings", url.PathEscape(owner), url.PathEscape(repo)), map[string]string{
"_csrf": GetUserCSRFToken(t, session),
"action": "push-mirror-remove",
"push_mirror_id": strconv.FormatInt(pushMirrorID, 10),
})
@@ -105,7 +103,6 @@ func doRemovePushMirror(t *testing.T, session *TestSession, owner, repo string,
func doUpdatePushMirror(t *testing.T, session *TestSession, owner, repo string, pushMirrorID int64, interval string) bool {
req := NewRequestWithValues(t, "POST", fmt.Sprintf("/%s/%s/settings", owner, repo), map[string]string{
"_csrf": GetUserCSRFToken(t, session),
"action": "push-mirror-update",
"push_mirror_id": strconv.FormatInt(pushMirrorID, 10),
"push_mirror_interval": interval,

View File

@@ -17,9 +17,7 @@ import (
func setDefaultBranch(t *testing.T, session *TestSession, user, repo, branch string) {
location := path.Join("/", user, repo, "settings/branches")
csrf := GetUserCSRFToken(t, session)
req := NewRequestWithValues(t, "POST", location, map[string]string{
"_csrf": csrf,
"action": "default_branch",
"branch": branch,
})

View File

@@ -92,7 +92,6 @@ func TestAuthorizeShow(t *testing.T) {
htmlDoc := NewHTMLParser(t, resp.Body)
AssertHTMLElement(t, htmlDoc, "#authorize-app", true)
htmlDoc.GetCSRF()
}
func TestAuthorizeRedirectWithExistingGrant(t *testing.T) {

View File

@@ -34,7 +34,6 @@ func TestOrgProjectAccess(t *testing.T) {
// change the org's visibility to private
session := loginUser(t, "user2")
req = NewRequestWithValues(t, "POST", "/org/org3/settings", map[string]string{
"_csrf": GetUserCSRFToken(t, session),
"name": "org3",
"visibility": "2",
})
@@ -48,7 +47,6 @@ func TestOrgProjectAccess(t *testing.T) {
// disable team1's project unit
session = loginUser(t, "user2")
req = NewRequestWithValues(t, "POST", "/org/org3/teams/team1/edit", map[string]string{
"_csrf": GetUserCSRFToken(t, session),
"team_name": "team1",
"repo_access": "specific",
"permission": "read",

View File

@@ -39,9 +39,7 @@ func TestOrgTeamEmailInvite(t *testing.T) {
session := loginUser(t, "user1")
teamURL := fmt.Sprintf("/org/%s/teams/%s", org.Name, team.Name)
csrf := GetUserCSRFToken(t, session)
req := NewRequestWithValues(t, "POST", teamURL+"/action/add", map[string]string{
"_csrf": csrf,
"uid": "1",
"uname": user.Email,
})
@@ -58,10 +56,7 @@ func TestOrgTeamEmailInvite(t *testing.T) {
// join the team
inviteURL := "/org/invite/" + invites[0].Token
csrf = GetUserCSRFToken(t, session)
req = NewRequestWithValues(t, "POST", inviteURL, map[string]string{
"_csrf": csrf,
})
req = NewRequest(t, "POST", inviteURL)
resp = session.MakeRequest(t, req, http.StatusSeeOther)
req = NewRequest(t, "GET", test.RedirectURL(resp))
session.MakeRequest(t, req, http.StatusOK)
@@ -93,7 +88,6 @@ func TestOrgTeamEmailInviteRedirectsExistingUser(t *testing.T) {
teamURL := fmt.Sprintf("/org/%s/teams/%s", org.Name, team.Name)
req := NewRequestWithValues(t, "POST", teamURL+"/action/add", map[string]string{
"_csrf": GetUserCSRFToken(t, session),
"uid": "1",
"uname": user.Email,
})
@@ -111,9 +105,7 @@ func TestOrgTeamEmailInviteRedirectsExistingUser(t *testing.T) {
req = NewRequest(t, "GET", "/user/login?redirect_to="+url.QueryEscape(inviteURL))
resp = MakeRequest(t, req, http.StatusOK)
doc := NewHTMLParser(t, resp.Body)
req = NewRequestWithValues(t, "POST", "/user/login", map[string]string{
"_csrf": doc.GetCSRF(),
"user_name": "user5",
"password": "password",
})
@@ -135,9 +127,7 @@ func TestOrgTeamEmailInviteRedirectsExistingUser(t *testing.T) {
session.jar.SetCookies(baseURL, cr.Cookies())
// make the request
req = NewRequestWithValues(t, "POST", test.RedirectURL(resp), map[string]string{
"_csrf": GetUserCSRFToken(t, session),
})
req = NewRequest(t, "POST", test.RedirectURL(resp))
resp = session.MakeRequest(t, req, http.StatusSeeOther)
req = NewRequest(t, "GET", test.RedirectURL(resp))
session.MakeRequest(t, req, http.StatusOK)
@@ -164,7 +154,6 @@ func TestOrgTeamEmailInviteRedirectsNewUser(t *testing.T) {
teamURL := fmt.Sprintf("/org/%s/teams/%s", org.Name, team.Name)
req := NewRequestWithValues(t, "POST", teamURL+"/action/add", map[string]string{
"_csrf": GetUserCSRFToken(t, session),
"uid": "1",
"uname": "doesnotexist@example.com",
})
@@ -182,9 +171,7 @@ func TestOrgTeamEmailInviteRedirectsNewUser(t *testing.T) {
req = NewRequest(t, "GET", "/user/sign_up?redirect_to="+url.QueryEscape(inviteURL))
resp = MakeRequest(t, req, http.StatusOK)
doc := NewHTMLParser(t, resp.Body)
req = NewRequestWithValues(t, "POST", "/user/sign_up", map[string]string{
"_csrf": doc.GetCSRF(),
"user_name": "doesnotexist",
"email": "doesnotexist@example.com",
"password": "examplePassword!1",
@@ -208,9 +195,7 @@ func TestOrgTeamEmailInviteRedirectsNewUser(t *testing.T) {
session.jar.SetCookies(baseURL, cr.Cookies())
// make the redirected request
req = NewRequestWithValues(t, "POST", test.RedirectURL(resp), map[string]string{
"_csrf": GetUserCSRFToken(t, session),
})
req = NewRequest(t, "POST", test.RedirectURL(resp))
resp = session.MakeRequest(t, req, http.StatusSeeOther)
req = NewRequest(t, "GET", test.RedirectURL(resp))
session.MakeRequest(t, req, http.StatusOK)
@@ -243,7 +228,6 @@ func TestOrgTeamEmailInviteRedirectsNewUserWithActivation(t *testing.T) {
teamURL := fmt.Sprintf("/org/%s/teams/%s", org.Name, team.Name)
req := NewRequestWithValues(t, "POST", teamURL+"/action/add", map[string]string{
"_csrf": GetUserCSRFToken(t, session),
"uid": "1",
"uname": "doesnotexist@example.com",
})
@@ -283,9 +267,7 @@ func TestOrgTeamEmailInviteRedirectsNewUserWithActivation(t *testing.T) {
// should be redirected to accept the invite
assert.Equal(t, inviteURL, test.RedirectURL(resp))
req = NewRequestWithValues(t, "POST", test.RedirectURL(resp), map[string]string{
"_csrf": GetUserCSRFToken(t, session),
})
req = NewRequest(t, "POST", test.RedirectURL(resp))
resp = session.MakeRequest(t, req, http.StatusSeeOther)
req = NewRequest(t, "GET", test.RedirectURL(resp))
session.MakeRequest(t, req, http.StatusOK)
@@ -319,7 +301,6 @@ func TestOrgTeamEmailInviteRedirectsExistingUserWithLogin(t *testing.T) {
teamURL := fmt.Sprintf("/org/%s/teams/%s", org.Name, team.Name)
req := NewRequestWithValues(t, "POST", teamURL+"/action/add", map[string]string{
"_csrf": GetUserCSRFToken(t, session),
"uid": "1",
"uname": user.Email,
})
@@ -342,9 +323,7 @@ func TestOrgTeamEmailInviteRedirectsExistingUserWithLogin(t *testing.T) {
assert.Equal(t, inviteURL, test.RedirectURL(resp))
// make the request
req = NewRequestWithValues(t, "POST", test.RedirectURL(resp), map[string]string{
"_csrf": GetUserCSRFToken(t, session),
})
req = NewRequest(t, "POST", test.RedirectURL(resp))
resp = session.MakeRequest(t, req, http.StatusSeeOther)
req = NewRequest(t, "GET", test.RedirectURL(resp))
session.MakeRequest(t, req, http.StatusOK)

View File

@@ -48,7 +48,6 @@ func testPrivateActivityDoSomethingForActionEntries(t *testing.T) {
func testPrivateActivityHelperEnablePrivateActivity(t *testing.T) {
session := loginUser(t, privateActivityTestUser)
req := NewRequestWithValues(t, "POST", "/user/settings", map[string]string{
"_csrf": GetUserCSRFToken(t, session),
"name": privateActivityTestUser,
"email": privateActivityTestUser + "@example.com",
"language": "en-US",

View File

@@ -63,10 +63,9 @@ func TestMoveRepoProjectColumns(t *testing.T) {
sess := loginUser(t, "user1")
req := NewRequest(t, "GET", fmt.Sprintf("/%s/projects/%d", repo2.FullName(), project1.ID))
resp := sess.MakeRequest(t, req, http.StatusOK)
htmlDoc := NewHTMLParser(t, resp.Body)
sess.MakeRequest(t, req, http.StatusOK)
req = NewRequestWithJSON(t, "POST", fmt.Sprintf("/%s/projects/%d/move?_csrf="+htmlDoc.GetCSRF(), repo2.FullName(), project1.ID), map[string]any{
req = NewRequestWithJSON(t, "POST", fmt.Sprintf("/%s/projects/%d/move", repo2.FullName(), project1.ID), map[string]any{
"columns": []map[string]any{
{"columnID": columns[1].ID, "sorting": 0},
{"columnID": columns[2].ID, "sorting": 1},

View File

@@ -89,7 +89,6 @@ func testPullCommentRetarget(t *testing.T, u *url.URL, session *TestSession) {
// do retarget
req := NewRequestWithValues(t, "POST", fmt.Sprintf("/user2/repo1/pull/%d/target_branch", prIssue.PullRequest.Index), map[string]string{
"_csrf": GetUserCSRFToken(t, session),
"target_branch": "test-branch/retarget-no-conflict",
})
session.MakeRequest(t, req, http.StatusOK)

View File

@@ -133,7 +133,6 @@ func TestPullCompare_EnableAllowEditsFromMaintainer(t *testing.T) {
dataURL, exists := htmlDoc.doc.Find("#allow-edits-from-maintainers").Attr("data-url")
assert.True(t, exists)
req := NewRequestWithValues(t, "POST", dataURL+"/set_allow_maintainer_edit", map[string]string{
"_csrf": htmlDoc.GetCSRF(),
"allow_maintainer_edit": "true",
})
user4Session.MakeRequest(t, req, http.StatusOK)
@@ -159,7 +158,6 @@ func TestPullCompare_EnableAllowEditsFromMaintainer(t *testing.T) {
lastCommit := htmlDoc.GetInputValueByName("last_commit")
assert.NotEmpty(t, lastCommit)
req := NewRequestWithValues(t, "POST", editFileLink, map[string]string{
"_csrf": htmlDoc.GetCSRF(),
"last_commit": lastCommit,
"tree_path": "README.md",
"content": "File is edited by the maintainer user2",

View File

@@ -59,7 +59,6 @@ func testPullCreate(t *testing.T, session *TestSession, user, repo string, toSel
link, exists = htmlDoc.doc.Find("form.ui.form").Attr("action")
assert.True(t, exists, "The template has changed")
req = NewRequestWithValues(t, "POST", link, map[string]string{
"_csrf": htmlDoc.GetCSRF(),
"title": title,
})
resp = session.MakeRequest(t, req, http.StatusOK)
@@ -103,7 +102,6 @@ func testPullCreateDirectly(t *testing.T, session *TestSession, opts createPullR
link, exists := htmlDoc.doc.Find("form.ui.form").Attr("action")
assert.True(t, exists, "The template has changed")
params := map[string]string{
"_csrf": htmlDoc.GetCSRF(),
"title": opts.Title,
}
if opts.ReviewerIDs != "" {
@@ -131,7 +129,6 @@ func testPullCreateFailure(t *testing.T, session *TestSession, baseRepoOwner, ba
link, exists := htmlDoc.doc.Find("form.ui.form").Attr("action")
assert.True(t, exists, "The template has changed")
req = NewRequestWithValues(t, "POST", link, map[string]string{
"_csrf": htmlDoc.GetCSRF(),
"title": title,
})
resp = session.MakeRequest(t, req, http.StatusBadRequest)
@@ -159,7 +156,6 @@ func TestPullCreate(t *testing.T) {
// test create the pull request again and it should fail now
link := "/user2/repo1/compare/master...user1/repo1:master"
req := NewRequestWithValues(t, "POST", link, map[string]string{
"_csrf": GetUserCSRFToken(t, session),
"title": "This is a pull title",
})
session.MakeRequest(t, req, http.StatusBadRequest)
@@ -200,7 +196,6 @@ func TestPullCreate_TitleEscape(t *testing.T) {
assert.True(t, exists, "The template has changed")
req = NewRequestWithValues(t, "POST", editTestTitleURL, map[string]string{
"_csrf": htmlDoc.GetCSRF(),
"title": "<u>XSS PR</u>",
})
session.MakeRequest(t, req, http.StatusOK)
@@ -219,25 +214,15 @@ func TestPullCreate_TitleEscape(t *testing.T) {
func testUIDeleteBranch(t *testing.T, session *TestSession, ownerName, repoName, branchName string) {
relURL := "/" + path.Join(ownerName, repoName, "branches")
req := NewRequest(t, "GET", relURL)
resp := session.MakeRequest(t, req, http.StatusOK)
htmlDoc := NewHTMLParser(t, resp.Body)
req = NewRequestWithValues(t, "POST", relURL+"/delete", map[string]string{
"_csrf": htmlDoc.GetCSRF(),
"name": branchName,
req := NewRequestWithValues(t, "POST", relURL+"/delete", map[string]string{
"name": branchName,
})
session.MakeRequest(t, req, http.StatusOK)
}
func testDeleteRepository(t *testing.T, session *TestSession, ownerName, repoName string) {
relURL := "/" + path.Join(ownerName, repoName, "settings")
req := NewRequest(t, "GET", relURL)
resp := session.MakeRequest(t, req, http.StatusOK)
htmlDoc := NewHTMLParser(t, resp.Body)
req = NewRequestWithValues(t, "POST", relURL+"?action=delete", map[string]string{
"_csrf": htmlDoc.GetCSRF(),
req := NewRequestWithValues(t, "POST", relURL+"?action=delete", map[string]string{
"repo_name": repoName,
})
session.MakeRequest(t, req, http.StatusSeeOther)

View File

@@ -51,38 +51,27 @@ type MergeOptions struct {
DeleteBranch bool
}
func testPullMerge(t *testing.T, session *TestSession, user, repo, pullnum string, mergeOptions MergeOptions) *httptest.ResponseRecorder {
req := NewRequest(t, "GET", path.Join(user, repo, "pulls", pullnum))
resp := session.MakeRequest(t, req, http.StatusOK)
htmlDoc := NewHTMLParser(t, resp.Body)
link := path.Join(user, repo, "pulls", pullnum, "merge")
func testPullMerge(t *testing.T, session *TestSession, user, repo, pullNum string, mergeOptions MergeOptions) *httptest.ResponseRecorder {
options := map[string]string{
"_csrf": htmlDoc.GetCSRF(),
"do": string(mergeOptions.Style),
"head_commit_id": mergeOptions.HeadCommitID,
"do": string(mergeOptions.Style),
"head_commit_id": mergeOptions.HeadCommitID,
"delete_branch_after_merge": util.Iif(mergeOptions.DeleteBranch, "on", ""),
}
var resp *httptest.ResponseRecorder
require.Eventually(t, func() bool {
req := NewRequestWithValues(t, "POST", fmt.Sprintf("/%s/%s/pulls/%s/merge", user, repo, pullNum), options)
resp = session.MakeRequest(t, req, NoExpectedStatus)
return resp.Code == http.StatusOK
}, 5*time.Second, 50*time.Millisecond, "Timed out waiting for pull merge to succeed")
if mergeOptions.DeleteBranch {
options["delete_branch_after_merge"] = "on"
}
redirect := test.RedirectURL(resp)
assert.Equal(t, fmt.Sprintf("/%s/%s/pulls/%s", user, repo, pullNum), redirect)
req = NewRequestWithValues(t, "POST", link, options)
resp = session.MakeRequest(t, req, http.StatusOK)
respJSON := struct {
Redirect string
}{}
DecodeJSON(t, resp, &respJSON)
assert.Equal(t, fmt.Sprintf("/%s/%s/pulls/%s", user, repo, pullnum), respJSON.Redirect)
pullnumInt, err := strconv.ParseInt(pullnum, 10, 64)
pullNumInt, err := strconv.ParseInt(pullNum, 10, 64)
assert.NoError(t, err)
repository, err := repo_model.GetRepositoryByOwnerAndName(t.Context(), user, repo)
assert.NoError(t, err)
pull, err := issues_model.GetPullRequestByIndex(t.Context(), repository.ID, pullnumInt)
pull, err := issues_model.GetPullRequestByIndex(t.Context(), repository.ID, pullNumInt)
assert.NoError(t, err)
assert.True(t, pull.HasMerged)
@@ -97,9 +86,7 @@ func testPullCleanUp(t *testing.T, session *TestSession, user, repo, pullnum str
htmlDoc := NewHTMLParser(t, resp.Body)
link, exists := htmlDoc.doc.Find(".timeline-item .delete-branch-after-merge").Attr("data-url")
assert.True(t, exists, "The template has changed, can not find delete button url")
req = NewRequestWithValues(t, "POST", link, map[string]string{
"_csrf": htmlDoc.GetCSRF(),
})
req = NewRequest(t, "POST", link)
resp = session.MakeRequest(t, req, http.StatusOK)
return resp
@@ -844,11 +831,8 @@ func TestPullAutoMergeAfterCommitStatusSucceed(t *testing.T) {
HeadBranch: "master",
})
// add protected branch for commit status
csrf := GetUserCSRFToken(t, session)
// Change the "master" branch to "protected"
req := NewRequestWithValues(t, "POST", "/user2/repo1/settings/branches/edit", map[string]string{
"_csrf": csrf,
"rule_name": "master",
"enable_push": "true",
"enable_status_check": "true",
@@ -937,11 +921,8 @@ func TestPullAutoMergeAfterCommitStatusSucceedAndApproval(t *testing.T) {
HeadBranch: "master",
})
// add protected branch for commit status
csrf := GetUserCSRFToken(t, session)
// Change master branch to protected
req := NewRequestWithValues(t, "POST", "/user2/repo1/settings/branches/edit", map[string]string{
"_csrf": csrf,
"rule_name": "master",
"enable_push": "true",
"enable_status_check": "true",
@@ -993,10 +974,7 @@ func TestPullAutoMergeAfterCommitStatusSucceedAndApproval(t *testing.T) {
// approve the PR from non-author
approveSession := loginUser(t, "user2")
req = NewRequest(t, "GET", fmt.Sprintf("/user2/repo1/pulls/%d", pr.Index))
resp := approveSession.MakeRequest(t, req, http.StatusOK)
htmlDoc := NewHTMLParser(t, resp.Body)
testSubmitReview(t, approveSession, htmlDoc.GetCSRF(), "user2", "repo1", strconv.Itoa(int(pr.Index)), sha, "approve", http.StatusOK)
testSubmitReview(t, approveSession, "user2", "repo1", strconv.Itoa(int(pr.Index)), sha, "approve", http.StatusOK)
time.Sleep(2 * time.Second)
@@ -1067,11 +1045,8 @@ func TestPullAutoMergeAfterCommitStatusSucceedAndApprovalForAgitFlow(t *testing.
})
session := loginUser(t, "user1")
// add protected branch for commit status
csrf := GetUserCSRFToken(t, session)
// Change master branch to protected
req := NewRequestWithValues(t, "POST", "/user2/repo1/settings/branches/edit", map[string]string{
"_csrf": csrf,
"rule_name": "master",
"enable_push": "true",
"enable_status_check": "true",
@@ -1122,10 +1097,7 @@ func TestPullAutoMergeAfterCommitStatusSucceedAndApprovalForAgitFlow(t *testing.
// approve the PR from non-author
approveSession := loginUser(t, "user1")
req = NewRequest(t, "GET", fmt.Sprintf("/user2/repo1/pulls/%d", pr.Index))
resp := approveSession.MakeRequest(t, req, http.StatusOK)
htmlDoc := NewHTMLParser(t, resp.Body)
testSubmitReview(t, approveSession, htmlDoc.GetCSRF(), "user2", "repo1", strconv.Itoa(int(pr.Index)), sha, "approve", http.StatusOK)
testSubmitReview(t, approveSession, "user2", "repo1", strconv.Itoa(int(pr.Index)), sha, "approve", http.StatusOK)
// reload pr again
pr = unittest.AssertExistsAndLoadBean(t, &issues_model.PullRequest{ID: pr.ID})
@@ -1156,11 +1128,8 @@ func TestPullNonMergeForAdminWithBranchProtection(t *testing.T) {
HeadBranch: "master",
})
// add protected branch for commit status
csrf := GetUserCSRFToken(t, session)
// Change master branch to protected
pbCreateReq := NewRequestWithValues(t, "POST", "/user2/repo1/settings/branches/edit", map[string]string{
"_csrf": csrf,
"rule_name": "master",
"enable_push": "true",
"enable_status_check": "true",
@@ -1172,7 +1141,6 @@ func TestPullNonMergeForAdminWithBranchProtection(t *testing.T) {
token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteRepository)
mergeReq := NewRequestWithValues(t, "POST", "/api/v1/repos/user2/repo1/pulls/6/merge", map[string]string{
"_csrf": csrf,
"head_commit_id": "",
"merge_when_checks_succeed": "false",
"force_merge": "true",

View File

@@ -233,16 +233,11 @@ func TestPullView_GivenApproveOrRejectReviewOnClosedPR(t *testing.T) {
DeleteBranch: false,
})
// Grab the CSRF token.
req := NewRequest(t, "GET", path.Join(elem[1], elem[2], "pulls", elem[4]))
resp = user2Session.MakeRequest(t, req, http.StatusOK)
htmlDoc := NewHTMLParser(t, resp.Body)
// Submit an approve review on the PR.
testSubmitReview(t, user2Session, htmlDoc.GetCSRF(), "user2", "repo1", elem[4], "", "approve", http.StatusUnprocessableEntity)
testSubmitReview(t, user2Session, "user2", "repo1", elem[4], "", "approve", http.StatusUnprocessableEntity)
// Submit a reject review on the PR.
testSubmitReview(t, user2Session, htmlDoc.GetCSRF(), "user2", "repo1", elem[4], "", "reject", http.StatusUnprocessableEntity)
testSubmitReview(t, user2Session, "user2", "repo1", elem[4], "", "reject", http.StatusUnprocessableEntity)
})
t.Run("Submit approve/reject review on closed PR", func(t *testing.T) {
@@ -253,23 +248,17 @@ func TestPullView_GivenApproveOrRejectReviewOnClosedPR(t *testing.T) {
assert.Equal(t, "pulls", elem[3])
testIssueClose(t, user1Session, elem[1], elem[2], elem[4])
// Grab the CSRF token.
req := NewRequest(t, "GET", path.Join(elem[1], elem[2], "pulls", elem[4]))
resp = user2Session.MakeRequest(t, req, http.StatusOK)
htmlDoc := NewHTMLParser(t, resp.Body)
// Submit an approve review on the PR.
testSubmitReview(t, user2Session, htmlDoc.GetCSRF(), "user2", "repo1", elem[4], "", "approve", http.StatusUnprocessableEntity)
testSubmitReview(t, user2Session, "user2", "repo1", elem[4], "", "approve", http.StatusUnprocessableEntity)
// Submit a reject review on the PR.
testSubmitReview(t, user2Session, htmlDoc.GetCSRF(), "user2", "repo1", elem[4], "", "reject", http.StatusUnprocessableEntity)
testSubmitReview(t, user2Session, "user2", "repo1", elem[4], "", "reject", http.StatusUnprocessableEntity)
})
})
}
func testSubmitReview(t *testing.T, session *TestSession, csrf, owner, repo, pullNumber, commitID, reviewType string, expectedSubmitStatus int) *httptest.ResponseRecorder {
func testSubmitReview(t *testing.T, session *TestSession, owner, repo, pullNumber, commitID, reviewType string, expectedSubmitStatus int) *httptest.ResponseRecorder {
options := map[string]string{
"_csrf": csrf,
"commit_id": commitID,
"content": "test",
"type": reviewType,
@@ -281,17 +270,12 @@ func testSubmitReview(t *testing.T, session *TestSession, csrf, owner, repo, pul
}
func testIssueClose(t *testing.T, session *TestSession, owner, repo, issueNumber string) *httptest.ResponseRecorder {
req := NewRequest(t, "GET", path.Join(owner, repo, "pulls", issueNumber))
resp := session.MakeRequest(t, req, http.StatusOK)
htmlDoc := NewHTMLParser(t, resp.Body)
closeURL := path.Join(owner, repo, "issues", issueNumber, "comments")
options := map[string]string{
"_csrf": htmlDoc.GetCSRF(),
"status": "close",
}
req = NewRequestWithValues(t, "POST", closeURL, options)
req := NewRequestWithValues(t, "POST", closeURL, options)
return session.MakeRequest(t, req, http.StatusOK)
}

View File

@@ -34,7 +34,6 @@ func TestPullCreate_CommitStatus(t *testing.T) {
url := path.Join("user1", "repo1", "compare", "master...status1")
req := NewRequestWithValues(t, "POST", url,
map[string]string{
"_csrf": GetUserCSRFToken(t, session),
"title": "pull request from status1",
},
)
@@ -134,7 +133,6 @@ func TestPullCreate_EmptyChangesWithDifferentCommits(t *testing.T) {
url := path.Join("user1", "repo1", "compare", "master...status1")
req := NewRequestWithValues(t, "POST", url,
map[string]string{
"_csrf": GetUserCSRFToken(t, session),
"title": "pull request from status1",
},
)
@@ -157,7 +155,6 @@ func TestPullCreate_EmptyChangesWithSameCommits(t *testing.T) {
url := path.Join("user1", "repo1", "compare", "master...status1")
req := NewRequestWithValues(t, "POST", url,
map[string]string{
"_csrf": GetUserCSRFToken(t, session),
"title": "pull request from status1",
},
)

View File

@@ -28,7 +28,6 @@ func createNewRelease(t *testing.T, session *TestSession, repoURL, tag, title st
assert.True(t, exists, "The template has changed")
postData := map[string]string{
"_csrf": htmlDoc.GetCSRF(),
"tag_name": tag,
"tag_target": "master",
"title": title,

View File

@@ -27,14 +27,9 @@ func testRenameBranch(t *testing.T, u *url.URL) {
// get branch setting page
session := loginUser(t, "user2")
req := NewRequest(t, "GET", "/user2/repo1/branches")
resp := session.MakeRequest(t, req, http.StatusOK)
htmlDoc := NewHTMLParser(t, resp.Body)
req = NewRequestWithValues(t, "POST", "/user2/repo1/branches/rename", map[string]string{
"_csrf": htmlDoc.GetCSRF(),
"from": "master",
"to": "main",
req := NewRequestWithValues(t, "POST", "/user2/repo1/branches/rename", map[string]string{
"from": "master",
"to": "main",
})
session.MakeRequest(t, req, http.StatusSeeOther)
@@ -44,7 +39,7 @@ func testRenameBranch(t *testing.T, u *url.URL) {
// check old branch link
req = NewRequestWithValues(t, "GET", "/user2/repo1/src/branch/master/README.md", nil)
resp = session.MakeRequest(t, req, http.StatusSeeOther)
resp := session.MakeRequest(t, req, http.StatusSeeOther)
location := resp.Header().Get("Location")
assert.Equal(t, "/user2/repo1/src/branch/main/README.md", location)
@@ -53,10 +48,7 @@ func testRenameBranch(t *testing.T, u *url.URL) {
assert.Equal(t, "main", repo1.DefaultBranch)
// create branch1
csrf := GetUserCSRFToken(t, session)
req = NewRequestWithValues(t, "POST", "/user2/repo1/branches/_new/branch/main", map[string]string{
"_csrf": csrf,
"new_branch_name": "branch1",
})
session.MakeRequest(t, req, http.StatusSeeOther)
@@ -66,7 +58,6 @@ func testRenameBranch(t *testing.T, u *url.URL) {
// create branch2
req = NewRequestWithValues(t, "POST", "/user2/repo1/branches/_new/branch/main", map[string]string{
"_csrf": csrf,
"new_branch_name": "branch2",
})
session.MakeRequest(t, req, http.StatusSeeOther)
@@ -76,9 +67,8 @@ func testRenameBranch(t *testing.T, u *url.URL) {
// rename branch2 to branch1
req = NewRequestWithValues(t, "POST", "/user2/repo1/branches/rename", map[string]string{
"_csrf": htmlDoc.GetCSRF(),
"from": "branch2",
"to": "branch1",
"from": "branch2",
"to": "branch1",
})
session.MakeRequest(t, req, http.StatusSeeOther)
flashMsg := session.GetCookieFlashMessage()
@@ -91,8 +81,7 @@ func testRenameBranch(t *testing.T, u *url.URL) {
// delete branch1
req = NewRequestWithValues(t, "POST", "/user2/repo1/branches/delete", map[string]string{
"_csrf": htmlDoc.GetCSRF(),
"name": "branch1",
"name": "branch1",
})
session.MakeRequest(t, req, http.StatusOK)
branch2 = unittest.AssertExistsAndLoadBean(t, &git_model.Branch{RepoID: repo1.ID, Name: "branch2"})
@@ -102,9 +91,8 @@ func testRenameBranch(t *testing.T, u *url.URL) {
// rename branch2 to branch1 again
req = NewRequestWithValues(t, "POST", "/user2/repo1/branches/rename", map[string]string{
"_csrf": htmlDoc.GetCSRF(),
"from": "branch2",
"to": "branch1",
"from": "branch2",
"to": "branch1",
})
session.MakeRequest(t, req, http.StatusSeeOther)

View File

@@ -15,16 +15,13 @@ import (
"code.gitea.io/gitea/models/unittest"
"code.gitea.io/gitea/modules/test"
"code.gitea.io/gitea/modules/translation"
"code.gitea.io/gitea/tests"
"github.com/PuerkitoBio/goquery"
"github.com/stretchr/testify/assert"
)
func testCreateBranch(t testing.TB, session *TestSession, user, repo, oldRefSubURL, newBranchName string, expectedStatus int) string {
csrf := GetUserCSRFToken(t, session)
req := NewRequestWithValues(t, "POST", path.Join(user, repo, "branches/_new", oldRefSubURL), map[string]string{
"_csrf": csrf,
"new_branch_name": newBranchName,
})
resp := session.MakeRequest(t, req, expectedStatus)
@@ -126,17 +123,6 @@ func testCreateBranches(t *testing.T, giteaURL *url.URL) {
}
}
func TestCreateBranchInvalidCSRF(t *testing.T) {
defer tests.PrepareTestEnv(t)()
session := loginUser(t, "user2")
req := NewRequestWithValues(t, "POST", "user2/repo1/branches/_new/branch/master", map[string]string{
"_csrf": "fake_csrf",
"new_branch_name": "test",
})
resp := session.MakeRequest(t, req, http.StatusBadRequest)
assert.Contains(t, resp.Body.String(), "Invalid CSRF token")
}
func prepareRecentlyPushedBranchTest(t *testing.T, headSession *TestSession, baseRepo, headRepo *repo_model.Repository) {
refSubURL := "branch/" + headRepo.DefaultBranch
baseRepoPath := baseRepo.OwnerName + "/" + baseRepo.Name

View File

@@ -46,7 +46,6 @@ func testRepoFork(t *testing.T, session *TestSession, ownerName, repoName, forkO
_, exists = htmlDoc.doc.Find(fmt.Sprintf(".owner.dropdown .item[data-value=\"%d\"]", forkOwner.ID)).Attr("data-value")
assert.True(t, exists, "Fork owner '%s' is not present in select box", forkOwnerName)
req = NewRequestWithValues(t, "POST", link, map[string]string{
"_csrf": htmlDoc.GetCSRF(),
"uid": strconv.FormatInt(forkOwner.ID, 10),
"repo_name": forkRepoName,
"fork_single_branch": forkBranch,

View File

@@ -44,7 +44,6 @@ func testRepoGenerate(t *testing.T, session *TestSession, templateID, templateOw
_, exists = htmlDoc.doc.Find(fmt.Sprintf(`#repo_owner_dropdown .item[data-value="%d"]`, generateOwner.ID)).Attr("data-value")
assert.True(t, exists, "Generate owner '%s' is not present in select box", generateOwnerName)
req = NewRequestWithValues(t, "POST", link, map[string]string{
"_csrf": htmlDoc.GetCSRF(),
"uid": strconv.FormatInt(generateOwner.ID, 10),
"repo_name": generateRepoName,
"repo_template": templateID,

View File

@@ -49,7 +49,6 @@ func TestRepoMergeUpstream(t *testing.T) {
// create fork-branch
req = NewRequestWithValues(t, "POST", fmt.Sprintf("/%s/test-repo-fork/branches/_new/branch/master", forkUser.Name), map[string]string{
"_csrf": GetUserCSRFToken(t, session),
"new_branch_name": "fork-branch",
})
session.MakeRequest(t, req, http.StatusSeeOther)
@@ -81,7 +80,6 @@ func TestRepoMergeUpstream(t *testing.T) {
t.Run("DetectSameBranch", func(t *testing.T) {
// if the fork-branch name also exists in the base repo, then use that branch instead
req = NewRequestWithValues(t, "POST", "/user2/repo1/branches/_new/branch/master", map[string]string{
"_csrf": GetUserCSRFToken(t, sessionBaseUser),
"new_branch_name": "fork-branch",
})
sessionBaseUser.MakeRequest(t, req, http.StatusSeeOther)
@@ -99,14 +97,12 @@ func TestRepoMergeUpstream(t *testing.T) {
})
// click the "sync fork" button
req = NewRequestWithValues(t, "POST", mergeUpstreamLink, map[string]string{"_csrf": GetUserCSRFToken(t, session)})
req = NewRequest(t, "POST", mergeUpstreamLink)
session.MakeRequest(t, req, http.StatusOK)
checkFileContent("fork-branch", "test-content-1")
// delete the "fork-branch" from the base repo
req = NewRequestWithValues(t, "POST", "/user2/repo1/branches/delete?name=fork-branch", map[string]string{
"_csrf": GetUserCSRFToken(t, sessionBaseUser),
})
req = NewRequest(t, "POST", "/user2/repo1/branches/delete?name=fork-branch")
sessionBaseUser.MakeRequest(t, req, http.StatusOK)
})
@@ -151,7 +147,6 @@ func TestRepoMergeUpstream(t *testing.T) {
t.Run("FastForwardOnly", func(t *testing.T) {
// Create a clean branch for fast-forward testing
req = NewRequestWithValues(t, "POST", fmt.Sprintf("/%s/test-repo-fork/branches/_new/branch/master", forkUser.Name), map[string]string{
"_csrf": GetUserCSRFToken(t, session),
"new_branch_name": "ff-test-branch",
})
session.MakeRequest(t, req, http.StatusSeeOther)

View File

@@ -27,7 +27,6 @@ func testRepoMigrate(t testing.TB, session *TestSession, cloneAddr, repoName str
assert.True(t, exists, "The template has changed")
req = NewRequestWithValues(t, "POST", link, map[string]string{
"_csrf": htmlDoc.GetCSRF(),
"clone_addr": cloneAddr,
"uid": uid,
"repo_name": repoName,

View File

@@ -157,7 +157,6 @@ func testViewRepoPrivate(t *testing.T) {
// set unit code to "anonymous read"
req = NewRequestWithValues(t, "POST", "/org3/repo3/settings/public_access", map[string]string{
"_csrf": GetUserCSRFToken(t, session),
"repo-unit-access-" + strconv.Itoa(int(unit.TypeCode)): "anonymous-read",
})
session.MakeRequest(t, req, http.StatusSeeOther)
@@ -168,9 +167,7 @@ func testViewRepoPrivate(t *testing.T) {
assert.Contains(t, resp.Body.String(), `<span class="ui basic orange label">Public Access</span>`)
// remove "anonymous read"
req = NewRequestWithValues(t, "POST", "/org3/repo3/settings/public_access", map[string]string{
"_csrf": GetUserCSRFToken(t, session),
})
req = NewRequest(t, "POST", "/org3/repo3/settings/public_access")
session.MakeRequest(t, req, http.StatusSeeOther)
// try to "anonymous read" (not found)

View File

@@ -83,9 +83,7 @@ func testAPICreateWebhookForRepo(t *testing.T, session *TestSession, userName, r
}
func testCreateWebhookForRepo(t *testing.T, session *TestSession, webhookType, userName, repoName, url, eventKind string) {
csrf := GetUserCSRFToken(t, session)
req := NewRequestWithValues(t, "POST", "/"+userName+"/"+repoName+"/settings/hooks/"+webhookType+"/new", map[string]string{
"_csrf": csrf,
"payload_url": url,
"events": eventKind,
"active": "true",
@@ -278,7 +276,6 @@ func Test_WebhookIssueComment(t *testing.T) {
commentID := testIssueAddComment(t, session, issueURL, "issue title3 comment1", "")
modifiedContent := "issue title2 comment1 - modified"
req := NewRequestWithValues(t, "POST", fmt.Sprintf("/%s/%s/comments/%d", "user2", "repo1", commentID), map[string]string{
"_csrf": GetUserCSRFToken(t, session),
"content": modifiedContent,
})
session.MakeRequest(t, req, http.StatusOK)
@@ -306,7 +303,6 @@ func Test_WebhookIssueComment(t *testing.T) {
payloads = make([]api.IssueCommentPayload, 0, 2)
triggeredEvent = ""
req := NewRequestWithValues(t, "POST", fmt.Sprintf("/%s/%s/comments/%d", "user2", "repo1", commentID), map[string]string{
"_csrf": GetUserCSRFToken(t, session),
"content": commentContent,
})
session.MakeRequest(t, req, http.StatusOK)
@@ -1284,9 +1280,7 @@ jobs:
// Call cancel ui api
// Only a web UI API exists for cancelling workflow runs, so use the UI endpoint.
cancelURL := fmt.Sprintf("/user2/repo1/actions/runs/%d/cancel", webhookData.payloads[0].WorkflowRun.RunNumber)
req := NewRequestWithValues(t, "POST", cancelURL, map[string]string{
"_csrf": GetUserCSRFToken(t, session),
})
req := NewRequest(t, "POST", cancelURL)
session.MakeRequest(t, req, http.StatusOK)
assert.Len(t, webhookData.payloads, 2)
@@ -1418,9 +1412,7 @@ jobs:
// Call cancel ui api
// Only a web UI API exists for cancelling workflow runs, so use the UI endpoint.
cancelURL := fmt.Sprintf("/user2/repo1/actions/runs/%d/cancel", webhookData.payloads[0].WorkflowRun.RunNumber)
req := NewRequestWithValues(t, "POST", cancelURL, map[string]string{
"_csrf": GetUserCSRFToken(t, session),
})
req := NewRequest(t, "POST", cancelURL)
session.MakeRequest(t, req, http.StatusOK)
assert.Len(t, webhookData.payloads, 2)
@@ -1438,9 +1430,7 @@ jobs:
// Call rerun ui api
// Only a web UI API exists for rerunning workflow runs, so use the UI endpoint.
rerunURL := fmt.Sprintf("/user2/repo1/actions/runs/%d/rerun", webhookData.payloads[0].WorkflowRun.RunNumber)
req = NewRequestWithValues(t, "POST", rerunURL, map[string]string{
"_csrf": GetUserCSRFToken(t, session),
})
req = NewRequest(t, "POST", rerunURL)
session.MakeRequest(t, req, http.StatusOK)
assert.Len(t, webhookData.payloads, 3)

View File

@@ -46,9 +46,7 @@ func testViewTimetrackingControls(t *testing.T, session *TestSession, user, repo
AssertHTMLElement(t, htmlDoc, ".issue-add-time", canTrackTime)
issueLink := path.Join(user, repo, "issues", issue)
reqStart := NewRequestWithValues(t, "POST", path.Join(issueLink, "times", "stopwatch", "start"), map[string]string{
"_csrf": htmlDoc.GetCSRF(),
})
reqStart := NewRequest(t, "POST", path.Join(issueLink, "times", "stopwatch", "start"))
if canTrackTime {
session.MakeRequest(t, reqStart, http.StatusOK)
@@ -65,9 +63,7 @@ func testViewTimetrackingControls(t *testing.T, session *TestSession, user, repo
// Sleep for 1 second to not get wrong order for stopping timer
time.Sleep(time.Second)
reqStop := NewRequestWithValues(t, "POST", path.Join(issueLink, "times", "stopwatch", "stop"), map[string]string{
"_csrf": htmlDoc.GetCSRF(),
})
reqStop := NewRequest(t, "POST", path.Join(issueLink, "times", "stopwatch", "stop"))
session.MakeRequest(t, reqStop, http.StatusOK)
req = NewRequest(t, "GET", issueLink)

View File

@@ -35,7 +35,6 @@ func TestUserAvatar(t *testing.T) {
}
session := loginUser(t, "user2")
csrf := GetUserCSRFToken(t, session)
imgData := &bytes.Buffer{}
@@ -66,7 +65,6 @@ func TestUserAvatar(t *testing.T) {
}
req := NewRequestWithBody(t, "POST", "/user/settings/avatar", body)
req.Header.Add("X-Csrf-Token", csrf)
req.Header.Add("Content-Type", writer.FormDataContentType())
session.MakeRequest(t, req, http.StatusSeeOther)

View File

@@ -129,13 +129,7 @@ func TestUserSettingsUpdatePassword(t *testing.T) {
defer tests.PrintCurrentTest(t)()
session := loginUser(t, "user2")
req := NewRequest(t, "GET", "/user/settings/account")
resp := session.MakeRequest(t, req, http.StatusOK)
doc := NewHTMLParser(t, resp.Body)
req = NewRequestWithValues(t, "POST", "/user/settings/account", map[string]string{
"_csrf": doc.GetCSRF(),
req := NewRequestWithValues(t, "POST", "/user/settings/account", map[string]string{
"old_password": "password",
"password": "password",
"retype": "password",
@@ -147,16 +141,8 @@ func TestUserSettingsUpdatePassword(t *testing.T) {
defer tests.PrintCurrentTest(t)()
WithDisabledFeatures(t, setting.UserFeatureManageCredentials)
session := loginUser(t, "user2")
req := NewRequest(t, "GET", "/user/settings/account")
resp := session.MakeRequest(t, req, http.StatusOK)
doc := NewHTMLParser(t, resp.Body)
req = NewRequestWithValues(t, "POST", "/user/settings/account", map[string]string{
"_csrf": doc.GetCSRF(),
})
req := NewRequest(t, "POST", "/user/settings/account")
session.MakeRequest(t, req, http.StatusNotFound)
})
}
@@ -168,16 +154,8 @@ func TestUserSettingsUpdateEmail(t *testing.T) {
defer tests.PrintCurrentTest(t)()
WithDisabledFeatures(t, setting.UserFeatureManageCredentials)
session := loginUser(t, "user2")
req := NewRequest(t, "GET", "/user/settings/account")
resp := session.MakeRequest(t, req, http.StatusOK)
doc := NewHTMLParser(t, resp.Body)
req = NewRequestWithValues(t, "POST", "/user/settings/account/email", map[string]string{
"_csrf": doc.GetCSRF(),
})
req := NewRequest(t, "POST", "/user/settings/account/email")
session.MakeRequest(t, req, http.StatusNotFound)
})
}
@@ -189,16 +167,8 @@ func TestUserSettingsDeleteEmail(t *testing.T) {
defer tests.PrintCurrentTest(t)()
WithDisabledFeatures(t, setting.UserFeatureManageCredentials)
session := loginUser(t, "user2")
req := NewRequest(t, "GET", "/user/settings/account")
resp := session.MakeRequest(t, req, http.StatusOK)
doc := NewHTMLParser(t, resp.Body)
req = NewRequestWithValues(t, "POST", "/user/settings/account/email/delete", map[string]string{
"_csrf": doc.GetCSRF(),
})
req := NewRequest(t, "POST", "/user/settings/account/email/delete")
session.MakeRequest(t, req, http.StatusNotFound)
})
}
@@ -212,14 +182,7 @@ func TestUserSettingsDelete(t *testing.T) {
WithDisabledFeatures(t, setting.UserFeatureDeletion)
session := loginUser(t, "user2")
req := NewRequest(t, "GET", "/user/settings/account")
resp := session.MakeRequest(t, req, http.StatusOK)
doc := NewHTMLParser(t, resp.Body)
req = NewRequestWithValues(t, "POST", "/user/settings/account/delete", map[string]string{
"_csrf": doc.GetCSRF(),
})
req := NewRequest(t, "POST", "/user/settings/account/delete")
session.MakeRequest(t, req, http.StatusNotFound)
})
}
@@ -308,15 +271,10 @@ func TestUserSettingsApplications(t *testing.T) {
t.Run("OAuthApplicationsEdit", func(t *testing.T) {
defer tests.PrintCurrentTest(t)()
req := NewRequest(t, "GET", "/user/settings/applications/oauth2/2")
resp := session.MakeRequest(t, req, http.StatusOK)
doc := NewHTMLParser(t, resp.Body)
t.Run("Invalid URL", func(t *testing.T) {
defer tests.PrintCurrentTest(t)()
req := NewRequestWithValues(t, "POST", "/user/settings/applications/oauth2/2", map[string]string{
"_csrf": doc.GetCSRF(),
"application_name": "Test native app",
"redirect_uris": "ftp://127.0.0.1",
"confidential_client": "false",
@@ -332,7 +290,6 @@ func TestUserSettingsApplications(t *testing.T) {
defer tests.PrintCurrentTest(t)()
req := NewRequestWithValues(t, "POST", "/user/settings/applications/oauth2/2", map[string]string{
"_csrf": doc.GetCSRF(),
"application_name": "Test native app",
"redirect_uris": "http://127.0.0.1",
"confidential_client": "false",

View File

@@ -34,7 +34,6 @@ func TestRenameUsername(t *testing.T) {
session := loginUser(t, "user2")
req := NewRequestWithValues(t, "POST", "/user/settings", map[string]string{
"_csrf": GetUserCSRFToken(t, session),
"name": "newUsername",
"email": "user2@example.com",
"language": "en-US",
@@ -57,7 +56,6 @@ func TestViewLimitedAndPrivateUserAndRename(t *testing.T) {
oldName := org22.Name
newName := "org22_renamed"
req = NewRequestWithValues(t, "POST", "/org/"+oldName+"/settings/rename", map[string]string{
"_csrf": GetUserCSRFToken(t, session),
"org_name": oldName,
"new_org_name": newName,
})
@@ -79,7 +77,6 @@ func TestViewLimitedAndPrivateUserAndRename(t *testing.T) {
oldName = org23.Name
newName = "org23_renamed"
req = NewRequestWithValues(t, "POST", "/org/"+oldName+"/settings/rename", map[string]string{
"_csrf": GetUserCSRFToken(t, session),
"org_name": oldName,
"new_org_name": newName,
})
@@ -102,7 +99,6 @@ func TestViewLimitedAndPrivateUserAndRename(t *testing.T) {
newName = "user31_renamed"
session2 := loginUser(t, oldName)
req = NewRequestWithValues(t, "POST", "/user/settings", map[string]string{
"_csrf": GetUserCSRFToken(t, session2),
"name": newName,
"visibility": "2", // private
})
@@ -150,7 +146,6 @@ func TestRenameInvalidUsername(t *testing.T) {
t.Logf("Testing username %s", invalidUsername)
req := NewRequestWithValues(t, "POST", "/user/settings", map[string]string{
"_csrf": GetUserCSRFToken(t, session),
"name": invalidUsername,
"email": "user2@example.com",
})
@@ -178,7 +173,6 @@ func TestRenameReservedUsername(t *testing.T) {
locale := translation.NewLocale("en-US")
for _, reservedUsername := range reservedUsernames {
req := NewRequestWithValues(t, "POST", "/user/settings", map[string]string{
"_csrf": GetUserCSRFToken(t, session),
"name": reservedUsername,
"email": "user2@example.com",
"language": "en-US",
@@ -334,7 +328,6 @@ func TestUserLocationMapLink(t *testing.T) {
session := loginUser(t, "user2")
req := NewRequestWithValues(t, "POST", "/user/settings", map[string]string{
"_csrf": GetUserCSRFToken(t, session),
"name": "user2",
"email": "user@example.com",
"language": "en-US",

View File

@@ -21,7 +21,6 @@ func TestXSSUserFullName(t *testing.T) {
session := loginUser(t, user.Name)
req := NewRequestWithValues(t, "POST", "/user/settings", map[string]string{
"_csrf": GetUserCSRFToken(t, session),
"name": user.Name,
"full_name": fullName,
"email": user.Email,