Skip to content

Fix: passkey login not working anymore #32623

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 19 commits into from
Nov 26, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
revert and fix
  • Loading branch information
wxiaoguang committed Nov 26, 2024
commit c5a32f4fa462c6799a8ea5dedb5133e84e1eca1c
27 changes: 10 additions & 17 deletions models/auth/webauthn.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,6 @@ import (
"strings"

"code.gitea.io/gitea/models/db"
"code.gitea.io/gitea/modules/json"
"code.gitea.io/gitea/modules/log"
"code.gitea.io/gitea/modules/timeutil"
"code.gitea.io/gitea/modules/util"

Expand Down Expand Up @@ -52,7 +50,6 @@ type WebAuthnCredential struct {
PublicKey []byte
AttestationType string
AAGUID []byte
CredentialFlags string `xorm:"TEXT"`
SignCount uint32 `xorm:"BIGINT"`
CloneWarning bool
CreatedUnix timeutil.TimeStamp `xorm:"INDEX created"`
Expand Down Expand Up @@ -96,14 +93,6 @@ type WebAuthnCredentialList []*WebAuthnCredential
func (list WebAuthnCredentialList) ToCredentials() []webauthn.Credential {
creds := make([]webauthn.Credential, 0, len(list))
for _, cred := range list {
var flags webauthn.CredentialFlags
if cred.CredentialFlags != "" {
err := json.Unmarshal([]byte(cred.CredentialFlags), &flags)
if err != nil {
log.Error("Failed to unmarshal CredentialFlags, webauthn credential id:%d, err:%v", cred.ID, err)
continue
}
}
creds = append(creds, webauthn.Credential{
ID: cred.CredentialID,
PublicKey: cred.PublicKey,
Expand All @@ -113,7 +102,6 @@ func (list WebAuthnCredentialList) ToCredentials() []webauthn.Credential {
SignCount: cred.SignCount,
CloneWarning: cred.CloneWarning,
},
Flags: flags,
})
}
return creds
Expand Down Expand Up @@ -170,18 +158,13 @@ func GetWebAuthnCredentialByCredID(ctx context.Context, userID int64, credID []b

// CreateCredential will create a new WebAuthnCredential from the given Credential
func CreateCredential(ctx context.Context, userID int64, name string, cred *webauthn.Credential) (*WebAuthnCredential, error) {
flagsJSON, err := json.Marshal(cred.Flags)
if err != nil {
return nil, err
}
c := &WebAuthnCredential{
UserID: userID,
Name: name,
CredentialID: cred.ID,
PublicKey: cred.PublicKey,
AttestationType: cred.AttestationType,
AAGUID: cred.Authenticator.AAGUID,
CredentialFlags: string(flagsJSON),
SignCount: cred.Authenticator.SignCount,
CloneWarning: false,
}
Expand All @@ -197,3 +180,13 @@ func DeleteCredential(ctx context.Context, id, userID int64) (bool, error) {
had, err := db.GetEngine(ctx).ID(id).Where("user_id = ?", userID).Delete(&WebAuthnCredential{})
return had > 0, err
}

// WebAuthnCredentials implements the webauthn.User interface
func WebAuthnCredentials(ctx context.Context, userID int64) ([]webauthn.Credential, error) {
dbCreds, err := GetWebAuthnCredentialsByUID(ctx, userID)
if err != nil {
return nil, err
}

return dbCreds.ToCredentials(), nil
}
18 changes: 2 additions & 16 deletions models/auth/webauthn_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -58,24 +58,10 @@ func TestWebAuthnCredential_UpdateLargeCounter(t *testing.T) {
func TestCreateCredential(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())

flags := webauthn.CredentialFlags{
UserPresent: true,
UserVerified: true,
BackupEligible: true,
BackupState: true,
}
res, err := auth_model.CreateCredential(db.DefaultContext, 1, "WebAuthn Created Credential", &webauthn.Credential{
ID: []byte("Test"),
Flags: flags,
})
res, err := auth_model.CreateCredential(db.DefaultContext, 1, "WebAuthn Created Credential", &webauthn.Credential{ID: []byte("Test")})
assert.NoError(t, err)
assert.Equal(t, "WebAuthn Created Credential", res.Name)
assert.Equal(t, []byte("Test"), res.CredentialID)

webauthnUser1 := unittest.AssertExistsAndLoadBean(t, &auth_model.WebAuthnCredential{UserID: 1})
assert.Equal(t, "WebAuthn Created Credential", webauthnUser1.Name)
assert.Equal(t, []byte("Test"), webauthnUser1.CredentialID)

credList := auth_model.WebAuthnCredentialList{webauthnUser1}.ToCredentials()
assert.Equal(t, flags, credList[0].Flags)
unittest.AssertExistsIf(t, true, &auth_model.WebAuthnCredential{Name: "WebAuthn Created Credential", UserID: 1})
}
1 change: 0 additions & 1 deletion models/migrations/migrations.go
Original file line number Diff line number Diff line change
Expand Up @@ -367,7 +367,6 @@ func prepareMigrationTasks() []*migration {
newMigration(307, "Fix milestone deadline_unix when there is no due date", v1_23.FixMilestoneNoDueDate),
newMigration(308, "Add index(user_id, is_deleted) for action table", v1_23.AddNewIndexForUserDashboard),
newMigration(309, "Improve Notification table indices", v1_23.ImproveNotificationTableIndices),
newMigration(310, "Add flags on table webauthn_credential", v1_23.AddFlagsOnWebAuthnCredential),
}
return preparedMigrations
}
Expand Down
35 changes: 0 additions & 35 deletions models/migrations/v1_23/v310.go

This file was deleted.

53 changes: 0 additions & 53 deletions models/migrations/v1_23/v310_test.go

This file was deleted.

41 changes: 21 additions & 20 deletions modules/auth/webauthn/webauthn.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,14 @@
package webauthn

import (
"context"
"encoding/binary"
"encoding/gob"

"code.gitea.io/gitea/models/auth"
"code.gitea.io/gitea/models/db"
user_model "code.gitea.io/gitea/models/user"
"code.gitea.io/gitea/modules/setting"
"code.gitea.io/gitea/modules/util"

"github.com/go-webauthn/webauthn/protocol"
"github.com/go-webauthn/webauthn/webauthn"
Expand Down Expand Up @@ -38,40 +39,40 @@ func Init() {
}
}

// User represents an implementation of webauthn.User based on User model
type User user_model.User
// user represents an implementation of webauthn.User based on User model
type user struct {
ctx context.Context
User *user_model.User
}

var _ webauthn.User = (*user)(nil)

func NewWebAuthnUser(ctx context.Context, u *user_model.User) webauthn.User {
return &user{ctx: ctx, User: u}
}

// WebAuthnID implements the webauthn.User interface
func (u *User) WebAuthnID() []byte {
func (u *user) WebAuthnID() []byte {
id := make([]byte, 8)
binary.PutVarint(id, u.ID)
binary.PutVarint(id, u.User.ID)
return id
}

// WebAuthnName implements the webauthn.User interface
func (u *User) WebAuthnName() string {
if u.LoginName == "" {
return u.Name
}
return u.LoginName
func (u *user) WebAuthnName() string {
return util.IfZero(u.User.LoginName, u.User.Name)
}

// WebAuthnDisplayName implements the webauthn.User interface
func (u *User) WebAuthnDisplayName() string {
return (*user_model.User)(u).DisplayName()
}

// WebAuthnIcon implements the webauthn.User interface
func (u *User) WebAuthnIcon() string {
return (*user_model.User)(u).AvatarLink(db.DefaultContext)
func (u *user) WebAuthnDisplayName() string {
return u.User.DisplayName()
}

// WebAuthnCredentials implements the webauthn.User interface
func (u *User) WebAuthnCredentials() []webauthn.Credential {
dbCreds, err := auth.GetWebAuthnCredentialsByUID(db.DefaultContext, u.ID)
func (u *user) WebAuthnCredentials() []webauthn.Credential {
dbCreds, err := auth.GetWebAuthnCredentialsByUID(u.ctx, u.User.ID)
if err != nil {
return nil
}

return dbCreds.ToCredentials()
}
8 changes: 5 additions & 3 deletions routers/web/auth/webauthn.go
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ func WebAuthnPasskeyLogin(ctx *context.Context) {
return nil, err
}

return (*wa.User)(user), nil
return wa.NewWebAuthnUser(ctx, user), nil
}, *sessionData, ctx.Req)
if err != nil {
// Failed authentication attempt.
Expand Down Expand Up @@ -171,7 +171,8 @@ func WebAuthnLoginAssertion(ctx *context.Context) {
return
}

assertion, sessionData, err := wa.WebAuthn.BeginLogin((*wa.User)(user))
webAuthnUser := wa.NewWebAuthnUser(ctx, user)
assertion, sessionData, err := wa.WebAuthn.BeginLogin(webAuthnUser)
if err != nil {
ctx.ServerError("webauthn.BeginLogin", err)
return
Expand Down Expand Up @@ -216,7 +217,8 @@ func WebAuthnLoginAssertionPost(ctx *context.Context) {
}

// Validate the parsed response.
cred, err := wa.WebAuthn.ValidateLogin((*wa.User)(user), *sessionData, parsedResponse)
webAuthnUser := wa.NewWebAuthnUser(ctx, user)
cred, err := wa.WebAuthn.ValidateLogin(webAuthnUser, *sessionData, parsedResponse)
if err != nil {
// Failed authentication attempt.
log.Info("Failed authentication attempt for %s from %s: %v", user.Name, ctx.RemoteAddr(), err)
Expand Down
6 changes: 4 additions & 2 deletions routers/web/user/setting/security/webauthn.go
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,8 @@ func WebAuthnRegister(ctx *context.Context) {
return
}

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

// Verify that the challenge succeeded
cred, err := wa.WebAuthn.FinishRegistration((*wa.User)(ctx.Doer), *sessionData, ctx.Req)
webAuthnUser := wa.NewWebAuthnUser(ctx, ctx.Doer)
cred, err := wa.WebAuthn.FinishRegistration(webAuthnUser, *sessionData, ctx.Req)
if err != nil {
if pErr, ok := err.(*protocol.Error); ok {
log.Error("Unable to finish registration due to error: %v\nDevInfo: %s", pErr, pErr.DevInfo)
Expand Down
22 changes: 11 additions & 11 deletions web_src/js/features/user-auth-webauthn.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,14 +40,15 @@ async function loginPasskey() {
try {
const credential = await navigator.credentials.get({
publicKey: options.publicKey,
});
}) as PublicKeyCredential;
const credResp = credential.response as AuthenticatorAssertionResponse;

// Move data into Arrays in case it is super long
const authData = new Uint8Array(credential.response.authenticatorData);
const clientDataJSON = new Uint8Array(credential.response.clientDataJSON);
const authData = new Uint8Array(credResp.authenticatorData);
const clientDataJSON = new Uint8Array(credResp.clientDataJSON);
const rawId = new Uint8Array(credential.rawId);
const sig = new Uint8Array(credential.response.signature);
const userHandle = new Uint8Array(credential.response.userHandle);
const sig = new Uint8Array(credResp.signature);
const userHandle = new Uint8Array(credResp.userHandle);

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

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

if (errorType === 'general') {
Expand Down Expand Up @@ -207,10 +208,9 @@ function detectWebAuthnSupport() {
}

export function initUserAuthWebAuthnRegister() {
const elRegister = document.querySelector('#register-webauthn');
if (!elRegister) {
return;
}
const elRegister = document.querySelector<HTMLInputElement>('#register-webauthn');
if (!elRegister) return;

if (!detectWebAuthnSupport()) {
elRegister.disabled = true;
return;
Expand All @@ -222,7 +222,7 @@ export function initUserAuthWebAuthnRegister() {
}

async function webAuthnRegisterRequest() {
const elNickname = document.querySelector('#nickname');
const elNickname = document.querySelector<HTMLInputElement>('#nickname');

const formData = new FormData();
formData.append('name', elNickname.value);
Expand Down
4 changes: 2 additions & 2 deletions web_src/js/modules/fetch.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import {isObject} from '../utils.ts';
import type {RequestData, RequestOpts} from '../types.ts';
import type {RequestOpts} from '../types.ts';

const {csrfToken} = window.config;

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