Documentation
¶
Overview ¶
Package webauthn is a WebAuthn Level 3 relying party on Go's standard library: passkey registration, discoverable sign-in and step-up ceremonies. It imports the core access 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 BeginReauthentication(rp *RelyingParty, user *User, origin Origin) (*CredentialAssertion, Ceremony, error)
- func BeginRegistration(rp *RelyingParty, user *User, origin Origin) (*CredentialCreation, Ceremony, error)
- func FinishRegistration(rp *RelyingParty, user *User, ceremony Ceremony, response io.Reader) (*access.PasskeyCredential, error)
- func PasskeyFriendlyName(aaguid []byte, existingNames []string) string
- func ValidateRPID(id string) error
- type AuthenticatorSelection
- type AuthenticatorTransport
- type Base64URL
- type COSEAlgorithm
- type Ceremony
- type CredentialAssertion
- type CredentialCreation
- type CredentialCreationOptions
- type CredentialDescriptor
- type CredentialParameter
- type CredentialRequestOptions
- type CredentialType
- type LoginResult
- 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 is the maximum duration a user has to complete an auth ceremony. CeremonyTimeout = 5 * time.Minute // MaxResponseBytes is the largest authenticator response a Finish or // Complete call reads; a larger one is refused with [ErrResponseTooLarge]. MaxResponseBytes = 64 << 10 )
Variables ¶
var ErrCeremonyUnbound = errors.New("access/webauthn: the ceremony did not come from a Begin function")
ErrCeremonyUnbound reports a Ceremony that no Begin function returned, such as the zero value. It is a fail-closed guard, never a condition a caller that keeps the Begin function's Ceremony can reach.
var ErrIllegalRPID = errors.New("access/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 states the reason.
var ErrNotDiscoverable = errors.New("access/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 ErrResponseTooLarge = errors.New("access/webauthn: the authenticator response is larger than MaxResponseBytes")
ErrResponseTooLarge reports an authenticator response longer than MaxResponseBytes. At most MaxResponseBytes+1 bytes are read to decide it.
var ErrUnknownCredential = errors.New("access/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 wraps nothing.
Functions ¶
func AuthenticatorName ¶
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. The AAGUID is self-asserted by the authenticator under "none" attestation, so the name is a display label, never evidence of the authenticator's make.
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. CompleteLogin finishes it.
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 BeginReauthentication ¶
func BeginReauthentication(rp *RelyingParty, user *User, origin Origin) (*CredentialAssertion, Ceremony, error)
BeginReauthentication starts an assertion bound to one user's credentials, for step-up, at origin, which must pass RelyingParty.CheckOrigin and is bound into the ceremony exactly as in BeginRegistration. A user with no passkey cannot begin one, and a user handle outside 1 to 64 bytes is refused (WebAuthn §5.4.3).
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). An origin that fails RelyingParty.CheckOrigin returns its *OriginError unchanged; the ceremony verifies the response against exactly that origin. A user handle outside 1 to 64 bytes is refused (WebAuthn §5.4.3). The three ML-DSA parameter sets are offered ahead of EdDSA, ES256 and RS256, so a post-quantum authenticator registers a post-quantum credential and every other one still registers.
func FinishRegistration ¶
func FinishRegistration(rp *RelyingParty, user *User, ceremony Ceremony, response io.Reader) (*access.PasskeyCredential, error)
FinishRegistration completes a registration from the PublicKeyCredential JSON in response, reading at most MaxResponseBytes (ErrResponseTooLarge past it), for the ceremony BeginRegistration began for user (ErrCeremonyUnbound for a Ceremony no Begin function returned). Only "none" and self attestation are accepted. A credential the client's credProps output reports as not discoverable is ErrNotDiscoverable, since no discoverable login can use it; a missing report is accepted, so forward clientExtensionResults for the check to fire.
func PasskeyFriendlyName ¶
PasskeyFriendlyName returns a display-only label for a newly registered passkey that duplicates no entry in existingNames. A known AAGUID gets its registry name ("Chrome on Mac"), numbered from the second of its kind ("Chrome on Mac 2"); an unknown one is always numbered ("Passkey 1"). The number is one past the highest in use, so a gap left by a deletion never yields a duplicate.
func ValidateRPID ¶
ValidateRPID reports whether id is a legal relying-party ID: a valid domain string (WebAuthn §4 "RP ID", WHATWG URL §3.4) in lowercase, of at most 253 bytes, with no scheme, port, path, query or fragment, and not an IP address. Its labels hold 1 to 63 letters, digits and hyphens, none at a label's ends and none in both its third and fourth places unless it starts with "xn--" (UTS #46 §4.1); the last label is not a number (WHATWG URL §3.5), and a single label is legal only as localhost. A refusal matches ErrIllegalRPID.
Types ¶
type AuthenticatorSelection ¶
type AuthenticatorSelection struct {
ResidentKey ResidentKeyRequirement `json:"residentKey,omitempty"`
UserVerification UserVerificationRequirement `json:"userVerification,omitempty"`
// RequireResidentKey is true when ResidentKey is required, since a Level 1
// client reads only this member (WebAuthn §5.4.4).
RequireResidentKey bool `json:"requireResidentKey,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 its Finish step verifies the response against. Keep it server-side, unmodified, from Begin to Finish, then discard it; a ceremony store needs only Ceremony.Expires. Copies share one immutable ceremony. The zero value is unusable and reports a zero deadline, so a lookup reports absence with a separate boolean.
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"`
User UserEntity `json:"user"`
Challenge Base64URL `json:"challenge"`
Parameters []CredentialParameter `json:"pubKeyCredParams,omitempty"`
ExcludeCredentials []CredentialDescriptor `json:"excludeCredentials,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).
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"`
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 LoginResult ¶
type LoginResult struct {
User *access.User
CredentialID []byte
// CloneWarning reports that the sign counter regressed on this assertion,
// the signal of a cloned authenticator; the stored flag stays set after it.
CloneWarning bool
}
LoginResult is a verified assertion whose custody update is stored.
func CompleteLogin ¶
func CompleteLogin(ctx context.Context, rp *RelyingParty, store Store, ceremony Ceremony, response io.Reader) (LoginResult, error)
CompleteLogin verifies a discoverable assertion read from response (at most MaxResponseBytes, else ErrResponseTooLarge) for a ceremony from BeginLogin or BeginConditionalLogin (ErrCeremonyUnbound for one no Begin function returned) and stores the custody update. The caller MUST check User.Enabled before creating a session. A handle with no account, or an account without the credential, is ErrUnknownCredential; a store failure, in the lookup or the custody write, matches access.ErrAuthBackend.
func CompleteReauthentication ¶
func CompleteReauthentication(ctx context.Context, rp *RelyingParty, store Store, user *User, ceremony Ceremony, response io.Reader) (LoginResult, error)
CompleteReauthentication verifies a step-up assertion, read from response as in CompleteLogin, for user, the ceremony's user from BeginReauthentication with the passkeys stored now, and stores the custody update. A ceremony begun for another user, or a discoverable one, is refused; a credential user does not hold is ErrUnknownCredential; a failed custody write matches access.ErrAuthBackend.
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 an Origin request header; the error is a *OriginError. It folds ASCII case and elides a default port, as that serialization does, so Origin.String is what a response's clientDataJSON origin must equal byte for byte. It refuses a trailing dot, an empty label, a non-ASCII host, one neither a hostname nor an IP address, and an IP address spelled otherwise: a repair would turn a refusal before the authenticator prompt into a mismatch after.
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 host rule accepted the origin, and it is not one of the accepted origins, the RPConfig.Origins entries or by default the relying party's exact origin.
func OriginRejections ¶
func OriginRejections() []OriginRejection
OriginRejections returns every OriginRejection: the parse, policy and list stages in that order.
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 set, is the exact list of origins ceremonies may run at
// (scheme, host and port), e.g. "https://app.example.com". Each must be
// the ID or a subdomain of it: New refuses an entry the host rule rejects.
Origins []string
// AllowSubdomains widens the default (empty Origins) from the exact origin
// to every subdomain and port of ID. It cannot be combined with Origins,
// and is unsafe wherever another host under ID can run script.
AllowSubdomains bool
}
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. By default only the relying party's exact origin is accepted; Origins replaces that set and AllowSubdomains widens it.
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. 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, an illegal ID with one matching ErrIllegalRPID, and Origins set beside AllowSubdomains with an error naming both, 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 host rule would refuse, is rejected with a *OriginsError naming the entry.
func (*RelyingParty) CheckOrigin ¶
func (rp *RelyingParty) CheckOrigin(o Origin) error
CheckOrigin returns nil when a ceremony may run at o, else a *OriginError. The host rule comes first: https, or http on localhost, at the relying-party ID or a subdomain of it, on any port. Unless RPConfig.AllowSubdomains is set, o must then equal on scheme, host and port an RPConfig.Origins entry, or by default https://<ID> on the default port (plus http://localhost for the ID localhost); a miss is RejectNotAllowlisted.
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) ([]access.PasskeyCredential, error)
// RecordAssertion stores a verified assertion's custody in one atomic
// step: the larger of the stored and upd's SignCount, the OR of both
// CloneWarnings, and upd's RawFlags and At (BS may clear,
// WebAuthn L3 §6.1.3). It compares nothing: the ceremony decided the
// regression. A credential userID does not hold is an error.
RecordAssertion(ctx context.Context, userID int64, credID []byte, upd access.PasskeyLoginUpdate) error
UserByWebAuthnHandle(ctx context.Context, handle []byte) (user *access.User, found bool, err error)
}
Store is the store interface CompleteLogin and CompleteReauthentication consume: the account and its passkeys by user handle, and the post-login custody write. The account package's passkey sign-in implements it over an github.com/cplieger/access/account.Store.
type User ¶
type User struct {
AuthUser *access.User
Credentials []access.PasskeyCredential
}
User is the account a ceremony runs for, with the passkeys it holds now.
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 access.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.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
internal
|
|
|
cbor
Package cbor decodes the RFC 8949 data items WebAuthn carries: one item per call, bounded in size, depth and item count, with no indefinite lengths or tags.
|
Package cbor decodes the RFC 8949 data items WebAuthn carries: one item per call, bounded in size, depth and item count, with no indefinite lengths or tags. |
|
cose
Package cose reads a WebAuthn credential public key, a COSE_Key (RFC 9052 §7), for the algorithms access offers, and verifies an assertion or self attestation signature under it.
|
Package cose reads a WebAuthn credential public key, a COSE_Key (RFC 9052 §7), for the algorithms access offers, and verifies an assertion or self attestation signature under it. |