Commit Graph

275 Commits

Author SHA1 Message Date
KN4CK3R e8186f1c0f
Map OIDC groups to Orgs/Teams (#21441)
Fixes #19555

Test-Instructions:
https://github.com/go-gitea/gitea/pull/21441#issuecomment-1419438000

This PR implements the mapping of user groups provided by OIDC providers
to orgs teams in Gitea. The main part is a refactoring of the existing
LDAP code to make it usable from different providers.

Refactorings:
- Moved the router auth code from module to service because of import
cycles
- Changed some model methods to take a `Context` parameter
- Moved the mapping code from LDAP to a common location

I've tested it with Keycloak but other providers should work too. The
JSON mapping format is the same as for LDAP.


![grafik](https://user-images.githubusercontent.com/1666336/195634392-3fc540fc-b229-4649-99ac-91ae8e19df2d.png)

---------

Co-authored-by: Lunny Xiao <xiaolunwen@gmail.com>
2023-02-08 14:44:42 +08:00
Jason Song 4011821c94
Implement actions (#21937)
Close #13539.

Co-authored by: @lunny @appleboy @fuxiaohei and others.

Related projects:
- https://gitea.com/gitea/actions-proto-def
- https://gitea.com/gitea/actions-proto-go
- https://gitea.com/gitea/act
- https://gitea.com/gitea/act_runner

### Summary

The target of this PR is to bring a basic implementation of "Actions",
an internal CI/CD system of Gitea. That means even though it has been
merged, the state of the feature is **EXPERIMENTAL**, and please note
that:

- It is disabled by default;
- It shouldn't be used in a production environment currently;
- It shouldn't be used in a public Gitea instance currently;
- Breaking changes may be made before it's stable.

**Please comment on #13539 if you have any different product design
ideas**, all decisions reached there will be adopted here. But in this
PR, we don't talk about **naming, feature-creep or alternatives**.

### ⚠️ Breaking

`gitea-actions` will become a reserved user name. If a user with the
name already exists in the database, it is recommended to rename it.

### Some important reviews

- What is `DEFAULT_ACTIONS_URL` in `app.ini` for?
  - https://github.com/go-gitea/gitea/pull/21937#discussion_r1055954954
- Why the api for runners is not under the normal `/api/v1` prefix?
  - https://github.com/go-gitea/gitea/pull/21937#discussion_r1061173592
- Why DBFS?
  - https://github.com/go-gitea/gitea/pull/21937#discussion_r1061301178
- Why ignore events triggered by `gitea-actions` bot?
  - https://github.com/go-gitea/gitea/pull/21937#discussion_r1063254103
- Why there's no permission control for actions?
  - https://github.com/go-gitea/gitea/pull/21937#discussion_r1090229868

### What it looks like

<details>

#### Manage runners

<img width="1792" alt="image"
src="https://user-images.githubusercontent.com/9418365/205870657-c72f590e-2e08-4cd4-be7f-2e0abb299bbf.png">

#### List runs

<img width="1792" alt="image"
src="https://user-images.githubusercontent.com/9418365/205872794-50fde990-2b45-48c1-a178-908e4ec5b627.png">


#### View logs

<img width="1792" alt="image"
src="https://user-images.githubusercontent.com/9418365/205872501-9b7b9000-9542-4991-8f55-18ccdada77c3.png">



</details>

### How to try it

<details>

#### 1. Start Gitea

Clone this branch and [install from
source](https://docs.gitea.io/en-us/install-from-source).

Add additional configurations in `app.ini` to enable Actions:

```ini
[actions]
ENABLED = true
```

Start it.

If all is well, you'll see the management page of runners:

<img width="1792" alt="image"
src="https://user-images.githubusercontent.com/9418365/205877365-8e30a780-9b10-4154-b3e8-ee6c3cb35a59.png">


#### 2. Start runner

Clone the [act_runner](https://gitea.com/gitea/act_runner), and follow
the
[README](https://gitea.com/gitea/act_runner/src/branch/main/README.md)
to start it.

If all is well, you'll see a new runner has been added:

<img width="1792" alt="image"
src="https://user-images.githubusercontent.com/9418365/205878000-216f5937-e696-470d-b66c-8473987d91c3.png">

#### 3. Enable actions for a repo

Create a new repo or open an existing one, check the `Actions` checkbox
in settings and submit.

<img width="1792" alt="image"
src="https://user-images.githubusercontent.com/9418365/205879705-53e09208-73c0-4b3e-a123-2dcf9aba4b9c.png">
<img width="1792" alt="image"
src="https://user-images.githubusercontent.com/9418365/205879383-23f3d08f-1a85-41dd-a8b3-54e2ee6453e8.png">

If all is well, you'll see a new tab "Actions":

<img width="1792" alt="image"
src="https://user-images.githubusercontent.com/9418365/205881648-a8072d8c-5803-4d76-b8a8-9b2fb49516c1.png">

#### 4. Upload workflow files

Upload some workflow files to `.gitea/workflows/xxx.yaml`, you can
follow the [quickstart](https://docs.github.com/en/actions/quickstart)
of GitHub Actions. Yes, Gitea Actions is compatible with GitHub Actions
in most cases, you can use the same demo:

```yaml
name: GitHub Actions Demo
run-name: ${{ github.actor }} is testing out GitHub Actions 🚀
on: [push]
jobs:
  Explore-GitHub-Actions:
    runs-on: ubuntu-latest
    steps:
      - run: echo "🎉 The job was automatically triggered by a ${{ github.event_name }} event."
      - run: echo "🐧 This job is now running on a ${{ runner.os }} server hosted by GitHub!"
      - run: echo "🔎 The name of your branch is ${{ github.ref }} and your repository is ${{ github.repository }}."
      - name: Check out repository code
        uses: actions/checkout@v3
      - run: echo "💡 The ${{ github.repository }} repository has been cloned to the runner."
      - run: echo "🖥️ The workflow is now ready to test your code on the runner."
      - name: List files in the repository
        run: |
          ls ${{ github.workspace }}
      - run: echo "🍏 This job's status is ${{ job.status }}."
```

If all is well, you'll see a new run in `Actions` tab:

<img width="1792" alt="image"
src="https://user-images.githubusercontent.com/9418365/205884473-79a874bc-171b-4aaf-acd5-0241a45c3b53.png">

#### 5. Check the logs of jobs

Click a run and you'll see the logs:

<img width="1792" alt="image"
src="https://user-images.githubusercontent.com/9418365/205884800-994b0374-67f7-48ff-be9a-4c53f3141547.png">

#### 6. Go on

You can try more examples in [the
documents](https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions)
of GitHub Actions, then you might find a lot of bugs.

Come on, PRs are welcome.

</details>

See also: [Feature Preview: Gitea
Actions](https://blog.gitea.io/2022/12/feature-preview-gitea-actions/)

---------

Co-authored-by: a1012112796 <1012112796@qq.com>
Co-authored-by: Lunny Xiao <xiaolunwen@gmail.com>
Co-authored-by: delvh <dev.lh@web.de>
Co-authored-by: ChristopherHX <christopher.homberger@web.de>
Co-authored-by: John Olheiser <john.olheiser@gmail.com>
2023-01-31 09:45:19 +08:00
Lunny Xiao c0015979a6
Support system hook API (#14537)
This add system hook API
2023-01-28 19:12:10 +01:00
JakobDev 4d072a4c4e
Add API endpoint to get latest release (#21267)
This PR adds a new API endpoint to get the latest stable release of a
repo, similar to [GitHub
API](https://docs.github.com/en/rest/releases/releases#get-the-latest-release).
2023-01-26 10:33:47 -06:00
Chongyi Zheng de484e86bc
Support scoped access tokens (#20908)
This PR adds the support for scopes of access tokens, mimicking the
design of GitHub OAuth scopes.

The changes of the core logic are in `models/auth` that `AccessToken`
struct will have a `Scope` field. The normalized (no duplication of
scope), comma-separated scope string will be stored in `access_token`
table in the database.
In `services/auth`, the scope will be stored in context, which will be
used by `reqToken` middleware in API calls. Only OAuth2 tokens will have
granular token scopes, while others like BasicAuth will default to scope
`all`.
A large amount of work happens in `routers/api/v1/api.go` and the
corresponding `tests/integration` tests, that is adding necessary scopes
to each of the API calls as they fit.


- [x] Add `Scope` field to `AccessToken`
- [x] Add access control to all API endpoints
- [x] Update frontend & backend for when creating tokens
- [x] Add a database migration for `scope` column (enable 'all' access
to past tokens)

I'm aiming to complete it before Gitea 1.19 release.

Fixes #4300
2023-01-17 15:46:03 -06:00
zeripath cc1f8cbe96
Prevent panic on looking at api "git" endpoints for empty repos (#22457)
The API endpoints for "git" can panic if they are called on an empty
repo. We can simply allow empty repos for these endpoints without worry
as they should just work.

Fix #22452

Signed-off-by: Andrew Thornton <art27@cantab.net>
2023-01-15 08:33:25 -06:00
zeripath 83640c449e
Remove ReverseProxy authentication from the API (#22219)
Since we changed the /api/v1/ routes to disallow session authentication
we also removed their reliance on CSRF. However, we left the
ReverseProxy authentication here - but this means that POSTs to the API
are no longer protected by CSRF.

Now, ReverseProxy authentication is a kind of session authentication,
and is therefore inconsistent with the removal of session from the API.

This PR proposes that we simply remove the ReverseProxy authentication
from the API and therefore users of the API must explicitly use tokens
or basic authentication.

Replace #22077
Close #22221 
Close #22077 

Signed-off-by: Andrew Thornton <art27@cantab.net>
2022-12-27 08:34:05 +08:00
Lunny Xiao 6398ca745a
refactor bind functions based on generics (#22055) 2022-12-12 16:09:26 +08:00
KN4CK3R 3c59d31bc6
Add API management for issue/pull and comment attachments (#21783)
Close #14601
Fix #3690

Revive of #14601.
Updated to current code, cleanup and added more read/write checks.

Signed-off-by: Andrew Thornton <art27@cantab.net>
Signed-off-by: Andre Bruch <ab@andrebruch.com>
Co-authored-by: zeripath <art27@cantab.net>
Co-authored-by: 6543 <6543@obermui.de>
Co-authored-by: Norwin <git@nroo.de>
Co-authored-by: Lunny Xiao <xiaolunwen@gmail.com>
2022-12-09 14:35:56 +08:00
flynnnnnnnnnn e81ccc406b
Implement FSFE REUSE for golang files (#21840)
Change all license headers to comply with REUSE specification.

Fix #16132

Co-authored-by: flynnnnnnnnnn <flynnnnnnnnnn@github>
Co-authored-by: John Olheiser <john.olheiser@gmail.com>
2022-11-27 18:20:29 +00:00
zeripath a0a425a13b
Add some documentation to packages (#21648)
In #21637 it was mentioned that the purpose of the API routes for the
packages is unclear. This PR adds some documentation.

Fix #21637

Signed-off-by: Andrew Thornton <art27@cantab.net>
Co-authored-by: KN4CK3R <admin@oldschoolhack.me>
2022-11-12 18:59:15 +00:00
Jason Song bf2078640f
Load GitRepo in API before deleting issue (#21720)
Fix #20921.

The `ctx.Repo.GitRepo` has been used in deleting issues when the issue
is a PR.

Co-authored-by: Lunny Xiao <xiaolunwen@gmail.com>
Co-authored-by: Lauris BH <lauris@nix.lv>
2022-11-12 08:32:04 +08:00
Drew Noel 2cbea23d70
Add configuration for CORS allowed headers (#21747)
This PR enhances the CORS middleware usage by allowing for the headers
to be configured in `app.ini`.

Fixes #21746

Co-authored-by: KN4CK3R <admin@oldschoolhack.me>
Co-authored-by: John Olheiser <john.olheiser@gmail.com>
Co-authored-by: Lunny Xiao <xiaolunwen@gmail.com>
2022-11-11 14:39:27 +08:00
qwerty287 1dfa28ffa5
Add API endpoint to get changed files of a PR (#21177)
This adds an api endpoint `/files` to PRs that allows to get a list of changed files.

built upon #18228, reviews there are included
closes https://github.com/go-gitea/gitea/issues/654

Co-authored-by: Anton Bracke <anton@ju60.de>
Co-authored-by: 6543 <6543@obermui.de>
Co-authored-by: wxiaoguang <wxiaoguang@gmail.com>
2022-09-29 04:27:20 +02:00
John Olheiser a48d6ba4b4
Go 1.19 format (#20758)
* 1.19 gofumpt

Signed-off-by: jolheiser <john.olheiser@gmail.com>

* Change CSV test

Signed-off-by: jolheiser <john.olheiser@gmail.com>

* Commit whitespace fixes from @zeripath

Co-authored-by: zeripath <art27@cantab.net>

* Update emoji

Signed-off-by: jolheiser <john.olheiser@gmail.com>

* bump swagger & fix generate-swagger

Signed-off-by: jolheiser <john.olheiser@gmail.com>
Co-authored-by: zeripath <art27@cantab.net>
Co-authored-by: 6543 <6543@obermui.de>
Co-authored-by: Lauris BH <lauris@nix.lv>
2022-08-30 21:15:45 -05:00
zeripath bb0ff77e46
Share HTML template renderers and create a watcher framework (#20218)
The recovery, API, Web and package frameworks all create their own HTML
Renderers. This increases the memory requirements of Gitea
unnecessarily with duplicate templates being kept in memory.

Further the reloading framework in dev mode for these involves locking
and recompiling all of the templates on each load. This will potentially
hide concurrency issues and it is inefficient.

This PR stores the templates renderer in the context and stores this
context in the NormalRoutes, it then creates a fsnotify.Watcher
framework to watch files.

The watching framework is then extended to the mailer templates which
were previously not being reloaded in dev.

Then the locales are simplified to a similar structure.

Fix #20210 
Fix #20211
Fix #20217

Signed-off-by: Andrew Thornton <art27@cantab.net>
2022-08-28 10:43:25 +01:00
Mohamed Sekour 0e61a74e5a
Add new API endpoints for push mirrors management (#19841)
- Add a new push mirror to specific repository
- Sync now ( send all the changes to the configured push mirrors )
- Get list of all push mirrors of a repository
- Get a push mirror by ID
- Delete push mirror by ID

Signed-off-by: Mohamed Sekour <mohamed.sekour@exfo.com>
Signed-off-by: Andrew Thornton <art27@cantab.net>
Co-authored-by: zeripath <art27@cantab.net>
2022-07-30 18:45:59 +02:00
Gusted 3aec32ad16
Add write check for creating Commit status (#20332)
- Add write code checks for creating new commit status
- Regression #5314

Co-authored-by: zeripath <art27@cantab.net>
2022-07-12 14:51:06 +02:00
Anthony Wang e86f18a05a
User keypairs and HTTP signatures for ActivityPub federation using go-ap (#19133)
* go.mod: add go-fed/{httpsig,activity/pub,activity/streams} dependency

go get github.com/go-fed/activity/streams@master
go get github.com/go-fed/activity/pub@master
go get github.com/go-fed/httpsig@master

* activitypub: implement /api/v1/activitypub/user/{username} (#14186)

Return informations regarding a Person (as defined in ActivityStreams
https://www.w3.org/TR/activitystreams-vocabulary/#dfn-person).

Refs: https://github.com/go-gitea/gitea/issues/14186

Signed-off-by: Loïc Dachary <loic@dachary.org>

* activitypub: add the public key to Person (#14186)

Refs: https://github.com/go-gitea/gitea/issues/14186

Signed-off-by: Loïc Dachary <loic@dachary.org>

* activitypub: go-fed conformant Clock instance

Signed-off-by: Loïc Dachary <loic@dachary.org>

* activitypub: signing http client

Signed-off-by: Loïc Dachary <loic@dachary.org>

* activitypub: implement the ReqSignature middleware

Signed-off-by: Loïc Dachary <loic@dachary.org>

* activitypub: hack_16834

Signed-off-by: Loïc Dachary <loic@dachary.org>

* Fix CI checks-backend errors with go mod tidy

Signed-off-by: Anthony Wang <ta180m@pm.me>

* Change 2021 to 2022, properly format package imports

Signed-off-by: Anthony Wang <ta180m@pm.me>

* Run make fmt and make generate-swagger

Signed-off-by: Anthony Wang <ta180m@pm.me>

* Use Gitea JSON library, add assert for pkp

Signed-off-by: Anthony Wang <ta180m@pm.me>

* Run make fmt again, fix err var redeclaration

Signed-off-by: Anthony Wang <ta180m@pm.me>

* Remove LogSQL from ActivityPub person test

Signed-off-by: Anthony Wang <ta180m@pm.me>

* Assert if json.Unmarshal succeeds

Signed-off-by: Anthony Wang <ta180m@pm.me>

* Cleanup, handle invalid usernames for ActivityPub person GET request

Signed-off-by: Anthony Wang <ta180m@pm.me>

* Rename hack_16834 to user_settings

Signed-off-by: Anthony Wang <ta180m@pm.me>

* Use the httplib module instead of http for GET requests

* Clean up whitespace with make fmt

* Use time.RFC1123 and make the http.Client proxy-aware

* Check if digest algo is supported in setting module

* Clean up some variable declarations

* Remove unneeded copy

* Use system timezone instead of setting.DefaultUILocation

* Use named constant for httpsigExpirationTime

* Make pubKey IRI #main-key instead of /#main-key

* Move /#main-key to #main-key in tests

* Implemented Webfinger endpoint.

* Add visible check.

* Add user profile as alias.

* Add actor IRI and remote interaction URL to WebFinger response

* fmt

* Fix lint errors

* Use go-ap instead of go-fed

* Run go mod tidy to fix missing modules in go.mod and go.sum

* make fmt

* Convert remaining code to go-ap

* Clean up go.sum

* Fix JSON unmarshall error

* Fix CI errors by adding @context to Person() and making sure types match

* Correctly decode JSON in api_activitypub_person_test.go

* Force CI rerun

* Fix TestActivityPubPersonInbox segfault

* Fix lint error

* Use @mariusor's suggestions for idiomatic go-ap usage

* Correctly add inbox/outbox IRIs to person

* Code cleanup

* Remove another LogSQL from ActivityPub person test

* Move httpsig algos slice to an init() function

* Add actor IRI and remote interaction URL to WebFinger response

* Update TestWebFinger to check for ActivityPub IRI in aliases

* make fmt

* Force CI rerun

* WebFinger: Add CORS header and fix Href -> Template for remote interactions

The CORS header is needed due to https://datatracker.ietf.org/doc/html/rfc7033#section-5 and fixes some Peertube <-> Gitea federation issues

* make lint-backend

* Make sure Person endpoint has Content-Type application/activity+json and includes PreferredUsername, URL, and Icon

Setting the correct Content-Type is essential for federating with Mastodon

* Use UTC instead of GMT

* Rename pkey to pubKey

* Make sure HTTP request Date in GMT

* make fmt

* dont drop err

* Make sure API responses always refer to username in original case

Copied from what I wrote on #19133 discussion: Handling username case is a very tricky issue and I've already encountered a Mastodon <-> Gitea federation bug due to Gitea considering Ta180m and ta180m to be the same user while Mastodon thinks they are two different users. I think the best way forward is for Gitea to only use the original case version of the username for federation so other AP software don't get confused.

* Move httpsig algs constant slice to modules/setting/federation.go

* Add new federation settings to app.example.ini and config-cheat-sheet

* Return if marshalling error

* Make sure Person IRIs are generated correctly

This commit ensures that if the setting.AppURL is something like "http://127.0.0.1:42567" (like in the integration tests), a trailing slash will be added after that URL.

* If httpsig verification fails, fix Host header and try again

This fixes a very rare bug when Gitea and another AP server (confirmed to happen with Mastodon) are running on the same machine, Gitea fails to verify incoming HTTP signatures. This is because the other AP server creates the sig with the public Gitea domain as the Host. However, when Gitea receives the request, the Host header is instead localhost, so the signature verification fails. Manually changing the host header to the correct value and trying the veification again fixes the bug.


* Revert "If httpsig verification fails, fix Host header and try again"

This reverts commit f53e46c721a037c55facb9200106a6b491bf834c.

The bug was actually caused by nginx messing up the Host header when reverse-proxying since I didn't have the line `proxy_set_header Host $host;` in my nginx config for Gitea.

* Go back to using ap.IRI to generate inbox and outbox IRIs

* use const for key values

* Update routers/web/webfinger.go

* Use ctx.JSON in Person response to make code cleaner

* Revert "Use ctx.JSON in Person response to make code cleaner"

This doesn't work because the ctx.JSON() function already sends the response out and it's too late to edit the headers.

This reverts commit 95aad988975be3393c76094864ed6ba962157e0c.

* Use activitypub.ActivityStreamsContentType for Person response Content Type

* Limit maximum ActivityPub request and response sizes to a configurable setting

* Move setting key constants to models/user/setting_keys.go

* Fix failing ActivityPubPerson integration test by checking the correct field for username

* Add a warning about changing settings that can break federation

* Add better comments

* Don't multiply Federation.MaxSize by 1<<20 twice

* Add more better comments

* Fix failing ActivityPubMissingPerson test

We now use ctx.ContextUser so the message printed out when a user does not exist is slightly different

* make generate-swagger

For some reason I didn't realize that /templates/swagger/v1_json.tmpl was machine-generated by make generate-swagger... I've been editing it by hand for three months! 🤦

* Move getting the RFC 2616 time to a separate function

* More code cleanup

* Update go-ap to fix empty liked collection and removed unneeded HTTP headers

* go mod tidy

* Add ed25519 to httpsig algorithms

* Use go-ap/jsonld to add @context and marshal JSON

* Change Gitea user agent from the default to Gitea/Version

* Use ctx.ServerError and remove all remote interaction code from webfinger.go
2022-06-19 07:25:12 +02:00
Wim e528e2b435
Implement http signatures support for the API (#17565)
Fixes #12338

This allows use to talk to the API with our ssh certificate (and/or ssh-agent) without needing to fetch an API key or tokens.
It will just automatically work when users have added their ssh principal in gitea.

This needs client code in tea
Update: also support normal pubkeys

ref: https://tools.ietf.org/html/draft-cavage-http-signatures

Co-authored-by: Lunny Xiao <xiaolunwen@gmail.com>
Co-authored-by: zeripath <art27@cantab.net>
Signed-off-by: Andrew Thornton <art27@cantab.net>
2022-06-05 08:16:14 +01:00
qwerty287 df9612bb53
Add API to serve blob or LFS file content (#19689)
* Add LFS API

* Update routers/api/v1/repo/file.go

Co-authored-by: Gusted <williamzijl7@hotmail.com>

* Apply suggestions

* Apply suggestions

* Update routers/api/v1/repo/file.go

Co-authored-by: Gusted <williamzijl7@hotmail.com>

* Report errors

* ADd test

* Use own repo for test

* Use different repo name

* Improve handling

* Slight restructures

1. Avoid reading the blob data multiple times
2. Ensure that caching is only checked when about to serve the blob/lfs
3. Avoid nesting by returning early
4. Make log message a bit more clear
5. Ensure that the dataRc is closed by defer when passed to ServeData

Signed-off-by: Andrew Thornton <art27@cantab.net>

Co-authored-by: Gusted <williamzijl7@hotmail.com>
Co-authored-by: Andrew Thornton <art27@cantab.net>
Co-authored-by: Lunny Xiao <xiaolunwen@gmail.com>
2022-06-04 21:17:53 +08:00
Lunny Xiao fd7d83ace6
Move almost all functions' parameter db.Engine to context.Context (#19748)
* Move almost all functions' parameter db.Engine to context.Context
* remove some unnecessary wrap functions
2022-05-20 22:08:52 +08:00
Lunny Xiao cbd45471b1
Move access and repo permission to models/perm/access (#19350)
* Move access and repo permission to models/perm/access

* Remove unnecessary code
2022-05-11 12:09:36 +02:00
kolaente 59b30f060a
Auto merge pull requests when all checks succeeded via API (#9307)
* Fix indention

Signed-off-by: kolaente <k@knt.li>

* Add option to merge a pr right now without waiting for the checks to succeed

Signed-off-by: kolaente <k@knt.li>

* Fix lint

Signed-off-by: kolaente <k@knt.li>

* Add scheduled pr merge to tables used for testing

Signed-off-by: kolaente <k@knt.li>

* Add status param to make GetPullRequestByHeadBranch reusable

Signed-off-by: kolaente <k@knt.li>

* Move "Merge now" to a seperate button to make the ui clearer

Signed-off-by: kolaente <k@knt.li>

* Update models/scheduled_pull_request_merge.go

Co-authored-by: 赵智超 <1012112796@qq.com>

* Update web_src/js/index.js

Co-authored-by: 赵智超 <1012112796@qq.com>

* Update web_src/js/index.js

Co-authored-by: 赵智超 <1012112796@qq.com>

* Re-add migration after merge

* Fix frontend lint

* Fix version compare

* Add vendored dependencies

* Add basic tets

* Make sure the api route is capable of scheduling PRs for merging

* Fix comparing version

* make vendor

* adopt refactor

* apply suggestion: User -> Doer

* init var once

* Fix Test

* Update templates/repo/issue/view_content/comments.tmpl

* adopt

* nits

* next

* code format

* lint

* use same name schema; rm CreateUnScheduledPRToAutoMergeComment

* API: can not create schedule twice

* Add TestGetBranchNamesForSha

* nits

* new go routine for each pull to merge

* Update models/pull.go

Co-authored-by: a1012112796 <1012112796@qq.com>

* Update models/scheduled_pull_request_merge.go

Co-authored-by: a1012112796 <1012112796@qq.com>

* fix & add renaming sugestions

* Update services/automerge/pull_auto_merge.go

Co-authored-by: a1012112796 <1012112796@qq.com>

* fix conflict relicts

* apply latest refactors

* fix: migration after merge

* Update models/error.go

Co-authored-by: delvh <dev.lh@web.de>

* Update options/locale/locale_en-US.ini

Co-authored-by: delvh <dev.lh@web.de>

* Update options/locale/locale_en-US.ini

Co-authored-by: delvh <dev.lh@web.de>

* adapt latest refactors

* fix test

* use more context

* skip potential edgecases

* document func usage

* GetBranchNamesForSha() -> GetRefsBySha()

* start refactoring

* ajust to new changes

* nit

* docu nit

* the great check move

* move checks for branchprotection into own package

* resolve todo now ...

* move & rename

* unexport if posible

* fix

* check if merge is allowed before merge on scheduled pull

* debugg

* wording

* improve SetDefaults & nits

* NotAllowedToMerge -> DisallowedToMerge

* fix test

* merge files

* use package "errors"

* merge files

* add string names

* other implementation for gogit

* adapt refactor

* more context for models/pull.go

* GetUserRepoPermission use context

* more ctx

* use context for loading pull head/base-repo

* more ctx

* more ctx

* models.LoadIssueCtx()

* models.LoadIssueCtx()

* Handle pull_service.Merge in one DB transaction

* add TODOs

* next

* next

* next

* more ctx

* more ctx

* Start refactoring structure of old pull code ...

* move code into new packages

* shorter names ... and finish **restructure**

* Update models/branches.go

Co-authored-by: zeripath <art27@cantab.net>

* finish UpdateProtectBranch

* more and fix

* update datum

* template: use "svg" helper

* rename prQueue 2 prPatchCheckerQueue

* handle automerge in queue

* lock pull on git&db actions ...

* lock pull on git&db actions ...

* add TODO notes

* the regex

* transaction in tests

* GetRepositoryByIDCtx

* shorter table name and lint fix

* close transaction bevore notify

* Update models/pull.go

* next

* CheckPullMergable check all branch protections!

* Update routers/web/repo/pull.go

* CheckPullMergable check all branch protections!

* Revert "PullService lock via pullID (#19520)" (for now...)

This reverts commit 6cde7c9159a5ea75a10356feb7b8c7ad4c434a9a.

* Update services/pull/check.go

* Use for a repo action one database transaction

* Apply suggestions from code review

* Apply suggestions from code review

Co-authored-by: delvh <dev.lh@web.de>

* Update services/issue/status.go

Co-authored-by: delvh <dev.lh@web.de>

* Update services/issue/status.go

Co-authored-by: delvh <dev.lh@web.de>

* use db.WithTx()

* gofmt

* make pr.GetDefaultMergeMessage() context aware

* make MergePullRequestForm.SetDefaults context aware

* use db.WithTx()

* pull.SetMerged only with context

* fix deadlock in `test-sqlite\#TestAPIBranchProtection`

* dont forget templates

* db.WithTx allow to set the parentCtx

* handle db transaction in service packages but not router

* issue_service.ChangeStatus just had caused another deadlock :/
it has to do something with how notification package is handled

* if we merge a pull in one database transaktion, we get a lock, because merge infoce internal api that cant handle open db sessions to the same repo

* ajust to current master

* Apply suggestions from code review

Co-authored-by: delvh <dev.lh@web.de>

* dont open db transaction in router

* make generate-swagger

* one _success less

* wording nit

* rm

* adapt

* remove not needed test files

* rm less diff & use attr in JS

* ...

* Update services/repository/files/commit.go

Co-authored-by: wxiaoguang <wxiaoguang@gmail.com>

* ajust db schema for PullAutoMerge

* skip broken pull refs

* more context in error messages

* remove webUI part for another pull

* remove more WebUI only parts

* API: add CancleAutoMergePR

* Apply suggestions from code review

Co-authored-by: wxiaoguang <wxiaoguang@gmail.com>

* fix lint

* Apply suggestions from code review

* cancle -> cancel

Co-authored-by: delvh <dev.lh@web.de>

* change queue identifyer

* fix swagger

* prevent nil issue

* fix and dont drop error

* as per @zeripath

* Update integrations/git_test.go

Co-authored-by: delvh <dev.lh@web.de>

* Update integrations/git_test.go

Co-authored-by: delvh <dev.lh@web.de>

* more declarative integration tests (dedup code)

* use assert.False/True helper

Co-authored-by: 赵智超 <1012112796@qq.com>
Co-authored-by: 6543 <6543@obermui.de>
Co-authored-by: delvh <dev.lh@web.de>
Co-authored-by: zeripath <art27@cantab.net>
Co-authored-by: wxiaoguang <wxiaoguang@gmail.com>
2022-05-08 01:05:52 +08:00
qwerty287 ac6c338428
Add API to check if team has repo access (#19540)
* Add API to check if team has repo access

* Add test case
2022-05-01 17:39:04 +02:00
6543 1597e2da3e
Use middleware to open gitRepo (#19559) 2022-04-30 16:32:01 +02:00
Florin Hillebrand ad6d08d155
Add API to query collaborators permission for a repository (#18761)
Targeting #14936, #15332

Adds a collaborator permissions API endpoint according to GitHub API: https://docs.github.com/en/rest/collaborators/collaborators#get-repository-permissions-for-a-user to retrieve a collaborators permissions for a specific repository.

### Checks the repository permissions of a collaborator. 

`GET` `/repos/{owner}/{repo}/collaborators/{collaborator}/permission`

Possible `permission` values are `admin`, `write`, `read`, `owner`, `none`.

```json
{
  "permission": "admin",
  "role_name": "admin",
  "user": {}
}
```

Where `permission` and `role_name` hold the same `permission` value and `user` is filled with the user API object. Only admins are allowed to use this API endpoint.
2022-04-29 14:24:38 +02:00
qwerty287 8eb1cd9264
Add "Allow edits from maintainer" feature (#18002)
Adds a feature [like GitHub has](https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/proposing-changes-to-your-work-with-pull-requests/creating-a-pull-request-from-a-fork) (step 7).
If you create a new PR from a forked repo, you can select (and change later, but only if you are the PR creator/poster) the "Allow edits from maintainers" option.
Then users with write access to the base branch get more permissions on this branch:
* use the update pull request button
* push directly from the command line (`git push`)
* edit/delete/upload files via web UI
* use related API endpoints

You can't merge PRs to this branch with this enabled, you'll need "full" code write permissions.

This feature has a pretty big impact on the permission system. I might forgot changing some things or didn't find security vulnerabilities. In this case, please leave a review or comment on this PR.

Closes #17728

Co-authored-by: 6543 <6543@obermui.de>
2022-04-28 17:45:33 +02:00
6543 06e4687cec
more context for models (#19511)
make more usage of context, to have more db transaction in one session

(make diff of  #9307 smaller)
2022-04-28 13:48:48 +02:00
6543 c764355676
RepoAssignment ensure to close before overwrite (#19449)
* check if GitRepo already open and close if

* only run RepoAssignment once

* refactor context helper for api to open GitRepo
2022-04-21 17:17:57 +02:00
Lunny Xiao 3c3d49899f
Remove dependent on session auth for api/v1 routers (#19321)
* Remove dependent on session auth for api/v1 routers

* Remove unnecessary session on API context

* remove missed header

* fix test

* fix missed api/v1
2022-04-08 06:22:10 +02:00
KN4CK3R 1d332342db
Add Package Registry (#16510)
* Added package store settings.

* Added models.

* Added generic package registry.

* Added tests.

* Added NuGet package registry.

* Moved service index to api file.

* Added NPM package registry.

* Added Maven package registry.

* Added PyPI package registry.

* Summary is deprecated.

* Changed npm name.

* Sanitize project url.

* Allow only scoped packages.

* Added user interface.

* Changed method name.

* Added missing migration file.

* Set page info.

* Added documentation.

* Added documentation links.

* Fixed wrong error message.

* Lint template files.

* Fixed merge errors.

* Fixed unit test storage path.

* Switch to json module.

* Added suggestions.

* Added package webhook.

* Add package api.

* Fixed swagger file.

* Fixed enum and comments.

* Fixed NuGet pagination.

* Print test names.

* Added api tests.

* Fixed access level.

* Fix User unmarshal.

* Added RubyGems package registry.

* Fix lint.

* Implemented io.Writer.

* Added support for sha256/sha512 checksum files.

* Improved maven-metadata.xml support.

* Added support for symbol package uploads.

* Added tests.

* Added overview docs.

* Added npm dependencies and keywords.

* Added no-packages information.

* Display file size.

* Display asset count.

* Fixed filter alignment.

* Added package icons.

* Formatted instructions.

* Allow anonymous package downloads.

* Fixed comments.

* Fixed postgres test.

* Moved file.

* Moved models to models/packages.

* Use correct error response format per client.

* Use simpler search form.

* Fixed IsProd.

* Restructured data model.

* Prevent empty filename.

* Fix swagger.

* Implemented user/org registry.

* Implemented UI.

* Use GetUserByIDCtx.

* Use table for dependencies.

* make svg

* Added support for unscoped npm packages.

* Add support for npm dist tags.

* Added tests for npm tags.

* Unlink packages if repository gets deleted.

* Prevent user/org delete if a packages exist.

* Use package unlink in repository service.

* Added support for composer packages.

* Restructured package docs.

* Added missing tests.

* Fixed generic content page.

* Fixed docs.

* Fixed swagger.

* Added missing type.

* Fixed ambiguous column.

* Organize content store by sha256 hash.

* Added admin package management.

* Added support for sorting.

* Add support for multiple identical versions/files.

* Added missing repository unlink.

* Added file properties.

* make fmt

* lint

* Added Conan package registry.

* Updated docs.

* Unify package names.

* Added swagger enum.

* Use longer TEXT column type.

* Removed version composite key.

* Merged package and container registry.

* Removed index.

* Use dedicated package router.

* Moved files to new location.

* Updated docs.

* Fixed JOIN order.

* Fixed GROUP BY statement.

* Fixed GROUP BY #2.

* Added symbol server support.

* Added more tests.

* Set NOT NULL.

* Added setting to disable package registries.

* Moved auth into service.

* refactor

* Use ctx everywhere.

* Added package cleanup task.

* Changed packages path.

* Added container registry.

* Refactoring

* Updated comparison.

* Fix swagger.

* Fixed table order.

* Use token auth for npm routes.

* Enabled ReverseProxy auth.

* Added packages link for orgs.

* Fixed anonymous org access.

* Enable copy button for setup instructions.

* Merge error

* Added suggestions.

* Fixed merge.

* Handle "generic".

* Added link for TODO.

* Added suggestions.

* Changed temporary buffer filename.

* Added suggestions.

* Apply suggestions from code review

Co-authored-by: Thomas Boerger <thomas@webhippie.de>

* Update docs/content/doc/packages/nuget.en-us.md

Co-authored-by: wxiaoguang <wxiaoguang@gmail.com>
Co-authored-by: Thomas Boerger <thomas@webhippie.de>
2022-03-30 16:42:47 +08:00
Lunny Xiao b06b9a056c
Move organization related structs into sub package (#18518)
* Move organization related structs into sub package

* Fix test

* Fix lint

* Move more functions into sub packages

* Fix bug

* Fix test

* Update models/organization/team_repo.go

Co-authored-by: KN4CK3R <admin@oldschoolhack.me>

* Apply suggestions from code review

Co-authored-by: KN4CK3R <admin@oldschoolhack.me>

* Fix fmt

* Follow suggestion from @Gusted

* Fix test

* Fix test

* Fix bug

* Use ctx but db.DefaultContext on routers

* Fix bug

* Fix bug

* fix bug

* Update models/organization/team_user.go

* Fix bug

Co-authored-by: KN4CK3R <admin@oldschoolhack.me>
Co-authored-by: wxiaoguang <wxiaoguang@gmail.com>
2022-03-29 14:29:02 +08:00
Lunny Xiao 6526733a58
Let web and API routes have different auth methods group (#19168)
* remove the global methods but create dynamiclly

* Fix lint

* Fix windows lint

* Fix windows lint

* some improvements

Co-authored-by: wxiaoguang <wxiaoguang@gmail.com>
2022-03-28 12:46:28 +08:00
KN4CK3R 59b867dc2d
Add `ContextUser` to http request context (#18798)
This PR adds a middleware which sets a ContextUser (like GetUserByParams before) in a single place which can be used by other methods. For routes which represent a repo or org the respective middlewares set the field too.

Also fix a bug in modules/context/org.go during refactoring.
2022-03-26 17:04:22 +08:00
KN4CK3R 80fd25524e
Renamed ctx.User to ctx.Doer. (#19161)
Co-authored-by: 6543 <6543@obermui.de>
Co-authored-by: wxiaoguang <wxiaoguang@gmail.com>
2022-03-22 15:03:22 +08:00
Otto Richter (fnetX) 062fd4c217
[API] Allow removing issues (#18879)
Add new feature to delete issues and pulls via API

Co-authored-by: fnetx <git@fralix.ovh>
Co-authored-by: Lunny Xiao <xiaolunwen@gmail.com>
Co-authored-by: Gusted <williamzijl7@hotmail.com>
Co-authored-by: 6543 <6543@obermui.de>
2022-03-01 01:20:15 +01:00
zeripath eb748f5f3c
Add apply-patch, basic revert and cherry-pick functionality (#17902)
This code adds a simple endpoint to apply patches to repositories and
branches on gitea. This is then used along with the conflicting checking
code in #18004 to provide a basic implementation of cherry-pick revert.

Now because the buttons necessary for cherry-pick and revert have 
required us to create a dropdown next to the Browse Source button
I've also implemented Create Branch and Create Tag operations.

Fix #3880 
Fix #17986 

Signed-off-by: Andrew Thornton <art27@cantab.net>
2022-02-09 20:28:55 +00:00
6543 54e9ee37a7
format with gofumpt (#18184)
* gofumpt -w -l .

* gofumpt -w -l -extra .

* Add linter

* manual fix

* change make fmt
2022-01-20 18:46:10 +01:00
zeripath 5cb0c9aa0d
Propagate context and ensure git commands run in request context (#17868)
This PR continues the work in #17125 by progressively ensuring that git
commands run within the request context.

This now means that the if there is a git repo already open in the context it will be used instead of reopening it.

Signed-off-by: Andrew Thornton <art27@cantab.net>
2022-01-19 23:26:57 +00:00
qwerty287 7db2f110ad
Add API to get issue/pull comments and events (timeline) (#17403)
* Add API to get issue/pull comments and events (timeline)
Adds an API to get both comments and events in one endpoint with all required data.
Closes go-gitea/gitea#13250

* Fix swagger

* Don't show code comments (use review api instead)

* fmt

* Fix comment

* Time -> TrackedTime

* Use var directly

* Add logger

* Fix lint

* Fix test

* Add comments

* fmt

* [test] get issue directly by ID

* Update test

* Add description for changed refs

* Fix build issues + lint

* Fix build

* Use string enums

* Update swagger

* Support `page` and `limit` params

* fmt + swagger

* Use global slices

Co-authored-by: zeripath <art27@cantab.net>
Co-authored-by: Lunny Xiao <xiaolunwen@gmail.com>
2022-01-01 22:12:25 +08:00
qwerty287 7cc44491fa
Add API to manage repo tranfers (#17963) 2021-12-23 23:26:52 -05:00
Lunny Xiao 5723240490
Some repository refactors (#17950)
* some repository refactors

* remove unnecessary code

* Fix test

* Remove unnecessary banner
2021-12-12 23:48:20 +08:00
Lunny Xiao 719bddcd76
Move repository model into models/repo (#17933)
* Some refactors related repository model

* Move more methods out of repository

* Move repository into models/repo

* Fix test

* Fix test

* some improvements

* Remove unnecessary function
2021-12-10 09:27:50 +08:00
Lunny Xiao a666829a37
Move user related model into models/user (#17781)
* Move user related model into models/user

* Fix lint for windows

* Fix windows lint

* Fix windows lint

* Move some tests in models

* Merge
2021-11-24 17:49:20 +08:00
Gusted ed23a6c397
Make `bind` error more readable (#17750)
- Add the related fieldNames into the response JSON, such that the developer can figure out what's going on.
- Related:
https://github.com/go-gitea/gitea/issues/17126#issuecomment-937848295
2021-11-22 21:05:29 +08:00
zeripath f8ec43dbc7
Extract constant names out for the ReverseProxy and Basic authentication methods (#17735)
In order to reduce load on the GC extract out the constant names of the Basic and ReverseProxy methods.

As mentioned in https://github.com/go-gitea/gitea/pull/15119#discussion_r730352176

Signed-off-by: Andrew Thornton <art27@cantab.net>
2021-11-20 23:33:18 +08:00
Paweł Bogusławski d4e281bc02
Allow Token API calls be authorized using the reverse-proxy header (#15119)
* API calls authorized with HTTP header

This mod allows API calls to be authorized with HTTP header
when ENABLE_REVERSE_PROXY_AUTHENTICATION is enabled. Without
it user authenticated by reverse proxy is able to access
gitea UI but not API which is inconsistent.

Author-Change-Id: IB#1107572

* Fixed API calls authorized with HTTP header

Only reqBasicAuth is modified to allow reverse proxy
auth as alternative and reqToken is left untouched.

Fixes: dc952c063206d11504085ddea966f121e796a04c
Author-Change-Id: IB#1107572

* Reverse proxy API auth separated in docs

Related: https://github.com/go-gitea/gitea/pull/15119#discussion_r621322127
Author-Change-Id: IB#1107572

* Reverse proxy API auth separated in docs

Related: https://github.com/go-gitea/gitea/pull/15119#discussion_r621322127
Author-Change-Id: IB#1107572

* Reverse proxy API auth separated

Related: https://github.com/go-gitea/gitea/pull/15119#discussion_r621322127
Author-Change-Id: IB#1107572

* ReverseProxyAuth removed from swagger

ReverseProxyAuth removed from swagger as in upstream's suggestion.

Related: https://github.com/go-gitea/gitea/pull/15119#pullrequestreview-692180940
Author-Change-Id: IB#1107572

* ReverseProxyAuth API authorization fixed

Related: https://github.com/go-gitea/gitea/pull/15119#issuecomment-868465099
Author-Change-Id: IB#1107572

* ReverseProxyAuth API authorization fixed

Related: https://github.com/go-gitea/gitea/pull/15119#issuecomment-868465099
Author-Change-Id: IB#1107572
2021-11-19 22:54:44 +08:00
wxiaoguang 750a8465f5
A better go code formatter, and now `make fmt` can run in Windows (#17684)
* go build / format tools
* re-format imports
2021-11-17 20:34:35 +08:00
Lunny Xiao 90eb9fb889
Move EmailAddress & UserRedirect into models/user/ (#17607)
* Move EmailAddress into models/user/

* Fix test

* rename user_mail to user_email

* Fix test

* Move UserRedirect into models/user/

* Fix lint & test

* Fix lint

* Fix lint

* remove nolint comment

* Fix lint
2021-11-11 15:03:30 +08:00