Compare commits

..
50 Commits
Author SHA1 Message Date
Giteabotandsilverwind 4be850fef8 fix(gpg): verify OpenPGP v6 commit signatures (#40631) (#40646)
Backport #40631 by @silverwind

Commit verification skipped the salt that OpenPGP v6 signatures (RFC
9580) hash before the data, so v6-signed commits never verified. Use
go-crypto's `PrepareVerify`, which adds it. Post-quantum ML-DSA
signatures (RFC 9980) require v6 keys, so they now verify too.

Assisted-by: Claude Code:claude-opus-5-5

Co-authored-by: silverwind <me@silverwind.io>
2026-12-04 08:06:07 +00:00
wxiaoguangandsilverwind 41b3d0d4e3 fix: make FormStrings parse form data correctly (#40558) (#40560)
backport #40558

---------

Co-authored-by: silverwind <me@silverwind.io>
2026-11-27 12:53:45 +00:00
1cadf5338b fix(glob): treat escaped characters as literals (#40516) (#40561)
Backport #40516 by @karnati-praveen

The glob compiler wrote a backslash followed by the escaped character
into the generated regexp, so `\d`, `\w`, `\s` and `\b` were parsed as
regexp constructs instead of the literal character. `a\d` compiled to
`^a\d$` and matched "a5" instead of "ad"; `a\b` became a zero-width word
boundary. Escaping a character Go does not recognise, e.g. `\C`, made
the pattern fail to compile, and protected branch rules then fell back
to matching the raw rule text literally.

Escape only ASCII punctuation, which Go always reads as a literal, and
write letters, digits and non-ASCII characters as-is. This matches
gobwas/glob and act. Rules that relied on `\d` matching a digit since
https://github.com/go-gitea/gitea/pull/35478 now match a literal `d`.

Assisted-by: OpenCode (DeepSeek V4.1 Flash)
Assisted-by: Claude Code:claude-opus-5-5

Co-authored-by: karnati praveen <karnatipraveen17@gmail.com>
Co-authored-by: silverwind <me@silverwind.io>
2026-11-27 12:53:17 +00:00
bircni 38ce87a77e chore: stop accepting security reports by mail (#40544) (#40545)
Backport of https://github.com/go-gitea/gitea/pull/40544

The volume of reports sent to `security@gitea.io` can no longer be
handled, so vulnerability reports are now only accepted through GitHub
security advisories. The security policy says so explicitly, and the
README, contributing guide and issue templates point to the advisory
form instead of the mail address.

The address stays for security matters that are not vulnerability
reports, such as questions about the policy or coordinating the
disclosure of an existing advisory.
2026-11-26 14:43:13 +00:00
Giteabotandsilverwind 2d84f79e3b perf: avoid commit status summary full table scan (#40451) (#40459)
Backport #40451 by @silverwind

The dashboard repo list read the entire `commit_status_summary` table on
every load when the page held an empty repo and the other repos'
statuses were cached, about 1.2 s with 1M rows. Those other repos also
showed and cached the status of an arbitrary older commit.

Also fixes the MySQL upsert not updating `target_url`.

Assisted-by: Claude Code:claude-opus-5-5

Co-authored-by: silverwind <me@silverwind.io>
2026-11-20 11:41:12 +00:00
62e9f747e8 fix(web): redirect to the branch after applying a patch (#40450) (#40455)
Backport #40450 by @lazerg

After applying a patch in the web editor, Gitea redirected to
`/src/branch/<branch>/__dummy_for_EditRepoFileForm.TreePath(Required)__`,
which is a 404. The patch form only sends that placeholder `tree_path`
to pass form validation, but the handler still used it as the redirect
path. It now redirects to the branch root, like cherry-pick and revert
do.

Fixes: https://github.com/go-gitea/gitea/issues/40449

Assisted-by: Claude Code:claude-opus-5-5

Co-authored-by: Lazizbek Ergashev <lazerg2@gmail.com>
Co-authored-by: wxiaoguang <wxiaoguang@gmail.com>
2026-11-20 10:20:35 +00:00
93ae5fb35b fix(routing): remove unsynchronized write in GetFuncInfo (#40409) (#40421)
Backport #40409 by @lazerg

`GetFuncInfo` wrote the friendly name into `funcInfoNameMap` once
without holding `funcInfoMapMu`, right before the same locked write.
Concurrent requests hitting that branch could then crash the process
with `fatal error: concurrent map writes`. This drops the unlocked
write.

Fixes: https://github.com/go-gitea/gitea/issues/40407

Assisted-by: Claude Code:claude-opus-5-5

Co-authored-by: Lazizbek Ergashev <lazerg2@gmail.com>
Co-authored-by: Lunny Xiao <xiaolunwen@gmail.com>
2026-11-17 23:33:05 +00:00
f8c4012ab8 fix(migrations): wait out GitHub rate limits and tolerate failed patch downloads (#40012) (#40397)
Backport https://github.com/go-gitea/gitea/pull/40012

Large GitHub migrations failed once the API budget ran out. A rejected
request never updated the downloader's rate state, so go-github refused
every retry locally.

- Record the rate limit from error responses too, so the next request
waits for the reset
- Retry repository-wide comment pages like the other downloader calls
- Stop `waitAndPickClient` spinning when the rate refresh fails
- Skip reaction requests when the reaction rollup reports none
- Log a failed patch download instead of failing the migration

Assisted-by: Claude Code:claude-opus-5-5

Co-authored-by: Phoenix <44333391+yuhongwei380@users.noreply.github.com>
Co-authored-by: bircni <bircni@icloud.com>
Co-authored-by: Giteabot <teabot@gitea.io>
2026-11-17 20:26:49 +00:00
silverwind a0f0c937c4 fix(packages): replace blakesmith/ar with an in-tree reader (#40401) (#40410)
Backport https://github.com/go-gitea/gitea/pull/40401

https://github.com/blakesmith/ar is unmaintained since 2019 and panics
on a negative member size (https://pkg.go.dev/vuln/GO-2026-6905), with
no fixed version. Debian packages only need a small subset of the `ar`
format, so this reads it in-tree.

- Malformed or truncated archives are rejected with a 400 instead of a
500 or a panic
- Parsing stops after the first `control.tar` member, deb(5) allows only
one

Assisted-by: Claude Code:claude-opus-5-5
2026-11-17 05:17:20 +00:00
0b5dfdeeea fix(repo): do not check out existing repo content during auto-init (#40376) (#40383)
Backport #40376 by @bircni

Plain repository creation marked a new repository as ready before its
git data, hooks and initial commit existed, and auto-init cloned the new
repository to build its initial commit on top of whatever it already
contained.

- Auto-init builds the initial commit in a freshly initialized temp
repository instead of a clone
- New repositories are inserted as being created and marked ready once
initialized, as fork, template generation, adoption and migrations
already do

---------

Co-authored-by: bircni <bircni@icloud.com>
Co-authored-by: Lunny Xiao <xiaolunwen@gmail.com>
Co-authored-by: silverwind <me@silverwind.io>
2026-11-15 18:39:36 +00:00
6b5f406f81 fix(auth): limit failed TOTP attempts per account (#39993) (#40374)
Backport https://github.com/go-gitea/gitea/pull/39993

Gitea accepted unlimited wrong TOTP passcodes, so anyone holding an
account's password could enumerate the 6-digit code in minutes. This
allows 5 failed attempts per account, then refuses TOTP until 15 minutes
after the last one.

- The count lives in the cache, and the global lock spans the check,
validation and counting, so new sessions and concurrent requests cannot
widen it. With Redis, both are shared across instances
- Applies to every TOTP check: the web 2FA page, account recovery and
Basic auth with `X-Gitea-OTP` (API, git, packages)
- Only wrong or replayed passcodes count, server errors do not
- Scratch codes and WebAuthn stay usable as the recovery path while
locked
- Failures log `Failed authentication attempt for <user> from <ip>`,
which the fail2ban filter already matches

Co-authored-by: Sandiyo Christan <55909152+sandiyochristan@users.noreply.github.com>
Co-authored-by: silverwind <me@silverwind.io>
Co-authored-by: wxiaoguang <wxiaoguang@gmail.com>
Co-authored-by: Lunny Xiao <xiaolunwen@gmail.com>
2026-11-15 17:26:33 +00:00
bf2eb11ec1 fix(audit): record missing repository and content events (#40322) (#40390)
Backport https://github.com/go-gitea/gitea/pull/40322

Several API and background paths change repositories without writing the
audit event the web UI writes for the same change. This records the
existing actions on those paths, and webhook, secret and OAuth2
application events now also keep the impersonator.

Conflicts resolved for release/v28:
- The web project close/reopen handler uses
`NotFoundOrServerError`/`ServerError`, as `ServerErrorAuto` does not
exist on this branch.
- The repository webhook delete API keeps its documented 404 response.
- The notifier test keeps the release branch layout with the new cases
appended.

Signed-off-by: bircni <bircni@icloud.com>
Co-authored-by: silverwind <me@silverwind.io>
Co-authored-by: delvh <dev.lh@web.de>
2026-11-15 16:32:23 +00:00
bircniandwxiaoguang b0088f060b fix(repo): limit the commit status fields returned by repo search (#40377) (#40384)
Backport https://github.com/go-gitea/gitea/pull/40377

The web repo search response embedded the whole commit status model
although the dashboard only uses its state and target URL. It now
returns just those two fields.

Co-authored-by: wxiaoguang <wxiaoguang@gmail.com>
2026-11-15 16:28:28 +00:00
bircni df961a3962 fix(api): do not allow renaming the Owners team (#40381) (#40387)
Backport https://github.com/go-gitea/gitea/pull/40381

The API accepted a new name for an organization's Owners team. The owner
team is looked up by its name, so the organization had no owner team
afterwards and its owners lost access to it.

The API now rejects the rename, as the web UI already does.

Fixes #40380
2026-11-15 13:41:13 +00:00
58df887de6 fix(issues): hide unreadable issue types in search and milestone views (#40192) (#40375)
Backport https://github.com/go-gitea/gitea/pull/40192

The repository issue search JSON route sits behind the issues reader
check only, and the milestone page is open to anyone who can read either
issues or pull requests, since the issue routes have to tolerate pull
request permissions. Neither handler narrows the issue type to what the
viewer may read: the search route takes `type=pulls` straight from the
query or lists both types when it is absent, and the milestone page
always lists both. A team member granted only the Issues unit on a
private repository can therefore fetch every pull request's title and
body as JSON and see pull requests on milestone pages, while a
pull-requests-only reader sees issues there. I noticed it while
comparing these routes with the API `ListIssues` handler and the web
issue suggestions endpoint, which both already narrow the type. The
narrowing now lives in one small helper used by all three handlers, with
the search route answering 404 for a requested type the viewer cannot
read, like the API does. A unit test covers both handlers with an
issues-only permission.

Co-authored-by: Basavaraj S m <basavaraj@digiscrypt.com>
Co-authored-by: wxiaoguang <wxiaoguang@gmail.com>
2026-11-15 10:05:10 +00:00
fff18237d5 fix(repo): do not reuse pull mirror credentials for a new host (#39991) (#40373)
Backport https://github.com/go-gitea/gitea/pull/39991

Changing a pull mirror address with an empty password field carried the
stored credentials over to the new address. The password is write-only,
so a repo admin who did not set up the mirror could send the owner's
token to a host they control, or pull another repository on the same
host that the token can read.

Stored credentials are now reused only when the address is unchanged,
like a changed username already drops the stored password. The API
cannot change the address and push mirrors never reuse credentials, so
both are unaffected.

Co-authored-by: Basavaraj S m <basavaraj@digiscrypt.com>
Co-authored-by: silverwind <me@silverwind.io>
2026-11-15 05:04:55 +00:00
Lunny Xiao 06a2286930 fix(git): list affected files NUL-separated so special names are not quoted (#40362)
Backport of the `GetAffectedFiles` fix from main (#40326) to v28.

`git diff --name-only` C-quotes paths containing characters such as `"`
or non-ASCII bytes, so they never matched protected file patterns. Use
`diff-tree -r -z` and split on NUL. Renames now report both old and new
paths.

Assisted-by: Codet:claude
2026-11-14 12:19:53 +00:00
silverwindandBasavaraj S m 0c6645958b fix(api): hide org roles from non-members (#40042) (#40365)
Backport https://github.com/go-gitea/gitea/pull/40042

`GET /users/{username}/orgs/{org}/permissions` returned a user's team
roles to anyone who could see the org, revealing concealed members and
their roles. Now only the user, unrestricted org members and site admins
get the real answer, everyone else gets the non-member response:

- Outsiders get no roles, for public members too.
- Restricted members only get their own roles.
- Public-only tokens get none, and site admins need an `all`-scoped
token.

v28 lacks the doer token helpers from
https://github.com/go-gitea/gitea/pull/39690, so the check reads
`ctx.PublicOnly` and the request's token scope instead.

Assisted-by: Claude Code:claude-opus-5-5

Co-authored-by: Basavaraj S m <basavaraj@digiscrypt.com>
2026-11-14 12:19:34 +00:00
660c4b1de6 fix(packages): accept OCI 1.1 container image names (#40363) (#40369)
Backport #40363 by @lazerg

The container registry rejected image names with `__` or runs of `-`
(like `a__b` or `a--b`) with `NAME_INVALID`, because the name check
still used the distribution-spec v1.0 grammar. This updates the pattern
to the v1.1 grammar, which docker and podman already accept.

Fixes: https://github.com/go-gitea/gitea/issues/40360

Assisted-by: Claude Code:claude-opus-5-5

Signed-off-by: wxiaoguang <wxiaoguang@gmail.com>
Co-authored-by: Lazizbek Ergashev <lazerg2@gmail.com>
Co-authored-by: wxiaoguang <wxiaoguang@gmail.com>
2026-11-14 12:18:43 +00:00
Giteabotandwxiaoguang 7210b4cc52 fix: correctly apply team admin permission to doer (#40353) (#40356)
Backport #40353 by @wxiaoguang

fix #40352

Co-authored-by: wxiaoguang <wxiaoguang@gmail.com>
2026-11-13 22:47:38 +00:00
Giteabotandsilverwind 87c509a405 fix(web): fix memory leak in dropdown ARIA patch (#40349) (#40364)
Backport #40349 by @silverwind

Dropdowns initialized without an options object shared the default
Fomantic templates, so the ARIA patch kept wrapping `templates.menu` on
the defaults and retained every dropdown ever created. This grows memory
on the Actions run list, which re-renders its dropdowns on each refresh.

Each dropdown now gets its own templates copy, which the ARIA patch
modifies in place.

Fixes: https://github.com/go-gitea/gitea/issues/40347

Assisted-by: Claude Code:claude-opus-5-5

Co-authored-by: silverwind <me@silverwind.io>
2026-11-13 22:45:39 +00:00
95b69a4a2d fix(queue): bump levelqueue to v0.5.1 and remove workarounds (#40219) (#40350)
Backport https://github.com/go-gitea/gitea/pull/40219

levelqueue v0.5.1 fixes this upstream
(https://gitea.com/lunny/levelqueue/pulls/8), so this now only bumps the
dependency.

A push wrote "high" before the payload, so an interrupted push left an
id counted with no key. `LPop` then returned `ErrNotFound` without
advancing "low" and the wrapper retried forever: nothing popped, no
worker started, later items unreachable. All were only fixable by
clearing the queue, losing the backlog:
- https://github.com/go-gitea/gitea/issues/32006 — mail, 0 workers
- https://github.com/go-gitea/gitea/issues/28919 — mirror, "already in
queue"
- https://github.com/go-gitea/gitea/issues/33862 — archives hanging
- https://github.com/go-gitea/gitea/issues/33882 — self-healing request

v0.5.1 writes counter and payload in one batch, moves the counters past
missing keys, and repairs leftover unique-queue set entries, so affected
instances recover on their next pop.

No test: the behaviour lives in the dependency, which covers it in its
own `recover_test.go`.

Assisted-by: Claude Code:claude-opus-5-5

Signed-off-by: wxiaoguang <wxiaoguang@gmail.com>
Co-authored-by: William Desportes <williamdes@wdes.fr>
Co-authored-by: wxiaoguang <wxiaoguang@gmail.com>
Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
2026-11-13 17:12:25 +00:00
silverwind b60da6d876 enhance(websocket): improve client synchronization (#38847) (#40340)
Backport of https://github.com/go-gitea/gitea/pull/38847, which fixes
the stopwatch push flake in
https://github.com/go-gitea/gitea/actions/runs/43200377380/job/131122930118.

The stopwatch e2e test keeps its v28 flow, since main reworked it in a
separate change.

Assisted-by: Claude Code:claude-opus-5-5
2026-11-12 14:00:15 +00:00
78698abee0 fix: handle task list items checked with uppercase X (#40334) (#40339)
Backport #40334 by @SudhanshuMatrix

Markdown renders `[X]` as a checked task like `[x]`, but parts of the
frontend only recognize lowercase `x`.

- Clicking a `[X]` checkbox now unchecks it instead of failing.
- Pressing Enter on a `- [X]` line in the editor continues the list with
`- [ ] ` instead of dropping the checkbox.

Assisted-by: Claude Code:claude-opus-5-5

Co-authored-by: Shudhanshu Singh <sudhanshuwriterblc@gmail.com>
Co-authored-by: silverwind <me@silverwind.io>
2026-11-12 11:56:50 +00:00
silverwind b24cd7839b fix: add missing checks to more handlers and services (#40131) (#40281)
Backport https://github.com/go-gitea/gitea/pull/40131

Several code paths skipped checks that their siblings already perform.

- Code comment replies are rejected when they target a review of another
pull request or another user's pending review
- OAuth2 refuses tokens for users who can't sign in, and introspection
reports their tokens and already used refresh tokens as inactive
- AGit proc-receive runs the same pull request permission and wiki
checks as pre-receive
- Repository transfer drops the repository's owner-level scoped workflow
source registrations, and registrations whose source the owner no longer
owns are ignored
- The web editor's base branch copy into a fork and the fork's upstream
divergence info require read access to the base repository
- LFS downloads require sign-in under strict `REQUIRE_SIGNIN_VIEW`, like
git smart HTTP
- Unknown AGit target branches are reported as an unexpected ref again

Assisted-by: Claude:claude-opus-5-5
2026-11-11 17:05:39 +00:00
silverwind 5c69d5710a fix(ui): consistent spacing between labels (#40261) (#40330)
Backport https://github.com/go-gitea/gitea/pull/40261

The issue reference popup showed its labels without any spacing, and the
other label lists each used their own gap, with wrapped rows spaced
differently from columns.

`.labels-list` is now a wrapping flex list with `--gap-inline` by
default, giving the popup, issue sidebar and project cards equal gaps in
both directions. Lists inline with text, in issue list titles and
timeline events, stay inline so their labels still wrap one by one.

<img width="600" alt="Issue reference popup, issue sidebar and issue
list labels, before and after"
src="https://github.com/user-attachments/assets/fc4f0b9e-2b9d-4060-a2fb-c1bd3b7391db"
/>

Assisted-by: Claude Code:claude-opus-5-5
2026-11-11 14:39:45 +00:00
Giteabot 7b466a8a66 chore(deps): update go toolchain directive to v1.27.4 (#40315) (#40318)
Backport #40315 by @GiteaBot

This PR contains the following updates:

| Package | Type | Update | Change |
|---|---|---|---|
| [go](https://go.dev/)
([source](https://redirect.github.com/golang/go)) | toolchain | patch |
`1.27.3` → `1.27.4` |

---

### Configuration

📅 **Schedule**: (UTC)

- Branch creation
  - At any time (no schedule defined)
- Automerge
  - At any time (no schedule defined)

🚦 **Automerge**: Disabled by config. Please merge this manually once you
are satisfied.

♻ **Rebasing**: Whenever PR becomes conflicted, or you tick the
rebase/retry checkbox.

🔕 **Ignore**: Close this PR and you won't be reminded about this update
again.

---

- [ ] <!-- rebase-check -->If you want to rebase/retry this PR, check
this box

---

This PR has been generated by [Mend Renovate
CLI](https://redirect.github.com/renovatebot/renovate).

<!--renovate-debug:eyJjcmVhdGVkSW5WZXIiOiI0NC4yMTAuMCIsInVwZGF0ZWRJblZlciI6IjQ0LjIxMC4wIiwidGFyZ2V0QnJhbmNoIjoibWFpbiIsImxhYmVscyI6WyJkZXBlbmRlbmNpZXMiXX0=-->
2026-11-10 18:51:06 +00:00
GiteabotandLunny Xiao f9d31d2f11 fix(api): lock and unlock issues as the signed-in user, not the repository owner (#40291) (#40298)
Backport #40291 by @lunny

`PUT/DELETE /repos/{owner}/{repo}/issues/{index}/lock` passed
`ctx.ContextUser` as the doer of `LockIssue` / `UnlockIssue`. In the
repo routes that is the owner of the repository, so on a repository of
an organization the lock and unlock timeline comments were created by
the organization instead of the user who did it. The web handler already
uses the signed-in user; this uses `ctx.Doer` as well.

Adds a subtest `DoerOnOrganizationRepo` to the existing
`TestAPILockIssue`: a member of an organization locks and unlocks an
issue of an organization repository, and the comments must be posted by
that member.

Found while testing audit logging of the issue lock events downstream.

_Authored by Codet (Claude)._

Co-authored-by: Lunny Xiao <xiaolunwen@gmail.com>
2026-11-10 15:55:38 +00:00
Hyeonmin Parkandwxiaoguang 24bceb9f6e fix(markup): correct character escaping at read buffer boundaries (#40209)
When a file, README or wiki page is rendered as markup, the HTML is read
through a 32 KiB buffer to escape invisible and ambiguous characters. A
multi-byte character cut by that buffer right after a tag was shown as
broken characters, e.g. `<p>보기</p>` became `<p>���기</p>`. Such a part is
now kept for the next read. Two related cases are fixed as well:

- Invalid bytes right before a tag are marked as broken instead of
passing through raw as part of the tag.
- A BOM split across reads is kept instead of being escaped as
invisible.

To reproduce, view a Markdown file with 32734 `A` characters, a blank
line and `보기`, which puts `보` across the first 32 KiB of the rendered
HTML:
[split-rune-after-tag.md](https://github.com/user-attachments/files/34361104/split-rune-after-tag.md)

https://github.com/go-gitea/gitea/pull/39937 replaces this reader with a
single in-memory pass. This small fix can be backported to the release
branches.

Assisted-by: Claude Code:claude-opus-5-5

----

| Before (2ed6a6f61b) | After
(2a1d09755fecab764336ce9069e864c1a3b20c7c) |
| --- | --- |
|
![image](https://github.com/user-attachments/assets/d4f79a8a-17bd-4b7f-b853-1d1a7241dc9b)
|
![image](https://github.com/user-attachments/assets/d4b8b3dd-e28e-44dd-99de-d250ee4c282c)
|

Co-authored-by: wxiaoguang <wxiaoguang@gmail.com>
2026-11-09 16:36:34 +00:00
Giteabotandwxiaoguang df01835a83 fix: don't log network error in console when loading issue popup (#40288) (#40294)
Backport #40288

* fix #40286

Signed-off-by: wxiaoguang <wxiaoguang@gmail.com>
Co-authored-by: wxiaoguang <wxiaoguang@gmail.com>
2026-11-09 06:13:17 +00:00
silverwind 8e5585c5b9 fix(deps): update clippie to 4.3.1 (#40293)
Update clippie to 4.3.1, which fixes copy buttons in browsers that have
`navigator.clipboard.write` but no `ClipboardItem`, such as Pale Moon.
Text is now copied through `writeText`, with a copy event as fallback.
The same update is part of https://github.com/go-gitea/gitea/pull/40292
on main.

Fixes: https://github.com/go-gitea/gitea/issues/40287

Assisted-by: Claude Code:claude-opus-5-5
2026-11-09 05:59:36 +00:00
Giteabotandsilverwind 7d73ce020e fix: paste copied code as text, not as a markdown table (#40053) (#40280)
Backport #40053 by @silverwind

Copying lines from a diff, file view, blame, code search or code preview
and pasting them into a comment on Gitea or GitHub produced a markdown
table with escaped pipes and stripped indentation. Both use
`@github/paste-markdown`, which converts copied HTML tables unless they
carry `data-paste-markdown-skip`, as GitHub's own code tables do.
Gitea's code tables now set it too.

The test is a bit more complicated because of a upstream bug which
causes `paste-markdown` to insert pasted content twice, once
https://github.com/github/paste-markdown/pull/128 is merged and
released, the negative assertion could be removed.

Signed-off-by: silverwind <me@silverwind.io>
Co-authored-by: silverwind <me@silverwind.io>
2026-11-08 10:02:48 +00:00
f357a03049 fix(pull): don't add a timeline entry for pending API reviews (#40260) (#40272)
Backport #40260 by @lazerg

Pending reviews created through the API went through `SubmitReview`,
which added a timeline entry and sent notifications before the review
was submitted, so submitting it later showed the review twice.

- Pending reviews skip the timeline entry and notifications until
submitted, like on GitHub
- `CreatePullReview` rejects comments without a `path` or a positive
line with 422, like GitHub
- Already duplicated reviews stay as they are

Fixes https://github.com/go-gitea/gitea/issues/40259

Assisted-by: Claude Code:claude-opus-5-5

Co-authored-by: Lazizbek Ergashev <lazerg2@gmail.com>
Co-authored-by: silverwind <me@silverwind.io>
2026-11-07 15:36:19 +00:00
53cf53cbbc fix: add missing checks to several handlers and services (#40120) (#40268)
Backport #40120 by @silverwind

Several code paths skipped checks their siblings perform, or cleaned up
more than they validated.

- Official team review requests now count, and removing one no longer
marks an unrelated review official
- Release edits only delete files of validated attachments
- Rejected container uploads no longer delete an existing blob
- Attachment removal only removes the uploader's own pending uploads
- OpenID sign-in checks the allow and block lists against the normalized
identifier
- HTTP git access is rejected while a repository is being created, like
SSH

Signed-off-by: silverwind <me@silverwind.io>
Co-authored-by: silverwind <me@silverwind.io>
Co-authored-by: delvh <dev.lh@web.de>
Co-authored-by: wxiaoguang <wxiaoguang@gmail.com>
2026-11-07 10:51:18 +00:00
ba591d2d5a fix(repo): mark repository as non-empty before git push returns (#40102) (#40266)
Backport #40102 by @Zettat123

The post-receive hook syncs pushed branches to the database, but
`is_empty` and the default branch of an empty repository were only
updated later by the `push_update` queue. Until then the API treated the
repository as empty (branch list `null`, `GET /branches/{branch}` 500),
and the queue overwrote the default branch chosen by the hook or set via
the API.

`SyncBranchesToDB` now initializes an empty repository and repairs a
default branch missing in git in its locked transaction, so the state is
final when `git push` returns. The push queue and web file edits retry
it while the repository is still empty.

- The default branch is the configured one if it exists, else `main`,
else `master`, else the first branch by name, like GitLab. HEAD follows
it.
- A first push of several branches no longer depends on push order. The
push that initializes a repository still prints no pull request hints,
like GitHub.

---------

Co-authored-by: Zettat123 <zettat123@gmail.com>
Co-authored-by: silverwind <me@silverwind.io>
2026-11-07 04:26:04 +00:00
317db14701 fix: don't roll back branches on out-of-order post-receive hooks (#40110) (#40255)
Backport https://github.com/go-gitea/gitea/pull/40110

The post-receive hook wrote each push's new commit into the branch
table. Each push runs its own hook after the ref is updated, so with
pushes in close succession, like CI pushing back or a quick force-push,
a slower first hook can finish last. The table then keeps the older
commit, or marks a re-created branch as deleted.

- The sync reads each pushed branch's state from git under a repo-scoped
lock
- Deletions go through the same sync, so a re-created branch stays
active
- A branch that fails to sync is logged and skipped instead of aborting
the batch

Co-authored-by: wxiaoguang <wxiaoguang@gmail.com>
Co-authored-by: Giteabot <teabot@gitea.io>
2026-11-07 02:59:15 +00:00
silverwind 2f40e966f7 ci: update giteabot to v1.5.1, label conflict-free backports (#40247) (#40248)
Backport https://github.com/go-gitea/gitea/pull/40247

Release branch pushes run this branch's workflow.

_Written by Claude (Opus 5.5)._
2026-11-06 08:00:23 +00:00
Giteabotandsilverwind 88e1e4ccd7 fix: upgrade Alpine base packages in Docker images (#40252) (#40253)
Backport #40252 by @silverwind

The `alpine:3.24` base image lags behind fixes published to the Alpine
repository.

Both images now run `apk upgrade` before `apk add`. Packages from `apk
add` are already current, so this only affects the preinstalled base
packages.

_Written by Claude (Opus 5.5)._

Co-authored-by: silverwind <me@silverwind.io>
2026-11-06 07:31:05 +00:00
Giteabot e847d6a9c6 fix(deps): update module github.com/andybalholm/brotli to v1.2.7 [security] (#40246) (#40249)
Backport #40246 by @GiteaBot

This PR contains the following updates:

| Package | Change |
[Age](https://docs.renovatebot.com/merge-confidence/) |
[Confidence](https://docs.renovatebot.com/merge-confidence/) |
|---|---|---|---|
|
[github.com/andybalholm/brotli](https://redirect.github.com/andybalholm/brotli)
| `v1.2.1` → `v1.2.7` |
![age](https://developer.mend.io/api/mc/badges/age/go/github.com%2fandybalholm%2fbrotli/v1.2.7?slim=true)
|
![confidence](https://developer.mend.io/api/mc/badges/confidence/go/github.com%2fandybalholm%2fbrotli/v1.2.1/v1.2.7?slim=true)
|

---

### Excessive memory allocation when decompressing crafted streams in
github.com/andybalholm/brotli
BIT-brotli-2026-111497 / BIT-dotnet-2026-111497 /
BIT-dotnet-sdk-2026-111497 / BIT-node-2026-111497 /
BIT-node-min-2026-111497 / BIT-powershell-2026-111497 /
[CVE-2026-111497](https://nvd.nist.gov/vuln/detail/CVE-2026-111497) /
[GHSA-9v8h-qqgm-4m35](https://redirect.github.com/advisories/GHSA-9v8h-qqgm-4m35)
/
[GHSA-c9gr-gmg4-2vqv](https://redirect.github.com/advisories/GHSA-c9gr-gmg4-2vqv)
/ [GO-2026-6888](https://pkg.go.dev/vuln/GO-2026-6888) / PYSEC-2026-4322
/ PYSEC-2026-4323

<details>
<summary>More information</summary>

#### Details
In github.com/andybalholm/brotli before v1.2.7, the decompressor
allocates memory for Huffman tables and block-type trees on every
meta-block header without bounding the cumulative allocations relative
to the input size. A small crafted brotli stream containing many empty
meta-blocks with new Huffman trees can trigger hundreds of megabytes of
allocations per kilobyte of input, leading to denial of service.

#### Severity
Unknown

#### References
-
[https://github.com/andybalholm/brotli/security/advisories/GHSA-c9gr-gmg4-2vqv](https://redirect.github.com/andybalholm/brotli/security/advisories/GHSA-c9gr-gmg4-2vqv)
-
[https://github.com/andybalholm/brotli/commit/33c2a9884269798192b5ecf171288f98939dbe42](https://redirect.github.com/andybalholm/brotli/commit/33c2a9884269798192b5ecf171288f98939dbe42)
-
[https://github.com/andybalholm/brotli/releases/tag/v1.2.7](https://redirect.github.com/andybalholm/brotli/releases/tag/v1.2.7)
-
[https://github.com/google/brotli/commit/0ed4268a4401abcb4472096340477cf4af7d1a2b](https://redirect.github.com/google/brotli/commit/0ed4268a4401abcb4472096340477cf4af7d1a2b)

This data is provided by
[OSV](https://osv.dev/vulnerability/GO-2026-6888) and the [Go
Vulnerability Database](https://redirect.github.com/golang/vulndb)
([CC-BY 4.0](https://redirect.github.com/golang/vulndb#license)).
</details>

---

### Release Notes

<details>
<summary>andybalholm/brotli (github.com/andybalholm/brotli)</summary>

###
[`v1.2.7`](https://redirect.github.com/andybalholm/brotli/compare/v1.2.6...v1.2.7)

[Compare
Source](https://redirect.github.com/andybalholm/brotli/compare/v1.2.6...v1.2.7)

###
[`v1.2.6`](https://redirect.github.com/andybalholm/brotli/compare/v1.2.5...v1.2.6)

[Compare
Source](https://redirect.github.com/andybalholm/brotli/compare/v1.2.5...v1.2.6)

###
[`v1.2.5`](https://redirect.github.com/andybalholm/brotli/compare/v1.2.4...v1.2.5)

[Compare
Source](https://redirect.github.com/andybalholm/brotli/compare/v1.2.4...v1.2.5)

###
[`v1.2.4`](https://redirect.github.com/andybalholm/brotli/compare/v1.2.3...v1.2.4)

[Compare
Source](https://redirect.github.com/andybalholm/brotli/compare/v1.2.3...v1.2.4)

###
[`v1.2.3`](https://redirect.github.com/andybalholm/brotli/compare/v1.2.2...v1.2.3)

[Compare
Source](https://redirect.github.com/andybalholm/brotli/compare/v1.2.2...v1.2.3)

###
[`v1.2.2`](https://redirect.github.com/andybalholm/brotli/compare/v1.2.1...v1.2.2)

[Compare
Source](https://redirect.github.com/andybalholm/brotli/compare/v1.2.1...v1.2.2)

</details>

---

### Configuration

📅 **Schedule**: (UTC)

- Branch creation
  - At any time (no schedule defined)
- Automerge
  - At any time (no schedule defined)

🚦 **Automerge**: Disabled by config. Please merge this manually once you
are satisfied.

♻ **Rebasing**: Whenever PR becomes conflicted, or you tick the
rebase/retry checkbox.

🔕 **Ignore**: Close this PR and you won't be reminded about this update
again.

---

- [ ] <!-- rebase-check -->If you want to rebase/retry this PR, check
this box

---

This PR has been generated by [Mend Renovate
CLI](https://redirect.github.com/renovatebot/renovate).

<!--renovate-debug:eyJjcmVhdGVkSW5WZXIiOiI0NC4xOTAuMSIsInVwZGF0ZWRJblZlciI6IjQ0LjE5MC4xIiwidGFyZ2V0QnJhbmNoIjoibWFpbiIsImxhYmVscyI6WyJkZXBlbmRlbmNpZXMiXX0=-->
2026-11-06 03:05:25 +00:00
Giteabotandrafał przypek d0e8294f46 fix(packages): return empty Chef dependencies instead of null (#40237) (#40242)
Backport #40237 by @Shadow0Bit

Fixes #40230

Cookbooks without dependencies are served with `"dependencies": null`
from the universe and version metadata endpoints. This happens because
`omitempty` drops the empty map when the metadata is stored. Chef
clients iterate over this value and Policyfile resolution crashes.

Supermarket returns `{}` for these cookbooks, Gitea now does too. The
fix checks whether dependencies are `nil` while building response,
returns an empty map if true. This way cookbooks that are already stored
are covered without a re-upload.

Tested with the Chef integration test and `chef-cli install`.

Assisted by Claude Code (claude-opus-5-5).

Co-authored-by: rafał przypek <58443512+Shadow0Bit@users.noreply.github.com>
2026-11-05 19:03:52 +00:00
wxiaoguangandsilverwind b9a99f0f3e fix: allow clearing the full name in profile settings (#40186) (#40191)
backport #40186

Co-authored-by: silverwind <me@silverwind.io>
2026-11-04 20:33:38 +00:00
Giteabotandsilverwind 4f536f1513 fix(web): build issue popup request from parsed link (#40207) (#40225)
Backport #40207 by @silverwind

The issue reference popup built its `/info` request from the raw link
path, so a link ending in `/owner/repo/issues/N` queried an unrelated
location.

It now builds the request from the owner, repo, type and index parsed
from the link, with `parseIssueHref` anchored to the pathname under
`appSubUrl`.

Co-authored-by: silverwind <me@silverwind.io>
2026-11-04 21:02:45 +01:00
Giteabotandsilverwind db5df0494a fix(actions): evaluate job if: against needs finished in the same pass (#40126) (#40221)
Backport #40126 by @silverwind

The job emitter resolves a dependency chain in several rounds in memory,
but a job's `if:` reads its needs' results from the database, where a
need skipped or failed earlier in the same pass was still blocked. A job
with `if: always() && needs.build.result == 'skipped'` was therefore
skipped instead of started.

Finished statuses are now persisted at the end of each round, which also
replaces the separate handling of skipped and failed reusable workflow
callers.

Co-authored-by: silverwind <me@silverwind.io>
2026-11-04 19:17:17 +00:00
silverwind 5aea433c71 fix(api): don't panic on null milestone due_on (#40171)
On release/v28, `PATCH /repos/{owner}/{repo}/milestones/{id}` with
`"due_on": null`, the documented way to remove a deadline, returns HTTP
500. The backport https://github.com/go-gitea/gitea/pull/39921 changed
`EditMilestoneOption.Deadline` to `optional.Option[*string]`, which
decodes `null` as a slice holding a nil pointer, and the go-chi/binding
validator panics on that element (`reflect: call of
reflect.Value.Interface on zero Value`).

The field has no binding rules, so tag it `form:"-"` to skip validation.
main is unaffected since https://github.com/go-gitea/gitea/pull/39528
moved the binding into Gitea.
2026-11-04 06:08:08 +00:00
a67b72e57b fix(notifications): avoid deadlock when creating issue notifications concurrently (#40166) (#40203)
Backport #40166 by @perfectra1n

Concurrent `notification-service` workers can deadlock in the
transaction for-loop.

The transaction is useless, so it is removed to avoid deadlock.

Co-authored-by: Jon Fuller <jonfuller2012@gmail.com>
Co-authored-by: wxiaoguang <wxiaoguang@gmail.com>
2026-11-04 00:20:19 +00:00
a4cad57174 fix(repo): avoid deadlock when updating language stats concurrently (#40167) (#40202)
Backport #40167 by @perfectra1n

The `repo_stats_update` queue only deduplicates waiting items, so
several workers can index the same repository at once, then
`UpdateLanguageStats` can lead to transaction deadlock.

Use a global lock to avoid concurrent updates, and also helps
https://github.com/go-gitea/gitea/pull/39342 to avoid duplicate updates.

Co-authored-by: Jon Fuller <jonfuller2012@gmail.com>
Co-authored-by: silverwind <me@silverwind.io>
Co-authored-by: wxiaoguang <wxiaoguang@gmail.com>
2026-11-03 17:02:11 +00:00
ad8fa1770a fix(actions): make Actions API work with repo admin permission (#40174) (#40180)
Backport #40174

* Fix #40173

Co-authored-by: wxiaoguang <wxiaoguang@gmail.com>
Co-authored-by: silverwind <me@silverwind.io>
2026-11-03 00:24:55 +00:00
8fb1547a4c fix(web): read the wiki blob excerpt from the wiki repository (#40165) (#40178)
Backport #40165 by @hktitof

The "load more lines" button in wiki diffs returned 404. `ExcerptBlob`
loads the commit from the wiki repo but read the blob from
`ctx.Repo.GitRepo`, a regression from
https://github.com/go-gitea/gitea/pull/38464.

Read the blob from the repo the commit was loaded from.

Co-authored-by: Abdellatif Anaflous <62770500+hktitof@users.noreply.github.com>
Co-authored-by: Abdel <hktitof@users.noreply.github.com>
Co-authored-by: silverwind <me@silverwind.io>
2026-11-02 10:35:23 -08:00
silverwind fb79898c28 fix(api): return language of starred and watched repositories (#40127) (#40157)
Backport https://github.com/go-gitea/gitea/pull/40127

The starred and watched repository API lists converted repositories
without loading their attributes, so `language` was always empty. They
are now loaded in one batch, owners included.

Three of these handlers also continued after an internal error and wrote
a second response body, they now return.
2026-11-01 09:05:28 -08:00
96b2997c06 ci: use GitHub merge queue (#40130) (#40162)
Backport #40130 by @bircni

Requiring branches to be up to date reruns the full CI matrix on every
waiting PR after each merge, which saturates our 20 concurrent jobs. A
merge queue still tests against the latest `main`, but once per batch.

This runs the PR workflows on `merge_group` and reports `giteabot/lgtm`
on queue commits, since GiteaBot only sets it on PR heads. Mergers queue
PRs with "Merge when ready" instead of `reviewed/wait-merge`, so
giteabot no longer updates branches. Nothing changes until the
`merge-queue` ruleset is enabled and "Require branches to be up to date"
is turned off. Backport to `release/v28` before the ruleset covers it.

Co-authored-by: bircni <bircni@icloud.com>
Co-authored-by: silverwind <me@silverwind.io>
2026-11-01 10:40:02 +00:00
227 changed files with 2566 additions and 1625 deletions

No files matched your search

+1 -1
View File
@@ -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
+2 -2
View File
@@ -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 -3
View File
@@ -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
+6 -12
View File
@@ -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' }}
+16
View File
@@ -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"
+1
View File
@@ -2,6 +2,7 @@ name: compliance
on:
pull_request:
merge_group:
concurrency:
group: ${{ github.workflow }}-${{ github.head_ref || github.run_id }}
+1
View File
@@ -2,6 +2,7 @@ name: db-tests
on:
pull_request:
merge_group:
concurrency:
group: ${{ github.workflow }}-${{ github.head_ref || github.run_id }}
+1
View File
@@ -2,6 +2,7 @@ name: e2e-tests
on:
pull_request:
merge_group:
concurrency:
group: ${{ github.workflow }}-${{ github.head_ref || github.run_id }}
+2 -2
View File
@@ -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
View File
@@ -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
View File
@@ -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 \
+1 -1
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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.
-10
View File
@@ -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",
+5 -7
View File
@@ -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.
+2
View File
@@ -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
+3 -4
View File
@@ -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
+4 -6
View File
@@ -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=
+15 -15
View File
@@ -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
}
+24 -22
View File
@@ -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)
+5 -6
View File
@@ -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)
+5 -11
View File
@@ -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
+12
View File
@@ -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 -3
View File
@@ -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
}
+15 -2
View File
@@ -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
View File
@@ -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.
+32 -7
View File
@@ -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) {
+2 -2
View File
@@ -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"
+2 -2
View File
@@ -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"`
+5 -2
View File
@@ -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
}
+7
View File
@@ -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
View File
@@ -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
})
+15
View File
@@ -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)
}
+4 -1
View File
@@ -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) {
+4
View File
@@ -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.
+1 -1
View File
@@ -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
}
+28
View File
@@ -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)
}
}
+16 -16
View File
@@ -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)
+13
View File
@@ -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
View File
@@ -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.
+41
View File
@@ -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
View File
@@ -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('\\')
+3
View File
@@ -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"),
+8
View File
@@ -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
+2 -1
View File
@@ -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")
+2
View File
@@ -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>`,
+15
View File
@@ -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)
}
+43
View File
@@ -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
}
+10 -8
View File
@@ -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
+32 -50
View File
@@ -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)
})
}
})
}
})
+6 -17
View File
@@ -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()
}
+8 -8
View File
@@ -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) {
-54
View File
@@ -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())
}
+8 -20
View File
@@ -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()
}
+5 -2
View File
@@ -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")))
})
}
-48
View File
@@ -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
}
+1 -1
View File
@@ -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
}
+1
View File
@@ -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
+7
View File
@@ -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
}
-1
View File
@@ -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()
+2 -1
View File
@@ -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
View File
@@ -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",
+5 -5
View File
@@ -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:
+2 -2
View File
@@ -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),
})
}
+4 -2
View File
@@ -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)
}
+2 -1
View File
@@ -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)
}
}
+8 -2
View File
@@ -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
View File
@@ -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)
+19
View File
@@ -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)
+5 -1
View File
@@ -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
}
+5
View File
@@ -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)
}
+8 -6
View File
@@ -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)
}
+3 -17
View File
@@ -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() {
+2 -2
View File
@@ -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,
}
+4
View File
@@ -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))
}
-1
View File
@@ -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)
+3
View File
@@ -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)
+7
View File
@@ -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)
+6
View File
@@ -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)
}
}
+5
View File
@@ -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)
}
+16 -2
View File
@@ -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)
}
+4
View File
@@ -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)
+5
View File
@@ -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)
+12 -1
View File
@@ -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)
}
+28
View File
@@ -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
+12 -61
View File
@@ -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)
}
}
}
+8 -31
View File
@@ -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)
+19
View File
@@ -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())
}
+3 -1
View File
@@ -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
}
+7 -4
View File
@@ -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.
+13 -9
View File
@@ -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",
+16 -1
View File
@@ -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) {
+6 -3
View File
@@ -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
}
}
+1
View File
@@ -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