diff --git a/README.md b/README.md
index 982e969..fb253b8 100644
--- a/README.md
+++ b/README.md
@@ -73,7 +73,7 @@ access to the database:
```sh
goftp user add bob --role operator # prints a temporary password
goftp user list
-goftp user passwd bob # new temporary password, ends bob's sessions
+goftp user passwd bob # new temporary password, ends bob's sessions and passkeys
goftp user two-factor-off bob # for when he lost his app and recovery codes
goftp user role bob admin
goftp user quota bob 10GiB # how much his home may hold; none, or default
@@ -84,6 +84,21 @@ New and reset passwords are temporary: after signing in, users can do
nothing but choose their own password (at least 12 characters), which ends
all their other sessions.
+### Passkeys
+
+Users can sign in without their password, with a passkey: a key that their
+phone, computer or security key keeps and unlocks with a fingerprint, their
+face or a PIN. They add one under **Passkeys** in their account menu,
+confirming with their password, on each device (up to 10), and then pick
+**Sign in with a passkey** on the sign-in page, or the passkey the browser
+offers under the username. A passkey works only on the site it was made on,
+by host name (as a proxy passes the `Host` header on), so a page made to
+look like it cannot use it. It is a second factor in itself: two-factor
+sign-in asks no code after one. A new temporary password (`goftp user
+passwd`, or **Users**) deletes the user's passkeys too, as after a break-in;
+changing one's own password keeps them. Browsers need a secure page for
+passkeys: HTTPS, or `http://localhost`.
+
### Two-factor sign-in
Users can have signing in take a code from an authenticator app after
@@ -535,7 +550,7 @@ Wrong app passwords count against the client's sign-in budget
sends `X-Forwarded-Proto`) the session cookie is `Secure` and `__Host-`
prefixed, and HSTS is sent.
- Passwords are hashed with Argon2id; only SHA-256 hashes of session tokens
- and recovery codes are stored. Two-factor secrets are stored as they
+ and recovery codes are stored, and of passkeys only their public keys. Two-factor secrets are stored as they
are, as codes are made from them: whoever reads the database can make
codes, but still needs the password.
- Failed sign-ins (and wrong current passwords) are rate limited per client
diff --git a/go.mod b/go.mod
index 8491844..e52e89b 100644
--- a/go.mod
+++ b/go.mod
@@ -4,7 +4,9 @@ go 1.27.3
require (
github.com/casbin/casbin/v3 v3.11.0
+ github.com/descope/virtualwebauthn v1.0.5
github.com/go-viper/mapstructure/v2 v2.5.0
+ github.com/go-webauthn/webauthn v0.18.2
github.com/gofiber/fiber/v3 v3.5.0
github.com/jackc/pgx/v5 v5.11.0
github.com/spf13/cobra v1.10.2
@@ -23,8 +25,12 @@ require (
github.com/bmatcuk/doublestar/v4 v4.6.1 // indirect
github.com/casbin/govaluate v1.3.0 // indirect
github.com/fsnotify/fsnotify v1.9.0 // indirect
+ github.com/fxamacker/cbor/v2 v2.9.4 // indirect
+ github.com/go-webauthn/x v0.3.1 // indirect
github.com/gofiber/schema v1.8.3 // indirect
github.com/gofiber/utils/v2 v2.4.1 // indirect
+ github.com/golang-jwt/jwt/v5 v5.3.1 // indirect
+ github.com/google/go-tpm v0.9.8 // indirect
github.com/google/uuid v1.6.0 // indirect
github.com/inconshreveable/mousetrap v1.1.0 // indirect
github.com/jackc/pgpassfile v1.0.0 // indirect
@@ -43,8 +49,9 @@ require (
github.com/subosito/gotenv v1.6.0 // indirect
github.com/tinylib/msgp v1.6.4 // indirect
github.com/valyala/bytebufferpool v1.0.0 // indirect
+ github.com/x448/float16 v0.8.4 // indirect
go.uber.org/multierr v1.10.0 // indirect
- go.yaml.in/yaml/v3 v3.0.4 // indirect
+ go.yaml.in/yaml/v3 v3.0.5 // indirect
golang.org/x/net v0.60.0 // indirect
golang.org/x/sync v0.23.0 // indirect
)
diff --git a/go.sum b/go.sum
index af947ae..0f0f642 100644
--- a/go.sum
+++ b/go.sum
@@ -6,24 +6,34 @@ github.com/casbin/govaluate v1.3.0 h1:VA0eSY0M2lA86dYd5kPPuNZMUD9QkWnOCnavGrw9my
github.com/casbin/govaluate v1.3.0/go.mod h1:G/UnbIjZk/0uMNaLwZZmFQrR72tYRZWQkO70si/iR7A=
github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
-github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
-github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
+github.com/descope/virtualwebauthn v1.0.5 h1:fMXji5UMepJC51Ge6d4v5IAjiJQRKmXE9hlo/B9SczQ=
+github.com/descope/virtualwebauthn v1.0.5/go.mod h1:lLCfN+DpCM3iisM4bCILZlFEWkC1Zo7ZgsxC45CUapI=
github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHkI4W8=
github.com/frankban/quicktest v1.14.6/go.mod h1:4ptaffx2x8+WTWXmUCuVU6aPUX1/Mz7zb5vbUoiM6w0=
github.com/fsnotify/fsnotify v1.9.0 h1:2Ml+OJNzbYCTzsxtv8vKSFD9PbJjmhYF14k/jKC7S9k=
github.com/fsnotify/fsnotify v1.9.0/go.mod h1:8jBTzvmWwFyi3Pb8djgCCO5IBqzKJ/Jwo8TRcHyHii0=
-github.com/fxamacker/cbor/v2 v2.9.2 h1:X4Ksno9+x3cz0TZv69ec1hxP/+tymuR8PXQJyDwfh78=
-github.com/fxamacker/cbor/v2 v2.9.2/go.mod h1:vM4b+DJCtHn+zz7h3FFp/hDAI9WNWCsZj23V5ytsSxQ=
+github.com/fxamacker/cbor/v2 v2.9.4 h1:xwjVlxEMR3S605oUlgBjKLTTeGFciYPGYCtF/35LKGo=
+github.com/fxamacker/cbor/v2 v2.9.4/go.mod h1:vM4b+DJCtHn+zz7h3FFp/hDAI9WNWCsZj23V5ytsSxQ=
github.com/go-viper/mapstructure/v2 v2.5.0 h1:vM5IJoUAy3d7zRSVtIwQgBj7BiWtMPfmPEgAXnvj1Ro=
github.com/go-viper/mapstructure/v2 v2.5.0/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM=
+github.com/go-webauthn/webauthn v0.18.2 h1:0BeftmEHU7i3Dv0VFwBtidy/ba37Vcdjvqst9EYu8Sk=
+github.com/go-webauthn/webauthn v0.18.2/go.mod h1:hEXaOuLxvZ3zG9miZe3ehlyeVso9AtklXG+kTn36k+A=
+github.com/go-webauthn/x v0.3.1 h1:1ff37z3XfmTTomkhlURgGizLIDyOvPgTt2t9nlzKLRo=
+github.com/go-webauthn/x v0.3.1/go.mod h1:ZInxAynYXfBPvvm5gzKZ7geBlL23K71xASMgohHl/Rg=
github.com/gofiber/fiber/v3 v3.5.0 h1:dk7TOUH6DXJGtOLsN2XEG+0ZML7cznzHILTVozbNEK8=
github.com/gofiber/fiber/v3 v3.5.0/go.mod h1:GOVDTW+gjJvfe0iJyVujbQ1Lnx+JUjFySJRI/9/xX/w=
github.com/gofiber/schema v1.8.3 h1:06ZedxIYjngzc0095PYy7uWnFnbRflWFpikvZH61fDc=
github.com/gofiber/schema v1.8.3/go.mod h1:jWnnZdhcW1mHyV+VnfRxKJDPNcepJsTZ9RIWxrr32Ng=
github.com/gofiber/utils/v2 v2.4.1 h1:E2X9G8O5Mn7b2GDb0JU3IUk42Rw2npuhhepIbuJQ2po=
github.com/gofiber/utils/v2 v2.4.1/go.mod h1:I+RTsgMUdzFuifVc3LOEkfh32wQW9BfRl7l5RYjamW4=
+github.com/golang-jwt/jwt/v5 v5.3.1 h1:kYf81DTWFe7t+1VvL7eS+jKFVWaUnK9cB1qbwn63YCY=
+github.com/golang-jwt/jwt/v5 v5.3.1/go.mod h1:fxCRLWMO43lRc8nhHWY6LGqRcf+1gQWArsqaEUEa5bE=
github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
+github.com/google/go-tpm v0.9.8 h1:slArAR9Ft+1ybZu0lBwpSmpwhRXaa85hWtMinMyRAWo=
+github.com/google/go-tpm v0.9.8/go.mod h1:h9jEsEECg7gtLis0upRBQU+GhYVH6jMjrFxI8u6bVUY=
+github.com/google/go-tpm-tools v0.3.13-0.20230620182252-4639ecce2aba h1:qJEJcuLzH5KDR0gKc0zcktin6KSAwL7+jWKBYceddTc=
+github.com/google/go-tpm-tools v0.3.13-0.20230620182252-4639ecce2aba/go.mod h1:EFYHy8/1y2KfgTAsx7Luu7NGhoxtuVHnNo8jE7FikKc=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=
@@ -52,7 +62,6 @@ github.com/pelletier/go-toml/v2 v2.2.4 h1:mye9XuhQ6gvn5h28+VilKrrPoQVanw5PMw/TB0
github.com/pelletier/go-toml/v2 v2.2.4/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY=
github.com/philhofer/fwd v1.2.0 h1:e6DnBTl7vGY+Gz322/ASL4Gyp1FspeMvx1RNDoToZuM=
github.com/philhofer/fwd v1.2.0/go.mod h1:RqIHx9QI14HlwKwm98g9Re5prTQ6LdeRQn+gXJFxsJM=
-github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/rogpeppe/go-internal v1.9.0 h1:73kH8U+JUqXU8lRuOHeVHaa/SZPifC7BkcraZVejAe8=
github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs=
@@ -77,8 +86,8 @@ github.com/spf13/viper v1.21.0/go.mod h1:P0lhsswPGWD/1lZJ9ny3fYnVqxiegrlNrEmgLjb
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
-github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
-github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
+github.com/stretchr/testify v1.12.1 h1:EuwCh5fleGS7H32xRwO3wRGT7DxrDhLAT6FF8MpWDWE=
+github.com/stretchr/testify v1.12.1/go.mod h1:MDEgiDPPsNp5cuIrHPPCyornHKgEVbtFUmoNlxoYthg=
github.com/subosito/gotenv v1.6.0 h1:9NlTDc1FTs4qu0DDq7AEtTPNw6SVm7uBMsUCUjABIf8=
github.com/subosito/gotenv v1.6.0/go.mod h1:Dk4QP5c2W3ibzajGcXpNraDfq2IrhjMIvMSWPKKo0FU=
github.com/tinylib/msgp v1.6.4 h1:mOwYbyYDLPj35mkA2BjjYejgJk9BuHxDdvRnb6v2ZcQ=
@@ -91,12 +100,15 @@ github.com/x448/float16 v0.8.4 h1:qLwI1I70+NjRFUR3zs1JPUCgaCXSh3SW62uAKT1mSBM=
github.com/x448/float16 v0.8.4/go.mod h1:14CWIYCyZA/cWjXOioeEpHeN/83MdbZDRQHoFcYsOfg=
go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=
go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=
+go.uber.org/mock v0.6.0 h1:hyF9dfmbgIX5EfOdasqLsWD6xqpNZlXblLB/Dbnwv3Y=
+go.uber.org/mock v0.6.0/go.mod h1:KiVJ4BqZJaMj4svdfmHM0AUx4NJYO8ZNpPnZn1Z+BBU=
go.uber.org/multierr v1.10.0 h1:S0h4aNzvfcFsC3dRF1jLoaov7oRaKqRGC/pUEJ2yvPQ=
go.uber.org/multierr v1.10.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=
go.uber.org/zap v1.28.0 h1:IZzaP1Fv73/T/pBMLk4VutPl36uNC+OSUh3JLG3FIjo=
go.uber.org/zap v1.28.0/go.mod h1:rDLpOi171uODNm/mxFcuYWxDsqWSAVkFdX4XojSKg/Q=
-go.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc=
go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=
+go.yaml.in/yaml/v3 v3.0.5 h1:N6y/pJk8buWs9NY5ERU2HSMfm+IuD/OtfdAnq6kESPw=
+go.yaml.in/yaml/v3 v3.0.5/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg=
golang.org/x/crypto v0.57.0 h1:3ZVCjf8Ggz7zneR/EHRVx68Ctf+2pmIMP2UFhh9cC6M=
golang.org/x/crypto v0.57.0/go.mod h1:Fdz0i5U6CoizGwLda9DttjSk6qlZo25zYNtR+ycvuZA=
golang.org/x/image v0.46.0 h1:b1+oYj0Jbp6K5MDT4i4/eZpYlk3V8SJhhDKh6LBHAyQ=
@@ -112,10 +124,6 @@ golang.org/x/text v0.42.0/go.mod h1:ojzP1Z+2QtioaF8DTtO8K5q7JWVVYwZKenzujK0Zd0E=
golang.org/x/tools v0.49.0 h1:3NI7VXzL9+1WZD52Dx2ttoPwD5DWrFGpl9mFZDlmisI=
golang.org/x/tools v0.49.0/go.mod h1:SJNXV9DBKT0UbdttsQjbfJlAE/q+y36++zo3uL3N0Oo=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
-gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
-gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
-gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
-gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
rsc.io/qr v0.2.0 h1:6vBLea5/NRMVTz8V66gipeLycZMl/+UlFmk8DvqQ6WY=
rsc.io/qr v0.2.0/go.mod h1:IF+uZjkb9fqyeF/4tlBoynqmQxUoPfWEKh921coOuXs=
diff --git a/internal/auth/authtest/store.go b/internal/auth/authtest/store.go
index 5eedf58..75d74ae 100644
--- a/internal/auth/authtest/store.go
+++ b/internal/auth/authtest/store.go
@@ -23,6 +23,7 @@ type Store struct {
apps map[string]*auth.AppPassword // by token hash
folders map[int64]*auth.FolderShare // by ID
factors map[int64]*twoFactor // by user ID
+ passkeys map[int64]*auth.Passkey // by ID
}
// twoFactor is what is kept of a user's two-factor sign-in.
@@ -48,7 +49,7 @@ var _ auth.Store = (*Store)(nil)
func NewStore() *Store {
return &Store{users: make(map[int64]*auth.User), sessions: make(map[string]session), shares: make(map[string]*auth.Share),
uploads: make(map[string]*upload), apps: make(map[string]*auth.AppPassword), folders: make(map[int64]*auth.FolderShare),
- factors: make(map[int64]*twoFactor)}
+ factors: make(map[int64]*twoFactor), passkeys: make(map[int64]*auth.Passkey)}
}
// NewService returns a service with an empty store and the default policy.
@@ -117,10 +118,90 @@ func (s *Store) SetPassword(_ context.Context, userID int64, passwordHash string
s.deleteApps(userID)
if mustChange {
s.deleteShares(userID)
+ s.deletePasskeys(userID)
}
return nil
}
+func (s *Store) deletePasskeys(userID int64) {
+ for id, pk := range s.passkeys {
+ if pk.UserID == userID {
+ delete(s.passkeys, id)
+ }
+ }
+}
+
+func (s *Store) UserByID(_ context.Context, id int64) (*auth.User, error) {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ u, ok := s.users[id]
+ if !ok {
+ return nil, auth.ErrNotFound
+ }
+ c := *u
+ return &c, nil
+}
+
+func (s *Store) CreatePasskey(_ context.Context, pk *auth.Passkey) error {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ if _, ok := s.users[pk.UserID]; !ok {
+ return auth.ErrNotFound
+ }
+ n := 0
+ for _, other := range s.passkeys {
+ if bytes.Equal(other.CredentialID, pk.CredentialID) {
+ return auth.ErrExists
+ }
+ if other.UserID == pk.UserID {
+ n++
+ }
+ }
+ if n >= auth.MaxPasskeys {
+ return auth.ErrTooMany
+ }
+ s.nextID++
+ pk.ID, pk.CreatedAt = s.nextID, time.Now()
+ c := *pk
+ s.passkeys[pk.ID] = &c
+ return nil
+}
+
+func (s *Store) Passkeys(_ context.Context, userID int64) ([]auth.Passkey, error) {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ var out []auth.Passkey
+ for _, pk := range s.passkeys {
+ if pk.UserID == userID {
+ out = append(out, *pk)
+ }
+ }
+ slices.SortFunc(out, func(a, b auth.Passkey) int { return cmp.Compare(a.ID, b.ID) })
+ return out, nil
+}
+
+func (s *Store) UsePasskey(_ context.Context, id int64, credential []byte) error {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ pk, ok := s.passkeys[id]
+ if !ok {
+ return auth.ErrNotFound
+ }
+ pk.Credential, pk.LastUsedAt = credential, time.Now()
+ return nil
+}
+
+func (s *Store) DeletePasskey(_ context.Context, userID, id int64) error {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ pk, ok := s.passkeys[id]
+ if !ok || pk.UserID != userID {
+ return auth.ErrNotFound
+ }
+ delete(s.passkeys, id)
+ return nil
+}
+
// factor returns the two-factor sign-in of userID, made if need be.
func (s *Store) factor(userID int64) (*twoFactor, error) {
if _, ok := s.users[userID]; !ok {
@@ -248,6 +329,7 @@ func (s *Store) DeleteUser(_ context.Context, userID int64) error {
}
delete(s.users, userID)
delete(s.factors, userID)
+ s.deletePasskeys(userID)
s.deleteSessions(userID)
s.deleteShares(userID)
s.deleteApps(userID)
diff --git a/internal/auth/passkey.go b/internal/auth/passkey.go
new file mode 100644
index 0000000..0d90e39
--- /dev/null
+++ b/internal/auth/passkey.go
@@ -0,0 +1,334 @@
+package auth
+
+import (
+ "context"
+ "encoding/binary"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "strings"
+ "sync"
+ "time"
+ "unicode"
+ "unicode/utf8"
+
+ "github.com/go-webauthn/webauthn/protocol"
+ "github.com/go-webauthn/webauthn/webauthn"
+)
+
+// Passkeys sign users in without a password, with a key that their phone,
+// computer or security key keeps and unlocks with a fingerprint, their face
+// or a PIN (WebAuthn). A user already signed in makes one, confirming with
+// their password. A passkey is a second factor in itself, so two-factor
+// sign-in asks no code after one. Each works only on the site (host name)
+// it was made on.
+
+// Passkey is one of a user's passkeys.
+type Passkey struct {
+ ID int64
+ UserID int64
+ Name string // what it is, e.g. "iPhone"
+ CreatedAt time.Time
+ LastUsedAt time.Time // zero if never
+ CredentialID []byte
+ Credential []byte // the webauthn.Credential, as JSON
+}
+
+// MaxPasskeys bounds the passkeys of one user.
+const MaxPasskeys = 10
+
+// maxPasskeyName bounds the length of a passkey's name.
+const maxPasskeyName = 64
+
+// A passkey is made, or used to sign in, within ceremonyTTL of starting.
+const (
+ ceremonyTTL = 5 * time.Minute
+ maxCeremonies = 10_000
+)
+
+var (
+ // ErrPasskeyRefused is a passkey, or an answer of the browser, that
+ // does not check out.
+ ErrPasskeyRefused = errors.New("passkey refused")
+ // ErrCeremonyGone is a passkey that took too long to make or use, or
+ // was started elsewhere: it starts again.
+ ErrCeremonyGone = errors.New("start again")
+)
+
+// Site is where passkeys are made and used: the host name, which they are
+// bound to, and the origin of the pages that use them.
+type Site struct{ Host, Origin string }
+
+func (site Site) webauthn() (*webauthn.WebAuthn, error) {
+ return webauthn.New(&webauthn.Config{
+ RPID: site.Host,
+ RPDisplayName: "goftp",
+ RPOrigins: []string{site.Origin},
+ // Passkeys proper: kept by the authenticator, which checks who
+ // uses them, so that they can sign in without a username.
+ AuthenticatorSelection: protocol.AuthenticatorSelection{
+ ResidentKey: protocol.ResidentKeyRequirementRequired,
+ RequireResidentKey: protocol.ResidentKeyRequired(),
+ UserVerification: protocol.VerificationRequired,
+ },
+ AttestationPreference: protocol.PreferNoAttestation,
+ })
+}
+
+// passkeyUser is a user as WebAuthn knows them.
+type passkeyUser struct {
+ u *User
+ keys []Passkey
+ creds []webauthn.Credential
+}
+
+func newPasskeyUser(u *User, keys []Passkey) (*passkeyUser, error) {
+ pu := &passkeyUser{u: u, keys: keys}
+ for _, k := range keys {
+ var cred webauthn.Credential
+ if err := json.Unmarshal(k.Credential, &cred); err != nil {
+ return nil, fmt.Errorf("passkey %d: %w", k.ID, err)
+ }
+ pu.creds = append(pu.creds, cred)
+ }
+ return pu, nil
+}
+
+// userHandle is how passkeys name the user id: never reused, and nothing
+// else about them.
+func userHandle(id int64) []byte { return binary.BigEndian.AppendUint64(nil, uint64(id)) }
+
+func (pu *passkeyUser) WebAuthnID() []byte { return userHandle(pu.u.ID) }
+func (pu *passkeyUser) WebAuthnName() string { return pu.u.Username }
+func (pu *passkeyUser) WebAuthnDisplayName() string { return pu.u.Username }
+func (pu *passkeyUser) WebAuthnCredentials() []webauthn.Credential { return pu.creds }
+
+// key returns the passkey of the credential id.
+func (pu *passkeyUser) key(id []byte) *Passkey {
+ for i := range pu.keys {
+ if string(pu.keys[i].CredentialID) == string(id) {
+ return &pu.keys[i]
+ }
+ }
+ return nil
+}
+
+// ceremony is a passkey being made, for user, or used to sign in.
+type ceremony struct {
+ data webauthn.SessionData
+ site Site
+ user *User
+ expires time.Time
+}
+
+// ceremonies are those under way, by token hash.
+type ceremonies struct {
+ mu sync.Mutex
+ m map[string]*ceremony
+}
+
+func (cs *ceremonies) start(c *ceremony) (string, error) {
+ cs.mu.Lock()
+ defer cs.mu.Unlock()
+ now := time.Now()
+ if cs.m == nil {
+ cs.m = map[string]*ceremony{}
+ }
+ if len(cs.m) >= maxCeremonies {
+ for k, old := range cs.m {
+ if now.After(old.expires) {
+ delete(cs.m, k)
+ }
+ }
+ if len(cs.m) >= maxCeremonies {
+ return "", ErrBusy
+ }
+ }
+ c.expires = now.Add(ceremonyTTL)
+ token := newToken()
+ cs.m[string(tokenHash(token))] = c
+ return token, nil
+}
+
+// take ends the ceremony token and returns it, if it is still under way.
+func (cs *ceremonies) take(token string) (*ceremony, bool) {
+ if len(token) != 43 {
+ return nil, false
+ }
+ key := string(tokenHash(token))
+ cs.mu.Lock()
+ defer cs.mu.Unlock()
+ c, ok := cs.m[key]
+ delete(cs.m, key)
+ if !ok || time.Now().After(c.expires) {
+ return nil, false
+ }
+ return c, true
+}
+
+// Passkeys lists u's passkeys, oldest first.
+func (s *Service) Passkeys(ctx context.Context, u *User) ([]Passkey, error) {
+ return s.store.Passkeys(ctx, u.ID)
+}
+
+// DeletePasskey deletes u's passkey id (ErrNotFound if u has none of that
+// ID).
+func (s *Service) DeletePasskey(ctx context.Context, u *User, id int64) error {
+ return s.store.DeletePasskey(ctx, u.ID, id)
+}
+
+// BeginPasskey starts making a passkey for u at site, after checking their
+// password. It returns the options for the browser's
+// navigator.credentials.create, as JSON, and a token that FinishPasskey
+// takes with the browser's answer. ErrTooMany if u has MaxPasskeys.
+func (s *Service) BeginPasskey(ctx context.Context, u *User, password string, site Site) ([]byte, string, error) {
+ if err := s.checkPasswordOf(ctx, u, password); err != nil {
+ return nil, "", err
+ }
+ keys, err := s.store.Passkeys(ctx, u.ID)
+ if err != nil {
+ return nil, "", err
+ }
+ if len(keys) >= MaxPasskeys {
+ return nil, "", ErrTooMany
+ }
+ pu, err := newPasskeyUser(u, keys)
+ if err != nil {
+ return nil, "", err
+ }
+ wa, err := site.webauthn()
+ if err != nil {
+ return nil, "", err
+ }
+ // An authenticator that has one of u's passkeys makes no other.
+ var exclude []protocol.CredentialDescriptor
+ for _, cred := range pu.creds {
+ exclude = append(exclude, cred.Descriptor())
+ }
+ creation, data, err := wa.BeginRegistration(pu, webauthn.WithExclusions(exclude))
+ if err != nil {
+ return nil, "", err
+ }
+ token, err := s.ceremonies.start(&ceremony{data: *data, site: site, user: u})
+ if err != nil {
+ return nil, "", err
+ }
+ options, err := json.Marshal(creation)
+ return options, token, err
+}
+
+// FinishPasskey makes the passkey that the ceremony token started, named
+// name, from response, the browser's answer as JSON.
+func (s *Service) FinishPasskey(ctx context.Context, u *User, token, name string, response []byte) (*Passkey, error) {
+ name = strings.TrimSpace(name)
+ if name == "" || utf8.RuneCountInString(name) > maxPasskeyName || strings.ContainsFunc(name, unicode.IsControl) {
+ return nil, fmt.Errorf("%w: name it in up to %d characters", ErrInvalid, maxPasskeyName)
+ }
+ c, ok := s.ceremonies.take(token)
+ if !ok || c.user == nil || c.user.ID != u.ID {
+ return nil, ErrCeremonyGone
+ }
+ parsed, err := protocol.ParseCredentialCreationResponseBytes(response)
+ if err != nil {
+ return nil, fmt.Errorf("%w: %w", ErrPasskeyRefused, err)
+ }
+ keys, err := s.store.Passkeys(ctx, u.ID)
+ if err != nil {
+ return nil, err
+ }
+ pu, err := newPasskeyUser(u, keys)
+ if err != nil {
+ return nil, err
+ }
+ wa, err := c.site.webauthn()
+ if err != nil {
+ return nil, err
+ }
+ cred, err := wa.CreateCredential(pu, c.data, parsed)
+ if err != nil {
+ return nil, fmt.Errorf("%w: %w", ErrPasskeyRefused, err)
+ }
+ raw, err := json.Marshal(cred)
+ if err != nil {
+ return nil, err
+ }
+ pk := &Passkey{UserID: u.ID, Name: name, CredentialID: cred.ID, Credential: raw}
+ if err := s.store.CreatePasskey(ctx, pk); err != nil {
+ return nil, err
+ }
+ return pk, nil
+}
+
+// BeginPasskeyLogin starts signing in with a passkey at site, whoever has
+// it. It returns the options for the browser's navigator.credentials.get,
+// as JSON, and a token that PasskeyLogin takes with the browser's answer.
+func (s *Service) BeginPasskeyLogin(site Site) ([]byte, string, error) {
+ wa, err := site.webauthn()
+ if err != nil {
+ return nil, "", err
+ }
+ assertion, data, err := wa.BeginDiscoverableLogin(webauthn.WithUserVerification(protocol.VerificationRequired))
+ if err != nil {
+ return nil, "", err
+ }
+ token, err := s.ceremonies.start(&ceremony{data: *data, site: site})
+ if err != nil {
+ return nil, "", err
+ }
+ options, err := json.Marshal(assertion)
+ return options, token, err
+}
+
+// PasskeyLogin signs in with the passkey of response, the browser's answer
+// as JSON to the ceremony token, and starts a session for its user.
+func (s *Service) PasskeyLogin(ctx context.Context, token string, response []byte) (*Session, error) {
+ c, ok := s.ceremonies.take(token)
+ if !ok || c.user != nil {
+ return nil, ErrCeremonyGone
+ }
+ parsed, err := protocol.ParseCredentialRequestResponseBytes(response)
+ if err != nil {
+ return nil, fmt.Errorf("%w: %w", ErrPasskeyRefused, err)
+ }
+ var owner *passkeyUser
+ find := func(_, handle []byte) (webauthn.User, error) {
+ if len(handle) != 8 {
+ return nil, ErrNotFound
+ }
+ u, err := s.store.UserByID(ctx, int64(binary.BigEndian.Uint64(handle)))
+ if err != nil {
+ return nil, err
+ }
+ keys, err := s.store.Passkeys(ctx, u.ID)
+ if err != nil {
+ return nil, err
+ }
+ if owner, err = newPasskeyUser(u, keys); err != nil {
+ return nil, err
+ }
+ return owner, nil
+ }
+ wa, err := c.site.webauthn()
+ if err != nil {
+ return nil, err
+ }
+ cred, err := wa.ValidateDiscoverableLogin(find, c.data, parsed)
+ if err != nil {
+ return nil, fmt.Errorf("%w: %w", ErrPasskeyRefused, err)
+ }
+ if cred.Authenticator.CloneWarning {
+ return nil, fmt.Errorf("%w: its signature counter went back, as if it was copied", ErrPasskeyRefused)
+ }
+ pk := owner.key(cred.ID)
+ if pk == nil {
+ return nil, ErrPasskeyRefused
+ }
+ raw, err := json.Marshal(cred)
+ if err != nil {
+ return nil, err
+ }
+ if err := s.store.UsePasskey(ctx, pk.ID, raw); err != nil {
+ return nil, err
+ }
+ return s.loginSession(ctx, owner.u, false)
+}
diff --git a/internal/auth/passkey_test.go b/internal/auth/passkey_test.go
new file mode 100644
index 0000000..4a9a540
--- /dev/null
+++ b/internal/auth/passkey_test.go
@@ -0,0 +1,176 @@
+package auth_test
+
+import (
+ "context"
+ "errors"
+ "testing"
+
+ "github.com/descope/virtualwebauthn"
+
+ "goftp/internal/auth"
+)
+
+var (
+ site = auth.Site{Host: "files.example.com", Origin: "https://files.example.com"}
+ siteRP = virtualwebauthn.RelyingParty{Name: "goftp", ID: site.Host, Origin: site.Origin}
+)
+
+// makePasskey makes a passkey for u named name on a new authenticator,
+// which it returns with the passkey's key.
+func makePasskey(t *testing.T, svc *auth.Service, u *auth.User, password, name string) (virtualwebauthn.Authenticator, virtualwebauthn.Credential, *auth.Passkey) {
+ t.Helper()
+ ctx := context.Background()
+ options, token, err := svc.BeginPasskey(ctx, u, password, site)
+ if err != nil {
+ t.Fatal(err)
+ }
+ parsed, err := virtualwebauthn.ParseAttestationOptions(string(options))
+ if err != nil {
+ t.Fatal(err)
+ }
+ a := virtualwebauthn.NewAuthenticatorWithOptions(virtualwebauthn.AuthenticatorOptions{UserHandle: []byte(parsed.UserID)})
+ cred := virtualwebauthn.NewCredential(virtualwebauthn.KeyTypeEC2)
+ pk, err := svc.FinishPasskey(ctx, u, token, name, []byte(virtualwebauthn.CreateAttestationResponse(siteRP, a, cred, *parsed)))
+ if err != nil {
+ t.Fatal(err)
+ }
+ a.AddCredential(cred)
+ return a, cred, pk
+}
+
+// signInWith signs in with the passkey cred of a, answering as rp.
+func signInWith(t *testing.T, svc *auth.Service, a virtualwebauthn.Authenticator, cred virtualwebauthn.Credential, rp virtualwebauthn.RelyingParty) (*auth.Session, error) {
+ t.Helper()
+ options, token, err := svc.BeginPasskeyLogin(site)
+ if err != nil {
+ t.Fatal(err)
+ }
+ parsed, err := virtualwebauthn.ParseAssertionOptions(string(options))
+ if err != nil {
+ t.Fatal(err)
+ }
+ return svc.PasskeyLogin(context.Background(), token, []byte(virtualwebauthn.CreateAssertionResponse(rp, a, cred, *parsed)))
+}
+
+func TestPasskeys(t *testing.T) {
+ services(t, func(t *testing.T, svc *auth.Service) {
+ ctx := context.Background()
+ password, err := svc.CreateUser(ctx, "dora", "user")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err := svc.CreateUser(ctx, "erin", "user"); err != nil {
+ t.Fatal(err)
+ }
+ dora, erin := userNamed(t, svc, "dora"), userNamed(t, svc, "erin")
+
+ if _, _, err := svc.BeginPasskey(ctx, dora, "wrong password", site); !errors.Is(err, auth.ErrInvalidCredentials) {
+ t.Errorf("wrong password: %v", err)
+ }
+ _, token, err := svc.BeginPasskey(ctx, dora, password, site)
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, name := range []string{"", " ", "a\nb"} {
+ if _, err := svc.FinishPasskey(ctx, dora, token, name, []byte("{}")); !errors.Is(err, auth.ErrInvalid) {
+ t.Errorf("name %q: %v", name, err)
+ }
+ }
+ if _, err := svc.FinishPasskey(ctx, erin, token, "phone", []byte("{}")); !errors.Is(err, auth.ErrCeremonyGone) {
+ t.Errorf("someone else's: %v", err)
+ }
+ if _, err := svc.FinishPasskey(ctx, dora, token, "phone", []byte("{}")); !errors.Is(err, auth.ErrCeremonyGone) {
+ t.Errorf("finished twice: %v", err)
+ }
+
+ a, cred, pk := makePasskey(t, svc, dora, password, " laptop ")
+ if pk.ID == 0 || pk.Name != "laptop" || pk.UserID != dora.ID || len(pk.CredentialID) == 0 {
+ t.Errorf("passkey %+v", pk)
+ }
+ // An authenticator with one of dora's passkeys makes no other.
+ options, _, err := svc.BeginPasskey(ctx, dora, password, site)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if parsed, err := virtualwebauthn.ParseAttestationOptions(string(options)); err != nil || len(parsed.ExcludeCredentials) != 1 {
+ t.Errorf("excluded: %+v, %v", parsed, err)
+ }
+
+ // It signs dora in, whoever she is to the browser.
+ sess, err := signInWith(t, svc, a, cred, siteRP)
+ if err != nil || sess.User.ID != dora.ID || len(sess.Token) != 43 {
+ t.Fatalf("signed in: %+v, %v", sess, err)
+ }
+ if keys, err := svc.Passkeys(ctx, dora); err != nil || len(keys) != 1 || keys[0].LastUsedAt.IsZero() {
+ t.Errorf("used: %+v, %v", keys, err)
+ }
+ // Not on another site, nor with a passkey it does not know.
+ if _, err := signInWith(t, svc, a, cred, virtualwebauthn.RelyingParty{Name: "goftp", ID: site.Host, Origin: "https://evil.example.com"}); !errors.Is(err, auth.ErrPasskeyRefused) {
+ t.Errorf("another origin: %v", err)
+ }
+ if _, err := signInWith(t, svc, a, cred, virtualwebauthn.RelyingParty{Name: "goftp", ID: "evil.example.com", Origin: site.Origin}); !errors.Is(err, auth.ErrPasskeyRefused) {
+ t.Errorf("another site: %v", err)
+ }
+ stranger := virtualwebauthn.NewCredential(virtualwebauthn.KeyTypeEC2)
+ a.AddCredential(stranger)
+ if _, err := signInWith(t, svc, a, stranger, siteRP); !errors.Is(err, auth.ErrPasskeyRefused) {
+ t.Errorf("an unknown passkey: %v", err)
+ }
+ if _, err := svc.PasskeyLogin(ctx, "nope", []byte("{}")); !errors.Is(err, auth.ErrCeremonyGone) {
+ t.Errorf("no such ceremony: %v", err)
+ }
+
+ // With two-factor sign-in, no code after it: a passkey is one in
+ // itself.
+ secret, err := svc.StartTwoFactor(ctx, dora)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, _, err := svc.ConfirmTwoFactor(ctx, dora, codeOf(t, secret, 0)); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := signInWith(t, svc, a, cred, siteRP); err != nil {
+ t.Errorf("with two-factor sign-in on: %v", err)
+ }
+
+ // Deleted, it signs nobody in.
+ if err := svc.DeletePasskey(ctx, erin, pk.ID); !errors.Is(err, auth.ErrNotFound) {
+ t.Errorf("deleted by someone else: %v", err)
+ }
+ if err := svc.DeletePasskey(ctx, dora, pk.ID); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := signInWith(t, svc, a, cred, siteRP); !errors.Is(err, auth.ErrPasskeyRefused) {
+ t.Errorf("a deleted passkey: %v", err)
+ }
+
+ // A new temporary password ends them, as one does after a break-in.
+ a, cred, _ = makePasskey(t, svc, dora, password, "phone")
+ if _, err := svc.ResetPassword(ctx, "dora"); err != nil {
+ t.Fatal(err)
+ }
+ if keys, err := svc.Passkeys(ctx, dora); err != nil || len(keys) != 0 {
+ t.Errorf("after a reset: %+v, %v", keys, err)
+ }
+ if _, err := signInWith(t, svc, a, cred, siteRP); !errors.Is(err, auth.ErrPasskeyRefused) {
+ t.Errorf("after a reset: %v", err)
+ }
+ })
+}
+
+func TestPasskeyLimit(t *testing.T) {
+ services(t, func(t *testing.T, svc *auth.Service) {
+ ctx := context.Background()
+ password, err := svc.CreateUser(ctx, "dora", "user")
+ if err != nil {
+ t.Fatal(err)
+ }
+ dora := userNamed(t, svc, "dora")
+ for range auth.MaxPasskeys {
+ makePasskey(t, svc, dora, password, "key")
+ }
+ if _, _, err := svc.BeginPasskey(ctx, dora, password, site); !errors.Is(err, auth.ErrTooMany) {
+ t.Errorf("one too many: %v", err)
+ }
+ })
+}
diff --git a/internal/auth/postgres.go b/internal/auth/postgres.go
index e01baa7..393c534 100644
--- a/internal/auth/postgres.go
+++ b/internal/auth/postgres.go
@@ -48,6 +48,10 @@ func (s *PgStore) UserByName(ctx context.Context, username string) (*User, error
return scanUser(s.db.QueryRow(ctx, "SELECT "+userColumns+" FROM users WHERE username = $1", username))
}
+func (s *PgStore) UserByID(ctx context.Context, id int64) (*User, error) {
+ return scanUser(s.db.QueryRow(ctx, "SELECT "+userColumns+" FROM users WHERE id = $1", id))
+}
+
func (s *PgStore) ListUsers(ctx context.Context) ([]User, error) {
rows, err := s.db.Query(ctx, "SELECT "+userColumns+" FROM users ORDER BY username")
if err != nil {
@@ -79,7 +83,10 @@ func (s *PgStore) SetPassword(ctx context.Context, userID int64, passwordHash st
if _, err = tx.Exec(ctx, "DELETE FROM app_passwords WHERE user_id = $1", userID); err != nil || !mustChange {
return err
}
- _, err = tx.Exec(ctx, "DELETE FROM shares WHERE created_by = $1", userID)
+ if _, err = tx.Exec(ctx, "DELETE FROM shares WHERE created_by = $1", userID); err != nil {
+ return err
+ }
+ _, err = tx.Exec(ctx, "DELETE FROM passkeys WHERE user_id = $1", userID)
return err
})
}
@@ -340,6 +347,65 @@ func setRecoveryCodes(ctx context.Context, tx pgx.Tx, userID int64, hashes [][]b
return err
}
+func (s *PgStore) CreatePasskey(ctx context.Context, pk *Passkey) error {
+ return pgx.BeginFunc(ctx, s.db, func(tx pgx.Tx) error {
+ // The row lock serializes a user's passkeys, so they cannot exceed
+ // the limit together.
+ if _, err := tx.Exec(ctx, "SELECT 1 FROM users WHERE id = $1 FOR UPDATE", pk.UserID); err != nil {
+ return err
+ }
+ var n int
+ if err := tx.QueryRow(ctx, "SELECT count(*) FROM passkeys WHERE user_id = $1", pk.UserID).Scan(&n); err != nil {
+ return err
+ }
+ if n >= MaxPasskeys {
+ return ErrTooMany
+ }
+ err := tx.QueryRow(ctx, `INSERT INTO passkeys (user_id, name, credential_id, credential) VALUES ($1, $2, $3, $4)
+ ON CONFLICT (credential_id) DO NOTHING RETURNING id, created_at`, pk.UserID, pk.Name, pk.CredentialID, pk.Credential).
+ Scan(&pk.ID, &pk.CreatedAt)
+ if errors.Is(err, pgx.ErrNoRows) {
+ return ErrExists
+ }
+ return err
+ })
+}
+
+func (s *PgStore) Passkeys(ctx context.Context, userID int64) ([]Passkey, error) {
+ rows, err := s.db.Query(ctx, `SELECT id, user_id, name, credential_id, credential, created_at, last_used_at
+ FROM passkeys WHERE user_id = $1 ORDER BY created_at, id`, userID)
+ if err != nil {
+ return nil, err
+ }
+ return pgx.CollectRows(rows, func(row pgx.CollectableRow) (Passkey, error) {
+ var (
+ pk Passkey
+ lastUsed *time.Time
+ )
+ err := row.Scan(&pk.ID, &pk.UserID, &pk.Name, &pk.CredentialID, &pk.Credential, &pk.CreatedAt, &lastUsed)
+ if lastUsed != nil {
+ pk.LastUsedAt = *lastUsed
+ }
+ return pk, err
+ })
+}
+
+func (s *PgStore) UsePasskey(ctx context.Context, id int64, credential []byte) error {
+ tag, err := s.db.Exec(ctx, "UPDATE passkeys SET credential = $2, last_used_at = now() WHERE id = $1", id, credential)
+ if err == nil && tag.RowsAffected() == 0 {
+ err = ErrNotFound
+ }
+ return err
+}
+
+func (s *PgStore) DeletePasskey(ctx context.Context, userID, id int64) error {
+ tag, err := s.db.Exec(ctx, "DELETE FROM passkeys WHERE id = $1 AND user_id = $2", id, userID)
+ if err == nil && tag.RowsAffected() == 0 {
+ err = ErrNotFound
+ }
+ return err
+}
+
func (s *PgStore) SetHomeQuota(ctx context.Context, userID int64, quota *int64) error {
tag, err := s.db.Exec(ctx, "UPDATE users SET home_quota = $2 WHERE id = $1", userID, quota)
if err == nil && tag.RowsAffected() == 0 {
diff --git a/internal/auth/service.go b/internal/auth/service.go
index dd1c842..ed217c4 100644
--- a/internal/auth/service.go
+++ b/internal/auth/service.go
@@ -46,6 +46,7 @@ type Service struct {
fold atomic.Value // how rules compare paths (see SetFold)
challenges challenges // sign-ins that wait for a two-factor code
+ ceremonies ceremonies // passkeys being made or used
}
func NewService(store Store, enforcer *casbin.SyncedEnforcer, sessionTTL time.Duration) *Service {
diff --git a/internal/auth/store.go b/internal/auth/store.go
index f292e5c..648b6a2 100644
--- a/internal/auth/store.go
+++ b/internal/auth/store.go
@@ -84,9 +84,11 @@ type Upload struct {
type Store interface {
CreateUser(ctx context.Context, username, passwordHash string) (int64, error)
UserByName(ctx context.Context, username string) (*User, error)
+ UserByID(ctx context.Context, id int64) (*User, error)
ListUsers(ctx context.Context) ([]User, error)
// SetPassword also ends all of the user's sessions and app passwords
- // and, for a temporary password (mustChange), their share links.
+ // and, for a temporary password (mustChange), their share links and
+ // passkeys.
SetPassword(ctx context.Context, userID int64, passwordHash string, mustChange bool) error
// DeleteUser also deletes the user's sessions, app passwords and share
// links.
@@ -149,6 +151,17 @@ type Store interface {
// hashes.
SetRecoveryCodes(ctx context.Context, userID int64, hashes [][]byte) error
+ // CreatePasskey stores pk and sets its ID and CreatedAt; ErrTooMany if
+ // its user has MaxPasskeys, ErrExists if its credential is stored
+ // already.
+ CreatePasskey(ctx context.Context, pk *Passkey) error
+ // Passkeys lists userID's passkeys, oldest first.
+ Passkeys(ctx context.Context, userID int64) ([]Passkey, error)
+ // UsePasskey notes that the passkey id was used, now with credential.
+ UsePasskey(ctx context.Context, id int64, credential []byte) error
+ // DeletePasskey deletes userID's passkey id (ErrNotFound if none).
+ DeletePasskey(ctx context.Context, userID, id int64) error
+
// CreateSession starts a session for u, unless u was deleted or changed
// password since it was read (ErrNotFound). It may drop the user's
// oldest sessions to bound their number.
diff --git a/internal/db/db_test.go b/internal/db/db_test.go
index 89f9759..e46698a 100644
--- a/internal/db/db_test.go
+++ b/internal/db/db_test.go
@@ -56,7 +56,7 @@ func TestConcurrentMigrations(t *testing.T) {
if err := pools[0].QueryRow(ctx, "SELECT count(*) FROM casbin_rule").Scan(&rules); err != nil {
t.Fatal(err)
}
- if versions != 11 || rules != 9 {
+ if versions != 12 || rules != 9 {
t.Errorf("%d migrations recorded, %d rules seeded", versions, rules)
}
}
diff --git a/internal/db/migrations/012_passkeys.sql b/internal/db/migrations/012_passkeys.sql
new file mode 100644
index 0000000..cea2d03
--- /dev/null
+++ b/internal/db/migrations/012_passkeys.sql
@@ -0,0 +1,13 @@
+-- Passkeys (WebAuthn credentials) sign their users in without a password.
+-- credential holds what checking one takes, as JSON: its public key, sign
+-- counter and flags; credential_id is the authenticator's name for it.
+CREATE TABLE passkeys (
+ id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
+ user_id BIGINT NOT NULL REFERENCES users (id) ON DELETE CASCADE,
+ name TEXT NOT NULL CHECK (length(name) BETWEEN 1 AND 64),
+ credential_id BYTEA NOT NULL UNIQUE,
+ credential BYTEA NOT NULL,
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ last_used_at TIMESTAMPTZ
+);
+CREATE INDEX passkeys_user_id_idx ON passkeys (user_id);
diff --git a/internal/server/auth.go b/internal/server/auth.go
index 084bc1b..589a357 100644
--- a/internal/server/auth.go
+++ b/internal/server/auth.go
@@ -248,18 +248,10 @@ func (s *Server) readFormValues(c fiber.Ctx) (url.Values, bool, error) {
if !isJSON && mediaType != fiber.MIMEApplicationForm {
return nil, false, fiber.ErrUnsupportedMediaType
}
- body := s.requestBody(c)
- // Unlike an upload, a form has to arrive within one read timeout, so a
- // client trickling it cannot hold the connection.
- body.deadline = time.Now().Add(body.timeout)
- data, err := io.ReadAll(io.LimitReader(body, maxFormSize+1))
+ data, err := s.readSmallBody(c)
if err != nil {
- return nil, isJSON, s.uploadError(body, err)
- }
- if len(data) > maxFormSize {
- return nil, isJSON, fiber.ErrRequestEntityTooLarge
+ return nil, isJSON, err
}
- s.finishBody(c, body)
if !isJSON {
values, err := url.ParseQuery(string(data))
@@ -290,6 +282,23 @@ func (s *Server) readFormValues(c fiber.Ctx) (url.Values, bool, error) {
return values, true, nil
}
+// readSmallBody reads a body of up to maxFormSize, such as a form.
+func (s *Server) readSmallBody(c fiber.Ctx) ([]byte, error) {
+ body := s.requestBody(c)
+ // Unlike an upload, a form has to arrive within one read timeout, so a
+ // client trickling it cannot hold the connection.
+ body.deadline = time.Now().Add(body.timeout)
+ data, err := io.ReadAll(io.LimitReader(body, maxFormSize+1))
+ if err != nil {
+ return nil, s.uploadError(body, err)
+ }
+ if len(data) > maxFormSize {
+ return nil, fiber.ErrRequestEntityTooLarge
+ }
+ s.finishBody(c, body)
+ return data, nil
+}
+
// signInsPerMinute bounds a user's successful password checks: hashing
// costs as much for valid credentials as for guesses.
var signInsPerMinute = 30
diff --git a/internal/server/passkey.go b/internal/server/passkey.go
new file mode 100644
index 0000000..3979561
--- /dev/null
+++ b/internal/server/passkey.go
@@ -0,0 +1,269 @@
+package server
+
+import (
+ "encoding/json"
+ "errors"
+ "mime"
+ "net/url"
+ "strconv"
+ "strings"
+ "time"
+
+ "github.com/gofiber/fiber/v3"
+ "go.uber.org/zap"
+
+ "goftp/internal/auth"
+)
+
+// Passkeys (see auth.Passkey): the sign-in page offers them, the Passkeys
+// page makes and deletes them. Browsers talk to both in JSON, as WebAuthn
+// takes it.
+const (
+ passkeyLoginPath = authPrefix + "passkey"
+ passkeysPath = authPrefix + "passkeys"
+)
+
+// passkeyStartsPerMinute bounds how often a client may start signing in
+// with a passkey: each start is kept a while.
+var passkeyStartsPerMinute = 30
+
+// passkeyRequest is what browsers send about passkeys.
+type passkeyRequest struct {
+ Action string `json:"action"`
+ Token string `json:"token"`
+ Name string `json:"name"`
+ Password string `json:"password"`
+ Next string `json:"next"`
+ Credential json.RawMessage `json:"credential"`
+}
+
+// siteOf is where the visitor of c makes and uses passkeys.
+func siteOf(c fiber.Ctx) auth.Site { return auth.Site{Host: c.Hostname(), Origin: c.BaseURL()} }
+
+// readJSON reads a small JSON body into v.
+func (s *Server) readJSON(c fiber.Ctx, v any) error {
+ if mediaType, _, _ := mime.ParseMediaType(c.Get(fiber.HeaderContentType)); mediaType != fiber.MIMEApplicationJSON {
+ return fiber.ErrUnsupportedMediaType
+ }
+ data, err := s.readSmallBody(c)
+ if err != nil {
+ return err
+ }
+ if json.Unmarshal(data, v) != nil {
+ return fiber.ErrBadRequest
+ }
+ return nil
+}
+
+// sendOptions answers the start of a passkey ceremony: the options for the
+// browser, and the token that goes with its answer.
+func sendOptions(c fiber.Ctx, options []byte, token string) error {
+ c.Set(fiber.HeaderCacheControl, "no-store")
+ return c.JSON(fiber.Map{"options": json.RawMessage(options), "token": token})
+}
+
+// passkeyLogin signs in with a passkey:
+//
+// {"action": "begin"} the options for
+// navigator.credentials.get
+// {"action": "finish", "token": ..., "credential": ...} what it answered,
+// with "next" for where
+// to go then
+func (s *Server) passkeyLogin(c fiber.Ctx) error {
+ var req passkeyRequest
+ if err := s.readJSON(c, &req); err != nil {
+ return err
+ }
+ ctx, cancel := dbContext(c)
+ defer cancel()
+ switch req.Action {
+ case "begin":
+ if wait := s.passkeyStarts.attempt(clientKey(c.IP()), true, time.Now()); wait > 0 {
+ retryAfter(c, wait)
+ return fiber.ErrTooManyRequests
+ }
+ options, token, err := s.auth.BeginPasskeyLogin(siteOf(c))
+ if errors.Is(err, auth.ErrBusy) {
+ retryAfter(c, time.Second)
+ return fiber.ErrServiceUnavailable
+ }
+ if err != nil {
+ return err
+ }
+ return sendOptions(c, options, token)
+ case "finish":
+ default:
+ return fiber.ErrBadRequest
+ }
+
+ check, wait := s.checkCode(c)
+ if wait > 0 {
+ retryAfter(c, wait)
+ return explain(fiber.ErrTooManyRequests, tooMany)
+ }
+ sess, err := s.auth.PasskeyLogin(ctx, req.Token, req.Credential)
+ switch {
+ case errors.Is(err, auth.ErrCeremonyGone):
+ check.refund()
+ return explain(fiber.ErrUnauthorized, "It took too long: try again.")
+ case errors.Is(err, auth.ErrPasskeyRefused), errors.Is(err, auth.ErrInvalidCredentials):
+ s.log.Warn("passkey refused", zap.String("ip", c.IP()), zap.Error(err))
+ return explain(fiber.ErrUnauthorized, "That passkey does not sign anyone in here. Sign in with your password, then add it under Passkeys.")
+ case err != nil:
+ check.refund()
+ return err
+ }
+ check.refund()
+ s.log.Info("login", zap.String("ip", c.IP()), zap.String("user", sess.User.Username), zap.Bool("passkey", true))
+ s.setCookie(c, sess)
+ next := safeNext(req.Next)
+ if sess.User.MustChangePassword {
+ next = passwordPath + "?next=" + url.QueryEscape(next)
+ }
+ c.Set(fiber.HeaderCacheControl, "no-store")
+ return c.JSON(fiber.Map{"next": next})
+}
+
+type passkeysPage struct {
+ page
+ Keys []passkeyView
+ Notice string
+ Error string
+}
+
+type passkeyView struct {
+ ID int64
+ Name string
+ Created, CreatedISO string
+ LastUsed, LastUsedISO string // "" if never
+}
+
+var passkeyNotices = map[string]string{
+ "added": "The passkey was added: it signs you in on this site, without your password.",
+ "deleted": "The passkey was deleted. Remove it from the device too, under its passwords or passkeys.",
+}
+
+func (s *Server) passkeysPage(c fiber.Ctx) error {
+ if userOf(c) == nil {
+ return s.deny(c)
+ }
+ return s.renderPasskeys(c, fiber.StatusOK, passkeyNotices[c.Query("done")], "")
+}
+
+func (s *Server) renderPasskeys(c fiber.Ctx, status int, notice, failure string) error {
+ ctx, cancel := dbContext(c)
+ defer cancel()
+ keys, err := s.auth.Passkeys(ctx, userOf(c))
+ if err != nil {
+ return err
+ }
+ data := passkeysPage{page: s.page(c, "Passkeys"), Notice: notice, Error: failure}
+ for _, k := range keys {
+ v := passkeyView{ID: k.ID, Name: k.Name, Created: shownTime(k.CreatedAt), CreatedISO: isoTime(k.CreatedAt)}
+ if !k.LastUsedAt.IsZero() {
+ v.LastUsed, v.LastUsedISO = shownTime(k.LastUsedAt), isoTime(k.LastUsedAt)
+ }
+ data.Keys = append(data.Keys, v)
+ }
+ return s.render(c, status, "passkeys", data)
+}
+
+// passkeysAction makes and deletes the visitor's passkeys:
+//
+// {"action": "begin", "password": ...} the options for
+// navigator.credentials.create
+// {"action": "finish", "token": ..., "name": ..., makes the passkey of what
+// "credential": ...} it answered
+// action=delete&id=ID deletes the passkey ID
+func (s *Server) passkeysAction(c fiber.Ctx) error {
+ u := userOf(c)
+ if u == nil {
+ return s.deny(c)
+ }
+ if mediaType, _, _ := mime.ParseMediaType(c.Get(fiber.HeaderContentType)); mediaType != fiber.MIMEApplicationJSON {
+ form, _, err := s.readForm(c)
+ if err != nil {
+ return err
+ }
+ if form["action"] != "delete" {
+ return fiber.ErrBadRequest
+ }
+ return s.deletePasskey(c, u, form["id"])
+ }
+ var req passkeyRequest
+ if err := s.readJSON(c, &req); err != nil {
+ return err
+ }
+ ctx, cancel := dbContext(c)
+ defer cancel()
+ switch req.Action {
+ case "begin":
+ check, wait := s.checkPassword(c, u.Username)
+ if wait > 0 {
+ retryAfter(c, wait)
+ return explain(fiber.ErrTooManyRequests, tooMany)
+ }
+ options, token, err := s.auth.BeginPasskey(ctx, u, req.Password, siteOf(c))
+ switch {
+ case errors.Is(err, auth.ErrInvalidCredentials):
+ s.log.Warn("passkey refused: wrong password", zap.String("ip", c.IP()), zap.String("user", u.Username))
+ return explain(fiber.ErrForbidden, "The password is wrong.")
+ case errors.Is(err, auth.ErrTooMany):
+ check.succeeded()
+ return explain(fiber.ErrConflict, "You have "+strconv.Itoa(auth.MaxPasskeys)+" passkeys. Delete one first.")
+ case errors.Is(err, auth.ErrBusy):
+ check.refund()
+ retryAfter(c, time.Second)
+ return explain(fiber.ErrServiceUnavailable, busy)
+ case err != nil:
+ check.refund()
+ return err
+ }
+ check.succeeded()
+ return sendOptions(c, options, token)
+ case "finish":
+ pk, err := s.auth.FinishPasskey(ctx, u, req.Token, req.Name, req.Credential)
+ switch {
+ case errors.Is(err, auth.ErrInvalid):
+ return explain(fiber.ErrBadRequest, "Name the passkey in up to 64 characters, e.g. the device it is on.")
+ case errors.Is(err, auth.ErrCeremonyGone):
+ return explain(fiber.ErrConflict, "It took too long: try again.")
+ case errors.Is(err, auth.ErrPasskeyRefused):
+ s.log.Warn("passkey refused", zap.String("ip", c.IP()), zap.String("user", u.Username), zap.Error(err))
+ return explain(fiber.ErrBadRequest, "The browser's answer did not check out: try again.")
+ case errors.Is(err, auth.ErrExists):
+ return explain(fiber.ErrConflict, "That passkey is in use already.")
+ case errors.Is(err, auth.ErrTooMany):
+ return explain(fiber.ErrConflict, "You have "+strconv.Itoa(auth.MaxPasskeys)+" passkeys. Delete one first.")
+ case err != nil:
+ return err
+ }
+ s.log.Info("passkey added", zap.String("ip", c.IP()), zap.String("user", u.Username), zap.Int64("passkey", pk.ID))
+ return c.Status(fiber.StatusCreated).JSON(fiber.Map{"id": pk.ID, "name": pk.Name})
+ }
+ return fiber.ErrBadRequest
+}
+
+func (s *Server) deletePasskey(c fiber.Ctx, u *auth.User, idText string) error {
+ id, err := strconv.ParseInt(idText, 10, 64)
+ if err != nil {
+ return fiber.ErrBadRequest
+ }
+ ctx, cancel := dbContext(c)
+ defer cancel()
+ html := strings.Contains(c.Get(fiber.HeaderAccept), fiber.MIMETextHTML)
+ err = s.auth.DeletePasskey(ctx, u, id)
+ switch {
+ case errors.Is(err, auth.ErrNotFound) && html:
+ return s.renderPasskeys(c, fiber.StatusNotFound, "", "There is no such passkey: it may have been deleted already.")
+ case errors.Is(err, auth.ErrNotFound):
+ return fiber.ErrNotFound
+ case err != nil:
+ return err
+ }
+ s.log.Info("passkey deleted", zap.String("ip", c.IP()), zap.String("user", u.Username), zap.Int64("passkey", id))
+ if html {
+ return s.redirect(c, passkeysPath+"?done=deleted")
+ }
+ return c.SendStatus(fiber.StatusNoContent)
+}
diff --git a/internal/server/passkey_test.go b/internal/server/passkey_test.go
new file mode 100644
index 0000000..ad9fe57
--- /dev/null
+++ b/internal/server/passkey_test.go
@@ -0,0 +1,184 @@
+package server
+
+import (
+ "encoding/json"
+ "net/http"
+ "strconv"
+ "strings"
+ "testing"
+
+ "github.com/descope/virtualwebauthn"
+)
+
+// Test requests come from http://example.com.
+var testRP = virtualwebauthn.RelyingParty{Name: "goftp", ID: "example.com", Origin: "http://example.com"}
+
+// postJSON posts body as JSON as the client f, and decodes the answer
+// into out, if it is JSON.
+func postJSON(t *testing.T, f *fixture, uri string, body any, out any) (*http.Response, string) {
+ t.Helper()
+ data, err := json.Marshal(body)
+ if err != nil {
+ t.Fatal(err)
+ }
+ resp, raw := f.send(t, "POST", uri, strings.NewReader(string(data)), "Content-Type", "application/json")
+ if out != nil && strings.HasPrefix(resp.Header.Get("Content-Type"), "application/json") {
+ if err := json.Unmarshal([]byte(raw), out); err != nil {
+ t.Fatal(err)
+ }
+ }
+ return resp, raw
+}
+
+type ceremonyStart struct {
+ Options json.RawMessage
+ Token string
+}
+
+// addPasskey makes a passkey named name for the user of f, whose password
+// is password, on a new authenticator, which it returns with the key.
+func addPasskey(t *testing.T, f *fixture, password, name string) (virtualwebauthn.Authenticator, virtualwebauthn.Credential) {
+ t.Helper()
+ var start ceremonyStart
+ resp, body := postJSON(t, f, passkeysPath, map[string]string{"action": "begin", "password": password}, &start)
+ if resp.StatusCode != http.StatusOK || start.Token == "" {
+ t.Fatalf("begin: %d %s", resp.StatusCode, body)
+ }
+ opts, err := virtualwebauthn.ParseAttestationOptions(string(start.Options))
+ if err != nil {
+ t.Fatal(err)
+ }
+ a := virtualwebauthn.NewAuthenticatorWithOptions(virtualwebauthn.AuthenticatorOptions{UserHandle: []byte(opts.UserID)})
+ cred := virtualwebauthn.NewCredential(virtualwebauthn.KeyTypeEC2)
+ answer := json.RawMessage(virtualwebauthn.CreateAttestationResponse(testRP, a, cred, *opts))
+ resp, body = postJSON(t, f, passkeysPath, map[string]any{"action": "finish", "token": start.Token, "name": name, "credential": answer}, nil)
+ if resp.StatusCode != http.StatusCreated {
+ t.Fatalf("finish: %d %s", resp.StatusCode, body)
+ }
+ a.AddCredential(cred)
+ return a, cred
+}
+
+// passkeySignIn signs in anonymously with the passkey cred of a.
+func passkeySignIn(t *testing.T, f *fixture, a virtualwebauthn.Authenticator, cred virtualwebauthn.Credential, next string) (*http.Response, string) {
+ t.Helper()
+ anon := f.as("")
+ var start ceremonyStart
+ if resp, body := postJSON(t, anon, passkeyLoginPath, map[string]string{"action": "begin"}, &start); resp.StatusCode != http.StatusOK {
+ t.Fatalf("begin: %d %s", resp.StatusCode, body)
+ }
+ opts, err := virtualwebauthn.ParseAssertionOptions(string(start.Options))
+ if err != nil {
+ t.Fatal(err)
+ }
+ answer := json.RawMessage(virtualwebauthn.CreateAssertionResponse(testRP, a, cred, *opts))
+ return postJSON(t, anon, passkeyLoginPath, map[string]any{"action": "finish", "token": start.Token, "next": next, "credential": answer}, nil)
+}
+
+func TestPasskeySignIn(t *testing.T) {
+ ta := newTestAuth(t)
+ f := newFixtureWith(t, ta)
+ dora := f.signedIn(ta.addUser(t, "dora", "user"))
+ html := []string{"Accept", "text/html"}
+
+ if _, body := dora.do(t, "GET", "/", html...); !strings.Contains(body, ``) {
+ t.Error("no menu entry")
+ }
+ if _, body := f.as("").do(t, "GET", loginPath, html...); !strings.Contains(body, `autocomplete="username webauthn"`) || !strings.Contains(body, `id="passkey-signin"`) {
+ t.Errorf("login page: %s", body)
+ }
+ _, body := dora.do(t, "GET", passkeysPath, html...)
+ if !strings.Contains(body, "You have no passkeys.") || !strings.Contains(body, `id="add-passkey"`) {
+ t.Errorf("no passkeys: %s", body)
+ }
+
+ // Adding one takes the password.
+ if resp, body := postJSON(t, dora, passkeysPath, map[string]string{"action": "begin", "password": "wrong"}, nil); resp.StatusCode != http.StatusForbidden ||
+ !strings.Contains(body, "The password is wrong.") {
+ t.Errorf("wrong password: %d %s", resp.StatusCode, body)
+ }
+ if resp, _ := post(t, dora, passkeysPath, "action=begin"); resp.StatusCode != http.StatusBadRequest {
+ t.Errorf("as a form: %d", resp.StatusCode)
+ }
+ a, cred := addPasskey(t, dora, testPassword("dora"), "laptop")
+ _, body = dora.do(t, "GET", passkeysPath, html...)
+ if !strings.Contains(body, "laptop ") || !strings.Contains(body, `never `) {
+ t.Errorf("listed: %s", body)
+ }
+
+ // It signs dora in, without a password, and her browser goes on.
+ resp, body := passkeySignIn(t, f, a, cred, "/docs/")
+ var done struct{ Next string }
+ if resp.StatusCode != http.StatusOK || json.Unmarshal([]byte(body), &done) != nil || done.Next != "/docs/" {
+ t.Fatalf("signed in: %d %s", resp.StatusCode, body)
+ }
+ cookie := cookieOf(resp, cookieName)
+ if cookie == nil {
+ t.Fatal("no session cookie")
+ }
+ if _, body := f.as("").do(t, "GET", "/", "Accept", "text/html", "Cookie", cookieName+"="+cookie.Value); !strings.Contains(body, "Signed in as dora ") {
+ t.Errorf("the session: %s", body)
+ }
+ if e := f.logs.entries("login"); len(e) == 0 || e[len(e)-1]["passkey"] != true {
+ t.Errorf("logged: %v", e)
+ }
+ if resp, _ := passkeySignIn(t, f, a, cred, "https://evil.example/"); resp.StatusCode != http.StatusOK {
+ t.Errorf("signed in again: %d", resp.StatusCode)
+ } else if _, body := passkeySignIn(t, f, a, cred, "//evil.example/"); !strings.Contains(body, `"next":"/"`) {
+ t.Errorf("next leads elsewhere: %s", body)
+ }
+
+ // With two-factor sign-in, no code after it.
+ _, _, dora = setUpTwoFactor(t, dora)
+ if resp, _ := passkeySignIn(t, f, a, cred, "/"); resp.StatusCode != http.StatusOK {
+ t.Errorf("with two-factor sign-in: %d", resp.StatusCode)
+ }
+
+ // Passkeys it does not know, and answers that do not check out, are
+ // refused.
+ stranger := virtualwebauthn.NewCredential(virtualwebauthn.KeyTypeEC2)
+ a.AddCredential(stranger)
+ if resp, body := passkeySignIn(t, f, a, stranger, "/"); resp.StatusCode != http.StatusUnauthorized || !strings.Contains(body, "does not sign anyone in here") {
+ t.Errorf("an unknown passkey: %d %s", resp.StatusCode, body)
+ }
+ if resp, body := postJSON(t, f.as(""), passkeyLoginPath, map[string]any{"action": "finish", "token": strings.Repeat("x", 43), "credential": map[string]string{}}, nil); resp.StatusCode != http.StatusUnauthorized ||
+ !strings.Contains(body, "It took too long") {
+ t.Errorf("no such ceremony: %d %s", resp.StatusCode, body)
+ }
+ if resp, _ := f.as("").send(t, "POST", passkeyLoginPath, strings.NewReader("action=begin"), "Content-Type", formType); resp.StatusCode != http.StatusUnsupportedMediaType {
+ t.Errorf("as a form: %d", resp.StatusCode)
+ }
+
+ // Deleted, it signs nobody in.
+ u, err := ta.svc.UserNamed(t.Context(), "dora")
+ if err != nil {
+ t.Fatal(err)
+ }
+ keys, err := ta.svc.Passkeys(t.Context(), u)
+ if err != nil || len(keys) != 1 {
+ t.Fatalf("passkeys: %v, %v", keys, err)
+ }
+ resp, _ = post(t, dora, passkeysPath, "action=delete&id="+strconv.FormatInt(keys[0].ID, 10), html...)
+ if resp.StatusCode != http.StatusSeeOther || resp.Header.Get("Location") != passkeysPath+"?done=deleted" {
+ t.Errorf("deleted: %d %v", resp.StatusCode, resp.Header)
+ }
+ if resp, _ := passkeySignIn(t, f, a, cred, "/"); resp.StatusCode != http.StatusUnauthorized {
+ t.Errorf("a deleted passkey: %d", resp.StatusCode)
+ }
+ if resp, _ := post(t, dora, passkeysPath, "action=delete&id="+strconv.FormatInt(keys[0].ID, 10)); resp.StatusCode != http.StatusNotFound {
+ t.Errorf("deleted twice: %d", resp.StatusCode)
+ }
+}
+
+// Starting passkey sign-ins is limited per client.
+func TestPasskeyStartLimit(t *testing.T) {
+ defer func(n int) { passkeyStartsPerMinute = n }(passkeyStartsPerMinute)
+ passkeyStartsPerMinute = 2
+ f := newFixture(t).as("")
+ for i := range 3 {
+ resp, _ := postJSON(t, f, passkeyLoginPath, map[string]string{"action": "begin"}, nil)
+ if want := map[bool]int{true: http.StatusOK, false: http.StatusTooManyRequests}[i < 2]; resp.StatusCode != want {
+ t.Errorf("start %d: %d", i, resp.StatusCode)
+ }
+ }
+}
diff --git a/internal/server/server.go b/internal/server/server.go
index 55e3962..324da69 100644
--- a/internal/server/server.go
+++ b/internal/server/server.go
@@ -66,9 +66,11 @@ type Server struct {
proxyNoted atomic.Bool
shareGuesses *rateLimiter // password checks per share link
- thumbs *thumbCache
- thumbing chan struct{} // thumbnails being made
- thumbWait time.Duration // for a turn to make one
+ // passkeyStarts are the passkey sign-ins started per client.
+ passkeyStarts *rateLimiter
+ thumbs *thumbCache
+ thumbing chan struct{} // thumbnails being made
+ thumbWait time.Duration // for a turn to make one
}
func New(cfg *config.Config, log *zap.Logger, authSvc *auth.Service) (*Server, error) {
@@ -153,6 +155,7 @@ func New(cfg *config.Config, log *zap.Logger, authSvc *auth.Service) (*Server, e
}
s.signIns = newRateLimiter(signInsPerMinute, time.Minute)
s.shareGuesses = newRateLimiter(shareGuessesPerMinute, time.Minute)
+ s.passkeyStarts = newRateLimiter(passkeyStartsPerMinute, time.Minute)
s.thumbs = newThumbCache(cfg.Cache.Dir, int64(cfg.Cache.MaxSize), log)
s.thumbing, s.thumbWait = make(chan struct{}, thumbConcurrency()), 30*time.Second
s.app.Use(s.noteProxyHeaders, s.checkOrigin, s.identify, s.requirePasswordChange)
@@ -163,6 +166,9 @@ func New(cfg *config.Config, log *zap.Logger, authSvc *auth.Service) (*Server, e
s.app.Post(passwordPath, s.changePassword)
s.app.Get(twoFactorPath, s.twoFactorPage)
s.app.Post(twoFactorPath, s.twoFactorAction)
+ s.app.Post(passkeyLoginPath, s.passkeyLogin)
+ s.app.Get(passkeysPath, s.passkeysPage)
+ s.app.Post(passkeysPath, s.passkeysAction)
s.app.Get(strings.TrimSuffix(adminPath, "/"), s.adminHome)
s.app.Get(adminPath, s.adminHome)
s.app.Get(usersPath, s.usersPage)
diff --git a/internal/server/server_unix_test.go b/internal/server/server_unix_test.go
index 7d73cc6..ab54647 100644
--- a/internal/server/server_unix_test.go
+++ b/internal/server/server_unix_test.go
@@ -71,7 +71,7 @@ func TestSymlinks(t *testing.T) {
}
}
for _, hidden := range []string{"to-outside", "to-secret", "to-parent", "abs-inside", "dangling", "pub", "env", "deep"} {
- if strings.Contains(body, hidden) {
+ if strings.Contains(body, `data-name="`+hidden+`"`) || strings.Contains(body, `href="/`+hidden) || strings.Contains(body, ">"+hidden+"<") {
t.Errorf("listing shows unusable link %s", hidden)
}
}
diff --git a/internal/server/templates/admin.html b/internal/server/templates/admin.html
index c30019b..e9a5a5d 100644
--- a/internal/server/templates/admin.html
+++ b/internal/server/templates/admin.html
@@ -71,7 +71,7 @@ Add a user
diff --git a/internal/server/templates/app.js b/internal/server/templates/app.js
index 38aba4a..8387f64 100644
--- a/internal/server/templates/app.js
+++ b/internal/server/templates/app.js
@@ -39,13 +39,125 @@
// Confirmations are shown once, not again on reload.
const params = new URLSearchParams(location.search);
- const shown = ["uploaded", "created", "renamed", "restored", "deleted", "undo", "trashed", "moved", "copied", "to", "done", "granted", "ungranted"]
+ const shown = ["uploaded", "created", "renamed", "restored", "deleted", "undo", "trashed", "moved", "copied", "to", "done", "granted", "ungranted", "recovered"]
.filter(p => params.has(p));
if (shown.length) {
for (const p of shown) params.delete(p);
history.replaceState(null, "", location.pathname + (params.size ? "?" + params : ""));
}
+ // Passkeys (WebAuthn): the server sends and takes binary values in
+ // base64url, which browsers that lack the JSON forms get converted.
+ const fromB64 = s => {
+ s = s.replace(/-/g, "+").replace(/_/g, "/");
+ return Uint8Array.from(atob(s + "=".repeat((4 - s.length % 4) % 4)), c => c.charCodeAt(0));
+ };
+ const toB64 = buf => btoa(String.fromCharCode(...new Uint8Array(buf))).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
+ const ids = list => (list || []).map(c => ({ ...c, id: fromB64(c.id) }));
+ const creationOptions = o => PublicKeyCredential.parseCreationOptionsFromJSON
+ ? PublicKeyCredential.parseCreationOptionsFromJSON(o)
+ : { ...o, challenge: fromB64(o.challenge), user: { ...o.user, id: fromB64(o.user.id) }, excludeCredentials: ids(o.excludeCredentials) };
+ const requestOptions = o => PublicKeyCredential.parseRequestOptionsFromJSON
+ ? PublicKeyCredential.parseRequestOptionsFromJSON(o)
+ : { ...o, challenge: fromB64(o.challenge), allowCredentials: ids(o.allowCredentials) };
+ const credentialJSON = cred => {
+ try {
+ if (cred.toJSON) return cred.toJSON();
+ } catch {}
+ const r = cred.response;
+ const out = { id: cred.id, rawId: toB64(cred.rawId), type: cred.type, authenticatorAttachment: cred.authenticatorAttachment,
+ clientExtensionResults: cred.getClientExtensionResults(), response: { clientDataJSON: toB64(r.clientDataJSON) } };
+ if (r.attestationObject) {
+ out.response.attestationObject = toB64(r.attestationObject);
+ out.response.transports = r.getTransports ? r.getTransports() : [];
+ }
+ if (r.authenticatorData) {
+ out.response.authenticatorData = toB64(r.authenticatorData);
+ out.response.signature = toB64(r.signature);
+ out.response.userHandle = r.userHandle ? toB64(r.userHandle) : null;
+ }
+ return out;
+ };
+ const postJSON = async (url, body) => {
+ let resp = null;
+ try {
+ resp = await fetch(url, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) });
+ } catch {
+ throw new Error("The connection was lost. Try again.");
+ }
+ if (!resp.ok) throw new Error((await detailOf(resp)) || `It did not work (error ${resp.status}).`);
+ return resp.json();
+ };
+ const passkeyFailed = (e, cancelled) => e.name === "NotAllowedError" ? cancelled
+ : e.name === "InvalidStateError" ? "This device has a passkey for you here already."
+ : e.message || "The passkey did not work. Try again.";
+
+ // Signing in with a passkey: with the button, or by picking one where the
+ // browser offers them, under the username.
+ const passkeyBox = $(".passkey-signin");
+ if (passkeyBox && window.PublicKeyCredential) {
+ passkeyBox.hidden = false;
+ const error = $(".popover-error", passkeyBox);
+ const button = $("#passkey-signin");
+ const next = ($("input[name=next]") || {}).value || "/";
+ let waiting = null;
+ const signIn = async mediation => {
+ const { options, token } = await postJSON("/.auth/passkey", { action: "begin" });
+ const abort = new AbortController();
+ if (mediation === "conditional") waiting = abort;
+ else if (waiting) waiting.abort();
+ const cred = await navigator.credentials.get({ publicKey: requestOptions(options.publicKey), mediation, signal: abort.signal });
+ const done = await postJSON("/.auth/passkey", { action: "finish", token, next, credential: credentialJSON(cred) });
+ location.assign(done.next);
+ };
+ button.addEventListener("click", async () => {
+ error.hidden = true;
+ button.disabled = true;
+ try {
+ await signIn("optional");
+ } catch (e) {
+ error.textContent = passkeyFailed(e, "No passkey was picked, or this device has none for this site.");
+ error.hidden = false;
+ }
+ button.disabled = false;
+ });
+ if (PublicKeyCredential.isConditionalMediationAvailable) {
+ PublicKeyCredential.isConditionalMediationAvailable().then(ok => ok && signIn("conditional")).catch(e => {
+ if (e.name !== "AbortError" && e.name !== "NotAllowedError") {
+ error.textContent = passkeyFailed(e, "");
+ error.hidden = false;
+ }
+ });
+ }
+ }
+
+ // Adding a passkey, after the password.
+ const addPasskey = $("#add-passkey");
+ if (addPasskey) {
+ const error = addPasskey.parentElement.querySelector(".popover-error");
+ if (!window.PublicKeyCredential) {
+ addPasskey.hidden = true;
+ $(".passkey-unsupported").hidden = false;
+ }
+ const submit = $("button[type=submit]", addPasskey);
+ addPasskey.addEventListener("submit", async e => {
+ e.preventDefault();
+ error.hidden = true;
+ submit.disabled = true;
+ try {
+ const { options, token } = await postJSON("/.auth/passkeys", { action: "begin", password: addPasskey.elements.password.value });
+ const cred = await navigator.credentials.create({ publicKey: creationOptions(options.publicKey) });
+ await postJSON("/.auth/passkeys", { action: "finish", token, name: addPasskey.elements.name.value, credential: credentialJSON(cred) });
+ location.assign("/.auth/passkeys?done=added");
+ return;
+ } catch (e) {
+ error.textContent = passkeyFailed(e, "The passkey was not made: it was cancelled, or took too long.");
+ error.hidden = false;
+ }
+ submit.disabled = false;
+ });
+ }
+
// Times in the visitor's time zone.
const when = new Intl.DateTimeFormat(undefined, { dateStyle: "medium", timeStyle: "short" });
for (const t of $$("time[datetime]")) {
diff --git a/internal/server/templates/base.html b/internal/server/templates/base.html
index 56ae273..9a50f9c 100644
--- a/internal/server/templates/base.html
+++ b/internal/server/templates/base.html
@@ -440,6 +440,10 @@
.qr-key code { overflow-wrap: anywhere; font-size: 14px; letter-spacing: 0.06em; }
.recovery-codes { display: grid; grid-template-columns: repeat(2, max-content); gap: 4px 24px; margin: 0; padding: 0; list-style: none; }
.recovery-codes code { font-size: 15px; letter-spacing: 0.04em; }
+ .passkey-signin { display: flex; flex-direction: column; gap: 12px; margin-top: 16px; }
+ .passkey-signin[hidden] { display: none; }
+ .or { display: flex; align-items: center; gap: 12px; color: var(--faint); font-size: 13px; }
+ .or::before, .or::after { content: ""; flex: 1; border-top: 1px solid var(--border); }
.shares-section { margin-top: 28px; }
.shares-section:first-of-type { margin-top: 0; }
.shares-section > h2 { margin-bottom: 10px; font-size: 16px; }
@@ -780,6 +784,7 @@
{{if .Admin}} Users and rules {{end}}
Sync
Change password
+ Passkeys
Two-factor sign-in
@@ -822,6 +827,7 @@
+
diff --git a/internal/server/templates/login.html b/internal/server/templates/login.html
index 4d370ea..e4014ab 100644
--- a/internal/server/templates/login.html
+++ b/internal/server/templates/login.html
@@ -24,7 +24,7 @@ Sign in
{{with .Error}}{{.}}
{{end}}
Username
-
+
Password
@@ -32,6 +32,11 @@ Sign in
Sign in
+
+
or
+
Sign in with a passkey
+
+
No account yet? Ask your administrator to create one.
{{end}}
diff --git a/internal/server/templates/passkeys.html b/internal/server/templates/passkeys.html
new file mode 100644
index 0000000..70ca1b9
--- /dev/null
+++ b/internal/server/templates/passkeys.html
@@ -0,0 +1,69 @@
+{{define "passkeys"}}{{template "head" .}}
+
+{{template "topbar" .}}
+
+
+
+
Passkeys
+
Sign in without your password, with your fingerprint, your face or a PIN on your phone, computer or security key. A passkey works only on this site, and nobody can steal it from a page made to look like it.
+
+
+
+ {{with .Notice}}{{.}}
{{end}}
+ {{with .Error}}{{.}}
{{end}}
+
+
+
+
+ {{if .Keys}}
+
+ Passkey Added Last used Delete
+
+ {{range .Keys}}
+
+ {{.Name}}
+ Added {{.Created}}
+ Last used {{if .LastUsed}}{{.LastUsed}} {{else}}never {{end}}
+
+
+
+
+
+
+
+ {{end}}
+
+
+ {{else}}
+
+
+
You have no passkeys.
+
Add one above, on each device you sign in from.
+
+ {{end}}
+
+
+{{template "footer" .}}
+{{template "icons"}}
+{{script}}
+
+