Skip to content

Commit b491b21

Browse files
authored
Fix panic of ssh public key page after deletion of auth source (#31829)
Fix #31730 This PR rewrote the function `PublicKeysAreExternallyManaged` with a simple test. The new function removed the loop to make it more readable.
1 parent 86c848e commit b491b21

File tree

2 files changed

+17
-16
lines changed

2 files changed

+17
-16
lines changed

models/asymkey/ssh_key.go

Lines changed: 7 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -229,35 +229,26 @@ func UpdatePublicKeyUpdated(ctx context.Context, id int64) error {
229229

230230
// PublicKeysAreExternallyManaged returns whether the provided KeyID represents an externally managed Key
231231
func PublicKeysAreExternallyManaged(ctx context.Context, keys []*PublicKey) ([]bool, error) {
232-
sources := make([]*auth.Source, 0, 5)
232+
sourceCache := make(map[int64]*auth.Source, len(keys))
233233
externals := make([]bool, len(keys))
234-
keyloop:
234+
235235
for i, key := range keys {
236236
if key.LoginSourceID == 0 {
237237
externals[i] = false
238-
continue keyloop
239-
}
240-
241-
var source *auth.Source
242-
243-
sourceloop:
244-
for _, s := range sources {
245-
if s.ID == key.LoginSourceID {
246-
source = s
247-
break sourceloop
248-
}
238+
continue
249239
}
250240

251-
if source == nil {
241+
source, ok := sourceCache[key.LoginSourceID]
242+
if !ok {
252243
var err error
253244
source, err = auth.GetSourceByID(ctx, key.LoginSourceID)
254245
if err != nil {
255246
if auth.IsErrSourceNotExist(err) {
256247
externals[i] = false
257-
sources[i] = &auth.Source{
248+
sourceCache[key.LoginSourceID] = &auth.Source{
258249
ID: key.LoginSourceID,
259250
}
260-
continue keyloop
251+
continue
261252
}
262253
return nil, err
263254
}

models/asymkey/ssh_key_test.go

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,8 @@ import (
1212
"strings"
1313
"testing"
1414

15+
"code.gitea.io/gitea/models/db"
16+
"code.gitea.io/gitea/models/unittest"
1517
"code.gitea.io/gitea/modules/setting"
1618

1719
"github.com/42wim/sshsig"
@@ -503,3 +505,11 @@ func runErr(t *testing.T, stdin []byte, args ...string) {
503505
t.Fatal("expected error")
504506
}
505507
}
508+
509+
func Test_PublicKeysAreExternallyManaged(t *testing.T) {
510+
key1 := unittest.AssertExistsAndLoadBean(t, &PublicKey{ID: 1})
511+
externals, err := PublicKeysAreExternallyManaged(db.DefaultContext, []*PublicKey{key1})
512+
assert.NoError(t, err)
513+
assert.Len(t, externals, 1)
514+
assert.False(t, externals[0])
515+
}

0 commit comments

Comments
 (0)