Skip to content
This repository was archived by the owner on Apr 7, 2024. It is now read-only.

Commit ae05469

Browse files
authored
Merge pull request #1 from lunny/WinnerSoftLab-feature/code_owners
2 parents 1b80b88 + 7ddd654 commit ae05469

File tree

40 files changed

+508
-214
lines changed

40 files changed

+508
-214
lines changed

.golangci.yml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -86,6 +86,7 @@ linters-settings:
8686
- io/ioutil: "use os or io instead"
8787
- golang.org/x/exp: "it's experimental and unreliable."
8888
- code.gitea.io/gitea/modules/git/internal: "do not use the internal package, use AddXxx function instead"
89+
- gopkg.in/ini.v1: "do not use the ini package, use gitea's config system instead"
8990

9091
issues:
9192
max-issues-per-linter: 0

build/backport-locales.go

Lines changed: 4 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ import (
1212
"path/filepath"
1313
"strings"
1414

15-
"gopkg.in/ini.v1"
15+
"code.gitea.io/gitea/modules/setting"
1616
)
1717

1818
func main() {
@@ -22,25 +22,21 @@ func main() {
2222
os.Exit(1)
2323
}
2424

25-
ini.PrettyFormat = false
2625
mustNoErr := func(err error) {
2726
if err != nil {
2827
panic(err)
2928
}
3029
}
31-
collectInis := func(ref string) map[string]*ini.File {
32-
inis := map[string]*ini.File{}
30+
collectInis := func(ref string) map[string]setting.ConfigProvider {
31+
inis := map[string]setting.ConfigProvider{}
3332
err := filepath.WalkDir("options/locale", func(path string, d os.DirEntry, err error) error {
3433
if err != nil {
3534
return err
3635
}
3736
if d.IsDir() || !strings.HasSuffix(d.Name(), ".ini") {
3837
return nil
3938
}
40-
cfg, err := ini.LoadSources(ini.LoadOptions{
41-
IgnoreInlineComment: true,
42-
UnescapeValueCommentSymbols: true,
43-
}, path)
39+
cfg, err := setting.NewConfigProviderForLocale(path)
4440
mustNoErr(err)
4541
inis[path] = cfg
4642
fmt.Printf("collecting: %s @ %s\n", path, ref)

contrib/environment-to-ini/environment-to-ini.go

Lines changed: 2 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -9,10 +9,8 @@ import (
99

1010
"code.gitea.io/gitea/modules/log"
1111
"code.gitea.io/gitea/modules/setting"
12-
"code.gitea.io/gitea/modules/util"
1312

1413
"github.com/urfave/cli"
15-
"gopkg.in/ini.v1"
1614
)
1715

1816
// EnvironmentPrefix environment variables prefixed with this represent ini values to write
@@ -97,19 +95,10 @@ func runEnvironmentToIni(c *cli.Context) error {
9795
providedWorkPath := c.String("work-path")
9896
setting.SetCustomPathAndConf(providedCustom, providedConf, providedWorkPath)
9997

100-
cfg := ini.Empty()
101-
confFileExists, err := util.IsFile(setting.CustomConf)
98+
cfg, err := setting.NewConfigProviderFromFile(&setting.Options{CustomConf: setting.CustomConf, AllowEmpty: true})
10299
if err != nil {
103-
log.Fatal("Unable to check if %s is a file. Error: %v", setting.CustomConf, err)
100+
log.Fatal("Failed to load custom conf '%s': %v", setting.CustomConf, err)
104101
}
105-
if confFileExists {
106-
if err := cfg.Append(setting.CustomConf); err != nil {
107-
log.Fatal("Failed to load custom conf '%s': %v", setting.CustomConf, err)
108-
}
109-
} else {
110-
log.Warn("Custom config '%s' not found, ignore this if you're running first time", setting.CustomConf)
111-
}
112-
cfg.NameMapper = ini.SnackCase
113102

114103
prefixGitea := c.String("prefix") + "__"
115104
suffixFile := "__FILE"

docs/content/doc/development/oauth2-provider.en-us.md

Lines changed: 71 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
---
2-
date: "2019-04-19:44:00+01:00"
2+
date: "2023-06-01T08:40:00+08:00"
33
title: "OAuth2 provider"
44
slug: "oauth2-provider"
55
weight: 41
@@ -40,7 +40,7 @@ At the moment Gitea only supports the [**Authorization Code Grant**](https://too
4040
- [Proof Key for Code Exchange (PKCE)](https://tools.ietf.org/html/rfc7636)
4141
- [OpenID Connect (OIDC)](https://openid.net/specs/openid-connect-core-1_0.html#CodeFlowAuth)
4242

43-
To use the Authorization Code Grant as a third party application it is required to register a new application via the "Settings" (`/user/settings/applications`) section of the settings.
43+
To use the Authorization Code Grant as a third party application it is required to register a new application via the "Settings" (`/user/settings/applications`) section of the settings. To test or debug you can use the web-tool https://oauthdebugger.com/.
4444

4545
## Scopes
4646

@@ -87,17 +87,19 @@ Gitea supports both confidential and public client types, [as defined by RFC 674
8787

8888
For public clients, a redirect URI of a loopback IP address such as `http://127.0.0.1/` allows any port. Avoid using `localhost`, [as recommended by RFC 8252](https://datatracker.ietf.org/doc/html/rfc8252#section-8.3).
8989

90-
## Example
90+
## Examples
91+
92+
### Confidential client
9193

9294
**Note:** This example does not use PKCE.
9395

94-
1. Redirect to user to the authorization endpoint in order to get their consent for accessing the resources:
96+
1. Redirect the user to the authorization endpoint in order to get their consent for accessing the resources:
9597

9698
```curl
9799
https://[YOUR-GITEA-URL]/login/oauth/authorize?client_id=CLIENT_ID&redirect_uri=REDIRECT_URI&response_type=code&state=STATE
98100
```
99101

100-
The `CLIENT_ID` can be obtained by registering an application in the settings. The `STATE` is a random string that will be send back to your application after the user authorizes. The `state` parameter is optional but should be used to prevent CSRF attacks.
102+
The `CLIENT_ID` can be obtained by registering an application in the settings. The `STATE` is a random string that will be sent back to your application after the user authorizes. The `state` parameter is optional, but should be used to prevent CSRF attacks.
101103

102104
![Authorization Page](/authorize.png)
103105

@@ -107,7 +109,7 @@ For public clients, a redirect URI of a loopback IP address such as `http://127.
107109
https://[REDIRECT_URI]?code=RETURNED_CODE&state=STATE
108110
```
109111

110-
2. Using the provided `code` from the redirect, you can request a new application and refresh token. The access token endpoints accepts POST requests with `application/json` and `application/x-www-form-urlencoded` body, for example:
112+
2. Using the provided `code` from the redirect, you can request a new application and refresh token. The access token endpoint accepts POST requests with `application/json` and `application/x-www-form-urlencoded` body, for example:
111113

112114
```curl
113115
POST https://[YOUR-GITEA-URL]/login/oauth/access_token
@@ -134,7 +136,69 @@ For public clients, a redirect URI of a loopback IP address such as `http://127.
134136
}
135137
```
136138

137-
The `CLIENT_SECRET` is the unique secret code generated for this application. Please note that the secret will only be visible after you created/registered the application with Gitea and cannot be recovered. If you lose the secret you must regenerate the secret via the application's settings.
139+
The `CLIENT_SECRET` is the unique secret code generated for this application. Please note that the secret will only be visible after you created/registered the application with Gitea and cannot be recovered. If you lose the secret, you must regenerate the secret via the application's settings.
140+
141+
The `REDIRECT_URI` in the `access_token` request must match the `REDIRECT_URI` in the `authorize` request.
142+
143+
3. Use the `access_token` to make [API requests](https://docs.gitea.io/en-us/api-usage#oauth2) to access the user's resources.
144+
145+
### Public client (PKCE)
146+
147+
PKCE (Proof Key for Code Exchange) is an extension to the OAuth flow which allows for a secure credential exchange without the requirement to provide a client secret.
148+
149+
**Note**: Please ensure you have registered your OAuth application as a public client.
150+
151+
To achieve this, you have to provide a `code_verifier` for every authorization request. A `code_verifier` has to be a random string with a minimum length of 43 characters and a maximum length of 128 characters. It can contain alphanumeric characters as well as the characters `-`, `.`, `_` and `~`.
152+
153+
Using this `code_verifier` string, a new one called `code_challenge` is created by using one of two methods:
154+
155+
- If you have the required functionality on your client, set `code_challenge` to be a URL-safe base64-encoded string of the SHA256 hash of `code_verifier`. In that case, your `code_challenge_method` becomes `S256`.
156+
- If you are unable to do so, you can provide your `code_verifier` as a plain string to `code_challenge`. Then you have to set your `code_challenge_method` as `plain`.
157+
158+
After you have generated this values, you can continue with your request.
159+
160+
1. Redirect the user to the authorization endpoint in order to get their consent for accessing the resources:
161+
162+
```curl
163+
https://[YOUR-GITEA-URL]/login/oauth/authorize?client_id=CLIENT_ID&redirect_uri=REDIRECT_URI&response_type=code&code_challenge_method=CODE_CHALLENGE_METHOD&code_challenge=CODE_CHALLENGE&state=STATE
164+
```
165+
166+
The `CLIENT_ID` can be obtained by registering an application in the settings. The `STATE` is a random string that will be sent back to your application after the user authorizes. The `state` parameter is optional, but should be used to prevent CSRF attacks.
167+
168+
![Authorization Page](/authorize.png)
169+
170+
The user will now be asked to authorize your application. If they authorize it, the user will be redirected to the `REDIRECT_URL`, for example:
171+
172+
```curl
173+
https://[REDIRECT_URI]?code=RETURNED_CODE&state=STATE
174+
```
175+
176+
2. Using the provided `code` from the redirect, you can request a new application and refresh token. The access token endpoint accepts POST requests with `application/json` and `application/x-www-form-urlencoded` body, for example:
177+
178+
```curl
179+
POST https://[YOUR-GITEA-URL]/login/oauth/access_token
180+
```
181+
182+
```json
183+
{
184+
"client_id": "YOUR_CLIENT_ID",
185+
"code": "RETURNED_CODE",
186+
"grant_type": "authorization_code",
187+
"redirect_uri": "REDIRECT_URI",
188+
"code_verifier": "CODE_VERIFIER",
189+
}
190+
```
191+
192+
Response:
193+
194+
```json
195+
{
196+
"access_token": "eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9.eyJnbnQiOjIsInR0IjowLCJleHAiOjE1NTUxNzk5MTIsImlhdCI6MTU1NTE3NjMxMn0.0-iFsAwBtxuckA0sNZ6QpBQmywVPz129u75vOM7wPJecw5wqGyBkmstfJHAjEOqrAf_V5Z-1QYeCh_Cz4RiKug",
197+
"token_type": "bearer",
198+
"expires_in": 3600,
199+
"refresh_token": "eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9.eyJnbnQiOjIsInR0IjoxLCJjbnQiOjEsImV4cCI6MTU1NzgwNDMxMiwiaWF0IjoxNTU1MTc2MzEyfQ.S_HZQBy4q9r5SEzNGNIoFClT43HPNDbUdHH-GYNYYdkRfft6XptJBkUQscZsGxOW975Yk6RbgtGvq1nkEcklOw"
200+
}
201+
```
138202

139203
The `REDIRECT_URI` in the `access_token` request must match the `REDIRECT_URI` in the `authorize` request.
140204

docs/content/doc/usage/labels.en-us.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ For organizations, you can define organization-wide labels that are shared with
2727

2828
Labels have a mandatory name, a mandatory color, an optional description, and must either be exclusive or not (see `Scoped Labels` below).
2929

30-
When you create a repository, you can ensure certain labels exist by using the `Issue Labels` option. This option lists a number of available label sets that are [configured globally on your instance](../customizing-gitea/#labels). Its contained labels will all be created as well while creating the repository.
30+
When you create a repository, you can ensure certain labels exist by using the `Issue Labels` option. This option lists a number of available label sets that are [configured globally on your instance](../administration/customizing-gitea/#labels). Its contained labels will all be created as well while creating the repository.
3131

3232
## Scoped Labels
3333

docs/content/doc/usage/labels.zh-cn.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ menu:
2727

2828
标签具有必填的名称和颜色,可选的描述,以及必须是独占的或非独占的(见下面的“作用域标签”)。
2929

30-
当您创建一个仓库时,可以通过使用 `工单标签(Issue Labels)` 选项来选择标签集。该选项列出了一些在您的实例上 [全局配置的可用标签集](../customizing-gitea/#labels)。在创建仓库时,这些标签也将被创建。
30+
当您创建一个仓库时,可以通过使用 `工单标签(Issue Labels)` 选项来选择标签集。该选项列出了一些在您的实例上 [全局配置的可用标签集](../administration/customizing-gitea/#labels)。在创建仓库时,这些标签也将被创建。
3131

3232
## 作用域标签
3333

models/activities/statistic.go

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ import (
2121
type Statistic struct {
2222
Counter struct {
2323
User, Org, PublicKey,
24-
Repo, Watch, Star, Action, Access,
24+
Repo, Watch, Star, Access,
2525
Issue, IssueClosed, IssueOpen,
2626
Comment, Oauth, Follow,
2727
Mirror, Release, AuthSource, Webhook,
@@ -55,7 +55,6 @@ func GetStatistic() (stats Statistic) {
5555
stats.Counter.Repo, _ = repo_model.CountRepositories(db.DefaultContext, repo_model.CountRepositoryOptions{})
5656
stats.Counter.Watch, _ = e.Count(new(repo_model.Watch))
5757
stats.Counter.Star, _ = e.Count(new(repo_model.Star))
58-
stats.Counter.Action, _ = db.EstimateCount(db.DefaultContext, new(Action))
5958
stats.Counter.Access, _ = e.Count(new(access_model.Access))
6059

6160
type IssueCount struct {
@@ -83,7 +82,7 @@ func GetStatistic() (stats Statistic) {
8382
Find(&stats.Counter.IssueByRepository)
8483
}
8584

86-
issueCounts := []IssueCount{}
85+
var issueCounts []IssueCount
8786

8887
_ = e.Select("COUNT(*) AS count, is_closed").Table("issue").GroupBy("is_closed").Find(&issueCounts)
8988
for _, c := range issueCounts {

models/db/context.go

Lines changed: 0 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,6 @@ import (
99

1010
"xorm.io/builder"
1111
"xorm.io/xorm"
12-
"xorm.io/xorm/schemas"
1312
)
1413

1514
// DefaultContext is the default context to run xorm queries in
@@ -241,30 +240,6 @@ func TableName(bean interface{}) string {
241240
return x.TableName(bean)
242241
}
243242

244-
// EstimateCount returns an estimate of total number of rows in table
245-
func EstimateCount(ctx context.Context, bean interface{}) (int64, error) {
246-
e := GetEngine(ctx)
247-
e.Context(ctx)
248-
249-
var rows int64
250-
var err error
251-
tablename := TableName(bean)
252-
switch x.Dialect().URI().DBType {
253-
case schemas.MYSQL:
254-
_, err = e.Context(ctx).SQL("SELECT table_rows FROM information_schema.tables WHERE tables.table_name = ? AND tables.table_schema = ?;", tablename, x.Dialect().URI().DBName).Get(&rows)
255-
case schemas.POSTGRES:
256-
// the table can live in multiple schemas of a postgres database
257-
// See https://wiki.postgresql.org/wiki/Count_estimate
258-
tablename = x.TableName(bean, true)
259-
_, err = e.Context(ctx).SQL("SELECT reltuples::bigint AS estimate FROM pg_class WHERE oid = ?::regclass;", tablename).Get(&rows)
260-
case schemas.MSSQL:
261-
_, err = e.Context(ctx).SQL("sp_spaceused ?;", tablename).Get(&rows)
262-
default:
263-
return e.Context(ctx).Count(tablename)
264-
}
265-
return rows, err
266-
}
267-
268243
// InTransaction returns true if the engine is in a transaction otherwise return false
269244
func InTransaction(ctx context.Context) bool {
270245
_, ok := inTransaction(ctx)

models/issues/pull_test.go

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -324,5 +324,4 @@ func TestParseCodeOwnersLine(t *testing.T) {
324324
tokens := issues_model.TokenizeCodeOwnersLine(g.Line)
325325
assert.Equal(t, g.Tokens, tokens, "Codeowners tokenizer failed")
326326
}
327-
328327
}

modules/metrics/collector.go

Lines changed: 0 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,6 @@ const namespace = "gitea_"
1818
// exposes gitea metrics for prometheus
1919
type Collector struct {
2020
Accesses *prometheus.Desc
21-
Actions *prometheus.Desc
2221
Attachments *prometheus.Desc
2322
BuildInfo *prometheus.Desc
2423
Comments *prometheus.Desc
@@ -56,11 +55,6 @@ func NewCollector() Collector {
5655
"Number of Accesses",
5756
nil, nil,
5857
),
59-
Actions: prometheus.NewDesc(
60-
namespace+"actions",
61-
"Number of Actions",
62-
nil, nil,
63-
),
6458
Attachments: prometheus.NewDesc(
6559
namespace+"attachments",
6660
"Number of Attachments",
@@ -207,7 +201,6 @@ func NewCollector() Collector {
207201
// Describe returns all possible prometheus.Desc
208202
func (c Collector) Describe(ch chan<- *prometheus.Desc) {
209203
ch <- c.Accesses
210-
ch <- c.Actions
211204
ch <- c.Attachments
212205
ch <- c.BuildInfo
213206
ch <- c.Comments
@@ -246,11 +239,6 @@ func (c Collector) Collect(ch chan<- prometheus.Metric) {
246239
prometheus.GaugeValue,
247240
float64(stats.Counter.Access),
248241
)
249-
ch <- prometheus.MustNewConstMetric(
250-
c.Actions,
251-
prometheus.GaugeValue,
252-
float64(stats.Counter.Action),
253-
)
254242
ch <- prometheus.MustNewConstMetric(
255243
c.Attachments,
256244
prometheus.GaugeValue,

modules/repository/repo.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ import (
2727
"code.gitea.io/gitea/modules/timeutil"
2828
"code.gitea.io/gitea/modules/util"
2929

30-
"gopkg.in/ini.v1"
30+
"gopkg.in/ini.v1" //nolint:depguard
3131
)
3232

3333
/*
@@ -241,7 +241,7 @@ func MigrateRepositoryGitData(ctx context.Context, u *user_model.User,
241241
// cleanUpMigrateGitConfig removes mirror info which prevents "push --all".
242242
// This also removes possible user credentials.
243243
func cleanUpMigrateGitConfig(configPath string) error {
244-
cfg, err := ini.Load(configPath)
244+
cfg, err := ini.Load(configPath) // FIXME: the ini package doesn't really work with git config files
245245
if err != nil {
246246
return fmt.Errorf("open config file: %w", err)
247247
}

modules/setting/config_env.go

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -10,8 +10,6 @@ import (
1010
"strings"
1111

1212
"code.gitea.io/gitea/modules/log"
13-
14-
"gopkg.in/ini.v1"
1513
)
1614

1715
const escapeRegexpString = "_0[xX](([0-9a-fA-F][0-9a-fA-F])+)_"
@@ -89,7 +87,7 @@ func decodeEnvironmentKey(prefixGitea, suffixFile, envKey string) (ok bool, sect
8987
return ok, section, key, useFileValue
9088
}
9189

92-
func EnvironmentToConfig(cfg *ini.File, prefixGitea, suffixFile string, envs []string) (changed bool) {
90+
func EnvironmentToConfig(cfg ConfigProvider, prefixGitea, suffixFile string, envs []string) (changed bool) {
9391
for _, kv := range envs {
9492
idx := strings.IndexByte(kv, '=')
9593
if idx < 0 {

modules/setting/config_env_test.go

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,6 @@ import (
88
"testing"
99

1010
"github.com/stretchr/testify/assert"
11-
"gopkg.in/ini.v1"
1211
)
1312

1413
func TestDecodeEnvSectionKey(t *testing.T) {
@@ -71,15 +70,15 @@ func TestDecodeEnvironmentKey(t *testing.T) {
7170
}
7271

7372
func TestEnvironmentToConfig(t *testing.T) {
74-
cfg := ini.Empty()
73+
cfg, _ := NewConfigProviderFromData("")
7574

7675
changed := EnvironmentToConfig(cfg, "GITEA__", "__FILE", nil)
7776
assert.False(t, changed)
7877

79-
cfg, err := ini.Load([]byte(`
78+
cfg, err := NewConfigProviderFromData(`
8079
[sec]
8180
key = old
82-
`))
81+
`)
8382
assert.NoError(t, err)
8483

8584
changed = EnvironmentToConfig(cfg, "GITEA__", "__FILE", []string{"GITEA__sec__key=new"})

0 commit comments

Comments
 (0)