This PR adds the necessary work to make it possible to create files on empty
repos using the API.
Fix#10993
Signed-off-by: Andrew Thornton <art27@cantab.net>
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.
* Fix page and missing return on unadopted repos API
Page must be 1 if it's not specified and it should return after sending an internal server error.
* Allow ignore pages
Co-authored-by: Lunny Xiao <xiaolunwen@gmail.com>
* logs: add the buffer logger to inspect logs during testing
Signed-off-by: Loïc Dachary <loic@dachary.org>
* migrations: add test for importing pull requests in gitea uploader
Signed-off-by: Loïc Dachary <loic@dachary.org>
* for each git.OpenRepositoryCtx, call Close
* Content is expected to return the content of the log
* test for errors before defer
Co-authored-by: Loïc Dachary <loic@dachary.org>
Co-authored-by: zeripath <art27@cantab.net>
Co-authored-by: Lunny Xiao <xiaolunwen@gmail.com>
* Use email_address table to check user's email when login with email adress
* Update services/auth/signin.go
* Fix test
* Fix test
* Fix logging in with ldap username != loginname
* Fix if user does not exist yet
* Make more clear this is loginName
* Fix formatting
Co-authored-by: Lunny Xiao <xiaolunwen@gmail.com>
Co-authored-by: zeripath <art27@cantab.net>
* Add setting for a JSON that maps LDAP groups to Org Teams.
* Add log when removing or adding team members.
* Sync is being run on login and periodically.
* Existing group filter settings are reused.
* Adding and removing team members.
* Sync not existing LDAP group.
* Login with broken group map JSON.
It is a leftover forgotten in https://github.com/go-gitea/gitea/pull/18621
Signed-off-by: singuliere <singuliere@autistici.org>
Co-authored-by: Lunny Xiao <xiaolunwen@gmail.com>
The tests were refactored so that all YAML files content are checked,
unless an exception is set (for instance for the Updated field which
is automatically updated by the database and cannot be expected to be
identical over a dump/restore/dump round.
This approach helps catch more errors where fields are added in the
migration files because they do not need to be added to the tests to
be verified.
It also helps as a reminder of what is left to be implemented, such as
the the Assignees field in issues.
A helper is added to keep the tests DRY and facilitate their
maintenance.
Signed-off-by: Loïc Dachary <loic@dachary.org>
Co-authored-by: Loïc Dachary <loic@dachary.org>
Co-authored-by: Lunny Xiao <xiaolunwen@gmail.com>
When calling DumpRepository and RestoreRepository on the same Gitea
instance, the users are preserved: all labels, issues etc. belong to
the external user who is, in this particular case, the local user.
Dead code verifying g.gitServiceType.Name() == "" (i.e. plain git) is
removed. The function is never called because the plain git downloader
does not migrate anything that is associated to a user, by definition.
Errors returned by GetUserIDByExternalUserID are no longer ignored.
The userMap is used when the external user is not kown, which is the
most common case. It was only used when the external user exists
which happens less often and, as a result, every occurence of an
unknown external user required a SQL query.
Signed-off-by: Loïc Dachary <loic@dachary.org>
Co-authored-by: Loïc Dachary <loic@dachary.org>
Co-authored-by: Lunny Xiao <xiaolunwen@gmail.com>
- Switch to use `CryptoRandomBytes` instead of `CryptoRandomString`, OAuth's secrets are copied pasted and don't need to avoid dubious characters etc.
- `CryptoRandomBytes` gives ![2^256 = 1.15 * 10^77](https://render.githubusercontent.com/render/math?math=2^256%20=%201.15%20\cdot%2010^77) `CryptoRandomString` gives ![62^44 = 7.33 * 10^78](https://render.githubusercontent.com/render/math?math=62^44%20=%207.33%20\cdot%2010^78) possible states.
- Add a prefix, such that code scanners can easily grep these in source code.
- 32 Bytes + prefix
One of the repeated intermittent failures we see in testing is a failure due to
branches not being ready to merge.
Prior to the immediate queue implementation we would attempt to flush all the queues
and this would prevent the issue. However, the immediate queue is not flushable so
the flushall is not successful at preventing this.
This PR proposes an alternative solution - wait some time and try again up to 5 times.
If this fails then there is a genuine issue and we should fail.
Related #17719
Signed-off-by: Andrew Thornton <art27@cantab.net>
* Ensure git tag tests and other create test repos in tmpdir
There are a few places where tests appear to reuse testing repos which
causes random CI failures.
This PR simply changes these tests to ensure that cloning always happens
into new temporary directories.
Fix#18444
* Change log root for integration tests to use the REPO_TEST_DIR
There is a potential race in the drone integration tests whereby test-mysql etc
will start writing to log files causing make test-check fail.
Fix#18077
Signed-off-by: Andrew Thornton <art27@cantab.net>
- Pass the Global command args into serviceRPC.
- Fixes error with partial cloning.
- Add partial clone test
- Include diff
Co-authored-by: Lunny Xiao <xiaolunwen@gmail.com>
* Switch to non-deprecation setting
(Avoid by-default: "Deprecated fallback `[server]` `LFS_CONTENT_PATH` present. Use `[lfs]` `PATH` instead. This fallback will be removed in v1.18.0")
* Update all references
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>
* migrations: a deadline at January 1st, 1970 is valid
Do not change the deadline value if it is set to January 1st, 1970.
Setting the deadline to year 9999 when it is zero (which is equal to
January 1st, 1970) modifies a deadline set to January 1st, 1970 which
is a valid date. In addition, setting a date in year 9999 will be
converted to a null date in some cases.
Signed-off-by: Loïc Dachary <loic@dachary.org>
* tests: set milestone.deadline_unix in fixtures
The value of deadline_unix must be set to 253370764800 (i.e. 9999-01-01) in
fixtures, otherwise it will be inserted as null which leads to
unexpected errors. For instance, DumpRepository will store a null
deadline_unix as 0 (i.e. 1970-01-01) and RestoreRepository will change
it to 9999-01-01.
Signed-off-by: Loïc Dachary <loic@dachary.org>
Co-authored-by: Loïc Dachary <loic@dachary.org>
Co-authored-by: wxiaoguang <wxiaoguang@gmail.com>
* Team permission allow different unit has different permission
* Finish the interface and the logic
* Fix lint
* Fix translation
* align center for table cell content
* Fix fixture
* merge
* Fix test
* Add deprecated
* Improve code
* Add tooltip
* Fix swagger
* Fix newline
* Fix tests
* Fix tests
* Fix test
* Fix test
* Max permission of external wiki and issues should be read
* Move team units with limited max level below units table
* Update label and column names
* Some improvements
* Fix lint
* Some improvements
* Fix template variables
* Add permission docs
* improve doc
* Fix fixture
* Fix bug
* Fix some bug
* fix
* gofumpt
* Integration test for migration (#18124)
integrations: basic test for Gitea {dump,restore}-repo
This is a first step for integration testing of DumpRepository and
RestoreRepository. It:
runs a Gitea server,
dumps a repo via DumpRepository to the filesystem,
restores the repo via RestoreRepository from the filesystem,
dumps the restored repository to the filesystem,
compares the first and second dump and expects them to be identical
The verification is trivial and the goal is to add more tests for each
topic of the dump.
Signed-off-by: Loïc Dachary <loic@dachary.org>
* Team permission allow different unit has different permission
* Finish the interface and the logic
* Fix lint
* Fix translation
* align center for table cell content
* Fix fixture
* merge
* Fix test
* Add deprecated
* Improve code
* Add tooltip
* Fix swagger
* Fix newline
* Fix tests
* Fix tests
* Fix test
* Fix test
* Max permission of external wiki and issues should be read
* Move team units with limited max level below units table
* Update label and column names
* Some improvements
* Fix lint
* Some improvements
* Fix template variables
* Add permission docs
* improve doc
* Fix fixture
* Fix bug
* Fix some bug
* Fix bug
Co-authored-by: Lauris BH <lauris@nix.lv>
Co-authored-by: 6543 <6543@obermui.de>
Co-authored-by: Aravinth Manivannan <realaravinth@batsense.net>
integrations: basic test for Gitea {dump,restore}-repo
This is a first step for integration testing of DumpRepository and
RestoreRepository. It:
runs a Gitea server,
dumps a repo via DumpRepository to the filesystem,
restores the repo via RestoreRepository from the filesystem,
dumps the restored repository to the filesystem,
compares the first and second dump and expects them to be identical
The verification is trivial and the goal is to add more tests for each
topic of the dump.
Signed-off-by: Loïc Dachary <loic@dachary.org>
* 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.
Closesgo-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>
* Handle invalid issues
- When you hover over a issue reference, and the issue doesn't exist, it
will just hang on the loading animation.
- This patch fixes that by showing them the pop-up with a "Error
occured" message.
* Add I18N
* refactor
* fix comment for lint
* fix unit test for i18n
* fix unit test for i18n
* add comments
Co-authored-by: Lunny Xiao <xiaolunwen@gmail.com>
Co-authored-by: wxiaoguang <wxiaoguang@gmail.com>
A consequence of forcibly setting the RoutePath to the escaped url is that the
auto routing to endpoints without terminal slashes fails (Causing #18060.) This
failure raises the possibility that forcibly setting the RoutePath causes other
unexpected behaviors too.
Therefore, instead we should simply pre-escape the URL in the process registering
handler. Then the request URL will be properly escaped for all the following calls.
Fix#17938Fix#18060
Replace #18062
Replace #17997
Signed-off-by: Andrew Thornton <art27@cantab.net>
PR #17997 means that urls with terminal '/' are no longer immediately mapped
to the url without a terminal slash. However, it has revealed that the NotFound handler
appears to have been lost.
This PR adds back in a NotFound handler that simply redirects to a path without the
terminal slash or runs the NotFound handler.
Fix#18060
Signed-off-by: Andrew Thornton <art27@cantab.net>
* Make test work with different default branch config
On a system configured with a different default branch name, doGitInitTestRepository
will create a repository with a branch named differently, and so further tests
would break:
--- FAIL: TestGit/HTTP/PushCreate/SuccessfullyPushAndCreateTestRepository (0.02s)
git_helper_for_declarative_test.go:167:
Error Trace: git_helper_for_declarative_test.go:167
Error: Received unexpected error:
exit status 1 - error: src refspec master does not match any
error: failed to push some refs to 'http://127.0.0.1:3003/user2/repo-tmp-push-create-http.git'
Test: TestGit/HTTP/PushCreate/SuccessfullyPushAndCreateTestRepository
git_test.go:587:
Error Trace: git_test.go:587
Error: Received unexpected error:
repository does not exist [id: 0, uid: 0, owner_name: user2, name: repo-tmp-push-create-http]
Test: TestGit/HTTP/PushCreate
* Update integrations/git_helper_for_declarative_test.go
Co-authored-by: Lunny Xiao <xiaolunwen@gmail.com>
Co-authored-by: zeripath <art27@cantab.net>
Co-authored-by: 6543 <6543@obermui.de>
* Abort merge if head has been updated before pressing merge
It is possible that a PR head may be pushed to between the merge page being shown
and the merge button being pressed. Pass the current expected head in as a parameter
and cancel the merge if it has changed.
Fix#18028
Signed-off-by: Andrew Thornton <art27@cantab.net>
* adjust swagger
Signed-off-by: Andrew Thornton <art27@cantab.net>
* fix test
Signed-off-by: Andrew Thornton <art27@cantab.net>
* placate lint
Signed-off-by: Andrew Thornton <art27@cantab.net>
This PR contains multiple fixes. The most important of which is:
* Prevent hang in git cat-file if the repository is not a valid repository
Unfortunately it appears that if git cat-file is run in an invalid
repository it will hang until stdin is closed. This will result in
deadlocked /pulls pages and dangling git cat-file calls if a broken
repository is tried to be reviewed or pulls exists for a broken
repository.
Fix#14734Fix#9271Fix#16113
Otherwise there are a few small other fixes included which this PR was initially intending to fix:
* Fix panic on partial compares due to missing PullRequestWorkInProgressPrefixes
* Fix links on pulls pages due to regression from #17551 - by making most /issues routes match /pulls too - Fix#17983
* Fix links on feeds pages due to another regression from #17551 but also fix issue with syncing tags - Fix#17943
* Add missing locale entries for oauth group claims
* Prevent NPEs if ColorFormat is called on nil users, repos or teams.
There was an unfortunate regression in #14293 which has led to the double decoding
of url parameter elements if they contain a '%'. This is due to an issue
with the way chi decodes its RoutePath. In detail the problem lies in
mux.go where the routeHTTP path uses the URL.RawPath or even the
URL.Path instead of the escaped path to do routing.
This PR simply forcibly sets the routePath to that of the EscapedPath.
Fix#17938
Signed-off-by: Andrew Thornton <art27@cantab.net>
* Move keys to models/keys
* Rename models/keys -> models/asymkey
* change the missed package name
* Fix package alias
* Fix test
* Fix docs
* Fix test
* Fix test
* merge
* 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
* Improve install code to avoid low-level mistakes.
If a user tries to do a re-install in a Gitea database, they gets a warning and double check.
When Gitea runs, it never create empty app.ini automatically.
Also some small (related) refactoring:
* Refactor db.InitEngine related logic make it more clean (especially for the install code)
* Move some i18n strings out from setting.go to make the setting.go can be easily maintained.
* Show errors in CLI code if an incorrect app.ini is used.
* APP_DATA_PATH is created when installing, and checked when starting (no empty directory is created any more).
Use hostmacher to replace matchlist.
And we introduce a better DialContext to do a full host/IP check, otherwise the attackers can still bypass the allow/block list by a 302 redirection.
There are multiple places where Gitea does not properly escape URLs that it is building and there are multiple places where it builds urls when there is already a simpler function available to use this.
This is an extensive PR attempting to fix these issues.
1. The first commit in this PR looks through all href, src and links in the Gitea codebase and has attempted to catch all the places where there is potentially incomplete escaping.
2. Whilst doing this we will prefer to use functions that create URLs over recreating them by hand.
3. All uses of strings should be directly escaped - even if they are not currently expected to contain escaping characters. The main benefit to doing this will be that we can consider relaxing the constraints on user names and reponames in future.
4. The next commit looks at escaping in the wiki and re-considers the urls that are used there. Using the improved escaping here wiki files containing '/'. (This implementation will currently still place all of the wiki files the root directory of the repo but this would not be difficult to change.)
5. The title generation in feeds is now properly escaped.
6. EscapePound is no longer needed - urls should be PathEscaped / QueryEscaped as necessary but then re-escaped with Escape when creating html with locales Signed-off-by: Andrew Thornton <art27@cantab.net>
Signed-off-by: Andrew Thornton <art27@cantab.net>
The functioning of the code indexer queue really only makes sense as an unique queue
and doing this allows use to simplify the indexer data to simply delete the data if
the repo is no longer in the db.
Signed-off-by: Andrew Thornton <art27@cantab.net>
There is a small bug in the way that repo access is checked in
repoAssignment: Accessibility is checked by checking if the user has a
marked access to the repository instead of checking if the user has any
team granted access.
This PR changes this permissions check to use HasAccess() which does the
correct test. There is also a fix in the release api ListReleases where
it should return draft releases if the user is a member of a team with
write access to the releases.
The PR also adds a testcase.
Signed-off-by: Andrew Thornton <art27@cantab.net>
modules/private/serv.go has two major functions that are missing testcases to ensure
that Deploy and normal SSH keys work correctly.
This PR adds some basic integration tests for these.
Signed-off-by: Andrew Thornton <art27@cantab.net>
- Update default branch if needed
- Update protected branch if needed
- Update all not merged pull request base branch name
- Rename git branch
- Record this rename work and auto redirect for old branch on ui
Signed-off-by: a1012112796 <1012112796@qq.com>
Co-authored-by: delvh <dev.lh@web.de>
Why this refactor
The goal is to move most files from `models` package to `models.xxx` package. Many models depend on avatar model, so just move this first.
And the existing logic is not clear, there are too many function like `AvatarLink`, `RelAvatarLink`, `SizedRelAvatarLink`, `SizedAvatarLink`, `MakeFinalAvatarURL`, `HashedAvatarLink`, etc. This refactor make everything clear:
* user.AvatarLink()
* user.AvatarLinkWithSize(size)
* avatars.GenerateEmailAvatarFastLink(email, size)
* avatars.GenerateEmailAvatarFinalLink(email, size)
And many duplicated code are deleted in route handler, the handler and the model share the same avatar logic now.
* Prevent NPE on invalid diff
If ParseCompareInfo returns a nil compare info the defer function needs to ensure
that it does not attempt to close the HeadGitRepo.
Fix#17193
Signed-off-by: Andrew Thornton <art27@cantab.net>
* add TEST
Co-authored-by: 6543 <6543@obermui.de>
The io/ioutil package has been deprecated as of Go 1.16, see
https://golang.org/doc/go1.16#ioutil. This commit replaces the existing
io/ioutil functions with their new definitions in io and os packages.
Signed-off-by: Eng Zer Jun <engzerjun@gmail.com>
Co-authored-by: techknowlogick <techknowlogick@gitea.io>
Fixes#16381
Note that changes to unprotected files via the web editor still cannot be pushed directly to the protected branch. I could easily add such support for edits and deletes if needed. But for adding, uploading or renaming unprotected files, it is not trivial.
* Extract & Move GetAffectedFiles to modules/git
Rename`[repository]` `DISABLE_MIRRORS` to `[mirror]` `DISABLE_NEW_PULL` and add `ENABLED` and `DISABLE_NEW_PUSH` with the below meanings:
- `ENABLED`: **true**: Enables the mirror functionality. Set to **false** to disable all mirrors.
- `DISABLE_NEW_PULL`: **false**: Disable the creation of **new** mirrors. Pre-existing mirrors remain valid.
- `DISABLE_NEW_PUSH`: **false**: Disable the creation of **new** push mirrors. Pre-existing mirrors remain valid.
Co-authored-by: zeripath <art27@cantab.net>
Co-authored-by: delvh <dev.lh@web.de>
It is possible to get a data race right at the end of the TestMain
in integrations during the final removal of the test from the testlogger. This PR
uses a Reset function to remove any final tests but adds some extra
logging which will forcibly fail if there is an unclosed logger.
Signed-off-by: Andrew Thornton <art27@cantab.net>
* Timeout on flush in testing
At the end of each test the queues are flushed. At present there is no limit on the
length of time a flush can take which can lead to long flushes.
However, if the CI task is cancelled we lose the log information as to where the long
flush was taking place.
This PR simply adds a default time limit of 2 minutes - at which point an error will
be produced. This should allow us to more easily find the culprit.
Signed-off-by: Andrew Thornton <art27@cantab.net>
* return better error
Signed-off-by: Andrew Thornton <art27@cantab.net>
Co-authored-by: 6543 <6543@obermui.de>