Skip to content

Commit 87bb5ed

Browse files
hiifongwxiaoguang
andauthored
Fix: passkey login not working anymore (#32623)
Quick fix #32595, use authenticator auth flags to login --------- Co-authored-by: wxiaoguang <[email protected]>
1 parent 0f4b0cf commit 87bb5ed

File tree

9 files changed

+86
-47
lines changed

9 files changed

+86
-47
lines changed

models/auth/webauthn.go

+21-1
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ import (
1212
"code.gitea.io/gitea/modules/timeutil"
1313
"code.gitea.io/gitea/modules/util"
1414

15+
"github.com/go-webauthn/webauthn/protocol"
1516
"github.com/go-webauthn/webauthn/webauthn"
1617
)
1718

@@ -89,14 +90,33 @@ func (cred *WebAuthnCredential) AfterLoad() {
8990
// WebAuthnCredentialList is a list of *WebAuthnCredential
9091
type WebAuthnCredentialList []*WebAuthnCredential
9192

93+
// newCredentialFlagsFromAuthenticatorFlags is copied from https://github.com/go-webauthn/webauthn/pull/337
94+
// to convert protocol.AuthenticatorFlags to webauthn.CredentialFlags
95+
func newCredentialFlagsFromAuthenticatorFlags(flags protocol.AuthenticatorFlags) webauthn.CredentialFlags {
96+
return webauthn.CredentialFlags{
97+
UserPresent: flags.HasUserPresent(),
98+
UserVerified: flags.HasUserVerified(),
99+
BackupEligible: flags.HasBackupEligible(),
100+
BackupState: flags.HasBackupState(),
101+
}
102+
}
103+
92104
// ToCredentials will convert all WebAuthnCredentials to webauthn.Credentials
93-
func (list WebAuthnCredentialList) ToCredentials() []webauthn.Credential {
105+
func (list WebAuthnCredentialList) ToCredentials(defaultAuthFlags ...protocol.AuthenticatorFlags) []webauthn.Credential {
106+
// TODO: at the moment, Gitea doesn't store or check the flags
107+
// so we need to use the default flags from the authenticator to make the login validation pass
108+
// In the future, we should:
109+
// 1. store the flags when registering the credential
110+
// 2. provide the stored flags when converting the credentials (for login)
111+
// 3. for old users, still use this fallback to the default flags
112+
defAuthFlags := util.OptionalArg(defaultAuthFlags)
94113
creds := make([]webauthn.Credential, 0, len(list))
95114
for _, cred := range list {
96115
creds = append(creds, webauthn.Credential{
97116
ID: cred.CredentialID,
98117
PublicKey: cred.PublicKey,
99118
AttestationType: cred.AttestationType,
119+
Flags: newCredentialFlagsFromAuthenticatorFlags(defAuthFlags),
100120
Authenticator: webauthn.Authenticator{
101121
AAGUID: cred.AAGUID,
102122
SignCount: cred.SignCount,

models/db/engine.go

+3
Original file line numberDiff line numberDiff line change
@@ -134,6 +134,9 @@ func SyncAllTables() error {
134134
func InitEngine(ctx context.Context) error {
135135
xormEngine, err := newXORMEngine()
136136
if err != nil {
137+
if strings.Contains(err.Error(), "SQLite3 support") {
138+
return fmt.Errorf(`sqlite3 requires: -tags sqlite,sqlite_unlock_notify%s%w`, "\n", err)
139+
}
137140
return fmt.Errorf("failed to connect to database: %w", err)
138141
}
139142

models/migrations/base/tests.go

+4-4
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ import (
1818
"code.gitea.io/gitea/modules/setting"
1919
"code.gitea.io/gitea/modules/testlogger"
2020

21-
"github.com/stretchr/testify/assert"
21+
"github.com/stretchr/testify/require"
2222
"xorm.io/xorm"
2323
)
2424

@@ -33,15 +33,15 @@ func PrepareTestEnv(t *testing.T, skip int, syncModels ...any) (*xorm.Engine, fu
3333
ourSkip := 2
3434
ourSkip += skip
3535
deferFn := testlogger.PrintCurrentTest(t, ourSkip)
36-
assert.NoError(t, unittest.SyncDirs(filepath.Join(filepath.Dir(setting.AppPath), "tests/gitea-repositories-meta"), setting.RepoRootPath))
36+
require.NoError(t, unittest.SyncDirs(filepath.Join(filepath.Dir(setting.AppPath), "tests/gitea-repositories-meta"), setting.RepoRootPath))
3737

3838
if err := deleteDB(); err != nil {
39-
t.Errorf("unable to reset database: %v", err)
39+
t.Fatalf("unable to reset database: %v", err)
4040
return nil, deferFn
4141
}
4242

4343
x, err := newXORMEngine()
44-
assert.NoError(t, err)
44+
require.NoError(t, err)
4545
if x != nil {
4646
oldDefer := deferFn
4747
deferFn = func() {

modules/auth/webauthn/webauthn.go

+24-21
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,42 @@ 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+
defaultAuthFlags protocol.AuthenticatorFlags
48+
}
49+
50+
var _ webauthn.User = (*user)(nil)
51+
52+
func NewWebAuthnUser(ctx context.Context, u *user_model.User, defaultAuthFlags ...protocol.AuthenticatorFlags) webauthn.User {
53+
return &user{ctx: ctx, User: u, defaultAuthFlags: util.OptionalArg(defaultAuthFlags)}
54+
}
4355

4456
// WebAuthnID implements the webauthn.User interface
45-
func (u *User) WebAuthnID() []byte {
57+
func (u *user) WebAuthnID() []byte {
4658
id := make([]byte, 8)
47-
binary.PutVarint(id, u.ID)
59+
binary.PutVarint(id, u.User.ID)
4860
return id
4961
}
5062

5163
// 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
64+
func (u *user) WebAuthnName() string {
65+
return util.IfZero(u.User.LoginName, u.User.Name)
5766
}
5867

5968
// 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)
69+
func (u *user) WebAuthnDisplayName() string {
70+
return u.User.DisplayName()
6771
}
6872

6973
// WebAuthnCredentials implements the webauthn.User interface
70-
func (u *User) WebAuthnCredentials() []webauthn.Credential {
71-
dbCreds, err := auth.GetWebAuthnCredentialsByUID(db.DefaultContext, u.ID)
74+
func (u *user) WebAuthnCredentials() []webauthn.Credential {
75+
dbCreds, err := auth.GetWebAuthnCredentialsByUID(u.ctx, u.User.ID)
7276
if err != nil {
7377
return nil
7478
}
75-
76-
return dbCreds.ToCredentials()
79+
return dbCreds.ToCredentials(u.defaultAuthFlags)
7780
}

routers/web/auth/webauthn.go

+16-5
Original file line numberDiff line numberDiff line change
@@ -76,8 +76,17 @@ func WebAuthnPasskeyLogin(ctx *context.Context) {
7676
}()
7777

7878
// Validate the parsed response.
79+
80+
// ParseCredentialRequestResponse+ValidateDiscoverableLogin equals to FinishDiscoverableLogin, but we need to ParseCredentialRequestResponse first to get flags
7981
var user *user_model.User
80-
cred, err := wa.WebAuthn.FinishDiscoverableLogin(func(rawID, userHandle []byte) (webauthn.User, error) {
82+
parsedResponse, err := protocol.ParseCredentialRequestResponse(ctx.Req)
83+
if err != nil {
84+
// Failed authentication attempt.
85+
log.Info("Failed authentication attempt for %s from %s: %v", user.Name, ctx.RemoteAddr(), err)
86+
ctx.Status(http.StatusForbidden)
87+
return
88+
}
89+
cred, err := wa.WebAuthn.ValidateDiscoverableLogin(func(rawID, userHandle []byte) (webauthn.User, error) {
8190
userID, n := binary.Varint(userHandle)
8291
if n <= 0 {
8392
return nil, errors.New("invalid rawID")
@@ -89,8 +98,8 @@ func WebAuthnPasskeyLogin(ctx *context.Context) {
8998
return nil, err
9099
}
91100

92-
return (*wa.User)(user), nil
93-
}, *sessionData, ctx.Req)
101+
return wa.NewWebAuthnUser(ctx, user, parsedResponse.Response.AuthenticatorData.Flags), nil
102+
}, *sessionData, parsedResponse)
94103
if err != nil {
95104
// Failed authentication attempt.
96105
log.Info("Failed authentication attempt for passkey from %s: %v", ctx.RemoteAddr(), err)
@@ -171,7 +180,8 @@ func WebAuthnLoginAssertion(ctx *context.Context) {
171180
return
172181
}
173182

174-
assertion, sessionData, err := wa.WebAuthn.BeginLogin((*wa.User)(user))
183+
webAuthnUser := wa.NewWebAuthnUser(ctx, user)
184+
assertion, sessionData, err := wa.WebAuthn.BeginLogin(webAuthnUser)
175185
if err != nil {
176186
ctx.ServerError("webauthn.BeginLogin", err)
177187
return
@@ -216,7 +226,8 @@ func WebAuthnLoginAssertionPost(ctx *context.Context) {
216226
}
217227

218228
// Validate the parsed response.
219-
cred, err := wa.WebAuthn.ValidateLogin((*wa.User)(user), *sessionData, parsedResponse)
229+
webAuthnUser := wa.NewWebAuthnUser(ctx, user, parsedResponse.Response.AuthenticatorData.Flags)
230+
cred, err := wa.WebAuthn.ValidateLogin(webAuthnUser, *sessionData, parsedResponse)
220231
if err != nil {
221232
// Failed authentication attempt.
222233
log.Info("Failed authentication attempt for %s from %s: %v", user.Name, ctx.RemoteAddr(), err)

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

+4-2
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

+11-11
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

+2-2
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;

web_src/js/types.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ export type Config = {
2424

2525
export type Intent = 'error' | 'warning' | 'info';
2626

27-
export type RequestData = string | FormData | URLSearchParams;
27+
export type RequestData = string | FormData | URLSearchParams | Record<string, any>;
2828

2929
export type RequestOpts = {
3030
data?: RequestData,

0 commit comments

Comments
 (0)