Skip to content

Commit c5a32f4

Browse files
committed
revert and fix
1 parent d4d98ad commit c5a32f4

File tree

11 files changed

+56
-161
lines changed

11 files changed

+56
-161
lines changed

models/auth/webauthn.go

Lines changed: 10 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -9,8 +9,6 @@ import (
99
"strings"
1010

1111
"code.gitea.io/gitea/models/db"
12-
"code.gitea.io/gitea/modules/json"
13-
"code.gitea.io/gitea/modules/log"
1412
"code.gitea.io/gitea/modules/timeutil"
1513
"code.gitea.io/gitea/modules/util"
1614

@@ -52,7 +50,6 @@ type WebAuthnCredential struct {
5250
PublicKey []byte
5351
AttestationType string
5452
AAGUID []byte
55-
CredentialFlags string `xorm:"TEXT"`
5653
SignCount uint32 `xorm:"BIGINT"`
5754
CloneWarning bool
5855
CreatedUnix timeutil.TimeStamp `xorm:"INDEX created"`
@@ -96,14 +93,6 @@ type WebAuthnCredentialList []*WebAuthnCredential
9693
func (list WebAuthnCredentialList) ToCredentials() []webauthn.Credential {
9794
creds := make([]webauthn.Credential, 0, len(list))
9895
for _, cred := range list {
99-
var flags webauthn.CredentialFlags
100-
if cred.CredentialFlags != "" {
101-
err := json.Unmarshal([]byte(cred.CredentialFlags), &flags)
102-
if err != nil {
103-
log.Error("Failed to unmarshal CredentialFlags, webauthn credential id:%d, err:%v", cred.ID, err)
104-
continue
105-
}
106-
}
10796
creds = append(creds, webauthn.Credential{
10897
ID: cred.CredentialID,
10998
PublicKey: cred.PublicKey,
@@ -113,7 +102,6 @@ func (list WebAuthnCredentialList) ToCredentials() []webauthn.Credential {
113102
SignCount: cred.SignCount,
114103
CloneWarning: cred.CloneWarning,
115104
},
116-
Flags: flags,
117105
})
118106
}
119107
return creds
@@ -170,18 +158,13 @@ func GetWebAuthnCredentialByCredID(ctx context.Context, userID int64, credID []b
170158

171159
// CreateCredential will create a new WebAuthnCredential from the given Credential
172160
func CreateCredential(ctx context.Context, userID int64, name string, cred *webauthn.Credential) (*WebAuthnCredential, error) {
173-
flagsJSON, err := json.Marshal(cred.Flags)
174-
if err != nil {
175-
return nil, err
176-
}
177161
c := &WebAuthnCredential{
178162
UserID: userID,
179163
Name: name,
180164
CredentialID: cred.ID,
181165
PublicKey: cred.PublicKey,
182166
AttestationType: cred.AttestationType,
183167
AAGUID: cred.Authenticator.AAGUID,
184-
CredentialFlags: string(flagsJSON),
185168
SignCount: cred.Authenticator.SignCount,
186169
CloneWarning: false,
187170
}
@@ -197,3 +180,13 @@ func DeleteCredential(ctx context.Context, id, userID int64) (bool, error) {
197180
had, err := db.GetEngine(ctx).ID(id).Where("user_id = ?", userID).Delete(&WebAuthnCredential{})
198181
return had > 0, err
199182
}
183+
184+
// WebAuthnCredentials implements the webauthn.User interface
185+
func WebAuthnCredentials(ctx context.Context, userID int64) ([]webauthn.Credential, error) {
186+
dbCreds, err := GetWebAuthnCredentialsByUID(ctx, userID)
187+
if err != nil {
188+
return nil, err
189+
}
190+
191+
return dbCreds.ToCredentials(), nil
192+
}

models/auth/webauthn_test.go

Lines changed: 2 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -58,24 +58,10 @@ func TestWebAuthnCredential_UpdateLargeCounter(t *testing.T) {
5858
func TestCreateCredential(t *testing.T) {
5959
assert.NoError(t, unittest.PrepareTestDatabase())
6060

61-
flags := webauthn.CredentialFlags{
62-
UserPresent: true,
63-
UserVerified: true,
64-
BackupEligible: true,
65-
BackupState: true,
66-
}
67-
res, err := auth_model.CreateCredential(db.DefaultContext, 1, "WebAuthn Created Credential", &webauthn.Credential{
68-
ID: []byte("Test"),
69-
Flags: flags,
70-
})
61+
res, err := auth_model.CreateCredential(db.DefaultContext, 1, "WebAuthn Created Credential", &webauthn.Credential{ID: []byte("Test")})
7162
assert.NoError(t, err)
7263
assert.Equal(t, "WebAuthn Created Credential", res.Name)
7364
assert.Equal(t, []byte("Test"), res.CredentialID)
7465

75-
webauthnUser1 := unittest.AssertExistsAndLoadBean(t, &auth_model.WebAuthnCredential{UserID: 1})
76-
assert.Equal(t, "WebAuthn Created Credential", webauthnUser1.Name)
77-
assert.Equal(t, []byte("Test"), webauthnUser1.CredentialID)
78-
79-
credList := auth_model.WebAuthnCredentialList{webauthnUser1}.ToCredentials()
80-
assert.Equal(t, flags, credList[0].Flags)
66+
unittest.AssertExistsIf(t, true, &auth_model.WebAuthnCredential{Name: "WebAuthn Created Credential", UserID: 1})
8167
}

models/migrations/migrations.go

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -367,7 +367,6 @@ func prepareMigrationTasks() []*migration {
367367
newMigration(307, "Fix milestone deadline_unix when there is no due date", v1_23.FixMilestoneNoDueDate),
368368
newMigration(308, "Add index(user_id, is_deleted) for action table", v1_23.AddNewIndexForUserDashboard),
369369
newMigration(309, "Improve Notification table indices", v1_23.ImproveNotificationTableIndices),
370-
newMigration(310, "Add flags on table webauthn_credential", v1_23.AddFlagsOnWebAuthnCredential),
371370
}
372371
return preparedMigrations
373372
}

models/migrations/v1_23/v310.go

Lines changed: 0 additions & 35 deletions
This file was deleted.

models/migrations/v1_23/v310_test.go

Lines changed: 0 additions & 53 deletions
This file was deleted.

modules/auth/webauthn/webauthn.go

Lines changed: 21 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -4,13 +4,14 @@
44
package webauthn
55

66
import (
7+
"context"
78
"encoding/binary"
89
"encoding/gob"
910

1011
"code.gitea.io/gitea/models/auth"
11-
"code.gitea.io/gitea/models/db"
1212
user_model "code.gitea.io/gitea/models/user"
1313
"code.gitea.io/gitea/modules/setting"
14+
"code.gitea.io/gitea/modules/util"
1415

1516
"github.com/go-webauthn/webauthn/protocol"
1617
"github.com/go-webauthn/webauthn/webauthn"
@@ -38,40 +39,40 @@ func Init() {
3839
}
3940
}
4041

41-
// User represents an implementation of webauthn.User based on User model
42-
type User user_model.User
42+
// user represents an implementation of webauthn.User based on User model
43+
type user struct {
44+
ctx context.Context
45+
User *user_model.User
46+
}
47+
48+
var _ webauthn.User = (*user)(nil)
49+
50+
func NewWebAuthnUser(ctx context.Context, u *user_model.User) webauthn.User {
51+
return &user{ctx: ctx, User: u}
52+
}
4353

4454
// WebAuthnID implements the webauthn.User interface
45-
func (u *User) WebAuthnID() []byte {
55+
func (u *user) WebAuthnID() []byte {
4656
id := make([]byte, 8)
47-
binary.PutVarint(id, u.ID)
57+
binary.PutVarint(id, u.User.ID)
4858
return id
4959
}
5060

5161
// WebAuthnName implements the webauthn.User interface
52-
func (u *User) WebAuthnName() string {
53-
if u.LoginName == "" {
54-
return u.Name
55-
}
56-
return u.LoginName
62+
func (u *user) WebAuthnName() string {
63+
return util.IfZero(u.User.LoginName, u.User.Name)
5764
}
5865

5966
// WebAuthnDisplayName implements the webauthn.User interface
60-
func (u *User) WebAuthnDisplayName() string {
61-
return (*user_model.User)(u).DisplayName()
62-
}
63-
64-
// WebAuthnIcon implements the webauthn.User interface
65-
func (u *User) WebAuthnIcon() string {
66-
return (*user_model.User)(u).AvatarLink(db.DefaultContext)
67+
func (u *user) WebAuthnDisplayName() string {
68+
return u.User.DisplayName()
6769
}
6870

6971
// WebAuthnCredentials implements the webauthn.User interface
70-
func (u *User) WebAuthnCredentials() []webauthn.Credential {
71-
dbCreds, err := auth.GetWebAuthnCredentialsByUID(db.DefaultContext, u.ID)
72+
func (u *user) WebAuthnCredentials() []webauthn.Credential {
73+
dbCreds, err := auth.GetWebAuthnCredentialsByUID(u.ctx, u.User.ID)
7274
if err != nil {
7375
return nil
7476
}
75-
7677
return dbCreds.ToCredentials()
7778
}

routers/web/auth/webauthn.go

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -89,7 +89,7 @@ func WebAuthnPasskeyLogin(ctx *context.Context) {
8989
return nil, err
9090
}
9191

92-
return (*wa.User)(user), nil
92+
return wa.NewWebAuthnUser(ctx, user), nil
9393
}, *sessionData, ctx.Req)
9494
if err != nil {
9595
// Failed authentication attempt.
@@ -171,7 +171,8 @@ func WebAuthnLoginAssertion(ctx *context.Context) {
171171
return
172172
}
173173

174-
assertion, sessionData, err := wa.WebAuthn.BeginLogin((*wa.User)(user))
174+
webAuthnUser := wa.NewWebAuthnUser(ctx, user)
175+
assertion, sessionData, err := wa.WebAuthn.BeginLogin(webAuthnUser)
175176
if err != nil {
176177
ctx.ServerError("webauthn.BeginLogin", err)
177178
return
@@ -216,7 +217,8 @@ func WebAuthnLoginAssertionPost(ctx *context.Context) {
216217
}
217218

218219
// Validate the parsed response.
219-
cred, err := wa.WebAuthn.ValidateLogin((*wa.User)(user), *sessionData, parsedResponse)
220+
webAuthnUser := wa.NewWebAuthnUser(ctx, user)
221+
cred, err := wa.WebAuthn.ValidateLogin(webAuthnUser, *sessionData, parsedResponse)
220222
if err != nil {
221223
// Failed authentication attempt.
222224
log.Info("Failed authentication attempt for %s from %s: %v", user.Name, ctx.RemoteAddr(), err)

routers/web/user/setting/security/webauthn.go

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -51,7 +51,8 @@ func WebAuthnRegister(ctx *context.Context) {
5151
return
5252
}
5353

54-
credentialOptions, sessionData, err := wa.WebAuthn.BeginRegistration((*wa.User)(ctx.Doer), webauthn.WithAuthenticatorSelection(protocol.AuthenticatorSelection{
54+
webAuthnUser := wa.NewWebAuthnUser(ctx, ctx.Doer)
55+
credentialOptions, sessionData, err := wa.WebAuthn.BeginRegistration(webAuthnUser, webauthn.WithAuthenticatorSelection(protocol.AuthenticatorSelection{
5556
ResidentKey: protocol.ResidentKeyRequirementRequired,
5657
}))
5758
if err != nil {
@@ -92,7 +93,8 @@ func WebauthnRegisterPost(ctx *context.Context) {
9293
}()
9394

9495
// Verify that the challenge succeeded
95-
cred, err := wa.WebAuthn.FinishRegistration((*wa.User)(ctx.Doer), *sessionData, ctx.Req)
96+
webAuthnUser := wa.NewWebAuthnUser(ctx, ctx.Doer)
97+
cred, err := wa.WebAuthn.FinishRegistration(webAuthnUser, *sessionData, ctx.Req)
9698
if err != nil {
9799
if pErr, ok := err.(*protocol.Error); ok {
98100
log.Error("Unable to finish registration due to error: %v\nDevInfo: %s", pErr, pErr.DevInfo)

web_src/js/features/user-auth-webauthn.ts

Lines changed: 11 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -40,14 +40,15 @@ async function loginPasskey() {
4040
try {
4141
const credential = await navigator.credentials.get({
4242
publicKey: options.publicKey,
43-
});
43+
}) as PublicKeyCredential;
44+
const credResp = credential.response as AuthenticatorAssertionResponse;
4445

4546
// Move data into Arrays in case it is super long
46-
const authData = new Uint8Array(credential.response.authenticatorData);
47-
const clientDataJSON = new Uint8Array(credential.response.clientDataJSON);
47+
const authData = new Uint8Array(credResp.authenticatorData);
48+
const clientDataJSON = new Uint8Array(credResp.clientDataJSON);
4849
const rawId = new Uint8Array(credential.rawId);
49-
const sig = new Uint8Array(credential.response.signature);
50-
const userHandle = new Uint8Array(credential.response.userHandle);
50+
const sig = new Uint8Array(credResp.signature);
51+
const userHandle = new Uint8Array(credResp.userHandle);
5152

5253
const res = await POST(`${appSubUrl}/user/webauthn/passkey/login`, {
5354
data: {
@@ -175,7 +176,7 @@ async function webauthnRegistered(newCredential) {
175176
window.location.reload();
176177
}
177178

178-
function webAuthnError(errorType, message) {
179+
function webAuthnError(errorType: string, message:string = '') {
179180
const elErrorMsg = document.querySelector(`#webauthn-error-msg`);
180181

181182
if (errorType === 'general') {
@@ -207,10 +208,9 @@ function detectWebAuthnSupport() {
207208
}
208209

209210
export function initUserAuthWebAuthnRegister() {
210-
const elRegister = document.querySelector('#register-webauthn');
211-
if (!elRegister) {
212-
return;
213-
}
211+
const elRegister = document.querySelector<HTMLInputElement>('#register-webauthn');
212+
if (!elRegister) return;
213+
214214
if (!detectWebAuthnSupport()) {
215215
elRegister.disabled = true;
216216
return;
@@ -222,7 +222,7 @@ export function initUserAuthWebAuthnRegister() {
222222
}
223223

224224
async function webAuthnRegisterRequest() {
225-
const elNickname = document.querySelector('#nickname');
225+
const elNickname = document.querySelector<HTMLInputElement>('#nickname');
226226

227227
const formData = new FormData();
228228
formData.append('name', elNickname.value);

web_src/js/modules/fetch.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import {isObject} from '../utils.ts';
2-
import type {RequestData, RequestOpts} from '../types.ts';
2+
import type {RequestOpts} from '../types.ts';
33

44
const {csrfToken} = window.config;
55

@@ -10,7 +10,7 @@ const safeMethods = new Set(['GET', 'HEAD', 'OPTIONS', 'TRACE']);
1010
// which will automatically set an appropriate headers. For json content, only object
1111
// and array types are currently supported.
1212
export function request(url: string, {method = 'GET', data, headers = {}, ...other}: RequestOpts = {}): Promise<Response> {
13-
let body: RequestData;
13+
let body: string | FormData | URLSearchParams;
1414
let contentType: string;
1515
if (data instanceof FormData || data instanceof URLSearchParams) {
1616
body = data;

0 commit comments

Comments
 (0)