Remove passkey login
ci / test-guard (pull_request) Successful in 3s
ci / go (pull_request) Successful in 3m34s
ci / package (pull_request) Successful in 3m39s
ci / install-test (debian:13) (pull_request) Successful in 1m16s
ci / install-test (debian:12) (pull_request) Successful in 1m24s
ci / smb (pull_request) Successful in 1m15s
ci / e2e (pull_request) Successful in 3m6s

Owner's decision 2026-11-30 after a cost/value review. WebAuthn only works
when the UI is opened by host name with a trusted certificate; most homes and
small offices use an IP address and the self-signed certificate, where
passkeys don't work at all. For that it cost ~800 lines of security-relevant
code and 9 of the 11 Go dependencies (go-webauthn and what it pulls in: cbor,
go-tpm, jwt, uuid, mapstructure, msgp, …), each a source of update churn.

Removed: internal/app/passkeys, the /api/v1/auth/passkey/* and
/api/v1/me/passkeys* routes and their API description, auth.LoginVerified /
Failed / Blocked (only passkey login used them), the passkey button on the
login page, the Passkeys card on "My account", lib/webauthn.ts, the
dependencies (go mod tidy: go.mod now needs only pam and x/sys). F-AUT-6 is
marked dropped in 02-requirements with the reason. Password login, its
backoff and locked-account checks are unchanged.

Existing installations keep /var/lib/sharestead/passkeys.json; nothing reads
it any more (public keys only, no secret).

Effect: .deb 5.4 → 4.1 MB. Checked on CT 151: the passkey routes answer 404;
login, wrong password, self-service, own account, CSP and axe e2e tests pass
on desktop and phone.

Test changed because: these tests covered the removed passkey feature
(F-AUT-6, dropped by the owner) and are deleted with it:
internal/app/passkeys/passkeys_test.go; TestPasskeysNeedAHostName,
TestDeletingAUserForgetsTheirPasskeys, TestMyPasskeys,
TestPasskeyLoginIsBlockedDuringBackoff (internal/server);
TestPasskeyLoginOfLockedAccountIsRefused and the passkey half of
TestLockedAccountCantLogIn (internal/auth; its password half stays);
web/src/lib/webauthn.test.ts; the e2e test "passkeys: add one, log in with
it, remove it". The requirements they covered for passwords (backoff, locked
accounts, own account) keep their own tests.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
tandClaude Opus 5.5 committed 2026-11-30 18:38:43 +01:00
1 parent 4b732a49e4
commit 62b0f80b33
29 files changed
+11 -1126

No files matched your search

-1
View File
@@ -100,7 +100,6 @@ the filesystem owner (limits, ACLs) must be checked on both instances.
"personal folders", "storage limit") fail on CT 151 by design.
3. Take screenshots (desktop, phone, light and dark) and look at them critically.
Passkeys need a host name: start Chromium with `--host-resolver-rules=MAP sharestead.test 192.168.0.157`.
`ignoreHTTPSErrors` hides certificate errors, so it proves nothing about untrusted certificates.
## Git
-2
View File
@@ -30,7 +30,6 @@ import (
"sharestead/internal/app/health"
"sharestead/internal/app/homes"
"sharestead/internal/app/limitations"
"sharestead/internal/app/passkeys"
"sharestead/internal/app/quotas"
svcs "sharestead/internal/app/services"
"sharestead/internal/app/settings"
@@ -195,7 +194,6 @@ func run(listen, dataDir, adminGroup string, log *slog.Logger) error {
Quotas: quotasSvc,
Settings: appSettings,
DLNA: &dlna.Service{Store: store, Path: dlnaConf, Run: run, Access: osfs.FS{}, AllowedRoots: roots},
Passkeys: &passkeys.Service{Files: osfs.FS{}, Path: filepath.Join(dataDir, "passkeys.json")},
Updates: updatesSvc,
Capabilities: capabilitiesSvc,
Limitations: limitationsSvc,
+1 -1
View File
@@ -259,7 +259,7 @@ One share model, several ways to reach it. Each protocol is a module and can be
| F-AUT-4b | Behind a reverse proxy, the client IP for rate limiting comes from a configurable trusted proxy header (X-Forwarded-For), otherwise one person's typos would slow down everyone | S | v1 |
| F-AUT-5 | Re-authentication for dangerous actions (delete data, API keys, admin rights, services) | M | MVP |
| F-AUT-7 | **Self-service** ("My account") for normal users: change own password (needs the current one), see own storage and limits, the shares they can open with Read/Read & write and why, and how to connect (Windows, Mac, Linux). No other user's data, no admin actions (403 on every admin route, tested). One **global** on/off switch for admins (System page), no per-user setting; off ends user sessions. *Owner request 2026-11-29* | M | MVP |
| F-AUT-6 | **Passkey login** (WebAuthn) in addition to the password, when the user registered one; register/remove passkeys after a password confirmation; password stays as fallback. Preconditions (WebAuthn spec / browsers): the UI is opened by **host name**, not IP address, and with a **trusted certificate** — the UI explains both when missing. *Owner request 2026-11-29* — built: go-webauthn, discoverable credentials (no user name), random user handle, public keys in /var/lib/sharestead/passkeys.json, adding/removing needs a recent password, same login rules and backoff as passwords. Tested with Chromium's virtual authenticator on https://localhost and a mapped host name — with Playwright's ignoreHTTPSErrors, which hides certificate errors, so whether a browser allows passkeys after clicking past a certificate warning is **not verified**; plan for a trusted certificate | S | MVP |
| ~~F-AUT-6~~ | **Passkey login — dropped 2026-11-30** (owner's decision after a cost/value review): WebAuthn needs the UI opened by host name with a trusted certificate, which most homes and small offices don't have (IP address, self-signed certificate); for that it cost ~800 lines and 9 of the 11 Go dependencies. Password login stays. The built version is in the Git history (removed in the commit "Remove passkey login") | — | dropped |
| F-AUT-6 | TOTP 2FA for admins | S | v1 |
### API
+1 -13
View File
@@ -3,20 +3,8 @@ module sharestead
go 1.27.4
require (
github.com/fxamacker/cbor/v2 v2.9.4
github.com/go-webauthn/webauthn v0.18.2
github.com/msteinert/pam/v2 v2.1.0
golang.org/x/sys v0.50.0
)
require (
github.com/go-viper/mapstructure/v2 v2.5.0 // indirect
github.com/go-webauthn/x v0.3.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/philhofer/fwd v1.2.0 // indirect
github.com/tinylib/msgp v1.6.4 // indirect
github.com/x448/float16 v0.8.4 // indirect
golang.org/x/crypto v0.57.0 // indirect
)
require golang.org/x/term v0.46.0 // indirect
-30
View File
@@ -1,35 +1,5 @@
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/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-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/msteinert/pam/v2 v2.1.0 h1:er5F9TKV5nGFuTt12ubtqPHEUdeBwReP7vd3wovidGY=
github.com/msteinert/pam/v2 v2.1.0/go.mod h1:KT28NNIcDFf3PcBmNI2mIGO4zZJ+9RSs/At2PB3IDVc=
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/stretchr/testify v1.12.1 h1:EuwCh5fleGS7H32xRwO3wRGT7DxrDhLAT6FF8MpWDWE=
github.com/stretchr/testify v1.12.1/go.mod h1:MDEgiDPPsNp5cuIrHPPCyornHKgEVbtFUmoNlxoYthg=
github.com/tinylib/msgp v1.6.4 h1:mOwYbyYDLPj35mkA2BjjYejgJk9BuHxDdvRnb6v2ZcQ=
github.com/tinylib/msgp v1.6.4/go.mod h1:RSp0LW9oSxFut3KzESt5Voq4GVWyS+PSulT77roAqEA=
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/mock v0.6.0 h1:hyF9dfmbgIX5EfOdasqLsWD6xqpNZlXblLB/Dbnwv3Y=
go.uber.org/mock v0.6.0/go.mod h1:KiVJ4BqZJaMj4svdfmHM0AUx4NJYO8ZNpPnZn1Z+BBU=
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/sys v0.50.0 h1:dkKZEFTEKaLr1sjhs0WiKqoi8Jj5nHbS3Njmx1UoMJs=
golang.org/x/sys v0.50.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og=
golang.org/x/term v0.46.0 h1:3+OXuTbaKDgwk8jTi3aSLHRlmWqHEUDUtxnbFigO4YE=
+1 -1
View File
@@ -74,7 +74,7 @@ var shadowPath = "/etc/shadow"
// Usable checks /etc/shadow: a locked password ("usermod --lock"), no
// password at all, an expired account or a password expired past its
// inactivity period make the account unusable. pam_unix's account check
// ignores the lock, so this is checked here, also for passkey logins.
// ignores the lock, so this is checked here.
// Accounts without a shadow entry (e.g. from a directory service) pass.
func (PAM) Usable(name string) error {
data, err := os.ReadFile(shadowPath)
+1 -1
View File
@@ -66,7 +66,7 @@ reports/ current problems and the storage folder check
What is NOT inside
------------------
Passwords, password hashes, passkeys, the TLS key, sessions and API keys.
Passwords, password hashes, the TLS key, sessions and API keys.
Lines whose setting name contains "password", "secret" or "token", and
anything that looks like a Sharestead API key, are replaced by <removed>.
-383
View File
@@ -1,383 +0,0 @@
// Package passkeys is the use case "log in with a passkey" (WebAuthn):
// users register passkeys for their own account and log in without typing
// a password or user name. Only public keys are stored.
//
// WebAuthn binds a passkey to a host name (the relying party ID), not to an
// IP address, and browsers need a secure (HTTPS) page; the UI explains both.
package passkeys
import (
"crypto/rand"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"io/fs"
"net"
"strings"
"sync"
"time"
"github.com/go-webauthn/webauthn/protocol"
"github.com/go-webauthn/webauthn/webauthn"
)
// Errors.
var (
ErrHostIsIP = errors.New("passkeys need a host name, not an IP address")
ErrExpired = errors.New("the passkey request expired; start again")
ErrNotFound = errors.New("passkey not found")
ErrInvalid = errors.New("the passkey answer couldn't be verified")
ErrNoPasskeys = errors.New("unknown passkey")
)
// Files reads and writes the store (adapter).
type Files interface {
ReadFile(path string) ([]byte, error)
WriteFile(path string, data []byte) error
}
// Passkey is one registered passkey.
type Passkey struct {
ID string `json:"id"` // credential ID, base64url
Name string `json:"name"`
Created time.Time `json:"created"`
LastUsed time.Time `json:"last_used,omitzero"`
Cred webauthn.Credential `json:"credential"`
}
// Info is what the UI shows about a passkey.
type Info struct {
ID string `json:"id"`
Name string `json:"name"`
Created time.Time `json:"created"`
LastUsed time.Time `json:"last_used,omitzero"`
}
type account struct {
Handle []byte `json:"handle"` // random user handle (not the user name)
Passkeys []Passkey `json:"passkeys"`
}
type data struct {
Users map[string]*account `json:"users"`
}
type ceremony struct {
session webauthn.SessionData
user string // registration only
expires time.Time
}
// Service manages passkeys.
type Service struct {
Files Files
Path string // /var/lib/sharestead/passkeys.json
Now func() time.Time
mu sync.Mutex
pending map[string]ceremony
}
func (s *Service) now() time.Time {
if s.Now != nil {
return s.Now()
}
return time.Now()
}
// party returns the WebAuthn relying party for the host the UI was opened
// with (host[:port]).
func party(host string) (*webauthn.WebAuthn, error) {
name := host
if h, _, err := net.SplitHostPort(host); err == nil {
name = h
}
name = strings.Trim(name, "[]")
if net.ParseIP(name) != nil {
return nil, ErrHostIsIP
}
return webauthn.New(&webauthn.Config{RPID: name, RPDisplayName: "Sharestead", RPOrigins: []string{"https://" + host}})
}
type user struct {
name string
acc *account
}
func (u user) WebAuthnID() []byte { return u.acc.Handle }
func (u user) WebAuthnName() string { return u.name }
func (u user) WebAuthnDisplayName() string { return u.name }
func (u user) WebAuthnCredentials() []webauthn.Credential {
out := make([]webauthn.Credential, 0, len(u.acc.Passkeys))
for _, p := range u.acc.Passkeys {
out = append(out, p.Cred)
}
return out
}
func (s *Service) load() (data, error) {
d := data{Users: map[string]*account{}}
b, err := s.Files.ReadFile(s.Path)
if errors.Is(err, fs.ErrNotExist) {
return d, nil
}
if err != nil {
return d, err
}
if err := json.Unmarshal(b, &d); err != nil {
return d, fmt.Errorf("reading %s: %w", s.Path, err)
}
if d.Users == nil {
d.Users = map[string]*account{}
}
return d, nil
}
func (s *Service) save(d data) error {
b, err := json.MarshalIndent(d, "", " ")
if err != nil {
return err
}
return s.Files.WriteFile(s.Path, append(b, '\n'))
}
func token() string {
b := make([]byte, 24)
if _, err := rand.Read(b); err != nil {
panic(err)
}
return base64.RawURLEncoding.EncodeToString(b)
}
func (s *Service) remember(c ceremony) string {
t := token()
s.mu.Lock()
defer s.mu.Unlock()
if s.pending == nil {
s.pending = map[string]ceremony{}
}
now := s.now()
for k, v := range s.pending {
if now.After(v.expires) {
delete(s.pending, k)
}
}
c.expires = now.Add(5 * time.Minute)
s.pending[t] = c
return t
}
func (s *Service) take(t string) (ceremony, error) {
s.mu.Lock()
defer s.mu.Unlock()
c, ok := s.pending[t]
delete(s.pending, t)
if !ok || s.now().After(c.expires) {
return ceremony{}, ErrExpired
}
return c, nil
}
// BeginRegistration starts adding a passkey for name. It returns the options
// for navigator.credentials.create() and a token for FinishRegistration.
func (s *Service) BeginRegistration(host, name string) (*protocol.CredentialCreation, string, error) {
wa, err := party(host)
if err != nil {
return nil, "", err
}
s.mu.Lock()
d, err := s.load()
if err == nil {
if d.Users[name] == nil {
h := make([]byte, 32)
if _, err := rand.Read(h); err != nil {
panic(err)
}
d.Users[name] = &account{Handle: h}
err = s.save(d)
}
}
s.mu.Unlock()
if err != nil {
return nil, "", err
}
u := user{name, d.Users[name]}
var exclude []protocol.CredentialDescriptor
for _, c := range u.WebAuthnCredentials() {
exclude = append(exclude, c.Descriptor())
}
opts, session, err := wa.BeginRegistration(u, func(o *protocol.PublicKeyCredentialCreationOptions) error {
o.AuthenticatorSelection = protocol.AuthenticatorSelection{
ResidentKey: protocol.ResidentKeyRequirementRequired, RequireResidentKey: protocol.ResidentKeyRequired(),
UserVerification: protocol.VerificationPreferred,
}
o.CredentialExcludeList = exclude
return nil
})
if err != nil {
return nil, "", err
}
return opts, s.remember(ceremony{session: *session, user: name}), nil
}
// FinishRegistration verifies the browser's answer and stores the passkey.
func (s *Service) FinishRegistration(host, name, tok, label string, body []byte) (Info, error) {
c, err := s.take(tok)
if err != nil {
return Info{}, err
}
if c.user != name {
return Info{}, ErrExpired
}
wa, err := party(host)
if err != nil {
return Info{}, err
}
parsed, err := protocol.ParseCredentialCreationResponseBytes(body)
if err != nil {
return Info{}, fmt.Errorf("%w: %v", ErrInvalid, err)
}
s.mu.Lock()
defer s.mu.Unlock()
d, err := s.load()
if err != nil {
return Info{}, err
}
acc := d.Users[name]
if acc == nil {
return Info{}, ErrExpired
}
cred, err := wa.CreateCredential(user{name, acc}, c.session, parsed)
if err != nil {
return Info{}, fmt.Errorf("%w: %v", ErrInvalid, err)
}
label = strings.TrimSpace(label)
if label == "" || len(label) > 64 {
label = "Passkey " + s.now().Format("2006-01-02")
}
p := Passkey{ID: base64.RawURLEncoding.EncodeToString(cred.ID), Name: label, Created: s.now(), Cred: *cred}
acc.Passkeys = append(acc.Passkeys, p)
if err := s.save(d); err != nil {
return Info{}, err
}
return info(p), nil
}
func info(p Passkey) Info {
return Info{ID: p.ID, Name: p.Name, Created: p.Created, LastUsed: p.LastUsed}
}
// List returns a user's passkeys.
func (s *Service) List(name string) ([]Info, error) {
s.mu.Lock()
defer s.mu.Unlock()
d, err := s.load()
if err != nil {
return nil, err
}
out := []Info{}
if acc := d.Users[name]; acc != nil {
for _, p := range acc.Passkeys {
out = append(out, info(p))
}
}
return out, nil
}
// Remove deletes one of a user's passkeys.
func (s *Service) Remove(name, id string) error {
s.mu.Lock()
defer s.mu.Unlock()
d, err := s.load()
if err != nil {
return err
}
acc := d.Users[name]
if acc == nil {
return ErrNotFound
}
for i, p := range acc.Passkeys {
if p.ID == id {
acc.Passkeys = append(acc.Passkeys[:i], acc.Passkeys[i+1:]...)
return s.save(d)
}
}
return ErrNotFound
}
// Forget removes all passkeys of a deleted user.
func (s *Service) Forget(name string) error {
s.mu.Lock()
defer s.mu.Unlock()
d, err := s.load()
if err != nil || d.Users[name] == nil {
return err
}
delete(d.Users, name)
return s.save(d)
}
// BeginLogin starts a passkey login without a user name.
func (s *Service) BeginLogin(host string) (*protocol.CredentialAssertion, string, error) {
wa, err := party(host)
if err != nil {
return nil, "", err
}
opts, session, err := wa.BeginDiscoverableLogin(func(o *protocol.PublicKeyCredentialRequestOptions) error {
o.UserVerification = protocol.VerificationPreferred
return nil
})
if err != nil {
return nil, "", err
}
return opts, s.remember(ceremony{session: *session}), nil
}
// FinishLogin verifies the browser's answer and returns the user name.
func (s *Service) FinishLogin(host, tok string, body []byte) (string, error) {
c, err := s.take(tok)
if err != nil {
return "", err
}
wa, err := party(host)
if err != nil {
return "", err
}
parsed, err := protocol.ParseCredentialRequestResponseBytes(body)
if err != nil {
return "", fmt.Errorf("%w: %v", ErrInvalid, err)
}
s.mu.Lock()
defer s.mu.Unlock()
d, err := s.load()
if err != nil {
return "", err
}
var found string
handler := func(_, handle []byte) (webauthn.User, error) {
for n, acc := range d.Users {
if string(acc.Handle) == string(handle) {
found = n
return user{n, acc}, nil
}
}
return nil, ErrNoPasskeys
}
_, cred, err := wa.ValidatePasskeyLogin(handler, c.session, parsed)
if err != nil {
return "", fmt.Errorf("%w: %v", ErrInvalid, err)
}
acc := d.Users[found]
id := base64.RawURLEncoding.EncodeToString(cred.ID)
for i := range acc.Passkeys {
if acc.Passkeys[i].ID == id {
acc.Passkeys[i].Cred = *cred // sign counter, flags
acc.Passkeys[i].LastUsed = s.now()
}
}
if err := s.save(d); err != nil {
return "", err
}
return found, nil
}
-188
View File
@@ -1,188 +0,0 @@
package passkeys
import (
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/sha256"
"encoding/base64"
"encoding/binary"
"encoding/json"
"errors"
"io/fs"
"testing"
"time"
"github.com/fxamacker/cbor/v2"
"github.com/go-webauthn/webauthn/protocol"
)
type mem map[string][]byte
func (m mem) ReadFile(p string) ([]byte, error) {
if b, ok := m[p]; ok {
return b, nil
}
return nil, fs.ErrNotExist
}
func (m mem) WriteFile(p string, b []byte) error { m[p] = b; return nil }
// authenticator is a minimal software passkey (P-256, attestation "none").
type authenticator struct {
key *ecdsa.PrivateKey
credID []byte
handle []byte
count uint32
}
func newAuthenticator(t *testing.T) *authenticator {
k, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
t.Fatal(err)
}
id := make([]byte, 16)
_, _ = rand.Read(id)
return &authenticator{key: k, credID: id}
}
var b64 = base64.RawURLEncoding
func clientData(typ, challenge, origin string) []byte {
b, _ := json.Marshal(map[string]any{"type": typ, "challenge": challenge, "origin": origin, "crossOrigin": false})
return b
}
func (a *authenticator) authData(rpID string, attested bool) []byte {
h := sha256.Sum256([]byte(rpID))
flags := byte(0x01 | 0x04) // user present, user verified
if attested {
flags |= 0x40
}
a.count++
out := append(h[:], flags)
out = binary.BigEndian.AppendUint32(out, a.count)
if attested {
out = append(out, make([]byte, 16)...) // AAGUID
out = binary.BigEndian.AppendUint16(out, uint16(len(a.credID)))
out = append(out, a.credID...)
x, y := a.key.PublicKey.X.FillBytes(make([]byte, 32)), a.key.PublicKey.Y.FillBytes(make([]byte, 32))
cose, _ := cbor.Marshal(map[int]any{1: 2, 3: -7, -1: 1, -2: x, -3: y})
out = append(out, cose...)
}
return out
}
func handleOf(opts *protocol.CredentialCreation) []byte {
switch id := opts.Response.User.ID.(type) {
case []byte:
return id
case protocol.URLEncodedBase64:
return id
}
return nil
}
func (a *authenticator) create(t *testing.T, opts *protocol.CredentialCreation, origin string) []byte {
a.handle = handleOf(opts)
cd := clientData("webauthn.create", b64.EncodeToString(opts.Response.Challenge), origin)
att, _ := cbor.Marshal(map[string]any{"fmt": "none", "attStmt": map[string]any{}, "authData": a.authData(opts.Response.RelyingParty.ID, true)})
body, _ := json.Marshal(map[string]any{"id": b64.EncodeToString(a.credID), "rawId": b64.EncodeToString(a.credID), "type": "public-key",
"response": map[string]any{"clientDataJSON": b64.EncodeToString(cd), "attestationObject": b64.EncodeToString(att)}})
return body
}
func (a *authenticator) get(t *testing.T, opts *protocol.CredentialAssertion, rpID, origin string) []byte {
cd := clientData("webauthn.get", b64.EncodeToString(opts.Response.Challenge), origin)
ad := a.authData(rpID, false)
h := sha256.Sum256(cd)
digest := sha256.Sum256(append(append([]byte{}, ad...), h[:]...))
sig, err := ecdsa.SignASN1(rand.Reader, a.key, digest[:])
if err != nil {
t.Fatal(err)
}
body, _ := json.Marshal(map[string]any{"id": b64.EncodeToString(a.credID), "rawId": b64.EncodeToString(a.credID), "type": "public-key",
"response": map[string]any{"clientDataJSON": b64.EncodeToString(cd), "authenticatorData": b64.EncodeToString(ad), "signature": b64.EncodeToString(sig), "userHandle": b64.EncodeToString(a.handle)}})
return body
}
const host = "nas.home.arpa:8443"
const origin = "https://" + host
func TestRegisterAndLogInWithAPasskey(t *testing.T) {
s := &Service{Files: mem{}, Path: "/p.json"}
a := newAuthenticator(t)
opts, tok, err := s.BeginRegistration(host, "alex")
if err != nil {
t.Fatal(err)
}
if opts.Response.RelyingParty.ID != "nas.home.arpa" {
t.Fatalf("rp id %q", opts.Response.RelyingParty.ID)
}
if h := handleOf(opts); len(h) != 32 || string(h) == "alex" {
t.Fatal("user handle must not be the user name")
}
p, err := s.FinishRegistration(host, "alex", tok, "Laptop", a.create(t, opts, origin))
if err != nil {
t.Fatal(err)
}
if p.Name != "Laptop" {
t.Fatalf("passkey %+v", p)
}
// The token works once.
if _, err := s.FinishRegistration(host, "alex", tok, "x", a.create(t, opts, origin)); !errors.Is(err, ErrExpired) {
t.Fatalf("reused token: %v", err)
}
lopts, ltok, err := s.BeginLogin(host)
if err != nil {
t.Fatal(err)
}
who, err := s.FinishLogin(host, ltok, a.get(t, lopts, "nas.home.arpa", origin))
if err != nil || who != "alex" {
t.Fatalf("login: %q %v", who, err)
}
list, _ := s.List("alex")
if len(list) != 1 || list[0].LastUsed.IsZero() {
t.Fatalf("list %+v", list)
}
// Another site (phishing origin) is refused.
lopts, ltok, _ = s.BeginLogin(host)
if _, err := s.FinishLogin(host, ltok, a.get(t, lopts, "nas.home.arpa", "https://evil.example")); !errors.Is(err, ErrInvalid) {
t.Fatalf("wrong origin accepted: %v", err)
}
// A different authenticator (unknown key) is refused.
other := newAuthenticator(t)
other.handle = a.handle
lopts, ltok, _ = s.BeginLogin(host)
if _, err := s.FinishLogin(host, ltok, other.get(t, lopts, "nas.home.arpa", origin)); err == nil {
t.Fatal("unknown passkey accepted")
}
// Removed passkeys no longer work.
if err := s.Remove("alex", p.ID); err != nil {
t.Fatal(err)
}
lopts, ltok, _ = s.BeginLogin(host)
if _, err := s.FinishLogin(host, ltok, a.get(t, lopts, "nas.home.arpa", origin)); err == nil {
t.Fatal("removed passkey accepted")
}
}
func TestIPAddressAndExpiry(t *testing.T) {
s := &Service{Files: mem{}, Path: "/p.json"}
for _, h := range []string{"192.168.0.157:8443", "[fe80::1]:8443", "10.0.0.1"} {
if _, _, err := s.BeginRegistration(h, "alex"); !errors.Is(err, ErrHostIsIP) {
t.Errorf("%s: %v", h, err)
}
}
now := time.Now()
s.Now = func() time.Time { return now }
_, tok, err := s.BeginLogin(host)
if err != nil {
t.Fatal(err)
}
now = now.Add(6 * time.Minute)
if _, err := s.FinishLogin(host, tok, []byte("{}")); !errors.Is(err, ErrExpired) {
t.Fatalf("expired: %v", err)
}
}
+1 -1
View File
@@ -24,7 +24,7 @@ type Authenticator interface {
// Groups returns the names of the groups the user belongs to.
Groups(user string) ([]string, error)
// Usable returns ErrAccountLocked if the account is locked, disabled or
// expired. Checked for every login (also with a passkey) and again
// expired. Checked for every login and again
// while a session is used.
Usable(user string) error
}
-17
View File
@@ -122,23 +122,6 @@ func (s *Service) Login(ctx context.Context, user, password, ip string) (*Sessio
return s.session(user)
}
// LoginVerified creates a session for a user whose identity was proven
// another way (a passkey). The same rules as for Login apply.
func (s *Service) LoginVerified(user, ip string) (*Session, error) {
if wait := s.blocked([]string{"ip:" + ip}); wait > 0 {
return nil, &TooManyAttemptsError{RetryAfter: wait}
}
s.reset([]string{"ip:" + ip, "user:" + strings.ToLower(user)})
return s.session(user)
}
// Failed counts a failed login attempt from ip that wasn't a password
// (passkey); it delays further attempts like wrong passwords do.
func (s *Service) Failed(ip string) { s.fail([]string{"ip:" + ip}) }
// Blocked returns how long logins from ip are delayed.
func (s *Service) Blocked(ip string) time.Duration { return s.blocked([]string{"ip:" + ip}) }
func (s *Service) session(user string) (*Session, error) {
admin, err := s.allowed(user)
if err != nil {
-11
View File
@@ -228,14 +228,6 @@ func newSvcFake() (*Service, *clock, fakeAuthn) {
return NewService(a, Config{Now: c.now}), c, a
}
func TestPasskeyLoginOfLockedAccountIsRefused(t *testing.T) {
s, _, a := newSvcFake()
a.locked["kim"] = true
if _, err := s.LoginVerified("kim", "10.0.0.1"); !errors.Is(err, ErrAccountLocked) {
t.Fatalf("got %v", err)
}
}
func TestSessionRecheck(t *testing.T) {
s, c, a := newSvcFake()
sess, _ := s.Login(context.Background(), "kim", "pw", "10.0.0.1")
@@ -312,9 +304,6 @@ func TestLockedAccountCantLogIn(t *testing.T) {
locked: map[string]bool{"kim": true},
}
s := NewService(a, Config{})
if _, err := s.LoginVerified("kim", "10.0.0.1"); !errors.Is(err, ErrAccountLocked) {
t.Errorf("passkey login: got %v", err)
}
if _, err := s.Login(context.Background(), "kim", "pw", "10.0.0.1"); !errors.Is(err, ErrAccountLocked) {
t.Errorf("password login: got %v", err)
}
-5
View File
@@ -198,11 +198,6 @@ func (a *api) deleteUser(w http.ResponseWriter, r *http.Request) {
return
}
a.auth.LogoutUser(name, "")
if a.passkeys != nil {
if err := a.passkeys.Forget(name); err != nil {
a.log.Warn("removing passkeys of deleted user", "user", name, "error", err)
}
}
if a.quotas != nil {
if err := a.quotas.Forget(r.Context(), name); err != nil {
a.log.Warn("removing storage limit of deleted user", "user", name, "error", err)
-2
View File
@@ -22,7 +22,6 @@ import (
apphealth "sharestead/internal/app/health"
"sharestead/internal/app/homes"
"sharestead/internal/app/limitations"
"sharestead/internal/app/passkeys"
"sharestead/internal/app/quotas"
svcs "sharestead/internal/app/services"
"sharestead/internal/app/settings"
@@ -71,7 +70,6 @@ type api struct {
subfolders *subfolders.Service
homes *homes.Service
settings *settings.Store
passkeys *passkeys.Service
dlna *dlna.Service
log *slog.Logger
routes []Route
+1 -1
View File
@@ -361,7 +361,7 @@ func TestEveryChangingRouteNeedsCSRFAndSameOrigin(t *testing.T) {
}
}
}
// public changing routes (login, passkey login) refuse other sites, too
// public changing routes (login) refuse other sites, too
for _, rt := range s.Routes() {
if rt.Scope != ScopePublic || rt.Method == "GET" {
continue
-26
View File
@@ -97,29 +97,3 @@ func TestSelfServiceSwitchEndsUserSessions(t *testing.T) {
t.Fatalf("kim login while off: %d %s", rec.Code, rec.Body)
}
}
func TestPasskeysNeedAHostName(t *testing.T) {
h := newTestHandler()
// The test requests go to nas.example:8443: a host name works …
r := req("POST", "/api/v1/auth/passkey/begin", "", map[string]string{"Origin": origin})
rec := httptest.NewRecorder()
h.ServeHTTP(rec, r)
if rec.Code != 200 || !strings.Contains(rec.Body.String(), `"rpId":"nas.example"`) {
t.Fatalf("begin: %d %s", rec.Code, rec.Body)
}
// … an IP address gets an explanation.
r = req("POST", "/api/v1/auth/passkey/begin", "", map[string]string{"Origin": "https://192.168.0.157:8443"})
r.Host = "192.168.0.157:8443"
rec = httptest.NewRecorder()
h.ServeHTTP(rec, r)
if rec.Code != 409 || !strings.Contains(rec.Body.String(), "passkeys_need_hostname") {
t.Fatalf("ip: %d %s", rec.Code, rec.Body)
}
// A made-up answer is refused and counts as a failed login.
r = req("POST", "/api/v1/auth/passkey/finish", `{"token":"x","credential":{}}`, map[string]string{"Origin": origin, "Content-Type": "application/json"})
rec = httptest.NewRecorder()
h.ServeHTTP(rec, r)
if rec.Code == 200 {
t.Fatalf("forged passkey answer accepted: %s", rec.Body)
}
}
-2
View File
@@ -24,7 +24,6 @@ import (
"sharestead/internal/adapters/configstore"
"sharestead/internal/adapters/osfs"
"sharestead/internal/app/accounts"
"sharestead/internal/app/passkeys"
"sharestead/internal/app/shares"
"sharestead/internal/auth"
)
@@ -199,7 +198,6 @@ func newWorld(t *testing.T, more ...func(*Deps)) *world {
Auth: auth.NewService(fakeAuthn{}, auth.Config{}),
Accounts: &accounts.Service{Files: memFiles{"/etc/passwd": "admin:x:1000:1000::/:/usr/sbin/nologin\n", "/etc/group": "sharestead-admins:x:1006:admin\n"}, Run: w.rec, AdminGroup: "sharestead-admins"},
Store: store,
Passkeys: &passkeys.Service{Files: memSettings{}, Path: "/passkeys.json"},
Editor: &shares.Editor{Store: store, Files: osfs.FS{}, Folders: tmpFolders{w.rec}, Groups: w.rec, Paths: paths, AllowedRoots: []string{w.root}},
Shares: &shares.Service{Files: osfs.FS{}, Disk: osfs.FS{}, Paths: paths},
}
-60
View File
@@ -10,69 +10,9 @@ import (
"strings"
"testing"
"sharestead/internal/app/passkeys"
"sharestead/internal/app/settings"
"sharestead/internal/app/updates"
)
const seededPasskeys = `{"users":{"kim":{"handle":"AQID","passkeys":[{"id":"cred1","name":"Kim's phone","created":"2026-11-01T00:00:00Z","credential":{}}]}}}`
// F-AUT-6 + F-USR-1: a deleted user's passkeys go with the account, so a
// later account with the same name can't log in with them.
func TestDeletingAUserForgetsTheirPasskeys(t *testing.T) {
store := memSettings{"/passkeys.json": []byte(seededPasskeys)}
w := newWorld(t, func(d *Deps) {
d.Accounts.Files = memFiles{"/etc/passwd": passwdFile, "/etc/group": groupFile}
d.Passkeys = &passkeys.Service{Files: store, Path: "/passkeys.json"}
})
if r := w.call("DELETE", "/api/v1/users/kim", nil); r.Code != 204 {
t.Fatalf("delete: %d %s", r.Code, r.Body)
}
if strings.Contains(string(store["/passkeys.json"]), "cred1") {
t.Errorf("kim's passkey is still stored: %s", store["/passkeys.json"])
}
}
// F-AUT-7 / F-AUT-6: a user sees their own passkeys, removing one needs a
// known id.
func TestMyPasskeys(t *testing.T) {
st := &settings.Store{Files: memSettings{}, Path: "/settings.json"}
on := true
st.Update(func(s *settings.Settings) { s.SelfService = &on })
store := memSettings{"/passkeys.json": []byte(seededPasskeys)}
w := newWorld(t, func(d *Deps) {
d.Settings = st
d.Passkeys = &passkeys.Service{Files: store, Path: "/passkeys.json"}
d.Auth = selfServiceAuth(st)
})
_, cookie, csrf := login(t, w.h, "kim", "pw")
r := w.callAs(cookie, csrf, "GET", "/api/v1/me/passkeys", nil)
if r.Code != 200 || !strings.Contains(r.Body, "Kim's phone") {
t.Fatalf("list: %d %s", r.Code, r.Body)
}
if r := w.call("GET", "/api/v1/me/passkeys", nil); strings.Contains(r.Body, "Kim's phone") {
t.Error("admin sees kim's passkeys under /me")
}
if r := w.callAs(cookie, csrf, "DELETE", "/api/v1/me/passkeys/nope", nil); r.Code != 404 {
t.Errorf("remove unknown: %d %s", r.Code, r.Body)
}
if r := w.call("DELETE", "/api/v1/me/passkeys/cred1", nil); r.Code != 404 {
t.Errorf("admin removed kim's passkey via /me: %d %s", r.Code, r.Body)
}
}
// 07 §2.1 + F-AUT-6: passkey login has the same backoff as passwords.
func TestPasskeyLoginIsBlockedDuringBackoff(t *testing.T) {
w := newWorld(t)
for i := 0; i < 5; i++ {
login(t, w.h, "admin", "wrong")
}
r := w.callAs(nil, "", "POST", "/api/v1/auth/passkey/finish", map[string]any{"token": "x", "credential": map[string]any{}})
if r.Code != 429 || r.Hdr.Get("Retry-After") == "" {
t.Errorf("passkey login during backoff: %d %s", r.Code, r.Body)
}
}
// F-AUT-4: Retry-After and retry_after_seconds agree and are at least 1.
func TestBackoffTellsHowLongToWait(t *testing.T) {
w := newWorld(t)
+2 -9
View File
@@ -12,7 +12,6 @@ import (
"sharestead/internal/app/dlna"
"sharestead/internal/app/folders"
apphealth "sharestead/internal/app/health"
"sharestead/internal/app/passkeys"
"sharestead/internal/app/quotas"
"sharestead/internal/app/subfolders"
"sharestead/internal/app/updates"
@@ -101,16 +100,10 @@ var apiDocs = map[string]opDoc{
"GET /api/v1/problems": {Tag: "Problems", Summary: "Current problems", Description: "Each says what is wrong, what is affected, the cause and what to do.", Response: problemsList{}},
"POST /api/v1/problems/fix": {Tag: "Problems", Summary: "Apply a one-click fix", Request: fixProblemRequest{}, Errors: map[int]string{404: "The service of this fix doesn’t exist"}},
"GET /api/v1/folders/capabilities": {Tag: "Folders", Summary: "Storage folders and what they support", Description: "Per storage folder (mounts below /srv, /mnt, /media, /data, and those folders): filesystem and whether POSIX ACLs work, found by trying it on a temporary folder. Without ACLs Sharestead works with access per share; subfolder permissions need ACLs. The result is kept for 10 minutes.", Response: capabilities.Report{}, Query: []queryParam{{Name: "fresh", Description: "1: check again now instead of the kept result", Schema: map[string]any{"type": "string", "enum": []string{"1"}}}}},
"GET /api/v1/diagnostics": {Tag: "Problems", Summary: "Diagnostic bundle (ZIP)", Description: "For troubleshooting and bug reports: system and package versions, config files, testparm, service states, the last 300 log lines, current problems and the storage check. Passwords, password hashes, passkeys, the TLS key, sessions and API keys are not included; setting values named like password/secret/token are replaced. Still contains user, share and host names and IP addresses.", Response: []byte{}, MediaType: "application/zip"},
"GET /api/v1/diagnostics": {Tag: "Problems", Summary: "Diagnostic bundle (ZIP)", Description: "For troubleshooting and bug reports: system and package versions, config files, testparm, service states, the last 300 log lines, current problems and the storage check. Passwords, password hashes, the TLS key, sessions and API keys are not included; setting values named like password/secret/token are replaced. Still contains user, share and host names and IP addresses.", Response: []byte{}, MediaType: "application/zip"},
"PUT /api/v1/shares/{name}/limit": {Tag: "Storage", Summary: "Set a share's soft limit", Description: "0 removes it. For shares reachable over SMB, where no hard limit is possible. Sharestead measures the folder every few minutes; over the limit the share is read-only over SMB for everyone, and clients see the space left in the limit. Writes on the server itself or over NFS aren't stopped.", Request: setShareLimitRequest{}},
"PUT /api/v1/limitations/acknowledged": {Tag: "Problems", Summary: "Acknowledge a limitation, or show it again", Description: "Limitations are the problems with severity info: Sharestead works, one feature isn't available here. An acknowledged one stays listed (acknowledged: true) and comes back when its facts change.", Request: acknowledgeRequest{}, Errors: map[int]string{404: "The ID isn’t a current limitation (it may have been resolved)"}},
"GET /api/v1/updates": {Tag: "Updates", Summary: "Pending system updates", Description: "From a simulated upgrade; nothing is installed.", Response: updates.Status{}, Query: []queryParam{{Name: "fresh", Description: "1: check again now instead of the cached result", Schema: map[string]any{"type": "string", "enum": []string{"1"}}}}},
"GET /api/v1/me/passkeys": {Tag: "Self-service", Summary: "My passkeys", Response: passkeyList{}},
"POST /api/v1/me/passkeys/begin": {Tag: "Self-service", Summary: "Start adding a passkey", Description: "Returns WebAuthn options for navigator.credentials.create(). Needs a recent password and a host name (not an IP address).", Response: passkeyCreation{}, Confirm: true},
"POST /api/v1/me/passkeys/finish": {Tag: "Self-service", Summary: "Finish adding a passkey", Description: "Send the browser's PublicKeyCredential with the token.", Request: finishPasskeyRequest{}, Response: passkeys.Info{}},
"DELETE /api/v1/me/passkeys/{id}": {Tag: "Self-service", Summary: "Remove a passkey", Confirm: true},
"POST /api/v1/auth/passkey/begin": {Tag: "Auth", Summary: "Start a passkey login", Description: "No user name needed (discoverable credential). Returns options for navigator.credentials.get().", Response: passkeyAssertion{}},
"POST /api/v1/auth/passkey/finish": {Tag: "Auth", Summary: "Finish a passkey login", Description: "Verifies the passkey and sets the session cookie. Same rules as the password login.", Request: finishPasskeyRequest{}, Response: sessionInfo{}},
"GET /api/v1/dlna": {Tag: "Services", Summary: "TV & media players (DLNA)", Description: "Name shown on TVs, media folders, and whether the media server may read them.", Response: dlna.Status{}},
"PUT /api/v1/dlna": {Tag: "Services", Summary: "Change DLNA folders and name", Description: "Applying restarts the media server: playback on TVs stops for a moment. Folder type: empty = all media, A = audio, V = video, P = pictures, or a combination such as PV.", Request: setDLNARequest{}, Response: editResponse{}, Edit: true},
"POST /api/v1/dlna/rescan": {Tag: "Services", Summary: "Scan the media folders again", Description: "Rebuilds the media list from scratch; TVs see new files when it's done.", Status: http.StatusAccepted},
@@ -276,7 +269,7 @@ func openAPI(routes []Route) map[string]any {
if d.Edit {
problem(409, "The configuration changed in the meantime, or the change conflicts with later ones")
}
if rt.Pattern == "/api/v1/auth/login" || rt.Pattern == "/api/v1/auth/confirm" || rt.Pattern == "/api/v1/me/password" || rt.Pattern == "/api/v1/auth/passkey/finish" {
if rt.Pattern == "/api/v1/auth/login" || rt.Pattern == "/api/v1/auth/confirm" || rt.Pattern == "/api/v1/me/password" {
problem(429, "Too many wrong passwords; wait (Retry-After)")
problem(401, "Wrong user name or password")
}
-171
View File
@@ -1,171 +0,0 @@
package server
import (
"encoding/json"
"errors"
"fmt"
"net/http"
"strconv"
"github.com/go-webauthn/webauthn/protocol"
"sharestead/internal/app/passkeys"
"sharestead/internal/auth"
)
func (a *api) registerPasskeys() {
a.handle("GET", "/api/v1/me/passkeys", ScopeSession, a.listPasskeys)
a.handle("POST", "/api/v1/me/passkeys/begin", ScopeSession, a.beginPasskey)
a.handle("POST", "/api/v1/me/passkeys/finish", ScopeSession, a.finishPasskey)
a.handle("DELETE", "/api/v1/me/passkeys/{id}", ScopeSession, a.removePasskey)
a.handle("POST", "/api/v1/auth/passkey/begin", ScopePublic, a.beginPasskeyLogin)
a.handle("POST", "/api/v1/auth/passkey/finish", ScopePublic, a.finishPasskeyLogin)
}
// passkeyList is the answer to listPasskeys.
type passkeyList struct {
Passkeys []passkeys.Info `json:"passkeys"`
}
// passkeyCreation starts adding a passkey: options for navigator.credentials.create().
type passkeyCreation struct {
Options *protocol.CredentialCreation `json:"options"`
Token string `json:"token"` // send back with the answer
}
// passkeyAssertion starts a passkey login: options for navigator.credentials.get().
type passkeyAssertion struct {
Options *protocol.CredentialAssertion `json:"options"`
Token string `json:"token"`
}
// finishPasskeyRequest carries the browser's answer.
type finishPasskeyRequest struct {
Token string `json:"token"`
Name string `json:"name,omitempty"` // label, e.g. "Laptop" (registration only)
Credential json.RawMessage `json:"credential"` // PublicKeyCredential as JSON (WebAuthn)
}
func passkeyProblem(w http.ResponseWriter, err error) {
switch {
case errors.Is(err, passkeys.ErrHostIsIP):
problem(w, http.StatusConflict, "passkeys_need_hostname", "Passkeys need a host name",
"Open Sharestead with its host name (for example https://nas.home.arpa:8443), not with an IP address: a passkey is bound to a name. A trusted certificate is needed too.", nil)
case errors.Is(err, passkeys.ErrExpired):
problem(w, http.StatusBadRequest, "passkey_expired", "The passkey request expired", "Start again.", nil)
case errors.Is(err, passkeys.ErrNotFound):
problem(w, http.StatusNotFound, "not_found", "Passkey not found", "It may have been removed already; reload the page.", nil)
case errors.Is(err, passkeys.ErrInvalid):
problem(w, http.StatusBadRequest, "passkey_invalid", "The passkey couldn’t be verified", err.Error()+" — nothing was changed.", nil)
default:
problem(w, http.StatusInternalServerError, "passkey_failed", "Passkeys couldn’t be used", err.Error(), nil)
}
}
func (a *api) listPasskeys(w http.ResponseWriter, r *http.Request) {
if a.selfServiceOff(w, r) {
return
}
list, err := a.passkeys.List(sessionFrom(r).User)
if err != nil {
passkeyProblem(w, err)
return
}
writeJSON(w, http.StatusOK, passkeyList{Passkeys: list})
}
func (a *api) beginPasskey(w http.ResponseWriter, r *http.Request) {
if a.selfServiceOff(w, r) || a.needsConfirm(w, r, "Adding a passkey") {
return
}
opts, tok, err := a.passkeys.BeginRegistration(r.Host, sessionFrom(r).User)
if err != nil {
passkeyProblem(w, err)
return
}
writeJSON(w, http.StatusOK, passkeyCreation{Options: opts, Token: tok})
}
func (a *api) finishPasskey(w http.ResponseWriter, r *http.Request) {
var in finishPasskeyRequest
if !decode(w, r, &in) || a.selfServiceOff(w, r) {
return
}
info, err := a.passkeys.FinishRegistration(r.Host, sessionFrom(r).User, in.Token, in.Name, in.Credential)
a.audit(r, "add passkey", sessionFrom(r).User, err)
a.record(r, "User "+sessionFrom(r).User+" added a passkey ("+info.Name+")", err)
if err != nil {
passkeyProblem(w, err)
return
}
writeJSON(w, http.StatusOK, info)
}
func (a *api) removePasskey(w http.ResponseWriter, r *http.Request) {
if a.selfServiceOff(w, r) || a.needsConfirm(w, r, "Removing a passkey") {
return
}
err := a.passkeys.Remove(sessionFrom(r).User, r.PathValue("id"))
a.audit(r, "remove passkey", sessionFrom(r).User, err)
a.record(r, "User "+sessionFrom(r).User+" removed a passkey", err)
if err != nil {
passkeyProblem(w, err)
return
}
w.WriteHeader(http.StatusNoContent)
}
func (a *api) beginPasskeyLogin(w http.ResponseWriter, r *http.Request) {
opts, tok, err := a.passkeys.BeginLogin(r.Host)
if err != nil {
passkeyProblem(w, err)
return
}
writeJSON(w, http.StatusOK, passkeyAssertion{Options: opts, Token: tok})
}
func (a *api) finishPasskeyLogin(w http.ResponseWriter, r *http.Request) {
var in finishPasskeyRequest
if !decode(w, r, &in) {
return
}
ip := clientIP(r)
if wait := a.auth.Blocked(ip); wait > 0 {
w.Header().Set("Retry-After", strconv.Itoa(int(wait.Seconds())+1))
problem(w, http.StatusTooManyRequests, "too_many_attempts", "Too many failed logins", fmt.Sprintf("Wait %s, then try again.", wait.Round(1e9)), nil)
return
}
user, err := a.passkeys.FinishLogin(r.Host, in.Token, in.Credential)
if err != nil {
a.auth.Failed(ip)
a.log.Warn("audit", "action", "passkey login", "result", "failed", "ip", ip, "error", err.Error())
if errors.Is(err, passkeys.ErrHostIsIP) || errors.Is(err, passkeys.ErrExpired) {
passkeyProblem(w, err)
return
}
problem(w, http.StatusUnauthorized, "bad_credentials", "This passkey isn’t accepted", "It may have been removed, or belong to another system. Log in with your password.", nil)
return
}
sess, err := a.auth.LoginVerified(user, ip)
var tm *auth.TooManyAttemptsError
switch {
case errors.As(err, &tm):
problem(w, http.StatusTooManyRequests, "too_many_attempts", "Too many failed logins", fmt.Sprintf("Wait %s, then try again.", tm.RetryAfter.Round(1e9)), nil)
return
case errors.Is(err, auth.ErrSelfServiceOff):
problem(w, http.StatusForbidden, "self_service_off", "Self-service is switched off", "Your administrator manages accounts on this NAS.", nil)
return
case errors.Is(err, auth.ErrAccountLocked):
problem(w, http.StatusForbidden, "account_disabled", "This account is disabled", "It is locked or expired on this system. Ask your administrator.", nil)
return
case errors.Is(err, auth.ErrNotAdmin):
problem(w, http.StatusForbidden, "not_admin", "This account may not use Sharestead", "Ask your administrator.", nil)
return
case err != nil:
problem(w, http.StatusInternalServerError, "login_failed", "Login failed", err.Error(), nil)
return
}
a.log.Info("audit", "actor", user, "action", "passkey login", "result", "ok", "ip", ip)
http.SetCookie(w, &http.Cookie{Name: sessionCookie, Value: sess.ID, Path: "/", HttpOnly: true, Secure: true, SameSite: http.SameSiteStrictMode})
writeJSON(w, http.StatusOK, sessionInfo{User: sess.User, Admin: sess.Admin, CSRF: sess.CSRF})
}
+1 -4
View File
@@ -22,7 +22,6 @@ import (
apphealth "sharestead/internal/app/health"
"sharestead/internal/app/homes"
"sharestead/internal/app/limitations"
"sharestead/internal/app/passkeys"
"sharestead/internal/app/quotas"
svcs "sharestead/internal/app/services"
"sharestead/internal/app/settings"
@@ -55,7 +54,6 @@ type Deps struct {
Updates *updates.Service
Homes *homes.Service
Settings *settings.Store
Passkeys *passkeys.Service
DLNA *dlna.Service
// Capabilities checks what the storage folders support (ACLs).
Capabilities *capabilities.Service
@@ -70,7 +68,7 @@ type Deps struct {
// New creates a server listening on addr with the given certificate.
func New(addr string, cert tls.Certificate, d Deps, log *slog.Logger) *Server {
mux := http.NewServeMux()
a := &api{mux: mux, auth: d.Auth, shares: d.Shares, accounts: d.Accounts, editor: d.Editor, store: d.Store, folders: d.Folders, services: d.Services, health: d.Health, quotas: d.Quotas, updates: d.Updates, homes: d.Homes, settings: d.Settings, passkeys: d.Passkeys, dlna: d.DLNA, capabilities: d.Capabilities, diagnostics: d.Diagnostics, limitations: d.Limitations, subfolders: d.Subfolders, log: log}
a := &api{mux: mux, auth: d.Auth, shares: d.Shares, accounts: d.Accounts, editor: d.Editor, store: d.Store, folders: d.Folders, services: d.Services, health: d.Health, quotas: d.Quotas, updates: d.Updates, homes: d.Homes, settings: d.Settings, dlna: d.DLNA, capabilities: d.Capabilities, diagnostics: d.Diagnostics, limitations: d.Limitations, subfolders: d.Subfolders, log: log}
a.handle("POST", "/api/v1/auth/login", ScopePublic, a.login)
a.handle("POST", "/api/v1/auth/logout", ScopeSession, a.logout)
a.handle("GET", "/api/v1/auth/session", ScopeSession, a.currentSession)
@@ -91,7 +89,6 @@ func New(addr string, cert tls.Certificate, d Deps, log *slog.Logger) *Server {
a.registerHomes()
a.registerMe()
a.registerSettings()
a.registerPasskeys()
a.registerDLNA()
a.registerOpenAPI()
mux.HandleFunc("/api/", func(w http.ResponseWriter, r *http.Request) {
-2
View File
@@ -15,7 +15,6 @@ import (
"sharestead/internal/app/accounts"
"sharestead/internal/app/changes"
"sharestead/internal/app/passkeys"
"sharestead/internal/app/shares"
"sharestead/internal/auth"
)
@@ -50,7 +49,6 @@ func newTestServerAuth(cfg auth.Config, more ...func(*Deps)) *Server {
Auth: auth.NewService(fakeAuthn{}, cfg),
Accounts: &accounts.Service{Files: memFiles{"/etc/passwd": "admin:x:1000:1000::/:/usr/sbin/nologin\n", "/etc/group": "sharestead-admins:x:1006:admin\n"}, Run: noopRunner{}, AdminGroup: "sharestead-admins"},
Store: emptyStore{},
Passkeys: &passkeys.Service{Files: memSettings{}, Path: "/passkeys.json"},
Editor: &shares.Editor{},
Shares: &shares.Service{Files: memFiles{"/etc/samba/smb.conf": "[Family]\npath = /srv/family\nvalid users = @family\n"}, Disk: memDisk{}, Paths: shares.DefaultPaths},
}
-34
View File
@@ -891,37 +891,3 @@ test('API page: OpenAPI 3.1 description, grouped, with “Try it” for GET', as
expect(errors).toEqual([]);
});
test('passkeys: add one, log in with it, remove it (virtual authenticator)', async ({ page }, info) => {
test.skip(info.project.name !== 'chromium', 'Chromium-only: virtual authenticator via DevTools protocol');
const errors = watchConsole(page, true);
// Passkeys need a host name, so this test uses localhost instead of 127.0.0.1.
const base = (process.env.SST_URL ?? 'https://127.0.0.1:8443').replace('127.0.0.1', 'localhost');
const cdp = await page.context().newCDPSession(page);
await cdp.send('WebAuthn.enable');
await cdp.send('WebAuthn.addVirtualAuthenticator', { options: { protocol: 'ctap2', transport: 'internal', hasResidentKey: true, hasUserVerification: true, isUserVerified: true, automaticPresenceSimulation: true } });
await page.goto(base + '/');
await page.getByLabel('User name').fill(user);
await page.getByLabel('Password').fill(pass);
await page.getByRole('button', { name: 'Log in', exact: true }).click();
await expect(page.getByRole('heading', { name: 'Dashboard' })).toBeVisible();
await page.goto(base + '/#/me');
const card = page.locator('.card').filter({ has: page.getByRole('heading', { name: 'Passkeys' }) });
await card.getByLabel('Passkey name').fill('CI key');
await card.getByRole('button', { name: 'Add passkey' }).click();
await expect(page.getByRole('status')).toContainText('Passkey “CI key” added.');
await expect(card).toContainText('CI key');
await page.screenshot({ path: `e2e-results/screens/${info.project.name}-passkeys.png`, fullPage: true, caret: 'initial', animations: 'disabled' });
await page.getByRole('button', { name: 'Log out' }).click();
await page.getByRole('button', { name: 'Log in with a passkey' }).click();
// Logged in again; the app stays on the page it was on (#/me).
await expect(page.getByRole('navigation', { name: 'Main' })).toBeVisible();
await expect(page.getByRole('heading', { name: 'My account' })).toBeVisible();
await page.goto(base + '/#/me');
await expect(card).toContainText('last used');
await card.getByRole('button', { name: 'Remove' }).click();
await expect(page.getByRole('status')).toContainText('Passkey “CI key” removed.');
expect(errors).toEqual([]);
});
+1 -7
View File
@@ -1,4 +1,4 @@
import type { DLNAStatus, MediaDir, PasskeyInfo, Me, HomesStatus, UpdateStatus, FolderCapabilities, StorageReport, HealthProblem, Client, ServiceStatus, FolderEntry, FolderListing, FolderStats, AccessSpec, Accounts, ChangeFilter, ChangesPage, EditResponse, RestoreResponse, NFSClient, Problem, SambaSettings, SessionInfo, Share, ShareOptions, SubfolderEntry, SubfolderInfo, SubfolderResponse } from './types';
import type { DLNAStatus, MediaDir, Me, HomesStatus, UpdateStatus, FolderCapabilities, StorageReport, HealthProblem, Client, ServiceStatus, FolderEntry, FolderListing, FolderStats, AccessSpec, Accounts, ChangeFilter, ChangesPage, EditResponse, RestoreResponse, NFSClient, Problem, SambaSettings, SessionInfo, Share, ShareOptions, SubfolderEntry, SubfolderInfo, SubfolderResponse } from './types';
/** An API call that failed. Carries the server's problem details. */
export class ApiError extends Error {
@@ -150,12 +150,6 @@ export const api = {
rescanDLNA: () => request<void>('POST', '/api/v1/dlna/rescan'),
allowDLNA: (path: string) => request<{ group: string }>('POST', '/api/v1/dlna/allow', { path }),
me: () => request<Me>('GET', '/api/v1/me'),
passkeys: () => request<{ passkeys: PasskeyInfo[] }>('GET', '/api/v1/me/passkeys').then((r) => r.passkeys),
beginPasskey: () => request<{ options: never; token: string }>('POST', '/api/v1/me/passkeys/begin'),
finishPasskey: (token: string, name: string, credential: unknown) => request<PasskeyInfo>('POST', '/api/v1/me/passkeys/finish', { token, name, credential }),
removePasskey: (id: string) => request<void>('DELETE', '/api/v1/me/passkeys/' + encodeURIComponent(id)),
beginPasskeyLogin: () => request<{ options: never; token: string }>('POST', '/api/v1/auth/passkey/begin'),
finishPasskeyLogin: (token: string, credential: unknown) => request<SessionInfo>('POST', '/api/v1/auth/passkey/finish', { token, credential }),
setMyPassword: (current: string, next: string) => request<void>('PUT', '/api/v1/me/password', { current, new: next }),
appSettings: () => request<{ self_service: boolean; home_by_default: boolean }>('GET', '/api/v1/settings/app'),
setAppSettings: (s: { self_service?: boolean; home_by_default?: boolean }) => request<{ self_service: boolean; home_by_default: boolean; sessions_ended: number }>('PUT', '/api/v1/settings/app', s),
-1
View File
@@ -68,7 +68,6 @@ export interface HomeUsage { path: string; used: number; limit: number; source?:
export interface MyShare { share: string; comment?: string; level: Level; reason: string; home?: boolean; hidden?: boolean; unsure?: boolean }
export interface Me { user: string; full_name: string; uid: number; groups: string[]; admin: boolean; samba: boolean; shares: MyShare[]; storage?: UserUsage; scanned_at?: string; warn_percent?: number }
export interface PasskeyInfo { id: string; name: string; created: string; last_used?: string }
export interface MediaDir { path: string; type?: string }
export interface DLNAFolder extends MediaDir { readable: boolean; group?: string; problem?: string }
-11
View File
@@ -1,11 +0,0 @@
import { describe, expect, it } from 'vitest';
import { b64u } from './webauthn';
describe('base64url', () => {
it('round-trips binary data without padding', () => {
const bytes = new Uint8Array([0, 255, 62, 63, 250, 1]);
const s = b64u.encode(bytes.buffer);
expect(s).not.toMatch(/[+/=]/);
expect(Array.from(new Uint8Array(b64u.decode(s)))).toEqual(Array.from(bytes));
});
});
-71
View File
@@ -1,71 +0,0 @@
// WebAuthn (passkeys) in the browser: convert the server's JSON options
// (base64url) to what navigator.credentials expects, and the result back.
const b64u = {
decode(s: string): ArrayBuffer {
const pad = '='.repeat((4 - (s.length % 4)) % 4);
const bin = atob((s + pad).replace(/-/g, '+').replace(/_/g, '/'));
const out = new Uint8Array(bin.length);
for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);
return out.buffer;
},
encode(b: ArrayBuffer | null): string {
if (!b) return '';
let s = '';
for (const x of new Uint8Array(b)) s += String.fromCharCode(x);
return btoa(s).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
},
};
export { b64u };
/** Why passkeys can't be used here, or '' when they can. */
export function passkeyUnavailable(): string {
if (typeof window === 'undefined' || !window.PublicKeyCredential) return 'This browser doesn’t support passkeys.';
if (/^\d+\.\d+\.\d+\.\d+$/.test(location.hostname) || location.hostname.includes(':')) return 'Passkeys need a host name: open Sharestead by its name (for example https://nas.home.arpa:8443), not by its IP address.';
if (!window.isSecureContext) return 'Passkeys need a secure (HTTPS) page with a trusted certificate.';
return '';
}
type Desc = { id: string; type: string; transports?: string[] };
type CreationJSON = { publicKey: { challenge: string; user: { id: string; name: string; displayName: string }; excludeCredentials?: Desc[]; [k: string]: unknown } };
type RequestJSON = { publicKey: { challenge: string; allowCredentials?: Desc[]; [k: string]: unknown } };
function descs(list: Desc[] | undefined): PublicKeyCredentialDescriptor[] | undefined {
return list?.map((d) => ({ ...d, id: b64u.decode(d.id) }) as PublicKeyCredentialDescriptor);
}
export async function createPasskey(options: CreationJSON): Promise<unknown> {
const pk = options.publicKey;
const cred = (await navigator.credentials.create({
publicKey: { ...pk, challenge: b64u.decode(pk.challenge), user: { ...pk.user, id: b64u.decode(pk.user.id) }, excludeCredentials: descs(pk.excludeCredentials) } as PublicKeyCredentialCreationOptions,
})) as PublicKeyCredential | null;
if (!cred) throw new Error('No passkey was created.');
const r = cred.response as AuthenticatorAttestationResponse;
return {
id: cred.id, rawId: b64u.encode(cred.rawId), type: cred.type,
response: { clientDataJSON: b64u.encode(r.clientDataJSON), attestationObject: b64u.encode(r.attestationObject), transports: r.getTransports?.() ?? [] },
clientExtensionResults: cred.getClientExtensionResults(), authenticatorAttachment: cred.authenticatorAttachment,
};
}
export async function getPasskey(options: RequestJSON): Promise<unknown> {
const pk = options.publicKey;
const cred = (await navigator.credentials.get({
publicKey: { ...pk, challenge: b64u.decode(pk.challenge), allowCredentials: descs(pk.allowCredentials) } as PublicKeyCredentialRequestOptions,
})) as PublicKeyCredential | null;
if (!cred) throw new Error('No passkey was chosen.');
const r = cred.response as AuthenticatorAssertionResponse;
return {
id: cred.id, rawId: b64u.encode(cred.rawId), type: cred.type,
response: { clientDataJSON: b64u.encode(r.clientDataJSON), authenticatorData: b64u.encode(r.authenticatorData), signature: b64u.encode(r.signature), userHandle: b64u.encode(r.userHandle) },
clientExtensionResults: cred.getClientExtensionResults(),
};
}
/** Plain words for the errors navigator.credentials throws. */
export function passkeyError(e: unknown): string {
const name = e instanceof DOMException ? e.name : '';
if (name === 'NotAllowedError') return 'Cancelled or timed out — nothing was changed.';
if (name === 'InvalidStateError') return 'This device already has a passkey for your account.';
if (name === 'SecurityError') return 'The browser refused: passkeys need the host name and a trusted HTTPS certificate.';
return e instanceof Error ? e.message : String(e);
}
-19
View File
@@ -3,7 +3,6 @@
import { api, ApiError, setCsrf } from '../lib/api';
import type { Problem, SessionInfo } from '../lib/types';
import Notice from '../components/Notice.svelte';
import { getPasskey, passkeyError, passkeyUnavailable } from '../lib/webauthn';
let { onlogin }: { onlogin: (s: SessionInfo) => void } = $props();
let username = $state('');
@@ -14,20 +13,6 @@
let busy = $state(false);
let problem = $state<Problem | null>(null);
const noPasskeys = passkeyUnavailable();
async function withPasskey() {
busy = true; problem = null;
try {
const begin = await api.beginPasskeyLogin();
const cred = await getPasskey(begin.options);
const s = await api.finishPasskeyLogin(begin.token, cred);
setCsrf(s.csrf);
onlogin(s);
} catch (err) {
problem = err instanceof ApiError ? err.problem : { status: 0, code: 'passkey', title: 'Passkey login didn’t work', detail: passkeyError(err) };
} finally { busy = false; }
}
async function submit(e: SubmitEvent) {
e.preventDefault();
busy = true;
@@ -54,15 +39,11 @@
<input class="t" id="p" type="password" autocomplete="current-password" required bind:value={password} />
{#if problem}<div class="err"><Notice {problem} /></div>{/if}
<button class="btn primary full" type="submit" disabled={busy}>{busy ? 'Logging in…' : 'Log in'}</button>
{#if !noPasskeys}
<button class="btn full passkey" type="button" onclick={withPasskey} disabled={busy}>Log in with a passkey</button>
{/if}
<p class="muted small">Your user name and password for this NAS — the same as for the shares.</p>
</form>
</div>
<style>
.passkey { margin-top: 10px; justify-content: center; }
.center { min-height: 100vh; display: grid; place-items: center; padding: 16px; }
.login { width: min(380px, 100%); padding: 28px 32px; }
.brand { margin-bottom: 6px; }
+1 -52
View File
@@ -2,7 +2,7 @@
// Self-service: the logged-in user's own account — password, storage,
// shares and how to connect. Shows nothing about other users.
import { onMount } from 'svelte';
import { api, ApiError } from '../lib/api';
import { api } from '../lib/api';
import type { Me, Problem } from '../lib/types';
import { toProblem } from '../lib/errors';
import { bytes, levelLabel } from '../lib/format';
@@ -14,8 +14,6 @@
import UsageBar from '../components/UsageBar.svelte';
import HelpIcon from '../components/HelpIcon.svelte';
import ConnectHelp from '../components/ConnectHelp.svelte';
import type { PasskeyInfo } from '../lib/types';
import { createPasskey, passkeyError, passkeyUnavailable } from '../lib/webauthn';
let me = $state<Me | null>(null);
let problem = $state<Problem | null>(null);
@@ -30,31 +28,6 @@
}
onMount(load);
// Passkeys
const noPasskeys = passkeyUnavailable();
let keys = $state<PasskeyInfo[]>([]);
let keyName = $state('');
const loadKeys = () => api.passkeys().then((k) => (keys = k)).catch((err) => (problem = toProblem(err)));
onMount(() => { if (!noPasskeys) loadKeys(); });
async function addKey(e: SubmitEvent) {
e.preventDefault();
busy = true; problem = null; ok = '';
try {
const begin = await api.beginPasskey();
const cred = await createPasskey(begin.options);
const k = await api.finishPasskey(begin.token, keyName, cred);
ok = `Passkey “${k.name}” added. Next time choose “Log in with a passkey”.`;
keyName = '';
await loadKeys();
} catch (err) {
problem = err instanceof ApiError ? err.problem : { status: 0, code: 'passkey', title: 'The passkey wasn’t added', detail: passkeyError(err) };
} finally { busy = false; }
}
async function removeKey(k: PasskeyInfo) {
busy = true; problem = null; ok = '';
try { await api.removePasskey(k.id); ok = `Passkey “${k.name}” removed.`; await loadKeys(); } catch (err) { problem = toProblem(err); } finally { busy = false; }
}
async function changePassword(e: SubmitEvent) {
e.preventDefault();
busy = true; problem = null; ok = '';
@@ -135,27 +108,6 @@
<div class="row end"><button class="btn primary" type="submit" disabled={busy || !current || next.length < 8}>{busy ? 'Saving…' : 'Change password'}</button></div>
</form>
<div class="card">
<h2>Passkeys</h2>
{#if noPasskeys}
<p class="muted small">{noPasskeys}</p>
{:else}
<p class="muted small desc">Log in with your fingerprint, face or device PIN instead of the password. The password keeps working.</p>
{#if keys.length}
<table><tbody>
{#each keys as k (k.id)}
<tr><td><b>{k.name}</b><div class="facts">added {new Date(k.created).toLocaleDateString()}{k.last_used ? ' · last used ' + ago(k.last_used) : ' · not used yet'}</div></td>
<td class="right"><button class="btn sm danger" onclick={() => removeKey(k)} disabled={busy}>Remove</button></td></tr>
{/each}
</tbody></table>
{/if}
<form class="row wrap addkey" onsubmit={addKey}>
<input class="t keyname" bind:value={keyName} placeholder="Name, e.g. Laptop" aria-label="Passkey name" maxlength="64" />
<button class="btn" type="submit" disabled={busy}>Add passkey</button>
</form>
{/if}
</div>
<div class="card">
<h2>Account</h2>
<table class="kv"><tbody>
@@ -175,7 +127,4 @@
.inline { width: auto; display: inline-block; margin-left: 6px; }
.end { justify-content: flex-end; margin-top: 16px; }
.kv td { padding: 6px 8px 6px 0; }
.right { text-align: right; }
.addkey { margin-top: 10px; }
.keyname { flex: 1 1 180px; width: auto; }
</style>