passkey

package
v0.6.2 Latest Latest
Warning

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

Go to latest
Published: Oct 18, 2026 License: Apache-2.0 Imports: 11 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package passkey orchestrates the full lifecycle of a WebAuthn ("passkey") ceremony on top of github.com/go-webauthn/webauthn: registration (enrollment) and authentication, each as a begin/finish pair, plus client-side discoverable ("usernameless") login. go-webauthn documents two things it deliberately leaves to the caller: where the per-ceremony challenge lives between Begin and Finish, and where credential records are persisted. This package fills both in — behind the SessionStore and CredentialStore interfaces, with a bounded in-memory SessionStore usable out of the box — and adds the orchestration a real deployment needs around them: automatic exclusion/allow lists, a configurable default user verification requirement (and a documented explanation of what "preferred" does and does not enforce), and counter-rollback (clone) detection surfaced to the caller rather than decided for them.

Mechanism, not policy

Like every package in this module, passkey knows nothing about accounts, users, tenants, organizations, or roles — that vocabulary does not appear anywhere in its public API and never will. Where the package needs to tell one identity apart from another, it accepts an opaque byte-string "user handle" (exactly the WebAuthn user handle passed to a caller's authenticator) and never interprets it. A caller that wants to scope credentials to an account looks the account up on their own, derives a stable handle for it however they see fit, and passes that handle in; this package only ever round-trips it.

Credential *management* that has no WebAuthn-ceremony content — listing credentials for a "your devices" page, letting a user rename or delete one, counting how many accounts have a passkey — is deliberately not part of this package's API. Those are thin queries against whatever storage CredentialStore is backed by, and belong in the caller's own repository code, keyed by the credential and user-handle values this package already hands back.

The package also does not log anything. Every ceremony outcome this package cannot fully resolve on its own — a clone/rollback signal, a discoverable login's resolved identity, a session lookup miss — is placed in a return value, and it is entirely the caller's decision how (or whether) to record it.

Registration and login

BeginRegistration / FinishRegistration enroll a new credential for an already-identified handle (e.g. from a logged-in account adding a second device). BeginLogin / FinishLogin verify a credential against a single, already-identified handle (e.g. a passkey used as a second factor after a password). BeginDiscoverableLogin / FinishDiscoverableLogin run the usernameless "passkey proper" ceremony, where the identity is not known until the authenticator's own response names a credential; the account is resolved via CredentialStore.FindByID, never trusted from the client verbatim — go-webauthn cross-checks it against the user handle the assertion itself reports and fails the ceremony on a mismatch.

Clone / counter-rollback detection

Every authenticator that implements a signature counter is expected to report a strictly increasing value on each use; go-webauthn compares the reported counter against the value on file and sets Credential.Authenticator.CloneWarning when it did not advance — a sign the credential's private key may exist in more than one place. An authenticator that never implements a counter legitimately reports 0 every time, and that alone is never flagged (go-webauthn exempts the all-zero case).

This package surfaces CloneWarning on the LoginResult it returns and does not act on it. What it being set should MEAN for that login — refuse it outright, accept it but raise an alert, or something else — is a decision this package leaves entirely to the caller, and there are exactly two places to make it:

  • Inside CredentialStore.UpdateSignCount, which always runs before FinishLogin / FinishDiscoverableLogin returns. Refusing there returns a nil *LoginResult and the Store's error, so the login fails — and because the refusal happens before the write, the stored record is untouched. This is the way to reject a flagged login.
  • On the returned LoginResult, after the fact. The login can still be rejected, but the advanced counter and flags have already been written back; go-webauthn's storage guidance is that they must be, on every cryptographically successful login.

User verification: "preferred" is not enforced

go-webauthn only checks user verification (PIN/biometric, as opposed to mere possession) server-side when a ceremony's requirement is protocol.VerificationRequired. protocol.VerificationPreferred — the package's own default, see Config.UserVerification — is conveyed to the authenticator as a hint but never checked against the response. A discoverable ("usernameless") login is single-factor: there is no password behind it, so a deployment that offers BeginDiscoverableLogin as a real sign-in method (not merely a second factor) should set UserVerification to protocol.VerificationRequired for that ceremony, either via Config or by passing webauthn.WithUserVerification(protocol.VerificationRequired) to BeginDiscoverableLogin directly.

Index

Constants

View Source
const (
	DefaultSessionTTL      = 5 * time.Minute
	DefaultSessionCapacity = 10_000
)

DefaultSessionTTL and DefaultSessionCapacity are the bounds DefaultMemoryStore uses.

Variables

View Source
var (
	// ErrSessionNotFound is returned by a Finish call when sessionID is
	// unknown, already consumed, or expired. These three cases are
	// indistinguishable by design: a Finish call cannot be used to probe
	// which session ids were ever issued or how long ago. The ceremony must
	// be restarted from Begin.
	ErrSessionNotFound = errors.New("passkey: ceremony session not found or expired")

	// ErrNoCredentials is returned by BeginLogin when handle has no
	// credentials enrolled to build an allow-list from. It is never returned
	// by BeginDiscoverableLogin, which does not know the identity yet.
	ErrNoCredentials = errors.New("passkey: no credentials enrolled for this handle")
)

Sentinel errors returned by this package. Errors originating from go-webauthn itself (a failed signature, origin, or RP ID check; a session state validation) are returned unwrapped from the Begin/Finish calls that produced them — this package does not re-wrap them behind its own type, so a caller that wants to inspect one uses go-webauthn's protocol.Error directly.

View Source
var ErrCredentialNotFound = errors.New("passkey: credential not found")

ErrCredentialNotFound is returned by a CredentialStore's FindByID when no credential is stored under the given id. Implementations backed by a real database should return this exact sentinel (directly, or wrapped so errors.Is matches) so this package's discoverable-login lookup behaves consistently across backends.

Functions

This section is empty.

Types

type Config

type Config struct {
	// RPID is the WebAuthn Relying Party ID: the effective domain the
	// credentials are scoped to (e.g. "example.com"), never a full origin
	// (no scheme, no port). Required. Deriving this from an
	// attacker-influenced value such as an HTTP request's Host header is the
	// classic RP-ID-poisoning mistake — it must come from configuration the
	// caller controls.
	RPID string

	// RPDisplayName is a human-readable name for the relying party that some
	// authenticator UIs show during a ceremony. Required: WebAuthn itself
	// permits an empty string here, but this package does not, since a blank
	// prompt is never the deployment's intent.
	RPDisplayName string

	// RPOrigins lists every origin a ceremony may be started from and
	// finished against (e.g. "https://example.com",
	// "https://accounts.example.com"). A response is accepted if its origin
	// matches any entry — this is how one relying party serves several
	// domains or subdomains. At least one is required.
	RPOrigins []string

	// AuthenticatorSelection is the default sent with every registration
	// ceremony. Its zero value is go-webauthn's own default: ResidentKey
	// unset behaves as "discouraged", so a deployment that wants credentials
	// to actually be client-side discoverable (the "passkey" in
	// BeginDiscoverableLogin) should set
	// ResidentKey: protocol.ResidentKeyRequirementPreferred (or ...Required).
	// AuthenticatorSelection.UserVerification, if left as the empty string,
	// is filled in from Config.UserVerification. Override per call with
	// webauthn.WithAuthenticatorSelection.
	AuthenticatorSelection protocol.AuthenticatorSelection

	// AttestationPreference is the default attestation conveyance preference
	// sent with every registration ceremony. The zero value defaults to
	// protocol.PreferNoAttestation ("none"): no attestation statement is
	// requested, which reveals nothing about the authenticator model and is
	// the right default for almost every deployment. Set
	// protocol.PreferIndirectAttestation or protocol.PreferDirectAttestation
	// to request one instead. Override per call with
	// webauthn.WithConveyancePreference.
	AttestationPreference protocol.ConveyancePreference

	// UserVerification is this package's default user-verification
	// requirement. It is applied to every login ceremony (BeginLogin and
	// BeginDiscoverableLogin alike) unless a call overrides it by passing its
	// own webauthn.WithUserVerification, and it fills in
	// AuthenticatorSelection.UserVerification for registration when that is
	// left as the empty string. See "User verification: 'preferred' is not
	// enforced" in the package doc for why the choice between Preferred and
	// Required matters more than it looks. The zero value defaults to
	// protocol.VerificationPreferred.
	UserVerification protocol.UserVerificationRequirement

	// Sessions holds the challenge state a ceremony's Begin call produces
	// until its Finish call consumes it. Defaults to DefaultMemoryStore()
	// when nil.
	Sessions SessionStore

	// Credentials is this package's only persistent dependency. Required —
	// there is no in-memory default, because a WebAuthn credential is
	// permanent account data (see CredentialStore and MemoryCredentialStore).
	Credentials CredentialStore

	// Now stands in for time.Now in tests. Defaults to time.Now.
	Now func() time.Time
}

Config configures a Service.

type CredentialStore

type CredentialStore interface {
	// FindByID returns the credential stored under the raw credential ID (as
	// in webauthn.Credential.ID, or a response's RawID), or
	// ErrCredentialNotFound if none exists. Used to resolve identity during
	// a discoverable (usernameless) login.
	FindByID(ctx context.Context, credentialID []byte) (StoredCredential, error)

	// FindByUserHandle returns every credential registered under handle, in
	// any order. A handle with none returns an empty (or nil) slice and a
	// nil error — "no credentials yet" is not an error condition. Used to
	// build registration exclusion lists and login allow-lists, and to load
	// the current authenticator state (SignCount, Flags) an allow-listed
	// login must be verified against.
	FindByUserHandle(ctx context.Context, handle []byte) ([]StoredCredential, error)

	// Save persists a newly registered credential. Implementations should
	// reject (or upsert, if that is the caller's chosen policy) a duplicate
	// Credential.ID; BeginRegistration already excludes a handle's existing
	// credentials via go-webauthn's WithExclusions, so a collision here
	// signals either a client that ignored that exclusion list or an actual
	// ID collision.
	Save(ctx context.Context, cred StoredCredential) error

	// UpdateSignCount persists a credential's advanced authenticator state
	// after a successful login. cred is the full post-ceremony credential —
	// go-webauthn's own storage guidance is that SignCount, CloneWarning,
	// and the UserVerified/BackupState flags must all be written back on
	// every successful login, not just the counter, so an implementation
	// that only has a sign_count column should extract what it needs from
	// cred rather than persist it verbatim. usedAt is the ceremony's finish
	// time, for a last-used timestamp.
	//
	// # The write-back contract
	//
	// Both FinishLogin and FinishDiscoverableLogin call this once after the
	// assertion verifies, INCLUDING when cred.Authenticator.CloneWarning is
	// set — this package does not treat a counter rollback as a verification
	// failure. Being called is not the same as being obliged to write: an
	// implementation may apply its own policy and REFUSE BEFORE WRITING,
	// returning a classifiable error. What it must not do is return nil
	// while claiming a write it did not perform.
	//
	// A non-nil error fails the ceremony: both Finish methods return a nil
	// *LoginResult and that error, wrapped so errors.Is / errors.As still
	// reach it. This package never logs a write-back error and carries on —
	// an application that rejects a credential on a clone warning needs the
	// rejection to BE the outcome of the login, not a note attached to a
	// successful one. The ceremony's challenge is already consumed by then,
	// so a refused login has to be begun again.
	//
	// Refusing before writing is also the only way to get the stronger
	// property. This package does not attempt to undo a write an
	// implementation has already made: a Store that persists first and
	// decides afterwards has already changed the record.
	UpdateSignCount(ctx context.Context, credentialID []byte, cred webauthn.Credential, usedAt time.Time) error
}

CredentialStore is the minimal, caller-implemented contract this package needs to persist and look up WebAuthn credentials. It says nothing about who a credential belongs to beyond the opaque UserHandle on StoredCredential — no user, account, or tenant concept, and no assumption about the backing storage engine. A real implementation is typically a thin wrapper over one SQL table; see the "Storage" section of pkg.go.dev/github.com/go-webauthn/webauthn/webauthn for the column shape go-webauthn itself recommends, which this interface's methods map onto directly.

This is deliberately NOT a full credential-management API: renaming a credential for display, listing them for a "your devices" page, deleting one, or counting how many accounts have one are account-model operations with no WebAuthn-ceremony content. They belong in the caller's own repository code, built directly on their own storage, using the credential and user-handle values this package already round-trips to them — not in this interface.

type LoginResult

type LoginResult struct {
	// UserHandle is the opaque handle of the account this login was
	// verified for: the same value passed to BeginLogin, or the value
	// resolved from the credential the authenticator used, for a
	// discoverable ceremony.
	UserHandle []byte

	// Credential is the credential record as it stands after this login.
	// SignCount and Flags reflect this assertion, and the record was written
	// back via CredentialStore.UpdateSignCount before this value was
	// returned. A login that reaches here was accepted by that write-back;
	// a Store that refused it produces a nil *LoginResult instead (see that
	// method for the contract).
	//
	// Credential.Authenticator.CloneWarning is the counter-rollback signal:
	// it is set when the authenticator's reported counter did not advance
	// past the value already on file (and the two are not both simply
	// zero — an authenticator that never implements a counter legitimately
	// reports 0 every time, and that alone is never flagged). This package
	// does not act on it. A caller can still reject the login after
	// inspecting this field, but the write has happened by then; to reject a
	// flagged login WITHOUT writing it, refuse inside UpdateSignCount, which
	// fails the ceremony — see the package doc.
	Credential webauthn.Credential
}

LoginResult is what a successful FinishLogin or FinishDiscoverableLogin returns.

type MemoryCredentialStore

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

MemoryCredentialStore is a process-local CredentialStore backed by a plain map, safe for concurrent use. It has no eviction and no TTL: unlike the ephemeral ceremony state MemoryStore holds, a WebAuthn credential is permanent account data that must survive for the credential's lifetime — a store that aged entries out would silently lock people out of their passkeys. It exists for tests and local prototyping; every real deployment should implement CredentialStore against its own database instead (see the CredentialStore doc for the recommended shape).

func NewMemoryCredentialStore

func NewMemoryCredentialStore() *MemoryCredentialStore

NewMemoryCredentialStore returns an empty MemoryCredentialStore.

func (*MemoryCredentialStore) FindByID

func (m *MemoryCredentialStore) FindByID(_ context.Context, credentialID []byte) (StoredCredential, error)

FindByID implements CredentialStore.

func (*MemoryCredentialStore) FindByUserHandle

func (m *MemoryCredentialStore) FindByUserHandle(_ context.Context, handle []byte) ([]StoredCredential, error)

FindByUserHandle implements CredentialStore.

func (*MemoryCredentialStore) Save

Save implements CredentialStore. It errors if credentialID is already stored.

func (*MemoryCredentialStore) UpdateSignCount

func (m *MemoryCredentialStore) UpdateSignCount(_ context.Context, credentialID []byte, cred webauthn.Credential, _ time.Time) error

UpdateSignCount implements CredentialStore. It errors if credentialID is not stored.

type MemoryStore

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

MemoryStore is the package's default SessionStore: an in-process map bounded on two axes so it cannot grow without limit, mirroring captcha.MemoryStore elsewhere in this module. Entries older than ttl are treated as gone, and the store never holds more than maxItems entries at once — once full, the oldest entry (by insertion order) is evicted to make room for a new one, expired or not. Both bounds are enforced inline, on Put and Take; there is no background goroutine to start, leak, or shut down.

MemoryStore is safe for concurrent use.

func DefaultMemoryStore

func DefaultMemoryStore() *MemoryStore

DefaultMemoryStore returns a MemoryStore using the package's default TTL and capacity.

func NewMemoryStore

func NewMemoryStore(maxItems int, ttl time.Duration) *MemoryStore

NewMemoryStore returns a MemoryStore that keeps at most maxItems entries, each expiring ttl after it was put. maxItems <= 0 or ttl <= 0 are replaced with the package defaults rather than producing an unbounded store.

func (*MemoryStore) Len

func (s *MemoryStore) Len() int

Len reports the number of entries currently held, including any that have expired but not yet been purged by a Put or a Take. Exposed mainly so tests can observe the capacity cap taking effect.

func (*MemoryStore) Put

Put implements SessionStore.

func (*MemoryStore) Take

Take implements SessionStore.

type Service

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

Service orchestrates WebAuthn ceremonies for one relying-party configuration. It is safe for concurrent use; a typical deployment constructs one Service at startup and shares it across every request goroutine.

func New

func New(cfg Config) (*Service, error)

New builds a Service from cfg. It errors on an incomplete or invalid relying-party configuration (RPID / RPDisplayName / RPOrigins — see go-webauthn's own webauthn.New for what it validates) or a missing Credentials store.

func (*Service) BeginDiscoverableLogin

func (s *Service) BeginDiscoverableLogin(ctx context.Context, opts ...webauthn.LoginOption) (*protocol.CredentialAssertion, string, error)

BeginDiscoverableLogin starts a usernameless ("passkey", client-side discoverable credential) login ceremony: the browser is given no allow-list and may offer any passkey it holds for this relying party, so the account being authenticated is not known until FinishDiscoverableLogin resolves it from the credential the authenticator actually used. This reveals nothing about which accounts exist — unlike BeginLogin, it never even queries CredentialStore before the browser responds.

See "User verification: 'preferred' is not enforced" in the package doc: a discoverable login is typically single-factor, so most deployments offering it want protocol.VerificationRequired here, either via Config.UserVerification or by passing webauthn.WithUserVerification(protocol.VerificationRequired) in opts.

func (*Service) BeginLogin

func (s *Service) BeginLogin(ctx context.Context, handle []byte, opts ...webauthn.LoginOption) (*protocol.CredentialAssertion, string, error)

BeginLogin starts an allow-listed login ceremony scoped to a single, already-identified handle — e.g. a passkey used as a second factor after a password, or a scoped re-authentication. It requires at least one credential to already be registered under handle (ErrNoCredentials otherwise); for the usernameless "passkey proper" flow where the identity is not yet known, use BeginDiscoverableLogin instead.

func (*Service) BeginRegistration

func (s *Service) BeginRegistration(ctx context.Context, handle []byte, name, displayName string, opts ...webauthn.RegistrationOption) (*protocol.CredentialCreation, string, error)

BeginRegistration starts a registration (enrollment) ceremony for handle.

handle is the WebAuthn user handle: an opaque byte string, at most 64 bytes per the spec, that MUST be stable for the lifetime of the account and identical across every credential it owns. This package never interprets it — only threads it through to the authenticator and back. name and displayName populate the two purely cosmetic fields an authenticator's own UI may show (WebAuthnName / WebAuthnDisplayName); pass the same caller-meaningful string for both if there is no separate display name.

Credentials already registered under handle are automatically added to the exclusion list (go-webauthn's WithExclusions), so re-registering an authenticator the account already has is reported by the browser instead of silently creating a duplicate credential. Pass an explicit webauthn.WithExclusions in opts to override this default.

The returned string is a session id: hand it back to FinishRegistration unchanged, exactly as received.

func (*Service) FinishDiscoverableLogin

func (s *Service) FinishDiscoverableLogin(ctx context.Context, sessionID string, r *http.Request) (*LoginResult, error)

FinishDiscoverableLogin completes a discoverable login ceremony started by BeginDiscoverableLogin. It resolves the account from the credential ID the authenticator's response names — looked up via CredentialStore.FindByID, never trusted from the client beyond that lookup — and go-webauthn itself cross-checks the resolved identity's handle against the user handle the assertion separately reports, failing the ceremony on a mismatch rather than resolving to the wrong account.

sessionID is single-use regardless of outcome, exactly like FinishLogin.

func (*Service) FinishLogin

func (s *Service) FinishLogin(ctx context.Context, handle []byte, sessionID string, r *http.Request) (*LoginResult, error)

FinishLogin completes an allow-listed login ceremony started by BeginLogin. handle must match the value BeginLogin was called with — go-webauthn rejects a mismatch itself (see the package doc). sessionID is single-use regardless of outcome, exactly like FinishRegistration.

func (*Service) FinishRegistration

func (s *Service) FinishRegistration(ctx context.Context, handle []byte, sessionID string, r *http.Request) (*webauthn.Credential, error)

FinishRegistration completes a registration ceremony started by BeginRegistration: it verifies r against the parked session and, on success, persists the new credential via CredentialStore.Save before returning it.

handle must be the same value passed to the matching BeginRegistration. go-webauthn rejects a mismatch itself (it compares handle against the user handle baked into the session at Begin time) rather than silently registering the credential under a different identity — see the package doc.

sessionID is single-use regardless of outcome: a failed verification consumes it exactly like a successful one, so a rejected attempt cannot be retried against the same challenge.

type SessionStore

type SessionStore interface {
	// Put stores data under a fresh, unguessable id and returns that id.
	Put(ctx context.Context, data *webauthn.SessionData) (id string, err error)

	// Take returns the session data stored under id and atomically removes
	// it. ok is false when id is unknown, already taken, or expired — these
	// are indistinguishable to the caller by design.
	Take(ctx context.Context, id string) (data *webauthn.SessionData, ok bool)
}

SessionStore holds the *webauthn.SessionData a Begin call produces until the matching Finish call consumes it — the storage go-webauthn's own documentation leaves entirely to the caller between the Begin and Finish steps of a ceremony (see the Storage section of pkg.go.dev/github.com/go-webauthn/webauthn/webauthn). It has nothing to do with an HTTP login session: it exists only to span one register-or-login ceremony, typically a few seconds, and is discarded once that ceremony ends.

An implementation MUST be single-use: Take removes the entry unconditionally, whether the ceremony that follows succeeds or the authenticator's response fails verification, so a challenge can never be replayed and a rejected guess cannot be retried against the same one.

type StoredCredential

type StoredCredential struct {
	UserHandle []byte
	Credential webauthn.Credential
}

StoredCredential is a WebAuthn credential together with the opaque handle of the account it belongs to. UserHandle is exactly the byte string a caller passed as handle to BeginRegistration — this package never inspects or interprets it, only threads it through.

Jump to

Keyboard shortcuts

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