webauthn

package
v5.0.3 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 2, 2026 License: Apache-2.0 Imports: 15 Imported by: 0

Documentation

Overview

Package webauthn wraps go-webauthn/webauthn to provide WebAuthn/FIDO2 passkey ceremony helpers. It imports the core auth package for types but never the reverse.

Index

Constants

View Source
const CeremonyTimeout = 5 * time.Minute

CeremonyTimeout is the maximum duration a user has to complete an auth ceremony.

Variables

View Source
var ErrNotDiscoverable = errors.New("auth/webauthn: authenticator did not create a discoverable credential")

ErrNotDiscoverable reports a registration whose client stated the new credential is not client-side discoverable. Matchable with errors.Is so a caller can tell it apart from a verification failure and tell the user their authenticator cannot store a passkey.

View Source
var ErrUnknownCredential = errors.New("auth/webauthn: the asserted credential is not registered")

ErrUnknownCredential reports a login whose asserted credential this relying party has no record of, which is what a passkey deleted server-side looks like from the client's side. Matchable with errors.Is, so a caller can tell it apart from a verification failure and signal the client to forget the stale passkey rather than telling the user their sign-in failed.

It is a translation of the upstream condition, not a wrapper around it: the upstream error is deliberately NOT in this error's chain, so a caller cannot reach go-webauthn's type through it and grow a dependency on this package's internals. A test pins that.

View Source
var KnownAAGUIDs = []AAGUIDEntry{
	{"ea9b8d66-4d01-1d21-3ce4-b6b48cb575d4", "Google Password Manager"},
	{aaguidChromeOnMac, credNameChromeOnMac},
	{"08987058-cadc-4b81-b6e1-30de50dcbe96", credNameWindowsHello},
	{"9ddd1817-af5a-4672-a2b9-3e3dd95000a9", credNameWindowsHello},
	{"6028b017-b1d4-4c02-b4b3-afcdafc96bb2", credNameWindowsHello},
	{"dd4ec289-e01d-41c9-bb89-70fa845d4bf2", "iCloud Keychain"},
	{"fbfc3007-154e-4ecc-8c0b-6e020557d7bd", "iCloud Keychain"},
	{"d548826e-79b4-db40-a3d8-11116f7e8349", "Bitwarden"},
	{"b5397723-31d4-4c13-b037-37be46e30e9e", "1Password"},
	{"bada5566-a7aa-401f-bd96-45619a55120d", "1Password"},
	{"2fc0579f-8113-47ea-b116-bb5a8db9202a", "YubiKey 5"},
	{"fa2b99dc-9e39-4257-8f92-4a30d23c4118", "YubiKey 5 NFC"},
}

KnownAAGUIDs is the registry of known authenticator AAGUIDs.

Functions

func BeginConditionalLogin

func BeginConditionalLogin(rp *RelyingParty) (*CredentialAssertion, Ceremony, error)

BeginConditionalLogin starts a WebAuthn assertion ceremony with conditional mediation, enabling browser autofill UI for passkeys.

func BeginLogin

func BeginLogin(rp *RelyingParty) (*CredentialAssertion, Ceremony, error)

BeginLogin starts a WebAuthn assertion ceremony (discoverable login).

func BeginRegistration

func BeginRegistration(rp *RelyingParty, user *User) (*CredentialCreation, Ceremony, error)

BeginRegistration starts a WebAuthn registration ceremony.

The credential parameters offer the three ML-DSA parameter sets ahead of EdDSA, ES256 and RS256, so an authenticator that implements a post-quantum algorithm produces a post-quantum credential and every authenticator in current use still registers on a classical one. Verifying an ML-DSA signature needs Go 1.27, which this module already requires.

func CompleteLogin

func CompleteLogin(ctx context.Context, rp *RelyingParty, store Store, ceremony Ceremony, r *http.Request) (*auth.User, error)

CompleteLogin completes a discoverable (passkey) login ceremony against the store: it resolves the asserting user and registered credentials from the assertion's user handle, verifies the assertion response, and persists the post-login credential custody (sign count and authenticator flags, the cloned-authenticator detection state).

The custody write is best-effort: a store failure is logged at Warn and does not fail the login (sign-count bookkeeping is clone *detection*, not part of assertion verification). The returned user is the account as stored — the caller owns account-status policy and MUST check User.Enabled (and any app-specific state) before creating a session. A ceremony failure caused by a credential deleted server-side surfaces as a wrapped protocol.ErrorUnknownCredential, matchable with errors.As so callers can signal the client to forget the stale passkey.

func FinishRegistration

func FinishRegistration(rp *RelyingParty, user *User, ceremony Ceremony, response *http.Request) (*auth.PasskeyCredential, error)

FinishRegistration completes a WebAuthn registration ceremony.

A credential the client reports as non-discoverable is rejected with ErrNotDiscoverable instead of being returned for storage. BeginLogin and BeginConditionalLogin are discoverable ceremonies, so such a credential can never complete a login: storing it gives the user a passkey in their list that fails every time they select it. The check reads the typed credProps output BeginRegistration requests, and an authenticator that reports nothing is accepted, because absence is not a denial.

func PasskeyFriendlyName

func PasskeyFriendlyName(aaguid []byte, existingNames []string) string

PasskeyFriendlyName returns a display-only, human-friendly label for a newly registered passkey, chosen so it does not duplicate any entry in existingNames (the user's current passkey labels). A known authenticator (matched by AAGUID) gets its bare registry name for the first of its kind (e.g. "Chrome on Mac") and a numbered name for each subsequent one ("Chrome on Mac 2", ...); an unknown authenticator is always numbered ("Passkey 1", "Passkey 2", ...). The numeric suffix is one past the highest already in use, so deleting a passkey that leaves a numbering gap never yields a duplicate label.

Types

type AAGUIDEntry

type AAGUIDEntry struct {
	UUID string
	Name string
}

AAGUIDEntry maps an authenticator AAGUID to a friendly name.

type AttestationStatementFormat

type AttestationStatementFormat string

AttestationStatementFormat is an attestation statement format identifier the relying party will accept.

const (
	AttestationFormatPacked           AttestationStatementFormat = "packed"
	AttestationFormatTPM              AttestationStatementFormat = "tpm"
	AttestationFormatAndroidKey       AttestationStatementFormat = "android-key"
	AttestationFormatAndroidSafetyNet AttestationStatementFormat = "android-safetynet"
	AttestationFormatFIDOU2F          AttestationStatementFormat = "fido-u2f"
	AttestationFormatApple            AttestationStatementFormat = "apple"
	AttestationFormatCompound         AttestationStatementFormat = "compound"
	AttestationFormatNone             AttestationStatementFormat = "none"
)

The attestation statement formats registered by WebAuthn §8.

type AuthenticatorSelection

type AuthenticatorSelection struct {
	ResidentKey      ResidentKeyRequirement      `json:"residentKey,omitempty"`
	UserVerification UserVerificationRequirement `json:"userVerification,omitempty"`
}

AuthenticatorSelection is the relying party's criteria for which authenticators may be used (WebAuthn §5.4.4).

type AuthenticatorTransport

type AuthenticatorTransport string

AuthenticatorTransport is a transport an authenticator may be reached over. Clients must ignore a value they do not know, so this list is not exhaustive of what may arrive.

const (
	TransportUSB       AuthenticatorTransport = "usb"
	TransportNFC       AuthenticatorTransport = "nfc"
	TransportBLE       AuthenticatorTransport = "ble"
	TransportSmartCard AuthenticatorTransport = "smart-card"
	TransportHybrid    AuthenticatorTransport = "hybrid"
	TransportInternal  AuthenticatorTransport = "internal"
)

The transports defined by WebAuthn §5.8.4.

type Base64URL

type Base64URL []byte

Base64URL is a byte string that travels as unpadded base64url, the encoding every binary member of the options dictionaries uses.

func (Base64URL) MarshalJSON

func (b Base64URL) MarshalJSON() ([]byte, error)

MarshalJSON encodes the bytes as an unpadded base64url JSON string.

func (*Base64URL) UnmarshalJSON

func (b *Base64URL) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes an unpadded base64url JSON string. Padded input is accepted too, because some clients emit it.

type COSEAlgorithm

type COSEAlgorithm int

COSEAlgorithm is a COSE algorithm identifier, the value a relying party names to ask for a particular signature algorithm.

type Ceremony

type Ceremony struct {
	// contains filtered or unexported fields
}

Ceremony is the server-side state of one in-flight WebAuthn ceremony: the challenge and the parameters the matching Finish step verifies the authenticator's response against.

It is opaque and atomic. Hold it between the Begin and the Finish call without reshaping it, keep it server-side where a client cannot modify it, and discard it once the ceremony completes. A consumer's ceremony store keys it by its own opaque token; Ceremony.Expires is the only value that store needs to read.

The value is cheap to copy and every copy refers to the same ceremony, which is safe because nothing mutates one after a Begin call returns it. The zero value is not a usable ceremony and reports a zero deadline, which is why a ceremony lookup reports absence with a separate boolean rather than a nil.

func (Ceremony) Expires

func (c Ceremony) Expires() time.Time

Expires reports when the ceremony stops being verifiable. A ceremony store evicts on this rather than tracking its own creation time, so the deadline the authenticator was given and the deadline the store enforces cannot drift apart.

type ConveyancePreference

type ConveyancePreference string

ConveyancePreference is the relying party's attestation-conveyance preference. This library requests the specification's default, so it does not set the member.

const (
	ConveyanceNone       ConveyancePreference = "none"
	ConveyanceIndirect   ConveyancePreference = "indirect"
	ConveyanceDirect     ConveyancePreference = "direct"
	ConveyanceEnterprise ConveyancePreference = "enterprise"
)

The attestation-conveyance preferences defined by WebAuthn §5.4.7.

type CredentialAssertion

type CredentialAssertion struct {
	Mediation Mediation                `json:"mediation,omitempty"`
	Response  CredentialRequestOptions `json:"publicKey"`
}

CredentialAssertion is what a login ceremony hands the browser.

type CredentialCreation

type CredentialCreation struct {
	Response CredentialCreationOptions `json:"publicKey"`
}

CredentialCreation is what a registration ceremony hands the browser. The publicKey member is the name navigator.credentials.create() reads, so it is the specification yielding rather than this fleet's JSON convention breaking.

type CredentialCreationOptions

type CredentialCreationOptions struct {
	RelyingParty           RelyingPartyEntity           `json:"rp"`
	AuthenticatorSelection AuthenticatorSelection       `json:"authenticatorSelection"`
	Attestation            ConveyancePreference         `json:"attestation,omitempty"`
	User                   UserEntity                   `json:"user"`
	Challenge              Base64URL                    `json:"challenge"`
	Parameters             []CredentialParameter        `json:"pubKeyCredParams,omitempty"`
	ExcludeCredentials     []CredentialDescriptor       `json:"excludeCredentials,omitempty"`
	Hints                  []CredentialHint             `json:"hints,omitempty"`
	AttestationFormats     []AttestationStatementFormat `json:"attestationFormats,omitempty"`
	Timeout                int                          `json:"timeout,omitempty"`
	Extensions             RegistrationExtensions       `json:"extensions"`
}

CredentialCreationOptions is WebAuthn §5.4 PublicKeyCredentialCreationOptions: everything the client needs to create a credential.

type CredentialDescriptor

type CredentialDescriptor struct {
	Type       CredentialType           `json:"type"`
	ID         Base64URL                `json:"id"`
	Transports []AuthenticatorTransport `json:"transports,omitempty"`
}

CredentialDescriptor refers to an existing credential (WebAuthn §5.8.3). It carries only the three IDL members; upstream's equivalent also holds attestation bookkeeping that is never serialized.

type CredentialHint

type CredentialHint string

CredentialHint guides the client's user interface toward a kind of authenticator. It is a hint, so a client may ignore it.

const (
	HintSecurityKey  CredentialHint = "security-key"
	HintClientDevice CredentialHint = "client-device"
	HintHybrid       CredentialHint = "hybrid"
)

The hints defined by WebAuthn §5.8.7.

type CredentialParameter

type CredentialParameter struct {
	Type      CredentialType `json:"type"`
	Algorithm COSEAlgorithm  `json:"alg"`
}

CredentialParameter names a credential type and signature algorithm the relying party will accept (WebAuthn §5.3).

type CredentialRequestOptions

type CredentialRequestOptions struct {
	RelyingPartyID   string                      `json:"rpId,omitempty"`
	UserVerification UserVerificationRequirement `json:"userVerification,omitempty"`
	Challenge        Base64URL                   `json:"challenge"`
	AllowCredentials []CredentialDescriptor      `json:"allowCredentials,omitempty"`
	Hints            []CredentialHint            `json:"hints,omitempty"`
	Timeout          int                         `json:"timeout,omitempty"`
}

CredentialRequestOptions is WebAuthn §5.5 PublicKeyCredentialRequestOptions: everything the client needs to produce an assertion.

type CredentialType

type CredentialType string

CredentialType is the credential type of a public key credential. The specification defines exactly one value and marks the enumeration extensible.

const PublicKeyCredentialType CredentialType = "public-key"

PublicKeyCredentialType is the only credential type WebAuthn defines.

type Mediation

type Mediation string

Mediation is the credential-mediation requirement, which decides how much the client may complete a ceremony without an explicit user gesture.

const (
	MediationSilent      Mediation = "silent"
	MediationOptional    Mediation = "optional"
	MediationConditional Mediation = "conditional"
	MediationRequired    Mediation = "required"
)

The mediation requirements defined by the Credential Management specification.

type RPConfig

type RPConfig struct {
	// ID is the relying party identifier, an effective domain
	// (e.g. "example.com").
	ID string
	// DisplayName is the human-readable relying party name shown by
	// authenticators.
	DisplayName string
	// Origins are the allowed browser origins for ceremonies
	// (e.g. "https://example.com").
	Origins []string
}

RPConfig identifies the relying party that a New-constructed RelyingParty serves. The ID and display name would otherwise sit as adjacent same-typed string parameters, where a silent swap ships a broken RP ID; the field names make each value's role explicit at the call site.

type RegistrationExtensions

type RegistrationExtensions struct {
	// CredProps requests the Credential Properties extension, whose output tells
	// the relying party whether the new credential is discoverable.
	CredProps bool `json:"credProps,omitempty"`
}

RegistrationExtensions are the client extension inputs a registration requests. It carries only credProps, because that is the only extension this library requests; an extension that is not requested is never reported, so a member for one would always be false.

type RelyingParty

type RelyingParty struct {
	// contains filtered or unexported fields
}

RelyingParty is a configured relying party, and the value every ceremony function takes. It replaces the upstream handle on this package's exported surface so a consumer needs no go-webauthn import to run a ceremony; see the package documentation for why that boundary is drawn here.

Construct one with New. The zero value is not usable.

func New

func New(rp RPConfig) (*RelyingParty, error)

New creates a configured RelyingParty. An RPConfig with an empty ID is rejected here with an error naming the field: upstream go-webauthn constructs successfully without an RP ID and then fails every ceremony with an RP-hash mismatch, which defeats this wrapper's purpose of making the relying party legible at construction.

func (*RelyingParty) ID

func (rp *RelyingParty) ID() string

ID returns the relying party identifier ceremonies are bound to. A stored credential records the ID it was registered against, so comparing the two is how a relying-party rename is detected rather than silently orphaning every passkey.

type RelyingPartyEntity

type RelyingPartyEntity struct {
	// Name is the human-palatable relying party name, for display only.
	Name string `json:"name"`
	// ID is the relying party identifier, which sets the RP ID.
	ID string `json:"id"`
}

RelyingPartyEntity describes the relying party a credential is registered to (WebAuthn §5.4.2).

type ResidentKeyRequirement

type ResidentKeyRequirement string

ResidentKeyRequirement is the relying party's requirement for a client-side discoverable credential.

const (
	ResidentKeyDiscouraged ResidentKeyRequirement = "discouraged"
	ResidentKeyPreferred   ResidentKeyRequirement = "preferred"
	ResidentKeyRequired    ResidentKeyRequirement = "required"
)

The resident-key requirements defined by WebAuthn §5.4.6.

type SignalAllAcceptedCredentials

type SignalAllAcceptedCredentials struct {
	RPID                     string      `json:"rpId"`
	UserID                   Base64URL   `json:"userId"`
	AllAcceptedCredentialIDs []Base64URL `json:"allAcceptedCredentialIds"`
}

SignalAllAcceptedCredentials is the payload for the client's signalAllAcceptedCredentials call: every credential this relying party still accepts for the user.

An EMPTY list is meaningful and is not the same as sending nothing — it tells the credential manager to remove every passkey it holds for this account, which is the correct signal after the last one is deleted server-side. It therefore always serializes as a JSON array, never as null.

type SignalCurrentUserDetails

type SignalCurrentUserDetails struct {
	RPID        string    `json:"rpId"`
	Name        string    `json:"name"`
	DisplayName string    `json:"displayName"`
	UserID      Base64URL `json:"userId"`
}

SignalCurrentUserDetails is the payload for the client's signalCurrentUserDetails call: what the account is called now.

type Signals

type Signals struct {
	CurrentUserDetails     SignalCurrentUserDetails     `json:"currentUserDetails"`
	AllAcceptedCredentials SignalAllAcceptedCredentials `json:"allAcceptedCredentials"`
}

Signals carries both reconciliation payloads for one user, derived together because both are read from the same account state and a client that sends one wants the other.

func NewSignals

func NewSignals(rpID string, user *User) Signals

NewSignals derives both reconciliation payloads from a user and their stored credentials. It is pure and cannot fail: every value is read from the user, so there is no lookup to go wrong.

The display name falls back to the username when the account has none, which matches what registration put in the credential in the first place, so the signal does not blank a name the authenticator is already showing.

type Store

type Store interface {
	PasskeysByUserID(ctx context.Context, userID int64) ([]auth.PasskeyCredential, error)
	UpdatePasskeyAfterLogin(ctx context.Context, credID []byte, signCount uint32, flags auth.PasskeyFlags) error
	UserByWebAuthnHandle(ctx context.Context, handle []byte) (user *auth.User, found bool, err error)
}

Store is the narrow store interface consumed by CompleteLogin: user and credential lookup to resolve the asserting account from its user handle, and the post-login credential-custody write. A storage layer implementing auth.UserStore and auth.PasskeyStore satisfies it. Consumers composing the lower-level ceremony helpers (BeginLogin, BeginConditionalLogin) with their own user finder do not need it.

type User

type User struct {
	AuthUser    *auth.User
	Credentials []auth.PasskeyCredential
}

User adapts auth.User + credentials to the gowebauthn.User interface.

func NewUser

func NewUser(user *auth.User, creds []auth.PasskeyCredential) (*User, error)

NewUser returns a User with the given user and credentials.

func (*User) WebAuthnDisplayName

func (u *User) WebAuthnDisplayName() string

WebAuthnDisplayName returns the display name, falling back to username.

func (*User) WebAuthnID

func (u *User) WebAuthnID() []byte

WebAuthnID returns the account's stored WebAuthn user handle.

The store sets it with auth.GenerateWebAuthnHandle at account creation and never changes it; every passkey is bound to the value in force at its registration. An empty handle violates the specification's MUST NOT-be-empty rule, so a store that returns one is misconfigured.

func (*User) WebAuthnName

func (u *User) WebAuthnName() string

WebAuthnName returns the username.

type UserEntity

type UserEntity struct {
	// Name is a human-palatable account identifier, for display only.
	Name string `json:"name"`
	// DisplayName is a human-palatable name for the account holder, for display
	// only.
	DisplayName string `json:"displayName"`
	// ID is the user handle. Authentication and authorization decisions are made
	// on this value, never on the two names above.
	ID Base64URL `json:"id"`
}

UserEntity describes the user account a credential is registered to (WebAuthn §5.4.3).

type UserVerificationRequirement

type UserVerificationRequirement string

UserVerificationRequirement is the relying party's user-verification requirement for a ceremony.

const (
	VerificationRequired    UserVerificationRequirement = "required"
	VerificationPreferred   UserVerificationRequirement = "preferred"
	VerificationDiscouraged UserVerificationRequirement = "discouraged"
)

The user-verification requirements defined by WebAuthn §5.8.6.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL