mirror of
https://github.com/go-gitea/gitea.git
synced 2026-12-05 07:57:02 +00:00
Compare commits
50
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4be850fef8 | ||
|
|
41b3d0d4e3 | ||
|
|
1cadf5338b | ||
|
|
38ce87a77e | ||
|
|
2d84f79e3b | ||
|
|
62e9f747e8 | ||
|
|
93ae5fb35b | ||
|
|
f8c4012ab8 | ||
|
|
a0f0c937c4 | ||
|
|
0b5dfdeeea | ||
|
|
6b5f406f81 | ||
|
|
bf2eb11ec1 | ||
|
|
b0088f060b | ||
|
|
df961a3962 | ||
|
|
58df887de6 | ||
|
|
fff18237d5 | ||
|
|
06a2286930 | ||
|
|
0c6645958b | ||
|
|
660c4b1de6 | ||
|
|
7210b4cc52 | ||
|
|
87c509a405 | ||
|
|
95b69a4a2d | ||
|
|
b60da6d876 | ||
|
|
78698abee0 | ||
|
|
b24cd7839b | ||
|
|
5c69d5710a | ||
|
|
7b466a8a66 | ||
|
|
f9d31d2f11 | ||
|
|
24bceb9f6e | ||
|
|
df01835a83 | ||
|
|
8e5585c5b9 | ||
|
|
7d73ce020e | ||
|
|
f357a03049 | ||
|
|
53cf53cbbc | ||
|
|
ba591d2d5a | ||
|
|
317db14701 | ||
|
|
2f40e966f7 | ||
|
|
88e1e4ccd7 | ||
|
|
e847d6a9c6 | ||
|
|
d0e8294f46 | ||
|
|
b9a99f0f3e | ||
|
|
4f536f1513 | ||
|
|
db5df0494a | ||
|
|
5aea433c71 | ||
|
|
a67b72e57b | ||
|
|
a4cad57174 | ||
|
|
ad8fa1770a | ||
|
|
8fb1547a4c | ||
|
|
fb79898c28 | ||
|
|
96b2997c06 |
No files matched your search
@@ -5,7 +5,7 @@ body:
|
||||
- type: markdown
|
||||
attributes:
|
||||
value: |
|
||||
- **Security issue?** Email security@gitea.io instead of opening a public issue.
|
||||
- **Security issue?** Open a [security advisory](https://github.com/go-gitea/gitea/security/advisories/new) instead of a public issue.
|
||||
- **Need help** with setup or configuration? Ask on [Discord](https://discord.gg/Gitea) or the [forum](https://forum.gitea.com).
|
||||
- Search [existing issues](https://github.com/go-gitea/gitea/issues?q=is%3Aissue) first.
|
||||
- type: input
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
blank_issues_enabled: false
|
||||
contact_links:
|
||||
- name: Security Concern
|
||||
url: https://tinyurl.com/security-gitea
|
||||
about: For security concerns, please send a mail to security@gitea.io instead of opening a public issue.
|
||||
url: https://github.com/go-gitea/gitea/security/advisories/new
|
||||
about: Please report vulnerabilities privately through a GitHub security advisory instead of opening a public issue.
|
||||
- name: Discord Server
|
||||
url: https://discord.gg/Gitea
|
||||
about: Please ask questions and discuss configuration or deployment problems here.
|
||||
|
||||
@@ -4,13 +4,14 @@ on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
- release/v*
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: ${{ github.workflow }}
|
||||
group: ${{ github.workflow }}-${{ github.ref }}
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
@@ -19,8 +20,8 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 30
|
||||
steps:
|
||||
- uses: go-gitea/giteabot@36ea99f821fefa3e8fb26aeac6211735664cd9c0 # v1.3.1
|
||||
- uses: go-gitea/giteabot@15b18fdedd98a80d0968d0bd9db3a9428814b808 # v1.5.1
|
||||
with:
|
||||
github_token: ${{ secrets.GITEABOT_TOKEN }}
|
||||
gitea_fork: giteabot/gitea
|
||||
checks: backport
|
||||
checks: backport,backport_conflict_free
|
||||
@@ -1,16 +1,11 @@
|
||||
name: giteabot
|
||||
|
||||
on:
|
||||
# When main advances, rerun merge queue maintenance so the oldest
|
||||
# reviewed/wait-merge PR can be updated against the new base promptly.
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
# pull_request_target gives this workflow access to GITEABOT_TOKEN on PRs from
|
||||
# forks, which the bot needs to write labels, statuses and comments. Safe here
|
||||
# because the job only runs a pinned action and never checks out PR HEAD.
|
||||
# These PR lifecycle events drive label maintenance, queue maintenance, and
|
||||
# explicit bot actions triggered by relevant label changes.
|
||||
# These PR lifecycle events drive label maintenance, lgtm, and explicit bot
|
||||
# actions triggered by relevant label changes.
|
||||
pull_request_target: # zizmor: ignore[dangerous-triggers]
|
||||
types:
|
||||
- opened
|
||||
@@ -26,8 +21,7 @@ on:
|
||||
- giteabot-review
|
||||
types:
|
||||
- requested
|
||||
# Periodic maintenance is still useful as a backstop for queue cleanup and
|
||||
# other housekeeping, even though main pushes now trigger it promptly.
|
||||
# Daily housekeeping like locks, stale feedback issues, last calls and milestones
|
||||
schedule:
|
||||
- cron: "15 3 * * *"
|
||||
# Allow maintainers to rerun selected checks manually when debugging bot
|
||||
@@ -37,7 +31,7 @@ on:
|
||||
checks:
|
||||
description: Comma-separated list of non-backport checks to run
|
||||
required: false
|
||||
default: backport_branches,labels,merge_queue,lock,feedback,last_call,milestones,lgtm,translation_comment,pr_actions
|
||||
default: backport_branches,backport_conflict_free,labels,lock,feedback,last_call,milestones,lgtm,translation_comment,pr_actions
|
||||
|
||||
permissions: {}
|
||||
|
||||
@@ -56,7 +50,7 @@ jobs:
|
||||
pull-requests: write
|
||||
statuses: write
|
||||
steps:
|
||||
- uses: go-gitea/giteabot@36ea99f821fefa3e8fb26aeac6211735664cd9c0 # v1.3.1
|
||||
- uses: go-gitea/giteabot@15b18fdedd98a80d0968d0bd9db3a9428814b808 # v1.5.1
|
||||
with:
|
||||
github_token: ${{ secrets.GITEABOT_TOKEN }}
|
||||
checks: ${{ github.event.inputs.checks || 'backport_branches,labels,merge_queue,lock,feedback,last_call,milestones,lgtm,translation_comment,pr_actions' }}
|
||||
checks: ${{ github.event.inputs.checks || 'backport_branches,backport_conflict_free,labels,lock,feedback,last_call,milestones,lgtm,translation_comment,pr_actions' }}
|
||||
@@ -0,0 +1,16 @@
|
||||
name: merge-group
|
||||
|
||||
# Reports the required giteabot/lgtm check on merge queue commits. giteabot only sets it
|
||||
# on PR heads, which already passed it before entering the queue.
|
||||
|
||||
on:
|
||||
merge_group:
|
||||
|
||||
permissions: {}
|
||||
|
||||
jobs:
|
||||
lgtm:
|
||||
name: giteabot/lgtm
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- run: "true"
|
||||
@@ -2,6 +2,7 @@ name: compliance
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
merge_group:
|
||||
|
||||
concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.head_ref || github.run_id }}
|
||||
|
||||
@@ -2,6 +2,7 @@ name: db-tests
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
merge_group:
|
||||
|
||||
concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.head_ref || github.run_id }}
|
||||
|
||||
@@ -2,6 +2,7 @@ name: e2e-tests
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
merge_group:
|
||||
|
||||
concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.head_ref || github.run_id }}
|
||||
|
||||
+2
-2
@@ -46,7 +46,7 @@ This document explains how to contribute changes to the Gitea project. Topic-spe
|
||||
## Introduction
|
||||
|
||||
It assumes you have followed the [installation instructions](https://docs.gitea.com/category/installation). \
|
||||
Sensitive security-related issues should be reported to [security@gitea.io](mailto:security@gitea.io).
|
||||
Sensitive security-related issues should be reported through a [GitHub security advisory](https://github.com/go-gitea/gitea/security/advisories/new), see the [security policy](SECURITY.md).
|
||||
|
||||
For configuring IDEs for Gitea development, see the [IDE setup notes](docs/development.md#ide-configuration) and the [contributed configurations](contrib/development/).
|
||||
|
||||
@@ -85,7 +85,7 @@ Please be kind—remember that Gitea comes at no cost to you, and you're getting
|
||||
Typically, issues fall in one of the following categories:
|
||||
|
||||
- `bug`: Something in the frontend or backend behaves unexpectedly
|
||||
- `security issue`: bug that has serious implications such as leaking another users data. Please do not file such issues on the public tracker and send a mail to security@gitea.io instead
|
||||
- `security issue`: bug that has serious implications such as leaking another users data. Please do not file such issues on the public tracker and open a [GitHub security advisory](https://github.com/go-gitea/gitea/security/advisories/new) instead
|
||||
- `feature`: Completely new functionality. You should describe this feature in enough detail that anyone who reads the issue can understand how it is supposed to be implemented
|
||||
- `enhancement`: An existing feature should get an upgrade
|
||||
- `refactoring`: Parts of the code base don't conform with other parts and should be changed to improve Gitea's maintainability
|
||||
|
||||
+1
-1
@@ -48,7 +48,7 @@ FROM docker.io/library/alpine:3.24 AS gitea
|
||||
|
||||
EXPOSE 22 3000
|
||||
|
||||
RUN apk --no-cache add \
|
||||
RUN apk --no-cache upgrade && apk --no-cache add \
|
||||
bash \
|
||||
ca-certificates \
|
||||
curl \
|
||||
|
||||
+1
-1
@@ -43,7 +43,7 @@ FROM docker.io/library/alpine:3.24 AS gitea-rootless
|
||||
|
||||
EXPOSE 2222 3000
|
||||
|
||||
RUN apk --no-cache add \
|
||||
RUN apk --no-cache upgrade && apk --no-cache add \
|
||||
bash \
|
||||
ca-certificates \
|
||||
dumb-init \
|
||||
|
||||
@@ -54,7 +54,7 @@ Expected workflow is: Fork -> Patch -> Push -> Pull Request
|
||||
>
|
||||
> 1. **YOU MUST READ THE [CONTRIBUTORS GUIDE](CONTRIBUTING.md) BEFORE STARTING TO WORK ON A PULL REQUEST.**
|
||||
> 2. New to the codebase? The [development guide](docs/development.md) walks through setting up a local environment and building from source.
|
||||
> 3. If you have found a vulnerability in the project, please write privately to **security@gitea.io**. Thanks!
|
||||
> 3. If you have found a vulnerability in the project, please report it privately through a [GitHub security advisory](https://github.com/go-gitea/gitea/security/advisories/new), see the [security policy](SECURITY.md). Thanks!
|
||||
|
||||
## Translating
|
||||
|
||||
|
||||
+1
-1
@@ -62,7 +62,7 @@
|
||||
> [!注意]
|
||||
>
|
||||
> 1. **在开始进行 Pull Request 之前,您必须阅读 [贡献者指南](CONTRIBUTING.md)。**
|
||||
> 2. 如果您在项目中发现了漏洞,请私下写信给 **security@gitea.io**。谢谢!
|
||||
> 2. 如果您在项目中发现了漏洞,请通过 [GitHub 安全公告](https://github.com/go-gitea/gitea/security/advisories/new) 私下报告,详见[安全策略](SECURITY.md)。谢谢!
|
||||
|
||||
## 翻译
|
||||
|
||||
|
||||
+1
-1
@@ -62,7 +62,7 @@
|
||||
> [!注意]
|
||||
>
|
||||
> 1. **在開始進行 Pull Request 之前,您必須閱讀 [貢獻者指南](CONTRIBUTING.md)。**
|
||||
> 2. 如果您在項目中發現了漏洞,請私下寫信給 **security@gitea.io**。謝謝!
|
||||
> 2. 如果您在項目中發現了漏洞,請透過 [GitHub 安全公告](https://github.com/go-gitea/gitea/security/advisories/new) 私下回報,詳見[安全政策](SECURITY.md)。謝謝!
|
||||
|
||||
## 翻譯
|
||||
|
||||
|
||||
+4
-3
@@ -14,15 +14,16 @@ Reports must be filed against a supported version. Before reporting, verify that
|
||||
|
||||
## Reporting a Vulnerability
|
||||
|
||||
Please **DO NOT** file a public issue. Instead, report the vulnerability privately by opening a [GitHub security advisory](https://github.com/go-gitea/gitea/security/advisories/new), or optionally by sending your report to `security@gitea.io`.
|
||||
If reporting via GitHub, open an advisory per found issue. You can group the found issues if they relate to a single area (same feature, same fault present in multiple routes) but do not group unrelated reports into one as it makes it much harder to assess and track for duplicates.
|
||||
Please **DO NOT** file a public issue. Instead, report the vulnerability privately by opening a [GitHub security advisory](https://github.com/go-gitea/gitea/security/advisories/new).
|
||||
Due to the high volume of reports, we can no longer handle submissions by mail: reports sent by mail are not accepted and will not be processed. `security@gitea.io` is only for security matters that are not vulnerability reports, such as questions about this policy or coordinating the disclosure of an existing advisory.
|
||||
Open an advisory per found issue. You can group the found issues if they relate to a single area (same feature, same fault present in multiple routes) but do not group unrelated reports into one as it makes it much harder to assess and track for duplicates.
|
||||
Do not use LLM to write the reports. It's meant for people to read so take your time and use your own words to write it. If you have used LLM to find the bug, be transparent about it and verify that it is not hallucination before submitting the report.
|
||||
|
||||
If your report turns out to be a duplicate, you will be credited in the original report.
|
||||
|
||||
## Protecting Security Information
|
||||
|
||||
Due to the sensitive nature of security information, you can use the below GPG public key to encrypt your mail body.
|
||||
Vulnerability details belong in the GitHub security advisory, not in a mail. If you need to send other sensitive information to `security@gitea.io`, you can use the below GPG public key to encrypt your mail body.
|
||||
|
||||
The PGP key is valid until July 23, 2027.
|
||||
|
||||
|
||||
Generated
-10
@@ -119,11 +119,6 @@
|
||||
"path": "github.com/andybalholm/brotli/LICENSE",
|
||||
"licenseText": "Copyright (c) 2009, 2010, 2013-2016 by the Brotli Authors.\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n"
|
||||
},
|
||||
{
|
||||
"name": "github.com/andybalholm/brotli/flate",
|
||||
"path": "github.com/andybalholm/brotli/flate/LICENSE",
|
||||
"licenseText": "Copyright (c) 2009 The Go Authors. All rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are\nmet:\n\n * Redistributions of source code must retain the above copyright\nnotice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above\ncopyright notice, this list of conditions and the following disclaimer\nin the documentation and/or other materials provided with the\ndistribution.\n * Neither the name of Google Inc. nor the names of its\ncontributors may be used to endorse or promote products derived from\nthis software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\nLIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\nA PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\nOWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\nSPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\nLIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\nDATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\nTHEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n"
|
||||
},
|
||||
{
|
||||
"name": "github.com/andybalholm/cascadia",
|
||||
"path": "github.com/andybalholm/cascadia/LICENSE",
|
||||
@@ -144,11 +139,6 @@
|
||||
"path": "github.com/bits-and-blooms/bitset/LICENSE",
|
||||
"licenseText": "Copyright (c) 2014 the bitset authors. All rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are\nmet:\n\n * Redistributions of source code must retain the above copyright\nnotice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above\ncopyright notice, this list of conditions and the following disclaimer\nin the documentation and/or other materials provided with the\ndistribution.\n * Neither the name of Google Inc. nor the names of its\ncontributors may be used to endorse or promote products derived from\nthis software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\nLIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\nA PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\nOWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\nSPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\nLIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\nDATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\nTHEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n"
|
||||
},
|
||||
{
|
||||
"name": "github.com/blakesmith/ar",
|
||||
"path": "github.com/blakesmith/ar/COPYING",
|
||||
"licenseText": "Copyright (c) 2013 Blake Smith \u003cblakesmith0@gmail.com\u003e\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n\n"
|
||||
},
|
||||
{
|
||||
"name": "github.com/blevesearch/bleve/v2",
|
||||
"path": "github.com/blevesearch/bleve/v2/LICENSE",
|
||||
|
||||
@@ -74,15 +74,13 @@ Changes to Gitea must be reviewed before they are accepted, including changes fr
|
||||
|
||||
We require two maintainer approvals for every PR. When that is satisfied, your PR gets the `lgtm/done` label. After that, you mainly fix merge conflicts and respond to or implement maintainer requests; maintainers drive getting the PR merged.
|
||||
|
||||
If a PR has `lgtm/done`, no open discussions, and no merge conflicts, any maintainer may add `reviewed/wait-merge`. That puts the PR in the merge queue. PRs are merged from the queue in the order of this list:
|
||||
If a PR has `lgtm/done`, no open discussions, and no merge conflicts, a merger rewrites its title and description into the final [commit message](#commit-messages) and clicks **Merge when ready**. That adds the PR to the [merge queue](https://github.com/go-gitea/gitea/queue/main), which tests it on top of the latest `main` and the PRs ahead of it, and merges it once CI passes. Edits to the title and description no longer reach the commit once the queue starts building the PR, so make them before queueing.
|
||||
|
||||
<https://github.com/go-gitea/gitea/pulls?q=is%3Apr+label%3Areviewed%2Fwait-merge+sort%3Acreated-asc+is%3Aopen>
|
||||
|
||||
Gitea uses its own tool, <https://github.com/go-gitea/gitea/blob/main/.github/workflows/giteabot.yml>, to automate parts of the review process. The backporter:
|
||||
Gitea uses its own tool, <https://github.com/go-gitea/gitea/blob/main/.github/workflows/giteabot.yml>, to automate parts of the review process. It:
|
||||
|
||||
- Counts maintainer approvals and sets the `lgtm/*` labels and the `giteabot/lgtm` status.
|
||||
- Takes a PR out of the merge queue when it loses its approval.
|
||||
- Creates a backport PR when needed after the initial PR merges.
|
||||
- Removes the PR from the merge queue after it merges.
|
||||
- Keeps the oldest branch in the merge queue up to date with merges.
|
||||
|
||||
### Final call
|
||||
|
||||
@@ -164,7 +162,7 @@ Any account with write access (including bots and TOC members) **must** use [2FA
|
||||
|
||||
Mergers are the maintainers who carry out the final merge of approved PRs. Their responsibilities, described throughout this guide, are:
|
||||
|
||||
- Merging PRs from the [merge queue](#getting-prs-merged) in order, once a PR has `lgtm/done`, no open discussions, and no merge conflicts.
|
||||
- Adding PRs to the [merge queue](#getting-prs-merged) once a PR has `lgtm/done`, no open discussions, and no merge conflicts.
|
||||
- Rewriting the PR title and description prior to the merge, making the [commit message](#commit-messages) clear.\
|
||||
In particular, mergers should edit the PR description.\
|
||||
Mergers should **not** edit the actual commit message except to remove unnecessary information. Because of that, even if users are looking at the PR, they can understand what changed.
|
||||
|
||||
@@ -24,6 +24,8 @@ Now, that's not a requirement anymore as our [backport bot](https://github.com/G
|
||||
|
||||
The `backport/manual` label signifies either that you want to backport the change yourself, or that there were conflicts when backporting, thus you **must** do it yourself.
|
||||
|
||||
The bot labels open PRs targeting `main` that have a `backport/<version>` label with `backport/conflict-free` when they would cherry-pick onto the latest release branch without conflicts.
|
||||
|
||||
### Format of backport PRs
|
||||
|
||||
The title of backport PRs should be
|
||||
|
||||
@@ -2,7 +2,7 @@ module gitea.dev
|
||||
|
||||
go 1.27
|
||||
|
||||
toolchain go1.27.3
|
||||
toolchain go1.27.4
|
||||
|
||||
require (
|
||||
connectrpc.com/connect v1.21.0
|
||||
@@ -11,7 +11,7 @@ require (
|
||||
gitea.com/go-chi/captcha v0.0.0-20240315150714-fb487f629098
|
||||
gitea.com/go-chi/session v0.0.0-20260708011333-ebced8a7a2d6
|
||||
gitea.com/lunny/dingtalk_webhook v0.0.0-20171025031554-e3534c89ef96
|
||||
gitea.com/lunny/levelqueue v0.4.2-0.20230414023320-3c0159fe0fe4
|
||||
gitea.com/lunny/levelqueue v0.5.1
|
||||
gitea.dev/actionslib v1.2.1
|
||||
gitea.dev/sdk v1.3.0
|
||||
github.com/42wim/httpsig v1.2.4
|
||||
@@ -22,7 +22,6 @@ require (
|
||||
github.com/PuerkitoBio/goquery v1.13.0
|
||||
github.com/SaveTheRbtz/zstd-seekable-format-go/pkg v0.10.0
|
||||
github.com/alecthomas/chroma/v2 v2.27.0
|
||||
github.com/blakesmith/ar v0.0.0-20190502131153-809d4375e1fb
|
||||
github.com/blevesearch/bleve/v2 v2.6.1
|
||||
github.com/bohde/codel v0.2.0
|
||||
github.com/buildkite/terminal-to-html/v3 v3.17.1
|
||||
@@ -120,7 +119,7 @@ require (
|
||||
github.com/Microsoft/go-winio v0.6.2 // indirect
|
||||
github.com/RoaringBitmap/roaring/v2 v2.18.2 // indirect
|
||||
github.com/STARRY-S/zip v0.2.3 // indirect
|
||||
github.com/andybalholm/brotli v1.2.1 // indirect
|
||||
github.com/andybalholm/brotli v1.2.7 // indirect
|
||||
github.com/andybalholm/cascadia v1.3.4 // indirect
|
||||
github.com/aymerick/douceur v0.2.0 // indirect
|
||||
github.com/beorn7/perks v1.0.1 // indirect
|
||||
|
||||
@@ -18,8 +18,8 @@ gitea.com/go-chi/session v0.0.0-20260708011333-ebced8a7a2d6 h1:YWzVGeC/8SZThrJS4
|
||||
gitea.com/go-chi/session v0.0.0-20260708011333-ebced8a7a2d6/go.mod h1:KDvcfMUoXfATPHs2mbMoXFTXT45/FAFAS39waz9tPk0=
|
||||
gitea.com/lunny/dingtalk_webhook v0.0.0-20171025031554-e3534c89ef96 h1:+wWBi6Qfruqu7xJgjOIrKVQGiLUZdpKYCZewJ4clqhw=
|
||||
gitea.com/lunny/dingtalk_webhook v0.0.0-20171025031554-e3534c89ef96/go.mod h1:VyMQP6ue6MKHM8UsOXfNfuMKD0oSAWZdXVcpHIN2yaY=
|
||||
gitea.com/lunny/levelqueue v0.4.2-0.20230414023320-3c0159fe0fe4 h1:IFT+hup2xejHqdhS7keYWioqfmxdnfblFDTGoOwcZ+o=
|
||||
gitea.com/lunny/levelqueue v0.4.2-0.20230414023320-3c0159fe0fe4/go.mod h1:HBqmLbz56JWpfEGG0prskAV97ATNRoj5LDmPicD22hU=
|
||||
gitea.com/lunny/levelqueue v0.5.1 h1:15q1oBWaO2Aw9t3rDthQSTX+vBNgjYNkCgRJgES9gA8=
|
||||
gitea.com/lunny/levelqueue v0.5.1/go.mod h1:HBqmLbz56JWpfEGG0prskAV97ATNRoj5LDmPicD22hU=
|
||||
gitea.com/xorm/sqlfiddle v0.0.0-20180821085327-62ce714f951a h1:lSA0F4e9A2NcQSqGqTOXqu2aRi/XEQxDCBwM8yJtE6s=
|
||||
gitea.com/xorm/sqlfiddle v0.0.0-20180821085327-62ce714f951a/go.mod h1:EXuID2Zs0pAQhH8yz+DNjUbjppKQzKFAn28TMYPB6IU=
|
||||
gitea.dev/actionslib v1.2.1 h1:GL//K/0zIZV6h1OOksv1awvFVg0rg7fug2xWcG7mkG0=
|
||||
@@ -71,8 +71,8 @@ github.com/alecthomas/repr v0.5.2 h1:SU73FTI9D1P5UNtvseffFSGmdNci/O6RsqzeXJtP0Qs
|
||||
github.com/alecthomas/repr v0.5.2/go.mod h1:Fr0507jx4eOXV7AlPV6AVZLYrLIuIeSOWtW57eE/O/4=
|
||||
github.com/alexbrainman/sspi v0.0.0-20250919150558-7d374ff0d59e h1:4dAU9FXIyQktpoUAgOJK3OTFc/xug0PCXYCqU0FgDKI=
|
||||
github.com/alexbrainman/sspi v0.0.0-20250919150558-7d374ff0d59e/go.mod h1:cEWa1LVoE5KvSD9ONXsZrj0z6KqySlCCNKHlLzbqAt4=
|
||||
github.com/andybalholm/brotli v1.2.1 h1:R+f5xP285VArJDRgowrfb9DqL18yVK0gKAW/F+eTWro=
|
||||
github.com/andybalholm/brotli v1.2.1/go.mod h1:rzTDkvFWvIrjDXZHkuS16NPggd91W3kUSvPlQ1pLaKY=
|
||||
github.com/andybalholm/brotli v1.2.7 h1:UgafRPGMam5ySHfRkhthMqOFA6IFoeF3D7mWIDLjG5A=
|
||||
github.com/andybalholm/brotli v1.2.7/go.mod h1:rzTDkvFWvIrjDXZHkuS16NPggd91W3kUSvPlQ1pLaKY=
|
||||
github.com/andybalholm/cascadia v1.3.4 h1:vM2lgh0Vru9Vwyfm4cQqWP2HHMW0u0+2PAW7Q38Qufg=
|
||||
github.com/andybalholm/cascadia v1.3.4/go.mod h1:BLRmbRjpEtNKieZOCCvYj4RqN+KRA41GBe/5O+G93kM=
|
||||
github.com/anmitsu/go-shlex v0.0.0-20200514113438-38f4b401e2be h1:9AeTilPcZAjCFIImctFaOjnTIavg87rW78vTPkQqLI8=
|
||||
@@ -85,8 +85,6 @@ github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM=
|
||||
github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw=
|
||||
github.com/bits-and-blooms/bitset v1.24.5 h1:654xBVHc23gJMAgOTkPNoCVfiRxuIOAUnAZFtopqJ4w=
|
||||
github.com/bits-and-blooms/bitset v1.24.5/go.mod h1:7hO7Gc7Pp1vODcmWvKMRA9BNmbv6a/7QIWpPxHddWR8=
|
||||
github.com/blakesmith/ar v0.0.0-20190502131153-809d4375e1fb h1:m935MPodAbYS46DG4pJSv7WO+VECIWUQ7OJYSoTrMh4=
|
||||
github.com/blakesmith/ar v0.0.0-20190502131153-809d4375e1fb/go.mod h1:PkYb9DJNAwrSvRx5DYA+gUcOIgTGVMNkfSCbZM8cWpI=
|
||||
github.com/blevesearch/bleve/v2 v2.6.1 h1:47vLskRTqxvQEtxVPYHjf5KpOgzD2msslXFjvUQCgWQ=
|
||||
github.com/blevesearch/bleve/v2 v2.6.1/go.mod h1:Dvvx6ZoEBTOj6RSzfk0lEz0wce/qhe2yOUubXeuzd2c=
|
||||
github.com/blevesearch/bleve_index_api v1.4.1 h1:CYIyecFlI+/RYjzUm+NmDjYbSvk870Bb7f+Vl4b12q8=
|
||||
|
||||
@@ -65,26 +65,22 @@ func (opts FindScopedWorkflowSourceOpts) ToConds() builder.Cond {
|
||||
if opts.SourceRepoID != 0 {
|
||||
cond = cond.And(builder.Eq{"source_repo_id": opts.SourceRepoID})
|
||||
}
|
||||
return cond
|
||||
return cond.And(scopedWorkflowSourceOwnedCond())
|
||||
}
|
||||
|
||||
func scopedWorkflowSourceOwnedCond() builder.Cond {
|
||||
return builder.Eq{"owner_id": 0}.Or(builder.Expr("EXISTS (SELECT 1 FROM repository WHERE repository.id = action_scoped_workflow_source.source_repo_id AND repository.owner_id = action_scoped_workflow_source.owner_id)"))
|
||||
}
|
||||
|
||||
// GetEffectiveScopedWorkflowSources returns the scoped-workflow sources effective for a repo owned by repoOwnerID:
|
||||
// the owner's own sources plus instance-level (owner_id=0) sources.
|
||||
func GetEffectiveScopedWorkflowSources(ctx context.Context, repoOwnerID int64) ([]*ActionScopedWorkflowSource, error) {
|
||||
owners := []int64{0}
|
||||
if repoOwnerID != 0 {
|
||||
owners = append(owners, repoOwnerID)
|
||||
}
|
||||
return db.Find[ActionScopedWorkflowSource](ctx, FindScopedWorkflowSourceOpts{OwnerIDs: owners})
|
||||
return db.Find[ActionScopedWorkflowSource](ctx, FindScopedWorkflowSourceOpts{OwnerIDs: []int64{0, repoOwnerID}})
|
||||
}
|
||||
|
||||
// IsScopedWorkflowSourceEffective reports whether sourceRepoID is a scoped-workflow source effective for a repo owned by repoOwnerID.
|
||||
func IsScopedWorkflowSourceEffective(ctx context.Context, repoOwnerID, sourceRepoID int64) (bool, error) {
|
||||
owners := []int64{0}
|
||||
if repoOwnerID != 0 {
|
||||
owners = append(owners, repoOwnerID)
|
||||
}
|
||||
return db.Exist[ActionScopedWorkflowSource](ctx, FindScopedWorkflowSourceOpts{OwnerIDs: owners, SourceRepoID: sourceRepoID}.ToConds())
|
||||
return db.Exist[ActionScopedWorkflowSource](ctx, FindScopedWorkflowSourceOpts{OwnerIDs: []int64{0, repoOwnerID}, SourceRepoID: sourceRepoID}.ToConds())
|
||||
}
|
||||
|
||||
// IsWorkflowRequiredInSources reports whether workflowID from sourceRepoID is required by any of the given sources.
|
||||
@@ -138,12 +134,10 @@ func GetScopedWorkflowSourcesByOwner(ctx context.Context, ownerID int64) ([]*Act
|
||||
|
||||
// GetScopedWorkflowSource returns the (owner, repo) source registration or a NotExist error.
|
||||
func GetScopedWorkflowSource(ctx context.Context, ownerID, repoID int64) (*ActionScopedWorkflowSource, error) {
|
||||
src := &ActionScopedWorkflowSource{}
|
||||
has, err := db.GetEngine(ctx).Where("owner_id = ? AND source_repo_id = ?", ownerID, repoID).Get(src)
|
||||
src, has, err := db.Get[ActionScopedWorkflowSource](ctx, builder.Eq{"owner_id": ownerID, "source_repo_id": repoID}.And(scopedWorkflowSourceOwnedCond()))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !has {
|
||||
} else if !has {
|
||||
return nil, util.NewNotExistErrorf("scoped workflow source (owner %d, repo %d) does not exist", ownerID, repoID)
|
||||
}
|
||||
return src, nil
|
||||
@@ -181,3 +175,9 @@ func RemoveScopedWorkflowSource(ctx context.Context, ownerID, repoID int64) erro
|
||||
_, err := db.GetEngine(ctx).Where("owner_id = ? AND source_repo_id = ?", ownerID, repoID).Delete(new(ActionScopedWorkflowSource))
|
||||
return err
|
||||
}
|
||||
|
||||
// RemoveOwnerScopedWorkflowSources removes every owner-level registration of repoID, as only its current owner may hold one.
|
||||
func RemoveOwnerScopedWorkflowSources(ctx context.Context, repoID int64) error {
|
||||
_, err := db.GetEngine(ctx).Where("owner_id <> 0 AND source_repo_id = ?", repoID).Delete(new(ActionScopedWorkflowSource))
|
||||
return err
|
||||
}
|
||||
@@ -48,26 +48,28 @@ func TestGetEffectiveScopedWorkflowSources(t *testing.T) {
|
||||
require.NoError(t, unittest.PrepareTestDatabase())
|
||||
ctx := t.Context()
|
||||
|
||||
rows := []*ActionScopedWorkflowSource{
|
||||
{OwnerID: 2, SourceRepoID: 100, WorkflowConfigs: nil}, // org 2 registers repo 100 (optional)
|
||||
{OwnerID: 0, SourceRepoID: 100, WorkflowConfigs: map[string]*ScopedWorkflowConfig{"a.yml": {Required: true, Patterns: []string{"p"}}}}, // instance also registers repo 100 (required)
|
||||
{OwnerID: 0, SourceRepoID: 200, WorkflowConfigs: map[string]*ScopedWorkflowConfig{"b.yml": {Required: true, Patterns: []string{"p"}}}}, // instance source 200
|
||||
{OwnerID: 3, SourceRepoID: 300, WorkflowConfigs: map[string]*ScopedWorkflowConfig{"c.yml": {Required: true, Patterns: []string{"p"}}}}, // a different owner's source
|
||||
}
|
||||
for _, r := range rows {
|
||||
require.NoError(t, db.Insert(ctx, r))
|
||||
for _, source := range []*ActionScopedWorkflowSource{
|
||||
{OwnerID: 2, SourceRepoID: 1},
|
||||
{OwnerID: 0, SourceRepoID: 1, WorkflowConfigs: map[string]*ScopedWorkflowConfig{"a.yml": {Required: true}}},
|
||||
{OwnerID: 0, SourceRepoID: 200, WorkflowConfigs: map[string]*ScopedWorkflowConfig{"b.yml": {Required: true}}},
|
||||
{OwnerID: 3, SourceRepoID: 3, WorkflowConfigs: map[string]*ScopedWorkflowConfig{"c.yml": {Required: true}}},
|
||||
{OwnerID: 2, SourceRepoID: 3, WorkflowConfigs: map[string]*ScopedWorkflowConfig{"c.yml": {Required: true}}},
|
||||
} {
|
||||
require.NoError(t, db.Insert(ctx, source))
|
||||
}
|
||||
|
||||
// owner 2 sees its own sources plus instance-level ones, but not owner 3's.
|
||||
owner2, err := GetEffectiveScopedWorkflowSources(ctx, 2)
|
||||
require.NoError(t, err)
|
||||
assert.Len(t, owner2, 3)
|
||||
_, err = GetScopedWorkflowSource(ctx, 2, 3)
|
||||
assert.ErrorIs(t, err, util.ErrNotExist)
|
||||
|
||||
required, err := IsScopedWorkflowRequired(ctx, 2, 100, "a.yml")
|
||||
required, err := IsScopedWorkflowRequired(ctx, 2, 1, "a.yml")
|
||||
require.NoError(t, err)
|
||||
assert.True(t, required, "instance marks a.yml required → required for owner 2 even though org left it optional")
|
||||
|
||||
required, err = IsScopedWorkflowRequired(ctx, 2, 100, "x.yml")
|
||||
required, err = IsScopedWorkflowRequired(ctx, 2, 1, "x.yml")
|
||||
require.NoError(t, err)
|
||||
assert.False(t, required)
|
||||
|
||||
@@ -76,12 +78,12 @@ func TestGetEffectiveScopedWorkflowSources(t *testing.T) {
|
||||
assert.True(t, required)
|
||||
|
||||
// owner 3's source must not be effective for owner 2.
|
||||
required, err = IsScopedWorkflowRequired(ctx, 2, 300, "c.yml")
|
||||
required, err = IsScopedWorkflowRequired(ctx, 2, 3, "c.yml")
|
||||
require.NoError(t, err)
|
||||
assert.False(t, required)
|
||||
|
||||
// IsScopedWorkflowSourceEffective: owner-level and instance-level sources are effective; another owner's is not.
|
||||
effective, err := IsScopedWorkflowSourceEffective(ctx, 2, 100)
|
||||
effective, err := IsScopedWorkflowSourceEffective(ctx, 2, 1)
|
||||
require.NoError(t, err)
|
||||
assert.True(t, effective, "owner 2's own source")
|
||||
|
||||
@@ -89,7 +91,7 @@ func TestGetEffectiveScopedWorkflowSources(t *testing.T) {
|
||||
require.NoError(t, err)
|
||||
assert.True(t, effective, "instance-level source is effective for any owner")
|
||||
|
||||
effective, err = IsScopedWorkflowSourceEffective(ctx, 2, 300)
|
||||
effective, err = IsScopedWorkflowSourceEffective(ctx, 2, 3)
|
||||
require.NoError(t, err)
|
||||
assert.False(t, effective, "owner 3's source is not effective for owner 2")
|
||||
|
||||
@@ -97,7 +99,7 @@ func TestGetEffectiveScopedWorkflowSources(t *testing.T) {
|
||||
require.NoError(t, err)
|
||||
assert.False(t, effective, "unknown source repo")
|
||||
|
||||
effective, err = IsScopedWorkflowSourceEffective(ctx, 3, 300)
|
||||
effective, err = IsScopedWorkflowSourceEffective(ctx, 3, 3)
|
||||
require.NoError(t, err)
|
||||
assert.True(t, effective, "owner 3's own source is effective for owner 3")
|
||||
}
|
||||
@@ -107,8 +109,8 @@ func TestScopedWorkflowSourceCRUD(t *testing.T) {
|
||||
ctx := t.Context()
|
||||
|
||||
// add is idempotent
|
||||
require.NoError(t, AddScopedWorkflowSource(ctx, 5, 10))
|
||||
require.NoError(t, AddScopedWorkflowSource(ctx, 5, 10))
|
||||
require.NoError(t, AddScopedWorkflowSource(ctx, 5, 4))
|
||||
require.NoError(t, AddScopedWorkflowSource(ctx, 5, 4))
|
||||
sources, err := GetScopedWorkflowSourcesByOwner(ctx, 5)
|
||||
require.NoError(t, err)
|
||||
assert.Len(t, sources, 1)
|
||||
@@ -118,20 +120,20 @@ func TestScopedWorkflowSourceCRUD(t *testing.T) {
|
||||
"a.yml": {Required: true, Patterns: []string{"src: a.yml / *"}},
|
||||
"b.yml": {Required: false, Patterns: []string{"src: b.yml / build (push)"}},
|
||||
}
|
||||
require.NoError(t, SetScopedWorkflowSourceConfigs(ctx, 5, 10, configs))
|
||||
src, err := GetScopedWorkflowSource(ctx, 5, 10)
|
||||
require.NoError(t, SetScopedWorkflowSourceConfigs(ctx, 5, 4, configs))
|
||||
src, err := GetScopedWorkflowSource(ctx, 5, 4)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, configs, src.WorkflowConfigs)
|
||||
|
||||
// clearing the configs works
|
||||
require.NoError(t, SetScopedWorkflowSourceConfigs(ctx, 5, 10, nil))
|
||||
src, err = GetScopedWorkflowSource(ctx, 5, 10)
|
||||
require.NoError(t, SetScopedWorkflowSourceConfigs(ctx, 5, 4, nil))
|
||||
src, err = GetScopedWorkflowSource(ctx, 5, 4)
|
||||
require.NoError(t, err)
|
||||
assert.Empty(t, src.WorkflowConfigs)
|
||||
|
||||
// remove
|
||||
require.NoError(t, RemoveScopedWorkflowSource(ctx, 5, 10))
|
||||
_, err = GetScopedWorkflowSource(ctx, 5, 10)
|
||||
require.NoError(t, RemoveScopedWorkflowSource(ctx, 5, 4))
|
||||
_, err = GetScopedWorkflowSource(ctx, 5, 4)
|
||||
assert.ErrorIs(t, err, util.ErrNotExist)
|
||||
sources, err = GetScopedWorkflowSourcesByOwner(ctx, 5)
|
||||
require.NoError(t, err)
|
||||
|
||||
@@ -180,15 +180,14 @@ func updateIssueNotification(ctx context.Context, userID, issueID, commentID, up
|
||||
}
|
||||
|
||||
// NOTICE: Only update comment id when the before notification on this issue is read, otherwise you may miss some old comments.
|
||||
// But we need update update_by so that the notification will be reorder
|
||||
var cols []string
|
||||
// Always update so that updated_unix moves the notification to the top of the list
|
||||
// Actually, it's unclear what UpdatedBy is used for, or maybe not used at all, or maybe it should just be dropped.
|
||||
notification.UpdatedBy = updatedByID
|
||||
cols := []string{"updated_by"}
|
||||
if notification.Status == NotificationStatusRead {
|
||||
notification.Status = NotificationStatusUnread
|
||||
notification.CommentID = commentID
|
||||
cols = []string{"status", "update_by", "comment_id"}
|
||||
} else {
|
||||
notification.UpdatedBy = updatedByID
|
||||
cols = []string{"update_by"}
|
||||
cols = append(cols, "status", "comment_id")
|
||||
}
|
||||
|
||||
_, err = db.GetEngine(ctx).ID(notification.ID).Cols(cols...).Update(notification)
|
||||
|
||||
@@ -71,16 +71,6 @@ func (opts FindNotificationOptions) ToOrders() string {
|
||||
// receiverID > 0 just send to receiver, else send to all watcher
|
||||
// Returns the set of user IDs whose notification rows were created or updated.
|
||||
func CreateOrUpdateIssueNotifications(ctx context.Context, issueID, commentID, notificationAuthorID, receiverID int64) ([]int64, error) {
|
||||
var notifiedIDs []int64
|
||||
err := db.WithTx(ctx, func(ctx context.Context) error {
|
||||
var innerErr error
|
||||
notifiedIDs, innerErr = createOrUpdateIssueNotifications(ctx, issueID, commentID, notificationAuthorID, receiverID)
|
||||
return innerErr
|
||||
})
|
||||
return notifiedIDs, err
|
||||
}
|
||||
|
||||
func createOrUpdateIssueNotifications(ctx context.Context, issueID, commentID, notificationAuthorID, receiverID int64) ([]int64, error) {
|
||||
// init
|
||||
var toNotify container.Set[int64]
|
||||
notifications, err := db.Find[Notification](ctx, FindNotificationOptions{
|
||||
@@ -181,7 +171,11 @@ func createOrUpdateIssueNotifications(ctx context.Context, issueID, commentID, n
|
||||
if notificationExists(notifications, issue.ID, userID) {
|
||||
err = updateIssueNotification(ctx, userID, issue.ID, commentID, notificationAuthorID)
|
||||
} else {
|
||||
err = createIssueNotification(ctx, userID, issue, commentID, notificationAuthorID)
|
||||
if err = createIssueNotification(ctx, userID, issue, commentID, notificationAuthorID); err != nil {
|
||||
if errUpdate := updateIssueNotification(ctx, userID, issue.ID, commentID, notificationAuthorID); errUpdate == nil {
|
||||
err = nil
|
||||
}
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
|
||||
@@ -31,6 +31,18 @@ func TestCreateOrUpdateIssueNotifications(t *testing.T) {
|
||||
|
||||
notf = unittest.AssertExistsAndLoadBean(t, &activities_model.Notification{UserID: 4, IssueID: issue.ID})
|
||||
assert.Equal(t, activities_model.NotificationStatusUnread, notf.Status)
|
||||
|
||||
// unread notification should get latest updated_unix when re-notified
|
||||
_, err = db.GetEngine(t.Context()).ID(notf.ID).NoAutoTime().Cols("updated_unix").Update(&activities_model.Notification{UpdatedUnix: 123})
|
||||
assert.NoError(t, err)
|
||||
notf = unittest.AssertExistsAndLoadBean(t, &activities_model.Notification{ID: notf.ID})
|
||||
assert.EqualValues(t, 123, notf.UpdatedUnix)
|
||||
|
||||
_, err = activities_model.CreateOrUpdateIssueNotifications(t.Context(), issue.ID, 0, 3, 0)
|
||||
assert.NoError(t, err)
|
||||
notf = unittest.AssertExistsAndLoadBean(t, &activities_model.Notification{ID: notf.ID})
|
||||
assert.NotEqualValues(t, 123, notf.UpdatedUnix)
|
||||
assert.EqualValues(t, 3, notf.UpdatedBy)
|
||||
}
|
||||
|
||||
func TestCreateOrUpdateIssueNotificationsForAssigneeAndReviewer(t *testing.T) {
|
||||
|
||||
@@ -65,7 +65,7 @@ func verifySign(s *packet.Signature, h hash.Hash, k *GPGKey) error {
|
||||
|
||||
func hashAndVerify(sig *packet.Signature, payload string, k *GPGKey) (*GPGKey, error) {
|
||||
// Generating hash of commit
|
||||
hash, err := populateHash(sig.Hash, []byte(payload))
|
||||
hash, err := populateHash(sig, []byte(payload))
|
||||
if err != nil { // Skipping as failed to generate hash
|
||||
log.Error("PopulateHash: %v", err)
|
||||
return nil, err
|
||||
|
||||
@@ -5,7 +5,6 @@ package asymkey
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto"
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"fmt"
|
||||
@@ -100,8 +99,11 @@ func getExpiryTime(e *openpgp.Entity) time.Time {
|
||||
return expiry
|
||||
}
|
||||
|
||||
func populateHash(hashFunc crypto.Hash, msg []byte) (hash.Hash, error) {
|
||||
h := hashFunc.New()
|
||||
func populateHash(sig *packet.Signature, msg []byte) (hash.Hash, error) {
|
||||
h, err := sig.PrepareVerify()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if _, err := h.Write(msg); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
package asymkey
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
@@ -181,9 +182,9 @@ Unknown GPG key with good email
|
||||
assert.NoError(t, err, "Could not parse a valid GPG armored signature", testBadSigArmor)
|
||||
|
||||
// Generating hash of commit
|
||||
goodHash, err := populateHash(goodSig.Hash, []byte(testGoodPayload))
|
||||
goodHash, err := populateHash(goodSig, []byte(testGoodPayload))
|
||||
assert.NoError(t, err, "Could not generate a valid hash of payload", testGoodPayload)
|
||||
badHash, err := populateHash(badSig.Hash, []byte(testBadPayload))
|
||||
badHash, err := populateHash(badSig, []byte(testBadPayload))
|
||||
assert.NoError(t, err, "Could not generate a valid hash of payload", testBadPayload)
|
||||
|
||||
// Verify
|
||||
@@ -193,6 +194,18 @@ Unknown GPG key with good email
|
||||
assert.Error(t, err, "Validate a bad signature")
|
||||
err = verifySign(goodSig, goodHash, cannotsignkey)
|
||||
assert.Error(t, err, "Validate a bad signature with a kay that can not sign")
|
||||
|
||||
v6Entity, err := openpgp.NewEntity("v6", "", "v6@example.com", &packet.Config{V6Keys: true, Algorithm: packet.PubKeyAlgoMldsa65Ed25519})
|
||||
require.NoError(t, err)
|
||||
var v6SigArmor strings.Builder
|
||||
require.NoError(t, openpgp.ArmoredDetachSign(&v6SigArmor, v6Entity, strings.NewReader(testGoodPayload), nil))
|
||||
v6Sig, err := ExtractSignature(v6SigArmor.String())
|
||||
require.NoError(t, err)
|
||||
v6Content, err := Base64EncPubKey(v6Entity.PrimaryKey)
|
||||
require.NoError(t, err)
|
||||
v6Hash, err := populateHash(v6Sig, []byte(testGoodPayload))
|
||||
require.NoError(t, err)
|
||||
assert.NoError(t, verifySign(v6Sig, v6Hash, &GPGKey{Content: v6Content, CanSign: true}))
|
||||
}
|
||||
|
||||
func TestCheckGPGUserEmail(t *testing.T) {
|
||||
|
||||
+59
-18
@@ -12,8 +12,11 @@ import (
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"strconv"
|
||||
|
||||
"gitea.dev/models/db"
|
||||
"gitea.dev/modules/cache"
|
||||
"gitea.dev/modules/globallock"
|
||||
"gitea.dev/modules/secret"
|
||||
"gitea.dev/modules/setting"
|
||||
"gitea.dev/modules/timeutil"
|
||||
@@ -48,6 +51,11 @@ func (err ErrTwoFactorNotEnrolled) Unwrap() error {
|
||||
return util.ErrNotExist
|
||||
}
|
||||
|
||||
const (
|
||||
totpMaxAttempts = 5
|
||||
totpAttemptsTTL = 15 * 60 // seconds, renewed by every failed attempt
|
||||
)
|
||||
|
||||
// TwoFactor represents a two-factor authentication token.
|
||||
type TwoFactor struct {
|
||||
ID int64 `xorm:"pk autoincr"`
|
||||
@@ -120,26 +128,59 @@ func (t *TwoFactor) validateTOTP(passcode string) (bool, error) {
|
||||
return totp.Validate(passcode, secretStr), nil
|
||||
}
|
||||
|
||||
type TwoFactorResult int
|
||||
|
||||
const (
|
||||
TwoFactorResultValid TwoFactorResult = iota + 1
|
||||
TwoFactorResultInvalid
|
||||
TwoFactorResultTooManyAttempts
|
||||
)
|
||||
|
||||
// ValidateAndConsumeTOTP validates the passcode and atomically records it as used so that the
|
||||
// same passcode cannot be redeemed more than once (RFC 6238 §5.2). It returns false for an
|
||||
// invalid passcode as well as for a replay, including the case where a concurrent request with
|
||||
// the same passcode won the race first. All TOTP login surfaces must go through this helper.
|
||||
func (t *TwoFactor) ValidateAndConsumeTOTP(ctx context.Context, passcode string) (bool, error) {
|
||||
ok, err := t.validateTOTP(passcode)
|
||||
if err != nil || !ok {
|
||||
return false, err
|
||||
// same passcode cannot be redeemed more than once (RFC 6238 §5.2). Invalid passcodes and replays
|
||||
// return TwoFactorResultInvalid; exhausted attempts return TwoFactorResultTooManyAttempts.
|
||||
// All TOTP login surfaces must go through this helper.
|
||||
func (t *TwoFactor) ValidateAndConsumeTOTP(ctx context.Context, passcode string) (result TwoFactorResult, err error) {
|
||||
if passcode == "" {
|
||||
// password-only Basic auth clients must not use up the attempts
|
||||
return TwoFactorResultInvalid, nil
|
||||
}
|
||||
// Conditional update: only a row whose stored passcode differs from this one is updated, so a
|
||||
// replay (or a concurrent duplicate) matches zero rows and is rejected. The row lock taken by
|
||||
// the UPDATE serializes racing requests, closing the read-validate-write TOCTOU window.
|
||||
t.LastUsedPasscode = passcode
|
||||
n, err := db.GetEngine(ctx).ID(t.ID).
|
||||
Where(builder.Or(builder.IsNull{"last_used_passcode"}, builder.Neq{"last_used_passcode": passcode})).
|
||||
Cols("last_used_passcode").Update(t)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
return n == 1, nil
|
||||
// the lock spans check, validation and counting so that concurrent requests cannot exceed the limit
|
||||
attemptsKey := fmt.Sprintf("twofa_attempts_%d", t.UID)
|
||||
err = globallock.LockAndDo(ctx, attemptsKey, func(ctx context.Context) error {
|
||||
value, _ := cache.GetCache().Get(attemptsKey)
|
||||
attempts, _ := strconv.Atoi(value)
|
||||
if attempts >= totpMaxAttempts {
|
||||
result = TwoFactorResultTooManyAttempts
|
||||
return nil
|
||||
}
|
||||
|
||||
valid, err := t.validateTOTP(passcode)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if valid {
|
||||
// Conditional update: only a row whose stored passcode differs from this one is updated, so a
|
||||
// replay (or a concurrent duplicate) matches zero rows and is rejected. The row lock taken by
|
||||
// the UPDATE serializes racing requests, closing the read-validate-write TOCTOU window.
|
||||
t.LastUsedPasscode = passcode
|
||||
n, err := db.GetEngine(ctx).ID(t.ID).
|
||||
Where(builder.Or(builder.IsNull{"last_used_passcode"}, builder.Neq{"last_used_passcode": passcode})).
|
||||
Cols("last_used_passcode").Update(t)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
valid = n == 1
|
||||
}
|
||||
if !valid {
|
||||
result = TwoFactorResultInvalid
|
||||
return cache.GetCache().Put(attemptsKey, strconv.Itoa(attempts+1), totpAttemptsTTL)
|
||||
}
|
||||
cache.Remove(attemptsKey)
|
||||
result = TwoFactorResultValid
|
||||
return nil
|
||||
})
|
||||
return result, err
|
||||
}
|
||||
|
||||
// NewTwoFactor creates a new two-factor authentication token.
|
||||
|
||||
@@ -4,11 +4,15 @@
|
||||
package auth_test
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
auth_model "gitea.dev/models/auth"
|
||||
"gitea.dev/models/unittest"
|
||||
"gitea.dev/modules/cache"
|
||||
|
||||
"github.com/go-webauthn/webauthn/webauthn"
|
||||
"github.com/pquerna/otp/totp"
|
||||
@@ -30,21 +34,42 @@ func TestTwoFactorValidateAndConsumeTOTP(t *testing.T) {
|
||||
require.NoError(t, err)
|
||||
|
||||
// first use of a valid passcode succeeds
|
||||
ok, err := tfa.ValidateAndConsumeTOTP(t.Context(), passcode)
|
||||
result, err := tfa.ValidateAndConsumeTOTP(t.Context(), passcode)
|
||||
require.NoError(t, err)
|
||||
assert.True(t, ok)
|
||||
assert.Equal(t, auth_model.TwoFactorResultValid, result)
|
||||
|
||||
// replaying the same passcode is refused, even when still inside the TOTP validity window
|
||||
reloaded, err := auth_model.GetTwoFactorByUID(t.Context(), tfa.UID)
|
||||
require.NoError(t, err)
|
||||
ok, err = reloaded.ValidateAndConsumeTOTP(t.Context(), passcode)
|
||||
result, err = reloaded.ValidateAndConsumeTOTP(t.Context(), passcode)
|
||||
require.NoError(t, err)
|
||||
assert.False(t, ok)
|
||||
assert.Equal(t, auth_model.TwoFactorResultInvalid, result)
|
||||
|
||||
// an invalid passcode is rejected without consuming anything
|
||||
ok, err = reloaded.ValidateAndConsumeTOTP(t.Context(), "000000")
|
||||
var limited atomic.Int32
|
||||
var wg sync.WaitGroup
|
||||
for range 10 {
|
||||
wg.Go(func() {
|
||||
result, err := reloaded.ValidateAndConsumeTOTP(t.Context(), "0000000")
|
||||
assert.NoError(t, err)
|
||||
if result == auth_model.TwoFactorResultTooManyAttempts {
|
||||
limited.Add(1)
|
||||
} else {
|
||||
assert.Equal(t, auth_model.TwoFactorResultInvalid, result)
|
||||
}
|
||||
})
|
||||
}
|
||||
wg.Wait()
|
||||
assert.EqualValues(t, 6, limited.Load())
|
||||
nextPasscode, err := totp.GenerateCode(key.Secret(), time.Now().Add(30*time.Second))
|
||||
require.NoError(t, err)
|
||||
assert.False(t, ok)
|
||||
result, err = reloaded.ValidateAndConsumeTOTP(t.Context(), nextPasscode)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, auth_model.TwoFactorResultTooManyAttempts, result)
|
||||
|
||||
cache.Remove(fmt.Sprintf("twofa_attempts_%d", tfa.UID))
|
||||
result, err = reloaded.ValidateAndConsumeTOTP(t.Context(), nextPasscode)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, auth_model.TwoFactorResultValid, result)
|
||||
}
|
||||
|
||||
func TestDisableTwoFactor(t *testing.T) {
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
updated_unix: 1546869730
|
||||
|
||||
- id: 2
|
||||
user_id: 3
|
||||
user_id: 14
|
||||
application_id: 1
|
||||
counter: 1
|
||||
scope: "openid"
|
||||
@@ -23,7 +23,7 @@
|
||||
updated_unix: 1546869730
|
||||
|
||||
- id: 4
|
||||
user_id: 99
|
||||
user_id: 2
|
||||
application_id: 2
|
||||
counter: 1
|
||||
scope: "whatever"
|
||||
|
||||
@@ -39,7 +39,7 @@ type CommitStatus struct {
|
||||
RepoID int64 `xorm:"UNIQUE(repo_sha_index)"`
|
||||
SHA string `xorm:"VARCHAR(64) NOT NULL INDEX UNIQUE(repo_sha_index)"`
|
||||
Index int64 `xorm:"INDEX UNIQUE(repo_sha_index)"`
|
||||
Repo *repo_model.Repository `xorm:"-"`
|
||||
Repo *repo_model.Repository `xorm:"-" json:"-"`
|
||||
State commitstatus.CommitStatusState `xorm:"VARCHAR(7) NOT NULL"`
|
||||
|
||||
// TargetURL points to the commit status page reported by a CI system
|
||||
@@ -49,7 +49,7 @@ type CommitStatus struct {
|
||||
Description string `xorm:"TEXT"`
|
||||
ContextHash string `xorm:"VARCHAR(64) index"`
|
||||
Context string `xorm:"TEXT"`
|
||||
Creator *user_model.User `xorm:"-"`
|
||||
Creator *user_model.User `xorm:"-" json:"-"`
|
||||
CreatorID int64
|
||||
|
||||
CreatedUnix timeutil.TimeStamp `xorm:"INDEX created"`
|
||||
|
||||
@@ -32,6 +32,9 @@ type RepoSHA struct {
|
||||
}
|
||||
|
||||
func GetLatestCommitStatusForRepoAndSHAs(ctx context.Context, repoSHAs []RepoSHA) ([]*CommitStatus, error) {
|
||||
if len(repoSHAs) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
cond := builder.NewCond()
|
||||
for _, rs := range repoSHAs {
|
||||
cond = cond.Or(builder.Eq{"repo_id": rs.RepoID, "sha": rs.SHA})
|
||||
@@ -67,8 +70,8 @@ func UpdateCommitStatusSummary(ctx context.Context, repoID int64, sha string) er
|
||||
// mysql will return 0 when update a record which state hasn't been changed which behaviour is different from other database,
|
||||
// so we need to use insert in on duplicate
|
||||
if setting.Database.Type.IsMySQL() {
|
||||
_, err := db.GetEngine(ctx).Exec("INSERT INTO commit_status_summary (repo_id,sha,state,target_url) VALUES (?,?,?,?) ON DUPLICATE KEY UPDATE state=?",
|
||||
repoID, sha, state.State, state.TargetURL, state.State)
|
||||
_, err := db.GetEngine(ctx).Exec("INSERT INTO commit_status_summary (repo_id,sha,state,target_url) VALUES (?,?,?,?) ON DUPLICATE KEY UPDATE state=?, target_url=?",
|
||||
repoID, sha, state.State, state.TargetURL, state.State, state.TargetURL)
|
||||
return err
|
||||
}
|
||||
|
||||
|
||||
@@ -89,6 +89,13 @@ func TestGetCommitStatuses(t *testing.T) {
|
||||
"deploy/awesomeness": 5,
|
||||
}, latestIndexes)
|
||||
})
|
||||
|
||||
t.Run("GetLatestCommitStatusForRepoAndSHAsEmpty", func(t *testing.T) {
|
||||
assert.NoError(t, git_model.UpdateCommitStatusSummary(t.Context(), repo1.ID, sha1))
|
||||
statuses, err := git_model.GetLatestCommitStatusForRepoAndSHAs(t.Context(), nil)
|
||||
assert.NoError(t, err)
|
||||
assert.Empty(t, statuses)
|
||||
})
|
||||
}
|
||||
|
||||
func Test_CalcCommitStatus(t *testing.T) {
|
||||
|
||||
+87
-138
@@ -285,23 +285,12 @@ func IsOfficialReviewer(ctx context.Context, issue *Issue, reviewer *user_model.
|
||||
}
|
||||
if rule == nil {
|
||||
// if no rule is found, then user with write access can make official reviews
|
||||
err := pr.LoadBaseRepo(ctx)
|
||||
if err != nil {
|
||||
if err := pr.LoadBaseRepo(ctx); err != nil {
|
||||
return false, err
|
||||
}
|
||||
writeAccess, err := access_model.HasAccessUnit(ctx, reviewer, pr.BaseRepo, unit.TypeCode, perm.AccessModeWrite)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
return writeAccess, nil
|
||||
return access_model.HasAccessUnit(ctx, reviewer, pr.BaseRepo, unit.TypeCode, perm.AccessModeWrite)
|
||||
}
|
||||
|
||||
official, err := git_model.IsUserOfficialReviewer(ctx, rule, reviewer)
|
||||
if official || err != nil {
|
||||
return official, err
|
||||
}
|
||||
|
||||
return false, nil
|
||||
return git_model.IsUserOfficialReviewer(ctx, rule, reviewer)
|
||||
}
|
||||
|
||||
// IsOfficialReviewerTeam check if reviewer in this team can make official reviews in issue (counts towards required approvals)
|
||||
@@ -313,66 +302,82 @@ func IsOfficialReviewerTeam(ctx context.Context, issue *Issue, team *organizatio
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
if pb == nil {
|
||||
return false, nil
|
||||
if pb != nil && pb.EnableApprovalsWhitelist {
|
||||
return slices.Contains(pb.ApprovalsWhitelistTeamIDs, team.ID), nil
|
||||
}
|
||||
|
||||
if !pb.EnableApprovalsWhitelist {
|
||||
return team.UnitAccessMode(ctx, unit.TypeCode) >= perm.AccessModeWrite, nil
|
||||
}
|
||||
|
||||
return slices.Contains(pb.ApprovalsWhitelistTeamIDs, team.ID), nil
|
||||
return team.UnitAccessMode(ctx, unit.TypeCode) >= perm.AccessModeWrite, nil
|
||||
}
|
||||
|
||||
// RecalculateReviewsOfficial re-evaluates the "official" flag of the latest approve
|
||||
// and reject reviews of an issue against its pull request's current base branch.
|
||||
// It must be called whenever the target branch changes, otherwise an approval that
|
||||
// was official on the previous (possibly unprotected) branch would keep satisfying
|
||||
// the new branch's protection rules.
|
||||
func RecalculateReviewsOfficial(ctx context.Context, issue *Issue) error {
|
||||
if err := issue.LoadPullRequest(ctx); err != nil {
|
||||
// updateReviewerOfficial keeps the official flag only on the reviewer's latest approval, rejection or review request, and only if the reviewer is official
|
||||
func updateReviewerOfficial(ctx context.Context, issueID, reviewerID int64, official bool) error {
|
||||
if _, err := db.GetEngine(ctx).Where(builder.Eq{"issue_id": issueID, "reviewer_id": reviewerID}).
|
||||
NoAutoTime().Cols("official").Update(&Review{}); err != nil {
|
||||
return err
|
||||
}
|
||||
if !official {
|
||||
return nil
|
||||
}
|
||||
latest, err := GetReviewByIssueIDAndUserID(ctx, issueID, reviewerID)
|
||||
if IsErrReviewNotExist(err) {
|
||||
return nil
|
||||
} else if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = db.GetEngine(ctx).ID(latest.ID).NoAutoTime().Cols("official").Update(&Review{Official: true})
|
||||
return err
|
||||
}
|
||||
|
||||
// Clearing and restoring the official flags must happen atomically, otherwise a
|
||||
// failure in between would leave the reviews without any official flag set.
|
||||
// RecalculateReviewsOfficial re-evaluates the "official" flag of an issue's reviews and review requests
|
||||
// against its pull request's current base branch. It must be called whenever the target branch changes,
|
||||
// otherwise an approval that was official on the previous (possibly unprotected) branch would keep
|
||||
// satisfying the new branch's protection rules.
|
||||
func RecalculateReviewsOfficial(ctx context.Context, issue *Issue) error {
|
||||
return db.WithTx(ctx, func(ctx context.Context) error {
|
||||
// Only the latest approve/reject review of each reviewer counts as official, so
|
||||
// clear the flag on all of them first and restore it only where it still applies.
|
||||
if _, err := db.GetEngine(ctx).
|
||||
Where("issue_id = ?", issue.ID).
|
||||
In("type", ReviewTypeApprove, ReviewTypeReject).
|
||||
Cols("official").
|
||||
Update(&Review{Official: false}); err != nil {
|
||||
if _, err := db.GetEngine(ctx).Where("issue_id = ?", issue.ID).NoAutoTime().Cols("official").Update(&Review{}); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
reviews, err := FindLatestReviews(ctx, FindReviewOptions{
|
||||
Types: []ReviewType{ReviewTypeApprove, ReviewTypeReject},
|
||||
IssueID: issue.ID,
|
||||
})
|
||||
if err != nil {
|
||||
reviewerIDs := make([]int64, 0, 5)
|
||||
if err := db.GetEngine(ctx).Table("review").Cols("reviewer_id").
|
||||
Where(builder.Eq{"issue_id": issue.ID, "original_author_id": 0}).
|
||||
And(builder.In("type", ReviewTypeApprove, ReviewTypeReject, ReviewTypeRequest)).
|
||||
And(builder.Neq{"reviewer_id": 0}).
|
||||
Distinct("reviewer_id").Find(&reviewerIDs); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
for _, review := range reviews {
|
||||
if err := review.LoadReviewer(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
if review.Reviewer == nil {
|
||||
continue
|
||||
}
|
||||
official, err := IsOfficialReviewer(ctx, issue, review.Reviewer)
|
||||
for _, reviewerID := range reviewerIDs {
|
||||
_, reviewer, err := user_model.GetPossibleUserByID(ctx, reviewerID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if official {
|
||||
if _, err := db.GetEngine(ctx).ID(review.ID).Cols("official").Update(&Review{Official: true}); err != nil {
|
||||
return err
|
||||
}
|
||||
official, err := IsOfficialReviewer(ctx, issue, reviewer)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := updateReviewerOfficial(ctx, issue.ID, reviewerID, official); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
teamRequests := make([]*Review, 0, 5)
|
||||
if err := db.GetEngine(ctx).Where(builder.Eq{"issue_id": issue.ID, "type": ReviewTypeRequest}).
|
||||
And(builder.Gt{"reviewer_team_id": 0}).Find(&teamRequests); err != nil {
|
||||
return err
|
||||
}
|
||||
for _, request := range teamRequests {
|
||||
if err := request.LoadReviewerTeam(ctx); organization.IsErrTeamNotExist(err) {
|
||||
continue
|
||||
} else if err != nil {
|
||||
return err
|
||||
}
|
||||
official, err := IsOfficialReviewerTeam(ctx, issue, request.ReviewerTeam)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := db.GetEngine(ctx).ID(request.ID).NoAutoTime().Cols("official").Update(&Review{Official: official}); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
}
|
||||
@@ -474,7 +479,13 @@ func SubmitReview(ctx context.Context, doer *user_model.User, issue *Issue, revi
|
||||
defer committer.Close()
|
||||
sess := db.GetEngine(ctx)
|
||||
|
||||
isApproveOrReject := reviewType == ReviewTypeApprove || reviewType == ReviewTypeReject
|
||||
official := false
|
||||
if isApproveOrReject {
|
||||
if official, err = IsOfficialReviewer(ctx, issue, doer); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
}
|
||||
|
||||
review, err := GetCurrentReview(ctx, doer, issue)
|
||||
if err != nil {
|
||||
@@ -486,16 +497,6 @@ func SubmitReview(ctx context.Context, doer *user_model.User, issue *Issue, revi
|
||||
return nil, nil, ContentEmptyErr{}
|
||||
}
|
||||
|
||||
if reviewType == ReviewTypeApprove || reviewType == ReviewTypeReject {
|
||||
// Only reviewers latest review of type approve and reject shall count as "official", so existing reviews needs to be cleared
|
||||
if _, err := db.Exec(ctx, "UPDATE `review` SET official=? WHERE issue_id=? AND reviewer_id=?", false, issue.ID, doer.ID); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
if official, err = IsOfficialReviewer(ctx, issue, doer); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
}
|
||||
|
||||
// No current review. Create a new one!
|
||||
if review, err = CreateReview(ctx, CreateReviewOptions{
|
||||
Type: reviewType,
|
||||
@@ -516,16 +517,6 @@ func SubmitReview(ctx context.Context, doer *user_model.User, issue *Issue, revi
|
||||
return nil, nil, ContentEmptyErr{}
|
||||
}
|
||||
|
||||
if reviewType == ReviewTypeApprove || reviewType == ReviewTypeReject {
|
||||
// Only reviewers latest review of type approve and reject shall count as "official", so existing reviews needs to be cleared
|
||||
if _, err := db.Exec(ctx, "UPDATE `review` SET official=? WHERE issue_id=? AND reviewer_id=?", false, issue.ID, doer.ID); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
if official, err = IsOfficialReviewer(ctx, issue, doer); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
}
|
||||
|
||||
review.Official = official
|
||||
review.Issue = issue
|
||||
review.Content = content
|
||||
@@ -546,6 +537,16 @@ func SubmitReview(ctx context.Context, doer *user_model.User, issue *Issue, revi
|
||||
}
|
||||
}
|
||||
|
||||
if isApproveOrReject {
|
||||
if err := updateReviewerOfficial(ctx, issue.ID, doer.ID, official); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
}
|
||||
|
||||
if reviewType == ReviewTypePending {
|
||||
return review, nil, committer.Commit()
|
||||
}
|
||||
|
||||
comm, err := CreateComment(ctx, &CreateCommentOptions{
|
||||
Type: CommentTypeReview,
|
||||
Doer: doer,
|
||||
@@ -560,7 +561,7 @@ func SubmitReview(ctx context.Context, doer *user_model.User, issue *Issue, revi
|
||||
}
|
||||
|
||||
// try to remove team review request if need
|
||||
if issue.Repo.Owner.IsOrganization() && (reviewType == ReviewTypeApprove || reviewType == ReviewTypeReject) {
|
||||
if issue.Repo.Owner.IsOrganization() && isApproveOrReject {
|
||||
teamReviewRequests := make([]*Review, 0, 10)
|
||||
if err := sess.SQL("SELECT * FROM review WHERE issue_id = ? AND reviewer_team_id > 0 AND type = ?", issue.ID, ReviewTypeRequest).Find(&teamReviewRequests); err != nil {
|
||||
return nil, nil, err
|
||||
@@ -698,8 +699,6 @@ func InsertReviews(ctx context.Context, reviews []*Review) error {
|
||||
// AddReviewRequest add a review request from one reviewer
|
||||
func AddReviewRequest(ctx context.Context, issue *Issue, reviewer, doer *user_model.User, isCodeOwners bool) (*Comment, error) {
|
||||
return db.WithTx2(ctx, func(ctx context.Context) (*Comment, error) {
|
||||
sess := db.GetEngine(ctx)
|
||||
|
||||
review, err := GetReviewByIssueIDAndUserID(ctx, issue.ID, reviewer.ID)
|
||||
if err != nil && !IsErrReviewNotExist(err) {
|
||||
return nil, err
|
||||
@@ -725,15 +724,9 @@ func AddReviewRequest(ctx context.Context, issue *Issue, reviewer, doer *user_mo
|
||||
}
|
||||
}
|
||||
|
||||
// if the reviewer is an official reviewer,
|
||||
// remove the official flag in the all previous reviews
|
||||
official, err := IsOfficialReviewer(ctx, issue, reviewer)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
} else if official {
|
||||
if _, err := sess.Exec("UPDATE `review` SET official=? WHERE issue_id=? AND reviewer_id=?", false, issue.ID, reviewer.ID); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
review, err = CreateReview(ctx, CreateReviewOptions{
|
||||
@@ -747,6 +740,10 @@ func AddReviewRequest(ctx context.Context, issue *Issue, reviewer, doer *user_mo
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if err := updateReviewerOfficial(ctx, issue.ID, reviewer.ID, official); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
comment, err := CreateComment(ctx, &CreateCommentOptions{
|
||||
Type: CommentTypeReviewRequest,
|
||||
Doer: doer,
|
||||
@@ -787,10 +784,9 @@ func RemoveReviewRequest(ctx context.Context, issue *Issue, reviewer, doer *user
|
||||
official, err := IsOfficialReviewer(ctx, issue, reviewer)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
} else if official {
|
||||
if err := restoreLatestOfficialReview(ctx, issue.ID, reviewer.ID); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
if err := updateReviewerOfficial(ctx, issue.ID, reviewer.ID, official); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return CreateComment(ctx, &CreateCommentOptions{
|
||||
@@ -804,22 +800,6 @@ func RemoveReviewRequest(ctx context.Context, issue *Issue, reviewer, doer *user
|
||||
})
|
||||
}
|
||||
|
||||
// Recalculate the latest official review for reviewer
|
||||
func restoreLatestOfficialReview(ctx context.Context, issueID, reviewerID int64) error {
|
||||
review, err := GetReviewByIssueIDAndUserID(ctx, issueID, reviewerID)
|
||||
if err != nil && !IsErrReviewNotExist(err) {
|
||||
return err
|
||||
}
|
||||
|
||||
if review != nil {
|
||||
if _, err := db.Exec(ctx, "UPDATE `review` SET official=? WHERE id=?", true, review.ID); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// AddTeamReviewRequest add a review request from one team
|
||||
func AddTeamReviewRequest(ctx context.Context, issue *Issue, reviewer *organization.Team, doer *user_model.User, isCodeOwners bool) (*Comment, error) {
|
||||
return db.WithTx2(ctx, func(ctx context.Context) (*Comment, error) {
|
||||
@@ -836,10 +816,6 @@ func AddTeamReviewRequest(ctx context.Context, issue *Issue, reviewer *organizat
|
||||
official, err := IsOfficialReviewerTeam(ctx, issue, reviewer)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("isOfficialReviewerTeam(): %w", err)
|
||||
} else if !official {
|
||||
if official, err = IsOfficialReviewer(ctx, issue, doer); err != nil {
|
||||
return nil, fmt.Errorf("isOfficialReviewer(): %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
if review, err = CreateReview(ctx, CreateReviewOptions{
|
||||
@@ -852,12 +828,6 @@ func AddTeamReviewRequest(ctx context.Context, issue *Issue, reviewer *organizat
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if official {
|
||||
if _, err := db.Exec(ctx, "UPDATE `review` SET official=? WHERE issue_id=? AND reviewer_team_id=?", false, issue.ID, reviewer.ID); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
comment, err := CreateComment(ctx, &CreateCommentOptions{
|
||||
Type: CommentTypeReviewRequest,
|
||||
Doer: doer,
|
||||
@@ -892,25 +862,6 @@ func RemoveTeamReviewRequest(ctx context.Context, issue *Issue, reviewer *organi
|
||||
return nil, err
|
||||
}
|
||||
|
||||
official, err := IsOfficialReviewerTeam(ctx, issue, reviewer)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("isOfficialReviewerTeam(): %w", err)
|
||||
}
|
||||
|
||||
if official {
|
||||
// recalculate which is the latest official review from that team
|
||||
review, err := GetReviewByIssueIDAndUserID(ctx, issue.ID, -reviewer.ID)
|
||||
if err != nil && !IsErrReviewNotExist(err) {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if review != nil {
|
||||
if _, err := db.Exec(ctx, "UPDATE `review` SET official=? WHERE id=?", true, review.ID); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if doer == nil {
|
||||
return nil, nil
|
||||
}
|
||||
@@ -1037,10 +988,8 @@ func DeleteReview(ctx context.Context, r *Review) error {
|
||||
return err
|
||||
}
|
||||
|
||||
if r.Official {
|
||||
if err := restoreLatestOfficialReview(ctx, r.IssueID, r.ReviewerID); err != nil {
|
||||
return err
|
||||
}
|
||||
if r.Official && r.OriginalAuthorID == 0 {
|
||||
return updateReviewerOfficial(ctx, r.IssueID, r.ReviewerID, true)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
|
||||
@@ -9,6 +9,7 @@ import (
|
||||
"gitea.dev/models/db"
|
||||
git_model "gitea.dev/models/git"
|
||||
issues_model "gitea.dev/models/issues"
|
||||
"gitea.dev/models/organization"
|
||||
repo_model "gitea.dev/models/repo"
|
||||
"gitea.dev/models/unittest"
|
||||
user_model "gitea.dev/models/user"
|
||||
@@ -440,3 +441,17 @@ func TestRecalculateReviewsOfficial(t *testing.T) {
|
||||
review = unittest.AssertExistsAndLoadBean(t, &issues_model.Review{ID: review.ID})
|
||||
assert.True(t, review.Official)
|
||||
}
|
||||
|
||||
func TestTeamReviewRequestOfficial(t *testing.T) {
|
||||
assert.NoError(t, unittest.PrepareTestDatabase())
|
||||
|
||||
issue := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{ID: 12})
|
||||
assert.NoError(t, issue.LoadRepo(t.Context()))
|
||||
comment, err := issues_model.AddTeamReviewRequest(t.Context(), issue, unittest.AssertExistsAndLoadBean(t, &organization.Team{ID: 2}), &user_model.User{ID: 2}, false)
|
||||
assert.NoError(t, err)
|
||||
assert.True(t, unittest.AssertExistsAndLoadBean(t, &issues_model.Review{ID: comment.ReviewID}).Official)
|
||||
|
||||
assert.NoError(t, db.Insert(t.Context(), &git_model.ProtectedBranch{RepoID: issue.RepoID, RuleName: "master", EnableApprovalsWhitelist: true}))
|
||||
assert.NoError(t, issues_model.RecalculateReviewsOfficial(t.Context(), issue))
|
||||
assert.False(t, unittest.AssertExistsAndLoadBean(t, &issues_model.Review{ID: comment.ReviewID}).Official)
|
||||
}
|
||||
@@ -506,13 +506,16 @@ func GetIndividualUserRepoPermission(ctx context.Context, repo *repo_model.Repos
|
||||
}
|
||||
}
|
||||
|
||||
// if user in an owner team
|
||||
// Apply repository-level access from teams.
|
||||
for _, team := range perm.orgRepoTeams {
|
||||
if team.IsOwnerTeam() || team.AccessMode == perm_model.AccessModeOwner {
|
||||
perm.AccessMode = perm_model.AccessModeOwner
|
||||
perm.unitsMode = nil
|
||||
return perm, nil
|
||||
}
|
||||
if team.AccessMode == perm_model.AccessModeAdmin {
|
||||
perm.AccessMode = max(perm.AccessMode, perm_model.AccessModeAdmin)
|
||||
}
|
||||
}
|
||||
|
||||
for _, u := range repo.Units {
|
||||
|
||||
@@ -236,6 +236,32 @@ func testGetIndividualUserRepoPermission(t *testing.T) {
|
||||
require.Empty(t, users)
|
||||
})
|
||||
|
||||
t.Run("DoerWithAdminTeamWithoutAccessRow", func(t *testing.T) {
|
||||
_, err := db.GetEngine(ctx).ID(team.ID).Cols("authorize").Update(&organization.Team{AccessMode: perm_model.AccessModeAdmin})
|
||||
require.NoError(t, err)
|
||||
defer func() {
|
||||
_, err := db.GetEngine(ctx).ID(team.ID).Cols("authorize").Update(&organization.Team{AccessMode: perm_model.AccessModeNone})
|
||||
require.NoError(t, err)
|
||||
}()
|
||||
|
||||
for _, repo := range []*repo_model.Repository{repo3, repo32} {
|
||||
perm, err := GetIndividualUserRepoPermission(ctx, repo, user)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, perm_model.AccessModeAdmin, perm.AccessMode)
|
||||
assert.True(t, perm.IsAdmin())
|
||||
assert.False(t, perm.IsOwner())
|
||||
for _, repoUnit := range repo.Units {
|
||||
assert.Equal(t, perm_model.AccessModeAdmin, perm.UnitAccessMode(repoUnit.Type))
|
||||
}
|
||||
}
|
||||
|
||||
unrelatedRepo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 5})
|
||||
require.Equal(t, org.ID, unrelatedRepo.OwnerID)
|
||||
perm, err := GetIndividualUserRepoPermission(ctx, unrelatedRepo, user)
|
||||
require.NoError(t, err)
|
||||
assert.False(t, perm.IsAdmin())
|
||||
})
|
||||
|
||||
require.NoError(t, db.Insert(ctx, repo_model.Collaboration{RepoID: repo3.ID, UserID: user.ID, Mode: perm_model.AccessModeWrite}))
|
||||
require.NoError(t, db.Insert(ctx, Access{RepoID: repo3.ID, UserID: user.ID, Mode: perm_model.AccessModeWrite}))
|
||||
t.Run("DoerWithReadIssueTeamAndWriteCollaboratorOnPrivateRepo", func(t *testing.T) {
|
||||
|
||||
@@ -42,6 +42,10 @@ func init() {
|
||||
db.RegisterModel(new(Attachment))
|
||||
}
|
||||
|
||||
func (a *Attachment) IsLinked() bool {
|
||||
return a.IssueID > 0 || a.ReleaseID > 0 || a.CommentID > 0
|
||||
}
|
||||
|
||||
// IncreaseDownloadCount is update download count + 1
|
||||
func (a *Attachment) IncreaseDownloadCount(ctx context.Context) error {
|
||||
// Update download count.
|
||||
|
||||
@@ -151,7 +151,7 @@ func UpdateLanguageStats(ctx context.Context, repo *Repository, commitID string,
|
||||
var topLang string
|
||||
var s int64
|
||||
for lang, size := range stats {
|
||||
if size > s {
|
||||
if size > s || (size == s && lang < topLang) {
|
||||
s = size
|
||||
topLang = lang
|
||||
}
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
// Copyright 2026 The Gitea Authors. All rights reserved.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package repo_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
repo_model "gitea.dev/models/repo"
|
||||
"gitea.dev/models/unittest"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestUpdateLanguageStatsPrimaryTie(t *testing.T) {
|
||||
require.NoError(t, unittest.PrepareTestDatabase())
|
||||
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1})
|
||||
|
||||
require.NoError(t, repo_model.UpdateLanguageStats(t.Context(), repo, "1234567890", map[string]int64{"Go": 10, "C": 10}))
|
||||
|
||||
stats, err := repo_model.GetLanguageStats(t.Context(), repo)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, stats, 2)
|
||||
for _, stat := range stats {
|
||||
assert.Equal(t, stat.Language == "C", stat.IsPrimary, stat.Language)
|
||||
}
|
||||
}
|
||||
@@ -55,11 +55,9 @@ func escapeStream(locale translation.Locale, in io.Reader, out io.Writer, opts .
|
||||
es.allowed = opts[0].Allowed
|
||||
}
|
||||
|
||||
readCount := 0
|
||||
lastIsTag := false
|
||||
isContentBegin := true
|
||||
for {
|
||||
parts, partInTag, err := es.readRunes()
|
||||
readCount++
|
||||
if err == io.EOF {
|
||||
return es.escaped, nil
|
||||
} else if err != nil {
|
||||
@@ -67,17 +65,14 @@ func escapeStream(locale translation.Locale, in io.Reader, out io.Writer, opts .
|
||||
}
|
||||
for i, part := range parts {
|
||||
if partInTag[i] {
|
||||
lastIsTag = true
|
||||
isContentBegin = true
|
||||
es.trackHtmlTag(part)
|
||||
if _, err := out.Write(part); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
} else {
|
||||
// if last part is tag, then this part is content begin
|
||||
// if the content is the first part of the first read, then it's also content begin
|
||||
isContentBegin := lastIsTag || (readCount == 1 && i == 0)
|
||||
lastIsTag = false
|
||||
if isContentBegin {
|
||||
isContentBegin = false
|
||||
if part, err = es.trimAndWriteBom(part); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -236,18 +231,23 @@ func (e *htmlChunkReader) readRunes() (parts [][]byte, partInTag []bool, _ error
|
||||
copy(curPart, e.readBuf[pos:curPartEnd])
|
||||
// now we get the curPart bytes, but we can't directly use it, the last rune in it might have been cut
|
||||
// try to decode the last rune, if it's invalid, then we cut the last byte and try again until we get a valid rune or no byte left
|
||||
for i := curPartLen - 1; i >= 0; i-- {
|
||||
last, lastSize := utf8.DecodeRune(curPart[i:])
|
||||
if last == utf8.RuneError && lastSize == 1 {
|
||||
curPartLen--
|
||||
} else {
|
||||
curPartLen += lastSize - 1
|
||||
break
|
||||
if e.readErr == nil && curPartEnd == len(e.readBuf) {
|
||||
for i := curPartLen - 1; i >= 0; i-- {
|
||||
last, lastSize := utf8.DecodeRune(curPart[i:])
|
||||
if last == utf8.RuneError && lastSize == 1 {
|
||||
curPartLen--
|
||||
} else {
|
||||
curPartLen += lastSize - 1
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
if curPartLen == 0 {
|
||||
if !utf8.FullRune(curPart) && len(curPart) <= cap(e.readBuf)*3/4 {
|
||||
break // keep a rune cut by the read boundary for the next read
|
||||
}
|
||||
// actually it's impossible that the part doesn't contain any valid rune,
|
||||
// the only case is that the cap(readBuf) is too small, or the origin contain indeed doesn't contain any valid rune
|
||||
// the only case is that the cap(readBuf) is too small, or the origin content indeed doesn't contain any valid rune
|
||||
// * try to leave the last 4 bytes (possible longest utf-8 encoding) to next round
|
||||
// * at least consume 1 byte to avoid infinite loop
|
||||
curPartLen = max(len(curPart)-utf8.UTFMax, 1)
|
||||
|
||||
@@ -6,6 +6,7 @@ package charset
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
"testing/iotest"
|
||||
|
||||
"gitea.dev/modules/htmlutil"
|
||||
"gitea.dev/modules/setting"
|
||||
@@ -160,6 +161,11 @@ func TestEscapeControlReader(t *testing.T) {
|
||||
assert.Equal(t, tt.result, outStr)
|
||||
})
|
||||
}
|
||||
|
||||
output := &htmlutil.HTMLBuilder{}
|
||||
_, err := EscapeControlReader(iotest.OneByteReader(strings.NewReader("\xef\xbb\xbftest")), output, &translation.MockLocale{})
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, "\xef\xbb\xbftest", output.String())
|
||||
}
|
||||
|
||||
func TestTrackHtmlTag(t *testing.T) {
|
||||
@@ -234,4 +240,11 @@ func TestHTMLChunkReader(t *testing.T) {
|
||||
testReadChunks(t, 5, input, []textPart{{"<Aé", true}, {"啊", true}, {"🌞>", true}, {"Aé", false}, {"啊", false}, {"🌞", false}})
|
||||
testReadChunks(t, 6, input, []textPart{{"<Aé", true}, {"啊", true}, {"🌞>", true}, {"A", false}, {"é啊", false}, {"🌞", false}})
|
||||
testReadChunks(t, 7, input, []textPart{{"<Aé啊", true}, {"🌞>", true}, {"A", false}, {"é啊", false}, {"🌞", false}})
|
||||
|
||||
for chunkSize := 6; chunkSize < 5+len(rune4); chunkSize++ {
|
||||
testReadChunks(t, chunkSize, "<abc>"+rune4, []textPart{{"<abc>", true}, {rune4, false}})
|
||||
}
|
||||
testReadChunks(t, 6, "<abc>"+rune3[:2], []textPart{{"<abc>", true}, {rune3[:2], false}})
|
||||
testReadChunks(t, 7, "<abc>"+rune3[:2]+"<b>", []textPart{{"<abc>", true}, {rune3[:2], false}, {"<b>", true}})
|
||||
testReadChunks(t, 1, rune2, []textPart{{rune2[:1], false}, {rune2[1:], false}})
|
||||
}
|
||||
+9
-22
@@ -308,31 +308,18 @@ func GetAffectedFiles(ctx context.Context, repo *Repository, branchName, oldComm
|
||||
oldCommitID = startCommitID
|
||||
}
|
||||
|
||||
affectedFiles := make([]string, 0, 32)
|
||||
|
||||
// Run `git diff --name-only` to get the names of the changed files
|
||||
cmd := gitcmd.NewCommand("diff", "--name-only").AddDynamicArguments(oldCommitID, newCommitID)
|
||||
stdoutReader, stdoutReaderClose := cmd.MakeStdoutPipe()
|
||||
defer stdoutReaderClose()
|
||||
err := cmd.WithEnv(env).WithRepo(repo).
|
||||
WithPipelineFunc(func(ctx gitcmd.Context) error {
|
||||
// Now scan the output from the command
|
||||
scanner := bufio.NewScanner(stdoutReader)
|
||||
for scanner.Scan() {
|
||||
path := strings.TrimSpace(scanner.Text())
|
||||
if len(path) == 0 {
|
||||
continue
|
||||
}
|
||||
affectedFiles = append(affectedFiles, path)
|
||||
}
|
||||
return scanner.Err()
|
||||
}).
|
||||
Run(ctx)
|
||||
// use "diff-tree -r -z": paths are NUL-separated (never quoted) and renames report both the old and new path
|
||||
cmd := gitcmd.NewCommand("diff-tree", "--name-only", "--no-commit-id", "-r", "-z").AddDynamicArguments(oldCommitID, newCommitID)
|
||||
stdout, _, err := cmd.WithEnv(env).WithRepo(repo).RunStdString(ctx)
|
||||
if err != nil {
|
||||
log.Error("Unable to get affected files for commits from %s to %s in %s: %v", oldCommitID, newCommitID, repo.LogString(), err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return affectedFiles, err
|
||||
affectedFiles := strings.Split(strings.TrimSuffix(stdout, "\x00"), "\x00")
|
||||
if len(affectedFiles) == 1 && affectedFiles[0] == "" {
|
||||
affectedFiles = nil
|
||||
}
|
||||
return affectedFiles, nil
|
||||
}
|
||||
|
||||
// GetReverseRawDiff dumps the reverse diff results of repository in given commit ID to io.Writer.
|
||||
|
||||
@@ -4,10 +4,14 @@
|
||||
package git
|
||||
|
||||
import (
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"gitea.dev/modules/git/gitcmd"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
const exampleDiff = `diff --git a/README.md b/README.md
|
||||
@@ -190,3 +194,40 @@ func TestParseDiffHunkString(t *testing.T) {
|
||||
assert.Equal(t, 19, rightLine)
|
||||
assert.Equal(t, 5, rightHunk)
|
||||
}
|
||||
|
||||
func TestGetAffectedFilesSpecialNames(t *testing.T) {
|
||||
repoDir := filepath.Join(t.TempDir(), "repo.git")
|
||||
require.NoError(t, gitcmd.NewCommand("init").AddDynamicArguments(repoDir).Run(t.Context()))
|
||||
stdin := `commit refs/heads/main
|
||||
committer User <user@example.com> 1714310400 +0000
|
||||
data 1
|
||||
a
|
||||
M 100644 inline base.txt
|
||||
data 1
|
||||
x
|
||||
|
||||
commit refs/heads/main
|
||||
committer User <user@example.com> 1714310401 +0000
|
||||
data 1
|
||||
b
|
||||
M 100644 inline "protected/we\"ird.md"
|
||||
data 1
|
||||
x
|
||||
M 100644 inline "protected/\344\270\255\346\226\207.md"
|
||||
data 1
|
||||
x
|
||||
M 100644 inline protected/normal.md
|
||||
data 1
|
||||
x
|
||||
R base.txt protected/renamed.md
|
||||
`
|
||||
require.NoError(t, gitcmd.NewCommand("fast-import").WithDir(repoDir).WithStdinBytes([]byte(stdin)).Run(t.Context()))
|
||||
|
||||
repo, err := OpenRepository(t.Context(), mockRepository(repoDir))
|
||||
require.NoError(t, err)
|
||||
defer repo.Close()
|
||||
|
||||
files, err := GetAffectedFiles(t.Context(), repo, "main", "main~1", "main", nil)
|
||||
require.NoError(t, err)
|
||||
assert.ElementsMatch(t, []string{`protected/we"ird.md`, "protected/中文.md", "protected/normal.md", "base.txt", "protected/renamed.md"}, files)
|
||||
}
|
||||
+11
-4
@@ -9,6 +9,7 @@ import (
|
||||
"regexp"
|
||||
"slices"
|
||||
"strings"
|
||||
"unicode"
|
||||
|
||||
"gitea.dev/modules/util"
|
||||
)
|
||||
@@ -35,6 +36,14 @@ type globCompiler struct {
|
||||
negativeFlip bool
|
||||
}
|
||||
|
||||
// writeLiteral escapes only ASCII punctuation, an escaped letter like \d is a regexp class
|
||||
func (g *globCompiler) writeLiteral(r rune) {
|
||||
if r <= unicode.MaxASCII && !unicode.IsLetter(r) && !unicode.IsDigit(r) {
|
||||
g.builder.WriteByte('\\')
|
||||
}
|
||||
g.builder.WriteRune(r)
|
||||
}
|
||||
|
||||
// compileChars compiles character class patterns like [abc] or [!abc]
|
||||
func (g *globCompiler) compileChars() error {
|
||||
g.builder.WriteByte('[')
|
||||
@@ -56,8 +65,7 @@ func (g *globCompiler) compileChars() error {
|
||||
if g.pos >= len(g.globPattern) {
|
||||
return errors.New("unterminated character class escape")
|
||||
}
|
||||
g.builder.WriteByte('\\')
|
||||
g.builder.WriteRune(g.globPattern[g.pos])
|
||||
g.writeLiteral(g.globPattern[g.pos])
|
||||
g.pos++
|
||||
} else {
|
||||
g.builder.WriteRune(c)
|
||||
@@ -135,8 +143,7 @@ func (g *globCompiler) compile(subPattern bool) error {
|
||||
if g.pos >= len(g.globPattern) {
|
||||
return errors.New("no character to escape")
|
||||
}
|
||||
g.builder.WriteByte('\\')
|
||||
g.builder.WriteRune(g.globPattern[g.pos])
|
||||
g.writeLiteral(g.globPattern[g.pos])
|
||||
g.pos++
|
||||
case '.', '^', '$', '(', ')', '|':
|
||||
g.builder.WriteByte('\\')
|
||||
|
||||
@@ -90,6 +90,9 @@ func TestGlob(t *testing.T) {
|
||||
glob(true, "?at", "fat"),
|
||||
glob(true, "*", "abc"),
|
||||
glob(true, `\*`, "*"),
|
||||
glob(true, `a\d`, "ad"),
|
||||
glob(true, `[\d]`, "d"),
|
||||
glob(false, `[a\-z]`, "m"),
|
||||
glob(true, "**", "a.b.c", '.'),
|
||||
|
||||
glob(false, "?at", "at"),
|
||||
|
||||
@@ -9,6 +9,7 @@ import (
|
||||
repo_model "gitea.dev/models/repo"
|
||||
"gitea.dev/modules/git"
|
||||
"gitea.dev/modules/git/languagestats"
|
||||
"gitea.dev/modules/globallock"
|
||||
"gitea.dev/modules/graceful"
|
||||
"gitea.dev/modules/log"
|
||||
"gitea.dev/modules/process"
|
||||
@@ -23,6 +24,13 @@ func (db *DBIndexer) Index(id int64) error {
|
||||
ctx, _, finished := process.GetManager().AddContext(graceful.GetManager().ShutdownContext(), fmt.Sprintf("Stats.DB Index Repo[%d]", id))
|
||||
defer finished()
|
||||
|
||||
// the unique queue doesn't stop two workers from indexing the same repository at once
|
||||
releaser, err := globallock.Lock(ctx, fmt.Sprintf("repo_stats_index_%d", id))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer releaser()
|
||||
|
||||
repo, err := repo_model.GetRepositoryByID(ctx, id)
|
||||
if err != nil {
|
||||
return err
|
||||
|
||||
@@ -31,8 +31,9 @@ func (st *Sanitizer) createDefaultPolicy() *bluemonday.Policy {
|
||||
// Chroma always uses 1-2 letters for style names, we could tolerate it at the moment
|
||||
policy.AllowAttrs("class").Matching(regexp.MustCompile(`^\w{0,2}$`)).OnElements("span")
|
||||
|
||||
// Line numbers on codepreview
|
||||
// Line numbers and paste behavior on codepreview
|
||||
policy.AllowAttrs("data-line-number").OnElements("span")
|
||||
policy.AllowAttrs("data-paste-markdown-skip").OnElements("table")
|
||||
|
||||
// emoji aliases for dark theme inversion
|
||||
policy.AllowAttrs("data-alias").OnElements("span")
|
||||
|
||||
@@ -49,6 +49,8 @@ func TestSanitizer(t *testing.T) {
|
||||
`<p style="bad-color: red">Hello World</p>`, `<p>Hello World</p>`,
|
||||
`<code style="bad-color: red">Hello World</code>`, `<code>Hello World</code>`,
|
||||
|
||||
`<table data-paste-markdown-skip><tr><td>1</td></tr></table>`, `<table data-paste-markdown-skip=""><tr><td>1</td></tr></table>`,
|
||||
|
||||
// Org mode status of list items.
|
||||
`<li class="checked"></li>`, `<li class="checked"></li>`,
|
||||
`<li class="unchecked"></li>`, `<li class="unchecked"></li>`,
|
||||
|
||||
@@ -154,6 +154,21 @@ func (d *RetryDownloader) GetComments(ctx context.Context, commentable Commentab
|
||||
return comments, isEnd, err
|
||||
}
|
||||
|
||||
func (d *RetryDownloader) GetAllComments(ctx context.Context, page, perPage int) ([]*Comment, bool, error) {
|
||||
var (
|
||||
comments []*Comment
|
||||
isEnd bool
|
||||
err error
|
||||
)
|
||||
|
||||
err = d.retry(ctx, func(ctx context.Context) error {
|
||||
comments, isEnd, err = d.Downloader.GetAllComments(ctx, page, perPage)
|
||||
return err
|
||||
})
|
||||
|
||||
return comments, isEnd, err
|
||||
}
|
||||
|
||||
// GetPullRequests returns a repository's pull requests with retry
|
||||
func (d *RetryDownloader) GetPullRequests(ctx context.Context, page, perPage int) ([]*PullRequest, bool, error) {
|
||||
var (
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
// Copyright 2026 The Gitea Authors. All rights reserved.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package migration
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
type failingCommentsDownloader struct {
|
||||
NullDownloader
|
||||
attempts int
|
||||
}
|
||||
|
||||
func (d *failingCommentsDownloader) GetAllComments(_ctx context.Context, _page, _perPage int) ([]*Comment, bool, error) {
|
||||
d.attempts++
|
||||
return nil, false, errors.New("permission denied")
|
||||
}
|
||||
|
||||
func TestRetryDownloaderExhaustsAttempts(t *testing.T) {
|
||||
source := &failingCommentsDownloader{}
|
||||
_, _, err := NewRetryDownloader(source, 3, 0).GetAllComments(t.Context(), 1, 50)
|
||||
assert.EqualError(t, err, "permission denied")
|
||||
assert.Equal(t, 3, source.attempts)
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
// Copyright 2026 The Gitea Authors. All rights reserved.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package debian
|
||||
|
||||
import (
|
||||
"io"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"gitea.dev/modules/util"
|
||||
)
|
||||
|
||||
const arMagic = "!<arch>\n"
|
||||
|
||||
type arReader struct {
|
||||
io.LimitedReader
|
||||
pad int64
|
||||
}
|
||||
|
||||
func newArReader(r io.Reader) (*arReader, error) {
|
||||
var magic [len(arMagic)]byte
|
||||
if _, err := io.ReadFull(r, magic[:]); err != nil || string(magic[:]) != arMagic {
|
||||
return nil, GlobalVars().ErrInvalidArchive
|
||||
}
|
||||
return &arReader{LimitedReader: io.LimitedReader{R: r}}, nil
|
||||
}
|
||||
|
||||
func (ar *arReader) next() (string, error) {
|
||||
if _, err := io.CopyN(io.Discard, ar.R, ar.N+ar.pad); err != nil {
|
||||
return "", GlobalVars().ErrInvalidArchive
|
||||
}
|
||||
var header [60]byte
|
||||
if _, err := io.ReadFull(ar.R, header[:]); err != nil {
|
||||
return "", util.Iif(err == io.EOF, err, GlobalVars().ErrInvalidArchive)
|
||||
}
|
||||
size, err := strconv.ParseInt(strings.TrimRight(string(header[48:58]), " "), 10, 64)
|
||||
if err != nil || size < 0 || string(header[58:]) != "`\n" {
|
||||
return "", GlobalVars().ErrInvalidArchive
|
||||
}
|
||||
ar.N, ar.pad = size, size%2
|
||||
return strings.TrimSuffix(strings.TrimRight(string(header[:16]), " "), "/"), nil // GNU ar terminates names with a slash
|
||||
}
|
||||
@@ -17,7 +17,6 @@ import (
|
||||
"gitea.dev/modules/validation"
|
||||
"gitea.dev/modules/zstd"
|
||||
|
||||
"github.com/blakesmith/ar"
|
||||
"github.com/ulikunitz/xz"
|
||||
)
|
||||
|
||||
@@ -38,6 +37,7 @@ const (
|
||||
)
|
||||
|
||||
var GlobalVars = sync.OnceValue(func() (ret struct {
|
||||
ErrInvalidArchive error
|
||||
ErrMissingControlFile error
|
||||
ErrUnsupportedCompression error
|
||||
ErrInvalidName error
|
||||
@@ -49,6 +49,7 @@ var GlobalVars = sync.OnceValue(func() (ret struct {
|
||||
symbolPattern *regexp.Regexp
|
||||
},
|
||||
) {
|
||||
ret.ErrInvalidArchive = util.NewInvalidArgumentErrorf("package archive is invalid")
|
||||
ret.ErrMissingControlFile = util.NewInvalidArgumentErrorf("control file is missing")
|
||||
ret.ErrUnsupportedCompression = util.NewInvalidArgumentErrorf("unsupported compression algorithm")
|
||||
ret.ErrInvalidName = util.NewInvalidArgumentErrorf("package name is invalid")
|
||||
@@ -90,10 +91,13 @@ func IsValidDistributionOrComponent(s string) bool {
|
||||
// ParsePackage parses the Debian package file
|
||||
// https://manpages.debian.org/bullseye/dpkg-dev/deb.5.en.html
|
||||
func ParsePackage(r io.Reader) (*Package, error) {
|
||||
arr := ar.NewReader(r)
|
||||
arr, err := newArReader(r)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
for {
|
||||
hd, err := arr.Next()
|
||||
name, err := arr.next()
|
||||
if err == io.EOF {
|
||||
break
|
||||
}
|
||||
@@ -101,11 +105,9 @@ func ParsePackage(r io.Reader) (*Package, error) {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if strings.HasPrefix(hd.Name, controlTar) {
|
||||
if strings.HasPrefix(name, controlTar) {
|
||||
var inner io.Reader
|
||||
// https://man7.org/linux/man-pages/man5/deb-split.5.html#FORMAT
|
||||
// The file names might contain a trailing slash (since dpkg 1.15.6).
|
||||
switch strings.TrimSuffix(hd.Name[len(controlTar):], "/") {
|
||||
switch name[len(controlTar):] {
|
||||
case "":
|
||||
inner = arr
|
||||
case ".gz":
|
||||
@@ -142,7 +144,7 @@ func ParsePackage(r io.Reader) (*Package, error) {
|
||||
for {
|
||||
hd, err := tr.Next()
|
||||
if err == io.EOF {
|
||||
break
|
||||
return nil, GlobalVars().ErrMissingControlFile
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
|
||||
@@ -7,13 +7,14 @@ import (
|
||||
"archive/tar"
|
||||
"bytes"
|
||||
"compress/gzip"
|
||||
"fmt"
|
||||
"io"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"gitea.dev/modules/util"
|
||||
"gitea.dev/modules/zstd"
|
||||
|
||||
"github.com/blakesmith/ar"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/ulikunitz/xz"
|
||||
)
|
||||
@@ -28,49 +29,39 @@ const (
|
||||
)
|
||||
|
||||
func TestParsePackage(t *testing.T) {
|
||||
createArchive := func(files map[string][]byte) io.Reader {
|
||||
var buf bytes.Buffer
|
||||
aw := ar.NewWriter(&buf)
|
||||
aw.WriteGlobalHeader()
|
||||
for filename, content := range files {
|
||||
hdr := &ar.Header{
|
||||
Name: filename,
|
||||
Mode: 0o600,
|
||||
Size: int64(len(content)),
|
||||
}
|
||||
aw.WriteHeader(hdr)
|
||||
aw.Write(content)
|
||||
}
|
||||
return &buf
|
||||
member := func(name, content string) string {
|
||||
return fmt.Sprintf("%-48s%-10d`\n%s%s", name, len(content), content, strings.Repeat("\n", len(content)%2))
|
||||
}
|
||||
debianBinary := member("debian-binary", "2.0\n")
|
||||
|
||||
t.Run("MissingControlFile", func(t *testing.T) {
|
||||
data := createArchive(map[string][]byte{"dummy.txt": {}})
|
||||
var buf bytes.Buffer
|
||||
tw := tar.NewWriter(&buf)
|
||||
tw.WriteHeader(&tar.Header{
|
||||
Name: "control",
|
||||
Mode: 0o600,
|
||||
Size: 50,
|
||||
})
|
||||
tw.Write([]byte("Package: gitea\nVersion: 1.0.0\nArchitecture: amd64\n"))
|
||||
tw.Close()
|
||||
|
||||
p, err := ParsePackage(data)
|
||||
assert.Nil(t, p)
|
||||
assert.ErrorIs(t, err, GlobalVars().ErrMissingControlFile)
|
||||
t.Run("Invalid", func(t *testing.T) {
|
||||
for data, expected := range map[string]error{
|
||||
"!<ARCH>\n" + debianBinary: GlobalVars().ErrInvalidArchive,
|
||||
arMagic + debianBinary[:20]: GlobalVars().ErrInvalidArchive,
|
||||
arMagic + debianBinary[:62]: GlobalVars().ErrInvalidArchive,
|
||||
arMagic + member("control.tar", "")[:58] + "\n\n": GlobalVars().ErrInvalidArchive,
|
||||
arMagic + fmt.Sprintf("%-48s%-10d`\n", "control.tar", -1): GlobalVars().ErrInvalidArchive,
|
||||
arMagic + member("dummy.txt", "x"): GlobalVars().ErrMissingControlFile,
|
||||
arMagic + member("control.tar", "") + member("control.tar", buf.String()): GlobalVars().ErrMissingControlFile,
|
||||
arMagic + member("control.tar.foo", ""): GlobalVars().ErrUnsupportedCompression,
|
||||
} {
|
||||
p, err := ParsePackage(strings.NewReader(data))
|
||||
assert.Nil(t, p)
|
||||
assert.ErrorIs(t, err, expected, "%q", data)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Compression", func(t *testing.T) {
|
||||
t.Run("Unsupported", func(t *testing.T) {
|
||||
data := createArchive(map[string][]byte{"control.tar.foo": {}})
|
||||
|
||||
p, err := ParsePackage(data)
|
||||
assert.Nil(t, p)
|
||||
assert.ErrorIs(t, err, GlobalVars().ErrUnsupportedCompression)
|
||||
})
|
||||
|
||||
var buf bytes.Buffer
|
||||
tw := tar.NewWriter(&buf)
|
||||
tw.WriteHeader(&tar.Header{
|
||||
Name: "control",
|
||||
Mode: 0o600,
|
||||
Size: 50,
|
||||
})
|
||||
tw.Write([]byte("Package: gitea\nVersion: 1.0.0\nArchitecture: amd64\n"))
|
||||
tw.Close()
|
||||
|
||||
cases := []struct {
|
||||
Extension string
|
||||
WriterFactory func(io.Writer) io.WriteCloser
|
||||
@@ -110,21 +101,12 @@ func TestParsePackage(t *testing.T) {
|
||||
w.Write(buf.Bytes())
|
||||
w.Close()
|
||||
|
||||
data := createArchive(map[string][]byte{"control.tar" + c.Extension: cbuf.Bytes()})
|
||||
|
||||
p, err := ParsePackage(data)
|
||||
assert.NotNil(t, p)
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, "gitea", p.Name)
|
||||
|
||||
t.Run("TrailingSlash", func(t *testing.T) {
|
||||
data := createArchive(map[string][]byte{"control.tar" + c.Extension + "/": cbuf.Bytes()})
|
||||
|
||||
p, err := ParsePackage(data)
|
||||
for _, suffix := range []string{"", "/"} {
|
||||
p, err := ParsePackage(strings.NewReader(arMagic + debianBinary + member("control.tar"+c.Extension+suffix, cbuf.String())))
|
||||
assert.NotNil(t, p)
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, "gitea", p.Name)
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
@@ -5,10 +5,8 @@ package queue
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sync/atomic"
|
||||
|
||||
"gitea.dev/modules/nosql"
|
||||
"gitea.dev/modules/queue/lqinternal"
|
||||
|
||||
"gitea.com/lunny/levelqueue"
|
||||
"github.com/syndtr/goleveldb/leveldb"
|
||||
@@ -16,7 +14,7 @@ import (
|
||||
|
||||
type baseLevelQueue struct {
|
||||
*baseLevelQueueCommonImpl
|
||||
internal atomic.Pointer[levelqueue.Queue]
|
||||
internal *levelqueue.Queue
|
||||
|
||||
conn string
|
||||
cfg *BaseConfig
|
||||
@@ -41,12 +39,11 @@ func newBaseLevelQueueSimple(cfg *BaseConfig) (baseQueue, error) {
|
||||
return nil, err
|
||||
}
|
||||
q := &baseLevelQueue{conn: conn, cfg: cfg, db: db}
|
||||
lq, err := levelqueue.NewQueue(db, []byte(cfg.QueueFullName), false)
|
||||
q.internal, err = levelqueue.NewQueue(db, []byte(cfg.QueueFullName), false)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
q.internal.Store(lq)
|
||||
q.baseLevelQueueCommonImpl = baseLevelQueueCommon(q.cfg, nil, func() baseLevelQueuePushPoper { return q.internal.Load() })
|
||||
q.baseLevelQueueCommonImpl = baseLevelQueueCommon(q.cfg, nil, q.internal)
|
||||
return q, nil
|
||||
}
|
||||
|
||||
@@ -55,24 +52,16 @@ func (q *baseLevelQueue) HasItem(ctx context.Context, data []byte) (bool, error)
|
||||
}
|
||||
|
||||
func (q *baseLevelQueue) Len(ctx context.Context) (int, error) {
|
||||
return int(q.internal.Load().Len()), nil
|
||||
return int(q.internal.Len()), nil
|
||||
}
|
||||
|
||||
func (q *baseLevelQueue) Close() error {
|
||||
err := q.internal.Load().Close()
|
||||
err := q.internal.Close()
|
||||
_ = nosql.GetManager().CloseLevelDB(q.conn)
|
||||
q.db = nil // the db is not managed by us, it's managed by the nosql manager
|
||||
return err
|
||||
}
|
||||
|
||||
func (q *baseLevelQueue) RemoveAll(ctx context.Context) error {
|
||||
lqinternal.RemoveLevelQueueKeys(q.db, []byte(q.cfg.QueueFullName))
|
||||
lq, err := levelqueue.NewQueue(q.db, []byte(q.cfg.QueueFullName), false)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
old := q.internal.Load()
|
||||
q.internal.Store(lq)
|
||||
_ = old.Close() // Not ideal for concurrency. Luckily, the levelqueue only sets its db=nil because it doesn't manage the db, so far so good
|
||||
return nil
|
||||
return q.internal.RemoveAll()
|
||||
}
|
||||
@@ -26,9 +26,9 @@ type baseLevelQueuePushPoper interface {
|
||||
|
||||
type baseLevelQueueCommonImpl struct {
|
||||
*baseQueueNotifiable
|
||||
length int
|
||||
internalFunc func() baseLevelQueuePushPoper
|
||||
muCommon *sync.Mutex
|
||||
length int
|
||||
internal baseLevelQueuePushPoper
|
||||
muCommon *sync.Mutex
|
||||
}
|
||||
|
||||
func (q *baseLevelQueueCommonImpl) PushItem(ctx context.Context, data []byte) error {
|
||||
@@ -38,11 +38,11 @@ func (q *baseLevelQueueCommonImpl) PushItem(ctx context.Context, data []byte) er
|
||||
defer q.muCommon.Unlock()
|
||||
}
|
||||
|
||||
cnt := int(q.internalFunc().Len())
|
||||
cnt := int(q.internal.Len())
|
||||
if cnt >= q.length {
|
||||
return true, nil, nil
|
||||
}
|
||||
retry, err = false, q.internalFunc().RPush(data)
|
||||
retry, err = false, q.internal.RPush(data)
|
||||
if err == levelqueue.ErrAlreadyInQueue {
|
||||
err = ErrAlreadyInQueue
|
||||
}
|
||||
@@ -61,7 +61,7 @@ func (q *baseLevelQueueCommonImpl) PopItem(ctx context.Context) ([]byte, error)
|
||||
defer q.muCommon.Unlock()
|
||||
}
|
||||
|
||||
data, err = q.internalFunc().LPop()
|
||||
data, err = q.internal.LPop()
|
||||
if err == levelqueue.ErrNotFound {
|
||||
return true, nil, nil
|
||||
}
|
||||
@@ -72,8 +72,8 @@ func (q *baseLevelQueueCommonImpl) PopItem(ctx context.Context) ([]byte, error)
|
||||
})
|
||||
}
|
||||
|
||||
func baseLevelQueueCommon(cfg *BaseConfig, mu *sync.Mutex, internalFunc func() baseLevelQueuePushPoper) *baseLevelQueueCommonImpl {
|
||||
return &baseLevelQueueCommonImpl{length: cfg.Length, muCommon: mu, internalFunc: internalFunc, baseQueueNotifiable: newBaseQueueNotifiable()}
|
||||
func baseLevelQueueCommon(cfg *BaseConfig, mu *sync.Mutex, internal baseLevelQueuePushPoper) *baseLevelQueueCommonImpl {
|
||||
return &baseLevelQueueCommonImpl{length: cfg.Length, muCommon: mu, internal: internal, baseQueueNotifiable: newBaseQueueNotifiable()}
|
||||
}
|
||||
|
||||
func prepareLevelDB(cfg *BaseConfig) (conn string, db *leveldb.DB, err error) {
|
||||
|
||||
@@ -6,13 +6,9 @@ package queue
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"gitea.dev/modules/queue/lqinternal"
|
||||
"gitea.dev/modules/setting"
|
||||
|
||||
"gitea.com/lunny/levelqueue"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
"github.com/syndtr/goleveldb/leveldb"
|
||||
)
|
||||
|
||||
func TestBaseLevelDB(t *testing.T) {
|
||||
@@ -27,53 +23,3 @@ func TestBaseLevelDB(t *testing.T) {
|
||||
testQueueBasic(t, newBaseLevelQueueSimple, toBaseConfig("baseLevelQueue", setting.QueueSettings{Datadir: t.TempDir() + "/queue-test", Length: 10}), optsSimple)
|
||||
testQueueBasic(t, newBaseLevelQueueUnique, toBaseConfig("baseLevelQueueUnique", setting.QueueSettings{ConnStr: "leveldb://" + t.TempDir() + "/queue-test", Length: 10}), optsUnique)
|
||||
}
|
||||
|
||||
func TestCorruptedLevelQueue(t *testing.T) {
|
||||
// sometimes the levelqueue could be in a corrupted state, this test is to make sure it can recover from it
|
||||
dbDir := t.TempDir() + "/levelqueue-test"
|
||||
db, err := leveldb.OpenFile(dbDir, nil)
|
||||
require.NoError(t, err)
|
||||
defer db.Close()
|
||||
|
||||
assert.NoError(t, db.Put([]byte("other-key"), []byte("other-value"), nil))
|
||||
|
||||
nameQueuePrefix := []byte("queue_name")
|
||||
nameSetPrefix := []byte("set_name")
|
||||
lq, err := levelqueue.NewUniqueQueue(db, nameQueuePrefix, nameSetPrefix, false)
|
||||
assert.NoError(t, err)
|
||||
assert.NoError(t, lq.RPush([]byte("item-1")))
|
||||
|
||||
itemKey := lqinternal.QueueItemKeyBytes(nameQueuePrefix, 1)
|
||||
itemValue, err := db.Get(itemKey, nil)
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, []byte("item-1"), itemValue)
|
||||
|
||||
// there should be 5 keys in db: queue low, queue high, 1 queue item, 1 set item, and "other-key"
|
||||
keys := lqinternal.ListLevelQueueKeys(db)
|
||||
assert.Len(t, keys, 5)
|
||||
|
||||
// delete the queue item key, to corrupt the queue
|
||||
assert.NoError(t, db.Delete(itemKey, nil))
|
||||
// now the queue is corrupted, it never works again
|
||||
_, err = lq.LPop()
|
||||
assert.ErrorIs(t, err, levelqueue.ErrNotFound)
|
||||
assert.NoError(t, lq.Close())
|
||||
|
||||
// remove all the queue related keys to reset the queue
|
||||
lqinternal.RemoveLevelQueueKeys(db, nameQueuePrefix)
|
||||
lqinternal.RemoveLevelQueueKeys(db, nameSetPrefix)
|
||||
// now there should be only 1 key in db: "other-key"
|
||||
keys = lqinternal.ListLevelQueueKeys(db)
|
||||
assert.Len(t, keys, 1)
|
||||
assert.Equal(t, []byte("other-key"), keys[0])
|
||||
|
||||
// re-create a queue from db
|
||||
lq, err = levelqueue.NewUniqueQueue(db, nameQueuePrefix, nameSetPrefix, false)
|
||||
assert.NoError(t, err)
|
||||
assert.NoError(t, lq.RPush([]byte("item-new-1")))
|
||||
// now the queue works again
|
||||
itemValue, err = lq.LPop()
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, []byte("item-new-1"), itemValue)
|
||||
assert.NoError(t, lq.Close())
|
||||
}
|
||||
@@ -6,10 +6,8 @@ package queue
|
||||
import (
|
||||
"context"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
|
||||
"gitea.dev/modules/nosql"
|
||||
"gitea.dev/modules/queue/lqinternal"
|
||||
|
||||
"gitea.com/lunny/levelqueue"
|
||||
"github.com/syndtr/goleveldb/leveldb"
|
||||
@@ -17,13 +15,13 @@ import (
|
||||
|
||||
type baseLevelQueueUnique struct {
|
||||
*baseLevelQueueCommonImpl
|
||||
internal atomic.Pointer[levelqueue.UniqueQueue]
|
||||
internal *levelqueue.UniqueQueue
|
||||
|
||||
conn string
|
||||
cfg *BaseConfig
|
||||
db *leveldb.DB
|
||||
|
||||
muBase sync.Mutex // the levelqueue.UniqueQueue is not thread-safe, there is no mutex protecting the underlying queue&set together
|
||||
muBase sync.Mutex // protects multi-step queue+set operations, e.g. the length check followed by a push
|
||||
}
|
||||
|
||||
var (
|
||||
@@ -37,31 +35,30 @@ func newBaseLevelQueueUnique(cfg *BaseConfig) (baseQueue, error) {
|
||||
return nil, err
|
||||
}
|
||||
q := &baseLevelQueueUnique{conn: conn, cfg: cfg, db: db}
|
||||
lq, err := levelqueue.NewUniqueQueue(db, []byte(cfg.QueueFullName), []byte(cfg.SetFullName), false)
|
||||
q.internal, err = levelqueue.NewUniqueQueue(db, []byte(cfg.QueueFullName), []byte(cfg.SetFullName), false)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
q.internal.Store(lq)
|
||||
q.baseLevelQueueCommonImpl = baseLevelQueueCommon(q.cfg, &q.muBase, func() baseLevelQueuePushPoper { return q.internal.Load() })
|
||||
q.baseLevelQueueCommonImpl = baseLevelQueueCommon(q.cfg, &q.muBase, q.internal)
|
||||
return q, nil
|
||||
}
|
||||
|
||||
func (q *baseLevelQueueUnique) HasItem(ctx context.Context, data []byte) (bool, error) {
|
||||
q.muBase.Lock()
|
||||
defer q.muBase.Unlock()
|
||||
return q.internal.Load().Has(data)
|
||||
return q.internal.Has(data)
|
||||
}
|
||||
|
||||
func (q *baseLevelQueueUnique) Len(ctx context.Context) (int, error) {
|
||||
q.muBase.Lock()
|
||||
defer q.muBase.Unlock()
|
||||
return int(q.internal.Load().Len()), nil
|
||||
return int(q.internal.Len()), nil
|
||||
}
|
||||
|
||||
func (q *baseLevelQueueUnique) Close() error {
|
||||
q.muBase.Lock()
|
||||
defer q.muBase.Unlock()
|
||||
err := q.internal.Load().Close()
|
||||
err := q.internal.Close()
|
||||
q.db = nil // the db is not managed by us, it's managed by the nosql manager
|
||||
_ = nosql.GetManager().CloseLevelDB(q.conn)
|
||||
return err
|
||||
@@ -70,14 +67,5 @@ func (q *baseLevelQueueUnique) Close() error {
|
||||
func (q *baseLevelQueueUnique) RemoveAll(ctx context.Context) error {
|
||||
q.muBase.Lock()
|
||||
defer q.muBase.Unlock()
|
||||
lqinternal.RemoveLevelQueueKeys(q.db, []byte(q.cfg.QueueFullName))
|
||||
lqinternal.RemoveLevelQueueKeys(q.db, []byte(q.cfg.SetFullName))
|
||||
lq, err := levelqueue.NewUniqueQueue(q.db, []byte(q.cfg.QueueFullName), []byte(q.cfg.SetFullName), false)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
old := q.internal.Load()
|
||||
q.internal.Store(lq)
|
||||
_ = old.Close() // Not ideal for concurrency. Luckily, the levelqueue only sets its db=nil because it doesn't manage the db, so far so good
|
||||
return nil
|
||||
return q.internal.RemoveAll()
|
||||
}
|
||||
@@ -25,7 +25,7 @@ func testQueueBasic(t *testing.T, newFn func(cfg *BaseConfig) (baseQueue, error)
|
||||
assert.NoError(t, err)
|
||||
|
||||
ctx := t.Context()
|
||||
_ = q.RemoveAll(ctx)
|
||||
assert.NoError(t, q.RemoveAll(ctx))
|
||||
cnt, err := q.Len(ctx)
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, 0, cnt)
|
||||
@@ -138,11 +138,14 @@ func testQueueBasic(t *testing.T, newFn func(cfg *BaseConfig) (baseQueue, error)
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, cfg.Length, cnt)
|
||||
|
||||
_ = q.RemoveAll(ctx)
|
||||
assert.NoError(t, q.RemoveAll(ctx))
|
||||
|
||||
cnt, err = q.Len(ctx)
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, 0, cnt)
|
||||
|
||||
// a removed payload must not stay reserved in the set, or this returns ErrAlreadyInQueue
|
||||
assert.NoError(t, q.PushItem(ctx, []byte("item-0")))
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -1,48 +0,0 @@
|
||||
// Copyright 2023 The Gitea Authors. All rights reserved.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package lqinternal
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/binary"
|
||||
|
||||
"github.com/syndtr/goleveldb/leveldb"
|
||||
"github.com/syndtr/goleveldb/leveldb/opt"
|
||||
)
|
||||
|
||||
func QueueItemIDBytes(id int64) []byte {
|
||||
buf := make([]byte, 8)
|
||||
binary.PutVarint(buf, id)
|
||||
return buf
|
||||
}
|
||||
|
||||
func QueueItemKeyBytes(prefix []byte, id int64) []byte {
|
||||
key := make([]byte, len(prefix), len(prefix)+1+8)
|
||||
copy(key, prefix)
|
||||
key = append(key, '-')
|
||||
return append(key, QueueItemIDBytes(id)...)
|
||||
}
|
||||
|
||||
func RemoveLevelQueueKeys(db *leveldb.DB, namePrefix []byte) {
|
||||
keyPrefix := make([]byte, len(namePrefix)+1)
|
||||
copy(keyPrefix, namePrefix)
|
||||
keyPrefix[len(namePrefix)] = '-'
|
||||
|
||||
it := db.NewIterator(nil, &opt.ReadOptions{Strict: opt.NoStrict})
|
||||
defer it.Release()
|
||||
for it.Next() {
|
||||
if bytes.HasPrefix(it.Key(), keyPrefix) {
|
||||
_ = db.Delete(it.Key(), nil)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func ListLevelQueueKeys(db *leveldb.DB) (res [][]byte) {
|
||||
it := db.NewIterator(nil, &opt.ReadOptions{Strict: opt.NoStrict})
|
||||
defer it.Release()
|
||||
for it.Next() {
|
||||
res = append(res, it.Key())
|
||||
}
|
||||
return res
|
||||
}
|
||||
@@ -58,5 +58,5 @@ type EditMilestoneOption struct {
|
||||
State *string `json:"state"`
|
||||
// Deadline is the due date for the milestone, use null or empty string to remove the deadline
|
||||
// swagger:strfmt date-time
|
||||
Deadline optional.Option[*string] `json:"due_on,omitzero"`
|
||||
Deadline optional.Option[*string] `json:"due_on,omitzero" form:"-"` // go-chi/binding panics validating the nil element a JSON null decodes to
|
||||
}
|
||||
@@ -86,6 +86,7 @@ type CreatePullReviewOptions struct {
|
||||
// CreatePullReviewComment represent a review comment for creation api
|
||||
type CreatePullReviewComment struct {
|
||||
// the tree path
|
||||
// required: true
|
||||
Path string `json:"path"`
|
||||
Body string `json:"body"`
|
||||
// if comment to old file line or 0
|
||||
|
||||
@@ -77,3 +77,10 @@ func SliceNilAsEmpty[T any](a []T) []T {
|
||||
}
|
||||
return a
|
||||
}
|
||||
|
||||
func MapNilAsEmpty[K comparable, V any](m map[K]V) map[K]V {
|
||||
if m == nil {
|
||||
return map[K]V{}
|
||||
}
|
||||
return m
|
||||
}
|
||||
@@ -62,7 +62,6 @@ func GetFuncInfo(fn any, friendlyName ...string) *FuncInfo {
|
||||
info = copyFuncInfo(info)
|
||||
info.shortName = name
|
||||
|
||||
funcInfoNameMap[name] = info
|
||||
funcInfoMapMu.Lock()
|
||||
funcInfoNameMap[name] = info
|
||||
funcInfoMapMu.Unlock()
|
||||
|
||||
@@ -406,6 +406,7 @@
|
||||
"auth.twofa_scratch_used": "You have used your scratch code. You have been redirected to the two-factor settings page so you may remove your device enrollment or generate a new scratch code.",
|
||||
"auth.twofa_passcode_incorrect": "Your passcode is incorrect. If you misplaced your device, use your scratch code to sign in.",
|
||||
"auth.twofa_scratch_token_incorrect": "Your scratch code is incorrect.",
|
||||
"auth.twofa_too_many_attempts": "Too many incorrect passcodes. Try again later or use your scratch code.",
|
||||
"auth.twofa_required": "You must set up two-factor authentication to get access to repositories, or try to log in again.",
|
||||
"auth.login_userpass": "Sign In",
|
||||
"auth.login_openid": "OpenID",
|
||||
@@ -1023,7 +1024,7 @@
|
||||
"repo.mirror_last_synced": "Last Synchronized",
|
||||
"repo.mirror_password_placeholder": "(Unchanged)",
|
||||
"repo.mirror_password_blank_placeholder": "(Unset)",
|
||||
"repo.mirror_password_help": "Change the username to erase a stored password.",
|
||||
"repo.mirror_password_help": "Change the username or the address to erase a stored password.",
|
||||
"repo.watchers": "Watchers",
|
||||
"repo.stargazers": "Stargazers",
|
||||
"repo.stars_remove_warning": "This will remove all stars from this repository.",
|
||||
|
||||
+1
-1
@@ -37,7 +37,7 @@
|
||||
"asciinema-player": "3.17.0",
|
||||
"chart.js": "4.5.1",
|
||||
"chartjs-plugin-zoom": "2.2.0",
|
||||
"clippie": "4.2.1",
|
||||
"clippie": "4.3.1",
|
||||
"codemirror-lang-elixir": "4.0.1",
|
||||
"colord": "2.10.0",
|
||||
"compare-versions": "6.1.1",
|
||||
|
||||
Generated
+5
-5
@@ -260,8 +260,8 @@ importers:
|
||||
specifier: 2.2.0
|
||||
version: 2.2.0(chart.js@4.5.1)
|
||||
clippie:
|
||||
specifier: 4.2.1
|
||||
version: 4.2.1
|
||||
specifier: 4.3.1
|
||||
version: 4.3.1
|
||||
codemirror-lang-elixir:
|
||||
specifier: 4.0.1
|
||||
version: 4.0.1
|
||||
@@ -2073,8 +2073,8 @@ packages:
|
||||
citeproc@2.4.63:
|
||||
resolution: {integrity: sha512-68F95Bp4UbgZU/DBUGQn0qV3HDZLCdI9+Bb2ByrTaNJDL5VEm9LqaiNaxljsvoaExSLEXe1/r6n2Z06SCzW3/Q==}
|
||||
|
||||
clippie@4.2.1:
|
||||
resolution: {integrity: sha512-+Shk4WLaaBtxTwgaspGnFm/WrtjZCVCKsl66mPglNRj6B+OzgIYnp4LX7EjW1UTG5NfJsW60jxwV8EvqtyrDUA==}
|
||||
clippie@4.3.1:
|
||||
resolution: {integrity: sha512-YGBIrB/O/339z1sl0voeJ/MuRkn7EmLTsZAlHtnZD0i1v6uEFRr6Ju8WQ0faf9n5r/1WYX7s3qFQ7I+syUOX7g==}
|
||||
|
||||
codemirror-lang-elixir@4.0.1:
|
||||
resolution: {integrity: sha512-z6W/XB4b7TZrp9EZYBGVq93vQfvKbff+1iM8YZaVErL0dguBAeLmVRlEv1NuDZHOP1qjJ3NwyibkUkNWn7q9VQ==}
|
||||
@@ -6433,7 +6433,7 @@ snapshots:
|
||||
|
||||
citeproc@2.4.63: {}
|
||||
|
||||
clippie@4.2.1: {}
|
||||
clippie@4.3.1: {}
|
||||
|
||||
codemirror-lang-elixir@4.0.1:
|
||||
dependencies:
|
||||
|
||||
@@ -71,7 +71,7 @@ func PackagesUniverse(ctx *context.Context) {
|
||||
LocationType: "opscode",
|
||||
LocationPath: baseURL,
|
||||
DownloadURL: fmt.Sprintf("%s/cookbooks/%s/versions/%s/download", baseURL, url.PathEscape(pd.Package.Name), pd.Version.Version),
|
||||
Dependencies: packages_model.DescriptorMetadata[*chef_module.Metadata](pd).Dependencies,
|
||||
Dependencies: util.MapNilAsEmpty(packages_model.DescriptorMetadata[*chef_module.Metadata](pd).Dependencies),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -250,7 +250,7 @@ func PackageVersionMetadata(ctx *context.Context) {
|
||||
Cookbook: baseURL,
|
||||
File: fmt.Sprintf("%s/versions/%s/download", baseURL, pd.Version.Version),
|
||||
License: metadata.License,
|
||||
Dependencies: metadata.Dependencies,
|
||||
Dependencies: util.MapNilAsEmpty(metadata.Dependencies),
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -36,7 +36,7 @@ func saveAsPackageBlob(ctx context.Context, hsr packages_module.HashedSizeReader
|
||||
}
|
||||
|
||||
func saveAsPackageBlobInternal(ctx context.Context, hsr packages_module.HashedSizeReader, pci *packages_service.PackageCreationInfo, pb *packages_model.PackageBlob) (*packages_model.PackageBlob, error) {
|
||||
exists := false
|
||||
blobCreated := false
|
||||
|
||||
contentStore := packages_module.NewContentStore()
|
||||
|
||||
@@ -49,14 +49,16 @@ func saveAsPackageBlobInternal(ctx context.Context, hsr packages_module.HashedSi
|
||||
if err := packages_service.CheckSizeQuotaExceeded(ctx, pci.Creator, pci.Owner, packages_model.TypeContainer, hsr.Size()); err != nil {
|
||||
return err
|
||||
}
|
||||
var exists bool
|
||||
pb, exists, err = packages_service.GetOrSavePackageBlob(ctx, contentStore, pb, hsr)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
blobCreated = !exists
|
||||
return createFileForBlob(ctx, uploadVersion, pb)
|
||||
})
|
||||
if err != nil {
|
||||
if !exists && pb != nil { // pb can be nil if GetOrInsertBlob failed
|
||||
if blobCreated {
|
||||
if err := contentStore.Delete(packages_module.BlobHash256Key(pb.HashSHA256)); err != nil {
|
||||
log.Error("Error deleting package blob from content store: %v", err)
|
||||
}
|
||||
|
||||
@@ -45,7 +45,8 @@ var globalVars = sync.OnceValue(func() (ret struct {
|
||||
imageNamePattern, referencePattern *regexp.Regexp
|
||||
},
|
||||
) {
|
||||
ret.imageNamePattern = regexp.MustCompile(`\A[a-z0-9]+([._-][a-z0-9]+)*(/[a-z0-9]+([._-][a-z0-9]+)*)*\z`)
|
||||
// ref: https://github.com/opencontainers/distribution-spec/blob/v1.1.1/spec.md#pulling-manifests
|
||||
ret.imageNamePattern = regexp.MustCompile(`\A[a-z0-9]+((\.|_|__|-+)[a-z0-9]+)*(/[a-z0-9]+((\.|_|__|-+)[a-z0-9]+)*)*\z`)
|
||||
ret.referencePattern = regexp.MustCompile(`\A[a-zA-Z0-9_][a-zA-Z0-9._-]{0,127}\z`)
|
||||
return ret
|
||||
})
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
// Copyright 2026 The Gitea Authors. All rights reserved.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package container
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestImageNamePattern(t *testing.T) {
|
||||
for _, name := range []string{"a", "a.b", "a_b", "a__b", "a-b", "a--b", "a---b", "sub/a__b/c--d"} {
|
||||
assert.True(t, globalVars().imageNamePattern.MatchString(name), name)
|
||||
}
|
||||
for _, name := range []string{"", "A", "a___b", "a._b", "-a", "a-", "a//b", "/a", "a/"} {
|
||||
assert.False(t, globalVars().imageNamePattern.MatchString(name), name)
|
||||
}
|
||||
}
|
||||
@@ -14,6 +14,7 @@ import (
|
||||
"gitea.dev/modules/util"
|
||||
"gitea.dev/modules/web"
|
||||
"gitea.dev/routers/api/v1/utils"
|
||||
"gitea.dev/services/audit"
|
||||
"gitea.dev/services/context"
|
||||
webhook_service "gitea.dev/services/webhook"
|
||||
)
|
||||
@@ -191,8 +192,12 @@ func DeleteHook(ctx *context.APIContext) {
|
||||
// "204":
|
||||
// "$ref": "#/responses/empty"
|
||||
|
||||
hookID := ctx.PathParamInt64("id")
|
||||
if err := webhook.DeleteDefaultSystemWebhook(ctx, hookID); err != nil {
|
||||
hook, err := webhook.GetSystemOrDefaultWebhook(ctx, ctx.PathParamInt64("id"))
|
||||
if err != nil {
|
||||
ctx.APIErrorAuto(err)
|
||||
return
|
||||
}
|
||||
if err := webhook.DeleteDefaultSystemWebhook(ctx, hook.ID); err != nil {
|
||||
if errors.Is(err, util.ErrNotExist) {
|
||||
ctx.APIErrorNotFound()
|
||||
} else {
|
||||
@@ -200,5 +205,6 @@ func DeleteHook(ctx *context.APIContext) {
|
||||
}
|
||||
return
|
||||
}
|
||||
audit.RecordScoped(ctx, nil, nil, audit.WebhookRemove, "webhook", hook.URL)
|
||||
ctx.Status(http.StatusNoContent)
|
||||
}
|
||||
+28
-35
@@ -426,16 +426,6 @@ func reqSiteAdmin() func(ctx *context.APIContext) {
|
||||
}
|
||||
}
|
||||
|
||||
// reqOwner user should be the owner of the repo or site admin.
|
||||
func reqOwner() func(ctx *context.APIContext) {
|
||||
return func(ctx *context.APIContext) {
|
||||
if !ctx.Repo.Permission.IsOwner() && !ctx.IsUserSiteAdmin() {
|
||||
ctx.APIError(http.StatusForbidden, "user should be the owner of the repo")
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func reqRepoDangerZone() func(ctx *context.APIContext) {
|
||||
return func(ctx *context.APIContext) {
|
||||
if !access_model.CanDoerManageRepoDangerZone(ctx, ctx.Doer, ctx.Repo.Repository, &ctx.Repo.Permission) {
|
||||
@@ -449,22 +439,24 @@ func reqRepoDangerZone() func(ctx *context.APIContext) {
|
||||
func reqSelfOrAdmin() func(ctx *context.APIContext) {
|
||||
return func(ctx *context.APIContext) {
|
||||
if !ctx.IsUserSiteAdmin() && ctx.ContextUser != ctx.Doer {
|
||||
ctx.APIError(http.StatusForbidden, "doer should be the site admin or be same as the contextUser")
|
||||
ctx.APIError(http.StatusForbidden, "doer should be the site admin or be same as the target user")
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// reqAdmin user should be an owner or a collaborator with admin write of a repository, or site admin
|
||||
func reqAdmin() func(ctx *context.APIContext) {
|
||||
func reqRepoAdmin() func(ctx *context.APIContext) {
|
||||
return func(ctx *context.APIContext) {
|
||||
if !ctx.IsUserRepoAdmin() && !ctx.IsUserSiteAdmin() {
|
||||
ctx.APIError(http.StatusForbidden, "user should be an owner or a collaborator with admin write of a repository")
|
||||
ctx.APIError(http.StatusForbidden, "user should be an owner or have admin permission of the repository")
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: refactor to use reqRepoAdmin instead of reqAdmin in the future
|
||||
func reqAdmin() func(ctx *context.APIContext) { return reqRepoAdmin() }
|
||||
|
||||
// reqRepoWriter user should have a permission to write to a repo, or be a site admin
|
||||
func reqRepoWriter(unitTypes ...unit.Type) func(ctx *context.APIContext) {
|
||||
return func(ctx *context.APIContext) {
|
||||
@@ -1039,36 +1031,37 @@ func Routes() *web.Router {
|
||||
addActionsRoutes := func(
|
||||
m *web.Router,
|
||||
reqReaderCheck func(ctx *context.APIContext),
|
||||
reqOwnerCheck func(ctx *context.APIContext),
|
||||
reqManagerCheck func(ctx *context.APIContext),
|
||||
act actions.API,
|
||||
) {
|
||||
m.Group("/actions", func() {
|
||||
m.Group("/secrets", func() {
|
||||
m.Get("", reqToken(), reqOwnerCheck, act.ListActionsSecrets)
|
||||
m.Get("", act.ListActionsSecrets)
|
||||
m.Combo("/{secretname}").
|
||||
Put(reqToken(), reqOwnerCheck, bind(api.CreateOrUpdateSecretOption{}), act.CreateOrUpdateSecret).
|
||||
Delete(reqToken(), reqOwnerCheck, act.DeleteSecret)
|
||||
})
|
||||
Put(bind(api.CreateOrUpdateSecretOption{}), act.CreateOrUpdateSecret).
|
||||
Delete(act.DeleteSecret)
|
||||
}, reqManagerCheck)
|
||||
|
||||
m.Group("/variables", func() {
|
||||
m.Get("", reqToken(), reqOwnerCheck, act.ListVariables)
|
||||
m.Get("", act.ListVariables)
|
||||
m.Combo("/{variablename}").
|
||||
Get(reqToken(), reqOwnerCheck, act.GetVariable).
|
||||
Delete(reqToken(), reqOwnerCheck, act.DeleteVariable).
|
||||
Post(reqToken(), reqOwnerCheck, bind(api.CreateVariableOption{}), act.CreateVariable).
|
||||
Put(reqToken(), reqOwnerCheck, bind(api.UpdateVariableOption{}), act.UpdateVariable)
|
||||
})
|
||||
Get(act.GetVariable).
|
||||
Delete(act.DeleteVariable).
|
||||
Post(bind(api.CreateVariableOption{}), act.CreateVariable).
|
||||
Put(bind(api.UpdateVariableOption{}), act.UpdateVariable)
|
||||
}, reqManagerCheck)
|
||||
|
||||
m.Group("/runners", func() {
|
||||
m.Get("", reqToken(), reqOwnerCheck, act.ListRunners)
|
||||
m.Post("/registration-token", reqToken(), reqOwnerCheck, act.CreateRegistrationToken)
|
||||
m.Get("/{runner_id}", reqToken(), reqOwnerCheck, act.GetRunner)
|
||||
m.Delete("/{runner_id}", reqToken(), reqOwnerCheck, act.DeleteRunner)
|
||||
m.Patch("/{runner_id}", reqToken(), reqOwnerCheck, bind(api.EditActionRunnerOption{}), act.UpdateRunner)
|
||||
})
|
||||
m.Get("/runs", reqToken(), reqReaderCheck, act.ListWorkflowRuns)
|
||||
m.Get("/jobs", reqToken(), reqReaderCheck, act.ListWorkflowJobs)
|
||||
})
|
||||
m.Get("", act.ListRunners)
|
||||
m.Post("/registration-token", act.CreateRegistrationToken)
|
||||
m.Get("/{runner_id}", act.GetRunner)
|
||||
m.Delete("/{runner_id}", act.DeleteRunner)
|
||||
m.Patch("/{runner_id}", bind(api.EditActionRunnerOption{}), act.UpdateRunner)
|
||||
}, reqManagerCheck)
|
||||
|
||||
m.Get("/runs", reqReaderCheck, act.ListWorkflowRuns)
|
||||
m.Get("/jobs", reqReaderCheck, act.ListWorkflowJobs)
|
||||
}, reqToken())
|
||||
}
|
||||
|
||||
m.Group("", func() {
|
||||
@@ -1328,7 +1321,7 @@ func Routes() *web.Router {
|
||||
}, reqToken())
|
||||
|
||||
// Adds the routes for secrets/variables and runner management
|
||||
addActionsRoutes(m, reqRepoReader(unit.TypeActions), reqOwner(), repo.NewAction())
|
||||
addActionsRoutes(m, reqRepoReader(unit.TypeActions), reqRepoAdmin(), repo.NewAction())
|
||||
|
||||
m.Group("/actions/workflows", func() {
|
||||
m.Get("", repo.ActionsListRepositoryWorkflows)
|
||||
|
||||
@@ -12,6 +12,7 @@ import (
|
||||
|
||||
activities_model "gitea.dev/models/activities"
|
||||
audit_model "gitea.dev/models/audit"
|
||||
auth_model "gitea.dev/models/auth"
|
||||
"gitea.dev/models/db"
|
||||
"gitea.dev/models/organization"
|
||||
"gitea.dev/models/perm"
|
||||
@@ -160,6 +161,24 @@ func GetUserOrgsPermissions(ctx *context.APIContext) {
|
||||
}
|
||||
|
||||
org := organization.OrgFromUser(o)
|
||||
canViewRoles := false
|
||||
if !ctx.PublicOnly {
|
||||
scope, hasScope := ctx.Data["ApiTokenScope"].(auth_model.AccessTokenScope)
|
||||
canViewRoles = ctx.Doer.ID == ctx.ContextUser.ID || ctx.Doer.IsAdmin && (!hasScope || scope == auth_model.AccessTokenScopeAll)
|
||||
if !canViewRoles && !ctx.Doer.IsRestricted {
|
||||
isDoerMember, err := org.IsOrgMember(ctx, ctx.Doer.ID)
|
||||
if err != nil {
|
||||
ctx.APIErrorInternal(err)
|
||||
return
|
||||
}
|
||||
canViewRoles = isDoerMember
|
||||
}
|
||||
}
|
||||
if !canViewRoles {
|
||||
ctx.JSON(http.StatusOK, op)
|
||||
return
|
||||
}
|
||||
|
||||
authorizeLevel, err := org.GetOrgUserMaxAuthorizeLevel(ctx, ctx.ContextUser.ID)
|
||||
if err != nil {
|
||||
ctx.APIErrorInternal(err)
|
||||
|
||||
@@ -279,7 +279,11 @@ func EditTeam(ctx *context.APIContext) {
|
||||
team.CanCreateOrgRepo = team.IsOwnerTeam() || *form.CanCreateOrgRepo
|
||||
}
|
||||
|
||||
if len(form.Name) > 0 {
|
||||
if len(form.Name) > 0 && form.Name != team.Name {
|
||||
if team.IsOwnerTeam() {
|
||||
ctx.APIError(http.StatusUnprocessableEntity, "the owner team cannot be renamed")
|
||||
return
|
||||
}
|
||||
team.Name = form.Name
|
||||
}
|
||||
|
||||
|
||||
@@ -8,6 +8,7 @@ import (
|
||||
"errors"
|
||||
"net/http"
|
||||
|
||||
audit_model "gitea.dev/models/audit"
|
||||
"gitea.dev/models/db"
|
||||
git_model "gitea.dev/models/git"
|
||||
"gitea.dev/models/organization"
|
||||
@@ -20,6 +21,7 @@ import (
|
||||
"gitea.dev/modules/util"
|
||||
"gitea.dev/modules/web"
|
||||
"gitea.dev/routers/api/v1/utils"
|
||||
"gitea.dev/services/audit"
|
||||
"gitea.dev/services/context"
|
||||
"gitea.dev/services/convert"
|
||||
pull_service "gitea.dev/services/pull"
|
||||
@@ -822,6 +824,7 @@ func CreateBranchProtection(ctx *context.APIContext) {
|
||||
ctx.APIErrorInternal(err)
|
||||
return
|
||||
}
|
||||
audit.Record(ctx, audit_model.RepositoryBranchProtectionAdd, ctx.Repo.Repository, "rule", protectBranch.RuleName)
|
||||
|
||||
// Reload from db to get all whitelists
|
||||
bp, err := git_model.GetProtectedBranchRuleByName(ctx, ctx.Repo.Repository.ID, ruleName)
|
||||
@@ -1154,6 +1157,7 @@ func EditBranchProtection(ctx *context.APIContext) {
|
||||
ctx.APIErrorInternal(err)
|
||||
return
|
||||
}
|
||||
audit.Record(ctx, audit_model.RepositoryBranchProtectionUpdate, ctx.Repo.Repository, "rule", protectBranch.RuleName)
|
||||
|
||||
isPlainRule := !git_model.IsRuleNameSpecial(bpName)
|
||||
var isBranchExist bool
|
||||
@@ -1255,6 +1259,7 @@ func DeleteBranchProtection(ctx *context.APIContext) {
|
||||
ctx.APIErrorInternal(err)
|
||||
return
|
||||
}
|
||||
audit.Record(ctx, audit_model.RepositoryBranchProtectionRemove, ctx.Repo.Repository, "rule", bp.RuleName)
|
||||
|
||||
ctx.Status(http.StatusNoContent)
|
||||
}
|
||||
|
||||
@@ -17,6 +17,7 @@ import (
|
||||
"gitea.dev/modules/web"
|
||||
webhook_module "gitea.dev/modules/webhook"
|
||||
"gitea.dev/routers/api/v1/utils"
|
||||
"gitea.dev/services/audit"
|
||||
"gitea.dev/services/context"
|
||||
"gitea.dev/services/convert"
|
||||
webhook_service "gitea.dev/services/webhook"
|
||||
@@ -296,13 +297,14 @@ func DeleteHook(ctx *context.APIContext) {
|
||||
// "$ref": "#/responses/empty"
|
||||
// "404":
|
||||
// "$ref": "#/responses/notFound"
|
||||
if err := webhook.DeleteWebhookByRepoID(ctx, ctx.Repo.Repository.ID, ctx.PathParamInt64("id")); err != nil {
|
||||
if webhook.IsErrWebhookNotExist(err) {
|
||||
ctx.APIErrorNotFound()
|
||||
} else {
|
||||
ctx.APIErrorInternal(err)
|
||||
}
|
||||
hook, err := utils.GetRepoHook(ctx, ctx.Repo.Repository.ID, ctx.PathParamInt64("id"))
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
if err := webhook.DeleteWebhookByRepoID(ctx, ctx.Repo.Repository.ID, hook.ID); err != nil {
|
||||
ctx.APIErrorAuto(err)
|
||||
return
|
||||
}
|
||||
audit.RecordScoped(ctx, nil, ctx.Repo.Repository, audit.WebhookRemove, "webhook", hook.URL)
|
||||
ctx.Status(http.StatusNoContent)
|
||||
}
|
||||
@@ -377,26 +377,12 @@ func ListIssues(ctx *context.APIContext) {
|
||||
|
||||
listOptions := utils.GetListOptions(ctx)
|
||||
|
||||
isPull := common.ParseIssueFilterTypeIsPull(ctx.FormString("type"))
|
||||
|
||||
if isPull.Has() && !ctx.Repo.Permission.CanReadIssuesOrPulls(isPull.Value()) {
|
||||
ctx.APIErrorNotFound()
|
||||
isPull, ok := common.ParseIssueFilterTypeIsPullWithPermission(ctx.Repo.Permission, ctx.FormString("type"))
|
||||
if !ok {
|
||||
ctx.APIError(http.StatusForbidden, "no permission to read issues or pulls")
|
||||
return
|
||||
}
|
||||
|
||||
if !isPull.Has() {
|
||||
canReadIssues := ctx.Repo.Permission.CanRead(unit.TypeIssues)
|
||||
canReadPulls := ctx.Repo.Permission.CanRead(unit.TypePullRequests)
|
||||
if !canReadIssues && !canReadPulls {
|
||||
ctx.APIErrorNotFound()
|
||||
return
|
||||
} else if !canReadIssues {
|
||||
isPull = optional.Some(true)
|
||||
} else if !canReadPulls {
|
||||
isPull = optional.Some(false)
|
||||
}
|
||||
}
|
||||
|
||||
// FIXME: we should be more efficient here
|
||||
createdByID := getUserIDForFilter(ctx, "created_by")
|
||||
if ctx.Written() {
|
||||
|
||||
@@ -63,7 +63,7 @@ func LockIssue(ctx *context.APIContext) {
|
||||
|
||||
if !issue.IsLocked {
|
||||
opt := &issues_model.IssueLockOptions{
|
||||
Doer: ctx.ContextUser,
|
||||
Doer: ctx.Doer,
|
||||
Issue: issue,
|
||||
Reason: reason,
|
||||
}
|
||||
@@ -125,7 +125,7 @@ func UnlockIssue(ctx *context.APIContext) {
|
||||
|
||||
if issue.IsLocked {
|
||||
opt := &issues_model.IssueLockOptions{
|
||||
Doer: ctx.ContextUser,
|
||||
Doer: ctx.Doer,
|
||||
Issue: issue,
|
||||
}
|
||||
|
||||
|
||||
@@ -10,6 +10,7 @@ import (
|
||||
"net/http"
|
||||
|
||||
asymkey_model "gitea.dev/models/asymkey"
|
||||
audit_model "gitea.dev/models/audit"
|
||||
"gitea.dev/models/db"
|
||||
deploykey_model "gitea.dev/models/deploykey"
|
||||
"gitea.dev/models/perm"
|
||||
@@ -20,6 +21,7 @@ import (
|
||||
"gitea.dev/modules/web"
|
||||
"gitea.dev/routers/api/v1/utils"
|
||||
asymkey_service "gitea.dev/services/asymkey"
|
||||
"gitea.dev/services/audit"
|
||||
"gitea.dev/services/context"
|
||||
"gitea.dev/services/convert"
|
||||
)
|
||||
@@ -219,6 +221,7 @@ func CreateDeployKey(ctx *context.APIContext) {
|
||||
HandleAddKeyError(ctx, err)
|
||||
return
|
||||
}
|
||||
audit.Record(ctx, audit_model.RepositoryDeployKeyAdd, ctx.Repo.Repository, "deploy_key", key.Name)
|
||||
ctx.JSON(http.StatusCreated, convert.ToDeployKey(ctx, ctx.Repo.Repository, key))
|
||||
}
|
||||
|
||||
@@ -261,6 +264,7 @@ func CreateDeployToken(ctx *context.APIContext) {
|
||||
HandleAddKeyError(ctx, err)
|
||||
return
|
||||
}
|
||||
audit.Record(ctx, audit_model.RepositoryDeployKeyAdd, ctx.Repo.Repository, "deploy_key", key.Name)
|
||||
|
||||
ctx.JSON(http.StatusCreated, convert.ToDeployKey(ctx, ctx.Repo.Repository, key))
|
||||
}
|
||||
|
||||
@@ -176,7 +176,6 @@ func Migrate(ctx *context.APIContext) {
|
||||
GitServiceType: gitServiceType,
|
||||
IsPrivate: opts.Private || setting.Repository.ForcePrivate,
|
||||
IsMirror: opts.Mirror,
|
||||
Status: repo_model.RepositoryBeingMigrated,
|
||||
}, false)
|
||||
if err != nil {
|
||||
handleMigrateError(ctx, repoOwner, err)
|
||||
|
||||
@@ -10,6 +10,7 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
audit_model "gitea.dev/models/audit"
|
||||
"gitea.dev/models/db"
|
||||
repo_model "gitea.dev/models/repo"
|
||||
"gitea.dev/models/unit"
|
||||
@@ -19,6 +20,7 @@ import (
|
||||
"gitea.dev/modules/util"
|
||||
"gitea.dev/modules/web"
|
||||
"gitea.dev/routers/api/v1/utils"
|
||||
"gitea.dev/services/audit"
|
||||
"gitea.dev/services/context"
|
||||
"gitea.dev/services/convert"
|
||||
"gitea.dev/services/migrations"
|
||||
@@ -399,6 +401,7 @@ func CreatePushMirror(ctx *context.APIContext, mirrorOption *api.CreatePushMirro
|
||||
ctx.APIErrorInternal(err)
|
||||
return
|
||||
}
|
||||
audit.Record(ctx, audit_model.RepositoryMirrorPushAdd, repo, "mirror_id", pushMirror.ID, "remote_address", pushMirror.RemoteAddress)
|
||||
m, err := convert.ToPushMirror(ctx, pushMirror)
|
||||
if err != nil {
|
||||
ctx.APIErrorInternal(err)
|
||||
|
||||
@@ -503,6 +503,13 @@ func CreatePullReview(ctx *context.APIContext) {
|
||||
// "$ref": "#/responses/validationError"
|
||||
|
||||
opts := web.GetForm[*api.CreatePullReviewOptions](ctx)
|
||||
for _, comment := range opts.Comments {
|
||||
if comment.Path == "" || (comment.NewLineNum <= 0 && comment.OldLineNum <= 0) {
|
||||
ctx.APIError(http.StatusUnprocessableEntity, "review comments require a path and a positive new_position or old_position")
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
pr, err := issues_model.GetPullRequestByIndex(ctx, ctx.Repo.Repository.ID, ctx.PathParamInt64("index"))
|
||||
if err != nil {
|
||||
ctx.APIErrorAuto(err)
|
||||
|
||||
@@ -726,6 +726,7 @@ func updateBasicProperties(ctx *context.APIContext, opts api.EditRepoOption) err
|
||||
|
||||
if oldDefaultBranch != "" {
|
||||
actions_service.SwitchSchedulesToDefaultBranch(ctx, repo, oldDefaultBranch)
|
||||
audit.Record(ctx, audit_model.RepositoryBranchDefault, repo, "default_branch", repo.DefaultBranch)
|
||||
}
|
||||
|
||||
if visibilityChanged {
|
||||
@@ -984,6 +985,9 @@ func updateRepoArchivedState(ctx *context.APIContext, opts api.EditRepoOption) e
|
||||
ctx.APIError(http.StatusUnprocessableEntity, err.Error())
|
||||
return err
|
||||
}
|
||||
if *opts.Archived == repo.IsArchived {
|
||||
return nil
|
||||
}
|
||||
if *opts.Archived {
|
||||
if err := repo_model.SetArchiveRepoState(ctx, repo, *opts.Archived); err != nil {
|
||||
log.Error("Tried to archive a repo: %s", err)
|
||||
@@ -993,6 +997,7 @@ func updateRepoArchivedState(ctx *context.APIContext, opts api.EditRepoOption) e
|
||||
if err := actions_service.CleanRepoScheduleTasks(ctx, repo); err != nil {
|
||||
log.Error("CleanRepoScheduleTasks for archived repo %s/%s: %v", ctx.Repo.Owner.Name, repo.Name, err)
|
||||
}
|
||||
audit.Record(ctx, audit_model.RepositoryArchive, repo)
|
||||
log.Trace("Repository was archived: %s/%s", ctx.Repo.Owner.Name, repo.Name)
|
||||
} else {
|
||||
if err := repo_model.SetArchiveRepoState(ctx, repo, *opts.Archived); err != nil {
|
||||
@@ -1005,6 +1010,7 @@ func updateRepoArchivedState(ctx *context.APIContext, opts api.EditRepoOption) e
|
||||
log.Error("DetectAndHandleSchedules for un-archived repo %s/%s: %v", ctx.Repo.Owner.Name, repo.Name, err)
|
||||
}
|
||||
}
|
||||
audit.Record(ctx, audit_model.RepositoryUnarchive, repo)
|
||||
log.Trace("Repository was un-archived: %s/%s", ctx.Repo.Owner.Name, repo.Name)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,6 +9,7 @@ import (
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
audit_model "gitea.dev/models/audit"
|
||||
git_model "gitea.dev/models/git"
|
||||
"gitea.dev/models/organization"
|
||||
repo_model "gitea.dev/models/repo"
|
||||
@@ -16,6 +17,7 @@ import (
|
||||
api "gitea.dev/modules/structs"
|
||||
"gitea.dev/modules/web"
|
||||
"gitea.dev/routers/api/v1/utils"
|
||||
"gitea.dev/services/audit"
|
||||
"gitea.dev/services/context"
|
||||
"gitea.dev/services/convert"
|
||||
release_service "gitea.dev/services/release"
|
||||
@@ -467,6 +469,7 @@ func CreateTagProtection(ctx *context.APIContext) {
|
||||
ctx.APIErrorInternal(err)
|
||||
return
|
||||
}
|
||||
audit.Record(ctx, audit_model.RepositoryTagProtectionAdd, repo, "pattern", protectTag.NamePattern)
|
||||
|
||||
pt, err = git_model.GetProtectedTagByID(ctx, protectTag.ID)
|
||||
if err != nil {
|
||||
@@ -574,6 +577,7 @@ func EditTagProtection(ctx *context.APIContext) {
|
||||
ctx.APIErrorInternal(err)
|
||||
return
|
||||
}
|
||||
audit.Record(ctx, audit_model.RepositoryTagProtectionUpdate, repo, "pattern", pt.NamePattern)
|
||||
|
||||
pt, err = git_model.GetProtectedTagByID(ctx, id)
|
||||
if err != nil {
|
||||
@@ -636,6 +640,7 @@ func DeleteTagProtection(ctx *context.APIContext) {
|
||||
ctx.APIErrorInternal(err)
|
||||
return
|
||||
}
|
||||
audit.Record(ctx, audit_model.RepositoryTagProtectionRemove, repo, "pattern", pt.NamePattern)
|
||||
|
||||
ctx.Status(http.StatusNoContent)
|
||||
}
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
"math"
|
||||
"net/http"
|
||||
|
||||
audit_model "gitea.dev/models/audit"
|
||||
"gitea.dev/models/db"
|
||||
issues_model "gitea.dev/models/issues"
|
||||
access_model "gitea.dev/models/perm/access"
|
||||
@@ -20,6 +21,7 @@ import (
|
||||
"gitea.dev/modules/web"
|
||||
"gitea.dev/routers/api/v1/utils"
|
||||
"gitea.dev/routers/common"
|
||||
"gitea.dev/services/audit"
|
||||
"gitea.dev/services/context"
|
||||
"gitea.dev/services/convert"
|
||||
project_service "gitea.dev/services/projects"
|
||||
@@ -57,6 +59,13 @@ func (s projectScope) ownerID() int64 {
|
||||
return 0
|
||||
}
|
||||
|
||||
func (s projectScope) auditScope() any {
|
||||
if s.Repo != nil {
|
||||
return s.Repo
|
||||
}
|
||||
return s.Owner
|
||||
}
|
||||
|
||||
// attach preloads the relation the converter needs for HTMLURL, sparing a lookup per project.
|
||||
func (s projectScope) attach(projects ...*project_model.Project) {
|
||||
for _, project := range projects {
|
||||
@@ -505,6 +514,7 @@ func CreateProject(ctx *context.APIContext) {
|
||||
ctx.APIErrorInternal(err)
|
||||
return
|
||||
}
|
||||
audit.Record(ctx, audit_model.ProjectCreate, scope.auditScope(), "project", project.Title, "project_id", project.ID)
|
||||
|
||||
scope.attach(project)
|
||||
ctx.JSON(http.StatusCreated, convert.ToProject(ctx, project, ctx.Doer))
|
||||
@@ -606,7 +616,8 @@ func EditProject(ctx *context.APIContext) {
|
||||
// "404":
|
||||
// "$ref": "#/responses/notFound"
|
||||
|
||||
project := projectScopeFromContext(ctx).findProject(ctx)
|
||||
scope := projectScopeFromContext(ctx)
|
||||
project := scope.findProject(ctx)
|
||||
if ctx.Written() {
|
||||
return
|
||||
}
|
||||
@@ -639,6 +650,7 @@ func EditProject(ctx *context.APIContext) {
|
||||
ctx.APIErrorInternal(err)
|
||||
return
|
||||
}
|
||||
audit.Record(ctx, audit_model.ProjectUpdate, scope.auditScope(), "project", project.Title, "project_id", project.ID)
|
||||
|
||||
if err := project_service.LoadIssueNumbersForProject(ctx, project, ctx.Doer); err != nil {
|
||||
ctx.APIErrorInternal(err)
|
||||
@@ -713,7 +725,8 @@ func DeleteProject(ctx *context.APIContext) {
|
||||
// "404":
|
||||
// "$ref": "#/responses/notFound"
|
||||
|
||||
project := projectScopeFromContext(ctx).findProject(ctx)
|
||||
scope := projectScopeFromContext(ctx)
|
||||
project := scope.findProject(ctx)
|
||||
if ctx.Written() {
|
||||
return
|
||||
}
|
||||
@@ -721,6 +734,7 @@ func DeleteProject(ctx *context.APIContext) {
|
||||
ctx.APIErrorInternal(err)
|
||||
return
|
||||
}
|
||||
audit.Record(ctx, audit_model.ProjectDelete, scope.auditScope(), "project", project.Title, "project_id", project.ID)
|
||||
ctx.Status(http.StatusNoContent)
|
||||
}
|
||||
|
||||
|
||||
@@ -32,6 +32,9 @@ func getStarredRepos(ctx *context.APIContext, user *user_model.User, private boo
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := repo_model.RepositoryList(starredRepos).LoadAttributes(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
repos := make([]*api.Repository, 0, len(starredRepos))
|
||||
for _, starred := range starredRepos {
|
||||
@@ -113,6 +116,7 @@ func GetMyStarredRepos(ctx *context.APIContext) {
|
||||
repos, err := getStarredRepos(ctx, ctx.Doer, true)
|
||||
if err != nil {
|
||||
ctx.APIErrorInternal(err)
|
||||
return
|
||||
}
|
||||
|
||||
ctx.SetLinkHeader(int64(ctx.Doer.NumStars), utils.GetListOptions(ctx).PageSize)
|
||||
|
||||
@@ -30,6 +30,9 @@ func getWatchedRepos(ctx *context.APIContext, user *user_model.User, private boo
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
if err := repo_model.RepositoryList(watchedRepos).LoadAttributes(ctx); err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
repos := make([]*api.Repository, len(watchedRepos))
|
||||
for i, watched := range watchedRepos {
|
||||
@@ -73,6 +76,7 @@ func GetWatchedRepos(ctx *context.APIContext) {
|
||||
repos, total, err := getWatchedRepos(ctx, ctx.ContextUser, private)
|
||||
if err != nil {
|
||||
ctx.APIErrorInternal(err)
|
||||
return
|
||||
}
|
||||
|
||||
ctx.SetLinkHeader(total, utils.GetListOptions(ctx).PageSize)
|
||||
@@ -103,6 +107,7 @@ func GetMyWatchedRepos(ctx *context.APIContext) {
|
||||
repos, total, err := getWatchedRepos(ctx, ctx.Doer, true)
|
||||
if err != nil {
|
||||
ctx.APIErrorInternal(err)
|
||||
return
|
||||
}
|
||||
ctx.SetLinkHeader(total, utils.GetListOptions(ctx).PageSize)
|
||||
ctx.SetTotalCountHeader(total)
|
||||
|
||||
@@ -17,6 +17,7 @@ import (
|
||||
"gitea.dev/modules/util"
|
||||
"gitea.dev/modules/validation"
|
||||
webhook_module "gitea.dev/modules/webhook"
|
||||
"gitea.dev/services/audit"
|
||||
"gitea.dev/services/context"
|
||||
webhook_service "gitea.dev/services/webhook"
|
||||
)
|
||||
@@ -105,6 +106,7 @@ func checkCreateHookOption(ctx *context.APIContext, form *api.CreateHookOption)
|
||||
func AddSystemHook(ctx *context.APIContext, form *api.CreateHookOption) {
|
||||
hook, ok := addHook(ctx, form, 0, 0)
|
||||
if ok {
|
||||
audit.RecordScoped(ctx, nil, nil, audit.WebhookAdd, "webhook", hook.URL)
|
||||
h, err := webhook_service.ToHook(setting.AppSubURL+"/-/admin", hook)
|
||||
if err != nil {
|
||||
ctx.APIErrorInternal(err)
|
||||
@@ -120,6 +122,7 @@ func AddOwnerHook(ctx *context.APIContext, owner *user_model.User, form *api.Cre
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
audit.RecordScoped(ctx, owner, nil, audit.WebhookAdd, "webhook", hook.URL)
|
||||
apiHook, ok := toAPIHook(ctx, owner.HomeLink(), hook)
|
||||
if !ok {
|
||||
return
|
||||
@@ -134,6 +137,7 @@ func AddRepoHook(ctx *context.APIContext, form *api.CreateHookOption) {
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
audit.RecordScoped(ctx, nil, repo.Repository, audit.WebhookAdd, "webhook", hook.URL)
|
||||
apiHook, ok := toAPIHook(ctx, repo.RepoLink, hook)
|
||||
if !ok {
|
||||
return
|
||||
@@ -278,9 +282,9 @@ func EditSystemHook(ctx *context.APIContext, form *api.EditHookOption, hookID in
|
||||
return
|
||||
}
|
||||
if !editHook(ctx, form, hook) {
|
||||
ctx.APIErrorInternal(err)
|
||||
return
|
||||
}
|
||||
audit.RecordScoped(ctx, nil, nil, audit.WebhookUpdate, "webhook", hook.URL)
|
||||
updated, err := webhook.GetSystemOrDefaultWebhook(ctx, hookID)
|
||||
if err != nil {
|
||||
ctx.APIErrorInternal(err)
|
||||
@@ -303,6 +307,7 @@ func EditOwnerHook(ctx *context.APIContext, owner *user_model.User, form *api.Ed
|
||||
if !editHook(ctx, form, hook) {
|
||||
return
|
||||
}
|
||||
audit.RecordScoped(ctx, owner, nil, audit.WebhookUpdate, "webhook", hook.URL)
|
||||
updated, err := GetOwnerHook(ctx, owner.ID, hookID)
|
||||
if err != nil {
|
||||
return
|
||||
@@ -324,6 +329,7 @@ func EditRepoHook(ctx *context.APIContext, form *api.EditHookOption, hookID int6
|
||||
if !editHook(ctx, form, hook) {
|
||||
return
|
||||
}
|
||||
audit.RecordScoped(ctx, nil, repo.Repository, audit.WebhookUpdate, "webhook", hook.URL)
|
||||
updated, err := GetRepoHook(ctx, repo.Repository.ID, hookID)
|
||||
if err != nil {
|
||||
return
|
||||
@@ -406,6 +412,10 @@ func editHook(ctx *context.APIContext, form *api.EditHookOption, w *webhook.Webh
|
||||
|
||||
// DeleteOwnerHook deletes the hook owned by the owner.
|
||||
func DeleteOwnerHook(ctx *context.APIContext, owner *user_model.User, hookID int64) {
|
||||
hook, err := GetOwnerHook(ctx, owner.ID, hookID)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
if err := webhook.DeleteWebhookByOwnerID(ctx, owner.ID, hookID); err != nil {
|
||||
if webhook.IsErrWebhookNotExist(err) {
|
||||
ctx.APIErrorNotFound()
|
||||
@@ -414,5 +424,6 @@ func DeleteOwnerHook(ctx *context.APIContext, owner *user_model.User, hookID int
|
||||
}
|
||||
return
|
||||
}
|
||||
audit.RecordScoped(ctx, owner, nil, audit.WebhookRemove, "webhook", hook.URL)
|
||||
ctx.Status(http.StatusNoContent)
|
||||
}
|
||||
@@ -7,7 +7,9 @@ import (
|
||||
"context"
|
||||
|
||||
"gitea.dev/models/organization"
|
||||
access_model "gitea.dev/models/perm/access"
|
||||
repo_model "gitea.dev/models/repo"
|
||||
"gitea.dev/models/unit"
|
||||
user_model "gitea.dev/models/user"
|
||||
"gitea.dev/modules/optional"
|
||||
"gitea.dev/modules/util"
|
||||
@@ -30,6 +32,32 @@ func ParseIssueFilterTypeIsPull(typ string) optional.Option[bool] {
|
||||
return optional.FromMapLookup(map[string]bool{"pulls": true, "issues": false}, typ)
|
||||
}
|
||||
|
||||
func ParseIssueFilterTypeIsPullWithPermission(userPerm access_model.Permission, typ string) (optional.Option[bool], bool) {
|
||||
typeIssues, typePulls := "issues", "pulls"
|
||||
canReadIssues := userPerm.CanRead(unit.TypeIssues)
|
||||
canReadPulls := userPerm.CanRead(unit.TypePullRequests)
|
||||
switch {
|
||||
case canReadIssues && canReadPulls:
|
||||
return ParseIssueFilterTypeIsPull(typ), true
|
||||
case typ == typeIssues && canReadIssues:
|
||||
return optional.Some(false), true
|
||||
case typ == typePulls && canReadPulls:
|
||||
return optional.Some(true), true
|
||||
default:
|
||||
isPull := ParseIssueFilterTypeIsPull(typ)
|
||||
if isPull.Has() {
|
||||
if (isPull.Value() && canReadPulls) || (!isPull.Value() && canReadIssues) {
|
||||
// explicitly specified a type that the user can read, so return it
|
||||
return isPull, true
|
||||
}
|
||||
} else if canReadIssues || canReadPulls {
|
||||
// no type specified, so return the type the user can read
|
||||
return optional.Some(canReadPulls), true
|
||||
}
|
||||
return optional.None[bool](), false
|
||||
}
|
||||
}
|
||||
|
||||
type SearchIssuesRepoIDsOptions struct {
|
||||
Doer *user_model.User
|
||||
PublicOnly bool
|
||||
|
||||
@@ -9,7 +9,6 @@ import (
|
||||
"net/http"
|
||||
|
||||
audit_model "gitea.dev/models/audit"
|
||||
git_model "gitea.dev/models/git"
|
||||
issues_model "gitea.dev/models/issues"
|
||||
repo_model "gitea.dev/models/repo"
|
||||
"gitea.dev/modules/git"
|
||||
@@ -51,24 +50,18 @@ func hookPostReceiveCollectPushUpdates(opts *private.HookOptions, repo *repo_mod
|
||||
}
|
||||
|
||||
func hookPostReceiveSyncDatabaseBranches(ctx *gitea_context.PrivateContext, opts *private.HookOptions, repo *repo_model.Repository, updates []*repo_module.PushUpdateOptions) {
|
||||
branchesToSync := make([]*repo_module.PushUpdateOptions, 0, len(updates))
|
||||
branchNames := make([]string, 0, len(updates))
|
||||
for _, update := range updates {
|
||||
if !update.RefFullName.IsBranch() {
|
||||
continue
|
||||
}
|
||||
if update.IsDelRef() {
|
||||
if err := git_model.MarkBranchAsDeleted(ctx, repo.ID, update.RefFullName.BranchName(), update.PusherID); err != nil {
|
||||
log.Error("failed to mark branch %s as deleted: %v", update.RefFullName, err)
|
||||
continue
|
||||
}
|
||||
} else {
|
||||
branchesToSync = append(branchesToSync, update)
|
||||
// TODO: should we return the error and return the error when pushing? Currently it will log the error and not prevent the pushing
|
||||
branchNames = append(branchNames, update.RefFullName.BranchName())
|
||||
if !update.IsDelRef() {
|
||||
pull_service.UpdatePullsRefs(ctx, repo, update)
|
||||
}
|
||||
}
|
||||
|
||||
if len(branchesToSync) == 0 {
|
||||
if len(branchNames) == 0 {
|
||||
return
|
||||
}
|
||||
|
||||
@@ -78,13 +71,7 @@ func hookPostReceiveSyncDatabaseBranches(ctx *gitea_context.PrivateContext, opts
|
||||
return
|
||||
}
|
||||
|
||||
branchNames := make([]string, 0, len(branchesToSync))
|
||||
commitIDs := make([]string, 0, len(branchesToSync))
|
||||
for _, update := range branchesToSync {
|
||||
branchNames = append(branchNames, update.RefFullName.BranchName())
|
||||
commitIDs = append(commitIDs, update.NewCommitID)
|
||||
}
|
||||
if err = repo_service.SyncBranchesToDB(ctx, repo.ID, opts.UserID, gitRepo, branchNames, commitIDs); err != nil {
|
||||
if err = repo_service.SyncBranchesToDB(ctx, repo, opts.UserID, gitRepo, branchNames); err != nil {
|
||||
log.Error("failed to sync branch to DB: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -100,16 +87,20 @@ func HookPostReceive(ctx *gitea_context.PrivateContext) {
|
||||
// In the post-receive hook, the git repo has received all changes,
|
||||
// So even if any error happens, nothing can be stopped or undone, so the errors should be skipped
|
||||
repo := ctx.Repo.Repository
|
||||
updates := hookPostReceiveCollectPushUpdates(opts, repo) // first, collect updates and sync branches
|
||||
wasEmpty := repo.IsEmpty
|
||||
updates := hookPostReceiveCollectPushUpdates(opts, repo)
|
||||
hookPostReceiveUpdateRepoByOptions(ctx, opts, repo) // push options are only honored while the repo is still empty
|
||||
hookPostReceiveSyncDatabaseBranches(ctx, opts, repo, updates)
|
||||
hookPostReceiveSyncRepoDefaultBranch(ctx, opts, repo)
|
||||
hookPostReceiveUpdateRepoByOptions(ctx, opts, repo)
|
||||
|
||||
// handle async updates (e.g.: notification, cache management, repo update time, etc.)
|
||||
if err := repo_service.PushUpdates(updates...); err != nil {
|
||||
log.Error("failed to push updates: %v", err)
|
||||
}
|
||||
|
||||
if wasEmpty && !repo.IsFork {
|
||||
ctx.JSON(http.StatusOK, private.HookPostReceiveResult{})
|
||||
return
|
||||
}
|
||||
hookPostReceiveRespondWithTrailer(ctx, opts, repo)
|
||||
}
|
||||
|
||||
@@ -214,43 +205,3 @@ func hookPostReceiveRespondWithTrailer(ctx *gitea_context.PrivateContext, opts *
|
||||
}
|
||||
ctx.JSON(http.StatusOK, private.HookPostReceiveResult{Results: results})
|
||||
}
|
||||
|
||||
func hookPostReceiveSyncRepoDefaultBranch(ctx *gitea_context.PrivateContext, opts *private.HookOptions, repo *repo_model.Repository) {
|
||||
hasBranch := false
|
||||
for _, refFullName := range opts.RefFullNames {
|
||||
if hasBranch = refFullName.IsBranch(); hasBranch {
|
||||
break
|
||||
}
|
||||
}
|
||||
if !hasBranch {
|
||||
return
|
||||
}
|
||||
gitRepo, err := git.RepositoryFromRequestContextOrOpen(ctx, repo)
|
||||
if err != nil {
|
||||
log.Error("failed to open git repo: %v", err)
|
||||
return
|
||||
}
|
||||
|
||||
// if default branch doesn't exist, try to guess one from existing git repo
|
||||
_, err = gitRepo.GetBranchCommitID(ctx, repo.DefaultBranch)
|
||||
if errors.Is(err, util.ErrNotExist) {
|
||||
for _, guessBranchName := range []string{"main", "master"} {
|
||||
if _, err = gitRepo.GetBranchCommitID(ctx, guessBranchName); err == nil {
|
||||
repo.DefaultBranch = guessBranchName
|
||||
err = repo_model.UpdateDefaultBranch(ctx, repo)
|
||||
if err != nil {
|
||||
log.Error("failed to update default branch: %v", err)
|
||||
return
|
||||
}
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// if default branch was pushed, always keep the HEAD ref in sync
|
||||
for _, refFullName := range opts.RefFullNames {
|
||||
if refFullName.IsBranch() && refFullName.BranchName() == repo.DefaultBranch {
|
||||
_ = git.SetDefaultBranch(ctx, repo, repo.DefaultBranch)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -29,7 +29,6 @@ type preReceiveContext struct {
|
||||
|
||||
// this context should only contain shared variables, mutable variables like "current branch name" shouldn't be put here
|
||||
canWriteCodeUnitCached *bool
|
||||
canCreatePullRequest *bool
|
||||
protectedTags []*git_model.ProtectedTag
|
||||
}
|
||||
|
||||
@@ -64,21 +63,10 @@ func (ctx *preReceiveContext) assertCanWriteRef(refFullName git.RefName) bool {
|
||||
return true
|
||||
}
|
||||
|
||||
// CanCreatePullRequest returns true if pusher can create pull requests
|
||||
func (ctx *preReceiveContext) CanCreatePullRequest() bool {
|
||||
if ctx.canCreatePullRequest == nil {
|
||||
ctx.canCreatePullRequest = new(ctx.Repo.Permission.CanRead(unit.TypePullRequests))
|
||||
}
|
||||
return *ctx.canCreatePullRequest
|
||||
}
|
||||
|
||||
// AssertCreatePullRequest returns true if can create pull requests
|
||||
func (ctx *preReceiveContext) AssertCreatePullRequest() bool {
|
||||
if !ctx.CanCreatePullRequest() {
|
||||
if ctx.Written() {
|
||||
return false
|
||||
}
|
||||
ctx.PrivateUserErrorf(http.StatusForbidden, "User permission denied for creating pull-request.")
|
||||
func assertCanCreatePullRequest(ctx *gitea_context.PrivateContext, opts *private.HookOptions) bool {
|
||||
canReadPullRequests := ctx.Repo.Permission.CanRead(unit.TypePullRequests)
|
||||
if !canReadPullRequests || opts.IsWiki {
|
||||
ctx.PrivateUserErrorf(http.StatusForbidden, "%s", util.Iif(canReadPullRequests, "Pull requests are not supported on the wiki.", "User permission denied for creating pull-request."))
|
||||
return false
|
||||
}
|
||||
return true
|
||||
@@ -343,23 +331,12 @@ func preReceiveTag(ctx *preReceiveContext, refFullName git.RefName) {
|
||||
}
|
||||
|
||||
func preReceiveFor(ctx *preReceiveContext, refFullName git.RefName) {
|
||||
if !ctx.AssertCreatePullRequest() {
|
||||
if !assertCanCreatePullRequest(ctx.PrivateContext, ctx.opts) {
|
||||
return
|
||||
}
|
||||
|
||||
if ctx.Repo.Repository.IsEmpty {
|
||||
} else if ctx.Repo.Repository.IsEmpty {
|
||||
ctx.PrivateUserErrorf(http.StatusForbidden, "Can't create pull request for an empty repository.")
|
||||
return
|
||||
}
|
||||
|
||||
if ctx.opts.IsWiki {
|
||||
ctx.PrivateUserErrorf(http.StatusForbidden, "Pull requests are not supported on the wiki.")
|
||||
return
|
||||
}
|
||||
|
||||
_, _, err := agit.GetAgitBranchInfo(ctx, ctx.Repo.Repository.ID, refFullName.ForBranchName())
|
||||
if err != nil {
|
||||
if !errors.Is(err, util.ErrNotExist) {
|
||||
} else if _, _, err := agit.GetAgitBranchInfo(ctx, ctx.Repo.Repository.ID, refFullName.ForBranchName()); err != nil {
|
||||
if errors.Is(err, util.ErrNotExist) {
|
||||
ctx.PrivateUserErrorf(http.StatusForbidden, "Unexpected ref: %s", refFullName)
|
||||
} else {
|
||||
ctx.PrivateInternalErrorf("Unable to get branch info for ref %s: %v", refFullName, err)
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
package private
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"testing"
|
||||
|
||||
"gitea.dev/models/db"
|
||||
@@ -14,6 +15,7 @@ import (
|
||||
user_model "gitea.dev/models/user"
|
||||
"gitea.dev/modules/git"
|
||||
"gitea.dev/modules/private"
|
||||
"gitea.dev/modules/web"
|
||||
"gitea.dev/services/contexttest"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
@@ -113,3 +115,20 @@ func TestPreReceiveCanWriteCodePerBranch(t *testing.T) {
|
||||
// yields an empty branch name, so this guards the per-ref evaluation, not the IsBranch check.)
|
||||
assert.False(t, ctx.canWriteCodeRef(git.RefNameFromTag("granted-branch")))
|
||||
}
|
||||
|
||||
func TestHookProcReceiveNeedsPullRequests(t *testing.T) {
|
||||
require.NoError(t, unittest.PrepareTestDatabase())
|
||||
ctx, resp := contexttest.MockPrivateContext(t, "/")
|
||||
ctx.SetPathParam("owner", "user2")
|
||||
ctx.SetPathParam("repo", "repo2")
|
||||
RepoAssignment(ctx)
|
||||
require.False(t, ctx.Written())
|
||||
defer ctx.Repo.GitRepo.Close()
|
||||
|
||||
web.SetForm(ctx, &private.HookOptions{
|
||||
UserID: 2,
|
||||
RefFullNames: []git.RefName{"refs/for/master"},
|
||||
})
|
||||
HookProcReceive(ctx)
|
||||
assert.Equal(t, http.StatusForbidden, resp.Code, resp.Body.String())
|
||||
}
|
||||
@@ -6,6 +6,7 @@ package private
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"slices"
|
||||
|
||||
issues_model "gitea.dev/models/issues"
|
||||
user_model "gitea.dev/models/user"
|
||||
@@ -23,7 +24,8 @@ func HookProcReceive(ctx *gitea_context.PrivateContext) {
|
||||
ctx.Status(http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
if !loadContextDoerPermission(ctx, opts.UserID, opts.UserExtDoerData) {
|
||||
if !loadContextDoerPermission(ctx, opts.UserID, opts.UserExtDoerData) ||
|
||||
(slices.ContainsFunc(opts.RefFullNames, git.RefName.IsFor) && !assertCanCreatePullRequest(ctx, opts)) {
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
@@ -10,9 +10,11 @@ import (
|
||||
audit_model "gitea.dev/models/audit"
|
||||
"gitea.dev/models/auth"
|
||||
user_model "gitea.dev/models/user"
|
||||
"gitea.dev/modules/log"
|
||||
"gitea.dev/modules/session"
|
||||
"gitea.dev/modules/setting"
|
||||
"gitea.dev/modules/templates"
|
||||
"gitea.dev/modules/util"
|
||||
"gitea.dev/modules/web"
|
||||
"gitea.dev/services/audit"
|
||||
"gitea.dev/services/context"
|
||||
@@ -60,13 +62,13 @@ func TwoFactorPost(ctx *context.Context) {
|
||||
}
|
||||
|
||||
// Validate the passcode and atomically consume it to prevent reuse/replay.
|
||||
ok, err := twofa.ValidateAndConsumeTOTP(ctx, form.Passcode)
|
||||
tfaResult, err := twofa.ValidateAndConsumeTOTP(ctx, form.Passcode)
|
||||
if err != nil {
|
||||
ctx.ServerError("UserSignIn", err)
|
||||
return
|
||||
}
|
||||
|
||||
if ok {
|
||||
if tfaResult == auth.TwoFactorResultValid {
|
||||
remember := ctx.Session.Get("twofaRemember").(bool) //nolint:forcetypeassert // must exist
|
||||
u, err := user_model.GetUserByID(ctx, id)
|
||||
if err != nil {
|
||||
@@ -86,9 +88,10 @@ func TwoFactorPost(ctx *context.Context) {
|
||||
|
||||
if u, err := user_model.GetUserByID(ctx, id); err == nil {
|
||||
audit.RecordAs(ctx, u, audit_model.UserAuthenticationFailTwoFactor, u)
|
||||
log.Warn("Failed authentication attempt for %s from %s: invalid two-factor passcode", u.Name, ctx.RemoteAddr())
|
||||
}
|
||||
|
||||
ctx.RenderWithErrDeprecated(ctx.Tr("auth.twofa_passcode_incorrect"), tplTwofa, forms.TwoFactorAuthForm{})
|
||||
errMsg := ctx.Tr(util.Iif(tfaResult == auth.TwoFactorResultTooManyAttempts, "auth.twofa_too_many_attempts", "auth.twofa_passcode_incorrect"))
|
||||
ctx.RenderWithErrDeprecated(errMsg, tplTwofa, forms.TwoFactorAuthForm{})
|
||||
}
|
||||
|
||||
// TwoFactorScratch shows the scratch code form for two-factor authentication.
|
||||
|
||||
@@ -189,22 +189,22 @@ func IntrospectOAuth(ctx *context.Context) {
|
||||
ctx.ServerError("GetOAuth2GrantByID", err)
|
||||
return
|
||||
}
|
||||
if grant == nil || grant.ApplicationID != introspectingApp.ID {
|
||||
if grant == nil || grant.ApplicationID != introspectingApp.ID || (token.Kind == oauth2_provider.KindRefreshToken && isRefreshTokenUsed(grant, token)) {
|
||||
// RFC 7662 allows the server to reply inactive when the caller must not learn more.
|
||||
// https://www.rfc-editor.org/rfc/rfc7662.html#section-2.2
|
||||
ctx.JSON(http.StatusOK, response)
|
||||
return
|
||||
}
|
||||
|
||||
response.Active = true
|
||||
response.Scope = grant.Scope
|
||||
response.RegisteredClaims = oauth2_provider.NewJwtRegisteredClaimsFromUser(introspectingApp.ClientID, grant.UserID, nil /*exp*/)
|
||||
user, err := user_model.GetUserByID(ctx, grant.UserID)
|
||||
if err != nil {
|
||||
ctx.ServerError("GetUserByID", err)
|
||||
if user, err := user_model.GetValidDoerUserByID(ctx, grant.UserID); err == nil {
|
||||
response.Active = true
|
||||
response.Scope = grant.Scope
|
||||
response.RegisteredClaims = oauth2_provider.NewJwtRegisteredClaimsFromUser(introspectingApp.ClientID, grant.UserID, nil /*exp*/)
|
||||
response.Username = user.Name
|
||||
} else if !errors.Is(err, util.ErrNotExist) && !errors.Is(err, util.ErrPermissionDenied) {
|
||||
ctx.ServerError("GetValidDoerUserByID", err)
|
||||
return
|
||||
}
|
||||
response.Username = user.Name
|
||||
|
||||
ctx.JSON(http.StatusOK, response)
|
||||
}
|
||||
@@ -559,6 +559,10 @@ func AccessTokenOAuth(ctx *context.Context) {
|
||||
}
|
||||
}
|
||||
|
||||
func isRefreshTokenUsed(grant *auth.OAuth2Grant, token *oauth2_provider.Token) bool {
|
||||
return setting.OAuth2.InvalidateRefreshTokens && (grant.Counter != token.Counter || token.Counter == 0)
|
||||
}
|
||||
|
||||
func handleRefreshToken(ctx *context.Context, form forms.AccessTokenForm, serverKey, clientKey oauth2_provider.JWTSigningKey) {
|
||||
app, err := auth.GetOAuth2ApplicationByClientID(ctx, form.ClientID)
|
||||
if err != nil {
|
||||
@@ -610,7 +614,7 @@ func handleRefreshToken(ctx *context.Context, form forms.AccessTokenForm, server
|
||||
}
|
||||
|
||||
// check if token got already used
|
||||
if setting.OAuth2.InvalidateRefreshTokens && (grant.Counter != token.Counter || token.Counter == 0) {
|
||||
if isRefreshTokenUsed(grant, token) {
|
||||
handleAccessTokenError(ctx, oauth2_provider.AccessTokenError{
|
||||
ErrorCode: oauth2_provider.AccessTokenErrorCodeUnauthorizedClient,
|
||||
ErrorDescription: "token was already used",
|
||||
|
||||
@@ -14,6 +14,8 @@ import (
|
||||
user_model "gitea.dev/models/user"
|
||||
"gitea.dev/modules/egress/policy"
|
||||
"gitea.dev/modules/session"
|
||||
"gitea.dev/modules/setting"
|
||||
"gitea.dev/modules/test"
|
||||
"gitea.dev/modules/web"
|
||||
"gitea.dev/services/contexttest"
|
||||
"gitea.dev/services/forms"
|
||||
@@ -51,7 +53,7 @@ func createAndParseToken(t *testing.T, grant *auth.OAuth2Grant) *oauth2_provider
|
||||
func TestNewAccessTokenResponse_OIDCToken(t *testing.T) {
|
||||
assert.NoError(t, unittest.PrepareTestDatabase())
|
||||
|
||||
grants, err := auth.GetOAuth2GrantsByUserID(t.Context(), 3)
|
||||
grants, err := auth.GetOAuth2GrantsByUserID(t.Context(), 14)
|
||||
assert.NoError(t, err)
|
||||
assert.Len(t, grants, 1)
|
||||
|
||||
@@ -81,6 +83,19 @@ func TestNewAccessTokenResponse_OIDCToken(t *testing.T) {
|
||||
assert.Equal(t, user.UpdatedUnix, oidcToken.UpdatedAt)
|
||||
assert.Equal(t, user.Email, oidcToken.Email)
|
||||
assert.Equal(t, user.IsActive, oidcToken.EmailVerified)
|
||||
|
||||
defer test.MockVariableValue(&setting.OAuth2.InvalidateRefreshTokens, true)()
|
||||
require.NoError(t, user_model.UpdateUserCols(t.Context(), &user_model.User{ID: user.ID}, "is_active"))
|
||||
defer func() {
|
||||
require.NoError(t, user_model.UpdateUserCols(t.Context(), user, "is_active"))
|
||||
}()
|
||||
signingKey, err := oauth2_provider.CreateJWTSigningKey("HS256", make([]byte, 32))
|
||||
require.NoError(t, err)
|
||||
counter := grants[0].Counter
|
||||
response, tokenErr := oauth2_provider.NewAccessTokenResponse(t.Context(), grants[0], signingKey, signingKey)
|
||||
assert.Nil(t, response)
|
||||
assert.Equal(t, &oauth2_provider.AccessTokenError{ErrorCode: oauth2_provider.AccessTokenErrorCodeInvalidGrant, ErrorDescription: "user is not allowed to sign in"}, tokenErr)
|
||||
assert.Equal(t, counter, unittest.AssertExistsAndLoadBean(t, &auth.OAuth2Grant{ID: grants[0].ID}).Counter)
|
||||
}
|
||||
|
||||
func TestOAuth2AvatarClientBlocksLoopback(t *testing.T) {
|
||||
|
||||
@@ -16,6 +16,7 @@ import (
|
||||
"gitea.dev/modules/setting"
|
||||
"gitea.dev/modules/templates"
|
||||
"gitea.dev/modules/timeutil"
|
||||
"gitea.dev/modules/util"
|
||||
"gitea.dev/modules/web"
|
||||
"gitea.dev/routers/common"
|
||||
"gitea.dev/services/audit"
|
||||
@@ -187,15 +188,17 @@ func ResetPasswdPost(ctx *context.Context) {
|
||||
regenerateScratchToken = true
|
||||
} else {
|
||||
passcode := ctx.FormString("passcode")
|
||||
ok, err := twofa.ValidateAndConsumeTOTP(ctx, passcode)
|
||||
tfaResult, err := twofa.ValidateAndConsumeTOTP(ctx, passcode)
|
||||
if err != nil {
|
||||
ctx.HTTPError(http.StatusInternalServerError, "ValidateAndConsumeTOTP", err.Error())
|
||||
return
|
||||
}
|
||||
if !ok {
|
||||
if tfaResult != auth.TwoFactorResultValid {
|
||||
log.Warn("Failed authentication attempt for %s from %s: invalid two-factor passcode", u.Name, ctx.RemoteAddr())
|
||||
ctx.Data["IsResetForm"] = true
|
||||
ctx.Data["Err_Passcode"] = true
|
||||
ctx.RenderWithErrDeprecated(ctx.Tr("auth.twofa_passcode_incorrect"), tplResetPassword, nil)
|
||||
errMsg := ctx.Tr(util.Iif(tfaResult == auth.TwoFactorResultTooManyAttempts, "auth.twofa_too_many_attempts", "auth.twofa_passcode_incorrect"))
|
||||
ctx.RenderWithErrDeprecated(errMsg, tplResetPassword, nil)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
@@ -203,6 +203,7 @@ func ChangeProjectStatus(ctx *context.Context) {
|
||||
ctx.NotFoundOrServerError("ChangeProjectStatusByRepoIDAndID", project_model.IsErrProjectNotExist, err)
|
||||
return
|
||||
}
|
||||
audit.Record(ctx, audit_model.ProjectUpdate, ctx.ContextUser, "project", project.Title, "project_id", project.ID)
|
||||
ctx.JSONRedirect(project_model.ProjectLinkForOrg(ctx.ContextUser, project.ID))
|
||||
}
|
||||
|
||||
|
||||
Loaded 100 of 227 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user