Skip to content

Commit 6e5359c

Browse files
committed
Merge remote-tracking branch 'giteaofficial/main'
* giteaofficial/main: (30 commits) Improve grep search (go-gitea#30843) Don't only list code-enabled repositories when using repository API (go-gitea#30817) Fix no edit history after editing issue's title and content (go-gitea#30814) Ignore useless error message "broken pipe" (go-gitea#30801) Fix JS error on pull request page (go-gitea#30838) Fix body margin shifting with modals, fix error on project column edit (go-gitea#30831) Improve repo button row layout (go-gitea#30668) refactor: merge ListActionTasks func to action.go file (go-gitea#30811) Prevent automatic OAuth grants for public clients (go-gitea#30790) Catch and handle unallowed file type errors in issue attachment API (go-gitea#30791) Fix incorrect message id for releaes email (go-gitea#30825) Add hover outline to heatmap squares (go-gitea#30828) Remove external API calls in `TestPassword` (go-gitea#30716) Upgrade chi-binding (go-gitea#30826) Improve context popup rendering (go-gitea#30824) Fix activity heat map padding & locale (go-gitea#30823) Fix issue card layout (go-gitea#30800) Fix branch selector UI (go-gitea#30803) Fix rounded border for segment followed by pagination (go-gitea#30809) Skip gzip for some well-known compressed file types (go-gitea#30796) ...
2 parents 316e61b + 0f3e717 commit 6e5359c

File tree

87 files changed

+1078
-583
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

87 files changed

+1078
-583
lines changed

custom/conf/app.example.ini

Lines changed: 5 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1456,7 +1456,7 @@ LEVEL = Info
14561456
;; Batch size to send for batched queues
14571457
;BATCH_LENGTH = 20
14581458
;;
1459-
;; Connection string for redis queues this will store the redis or redis-cluster connection string.
1459+
;; Connection string for redis queues this will store the redis (or Redis cluster) connection string.
14601460
;; When `TYPE` is `persistable-channel`, this provides a directory for the underlying leveldb
14611461
;; or additional options of the form `leveldb://path/to/db?option=value&....`, and will override `DATADIR`.
14621462
;CONN_STR = "redis://127.0.0.1:6379/0"
@@ -1740,9 +1740,8 @@ LEVEL = Info
17401740
;; For "memory" only, GC interval in seconds, default is 60
17411741
;INTERVAL = 60
17421742
;;
1743-
;; For "redis", "redis-cluster" and "memcache", connection host address
1744-
;; redis: `redis://127.0.0.1:6379/0?pool_size=100&idle_timeout=180s`
1745-
;; redis-cluster: `redis+cluster://127.0.0.1:6379/0?pool_size=100&idle_timeout=180s`
1743+
;; For "redis" and "memcache", connection host address
1744+
;; redis: `redis://127.0.0.1:6379/0?pool_size=100&idle_timeout=180s` (or `redis+cluster://127.0.0.1:6379/0?pool_size=100&idle_timeout=180s` for a Redis cluster)
17461745
;; memcache: `127.0.0.1:11211`
17471746
;; twoqueue: `{"size":50000,"recent_ratio":0.25,"ghost_ratio":0.5}` or `50000`
17481747
;HOST =
@@ -1772,15 +1771,14 @@ LEVEL = Info
17721771
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
17731772
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
17741773
;;
1775-
;; Either "memory", "file", "redis", "redis-cluster", "db", "mysql", "couchbase", "memcache" or "postgres"
1774+
;; Either "memory", "file", "redis", "db", "mysql", "couchbase", "memcache" or "postgres"
17761775
;; Default is "memory". "db" will reuse the configuration in [database]
17771776
;PROVIDER = memory
17781777
;;
17791778
;; Provider config options
17801779
;; memory: doesn't have any config yet
17811780
;; file: session file path, e.g. `data/sessions`
1782-
;; redis: `redis://127.0.0.1:6379/0?pool_size=100&idle_timeout=180s`
1783-
;; redis-cluster: `redis+cluster://127.0.0.1:6379/0?pool_size=100&idle_timeout=180s`
1781+
;; redis: `redis://127.0.0.1:6379/0?pool_size=100&idle_timeout=180s` (or `redis+cluster://127.0.0.1:6379/0?pool_size=100&idle_timeout=180s` for a Redis cluster)
17841782
;; mysql: go-sql-driver/mysql dsn config string, e.g. `root:password@/session_table`
17851783
;PROVIDER_CONFIG = data/sessions ; Relative paths will be made absolute against _`AppWorkPath`_.
17861784
;;

docs/content/administration/config-cheat-sheet.en-us.md

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -492,7 +492,7 @@ Configuration at `[queue]` will set defaults for queues with overrides for indiv
492492
- `DATADIR`: **queues/common**: Base DataDir for storing level queues. `DATADIR` for individual queues can be set in `queue.name` sections. Relative paths will be made absolute against `%(APP_DATA_PATH)s`.
493493
- `LENGTH`: **100000**: Maximal queue size before channel queues block
494494
- `BATCH_LENGTH`: **20**: Batch data before passing to the handler
495-
- `CONN_STR`: **redis://127.0.0.1:6379/0**: Connection string for the redis queue type. For `redis-cluster` use `redis+cluster://127.0.0.1:6379/0`. Options can be set using query params. Similarly, LevelDB options can also be set using: **leveldb://relative/path?option=value** or **leveldb:///absolute/path?option=value**, and will override `DATADIR`
495+
- `CONN_STR`: **redis://127.0.0.1:6379/0**: Connection string for the redis queue type. If you're running a Redis cluster, use `redis+cluster://127.0.0.1:6379/0`. Options can be set using query params. Similarly, LevelDB options can also be set using: **leveldb://relative/path?option=value** or **leveldb:///absolute/path?option=value**, and will override `DATADIR`
496496
- `QUEUE_NAME`: **_queue**: The suffix for default redis and disk queue name. Individual queues will default to **`name`**`QUEUE_NAME` but can be overridden in the specific `queue.name` section.
497497
- `SET_NAME`: **_unique**: The suffix that will be added to the default redis and disk queue `set` name for unique queues. Individual queues will default to **`name`**`QUEUE_NAME`_`SET_NAME`_ but can be overridden in the specific `queue.name` section.
498498
- `MAX_WORKERS`: **(dynamic)**: Maximum number of worker go-routines for the queue. Default value is "CpuNum/2" clipped to between 1 and 10.
@@ -777,11 +777,11 @@ and
777777

778778
## Cache (`cache`)
779779

780-
- `ADAPTER`: **memory**: Cache engine adapter, either `memory`, `redis`, `redis-cluster`, `twoqueue` or `memcache`. (`twoqueue` represents a size limited LRU cache.)
780+
- `ADAPTER`: **memory**: Cache engine adapter, either `memory`, `redis`, `twoqueue` or `memcache`. (`twoqueue` represents a size limited LRU cache.)
781781
- `INTERVAL`: **60**: Garbage Collection interval (sec), for memory and twoqueue cache only.
782-
- `HOST`: **_empty_**: Connection string for `redis`, `redis-cluster` and `memcache`. For `twoqueue` sets configuration for the queue.
782+
- `HOST`: **_empty_**: Connection string for `redis` and `memcache`. For `twoqueue` sets configuration for the queue.
783783
- Redis: `redis://:[email protected]:6379/0?pool_size=100&idle_timeout=180s`
784-
- Redis-cluster `redis+cluster://:[email protected]:6379/0?pool_size=100&idle_timeout=180s`
784+
- For a Redis cluster: `redis+cluster://:[email protected]:6379/0?pool_size=100&idle_timeout=180s`
785785
- Memcache: `127.0.0.1:9090;127.0.0.1:9091`
786786
- TwoQueue LRU cache: `{"size":50000,"recent_ratio":0.25,"ghost_ratio":0.5}` or `50000` representing the maximum number of objects stored in the cache.
787787
- `ITEM_TTL`: **16h**: Time to keep items in cache if not used, Setting it to -1 disables caching.
@@ -793,7 +793,7 @@ and
793793

794794
## Session (`session`)
795795

796-
- `PROVIDER`: **memory**: Session engine provider \[memory, file, redis, redis-cluster, db, mysql, couchbase, memcache, postgres\]. Setting `db` will reuse the configuration in `[database]`
796+
- `PROVIDER`: **memory**: Session engine provider \[memory, file, redis, db, mysql, couchbase, memcache, postgres\]. Setting `db` will reuse the configuration in `[database]`
797797
- `PROVIDER_CONFIG`: **data/sessions**: For file, the root path; for db, empty (database config will be used); for others, the connection string. Relative paths will be made absolute against _`AppWorkPath`_.
798798
- `COOKIE_SECURE`:**_empty_**: `true` or `false`. Enable this to force using HTTPS for all session access. If not set, it defaults to `true` if the ROOT_URL is an HTTPS URL.
799799
- `COOKIE_NAME`: **i\_like\_gitea**: The name of the cookie used for the session ID.

go.mod

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ require (
88
code.gitea.io/sdk/gitea v0.17.1
99
codeberg.org/gusted/mcaptcha v0.0.0-20220723083913-4f3072e1d570
1010
connectrpc.com/connect v1.15.0
11-
gitea.com/go-chi/binding v0.0.0-20240316035258-17450c5f3028
11+
gitea.com/go-chi/binding v0.0.0-20240430071103-39a851e106ed
1212
gitea.com/go-chi/cache v0.2.0
1313
gitea.com/go-chi/captcha v0.0.0-20240315150714-fb487f629098
1414
gitea.com/go-chi/session v0.0.0-20240316035857-16768d98ec96
@@ -59,6 +59,7 @@ require (
5959
github.com/google/uuid v1.6.0
6060
github.com/gorilla/feeds v1.1.2
6161
github.com/gorilla/sessions v1.2.2
62+
github.com/h2non/gock v1.2.0
6263
github.com/hashicorp/go-version v1.6.0
6364
github.com/hashicorp/golang-lru/v2 v2.0.7
6465
github.com/huandu/xstrings v1.4.0
@@ -209,6 +210,7 @@ require (
209210
github.com/gorilla/handlers v1.5.2 // indirect
210211
github.com/gorilla/mux v1.8.1 // indirect
211212
github.com/gorilla/securecookie v1.1.2 // indirect
213+
github.com/h2non/parth v0.0.0-20190131123155-b4df798d6542 // indirect
212214
github.com/hashicorp/go-cleanhttp v0.5.2 // indirect
213215
github.com/hashicorp/go-retryablehttp v0.7.5 // indirect
214216
github.com/hashicorp/hcl v1.0.0 // indirect

go.sum

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -20,8 +20,8 @@ git.sr.ht/~mariusor/go-xsd-duration v0.0.0-20220703122237-02e73435a078 h1:cliQ4H
2020
git.sr.ht/~mariusor/go-xsd-duration v0.0.0-20220703122237-02e73435a078/go.mod h1:g/V2Hjas6Z1UHUp4yIx6bATpNzJ7DYtD0FG3+xARWxs=
2121
gitea.com/gitea/act v0.259.1 h1:8GG1o/xtUHl3qjn5f0h/2FXrT5ubBn05TJOM5ry+FBw=
2222
gitea.com/gitea/act v0.259.1/go.mod h1:UxZWRYqQG2Yj4+4OqfGWW5a3HELwejyWFQyU7F1jUD8=
23-
gitea.com/go-chi/binding v0.0.0-20240316035258-17450c5f3028 h1:6/QAx4+s0dyRwdaTFPTnhGppuiuu0OqxIH9szyTpvKw=
24-
gitea.com/go-chi/binding v0.0.0-20240316035258-17450c5f3028/go.mod h1:E3i3cgB04dDx0v3CytCgRTTn9Z/9x891aet3r456RVw=
23+
gitea.com/go-chi/binding v0.0.0-20240430071103-39a851e106ed h1:EZZBtilMLSZNWtHHcgq2mt6NSGhJSZBuduAlinMEmso=
24+
gitea.com/go-chi/binding v0.0.0-20240430071103-39a851e106ed/go.mod h1:E3i3cgB04dDx0v3CytCgRTTn9Z/9x891aet3r456RVw=
2525
gitea.com/go-chi/cache v0.2.0 h1:E0npuTfDW6CT1yD8NMDVc1SK6IeRjfmRL2zlEsCEd7w=
2626
gitea.com/go-chi/cache v0.2.0/go.mod h1:iQlVK2aKTZ/rE9UcHyz9pQWGvdP9i1eI2spOpzgCrtE=
2727
gitea.com/go-chi/captcha v0.0.0-20240315150714-fb487f629098 h1:p2ki+WK0cIeNQuqjR98IP2KZQKRzJJiV7aTeMAFwaWo=
@@ -430,6 +430,10 @@ github.com/gorilla/securecookie v1.1.2/go.mod h1:NfCASbcHqRSY+3a8tlWJwsQap2VX5pw
430430
github.com/gorilla/sessions v1.2.0/go.mod h1:dk2InVEVJ0sfLlnXv9EAgkf6ecYs/i80K/zI+bUmuGM=
431431
github.com/gorilla/sessions v1.2.2 h1:lqzMYz6bOfvn2WriPUjNByzeXIlVzURcPmgMczkmTjY=
432432
github.com/gorilla/sessions v1.2.2/go.mod h1:ePLdVu+jbEgHH+KWw8I1z2wqd0BAdAQh/8LRvBeoNcQ=
433+
github.com/h2non/gock v1.2.0 h1:K6ol8rfrRkUOefooBC8elXoaNGYkpp7y2qcxGG6BzUE=
434+
github.com/h2non/gock v1.2.0/go.mod h1:tNhoxHYW2W42cYkYb1WqzdbYIieALC99kpYr7rH/BQk=
435+
github.com/h2non/parth v0.0.0-20190131123155-b4df798d6542 h1:2VTzZjLZBgl62/EtslCrtky5vbi9dd7HrQPQIx6wqiw=
436+
github.com/h2non/parth v0.0.0-20190131123155-b4df798d6542/go.mod h1:Ow0tF8D4Kplbc8s8sSb3V2oUCygFHVp8gC3Dn6U4MNI=
433437
github.com/hashicorp/go-cleanhttp v0.5.2 h1:035FKYIWjmULyFRBKPs8TBQoi0x6d9G4xc9neXJWAZQ=
434438
github.com/hashicorp/go-cleanhttp v0.5.2/go.mod h1:kO/YDlP8L1346E6Sodw+PrpBSV4/SoxCXGY6BqNFT48=
435439
github.com/hashicorp/go-hclog v0.9.2/go.mod h1:5CU+agLiy3J7N7QjHK5d05KxGsuXiQLrjA0H7acj2lQ=
@@ -591,6 +595,8 @@ github.com/mschoch/smat v0.2.0 h1:8imxQsjDm8yFEAVBe7azKmKSgzSkZXDuKkSq9374khM=
591595
github.com/mschoch/smat v0.2.0/go.mod h1:kc9mz7DoBKqDyiRL7VZN8KvXQMWeTaVnttLRXOlotKw=
592596
github.com/msteinert/pam v1.2.0 h1:mYfjlvN2KYs2Pb9G6nb/1f/nPfAttT/Jee5Sq9r3bGE=
593597
github.com/msteinert/pam v1.2.0/go.mod h1:d2n0DCUK8rGecChV3JzvmsDjOY4R7AYbsNxAT+ftQl0=
598+
github.com/nbio/st v0.0.0-20140626010706-e9e8d9816f32 h1:W6apQkHrMkS0Muv8G/TipAy/FJl/rCYT0+EuS8+Z0z4=
599+
github.com/nbio/st v0.0.0-20140626010706-e9e8d9816f32/go.mod h1:9wM+0iRr9ahx58uYLpLIr5fm8diHn0JbqRycJi6w0Ms=
594600
github.com/niklasfasching/go-org v1.7.0 h1:vyMdcMWWTe/XmANk19F4k8XGBYg0GQ/gJGMimOjGMek=
595601
github.com/niklasfasching/go-org v1.7.0/go.mod h1:WuVm4d45oePiE0eX25GqTDQIt/qPW1T9DGkRscqLW5o=
596602
github.com/nwaples/rardecode v1.1.0/go.mod h1:5DzqNKiOdpKKBH87u8VlvAnPZMXcGRhxWkRpHbbfGS0=

models/issues/issue_update.go

Lines changed: 0 additions & 56 deletions
Original file line numberDiff line numberDiff line change
@@ -429,62 +429,6 @@ func UpdateIssueMentions(ctx context.Context, issueID int64, mentions []*user_mo
429429
return nil
430430
}
431431

432-
// UpdateIssueByAPI updates all allowed fields of given issue.
433-
// If the issue status is changed a statusChangeComment is returned
434-
// similarly if the title is changed the titleChanged bool is set to true
435-
func UpdateIssueByAPI(ctx context.Context, issue *Issue, doer *user_model.User) (statusChangeComment *Comment, titleChanged bool, err error) {
436-
ctx, committer, err := db.TxContext(ctx)
437-
if err != nil {
438-
return nil, false, err
439-
}
440-
defer committer.Close()
441-
442-
if err := issue.LoadRepo(ctx); err != nil {
443-
return nil, false, fmt.Errorf("loadRepo: %w", err)
444-
}
445-
446-
// Reload the issue
447-
currentIssue, err := GetIssueByID(ctx, issue.ID)
448-
if err != nil {
449-
return nil, false, err
450-
}
451-
452-
if _, err := db.GetEngine(ctx).ID(issue.ID).Cols(
453-
"name", "content", "milestone_id", "priority",
454-
"deadline_unix", "updated_unix", "is_locked").
455-
Update(issue); err != nil {
456-
return nil, false, err
457-
}
458-
459-
titleChanged = currentIssue.Title != issue.Title
460-
if titleChanged {
461-
opts := &CreateCommentOptions{
462-
Type: CommentTypeChangeTitle,
463-
Doer: doer,
464-
Repo: issue.Repo,
465-
Issue: issue,
466-
OldTitle: currentIssue.Title,
467-
NewTitle: issue.Title,
468-
}
469-
_, err := CreateComment(ctx, opts)
470-
if err != nil {
471-
return nil, false, fmt.Errorf("createComment: %w", err)
472-
}
473-
}
474-
475-
if currentIssue.IsClosed != issue.IsClosed {
476-
statusChangeComment, err = doChangeIssueStatus(ctx, issue, doer, false)
477-
if err != nil {
478-
return nil, false, err
479-
}
480-
}
481-
482-
if err := issue.AddCrossReferences(ctx, doer, true); err != nil {
483-
return nil, false, err
484-
}
485-
return statusChangeComment, titleChanged, committer.Commit()
486-
}
487-
488432
// UpdateIssueDeadline updates an issue deadline and adds comments. Setting a deadline to 0 means deleting it.
489433
func UpdateIssueDeadline(ctx context.Context, issue *Issue, deadlineUnix timeutil.TimeStamp, doer *user_model.User) (err error) {
490434
// if the deadline hasn't changed do nothing

models/repo/user_repo.go

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -130,7 +130,10 @@ func GetRepoAssignees(ctx context.Context, repo *Repository) (_ []*user_model.Us
130130
// and just waste 1 unit is cheaper than re-allocate memory once.
131131
users := make([]*user_model.User, 0, len(uniqueUserIDs)+1)
132132
if len(userIDs) > 0 {
133-
if err = e.In("id", uniqueUserIDs.Values()).OrderBy(user_model.GetOrderByName()).Find(&users); err != nil {
133+
if err = e.In("id", uniqueUserIDs.Values()).
134+
Where(builder.Eq{"`user`.is_active": true}).
135+
OrderBy(user_model.GetOrderByName()).
136+
Find(&users); err != nil {
134137
return nil, err
135138
}
136139
}
@@ -152,7 +155,8 @@ func GetReviewers(ctx context.Context, repo *Repository, doerID, posterID int64)
152155
return nil, err
153156
}
154157

155-
cond := builder.And(builder.Neq{"`user`.id": posterID})
158+
cond := builder.And(builder.Neq{"`user`.id": posterID}).
159+
And(builder.Eq{"`user`.is_active": true})
156160

157161
if repo.IsPrivate || repo.Owner.Visibility == api.VisibleTypePrivate {
158162
// This a private repository:

models/repo/user_repo_test.go

Lines changed: 17 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import (
99
"code.gitea.io/gitea/models/db"
1010
repo_model "code.gitea.io/gitea/models/repo"
1111
"code.gitea.io/gitea/models/unittest"
12+
user_model "code.gitea.io/gitea/models/user"
1213

1314
"github.com/stretchr/testify/assert"
1415
)
@@ -25,8 +26,17 @@ func TestRepoAssignees(t *testing.T) {
2526
repo21 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 21})
2627
users, err = repo_model.GetRepoAssignees(db.DefaultContext, repo21)
2728
assert.NoError(t, err)
28-
assert.Len(t, users, 4)
29-
assert.ElementsMatch(t, []int64{10, 15, 16, 18}, []int64{users[0].ID, users[1].ID, users[2].ID, users[3].ID})
29+
if assert.Len(t, users, 4) {
30+
assert.ElementsMatch(t, []int64{10, 15, 16, 18}, []int64{users[0].ID, users[1].ID, users[2].ID, users[3].ID})
31+
}
32+
33+
// do not return deactivated users
34+
assert.NoError(t, user_model.UpdateUserCols(db.DefaultContext, &user_model.User{ID: 15, IsActive: false}, "is_active"))
35+
users, err = repo_model.GetRepoAssignees(db.DefaultContext, repo21)
36+
assert.NoError(t, err)
37+
if assert.Len(t, users, 3) {
38+
assert.NotContains(t, []int64{users[0].ID, users[1].ID, users[2].ID}, 15)
39+
}
3040
}
3141

3242
func TestRepoGetReviewers(t *testing.T) {
@@ -38,17 +48,19 @@ func TestRepoGetReviewers(t *testing.T) {
3848
ctx := db.DefaultContext
3949
reviewers, err := repo_model.GetReviewers(ctx, repo1, 2, 2)
4050
assert.NoError(t, err)
41-
assert.Len(t, reviewers, 4)
51+
if assert.Len(t, reviewers, 3) {
52+
assert.ElementsMatch(t, []int64{1, 4, 11}, []int64{reviewers[0].ID, reviewers[1].ID, reviewers[2].ID})
53+
}
4254

4355
// should include doer if doer is not PR poster.
4456
reviewers, err = repo_model.GetReviewers(ctx, repo1, 11, 2)
4557
assert.NoError(t, err)
46-
assert.Len(t, reviewers, 4)
58+
assert.Len(t, reviewers, 3)
4759

4860
// should not include PR poster, if PR poster would be otherwise eligible
4961
reviewers, err = repo_model.GetReviewers(ctx, repo1, 11, 4)
5062
assert.NoError(t, err)
51-
assert.Len(t, reviewers, 3)
63+
assert.Len(t, reviewers, 2)
5264

5365
// test private user repo
5466
repo2 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 2})

modules/auth/password/pwn/pwn_test.go

Lines changed: 23 additions & 76 deletions
Original file line numberDiff line numberDiff line change
@@ -4,12 +4,11 @@
44
package pwn
55

66
import (
7-
"math/rand/v2"
87
"net/http"
9-
"strings"
108
"testing"
119
"time"
1210

11+
"github.com/h2non/gock"
1312
"github.com/stretchr/testify/assert"
1413
)
1514

@@ -18,86 +17,34 @@ var client = New(WithHTTP(&http.Client{
1817
}))
1918

2019
func TestPassword(t *testing.T) {
21-
// Check input error
22-
_, err := client.CheckPassword("", false)
20+
defer gock.Off()
21+
22+
count, err := client.CheckPassword("", false)
2323
assert.ErrorIs(t, err, ErrEmptyPassword, "blank input should return ErrEmptyPassword")
24+
assert.Equal(t, -1, count)
2425

25-
// Should fail
26-
fail := "password1234"
27-
count, err := client.CheckPassword(fail, false)
28-
assert.NotEmpty(t, count, "%s should fail as a password", fail)
26+
gock.New("https://api.pwnedpasswords.com").Get("/range/5c1d8").Times(1).Reply(200).BodyString("EAF2F254732680E8AC339B84F3266ECCBB5:1\r\nFC446EB88938834178CB9322C1EE273C2A7:2")
27+
count, err = client.CheckPassword("pwned", false)
2928
assert.NoError(t, err)
29+
assert.Equal(t, 1, count)
3030

31-
// Should fail (with padding)
32-
failPad := "administrator"
33-
count, err = client.CheckPassword(failPad, true)
34-
assert.NotEmpty(t, count, "%s should fail as a password", failPad)
31+
gock.New("https://api.pwnedpasswords.com").Get("/range/ba189").Times(1).Reply(200).BodyString("FD4CB34F0378BCB15D23F6FFD28F0775C9E:3\r\nFDF342FCD8C3611DAE4D76E8A992A3E4169:4")
32+
count, err = client.CheckPassword("notpwned", false)
3533
assert.NoError(t, err)
34+
assert.Equal(t, 0, count)
3635

37-
// Checking for a "good" password isn't going to be perfect, but we can give it a good try
38-
// with hopefully minimal error. Try five times?
39-
assert.Condition(t, func() bool {
40-
for i := 0; i <= 5; i++ {
41-
count, err = client.CheckPassword(testPassword(), false)
42-
assert.NoError(t, err)
43-
if count == 0 {
44-
return true
45-
}
46-
}
47-
return false
48-
}, "no generated passwords passed. there is a chance this is a fluke")
49-
50-
// Again, but with padded responses
51-
assert.Condition(t, func() bool {
52-
for i := 0; i <= 5; i++ {
53-
count, err = client.CheckPassword(testPassword(), true)
54-
assert.NoError(t, err)
55-
if count == 0 {
56-
return true
57-
}
58-
}
59-
return false
60-
}, "no generated passwords passed. there is a chance this is a fluke")
61-
}
62-
63-
// Credit to https://golangbyexample.com/generate-random-password-golang/
64-
// DO NOT USE THIS FOR AN ACTUAL PASSWORD GENERATOR
65-
var (
66-
lowerCharSet = "abcdedfghijklmnopqrst"
67-
upperCharSet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
68-
specialCharSet = "!@#$%&*"
69-
numberSet = "0123456789"
70-
allCharSet = lowerCharSet + upperCharSet + specialCharSet + numberSet
71-
)
72-
73-
func testPassword() string {
74-
var password strings.Builder
75-
76-
// Set special character
77-
for i := 0; i < 5; i++ {
78-
random := rand.IntN(len(specialCharSet))
79-
password.WriteString(string(specialCharSet[random]))
80-
}
81-
82-
// Set numeric
83-
for i := 0; i < 5; i++ {
84-
random := rand.IntN(len(numberSet))
85-
password.WriteString(string(numberSet[random]))
86-
}
36+
gock.New("https://api.pwnedpasswords.com").Get("/range/a1733").Times(1).Reply(200).BodyString("C4CE0F1F0062B27B9E2F41AF0C08218017C:1\r\nFC446EB88938834178CB9322C1EE273C2A7:2\r\nFE81480327C992FE62065A827429DD1318B:0")
37+
count, err = client.CheckPassword("paddedpwned", true)
38+
assert.NoError(t, err)
39+
assert.Equal(t, 1, count)
8740

88-
// Set uppercase
89-
for i := 0; i < 5; i++ {
90-
random := rand.IntN(len(upperCharSet))
91-
password.WriteString(string(upperCharSet[random]))
92-
}
41+
gock.New("https://api.pwnedpasswords.com").Get("/range/5617b").Times(1).Reply(200).BodyString("FD4CB34F0378BCB15D23F6FFD28F0775C9E:3\r\nFDF342FCD8C3611DAE4D76E8A992A3E4169:4\r\nFE81480327C992FE62065A827429DD1318B:0")
42+
count, err = client.CheckPassword("paddednotpwned", true)
43+
assert.NoError(t, err)
44+
assert.Equal(t, 0, count)
9345

94-
for i := 0; i < 5; i++ {
95-
random := rand.IntN(len(allCharSet))
96-
password.WriteString(string(allCharSet[random]))
97-
}
98-
inRune := []rune(password.String())
99-
rand.Shuffle(len(inRune), func(i, j int) {
100-
inRune[i], inRune[j] = inRune[j], inRune[i]
101-
})
102-
return string(inRune)
46+
gock.New("https://api.pwnedpasswords.com").Get("/range/79082").Times(1).Reply(200).BodyString("FDF342FCD8C3611DAE4D76E8A992A3E4169:4\r\nFE81480327C992FE62065A827429DD1318B:0\r\nAFEF386F56EB0B4BE314E07696E5E6E6536:0")
47+
count, err = client.CheckPassword("paddednotpwnedzero", true)
48+
assert.NoError(t, err)
49+
assert.Equal(t, 0, count)
10350
}

0 commit comments

Comments
 (0)