From 6a725b6f9cde28862869befb9d2b101d9e342427 Mon Sep 17 00:00:00 2001 From: Nanguan Lin <70063547+lng2020@users.noreply.github.com> Date: Wed, 20 Dec 2023 03:12:02 +0800 Subject: [PATCH 001/189] Remove deadcode under models/issues (#28536) Using the Go Official tool `golang.org/x/tools/cmd/deadcode@latest` mentioned by [go blog](https://go.dev/blog/deadcode). Just use `deadcode .` in the project root folder and it gives a list of unused functions. Though it has some false alarms. This PR removes dead code detected in `models/issues`. --- models/issues/assignees_test.go | 5 ++++- models/issues/issue.go | 9 --------- models/issues/issue_search.go | 20 -------------------- models/issues/issue_test.go | 30 ------------------------------ models/issues/label.go | 16 ---------------- models/issues/label_test.go | 24 ------------------------ models/issues/milestone_list.go | 26 -------------------------- models/issues/milestone_test.go | 29 ----------------------------- models/issues/pull.go | 30 ------------------------------ models/issues/stopwatch.go | 14 -------------- services/issue/assignee_test.go | 6 +++++- 11 files changed, 9 insertions(+), 200 deletions(-) diff --git a/models/issues/assignees_test.go b/models/issues/assignees_test.go index 3898e814c31..2c33efd99e6 100644 --- a/models/issues/assignees_test.go +++ b/models/issues/assignees_test.go @@ -18,7 +18,10 @@ func TestUpdateAssignee(t *testing.T) { assert.NoError(t, unittest.PrepareTestDatabase()) // Fake issue with assignees - issue, err := issues_model.GetIssueWithAttrsByID(db.DefaultContext, 1) + issue, err := issues_model.GetIssueByID(db.DefaultContext, 1) + assert.NoError(t, err) + + err = issue.LoadAttributes(db.DefaultContext) assert.NoError(t, err) // Assign multiple users diff --git a/models/issues/issue.go b/models/issues/issue.go index b0ff0adddda..90aad10bb90 100644 --- a/models/issues/issue.go +++ b/models/issues/issue.go @@ -534,15 +534,6 @@ func GetIssueByID(ctx context.Context, id int64) (*Issue, error) { return issue, nil } -// GetIssueWithAttrsByID returns an issue with attributes by given ID. -func GetIssueWithAttrsByID(ctx context.Context, id int64) (*Issue, error) { - issue, err := GetIssueByID(ctx, id) - if err != nil { - return nil, err - } - return issue, issue.LoadAttributes(ctx) -} - // GetIssuesByIDs return issues with the given IDs. // If keepOrder is true, the order of the returned issues will be the same as the given IDs. func GetIssuesByIDs(ctx context.Context, issueIDs []int64, keepOrder ...bool) (IssueList, error) { diff --git a/models/issues/issue_search.go b/models/issues/issue_search.go index 65ad3c81355..7dc277327a8 100644 --- a/models/issues/issue_search.go +++ b/models/issues/issue_search.go @@ -455,26 +455,6 @@ func applySubscribedCondition(sess *xorm.Session, subscriberID int64) *xorm.Sess ) } -// GetRepoIDsForIssuesOptions find all repo ids for the given options -func GetRepoIDsForIssuesOptions(ctx context.Context, opts *IssuesOptions, user *user_model.User) ([]int64, error) { - repoIDs := make([]int64, 0, 5) - e := db.GetEngine(ctx) - - sess := e.Join("INNER", "repository", "`issue`.repo_id = `repository`.id") - - applyConditions(sess, opts) - - accessCond := repo_model.AccessibleRepositoryCondition(user, unit.TypeInvalid) - if err := sess.Where(accessCond). - Distinct("issue.repo_id"). - Table("issue"). - Find(&repoIDs); err != nil { - return nil, fmt.Errorf("unable to GetRepoIDsForIssuesOptions: %w", err) - } - - return repoIDs, nil -} - // Issues returns a list of issues by given conditions. func Issues(ctx context.Context, opts *IssuesOptions) (IssueList, error) { sess := db.GetEngine(ctx). diff --git a/models/issues/issue_test.go b/models/issues/issue_test.go index 4393d18bcf4..723fa27b1be 100644 --- a/models/issues/issue_test.go +++ b/models/issues/issue_test.go @@ -216,36 +216,6 @@ func TestIssue_loadTotalTimes(t *testing.T) { assert.Equal(t, int64(3682), ms.TotalTrackedTime) } -func TestGetRepoIDsForIssuesOptions(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) - user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) - for _, test := range []struct { - Opts issues_model.IssuesOptions - ExpectedRepoIDs []int64 - }{ - { - issues_model.IssuesOptions{ - AssigneeID: 2, - }, - []int64{3, 32}, - }, - { - issues_model.IssuesOptions{ - RepoCond: builder.In("repo_id", 1, 2), - }, - []int64{1, 2}, - }, - } { - repoIDs, err := issues_model.GetRepoIDsForIssuesOptions(db.DefaultContext, &test.Opts, user) - assert.NoError(t, err) - if assert.Len(t, repoIDs, len(test.ExpectedRepoIDs)) { - for i, repoID := range repoIDs { - assert.EqualValues(t, test.ExpectedRepoIDs[i], repoID) - } - } - } -} - func testInsertIssue(t *testing.T, title, content string, expectIndex int64) *issues_model.Issue { var newIssue issues_model.Issue t.Run(title, func(t *testing.T) { diff --git a/models/issues/label.go b/models/issues/label.go index 5c6b8e08d72..3b811c1529a 100644 --- a/models/issues/label.go +++ b/models/issues/label.go @@ -424,22 +424,6 @@ func GetLabelInOrgByID(ctx context.Context, orgID, labelID int64) (*Label, error return l, nil } -// GetLabelIDsInOrgByNames returns a list of labelIDs by names in a given -// organization. -func GetLabelIDsInOrgByNames(ctx context.Context, orgID int64, labelNames []string) ([]int64, error) { - if orgID <= 0 { - return nil, ErrOrgLabelNotExist{0, orgID} - } - labelIDs := make([]int64, 0, len(labelNames)) - - return labelIDs, db.GetEngine(ctx).Table("label"). - Where("org_id = ?", orgID). - In("name", labelNames). - Asc("name"). - Cols("id"). - Find(&labelIDs) -} - // GetLabelsInOrgByIDs returns a list of labels by IDs in given organization, // it silently ignores label IDs that do not belong to the organization. func GetLabelsInOrgByIDs(ctx context.Context, orgID int64, labelIDs []int64) ([]*Label, error) { diff --git a/models/issues/label_test.go b/models/issues/label_test.go index 3a8db6ceec5..517a3cf1abd 100644 --- a/models/issues/label_test.go +++ b/models/issues/label_test.go @@ -164,30 +164,6 @@ func TestGetLabelInOrgByName(t *testing.T) { assert.True(t, issues_model.IsErrOrgLabelNotExist(err)) } -func TestGetLabelInOrgByNames(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) - labelIDs, err := issues_model.GetLabelIDsInOrgByNames(db.DefaultContext, 3, []string{"orglabel3", "orglabel4"}) - assert.NoError(t, err) - - assert.Len(t, labelIDs, 2) - - assert.Equal(t, int64(3), labelIDs[0]) - assert.Equal(t, int64(4), labelIDs[1]) -} - -func TestGetLabelInOrgByNamesDiscardsNonExistentLabels(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) - // orglabel99 doesn't exists.. See labels.yml - labelIDs, err := issues_model.GetLabelIDsInOrgByNames(db.DefaultContext, 3, []string{"orglabel3", "orglabel4", "orglabel99"}) - assert.NoError(t, err) - - assert.Len(t, labelIDs, 2) - - assert.Equal(t, int64(3), labelIDs[0]) - assert.Equal(t, int64(4), labelIDs[1]) - assert.NoError(t, err) -} - func TestGetLabelInOrgByID(t *testing.T) { assert.NoError(t, unittest.PrepareTestDatabase()) label, err := issues_model.GetLabelInOrgByID(db.DefaultContext, 3, 3) diff --git a/models/issues/milestone_list.go b/models/issues/milestone_list.go index f331b2590fa..a73bf73c17c 100644 --- a/models/issues/milestone_list.go +++ b/models/issues/milestone_list.go @@ -160,32 +160,6 @@ func (m MilestonesStats) Total() int64 { return m.OpenCount + m.ClosedCount } -// GetMilestonesStatsByRepoCond returns milestone statistic information for dashboard by given conditions. -func GetMilestonesStatsByRepoCond(ctx context.Context, repoCond builder.Cond) (*MilestonesStats, error) { - var err error - stats := &MilestonesStats{} - - sess := db.GetEngine(ctx).Where("is_closed = ?", false) - if repoCond.IsValid() { - sess.And(builder.In("repo_id", builder.Select("id").From("repository").Where(repoCond))) - } - stats.OpenCount, err = sess.Count(new(Milestone)) - if err != nil { - return nil, err - } - - sess = db.GetEngine(ctx).Where("is_closed = ?", true) - if repoCond.IsValid() { - sess.And(builder.In("repo_id", builder.Select("id").From("repository").Where(repoCond))) - } - stats.ClosedCount, err = sess.Count(new(Milestone)) - if err != nil { - return nil, err - } - - return stats, nil -} - // GetMilestonesStatsByRepoCondAndKw returns milestone statistic information for dashboard by given repo conditions and name keyword. func GetMilestonesStatsByRepoCondAndKw(ctx context.Context, repoCond builder.Cond, keyword string) (*MilestonesStats, error) { var err error diff --git a/models/issues/milestone_test.go b/models/issues/milestone_test.go index 0581d3d1488..7477af92c8c 100644 --- a/models/issues/milestone_test.go +++ b/models/issues/milestone_test.go @@ -17,7 +17,6 @@ import ( "code.gitea.io/gitea/modules/util" "github.com/stretchr/testify/assert" - "xorm.io/builder" ) func TestMilestone_State(t *testing.T) { @@ -285,34 +284,6 @@ func TestGetMilestonesByRepoIDs(t *testing.T) { }) } -func TestGetMilestonesStats(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) - - test := func(repoID int64) { - repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: repoID}) - stats, err := issues_model.GetMilestonesStatsByRepoCond(db.DefaultContext, builder.And(builder.Eq{"repo_id": repoID})) - assert.NoError(t, err) - assert.EqualValues(t, repo.NumMilestones-repo.NumClosedMilestones, stats.OpenCount) - assert.EqualValues(t, repo.NumClosedMilestones, stats.ClosedCount) - } - test(1) - test(2) - test(3) - - stats, err := issues_model.GetMilestonesStatsByRepoCond(db.DefaultContext, builder.And(builder.Eq{"repo_id": unittest.NonexistentID})) - assert.NoError(t, err) - assert.EqualValues(t, 0, stats.OpenCount) - assert.EqualValues(t, 0, stats.ClosedCount) - - repo1 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}) - repo2 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 2}) - - milestoneStats, err := issues_model.GetMilestonesStatsByRepoCond(db.DefaultContext, builder.In("repo_id", []int64{repo1.ID, repo2.ID})) - assert.NoError(t, err) - assert.EqualValues(t, repo1.NumOpenMilestones+repo2.NumOpenMilestones, milestoneStats.OpenCount) - assert.EqualValues(t, repo1.NumClosedMilestones+repo2.NumClosedMilestones, milestoneStats.ClosedCount) -} - func TestNewMilestone(t *testing.T) { assert.NoError(t, unittest.PrepareTestDatabase()) milestone := &issues_model.Milestone{ diff --git a/models/issues/pull.go b/models/issues/pull.go index c51a7daf4ec..34bea921a0d 100644 --- a/models/issues/pull.go +++ b/models/issues/pull.go @@ -78,24 +78,6 @@ func (err ErrPullRequestAlreadyExists) Unwrap() error { return util.ErrAlreadyExist } -// ErrPullRequestHeadRepoMissing represents a "ErrPullRequestHeadRepoMissing" error -type ErrPullRequestHeadRepoMissing struct { - ID int64 - HeadRepoID int64 -} - -// IsErrErrPullRequestHeadRepoMissing checks if an error is a ErrPullRequestHeadRepoMissing. -func IsErrErrPullRequestHeadRepoMissing(err error) bool { - _, ok := err.(ErrPullRequestHeadRepoMissing) - return ok -} - -// Error does pretty-printing :D -func (err ErrPullRequestHeadRepoMissing) Error() string { - return fmt.Sprintf("pull request head repo missing [id: %d, head_repo_id: %d]", - err.ID, err.HeadRepoID) -} - // ErrPullWasClosed is used close a closed pull request type ErrPullWasClosed struct { ID int64 @@ -758,18 +740,6 @@ func (pr *PullRequest) IsSameRepo() bool { return pr.BaseRepoID == pr.HeadRepoID } -// GetPullRequestsByHeadBranch returns all prs by head branch -// Since there could be multiple prs with the same head branch, this function returns a slice of prs -func GetPullRequestsByHeadBranch(ctx context.Context, headBranch string, headRepoID int64) ([]*PullRequest, error) { - log.Trace("GetPullRequestsByHeadBranch: headBranch: '%s', headRepoID: '%d'", headBranch, headRepoID) - prs := make([]*PullRequest, 0, 2) - if err := db.GetEngine(ctx).Where(builder.Eq{"head_branch": headBranch, "head_repo_id": headRepoID}). - Find(&prs); err != nil { - return nil, err - } - return prs, nil -} - // GetBaseBranchLink returns the relative URL of the base branch func (pr *PullRequest) GetBaseBranchLink(ctx context.Context) string { if err := pr.LoadBaseRepo(ctx); err != nil { diff --git a/models/issues/stopwatch.go b/models/issues/stopwatch.go index 2c662bdb06a..fd9c7d78755 100644 --- a/models/issues/stopwatch.go +++ b/models/issues/stopwatch.go @@ -29,20 +29,6 @@ func (err ErrIssueStopwatchNotExist) Unwrap() error { return util.ErrNotExist } -// ErrIssueStopwatchAlreadyExist represents an error that stopwatch is already exist -type ErrIssueStopwatchAlreadyExist struct { - UserID int64 - IssueID int64 -} - -func (err ErrIssueStopwatchAlreadyExist) Error() string { - return fmt.Sprintf("issue stopwatch already exists[uid: %d, issue_id: %d", err.UserID, err.IssueID) -} - -func (err ErrIssueStopwatchAlreadyExist) Unwrap() error { - return util.ErrAlreadyExist -} - // Stopwatch represents a stopwatch for time tracking. type Stopwatch struct { ID int64 `xorm:"pk autoincr"` diff --git a/services/issue/assignee_test.go b/services/issue/assignee_test.go index e16b012a174..da25da60ee1 100644 --- a/services/issue/assignee_test.go +++ b/services/issue/assignee_test.go @@ -18,8 +18,12 @@ func TestDeleteNotPassedAssignee(t *testing.T) { assert.NoError(t, unittest.PrepareTestDatabase()) // Fake issue with assignees - issue, err := issues_model.GetIssueWithAttrsByID(db.DefaultContext, 1) + issue, err := issues_model.GetIssueByID(db.DefaultContext, 1) assert.NoError(t, err) + + err = issue.LoadAttributes(db.DefaultContext) + assert.NoError(t, err) + assert.Len(t, issue.Assignees, 1) user1, err := user_model.GetUserByID(db.DefaultContext, 1) // This user is already assigned (see the definition in fixtures), so running UpdateAssignee should unassign him From 9483ccd463d31d465599eb4a0cc5621bc2caaf70 Mon Sep 17 00:00:00 2001 From: GiteaBot Date: Wed, 20 Dec 2023 00:20:44 +0000 Subject: [PATCH 002/189] [skip ci] Updated translations via Crowdin --- options/locale/locale_ja-JP.ini | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/options/locale/locale_ja-JP.ini b/options/locale/locale_ja-JP.ini index c2557b180e7..871a9d6809e 100644 --- a/options/locale/locale_ja-JP.ini +++ b/options/locale/locale_ja-JP.ini @@ -91,6 +91,7 @@ remove=除去 remove_all=すべて除去 remove_label_str=アイテム「%s」を削除 edit=編集 +view=表示 enabled=有効 disabled=無効 @@ -3531,6 +3532,9 @@ runs.status=ステータス runs.actors_no_select=すべてのアクター runs.status_no_select=すべてのステータス runs.no_results=一致する結果はありません。 +runs.no_workflows=ワークフローはまだありません。 +runs.no_workflows.quick_start=Gitea Action の始め方がわからない? クイックスタートガイドをご覧ください。 +runs.no_workflows.documentation=Gitea Action の詳細については、ドキュメントを参照してください。 runs.no_runs=ワークフローはまだ実行されていません。 runs.empty_commit_message=(空のコミットメッセージ) From 577421691b5bca38b9116eb36efcfc9b1dfe2043 Mon Sep 17 00:00:00 2001 From: Lunny Xiao Date: Wed, 20 Dec 2023 19:54:34 +0800 Subject: [PATCH 003/189] Add missing head of lfs client batch (#28550) ref https://github.com/git-lfs/git-lfs/blob/main/docs/api/batch.md#git-lfs-batch-api --- modules/lfs/http_client.go | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/modules/lfs/http_client.go b/modules/lfs/http_client.go index de0b1e4fede..41774733623 100644 --- a/modules/lfs/http_client.go +++ b/modules/lfs/http_client.go @@ -79,7 +79,10 @@ func (c *HTTPClient) batch(ctx context.Context, operation string, objects []Poin return nil, err } - req, err := createRequest(ctx, http.MethodPost, url, map[string]string{"Content-Type": MediaType}, payload) + req, err := createRequest(ctx, http.MethodPost, url, map[string]string{ + "Content-Type": MediaType, + "Accept": MediaType, + }, payload) if err != nil { return nil, err } From e4a24d6727e70a8a7f4688d738c36db1f0fcbcc4 Mon Sep 17 00:00:00 2001 From: wxiaoguang Date: Wed, 20 Dec 2023 22:11:59 +0800 Subject: [PATCH 004/189] Fix the issue ref rendering for wiki (#28556) Fix #28526, regression of * #26365 (although the author of #26365 has recent activities, but there is no response for the regression, so I proposed this quick fix and keep the fix simple to make it easier to backport to 1.21) --- modules/markup/html.go | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/modules/markup/html.go b/modules/markup/html.go index 774cbe1557e..03168b69468 100644 --- a/modules/markup/html.go +++ b/modules/markup/html.go @@ -852,7 +852,9 @@ func fullIssuePatternProcessor(ctx *RenderContext, node *html.Node) { } func issueIndexPatternProcessor(ctx *RenderContext, node *html.Node) { - if ctx.Metas == nil || ctx.Metas["mode"] == "document" { + // FIXME: the use of "mode" is quite dirty and hacky, for example: what is a "document"? how should it be rendered? + // The "mode" approach should be refactored to some other more clear&reliable way. + if ctx.Metas == nil || (ctx.Metas["mode"] == "document" && !ctx.IsWiki) { return } var ( From 2c48733afea30a5e25fc1a6b3054f0ae907f990b Mon Sep 17 00:00:00 2001 From: 6543 Date: Wed, 20 Dec 2023 16:19:58 +0100 Subject: [PATCH 005/189] Fix inperformant query on retrifing review from database. (#28552) can we please PLEAS PLEASE only use raw SQL statements if it is relay needed!!! source is https://github.com/go-gitea/gitea/pull/28544 (before refactoring) --- models/issues/review.go | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/models/issues/review.go b/models/issues/review.go index 3db73a09ebc..e2f65e369f1 100644 --- a/models/issues/review.go +++ b/models/issues/review.go @@ -460,8 +460,10 @@ func SubmitReview(ctx context.Context, doer *user_model.User, issue *Issue, revi func GetReviewByIssueIDAndUserID(ctx context.Context, issueID, userID int64) (*Review, error) { review := new(Review) - has, err := db.GetEngine(ctx).SQL("SELECT * FROM review WHERE id IN (SELECT max(id) as id FROM review WHERE issue_id = ? AND reviewer_id = ? AND original_author_id = 0 AND type in (?, ?, ?))", - issueID, userID, ReviewTypeApprove, ReviewTypeReject, ReviewTypeRequest). + has, err := db.GetEngine(ctx).Where( + builder.In("type", ReviewTypeApprove, ReviewTypeReject, ReviewTypeRequest). + And(builder.Eq{"issue_id": issueID, "reviewer_id": userID, "original_author_id": 0})). + Desc("id"). Get(review) if err != nil { return nil, err @@ -475,13 +477,13 @@ func GetReviewByIssueIDAndUserID(ctx context.Context, issueID, userID int64) (*R } // GetTeamReviewerByIssueIDAndTeamID get the latest review request of reviewer team for a pull request -func GetTeamReviewerByIssueIDAndTeamID(ctx context.Context, issueID, teamID int64) (review *Review, err error) { - review = new(Review) +func GetTeamReviewerByIssueIDAndTeamID(ctx context.Context, issueID, teamID int64) (*Review, error) { + review := new(Review) - var has bool - if has, err = db.GetEngine(ctx).SQL("SELECT * FROM review WHERE id IN (SELECT max(id) as id FROM review WHERE issue_id = ? AND reviewer_team_id = ?)", - issueID, teamID). - Get(review); err != nil { + has, err := db.GetEngine(ctx).Where(builder.Eq{"issue_id": issueID, "reviewer_team_id": teamID}). + Desc("id"). + Get(review) + if err != nil { return nil, err } From 3d98d99e27dfbe86227b0557d04b5e4ea1c6e946 Mon Sep 17 00:00:00 2001 From: Lunny Xiao Date: Thu, 21 Dec 2023 04:12:25 +0800 Subject: [PATCH 006/189] Update actions document about comparsion as Github Actions (#28560) --- docs/content/usage/actions/comparison.en-us.md | 8 ++++++++ docs/content/usage/actions/comparison.zh-cn.md | 8 ++++++++ 2 files changed, 16 insertions(+) diff --git a/docs/content/usage/actions/comparison.en-us.md b/docs/content/usage/actions/comparison.en-us.md index be40657bed7..4d725f7a7e8 100644 --- a/docs/content/usage/actions/comparison.en-us.md +++ b/docs/content/usage/actions/comparison.en-us.md @@ -29,6 +29,10 @@ Like `uses: https://github.com/actions/checkout@v3` or `uses: http://your_gitea. Gitea Actions supports writing actions in Go. See [Creating Go Actions](https://blog.gitea.com/creating-go-actions/). +### Support the non-standard syntax @yearly, @monthly, @weekly, @daily, @hourly on schedule + +Github Actions doesn't support that. https://docs.github.com/en/actions/using-workflows/events-that-trigger-workflows#schedule + ## Unsupported workflows syntax ### `concurrency` @@ -110,6 +114,10 @@ It's ignored by Gitea Actions now. Pre and Post steps don't have their own section in the job log user interface. +### Services steps + +Services steps don't have their own section in the job log user interface. + ## Different behavior ### Downloading actions diff --git a/docs/content/usage/actions/comparison.zh-cn.md b/docs/content/usage/actions/comparison.zh-cn.md index 1ef7d3ca989..da3abfe01e9 100644 --- a/docs/content/usage/actions/comparison.zh-cn.md +++ b/docs/content/usage/actions/comparison.zh-cn.md @@ -29,6 +29,10 @@ Gitea Actions支持通过URL绝对路径定义actions,这意味着您可以使 Gitea Actions支持使用Go编写Actions。 请参阅[创建Go Actions](https://blog.gitea.com/creating-go-actions/)。 +### 支持非标准的调度语法 @yearly, @monthly, @weekly, @daily, @hourly + +Github Actions 不支持这些语法,详见: https://docs.github.com/en/actions/using-workflows/events-that-trigger-workflows#schedule + ## 不支持的工作流语法 ### `concurrency` @@ -116,6 +120,10 @@ Gitea Actions目前不支持此功能。 预处理和后处理步骤在Job日志用户界面中没有自己的用户界面。 +### 服务步骤 + +服务步骤在Job日志用户界面中没有自己的用户界面。 + ## 不一样的行为 ### 下载Actions From caceb43313a586842e208249b2c67f90d4bf7139 Mon Sep 17 00:00:00 2001 From: Rui Chen Date: Thu, 21 Dec 2023 00:31:04 -0500 Subject: [PATCH 007/189] feat: bump `dessant/lock-threads` and `actions/setup-go` to use nodejs20 runtime (#28565) Update more actions to use nodejs20 runtime and also update the docs for checkout action usage. similar to: - #27836 - #27096 --------- Signed-off-by: Rui Chen --- .github/workflows/cron-licenses.yml | 2 +- .github/workflows/cron-lock.yml | 2 +- .github/workflows/pull-compliance.yml | 12 ++++++------ .github/workflows/pull-db-tests.yml | 10 +++++----- .github/workflows/pull-e2e-tests.yml | 2 +- .github/workflows/release-nightly.yml | 6 +++--- .github/workflows/release-tag-rc.yml | 2 +- .github/workflows/release-tag-version.yml | 2 +- .../administration/config-cheat-sheet.en-us.md | 6 +++--- .../administration/config-cheat-sheet.zh-cn.md | 6 +++--- docs/content/usage/actions/comparison.en-us.md | 6 +++--- docs/content/usage/actions/comparison.zh-cn.md | 8 ++++---- docs/content/usage/actions/design.en-us.md | 6 +++--- docs/content/usage/actions/design.zh-cn.md | 6 +++--- docs/content/usage/actions/faq.en-us.md | 4 ++-- docs/content/usage/actions/faq.zh-cn.md | 4 ++-- docs/content/usage/actions/overview.en-us.md | 2 +- docs/content/usage/actions/overview.zh-cn.md | 2 +- docs/content/usage/actions/quickstart.en-us.md | 2 +- docs/content/usage/actions/quickstart.zh-cn.md | 2 +- 20 files changed, 46 insertions(+), 46 deletions(-) diff --git a/.github/workflows/cron-licenses.yml b/.github/workflows/cron-licenses.yml index 6ef5813a64f..cd8386ecc52 100644 --- a/.github/workflows/cron-licenses.yml +++ b/.github/workflows/cron-licenses.yml @@ -11,7 +11,7 @@ jobs: if: github.repository == 'go-gitea/gitea' steps: - uses: actions/checkout@v4 - - uses: actions/setup-go@v4 + - uses: actions/setup-go@v5 with: go-version-file: go.mod check-latest: true diff --git a/.github/workflows/cron-lock.yml b/.github/workflows/cron-lock.yml index 935f926cce9..746ec49bc63 100644 --- a/.github/workflows/cron-lock.yml +++ b/.github/workflows/cron-lock.yml @@ -17,6 +17,6 @@ jobs: runs-on: ubuntu-latest if: github.repository == 'go-gitea/gitea' steps: - - uses: dessant/lock-threads@v4 + - uses: dessant/lock-threads@v5 with: issue-inactive-days: 45 diff --git a/.github/workflows/pull-compliance.yml b/.github/workflows/pull-compliance.yml index 6977dc32b29..0472d9a9f07 100644 --- a/.github/workflows/pull-compliance.yml +++ b/.github/workflows/pull-compliance.yml @@ -17,7 +17,7 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - - uses: actions/setup-go@v4 + - uses: actions/setup-go@v5 with: go-version-file: go.mod check-latest: true @@ -70,7 +70,7 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - - uses: actions/setup-go@v4 + - uses: actions/setup-go@v5 with: go-version-file: go.mod check-latest: true @@ -87,7 +87,7 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - - uses: actions/setup-go@v4 + - uses: actions/setup-go@v5 with: go-version-file: go.mod check-latest: true @@ -102,7 +102,7 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - - uses: actions/setup-go@v4 + - uses: actions/setup-go@v5 with: go-version-file: go.mod check-latest: true @@ -130,7 +130,7 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - - uses: actions/setup-go@v4 + - uses: actions/setup-go@v5 with: go-version-file: go.mod check-latest: true @@ -175,7 +175,7 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - - uses: actions/setup-go@v4 + - uses: actions/setup-go@v5 with: go-version-file: go.mod check-latest: true diff --git a/.github/workflows/pull-db-tests.yml b/.github/workflows/pull-db-tests.yml index 97446e6cd3b..a3886bf6180 100644 --- a/.github/workflows/pull-db-tests.yml +++ b/.github/workflows/pull-db-tests.yml @@ -39,7 +39,7 @@ jobs: - "9000:9000" steps: - uses: actions/checkout@v4 - - uses: actions/setup-go@v4 + - uses: actions/setup-go@v5 with: go-version-file: go.mod check-latest: true @@ -64,7 +64,7 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - - uses: actions/setup-go@v4 + - uses: actions/setup-go@v5 with: go-version-file: go.mod check-latest: true @@ -115,7 +115,7 @@ jobs: - "9000:9000" steps: - uses: actions/checkout@v4 - - uses: actions/setup-go@v4 + - uses: actions/setup-go@v5 with: go-version-file: go.mod check-latest: true @@ -165,7 +165,7 @@ jobs: - "993:993" steps: - uses: actions/checkout@v4 - - uses: actions/setup-go@v4 + - uses: actions/setup-go@v5 with: go-version-file: go.mod check-latest: true @@ -198,7 +198,7 @@ jobs: - "1433:1433" steps: - uses: actions/checkout@v4 - - uses: actions/setup-go@v4 + - uses: actions/setup-go@v5 with: go-version-file: go.mod check-latest: true diff --git a/.github/workflows/pull-e2e-tests.yml b/.github/workflows/pull-e2e-tests.yml index 540263788d4..5a249db9f8d 100644 --- a/.github/workflows/pull-e2e-tests.yml +++ b/.github/workflows/pull-e2e-tests.yml @@ -17,7 +17,7 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - - uses: actions/setup-go@v4 + - uses: actions/setup-go@v5 with: go-version-file: go.mod check-latest: true diff --git a/.github/workflows/release-nightly.yml b/.github/workflows/release-nightly.yml index ef1e63df2ff..80e6683919f 100644 --- a/.github/workflows/release-nightly.yml +++ b/.github/workflows/release-nightly.yml @@ -18,7 +18,7 @@ jobs: # fetch all commits instead of only the last as some branches are long lived and could have many between versions # fetch all tags to ensure that "git describe" reports expected Gitea version, eg. v1.21.0-dev-1-g1234567 - run: git fetch --unshallow --quiet --tags --force - - uses: actions/setup-go@v4 + - uses: actions/setup-go@v5 with: go-version-file: go.mod check-latest: true @@ -64,7 +64,7 @@ jobs: # fetch all commits instead of only the last as some branches are long lived and could have many between versions # fetch all tags to ensure that "git describe" reports expected Gitea version, eg. v1.21.0-dev-1-g1234567 - run: git fetch --unshallow --quiet --tags --force - - uses: actions/setup-go@v4 + - uses: actions/setup-go@v5 with: go-version-file: go.mod check-latest: true @@ -101,7 +101,7 @@ jobs: # fetch all commits instead of only the last as some branches are long lived and could have many between versions # fetch all tags to ensure that "git describe" reports expected Gitea version, eg. v1.21.0-dev-1-g1234567 - run: git fetch --unshallow --quiet --tags --force - - uses: actions/setup-go@v4 + - uses: actions/setup-go@v5 with: go-version-file: go.mod check-latest: true diff --git a/.github/workflows/release-tag-rc.yml b/.github/workflows/release-tag-rc.yml index d73d67aede7..12d1e1e4beb 100644 --- a/.github/workflows/release-tag-rc.yml +++ b/.github/workflows/release-tag-rc.yml @@ -17,7 +17,7 @@ jobs: # fetch all commits instead of only the last as some branches are long lived and could have many between versions # fetch all tags to ensure that "git describe" reports expected Gitea version, eg. v1.21.0-dev-1-g1234567 - run: git fetch --unshallow --quiet --tags --force - - uses: actions/setup-go@v4 + - uses: actions/setup-go@v5 with: go-version-file: go.mod check-latest: true diff --git a/.github/workflows/release-tag-version.yml b/.github/workflows/release-tag-version.yml index 0379350900a..e0e93633e8a 100644 --- a/.github/workflows/release-tag-version.yml +++ b/.github/workflows/release-tag-version.yml @@ -19,7 +19,7 @@ jobs: # fetch all commits instead of only the last as some branches are long lived and could have many between versions # fetch all tags to ensure that "git describe" reports expected Gitea version, eg. v1.21.0-dev-1-g1234567 - run: git fetch --unshallow --quiet --tags --force - - uses: actions/setup-go@v4 + - uses: actions/setup-go@v5 with: go-version-file: go.mod check-latest: true diff --git a/docs/content/administration/config-cheat-sheet.en-us.md b/docs/content/administration/config-cheat-sheet.en-us.md index 93a19cec4e7..64c2fa475cf 100644 --- a/docs/content/administration/config-cheat-sheet.en-us.md +++ b/docs/content/administration/config-cheat-sheet.en-us.md @@ -1399,8 +1399,8 @@ PROXY_HOSTS = *.github.com - `SKIP_WORKFLOW_STRINGS`: **[skip ci],[ci skip],[no ci],[skip actions],[actions skip]**: Strings committers can place inside a commit message to skip executing the corresponding actions workflow `DEFAULT_ACTIONS_URL` indicates where the Gitea Actions runners should find the actions with relative path. -For example, `uses: actions/checkout@v3` means `https://github.com/actions/checkout@v3` since the value of `DEFAULT_ACTIONS_URL` is `github`. -And it can be changed to `self` to make it `root_url_of_your_gitea/actions/checkout@v3`. +For example, `uses: actions/checkout@v4` means `https://github.com/actions/checkout@v4` since the value of `DEFAULT_ACTIONS_URL` is `github`. +And it can be changed to `self` to make it `root_url_of_your_gitea/actions/checkout@v4`. Please note that using `self` is not recommended for most cases, as it could make names globally ambiguous. Additionally, it requires you to mirror all the actions you need to your Gitea instance, which may not be worth it. @@ -1409,7 +1409,7 @@ Therefore, please use `self` only if you understand what you are doing. In earlier versions (`<= 1.19`), `DEFAULT_ACTIONS_URL` could be set to any custom URLs like `https://gitea.com` or `http://your-git-server,https://gitea.com`, and the default value was `https://gitea.com`. However, later updates removed those options, and now the only options are `github` and `self`, with the default value being `github`. However, if you want to use actions from other git server, you can use a complete URL in `uses` field, it's supported by Gitea (but not GitHub). -Like `uses: https://gitea.com/actions/checkout@v3` or `uses: http://your-git-server/actions/checkout@v3`. +Like `uses: https://gitea.com/actions/checkout@v4` or `uses: http://your-git-server/actions/checkout@v4`. ## Other (`other`) diff --git a/docs/content/administration/config-cheat-sheet.zh-cn.md b/docs/content/administration/config-cheat-sheet.zh-cn.md index 596e82a12a0..befce0a1b71 100644 --- a/docs/content/administration/config-cheat-sheet.zh-cn.md +++ b/docs/content/administration/config-cheat-sheet.zh-cn.md @@ -1335,8 +1335,8 @@ PROXY_HOSTS = *.github.com - `MINIO_BASE_PATH`: **actions_log/**:Minio存储桶上的基本路径,仅在`STORAGE_TYPE`为`minio`时可用。 `DEFAULT_ACTIONS_URL` 指示 Gitea 操作运行程序应该在哪里找到带有相对路径的操作。 -例如,`uses: actions/checkout@v3` 表示 `https://github.com/actions/checkout@v3`,因为 `DEFAULT_ACTIONS_URL` 的值为 `github`。 -它可以更改为 `self`,以使其成为 `root_url_of_your_gitea/actions/checkout@v3`。 +例如,`uses: actions/checkout@v4` 表示 `https://github.com/actions/checkout@v4`,因为 `DEFAULT_ACTIONS_URL` 的值为 `github`。 +它可以更改为 `self`,以使其成为 `root_url_of_your_gitea/actions/checkout@v4`。 请注意,对于大多数情况,不建议使用 `self`,因为它可能使名称在全局范围内产生歧义。 此外,它要求您将所有所需的操作镜像到您的 Gitea 实例,这可能不值得。 @@ -1345,7 +1345,7 @@ PROXY_HOSTS = *.github.com 在早期版本(`<= 1.19`)中,`DEFAULT_ACTIONS_URL` 可以设置为任何自定义 URL,例如 `https://gitea.com` 或 `http://your-git-server,https://gitea.com`,默认值为 `https://gitea.com`。 然而,后来的更新删除了这些选项,现在唯一的选项是 `github` 和 `self`,默认值为 `github`。 但是,如果您想要使用其他 Git 服务器中的操作,您可以在 `uses` 字段中使用完整的 URL,Gitea 支持此功能(GitHub 不支持)。 -例如 `uses: https://gitea.com/actions/checkout@v3` 或 `uses: http://your-git-server/actions/checkout@v3`。 +例如 `uses: https://gitea.com/actions/checkout@v4` 或 `uses: http://your-git-server/actions/checkout@v4`。 ## 其他 (`other`) diff --git a/docs/content/usage/actions/comparison.en-us.md b/docs/content/usage/actions/comparison.en-us.md index 4d725f7a7e8..1ea3afac5bf 100644 --- a/docs/content/usage/actions/comparison.en-us.md +++ b/docs/content/usage/actions/comparison.en-us.md @@ -22,7 +22,7 @@ Even though Gitea Actions is designed to be compatible with GitHub Actions, ther ### Absolute action URLs Gitea Actions supports defining actions via absolute URL, which means that you can use actions from any git repository. -Like `uses: https://github.com/actions/checkout@v3` or `uses: http://your_gitea.com/owner/repo@branch`. +Like `uses: https://github.com/actions/checkout@v4` or `uses: http://your_gitea.com/owner/repo@branch`. ### Actions written in Go @@ -125,9 +125,9 @@ Services steps don't have their own section in the job log user interface. Previously (Pre 1.21.0), `[actions].DEFAULT_ACTIONS_URL` defaulted to `https://gitea.com`. We have since restricted this option to only allow two values (`github` and `self`). When set to `github`, the new default, Gitea will download non-fully-qualified actions from `https://github.com`. -For example, if you use `uses: actions/checkout@v3`, it will download the checkout repository from `https://github.com/actions/checkout.git`. +For example, if you use `uses: actions/checkout@v4`, it will download the checkout repository from `https://github.com/actions/checkout.git`. -If you want to download an action from another git hoster, you can use an absolute URL, e.g. `uses: https://gitea.com/actions/checkout@v3`. +If you want to download an action from another git hoster, you can use an absolute URL, e.g. `uses: https://gitea.com/actions/checkout@v4`. If your Gitea instance is in an intranet or a restricted area, you can set the URL to `self` to only download actions from your own instance by default. Of course, you can still use absolute URLs in workflows. diff --git a/docs/content/usage/actions/comparison.zh-cn.md b/docs/content/usage/actions/comparison.zh-cn.md index da3abfe01e9..006fc8de3f5 100644 --- a/docs/content/usage/actions/comparison.zh-cn.md +++ b/docs/content/usage/actions/comparison.zh-cn.md @@ -22,7 +22,7 @@ menu: ### Action URL绝对路径 Gitea Actions支持通过URL绝对路径定义actions,这意味着您可以使用来自任何Git存储库的Actions。 -例如,`uses: https://github.com/actions/checkout@v3`或`uses: http://your_gitea.com/owner/repo@branch`。 +例如,`uses: https://github.com/actions/checkout@v4`或`uses: http://your_gitea.com/owner/repo@branch`。 ### 使用Go编写Actions @@ -129,10 +129,10 @@ Gitea Actions目前不支持此功能。 ### 下载Actions 当 `[actions].DEFAULT_ACTIONS_URL` 保持默认值为 `github` 时,Gitea将会从 https://github.com 下载相对路径的actions。比如: -如果你使用 `uses: actions/checkout@v3`,Gitea将会从 https://github.com/actions/checkout.git 下载这个 actions 项目。 -如果你想要从另外一个 Git服务下载actions,你只需要使用绝对URL `uses: https://gitea.com/actions/checkout@v3` 来下载。 +如果你使用 `uses: actions/checkout@v4`,Gitea将会从 https://github.com/actions/checkout.git 下载这个 actions 项目。 +如果你想要从另外一个 Git服务下载actions,你只需要使用绝对URL `uses: https://gitea.com/actions/checkout@v4` 来下载。 -如果你的 Gitea 实例是部署在一个互联网限制的网络中,有可以使用绝对地址来下载 actions。你也可以讲配置项修改为 `[actions].DEFAULT_ACTIONS_URL = self`。这样所有的相对路径的actions引用,将不再会从 github.com 去下载,而会从这个 Gitea 实例自己的仓库中去下载。例如: `uses: actions/checkout@v3` 将会从 `[server].ROOT_URL`/actions/checkout.git 这个地址去下载 actions。 +如果你的 Gitea 实例是部署在一个互联网限制的网络中,有可以使用绝对地址来下载 actions。你也可以讲配置项修改为 `[actions].DEFAULT_ACTIONS_URL = self`。这样所有的相对路径的actions引用,将不再会从 github.com 去下载,而会从这个 Gitea 实例自己的仓库中去下载。例如: `uses: actions/checkout@v4` 将会从 `[server].ROOT_URL`/actions/checkout.git 这个地址去下载 actions。 设置`[actions].DEFAULT_ACTIONS_URL`进行配置。请参阅[配置备忘单](administration/config-cheat-sheet.md#actions-actions)。 diff --git a/docs/content/usage/actions/design.en-us.md b/docs/content/usage/actions/design.en-us.md index 8394e822dc6..29fa433e59b 100644 --- a/docs/content/usage/actions/design.en-us.md +++ b/docs/content/usage/actions/design.en-us.md @@ -95,7 +95,7 @@ The act runner must be able to connect to Gitea to receive tasks and send back t ### Connection 2, job containers to Gitea instance The job containers have different network namespaces than the runner, even if they are on the same machine. -They need to connect to Gitea to fetch codes if there is `actions/checkout@v3` in the workflow, for example. +They need to connect to Gitea to fetch codes if there is `actions/checkout@v4` in the workflow, for example. Fetching code is not always necessary to run some jobs, but it is required in most cases. If you use a loopback address to register a runner, the runner can connect to Gitea when it is on the same machine. @@ -103,7 +103,7 @@ However, if a job container tries to fetch code from localhost, it will fail bec ### Connection 3, act runner to internet -When you use some actions like `actions/checkout@v3`, the act runner downloads the scripts, not the job containers. +When you use some actions like `actions/checkout@v4`, the act runner downloads the scripts, not the job containers. By default, it downloads from [gitea.com](http://gitea.com/), so it requires access to the internet. It also downloads some docker images from Docker Hub by default, which also requires internet access. @@ -116,7 +116,7 @@ And [Gitea Container Registry](usage/packages/container.md) can be used as a Doc ### Connection 4, job containers to internet -When using actions such as `actions/setup-go@v4`, it may be necessary to download resources from the internet to set up the Go language environment in job containers. +When using actions such as `actions/setup-go@v5`, it may be necessary to download resources from the internet to set up the Go language environment in job containers. Therefore, access to the internet is required for the successful completion of these actions. However, it is optional as well. diff --git a/docs/content/usage/actions/design.zh-cn.md b/docs/content/usage/actions/design.zh-cn.md index 06f600f3915..8add1cf7c54 100644 --- a/docs/content/usage/actions/design.zh-cn.md +++ b/docs/content/usage/actions/design.zh-cn.md @@ -96,7 +96,7 @@ act runner 必须能够连接到Gitea以接收任务并发送执行结果回来 ### 连接 2,Job容器到Gitea实例 即使Job容器位于同一台机器上,它们的网络命名空间与Runner不同。 -举个例子,如果工作流中包含 `actions/checkout@v3`,Job容器需要连接到Gitea来获取代码。 +举个例子,如果工作流中包含 `actions/checkout@v4`,Job容器需要连接到Gitea来获取代码。 获取代码并不总是运行某些Job所必需的,但在大多数情况下是必需的。 如果您使用回环地址注册Runner,当Runner与Gitea在同一台机器上时,Runner可以连接到Gitea。 @@ -104,7 +104,7 @@ act runner 必须能够连接到Gitea以接收任务并发送执行结果回来 ### 连接 3,act runner到互联网 -当您使用诸如 `actions/checkout@v3` 的一些Actions时,act runner下载的是脚本,而不是Job容器。 +当您使用诸如 `actions/checkout@v4` 的一些Actions时,act runner下载的是脚本,而不是Job容器。 默认情况下,它从[gitea.com](http://gitea.com/)下载,因此需要访问互联网。 它还默认从Docker Hub下载一些Docker镜像,这也需要互联网访问。 @@ -117,7 +117,7 @@ act runner 必须能够连接到Gitea以接收任务并发送执行结果回来 ### 连接 4,Job容器到互联网 -当使用诸如`actions/setup-go@v4`的Actions时,可能需要从互联网下载资源,以设置Job容器中的Go语言环境。 +当使用诸如`actions/setup-go@v5`的Actions时,可能需要从互联网下载资源,以设置Job容器中的Go语言环境。 因此,成功完成这些Actions需要访问互联网。 然而,这也是可选的。 diff --git a/docs/content/usage/actions/faq.en-us.md b/docs/content/usage/actions/faq.en-us.md index 1d59872936a..7ed59e02cdc 100644 --- a/docs/content/usage/actions/faq.en-us.md +++ b/docs/content/usage/actions/faq.en-us.md @@ -43,10 +43,10 @@ Still, this is completely optional since both options have the same effect at th Not yet. It is technically possible to implement, but we need to discuss whether it is necessary. -## Where will the runner download scripts when using actions such as `actions/checkout@v3`? +## Where will the runner download scripts when using actions such as `actions/checkout@v4`? You may be aware that there are tens of thousands of [marketplace actions](https://github.com/marketplace?type=actions) in GitHub. -However, when you write `uses: actions/checkout@v3`, it actually downloads the scripts from [gitea.com/actions/checkout](http://gitea.com/actions/checkout) by default (not GitHub). +However, when you write `uses: actions/checkout@v4`, it actually downloads the scripts from [gitea.com/actions/checkout](http://gitea.com/actions/checkout) by default (not GitHub). This is a mirror of [github.com/actions/checkout](http://github.com/actions/checkout), but it's impossible to mirror all of them. That's why you may encounter failures when trying to use some actions that haven't been mirrored. diff --git a/docs/content/usage/actions/faq.zh-cn.md b/docs/content/usage/actions/faq.zh-cn.md index 7bb79d02fc4..ba5f87bf0c4 100644 --- a/docs/content/usage/actions/faq.zh-cn.md +++ b/docs/content/usage/actions/faq.zh-cn.md @@ -43,10 +43,10 @@ DEFAULT_REPO_UNITS = ...,repo.actions 目前还不可以。 从技术上讲是可以实现的,但我们需要讨论是否有必要。 -## 使用`actions/checkout@v3`等Actions时,Job容器会从何处下载脚本? +## 使用`actions/checkout@v4`等Actions时,Job容器会从何处下载脚本? 您可能知道GitHub上有成千上万个[Actions市场](https://github.com/marketplace?type=actions)。 -然而,当您编写`uses: actions/checkout@v3`时,它实际上默认从[gitea.com/actions/checkout](http://gitea.com/actions/checkout)下载脚本(而不是从GitHub下载)。 +然而,当您编写`uses: actions/checkout@v4`时,它实际上默认从[gitea.com/actions/checkout](http://gitea.com/actions/checkout)下载脚本(而不是从GitHub下载)。 这是[github.com/actions/checkout](http://github.com/actions/checkout)的镜像,但无法将它们全部镜像。 这就是为什么在尝试使用尚未镜像的某些Actions时可能会遇到失败的原因。 diff --git a/docs/content/usage/actions/overview.en-us.md b/docs/content/usage/actions/overview.en-us.md index 59e539f9c1b..135fdfd4337 100644 --- a/docs/content/usage/actions/overview.en-us.md +++ b/docs/content/usage/actions/overview.en-us.md @@ -25,7 +25,7 @@ To avoid confusion, we have clarified the spelling here: - "Gitea Actions" (with an "s", both words capitalized) is the name of the Gitea feature. - "GitHub Actions" is the name of the GitHub feature. - "Actions" could refer to either of the above, depending on the context. So it refers to "Gitea Actions" in this document. -- "action" or "actions" refer to some scripts/plugins to be used, like "actions/checkout@v3" or "actions/cache@v3". +- "action" or "actions" refer to some scripts/plugins to be used, like "actions/checkout@v4" or "actions/cache@v3". ## Runners diff --git a/docs/content/usage/actions/overview.zh-cn.md b/docs/content/usage/actions/overview.zh-cn.md index 0e57bf568f8..a2ec3070bcf 100644 --- a/docs/content/usage/actions/overview.zh-cn.md +++ b/docs/content/usage/actions/overview.zh-cn.md @@ -25,7 +25,7 @@ Gitea Actions与[GitHub Actions](https://github.com/features/actions)相似且 - "Gitea Actions"(两个单词都大写且带有"s")是Gitea功能的名称。 - "GitHub Actions"是GitHub功能的名称。 - "Actions"根据上下文的不同可以指代以上任意一个。在本文档中指代的是"Gitea Actions"。 -- "action"或"actions"指代一些要使用的脚本/插件,比如"actions/checkout@v3"或"actions/cache@v3"。 +- "action"或"actions"指代一些要使用的脚本/插件,比如"actions/checkout@v4"或"actions/cache@v3"。 ## Runner diff --git a/docs/content/usage/actions/quickstart.en-us.md b/docs/content/usage/actions/quickstart.en-us.md index f7f4ee2c366..2a2cf725847 100644 --- a/docs/content/usage/actions/quickstart.en-us.md +++ b/docs/content/usage/actions/quickstart.en-us.md @@ -113,7 +113,7 @@ jobs: - run: echo "🐧 This job is now running on a ${{ runner.os }} server hosted by Gitea!" - run: echo "🔎 The name of your branch is ${{ gitea.ref }} and your repository is ${{ gitea.repository }}." - name: Check out repository code - uses: actions/checkout@v3 + uses: actions/checkout@v4 - run: echo "💡 The ${{ gitea.repository }} repository has been cloned to the runner." - run: echo "🖥️ The workflow is now ready to test your code on the runner." - name: List files in the repository diff --git a/docs/content/usage/actions/quickstart.zh-cn.md b/docs/content/usage/actions/quickstart.zh-cn.md index ffc1f07df25..8fccc6c909c 100644 --- a/docs/content/usage/actions/quickstart.zh-cn.md +++ b/docs/content/usage/actions/quickstart.zh-cn.md @@ -112,7 +112,7 @@ jobs: - run: echo "🐧 This job is now running on a ${{ runner.os }} server hosted by Gitea!" - run: echo "🔎 The name of your branch is ${{ gitea.ref }} and your repository is ${{ gitea.repository }}." - name: Check out repository code - uses: actions/checkout@v3 + uses: actions/checkout@v4 - run: echo "💡 The ${{ gitea.repository }} repository has been cloned to the runner." - run: echo "🖥️ The workflow is now ready to test your code on the runner." - name: List files in the repository From fe5a61639237138d6bb87cde17aedca3eb5bdd12 Mon Sep 17 00:00:00 2001 From: FuXiaoHei Date: Thu, 21 Dec 2023 15:04:50 +0800 Subject: [PATCH 008/189] Fix merging artifact chunks error when minio storage basepath is set (#28555) Related to https://github.com/go-gitea/gitea/issues/28279 When merging artifact chunks, it lists chunks from storage. When storage is minio, chunk's path contains `MINIO_BASE_PATH` that makes merging break. So trim the `MINIO_BASE_PATH` when handle chunks. Update the chunk file's basename to retain necessary information. It ensures that the directory in the chunk's path remains unaffected. --- routers/api/actions/artifacts_chunks.go | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/routers/api/actions/artifacts_chunks.go b/routers/api/actions/artifacts_chunks.go index c7ab70afa95..36432a0ca08 100644 --- a/routers/api/actions/artifacts_chunks.go +++ b/routers/api/actions/artifacts_chunks.go @@ -26,10 +26,11 @@ func saveUploadChunk(st storage.ObjectStorage, ctx *ArtifactContext, contentRange := ctx.Req.Header.Get("Content-Range") start, end, length := int64(0), int64(0), int64(0) if _, err := fmt.Sscanf(contentRange, "bytes %d-%d/%d", &start, &end, &length); err != nil { + log.Warn("parse content range error: %v, content-range: %s", err, contentRange) return -1, fmt.Errorf("parse content range error: %v", err) } // build chunk store path - storagePath := fmt.Sprintf("tmp%d/%d-%d-%d.chunk", runID, artifact.ID, start, end) + storagePath := fmt.Sprintf("tmp%d/%d-%d-%d-%d.chunk", runID, runID, artifact.ID, start, end) // use io.TeeReader to avoid reading all body to md5 sum. // it writes data to hasher after reading end // if hash is not matched, delete the read-end result @@ -58,6 +59,7 @@ func saveUploadChunk(st storage.ObjectStorage, ctx *ArtifactContext, } type chunkFileItem struct { + RunID int64 ArtifactID int64 Start int64 End int64 @@ -67,9 +69,12 @@ type chunkFileItem struct { func listChunksByRunID(st storage.ObjectStorage, runID int64) (map[int64][]*chunkFileItem, error) { storageDir := fmt.Sprintf("tmp%d", runID) var chunks []*chunkFileItem - if err := st.IterateObjects(storageDir, func(path string, obj storage.Object) error { - item := chunkFileItem{Path: path} - if _, err := fmt.Sscanf(path, filepath.Join(storageDir, "%d-%d-%d.chunk"), &item.ArtifactID, &item.Start, &item.End); err != nil { + if err := st.IterateObjects(storageDir, func(fpath string, obj storage.Object) error { + baseName := filepath.Base(fpath) + // when read chunks from storage, it only contains storage dir and basename, + // no matter the subdirectory setting in storage config + item := chunkFileItem{Path: storageDir + "/" + baseName} + if _, err := fmt.Sscanf(baseName, "%d-%d-%d-%d.chunk", &item.RunID, &item.ArtifactID, &item.Start, &item.End); err != nil { return fmt.Errorf("parse content range error: %v", err) } chunks = append(chunks, &item) From 177cea7c70473e375c1695f1e20fb9d538ff78fb Mon Sep 17 00:00:00 2001 From: Lunny Xiao Date: Thu, 21 Dec 2023 15:42:16 +0800 Subject: [PATCH 009/189] Make offline mode as default to no connect external avatar service by default (#28548) To keep user's privacy, make offline mode as true by default. Users can still change it from installation ui and app.ini --- custom/conf/app.example.ini | 2 +- docs/content/administration/config-cheat-sheet.en-us.md | 2 +- docs/content/administration/config-cheat-sheet.zh-cn.md | 2 +- modules/repository/commits_test.go | 3 ++- modules/setting/server.go | 2 +- 5 files changed, 6 insertions(+), 5 deletions(-) diff --git a/custom/conf/app.example.ini b/custom/conf/app.example.ini index f10a3f2edff..f9111d541c7 100644 --- a/custom/conf/app.example.ini +++ b/custom/conf/app.example.ini @@ -234,7 +234,7 @@ RUN_USER = ; git ;MINIMUM_KEY_SIZE_CHECK = false ;; ;; Disable CDN even in "prod" mode -;OFFLINE_MODE = false +;OFFLINE_MODE = true ;; ;; TLS Settings: Either ACME or manual ;; (Other common TLS configuration are found before) diff --git a/docs/content/administration/config-cheat-sheet.en-us.md b/docs/content/administration/config-cheat-sheet.en-us.md index 64c2fa475cf..1ba5dd04cc4 100644 --- a/docs/content/administration/config-cheat-sheet.en-us.md +++ b/docs/content/administration/config-cheat-sheet.en-us.md @@ -357,7 +357,7 @@ The following configuration set `Content-Type: application/vnd.android.package-a - `SSH_PER_WRITE_PER_KB_TIMEOUT`: **10s**: Timeout per Kb written to SSH connections. - `MINIMUM_KEY_SIZE_CHECK`: **true**: Indicate whether to check minimum key size with corresponding type. -- `OFFLINE_MODE`: **false**: Disables use of CDN for static files and Gravatar for profile pictures. +- `OFFLINE_MODE`: **true**: Disables use of CDN for static files and Gravatar for profile pictures. - `CERT_FILE`: **https/cert.pem**: Cert file path used for HTTPS. When chaining, the server certificate must come first, then intermediate CA certificates (if any). This is ignored if `ENABLE_ACME=true`. Paths are relative to `CUSTOM_PATH`. - `KEY_FILE`: **https/key.pem**: Key file path used for HTTPS. This is ignored if `ENABLE_ACME=true`. Paths are relative to `CUSTOM_PATH`. - `STATIC_ROOT_PATH`: **_`StaticRootPath`_**: Upper level of template and static files path. diff --git a/docs/content/administration/config-cheat-sheet.zh-cn.md b/docs/content/administration/config-cheat-sheet.zh-cn.md index befce0a1b71..434d69815b1 100644 --- a/docs/content/administration/config-cheat-sheet.zh-cn.md +++ b/docs/content/administration/config-cheat-sheet.zh-cn.md @@ -346,7 +346,7 @@ menu: - `SSH_PER_WRITE_TIMEOUT`: **30s**:对 SSH 连接的任何写入设置超时。(将其设置为 -1 可以禁用所有超时。) - `SSH_PER_WRITE_PER_KB_TIMEOUT`: **10s**:对写入 SSH 连接的每 KB 设置超时。 - `MINIMUM_KEY_SIZE_CHECK`: **true**:指示是否检查最小密钥大小与相应类型。 -- `OFFLINE_MODE`: **false**:禁用 CDN 用于静态文件和 Gravatar 用于个人资料图片。 +- `OFFLINE_MODE`: **true**:禁用 CDN 用于静态文件和 Gravatar 用于个人资料图片。 - `CERT_FILE`: **https/cert.pem**:用于 HTTPS 的证书文件路径。在链接时,服务器证书必须首先出现,然后是中间 CA 证书(如果有)。如果 `ENABLE_ACME=true`,则此设置会被忽略。路径相对于 `CUSTOM_PATH`。 - `KEY_FILE`: **https/key.pem**:用于 HTTPS 的密钥文件路径。如果 `ENABLE_ACME=true`,则此设置会被忽略。路径相对于 `CUSTOM_PATH`。 - `STATIC_ROOT_PATH`: **_`StaticRootPath`_**:模板和静态文件路径的上一级。 diff --git a/modules/repository/commits_test.go b/modules/repository/commits_test.go index 827b2a98493..248673a907d 100644 --- a/modules/repository/commits_test.go +++ b/modules/repository/commits_test.go @@ -126,9 +126,10 @@ func TestPushCommits_AvatarLink(t *testing.T) { } setting.GravatarSource = "https://secure.gravatar.com/avatar" + setting.OfflineMode = true assert.Equal(t, - "https://secure.gravatar.com/avatar/ab53a2911ddf9b4817ac01ddcd3d975f?d=identicon&s="+strconv.Itoa(28*setting.Avatar.RenderedSizeFactor), + "/avatars/avatar2?size="+strconv.Itoa(28*setting.Avatar.RenderedSizeFactor), pushCommits.AvatarLink(db.DefaultContext, "user2@example.com")) assert.Equal(t, diff --git a/modules/setting/server.go b/modules/setting/server.go index d053fee5e76..80b85eeebdd 100644 --- a/modules/setting/server.go +++ b/modules/setting/server.go @@ -315,7 +315,7 @@ func loadServerFrom(rootCfg ConfigProvider) { RedirectOtherPort = sec.Key("REDIRECT_OTHER_PORT").MustBool(false) PortToRedirect = sec.Key("PORT_TO_REDIRECT").MustString("80") RedirectorUseProxyProtocol = sec.Key("REDIRECTOR_USE_PROXY_PROTOCOL").MustBool(UseProxyProtocol) - OfflineMode = sec.Key("OFFLINE_MODE").MustBool() + OfflineMode = sec.Key("OFFLINE_MODE").MustBool(true) if len(StaticRootPath) == 0 { StaticRootPath = AppWorkPath } From 31426938928c89a9441dcf04b767db60c666e09a Mon Sep 17 00:00:00 2001 From: KN4CK3R Date: Thu, 21 Dec 2023 22:48:18 +0100 Subject: [PATCH 010/189] Use information from previous blame parts (#28572) Fixes #28545 `git blame` output can contain blocks without commit information if it was outputted before (the `0dafa97ea3f6d9662299579e5be1875cd28baaae 48 26 1` line): ``` fec25436488499df7231f63b857f66457c193d5c 24 25 1 author Bastien Montagne author-mail author-time 1660731031 author-tz +0200 committer Bastien Montagne committer-mail committer-time 1660731031 committer-tz +0200 summary LibOverride: Add Make/Reset/Clear entries to IDTemplate contextual menu. previous 839ece6477203382b7a7483062961540180ff1cd source/blender/editors/interface/interface_ops.c filename source/blender/editors/interface/interface_ops.c #include "BLT_translation.h" 0dafa97ea3f6d9662299579e5be1875cd28baaae 48 26 1 3d57bc4397fca53bc9702a27bbf50102827829b0 27 27 1 author Hans Goudey author-mail author-time 1700131315 author-tz +0100 committer Hans Goudey committer-mail committer-time 1700131315 committer-tz +0100 summary Cleanup: Move several blenkernel headers to C++ previous 451c054d9b7d3148a646caa5a72fb127a5b5c408 source/blender/editors/interface/interface_ops.cc filename source/blender/editors/interface/interface_ops.cc #include "BKE_context.hh" ``` This PR reuses data from the previous blame part to fill these gaps. --- routers/web/repo/blame.go | 22 +++++++++++++++++----- 1 file changed, 17 insertions(+), 5 deletions(-) diff --git a/routers/web/repo/blame.go b/routers/web/repo/blame.go index b2374e32c28..d414779a14e 100644 --- a/routers/web/repo/blame.go +++ b/routers/web/repo/blame.go @@ -125,7 +125,7 @@ func RefBlame(ctx *context.Context) { } type blameResult struct { - Parts []git.BlamePart + Parts []*git.BlamePart UsesIgnoreRevs bool FaultyIgnoreRevsFile bool } @@ -175,7 +175,9 @@ func performBlame(ctx *context.Context, repoPath string, commit *git.Commit, fil func fillBlameResult(br *git.BlameReader, r *blameResult) error { r.UsesIgnoreRevs = br.UsesIgnoreRevs() - r.Parts = make([]git.BlamePart, 0, 5) + previousHelper := make(map[string]*git.BlamePart) + + r.Parts = make([]*git.BlamePart, 0, 5) for { blamePart, err := br.NextPart() if err != nil { @@ -184,13 +186,23 @@ func fillBlameResult(br *git.BlameReader, r *blameResult) error { if blamePart == nil { break } - r.Parts = append(r.Parts, *blamePart) + + if prev, ok := previousHelper[blamePart.Sha]; ok { + if blamePart.PreviousSha == "" { + blamePart.PreviousSha = prev.PreviousSha + blamePart.PreviousPath = prev.PreviousPath + } + } else { + previousHelper[blamePart.Sha] = blamePart + } + + r.Parts = append(r.Parts, blamePart) } return nil } -func processBlameParts(ctx *context.Context, blameParts []git.BlamePart) map[string]*user_model.UserCommit { +func processBlameParts(ctx *context.Context, blameParts []*git.BlamePart) map[string]*user_model.UserCommit { // store commit data by SHA to look up avatar info etc commitNames := make(map[string]*user_model.UserCommit) // and as blameParts can reference the same commits multiple @@ -232,7 +244,7 @@ func processBlameParts(ctx *context.Context, blameParts []git.BlamePart) map[str return commitNames } -func renderBlame(ctx *context.Context, blameParts []git.BlamePart, commitNames map[string]*user_model.UserCommit) { +func renderBlame(ctx *context.Context, blameParts []*git.BlamePart, commitNames map[string]*user_model.UserCommit) { repoLink := ctx.Repo.RepoLink language := "" From b35d3fddfac389a7be401a63b4e1283dd74af681 Mon Sep 17 00:00:00 2001 From: Lunny Xiao Date: Fri, 22 Dec 2023 06:25:57 +0800 Subject: [PATCH 011/189] improve possible performance bottleneck (#28547) Replace #28500 --------- Co-authored-by: Giteabot --- models/issues/comment.go | 11 +++-------- 1 file changed, 3 insertions(+), 8 deletions(-) diff --git a/models/issues/comment.go b/models/issues/comment.go index ba5aed9c652..ce5cf5902d7 100644 --- a/models/issues/comment.go +++ b/models/issues/comment.go @@ -1161,14 +1161,9 @@ func DeleteComment(ctx context.Context, comment *Comment) error { // UpdateCommentsMigrationsByType updates comments' migrations information via given git service type and original id and poster id func UpdateCommentsMigrationsByType(ctx context.Context, tp structs.GitServiceType, originalAuthorID string, posterID int64) error { _, err := db.GetEngine(ctx).Table("comment"). - Where(builder.In("issue_id", - builder.Select("issue.id"). - From("issue"). - InnerJoin("repository", "issue.repo_id = repository.id"). - Where(builder.Eq{ - "repository.original_service_type": tp, - }), - )). + Join("INNER", "issue", "issue.id = comment.issue_id"). + Join("INNER", "repository", "issue.repo_id = repository.id"). + Where("repository.original_service_type = ?", tp). And("comment.original_author_id = ?", originalAuthorID). Update(map[string]any{ "poster_id": posterID, From 04b235d094218b780b62f024b7ae9716ad2e633f Mon Sep 17 00:00:00 2001 From: wxiaoguang Date: Fri, 22 Dec 2023 07:09:14 +0800 Subject: [PATCH 012/189] Fix 500 error of searching commits (#28576) Regression of #28454 . Now the string is escaped HTML, so it doesn't need `| Safe`. Fix #28575 --- templates/code/searchresults.tmpl | 2 +- templates/repo/search.tmpl | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/templates/code/searchresults.tmpl b/templates/code/searchresults.tmpl index 28c33a26de9..bb21a5e0dca 100644 --- a/templates/code/searchresults.tmpl +++ b/templates/code/searchresults.tmpl @@ -31,7 +31,7 @@ {{.}} {{end}} - {{.FormattedLines | Safe}} + {{.FormattedLines}} diff --git a/templates/repo/search.tmpl b/templates/repo/search.tmpl index b6c90de32f6..b616b4de323 100644 --- a/templates/repo/search.tmpl +++ b/templates/repo/search.tmpl @@ -53,7 +53,7 @@ {{.}} {{end}} - {{.FormattedLines | Safe}} + {{.FormattedLines}} From 838db2f8911690fa2115c6827ed73687db71bef1 Mon Sep 17 00:00:00 2001 From: KN4CK3R Date: Fri, 22 Dec 2023 00:59:59 +0100 Subject: [PATCH 013/189] Convert to url auth to header auth in tests (#28484) Related #28390 --- .../integration/api_actions_artifact_test.go | 89 ++++---- .../api_activitypub_person_test.go | 4 +- tests/integration/api_admin_org_test.go | 9 +- tests/integration/api_admin_test.go | 89 ++++---- tests/integration/api_branch_test.go | 23 +- .../api_comment_attachment_test.go | 31 +-- tests/integration/api_comment_test.go | 36 +-- tests/integration/api_gpg_keys_test.go | 36 +-- .../api_helper_for_declarative_test.go | 108 ++++----- tests/integration/api_httpsig_test.go | 14 +- .../integration/api_issue_attachment_test.go | 26 +-- tests/integration/api_issue_label_test.go | 58 ++--- tests/integration/api_issue_milestone_test.go | 23 +- tests/integration/api_issue_pin_test.go | 62 ++---- tests/integration/api_issue_reaction_test.go | 34 +-- tests/integration/api_issue_stopwatch_test.go | 12 +- .../api_issue_subscription_test.go | 20 +- tests/integration/api_issue_test.go | 12 +- .../api_issue_tracked_time_test.go | 19 +- tests/integration/api_keys_test.go | 54 ++--- tests/integration/api_nodeinfo_test.go | 2 +- tests/integration/api_notification_test.go | 45 ++-- tests/integration/api_oauth2_apps_test.go | 24 +- tests/integration/api_org_avatar_test.go | 12 +- tests/integration/api_org_test.go | 34 +-- tests/integration/api_packages_alpine_test.go | 12 +- tests/integration/api_packages_cargo_test.go | 36 +-- tests/integration/api_packages_chef_test.go | 83 +++---- .../integration/api_packages_composer_test.go | 32 +-- tests/integration/api_packages_conan_test.go | 112 +++++----- tests/integration/api_packages_conda_test.go | 16 +- .../api_packages_container_test.go | 210 +++++++++--------- tests/integration/api_packages_cran_test.go | 45 ++-- tests/integration/api_packages_debian_test.go | 28 +-- .../integration/api_packages_generic_test.go | 48 ++-- .../integration/api_packages_goproxy_test.go | 16 +- tests/integration/api_packages_helm_test.go | 16 +- tests/integration/api_packages_maven_test.go | 36 +-- tests/integration/api_packages_npm_test.go | 56 ++--- tests/integration/api_packages_nuget_test.go | 137 ++++++------ tests/integration/api_packages_pub_test.go | 14 +- tests/integration/api_packages_pypi_test.go | 14 +- tests/integration/api_packages_rpm_test.go | 16 +- .../integration/api_packages_rubygems_test.go | 22 +- tests/integration/api_packages_swift_test.go | 70 +++--- tests/integration/api_packages_test.go | 65 +++--- .../integration/api_packages_vagrant_test.go | 12 +- tests/integration/api_pull_review_test.go | 95 ++++---- tests/integration/api_pull_test.go | 34 +-- tests/integration/api_releases_test.go | 49 ++-- tests/integration/api_repo_avatar_test.go | 12 +- .../integration/api_repo_collaborator_test.go | 24 +- tests/integration/api_repo_edit_test.go | 79 ++++--- .../integration/api_repo_file_create_test.go | 42 ++-- .../integration/api_repo_file_delete_test.go | 38 ++-- .../integration/api_repo_file_update_test.go | 42 ++-- .../integration/api_repo_files_change_test.go | 40 ++-- .../api_repo_get_contents_list_test.go | 9 +- .../integration/api_repo_get_contents_test.go | 9 +- tests/integration/api_repo_git_blobs_test.go | 9 +- .../integration/api_repo_git_commits_test.go | 39 ++-- tests/integration/api_repo_git_hook_test.go | 47 ++-- tests/integration/api_repo_git_notes_test.go | 9 +- tests/integration/api_repo_git_ref_test.go | 9 +- tests/integration/api_repo_git_tags_test.go | 17 +- tests/integration/api_repo_git_trees_test.go | 6 +- tests/integration/api_repo_hook_test.go | 7 +- .../integration/api_repo_lfs_migrate_test.go | 4 +- tests/integration/api_repo_lfs_test.go | 23 +- tests/integration/api_repo_raw_test.go | 6 +- tests/integration/api_repo_secrets_test.go | 23 +- tests/integration/api_repo_tags_test.go | 13 +- tests/integration/api_repo_teams_test.go | 24 +- tests/integration/api_repo_test.go | 82 ++++--- tests/integration/api_repo_topic_test.go | 51 +++-- tests/integration/api_team_test.go | 54 +++-- tests/integration/api_team_user_test.go | 6 +- tests/integration/api_token_test.go | 46 ++-- tests/integration/api_twofa_test.go | 12 +- tests/integration/api_user_avatar_test.go | 12 +- tests/integration/api_user_email_test.go | 21 +- tests/integration/api_user_follow_test.go | 30 ++- tests/integration/api_user_heatmap_test.go | 4 +- tests/integration/api_user_info_test.go | 9 +- tests/integration/api_user_org_perm_test.go | 9 +- tests/integration/api_user_orgs_test.go | 7 +- tests/integration/api_user_search_test.go | 7 +- tests/integration/api_user_secrets_test.go | 23 +- tests/integration/api_user_star_test.go | 18 +- tests/integration/api_user_watch_test.go | 18 +- tests/integration/api_wiki_test.go | 8 +- tests/integration/cors_test.go | 2 +- tests/integration/empty_repo_test.go | 9 +- tests/integration/eventsource_test.go | 9 +- tests/integration/integration_test.go | 81 ++++--- tests/integration/org_test.go | 8 +- tests/integration/privateactivity_test.go | 7 +- tests/integration/pull_merge_test.go | 8 +- tests/integration/pull_status_test.go | 6 +- tests/integration/pull_update_test.go | 6 +- tests/integration/repo_search_test.go | 2 +- tests/integration/user_test.go | 2 +- 102 files changed, 1715 insertions(+), 1523 deletions(-) diff --git a/tests/integration/api_actions_artifact_test.go b/tests/integration/api_actions_artifact_test.go index 101bedde027..2597d103746 100644 --- a/tests/integration/api_actions_artifact_test.go +++ b/tests/integration/api_actions_artifact_test.go @@ -30,8 +30,7 @@ func TestActionsArtifactUploadSingleFile(t *testing.T) { req := NewRequestWithJSON(t, "POST", "/api/actions_pipeline/_apis/pipelines/workflows/791/artifacts", getUploadArtifactRequest{ Type: "actions_storage", Name: "artifact", - }) - req = addTokenAuthHeader(req, "Bearer 8061e833a55f6fc0157c98b883e91fcfeeb1a71a") + }).AddTokenAuth("8061e833a55f6fc0157c98b883e91fcfeeb1a71a") resp := MakeRequest(t, req, http.StatusOK) var uploadResp uploadArtifactResponse DecodeJSON(t, resp, &uploadResp) @@ -43,18 +42,18 @@ func TestActionsArtifactUploadSingleFile(t *testing.T) { // upload artifact chunk body := strings.Repeat("A", 1024) - req = NewRequestWithBody(t, "PUT", url, strings.NewReader(body)) - req = addTokenAuthHeader(req, "Bearer 8061e833a55f6fc0157c98b883e91fcfeeb1a71a") - req.Header.Add("Content-Range", "bytes 0-1023/1024") - req.Header.Add("x-tfs-filelength", "1024") - req.Header.Add("x-actions-results-md5", "1HsSe8LeLWh93ILaw1TEFQ==") // base64(md5(body)) + req = NewRequestWithBody(t, "PUT", url, strings.NewReader(body)). + AddTokenAuth("8061e833a55f6fc0157c98b883e91fcfeeb1a71a"). + SetHeader("Content-Range", "bytes 0-1023/1024"). + SetHeader("x-tfs-filelength", "1024"). + SetHeader("x-actions-results-md5", "1HsSe8LeLWh93ILaw1TEFQ==") // base64(md5(body)) MakeRequest(t, req, http.StatusOK) t.Logf("Create artifact confirm") // confirm artifact upload - req = NewRequest(t, "PATCH", "/api/actions_pipeline/_apis/pipelines/workflows/791/artifacts?artifactName=artifact") - req = addTokenAuthHeader(req, "Bearer 8061e833a55f6fc0157c98b883e91fcfeeb1a71a") + req = NewRequest(t, "PATCH", "/api/actions_pipeline/_apis/pipelines/workflows/791/artifacts?artifactName=artifact"). + AddTokenAuth("8061e833a55f6fc0157c98b883e91fcfeeb1a71a") MakeRequest(t, req, http.StatusOK) } @@ -64,11 +63,11 @@ func TestActionsArtifactUploadInvalidHash(t *testing.T) { // artifact id 54321 not exist url := "/api/actions_pipeline/_apis/pipelines/workflows/791/artifacts/8e5b948a454515dbabfc7eb718ddddddd/upload?itemPath=artifact/abc.txt" body := strings.Repeat("A", 1024) - req := NewRequestWithBody(t, "PUT", url, strings.NewReader(body)) - req = addTokenAuthHeader(req, "Bearer 8061e833a55f6fc0157c98b883e91fcfeeb1a71a") - req.Header.Add("Content-Range", "bytes 0-1023/1024") - req.Header.Add("x-tfs-filelength", "1024") - req.Header.Add("x-actions-results-md5", "1HsSe8LeLWh93ILaw1TEFQ==") // base64(md5(body)) + req := NewRequestWithBody(t, "PUT", url, strings.NewReader(body)). + AddTokenAuth("8061e833a55f6fc0157c98b883e91fcfeeb1a71a"). + SetHeader("Content-Range", "bytes 0-1023/1024"). + SetHeader("x-tfs-filelength", "1024"). + SetHeader("x-actions-results-md5", "1HsSe8LeLWh93ILaw1TEFQ==") // base64(md5(body)) resp := MakeRequest(t, req, http.StatusBadRequest) assert.Contains(t, resp.Body.String(), "Invalid artifact hash") } @@ -76,8 +75,8 @@ func TestActionsArtifactUploadInvalidHash(t *testing.T) { func TestActionsArtifactConfirmUploadWithoutName(t *testing.T) { defer tests.PrepareTestEnv(t)() - req := NewRequest(t, "PATCH", "/api/actions_pipeline/_apis/pipelines/workflows/791/artifacts") - req = addTokenAuthHeader(req, "Bearer 8061e833a55f6fc0157c98b883e91fcfeeb1a71a") + req := NewRequest(t, "PATCH", "/api/actions_pipeline/_apis/pipelines/workflows/791/artifacts"). + AddTokenAuth("8061e833a55f6fc0157c98b883e91fcfeeb1a71a") resp := MakeRequest(t, req, http.StatusBadRequest) assert.Contains(t, resp.Body.String(), "artifact name is empty") } @@ -111,8 +110,8 @@ type ( func TestActionsArtifactDownload(t *testing.T) { defer tests.PrepareTestEnv(t)() - req := NewRequest(t, "GET", "/api/actions_pipeline/_apis/pipelines/workflows/791/artifacts") - req = addTokenAuthHeader(req, "Bearer 8061e833a55f6fc0157c98b883e91fcfeeb1a71a") + req := NewRequest(t, "GET", "/api/actions_pipeline/_apis/pipelines/workflows/791/artifacts"). + AddTokenAuth("8061e833a55f6fc0157c98b883e91fcfeeb1a71a") resp := MakeRequest(t, req, http.StatusOK) var listResp listArtifactsResponse DecodeJSON(t, resp, &listResp) @@ -122,8 +121,8 @@ func TestActionsArtifactDownload(t *testing.T) { idx := strings.Index(listResp.Value[0].FileContainerResourceURL, "/api/actions_pipeline/_apis/pipelines/") url := listResp.Value[0].FileContainerResourceURL[idx+1:] + "?itemPath=artifact" - req = NewRequest(t, "GET", url) - req = addTokenAuthHeader(req, "Bearer 8061e833a55f6fc0157c98b883e91fcfeeb1a71a") + req = NewRequest(t, "GET", url). + AddTokenAuth("8061e833a55f6fc0157c98b883e91fcfeeb1a71a") resp = MakeRequest(t, req, http.StatusOK) var downloadResp downloadArtifactResponse DecodeJSON(t, resp, &downloadResp) @@ -134,8 +133,8 @@ func TestActionsArtifactDownload(t *testing.T) { idx = strings.Index(downloadResp.Value[0].ContentLocation, "/api/actions_pipeline/_apis/pipelines/") url = downloadResp.Value[0].ContentLocation[idx:] - req = NewRequest(t, "GET", url) - req = addTokenAuthHeader(req, "Bearer 8061e833a55f6fc0157c98b883e91fcfeeb1a71a") + req = NewRequest(t, "GET", url). + AddTokenAuth("8061e833a55f6fc0157c98b883e91fcfeeb1a71a") resp = MakeRequest(t, req, http.StatusOK) body := strings.Repeat("A", 1024) assert.Equal(t, resp.Body.String(), body) @@ -150,8 +149,7 @@ func TestActionsArtifactUploadMultipleFile(t *testing.T) { req := NewRequestWithJSON(t, "POST", "/api/actions_pipeline/_apis/pipelines/workflows/791/artifacts", getUploadArtifactRequest{ Type: "actions_storage", Name: testArtifactName, - }) - req = addTokenAuthHeader(req, "Bearer 8061e833a55f6fc0157c98b883e91fcfeeb1a71a") + }).AddTokenAuth("8061e833a55f6fc0157c98b883e91fcfeeb1a71a") resp := MakeRequest(t, req, http.StatusOK) var uploadResp uploadArtifactResponse DecodeJSON(t, resp, &uploadResp) @@ -182,19 +180,19 @@ func TestActionsArtifactUploadMultipleFile(t *testing.T) { url := uploadResp.FileContainerResourceURL[idx:] + "?itemPath=" + testArtifactName + "/" + f.Path // upload artifact chunk - req = NewRequestWithBody(t, "PUT", url, strings.NewReader(f.Content)) - req = addTokenAuthHeader(req, "Bearer 8061e833a55f6fc0157c98b883e91fcfeeb1a71a") - req.Header.Add("Content-Range", "bytes 0-1023/1024") - req.Header.Add("x-tfs-filelength", "1024") - req.Header.Add("x-actions-results-md5", f.MD5) // base64(md5(body)) + req = NewRequestWithBody(t, "PUT", url, strings.NewReader(f.Content)). + AddTokenAuth("8061e833a55f6fc0157c98b883e91fcfeeb1a71a"). + SetHeader("Content-Range", "bytes 0-1023/1024"). + SetHeader("x-tfs-filelength", "1024"). + SetHeader("x-actions-results-md5", f.MD5) // base64(md5(body)) MakeRequest(t, req, http.StatusOK) } t.Logf("Create artifact confirm") // confirm artifact upload - req = NewRequest(t, "PATCH", "/api/actions_pipeline/_apis/pipelines/workflows/791/artifacts?artifactName="+testArtifactName) - req = addTokenAuthHeader(req, "Bearer 8061e833a55f6fc0157c98b883e91fcfeeb1a71a") + req = NewRequest(t, "PATCH", "/api/actions_pipeline/_apis/pipelines/workflows/791/artifacts?artifactName="+testArtifactName). + AddTokenAuth("8061e833a55f6fc0157c98b883e91fcfeeb1a71a") MakeRequest(t, req, http.StatusOK) } @@ -203,8 +201,8 @@ func TestActionsArtifactDownloadMultiFiles(t *testing.T) { const testArtifactName = "multi-files" - req := NewRequest(t, "GET", "/api/actions_pipeline/_apis/pipelines/workflows/791/artifacts") - req = addTokenAuthHeader(req, "Bearer 8061e833a55f6fc0157c98b883e91fcfeeb1a71a") + req := NewRequest(t, "GET", "/api/actions_pipeline/_apis/pipelines/workflows/791/artifacts"). + AddTokenAuth("8061e833a55f6fc0157c98b883e91fcfeeb1a71a") resp := MakeRequest(t, req, http.StatusOK) var listResp listArtifactsResponse DecodeJSON(t, resp, &listResp) @@ -221,8 +219,8 @@ func TestActionsArtifactDownloadMultiFiles(t *testing.T) { idx := strings.Index(fileContainerResourceURL, "/api/actions_pipeline/_apis/pipelines/") url := fileContainerResourceURL[idx+1:] + "?itemPath=" + testArtifactName - req = NewRequest(t, "GET", url) - req = addTokenAuthHeader(req, "Bearer 8061e833a55f6fc0157c98b883e91fcfeeb1a71a") + req = NewRequest(t, "GET", url). + AddTokenAuth("8061e833a55f6fc0157c98b883e91fcfeeb1a71a") resp = MakeRequest(t, req, http.StatusOK) var downloadResp downloadArtifactResponse DecodeJSON(t, resp, &downloadResp) @@ -246,8 +244,8 @@ func TestActionsArtifactDownloadMultiFiles(t *testing.T) { idx = strings.Index(value.ContentLocation, "/api/actions_pipeline/_apis/pipelines/") url = value.ContentLocation[idx:] - req = NewRequest(t, "GET", url) - req = addTokenAuthHeader(req, "Bearer 8061e833a55f6fc0157c98b883e91fcfeeb1a71a") + req = NewRequest(t, "GET", url). + AddTokenAuth("8061e833a55f6fc0157c98b883e91fcfeeb1a71a") resp = MakeRequest(t, req, http.StatusOK) body := strings.Repeat(bodyChar, 1024) assert.Equal(t, resp.Body.String(), body) @@ -262,8 +260,7 @@ func TestActionsArtifactUploadWithRetentionDays(t *testing.T) { Type: "actions_storage", Name: "artifact-retention-days", RetentionDays: 9, - }) - req = addTokenAuthHeader(req, "Bearer 8061e833a55f6fc0157c98b883e91fcfeeb1a71a") + }).AddTokenAuth("8061e833a55f6fc0157c98b883e91fcfeeb1a71a") resp := MakeRequest(t, req, http.StatusOK) var uploadResp uploadArtifactResponse DecodeJSON(t, resp, &uploadResp) @@ -276,17 +273,17 @@ func TestActionsArtifactUploadWithRetentionDays(t *testing.T) { // upload artifact chunk body := strings.Repeat("A", 1024) - req = NewRequestWithBody(t, "PUT", url, strings.NewReader(body)) - req = addTokenAuthHeader(req, "Bearer 8061e833a55f6fc0157c98b883e91fcfeeb1a71a") - req.Header.Add("Content-Range", "bytes 0-1023/1024") - req.Header.Add("x-tfs-filelength", "1024") - req.Header.Add("x-actions-results-md5", "1HsSe8LeLWh93ILaw1TEFQ==") // base64(md5(body)) + req = NewRequestWithBody(t, "PUT", url, strings.NewReader(body)). + AddTokenAuth("8061e833a55f6fc0157c98b883e91fcfeeb1a71a"). + SetHeader("Content-Range", "bytes 0-1023/1024"). + SetHeader("x-tfs-filelength", "1024"). + SetHeader("x-actions-results-md5", "1HsSe8LeLWh93ILaw1TEFQ==") // base64(md5(body)) MakeRequest(t, req, http.StatusOK) t.Logf("Create artifact confirm") // confirm artifact upload - req = NewRequest(t, "PATCH", "/api/actions_pipeline/_apis/pipelines/workflows/791/artifacts?artifactName=artifact-retention-days") - req = addTokenAuthHeader(req, "Bearer 8061e833a55f6fc0157c98b883e91fcfeeb1a71a") + req = NewRequest(t, "PATCH", "/api/actions_pipeline/_apis/pipelines/workflows/791/artifacts?artifactName=artifact-retention-days"). + AddTokenAuth("8061e833a55f6fc0157c98b883e91fcfeeb1a71a") MakeRequest(t, req, http.StatusOK) } diff --git a/tests/integration/api_activitypub_person_test.go b/tests/integration/api_activitypub_person_test.go index 3222dfc8071..42a2a090727 100644 --- a/tests/integration/api_activitypub_person_test.go +++ b/tests/integration/api_activitypub_person_test.go @@ -32,7 +32,7 @@ func TestActivityPubPerson(t *testing.T) { onGiteaRun(t, func(*testing.T, *url.URL) { userID := 2 username := "user2" - req := NewRequestf(t, "GET", fmt.Sprintf("/api/v1/activitypub/user-id/%v", userID)) + req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/activitypub/user-id/%v", userID)) resp := MakeRequest(t, req, http.StatusOK) body := resp.Body.Bytes() assert.Contains(t, string(body), "@context") @@ -68,7 +68,7 @@ func TestActivityPubMissingPerson(t *testing.T) { }() onGiteaRun(t, func(*testing.T, *url.URL) { - req := NewRequestf(t, "GET", "/api/v1/activitypub/user-id/999999999") + req := NewRequest(t, "GET", "/api/v1/activitypub/user-id/999999999") resp := MakeRequest(t, req, http.StatusNotFound) assert.Contains(t, resp.Body.String(), "user does not exist") }) diff --git a/tests/integration/api_admin_org_test.go b/tests/integration/api_admin_org_test.go index 0bf4b1f7cba..a29d0ba1d74 100644 --- a/tests/integration/api_admin_org_test.go +++ b/tests/integration/api_admin_org_test.go @@ -31,7 +31,8 @@ func TestAPIAdminOrgCreate(t *testing.T) { Location: "Shanghai", Visibility: "private", } - req := NewRequestWithJSON(t, "POST", "/api/v1/admin/users/user2/orgs?token="+token, &org) + req := NewRequestWithJSON(t, "POST", "/api/v1/admin/users/user2/orgs", &org). + AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusCreated) var apiOrg api.Organization @@ -65,7 +66,8 @@ func TestAPIAdminOrgCreateBadVisibility(t *testing.T) { Location: "Shanghai", Visibility: "notvalid", } - req := NewRequestWithJSON(t, "POST", "/api/v1/admin/users/user2/orgs?token="+token, &org) + req := NewRequestWithJSON(t, "POST", "/api/v1/admin/users/user2/orgs", &org). + AddTokenAuth(token) MakeRequest(t, req, http.StatusUnprocessableEntity) }) } @@ -83,6 +85,7 @@ func TestAPIAdminOrgCreateNotAdmin(t *testing.T) { Location: "Shanghai", Visibility: "public", } - req := NewRequestWithJSON(t, "POST", "/api/v1/admin/users/user2/orgs?token="+token, &org) + req := NewRequestWithJSON(t, "POST", "/api/v1/admin/users/user2/orgs", &org). + AddTokenAuth(token) MakeRequest(t, req, http.StatusForbidden) } diff --git a/tests/integration/api_admin_test.go b/tests/integration/api_admin_test.go index aae9ec4a24a..ff7c2ddca39 100644 --- a/tests/integration/api_admin_test.go +++ b/tests/integration/api_admin_test.go @@ -27,11 +27,11 @@ func TestAPIAdminCreateAndDeleteSSHKey(t *testing.T) { keyOwner := unittest.AssertExistsAndLoadBean(t, &user_model.User{Name: "user2"}) token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteAdmin) - urlStr := fmt.Sprintf("/api/v1/admin/users/%s/keys?token=%s", keyOwner.Name, token) + urlStr := fmt.Sprintf("/api/v1/admin/users/%s/keys", keyOwner.Name) req := NewRequestWithValues(t, "POST", urlStr, map[string]string{ "key": "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQC4cn+iXnA4KvcQYSV88vGn0Yi91vG47t1P7okprVmhNTkipNRIHWr6WdCO4VDr/cvsRkuVJAsLO2enwjGWWueOO6BodiBgyAOZ/5t5nJNMCNuLGT5UIo/RI1b0WRQwxEZTRjt6mFNw6lH14wRd8ulsr9toSWBPMOGWoYs1PDeDL0JuTjL+tr1SZi/EyxCngpYszKdXllJEHyI79KQgeD0Vt3pTrkbNVTOEcCNqZePSVmUH8X8Vhugz3bnE0/iE9Pb5fkWO9c4AnM1FgI/8Bvp27Fw2ShryIXuR6kKvUqhVMTuOSDHwu6A8jLE5Owt3GAYugDpDYuwTVNGrHLXKpPzrGGPE/jPmaLCMZcsdkec95dYeU3zKODEm8UQZFhmJmDeWVJ36nGrGZHL4J5aTTaeFUJmmXDaJYiJ+K2/ioKgXqnXvltu0A9R8/LGy4nrTJRr4JMLuJFoUXvGm1gXQ70w2LSpk6yl71RNC0hCtsBe8BP8IhYCM0EP5jh7eCMQZNvM= nocomment\n", "title": "test-key", - }) + }).AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusCreated) var newPublicKey api.PublicKey @@ -43,8 +43,8 @@ func TestAPIAdminCreateAndDeleteSSHKey(t *testing.T) { OwnerID: keyOwner.ID, }) - req = NewRequestf(t, "DELETE", "/api/v1/admin/users/%s/keys/%d?token=%s", - keyOwner.Name, newPublicKey.ID, token) + req = NewRequestf(t, "DELETE", "/api/v1/admin/users/%s/keys/%d", keyOwner.Name, newPublicKey.ID). + AddTokenAuth(token) MakeRequest(t, req, http.StatusNoContent) unittest.AssertNotExistsBean(t, &asymkey_model.PublicKey{ID: newPublicKey.ID}) } @@ -54,7 +54,8 @@ func TestAPIAdminDeleteMissingSSHKey(t *testing.T) { // user1 is an admin user token := getUserToken(t, "user1", auth_model.AccessTokenScopeWriteAdmin) - req := NewRequestf(t, "DELETE", "/api/v1/admin/users/user1/keys/%d?token=%s", unittest.NonexistentID, token) + req := NewRequestf(t, "DELETE", "/api/v1/admin/users/user1/keys/%d", unittest.NonexistentID). + AddTokenAuth(token) MakeRequest(t, req, http.StatusNotFound) } @@ -64,18 +65,18 @@ func TestAPIAdminDeleteUnauthorizedKey(t *testing.T) { normalUsername := "user2" token := getUserToken(t, adminUsername, auth_model.AccessTokenScopeWriteAdmin) - urlStr := fmt.Sprintf("/api/v1/admin/users/%s/keys?token=%s", adminUsername, token) + urlStr := fmt.Sprintf("/api/v1/admin/users/%s/keys", adminUsername) req := NewRequestWithValues(t, "POST", urlStr, map[string]string{ "key": "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQC4cn+iXnA4KvcQYSV88vGn0Yi91vG47t1P7okprVmhNTkipNRIHWr6WdCO4VDr/cvsRkuVJAsLO2enwjGWWueOO6BodiBgyAOZ/5t5nJNMCNuLGT5UIo/RI1b0WRQwxEZTRjt6mFNw6lH14wRd8ulsr9toSWBPMOGWoYs1PDeDL0JuTjL+tr1SZi/EyxCngpYszKdXllJEHyI79KQgeD0Vt3pTrkbNVTOEcCNqZePSVmUH8X8Vhugz3bnE0/iE9Pb5fkWO9c4AnM1FgI/8Bvp27Fw2ShryIXuR6kKvUqhVMTuOSDHwu6A8jLE5Owt3GAYugDpDYuwTVNGrHLXKpPzrGGPE/jPmaLCMZcsdkec95dYeU3zKODEm8UQZFhmJmDeWVJ36nGrGZHL4J5aTTaeFUJmmXDaJYiJ+K2/ioKgXqnXvltu0A9R8/LGy4nrTJRr4JMLuJFoUXvGm1gXQ70w2LSpk6yl71RNC0hCtsBe8BP8IhYCM0EP5jh7eCMQZNvM= nocomment\n", "title": "test-key", - }) + }).AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusCreated) var newPublicKey api.PublicKey DecodeJSON(t, resp, &newPublicKey) token = getUserToken(t, normalUsername) - req = NewRequestf(t, "DELETE", "/api/v1/admin/users/%s/keys/%d?token=%s", - adminUsername, newPublicKey.ID, token) + req = NewRequestf(t, "DELETE", "/api/v1/admin/users/%s/keys/%d", adminUsername, newPublicKey.ID). + AddTokenAuth(token) MakeRequest(t, req, http.StatusForbidden) } @@ -85,8 +86,8 @@ func TestAPISudoUser(t *testing.T) { normalUsername := "user2" token := getUserToken(t, adminUsername, auth_model.AccessTokenScopeReadUser) - urlStr := fmt.Sprintf("/api/v1/user?sudo=%s&token=%s", normalUsername, token) - req := NewRequest(t, "GET", urlStr) + req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/user?sudo=%s", normalUsername)). + AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusOK) var user api.User DecodeJSON(t, resp, &user) @@ -100,8 +101,8 @@ func TestAPISudoUserForbidden(t *testing.T) { normalUsername := "user2" token := getUserToken(t, normalUsername, auth_model.AccessTokenScopeReadAdmin) - urlStr := fmt.Sprintf("/api/v1/user?sudo=%s&token=%s", adminUsername, token) - req := NewRequest(t, "GET", urlStr) + req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/user?sudo=%s", adminUsername)). + AddTokenAuth(token) MakeRequest(t, req, http.StatusForbidden) } @@ -110,8 +111,8 @@ func TestAPIListUsers(t *testing.T) { adminUsername := "user1" token := getUserToken(t, adminUsername, auth_model.AccessTokenScopeReadAdmin) - urlStr := fmt.Sprintf("/api/v1/admin/users?token=%s", token) - req := NewRequest(t, "GET", urlStr) + req := NewRequest(t, "GET", "/api/v1/admin/users"). + AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusOK) var users []api.User DecodeJSON(t, resp, &users) @@ -137,7 +138,8 @@ func TestAPIListUsersNonAdmin(t *testing.T) { defer tests.PrepareTestEnv(t)() nonAdminUsername := "user2" token := getUserToken(t, nonAdminUsername) - req := NewRequestf(t, "GET", "/api/v1/admin/users?token=%s", token) + req := NewRequest(t, "GET", "/api/v1/admin/users"). + AddTokenAuth(token) MakeRequest(t, req, http.StatusForbidden) } @@ -145,8 +147,7 @@ func TestAPICreateUserInvalidEmail(t *testing.T) { defer tests.PrepareTestEnv(t)() adminUsername := "user1" token := getUserToken(t, adminUsername, auth_model.AccessTokenScopeWriteAdmin) - urlStr := fmt.Sprintf("/api/v1/admin/users?token=%s", token) - req := NewRequestWithValues(t, "POST", urlStr, map[string]string{ + req := NewRequestWithValues(t, "POST", "/api/v1/admin/users", map[string]string{ "email": "invalid_email@domain.com\r\n", "full_name": "invalid user", "login_name": "invalidUser", @@ -155,7 +156,7 @@ func TestAPICreateUserInvalidEmail(t *testing.T) { "send_notify": "true", "source_id": "0", "username": "invalidUser", - }) + }).AddTokenAuth(token) MakeRequest(t, req, http.StatusUnprocessableEntity) } @@ -167,7 +168,7 @@ func TestAPICreateAndDeleteUser(t *testing.T) { req := NewRequestWithValues( t, "POST", - fmt.Sprintf("/api/v1/admin/users?token=%s", token), + "/api/v1/admin/users", map[string]string{ "email": "deleteme@domain.com", "full_name": "delete me", @@ -178,10 +179,11 @@ func TestAPICreateAndDeleteUser(t *testing.T) { "source_id": "0", "username": "deleteme", }, - ) + ).AddTokenAuth(token) MakeRequest(t, req, http.StatusCreated) - req = NewRequest(t, "DELETE", fmt.Sprintf("/api/v1/admin/users/deleteme?token=%s", token)) + req = NewRequest(t, "DELETE", "/api/v1/admin/users/deleteme"). + AddTokenAuth(token) MakeRequest(t, req, http.StatusNoContent) } @@ -189,7 +191,7 @@ func TestAPIEditUser(t *testing.T) { defer tests.PrepareTestEnv(t)() adminUsername := "user1" token := getUserToken(t, adminUsername, auth_model.AccessTokenScopeWriteAdmin) - urlStr := fmt.Sprintf("/api/v1/admin/users/%s?token=%s", "user2", token) + urlStr := fmt.Sprintf("/api/v1/admin/users/%s", "user2") req := NewRequestWithValues(t, "PATCH", urlStr, map[string]string{ // required @@ -197,7 +199,7 @@ func TestAPIEditUser(t *testing.T) { "source_id": "0", // to change "full_name": "Full Name User 2", - }) + }).AddTokenAuth(token) MakeRequest(t, req, http.StatusOK) empty := "" @@ -205,7 +207,7 @@ func TestAPIEditUser(t *testing.T) { LoginName: "user2", SourceID: 0, Email: &empty, - }) + }).AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusUnprocessableEntity) errMap := make(map[string]any) @@ -221,7 +223,7 @@ func TestAPIEditUser(t *testing.T) { SourceID: 0, // to change Restricted: &bTrue, - }) + }).AddTokenAuth(token) MakeRequest(t, req, http.StatusOK) user2 = unittest.AssertExistsAndLoadBean(t, &user_model.User{LoginName: "user2"}) assert.True(t, user2.IsRestricted) @@ -235,11 +237,11 @@ func TestAPICreateRepoForUser(t *testing.T) { req := NewRequestWithJSON( t, "POST", - fmt.Sprintf("/api/v1/admin/users/%s/repos?token=%s", adminUsername, token), + fmt.Sprintf("/api/v1/admin/users/%s/repos", adminUsername), &api.CreateRepoOption{ Name: "admincreatedrepo", }, - ) + ).AddTokenAuth(token) MakeRequest(t, req, http.StatusCreated) } @@ -247,40 +249,38 @@ func TestAPIRenameUser(t *testing.T) { defer tests.PrepareTestEnv(t)() adminUsername := "user1" token := getUserToken(t, adminUsername, auth_model.AccessTokenScopeWriteAdmin) - urlStr := fmt.Sprintf("/api/v1/admin/users/%s/rename?token=%s", "user2", token) + urlStr := fmt.Sprintf("/api/v1/admin/users/%s/rename", "user2") req := NewRequestWithValues(t, "POST", urlStr, map[string]string{ // required "new_name": "User2", - }) + }).AddTokenAuth(token) MakeRequest(t, req, http.StatusOK) - urlStr = fmt.Sprintf("/api/v1/admin/users/%s/rename?token=%s", "User2", token) + urlStr = fmt.Sprintf("/api/v1/admin/users/%s/rename", "User2") req = NewRequestWithValues(t, "POST", urlStr, map[string]string{ // required "new_name": "User2-2-2", - }) + }).AddTokenAuth(token) MakeRequest(t, req, http.StatusOK) - urlStr = fmt.Sprintf("/api/v1/admin/users/%s/rename?token=%s", "User2", token) req = NewRequestWithValues(t, "POST", urlStr, map[string]string{ // required "new_name": "user1", - }) + }).AddTokenAuth(token) // the old user name still be used by with a redirect MakeRequest(t, req, http.StatusTemporaryRedirect) - urlStr = fmt.Sprintf("/api/v1/admin/users/%s/rename?token=%s", "User2-2-2", token) + urlStr = fmt.Sprintf("/api/v1/admin/users/%s/rename", "User2-2-2") req = NewRequestWithValues(t, "POST", urlStr, map[string]string{ // required "new_name": "user1", - }) + }).AddTokenAuth(token) MakeRequest(t, req, http.StatusUnprocessableEntity) - urlStr = fmt.Sprintf("/api/v1/admin/users/%s/rename?token=%s", "User2-2-2", token) req = NewRequestWithValues(t, "POST", urlStr, map[string]string{ // required "new_name": "user2", - }) + }).AddTokenAuth(token) MakeRequest(t, req, http.StatusOK) } @@ -294,8 +294,9 @@ func TestAPICron(t *testing.T) { defer tests.PrintCurrentTest(t)() token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeReadAdmin) - urlStr := fmt.Sprintf("/api/v1/admin/cron?token=%s", token) - req := NewRequest(t, "GET", urlStr) + + req := NewRequest(t, "GET", "/api/v1/admin/cron"). + AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusOK) assert.Equal(t, "28", resp.Header().Get("X-Total-Count")) @@ -313,13 +314,13 @@ func TestAPICron(t *testing.T) { // Archive cleanup is harmless, because in the test environment there are none // and is thus an NOOP operation and therefore doesn't interfere with any other // tests. - urlStr := fmt.Sprintf("/api/v1/admin/cron/archive_cleanup?token=%s", token) - req := NewRequest(t, "POST", urlStr) + req := NewRequest(t, "POST", "/api/v1/admin/cron/archive_cleanup"). + AddTokenAuth(token) MakeRequest(t, req, http.StatusNoContent) // Check for the latest run time for this cron, to ensure it has been run. - urlStr = fmt.Sprintf("/api/v1/admin/cron?token=%s", token) - req = NewRequest(t, "GET", urlStr) + req = NewRequest(t, "GET", "/api/v1/admin/cron"). + AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusOK) var crons []api.Cron diff --git a/tests/integration/api_branch_test.go b/tests/integration/api_branch_test.go index bc026c117f6..28e690b3568 100644 --- a/tests/integration/api_branch_test.go +++ b/tests/integration/api_branch_test.go @@ -17,7 +17,8 @@ import ( func testAPIGetBranch(t *testing.T, branchName string, exists bool) { token := getUserToken(t, "user2", auth_model.AccessTokenScopeReadRepository) - req := NewRequestf(t, "GET", "/api/v1/repos/user2/repo1/branches/%s?token=%s", branchName, token) + req := NewRequestf(t, "GET", "/api/v1/repos/user2/repo1/branches/%s", branchName). + AddTokenAuth(token) resp := MakeRequest(t, req, NoExpectedStatus) if !exists { assert.EqualValues(t, http.StatusNotFound, resp.Code) @@ -33,7 +34,8 @@ func testAPIGetBranch(t *testing.T, branchName string, exists bool) { func testAPIGetBranchProtection(t *testing.T, branchName string, expectedHTTPStatus int) *api.BranchProtection { token := getUserToken(t, "user2", auth_model.AccessTokenScopeReadRepository) - req := NewRequestf(t, "GET", "/api/v1/repos/user2/repo1/branch_protections/%s?token=%s", branchName, token) + req := NewRequestf(t, "GET", "/api/v1/repos/user2/repo1/branch_protections/%s", branchName). + AddTokenAuth(token) resp := MakeRequest(t, req, expectedHTTPStatus) if resp.Code == http.StatusOK { @@ -47,9 +49,9 @@ func testAPIGetBranchProtection(t *testing.T, branchName string, expectedHTTPSta func testAPICreateBranchProtection(t *testing.T, branchName string, expectedHTTPStatus int) { token := getUserToken(t, "user2", auth_model.AccessTokenScopeWriteRepository) - req := NewRequestWithJSON(t, "POST", "/api/v1/repos/user2/repo1/branch_protections?token="+token, &api.BranchProtection{ + req := NewRequestWithJSON(t, "POST", "/api/v1/repos/user2/repo1/branch_protections", &api.BranchProtection{ RuleName: branchName, - }) + }).AddTokenAuth(token) resp := MakeRequest(t, req, expectedHTTPStatus) if resp.Code == http.StatusCreated { @@ -61,7 +63,8 @@ func testAPICreateBranchProtection(t *testing.T, branchName string, expectedHTTP func testAPIEditBranchProtection(t *testing.T, branchName string, body *api.BranchProtection, expectedHTTPStatus int) { token := getUserToken(t, "user2", auth_model.AccessTokenScopeWriteRepository) - req := NewRequestWithJSON(t, "PATCH", "/api/v1/repos/user2/repo1/branch_protections/"+branchName+"?token="+token, body) + req := NewRequestWithJSON(t, "PATCH", "/api/v1/repos/user2/repo1/branch_protections/"+branchName, body). + AddTokenAuth(token) resp := MakeRequest(t, req, expectedHTTPStatus) if resp.Code == http.StatusOK { @@ -73,13 +76,15 @@ func testAPIEditBranchProtection(t *testing.T, branchName string, body *api.Bran func testAPIDeleteBranchProtection(t *testing.T, branchName string, expectedHTTPStatus int) { token := getUserToken(t, "user2", auth_model.AccessTokenScopeWriteRepository) - req := NewRequestf(t, "DELETE", "/api/v1/repos/user2/repo1/branch_protections/%s?token=%s", branchName, token) + req := NewRequestf(t, "DELETE", "/api/v1/repos/user2/repo1/branch_protections/%s", branchName). + AddTokenAuth(token) MakeRequest(t, req, expectedHTTPStatus) } func testAPIDeleteBranch(t *testing.T, branchName string, expectedHTTPStatus int) { token := getUserToken(t, "user2", auth_model.AccessTokenScopeWriteRepository) - req := NewRequestf(t, "DELETE", "/api/v1/repos/user2/repo1/branches/%s?token=%s", branchName, token) + req := NewRequestf(t, "DELETE", "/api/v1/repos/user2/repo1/branches/%s", branchName). + AddTokenAuth(token) MakeRequest(t, req, expectedHTTPStatus) } @@ -152,10 +157,10 @@ func testAPICreateBranches(t *testing.T, giteaURL *url.URL) { func testAPICreateBranch(t testing.TB, session *TestSession, user, repo, oldBranch, newBranch string, status int) bool { token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteRepository) - req := NewRequestWithJSON(t, "POST", "/api/v1/repos/"+user+"/"+repo+"/branches?token="+token, &api.CreateBranchRepoOption{ + req := NewRequestWithJSON(t, "POST", "/api/v1/repos/"+user+"/"+repo+"/branches", &api.CreateBranchRepoOption{ BranchName: newBranch, OldBranchName: oldBranch, - }) + }).AddTokenAuth(token) resp := MakeRequest(t, req, status) var branch api.Branch diff --git a/tests/integration/api_comment_attachment_test.go b/tests/integration/api_comment_attachment_test.go index 95a7a81eb40..e5e62a86b7b 100644 --- a/tests/integration/api_comment_attachment_test.go +++ b/tests/integration/api_comment_attachment_test.go @@ -39,15 +39,18 @@ func TestAPIGetCommentAttachment(t *testing.T) { repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 4}) repoOwner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}) token := getUserToken(t, repoOwner.Name, auth_model.AccessTokenScopeWriteIssue) - req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/issues/comments/%d/assets/%d?token=%s", repoOwner.Name, repo.Name, comment.ID, attachment.ID, token) + req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/issues/comments/%d/assets/%d", repoOwner.Name, repo.Name, comment.ID, attachment.ID). + AddTokenAuth(token) MakeRequest(t, req, http.StatusNotFound) }) session := loginUser(t, repoOwner.Name) token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeReadIssue) - req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/issues/comments/%d/assets/%d?token=%s", repoOwner.Name, repo.Name, comment.ID, attachment.ID, token) + req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/issues/comments/%d/assets/%d", repoOwner.Name, repo.Name, comment.ID, attachment.ID). + AddTokenAuth(token) session.MakeRequest(t, req, http.StatusOK) - req = NewRequestf(t, "GET", "/api/v1/repos/%s/%s/issues/comments/%d/assets/%d?token=%s", repoOwner.Name, repo.Name, comment.ID, attachment.ID, token) + req = NewRequestf(t, "GET", "/api/v1/repos/%s/%s/issues/comments/%d/assets/%d", repoOwner.Name, repo.Name, comment.ID, attachment.ID). + AddTokenAuth(token) resp := session.MakeRequest(t, req, http.StatusOK) var apiAttachment api.Attachment @@ -71,8 +74,8 @@ func TestAPIListCommentAttachments(t *testing.T) { session := loginUser(t, repoOwner.Name) token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeReadIssue) - req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/issues/comments/%d/assets?token=%s", - repoOwner.Name, repo.Name, comment.ID, token) + req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/issues/comments/%d/assets", repoOwner.Name, repo.Name, comment.ID). + AddTokenAuth(token) resp := session.MakeRequest(t, req, http.StatusOK) var apiAttachments []*api.Attachment @@ -93,8 +96,6 @@ func TestAPICreateCommentAttachment(t *testing.T) { session := loginUser(t, repoOwner.Name) token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteIssue) - urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/issues/comments/%d/assets?token=%s", - repoOwner.Name, repo.Name, comment.ID, token) filename := "image.png" buff := generateImg() @@ -109,8 +110,9 @@ func TestAPICreateCommentAttachment(t *testing.T) { err = writer.Close() assert.NoError(t, err) - req := NewRequestWithBody(t, "POST", urlStr, body) - req.Header.Add("Content-Type", writer.FormDataContentType()) + req := NewRequestWithBody(t, "POST", fmt.Sprintf("/api/v1/repos/%s/%s/issues/comments/%d/assets", repoOwner.Name, repo.Name, comment.ID), body). + AddTokenAuth(token). + SetHeader("Content-Type", writer.FormDataContentType()) resp := session.MakeRequest(t, req, http.StatusCreated) apiAttachment := new(api.Attachment) @@ -132,11 +134,11 @@ func TestAPIEditCommentAttachment(t *testing.T) { session := loginUser(t, repoOwner.Name) token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteIssue) - urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/issues/comments/%d/assets/%d?token=%s", - repoOwner.Name, repo.Name, comment.ID, attachment.ID, token) + urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/issues/comments/%d/assets/%d", + repoOwner.Name, repo.Name, comment.ID, attachment.ID) req := NewRequestWithValues(t, "PATCH", urlStr, map[string]string{ "name": newAttachmentName, - }) + }).AddTokenAuth(token) resp := session.MakeRequest(t, req, http.StatusCreated) apiAttachment := new(api.Attachment) DecodeJSON(t, resp, &apiAttachment) @@ -155,10 +157,9 @@ func TestAPIDeleteCommentAttachment(t *testing.T) { session := loginUser(t, repoOwner.Name) token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteIssue) - urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/issues/comments/%d/assets/%d?token=%s", - repoOwner.Name, repo.Name, comment.ID, attachment.ID, token) - req := NewRequestf(t, "DELETE", urlStr) + req := NewRequest(t, "DELETE", fmt.Sprintf("/api/v1/repos/%s/%s/issues/comments/%d/assets/%d", repoOwner.Name, repo.Name, comment.ID, attachment.ID)). + AddTokenAuth(token) session.MakeRequest(t, req, http.StatusNoContent) unittest.AssertNotExistsBean(t, &repo_model.Attachment{ID: attachment.ID, CommentID: comment.ID}) diff --git a/tests/integration/api_comment_test.go b/tests/integration/api_comment_test.go index fe272cf9269..a9c5228a16c 100644 --- a/tests/integration/api_comment_test.go +++ b/tests/integration/api_comment_test.go @@ -77,8 +77,8 @@ func TestAPIListIssueComments(t *testing.T) { repoOwner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}) token := getUserToken(t, repoOwner.Name, auth_model.AccessTokenScopeReadIssue) - req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/issues/%d/comments?token=%s", - repoOwner.Name, repo.Name, issue.Index, token) + req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/issues/%d/comments", repoOwner.Name, repo.Name, issue.Index). + AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusOK) var comments []*api.Comment @@ -97,11 +97,11 @@ func TestAPICreateComment(t *testing.T) { repoOwner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}) token := getUserToken(t, repoOwner.Name, auth_model.AccessTokenScopeWriteIssue) - urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/issues/%d/comments?token=%s", - repoOwner.Name, repo.Name, issue.Index, token) + urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/issues/%d/comments", + repoOwner.Name, repo.Name, issue.Index) req := NewRequestWithValues(t, "POST", urlStr, map[string]string{ "body": commentBody, - }) + }).AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusCreated) var updatedComment api.Comment @@ -121,7 +121,8 @@ func TestAPIGetComment(t *testing.T) { token := getUserToken(t, repoOwner.Name, auth_model.AccessTokenScopeReadIssue) req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/issues/comments/%d", repoOwner.Name, repo.Name, comment.ID) MakeRequest(t, req, http.StatusOK) - req = NewRequestf(t, "GET", "/api/v1/repos/%s/%s/issues/comments/%d?token=%s", repoOwner.Name, repo.Name, comment.ID, token) + req = NewRequestf(t, "GET", "/api/v1/repos/%s/%s/issues/comments/%d", repoOwner.Name, repo.Name, comment.ID). + AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusOK) var apiComment api.Comment @@ -188,20 +189,20 @@ func TestAPIEditComment(t *testing.T) { repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 4}) repoOwner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}) token := getUserToken(t, repoOwner.Name, auth_model.AccessTokenScopeWriteIssue) - urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/issues/comments/%d?token=%s", - repoOwner.Name, repo.Name, comment.ID, token) + urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/issues/comments/%d", + repoOwner.Name, repo.Name, comment.ID) req := NewRequestWithValues(t, "PATCH", urlStr, map[string]string{ "body": newCommentBody, - }) + }).AddTokenAuth(token) MakeRequest(t, req, http.StatusNotFound) }) token := getUserToken(t, repoOwner.Name, auth_model.AccessTokenScopeWriteIssue) - urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/issues/comments/%d?token=%s", - repoOwner.Name, repo.Name, comment.ID, token) + urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/issues/comments/%d", + repoOwner.Name, repo.Name, comment.ID) req := NewRequestWithValues(t, "PATCH", urlStr, map[string]string{ "body": newCommentBody, - }) + }).AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusOK) var updatedComment api.Comment @@ -225,14 +226,14 @@ func TestAPIDeleteComment(t *testing.T) { repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 4}) repoOwner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}) token := getUserToken(t, repoOwner.Name, auth_model.AccessTokenScopeWriteIssue) - req := NewRequestf(t, "DELETE", "/api/v1/repos/%s/%s/issues/comments/%d?token=%s", - repoOwner.Name, repo.Name, comment.ID, token) + req := NewRequestf(t, "DELETE", "/api/v1/repos/%s/%s/issues/comments/%d", repoOwner.Name, repo.Name, comment.ID). + AddTokenAuth(token) MakeRequest(t, req, http.StatusNotFound) }) token := getUserToken(t, repoOwner.Name, auth_model.AccessTokenScopeWriteIssue) - req := NewRequestf(t, "DELETE", "/api/v1/repos/%s/%s/issues/comments/%d?token=%s", - repoOwner.Name, repo.Name, comment.ID, token) + req := NewRequestf(t, "DELETE", "/api/v1/repos/%s/%s/issues/comments/%d", repoOwner.Name, repo.Name, comment.ID). + AddTokenAuth(token) MakeRequest(t, req, http.StatusNoContent) unittest.AssertNotExistsBean(t, &issues_model.Comment{ID: comment.ID}) @@ -247,8 +248,7 @@ func TestAPIListIssueTimeline(t *testing.T) { repoOwner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}) // make request - req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/issues/%d/timeline", - repoOwner.Name, repo.Name, issue.Index) + req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/issues/%d/timeline", repoOwner.Name, repo.Name, issue.Index) resp := MakeRequest(t, req, http.StatusOK) // check if lens of list returned by API and diff --git a/tests/integration/api_gpg_keys_test.go b/tests/integration/api_gpg_keys_test.go index a4545bd0bbd..ec0dafc2d6d 100644 --- a/tests/integration/api_gpg_keys_test.go +++ b/tests/integration/api_gpg_keys_test.go @@ -16,7 +16,7 @@ import ( "github.com/stretchr/testify/assert" ) -type makeRequestFunc func(testing.TB, *http.Request, int) *httptest.ResponseRecorder +type makeRequestFunc func(testing.TB, *RequestWrapper, int) *httptest.ResponseRecorder func TestGPGKeys(t *testing.T) { defer tests.PrepareTestEnv(t)() @@ -79,7 +79,8 @@ func TestGPGKeys(t *testing.T) { t.Run("CheckState", func(t *testing.T) { var keys []*api.GPGKey - req := NewRequest(t, "GET", "/api/v1/user/gpg_keys?token="+tokenWithGPGKeyScope) // GET all keys + req := NewRequest(t, "GET", "/api/v1/user/gpg_keys"). // GET all keys + AddTokenAuth(tokenWithGPGKeyScope) resp := MakeRequest(t, req, http.StatusOK) DecodeJSON(t, resp, &keys) assert.Len(t, keys, 1) @@ -95,7 +96,8 @@ func TestGPGKeys(t *testing.T) { assert.Empty(t, subKey.Emails) var key api.GPGKey - req = NewRequest(t, "GET", "/api/v1/user/gpg_keys/"+strconv.FormatInt(primaryKey1.ID, 10)+"?token="+tokenWithGPGKeyScope) // Primary key 1 + req = NewRequest(t, "GET", "/api/v1/user/gpg_keys/"+strconv.FormatInt(primaryKey1.ID, 10)). // Primary key 1 + AddTokenAuth(tokenWithGPGKeyScope) resp = MakeRequest(t, req, http.StatusOK) DecodeJSON(t, resp, &key) assert.EqualValues(t, "38EA3BCED732982C", key.KeyID) @@ -103,7 +105,8 @@ func TestGPGKeys(t *testing.T) { assert.EqualValues(t, "user2@example.com", key.Emails[0].Email) assert.True(t, key.Emails[0].Verified) - req = NewRequest(t, "GET", "/api/v1/user/gpg_keys/"+strconv.FormatInt(subKey.ID, 10)+"?token="+tokenWithGPGKeyScope) // Subkey of 38EA3BCED732982C + req = NewRequest(t, "GET", "/api/v1/user/gpg_keys/"+strconv.FormatInt(subKey.ID, 10)). // Subkey of 38EA3BCED732982C + AddTokenAuth(tokenWithGPGKeyScope) resp = MakeRequest(t, req, http.StatusOK) DecodeJSON(t, resp, &key) assert.EqualValues(t, "70D7C694D17D03AD", key.KeyID) @@ -114,7 +117,8 @@ func TestGPGKeys(t *testing.T) { t.Run("CheckCommits", func(t *testing.T) { t.Run("NotSigned", func(t *testing.T) { var branch api.Branch - req := NewRequest(t, "GET", "/api/v1/repos/user2/repo16/branches/not-signed?token="+token) + req := NewRequest(t, "GET", "/api/v1/repos/user2/repo16/branches/not-signed"). + AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusOK) DecodeJSON(t, resp, &branch) assert.False(t, branch.Commit.Verification.Verified) @@ -122,7 +126,8 @@ func TestGPGKeys(t *testing.T) { t.Run("SignedWithNotValidatedEmail", func(t *testing.T) { var branch api.Branch - req := NewRequest(t, "GET", "/api/v1/repos/user2/repo16/branches/good-sign-not-yet-validated?token="+token) + req := NewRequest(t, "GET", "/api/v1/repos/user2/repo16/branches/good-sign-not-yet-validated"). + AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusOK) DecodeJSON(t, resp, &branch) assert.False(t, branch.Commit.Verification.Verified) @@ -130,7 +135,8 @@ func TestGPGKeys(t *testing.T) { t.Run("SignedWithValidEmail", func(t *testing.T) { var branch api.Branch - req := NewRequest(t, "GET", "/api/v1/repos/user2/repo16/branches/good-sign?token="+token) + req := NewRequest(t, "GET", "/api/v1/repos/user2/repo16/branches/good-sign"). + AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusOK) DecodeJSON(t, resp, &branch) assert.True(t, branch.Commit.Verification.Verified) @@ -139,29 +145,33 @@ func TestGPGKeys(t *testing.T) { } func testViewOwnGPGKeys(t *testing.T, makeRequest makeRequestFunc, token string, expected int) { - req := NewRequest(t, "GET", "/api/v1/user/gpg_keys?token="+token) + req := NewRequest(t, "GET", "/api/v1/user/gpg_keys"). + AddTokenAuth(token) makeRequest(t, req, expected) } func testViewGPGKeys(t *testing.T, makeRequest makeRequestFunc, token string, expected int) { - req := NewRequest(t, "GET", "/api/v1/users/user2/gpg_keys?token="+token) + req := NewRequest(t, "GET", "/api/v1/users/user2/gpg_keys"). + AddTokenAuth(token) makeRequest(t, req, expected) } func testGetGPGKey(t *testing.T, makeRequest makeRequestFunc, token string, expected int) { - req := NewRequest(t, "GET", "/api/v1/user/gpg_keys/1?token="+token) + req := NewRequest(t, "GET", "/api/v1/user/gpg_keys/1"). + AddTokenAuth(token) makeRequest(t, req, expected) } func testDeleteGPGKey(t *testing.T, makeRequest makeRequestFunc, token string, expected int) { - req := NewRequest(t, "DELETE", "/api/v1/user/gpg_keys/1?token="+token) + req := NewRequest(t, "DELETE", "/api/v1/user/gpg_keys/1"). + AddTokenAuth(token) makeRequest(t, req, expected) } func testCreateGPGKey(t *testing.T, makeRequest makeRequestFunc, token string, expected int, publicKey string) { - req := NewRequestWithJSON(t, "POST", "/api/v1/user/gpg_keys?token="+token, api.CreateGPGKeyOption{ + req := NewRequestWithJSON(t, "POST", "/api/v1/user/gpg_keys", api.CreateGPGKeyOption{ ArmoredKey: publicKey, - }) + }).AddTokenAuth(token) makeRequest(t, req, expected) } diff --git a/tests/integration/api_helper_for_declarative_test.go b/tests/integration/api_helper_for_declarative_test.go index 3524ce9834a..7755b9861ae 100644 --- a/tests/integration/api_helper_for_declarative_test.go +++ b/tests/integration/api_helper_for_declarative_test.go @@ -59,7 +59,8 @@ func doAPICreateRepository(ctx APITestContext, empty bool, callback ...func(*tes License: "WTFPL", Readme: "Default", } - req := NewRequestWithJSON(t, "POST", "/api/v1/user/repos?token="+ctx.Token, createRepoOption) + req := NewRequestWithJSON(t, "POST", "/api/v1/user/repos", createRepoOption). + AddTokenAuth(ctx.Token) if ctx.ExpectedCode != 0 { ctx.Session.MakeRequest(t, req, ctx.ExpectedCode) return @@ -76,7 +77,8 @@ func doAPICreateRepository(ctx APITestContext, empty bool, callback ...func(*tes func doAPIEditRepository(ctx APITestContext, editRepoOption *api.EditRepoOption, callback ...func(*testing.T, api.Repository)) func(*testing.T) { return func(t *testing.T) { - req := NewRequestWithJSON(t, "PATCH", fmt.Sprintf("/api/v1/repos/%s/%s?token=%s", url.PathEscape(ctx.Username), url.PathEscape(ctx.Reponame), ctx.Token), editRepoOption) + req := NewRequestWithJSON(t, "PATCH", fmt.Sprintf("/api/v1/repos/%s/%s", url.PathEscape(ctx.Username), url.PathEscape(ctx.Reponame)), editRepoOption). + AddTokenAuth(ctx.Token) if ctx.ExpectedCode != 0 { ctx.Session.MakeRequest(t, req, ctx.ExpectedCode) return @@ -103,7 +105,8 @@ func doAPIAddCollaborator(ctx APITestContext, username string, mode perm.AccessM addCollaboratorOption := &api.AddCollaboratorOption{ Permission: &permission, } - req := NewRequestWithJSON(t, "PUT", fmt.Sprintf("/api/v1/repos/%s/%s/collaborators/%s?token=%s", ctx.Username, ctx.Reponame, username, ctx.Token), addCollaboratorOption) + req := NewRequestWithJSON(t, "PUT", fmt.Sprintf("/api/v1/repos/%s/%s/collaborators/%s", ctx.Username, ctx.Reponame, username), addCollaboratorOption). + AddTokenAuth(ctx.Token) if ctx.ExpectedCode != 0 { ctx.Session.MakeRequest(t, req, ctx.ExpectedCode) return @@ -115,7 +118,8 @@ func doAPIAddCollaborator(ctx APITestContext, username string, mode perm.AccessM func doAPIForkRepository(ctx APITestContext, username string, callback ...func(*testing.T, api.Repository)) func(*testing.T) { return func(t *testing.T) { createForkOption := &api.CreateForkOption{} - req := NewRequestWithJSON(t, "POST", fmt.Sprintf("/api/v1/repos/%s/%s/forks?token=%s", username, ctx.Reponame, ctx.Token), createForkOption) + req := NewRequestWithJSON(t, "POST", fmt.Sprintf("/api/v1/repos/%s/%s/forks", username, ctx.Reponame), createForkOption). + AddTokenAuth(ctx.Token) if ctx.ExpectedCode != 0 { ctx.Session.MakeRequest(t, req, ctx.ExpectedCode) return @@ -131,9 +135,8 @@ func doAPIForkRepository(ctx APITestContext, username string, callback ...func(* func doAPIGetRepository(ctx APITestContext, callback ...func(*testing.T, api.Repository)) func(*testing.T) { return func(t *testing.T) { - urlStr := fmt.Sprintf("/api/v1/repos/%s/%s?token=%s", ctx.Username, ctx.Reponame, ctx.Token) - - req := NewRequest(t, "GET", urlStr) + req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/repos/%s/%s", ctx.Username, ctx.Reponame)). + AddTokenAuth(ctx.Token) if ctx.ExpectedCode != 0 { ctx.Session.MakeRequest(t, req, ctx.ExpectedCode) return @@ -150,9 +153,8 @@ func doAPIGetRepository(ctx APITestContext, callback ...func(*testing.T, api.Rep func doAPIDeleteRepository(ctx APITestContext) func(*testing.T) { return func(t *testing.T) { - urlStr := fmt.Sprintf("/api/v1/repos/%s/%s?token=%s", ctx.Username, ctx.Reponame, ctx.Token) - - req := NewRequest(t, "DELETE", urlStr) + req := NewRequest(t, "DELETE", fmt.Sprintf("/api/v1/repos/%s/%s", ctx.Username, ctx.Reponame)). + AddTokenAuth(ctx.Token) if ctx.ExpectedCode != 0 { ctx.Session.MakeRequest(t, req, ctx.ExpectedCode) return @@ -163,14 +165,12 @@ func doAPIDeleteRepository(ctx APITestContext) func(*testing.T) { func doAPICreateUserKey(ctx APITestContext, keyname, keyFile string, callback ...func(*testing.T, api.PublicKey)) func(*testing.T) { return func(t *testing.T) { - urlStr := fmt.Sprintf("/api/v1/user/keys?token=%s", ctx.Token) - dataPubKey, err := os.ReadFile(keyFile + ".pub") assert.NoError(t, err) - req := NewRequestWithJSON(t, "POST", urlStr, &api.CreateKeyOption{ + req := NewRequestWithJSON(t, "POST", "/api/v1/user/keys", &api.CreateKeyOption{ Title: keyname, Key: string(dataPubKey), - }) + }).AddTokenAuth(ctx.Token) if ctx.ExpectedCode != 0 { ctx.Session.MakeRequest(t, req, ctx.ExpectedCode) return @@ -186,9 +186,8 @@ func doAPICreateUserKey(ctx APITestContext, keyname, keyFile string, callback .. func doAPIDeleteUserKey(ctx APITestContext, keyID int64) func(*testing.T) { return func(t *testing.T) { - urlStr := fmt.Sprintf("/api/v1/user/keys/%d?token=%s", keyID, ctx.Token) - - req := NewRequest(t, "DELETE", urlStr) + req := NewRequest(t, "DELETE", fmt.Sprintf("/api/v1/user/keys/%d", keyID)). + AddTokenAuth(ctx.Token) if ctx.ExpectedCode != 0 { ctx.Session.MakeRequest(t, req, ctx.ExpectedCode) return @@ -199,15 +198,13 @@ func doAPIDeleteUserKey(ctx APITestContext, keyID int64) func(*testing.T) { func doAPICreateDeployKey(ctx APITestContext, keyname, keyFile string, readOnly bool) func(*testing.T) { return func(t *testing.T) { - urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/keys?token=%s", ctx.Username, ctx.Reponame, ctx.Token) - dataPubKey, err := os.ReadFile(keyFile + ".pub") assert.NoError(t, err) - req := NewRequestWithJSON(t, "POST", urlStr, api.CreateKeyOption{ + req := NewRequestWithJSON(t, "POST", fmt.Sprintf("/api/v1/repos/%s/%s/keys", ctx.Username, ctx.Reponame), api.CreateKeyOption{ Title: keyname, Key: string(dataPubKey), ReadOnly: readOnly, - }) + }).AddTokenAuth(ctx.Token) if ctx.ExpectedCode != 0 { ctx.Session.MakeRequest(t, req, ctx.ExpectedCode) @@ -219,13 +216,11 @@ func doAPICreateDeployKey(ctx APITestContext, keyname, keyFile string, readOnly func doAPICreatePullRequest(ctx APITestContext, owner, repo, baseBranch, headBranch string) func(*testing.T) (api.PullRequest, error) { return func(t *testing.T) (api.PullRequest, error) { - urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/pulls?token=%s", - owner, repo, ctx.Token) - req := NewRequestWithJSON(t, http.MethodPost, urlStr, &api.CreatePullRequestOption{ + req := NewRequestWithJSON(t, http.MethodPost, fmt.Sprintf("/api/v1/repos/%s/%s/pulls", owner, repo), &api.CreatePullRequestOption{ Head: headBranch, Base: baseBranch, Title: fmt.Sprintf("create a pr from %s to %s", headBranch, baseBranch), - }) + }).AddTokenAuth(ctx.Token) expected := http.StatusCreated if ctx.ExpectedCode != 0 { @@ -242,9 +237,8 @@ func doAPICreatePullRequest(ctx APITestContext, owner, repo, baseBranch, headBra func doAPIGetPullRequest(ctx APITestContext, owner, repo string, index int64) func(*testing.T) (api.PullRequest, error) { return func(t *testing.T) (api.PullRequest, error) { - urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/pulls/%d?token=%s", - owner, repo, index, ctx.Token) - req := NewRequest(t, http.MethodGet, urlStr) + req := NewRequest(t, http.MethodGet, fmt.Sprintf("/api/v1/repos/%s/%s/pulls/%d", owner, repo, index)). + AddTokenAuth(ctx.Token) expected := http.StatusOK if ctx.ExpectedCode != 0 { @@ -261,17 +255,16 @@ func doAPIGetPullRequest(ctx APITestContext, owner, repo string, index int64) fu func doAPIMergePullRequest(ctx APITestContext, owner, repo string, index int64) func(*testing.T) { return func(t *testing.T) { - urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/pulls/%d/merge?token=%s", - owner, repo, index, ctx.Token) + urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/pulls/%d/merge", owner, repo, index) - var req *http.Request + var req *RequestWrapper var resp *httptest.ResponseRecorder for i := 0; i < 6; i++ { req = NewRequestWithJSON(t, http.MethodPost, urlStr, &forms.MergePullRequestForm{ MergeMessageField: "doAPIMergePullRequest Merge", Do: string(repo_model.MergeStyleMerge), - }) + }).AddTokenAuth(ctx.Token) resp = ctx.Session.MakeRequest(t, req, NoExpectedStatus) @@ -299,12 +292,11 @@ func doAPIMergePullRequest(ctx APITestContext, owner, repo string, index int64) func doAPIManuallyMergePullRequest(ctx APITestContext, owner, repo, commitID string, index int64) func(*testing.T) { return func(t *testing.T) { - urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/pulls/%d/merge?token=%s", - owner, repo, index, ctx.Token) + urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/pulls/%d/merge", owner, repo, index) req := NewRequestWithJSON(t, http.MethodPost, urlStr, &forms.MergePullRequestForm{ Do: string(repo_model.MergeStyleManuallyMerged), MergeCommitID: commitID, - }) + }).AddTokenAuth(ctx.Token) if ctx.ExpectedCode != 0 { ctx.Session.MakeRequest(t, req, ctx.ExpectedCode) @@ -316,38 +308,37 @@ func doAPIManuallyMergePullRequest(ctx APITestContext, owner, repo, commitID str func doAPIAutoMergePullRequest(ctx APITestContext, owner, repo string, index int64) func(*testing.T) { return func(t *testing.T) { - urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/pulls/%d/merge?token=%s", - owner, repo, index, ctx.Token) + urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/pulls/%d/merge", owner, repo, index) req := NewRequestWithJSON(t, http.MethodPost, urlStr, &forms.MergePullRequestForm{ MergeMessageField: "doAPIMergePullRequest Merge", Do: string(repo_model.MergeStyleMerge), MergeWhenChecksSucceed: true, - }) + }).AddTokenAuth(ctx.Token) if ctx.ExpectedCode != 0 { ctx.Session.MakeRequest(t, req, ctx.ExpectedCode) return } - ctx.Session.MakeRequest(t, req, 200) + ctx.Session.MakeRequest(t, req, http.StatusOK) } } func doAPICancelAutoMergePullRequest(ctx APITestContext, owner, repo string, index int64) func(*testing.T) { return func(t *testing.T) { - urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/pulls/%d/merge?token=%s", - owner, repo, index, ctx.Token) - req := NewRequest(t, http.MethodDelete, urlStr) + req := NewRequest(t, http.MethodDelete, fmt.Sprintf("/api/v1/repos/%s/%s/pulls/%d/merge", owner, repo, index)). + AddTokenAuth(ctx.Token) if ctx.ExpectedCode != 0 { ctx.Session.MakeRequest(t, req, ctx.ExpectedCode) return } - ctx.Session.MakeRequest(t, req, 204) + ctx.Session.MakeRequest(t, req, http.StatusNoContent) } } func doAPIGetBranch(ctx APITestContext, branch string, callback ...func(*testing.T, api.Branch)) func(*testing.T) { return func(t *testing.T) { - req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/branches/%s?token=%s", ctx.Username, ctx.Reponame, branch, ctx.Token) + req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/branches/%s", ctx.Username, ctx.Reponame, branch). + AddTokenAuth(ctx.Token) if ctx.ExpectedCode != 0 { ctx.Session.MakeRequest(t, req, ctx.ExpectedCode) return @@ -364,8 +355,8 @@ func doAPIGetBranch(ctx APITestContext, branch string, callback ...func(*testing func doAPICreateFile(ctx APITestContext, treepath string, options *api.CreateFileOptions, callback ...func(*testing.T, api.FileResponse)) func(*testing.T) { return func(t *testing.T) { - url := fmt.Sprintf("/api/v1/repos/%s/%s/contents/%s?token=%s", ctx.Username, ctx.Reponame, treepath, ctx.Token) - req := NewRequestWithJSON(t, "POST", url, &options) + req := NewRequestWithJSON(t, "POST", fmt.Sprintf("/api/v1/repos/%s/%s/contents/%s", ctx.Username, ctx.Reponame, treepath), &options). + AddTokenAuth(ctx.Token) if ctx.ExpectedCode != 0 { ctx.Session.MakeRequest(t, req, ctx.ExpectedCode) return @@ -382,9 +373,8 @@ func doAPICreateFile(ctx APITestContext, treepath string, options *api.CreateFil func doAPICreateOrganization(ctx APITestContext, options *api.CreateOrgOption, callback ...func(*testing.T, api.Organization)) func(t *testing.T) { return func(t *testing.T) { - url := fmt.Sprintf("/api/v1/orgs?token=%s", ctx.Token) - - req := NewRequestWithJSON(t, "POST", url, &options) + req := NewRequestWithJSON(t, "POST", "/api/v1/orgs", &options). + AddTokenAuth(ctx.Token) if ctx.ExpectedCode != 0 { ctx.Session.MakeRequest(t, req, ctx.ExpectedCode) return @@ -401,9 +391,8 @@ func doAPICreateOrganization(ctx APITestContext, options *api.CreateOrgOption, c func doAPICreateOrganizationRepository(ctx APITestContext, orgName string, options *api.CreateRepoOption, callback ...func(*testing.T, api.Repository)) func(t *testing.T) { return func(t *testing.T) { - url := fmt.Sprintf("/api/v1/orgs/%s/repos?token=%s", orgName, ctx.Token) - - req := NewRequestWithJSON(t, "POST", url, &options) + req := NewRequestWithJSON(t, "POST", fmt.Sprintf("/api/v1/orgs/%s/repos", orgName), &options). + AddTokenAuth(ctx.Token) if ctx.ExpectedCode != 0 { ctx.Session.MakeRequest(t, req, ctx.ExpectedCode) return @@ -420,9 +409,8 @@ func doAPICreateOrganizationRepository(ctx APITestContext, orgName string, optio func doAPICreateOrganizationTeam(ctx APITestContext, orgName string, options *api.CreateTeamOption, callback ...func(*testing.T, api.Team)) func(t *testing.T) { return func(t *testing.T) { - url := fmt.Sprintf("/api/v1/orgs/%s/teams?token=%s", orgName, ctx.Token) - - req := NewRequestWithJSON(t, "POST", url, &options) + req := NewRequestWithJSON(t, "POST", fmt.Sprintf("/api/v1/orgs/%s/teams", orgName), &options). + AddTokenAuth(ctx.Token) if ctx.ExpectedCode != 0 { ctx.Session.MakeRequest(t, req, ctx.ExpectedCode) return @@ -439,9 +427,8 @@ func doAPICreateOrganizationTeam(ctx APITestContext, orgName string, options *ap func doAPIAddUserToOrganizationTeam(ctx APITestContext, teamID int64, username string) func(t *testing.T) { return func(t *testing.T) { - url := fmt.Sprintf("/api/v1/teams/%d/members/%s?token=%s", teamID, username, ctx.Token) - - req := NewRequest(t, "PUT", url) + req := NewRequest(t, "PUT", fmt.Sprintf("/api/v1/teams/%d/members/%s", teamID, username)). + AddTokenAuth(ctx.Token) if ctx.ExpectedCode != 0 { ctx.Session.MakeRequest(t, req, ctx.ExpectedCode) return @@ -452,9 +439,8 @@ func doAPIAddUserToOrganizationTeam(ctx APITestContext, teamID int64, username s func doAPIAddRepoToOrganizationTeam(ctx APITestContext, teamID int64, orgName, repoName string) func(t *testing.T) { return func(t *testing.T) { - url := fmt.Sprintf("/api/v1/teams/%d/repos/%s/%s?token=%s", teamID, orgName, repoName, ctx.Token) - - req := NewRequest(t, "PUT", url) + req := NewRequest(t, "PUT", fmt.Sprintf("/api/v1/teams/%d/repos/%s/%s", teamID, orgName, repoName)). + AddTokenAuth(ctx.Token) if ctx.ExpectedCode != 0 { ctx.Session.MakeRequest(t, req, ctx.ExpectedCode) return diff --git a/tests/integration/api_httpsig_test.go b/tests/integration/api_httpsig_test.go index 675ec54ff58..30aed3cacce 100644 --- a/tests/integration/api_httpsig_test.go +++ b/tests/integration/api_httpsig_test.go @@ -5,7 +5,6 @@ package integration import ( "encoding/base64" - "fmt" "net/http" "net/url" "testing" @@ -57,14 +56,14 @@ func TestHTTPSigPubKey(t *testing.T) { defer test.MockVariableValue(&setting.SSH.MinimumKeySizeCheck, false)() session := loginUser(t, "user1") token := url.QueryEscape(getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteUser)) - keysURL := fmt.Sprintf("/api/v1/user/keys?token=%s", token) keyType := "ssh-rsa" keyContent := "AAAAB3NzaC1yc2EAAAADAQABAAABAQCqOZB5vkRvXFXups1/0StDRdG8plbNSwsWEnNnP4Bvurxa0+z3W9B8GLKnDiLw5MbpbMNyBlpXw13GfuIeciy10DWTz0xUbiy3J3KabCaT36asIw2y7k6Z0jL0UBnrVENwq5/lUbZYqSZ4rRU744wkhh8TULpzM14npQCZwg6aEbG+MwjzddQ72fR+3BPBrKn5dTmmu8rH99O+U+Nuto81Tg7PA+NUupcHOmhdiEGq49plgVFXK98Vks5tiybL4GuzFyWgyX73Dg/QBMn2eMHt1EMv5Gs3i6GFhKKGo4rjDi9qI6PX5oDR4LTNe6cR8td8YhVD8WFZwLLl/vaYyIqd" rawKeyBody := api.CreateKeyOption{ Title: "test-key", Key: keyType + " " + keyContent, } - req := NewRequestWithJSON(t, "POST", keysURL, rawKeyBody) + req := NewRequestWithJSON(t, "POST", "/api/v1/user/keys", rawKeyBody). + AddTokenAuth(token) MakeRequest(t, req, http.StatusCreated) // parse our private key and create the httpsig request @@ -73,7 +72,8 @@ func TestHTTPSigPubKey(t *testing.T) { // create the request token = getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeReadAdmin) - req = NewRequest(t, "GET", fmt.Sprintf("/api/v1/admin/users?token=%s", token)) + req = NewRequest(t, "GET", "/api/v1/admin/users"). + AddTokenAuth(token) signer, _, err := httpsig.NewSSHSigner(sshSigner, httpsig.DigestSha512, []string{httpsig.RequestTarget, "(created)", "(expires)"}, httpsig.Signature, 10) if err != nil { @@ -81,7 +81,7 @@ func TestHTTPSigPubKey(t *testing.T) { } // sign the request - err = signer.SignRequest(keyID, req, nil) + err = signer.SignRequest(keyID, req.Request, nil) if err != nil { t.Fatal(err) } @@ -124,7 +124,7 @@ func TestHTTPSigCert(t *testing.T) { // add our cert to the request certString := base64.RawStdEncoding.EncodeToString(pkcert.(*ssh.Certificate).Marshal()) - req.Header.Add("x-ssh-certificate", certString) + req.SetHeader("x-ssh-certificate", certString) signer, _, err := httpsig.NewSSHSigner(certSigner, httpsig.DigestSha512, []string{httpsig.RequestTarget, "(created)", "(expires)", "x-ssh-certificate"}, httpsig.Signature, 10) if err != nil { @@ -132,7 +132,7 @@ func TestHTTPSigCert(t *testing.T) { } // sign the request - err = signer.SignRequest(keyID, req, nil) + err = signer.SignRequest(keyID, req.Request, nil) if err != nil { t.Fatal(err) } diff --git a/tests/integration/api_issue_attachment_test.go b/tests/integration/api_issue_attachment_test.go index 3b43ba2c412..4b57d387d87 100644 --- a/tests/integration/api_issue_attachment_test.go +++ b/tests/integration/api_issue_attachment_test.go @@ -33,10 +33,9 @@ func TestAPIGetIssueAttachment(t *testing.T) { session := loginUser(t, repoOwner.Name) token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeReadIssue) - urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/issues/%d/assets/%d?token=%s", - repoOwner.Name, repo.Name, issue.Index, attachment.ID, token) - req := NewRequest(t, "GET", urlStr) + req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/repos/%s/%s/issues/%d/assets/%d", repoOwner.Name, repo.Name, issue.Index, attachment.ID)). + AddTokenAuth(token) resp := session.MakeRequest(t, req, http.StatusOK) apiAttachment := new(api.Attachment) DecodeJSON(t, resp, &apiAttachment) @@ -54,10 +53,9 @@ func TestAPIListIssueAttachments(t *testing.T) { session := loginUser(t, repoOwner.Name) token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeReadIssue) - urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/issues/%d/assets?token=%s", - repoOwner.Name, repo.Name, issue.Index, token) - req := NewRequest(t, "GET", urlStr) + req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/repos/%s/%s/issues/%d/assets", repoOwner.Name, repo.Name, issue.Index)). + AddTokenAuth(token) resp := session.MakeRequest(t, req, http.StatusOK) apiAttachment := new([]api.Attachment) DecodeJSON(t, resp, &apiAttachment) @@ -74,8 +72,6 @@ func TestAPICreateIssueAttachment(t *testing.T) { session := loginUser(t, repoOwner.Name) token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteIssue) - urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/issues/%d/assets?token=%s", - repoOwner.Name, repo.Name, issue.Index, token) filename := "image.png" buff := generateImg() @@ -90,7 +86,8 @@ func TestAPICreateIssueAttachment(t *testing.T) { err = writer.Close() assert.NoError(t, err) - req := NewRequestWithBody(t, "POST", urlStr, body) + req := NewRequestWithBody(t, "POST", fmt.Sprintf("/api/v1/repos/%s/%s/issues/%d/assets", repoOwner.Name, repo.Name, issue.Index), body). + AddTokenAuth(token) req.Header.Add("Content-Type", writer.FormDataContentType()) resp := session.MakeRequest(t, req, http.StatusCreated) @@ -112,11 +109,11 @@ func TestAPIEditIssueAttachment(t *testing.T) { session := loginUser(t, repoOwner.Name) token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteIssue) - urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/issues/%d/assets/%d?token=%s", - repoOwner.Name, repo.Name, issue.Index, attachment.ID, token) + urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/issues/%d/assets/%d", + repoOwner.Name, repo.Name, issue.Index, attachment.ID) req := NewRequestWithValues(t, "PATCH", urlStr, map[string]string{ "name": newAttachmentName, - }) + }).AddTokenAuth(token) resp := session.MakeRequest(t, req, http.StatusCreated) apiAttachment := new(api.Attachment) DecodeJSON(t, resp, &apiAttachment) @@ -134,10 +131,9 @@ func TestAPIDeleteIssueAttachment(t *testing.T) { session := loginUser(t, repoOwner.Name) token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteIssue) - urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/issues/%d/assets/%d?token=%s", - repoOwner.Name, repo.Name, issue.Index, attachment.ID, token) - req := NewRequest(t, "DELETE", urlStr) + req := NewRequest(t, "DELETE", fmt.Sprintf("/api/v1/repos/%s/%s/issues/%d/assets/%d", repoOwner.Name, repo.Name, issue.Index, attachment.ID)). + AddTokenAuth(token) session.MakeRequest(t, req, http.StatusNoContent) unittest.AssertNotExistsBean(t, &repo_model.Attachment{ID: attachment.ID, IssueID: issue.ID}) diff --git a/tests/integration/api_issue_label_test.go b/tests/integration/api_issue_label_test.go index d2d8af102b3..35c07182634 100644 --- a/tests/integration/api_issue_label_test.go +++ b/tests/integration/api_issue_label_test.go @@ -26,14 +26,14 @@ func TestAPIModifyLabels(t *testing.T) { owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}) session := loginUser(t, owner.Name) token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteIssue) - urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/labels?token=%s", owner.Name, repo.Name, token) + urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/labels", owner.Name, repo.Name) // CreateLabel req := NewRequestWithJSON(t, "POST", urlStr, &api.CreateLabelOption{ Name: "TestL 1", Color: "abcdef", Description: "test label", - }) + }).AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusCreated) apiLabel := new(api.Label) DecodeJSON(t, resp, &apiLabel) @@ -45,24 +45,26 @@ func TestAPIModifyLabels(t *testing.T) { Name: "TestL 2", Color: "#123456", Description: "jet another test label", - }) + }).AddTokenAuth(token) MakeRequest(t, req, http.StatusCreated) req = NewRequestWithJSON(t, "POST", urlStr, &api.CreateLabelOption{ Name: "WrongTestL", Color: "#12345g", - }) + }).AddTokenAuth(token) MakeRequest(t, req, http.StatusUnprocessableEntity) // ListLabels - req = NewRequest(t, "GET", urlStr) + req = NewRequest(t, "GET", urlStr). + AddTokenAuth(token) resp = MakeRequest(t, req, http.StatusOK) var apiLabels []*api.Label DecodeJSON(t, resp, &apiLabels) assert.Len(t, apiLabels, 2) // GetLabel - singleURLStr := fmt.Sprintf("/api/v1/repos/%s/%s/labels/%d?token=%s", owner.Name, repo.Name, dbLabel.ID, token) - req = NewRequest(t, "GET", singleURLStr) + singleURLStr := fmt.Sprintf("/api/v1/repos/%s/%s/labels/%d", owner.Name, repo.Name, dbLabel.ID) + req = NewRequest(t, "GET", singleURLStr). + AddTokenAuth(token) resp = MakeRequest(t, req, http.StatusOK) DecodeJSON(t, resp, &apiLabel) assert.EqualValues(t, strings.TrimLeft(dbLabel.Color, "#"), apiLabel.Color) @@ -74,17 +76,18 @@ func TestAPIModifyLabels(t *testing.T) { req = NewRequestWithJSON(t, "PATCH", singleURLStr, &api.EditLabelOption{ Name: &newName, Color: &newColor, - }) + }).AddTokenAuth(token) resp = MakeRequest(t, req, http.StatusOK) DecodeJSON(t, resp, &apiLabel) assert.EqualValues(t, newColor, apiLabel.Color) req = NewRequestWithJSON(t, "PATCH", singleURLStr, &api.EditLabelOption{ Color: &newColorWrong, - }) + }).AddTokenAuth(token) MakeRequest(t, req, http.StatusUnprocessableEntity) // DeleteLabel - req = NewRequest(t, "DELETE", singleURLStr) + req = NewRequest(t, "DELETE", singleURLStr). + AddTokenAuth(token) MakeRequest(t, req, http.StatusNoContent) } @@ -98,11 +101,11 @@ func TestAPIAddIssueLabels(t *testing.T) { session := loginUser(t, owner.Name) token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteIssue) - urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/issues/%d/labels?token=%s", - repo.OwnerName, repo.Name, issue.Index, token) + urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/issues/%d/labels", + repo.OwnerName, repo.Name, issue.Index) req := NewRequestWithJSON(t, "POST", urlStr, &api.IssueLabelsOption{ Labels: []int64{1, 2}, - }) + }).AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusOK) var apiLabels []*api.Label DecodeJSON(t, resp, &apiLabels) @@ -121,11 +124,11 @@ func TestAPIReplaceIssueLabels(t *testing.T) { session := loginUser(t, owner.Name) token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteIssue) - urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/issues/%d/labels?token=%s", - owner.Name, repo.Name, issue.Index, token) + urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/issues/%d/labels", + owner.Name, repo.Name, issue.Index) req := NewRequestWithJSON(t, "PUT", urlStr, &api.IssueLabelsOption{ Labels: []int64{label.ID}, - }) + }).AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusOK) var apiLabels []*api.Label DecodeJSON(t, resp, &apiLabels) @@ -145,14 +148,14 @@ func TestAPIModifyOrgLabels(t *testing.T) { user := "user1" session := loginUser(t, user) token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteRepository, auth_model.AccessTokenScopeWriteOrganization) - urlStr := fmt.Sprintf("/api/v1/orgs/%s/labels?token=%s", owner.Name, token) + urlStr := fmt.Sprintf("/api/v1/orgs/%s/labels", owner.Name) // CreateLabel req := NewRequestWithJSON(t, "POST", urlStr, &api.CreateLabelOption{ Name: "TestL 1", Color: "abcdef", Description: "test label", - }) + }).AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusCreated) apiLabel := new(api.Label) DecodeJSON(t, resp, &apiLabel) @@ -164,24 +167,26 @@ func TestAPIModifyOrgLabels(t *testing.T) { Name: "TestL 2", Color: "#123456", Description: "jet another test label", - }) + }).AddTokenAuth(token) MakeRequest(t, req, http.StatusCreated) req = NewRequestWithJSON(t, "POST", urlStr, &api.CreateLabelOption{ Name: "WrongTestL", Color: "#12345g", - }) + }).AddTokenAuth(token) MakeRequest(t, req, http.StatusUnprocessableEntity) // ListLabels - req = NewRequest(t, "GET", urlStr) + req = NewRequest(t, "GET", urlStr). + AddTokenAuth(token) resp = MakeRequest(t, req, http.StatusOK) var apiLabels []*api.Label DecodeJSON(t, resp, &apiLabels) assert.Len(t, apiLabels, 4) // GetLabel - singleURLStr := fmt.Sprintf("/api/v1/orgs/%s/labels/%d?token=%s", owner.Name, dbLabel.ID, token) - req = NewRequest(t, "GET", singleURLStr) + singleURLStr := fmt.Sprintf("/api/v1/orgs/%s/labels/%d", owner.Name, dbLabel.ID) + req = NewRequest(t, "GET", singleURLStr). + AddTokenAuth(token) resp = MakeRequest(t, req, http.StatusOK) DecodeJSON(t, resp, &apiLabel) assert.EqualValues(t, strings.TrimLeft(dbLabel.Color, "#"), apiLabel.Color) @@ -193,16 +198,17 @@ func TestAPIModifyOrgLabels(t *testing.T) { req = NewRequestWithJSON(t, "PATCH", singleURLStr, &api.EditLabelOption{ Name: &newName, Color: &newColor, - }) + }).AddTokenAuth(token) resp = MakeRequest(t, req, http.StatusOK) DecodeJSON(t, resp, &apiLabel) assert.EqualValues(t, newColor, apiLabel.Color) req = NewRequestWithJSON(t, "PATCH", singleURLStr, &api.EditLabelOption{ Color: &newColorWrong, - }) + }).AddTokenAuth(token) MakeRequest(t, req, http.StatusUnprocessableEntity) // DeleteLabel - req = NewRequest(t, "DELETE", singleURLStr) + req = NewRequest(t, "DELETE", singleURLStr). + AddTokenAuth(token) MakeRequest(t, req, http.StatusNoContent) } diff --git a/tests/integration/api_issue_milestone_test.go b/tests/integration/api_issue_milestone_test.go index 3bd763f4b52..32ac56298fa 100644 --- a/tests/integration/api_issue_milestone_test.go +++ b/tests/integration/api_issue_milestone_test.go @@ -34,48 +34,53 @@ func TestAPIIssuesMilestone(t *testing.T) { // update values of issue milestoneState := "closed" - urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/milestones/%d?token=%s", owner.Name, repo.Name, milestone.ID, token) + urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/milestones/%d", owner.Name, repo.Name, milestone.ID) req := NewRequestWithJSON(t, "PATCH", urlStr, structs.EditMilestoneOption{ State: &milestoneState, - }) + }).AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusOK) var apiMilestone structs.Milestone DecodeJSON(t, resp, &apiMilestone) assert.EqualValues(t, "closed", apiMilestone.State) - req = NewRequest(t, "GET", urlStr) + req = NewRequest(t, "GET", urlStr). + AddTokenAuth(token) resp = MakeRequest(t, req, http.StatusOK) var apiMilestone2 structs.Milestone DecodeJSON(t, resp, &apiMilestone2) assert.EqualValues(t, "closed", apiMilestone2.State) - req = NewRequestWithJSON(t, "POST", fmt.Sprintf("/api/v1/repos/%s/%s/milestones?token=%s", owner.Name, repo.Name, token), structs.CreateMilestoneOption{ + req = NewRequestWithJSON(t, "POST", fmt.Sprintf("/api/v1/repos/%s/%s/milestones", owner.Name, repo.Name), structs.CreateMilestoneOption{ Title: "wow", Description: "closed one", State: "closed", - }) + }).AddTokenAuth(token) resp = MakeRequest(t, req, http.StatusCreated) DecodeJSON(t, resp, &apiMilestone) assert.Equal(t, "wow", apiMilestone.Title) assert.Equal(t, structs.StateClosed, apiMilestone.State) var apiMilestones []structs.Milestone - req = NewRequest(t, "GET", fmt.Sprintf("/api/v1/repos/%s/%s/milestones?state=%s&token=%s", owner.Name, repo.Name, "all", token)) + req = NewRequest(t, "GET", fmt.Sprintf("/api/v1/repos/%s/%s/milestones?state=%s", owner.Name, repo.Name, "all")). + AddTokenAuth(token) resp = MakeRequest(t, req, http.StatusOK) DecodeJSON(t, resp, &apiMilestones) assert.Len(t, apiMilestones, 4) - req = NewRequest(t, "GET", fmt.Sprintf("/api/v1/repos/%s/%s/milestones/%s?token=%s", owner.Name, repo.Name, apiMilestones[2].Title, token)) + req = NewRequest(t, "GET", fmt.Sprintf("/api/v1/repos/%s/%s/milestones/%s", owner.Name, repo.Name, apiMilestones[2].Title)). + AddTokenAuth(token) resp = MakeRequest(t, req, http.StatusOK) DecodeJSON(t, resp, &apiMilestone) assert.EqualValues(t, apiMilestones[2], apiMilestone) - req = NewRequest(t, "GET", fmt.Sprintf("/api/v1/repos/%s/%s/milestones?state=%s&name=%s&token=%s", owner.Name, repo.Name, "all", "milestone2", token)) + req = NewRequest(t, "GET", fmt.Sprintf("/api/v1/repos/%s/%s/milestones?state=%s&name=%s", owner.Name, repo.Name, "all", "milestone2")). + AddTokenAuth(token) resp = MakeRequest(t, req, http.StatusOK) DecodeJSON(t, resp, &apiMilestones) assert.Len(t, apiMilestones, 1) assert.Equal(t, int64(2), apiMilestones[0].ID) - req = NewRequest(t, "DELETE", fmt.Sprintf("/api/v1/repos/%s/%s/milestones/%d?token=%s", owner.Name, repo.Name, apiMilestone.ID, token)) + req = NewRequest(t, "DELETE", fmt.Sprintf("/api/v1/repos/%s/%s/milestones/%d", owner.Name, repo.Name, apiMilestone.ID)). + AddTokenAuth(token) MakeRequest(t, req, http.StatusNoContent) } diff --git a/tests/integration/api_issue_pin_test.go b/tests/integration/api_issue_pin_test.go index 5a9efc058bf..1cff937254b 100644 --- a/tests/integration/api_issue_pin_test.go +++ b/tests/integration/api_issue_pin_test.go @@ -32,14 +32,12 @@ func TestAPIPinIssue(t *testing.T) { token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteIssue) // Pin the Issue - urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/issues/%d/pin?token=%s", - repo.OwnerName, repo.Name, issue.Index, token) - req := NewRequest(t, "POST", urlStr) + req := NewRequest(t, "POST", fmt.Sprintf("/api/v1/repos/%s/%s/issues/%d/pin", repo.OwnerName, repo.Name, issue.Index)). + AddTokenAuth(token) MakeRequest(t, req, http.StatusNoContent) // Check if the Issue is pinned - urlStr = fmt.Sprintf("/api/v1/repos/%s/%s/issues/%d", repo.OwnerName, repo.Name, issue.Index) - req = NewRequest(t, "GET", urlStr) + req = NewRequest(t, "GET", fmt.Sprintf("/api/v1/repos/%s/%s/issues/%d", repo.OwnerName, repo.Name, issue.Index)) resp := MakeRequest(t, req, http.StatusOK) var issueAPI api.Issue DecodeJSON(t, resp, &issueAPI) @@ -59,28 +57,24 @@ func TestAPIUnpinIssue(t *testing.T) { token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteIssue) // Pin the Issue - urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/issues/%d/pin?token=%s", - repo.OwnerName, repo.Name, issue.Index, token) - req := NewRequest(t, "POST", urlStr) + req := NewRequest(t, "POST", fmt.Sprintf("/api/v1/repos/%s/%s/issues/%d/pin", repo.OwnerName, repo.Name, issue.Index)). + AddTokenAuth(token) MakeRequest(t, req, http.StatusNoContent) // Check if the Issue is pinned - urlStr = fmt.Sprintf("/api/v1/repos/%s/%s/issues/%d", repo.OwnerName, repo.Name, issue.Index) - req = NewRequest(t, "GET", urlStr) + req = NewRequest(t, "GET", fmt.Sprintf("/api/v1/repos/%s/%s/issues/%d", repo.OwnerName, repo.Name, issue.Index)) resp := MakeRequest(t, req, http.StatusOK) var issueAPI api.Issue DecodeJSON(t, resp, &issueAPI) assert.Equal(t, 1, issueAPI.PinOrder) // Unpin the Issue - urlStr = fmt.Sprintf("/api/v1/repos/%s/%s/issues/%d/pin?token=%s", - repo.OwnerName, repo.Name, issue.Index, token) - req = NewRequest(t, "DELETE", urlStr) + req = NewRequest(t, "DELETE", fmt.Sprintf("/api/v1/repos/%s/%s/issues/%d/pin", repo.OwnerName, repo.Name, issue.Index)). + AddTokenAuth(token) MakeRequest(t, req, http.StatusNoContent) // Check if the Issue is no longer pinned - urlStr = fmt.Sprintf("/api/v1/repos/%s/%s/issues/%d", repo.OwnerName, repo.Name, issue.Index) - req = NewRequest(t, "GET", urlStr) + req = NewRequest(t, "GET", fmt.Sprintf("/api/v1/repos/%s/%s/issues/%d", repo.OwnerName, repo.Name, issue.Index)) resp = MakeRequest(t, req, http.StatusOK) DecodeJSON(t, resp, &issueAPI) assert.Equal(t, 0, issueAPI.PinOrder) @@ -100,42 +94,36 @@ func TestAPIMoveIssuePin(t *testing.T) { token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteIssue) // Pin the first Issue - urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/issues/%d/pin?token=%s", - repo.OwnerName, repo.Name, issue.Index, token) - req := NewRequest(t, "POST", urlStr) + req := NewRequest(t, "POST", fmt.Sprintf("/api/v1/repos/%s/%s/issues/%d/pin", repo.OwnerName, repo.Name, issue.Index)). + AddTokenAuth(token) MakeRequest(t, req, http.StatusNoContent) // Check if the first Issue is pinned at position 1 - urlStr = fmt.Sprintf("/api/v1/repos/%s/%s/issues/%d", repo.OwnerName, repo.Name, issue.Index) - req = NewRequest(t, "GET", urlStr) + req = NewRequest(t, "GET", fmt.Sprintf("/api/v1/repos/%s/%s/issues/%d", repo.OwnerName, repo.Name, issue.Index)) resp := MakeRequest(t, req, http.StatusOK) var issueAPI api.Issue DecodeJSON(t, resp, &issueAPI) assert.Equal(t, 1, issueAPI.PinOrder) // Pin the second Issue - urlStr = fmt.Sprintf("/api/v1/repos/%s/%s/issues/%d/pin?token=%s", - repo.OwnerName, repo.Name, issue2.Index, token) - req = NewRequest(t, "POST", urlStr) + req = NewRequest(t, "POST", fmt.Sprintf("/api/v1/repos/%s/%s/issues/%d/pin", repo.OwnerName, repo.Name, issue2.Index)). + AddTokenAuth(token) MakeRequest(t, req, http.StatusNoContent) // Move the first Issue to position 2 - urlStr = fmt.Sprintf("/api/v1/repos/%s/%s/issues/%d/pin/2?token=%s", - repo.OwnerName, repo.Name, issue.Index, token) - req = NewRequest(t, "PATCH", urlStr) + req = NewRequest(t, "PATCH", fmt.Sprintf("/api/v1/repos/%s/%s/issues/%d/pin/2", repo.OwnerName, repo.Name, issue.Index)). + AddTokenAuth(token) MakeRequest(t, req, http.StatusNoContent) // Check if the first Issue is pinned at position 2 - urlStr = fmt.Sprintf("/api/v1/repos/%s/%s/issues/%d", repo.OwnerName, repo.Name, issue.Index) - req = NewRequest(t, "GET", urlStr) + req = NewRequest(t, "GET", fmt.Sprintf("/api/v1/repos/%s/%s/issues/%d", repo.OwnerName, repo.Name, issue.Index)) resp = MakeRequest(t, req, http.StatusOK) var issueAPI3 api.Issue DecodeJSON(t, resp, &issueAPI3) assert.Equal(t, 2, issueAPI3.PinOrder) // Check if the second Issue is pinned at position 1 - urlStr = fmt.Sprintf("/api/v1/repos/%s/%s/issues/%d", repo.OwnerName, repo.Name, issue2.Index) - req = NewRequest(t, "GET", urlStr) + req = NewRequest(t, "GET", fmt.Sprintf("/api/v1/repos/%s/%s/issues/%d", repo.OwnerName, repo.Name, issue2.Index)) resp = MakeRequest(t, req, http.StatusOK) var issueAPI4 api.Issue DecodeJSON(t, resp, &issueAPI4) @@ -155,14 +143,12 @@ func TestAPIListPinnedIssues(t *testing.T) { token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteIssue) // Pin the Issue - urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/issues/%d/pin?token=%s", - repo.OwnerName, repo.Name, issue.Index, token) - req := NewRequest(t, "POST", urlStr) + req := NewRequest(t, "POST", fmt.Sprintf("/api/v1/repos/%s/%s/issues/%d/pin", repo.OwnerName, repo.Name, issue.Index)). + AddTokenAuth(token) MakeRequest(t, req, http.StatusNoContent) // Check if the Issue is in the List - urlStr = fmt.Sprintf("/api/v1/repos/%s/%s/issues/pinned", repo.OwnerName, repo.Name) - req = NewRequest(t, "GET", urlStr) + req = NewRequest(t, "GET", fmt.Sprintf("/api/v1/repos/%s/%s/issues/pinned", repo.OwnerName, repo.Name)) resp := MakeRequest(t, req, http.StatusOK) var issueList []api.Issue DecodeJSON(t, resp, &issueList) @@ -178,8 +164,7 @@ func TestAPIListPinnedPullrequests(t *testing.T) { repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}) - urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/pulls/pinned", repo.OwnerName, repo.Name) - req := NewRequest(t, "GET", urlStr) + req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/repos/%s/%s/pulls/pinned", repo.OwnerName, repo.Name)) resp := MakeRequest(t, req, http.StatusOK) var prList []api.PullRequest DecodeJSON(t, resp, &prList) @@ -193,8 +178,7 @@ func TestAPINewPinAllowed(t *testing.T) { repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}) owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}) - urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/new_pin_allowed", owner.Name, repo.Name) - req := NewRequest(t, "GET", urlStr) + req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/repos/%s/%s/new_pin_allowed", owner.Name, repo.Name)) resp := MakeRequest(t, req, http.StatusOK) var newPinsAllowed api.NewIssuePinsAllowed diff --git a/tests/integration/api_issue_reaction_test.go b/tests/integration/api_issue_reaction_test.go index 124d729353c..4ca909f2812 100644 --- a/tests/integration/api_issue_reaction_test.go +++ b/tests/integration/api_issue_reaction_test.go @@ -33,25 +33,24 @@ func TestAPIIssuesReactions(t *testing.T) { token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteIssue) user2 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) - urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/issues/%d/reactions?token=%s", - owner.Name, issue.Repo.Name, issue.Index, token) + urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/issues/%d/reactions", owner.Name, issue.Repo.Name, issue.Index) // Try to add not allowed reaction req := NewRequestWithJSON(t, "POST", urlStr, &api.EditReactionOption{ Reaction: "wrong", - }) + }).AddTokenAuth(token) MakeRequest(t, req, http.StatusForbidden) // Delete not allowed reaction req = NewRequestWithJSON(t, "DELETE", urlStr, &api.EditReactionOption{ Reaction: "zzz", - }) + }).AddTokenAuth(token) MakeRequest(t, req, http.StatusOK) // Add allowed reaction req = NewRequestWithJSON(t, "POST", urlStr, &api.EditReactionOption{ Reaction: "rocket", - }) + }).AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusCreated) var apiNewReaction api.Reaction DecodeJSON(t, resp, &apiNewReaction) @@ -60,7 +59,8 @@ func TestAPIIssuesReactions(t *testing.T) { MakeRequest(t, req, http.StatusForbidden) // Get end result of reaction list of issue #1 - req = NewRequestf(t, "GET", urlStr) + req = NewRequest(t, "GET", urlStr). + AddTokenAuth(token) resp = MakeRequest(t, req, http.StatusOK) var apiReactions []*api.Reaction DecodeJSON(t, resp, &apiReactions) @@ -93,19 +93,18 @@ func TestAPICommentReactions(t *testing.T) { user1 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1}) user2 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) - urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/issues/comments/%d/reactions?token=%s", - owner.Name, issue.Repo.Name, comment.ID, token) + urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/issues/comments/%d/reactions", owner.Name, issue.Repo.Name, comment.ID) // Try to add not allowed reaction req := NewRequestWithJSON(t, "POST", urlStr, &api.EditReactionOption{ Reaction: "wrong", - }) + }).AddTokenAuth(token) MakeRequest(t, req, http.StatusForbidden) // Delete none existing reaction req = NewRequestWithJSON(t, "DELETE", urlStr, &api.EditReactionOption{ Reaction: "eyes", - }) + }).AddTokenAuth(token) MakeRequest(t, req, http.StatusOK) t.Run("UnrelatedCommentID", func(t *testing.T) { @@ -113,25 +112,25 @@ func TestAPICommentReactions(t *testing.T) { repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 4}) repoOwner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}) token := getUserToken(t, repoOwner.Name, auth_model.AccessTokenScopeWriteIssue) - urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/issues/comments/%d/reactions?token=%s", - repoOwner.Name, repo.Name, comment.ID, token) + urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/issues/comments/%d/reactions", repoOwner.Name, repo.Name, comment.ID) req = NewRequestWithJSON(t, "POST", urlStr, &api.EditReactionOption{ Reaction: "+1", - }) + }).AddTokenAuth(token) MakeRequest(t, req, http.StatusNotFound) req = NewRequestWithJSON(t, "DELETE", urlStr, &api.EditReactionOption{ Reaction: "+1", - }) + }).AddTokenAuth(token) MakeRequest(t, req, http.StatusNotFound) - req = NewRequestf(t, "GET", urlStr) + req = NewRequest(t, "GET", urlStr). + AddTokenAuth(token) MakeRequest(t, req, http.StatusNotFound) }) // Add allowed reaction req = NewRequestWithJSON(t, "POST", urlStr, &api.EditReactionOption{ Reaction: "+1", - }) + }).AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusCreated) var apiNewReaction api.Reaction DecodeJSON(t, resp, &apiNewReaction) @@ -140,7 +139,8 @@ func TestAPICommentReactions(t *testing.T) { MakeRequest(t, req, http.StatusForbidden) // Get end result of reaction list of issue #1 - req = NewRequestf(t, "GET", urlStr) + req = NewRequest(t, "GET", urlStr). + AddTokenAuth(token) resp = MakeRequest(t, req, http.StatusOK) var apiReactions []*api.Reaction DecodeJSON(t, resp, &apiReactions) diff --git a/tests/integration/api_issue_stopwatch_test.go b/tests/integration/api_issue_stopwatch_test.go index 09d404ce4e2..23066782173 100644 --- a/tests/integration/api_issue_stopwatch_test.go +++ b/tests/integration/api_issue_stopwatch_test.go @@ -27,7 +27,8 @@ func TestAPIListStopWatches(t *testing.T) { session := loginUser(t, owner.Name) token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeReadRepository, auth_model.AccessTokenScopeReadUser) - req := NewRequestf(t, "GET", "/api/v1/user/stopwatches?token=%s", token) + req := NewRequest(t, "GET", "/api/v1/user/stopwatches"). + AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusOK) var apiWatches []*api.StopWatch DecodeJSON(t, resp, &apiWatches) @@ -54,7 +55,8 @@ func TestAPIStopStopWatches(t *testing.T) { session := loginUser(t, user.Name) token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteIssue) - req := NewRequestf(t, "POST", "/api/v1/repos/%s/%s/issues/%d/stopwatch/stop?token=%s", owner.Name, issue.Repo.Name, issue.Index, token) + req := NewRequestf(t, "POST", "/api/v1/repos/%s/%s/issues/%d/stopwatch/stop", owner.Name, issue.Repo.Name, issue.Index). + AddTokenAuth(token) MakeRequest(t, req, http.StatusCreated) MakeRequest(t, req, http.StatusConflict) } @@ -70,7 +72,8 @@ func TestAPICancelStopWatches(t *testing.T) { session := loginUser(t, user.Name) token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteIssue) - req := NewRequestf(t, "DELETE", "/api/v1/repos/%s/%s/issues/%d/stopwatch/delete?token=%s", owner.Name, issue.Repo.Name, issue.Index, token) + req := NewRequestf(t, "DELETE", "/api/v1/repos/%s/%s/issues/%d/stopwatch/delete", owner.Name, issue.Repo.Name, issue.Index). + AddTokenAuth(token) MakeRequest(t, req, http.StatusNoContent) MakeRequest(t, req, http.StatusConflict) } @@ -86,7 +89,8 @@ func TestAPIStartStopWatches(t *testing.T) { session := loginUser(t, user.Name) token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteIssue) - req := NewRequestf(t, "POST", "/api/v1/repos/%s/%s/issues/%d/stopwatch/start?token=%s", owner.Name, issue.Repo.Name, issue.Index, token) + req := NewRequestf(t, "POST", "/api/v1/repos/%s/%s/issues/%d/stopwatch/start", owner.Name, issue.Repo.Name, issue.Index). + AddTokenAuth(token) MakeRequest(t, req, http.StatusCreated) MakeRequest(t, req, http.StatusConflict) } diff --git a/tests/integration/api_issue_subscription_test.go b/tests/integration/api_issue_subscription_test.go index 28650a33752..7a716301c46 100644 --- a/tests/integration/api_issue_subscription_test.go +++ b/tests/integration/api_issue_subscription_test.go @@ -37,8 +37,8 @@ func TestAPIIssueSubscriptions(t *testing.T) { testSubscription := func(issue *issues_model.Issue, isWatching bool) { issueRepo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: issue.RepoID}) - urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/issues/%d/subscriptions/check?token=%s", issueRepo.OwnerName, issueRepo.Name, issue.Index, token) - req := NewRequest(t, "GET", urlStr) + req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/repos/%s/%s/issues/%d/subscriptions/check", issueRepo.OwnerName, issueRepo.Name, issue.Index)). + AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusOK) wi := new(api.WatchInfo) DecodeJSON(t, resp, wi) @@ -57,22 +57,26 @@ func TestAPIIssueSubscriptions(t *testing.T) { testSubscription(issue5, false) issue1Repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: issue1.RepoID}) - urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/issues/%d/subscriptions/%s?token=%s", issue1Repo.OwnerName, issue1Repo.Name, issue1.Index, owner.Name, token) - req := NewRequest(t, "DELETE", urlStr) + urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/issues/%d/subscriptions/%s", issue1Repo.OwnerName, issue1Repo.Name, issue1.Index, owner.Name) + req := NewRequest(t, "DELETE", urlStr). + AddTokenAuth(token) MakeRequest(t, req, http.StatusCreated) testSubscription(issue1, false) - req = NewRequest(t, "DELETE", urlStr) + req = NewRequest(t, "DELETE", urlStr). + AddTokenAuth(token) MakeRequest(t, req, http.StatusOK) testSubscription(issue1, false) issue5Repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: issue5.RepoID}) - urlStr = fmt.Sprintf("/api/v1/repos/%s/%s/issues/%d/subscriptions/%s?token=%s", issue5Repo.OwnerName, issue5Repo.Name, issue5.Index, owner.Name, token) - req = NewRequest(t, "PUT", urlStr) + urlStr = fmt.Sprintf("/api/v1/repos/%s/%s/issues/%d/subscriptions/%s", issue5Repo.OwnerName, issue5Repo.Name, issue5.Index, owner.Name) + req = NewRequest(t, "PUT", urlStr). + AddTokenAuth(token) MakeRequest(t, req, http.StatusCreated) testSubscription(issue5, true) - req = NewRequest(t, "PUT", urlStr) + req = NewRequest(t, "PUT", urlStr). + AddTokenAuth(token) MakeRequest(t, req, http.StatusOK) testSubscription(issue5, true) } diff --git a/tests/integration/api_issue_test.go b/tests/integration/api_issue_test.go index 29f09fa09e7..dcccafb0f29 100644 --- a/tests/integration/api_issue_test.go +++ b/tests/integration/api_issue_test.go @@ -84,12 +84,12 @@ func TestAPICreateIssue(t *testing.T) { session := loginUser(t, owner.Name) token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteIssue) - urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/issues?state=all&token=%s", owner.Name, repoBefore.Name, token) + urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/issues?state=all", owner.Name, repoBefore.Name) req := NewRequestWithJSON(t, "POST", urlStr, &api.CreateIssueOption{ Body: body, Title: title, Assignee: owner.Name, - }) + }).AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusCreated) var apiIssue api.Issue DecodeJSON(t, resp, &apiIssue) @@ -117,7 +117,7 @@ func TestAPICreateIssueParallel(t *testing.T) { session := loginUser(t, owner.Name) token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteIssue) - urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/issues?state=all&token=%s", owner.Name, repoBefore.Name, token) + urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/issues?state=all", owner.Name, repoBefore.Name) var wg sync.WaitGroup for i := 0; i < 10; i++ { @@ -130,7 +130,7 @@ func TestAPICreateIssueParallel(t *testing.T) { Body: newBody, Title: newTitle, Assignee: owner.Name, - }) + }).AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusCreated) var apiIssue api.Issue DecodeJSON(t, resp, &apiIssue) @@ -171,7 +171,7 @@ func TestAPIEditIssue(t *testing.T) { body := "new content!" title := "new title from api set" - urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/issues/%d?token=%s", owner.Name, repoBefore.Name, issueBefore.Index, token) + urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/issues/%d", owner.Name, repoBefore.Name, issueBefore.Index) req := NewRequestWithJSON(t, "PATCH", urlStr, api.EditIssueOption{ State: &issueState, RemoveDeadline: &removeDeadline, @@ -180,7 +180,7 @@ func TestAPIEditIssue(t *testing.T) { Title: title, // ToDo change more - }) + }).AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusCreated) var apiIssue api.Issue DecodeJSON(t, resp, &apiIssue) diff --git a/tests/integration/api_issue_tracked_time_test.go b/tests/integration/api_issue_tracked_time_test.go index d3e45456a6c..fd2c452b206 100644 --- a/tests/integration/api_issue_tracked_time_test.go +++ b/tests/integration/api_issue_tracked_time_test.go @@ -30,7 +30,8 @@ func TestAPIGetTrackedTimes(t *testing.T) { session := loginUser(t, user2.Name) token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeReadIssue) - req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/issues/%d/times?token=%s", user2.Name, issue2.Repo.Name, issue2.Index, token) + req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/issues/%d/times", user2.Name, issue2.Repo.Name, issue2.Index). + AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusOK) var apiTimes api.TrackedTimeList DecodeJSON(t, resp, &apiTimes) @@ -53,7 +54,8 @@ func TestAPIGetTrackedTimes(t *testing.T) { since := "2000-01-01T00%3A00%3A02%2B00%3A00" // 946684802 before := "2000-01-01T00%3A00%3A12%2B00%3A00" // 946684812 - req = NewRequestf(t, "GET", "/api/v1/repos/%s/%s/issues/%d/times?since=%s&before=%s&token=%s", user2.Name, issue2.Repo.Name, issue2.Index, since, before, token) + req = NewRequestf(t, "GET", "/api/v1/repos/%s/%s/issues/%d/times?since=%s&before=%s", user2.Name, issue2.Repo.Name, issue2.Index, since, before). + AddTokenAuth(token) resp = MakeRequest(t, req, http.StatusOK) var filterAPITimes api.TrackedTimeList DecodeJSON(t, resp, &filterAPITimes) @@ -74,11 +76,13 @@ func TestAPIDeleteTrackedTime(t *testing.T) { token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteIssue) // Deletion not allowed - req := NewRequestf(t, "DELETE", "/api/v1/repos/%s/%s/issues/%d/times/%d?token=%s", user2.Name, issue2.Repo.Name, issue2.Index, time6.ID, token) + req := NewRequestf(t, "DELETE", "/api/v1/repos/%s/%s/issues/%d/times/%d", user2.Name, issue2.Repo.Name, issue2.Index, time6.ID). + AddTokenAuth(token) MakeRequest(t, req, http.StatusForbidden) time3 := unittest.AssertExistsAndLoadBean(t, &issues_model.TrackedTime{ID: 3}) - req = NewRequestf(t, "DELETE", "/api/v1/repos/%s/%s/issues/%d/times/%d?token=%s", user2.Name, issue2.Repo.Name, issue2.Index, time3.ID, token) + req = NewRequestf(t, "DELETE", "/api/v1/repos/%s/%s/issues/%d/times/%d", user2.Name, issue2.Repo.Name, issue2.Index, time3.ID). + AddTokenAuth(token) MakeRequest(t, req, http.StatusNoContent) // Delete non existing time MakeRequest(t, req, http.StatusNotFound) @@ -88,7 +92,8 @@ func TestAPIDeleteTrackedTime(t *testing.T) { assert.NoError(t, err) assert.Equal(t, int64(3661), trackedSeconds) - req = NewRequestf(t, "DELETE", "/api/v1/repos/%s/%s/issues/%d/times?token=%s", user2.Name, issue2.Repo.Name, issue2.Index, token) + req = NewRequestf(t, "DELETE", "/api/v1/repos/%s/%s/issues/%d/times", user2.Name, issue2.Repo.Name, issue2.Index). + AddTokenAuth(token) MakeRequest(t, req, http.StatusNoContent) MakeRequest(t, req, http.StatusNotFound) @@ -108,13 +113,13 @@ func TestAPIAddTrackedTimes(t *testing.T) { session := loginUser(t, admin.Name) token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteIssue) - urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/issues/%d/times?token=%s", user2.Name, issue2.Repo.Name, issue2.Index, token) + urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/issues/%d/times", user2.Name, issue2.Repo.Name, issue2.Index) req := NewRequestWithJSON(t, "POST", urlStr, &api.AddTimeOption{ Time: 33, User: user2.Name, Created: time.Unix(947688818, 0), - }) + }).AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusOK) var apiNewTime api.TrackedTime DecodeJSON(t, resp, &apiNewTime) diff --git a/tests/integration/api_keys_test.go b/tests/integration/api_keys_test.go index 03d28c91266..89ad1ec0df5 100644 --- a/tests/integration/api_keys_test.go +++ b/tests/integration/api_keys_test.go @@ -55,13 +55,14 @@ func TestCreateReadOnlyDeployKey(t *testing.T) { session := loginUser(t, repoOwner.Name) token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteRepository) - keysURL := fmt.Sprintf("/api/v1/repos/%s/%s/keys?token=%s", repoOwner.Name, repo.Name, token) + keysURL := fmt.Sprintf("/api/v1/repos/%s/%s/keys", repoOwner.Name, repo.Name) rawKeyBody := api.CreateKeyOption{ Title: "read-only", Key: "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQC4cn+iXnA4KvcQYSV88vGn0Yi91vG47t1P7okprVmhNTkipNRIHWr6WdCO4VDr/cvsRkuVJAsLO2enwjGWWueOO6BodiBgyAOZ/5t5nJNMCNuLGT5UIo/RI1b0WRQwxEZTRjt6mFNw6lH14wRd8ulsr9toSWBPMOGWoYs1PDeDL0JuTjL+tr1SZi/EyxCngpYszKdXllJEHyI79KQgeD0Vt3pTrkbNVTOEcCNqZePSVmUH8X8Vhugz3bnE0/iE9Pb5fkWO9c4AnM1FgI/8Bvp27Fw2ShryIXuR6kKvUqhVMTuOSDHwu6A8jLE5Owt3GAYugDpDYuwTVNGrHLXKpPzrGGPE/jPmaLCMZcsdkec95dYeU3zKODEm8UQZFhmJmDeWVJ36nGrGZHL4J5aTTaeFUJmmXDaJYiJ+K2/ioKgXqnXvltu0A9R8/LGy4nrTJRr4JMLuJFoUXvGm1gXQ70w2LSpk6yl71RNC0hCtsBe8BP8IhYCM0EP5jh7eCMQZNvM= nocomment\n", ReadOnly: true, } - req := NewRequestWithJSON(t, "POST", keysURL, rawKeyBody) + req := NewRequestWithJSON(t, "POST", keysURL, rawKeyBody). + AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusCreated) var newDeployKey api.DeployKey @@ -75,12 +76,14 @@ func TestCreateReadOnlyDeployKey(t *testing.T) { // Using the ID of a key that does not belong to the repository must fail { - req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/repos/%s/%s/keys/%d?token=%s", repoOwner.Name, repo.Name, newDeployKey.ID, token)) + req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/repos/%s/%s/keys/%d", repoOwner.Name, repo.Name, newDeployKey.ID)). + AddTokenAuth(token) MakeRequest(t, req, http.StatusOK) session5 := loginUser(t, "user5") token5 := getTokenForLoggedInUser(t, session5, auth_model.AccessTokenScopeWriteRepository) - req = NewRequest(t, "GET", fmt.Sprintf("/api/v1/repos/user5/repo4/keys/%d?token=%s", newDeployKey.ID, token5)) + req = NewRequest(t, "GET", fmt.Sprintf("/api/v1/repos/user5/repo4/keys/%d", newDeployKey.ID)). + AddTokenAuth(token5) MakeRequest(t, req, http.StatusNotFound) } } @@ -92,12 +95,13 @@ func TestCreateReadWriteDeployKey(t *testing.T) { session := loginUser(t, repoOwner.Name) token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteRepository) - keysURL := fmt.Sprintf("/api/v1/repos/%s/%s/keys?token=%s", repoOwner.Name, repo.Name, token) + keysURL := fmt.Sprintf("/api/v1/repos/%s/%s/keys", repoOwner.Name, repo.Name) rawKeyBody := api.CreateKeyOption{ Title: "read-write", Key: "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQC4cn+iXnA4KvcQYSV88vGn0Yi91vG47t1P7okprVmhNTkipNRIHWr6WdCO4VDr/cvsRkuVJAsLO2enwjGWWueOO6BodiBgyAOZ/5t5nJNMCNuLGT5UIo/RI1b0WRQwxEZTRjt6mFNw6lH14wRd8ulsr9toSWBPMOGWoYs1PDeDL0JuTjL+tr1SZi/EyxCngpYszKdXllJEHyI79KQgeD0Vt3pTrkbNVTOEcCNqZePSVmUH8X8Vhugz3bnE0/iE9Pb5fkWO9c4AnM1FgI/8Bvp27Fw2ShryIXuR6kKvUqhVMTuOSDHwu6A8jLE5Owt3GAYugDpDYuwTVNGrHLXKpPzrGGPE/jPmaLCMZcsdkec95dYeU3zKODEm8UQZFhmJmDeWVJ36nGrGZHL4J5aTTaeFUJmmXDaJYiJ+K2/ioKgXqnXvltu0A9R8/LGy4nrTJRr4JMLuJFoUXvGm1gXQ70w2LSpk6yl71RNC0hCtsBe8BP8IhYCM0EP5jh7eCMQZNvM= nocomment\n", } - req := NewRequestWithJSON(t, "POST", keysURL, rawKeyBody) + req := NewRequestWithJSON(t, "POST", keysURL, rawKeyBody). + AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusCreated) var newDeployKey api.DeployKey @@ -116,14 +120,14 @@ func TestCreateUserKey(t *testing.T) { session := loginUser(t, "user1") token := url.QueryEscape(getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteUser)) - keysURL := fmt.Sprintf("/api/v1/user/keys?token=%s", token) keyType := "ssh-rsa" keyContent := "AAAAB3NzaC1yc2EAAAADAQABAAABgQC4cn+iXnA4KvcQYSV88vGn0Yi91vG47t1P7okprVmhNTkipNRIHWr6WdCO4VDr/cvsRkuVJAsLO2enwjGWWueOO6BodiBgyAOZ/5t5nJNMCNuLGT5UIo/RI1b0WRQwxEZTRjt6mFNw6lH14wRd8ulsr9toSWBPMOGWoYs1PDeDL0JuTjL+tr1SZi/EyxCngpYszKdXllJEHyI79KQgeD0Vt3pTrkbNVTOEcCNqZePSVmUH8X8Vhugz3bnE0/iE9Pb5fkWO9c4AnM1FgI/8Bvp27Fw2ShryIXuR6kKvUqhVMTuOSDHwu6A8jLE5Owt3GAYugDpDYuwTVNGrHLXKpPzrGGPE/jPmaLCMZcsdkec95dYeU3zKODEm8UQZFhmJmDeWVJ36nGrGZHL4J5aTTaeFUJmmXDaJYiJ+K2/ioKgXqnXvltu0A9R8/LGy4nrTJRr4JMLuJFoUXvGm1gXQ70w2LSpk6yl71RNC0hCtsBe8BP8IhYCM0EP5jh7eCMQZNvM=" rawKeyBody := api.CreateKeyOption{ Title: "test-key", Key: keyType + " " + keyContent, } - req := NewRequestWithJSON(t, "POST", keysURL, rawKeyBody) + req := NewRequestWithJSON(t, "POST", "/api/v1/user/keys", rawKeyBody). + AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusCreated) var newPublicKey api.PublicKey @@ -139,9 +143,8 @@ func TestCreateUserKey(t *testing.T) { }) // Search by fingerprint - fingerprintURL := fmt.Sprintf("/api/v1/user/keys?token=%s&fingerprint=%s", token, newPublicKey.Fingerprint) - - req = NewRequest(t, "GET", fingerprintURL) + req = NewRequest(t, "GET", fmt.Sprintf("/api/v1/user/keys?fingerprint=%s", newPublicKey.Fingerprint)). + AddTokenAuth(token) resp = MakeRequest(t, req, http.StatusOK) var fingerprintPublicKeys []api.PublicKey @@ -150,9 +153,8 @@ func TestCreateUserKey(t *testing.T) { assert.Equal(t, newPublicKey.ID, fingerprintPublicKeys[0].ID) assert.Equal(t, user.ID, fingerprintPublicKeys[0].Owner.ID) - fingerprintURL = fmt.Sprintf("/api/v1/users/%s/keys?token=%s&fingerprint=%s", user.Name, token, newPublicKey.Fingerprint) - - req = NewRequest(t, "GET", fingerprintURL) + req = NewRequest(t, "GET", fmt.Sprintf("/api/v1/users/%s/keys?fingerprint=%s", user.Name, newPublicKey.Fingerprint)). + AddTokenAuth(token) resp = MakeRequest(t, req, http.StatusOK) DecodeJSON(t, resp, &fingerprintPublicKeys) @@ -161,17 +163,16 @@ func TestCreateUserKey(t *testing.T) { assert.Equal(t, user.ID, fingerprintPublicKeys[0].Owner.ID) // Fail search by fingerprint - fingerprintURL = fmt.Sprintf("/api/v1/user/keys?token=%s&fingerprint=%sA", token, newPublicKey.Fingerprint) - - req = NewRequest(t, "GET", fingerprintURL) + req = NewRequest(t, "GET", fmt.Sprintf("/api/v1/user/keys?fingerprint=%sA", newPublicKey.Fingerprint)). + AddTokenAuth(token) resp = MakeRequest(t, req, http.StatusOK) DecodeJSON(t, resp, &fingerprintPublicKeys) assert.Len(t, fingerprintPublicKeys, 0) // Fail searching for wrong users key - fingerprintURL = fmt.Sprintf("/api/v1/users/%s/keys?token=%s&fingerprint=%s", "user2", token, newPublicKey.Fingerprint) - req = NewRequest(t, "GET", fingerprintURL) + req = NewRequest(t, "GET", fmt.Sprintf("/api/v1/users/%s/keys?fingerprint=%s", "user2", newPublicKey.Fingerprint)). + AddTokenAuth(token) resp = MakeRequest(t, req, http.StatusOK) DecodeJSON(t, resp, &fingerprintPublicKeys) @@ -179,11 +180,11 @@ func TestCreateUserKey(t *testing.T) { // Now login as user 2 session2 := loginUser(t, "user2") - token2 := url.QueryEscape(getTokenForLoggedInUser(t, session2, auth_model.AccessTokenScopeWriteUser)) + token2 := getTokenForLoggedInUser(t, session2, auth_model.AccessTokenScopeWriteUser) // Should find key even though not ours, but we shouldn't know whose it is - fingerprintURL = fmt.Sprintf("/api/v1/user/keys?token=%s&fingerprint=%s", token2, newPublicKey.Fingerprint) - req = NewRequest(t, "GET", fingerprintURL) + req = NewRequest(t, "GET", fmt.Sprintf("/api/v1/user/keys?fingerprint=%s", newPublicKey.Fingerprint)). + AddTokenAuth(token2) resp = MakeRequest(t, req, http.StatusOK) DecodeJSON(t, resp, &fingerprintPublicKeys) @@ -192,9 +193,8 @@ func TestCreateUserKey(t *testing.T) { assert.Nil(t, fingerprintPublicKeys[0].Owner) // Should find key even though not ours, but we shouldn't know whose it is - fingerprintURL = fmt.Sprintf("/api/v1/users/%s/keys?token=%s&fingerprint=%s", user.Name, token2, newPublicKey.Fingerprint) - - req = NewRequest(t, "GET", fingerprintURL) + req = NewRequest(t, "GET", fmt.Sprintf("/api/v1/users/%s/keys?fingerprint=%s", user.Name, newPublicKey.Fingerprint)). + AddTokenAuth(token2) resp = MakeRequest(t, req, http.StatusOK) DecodeJSON(t, resp, &fingerprintPublicKeys) @@ -203,8 +203,8 @@ func TestCreateUserKey(t *testing.T) { assert.Nil(t, fingerprintPublicKeys[0].Owner) // Fail when searching for key if it is not ours - fingerprintURL = fmt.Sprintf("/api/v1/users/%s/keys?token=%s&fingerprint=%s", "user2", token2, newPublicKey.Fingerprint) - req = NewRequest(t, "GET", fingerprintURL) + req = NewRequest(t, "GET", fmt.Sprintf("/api/v1/users/%s/keys?fingerprint=%s", "user2", newPublicKey.Fingerprint)). + AddTokenAuth(token2) resp = MakeRequest(t, req, http.StatusOK) DecodeJSON(t, resp, &fingerprintPublicKeys) diff --git a/tests/integration/api_nodeinfo_test.go b/tests/integration/api_nodeinfo_test.go index fb35d72ac2f..a727aea3ce8 100644 --- a/tests/integration/api_nodeinfo_test.go +++ b/tests/integration/api_nodeinfo_test.go @@ -24,7 +24,7 @@ func TestNodeinfo(t *testing.T) { }() onGiteaRun(t, func(*testing.T, *url.URL) { - req := NewRequestf(t, "GET", "/api/v1/nodeinfo") + req := NewRequest(t, "GET", "/api/v1/nodeinfo") resp := MakeRequest(t, req, http.StatusOK) VerifyJSONSchema(t, resp, "nodeinfo_2.1.json") diff --git a/tests/integration/api_notification_test.go b/tests/integration/api_notification_test.go index c6ee576e592..528890ca22b 100644 --- a/tests/integration/api_notification_test.go +++ b/tests/integration/api_notification_test.go @@ -35,7 +35,8 @@ func TestAPINotification(t *testing.T) { // -- GET /notifications -- // test filter since := "2000-01-01T00%3A50%3A01%2B00%3A00" // 946687801 - req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/notifications?since=%s&token=%s", since, token)) + req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/notifications?since=%s", since)). + AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusOK) var apiNL []api.NotificationThread DecodeJSON(t, resp, &apiNL) @@ -46,7 +47,8 @@ func TestAPINotification(t *testing.T) { // test filter before := "2000-01-01T01%3A06%3A59%2B00%3A00" // 946688819 - req = NewRequest(t, "GET", fmt.Sprintf("/api/v1/notifications?all=%s&before=%s&token=%s", "true", before, token)) + req = NewRequest(t, "GET", fmt.Sprintf("/api/v1/notifications?all=%s&before=%s", "true", before)). + AddTokenAuth(token) resp = MakeRequest(t, req, http.StatusOK) DecodeJSON(t, resp, &apiNL) @@ -62,7 +64,8 @@ func TestAPINotification(t *testing.T) { assert.False(t, apiNL[2].Pinned) // -- GET /repos/{owner}/{repo}/notifications -- - req = NewRequest(t, "GET", fmt.Sprintf("/api/v1/repos/%s/%s/notifications?status-types=unread&token=%s", user2.Name, repo1.Name, token)) + req = NewRequest(t, "GET", fmt.Sprintf("/api/v1/repos/%s/%s/notifications?status-types=unread", user2.Name, repo1.Name)). + AddTokenAuth(token) resp = MakeRequest(t, req, http.StatusOK) DecodeJSON(t, resp, &apiNL) @@ -70,7 +73,8 @@ func TestAPINotification(t *testing.T) { assert.EqualValues(t, 4, apiNL[0].ID) // -- GET /repos/{owner}/{repo}/notifications -- multiple status-types - req = NewRequest(t, "GET", fmt.Sprintf("/api/v1/repos/%s/%s/notifications?status-types=unread&status-types=pinned&token=%s", user2.Name, repo1.Name, token)) + req = NewRequest(t, "GET", fmt.Sprintf("/api/v1/repos/%s/%s/notifications?status-types=unread&status-types=pinned", user2.Name, repo1.Name)). + AddTokenAuth(token) resp = MakeRequest(t, req, http.StatusOK) DecodeJSON(t, resp, &apiNL) @@ -86,11 +90,13 @@ func TestAPINotification(t *testing.T) { // -- GET /notifications/threads/{id} -- // get forbidden - req = NewRequest(t, "GET", fmt.Sprintf("/api/v1/notifications/threads/%d?token=%s", 1, token)) + req = NewRequest(t, "GET", fmt.Sprintf("/api/v1/notifications/threads/%d", 1)). + AddTokenAuth(token) MakeRequest(t, req, http.StatusForbidden) // get own - req = NewRequest(t, "GET", fmt.Sprintf("/api/v1/notifications/threads/%d?token=%s", thread5.ID, token)) + req = NewRequest(t, "GET", fmt.Sprintf("/api/v1/notifications/threads/%d", thread5.ID)). + AddTokenAuth(token) resp = MakeRequest(t, req, http.StatusOK) var apiN api.NotificationThread DecodeJSON(t, resp, &apiN) @@ -110,28 +116,33 @@ func TestAPINotification(t *testing.T) { }{} // -- check notifications -- - req = NewRequest(t, "GET", fmt.Sprintf("/api/v1/notifications/new?token=%s", token)) + req = NewRequest(t, "GET", "/api/v1/notifications/new"). + AddTokenAuth(token) resp = MakeRequest(t, req, http.StatusOK) DecodeJSON(t, resp, &new) assert.True(t, new.New > 0) // -- mark notifications as read -- - req = NewRequest(t, "GET", fmt.Sprintf("/api/v1/notifications?status-types=unread&token=%s", token)) + req = NewRequest(t, "GET", "/api/v1/notifications?status-types=unread"). + AddTokenAuth(token) resp = MakeRequest(t, req, http.StatusOK) DecodeJSON(t, resp, &apiNL) assert.Len(t, apiNL, 2) lastReadAt := "2000-01-01T00%3A50%3A01%2B00%3A00" // 946687801 <- only Notification 4 is in this filter ... - req = NewRequest(t, "PUT", fmt.Sprintf("/api/v1/repos/%s/%s/notifications?last_read_at=%s&token=%s", user2.Name, repo1.Name, lastReadAt, token)) + req = NewRequest(t, "PUT", fmt.Sprintf("/api/v1/repos/%s/%s/notifications?last_read_at=%s", user2.Name, repo1.Name, lastReadAt)). + AddTokenAuth(token) MakeRequest(t, req, http.StatusResetContent) - req = NewRequest(t, "GET", fmt.Sprintf("/api/v1/notifications?status-types=unread&token=%s", token)) + req = NewRequest(t, "GET", "/api/v1/notifications?status-types=unread"). + AddTokenAuth(token) resp = MakeRequest(t, req, http.StatusOK) DecodeJSON(t, resp, &apiNL) assert.Len(t, apiNL, 1) // -- PATCH /notifications/threads/{id} -- - req = NewRequest(t, "PATCH", fmt.Sprintf("/api/v1/notifications/threads/%d?token=%s", thread5.ID, token)) + req = NewRequest(t, "PATCH", fmt.Sprintf("/api/v1/notifications/threads/%d", thread5.ID)). + AddTokenAuth(token) MakeRequest(t, req, http.StatusResetContent) assert.Equal(t, activities_model.NotificationStatusUnread, thread5.Status) @@ -139,7 +150,8 @@ func TestAPINotification(t *testing.T) { assert.Equal(t, activities_model.NotificationStatusRead, thread5.Status) // -- check notifications -- - req = NewRequest(t, "GET", fmt.Sprintf("/api/v1/notifications/new?token=%s", token)) + req = NewRequest(t, "GET", "/api/v1/notifications/new"). + AddTokenAuth(token) resp = MakeRequest(t, req, http.StatusOK) DecodeJSON(t, resp, &new) assert.True(t, new.New == 0) @@ -155,7 +167,8 @@ func TestAPINotificationPUT(t *testing.T) { token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteNotification) // Check notifications are as expected - req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/notifications?all=true&token=%s", token)) + req := NewRequest(t, "GET", "/api/v1/notifications?all=true"). + AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusOK) var apiNL []api.NotificationThread DecodeJSON(t, resp, &apiNL) @@ -178,7 +191,8 @@ func TestAPINotificationPUT(t *testing.T) { // Notification ID 2 is the only one with status-type read & pinned // change it to unread. // - req = NewRequest(t, "PUT", fmt.Sprintf("/api/v1/notifications?status-types=read&status-type=pinned&to-status=unread&token=%s", token)) + req = NewRequest(t, "PUT", "/api/v1/notifications?status-types=read&status-type=pinned&to-status=unread"). + AddTokenAuth(token) resp = MakeRequest(t, req, http.StatusResetContent) DecodeJSON(t, resp, &apiNL) assert.Len(t, apiNL, 1) @@ -189,7 +203,8 @@ func TestAPINotificationPUT(t *testing.T) { // // Now nofication ID 2 is the first in the list and is unread. // - req = NewRequest(t, "GET", fmt.Sprintf("/api/v1/notifications?all=true&token=%s", token)) + req = NewRequest(t, "GET", "/api/v1/notifications?all=true"). + AddTokenAuth(token) resp = MakeRequest(t, req, http.StatusOK) DecodeJSON(t, resp, &apiNL) diff --git a/tests/integration/api_oauth2_apps_test.go b/tests/integration/api_oauth2_apps_test.go index 72cdba2ea2f..0ea3dc72ff9 100644 --- a/tests/integration/api_oauth2_apps_test.go +++ b/tests/integration/api_oauth2_apps_test.go @@ -36,8 +36,8 @@ func testAPICreateOAuth2Application(t *testing.T) { ConfidentialClient: true, } - req := NewRequestWithJSON(t, "POST", "/api/v1/user/applications/oauth2", &appBody) - req = AddBasicAuthHeader(req, user.Name) + req := NewRequestWithJSON(t, "POST", "/api/v1/user/applications/oauth2", &appBody). + AddBasicAuth(user.Name) resp := MakeRequest(t, req, http.StatusCreated) var createdApp *api.OAuth2Application @@ -66,8 +66,8 @@ func testAPIListOAuth2Applications(t *testing.T) { ConfidentialClient: true, }) - urlStr := fmt.Sprintf("/api/v1/user/applications/oauth2?token=%s", token) - req := NewRequest(t, "GET", urlStr) + req := NewRequest(t, "GET", "/api/v1/user/applications/oauth2"). + AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusOK) var appList api.OAuth2ApplicationList @@ -93,14 +93,16 @@ func testAPIDeleteOAuth2Application(t *testing.T) { Name: "test-app-1", }) - urlStr := fmt.Sprintf("/api/v1/user/applications/oauth2/%d?token=%s", oldApp.ID, token) - req := NewRequest(t, "DELETE", urlStr) + urlStr := fmt.Sprintf("/api/v1/user/applications/oauth2/%d", oldApp.ID) + req := NewRequest(t, "DELETE", urlStr). + AddTokenAuth(token) MakeRequest(t, req, http.StatusNoContent) unittest.AssertNotExistsBean(t, &auth_model.OAuth2Application{UID: oldApp.UID, Name: oldApp.Name}) // Delete again will return not found - req = NewRequest(t, "DELETE", urlStr) + req = NewRequest(t, "DELETE", urlStr). + AddTokenAuth(token) MakeRequest(t, req, http.StatusNotFound) } @@ -118,8 +120,8 @@ func testAPIGetOAuth2Application(t *testing.T) { ConfidentialClient: true, }) - urlStr := fmt.Sprintf("/api/v1/user/applications/oauth2/%d?token=%s", existApp.ID, token) - req := NewRequest(t, "GET", urlStr) + req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/user/applications/oauth2/%d", existApp.ID)). + AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusOK) var app api.OAuth2Application @@ -157,8 +159,8 @@ func testAPIUpdateOAuth2Application(t *testing.T) { } urlStr := fmt.Sprintf("/api/v1/user/applications/oauth2/%d", existApp.ID) - req := NewRequestWithJSON(t, "PATCH", urlStr, &appBody) - req = AddBasicAuthHeader(req, user.Name) + req := NewRequestWithJSON(t, "PATCH", urlStr, &appBody). + AddBasicAuth(user.Name) resp := MakeRequest(t, req, http.StatusOK) var app api.OAuth2Application diff --git a/tests/integration/api_org_avatar_test.go b/tests/integration/api_org_avatar_test.go index 91100c8eb78..cc1452c1535 100644 --- a/tests/integration/api_org_avatar_test.go +++ b/tests/integration/api_org_avatar_test.go @@ -34,7 +34,8 @@ func TestAPIUpdateOrgAvatar(t *testing.T) { Image: base64.StdEncoding.EncodeToString(avatar), } - req := NewRequestWithJSON(t, "POST", "/api/v1/orgs/org3/avatar?token="+token, &opts) + req := NewRequestWithJSON(t, "POST", "/api/v1/orgs/org3/avatar", &opts). + AddTokenAuth(token) MakeRequest(t, req, http.StatusNoContent) // Test what happens if you don't have a valid Base64 string @@ -42,7 +43,8 @@ func TestAPIUpdateOrgAvatar(t *testing.T) { Image: "Invalid", } - req = NewRequestWithJSON(t, "POST", "/api/v1/orgs/org3/avatar?token="+token, &opts) + req = NewRequestWithJSON(t, "POST", "/api/v1/orgs/org3/avatar", &opts). + AddTokenAuth(token) MakeRequest(t, req, http.StatusBadRequest) // Test what happens if you use a file that is not an image @@ -56,7 +58,8 @@ func TestAPIUpdateOrgAvatar(t *testing.T) { Image: base64.StdEncoding.EncodeToString(text), } - req = NewRequestWithJSON(t, "POST", "/api/v1/orgs/org3/avatar?token="+token, &opts) + req = NewRequestWithJSON(t, "POST", "/api/v1/orgs/org3/avatar", &opts). + AddTokenAuth(token) MakeRequest(t, req, http.StatusInternalServerError) } @@ -67,6 +70,7 @@ func TestAPIDeleteOrgAvatar(t *testing.T) { token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteOrganization) - req := NewRequest(t, "DELETE", "/api/v1/orgs/org3/avatar?token="+token) + req := NewRequest(t, "DELETE", "/api/v1/orgs/org3/avatar"). + AddTokenAuth(token) MakeRequest(t, req, http.StatusNoContent) } diff --git a/tests/integration/api_org_test.go b/tests/integration/api_org_test.go index f19b46c2f44..1cd82fe4e09 100644 --- a/tests/integration/api_org_test.go +++ b/tests/integration/api_org_test.go @@ -36,7 +36,8 @@ func TestAPIOrgCreate(t *testing.T) { Location: "Shanghai", Visibility: "limited", } - req := NewRequestWithJSON(t, "POST", "/api/v1/orgs?token="+token, &org) + req := NewRequestWithJSON(t, "POST", "/api/v1/orgs", &org). + AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusCreated) var apiOrg api.Organization @@ -71,12 +72,14 @@ func TestAPIOrgCreate(t *testing.T) { }) } - req = NewRequestf(t, "GET", "/api/v1/orgs/%s?token=%s", org.UserName, token) + req = NewRequestf(t, "GET", "/api/v1/orgs/%s", org.UserName). + AddTokenAuth(token) resp = MakeRequest(t, req, http.StatusOK) DecodeJSON(t, resp, &apiOrg) assert.EqualValues(t, org.UserName, apiOrg.Name) - req = NewRequestf(t, "GET", "/api/v1/orgs/%s/repos?token=%s", org.UserName, token) + req = NewRequestf(t, "GET", "/api/v1/orgs/%s/repos", org.UserName). + AddTokenAuth(token) resp = MakeRequest(t, req, http.StatusOK) var repos []*api.Repository @@ -85,7 +88,8 @@ func TestAPIOrgCreate(t *testing.T) { assert.False(t, repo.Private) } - req = NewRequestf(t, "GET", "/api/v1/orgs/%s/members?token=%s", org.UserName, token) + req = NewRequestf(t, "GET", "/api/v1/orgs/%s/members", org.UserName). + AddTokenAuth(token) resp = MakeRequest(t, req, http.StatusOK) // user1 on this org is public @@ -108,7 +112,8 @@ func TestAPIOrgEdit(t *testing.T) { Location: "Beijing", Visibility: "private", } - req := NewRequestWithJSON(t, "PATCH", "/api/v1/orgs/org3?token="+token, &org) + req := NewRequestWithJSON(t, "PATCH", "/api/v1/orgs/org3", &org). + AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusOK) var apiOrg api.Organization @@ -135,7 +140,8 @@ func TestAPIOrgEditBadVisibility(t *testing.T) { Location: "Beijing", Visibility: "badvisibility", } - req := NewRequestWithJSON(t, "PATCH", "/api/v1/orgs/org3?token="+token, &org) + req := NewRequestWithJSON(t, "PATCH", "/api/v1/orgs/org3", &org). + AddTokenAuth(token) MakeRequest(t, req, http.StatusUnprocessableEntity) }) } @@ -165,7 +171,8 @@ func TestAPIGetAll(t *testing.T) { token := getUserToken(t, "user1", auth_model.AccessTokenScopeReadOrganization) // accessing with a token will return all orgs - req := NewRequestf(t, "GET", "/api/v1/orgs?token=%s", token) + req := NewRequest(t, "GET", "/api/v1/orgs"). + AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusOK) var apiOrgList []*api.Organization @@ -175,7 +182,7 @@ func TestAPIGetAll(t *testing.T) { assert.Equal(t, "limited", apiOrgList[1].Visibility) // accessing without a token will return only public orgs - req = NewRequestf(t, "GET", "/api/v1/orgs") + req = NewRequest(t, "GET", "/api/v1/orgs") resp = MakeRequest(t, req, http.StatusOK) DecodeJSON(t, resp, &apiOrgList) @@ -190,22 +197,23 @@ func TestAPIOrgSearchEmptyTeam(t *testing.T) { orgName := "org_with_empty_team" // create org - req := NewRequestWithJSON(t, "POST", "/api/v1/orgs?token="+token, &api.CreateOrgOption{ + req := NewRequestWithJSON(t, "POST", "/api/v1/orgs", &api.CreateOrgOption{ UserName: orgName, - }) + }).AddTokenAuth(token) MakeRequest(t, req, http.StatusCreated) // create team with no member - req = NewRequestWithJSON(t, "POST", fmt.Sprintf("/api/v1/orgs/%s/teams?token=%s", orgName, token), &api.CreateTeamOption{ + req = NewRequestWithJSON(t, "POST", fmt.Sprintf("/api/v1/orgs/%s/teams", orgName), &api.CreateTeamOption{ Name: "Empty", IncludesAllRepositories: true, Permission: "read", Units: []string{"repo.code", "repo.issues", "repo.ext_issues", "repo.wiki", "repo.pulls"}, - }) + }).AddTokenAuth(token) MakeRequest(t, req, http.StatusCreated) // case-insensitive search for teams that have no members - req = NewRequest(t, "GET", fmt.Sprintf("/api/v1/orgs/%s/teams/search?q=%s&token=%s", orgName, "empty", token)) + req = NewRequest(t, "GET", fmt.Sprintf("/api/v1/orgs/%s/teams/search?q=%s", orgName, "empty")). + AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusOK) data := struct { Ok bool diff --git a/tests/integration/api_packages_alpine_test.go b/tests/integration/api_packages_alpine_test.go index 9a2acf854c4..3cc7178e028 100644 --- a/tests/integration/api_packages_alpine_test.go +++ b/tests/integration/api_packages_alpine_test.go @@ -85,12 +85,12 @@ Djfa/2q5bH4699v++uMAAAAAAAAAAAAAAAAAAAAAAHbgA/eXQh8AKAAA` req := NewRequestWithBody(t, "PUT", uploadURL, bytes.NewReader([]byte{})) MakeRequest(t, req, http.StatusUnauthorized) - req = NewRequestWithBody(t, "PUT", uploadURL, bytes.NewReader([]byte{})) - AddBasicAuthHeader(req, user.Name) + req = NewRequestWithBody(t, "PUT", uploadURL, bytes.NewReader([]byte{})). + AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusBadRequest) - req = NewRequestWithBody(t, "PUT", uploadURL, bytes.NewReader(content)) - AddBasicAuthHeader(req, user.Name) + req = NewRequestWithBody(t, "PUT", uploadURL, bytes.NewReader(content)). + AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusCreated) pvs, err := packages.GetVersionsByPackageType(db.DefaultContext, user.ID, packages.TypeAlpine) @@ -216,8 +216,8 @@ Djfa/2q5bH4699v++uMAAAAAAAAAAAAAAAAAAAAAAHbgA/eXQh8AKAAA` req := NewRequest(t, "DELETE", fmt.Sprintf("%s/%s/%s/x86_64/%s-%s.apk", rootURL, branch, repository, packageName, packageVersion)) MakeRequest(t, req, http.StatusUnauthorized) - req = NewRequest(t, "DELETE", fmt.Sprintf("%s/%s/%s/x86_64/%s-%s.apk", rootURL, branch, repository, packageName, packageVersion)) - AddBasicAuthHeader(req, user.Name) + req = NewRequest(t, "DELETE", fmt.Sprintf("%s/%s/%s/x86_64/%s-%s.apk", rootURL, branch, repository, packageName, packageVersion)). + AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusNoContent) // Deleting the last file of an architecture should remove that index diff --git a/tests/integration/api_packages_cargo_test.go b/tests/integration/api_packages_cargo_test.go index 03d8e0c5207..6b8154af457 100644 --- a/tests/integration/api_packages_cargo_test.go +++ b/tests/integration/api_packages_cargo_test.go @@ -132,8 +132,8 @@ func testPackageCargo(t *testing.T, _ *neturl.URL) { content := createPackage("0test", "1.0.0") - req := NewRequestWithBody(t, "PUT", url+"/new", content) - req = AddBasicAuthHeader(req, user.Name) + req := NewRequestWithBody(t, "PUT", url+"/new", content). + AddBasicAuth(user.Name) resp := MakeRequest(t, req, http.StatusBadRequest) var status cargo_router.StatusResponse @@ -142,8 +142,8 @@ func testPackageCargo(t *testing.T, _ *neturl.URL) { content = createPackage("test", "-1.0.0") - req = NewRequestWithBody(t, "PUT", url+"/new", content) - req = AddBasicAuthHeader(req, user.Name) + req = NewRequestWithBody(t, "PUT", url+"/new", content). + AddBasicAuth(user.Name) resp = MakeRequest(t, req, http.StatusBadRequest) DecodeJSON(t, resp, &status) @@ -161,8 +161,8 @@ func testPackageCargo(t *testing.T, _ *neturl.URL) { binary.Write(&buf, binary.LittleEndian, uint32(4)) buf.WriteString("te") - req := NewRequestWithBody(t, "PUT", url+"/new", &buf) - req = AddBasicAuthHeader(req, user.Name) + req := NewRequestWithBody(t, "PUT", url+"/new", &buf). + AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusBadRequest) }) @@ -172,8 +172,8 @@ func testPackageCargo(t *testing.T, _ *neturl.URL) { req := NewRequestWithBody(t, "PUT", url+"/new", createPackage(packageName, packageVersion)) MakeRequest(t, req, http.StatusUnauthorized) - req = NewRequestWithBody(t, "PUT", url+"/new", createPackage(packageName, packageVersion)) - req = AddBasicAuthHeader(req, user.Name) + req = NewRequestWithBody(t, "PUT", url+"/new", createPackage(packageName, packageVersion)). + AddBasicAuth(user.Name) resp := MakeRequest(t, req, http.StatusOK) var status cargo_router.StatusResponse @@ -201,8 +201,8 @@ func testPackageCargo(t *testing.T, _ *neturl.URL) { assert.NoError(t, err) assert.EqualValues(t, 4, pb.Size) - req = NewRequestWithBody(t, "PUT", url+"/new", createPackage(packageName, packageVersion)) - req = AddBasicAuthHeader(req, user.Name) + req = NewRequestWithBody(t, "PUT", url+"/new", createPackage(packageName, packageVersion)). + AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusConflict) t.Run("Index", func(t *testing.T) { @@ -288,8 +288,8 @@ func testPackageCargo(t *testing.T, _ *neturl.URL) { assert.NoError(t, err) assert.Len(t, pfs, 1) - req := NewRequest(t, "GET", fmt.Sprintf("%s/%s/%s/download", url, neturl.PathEscape(packageName), neturl.PathEscape(pv.Version))) - req = AddBasicAuthHeader(req, user.Name) + req := NewRequest(t, "GET", fmt.Sprintf("%s/%s/%s/download", url, neturl.PathEscape(packageName), neturl.PathEscape(pv.Version))). + AddBasicAuth(user.Name) resp := MakeRequest(t, req, http.StatusOK) assert.Equal(t, "test", resp.Body.String()) @@ -318,8 +318,8 @@ func testPackageCargo(t *testing.T, _ *neturl.URL) { } for i, c := range cases { - req := NewRequest(t, "GET", fmt.Sprintf("%s?q=%s&page=%d&per_page=%d", url, c.Query, c.Page, c.PerPage)) - req = AddBasicAuthHeader(req, user.Name) + req := NewRequest(t, "GET", fmt.Sprintf("%s?q=%s&page=%d&per_page=%d", url, c.Query, c.Page, c.PerPage)). + AddBasicAuth(user.Name) resp := MakeRequest(t, req, http.StatusOK) var result cargo_router.SearchResult @@ -333,8 +333,8 @@ func testPackageCargo(t *testing.T, _ *neturl.URL) { t.Run("Yank", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequest(t, "DELETE", fmt.Sprintf("%s/%s/%s/yank", url, neturl.PathEscape(packageName), neturl.PathEscape(packageVersion))) - req = AddBasicAuthHeader(req, user.Name) + req := NewRequest(t, "DELETE", fmt.Sprintf("%s/%s/%s/yank", url, neturl.PathEscape(packageName), neturl.PathEscape(packageVersion))). + AddBasicAuth(user.Name) resp := MakeRequest(t, req, http.StatusOK) var status cargo_router.StatusResponse @@ -353,8 +353,8 @@ func testPackageCargo(t *testing.T, _ *neturl.URL) { t.Run("Unyank", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequest(t, "PUT", fmt.Sprintf("%s/%s/%s/unyank", url, neturl.PathEscape(packageName), neturl.PathEscape(packageVersion))) - req = AddBasicAuthHeader(req, user.Name) + req := NewRequest(t, "PUT", fmt.Sprintf("%s/%s/%s/unyank", url, neturl.PathEscape(packageName), neturl.PathEscape(packageVersion))). + AddBasicAuth(user.Name) resp := MakeRequest(t, req, http.StatusOK) var status cargo_router.StatusResponse diff --git a/tests/integration/api_packages_chef_test.go b/tests/integration/api_packages_chef_test.go index 7f55a84f091..4123c7216c4 100644 --- a/tests/integration/api_packages_chef_test.go +++ b/tests/integration/api_packages_chef_test.go @@ -93,7 +93,7 @@ nwIDAQAB defer tests.PrintCurrentTest(t)() req := NewRequest(t, "POST", "/dummy") - u, err := auth.Verify(req, nil, nil, nil) + u, err := auth.Verify(req.Request, nil, nil, nil) assert.Nil(t, u) assert.NoError(t, err) }) @@ -101,9 +101,9 @@ nwIDAQAB t.Run("NotExistingUser", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequest(t, "POST", "/dummy") - req.Header.Set("X-Ops-Userid", "not-existing-user") - u, err := auth.Verify(req, nil, nil, nil) + req := NewRequest(t, "POST", "/dummy"). + SetHeader("X-Ops-Userid", "not-existing-user") + u, err := auth.Verify(req.Request, nil, nil, nil) assert.Nil(t, u) assert.Error(t, err) }) @@ -111,14 +111,14 @@ nwIDAQAB t.Run("Timestamp", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequest(t, "POST", "/dummy") - req.Header.Set("X-Ops-Userid", user.Name) - u, err := auth.Verify(req, nil, nil, nil) + req := NewRequest(t, "POST", "/dummy"). + SetHeader("X-Ops-Userid", user.Name) + u, err := auth.Verify(req.Request, nil, nil, nil) assert.Nil(t, u) assert.Error(t, err) - req.Header.Set("X-Ops-Timestamp", "2023-01-01T00:00:00Z") - u, err = auth.Verify(req, nil, nil, nil) + req.SetHeader("X-Ops-Timestamp", "2023-01-01T00:00:00Z") + u, err = auth.Verify(req.Request, nil, nil, nil) assert.Nil(t, u) assert.Error(t, err) }) @@ -126,30 +126,30 @@ nwIDAQAB t.Run("SigningVersion", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequest(t, "POST", "/dummy") - req.Header.Set("X-Ops-Userid", user.Name) - req.Header.Set("X-Ops-Timestamp", time.Now().UTC().Format(time.RFC3339)) - u, err := auth.Verify(req, nil, nil, nil) + req := NewRequest(t, "POST", "/dummy"). + SetHeader("X-Ops-Userid", user.Name). + SetHeader("X-Ops-Timestamp", time.Now().UTC().Format(time.RFC3339)) + u, err := auth.Verify(req.Request, nil, nil, nil) assert.Nil(t, u) assert.Error(t, err) - req.Header.Set("X-Ops-Sign", "version=none") - u, err = auth.Verify(req, nil, nil, nil) + req.SetHeader("X-Ops-Sign", "version=none") + u, err = auth.Verify(req.Request, nil, nil, nil) assert.Nil(t, u) assert.Error(t, err) - req.Header.Set("X-Ops-Sign", "version=1.4") - u, err = auth.Verify(req, nil, nil, nil) + req.SetHeader("X-Ops-Sign", "version=1.4") + u, err = auth.Verify(req.Request, nil, nil, nil) assert.Nil(t, u) assert.Error(t, err) - req.Header.Set("X-Ops-Sign", "version=1.0;algorithm=sha2") - u, err = auth.Verify(req, nil, nil, nil) + req.SetHeader("X-Ops-Sign", "version=1.0;algorithm=sha2") + u, err = auth.Verify(req.Request, nil, nil, nil) assert.Nil(t, u) assert.Error(t, err) - req.Header.Set("X-Ops-Sign", "version=1.0;algorithm=sha256") - u, err = auth.Verify(req, nil, nil, nil) + req.SetHeader("X-Ops-Sign", "version=1.0;algorithm=sha256") + u, err = auth.Verify(req.Request, nil, nil, nil) assert.Nil(t, u) assert.Error(t, err) }) @@ -159,17 +159,18 @@ nwIDAQAB ts := time.Now().UTC().Format(time.RFC3339) - req := NewRequest(t, "POST", "/dummy") - req.Header.Set("X-Ops-Userid", user.Name) - req.Header.Set("X-Ops-Timestamp", ts) - req.Header.Set("X-Ops-Sign", "version=1.0;algorithm=sha1") - req.Header.Set("X-Ops-Content-Hash", "unused") - req.Header.Set("X-Ops-Authorization-4", "dummy") - u, err := auth.Verify(req, nil, nil, nil) + req := NewRequest(t, "POST", "/dummy"). + SetHeader("X-Ops-Userid", user.Name). + SetHeader("X-Ops-Timestamp", ts). + SetHeader("X-Ops-Sign", "version=1.0;algorithm=sha1"). + SetHeader("X-Ops-Content-Hash", "unused"). + SetHeader("X-Ops-Authorization-4", "dummy") + u, err := auth.Verify(req.Request, nil, nil, nil) assert.Nil(t, u) assert.Error(t, err) - signRequest := func(t *testing.T, req *http.Request, version string) { + signRequest := func(t *testing.T, rw *RequestWrapper, version string) { + req := rw.Request username := req.Header.Get("X-Ops-Userid") if version != "1.0" && version != "1.3" { sum := sha1.Sum([]byte(username)) @@ -255,7 +256,7 @@ nwIDAQAB defer tests.PrintCurrentTest(t)() signRequest(t, req, v) - u, err = auth.Verify(req, nil, nil, nil) + u, err = auth.Verify(req.Request, nil, nil, nil) assert.NotNil(t, u) assert.NoError(t, err) }) @@ -291,9 +292,9 @@ nwIDAQAB zw.Close() mpw.Close() - req := NewRequestWithBody(t, "POST", root+"/cookbooks", &body) - req.Header.Add("Content-Type", mpw.FormDataContentType()) - AddBasicAuthHeader(req, user.Name) + req := NewRequestWithBody(t, "POST", root+"/cookbooks", &body). + SetHeader("Content-Type", mpw.FormDataContentType()). + AddBasicAuth(user.Name) MakeRequest(t, req, expectedStatus) } @@ -394,8 +395,8 @@ nwIDAQAB } for i, c := range cases { - req := NewRequest(t, "GET", fmt.Sprintf("%s/search?q=%s&start=%d&items=%d", root, c.Query, c.Start, c.Items)) - req = AddBasicAuthHeader(req, user.Name) + req := NewRequest(t, "GET", fmt.Sprintf("%s/search?q=%s&start=%d&items=%d", root, c.Query, c.Start, c.Items)). + AddBasicAuth(user.Name) resp := MakeRequest(t, req, http.StatusOK) var result Result @@ -445,8 +446,8 @@ nwIDAQAB } for i, c := range cases { - req := NewRequest(t, "GET", fmt.Sprintf("%s/cookbooks?start=%d&items=%d&sort=%s", root, c.Start, c.Items, c.Sort)) - req = AddBasicAuthHeader(req, user.Name) + req := NewRequest(t, "GET", fmt.Sprintf("%s/cookbooks?start=%d&items=%d&sort=%s", root, c.Start, c.Items, c.Sort)). + AddBasicAuth(user.Name) resp := MakeRequest(t, req, http.StatusOK) var result Result @@ -533,8 +534,8 @@ nwIDAQAB req := NewRequest(t, "DELETE", fmt.Sprintf("%s/cookbooks/%s/versions/%s", root, packageName, "1.0.2")) MakeRequest(t, req, http.StatusUnauthorized) - req = NewRequest(t, "DELETE", fmt.Sprintf("%s/cookbooks/%s/versions/%s", root, packageName, "1.0.2")) - AddBasicAuthHeader(req, user.Name) + req = NewRequest(t, "DELETE", fmt.Sprintf("%s/cookbooks/%s/versions/%s", root, packageName, "1.0.2")). + AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusOK) pv, err := packages.GetVersionByNameAndVersion(db.DefaultContext, user.ID, packages.TypeChef, packageName, "1.0.2") @@ -548,8 +549,8 @@ nwIDAQAB req := NewRequest(t, "DELETE", fmt.Sprintf("%s/cookbooks/%s", root, packageName)) MakeRequest(t, req, http.StatusUnauthorized) - req = NewRequest(t, "DELETE", fmt.Sprintf("%s/cookbooks/%s", root, packageName)) - AddBasicAuthHeader(req, user.Name) + req = NewRequest(t, "DELETE", fmt.Sprintf("%s/cookbooks/%s", root, packageName)). + AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusOK) pvs, err := packages.GetVersionsByPackageType(db.DefaultContext, user.ID, packages.TypeChef) diff --git a/tests/integration/api_packages_composer_test.go b/tests/integration/api_packages_composer_test.go index 896462d9a9f..6e0d2eee1b3 100644 --- a/tests/integration/api_packages_composer_test.go +++ b/tests/integration/api_packages_composer_test.go @@ -59,8 +59,8 @@ func TestPackageComposer(t *testing.T) { t.Run("ServiceIndex", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequest(t, "GET", fmt.Sprintf("%s/packages.json", url)) - req = AddBasicAuthHeader(req, user.Name) + req := NewRequest(t, "GET", fmt.Sprintf("%s/packages.json", url)). + AddBasicAuth(user.Name) resp := MakeRequest(t, req, http.StatusOK) var result composer.ServiceIndexResponse @@ -75,8 +75,8 @@ func TestPackageComposer(t *testing.T) { t.Run("MissingVersion", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequestWithBody(t, "PUT", url, bytes.NewReader(content)) - req = AddBasicAuthHeader(req, user.Name) + req := NewRequestWithBody(t, "PUT", url, bytes.NewReader(content)). + AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusBadRequest) }) @@ -85,8 +85,8 @@ func TestPackageComposer(t *testing.T) { uploadURL := url + "?version=" + packageVersion - req := NewRequestWithBody(t, "PUT", uploadURL, bytes.NewReader(content)) - req = AddBasicAuthHeader(req, user.Name) + req := NewRequestWithBody(t, "PUT", uploadURL, bytes.NewReader(content)). + AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusCreated) pvs, err := packages.GetVersionsByPackageType(db.DefaultContext, user.ID, packages.TypeComposer) @@ -110,8 +110,8 @@ func TestPackageComposer(t *testing.T) { assert.NoError(t, err) assert.Equal(t, int64(len(content)), pb.Size) - req = NewRequestWithBody(t, "PUT", uploadURL, bytes.NewReader(content)) - req = AddBasicAuthHeader(req, user.Name) + req = NewRequestWithBody(t, "PUT", uploadURL, bytes.NewReader(content)). + AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusConflict) }) }) @@ -128,8 +128,8 @@ func TestPackageComposer(t *testing.T) { assert.NoError(t, err) assert.Len(t, pfs, 1) - req := NewRequest(t, "GET", fmt.Sprintf("%s/files/%s/%s/%s", url, neturl.PathEscape(packageName), neturl.PathEscape(pvs[0].LowerVersion), neturl.PathEscape(pfs[0].LowerName))) - req = AddBasicAuthHeader(req, user.Name) + req := NewRequest(t, "GET", fmt.Sprintf("%s/files/%s/%s/%s", url, neturl.PathEscape(packageName), neturl.PathEscape(pvs[0].LowerVersion), neturl.PathEscape(pfs[0].LowerName))). + AddBasicAuth(user.Name) resp := MakeRequest(t, req, http.StatusOK) assert.Equal(t, content, resp.Body.Bytes()) @@ -162,8 +162,8 @@ func TestPackageComposer(t *testing.T) { } for i, c := range cases { - req := NewRequest(t, "GET", fmt.Sprintf("%s/search.json?q=%s&type=%s&page=%d&per_page=%d", url, c.Query, c.Type, c.Page, c.PerPage)) - req = AddBasicAuthHeader(req, user.Name) + req := NewRequest(t, "GET", fmt.Sprintf("%s/search.json?q=%s&type=%s&page=%d&per_page=%d", url, c.Query, c.Type, c.Page, c.PerPage)). + AddBasicAuth(user.Name) resp := MakeRequest(t, req, http.StatusOK) var result composer.SearchResultResponse @@ -177,8 +177,8 @@ func TestPackageComposer(t *testing.T) { t.Run("EnumeratePackages", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequest(t, "GET", url+"/list.json") - req = AddBasicAuthHeader(req, user.Name) + req := NewRequest(t, "GET", url+"/list.json"). + AddBasicAuth(user.Name) resp := MakeRequest(t, req, http.StatusOK) var result map[string][]string @@ -193,8 +193,8 @@ func TestPackageComposer(t *testing.T) { t.Run("PackageMetadata", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequest(t, "GET", fmt.Sprintf("%s/p2/%s/%s.json", url, vendorName, projectName)) - req = AddBasicAuthHeader(req, user.Name) + req := NewRequest(t, "GET", fmt.Sprintf("%s/p2/%s/%s.json", url, vendorName, projectName)). + AddBasicAuth(user.Name) resp := MakeRequest(t, req, http.StatusOK) var result composer.PackageMetadataResponse diff --git a/tests/integration/api_packages_conan_test.go b/tests/integration/api_packages_conan_test.go index ab128bf4a5e..a25713f039f 100644 --- a/tests/integration/api_packages_conan_test.go +++ b/tests/integration/api_packages_conan_test.go @@ -62,11 +62,6 @@ const ( CC=gcc-10` ) -func addTokenAuthHeader(request *http.Request, token string) *http.Request { - request.Header.Set("Authorization", token) - return request -} - func buildConanfileContent(name, version string) string { return `from conans import ConanFile, CMake, tools @@ -90,16 +85,16 @@ func uploadConanPackageV1(t *testing.T, baseURL, token, name, version, user, cha recipeURL := fmt.Sprintf("%s/v1/conans/%s/%s/%s/%s", baseURL, name, version, user, channel) - req := NewRequest(t, "GET", recipeURL) - req = addTokenAuthHeader(req, token) + req := NewRequest(t, "GET", recipeURL). + AddTokenAuth(token) MakeRequest(t, req, http.StatusNotFound) - req = NewRequest(t, "GET", fmt.Sprintf("%s/digest", recipeURL)) - req = addTokenAuthHeader(req, token) + req = NewRequest(t, "GET", fmt.Sprintf("%s/digest", recipeURL)). + AddTokenAuth(token) MakeRequest(t, req, http.StatusNotFound) - req = NewRequest(t, "GET", fmt.Sprintf("%s/download_urls", recipeURL)) - req = addTokenAuthHeader(req, token) + req = NewRequest(t, "GET", fmt.Sprintf("%s/download_urls", recipeURL)). + AddTokenAuth(token) MakeRequest(t, req, http.StatusNotFound) req = NewRequest(t, "POST", fmt.Sprintf("%s/upload_urls", recipeURL)) @@ -108,8 +103,7 @@ func uploadConanPackageV1(t *testing.T, baseURL, token, name, version, user, cha req = NewRequestWithJSON(t, "POST", fmt.Sprintf("%s/upload_urls", recipeURL), map[string]int64{ conanfileName: int64(len(contentConanfile)), "removed.txt": 0, - }) - req = addTokenAuthHeader(req, token) + }).AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusOK) uploadURLs := make(map[string]string) @@ -121,22 +115,22 @@ func uploadConanPackageV1(t *testing.T, baseURL, token, name, version, user, cha uploadURL := uploadURLs[conanfileName] assert.NotEmpty(t, uploadURL) - req = NewRequestWithBody(t, "PUT", uploadURL, strings.NewReader(contentConanfile)) - req = addTokenAuthHeader(req, token) + req = NewRequestWithBody(t, "PUT", uploadURL, strings.NewReader(contentConanfile)). + AddTokenAuth(token) MakeRequest(t, req, http.StatusCreated) packageURL := fmt.Sprintf("%s/packages/%s", recipeURL, conanPackageReference) - req = NewRequest(t, "GET", packageURL) - req = addTokenAuthHeader(req, token) + req = NewRequest(t, "GET", packageURL). + AddTokenAuth(token) MakeRequest(t, req, http.StatusNotFound) - req = NewRequest(t, "GET", fmt.Sprintf("%s/digest", packageURL)) - req = addTokenAuthHeader(req, token) + req = NewRequest(t, "GET", fmt.Sprintf("%s/digest", packageURL)). + AddTokenAuth(token) MakeRequest(t, req, http.StatusNotFound) - req = NewRequest(t, "GET", fmt.Sprintf("%s/download_urls", packageURL)) - req = addTokenAuthHeader(req, token) + req = NewRequest(t, "GET", fmt.Sprintf("%s/download_urls", packageURL)). + AddTokenAuth(token) MakeRequest(t, req, http.StatusNotFound) req = NewRequest(t, "POST", fmt.Sprintf("%s/upload_urls", packageURL)) @@ -145,8 +139,7 @@ func uploadConanPackageV1(t *testing.T, baseURL, token, name, version, user, cha req = NewRequestWithJSON(t, "POST", fmt.Sprintf("%s/upload_urls", packageURL), map[string]int64{ conaninfoName: int64(len(contentConaninfo)), "removed.txt": 0, - }) - req = addTokenAuthHeader(req, token) + }).AddTokenAuth(token) resp = MakeRequest(t, req, http.StatusOK) uploadURLs = make(map[string]string) @@ -158,8 +151,8 @@ func uploadConanPackageV1(t *testing.T, baseURL, token, name, version, user, cha uploadURL = uploadURLs[conaninfoName] assert.NotEmpty(t, uploadURL) - req = NewRequestWithBody(t, "PUT", uploadURL, strings.NewReader(contentConaninfo)) - req = addTokenAuthHeader(req, token) + req = NewRequestWithBody(t, "PUT", uploadURL, strings.NewReader(contentConaninfo)). + AddTokenAuth(token) MakeRequest(t, req, http.StatusCreated) } @@ -168,12 +161,12 @@ func uploadConanPackageV2(t *testing.T, baseURL, token, name, version, user, cha recipeURL := fmt.Sprintf("%s/v2/conans/%s/%s/%s/%s/revisions/%s", baseURL, name, version, user, channel, recipeRevision) - req := NewRequestWithBody(t, "PUT", fmt.Sprintf("%s/files/%s", recipeURL, conanfileName), strings.NewReader(contentConanfile)) - req = addTokenAuthHeader(req, token) + req := NewRequestWithBody(t, "PUT", fmt.Sprintf("%s/files/%s", recipeURL, conanfileName), strings.NewReader(contentConanfile)). + AddTokenAuth(token) MakeRequest(t, req, http.StatusCreated) - req = NewRequest(t, "GET", fmt.Sprintf("%s/files", recipeURL)) - req = addTokenAuthHeader(req, token) + req = NewRequest(t, "GET", fmt.Sprintf("%s/files", recipeURL)). + AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusOK) var list *struct { @@ -185,16 +178,16 @@ func uploadConanPackageV2(t *testing.T, baseURL, token, name, version, user, cha packageURL := fmt.Sprintf("%s/packages/%s/revisions/%s", recipeURL, conanPackageReference, packageRevision) - req = NewRequest(t, "GET", fmt.Sprintf("%s/files", packageURL)) - req = addTokenAuthHeader(req, token) + req = NewRequest(t, "GET", fmt.Sprintf("%s/files", packageURL)). + AddTokenAuth(token) MakeRequest(t, req, http.StatusNotFound) - req = NewRequestWithBody(t, "PUT", fmt.Sprintf("%s/files/%s", packageURL, conaninfoName), strings.NewReader(contentConaninfo)) - req = addTokenAuthHeader(req, token) + req = NewRequestWithBody(t, "PUT", fmt.Sprintf("%s/files/%s", packageURL, conaninfoName), strings.NewReader(contentConaninfo)). + AddTokenAuth(token) MakeRequest(t, req, http.StatusCreated) - req = NewRequest(t, "GET", fmt.Sprintf("%s/files", packageURL)) - req = addTokenAuthHeader(req, token) + req = NewRequest(t, "GET", fmt.Sprintf("%s/files", packageURL)). + AddTokenAuth(token) resp = MakeRequest(t, req, http.StatusOK) list = nil @@ -235,21 +228,19 @@ func TestPackageConan(t *testing.T) { t.Run("Authenticate", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequest(t, "GET", fmt.Sprintf("%s/v1/users/authenticate", url)) - req = AddBasicAuthHeader(req, user.Name) + req := NewRequest(t, "GET", fmt.Sprintf("%s/v1/users/authenticate", url)). + AddBasicAuth(user.Name) resp := MakeRequest(t, req, http.StatusOK) - body := resp.Body.String() - assert.NotEmpty(t, body) - - token = fmt.Sprintf("Bearer %s", body) + token = resp.Body.String() + assert.NotEmpty(t, token) }) t.Run("CheckCredentials", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequest(t, "GET", fmt.Sprintf("%s/v1/users/check_credentials", url)) - req = addTokenAuthHeader(req, token) + req := NewRequest(t, "GET", fmt.Sprintf("%s/v1/users/check_credentials", url)). + AddTokenAuth(token) MakeRequest(t, req, http.StatusOK) }) @@ -440,8 +431,7 @@ func TestPackageConan(t *testing.T) { req := NewRequestWithJSON(t, "POST", fmt.Sprintf("%s/v1/conans/%s/%s/%s/%s/packages/delete", url, name, version1, user1, c.Channel), map[string][]string{ "package_ids": c.References, - }) - req = addTokenAuthHeader(req, token) + }).AddTokenAuth(token) MakeRequest(t, req, http.StatusOK) references, err = conan_model.GetPackageReferences(db.DefaultContext, user.ID, rref) @@ -466,8 +456,8 @@ func TestPackageConan(t *testing.T) { assert.NoError(t, err) assert.NotEmpty(t, revisions) - req := NewRequest(t, "DELETE", fmt.Sprintf("%s/v1/conans/%s/%s/%s/%s", url, name, version1, user1, c.Channel)) - req = addTokenAuthHeader(req, token) + req := NewRequest(t, "DELETE", fmt.Sprintf("%s/v1/conans/%s/%s/%s/%s", url, name, version1, user1, c.Channel)). + AddTokenAuth(token) MakeRequest(t, req, http.StatusOK) revisions, err = conan_model.GetRecipeRevisions(db.DefaultContext, user.ID, rref) @@ -493,8 +483,8 @@ func TestPackageConan(t *testing.T) { t.Run("Authenticate", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequest(t, "GET", fmt.Sprintf("%s/v2/users/authenticate", url)) - req = AddBasicAuthHeader(req, user.Name) + req := NewRequest(t, "GET", fmt.Sprintf("%s/v2/users/authenticate", url)). + AddBasicAuth(user.Name) resp := MakeRequest(t, req, http.StatusOK) body := resp.Body.String() @@ -506,8 +496,8 @@ func TestPackageConan(t *testing.T) { t.Run("CheckCredentials", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequest(t, "GET", fmt.Sprintf("%s/v2/users/check_credentials", url)) - req = addTokenAuthHeader(req, token) + req := NewRequest(t, "GET", fmt.Sprintf("%s/v2/users/check_credentials", url)). + AddTokenAuth(token) MakeRequest(t, req, http.StatusOK) }) @@ -672,14 +662,14 @@ func TestPackageConan(t *testing.T) { checkPackageRevisionCount(2) - req := NewRequest(t, "DELETE", fmt.Sprintf("%s/v2/conans/%s/%s/%s/%s/revisions/%s/packages/%s/revisions/%s", url, name, version1, user1, channel1, revision1, conanPackageReference, revision1)) - req = addTokenAuthHeader(req, token) + req := NewRequest(t, "DELETE", fmt.Sprintf("%s/v2/conans/%s/%s/%s/%s/revisions/%s/packages/%s/revisions/%s", url, name, version1, user1, channel1, revision1, conanPackageReference, revision1)). + AddTokenAuth(token) MakeRequest(t, req, http.StatusOK) checkPackageRevisionCount(1) - req = NewRequest(t, "DELETE", fmt.Sprintf("%s/v2/conans/%s/%s/%s/%s/revisions/%s/packages/%s", url, name, version1, user1, channel1, revision1, conanPackageReference)) - req = addTokenAuthHeader(req, token) + req = NewRequest(t, "DELETE", fmt.Sprintf("%s/v2/conans/%s/%s/%s/%s/revisions/%s/packages/%s", url, name, version1, user1, channel1, revision1, conanPackageReference)). + AddTokenAuth(token) MakeRequest(t, req, http.StatusOK) checkPackageRevisionCount(0) @@ -688,8 +678,8 @@ func TestPackageConan(t *testing.T) { checkPackageReferenceCount(1) - req = NewRequest(t, "DELETE", fmt.Sprintf("%s/v2/conans/%s/%s/%s/%s/revisions/%s/packages", url, name, version1, user1, channel1, revision2)) - req = addTokenAuthHeader(req, token) + req = NewRequest(t, "DELETE", fmt.Sprintf("%s/v2/conans/%s/%s/%s/%s/revisions/%s/packages", url, name, version1, user1, channel1, revision2)). + AddTokenAuth(token) MakeRequest(t, req, http.StatusOK) checkPackageReferenceCount(0) @@ -708,14 +698,14 @@ func TestPackageConan(t *testing.T) { checkRecipeRevisionCount(2) - req := NewRequest(t, "DELETE", fmt.Sprintf("%s/v2/conans/%s/%s/%s/%s/revisions/%s", url, name, version1, user1, channel1, revision1)) - req = addTokenAuthHeader(req, token) + req := NewRequest(t, "DELETE", fmt.Sprintf("%s/v2/conans/%s/%s/%s/%s/revisions/%s", url, name, version1, user1, channel1, revision1)). + AddTokenAuth(token) MakeRequest(t, req, http.StatusOK) checkRecipeRevisionCount(1) - req = NewRequest(t, "DELETE", fmt.Sprintf("%s/v2/conans/%s/%s/%s/%s", url, name, version1, user1, channel1)) - req = addTokenAuthHeader(req, token) + req = NewRequest(t, "DELETE", fmt.Sprintf("%s/v2/conans/%s/%s/%s/%s", url, name, version1, user1, channel1)). + AddTokenAuth(token) MakeRequest(t, req, http.StatusOK) checkRecipeRevisionCount(0) diff --git a/tests/integration/api_packages_conda_test.go b/tests/integration/api_packages_conda_test.go index daa7dca55fa..bb269e82d60 100644 --- a/tests/integration/api_packages_conda_test.go +++ b/tests/integration/api_packages_conda_test.go @@ -66,12 +66,12 @@ func TestPackageConda(t *testing.T) { req := NewRequestWithBody(t, "PUT", root+"/"+filename, bytes.NewReader(buf.Bytes())) MakeRequest(t, req, http.StatusUnauthorized) - req = NewRequestWithBody(t, "PUT", root+"/"+filename, bytes.NewReader(buf.Bytes())) - AddBasicAuthHeader(req, user.Name) + req = NewRequestWithBody(t, "PUT", root+"/"+filename, bytes.NewReader(buf.Bytes())). + AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusCreated) - req = NewRequestWithBody(t, "PUT", root+"/"+filename, bytes.NewReader(buf.Bytes())) - AddBasicAuthHeader(req, user.Name) + req = NewRequestWithBody(t, "PUT", root+"/"+filename, bytes.NewReader(buf.Bytes())). + AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusConflict) pvs, err := packages.GetVersionsByPackageType(db.DefaultContext, user.ID, packages.TypeConda) @@ -107,12 +107,12 @@ func TestPackageConda(t *testing.T) { req := NewRequestWithBody(t, "PUT", root+"/"+channel+"/"+filename, bytes.NewReader(buf.Bytes())) MakeRequest(t, req, http.StatusUnauthorized) - req = NewRequestWithBody(t, "PUT", root+"/"+channel+"/"+filename, bytes.NewReader(buf.Bytes())) - AddBasicAuthHeader(req, user.Name) + req = NewRequestWithBody(t, "PUT", root+"/"+channel+"/"+filename, bytes.NewReader(buf.Bytes())). + AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusCreated) - req = NewRequestWithBody(t, "PUT", root+"/"+channel+"/"+filename, bytes.NewReader(buf.Bytes())) - AddBasicAuthHeader(req, user.Name) + req = NewRequestWithBody(t, "PUT", root+"/"+channel+"/"+filename, bytes.NewReader(buf.Bytes())). + AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusConflict) pvs, err := packages.GetVersionsByPackageType(db.DefaultContext, user.ID, packages.TypeConda) diff --git a/tests/integration/api_packages_container_test.go b/tests/integration/api_packages_container_test.go index 93b4ff46241..f32d33888b4 100644 --- a/tests/integration/api_packages_container_test.go +++ b/tests/integration/api_packages_container_test.go @@ -103,8 +103,8 @@ func TestPackageContainer(t *testing.T) { anonymousToken = fmt.Sprintf("Bearer %s", tokenResponse.Token) - req = NewRequest(t, "GET", fmt.Sprintf("%sv2", setting.AppURL)) - addTokenAuthHeader(req, anonymousToken) + req = NewRequest(t, "GET", fmt.Sprintf("%sv2", setting.AppURL)). + AddTokenAuth(anonymousToken) MakeRequest(t, req, http.StatusOK) }) @@ -116,8 +116,8 @@ func TestPackageContainer(t *testing.T) { assert.ElementsMatch(t, authenticate, resp.Header().Values("WWW-Authenticate")) - req = NewRequest(t, "GET", fmt.Sprintf("%sv2/token", setting.AppURL)) - req = AddBasicAuthHeader(req, user.Name) + req = NewRequest(t, "GET", fmt.Sprintf("%sv2/token", setting.AppURL)). + AddBasicAuth(user.Name) resp = MakeRequest(t, req, http.StatusOK) tokenResponse := &TokenResponse{} @@ -127,8 +127,8 @@ func TestPackageContainer(t *testing.T) { userToken = fmt.Sprintf("Bearer %s", tokenResponse.Token) - req = NewRequest(t, "GET", fmt.Sprintf("%sv2", setting.AppURL)) - addTokenAuthHeader(req, userToken) + req = NewRequest(t, "GET", fmt.Sprintf("%sv2", setting.AppURL)). + AddTokenAuth(userToken) MakeRequest(t, req, http.StatusOK) }) }) @@ -136,8 +136,8 @@ func TestPackageContainer(t *testing.T) { t.Run("DetermineSupport", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequest(t, "GET", fmt.Sprintf("%sv2", setting.AppURL)) - addTokenAuthHeader(req, userToken) + req := NewRequest(t, "GET", fmt.Sprintf("%sv2", setting.AppURL)). + AddTokenAuth(userToken) resp := MakeRequest(t, req, http.StatusOK) assert.Equal(t, "registry/2.0", resp.Header().Get("Docker-Distribution-Api-Version")) }) @@ -149,16 +149,16 @@ func TestPackageContainer(t *testing.T) { t.Run("UploadBlob/Monolithic", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequest(t, "POST", fmt.Sprintf("%s/blobs/uploads", url)) - addTokenAuthHeader(req, anonymousToken) + req := NewRequest(t, "POST", fmt.Sprintf("%s/blobs/uploads", url)). + AddTokenAuth(anonymousToken) MakeRequest(t, req, http.StatusUnauthorized) - req = NewRequestWithBody(t, "POST", fmt.Sprintf("%s/blobs/uploads?digest=%s", url, unknownDigest), bytes.NewReader(blobContent)) - addTokenAuthHeader(req, userToken) + req = NewRequestWithBody(t, "POST", fmt.Sprintf("%s/blobs/uploads?digest=%s", url, unknownDigest), bytes.NewReader(blobContent)). + AddTokenAuth(userToken) MakeRequest(t, req, http.StatusBadRequest) - req = NewRequestWithBody(t, "POST", fmt.Sprintf("%s/blobs/uploads?digest=%s", url, blobDigest), bytes.NewReader(blobContent)) - addTokenAuthHeader(req, userToken) + req = NewRequestWithBody(t, "POST", fmt.Sprintf("%s/blobs/uploads?digest=%s", url, blobDigest), bytes.NewReader(blobContent)). + AddTokenAuth(userToken) resp := MakeRequest(t, req, http.StatusCreated) assert.Equal(t, fmt.Sprintf("/v2/%s/%s/blobs/%s", user.Name, image, blobDigest), resp.Header().Get("Location")) @@ -179,8 +179,8 @@ func TestPackageContainer(t *testing.T) { t.Run("UploadBlob/Chunked", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequest(t, "POST", fmt.Sprintf("%s/blobs/uploads", url)) - addTokenAuthHeader(req, userToken) + req := NewRequest(t, "POST", fmt.Sprintf("%s/blobs/uploads", url)). + AddTokenAuth(userToken) resp := MakeRequest(t, req, http.StatusAccepted) uuid := resp.Header().Get("Docker-Upload-Uuid") @@ -193,18 +193,17 @@ func TestPackageContainer(t *testing.T) { uploadURL := resp.Header().Get("Location") assert.NotEmpty(t, uploadURL) - req = NewRequestWithBody(t, "PATCH", setting.AppURL+uploadURL[1:]+"000", bytes.NewReader(blobContent)) - addTokenAuthHeader(req, userToken) + req = NewRequestWithBody(t, "PATCH", setting.AppURL+uploadURL[1:]+"000", bytes.NewReader(blobContent)). + AddTokenAuth(userToken) MakeRequest(t, req, http.StatusNotFound) - req = NewRequestWithBody(t, "PATCH", setting.AppURL+uploadURL[1:], bytes.NewReader(blobContent)) - addTokenAuthHeader(req, userToken) - - req.Header.Set("Content-Range", "1-10") + req = NewRequestWithBody(t, "PATCH", setting.AppURL+uploadURL[1:], bytes.NewReader(blobContent)). + AddTokenAuth(userToken). + SetHeader("Content-Range", "1-10") MakeRequest(t, req, http.StatusRequestedRangeNotSatisfiable) contentRange := fmt.Sprintf("0-%d", len(blobContent)-1) - req.Header.Set("Content-Range", contentRange) + req.SetHeader("Content-Range", contentRange) resp = MakeRequest(t, req, http.StatusAccepted) assert.Equal(t, uuid, resp.Header().Get("Docker-Upload-Uuid")) @@ -212,8 +211,8 @@ func TestPackageContainer(t *testing.T) { uploadURL = resp.Header().Get("Location") - req = NewRequest(t, "GET", setting.AppURL+uploadURL[1:]) - addTokenAuthHeader(req, userToken) + req = NewRequest(t, "GET", setting.AppURL+uploadURL[1:]). + AddTokenAuth(userToken) resp = MakeRequest(t, req, http.StatusNoContent) assert.Equal(t, uuid, resp.Header().Get("Docker-Upload-Uuid")) @@ -223,8 +222,8 @@ func TestPackageContainer(t *testing.T) { assert.NoError(t, err) assert.EqualValues(t, len(blobContent), pbu.BytesReceived) - req = NewRequest(t, "PUT", fmt.Sprintf("%s?digest=%s", setting.AppURL+uploadURL[1:], blobDigest)) - addTokenAuthHeader(req, userToken) + req = NewRequest(t, "PUT", fmt.Sprintf("%s?digest=%s", setting.AppURL+uploadURL[1:], blobDigest)). + AddTokenAuth(userToken) resp = MakeRequest(t, req, http.StatusCreated) assert.Equal(t, fmt.Sprintf("/v2/%s/%s/blobs/%s", user.Name, image, blobDigest), resp.Header().Get("Location")) @@ -233,8 +232,8 @@ func TestPackageContainer(t *testing.T) { t.Run("Cancel", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequest(t, "POST", fmt.Sprintf("%s/blobs/uploads", url)) - addTokenAuthHeader(req, userToken) + req := NewRequest(t, "POST", fmt.Sprintf("%s/blobs/uploads", url)). + AddTokenAuth(userToken) resp := MakeRequest(t, req, http.StatusAccepted) uuid := resp.Header().Get("Docker-Upload-Uuid") @@ -243,19 +242,19 @@ func TestPackageContainer(t *testing.T) { uploadURL := resp.Header().Get("Location") assert.NotEmpty(t, uploadURL) - req = NewRequest(t, "GET", setting.AppURL+uploadURL[1:]) - addTokenAuthHeader(req, userToken) + req = NewRequest(t, "GET", setting.AppURL+uploadURL[1:]). + AddTokenAuth(userToken) resp = MakeRequest(t, req, http.StatusNoContent) assert.Equal(t, uuid, resp.Header().Get("Docker-Upload-Uuid")) assert.Equal(t, "0-0", resp.Header().Get("Range")) - req = NewRequest(t, "DELETE", setting.AppURL+uploadURL[1:]) - addTokenAuthHeader(req, userToken) + req = NewRequest(t, "DELETE", setting.AppURL+uploadURL[1:]). + AddTokenAuth(userToken) MakeRequest(t, req, http.StatusNoContent) - req = NewRequest(t, "GET", setting.AppURL+uploadURL[1:]) - addTokenAuthHeader(req, userToken) + req = NewRequest(t, "GET", setting.AppURL+uploadURL[1:]). + AddTokenAuth(userToken) MakeRequest(t, req, http.StatusNotFound) }) }) @@ -264,31 +263,31 @@ func TestPackageContainer(t *testing.T) { defer tests.PrintCurrentTest(t)() privateBlobDigest := "sha256:6ccce4863b70f258d691f59609d31b4502e1ba5199942d3bc5d35d17a4ce771d" - req := NewRequestWithBody(t, "POST", fmt.Sprintf("%sv2/%s/%s/blobs/uploads?digest=%s", setting.AppURL, privateUser.Name, image, privateBlobDigest), strings.NewReader("gitea")) - req = AddBasicAuthHeader(req, privateUser.Name) + req := NewRequestWithBody(t, "POST", fmt.Sprintf("%sv2/%s/%s/blobs/uploads?digest=%s", setting.AppURL, privateUser.Name, image, privateBlobDigest), strings.NewReader("gitea")). + AddBasicAuth(privateUser.Name) MakeRequest(t, req, http.StatusCreated) - req = NewRequest(t, "POST", fmt.Sprintf("%s/blobs/uploads?mount=%s", url, unknownDigest)) - addTokenAuthHeader(req, userToken) + req = NewRequest(t, "POST", fmt.Sprintf("%s/blobs/uploads?mount=%s", url, unknownDigest)). + AddTokenAuth(userToken) MakeRequest(t, req, http.StatusAccepted) - req = NewRequest(t, "POST", fmt.Sprintf("%s/blobs/uploads?mount=%s", url, privateBlobDigest)) - addTokenAuthHeader(req, userToken) + req = NewRequest(t, "POST", fmt.Sprintf("%s/blobs/uploads?mount=%s", url, privateBlobDigest)). + AddTokenAuth(userToken) MakeRequest(t, req, http.StatusAccepted) - req = NewRequest(t, "POST", fmt.Sprintf("%s/blobs/uploads?mount=%s", url, blobDigest)) - addTokenAuthHeader(req, userToken) + req = NewRequest(t, "POST", fmt.Sprintf("%s/blobs/uploads?mount=%s", url, blobDigest)). + AddTokenAuth(userToken) resp := MakeRequest(t, req, http.StatusCreated) assert.Equal(t, fmt.Sprintf("/v2/%s/%s/blobs/%s", user.Name, image, blobDigest), resp.Header().Get("Location")) assert.Equal(t, blobDigest, resp.Header().Get("Docker-Content-Digest")) - req = NewRequest(t, "POST", fmt.Sprintf("%s/blobs/uploads?mount=%s&from=%s", url, unknownDigest, "unknown/image")) - addTokenAuthHeader(req, userToken) + req = NewRequest(t, "POST", fmt.Sprintf("%s/blobs/uploads?mount=%s&from=%s", url, unknownDigest, "unknown/image")). + AddTokenAuth(userToken) MakeRequest(t, req, http.StatusAccepted) - req = NewRequest(t, "POST", fmt.Sprintf("%s/blobs/uploads?mount=%s&from=%s/%s", url, blobDigest, user.Name, image)) - addTokenAuthHeader(req, userToken) + req = NewRequest(t, "POST", fmt.Sprintf("%s/blobs/uploads?mount=%s&from=%s/%s", url, blobDigest, user.Name, image)). + AddTokenAuth(userToken) resp = MakeRequest(t, req, http.StatusCreated) assert.Equal(t, fmt.Sprintf("/v2/%s/%s/blobs/%s", user.Name, image, blobDigest), resp.Header().Get("Location")) @@ -300,18 +299,18 @@ func TestPackageContainer(t *testing.T) { t.Run("UploadManifest", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequestWithBody(t, "POST", fmt.Sprintf("%s/blobs/uploads?digest=%s", url, configDigest), strings.NewReader(configContent)) - addTokenAuthHeader(req, userToken) + req := NewRequestWithBody(t, "POST", fmt.Sprintf("%s/blobs/uploads?digest=%s", url, configDigest), strings.NewReader(configContent)). + AddTokenAuth(userToken) MakeRequest(t, req, http.StatusCreated) - req = NewRequestWithBody(t, "PUT", fmt.Sprintf("%s/manifests/%s", url, tag), strings.NewReader(manifestContent)) - addTokenAuthHeader(req, anonymousToken) - req.Header.Set("Content-Type", "application/vnd.docker.distribution.manifest.v2+json") + req = NewRequestWithBody(t, "PUT", fmt.Sprintf("%s/manifests/%s", url, tag), strings.NewReader(manifestContent)). + AddTokenAuth(anonymousToken). + SetHeader("Content-Type", "application/vnd.docker.distribution.manifest.v2+json") MakeRequest(t, req, http.StatusUnauthorized) - req = NewRequestWithBody(t, "PUT", fmt.Sprintf("%s/manifests/%s", url, tag), strings.NewReader(manifestContent)) - addTokenAuthHeader(req, userToken) - req.Header.Set("Content-Type", "application/vnd.docker.distribution.manifest.v2+json") + req = NewRequestWithBody(t, "PUT", fmt.Sprintf("%s/manifests/%s", url, tag), strings.NewReader(manifestContent)). + AddTokenAuth(userToken). + SetHeader("Content-Type", "application/vnd.docker.distribution.manifest.v2+json") resp := MakeRequest(t, req, http.StatusCreated) assert.Equal(t, manifestDigest, resp.Header().Get("Docker-Content-Digest")) @@ -353,8 +352,8 @@ func TestPackageContainer(t *testing.T) { } } - req = NewRequest(t, "GET", fmt.Sprintf("%s/manifests/%s", url, tag)) - addTokenAuthHeader(req, userToken) + req = NewRequest(t, "GET", fmt.Sprintf("%s/manifests/%s", url, tag)). + AddTokenAuth(userToken) MakeRequest(t, req, http.StatusOK) pv, err = packages_model.GetVersionByNameAndVersion(db.DefaultContext, user.ID, packages_model.TypeContainer, image, tag) @@ -362,9 +361,9 @@ func TestPackageContainer(t *testing.T) { assert.EqualValues(t, 1, pv.DownloadCount) // Overwrite existing tag should keep the download count - req = NewRequestWithBody(t, "PUT", fmt.Sprintf("%s/manifests/%s", url, tag), strings.NewReader(manifestContent)) - addTokenAuthHeader(req, userToken) - req.Header.Set("Content-Type", oci.MediaTypeImageManifest) + req = NewRequestWithBody(t, "PUT", fmt.Sprintf("%s/manifests/%s", url, tag), strings.NewReader(manifestContent)). + AddTokenAuth(userToken). + SetHeader("Content-Type", oci.MediaTypeImageManifest) MakeRequest(t, req, http.StatusCreated) pv, err = packages_model.GetVersionByNameAndVersion(db.DefaultContext, user.ID, packages_model.TypeContainer, image, tag) @@ -375,12 +374,12 @@ func TestPackageContainer(t *testing.T) { t.Run("HeadManifest", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequest(t, "HEAD", fmt.Sprintf("%s/manifests/unknown-tag", url)) - addTokenAuthHeader(req, userToken) + req := NewRequest(t, "HEAD", fmt.Sprintf("%s/manifests/unknown-tag", url)). + AddTokenAuth(userToken) MakeRequest(t, req, http.StatusNotFound) - req = NewRequest(t, "HEAD", fmt.Sprintf("%s/manifests/%s", url, tag)) - addTokenAuthHeader(req, userToken) + req = NewRequest(t, "HEAD", fmt.Sprintf("%s/manifests/%s", url, tag)). + AddTokenAuth(userToken) resp := MakeRequest(t, req, http.StatusOK) assert.Equal(t, fmt.Sprintf("%d", len(manifestContent)), resp.Header().Get("Content-Length")) @@ -390,12 +389,12 @@ func TestPackageContainer(t *testing.T) { t.Run("GetManifest", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequest(t, "GET", fmt.Sprintf("%s/manifests/unknown-tag", url)) - addTokenAuthHeader(req, userToken) + req := NewRequest(t, "GET", fmt.Sprintf("%s/manifests/unknown-tag", url)). + AddTokenAuth(userToken) MakeRequest(t, req, http.StatusNotFound) - req = NewRequest(t, "GET", fmt.Sprintf("%s/manifests/%s", url, tag)) - addTokenAuthHeader(req, userToken) + req = NewRequest(t, "GET", fmt.Sprintf("%s/manifests/%s", url, tag)). + AddTokenAuth(userToken) resp := MakeRequest(t, req, http.StatusOK) assert.Equal(t, fmt.Sprintf("%d", len(manifestContent)), resp.Header().Get("Content-Length")) @@ -409,15 +408,15 @@ func TestPackageContainer(t *testing.T) { t.Run("UploadUntaggedManifest", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequestWithBody(t, "PUT", fmt.Sprintf("%s/manifests/%s", url, untaggedManifestDigest), strings.NewReader(untaggedManifestContent)) - addTokenAuthHeader(req, userToken) - req.Header.Set("Content-Type", oci.MediaTypeImageManifest) + req := NewRequestWithBody(t, "PUT", fmt.Sprintf("%s/manifests/%s", url, untaggedManifestDigest), strings.NewReader(untaggedManifestContent)). + AddTokenAuth(userToken). + SetHeader("Content-Type", oci.MediaTypeImageManifest) resp := MakeRequest(t, req, http.StatusCreated) assert.Equal(t, untaggedManifestDigest, resp.Header().Get("Docker-Content-Digest")) - req = NewRequest(t, "HEAD", fmt.Sprintf("%s/manifests/%s", url, untaggedManifestDigest)) - addTokenAuthHeader(req, userToken) + req = NewRequest(t, "HEAD", fmt.Sprintf("%s/manifests/%s", url, untaggedManifestDigest)). + AddTokenAuth(userToken) resp = MakeRequest(t, req, http.StatusOK) assert.Equal(t, fmt.Sprintf("%d", len(untaggedManifestContent)), resp.Header().Get("Content-Length")) @@ -449,9 +448,9 @@ func TestPackageContainer(t *testing.T) { t.Run("UploadIndexManifest", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequestWithBody(t, "PUT", fmt.Sprintf("%s/manifests/%s", url, multiTag), strings.NewReader(indexManifestContent)) - addTokenAuthHeader(req, userToken) - req.Header.Set("Content-Type", oci.MediaTypeImageIndex) + req := NewRequestWithBody(t, "PUT", fmt.Sprintf("%s/manifests/%s", url, multiTag), strings.NewReader(indexManifestContent)). + AddTokenAuth(userToken). + SetHeader("Content-Type", oci.MediaTypeImageIndex) resp := MakeRequest(t, req, http.StatusCreated) assert.Equal(t, indexManifestDigest, resp.Header().Get("Docker-Content-Digest")) @@ -498,31 +497,31 @@ func TestPackageContainer(t *testing.T) { t.Run("HeadBlob", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequest(t, "HEAD", fmt.Sprintf("%s/blobs/%s", url, unknownDigest)) - addTokenAuthHeader(req, userToken) + req := NewRequest(t, "HEAD", fmt.Sprintf("%s/blobs/%s", url, unknownDigest)). + AddTokenAuth(userToken) MakeRequest(t, req, http.StatusNotFound) - req = NewRequest(t, "HEAD", fmt.Sprintf("%s/blobs/%s", url, blobDigest)) - addTokenAuthHeader(req, userToken) + req = NewRequest(t, "HEAD", fmt.Sprintf("%s/blobs/%s", url, blobDigest)). + AddTokenAuth(userToken) resp := MakeRequest(t, req, http.StatusOK) assert.Equal(t, fmt.Sprintf("%d", len(blobContent)), resp.Header().Get("Content-Length")) assert.Equal(t, blobDigest, resp.Header().Get("Docker-Content-Digest")) - req = NewRequest(t, "HEAD", fmt.Sprintf("%s/blobs/%s", url, blobDigest)) - addTokenAuthHeader(req, anonymousToken) + req = NewRequest(t, "HEAD", fmt.Sprintf("%s/blobs/%s", url, blobDigest)). + AddTokenAuth(anonymousToken) MakeRequest(t, req, http.StatusOK) }) t.Run("GetBlob", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequest(t, "GET", fmt.Sprintf("%s/blobs/%s", url, unknownDigest)) - addTokenAuthHeader(req, userToken) + req := NewRequest(t, "GET", fmt.Sprintf("%s/blobs/%s", url, unknownDigest)). + AddTokenAuth(userToken) MakeRequest(t, req, http.StatusNotFound) - req = NewRequest(t, "GET", fmt.Sprintf("%s/blobs/%s", url, blobDigest)) - addTokenAuthHeader(req, userToken) + req = NewRequest(t, "GET", fmt.Sprintf("%s/blobs/%s", url, blobDigest)). + AddTokenAuth(userToken) resp := MakeRequest(t, req, http.StatusOK) assert.Equal(t, fmt.Sprintf("%d", len(blobContent)), resp.Header().Get("Content-Length")) @@ -566,8 +565,8 @@ func TestPackageContainer(t *testing.T) { } for _, c := range cases { - req := NewRequest(t, "GET", c.URL) - addTokenAuthHeader(req, userToken) + req := NewRequest(t, "GET", c.URL). + AddTokenAuth(userToken) resp := MakeRequest(t, req, http.StatusOK) type TagList struct { @@ -583,7 +582,8 @@ func TestPackageContainer(t *testing.T) { assert.Equal(t, c.ExpectedLink, resp.Header().Get("Link")) } - req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/packages/%s?type=container&q=%s&token=%s", user.Name, image, token)) + req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/packages/%s?type=container&q=%s", user.Name, image)). + AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusOK) var apiPackages []*api.Package @@ -595,36 +595,36 @@ func TestPackageContainer(t *testing.T) { t.Run("Blob", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequest(t, "DELETE", fmt.Sprintf("%s/blobs/%s", url, blobDigest)) - addTokenAuthHeader(req, userToken) + req := NewRequest(t, "DELETE", fmt.Sprintf("%s/blobs/%s", url, blobDigest)). + AddTokenAuth(userToken) MakeRequest(t, req, http.StatusAccepted) - req = NewRequest(t, "HEAD", fmt.Sprintf("%s/blobs/%s", url, blobDigest)) - addTokenAuthHeader(req, userToken) + req = NewRequest(t, "HEAD", fmt.Sprintf("%s/blobs/%s", url, blobDigest)). + AddTokenAuth(userToken) MakeRequest(t, req, http.StatusNotFound) }) t.Run("ManifestByDigest", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequest(t, "DELETE", fmt.Sprintf("%s/manifests/%s", url, untaggedManifestDigest)) - addTokenAuthHeader(req, userToken) + req := NewRequest(t, "DELETE", fmt.Sprintf("%s/manifests/%s", url, untaggedManifestDigest)). + AddTokenAuth(userToken) MakeRequest(t, req, http.StatusAccepted) - req = NewRequest(t, "HEAD", fmt.Sprintf("%s/manifests/%s", url, untaggedManifestDigest)) - addTokenAuthHeader(req, userToken) + req = NewRequest(t, "HEAD", fmt.Sprintf("%s/manifests/%s", url, untaggedManifestDigest)). + AddTokenAuth(userToken) MakeRequest(t, req, http.StatusNotFound) }) t.Run("ManifestByTag", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequest(t, "DELETE", fmt.Sprintf("%s/manifests/%s", url, multiTag)) - addTokenAuthHeader(req, userToken) + req := NewRequest(t, "DELETE", fmt.Sprintf("%s/manifests/%s", url, multiTag)). + AddTokenAuth(userToken) MakeRequest(t, req, http.StatusAccepted) - req = NewRequest(t, "HEAD", fmt.Sprintf("%s/manifests/%s", url, multiTag)) - addTokenAuthHeader(req, userToken) + req = NewRequest(t, "HEAD", fmt.Sprintf("%s/manifests/%s", url, multiTag)). + AddTokenAuth(userToken) MakeRequest(t, req, http.StatusNotFound) }) }) @@ -647,8 +647,8 @@ func TestPackageContainer(t *testing.T) { go func() { defer wg.Done() - req := NewRequestWithBody(t, "POST", fmt.Sprintf("%s/blobs/uploads?digest=%s", url, digest), bytes.NewReader(content)) - addTokenAuthHeader(req, userToken) + req := NewRequestWithBody(t, "POST", fmt.Sprintf("%s/blobs/uploads?digest=%s", url, digest), bytes.NewReader(content)). + AddTokenAuth(userToken) resp := MakeRequest(t, req, http.StatusCreated) assert.Equal(t, digest, resp.Header().Get("Docker-Content-Digest")) @@ -664,8 +664,8 @@ func TestPackageContainer(t *testing.T) { return func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequest(t, "GET", fmt.Sprintf("%sv2/_catalog", setting.AppURL)) - addTokenAuthHeader(req, userToken) + req := NewRequest(t, "GET", fmt.Sprintf("%sv2/_catalog", setting.AppURL)). + AddTokenAuth(userToken) resp := MakeRequest(t, req, http.StatusOK) type RepositoryList struct { diff --git a/tests/integration/api_packages_cran_test.go b/tests/integration/api_packages_cran_test.go index 9ef23226db0..d307e87d4e0 100644 --- a/tests/integration/api_packages_cran_test.go +++ b/tests/integration/api_packages_cran_test.go @@ -74,15 +74,13 @@ func TestPackageCran(t *testing.T) { req = NewRequestWithBody(t, "PUT", uploadURL, createArchive( "dummy.txt", []byte{}, - )) - req = AddBasicAuthHeader(req, user.Name) + )).AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusBadRequest) req = NewRequestWithBody(t, "PUT", uploadURL, createArchive( "package/DESCRIPTION", createDescription(packageName, packageVersion), - )) - req = AddBasicAuthHeader(req, user.Name) + )).AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusCreated) pvs, err := packages.GetVersionsByPackageType(db.DefaultContext, user.ID, packages.TypeCran) @@ -105,24 +103,23 @@ func TestPackageCran(t *testing.T) { req = NewRequestWithBody(t, "PUT", uploadURL, createArchive( "package/DESCRIPTION", createDescription(packageName, packageVersion), - )) - req = AddBasicAuthHeader(req, user.Name) + )).AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusConflict) }) t.Run("Download", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequest(t, "GET", fmt.Sprintf("%s/src/contrib/%s_%s.tar.gz", url, packageName, packageVersion)) - req = AddBasicAuthHeader(req, user.Name) + req := NewRequest(t, "GET", fmt.Sprintf("%s/src/contrib/%s_%s.tar.gz", url, packageName, packageVersion)). + AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusOK) }) t.Run("Enumerate", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequest(t, "GET", url+"/src/contrib/PACKAGES") - req = AddBasicAuthHeader(req, user.Name) + req := NewRequest(t, "GET", url+"/src/contrib/PACKAGES"). + AddBasicAuth(user.Name) resp := MakeRequest(t, req, http.StatusOK) assert.Contains(t, resp.Header().Get("Content-Type"), "text/plain") @@ -131,8 +128,8 @@ func TestPackageCran(t *testing.T) { assert.Contains(t, body, fmt.Sprintf("Package: %s", packageName)) assert.Contains(t, body, fmt.Sprintf("Version: %s", packageVersion)) - req = NewRequest(t, "GET", url+"/src/contrib/PACKAGES.gz") - req = AddBasicAuthHeader(req, user.Name) + req = NewRequest(t, "GET", url+"/src/contrib/PACKAGES.gz"). + AddBasicAuth(user.Name) resp = MakeRequest(t, req, http.StatusOK) assert.Contains(t, resp.Header().Get("Content-Type"), "application/x-gzip") @@ -160,15 +157,13 @@ func TestPackageCran(t *testing.T) { req = NewRequestWithBody(t, "PUT", uploadURL, createArchive( "dummy.txt", []byte{}, - )) - req = AddBasicAuthHeader(req, user.Name) + )).AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusBadRequest) req = NewRequestWithBody(t, "PUT", uploadURL+"?platform=&rversion=", createArchive( "package/DESCRIPTION", createDescription(packageName, packageVersion), - )) - req = AddBasicAuthHeader(req, user.Name) + )).AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusBadRequest) uploadURL += "?platform=windows&rversion=4.2" @@ -176,8 +171,7 @@ func TestPackageCran(t *testing.T) { req = NewRequestWithBody(t, "PUT", uploadURL, createArchive( "package/DESCRIPTION", createDescription(packageName, packageVersion), - )) - req = AddBasicAuthHeader(req, user.Name) + )).AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusCreated) pvs, err := packages.GetVersionsByPackageType(db.DefaultContext, user.ID, packages.TypeCran) @@ -191,8 +185,7 @@ func TestPackageCran(t *testing.T) { req = NewRequestWithBody(t, "PUT", uploadURL, createArchive( "package/DESCRIPTION", createDescription(packageName, packageVersion), - )) - req = AddBasicAuthHeader(req, user.Name) + )).AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusConflict) }) @@ -210,8 +203,8 @@ func TestPackageCran(t *testing.T) { } for _, c := range cases { - req := NewRequest(t, "GET", fmt.Sprintf("%s/bin/%s/contrib/%s/%s_%s.zip", url, c.Platform, c.RVersion, packageName, packageVersion)) - req = AddBasicAuthHeader(req, user.Name) + req := NewRequest(t, "GET", fmt.Sprintf("%s/bin/%s/contrib/%s/%s_%s.zip", url, c.Platform, c.RVersion, packageName, packageVersion)). + AddBasicAuth(user.Name) MakeRequest(t, req, c.ExpectedStatus) } }) @@ -222,8 +215,8 @@ func TestPackageCran(t *testing.T) { req := NewRequest(t, "GET", url+"/bin/windows/contrib/4.1/PACKAGES") MakeRequest(t, req, http.StatusNotFound) - req = NewRequest(t, "GET", url+"/bin/windows/contrib/4.2/PACKAGES") - req = AddBasicAuthHeader(req, user.Name) + req = NewRequest(t, "GET", url+"/bin/windows/contrib/4.2/PACKAGES"). + AddBasicAuth(user.Name) resp := MakeRequest(t, req, http.StatusOK) assert.Contains(t, resp.Header().Get("Content-Type"), "text/plain") @@ -232,8 +225,8 @@ func TestPackageCran(t *testing.T) { assert.Contains(t, body, fmt.Sprintf("Package: %s", packageName)) assert.Contains(t, body, fmt.Sprintf("Version: %s", packageVersion)) - req = NewRequest(t, "GET", url+"/bin/windows/contrib/4.2/PACKAGES.gz") - req = AddBasicAuthHeader(req, user.Name) + req = NewRequest(t, "GET", url+"/bin/windows/contrib/4.2/PACKAGES.gz"). + AddBasicAuth(user.Name) resp = MakeRequest(t, req, http.StatusOK) assert.Contains(t, resp.Header().Get("Content-Type"), "application/x-gzip") diff --git a/tests/integration/api_packages_debian_test.go b/tests/integration/api_packages_debian_test.go index 6c43f72a71d..05979fccb54 100644 --- a/tests/integration/api_packages_debian_test.go +++ b/tests/integration/api_packages_debian_test.go @@ -89,16 +89,16 @@ func TestPackageDebian(t *testing.T) { req := NewRequestWithBody(t, "PUT", uploadURL, bytes.NewReader([]byte{})) MakeRequest(t, req, http.StatusUnauthorized) - req = NewRequestWithBody(t, "PUT", uploadURL, bytes.NewReader([]byte{})) - AddBasicAuthHeader(req, user.Name) + req = NewRequestWithBody(t, "PUT", uploadURL, bytes.NewReader([]byte{})). + AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusBadRequest) - req = NewRequestWithBody(t, "PUT", uploadURL, createArchive("", "", "")) - AddBasicAuthHeader(req, user.Name) + req = NewRequestWithBody(t, "PUT", uploadURL, createArchive("", "", "")). + AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusBadRequest) - req = NewRequestWithBody(t, "PUT", uploadURL, createArchive(packageName, packageVersion, architecture)) - AddBasicAuthHeader(req, user.Name) + req = NewRequestWithBody(t, "PUT", uploadURL, createArchive(packageName, packageVersion, architecture)). + AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusCreated) pv, err := packages.GetVersionByNameAndVersion(db.DefaultContext, user.ID, packages.TypeDebian, packageName, packageVersion) @@ -145,8 +145,8 @@ func TestPackageDebian(t *testing.T) { return seen }) - req = NewRequestWithBody(t, "PUT", uploadURL, createArchive(packageName, packageVersion, architecture)) - AddBasicAuthHeader(req, user.Name) + req = NewRequestWithBody(t, "PUT", uploadURL, createArchive(packageName, packageVersion, architecture)). + AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusConflict) }) @@ -162,8 +162,8 @@ func TestPackageDebian(t *testing.T) { t.Run("Packages", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequestWithBody(t, "PUT", uploadURL, createArchive(packageName, packageVersion2, architecture)) - AddBasicAuthHeader(req, user.Name) + req := NewRequestWithBody(t, "PUT", uploadURL, createArchive(packageName, packageVersion2, architecture)). + AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusCreated) url := fmt.Sprintf("%s/dists/%s/%s/binary-%s/Packages", rootURL, distribution, component, architecture) @@ -243,12 +243,12 @@ func TestPackageDebian(t *testing.T) { req := NewRequest(t, "DELETE", fmt.Sprintf("%s/pool/%s/%s/%s/%s/%s", rootURL, distribution, component, packageName, packageVersion, architecture)) MakeRequest(t, req, http.StatusUnauthorized) - req = NewRequest(t, "DELETE", fmt.Sprintf("%s/pool/%s/%s/%s/%s/%s", rootURL, distribution, component, packageName, packageVersion, architecture)) - AddBasicAuthHeader(req, user.Name) + req = NewRequest(t, "DELETE", fmt.Sprintf("%s/pool/%s/%s/%s/%s/%s", rootURL, distribution, component, packageName, packageVersion, architecture)). + AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusNoContent) - req = NewRequest(t, "DELETE", fmt.Sprintf("%s/pool/%s/%s/%s/%s/%s", rootURL, distribution, component, packageName, packageVersion2, architecture)) - AddBasicAuthHeader(req, user.Name) + req = NewRequest(t, "DELETE", fmt.Sprintf("%s/pool/%s/%s/%s/%s/%s", rootURL, distribution, component, packageName, packageVersion2, architecture)). + AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusNoContent) req = NewRequest(t, "GET", fmt.Sprintf("%s/dists/%s/%s/binary-%s/Packages", rootURL, distribution, component, architecture)) diff --git a/tests/integration/api_packages_generic_test.go b/tests/integration/api_packages_generic_test.go index f5d8def0f33..93525ac4b19 100644 --- a/tests/integration/api_packages_generic_test.go +++ b/tests/integration/api_packages_generic_test.go @@ -35,8 +35,8 @@ func TestPackageGeneric(t *testing.T) { t.Run("Upload", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequestWithBody(t, "PUT", url+"/"+filename, bytes.NewReader(content)) - AddBasicAuthHeader(req, user.Name) + req := NewRequestWithBody(t, "PUT", url+"/"+filename, bytes.NewReader(content)). + AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusCreated) pvs, err := packages.GetVersionsByPackageType(db.DefaultContext, user.ID, packages.TypeGeneric) @@ -62,16 +62,16 @@ func TestPackageGeneric(t *testing.T) { t.Run("Exists", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequestWithBody(t, "PUT", url+"/"+filename, bytes.NewReader(content)) - AddBasicAuthHeader(req, user.Name) + req := NewRequestWithBody(t, "PUT", url+"/"+filename, bytes.NewReader(content)). + AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusConflict) }) t.Run("Additional", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequestWithBody(t, "PUT", url+"/dummy.bin", bytes.NewReader(content)) - AddBasicAuthHeader(req, user.Name) + req := NewRequestWithBody(t, "PUT", url+"/dummy.bin", bytes.NewReader(content)). + AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusCreated) // Check deduplication @@ -84,16 +84,16 @@ func TestPackageGeneric(t *testing.T) { t.Run("InvalidParameter", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequestWithBody(t, "PUT", fmt.Sprintf("/api/packages/%s/generic/%s/%s/%s", user.Name, "invalid+package name", packageVersion, filename), bytes.NewReader(content)) - AddBasicAuthHeader(req, user.Name) + req := NewRequestWithBody(t, "PUT", fmt.Sprintf("/api/packages/%s/generic/%s/%s/%s", user.Name, "invalid+package name", packageVersion, filename), bytes.NewReader(content)). + AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusBadRequest) - req = NewRequestWithBody(t, "PUT", fmt.Sprintf("/api/packages/%s/generic/%s/%s/%s", user.Name, packageName, "%20test ", filename), bytes.NewReader(content)) - AddBasicAuthHeader(req, user.Name) + req = NewRequestWithBody(t, "PUT", fmt.Sprintf("/api/packages/%s/generic/%s/%s/%s", user.Name, packageName, "%20test ", filename), bytes.NewReader(content)). + AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusBadRequest) - req = NewRequestWithBody(t, "PUT", fmt.Sprintf("/api/packages/%s/generic/%s/%s/%s", user.Name, packageName, packageVersion, "inval+id.na me"), bytes.NewReader(content)) - AddBasicAuthHeader(req, user.Name) + req = NewRequestWithBody(t, "PUT", fmt.Sprintf("/api/packages/%s/generic/%s/%s/%s", user.Name, packageName, packageVersion, "inval+id.na me"), bytes.NewReader(content)). + AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusBadRequest) }) }) @@ -187,15 +187,15 @@ func TestPackageGeneric(t *testing.T) { req := NewRequest(t, "DELETE", url+"/"+filename) MakeRequest(t, req, http.StatusUnauthorized) - req = NewRequest(t, "DELETE", url+"/"+filename) - AddBasicAuthHeader(req, user.Name) + req = NewRequest(t, "DELETE", url+"/"+filename). + AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusNoContent) req = NewRequest(t, "GET", url+"/"+filename) MakeRequest(t, req, http.StatusNotFound) - req = NewRequest(t, "DELETE", url+"/"+filename) - AddBasicAuthHeader(req, user.Name) + req = NewRequest(t, "DELETE", url+"/"+filename). + AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusNotFound) pvs, err := packages.GetVersionsByPackageType(db.DefaultContext, user.ID, packages.TypeGeneric) @@ -205,8 +205,8 @@ func TestPackageGeneric(t *testing.T) { t.Run("RemovesVersion", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req = NewRequest(t, "DELETE", url+"/dummy.bin") - AddBasicAuthHeader(req, user.Name) + req = NewRequest(t, "DELETE", url+"/dummy.bin"). + AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusNoContent) pvs, err := packages.GetVersionsByPackageType(db.DefaultContext, user.ID, packages.TypeGeneric) @@ -218,15 +218,15 @@ func TestPackageGeneric(t *testing.T) { t.Run("Version", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequestWithBody(t, "PUT", url+"/"+filename, bytes.NewReader(content)) - AddBasicAuthHeader(req, user.Name) + req := NewRequestWithBody(t, "PUT", url+"/"+filename, bytes.NewReader(content)). + AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusCreated) req = NewRequest(t, "DELETE", url) MakeRequest(t, req, http.StatusUnauthorized) - req = NewRequest(t, "DELETE", url) - AddBasicAuthHeader(req, user.Name) + req = NewRequest(t, "DELETE", url). + AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusNoContent) pvs, err := packages.GetVersionsByPackageType(db.DefaultContext, user.ID, packages.TypeGeneric) @@ -236,8 +236,8 @@ func TestPackageGeneric(t *testing.T) { req = NewRequest(t, "GET", url+"/"+filename) MakeRequest(t, req, http.StatusNotFound) - req = NewRequest(t, "DELETE", url) - AddBasicAuthHeader(req, user.Name) + req = NewRequest(t, "DELETE", url). + AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusNotFound) }) }) diff --git a/tests/integration/api_packages_goproxy_test.go b/tests/integration/api_packages_goproxy_test.go index 08c1ca54f14..dab9fefc5e1 100644 --- a/tests/integration/api_packages_goproxy_test.go +++ b/tests/integration/api_packages_goproxy_test.go @@ -51,16 +51,16 @@ func TestPackageGo(t *testing.T) { req := NewRequestWithBody(t, "PUT", url+"/upload", bytes.NewReader(content)) MakeRequest(t, req, http.StatusUnauthorized) - req = NewRequestWithBody(t, "PUT", url+"/upload", bytes.NewReader(content)) - AddBasicAuthHeader(req, user.Name) + req = NewRequestWithBody(t, "PUT", url+"/upload", bytes.NewReader(content)). + AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusBadRequest) content = createArchive(map[string][]byte{ packageName + "@" + packageVersion + "/go.mod": []byte(goModContent), }) - req = NewRequestWithBody(t, "PUT", url+"/upload", bytes.NewReader(content)) - AddBasicAuthHeader(req, user.Name) + req = NewRequestWithBody(t, "PUT", url+"/upload", bytes.NewReader(content)). + AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusCreated) pvs, err := packages.GetVersionsByPackageType(db.DefaultContext, user.ID, packages.TypeGo) @@ -83,8 +83,8 @@ func TestPackageGo(t *testing.T) { assert.NoError(t, err) assert.Equal(t, int64(len(content)), pb.Size) - req = NewRequestWithBody(t, "PUT", url+"/upload", bytes.NewReader(content)) - AddBasicAuthHeader(req, user.Name) + req = NewRequestWithBody(t, "PUT", url+"/upload", bytes.NewReader(content)). + AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusConflict) time.Sleep(time.Second) @@ -93,8 +93,8 @@ func TestPackageGo(t *testing.T) { packageName + "@" + packageVersion2 + "/go.mod": []byte(goModContent), }) - req = NewRequestWithBody(t, "PUT", url+"/upload", bytes.NewReader(content)) - AddBasicAuthHeader(req, user.Name) + req = NewRequestWithBody(t, "PUT", url+"/upload", bytes.NewReader(content)). + AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusCreated) }) diff --git a/tests/integration/api_packages_helm_test.go b/tests/integration/api_packages_helm_test.go index 4f61452071b..76285add117 100644 --- a/tests/integration/api_packages_helm_test.go +++ b/tests/integration/api_packages_helm_test.go @@ -68,8 +68,8 @@ dependencies: uploadURL := url + "/api/charts" - req := NewRequestWithBody(t, "POST", uploadURL, bytes.NewReader(content)) - req = AddBasicAuthHeader(req, user.Name) + req := NewRequestWithBody(t, "POST", uploadURL, bytes.NewReader(content)). + AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusCreated) pvs, err := packages.GetVersionsByPackageType(db.DefaultContext, user.ID, packages.TypeHelm) @@ -93,8 +93,8 @@ dependencies: assert.NoError(t, err) assert.Equal(t, int64(len(content)), pb.Size) - req = NewRequestWithBody(t, "POST", uploadURL, bytes.NewReader(content)) - req = AddBasicAuthHeader(req, user.Name) + req = NewRequestWithBody(t, "POST", uploadURL, bytes.NewReader(content)). + AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusCreated) }) @@ -110,8 +110,8 @@ dependencies: checkDownloadCount(0) - req := NewRequest(t, "GET", fmt.Sprintf("%s/%s", url, filename)) - req = AddBasicAuthHeader(req, user.Name) + req := NewRequest(t, "GET", fmt.Sprintf("%s/%s", url, filename)). + AddBasicAuth(user.Name) resp := MakeRequest(t, req, http.StatusOK) assert.Equal(t, content, resp.Body.Bytes()) @@ -122,8 +122,8 @@ dependencies: t.Run("Index", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequest(t, "GET", fmt.Sprintf("%s/index.yaml", url)) - req = AddBasicAuthHeader(req, user.Name) + req := NewRequest(t, "GET", fmt.Sprintf("%s/index.yaml", url)). + AddBasicAuth(user.Name) resp := MakeRequest(t, req, http.StatusOK) type ChartVersion struct { diff --git a/tests/integration/api_packages_maven_test.go b/tests/integration/api_packages_maven_test.go index c78024563f4..c7ed554a9d7 100644 --- a/tests/integration/api_packages_maven_test.go +++ b/tests/integration/api_packages_maven_test.go @@ -35,8 +35,8 @@ func TestPackageMaven(t *testing.T) { filename := fmt.Sprintf("%s-%s.jar", packageName, packageVersion) putFile := func(t *testing.T, path, content string, expectedStatus int) { - req := NewRequestWithBody(t, "PUT", root+path, strings.NewReader(content)) - req = AddBasicAuthHeader(req, user.Name) + req := NewRequestWithBody(t, "PUT", root+path, strings.NewReader(content)). + AddBasicAuth(user.Name) MakeRequest(t, req, expectedStatus) } @@ -84,14 +84,14 @@ func TestPackageMaven(t *testing.T) { t.Run("Download", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequest(t, "HEAD", fmt.Sprintf("%s/%s/%s", root, packageVersion, filename)) - req = AddBasicAuthHeader(req, user.Name) + req := NewRequest(t, "HEAD", fmt.Sprintf("%s/%s/%s", root, packageVersion, filename)). + AddBasicAuth(user.Name) resp := MakeRequest(t, req, http.StatusOK) checkHeaders(t, resp.Header(), "application/java-archive", 4) - req = NewRequest(t, "GET", fmt.Sprintf("%s/%s/%s", root, packageVersion, filename)) - req = AddBasicAuthHeader(req, user.Name) + req = NewRequest(t, "GET", fmt.Sprintf("%s/%s/%s", root, packageVersion, filename)). + AddBasicAuth(user.Name) resp = MakeRequest(t, req, http.StatusOK) checkHeaders(t, resp.Header(), "application/java-archive", 4) @@ -165,14 +165,14 @@ func TestPackageMaven(t *testing.T) { t.Run("DownloadPOM", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequest(t, "HEAD", fmt.Sprintf("%s/%s/%s.pom", root, packageVersion, filename)) - req = AddBasicAuthHeader(req, user.Name) + req := NewRequest(t, "HEAD", fmt.Sprintf("%s/%s/%s.pom", root, packageVersion, filename)). + AddBasicAuth(user.Name) resp := MakeRequest(t, req, http.StatusOK) checkHeaders(t, resp.Header(), "text/xml", int64(len(pomContent))) - req = NewRequest(t, "GET", fmt.Sprintf("%s/%s/%s.pom", root, packageVersion, filename)) - req = AddBasicAuthHeader(req, user.Name) + req = NewRequest(t, "GET", fmt.Sprintf("%s/%s/%s.pom", root, packageVersion, filename)). + AddBasicAuth(user.Name) resp = MakeRequest(t, req, http.StatusOK) checkHeaders(t, resp.Header(), "text/xml", int64(len(pomContent))) @@ -188,8 +188,8 @@ func TestPackageMaven(t *testing.T) { t.Run("DownloadChecksums", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequest(t, "GET", fmt.Sprintf("%s/1.2.3/%s", root, filename)) - req = AddBasicAuthHeader(req, user.Name) + req := NewRequest(t, "GET", fmt.Sprintf("%s/1.2.3/%s", root, filename)). + AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusNotFound) for key, checksum := range map[string]string{ @@ -198,8 +198,8 @@ func TestPackageMaven(t *testing.T) { "sha256": "9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08", "sha512": "ee26b0dd4af7e749aa1a8ee3c10ae9923f618980772e473f8819a5d4940e0db27ac185f8a0e1d5f84f88bc887fd67b143732c304cc5fa9ad8e6f57f50028a8ff", } { - req := NewRequest(t, "GET", fmt.Sprintf("%s/%s/%s.%s", root, packageVersion, filename, key)) - req = AddBasicAuthHeader(req, user.Name) + req := NewRequest(t, "GET", fmt.Sprintf("%s/%s/%s.%s", root, packageVersion, filename, key)). + AddBasicAuth(user.Name) resp := MakeRequest(t, req, http.StatusOK) assert.Equal(t, checksum, resp.Body.String()) @@ -209,8 +209,8 @@ func TestPackageMaven(t *testing.T) { t.Run("DownloadMetadata", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequest(t, "GET", root+"/maven-metadata.xml") - req = AddBasicAuthHeader(req, user.Name) + req := NewRequest(t, "GET", root+"/maven-metadata.xml"). + AddBasicAuth(user.Name) resp := MakeRequest(t, req, http.StatusOK) expectedMetadata := `` + "\ncom.giteatest-project1.0.11.0.11.0.1" @@ -225,8 +225,8 @@ func TestPackageMaven(t *testing.T) { "sha256": "3f48322f81c4b2c3bb8649ae1e5c9801476162b520e1c2734ac06b2c06143208", "sha512": "cb075aa2e2ef1a83cdc14dd1e08c505b72d633399b39e73a21f00f0deecb39a3e2c79f157c1163f8a3854828750706e0dec3a0f5e4778e91f8ec2cf351a855f2", } { - req := NewRequest(t, "GET", fmt.Sprintf("%s/maven-metadata.xml.%s", root, key)) - req = AddBasicAuthHeader(req, user.Name) + req := NewRequest(t, "GET", fmt.Sprintf("%s/maven-metadata.xml.%s", root, key)). + AddBasicAuth(user.Name) resp := MakeRequest(t, req, http.StatusOK) assert.Equal(t, checksum, resp.Body.String()) diff --git a/tests/integration/api_packages_npm_test.go b/tests/integration/api_packages_npm_test.go index bd3bfeeff06..9c888972ffb 100644 --- a/tests/integration/api_packages_npm_test.go +++ b/tests/integration/api_packages_npm_test.go @@ -87,8 +87,8 @@ func TestPackageNpm(t *testing.T) { t.Run("Upload", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequestWithBody(t, "PUT", root, strings.NewReader(buildUpload(packageVersion))) - req = addTokenAuthHeader(req, token) + req := NewRequestWithBody(t, "PUT", root, strings.NewReader(buildUpload(packageVersion))). + AddTokenAuth(token) MakeRequest(t, req, http.StatusCreated) pvs, err := packages.GetVersionsByPackageType(db.DefaultContext, user.ID, packages.TypeNpm) @@ -119,23 +119,23 @@ func TestPackageNpm(t *testing.T) { t.Run("UploadExists", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequestWithBody(t, "PUT", root, strings.NewReader(buildUpload(packageVersion))) - req = addTokenAuthHeader(req, token) + req := NewRequestWithBody(t, "PUT", root, strings.NewReader(buildUpload(packageVersion))). + AddTokenAuth(token) MakeRequest(t, req, http.StatusConflict) }) t.Run("Download", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequest(t, "GET", fmt.Sprintf("%s/-/%s/%s", root, packageVersion, filename)) - req = addTokenAuthHeader(req, token) + req := NewRequest(t, "GET", fmt.Sprintf("%s/-/%s/%s", root, packageVersion, filename)). + AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusOK) b, _ := base64.StdEncoding.DecodeString(data) assert.Equal(t, b, resp.Body.Bytes()) - req = NewRequest(t, "GET", fmt.Sprintf("%s/-/%s", root, filename)) - req = addTokenAuthHeader(req, token) + req = NewRequest(t, "GET", fmt.Sprintf("%s/-/%s", root, filename)). + AddTokenAuth(token) resp = MakeRequest(t, req, http.StatusOK) assert.Equal(t, b, resp.Body.Bytes()) @@ -149,12 +149,12 @@ func TestPackageNpm(t *testing.T) { t.Run("PackageMetadata", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequest(t, "GET", fmt.Sprintf("/api/packages/%s/npm/%s", user.Name, "does-not-exist")) - req = addTokenAuthHeader(req, token) + req := NewRequest(t, "GET", fmt.Sprintf("/api/packages/%s/npm/%s", user.Name, "does-not-exist")). + AddTokenAuth(token) MakeRequest(t, req, http.StatusNotFound) - req = NewRequest(t, "GET", root) - req = addTokenAuthHeader(req, token) + req = NewRequest(t, "GET", root). + AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusOK) var result npm.PackageMetadata @@ -184,8 +184,8 @@ func TestPackageNpm(t *testing.T) { defer tests.PrintCurrentTest(t)() test := func(t *testing.T, status int, tag, version string) { - req := NewRequestWithBody(t, "PUT", fmt.Sprintf("%s/%s", tagsRoot, tag), strings.NewReader(`"`+version+`"`)) - req = addTokenAuthHeader(req, token) + req := NewRequestWithBody(t, "PUT", fmt.Sprintf("%s/%s", tagsRoot, tag), strings.NewReader(`"`+version+`"`)). + AddTokenAuth(token) MakeRequest(t, req, status) } @@ -199,8 +199,8 @@ func TestPackageNpm(t *testing.T) { t.Run("ListTags", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequest(t, "GET", tagsRoot) - req = addTokenAuthHeader(req, token) + req := NewRequest(t, "GET", tagsRoot). + AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusOK) var result map[string]string @@ -216,8 +216,8 @@ func TestPackageNpm(t *testing.T) { t.Run("PackageMetadataDistTags", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequest(t, "GET", root) - req = addTokenAuthHeader(req, token) + req := NewRequest(t, "GET", root). + AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusOK) var result npm.PackageMetadata @@ -234,8 +234,8 @@ func TestPackageNpm(t *testing.T) { defer tests.PrintCurrentTest(t)() test := func(t *testing.T, status int, tag string) { - req := NewRequest(t, "DELETE", fmt.Sprintf("%s/%s", tagsRoot, tag)) - req = addTokenAuthHeader(req, token) + req := NewRequest(t, "DELETE", fmt.Sprintf("%s/%s", tagsRoot, tag)). + AddTokenAuth(token) MakeRequest(t, req, status) } @@ -279,15 +279,15 @@ func TestPackageNpm(t *testing.T) { t.Run("Delete", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequestWithBody(t, "PUT", root, strings.NewReader(buildUpload(packageVersion+"-dummy"))) - req = addTokenAuthHeader(req, token) + req := NewRequestWithBody(t, "PUT", root, strings.NewReader(buildUpload(packageVersion+"-dummy"))). + AddTokenAuth(token) MakeRequest(t, req, http.StatusCreated) req = NewRequest(t, "PUT", root+"/-rev/dummy") MakeRequest(t, req, http.StatusUnauthorized) - req = NewRequest(t, "PUT", root+"/-rev/dummy") - req = addTokenAuthHeader(req, token) + req = NewRequest(t, "PUT", root+"/-rev/dummy"). + AddTokenAuth(token) MakeRequest(t, req, http.StatusOK) t.Run("Version", func(t *testing.T) { @@ -300,8 +300,8 @@ func TestPackageNpm(t *testing.T) { req := NewRequest(t, "DELETE", fmt.Sprintf("%s/-/%s/%s/-rev/dummy", root, packageVersion, filename)) MakeRequest(t, req, http.StatusUnauthorized) - req = NewRequest(t, "DELETE", fmt.Sprintf("%s/-/%s/%s/-rev/dummy", root, packageVersion, filename)) - req = addTokenAuthHeader(req, token) + req = NewRequest(t, "DELETE", fmt.Sprintf("%s/-/%s/%s/-rev/dummy", root, packageVersion, filename)). + AddTokenAuth(token) MakeRequest(t, req, http.StatusOK) pvs, err = packages.GetVersionsByPackageType(db.DefaultContext, user.ID, packages.TypeNpm) @@ -319,8 +319,8 @@ func TestPackageNpm(t *testing.T) { req := NewRequest(t, "DELETE", root+"/-rev/dummy") MakeRequest(t, req, http.StatusUnauthorized) - req = NewRequest(t, "DELETE", root+"/-rev/dummy") - req = addTokenAuthHeader(req, token) + req = NewRequest(t, "DELETE", root+"/-rev/dummy"). + AddTokenAuth(token) MakeRequest(t, req, http.StatusOK) pvs, err = packages.GetVersionsByPackageType(db.DefaultContext, user.ID, packages.TypeNpm) diff --git a/tests/integration/api_packages_nuget_test.go b/tests/integration/api_packages_nuget_test.go index 04c2fbce0ec..20dafd5cc79 100644 --- a/tests/integration/api_packages_nuget_test.go +++ b/tests/integration/api_packages_nuget_test.go @@ -31,9 +31,8 @@ import ( "github.com/stretchr/testify/assert" ) -func addNuGetAPIKeyHeader(request *http.Request, token string) *http.Request { - request.Header.Set("X-NuGet-ApiKey", token) - return request +func addNuGetAPIKeyHeader(req *RequestWrapper, token string) { + req.SetHeader("X-NuGet-ApiKey", token) } func decodeXML(t testing.TB, resp *httptest.ResponseRecorder, v any) { @@ -141,9 +140,9 @@ func TestPackageNuGet(t *testing.T) { req := NewRequest(t, "GET", url) if c.UseBasicAuth { - req = AddBasicAuthHeader(req, user.Name) + req.AddBasicAuth(user.Name) } else if c.UseTokenAuth { - req = addNuGetAPIKeyHeader(req, token) + addNuGetAPIKeyHeader(req, token) } resp := MakeRequest(t, req, http.StatusOK) @@ -178,9 +177,9 @@ func TestPackageNuGet(t *testing.T) { req := NewRequest(t, "GET", fmt.Sprintf("%s/index.json", url)) if c.UseBasicAuth { - req = AddBasicAuthHeader(req, user.Name) + req.AddBasicAuth(user.Name) } else if c.UseTokenAuth { - req = addNuGetAPIKeyHeader(req, token) + addNuGetAPIKeyHeader(req, token) } resp := MakeRequest(t, req, http.StatusOK) @@ -219,8 +218,8 @@ func TestPackageNuGet(t *testing.T) { t.Run("DependencyPackage", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequestWithBody(t, "PUT", url, bytes.NewReader(content)) - req = AddBasicAuthHeader(req, user.Name) + req := NewRequestWithBody(t, "PUT", url, bytes.NewReader(content)). + AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusCreated) pvs, err := packages.GetVersionsByPackageType(db.DefaultContext, user.ID, packages.TypeNuGet) @@ -244,8 +243,8 @@ func TestPackageNuGet(t *testing.T) { assert.NoError(t, err) assert.Equal(t, int64(len(content)), pb.Size) - req = NewRequestWithBody(t, "PUT", url, bytes.NewReader(content)) - req = AddBasicAuthHeader(req, user.Name) + req = NewRequestWithBody(t, "PUT", url, bytes.NewReader(content)). + AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusConflict) }) @@ -278,16 +277,16 @@ AAAjQmxvYgAAAGm7ENm9SGxMtAFVvPUsPJTF6PbtAAAAAFcVogEJAAAAAQAAAA==`) return &buf } - req := NewRequestWithBody(t, "PUT", fmt.Sprintf("%s/symbolpackage", url), createSymbolPackage("unknown-package", "SymbolsPackage")) - req = AddBasicAuthHeader(req, user.Name) + req := NewRequestWithBody(t, "PUT", fmt.Sprintf("%s/symbolpackage", url), createSymbolPackage("unknown-package", "SymbolsPackage")). + AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusNotFound) - req = NewRequestWithBody(t, "PUT", fmt.Sprintf("%s/symbolpackage", url), createSymbolPackage(packageName, "DummyPackage")) - req = AddBasicAuthHeader(req, user.Name) + req = NewRequestWithBody(t, "PUT", fmt.Sprintf("%s/symbolpackage", url), createSymbolPackage(packageName, "DummyPackage")). + AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusBadRequest) - req = NewRequestWithBody(t, "PUT", fmt.Sprintf("%s/symbolpackage", url), createSymbolPackage(packageName, "SymbolsPackage")) - req = AddBasicAuthHeader(req, user.Name) + req = NewRequestWithBody(t, "PUT", fmt.Sprintf("%s/symbolpackage", url), createSymbolPackage(packageName, "SymbolsPackage")). + AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusCreated) pvs, err := packages.GetVersionsByPackageType(db.DefaultContext, user.ID, packages.TypeNuGet) @@ -330,8 +329,8 @@ AAAjQmxvYgAAAGm7ENm9SGxMtAFVvPUsPJTF6PbtAAAAAFcVogEJAAAAAQAAAA==`) } } - req = NewRequestWithBody(t, "PUT", fmt.Sprintf("%s/symbolpackage", url), createSymbolPackage(packageName, "SymbolsPackage")) - req = AddBasicAuthHeader(req, user.Name) + req = NewRequestWithBody(t, "PUT", fmt.Sprintf("%s/symbolpackage", url), createSymbolPackage(packageName, "SymbolsPackage")). + AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusConflict) }) }) @@ -348,16 +347,16 @@ AAAjQmxvYgAAAGm7ENm9SGxMtAFVvPUsPJTF6PbtAAAAAFcVogEJAAAAAQAAAA==`) checkDownloadCount(0) - req := NewRequest(t, "GET", fmt.Sprintf("%s/package/%s/%s/%s.%s.nupkg", url, packageName, packageVersion, packageName, packageVersion)) - req = AddBasicAuthHeader(req, user.Name) + req := NewRequest(t, "GET", fmt.Sprintf("%s/package/%s/%s/%s.%s.nupkg", url, packageName, packageVersion, packageName, packageVersion)). + AddBasicAuth(user.Name) resp := MakeRequest(t, req, http.StatusOK) assert.Equal(t, content, resp.Body.Bytes()) checkDownloadCount(1) - req = NewRequest(t, "GET", fmt.Sprintf("%s/package/%s/%s/%s.%s.snupkg", url, packageName, packageVersion, packageName, packageVersion)) - req = AddBasicAuthHeader(req, user.Name) + req = NewRequest(t, "GET", fmt.Sprintf("%s/package/%s/%s/%s.%s.snupkg", url, packageName, packageVersion, packageName, packageVersion)). + AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusOK) checkDownloadCount(1) @@ -368,12 +367,12 @@ AAAjQmxvYgAAAGm7ENm9SGxMtAFVvPUsPJTF6PbtAAAAAFcVogEJAAAAAQAAAA==`) req := NewRequest(t, "GET", fmt.Sprintf("%s/symbols/%s/%sFFFFFFFF/gitea.pdb", url, symbolFilename, symbolID)) MakeRequest(t, req, http.StatusBadRequest) - req = NewRequest(t, "GET", fmt.Sprintf("%s/symbols/%s/%sFFFFFFFF/%s", url, symbolFilename, "00000000000000000000000000000000", symbolFilename)) - req = AddBasicAuthHeader(req, user.Name) + req = NewRequest(t, "GET", fmt.Sprintf("%s/symbols/%s/%sFFFFFFFF/%s", url, symbolFilename, "00000000000000000000000000000000", symbolFilename)). + AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusNotFound) - req = NewRequest(t, "GET", fmt.Sprintf("%s/symbols/%s/%sFFFFffff/%s", url, symbolFilename, symbolID, symbolFilename)) - req = AddBasicAuthHeader(req, user.Name) + req = NewRequest(t, "GET", fmt.Sprintf("%s/symbols/%s/%sFFFFffff/%s", url, symbolFilename, symbolID, symbolFilename)). + AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusOK) checkDownloadCount(1) @@ -414,8 +413,8 @@ AAAjQmxvYgAAAGm7ENm9SGxMtAFVvPUsPJTF6PbtAAAAAFcVogEJAAAAAQAAAA==`) {"test", 1, 10, 1, 0}, } - req := NewRequestWithBody(t, "PUT", url, createPackage(packageName, "1.0.99")) - req = AddBasicAuthHeader(req, user.Name) + req := NewRequestWithBody(t, "PUT", url, createPackage(packageName, "1.0.99")). + AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusCreated) t.Run("v2", func(t *testing.T) { @@ -423,8 +422,8 @@ AAAjQmxvYgAAAGm7ENm9SGxMtAFVvPUsPJTF6PbtAAAAAFcVogEJAAAAAQAAAA==`) defer tests.PrintCurrentTest(t)() for i, c := range cases { - req := NewRequest(t, "GET", fmt.Sprintf("%s/Search()?searchTerm='%s'&$skip=%d&$top=%d", url, c.Query, c.Skip, c.Take)) - req = AddBasicAuthHeader(req, user.Name) + req := NewRequest(t, "GET", fmt.Sprintf("%s/Search()?searchTerm='%s'&$skip=%d&$top=%d", url, c.Query, c.Skip, c.Take)). + AddBasicAuth(user.Name) resp := MakeRequest(t, req, http.StatusOK) var result FeedResponse @@ -433,8 +432,8 @@ AAAjQmxvYgAAAGm7ENm9SGxMtAFVvPUsPJTF6PbtAAAAAFcVogEJAAAAAQAAAA==`) assert.Equal(t, c.ExpectedTotal, result.Count, "case %d: unexpected total hits", i) assert.Len(t, result.Entries, c.ExpectedResults, "case %d: unexpected result count", i) - req = NewRequest(t, "GET", fmt.Sprintf("%s/Search()/$count?searchTerm='%s'&$skip=%d&$top=%d", url, c.Query, c.Skip, c.Take)) - req = AddBasicAuthHeader(req, user.Name) + req = NewRequest(t, "GET", fmt.Sprintf("%s/Search()/$count?searchTerm='%s'&$skip=%d&$top=%d", url, c.Query, c.Skip, c.Take)). + AddBasicAuth(user.Name) resp = MakeRequest(t, req, http.StatusOK) assert.Equal(t, strconv.FormatInt(c.ExpectedTotal, 10), resp.Body.String(), "case %d: unexpected total hits", i) @@ -445,8 +444,8 @@ AAAjQmxvYgAAAGm7ENm9SGxMtAFVvPUsPJTF6PbtAAAAAFcVogEJAAAAAQAAAA==`) defer tests.PrintCurrentTest(t)() for i, c := range cases { - req := NewRequest(t, "GET", fmt.Sprintf("%s/Packages()?$filter=substringof('%s',tolower(Id))&$skip=%d&$top=%d", url, c.Query, c.Skip, c.Take)) - req = AddBasicAuthHeader(req, user.Name) + req := NewRequest(t, "GET", fmt.Sprintf("%s/Packages()?$filter=substringof('%s',tolower(Id))&$skip=%d&$top=%d", url, c.Query, c.Skip, c.Take)). + AddBasicAuth(user.Name) resp := MakeRequest(t, req, http.StatusOK) var result FeedResponse @@ -455,8 +454,8 @@ AAAjQmxvYgAAAGm7ENm9SGxMtAFVvPUsPJTF6PbtAAAAAFcVogEJAAAAAQAAAA==`) assert.Equal(t, c.ExpectedTotal, result.Count, "case %d: unexpected total hits", i) assert.Len(t, result.Entries, c.ExpectedResults, "case %d: unexpected result count", i) - req = NewRequest(t, "GET", fmt.Sprintf("%s/Packages()/$count?$filter=substringof('%s',tolower(Id))&$skip=%d&$top=%d", url, c.Query, c.Skip, c.Take)) - req = AddBasicAuthHeader(req, user.Name) + req = NewRequest(t, "GET", fmt.Sprintf("%s/Packages()/$count?$filter=substringof('%s',tolower(Id))&$skip=%d&$top=%d", url, c.Query, c.Skip, c.Take)). + AddBasicAuth(user.Name) resp = MakeRequest(t, req, http.StatusOK) assert.Equal(t, strconv.FormatInt(c.ExpectedTotal, 10), resp.Body.String(), "case %d: unexpected total hits", i) @@ -464,8 +463,8 @@ AAAjQmxvYgAAAGm7ENm9SGxMtAFVvPUsPJTF6PbtAAAAAFcVogEJAAAAAQAAAA==`) }) t.Run("Next", func(t *testing.T) { - req := NewRequest(t, "GET", fmt.Sprintf("%s/Search()?searchTerm='test'&$skip=0&$top=1", url)) - req = AddBasicAuthHeader(req, user.Name) + req := NewRequest(t, "GET", fmt.Sprintf("%s/Search()?searchTerm='test'&$skip=0&$top=1", url)). + AddBasicAuth(user.Name) resp := MakeRequest(t, req, http.StatusOK) var result FeedResponse @@ -479,8 +478,8 @@ AAAjQmxvYgAAAGm7ENm9SGxMtAFVvPUsPJTF6PbtAAAAAFcVogEJAAAAAQAAAA==`) defer tests.PrintCurrentTest(t)() for i, c := range cases { - req := NewRequest(t, "GET", fmt.Sprintf("%s/query?q=%s&skip=%d&take=%d", url, c.Query, c.Skip, c.Take)) - req = AddBasicAuthHeader(req, user.Name) + req := NewRequest(t, "GET", fmt.Sprintf("%s/query?q=%s&skip=%d&take=%d", url, c.Query, c.Skip, c.Take)). + AddBasicAuth(user.Name) resp := MakeRequest(t, req, http.StatusOK) var result nuget.SearchResultResponse @@ -493,12 +492,12 @@ AAAjQmxvYgAAAGm7ENm9SGxMtAFVvPUsPJTF6PbtAAAAAFcVogEJAAAAAQAAAA==`) t.Run("EnforceGrouped", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequestWithBody(t, "PUT", url, createPackage(packageName+".dummy", "1.0.0")) - req = AddBasicAuthHeader(req, user.Name) + req := NewRequestWithBody(t, "PUT", url, createPackage(packageName+".dummy", "1.0.0")). + AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusCreated) - req = NewRequest(t, "GET", fmt.Sprintf("%s/query?q=%s", url, packageName)) - req = AddBasicAuthHeader(req, user.Name) + req = NewRequest(t, "GET", fmt.Sprintf("%s/query?q=%s", url, packageName)). + AddBasicAuth(user.Name) resp := MakeRequest(t, req, http.StatusOK) var result nuget.SearchResultResponse @@ -514,14 +513,14 @@ AAAjQmxvYgAAAGm7ENm9SGxMtAFVvPUsPJTF6PbtAAAAAFcVogEJAAAAAQAAAA==`) } } - req = NewRequest(t, "DELETE", fmt.Sprintf("%s/%s/%s", url, packageName+".dummy", "1.0.0")) - req = AddBasicAuthHeader(req, user.Name) + req = NewRequest(t, "DELETE", fmt.Sprintf("%s/%s/%s", url, packageName+".dummy", "1.0.0")). + AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusNoContent) }) }) - req = NewRequest(t, "DELETE", fmt.Sprintf("%s/%s/%s", url, packageName, "1.0.99")) - req = AddBasicAuthHeader(req, user.Name) + req = NewRequest(t, "DELETE", fmt.Sprintf("%s/%s/%s", url, packageName, "1.0.99")). + AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusNoContent) }) @@ -533,8 +532,8 @@ AAAjQmxvYgAAAGm7ENm9SGxMtAFVvPUsPJTF6PbtAAAAAFcVogEJAAAAAQAAAA==`) t.Run("RegistrationIndex", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequest(t, "GET", fmt.Sprintf("%s/registration/%s/index.json", url, packageName)) - req = AddBasicAuthHeader(req, user.Name) + req := NewRequest(t, "GET", fmt.Sprintf("%s/registration/%s/index.json", url, packageName)). + AddBasicAuth(user.Name) resp := MakeRequest(t, req, http.StatusOK) var result nuget.RegistrationIndexResponse @@ -560,8 +559,8 @@ AAAjQmxvYgAAAGm7ENm9SGxMtAFVvPUsPJTF6PbtAAAAAFcVogEJAAAAAQAAAA==`) t.Run("v2", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequest(t, "GET", fmt.Sprintf("%s/Packages(Id='%s',Version='%s')", url, packageName, packageVersion)) - req = AddBasicAuthHeader(req, user.Name) + req := NewRequest(t, "GET", fmt.Sprintf("%s/Packages(Id='%s',Version='%s')", url, packageName, packageVersion)). + AddBasicAuth(user.Name) resp := MakeRequest(t, req, http.StatusOK) var result FeedEntry @@ -577,8 +576,8 @@ AAAjQmxvYgAAAGm7ENm9SGxMtAFVvPUsPJTF6PbtAAAAAFcVogEJAAAAAQAAAA==`) t.Run("v3", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequest(t, "GET", fmt.Sprintf("%s/registration/%s/%s.json", url, packageName, packageVersion)) - req = AddBasicAuthHeader(req, user.Name) + req := NewRequest(t, "GET", fmt.Sprintf("%s/registration/%s/%s.json", url, packageName, packageVersion)). + AddBasicAuth(user.Name) resp := MakeRequest(t, req, http.StatusOK) var result nuget.RegistrationLeafResponse @@ -595,8 +594,8 @@ AAAjQmxvYgAAAGm7ENm9SGxMtAFVvPUsPJTF6PbtAAAAAFcVogEJAAAAAQAAAA==`) t.Run("v2", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequest(t, "GET", fmt.Sprintf("%s/FindPackagesById()?id='%s'&$top=1", url, packageName)) - req = AddBasicAuthHeader(req, user.Name) + req := NewRequest(t, "GET", fmt.Sprintf("%s/FindPackagesById()?id='%s'&$top=1", url, packageName)). + AddBasicAuth(user.Name) resp := MakeRequest(t, req, http.StatusOK) var result FeedResponse @@ -606,8 +605,8 @@ AAAjQmxvYgAAAGm7ENm9SGxMtAFVvPUsPJTF6PbtAAAAAFcVogEJAAAAAQAAAA==`) assert.Equal(t, packageVersion, result.Entries[0].Properties.Version) assert.Condition(t, containsOneNextLink(t, result.Links)) - req = NewRequest(t, "GET", fmt.Sprintf("%s/FindPackagesById()/$count?id='%s'", url, packageName)) - req = AddBasicAuthHeader(req, user.Name) + req = NewRequest(t, "GET", fmt.Sprintf("%s/FindPackagesById()/$count?id='%s'", url, packageName)). + AddBasicAuth(user.Name) resp = MakeRequest(t, req, http.StatusOK) assert.Equal(t, "1", resp.Body.String()) @@ -616,8 +615,8 @@ AAAjQmxvYgAAAGm7ENm9SGxMtAFVvPUsPJTF6PbtAAAAAFcVogEJAAAAAQAAAA==`) t.Run("v3", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequest(t, "GET", fmt.Sprintf("%s/package/%s/index.json", url, packageName)) - req = AddBasicAuthHeader(req, user.Name) + req := NewRequest(t, "GET", fmt.Sprintf("%s/package/%s/index.json", url, packageName)). + AddBasicAuth(user.Name) resp := MakeRequest(t, req, http.StatusOK) var result nuget.PackageVersionsResponse @@ -631,8 +630,8 @@ AAAjQmxvYgAAAGm7ENm9SGxMtAFVvPUsPJTF6PbtAAAAAFcVogEJAAAAAQAAAA==`) t.Run("Delete", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequest(t, "DELETE", fmt.Sprintf("%s/%s/%s", url, packageName, packageVersion)) - req = AddBasicAuthHeader(req, user.Name) + req := NewRequest(t, "DELETE", fmt.Sprintf("%s/%s/%s", url, packageName, packageVersion)). + AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusNoContent) pvs, err := packages.GetVersionsByPackageType(db.DefaultContext, user.ID, packages.TypeNuGet) @@ -643,20 +642,20 @@ AAAjQmxvYgAAAGm7ENm9SGxMtAFVvPUsPJTF6PbtAAAAAFcVogEJAAAAAQAAAA==`) t.Run("DownloadNotExists", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequest(t, "GET", fmt.Sprintf("%s/package/%s/%s/%s.%s.nupkg", url, packageName, packageVersion, packageName, packageVersion)) - req = AddBasicAuthHeader(req, user.Name) + req := NewRequest(t, "GET", fmt.Sprintf("%s/package/%s/%s/%s.%s.nupkg", url, packageName, packageVersion, packageName, packageVersion)). + AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusNotFound) - req = NewRequest(t, "GET", fmt.Sprintf("%s/package/%s/%s/%s.%s.snupkg", url, packageName, packageVersion, packageName, packageVersion)) - req = AddBasicAuthHeader(req, user.Name) + req = NewRequest(t, "GET", fmt.Sprintf("%s/package/%s/%s/%s.%s.snupkg", url, packageName, packageVersion, packageName, packageVersion)). + AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusNotFound) }) t.Run("DeleteNotExists", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequest(t, "DELETE", fmt.Sprintf("%s/package/%s/%s", url, packageName, packageVersion)) - req = AddBasicAuthHeader(req, user.Name) + req := NewRequest(t, "DELETE", fmt.Sprintf("%s/package/%s/%s", url, packageName, packageVersion)). + AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusNotFound) }) } diff --git a/tests/integration/api_packages_pub_test.go b/tests/integration/api_packages_pub_test.go index 6e9d8742f47..11da894ddf3 100644 --- a/tests/integration/api_packages_pub_test.go +++ b/tests/integration/api_packages_pub_test.go @@ -66,8 +66,8 @@ description: ` + packageDescription req := NewRequest(t, "GET", uploadURL) MakeRequest(t, req, http.StatusUnauthorized) - req = NewRequest(t, "GET", uploadURL) - addTokenAuthHeader(req, token) + req = NewRequest(t, "GET", uploadURL). + AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusOK) type UploadRequest struct { @@ -88,16 +88,16 @@ description: ` + packageDescription _ = writer.Close() - req := NewRequestWithBody(t, "POST", url, body) - req.Header.Add("Content-Type", writer.FormDataContentType()) - addTokenAuthHeader(req, token) + req := NewRequestWithBody(t, "POST", url, body). + SetHeader("Content-Type", writer.FormDataContentType()). + AddTokenAuth(token) return MakeRequest(t, req, expectedStatus) } resp = uploadFile(t, result.URL, content, http.StatusNoContent) - req = NewRequest(t, "GET", resp.Header().Get("Location")) - addTokenAuthHeader(req, token) + req = NewRequest(t, "GET", resp.Header().Get("Location")). + AddTokenAuth(token) MakeRequest(t, req, http.StatusOK) pvs, err := packages.GetVersionsByPackageType(db.DefaultContext, user.ID, packages.TypePub) diff --git a/tests/integration/api_packages_pypi_test.go b/tests/integration/api_packages_pypi_test.go index 76013b79c84..a090b31e206 100644 --- a/tests/integration/api_packages_pypi_test.go +++ b/tests/integration/api_packages_pypi_test.go @@ -54,9 +54,9 @@ func TestPackagePyPI(t *testing.T) { _ = writer.Close() - req := NewRequestWithBody(t, "POST", root, body) - req.Header.Add("Content-Type", writer.FormDataContentType()) - req = AddBasicAuthHeader(req, user.Name) + req := NewRequestWithBody(t, "POST", root, body). + SetHeader("Content-Type", writer.FormDataContentType()). + AddBasicAuth(user.Name) MakeRequest(t, req, expectedStatus) } @@ -137,8 +137,8 @@ func TestPackagePyPI(t *testing.T) { defer tests.PrintCurrentTest(t)() downloadFile := func(filename string) { - req := NewRequest(t, "GET", fmt.Sprintf("%s/files/%s/%s/%s", root, packageName, packageVersion, filename)) - req = AddBasicAuthHeader(req, user.Name) + req := NewRequest(t, "GET", fmt.Sprintf("%s/files/%s/%s/%s", root, packageName, packageVersion, filename)). + AddBasicAuth(user.Name) resp := MakeRequest(t, req, http.StatusOK) assert.Equal(t, []byte(content), resp.Body.Bytes()) @@ -156,8 +156,8 @@ func TestPackagePyPI(t *testing.T) { t.Run("PackageMetadata", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequest(t, "GET", fmt.Sprintf("%s/simple/%s", root, packageName)) - req = AddBasicAuthHeader(req, user.Name) + req := NewRequest(t, "GET", fmt.Sprintf("%s/simple/%s", root, packageName)). + AddBasicAuth(user.Name) resp := MakeRequest(t, req, http.StatusOK) htmlDoc := NewHTMLParser(t, resp.Body) diff --git a/tests/integration/api_packages_rpm_test.go b/tests/integration/api_packages_rpm_test.go index 6d3b0688f2a..caf6f86381e 100644 --- a/tests/integration/api_packages_rpm_test.go +++ b/tests/integration/api_packages_rpm_test.go @@ -105,8 +105,8 @@ gpgkey=%sapi/packages/%s/rpm/repository.key`, user.Name, user.Name, setting.AppN req := NewRequestWithBody(t, "PUT", url, bytes.NewReader(content)) MakeRequest(t, req, http.StatusUnauthorized) - req = NewRequestWithBody(t, "PUT", url, bytes.NewReader(content)) - req = AddBasicAuthHeader(req, user.Name) + req = NewRequestWithBody(t, "PUT", url, bytes.NewReader(content)). + AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusCreated) pvs, err := packages.GetVersionsByPackageType(db.DefaultContext, user.ID, packages.TypeRpm) @@ -130,8 +130,8 @@ gpgkey=%sapi/packages/%s/rpm/repository.key`, user.Name, user.Name, setting.AppN assert.NoError(t, err) assert.Equal(t, int64(len(content)), pb.Size) - req = NewRequestWithBody(t, "PUT", url, bytes.NewReader(content)) - req = AddBasicAuthHeader(req, user.Name) + req = NewRequestWithBody(t, "PUT", url, bytes.NewReader(content)). + AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusConflict) }) @@ -404,16 +404,16 @@ gpgkey=%sapi/packages/%s/rpm/repository.key`, user.Name, user.Name, setting.AppN req := NewRequest(t, "DELETE", fmt.Sprintf("%s/package/%s/%s/%s", rootURL, packageName, packageVersion, packageArchitecture)) MakeRequest(t, req, http.StatusUnauthorized) - req = NewRequest(t, "DELETE", fmt.Sprintf("%s/package/%s/%s/%s", rootURL, packageName, packageVersion, packageArchitecture)) - req = AddBasicAuthHeader(req, user.Name) + req = NewRequest(t, "DELETE", fmt.Sprintf("%s/package/%s/%s/%s", rootURL, packageName, packageVersion, packageArchitecture)). + AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusNoContent) pvs, err := packages.GetVersionsByPackageType(db.DefaultContext, user.ID, packages.TypeRpm) assert.NoError(t, err) assert.Empty(t, pvs) - req = NewRequest(t, "DELETE", fmt.Sprintf("%s/package/%s/%s/%s", rootURL, packageName, packageVersion, packageArchitecture)) - req = AddBasicAuthHeader(req, user.Name) + req = NewRequest(t, "DELETE", fmt.Sprintf("%s/package/%s/%s/%s", rootURL, packageName, packageVersion, packageArchitecture)). + AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusNotFound) }) } diff --git a/tests/integration/api_packages_rubygems_test.go b/tests/integration/api_packages_rubygems_test.go index a3df143209a..5670731c492 100644 --- a/tests/integration/api_packages_rubygems_test.go +++ b/tests/integration/api_packages_rubygems_test.go @@ -115,8 +115,8 @@ AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA`) root := fmt.Sprintf("/api/packages/%s/rubygems", user.Name) uploadFile := func(t *testing.T, expectedStatus int) { - req := NewRequestWithBody(t, "POST", fmt.Sprintf("%s/api/v1/gems", root), bytes.NewReader(gemContent)) - req = AddBasicAuthHeader(req, user.Name) + req := NewRequestWithBody(t, "POST", fmt.Sprintf("%s/api/v1/gems", root), bytes.NewReader(gemContent)). + AddBasicAuth(user.Name) MakeRequest(t, req, expectedStatus) } @@ -156,8 +156,8 @@ AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA`) t.Run("Download", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequest(t, "GET", fmt.Sprintf("%s/gems/%s", root, packageFilename)) - req = AddBasicAuthHeader(req, user.Name) + req := NewRequest(t, "GET", fmt.Sprintf("%s/gems/%s", root, packageFilename)). + AddBasicAuth(user.Name) resp := MakeRequest(t, req, http.StatusOK) assert.Equal(t, gemContent, resp.Body.Bytes()) @@ -171,8 +171,8 @@ AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA`) t.Run("DownloadGemspec", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequest(t, "GET", fmt.Sprintf("%s/quick/Marshal.4.8/%sspec.rz", root, packageFilename)) - req = AddBasicAuthHeader(req, user.Name) + req := NewRequest(t, "GET", fmt.Sprintf("%s/quick/Marshal.4.8/%sspec.rz", root, packageFilename)). + AddBasicAuth(user.Name) resp := MakeRequest(t, req, http.StatusOK) b, _ := base64.StdEncoding.DecodeString(`eJxi4Si1EndPzbWyCi5ITc5My0xOLMnMz2M8zMIRLeGpxGWsZ6RnzGbF5hqSyempxJWeWZKayGbN @@ -191,8 +191,8 @@ gAAAAP//MS06Gw==`) defer tests.PrintCurrentTest(t)() enumeratePackages := func(t *testing.T, endpoint string, expectedContent []byte) { - req := NewRequest(t, "GET", fmt.Sprintf("%s/%s", root, endpoint)) - req = AddBasicAuthHeader(req, user.Name) + req := NewRequest(t, "GET", fmt.Sprintf("%s/%s", root, endpoint)). + AddBasicAuth(user.Name) resp := MakeRequest(t, req, http.StatusOK) assert.Equal(t, expectedContent, resp.Body.Bytes()) @@ -215,9 +215,9 @@ gAAAAP//MS06Gw==`) writer.WriteField("version", packageVersion) writer.Close() - req := NewRequestWithBody(t, "DELETE", fmt.Sprintf("%s/api/v1/gems/yank", root), &body) - req.Header.Add("Content-Type", writer.FormDataContentType()) - req = AddBasicAuthHeader(req, user.Name) + req := NewRequestWithBody(t, "DELETE", fmt.Sprintf("%s/api/v1/gems/yank", root), &body). + SetHeader("Content-Type", writer.FormDataContentType()). + AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusOK) pvs, err := packages.GetVersionsByPackageType(db.DefaultContext, user.ID, packages.TypeRubyGems) diff --git a/tests/integration/api_packages_swift_test.go b/tests/integration/api_packages_swift_test.go index a3035ea6048..7d4ff954e22 100644 --- a/tests/integration/api_packages_swift_test.go +++ b/tests/integration/api_packages_swift_test.go @@ -62,9 +62,9 @@ func TestPackageSwift(t *testing.T) { assert.Equal(t, "application/problem+json", resp.Header().Get("Content-Type")) } - req := NewRequestWithBody(t, "PUT", url+"/scope/package/1.0.0", strings.NewReader("")) - req = AddBasicAuthHeader(req, user.Name) - req.Header.Add("Accept", "application/unknown") + req := NewRequestWithBody(t, "PUT", url+"/scope/package/1.0.0", strings.NewReader("")). + AddBasicAuth(user.Name). + SetHeader("Accept", "application/unknown") resp := MakeRequest(t, req, http.StatusBadRequest) assert.Equal(t, "1", resp.Header().Get("Content-Version")) @@ -87,10 +87,10 @@ func TestPackageSwift(t *testing.T) { mpw.Close() - req := NewRequestWithBody(t, "PUT", url, &body) - req.Header.Add("Content-Type", mpw.FormDataContentType()) - req.Header.Add("Accept", swift_router.AcceptJSON) - req = AddBasicAuthHeader(req, user.Name) + req := NewRequestWithBody(t, "PUT", url, &body). + SetHeader("Content-Type", mpw.FormDataContentType()). + SetHeader("Accept", swift_router.AcceptJSON). + AddBasicAuth(user.Name) MakeRequest(t, req, expectedStatus) } @@ -106,8 +106,8 @@ func TestPackageSwift(t *testing.T) { } for _, triple := range []string{"/sc_ope/package/1.0.0", "/scope/pack~age/1.0.0", "/scope/package/1_0.0"} { - req := NewRequestWithBody(t, "PUT", url+triple, bytes.NewReader([]byte{})) - req = AddBasicAuthHeader(req, user.Name) + req := NewRequestWithBody(t, "PUT", url+triple, bytes.NewReader([]byte{})). + AddBasicAuth(user.Name) resp := MakeRequest(t, req, http.StatusBadRequest) assert.Equal(t, "1", resp.Header().Get("Content-Version")) @@ -168,9 +168,9 @@ func TestPackageSwift(t *testing.T) { t.Run("Download", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequest(t, "GET", fmt.Sprintf("%s/%s/%s/%s.zip", url, packageScope, packageName, packageVersion)) - req = AddBasicAuthHeader(req, user.Name) - req.Header.Add("Accept", swift_router.AcceptZip) + req := NewRequest(t, "GET", fmt.Sprintf("%s/%s/%s/%s.zip", url, packageScope, packageName, packageVersion)). + AddBasicAuth(user.Name). + SetHeader("Accept", swift_router.AcceptZip) resp := MakeRequest(t, req, http.StatusOK) assert.Equal(t, "1", resp.Header().Get("Content-Version")) @@ -188,9 +188,9 @@ func TestPackageSwift(t *testing.T) { t.Run("EnumeratePackageVersions", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequest(t, "GET", fmt.Sprintf("%s/%s/%s", url, packageScope, packageName)) - req = AddBasicAuthHeader(req, user.Name) - req.Header.Add("Accept", swift_router.AcceptJSON) + req := NewRequest(t, "GET", fmt.Sprintf("%s/%s/%s", url, packageScope, packageName)). + AddBasicAuth(user.Name). + SetHeader("Accept", swift_router.AcceptJSON) resp := MakeRequest(t, req, http.StatusOK) versionURL := setting.AppURL + url[1:] + fmt.Sprintf("/%s/%s/%s", packageScope, packageName, packageVersion) @@ -207,8 +207,8 @@ func TestPackageSwift(t *testing.T) { assert.Contains(t, result.Releases, packageVersion) assert.Equal(t, versionURL, result.Releases[packageVersion].URL) - req = NewRequest(t, "GET", fmt.Sprintf("%s/%s/%s.json", url, packageScope, packageName)) - req = AddBasicAuthHeader(req, user.Name) + req = NewRequest(t, "GET", fmt.Sprintf("%s/%s/%s.json", url, packageScope, packageName)). + AddBasicAuth(user.Name) resp = MakeRequest(t, req, http.StatusOK) assert.Equal(t, body, resp.Body.String()) @@ -217,9 +217,9 @@ func TestPackageSwift(t *testing.T) { t.Run("PackageVersionMetadata", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequest(t, "GET", fmt.Sprintf("%s/%s/%s/%s", url, packageScope, packageName, packageVersion)) - req = AddBasicAuthHeader(req, user.Name) - req.Header.Add("Accept", swift_router.AcceptJSON) + req := NewRequest(t, "GET", fmt.Sprintf("%s/%s/%s/%s", url, packageScope, packageName, packageVersion)). + AddBasicAuth(user.Name). + SetHeader("Accept", swift_router.AcceptJSON) resp := MakeRequest(t, req, http.StatusOK) assert.Equal(t, "1", resp.Header().Get("Content-Version")) @@ -249,8 +249,8 @@ func TestPackageSwift(t *testing.T) { assert.Equal(t, "Swift", result.Metadata.ProgrammingLanguage.Name) assert.Equal(t, packageAuthor, result.Metadata.Author.GivenName) - req = NewRequest(t, "GET", fmt.Sprintf("%s/%s/%s/%s.json", url, packageScope, packageName, packageVersion)) - req = AddBasicAuthHeader(req, user.Name) + req = NewRequest(t, "GET", fmt.Sprintf("%s/%s/%s/%s.json", url, packageScope, packageName, packageVersion)). + AddBasicAuth(user.Name) resp = MakeRequest(t, req, http.StatusOK) assert.Equal(t, body, resp.Body.String()) @@ -262,9 +262,9 @@ func TestPackageSwift(t *testing.T) { t.Run("Default", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequest(t, "GET", manifestURL) - req = AddBasicAuthHeader(req, user.Name) - req.Header.Add("Accept", swift_router.AcceptSwift) + req := NewRequest(t, "GET", manifestURL). + AddBasicAuth(user.Name). + SetHeader("Accept", swift_router.AcceptSwift) resp := MakeRequest(t, req, http.StatusOK) assert.Equal(t, "1", resp.Header().Get("Content-Version")) @@ -275,24 +275,24 @@ func TestPackageSwift(t *testing.T) { t.Run("DifferentVersion", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequest(t, "GET", manifestURL+"?swift-version=5.6") - req = AddBasicAuthHeader(req, user.Name) + req := NewRequest(t, "GET", manifestURL+"?swift-version=5.6"). + AddBasicAuth(user.Name) resp := MakeRequest(t, req, http.StatusOK) assert.Equal(t, "1", resp.Header().Get("Content-Version")) assert.Equal(t, "text/x-swift", resp.Header().Get("Content-Type")) assert.Equal(t, contentManifest2, resp.Body.String()) - req = NewRequest(t, "GET", manifestURL+"?swift-version=5.6.0") - req = AddBasicAuthHeader(req, user.Name) + req = NewRequest(t, "GET", manifestURL+"?swift-version=5.6.0"). + AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusOK) }) t.Run("Redirect", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequest(t, "GET", manifestURL+"?swift-version=1.0") - req = AddBasicAuthHeader(req, user.Name) + req := NewRequest(t, "GET", manifestURL+"?swift-version=1.0"). + AddBasicAuth(user.Name) resp := MakeRequest(t, req, http.StatusSeeOther) assert.Equal(t, "1", resp.Header().Get("Content-Version")) @@ -303,8 +303,8 @@ func TestPackageSwift(t *testing.T) { t.Run("LookupPackageIdentifiers", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequest(t, "GET", url+"/identifiers") - req.Header.Add("Accept", swift_router.AcceptJSON) + req := NewRequest(t, "GET", url+"/identifiers"). + SetHeader("Accept", swift_router.AcceptJSON) resp := MakeRequest(t, req, http.StatusBadRequest) assert.Equal(t, "1", resp.Header().Get("Content-Version")) @@ -313,8 +313,8 @@ func TestPackageSwift(t *testing.T) { req = NewRequest(t, "GET", url+"/identifiers?url=https://unknown.host/") MakeRequest(t, req, http.StatusNotFound) - req = NewRequest(t, "GET", url+"/identifiers?url="+packageRepositoryURL) - req.Header.Add("Accept", swift_router.AcceptJSON) + req = NewRequest(t, "GET", url+"/identifiers?url="+packageRepositoryURL). + SetHeader("Accept", swift_router.AcceptJSON) resp = MakeRequest(t, req, http.StatusOK) var result *swift_router.LookupPackageIdentifiersResponse diff --git a/tests/integration/api_packages_test.go b/tests/integration/api_packages_test.go index e530b2c1ad7..8c981566b60 100644 --- a/tests/integration/api_packages_test.go +++ b/tests/integration/api_packages_test.go @@ -41,14 +41,15 @@ func TestPackageAPI(t *testing.T) { filename := "file.bin" url := fmt.Sprintf("/api/packages/%s/generic/%s/%s/%s", user.Name, packageName, packageVersion, filename) - req := NewRequestWithBody(t, "PUT", url, bytes.NewReader([]byte{})) - AddBasicAuthHeader(req, user.Name) + req := NewRequestWithBody(t, "PUT", url, bytes.NewReader([]byte{})). + AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusCreated) t.Run("ListPackages", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/packages/%s?token=%s", user.Name, tokenReadPackage)) + req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/packages/%s", user.Name)). + AddTokenAuth(tokenReadPackage) resp := MakeRequest(t, req, http.StatusOK) var apiPackages []*api.Package @@ -65,10 +66,12 @@ func TestPackageAPI(t *testing.T) { t.Run("GetPackage", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/packages/%s/dummy/%s/%s?token=%s", user.Name, packageName, packageVersion, tokenReadPackage)) + req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/packages/%s/dummy/%s/%s", user.Name, packageName, packageVersion)). + AddTokenAuth(tokenReadPackage) MakeRequest(t, req, http.StatusNotFound) - req = NewRequest(t, "GET", fmt.Sprintf("/api/v1/packages/%s/generic/%s/%s?token=%s", user.Name, packageName, packageVersion, tokenReadPackage)) + req = NewRequest(t, "GET", fmt.Sprintf("/api/v1/packages/%s/generic/%s/%s", user.Name, packageName, packageVersion)). + AddTokenAuth(tokenReadPackage) resp := MakeRequest(t, req, http.StatusOK) var p *api.Package @@ -87,7 +90,8 @@ func TestPackageAPI(t *testing.T) { assert.NoError(t, err) // no repository link - req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/packages/%s/generic/%s/%s?token=%s", user.Name, packageName, packageVersion, tokenReadPackage)) + req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/packages/%s/generic/%s/%s", user.Name, packageName, packageVersion)). + AddTokenAuth(tokenReadPackage) resp := MakeRequest(t, req, http.StatusOK) var ap1 *api.Package @@ -97,7 +101,8 @@ func TestPackageAPI(t *testing.T) { // link to public repository assert.NoError(t, packages_model.SetRepositoryLink(db.DefaultContext, p.ID, 1)) - req = NewRequest(t, "GET", fmt.Sprintf("/api/v1/packages/%s/generic/%s/%s?token=%s", user.Name, packageName, packageVersion, tokenReadPackage)) + req = NewRequest(t, "GET", fmt.Sprintf("/api/v1/packages/%s/generic/%s/%s", user.Name, packageName, packageVersion)). + AddTokenAuth(tokenReadPackage) resp = MakeRequest(t, req, http.StatusOK) var ap2 *api.Package @@ -108,7 +113,8 @@ func TestPackageAPI(t *testing.T) { // link to private repository assert.NoError(t, packages_model.SetRepositoryLink(db.DefaultContext, p.ID, 2)) - req = NewRequest(t, "GET", fmt.Sprintf("/api/v1/packages/%s/generic/%s/%s?token=%s", user.Name, packageName, packageVersion, tokenReadPackage)) + req = NewRequest(t, "GET", fmt.Sprintf("/api/v1/packages/%s/generic/%s/%s", user.Name, packageName, packageVersion)). + AddTokenAuth(tokenReadPackage) resp = MakeRequest(t, req, http.StatusOK) var ap3 *api.Package @@ -122,10 +128,12 @@ func TestPackageAPI(t *testing.T) { t.Run("ListPackageFiles", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/packages/%s/dummy/%s/%s/files?token=%s", user.Name, packageName, packageVersion, tokenReadPackage)) + req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/packages/%s/dummy/%s/%s/files", user.Name, packageName, packageVersion)). + AddTokenAuth(tokenReadPackage) MakeRequest(t, req, http.StatusNotFound) - req = NewRequest(t, "GET", fmt.Sprintf("/api/v1/packages/%s/generic/%s/%s/files?token=%s", user.Name, packageName, packageVersion, tokenReadPackage)) + req = NewRequest(t, "GET", fmt.Sprintf("/api/v1/packages/%s/generic/%s/%s/files", user.Name, packageName, packageVersion)). + AddTokenAuth(tokenReadPackage) resp := MakeRequest(t, req, http.StatusOK) var files []*api.PackageFile @@ -143,10 +151,12 @@ func TestPackageAPI(t *testing.T) { t.Run("DeletePackage", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequest(t, "DELETE", fmt.Sprintf("/api/v1/packages/%s/dummy/%s/%s?token=%s", user.Name, packageName, packageVersion, tokenDeletePackage)) + req := NewRequest(t, "DELETE", fmt.Sprintf("/api/v1/packages/%s/dummy/%s/%s", user.Name, packageName, packageVersion)). + AddTokenAuth(tokenDeletePackage) MakeRequest(t, req, http.StatusNotFound) - req = NewRequest(t, "DELETE", fmt.Sprintf("/api/v1/packages/%s/generic/%s/%s?token=%s", user.Name, packageName, packageVersion, tokenDeletePackage)) + req = NewRequest(t, "DELETE", fmt.Sprintf("/api/v1/packages/%s/generic/%s/%s", user.Name, packageName, packageVersion)). + AddTokenAuth(tokenDeletePackage) MakeRequest(t, req, http.StatusNoContent) }) } @@ -170,7 +180,7 @@ func TestPackageAccess(t *testing.T) { url := fmt.Sprintf("/api/packages/%s/generic/test-package/1.0/%s.bin", owner.Name, filename) req := NewRequestWithBody(t, "PUT", url, bytes.NewReader([]byte{1})) if doer != nil { - AddBasicAuthHeader(req, doer.Name) + req.AddBasicAuth(doer.Name) } MakeRequest(t, req, expectedStatus) } @@ -179,7 +189,7 @@ func TestPackageAccess(t *testing.T) { url := fmt.Sprintf("/api/packages/%s/generic/test-package/1.0/admin.bin", owner.Name) req := NewRequest(t, "GET", url) if doer != nil { - AddBasicAuthHeader(req, doer.Name) + req.AddBasicAuth(doer.Name) } MakeRequest(t, req, expectedStatus) } @@ -374,7 +384,8 @@ func TestPackageAccess(t *testing.T) { {limitedOrgNoMember, http.StatusOK}, {publicOrgNoMember, http.StatusOK}, } { - req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/packages/%s?token=%s", target.Owner.Name, tokenReadPackage)) + req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/packages/%s", target.Owner.Name)). + AddTokenAuth(tokenReadPackage) MakeRequest(t, req, target.ExpectedStatus) } }) @@ -396,8 +407,8 @@ func TestPackageQuota(t *testing.T) { uploadPackage := func(doer *user_model.User, version string, expectedStatus int) { url := fmt.Sprintf("/api/packages/%s/generic/test-package/%s/file.bin", user.Name, version) - req := NewRequestWithBody(t, "PUT", url, bytes.NewReader([]byte{1})) - AddBasicAuthHeader(req, doer.Name) + req := NewRequestWithBody(t, "PUT", url, bytes.NewReader([]byte{1})). + AddBasicAuth(doer.Name) MakeRequest(t, req, expectedStatus) } @@ -424,8 +435,8 @@ func TestPackageQuota(t *testing.T) { uploadBlob := func(doer *user_model.User, data string, expectedStatus int) { url := fmt.Sprintf("/v2/%s/quota-test/blobs/uploads?digest=sha256:%x", user.Name, sha256.Sum256([]byte(data))) - req := NewRequestWithBody(t, "POST", url, strings.NewReader(data)) - AddBasicAuthHeader(req, doer.Name) + req := NewRequestWithBody(t, "POST", url, strings.NewReader(data)). + AddBasicAuth(doer.Name) MakeRequest(t, req, expectedStatus) } @@ -454,18 +465,18 @@ func TestPackageCleanup(t *testing.T) { // Upload and delete a generic package and upload a container blob data, _ := util.CryptoRandomBytes(5) url := fmt.Sprintf("/api/packages/%s/generic/cleanup-test/1.1.1/file.bin", user.Name) - req := NewRequestWithBody(t, "PUT", url, bytes.NewReader(data)) - AddBasicAuthHeader(req, user.Name) + req := NewRequestWithBody(t, "PUT", url, bytes.NewReader(data)). + AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusCreated) - req = NewRequest(t, "DELETE", url) - AddBasicAuthHeader(req, user.Name) + req = NewRequest(t, "DELETE", url). + AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusNoContent) data, _ = util.CryptoRandomBytes(5) url = fmt.Sprintf("/v2/%s/cleanup-test/blobs/uploads?digest=sha256:%x", user.Name, sha256.Sum256(data)) - req = NewRequestWithBody(t, "POST", url, bytes.NewReader(data)) - AddBasicAuthHeader(req, user.Name) + req = NewRequestWithBody(t, "POST", url, bytes.NewReader(data)). + AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusCreated) pbs, err := packages_model.FindExpiredUnreferencedBlobs(db.DefaultContext, duration) @@ -592,8 +603,8 @@ func TestPackageCleanup(t *testing.T) { for _, v := range c.Versions { url := fmt.Sprintf("/api/packages/%s/generic/package/%s/file.bin", user.Name, v.Version) - req := NewRequestWithBody(t, "PUT", url, bytes.NewReader([]byte{1})) - AddBasicAuthHeader(req, user.Name) + req := NewRequestWithBody(t, "PUT", url, bytes.NewReader([]byte{1})). + AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusCreated) if v.Created != 0 { diff --git a/tests/integration/api_packages_vagrant_test.go b/tests/integration/api_packages_vagrant_test.go index cbfc362f32d..a5e954f3a27 100644 --- a/tests/integration/api_packages_vagrant_test.go +++ b/tests/integration/api_packages_vagrant_test.go @@ -64,8 +64,8 @@ func TestPackageVagrant(t *testing.T) { req := NewRequest(t, "GET", authenticateURL) MakeRequest(t, req, http.StatusUnauthorized) - req = NewRequest(t, "GET", authenticateURL) - addTokenAuthHeader(req, token) + req = NewRequest(t, "GET", authenticateURL). + AddTokenAuth(token) MakeRequest(t, req, http.StatusOK) }) @@ -82,8 +82,8 @@ func TestPackageVagrant(t *testing.T) { req = NewRequestWithBody(t, "PUT", uploadURL, bytes.NewReader(content)) MakeRequest(t, req, http.StatusUnauthorized) - req = NewRequestWithBody(t, "PUT", uploadURL, bytes.NewReader(content)) - addTokenAuthHeader(req, token) + req = NewRequestWithBody(t, "PUT", uploadURL, bytes.NewReader(content)). + AddTokenAuth(token) MakeRequest(t, req, http.StatusCreated) req = NewRequest(t, "HEAD", boxURL) @@ -111,8 +111,8 @@ func TestPackageVagrant(t *testing.T) { assert.NoError(t, err) assert.Equal(t, int64(len(content)), pb.Size) - req = NewRequestWithBody(t, "PUT", uploadURL, bytes.NewReader(content)) - addTokenAuthHeader(req, token) + req = NewRequestWithBody(t, "PUT", uploadURL, bytes.NewReader(content)). + AddTokenAuth(token) MakeRequest(t, req, http.StatusConflict) }) diff --git a/tests/integration/api_pull_review_test.go b/tests/integration/api_pull_review_test.go index 0e9bace44c9..daa136b21e4 100644 --- a/tests/integration/api_pull_review_test.go +++ b/tests/integration/api_pull_review_test.go @@ -29,7 +29,8 @@ func TestAPIPullReview(t *testing.T) { // test ListPullReviews session := loginUser(t, "user2") token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteRepository) - req := NewRequestf(t, http.MethodGet, "/api/v1/repos/%s/%s/pulls/%d/reviews?token=%s", repo.OwnerName, repo.Name, pullIssue.Index, token) + req := NewRequestf(t, http.MethodGet, "/api/v1/repos/%s/%s/pulls/%d/reviews", repo.OwnerName, repo.Name, pullIssue.Index). + AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusOK) var reviews []*api.PullReview @@ -54,20 +55,23 @@ func TestAPIPullReview(t *testing.T) { assert.True(t, reviews[5].Official) // test GetPullReview - req = NewRequestf(t, http.MethodGet, "/api/v1/repos/%s/%s/pulls/%d/reviews/%d?token=%s", repo.OwnerName, repo.Name, pullIssue.Index, reviews[3].ID, token) + req = NewRequestf(t, http.MethodGet, "/api/v1/repos/%s/%s/pulls/%d/reviews/%d", repo.OwnerName, repo.Name, pullIssue.Index, reviews[3].ID). + AddTokenAuth(token) resp = MakeRequest(t, req, http.StatusOK) var review api.PullReview DecodeJSON(t, resp, &review) assert.EqualValues(t, *reviews[3], review) - req = NewRequestf(t, "GET", "/api/v1/repos/%s/%s/pulls/%d/reviews/%d?token=%s", repo.OwnerName, repo.Name, pullIssue.Index, reviews[5].ID, token) + req = NewRequestf(t, "GET", "/api/v1/repos/%s/%s/pulls/%d/reviews/%d", repo.OwnerName, repo.Name, pullIssue.Index, reviews[5].ID). + AddTokenAuth(token) resp = MakeRequest(t, req, http.StatusOK) DecodeJSON(t, resp, &review) assert.EqualValues(t, *reviews[5], review) // test GetPullReviewComments comment := unittest.AssertExistsAndLoadBean(t, &issues_model.Comment{ID: 7}) - req = NewRequestf(t, http.MethodGet, "/api/v1/repos/%s/%s/pulls/%d/reviews/%d/comments?token=%s", repo.OwnerName, repo.Name, pullIssue.Index, 10, token) + req = NewRequestf(t, http.MethodGet, "/api/v1/repos/%s/%s/pulls/%d/reviews/%d/comments", repo.OwnerName, repo.Name, pullIssue.Index, 10). + AddTokenAuth(token) resp = MakeRequest(t, req, http.StatusOK) var reviewComments []*api.PullReviewComment DecodeJSON(t, resp, &reviewComments) @@ -79,7 +83,7 @@ func TestAPIPullReview(t *testing.T) { assert.EqualValues(t, comment.HTMLURL(db.DefaultContext), reviewComments[0].HTMLURL) // test CreatePullReview - req = NewRequestWithJSON(t, http.MethodPost, fmt.Sprintf("/api/v1/repos/%s/%s/pulls/%d/reviews?token=%s", repo.OwnerName, repo.Name, pullIssue.Index, token), &api.CreatePullReviewOptions{ + req = NewRequestWithJSON(t, http.MethodPost, fmt.Sprintf("/api/v1/repos/%s/%s/pulls/%d/reviews", repo.OwnerName, repo.Name, pullIssue.Index), &api.CreatePullReviewOptions{ Body: "body1", // Event: "" # will result in PENDING Comments: []api.CreatePullReviewComment{ @@ -100,7 +104,7 @@ func TestAPIPullReview(t *testing.T) { NewLineNum: 1, }, }, - }) + }).AddTokenAuth(token) resp = MakeRequest(t, req, http.StatusOK) DecodeJSON(t, resp, &review) assert.EqualValues(t, 6, review.ID) @@ -108,10 +112,10 @@ func TestAPIPullReview(t *testing.T) { assert.EqualValues(t, 3, review.CodeCommentsCount) // test SubmitPullReview - req = NewRequestWithJSON(t, http.MethodPost, fmt.Sprintf("/api/v1/repos/%s/%s/pulls/%d/reviews/%d?token=%s", repo.OwnerName, repo.Name, pullIssue.Index, review.ID, token), &api.SubmitPullReviewOptions{ + req = NewRequestWithJSON(t, http.MethodPost, fmt.Sprintf("/api/v1/repos/%s/%s/pulls/%d/reviews/%d", repo.OwnerName, repo.Name, pullIssue.Index, review.ID), &api.SubmitPullReviewOptions{ Event: "APPROVED", Body: "just two nits", - }) + }).AddTokenAuth(token) resp = MakeRequest(t, req, http.StatusOK) DecodeJSON(t, resp, &review) assert.EqualValues(t, 6, review.ID) @@ -119,35 +123,37 @@ func TestAPIPullReview(t *testing.T) { assert.EqualValues(t, 3, review.CodeCommentsCount) // test dismiss review - req = NewRequestWithJSON(t, http.MethodPost, fmt.Sprintf("/api/v1/repos/%s/%s/pulls/%d/reviews/%d/dismissals?token=%s", repo.OwnerName, repo.Name, pullIssue.Index, review.ID, token), &api.DismissPullReviewOptions{ + req = NewRequestWithJSON(t, http.MethodPost, fmt.Sprintf("/api/v1/repos/%s/%s/pulls/%d/reviews/%d/dismissals", repo.OwnerName, repo.Name, pullIssue.Index, review.ID), &api.DismissPullReviewOptions{ Message: "test", - }) + }).AddTokenAuth(token) resp = MakeRequest(t, req, http.StatusOK) DecodeJSON(t, resp, &review) assert.EqualValues(t, 6, review.ID) assert.True(t, review.Dismissed) // test dismiss review - req = NewRequest(t, http.MethodPost, fmt.Sprintf("/api/v1/repos/%s/%s/pulls/%d/reviews/%d/undismissals?token=%s", repo.OwnerName, repo.Name, pullIssue.Index, review.ID, token)) + req = NewRequest(t, http.MethodPost, fmt.Sprintf("/api/v1/repos/%s/%s/pulls/%d/reviews/%d/undismissals", repo.OwnerName, repo.Name, pullIssue.Index, review.ID)). + AddTokenAuth(token) resp = MakeRequest(t, req, http.StatusOK) DecodeJSON(t, resp, &review) assert.EqualValues(t, 6, review.ID) assert.False(t, review.Dismissed) // test DeletePullReview - req = NewRequestWithJSON(t, http.MethodPost, fmt.Sprintf("/api/v1/repos/%s/%s/pulls/%d/reviews?token=%s", repo.OwnerName, repo.Name, pullIssue.Index, token), &api.CreatePullReviewOptions{ + req = NewRequestWithJSON(t, http.MethodPost, fmt.Sprintf("/api/v1/repos/%s/%s/pulls/%d/reviews", repo.OwnerName, repo.Name, pullIssue.Index), &api.CreatePullReviewOptions{ Body: "just a comment", Event: "COMMENT", - }) + }).AddTokenAuth(token) resp = MakeRequest(t, req, http.StatusOK) DecodeJSON(t, resp, &review) assert.EqualValues(t, "COMMENT", review.State) assert.EqualValues(t, 0, review.CodeCommentsCount) - req = NewRequestf(t, http.MethodDelete, "/api/v1/repos/%s/%s/pulls/%d/reviews/%d?token=%s", repo.OwnerName, repo.Name, pullIssue.Index, review.ID, token) + req = NewRequestf(t, http.MethodDelete, "/api/v1/repos/%s/%s/pulls/%d/reviews/%d", repo.OwnerName, repo.Name, pullIssue.Index, review.ID). + AddTokenAuth(token) MakeRequest(t, req, http.StatusNoContent) // test CreatePullReview Comment without body but with comments - req = NewRequestWithJSON(t, http.MethodPost, fmt.Sprintf("/api/v1/repos/%s/%s/pulls/%d/reviews?token=%s", repo.OwnerName, repo.Name, pullIssue.Index, token), &api.CreatePullReviewOptions{ + req = NewRequestWithJSON(t, http.MethodPost, fmt.Sprintf("/api/v1/repos/%s/%s/pulls/%d/reviews", repo.OwnerName, repo.Name, pullIssue.Index), &api.CreatePullReviewOptions{ // Body: "", Event: "COMMENT", Comments: []api.CreatePullReviewComment{ @@ -163,7 +169,7 @@ func TestAPIPullReview(t *testing.T) { NewLineNum: 0, }, }, - }) + }).AddTokenAuth(token) var commentReview api.PullReview resp = MakeRequest(t, req, http.StatusOK) @@ -175,11 +181,11 @@ func TestAPIPullReview(t *testing.T) { // test CreatePullReview Comment with body but without comments commentBody := "This is a body of the comment." - req = NewRequestWithJSON(t, http.MethodPost, fmt.Sprintf("/api/v1/repos/%s/%s/pulls/%d/reviews?token=%s", repo.OwnerName, repo.Name, pullIssue.Index, token), &api.CreatePullReviewOptions{ + req = NewRequestWithJSON(t, http.MethodPost, fmt.Sprintf("/api/v1/repos/%s/%s/pulls/%d/reviews", repo.OwnerName, repo.Name, pullIssue.Index), &api.CreatePullReviewOptions{ Body: commentBody, Event: "COMMENT", Comments: []api.CreatePullReviewComment{}, - }) + }).AddTokenAuth(token) resp = MakeRequest(t, req, http.StatusOK) DecodeJSON(t, resp, &commentReview) @@ -189,11 +195,11 @@ func TestAPIPullReview(t *testing.T) { assert.False(t, commentReview.Dismissed) // test CreatePullReview Comment without body and no comments - req = NewRequestWithJSON(t, http.MethodPost, fmt.Sprintf("/api/v1/repos/%s/%s/pulls/%d/reviews?token=%s", repo.OwnerName, repo.Name, pullIssue.Index, token), &api.CreatePullReviewOptions{ + req = NewRequestWithJSON(t, http.MethodPost, fmt.Sprintf("/api/v1/repos/%s/%s/pulls/%d/reviews", repo.OwnerName, repo.Name, pullIssue.Index), &api.CreatePullReviewOptions{ Body: "", Event: "COMMENT", Comments: []api.CreatePullReviewComment{}, - }) + }).AddTokenAuth(token) resp = MakeRequest(t, req, http.StatusUnprocessableEntity) errMap := make(map[string]any) json.Unmarshal(resp.Body.Bytes(), &errMap) @@ -205,7 +211,8 @@ func TestAPIPullReview(t *testing.T) { assert.NoError(t, pullIssue12.LoadAttributes(db.DefaultContext)) repo3 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: pullIssue12.RepoID}) - req = NewRequestf(t, http.MethodGet, "/api/v1/repos/%s/%s/pulls/%d/reviews?token=%s", repo3.OwnerName, repo3.Name, pullIssue12.Index, token) + req = NewRequestf(t, http.MethodGet, "/api/v1/repos/%s/%s/pulls/%d/reviews", repo3.OwnerName, repo3.Name, pullIssue12.Index). + AddTokenAuth(token) resp = MakeRequest(t, req, http.StatusOK) DecodeJSON(t, resp, &reviews) assert.EqualValues(t, 11, reviews[0].ID) @@ -232,41 +239,41 @@ func TestAPIPullReviewRequest(t *testing.T) { // Test add Review Request session := loginUser(t, "user2") token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteRepository) - req := NewRequestWithJSON(t, http.MethodPost, fmt.Sprintf("/api/v1/repos/%s/%s/pulls/%d/requested_reviewers?token=%s", repo.OwnerName, repo.Name, pullIssue.Index, token), &api.PullReviewRequestOptions{ + req := NewRequestWithJSON(t, http.MethodPost, fmt.Sprintf("/api/v1/repos/%s/%s/pulls/%d/requested_reviewers", repo.OwnerName, repo.Name, pullIssue.Index), &api.PullReviewRequestOptions{ Reviewers: []string{"user4@example.com", "user8"}, - }) + }).AddTokenAuth(token) MakeRequest(t, req, http.StatusCreated) // poster of pr can't be reviewer - req = NewRequestWithJSON(t, http.MethodPost, fmt.Sprintf("/api/v1/repos/%s/%s/pulls/%d/requested_reviewers?token=%s", repo.OwnerName, repo.Name, pullIssue.Index, token), &api.PullReviewRequestOptions{ + req = NewRequestWithJSON(t, http.MethodPost, fmt.Sprintf("/api/v1/repos/%s/%s/pulls/%d/requested_reviewers", repo.OwnerName, repo.Name, pullIssue.Index), &api.PullReviewRequestOptions{ Reviewers: []string{"user1"}, - }) + }).AddTokenAuth(token) MakeRequest(t, req, http.StatusUnprocessableEntity) // test user not exist - req = NewRequestWithJSON(t, http.MethodPost, fmt.Sprintf("/api/v1/repos/%s/%s/pulls/%d/requested_reviewers?token=%s", repo.OwnerName, repo.Name, pullIssue.Index, token), &api.PullReviewRequestOptions{ + req = NewRequestWithJSON(t, http.MethodPost, fmt.Sprintf("/api/v1/repos/%s/%s/pulls/%d/requested_reviewers", repo.OwnerName, repo.Name, pullIssue.Index), &api.PullReviewRequestOptions{ Reviewers: []string{"testOther"}, - }) + }).AddTokenAuth(token) MakeRequest(t, req, http.StatusNotFound) // Test Remove Review Request session2 := loginUser(t, "user4") token2 := getTokenForLoggedInUser(t, session2, auth_model.AccessTokenScopeWriteRepository) - req = NewRequestWithJSON(t, http.MethodDelete, fmt.Sprintf("/api/v1/repos/%s/%s/pulls/%d/requested_reviewers?token=%s", repo.OwnerName, repo.Name, pullIssue.Index, token2), &api.PullReviewRequestOptions{ + req = NewRequestWithJSON(t, http.MethodDelete, fmt.Sprintf("/api/v1/repos/%s/%s/pulls/%d/requested_reviewers", repo.OwnerName, repo.Name, pullIssue.Index), &api.PullReviewRequestOptions{ Reviewers: []string{"user4"}, - }) + }).AddTokenAuth(token2) MakeRequest(t, req, http.StatusNoContent) // doer is not admin - req = NewRequestWithJSON(t, http.MethodDelete, fmt.Sprintf("/api/v1/repos/%s/%s/pulls/%d/requested_reviewers?token=%s", repo.OwnerName, repo.Name, pullIssue.Index, token2), &api.PullReviewRequestOptions{ + req = NewRequestWithJSON(t, http.MethodDelete, fmt.Sprintf("/api/v1/repos/%s/%s/pulls/%d/requested_reviewers", repo.OwnerName, repo.Name, pullIssue.Index), &api.PullReviewRequestOptions{ Reviewers: []string{"user8"}, - }) + }).AddTokenAuth(token2) MakeRequest(t, req, http.StatusUnprocessableEntity) - req = NewRequestWithJSON(t, http.MethodDelete, fmt.Sprintf("/api/v1/repos/%s/%s/pulls/%d/requested_reviewers?token=%s", repo.OwnerName, repo.Name, pullIssue.Index, token), &api.PullReviewRequestOptions{ + req = NewRequestWithJSON(t, http.MethodDelete, fmt.Sprintf("/api/v1/repos/%s/%s/pulls/%d/requested_reviewers", repo.OwnerName, repo.Name, pullIssue.Index), &api.PullReviewRequestOptions{ Reviewers: []string{"user8"}, - }) + }).AddTokenAuth(token) MakeRequest(t, req, http.StatusNoContent) // Test team review request @@ -275,33 +282,35 @@ func TestAPIPullReviewRequest(t *testing.T) { repo3 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: pullIssue12.RepoID}) // Test add Team Review Request - req = NewRequestWithJSON(t, http.MethodPost, fmt.Sprintf("/api/v1/repos/%s/%s/pulls/%d/requested_reviewers?token=%s", repo3.OwnerName, repo3.Name, pullIssue12.Index, token), &api.PullReviewRequestOptions{ + req = NewRequestWithJSON(t, http.MethodPost, fmt.Sprintf("/api/v1/repos/%s/%s/pulls/%d/requested_reviewers", repo3.OwnerName, repo3.Name, pullIssue12.Index), &api.PullReviewRequestOptions{ TeamReviewers: []string{"team1", "owners"}, - }) + }).AddTokenAuth(token) MakeRequest(t, req, http.StatusCreated) // Test add Team Review Request to not allowned - req = NewRequestWithJSON(t, http.MethodPost, fmt.Sprintf("/api/v1/repos/%s/%s/pulls/%d/requested_reviewers?token=%s", repo3.OwnerName, repo3.Name, pullIssue12.Index, token), &api.PullReviewRequestOptions{ + req = NewRequestWithJSON(t, http.MethodPost, fmt.Sprintf("/api/v1/repos/%s/%s/pulls/%d/requested_reviewers", repo3.OwnerName, repo3.Name, pullIssue12.Index), &api.PullReviewRequestOptions{ TeamReviewers: []string{"test_team"}, - }) + }).AddTokenAuth(token) MakeRequest(t, req, http.StatusUnprocessableEntity) // Test add Team Review Request to not exist - req = NewRequestWithJSON(t, http.MethodPost, fmt.Sprintf("/api/v1/repos/%s/%s/pulls/%d/requested_reviewers?token=%s", repo3.OwnerName, repo3.Name, pullIssue12.Index, token), &api.PullReviewRequestOptions{ + req = NewRequestWithJSON(t, http.MethodPost, fmt.Sprintf("/api/v1/repos/%s/%s/pulls/%d/requested_reviewers", repo3.OwnerName, repo3.Name, pullIssue12.Index), &api.PullReviewRequestOptions{ TeamReviewers: []string{"not_exist_team"}, - }) + }).AddTokenAuth(token) MakeRequest(t, req, http.StatusNotFound) // Test Remove team Review Request - req = NewRequestWithJSON(t, http.MethodDelete, fmt.Sprintf("/api/v1/repos/%s/%s/pulls/%d/requested_reviewers?token=%s", repo3.OwnerName, repo3.Name, pullIssue12.Index, token), &api.PullReviewRequestOptions{ + req = NewRequestWithJSON(t, http.MethodDelete, fmt.Sprintf("/api/v1/repos/%s/%s/pulls/%d/requested_reviewers", repo3.OwnerName, repo3.Name, pullIssue12.Index), &api.PullReviewRequestOptions{ TeamReviewers: []string{"team1"}, - }) + }).AddTokenAuth(token) MakeRequest(t, req, http.StatusNoContent) // empty request test - req = NewRequestWithJSON(t, http.MethodPost, fmt.Sprintf("/api/v1/repos/%s/%s/pulls/%d/requested_reviewers?token=%s", repo3.OwnerName, repo3.Name, pullIssue12.Index, token), &api.PullReviewRequestOptions{}) + req = NewRequestWithJSON(t, http.MethodPost, fmt.Sprintf("/api/v1/repos/%s/%s/pulls/%d/requested_reviewers", repo3.OwnerName, repo3.Name, pullIssue12.Index), &api.PullReviewRequestOptions{}). + AddTokenAuth(token) MakeRequest(t, req, http.StatusCreated) - req = NewRequestWithJSON(t, http.MethodDelete, fmt.Sprintf("/api/v1/repos/%s/%s/pulls/%d/requested_reviewers?token=%s", repo3.OwnerName, repo3.Name, pullIssue12.Index, token), &api.PullReviewRequestOptions{}) + req = NewRequestWithJSON(t, http.MethodDelete, fmt.Sprintf("/api/v1/repos/%s/%s/pulls/%d/requested_reviewers", repo3.OwnerName, repo3.Name, pullIssue12.Index), &api.PullReviewRequestOptions{}). + AddTokenAuth(token) MakeRequest(t, req, http.StatusNoContent) } diff --git a/tests/integration/api_pull_test.go b/tests/integration/api_pull_test.go index 9d590630e45..33cc826e5ea 100644 --- a/tests/integration/api_pull_test.go +++ b/tests/integration/api_pull_test.go @@ -31,7 +31,8 @@ func TestAPIViewPulls(t *testing.T) { ctx := NewAPITestContext(t, "user2", repo.Name, auth_model.AccessTokenScopeReadRepository) - req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/pulls?state=all&token="+ctx.Token, owner.Name, repo.Name) + req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/pulls?state=all", owner.Name, repo.Name). + AddTokenAuth(ctx.Token) resp := ctx.Session.MakeRequest(t, req, http.StatusOK) var pulls []*api.PullRequest @@ -76,10 +77,10 @@ func TestAPIMergePullWIP(t *testing.T) { session := loginUser(t, owner.Name) token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteRepository) - req := NewRequestWithJSON(t, http.MethodPost, fmt.Sprintf("/api/v1/repos/%s/%s/pulls/%d/merge?token=%s", owner.Name, repo.Name, pr.Index, token), &forms.MergePullRequestForm{ + req := NewRequestWithJSON(t, http.MethodPost, fmt.Sprintf("/api/v1/repos/%s/%s/pulls/%d/merge", owner.Name, repo.Name, pr.Index), &forms.MergePullRequestForm{ MergeMessageField: pr.Issue.Title, Do: string(repo_model.MergeStyleMerge), - }) + }).AddTokenAuth(token) MakeRequest(t, req, http.StatusMethodNotAllowed) } @@ -95,11 +96,11 @@ func TestAPICreatePullSuccess(t *testing.T) { session := loginUser(t, owner11.Name) token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteRepository) - req := NewRequestWithJSON(t, http.MethodPost, fmt.Sprintf("/api/v1/repos/%s/%s/pulls?token=%s", owner10.Name, repo10.Name, token), &api.CreatePullRequestOption{ + req := NewRequestWithJSON(t, http.MethodPost, fmt.Sprintf("/api/v1/repos/%s/%s/pulls", owner10.Name, repo10.Name), &api.CreatePullRequestOption{ Head: fmt.Sprintf("%s:master", owner11.Name), Base: "master", Title: "create a failure pr", - }) + }).AddTokenAuth(token) MakeRequest(t, req, http.StatusCreated) MakeRequest(t, req, http.StatusUnprocessableEntity) // second request should fail } @@ -126,7 +127,8 @@ func TestAPICreatePullWithFieldsSuccess(t *testing.T) { Labels: []int64{5}, } - req := NewRequestWithJSON(t, http.MethodPost, fmt.Sprintf("/api/v1/repos/%s/%s/pulls?token=%s", owner10.Name, repo10.Name, token), opts) + req := NewRequestWithJSON(t, http.MethodPost, fmt.Sprintf("/api/v1/repos/%s/%s/pulls", owner10.Name, repo10.Name), opts). + AddTokenAuth(token) res := MakeRequest(t, req, http.StatusCreated) pull := new(api.PullRequest) @@ -158,7 +160,8 @@ func TestAPICreatePullWithFieldsFailure(t *testing.T) { Base: "master", } - req := NewRequestWithJSON(t, http.MethodPost, fmt.Sprintf("/api/v1/repos/%s/%s/pulls?token=%s", owner10.Name, repo10.Name, token), opts) + req := NewRequestWithJSON(t, http.MethodPost, fmt.Sprintf("/api/v1/repos/%s/%s/pulls", owner10.Name, repo10.Name), opts). + AddTokenAuth(token) MakeRequest(t, req, http.StatusUnprocessableEntity) opts.Title = "is required" @@ -182,35 +185,34 @@ func TestAPIEditPull(t *testing.T) { session := loginUser(t, owner10.Name) token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteRepository) - req := NewRequestWithJSON(t, http.MethodPost, fmt.Sprintf("/api/v1/repos/%s/%s/pulls?token=%s", owner10.Name, repo10.Name, token), &api.CreatePullRequestOption{ + req := NewRequestWithJSON(t, http.MethodPost, fmt.Sprintf("/api/v1/repos/%s/%s/pulls", owner10.Name, repo10.Name), &api.CreatePullRequestOption{ Head: "develop", Base: "master", Title: "create a success pr", - }) + }).AddTokenAuth(token) pull := new(api.PullRequest) resp := MakeRequest(t, req, http.StatusCreated) DecodeJSON(t, resp, pull) assert.EqualValues(t, "master", pull.Base.Name) - req = NewRequestWithJSON(t, http.MethodPatch, fmt.Sprintf("/api/v1/repos/%s/%s/pulls/%d?token=%s", owner10.Name, repo10.Name, pull.Index, token), &api.EditPullRequestOption{ + req = NewRequestWithJSON(t, http.MethodPatch, fmt.Sprintf("/api/v1/repos/%s/%s/pulls/%d", owner10.Name, repo10.Name, pull.Index), &api.EditPullRequestOption{ Base: "feature/1", Title: "edit a this pr", - }) + }).AddTokenAuth(token) resp = MakeRequest(t, req, http.StatusCreated) DecodeJSON(t, resp, pull) assert.EqualValues(t, "feature/1", pull.Base.Name) - req = NewRequestWithJSON(t, http.MethodPatch, fmt.Sprintf("/api/v1/repos/%s/%s/pulls/%d?token=%s", owner10.Name, repo10.Name, pull.Index, token), &api.EditPullRequestOption{ + req = NewRequestWithJSON(t, http.MethodPatch, fmt.Sprintf("/api/v1/repos/%s/%s/pulls/%d", owner10.Name, repo10.Name, pull.Index), &api.EditPullRequestOption{ Base: "not-exist", - }) + }).AddTokenAuth(token) MakeRequest(t, req, http.StatusNotFound) } func doAPIGetPullFiles(ctx APITestContext, pr *api.PullRequest, callback func(*testing.T, []*api.ChangedFile)) func(*testing.T) { return func(t *testing.T) { - url := fmt.Sprintf("/api/v1/repos/%s/%s/pulls/%d/files?token=%s", ctx.Username, ctx.Reponame, pr.Index, ctx.Token) - - req := NewRequest(t, http.MethodGet, url) + req := NewRequest(t, http.MethodGet, fmt.Sprintf("/api/v1/repos/%s/%s/pulls/%d/files", ctx.Username, ctx.Reponame, pr.Index)). + AddTokenAuth(ctx.Token) if ctx.ExpectedCode == 0 { ctx.ExpectedCode = http.StatusOK } diff --git a/tests/integration/api_releases_test.go b/tests/integration/api_releases_test.go index 526842d5ac0..6ec3fcc4b8b 100644 --- a/tests/integration/api_releases_test.go +++ b/tests/integration/api_releases_test.go @@ -59,11 +59,12 @@ func TestAPIListReleases(t *testing.T) { // test filter testFilterByLen := func(auth bool, query url.Values, expectedLength int, msgAndArgs ...string) { - if auth { - query.Set("token", token) - } link.RawQuery = query.Encode() - resp = MakeRequest(t, NewRequest(t, "GET", link.String()), http.StatusOK) + req := NewRequest(t, "GET", link.String()) + if auth { + req.AddTokenAuth(token) + } + resp = MakeRequest(t, req, http.StatusOK) DecodeJSON(t, resp, &apiReleases) assert.Len(t, apiReleases, expectedLength, msgAndArgs) } @@ -77,8 +78,7 @@ func TestAPIListReleases(t *testing.T) { } func createNewReleaseUsingAPI(t *testing.T, session *TestSession, token string, owner *user_model.User, repo *repo_model.Repository, name, target, title, desc string) *api.Release { - urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/releases?token=%s", - owner.Name, repo.Name, token) + urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/releases", owner.Name, repo.Name) req := NewRequestWithJSON(t, "POST", urlStr, &api.CreateReleaseOption{ TagName: name, Title: title, @@ -86,7 +86,7 @@ func createNewReleaseUsingAPI(t *testing.T, session *TestSession, token string, IsDraft: false, IsPrerelease: false, Target: target, - }) + }).AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusCreated) var newRelease api.Release @@ -122,9 +122,9 @@ func TestAPICreateAndUpdateRelease(t *testing.T) { newRelease := createNewReleaseUsingAPI(t, session, token, owner, repo, "v0.0.1", target, "v0.0.1", "test") - urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/releases/%d?token=%s", - owner.Name, repo.Name, newRelease.ID, token) - req := NewRequest(t, "GET", urlStr) + urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/releases/%d", owner.Name, repo.Name, newRelease.ID) + req := NewRequest(t, "GET", urlStr). + AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusOK) var release api.Release @@ -141,7 +141,7 @@ func TestAPICreateAndUpdateRelease(t *testing.T) { IsDraft: &release.IsDraft, IsPrerelease: &release.IsPrerelease, Target: release.Target, - }) + }).AddTokenAuth(token) resp = MakeRequest(t, req, http.StatusOK) DecodeJSON(t, resp, &newRelease) @@ -189,10 +189,7 @@ func TestAPIGetLatestRelease(t *testing.T) { repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}) owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}) - urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/releases/latest", - owner.Name, repo.Name) - - req := NewRequestf(t, "GET", urlStr) + req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/repos/%s/%s/releases/latest", owner.Name, repo.Name)) resp := MakeRequest(t, req, http.StatusOK) var release *api.Release @@ -209,10 +206,7 @@ func TestAPIGetReleaseByTag(t *testing.T) { tag := "v1.1" - urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/releases/tags/%s", - owner.Name, repo.Name, tag) - - req := NewRequestf(t, "GET", urlStr) + req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/repos/%s/%s/releases/tags/%s", owner.Name, repo.Name, tag)) resp := MakeRequest(t, req, http.StatusOK) var release *api.Release @@ -222,10 +216,7 @@ func TestAPIGetReleaseByTag(t *testing.T) { nonexistingtag := "nonexistingtag" - urlStr = fmt.Sprintf("/api/v1/repos/%s/%s/releases/tags/%s", - owner.Name, repo.Name, nonexistingtag) - - req = NewRequestf(t, "GET", urlStr) + req = NewRequest(t, "GET", fmt.Sprintf("/api/v1/repos/%s/%s/releases/tags/%s", owner.Name, repo.Name, nonexistingtag)) resp = MakeRequest(t, req, http.StatusNotFound) var err *api.APIError @@ -244,15 +235,18 @@ func TestAPIDeleteReleaseByTagName(t *testing.T) { createNewReleaseUsingAPI(t, session, token, owner, repo, "release-tag", "", "Release Tag", "test") // delete release - req := NewRequestf(t, http.MethodDelete, fmt.Sprintf("/api/v1/repos/%s/%s/releases/tags/release-tag?token=%s", owner.Name, repo.Name, token)) + req := NewRequestf(t, http.MethodDelete, fmt.Sprintf("/api/v1/repos/%s/%s/releases/tags/release-tag", owner.Name, repo.Name)). + AddTokenAuth(token) _ = MakeRequest(t, req, http.StatusNoContent) // make sure release is deleted - req = NewRequestf(t, http.MethodDelete, fmt.Sprintf("/api/v1/repos/%s/%s/releases/tags/release-tag?token=%s", owner.Name, repo.Name, token)) + req = NewRequestf(t, http.MethodDelete, fmt.Sprintf("/api/v1/repos/%s/%s/releases/tags/release-tag", owner.Name, repo.Name)). + AddTokenAuth(token) _ = MakeRequest(t, req, http.StatusNotFound) // delete release tag too - req = NewRequestf(t, http.MethodDelete, fmt.Sprintf("/api/v1/repos/%s/%s/tags/release-tag?token=%s", owner.Name, repo.Name, token)) + req = NewRequestf(t, http.MethodDelete, fmt.Sprintf("/api/v1/repos/%s/%s/tags/release-tag", owner.Name, repo.Name)). + AddTokenAuth(token) _ = MakeRequest(t, req, http.StatusNoContent) } @@ -278,7 +272,8 @@ func TestAPIUploadAssetRelease(t *testing.T) { err = writer.Close() assert.NoError(t, err) - req := NewRequestWithBody(t, http.MethodPost, fmt.Sprintf("/api/v1/repos/%s/%s/releases/%d/assets?name=test-asset&token=%s", owner.Name, repo.Name, r.ID, token), body) + req := NewRequestWithBody(t, http.MethodPost, fmt.Sprintf("/api/v1/repos/%s/%s/releases/%d/assets?name=test-asset", owner.Name, repo.Name, r.ID), body). + AddTokenAuth(token) req.Header.Add("Content-Type", writer.FormDataContentType()) resp := MakeRequest(t, req, http.StatusCreated) diff --git a/tests/integration/api_repo_avatar_test.go b/tests/integration/api_repo_avatar_test.go index 58a4fc536c8..6677885f7eb 100644 --- a/tests/integration/api_repo_avatar_test.go +++ b/tests/integration/api_repo_avatar_test.go @@ -38,7 +38,8 @@ func TestAPIUpdateRepoAvatar(t *testing.T) { Image: base64.StdEncoding.EncodeToString(avatar), } - req := NewRequestWithJSON(t, "POST", fmt.Sprintf("/api/v1/repos/%s/%s/avatar?token=%s", repo.OwnerName, repo.Name, token), &opts) + req := NewRequestWithJSON(t, "POST", fmt.Sprintf("/api/v1/repos/%s/%s/avatar", repo.OwnerName, repo.Name), &opts). + AddTokenAuth(token) MakeRequest(t, req, http.StatusNoContent) // Test what happens if you don't have a valid Base64 string @@ -46,7 +47,8 @@ func TestAPIUpdateRepoAvatar(t *testing.T) { Image: "Invalid", } - req = NewRequestWithJSON(t, "POST", fmt.Sprintf("/api/v1/repos/%s/%s/avatar?token=%s", repo.OwnerName, repo.Name, token), &opts) + req = NewRequestWithJSON(t, "POST", fmt.Sprintf("/api/v1/repos/%s/%s/avatar", repo.OwnerName, repo.Name), &opts). + AddTokenAuth(token) MakeRequest(t, req, http.StatusBadRequest) // Test what happens if you use a file that is not an image @@ -60,7 +62,8 @@ func TestAPIUpdateRepoAvatar(t *testing.T) { Image: base64.StdEncoding.EncodeToString(text), } - req = NewRequestWithJSON(t, "POST", fmt.Sprintf("/api/v1/repos/%s/%s/avatar?token=%s", repo.OwnerName, repo.Name, token), &opts) + req = NewRequestWithJSON(t, "POST", fmt.Sprintf("/api/v1/repos/%s/%s/avatar", repo.OwnerName, repo.Name), &opts). + AddTokenAuth(token) MakeRequest(t, req, http.StatusInternalServerError) } @@ -71,6 +74,7 @@ func TestAPIDeleteRepoAvatar(t *testing.T) { user2 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) token := getUserToken(t, user2.LowerName, auth_model.AccessTokenScopeWriteRepository) - req := NewRequest(t, "DELETE", fmt.Sprintf("/api/v1/repos/%s/%s/avatar?token=%s", repo.OwnerName, repo.Name, token)) + req := NewRequest(t, "DELETE", fmt.Sprintf("/api/v1/repos/%s/%s/avatar", repo.OwnerName, repo.Name)). + AddTokenAuth(token) MakeRequest(t, req, http.StatusNoContent) } diff --git a/tests/integration/api_repo_collaborator_test.go b/tests/integration/api_repo_collaborator_test.go index b7280a4f6c4..59cf85fef33 100644 --- a/tests/integration/api_repo_collaborator_test.go +++ b/tests/integration/api_repo_collaborator_test.go @@ -31,7 +31,8 @@ func TestAPIRepoCollaboratorPermission(t *testing.T) { testCtx := NewAPITestContext(t, repo2Owner.Name, repo2.Name, auth_model.AccessTokenScopeWriteRepository) t.Run("RepoOwnerShouldBeOwner", func(t *testing.T) { - req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/collaborators/%s/permission?token=%s", repo2Owner.Name, repo2.Name, repo2Owner.Name, testCtx.Token) + req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/collaborators/%s/permission", repo2Owner.Name, repo2.Name, repo2Owner.Name). + AddTokenAuth(testCtx.Token) resp := MakeRequest(t, req, http.StatusOK) var repoPermission api.RepoCollaboratorPermission @@ -43,7 +44,8 @@ func TestAPIRepoCollaboratorPermission(t *testing.T) { t.Run("CollaboratorWithReadAccess", func(t *testing.T) { t.Run("AddUserAsCollaboratorWithReadAccess", doAPIAddCollaborator(testCtx, user4.Name, perm.AccessModeRead)) - req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/collaborators/%s/permission?token=%s", repo2Owner.Name, repo2.Name, user4.Name, testCtx.Token) + req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/collaborators/%s/permission", repo2Owner.Name, repo2.Name, user4.Name). + AddTokenAuth(testCtx.Token) resp := MakeRequest(t, req, http.StatusOK) var repoPermission api.RepoCollaboratorPermission @@ -55,7 +57,8 @@ func TestAPIRepoCollaboratorPermission(t *testing.T) { t.Run("CollaboratorWithWriteAccess", func(t *testing.T) { t.Run("AddUserAsCollaboratorWithWriteAccess", doAPIAddCollaborator(testCtx, user4.Name, perm.AccessModeWrite)) - req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/collaborators/%s/permission?token=%s", repo2Owner.Name, repo2.Name, user4.Name, testCtx.Token) + req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/collaborators/%s/permission", repo2Owner.Name, repo2.Name, user4.Name). + AddTokenAuth(testCtx.Token) resp := MakeRequest(t, req, http.StatusOK) var repoPermission api.RepoCollaboratorPermission @@ -67,7 +70,8 @@ func TestAPIRepoCollaboratorPermission(t *testing.T) { t.Run("CollaboratorWithAdminAccess", func(t *testing.T) { t.Run("AddUserAsCollaboratorWithAdminAccess", doAPIAddCollaborator(testCtx, user4.Name, perm.AccessModeAdmin)) - req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/collaborators/%s/permission?token=%s", repo2Owner.Name, repo2.Name, user4.Name, testCtx.Token) + req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/collaborators/%s/permission", repo2Owner.Name, repo2.Name, user4.Name). + AddTokenAuth(testCtx.Token) resp := MakeRequest(t, req, http.StatusOK) var repoPermission api.RepoCollaboratorPermission @@ -77,7 +81,8 @@ func TestAPIRepoCollaboratorPermission(t *testing.T) { }) t.Run("CollaboratorNotFound", func(t *testing.T) { - req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/collaborators/%s/permission?token=%s", repo2Owner.Name, repo2.Name, "non-existent-user", testCtx.Token) + req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/collaborators/%s/permission", repo2Owner.Name, repo2.Name, "non-existent-user"). + AddTokenAuth(testCtx.Token) MakeRequest(t, req, http.StatusNotFound) }) @@ -87,7 +92,8 @@ func TestAPIRepoCollaboratorPermission(t *testing.T) { _session := loginUser(t, user5.Name) _testCtx := NewAPITestContext(t, user5.Name, repo2.Name, auth_model.AccessTokenScopeReadRepository) - req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/collaborators/%s/permission?token=%s", repo2Owner.Name, repo2.Name, user5.Name, _testCtx.Token) + req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/collaborators/%s/permission", repo2Owner.Name, repo2.Name, user5.Name). + AddTokenAuth(_testCtx.Token) resp := _session.MakeRequest(t, req, http.StatusOK) var repoPermission api.RepoCollaboratorPermission @@ -102,7 +108,8 @@ func TestAPIRepoCollaboratorPermission(t *testing.T) { _session := loginUser(t, user5.Name) _testCtx := NewAPITestContext(t, user5.Name, repo2.Name, auth_model.AccessTokenScopeReadRepository) - req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/collaborators/%s/permission?token=%s", repo2Owner.Name, repo2.Name, user5.Name, _testCtx.Token) + req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/collaborators/%s/permission", repo2Owner.Name, repo2.Name, user5.Name). + AddTokenAuth(_testCtx.Token) resp := _session.MakeRequest(t, req, http.StatusOK) var repoPermission api.RepoCollaboratorPermission @@ -118,7 +125,8 @@ func TestAPIRepoCollaboratorPermission(t *testing.T) { _session := loginUser(t, user10.Name) _testCtx := NewAPITestContext(t, user10.Name, repo2.Name, auth_model.AccessTokenScopeReadRepository) - req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/collaborators/%s/permission?token=%s", repo2Owner.Name, repo2.Name, user11.Name, _testCtx.Token) + req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/collaborators/%s/permission", repo2Owner.Name, repo2.Name, user11.Name). + AddTokenAuth(_testCtx.Token) resp := _session.MakeRequest(t, req, http.StatusOK) var repoPermission api.RepoCollaboratorPermission diff --git a/tests/integration/api_repo_edit_test.go b/tests/integration/api_repo_edit_test.go index 0e992c2df24..c4fc2177b4c 100644 --- a/tests/integration/api_repo_edit_test.go +++ b/tests/integration/api_repo_edit_test.go @@ -155,8 +155,8 @@ func TestAPIRepoEdit(t *testing.T) { // Test editing a repo1 which user2 owns, changing name and many properties origRepoEditOption := getRepoEditOptionFromRepo(repo1) repoEditOption := getNewRepoEditOption(origRepoEditOption) - url := fmt.Sprintf("/api/v1/repos/%s/%s?token=%s", user2.Name, repo1.Name, token2) - req := NewRequestWithJSON(t, "PATCH", url, &repoEditOption) + req := NewRequestWithJSON(t, "PATCH", fmt.Sprintf("/api/v1/repos/%s/%s", user2.Name, repo1.Name), &repoEditOption). + AddTokenAuth(token2) resp := MakeRequest(t, req, http.StatusOK) var repo api.Repository DecodeJSON(t, resp, &repo) @@ -186,8 +186,9 @@ func TestAPIRepoEdit(t *testing.T) { } *repoEditOption.HasWiki = true repoEditOption.ExternalWiki = nil - url = fmt.Sprintf("/api/v1/repos/%s/%s?token=%s", user2.Name, *repoEditOption.Name, token2) - req = NewRequestWithJSON(t, "PATCH", url, &repoEditOption) + url := fmt.Sprintf("/api/v1/repos/%s/%s", user2.Name, *repoEditOption.Name) + req = NewRequestWithJSON(t, "PATCH", url, &repoEditOption). + AddTokenAuth(token2) resp = MakeRequest(t, req, http.StatusOK) DecodeJSON(t, resp, &repo) assert.NotNil(t, repo) @@ -209,7 +210,8 @@ func TestAPIRepoEdit(t *testing.T) { repoEditOption.ExternalWiki = &api.ExternalWiki{ ExternalWikiURL: "http://www.somewebsite.com", } - req = NewRequestWithJSON(t, "PATCH", url, &repoEditOption) + req = NewRequestWithJSON(t, "PATCH", url, &repoEditOption). + AddTokenAuth(token2) resp = MakeRequest(t, req, http.StatusOK) DecodeJSON(t, resp, &repo) assert.NotNil(t, repo) @@ -223,7 +225,8 @@ func TestAPIRepoEdit(t *testing.T) { repoEditOption.ExternalTracker.ExternalTrackerStyle = "regexp" repoEditOption.ExternalTracker.ExternalTrackerRegexpPattern = `(\d+)` - req = NewRequestWithJSON(t, "PATCH", url, &repoEditOption) + req = NewRequestWithJSON(t, "PATCH", url, &repoEditOption). + AddTokenAuth(token2) resp = MakeRequest(t, req, http.StatusOK) DecodeJSON(t, resp, &repo) assert.NotNil(t, repo) @@ -234,15 +237,18 @@ func TestAPIRepoEdit(t *testing.T) { // Do some tests with invalid URL for external tracker and wiki repoEditOption.ExternalTracker.ExternalTrackerURL = "htp://www.somewebsite.com" - req = NewRequestWithJSON(t, "PATCH", url, &repoEditOption) + req = NewRequestWithJSON(t, "PATCH", url, &repoEditOption). + AddTokenAuth(token2) MakeRequest(t, req, http.StatusUnprocessableEntity) repoEditOption.ExternalTracker.ExternalTrackerURL = "http://www.somewebsite.com" repoEditOption.ExternalTracker.ExternalTrackerFormat = "http://www.somewebsite.com/{user/{repo}?issue={index}" - req = NewRequestWithJSON(t, "PATCH", url, &repoEditOption) + req = NewRequestWithJSON(t, "PATCH", url, &repoEditOption). + AddTokenAuth(token2) MakeRequest(t, req, http.StatusUnprocessableEntity) repoEditOption.ExternalTracker.ExternalTrackerFormat = "http://www.somewebsite.com/{user}/{repo}?issue={index}" repoEditOption.ExternalWiki.ExternalWikiURL = "htp://www.somewebsite.com" - req = NewRequestWithJSON(t, "PATCH", url, &repoEditOption) + req = NewRequestWithJSON(t, "PATCH", url, &repoEditOption). + AddTokenAuth(token2) MakeRequest(t, req, http.StatusUnprocessableEntity) // Test small repo change through API with issue and wiki option not set; They shall not be touched. @@ -251,7 +257,8 @@ func TestAPIRepoEdit(t *testing.T) { repoEditOption.ExternalTracker = nil repoEditOption.HasWiki = nil repoEditOption.ExternalWiki = nil - req = NewRequestWithJSON(t, "PATCH", url, &repoEditOption) + req = NewRequestWithJSON(t, "PATCH", url, &repoEditOption). + AddTokenAuth(token2) resp = MakeRequest(t, req, http.StatusOK) DecodeJSON(t, resp, &repo) assert.NotNil(t, repo) @@ -265,39 +272,38 @@ func TestAPIRepoEdit(t *testing.T) { assert.NotNil(t, *repo1editedOption.ExternalWiki) // reset repo in db - url = fmt.Sprintf("/api/v1/repos/%s/%s?token=%s", user2.Name, *repoEditOption.Name, token2) - req = NewRequestWithJSON(t, "PATCH", url, &origRepoEditOption) + req = NewRequestWithJSON(t, "PATCH", fmt.Sprintf("/api/v1/repos/%s/%s", user2.Name, *repoEditOption.Name), &origRepoEditOption). + AddTokenAuth(token2) _ = MakeRequest(t, req, http.StatusOK) // Test editing a non-existing repo name := "repodoesnotexist" - url = fmt.Sprintf("/api/v1/repos/%s/%s?token=%s", user2.Name, name, token2) - req = NewRequestWithJSON(t, "PATCH", url, &api.EditRepoOption{Name: &name}) + req = NewRequestWithJSON(t, "PATCH", fmt.Sprintf("/api/v1/repos/%s/%s", user2.Name, name), &api.EditRepoOption{Name: &name}). + AddTokenAuth(token2) _ = MakeRequest(t, req, http.StatusNotFound) // Test editing repo16 by user4 who does not have write access origRepoEditOption = getRepoEditOptionFromRepo(repo16) repoEditOption = getNewRepoEditOption(origRepoEditOption) - url = fmt.Sprintf("/api/v1/repos/%s/%s?token=%s", user2.Name, repo16.Name, token4) - req = NewRequestWithJSON(t, "PATCH", url, &repoEditOption) + req = NewRequestWithJSON(t, "PATCH", fmt.Sprintf("/api/v1/repos/%s/%s", user2.Name, repo16.Name), &repoEditOption). + AddTokenAuth(token4) MakeRequest(t, req, http.StatusNotFound) // Tests a repo with no token given so will fail origRepoEditOption = getRepoEditOptionFromRepo(repo16) repoEditOption = getNewRepoEditOption(origRepoEditOption) - url = fmt.Sprintf("/api/v1/repos/%s/%s", user2.Name, repo16.Name) - req = NewRequestWithJSON(t, "PATCH", url, &repoEditOption) + req = NewRequestWithJSON(t, "PATCH", fmt.Sprintf("/api/v1/repos/%s/%s", user2.Name, repo16.Name), &repoEditOption) _ = MakeRequest(t, req, http.StatusNotFound) // Test using access token for a private repo that the user of the token owns origRepoEditOption = getRepoEditOptionFromRepo(repo16) repoEditOption = getNewRepoEditOption(origRepoEditOption) - url = fmt.Sprintf("/api/v1/repos/%s/%s?token=%s", user2.Name, repo16.Name, token2) - req = NewRequestWithJSON(t, "PATCH", url, &repoEditOption) + req = NewRequestWithJSON(t, "PATCH", fmt.Sprintf("/api/v1/repos/%s/%s", user2.Name, repo16.Name), &repoEditOption). + AddTokenAuth(token2) _ = MakeRequest(t, req, http.StatusOK) // reset repo in db - url = fmt.Sprintf("/api/v1/repos/%s/%s?token=%s", user2.Name, *repoEditOption.Name, token2) - req = NewRequestWithJSON(t, "PATCH", url, &origRepoEditOption) + req = NewRequestWithJSON(t, "PATCH", fmt.Sprintf("/api/v1/repos/%s/%s", user2.Name, *repoEditOption.Name), &origRepoEditOption). + AddTokenAuth(token2) _ = MakeRequest(t, req, http.StatusOK) // Test making a repo public that is private @@ -306,53 +312,54 @@ func TestAPIRepoEdit(t *testing.T) { repoEditOption = &api.EditRepoOption{ Private: &bFalse, } - url = fmt.Sprintf("/api/v1/repos/%s/%s?token=%s", user2.Name, repo16.Name, token2) - req = NewRequestWithJSON(t, "PATCH", url, &repoEditOption) + url = fmt.Sprintf("/api/v1/repos/%s/%s", user2.Name, repo16.Name) + req = NewRequestWithJSON(t, "PATCH", url, &repoEditOption). + AddTokenAuth(token2) _ = MakeRequest(t, req, http.StatusOK) repo16 = unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 16}) assert.False(t, repo16.IsPrivate) // Make it private again repoEditOption.Private = &bTrue - req = NewRequestWithJSON(t, "PATCH", url, &repoEditOption) + req = NewRequestWithJSON(t, "PATCH", url, &repoEditOption). + AddTokenAuth(token2) _ = MakeRequest(t, req, http.StatusOK) // Test to change empty repo assert.False(t, repo15.IsArchived) - url = fmt.Sprintf("/api/v1/repos/%s/%s?token=%s", user2.Name, repo15.Name, token2) + url = fmt.Sprintf("/api/v1/repos/%s/%s", user2.Name, repo15.Name) req = NewRequestWithJSON(t, "PATCH", url, &api.EditRepoOption{ Archived: &bTrue, - }) + }).AddTokenAuth(token2) _ = MakeRequest(t, req, http.StatusOK) repo15 = unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 15}) assert.True(t, repo15.IsArchived) req = NewRequestWithJSON(t, "PATCH", url, &api.EditRepoOption{ Archived: &bFalse, - }) + }).AddTokenAuth(token2) _ = MakeRequest(t, req, http.StatusOK) // Test using org repo "org3/repo3" where user2 is a collaborator origRepoEditOption = getRepoEditOptionFromRepo(repo3) repoEditOption = getNewRepoEditOption(origRepoEditOption) - url = fmt.Sprintf("/api/v1/repos/%s/%s?token=%s", org3.Name, repo3.Name, token2) - req = NewRequestWithJSON(t, "PATCH", url, &repoEditOption) + req = NewRequestWithJSON(t, "PATCH", fmt.Sprintf("/api/v1/repos/%s/%s", org3.Name, repo3.Name), &repoEditOption). + AddTokenAuth(token2) MakeRequest(t, req, http.StatusOK) // reset repo in db - url = fmt.Sprintf("/api/v1/repos/%s/%s?token=%s", org3.Name, *repoEditOption.Name, token2) - req = NewRequestWithJSON(t, "PATCH", url, &origRepoEditOption) + req = NewRequestWithJSON(t, "PATCH", fmt.Sprintf("/api/v1/repos/%s/%s", org3.Name, *repoEditOption.Name), &origRepoEditOption). + AddTokenAuth(token2) _ = MakeRequest(t, req, http.StatusOK) // Test using org repo "org3/repo3" with no user token origRepoEditOption = getRepoEditOptionFromRepo(repo3) repoEditOption = getNewRepoEditOption(origRepoEditOption) - url = fmt.Sprintf("/api/v1/repos/%s/%s", org3.Name, repo3.Name) - req = NewRequestWithJSON(t, "PATCH", url, &repoEditOption) + req = NewRequestWithJSON(t, "PATCH", fmt.Sprintf("/api/v1/repos/%s/%s", org3.Name, repo3.Name), &repoEditOption) MakeRequest(t, req, http.StatusNotFound) // Test using repo "user2/repo1" where user4 is a NOT collaborator origRepoEditOption = getRepoEditOptionFromRepo(repo1) repoEditOption = getNewRepoEditOption(origRepoEditOption) - url = fmt.Sprintf("/api/v1/repos/%s/%s?token=%s", user2.Name, repo1.Name, token4) - req = NewRequestWithJSON(t, "PATCH", url, &repoEditOption) + req = NewRequestWithJSON(t, "PATCH", fmt.Sprintf("/api/v1/repos/%s/%s", user2.Name, repo1.Name), &repoEditOption). + AddTokenAuth(token4) MakeRequest(t, req, http.StatusForbidden) }) } diff --git a/tests/integration/api_repo_file_create_test.go b/tests/integration/api_repo_file_create_test.go index fbe0b5bcd05..f78909eb325 100644 --- a/tests/integration/api_repo_file_create_test.go +++ b/tests/integration/api_repo_file_create_test.go @@ -164,8 +164,8 @@ func TestAPICreateFile(t *testing.T) { createFileOptions.BranchName = branch fileID++ treePath := fmt.Sprintf("new/file%d.txt", fileID) - url := fmt.Sprintf("/api/v1/repos/%s/%s/contents/%s?token=%s", user2.Name, repo1.Name, treePath, token2) - req := NewRequestWithJSON(t, "POST", url, &createFileOptions) + req := NewRequestWithJSON(t, "POST", fmt.Sprintf("/api/v1/repos/%s/%s/contents/%s", user2.Name, repo1.Name, treePath), &createFileOptions). + AddTokenAuth(token2) resp := MakeRequest(t, req, http.StatusCreated) gitRepo, _ := git.OpenRepository(stdCtx.Background(), repo1.RepoPath()) commitID, _ := gitRepo.GetBranchCommitID(createFileOptions.NewBranchName) @@ -191,8 +191,8 @@ func TestAPICreateFile(t *testing.T) { createFileOptions.NewBranchName = "new_branch" fileID++ treePath := fmt.Sprintf("new/file%d.txt", fileID) - url := fmt.Sprintf("/api/v1/repos/%s/%s/contents/%s?token=%s", user2.Name, repo1.Name, treePath, token2) - req := NewRequestWithJSON(t, "POST", url, &createFileOptions) + req := NewRequestWithJSON(t, "POST", fmt.Sprintf("/api/v1/repos/%s/%s/contents/%s", user2.Name, repo1.Name, treePath), &createFileOptions). + AddTokenAuth(token2) resp := MakeRequest(t, req, http.StatusCreated) var fileResponse api.FileResponse DecodeJSON(t, resp, &fileResponse) @@ -209,8 +209,8 @@ func TestAPICreateFile(t *testing.T) { createFileOptions.Message = "" fileID++ treePath = fmt.Sprintf("new/file%d.txt", fileID) - url = fmt.Sprintf("/api/v1/repos/%s/%s/contents/%s?token=%s", user2.Name, repo1.Name, treePath, token2) - req = NewRequestWithJSON(t, "POST", url, &createFileOptions) + req = NewRequestWithJSON(t, "POST", fmt.Sprintf("/api/v1/repos/%s/%s/contents/%s", user2.Name, repo1.Name, treePath), &createFileOptions). + AddTokenAuth(token2) resp = MakeRequest(t, req, http.StatusCreated) DecodeJSON(t, resp, &fileResponse) expectedMessage := "Add " + treePath + "\n" @@ -219,8 +219,8 @@ func TestAPICreateFile(t *testing.T) { // Test trying to create a file that already exists, should fail createFileOptions = getCreateFileOptions() treePath = "README.md" - url = fmt.Sprintf("/api/v1/repos/%s/%s/contents/%s?token=%s", user2.Name, repo1.Name, treePath, token2) - req = NewRequestWithJSON(t, "POST", url, &createFileOptions) + req = NewRequestWithJSON(t, "POST", fmt.Sprintf("/api/v1/repos/%s/%s/contents/%s", user2.Name, repo1.Name, treePath), &createFileOptions). + AddTokenAuth(token2) resp = MakeRequest(t, req, http.StatusUnprocessableEntity) expectedAPIError := context.APIError{ Message: "repository file already exists [path: " + treePath + "]", @@ -234,48 +234,46 @@ func TestAPICreateFile(t *testing.T) { createFileOptions = getCreateFileOptions() fileID++ treePath = fmt.Sprintf("new/file%d.txt", fileID) - url = fmt.Sprintf("/api/v1/repos/%s/%s/contents/%s?token=%s", user2.Name, repo16.Name, treePath, token4) - req = NewRequestWithJSON(t, "POST", url, &createFileOptions) + req = NewRequestWithJSON(t, "POST", fmt.Sprintf("/api/v1/repos/%s/%s/contents/%s", user2.Name, repo16.Name, treePath), &createFileOptions). + AddTokenAuth(token4) MakeRequest(t, req, http.StatusNotFound) // Tests a repo with no token given so will fail createFileOptions = getCreateFileOptions() fileID++ treePath = fmt.Sprintf("new/file%d.txt", fileID) - url = fmt.Sprintf("/api/v1/repos/%s/%s/contents/%s", user2.Name, repo16.Name, treePath) - req = NewRequestWithJSON(t, "POST", url, &createFileOptions) + req = NewRequestWithJSON(t, "POST", fmt.Sprintf("/api/v1/repos/%s/%s/contents/%s", user2.Name, repo16.Name, treePath), &createFileOptions) MakeRequest(t, req, http.StatusNotFound) // Test using access token for a private repo that the user of the token owns createFileOptions = getCreateFileOptions() fileID++ treePath = fmt.Sprintf("new/file%d.txt", fileID) - url = fmt.Sprintf("/api/v1/repos/%s/%s/contents/%s?token=%s", user2.Name, repo16.Name, treePath, token2) - req = NewRequestWithJSON(t, "POST", url, &createFileOptions) + req = NewRequestWithJSON(t, "POST", fmt.Sprintf("/api/v1/repos/%s/%s/contents/%s", user2.Name, repo16.Name, treePath), &createFileOptions). + AddTokenAuth(token2) MakeRequest(t, req, http.StatusCreated) // Test using org repo "org3/repo3" where user2 is a collaborator createFileOptions = getCreateFileOptions() fileID++ treePath = fmt.Sprintf("new/file%d.txt", fileID) - url = fmt.Sprintf("/api/v1/repos/%s/%s/contents/%s?token=%s", org3.Name, repo3.Name, treePath, token2) - req = NewRequestWithJSON(t, "POST", url, &createFileOptions) + req = NewRequestWithJSON(t, "POST", fmt.Sprintf("/api/v1/repos/%s/%s/contents/%s", org3.Name, repo3.Name, treePath), &createFileOptions). + AddTokenAuth(token2) MakeRequest(t, req, http.StatusCreated) // Test using org repo "org3/repo3" with no user token createFileOptions = getCreateFileOptions() fileID++ treePath = fmt.Sprintf("new/file%d.txt", fileID) - url = fmt.Sprintf("/api/v1/repos/%s/%s/contents/%s", org3.Name, repo3.Name, treePath) - req = NewRequestWithJSON(t, "POST", url, &createFileOptions) + req = NewRequestWithJSON(t, "POST", fmt.Sprintf("/api/v1/repos/%s/%s/contents/%s", org3.Name, repo3.Name, treePath), &createFileOptions) MakeRequest(t, req, http.StatusNotFound) // Test using repo "user2/repo1" where user4 is a NOT collaborator createFileOptions = getCreateFileOptions() fileID++ treePath = fmt.Sprintf("new/file%d.txt", fileID) - url = fmt.Sprintf("/api/v1/repos/%s/%s/contents/%s?token=%s", user2.Name, repo1.Name, treePath, token4) - req = NewRequestWithJSON(t, "POST", url, &createFileOptions) + req = NewRequestWithJSON(t, "POST", fmt.Sprintf("/api/v1/repos/%s/%s/contents/%s", user2.Name, repo1.Name, treePath), &createFileOptions). + AddTokenAuth(token4) MakeRequest(t, req, http.StatusForbidden) // Test creating a file in an empty repository @@ -283,8 +281,8 @@ func TestAPICreateFile(t *testing.T) { createFileOptions = getCreateFileOptions() fileID++ treePath = fmt.Sprintf("new/file%d.txt", fileID) - url = fmt.Sprintf("/api/v1/repos/%s/%s/contents/%s?token=%s", user2.Name, "empty-repo", treePath, token2) - req = NewRequestWithJSON(t, "POST", url, &createFileOptions) + req = NewRequestWithJSON(t, "POST", fmt.Sprintf("/api/v1/repos/%s/%s/contents/%s", user2.Name, "empty-repo", treePath), &createFileOptions). + AddTokenAuth(token2) resp = MakeRequest(t, req, http.StatusCreated) emptyRepo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{OwnerName: "user2", Name: "empty-repo"}) // public repo gitRepo, _ := git.OpenRepository(stdCtx.Background(), emptyRepo.RepoPath()) diff --git a/tests/integration/api_repo_file_delete_test.go b/tests/integration/api_repo_file_delete_test.go index c6ab7a0e615..7c93307e198 100644 --- a/tests/integration/api_repo_file_delete_test.go +++ b/tests/integration/api_repo_file_delete_test.go @@ -64,8 +64,8 @@ func TestAPIDeleteFile(t *testing.T) { createFile(user2, repo1, treePath) deleteFileOptions := getDeleteFileOptions() deleteFileOptions.BranchName = branch - url := fmt.Sprintf("/api/v1/repos/%s/%s/contents/%s?token=%s", user2.Name, repo1.Name, treePath, token2) - req := NewRequestWithJSON(t, "DELETE", url, &deleteFileOptions) + req := NewRequestWithJSON(t, "DELETE", fmt.Sprintf("/api/v1/repos/%s/%s/contents/%s", user2.Name, repo1.Name, treePath), &deleteFileOptions). + AddTokenAuth(token2) resp := MakeRequest(t, req, http.StatusOK) var fileResponse api.FileResponse DecodeJSON(t, resp, &fileResponse) @@ -80,8 +80,8 @@ func TestAPIDeleteFile(t *testing.T) { deleteFileOptions := getDeleteFileOptions() deleteFileOptions.BranchName = repo1.DefaultBranch deleteFileOptions.NewBranchName = "new_branch" - url := fmt.Sprintf("/api/v1/repos/%s/%s/contents/%s?token=%s", user2.Name, repo1.Name, treePath, token2) - req := NewRequestWithJSON(t, "DELETE", url, &deleteFileOptions) + req := NewRequestWithJSON(t, "DELETE", fmt.Sprintf("/api/v1/repos/%s/%s/contents/%s", user2.Name, repo1.Name, treePath), &deleteFileOptions). + AddTokenAuth(token2) resp := MakeRequest(t, req, http.StatusOK) var fileResponse api.FileResponse DecodeJSON(t, resp, &fileResponse) @@ -95,8 +95,8 @@ func TestAPIDeleteFile(t *testing.T) { createFile(user2, repo1, treePath) deleteFileOptions = getDeleteFileOptions() deleteFileOptions.Message = "" - url = fmt.Sprintf("/api/v1/repos/%s/%s/contents/%s?token=%s", user2.Name, repo1.Name, treePath, token2) - req = NewRequestWithJSON(t, "DELETE", url, &deleteFileOptions) + req = NewRequestWithJSON(t, "DELETE", fmt.Sprintf("/api/v1/repos/%s/%s/contents/%s", user2.Name, repo1.Name, treePath), &deleteFileOptions). + AddTokenAuth(token2) resp = MakeRequest(t, req, http.StatusOK) DecodeJSON(t, resp, &fileResponse) expectedMessage := "Delete " + treePath + "\n" @@ -108,8 +108,8 @@ func TestAPIDeleteFile(t *testing.T) { createFile(user2, repo1, treePath) deleteFileOptions = getDeleteFileOptions() deleteFileOptions.SHA = "badsha" - url = fmt.Sprintf("/api/v1/repos/%s/%s/contents/%s?token=%s", user2.Name, repo1.Name, treePath, token2) - req = NewRequestWithJSON(t, "DELETE", url, &deleteFileOptions) + req = NewRequestWithJSON(t, "DELETE", fmt.Sprintf("/api/v1/repos/%s/%s/contents/%s", user2.Name, repo1.Name, treePath), &deleteFileOptions). + AddTokenAuth(token2) MakeRequest(t, req, http.StatusBadRequest) // Test creating a file in repo16 by user4 who does not have write access @@ -117,8 +117,8 @@ func TestAPIDeleteFile(t *testing.T) { treePath = fmt.Sprintf("delete/file%d.txt", fileID) createFile(user2, repo16, treePath) deleteFileOptions = getDeleteFileOptions() - url = fmt.Sprintf("/api/v1/repos/%s/%s/contents/%s?token=%s", user2.Name, repo16.Name, treePath, token4) - req = NewRequestWithJSON(t, "DELETE", url, &deleteFileOptions) + req = NewRequestWithJSON(t, "DELETE", fmt.Sprintf("/api/v1/repos/%s/%s/contents/%s", user2.Name, repo16.Name, treePath), &deleteFileOptions). + AddTokenAuth(token4) MakeRequest(t, req, http.StatusNotFound) // Tests a repo with no token given so will fail @@ -126,8 +126,7 @@ func TestAPIDeleteFile(t *testing.T) { treePath = fmt.Sprintf("delete/file%d.txt", fileID) createFile(user2, repo16, treePath) deleteFileOptions = getDeleteFileOptions() - url = fmt.Sprintf("/api/v1/repos/%s/%s/contents/%s", user2.Name, repo16.Name, treePath) - req = NewRequestWithJSON(t, "DELETE", url, &deleteFileOptions) + req = NewRequestWithJSON(t, "DELETE", fmt.Sprintf("/api/v1/repos/%s/%s/contents/%s", user2.Name, repo16.Name, treePath), &deleteFileOptions) MakeRequest(t, req, http.StatusNotFound) // Test using access token for a private repo that the user of the token owns @@ -135,8 +134,8 @@ func TestAPIDeleteFile(t *testing.T) { treePath = fmt.Sprintf("delete/file%d.txt", fileID) createFile(user2, repo16, treePath) deleteFileOptions = getDeleteFileOptions() - url = fmt.Sprintf("/api/v1/repos/%s/%s/contents/%s?token=%s", user2.Name, repo16.Name, treePath, token2) - req = NewRequestWithJSON(t, "DELETE", url, &deleteFileOptions) + req = NewRequestWithJSON(t, "DELETE", fmt.Sprintf("/api/v1/repos/%s/%s/contents/%s", user2.Name, repo16.Name, treePath), &deleteFileOptions). + AddTokenAuth(token2) MakeRequest(t, req, http.StatusOK) // Test using org repo "org3/repo3" where user2 is a collaborator @@ -144,8 +143,8 @@ func TestAPIDeleteFile(t *testing.T) { treePath = fmt.Sprintf("delete/file%d.txt", fileID) createFile(org3, repo3, treePath) deleteFileOptions = getDeleteFileOptions() - url = fmt.Sprintf("/api/v1/repos/%s/%s/contents/%s?token=%s", org3.Name, repo3.Name, treePath, token2) - req = NewRequestWithJSON(t, "DELETE", url, &deleteFileOptions) + req = NewRequestWithJSON(t, "DELETE", fmt.Sprintf("/api/v1/repos/%s/%s/contents/%s", org3.Name, repo3.Name, treePath), &deleteFileOptions). + AddTokenAuth(token2) MakeRequest(t, req, http.StatusOK) // Test using org repo "org3/repo3" with no user token @@ -153,8 +152,7 @@ func TestAPIDeleteFile(t *testing.T) { treePath = fmt.Sprintf("delete/file%d.txt", fileID) createFile(org3, repo3, treePath) deleteFileOptions = getDeleteFileOptions() - url = fmt.Sprintf("/api/v1/repos/%s/%s/contents/%s", org3.Name, repo3.Name, treePath) - req = NewRequestWithJSON(t, "DELETE", url, &deleteFileOptions) + req = NewRequestWithJSON(t, "DELETE", fmt.Sprintf("/api/v1/repos/%s/%s/contents/%s", org3.Name, repo3.Name, treePath), &deleteFileOptions) MakeRequest(t, req, http.StatusNotFound) // Test using repo "user2/repo1" where user4 is a NOT collaborator @@ -162,8 +160,8 @@ func TestAPIDeleteFile(t *testing.T) { treePath = fmt.Sprintf("delete/file%d.txt", fileID) createFile(user2, repo1, treePath) deleteFileOptions = getDeleteFileOptions() - url = fmt.Sprintf("/api/v1/repos/%s/%s/contents/%s?token=%s", user2.Name, repo1.Name, treePath, token4) - req = NewRequestWithJSON(t, "DELETE", url, &deleteFileOptions) + req = NewRequestWithJSON(t, "DELETE", fmt.Sprintf("/api/v1/repos/%s/%s/contents/%s", user2.Name, repo1.Name, treePath), &deleteFileOptions). + AddTokenAuth(token4) MakeRequest(t, req, http.StatusForbidden) }) } diff --git a/tests/integration/api_repo_file_update_test.go b/tests/integration/api_repo_file_update_test.go index ecf24cdbf98..7e88f6cd803 100644 --- a/tests/integration/api_repo_file_update_test.go +++ b/tests/integration/api_repo_file_update_test.go @@ -132,8 +132,8 @@ func TestAPIUpdateFile(t *testing.T) { createFile(user2, repo1, treePath) updateFileOptions := getUpdateFileOptions() updateFileOptions.BranchName = branch - url := fmt.Sprintf("/api/v1/repos/%s/%s/contents/%s?token=%s", user2.Name, repo1.Name, treePath, token2) - req := NewRequestWithJSON(t, "PUT", url, &updateFileOptions) + req := NewRequestWithJSON(t, "PUT", fmt.Sprintf("/api/v1/repos/%s/%s/contents/%s", user2.Name, repo1.Name, treePath), &updateFileOptions). + AddTokenAuth(token2) resp := MakeRequest(t, req, http.StatusOK) gitRepo, _ := git.OpenRepository(stdCtx.Background(), repo1.RepoPath()) commitID, _ := gitRepo.GetBranchCommitID(updateFileOptions.NewBranchName) @@ -156,8 +156,8 @@ func TestAPIUpdateFile(t *testing.T) { fileID++ treePath := fmt.Sprintf("update/file%d.txt", fileID) createFile(user2, repo1, treePath) - url := fmt.Sprintf("/api/v1/repos/%s/%s/contents/%s?token=%s", user2.Name, repo1.Name, treePath, token2) - req := NewRequestWithJSON(t, "PUT", url, &updateFileOptions) + req := NewRequestWithJSON(t, "PUT", fmt.Sprintf("/api/v1/repos/%s/%s/contents/%s", user2.Name, repo1.Name, treePath), &updateFileOptions). + AddTokenAuth(token2) resp := MakeRequest(t, req, http.StatusOK) var fileResponse api.FileResponse DecodeJSON(t, resp, &fileResponse) @@ -177,8 +177,8 @@ func TestAPIUpdateFile(t *testing.T) { createFile(user2, repo1, treePath) updateFileOptions.FromPath = treePath treePath = "rename/" + treePath - url = fmt.Sprintf("/api/v1/repos/%s/%s/contents/%s?token=%s", user2.Name, repo1.Name, treePath, token2) - req = NewRequestWithJSON(t, "PUT", url, &updateFileOptions) + req = NewRequestWithJSON(t, "PUT", fmt.Sprintf("/api/v1/repos/%s/%s/contents/%s", user2.Name, repo1.Name, treePath), &updateFileOptions). + AddTokenAuth(token2) resp = MakeRequest(t, req, http.StatusOK) DecodeJSON(t, resp, &fileResponse) expectedSHA = "08bd14b2e2852529157324de9c226b3364e76136" @@ -195,8 +195,8 @@ func TestAPIUpdateFile(t *testing.T) { fileID++ treePath = fmt.Sprintf("update/file%d.txt", fileID) createFile(user2, repo1, treePath) - url = fmt.Sprintf("/api/v1/repos/%s/%s/contents/%s?token=%s", user2.Name, repo1.Name, treePath, token2) - req = NewRequestWithJSON(t, "PUT", url, &updateFileOptions) + req = NewRequestWithJSON(t, "PUT", fmt.Sprintf("/api/v1/repos/%s/%s/contents/%s", user2.Name, repo1.Name, treePath), &updateFileOptions). + AddTokenAuth(token2) resp = MakeRequest(t, req, http.StatusOK) DecodeJSON(t, resp, &fileResponse) expectedMessage := "Update " + treePath + "\n" @@ -209,8 +209,8 @@ func TestAPIUpdateFile(t *testing.T) { updateFileOptions = getUpdateFileOptions() correctSHA := updateFileOptions.SHA updateFileOptions.SHA = "badsha" - url = fmt.Sprintf("/api/v1/repos/%s/%s/contents/%s?token=%s", user2.Name, repo1.Name, treePath, token2) - req = NewRequestWithJSON(t, "PUT", url, &updateFileOptions) + req = NewRequestWithJSON(t, "PUT", fmt.Sprintf("/api/v1/repos/%s/%s/contents/%s", user2.Name, repo1.Name, treePath), &updateFileOptions). + AddTokenAuth(token2) resp = MakeRequest(t, req, http.StatusUnprocessableEntity) expectedAPIError := context.APIError{ Message: "sha does not match [given: " + updateFileOptions.SHA + ", expected: " + correctSHA + "]", @@ -225,8 +225,8 @@ func TestAPIUpdateFile(t *testing.T) { treePath = fmt.Sprintf("update/file%d.txt", fileID) createFile(user2, repo16, treePath) updateFileOptions = getUpdateFileOptions() - url = fmt.Sprintf("/api/v1/repos/%s/%s/contents/%s?token=%s", user2.Name, repo16.Name, treePath, token4) - req = NewRequestWithJSON(t, "PUT", url, &updateFileOptions) + req = NewRequestWithJSON(t, "PUT", fmt.Sprintf("/api/v1/repos/%s/%s/contents/%s", user2.Name, repo16.Name, treePath), &updateFileOptions). + AddTokenAuth(token4) MakeRequest(t, req, http.StatusNotFound) // Tests a repo with no token given so will fail @@ -234,8 +234,7 @@ func TestAPIUpdateFile(t *testing.T) { treePath = fmt.Sprintf("update/file%d.txt", fileID) createFile(user2, repo16, treePath) updateFileOptions = getUpdateFileOptions() - url = fmt.Sprintf("/api/v1/repos/%s/%s/contents/%s", user2.Name, repo16.Name, treePath) - req = NewRequestWithJSON(t, "PUT", url, &updateFileOptions) + req = NewRequestWithJSON(t, "PUT", fmt.Sprintf("/api/v1/repos/%s/%s/contents/%s", user2.Name, repo16.Name, treePath), &updateFileOptions) MakeRequest(t, req, http.StatusNotFound) // Test using access token for a private repo that the user of the token owns @@ -243,8 +242,8 @@ func TestAPIUpdateFile(t *testing.T) { treePath = fmt.Sprintf("update/file%d.txt", fileID) createFile(user2, repo16, treePath) updateFileOptions = getUpdateFileOptions() - url = fmt.Sprintf("/api/v1/repos/%s/%s/contents/%s?token=%s", user2.Name, repo16.Name, treePath, token2) - req = NewRequestWithJSON(t, "PUT", url, &updateFileOptions) + req = NewRequestWithJSON(t, "PUT", fmt.Sprintf("/api/v1/repos/%s/%s/contents/%s", user2.Name, repo16.Name, treePath), &updateFileOptions). + AddTokenAuth(token2) MakeRequest(t, req, http.StatusOK) // Test using org repo "org3/repo3" where user2 is a collaborator @@ -252,8 +251,8 @@ func TestAPIUpdateFile(t *testing.T) { treePath = fmt.Sprintf("update/file%d.txt", fileID) createFile(org3, repo3, treePath) updateFileOptions = getUpdateFileOptions() - url = fmt.Sprintf("/api/v1/repos/%s/%s/contents/%s?token=%s", org3.Name, repo3.Name, treePath, token2) - req = NewRequestWithJSON(t, "PUT", url, &updateFileOptions) + req = NewRequestWithJSON(t, "PUT", fmt.Sprintf("/api/v1/repos/%s/%s/contents/%s", org3.Name, repo3.Name, treePath), &updateFileOptions). + AddTokenAuth(token2) MakeRequest(t, req, http.StatusOK) // Test using org repo "org3/repo3" with no user token @@ -261,8 +260,7 @@ func TestAPIUpdateFile(t *testing.T) { treePath = fmt.Sprintf("update/file%d.txt", fileID) createFile(org3, repo3, treePath) updateFileOptions = getUpdateFileOptions() - url = fmt.Sprintf("/api/v1/repos/%s/%s/contents/%s", org3.Name, repo3.Name, treePath) - req = NewRequestWithJSON(t, "PUT", url, &updateFileOptions) + req = NewRequestWithJSON(t, "PUT", fmt.Sprintf("/api/v1/repos/%s/%s/contents/%s", org3.Name, repo3.Name, treePath), &updateFileOptions) MakeRequest(t, req, http.StatusNotFound) // Test using repo "user2/repo1" where user4 is a NOT collaborator @@ -270,8 +268,8 @@ func TestAPIUpdateFile(t *testing.T) { treePath = fmt.Sprintf("update/file%d.txt", fileID) createFile(user2, repo1, treePath) updateFileOptions = getUpdateFileOptions() - url = fmt.Sprintf("/api/v1/repos/%s/%s/contents/%s?token=%s", user2.Name, repo1.Name, treePath, token4) - req = NewRequestWithJSON(t, "PUT", url, &updateFileOptions) + req = NewRequestWithJSON(t, "PUT", fmt.Sprintf("/api/v1/repos/%s/%s/contents/%s", user2.Name, repo1.Name, treePath), &updateFileOptions). + AddTokenAuth(token4) MakeRequest(t, req, http.StatusForbidden) }) } diff --git a/tests/integration/api_repo_files_change_test.go b/tests/integration/api_repo_files_change_test.go index 1ab759497fb..d500d48b360 100644 --- a/tests/integration/api_repo_files_change_test.go +++ b/tests/integration/api_repo_files_change_test.go @@ -93,8 +93,8 @@ func TestAPIChangeFiles(t *testing.T) { changeFilesOptions.Files[0].Path = createTreePath changeFilesOptions.Files[1].Path = updateTreePath changeFilesOptions.Files[2].Path = deleteTreePath - url := fmt.Sprintf("/api/v1/repos/%s/%s/contents?token=%s", user2.Name, repo1.Name, token2) - req := NewRequestWithJSON(t, "POST", url, &changeFilesOptions) + req := NewRequestWithJSON(t, "POST", fmt.Sprintf("/api/v1/repos/%s/%s/contents", user2.Name, repo1.Name), &changeFilesOptions). + AddTokenAuth(token2) resp := MakeRequest(t, req, http.StatusCreated) gitRepo, _ := git.OpenRepository(stdCtx.Background(), repo1.RepoPath()) commitID, _ := gitRepo.GetBranchCommitID(changeFilesOptions.NewBranchName) @@ -138,8 +138,9 @@ func TestAPIChangeFiles(t *testing.T) { changeFilesOptions.Files[2].Path = deleteTreePath createFile(user2, repo1, updateTreePath) createFile(user2, repo1, deleteTreePath) - url := fmt.Sprintf("/api/v1/repos/%s/%s/contents?token=%s", user2.Name, repo1.Name, token2) - req := NewRequestWithJSON(t, "POST", url, &changeFilesOptions) + url := fmt.Sprintf("/api/v1/repos/%s/%s/contents", user2.Name, repo1.Name) + req := NewRequestWithJSON(t, "POST", url, &changeFilesOptions). + AddTokenAuth(token2) resp := MakeRequest(t, req, http.StatusCreated) var filesResponse api.FilesResponse DecodeJSON(t, resp, &filesResponse) @@ -168,7 +169,8 @@ func TestAPIChangeFiles(t *testing.T) { changeFilesOptions.Files = []*api.ChangeFileOperation{changeFilesOptions.Files[1]} changeFilesOptions.Files[0].FromPath = updateTreePath changeFilesOptions.Files[0].Path = "rename/" + updateTreePath - req = NewRequestWithJSON(t, "POST", url, &changeFilesOptions) + req = NewRequestWithJSON(t, "POST", url, &changeFilesOptions). + AddTokenAuth(token2) resp = MakeRequest(t, req, http.StatusCreated) DecodeJSON(t, resp, &filesResponse) expectedUpdateSHA = "08bd14b2e2852529157324de9c226b3364e76136" @@ -191,7 +193,8 @@ func TestAPIChangeFiles(t *testing.T) { changeFilesOptions.Files[2].Path = deleteTreePath createFile(user2, repo1, updateTreePath) createFile(user2, repo1, deleteTreePath) - req = NewRequestWithJSON(t, "POST", url, &changeFilesOptions) + req = NewRequestWithJSON(t, "POST", url, &changeFilesOptions). + AddTokenAuth(token2) resp = MakeRequest(t, req, http.StatusCreated) DecodeJSON(t, resp, &filesResponse) expectedMessage := fmt.Sprintf("Add %v\nUpdate %v\nDelete %v\n", createTreePath, updateTreePath, deleteTreePath) @@ -206,7 +209,8 @@ func TestAPIChangeFiles(t *testing.T) { changeFilesOptions.Files[0].Path = updateTreePath correctSHA := changeFilesOptions.Files[0].SHA changeFilesOptions.Files[0].SHA = "badsha" - req = NewRequestWithJSON(t, "POST", url, &changeFilesOptions) + req = NewRequestWithJSON(t, "POST", url, &changeFilesOptions). + AddTokenAuth(token2) resp = MakeRequest(t, req, http.StatusUnprocessableEntity) expectedAPIError := context.APIError{ Message: "sha does not match [given: " + changeFilesOptions.Files[0].SHA + ", expected: " + correctSHA + "]", @@ -227,8 +231,8 @@ func TestAPIChangeFiles(t *testing.T) { changeFilesOptions.Files[0].Path = createTreePath changeFilesOptions.Files[1].Path = updateTreePath changeFilesOptions.Files[2].Path = deleteTreePath - url = fmt.Sprintf("/api/v1/repos/%s/%s/contents?token=%s", user2.Name, repo16.Name, token4) - req = NewRequestWithJSON(t, "POST", url, &changeFilesOptions) + req = NewRequestWithJSON(t, "POST", fmt.Sprintf("/api/v1/repos/%s/%s/contents", user2.Name, repo16.Name), &changeFilesOptions). + AddTokenAuth(token4) MakeRequest(t, req, http.StatusNotFound) // Tests a repo with no token given so will fail @@ -242,8 +246,7 @@ func TestAPIChangeFiles(t *testing.T) { changeFilesOptions.Files[0].Path = createTreePath changeFilesOptions.Files[1].Path = updateTreePath changeFilesOptions.Files[2].Path = deleteTreePath - url = fmt.Sprintf("/api/v1/repos/%s/%s/contents", user2.Name, repo16.Name) - req = NewRequestWithJSON(t, "POST", url, &changeFilesOptions) + req = NewRequestWithJSON(t, "POST", fmt.Sprintf("/api/v1/repos/%s/%s/contents", user2.Name, repo16.Name), &changeFilesOptions) MakeRequest(t, req, http.StatusNotFound) // Test using access token for a private repo that the user of the token owns @@ -257,8 +260,8 @@ func TestAPIChangeFiles(t *testing.T) { changeFilesOptions.Files[0].Path = createTreePath changeFilesOptions.Files[1].Path = updateTreePath changeFilesOptions.Files[2].Path = deleteTreePath - url = fmt.Sprintf("/api/v1/repos/%s/%s/contents?token=%s", user2.Name, repo16.Name, token2) - req = NewRequestWithJSON(t, "POST", url, &changeFilesOptions) + req = NewRequestWithJSON(t, "POST", fmt.Sprintf("/api/v1/repos/%s/%s/contents", user2.Name, repo16.Name), &changeFilesOptions). + AddTokenAuth(token2) MakeRequest(t, req, http.StatusCreated) // Test using org repo "org3/repo3" where user2 is a collaborator @@ -272,8 +275,8 @@ func TestAPIChangeFiles(t *testing.T) { changeFilesOptions.Files[0].Path = createTreePath changeFilesOptions.Files[1].Path = updateTreePath changeFilesOptions.Files[2].Path = deleteTreePath - url = fmt.Sprintf("/api/v1/repos/%s/%s/contents?token=%s", org3.Name, repo3.Name, token2) - req = NewRequestWithJSON(t, "POST", url, &changeFilesOptions) + req = NewRequestWithJSON(t, "POST", fmt.Sprintf("/api/v1/repos/%s/%s/contents", org3.Name, repo3.Name), &changeFilesOptions). + AddTokenAuth(token2) MakeRequest(t, req, http.StatusCreated) // Test using org repo "org3/repo3" with no user token @@ -287,8 +290,7 @@ func TestAPIChangeFiles(t *testing.T) { changeFilesOptions.Files[0].Path = createTreePath changeFilesOptions.Files[1].Path = updateTreePath changeFilesOptions.Files[2].Path = deleteTreePath - url = fmt.Sprintf("/api/v1/repos/%s/%s/contents", org3.Name, repo3.Name) - req = NewRequestWithJSON(t, "POST", url, &changeFilesOptions) + req = NewRequestWithJSON(t, "POST", fmt.Sprintf("/api/v1/repos/%s/%s/contents", org3.Name, repo3.Name), &changeFilesOptions) MakeRequest(t, req, http.StatusNotFound) // Test using repo "user2/repo1" where user4 is a NOT collaborator @@ -302,8 +304,8 @@ func TestAPIChangeFiles(t *testing.T) { changeFilesOptions.Files[0].Path = createTreePath changeFilesOptions.Files[1].Path = updateTreePath changeFilesOptions.Files[2].Path = deleteTreePath - url = fmt.Sprintf("/api/v1/repos/%s/%s/contents?token=%s", user2.Name, repo1.Name, token4) - req = NewRequestWithJSON(t, "POST", url, &changeFilesOptions) + req = NewRequestWithJSON(t, "POST", fmt.Sprintf("/api/v1/repos/%s/%s/contents", user2.Name, repo1.Name), &changeFilesOptions). + AddTokenAuth(token4) MakeRequest(t, req, http.StatusForbidden) }) } diff --git a/tests/integration/api_repo_get_contents_list_test.go b/tests/integration/api_repo_get_contents_list_test.go index 7874eddfd4d..86313f5e3b2 100644 --- a/tests/integration/api_repo_get_contents_list_test.go +++ b/tests/integration/api_repo_get_contents_list_test.go @@ -154,14 +154,17 @@ func testAPIGetContentsList(t *testing.T, u *url.URL) { MakeRequest(t, req, http.StatusNotFound) // Test accessing private ref with user token that does not have access - should fail - req = NewRequestf(t, "GET", "/api/v1/repos/%s/%s/contents/%s?token=%s", user2.Name, repo16.Name, treePath, token4) + req = NewRequestf(t, "GET", "/api/v1/repos/%s/%s/contents/%s", user2.Name, repo16.Name, treePath). + AddTokenAuth(token4) MakeRequest(t, req, http.StatusNotFound) // Test access private ref of owner of token - req = NewRequestf(t, "GET", "/api/v1/repos/%s/%s/contents/readme.md?token=%s", user2.Name, repo16.Name, token2) + req = NewRequestf(t, "GET", "/api/v1/repos/%s/%s/contents/readme.md", user2.Name, repo16.Name). + AddTokenAuth(token2) MakeRequest(t, req, http.StatusOK) // Test access of org org3 private repo file by owner user2 - req = NewRequestf(t, "GET", "/api/v1/repos/%s/%s/contents/%s?token=%s", org3.Name, repo3.Name, treePath, token2) + req = NewRequestf(t, "GET", "/api/v1/repos/%s/%s/contents/%s", org3.Name, repo3.Name, treePath). + AddTokenAuth(token2) MakeRequest(t, req, http.StatusOK) } diff --git a/tests/integration/api_repo_get_contents_test.go b/tests/integration/api_repo_get_contents_test.go index 1d708a4cdb4..ffbdfcb0fab 100644 --- a/tests/integration/api_repo_get_contents_test.go +++ b/tests/integration/api_repo_get_contents_test.go @@ -151,15 +151,18 @@ func testAPIGetContents(t *testing.T, u *url.URL) { MakeRequest(t, req, http.StatusNotFound) // Test accessing private ref with user token that does not have access - should fail - req = NewRequestf(t, "GET", "/api/v1/repos/%s/%s/contents/%s?token=%s", user2.Name, repo16.Name, treePath, token4) + req = NewRequestf(t, "GET", "/api/v1/repos/%s/%s/contents/%s", user2.Name, repo16.Name, treePath). + AddTokenAuth(token4) MakeRequest(t, req, http.StatusNotFound) // Test access private ref of owner of token - req = NewRequestf(t, "GET", "/api/v1/repos/%s/%s/contents/readme.md?token=%s", user2.Name, repo16.Name, token2) + req = NewRequestf(t, "GET", "/api/v1/repos/%s/%s/contents/readme.md", user2.Name, repo16.Name). + AddTokenAuth(token2) MakeRequest(t, req, http.StatusOK) // Test access of org org3 private repo file by owner user2 - req = NewRequestf(t, "GET", "/api/v1/repos/%s/%s/contents/%s?token=%s", org3.Name, repo3.Name, treePath, token2) + req = NewRequestf(t, "GET", "/api/v1/repos/%s/%s/contents/%s", org3.Name, repo3.Name, treePath). + AddTokenAuth(token2) MakeRequest(t, req, http.StatusOK) } diff --git a/tests/integration/api_repo_git_blobs_test.go b/tests/integration/api_repo_git_blobs_test.go index 866234d0a6c..184362e7e32 100644 --- a/tests/integration/api_repo_git_blobs_test.go +++ b/tests/integration/api_repo_git_blobs_test.go @@ -48,7 +48,8 @@ func TestAPIReposGitBlobs(t *testing.T) { MakeRequest(t, req, http.StatusNotFound) // Test using access token for a private repo that the user of the token owns - req = NewRequestf(t, "GET", "/api/v1/repos/%s/%s/git/blobs/%s?token=%s", user2.Name, repo16.Name, repo16ReadmeSHA, token) + req = NewRequestf(t, "GET", "/api/v1/repos/%s/%s/git/blobs/%s", user2.Name, repo16.Name, repo16ReadmeSHA). + AddTokenAuth(token) MakeRequest(t, req, http.StatusOK) // Test using bad sha @@ -56,11 +57,13 @@ func TestAPIReposGitBlobs(t *testing.T) { MakeRequest(t, req, http.StatusBadRequest) // Test using org repo "org3/repo3" where user2 is a collaborator - req = NewRequestf(t, "GET", "/api/v1/repos/%s/%s/git/blobs/%s?token=%s", org3.Name, repo3.Name, repo3ReadmeSHA, token) + req = NewRequestf(t, "GET", "/api/v1/repos/%s/%s/git/blobs/%s", org3.Name, repo3.Name, repo3ReadmeSHA). + AddTokenAuth(token) MakeRequest(t, req, http.StatusOK) // Test using org repo "org3/repo3" where user2 is a collaborator - req = NewRequestf(t, "GET", "/api/v1/repos/%s/%s/git/blobs/%s?token=%s", org3.Name, repo3.Name, repo3ReadmeSHA, token) + req = NewRequestf(t, "GET", "/api/v1/repos/%s/%s/git/blobs/%s", org3.Name, repo3.Name, repo3ReadmeSHA). + AddTokenAuth(token) MakeRequest(t, req, http.StatusOK) // Test using org repo "org3/repo3" with no user token diff --git a/tests/integration/api_repo_git_commits_test.go b/tests/integration/api_repo_git_commits_test.go index 765055720d7..36552062073 100644 --- a/tests/integration/api_repo_git_commits_test.go +++ b/tests/integration/api_repo_git_commits_test.go @@ -32,13 +32,16 @@ func TestAPIReposGitCommits(t *testing.T) { token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeReadRepository) // check invalid requests - req := NewRequestf(t, "GET", "/api/v1/repos/%s/repo1/git/commits/12345?token="+token, user.Name) + req := NewRequestf(t, "GET", "/api/v1/repos/%s/repo1/git/commits/12345", user.Name). + AddTokenAuth(token) MakeRequest(t, req, http.StatusNotFound) - req = NewRequestf(t, "GET", "/api/v1/repos/%s/repo1/git/commits/..?token="+token, user.Name) + req = NewRequestf(t, "GET", "/api/v1/repos/%s/repo1/git/commits/..", user.Name). + AddTokenAuth(token) MakeRequest(t, req, http.StatusUnprocessableEntity) - req = NewRequestf(t, "GET", "/api/v1/repos/%s/repo1/git/commits/branch-not-exist?token="+token, user.Name) + req = NewRequestf(t, "GET", "/api/v1/repos/%s/repo1/git/commits/branch-not-exist", user.Name). + AddTokenAuth(token) MakeRequest(t, req, http.StatusNotFound) for _, ref := range [...]string{ @@ -47,7 +50,8 @@ func TestAPIReposGitCommits(t *testing.T) { "65f1", // short sha "65f1bf27bc3bf70f64657658635e66094edbcb4d", // full sha } { - req := NewRequestf(t, "GET", "/api/v1/repos/%s/repo1/git/commits/%s?token="+token, user.Name, ref) + req := NewRequestf(t, "GET", "/api/v1/repos/%s/repo1/git/commits/%s", user.Name, ref). + AddTokenAuth(token) MakeRequest(t, req, http.StatusOK) } } @@ -60,7 +64,8 @@ func TestAPIReposGitCommitList(t *testing.T) { token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeReadRepository) // Test getting commits (Page 1) - req := NewRequestf(t, "GET", "/api/v1/repos/%s/repo20/commits?token="+token+"¬=master&sha=remove-files-a", user.Name) + req := NewRequestf(t, "GET", "/api/v1/repos/%s/repo20/commits?not=master&sha=remove-files-a", user.Name). + AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusOK) var apiData []api.Commit @@ -83,7 +88,8 @@ func TestAPIReposGitCommitListNotMaster(t *testing.T) { token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeReadRepository) // Test getting commits (Page 1) - req := NewRequestf(t, "GET", "/api/v1/repos/%s/repo16/commits?token="+token, user.Name) + req := NewRequestf(t, "GET", "/api/v1/repos/%s/repo16/commits", user.Name). + AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusOK) var apiData []api.Commit @@ -108,7 +114,8 @@ func TestAPIReposGitCommitListPage2Empty(t *testing.T) { token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeReadRepository) // Test getting commits (Page=2) - req := NewRequestf(t, "GET", "/api/v1/repos/%s/repo16/commits?token="+token+"&page=2", user.Name) + req := NewRequestf(t, "GET", "/api/v1/repos/%s/repo16/commits?page=2", user.Name). + AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusOK) var apiData []api.Commit @@ -125,7 +132,8 @@ func TestAPIReposGitCommitListDifferentBranch(t *testing.T) { token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeReadRepository) // Test getting commits (Page=1, Branch=good-sign) - req := NewRequestf(t, "GET", "/api/v1/repos/%s/repo16/commits?token="+token+"&sha=good-sign", user.Name) + req := NewRequestf(t, "GET", "/api/v1/repos/%s/repo16/commits?sha=good-sign", user.Name). + AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusOK) var apiData []api.Commit @@ -144,7 +152,8 @@ func TestAPIReposGitCommitListWithoutSelectFields(t *testing.T) { token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeReadRepository) // Test getting commits without files, verification, and stats - req := NewRequestf(t, "GET", "/api/v1/repos/%s/repo16/commits?token="+token+"&sha=good-sign&stat=false&files=false&verification=false", user.Name) + req := NewRequestf(t, "GET", "/api/v1/repos/%s/repo16/commits?sha=good-sign&stat=false&files=false&verification=false", user.Name). + AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusOK) var apiData []api.Commit @@ -165,14 +174,16 @@ func TestDownloadCommitDiffOrPatch(t *testing.T) { token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeReadRepository) // Test getting diff - reqDiff := NewRequestf(t, "GET", "/api/v1/repos/%s/repo16/git/commits/f27c2b2b03dcab38beaf89b0ab4ff61f6de63441.diff?token="+token, user.Name) + reqDiff := NewRequestf(t, "GET", "/api/v1/repos/%s/repo16/git/commits/f27c2b2b03dcab38beaf89b0ab4ff61f6de63441.diff", user.Name). + AddTokenAuth(token) resp := MakeRequest(t, reqDiff, http.StatusOK) assert.EqualValues(t, "commit f27c2b2b03dcab38beaf89b0ab4ff61f6de63441\nAuthor: User2 \nDate: Sun Aug 6 19:55:01 2017 +0200\n\n good signed commit\n\ndiff --git a/readme.md b/readme.md\nnew file mode 100644\nindex 0000000..458121c\n--- /dev/null\n+++ b/readme.md\n@@ -0,0 +1 @@\n+good sign\n", resp.Body.String()) // Test getting patch - reqPatch := NewRequestf(t, "GET", "/api/v1/repos/%s/repo16/git/commits/f27c2b2b03dcab38beaf89b0ab4ff61f6de63441.patch?token="+token, user.Name) + reqPatch := NewRequestf(t, "GET", "/api/v1/repos/%s/repo16/git/commits/f27c2b2b03dcab38beaf89b0ab4ff61f6de63441.patch", user.Name). + AddTokenAuth(token) resp = MakeRequest(t, reqPatch, http.StatusOK) assert.EqualValues(t, "From f27c2b2b03dcab38beaf89b0ab4ff61f6de63441 Mon Sep 17 00:00:00 2001\nFrom: User2 \nDate: Sun, 6 Aug 2017 19:55:01 +0200\nSubject: [PATCH] good signed commit\n\n---\n readme.md | 1 +\n 1 file changed, 1 insertion(+)\n create mode 100644 readme.md\n\ndiff --git a/readme.md b/readme.md\nnew file mode 100644\nindex 0000000..458121c\n--- /dev/null\n+++ b/readme.md\n@@ -0,0 +1 @@\n+good sign\n", @@ -186,7 +197,8 @@ func TestGetFileHistory(t *testing.T) { session := loginUser(t, user.Name) token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeReadRepository) - req := NewRequestf(t, "GET", "/api/v1/repos/%s/repo16/commits?path=readme.md&token="+token+"&sha=good-sign", user.Name) + req := NewRequestf(t, "GET", "/api/v1/repos/%s/repo16/commits?path=readme.md&sha=good-sign", user.Name). + AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusOK) var apiData []api.Commit @@ -206,7 +218,8 @@ func TestGetFileHistoryNotOnMaster(t *testing.T) { session := loginUser(t, user.Name) token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeReadRepository) - req := NewRequestf(t, "GET", "/api/v1/repos/%s/repo20/commits?path=test.csv&token="+token+"&sha=add-csv¬=master", user.Name) + req := NewRequestf(t, "GET", "/api/v1/repos/%s/repo20/commits?path=test.csv&sha=add-csv¬=master", user.Name). + AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusOK) var apiData []api.Commit diff --git a/tests/integration/api_repo_git_hook_test.go b/tests/integration/api_repo_git_hook_test.go index 9f3205ce60d..9917b41790d 100644 --- a/tests/integration/api_repo_git_hook_test.go +++ b/tests/integration/api_repo_git_hook_test.go @@ -32,8 +32,8 @@ func TestAPIListGitHooks(t *testing.T) { // user1 is an admin user session := loginUser(t, "user1") token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeReadRepository) - req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/hooks/git?token=%s", - owner.Name, repo.Name, token) + req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/hooks/git", owner.Name, repo.Name). + AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusOK) var apiGitHooks []*api.GitHook DecodeJSON(t, resp, &apiGitHooks) @@ -58,8 +58,8 @@ func TestAPIListGitHooksNoHooks(t *testing.T) { // user1 is an admin user session := loginUser(t, "user1") token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeReadRepository) - req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/hooks/git?token=%s", - owner.Name, repo.Name, token) + req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/hooks/git", owner.Name, repo.Name). + AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusOK) var apiGitHooks []*api.GitHook DecodeJSON(t, resp, &apiGitHooks) @@ -78,8 +78,8 @@ func TestAPIListGitHooksNoAccess(t *testing.T) { session := loginUser(t, owner.Name) token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeReadRepository) - req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/hooks/git?token=%s", - owner.Name, repo.Name, token) + req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/hooks/git", owner.Name, repo.Name). + AddTokenAuth(token) MakeRequest(t, req, http.StatusForbidden) } @@ -92,8 +92,8 @@ func TestAPIGetGitHook(t *testing.T) { // user1 is an admin user session := loginUser(t, "user1") token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeReadRepository) - req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/hooks/git/pre-receive?token=%s", - owner.Name, repo.Name, token) + req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/hooks/git/pre-receive", owner.Name, repo.Name). + AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusOK) var apiGitHook *api.GitHook DecodeJSON(t, resp, &apiGitHook) @@ -109,8 +109,8 @@ func TestAPIGetGitHookNoAccess(t *testing.T) { session := loginUser(t, owner.Name) token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeReadRepository) - req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/hooks/git/pre-receive?token=%s", - owner.Name, repo.Name, token) + req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/hooks/git/pre-receive", owner.Name, repo.Name). + AddTokenAuth(token) MakeRequest(t, req, http.StatusForbidden) } @@ -124,19 +124,19 @@ func TestAPIEditGitHook(t *testing.T) { session := loginUser(t, "user1") token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteRepository) - urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/hooks/git/pre-receive?token=%s", - owner.Name, repo.Name, token) + urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/hooks/git/pre-receive", + owner.Name, repo.Name) req := NewRequestWithJSON(t, "PATCH", urlStr, &api.EditGitHookOption{ Content: testHookContent, - }) + }).AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusOK) var apiGitHook *api.GitHook DecodeJSON(t, resp, &apiGitHook) assert.True(t, apiGitHook.IsActive) assert.Equal(t, testHookContent, apiGitHook.Content) - req = NewRequestf(t, "GET", "/api/v1/repos/%s/%s/hooks/git/pre-receive?token=%s", - owner.Name, repo.Name, token) + req = NewRequestf(t, "GET", "/api/v1/repos/%s/%s/hooks/git/pre-receive", owner.Name, repo.Name). + AddTokenAuth(token) resp = MakeRequest(t, req, http.StatusOK) var apiGitHook2 *api.GitHook DecodeJSON(t, resp, &apiGitHook2) @@ -152,11 +152,10 @@ func TestAPIEditGitHookNoAccess(t *testing.T) { session := loginUser(t, owner.Name) token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteRepository) - urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/hooks/git/pre-receive?token=%s", - owner.Name, repo.Name, token) + urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/hooks/git/pre-receive", owner.Name, repo.Name) req := NewRequestWithJSON(t, "PATCH", urlStr, &api.EditGitHookOption{ Content: testHookContent, - }) + }).AddTokenAuth(token) MakeRequest(t, req, http.StatusForbidden) } @@ -170,12 +169,12 @@ func TestAPIDeleteGitHook(t *testing.T) { session := loginUser(t, "user1") token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteRepository) - req := NewRequestf(t, "DELETE", "/api/v1/repos/%s/%s/hooks/git/pre-receive?token=%s", - owner.Name, repo.Name, token) + req := NewRequestf(t, "DELETE", "/api/v1/repos/%s/%s/hooks/git/pre-receive", owner.Name, repo.Name). + AddTokenAuth(token) MakeRequest(t, req, http.StatusNoContent) - req = NewRequestf(t, "GET", "/api/v1/repos/%s/%s/hooks/git/pre-receive?token=%s", - owner.Name, repo.Name, token) + req = NewRequestf(t, "GET", "/api/v1/repos/%s/%s/hooks/git/pre-receive", owner.Name, repo.Name). + AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusOK) var apiGitHook2 *api.GitHook DecodeJSON(t, resp, &apiGitHook2) @@ -191,7 +190,7 @@ func TestAPIDeleteGitHookNoAccess(t *testing.T) { session := loginUser(t, owner.Name) token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteRepository) - req := NewRequestf(t, "DELETE", "/api/v1/repos/%s/%s/hooks/git/pre-receive?token=%s", - owner.Name, repo.Name, token) + req := NewRequestf(t, "DELETE", "/api/v1/repos/%s/%s/hooks/git/pre-receive", owner.Name, repo.Name). + AddTokenAuth(token) MakeRequest(t, req, http.StatusForbidden) } diff --git a/tests/integration/api_repo_git_notes_test.go b/tests/integration/api_repo_git_notes_test.go index a7327d93274..9f3e927077e 100644 --- a/tests/integration/api_repo_git_notes_test.go +++ b/tests/integration/api_repo_git_notes_test.go @@ -24,14 +24,17 @@ func TestAPIReposGitNotes(t *testing.T) { token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeReadRepository) // check invalid requests - req := NewRequestf(t, "GET", "/api/v1/repos/%s/repo1/git/notes/12345?token=%s", user.Name, token) + req := NewRequestf(t, "GET", "/api/v1/repos/%s/repo1/git/notes/12345", user.Name). + AddTokenAuth(token) MakeRequest(t, req, http.StatusNotFound) - req = NewRequestf(t, "GET", "/api/v1/repos/%s/repo1/git/notes/..?token=%s", user.Name, token) + req = NewRequestf(t, "GET", "/api/v1/repos/%s/repo1/git/notes/..", user.Name). + AddTokenAuth(token) MakeRequest(t, req, http.StatusUnprocessableEntity) // check valid request - req = NewRequestf(t, "GET", "/api/v1/repos/%s/repo1/git/notes/65f1bf27bc3bf70f64657658635e66094edbcb4d?token=%s", user.Name, token) + req = NewRequestf(t, "GET", "/api/v1/repos/%s/repo1/git/notes/65f1bf27bc3bf70f64657658635e66094edbcb4d", user.Name). + AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusOK) var apiData api.Note diff --git a/tests/integration/api_repo_git_ref_test.go b/tests/integration/api_repo_git_ref_test.go index 20900b32419..875752ae3fd 100644 --- a/tests/integration/api_repo_git_ref_test.go +++ b/tests/integration/api_repo_git_ref_test.go @@ -24,13 +24,16 @@ func TestAPIReposGitRefs(t *testing.T) { "refs/heads/master", // Branch "refs/tags/v1.1", // Tag } { - req := NewRequestf(t, "GET", "/api/v1/repos/%s/repo1/git/%s?token="+token, user.Name, ref) + req := NewRequestf(t, "GET", "/api/v1/repos/%s/repo1/git/%s", user.Name, ref). + AddTokenAuth(token) MakeRequest(t, req, http.StatusOK) } // Test getting all refs - req := NewRequestf(t, "GET", "/api/v1/repos/%s/repo1/git/refs?token="+token, user.Name) + req := NewRequestf(t, "GET", "/api/v1/repos/%s/repo1/git/refs", user.Name). + AddTokenAuth(token) MakeRequest(t, req, http.StatusOK) // Test getting non-existent refs - req = NewRequestf(t, "GET", "/api/v1/repos/%s/repo1/git/refs/heads/unknown?token="+token, user.Name) + req = NewRequestf(t, "GET", "/api/v1/repos/%s/repo1/git/refs/heads/unknown", user.Name). + AddTokenAuth(token) MakeRequest(t, req, http.StatusNotFound) } diff --git a/tests/integration/api_repo_git_tags_test.go b/tests/integration/api_repo_git_tags_test.go index a9d47abf937..2e8510ab1b3 100644 --- a/tests/integration/api_repo_git_tags_test.go +++ b/tests/integration/api_repo_git_tags_test.go @@ -45,7 +45,8 @@ func TestAPIGitTags(t *testing.T) { aTag, _ := gitRepo.GetTag(aTagName) // SHOULD work for annotated tags - req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/git/tags/%s?token=%s", user.Name, repo.Name, aTag.ID.String(), token) + req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/git/tags/%s", user.Name, repo.Name, aTag.ID.String()). + AddTokenAuth(token) res := MakeRequest(t, req, http.StatusOK) var tag *api.AnnotatedTag @@ -60,7 +61,8 @@ func TestAPIGitTags(t *testing.T) { assert.Equal(t, util.URLJoin(repo.APIURL(), "git/tags", aTag.ID.String()), tag.URL) // Should NOT work for lightweight tags - badReq := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/git/tags/%s?token=%s", user.Name, repo.Name, commit.ID.String(), token) + badReq := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/git/tags/%s", user.Name, repo.Name, commit.ID.String()). + AddTokenAuth(token) MakeRequest(t, badReq, http.StatusBadRequest) } @@ -72,17 +74,14 @@ func TestAPIDeleteTagByName(t *testing.T) { session := loginUser(t, owner.LowerName) token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteRepository) - urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/tags/delete-tag?token=%s", - owner.Name, repo.Name, token) - - req := NewRequestf(t, http.MethodDelete, urlStr) + req := NewRequest(t, http.MethodDelete, fmt.Sprintf("/api/v1/repos/%s/%s/tags/delete-tag", owner.Name, repo.Name)). + AddTokenAuth(token) _ = MakeRequest(t, req, http.StatusNoContent) // Make sure that actual releases can't be deleted outright createNewReleaseUsingAPI(t, session, token, owner, repo, "release-tag", "", "Release Tag", "test") - urlStr = fmt.Sprintf("/api/v1/repos/%s/%s/tags/release-tag?token=%s", - owner.Name, repo.Name, token) - req = NewRequestf(t, http.MethodDelete, urlStr) + req = NewRequest(t, http.MethodDelete, fmt.Sprintf("/api/v1/repos/%s/%s/tags/release-tag", owner.Name, repo.Name)). + AddTokenAuth(token) _ = MakeRequest(t, req, http.StatusConflict) } diff --git a/tests/integration/api_repo_git_trees_test.go b/tests/integration/api_repo_git_trees_test.go index aa732b9946c..8eec6d8d220 100644 --- a/tests/integration/api_repo_git_trees_test.go +++ b/tests/integration/api_repo_git_trees_test.go @@ -50,7 +50,8 @@ func TestAPIReposGitTrees(t *testing.T) { } // Test using access token for a private repo that the user of the token owns - req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/git/trees/%s?token=%s", user2.Name, repo16.Name, repo16TreeSHA, token) + req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/git/trees/%s", user2.Name, repo16.Name, repo16TreeSHA). + AddTokenAuth(token) MakeRequest(t, req, http.StatusOK) // Test using bad sha @@ -58,7 +59,8 @@ func TestAPIReposGitTrees(t *testing.T) { MakeRequest(t, req, http.StatusBadRequest) // Test using org repo "org3/repo3" where user2 is a collaborator - req = NewRequestf(t, "GET", "/api/v1/repos/%s/%s/git/trees/%s?token=%s", org3.Name, repo3.Name, repo3TreeSHA, token) + req = NewRequestf(t, "GET", "/api/v1/repos/%s/%s/git/trees/%s", org3.Name, repo3.Name, repo3TreeSHA). + AddTokenAuth(token) MakeRequest(t, req, http.StatusOK) // Test using org repo "org3/repo3" with no user token diff --git a/tests/integration/api_repo_hook_test.go b/tests/integration/api_repo_hook_test.go index 18b12597dbd..f27fcc00d6b 100644 --- a/tests/integration/api_repo_hook_test.go +++ b/tests/integration/api_repo_hook_test.go @@ -27,17 +27,14 @@ func TestAPICreateHook(t *testing.T) { // user1 is an admin user session := loginUser(t, "user1") token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteRepository) - completeURL := func(lastSegment string) string { - return fmt.Sprintf("/api/v1/repos/%s/%s/%s?token=%s", owner.Name, repo.Name, lastSegment, token) - } - req := NewRequestWithJSON(t, "POST", completeURL("hooks"), api.CreateHookOption{ + req := NewRequestWithJSON(t, "POST", fmt.Sprintf("/api/v1/repos/%s/%s/%s", owner.Name, repo.Name, "hooks"), api.CreateHookOption{ Type: "gitea", Config: api.CreateHookOptionConfig{ "content_type": "json", "url": "http://example.com/", }, AuthorizationHeader: "Bearer s3cr3t", - }) + }).AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusCreated) var apiHook *api.Hook diff --git a/tests/integration/api_repo_lfs_migrate_test.go b/tests/integration/api_repo_lfs_migrate_test.go index 2cd7132b76c..8b4d79db022 100644 --- a/tests/integration/api_repo_lfs_migrate_test.go +++ b/tests/integration/api_repo_lfs_migrate_test.go @@ -33,12 +33,12 @@ func TestAPIRepoLFSMigrateLocal(t *testing.T) { session := loginUser(t, user.Name) token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteRepository) - req := NewRequestWithJSON(t, "POST", "/api/v1/repos/migrate?token="+token, &api.MigrateRepoOptions{ + req := NewRequestWithJSON(t, "POST", "/api/v1/repos/migrate", &api.MigrateRepoOptions{ CloneAddr: path.Join(setting.RepoRootPath, "migration/lfs-test.git"), RepoOwnerID: user.ID, RepoName: "lfs-test-local", LFS: true, - }) + }).AddTokenAuth(token) resp := MakeRequest(t, req, NoExpectedStatus) assert.EqualValues(t, http.StatusCreated, resp.Code) diff --git a/tests/integration/api_repo_lfs_test.go b/tests/integration/api_repo_lfs_test.go index b0e9269bb86..211dcf76c11 100644 --- a/tests/integration/api_repo_lfs_test.go +++ b/tests/integration/api_repo_lfs_test.go @@ -82,11 +82,10 @@ func TestAPILFSBatch(t *testing.T) { session := loginUser(t, "user2") - newRequest := func(t testing.TB, br *lfs.BatchRequest) *http.Request { - req := NewRequestWithJSON(t, "POST", "/user2/lfs-batch-repo.git/info/lfs/objects/batch", br) - req.Header.Set("Accept", lfs.MediaType) - req.Header.Set("Content-Type", lfs.MediaType) - return req + newRequest := func(t testing.TB, br *lfs.BatchRequest) *RequestWrapper { + return NewRequestWithJSON(t, "POST", "/user2/lfs-batch-repo.git/info/lfs/objects/batch", br). + SetHeader("Accept", lfs.MediaType). + SetHeader("Content-Type", lfs.MediaType) } decodeResponse := func(t *testing.T, b *bytes.Buffer) *lfs.BatchResponse { var br lfs.BatchResponse @@ -342,9 +341,8 @@ func TestAPILFSUpload(t *testing.T) { session := loginUser(t, "user2") - newRequest := func(t testing.TB, p lfs.Pointer, content string) *http.Request { - req := NewRequestWithBody(t, "PUT", path.Join("/user2/lfs-upload-repo.git/info/lfs/objects/", p.Oid, strconv.FormatInt(p.Size, 10)), strings.NewReader(content)) - return req + newRequest := func(t testing.TB, p lfs.Pointer, content string) *RequestWrapper { + return NewRequestWithBody(t, "PUT", path.Join("/user2/lfs-upload-repo.git/info/lfs/objects/", p.Oid, strconv.FormatInt(p.Size, 10)), strings.NewReader(content)) } t.Run("InvalidPointer", func(t *testing.T) { @@ -447,11 +445,10 @@ func TestAPILFSVerify(t *testing.T) { session := loginUser(t, "user2") - newRequest := func(t testing.TB, p *lfs.Pointer) *http.Request { - req := NewRequestWithJSON(t, "POST", "/user2/lfs-verify-repo.git/info/lfs/verify", p) - req.Header.Set("Accept", lfs.MediaType) - req.Header.Set("Content-Type", lfs.MediaType) - return req + newRequest := func(t testing.TB, p *lfs.Pointer) *RequestWrapper { + return NewRequestWithJSON(t, "POST", "/user2/lfs-verify-repo.git/info/lfs/verify", p). + SetHeader("Accept", lfs.MediaType). + SetHeader("Content-Type", lfs.MediaType) } t.Run("InvalidJsonRequest", func(t *testing.T) { diff --git a/tests/integration/api_repo_raw_test.go b/tests/integration/api_repo_raw_test.go index ccb20a939ee..e5f83d1c80c 100644 --- a/tests/integration/api_repo_raw_test.go +++ b/tests/integration/api_repo_raw_test.go @@ -27,12 +27,14 @@ func TestAPIReposRaw(t *testing.T) { "v1.1", // Tag "65f1bf27bc3bf70f64657658635e66094edbcb4d", // Commit } { - req := NewRequestf(t, "GET", "/api/v1/repos/%s/repo1/raw/%s/README.md?token="+token, user.Name, ref) + req := NewRequestf(t, "GET", "/api/v1/repos/%s/repo1/raw/%s/README.md", user.Name, ref). + AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusOK) assert.EqualValues(t, "file", resp.Header().Get("x-gitea-object-type")) } // Test default branch - req := NewRequestf(t, "GET", "/api/v1/repos/%s/repo1/raw/README.md?token="+token, user.Name) + req := NewRequestf(t, "GET", "/api/v1/repos/%s/repo1/raw/README.md", user.Name). + AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusOK) assert.EqualValues(t, "file", resp.Header().Get("x-gitea-object-type")) } diff --git a/tests/integration/api_repo_secrets_test.go b/tests/integration/api_repo_secrets_test.go index 263ad1608cd..feb9bae2b22 100644 --- a/tests/integration/api_repo_secrets_test.go +++ b/tests/integration/api_repo_secrets_test.go @@ -60,44 +60,47 @@ func TestAPIRepoSecrets(t *testing.T) { } for _, c := range cases { - req := NewRequestWithJSON(t, "PUT", fmt.Sprintf("/api/v1/repos/%s/actions/secrets/%s?token=%s", repo.FullName(), c.Name, token), api.CreateOrUpdateSecretOption{ + req := NewRequestWithJSON(t, "PUT", fmt.Sprintf("/api/v1/repos/%s/actions/secrets/%s", repo.FullName(), c.Name), api.CreateOrUpdateSecretOption{ Data: "data", - }) + }).AddTokenAuth(token) MakeRequest(t, req, c.ExpectedStatus) } }) t.Run("Update", func(t *testing.T) { name := "update_secret" - url := fmt.Sprintf("/api/v1/repos/%s/actions/secrets/%s?token=%s", repo.FullName(), name, token) + url := fmt.Sprintf("/api/v1/repos/%s/actions/secrets/%s", repo.FullName(), name) req := NewRequestWithJSON(t, "PUT", url, api.CreateOrUpdateSecretOption{ Data: "initial", - }) + }).AddTokenAuth(token) MakeRequest(t, req, http.StatusCreated) req = NewRequestWithJSON(t, "PUT", url, api.CreateOrUpdateSecretOption{ Data: "changed", - }) + }).AddTokenAuth(token) MakeRequest(t, req, http.StatusNoContent) }) t.Run("Delete", func(t *testing.T) { name := "delete_secret" - url := fmt.Sprintf("/api/v1/repos/%s/actions/secrets/%s?token=%s", repo.FullName(), name, token) + url := fmt.Sprintf("/api/v1/repos/%s/actions/secrets/%s", repo.FullName(), name) req := NewRequestWithJSON(t, "PUT", url, api.CreateOrUpdateSecretOption{ Data: "initial", - }) + }).AddTokenAuth(token) MakeRequest(t, req, http.StatusCreated) - req = NewRequest(t, "DELETE", url) + req = NewRequest(t, "DELETE", url). + AddTokenAuth(token) MakeRequest(t, req, http.StatusNoContent) - req = NewRequest(t, "DELETE", url) + req = NewRequest(t, "DELETE", url). + AddTokenAuth(token) MakeRequest(t, req, http.StatusNotFound) - req = NewRequest(t, "DELETE", fmt.Sprintf("/api/v1/repos/%s/actions/secrets/000?token=%s", repo.FullName(), token)) + req = NewRequest(t, "DELETE", fmt.Sprintf("/api/v1/repos/%s/actions/secrets/000", repo.FullName())). + AddTokenAuth(token) MakeRequest(t, req, http.StatusBadRequest) }) } diff --git a/tests/integration/api_repo_tags_test.go b/tests/integration/api_repo_tags_test.go index c4282f99284..c6eeb404c02 100644 --- a/tests/integration/api_repo_tags_test.go +++ b/tests/integration/api_repo_tags_test.go @@ -27,7 +27,8 @@ func TestAPIRepoTags(t *testing.T) { repoName := "repo1" - req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/tags?token=%s", user.Name, repoName, token) + req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/tags", user.Name, repoName). + AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusOK) var tags []*api.Tag @@ -55,14 +56,16 @@ func TestAPIRepoTags(t *testing.T) { } // get created tag - req = NewRequestf(t, "GET", "/api/v1/repos/%s/%s/tags/%s?token=%s", user.Name, repoName, newTag.Name, token) + req = NewRequestf(t, "GET", "/api/v1/repos/%s/%s/tags/%s", user.Name, repoName, newTag.Name). + AddTokenAuth(token) resp = MakeRequest(t, req, http.StatusOK) var tag *api.Tag DecodeJSON(t, resp, &tag) assert.EqualValues(t, newTag, tag) // delete tag - delReq := NewRequestf(t, "DELETE", "/api/v1/repos/%s/%s/tags/%s?token=%s", user.Name, repoName, newTag.Name, token) + delReq := NewRequestf(t, "DELETE", "/api/v1/repos/%s/%s/tags/%s", user.Name, repoName, newTag.Name). + AddTokenAuth(token) MakeRequest(t, delReq, http.StatusNoContent) // check if it's gone @@ -70,12 +73,12 @@ func TestAPIRepoTags(t *testing.T) { } func createNewTagUsingAPI(t *testing.T, session *TestSession, token, ownerName, repoName, name, target, msg string) *api.Tag { - urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/tags?token=%s", ownerName, repoName, token) + urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/tags", ownerName, repoName) req := NewRequestWithJSON(t, "POST", urlStr, &api.CreateTagOption{ TagName: name, Message: msg, Target: target, - }) + }).AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusCreated) var respObj api.Tag diff --git a/tests/integration/api_repo_teams_test.go b/tests/integration/api_repo_teams_test.go index 23cf8a25672..558bac81501 100644 --- a/tests/integration/api_repo_teams_test.go +++ b/tests/integration/api_repo_teams_test.go @@ -31,8 +31,8 @@ func TestAPIRepoTeams(t *testing.T) { token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteRepository) // ListTeams - url := fmt.Sprintf("/api/v1/repos/%s/teams?token=%s", publicOrgRepo.FullName(), token) - req := NewRequest(t, "GET", url) + req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/repos/%s/teams", publicOrgRepo.FullName())). + AddTokenAuth(token) res := MakeRequest(t, req, http.StatusOK) var teams []*api.Team DecodeJSON(t, res, &teams) @@ -49,34 +49,34 @@ func TestAPIRepoTeams(t *testing.T) { } // IsTeam - url = fmt.Sprintf("/api/v1/repos/%s/teams/%s?token=%s", publicOrgRepo.FullName(), "Test_Team", token) - req = NewRequest(t, "GET", url) + req = NewRequest(t, "GET", fmt.Sprintf("/api/v1/repos/%s/teams/%s", publicOrgRepo.FullName(), "Test_Team")). + AddTokenAuth(token) res = MakeRequest(t, req, http.StatusOK) var team *api.Team DecodeJSON(t, res, &team) assert.EqualValues(t, teams[1], team) - url = fmt.Sprintf("/api/v1/repos/%s/teams/%s?token=%s", publicOrgRepo.FullName(), "NonExistingTeam", token) - req = NewRequest(t, "GET", url) + req = NewRequest(t, "GET", fmt.Sprintf("/api/v1/repos/%s/teams/%s", publicOrgRepo.FullName(), "NonExistingTeam")). + AddTokenAuth(token) MakeRequest(t, req, http.StatusNotFound) // AddTeam with user4 - url = fmt.Sprintf("/api/v1/repos/%s/teams/%s?token=%s", publicOrgRepo.FullName(), "team1", token) - req = NewRequest(t, "PUT", url) + req = NewRequest(t, "PUT", fmt.Sprintf("/api/v1/repos/%s/teams/%s", publicOrgRepo.FullName(), "team1")). + AddTokenAuth(token) MakeRequest(t, req, http.StatusForbidden) // AddTeam with user2 user = unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) session = loginUser(t, user.Name) token = getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteRepository) - url = fmt.Sprintf("/api/v1/repos/%s/teams/%s?token=%s", publicOrgRepo.FullName(), "team1", token) - req = NewRequest(t, "PUT", url) + req = NewRequest(t, "PUT", fmt.Sprintf("/api/v1/repos/%s/teams/%s", publicOrgRepo.FullName(), "team1")). + AddTokenAuth(token) MakeRequest(t, req, http.StatusNoContent) MakeRequest(t, req, http.StatusUnprocessableEntity) // test duplicate request // DeleteTeam - url = fmt.Sprintf("/api/v1/repos/%s/teams/%s?token=%s", publicOrgRepo.FullName(), "team1", token) - req = NewRequest(t, "DELETE", url) + req = NewRequest(t, "DELETE", fmt.Sprintf("/api/v1/repos/%s/teams/%s", publicOrgRepo.FullName(), "team1")). + AddTokenAuth(token) MakeRequest(t, req, http.StatusNoContent) MakeRequest(t, req, http.StatusUnprocessableEntity) // test duplicate request } diff --git a/tests/integration/api_repo_test.go b/tests/integration/api_repo_test.go index fa159c6c5b9..90f84c794e1 100644 --- a/tests/integration/api_repo_test.go +++ b/tests/integration/api_repo_test.go @@ -45,8 +45,8 @@ func TestAPIUserReposWithWrongToken(t *testing.T) { defer tests.PrepareTestEnv(t)() user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) wrongToken := fmt.Sprintf("Bearer %s", "wrong_token") - req := NewRequestf(t, "GET", "/api/v1/users/%s/repos", user.Name) - req = addTokenAuthHeader(req, wrongToken) + req := NewRequestf(t, "GET", "/api/v1/users/%s/repos", user.Name). + AddTokenAuth(wrongToken) resp := MakeRequest(t, req, http.StatusUnauthorized) assert.Contains(t, resp.Body.String(), "user does not exist") @@ -208,7 +208,8 @@ func TestAPISearchRepo(t *testing.T) { } t.Run(testName, func(t *testing.T) { - request := NewRequest(t, "GET", testCase.requestURL+"&token="+token) + request := NewRequest(t, "GET", testCase.requestURL). + AddTokenAuth(token) response := MakeRequest(t, request, http.StatusOK) var body api.SearchResults @@ -309,7 +310,8 @@ func TestAPIOrgRepos(t *testing.T) { token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeReadOrganization) t.Run(testName, func(t *testing.T) { - req := NewRequestf(t, "GET", "/api/v1/orgs/%s/repos?token="+token, sourceOrg.Name) + req := NewRequestf(t, "GET", "/api/v1/orgs/%s/repos", sourceOrg.Name). + AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusOK) var apiRepos []*api.Repository @@ -329,7 +331,8 @@ func TestAPIGetRepoByIDUnauthorized(t *testing.T) { user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 4}) session := loginUser(t, user.Name) token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeReadRepository) - req := NewRequestf(t, "GET", "/api/v1/repositories/2?token="+token) + req := NewRequest(t, "GET", "/api/v1/repositories/2"). + AddTokenAuth(token) MakeRequest(t, req, http.StatusNotFound) } @@ -353,11 +356,11 @@ func TestAPIRepoMigrate(t *testing.T) { user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: testCase.ctxUserID}) session := loginUser(t, user.Name) token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteRepository) - req := NewRequestWithJSON(t, "POST", "/api/v1/repos/migrate?token="+token, &api.MigrateRepoOptions{ + req := NewRequestWithJSON(t, "POST", "/api/v1/repos/migrate", &api.MigrateRepoOptions{ CloneAddr: testCase.cloneURL, RepoOwnerID: testCase.userID, RepoName: testCase.repoName, - }) + }).AddTokenAuth(token) resp := MakeRequest(t, req, NoExpectedStatus) if resp.Code == http.StatusUnprocessableEntity { respJSON := map[string]string{} @@ -398,12 +401,13 @@ func testAPIRepoMigrateConflict(t *testing.T, u *url.URL) { cloneURL := "https://github.com/go-gitea/test_repo.git" - req := NewRequestWithJSON(t, "POST", "/api/v1/repos/migrate?token="+httpContext.Token, + req := NewRequestWithJSON(t, "POST", "/api/v1/repos/migrate", &api.MigrateRepoOptions{ CloneAddr: cloneURL, RepoOwnerID: userID, RepoName: httpContext.Reponame, - }) + }). + AddTokenAuth(httpContext.Token) resp := httpContext.Session.MakeRequest(t, req, http.StatusConflict) respJSON := map[string]string{} DecodeJSON(t, resp, &respJSON) @@ -425,7 +429,8 @@ func TestAPIMirrorSyncNonMirrorRepo(t *testing.T) { DecodeJSON(t, resp, &repo) assert.False(t, repo.Mirror) - req = NewRequestf(t, "POST", "/api/v1/repos/user2/repo1/mirror-sync?token=%s", token) + req = NewRequestf(t, "POST", "/api/v1/repos/user2/repo1/mirror-sync"). + AddTokenAuth(token) resp = MakeRequest(t, req, http.StatusBadRequest) errRespJSON := map[string]string{} DecodeJSON(t, resp, &errRespJSON) @@ -450,9 +455,9 @@ func TestAPIOrgRepoCreate(t *testing.T) { user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: testCase.ctxUserID}) session := loginUser(t, user.Name) token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteOrganization, auth_model.AccessTokenScopeWriteRepository) - req := NewRequestWithJSON(t, "POST", fmt.Sprintf("/api/v1/org/%s/repos?token="+token, testCase.orgName), &api.CreateRepoOption{ + req := NewRequestWithJSON(t, "POST", fmt.Sprintf("/api/v1/org/%s/repos", testCase.orgName), &api.CreateRepoOption{ Name: testCase.repoName, - }) + }).AddTokenAuth(token) MakeRequest(t, req, testCase.expectedStatus) } } @@ -473,10 +478,11 @@ func testAPIRepoCreateConflict(t *testing.T, u *url.URL) { httpContext.Reponame = "repo-tmp-17" t.Run("CreateRepo", doAPICreateRepository(httpContext, false)) - req := NewRequestWithJSON(t, "POST", "/api/v1/user/repos?token="+httpContext.Token, + req := NewRequestWithJSON(t, "POST", "/api/v1/user/repos", &api.CreateRepoOption{ Name: httpContext.Reponame, - }) + }). + AddTokenAuth(httpContext.Token) resp := httpContext.Session.MakeRequest(t, req, http.StatusConflict) respJSON := map[string]string{} DecodeJSON(t, resp, &respJSON) @@ -516,13 +522,13 @@ func TestAPIRepoTransfer(t *testing.T) { token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteRepository, auth_model.AccessTokenScopeWriteUser) repoName := "moveME" apiRepo := new(api.Repository) - req := NewRequestWithJSON(t, "POST", fmt.Sprintf("/api/v1/user/repos?token=%s", token), &api.CreateRepoOption{ + req := NewRequestWithJSON(t, "POST", "/api/v1/user/repos", &api.CreateRepoOption{ Name: repoName, Description: "repo move around", Private: false, Readme: "Default", AutoInit: true, - }) + }).AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusCreated) DecodeJSON(t, resp, apiRepo) @@ -532,10 +538,10 @@ func TestAPIRepoTransfer(t *testing.T) { repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: apiRepo.ID}) session = loginUser(t, user.Name) token = getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteRepository) - req = NewRequestWithJSON(t, "POST", fmt.Sprintf("/api/v1/repos/%s/%s/transfer?token=%s", repo.OwnerName, repo.Name, token), &api.TransferRepoOption{ + req = NewRequestWithJSON(t, "POST", fmt.Sprintf("/api/v1/repos/%s/%s/transfer", repo.OwnerName, repo.Name), &api.TransferRepoOption{ NewOwner: testCase.newOwner, TeamIDs: testCase.teams, - }) + }).AddTokenAuth(token) MakeRequest(t, req, testCase.expectedStatus) } @@ -551,21 +557,21 @@ func transfer(t *testing.T) *repo_model.Repository { token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteRepository, auth_model.AccessTokenScopeWriteUser) repoName := "moveME" apiRepo := new(api.Repository) - req := NewRequestWithJSON(t, "POST", fmt.Sprintf("/api/v1/user/repos?token=%s", token), &api.CreateRepoOption{ + req := NewRequestWithJSON(t, "POST", "/api/v1/user/repos", &api.CreateRepoOption{ Name: repoName, Description: "repo move around", Private: false, Readme: "Default", AutoInit: true, - }) + }).AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusCreated) DecodeJSON(t, resp, apiRepo) repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: apiRepo.ID}) - req = NewRequestWithJSON(t, "POST", fmt.Sprintf("/api/v1/repos/%s/%s/transfer?token=%s", repo.OwnerName, repo.Name, token), &api.TransferRepoOption{ + req = NewRequestWithJSON(t, "POST", fmt.Sprintf("/api/v1/repos/%s/%s/transfer", repo.OwnerName, repo.Name), &api.TransferRepoOption{ NewOwner: "user4", - }) + }).AddTokenAuth(token) MakeRequest(t, req, http.StatusCreated) return repo @@ -579,18 +585,21 @@ func TestAPIAcceptTransfer(t *testing.T) { // try to accept with not authorized user session := loginUser(t, "user2") token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteRepository, auth_model.AccessTokenScopeWriteUser) - req := NewRequest(t, "POST", fmt.Sprintf("/api/v1/repos/%s/%s/transfer/reject?token=%s", repo.OwnerName, repo.Name, token)) + req := NewRequest(t, "POST", fmt.Sprintf("/api/v1/repos/%s/%s/transfer/reject", repo.OwnerName, repo.Name)). + AddTokenAuth(token) MakeRequest(t, req, http.StatusForbidden) // try to accept repo that's not marked as transferred - req = NewRequest(t, "POST", fmt.Sprintf("/api/v1/repos/%s/%s/transfer/accept?token=%s", "user2", "repo1", token)) + req = NewRequest(t, "POST", fmt.Sprintf("/api/v1/repos/%s/%s/transfer/accept", "user2", "repo1")). + AddTokenAuth(token) MakeRequest(t, req, http.StatusNotFound) // accept transfer session = loginUser(t, "user4") token = getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteRepository, auth_model.AccessTokenScopeWriteUser) - req = NewRequest(t, "POST", fmt.Sprintf("/api/v1/repos/%s/%s/transfer/accept?token=%s", repo.OwnerName, repo.Name, token)) + req = NewRequest(t, "POST", fmt.Sprintf("/api/v1/repos/%s/%s/transfer/accept", repo.OwnerName, repo.Name)). + AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusAccepted) apiRepo := new(api.Repository) DecodeJSON(t, resp, apiRepo) @@ -605,18 +614,21 @@ func TestAPIRejectTransfer(t *testing.T) { // try to reject with not authorized user session := loginUser(t, "user2") token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteRepository) - req := NewRequest(t, "POST", fmt.Sprintf("/api/v1/repos/%s/%s/transfer/reject?token=%s", repo.OwnerName, repo.Name, token)) + req := NewRequest(t, "POST", fmt.Sprintf("/api/v1/repos/%s/%s/transfer/reject", repo.OwnerName, repo.Name)). + AddTokenAuth(token) MakeRequest(t, req, http.StatusForbidden) // try to reject repo that's not marked as transferred - req = NewRequest(t, "POST", fmt.Sprintf("/api/v1/repos/%s/%s/transfer/reject?token=%s", "user2", "repo1", token)) + req = NewRequest(t, "POST", fmt.Sprintf("/api/v1/repos/%s/%s/transfer/reject", "user2", "repo1")). + AddTokenAuth(token) MakeRequest(t, req, http.StatusNotFound) // reject transfer session = loginUser(t, "user4") token = getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteRepository) - req = NewRequest(t, "POST", fmt.Sprintf("/api/v1/repos/%s/%s/transfer/reject?token=%s", repo.OwnerName, repo.Name, token)) + req = NewRequest(t, "POST", fmt.Sprintf("/api/v1/repos/%s/%s/transfer/reject", repo.OwnerName, repo.Name)). + AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusOK) apiRepo := new(api.Repository) DecodeJSON(t, resp, apiRepo) @@ -634,26 +646,26 @@ func TestAPIGenerateRepo(t *testing.T) { // user repo := new(api.Repository) - req := NewRequestWithJSON(t, "POST", fmt.Sprintf("/api/v1/repos/%s/%s/generate?token=%s", templateRepo.OwnerName, templateRepo.Name, token), &api.GenerateRepoOption{ + req := NewRequestWithJSON(t, "POST", fmt.Sprintf("/api/v1/repos/%s/%s/generate", templateRepo.OwnerName, templateRepo.Name), &api.GenerateRepoOption{ Owner: user.Name, Name: "new-repo", Description: "test generate repo", Private: false, GitContent: true, - }) + }).AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusCreated) DecodeJSON(t, resp, repo) assert.Equal(t, "new-repo", repo.Name) // org - req = NewRequestWithJSON(t, "POST", fmt.Sprintf("/api/v1/repos/%s/%s/generate?token=%s", templateRepo.OwnerName, templateRepo.Name, token), &api.GenerateRepoOption{ + req = NewRequestWithJSON(t, "POST", fmt.Sprintf("/api/v1/repos/%s/%s/generate", templateRepo.OwnerName, templateRepo.Name), &api.GenerateRepoOption{ Owner: "org3", Name: "new-repo", Description: "test generate repo", Private: false, GitContent: true, - }) + }).AddTokenAuth(token) resp = MakeRequest(t, req, http.StatusCreated) DecodeJSON(t, resp, repo) @@ -667,7 +679,8 @@ func TestAPIRepoGetReviewers(t *testing.T) { token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeReadRepository) repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}) - req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/reviewers?token=%s", user.Name, repo.Name, token) + req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/reviewers", user.Name, repo.Name). + AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusOK) var reviewers []*api.User DecodeJSON(t, resp, &reviewers) @@ -681,7 +694,8 @@ func TestAPIRepoGetAssignees(t *testing.T) { token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeReadRepository) repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}) - req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/assignees?token=%s", user.Name, repo.Name, token) + req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/assignees", user.Name, repo.Name). + AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusOK) var assignees []*api.User DecodeJSON(t, resp, &assignees) diff --git a/tests/integration/api_repo_topic_test.go b/tests/integration/api_repo_topic_test.go index e7c9b95543b..c41bc4abb63 100644 --- a/tests/integration/api_repo_topic_test.go +++ b/tests/integration/api_repo_topic_test.go @@ -63,30 +63,33 @@ func TestAPIRepoTopic(t *testing.T) { token2 := getUserToken(t, user2.Name, auth_model.AccessTokenScopeWriteRepository) // Test read topics using login - url := fmt.Sprintf("/api/v1/repos/%s/%s/topics", user2.Name, repo2.Name) - req := NewRequest(t, "GET", url+"?token="+token2) + req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/repos/%s/%s/topics", user2.Name, repo2.Name)). + AddTokenAuth(token2) res := MakeRequest(t, req, http.StatusOK) var topics *api.TopicName DecodeJSON(t, res, &topics) assert.ElementsMatch(t, []string{"topicname1", "topicname2"}, topics.TopicNames) - // Log out user2 - url = fmt.Sprintf("/api/v1/repos/%s/%s/topics?token=%s", user2.Name, repo2.Name, token2) - // Test delete a topic - req = NewRequestf(t, "DELETE", "/api/v1/repos/%s/%s/topics/%s?token=%s", user2.Name, repo2.Name, "Topicname1", token2) + req = NewRequestf(t, "DELETE", "/api/v1/repos/%s/%s/topics/%s", user2.Name, repo2.Name, "Topicname1"). + AddTokenAuth(token2) MakeRequest(t, req, http.StatusNoContent) // Test add an existing topic - req = NewRequestf(t, "PUT", "/api/v1/repos/%s/%s/topics/%s?token=%s", user2.Name, repo2.Name, "Golang", token2) + req = NewRequestf(t, "PUT", "/api/v1/repos/%s/%s/topics/%s", user2.Name, repo2.Name, "Golang"). + AddTokenAuth(token2) MakeRequest(t, req, http.StatusNoContent) // Test add a topic - req = NewRequestf(t, "PUT", "/api/v1/repos/%s/%s/topics/%s?token=%s", user2.Name, repo2.Name, "topicName3", token2) + req = NewRequestf(t, "PUT", "/api/v1/repos/%s/%s/topics/%s", user2.Name, repo2.Name, "topicName3"). + AddTokenAuth(token2) MakeRequest(t, req, http.StatusNoContent) + url := fmt.Sprintf("/api/v1/repos/%s/%s/topics", user2.Name, repo2.Name) + // Test read topics using token - req = NewRequest(t, "GET", url) + req = NewRequest(t, "GET", url). + AddTokenAuth(token2) res = MakeRequest(t, req, http.StatusOK) DecodeJSON(t, res, &topics) assert.ElementsMatch(t, []string{"topicname2", "golang", "topicname3"}, topics.TopicNames) @@ -95,9 +98,10 @@ func TestAPIRepoTopic(t *testing.T) { newTopics := []string{" windows ", " ", "MAC "} req = NewRequestWithJSON(t, "PUT", url, &api.RepoTopicOptions{ Topics: newTopics, - }) + }).AddTokenAuth(token2) MakeRequest(t, req, http.StatusNoContent) - req = NewRequest(t, "GET", url) + req = NewRequest(t, "GET", url). + AddTokenAuth(token2) res = MakeRequest(t, req, http.StatusOK) DecodeJSON(t, res, &topics) assert.ElementsMatch(t, []string{"windows", "mac"}, topics.TopicNames) @@ -106,9 +110,10 @@ func TestAPIRepoTopic(t *testing.T) { newTopics = []string{"topicname1", "topicname2", "topicname!"} req = NewRequestWithJSON(t, "PUT", url, &api.RepoTopicOptions{ Topics: newTopics, - }) + }).AddTokenAuth(token2) MakeRequest(t, req, http.StatusUnprocessableEntity) - req = NewRequest(t, "GET", url) + req = NewRequest(t, "GET", url). + AddTokenAuth(token2) res = MakeRequest(t, req, http.StatusOK) DecodeJSON(t, res, &topics) assert.ElementsMatch(t, []string{"windows", "mac"}, topics.TopicNames) @@ -117,9 +122,10 @@ func TestAPIRepoTopic(t *testing.T) { newTopics = []string{"t1", "t2", "t1", "t3", "t4", "t5", "t6", "t7", "t8", "t9", "t10", "t11", "t12", "t13", "t14", "t15", "t16", "17", "t18", "t19", "t20", "t21", "t22", "t23", "t24", "t25"} req = NewRequestWithJSON(t, "PUT", url, &api.RepoTopicOptions{ Topics: newTopics, - }) + }).AddTokenAuth(token2) MakeRequest(t, req, http.StatusNoContent) - req = NewRequest(t, "GET", url) + req = NewRequest(t, "GET", url). + AddTokenAuth(token2) res = MakeRequest(t, req, http.StatusOK) DecodeJSON(t, res, &topics) assert.Len(t, topics.TopicNames, 25) @@ -128,28 +134,31 @@ func TestAPIRepoTopic(t *testing.T) { newTopics = append(newTopics, "t26") req = NewRequestWithJSON(t, "PUT", url, &api.RepoTopicOptions{ Topics: newTopics, - }) + }).AddTokenAuth(token2) MakeRequest(t, req, http.StatusUnprocessableEntity) // Test add a topic when there is already maximum - req = NewRequestf(t, "PUT", "/api/v1/repos/%s/%s/topics/%s?token=%s", user2.Name, repo2.Name, "t26", token2) + req = NewRequestf(t, "PUT", "/api/v1/repos/%s/%s/topics/%s", user2.Name, repo2.Name, "t26"). + AddTokenAuth(token2) MakeRequest(t, req, http.StatusUnprocessableEntity) // Test delete a topic that repo doesn't have - req = NewRequestf(t, "DELETE", "/api/v1/repos/%s/%s/topics/%s?token=%s", user2.Name, repo2.Name, "Topicname1", token2) + req = NewRequestf(t, "DELETE", "/api/v1/repos/%s/%s/topics/%s", user2.Name, repo2.Name, "Topicname1"). + AddTokenAuth(token2) MakeRequest(t, req, http.StatusNotFound) // Get user4's token token4 := getUserToken(t, user4.Name, auth_model.AccessTokenScopeWriteRepository) // Test read topics with write access - url = fmt.Sprintf("/api/v1/repos/%s/%s/topics?token=%s", org3.Name, repo3.Name, token4) - req = NewRequest(t, "GET", url) + req = NewRequest(t, "GET", fmt.Sprintf("/api/v1/repos/%s/%s/topics", org3.Name, repo3.Name)). + AddTokenAuth(token4) res = MakeRequest(t, req, http.StatusOK) DecodeJSON(t, res, &topics) assert.Empty(t, topics.TopicNames) // Test add a topic to repo with write access (requires repo admin access) - req = NewRequestf(t, "PUT", "/api/v1/repos/%s/%s/topics/%s?token=%s", org3.Name, repo3.Name, "topicName", token4) + req = NewRequestf(t, "PUT", "/api/v1/repos/%s/%s/topics/%s", org3.Name, repo3.Name, "topicName"). + AddTokenAuth(token4) MakeRequest(t, req, http.StatusForbidden) } diff --git a/tests/integration/api_team_test.go b/tests/integration/api_team_test.go index a9ae8907174..4df545284e9 100644 --- a/tests/integration/api_team_test.go +++ b/tests/integration/api_team_test.go @@ -34,7 +34,8 @@ func TestAPITeam(t *testing.T) { session := loginUser(t, user.Name) token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeReadOrganization) - req := NewRequestf(t, "GET", "/api/v1/teams/%d?token="+token, teamUser.TeamID) + req := NewRequestf(t, "GET", "/api/v1/teams/%d", teamUser.TeamID). + AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusOK) var apiTeam api.Team @@ -49,7 +50,8 @@ func TestAPITeam(t *testing.T) { session = loginUser(t, user2.Name) token = getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeReadOrganization) - req = NewRequestf(t, "GET", "/api/v1/teams/%d?token="+token, teamUser.TeamID) + req = NewRequestf(t, "GET", "/api/v1/teams/%d", teamUser.TeamID). + AddTokenAuth(token) _ = MakeRequest(t, req, http.StatusForbidden) req = NewRequestf(t, "GET", "/api/v1/teams/%d", teamUser.TeamID) @@ -70,7 +72,8 @@ func TestAPITeam(t *testing.T) { Permission: "write", Units: []string{"repo.code", "repo.issues"}, } - req = NewRequestWithJSON(t, "POST", fmt.Sprintf("/api/v1/orgs/%s/teams?token=%s", org.Name, token), teamToCreate) + req = NewRequestWithJSON(t, "POST", fmt.Sprintf("/api/v1/orgs/%s/teams", org.Name), teamToCreate). + AddTokenAuth(token) resp = MakeRequest(t, req, http.StatusCreated) apiTeam = api.Team{} DecodeJSON(t, resp, &apiTeam) @@ -91,7 +94,8 @@ func TestAPITeam(t *testing.T) { Units: []string{"repo.code", "repo.pulls", "repo.releases"}, } - req = NewRequestWithJSON(t, "PATCH", fmt.Sprintf("/api/v1/teams/%d?token=%s", teamID, token), teamToEdit) + req = NewRequestWithJSON(t, "PATCH", fmt.Sprintf("/api/v1/teams/%d", teamID), teamToEdit). + AddTokenAuth(token) resp = MakeRequest(t, req, http.StatusOK) apiTeam = api.Team{} DecodeJSON(t, resp, &apiTeam) @@ -103,7 +107,8 @@ func TestAPITeam(t *testing.T) { // Edit team Description only editDescription = "first team" teamToEditDesc := api.EditTeamOption{Description: &editDescription} - req = NewRequestWithJSON(t, "PATCH", fmt.Sprintf("/api/v1/teams/%d?token=%s", teamID, token), teamToEditDesc) + req = NewRequestWithJSON(t, "PATCH", fmt.Sprintf("/api/v1/teams/%d", teamID), teamToEditDesc). + AddTokenAuth(token) resp = MakeRequest(t, req, http.StatusOK) apiTeam = api.Team{} DecodeJSON(t, resp, &apiTeam) @@ -115,7 +120,8 @@ func TestAPITeam(t *testing.T) { // Read team. teamRead := unittest.AssertExistsAndLoadBean(t, &organization.Team{ID: teamID}) assert.NoError(t, teamRead.LoadUnits(db.DefaultContext)) - req = NewRequestf(t, "GET", "/api/v1/teams/%d?token="+token, teamID) + req = NewRequestf(t, "GET", "/api/v1/teams/%d", teamID). + AddTokenAuth(token) resp = MakeRequest(t, req, http.StatusOK) apiTeam = api.Team{} DecodeJSON(t, resp, &apiTeam) @@ -123,7 +129,8 @@ func TestAPITeam(t *testing.T) { teamRead.AccessMode.String(), teamRead.GetUnitNames(), teamRead.GetUnitsMap()) // Delete team. - req = NewRequestf(t, "DELETE", "/api/v1/teams/%d?token="+token, teamID) + req = NewRequestf(t, "DELETE", "/api/v1/teams/%d", teamID). + AddTokenAuth(token) MakeRequest(t, req, http.StatusNoContent) unittest.AssertNotExistsBean(t, &organization.Team{ID: teamID}) @@ -136,7 +143,8 @@ func TestAPITeam(t *testing.T) { Permission: "write", UnitsMap: map[string]string{"repo.code": "read", "repo.issues": "write", "repo.wiki": "none"}, } - req = NewRequestWithJSON(t, "POST", fmt.Sprintf("/api/v1/orgs/%s/teams?token=%s", org.Name, token), teamToCreate) + req = NewRequestWithJSON(t, "POST", fmt.Sprintf("/api/v1/orgs/%s/teams", org.Name), teamToCreate). + AddTokenAuth(token) resp = MakeRequest(t, req, http.StatusCreated) apiTeam = api.Team{} DecodeJSON(t, resp, &apiTeam) @@ -157,7 +165,8 @@ func TestAPITeam(t *testing.T) { UnitsMap: map[string]string{"repo.code": "read", "repo.pulls": "read", "repo.releases": "write"}, } - req = NewRequestWithJSON(t, "PATCH", fmt.Sprintf("/api/v1/teams/%d?token=%s", teamID, token), teamToEdit) + req = NewRequestWithJSON(t, "PATCH", fmt.Sprintf("/api/v1/teams/%d", teamID), teamToEdit). + AddTokenAuth(token) resp = MakeRequest(t, req, http.StatusOK) apiTeam = api.Team{} DecodeJSON(t, resp, &apiTeam) @@ -169,7 +178,8 @@ func TestAPITeam(t *testing.T) { // Edit team Description only editDescription = "second team" teamToEditDesc = api.EditTeamOption{Description: &editDescription} - req = NewRequestWithJSON(t, "PATCH", fmt.Sprintf("/api/v1/teams/%d?token=%s", teamID, token), teamToEditDesc) + req = NewRequestWithJSON(t, "PATCH", fmt.Sprintf("/api/v1/teams/%d", teamID), teamToEditDesc). + AddTokenAuth(token) resp = MakeRequest(t, req, http.StatusOK) apiTeam = api.Team{} DecodeJSON(t, resp, &apiTeam) @@ -180,7 +190,8 @@ func TestAPITeam(t *testing.T) { // Read team. teamRead = unittest.AssertExistsAndLoadBean(t, &organization.Team{ID: teamID}) - req = NewRequestf(t, "GET", "/api/v1/teams/%d?token="+token, teamID) + req = NewRequestf(t, "GET", "/api/v1/teams/%d", teamID). + AddTokenAuth(token) resp = MakeRequest(t, req, http.StatusOK) apiTeam = api.Team{} DecodeJSON(t, resp, &apiTeam) @@ -189,7 +200,8 @@ func TestAPITeam(t *testing.T) { teamRead.AccessMode.String(), teamRead.GetUnitNames(), teamRead.GetUnitsMap()) // Delete team. - req = NewRequestf(t, "DELETE", "/api/v1/teams/%d?token="+token, teamID) + req = NewRequestf(t, "DELETE", "/api/v1/teams/%d", teamID). + AddTokenAuth(token) MakeRequest(t, req, http.StatusNoContent) unittest.AssertNotExistsBean(t, &organization.Team{ID: teamID}) @@ -200,7 +212,8 @@ func TestAPITeam(t *testing.T) { IncludesAllRepositories: true, Permission: "admin", } - req = NewRequestWithJSON(t, "POST", fmt.Sprintf("/api/v1/orgs/%s/teams?token=%s", org.Name, token), teamToCreate) + req = NewRequestWithJSON(t, "POST", fmt.Sprintf("/api/v1/orgs/%s/teams", org.Name), teamToCreate). + AddTokenAuth(token) resp = MakeRequest(t, req, http.StatusCreated) apiTeam = api.Team{} DecodeJSON(t, resp, &apiTeam) @@ -219,7 +232,8 @@ func TestAPITeam(t *testing.T) { teamID = apiTeam.ID // Delete team. - req = NewRequestf(t, "DELETE", "/api/v1/teams/%d?token="+token, teamID) + req = NewRequestf(t, "DELETE", "/api/v1/teams/%d", teamID). + AddTokenAuth(token) MakeRequest(t, req, http.StatusNoContent) unittest.AssertNotExistsBean(t, &organization.Team{ID: teamID}) } @@ -263,7 +277,8 @@ func TestAPITeamSearch(t *testing.T) { var results TeamSearchResults token := getUserToken(t, user.Name, auth_model.AccessTokenScopeReadOrganization) - req := NewRequestf(t, "GET", "/api/v1/orgs/%s/teams/search?q=%s&token=%s", org.Name, "_team", token) + req := NewRequestf(t, "GET", "/api/v1/orgs/%s/teams/search?q=%s", org.Name, "_team"). + AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusOK) DecodeJSON(t, resp, &results) assert.NotEmpty(t, results.Data) @@ -274,7 +289,8 @@ func TestAPITeamSearch(t *testing.T) { user5 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 5}) token5 := getUserToken(t, user5.Name, auth_model.AccessTokenScopeReadOrganization) - req = NewRequestf(t, "GET", "/api/v1/orgs/%s/teams/search?q=%s&token=%s", org.Name, "team", token5) + req = NewRequestf(t, "GET", "/api/v1/orgs/%s/teams/search?q=%s", org.Name, "team"). + AddTokenAuth(token5) MakeRequest(t, req, http.StatusForbidden) } @@ -288,7 +304,8 @@ func TestAPIGetTeamRepo(t *testing.T) { var results api.Repository token := getUserToken(t, user.Name, auth_model.AccessTokenScopeReadOrganization) - req := NewRequestf(t, "GET", "/api/v1/teams/%d/repos/%s/?token=%s", team.ID, teamRepo.FullName(), token) + req := NewRequestf(t, "GET", "/api/v1/teams/%d/repos/%s/", team.ID, teamRepo.FullName()). + AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusOK) DecodeJSON(t, resp, &results) assert.Equal(t, "big_test_private_4", teamRepo.Name) @@ -297,6 +314,7 @@ func TestAPIGetTeamRepo(t *testing.T) { user5 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 5}) token5 := getUserToken(t, user5.Name, auth_model.AccessTokenScopeReadOrganization) - req = NewRequestf(t, "GET", "/api/v1/teams/%d/repos/%s/?token=%s", team.ID, teamRepo.FullName(), token5) + req = NewRequestf(t, "GET", "/api/v1/teams/%d/repos/%s/", team.ID, teamRepo.FullName()). + AddTokenAuth(token5) MakeRequest(t, req, http.StatusNotFound) } diff --git a/tests/integration/api_team_user_test.go b/tests/integration/api_team_user_test.go index aa33c690413..6c80bc9f80b 100644 --- a/tests/integration/api_team_user_test.go +++ b/tests/integration/api_team_user_test.go @@ -25,10 +25,12 @@ func TestAPITeamUser(t *testing.T) { normalUsername := "user2" session := loginUser(t, normalUsername) token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeReadOrganization) - req := NewRequest(t, "GET", "/api/v1/teams/1/members/user1?token="+token) + req := NewRequest(t, "GET", "/api/v1/teams/1/members/user1"). + AddTokenAuth(token) MakeRequest(t, req, http.StatusNotFound) - req = NewRequest(t, "GET", "/api/v1/teams/1/members/user2?token="+token) + req = NewRequest(t, "GET", "/api/v1/teams/1/members/user2"). + AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusOK) var user2 *api.User DecodeJSON(t, resp, &user2) diff --git a/tests/integration/api_token_test.go b/tests/integration/api_token_test.go index e28d9a372f3..9c7bf37330d 100644 --- a/tests/integration/api_token_test.go +++ b/tests/integration/api_token_test.go @@ -35,8 +35,8 @@ func TestAPIDeleteMissingToken(t *testing.T) { defer tests.PrepareTestEnv(t)() user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1}) - req := NewRequestf(t, "DELETE", "/api/v1/users/user1/tokens/%d", unittest.NonexistentID) - req = AddBasicAuthHeader(req, user.Name) + req := NewRequestf(t, "DELETE", "/api/v1/users/user1/tokens/%d", unittest.NonexistentID). + AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusNotFound) } @@ -46,20 +46,20 @@ func TestAPIGetTokensPermission(t *testing.T) { // admin can get tokens for other users user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1}) - req := NewRequestf(t, "GET", "/api/v1/users/user2/tokens") - req = AddBasicAuthHeader(req, user.Name) + req := NewRequest(t, "GET", "/api/v1/users/user2/tokens"). + AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusOK) // non-admin can get tokens for himself user = unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) - req = NewRequestf(t, "GET", "/api/v1/users/user2/tokens") - req = AddBasicAuthHeader(req, user.Name) + req = NewRequest(t, "GET", "/api/v1/users/user2/tokens"). + AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusOK) // non-admin can't get tokens for other users user = unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 4}) - req = NewRequestf(t, "GET", "/api/v1/users/user2/tokens") - req = AddBasicAuthHeader(req, user.Name) + req = NewRequest(t, "GET", "/api/v1/users/user2/tokens"). + AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusForbidden) } @@ -73,20 +73,20 @@ func TestAPIDeleteTokensPermission(t *testing.T) { // admin can delete tokens for other users createAPIAccessTokenWithoutCleanUp(t, "test-key-1", user2, nil) - req := NewRequestf(t, "DELETE", "/api/v1/users/"+user2.LoginName+"/tokens/test-key-1") - req = AddBasicAuthHeader(req, admin.Name) + req := NewRequest(t, "DELETE", "/api/v1/users/"+user2.LoginName+"/tokens/test-key-1"). + AddBasicAuth(admin.Name) MakeRequest(t, req, http.StatusNoContent) // non-admin can delete tokens for himself createAPIAccessTokenWithoutCleanUp(t, "test-key-2", user2, nil) - req = NewRequestf(t, "DELETE", "/api/v1/users/"+user2.LoginName+"/tokens/test-key-2") - req = AddBasicAuthHeader(req, user2.Name) + req = NewRequest(t, "DELETE", "/api/v1/users/"+user2.LoginName+"/tokens/test-key-2"). + AddBasicAuth(user2.Name) MakeRequest(t, req, http.StatusNoContent) // non-admin can't delete tokens for other users createAPIAccessTokenWithoutCleanUp(t, "test-key-3", user2, nil) - req = NewRequestf(t, "DELETE", "/api/v1/users/"+user2.LoginName+"/tokens/test-key-3") - req = AddBasicAuthHeader(req, user4.Name) + req = NewRequest(t, "DELETE", "/api/v1/users/"+user2.LoginName+"/tokens/test-key-3"). + AddBasicAuth(user4.Name) MakeRequest(t, req, http.StatusForbidden) } @@ -117,9 +117,6 @@ func TestAPIDeniesPermissionBasedOnTokenScope(t *testing.T) { // from other endpoints and not updated. // // Test cases are in alphabetical order by URL. - // - // Note: query parameters are not currently supported since the token is - // appended with `?=token=`. testCases := []requiredScopeTestCase{ { "/api/v1/admin/emails", @@ -526,11 +523,9 @@ func runTestCase(t *testing.T, testCase *requiredScopeTestCase, user *user_model accessToken := createAPIAccessTokenWithoutCleanUp(t, "test-token", user, &unauthorizedScopes) defer deleteAPIAccessToken(t, accessToken, user) - // Add API access token to the URL. - url := fmt.Sprintf("%s?token=%s", testCase.url, accessToken.Token) - // Request the endpoint. Verify that permission is denied. - req := NewRequestf(t, testCase.method, url) + req := NewRequest(t, testCase.method, testCase.url). + AddTokenAuth(accessToken.Token) MakeRequest(t, req, http.StatusForbidden) }) } @@ -552,9 +547,8 @@ func createAPIAccessTokenWithoutCleanUp(t *testing.T, tokenName string, user *us } } log.Debug("Requesting creation of token with scopes: %v", scopes) - req := NewRequestWithJSON(t, "POST", "/api/v1/users/"+user.LoginName+"/tokens", payload) - - req = AddBasicAuthHeader(req, user.Name) + req := NewRequestWithJSON(t, "POST", "/api/v1/users/"+user.LoginName+"/tokens", payload). + AddBasicAuth(user.Name) resp := MakeRequest(t, req, http.StatusCreated) var newAccessToken api.AccessToken @@ -572,8 +566,8 @@ func createAPIAccessTokenWithoutCleanUp(t *testing.T, tokenName string, user *us // createAPIAccessTokenWithoutCleanUp Delete an API access token and assert that // deletion succeeded. func deleteAPIAccessToken(t *testing.T, accessToken api.AccessToken, user *user_model.User) { - req := NewRequestf(t, "DELETE", "/api/v1/users/"+user.LoginName+"/tokens/%d", accessToken.ID) - req = AddBasicAuthHeader(req, user.Name) + req := NewRequestf(t, "DELETE", "/api/v1/users/"+user.LoginName+"/tokens/%d", accessToken.ID). + AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusNoContent) unittest.AssertNotExistsBean(t, &auth_model.AccessToken{ID: accessToken.ID}) diff --git a/tests/integration/api_twofa_test.go b/tests/integration/api_twofa_test.go index 1e5e26b8ccb..aad806b6dc4 100644 --- a/tests/integration/api_twofa_test.go +++ b/tests/integration/api_twofa_test.go @@ -23,8 +23,8 @@ func TestAPITwoFactor(t *testing.T) { user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 16}) - req := NewRequestf(t, "GET", "/api/v1/user") - req = AddBasicAuthHeader(req, user.Name) + req := NewRequest(t, "GET", "/api/v1/user"). + AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusOK) otpKey, err := totp.Generate(totp.GenerateOpts{ @@ -41,15 +41,15 @@ func TestAPITwoFactor(t *testing.T) { assert.NoError(t, auth_model.NewTwoFactor(db.DefaultContext, tfa)) - req = NewRequestf(t, "GET", "/api/v1/user") - req = AddBasicAuthHeader(req, user.Name) + req = NewRequest(t, "GET", "/api/v1/user"). + AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusUnauthorized) passcode, err := totp.GenerateCode(otpKey.Secret(), time.Now()) assert.NoError(t, err) - req = NewRequestf(t, "GET", "/api/v1/user") - req = AddBasicAuthHeader(req, user.Name) + req = NewRequest(t, "GET", "/api/v1/user"). + AddBasicAuth(user.Name) req.Header.Set("X-Gitea-OTP", passcode) MakeRequest(t, req, http.StatusOK) } diff --git a/tests/integration/api_user_avatar_test.go b/tests/integration/api_user_avatar_test.go index 807c119e2c9..5b4546f1504 100644 --- a/tests/integration/api_user_avatar_test.go +++ b/tests/integration/api_user_avatar_test.go @@ -35,14 +35,16 @@ func TestAPIUpdateUserAvatar(t *testing.T) { Image: base64.StdEncoding.EncodeToString(avatar), } - req := NewRequestWithJSON(t, "POST", "/api/v1/user/avatar?token="+token, &opts) + req := NewRequestWithJSON(t, "POST", "/api/v1/user/avatar", &opts). + AddTokenAuth(token) MakeRequest(t, req, http.StatusNoContent) opts = api.UpdateUserAvatarOption{ Image: "Invalid", } - req = NewRequestWithJSON(t, "POST", "/api/v1/user/avatar?token="+token, &opts) + req = NewRequestWithJSON(t, "POST", "/api/v1/user/avatar", &opts). + AddTokenAuth(token) MakeRequest(t, req, http.StatusBadRequest) // Test what happens if you use a file that is not an image @@ -56,7 +58,8 @@ func TestAPIUpdateUserAvatar(t *testing.T) { Image: base64.StdEncoding.EncodeToString(text), } - req = NewRequestWithJSON(t, "POST", "/api/v1/user/avatar?token="+token, &opts) + req = NewRequestWithJSON(t, "POST", "/api/v1/user/avatar", &opts). + AddTokenAuth(token) MakeRequest(t, req, http.StatusInternalServerError) } @@ -67,6 +70,7 @@ func TestAPIDeleteUserAvatar(t *testing.T) { session := loginUser(t, normalUsername) token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteUser) - req := NewRequest(t, "DELETE", "/api/v1/user/avatar?token="+token) + req := NewRequest(t, "DELETE", "/api/v1/user/avatar"). + AddTokenAuth(token) MakeRequest(t, req, http.StatusNoContent) } diff --git a/tests/integration/api_user_email_test.go b/tests/integration/api_user_email_test.go index 9fff42af422..6eeb5474445 100644 --- a/tests/integration/api_user_email_test.go +++ b/tests/integration/api_user_email_test.go @@ -21,7 +21,8 @@ func TestAPIListEmails(t *testing.T) { session := loginUser(t, normalUsername) token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeReadUser) - req := NewRequest(t, "GET", "/api/v1/user/emails?token="+token) + req := NewRequest(t, "GET", "/api/v1/user/emails"). + AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusOK) var emails []*api.Email @@ -52,13 +53,15 @@ func TestAPIAddEmail(t *testing.T) { Emails: []string{"user101@example.com"}, } - req := NewRequestWithJSON(t, "POST", "/api/v1/user/emails?token="+token, &opts) + req := NewRequestWithJSON(t, "POST", "/api/v1/user/emails", &opts). + AddTokenAuth(token) MakeRequest(t, req, http.StatusUnprocessableEntity) opts = api.CreateEmailOption{ Emails: []string{"user2-3@example.com"}, } - req = NewRequestWithJSON(t, "POST", "/api/v1/user/emails?token="+token, &opts) + req = NewRequestWithJSON(t, "POST", "/api/v1/user/emails", &opts). + AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusCreated) var emails []*api.Email @@ -74,7 +77,8 @@ func TestAPIAddEmail(t *testing.T) { opts = api.CreateEmailOption{ Emails: []string{"notAEmail"}, } - req = NewRequestWithJSON(t, "POST", "/api/v1/user/emails?token="+token, &opts) + req = NewRequestWithJSON(t, "POST", "/api/v1/user/emails", &opts). + AddTokenAuth(token) MakeRequest(t, req, http.StatusUnprocessableEntity) } @@ -88,16 +92,19 @@ func TestAPIDeleteEmail(t *testing.T) { opts := api.DeleteEmailOption{ Emails: []string{"user2-3@example.com"}, } - req := NewRequestWithJSON(t, "DELETE", "/api/v1/user/emails?token="+token, &opts) + req := NewRequestWithJSON(t, "DELETE", "/api/v1/user/emails", &opts). + AddTokenAuth(token) MakeRequest(t, req, http.StatusNotFound) opts = api.DeleteEmailOption{ Emails: []string{"user2-2@example.com"}, } - req = NewRequestWithJSON(t, "DELETE", "/api/v1/user/emails?token="+token, &opts) + req = NewRequestWithJSON(t, "DELETE", "/api/v1/user/emails", &opts). + AddTokenAuth(token) MakeRequest(t, req, http.StatusNoContent) - req = NewRequest(t, "GET", "/api/v1/user/emails?token="+token) + req = NewRequest(t, "GET", "/api/v1/user/emails"). + AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusOK) var emails []*api.Email diff --git a/tests/integration/api_user_follow_test.go b/tests/integration/api_user_follow_test.go index 62717af90e2..1762732c10e 100644 --- a/tests/integration/api_user_follow_test.go +++ b/tests/integration/api_user_follow_test.go @@ -30,14 +30,16 @@ func TestAPIFollow(t *testing.T) { t.Run("Follow", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequest(t, "PUT", fmt.Sprintf("/api/v1/user/following/%s?token=%s", user1, token2)) + req := NewRequest(t, "PUT", fmt.Sprintf("/api/v1/user/following/%s", user1)). + AddTokenAuth(token2) MakeRequest(t, req, http.StatusNoContent) }) t.Run("ListFollowing", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/users/%s/following?token=%s", user2, token2)) + req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/users/%s/following", user2)). + AddTokenAuth(token2) resp := MakeRequest(t, req, http.StatusOK) var users []api.User @@ -49,7 +51,8 @@ func TestAPIFollow(t *testing.T) { t.Run("ListMyFollowing", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/user/following?token=%s", token2)) + req := NewRequest(t, "GET", "/api/v1/user/following"). + AddTokenAuth(token2) resp := MakeRequest(t, req, http.StatusOK) var users []api.User @@ -61,7 +64,8 @@ func TestAPIFollow(t *testing.T) { t.Run("ListFollowers", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/users/%s/followers?token=%s", user1, token1)) + req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/users/%s/followers", user1)). + AddTokenAuth(token1) resp := MakeRequest(t, req, http.StatusOK) var users []api.User @@ -73,7 +77,8 @@ func TestAPIFollow(t *testing.T) { t.Run("ListMyFollowers", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/user/followers?token=%s", token1)) + req := NewRequest(t, "GET", "/api/v1/user/followers"). + AddTokenAuth(token1) resp := MakeRequest(t, req, http.StatusOK) var users []api.User @@ -85,27 +90,32 @@ func TestAPIFollow(t *testing.T) { t.Run("CheckFollowing", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/users/%s/following/%s?token=%s", user2, user1, token2)) + req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/users/%s/following/%s", user2, user1)). + AddTokenAuth(token2) MakeRequest(t, req, http.StatusNoContent) - req = NewRequest(t, "GET", fmt.Sprintf("/api/v1/users/%s/following/%s?token=%s", user1, user2, token2)) + req = NewRequest(t, "GET", fmt.Sprintf("/api/v1/users/%s/following/%s", user1, user2)). + AddTokenAuth(token2) MakeRequest(t, req, http.StatusNotFound) }) t.Run("CheckMyFollowing", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/user/following/%s?token=%s", user1, token2)) + req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/user/following/%s", user1)). + AddTokenAuth(token2) MakeRequest(t, req, http.StatusNoContent) - req = NewRequest(t, "GET", fmt.Sprintf("/api/v1/user/following/%s?token=%s", user2, token1)) + req = NewRequest(t, "GET", fmt.Sprintf("/api/v1/user/following/%s", user2)). + AddTokenAuth(token1) MakeRequest(t, req, http.StatusNotFound) }) t.Run("Unfollow", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequest(t, "DELETE", fmt.Sprintf("/api/v1/user/following/%s?token=%s", user1, token2)) + req := NewRequest(t, "DELETE", fmt.Sprintf("/api/v1/user/following/%s", user1)). + AddTokenAuth(token2) MakeRequest(t, req, http.StatusNoContent) }) } diff --git a/tests/integration/api_user_heatmap_test.go b/tests/integration/api_user_heatmap_test.go index 5a7e58a02d6..a49bdd0c252 100644 --- a/tests/integration/api_user_heatmap_test.go +++ b/tests/integration/api_user_heatmap_test.go @@ -27,8 +27,8 @@ func TestUserHeatmap(t *testing.T) { timeutil.Set(fakeNow) defer timeutil.Unset() - urlStr := fmt.Sprintf("/api/v1/users/%s/heatmap?token=%s", normalUsername, token) - req := NewRequest(t, "GET", urlStr) + req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/users/%s/heatmap", normalUsername)). + AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusOK) var heatmap []*activities_model.UserHeatmapData DecodeJSON(t, resp, &heatmap) diff --git a/tests/integration/api_user_info_test.go b/tests/integration/api_user_info_test.go index cf42b50a4d5..89f72668597 100644 --- a/tests/integration/api_user_info_test.go +++ b/tests/integration/api_user_info_test.go @@ -31,7 +31,8 @@ func TestAPIUserInfo(t *testing.T) { t.Run("GetInfo", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/users/%s?token=%s", user2, token)) + req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/users/%s", user2)). + AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusOK) var u api.User @@ -48,7 +49,8 @@ func TestAPIUserInfo(t *testing.T) { assert.Equal(t, org3.GetPlaceholderEmail(), u.Email) // Test if the correct Mail is returned if a User is logged in - req = NewRequest(t, "GET", fmt.Sprintf("/api/v1/users/%s?token=%s", org3.Name, token)) + req = NewRequest(t, "GET", fmt.Sprintf("/api/v1/users/%s", org3.Name)). + AddTokenAuth(token) resp = MakeRequest(t, req, http.StatusOK) DecodeJSON(t, resp, &u) assert.Equal(t, org3.GetEmail(), u.Email) @@ -57,7 +59,8 @@ func TestAPIUserInfo(t *testing.T) { t.Run("GetAuthenticatedUser", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/user?token=%s", token)) + req := NewRequest(t, "GET", "/api/v1/user"). + AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusOK) var u api.User diff --git a/tests/integration/api_user_org_perm_test.go b/tests/integration/api_user_org_perm_test.go index c61004fab44..85bb1db1709 100644 --- a/tests/integration/api_user_org_perm_test.go +++ b/tests/integration/api_user_org_perm_test.go @@ -35,7 +35,8 @@ func sampleTest(t *testing.T, auoptc apiUserOrgPermTestCase) { session := loginUser(t, auoptc.LoginUser) token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeReadOrganization, auth_model.AccessTokenScopeReadUser) - req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/users/%s/orgs/%s/permissions?token=%s", auoptc.User, auoptc.Organization, token)) + req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/users/%s/orgs/%s/permissions", auoptc.User, auoptc.Organization)). + AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusOK) var apiOP api.OrganizationPermissions @@ -128,7 +129,8 @@ func TestUnknowUser(t *testing.T) { session := loginUser(t, "user1") token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeReadUser, auth_model.AccessTokenScopeReadOrganization) - req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/users/unknow/orgs/org25/permissions?token=%s", token)) + req := NewRequest(t, "GET", "/api/v1/users/unknow/orgs/org25/permissions"). + AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusNotFound) var apiError api.APIError @@ -142,7 +144,8 @@ func TestUnknowOrganization(t *testing.T) { session := loginUser(t, "user1") token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeReadUser, auth_model.AccessTokenScopeReadOrganization) - req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/users/user1/orgs/unknow/permissions?token=%s", token)) + req := NewRequest(t, "GET", "/api/v1/users/user1/orgs/unknow/permissions"). + AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusNotFound) var apiError api.APIError DecodeJSON(t, resp, &apiError) diff --git a/tests/integration/api_user_orgs_test.go b/tests/integration/api_user_orgs_test.go index 51830961aca..b6b4b6f2b2d 100644 --- a/tests/integration/api_user_orgs_test.go +++ b/tests/integration/api_user_orgs_test.go @@ -74,8 +74,8 @@ func getUserOrgs(t *testing.T, userDoer, userCheck string) (orgs []*api.Organiza if len(userDoer) != 0 { token = getUserToken(t, userDoer, auth_model.AccessTokenScopeReadOrganization, auth_model.AccessTokenScopeReadUser) } - urlStr := fmt.Sprintf("/api/v1/users/%s/orgs?token=%s", userCheck, token) - req := NewRequest(t, "GET", urlStr) + req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/users/%s/orgs", userCheck)). + AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusOK) DecodeJSON(t, resp, &orgs) return orgs @@ -95,7 +95,8 @@ func TestMyOrgs(t *testing.T) { normalUsername := "user2" token := getUserToken(t, normalUsername, auth_model.AccessTokenScopeReadOrganization, auth_model.AccessTokenScopeReadUser) - req = NewRequest(t, "GET", "/api/v1/user/orgs?token="+token) + req = NewRequest(t, "GET", "/api/v1/user/orgs"). + AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusOK) var orgs []*api.Organization DecodeJSON(t, resp, &orgs) diff --git a/tests/integration/api_user_search_test.go b/tests/integration/api_user_search_test.go index ddfeb25234b..f776b353257 100644 --- a/tests/integration/api_user_search_test.go +++ b/tests/integration/api_user_search_test.go @@ -27,7 +27,8 @@ func TestAPIUserSearchLoggedIn(t *testing.T) { session := loginUser(t, adminUsername) token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeReadUser) query := "user2" - req := NewRequestf(t, "GET", "/api/v1/users/search?token=%s&q=%s", token, query) + req := NewRequestf(t, "GET", "/api/v1/users/search?q=%s", query). + AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusOK) var results SearchResults @@ -84,8 +85,8 @@ func TestAPIUserSearchAdminLoggedInUserHidden(t *testing.T) { session := loginUser(t, adminUsername) token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeReadUser) query := "user31" - req := NewRequestf(t, "GET", "/api/v1/users/search?token=%s&q=%s", token, query) - req.SetBasicAuth(token, "x-oauth-basic") + req := NewRequestf(t, "GET", "/api/v1/users/search?q=%s", query). + AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusOK) var results SearchResults diff --git a/tests/integration/api_user_secrets_test.go b/tests/integration/api_user_secrets_test.go index 5909f4b8315..56bf30e8044 100644 --- a/tests/integration/api_user_secrets_test.go +++ b/tests/integration/api_user_secrets_test.go @@ -55,44 +55,47 @@ func TestAPIUserSecrets(t *testing.T) { } for _, c := range cases { - req := NewRequestWithJSON(t, "PUT", fmt.Sprintf("/api/v1/user/actions/secrets/%s?token=%s", c.Name, token), api.CreateOrUpdateSecretOption{ + req := NewRequestWithJSON(t, "PUT", fmt.Sprintf("/api/v1/user/actions/secrets/%s", c.Name), api.CreateOrUpdateSecretOption{ Data: "data", - }) + }).AddTokenAuth(token) MakeRequest(t, req, c.ExpectedStatus) } }) t.Run("Update", func(t *testing.T) { name := "update_secret" - url := fmt.Sprintf("/api/v1/user/actions/secrets/%s?token=%s", name, token) + url := fmt.Sprintf("/api/v1/user/actions/secrets/%s", name) req := NewRequestWithJSON(t, "PUT", url, api.CreateOrUpdateSecretOption{ Data: "initial", - }) + }).AddTokenAuth(token) MakeRequest(t, req, http.StatusCreated) req = NewRequestWithJSON(t, "PUT", url, api.CreateOrUpdateSecretOption{ Data: "changed", - }) + }).AddTokenAuth(token) MakeRequest(t, req, http.StatusNoContent) }) t.Run("Delete", func(t *testing.T) { name := "delete_secret" - url := fmt.Sprintf("/api/v1/user/actions/secrets/%s?token=%s", name, token) + url := fmt.Sprintf("/api/v1/user/actions/secrets/%s", name) req := NewRequestWithJSON(t, "PUT", url, api.CreateOrUpdateSecretOption{ Data: "initial", - }) + }).AddTokenAuth(token) MakeRequest(t, req, http.StatusCreated) - req = NewRequest(t, "DELETE", url) + req = NewRequest(t, "DELETE", url). + AddTokenAuth(token) MakeRequest(t, req, http.StatusNoContent) - req = NewRequest(t, "DELETE", url) + req = NewRequest(t, "DELETE", url). + AddTokenAuth(token) MakeRequest(t, req, http.StatusNotFound) - req = NewRequest(t, "DELETE", fmt.Sprintf("/api/v1/user/actions/secrets/000?token=%s", token)) + req = NewRequest(t, "DELETE", "/api/v1/user/actions/secrets/000"). + AddTokenAuth(token) MakeRequest(t, req, http.StatusBadRequest) }) } diff --git a/tests/integration/api_user_star_test.go b/tests/integration/api_user_star_test.go index 15a555d17d5..50423c80e7a 100644 --- a/tests/integration/api_user_star_test.go +++ b/tests/integration/api_user_star_test.go @@ -28,14 +28,16 @@ func TestAPIStar(t *testing.T) { t.Run("Star", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequest(t, "PUT", fmt.Sprintf("/api/v1/user/starred/%s?token=%s", repo, tokenWithUserScope)) + req := NewRequest(t, "PUT", fmt.Sprintf("/api/v1/user/starred/%s", repo)). + AddTokenAuth(tokenWithUserScope) MakeRequest(t, req, http.StatusNoContent) }) t.Run("GetStarredRepos", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/users/%s/starred?token=%s", user, token)) + req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/users/%s/starred", user)). + AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusOK) assert.Equal(t, "1", resp.Header().Get("X-Total-Count")) @@ -49,7 +51,8 @@ func TestAPIStar(t *testing.T) { t.Run("GetMyStarredRepos", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/user/starred?token=%s", tokenWithUserScope)) + req := NewRequest(t, "GET", "/api/v1/user/starred"). + AddTokenAuth(tokenWithUserScope) resp := MakeRequest(t, req, http.StatusOK) assert.Equal(t, "1", resp.Header().Get("X-Total-Count")) @@ -63,17 +66,20 @@ func TestAPIStar(t *testing.T) { t.Run("IsStarring", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/user/starred/%s?token=%s", repo, tokenWithUserScope)) + req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/user/starred/%s", repo)). + AddTokenAuth(tokenWithUserScope) MakeRequest(t, req, http.StatusNoContent) - req = NewRequest(t, "GET", fmt.Sprintf("/api/v1/user/starred/%s?token=%s", repo+"notexisting", tokenWithUserScope)) + req = NewRequest(t, "GET", fmt.Sprintf("/api/v1/user/starred/%s", repo+"notexisting")). + AddTokenAuth(tokenWithUserScope) MakeRequest(t, req, http.StatusNotFound) }) t.Run("Unstar", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequest(t, "DELETE", fmt.Sprintf("/api/v1/user/starred/%s?token=%s", repo, tokenWithUserScope)) + req := NewRequest(t, "DELETE", fmt.Sprintf("/api/v1/user/starred/%s", repo)). + AddTokenAuth(tokenWithUserScope) MakeRequest(t, req, http.StatusNoContent) }) } diff --git a/tests/integration/api_user_watch_test.go b/tests/integration/api_user_watch_test.go index c07fd288d10..20528959e8c 100644 --- a/tests/integration/api_user_watch_test.go +++ b/tests/integration/api_user_watch_test.go @@ -28,14 +28,16 @@ func TestAPIWatch(t *testing.T) { t.Run("Watch", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequest(t, "PUT", fmt.Sprintf("/api/v1/repos/%s/subscription?token=%s", repo, tokenWithRepoScope)) + req := NewRequest(t, "PUT", fmt.Sprintf("/api/v1/repos/%s/subscription", repo)). + AddTokenAuth(tokenWithRepoScope) MakeRequest(t, req, http.StatusOK) }) t.Run("GetWatchedRepos", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/users/%s/subscriptions?token=%s", user, token)) + req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/users/%s/subscriptions", user)). + AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusOK) assert.Equal(t, "1", resp.Header().Get("X-Total-Count")) @@ -49,7 +51,8 @@ func TestAPIWatch(t *testing.T) { t.Run("GetMyWatchedRepos", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/user/subscriptions?token=%s", tokenWithRepoScope)) + req := NewRequest(t, "GET", "/api/v1/user/subscriptions"). + AddTokenAuth(tokenWithRepoScope) resp := MakeRequest(t, req, http.StatusOK) assert.Equal(t, "1", resp.Header().Get("X-Total-Count")) @@ -63,17 +66,20 @@ func TestAPIWatch(t *testing.T) { t.Run("IsWatching", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/repos/%s/subscription?token=%s", repo, tokenWithRepoScope)) + req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/repos/%s/subscription", repo)). + AddTokenAuth(tokenWithRepoScope) MakeRequest(t, req, http.StatusOK) - req = NewRequest(t, "GET", fmt.Sprintf("/api/v1/repos/%s/subscription?token=%s", repo+"notexisting", tokenWithRepoScope)) + req = NewRequest(t, "GET", fmt.Sprintf("/api/v1/repos/%s/subscription", repo+"notexisting")). + AddTokenAuth(tokenWithRepoScope) MakeRequest(t, req, http.StatusNotFound) }) t.Run("Unwatch", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - req := NewRequest(t, "DELETE", fmt.Sprintf("/api/v1/repos/%s/subscription?token=%s", repo, tokenWithRepoScope)) + req := NewRequest(t, "DELETE", fmt.Sprintf("/api/v1/repos/%s/subscription", repo)). + AddTokenAuth(tokenWithRepoScope) MakeRequest(t, req, http.StatusNoContent) }) } diff --git a/tests/integration/api_wiki_test.go b/tests/integration/api_wiki_test.go index f598982555b..05d90fc4e37 100644 --- a/tests/integration/api_wiki_test.go +++ b/tests/integration/api_wiki_test.go @@ -182,13 +182,13 @@ func TestAPINewWikiPage(t *testing.T) { session := loginUser(t, username) token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteRepository) - urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/wiki/new?token=%s", username, "repo1", token) + urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/wiki/new", username, "repo1") req := NewRequestWithJSON(t, "POST", urlStr, &api.CreateWikiPageOptions{ Title: title, ContentBase64: base64.StdEncoding.EncodeToString([]byte("Wiki page content for API unit tests")), Message: "", - }) + }).AddTokenAuth(token) MakeRequest(t, req, http.StatusCreated) } } @@ -199,13 +199,13 @@ func TestAPIEditWikiPage(t *testing.T) { session := loginUser(t, username) token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteRepository) - urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/wiki/page/Page-With-Spaced-Name?token=%s", username, "repo1", token) + urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/wiki/page/Page-With-Spaced-Name", username, "repo1") req := NewRequestWithJSON(t, "PATCH", urlStr, &api.CreateWikiPageOptions{ Title: "edited title", ContentBase64: base64.StdEncoding.EncodeToString([]byte("Edited wiki page content for API unit tests")), Message: "", - }) + }).AddTokenAuth(token) MakeRequest(t, req, http.StatusOK) } diff --git a/tests/integration/cors_test.go b/tests/integration/cors_test.go index e4151d1c32e..83d200402c8 100644 --- a/tests/integration/cors_test.go +++ b/tests/integration/cors_test.go @@ -14,7 +14,7 @@ import ( func TestCORSNotSet(t *testing.T) { defer tests.PrepareTestEnv(t)() - req := NewRequestf(t, "GET", "/api/v1/version") + req := NewRequest(t, "GET", "/api/v1/version") session := loginUser(t, "user2") resp := session.MakeRequest(t, req, http.StatusOK) assert.Equal(t, resp.Code, http.StatusOK) diff --git a/tests/integration/empty_repo_test.go b/tests/integration/empty_repo_test.go index 78453f28a58..8842de5f6f5 100644 --- a/tests/integration/empty_repo_test.go +++ b/tests/integration/empty_repo_test.go @@ -6,7 +6,6 @@ package integration import ( "bytes" "encoding/base64" - "fmt" "io" "mime/multipart" "net/http" @@ -119,14 +118,13 @@ func TestEmptyRepoAddFileByAPI(t *testing.T) { session := loginUser(t, "user30") token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteRepository) - url := fmt.Sprintf("/api/v1/repos/user30/empty/contents/new-file.txt?token=%s", token) - req := NewRequestWithJSON(t, "POST", url, &api.CreateFileOptions{ + req := NewRequestWithJSON(t, "POST", "/api/v1/repos/user30/empty/contents/new-file.txt", &api.CreateFileOptions{ FileOptions: api.FileOptions{ NewBranchName: "new_branch", Message: "init", }, ContentBase64: base64.StdEncoding.EncodeToString([]byte("newly-added-api-file")), - }) + }).AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusCreated) var fileResponse api.FileResponse @@ -138,7 +136,8 @@ func TestEmptyRepoAddFileByAPI(t *testing.T) { resp = session.MakeRequest(t, req, http.StatusOK) assert.Contains(t, resp.Body.String(), "newly-added-api-file") - req = NewRequest(t, "GET", fmt.Sprintf("/api/v1/repos/user30/empty?token=%s", token)) + req = NewRequest(t, "GET", "/api/v1/repos/user30/empty"). + AddTokenAuth(token) resp = session.MakeRequest(t, req, http.StatusOK) var apiRepo api.Repository DecodeJSON(t, resp, &apiRepo) diff --git a/tests/integration/eventsource_test.go b/tests/integration/eventsource_test.go index 734f4a6a0a3..2ef42189775 100644 --- a/tests/integration/eventsource_test.go +++ b/tests/integration/eventsource_test.go @@ -65,17 +65,20 @@ func TestEventSourceManagerRun(t *testing.T) { var apiNL []api.NotificationThread // -- mark notifications as read -- - req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/notifications?status-types=unread&token=%s", token)) + req := NewRequest(t, "GET", "/api/v1/notifications?status-types=unread"). + AddTokenAuth(token) resp := session.MakeRequest(t, req, http.StatusOK) DecodeJSON(t, resp, &apiNL) assert.Len(t, apiNL, 2) lastReadAt := "2000-01-01T00%3A50%3A01%2B00%3A00" // 946687801 <- only Notification 4 is in this filter ... - req = NewRequest(t, "PUT", fmt.Sprintf("/api/v1/repos/%s/%s/notifications?last_read_at=%s&token=%s", user2.Name, repo1.Name, lastReadAt, token)) + req = NewRequest(t, "PUT", fmt.Sprintf("/api/v1/repos/%s/%s/notifications?last_read_at=%s", user2.Name, repo1.Name, lastReadAt)). + AddTokenAuth(token) session.MakeRequest(t, req, http.StatusResetContent) - req = NewRequest(t, "GET", fmt.Sprintf("/api/v1/notifications?token=%s&status-types=unread", token)) + req = NewRequest(t, "GET", "/api/v1/notifications?status-types=unread"). + AddTokenAuth(token) resp = session.MakeRequest(t, req, http.StatusOK) DecodeJSON(t, resp, &apiNL) assert.Len(t, apiNL, 1) diff --git a/tests/integration/integration_test.go b/tests/integration/integration_test.go index 8534b0393b9..1127de1afcd 100644 --- a/tests/integration/integration_test.go +++ b/tests/integration/integration_test.go @@ -163,14 +163,15 @@ func (s *TestSession) GetCookie(name string) *http.Cookie { return nil } -func (s *TestSession) MakeRequest(t testing.TB, req *http.Request, expectedStatus int) *httptest.ResponseRecorder { +func (s *TestSession) MakeRequest(t testing.TB, rw *RequestWrapper, expectedStatus int) *httptest.ResponseRecorder { t.Helper() + req := rw.Request baseURL, err := url.Parse(setting.AppURL) assert.NoError(t, err) for _, c := range s.jar.Cookies(baseURL) { req.AddCookie(c) } - resp := MakeRequest(t, req, expectedStatus) + resp := MakeRequest(t, rw, expectedStatus) ch := http.Header{} ch.Add("Cookie", strings.Join(resp.Header()["Set-Cookie"], ";")) @@ -180,14 +181,15 @@ func (s *TestSession) MakeRequest(t testing.TB, req *http.Request, expectedStatu return resp } -func (s *TestSession) MakeRequestNilResponseRecorder(t testing.TB, req *http.Request, expectedStatus int) *NilResponseRecorder { +func (s *TestSession) MakeRequestNilResponseRecorder(t testing.TB, rw *RequestWrapper, expectedStatus int) *NilResponseRecorder { t.Helper() + req := rw.Request baseURL, err := url.Parse(setting.AppURL) assert.NoError(t, err) for _, c := range s.jar.Cookies(baseURL) { req.AddCookie(c) } - resp := MakeRequestNilResponseRecorder(t, req, expectedStatus) + resp := MakeRequestNilResponseRecorder(t, rw, expectedStatus) ch := http.Header{} ch.Add("Cookie", strings.Join(resp.Header()["Set-Cookie"], ";")) @@ -197,14 +199,15 @@ func (s *TestSession) MakeRequestNilResponseRecorder(t testing.TB, req *http.Req return resp } -func (s *TestSession) MakeRequestNilResponseHashSumRecorder(t testing.TB, req *http.Request, expectedStatus int) *NilResponseHashSumRecorder { +func (s *TestSession) MakeRequestNilResponseHashSumRecorder(t testing.TB, rw *RequestWrapper, expectedStatus int) *NilResponseHashSumRecorder { t.Helper() + req := rw.Request baseURL, err := url.Parse(setting.AppURL) assert.NoError(t, err) for _, c := range s.jar.Cookies(baseURL) { req.AddCookie(c) } - resp := MakeRequestNilResponseHashSumRecorder(t, req, expectedStatus) + resp := MakeRequestNilResponseHashSumRecorder(t, rw, expectedStatus) ch := http.Header{} ch.Add("Cookie", strings.Join(resp.Header()["Set-Cookie"], ";")) @@ -314,17 +317,42 @@ func getTokenForLoggedInUser(t testing.TB, session *TestSession, scopes ...auth. return token } -func NewRequest(t testing.TB, method, urlStr string) *http.Request { +type RequestWrapper struct { + *http.Request +} + +func (req *RequestWrapper) AddBasicAuth(username string) *RequestWrapper { + req.Request.SetBasicAuth(username, userPassword) + return req +} + +func (req *RequestWrapper) AddTokenAuth(token string) *RequestWrapper { + if token == "" { + return req + } + if !strings.HasPrefix(token, "Bearer ") { + token = "Bearer " + token + } + req.Request.Header.Set("Authorization", token) + return req +} + +func (req *RequestWrapper) SetHeader(name, value string) *RequestWrapper { + req.Request.Header.Set(name, value) + return req +} + +func NewRequest(t testing.TB, method, urlStr string) *RequestWrapper { t.Helper() return NewRequestWithBody(t, method, urlStr, nil) } -func NewRequestf(t testing.TB, method, urlFormat string, args ...any) *http.Request { +func NewRequestf(t testing.TB, method, urlFormat string, args ...any) *RequestWrapper { t.Helper() return NewRequest(t, method, fmt.Sprintf(urlFormat, args...)) } -func NewRequestWithValues(t testing.TB, method, urlStr string, values map[string]string) *http.Request { +func NewRequestWithValues(t testing.TB, method, urlStr string, values map[string]string) *RequestWrapper { t.Helper() urlValues := url.Values{} for key, value := range values { @@ -333,43 +361,38 @@ func NewRequestWithValues(t testing.TB, method, urlStr string, values map[string return NewRequestWithURLValues(t, method, urlStr, urlValues) } -func NewRequestWithURLValues(t testing.TB, method, urlStr string, urlValues url.Values) *http.Request { +func NewRequestWithURLValues(t testing.TB, method, urlStr string, urlValues url.Values) *RequestWrapper { t.Helper() - req := NewRequestWithBody(t, method, urlStr, bytes.NewBufferString(urlValues.Encode())) - req.Header.Add("Content-Type", "application/x-www-form-urlencoded") - return req + return NewRequestWithBody(t, method, urlStr, bytes.NewBufferString(urlValues.Encode())). + SetHeader("Content-Type", "application/x-www-form-urlencoded") } -func NewRequestWithJSON(t testing.TB, method, urlStr string, v any) *http.Request { +func NewRequestWithJSON(t testing.TB, method, urlStr string, v any) *RequestWrapper { t.Helper() jsonBytes, err := json.Marshal(v) assert.NoError(t, err) - req := NewRequestWithBody(t, method, urlStr, bytes.NewBuffer(jsonBytes)) - req.Header.Add("Content-Type", "application/json") - return req + return NewRequestWithBody(t, method, urlStr, bytes.NewBuffer(jsonBytes)). + SetHeader("Content-Type", "application/json") } -func NewRequestWithBody(t testing.TB, method, urlStr string, body io.Reader) *http.Request { +func NewRequestWithBody(t testing.TB, method, urlStr string, body io.Reader) *RequestWrapper { t.Helper() if !strings.HasPrefix(urlStr, "http") && !strings.HasPrefix(urlStr, "/") { urlStr = "/" + urlStr } - request, err := http.NewRequest(method, urlStr, body) + req, err := http.NewRequest(method, urlStr, body) assert.NoError(t, err) - request.RequestURI = urlStr - return request -} + req.RequestURI = urlStr -func AddBasicAuthHeader(request *http.Request, username string) *http.Request { - request.SetBasicAuth(username, userPassword) - return request + return &RequestWrapper{req} } const NoExpectedStatus = -1 -func MakeRequest(t testing.TB, req *http.Request, expectedStatus int) *httptest.ResponseRecorder { +func MakeRequest(t testing.TB, rw *RequestWrapper, expectedStatus int) *httptest.ResponseRecorder { t.Helper() + req := rw.Request recorder := httptest.NewRecorder() if req.RemoteAddr == "" { req.RemoteAddr = "test-mock:12345" @@ -383,8 +406,9 @@ func MakeRequest(t testing.TB, req *http.Request, expectedStatus int) *httptest. return recorder } -func MakeRequestNilResponseRecorder(t testing.TB, req *http.Request, expectedStatus int) *NilResponseRecorder { +func MakeRequestNilResponseRecorder(t testing.TB, rw *RequestWrapper, expectedStatus int) *NilResponseRecorder { t.Helper() + req := rw.Request recorder := NewNilResponseRecorder() testWebRoutes.ServeHTTP(recorder, req) if expectedStatus != NoExpectedStatus { @@ -396,8 +420,9 @@ func MakeRequestNilResponseRecorder(t testing.TB, req *http.Request, expectedSta return recorder } -func MakeRequestNilResponseHashSumRecorder(t testing.TB, req *http.Request, expectedStatus int) *NilResponseHashSumRecorder { +func MakeRequestNilResponseHashSumRecorder(t testing.TB, rw *RequestWrapper, expectedStatus int) *NilResponseHashSumRecorder { t.Helper() + req := rw.Request recorder := NewNilResponseHashSumRecorder() testWebRoutes.ServeHTTP(recorder, req) if expectedStatus != NoExpectedStatus { diff --git a/tests/integration/org_test.go b/tests/integration/org_test.go index aa01678ea94..94c4e197271 100644 --- a/tests/integration/org_test.go +++ b/tests/integration/org_test.go @@ -169,8 +169,8 @@ func TestOrgRestrictedUser(t *testing.T) { Units: []string{"repo.code"}, } - req = NewRequestWithJSON(t, "POST", - fmt.Sprintf("/api/v1/orgs/%s/teams?token=%s", orgName, token), teamToCreate) + req = NewRequestWithJSON(t, "POST", fmt.Sprintf("/api/v1/orgs/%s/teams", orgName), teamToCreate). + AddTokenAuth(token) var apiTeam api.Team @@ -183,8 +183,8 @@ func TestOrgRestrictedUser(t *testing.T) { // teamID := apiTeam.ID // Now we need to add the restricted user to the team - req = NewRequest(t, "PUT", - fmt.Sprintf("/api/v1/teams/%d/members/%s?token=%s", apiTeam.ID, restrictedUser, token)) + req = NewRequest(t, "PUT", fmt.Sprintf("/api/v1/teams/%d/members/%s", apiTeam.ID, restrictedUser)). + AddTokenAuth(token) _ = adminSession.MakeRequest(t, req, http.StatusNoContent) // Now we need to check if the restrictedUser can access the repo diff --git a/tests/integration/privateactivity_test.go b/tests/integration/privateactivity_test.go index 2b9b814106c..5362462f7df 100644 --- a/tests/integration/privateactivity_test.go +++ b/tests/integration/privateactivity_test.go @@ -35,11 +35,11 @@ func testPrivateActivityDoSomethingForActionEntries(t *testing.T) { session := loginUser(t, privateActivityTestUser) token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteIssue) - urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/issues?state=all&token=%s", owner.Name, repoBefore.Name, token) + urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/issues?state=all", owner.Name, repoBefore.Name) req := NewRequestWithJSON(t, "POST", urlStr, &api.CreateIssueOption{ Body: "test", Title: "test", - }) + }).AddTokenAuth(token) session.MakeRequest(t, req, http.StatusCreated) } @@ -127,7 +127,8 @@ func testPrivateActivityHelperHasHeatmapContentFromPublic(t *testing.T) bool { func testPrivateActivityHelperHasHeatmapContentFromSession(t *testing.T, session *TestSession) bool { token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeReadUser) - req := NewRequestf(t, "GET", "/api/v1/users/%s/heatmap?token=%s", privateActivityTestUser, token) + req := NewRequestf(t, "GET", "/api/v1/users/%s/heatmap", privateActivityTestUser). + AddTokenAuth(token) resp := session.MakeRequest(t, req, http.StatusOK) var items []*activities_model.UserHeatmapData diff --git a/tests/integration/pull_merge_test.go b/tests/integration/pull_merge_test.go index a4cc3e76fe9..d17bf4afda1 100644 --- a/tests/integration/pull_merge_test.go +++ b/tests/integration/pull_merge_test.go @@ -218,11 +218,11 @@ func TestCantMergeConflict(t *testing.T) { // Use API to create a conflicting pr token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteRepository) - req := NewRequestWithJSON(t, http.MethodPost, fmt.Sprintf("/api/v1/repos/%s/%s/pulls?token=%s", "user1", "repo1", token), &api.CreatePullRequestOption{ + req := NewRequestWithJSON(t, http.MethodPost, fmt.Sprintf("/api/v1/repos/%s/%s/pulls", "user1", "repo1"), &api.CreatePullRequestOption{ Head: "conflict", Base: "base", Title: "create a conflicting pr", - }) + }).AddTokenAuth(token) session.MakeRequest(t, req, http.StatusCreated) // Now this PR will be marked conflict - or at least a race will do - so drop down to pure code at this point... @@ -326,11 +326,11 @@ func TestCantMergeUnrelated(t *testing.T) { // Use API to create a conflicting pr token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteRepository) - req := NewRequestWithJSON(t, http.MethodPost, fmt.Sprintf("/api/v1/repos/%s/%s/pulls?token=%s", "user1", "repo1", token), &api.CreatePullRequestOption{ + req := NewRequestWithJSON(t, http.MethodPost, fmt.Sprintf("/api/v1/repos/%s/%s/pulls", "user1", "repo1"), &api.CreatePullRequestOption{ Head: "unrelated", Base: "base", Title: "create an unrelated pr", - }) + }).AddTokenAuth(token) session.MakeRequest(t, req, http.StatusCreated) // Now this PR could be marked conflict - or at least a race may occur - so drop down to pure code at this point... diff --git a/tests/integration/pull_status_test.go b/tests/integration/pull_status_test.go index 01cb40d2cf5..26c99e64459 100644 --- a/tests/integration/pull_status_test.go +++ b/tests/integration/pull_status_test.go @@ -77,7 +77,7 @@ func TestPullCreate_CommitStatus(t *testing.T) { Context: "testci", })) - req = NewRequestf(t, "GET", "/user1/repo1/pulls/1/commits") + req = NewRequest(t, "GET", "/user1/repo1/pulls/1/commits") resp = session.MakeRequest(t, req, http.StatusOK) doc = NewHTMLParser(t, resp.Body) @@ -98,9 +98,9 @@ func doAPICreateCommitStatus(ctx APITestContext, commitID string, data api.Creat req := NewRequestWithJSON( t, http.MethodPost, - fmt.Sprintf("/api/v1/repos/%s/%s/statuses/%s?token=%s", ctx.Username, ctx.Reponame, commitID, ctx.Token), + fmt.Sprintf("/api/v1/repos/%s/%s/statuses/%s", ctx.Username, ctx.Reponame, commitID), data, - ) + ).AddTokenAuth(ctx.Token) if ctx.ExpectedCode != 0 { ctx.Session.MakeRequest(t, req, ctx.ExpectedCode) return diff --git a/tests/integration/pull_update_test.go b/tests/integration/pull_update_test.go index e4b2ae65bd6..078253ffb0c 100644 --- a/tests/integration/pull_update_test.go +++ b/tests/integration/pull_update_test.go @@ -40,7 +40,8 @@ func TestAPIPullUpdate(t *testing.T) { session := loginUser(t, "user2") token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteRepository) - req := NewRequestf(t, "POST", "/api/v1/repos/%s/%s/pulls/%d/update?token="+token, pr.BaseRepo.OwnerName, pr.BaseRepo.Name, pr.Issue.Index) + req := NewRequestf(t, "POST", "/api/v1/repos/%s/%s/pulls/%d/update", pr.BaseRepo.OwnerName, pr.BaseRepo.Name, pr.Issue.Index). + AddTokenAuth(token) session.MakeRequest(t, req, http.StatusOK) // Test GetDiverging after update @@ -68,7 +69,8 @@ func TestAPIPullUpdateByRebase(t *testing.T) { session := loginUser(t, "user2") token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteRepository) - req := NewRequestf(t, "POST", "/api/v1/repos/%s/%s/pulls/%d/update?style=rebase&token="+token, pr.BaseRepo.OwnerName, pr.BaseRepo.Name, pr.Issue.Index) + req := NewRequestf(t, "POST", "/api/v1/repos/%s/%s/pulls/%d/update?style=rebase", pr.BaseRepo.OwnerName, pr.BaseRepo.Name, pr.Issue.Index). + AddTokenAuth(token) session.MakeRequest(t, req, http.StatusOK) // Test GetDiverging after update diff --git a/tests/integration/repo_search_test.go b/tests/integration/repo_search_test.go index d113d1e57d0..cf199e98c28 100644 --- a/tests/integration/repo_search_test.go +++ b/tests/integration/repo_search_test.go @@ -51,7 +51,7 @@ func TestSearchRepo(t *testing.T) { } func testSearch(t *testing.T, url string, expected []string) { - req := NewRequestf(t, "GET", url) + req := NewRequest(t, "GET", url) resp := MakeRequest(t, req, http.StatusOK) filenames := resultFilenames(t, NewHTMLParser(t, resp.Body)) diff --git a/tests/integration/user_test.go b/tests/integration/user_test.go index ddde4159607..d8e4c64e854 100644 --- a/tests/integration/user_test.go +++ b/tests/integration/user_test.go @@ -262,7 +262,7 @@ func TestListStopWatches(t *testing.T) { owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}) session := loginUser(t, owner.Name) - req := NewRequestf(t, "GET", "/user/stopwatches") + req := NewRequest(t, "GET", "/user/stopwatches") resp := session.MakeRequest(t, req, http.StatusOK) var apiWatches []*api.StopWatch DecodeJSON(t, resp, &apiWatches) From 21229ed2c8ed00f57100adf9ebc5f4a08da9a66e Mon Sep 17 00:00:00 2001 From: Jason Song Date: Fri, 22 Dec 2023 14:20:59 +0800 Subject: [PATCH 014/189] Add more ways to try (#28581) --- README.md | 7 ++++++- README_ZH.md | 6 +++++- 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index dc396465a7e..5ab5ab85864 100644 --- a/README.md +++ b/README.md @@ -62,11 +62,16 @@ painless way of setting up a self-hosted Git service. As Gitea is written in Go, it works across **all** the platforms and architectures that are supported by Go, including Linux, macOS, and Windows on x86, amd64, ARM and PowerPC architectures. -You can try it out using [the online demo](https://try.gitea.io/). This project has been [forked](https://blog.gitea.com/welcome-to-gitea/) from [Gogs](https://gogs.io) since November of 2016, but a lot has changed. +For online demonstrations, you can visit [try.gitea.io](https://try.gitea.io). + +For accessing free Gitea service (with a limited number of repositories), you can visit [gitea.com](https://gitea.com/user/login). + +To quickly deploy your own dedicated Gitea instance on Gitea Cloud, you can start a free trial at [cloud.gitea.com](https://cloud.gitea.com). + ## Building From the root of the source tree, run: diff --git a/README_ZH.md b/README_ZH.md index dd77c05de8f..b9384a9825b 100644 --- a/README_ZH.md +++ b/README_ZH.md @@ -58,7 +58,11 @@ Gitea 的首要目标是创建一个极易安装,运行非常快速,安装和使用体验良好的自建 Git 服务。我们采用 Go 作为后端语言,这使我们只要生成一个可执行程序即可。并且他还支持跨平台,支持 Linux, macOS 和 Windows 以及各种架构,除了 x86,amd64,还包括 ARM 和 PowerPC。 -如果您想试用一下,请访问 [在线Demo](https://try.gitea.io/)! +如果你想试用在线演示,请访问 [try.gitea.io](https://try.gitea.io/)。 + +如果你想使用免费的 Gitea 服务(有仓库数量限制),请访问 [gitea.com](https://gitea.com/user/login)。 + +如果你想在 Gitea Cloud 上快速部署你自己独享的 Gitea 实例,请访问 [cloud.gitea.com](https://cloud.gitea.com) 开始免费试用。 ## 提示 From 19869d1c11462294c828bc126bf006103239e397 Mon Sep 17 00:00:00 2001 From: morphelinho Date: Fri, 22 Dec 2023 13:23:24 +0100 Subject: [PATCH 015/189] Fix 405 method not allowed CORS / OIDC (#28583) Follow #28184 Follow #28515 Fix problem with 405 method not allowed for CORS wrt OIDC --- routers/web/web.go | 2 ++ 1 file changed, 2 insertions(+) diff --git a/routers/web/web.go b/routers/web/web.go index db0588056b5..359b608c71e 100644 --- a/routers/web/web.go +++ b/routers/web/web.go @@ -532,9 +532,11 @@ func registerRoutes(m *web.Route) { // TODO manage redirection m.Post("/authorize", web.Bind(forms.AuthorizationForm{}), auth.AuthorizeOAuth) }, ignSignInAndCsrf, reqSignIn) + m.Options("/login/oauth/userinfo", CorsHandler(), misc.DummyBadRequest) m.Get("/login/oauth/userinfo", ignSignInAndCsrf, auth.InfoOAuth) m.Options("/login/oauth/access_token", CorsHandler(), misc.DummyBadRequest) m.Post("/login/oauth/access_token", CorsHandler(), web.Bind(forms.AccessTokenForm{}), ignSignInAndCsrf, auth.AccessTokenOAuth) + m.Options("/login/oauth/keys", CorsHandler(), misc.DummyBadRequest) m.Get("/login/oauth/keys", ignSignInAndCsrf, auth.OIDCKeys) m.Options("/login/oauth/introspect", CorsHandler(), misc.DummyBadRequest) m.Post("/login/oauth/introspect", CorsHandler(), web.Bind(forms.IntrospectTokenForm{}), ignSignInAndCsrf, auth.IntrospectOAuth) From 907c97aabbe6fdfa5669ef2b2978f2d217cf0210 Mon Sep 17 00:00:00 2001 From: Zettat123 Date: Fri, 22 Dec 2023 21:29:50 +0800 Subject: [PATCH 016/189] Fix `status_check_contexts` matching bug (#28582) Fix #28570 Follow #24633 --- Copied from https://github.com/go-gitea/gitea/issues/28570#issuecomment-1867327999 The feature introduced in #24633 should be compatible with `status_check_contexts`. However, if one or more of `status_check_contexts` is not a legal glob expressions, `glob.Compile` will fail and the contexts cannot match. https://github.com/go-gitea/gitea/blob/21229ed2c8ed00f57100adf9ebc5f4a08da9a66e/routers/web/repo/pull.go#L653-L663 --- routers/web/repo/pull.go | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/routers/web/repo/pull.go b/routers/web/repo/pull.go index ec109ed665c..39f9cefa5c6 100644 --- a/routers/web/repo/pull.go +++ b/routers/web/repo/pull.go @@ -653,7 +653,15 @@ func PrepareViewPullInfo(ctx *context.Context, issue *issues_model.Issue) *git.C if pb != nil && pb.EnableStatusCheck { ctx.Data["is_context_required"] = func(context string) bool { for _, c := range pb.StatusCheckContexts { - if gp, err := glob.Compile(c); err == nil && gp.Match(context) { + if c == context { + return true + } + if gp, err := glob.Compile(c); err != nil { + // All newly created status_check_contexts are checked to ensure they are valid glob expressions before being stored in the database. + // But some old status_check_context created before glob was introduced may be invalid glob expressions. + // So log the error here for debugging. + log.Error("compile glob %q: %v", c, err) + } else if gp.Match(context) { return true } } From d9ed931c4d7ad3649a84913daf81ec252bbbaba1 Mon Sep 17 00:00:00 2001 From: Yarden Shoham Date: Fri, 22 Dec 2023 18:53:12 +0200 Subject: [PATCH 017/189] Fix wrong due date rendering in issue list page (#28588) It included the hours, minutes, and seconds. By removing these, the date renders correctly. Signed-off-by: Yarden Shoham --- templates/shared/issuelist.tmpl | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/templates/shared/issuelist.tmpl b/templates/shared/issuelist.tmpl index 7fd1f4e0f8d..4fea93be3c6 100644 --- a/templates/shared/issuelist.tmpl +++ b/templates/shared/issuelist.tmpl @@ -114,7 +114,7 @@ {{svg "octicon-calendar" 14}} - {{DateTime "short" .DeadlineUnix}} + {{DateTime "short" (.DeadlineUnix.Format "2006-01-02")}} {{end}} From 33439b733a4f69640350b9cda370963ebe9d1e0a Mon Sep 17 00:00:00 2001 From: Kyle D Date: Fri, 22 Dec 2023 22:29:51 -0500 Subject: [PATCH 018/189] Disable query token param in integration tests (#28592) Follow up to https://github.com/go-gitea/gitea/pull/28484, this PR enables the setting for integration tests and migrates a few additional test queries. --- tests/integration/api_issue_test.go | 55 +++++++++++----------- tests/integration/api_releases_test.go | 3 +- tests/integration/api_repo_archive_test.go | 12 ++--- tests/integration/api_repo_branch_test.go | 23 ++++----- tests/mssql.ini.tmpl | 1 + tests/mysql.ini.tmpl | 1 + tests/pgsql.ini.tmpl | 1 + tests/sqlite.ini.tmpl | 1 + 8 files changed, 45 insertions(+), 52 deletions(-) diff --git a/tests/integration/api_issue_test.go b/tests/integration/api_issue_test.go index dcccafb0f29..f0258068686 100644 --- a/tests/integration/api_issue_test.go +++ b/tests/integration/api_issue_test.go @@ -216,8 +216,6 @@ func TestAPIEditIssue(t *testing.T) { func TestAPISearchIssues(t *testing.T) { defer tests.PrepareTestEnv(t)() - token := getUserToken(t, "user2", auth_model.AccessTokenScopeReadIssue) - // as this API was used in the frontend, it uses UI page size expectedIssueCount := 18 // from the fixtures if expectedIssueCount > setting.UI.IssuePagingNum { @@ -225,11 +223,12 @@ func TestAPISearchIssues(t *testing.T) { } link, _ := url.Parse("/api/v1/repos/issues/search") - query := url.Values{"token": {getUserToken(t, "user1", auth_model.AccessTokenScopeReadIssue)}} + token := getUserToken(t, "user1", auth_model.AccessTokenScopeReadIssue) + query := url.Values{} var apiIssues []*api.Issue link.RawQuery = query.Encode() - req := NewRequest(t, "GET", link.String()) + req := NewRequest(t, "GET", link.String()).AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusOK) DecodeJSON(t, resp, &apiIssues) assert.Len(t, apiIssues, expectedIssueCount) @@ -238,9 +237,8 @@ func TestAPISearchIssues(t *testing.T) { before := time.Unix(999307200, 0).Format(time.RFC3339) query.Add("since", since) query.Add("before", before) - query.Add("token", token) link.RawQuery = query.Encode() - req = NewRequest(t, "GET", link.String()) + req = NewRequest(t, "GET", link.String()).AddTokenAuth(token) resp = MakeRequest(t, req, http.StatusOK) DecodeJSON(t, resp, &apiIssues) assert.Len(t, apiIssues, 11) @@ -249,14 +247,14 @@ func TestAPISearchIssues(t *testing.T) { query.Add("state", "closed") link.RawQuery = query.Encode() - req = NewRequest(t, "GET", link.String()) + req = NewRequest(t, "GET", link.String()).AddTokenAuth(token) resp = MakeRequest(t, req, http.StatusOK) DecodeJSON(t, resp, &apiIssues) assert.Len(t, apiIssues, 2) query.Set("state", "all") link.RawQuery = query.Encode() - req = NewRequest(t, "GET", link.String()) + req = NewRequest(t, "GET", link.String()).AddTokenAuth(token) resp = MakeRequest(t, req, http.StatusOK) DecodeJSON(t, resp, &apiIssues) assert.EqualValues(t, "20", resp.Header().Get("X-Total-Count")) @@ -264,50 +262,50 @@ func TestAPISearchIssues(t *testing.T) { query.Add("limit", "10") link.RawQuery = query.Encode() - req = NewRequest(t, "GET", link.String()) + req = NewRequest(t, "GET", link.String()).AddTokenAuth(token) resp = MakeRequest(t, req, http.StatusOK) DecodeJSON(t, resp, &apiIssues) assert.EqualValues(t, "20", resp.Header().Get("X-Total-Count")) assert.Len(t, apiIssues, 10) - query = url.Values{"assigned": {"true"}, "state": {"all"}, "token": {token}} + query = url.Values{"assigned": {"true"}, "state": {"all"}} link.RawQuery = query.Encode() - req = NewRequest(t, "GET", link.String()) + req = NewRequest(t, "GET", link.String()).AddTokenAuth(token) resp = MakeRequest(t, req, http.StatusOK) DecodeJSON(t, resp, &apiIssues) assert.Len(t, apiIssues, 2) - query = url.Values{"milestones": {"milestone1"}, "state": {"all"}, "token": {token}} + query = url.Values{"milestones": {"milestone1"}, "state": {"all"}} link.RawQuery = query.Encode() - req = NewRequest(t, "GET", link.String()) + req = NewRequest(t, "GET", link.String()).AddTokenAuth(token) resp = MakeRequest(t, req, http.StatusOK) DecodeJSON(t, resp, &apiIssues) assert.Len(t, apiIssues, 1) - query = url.Values{"milestones": {"milestone1,milestone3"}, "state": {"all"}, "token": {token}} + query = url.Values{"milestones": {"milestone1,milestone3"}, "state": {"all"}} link.RawQuery = query.Encode() - req = NewRequest(t, "GET", link.String()) + req = NewRequest(t, "GET", link.String()).AddTokenAuth(token) resp = MakeRequest(t, req, http.StatusOK) DecodeJSON(t, resp, &apiIssues) assert.Len(t, apiIssues, 2) - query = url.Values{"owner": {"user2"}, "token": {token}} // user + query = url.Values{"owner": {"user2"}} // user link.RawQuery = query.Encode() - req = NewRequest(t, "GET", link.String()) + req = NewRequest(t, "GET", link.String()).AddTokenAuth(token) resp = MakeRequest(t, req, http.StatusOK) DecodeJSON(t, resp, &apiIssues) assert.Len(t, apiIssues, 8) - query = url.Values{"owner": {"org3"}, "token": {token}} // organization + query = url.Values{"owner": {"org3"}} // organization link.RawQuery = query.Encode() - req = NewRequest(t, "GET", link.String()) + req = NewRequest(t, "GET", link.String()).AddTokenAuth(token) resp = MakeRequest(t, req, http.StatusOK) DecodeJSON(t, resp, &apiIssues) assert.Len(t, apiIssues, 5) - query = url.Values{"owner": {"org3"}, "team": {"team1"}, "token": {token}} // organization + team + query = url.Values{"owner": {"org3"}, "team": {"team1"}} // organization + team link.RawQuery = query.Encode() - req = NewRequest(t, "GET", link.String()) + req = NewRequest(t, "GET", link.String()).AddTokenAuth(token) resp = MakeRequest(t, req, http.StatusOK) DecodeJSON(t, resp, &apiIssues) assert.Len(t, apiIssues, 2) @@ -323,18 +321,19 @@ func TestAPISearchIssuesWithLabels(t *testing.T) { } link, _ := url.Parse("/api/v1/repos/issues/search") - query := url.Values{"token": {getUserToken(t, "user1", auth_model.AccessTokenScopeReadIssue)}} + token := getUserToken(t, "user1", auth_model.AccessTokenScopeReadIssue) + query := url.Values{} var apiIssues []*api.Issue link.RawQuery = query.Encode() - req := NewRequest(t, "GET", link.String()) + req := NewRequest(t, "GET", link.String()).AddTokenAuth(token) resp := MakeRequest(t, req, http.StatusOK) DecodeJSON(t, resp, &apiIssues) assert.Len(t, apiIssues, expectedIssueCount) query.Add("labels", "label1") link.RawQuery = query.Encode() - req = NewRequest(t, "GET", link.String()) + req = NewRequest(t, "GET", link.String()).AddTokenAuth(token) resp = MakeRequest(t, req, http.StatusOK) DecodeJSON(t, resp, &apiIssues) assert.Len(t, apiIssues, 2) @@ -342,7 +341,7 @@ func TestAPISearchIssuesWithLabels(t *testing.T) { // multiple labels query.Set("labels", "label1,label2") link.RawQuery = query.Encode() - req = NewRequest(t, "GET", link.String()) + req = NewRequest(t, "GET", link.String()).AddTokenAuth(token) resp = MakeRequest(t, req, http.StatusOK) DecodeJSON(t, resp, &apiIssues) assert.Len(t, apiIssues, 2) @@ -350,7 +349,7 @@ func TestAPISearchIssuesWithLabels(t *testing.T) { // an org label query.Set("labels", "orglabel4") link.RawQuery = query.Encode() - req = NewRequest(t, "GET", link.String()) + req = NewRequest(t, "GET", link.String()).AddTokenAuth(token) resp = MakeRequest(t, req, http.StatusOK) DecodeJSON(t, resp, &apiIssues) assert.Len(t, apiIssues, 1) @@ -359,7 +358,7 @@ func TestAPISearchIssuesWithLabels(t *testing.T) { query.Set("labels", "label2,orglabel4") query.Add("state", "all") link.RawQuery = query.Encode() - req = NewRequest(t, "GET", link.String()) + req = NewRequest(t, "GET", link.String()).AddTokenAuth(token) resp = MakeRequest(t, req, http.StatusOK) DecodeJSON(t, resp, &apiIssues) assert.Len(t, apiIssues, 2) @@ -367,7 +366,7 @@ func TestAPISearchIssuesWithLabels(t *testing.T) { // org and repo label which share the same issue query.Set("labels", "label1,orglabel4") link.RawQuery = query.Encode() - req = NewRequest(t, "GET", link.String()) + req = NewRequest(t, "GET", link.String()).AddTokenAuth(token) resp = MakeRequest(t, req, http.StatusOK) DecodeJSON(t, resp, &apiIssues) assert.Len(t, apiIssues, 2) diff --git a/tests/integration/api_releases_test.go b/tests/integration/api_releases_test.go index 6ec3fcc4b8b..e070bd05b5a 100644 --- a/tests/integration/api_releases_test.go +++ b/tests/integration/api_releases_test.go @@ -32,8 +32,7 @@ func TestAPIListReleases(t *testing.T) { token := getUserToken(t, user2.LowerName, auth_model.AccessTokenScopeReadRepository) link, _ := url.Parse(fmt.Sprintf("/api/v1/repos/%s/%s/releases", user2.Name, repo.Name)) - link.RawQuery = url.Values{"token": {token}}.Encode() - resp := MakeRequest(t, NewRequest(t, "GET", link.String()), http.StatusOK) + resp := MakeRequest(t, NewRequest(t, "GET", link.String()).AddTokenAuth(token), http.StatusOK) var apiReleases []*api.Release DecodeJSON(t, resp, &apiReleases) if assert.Len(t, apiReleases, 3) { diff --git a/tests/integration/api_repo_archive_test.go b/tests/integration/api_repo_archive_test.go index 5d1db1b09b7..57d3abfe840 100644 --- a/tests/integration/api_repo_archive_test.go +++ b/tests/integration/api_repo_archive_test.go @@ -28,27 +28,23 @@ func TestAPIDownloadArchive(t *testing.T) { token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeReadRepository) link, _ := url.Parse(fmt.Sprintf("/api/v1/repos/%s/%s/archive/master.zip", user2.Name, repo.Name)) - link.RawQuery = url.Values{"token": {token}}.Encode() - resp := MakeRequest(t, NewRequest(t, "GET", link.String()), http.StatusOK) + resp := MakeRequest(t, NewRequest(t, "GET", link.String()).AddTokenAuth(token), http.StatusOK) bs, err := io.ReadAll(resp.Body) assert.NoError(t, err) assert.Len(t, bs, 320) link, _ = url.Parse(fmt.Sprintf("/api/v1/repos/%s/%s/archive/master.tar.gz", user2.Name, repo.Name)) - link.RawQuery = url.Values{"token": {token}}.Encode() - resp = MakeRequest(t, NewRequest(t, "GET", link.String()), http.StatusOK) + resp = MakeRequest(t, NewRequest(t, "GET", link.String()).AddTokenAuth(token), http.StatusOK) bs, err = io.ReadAll(resp.Body) assert.NoError(t, err) assert.Len(t, bs, 266) link, _ = url.Parse(fmt.Sprintf("/api/v1/repos/%s/%s/archive/master.bundle", user2.Name, repo.Name)) - link.RawQuery = url.Values{"token": {token}}.Encode() - resp = MakeRequest(t, NewRequest(t, "GET", link.String()), http.StatusOK) + resp = MakeRequest(t, NewRequest(t, "GET", link.String()).AddTokenAuth(token), http.StatusOK) bs, err = io.ReadAll(resp.Body) assert.NoError(t, err) assert.Len(t, bs, 382) link, _ = url.Parse(fmt.Sprintf("/api/v1/repos/%s/%s/archive/master", user2.Name, repo.Name)) - link.RawQuery = url.Values{"token": {token}}.Encode() - MakeRequest(t, NewRequest(t, "GET", link.String()), http.StatusBadRequest) + MakeRequest(t, NewRequest(t, "GET", link.String()).AddTokenAuth(token), http.StatusBadRequest) } diff --git a/tests/integration/api_repo_branch_test.go b/tests/integration/api_repo_branch_test.go index 852c666c34c..b0ac2286c94 100644 --- a/tests/integration/api_repo_branch_test.go +++ b/tests/integration/api_repo_branch_test.go @@ -31,8 +31,7 @@ func TestAPIRepoBranchesPlain(t *testing.T) { token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteRepository) link, _ := url.Parse(fmt.Sprintf("/api/v1/repos/org3/%s/branches", repo3.Name)) // a plain repo - link.RawQuery = url.Values{"token": {token}}.Encode() - resp := MakeRequest(t, NewRequest(t, "GET", link.String()), http.StatusOK) + resp := MakeRequest(t, NewRequest(t, "GET", link.String()).AddTokenAuth(token), http.StatusOK) bs, err := io.ReadAll(resp.Body) assert.NoError(t, err) @@ -43,15 +42,14 @@ func TestAPIRepoBranchesPlain(t *testing.T) { assert.EqualValues(t, "master", branches[1].Name) link2, _ := url.Parse(fmt.Sprintf("/api/v1/repos/org3/%s/branches/test_branch", repo3.Name)) - link2.RawQuery = url.Values{"token": {token}}.Encode() - resp = MakeRequest(t, NewRequest(t, "GET", link2.String()), http.StatusOK) + resp = MakeRequest(t, NewRequest(t, "GET", link2.String()).AddTokenAuth(token), http.StatusOK) bs, err = io.ReadAll(resp.Body) assert.NoError(t, err) var branch api.Branch assert.NoError(t, json.Unmarshal(bs, &branch)) assert.EqualValues(t, "test_branch", branch.Name) - req := NewRequest(t, "POST", link.String()) + req := NewRequest(t, "POST", link.String()).AddTokenAuth(token) req.Header.Add("Content-Type", "application/json") req.Body = io.NopCloser(bytes.NewBufferString(`{"new_branch_name":"test_branch2", "old_branch_name": "test_branch", "old_ref_name":"refs/heads/test_branch"}`)) resp = MakeRequest(t, req, http.StatusCreated) @@ -62,7 +60,7 @@ func TestAPIRepoBranchesPlain(t *testing.T) { assert.EqualValues(t, "test_branch2", branch2.Name) assert.EqualValues(t, branch.Commit.ID, branch2.Commit.ID) - resp = MakeRequest(t, NewRequest(t, "GET", link.String()), http.StatusOK) + resp = MakeRequest(t, NewRequest(t, "GET", link.String()).AddTokenAuth(token), http.StatusOK) bs, err = io.ReadAll(resp.Body) assert.NoError(t, err) @@ -76,8 +74,7 @@ func TestAPIRepoBranchesPlain(t *testing.T) { link3, _ := url.Parse(fmt.Sprintf("/api/v1/repos/org3/%s/branches/test_branch2", repo3.Name)) MakeRequest(t, NewRequest(t, "DELETE", link3.String()), http.StatusNotFound) - link3.RawQuery = url.Values{"token": {token}}.Encode() - MakeRequest(t, NewRequest(t, "DELETE", link3.String()), http.StatusNoContent) + MakeRequest(t, NewRequest(t, "DELETE", link3.String()).AddTokenAuth(token), http.StatusNoContent) assert.NoError(t, err) }) } @@ -91,8 +88,7 @@ func TestAPIRepoBranchesMirror(t *testing.T) { token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteRepository) link, _ := url.Parse(fmt.Sprintf("/api/v1/repos/org3/%s/branches", repo5.Name)) // a mirror repo - link.RawQuery = url.Values{"token": {token}}.Encode() - resp := MakeRequest(t, NewRequest(t, "GET", link.String()), http.StatusOK) + resp := MakeRequest(t, NewRequest(t, "GET", link.String()).AddTokenAuth(token), http.StatusOK) bs, err := io.ReadAll(resp.Body) assert.NoError(t, err) @@ -103,15 +99,14 @@ func TestAPIRepoBranchesMirror(t *testing.T) { assert.EqualValues(t, "master", branches[1].Name) link2, _ := url.Parse(fmt.Sprintf("/api/v1/repos/org3/%s/branches/test_branch", repo5.Name)) - link2.RawQuery = url.Values{"token": {token}}.Encode() - resp = MakeRequest(t, NewRequest(t, "GET", link2.String()), http.StatusOK) + resp = MakeRequest(t, NewRequest(t, "GET", link2.String()).AddTokenAuth(token), http.StatusOK) bs, err = io.ReadAll(resp.Body) assert.NoError(t, err) var branch api.Branch assert.NoError(t, json.Unmarshal(bs, &branch)) assert.EqualValues(t, "test_branch", branch.Name) - req := NewRequest(t, "POST", link.String()) + req := NewRequest(t, "POST", link.String()).AddTokenAuth(token) req.Header.Add("Content-Type", "application/json") req.Body = io.NopCloser(bytes.NewBufferString(`{"new_branch_name":"test_branch2", "old_branch_name": "test_branch", "old_ref_name":"refs/heads/test_branch"}`)) resp = MakeRequest(t, req, http.StatusForbidden) @@ -119,7 +114,7 @@ func TestAPIRepoBranchesMirror(t *testing.T) { assert.NoError(t, err) assert.EqualValues(t, "{\"message\":\"Git Repository is a mirror.\",\"url\":\""+setting.AppURL+"api/swagger\"}\n", string(bs)) - resp = MakeRequest(t, NewRequest(t, "DELETE", link2.String()), http.StatusForbidden) + resp = MakeRequest(t, NewRequest(t, "DELETE", link2.String()).AddTokenAuth(token), http.StatusForbidden) bs, err = io.ReadAll(resp.Body) assert.NoError(t, err) assert.EqualValues(t, "{\"message\":\"Git Repository is a mirror.\",\"url\":\""+setting.AppURL+"api/swagger\"}\n", string(bs)) diff --git a/tests/mssql.ini.tmpl b/tests/mssql.ini.tmpl index 3cd64ec5cb8..07997f62edf 100644 --- a/tests/mssql.ini.tmpl +++ b/tests/mssql.ini.tmpl @@ -100,6 +100,7 @@ DISABLE_GIT_HOOKS = false INSTALL_LOCK = true SECRET_KEY = 9pCviYTWSb INTERNAL_TOKEN = eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYmYiOjE0OTU1NTE2MTh9.hhSVGOANkaKk3vfCd2jDOIww4pUk0xtg9JRde5UogyQ +DISABLE_QUERY_AUTH_TOKEN = true [lfs] PATH = tests/{{TEST_TYPE}}/gitea-{{TEST_TYPE}}-mssql/data/lfs diff --git a/tests/mysql.ini.tmpl b/tests/mysql.ini.tmpl index 2f890e67eb9..0fddde46de6 100644 --- a/tests/mysql.ini.tmpl +++ b/tests/mysql.ini.tmpl @@ -98,6 +98,7 @@ DISABLE_GIT_HOOKS = false INSTALL_LOCK = true SECRET_KEY = 9pCviYTWSb INTERNAL_TOKEN = eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYmYiOjE0OTU1NTE2MTh9.hhSVGOANkaKk3vfCd2jDOIww4pUk0xtg9JRde5UogyQ +DISABLE_QUERY_AUTH_TOKEN = true [lfs] PATH = tests/{{TEST_TYPE}}/gitea-{{TEST_TYPE}}-mysql/data/lfs diff --git a/tests/pgsql.ini.tmpl b/tests/pgsql.ini.tmpl index a1679cad6a6..486cfc945c1 100644 --- a/tests/pgsql.ini.tmpl +++ b/tests/pgsql.ini.tmpl @@ -101,6 +101,7 @@ DISABLE_GIT_HOOKS = false INSTALL_LOCK = true SECRET_KEY = 9pCviYTWSb INTERNAL_TOKEN = eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYmYiOjE0OTU1NTE2MTh9.hhSVGOANkaKk3vfCd2jDOIww4pUk0xtg9JRde5UogyQ +DISABLE_QUERY_AUTH_TOKEN = true [lfs] MINIO_BASE_PATH = lfs/ diff --git a/tests/sqlite.ini.tmpl b/tests/sqlite.ini.tmpl index 74e19571131..1cbcd8b2e59 100644 --- a/tests/sqlite.ini.tmpl +++ b/tests/sqlite.ini.tmpl @@ -97,6 +97,7 @@ DISABLE_GIT_HOOKS = false INSTALL_LOCK = true SECRET_KEY = 9pCviYTWSb INTERNAL_TOKEN = eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYmYiOjE0OTI3OTU5ODN9.OQkH5UmzID2XBdwQ9TAI6Jj2t1X-wElVTjbE7aoN4I8 +DISABLE_QUERY_AUTH_TOKEN = true [oauth2] JWT_SECRET = KZb_QLUd4fYVyxetjxC4eZkrBgWM2SndOOWDNtgUUko From 330aab47b3e4d777a6e5a3f05351ceab92ee5562 Mon Sep 17 00:00:00 2001 From: wxiaoguang Date: Sun, 24 Dec 2023 03:06:02 +0800 Subject: [PATCH 019/189] Include heap pprof in diagnosis report to help debugging memory leaks (#28596) --- routers/web/admin/diagnosis.go | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/routers/web/admin/diagnosis.go b/routers/web/admin/diagnosis.go index 5637894e6de..2d550125d55 100644 --- a/routers/web/admin/diagnosis.go +++ b/routers/web/admin/diagnosis.go @@ -58,4 +58,11 @@ func MonitorDiagnosis(ctx *context.Context) { return } _ = pprof.Lookup("goroutine").WriteTo(f, 1) + + f, err = zipWriter.CreateHeader(&zip.FileHeader{Name: "heap.dat", Method: zip.Deflate, Modified: time.Now()}) + if err != nil { + ctx.ServerError("Failed to create zip file", err) + return + } + _ = pprof.Lookup("heap").WriteTo(f, 0) } From a1d2a152f832e76db7d08803c7e0236289f7ade0 Mon Sep 17 00:00:00 2001 From: techknowlogick Date: Sat, 23 Dec 2023 16:04:58 -0500 Subject: [PATCH 020/189] bump to use alpine3.19 (#28594) --- Dockerfile | 4 ++-- Dockerfile.rootless | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/Dockerfile b/Dockerfile index 5fe8df91268..325b0255dfc 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,5 +1,5 @@ # Build stage -FROM docker.io/library/golang:1.21-alpine3.18 AS build-env +FROM docker.io/library/golang:1.21-alpine3.19 AS build-env ARG GOPROXY ENV GOPROXY ${GOPROXY:-direct} @@ -41,7 +41,7 @@ RUN chmod 755 /tmp/local/usr/bin/entrypoint \ /go/src/code.gitea.io/gitea/environment-to-ini RUN chmod 644 /go/src/code.gitea.io/gitea/contrib/autocompletion/bash_autocomplete -FROM docker.io/library/alpine:3.18 +FROM docker.io/library/alpine:3.19 LABEL maintainer="maintainers@gitea.io" EXPOSE 22 3000 diff --git a/Dockerfile.rootless b/Dockerfile.rootless index 5ea4d2fc751..6f27c698ace 100644 --- a/Dockerfile.rootless +++ b/Dockerfile.rootless @@ -1,5 +1,5 @@ # Build stage -FROM docker.io/library/golang:1.21-alpine3.18 AS build-env +FROM docker.io/library/golang:1.21-alpine3.19 AS build-env ARG GOPROXY ENV GOPROXY ${GOPROXY:-direct} @@ -39,7 +39,7 @@ RUN chmod 755 /tmp/local/usr/local/bin/docker-entrypoint.sh \ /go/src/code.gitea.io/gitea/environment-to-ini RUN chmod 644 /go/src/code.gitea.io/gitea/contrib/autocompletion/bash_autocomplete -FROM docker.io/library/alpine:3.18 +FROM docker.io/library/alpine:3.19 LABEL maintainer="maintainers@gitea.io" EXPOSE 2222 3000 From 8a71f7280a1136b19e5390716d7f8c43bed460cc Mon Sep 17 00:00:00 2001 From: wxiaoguang Date: Sun, 24 Dec 2023 13:08:41 +0800 Subject: [PATCH 021/189] Fix the scroll behavior for emoji/mention list (#28597) Fix #28595 by https://github.com/github/combobox-nav/pull/79 (combobox-nav v2.3.1) --- package-lock.json | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/package-lock.json b/package-lock.json index 5a49efee23e..5b62bd13a81 100644 --- a/package-lock.json +++ b/package-lock.json @@ -996,9 +996,9 @@ } }, "node_modules/@github/combobox-nav": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/@github/combobox-nav/-/combobox-nav-2.3.0.tgz", - "integrity": "sha512-5CX03DbsLZ41dX5hKHyQKtg133U6lruX4TD9G0Zs4W8BpWy7lN8DJ6TYaeZN/V7x8K34coaqNYk/Y5ic7stfkg==" + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/@github/combobox-nav/-/combobox-nav-2.3.1.tgz", + "integrity": "sha512-gwxPzLw8XKecy1nP63i9lOBritS3bWmxl02UX6G0TwMQZbMem1BCS1tEZgYd3mkrkiDrUMWaX+DbFCuDFo3K+A==" }, "node_modules/@github/markdown-toolbar-element": { "version": "2.2.1", From 8989d466ed4e3ebf60aaf6fe0e237699a93b70ee Mon Sep 17 00:00:00 2001 From: wxiaoguang Date: Sun, 24 Dec 2023 22:39:02 +0800 Subject: [PATCH 022/189] Fix flex container width (#28603) Fix #28489 --- web_src/css/modules/flexcontainer.css | 1 + 1 file changed, 1 insertion(+) diff --git a/web_src/css/modules/flexcontainer.css b/web_src/css/modules/flexcontainer.css index 1721f14b2ca..0b559f1e7d3 100644 --- a/web_src/css/modules/flexcontainer.css +++ b/web_src/css/modules/flexcontainer.css @@ -11,6 +11,7 @@ .flex-container-main { flex: 1; + min-width: 0; /* make the "text truncate" work, otherwise the flex axis is not limited and the text just overflows */ } @media (max-width: 767.98px) { From 7396e3618d61bfd68853fce6edd74200efe23d9b Mon Sep 17 00:00:00 2001 From: GiteaBot Date: Mon, 25 Dec 2023 00:25:23 +0000 Subject: [PATCH 023/189] [skip ci] Updated licenses and gitignores --- options/license/FSFAP-no-warranty-disclaimer | 5 +++++ options/license/HPND-Kevlin-Henney | 10 ++++++++++ 2 files changed, 15 insertions(+) create mode 100644 options/license/FSFAP-no-warranty-disclaimer create mode 100644 options/license/HPND-Kevlin-Henney diff --git a/options/license/FSFAP-no-warranty-disclaimer b/options/license/FSFAP-no-warranty-disclaimer new file mode 100644 index 00000000000..2cc8a933201 --- /dev/null +++ b/options/license/FSFAP-no-warranty-disclaimer @@ -0,0 +1,5 @@ +Copyright (C) 2008 Micah J. Cowan + +Copying and distribution of this file, with or without modification, +are permitted in any medium without royalty provided the copyright +notice and this notice are preserved. diff --git a/options/license/HPND-Kevlin-Henney b/options/license/HPND-Kevlin-Henney new file mode 100644 index 00000000000..ddf9bd6dca0 --- /dev/null +++ b/options/license/HPND-Kevlin-Henney @@ -0,0 +1,10 @@ +Copyright Kevlin Henney, 1997, 2003, 2012. All rights reserved. + +Permission to use, copy, modify, and distribute this software and its +documentation for any purpose is hereby granted without fee, provided +that this copyright and permissions notice appear in all copies and +derivatives. + +This software is supplied "as is" without express or implied warranty. + +But that said, if there are any problems please get in touch. From 0407a402bb29a3643e2b4a8992f1d7687a88b40c Mon Sep 17 00:00:00 2001 From: Lunny Xiao Date: Mon, 25 Dec 2023 14:52:17 +0800 Subject: [PATCH 024/189] Revert "improve possible performance bottleneck (#28547)" (#28593) This reverts commit b35d3fddfac389a7be401a63b4e1283dd74af681. This is totally wrong. I think `Update join` hasn't been supported well by xorm. I just revert the PR and will try to send another one. --- models/issues/comment.go | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/models/issues/comment.go b/models/issues/comment.go index ce5cf5902d7..ba5aed9c652 100644 --- a/models/issues/comment.go +++ b/models/issues/comment.go @@ -1161,9 +1161,14 @@ func DeleteComment(ctx context.Context, comment *Comment) error { // UpdateCommentsMigrationsByType updates comments' migrations information via given git service type and original id and poster id func UpdateCommentsMigrationsByType(ctx context.Context, tp structs.GitServiceType, originalAuthorID string, posterID int64) error { _, err := db.GetEngine(ctx).Table("comment"). - Join("INNER", "issue", "issue.id = comment.issue_id"). - Join("INNER", "repository", "issue.repo_id = repository.id"). - Where("repository.original_service_type = ?", tp). + Where(builder.In("issue_id", + builder.Select("issue.id"). + From("issue"). + InnerJoin("repository", "issue.repo_id = repository.id"). + Where(builder.Eq{ + "repository.original_service_type": tp, + }), + )). And("comment.original_author_id = ?", originalAuthorID). Update(map[string]any{ "poster_id": posterID, From d0f24ff4cad05c1145afeca791e7d02fe146d46a Mon Sep 17 00:00:00 2001 From: Jean-Baptiste Gomond Date: Mon, 25 Dec 2023 08:28:59 +0100 Subject: [PATCH 025/189] Added instance-level variables (#28115) This PR adds instance-level variables, and so closes #27726 ![gitea_instance_variables_1](https://github.com/go-gitea/gitea/assets/8344487/ad409cd4-ce36-4c84-a764-34451b0fb63a) ![gitea_instance_variables_2](https://github.com/go-gitea/gitea/assets/8344487/426f0965-dec6-4560-948c-067cdeddd720) ![gitea_instance_variables_3](https://github.com/go-gitea/gitea/assets/8344487/cf1d7776-4938-4825-922e-cbbbf28a5f33) --- models/actions/variable.go | 12 ++++-------- routers/api/actions/runner/utils.go | 10 ++++++++-- routers/web/repo/setting/variables.go | 21 ++++++++++++++++++--- routers/web/web.go | 9 +++++---- templates/admin/actions.tmpl | 3 +++ templates/admin/navbar.tmpl | 5 ++++- 6 files changed, 42 insertions(+), 18 deletions(-) diff --git a/models/actions/variable.go b/models/actions/variable.go index 030b7bae92a..12717e0ae46 100644 --- a/models/actions/variable.go +++ b/models/actions/variable.go @@ -31,8 +31,8 @@ func init() { } func (v *ActionVariable) Validate() error { - if v.OwnerID == 0 && v.RepoID == 0 { - return errors.New("the variable is not bound to any scope") + if v.OwnerID != 0 && v.RepoID != 0 { + return errors.New("a variable should not be bound to an owner and a repository at the same time") } return nil } @@ -58,12 +58,8 @@ type FindVariablesOpts struct { func (opts FindVariablesOpts) ToConds() builder.Cond { cond := builder.NewCond() - if opts.OwnerID > 0 { - cond = cond.And(builder.Eq{"owner_id": opts.OwnerID}) - } - if opts.RepoID > 0 { - cond = cond.And(builder.Eq{"repo_id": opts.RepoID}) - } + cond = cond.And(builder.Eq{"owner_id": opts.OwnerID}) + cond = cond.And(builder.Eq{"repo_id": opts.RepoID}) return cond } diff --git a/routers/api/actions/runner/utils.go b/routers/api/actions/runner/utils.go index bf913f2c057..2555f86c80d 100644 --- a/routers/api/actions/runner/utils.go +++ b/routers/api/actions/runner/utils.go @@ -94,6 +94,12 @@ func getSecretsOfTask(ctx context.Context, task *actions_model.ActionTask) map[s func getVariablesOfTask(ctx context.Context, task *actions_model.ActionTask) map[string]string { variables := map[string]string{} + // Global + globalVariables, err := db.Find[actions_model.ActionVariable](ctx, actions_model.FindVariablesOpts{}) + if err != nil { + log.Error("find global variables: %v", err) + } + // Org / User level ownerVariables, err := db.Find[actions_model.ActionVariable](ctx, actions_model.FindVariablesOpts{OwnerID: task.Job.Run.Repo.OwnerID}) if err != nil { @@ -106,8 +112,8 @@ func getVariablesOfTask(ctx context.Context, task *actions_model.ActionTask) map log.Error("find variables of repo: %d, error: %v", task.Job.Run.RepoID, err) } - // Level precedence: Repo > Org / User - for _, v := range append(ownerVariables, repoVariables...) { + // Level precedence: Repo > Org / User > Global + for _, v := range append(globalVariables, append(ownerVariables, repoVariables...)...) { variables[v.Name] = v.Data } diff --git a/routers/web/repo/setting/variables.go b/routers/web/repo/setting/variables.go index a697a5d8d85..428aa0bd5c4 100644 --- a/routers/web/repo/setting/variables.go +++ b/routers/web/repo/setting/variables.go @@ -15,9 +15,10 @@ import ( ) const ( - tplRepoVariables base.TplName = "repo/settings/actions" - tplOrgVariables base.TplName = "org/settings/actions" - tplUserVariables base.TplName = "user/settings/actions" + tplRepoVariables base.TplName = "repo/settings/actions" + tplOrgVariables base.TplName = "org/settings/actions" + tplUserVariables base.TplName = "user/settings/actions" + tplAdminVariables base.TplName = "admin/actions" ) type variablesCtx struct { @@ -26,6 +27,7 @@ type variablesCtx struct { IsRepo bool IsOrg bool IsUser bool + IsGlobal bool VariablesTemplate base.TplName RedirectLink string } @@ -33,6 +35,7 @@ type variablesCtx struct { func getVariablesCtx(ctx *context.Context) (*variablesCtx, error) { if ctx.Data["PageIsRepoSettings"] == true { return &variablesCtx{ + OwnerID: 0, RepoID: ctx.Repo.Repository.ID, IsRepo: true, VariablesTemplate: tplRepoVariables, @@ -48,6 +51,7 @@ func getVariablesCtx(ctx *context.Context) (*variablesCtx, error) { } return &variablesCtx{ OwnerID: ctx.ContextUser.ID, + RepoID: 0, IsOrg: true, VariablesTemplate: tplOrgVariables, RedirectLink: ctx.Org.OrgLink + "/settings/actions/variables", @@ -57,12 +61,23 @@ func getVariablesCtx(ctx *context.Context) (*variablesCtx, error) { if ctx.Data["PageIsUserSettings"] == true { return &variablesCtx{ OwnerID: ctx.Doer.ID, + RepoID: 0, IsUser: true, VariablesTemplate: tplUserVariables, RedirectLink: setting.AppSubURL + "/user/settings/actions/variables", }, nil } + if ctx.Data["PageIsAdmin"] == true { + return &variablesCtx{ + OwnerID: 0, + RepoID: 0, + IsGlobal: true, + VariablesTemplate: tplAdminVariables, + RedirectLink: setting.AppSubURL + "/admin/actions/variables", + }, nil + } + return nil, errors.New("unable to set Variables context") } diff --git a/routers/web/web.go b/routers/web/web.go index 359b608c71e..02fb11b1f51 100644 --- a/routers/web/web.go +++ b/routers/web/web.go @@ -417,7 +417,7 @@ func registerRoutes(m *web.Route) { m.Post("/packagist/{id}", web.Bind(forms.NewPackagistHookForm{}), repo_setting.PackagistHooksEditPost) } - addSettingVariablesRoutes := func() { + addSettingsVariablesRoutes := func() { m.Group("/variables", func() { m.Get("", repo_setting.Variables) m.Post("/new", web.Bind(forms.EditVariableForm{}), repo_setting.VariableCreate) @@ -618,7 +618,7 @@ func registerRoutes(m *web.Route) { m.Get("", user_setting.RedirectToDefaultSetting) addSettingsRunnersRoutes() addSettingsSecretsRoutes() - addSettingVariablesRoutes() + addSettingsVariablesRoutes() }, actions.MustEnableActions) m.Get("/organization", user_setting.Organization) @@ -763,6 +763,7 @@ func registerRoutes(m *web.Route) { m.Group("/actions", func() { m.Get("", admin.RedirectToDefaultSetting) addSettingsRunnersRoutes() + addSettingsVariablesRoutes() }) }, adminReq, ctxDataSet("EnableOAuth2", setting.OAuth2.Enable, "EnablePackages", setting.Packages.Enabled)) // ***** END: Admin ***** @@ -905,7 +906,7 @@ func registerRoutes(m *web.Route) { m.Get("", org_setting.RedirectToDefaultSetting) addSettingsRunnersRoutes() addSettingsSecretsRoutes() - addSettingVariablesRoutes() + addSettingsVariablesRoutes() }, actions.MustEnableActions) m.Methods("GET,POST", "/delete", org.SettingsDelete) @@ -1084,7 +1085,7 @@ func registerRoutes(m *web.Route) { m.Get("", repo_setting.RedirectToDefaultSetting) addSettingsRunnersRoutes() addSettingsSecretsRoutes() - addSettingVariablesRoutes() + addSettingsVariablesRoutes() }, actions.MustEnableActions) // the follow handler must be under "settings", otherwise this incomplete repo can't be accessed m.Group("/migrate", func() { diff --git a/templates/admin/actions.tmpl b/templates/admin/actions.tmpl index 9640e0fd1f4..597863d73b1 100644 --- a/templates/admin/actions.tmpl +++ b/templates/admin/actions.tmpl @@ -3,5 +3,8 @@ {{if eq .PageType "runners"}} {{template "shared/actions/runner_list" .}} {{end}} + {{if eq .PageType "variables"}} + {{template "shared/variables/variable_list" .}} + {{end}} {{template "admin/layout_footer" .}} diff --git a/templates/admin/navbar.tmpl b/templates/admin/navbar.tmpl index 8ece95239c1..b22db1d1fc8 100644 --- a/templates/admin/navbar.tmpl +++ b/templates/admin/navbar.tmpl @@ -60,12 +60,15 @@ {{end}} {{end}} {{if .EnableActions}} -
+
{{ctx.Locale.Tr "actions.actions"}}
{{end}} From b41925cee3d67a1fe546c7a219174e4a8b2302b7 Mon Sep 17 00:00:00 2001 From: wxiaoguang Date: Mon, 25 Dec 2023 20:13:18 +0800 Subject: [PATCH 026/189] Refactor CORS handler (#28587) The CORS code has been unmaintained for long time, and the behavior is not correct. This PR tries to improve it. The key point is written as comment in code. And add more tests. Fix #28515 Fix #27642 Fix #17098 --- custom/conf/app.example.ini | 8 +- .../config-cheat-sheet.en-us.md | 4 +- .../config-cheat-sheet.zh-cn.md | 2 - modules/public/public.go | 2 +- modules/setting/cors.go | 4 +- modules/web/route.go | 24 ++---- routers/api/v1/api.go | 4 +- routers/web/githttp.go | 22 ++--- routers/web/misc/misc.go | 4 - routers/web/web.go | 50 ++++++----- tests/integration/cors_test.go | 85 +++++++++++++++++-- 11 files changed, 131 insertions(+), 78 deletions(-) diff --git a/custom/conf/app.example.ini b/custom/conf/app.example.ini index f9111d541c7..0fcf895b5a2 100644 --- a/custom/conf/app.example.ini +++ b/custom/conf/app.example.ini @@ -1158,15 +1158,9 @@ LEVEL = Info ;; enable cors headers (disabled by default) ;ENABLED = false ;; -;; scheme of allowed requests -;SCHEME = http -;; -;; list of requesting domains that are allowed +;; list of requesting origins that are allowed, eg: "https://*.example.com" ;ALLOW_DOMAIN = * ;; -;; allow subdomains of headers listed above to request -;ALLOW_SUBDOMAIN = false -;; ;; list of methods allowed to request ;METHODS = GET,HEAD,POST,PUT,PATCH,DELETE,OPTIONS ;; diff --git a/docs/content/administration/config-cheat-sheet.en-us.md b/docs/content/administration/config-cheat-sheet.en-us.md index 1ba5dd04cc4..cd1f31fccd0 100644 --- a/docs/content/administration/config-cheat-sheet.en-us.md +++ b/docs/content/administration/config-cheat-sheet.en-us.md @@ -196,9 +196,7 @@ The following configuration set `Content-Type: application/vnd.android.package-a ## CORS (`cors`) - `ENABLED`: **false**: enable cors headers (disabled by default) -- `SCHEME`: **http**: scheme of allowed requests -- `ALLOW_DOMAIN`: **\***: list of requesting domains that are allowed -- `ALLOW_SUBDOMAIN`: **false**: allow subdomains of headers listed above to request +- `ALLOW_DOMAIN`: **\***: list of requesting origins that are allowed, eg: "https://*.example.com" - `METHODS`: **GET,HEAD,POST,PUT,PATCH,DELETE,OPTIONS**: list of methods allowed to request - `MAX_AGE`: **10m**: max time to cache response - `ALLOW_CREDENTIALS`: **false**: allow request with credentials diff --git a/docs/content/administration/config-cheat-sheet.zh-cn.md b/docs/content/administration/config-cheat-sheet.zh-cn.md index 434d69815b1..f85da439cd6 100644 --- a/docs/content/administration/config-cheat-sheet.zh-cn.md +++ b/docs/content/administration/config-cheat-sheet.zh-cn.md @@ -195,9 +195,7 @@ menu: ## 跨域 (`cors`) - `ENABLED`: **false**: 启用 CORS 头部(默认禁用) -- `SCHEME`: **http**: 允许请求的协议 - `ALLOW_DOMAIN`: **\***: 允许请求的域名列表 -- `ALLOW_SUBDOMAIN`: **false**: 允许上述列出的头部的子域名发出请求。 - `METHODS`: **GET,HEAD,POST,PUT,PATCH,DELETE,OPTIONS**: 允许发起的请求方式列表 - `MAX_AGE`: **10m**: 缓存响应的最大时间 - `ALLOW_CREDENTIALS`: **false**: 允许带有凭据的请求 diff --git a/modules/public/public.go b/modules/public/public.go index 5fbfe30a81c..abc6b461580 100644 --- a/modules/public/public.go +++ b/modules/public/public.go @@ -33,7 +33,7 @@ func FileHandlerFunc() http.HandlerFunc { assetFS := AssetFS() return func(resp http.ResponseWriter, req *http.Request) { if req.Method != "GET" && req.Method != "HEAD" { - resp.WriteHeader(http.StatusNotFound) + resp.WriteHeader(http.StatusMethodNotAllowed) return } handleRequest(resp, req, assetFS, req.URL.Path) diff --git a/modules/setting/cors.go b/modules/setting/cors.go index bafbbab64f9..63daaad60ba 100644 --- a/modules/setting/cors.go +++ b/modules/setting/cors.go @@ -12,9 +12,7 @@ import ( // CORSConfig defines CORS settings var CORSConfig = struct { Enabled bool - Scheme string - AllowDomain []string - AllowSubdomain bool + AllowDomain []string // FIXME: this option is from legacy code, it actually works as "AllowedOrigins". When refactoring in the future, the config option should also be renamed together. Methods []string MaxAge time.Duration AllowCredentials bool diff --git a/modules/web/route.go b/modules/web/route.go index 86b83dd7236..805fcb44115 100644 --- a/modules/web/route.go +++ b/modules/web/route.go @@ -101,16 +101,18 @@ func (r *Route) wrapMiddlewareAndHandler(h []any) ([]func(http.Handler) http.Han return middlewares, handlerFunc } -func (r *Route) Methods(method, pattern string, h ...any) { +// Methods adds the same handlers for multiple http "methods" (separated by ","). +// If any method is invalid, the lower level router will panic. +func (r *Route) Methods(methods, pattern string, h ...any) { middlewares, handlerFunc := r.wrapMiddlewareAndHandler(h) fullPattern := r.getPattern(pattern) - if strings.Contains(method, ",") { - methods := strings.Split(method, ",") + if strings.Contains(methods, ",") { + methods := strings.Split(methods, ",") for _, method := range methods { r.R.With(middlewares...).Method(strings.TrimSpace(method), fullPattern, handlerFunc) } } else { - r.R.With(middlewares...).Method(method, fullPattern, handlerFunc) + r.R.With(middlewares...).Method(methods, fullPattern, handlerFunc) } } @@ -136,20 +138,6 @@ func (r *Route) Get(pattern string, h ...any) { r.Methods("GET", pattern, h...) } -func (r *Route) Options(pattern string, h ...any) { - r.Methods("OPTIONS", pattern, h...) -} - -// GetOptions delegate get and options method -func (r *Route) GetOptions(pattern string, h ...any) { - r.Methods("GET,OPTIONS", pattern, h...) -} - -// PostOptions delegate post and options method -func (r *Route) PostOptions(pattern string, h ...any) { - r.Methods("POST,OPTIONS", pattern, h...) -} - // Head delegate head method func (r *Route) Head(pattern string, h ...any) { r.Methods("HEAD", pattern, h...) diff --git a/routers/api/v1/api.go b/routers/api/v1/api.go index 0e437bb92ec..a4c3d6f4440 100644 --- a/routers/api/v1/api.go +++ b/routers/api/v1/api.go @@ -822,9 +822,7 @@ func Routes() *web.Route { m.Use(securityHeaders()) if setting.CORSConfig.Enabled { m.Use(cors.Handler(cors.Options{ - // Scheme: setting.CORSConfig.Scheme, // FIXME: the cors middleware needs scheme option - AllowedOrigins: setting.CORSConfig.AllowDomain, - // setting.CORSConfig.AllowSubdomain // FIXME: the cors middleware needs allowSubdomain option + AllowedOrigins: setting.CORSConfig.AllowDomain, AllowedMethods: setting.CORSConfig.Methods, AllowCredentials: setting.CORSConfig.AllowCredentials, AllowedHeaders: append([]string{"Authorization", "X-Gitea-OTP"}, setting.CORSConfig.Headers...), diff --git a/routers/web/githttp.go b/routers/web/githttp.go index b2fb5b472f7..8d0d1ce03a3 100644 --- a/routers/web/githttp.go +++ b/routers/web/githttp.go @@ -28,16 +28,16 @@ func requireSignIn(ctx *context.Context) { func gitHTTPRouters(m *web.Route) { m.Group("", func() { - m.PostOptions("/git-upload-pack", repo.ServiceUploadPack) - m.PostOptions("/git-receive-pack", repo.ServiceReceivePack) - m.GetOptions("/info/refs", repo.GetInfoRefs) - m.GetOptions("/HEAD", repo.GetTextFile("HEAD")) - m.GetOptions("/objects/info/alternates", repo.GetTextFile("objects/info/alternates")) - m.GetOptions("/objects/info/http-alternates", repo.GetTextFile("objects/info/http-alternates")) - m.GetOptions("/objects/info/packs", repo.GetInfoPacks) - m.GetOptions("/objects/info/{file:[^/]*}", repo.GetTextFile("")) - m.GetOptions("/objects/{head:[0-9a-f]{2}}/{hash:[0-9a-f]{38}}", repo.GetLooseObject) - m.GetOptions("/objects/pack/pack-{file:[0-9a-f]{40}}.pack", repo.GetPackFile) - m.GetOptions("/objects/pack/pack-{file:[0-9a-f]{40}}.idx", repo.GetIdxFile) + m.Methods("POST,OPTIONS", "/git-upload-pack", repo.ServiceUploadPack) + m.Methods("POST,OPTIONS", "/git-receive-pack", repo.ServiceReceivePack) + m.Methods("GET,OPTIONS", "/info/refs", repo.GetInfoRefs) + m.Methods("GET,OPTIONS", "/HEAD", repo.GetTextFile("HEAD")) + m.Methods("GET,OPTIONS", "/objects/info/alternates", repo.GetTextFile("objects/info/alternates")) + m.Methods("GET,OPTIONS", "/objects/info/http-alternates", repo.GetTextFile("objects/info/http-alternates")) + m.Methods("GET,OPTIONS", "/objects/info/packs", repo.GetInfoPacks) + m.Methods("GET,OPTIONS", "/objects/info/{file:[^/]*}", repo.GetTextFile("")) + m.Methods("GET,OPTIONS", "/objects/{head:[0-9a-f]{2}}/{hash:[0-9a-f]{38}}", repo.GetLooseObject) + m.Methods("GET,OPTIONS", "/objects/pack/pack-{file:[0-9a-f]{40}}.pack", repo.GetPackFile) + m.Methods("GET,OPTIONS", "/objects/pack/pack-{file:[0-9a-f]{40}}.idx", repo.GetIdxFile) }, ignSignInAndCsrf, requireSignIn, repo.HTTPGitEnabledHandler, repo.CorsHandler(), context_service.UserAssignmentWeb()) } diff --git a/routers/web/misc/misc.go b/routers/web/misc/misc.go index e3519940107..54c93763f6a 100644 --- a/routers/web/misc/misc.go +++ b/routers/web/misc/misc.go @@ -33,10 +33,6 @@ func DummyOK(w http.ResponseWriter, req *http.Request) { w.WriteHeader(http.StatusOK) } -func DummyBadRequest(w http.ResponseWriter, req *http.Request) { - w.WriteHeader(http.StatusBadRequest) -} - func RobotsTxt(w http.ResponseWriter, req *http.Request) { robotsTxt := util.FilePathJoinAbs(setting.CustomPath, "public/robots.txt") if ok, _ := util.IsExist(robotsTxt); !ok { diff --git a/routers/web/web.go b/routers/web/web.go index 02fb11b1f51..164c137f2a3 100644 --- a/routers/web/web.go +++ b/routers/web/web.go @@ -60,13 +60,12 @@ const ( GzipMinSize = 1400 ) -// CorsHandler return a http handler who set CORS options if enabled by config -func CorsHandler() func(next http.Handler) http.Handler { +// optionsCorsHandler return a http handler which sets CORS options if enabled by config, it blocks non-CORS OPTIONS requests. +func optionsCorsHandler() func(next http.Handler) http.Handler { + var corsHandler func(next http.Handler) http.Handler if setting.CORSConfig.Enabled { - return cors.Handler(cors.Options{ - // Scheme: setting.CORSConfig.Scheme, // FIXME: the cors middleware needs scheme option - AllowedOrigins: setting.CORSConfig.AllowDomain, - // setting.CORSConfig.AllowSubdomain // FIXME: the cors middleware needs allowSubdomain option + corsHandler = cors.Handler(cors.Options{ + AllowedOrigins: setting.CORSConfig.AllowDomain, AllowedMethods: setting.CORSConfig.Methods, AllowCredentials: setting.CORSConfig.AllowCredentials, AllowedHeaders: setting.CORSConfig.Headers, @@ -75,7 +74,23 @@ func CorsHandler() func(next http.Handler) http.Handler { } return func(next http.Handler) http.Handler { - return next + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Method == http.MethodOptions { + if corsHandler != nil && r.Header.Get("Access-Control-Request-Method") != "" { + corsHandler(next).ServeHTTP(w, r) + } else { + // it should explicitly deny OPTIONS requests if CORS handler is not executed, to avoid the next GET/POST handler being incorrectly called by the OPTIONS request + w.WriteHeader(http.StatusMethodNotAllowed) + } + return + } + // for non-OPTIONS requests, call the CORS handler to add some related headers like "Vary" + if corsHandler != nil { + corsHandler(next).ServeHTTP(w, r) + } else { + next.ServeHTTP(w, r) + } + }) } } @@ -218,7 +233,7 @@ func Routes() *web.Route { routes := web.NewRoute() routes.Head("/", misc.DummyOK) // for health check - doesn't need to be passed through gzip handler - routes.Methods("GET, HEAD", "/assets/*", CorsHandler(), public.FileHandlerFunc()) + routes.Methods("GET, HEAD, OPTIONS", "/assets/*", optionsCorsHandler(), public.FileHandlerFunc()) routes.Methods("GET, HEAD", "/avatars/*", storageHandler(setting.Avatar.Storage, "avatars", storage.Avatars)) routes.Methods("GET, HEAD", "/repo-avatars/*", storageHandler(setting.RepoAvatar.Storage, "repo-avatars", storage.RepoAvatars)) routes.Methods("GET, HEAD", "/apple-touch-icon.png", misc.StaticRedirect("/assets/img/apple-touch-icon.png")) @@ -458,8 +473,8 @@ func registerRoutes(m *web.Route) { m.Get("/change-password", func(ctx *context.Context) { ctx.Redirect(setting.AppSubURL + "/user/settings/account") }) - m.Any("/*", CorsHandler(), public.FileHandlerFunc()) - }, CorsHandler()) + m.Methods("GET, HEAD", "/*", public.FileHandlerFunc()) + }, optionsCorsHandler()) m.Group("/explore", func() { m.Get("", func(ctx *context.Context) { @@ -532,14 +547,11 @@ func registerRoutes(m *web.Route) { // TODO manage redirection m.Post("/authorize", web.Bind(forms.AuthorizationForm{}), auth.AuthorizeOAuth) }, ignSignInAndCsrf, reqSignIn) - m.Options("/login/oauth/userinfo", CorsHandler(), misc.DummyBadRequest) - m.Get("/login/oauth/userinfo", ignSignInAndCsrf, auth.InfoOAuth) - m.Options("/login/oauth/access_token", CorsHandler(), misc.DummyBadRequest) - m.Post("/login/oauth/access_token", CorsHandler(), web.Bind(forms.AccessTokenForm{}), ignSignInAndCsrf, auth.AccessTokenOAuth) - m.Options("/login/oauth/keys", CorsHandler(), misc.DummyBadRequest) - m.Get("/login/oauth/keys", ignSignInAndCsrf, auth.OIDCKeys) - m.Options("/login/oauth/introspect", CorsHandler(), misc.DummyBadRequest) - m.Post("/login/oauth/introspect", CorsHandler(), web.Bind(forms.IntrospectTokenForm{}), ignSignInAndCsrf, auth.IntrospectOAuth) + + m.Methods("GET, OPTIONS", "/login/oauth/userinfo", optionsCorsHandler(), ignSignInAndCsrf, auth.InfoOAuth) + m.Methods("POST, OPTIONS", "/login/oauth/access_token", optionsCorsHandler(), web.Bind(forms.AccessTokenForm{}), ignSignInAndCsrf, auth.AccessTokenOAuth) + m.Methods("GET, OPTIONS", "/login/oauth/keys", optionsCorsHandler(), ignSignInAndCsrf, auth.OIDCKeys) + m.Methods("POST, OPTIONS", "/login/oauth/introspect", optionsCorsHandler(), web.Bind(forms.IntrospectTokenForm{}), ignSignInAndCsrf, auth.IntrospectOAuth) m.Group("/user/settings", func() { m.Get("", user_setting.Profile) @@ -770,7 +782,7 @@ func registerRoutes(m *web.Route) { m.Group("", func() { m.Get("/{username}", user.UsernameSubRoute) - m.Get("/attachments/{uuid}", repo.GetAttachment) + m.Methods("GET, OPTIONS", "/attachments/{uuid}", optionsCorsHandler(), repo.GetAttachment) }, ignSignIn) m.Post("/{username}", reqSignIn, context_service.UserAssignmentWeb(), user.Action) diff --git a/tests/integration/cors_test.go b/tests/integration/cors_test.go index 83d200402c8..25dfbabf41e 100644 --- a/tests/integration/cors_test.go +++ b/tests/integration/cors_test.go @@ -7,17 +7,88 @@ import ( "net/http" "testing" + "code.gitea.io/gitea/modules/setting" + "code.gitea.io/gitea/modules/test" + "code.gitea.io/gitea/routers" "code.gitea.io/gitea/tests" "github.com/stretchr/testify/assert" ) -func TestCORSNotSet(t *testing.T) { +func TestCORS(t *testing.T) { defer tests.PrepareTestEnv(t)() - req := NewRequest(t, "GET", "/api/v1/version") - session := loginUser(t, "user2") - resp := session.MakeRequest(t, req, http.StatusOK) - assert.Equal(t, resp.Code, http.StatusOK) - corsHeader := resp.Header().Get("Access-Control-Allow-Origin") - assert.Empty(t, corsHeader, "Access-Control-Allow-Origin: generated header should match") // header not set + t.Run("CORS enabled", func(t *testing.T) { + defer test.MockVariableValue(&setting.CORSConfig.Enabled, true)() + defer test.MockVariableValue(&testWebRoutes, routers.NormalRoutes())() + + t.Run("API with CORS", func(t *testing.T) { + // GET api with no CORS header + req := NewRequest(t, "GET", "/api/v1/version") + resp := MakeRequest(t, req, http.StatusOK) + assert.Empty(t, resp.Header().Get("Access-Control-Allow-Origin")) + assert.Contains(t, resp.Header().Values("Vary"), "Origin") + + // OPTIONS api for CORS + req = NewRequest(t, "OPTIONS", "/api/v1/version"). + SetHeader("Origin", "https://example.com"). + SetHeader("Access-Control-Request-Method", "GET") + resp = MakeRequest(t, req, http.StatusOK) + assert.NotEmpty(t, resp.Header().Get("Access-Control-Allow-Origin")) + assert.Contains(t, resp.Header().Values("Vary"), "Origin") + }) + + t.Run("Web with CORS", func(t *testing.T) { + // GET userinfo with no CORS header + req := NewRequest(t, "GET", "/login/oauth/userinfo") + resp := MakeRequest(t, req, http.StatusUnauthorized) + assert.Empty(t, resp.Header().Get("Access-Control-Allow-Origin")) + assert.Contains(t, resp.Header().Values("Vary"), "Origin") + + // OPTIONS userinfo for CORS + req = NewRequest(t, "OPTIONS", "/login/oauth/userinfo"). + SetHeader("Origin", "https://example.com"). + SetHeader("Access-Control-Request-Method", "GET") + resp = MakeRequest(t, req, http.StatusOK) + assert.NotEmpty(t, resp.Header().Get("Access-Control-Allow-Origin")) + assert.Contains(t, resp.Header().Values("Vary"), "Origin") + + // OPTIONS userinfo for non-CORS + req = NewRequest(t, "OPTIONS", "/login/oauth/userinfo") + resp = MakeRequest(t, req, http.StatusMethodNotAllowed) + assert.NotContains(t, resp.Header().Values("Vary"), "Origin") + }) + }) + + t.Run("CORS disabled", func(t *testing.T) { + defer test.MockVariableValue(&setting.CORSConfig.Enabled, false)() + defer test.MockVariableValue(&testWebRoutes, routers.NormalRoutes())() + + t.Run("API without CORS", func(t *testing.T) { + req := NewRequest(t, "GET", "/api/v1/version") + resp := MakeRequest(t, req, http.StatusOK) + assert.Empty(t, resp.Header().Get("Access-Control-Allow-Origin")) + assert.Empty(t, resp.Header().Values("Vary")) + + req = NewRequest(t, "OPTIONS", "/api/v1/version"). + SetHeader("Origin", "https://example.com"). + SetHeader("Access-Control-Request-Method", "GET") + resp = MakeRequest(t, req, http.StatusMethodNotAllowed) + assert.Empty(t, resp.Header().Get("Access-Control-Allow-Origin")) + assert.Empty(t, resp.Header().Values("Vary")) + }) + + t.Run("Web without CORS", func(t *testing.T) { + req := NewRequest(t, "GET", "/login/oauth/userinfo") + resp := MakeRequest(t, req, http.StatusUnauthorized) + assert.Empty(t, resp.Header().Get("Access-Control-Allow-Origin")) + assert.NotContains(t, resp.Header().Values("Vary"), "Origin") + + req = NewRequest(t, "OPTIONS", "/login/oauth/userinfo"). + SetHeader("Origin", "https://example.com"). + SetHeader("Access-Control-Request-Method", "GET") + resp = MakeRequest(t, req, http.StatusMethodNotAllowed) + assert.Empty(t, resp.Header().Get("Access-Control-Allow-Origin")) + assert.NotContains(t, resp.Header().Values("Vary"), "Origin") + }) + }) } From 778ad795fd4a19dc15723b59a846a250034c7c3a Mon Sep 17 00:00:00 2001 From: delvh Date: Mon, 25 Dec 2023 21:25:29 +0100 Subject: [PATCH 027/189] Refactor deletion (#28610) Introduce the new generic deletion methods - `func DeleteByID[T any](ctx context.Context, id int64) (int64, error)` - `func DeleteByIDs[T any](ctx context.Context, ids ...int64) error` - `func Delete[T any](ctx context.Context, opts FindOptions) (int64, error)` So, we no longer need any specific deletion method and can just use the generic ones instead. Replacement of #28450 Closes #28450 --------- Co-authored-by: Lunny Xiao --- models/actions/artifact.go | 13 --------- models/actions/runner.go | 2 +- models/asymkey/ssh_key.go | 14 ++-------- models/db/context.go | 34 +++++++++++++++++++----- models/db/error.go | 18 ------------- models/issues/issue_test.go | 4 +-- models/issues/label.go | 2 +- models/issues/milestone.go | 6 ++--- models/issues/review.go | 11 ++++---- models/org.go | 2 +- models/repo.go | 6 ++--- models/repo/archiver.go | 15 +---------- models/repo/pushmirror.go | 22 +++------------ models/repo/pushmirror_test.go | 6 ++--- models/repo/release.go | 8 +----- models/repo/upload.go | 4 +-- models/repo/watch.go | 10 +++---- models/system/notice.go | 17 ------------ models/system/notice_test.go | 11 ++------ models/webhook/webhook.go | 2 +- routers/api/actions/artifacts.go | 13 +++++---- routers/api/v1/repo/mirror.go | 13 ++++++--- routers/web/admin/notice.go | 3 ++- routers/web/repo/setting/setting.go | 2 +- services/asymkey/ssh_key.go | 2 +- services/mirror/mirror_push.go | 6 +++-- services/release/release.go | 2 +- services/repository/archiver/archiver.go | 4 +-- services/secrets/secrets.go | 2 +- services/user/delete.go | 2 +- tests/integration/repo_tag_test.go | 2 +- 31 files changed, 89 insertions(+), 169 deletions(-) diff --git a/models/actions/artifact.go b/models/actions/artifact.go index 42bd9c23cb4..5390f6288f1 100644 --- a/models/actions/artifact.go +++ b/models/actions/artifact.go @@ -90,19 +90,6 @@ func getArtifactByNameAndPath(ctx context.Context, runID int64, name, fpath stri return &art, nil } -// GetArtifactByID returns an artifact by id -func GetArtifactByID(ctx context.Context, id int64) (*ActionArtifact, error) { - var art ActionArtifact - has, err := db.GetEngine(ctx).ID(id).Get(&art) - if err != nil { - return nil, err - } else if !has { - return nil, util.ErrNotExist - } - - return &art, nil -} - // UpdateArtifactByID updates an artifact by id func UpdateArtifactByID(ctx context.Context, id int64, art *ActionArtifact) error { art.ID = id diff --git a/models/actions/runner.go b/models/actions/runner.go index 5630741550d..4103ba44776 100644 --- a/models/actions/runner.go +++ b/models/actions/runner.go @@ -254,7 +254,7 @@ func DeleteRunner(ctx context.Context, id int64) error { return err } - _, err := db.GetEngine(ctx).Delete(&ActionRunner{ID: id}) + _, err := db.DeleteByID[ActionRunner](ctx, id) return err } diff --git a/models/asymkey/ssh_key.go b/models/asymkey/ssh_key.go index 552f2ffd69e..116d6351b0d 100644 --- a/models/asymkey/ssh_key.go +++ b/models/asymkey/ssh_key.go @@ -227,16 +227,6 @@ func UpdatePublicKeyUpdated(ctx context.Context, id int64) error { return nil } -// DeletePublicKeys does the actual key deletion but does not update authorized_keys file. -func DeletePublicKeys(ctx context.Context, keyIDs ...int64) error { - if len(keyIDs) == 0 { - return nil - } - - _, err := db.GetEngine(ctx).In("id", keyIDs).Delete(new(PublicKey)) - return err -} - // PublicKeysAreExternallyManaged returns whether the provided KeyID represents an externally managed Key func PublicKeysAreExternallyManaged(ctx context.Context, keys []*PublicKey) ([]bool, error) { sources := make([]*auth.Source, 0, 5) @@ -322,8 +312,8 @@ func deleteKeysMarkedForDeletion(ctx context.Context, keys []string) (bool, erro log.Error("SearchPublicKeyByContent: %v", err) continue } - if err = DeletePublicKeys(ctx, key.ID); err != nil { - log.Error("deletePublicKeys: %v", err) + if _, err = db.DeleteByID[PublicKey](ctx, key.ID); err != nil { + log.Error("DeleteByID[PublicKey]: %v", err) continue } sshKeysNeedUpdate = true diff --git a/models/db/context.go b/models/db/context.go index 7b739f7e9f3..cda608af196 100644 --- a/models/db/context.go +++ b/models/db/context.go @@ -175,7 +175,7 @@ func Exec(ctx context.Context, sqlAndArgs ...any) (sql.Result, error) { func Get[T any](ctx context.Context, cond builder.Cond) (object *T, exist bool, err error) { if !cond.IsValid() { - return nil, false, ErrConditionRequired{} + panic("cond is invalid in db.Get(ctx, cond). This should not be possible.") } var bean T @@ -201,7 +201,7 @@ func GetByID[T any](ctx context.Context, id int64) (object *T, exist bool, err e func Exist[T any](ctx context.Context, cond builder.Cond) (bool, error) { if !cond.IsValid() { - return false, ErrConditionRequired{} + panic("cond is invalid in db.Exist(ctx, cond). This should not be possible.") } var bean T @@ -213,16 +213,36 @@ func ExistByID[T any](ctx context.Context, id int64) (bool, error) { return GetEngine(ctx).ID(id).NoAutoCondition().Exist(&bean) } +// DeleteByID deletes the given bean with the given ID +func DeleteByID[T any](ctx context.Context, id int64) (int64, error) { + var bean T + return GetEngine(ctx).ID(id).NoAutoCondition().NoAutoTime().Delete(&bean) +} + +func DeleteByIDs[T any](ctx context.Context, ids ...int64) error { + if len(ids) == 0 { + return nil + } + + var bean T + _, err := GetEngine(ctx).In("id", ids).NoAutoCondition().NoAutoTime().Delete(&bean) + return err +} + +func Delete[T any](ctx context.Context, opts FindOptions) (int64, error) { + if opts == nil || !opts.ToConds().IsValid() { + panic("opts are empty or invalid in db.Delete(ctx, opts). This should not be possible.") + } + + var bean T + return GetEngine(ctx).Where(opts.ToConds()).NoAutoCondition().NoAutoTime().Delete(&bean) +} + // DeleteByBean deletes all records according non-empty fields of the bean as conditions. func DeleteByBean(ctx context.Context, bean any) (int64, error) { return GetEngine(ctx).Delete(bean) } -// DeleteByID deletes the given bean with the given ID -func DeleteByID(ctx context.Context, id int64, bean any) (int64, error) { - return GetEngine(ctx).ID(id).NoAutoCondition().NoAutoTime().Delete(bean) -} - // FindIDs finds the IDs for the given table name satisfying the given condition // By passing a different value than "id" for "idCol", you can query for foreign IDs, i.e. the repo IDs which satisfy the condition func FindIDs(ctx context.Context, tableName, idCol string, cond builder.Cond) ([]int64, error) { diff --git a/models/db/error.go b/models/db/error.go index f601a15c01e..665e970e17c 100644 --- a/models/db/error.go +++ b/models/db/error.go @@ -72,21 +72,3 @@ func (err ErrNotExist) Error() string { func (err ErrNotExist) Unwrap() error { return util.ErrNotExist } - -// ErrConditionRequired represents an error which require condition. -type ErrConditionRequired struct{} - -// IsErrConditionRequired checks if an error is an ErrConditionRequired -func IsErrConditionRequired(err error) bool { - _, ok := err.(ErrConditionRequired) - return ok -} - -func (err ErrConditionRequired) Error() string { - return "condition is required" -} - -// Unwrap unwraps this as a ErrNotExist err -func (err ErrConditionRequired) Unwrap() error { - return util.ErrInvalidArgument -} diff --git a/models/issues/issue_test.go b/models/issues/issue_test.go index 723fa27b1be..cc363d2fae7 100644 --- a/models/issues/issue_test.go +++ b/models/issues/issue_test.go @@ -249,11 +249,11 @@ func TestIssue_InsertIssue(t *testing.T) { // there are 5 issues and max index is 5 on repository 1, so this one should 6 issue := testInsertIssue(t, "my issue1", "special issue's comments?", 6) - _, err := db.GetEngine(db.DefaultContext).ID(issue.ID).Delete(new(issues_model.Issue)) + _, err := db.DeleteByID[issues_model.Issue](db.DefaultContext, issue.ID) assert.NoError(t, err) issue = testInsertIssue(t, `my issue2, this is my son's love \n \r \ `, "special issue's '' comments?", 7) - _, err = db.GetEngine(db.DefaultContext).ID(issue.ID).Delete(new(issues_model.Issue)) + _, err = db.DeleteByID[issues_model.Issue](db.DefaultContext, issue.ID) assert.NoError(t, err) } diff --git a/models/issues/label.go b/models/issues/label.go index 3b811c1529a..527d8d78532 100644 --- a/models/issues/label.go +++ b/models/issues/label.go @@ -256,7 +256,7 @@ func DeleteLabel(ctx context.Context, id, labelID int64) error { return nil } - if _, err = sess.ID(labelID).Delete(new(Label)); err != nil { + if _, err = db.DeleteByID[Label](ctx, labelID); err != nil { return err } else if _, err = sess. Where("label_id = ?", labelID). diff --git a/models/issues/milestone.go b/models/issues/milestone.go index 9db7cb2b15e..eb42df8263b 100644 --- a/models/issues/milestone.go +++ b/models/issues/milestone.go @@ -289,9 +289,7 @@ func DeleteMilestoneByRepoID(ctx context.Context, repoID, id int64) error { } defer committer.Close() - sess := db.GetEngine(ctx) - - if _, err = sess.ID(m.ID).Delete(new(Milestone)); err != nil { + if _, err = db.DeleteByID[Milestone](ctx, m.ID); err != nil { return err } @@ -311,7 +309,7 @@ func DeleteMilestoneByRepoID(ctx context.Context, repoID, id int64) error { repo.NumMilestones = int(numMilestones) repo.NumClosedMilestones = int(numClosedMilestones) - if _, err = sess.ID(repo.ID).Cols("num_milestones, num_closed_milestones").Update(repo); err != nil { + if _, err = db.GetEngine(ctx).ID(repo.ID).Cols("num_milestones, num_closed_milestones").Update(repo); err != nil { return err } diff --git a/models/issues/review.go b/models/issues/review.go index e2f65e369f1..e06670c9a10 100644 --- a/models/issues/review.go +++ b/models/issues/review.go @@ -446,7 +446,7 @@ func SubmitReview(ctx context.Context, doer *user_model.User, issue *Issue, revi continue } - if _, err := sess.ID(teamReviewRequest.ID).NoAutoCondition().Delete(teamReviewRequest); err != nil { + if _, err := db.DeleteByID[Review](ctx, teamReviewRequest.ID); err != nil { return nil, nil, err } } @@ -869,7 +869,6 @@ func DeleteReview(ctx context.Context, r *Review) error { return err } defer committer.Close() - sess := db.GetEngine(ctx) if r.ID == 0 { return fmt.Errorf("review is not allowed to be 0") @@ -885,7 +884,7 @@ func DeleteReview(ctx context.Context, r *Review) error { ReviewID: r.ID, } - if _, err := sess.Where(opts.ToConds()).Delete(new(Comment)); err != nil { + if _, err := db.Delete[Comment](ctx, opts); err != nil { return err } @@ -895,7 +894,7 @@ func DeleteReview(ctx context.Context, r *Review) error { ReviewID: r.ID, } - if _, err := sess.Where(opts.ToConds()).Delete(new(Comment)); err != nil { + if _, err := db.Delete[Comment](ctx, opts); err != nil { return err } @@ -905,11 +904,11 @@ func DeleteReview(ctx context.Context, r *Review) error { ReviewID: r.ID, } - if _, err := sess.Where(opts.ToConds()).Delete(new(Comment)); err != nil { + if _, err := db.Delete[Comment](ctx, opts); err != nil { return err } - if _, err := sess.ID(r.ID).Delete(new(Review)); err != nil { + if _, err := db.DeleteByID[Review](ctx, r.ID); err != nil { return err } diff --git a/models/org.go b/models/org.go index 5e0deeb8de7..5f61f05b16a 100644 --- a/models/org.go +++ b/models/org.go @@ -57,7 +57,7 @@ func RemoveOrgUser(ctx context.Context, orgID, userID int64) error { } defer committer.Close() - if _, err := db.GetEngine(ctx).ID(ou.ID).Delete(ou); err != nil { + if _, err := db.DeleteByID[organization.OrgUser](ctx, ou.ID); err != nil { return err } else if _, err = db.Exec(ctx, "UPDATE `user` SET num_members=num_members-1 WHERE id=?", orgID); err != nil { return err diff --git a/models/repo.go b/models/repo.go index d525264b3b7..0dc8ee5df33 100644 --- a/models/repo.go +++ b/models/repo.go @@ -344,9 +344,7 @@ func DeleteDeployKey(ctx context.Context, doer *user_model.User, id int64) error } } - if _, err := db.DeleteByBean(ctx, &asymkey_model.DeployKey{ - ID: key.ID, - }); err != nil { + if _, err := db.DeleteByID[asymkey_model.DeployKey](ctx, key.ID); err != nil { return fmt.Errorf("delete deploy key [%d]: %w", key.ID, err) } @@ -355,7 +353,7 @@ func DeleteDeployKey(ctx context.Context, doer *user_model.User, id int64) error if err != nil { return err } else if !has { - if err = asymkey_model.DeletePublicKeys(ctx, key.KeyID); err != nil { + if _, err = db.DeleteByID[asymkey_model.PublicKey](ctx, key.KeyID); err != nil { return err } } diff --git a/models/repo/archiver.go b/models/repo/archiver.go index 6d0ed42877f..1fccb294994 100644 --- a/models/repo/archiver.go +++ b/models/repo/archiver.go @@ -68,14 +68,6 @@ func repoArchiverForRelativePath(relativePath string) (*RepoArchiver, error) { }, nil } -var delRepoArchiver = new(RepoArchiver) - -// DeleteRepoArchiver delete archiver -func DeleteRepoArchiver(ctx context.Context, archiver *RepoArchiver) error { - _, err := db.GetEngine(ctx).ID(archiver.ID).Delete(delRepoArchiver) - return err -} - // GetRepoArchiver get an archiver func GetRepoArchiver(ctx context.Context, repoID int64, tp git.ArchiveType, commitID string) (*RepoArchiver, error) { var archiver RepoArchiver @@ -100,12 +92,6 @@ func ExistsRepoArchiverWithStoragePath(ctx context.Context, storagePath string) return db.GetEngine(ctx).Exist(archiver) } -// AddRepoArchiver adds an archiver -func AddRepoArchiver(ctx context.Context, archiver *RepoArchiver) error { - _, err := db.GetEngine(ctx).Insert(archiver) - return err -} - // UpdateRepoArchiverStatus updates archiver's status func UpdateRepoArchiverStatus(ctx context.Context, archiver *RepoArchiver) error { _, err := db.GetEngine(ctx).ID(archiver.ID).Cols("status").Update(archiver) @@ -114,6 +100,7 @@ func UpdateRepoArchiverStatus(ctx context.Context, archiver *RepoArchiver) error // DeleteAllRepoArchives deletes all repo archives records func DeleteAllRepoArchives(ctx context.Context) error { + // 1=1 to enforce delete all data, otherwise it will delete nothing _, err := db.GetEngine(ctx).Where("1=1").Delete(new(RepoArchiver)) return err } diff --git a/models/repo/pushmirror.go b/models/repo/pushmirror.go index 61cf1849b00..24c58faf849 100644 --- a/models/repo/pushmirror.go +++ b/models/repo/pushmirror.go @@ -34,12 +34,13 @@ type PushMirror struct { } type PushMirrorOptions struct { + db.ListOptions ID int64 RepoID int64 RemoteName string } -func (opts *PushMirrorOptions) toConds() builder.Cond { +func (opts PushMirrorOptions) ToConds() builder.Cond { cond := builder.NewCond() if opts.RepoID > 0 { cond = cond.And(builder.Eq{"repo_id": opts.RepoID}) @@ -75,12 +76,6 @@ func (m *PushMirror) GetRemoteName() string { return m.RemoteName } -// InsertPushMirror inserts a push-mirror to database -func InsertPushMirror(ctx context.Context, m *PushMirror) error { - _, err := db.GetEngine(ctx).Insert(m) - return err -} - // UpdatePushMirror updates the push-mirror func UpdatePushMirror(ctx context.Context, m *PushMirror) error { _, err := db.GetEngine(ctx).ID(m.ID).AllCols().Update(m) @@ -95,23 +90,12 @@ func UpdatePushMirrorInterval(ctx context.Context, m *PushMirror) error { func DeletePushMirrors(ctx context.Context, opts PushMirrorOptions) error { if opts.RepoID > 0 { - _, err := db.GetEngine(ctx).Where(opts.toConds()).Delete(&PushMirror{}) + _, err := db.Delete[PushMirror](ctx, opts) return err } return util.NewInvalidArgumentErrorf("repoID required and must be set") } -func GetPushMirror(ctx context.Context, opts PushMirrorOptions) (*PushMirror, error) { - mirror := &PushMirror{} - exist, err := db.GetEngine(ctx).Where(opts.toConds()).Get(mirror) - if err != nil { - return nil, err - } else if !exist { - return nil, ErrPushMirrorNotExist - } - return mirror, nil -} - // GetPushMirrorsByRepoID returns push-mirror information of a repository. func GetPushMirrorsByRepoID(ctx context.Context, repoID int64, listOptions db.ListOptions) ([]*PushMirror, int64, error) { sess := db.GetEngine(ctx).Where("repo_id = ?", repoID) diff --git a/models/repo/pushmirror_test.go b/models/repo/pushmirror_test.go index 9ab70235913..e19749d93a2 100644 --- a/models/repo/pushmirror_test.go +++ b/models/repo/pushmirror_test.go @@ -20,20 +20,20 @@ func TestPushMirrorsIterate(t *testing.T) { now := timeutil.TimeStampNow() - repo_model.InsertPushMirror(db.DefaultContext, &repo_model.PushMirror{ + db.Insert(db.DefaultContext, &repo_model.PushMirror{ RemoteName: "test-1", LastUpdateUnix: now, Interval: 1, }) long, _ := time.ParseDuration("24h") - repo_model.InsertPushMirror(db.DefaultContext, &repo_model.PushMirror{ + db.Insert(db.DefaultContext, &repo_model.PushMirror{ RemoteName: "test-2", LastUpdateUnix: now, Interval: long, }) - repo_model.InsertPushMirror(db.DefaultContext, &repo_model.PushMirror{ + db.Insert(db.DefaultContext, &repo_model.PushMirror{ RemoteName: "test-3", LastUpdateUnix: now, Interval: 0, diff --git a/models/repo/release.go b/models/repo/release.go index 223d3f25019..4514a034ed9 100644 --- a/models/repo/release.go +++ b/models/repo/release.go @@ -450,12 +450,6 @@ func SortReleases(rels []*Release) { sort.Sort(sorter) } -// DeleteReleaseByID deletes a release from database by given ID. -func DeleteReleaseByID(ctx context.Context, id int64) error { - _, err := db.GetEngine(ctx).ID(id).Delete(new(Release)) - return err -} - // UpdateReleasesMigrationsByType updates all migrated repositories' releases from gitServiceType to replace originalAuthorID to posterID func UpdateReleasesMigrationsByType(ctx context.Context, gitServiceType structs.GitServiceType, originalAuthorID string, posterID int64) error { _, err := db.GetEngine(ctx).Table("release"). @@ -509,7 +503,7 @@ func PushUpdateDeleteTag(ctx context.Context, repo *Repository, tagName string) return fmt.Errorf("GetRelease: %w", err) } if rel.IsTag { - if _, err = db.GetEngine(ctx).ID(rel.ID).Delete(new(Release)); err != nil { + if _, err = db.DeleteByID[Release](ctx, rel.ID); err != nil { return fmt.Errorf("Delete: %w", err) } } else { diff --git a/models/repo/upload.go b/models/repo/upload.go index d96ab21bcde..18834f6b83f 100644 --- a/models/repo/upload.go +++ b/models/repo/upload.go @@ -131,9 +131,7 @@ func DeleteUploads(ctx context.Context, uploads ...*Upload) (err error) { for i := 0; i < len(uploads); i++ { ids[i] = uploads[i].ID } - if _, err = db.GetEngine(ctx). - In("id", ids). - Delete(new(Upload)); err != nil { + if err = db.DeleteByIDs[Upload](ctx, ids...); err != nil { return fmt.Errorf("delete uploads: %w", err) } diff --git a/models/repo/watch.go b/models/repo/watch.go index fba66d6dcb5..80da4030cbc 100644 --- a/models/repo/watch.go +++ b/models/repo/watch.go @@ -85,23 +85,21 @@ func watchRepoMode(ctx context.Context, watch Watch, mode WatchMode) (err error) watch.Mode = mode - e := db.GetEngine(ctx) - if !hadrec && needsrec { watch.Mode = mode - if _, err = e.Insert(watch); err != nil { + if err = db.Insert(ctx, watch); err != nil { return err } } else if needsrec { watch.Mode = mode - if _, err := e.ID(watch.ID).AllCols().Update(watch); err != nil { + if _, err := db.GetEngine(ctx).ID(watch.ID).AllCols().Update(watch); err != nil { return err } - } else if _, err = e.Delete(Watch{ID: watch.ID}); err != nil { + } else if _, err = db.DeleteByID[Watch](ctx, watch.ID); err != nil { return err } if repodiff != 0 { - _, err = e.Exec("UPDATE `repository` SET num_watches = num_watches + ? WHERE id = ?", repodiff, watch.RepoID) + _, err = db.GetEngine(ctx).Exec("UPDATE `repository` SET num_watches = num_watches + ? WHERE id = ?", repodiff, watch.RepoID) } return err } diff --git a/models/system/notice.go b/models/system/notice.go index 058b78e6771..e7ec6a9693f 100644 --- a/models/system/notice.go +++ b/models/system/notice.go @@ -102,12 +102,6 @@ func Notices(ctx context.Context, page, pageSize int) ([]*Notice, error) { Find(¬ices) } -// DeleteNotice deletes a system notice by given ID. -func DeleteNotice(ctx context.Context, id int64) error { - _, err := db.GetEngine(ctx).ID(id).Delete(new(Notice)) - return err -} - // DeleteNotices deletes all notices with ID from start to end (inclusive). func DeleteNotices(ctx context.Context, start, end int64) error { if start == 0 && end == 0 { @@ -123,17 +117,6 @@ func DeleteNotices(ctx context.Context, start, end int64) error { return err } -// DeleteNoticesByIDs deletes notices by given IDs. -func DeleteNoticesByIDs(ctx context.Context, ids []int64) error { - if len(ids) == 0 { - return nil - } - _, err := db.GetEngine(ctx). - In("id", ids). - Delete(new(Notice)) - return err -} - // DeleteOldSystemNotices deletes all old system notices from database. func DeleteOldSystemNotices(ctx context.Context, olderThan time.Duration) (err error) { if olderThan <= 0 { diff --git a/models/system/notice_test.go b/models/system/notice_test.go index e8ce05d3324..599b2fb65c3 100644 --- a/models/system/notice_test.go +++ b/models/system/notice_test.go @@ -69,14 +69,6 @@ func TestNotices(t *testing.T) { } } -func TestDeleteNotice(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) - - unittest.AssertExistsAndLoadBean(t, &system.Notice{ID: 3}) - assert.NoError(t, system.DeleteNotice(db.DefaultContext, 3)) - unittest.AssertNotExistsBean(t, &system.Notice{ID: 3}) -} - func TestDeleteNotices(t *testing.T) { // delete a non-empty range assert.NoError(t, unittest.PrepareTestDatabase()) @@ -109,7 +101,8 @@ func TestDeleteNoticesByIDs(t *testing.T) { unittest.AssertExistsAndLoadBean(t, &system.Notice{ID: 1}) unittest.AssertExistsAndLoadBean(t, &system.Notice{ID: 2}) unittest.AssertExistsAndLoadBean(t, &system.Notice{ID: 3}) - assert.NoError(t, system.DeleteNoticesByIDs(db.DefaultContext, []int64{1, 3})) + err := db.DeleteByIDs[system.Notice](db.DefaultContext, 1, 3) + assert.NoError(t, err) unittest.AssertNotExistsBean(t, &system.Notice{ID: 1}) unittest.AssertExistsAndLoadBean(t, &system.Notice{ID: 2}) unittest.AssertNotExistsBean(t, &system.Notice{ID: 3}) diff --git a/models/webhook/webhook.go b/models/webhook/webhook.go index a72bd938aac..4a84a3d4111 100644 --- a/models/webhook/webhook.go +++ b/models/webhook/webhook.go @@ -471,7 +471,7 @@ func DeleteWebhookByID(ctx context.Context, id int64) (err error) { } defer committer.Close() - if count, err := db.DeleteByID(ctx, id, new(Webhook)); err != nil { + if count, err := db.DeleteByID[Webhook](ctx, id); err != nil { return err } else if count == 0 { return ErrWebhookNotExist{ID: id} diff --git a/routers/api/actions/artifacts.go b/routers/api/actions/artifacts.go index 5411237103a..5bfcc9dfcd7 100644 --- a/routers/api/actions/artifacts.go +++ b/routers/api/actions/artifacts.go @@ -63,7 +63,6 @@ package actions import ( "crypto/md5" - "errors" "fmt" "net/http" "strconv" @@ -423,15 +422,15 @@ func (ar artifactRoutes) downloadArtifact(ctx *ArtifactContext) { } artifactID := ctx.ParamsInt64("artifact_id") - artifact, err := actions.GetArtifactByID(ctx, artifactID) - if errors.Is(err, util.ErrNotExist) { - log.Error("Error getting artifact: %v", err) - ctx.Error(http.StatusNotFound, err.Error()) - return - } else if err != nil { + artifact, exist, err := db.GetByID[actions.ActionArtifact](ctx, artifactID) + if err != nil { log.Error("Error getting artifact: %v", err) ctx.Error(http.StatusInternalServerError, err.Error()) return + } else if !exist { + log.Error("artifact with ID %d does not exist", artifactID) + ctx.Error(http.StatusNotFound, fmt.Sprintf("artifact with ID %d does not exist", artifactID)) + return } if artifact.RunID != runID { log.Error("Error dismatch runID and artifactID, task: %v, artifact: %v", runID, artifactID) diff --git a/routers/api/v1/repo/mirror.go b/routers/api/v1/repo/mirror.go index 72ddc758dce..26e0be301c1 100644 --- a/routers/api/v1/repo/mirror.go +++ b/routers/api/v1/repo/mirror.go @@ -227,11 +227,18 @@ func GetPushMirrorByName(ctx *context.APIContext) { mirrorName := ctx.Params(":name") // Get push mirror of a specific repo by remoteName - pushMirror, err := repo_model.GetPushMirror(ctx, repo_model.PushMirrorOptions{RepoID: ctx.Repo.Repository.ID, RemoteName: mirrorName}) + pushMirror, exist, err := db.Get[repo_model.PushMirror](ctx, repo_model.PushMirrorOptions{ + RepoID: ctx.Repo.Repository.ID, + RemoteName: mirrorName, + }.ToConds()) if err != nil { - ctx.Error(http.StatusNotFound, "GetPushMirrors", err) + ctx.Error(http.StatusInternalServerError, "GetPushMirrors", err) + return + } else if !exist { + ctx.Error(http.StatusNotFound, "GetPushMirrors", nil) return } + m, err := convert.ToPushMirror(ctx, pushMirror) if err != nil { ctx.ServerError("GetPushMirrorByRemoteName", err) @@ -368,7 +375,7 @@ func CreatePushMirror(ctx *context.APIContext, mirrorOption *api.CreatePushMirro RemoteAddress: remoteAddress, } - if err = repo_model.InsertPushMirror(ctx, pushMirror); err != nil { + if err = db.Insert(ctx, pushMirror); err != nil { ctx.ServerError("InsertPushMirror", err) return } diff --git a/routers/web/admin/notice.go b/routers/web/admin/notice.go index 99039a2a9f9..e1cb578d052 100644 --- a/routers/web/admin/notice.go +++ b/routers/web/admin/notice.go @@ -8,6 +8,7 @@ import ( "net/http" "strconv" + "code.gitea.io/gitea/models/db" system_model "code.gitea.io/gitea/models/system" "code.gitea.io/gitea/modules/base" "code.gitea.io/gitea/modules/context" @@ -55,7 +56,7 @@ func DeleteNotices(ctx *context.Context) { } } - if err := system_model.DeleteNoticesByIDs(ctx, ids); err != nil { + if err := db.DeleteByIDs[system_model.Notice](ctx, ids...); err != nil { ctx.Flash.Error("DeleteNoticesByIDs: " + err.Error()) ctx.Status(http.StatusInternalServerError) } else { diff --git a/routers/web/repo/setting/setting.go b/routers/web/repo/setting/setting.go index 0864b1c911a..289cf5c9aea 100644 --- a/routers/web/repo/setting/setting.go +++ b/routers/web/repo/setting/setting.go @@ -418,7 +418,7 @@ func SettingsPost(ctx *context.Context) { Interval: interval, RemoteAddress: remoteAddress, } - if err := repo_model.InsertPushMirror(ctx, m); err != nil { + if err := db.Insert(ctx, m); err != nil { ctx.ServerError("InsertPushMirror", err) return } diff --git a/services/asymkey/ssh_key.go b/services/asymkey/ssh_key.go index 1c3bf09b083..83d7edafa3b 100644 --- a/services/asymkey/ssh_key.go +++ b/services/asymkey/ssh_key.go @@ -33,7 +33,7 @@ func DeletePublicKey(ctx context.Context, doer *user_model.User, id int64) (err } defer committer.Close() - if err = asymkey_model.DeletePublicKeys(dbCtx, id); err != nil { + if _, err = db.DeleteByID[asymkey_model.PublicKey](dbCtx, id); err != nil { return err } diff --git a/services/mirror/mirror_push.go b/services/mirror/mirror_push.go index 6eaca71495e..b117e79faca 100644 --- a/services/mirror/mirror_push.go +++ b/services/mirror/mirror_push.go @@ -12,6 +12,7 @@ import ( "strings" "time" + "code.gitea.io/gitea/models/db" repo_model "code.gitea.io/gitea/models/repo" "code.gitea.io/gitea/modules/git" "code.gitea.io/gitea/modules/lfs" @@ -93,8 +94,9 @@ func SyncPushMirror(ctx context.Context, mirrorID int64) bool { log.Error("PANIC whilst syncPushMirror[%d] Panic: %v\nStacktrace: %s", mirrorID, err, log.Stack(2)) }() - m, err := repo_model.GetPushMirror(ctx, repo_model.PushMirrorOptions{ID: mirrorID}) - if err != nil { + // TODO: Handle "!exist" better + m, exist, err := db.GetByID[repo_model.PushMirror](ctx, mirrorID) + if err != nil || !exist { log.Error("GetPushMirrorByID [%d]: %v", mirrorID, err) return false } diff --git a/services/release/release.go b/services/release/release.go index fc91171fba6..ddfb11fa476 100644 --- a/services/release/release.go +++ b/services/release/release.go @@ -339,7 +339,7 @@ func DeleteReleaseByID(ctx context.Context, repo *repo_model.Repository, rel *re }, repository.NewPushCommits()) notify_service.DeleteRef(ctx, doer, repo, refName) - if err := repo_model.DeleteReleaseByID(ctx, rel.ID); err != nil { + if _, err := db.DeleteByID[repo_model.Release](ctx, rel.ID); err != nil { return fmt.Errorf("DeleteReleaseByID: %w", err) } } else { diff --git a/services/repository/archiver/archiver.go b/services/repository/archiver/archiver.go index f700e3af5de..b73d0eed480 100644 --- a/services/repository/archiver/archiver.go +++ b/services/repository/archiver/archiver.go @@ -177,7 +177,7 @@ func doArchive(ctx context.Context, r *ArchiveRequest) (*repo_model.RepoArchiver CommitID: r.CommitID, Status: repo_model.ArchiverGenerating, } - if err := repo_model.AddRepoArchiver(ctx, archiver); err != nil { + if err := db.Insert(ctx, archiver); err != nil { return nil, err } } @@ -309,7 +309,7 @@ func StartArchive(request *ArchiveRequest) error { } func deleteOldRepoArchiver(ctx context.Context, archiver *repo_model.RepoArchiver) error { - if err := repo_model.DeleteRepoArchiver(ctx, archiver); err != nil { + if _, err := db.DeleteByID[repo_model.RepoArchiver](ctx, archiver.ID); err != nil { return err } p := archiver.RelativePath() diff --git a/services/secrets/secrets.go b/services/secrets/secrets.go index 97e15ba6c7f..031c474dd72 100644 --- a/services/secrets/secrets.go +++ b/services/secrets/secrets.go @@ -76,7 +76,7 @@ func DeleteSecretByName(ctx context.Context, ownerID, repoID int64, name string) } func deleteSecret(ctx context.Context, s *secret_model.Secret) error { - if _, err := db.DeleteByID(ctx, s.ID, s); err != nil { + if _, err := db.DeleteByID[secret_model.Secret](ctx, s.ID); err != nil { return err } return nil diff --git a/services/user/delete.go b/services/user/delete.go index c4617e064e7..748f5c2d1e9 100644 --- a/services/user/delete.go +++ b/services/user/delete.go @@ -185,7 +185,7 @@ func deleteUser(ctx context.Context, u *user_model.User, purge bool) (err error) } // ***** END: ExternalLoginUser ***** - if _, err = db.DeleteByID(ctx, u.ID, new(user_model.User)); err != nil { + if _, err = db.DeleteByID[user_model.User](ctx, u.ID); err != nil { return fmt.Errorf("delete: %w", err) } diff --git a/tests/integration/repo_tag_test.go b/tests/integration/repo_tag_test.go index 8667a6d6e9f..e588097994f 100644 --- a/tests/integration/repo_tag_test.go +++ b/tests/integration/repo_tag_test.go @@ -81,7 +81,7 @@ func TestCreateNewTagProtected(t *testing.T) { assert.NoError(t, err) for _, release := range releases { - err = repo_model.DeleteReleaseByID(db.DefaultContext, release.ID) + _, err = db.DeleteByID[repo_model.Release](db.DefaultContext, release.ID) assert.NoError(t, err) } From ff7383e83a4fdf9a86879b698752fe1aa5c6d00f Mon Sep 17 00:00:00 2001 From: GiteaBot Date: Tue, 26 Dec 2023 00:24:05 +0000 Subject: [PATCH 028/189] [skip ci] Updated translations via Crowdin --- options/locale/locale_cs-CZ.ini | 2 -- options/locale/locale_de-DE.ini | 2 -- options/locale/locale_el-GR.ini | 2 -- options/locale/locale_es-ES.ini | 2 -- options/locale/locale_fa-IR.ini | 1 - options/locale/locale_fi-FI.ini | 1 - options/locale/locale_fr-FR.ini | 2 -- options/locale/locale_hu-HU.ini | 1 - options/locale/locale_id-ID.ini | 1 - options/locale/locale_it-IT.ini | 1 - options/locale/locale_ja-JP.ini | 2 -- options/locale/locale_ko-KR.ini | 1 - options/locale/locale_lv-LV.ini | 2 -- options/locale/locale_nl-NL.ini | 1 - options/locale/locale_pl-PL.ini | 1 - options/locale/locale_pt-BR.ini | 2 -- options/locale/locale_pt-PT.ini | 17 ++++++++--------- options/locale/locale_ru-RU.ini | 2 -- options/locale/locale_si-LK.ini | 1 - options/locale/locale_sv-SE.ini | 1 - options/locale/locale_tr-TR.ini | 2 -- options/locale/locale_uk-UA.ini | 1 - options/locale/locale_zh-CN.ini | 2 -- options/locale/locale_zh-HK.ini | 1 - options/locale/locale_zh-TW.ini | 2 -- 25 files changed, 8 insertions(+), 45 deletions(-) diff --git a/options/locale/locale_cs-CZ.ini b/options/locale/locale_cs-CZ.ini index 5a48624e07f..e9428ebcd4c 100644 --- a/options/locale/locale_cs-CZ.ini +++ b/options/locale/locale_cs-CZ.ini @@ -2767,7 +2767,6 @@ config.enable_openid_signin=Povolit přihlášení pomocí OpenID config.show_registration_button=Ukázat tlačítko registrace config.require_sign_in_view=Vyžadovat přihlášení k zobrazení stránek config.mail_notify=Povolit e-mailová oznámení -config.disable_key_size_check=Vypnout kontrolu minimální velikosti klíčů config.enable_captcha=Povolit CAPTCHA config.active_code_lives=Doba života aktivního kódu config.reset_password_code_lives=Čas vypršení platnosti kódu pro obnovení účtu @@ -3181,7 +3180,6 @@ runners.version=Verze runs.all_workflows=Všechny pracovní postupy runs.commit=Commit -runs.no_matching_runner_helper=Žádný odpovídající runner: %s runs.status=Status diff --git a/options/locale/locale_de-DE.ini b/options/locale/locale_de-DE.ini index c15e1de71a6..c24d25b1ac6 100644 --- a/options/locale/locale_de-DE.ini +++ b/options/locale/locale_de-DE.ini @@ -3063,7 +3063,6 @@ config.enable_openid_signin=OpenID-Anmeldung aktivieren config.show_registration_button=Schaltfläche zum Registrieren anzeigen config.require_sign_in_view=Seiten nur für angemeldete Benutzer zugänglich config.mail_notify=E-Mail-Benachrichtigungen aktivieren -config.disable_key_size_check=Prüfung der Mindestschlüssellänge deaktiveren config.enable_captcha=CAPTCHA aktivieren config.active_code_lives=Aktivierungscode-Lebensdauer config.reset_password_code_lives=Kontowiederherstellungs-Code Ablaufzeit @@ -3509,7 +3508,6 @@ runs.commit=Commit runs.scheduled=Geplant runs.pushed_by=gepusht von runs.invalid_workflow_helper=Die Workflow-Konfigurationsdatei ist ungültig. Bitte überprüfe Deine Konfigurationsdatei: %s -runs.no_matching_runner_helper=Kein passender Runner: %s runs.actor=Initiator runs.status=Status runs.actors_no_select=Alle Initiatoren diff --git a/options/locale/locale_el-GR.ini b/options/locale/locale_el-GR.ini index b540fe2e5dc..2424ee3fb62 100644 --- a/options/locale/locale_el-GR.ini +++ b/options/locale/locale_el-GR.ini @@ -2889,7 +2889,6 @@ config.enable_openid_signin=Ενεργοποίηση Σύνδεσης μέσω O config.show_registration_button=Εμφάνιση Κουμπιού Εγγραφής config.require_sign_in_view=Απαιτείται Είσοδος για Προβολή Σελίδων config.mail_notify=Ενεργοποίηση Ειδοποιήσεων Email -config.disable_key_size_check=Απενεργοποίηση Ελέγχου Ελάχιστου Μεγέθους Κλειδιού config.enable_captcha=Ενεργοποίηση CAPTCHA config.active_code_lives=Ζωή Ενεργού Κωδικού config.reset_password_code_lives=Λήξη Χρόνου Κωδικού Ανάκτησης του Λογαριασμού @@ -3321,7 +3320,6 @@ runners.reset_registration_token_success=Επιτυχής επανέκδοση runs.all_workflows=Όλες Οι Ροές Εργασίας runs.commit=Υποβολή runs.invalid_workflow_helper=Το αρχείο ροής εργασίας δεν είναι έγκυρο. Ελέγξτε το αρχείο σας: %s -runs.no_matching_runner_helper=Δε ταιριάζει εκτελεστής: %s runs.status=Κατάσταση diff --git a/options/locale/locale_es-ES.ini b/options/locale/locale_es-ES.ini index 2aab7fc71ba..1a82ce5b764 100644 --- a/options/locale/locale_es-ES.ini +++ b/options/locale/locale_es-ES.ini @@ -3063,7 +3063,6 @@ config.enable_openid_signin=Habilitar el inicio de sesión con OpenID config.show_registration_button=Mostrar Botón de Registro config.require_sign_in_view=Requerir inicio de sesión obligatorio para ver páginas config.mail_notify=Habilitar las notificaciones por correo electrónico -config.disable_key_size_check=Deshabilitar la comprobación de Tamaño Mínimo de Clave config.enable_captcha=Activar CAPTCHA config.active_code_lives=Habilitar Vida del Código config.reset_password_code_lives=Caducidad del código de recuperación de cuenta @@ -3509,7 +3508,6 @@ runs.commit=Commit runs.scheduled=Programado runs.pushed_by=push enviado por runs.invalid_workflow_helper=El archivo de configuración del trabajo no es válido. Revisa tu archivo de configuración: %s -runs.no_matching_runner_helper=No hay nodo coincidente: %s runs.actor=Actor runs.status=Estado runs.actors_no_select=Todos los actores diff --git a/options/locale/locale_fa-IR.ini b/options/locale/locale_fa-IR.ini index 9a3d6a98cfb..c9099299a02 100644 --- a/options/locale/locale_fa-IR.ini +++ b/options/locale/locale_fa-IR.ini @@ -2388,7 +2388,6 @@ config.enable_openid_signin=فعال کردن ورود با OpenID config.show_registration_button=نشان دادن دکمه ثبت نام config.require_sign_in_view=فعال‌سازی نیازمند به ورود در هنگام مشاهده صفحات config.mail_notify=فعال‌سازی اعلان‌های ایمیل (رایانامه) -config.disable_key_size_check=غیر فعال کردن بررسی حداقل اندازه کلید config.enable_captcha=فعال کردن کپچا config.active_code_lives=عمر کد فعال سازی config.reset_password_code_lives=مدت انقضای کد بازیابی حساب کاربری diff --git a/options/locale/locale_fi-FI.ini b/options/locale/locale_fi-FI.ini index b6cf0d842ad..b6abb49a35e 100644 --- a/options/locale/locale_fi-FI.ini +++ b/options/locale/locale_fi-FI.ini @@ -1586,7 +1586,6 @@ config.db_path=Polku config.service_config=Palvelu asetukset config.show_registration_button=Näytä rekisteröidy painike -config.disable_key_size_check=Poista käytöstä avaimen vähimmäiskoko tarkistus config.enable_captcha=Ota CAPTCHA käyttöön config.active_code_lives=Aktiivinen koodi elämät ennen vanhenemista config.default_keep_email_private=Piilota sähköpostiosoitteet oletuksena diff --git a/options/locale/locale_fr-FR.ini b/options/locale/locale_fr-FR.ini index c09dad7e5f8..2ca3d3ccd2a 100644 --- a/options/locale/locale_fr-FR.ini +++ b/options/locale/locale_fr-FR.ini @@ -3069,7 +3069,6 @@ config.enable_openid_signin=Activer la connexion avec OpenID config.show_registration_button=Afficher le bouton d'enregistrement config.require_sign_in_view=Exiger la connexion pour afficher les pages config.mail_notify=Activer les notifications par e-mail -config.disable_key_size_check=Désactiver la vérification de la taille de clé minimale config.enable_captcha=Activer le CAPTCHA config.active_code_lives=Limites de Code Actif config.reset_password_code_lives=Durée d'expiration du code de récupération de compte @@ -3515,7 +3514,6 @@ runs.commit=Révision runs.scheduled=Planifié runs.pushed_by=soumis par runs.invalid_workflow_helper=La configuration du flux de travail est invalide. Veuillez vérifier votre fichier %s. -runs.no_matching_runner_helper=Aucun exécuteur correspondant : %s runs.actor=Acteur runs.status=Statut runs.actors_no_select=Tous les acteurs diff --git a/options/locale/locale_hu-HU.ini b/options/locale/locale_hu-HU.ini index 4e0d1e0471b..aee4b44edf9 100644 --- a/options/locale/locale_hu-HU.ini +++ b/options/locale/locale_hu-HU.ini @@ -1476,7 +1476,6 @@ config.enable_openid_signin=OpenID bejelentkezés engedélyezése config.show_registration_button=Regisztráció gomb megjelenítése config.require_sign_in_view=Bejelentkezés megkövetelése az oldalak megtekintéséhez config.mail_notify=E-mail értesítés engedélyezése -config.disable_key_size_check=Minimális kulcsméret ellenőrzés letiltása config.enable_captcha=CAPTCHA engedélyezése config.active_code_lives=Aktív kód élettartam config.reset_password_code_lives=Fiók visszaállítási kód lejárati idő diff --git a/options/locale/locale_id-ID.ini b/options/locale/locale_id-ID.ini index 679b31269e1..4dd7c299dfa 100644 --- a/options/locale/locale_id-ID.ini +++ b/options/locale/locale_id-ID.ini @@ -1167,7 +1167,6 @@ config.enable_openid_signin=Aktifkan Login OpenID config.show_registration_button=Tampilkan tombol mendaftar config.require_sign_in_view=Harus Login Untuk Melihat Halaman config.mail_notify=Aktifkan Notifikasi Email -config.disable_key_size_check=Menonaktifkan memeriksa ukuran kunci minimum config.enable_captcha=Aktifkan CAPTCHA config.active_code_lives=Kode aktif hidup diff --git a/options/locale/locale_it-IT.ini b/options/locale/locale_it-IT.ini index 13edd4af03f..a30232dd102 100644 --- a/options/locale/locale_it-IT.ini +++ b/options/locale/locale_it-IT.ini @@ -2582,7 +2582,6 @@ config.enable_openid_signin=Attiva l'accesso tramite OpenID config.show_registration_button=Mostra Pulsane Registrazione config.require_sign_in_view=Richiedi l'accesso per visualizzare le pagine config.mail_notify=Attila le notifiche Email -config.disable_key_size_check=Disabilita controllo sulle dimensioni minime della chiave config.enable_captcha=Attiva CAPTCHA config.active_code_lives=Attiva Vita del Codice config.reset_password_code_lives=Recupera il codice di scadenza del tempo del tuo account diff --git a/options/locale/locale_ja-JP.ini b/options/locale/locale_ja-JP.ini index 871a9d6809e..e5fa9e59843 100644 --- a/options/locale/locale_ja-JP.ini +++ b/options/locale/locale_ja-JP.ini @@ -3080,7 +3080,6 @@ config.enable_openid_signin=OpenIDを使ったサインイン有効 config.show_registration_button=登録ボタンを表示 config.require_sign_in_view=ページ閲覧にサインインが必要 config.mail_notify=メール通知有効 -config.disable_key_size_check=最小キー長のチェックが無効 config.enable_captcha=CAPTCHA有効 config.active_code_lives=アカウント確認リンクの有効時間 config.reset_password_code_lives=アカウント回復リンクの有効時間 @@ -3526,7 +3525,6 @@ runs.commit=コミット runs.scheduled=スケジュール済み runs.pushed_by=pushed by runs.invalid_workflow_helper=ワークフロー設定ファイルは無効です。あなたの設定ファイルを確認してください: %s -runs.no_matching_runner_helper=一致するランナーがありません: %s runs.actor=アクター runs.status=ステータス runs.actors_no_select=すべてのアクター diff --git a/options/locale/locale_ko-KR.ini b/options/locale/locale_ko-KR.ini index 54e8e79aef8..1c79ee6bc7c 100644 --- a/options/locale/locale_ko-KR.ini +++ b/options/locale/locale_ko-KR.ini @@ -1431,7 +1431,6 @@ config.enable_openid_signin=OpenID 로그인 활성화 config.show_registration_button=등록 버튼을 표시 config.require_sign_in_view=페이지를 보려면 로그인 필수 config.mail_notify=이메일 알림 활성화 -config.disable_key_size_check=최소 키 크기 검사를 비활성화 config.enable_captcha=CAPTCHA 활성화 config.active_code_lives=코드 만료 기한 config.default_keep_email_private=기본적으로 이메일 주소를 숨김 diff --git a/options/locale/locale_lv-LV.ini b/options/locale/locale_lv-LV.ini index 9f84e787358..e275b02ba0a 100644 --- a/options/locale/locale_lv-LV.ini +++ b/options/locale/locale_lv-LV.ini @@ -2898,7 +2898,6 @@ config.enable_openid_signin=Iespējot pieteikšanos ar OpenID config.show_registration_button=Rādīt reģistrēšanās pogu config.require_sign_in_view=Pieprasīt pieteikšanos, lai aplūkotu lapas config.mail_notify=Iespējot e-pasta paziņojumus -config.disable_key_size_check=Atspējot atslēgas minimālā garuma pārbaudi config.enable_captcha=Iespējot drošības kodu config.active_code_lives=Aktīvā koda ilgums config.reset_password_code_lives=Konta atjaunošanas koda beigšanās laiks @@ -3330,7 +3329,6 @@ runners.reset_registration_token_success=Izpildītāja reģistrācijas pilnvara runs.all_workflows=Visas darbaplūsmas runs.commit=Revīzija runs.invalid_workflow_helper=Darbaplūsmas konfigurācijas fails ir kļūdains. Pārbaudiet konfiugrācijas failu: %s -runs.no_matching_runner_helper=Nav atbilstošu izpildītāju: %s runs.status=Statuss diff --git a/options/locale/locale_nl-NL.ini b/options/locale/locale_nl-NL.ini index ba4c28dd3bf..43265c9c319 100644 --- a/options/locale/locale_nl-NL.ini +++ b/options/locale/locale_nl-NL.ini @@ -2424,7 +2424,6 @@ config.enable_openid_signin=OpenID-inloggen inschakelen config.show_registration_button=Registeren knop weergeven config.require_sign_in_view=Vereis inloggen om pagina's te kunnen bekijken config.mail_notify=Activeer e-mailnotificaties -config.disable_key_size_check=Controle op key-lengte uitschakelen config.enable_captcha=CAPTCHA inschakelen config.active_code_lives=Actieve Code leven config.reset_password_code_lives=Herstel accountcode vervaltijd diff --git a/options/locale/locale_pl-PL.ini b/options/locale/locale_pl-PL.ini index 52c6d716cf3..d713110a722 100644 --- a/options/locale/locale_pl-PL.ini +++ b/options/locale/locale_pl-PL.ini @@ -2313,7 +2313,6 @@ config.enable_openid_signin=Włącz logowanie za pomocą OpenID config.show_registration_button=Pokazuj przycisk rejestracji config.require_sign_in_view=Wymagaj zalogowania w celu wyświetlania stron config.mail_notify=Włącz powiadomienia e-mail -config.disable_key_size_check=Wyłącz sprawdzanie minimalnego rozmiaru klucza config.enable_captcha=Włącz CAPTCHA config.active_code_lives=Ważność kodów aktywacyjnych config.reset_password_code_lives=Czas wygaśnięcia kodu przywracania konta diff --git a/options/locale/locale_pt-BR.ini b/options/locale/locale_pt-BR.ini index f77374e753f..cf5fd0055c8 100644 --- a/options/locale/locale_pt-BR.ini +++ b/options/locale/locale_pt-BR.ini @@ -2977,7 +2977,6 @@ config.enable_openid_signin=Habilitar acesso via OpenID config.show_registration_button=Mostrar botão de cadastro config.require_sign_in_view=Exigir acesso do usuário para a visualização de páginas config.mail_notify=Habilitar notificações de e-mail -config.disable_key_size_check=Desabilitar verificação de tamanho mínimo da chave config.enable_captcha=Habilitar o CAPTCHA config.active_code_lives=Ativar Code Lives config.reset_password_code_lives=Tempo de expiração do código de recuperação de conta @@ -3413,7 +3412,6 @@ runs.all_workflows=Todos os Workflows runs.commit=Commit runs.pushed_by=push feito por runs.invalid_workflow_helper=O arquivo de configuração do workflow é inválido. Por favor, verifique seu arquivo de configuração: %s -runs.no_matching_runner_helper=Nenhum runner correspondente: %s runs.status=Status diff --git a/options/locale/locale_pt-PT.ini b/options/locale/locale_pt-PT.ini index 54f83c57359..c7927687ab6 100644 --- a/options/locale/locale_pt-PT.ini +++ b/options/locale/locale_pt-PT.ini @@ -1997,7 +1997,7 @@ settings.mirror_settings.docs.disabled_push_mirror.pull_mirror_warning=Neste mom settings.mirror_settings.docs.disabled_push_mirror.info=As réplicas foram desabilitadas pelo administrador deste sítio. settings.mirror_settings.docs.no_new_mirrors=O seu repositório está a replicar modificações para, ou a partir, de outro repositório. Tenha em mente que não pode criar novas réplicas neste momento. settings.mirror_settings.docs.can_still_use=Embora não possa modificar réplicas existentes ou criar novas, ainda pode usar a sua réplica existente. -settings.mirror_settings.docs.pull_mirror_instructions=Para configurar uma réplica de outro repositório, consulte: +settings.mirror_settings.docs.pull_mirror_instructions=Para configurar uma réplica de outro repositório, consulte settings.mirror_settings.docs.more_information_if_disabled=Pode aprender mais sobre réplicas de envios e de puxadas aqui: settings.mirror_settings.docs.doc_link_title=Como é que eu replico repositórios? settings.mirror_settings.docs.doc_link_pull_section=a parte "Puxar de um repositório remoto" da documentação. @@ -2054,7 +2054,7 @@ settings.pulls.default_allow_edits_from_maintainers=Permitir, por norma, que os settings.releases_desc=Habilitar lançamentos no repositório settings.packages_desc=Habilitar o registo de pacotes do repositório settings.projects_desc=Habilitar planeamentos no repositório -settings.actions_desc=Habilitar operações no repositório +settings.actions_desc=Habilitar operações no repositório (Gitea Actions) settings.admin_settings=Configurações do administrador settings.admin_enable_health_check=Habilitar verificações de integridade (git fsck) no repositório settings.admin_code_indexer=Indexador de código @@ -2117,7 +2117,7 @@ settings.delete_notices_2=- Esta operação eliminará permanentemente o reposit settings.delete_notices_fork_1=- Derivações deste repositório tornar-se-ão independentes, após a eliminação. settings.deletion_success=O repositório foi eliminado. settings.update_settings_success=As configurações do repositório foram modificadas. -settings.update_settings_no_unit=O repositório deverá, ao menos, permitir algum tipo de interacção. +settings.update_settings_no_unit=O repositório deve permitir pelo menos algum tipo de interoperabilidade. settings.confirm_delete=Eliminar repositório settings.add_collaborator=Adicionar colaborador settings.add_collaborator_success=O colaborador foi adicionado. @@ -2643,7 +2643,7 @@ teams.leave.detail=Sair de %s? teams.can_create_org_repo=Criar repositórios teams.can_create_org_repo_helper=Os membros podem criar novos repositórios na organização. O criador terá acesso de administrador ao novo repositório. teams.none_access=Sem acesso -teams.none_access_helper=Os membros não podem ver nem fazer qualquer outra operação nesta unidade. +teams.none_access_helper=Os membros não podem ver nem fazer qualquer outra operação nesta unidade. Não tem qualquer efeito nos repositórios públicos. teams.general_access=Acesso geral teams.general_access_helper=As permissões dos membros serão decididas pela tabela de permissões abaixo. teams.read_access=Ler @@ -2750,7 +2750,7 @@ dashboard.reinit_missing_repos=Reinicializar todos os repositórios Git em falta dashboard.sync_external_users=Sincronizar dados externos do utilizador dashboard.cleanup_hook_task_table=Limpar tabela hook_task dashboard.cleanup_packages=Limpar pacotes expirados -dashboard.cleanup_actions=Registos expirados e artefactos das operações de limpeza +dashboard.cleanup_actions=Limpar registos e artefactos expirados das operações dashboard.server_uptime=Tempo em funcionamento contínuo do servidor dashboard.current_goroutine=Goroutines em execução dashboard.current_memory_usage=Utilização de memória corrente @@ -3080,7 +3080,6 @@ config.enable_openid_signin=Habilitar início de sessão com OpenID config.show_registration_button=Mostrar botão de registo config.require_sign_in_view=Exigir sessão iniciada para visualizar páginas config.mail_notify=Habilitar notificações por email -config.disable_key_size_check=Desabilitar verificação de tamanho mínimo da chave config.enable_captcha=Habilitar o CAPTCHA config.active_code_lives=Duração do código que está em uso config.reset_password_code_lives=Prazo do código de recuperação da conta @@ -3460,7 +3459,7 @@ secrets=Segredos description=Os segredos serão transmitidos a certas operações e não poderão ser lidos de outra forma. none=Ainda não há segredos. creation=Adicionar segredo -creation.name_placeholder=apenas caracteres sem distinção de maiúsculas, alfanuméricos ou sublinhados, não podem começar com GITEA_ nem com GITHUB_ +creation.name_placeholder=Só sublinhados ou alfanuméricos sem distinguir maiúsculas, sem começar com GITEA_ nem GITHUB_ creation.value_placeholder=Insira um conteúdo qualquer. Espaços em branco no início ou no fim serão omitidos. creation.success=O segredo "%s" foi adicionado. creation.failed=Falhou ao adicionar o segredo. @@ -3494,7 +3493,7 @@ runners.name=Nome runners.owner_type=Tipo runners.description=Descrição runners.labels=Rótulos -runners.last_online=Última vez ligado +runners.last_online=Última vez que esteve ligado runners.runner_title=Executor runners.task_list=Tarefas recentes deste executor runners.task_list.no_tasks=Ainda não há tarefas. @@ -3526,7 +3525,7 @@ runs.commit=Cometimento runs.scheduled=Agendadas runs.pushed_by=enviado por runs.invalid_workflow_helper=O ficheiro de configuração da sequência de trabalho é inválido. Verifique o seu ficheiro de configuração: %s -runs.no_matching_runner_helper=Não há qualquer executor que corresponda: %s +runs.no_matching_online_runner_helper=Não existem executores ligados que tenham o rótulo %s runs.actor=Interveniente runs.status=Estado runs.actors_no_select=Todos os intervenientes diff --git a/options/locale/locale_ru-RU.ini b/options/locale/locale_ru-RU.ini index 417f70303eb..b30133128ad 100644 --- a/options/locale/locale_ru-RU.ini +++ b/options/locale/locale_ru-RU.ini @@ -2979,7 +2979,6 @@ config.enable_openid_signin=Включение входа через OpenID config.show_registration_button=Показать кнопку регистрации config.require_sign_in_view=Для просмотра необходима авторизация config.mail_notify=Почтовые уведомления -config.disable_key_size_check=Отключить проверку на минимальный размер ключа config.enable_captcha=Включить CAPTCHA config.active_code_lives=Время жизни кода для активации config.reset_password_code_lives=Время действия кода восстановления аккаунта @@ -3418,7 +3417,6 @@ runs.all_workflows=Все рабочие потоки runs.commit=коммит runs.pushed_by=отправлено runs.invalid_workflow_helper=Файл конфигурации рабочего потока некорректен. Пожалуйста, проверьте конфигурационный файл: %s -runs.no_matching_runner_helper=Нет подходящего раннера: %s runs.actor=Актор runs.status=Статус runs.actors_no_select=Все акторы diff --git a/options/locale/locale_si-LK.ini b/options/locale/locale_si-LK.ini index 5824c49974e..6d70bc385ad 100644 --- a/options/locale/locale_si-LK.ini +++ b/options/locale/locale_si-LK.ini @@ -2344,7 +2344,6 @@ config.enable_openid_signin=OpenID සංඥා සක්රීය කරන් config.show_registration_button=ලියාපදිංචි බොත්තම පෙන්වන්න config.require_sign_in_view=පිටු බැලීම සඳහා සිග්න්-දී අවශ්ය config.mail_notify=වි-තැපැල් දැනුම්දීම් සබල කරන්න -config.disable_key_size_check=අවම කී තරම පරීක්ෂා කරන්න අක්රීය config.enable_captcha=කැප්චා සක්රීය කරන්න config.active_code_lives=ක්රියාකාරී කේතය Lives config.reset_password_code_lives=ගිණුම් කේත කල් ඉකුත් වීමේ වේලාව නැවත ලබා ගන්න diff --git a/options/locale/locale_sv-SE.ini b/options/locale/locale_sv-SE.ini index e24f2f9df64..411a83ed75d 100644 --- a/options/locale/locale_sv-SE.ini +++ b/options/locale/locale_sv-SE.ini @@ -1874,7 +1874,6 @@ config.enable_openid_signin=Aktivera OpenID-inloggning config.show_registration_button=Visa registreringsknapp config.require_sign_in_view=Kräv inloggning för att visa sidor config.mail_notify=Aktivera Mejlnotifikationer -config.disable_key_size_check=Avaktivera kontroll av minsta tillåtna nyckelstorlek config.enable_captcha=Aktivera CAPTCHA config.active_code_lives=Aktivera livstid för koder config.default_keep_email_private=Dölj mejladresser som standard diff --git a/options/locale/locale_tr-TR.ini b/options/locale/locale_tr-TR.ini index ed4c3182033..dd7d1b066e8 100644 --- a/options/locale/locale_tr-TR.ini +++ b/options/locale/locale_tr-TR.ini @@ -3019,7 +3019,6 @@ config.enable_openid_signin=OpenID Oturum Açmayı Etkinleştiriniz config.show_registration_button=Kaydolma Düğmesini Göster config.require_sign_in_view=Sayfaları Görüntülemek için Giriş Yapmaya Zorla config.mail_notify=E-Posta Bildirimlerini Etkinleştir -config.disable_key_size_check=Minimum Anahtar Uzunluğu Kontrolünü Devre Dışı Bırak config.enable_captcha=CAPTCHA'yı Etkinleştir config.active_code_lives=Kod Yaşamlarını Aktifleştir config.reset_password_code_lives=Hesap Kodunun Sona Erme Zamanını Kurtar @@ -3461,7 +3460,6 @@ runs.all_workflows=Tüm İş Akışları runs.commit=İşle runs.pushed_by=iten runs.invalid_workflow_helper=İş akışı yapılandırma dosyası geçersiz. Lütfen yapılandırma dosyanızı denetleyin: %s -runs.no_matching_runner_helper=Eşleşen çalıştırıcı yok: %s runs.actor=Aktör runs.status=Durum runs.actors_no_select=Tüm aktörler diff --git a/options/locale/locale_uk-UA.ini b/options/locale/locale_uk-UA.ini index 0d787c772fb..4cd6c44571b 100644 --- a/options/locale/locale_uk-UA.ini +++ b/options/locale/locale_uk-UA.ini @@ -2397,7 +2397,6 @@ config.enable_openid_signin=Увімкнути реєстрацію за доп config.show_registration_button=`Показувати кнопку "Реєстрація"` config.require_sign_in_view=Вимагати авторизації для перегляду сторінок config.mail_notify=Увімкнути сповіщення електронною поштою -config.disable_key_size_check=Вимкнути перевірку мінімального розміру ключа config.enable_captcha=Увімкнути CAPTCHA config.active_code_lives=Час актуальності кода підтвердження config.reset_password_code_lives=Відновлення часу закінчення терміну дії коду облікового запису diff --git a/options/locale/locale_zh-CN.ini b/options/locale/locale_zh-CN.ini index b56e797e738..77414f15706 100644 --- a/options/locale/locale_zh-CN.ini +++ b/options/locale/locale_zh-CN.ini @@ -3063,7 +3063,6 @@ config.enable_openid_signin=启用 OpenID 登录 config.show_registration_button=显示注册按钮 config.require_sign_in_view=启用登录访问限制 config.mail_notify=启用邮件通知 -config.disable_key_size_check=禁用密钥最小长度检查 config.enable_captcha=启用登录验证码 config.active_code_lives=激活用户链接有效期 config.reset_password_code_lives=恢复账户验证码过期时间 @@ -3509,7 +3508,6 @@ runs.commit=提交 runs.scheduled=已计划的 runs.pushed_by=推送者 runs.invalid_workflow_helper=工作流配置文件无效。请检查您的配置文件: %s -runs.no_matching_runner_helper=没有匹配的runner:%s runs.actor=操作者 runs.status=状态 runs.actors_no_select=所有操作者 diff --git a/options/locale/locale_zh-HK.ini b/options/locale/locale_zh-HK.ini index 9b065d7ae51..d4074026fd8 100644 --- a/options/locale/locale_zh-HK.ini +++ b/options/locale/locale_zh-HK.ini @@ -839,7 +839,6 @@ config.db_path=資料庫路徑 config.service_config=服務設定 config.show_registration_button=顯示註冊按鈕 -config.disable_key_size_check=禁用金鑰最小長度檢查 config.active_code_lives=啟用用戶連結有效期 config.webhook_config=Webhook 設定 diff --git a/options/locale/locale_zh-TW.ini b/options/locale/locale_zh-TW.ini index 99d888c4501..ea79c45674a 100644 --- a/options/locale/locale_zh-TW.ini +++ b/options/locale/locale_zh-TW.ini @@ -2808,7 +2808,6 @@ config.enable_openid_signin=啟用 OpenID 登入 config.show_registration_button=顯示註冊按鈕 config.require_sign_in_view=需要登入才能瀏覽頁面 config.mail_notify=啟用郵件通知 -config.disable_key_size_check=停用金鑰最小長度檢查 config.enable_captcha=啟用驗證碼 config.active_code_lives=啟用用戶連結有效期 config.reset_password_code_lives=帳戶救援碼有效時間 @@ -3225,7 +3224,6 @@ runners.reset_registration_token_success=成功重設了 Runner 註冊 Token runs.all_workflows=所有工作流程 runs.commit=提交 runs.invalid_workflow_helper=工作流程設定檔無效。請檢查您的設定檔: %s -runs.no_matching_runner_helper=找不到符合的 Runner: %s runs.status=狀態 runs.no_runs=工作流程沒有執行過。 From 0e9c9883738c71d192a6b79ec3d3f3f982925ed5 Mon Sep 17 00:00:00 2001 From: Volodymyr Stelmashchuk Date: Tue, 26 Dec 2023 18:36:11 +0200 Subject: [PATCH 029/189] Update repo-mirror.en-us.md (#28612) Add small changes to the doc. The workflow scope require for push code to github mirror in case the project use the github action compatibility ui. --- docs/content/usage/repo-mirror.en-us.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/content/usage/repo-mirror.en-us.md b/docs/content/usage/repo-mirror.en-us.md index 4a6571031b3..8804a8885a1 100644 --- a/docs/content/usage/repo-mirror.en-us.md +++ b/docs/content/usage/repo-mirror.en-us.md @@ -58,7 +58,7 @@ The repository now gets mirrored periodically to the remote repository. You can To set up a mirror from Gitea to GitHub, you need to follow these steps: -1. Create a [GitHub personal access token](https://docs.github.com/en/github/authenticating-to-github/creating-a-personal-access-token) with the *public_repo* box checked. +1. Create a [GitHub personal access token](https://docs.github.com/en/github/authenticating-to-github/creating-a-personal-access-token) with the *public_repo* box checked. Also check the **workflow** checkbox in case your repo using act for continuous integration. 2. Create a repository with that name on GitHub. Unlike Gitea, GitHub does not support creating repositories by pushing to the remote. You can also use an existing remote repo if it has the same commit history as your Gitea repo. 3. In the settings of your Gitea repo, fill in the **Git Remote Repository URL**: `https://github.com//.git`. 4. Fill in the **Authorization** fields with your GitHub username and the personal access token as **Password**. From d68b9237bf91aecd99132c8a98f815d40a1b8642 Mon Sep 17 00:00:00 2001 From: wxiaoguang Date: Wed, 27 Dec 2023 01:57:25 +0800 Subject: [PATCH 030/189] Use known issue IID to generate new PR index number when migrating from GitLab (#28616) Fix #13884 --- services/migrations/gitlab.go | 39 +++++++++++++++++++++--------- services/migrations/gitlab_test.go | 17 +++++++++++++ 2 files changed, 45 insertions(+), 11 deletions(-) diff --git a/services/migrations/gitlab.go b/services/migrations/gitlab.go index 22bc4cf8f39..3db10465fcb 100644 --- a/services/migrations/gitlab.go +++ b/services/migrations/gitlab.go @@ -55,19 +55,36 @@ func (f *GitlabDownloaderFactory) GitServiceType() structs.GitServiceType { return structs.GitlabService } +type gitlabIIDResolver struct { + maxIssueIID int64 + frozen bool +} + +func (r *gitlabIIDResolver) recordIssueIID(issueIID int) { + if r.frozen { + panic("cannot record issue IID after pull request IID generation has started") + } + r.maxIssueIID = max(r.maxIssueIID, int64(issueIID)) +} + +func (r *gitlabIIDResolver) generatePullRequestNumber(mrIID int) int64 { + r.frozen = true + return r.maxIssueIID + int64(mrIID) +} + // GitlabDownloader implements a Downloader interface to get repository information // from gitlab via go-gitlab // - issueCount is incremented in GetIssues() to ensure PR and Issue numbers do not overlap, // because Gitlab has individual Issue and Pull Request numbers. type GitlabDownloader struct { base.NullDownloader - ctx context.Context - client *gitlab.Client - baseURL string - repoID int - repoName string - issueCount int64 - maxPerPage int + ctx context.Context + client *gitlab.Client + baseURL string + repoID int + repoName string + iidResolver gitlabIIDResolver + maxPerPage int } // NewGitlabDownloader creates a gitlab Downloader via gitlab API @@ -450,8 +467,8 @@ func (g *GitlabDownloader) GetIssues(page, perPage int) ([]*base.Issue, bool, er Context: gitlabIssueContext{IsMergeRequest: false}, }) - // increment issueCount, to be used in GetPullRequests() - g.issueCount++ + // record the issue IID, to be used in GetPullRequests() + g.iidResolver.recordIssueIID(issue.IID) } return allIssues, len(issues) < perPage, nil @@ -607,8 +624,8 @@ func (g *GitlabDownloader) GetPullRequests(page, perPage int) ([]*base.PullReque awardPage++ } - // Add the PR ID to the Issue Count because PR and Issues share ID space in Gitea - newPRNumber := g.issueCount + int64(pr.IID) + // Generate new PR Numbers by the known Issue Numbers, because they share the same number space in Gitea, but they are independent in Gitlab + newPRNumber := g.iidResolver.generatePullRequestNumber(pr.IID) allPRs = append(allPRs, &base.PullRequest{ Title: pr.Title, diff --git a/services/migrations/gitlab_test.go b/services/migrations/gitlab_test.go index 731486eff21..1e0aa2b025b 100644 --- a/services/migrations/gitlab_test.go +++ b/services/migrations/gitlab_test.go @@ -516,3 +516,20 @@ func TestAwardsToReactions(t *testing.T) { }, }, reactions) } + +func TestGitlabIIDResolver(t *testing.T) { + r := gitlabIIDResolver{} + r.recordIssueIID(1) + r.recordIssueIID(2) + r.recordIssueIID(3) + r.recordIssueIID(2) + assert.EqualValues(t, 4, r.generatePullRequestNumber(1)) + assert.EqualValues(t, 13, r.generatePullRequestNumber(10)) + + assert.Panics(t, func() { + r := gitlabIIDResolver{} + r.recordIssueIID(1) + assert.EqualValues(t, 2, r.generatePullRequestNumber(1)) + r.recordIssueIID(3) // the generation procedure has been started, it shouldn't accept any new issue IID, so it panics + }) +} From a1dfffd723c434966152ee521c99e966a3aee065 Mon Sep 17 00:00:00 2001 From: GiteaBot Date: Wed, 27 Dec 2023 00:23:45 +0000 Subject: [PATCH 031/189] [skip ci] Updated translations via Crowdin --- options/locale/locale_fr-FR.ini | 1 + options/locale/locale_ru-RU.ini | 49 ++++++++++++++++++++++++++++++++- 2 files changed, 49 insertions(+), 1 deletion(-) diff --git a/options/locale/locale_fr-FR.ini b/options/locale/locale_fr-FR.ini index 2ca3d3ccd2a..d9fcf14b5ee 100644 --- a/options/locale/locale_fr-FR.ini +++ b/options/locale/locale_fr-FR.ini @@ -3514,6 +3514,7 @@ runs.commit=Révision runs.scheduled=Planifié runs.pushed_by=soumis par runs.invalid_workflow_helper=La configuration du flux de travail est invalide. Veuillez vérifier votre fichier %s. +runs.no_matching_online_runner_helper=Aucun exécuteur en ligne correspondant au libellé %s runs.actor=Acteur runs.status=Statut runs.actors_no_select=Tous les acteurs diff --git a/options/locale/locale_ru-RU.ini b/options/locale/locale_ru-RU.ini index b30133128ad..0a466854d09 100644 --- a/options/locale/locale_ru-RU.ini +++ b/options/locale/locale_ru-RU.ini @@ -359,6 +359,7 @@ disable_register_prompt=Извините, возможность регистр disable_register_mail=Подтверждение регистрации по электронной почте отключено. manual_activation_only=Обратитесь к администратору сайта для завершения активации. remember_me=Запомнить это устройство +remember_me.compromised=Токен входа более не действителен, что может указывать на компрометацию учётной записи. Пожалуйста, проверьте свою учётную запись на необычные действия. forgot_password_title=Восстановить пароль forgot_password=Забыли пароль? sign_up_now=Нужен аккаунт? Зарегистрируйтесь. @@ -704,6 +705,7 @@ requires_activation=Требуется активация primary_email=Сделать основным activate_email=Отправить активацию activations_pending=Ожидает активации +can_not_add_email_activations_pending=Ожидается активация. Если хотите добавить новый почтовый ящик, попробуйте еще раз через несколько минут. delete_email=Удалить email_deletion=Удалить адрес электронной почты email_deletion_desc=Адрес электронной почты и вся связанная с ним информация будет удалена из вашего аккаунта. Коммиты, сделанные от имени этого адреса электронной почты, не будут изменены. Продолжить? @@ -845,6 +847,7 @@ oauth2_client_id=ID клиента oauth2_client_secret=Клиентский ключ oauth2_regenerate_secret=Сгенерировать новый ключ oauth2_regenerate_secret_hint=Потеряли свой ключ? +oauth2_client_secret_hint=Пожалуйста, сохраните секрет, так как после закрытия или обновления страницы он больше не будет показан. oauth2_application_edit=Изменить oauth2_application_create_description=Приложения OAuth2 предоставляет стороннему приложению доступ к учётным записям пользователей данного сервиса. oauth2_application_remove_description=Удаление приложения OAuth2 приведёт к отмене его доступа к авторизованным учётным записям пользователей в данном экземпляре. Продолжить? @@ -857,6 +860,7 @@ revoke_oauth2_grant_description=Отзыв доступа у этого стор revoke_oauth2_grant_success=Доступ был успешно отозван. twofa_desc=Двухфакторная аутентификация повышает уровень безопасности вашей учётной записи. +twofa_recovery_tip=В случае утраты устройства можно использовать одноразовый ключ восстановления для получения доступа к учётной записи. twofa_is_enrolled=Ваша учётная запись в настоящее время использует двухфакторную аутентификацию. twofa_not_enrolled=Ваша учётная запись в настоящее время не использует двухфакторную аутентификацию. twofa_disable=Отключить двухфакторную аутентификацию @@ -878,6 +882,7 @@ webauthn_register_key=Добавить ключ безопасности webauthn_nickname=Имя пользователя webauthn_delete_key=Удалить ключ безопасности webauthn_delete_key_desc=Если вы удалите ключ безопасности, вы больше не сможете войти с его помощью. Продолжить? +webauthn_key_loss_warning=В случае утраты ключей безопасности вы потеряете доступ к учётной записи. manage_account_links=Управление привязанными аккаунтами manage_account_links_desc=Эти внешние аккаунты привязаны к вашему аккаунту Gitea. @@ -999,6 +1004,8 @@ delete_preexisting_success=Удалены непринятые файлы в %s blame_prior=Показать авторство предшествующих изменений author_search_tooltip=Показывает максимум 30 пользователей +tree_path_not_found_commit=Путь %[1]s не существует в коммите %[2]s +tree_path_not_found_branch=Путь %[1]s не существует в ветке %[2]s transfer.accept=Принять трансфер transfer.accept_desc=Переместить в «%s» @@ -1140,6 +1147,8 @@ file_view_rendered=Просмотр отрендеренного file_view_raw=Посмотреть исходник file_permalink=Постоянная ссылка file_too_large=Этот файл слишком большой, поэтому он не может быть отображён. +invisible_runes_header=`Этот файл содержит невидимые символы Юникода` +ambiguous_runes_header=`Этот файл содержит неоднозначные символы Юникода` invisible_runes_line=`В этой строке есть невидимые символы Юникода` ambiguous_runes_line=`В этой строке есть неоднозначные символы Юникода` ambiguous_character=`%[1]c [U+%04[1]X] можно спутать с %[2]c [U+%04[2]X]` @@ -1414,6 +1423,7 @@ issues.filter_sort.moststars=Больше звезд issues.filter_sort.feweststars=Меньше звезд issues.filter_sort.mostforks=Больше форков issues.filter_sort.fewestforks=Меньше форков +issues.keyword_search_unavailable=В настоящее время поиск по ключевым словам недоступен. Обратитесь к администратору сайта. issues.action_open=Открыть issues.action_close=Закрыть issues.action_label=Метка @@ -1462,9 +1472,15 @@ issues.ref_closed_from=`закрыл этот запрос %[4]s issues.ref_reopened_from=`переоткрыл эту задачу %[4]s %[2]s` issues.ref_from=`из %[1]s` issues.author=Автор +issues.author_helper=Этот пользователь является автором. issues.role.owner=Владелец +issues.role.owner_helper=Этот пользователь является владельцем репозитория. issues.role.member=Участник +issues.role.member_helper=Этот пользователь является членом организации, владеющей этим репозиторием. issues.role.collaborator=Соавтор +issues.role.collaborator_helper=Этот пользователь был приглашен сотрудничать в репозитории. +issues.role.first_time_contributor=Новый участник +issues.role.first_time_contributor_helper=Это первый вклад пользователя в репозиторий. issues.role.contributor=Участник issues.re_request_review=Повторить запрос на отзыв issues.is_stale=Со времени этого обзора в этот PR были внесены некоторые изменения @@ -1481,6 +1497,8 @@ issues.label_description=Описание метки issues.label_color=Цвет метки issues.label_exclusive=Эксклюзивный issues.label_archive=Метка архива +issues.label_archived_filter=Показать архивированные метки +issues.label_archive_tooltip=Архивированные метки исключаются по умолчанию из подсказок при поиске по метке. issues.label_exclusive_desc=Назовите метку область/элемент, чтобы сделать ее взаимоисключающей с другими метками область/. issues.label_exclusive_warning=Любые метки с конфликтующей областью будут удалены при редактировании меток задачи или запроса на слияние. issues.label_count=%d меток @@ -1535,6 +1553,7 @@ issues.tracking_already_started=`Вы уже начали отслеживать issues.stop_tracking=Остановить таймер issues.stop_tracking_history=`перестал(а) работать %s` issues.cancel_tracking=Отмена +issues.cancel_tracking_history=`отменил(а) отслеживание времени %s` issues.add_time=Вручную добавить время issues.del_time=Удалить этот журнал времени issues.add_time_short=Добавить время @@ -1690,6 +1709,7 @@ pulls.is_empty=Изменения из этой ветки уже есть в ц pulls.required_status_check_failed=Некоторые необходимые проверки не были пройдены. pulls.required_status_check_missing=Отсутствуют некоторые обязательные проверки. pulls.required_status_check_administrator=Как администратор, вы все равно можете принять этот запрос на слияние. +pulls.blocked_by_approvals=Этот запрос на слияние пока не имеет достаточного количества одобрений. Получено %d из %d одобрений. pulls.blocked_by_rejection=Официальный рецензент запросил изменения к этому запросу на слияние. pulls.can_auto_merge_desc=Этот запрос на слияние может быть объединён автоматически. pulls.cannot_auto_merge_desc=Этот запрос на слияние не может быть объединён автоматически. @@ -1736,6 +1756,8 @@ pulls.status_checks_failure=Некоторые проверки не удали pulls.status_checks_error=Некоторые проверки сообщили об ошибках pulls.status_checks_requested=Требуется pulls.status_checks_details=Информация +pulls.status_checks_hide_all=Скрыть все проверки +pulls.status_checks_show_all=Показать все проверки pulls.update_branch=Обновить ветку посредством слияния pulls.update_branch_rebase=Обновить ветку через rebase pulls.update_branch_success=Обновление ветки выполнено успешно @@ -1744,6 +1766,9 @@ pulls.outdated_with_base_branch=Эта ветка отстает от базов pulls.close=Закрыть запрос на слияние pulls.closed_at=`закрыл этот запрос на слияние %[2]s` pulls.reopened_at=`переоткрыл этот запрос на слияние %[2]s` +pulls.cmd_instruction_hint=`Просмотреть инструкции для командной строки.` +pulls.cmd_instruction_merge_title=Слить +pulls.cmd_instruction_merge_desc=Слить изменения и обновить в Gitea. pulls.clear_merge_message=Очистить сообщение о слиянии pulls.clear_merge_message_hint=Очистка сообщения о слиянии удалит только содержимое сообщения коммита, но сохранит сгенерированные git добавки, такие как "Co-Authored-By …". @@ -1787,6 +1812,8 @@ milestones.edit_success=Этап «%s» обновлён. milestones.deletion=Удалить этап milestones.deletion_desc=Удаление этапа приведет к его удалению из всех связанных задач. Продолжить? milestones.deletion_success=Этап успешно удалён. +milestones.filter_sort.earliest_due_data=По возрастанию даты завершения +milestones.filter_sort.latest_due_date=По убыванию даты завершения milestones.filter_sort.least_complete=Менее полное milestones.filter_sort.most_complete=Более полное milestones.filter_sort.most_issues=Большинство задач @@ -1797,7 +1824,9 @@ signing.wont_sign.never=Коммиты никогда не подписываю signing.wont_sign.always=Коммиты всегда подписываются. signing.wont_sign.pubkey=Этот коммит не будет подписан, поскольку к вашей учётной записи не привязано публичного ключа. signing.wont_sign.twofa=Для подписания коммитов у вас должна быть включена двухфакторная аутентификация. +signing.wont_sign.parentsigned=Этот коммит не будет подписан, так как родительский коммит не подписан. signing.wont_sign.basesigned=Слияние не будет подписано, так как базовый коммит не подписан. +signing.wont_sign.headsigned=Слияние не будет подписано, так как головной коммит не подписан. signing.wont_sign.commitssigned=Слияние не будет подписано, так как все связанные коммиты не подписаны. signing.wont_sign.approved=Слияние не будет подписано, так как запрос на слияние не одобрен. signing.wont_sign.not_signed_in=Вы не вошли в систему. @@ -1829,7 +1858,7 @@ wiki.page_already_exists=Страница вики с таким именем у wiki.reserved_page=Имя страницы вики «%s» зарезервировано. wiki.pages=Страницы wiki.last_updated=Последнее обновление %s -wiki.page_name_desc=Введите имя страницы вики. Некоторые специальные имена: 'Главна', '_Sidebar' и '_Footer'. +wiki.page_name_desc=Введите имя страницы вики. Некоторые специальные имена: 'Home', '_Sidebar' и '_Footer'. activity=Активность activity.period.filter_label=Период: @@ -1943,6 +1972,7 @@ settings.mirror_settings.push_mirror.add=Добавить Push-зеркало settings.mirror_settings.push_mirror.edit_sync_time=Изменить интервал синхронизации зеркала settings.sync_mirror=Синхронизировать +settings.push_mirror_sync_in_progress=Идёт отправка изменений в удалённый репозиторий %s. settings.site=Сайт settings.update_settings=Обновить настройки settings.update_mirror_settings=Обновить настройки зеркала @@ -2009,6 +2039,7 @@ settings.transfer.rejected=Трансфер репозитория отменё settings.transfer.success=Трансфер репозитория успешно выполнен. settings.transfer_abort=Отменить трансфер settings.transfer_abort_invalid=Невозможно отменить трансфер несуществующего репозитория. +settings.transfer_abort_success=Передача репозитория %s успешно отменена. settings.transfer_desc=Передать репозиторий другому пользователю или организации где у вас есть права администратора. settings.transfer_form_title=Введите сопутствующую информацию для подтверждения операции: settings.transfer_in_progress=Трансфер в процессе выполнения. Отмените его, если желаете выполнить трансфер другому пользователю. @@ -2240,6 +2271,7 @@ settings.dismiss_stale_approvals_desc=Когда новые коммиты, из settings.require_signed_commits=Требовать подписанные коммиты settings.require_signed_commits_desc=Отклонить отправку изменений в эту ветку, если они не подписаны или не проверяемы. settings.protect_branch_name_pattern=Шаблон имени для защищённых веток +settings.protect_branch_name_pattern_desc=Шаблоны имён защищённых веток. О синтаксисе шаблонов читайте в документации. Примеры: main, release/** settings.protect_patterns=Шаблоны settings.protect_protected_file_patterns=Шаблоны защищённых файлов (разделённые точкой с запятой ';'): settings.protect_protected_file_patterns_desc=Защищенные файлы нельзя изменить напрямую, даже если пользователь имеет право добавлять, редактировать или удалять файлы в этой ветке. Можно указать несколько шаблонов, разделяя их точкой с запятой (';'). О синтаксисе шаблонов читайте в документации github.com/gobwas/glob. Примеры: .drone.yml, /docs/**/*.txt. @@ -2451,6 +2483,7 @@ branch.default_deletion_failed=Ветка «%s» является веткой branch.restore=Восстановить ветку «%s» branch.download=Скачать ветку «%s» branch.rename=Переименовать ветку «%s» +branch.search=Поиск ветки branch.included_desc=Эта ветка является частью ветки по умолчанию branch.included=Включено branch.create_new_branch=Создать ветку из ветви: @@ -2473,6 +2506,7 @@ tag.create_success=Тег «%s» создан. topic.manage_topics=Редактировать тематические метки topic.done=Сохранить topic.count_prompt=Нельзя выбрать более 25 тем +topic.format_prompt=Темы должны начинаться с буквы или цифры и могут содержать дефисы («-») и точки («.»). Длина темы не должна превышать 35 символов. Все буквы должны быть строчными. find_file.go_to_file=Перейти к файлу find_file.no_matching=Совпадающих файлов не найдено @@ -2600,11 +2634,13 @@ teams.all_repositories_helper=Команда имеет доступ ко все teams.all_repositories_read_permission_desc=Эта команда предоставляет прочтено доступ к всем репозиториям: участники могут просматривать и клонировать репозитории. teams.all_repositories_write_permission_desc=Эта команда предоставляет Написать доступ к всем репозиториям: участники могут читать и выполнять push в репозитории. teams.all_repositories_admin_permission_desc=Эта команда предоставляет администратору доступ к всем репозиториям: участники могут читать, отправлять сообщения и добавлять соавторов в репозитории. +teams.invite.title=Вас пригласили присоединиться к команде %s организации %s. teams.invite.by=Приглашен(а) %s teams.invite.description=Нажмите на кнопку ниже, чтобы присоединиться к команде. [admin] dashboard=Панель +identity_access=Идентификация и доступ users=Пользователи organizations=Организации repositories=Репозитории @@ -2697,6 +2733,7 @@ dashboard.gc_lfs=Выполнить сборку мусора метаобъек dashboard.stop_zombie_tasks=Остановить задания-зомби dashboard.stop_endless_tasks=Остановить бесконечные задания dashboard.cancel_abandoned_jobs=Отменить брошенные задания +dashboard.start_schedule_tasks=Запустить запланированные задания users.user_manage_panel=Панель управления пользователями users.new_account=Создать новый аккаунт @@ -2766,6 +2803,7 @@ emails.updated=Email обновлён emails.not_updated=Не удалось обновить запрошенный адрес электронной почты: %v emails.duplicate_active=Этот адрес электронной почты уже активирован для другого пользователя. emails.change_email_header=Обновить свойства электронной почты +emails.change_email_text=Вы уверены, что хотите обновить этот адрес электронной почты? orgs.org_manage_panel=Управление организациями orgs.name=Название @@ -2790,6 +2828,7 @@ packages.package_manage_panel=Управление пакетами packages.total_size=Общий размер: %s packages.unreferenced_size=Размер по ссылке: %s packages.cleanup=Очистить устаревшие данные +packages.cleanup.success=Очистка устаревших данных успешно завершена packages.owner=Владелец packages.creator=Автор packages.name=Наименование @@ -3086,6 +3125,7 @@ monitor.queue.name=Имя monitor.queue.type=Тип monitor.queue.exemplar=Тип образца monitor.queue.numberworkers=Количество рабочих +monitor.queue.activeworkers=Активные рабочие monitor.queue.maxnumberworkers=Максимальное количество рабочих monitor.queue.numberinqueue=Позиция в очереди monitor.queue.settings.title=Настройки пула @@ -3411,16 +3451,23 @@ runners.status.idle=Простаивает runners.status.active=Активный runners.status.offline=Недоступен runners.version=Версия +runners.reset_registration_token=Сброс регистрационного токена runners.reset_registration_token_success=Токен регистрации раннера успешно сброшен runs.all_workflows=Все рабочие потоки runs.commit=коммит +runs.scheduled=Запланировано runs.pushed_by=отправлено runs.invalid_workflow_helper=Файл конфигурации рабочего потока некорректен. Пожалуйста, проверьте конфигурационный файл: %s runs.actor=Актор runs.status=Статус runs.actors_no_select=Все акторы +runs.no_results=Ничего не найдено. +runs.no_workflows=Пока нет рабочих процессов. +runs.no_workflows.quick_start=Не знаете, как начать использовать Действия Gitea? Читайте руководство по быстрому старту. +runs.no_workflows.documentation=Чтобы узнать больше о Действиях Gitea, читайте документацию. runs.no_runs=Рабочий поток ещё не запускался. +runs.empty_commit_message=(пустое сообщение коммита) workflow.disable=Выключить рабочий поток workflow.disable_success=Рабочий поток «%s» успешно выключен. From 4c29c75968f520123f125e8305b2c29198664251 Mon Sep 17 00:00:00 2001 From: Lunny Xiao Date: Wed, 27 Dec 2023 15:24:23 +0800 Subject: [PATCH 032/189] Fix session key conflict with database keyword (#28613) This is a regression from #28220 . `builder.Cond` will not add `` ` `` automatically but xorm method `Get/Find` adds `` ` ``. This PR also adds tests to prevent the method from being implemented incorrectly. The tests are added in `integrations` to test every database. --- models/auth/session.go | 17 ++++++++------ tests/integration/session_test.go | 37 +++++++++++++++++++++++++++++++ 2 files changed, 47 insertions(+), 7 deletions(-) create mode 100644 tests/integration/session_test.go diff --git a/models/auth/session.go b/models/auth/session.go index 60fdeaba7c2..75a205f702b 100644 --- a/models/auth/session.go +++ b/models/auth/session.go @@ -41,12 +41,15 @@ func ReadSession(ctx context.Context, key string) (*Session, error) { } defer committer.Close() - session, exist, err := db.Get[Session](ctx, builder.Eq{"key": key}) + session, exist, err := db.Get[Session](ctx, builder.Eq{"`key`": key}) if err != nil { return nil, err } else if !exist { - session.Expiry = timeutil.TimeStampNow() - if err := db.Insert(ctx, &session); err != nil { + session = &Session{ + Key: key, + Expiry: timeutil.TimeStampNow(), + } + if err := db.Insert(ctx, session); err != nil { return nil, err } } @@ -56,7 +59,7 @@ func ReadSession(ctx context.Context, key string) (*Session, error) { // ExistSession checks if a session exists func ExistSession(ctx context.Context, key string) (bool, error) { - return db.Exist[Session](ctx, builder.Eq{"key": key}) + return db.Exist[Session](ctx, builder.Eq{"`key`": key}) } // DestroySession destroys a session @@ -75,13 +78,13 @@ func RegenerateSession(ctx context.Context, oldKey, newKey string) (*Session, er } defer committer.Close() - if has, err := db.Exist[Session](ctx, builder.Eq{"key": newKey}); err != nil { + if has, err := db.Exist[Session](ctx, builder.Eq{"`key`": newKey}); err != nil { return nil, err } else if has { return nil, fmt.Errorf("session Key: %s already exists", newKey) } - if has, err := db.Exist[Session](ctx, builder.Eq{"key": oldKey}); err != nil { + if has, err := db.Exist[Session](ctx, builder.Eq{"`key`": oldKey}); err != nil { return nil, err } else if !has { if err := db.Insert(ctx, &Session{ @@ -96,7 +99,7 @@ func RegenerateSession(ctx context.Context, oldKey, newKey string) (*Session, er return nil, err } - s, _, err := db.Get[Session](ctx, builder.Eq{"key": newKey}) + s, _, err := db.Get[Session](ctx, builder.Eq{"`key`": newKey}) if err != nil { // is not exist, it should be impossible return nil, err diff --git a/tests/integration/session_test.go b/tests/integration/session_test.go new file mode 100644 index 00000000000..d47148efa23 --- /dev/null +++ b/tests/integration/session_test.go @@ -0,0 +1,37 @@ +// Copyright 2023 The Gitea Authors. All rights reserved. +// SPDX-License-Identifier: MIT + +package integration + +import ( + "testing" + + "code.gitea.io/gitea/models/auth" + "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" + "code.gitea.io/gitea/tests" + + "github.com/stretchr/testify/assert" +) + +func Test_RegenerateSession(t *testing.T) { + defer tests.PrepareTestEnv(t)() + + assert.NoError(t, unittest.PrepareTestDatabase()) + + key := "new_key890123456" // it must be 16 characters long + key2 := "new_key890123457" // it must be 16 characters + exist, err := auth.ExistSession(db.DefaultContext, key) + assert.NoError(t, err) + assert.False(t, exist) + + sess, err := auth.RegenerateSession(db.DefaultContext, "", key) + assert.NoError(t, err) + assert.EqualValues(t, key, sess.Key) + assert.Len(t, sess.Data, 0) + + sess, err = auth.ReadSession(db.DefaultContext, key2) + assert.NoError(t, err) + assert.EqualValues(t, key2, sess.Key) + assert.Len(t, sess.Data, 0) +} From baf0d402d9cb47849394202fcfc7c2e23b0faac3 Mon Sep 17 00:00:00 2001 From: Lunny Xiao Date: Wed, 27 Dec 2023 15:57:54 +0800 Subject: [PATCH 033/189] Add get actions runner registration token for API routes, repo, org, user and global level (#27144) Replace #23761 --------- Co-authored-by: Denys Konovalov Co-authored-by: techknowlogick --- routers/api/v1/admin/runners.go | 26 +++++ routers/api/v1/api.go | 49 ++++++--- routers/api/v1/org/runners.go | 31 ++++++ routers/api/v1/org/{action.go => secrets.go} | 0 routers/api/v1/repo/runners.go | 34 +++++++ routers/api/v1/shared/runners.go | 32 ++++++ routers/api/v1/user/runners.go | 26 +++++ templates/swagger/v1_json.tmpl | 101 +++++++++++++++++++ 8 files changed, 285 insertions(+), 14 deletions(-) create mode 100644 routers/api/v1/admin/runners.go create mode 100644 routers/api/v1/org/runners.go rename routers/api/v1/org/{action.go => secrets.go} (100%) create mode 100644 routers/api/v1/repo/runners.go create mode 100644 routers/api/v1/shared/runners.go create mode 100644 routers/api/v1/user/runners.go diff --git a/routers/api/v1/admin/runners.go b/routers/api/v1/admin/runners.go new file mode 100644 index 00000000000..c0d93644350 --- /dev/null +++ b/routers/api/v1/admin/runners.go @@ -0,0 +1,26 @@ +// Copyright 2023 The Gitea Authors. All rights reserved. +// SPDX-License-Identifier: MIT + +package admin + +import ( + "code.gitea.io/gitea/modules/context" + "code.gitea.io/gitea/routers/api/v1/shared" +) + +// https://docs.github.com/en/rest/actions/self-hosted-runners?apiVersion=2022-11-28#create-a-registration-token-for-an-organization + +// GetRegistrationToken returns the token to register global runners +func GetRegistrationToken(ctx *context.APIContext) { + // swagger:operation GET /admin/runners/registration-token admin adminGetRunnerRegistrationToken + // --- + // summary: Get an global actions runner registration token + // produces: + // - application/json + // parameters: + // responses: + // "200": + // "$ref": "#/responses/RegistrationToken" + + shared.GetRegistrationToken(ctx, 0, 0) +} diff --git a/routers/api/v1/api.go b/routers/api/v1/api.go index a4c3d6f4440..4fe4e20e794 100644 --- a/routers/api/v1/api.go +++ b/routers/api/v1/api.go @@ -948,11 +948,17 @@ func Routes() *web.Route { Post(bind(api.CreateEmailOption{}), user.AddEmail). Delete(bind(api.DeleteEmailOption{}), user.DeleteEmail) - // create or update a user's actions secrets - m.Group("/actions/secrets", func() { - m.Combo("/{secretname}"). - Put(bind(api.CreateOrUpdateSecretOption{}), user.CreateOrUpdateSecret). - Delete(user.DeleteSecret) + // manage user-level actions features + m.Group("/actions", func() { + m.Group("/secrets", func() { + m.Combo("/{secretname}"). + Put(bind(api.CreateOrUpdateSecretOption{}), user.CreateOrUpdateSecret). + Delete(user.DeleteSecret) + }) + + m.Group("/runners", func() { + m.Get("/registration-token", reqToken(), user.GetRegistrationToken) + }) }) m.Get("/followers", user.ListMyFollowers) @@ -1052,10 +1058,16 @@ func Routes() *web.Route { m.Post("/accept", repo.AcceptTransfer) m.Post("/reject", repo.RejectTransfer) }, reqToken()) - m.Group("/actions/secrets", func() { - m.Combo("/{secretname}"). - Put(reqToken(), reqOwner(), bind(api.CreateOrUpdateSecretOption{}), repo.CreateOrUpdateSecret). - Delete(reqToken(), reqOwner(), repo.DeleteSecret) + m.Group("/actions", func() { + m.Group("/secrets", func() { + m.Combo("/{secretname}"). + Put(reqToken(), reqOwner(), bind(api.CreateOrUpdateSecretOption{}), repo.CreateOrUpdateSecret). + Delete(reqToken(), reqOwner(), repo.DeleteSecret) + }) + + m.Group("/runners", func() { + m.Get("/registration-token", reqToken(), reqOwner(), repo.GetRegistrationToken) + }) }) m.Group("/hooks/git", func() { m.Combo("").Get(repo.ListGitHooks) @@ -1422,11 +1434,17 @@ func Routes() *web.Route { m.Combo("/{username}").Get(reqToken(), org.IsMember). Delete(reqToken(), reqOrgOwnership(), org.DeleteMember) }) - m.Group("/actions/secrets", func() { - m.Get("", reqToken(), reqOrgOwnership(), org.ListActionsSecrets) - m.Combo("/{secretname}"). - Put(reqToken(), reqOrgOwnership(), bind(api.CreateOrUpdateSecretOption{}), org.CreateOrUpdateSecret). - Delete(reqToken(), reqOrgOwnership(), org.DeleteSecret) + m.Group("/actions", func() { + m.Group("/secrets", func() { + m.Get("", reqToken(), reqOrgOwnership(), org.ListActionsSecrets) + m.Combo("/{secretname}"). + Put(reqToken(), reqOrgOwnership(), bind(api.CreateOrUpdateSecretOption{}), org.CreateOrUpdateSecret). + Delete(reqToken(), reqOrgOwnership(), org.DeleteSecret) + }) + + m.Group("/runners", func() { + m.Get("/registration-token", reqToken(), reqOrgOwnership(), org.GetRegistrationToken) + }) }) m.Group("/public_members", func() { m.Get("", org.ListPublicMembers) @@ -1518,6 +1536,9 @@ func Routes() *web.Route { Patch(bind(api.EditHookOption{}), admin.EditHook). Delete(admin.DeleteHook) }) + m.Group("/runners", func() { + m.Get("/registration-token", admin.GetRegistrationToken) + }) }, tokenRequiresScopes(auth_model.AccessTokenScopeCategoryAdmin), reqToken(), reqSiteAdmin()) m.Group("/topics", func() { diff --git a/routers/api/v1/org/runners.go b/routers/api/v1/org/runners.go new file mode 100644 index 00000000000..05bce8daefb --- /dev/null +++ b/routers/api/v1/org/runners.go @@ -0,0 +1,31 @@ +// Copyright 2023 The Gitea Authors. All rights reserved. +// SPDX-License-Identifier: MIT + +package org + +import ( + "code.gitea.io/gitea/modules/context" + "code.gitea.io/gitea/routers/api/v1/shared" +) + +// https://docs.github.com/en/rest/actions/self-hosted-runners?apiVersion=2022-11-28#create-a-registration-token-for-an-organization + +// GetRegistrationToken returns the token to register org runners +func GetRegistrationToken(ctx *context.APIContext) { + // swagger:operation GET /orgs/{org}/actions/runners/registration-token organization orgGetRunnerRegistrationToken + // --- + // summary: Get an organization's actions runner registration token + // produces: + // - application/json + // parameters: + // - name: org + // in: path + // description: name of the organization + // type: string + // required: true + // responses: + // "200": + // "$ref": "#/responses/RegistrationToken" + + shared.GetRegistrationToken(ctx, ctx.Org.Organization.ID, 0) +} diff --git a/routers/api/v1/org/action.go b/routers/api/v1/org/secrets.go similarity index 100% rename from routers/api/v1/org/action.go rename to routers/api/v1/org/secrets.go diff --git a/routers/api/v1/repo/runners.go b/routers/api/v1/repo/runners.go new file mode 100644 index 00000000000..0a2bbf81176 --- /dev/null +++ b/routers/api/v1/repo/runners.go @@ -0,0 +1,34 @@ +// Copyright 2023 The Gitea Authors. All rights reserved. +// SPDX-License-Identifier: MIT + +package repo + +import ( + "code.gitea.io/gitea/modules/context" + "code.gitea.io/gitea/routers/api/v1/shared" +) + +// GetRegistrationToken returns the token to register repo runners +func GetRegistrationToken(ctx *context.APIContext) { + // swagger:operation GET /repos/{owner}/{repo}/runners/registration-token repository repoGetRunnerRegistrationToken + // --- + // summary: Get a repository's actions runner registration token + // produces: + // - application/json + // parameters: + // - name: owner + // in: path + // description: owner of the repo + // type: string + // required: true + // - name: repo + // in: path + // description: name of the repo + // type: string + // required: true + // responses: + // "200": + // "$ref": "#/responses/RegistrationToken" + + shared.GetRegistrationToken(ctx, ctx.Repo.Repository.OwnerID, ctx.Repo.Repository.ID) +} diff --git a/routers/api/v1/shared/runners.go b/routers/api/v1/shared/runners.go new file mode 100644 index 00000000000..a342bd4b637 --- /dev/null +++ b/routers/api/v1/shared/runners.go @@ -0,0 +1,32 @@ +// Copyright 2023 The Gitea Authors. All rights reserved. +// SPDX-License-Identifier: MIT + +package shared + +import ( + "errors" + "net/http" + + actions_model "code.gitea.io/gitea/models/actions" + "code.gitea.io/gitea/modules/context" + "code.gitea.io/gitea/modules/util" +) + +// RegistrationToken is response related to registeration token +// swagger:response RegistrationToken +type RegistrationToken struct { + Token string `json:"token"` +} + +func GetRegistrationToken(ctx *context.APIContext, ownerID, repoID int64) { + token, err := actions_model.GetLatestRunnerToken(ctx, ownerID, repoID) + if errors.Is(err, util.ErrNotExist) || (token != nil && !token.IsActive) { + token, err = actions_model.NewRunnerToken(ctx, ownerID, repoID) + } + if err != nil { + ctx.InternalServerError(err) + return + } + + ctx.JSON(http.StatusOK, RegistrationToken{Token: token.Token}) +} diff --git a/routers/api/v1/user/runners.go b/routers/api/v1/user/runners.go new file mode 100644 index 00000000000..51556ae0fb8 --- /dev/null +++ b/routers/api/v1/user/runners.go @@ -0,0 +1,26 @@ +// Copyright 2023 The Gitea Authors. All rights reserved. +// SPDX-License-Identifier: MIT + +package user + +import ( + "code.gitea.io/gitea/modules/context" + "code.gitea.io/gitea/routers/api/v1/shared" +) + +// https://docs.github.com/en/rest/actions/self-hosted-runners?apiVersion=2022-11-28#create-a-registration-token-for-an-organization + +// GetRegistrationToken returns the token to register user runners +func GetRegistrationToken(ctx *context.APIContext) { + // swagger:operation GET /user/actions/runners/registration-token user userGetRunnerRegistrationToken + // --- + // summary: Get an user's actions runner registration token + // produces: + // - application/json + // parameters: + // responses: + // "200": + // "$ref": "#/responses/RegistrationToken" + + shared.GetRegistrationToken(ctx, ctx.Doer.ID, 0) +} diff --git a/templates/swagger/v1_json.tmpl b/templates/swagger/v1_json.tmpl index 215c1692f61..de3bc331f16 100644 --- a/templates/swagger/v1_json.tmpl +++ b/templates/swagger/v1_json.tmpl @@ -392,6 +392,23 @@ } } }, + "/admin/runners/registration-token": { + "get": { + "produces": [ + "application/json" + ], + "tags": [ + "admin" + ], + "summary": "Get an global actions runner registration token", + "operationId": "adminGetRunnerRegistrationToken", + "responses": { + "200": { + "$ref": "#/responses/RegistrationToken" + } + } + } + }, "/admin/unadopted": { "get": { "produces": [ @@ -1562,6 +1579,32 @@ } } }, + "/orgs/{org}/actions/runners/registration-token": { + "get": { + "produces": [ + "application/json" + ], + "tags": [ + "organization" + ], + "summary": "Get an organization's actions runner registration token", + "operationId": "orgGetRunnerRegistrationToken", + "parameters": [ + { + "type": "string", + "description": "name of the organization", + "name": "org", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "$ref": "#/responses/RegistrationToken" + } + } + } + }, "/orgs/{org}/actions/secrets": { "get": { "produces": [ @@ -12359,6 +12402,39 @@ } } }, + "/repos/{owner}/{repo}/runners/registration-token": { + "get": { + "produces": [ + "application/json" + ], + "tags": [ + "repository" + ], + "summary": "Get a repository's actions runner registration token", + "operationId": "repoGetRunnerRegistrationToken", + "parameters": [ + { + "type": "string", + "description": "owner of the repo", + "name": "owner", + "in": "path", + "required": true + }, + { + "type": "string", + "description": "name of the repo", + "name": "repo", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "$ref": "#/responses/RegistrationToken" + } + } + } + }, "/repos/{owner}/{repo}/signing-key.gpg": { "get": { "produces": [ @@ -14517,6 +14593,23 @@ } } }, + "/user/actions/runners/registration-token": { + "get": { + "produces": [ + "application/json" + ], + "tags": [ + "user" + ], + "summary": "Get an user's actions runner registration token", + "operationId": "userGetRunnerRegistrationToken", + "responses": { + "200": { + "$ref": "#/responses/RegistrationToken" + } + } + } + }, "/user/actions/secrets/{secretname}": { "put": { "consumes": [ @@ -23726,6 +23819,14 @@ } } }, + "RegistrationToken": { + "description": "RegistrationToken is response related to registeration token", + "headers": { + "token": { + "type": "string" + } + } + }, "Release": { "description": "Release", "schema": { From 42149ff1a816501643ec2407ed61a83bf5b65059 Mon Sep 17 00:00:00 2001 From: katsu Date: Wed, 27 Dec 2023 16:32:27 +0800 Subject: [PATCH 034/189] fix wrong link in user and organization profile when using relative url (#28617) fix #28436. the doc https://docs.gitea.com/usage/profile-readme maybe also need to be updated to tell that the main branch is necessary,which means the following three conditions should be satisfied: - repo: **.profile** - branch: **[default branch]** - markdown: **README.md** --- routers/web/org/home.go | 17 +++++++++++------ routers/web/shared/user/header.go | 6 +++--- routers/web/user/profile.go | 20 ++++++++++++++------ 3 files changed, 28 insertions(+), 15 deletions(-) diff --git a/routers/web/org/home.go b/routers/web/org/home.go index a9adfdc03cd..cdf280ed4ac 100644 --- a/routers/web/org/home.go +++ b/routers/web/org/home.go @@ -18,6 +18,7 @@ import ( "code.gitea.io/gitea/modules/markup" "code.gitea.io/gitea/modules/markup/markdown" "code.gitea.io/gitea/modules/setting" + "code.gitea.io/gitea/modules/util" shared_user "code.gitea.io/gitea/routers/web/shared/user" ) @@ -157,14 +158,14 @@ func Home(ctx *context.Context) { ctx.Data["ShowMemberAndTeamTab"] = ctx.Org.IsMember || len(members) > 0 - profileGitRepo, profileReadmeBlob, profileClose := shared_user.FindUserProfileReadme(ctx, ctx.Doer) + profileDbRepo, profileGitRepo, profileReadmeBlob, profileClose := shared_user.FindUserProfileReadme(ctx, ctx.Doer) defer profileClose() - prepareOrgProfileReadme(ctx, profileGitRepo, profileReadmeBlob) + prepareOrgProfileReadme(ctx, profileGitRepo, profileDbRepo, profileReadmeBlob) ctx.HTML(http.StatusOK, tplOrgHome) } -func prepareOrgProfileReadme(ctx *context.Context, profileGitRepo *git.Repository, profileReadme *git.Blob) { +func prepareOrgProfileReadme(ctx *context.Context, profileGitRepo *git.Repository, profileDbRepo *repo_model.Repository, profileReadme *git.Blob) { if profileGitRepo == nil || profileReadme == nil { return } @@ -172,10 +173,14 @@ func prepareOrgProfileReadme(ctx *context.Context, profileGitRepo *git.Repositor if bytes, err := profileReadme.GetBlobContent(setting.UI.MaxDisplayFileSize); err != nil { log.Error("failed to GetBlobContent: %v", err) } else { + // Pass URLPrefix to markdown render for the full link of media elements. + // The profile of default branch would be shown. + prefix := profileDbRepo.Link() + "/src/branch/" + util.PathEscapeSegments(profileDbRepo.DefaultBranch) if profileContent, err := markdown.RenderString(&markup.RenderContext{ - Ctx: ctx, - GitRepo: profileGitRepo, - Metas: map[string]string{"mode": "document"}, + Ctx: ctx, + GitRepo: profileGitRepo, + URLPrefix: prefix, + Metas: map[string]string{"mode": "document"}, }, bytes); err != nil { log.Error("failed to RenderString: %v", err) } else { diff --git a/routers/web/shared/user/header.go b/routers/web/shared/user/header.go index 411d499eb4f..919a080b42c 100644 --- a/routers/web/shared/user/header.go +++ b/routers/web/shared/user/header.go @@ -87,7 +87,7 @@ func PrepareContextForProfileBigAvatar(ctx *context.Context) { } } -func FindUserProfileReadme(ctx *context.Context, doer *user_model.User) (profileGitRepo *git.Repository, profileReadmeBlob *git.Blob, profileClose func()) { +func FindUserProfileReadme(ctx *context.Context, doer *user_model.User) (profileDbRepo *repo_model.Repository, profileGitRepo *git.Repository, profileReadmeBlob *git.Blob, profileClose func()) { profileDbRepo, err := repo_model.GetRepositoryByName(ctx, ctx.ContextUser.ID, ".profile") if err == nil { perm, err := access_model.GetUserRepoPermission(ctx, profileDbRepo, doer) @@ -105,7 +105,7 @@ func FindUserProfileReadme(ctx *context.Context, doer *user_model.User) (profile } else if !repo_model.IsErrRepoNotExist(err) { log.Error("FindUserProfileReadme failed to GetRepositoryByName: %v", err) } - return profileGitRepo, profileReadmeBlob, func() { + return profileDbRepo, profileGitRepo, profileReadmeBlob, func() { if profileGitRepo != nil { _ = profileGitRepo.Close() } @@ -115,7 +115,7 @@ func FindUserProfileReadme(ctx *context.Context, doer *user_model.User) (profile func RenderUserHeader(ctx *context.Context) { prepareContextForCommonProfile(ctx) - _, profileReadmeBlob, profileClose := FindUserProfileReadme(ctx, ctx.Doer) + _, _, profileReadmeBlob, profileClose := FindUserProfileReadme(ctx, ctx.Doer) defer profileClose() ctx.Data["HasProfileReadme"] = profileReadmeBlob != nil } diff --git a/routers/web/user/profile.go b/routers/web/user/profile.go index ac278e300d7..a8ab3dde81d 100644 --- a/routers/web/user/profile.go +++ b/routers/web/user/profile.go @@ -64,17 +64,17 @@ func userProfile(ctx *context.Context) { ctx.Data["HeatmapTotalContributions"] = activities_model.GetTotalContributionsInHeatmap(data) } - profileGitRepo, profileReadmeBlob, profileClose := shared_user.FindUserProfileReadme(ctx, ctx.Doer) + profileDbRepo, profileGitRepo, profileReadmeBlob, profileClose := shared_user.FindUserProfileReadme(ctx, ctx.Doer) defer profileClose() showPrivate := ctx.IsSigned && (ctx.Doer.IsAdmin || ctx.Doer.ID == ctx.ContextUser.ID) - prepareUserProfileTabData(ctx, showPrivate, profileGitRepo, profileReadmeBlob) + prepareUserProfileTabData(ctx, showPrivate, profileDbRepo, profileGitRepo, profileReadmeBlob) // call PrepareContextForProfileBigAvatar later to avoid re-querying the NumFollowers & NumFollowing shared_user.PrepareContextForProfileBigAvatar(ctx) ctx.HTML(http.StatusOK, tplProfile) } -func prepareUserProfileTabData(ctx *context.Context, showPrivate bool, profileGitRepo *git.Repository, profileReadme *git.Blob) { +func prepareUserProfileTabData(ctx *context.Context, showPrivate bool, profileDbRepo *repo_model.Repository, profileGitRepo *git.Repository, profileReadme *git.Blob) { // if there is a profile readme, default to "overview" page, otherwise, default to "repositories" page // if there is not a profile readme, the overview tab should be treated as the repositories tab tab := ctx.FormString("tab") @@ -233,10 +233,18 @@ func prepareUserProfileTabData(ctx *context.Context, showPrivate bool, profileGi if bytes, err := profileReadme.GetBlobContent(setting.UI.MaxDisplayFileSize); err != nil { log.Error("failed to GetBlobContent: %v", err) } else { + // Give the URLPrefix to the markdown render for the full link of media element. + // the media link usually be like /[user]/[repoName]/media/branch/[branchName], + // Eg. /Tom/.profile/media/branch/main + // The branch shown on the profile page is the default branch, this need to be in sync with doc, see: + // https://docs.gitea.com/usage/profile-readme + + prefix := profileDbRepo.Link() + "/src/branch/" + util.PathEscapeSegments(profileDbRepo.DefaultBranch) if profileContent, err := markdown.RenderString(&markup.RenderContext{ - Ctx: ctx, - GitRepo: profileGitRepo, - Metas: map[string]string{"mode": "document"}, + Ctx: ctx, + GitRepo: profileGitRepo, + URLPrefix: prefix, + Metas: map[string]string{"mode": "document"}, }, bytes); err != nil { log.Error("failed to RenderString: %v", err) } else { From c706b3e4366689ce5afca19476eaf18045e874db Mon Sep 17 00:00:00 2001 From: GiteaBot Date: Thu, 28 Dec 2023 00:24:21 +0000 Subject: [PATCH 035/189] [skip ci] Updated translations via Crowdin --- options/locale/locale_fr-FR.ini | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/options/locale/locale_fr-FR.ini b/options/locale/locale_fr-FR.ini index d9fcf14b5ee..f234f801f89 100644 --- a/options/locale/locale_fr-FR.ini +++ b/options/locale/locale_fr-FR.ini @@ -1665,10 +1665,10 @@ issues.review.un_resolve_conversation=Rouvrir la conversation issues.review.resolved_by=a marqué cette conversation comme résolue. issues.assignee.error=Tous les assignés n'ont pas été ajoutés en raison d'une erreur inattendue. issues.reference_issue.body=Corps -issues.content_history.deleted=supprimé -issues.content_history.edited=édité -issues.content_history.created=créé -issues.content_history.delete_from_history=Supprimé de l’historique +issues.content_history.deleted=a supprimé +issues.content_history.edited=a édité +issues.content_history.created=a créé +issues.content_history.delete_from_history=Supprimer de l’historique issues.content_history.delete_from_history_confirm=Supprimer de l’historique ? issues.content_history.options=Options issues.reference_link=Référence : %s @@ -3521,6 +3521,7 @@ runs.actors_no_select=Tous les acteurs runs.status_no_select=Touts les statuts runs.no_results=Aucun résultat correspondant. runs.no_runs=Le flux de travail n'a pas encore d'exécution. +runs.empty_commit_message=(message de révision vide) workflow.disable=Désactiver le flux de travail workflow.disable_success=Le flux de travail « %s » a bien été désactivé. From 4cd666d7dcc7531806cde65c6468f93529cc23dd Mon Sep 17 00:00:00 2001 From: KN4CK3R Date: Thu, 28 Dec 2023 04:59:00 +0100 Subject: [PATCH 036/189] Do not set `Accept` header twice (#28598) Revert #28550 Don't add the `Accept` header twice. --- modules/lfs/http_client.go | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/modules/lfs/http_client.go b/modules/lfs/http_client.go index 41774733623..de0b1e4fede 100644 --- a/modules/lfs/http_client.go +++ b/modules/lfs/http_client.go @@ -79,10 +79,7 @@ func (c *HTTPClient) batch(ctx context.Context, operation string, objects []Poin return nil, err } - req, err := createRequest(ctx, http.MethodPost, url, map[string]string{ - "Content-Type": MediaType, - "Accept": MediaType, - }, payload) + req, err := createRequest(ctx, http.MethodPost, url, map[string]string{"Content-Type": MediaType}, payload) if err != nil { return nil, err } From 921df1cbad83dcba37ff12cba88c7d3a69f8588b Mon Sep 17 00:00:00 2001 From: Lunny Xiao Date: Thu, 28 Dec 2023 15:28:57 +0800 Subject: [PATCH 037/189] Remove unnecessary syncbranchToDB with tests (#28624) #28361 introduced `syncBranchToDB` in `CreateNewBranchFromCommit`. This PR will revert the change because it's unnecessary. Every push will already be checked by `syncBranchToDB`. This PR also created a test to ensure it's right. --- services/repository/branch.go | 29 +++++++--------------- tests/integration/api_branch_test.go | 36 ++++++++++++++++++++++++++++ 2 files changed, 45 insertions(+), 20 deletions(-) diff --git a/services/repository/branch.go b/services/repository/branch.go index dca938444aa..72547787633 100644 --- a/services/repository/branch.go +++ b/services/repository/branch.go @@ -276,28 +276,17 @@ func CreateNewBranchFromCommit(ctx context.Context, doer *user_model.User, repo return err } - return db.WithTx(ctx, func(ctx context.Context) error { - commit, err := gitRepo.GetCommit(commitID) - if err != nil { + if err := git.Push(ctx, repo.RepoPath(), git.PushOptions{ + Remote: repo.RepoPath(), + Branch: fmt.Sprintf("%s:%s%s", commitID, git.BranchPrefix, branchName), + Env: repo_module.PushingEnvironment(doer, repo), + }); err != nil { + if git.IsErrPushOutOfDate(err) || git.IsErrPushRejected(err) { return err } - // database operation should be done before git operation so that we can rollback if git operation failed - if err := syncBranchToDB(ctx, repo.ID, doer.ID, branchName, commit); err != nil { - return err - } - - if err := git.Push(ctx, repo.RepoPath(), git.PushOptions{ - Remote: repo.RepoPath(), - Branch: fmt.Sprintf("%s:%s%s", commitID, git.BranchPrefix, branchName), - Env: repo_module.PushingEnvironment(doer, repo), - }); err != nil { - if git.IsErrPushOutOfDate(err) || git.IsErrPushRejected(err) { - return err - } - return fmt.Errorf("push: %w", err) - } - return nil - }) + return fmt.Errorf("push: %w", err) + } + return nil } // RenameBranch rename a branch diff --git a/tests/integration/api_branch_test.go b/tests/integration/api_branch_test.go index 28e690b3568..103f8f707f6 100644 --- a/tests/integration/api_branch_test.go +++ b/tests/integration/api_branch_test.go @@ -9,6 +9,8 @@ import ( "testing" auth_model "code.gitea.io/gitea/models/auth" + "code.gitea.io/gitea/models/db" + git_model "code.gitea.io/gitea/models/git" api "code.gitea.io/gitea/modules/structs" "code.gitea.io/gitea/tests" @@ -217,3 +219,37 @@ func TestAPIBranchProtection(t *testing.T) { testAPIDeleteBranch(t, "master", http.StatusForbidden) testAPIDeleteBranch(t, "branch2", http.StatusNoContent) } + +func TestAPICreateBranchWithSyncBranches(t *testing.T) { + defer tests.PrepareTestEnv(t)() + + branches, err := db.Find[git_model.Branch](db.DefaultContext, git_model.FindBranchOptions{ + RepoID: 1, + }) + assert.NoError(t, err) + assert.Len(t, branches, 4) + + // make a broke repository with no branch on database + _, err = db.DeleteByBean(db.DefaultContext, git_model.Branch{RepoID: 1}) + assert.NoError(t, err) + + onGiteaRun(t, func(t *testing.T, giteaURL *url.URL) { + ctx := NewAPITestContext(t, "user2", "repo1", auth_model.AccessTokenScopeWriteRepository, auth_model.AccessTokenScopeWriteUser) + giteaURL.Path = ctx.GitPath() + + testAPICreateBranch(t, ctx.Session, "user2", "repo1", "", "new_branch", http.StatusCreated) + }) + + branches, err = db.Find[git_model.Branch](db.DefaultContext, git_model.FindBranchOptions{ + RepoID: 1, + }) + assert.NoError(t, err) + assert.Len(t, branches, 5) + + branches, err = db.Find[git_model.Branch](db.DefaultContext, git_model.FindBranchOptions{ + RepoID: 1, + Keyword: "new_branch", + }) + assert.NoError(t, err) + assert.Len(t, branches, 1) +} From f3999888c0b765380003f814f9c3d5cf80128167 Mon Sep 17 00:00:00 2001 From: wxiaoguang Date: Thu, 28 Dec 2023 17:38:59 +0800 Subject: [PATCH 038/189] Refactor some legacy code and remove unused code (#28622) 1. use slices.Contains, remove Int64sContains 2. use HashEmail, remove base.EncodeMD5 3. remove BasicAuthEncode, IsLetter --- models/avatars/avatar.go | 7 ++++-- models/git/protected_branch.go | 7 +++--- models/git/protected_tag.go | 4 ++-- models/issues/review.go | 4 ++-- modules/base/tool.go | 30 ------------------------- modules/base/tool_test.go | 35 ----------------------------- routers/web/user/setting/profile.go | 3 ++- 7 files changed, 14 insertions(+), 76 deletions(-) diff --git a/models/avatars/avatar.go b/models/avatars/avatar.go index c197a22dc1a..bbe16483bf7 100644 --- a/models/avatars/avatar.go +++ b/models/avatars/avatar.go @@ -5,6 +5,8 @@ package avatars import ( "context" + "crypto/md5" + "encoding/hex" "fmt" "net/url" "path" @@ -13,7 +15,6 @@ import ( "sync/atomic" "code.gitea.io/gitea/models/db" - "code.gitea.io/gitea/modules/base" "code.gitea.io/gitea/modules/cache" "code.gitea.io/gitea/modules/log" "code.gitea.io/gitea/modules/setting" @@ -90,7 +91,9 @@ func DefaultAvatarLink() string { // HashEmail hashes email address to MD5 string. https://en.gravatar.com/site/implement/hash/ func HashEmail(email string) string { - return base.EncodeMD5(strings.ToLower(strings.TrimSpace(email))) + m := md5.New() + _, _ = m.Write([]byte(strings.ToLower(strings.TrimSpace(email)))) + return hex.EncodeToString(m.Sum(nil)) } // GetEmailForHash converts a provided md5sum to the email diff --git a/models/git/protected_branch.go b/models/git/protected_branch.go index 528acc175a2..66a4b52b179 100644 --- a/models/git/protected_branch.go +++ b/models/git/protected_branch.go @@ -17,7 +17,6 @@ import ( repo_model "code.gitea.io/gitea/models/repo" "code.gitea.io/gitea/models/unit" user_model "code.gitea.io/gitea/models/user" - "code.gitea.io/gitea/modules/base" "code.gitea.io/gitea/modules/log" "code.gitea.io/gitea/modules/timeutil" "code.gitea.io/gitea/modules/util" @@ -127,7 +126,7 @@ func (protectBranch *ProtectedBranch) CanUserPush(ctx context.Context, user *use return writeAccess } - if base.Int64sContains(protectBranch.WhitelistUserIDs, user.ID) { + if slices.Contains(protectBranch.WhitelistUserIDs, user.ID) { return true } @@ -150,7 +149,7 @@ func IsUserMergeWhitelisted(ctx context.Context, protectBranch *ProtectedBranch, return permissionInRepo.CanWrite(unit.TypeCode) } - if base.Int64sContains(protectBranch.MergeWhitelistUserIDs, userID) { + if slices.Contains(protectBranch.MergeWhitelistUserIDs, userID) { return true } @@ -182,7 +181,7 @@ func IsUserOfficialReviewer(ctx context.Context, protectBranch *ProtectedBranch, return writeAccess, nil } - if base.Int64sContains(protectBranch.ApprovalsWhitelistUserIDs, user.ID) { + if slices.Contains(protectBranch.ApprovalsWhitelistUserIDs, user.ID) { return true, nil } diff --git a/models/git/protected_tag.go b/models/git/protected_tag.go index 12e53a3331e..8a050456512 100644 --- a/models/git/protected_tag.go +++ b/models/git/protected_tag.go @@ -6,11 +6,11 @@ package git import ( "context" "regexp" + "slices" "strings" "code.gitea.io/gitea/models/db" "code.gitea.io/gitea/models/organization" - "code.gitea.io/gitea/modules/base" "code.gitea.io/gitea/modules/timeutil" "github.com/gobwas/glob" @@ -76,7 +76,7 @@ func DeleteProtectedTag(ctx context.Context, pt *ProtectedTag) error { // IsUserAllowedModifyTag returns true if the user is allowed to modify the tag func IsUserAllowedModifyTag(ctx context.Context, pt *ProtectedTag, userID int64) (bool, error) { - if base.Int64sContains(pt.AllowlistUserIDs, userID) { + if slices.Contains(pt.AllowlistUserIDs, userID) { return true, nil } diff --git a/models/issues/review.go b/models/issues/review.go index e06670c9a10..4cbfa4f4435 100644 --- a/models/issues/review.go +++ b/models/issues/review.go @@ -6,6 +6,7 @@ package issues import ( "context" "fmt" + "slices" "strings" "code.gitea.io/gitea/models/db" @@ -15,7 +16,6 @@ import ( access_model "code.gitea.io/gitea/models/perm/access" "code.gitea.io/gitea/models/unit" user_model "code.gitea.io/gitea/models/user" - "code.gitea.io/gitea/modules/base" "code.gitea.io/gitea/modules/structs" "code.gitea.io/gitea/modules/timeutil" "code.gitea.io/gitea/modules/util" @@ -279,7 +279,7 @@ func IsOfficialReviewerTeam(ctx context.Context, issue *Issue, team *organizatio return team.UnitAccessMode(ctx, unit.TypeCode) >= perm.AccessModeWrite, nil } - return base.Int64sContains(pb.ApprovalsWhitelistTeamIDs, team.ID), nil + return slices.Contains(pb.ApprovalsWhitelistTeamIDs, team.ID), nil } // CreateReview creates a new review based on opts diff --git a/modules/base/tool.go b/modules/base/tool.go index 71dcb83fb48..e9f4dfa2794 100644 --- a/modules/base/tool.go +++ b/modules/base/tool.go @@ -4,7 +4,6 @@ package base import ( - "crypto/md5" "crypto/sha1" "encoding/base64" "encoding/hex" @@ -16,7 +15,6 @@ import ( "strconv" "strings" "time" - "unicode" "unicode/utf8" "code.gitea.io/gitea/modules/git" @@ -27,13 +25,6 @@ import ( "github.com/minio/sha256-simd" ) -// EncodeMD5 encodes string to md5 hex value. -func EncodeMD5(str string) string { - m := md5.New() - _, _ = m.Write([]byte(str)) - return hex.EncodeToString(m.Sum(nil)) -} - // EncodeSha1 string to sha1 hex value. func EncodeSha1(str string) string { h := sha1.New() @@ -70,11 +61,6 @@ func BasicAuthDecode(encoded string) (string, string, error) { return auth[0], auth[1], nil } -// BasicAuthEncode encode basic auth string -func BasicAuthEncode(username, password string) string { - return base64.StdEncoding.EncodeToString([]byte(username + ":" + password)) -} - // VerifyTimeLimitCode verify time limit code func VerifyTimeLimitCode(data string, minutes int, code string) bool { if len(code) <= 18 { @@ -184,22 +170,6 @@ func Int64sToStrings(ints []int64) []string { return strs } -// Int64sContains returns if a int64 in a slice of int64 -func Int64sContains(intsSlice []int64, a int64) bool { - for _, c := range intsSlice { - if c == a { - return true - } - } - return false -} - -// IsLetter reports whether the rune is a letter (category L). -// https://github.com/golang/go/blob/c3b4918/src/go/scanner/scanner.go#L342 -func IsLetter(ch rune) bool { - return 'a' <= ch && ch <= 'z' || 'A' <= ch && ch <= 'Z' || ch == '_' || ch >= 0x80 && unicode.IsLetter(ch) -} - // EntryIcon returns the octicon class for displaying files/directories func EntryIcon(entry *git.TreeEntry) string { switch { diff --git a/modules/base/tool_test.go b/modules/base/tool_test.go index 0c3e76704ea..d28deb593d4 100644 --- a/modules/base/tool_test.go +++ b/modules/base/tool_test.go @@ -11,13 +11,6 @@ import ( "github.com/stretchr/testify/assert" ) -func TestEncodeMD5(t *testing.T) { - assert.Equal(t, - "3858f62230ac3c915f300c664312c63f", - EncodeMD5("foobar"), - ) -} - func TestEncodeSha1(t *testing.T) { assert.Equal(t, "8843d7f92416211de9ebb963ff4ce28125932878", @@ -52,11 +45,6 @@ func TestBasicAuthDecode(t *testing.T) { assert.Error(t, err) } -func TestBasicAuthEncode(t *testing.T) { - assert.Equal(t, "Zm9vOmJhcg==", BasicAuthEncode("foo", "bar")) - assert.Equal(t, "MjM6IjotLS0t", BasicAuthEncode("23:\"", "----")) -} - func TestVerifyTimeLimitCode(t *testing.T) { tc := []struct { data string @@ -167,29 +155,6 @@ func TestInt64sToStrings(t *testing.T) { ) } -func TestInt64sContains(t *testing.T) { - assert.True(t, Int64sContains([]int64{6, 44324, 4324, 32, 1, 2323}, 1)) - assert.True(t, Int64sContains([]int64{2323}, 2323)) - assert.False(t, Int64sContains([]int64{6, 44324, 4324, 32, 1, 2323}, 232)) -} - -func TestIsLetter(t *testing.T) { - assert.True(t, IsLetter('a')) - assert.True(t, IsLetter('e')) - assert.True(t, IsLetter('q')) - assert.True(t, IsLetter('z')) - assert.True(t, IsLetter('A')) - assert.True(t, IsLetter('E')) - assert.True(t, IsLetter('Q')) - assert.True(t, IsLetter('Z')) - assert.True(t, IsLetter('_')) - assert.False(t, IsLetter('-')) - assert.False(t, IsLetter('1')) - assert.False(t, IsLetter('$')) - assert.False(t, IsLetter(0x00)) - assert.False(t, IsLetter(0x93)) -} - // TODO: Test EntryIcon func TestSetupGiteaRoot(t *testing.T) { diff --git a/routers/web/user/setting/profile.go b/routers/web/user/setting/profile.go index d8331fef43f..00614565d20 100644 --- a/routers/web/user/setting/profile.go +++ b/routers/web/user/setting/profile.go @@ -14,6 +14,7 @@ import ( "path/filepath" "strings" + "code.gitea.io/gitea/models/avatars" "code.gitea.io/gitea/models/db" "code.gitea.io/gitea/models/organization" repo_model "code.gitea.io/gitea/models/repo" @@ -130,7 +131,7 @@ func UpdateAvatarSetting(ctx *context.Context, form *forms.AvatarForm, ctxUser * ctxUser.UseCustomAvatar = form.Source == forms.AvatarLocal if len(form.Gravatar) > 0 { if form.Avatar != nil { - ctxUser.Avatar = base.EncodeMD5(form.Gravatar) + ctxUser.Avatar = avatars.HashEmail(form.Gravatar) } else { ctxUser.Avatar = "" } From e743570f65b533552337d9606ac1d906ec054127 Mon Sep 17 00:00:00 2001 From: wxiaoguang Date: Thu, 28 Dec 2023 18:09:57 +0800 Subject: [PATCH 039/189] Refactor timeutil package (#28623) 1. make names more readable 2. remove unused FormatLong/FormatShort 3. use `FormatDate` instead of `Format "2006-01-02"` --- models/activities/user_heatmap_test.go | 4 +-- models/asymkey/gpg_key_verify.go | 5 +-- models/issues/comment.go | 6 ++-- models/issues/milestone.go | 2 +- modules/timeutil/timestamp.go | 34 +++++++------------ services/auth/auth_token_test.go | 10 +++--- .../repo/issue/view_content/sidebar.tmpl | 2 +- templates/shared/issuelist.tmpl | 2 +- tests/integration/api_user_heatmap_test.go | 4 +-- 9 files changed, 30 insertions(+), 39 deletions(-) diff --git a/models/activities/user_heatmap_test.go b/models/activities/user_heatmap_test.go index 657f0f043cf..b7babcbde1d 100644 --- a/models/activities/user_heatmap_test.go +++ b/models/activities/user_heatmap_test.go @@ -59,8 +59,8 @@ func TestGetUserHeatmapDataByUser(t *testing.T) { assert.NoError(t, unittest.PrepareTestDatabase()) // Mock time - timeutil.Set(time.Date(2021, 1, 1, 0, 0, 0, 0, time.UTC)) - defer timeutil.Unset() + timeutil.MockSet(time.Date(2021, 1, 1, 0, 0, 0, 0, time.UTC)) + defer timeutil.MockUnset() for _, tc := range testCases { user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: tc.userID}) diff --git a/models/asymkey/gpg_key_verify.go b/models/asymkey/gpg_key_verify.go index be36482c745..98a3e7d390c 100644 --- a/models/asymkey/gpg_key_verify.go +++ b/models/asymkey/gpg_key_verify.go @@ -107,8 +107,9 @@ func VerifyGPGKey(ctx context.Context, ownerID int64, keyID, token, signature st // VerificationToken returns token for the user that will be valid in minutes (time) func VerificationToken(user *user_model.User, minutes int) string { return base.EncodeSha256( - time.Now().Truncate(1*time.Minute).Add(time.Duration(minutes)*time.Minute).Format(time.RFC1123Z) + ":" + - user.CreatedUnix.FormatLong() + ":" + + time.Now().Truncate(1*time.Minute).Add(time.Duration(minutes)*time.Minute).Format( + time.RFC1123Z) + ":" + + user.CreatedUnix.Format(time.RFC1123Z) + ":" + user.Name + ":" + user.Email + ":" + strconv.FormatInt(user.ID, 10)) diff --git a/models/issues/comment.go b/models/issues/comment.go index ba5aed9c652..d92e49a444d 100644 --- a/models/issues/comment.go +++ b/models/issues/comment.go @@ -899,15 +899,15 @@ func createDeadlineComment(ctx context.Context, doer *user_model.User, issue *Is // newDeadline = 0 means deleting if newDeadlineUnix == 0 { commentType = CommentTypeRemovedDeadline - content = issue.DeadlineUnix.Format("2006-01-02") + content = issue.DeadlineUnix.FormatDate() } else if issue.DeadlineUnix == 0 { // Check if the new date was added or modified // If the actual deadline is 0 => deadline added commentType = CommentTypeAddedDeadline - content = newDeadlineUnix.Format("2006-01-02") + content = newDeadlineUnix.FormatDate() } else { // Otherwise modified commentType = CommentTypeModifiedDeadline - content = newDeadlineUnix.Format("2006-01-02") + "|" + issue.DeadlineUnix.Format("2006-01-02") + content = newDeadlineUnix.FormatDate() + "|" + issue.DeadlineUnix.FormatDate() } if err := issue.LoadRepo(ctx); err != nil { diff --git a/models/issues/milestone.go b/models/issues/milestone.go index eb42df8263b..f663d42fe92 100644 --- a/models/issues/milestone.go +++ b/models/issues/milestone.go @@ -86,7 +86,7 @@ func (m *Milestone) AfterLoad() { return } - m.DeadlineString = m.DeadlineUnix.Format("2006-01-02") + m.DeadlineString = m.DeadlineUnix.FormatDate() if m.IsClosed { m.IsOverdue = m.ClosedDateUnix >= m.DeadlineUnix } else { diff --git a/modules/timeutil/timestamp.go b/modules/timeutil/timestamp.go index c60d287faee..27a80b66823 100644 --- a/modules/timeutil/timestamp.go +++ b/modules/timeutil/timestamp.go @@ -13,27 +13,27 @@ import ( type TimeStamp int64 var ( - // mock is NOT concurrency-safe!! - mock time.Time + // mockNow is NOT concurrency-safe!! + mockNow time.Time // Used for IsZero, to check if timestamp is the zero time instant. timeZeroUnix = time.Time{}.Unix() ) -// Set sets the time to a mocked time.Time -func Set(now time.Time) { - mock = now +// MockSet sets the time to a mocked time.Time +func MockSet(now time.Time) { + mockNow = now } -// Unset will unset the mocked time.Time -func Unset() { - mock = time.Time{} +// MockUnset will unset the mocked time.Time +func MockUnset() { + mockNow = time.Time{} } // TimeStampNow returns now int64 func TimeStampNow() TimeStamp { - if !mock.IsZero() { - return TimeStamp(mock.Unix()) + if !mockNow.IsZero() { + return TimeStamp(mockNow.Unix()) } return TimeStamp(time.Now().Unix()) } @@ -89,19 +89,9 @@ func (ts TimeStamp) FormatInLocation(f string, loc *time.Location) string { return ts.AsTimeInLocation(loc).Format(f) } -// FormatLong formats as RFC1123Z -func (ts TimeStamp) FormatLong() string { - return ts.Format(time.RFC1123Z) -} - -// FormatShort formats as short -func (ts TimeStamp) FormatShort() string { - return ts.Format("Jan 02, 2006") -} - -// FormatDate formats a date in YYYY-MM-DD server time zone +// FormatDate formats a date in YYYY-MM-DD func (ts TimeStamp) FormatDate() string { - return time.Unix(int64(ts), 0).String()[:10] + return ts.Format("2006-01-02") } // IsZero is zero time diff --git a/services/auth/auth_token_test.go b/services/auth/auth_token_test.go index 654275df173..23c8d17e597 100644 --- a/services/auth/auth_token_test.go +++ b/services/auth/auth_token_test.go @@ -37,14 +37,14 @@ func TestCheckAuthToken(t *testing.T) { }) t.Run("Expired", func(t *testing.T) { - timeutil.Set(time.Date(2023, 1, 1, 0, 0, 0, 0, time.UTC)) + timeutil.MockSet(time.Date(2023, 1, 1, 0, 0, 0, 0, time.UTC)) at, token, err := CreateAuthTokenForUserID(db.DefaultContext, 2) assert.NoError(t, err) assert.NotNil(t, at) assert.NotEmpty(t, token) - timeutil.Unset() + timeutil.MockUnset() at2, err := CheckAuthToken(db.DefaultContext, at.ID+":"+token) assert.ErrorIs(t, err, ErrAuthTokenExpired) @@ -83,15 +83,15 @@ func TestCheckAuthToken(t *testing.T) { func TestRegenerateAuthToken(t *testing.T) { assert.NoError(t, unittest.PrepareTestDatabase()) - timeutil.Set(time.Date(2023, 1, 1, 0, 0, 0, 0, time.UTC)) - defer timeutil.Unset() + timeutil.MockSet(time.Date(2023, 1, 1, 0, 0, 0, 0, time.UTC)) + defer timeutil.MockUnset() at, token, err := CreateAuthTokenForUserID(db.DefaultContext, 2) assert.NoError(t, err) assert.NotNil(t, at) assert.NotEmpty(t, token) - timeutil.Set(time.Date(2023, 1, 1, 0, 0, 1, 0, time.UTC)) + timeutil.MockSet(time.Date(2023, 1, 1, 0, 0, 1, 0, time.UTC)) at2, token2, err := RegenerateAuthToken(db.DefaultContext, at) assert.NoError(t, err) diff --git a/templates/repo/issue/view_content/sidebar.tmpl b/templates/repo/issue/view_content/sidebar.tmpl index c81cc5c10a6..4334e4bcbdc 100644 --- a/templates/repo/issue/view_content/sidebar.tmpl +++ b/templates/repo/issue/view_content/sidebar.tmpl @@ -392,7 +392,7 @@
{{$.CsrfTokenHtml}} - + {{CountFmt .NumWatches}} @@ -74,7 +75,11 @@ {{$.CsrfTokenHtml}} {{end}} -
- + + {{if $.PullMirror}}
{{ctx.Locale.Tr "repo.mirror_from"}} {{$.PullMirror.RemoteAddress}}
{{end}} + {{if .IsFork}}
{{ctx.Locale.Tr "repo.forked_from"}} {{.BaseRepo.FullName}}
{{end}} + {{if .IsGenerated}}
{{ctx.Locale.Tr "repo.generated_from"}} {{(.TemplateRepo ctx).FullName}}
{{end}} + {{end}} -
+