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
- Variables
- func AuthenticatorName(aaguid []byte) (string, bool)
- func BeginConditionalLogin(rp *RelyingParty, origin Origin) (*CredentialAssertion, Ceremony, error)
- func BeginLogin(rp *RelyingParty, origin Origin) (*CredentialAssertion, Ceremony, error)
- func BeginRegistration(rp *RelyingParty, user *User, origin Origin) (*CredentialCreation, Ceremony, error)
- func CompleteLogin(ctx context.Context, rp *RelyingParty, store Store, ceremony Ceremony, ...) (*auth.User, error)
- func FinishRegistration(rp *RelyingParty, user *User, ceremony Ceremony, response *http.Request) (*auth.PasskeyCredential, error)
- func PasskeyFriendlyName(aaguid []byte, existingNames []string) string
- func ValidateRPID(id string) error
- type AAGUIDEntry
- type AttestationStatementFormat
- type AuthenticatorSelection
- type AuthenticatorTransport
- type Base64URL
- type COSEAlgorithm
- type Ceremony
- type ConveyancePreference
- type CredentialAssertion
- type CredentialCreation
- type CredentialCreationOptions
- type CredentialDescriptor
- type CredentialHint
- type CredentialParameter
- type CredentialRequestOptions
- type CredentialType
- type Mediation
- type Origin
- type OriginError
- type OriginRejection
- type OriginsError
- type RPConfig
- type RegistrationExtensions
- type RelyingParty
- type RelyingPartyEntity
- type ResidentKeyRequirement
- type SignalAllAcceptedCredentials
- type SignalCurrentUserDetails
- type Signals
- type Store
- type User
- type UserEntity
- type UserVerificationRequirement
Constants ¶
const CeremonyTimeout = 5 * time.Minute
CeremonyTimeout is the maximum duration a user has to complete an auth ceremony.
Variables ¶
var ErrCeremonyUnbound = errors.New("auth/webauthn: the ceremony is not bound to an origin")
ErrCeremonyUnbound reports a ceremony carrying no origin, which a ceremony from a Begin function always does. It is a fail-closed guard against a Ceremony assembled some other way, never a condition a caller can reach.
var ErrIllegalRPID = errors.New("auth/webauthn: illegal relying-party ID")
ErrIllegalRPID reports a value that cannot be a relying-party ID. Every error ValidateRPID returns matches it with errors.Is and also carries the upstream validator's reason.
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.
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.
var KnownAAGUIDs = slices.Clone(knownAAGUIDTable)
KnownAAGUIDs lists the authenticators AuthenticatorName can name.
Deprecated: use AuthenticatorName. Changing this slice has no effect.
Functions ¶
func AuthenticatorName ¶ added in v6.1.0
AuthenticatorName returns the passkey provider name for a 16-byte AAGUID, from the community list at https://github.com/passkeydeveloper/passkey-authenticator-aaguids. It reports false for an unknown AAGUID or one that is not 16 bytes long.
func BeginConditionalLogin ¶
func BeginConditionalLogin(rp *RelyingParty, origin Origin) (*CredentialAssertion, Ceremony, error)
BeginConditionalLogin starts a WebAuthn assertion ceremony with conditional mediation, enabling browser autofill UI for passkeys, at origin, which must pass RelyingParty.CheckOrigin and is bound into the ceremony exactly as in BeginRegistration.
func BeginLogin ¶
func BeginLogin(rp *RelyingParty, origin Origin) (*CredentialAssertion, Ceremony, error)
BeginLogin starts a WebAuthn assertion ceremony (discoverable login) at origin, which must pass RelyingParty.CheckOrigin and is bound into the ceremony exactly as in BeginRegistration.
func BeginRegistration ¶
func BeginRegistration(rp *RelyingParty, user *User, origin Origin) (*CredentialCreation, Ceremony, error)
BeginRegistration starts a WebAuthn registration ceremony at origin, the browser origin the request arrived from (see ParseOrigin). The origin must pass RelyingParty.CheckOrigin, whose *OriginError is returned unchanged otherwise, and is bound into the ceremony: the response is verified against exactly that origin.
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 verifies a discoverable (passkey) assertion against the origin the ceremony was begun at and persists the credential's sign count and flags; a store failure there is logged at Warn and does not fail the login. The caller MUST check User.Enabled before creating a session. A deleted credential returns ErrUnknownCredential (errors.Is), so the client can forget the stale passkey; a ceremony with no origin returns ErrCeremonyUnbound.
func FinishRegistration ¶
func FinishRegistration(rp *RelyingParty, user *User, ceremony Ceremony, response *http.Request) (*auth.PasskeyCredential, error)
FinishRegistration completes a WebAuthn registration ceremony. The response is verified against the origin the ceremony was begun at; a ceremony that carries none fails with ErrCeremonyUnbound.
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. Absence is also what a client that does not forward clientExtensionResults produces, so a consumer that wants the check to fire must forward them.
func PasskeyFriendlyName ¶
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.
func ValidateRPID ¶
ValidateRPID reports whether id is a legal relying-party ID: a lowercase domain name with no scheme, port or path, not an IP address, and not a single label other than localhost. A refusal matches ErrIllegalRPID.
The lowercase requirement is this package's own: the upstream validator accepts "Example.COM", but the relying-party hash is computed over the configured bytes, so whether a mixed-case ID ever verifies depends on the client, and a configured value must not.
Types ¶
type AAGUIDEntry ¶
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 ¶
MarshalJSON encodes the bytes as an unpadded base64url JSON string.
func (*Base64URL) UnmarshalJSON ¶
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.
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 module'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.
type Origin ¶
type Origin struct {
// contains filtered or unexported fields
}
Origin is a browser origin a ceremony may be conducted at: a scheme, a host and an optional port, with no path, query, fragment or userinfo. Construct one with ParseOrigin; the zero value is not a usable origin.
func ParseOrigin ¶
ParseOrigin parses a browser origin as a browser serializes it, typically the value of an Origin request header. The error is a *OriginError.
The result is the value a ceremony's response is later compared against, so the parser performs only the two normalizations that comparison also performs, ASCII case folding and default-port elision, and refuses rather than repairs everything else: a trailing dot, an empty label and a non-ASCII host are all refused, and an IP literal is kept exactly as written. Repairing any of those would move the failure from a clean refusal before the authenticator prompt to a mismatch after it.
type OriginError ¶
type OriginError struct {
// Origin is the refused value: as given for a parse failure, in canonical
// form for a policy or list refusal.
Origin string
// RPID is the relying party that refused the origin; empty for a parse
// failure, which involves no relying party.
RPID string
Reason OriginRejection
}
OriginError reports a string that is not a usable origin, or an origin the relying party will not conduct a ceremony at. Matchable with errors.As as the pointer form. Error's message is diagnostic; a consumer composes its own user-facing sentence from Reason, because only the consumer knows what it calls the setting that holds the relying-party ID.
func (*OriginError) Error ¶
func (e *OriginError) Error() string
type OriginRejection ¶
type OriginRejection string
OriginRejection names why an origin cannot conduct a ceremony, or why a string is not a usable origin at all.
const ( RejectMalformed OriginRejection = "malformed" RejectTrailingDot OriginRejection = "trailing_dot" RejectEmptyLabel OriginRejection = "empty_label" RejectNonASCII OriginRejection = "non_ascii" )
The parse-stage rejections, reported by ParseOrigin with an empty OriginError.RPID.
const ( RejectNoOrigin OriginRejection = "no_origin" RejectInsecureScheme OriginRejection = "insecure_scheme" RejectIPHost OriginRejection = "ip_host" RejectHostNotCovered OriginRejection = "host_not_covered" )
The policy-stage rejections, reported by RelyingParty.CheckOrigin.
const RejectNotAllowlisted OriginRejection = "not_allowlisted"
RejectNotAllowlisted is the list-stage rejection: the policy accepted the origin, RPConfig.Origins was set, and it does not hold this origin.
type OriginsError ¶
type OriginsError struct {
Err *OriginError
Entry string
RPID string
Index int
}
OriginsError reports an RPConfig.Origins entry New refused: one that is not a usable origin, or one the origin policy for this relying party would itself reject. A list may only narrow what the policy admits, never widen it. It wraps the *OriginError naming the reason, so errors.As reaches both.
func (*OriginsError) Error ¶
func (e *OriginsError) Error() string
func (*OriginsError) Unwrap ¶
func (e *OriginsError) Unwrap() error
type RPConfig ¶
type RPConfig struct {
// ID is the relying party identifier, an effective domain
// (e.g. "example.com"), spelled in lowercase. See [ValidateRPID].
ID string
// DisplayName is the human-readable relying party name shown by
// authenticators.
DisplayName string
// Origins, when non-empty, restricts ceremonies to exactly these browser
// origins (e.g. "https://app.example.com"): a presented origin must satisfy
// the origin policy AND equal one entry on scheme, host and port. Leave it
// nil to let the policy decide alone. New refuses an entry the policy
// itself would reject, so a list can never widen the policy.
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.
The origin a ceremony expects is the origin it is begun at, judged by RelyingParty.CheckOrigin; Origins optionally narrows that judgement to an explicit set.
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, and an illegal ID with one matching ErrIllegalRPID, so a misconfigured relying party surfaces at construction rather than as a failed ceremony. An Origins entry that is not a usable origin, or that the origin policy would refuse, is rejected with a *OriginsError naming the entry.
func (*RelyingParty) CheckOrigin ¶
func (rp *RelyingParty) CheckOrigin(o Origin) error
CheckOrigin reports whether a ceremony may be conducted at o, returning nil or a *OriginError naming the reason.
An origin is acceptable when its scheme is https, or http for the specification's localhost exception, and its host is the relying-party ID or a proper subdomain of it. The port is not restricted: a relying party cannot know the port a browser reaches it on, and the port is carried into the ceremony verbatim, so a response must declare the same one.
When RPConfig.Origins was set, the origin must also equal one of the listed origins on scheme, host and port. The list narrows the policy and never widens it: New refuses a listed origin the policy would reject.
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 ¶
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 (*User) WebAuthnDisplayName ¶
WebAuthnDisplayName returns the display name, falling back to username.
func (*User) WebAuthnID ¶
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.
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.